HRESULT CSchemeHandler::OnSourceOpen(_In_ IMFAsyncResult *pResult) { ComPtr<IUnknown> spState = pResult->GetStateNoAddRef(); if (!spState) { return MF_E_UNEXPECTED; } ComPtr<IMFAsyncResult> spSavedResult; HRESULT hr = S_OK; hr = spState.As(&spSavedResult); if (FAILED(hr)) { TRACEHR_RET(hr); } ComPtr<IUnknown> spunkSource; ComPtr<IMFMediaSource> spSource; hr = spSavedResult->GetObject(&spunkSource); if (SUCCEEDED(hr)) { hr = spunkSource.As(&spSource); if (SUCCEEDED(hr)) { CMediaSource *pSource = static_cast<CMediaSource *>(spSource.Get()); hr = pSource->EndOpen(pResult); } } spSavedResult->SetStatus(hr); hr = MFInvokeCallback(spSavedResult.Get()); TRACEHR_RET(hr); }
bool validateShortcut() { QString path = systemShortcutPath(); if (path.isEmpty() || cExeName().isEmpty()) return false; if (cAlphaVersion()) { path += qsl("TelegramAlpha.lnk"); if (validateShortcutAt(path)) return true; } else { if (validateShortcutAt(path + qsl("Telegram Desktop/Telegram.lnk"))) return true; if (validateShortcutAt(path + qsl("Telegram Win (Unofficial)/Telegram.lnk"))) return true; path += qsl("Telegram.lnk"); if (validateShortcutAt(path)) return true; } ComPtr<IShellLink> shellLink; HRESULT hr = CoCreateInstance(CLSID_ShellLink, nullptr, CLSCTX_INPROC_SERVER, IID_PPV_ARGS(&shellLink)); if (!SUCCEEDED(hr)) return false; hr = shellLink->SetPath(QDir::toNativeSeparators(cExeDir() + cExeName()).toStdWString().c_str()); if (!SUCCEEDED(hr)) return false; hr = shellLink->SetArguments(L""); if (!SUCCEEDED(hr)) return false; hr = shellLink->SetWorkingDirectory(QDir::toNativeSeparators(QDir(cWorkingDir()).absolutePath()).toStdWString().c_str()); if (!SUCCEEDED(hr)) return false; ComPtr<IPropertyStore> propertyStore; hr = shellLink.As(&propertyStore); if (!SUCCEEDED(hr)) return false; PROPVARIANT appIdPropVar; hr = InitPropVariantFromString(getId(), &appIdPropVar); if (!SUCCEEDED(hr)) return false; hr = propertyStore->SetValue(getKey(), appIdPropVar); PropVariantClear(&appIdPropVar); if (!SUCCEEDED(hr)) return false; PROPVARIANT startPinPropVar; hr = InitPropVariantFromUInt32(APPUSERMODEL_STARTPINOPTION_NOPINONINSTALL, &startPinPropVar); if (!SUCCEEDED(hr)) return false; hr = propertyStore->SetValue(pkey_AppUserModel_StartPinOption, startPinPropVar); PropVariantClear(&startPinPropVar); if (!SUCCEEDED(hr)) return false; hr = propertyStore->Commit(); if (!SUCCEEDED(hr)) return false; ComPtr<IPersistFile> persistFile; hr = shellLink.As(&persistFile); if (!SUCCEEDED(hr)) return false; hr = persistFile->Save(QDir::toNativeSeparators(path).toStdWString().c_str(), TRUE); if (!SUCCEEDED(hr)) return false; return true; }
Frame D3D11VideoRender::CreateFrame(IMFSample * sample, UINT width, UINT height) { // 获取 Buffer 数量 DWORD bufferCount; ThrowIfFailed(sample->GetBufferCount(&bufferCount)); ComPtr<ID3D11Texture2D> texture; for (DWORD i = 0; i < 1; i++) { ComPtr<IMFMediaBuffer> buffer; ThrowIfFailed(sample->GetBufferByIndex(i, &buffer)); ComPtr<IMFDXGIBuffer> dxgiBuffer; if (!SUCCEEDED(buffer.As(&dxgiBuffer))) { ThrowIfFailed(dxgiBuffer->GetResource(IID_PPV_ARGS(&texture))); D3D11_TEXTURE2D_DESC desc; texture->GetDesc(&desc); desc.Height = desc.Height; } else { ComPtr<IMF2DBuffer> buffer2d; ThrowIfFailed(buffer.As(&buffer2d)); DWORD bufferSize; ThrowIfFailed(buffer2d->GetContiguousLength(&bufferSize)); BYTE* base; LONG pitch; ThrowIfFailed(buffer2d->Lock2D(&base, &pitch)); auto fin = make_finalizer([&] { buffer2d->Unlock2D();}); //width = pitch; height = bufferSize / pitch * 2 / 3; D3D11_TEXTURE2D_DESC desc{ 0 }; desc.Width = width; desc.Height = height; desc.MipLevels = 1; desc.ArraySize = 1; desc.Format = DXGI_FORMAT_NV12; desc.SampleDesc.Count = 1; desc.Usage = D3D11_USAGE_IMMUTABLE; desc.BindFlags = D3D11_BIND_SHADER_RESOURCE; D3D11_SUBRESOURCE_DATA data{ base, static_cast<UINT>(pitch), 0 }; ThrowIfFailed(d3dDevice->CreateTexture2D(&desc, &data, &texture)); } } ComPtr<ID3D11ShaderResourceView> luminanceView, chrominanceView; D3D11_SHADER_RESOURCE_VIEW_DESC resDesc = CD3D11_SHADER_RESOURCE_VIEW_DESC( texture.Get(), D3D11_SRV_DIMENSION_TEXTURE2D, DXGI_FORMAT_R8_UNORM); ThrowIfFailed(d3dDevice->CreateShaderResourceView(texture.Get(), &resDesc, &luminanceView)); resDesc = CD3D11_SHADER_RESOURCE_VIEW_DESC( texture.Get(), D3D11_SRV_DIMENSION_TEXTURE2D, DXGI_FORMAT_R8G8_UNORM); ThrowIfFailed(d3dDevice->CreateShaderResourceView(texture.Get(), &resDesc, &chrominanceView)); return{ luminanceView, chrominanceView }; }
// Configures the Direct3D device, and stores handles to it and the device context. void DX::DeviceResources::CreateDeviceResources() { UINT creationFlags = D3D11_CREATE_DEVICE_BGRA_SUPPORT; #ifdef _DEBUG creationFlags |= D3D11_CREATE_DEVICE_DEBUG; #elif defined(PROFILE) creationFlags |= D3D11_CREATE_DEVICE_INSTRUMENTED; #endif if (m_fastSemantics) { creationFlags |= D3D11_CREATE_DEVICE_IMMEDIATE_CONTEXT_FAST_SEMANTICS; } D3D_FEATURE_LEVEL featureLevels[] = { D3D_FEATURE_LEVEL_11_1, }; // Create the Direct3D 11 API device object and a corresponding context. ComPtr<ID3D11Device> device; ComPtr<ID3D11DeviceContext> context; DX::ThrowIfFailed(D3D11CreateDevice( nullptr, D3D_DRIVER_TYPE_HARDWARE, 0, creationFlags, featureLevels, _countof(featureLevels), D3D11_SDK_VERSION, device.GetAddressOf(), // Returns the Direct3D device created. &m_d3dFeatureLevel, // Returns feature level of device created. context.GetAddressOf() // Returns the device immediate context. )); #ifndef NDEBUG ComPtr<ID3D11InfoQueue> d3dInfoQueue; if (SUCCEEDED(device.As(&d3dInfoQueue))) { #ifdef _DEBUG d3dInfoQueue->SetBreakOnSeverity(D3D11_MESSAGE_SEVERITY_CORRUPTION, true); d3dInfoQueue->SetBreakOnSeverity(D3D11_MESSAGE_SEVERITY_ERROR, true); #endif D3D11_MESSAGE_ID hide[] = { D3D11_MESSAGE_ID_SETPRIVATEDATA_CHANGINGPARAMS, }; D3D11_INFO_QUEUE_FILTER filter = {}; filter.DenyList.NumIDs = _countof(hide); filter.DenyList.pIDList = hide; d3dInfoQueue->AddStorageFilterEntries(&filter); } #endif DX::ThrowIfFailed(device.As(&m_d3dDevice)); DX::ThrowIfFailed(context.As(&m_d3dContext)); }
bool SwapChainPanelNativeWindow::initialize(EGLNativeWindowType window, IPropertySet *propertySet) { ComPtr<IPropertySet> props = propertySet; ComPtr<IInspectable> win = window; SIZE swapChainSize = {}; bool swapChainSizeSpecified = false; HRESULT result = S_OK; // IPropertySet is an optional parameter and can be null. // If one is specified, cache as an IMap and read the properties // used for initial host initialization. if (propertySet) { result = props.As(&mPropertyMap); if (SUCCEEDED(result)) { // The EGLRenderSurfaceSizeProperty is optional and may be missing. The IPropertySet // was prevalidated to contain the EGLNativeWindowType before being passed to // this host. result = GetOptionalSizePropertyValue(mPropertyMap, EGLRenderSurfaceSizeProperty, &swapChainSize, &swapChainSizeSpecified); } } if (SUCCEEDED(result)) { result = win.As(&mSwapChainPanel); } if (SUCCEEDED(result)) { // If a swapchain size is specfied, then the automatic resize // behaviors implemented by the host should be disabled. The swapchain // will be still be scaled when being rendered to fit the bounds // of the host. // Scaling of the swapchain output needs to be handled by the // host for swapchain panels even though the scaling mode setting // DXGI_SCALING_STRETCH is configured on the swapchain. if (swapChainSizeSpecified) { mClientRect = { 0, 0, swapChainSize.cx, swapChainSize.cy }; // Enable host swapchain scaling mRequiresSwapChainScaling = true; } else { result = GetSwapChainPanelSize(mSwapChainPanel, &mClientRect); } } if (SUCCEEDED(result)) { mNewClientRect = mClientRect; mClientRectChanged = false; return registerForSizeChangeEvents(); } return false; }
bool validateShortcutAt(const QString &path) { static const int maxFileLen = MAX_PATH * 10; std::wstring p = QDir::toNativeSeparators(path).toStdWString(); DWORD attributes = GetFileAttributes(p.c_str()); if (attributes >= 0xFFFFFFF) return false; // file does not exist ComPtr<IShellLink> shellLink; HRESULT hr = CoCreateInstance(CLSID_ShellLink, nullptr, CLSCTX_INPROC_SERVER, IID_PPV_ARGS(&shellLink)); if (!SUCCEEDED(hr)) return false; ComPtr<IPersistFile> persistFile; hr = shellLink.As(&persistFile); if (!SUCCEEDED(hr)) return false; hr = persistFile->Load(p.c_str(), STGM_READWRITE); if (!SUCCEEDED(hr)) return false; ComPtr<IPropertyStore> propertyStore; hr = shellLink.As(&propertyStore); if (!SUCCEEDED(hr)) return false; PROPVARIANT appIdPropVar; hr = propertyStore->GetValue(getKey(), &appIdPropVar); if (!SUCCEEDED(hr)) return false; WCHAR already[MAX_PATH]; hr = Dlls::PropVariantToString(appIdPropVar, already, MAX_PATH); if (SUCCEEDED(hr)) { if (std::wstring(getId()) == already) { PropVariantClear(&appIdPropVar); return true; } } if (appIdPropVar.vt != VT_EMPTY) { PropVariantClear(&appIdPropVar); return false; } PropVariantClear(&appIdPropVar); hr = InitPropVariantFromString(getId(), &appIdPropVar); if (!SUCCEEDED(hr)) return false; hr = propertyStore->SetValue(getKey(), appIdPropVar); PropVariantClear(&appIdPropVar); if (!SUCCEEDED(hr)) return false; hr = propertyStore->Commit(); if (!SUCCEEDED(hr)) return false; if (persistFile->IsDirty() == S_OK) { persistFile->Save(p.c_str(), TRUE); } return true; }
// Configures the Direct3D device, and stores handles to it and the device context. void StarboardWinRT::DeviceResources::CreateDeviceResources() { // This flag adds support for surfaces with a different color channel ordering // than the API default. It is required for compatibility with Direct2D. UINT creationFlags = D3D11_CREATE_DEVICE_BGRA_SUPPORT; #if defined(_DEBUG) if (StarboardWinRT::SdkLayersAvailable()) { // If the project is in a debug build, enable debugging via SDK Layers with this flag. creationFlags |= D3D11_CREATE_DEVICE_DEBUG; } #endif // This array defines the set of DirectX hardware feature levels this app will support. // Note the ordering should be preserved. // Don't forget to declare your application's minimum required feature level in its // description. All applications are assumed to support 9.1 unless otherwise stated. D3D_FEATURE_LEVEL featureLevels[] = { D3D_FEATURE_LEVEL_11_1, D3D_FEATURE_LEVEL_11_0, D3D_FEATURE_LEVEL_10_1, D3D_FEATURE_LEVEL_10_0, D3D_FEATURE_LEVEL_9_3, D3D_FEATURE_LEVEL_9_2, D3D_FEATURE_LEVEL_9_1 }; // Create the Direct3D 11 API device object and a corresponding context. ComPtr<ID3D11Device> device; ComPtr<ID3D11DeviceContext> context; HRESULT hr = D3D11CreateDevice(nullptr, // Specify nullptr to use the default adapter. D3D_DRIVER_TYPE_HARDWARE, // Create a device using the hardware graphics driver. 0, // Should be 0 unless the driver is D3D_DRIVER_TYPE_SOFTWARE. creationFlags, // Set debug and Direct2D compatibility flags. featureLevels, // List of feature levels this app can support. ARRAYSIZE(featureLevels), // Size of the list above. D3D11_SDK_VERSION, // Always set this to D3D11_SDK_VERSION for Windows Store apps. &device, // Returns the Direct3D device created. &m_d3dFeatureLevel, // Returns feature level of device created. &context // Returns the device immediate context. ); if (FAILED(hr)) { // If the initialization fails, fall back to the WARP device. // For more information on WARP, see: // http://go.microsoft.com/fwlink/?LinkId=286690 StarboardWinRT::ThrowIfFailed(D3D11CreateDevice(nullptr, D3D_DRIVER_TYPE_WARP, // Create a WARP device instead of a hardware device. 0, creationFlags, featureLevels, ARRAYSIZE(featureLevels), D3D11_SDK_VERSION, &device, &m_d3dFeatureLevel, &context)); } // Store pointers to the Direct3D 11.1 API device and immediate context. StarboardWinRT::ThrowIfFailed(device.As(&m_d3dDevice)); StarboardWinRT::ThrowIfFailed(context.As(&m_d3dContext)); }
// Install the shortcut HRESULT DesktopToastsApp::InstallShortcut(_In_z_ wchar_t *shortcutPath) { wchar_t exePath[MAX_PATH]; DWORD charWritten = GetModuleFileNameEx(GetCurrentProcess(), nullptr, exePath, ARRAYSIZE(exePath)); HRESULT hr = charWritten > 0 ? S_OK : E_FAIL; if (SUCCEEDED(hr)) { ComPtr<IShellLink> shellLink; hr = CoCreateInstance(CLSID_ShellLink, nullptr, CLSCTX_INPROC_SERVER, IID_PPV_ARGS(&shellLink)); if (SUCCEEDED(hr)) { hr = shellLink->SetPath(exePath); if (SUCCEEDED(hr)) { hr = shellLink->SetArguments(L""); if (SUCCEEDED(hr)) { ComPtr<IPropertyStore> propertyStore; hr = shellLink.As(&propertyStore); if (SUCCEEDED(hr)) { PROPVARIANT appIdPropVar; hr = InitPropVariantFromString(AppId, &appIdPropVar); if (SUCCEEDED(hr)) { hr = propertyStore->SetValue(PKEY_AppUserModel_ID, appIdPropVar); if (SUCCEEDED(hr)) { hr = propertyStore->Commit(); if (SUCCEEDED(hr)) { ComPtr<IPersistFile> persistFile; hr = shellLink.As(&persistFile); if (SUCCEEDED(hr)) { hr = persistFile->Save(shortcutPath, TRUE); } } } PropVariantClear(&appIdPropVar); } } } } } } return hr; }
void D3DRenderer::CreateDeviceResources() { // This flag is required in order to enable compatibility with Direct2D UINT creationFlags = D3D11_CREATE_DEVICE_BGRA_SUPPORT; ComPtr<IDXGIDevice> dxgiDevice; #if defined(_DEBUG) // If the project is in a debug build, enable debugging via SDK Layers with this flag creationFlags |= D3D11_CREATE_DEVICE_DEBUG; #endif // This array defines the ordering of feature levels that D3D should attempt to create D3D_FEATURE_LEVEL featureLevels[] = { D3D_FEATURE_LEVEL_11_1, D3D_FEATURE_LEVEL_11_0, D3D_FEATURE_LEVEL_10_1, D3D_FEATURE_LEVEL_10_0, D3D_FEATURE_LEVEL_9_3 }; ComPtr<ID3D11Device> device; ComPtr<ID3D11DeviceContext> context; DX::ThrowIfFailed( D3D11CreateDevice( nullptr, // specify null to use the default adapter D3D_DRIVER_TYPE_HARDWARE, nullptr, // leave as null if hardware is used creationFlags, // optionally set debug and Direct2D compatibility flags featureLevels, ARRAYSIZE(featureLevels), D3D11_SDK_VERSION, // always set this to D3D11_SDK_VERSION &device, &m_featureLevel, &context ) ); DX::ThrowIfFailed( device.As(&m_d3dDevice) ); DX::ThrowIfFailed( context.As(&m_d3dContext) ); // Obtain the underlying DXGI device of the Direct3D device DX::ThrowIfFailed( m_d3dDevice.As(&dxgiDevice) ); }
// These are the resources that depend on the device. void Direct3DBase::CreateDeviceResources() { // This flag adds support for surfaces with a different color channel ordering // than the API default. It is required for compatibility with Direct2D. UINT creationFlags = D3D11_CREATE_DEVICE_BGRA_SUPPORT; #if defined(_DEBUG) // If the project is in a debug build, enable debugging via SDK Layers with this flag. creationFlags |= D3D11_CREATE_DEVICE_DEBUG; #endif // This array defines the set of DirectX hardware feature levels this app will support. // Note the ordering should be preserved. // Don't forget to declare your application's minimum required feature level in its // description. All applications are assumed to support 9.1 unless otherwise stated. D3D_FEATURE_LEVEL featureLevels[] = { D3D_FEATURE_LEVEL_11_1, D3D_FEATURE_LEVEL_11_0, D3D_FEATURE_LEVEL_10_1, D3D_FEATURE_LEVEL_10_0, D3D_FEATURE_LEVEL_9_3 }; // Create the Direct3D 11 API device object and a corresponding context. ComPtr<ID3D11Device> device; ComPtr<ID3D11DeviceContext> context; DX::ThrowIfFailed( D3D11CreateDevice( nullptr, // Specify nullptr to use the default adapter. D3D_DRIVER_TYPE_HARDWARE, nullptr, creationFlags, // Set set debug and Direct2D compatibility flags. featureLevels, // List of feature levels this app can support. ARRAYSIZE(featureLevels), D3D11_SDK_VERSION, // Always set this to D3D11_SDK_VERSION. &device, // Returns the Direct3D device created. &m_featureLevel, // Returns feature level of device created. &context // Returns the device immediate context. ) ); // Get the Direct3D 11.1 API device and context interfaces. DX::ThrowIfFailed( device.As(&m_d3dDevice) ); DX::ThrowIfFailed( context.As(&m_d3dContext) ); }
// Deliver samples for every request client made void CMediaStream::DeliverSamples() { // Check if we have both: samples available in the queue and requests in request list. while (!_samples.IsEmpty() && !_tokens.IsEmpty()) { ComPtr<IUnknown> spEntry; ComPtr<IMFSample> spSample; ComPtr<IUnknown> spToken; BOOL fDrop = FALSE; // Get the entry ThrowIfError(_samples.RemoveFront(&spEntry)); if (SUCCEEDED(spEntry.As(&spSample))) { fDrop = ShouldDropSample(spSample.Get()); if (!fDrop) { // Get the request token ThrowIfError(_tokens.RemoveFront(&spToken)); if (spToken) { // If token was not null set the sample attribute. ThrowIfError(spSample->SetUnknown(MFSampleExtension_Token, spToken.Get())); } if (_fDiscontinuity) { // If token was not null set the sample attribute. ThrowIfError(spSample->SetUINT32(MFSampleExtension_Discontinuity, TRUE)); _fDiscontinuity = false; } // Send a sample event. ThrowIfError(_spEventQueue->QueueEventParamUnk(MEMediaSample, GUID_NULL, S_OK, spSample.Get())); } else { _fDiscontinuity = true; } } else { ComPtr<IMFMediaType> spMediaType; ThrowIfError(spEntry.As(&spMediaType)); // Send a sample event. ThrowIfError(_spEventQueue->QueueEventParamUnk(MEStreamFormatChanged, GUID_NULL, S_OK, spMediaType.Get())); } } }
// Install the shortcut HRESULT LinkHelper::installShortcut(const std::wstring &shortcutPath,const std::wstring &exePath, const std::wstring &appID) { std::wcout << L"Installing shortcut: " << shortcutPath << L" " << exePath << L" " << appID << std::endl; HRESULT hr = S_OK; if (SUCCEEDED(hr)) { ComPtr<IShellLink> shellLink; hr = CoCreateInstance(CLSID_ShellLink, nullptr, CLSCTX_INPROC_SERVER, IID_PPV_ARGS(&shellLink)); if (SUCCEEDED(hr)) { hr = shellLink->SetPath(exePath.c_str()); if (SUCCEEDED(hr)) { hr = shellLink->SetArguments(L""); if (SUCCEEDED(hr)) { ComPtr<IPropertyStore> propertyStore; hr = shellLink.As(&propertyStore); if (SUCCEEDED(hr)) { PROPVARIANT appIdPropVar; hr = InitPropVariantFromString(appID.c_str(), &appIdPropVar); if (SUCCEEDED(hr)) { hr = propertyStore->SetValue(PKEY_AppUserModel_ID, appIdPropVar); if (SUCCEEDED(hr)) { hr = propertyStore->Commit(); if (SUCCEEDED(hr)) { ComPtr<IPersistFile> persistFile; hr = shellLink.As(&persistFile); if (SUCCEEDED(hr)) { hr = persistFile->Save(shortcutPath.c_str(), TRUE); } } } PropVariantClear(&appIdPropVar); } } } } } } return hr; }
ComPtr<IBuffer> createIBufferFromData(const char *data, qint32 size) { static ComPtr<IBufferFactory> bufferFactory; HRESULT hr; if (!bufferFactory) { hr = RoGetActivationFactory(HString::MakeReference(RuntimeClass_Windows_Storage_Streams_Buffer).Get(), IID_PPV_ARGS(&bufferFactory)); Q_ASSERT_SUCCEEDED(hr); } ComPtr<IBuffer> buffer; const UINT32 length = size; hr = bufferFactory->Create(length, &buffer); Q_ASSERT_SUCCEEDED(hr); hr = buffer->put_Length(length); Q_ASSERT_SUCCEEDED(hr); ComPtr<Windows::Storage::Streams::IBufferByteAccess> byteArrayAccess; hr = buffer.As(&byteArrayAccess); Q_ASSERT_SUCCEEDED(hr); byte *bytes; hr = byteArrayAccess->Buffer(&bytes); Q_ASSERT_SUCCEEDED(hr); memcpy(bytes, data, length); return buffer; }
// Updates the text to be displayed. void SampleFpsTextRenderer::Update(DX::StepTimer const& timer) { // Update display text. uint32 fps = timer.GetFramesPerSecond(); m_text = (fps > 0) ? std::to_wstring(fps) + L" FPS" : L" - FPS"; ComPtr<IDWriteTextLayout> textLayout; DX::ThrowIfFailed( m_deviceResources->GetDWriteFactory()->CreateTextLayout( m_text.c_str(), (uint32) m_text.length(), m_textFormat.Get(), 240.0f, // Max width of the input text. 50.0f, // Max height of the input text. &textLayout ) ); DX::ThrowIfFailed( textLayout.As(&m_textLayout) ); DX::ThrowIfFailed( m_textLayout->GetMetrics(&m_textMetrics) ); }
// Initializes D2D resources used for text rendering. SampleFpsTextRenderer::SampleFpsTextRenderer(const std::shared_ptr<DX::DeviceResources>& deviceResources) : m_text(L""), m_deviceResources(deviceResources) { ZeroMemory(&m_textMetrics, sizeof(DWRITE_TEXT_METRICS)); // Create device independent resources ComPtr<IDWriteTextFormat> textFormat; DX::ThrowIfFailed( m_deviceResources->GetDWriteFactory()->CreateTextFormat( L"Segoe UI", nullptr, DWRITE_FONT_WEIGHT_LIGHT, DWRITE_FONT_STYLE_NORMAL, DWRITE_FONT_STRETCH_NORMAL, 32.0f, L"en-US", &textFormat ) ); DX::ThrowIfFailed( textFormat.As(&m_textFormat) ); DX::ThrowIfFailed( m_textFormat->SetParagraphAlignment(DWRITE_PARAGRAPH_ALIGNMENT_NEAR) ); DX::ThrowIfFailed( m_deviceResources->GetD2DFactory()->CreateDrawingStateBlock(&m_stateBlock) ); CreateDeviceDependentResources(); }
void CrossNodeResources::LoadPipeline() { // Describe and create the command queues. // Each GPU node needs its own command queue. D3D12_COMMAND_QUEUE_DESC queueDesc = {}; queueDesc.Flags = D3D12_COMMAND_QUEUE_FLAG_NONE; queueDesc.Type = D3D12_COMMAND_LIST_TYPE_DIRECT; std::vector<IUnknown*> ppQueues(Settings::BackBufferCount); std::vector<UINT> creationNodes(Settings::BackBufferCount); for (UINT n = 0; n < Settings::BackBufferCount; n++) { UINT nodeIndex = n % Settings::NodeCount; creationNodes[n] = 1 << nodeIndex; queueDesc.NodeMask = creationNodes[n]; if (!m_queues[nodeIndex]) { ThrowIfFailed(m_device->CreateCommandQueue(&queueDesc, IID_PPV_ARGS(&m_queues[nodeIndex]))); } ppQueues[n] = m_queues[nodeIndex].Get(); } // Describe and create the swap chain. DXGI_SWAP_CHAIN_DESC1 swapChainDesc = {}; swapChainDesc.BufferCount = Settings::BackBufferCount; swapChainDesc.Width = Settings::Width; swapChainDesc.Height = Settings::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; // It is recommended to always use the tearing flag when it is available. swapChainDesc.Flags = Settings::TearingSupport ? DXGI_SWAP_CHAIN_FLAG_ALLOW_TEARING : 0; ComPtr<IDXGISwapChain1> swapChain; ThrowIfFailed(m_factory->CreateSwapChainForCoreWindow( ppQueues[0], // 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)); if (Settings::NodeCount > 1) { // Set up the swap chain to allow back buffers to live on multiple GPU nodes. ThrowIfFailed(m_swapChain->ResizeBuffers1( swapChainDesc.BufferCount, swapChainDesc.Width, swapChainDesc.Height, DXGI_FORMAT_R8G8B8A8_UNORM, swapChainDesc.Flags, creationNodes.data(), ppQueues.data())); } }
bool CoreWindowNativeWindow::registerForSizeChangeEvents() { ComPtr<IWindowSizeChangedEventHandler> sizeChangedHandler; HRESULT result = Microsoft::WRL::MakeAndInitialize<CoreWindowSizeChangedHandler>(sizeChangedHandler.ReleaseAndGetAddressOf(), this->shared_from_this()); if (SUCCEEDED(result)) { result = mCoreWindow->add_SizeChanged(sizeChangedHandler.Get(), &mSizeChangedEventToken); } #if defined(ANGLE_ENABLE_WINDOWS_STORE) && (WINAPI_FAMILY == WINAPI_FAMILY_PHONE_APP) ComPtr<IDisplayOrientationEventHandler> orientationChangedHandler; result = sizeChangedHandler.As(&orientationChangedHandler); if (SUCCEEDED(result)) { result = mDisplayInformation->add_OrientationChanged(orientationChangedHandler.Get(), &mOrientationChangedEventToken); orientationChangedHandler->Invoke(mDisplayInformation.Get(), nullptr); } #endif if (SUCCEEDED(result)) { return true; } return false; }
HRESULT GetSwapChainPanelSize( const ComPtr<ABI::Windows::UI::Xaml::Controls::ISwapChainPanel> &swapChainPanel, const ComPtr<ICoreDispatcher> &dispatcher, SIZE *windowSize) { ComPtr<IUIElement> uiElement; Size renderSize = {0, 0}; HRESULT result = swapChainPanel.As(&uiElement); if (SUCCEEDED(result)) { result = RunOnUIThread( [uiElement, &renderSize] { return uiElement->get_RenderSize(&renderSize); }, dispatcher); } if (SUCCEEDED(result)) { *windowSize = { lround(renderSize.Width), lround(renderSize.Height) }; } return result; }
ComPtr<CanvasLinearGradientBrush> CanvasLinearGradientBrushManager::CreateNew( ICanvasResourceCreator* resourceCreator, UINT32 gradientStopCount, CanvasGradientStop* gradientStops, CanvasEdgeBehavior edgeBehavior, CanvasAlphaMode alphaMode, CanvasColorSpace preInterpolationSpace, CanvasColorSpace postInterpolationSpace, CanvasBufferPrecision bufferPrecision) { ComPtr<ICanvasDevice> device; ThrowIfFailed(resourceCreator->get_Device(&device)); ComPtr<ICanvasDeviceInternal> deviceInternal; ThrowIfFailed(device.As(&deviceInternal)); ComPtr<ID2D1GradientStopCollection1> stopCollection = deviceInternal->CreateGradientStopCollection( gradientStopCount, gradientStops, edgeBehavior, preInterpolationSpace, postInterpolationSpace, bufferPrecision, alphaMode); auto d2dBrush = deviceInternal->CreateLinearGradientBrush(stopCollection.Get()); auto canvasLinearGradientBrush = Make<CanvasLinearGradientBrush>( shared_from_this(), d2dBrush.Get(), device.Get()); CheckMakeResult(canvasLinearGradientBrush); return canvasLinearGradientBrush; }
void CanvasImageSource::SetResourceCreator(ICanvasResourceCreator* resourceCreator) { CheckInPointer(resourceCreator); ComPtr<ICanvasDevice> device; ThrowIfFailed(resourceCreator->get_Device(&device)); // // Get the D2D device and pass this to the underlying surface image // source. // ComPtr<ICanvasDeviceInternal> deviceInternal; ThrowIfFailed(device.As(&deviceInternal)); ComPtr<ID2D1Device1> d2dDevice = deviceInternal->GetD2DDevice(); ComPtr<ISurfaceImageSourceNativeWithD2D> sisNative; ThrowIfFailed(GetComposableBase().As(&sisNative)); // // Set the device. SiS does some validation here - for example, if the // width/height are 0 then this will fail with E_INVALIDARG. We don't // add additional validation around this since CanvasImageSource derives // from SurfaceImageSource and we want to be consistent with the // existing XAML behavior. // ThrowIfFailed(sisNative->SetDevice(d2dDevice.Get())); // // Remember the canvas device we're now using. We do this after we're // certain that all the previous steps succeeded (so we don't end up // with m_device referencing a device that we failed to set). // m_device = device; }
// Sets the color space for the swap chain in order to handle HDR output. void DeviceResources::UpdateColorSpace() { DXGI_COLOR_SPACE_TYPE colorSpace = DXGI_COLOR_SPACE_RGB_FULL_G22_NONE_P709; bool isDisplayHDR10 = false; #if defined(NTDDI_WIN10_RS2) if (m_swapChain) { ComPtr<IDXGIOutput> output; if (SUCCEEDED(m_swapChain->GetContainingOutput(output.GetAddressOf()))) { ComPtr<IDXGIOutput6> output6; if (SUCCEEDED(output.As(&output6))) { DXGI_OUTPUT_DESC1 desc; ThrowIfFailed(output6->GetDesc1(&desc)); if (desc.ColorSpace == DXGI_COLOR_SPACE_RGB_FULL_G2084_NONE_P2020) { // Display output is HDR10. isDisplayHDR10 = true; } } } } #endif if ((m_options & c_EnableHDR) && isDisplayHDR10) { switch (m_backBufferFormat) { case DXGI_FORMAT_R10G10B10A2_UNORM: // The application creates the HDR10 signal. colorSpace = DXGI_COLOR_SPACE_RGB_FULL_G2084_NONE_P2020; break; case DXGI_FORMAT_R16G16B16A16_FLOAT: // The system creates the HDR10 signal; application uses linear values. colorSpace = DXGI_COLOR_SPACE_RGB_FULL_G10_NONE_P709; break; default: break; } } m_colorSpace = colorSpace; ComPtr<IDXGISwapChain3> swapChain3; if (SUCCEEDED(m_swapChain.As(&swapChain3))) { UINT colorSpaceSupport = 0; if (SUCCEEDED(swapChain3->CheckColorSpaceSupport(colorSpace, &colorSpaceSupport)) && (colorSpaceSupport & DXGI_SWAP_CHAIN_COLOR_SPACE_SUPPORT_FLAG_PRESENT)) { ThrowIfFailed(swapChain3->SetColorSpace1(colorSpace)); } } }
void ShaderPass::SetViewport(const D3D11_VIEWPORT* viewport) { // can't change viewport while rendering assert(!Rendering); if (viewport) { Viewport = *viewport; } else { Viewport = {}; if (RenderTargets[0]) { ComPtr<ID3D11Resource> resource; RenderTargets[0]->GetResource(&resource); ComPtr<ID3D11Texture2D> texture; resource.As(&texture); D3D11_TEXTURE2D_DESC td{}; texture->GetDesc(&td); Viewport.Width = static_cast<float>(td.Width); Viewport.Height = static_cast<float>(td.Height); Viewport.MaxDepth = 1.f; } } }
void CMediaStream::CleanSampleQueue() { auto pos = _samples.FrontPosition(); ComPtr<IUnknown> spEntry; ComPtr<IMFSample> spSample; if (_fVideo) { // For video streams leave first key frame. for (;SUCCEEDED(_samples.GetItemPos(pos, spEntry.ReleaseAndGetAddressOf())); pos = _samples.Next(pos)) { if (SUCCEEDED(spEntry.As(&spSample)) && MFGetAttributeUINT32(spSample.Get(), MFSampleExtension_CleanPoint, 0)) { break; } } } _samples.Clear(); if (spSample != nullptr) { ThrowIfError(_samples.InsertFront(spSample.Get())); } }
inline ComPtr<IDXGISwapChain1> CreateSwapChainForHwnd(ComPtr<ID3D11Device> const & d3dDevice, HWND windowHandle) { ASSERT(d3dDevice); ASSERT(windowHandle); ComPtr<IDXGIDevice> dxgiDevice; HR(d3dDevice.As(&dxgiDevice)); ComPtr<IDXGIAdapter> dxgiAdapter; HR(dxgiDevice->GetAdapter(dxgiAdapter.GetAddressOf())); ComPtr<IDXGIFactory2> dxgiFactory; HR(dxgiAdapter->GetParent(__uuidof(dxgiFactory), reinterpret_cast<void **>(dxgiFactory.GetAddressOf()))); DXGI_SWAP_CHAIN_DESC1 desc{}; desc.Format = DXGI_FORMAT_B8G8R8A8_UNORM; desc.SampleDesc.Count = 1; desc.BufferCount = 2; // Swapchain contains 2 buffers ( front and back buffer ) desc.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT; ComPtr<IDXGISwapChain1> swapChain; HR(dxgiFactory->CreateSwapChainForHwnd(d3dDevice.Get(), windowHandle, &desc, nullptr, nullptr, swapChain.GetAddressOf())); return swapChain; }
void SpriteBatch::Begin() { // Reset internal sprite data. m_numSpritesDrawn = 0; m_spritesInRun = 0; m_spriteRuns.clear(); // Get the current render target dimensions and logical DPI. ComPtr<ID3D11RenderTargetView> renderTargetView; m_d3dContext->OMGetRenderTargets( 1, &renderTargetView, nullptr ); ComPtr<ID3D11Resource> renderTarget; renderTargetView->GetResource(&renderTarget); ComPtr<ID3D11Texture2D> renderTargetTexture; renderTarget.As(&renderTargetTexture); D3D11_TEXTURE2D_DESC renderTargetTextureDesc; renderTargetTexture->GetDesc(&renderTargetTextureDesc); m_renderTargetSize = float2( static_cast<float>(renderTargetTextureDesc.Width), static_cast<float>(renderTargetTextureDesc.Height) ); m_dpi = Windows::Graphics::Display::DisplayInformation::GetForCurrentView()->LogicalDpi; }
//--------------------------------------------------------------------------------- static size_t _WICBitsPerPixel( REFGUID targetGuid ) { IWICImagingFactory* pWIC = _GetWIC(); if ( !pWIC ) return 0; ComPtr<IWICComponentInfo> cinfo; if ( FAILED( pWIC->CreateComponentInfo( targetGuid, cinfo.GetAddressOf() ) ) ) return 0; WICComponentType type; if ( FAILED( cinfo->GetComponentType( &type ) ) ) return 0; if ( type != WICPixelFormat ) return 0; ComPtr<IWICPixelFormatInfo> pfinfo; if ( FAILED( cinfo.As( &pfinfo ) ) ) return 0; UINT bpp; if ( FAILED( pfinfo->GetBitsPerPixel( &bpp ) ) ) return 0; return bpp; }
void SetWindow(ABI::Windows::UI::Core::ICoreWindow* window) { using namespace Microsoft::WRL; using namespace Microsoft::WRL::Wrappers; if (mWindow.Get() == window) return; RemoveHandlers(); mWindow = window; if (!window) return; typedef __FITypedEventHandler_2_Windows__CUI__CCore__CCoreWindow_Windows__CUI__CCore__CWindowActivatedEventArgs ActivatedHandler; HRESULT hr = window->add_Activated(Callback<ActivatedHandler>(Activated).Get(), &mActivatedToken); ThrowIfFailed(hr); ComPtr<ABI::Windows::UI::Core::ICoreDispatcher> dispatcher; hr = window->get_Dispatcher( dispatcher.GetAddressOf() ); ThrowIfFailed(hr); ComPtr<ABI::Windows::UI::Core::ICoreAcceleratorKeys> keys; hr = dispatcher.As(&keys); ThrowIfFailed(hr); typedef __FITypedEventHandler_2_Windows__CUI__CCore__CCoreDispatcher_Windows__CUI__CCore__CAcceleratorKeyEventArgs AcceleratorKeyHandler; hr = keys->add_AcceleratorKeyActivated( Callback<AcceleratorKeyHandler>(AcceleratorKeyEvent).Get(), &mAcceleratorKeyToken); ThrowIfFailed(hr); }
void cleanupShortcut() { static const int maxFileLen = MAX_PATH * 10; QString path = systemShortcutPath() + qsl("Telegram.lnk"); std::wstring p = QDir::toNativeSeparators(path).toStdWString(); DWORD attributes = GetFileAttributes(p.c_str()); if (attributes >= 0xFFFFFFF) return; // file does not exist ComPtr<IShellLink> shellLink; HRESULT hr = CoCreateInstance(CLSID_ShellLink, nullptr, CLSCTX_INPROC_SERVER, IID_PPV_ARGS(&shellLink)); if (!SUCCEEDED(hr)) return; ComPtr<IPersistFile> persistFile; hr = shellLink.As(&persistFile); if (!SUCCEEDED(hr)) return; hr = persistFile->Load(p.c_str(), STGM_READWRITE); if (!SUCCEEDED(hr)) return; WCHAR szGotPath[MAX_PATH]; WIN32_FIND_DATA wfd; hr = shellLink->GetPath(szGotPath, MAX_PATH, (WIN32_FIND_DATA*)&wfd, SLGP_SHORTPATH); if (!SUCCEEDED(hr)) return; if (QDir::toNativeSeparators(cExeDir() + cExeName()).toStdWString() == szGotPath) { QFile().remove(path); } }
void CopyStops( ComPtr<ID2D1GradientStopCollection> const& stopCollection, UINT32* valueCount, CanvasGradientStop** valueElements) { ComPtr<ID2D1GradientStopCollection1> stopCollection1; ThrowIfFailed(stopCollection.As(&stopCollection1)); std::vector<D2D1_GRADIENT_STOP> d2dStops; UINT stopCount = stopCollection1->GetGradientStopCount(); assert(stopCount != 0); // Enforced by D2D d2dStops.resize(stopCount); stopCollection1->GetGradientStops1(&(d2dStops[0]), stopCount); auto stops = TransformToComArray<CanvasGradientStop>(d2dStops.begin(), d2dStops.end(), [](D2D1_GRADIENT_STOP const& d2dStop) { // TODO #837: Decide what to do about high-color gradient stops. return CanvasGradientStop{ d2dStop.position, ToWindowsColor(d2dStop.color) }; }); stops.Detach(valueCount, valueElements); }
void GraphicsManager::Impl::CreateDeviceResources() { UINT creationFlags = D3D11_CREATE_DEVICE_BGRA_SUPPORT; #ifdef _DEBUG creationFlags |= D3D11_CREATE_DEVICE_DEBUG; #endif D3D_FEATURE_LEVEL featureLevels[] = { D3D_FEATURE_LEVEL_11_1, D3D_FEATURE_LEVEL_11_0, D3D_FEATURE_LEVEL_10_1, D3D_FEATURE_LEVEL_10_0, D3D_FEATURE_LEVEL_9_3, D3D_FEATURE_LEVEL_9_2, D3D_FEATURE_LEVEL_9_1 }; ComPtr<ID3D11Device> device; ComPtr<ID3D11DeviceContext> context; Utility::ThrowIfFailed( D3D11CreateDevice( nullptr, //Use Default Adapter D3D_DRIVER_TYPE_HARDWARE, nullptr, creationFlags, featureLevels, ARRAYSIZE( featureLevels ), D3D11_SDK_VERSION, &device, &featureLevel, &context ) ); Utility::ThrowIfFailed( device.As( &d3dDevice ) ); Utility::ThrowIfFailed( context.As( &d3dContext ) ); Utility::ThrowIfFailed( d3dDevice.As( &dxgiDevice ) ); //d3dDevice->CreateDeferredContext1(0, &d3dContext); //Common States commonStates = std::make_unique<CommonStates>( d3dDevice.Get() ); //Viewports deviceViewport = CD3D11_VIEWPORT(); swapChain = nullptr; }//CreateDeviceResources()