void CProcesses::OnLvnGetdispinfoProcessList(NMHDR *pNMHDR, LRESULT *pResult) { NMLVDISPINFO *pDispInfo = reinterpret_cast<NMLVDISPINFO*>(pNMHDR); LVCOLUMN col; col.mask = LVCF_SUBITEM; /*Get the colum Info*/ ListView_GetColumn(hProcPageListCtrl,pDispInfo->item.iSubItem,&col); if(columns[col.iSubItem].isShow) { PERFDATA *pPerfData = (PERFDATA *)pDispInfo->item.lParam; /*Set the Column Data*/ switch(columns[col.iSubItem].nId) { case COLUMN_IMAGENAME: break; case COLUMN_PID: swprintf_s(pDispInfo->item.pszText,pDispInfo->item.cchTextMax,_T("%d"),pPerfData->ProcessId); break; case COLUMN_USERNAME: pDispInfo->item.pszText = pPerfData->UserName; break; case COLUMN_SESSIONID: swprintf_s(pDispInfo->item.pszText,pDispInfo->item.cchTextMax,_T("%d"),pPerfData->SessionId); break; case COLUMN_CPUUSAGE: swprintf_s(pDispInfo->item.pszText,pDispInfo->item.cchTextMax,_T("%02d"),pPerfData->CPUUsage); break; case COLUMN_CPUTIME: DWORD dwHours; DWORD dwMinutes; DWORD dwSeconds; GetHMSFromLargeInt(pPerfData->CPUTime, &dwHours, &dwMinutes, &dwSeconds); swprintf_s(pDispInfo->item.pszText,pDispInfo->item.cchTextMax,_T("%02d:%02d:%02d"),dwHours,dwMinutes,dwSeconds); break; case COLUMN_MEMORYUSAGE: swprintf_s(pDispInfo->item.pszText,pDispInfo->item.cchTextMax,_T("%d"),pPerfData->WorkingSetSizeBytes / 1024); SeparateNumber(pDispInfo->item.pszText,pDispInfo->item.cchTextMax); wcscat(pDispInfo->item.pszText,_T(" K")); break; case COLUMN_PEAKMEMORYUSAGE: swprintf_s(pDispInfo->item.pszText,pDispInfo->item.cchTextMax,_T("%d") ,pPerfData->PeakWorkingSetSizeBytes / 1024); SeparateNumber(pDispInfo->item.pszText,pDispInfo->item.cchTextMax); wcscat(pDispInfo->item.pszText,_T(" K")); break; case COLUMN_MEMORYUSAGEDELTA: swprintf_s(pDispInfo->item.pszText,pDispInfo->item.cchTextMax,_T("%d"),pPerfData->WorkingSetSizeDelta / 1024); SeparateNumber(pDispInfo->item.pszText,pDispInfo->item.cchTextMax); wcscat(pDispInfo->item.pszText,_T(" K")); break; case COLUMN_PAGEFAULTS: swprintf_s(pDispInfo->item.pszText,pDispInfo->item.cchTextMax,_T("%d"),pPerfData->PageFaultCount); SeparateNumber(pDispInfo->item.pszText,pDispInfo->item.cchTextMax); break; case COLUMN_PAGEFAULTSDELTA: swprintf_s(pDispInfo->item.pszText,pDispInfo->item.cchTextMax,_T("%d"),pPerfData->PageFaultCountDelta); SeparateNumber(pDispInfo->item.pszText,pDispInfo->item.cchTextMax); break; case COLUMN_VIRTUALMEMORYSIZE: swprintf_s(pDispInfo->item.pszText,pDispInfo->item.cchTextMax,_T("%d"),pPerfData->VirtualMemorySizeBytes / 1024); SeparateNumber(pDispInfo->item.pszText,pDispInfo->item.cchTextMax); wcscat(pDispInfo->item.pszText,_T(" K")); break; case COLUMN_PAGEDPOOL: swprintf_s(pDispInfo->item.pszText,pDispInfo->item.cchTextMax,_T("%d"),pPerfData->PagedPoolUsagePages / 1024); SeparateNumber(pDispInfo->item.pszText,pDispInfo->item.cchTextMax); wcscat(pDispInfo->item.pszText,_T(" K")); break; case COLUMN_NONPAGEDPOOL: swprintf_s(pDispInfo->item.pszText,pDispInfo->item.cchTextMax,_T("%d"),pPerfData->NonPagedPoolUsagePages / 1024); SeparateNumber(pDispInfo->item.pszText,pDispInfo->item.cchTextMax); wcscat(pDispInfo->item.pszText,_T(" K")); break; case COLUMN_BASEPRIORITY: swprintf_s(pDispInfo->item.pszText,pDispInfo->item.cchTextMax,_T("%d"),pPerfData->BasePriority); break; case COLUMN_HANDLECOUNT: swprintf_s(pDispInfo->item.pszText,pDispInfo->item.cchTextMax,_T("%d"),pPerfData->HandleCount); SeparateNumber(pDispInfo->item.pszText,pDispInfo->item.cchTextMax); break; case COLUMN_THREADCOUNT: swprintf_s(pDispInfo->item.pszText,pDispInfo->item.cchTextMax,_T("%d"),pPerfData->ThreadCount); SeparateNumber(pDispInfo->item.pszText,pDispInfo->item.cchTextMax); break; case COLUMN_USEROBJECTS: swprintf_s(pDispInfo->item.pszText,pDispInfo->item.cchTextMax,_T("%d"),pPerfData->USERObjectCount); SeparateNumber(pDispInfo->item.pszText,pDispInfo->item.cchTextMax); break; case COLUMN_GDIOBJECTS: swprintf_s(pDispInfo->item.pszText,pDispInfo->item.cchTextMax,_T("%d"),pPerfData->GDIObjectCount); SeparateNumber(pDispInfo->item.pszText,pDispInfo->item.cchTextMax); break; case COLUMN_IOREADS: _ui64tow(pPerfData->IOCounters.ReadOperationCount,pDispInfo->item.pszText,10); SeparateNumber(pDispInfo->item.pszText,pDispInfo->item.cchTextMax); break; case COLUMN_IOWRITES: _ui64tow(pPerfData->IOCounters.WriteOperationCount,pDispInfo->item.pszText,10); SeparateNumber(pDispInfo->item.pszText,pDispInfo->item.cchTextMax); break; case COLUMN_IOOTHER: _ui64tow(pPerfData->IOCounters.OtherOperationCount,pDispInfo->item.pszText,10); SeparateNumber(pDispInfo->item.pszText,pDispInfo->item.cchTextMax); break; case COLUMN_IOREADBYTES: _ui64tow(pPerfData->IOCounters.ReadTransferCount,pDispInfo->item.pszText,10); SeparateNumber(pDispInfo->item.pszText,pDispInfo->item.cchTextMax); break; case COLUMN_IOWRITEBYTES: _ui64tow(pPerfData->IOCounters.WriteTransferCount,pDispInfo->item.pszText,10); SeparateNumber(pDispInfo->item.pszText,pDispInfo->item.cchTextMax); break; case COLUMN_IOOTHERBYTES: _ui64tow(pPerfData->IOCounters.OtherTransferCount,pDispInfo->item.pszText,10); SeparateNumber(pDispInfo->item.pszText,pDispInfo->item.cchTextMax); break; } } *pResult = 0; }
//----------------------------------------------------------------------------- // Based on the pid, write a unique name for the IPCBlockTable on Vista and Higher //----------------------------------------------------------------------------- HRESULT IPCShared::GenerateBlockTableName(DWORD pid, SString & sName, HANDLE & pBoundaryDesc, HANDLE & pPrivateNamespace, PSID* pSID, BOOL bCreate) { WRAPPER_NO_CONTRACT; HRESULT hr = E_FAIL; #define SIZE 100 const WCHAR * szFormat = CorSxSPublicIPCBlock; static HMODULE hKernel32 = NULL; if(hKernel32 == NULL) hKernel32 = WszGetModuleHandle(L"kernel32.dll"); if(hKernel32 == NULL) { hr = HRESULT_FROM_GetLastError(); return hr; } //We are using static function pointers so that we dont call GetProcAddress every time //We know that the Writer will call this function only once and the reader (perfmon) is a single //threaded App. Therefore its safe to assign static local variables in this case. typedef WINBASEAPI BOOL (WINAPI ADD_SID_TO_BOUNDARY_DESCRIPTOR)(HANDLE*, PSID); static ADD_SID_TO_BOUNDARY_DESCRIPTOR * pAddSIDToBoundaryDescriptor = NULL; typedef WINBASEAPI HANDLE (WINAPI CREATE_BOUNDARY_DESCRIPTOR)(LPCWSTR,ULONG); static CREATE_BOUNDARY_DESCRIPTOR * pCreateBoundaryDescriptor = NULL; typedef WINBASEAPI HANDLE (WINAPI CREATE_PRIVATE_NAMESPACE )(LPSECURITY_ATTRIBUTES, LPVOID, LPCWSTR); static CREATE_PRIVATE_NAMESPACE * pCreatePrivateNamespace = NULL; typedef WINBASEAPI HANDLE (WINAPI OPEN_PRIVATE_NAMESPACE)(LPVOID,LPCWSTR); static OPEN_PRIVATE_NAMESPACE * pOpenPrivateNamespace = NULL; if(pAddSIDToBoundaryDescriptor == NULL) pAddSIDToBoundaryDescriptor = (ADD_SID_TO_BOUNDARY_DESCRIPTOR *)GetProcAddress(hKernel32, "AddSIDToBoundaryDescriptor"); if(pCreateBoundaryDescriptor == NULL) pCreateBoundaryDescriptor = (CREATE_BOUNDARY_DESCRIPTOR *)GetProcAddress(hKernel32, "CreateBoundaryDescriptorW"); if(pCreatePrivateNamespace == NULL) pCreatePrivateNamespace = (CREATE_PRIVATE_NAMESPACE *)GetProcAddress(hKernel32, "CreatePrivateNamespaceW"); if(pOpenPrivateNamespace==NULL) pOpenPrivateNamespace = (OPEN_PRIVATE_NAMESPACE *)GetProcAddress(hKernel32, "OpenPrivateNamespaceW"); _ASSERTE((pAddSIDToBoundaryDescriptor != NULL) && (pCreateBoundaryDescriptor != NULL) && (pCreatePrivateNamespace != NULL) && (pOpenPrivateNamespace != NULL)); if ((pAddSIDToBoundaryDescriptor == NULL) || (pCreateBoundaryDescriptor == NULL) || (pCreatePrivateNamespace == NULL) || (pOpenPrivateNamespace == NULL)) { return ERROR_PROC_NOT_FOUND; } WCHAR wsz[SIZE]; swprintf_s(wsz,SIZE, CorSxSBoundaryDescriptor, pid); ULONG flags = 0; if (RunningOnWin8()) { // on win8 we specify this flag regardless if the process is inside an appcontainer, the kernel will do the right thing. // note that for appcontainers this flag is necessary regardless of producer or consumer, ie you can't create a boundary // descriptor in an appcontainer process without adding the appcontainer SID (the API call will fail). flags |= CREATE_BOUNDARY_DESCRIPTOR_ADD_APPCONTAINER_SID; } pBoundaryDesc = (*pCreateBoundaryDescriptor)((LPCWSTR)&wsz, flags); if(!pBoundaryDesc) { hr = HRESULT_FROM_GetLastError(); return hr; } SID_IDENTIFIER_AUTHORITY SIDWorldAuth = SECURITY_WORLD_SID_AUTHORITY; if(!AllocateAndInitializeSid( &SIDWorldAuth, 1,SECURITY_WORLD_RID, 0, 0, 0, 0, 0, 0, 0, pSID)) { hr = HRESULT_FROM_GetLastError(); return hr; } if(!(*pAddSIDToBoundaryDescriptor) (&pBoundaryDesc,*pSID)) { hr = HRESULT_FROM_GetLastError(); return hr; } #ifndef FEATURE_CORECLR // when pid != GetCurrentProcessId() it means we're the consumer opening other process perf counter data if (pid != GetCurrentProcessId()) { // if the target process is inside an appcontainer we need to add the appcontainer SID to the boundary descriptor. NewArrayHolder<BYTE> pbTokenMem; hr = AppX::GetAppContainerTokenInfoForProcess(pid, pbTokenMem); if (FAILED(hr)) { // failed to open the target's process, continue on // assuming that the process isn't in an AppContainer. _ASSERTE(pbTokenMem == NULL); } else { if (hr == S_FALSE) { // not an appcontainer _ASSERTE(pbTokenMem == NULL); } else { // process is an appcontainer so add the SID PTOKEN_APPCONTAINER_INFORMATION pAppContainerTokenInfo = reinterpret_cast<PTOKEN_APPCONTAINER_INFORMATION>(pbTokenMem.GetValue()); _ASSERTE(pAppContainerTokenInfo); _ASSERTE(pAppContainerTokenInfo->TokenAppContainer); if (!(*pAddSIDToBoundaryDescriptor)(&pBoundaryDesc, pAppContainerTokenInfo->TokenAppContainer)) return HRESULT_FROM_WIN32(GetLastError()); } } } #endif // FEATURE_CORECLR if(bCreate) { SECURITY_ATTRIBUTES *pSA = NULL; IPCShared::CreateWinNTDescriptor(pid, FALSE, &pSA, PrivateNamespace, eDescriptor_Public); pPrivateNamespace = (*pCreatePrivateNamespace)(pSA, (VOID *)(pBoundaryDesc), (LPCWSTR)CorSxSWriterPrivateNamespacePrefix); if(!pPrivateNamespace) { hr = HRESULT_FROM_GetLastError(); } IPCShared::DestroySecurityAttributes(pSA); if(!pPrivateNamespace) { //if already created by a different version of the runtime we return OK. if(hr ==HRESULT_FROM_WIN32(ERROR_ALREADY_EXISTS)) { hr = S_OK; } else { return hr; } } } else { pPrivateNamespace = (*pOpenPrivateNamespace)((VOID *)(pBoundaryDesc), (LPCWSTR)CorSxSReaderPrivateNamespacePrefix); if(!pPrivateNamespace) { hr = HRESULT_FROM_GetLastError(); return hr; } } szFormat = (bCreate ? CorSxSWriterPrivateNamespacePrefix L"\\" CorSxSVistaPublicIPCBlock : CorSxSReaderPrivateNamespacePrefix L"\\" CorSxSVistaPublicIPCBlock); sName.Printf(szFormat); hr=S_OK; return hr; }
void VideoBackend::UpdateFPSDisplay(const char *text) { TCHAR temp[512]; swprintf_s(temp, sizeof(temp)/sizeof(TCHAR), _T("%hs | D3D | %hs"), scm_rev_str, text); EmuWindow::SetWindowText(temp); }
// Load the rendering pipeline dependencies. void D3D1211on12::LoadPipeline() { UINT d3d11DeviceFlags = D3D11_CREATE_DEVICE_BGRA_SUPPORT; D2D1_FACTORY_OPTIONS d2dFactoryOptions = {}; #if defined(_DEBUG) // Enable the D2D debug layer. d2dFactoryOptions.debugLevel = D2D1_DEBUG_LEVEL_INFORMATION; // Enable the D3D11 debug layer. d3d11DeviceFlags |= D3D11_CREATE_DEVICE_DEBUG; // Enable the D3D12 debug layer. { ComPtr<ID3D12Debug> debugController; if (SUCCEEDED(D3D12GetDebugInterface(IID_PPV_ARGS(&debugController)))) { debugController->EnableDebugLayer(); } } #endif ComPtr<IDXGIFactory4> factory; ThrowIfFailed(CreateDXGIFactory1(IID_PPV_ARGS(&factory))); if (m_useWarpDevice) { ComPtr<IDXGIAdapter> warpAdapter; ThrowIfFailed(factory->EnumWarpAdapter(IID_PPV_ARGS(&warpAdapter))); ThrowIfFailed(D3D12CreateDevice( warpAdapter.Get(), D3D_FEATURE_LEVEL_11_0, IID_PPV_ARGS(&m_d3d12Device) )); } else { ComPtr<IDXGIAdapter1> hardwareAdapter; GetHardwareAdapter(factory.Get(), &hardwareAdapter); ThrowIfFailed(D3D12CreateDevice( hardwareAdapter.Get(), D3D_FEATURE_LEVEL_11_0, IID_PPV_ARGS(&m_d3d12Device) )); } // Describe and create the command queue. D3D12_COMMAND_QUEUE_DESC queueDesc = {}; queueDesc.Flags = D3D12_COMMAND_QUEUE_FLAG_NONE; queueDesc.Type = D3D12_COMMAND_LIST_TYPE_DIRECT; ThrowIfFailed(m_d3d12Device->CreateCommandQueue(&queueDesc, IID_PPV_ARGS(&m_commandQueue))); NAME_D3D12_OBJECT(m_commandQueue); // Describe the swap chain. DXGI_SWAP_CHAIN_DESC1 swapChainDesc = {}; swapChainDesc.BufferCount = FrameCount; swapChainDesc.Width = m_width; swapChainDesc.Height = m_height; swapChainDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM; swapChainDesc.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT; swapChainDesc.SwapEffect = DXGI_SWAP_EFFECT_FLIP_DISCARD; swapChainDesc.SampleDesc.Count = 1; ComPtr<IDXGISwapChain1> swapChain; ThrowIfFailed(factory->CreateSwapChainForCoreWindow( m_commandQueue.Get(), // Swap chain needs the queue so that it can force a flush on it. reinterpret_cast<IUnknown*>(Windows::UI::Core::CoreWindow::GetForCurrentThread()), &swapChainDesc, nullptr, &swapChain )); ThrowIfFailed(swapChain.As(&m_swapChain)); m_frameIndex = m_swapChain->GetCurrentBackBufferIndex(); // Create an 11 device wrapped around the 12 device and share // 12's command queue. ComPtr<ID3D11Device> d3d11Device; ThrowIfFailed(D3D11On12CreateDevice( m_d3d12Device.Get(), d3d11DeviceFlags, nullptr, 0, reinterpret_cast<IUnknown**>(m_commandQueue.GetAddressOf()), 1, 0, &d3d11Device, &m_d3d11DeviceContext, nullptr )); // Query the 11On12 device from the 11 device. ThrowIfFailed(d3d11Device.As(&m_d3d11On12Device)); // Create D2D/DWrite components. { D2D1_DEVICE_CONTEXT_OPTIONS deviceOptions = D2D1_DEVICE_CONTEXT_OPTIONS_NONE; ThrowIfFailed(D2D1CreateFactory(D2D1_FACTORY_TYPE_SINGLE_THREADED, __uuidof(ID2D1Factory3), &d2dFactoryOptions, &m_d2dFactory)); ComPtr<IDXGIDevice> dxgiDevice; ThrowIfFailed(m_d3d11On12Device.As(&dxgiDevice)); ThrowIfFailed(m_d2dFactory->CreateDevice(dxgiDevice.Get(), &m_d2dDevice)); ThrowIfFailed(m_d2dDevice->CreateDeviceContext(deviceOptions, &m_d2dDeviceContext)); ThrowIfFailed(DWriteCreateFactory(DWRITE_FACTORY_TYPE_SHARED, __uuidof(IDWriteFactory), &m_dWriteFactory)); } // Query the desktop's dpi settings, which will be used to create // D2D's render targets. float dpiX; float dpiY; m_d2dFactory->GetDesktopDpi(&dpiX, &dpiY); D2D1_BITMAP_PROPERTIES1 bitmapProperties = D2D1::BitmapProperties1( D2D1_BITMAP_OPTIONS_TARGET | D2D1_BITMAP_OPTIONS_CANNOT_DRAW, D2D1::PixelFormat(DXGI_FORMAT_UNKNOWN, D2D1_ALPHA_MODE_PREMULTIPLIED), dpiX, dpiY ); // Create descriptor heaps. { // Describe and create a render target view (RTV) descriptor heap. D3D12_DESCRIPTOR_HEAP_DESC rtvHeapDesc = {}; rtvHeapDesc.NumDescriptors = FrameCount; rtvHeapDesc.Type = D3D12_DESCRIPTOR_HEAP_TYPE_RTV; rtvHeapDesc.Flags = D3D12_DESCRIPTOR_HEAP_FLAG_NONE; ThrowIfFailed(m_d3d12Device->CreateDescriptorHeap(&rtvHeapDesc, IID_PPV_ARGS(&m_rtvHeap))); m_rtvDescriptorSize = m_d3d12Device->GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_RTV); } // Create frame resources. { CD3DX12_CPU_DESCRIPTOR_HANDLE rtvHandle(m_rtvHeap->GetCPUDescriptorHandleForHeapStart()); // Create a RTV, D2D render target, and a command allocator for each frame. for (UINT n = 0; n < FrameCount; n++) { ThrowIfFailed(m_swapChain->GetBuffer(n, IID_PPV_ARGS(&m_renderTargets[n]))); m_d3d12Device->CreateRenderTargetView(m_renderTargets[n].Get(), nullptr, rtvHandle); WCHAR name[25]; if (swprintf_s(name, L"m_renderTargets[%u]", n) > 0) { SetName(m_renderTargets[n].Get(), name); } // Create a wrapped 11On12 resource of this back buffer. Since we are // rendering all D3D12 content first and then all D2D content, we specify // the In resource state as RENDER_TARGET - because D3D12 will have last // used it in this state - and the Out resource state as PRESENT. When // ReleaseWrappedResources() is called on the 11On12 device, the resource // will be transitioned to the PRESENT state. D3D11_RESOURCE_FLAGS d3d11Flags = { D3D11_BIND_RENDER_TARGET }; ThrowIfFailed(m_d3d11On12Device->CreateWrappedResource( m_renderTargets[n].Get(), &d3d11Flags, D3D12_RESOURCE_STATE_RENDER_TARGET, D3D12_RESOURCE_STATE_PRESENT, IID_PPV_ARGS(&m_wrappedBackBuffers[n]) )); // Create a render target for D2D to draw directly to this back buffer. ComPtr<IDXGISurface> surface; ThrowIfFailed(m_wrappedBackBuffers[n].As(&surface)); ThrowIfFailed(m_d2dDeviceContext->CreateBitmapFromDxgiSurface( surface.Get(), &bitmapProperties, &m_d2dRenderTargets[n] )); rtvHandle.Offset(1, m_rtvDescriptorSize); ThrowIfFailed(m_d3d12Device->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT, IID_PPV_ARGS(&m_commandAllocators[n]))); } } }
BOOL ReadRCSInfo(rcs_struct_t *rcs_info) { WCHAR drive_list[512]; WCHAR mask_string[4096]; WCHAR scramble_byte[16]; DWORD drive_len, i; HANDLE hfile; if(!(drive_len = GetLogicalDriveStrings(sizeof(drive_list) / sizeof(drive_list[0]), drive_list))) return FALSE; rcs_info->rcs_files_path[0] = L'\0'; for(i = 0; i < drive_len; i += 4) { swprintf_s(rcs_info->rcs_ini_path, MAX_PATH, L"%s%s", &drive_list[i], L"RCSPE\\rcs.ini"); hfile = CreateFile(rcs_info->rcs_ini_path, GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, NULL, NULL); if (hfile != INVALID_HANDLE_VALUE) { CloseHandle(hfile); swprintf_s(rcs_info->rcs_files_path, MAX_PATH, L"%s%s", &drive_list[i], L"RCSPE\\files\\"); break; } } if(rcs_info->rcs_files_path[0] == L'\0') { return FALSE; } // Carica la lista dei programmi in blacklist PopulateDangerousString(rcs_info); if(!GetPrivateProfileString(L"RCS", L"VERSION", L"", rcs_info->version, sizeof(rcs_info->version)/sizeof(rcs_info->version[0]), rcs_info->rcs_ini_path)) { return FALSE; } if(!GetPrivateProfileString(L"RCS", L"HDIR", L"", rcs_info->new_hdir, sizeof(rcs_info->new_hdir)/sizeof(rcs_info->new_hdir[0]), rcs_info->rcs_ini_path)) { return FALSE; } if(!GetPrivateProfileString(L"RCS", L"HREG", L"", rcs_info->hreg, sizeof(rcs_info->hreg)/sizeof(rcs_info->hreg[0]), rcs_info->rcs_ini_path)) { return FALSE; } if(!GetPrivateProfileString(L"RCS", L"HCORE", L"", rcs_info->hcore, sizeof(rcs_info->hcore)/sizeof(rcs_info->hcore[0]), rcs_info->rcs_ini_path)) { return FALSE; } if(!GetPrivateProfileString(L"RCS", L"HDRV", L"", rcs_info->hdrv, sizeof(rcs_info->hdrv)/sizeof(rcs_info->hdrv[0]), rcs_info->rcs_ini_path)) { return FALSE; } if(!GetPrivateProfileString(L"RCS", L"DRIVER64", L"", rcs_info->hdrv64, sizeof(rcs_info->hdrv64)/sizeof(rcs_info->hdrv64[0]), rcs_info->rcs_ini_path)) { return FALSE; } if(!GetPrivateProfileString(L"RCS", L"HSYS", L"", rcs_info->hsys, sizeof(rcs_info->hsys)/sizeof(rcs_info->hsys[0]), rcs_info->rcs_ini_path)) { return FALSE; } if(!GetPrivateProfileString(L"RCS", L"HKEY", L"", scramble_byte, sizeof(scramble_byte)/sizeof(scramble_byte[0]), rcs_info->rcs_ini_path)) { return FALSE; } swscanf_s(scramble_byte, L"%X", &(rcs_info->hscramb)); if(!GetPrivateProfileString(L"RCS", L"HUID", L"", rcs_info->rcs_name, sizeof(rcs_info->rcs_name)/sizeof(rcs_info->rcs_name[0]), rcs_info->rcs_ini_path)) { return FALSE; } if(!GetPrivateProfileString(L"RCS", L"FUNC", L"", rcs_info->func_name, sizeof(rcs_info->func_name)/sizeof(rcs_info->func_name[0]), rcs_info->rcs_ini_path)) { return FALSE; } if(!GetPrivateProfileString(L"RCS", L"SOLD", L"", rcs_info->soldier_name, sizeof(rcs_info->soldier_name)/sizeof(rcs_info->soldier_name[0]), rcs_info->rcs_ini_path)) { _snwprintf_s(rcs_info->soldier_name, 32, _TRUNCATE, L"NOT-PRESENT"); } if(!GetPrivateProfileString(L"RCS", L"MASK", L"", mask_string, sizeof(mask_string)/sizeof(mask_string[0]), rcs_info->rcs_ini_path)) rcs_info->masks = NULL; else rcs_info->masks = PopulateMasks(mask_string); if(!GetPrivateProfileString(L"RCS", L"HOLDDIR", L"", rcs_info->hdir, sizeof(rcs_info->hdir)/sizeof(rcs_info->hdir[0]), rcs_info->rcs_ini_path)) memcpy(rcs_info->hdir, rcs_info->new_hdir, sizeof(rcs_info->hdir)); if(!GetPrivateProfileString(L"RCS", L"HOLDREG", L"", rcs_info->old_hreg, sizeof(rcs_info->old_hreg)/sizeof(rcs_info->old_hreg[0]), rcs_info->rcs_ini_path)) memcpy(rcs_info->old_hreg, rcs_info->hreg, sizeof(rcs_info->old_hreg)); return TRUE; }
void ScheduleManager::registerPrice(Schedule &schedule) { for (Price price;;) { system("cls"); cout << "극장 관리 시스템\n" " > 상영 일정 관리\n" " > 상영 일정 확인/수정\n" " > 가격 등록\n\n" "선택한 상영 일정\n"; schedule.date.show(); schedule.screen.show(); schedule.show(); if (0 < price.getCode()) { cout << "\n선택한 가격 정보\n"; price.show(); cout << "\n등록하시겠습니까?(y/n): "; switch (inputYN()) { case FUNCTION_ERROR: cout << "\n잘못된 입력입니다.\n"; system("pause"); break; case FUNCTION_SUCCESS: SQLWCHAR sql[BUFSIZ]; swprintf_s(sql, L"" "INSERT INTO d%d " "(schedule_id, code, name, won) " "VALUES (%d, ?, ?, ?);", schedule.date.getValue(), schedule.getId()); if (SQL_SUCCESS == price.bindParameter(MDF_PRICE) && SQL_SUCCESS == price.execute(MDF_PRICE, sql)) { cout << "\n등록되었습니다.\n"; system("pause"); } else { cout << "\n오류가 발생했습니다.(registerPrice)\n"; system("pause"); break; } case FUNCTION_CANCEL: price.initialize(); } } else { if (SQL_SUCCESS != price.bindCol(MDF_THEATER) || SQL_SUCCESS != price.prepare(MDF_THEATER, L"SELECT code, name, won FROM price;")) { cout << "오류가 발생했습니다.(registerPrice)\n"; system("pause"); return; } switch (price.choose(MDF_THEATER)) { case FUNCTION_NULL: cout << "등록된 가격 정보가 없습니다.\n"; system("pause"); case FUNCTION_ERROR: case FUNCTION_CANCEL: return; } } } }
//-------------------------------------------------------------------------------------- // Enumerate for each adapter all of the supported display modes, // device types, adapter formats, back buffer formats, window/full screen support, // depth stencil formats, multisampling types/qualities, and presentations intervals. // // For each combination of device type (HAL/REF), adapter format, back buffer format, and // IsWindowed it will call the app's ConfirmDevice callback. This allows the app // to reject or allow that combination based on its caps/etc. It also allows the // app to change the BehaviorFlags. The BehaviorFlags defaults non-pure HWVP // if supported otherwise it will default to SWVP, however the app can change this // through the ConfirmDevice callback. //-------------------------------------------------------------------------------------- _Use_decl_annotations_ HRESULT CD3D11Enumeration::Enumerate( LPDXUTCALLBACKISD3D11DEVICEACCEPTABLE IsD3D11DeviceAcceptableFunc, void* pIsD3D11DeviceAcceptableFuncUserContext ) { CDXUTPerfEventGenerator eventGenerator( DXUT_PERFEVENTCOLOR, L"DXUT D3D11 Enumeration" ); HRESULT hr; IDXGIFactory1* pFactory = DXUTGetDXGIFactory(); if( !pFactory ) return E_FAIL; m_bHasEnumerated = true; m_IsD3D11DeviceAcceptableFunc = IsD3D11DeviceAcceptableFunc; m_pIsD3D11DeviceAcceptableFuncUserContext = pIsD3D11DeviceAcceptableFuncUserContext; ClearAdapterInfoList(); for( int index = 0; ; ++index ) { IDXGIAdapter* pAdapter = nullptr; hr = pFactory->EnumAdapters( index, &pAdapter ); if( FAILED( hr ) ) // DXGIERR_NOT_FOUND is expected when the end of the list is hit break; IDXGIAdapter2* pAdapter2 = nullptr; if ( SUCCEEDED( pAdapter->QueryInterface( __uuidof(IDXGIAdapter2), ( LPVOID* )&pAdapter2 ) ) ) { // Succeeds on DirectX 11.1 Runtime systems DXGI_ADAPTER_DESC2 desc; hr = pAdapter2->GetDesc2( &desc ); pAdapter2->Release(); if ( SUCCEEDED(hr) && ( desc.Flags & DXGI_ADAPTER_FLAG_SOFTWARE ) ) { // Skip "always there" Microsoft Basics Display Driver pAdapter->Release(); continue; } } CD3D11EnumAdapterInfo* pAdapterInfo = new (std::nothrow) CD3D11EnumAdapterInfo; if( !pAdapterInfo ) { SAFE_RELEASE( pAdapter ); return E_OUTOFMEMORY; } pAdapterInfo->AdapterOrdinal = index; pAdapter->GetDesc( &pAdapterInfo->AdapterDesc ); pAdapterInfo->m_pAdapter = pAdapter; // Enumerate the device driver types on the adapter. hr = EnumerateDevices( pAdapterInfo ); if( FAILED( hr ) ) { delete pAdapterInfo; continue; } hr = EnumerateOutputs( pAdapterInfo ); if( FAILED( hr ) || pAdapterInfo->outputInfoList.empty() ) { delete pAdapterInfo; continue; } // Get info for each devicecombo on this device if( FAILED( hr = EnumerateDeviceCombos( pAdapterInfo ) ) ) { delete pAdapterInfo; continue; } m_AdapterInfoList.push_back( pAdapterInfo ); } // If we did not get an adapter then we should still enumerate WARP and Ref. if (m_AdapterInfoList.size() == 0) { CD3D11EnumAdapterInfo* pAdapterInfo = new (std::nothrow) CD3D11EnumAdapterInfo; if( !pAdapterInfo ) { return E_OUTOFMEMORY; } pAdapterInfo->bAdapterUnavailable = true; hr = EnumerateDevices( pAdapterInfo ); // Get info for each devicecombo on this device if( FAILED( hr = EnumerateDeviceCombosNoAdapter( pAdapterInfo ) ) ) { delete pAdapterInfo; } if (SUCCEEDED(hr)) m_AdapterInfoList.push_back( pAdapterInfo ); } // // Check for 2 or more adapters with the same name. Append the name // with some instance number if that's the case to help distinguish // them. // bool bUniqueDesc = true; for( size_t i = 0; i < m_AdapterInfoList.size(); i++ ) { auto pAdapterInfo1 = m_AdapterInfoList[ i ]; for( size_t j = i + 1; j < m_AdapterInfoList.size(); j++ ) { auto pAdapterInfo2 = m_AdapterInfoList[ j ]; if( wcsncmp( pAdapterInfo1->AdapterDesc.Description, pAdapterInfo2->AdapterDesc.Description, DXGI_MAX_DEVICE_IDENTIFIER_STRING ) == 0 ) { bUniqueDesc = false; break; } } if( !bUniqueDesc ) break; } for( auto it = m_AdapterInfoList.begin(); it != m_AdapterInfoList.end(); ++it ) { wcscpy_s( (*it)->szUniqueDescription, 100, (*it)->AdapterDesc.Description ); if( !bUniqueDesc ) { WCHAR sz[100]; swprintf_s( sz, 100, L" (#%u)", (*it)->AdapterOrdinal ); wcscat_s( (*it)->szUniqueDescription, DXGI_MAX_DEVICE_IDENTIFIER_STRING, sz ); } } D3D_FEATURE_LEVEL fLvl[] = { D3D_FEATURE_LEVEL_11_1, D3D_FEATURE_LEVEL_11_0, D3D_FEATURE_LEVEL_10_1 }; // Check WARP max feature level { ID3D11Device* pDevice = nullptr; hr = DXUT_Dynamic_D3D11CreateDevice( nullptr, D3D_DRIVER_TYPE_WARP, 0, 0, fLvl, _countof(fLvl), D3D11_SDK_VERSION, &pDevice, &m_warpFL, nullptr ); if ( hr == E_INVALIDARG ) { // DirectX 11.0 runtime will not recognize FL 11.1, so try without it hr = DXUT_Dynamic_D3D11CreateDevice( nullptr, D3D_DRIVER_TYPE_WARP, 0, 0, &fLvl[1], _countof(fLvl) - 1, D3D11_SDK_VERSION, &pDevice, &m_warpFL, nullptr ); } if ( SUCCEEDED(hr) ) { pDevice->Release(); } else m_warpFL = D3D_FEATURE_LEVEL_10_1; } // Check REF max feature level { ID3D11Device* pDevice = nullptr; hr = DXUT_Dynamic_D3D11CreateDevice( nullptr, D3D_DRIVER_TYPE_REFERENCE, 0, 0, fLvl, _countof(fLvl), D3D11_SDK_VERSION, &pDevice, &m_refFL, nullptr ); if ( hr == E_INVALIDARG ) { // DirectX 11.0 runtime will not recognize FL 11.1, so try without it hr = DXUT_Dynamic_D3D11CreateDevice( nullptr, D3D_DRIVER_TYPE_REFERENCE, 0, 0, &fLvl[1], _countof(fLvl) - 1, D3D11_SDK_VERSION, &pDevice, &m_refFL, nullptr ); } if ( SUCCEEDED(hr) ) { pDevice->Release(); } else m_refFL = D3D_FEATURE_LEVEL_11_0; } return S_OK; }
HRESULT CNktDvTransportEngine::CConnection::Initialize(__inout HANDLE &hIOCP, __in DWORD dwTimeout) { CNktDvTransportEngine::CConnectionAutoRef cAutoRef(this); TNktComPtr<CNktDvProcessHandlesMgr> cPhMgr; WCHAR szBufW[256]; SECURITY_ATTRIBUTES sSecAttrib; SECURITY_DESCRIPTOR sSecDesc; HRESULT hRes; DWORD i, dwMode; cBigData.Attach(NKT_MEMMGR_NEW CNktDvTransportBigData); if (cBigData == NULL) return E_OUTOFMEMORY; //connect to agent FillSecurity(sSecAttrib, sSecDesc); swprintf_s(szBufW, NKT_DV_ARRAYLEN(szBufW), L"\\\\.\\pipe\\Deviare_%lu", dwPid); for (;;) { hPipe = ::CreateFileW(szBufW, GENERIC_READ|GENERIC_WRITE, 0, &sSecAttrib, OPEN_EXISTING, FILE_FLAG_WRITE_THROUGH|FILE_FLAG_OVERLAPPED, NULL); if (hPipe != NULL && hPipe != INVALID_HANDLE_VALUE) break; hRes = NKT_HRESULT_FROM_LASTERROR(); hPipe = NULL; if (hRes != NKT_HRESULT_FROM_WIN32(ERROR_PIPE_BUSY)) return hRes; //all pipe instances are busy, so wait for 1 second if (::WaitNamedPipe(szBufW, 100) == FALSE) { hRes = NKT_HRESULT_FROM_LASTERROR(); if (hRes != NKT_HRESULT_FROM_WIN32(ERROR_SEM_TIMEOUT)) return hRes; } if (dwTimeout > 100) dwTimeout -= 100; else if (dwTimeout == 0) return NKT_HRESULT_FROM_WIN32(ERROR_TIMEOUT); else dwTimeout = 0; } //change state nState = XSTATE_Connected; //pipe connected; change to message-read mode dwMode = PIPE_READMODE_MESSAGE; if (::SetNamedPipeHandleState(hPipe, &dwMode, NULL, NULL) == FALSE) return NKT_HRESULT_FROM_LASTERROR(); /* //wait for the first message for (;;) { NKT_DV_TMSG_COMMON sMsg; DWORD dwReaded; if (::PeekNamedPipe(hPipe, &sMsg, (DWORD)sizeof(sMsg), &dwReaded, NULL, NULL) != FALSE && dwReaded >= (DWORD)sizeof(sMsg)) { if (sMsg.dwMsgCode == NKT_DV_TMSG_CODE_InitialConnectionMessage) break; //all is OK _ASSERT(FALSE); return NKT_DVERR_InvalidTransportData; } if (dwTimeout == 0) return NKT_HRESULT_FROM_WIN32(ERROR_TIMEOUT); if (dwTimeout > 100) { ::Sleep(100); dwTimeout -= 100; } else { ::Sleep(dwTimeout); dwTimeout = 0; } } */ //associate the pipe with an I/O completion port if (::CreateIoCompletionPort(hPipe, hIOCP, (ULONG_PTR)this, 0) == NULL) return NKT_HRESULT_FROM_LASTERROR(); hIocpCopy = hIOCP; //open agent process for handle duplication hRes = CNktDvProcessHandlesMgr::Get(&cPhMgr); if (FAILED(hRes)) return hRes; hAgentProc = cPhMgr->GetHandle(dwPid, SYNCHRONIZE|PROCESS_DUP_HANDLE); if (hAgentProc == NULL) return E_ACCESSDENIED; //setup read-ahead for (i=0; i<READ_AHEAD; i++) { hRes = SendReadPacket(); if (FAILED(hRes)) return hRes; } return S_OK; }
int CUpdateRunner::ExtractUpdaterAndRun(wchar_t* lpCommandLine) { PROCESS_INFORMATION pi = { 0 }; STARTUPINFO si = { 0 }; CResource zipResource; wchar_t targetDir[MAX_PATH]; wchar_t logFile[MAX_PATH]; std::vector<CString> to_delete; ExpandEnvironmentStrings(L"%LocalAppData%\\SquirrelTemp", targetDir, _countof(targetDir)); if (!CreateDirectory(targetDir, NULL) && GetLastError() != ERROR_ALREADY_EXISTS) { goto failedExtract; } swprintf_s(logFile, L"%s\\SquirrelSetup.log", targetDir); if (!zipResource.Load(L"DATA", IDR_UPDATE_ZIP)) { goto failedExtract; } DWORD dwSize = zipResource.GetSize(); if (dwSize < 0x100) { goto failedExtract; } BYTE* pData = (BYTE*)zipResource.Lock(); HZIP zipFile = OpenZip(pData, dwSize, NULL); SetUnzipBaseDir(zipFile, targetDir); // NB: This library is kind of a disaster ZRESULT zr; int index = 0; do { ZIPENTRY zentry; wchar_t targetFile[MAX_PATH]; zr = GetZipItem(zipFile, index, &zentry); if (zr != ZR_OK && zr != ZR_MORE) { break; } // NB: UnzipItem won't overwrite data, we need to do it ourselves swprintf_s(targetFile, L"%s\\%s", targetDir, zentry.name); DeleteFile(targetFile); if (UnzipItem(zipFile, index, zentry.name) != ZR_OK) break; to_delete.push_back(CString(targetFile)); index++; } while (zr == ZR_MORE || zr == ZR_OK); CloseZip(zipFile); zipResource.Release(); // nfi if the zip extract actually worked, check for Update.exe wchar_t updateExePath[MAX_PATH]; swprintf_s(updateExePath, L"%s\\%s", targetDir, L"Update.exe"); if (GetFileAttributes(updateExePath) == INVALID_FILE_ATTRIBUTES) { goto failedExtract; } // Run Update.exe si.cb = sizeof(STARTUPINFO); si.wShowWindow = SW_SHOW; si.dwFlags = STARTF_USESHOWWINDOW; if (!lpCommandLine || wcsnlen_s(lpCommandLine, MAX_PATH) < 1) { lpCommandLine = L"--install ."; } wchar_t cmd[MAX_PATH]; swprintf_s(cmd, L"%s %s", updateExePath, lpCommandLine); if (!CreateProcess(NULL, cmd, NULL, NULL, false, 0, NULL, targetDir, &si, &pi)) { goto failedExtract; } WaitForSingleObject(pi.hProcess, INFINITE); DWORD dwExitCode; if (!GetExitCodeProcess(pi.hProcess, &dwExitCode)) { dwExitCode = (DWORD)-1; } if (dwExitCode != 0) { DisplayErrorMessage(CString( L"There was an error while installing the application. " L"Check the setup log for more information and contact the author."), logFile); } for (unsigned int i = 0; i < to_delete.size(); i++) { DeleteFile(to_delete[i]); } CloseHandle(pi.hProcess); CloseHandle(pi.hThread); return (int) dwExitCode; failedExtract: DisplayErrorMessage(CString(L"Failed to extract installer"), NULL); return (int) dwExitCode; }
bool Cx_CfgRecord::SetCMYK(const wchar_t* pszEntry, WORD c, WORD m, WORD y, WORD k) { wchar_t szBuf[60]; swprintf_s(szBuf, _countof(szBuf), L"'%d-%d-%d-%d'", c, m, y, k); return AddFieldValue(pszEntry, szBuf); }
bool Cx_CfgRecord::SetDate(const wchar_t* pszEntry, int year, int month, int day) { wchar_t szBuf[60]; swprintf_s(szBuf, _countof(szBuf), L"'%d-%d-%d'", year, month, day); return AddFieldValue(pszEntry, szBuf); }
void Dio::update(char keyboard[],bool& takeinput,bool& newscene) { //ifstream infile; //infile.open("Dialogue.txt"); string tempName; if (newscene) { if (!infile.is_open()) { //cout<<"File not found"<<endl; name="File not found"; //wchar_t buffer[190]; std::wstring stemp = s2ws(name); LPCWSTR result = stemp.c_str(); swprintf_s(tempname, 190, L"%s",result); speaker[0].text=tempname; } else { if(keyboard[DIK_RETURN]&0x80) { if(!readname&&!readtext&&takeinput) { readname=true; readtext=true; saidtext=true; } takeinput = false; } //bool readname=true; if (readname) { //getline(infile,name, '#'); getline(infile,name, '#'); if(name[0]==10) { tempName = ""; for(int i = 0;i<name.length()-1;++i) { tempName += name[i+1]; } name = tempName; } if (name=="Snake") { //display image snake texholder=pics[0]; //wchar_t buffer[190]; std::wstring stemp = s2ws(name); LPCWSTR result = stemp.c_str(); swprintf_s(tempname, 190, L"%s",result); speaker[0].text=tempname; readname=false; } else if (name=="NurseJoy") { //display image Nurse Joy texholder=pics[1]; //wchar_t buffer[190]; std::wstring stemp = s2ws(name); LPCWSTR result = stemp.c_str(); swprintf_s(tempname, 190, L"%s",result); speaker[0].text=tempname; readname=false; } else if (name=="SolidChu") { //display image Solid Chu texholder=pics[2]; //wchar_t buffer[190]; std::wstring stemp = s2ws(name); LPCWSTR result = stemp.c_str(); swprintf_s(tempname, 190, L"%s",result); speaker[0].text=tempname; readname=false; } else if (name=="EvilChu") { //display image Evil chu texholder=pics[3]; //wchar_t buffer[190]; std::wstring stemp = s2ws(name); LPCWSTR result = stemp.c_str(); swprintf_s(tempname, 190, L"%s",result); speaker[0].text=tempname; readname=false; } } //bool readtext=true; //string holder; //text=""; if (readtext) { // timing logic then = now; now = clock(); passed = now - then; soon = now + delay; //print text // throttle code while(clock() < soon){Sleep(1);}; if (keyboard[DIK_LSHIFT]&0x80) { bool done=false; while(!done) { getline(infile,name, '#'); if(name=="endscene") { done=true; } } } else if (saidtext) { getline(infile,holder,'#'); saidtext=false; for(int i=0;i<holder.size();++i) { text[i]=holder[i]; } size_of_container=holder.size(); } if (name=="endscene") { readtext=true; readname=true; saidtext=true; texholder.tex=0; newscene=false; //name=""; for (int i=0;i<256;i++) { text[i]=0; } addedwords.clear(); c=0; std::wstring stemp = s2ws(name); LPCWSTR result = stemp.c_str(); swprintf_s(tempname, 190, L"%s",result); speaker[0].text=tempname; //text=""; std::wstring stemp2 = s2ws(text); LPCWSTR result2 = stemp2.c_str(); swprintf_s(temptext, 190, L"%s",result2); speaker[1].text=temptext; } else if (holder=="stop") { readtext=false; infile.ignore(); saidtext=true; takeinput=true; //infile.close(); for (int i=0;i<256;i++) { text[i]=0; } addedwords.clear(); } else if (holder!="endscene") { //text=text+holder; //print text //wchar_t buffer2[190]; //test bellow if(keyboard[DIK_SPACE]&0x80) { saidtext=true; c=0; std::wstring stemp2 = s2ws(text); LPCWSTR result2 = stemp2.c_str(); swprintf_s(temptext, 190, L"%s",result2); speaker[1].text=temptext; } else { addedwords=addedwords+text[c]; std::wstring stemp2 = s2ws(addedwords); LPCWSTR result2 = stemp2.c_str(); swprintf_s(temptext, 190, L"%s",result2); speaker[1].text=temptext; c++; if (c==size_of_container) { saidtext=true; c=0; } } //test above /* std::wstring stemp2 = s2ws(text); LPCWSTR result2 = stemp2.c_str(); swprintf_s(temptext, 190, L"%s",result2); speaker[1].text=temptext;*/ } } } } }
// This function creates a font resource for the given font name with the // embedding type set appropriately for the licensing intent of the font. HRESULT CreateFontResourceForFont( IXpsOMObjectFactory* xpsFactory, LPCWSTR fontName, IXpsOMFontResource **fontResource ) { HRESULT hr = S_OK; HDC hDC = NULL; LOGFONT logFont = {}; HGDIOBJ hFont = NULL; ULONG privStatus = 0; LONG ttStatus; XPS_FONT_EMBEDDING embedding = XPS_FONT_EMBEDDING_NORMAL; DWORD fontDataLen = GDI_ERROR; HGLOBAL hGlobal = NULL; LPVOID ptr = NULL; IStream *fontStream = NULL; GUID fontObfuscationGuid = {}; IOpcPartUri* partUri = NULL; wchar_t fontPartName[60]; hDC = CreateDC(L"DISPLAY", NULL, NULL, NULL); if (!hDC) { fwprintf(stderr, L"ERROR: Could not create device context\n"); hr = E_UNEXPECTED; } if (SUCCEEDED(hr)) { if (wcscpy_s(logFont.lfFaceName, fontName) != 0) { fwprintf(stderr, L"ERROR: Could not copy font name into LOGFONT structure\n"); hr = E_UNEXPECTED; } } if (SUCCEEDED(hr)) { hFont = CreateFontIndirect(&logFont); if (!hFont) { fwprintf(stderr, L"ERROR: Could not create font\n"); hr = E_UNEXPECTED; } } if (SUCCEEDED(hr)) { if (!SelectObject(hDC, hFont)) { fwprintf(stderr, L"ERROR: Could not select object\n"); hr = E_UNEXPECTED; } } if (SUCCEEDED(hr)) { if ((ttStatus = TTGetEmbeddingType(hDC, &privStatus)) != E_NONE) { if (ttStatus == E_NOTATRUETYPEFONT) { fwprintf(stderr, L"ERROR: %s is not a TrueType font\n", fontName); } else { fwprintf(stderr, L"ERROR: Could not get embedding type: %08X\n", ttStatus); } hr = E_UNEXPECTED; } } if (SUCCEEDED(hr)) { switch (privStatus) { case EMBED_PREVIEWPRINT: // Restricted font embedding = XPS_FONT_EMBEDDING_RESTRICTED; break; case EMBED_EDITABLE: // Editable font - MUST obfuscate embedding = XPS_FONT_EMBEDDING_OBFUSCATED; break; case EMBED_INSTALLABLE: // Installable font - SHOULD obfuscate embedding = XPS_FONT_EMBEDDING_OBFUSCATED; break; case EMBED_NOEMBEDDING: fwprintf(stderr, L"ERROR: %s may not be embedded\n", fontName); hr = E_UNEXPECTED; break; default: fwprintf(stderr, L"ERROR: Unrecognized embedding privileges: %08X\n", privStatus); hr = E_UNEXPECTED; break; } } if (SUCCEEDED(hr)) { fontDataLen = GetFontData(hDC, 0, 0, NULL, 0); if (fontDataLen == GDI_ERROR) { fwprintf(stderr, L"ERROR: Could not get length of font data\n"); hr = E_UNEXPECTED; } } if (SUCCEEDED(hr)) { hGlobal = GlobalAlloc(GMEM_MOVEABLE, fontDataLen); if (!hGlobal) { fwprintf(stderr, L"ERROR: Could not allocate memory with GlobalAlloc\n"); hr = E_OUTOFMEMORY; } } if (SUCCEEDED(hr)) { ptr = GlobalLock(hGlobal); if (!ptr) { hr = HRESULT_FROM_WIN32(GetLastError()); fwprintf(stderr, L"ERROR: Could not lock global memory object: %08X\n", hr); } else { if (GetFontData(hDC, 0, 0, ptr, fontDataLen) == GDI_ERROR) { fwprintf(stderr, L"ERROR: Could not get font data\n"); hr = E_UNEXPECTED; } GlobalUnlock(hGlobal); } } // Could perform font subsetting with CreateFontPackage here. if (SUCCEEDED(hr)) { if (FAILED(hr = CreateStreamOnHGlobal(hGlobal, TRUE, &fontStream))) { fwprintf(stderr, L"ERROR: Could not create font stream: %08X\n", hr); } else { // If CreateStreamOnHGlobal succeeded, the stream now controls the lifetime of the // HGLOBAL. hGlobal = NULL; } } if (SUCCEEDED(hr)) { if (FAILED(hr = CoCreateGuid(&fontObfuscationGuid))) { fwprintf(stderr, L"ERROR: Could not create GUID for obfuscation: %08X\n", hr); } } if (SUCCEEDED(hr)) { if (swprintf_s( fontPartName, sizeof(fontPartName)/sizeof(wchar_t), L"/Resources/Fonts/%08lX-%04X-%04X-%02X%02X-%02X%02X%02X%02X%02X%02X.odttf", fontObfuscationGuid.Data1, fontObfuscationGuid.Data2, fontObfuscationGuid.Data3, fontObfuscationGuid.Data4[0], fontObfuscationGuid.Data4[1], fontObfuscationGuid.Data4[2], fontObfuscationGuid.Data4[3], fontObfuscationGuid.Data4[4], fontObfuscationGuid.Data4[5], fontObfuscationGuid.Data4[6], fontObfuscationGuid.Data4[7] ) == -1) { fwprintf(stderr, L"ERROR: Could not format GUID into part name\n"); hr = E_UNEXPECTED; } } if (SUCCEEDED(hr)) { if (FAILED(hr = xpsFactory->CreatePartUri( fontPartName, &partUri))) { fwprintf(stderr, L"ERROR: Could not create part URI: %08X\n", hr); } } if (SUCCEEDED(hr)) { if (FAILED(hr = xpsFactory->CreateFontResource( fontStream, embedding, partUri, FALSE, fontResource ))) { fwprintf(stderr, L"ERROR: Could not create font resource: %08X\n", hr); } } if (fontStream) { fontStream->Release(); fontStream = NULL; } if (partUri) { partUri->Release(); partUri = NULL; } if (hGlobal) { GlobalFree(hGlobal); } if (hFont) { DeleteObject(hFont); } if (hDC) { DeleteDC(hDC); } return hr; }
// Load the sample assets. void D3D12DynamicIndexing::LoadAssets() { // Note: ComPtr's are CPU objects but these resources need to stay in scope until // the command list that references them has finished executing on the GPU. // We will flush the GPU at the end of this method to ensure the resources are not // prematurely destroyed. ComPtr<ID3D12Resource> vertexBufferUploadHeap; ComPtr<ID3D12Resource> indexBufferUploadHeap; ComPtr<ID3D12Resource> textureUploadHeap; ComPtr<ID3D12Resource> materialsUploadHeap; // Create the root signature. { CD3DX12_DESCRIPTOR_RANGE ranges[3]; ranges[0].Init(D3D12_DESCRIPTOR_RANGE_TYPE_SRV, 1 + CityMaterialCount, 0); // Diffuse texture + array of materials. ranges[1].Init(D3D12_DESCRIPTOR_RANGE_TYPE_SAMPLER, 1, 0); ranges[2].Init(D3D12_DESCRIPTOR_RANGE_TYPE_CBV, 1, 0); CD3DX12_ROOT_PARAMETER rootParameters[4]; rootParameters[0].InitAsDescriptorTable(1, &ranges[0], D3D12_SHADER_VISIBILITY_PIXEL); rootParameters[1].InitAsDescriptorTable(1, &ranges[1], D3D12_SHADER_VISIBILITY_PIXEL); rootParameters[2].InitAsDescriptorTable(1, &ranges[2], D3D12_SHADER_VISIBILITY_VERTEX); rootParameters[3].InitAsConstants(1, 0, 0, D3D12_SHADER_VISIBILITY_PIXEL); CD3DX12_ROOT_SIGNATURE_DESC rootSignatureDesc; rootSignatureDesc.Init(_countof(rootParameters), rootParameters, 0, nullptr, D3D12_ROOT_SIGNATURE_FLAG_ALLOW_INPUT_ASSEMBLER_INPUT_LAYOUT); ComPtr<ID3DBlob> signature; ComPtr<ID3DBlob> error; ThrowIfFailed(D3D12SerializeRootSignature(&rootSignatureDesc, D3D_ROOT_SIGNATURE_VERSION_1, &signature, &error)); ThrowIfFailed(m_device->CreateRootSignature(0, signature->GetBufferPointer(), signature->GetBufferSize(), IID_PPV_ARGS(&m_rootSignature))); NAME_D3D12_OBJECT(m_rootSignature); } // Create the pipeline state, which includes loading shaders. { UINT8* pVertexShaderData; UINT8* pPixelShaderData; UINT vertexShaderDataLength; UINT pixelShaderDataLength; ThrowIfFailed(ReadDataFromFile(GetAssetFullPath(L"shader_mesh_simple_vert.cso").c_str(), &pVertexShaderData, &vertexShaderDataLength)); ThrowIfFailed(ReadDataFromFile(GetAssetFullPath(L"shader_mesh_dynamic_indexing_pixel.cso").c_str(), &pPixelShaderData, &pixelShaderDataLength)); CD3DX12_RASTERIZER_DESC rasterizerStateDesc(D3D12_DEFAULT); rasterizerStateDesc.CullMode = D3D12_CULL_MODE_NONE; // Describe and create the graphics pipeline state object (PSO). D3D12_GRAPHICS_PIPELINE_STATE_DESC psoDesc = {}; psoDesc.InputLayout = { SampleAssets::StandardVertexDescription, SampleAssets::StandardVertexDescriptionNumElements }; psoDesc.pRootSignature = m_rootSignature.Get(); psoDesc.VS = CD3DX12_SHADER_BYTECODE(pVertexShaderData, vertexShaderDataLength); psoDesc.PS = CD3DX12_SHADER_BYTECODE(pPixelShaderData, pixelShaderDataLength); psoDesc.RasterizerState = rasterizerStateDesc; psoDesc.BlendState = CD3DX12_BLEND_DESC(D3D12_DEFAULT); psoDesc.DepthStencilState = CD3DX12_DEPTH_STENCIL_DESC(D3D12_DEFAULT); psoDesc.SampleMask = UINT_MAX; psoDesc.PrimitiveTopologyType = D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE; psoDesc.NumRenderTargets = 1; psoDesc.RTVFormats[0] = DXGI_FORMAT_R8G8B8A8_UNORM; psoDesc.DSVFormat = DXGI_FORMAT_D32_FLOAT; psoDesc.SampleDesc.Count = 1; ThrowIfFailed(m_device->CreateGraphicsPipelineState(&psoDesc, IID_PPV_ARGS(&m_pipelineState))); NAME_D3D12_OBJECT(m_pipelineState); delete pVertexShaderData; delete pPixelShaderData; } ThrowIfFailed(m_device->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, m_commandAllocator.Get(), nullptr, IID_PPV_ARGS(&m_commandList))); NAME_D3D12_OBJECT(m_commandList); // Create render target views (RTVs). CD3DX12_CPU_DESCRIPTOR_HANDLE rtvHandle(m_rtvHeap->GetCPUDescriptorHandleForHeapStart()); for (UINT i = 0; i < FrameCount; i++) { ThrowIfFailed(m_swapChain->GetBuffer(i, IID_PPV_ARGS(&m_renderTargets[i]))); m_device->CreateRenderTargetView(m_renderTargets[i].Get(), nullptr, rtvHandle); rtvHandle.Offset(1, m_rtvDescriptorSize); WCHAR name[25]; if (swprintf_s(name, L"m_renderTargets[%u]", i) > 0) { SetName(m_renderTargets[i].Get(), name); } } // Read in mesh data for vertex/index buffers. UINT8* pMeshData; UINT meshDataLength; ThrowIfFailed(ReadDataFromFile(GetAssetFullPath(SampleAssets::DataFileName).c_str(), &pMeshData, &meshDataLength)); // Create the vertex buffer. { ThrowIfFailed(m_device->CreateCommittedResource( &CD3DX12_HEAP_PROPERTIES(D3D12_HEAP_TYPE_DEFAULT), D3D12_HEAP_FLAG_NONE, &CD3DX12_RESOURCE_DESC::Buffer(SampleAssets::VertexDataSize), D3D12_RESOURCE_STATE_COPY_DEST, nullptr, IID_PPV_ARGS(&m_vertexBuffer))); ThrowIfFailed(m_device->CreateCommittedResource( &CD3DX12_HEAP_PROPERTIES(D3D12_HEAP_TYPE_UPLOAD), D3D12_HEAP_FLAG_NONE, &CD3DX12_RESOURCE_DESC::Buffer(SampleAssets::VertexDataSize), D3D12_RESOURCE_STATE_GENERIC_READ, nullptr, IID_PPV_ARGS(&vertexBufferUploadHeap))); NAME_D3D12_OBJECT(m_vertexBuffer); // Copy data to the intermediate upload heap and then schedule a copy // from the upload heap to the vertex buffer. D3D12_SUBRESOURCE_DATA vertexData = {}; vertexData.pData = pMeshData + SampleAssets::VertexDataOffset; vertexData.RowPitch = SampleAssets::VertexDataSize; vertexData.SlicePitch = vertexData.RowPitch; UpdateSubresources<1>(m_commandList.Get(), m_vertexBuffer.Get(), vertexBufferUploadHeap.Get(), 0, 0, 1, &vertexData); m_commandList->ResourceBarrier(1, &CD3DX12_RESOURCE_BARRIER::Transition(m_vertexBuffer.Get(), D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_VERTEX_AND_CONSTANT_BUFFER)); // Initialize the vertex buffer view. m_vertexBufferView.BufferLocation = m_vertexBuffer->GetGPUVirtualAddress(); m_vertexBufferView.StrideInBytes = SampleAssets::StandardVertexStride; m_vertexBufferView.SizeInBytes = SampleAssets::VertexDataSize; } // Create the index buffer. { ThrowIfFailed(m_device->CreateCommittedResource( &CD3DX12_HEAP_PROPERTIES(D3D12_HEAP_TYPE_DEFAULT), D3D12_HEAP_FLAG_NONE, &CD3DX12_RESOURCE_DESC::Buffer(SampleAssets::IndexDataSize), D3D12_RESOURCE_STATE_COPY_DEST, nullptr, IID_PPV_ARGS(&m_indexBuffer))); ThrowIfFailed(m_device->CreateCommittedResource( &CD3DX12_HEAP_PROPERTIES(D3D12_HEAP_TYPE_UPLOAD), D3D12_HEAP_FLAG_NONE, &CD3DX12_RESOURCE_DESC::Buffer(SampleAssets::IndexDataSize), D3D12_RESOURCE_STATE_GENERIC_READ, nullptr, IID_PPV_ARGS(&indexBufferUploadHeap))); NAME_D3D12_OBJECT(m_indexBuffer); // Copy data to the intermediate upload heap and then schedule a copy // from the upload heap to the index buffer. D3D12_SUBRESOURCE_DATA indexData = {}; indexData.pData = pMeshData + SampleAssets::IndexDataOffset; indexData.RowPitch = SampleAssets::IndexDataSize; indexData.SlicePitch = indexData.RowPitch; UpdateSubresources<1>(m_commandList.Get(), m_indexBuffer.Get(), indexBufferUploadHeap.Get(), 0, 0, 1, &indexData); m_commandList->ResourceBarrier(1, &CD3DX12_RESOURCE_BARRIER::Transition(m_indexBuffer.Get(), D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_INDEX_BUFFER)); // Describe the index buffer view. m_indexBufferView.BufferLocation = m_indexBuffer->GetGPUVirtualAddress(); m_indexBufferView.Format = SampleAssets::StandardIndexFormat; m_indexBufferView.SizeInBytes = SampleAssets::IndexDataSize; m_numIndices = SampleAssets::IndexDataSize / 4; // R32_UINT (SampleAssets::StandardIndexFormat) = 4 bytes each. } // Create the textures and sampler. { // Procedurally generate an array of textures to use as city materials. { // All of these materials use the same texture desc. D3D12_RESOURCE_DESC textureDesc = {}; textureDesc.MipLevels = 1; textureDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM; textureDesc.Width = CityMaterialTextureWidth; textureDesc.Height = CityMaterialTextureHeight; textureDesc.Flags = D3D12_RESOURCE_FLAG_NONE; textureDesc.DepthOrArraySize = 1; textureDesc.SampleDesc.Count = 1; textureDesc.SampleDesc.Quality = 0; textureDesc.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D; // The textures evenly span the color rainbow so that each city gets // a different material. float materialGradStep = (1.0f / static_cast<float>(CityMaterialCount)); // Generate texture data. std::vector<std::vector<unsigned char>> cityTextureData; cityTextureData.resize(CityMaterialCount); for (int i = 0; i < CityMaterialCount; ++i) { ThrowIfFailed(m_device->CreateCommittedResource( &CD3DX12_HEAP_PROPERTIES(D3D12_HEAP_TYPE_DEFAULT), D3D12_HEAP_FLAG_NONE, &textureDesc, D3D12_RESOURCE_STATE_COPY_DEST, nullptr, IID_PPV_ARGS(&m_cityMaterialTextures[i]))); WCHAR name[35]; if (swprintf_s(name, L"m_cityMaterialTextures[%u]", i) > 0) { SetName(m_cityMaterialTextures[i].Get(), name); } // Fill the texture. float t = i * materialGradStep; cityTextureData[i].resize(CityMaterialTextureWidth * CityMaterialTextureHeight * CityMaterialTextureChannelCount); for (int x = 0; x < CityMaterialTextureWidth; ++x) { for (int y = 0; y < CityMaterialTextureHeight; ++y) { // Compute the appropriate index into the buffer based on the x/y coordinates. int pixelIndex = (y * CityMaterialTextureChannelCount * CityMaterialTextureWidth) + (x * CityMaterialTextureChannelCount); // Determine this row's position along the rainbow gradient. float tPrime = t + ((static_cast<float>(y) / static_cast<float>(CityMaterialTextureHeight)) * materialGradStep); // Compute the RGB value for this position along the rainbow // and pack the pixel value. XMVECTOR hsl = XMVectorSet(tPrime, 0.5f, 0.5f, 1.0f); XMVECTOR rgb = XMColorHSLToRGB(hsl); cityTextureData[i][pixelIndex + 0] = static_cast<unsigned char>((255 * XMVectorGetX(rgb))); cityTextureData[i][pixelIndex + 1] = static_cast<unsigned char>((255 * XMVectorGetY(rgb))); cityTextureData[i][pixelIndex + 2] = static_cast<unsigned char>((255 * XMVectorGetZ(rgb))); cityTextureData[i][pixelIndex + 3] = 255; } } } // Upload texture data to the default heap resources. { const UINT subresourceCount = textureDesc.DepthOrArraySize * textureDesc.MipLevels; const UINT64 uploadBufferStep = GetRequiredIntermediateSize(m_cityMaterialTextures[0].Get(), 0, subresourceCount); // All of our textures are the same size in this case. const UINT64 uploadBufferSize = uploadBufferStep * CityMaterialCount; ThrowIfFailed(m_device->CreateCommittedResource( &CD3DX12_HEAP_PROPERTIES(D3D12_HEAP_TYPE_UPLOAD), D3D12_HEAP_FLAG_NONE, &CD3DX12_RESOURCE_DESC::Buffer(uploadBufferSize), D3D12_RESOURCE_STATE_GENERIC_READ, nullptr, IID_PPV_ARGS(&materialsUploadHeap))); for (int i = 0; i < CityMaterialCount; ++i) { // Copy data to the intermediate upload heap and then schedule // a copy from the upload heap to the appropriate texture. D3D12_SUBRESOURCE_DATA textureData = {}; textureData.pData = &cityTextureData[i][0]; textureData.RowPitch = static_cast<LONG_PTR>((CityMaterialTextureChannelCount * textureDesc.Width)); textureData.SlicePitch = textureData.RowPitch * textureDesc.Height; UpdateSubresources(m_commandList.Get(), m_cityMaterialTextures[i].Get(), materialsUploadHeap.Get(), i * uploadBufferStep, 0, subresourceCount, &textureData); m_commandList->ResourceBarrier(1, &CD3DX12_RESOURCE_BARRIER::Transition(m_cityMaterialTextures[i].Get(), D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE)); } } } // Load the occcity diffuse texture with baked-in ambient lighting. // This texture will be blended with a texture from the materials // array in the pixel shader. { D3D12_RESOURCE_DESC textureDesc = {}; textureDesc.MipLevels = SampleAssets::Textures[0].MipLevels; textureDesc.Format = SampleAssets::Textures[0].Format; textureDesc.Width = SampleAssets::Textures[0].Width; textureDesc.Height = SampleAssets::Textures[0].Height; textureDesc.Flags = D3D12_RESOURCE_FLAG_NONE; textureDesc.DepthOrArraySize = 1; textureDesc.SampleDesc.Count = 1; textureDesc.SampleDesc.Quality = 0; textureDesc.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D; ThrowIfFailed(m_device->CreateCommittedResource( &CD3DX12_HEAP_PROPERTIES(D3D12_HEAP_TYPE_DEFAULT), D3D12_HEAP_FLAG_NONE, &textureDesc, D3D12_RESOURCE_STATE_COPY_DEST, nullptr, IID_PPV_ARGS(&m_cityDiffuseTexture))); const UINT subresourceCount = textureDesc.DepthOrArraySize * textureDesc.MipLevels; const UINT64 uploadBufferSize = GetRequiredIntermediateSize(m_cityDiffuseTexture.Get(), 0, subresourceCount); ThrowIfFailed(m_device->CreateCommittedResource( &CD3DX12_HEAP_PROPERTIES(D3D12_HEAP_TYPE_UPLOAD), D3D12_HEAP_FLAG_NONE, &CD3DX12_RESOURCE_DESC::Buffer(uploadBufferSize), D3D12_RESOURCE_STATE_GENERIC_READ, nullptr, IID_PPV_ARGS(&textureUploadHeap))); NAME_D3D12_OBJECT(m_cityDiffuseTexture); // Copy data to the intermediate upload heap and then schedule // a copy from the upload heap to the diffuse texture. D3D12_SUBRESOURCE_DATA textureData = {}; textureData.pData = pMeshData + SampleAssets::Textures[0].Data[0].Offset; textureData.RowPitch = SampleAssets::Textures[0].Data[0].Pitch; textureData.SlicePitch = SampleAssets::Textures[0].Data[0].Size; UpdateSubresources(m_commandList.Get(), m_cityDiffuseTexture.Get(), textureUploadHeap.Get(), 0, 0, subresourceCount, &textureData); m_commandList->ResourceBarrier(1, &CD3DX12_RESOURCE_BARRIER::Transition(m_cityDiffuseTexture.Get(), D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE)); } // Describe and create a sampler. D3D12_SAMPLER_DESC samplerDesc = {}; samplerDesc.Filter = D3D12_FILTER_MIN_MAG_MIP_LINEAR; samplerDesc.AddressU = D3D12_TEXTURE_ADDRESS_MODE_WRAP; samplerDesc.AddressV = D3D12_TEXTURE_ADDRESS_MODE_WRAP; samplerDesc.AddressW = D3D12_TEXTURE_ADDRESS_MODE_WRAP; samplerDesc.MinLOD = 0; samplerDesc.MaxLOD = D3D12_FLOAT32_MAX; samplerDesc.MipLODBias = 0.0f; samplerDesc.MaxAnisotropy = 1; samplerDesc.ComparisonFunc = D3D12_COMPARISON_FUNC_ALWAYS; m_device->CreateSampler(&samplerDesc, m_samplerHeap->GetCPUDescriptorHandleForHeapStart()); // Create SRV for the city's diffuse texture. CD3DX12_CPU_DESCRIPTOR_HANDLE srvHandle(m_cbvSrvHeap->GetCPUDescriptorHandleForHeapStart(), 0, m_cbvSrvDescriptorSize); D3D12_SHADER_RESOURCE_VIEW_DESC diffuseSrvDesc = {}; diffuseSrvDesc.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING; diffuseSrvDesc.Format = SampleAssets::Textures->Format; diffuseSrvDesc.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE2D; diffuseSrvDesc.Texture2D.MipLevels = 1; m_device->CreateShaderResourceView(m_cityDiffuseTexture.Get(), &diffuseSrvDesc, srvHandle); srvHandle.Offset(m_cbvSrvDescriptorSize); // Create SRVs for each city material. for (int i = 0; i < CityMaterialCount; ++i) { D3D12_SHADER_RESOURCE_VIEW_DESC materialSrvDesc = {}; materialSrvDesc.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING; materialSrvDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM; materialSrvDesc.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE2D; materialSrvDesc.Texture2D.MipLevels = 1; m_device->CreateShaderResourceView(m_cityMaterialTextures[i].Get(), &materialSrvDesc, srvHandle); srvHandle.Offset(m_cbvSrvDescriptorSize); } } delete pMeshData; // Create the depth stencil view. { D3D12_DEPTH_STENCIL_VIEW_DESC depthStencilDesc = {}; depthStencilDesc.Format = DXGI_FORMAT_D32_FLOAT; depthStencilDesc.ViewDimension = D3D12_DSV_DIMENSION_TEXTURE2D; depthStencilDesc.Flags = D3D12_DSV_FLAG_NONE; D3D12_CLEAR_VALUE depthOptimizedClearValue = {}; depthOptimizedClearValue.Format = DXGI_FORMAT_D32_FLOAT; depthOptimizedClearValue.DepthStencil.Depth = 1.0f; depthOptimizedClearValue.DepthStencil.Stencil = 0; ThrowIfFailed(m_device->CreateCommittedResource( &CD3DX12_HEAP_PROPERTIES(D3D12_HEAP_TYPE_DEFAULT), D3D12_HEAP_FLAG_NONE, &CD3DX12_RESOURCE_DESC::Tex2D(DXGI_FORMAT_D32_FLOAT, m_width, m_height, 1, 0, 1, 0, D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL), D3D12_RESOURCE_STATE_DEPTH_WRITE, &depthOptimizedClearValue, IID_PPV_ARGS(&m_depthStencil) )); NAME_D3D12_OBJECT(m_depthStencil); m_device->CreateDepthStencilView(m_depthStencil.Get(), &depthStencilDesc, m_dsvHeap->GetCPUDescriptorHandleForHeapStart()); } // Close the command list and execute it to begin the initial GPU setup. ThrowIfFailed(m_commandList->Close()); ID3D12CommandList* ppCommandLists[] = { m_commandList.Get() }; m_commandQueue->ExecuteCommandLists(_countof(ppCommandLists), ppCommandLists); CreateFrameResources(); // Create synchronization objects and wait until assets have been uploaded to the GPU. { ThrowIfFailed(m_device->CreateFence(m_fenceValue, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&m_fence))); m_fenceValue++; // Create an event handle to use for frame synchronization. m_fenceEvent = CreateEvent(nullptr, FALSE, FALSE, nullptr); if (m_fenceEvent == nullptr) { ThrowIfFailed(HRESULT_FROM_WIN32(GetLastError())); } // Wait for the command list to execute; we are reusing the same command // list in our main loop but for now, we just want to wait for setup to // complete before continuing. // Signal and increment the fence value. const UINT64 fenceToWaitFor = m_fenceValue; ThrowIfFailed(m_commandQueue->Signal(m_fence.Get(), fenceToWaitFor)); m_fenceValue++; // Wait until the fence is completed. ThrowIfFailed(m_fence->SetEventOnCompletion(fenceToWaitFor, m_fenceEvent)); WaitForSingleObject(m_fenceEvent, INFINITE); } }
// HANDLE VwCreateWin( // VApiHandle hWndParent, int X, int Y, int nWidth, int nHeight, // WCHAR* wszRegName, WCHAR* wszNewName, BOOL bIsAlpha) SQInteger VwCreateWin(HSQUIRRELVM v) { SQInteger nargs = sq_gettop(v); SQInteger nWndParent = 0; HWND hWndParent = NULL; CUIImage* pImg = NULL; CScriptMgr* pMgr = NULL; CPaintManagerUI* pPM = NULL; int X = 0; int Y = 0; int nWidth = 0; int nHeight = 0; const SQChar* pwszRegName = NULL; const SQChar* pwszNewName = NULL; WCHAR wszNewName[60] = {0}; SQBool bIsAlphaWin = NULL; WinMgrItem* pWinMgrIt = NULL; HWND hWnd = NULL; CWindowWnd* pWinObj = NULL; SQInteger nRet = 0; CMarkupNode* pRootXm = NULL; if (!v || 8 + 1 != nargs) {goto _Exit_;} if (OT_INTEGER != sq_gettype(v, 2)) {goto _Exit_;} if (OT_INTEGER != sq_gettype(v, 3)) {goto _Exit_;} if (OT_INTEGER != sq_gettype(v, 4)) {goto _Exit_;} if (OT_INTEGER != sq_gettype(v, 5)) {goto _Exit_;} if (OT_INTEGER != sq_gettype(v, 6)) {goto _Exit_;} if (OT_STRING != sq_gettype(v, 7)) {goto _Exit_;} if (OT_STRING != sq_gettype(v, 8)) {goto _Exit_;} if (OT_BOOL != sq_gettype(v, 9)) {goto _Exit_;} sq_getinteger(v, 2, &nWndParent); sq_getinteger(v, 3, &X); sq_getinteger(v, 4, &Y); sq_getinteger(v, 5, &nWidth); sq_getinteger(v, 6, &nHeight); sq_getstring(v, 7, &pwszRegName); //sq_getinteger(v, 8, &wszNewName); sq_getbool(v, 9, &bIsAlphaWin); swprintf_s(wszNewName, 60, L"%x", ::GetTickCount()); if (nWndParent) { hWndParent = QiHwHandleToWin(nWndParent)->pWinObj->GetHWND(); } pMgr = (CScriptMgr*)sq_getforeignptr(v); if (!pMgr) {goto _Exit_;} pPM = pMgr->GetManager(); if (!pPM || !pPM->GetWinMgr()) {goto _Exit_;} pWinMgrIt = pPM->GetWinMgr()->FindWinByName(pwszRegName); if (!pWinMgrIt) {goto _Exit_;} // 新建立个模板,因为需要可重复用以前的名字 pRootXm = new CMarkupNode(*pWinMgrIt->pWinXML); pWinObj = new CWindowTemplate(pWinMgrIt->pWinObj); pWinObj->GetPM()->SetWinMgr(pPM->GetWinMgr()); pWinObj->SetDefaultResource(pRootXm); pWinMgrIt = pPM->GetWinMgr()->AddOneWin(pWinObj, wszNewName, pRootXm, X, Y, nWidth, nHeight, pWinMgrIt->dwStyle, pWinMgrIt->dwExStyle, &pWinMgrIt->ExInfo); if (!bIsAlphaWin) { hWnd = pWinObj->Create(hWndParent, pwszNewName, pWinMgrIt->dwStyle, pWinMgrIt->dwExStyle, X, Y, nWidth, nHeight, 0); } else { hWnd = pWinObj->CreateAlphaWin(hWndParent, pwszNewName, pWinMgrIt->dwStyle | WS_EX_LAYERED, pWinMgrIt->dwExStyle, X, Y, nWidth, nHeight); } if (!hWnd) {goto _Exit_;} nRet = QiHwObjToHandle(pWinMgrIt); _Exit_: sq_pushinteger(v, nRet); return 1; }
void StepOneThreadSuite::RunDebuggee( Step* steps, int stepsCount ) { Exec exec; TEST_ASSERT_RETURN( SUCCEEDED( exec.Init( mCallback ) ) ); LaunchInfo info = { 0 }; wchar_t cmdLine[ MAX_PATH ] = L""; IProcess* proc = NULL; const wchar_t* Debuggee = StepOneThreadDebuggee; swprintf_s( cmdLine, L"\"%s\" 1", Debuggee ); info.CommandLine = cmdLine; info.Exe = Debuggee; TEST_ASSERT_RETURN( SUCCEEDED( exec.Launch( &info, proc ) ) ); uint32_t pid = proc->GetId(); int nextStep = 0; char msg[1024] = ""; RefPtr<IProcess> process; process = proc; proc->Release(); mCallback->SetTrackLastEvent( true ); for ( int i = 0; !mCallback->GetProcessExited(); i++ ) { bool continued = false; HRESULT hr = exec.WaitForEvent( DefaultTimeoutMillis ); // this should happen after process exit if ( hr == E_TIMEOUT ) break; TEST_ASSERT_RETURN( SUCCEEDED( hr ) ); TEST_ASSERT_RETURN( SUCCEEDED( hr = exec.DispatchEvent() ) ); if ( !process->IsStopped() ) continue; if ( (mCallback->GetLastEvent()->Code != ExecEvent_ModuleLoad) && (mCallback->GetLastEvent()->Code != ExecEvent_ModuleUnload) && (mCallback->GetLastEvent()->Code != ExecEvent_ThreadStart) && (mCallback->GetLastEvent()->Code != ExecEvent_ThreadExit) && (mCallback->GetLastEvent()->Code != ExecEvent_LoadComplete) ) { Step* curStep = &steps[nextStep]; nextStep++; RefPtr<Thread> thread; CONTEXT_X86 context = { 0 }; if ( mCallback->GetLastThreadId() != 0 ) { TEST_ASSERT_RETURN( process->FindThread( mCallback->GetLastThreadId(), thread.Ref() ) ); TEST_ASSERT_RETURN( exec.GetThreadContext( process, thread->GetId(), CONTEXT_X86_FULL, 0, &context, sizeof context ) == S_OK ); } uintptr_t baseAddr = 0; RefPtr<IModule> procMod = mCallback->GetProcessModule(); if ( procMod.Get() != NULL ) baseAddr = (uintptr_t) procMod->GetImageBase(); // TODO: test threadId if ( mCallback->GetLastEvent()->Code != curStep->Event.Code ) { sprintf_s( msg, "Expected event '%s', got '%s'.", GetEventName( curStep->Event.Code ), GetEventName( mCallback->GetLastEvent()->Code ) ); TEST_FAIL_MSG( msg ); break; } else if ( (curStep->Event.Code == ExecEvent_Exception) && (curStep->Event.ExceptionCode != ((ExceptionEventNode*) mCallback->GetLastEvent().get())->Exception.ExceptionCode) ) { sprintf_s( msg, "Expected exception %08x, got %08x.", curStep->Event.ExceptionCode, ((ExceptionEventNode*) mCallback->GetLastEvent().get())->Exception.ExceptionCode ); TEST_FAIL_MSG( msg ); break; } else if ( (curStep->Event.Code == ExecEvent_Exception) || (curStep->Event.Code == ExecEvent_StepComplete) || (curStep->Event.Code == ExecEvent_Breakpoint) ) { uintptr_t addr = (curStep->Event.AddressOffset + baseAddr); if ( context.Eip != addr ) { sprintf_s( msg, "Expected instruction pointer at %p, got %08x.", addr, context.Eip ); TEST_FAIL_MSG( msg ); break; } } mCallback->SetCanStepInFunctionReturnValue( curStep->Action.CanStepInFunction ); if ( curStep->Action.BPAddressOffset != 0 ) { uintptr_t addr = (curStep->Action.BPAddressOffset + baseAddr); TEST_ASSERT_RETURN( SUCCEEDED( exec.SetBreakpoint( process.Get(), addr ) ) ); } if ( curStep->Action.Action == Action_StepInstruction ) { TEST_ASSERT_RETURN( SUCCEEDED( exec.StepInstruction( process.Get(), curStep->Action.StepIn, true ) ) ); continued = true; } else if ( curStep->Action.Action == Action_StepRange ) { AddressRange range = { context.Eip, context.Eip }; TEST_ASSERT_RETURN( SUCCEEDED( exec.StepRange( process.Get(), curStep->Action.StepIn, range, true ) ) ); continued = true; } } if ( !continued ) TEST_ASSERT_RETURN( SUCCEEDED( exec.Continue( process, true ) ) ); } TEST_ASSERT( mCallback->GetLoadCompleted() ); TEST_ASSERT( mCallback->GetProcessExited() ); }
void Direct3DRender(HWND hwnd) { RECT formatRect; GetClientRect(hwnd, &formatRect); gPD3DDevice->Clear(0, nullptr, D3DCLEAR_TARGET | D3DCLEAR_ZBUFFER, D3DCOLOR_XRGB(0,0, 30), 1.0f, 0.0f); gPD3DDevice->BeginScene(); MatrixSet(); WCHAR str[50]; int strCount = swprintf_s(str, _T("Mat, Mesh & Light!")); gPFont->DrawTextW(nullptr, str, strCount, &formatRect, DT_TOP| DT_RIGHT, D3DCOLOR_XRGB(25, 134, 111)); D3DXMATRIX Ry; D3DXMatrixRotationY(&Ry, timeGetTime() / 1000.0f); D3DXMATRIX teaPotWorldTrans; D3DXMatrixTranslation(&teaPotWorldTrans, 2.5f, 2.5f, 2.5f); D3DXMATRIX Sa; D3DXMatrixScaling(&Sa, 2.0f, 2.0f, 2.0f); teaPotWorldTrans = teaPotWorldTrans * Ry * Sa; gPD3DDevice->SetTransform(D3DTS_WORLD, &teaPotWorldTrans); D3DMATERIAL9 material; ZeroMemory(&material, sizeof(material)); material.Ambient = D3DXCOLOR(0.5f, 0.5f, 0.7f, 1.0f); material.Diffuse = D3DXCOLOR(0.4f, 0.6f, 0.6f, 1.0f); material.Specular = D3DXCOLOR(0.3f, 0.3f, 0.3f, 0.3f); material.Emissive = D3DXCOLOR(0.3f, 0.0f, 0.1f, 1.0f); gPD3DDevice->SetMaterial(&material); gPTeapot->DrawSubset(0); D3DXMATRIX boxWorldTrans; D3DXMatrixTranslation(&boxWorldTrans, -5.0f, 5.0f, 5.0f); boxWorldTrans *= Ry; gPD3DDevice->SetTransform(D3DTS_WORLD, &boxWorldTrans); ZeroMemory(&material, sizeof(material)); material.Ambient = D3DXCOLOR(0.3f, 0.1f, 0.5f, 1.0f); material.Diffuse = D3DXCOLOR(0.4f, 0.6f, 0.6f, 1.0f); material.Specular = D3DXCOLOR(0.3f, 0.3f, 0.3f, 1.3f); material.Emissive = D3DXCOLOR(0.3f, 0.0f, 0.1f, 1.0f); gPD3DDevice->SetMaterial(&material); gPBox->DrawSubset(0); D3DXMATRIX torusWorldTrans; D3DXMatrixTranslation(&torusWorldTrans, 5.0f, -5.0f, 5.0f); torusWorldTrans *= Ry; gPD3DDevice->SetTransform(D3DTS_WORLD, &torusWorldTrans); ZeroMemory(&material, sizeof(material)); material.Ambient = D3DXCOLOR(0.5f, 0.2f, 0.3f, 1.0f); material.Diffuse = D3DXCOLOR(0.6f, 0.2f, 0.4f, 1.0f); material.Specular = D3DXCOLOR(0.3f, 0.3f, 0.3f, 0.3f); material.Emissive = D3DXCOLOR(0.3f, 0.0f, 0.1f, 1.0f); gPD3DDevice->SetMaterial(&material); gPTorus->DrawSubset(0); D3DXMATRIX sphereWorldTrans; D3DXMatrixTranslation(&sphereWorldTrans, -5.0f, -5.0f, 5.0f); sphereWorldTrans *= Ry; gPD3DDevice->SetTransform(D3DTS_WORLD, &sphereWorldTrans); ZeroMemory(&material, sizeof(material)); material.Ambient = D3DXCOLOR(0.9f, 0.1f, 0.9f, 1.0f); material.Diffuse = D3DXCOLOR(0.3f, 0.6f, 0.8f, 1.0f); material.Specular = D3DXCOLOR(0.3f, 0.3f, 0.3f, 0.3f); material.Emissive = D3DXCOLOR(0.9f, 0.4f, 0.7f, 1.0f); gPD3DDevice->SetMaterial(&material); gPSphere->DrawSubset(0); LightSet(gPD3DDevice, 1); gPD3DDevice->EndScene(); gPD3DDevice->Present(nullptr, nullptr, nullptr, nullptr); }
HRESULT FindAttributesOrClasses(IDirectorySearch *pSchemaNC, //IDirectorySearch pointer to schema naming context. LPOLESTR szFilter, //Filter for finding specific attributes. //NULL returns all attributeSchema objects. LPOLESTR *pszPropertiesToReturn, //Properties to return for attributeSchema objects found //NULL returns all set properties unless bIsVerbose is FALSE. BOOL bIsAttributeQuery, //TRUE queries for attributes;FALSE for classes BOOL bIsVerbose //TRUE means all properties for the found objects are displayed. //FALSE means only the ldapDisplayName with cn in parentheses: //example: l (Locality-Name) ) { if (!pSchemaNC) return E_POINTER; //Create search filter int allocFilter = MAX_PATH*2; LPOLESTR pszSearchFilter = new OLECHAR[allocFilter]; if ( !pszSearchFilter ) { delete [] pszSearchFilter; return E_OUTOFMEMORY; } LPOLESTR szCategory = NULL; if (bIsAttributeQuery) szCategory = L"attributeSchema"; else szCategory = L"classSchema"; wcscpy_s(pszSearchFilter, allocFilter, L"(&(objectCategory=attributeSchema)%s)"); BOOL bBufferOK=false; // Check for buffer overrun... if (szFilter) { if ( IS_BUFFER_ENOUGH(allocFilter,pszSearchFilter, szCategory) > 0 ) { swprintf_s(pszSearchFilter, allocFilter, L"(&(objectCategory=%s)%s)",szCategory,szFilter); bBufferOK=true; } } else { if ( IS_BUFFER_ENOUGH(allocFilter,pszSearchFilter, szCategory) > 0 ) { swprintf_s(pszSearchFilter, allocFilter,L"(objectCategory=%s)",szCategory); bBufferOK=true; } } if( !bBufferOK) { delete [] pszSearchFilter; wprintf(L"Filter is too large - aborting"); return E_FAIL; } //Attributes are one-level deep in the Schema container so only need to search one level. ADS_SEARCHPREF_INFO SearchPrefs; SearchPrefs.dwSearchPref = ADS_SEARCHPREF_SEARCH_SCOPE; SearchPrefs.vValue.dwType = ADSTYPE_INTEGER; SearchPrefs.vValue.Integer = ADS_SCOPE_ONELEVEL; DWORD dwNumPrefs = 1; // COL for iterations LPOLESTR pszColumn = NULL; ADS_SEARCH_COLUMN col; HRESULT hr; // Interface Pointers IADs *pObj = NULL; IADs * pIADs = NULL; // Handle used for searching ADS_SEARCH_HANDLE hSearch = NULL; // Set the search preference hr = pSchemaNC->SetSearchPreference( &SearchPrefs, dwNumPrefs); if (FAILED(hr)) return hr; LPOLESTR pszBool = NULL; DWORD dwBool; PSID pObjectSID = NULL; LPOLESTR szSID = NULL; LPGUID pObjectGUID = NULL; FILETIME filetime; SYSTEMTIME systemtime; DATE date; VARIANT varDate; LARGE_INTEGER liValue; LPOLESTR *pszPropertyList = NULL; LPOLESTR pszNonVerboseList[] = {L"lDAPDisplayName",L"cn"}; LPOLESTR szCNValue = new OLECHAR[MAX_PATH]; LPOLESTR szLDAPDispleyNameValue = new OLECHAR[MAX_PATH]; LPOLESTR szDSGUID = new WCHAR [39]; if ( !szCNValue || !szLDAPDispleyNameValue || !szDSGUID ) { if ( szDSGUID ) delete [] szDSGUID; if ( szCNValue ) delete [] szCNValue; if ( szLDAPDispleyNameValue ) delete [] szLDAPDispleyNameValue; if ( pszSearchFilter ) delete [] pszSearchFilter; return E_OUTOFMEMORY; } int iCount = 0; DWORD x = 0L; if (!bIsVerbose) { //Return non-verbose list properties only hr = pSchemaNC->ExecuteSearch(pszSearchFilter, pszNonVerboseList, sizeof(pszNonVerboseList)/sizeof(LPOLESTR), &hSearch ); } else { if (!pszPropertiesToReturn) { //Return all properties. hr = pSchemaNC->ExecuteSearch(pszSearchFilter, NULL, 0L, &hSearch ); } else { //specified subset. pszPropertyList = pszPropertiesToReturn; //Return specified properties hr = pSchemaNC->ExecuteSearch(pszSearchFilter, pszPropertyList, sizeof(pszPropertyList)/sizeof(LPOLESTR), &hSearch ); } } if ( SUCCEEDED(hr) ) { // Call IDirectorySearch::GetNextRow() to retrieve the next row //of data hr = pSchemaNC->GetFirstRow( hSearch); if (SUCCEEDED(hr)) { while( hr != S_ADS_NOMORE_ROWS ) { //Keep track of count. iCount++; if (bIsVerbose) wprintf(L"----------------------------------\n"); // loop through the array of passed column names, // print the data for each column while( pSchemaNC->GetNextColumnName( hSearch, &pszColumn ) != S_ADS_NOMORE_COLUMNS ) { hr = pSchemaNC->GetColumn( hSearch, pszColumn, &col ); if ( SUCCEEDED(hr) ) { // Print the data for the column and free the column if(bIsVerbose) { // Get the data for this column wprintf(L"%s\n",col.pszAttrName); switch (col.dwADsType) { case ADSTYPE_DN_STRING: for (x = 0; x< col.dwNumValues; x++) { wprintf(L" %s\r\n",col.pADsValues[x].DNString); } break; case ADSTYPE_CASE_EXACT_STRING: case ADSTYPE_CASE_IGNORE_STRING: case ADSTYPE_PRINTABLE_STRING: case ADSTYPE_NUMERIC_STRING: case ADSTYPE_TYPEDNAME: case ADSTYPE_FAXNUMBER: case ADSTYPE_PATH: case ADSTYPE_OBJECT_CLASS: for (x = 0; x< col.dwNumValues; x++) { wprintf(L" %s\r\n",col.pADsValues[x].CaseIgnoreString); } break; case ADSTYPE_BOOLEAN: for (x = 0; x< col.dwNumValues; x++) { dwBool = col.pADsValues[x].Boolean; pszBool = dwBool ? L"TRUE" : L"FALSE"; wprintf(L" %s\r\n",pszBool); } break; case ADSTYPE_INTEGER: for (x = 0; x< col.dwNumValues; x++) { wprintf(L" %d\r\n",col.pADsValues[x].Integer); } break; case ADSTYPE_OCTET_STRING: if ( _wcsicmp(col.pszAttrName,L"objectSID") == 0 ) { for (x = 0; x< col.dwNumValues; x++) { pObjectSID = (PSID)(col.pADsValues[x].OctetString.lpValue); //Convert SID to string. ConvertSidToStringSid(pObjectSID, &szSID); wprintf(L" %s\r\n",szSID); LocalFree(szSID); } } else if ( (_wcsicmp(col.pszAttrName,L"objectGUID") == 0) || (_wcsicmp(col.pszAttrName,L"schemaIDGUID") == 0) || (_wcsicmp(col.pszAttrName,L"attributeSecurityGUID") == 0) ) { for (x = 0; x< col.dwNumValues; x++) { //Cast to LPGUID pObjectGUID = (LPGUID)(col.pADsValues[x].OctetString.lpValue); //Convert GUID to string. ::StringFromGUID2(*pObjectGUID, szDSGUID, 39); //Print the GUID wprintf(L" %s\r\n",szDSGUID); } } else if ( _wcsicmp(col.pszAttrName,L"oMObjectClass") == 0 ) { //TODO: wprintf(L" TODO:No conversion for this."); } else wprintf(L" Value of type Octet String. No Conversion."); break; case ADSTYPE_UTC_TIME: for (x = 0; x< col.dwNumValues; x++) { systemtime = col.pADsValues[x].UTCTime; if (SystemTimeToVariantTime(&systemtime, &date) != 0) { //Pack in variant.vt varDate.vt = VT_DATE; varDate.date = date; VariantChangeType(&varDate,&varDate,VARIANT_NOVALUEPROP,VT_BSTR); wprintf(L" %s\r\n",varDate.bstrVal); VariantClear(&varDate); } else wprintf(L" Could not convert UTC-Time.\n"); } break; case ADSTYPE_LARGE_INTEGER: for (x = 0; x< col.dwNumValues; x++) { liValue = col.pADsValues[x].LargeInteger; filetime.dwLowDateTime = liValue.LowPart; filetime.dwHighDateTime = liValue.HighPart; if((filetime.dwHighDateTime==0) && (filetime.dwLowDateTime==0)) { wprintf(L" No value set.\n"); } else { //Check for properties of type LargeInteger that represent time //if TRUE, then convert to variant time. if ((0==wcscmp(L"accountExpires", col.pszAttrName))| (0==wcscmp(L"badPasswordTime", col.pszAttrName))|| (0==wcscmp(L"lastLogon", col.pszAttrName))|| (0==wcscmp(L"lastLogoff", col.pszAttrName))|| (0==wcscmp(L"lockoutTime", col.pszAttrName))|| (0==wcscmp(L"pwdLastSet", col.pszAttrName)) ) { //Handle special case for Never Expires where low part is -1 if (filetime.dwLowDateTime==-1) { wprintf(L" Never Expires.\n"); } else { if (FileTimeToLocalFileTime(&filetime, &filetime) != 0) { if (FileTimeToSystemTime(&filetime, &systemtime) != 0) { if (SystemTimeToVariantTime(&systemtime, &date) != 0) { //Pack in variant.vt varDate.vt = VT_DATE; varDate.date = date; VariantChangeType(&varDate,&varDate,VARIANT_NOVALUEPROP,VT_BSTR); wprintf(L" %s\r\n",varDate.bstrVal); VariantClear(&varDate); } else { wprintf(L" FileTimeToVariantTime failed\n"); } } else { wprintf(L" FileTimeToSystemTime failed\n"); } } else { wprintf(L" FileTimeToLocalFileTime failed\n"); } } } else { //Print the LargeInteger. wprintf(L" high: %d low: %d\r\n",filetime.dwHighDateTime, filetime.dwLowDateTime); } } } break; case ADSTYPE_NT_SECURITY_DESCRIPTOR: for (x = 0; x< col.dwNumValues; x++) { wprintf(L" Security descriptor.\n"); } break; default: wprintf(L"Unknown type %d.\n",col.dwADsType); } } else { //Verbose handles only the two single-valued attributes: cn and ldapdisplayname //so this is a special case. if (0==wcscmp(L"cn", pszColumn)) { wcscpy_s(szCNValue,MAX_PATH,col.pADsValues->CaseIgnoreString); } if (0==wcscmp(L"lDAPDisplayName", pszColumn)) { wcscpy_s(szLDAPDispleyNameValue,MAX_PATH,col.pADsValues->CaseIgnoreString); } } pSchemaNC->FreeColumn( &col ); } FreeADsMem( pszColumn ); } if (!bIsVerbose) wprintf(L"%s (%s)\n",szLDAPDispleyNameValue,szCNValue); //Get the next row hr = pSchemaNC->GetNextRow( hSearch); } } // Close the search handle to clean up pSchemaNC->CloseSearchHandle(hSearch); } if (SUCCEEDED(hr) && 0==iCount) hr = S_FALSE; delete [] szDSGUID; delete [] szCNValue; delete [] szLDAPDispleyNameValue; delete [] pszSearchFilter; return hr; }
int CRdbIniFile::WriteRdbIniFile( WINPOS* srcwinpos ) { m_mode = XMLIO_WRITE; MoveMemory( m_winpos, srcwinpos, sizeof( WINPOS ) * WINPOS_MAX ); WCHAR strpath[MAX_PATH]; swprintf_s( strpath, MAX_PATH, L"%sOpenRDB.ini", g_mediadir ); m_hfile = CreateFile( strpath, GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_ALWAYS, FILE_FLAG_SEQUENTIAL_SCAN, NULL ); if( m_hfile == INVALID_HANDLE_VALUE ){ DbgOut( L"RdbIniFile : WriteRdbIniFile : file open error !!!\n" ); _ASSERT( 0 ); return 1; } CallF( Write2File( "<?xml version=\"1.0\" encoding=\"Shift_JIS\"?>\r\n<RDBINI>\r\n" ), return 1 ); int kind; for( kind = WINPOS_3D; kind < WINPOS_MAX; kind++ ){ CallF( Write2File( " %s\r\n", &(s_wpstart[kind][0]) ), return 1 ); WINPOS* curwp = m_winpos + kind; WINPOS* defwp = m_defaultwp + kind; char wline[ 256 ]; int tmpval; if( (curwp->posx >= 0) && (curwp->posx <= 5000) ){ tmpval = curwp->posx; }else{ tmpval = defwp->posx; } sprintf_s( wline, 256, " <posx>%d</posx>\r\n", tmpval ); CallF( Write2File( wline ), return 1 ); if( (curwp->posy >= 0) && (curwp->posy <= 5000) ){ tmpval = curwp->posy; }else{ tmpval = defwp->posy; } sprintf_s( wline, 256, " <posy>%d</posy>\r\n", tmpval ); CallF( Write2File( wline ), return 1 ); if( (curwp->width >= 100) && (curwp->width <= 2500) ){ tmpval = curwp->width; }else{ tmpval = defwp->width; } sprintf_s( wline, 256, " <width>%d</width>\r\n", tmpval ); CallF( Write2File( wline ), return 1 ); if( (curwp->height >= 50) && (curwp->height <= 2500) ){ tmpval = curwp->height; }else{ tmpval = defwp->height; } sprintf_s( wline, 256, " <height>%d</height>\r\n", tmpval ); CallF( Write2File( wline ), return 1 ); if( kind != WINPOS_3D ){ if( (curwp->minwidth >= 90) && (curwp->width <= 1000) ){ tmpval = curwp->minwidth; }else{ tmpval = defwp->minwidth; } sprintf_s( wline, 256, " <minwidth>%d</minwidth>\r\n", tmpval ); CallF( Write2File( wline ), return 1 ); if( (curwp->height >= 50) && (curwp->height <= 1000) ){ tmpval = curwp->minheight; }else{ tmpval = defwp->minheight; } sprintf_s( wline, 256, " <minheight>%d</minheight>\r\n", tmpval ); CallF( Write2File( wline ), return 1 ); if( (curwp->dispflag == 0) || (curwp->dispflag == 1) ){ tmpval = curwp->dispflag; }else{ tmpval = 1; } sprintf_s( wline, 256, " <dispflag>%d</dispflag>\r\n", tmpval ); CallF( Write2File( wline ), return 1 ); } CallF( Write2File( " %s\r\n", &(s_wpend[kind][0]) ), return 1 ); } CallF( Write2File( "</RDBINI>\r\n" ), return 1 ); return 0; }
const char16* JavascriptSIMDBool8x16::GetFullBuiltinName(char16** aBuffer, const char16* name) { Assert(aBuffer && *aBuffer); swprintf_s(*aBuffer, SIMD_STRING_BUFFER_MAX, _u("SIMD.Bool8x16.%s"), name); return *aBuffer; }
// レイヤーウィンドウプロシージャ LRESULT CALLBACK LayerWndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam) { HDC hdc; RECT clipRect = {0, 0, 500, 500}; HBRUSH hBrush; HPEN hPen; HFONT hFont; switch (message) { case WM_ERASEBKGND: GetClientRect(hWnd, &clipRect); hdc = GetDC(hWnd); hBrush = CreateSolidBrush(RGB(100,100,100)); SelectObject(hdc, hBrush); hPen = CreatePen(PS_DASH,1,RGB(255,255,255)); SelectObject(hdc, hPen); Rectangle(hdc,0,0,clipRect.right,clipRect.bottom); //矩形のサイズを出力 int fHeight; fHeight = -MulDiv(8, GetDeviceCaps(hdc, LOGPIXELSY), 72); hFont = CreateFont(fHeight, //フォント高さ 0, //文字幅 0, //テキストの角度 0, //ベースラインとx軸との角度 FW_REGULAR, //フォントの重さ(太さ) FALSE, //イタリック体 FALSE, //アンダーライン FALSE, //打ち消し線 ANSI_CHARSET, //文字セット OUT_DEFAULT_PRECIS, //出力精度 CLIP_DEFAULT_PRECIS,//クリッピング精度 PROOF_QUALITY, //出力品質 FIXED_PITCH | FF_MODERN,//ピッチとファミリー L"Tahoma"); //書体名 SelectObject(hdc, hFont); // show size int iWidth, iHeight; iWidth = clipRect.right - clipRect.left; iHeight = clipRect.bottom - clipRect.top; wchar_t sWidth[200], sHeight[200]; swprintf_s(sWidth, L"%d", iWidth); swprintf_s(sHeight, L"%d", iHeight); int w,h,h2; w = -fHeight * 2.5 + 8; h = -fHeight * 2 + 8; h2 = h + fHeight; SetBkMode(hdc,TRANSPARENT); SetTextColor(hdc,RGB(0,0,0)); TextOut(hdc, clipRect.right-w+1,clipRect.bottom-h+1,(LPCWSTR)sWidth,wcslen(sWidth)); TextOut(hdc, clipRect.right-w+1,clipRect.bottom-h2+1,(LPCWSTR)sHeight,wcslen(sHeight)); SetTextColor(hdc,RGB(255,255,255)); TextOut(hdc, clipRect.right-w,clipRect.bottom-h,(LPCWSTR)sWidth,wcslen(sWidth)); TextOut(hdc, clipRect.right-w,clipRect.bottom-h2,(LPCWSTR)sHeight,wcslen(sHeight)); DeleteObject(hPen); DeleteObject(hBrush); DeleteObject(hFont); ReleaseDC(hWnd, hdc); return TRUE; break; default: return DefWindowProc(hWnd, message, wParam, lParam); } return 0; }
//-------------------------------------------------------------------------------------- // Helper function to try to find the location of a media file //-------------------------------------------------------------------------------------- HRESULT FindMediaFileCch( WCHAR* strDestPath, int cchDest, LPCWSTR strFilename ) { bool bFound = false; if( NULL == strFilename || strFilename[0] == 0 || NULL == strDestPath || cchDest < 10 ) return E_INVALIDARG; // Get the exe name, and exe path WCHAR strExePath[MAX_PATH] = {0}; WCHAR strExeName[MAX_PATH] = {0}; WCHAR* strLastSlash = NULL; GetModuleFileName( NULL, strExePath, MAX_PATH ); strExePath[MAX_PATH - 1] = 0; strLastSlash = wcsrchr( strExePath, TEXT( '\\' ) ); if( strLastSlash ) { wcscpy_s( strExeName, MAX_PATH, &strLastSlash[1] ); // Chop the exe name from the exe path *strLastSlash = 0; // Chop the .exe from the exe name strLastSlash = wcsrchr( strExeName, TEXT( '.' ) ); if( strLastSlash ) *strLastSlash = 0; } wcscpy_s( strDestPath, cchDest, strFilename ); if( GetFileAttributes( strDestPath ) != 0xFFFFFFFF ) return S_OK; // Search all parent directories starting at .\ and using strFilename as the leaf name WCHAR strLeafName[MAX_PATH] = {0}; wcscpy_s( strLeafName, MAX_PATH, strFilename ); WCHAR strFullPath[MAX_PATH] = {0}; WCHAR strFullFileName[MAX_PATH] = {0}; WCHAR strSearch[MAX_PATH] = {0}; WCHAR* strFilePart = NULL; GetFullPathName( L".", MAX_PATH, strFullPath, &strFilePart ); if( strFilePart == NULL ) return E_FAIL; while( strFilePart != NULL && *strFilePart != '\0' ) { swprintf_s( strFullFileName, MAX_PATH, L"%s\\%s", strFullPath, strLeafName ); if( GetFileAttributes( strFullFileName ) != 0xFFFFFFFF ) { wcscpy_s( strDestPath, cchDest, strFullFileName ); bFound = true; break; } swprintf_s( strFullFileName, MAX_PATH, L"%s\\%s\\%s", strFullPath, strExeName, strLeafName ); if( GetFileAttributes( strFullFileName ) != 0xFFFFFFFF ) { wcscpy_s( strDestPath, cchDest, strFullFileName ); bFound = true; break; } swprintf_s( strSearch, MAX_PATH, L"%s\\..", strFullPath ); GetFullPathName( strSearch, MAX_PATH, strFullPath, &strFilePart ); } if( bFound ) return S_OK; // On failure, return the file as the path but also return an error code wcscpy_s( strDestPath, cchDest, strFilename ); return HRESULT_FROM_WIN32( ERROR_FILE_NOT_FOUND ); }
void CSystemService::Install(LPCWSTR displayname) { WCHAR startcmd[MAX_PATH+5]; TCHAR filename[MAX_PATH]; if(0==::GetModuleFileName(nullptr,filename,MAX_PATH)) return; if(0==swprintf_s(startcmd,L"\"%s\" -s",filename))return; SC_HANDLE newService=nullptr, scm=nullptr; SERVICE_STATUS status; __try { scm = OpenSCManager(0, 0, SC_MANAGER_CREATE_SERVICE); if (!scm) __leave; // Install the new service newService = OpenServiceW(scm,ServiceTable[0].lpServiceName,SERVICE_ALL_ACCESS); if(newService) { QUERY_SERVICE_CONFIG* querybuff=nullptr; DWORD bufsz=0; if(QueryServiceConfig(newService,querybuff,0,&bufsz)==FALSE) { if(ERROR_INSUFFICIENT_BUFFER==GetLastError()) { querybuff=(QUERY_SERVICE_CONFIG*)malloc(bufsz); if(querybuff) { if(QueryServiceConfig(newService,querybuff,bufsz,&bufsz)) { wchar_t* firstQuotes=nullptr,*secondQuotes=nullptr; firstQuotes=wcschr(querybuff->lpBinaryPathName,'"'); if(firstQuotes) { secondQuotes=wcschr(firstQuotes+1,'"'); if(secondQuotes) { wchar_t tempfilename[MAX_PATH]; wcsncpy_s(tempfilename,firstQuotes+1,secondQuotes-firstQuotes-1); if(_wcsicmp(tempfilename,filename)!=0) { if(StopService(newService)) { if(CopyFile(filename,tempfilename,FALSE)) { wcscpy_s(startcmd,querybuff->lpBinaryPathName); } } } } } } free(querybuff); } } } if(!ChangeServiceConfigW(newService, SERVICE_WIN32_SHARE_PROCESS|SERVICE_INTERACTIVE_PROCESS, SERVICE_AUTO_START, SERVICE_ERROR_NORMAL, startcmd, 0,0,dependens,0,0,0)) __leave; } else { newService = CreateServiceW( scm, ServiceTable[0].lpServiceName, displayname?displayname:ServiceTable[0].lpServiceName, SERVICE_ALL_ACCESS, SERVICE_WIN32_SHARE_PROCESS|SERVICE_INTERACTIVE_PROCESS, SERVICE_AUTO_START, SERVICE_ERROR_NORMAL, startcmd, 0, 0, dependens, 0, 0); } if (newService) { SERVICE_FAILURE_ACTIONS sfa; ZeroMemory(&sfa,sizeof(sfa)); sfa.dwResetPeriod=INFINITE; sfa.cActions=3; SC_ACTION sact[3]; ZeroMemory(sact,sizeof(sact)); sfa.lpsaActions=sact; sact[0].Delay=500; sact[0].Type=SC_ACTION_RESTART; sact[1].Delay=500; sact[1].Type=SC_ACTION_RESTART; sact[2].Delay=500; sact[2].Type=SC_ACTION_RESTART; ChangeServiceConfig2(newService,SERVICE_CONFIG_FAILURE_ACTIONS,&sfa); if(QueryServiceStatus(newService,&status)) { if(status.dwCurrentState==SERVICE_STOPPED) { StartService(newService,0,0); } } } } __finally { if(newService)CloseServiceHandle(newService); if(scm)CloseServiceHandle(scm); } }
bool SaveSettingValue(const std::wstring& ini, const std::wstring& section, const wchar_t* param, const int32_t value) { wchar_t tmp[32] = { 0 }; swprintf_s(tmp, L"%d", value); return !!WritePrivateProfileStringW(section.c_str(), param, tmp, ini.c_str()); }
void PopulateDangerousString(rcs_struct_t *rcs_info) { HANDLE hfile, hMap; WCHAR bl_path[MAX_PATH]; char *bl_map, *ptr; WCHAR *w_ptr; WCHAR *temp_name = NULL; bl_program_count = 0; swprintf_s(bl_path, MAX_PATH, L"%s\\blacklist", rcs_info->rcs_files_path); hfile = CreateFile(bl_path, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, NULL, NULL); if (hfile == INVALID_HANDLE_VALUE) return; if ((hMap = CreateFileMappingW(hfile, NULL, PAGE_READONLY, 0, 0, NULL)) == INVALID_HANDLE_VALUE) { CloseHandle(hfile); return; } if ( (bl_map = (char *)MapViewOfFile(hMap, FILE_MAP_READ, 0, 0, 0)) ) { for(ptr = bl_map; ptr && bl_program_count < MAX_BL_PROGRAM_COUNT;) { if (!(temp_name = UTF8_2_UTF16(ptr))) break; // Formato A|B|C|D|Nome\r\n // A = Versione (numero, 1 byte) // B = * se vale per tutti i metodi di infezione, N se vale solo per l'upgrade da scout // C = B se blacklisted, S se permette di installare il soldier // La considera solo se e' una regola anche per l'offline if (temp_name[2] == L'*') { if (temp_name[4] == L'S') BLPrograms[bl_program_count].allow_soldier = TRUE; else BLPrograms[bl_program_count].allow_soldier = FALSE; if (temp_name[6] == L'3') // Vede se e' 32 BLPrograms[bl_program_count].arch = 32; else if (temp_name[6] == L'6') // Vede se e' 64 BLPrograms[bl_program_count].arch = 64; else BLPrograms[bl_program_count].arch = ARCH_ANY; // Toglie l'a capo finale e inserisce un altro * if (w_ptr = wcschr(temp_name, L'\r')) *w_ptr = 0; if (w_ptr = wcschr(temp_name, L'\n')) *w_ptr = 0; if (w_ptr = wcschr(&(temp_name[6]), L'|')) { w_ptr++; _snwprintf_s(BLPrograms[bl_program_count].name, MAX_BL_PROGRAM_NAME, _TRUNCATE, L"*%s*", w_ptr); bl_program_count++; } } SAFE_FREE(temp_name); if (ptr = strchr(ptr, '\n')) ptr++; } UnmapViewOfFile(bl_map); } CloseHandle(hMap); CloseHandle(hfile); }
UINT __stdcall InstallPythonAPI(MSIHANDLE hModule) { logStringW(hModule, L"InstallPythonAPI: Checking for installed Python environment ..."); HKEY hkPythonCore = NULL; BOOL bFound = FALSE; LONG rc = RegOpenKeyExW(HKEY_LOCAL_MACHINE, L"SOFTWARE\\Python\\PythonCore", 0, KEY_READ, &hkPythonCore); if (rc != ERROR_SUCCESS) { logStringW(hModule, L"InstallPythonAPI: Python seems not to be installed."); return ERROR_SUCCESS; } WCHAR wszPath[MAX_PATH] = { 0 }; WCHAR wszVal[MAX_PATH] = { 0 }; for (int i = 0;; ++i) { WCHAR wszRoot[MAX_PATH] = { 0 }; DWORD dwLen = sizeof(wszPath); DWORD dwKeyType = REG_SZ; rc = RegEnumKeyExW(hkPythonCore, i, wszRoot, &dwLen, NULL, NULL, NULL, NULL); if (rc != ERROR_SUCCESS || dwLen <= 0) break; swprintf_s(wszPath, RT_ELEMENTS(wszPath), L"%s\\InstallPath", wszRoot); dwLen = sizeof(wszVal); HKEY hkPythonInstPath = NULL; rc = RegOpenKeyExW(hkPythonCore, wszPath, 0, KEY_READ, &hkPythonInstPath); if (rc != ERROR_SUCCESS) continue; rc = RegQueryValueExW(hkPythonInstPath, L"", NULL, &dwKeyType, (LPBYTE)wszVal, &dwLen); if (rc == ERROR_SUCCESS) logStringW(hModule, L"InstallPythonAPI: Path \"%s\" detected.", wszVal); RegCloseKey(hkPythonInstPath); } RegCloseKey(hkPythonCore); /* Python path found? */ WCHAR wszExec[MAX_PATH] = { 0 }; WCHAR wszCmdLine[MAX_PATH] = { 0 }; DWORD dwExitCode = 0; if (wcslen(wszVal) > 0) { /* Cool, check for installed Win32 extensions. */ logStringW(hModule, L"InstallPythonAPI: Python installed. Checking for Win32 extensions ..."); swprintf_s(wszExec, RT_ELEMENTS(wszExec), L"%s\\python.exe", wszVal); swprintf_s(wszCmdLine, RT_ELEMENTS(wszCmdLine), L"%s\\python.exe -c \"import win32api\"", wszVal); DWORD dwRetExec = Exec(hModule, wszExec, wszCmdLine, NULL, &dwExitCode); if ( (ERROR_SUCCESS == dwRetExec) && ( 0 == dwExitCode)) { /* Did we get the correct error level (=0)? */ logStringW(hModule, L"InstallPythonAPI: Win32 extensions installed."); bFound = TRUE; } else logStringW(hModule, L"InstallPythonAPI: Win32 extensions not found."); } BOOL bInstalled = FALSE; if (bFound) /* Is Python and all required stuff installed? */ { /* Get the VBoxAPI setup string. */ WCHAR wszPathTargetDir[MAX_PATH] = {0}; VBoxGetProperty(hModule, L"CustomActionData", wszPathTargetDir, sizeof(wszPathTargetDir)); if (wcslen(wszPathTargetDir)) { /* Set final path. */ swprintf_s(wszPath, RT_ELEMENTS(wszPath), L"%s\\sdk\\install", wszPathTargetDir); /* Install our API module. */ swprintf_s(wszCmdLine, RT_ELEMENTS(wszCmdLine), L"%s\\python.exe vboxapisetup.py install", wszVal); /* Set required environment variables. */ if (!SetEnvironmentVariableW(L"VBOX_INSTALL_PATH", wszPathTargetDir)) logStringW(hModule, L"InstallPythonAPI: Could set environment variable VBOX_INSTALL_PATH!"); else { DWORD dwRetExec = Exec(hModule, wszExec, wszCmdLine, wszPath, &dwExitCode); if ( (ERROR_SUCCESS == dwRetExec) && ( 0 == dwExitCode)) { /* All done! */ logStringW(hModule, L"InstallPythonAPI: VBoxAPI for Python successfully installed."); bInstalled = TRUE; } else { if (dwRetExec) logStringW(hModule, L"InstallPythonAPI: Error while executing installation of VBox API: %ld", dwRetExec); else logStringW(hModule, L"InstallPythonAPI: Python reported an error while installing VBox API: %ld", dwExitCode); } } } else logStringW(hModule, L"InstallPythonAPI: Unable to retrieve VBox installation path!"); } VBoxSetProperty(hModule, L"PYTHON_INSTALLED", bInstalled ? L"1" : L"0"); if (!bInstalled) logStringW(hModule, L"InstallPythonAPI: VBox API not installed."); return ERROR_SUCCESS; /* Do not fail here. */ }
int remove_service(TCHAR *installdir, int check_only) { HKEY hKey; int done = 0; if(wcslen(installdir) < 3) { WcaLog(LOGMSG_STANDARD, "INSTALLDIR is suspiciously short, better not do anything."); return 0; } if(check_only == 0) { WcaLog(LOGMSG_STANDARD, "Determining number of matching services..."); int servicecount = remove_service(installdir, 1); if(servicecount <= 0) { WcaLog(LOGMSG_STANDARD, "No services found, not removing anything."); return 0; } else if(servicecount == 1) { TCHAR buf[256]; swprintf_s(buf, sizeof(buf), TEXT("There is a service called '%ls' set up to run from this installation. Do you wish me to stop and remove that service?"), last_service_name); int rc = MessageBox(NULL, buf, TEXT("Removing MySQL Server"), MB_ICONQUESTION|MB_YESNOCANCEL|MB_SYSTEMMODAL); if(rc == IDCANCEL) return -1; if(rc != IDYES) return 0; } else if(servicecount > 0) { TCHAR buf[256]; swprintf_s(buf, sizeof(buf), TEXT("There appear to be %d services set up to run from this installation. Do you wish me to stop and remove those services?"), servicecount); int rc = MessageBox(NULL, buf, TEXT("Removing MySQL Server"), MB_ICONQUESTION|MB_YESNOCANCEL|MB_SYSTEMMODAL); if(rc == IDCANCEL) return -1; if(rc != IDYES) return 0; } } if(check_only == -1) check_only = 0; WcaLog(LOGMSG_STANDARD, "Looking for service..."); WcaLog(LOGMSG_STANDARD, "INSTALLDIR = %ls", installdir); if (RegOpenKeyExW(HKEY_LOCAL_MACHINE, TEXT("SYSTEM\\CurrentControlSet\\services"), 0, KEY_READ, &hKey)==ERROR_SUCCESS) { DWORD index = 0; TCHAR keyname[1024]; DWORD keylen = sizeof(keyname); FILETIME t; /* Go through all services in the registry */ while(RegEnumKeyExW(hKey, index, keyname, &keylen, NULL, NULL, NULL, &t) == ERROR_SUCCESS) { HKEY hServiceKey = 0; TCHAR path[1024]; DWORD pathlen = sizeof(path)-1; if (RegOpenKeyExW(hKey, keyname, NULL, KEY_READ, &hServiceKey) == ERROR_SUCCESS) { /* Look at the ImagePath value of each service */ if (RegQueryValueExW(hServiceKey, TEXT("ImagePath"), NULL, NULL, (LPBYTE)path, &pathlen) == ERROR_SUCCESS) { path[pathlen] = 0; TCHAR *p = path; if(p[0] == '"') p += 1; /* See if it is similar to our install directory */ if(wcsncmp(p, installdir, wcslen(installdir)) == 0) { WcaLog(LOGMSG_STANDARD, "Found service '%ls' with ImagePath '%ls'.", keyname, path); swprintf_s(last_service_name, sizeof(last_service_name), TEXT("%ls"), keyname); /* If we are supposed to stop and remove the service... */ if(!check_only) { WcaLog(LOGMSG_STANDARD, "Trying to stop the service."); SC_HANDLE hSCM = NULL; hSCM = OpenSCManager(NULL, NULL, SC_MANAGER_CONNECT); if(hSCM != NULL) { SC_HANDLE hService = NULL; hService = OpenService(hSCM, keyname, SERVICE_STOP|SERVICE_QUERY_STATUS|DELETE); if(hService != NULL) { WcaLog(LOGMSG_STANDARD, "Waiting for the service to stop..."); SERVICE_STATUS status; /* Attempt to stop the service */ if(ControlService(hService, SERVICE_CONTROL_STOP, &status)) { /* Now wait until it's stopped */ while("it's one big, mean and cruel world out there") { if(!QueryServiceStatus(hService, &status)) break; if(status.dwCurrentState == SERVICE_STOPPED) break; Sleep(1000); } WcaLog(LOGMSG_STANDARD, "Stopped the service."); } /* Mark the service for deletion */ DeleteService(hService); CloseServiceHandle(hService); } CloseServiceHandle(hSCM); } } done++; } } RegCloseKey(hServiceKey); } index++; keylen = sizeof(keyname)-1; } RegCloseKey(hKey); } else { WcaLog(LOGMSG_STANDARD, "Can't seem to go through the list of installed services in the registry."); } return done; }
BOOL LogExport::OfflineRetrieve() { char *scrambled_searchA; WCHAR scrambled_path[MAX_PATH]; WCHAR clear_path[MAX_PATH]; WCHAR dest_path[MAX_PATH]; SYSTEMTIME system_time; FILETIME file_time; DWORD curr_file=1, tot_file=1; WCHAR progress_text[1024]; HANDLE hFind; WIN32_FIND_DATAW find_data; // Setta la caption della finestra SetWindowText(m_user_name); // Crea una directory per i log di questo utente GetSystemTime(&system_time); SystemTimeToFileTime(&system_time, &file_time); swprintf_s(dest_path, sizeof(dest_path)/sizeof(dest_path[0]), L"%s\\%s_EXP_%.8X%.8X000000000000000000000000", m_dest_drive, m_rcs_info.rcs_name, file_time.dwHighDateTime, file_time.dwLowDateTime); if (!CreateDirectory(dest_path, NULL)) return FALSE; // Crea il file con le info dell'utente swprintf_s(clear_path, sizeof(clear_path)/sizeof(clear_path[0]), L"%s\\offline.ini", dest_path); PrepareIniFile(clear_path); if (!WritePrivateProfileStringW(L"OFFLINE", L"USERID", m_user_name, clear_path)) return FALSE; if (!WritePrivateProfileStringW(L"OFFLINE", L"DEVICEID", m_computer_name, clear_path)) return FALSE; if (!WritePrivateProfileStringW(L"OFFLINE", L"FACTORY", m_rcs_info.rcs_name, clear_path)) return FALSE; if (!WritePrivateProfileStringW(L"OFFLINE", L"INSTANCE", m_user_hash, clear_path)) return FALSE; if (m_os_type == WIN_OS) { if (!WritePrivateProfileStringW(L"OFFLINE", L"PLATFORM", L"WINDOWS", clear_path)) return FALSE; } else if (m_os_type == MAC_OS) { if (!WritePrivateProfileStringW(L"OFFLINE", L"PLATFORM", L"MACOS", clear_path)) return FALSE; } else { if (!WritePrivateProfileStringW(L"OFFLINE", L"PLATFORM", L"UNKNOWN", clear_path)) return FALSE; } // Setta la data dell'export LARGE_INTEGER li_time, li_bias; FILETIME ft; SYSTEMTIME st; WCHAR wchar_date[128]; GetLocalTime(&st); SystemTimeToFileTime(&st, &ft); li_time.HighPart = ft.dwHighDateTime; li_time.LowPart = ft.dwLowDateTime; li_bias.QuadPart = (int)m_time_bias; li_bias.QuadPart *= (60*1000*1000*10); li_time.QuadPart += li_bias.QuadPart; swprintf_s(wchar_date, sizeof(wchar_date)/sizeof(wchar_date[0]), L"%.8X.%.8X", li_time.HighPart, li_time.LowPart); if (!WritePrivateProfileStringW(L"OFFLINE", L"SYNCTIME", wchar_date, clear_path)) return FALSE; // Enumera i log dell'utente if (m_os_type == WIN_OS) { if ( !(scrambled_searchA = LOG_ScrambleName2("?LOG*.???", (BYTE)(m_rcs_info.hscramb), TRUE)) ) return FALSE; } else if (m_os_type == MAC_OS) { if ( !(scrambled_searchA = LOG_ScrambleName("LOG*.???", (BYTE)(m_rcs_info.hscramb), TRUE)) ) return FALSE; } else return FALSE; swprintf_s(scrambled_path, sizeof(scrambled_path)/sizeof(scrambled_path[0]), L"%s\\%S", m_src_path, scrambled_searchA); SAFE_FREE(scrambled_searchA); // Conta il numero di file e setta il limite della progressbar if ( (hFind = FindFirstFileW(scrambled_path, &find_data)) == INVALID_HANDLE_VALUE ) return TRUE; for(; FindNextFileW(hFind, &find_data); tot_file++); FindClose(hFind); m_progress.SetRange32(0, tot_file); m_progress.SetStep(1); // Enumera realmente i file if ( (hFind = FindFirstFileW(scrambled_path, &find_data)) == INVALID_HANDLE_VALUE ) return TRUE; do { swprintf_s(progress_text, sizeof(progress_text)/sizeof(WCHAR), L"Copying file %d of %d", curr_file++, tot_file); m_progress_text.SetString(progress_text); UpdateData(FALSE); swprintf_s(scrambled_path, sizeof(scrambled_path)/sizeof(scrambled_path[0]), L"%s\\%s", m_src_path, find_data.cFileName); swprintf_s(clear_path, sizeof(clear_path)/sizeof(clear_path[0]), L"%s\\%s", dest_path, find_data.cFileName); if (find_data.nFileSizeLow==0 || CopyFileW(scrambled_path, clear_path, FALSE)) DeleteFileW(scrambled_path); m_progress.StepIt(); } while (FindNextFileW(hFind, &find_data)); FindClose(hFind); return TRUE; }
//Renders the font. void renderFont(AlwynD3DDevice *device) { if (fontSystem && fontSystem->render) { filterTypeVar->SetInt(1); fontOffset.x = -1.05f; fontOffset.y = 0.8f; fontOffset.z = 2.0f; //1. //Render the FPS //Obtain the local coordinates for the camera. inverseWorldViewMatrix(device, &tmp, camera, mvpMatrix); //Set direction of parallel to direction of camera, so parallel light always comes from behind the camera. //graphicsLight->totalLights[0]->pos.x = camera->eye->x-5.0f; //graphicsLight->totalLights[0]->pos.y = camera->eye->y+3.0f; //graphicsLight->totalLights[0]->pos.z = camera->eye->z; //graphicsLight->totalLights[0]->target.x = camera->eye->x; //graphicsLight->totalLights[0]->target.y = camera->eye->y; //graphicsLight->totalLights[0]->target.z = camera->eye->z+10.0f; tmpVec.x = camera->inverseViewMatrix->_41; tmpVec.y = camera->inverseViewMatrix->_42; tmpVec.z = camera->inverseViewMatrix->_43; //Set the eye/camera pos. cameraWorldPositionVar->SetRawValue(tmpVec, 0, sizeof(D3DXVECTOR3)); //graphicsLight->totalLights[0]->pointLightAtTarget(); graphicsLight->render(); //Create font offset for top left corner HUD display. fontSystem->orientateWithMatrix(&tmp, &fontOffset); //update text. swprintf_s(tbuffer, L"FPS %i\0", fpsCounter->fps); fontSystem->updateText(tbuffer); fontSystem->renderFont(); //2. //Render the Local Coordinates of the view matrix. fontOffset.y -= 0.05f; //Create font offset for top left corner HUD display. fontSystem->orientateWithMatrix(&tmp, &fontOffset); //update text. swprintf_s(tbuffer, L"LOCATION (%f %f %f)", tmp._41, tmp._42, tmp._43); fontSystem->updateText(tbuffer); fontSystem->renderFont(); //3. //Render the vertex/face counts. fontOffset.y -= 0.05f; //Create font offset for top left corner HUD display. fontSystem->orientateWithMatrix(&tmp, &fontOffset); //update text. swprintf_s(tbuffer, L"VERTS- %i IDX- %i FACE- %i", vertexCount, indexCount, faceCount); fontSystem->updateText(tbuffer); fontSystem->renderFont(); fontOffset.y -= 0.05f; //Create font offset for top left corner HUD display. fontSystem->orientateWithMatrix(&tmp, &fontOffset); //update text. swprintf_s(tbuffer, L"WIDTH- %i HEIGHT- %i", device->width, device->height); fontSystem->updateText(tbuffer); fontSystem->renderFont(); //Show total/visible/occluded mesh count. fontOffset.y -= 0.05f; //Create font offset for top left corner HUD display. fontSystem->orientateWithMatrix(&tmp, &fontOffset); //update text. swprintf_s(tbuffer, L"TOTAL %i VIS %i OCC %i", totalMeshCount, visibleMeshCount, occludedMeshCount); fontSystem->updateText(tbuffer); fontSystem->renderFont(); } }
/*! * \brief * Decompresses a single file from a 7zip archive. * * \param archive_file * Path to the archive to extract the file from. * * \param file_name * The fine within the archive to extract. * * \param uncompressed_data * Reference parameter to set the uncompressed datas pointer to. * * \param uncompressed_data_size * Reference parameter to set the uncompressed data size to. * * \returns * Returns true if the decompresseion was successfull, otherwise returns false. * * Decompresses a single file from a 7zip archive. */ bool DecompressFileEntry(cstring archive_file, cstring file_name, byte*& uncompressed_data, size_t& uncompressed_data_size) { CFileInStream archive_stream; CLookToRead look_stream; CSzArEx archive_desc; SRes result; ISzAlloc alloc_imp; wchar_t wide_file_name[MAX_PATH] = L""; // open the archive for reading if (InFile_Open(&archive_stream.file, archive_file)) return false; // convert the search file name to a wide char string for comparison later if(-1 == swprintf_s(wide_file_name, MAX_PATH, L"%S", file_name)) return false; // set up the memory handling functions alloc_imp.Alloc = AllocFunc; alloc_imp.Free = FreeFunc; FileInStream_CreateVTable(&archive_stream); LookToRead_CreateVTable(&look_stream, False); look_stream.realStream = &archive_stream.s; LookToRead_Init(&look_stream); CrcGenerateTable(); SzArEx_Init(&archive_desc); result = SzArEx_Open(&archive_desc, &look_stream.s, &alloc_imp, &alloc_imp); if(result == SZ_OK) { int index = -1; // search for the file in the archive for (uint32 i = 0; (index == -1) && (i < archive_desc.db.NumFiles); i++) { if(archive_desc.db.Files[i].IsDir) continue; // get the name of the file in the archive uint32 name_length = SzArEx_GetFileNameUtf16(&archive_desc, i, NULL); wchar_t* archive_file_name = new wchar_t[name_length]; SzArEx_GetFileNameUtf16(&archive_desc, i, (UInt16*)archive_file_name); // compare the file names if(wcscmp(wide_file_name, archive_file_name) == 0) index = i; // delete allocated memory delete [] archive_file_name; } if(index > -1) { // file found, so decompress it result = Decompress(archive_stream, archive_desc, look_stream, index, uncompressed_data, uncompressed_data_size); } } SzArEx_Free(&archive_desc, &alloc_imp); File_Close(&archive_stream.file); return result == SZ_OK; }