static IDXGIFactory *GetDXGIFactoryFromDevice(ID3D11Device *device) { IDXGIDevice *dxgiDevice = nullptr; HRESULT result = device->QueryInterface(__uuidof(IDXGIDevice), reinterpret_cast<void **>(&dxgiDevice)); if (FAILED(result)) { return nullptr; } IDXGIAdapter *dxgiAdapter = nullptr; result = dxgiDevice->GetParent(__uuidof(IDXGIAdapter), reinterpret_cast<void **>(&dxgiAdapter)); SafeRelease(dxgiDevice); if (FAILED(result)) { return nullptr; } IDXGIFactory *dxgiFactory = nullptr; result = dxgiAdapter->GetParent(__uuidof(IDXGIFactory), reinterpret_cast<void **>(&dxgiFactory)); SafeRelease(dxgiAdapter); if (FAILED(result)) { return nullptr; } return dxgiFactory; }
void D3D11RenderWindow::_createSwapChain() { // Fill out a DXGI_SWAP_CHAIN_DESC to describe our swap chain. DXGI_SWAP_CHAIN_DESC sd; sd.BufferDesc.Width = mWidth; sd.BufferDesc.Height = mHeight; sd.BufferDesc.RefreshRate.Numerator = 60; sd.BufferDesc.RefreshRate.Denominator = 1; sd.BufferDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM; sd.BufferDesc.ScanlineOrdering = DXGI_MODE_SCANLINE_ORDER_UNSPECIFIED; sd.BufferDesc.Scaling = DXGI_MODE_SCALING_UNSPECIFIED; // Use 4X MSAA? if (mEnable4xMsaa) { sd.SampleDesc.Count = 4; sd.SampleDesc.Quality = m4xMsaaQuality - 1; } // No MSAA else { sd.SampleDesc.Count = 1; sd.SampleDesc.Quality = 0; } sd.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT; sd.BufferCount = 2; sd.OutputWindow = mhMainWnd; sd.Windowed = true; sd.SwapEffect = DXGI_SWAP_EFFECT_DISCARD; sd.Flags = 0; // To correctly create the swap chain, we must use the IDXGIFactory that was // used to create the device. If we tried to use a different IDXGIFactory instance // (by calling CreateDXGIFactory), we get an error: "IDXGIFactory::CreateSwapChain: // This function is being called with a device from a different IDXGIFactory." IDXGIDevice* dxgiDevice = 0; HR(md3dDevice->QueryInterface(__uuidof(IDXGIDevice), (void**)&dxgiDevice)); IDXGIAdapter* dxgiAdapter = 0; HR(dxgiDevice->GetParent(__uuidof(IDXGIAdapter), (void**)&dxgiAdapter)); IDXGIFactory* dxgiFactory = 0; HR(dxgiAdapter->GetParent(__uuidof(IDXGIFactory), (void**)&dxgiFactory)); HR(dxgiFactory->CreateSwapChain(md3dDevice, &sd, &mSwapChain)); ReleaseCOM(dxgiDevice); ReleaseCOM(dxgiAdapter); ReleaseCOM(dxgiFactory); // The remaining steps that need to be carried out for d3d creation // also need to be executed every time the window is resized. So // just call the OnResize method here to avoid code duplication. _updateSwapChain(); }
void D3DContext::InitD3D(HWND hWnd) { m_MSAAEnabled = true; HRESULT hr = D3D11CreateDevice(NULL, D3D_DRIVER_TYPE_HARDWARE, NULL, m_DebugLayerEnabled ? D3D11_CREATE_DEVICE_DEBUG : D3D11_CREATE_DEVICE_SINGLETHREADED, NULL, NULL, D3D11_SDK_VERSION, &dev, &m_D3DFeatureLevel, &devcon); dev->CheckMultisampleQualityLevels(DXGI_FORMAT_R8G8B8A8_UNORM, 4, &m_MSAAQuality); // assert(m_MSAAQuality > 0); DXGI_SWAP_CHAIN_DESC scd; ZeroMemory(&scd, sizeof(DXGI_SWAP_CHAIN_DESC)); scd.BufferDesc.Width = m_Properties.width; scd.BufferDesc.Height = m_Properties.height; scd.BufferDesc.RefreshRate.Numerator = 60; scd.BufferDesc.RefreshRate.Denominator = 1; scd.BufferDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM; scd.SampleDesc.Count = m_MSAAEnabled ? 4 : 1; scd.SampleDesc.Quality = m_MSAAEnabled ? (m_MSAAQuality - 1) : 0; scd.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT; scd.BufferCount = 3; scd.OutputWindow = hWnd; scd.Windowed = !m_Properties.fullscreen; scd.SwapEffect = DXGI_SWAP_EFFECT_DISCARD; scd.Flags = DXGI_SWAP_CHAIN_FLAG_ALLOW_MODE_SWITCH; IDXGIDevice* dxgiDevice = 0; IDXGIAdapter* dxgiAdapter = 0; IDXGIFactory* dxgiFactory = 0; dev->QueryInterface(__uuidof(IDXGIDevice), (void**)&dxgiDevice); dxgiDevice->GetParent(__uuidof(IDXGIAdapter), (void**)&dxgiAdapter); dxgiAdapter->GetParent(__uuidof(IDXGIFactory), (void**)&dxgiFactory); dxgiFactory->CreateSwapChain(dev, &scd, &swapchain); dxgiFactory->Release(); dxgiAdapter->Release(); dxgiDevice->Release(); if (m_DebugLayerEnabled) { dev->QueryInterface(__uuidof(ID3D11Debug), reinterpret_cast<void**>(&m_DebugLayer)); m_DebugLayer->ReportLiveDeviceObjects(D3D11_RLDO_SUMMARY); ID3D11InfoQueue* infoQueue; dev->QueryInterface(__uuidof(ID3D11InfoQueue), reinterpret_cast<void**>(&infoQueue)); D3D11_MESSAGE_ID hide[] = { D3D11_MESSAGE_ID_DEVICE_DRAW_SAMPLER_NOT_SET }; D3D11_INFO_QUEUE_FILTER filter; memset(&filter, 0, sizeof(filter)); filter.DenyList.NumIDs = 1; filter.DenyList.pIDList = hide; infoQueue->AddStorageFilterEntries(&filter); } Resize(); }
bool CDuplicateOutputDx11::CreateOutputDuplicator() { SAFE_RELEASE(m_pOutputDuplication); HRESULT hRes = S_OK; IDXGIDevice* pDxgiDevice = nullptr; hRes = m_pDevice->QueryInterface(__uuidof(IDXGIDevice), reinterpret_cast<void**>(&pDxgiDevice)); if (!SUCCEEDED(hRes)) { DOLOG("m_pDevice->QueryInterface failed!"); return false; } IDXGIAdapter* pDxgiAdapter = nullptr; hRes = pDxgiDevice->GetParent(__uuidof(IDXGIAdapter), reinterpret_cast<void**>(&pDxgiAdapter)); SAFE_RELEASE(pDxgiDevice); if (!SUCCEEDED(hRes)) { DOLOG("pDxgiDevice->GetParent failed!"); return false; } DXGI_ADAPTER_DESC descAdapter; pDxgiAdapter->GetDesc(&descAdapter); // Get output IDXGIOutput* pDxgiOutput = nullptr; hRes = pDxgiAdapter->EnumOutputs(0, &pDxgiOutput); SAFE_RELEASE(pDxgiAdapter); if (!SUCCEEDED(hRes)) { DOLOG("pDxgiAdapter->EnumOutputs failed!"); return false; } // Get output1 IDXGIOutput1* pDxgiOutput1 = nullptr; hRes = pDxgiOutput->QueryInterface(__uuidof(IDXGIOutput1), reinterpret_cast<void**>(&pDxgiOutput1)); SAFE_RELEASE(pDxgiOutput); if (!SUCCEEDED(hRes)) { DOLOG("pDxgiOutput->QueryInterface failed!"); return false; } // Get duplicate hRes = pDxgiOutput1->DuplicateOutput(m_pDevice, &m_pOutputDuplication); SAFE_RELEASE(pDxgiOutput1); if (!SUCCEEDED(hRes)) { DOLOG("pDxgiOutput1->DuplicateOutput"); return false; } return true; }
bool TRenderDevice::CreateSwapChain(){ IDXGIDevice* device; if (FAILED(Device->QueryInterface(__uuidof(IDXGIDevice), (void**) &device))){ MessageBox(0,L"获取设备接口失败",0,0); return false; } IDXGIAdapter* adapter; if (FAILED(device->GetParent(__uuidof(IDXGIAdapter), (void**) &adapter))){ MessageBox(0,L"获取适配器接口失败",0,0); return false; } IDXGIFactory* factory; if (FAILED(adapter->GetParent(__uuidof(IDXGIFactory), (void**) &factory))){ MessageBox(0,L"获取Factory接口失败",0,0); return false; } DXGI_SWAP_CHAIN_DESC sd; sd.BufferDesc.Width = RenderSize->GetRenderWidth(); sd.BufferDesc.Height = RenderSize->GetRenderHeight(); sd.BufferDesc.RefreshRate.Numerator = 60; sd.BufferDesc.RefreshRate.Denominator = 1; sd.BufferDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM; sd.BufferDesc.ScanlineOrdering = DXGI_MODE_SCANLINE_ORDER_UNSPECIFIED; sd.BufferDesc.Scaling = DXGI_MODE_SCALING_UNSPECIFIED; if (MsaaQuality>0){ sd.SampleDesc.Count = MsaaQuality; sd.SampleDesc.Quality = MsaaQuality - 1; }else{ sd.SampleDesc.Count=1; sd.SampleDesc.Quality=0; } sd.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT; sd.BufferCount = 1; sd.OutputWindow = RenderWindow->GetHWnd(); sd.Windowed = true; sd.SwapEffect = DXGI_SWAP_EFFECT_DISCARD; sd.Flags = 0; if (FAILED(factory->CreateSwapChain(Device, &sd, &SwapChain))){ MessageBox(0,L"创建SwapChain失败",0,0); return false; } device->Release(); adapter->Release(); factory->Release(); return true; }
//************************************************************************************************* // Create the swap chain for the device //************************************************************************************************* SBOOL RenderContext::createSwapChain(HWND clientWindow, SUINT clientWidth, SUINT clientHeight) { // Fill out DXGI swap chain description DXGI_SWAP_CHAIN_DESC sd; sd.BufferDesc.Width = clientWidth; sd.BufferDesc.Height = clientHeight; sd.BufferDesc.RefreshRate.Numerator = 60; sd.BufferDesc.RefreshRate.Denominator = 1; sd.BufferDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM; sd.BufferDesc.ScanlineOrdering = DXGI_MODE_SCANLINE_ORDER_UNSPECIFIED; sd.BufferDesc.Scaling = DXGI_MODE_SCALING_UNSPECIFIED; // Use 4x Msaa if(_4xMsaaEnabled) { sd.SampleDesc.Count = 4; sd.SampleDesc.Quality = _4xMsaaQuality - 1; } // No Msaa else { sd.SampleDesc.Count = 1; sd.SampleDesc.Quality = 0; } sd.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT; sd.BufferCount = 1; sd.OutputWindow = clientWindow; sd.Windowed = true; sd.SwapEffect = DXGI_SWAP_EFFECT_DISCARD; sd.Flags = 0; // Generate an IDXGI factory to properly initialize the swap chain IDXGIDevice* dxgiDevice = 0; HR(_d3dDevice->QueryInterface(__uuidof(IDXGIDevice), (void**)&dxgiDevice)); IDXGIAdapter* dxgiAdapter = 0; HR(dxgiDevice->GetParent(__uuidof(IDXGIAdapter), (void**)&dxgiAdapter)); IDXGIFactory* dxgiFactory = 0; HR(dxgiAdapter->GetParent(__uuidof(IDXGIFactory), (void**)&dxgiFactory)); HR(dxgiFactory->CreateSwapChain(_d3dDevice, &sd, &_swapChain)); ReleaseCOM(dxgiDevice); ReleaseCOM(dxgiAdapter); ReleaseCOM(dxgiFactory); return true; }
inline void DisableDXGIWindowChanges(IUnknown* device, HWND window) { IDXGIDevice * pDXGIDevice; ThrowIfFailed(device->QueryInterface(IID_PPV_ARGS(&pDXGIDevice))); IDXGIAdapter * pDXGIAdapter; ThrowIfFailed(pDXGIDevice->GetParent(IID_PPV_ARGS(&pDXGIAdapter))); IDXGIFactory * pIDXGIFactory; ThrowIfFailed(pDXGIAdapter->GetParent(IID_PPV_ARGS(&pIDXGIFactory))); ThrowIfFailed(pIDXGIFactory->MakeWindowAssociation(window, DXGI_MWA_NO_WINDOW_CHANGES | DXGI_MWA_NO_ALT_ENTER)); pIDXGIFactory->Release(); pDXGIAdapter->Release(); pDXGIDevice->Release(); }
static IDXGIFactory* FactoryFromDevice(ID3D11Device *device) { assert(device); IDXGIDevice *dxgiDevice = nullptr; DEBUG_HR(device->QueryInterface(__uuidof(IDXGIDevice), reinterpret_cast<void**>(&dxgiDevice))); IDXGIAdapter *dxgiAdapter = nullptr; DEBUG_HR(dxgiDevice->GetParent(__uuidof(IDXGIAdapter), reinterpret_cast<void**>(&dxgiAdapter))); IDXGIFactory *dxgiFactory = nullptr; DEBUG_HR(dxgiAdapter->GetParent(__uuidof(IDXGIFactory), reinterpret_cast<void**>(&dxgiFactory))); ReleaseCom(dxgiAdapter); ReleaseCom(dxgiDevice); return dxgiFactory; }
//======================================================================== // For specified ID3D10Device returns IDXGIFactory used to create it //======================================================================== IDXGIFactory *getDeviceFactory(ID3D10Device *device) { IDXGIDevice *dxgiDevice = 0; IDXGIAdapter *dxgiAdapter = 0; IDXGIFactory *dxgiFactory = 0; if (SUCCEEDED( device->QueryInterface(__uuidof(IDXGIDevice), (void**)&dxgiDevice) )) { if (SUCCEEDED( dxgiDevice->GetParent(__uuidof(IDXGIAdapter), (void**)&dxgiAdapter) )) { dxgiAdapter->GetParent(__uuidof(IDXGIFactory), (void**)&dxgiFactory); dxgiAdapter->Release(); } dxgiDevice->Release(); } return dxgiFactory; }
bool Renderer::CreateSwapChain() { // Determine buffer size RECT rect; GetClientRect(hwnd,&rect); // Create swap chain DXGI_SWAP_CHAIN_DESC SwapChainDesc; SwapChainDesc.BufferCount = 1; SwapChainDesc.BufferDesc.Width = rect.right - rect.left; SwapChainDesc.BufferDesc.Height = rect.bottom - rect.top; SwapChainDesc.BufferDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM; SwapChainDesc.BufferDesc.RefreshRate.Numerator = 60; SwapChainDesc.BufferDesc.RefreshRate.Denominator = 1; // 60/1 = 60 Hz SwapChainDesc.BufferDesc.Scaling = DXGI_MODE_SCALING_UNSPECIFIED; SwapChainDesc.BufferDesc.ScanlineOrdering = DXGI_MODE_SCANLINE_ORDER_UNSPECIFIED; SwapChainDesc.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT; SwapChainDesc.Flags = DXGI_SWAP_CHAIN_FLAG_ALLOW_MODE_SWITCH; SwapChainDesc.OutputWindow = hwnd; SwapChainDesc.SampleDesc.Count = 1; SwapChainDesc.SampleDesc.Quality = 0; // no AA SwapChainDesc.SwapEffect = DXGI_SWAP_EFFECT_DISCARD; SwapChainDesc.Windowed = true; // Obtain DXGI factory that was used to create the device // ??? IDXGIDevice* DXGIDevice; D3DDevice->QueryInterface(__uuidof(IDXGIDevice),(void**)&DXGIDevice); IDXGIAdapter* DXGIAdapter; DXGIDevice->GetParent(__uuidof(IDXGIAdapter),(void**)&DXGIAdapter); IDXGIFactory* DXGIFactory; DXGIAdapter->GetParent(__uuidof(IDXGIFactory),(void**)&DXGIFactory); // Use it if(DXGIFactory->CreateSwapChain(D3DDevice,&SwapChainDesc,&SwapChain) != S_OK) { MessageBox(hwnd,"Error creating swap chain","Error",MB_OK); return false; } // Release unused stuff DXGIDevice->Release(); DXGIAdapter->Release(); DXGIFactory->Release(); return true; }
Bool CImplDirectXGraphicsManager::Initialize( CGraphicsManager& manager ) { m_PublicInterface = &manager; UInt32 flags = 0; IDXGIAdapter* selectedAdapter = NULL; D3D10_DRIVER_TYPE driverType = D3D10_DRIVER_TYPE_HARDWARE; #ifdef SETUP_CONFIG_DEBUG flags = D3D10_CREATE_DEVICE_DEBUG; #endif AssertDXCall( D3D10CreateDevice( selectedAdapter, driverType, NULL, flags, D3D10_SDK_VERSION, &m_Device ) ); #ifdef SETUP_CONFIG_DEBUG IDXGIDevice * pDXGIDevice; IDXGIAdapter * pDXGIAdapter; AssertDXCall( m_Device->QueryInterface(__uuidof(IDXGIDevice), (void **)&pDXGIDevice) ); AssertDXCall( pDXGIDevice->GetParent(__uuidof(IDXGIAdapter), (void **)&pDXGIAdapter) ); DXGI_ADAPTER_DESC desc; pDXGIAdapter->GetDesc( &desc ); Char description[256]; WStringToString( desc.Description, description, 256 ); DebugLogInfo("-----------------------------"); DebugLogInfo("Description: %s", description ); DebugLogInfo("DedicatedVideoMemory: %f mo", desc.DedicatedVideoMemory / 1024.0f / 1024.0f ); DebugLogInfo("DedicatedSystemMemory: %f mo", desc.DedicatedSystemMemory / 1024.0f / 1024.0f ); DebugLogInfo("SharedSystemMemory: %f mo", desc.SharedSystemMemory / 1024.0f / 1024.0f ); DebugLogInfo("-----------------------------"); #endif return TRUE; }
// // FUNCTION: GraphicsDeviceInterface::Initialize() // // PURPOSE: Initializes Direct3D // bool GraphicsDeviceInterface::Initialize(HWND hWnd, WindowSize* wind) { HRESULT hResult; // Clear the struct ZeroMemory(&scd, sizeof(DXGI_SWAP_CHAIN_DESC)); // Set the swap chain values scd.BufferCount = 1; // one back buffer scd.BufferDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM; // use 32 bit color scd.BufferDesc.Width = wind->getWidth(); // set width using windowSize object scd.BufferDesc.Height = wind->getHeight(); // set height using windowSize object scd.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT; // swap chain is output scd.OutputWindow = hWnd; // window to render into scd.SampleDesc.Count = 4; // use 4 multisamples for antialiasing scd.Windowed = wind->getWindowed(); // Sets windowed mode scd.Flags = DXGI_SWAP_CHAIN_FLAG_ALLOW_MODE_SWITCH; // Allow full-screen switching // Create the device, context, and swap chain hResult = D3D11CreateDeviceAndSwapChain(NULL, D3D_DRIVER_TYPE_HARDWARE, NULL, NULL, //D3D_FEATURE_LEVEL_10_0, NULL, NULL, D3D11_SDK_VERSION, &scd, &m_Swapchain, &m_Device, NULL, &m_Context); if (hResult != S_OK) { return FALSE; } // Retrieves the IDXGIFactory that created "m_Device" IDXGIDevice *pDXGIDevice; m_Device->QueryInterface(__uuidof(IDXGIDevice), (void **)&pDXGIDevice); IDXGIAdapter *pDXGIAdapter; pDXGIDevice->GetParent(__uuidof(IDXGIAdapter), (void **)&pDXGIAdapter); IDXGIFactory *pDXGIFactory; pDXGIAdapter->GetParent(__uuidof(IDXGIFactory), (void **)&pDXGIFactory); // Disables the use of Alt-Enter to switch between fullscreen/windowed pDXGIFactory->MakeWindowAssociation(hWnd, DXGI_MWA_NO_ALT_ENTER); // Resized the target (window or screen resolution) and back buffers m_Swapchain->ResizeTarget(&scd.BufferDesc); m_Swapchain->ResizeBuffers(0, 0, 0, DXGI_FORMAT_UNKNOWN, scd.Flags); // Get the back buffer address ID3D11Texture1D *pBackBuffer; m_Swapchain->GetBuffer(0, __uuidof(ID3D11Texture2D), (LPVOID*)&pBackBuffer); // Use the back buffer address to create a render target m_Device->CreateRenderTargetView(pBackBuffer, NULL, &m_BackBuffer); pBackBuffer->Release(); D3D11_TEXTURE2D_DESC depthBufferDesc; D3D11_DEPTH_STENCIL_DESC depthStencilDesc; D3D11_DEPTH_STENCIL_VIEW_DESC depthStencilViewDesc; D3D11_RASTERIZER_DESC rasterDesc; ZeroMemory(&depthBufferDesc, sizeof(depthBufferDesc)); depthBufferDesc.Width = wind->getWidth(); depthBufferDesc.Height = wind->getHeight(); depthBufferDesc.MipLevels = 1; depthBufferDesc.ArraySize = 1; depthBufferDesc.Format = DXGI_FORMAT_D24_UNORM_S8_UINT; depthBufferDesc.SampleDesc.Count = 4; depthBufferDesc.SampleDesc.Quality = 0; depthBufferDesc.Usage = D3D11_USAGE_DEFAULT; depthBufferDesc.BindFlags = D3D11_BIND_DEPTH_STENCIL; depthBufferDesc.CPUAccessFlags = 0; depthBufferDesc.MiscFlags = 0; m_Device->CreateTexture2D(&depthBufferDesc, NULL, &m_DepthStencilBuffer); // Initialize the description of the stencil state. ZeroMemory(&depthStencilDesc, sizeof(depthStencilDesc)); // Set up the description of the stencil state. depthStencilDesc.DepthEnable = true; depthStencilDesc.DepthWriteMask = D3D11_DEPTH_WRITE_MASK_ALL; depthStencilDesc.DepthFunc = D3D11_COMPARISON_LESS; depthStencilDesc.StencilEnable = true; depthStencilDesc.StencilReadMask = 0xFF; depthStencilDesc.StencilWriteMask = 0xFF; // Stencil operations if pixel is front-facing. depthStencilDesc.FrontFace.StencilFailOp = D3D11_STENCIL_OP_KEEP; depthStencilDesc.FrontFace.StencilDepthFailOp = D3D11_STENCIL_OP_INCR; depthStencilDesc.FrontFace.StencilPassOp = D3D11_STENCIL_OP_KEEP; depthStencilDesc.FrontFace.StencilFunc = D3D11_COMPARISON_ALWAYS; // Stencil operations if pixel is back-facing. depthStencilDesc.BackFace.StencilFailOp = D3D11_STENCIL_OP_KEEP; depthStencilDesc.BackFace.StencilDepthFailOp = D3D11_STENCIL_OP_DECR; depthStencilDesc.BackFace.StencilPassOp = D3D11_STENCIL_OP_KEEP; depthStencilDesc.BackFace.StencilFunc = D3D11_COMPARISON_ALWAYS; m_Device->CreateDepthStencilState(&depthStencilDesc, &m_DepthStencilState); m_Context->OMSetDepthStencilState(m_DepthStencilState, 1); // Initailze the depth stencil view. ZeroMemory(&depthStencilViewDesc, sizeof(depthStencilViewDesc)); // Set up the depth stencil view description. depthStencilViewDesc.Format = DXGI_FORMAT_D24_UNORM_S8_UINT; depthStencilViewDesc.ViewDimension = D3D11_DSV_DIMENSION_TEXTURE2D; depthStencilViewDesc.Texture2D.MipSlice = 0; m_Device->CreateDepthStencilView(m_DepthStencilBuffer, NULL, &m_DepthStencilView); // set the render target as the back buffer m_Context->OMSetRenderTargets(1, &m_BackBuffer, m_DepthStencilView); // Set the viewport using windowSize object D3D11_VIEWPORT viewport; ZeroMemory(&viewport, sizeof(D3D11_VIEWPORT)); viewport.TopLeftX = 0; viewport.TopLeftY = 0; viewport.MinDepth = 0.0f; viewport.MaxDepth = 1.0f; viewport.Width = (float)wind->getWidth(); viewport.Height = (float)wind->getHeight(); m_Context->RSSetViewports(1, &viewport); // Setup the projection matrix. float fieldOfView = (float)D3DX_PI / 4.0f; float screenAspect = (float)wind->getWidth() / (float)wind->getHeight(); // TODO: Make constants for screen depth and screen near. // Create the projection matrix for 3D rendering. D3DXMatrixPerspectiveFovLH(&m_projMatrix, fieldOfView, screenAspect, 0.1f, 1000.0f); InitPipeline(); InitGraphics(); return TRUE; }
// // Initialize duplication interfaces // DUPL_RETURN DUPLICATIONMANAGER::InitDupl(_In_ ID3D11Device* Device, UINT Output) { m_OutputNumber = Output; // Take a reference on the device m_Device = Device; m_Device->AddRef(); // Get DXGI device IDXGIDevice* DxgiDevice = nullptr; HRESULT hr = m_Device->QueryInterface(__uuidof(IDXGIDevice), reinterpret_cast<void**>(&DxgiDevice)); if (FAILED(hr)) { return ProcessFailure(nullptr, L"Failed to QI for DXGI Device", L"Error", hr); } // Get DXGI adapter IDXGIAdapter* DxgiAdapter = nullptr; hr = DxgiDevice->GetParent(__uuidof(IDXGIAdapter), reinterpret_cast<void**>(&DxgiAdapter)); DxgiDevice->Release(); DxgiDevice = nullptr; if (FAILED(hr)) { return ProcessFailure(m_Device, L"Failed to get parent DXGI Adapter", L"Error", hr, SystemTransitionsExpectedErrors); } // Get output IDXGIOutput* DxgiOutput = nullptr; hr = DxgiAdapter->EnumOutputs(Output, &DxgiOutput); DxgiAdapter->Release(); DxgiAdapter = nullptr; if (FAILED(hr)) { return ProcessFailure(m_Device, L"Failed to get specified output in DUPLICATIONMANAGER", L"Error", hr, EnumOutputsExpectedErrors); } DxgiOutput->GetDesc(&m_OutputDesc); // QI for Output 1 IDXGIOutput1* DxgiOutput1 = nullptr; hr = DxgiOutput->QueryInterface(__uuidof(DxgiOutput1), reinterpret_cast<void**>(&DxgiOutput1)); DxgiOutput->Release(); DxgiOutput = nullptr; if (FAILED(hr)) { return ProcessFailure(nullptr, L"Failed to QI for DxgiOutput1 in DUPLICATIONMANAGER", L"Error", hr); } // Create desktop duplication hr = DxgiOutput1->DuplicateOutput(m_Device, &m_DeskDupl); DxgiOutput1->Release(); DxgiOutput1 = nullptr; if (FAILED(hr)) { if (hr == DXGI_ERROR_NOT_CURRENTLY_AVAILABLE) { MessageBoxW(nullptr, L"There is already the maximum number of applications using the Desktop Duplication API running, please close one of those applications and then try again.", L"Error", MB_OK); return DUPL_RETURN_ERROR_UNEXPECTED; } return ProcessFailure(m_Device, L"Failed to get duplicate output in DUPLICATIONMANAGER", L"Error", hr, CreateDuplicationExpectedErrors); } return DUPL_RETURN_SUCCESS; }
// // Initialize all state // DUPL_RETURN OUTPUTMANAGER::InitOutput(HWND Window, INT SingleOutput, _Out_ UINT* OutCount, _Out_ RECT* DeskBounds) { HRESULT hr; // Store window handle m_WindowHandle = Window; // Driver types supported D3D_DRIVER_TYPE DriverTypes[] = { D3D_DRIVER_TYPE_HARDWARE, D3D_DRIVER_TYPE_WARP, D3D_DRIVER_TYPE_REFERENCE, }; UINT NumDriverTypes = ARRAYSIZE(DriverTypes); // Feature levels supported D3D_FEATURE_LEVEL FeatureLevels[] = { D3D_FEATURE_LEVEL_11_0, D3D_FEATURE_LEVEL_10_1, D3D_FEATURE_LEVEL_10_0, D3D_FEATURE_LEVEL_9_1 }; UINT NumFeatureLevels = ARRAYSIZE(FeatureLevels); D3D_FEATURE_LEVEL FeatureLevel; // Create device for (UINT DriverTypeIndex = 0; DriverTypeIndex < NumDriverTypes; ++DriverTypeIndex) { hr = D3D11CreateDevice(nullptr, DriverTypes[DriverTypeIndex], nullptr, 0, FeatureLevels, NumFeatureLevels, D3D11_SDK_VERSION, &m_Device, &FeatureLevel, &m_DeviceContext); if (SUCCEEDED(hr)) { // Device creation succeeded, no need to loop anymore break; } } if (FAILED(hr)) { return ProcessFailure(m_Device, L"Device creation in OUTPUTMANAGER failed", L"Error", hr, SystemTransitionsExpectedErrors); } // Get DXGI factory IDXGIDevice* DxgiDevice = nullptr; hr = m_Device->QueryInterface(__uuidof(IDXGIDevice), reinterpret_cast<void**>(&DxgiDevice)); if (FAILED(hr)) { return ProcessFailure(nullptr, L"Failed to QI for DXGI Device", L"Error", hr, nullptr); } IDXGIAdapter* DxgiAdapter = nullptr; hr = DxgiDevice->GetParent(__uuidof(IDXGIAdapter), reinterpret_cast<void**>(&DxgiAdapter)); DxgiDevice->Release(); DxgiDevice = nullptr; if (FAILED(hr)) { return ProcessFailure(m_Device, L"Failed to get parent DXGI Adapter", L"Error", hr, SystemTransitionsExpectedErrors); } hr = DxgiAdapter->GetParent(__uuidof(IDXGIFactory2), reinterpret_cast<void**>(&m_Factory)); DxgiAdapter->Release(); DxgiAdapter = nullptr; if (FAILED(hr)) { return ProcessFailure(m_Device, L"Failed to get parent DXGI Factory", L"Error", hr, SystemTransitionsExpectedErrors); } // Register for occlusion status windows message hr = m_Factory->RegisterOcclusionStatusWindow(Window, OCCLUSION_STATUS_MSG, &m_OcclusionCookie); if (FAILED(hr)) { return ProcessFailure(m_Device, L"Failed to register for occlusion message", L"Error", hr, SystemTransitionsExpectedErrors); } // Get window size RECT WindowRect; GetClientRect(m_WindowHandle, &WindowRect); UINT Width = WindowRect.right - WindowRect.left; UINT Height = WindowRect.bottom - WindowRect.top; // Create swapchain for window DXGI_SWAP_CHAIN_DESC1 SwapChainDesc; RtlZeroMemory(&SwapChainDesc, sizeof(SwapChainDesc)); SwapChainDesc.SwapEffect = DXGI_SWAP_EFFECT_FLIP_SEQUENTIAL; SwapChainDesc.BufferCount = 2; SwapChainDesc.Width = Width; SwapChainDesc.Height = Height; SwapChainDesc.Format = DXGI_FORMAT_B8G8R8A8_UNORM; SwapChainDesc.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT; SwapChainDesc.SampleDesc.Count = 1; SwapChainDesc.SampleDesc.Quality = 0; hr = m_Factory->CreateSwapChainForHwnd(m_Device, Window, &SwapChainDesc, nullptr, nullptr, &m_SwapChain); if (FAILED(hr)) { return ProcessFailure(m_Device, L"Failed to create window swapchain", L"Error", hr, SystemTransitionsExpectedErrors); } // Disable the ALT-ENTER shortcut for entering full-screen mode hr = m_Factory->MakeWindowAssociation(Window, DXGI_MWA_NO_ALT_ENTER); if (FAILED(hr)) { return ProcessFailure(m_Device, L"Failed to make window association", L"Error", hr, SystemTransitionsExpectedErrors); } // Create shared texture DUPL_RETURN Return = CreateSharedSurf(SingleOutput, OutCount, DeskBounds); if (Return != DUPL_RETURN_SUCCESS) { return Return; } // Make new render target view Return = MakeRTV(); if (Return != DUPL_RETURN_SUCCESS) { return Return; } // Set view port SetViewPort(Width, Height); // Create the sample state D3D11_SAMPLER_DESC SampDesc; RtlZeroMemory(&SampDesc, sizeof(SampDesc)); SampDesc.Filter = D3D11_FILTER_MIN_MAG_MIP_LINEAR; SampDesc.AddressU = D3D11_TEXTURE_ADDRESS_CLAMP; SampDesc.AddressV = D3D11_TEXTURE_ADDRESS_CLAMP; SampDesc.AddressW = D3D11_TEXTURE_ADDRESS_CLAMP; SampDesc.ComparisonFunc = D3D11_COMPARISON_NEVER; SampDesc.MinLOD = 0; SampDesc.MaxLOD = D3D11_FLOAT32_MAX; hr = m_Device->CreateSamplerState(&SampDesc, &m_SamplerLinear); if (FAILED(hr)) { return ProcessFailure(m_Device, L"Failed to create sampler state in OUTPUTMANAGER", L"Error", hr, SystemTransitionsExpectedErrors); } // Create the blend state D3D11_BLEND_DESC BlendStateDesc; BlendStateDesc.AlphaToCoverageEnable = FALSE; BlendStateDesc.IndependentBlendEnable = FALSE; BlendStateDesc.RenderTarget[0].BlendEnable = TRUE; BlendStateDesc.RenderTarget[0].SrcBlend = D3D11_BLEND_SRC_ALPHA; BlendStateDesc.RenderTarget[0].DestBlend = D3D11_BLEND_INV_SRC_ALPHA; BlendStateDesc.RenderTarget[0].BlendOp = D3D11_BLEND_OP_ADD; BlendStateDesc.RenderTarget[0].SrcBlendAlpha = D3D11_BLEND_ONE; BlendStateDesc.RenderTarget[0].DestBlendAlpha = D3D11_BLEND_ZERO; BlendStateDesc.RenderTarget[0].BlendOpAlpha = D3D11_BLEND_OP_ADD; BlendStateDesc.RenderTarget[0].RenderTargetWriteMask = D3D11_COLOR_WRITE_ENABLE_ALL; hr = m_Device->CreateBlendState(&BlendStateDesc, &m_BlendState); if (FAILED(hr)) { return ProcessFailure(m_Device, L"Failed to create blend state in OUTPUTMANAGER", L"Error", hr, SystemTransitionsExpectedErrors); } // Initialize shaders Return = InitShaders(); if (Return != DUPL_RETURN_SUCCESS) { return Return; } GetWindowRect(m_WindowHandle, &WindowRect); MoveWindow(m_WindowHandle, WindowRect.left, WindowRect.top, (DeskBounds->right - DeskBounds->left) / 2, (DeskBounds->bottom - DeskBounds->top) / 2, TRUE); return Return; }
bool BasicRenderer::initD3D() { unsigned int createDeviceFlags = 0; # if defined(DEBUG) || defined(_DEBUG) createDeviceFlags |= D3D11_CREATE_DEVICE_DEBUG; # endif D3D_FEATURE_LEVEL featureLevel; HRESULT hr = D3D11CreateDevice( 0, m_driverType, 0, createDeviceFlags, 0, 0, D3D11_SDK_VERSION, &m_device, &featureLevel, &m_context); if (FAILED(hr)) { return false; } if (featureLevel != D3D_FEATURE_LEVEL_11_0) { return false; } m_device->CheckMultisampleQualityLevels(DXGI_FORMAT_R8G8B8A8_UNORM, 4, &m_4xMSAAQuality); assert(m_4xMSAAQuality > 0); DXGI_SWAP_CHAIN_DESC swapChainDesc; swapChainDesc.BufferDesc.Width = m_width; swapChainDesc.BufferDesc.Height = m_height; swapChainDesc.BufferDesc.RefreshRate.Numerator = 60; swapChainDesc.BufferDesc.RefreshRate.Denominator = 1; swapChainDesc.BufferDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM; swapChainDesc.BufferDesc.ScanlineOrdering = DXGI_MODE_SCANLINE_ORDER_UNSPECIFIED; swapChainDesc.BufferDesc.Scaling = DXGI_MODE_SCALING_UNSPECIFIED; if( m_enable4xMSAA ) { swapChainDesc.SampleDesc.Count = 4; swapChainDesc.SampleDesc.Quality = m_4xMSAAQuality-1; } else { swapChainDesc.SampleDesc.Count = 1; swapChainDesc.SampleDesc.Quality = 0; } swapChainDesc.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT; swapChainDesc.BufferCount = 1; swapChainDesc.OutputWindow = reinterpret_cast<HWND>(m_windowHandle); swapChainDesc.Windowed = true; swapChainDesc.SwapEffect = DXGI_SWAP_EFFECT_DISCARD; swapChainDesc.Flags = DXGI_SWAP_CHAIN_FLAG_ALLOW_MODE_SWITCH; IDXGIDevice* dxgiDevice = 0; m_device->QueryInterface(__uuidof(IDXGIDevice), (void**)&dxgiDevice); IDXGIDevice* dxgiAdapter = 0; dxgiDevice->GetParent(__uuidof(IDXGIAdapter), (void**)&dxgiAdapter); IDXGIFactory* dxgiFactory = 0; dxgiAdapter->GetParent(__uuidof(IDXGIFactory), (void**)&dxgiFactory); dxgiFactory->CreateSwapChain(m_device, &swapChainDesc, &m_swapChain); releaseCOM(dxgiDevice); releaseCOM(dxgiAdapter); releaseCOM(dxgiFactory); onResize(); return true; }
// ´ÙÀÌ·ºÆ® °´Ã¼ ÃʱâÈ // - °¢Á¾±â´ÉÀ» Áö¿øÇϴ°¡ üũÇÏ°í(´ÙÁß »ùÇøµ µî), ½º¿ÒüÀÎ, ÄÄ °´Ã¼ µîÀ» »ý¼º, Á¦°ÅÇÑ´Ù. bool cInitD3D::InitDirect3D() { // µð¹ÙÀ̽º, µð¹ÙÀ̽º ÄÁÅؽºÆ® »ý¼º UINT createDeviceFlags = 0; #if defined(DEBUG) || defined(_DEBUG) createDeviceFlags |= D3D11_CREATE_DEVICE_DEBUG; #endif D3D_FEATURE_LEVEL featureLevel; HRESULT hr = D3D11CreateDevice( 0, // default adapter md3dDriverType, 0, // no software device createDeviceFlags, 0, 0, // default feature level array D3D11_SDK_VERSION, &md3dDevice, &featureLevel, &md3dImmediateContext); if (FAILED(hr)) { MessageBox(0, L"D3D11CreateDevice Failed.", 0, 0); return false; } if (featureLevel != D3D_FEATURE_LEVEL_11_0) { MessageBox(0, L"Direct3D Feature Level 11 unsupported.", 0, 0); return false; } // ¹é¹öÆÛ¿¡ 4X MSAA Ç°Áú Áö¿øÀ» È®ÀÎ HR(md3dDevice->CheckMultisampleQualityLevels( DXGI_FORMAT_R8G8B8A8_UNORM, 4, &m4xMsaaQuality)); assert(m4xMsaaQuality > 0); // ½º¿ÒüÀÎ »ý¼º DXGI_SWAP_CHAIN_DESC sd; sd.BufferDesc.Width = mClientWidth; sd.BufferDesc.Height = mClientHeight; sd.BufferDesc.RefreshRate.Numerator = 60; sd.BufferDesc.RefreshRate.Denominator = 1; sd.BufferDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM; sd.BufferDesc.ScanlineOrdering = DXGI_MODE_SCANLINE_ORDER_UNSPECIFIED; sd.BufferDesc.Scaling = DXGI_MODE_SCALING_UNSPECIFIED; // ´ÙÁß »ùÇøµ À¯¹« (Use 4X MSAA?) if (mEnable4xMsaa) { sd.SampleDesc.Count = 4; sd.SampleDesc.Quality = m4xMsaaQuality - 1; } // No MSAA else { sd.SampleDesc.Count = 1; sd.SampleDesc.Quality = 0; } // ¹öÆÛ »ý¼º sd.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT; sd.BufferCount = 1; sd.OutputWindow = mhMainWnd; sd.Windowed = true; sd.SwapEffect = DXGI_SWAP_EFFECT_DISCARD; sd.Flags = 0; // µð¹ÙÀ̽º »ý¼º IDXGIDevice* dxgiDevice = 0; HR(md3dDevice->QueryInterface(__uuidof(IDXGIDevice), (void**)&dxgiDevice)); IDXGIAdapter* dxgiAdapter = 0; HR(dxgiDevice->GetParent(__uuidof(IDXGIAdapter), (void**)&dxgiAdapter)); IDXGIFactory* dxgiFactory = 0; HR(dxgiAdapter->GetParent(__uuidof(IDXGIFactory), (void**)&dxgiFactory)); // ½º¿ÒüÀÎ »ý¼º ¹× È®ÀÎ HR(dxgiFactory->CreateSwapChain(md3dDevice, &sd, &mSwapChain)); // ÄÄ °´Ã¼ »èÁ¦ ReleaseCOM(dxgiDevice); ReleaseCOM(dxgiAdapter); ReleaseCOM(dxgiFactory); // â Å©±â Á¶Àý (ÄÚµå Áߺ¹ ÇÇÇϱâ À§ÇØ »ç¿ë) OnResize(); return true; }
bool D3DApp::InitDirect3D() { /* ----------------------------------------- Create the D3D11 Device and DeviceContext ----------------------------------------- */ /* ----------------------- //? D3D11CreateDevice Notes ----------------------- //! Function Signature HRESULT result = D3D11CreateDevice( pAdapter, DriverType, Software, Flags, pFeatureLevels, FeatureLevels, SDKVersion, ppDevice, pFeatureLevel, ppImmediateContext ); //! Parameter Descriptions // The display adapter we want the created device to represent // Notes: Specifying "null" indicates the primary display adapter. //! IDXGIAdapter* pAdapter; // Type of driver our device will represent // Notes: In general, this should always be D3D_DRIVER_TYPE_HARDWARE, unless you need a reference, software, or WARP device. //! D3D_DRIVER_TYPE DriverType; // Software Driver // Notes: This is "null" if using a hardware driver. //! HMODULE Software; // (Optional) Device creation flags // Ex: D3D11_CREATE_DEVICE_DEBUG - Enables the Debug Layer, Direct3D will send debug messages to the VC++ output window. // Ex: D3D11_CREATE_DEVICE_SINGLETHREADED - Improves performance if you guarantee that Direct3D will not be called from multiple threads. //! UINT Flags; // Array of D3D feature levels // Notes: The order indicates the order in which to check for feature level support. // Specifying "null" indicates to choose the greatest feature level supported. //! const D3D_FEATURE_LEVEL* pFeatureLevels; // Size of pFeatureLevels array. // Notes: Specify "0" if you specified "null" for pFeatureLevels. //! UINT FeatureLevels; // Direct3D SDK Version // Notes: While studying this book, always use D3D11_SDK_VERSION. //! UINT SDKVersion; // Returns: Pointer to the device which this function will create //! ID3D11Device** ppDevice; // Returns: The first (highest) supported feature level from pFeatureLevels //! D3D_FEATURE_LEVEL* pFeatureLevel; // Returns: The created device context //! ID3D11DeviceContext** ppImmediateContext; */ UINT CreateDeviceFlags = 0; #if defined(DEBUG) || defined(_DEBUG) CreateDeviceFlags |= D3D11_CREATE_DEVICE_DEBUG; #endif D3D_FEATURE_LEVEL FeatureLevel; HRESULT CreateDeviceResult = D3D11CreateDevice( nullptr, mD3DDriverType, nullptr, CreateDeviceFlags, nullptr, 0, D3D11_SDK_VERSION, &mDevice, &FeatureLevel, &mImmediateContext ); if (FAILED(CreateDeviceResult)) { MessageBox(0, L"D3D11CreateDevice failed.", 0, 0); return false; } if (FeatureLevel != D3D_FEATURE_LEVEL_11_0) { MessageBox(0, L"Direct3D Feature Level 11 unsupported.", 0, 0); return false; } /* ----------------------------------- Check 4X MSAA Quality Level Support ----------------------------------- */ HR(mDevice->CheckMultisampleQualityLevels(DXGI_FORMAT_R8G8B8A8_UNORM, 4, &mMultisampleQuality)); assert(mMultisampleQuality > 0); /* ---------------------------------------------- Describe the characteristics of the swap chain ---------------------------------------------- */ /* -------------------------- //? DXGI_SWAP_CHAIN_DESC Notes -------------------------- //! Structure Signature typedef struct DXGI_SWAP_CHAIN_DESC { DXGI_MODE_DESC BufferDesc; DXGI_SAMPLE_DESC SampleDesc; DXGI_USAGE BufferUsage; UINT BufferCount; HWND OutputWindow; BOOL Windowed; DXGI_SWAP_EFFECT SwapEffect; UINT Flags; } DXGI_SWAP_CHAIN_DESC; //! Member Descriptions // Properties of the back buffer // Notes: The main properties that concern us are the width, height, and pixel format. //! DXGI_MODE_DESC BufferDesc; // Number of multisamples and quality level //! DXGI_SAMPLE_DESC SampleDesc; // Usage of the back buffer // Notes: Specify DXGI_USAGE_RENDER_TARGET_OUTPUT to indicate that the back buffer will be used for rendering. //! DXGI_USAGE BufferUsage; // Number of back buffers in the swap chain // Notes: Use "1" to allocate one back buffer (double buffering) //! UINT BufferCount; // Handle to the window we are rendering to //! HWND OutputWindow; // Notes: "true" indicates windowed-mode, "false" indicates full-screen mode //! BOOL Windowed; // Notes: Specify DXGI_SWAP_EFFECT_DISCARD to let the display driver select the most efficient presentation method //! DXGI_SWAP_EFFECT SwapEffect; // (Optional) flags // Notes: If you use DXGI_SWAP_CHAIN_FLAG_ALLOW_MODE_SWITCH, then when you switch to full-screen mode, the application // will select a display mode that best matches the current back buffer settings. //! UINT Flags; */ DXGI_SWAP_CHAIN_DESC SwapChainDesc; /* -------------------------- //? DXGI_DESC_MODE Notes -------------------------- //! Structure Signature typedef struct DXGI_MODE_DESC { UINT Width; UINT Height; DXGI_RATIONAL RefreshRate; DXGI_FORMAT Format; DXGI_MODE_SCANLINE_ORDER ScanlineOrdering; DXGI_MODE_SCALING Scaling; } DXGI_MODE_DESC; //! Member Descriptions // Window resolution width //! UINT Width; // Window resolution height //! UINT Height; // Refresh rate defined in Hz (Numerator and Denominator) //! DXGI_RATIONAL RefreshRate; // Display format //! DXGI_FORMAT Format; // Scanline Drawing Mode //! DXGI_MODE_SCANLINE_ORDER ScanlineOrdering; // Scaling Mode // Notes: Indicates how an image is stretched to fit the screen resolution. //! DXGI_MODE_SCALING Scaling; */ DXGI_MODE_DESC BackBufferDesc; BackBufferDesc.Width = 800; BackBufferDesc.Height = 600; // Most monitors cannot output more than 24-bit color, so extra precision would be wasted // Even though the monitor cannot output the 8-bit alpha, those bits can be used for other things like effects BackBufferDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM; BackBufferDesc.RefreshRate.Numerator = 60; BackBufferDesc.RefreshRate.Denominator = 1; BackBufferDesc.ScanlineOrdering = DXGI_MODE_SCANLINE_ORDER_UNSPECIFIED; BackBufferDesc.Scaling = DXGI_MODE_SCALING_UNSPECIFIED; SwapChainDesc.BufferDesc = BackBufferDesc; if (mEnableMultisample) { SwapChainDesc.SampleDesc.Count = 4; SwapChainDesc.SampleDesc.Quality = mMultisampleQuality - 1; } else { SwapChainDesc.SampleDesc.Count = 1; SwapChainDesc.SampleDesc.Quality = 0; } SwapChainDesc.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT; SwapChainDesc.BufferCount = 1; SwapChainDesc.OutputWindow = mMainWindow; SwapChainDesc.Windowed = true; SwapChainDesc.SwapEffect = DXGI_SWAP_EFFECT_DISCARD; SwapChainDesc.Flags = 0; /* --------------------- Create the swap chain --------------------- */ IDXGIDevice* dxgiDevice = 0; mDevice->QueryInterface(__uuidof(IDXGIDevice), (void**)&dxgiDevice); IDXGIAdapter* dxgiAdapter = 0; dxgiDevice->GetParent(__uuidof(IDXGIAdapter), (void**)&dxgiAdapter); IDXGIFactory* dxgiFactory = 0; dxgiAdapter->GetParent(__uuidof(IDXGIFactory), (void**)&dxgiFactory); dxgiFactory->CreateSwapChain(mDevice, &SwapChainDesc, &mSwapChain); ReleaseCOM(dxgiDevice); ReleaseCOM(dxgiAdapter); ReleaseCOM(dxgiFactory); OnResize(); return true; }
// Direct3Dの初期化 HRESULT InitD3D( void ) { HRESULT hr = S_OK; D3D_FEATURE_LEVEL FeatureLevelsRequested[6] = { 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 }; UINT numLevelsRequested = 6; D3D_FEATURE_LEVEL FeatureLevelsSupported; // デバイス作成 hr = D3D11CreateDevice( NULL, D3D_DRIVER_TYPE_HARDWARE, NULL, 0, FeatureLevelsRequested, numLevelsRequested, D3D11_SDK_VERSION, &g_pd3dDevice, &FeatureLevelsSupported, &g_pImmediateContext ); if( FAILED ( hr ) ) { return hr; } // ファクトリの取得 IDXGIDevice * pDXGIDevice; hr = g_pd3dDevice->QueryInterface( __uuidof( IDXGIDevice ), ( void ** )&pDXGIDevice ); IDXGIAdapter * pDXGIAdapter; hr = pDXGIDevice->GetParent( __uuidof( IDXGIAdapter ), ( void ** )&pDXGIAdapter ); IDXGIFactory * pIDXGIFactory; pDXGIAdapter->GetParent( __uuidof( IDXGIFactory ), ( void ** )&pIDXGIFactory); // スワップチェインの作成 DXGI_SWAP_CHAIN_DESC sd; ZeroMemory( &sd, sizeof( sd ) ); sd.BufferCount = 1; sd.BufferDesc.Width = g_nClientWidth; sd.BufferDesc.Height = g_nClientHeight; sd.BufferDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM; sd.BufferDesc.RefreshRate.Numerator = 60; sd.BufferDesc.RefreshRate.Denominator = 1; sd.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT; sd.OutputWindow = g_hWnd; sd.SampleDesc.Count = 1; sd.SampleDesc.Quality = 0; sd.Windowed = TRUE; hr = pIDXGIFactory->CreateSwapChain( g_pd3dDevice, &sd, &g_pSwapChain ); pDXGIDevice->Release(); pDXGIAdapter->Release(); pIDXGIFactory->Release(); if( FAILED ( hr ) ) { return hr; } // レンダリングターゲットの生成 ID3D11Texture2D *pBackBuffer = NULL; D3D11_TEXTURE2D_DESC BackBufferSurfaceDesc; hr = g_pSwapChain->GetBuffer( 0, __uuidof( ID3D11Texture2D ), ( LPVOID* )&pBackBuffer ); if ( FAILED( hr ) ) { MessageBox( NULL, _T( "Can't get backbuffer." ), _T( "Error" ), MB_OK ); return hr; } pBackBuffer->GetDesc( &BackBufferSurfaceDesc ); hr = g_pd3dDevice->CreateRenderTargetView( pBackBuffer, NULL, &g_pRTV ); SAFE_RELEASE( pBackBuffer ); if ( FAILED( hr ) ) { MessageBox( NULL, _T( "Can't create render target view." ), _T( "Error" ), MB_OK ); return hr; } g_pImmediateContext->OMSetRenderTargets( 1, &g_pRTV, NULL ); // ラスタライザの設定 D3D11_RASTERIZER_DESC drd; ZeroMemory( &drd, sizeof( drd ) ); drd.FillMode = D3D11_FILL_SOLID; drd.CullMode = D3D11_CULL_NONE; drd.FrontCounterClockwise = FALSE; drd.DepthClipEnable = TRUE; hr = g_pd3dDevice->CreateRasterizerState( &drd, &g_pRS ); if ( FAILED( hr ) ) { MessageBox( NULL, _T( "Can't create rasterizer state." ), _T( "Error" ), MB_OK ); return hr; } g_pImmediateContext->RSSetState( g_pRS ); // ビューポートの設定 D3D11_VIEWPORT vp; vp.Width = ( FLOAT )g_nClientWidth; vp.Height = ( FLOAT )g_nClientHeight; vp.MinDepth = 0.0f; vp.MaxDepth = 1.0f; vp.TopLeftX = 0.0f; vp.TopLeftY = 0.0f; g_pImmediateContext->RSSetViewports( 1, &vp ); return S_OK; }
// Direct3Dの初期化 HRESULT InitD3D( void ) { HRESULT hr = S_OK; D3D_FEATURE_LEVEL FeatureLevelsRequested[6] = { 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 }; UINT numLevelsRequested = 6; D3D_FEATURE_LEVEL FeatureLevelsSupported; // デバイス作成 hr = D3D11CreateDevice( NULL, D3D_DRIVER_TYPE_HARDWARE, NULL, 0, FeatureLevelsRequested, numLevelsRequested, D3D11_SDK_VERSION, &g_pd3dDevice, &FeatureLevelsSupported, &g_pImmediateContext ); if( FAILED ( hr ) ) { return hr; } // ファクトリの取得 IDXGIDevice * pDXGIDevice; hr = g_pd3dDevice->QueryInterface( __uuidof( IDXGIDevice ), ( void ** )&pDXGIDevice ); IDXGIAdapter * pDXGIAdapter; hr = pDXGIDevice->GetParent( __uuidof( IDXGIAdapter ), ( void ** )&pDXGIAdapter ); IDXGIFactory * pIDXGIFactory; pDXGIAdapter->GetParent( __uuidof( IDXGIFactory ), ( void ** )&pIDXGIFactory); // スワップチェインの作成 DXGI_SWAP_CHAIN_DESC sd; ZeroMemory( &sd, sizeof( sd ) ); sd.BufferCount = 1; sd.BufferDesc.Width = g_nClientWidth; sd.BufferDesc.Height = g_nClientHeight; sd.BufferDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM; sd.BufferDesc.RefreshRate.Numerator = 60; sd.BufferDesc.RefreshRate.Denominator = 1; sd.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT; sd.OutputWindow = g_hWnd; sd.SampleDesc.Count = 1; sd.SampleDesc.Quality = 0; sd.Windowed = TRUE; hr = pIDXGIFactory->CreateSwapChain( g_pd3dDevice, &sd, &g_pSwapChain ); pDXGIDevice->Release(); pDXGIAdapter->Release(); pIDXGIFactory->Release(); if( FAILED ( hr ) ) { return hr; } // レンダリングターゲットの生成 ID3D11Texture2D *pBackBuffer = NULL; D3D11_TEXTURE2D_DESC BackBufferSurfaceDesc; hr = g_pSwapChain->GetBuffer( 0, __uuidof( ID3D11Texture2D ), ( LPVOID* )&pBackBuffer ); if ( FAILED( hr ) ) { MessageBox( NULL, _T( "Can't get backbuffer." ), _T( "Error" ), MB_OK ); return hr; } pBackBuffer->GetDesc( &BackBufferSurfaceDesc ); hr = g_pd3dDevice->CreateRenderTargetView( pBackBuffer, NULL, &g_pRTV ); SAFE_RELEASE( pBackBuffer ); if ( FAILED( hr ) ) { MessageBox( NULL, _T( "Can't create render target view." ), _T( "Error" ), MB_OK ); return hr; } // *** Create depth stencil texture *** D3D11_TEXTURE2D_DESC descDepth; RECT rc; GetClientRect( g_hWnd, &rc ); ZeroMemory( &descDepth, sizeof(descDepth) ); descDepth.Width = rc.right - rc.left; descDepth.Height = rc.bottom - rc.top; descDepth.MipLevels = 1; descDepth.ArraySize = 1; descDepth.Format = DXGI_FORMAT_D24_UNORM_S8_UINT; descDepth.SampleDesc.Count = 1; descDepth.SampleDesc.Quality = 0; descDepth.Usage = D3D11_USAGE_DEFAULT; descDepth.BindFlags = D3D11_BIND_DEPTH_STENCIL; descDepth.CPUAccessFlags = 0; descDepth.MiscFlags = 0; hr = g_pd3dDevice->CreateTexture2D( &descDepth, NULL, &g_pDepthStencil ); if( FAILED( hr ) ) return hr; // *** Create the depth stencil view *** D3D11_DEPTH_STENCIL_VIEW_DESC descDSV; ZeroMemory( &descDSV, sizeof(descDSV) ); descDSV.Format = descDepth.Format; descDSV.ViewDimension = D3D11_DSV_DIMENSION_TEXTURE2D; descDSV.Texture2D.MipSlice = 0; hr = g_pd3dDevice->CreateDepthStencilView( g_pDepthStencil, &descDSV, &g_pDepthStencilView ); if( FAILED( hr ) ) return hr; // *** レンダリングターゲット設定 *** g_pImmediateContext->OMSetRenderTargets( 1, &g_pRTV, g_pDepthStencilView ); // ステンシルステートの作成 D3D11_DEPTH_STENCIL_DESC dsDesc; // Depth test parameters dsDesc.DepthEnable = true; dsDesc.DepthWriteMask = D3D11_DEPTH_WRITE_MASK_ALL; dsDesc.DepthFunc = D3D11_COMPARISON_LESS; // Stencil test parameters dsDesc.StencilEnable = true; dsDesc.StencilReadMask = 0xFF; dsDesc.StencilWriteMask = 0xFF; // Stencil operations if pixel is front-facing dsDesc.FrontFace.StencilFailOp = D3D11_STENCIL_OP_KEEP; dsDesc.FrontFace.StencilDepthFailOp = D3D11_STENCIL_OP_INCR; dsDesc.FrontFace.StencilPassOp = D3D11_STENCIL_OP_KEEP; dsDesc.FrontFace.StencilFunc = D3D11_COMPARISON_ALWAYS; // Stencil operations if pixel is back-facing dsDesc.BackFace.StencilFailOp = D3D11_STENCIL_OP_KEEP; dsDesc.BackFace.StencilDepthFailOp = D3D11_STENCIL_OP_DECR; dsDesc.BackFace.StencilPassOp = D3D11_STENCIL_OP_KEEP; dsDesc.BackFace.StencilFunc = D3D11_COMPARISON_ALWAYS; // Create depth stencil state hr = g_pd3dDevice->CreateDepthStencilState( &dsDesc, &g_pDSDepthState ); dsDesc.DepthWriteMask = D3D11_DEPTH_WRITE_MASK_ZERO; hr = g_pd3dDevice->CreateDepthStencilState( &dsDesc, &g_pDSDepthState_NoWrite ); // g_pImmediateContext->OMSetDepthStencilState( g_pDSDepthState, 1 ); // ラスタライザの設定 D3D11_RASTERIZER_DESC drd; ZeroMemory( &drd, sizeof( drd ) ); drd.FillMode = D3D11_FILL_SOLID; drd.CullMode = D3D11_CULL_NONE; drd.FrontCounterClockwise = FALSE; drd.DepthClipEnable = TRUE; hr = g_pd3dDevice->CreateRasterizerState( &drd, &g_pRS ); if ( FAILED( hr ) ) { MessageBox( NULL, _T( "Can't create rasterizer state." ), _T( "Error" ), MB_OK ); return hr; } g_pImmediateContext->RSSetState( g_pRS ); // ラスタライザの設定(時計回りカリング) ZeroMemory( &drd, sizeof( drd ) ); drd.FillMode = D3D11_FILL_SOLID; drd.CullMode = D3D11_CULL_BACK; drd.FrontCounterClockwise = TRUE; drd.DepthClipEnable = TRUE; hr = g_pd3dDevice->CreateRasterizerState( &drd, &g_pRS_Cull_CW ); if ( FAILED( hr ) ) { MessageBox( NULL, _T( "Can't create rasterizer state." ), _T( "Error" ), MB_OK ); return hr; } // g_pImmediateContext->RSSetState( g_pRS_Cull_CW ); // ラスタライザの設定(反時計回りカリング) ZeroMemory( &drd, sizeof( drd ) ); drd.FillMode = D3D11_FILL_SOLID; drd.CullMode = D3D11_CULL_BACK; drd.FrontCounterClockwise = FALSE; drd.DepthClipEnable = TRUE; hr = g_pd3dDevice->CreateRasterizerState( &drd, &g_pRS_Cull_CCW ); if ( FAILED( hr ) ) { MessageBox( NULL, _T( "Can't create rasterizer state." ), _T( "Error" ), MB_OK ); return hr; } // g_pImmediateContext->RSSetState( g_pRS_Cull_CCW ); // ビューポートの設定 D3D11_VIEWPORT vp; vp.Width = ( FLOAT )g_nClientWidth; vp.Height = ( FLOAT )g_nClientHeight; vp.MinDepth = 0.0f; vp.MaxDepth = 1.0f; vp.TopLeftX = 0.0f; vp.TopLeftY = 0.0f; g_pImmediateContext->RSSetViewports( 1, &vp ); return S_OK; }
bool D3DRenderer::CreateSwapChain(int screenWidth, int screenHeight, HWND hwnd) { //Get refresh rate, display modes, and initialize the swap chain. HRESULT result; IDXGIDevice* dxgiDevice = 0; IDXGIFactory* dxgiFactory =0; IDXGIAdapter* dxgiAdapter =0; IDXGIOutput* dxgiAdapterOutput; unsigned int numModes, i, numerator, denominator, stringLength; DXGI_MODE_DESC* displayModeList; DXGI_ADAPTER_DESC adapterDesc; int error; DXGI_SWAP_CHAIN_DESC swapChainDesc; this->m_device->QueryInterface(__uuidof(IDXGIDevice), (void**)&dxgiDevice); dxgiDevice->GetParent(__uuidof(IDXGIAdapter), (void**)&dxgiAdapter); dxgiAdapter->GetParent(__uuidof(IDXGIFactory), (void**)&dxgiFactory); result = dxgiFactory->EnumAdapters(0, &dxgiAdapter); if (FAILED(result)) { return false; } result = dxgiAdapter->EnumOutputs(0, &dxgiAdapterOutput); if (FAILED(result)) { return false; } result = dxgiAdapterOutput->GetDisplayModeList(DXGI_FORMAT_R8G8B8A8_UNORM, DXGI_ENUM_MODES_INTERLACED, &numModes, NULL); if (FAILED(result)) { return false; } displayModeList = new DXGI_MODE_DESC[numModes]; if (!displayModeList) { return false; } result = dxgiAdapterOutput->GetDisplayModeList(DXGI_FORMAT_R8G8B8A8_UNORM, DXGI_ENUM_MODES_INTERLACED, &numModes, displayModeList); if (FAILED(result)) { return false; } for (i=0; i < numModes; i++) { if (displayModeList[i].Width == (unsigned int)screenWidth) { if (displayModeList[i].Height == (unsigned int)screenHeight) { numerator = displayModeList[i].RefreshRate.Numerator; denominator = displayModeList[i].RefreshRate.Denominator; } } } result = dxgiAdapter->GetDesc(&adapterDesc); if (FAILED(result)) { return false; } this->m_videoCardMemory = (int)(adapterDesc.DedicatedVideoMemory / 1024 / 1024); error = wcstombs_s(&stringLength, this->m_videoCardDescription, 128, adapterDesc.Description, 128); if (error != 0) { return false; } //Initialize the swap chain ZeroMemory(&swapChainDesc, sizeof(swapChainDesc)); //Single buffer count swapChainDesc.BufferCount = 1; swapChainDesc.BufferDesc.Width = screenWidth; swapChainDesc.BufferDesc.Height = screenHeight; //Using regular 32bit back buffer swapChainDesc.BufferDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM; if (this->m_vsync_enabled) { swapChainDesc.BufferDesc.RefreshRate.Numerator = numerator; swapChainDesc.BufferDesc.RefreshRate.Denominator = denominator; } else { swapChainDesc.BufferDesc.RefreshRate.Numerator = 0; swapChainDesc.BufferDesc.RefreshRate.Denominator = 1; } //Set the usage swapChainDesc.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT; swapChainDesc.OutputWindow = hwnd; //Turn multisamping off. This setting is for MSAA, for our purposes we don't need it. swapChainDesc.SampleDesc.Count = 1; swapChainDesc.SampleDesc.Quality = 0; swapChainDesc.Windowed = true; //Set the scan line ordering swapChainDesc.BufferDesc.ScanlineOrdering = DXGI_MODE_SCANLINE_ORDER_UNSPECIFIED; swapChainDesc.BufferDesc.Scaling = DXGI_MODE_SCALING_UNSPECIFIED; //Tells D3D to discard the back buffer after presenting swapChainDesc.SwapEffect = DXGI_SWAP_EFFECT_DISCARD; //Do not use advanced flags. swapChainDesc.Flags = 0; //Create the swap chain result = dxgiFactory->CreateSwapChain(this->m_device, &swapChainDesc, &this->m_swapChain); if (FAILED(result)) { return false; } delete [] displayModeList; displayModeList = 0; dxgiAdapterOutput->Release(); dxgiAdapterOutput = 0; dxgiAdapter->Release(); dxgiAdapter = 0; dxgiFactory->Release(); dxgiFactory = 0; return true; }
bool DXApp::InitDirectX() { UINT createDeviceFlags = 0; #if defined(DEBUG) || defined(_DEBUG) createDeviceFlags |= D3D11_CREATE_DEVICE_DEBUG; #endif D3D_FEATURE_LEVEL featurelvl; HRESULT hr = D3D11CreateDevice( 0, //default adapter D3D_DRIVER_TYPE_HARDWARE, 0, createDeviceFlags, 0, 0, D3D11_SDK_VERSION, &m_d3dDevice, &featurelvl, &m_d3dImmediateContext); if (FAILED(hr)) { MessageBox(0, L"Creation of Context failed", 0, 0); return false; } if (featurelvl != D3D_FEATURE_LEVEL_11_0) { MessageBox(0, L"DirectX11 not supported", 0, 0); return false; } m_d3dDevice->CheckMultisampleQualityLevels(DXGI_FORMAT_R8G8B8A8_UNORM, 4, &m_4xMsaaQuality); assert(m_4xMsaaQuality > 0); DXGI_SWAP_CHAIN_DESC sd; sd.BufferDesc.Width = m_clientWidth; sd.BufferDesc.Height = m_clientHeight; sd.BufferDesc.RefreshRate.Numerator = 60; sd.BufferDesc.RefreshRate.Denominator = 1; sd.BufferDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM; sd.BufferDesc.ScanlineOrdering = DXGI_MODE_SCANLINE_ORDER_UNSPECIFIED; sd.BufferDesc.Scaling = DXGI_MODE_SCALING_UNSPECIFIED; if (m_enable4xMsaa) { sd.SampleDesc.Count = 4; sd.SampleDesc.Quality = m_4xMsaaQuality - 1; } else { sd.SampleDesc.Count = 1; sd.SampleDesc.Quality = m_4xMsaaQuality - 1; } sd.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT; sd.BufferCount = 1; sd.OutputWindow =m_mainHandle; sd.Windowed = m_windowed; sd.SwapEffect = DXGI_SWAP_EFFECT_DISCARD; sd.Flags = 0; IDXGIDevice* dxgiDevice = 0; m_d3dDevice->QueryInterface(__uuidof(IDXGIDevice), (void**)&dxgiDevice); IDXGIAdapter* dxgiAdapter = 0; dxgiDevice->GetParent(__uuidof(IDXGIAdapter), (void**)&dxgiAdapter); IDXGIFactory* dxgiFactory = 0; dxgiAdapter->GetParent(__uuidof(IDXGIFactory), (void**)&dxgiFactory); dxgiFactory->CreateSwapChain(m_d3dDevice, &sd, &m_d3dSwapChain); //NO ALT-ENTER dxgiFactory->MakeWindowAssociation(m_mainHandle, DXGI_MWA_NO_ALT_ENTER); UINT i = 0; IDXGIAdapter* pAdapter; std::vector<IDXGIAdapter*> vAdapters; while (dxgiFactory->EnumAdapters(i, &pAdapter) != DXGI_ERROR_NOT_FOUND) { vAdapters.push_back(pAdapter); //pAdapter->CheckInterfaceSupport(__uuidof(DIRECT3D_VERSION), DIRECT3D_11.0); i++; } //MessageBox(0, LPCWSTR(std::to_string(vAdapters.size()).c_str()), 0, 0); for (auto a : vAdapters)a->Release(); dxgiDevice->Release(); dxgiAdapter->Release(); dxgiFactory->Release(); ID3D11Texture2D* backBuffer; m_d3dSwapChain->GetBuffer(0, __uuidof(ID3D11Texture2D), reinterpret_cast<void**>(&backBuffer)); m_d3dDevice->CreateRenderTargetView(backBuffer, 0, &m_d3dRenderTargetView); backBuffer->Release(); D3D11_TEXTURE2D_DESC depthStencilDesc; depthStencilDesc.Width = m_clientWidth; depthStencilDesc.Height = m_clientHeight; depthStencilDesc.MipLevels = 1; depthStencilDesc.ArraySize = 1; depthStencilDesc.Format = DXGI_FORMAT_D24_UNORM_S8_UINT; if (m_enable4xMsaa) { depthStencilDesc.SampleDesc.Count = 4; depthStencilDesc.SampleDesc.Quality = m_4xMsaaQuality - 1; } else { depthStencilDesc.SampleDesc.Count = 1; depthStencilDesc.SampleDesc.Quality = m_4xMsaaQuality - 0; } depthStencilDesc.Usage = D3D11_USAGE_DEFAULT; depthStencilDesc.BindFlags = D3D11_BIND_DEPTH_STENCIL; depthStencilDesc.CPUAccessFlags = 0; depthStencilDesc.MiscFlags = 0; m_d3dDevice->CreateTexture2D(&depthStencilDesc, 0, &m_d3dDepthStencilBuffer); m_d3dDevice->CreateDepthStencilView(m_d3dDepthStencilBuffer, 0, &m_d3dDepthStencilView); m_d3dImmediateContext->OMSetRenderTargets(1, &m_d3dRenderTargetView, m_d3dDepthStencilView); D3D11_VIEWPORT vp; vp.TopLeftX = 0.f; vp.TopLeftY = 0.f; vp.Width = static_cast<float>(m_clientWidth); vp.Height = static_cast<float>(m_clientHeight); vp.MinDepth = 0.f; vp.MaxDepth = 0.f; m_d3dImmediateContext->RSSetViewports(1, &vp); return true; }
bool cInitDirect3D::Init() { UINT createDeviceFlags = 0; #if defined(DEBUG) || defined(_DEBUG) createDeviceFlags |= D3D11_CREATE_DEVICE_DEBUG; #endif D3D_FEATURE_LEVEL featureLevel; HRESULT hr = D3D11CreateDevice( 0, // default adapter 사용할 IDXGIAdapter 인터페이스 md3dDriverType, //DirectX11 디바이스타입. 0, // no software device 보통 null createDeviceFlags, //디바이스 플래그 0, 0, // 피처레벨을 사용할 배열, 피처레벨 수 D3D11_SDK_VERSION, //SDK버전 &m_pD3dDevice, //넘겨받을 디바이스 인터페이스 &featureLevel, //피처레벨을 얻어낼 포인터 &m_pDeviceContext); //넘겨받을 디바이스 컨텍스트 인터페이스 if (FAILED(hr)) { MessageBox(0, L"D3D11CreateDevice Failed.", 0, 0); return false; } if (featureLevel != D3D_FEATURE_LEVEL_11_0) { MessageBox(0, L"Direct3D Feature Level 11 unsupported.", 0, 0); return false; } // Check 4X MSAA quality support for our back buffer format. // All Direct3D 11 capable devices support 4X MSAA for all render // target formats, so we only need to check quality support. HR(m_pD3dDevice->CheckMultisampleQualityLevels( DXGI_FORMAT_R8G8B8A8_UNORM, 4, &m4xMsaaQuality)); assert(m4xMsaaQuality > 0); // DXGI_SWAP_CHAIN_DESC구조체를 채운다. DXGI_SWAP_CHAIN_DESC sd; ZeroMemory(&sd, sizeof(sd));//구조체 초기화 sd.BufferCount = 1;//백버퍼 개수 sd.BufferDesc.Width = ClientWidth;//백버퍼 가로 sd.BufferDesc.Height = ClientHeight;//백버퍼 세로 sd.BufferDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;//백버퍼 포맷 : RGBA8비트이며 값의 범위0.0~1.0 sd.BufferDesc.RefreshRate.Numerator = 60;//화면 갱신율. 분자. sd.BufferDesc.RefreshRate.Denominator = 1;//화면 갱신율. 분모.(60/1) sd.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT;//백버퍼의 용도 sd.OutputWindow = g_hWnd;//버퍼를 출력할 윈도우 sd.SampleDesc.Count = 1;//멀티 샘플링 수 sd.SampleDesc.Quality = 0;//멀티 샘플링 퀄리티 sd.Windowed = true;//윈도우모드 sd.Flags = 0; // Use 4X MSAA? if (mEnable4xMsaa) { sd.SampleDesc.Count = 4; sd.SampleDesc.Quality = m4xMsaaQuality - 1; } // No MSAA else { sd.SampleDesc.Count = 1; sd.SampleDesc.Quality = 0; } // To correctly create the swap chain, we must use the IDXGIFactory that was // used to create the device. If we tried to use a different IDXGIFactory instance // (by calling CreateDXGIFactory), we get an error: "IDXGIFactory::CreateSwapChain: // This function is being called with a device from a different IDXGIFactory." IDXGIDevice* dxgiDevice = 0; HR(m_pD3dDevice->QueryInterface(__uuidof(IDXGIDevice), (void**)&dxgiDevice)); IDXGIAdapter* dxgiAdapter = 0; HR(dxgiDevice->GetParent(__uuidof(IDXGIAdapter), (void**)&dxgiAdapter)); IDXGIFactory* dxgiFactory = 0; HR(dxgiAdapter->GetParent(__uuidof(IDXGIFactory), (void**)&dxgiFactory)); HR(dxgiFactory->CreateSwapChain(m_pD3dDevice, &sd, &m_pSwapChain)); ReleaseCOM(dxgiDevice); ReleaseCOM(dxgiAdapter); ReleaseCOM(dxgiFactory); // The remaining steps that need to be carried out for d3d creation // also need to be executed every time the window is resized. So // just call the OnResize method here to avoid code duplication. Onresize(); return true; }
bool Direct3D::Initialize(HWND* hWnd) { mcWidth = &Settings->GetData()->mWidth; mcHeight = &Settings->GetData()->mHeight; UINT createDeviceFlags = 0; #if defined(_DEBUG) | (DEBUG) createDeviceFlags |= D3D11_CREATE_DEVICE_DEBUG; #endif D3D_FEATURE_LEVEL featureLevel; if( FAILED ( D3D11CreateDevice( nullptr, mDriverType, nullptr, 0, nullptr, 0, D3D11_SDK_VERSION, &mDevice, &featureLevel, &mDevCon))) { cout << "D3D11CreateDevice failed." << endl; return false; } if(featureLevel != D3D_FEATURE_LEVEL_11_0) { cout << "Direct3D feature level 11 unsupported." << endl; return false; } mDevice->CheckMultisampleQualityLevels(DXGI_FORMAT_R8G8B8A8_UNORM, 4, &m4xMSAAQuality); assert(m4xMSAAQuality > 0); DXGI_SWAP_CHAIN_DESC sd = {}; sd.BufferDesc.Width = *mcWidth; sd.BufferDesc.Height = *mcHeight; sd.BufferDesc.RefreshRate.Numerator = 60; sd.BufferDesc.RefreshRate.Denominator = 1; sd.BufferDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM; sd.BufferDesc.ScanlineOrdering = DXGI_MODE_SCANLINE_ORDER_UNSPECIFIED; sd.BufferDesc.Scaling = DXGI_MODE_SCALING_UNSPECIFIED; if (mEnable4xMsaa) { sd.SampleDesc.Count = 4; sd.SampleDesc.Quality = m4xMSAAQuality-1; } else { sd.SampleDesc.Count = 1; sd.SampleDesc.Quality = 0; } sd.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT; // Use back buffer as render target sd.BufferCount = 1; // Number of back buffers to use in swap chain sd.OutputWindow = *hWnd; // Specify window we render into sd.Windowed = !Settings->GetData()->mIsFullscreen; // Windowed mode or full-screen mode sd.SwapEffect = DXGI_SWAP_EFFECT_DISCARD; // Let display driver select most efficient presentation method sd.Flags = DXGI_SWAP_CHAIN_FLAG_ALLOW_MODE_SWITCH; IDXGIDevice* dxgiDevice = nullptr; mDevice->QueryInterface(__uuidof(IDXGIDevice), (void**)&dxgiDevice); IDXGIAdapter* dxgiAdapter = nullptr; dxgiDevice->GetParent(__uuidof(IDXGIAdapter),(void**)&dxgiAdapter); IDXGIFactory* dxgiFactory = nullptr; dxgiAdapter->GetParent(__uuidof(IDXGIFactory), (void**)&dxgiFactory); dxgiFactory->CreateSwapChain(mDevice, &sd, &mSwapChain); SafeRelease(dxgiDevice); SafeRelease(dxgiAdapter); SafeRelease(dxgiFactory); this->OnResize(); return true; }
bool Renderer::Init() { UINT createDeviceFlags = 0; #if defined(DEBUG) || defined(_DEBUG) //createDeviceFlags |= D3D11_CREATE_DEVICE_DEBUG; //createDeviceFlags |= D3D11_CREATE_DEVICE_DEBUGGABLE; #endif D3D_FEATURE_LEVEL featureLevel; HRESULT hresult = D3D11CreateDevice(0, _d3dDriverType, 0, createDeviceFlags, 0, 0, D3D11_SDK_VERSION, &_d3dDevice, &featureLevel, &_d3dImmediateContext); if (FAILED(hresult)) { // TODO: Throw exceptions _logger.LogLine(L"Failed to initialize Renderer: Failed to create D3D11CreateDevice."); _logger.LogHResult(hresult); MessageBox(0, L"Failed to initialize Renderer, see log for details.", 0, 0); return false; } if (featureLevel != D3D_FEATURE_LEVEL_11_0) //if (featureLevel != 0xc000) { // TODO: Throw exceptions _logger.LogLine(L"Failed to initialize Renderer: Required D3D feature level 11 not supported."); MessageBox(0, L"Failed to initialize Renderer, see log for details.", 0, 0); return false; } hresult = (_d3dDevice->CheckMultisampleQualityLevels(DXGI_FORMAT_R8G8B8A8_UNORM, 4, &_4xMsaaQuality)); if (FAILED(hresult)) { _logger.LogHResult(hresult); } assert(_4xMsaaQuality > 0); DXGI_SWAP_CHAIN_DESC swapChainDescription; swapChainDescription.BufferDesc.Width = _clientWidth; swapChainDescription.BufferDesc.Height = _clientHeight; swapChainDescription.BufferDesc.RefreshRate.Numerator = 60; swapChainDescription.BufferDesc.RefreshRate.Denominator = 1; swapChainDescription.BufferDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM; swapChainDescription.BufferDesc.ScanlineOrdering = DXGI_MODE_SCANLINE_ORDER_UNSPECIFIED; swapChainDescription.BufferDesc.Scaling = DXGI_MODE_SCALING_UNSPECIFIED; if (_enable4xMsaa) { swapChainDescription.SampleDesc.Count = 4; swapChainDescription.SampleDesc.Quality = _4xMsaaQuality - 1; } else { swapChainDescription.SampleDesc.Count = 1; swapChainDescription.SampleDesc.Quality = 0; } swapChainDescription.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT; swapChainDescription.BufferCount = 1; swapChainDescription.OutputWindow = _windowHandle; swapChainDescription.Windowed = true; swapChainDescription.SwapEffect = DXGI_SWAP_EFFECT_DISCARD; swapChainDescription.Flags = 0; IDXGIDevice* dxgiDevice = 0; hresult = (_d3dDevice->QueryInterface(__uuidof(IDXGIDevice), (void**)&dxgiDevice)); if (FAILED(hresult)) { _logger.LogHResult(hresult); } IDXGIAdapter* dxgiAdapter = 0; hresult = (dxgiDevice->GetParent(__uuidof(IDXGIAdapter), (void**)&dxgiAdapter)); if (FAILED(hresult)) { _logger.LogHResult(hresult); } IDXGIFactory* dxgiFactory = 0; hresult = (dxgiAdapter->GetParent(__uuidof(IDXGIFactory), (void**)&dxgiFactory)); if (FAILED(hresult)) { _logger.LogHResult(hresult); } hresult = (dxgiFactory->CreateSwapChain(_d3dDevice, &swapChainDescription, &_swapChain)); if (FAILED(hresult)) { _logger.LogHResult(hresult); } if (dxgiDevice) { dxgiDevice->Release(); dxgiDevice = 0; } if (dxgiAdapter) { dxgiAdapter->Release(); dxgiAdapter = 0; } if (dxgiFactory) { dxgiFactory->Release(); dxgiFactory = 0; } OnResize(); return true; }
void DirectXController::Initialize( void ) { WindowController::Get()->Initialize(); WindowController::Get()->OpenWindow(); driverType = D3D_DRIVER_TYPE_HARDWARE; enable4xMsaa = false; msaa4xQuality = 0; device.dx = nullptr; deviceContext.dx = nullptr; swapChain = nullptr; depthStencilBuffer = nullptr; renderTargetView = nullptr; depthStencilView = nullptr; ZeroMemory( &viewport, sizeof(D3D11_VIEWPORT) ); UINT createDeviceFlags = 0; #if defined(_DEBUG) || defined(DEBUG) createDeviceFlags |= D3D11_CREATE_DEVICE_DEBUG; #endif D3D_FEATURE_LEVEL requiredFeatureLevel = D3D_FEATURE_LEVEL_11_0; D3D_FEATURE_LEVEL featureLevel; HRESULT hResult = D3D11CreateDevice( NULL, // Adapter driverType, // Driver Type NULL, // Software createDeviceFlags, // Flags &requiredFeatureLevel, // Feature levels 1, // num Feature levels D3D11_SDK_VERSION, // SDK Version &device.dx, // Device &featureLevel, // Feature Level &deviceContext.dx ); // Device Context // Handle any device creation or DirectX version errors if( FAILED(hResult) ) { MessageBox(NULL, L"D3D11CreateDevice Failed", NULL, NULL); //return false; } if( featureLevel != requiredFeatureLevel ) { MessageBox(NULL, L"Direct3D Feature Level 11 unsupported", NULL, NULL); //return false; } // Check for 4X MSAA quality support HR(device.dx->CheckMultisampleQualityLevels( DXGI_FORMAT_R8G8B8A8_UNORM, 4, &msaa4xQuality)); //assert( msaa4xQuality > 0 ); // Potential problem if quality is 0 // set up swap chain DXGI_SWAP_CHAIN_DESC swapChainDesc; ZeroMemory(&swapChainDesc, sizeof(swapChainDesc) ); swapChainDesc.BufferCount = 1; swapChainDesc.BufferDesc.Width = WindowController::Get()->GetWidth();//windowWidth; swapChainDesc.BufferDesc.Height = WindowController::Get()->GetHeight();//windowHeight; swapChainDesc.BufferDesc.RefreshRate.Numerator = 60; swapChainDesc.BufferDesc.RefreshRate.Denominator = 1; swapChainDesc.BufferDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM; swapChainDesc.BufferDesc.ScanlineOrdering = DXGI_MODE_SCANLINE_ORDER_UNSPECIFIED; swapChainDesc.BufferDesc.Scaling = DXGI_MODE_SCALING_UNSPECIFIED; swapChainDesc.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT; swapChainDesc.OutputWindow = Win32Controller::Get()->GetHWnd();//hMainWnd; swapChainDesc.Windowed = true; swapChainDesc.Flags = 0; if( enable4xMsaa ) { // Set up 4x MSAA swapChainDesc.SampleDesc.Count = 4; swapChainDesc.SampleDesc.Quality = msaa4xQuality - 1; } else { // No MSAA swapChainDesc.SampleDesc.Count = 1; swapChainDesc.SampleDesc.Quality = 0; } // To correctly create the swap chain, we must use the IDXGIFactory that // was used to create the device. IDXGIDevice* dxgiDevice = 0; IDXGIAdapter* dxgiAdapter = 0; IDXGIFactory* dxgiFactory = 0; HR(device.dx->QueryInterface( __uuidof(IDXGIDevice), (void**)&dxgiDevice)); HR(dxgiDevice->GetParent( __uuidof(IDXGIAdapter), (void**)&dxgiAdapter)); HR(dxgiAdapter->GetParent( __uuidof(IDXGIFactory), (void**)&dxgiFactory)); // Finally make the swap chain and release the DXGI stuff HR(dxgiFactory->CreateSwapChain(device.dx, &swapChainDesc, &swapChain)); ReleaseCOMobjMacro(dxgiDevice); ReleaseCOMobjMacro(dxgiAdapter); ReleaseCOMobjMacro(dxgiFactory); // The remaining steps also need to happen each time the window // is resized, so just run the OnResize method Resize(); }
// // Recreate shared texture // DUPL_RETURN OUTPUTMANAGER::CreateSharedSurf(INT SingleOutput, _Out_ UINT* OutCount, _Out_ RECT* DeskBounds) { HRESULT hr; // Get DXGI resources IDXGIDevice* DxgiDevice = nullptr; hr = m_Device->QueryInterface(__uuidof(IDXGIDevice), reinterpret_cast<void**>(&DxgiDevice)); if (FAILED(hr)) { return ProcessFailure(nullptr, L"Failed to QI for DXGI Device", L"Error", hr); } IDXGIAdapter* DxgiAdapter = nullptr; hr = DxgiDevice->GetParent(__uuidof(IDXGIAdapter), reinterpret_cast<void**>(&DxgiAdapter)); DxgiDevice->Release(); DxgiDevice = nullptr; if (FAILED(hr)) { return ProcessFailure(m_Device, L"Failed to get parent DXGI Adapter", L"Error", hr, SystemTransitionsExpectedErrors); } // Set initial values so that we always catch the right coordinates DeskBounds->left = INT_MAX; DeskBounds->right = INT_MIN; DeskBounds->top = INT_MAX; DeskBounds->bottom = INT_MIN; IDXGIOutput* DxgiOutput = nullptr; // Figure out right dimensions for full size desktop texture and # of outputs to duplicate UINT OutputCount; if (SingleOutput < 0) { hr = S_OK; for (OutputCount = 0; SUCCEEDED(hr); ++OutputCount) // for (OutputCount = 0; OutputCount<1; ++OutputCount) { if (DxgiOutput) { DxgiOutput->Release(); DxgiOutput = nullptr; } hr = DxgiAdapter->EnumOutputs(OutputCount, &DxgiOutput); if (DxgiOutput && (hr != DXGI_ERROR_NOT_FOUND)) { DXGI_OUTPUT_DESC DesktopDesc; DxgiOutput->GetDesc(&DesktopDesc); DeskBounds->left = min(DesktopDesc.DesktopCoordinates.left, DeskBounds->left); DeskBounds->top = min(DesktopDesc.DesktopCoordinates.top, DeskBounds->top); DeskBounds->right = max(DesktopDesc.DesktopCoordinates.right, DeskBounds->right); DeskBounds->bottom = max(DesktopDesc.DesktopCoordinates.bottom, DeskBounds->bottom); } } --OutputCount; } else { hr = DxgiAdapter->EnumOutputs(SingleOutput, &DxgiOutput); if (FAILED(hr)) { DxgiAdapter->Release(); DxgiAdapter = nullptr; return ProcessFailure(m_Device, L"Output specified to be duplicated does not exist", L"Error", hr); } DXGI_OUTPUT_DESC DesktopDesc; DxgiOutput->GetDesc(&DesktopDesc); *DeskBounds = DesktopDesc.DesktopCoordinates; DxgiOutput->Release(); DxgiOutput = nullptr; OutputCount = 1; } DxgiAdapter->Release(); DxgiAdapter = nullptr; // Set passed in output count variable *OutCount = OutputCount; if (OutputCount == 0) { // We could not find any outputs, the system must be in a transition so return expected error // so we will attempt to recreate return DUPL_RETURN_ERROR_EXPECTED; } // Create shared texture for all duplication threads to draw into D3D11_TEXTURE2D_DESC DeskTexD; RtlZeroMemory(&DeskTexD, sizeof(D3D11_TEXTURE2D_DESC)); DeskTexD.Width = DeskBounds->right - DeskBounds->left; DeskTexD.Height = DeskBounds->bottom - DeskBounds->top; DeskTexD.MipLevels = 1; DeskTexD.ArraySize = 1; DeskTexD.Format = DXGI_FORMAT_B8G8R8A8_UNORM; DeskTexD.SampleDesc.Count = 1; DeskTexD.Usage = D3D11_USAGE_DEFAULT; DeskTexD.BindFlags = D3D11_BIND_RENDER_TARGET | D3D11_BIND_SHADER_RESOURCE; DeskTexD.CPUAccessFlags = 0; DeskTexD.MiscFlags = D3D11_RESOURCE_MISC_SHARED_KEYEDMUTEX; hr = m_Device->CreateTexture2D(&DeskTexD, nullptr, &m_SharedSurf); if (FAILED(hr)) { if (OutputCount != 1) { // If we are duplicating the complete desktop we try to create a single texture to hold the // complete desktop image and blit updates from the per output DDA interface. The GPU can // always support a texture size of the maximum resolution of any single output but there is no // guarantee that it can support a texture size of the desktop. // The sample only use this large texture to display the desktop image in a single window using DX // we could revert back to using GDI to update the window in this failure case. return ProcessFailure(m_Device, L"Failed to create DirectX shared texture - we are attempting to create a texture the size of the complete desktop and this may be larger than the maximum texture size of your GPU. Please try again using the -output command line parameter to duplicate only 1 monitor or configure your computer to a single monitor configuration", L"Error", hr, SystemTransitionsExpectedErrors); } else { return ProcessFailure(m_Device, L"Failed to create shared texture", L"Error", hr, SystemTransitionsExpectedErrors); } } // Get keyed mutex hr = m_SharedSurf->QueryInterface(__uuidof(IDXGIKeyedMutex), reinterpret_cast<void**>(&m_KeyMutex)); if (FAILED(hr)) { return ProcessFailure(m_Device, L"Failed to query for keyed mutex in OUTPUTMANAGER", L"Error", hr); } return DUPL_RETURN_SUCCESS; }
bool D3DRenderWidget::createDevice() { HRESULT re; // 函数返回值, HRESULT 是一种简单的数据类型,通常被属性和 ATL 用作返回值。 UINT createDeviceFlags = 0; #if defined(DEBUG) || defined(_DEBUG) createDeviceFlags |= D3D11_CREATE_DEVICE_DEBUG; #endif D3D_FEATURE_LEVEL featureLevel; // Direct3D 设备的功能级别目标 HRESULT hr = D3D11CreateDevice( 0, m_d3dDriverType, 0, createDeviceFlags, 0, 0, D3D11_SDK_VERSION, &m_d3dDevice, &featureLevel, &m_d3dImmediateContext); if (FAILED(hr)) { MessageBox(0, L"D3D11CreateDevice Failed.", 0, 0); return false; } if (featureLevel != D3D_FEATURE_LEVEL_11_0) { MessageBox(0, L"Direct3D Feature Level 11 unsupported.", 0, 0); return false; } re = m_d3dDevice->CheckMultisampleQualityLevels( DXGI_FORMAT_R8G8B8A8_UNORM, 4, &m_4xMsaaQuality); if (FAILED(re)) return false; assert(m_4xMsaaQuality > 0); DXGI_SWAP_CHAIN_DESC sd; sd.BufferDesc.Width = width(); sd.BufferDesc.Height = height(); sd.BufferDesc.RefreshRate.Numerator = 60; // 分子 sd.BufferDesc.RefreshRate.Denominator = 1; // 分母 sd.BufferDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM; sd.BufferDesc.ScanlineOrdering = DXGI_MODE_SCANLINE_ORDER_UNSPECIFIED; sd.BufferDesc.Scaling = DXGI_MODE_SCALING_UNSPECIFIED; if (m_enable4xMsaa) { sd.SampleDesc.Count = 4; sd.SampleDesc.Quality = m_4xMsaaQuality - 1; } else { sd.SampleDesc.Count = 1; sd.SampleDesc.Quality = 0; } sd.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT; sd.BufferCount = 1; sd.OutputWindow = (HWND)winId(); sd.Windowed = true; sd.SwapEffect = DXGI_SWAP_EFFECT_DISCARD; sd.Flags = 0; IDXGIDevice* dxgiDevice = 0; re = m_d3dDevice->QueryInterface(__uuidof(IDXGIDevice), (void**)&dxgiDevice); if (FAILED(re)) return false; IDXGIAdapter* dxgiAdapter = 0; re = dxgiDevice->GetParent(__uuidof(IDXGIAdapter), (void**)&dxgiAdapter); if (FAILED(re)) return false; IDXGIFactory* dxgiFactory = 0; re = dxgiAdapter->GetParent(__uuidof(IDXGIFactory), (void**)&dxgiFactory); if (FAILED(re)) return false; re = dxgiFactory->CreateSwapChain(m_d3dDevice, &sd, &m_swapChain); if (FAILED(re)) return false; safe_release(dxgiDevice); safe_release(dxgiAdapter); safe_release(dxgiFactory); return true; }
bool D3DApp::InitDirect3D() { // Create the device and device context. UINT createDeviceFlags = 0; #if defined(DEBUG) || defined(_DEBUG) createDeviceFlags |= D3D11_CREATE_DEVICE_DEBUG; #endif D3D_FEATURE_LEVEL featureLevel; HRESULT hr = D3D11CreateDevice( 0, // default adapter D3D_DRIVER_TYPE_HARDWARE,// D3D_DRIVER_TYPE_HARDWARE - 3D hardware acceleration for rendering 0, // no software driver createDeviceFlags, 0, 0, // default feature level array D3D11_SDK_VERSION, // This never changes &md3dDevice, // The now created device &featureLevel, // Greatest feature level supported &md3dImmediateContext); // The now created device context if( FAILED(hr) ) { MessageBox(0, L"D3D11CreateDevice Failed.", 0, 0); return false; } // This is the order that the feature levels are tried if( featureLevel == D3D_FEATURE_LEVEL_11_0 ) { printf("Using Direct3D Feature Level 11.0\n"); } else if( featureLevel == D3D_FEATURE_LEVEL_10_1 ) { printf("Using Direct3D Feature Level 10.1\n"); } else if( featureLevel == D3D_FEATURE_LEVEL_10_0 ) { printf("Using Direct3D Feature Level 10.0\n"); } else if( featureLevel == D3D_FEATURE_LEVEL_9_3 ) { printf("Using Direct3D Feature Level 9.3\n"); } else if( featureLevel == D3D_FEATURE_LEVEL_9_2 ) { printf("Using Direct3D Feature Level 9.2\n"); } else if( featureLevel == D3D_FEATURE_LEVEL_9_1 ) { printf("Using Direct3D Feature Level 9.1\n"); } // Check 4X MSAA quality support for our back buffer format. // All Direct3D 11 capable devices support 4X MSAA for all render // target formats, so we only need to check quality support. HR(md3dDevice->CheckMultisampleQualityLevels( DXGI_FORMAT_R8G8B8A8_UNORM, 4, &m4xMsaaQuality)); // If m4xMsaaQuality > 0 4x MSAA is supported //assert( m4xMsaaQuality > 0 ); // Fill out a DXGI_SWAP_CHAIN_DESC to describe our swap chain. DXGI_SWAP_CHAIN_DESC sd; sd.BufferDesc.Width = mClientWidth; sd.BufferDesc.Height = mClientHeight; sd.BufferDesc.RefreshRate.Numerator = 60; sd.BufferDesc.RefreshRate.Denominator = 1; sd.BufferDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM; sd.BufferDesc.ScanlineOrdering = DXGI_MODE_SCANLINE_ORDER_UNSPECIFIED; sd.BufferDesc.Scaling = DXGI_MODE_SCALING_UNSPECIFIED; // Use 4X MSAA? if( mEnable4xMsaa ) { sd.SampleDesc.Count = 4; sd.SampleDesc.Quality = m4xMsaaQuality-1; } // No MSAA else { sd.SampleDesc.Count = 1; sd.SampleDesc.Quality = 0; } sd.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT; // Rendering to the back buffer sd.BufferCount = 1; // Number of back buffers sd.OutputWindow = mhMainWnd; // Handle to the window we are rendering to sd.Windowed = true; sd.SwapEffect = DXGI_SWAP_EFFECT_DISCARD; // Let the driver choose the most efficient method sd.Flags = 0; // To correctly create the swap chain, we must use the IDXGIFactory that was // used to create the device. If we tried to use a different IDXGIFactory instance // (by calling CreateDXGIFactory), we get an error: "IDXGIFactory::CreateSwapChain: // This function is being called with a device from a different IDXGIFactory." IDXGIDevice* dxgiDevice = 0; HR(md3dDevice->QueryInterface(__uuidof(IDXGIDevice), (void**)&dxgiDevice)); IDXGIAdapter* dxgiAdapter = 0; HR(dxgiDevice->GetParent(__uuidof(IDXGIAdapter), (void**)&dxgiAdapter)); IDXGIFactory* dxgiFactory = 0; HR(dxgiAdapter->GetParent(__uuidof(IDXGIFactory), (void**)&dxgiFactory)); HR(dxgiFactory->CreateSwapChain(md3dDevice, &sd, &mSwapChain)); // Disables Alt + Enter to toggle between fullscreen and windowed mode //HR(dxgiFactory->MakeWindowAssociation(mhMainWnd, DXGI_MWA_NO_ALT_ENTER)); ReleaseCOM(dxgiDevice); ReleaseCOM(dxgiAdapter); ReleaseCOM(dxgiFactory); // The remaining steps that need to be carried out for d3d creation // also need to be executed every time the window is resized. So // just call the OnResize method here to avoid code duplication. OnResize(); return true; }
bool D3DApp::InitDirect3D() { // Create the device and device context. UINT createDeviceFlags = 0; #if defined(DEBUG) || defined(_DEBUG) createDeviceFlags |= D3D11_CREATE_DEVICE_DEBUG; #endif D3D_FEATURE_LEVEL featureLevel; HRESULT hr = D3D11CreateDevice( 0, // default adapter md3dDriverType, 0, // no software device createDeviceFlags, 0, 0, // default feature level array D3D11_SDK_VERSION, &md3dDevice, &featureLevel, &md3dImmediateContext); if( FAILED(hr) ) { MessageBox(0, L"D3D11CreateDevice Failed.", 0, 0); return false; } if( featureLevel != D3D_FEATURE_LEVEL_11_0 ) { MessageBox(0, L"Direct3D Feature Level 11 unsupported.", 0, 0); return false; } // Check 4X MSAA quality support for our back buffer format. // All Direct3D 11 capable devices support 4X MSAA for all render // target formats, so we only need to check quality support. HR(md3dDevice->CheckMultisampleQualityLevels( DXGI_FORMAT_R8G8B8A8_UNORM, 4, &m4xMsaaQuality)); assert( m4xMsaaQuality > 0 ); // Fill out a DXGI_SWAP_CHAIN_DESC to describe our swap chain. DXGI_SWAP_CHAIN_DESC sd; ZeroMemory(&sd, sizeof(DXGI_SWAP_CHAIN_DESC)); sd.BufferDesc.Width = mClientWidth; sd.BufferDesc.Height = mClientHeight; sd.Windowed = true; sd.BufferDesc.RefreshRate.Numerator = m_MonitorNumerator; sd.BufferDesc.RefreshRate.Denominator = m_MonitorDenumerator; sd.BufferDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM; sd.BufferDesc.ScanlineOrdering = DXGI_MODE_SCANLINE_ORDER_UNSPECIFIED; sd.BufferDesc.Scaling = DXGI_MODE_SCALING_UNSPECIFIED; // Use 4X MSAA? if( mEnable4xMsaa ) { sd.SampleDesc.Count = 4; sd.SampleDesc.Quality = m4xMsaaQuality-1; } // No MSAA else { sd.SampleDesc.Count = 1; sd.SampleDesc.Quality = 0; } sd.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT; sd.BufferCount = 1; sd.OutputWindow = mhMainWnd; sd.SwapEffect = DXGI_SWAP_EFFECT_DISCARD; sd.Flags = 0; // To correctly create the swap chain, we must use the IDXGIFactory that was // used to create the device. If we tried to use a different IDXGIFactory instance // (by calling CreateDXGIFactory), we get an error: "IDXGIFactory::CreateSwapChain: // This function is being called with a device from a different IDXGIFactory." IDXGIDevice* dxgiDevice = 0; HR(md3dDevice->QueryInterface(__uuidof(IDXGIDevice), (void**)&dxgiDevice)); IDXGIAdapter* dxgiAdapter = 0; HR(dxgiDevice->GetParent(__uuidof(IDXGIAdapter), (void**)&dxgiAdapter)); IDXGIFactory* dxgiFactory = 0; HR(dxgiAdapter->GetParent(__uuidof(IDXGIFactory), (void**)&dxgiFactory)); HR(dxgiFactory->CreateSwapChain(md3dDevice, &sd, &mSwapChain)); //Disable Alt-Enter Sequence dxgiFactory->MakeWindowAssociation(mhMainWnd, DXGI_MWA_NO_ALT_ENTER); ReleaseCOM(dxgiDevice); ReleaseCOM(dxgiAdapter); ReleaseCOM(dxgiFactory); // The remaining steps that need to be carried out for d3d creation // also need to be executed every time the window is resized. So // just call the OnResize method here to avoid code duplication. OnResize(); if (mFullScreen){ mSwapChain->SetFullscreenState(true, NULL); } return true; }
void InitializeDirectX() { UINT createDeviceFlags = 0; #if defined(DEBUG) || defined(_DEBUG) createDeviceFlags |= D3D11_CREATE_DEVICE_DEBUG; #endif D3D_FEATURE_LEVEL featureLevels[] = { D3D_FEATURE_LEVEL_11_0, D3D_FEATURE_LEVEL_10_1, D3D_FEATURE_LEVEL_10_0 }; ID3D11Device* direct3DDevice = nullptr; ID3D11DeviceContext* direct3DDeviceContext = nullptr; ThrowIfFailed(D3D11CreateDevice(NULL, D3D_DRIVER_TYPE_HARDWARE, NULL, createDeviceFlags, featureLevels, ARRAYSIZE(featureLevels), D3D11_SDK_VERSION, &direct3DDevice, &mFeatureLevel, &direct3DDeviceContext), "D3D11CreateDevice() failed"); ThrowIfFailed(direct3DDevice->QueryInterface(__uuidof(ID3D11Device1), reinterpret_cast<void**>(&mDirect3DDevice)), "ID3D11Device::QueryInterface() failed"); ThrowIfFailed(direct3DDeviceContext->QueryInterface(__uuidof(ID3D11DeviceContext1), reinterpret_cast<void**>(&mDirect3DDeviceContext)), "ID3D11Device::QueryInterface() failed"); ReleaseObject(direct3DDevice); ReleaseObject(direct3DDeviceContext); UINT multiSamplingCount = 4; UINT multiSamplingQualityLevels; mDirect3DDevice->CheckMultisampleQualityLevels(DXGI_FORMAT_R8G8B8A8_UNORM, multiSamplingCount, &multiSamplingQualityLevels); if (multiSamplingQualityLevels == 0) { throw GameException("Unsupported multi-sampling quality"); } DXGI_SWAP_CHAIN_DESC1 swapChainDesc; ZeroMemory(&swapChainDesc, sizeof(swapChainDesc)); swapChainDesc.Width = mScreenWidth; swapChainDesc.Height = mScreenHeight; swapChainDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM; swapChainDesc.SampleDesc.Count = multiSamplingCount; swapChainDesc.SampleDesc.Quality = multiSamplingQualityLevels - 1; swapChainDesc.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT; swapChainDesc.BufferCount = 1; swapChainDesc.SwapEffect = DXGI_SWAP_EFFECT_DISCARD; IDXGIDevice* dxgiDevice = nullptr; ThrowIfFailed(mDirect3DDevice->QueryInterface(__uuidof(IDXGIDevice), reinterpret_cast<void**>(&dxgiDevice)), "ID3D11Device::QueryInterface() failed"); IDXGIAdapter *dxgiAdapter = nullptr; HRESULT hr; if (FAILED(hr = dxgiDevice->GetParent(__uuidof(IDXGIAdapter), reinterpret_cast<void**>(&dxgiAdapter)))) { ReleaseObject(dxgiDevice); throw GameException("IDXGIDevice::GetParent() failed retrieving adapter.", hr); } IDXGIFactory2* dxgiFactory = nullptr; if (FAILED(hr = dxgiAdapter->GetParent(__uuidof(IDXGIFactory2), reinterpret_cast<void**>(&dxgiFactory)))) { ReleaseObject(dxgiDevice); ReleaseObject(dxgiAdapter); throw GameException("IDXGIAdapter::GetParent() failed retrieving factory.", hr); } DXGI_SWAP_CHAIN_FULLSCREEN_DESC fullScreenDesc; ZeroMemory(&fullScreenDesc, sizeof(fullScreenDesc)); fullScreenDesc.RefreshRate.Numerator = 60; fullScreenDesc.RefreshRate.Denominator = 1; fullScreenDesc.Windowed = true; if (FAILED(hr = dxgiFactory->CreateSwapChainForHwnd(dxgiDevice, mWindowHandle, &swapChainDesc, &fullScreenDesc, nullptr, &mSwapChain))) { ReleaseObject(dxgiDevice); ReleaseObject(dxgiAdapter); ReleaseObject(dxgiFactory); throw GameException("IDXGIDevice::CreateSwapChainForHwnd() failed.", hr); } ReleaseObject(dxgiDevice); ReleaseObject(dxgiAdapter); ReleaseObject(dxgiFactory); ID3D11Texture2D* backBuffer; ThrowIfFailed(mSwapChain->GetBuffer(0, __uuidof(ID3D11Texture2D), reinterpret_cast<void**>(&backBuffer)), "IDXGISwapChain::GetBuffer() failed."); if (FAILED(hr = mDirect3DDevice->CreateRenderTargetView(backBuffer, nullptr, &mRenderTargetView))) { ReleaseObject(backBuffer); throw GameException("IDXGIDevice::CreateRenderTargetView() failed.", hr); } ReleaseObject(backBuffer); D3D11_TEXTURE2D_DESC depthStencilDesc; ZeroMemory(&depthStencilDesc, sizeof(depthStencilDesc)); depthStencilDesc.Width = mScreenWidth; depthStencilDesc.Height = mScreenHeight; depthStencilDesc.MipLevels = 1; depthStencilDesc.ArraySize = 1; depthStencilDesc.Format = DXGI_FORMAT_D24_UNORM_S8_UINT; depthStencilDesc.BindFlags = D3D11_BIND_DEPTH_STENCIL; depthStencilDesc.Usage = D3D11_USAGE_DEFAULT; depthStencilDesc.SampleDesc.Count = multiSamplingCount; depthStencilDesc.SampleDesc.Quality = multiSamplingQualityLevels - 1; ThrowIfFailed(mDirect3DDevice->CreateTexture2D(&depthStencilDesc, nullptr, &mDepthStencilBuffer), "IDXGIDevice::CreateTexture2D() failed."); ThrowIfFailed(mDirect3DDevice->CreateDepthStencilView(mDepthStencilBuffer, nullptr, &mDepthStencilView), "IDXGIDevice::CreateDepthStencilView() failed."); D3D11_VIEWPORT viewport; viewport.TopLeftX = 0.0f; viewport.TopLeftY = 0.0f; viewport.Width = static_cast<float>(mScreenWidth); viewport.Height = static_cast<float>(mScreenHeight); viewport.MinDepth = 0.0f; viewport.MaxDepth = 1.0f; mDirect3DDeviceContext->OMSetRenderTargets(1, &mRenderTargetView, mDepthStencilView); mDirect3DDeviceContext->RSSetViewports(1, &viewport); }