//======================================================================== // Initialize hardware for rendering. Member of AbstractRender //======================================================================== HRESULT DX10Render::initDevice() { UINT createDeviceFlags = 0; #ifdef _DEBUG createDeviceFlags |= D3D10_CREATE_DEVICE_DEBUG; #endif HRESULT hr = D3D10CreateDevice(NULL, D3D10_DRIVER_TYPE_HARDWARE, NULL, createDeviceFlags, D3D10_SDK_VERSION, &this->device); if (FAILED(hr)) return hr; DXGI_SWAP_CHAIN_DESC sd; ZeroMemory(&sd, sizeof(sd)); sd.BufferCount = 1; sd.BufferDesc.Width = this->resolution.width; sd.BufferDesc.Height = this->resolution.height; 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 = this->hWindow; sd.SampleDesc.Count = 4; sd.SampleDesc.Quality = 4; sd.Windowed = !this->fullscreen; IDXGIFactory *factory = getDeviceFactory(device); if (factory == NULL) return E_FAIL; hr = factory->CreateSwapChain(device, &sd, &swapChain); if (FAILED(hr)) return hr; factory->Release(); return S_OK; }
/* * Class: org_lwjgl_d3d11_impl_DXGIFactoryImpl * Method: nCreateSwapChain * Signature: (JJJJ)J */ extern "C" JNIEXPORT jlong JNICALL Java_org_lwjgl_d3d11_impl_DXGIFactoryImpl_nCreateSwapChain (JNIEnv * env, jclass clazz, jlong thisPtr, jlong devicePtr, jlong swapChainDescPtr, jlong swapChainOutPtr) { IDXGIFactory* factory = (IDXGIFactory*)(intptr_t)thisPtr; IUnknown* device = (IUnknown*)(intptr_t)devicePtr; DXGI_SWAP_CHAIN_DESC* swapChainDesc = (DXGI_SWAP_CHAIN_DESC*)(intptr_t)swapChainDescPtr; IDXGISwapChain** swapChain = (IDXGISwapChain**)(intptr_t)swapChainOutPtr; return (jlong)factory->CreateSwapChain(device, swapChainDesc, swapChain); }
void InitBackendInfo() { HRESULT hr = DX11::D3D::LoadDXGI(); if (SUCCEEDED(hr)) hr = DX11::D3D::LoadD3D(); if (FAILED(hr)) { DX11::D3D::UnloadDXGI(); return; } g_Config.backend_info.APIType = API_D3D11; g_Config.backend_info.bUseRGBATextures = true; // the GX formats barely match any D3D11 formats g_Config.backend_info.bSupports3DVision = false; g_Config.backend_info.bSupportsDualSourceBlend = true; g_Config.backend_info.bSupportsFormatReinterpretation = true; g_Config.backend_info.bSupportsPixelLighting = true; IDXGIFactory* factory; IDXGIAdapter* ad; hr = DX11::PCreateDXGIFactory(__uuidof(IDXGIFactory), (void**)&factory); if (FAILED(hr)) PanicAlert("Failed to create IDXGIFactory object"); char tmpstr[512] = {}; DXGI_ADAPTER_DESC desc; // adapters g_Config.backend_info.Adapters.clear(); g_Config.backend_info.AAModes.clear(); while (factory->EnumAdapters((UINT)g_Config.backend_info.Adapters.size(), &ad) != DXGI_ERROR_NOT_FOUND) { ad->GetDesc(&desc); WideCharToMultiByte(/*CP_UTF8*/CP_ACP, 0, desc.Description, -1, tmpstr, 512, 0, false); // TODO: These don't get updated on adapter change, yet if (g_Config.backend_info.Adapters.size() == g_Config.iAdapter) { char buf[32]; std::vector<DXGI_SAMPLE_DESC> modes; modes = DX11::D3D::EnumAAModes(ad); for (unsigned int i = 0; i < modes.size(); ++i) { if (i == 0) sprintf_s(buf, 32, "None"); else if (modes[i].Quality) sprintf_s(buf, 32, "%d samples (quality level %d)", modes[i].Count, modes[i].Quality); else sprintf_s(buf, 32, "%d samples", modes[i].Count); g_Config.backend_info.AAModes.push_back(buf); } } g_Config.backend_info.Adapters.push_back(tmpstr); ad->Release(); } factory->Release(); // Clear ppshaders string vector g_Config.backend_info.PPShaders.clear(); DX11::D3D::UnloadDXGI(); DX11::D3D::UnloadD3D(); }
static ovrGraphicsLuid GetDefaultAdapterLuid() { ovrGraphicsLuid luid = ovrGraphicsLuid(); #if defined(_WIN32) IDXGIFactory* factory = nullptr; if (SUCCEEDED(CreateDXGIFactory(IID_PPV_ARGS(&factory)))) { IDXGIAdapter* adapter = nullptr; if (SUCCEEDED(factory->EnumAdapters(0, &adapter))) { DXGI_ADAPTER_DESC desc; adapter->GetDesc(&desc); memcpy(&luid, &desc.AdapterLuid, sizeof(luid)); adapter->Release(); } factory->Release(); } #endif return luid; }
void LogVideoCardStats() { HRESULT err; IDXGIFactory *factory; if(SUCCEEDED(err = CreateDXGIFactory(__uuidof(IDXGIFactory), (void**)&factory))) { UINT i=0; IDXGIAdapter *giAdapter; while(factory->EnumAdapters(i++, &giAdapter) == S_OK) { Log(TEXT("------------------------------------------")); DXGI_ADAPTER_DESC adapterDesc; if(err = SUCCEEDED(giAdapter->GetDesc(&adapterDesc))) { Log(TEXT("Adapter %u"), i); Log(TEXT(" Video Adapter: %s"), adapterDesc.Description); Log(TEXT(" Video Adapeter Dedicated Video Memory: %u"), adapterDesc.DedicatedVideoMemory); Log(TEXT(" Video Adapeter Shared System Memory: %u"), adapterDesc.SharedSystemMemory); } else AppWarning(TEXT("Could not query adapter %u"), i); giAdapter->Release(); } factory->Release(); } }
/* * Class: org_lwjgl_d3d11_impl_DXGIFactoryImpl * Method: nMakeWindowAssociation * Signature: (JJI)J */ extern "C" JNIEXPORT jlong JNICALL Java_org_lwjgl_d3d11_impl_DXGIFactoryImpl_nMakeWindowAssociation (JNIEnv * env, jclass clazz, jlong thisPtr, jlong hwnd, jint flags) { IDXGIFactory* factory = (IDXGIFactory*)(intptr_t)thisPtr; HWND hWnd = (HWND)hwnd; UINT Flags = (UINT)flags; return (jlong)factory->MakeWindowAssociation(hWnd, Flags); }
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(); }
std::wstring DXGI::GetGPUInfo (void) { static wchar_t adapters [4096]; *adapters = L'\0'; if (!NVAPI::CountPhysicalGPUs ()) { IDXGIFactory* pFactory = NULL; CreateDXGIFactory (__uuidof(IDXGIFactory), (void **)&pFactory); IDXGIAdapter* pDXGIAdapter; for (UINT i = 0; pFactory->EnumAdapters (i, &pDXGIAdapter) != DXGI_ERROR_NOT_FOUND; ++i) { DXGI_ADAPTER_DESC adapterDesc; pDXGIAdapter->GetDesc (&adapterDesc); // Skip Microsoft's virtual adapters... if (adapterDesc.VendorId != 0x1414) { swprintf (adapters, L"%sAdapter %02u (Vendor ID: %04X):\r\n" L"----------------------------------------\r\n\r\n" L" %s\r\n\r\n" L" %4.1f GiB Dedicated VRAM\r\n" L" %4.1f GiB Shared Memory (GART)\r\n\r\n", adapters, i, adapterDesc.VendorId, adapterDesc.Description, (float)adapterDesc.DedicatedVideoMemory / 1024.0f / 1024.0f / 1024.0f, (float)adapterDesc.SharedSystemMemory / 1024.0f / 1024.0f / 1024.0f); } pDXGIAdapter->Release (); } pFactory->Release (); } else { DXGI_ADAPTER_DESC* adapter_descs = NVAPI::EnumGPUs_DXGI (); int i = 0; while (*adapter_descs [i].Description != L'\0') { swprintf (adapters, L"%sAdapter %02d (Vendor ID: %04X):\r\n" L"----------------------------------------\r\n\r\n" L" %s\r\n\r\n" L" %4.1f GiB Dedicated VRAM\r\n" L" %4.1f GiB Shared Memory (GART)\r\n\r\n", adapters, i, adapter_descs [i].VendorId, adapter_descs [i].Description, (float)adapter_descs [i].DedicatedVideoMemory / 1024.0f / 1024.0f / 1024.0f, (float)adapter_descs [i].SharedSystemMemory / 1024.0f / 1024.0f / 1024.0f); ++i; } } return std::wstring (adapters); }
HRESULT CContextManager::CreateContext(HWND hWnd, int Width, int Height) { D3D_FEATURE_LEVEL featureLevels[] = { D3D_FEATURE_LEVEL_11_0, D3D_FEATURE_LEVEL_10_1, D3D_FEATURE_LEVEL_10_0, }; UINT numFeatureLevels = ARRAYSIZE(featureLevels); DXGI_SWAP_CHAIN_DESC sd; ZeroMemory(&sd, sizeof(sd)); sd.BufferCount = 1; sd.BufferDesc.Width = Width; sd.BufferDesc.Height = Height; 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 = hWnd; sd.SampleDesc.Count = 1; sd.SampleDesc.Quality = 0; sd.Windowed = TRUE; sd.Flags = DXGI_SWAP_CHAIN_FLAG_ALLOW_MODE_SWITCH; /*#if _DEBUG int flags = D3D11_CREATE_DEVICE_DEBUG; #else int flags = 0; #endif*/ int flags = 0; if (FAILED(D3D11CreateDeviceAndSwapChain(NULL, D3D_DRIVER_TYPE_HARDWARE, NULL, flags, featureLevels, numFeatureLevels, D3D11_SDK_VERSION, &sd, &m_SwapChain, &m_D3DDevice, NULL, &m_DeviceContext))) { return S_FALSE; } #if _DEBUG HRESULT hr = m_D3DDevice->QueryInterface(__uuidof(ID3D11Debug), reinterpret_cast<void**>(&m_D3DDebug)); if (FAILED(hr)) return hr; #endif // treure el ALT+INTRO automàtic IDXGIFactory* dxgiFactory; hr = m_SwapChain->GetParent(__uuidof(IDXGIFactory), (void **)&dxgiFactory); assert(hr == S_OK); hr = dxgiFactory->MakeWindowAssociation(hWnd, DXGI_MWA_NO_ALT_ENTER); assert(hr == S_OK); dxgiFactory->Release(); return S_OK; }
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(); }
OVR_PUBLIC_FUNCTION(ovrResult) ovr_Create(ovrSession* pSession, ovrGraphicsLuid* pLuid) { // Initialize the opaque pointer with our own OpenVR-specific struct ovrSession session = new struct ovrHmdStruct(); memset(session->ColorTexture, 0, sizeof(ovrHmdStruct::ColorTexture)); session->ThumbStick[ovrHand_Left] = true; // Get the compositor interface session->compositor = (vr::IVRCompositor*)VR_GetGenericInterface(vr::IVRCompositor_Version, &g_InitError); if (g_InitError != vr::VRInitError_None) return REV_InitErrorToOvrError(g_InitError); session->compositor->SetTrackingSpace(vr::TrackingUniverseSeated); // Get the settings interface session->settings = (vr::IVRSettings*)VR_GetGenericInterface(vr::IVRSettings_Version, &g_InitError); if (g_InitError != vr::VRInitError_None) return REV_InitErrorToOvrError(g_InitError); // Get the overlay interface session->overlay = (vr::IVROverlay*)VR_GetGenericInterface(vr::IVROverlay_Version, &g_InitError); if (g_InitError != vr::VRInitError_None) return REV_InitErrorToOvrError(g_InitError); // Apply settings session->ThumbStickRange = session->settings->GetFloat(REV_SETTINGS_SECTION, "ThumbStickRange", 0.8f); // Get the LUID for the adapter int32_t index; g_VRSystem->GetDXGIOutputInfo(&index); if (index == -1) index = 0; // Create the DXGI factory IDXGIFactory* pFactory; HRESULT hr = CreateDXGIFactory(__uuidof(IDXGIFactory), (void**)(&pFactory)); if (FAILED(hr)) return ovrError_IncompatibleGPU; IDXGIAdapter* pAdapter; hr = pFactory->EnumAdapters(index, &pAdapter); if (FAILED(hr)) return ovrError_MismatchedAdapters; DXGI_ADAPTER_DESC desc; hr = pAdapter->GetDesc(&desc); if (FAILED(hr)) return ovrError_MismatchedAdapters; // Copy the LUID into the structure memcpy(pLuid, &desc.AdapterLuid, sizeof(LUID)); // Cleanup and return pFactory->Release(); pAdapter->Release(); *pSession = session; return ovrSuccess; }
// Constructor. Creates a Direct3D device. D3D() : _Device(NULL), _ImmediateContext(NULL) { IDXGIFactory* factory; if (FAILED(CreateDXGIFactory(__uuidof(IDXGIFactory), (void**)&factory))) return; HRESULT hr = S_OK; UINT createDeviceFlags = 0; #ifdef _DEBUG createDeviceFlags |= D3D11_CREATE_DEVICE_DEBUG; #endif D3D_DRIVER_TYPE driverTypes[] = { D3D_DRIVER_TYPE_UNKNOWN, }; UINT numDriverTypes = sizeof(driverTypes) / sizeof(driverTypes[0]); D3D_FEATURE_LEVEL featureLevels[] = { D3D_FEATURE_LEVEL_11_0 }; unsigned int numFeatureLevels = 1; D3D_FEATURE_LEVEL usedFeatureLevel = D3D_FEATURE_LEVEL_11_0; // iterate the display adapters and look for a DirectX 11 capable device. for (UINT driverTypeIndex = 0; driverTypeIndex < numDriverTypes; driverTypeIndex++) { D3D_DRIVER_TYPE driverType = driverTypes[driverTypeIndex]; IDXGIAdapter* adapter; for (UINT i = 0; factory->EnumAdapters(i, &adapter) != DXGI_ERROR_NOT_FOUND; ++i) { DXGI_ADAPTER_DESC desc; adapter->GetDesc(&desc); std::wstring adapterDesc(desc.Description); hr = D3D11CreateDevice(adapter, driverType, NULL, createDeviceFlags, featureLevels, numFeatureLevels, D3D11_SDK_VERSION, &_Device, &usedFeatureLevel, &_ImmediateContext); if (SUCCEEDED(hr)) { wprintf(L"D3D is using: %s\n", adapterDesc.c_str()); break; } } if (!_Device) { printf("Couldn't create DirectX device.\nMaybe DirectX 11 is not supported on your machine?\n"); exit(-1); } if (adapter) adapter->Release(); if (SUCCEEDED(hr)) break; } factory->Release(); }
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; }
EGLint SwapChain11Api::createSwapChain( int backbufferWidth, int backbufferHeight, IDXGISwapChain **outSwapChain) { // We cannot create a swap chain for an HWND that is owned by a // different process DWORD currentProcessId = GetCurrentProcessId(); DWORD wndProcessId; GetWindowThreadProcessId((HWND)mWindow, &wndProcessId); if (currentProcessId != wndProcessId) { ERR("Could not create swap chain, window owned by different process"); return EGL_BAD_NATIVE_WINDOW; } ID3D11Device *device = getRenderer()->getDevice(); IDXGIFactory *factory = getRenderer()->getDxgiFactory(); DXGI_FORMAT format = gl_d3d11::ConvertRenderbufferFormat(mBackBufferFormat); DXGI_SWAP_CHAIN_DESC swapChainDesc = {0}; swapChainDesc.BufferCount = 2; swapChainDesc.BufferDesc.Format = format; swapChainDesc.BufferDesc.Width = backbufferWidth; swapChainDesc.BufferDesc.Height = backbufferHeight; swapChainDesc.BufferDesc.Scaling = DXGI_MODE_SCALING_UNSPECIFIED; swapChainDesc.BufferDesc.ScanlineOrdering = DXGI_MODE_SCANLINE_ORDER_UNSPECIFIED; swapChainDesc.BufferDesc.RefreshRate.Numerator = 0; swapChainDesc.BufferDesc.RefreshRate.Denominator = 1; swapChainDesc.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT; swapChainDesc.Flags = 0; swapChainDesc.OutputWindow = mWindow; swapChainDesc.SampleDesc.Count = 1; swapChainDesc.SampleDesc.Quality = 0; swapChainDesc.Windowed = TRUE; IDXGISwapChain *swapChain; HRESULT result = factory->CreateSwapChain(device, &swapChainDesc, &swapChain); if (SUCCEEDED(result)) { *outSwapChain = swapChain; d3d11::ResourceTracker::Track(swapChain); return EGL_SUCCESS; } else { if (d3d11::isDeviceLostError(result)) return EGL_CONTEXT_LOST; else return EGL_BAD_ALLOC; } }
GPA_Status DX12GetAdapterDesc(IUnknown* pDevice, DXGI_ADAPTER_DESC& adapterDesc) { GPA_Status status = GPA_STATUS_OK; if (nullptr == pDevice) { GPA_LogError("Parameter 'pDevice' is NULL."); status = GPA_STATUS_ERROR_NULL_POINTER; } else { ID3D12Device* dx12Device = static_cast<ID3D12Device*>(pDevice); LUID adapterLuid = dx12Device->GetAdapterLuid(); IDXGIFactory* pDXGIFactory = nullptr; HRESULT hr = CreateDXGIFactory(__uuidof(IDXGIFactory), reinterpret_cast<void**>(&pDXGIFactory)); if (FAILED(hr) || (nullptr == pDXGIFactory)) { GPA_LogError("Unable to get IDXGIFactory interface from ID3D12Device."); status = GPA_STATUS_ERROR_FAILED; } else { IDXGIAdapter* pAdapter = nullptr; for (UINT index = 0; pDXGIFactory->EnumAdapters(index, &pAdapter) != DXGI_ERROR_NOT_FOUND; ++index) { memset(&adapterDesc, 0, sizeof(adapterDesc)); hr = pAdapter->GetDesc(&adapterDesc); if (FAILED(hr)) { GPA_LogError("Could not get adapter description, hardware cannot be supported."); status = GPA_STATUS_ERROR_FAILED; } else { if (adapterDesc.AdapterLuid.HighPart == adapterLuid.HighPart && adapterDesc.AdapterLuid.LowPart == adapterLuid.LowPart) { // We found the matching adapter luid, so we're done. break; } } } } pDXGIFactory->Release(); } return status; }
//************************************************************************************************* // 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; }
void SysMtgsThread::OpenPlugin() { if( m_PluginOpened ) return; memcpy( RingBuffer.Regs, PS2MEM_GS, sizeof(PS2MEM_GS) ); GSsetBaseMem( RingBuffer.Regs ); GSirqCallback( dummyIrqCallback ); int result; if( GSopen2 != NULL ) result = GSopen2( (void*)pDsp, 1 | (renderswitch ? 4 : 0) ); else result = GSopen( (void*)pDsp, "PCSX2", renderswitch ? 2 : 1 ); GSsetVsync(EmuConfig.GS.FrameLimitEnable && EmuConfig.GS.VsyncEnable); if( result != 0 ) { DevCon.WriteLn( "GSopen Failed: return code: 0x%x", result ); throw Exception::PluginOpenError( PluginId_GS ); } // This is the preferred place to implement DXGI fullscreen overrides, using LoadLibrary. // But I hate COM, I don't know to make this work, and I don't have DX10, so I give up // and enjoy my working DX9 alt-enter instead. Someone else can fix this mess. --air // Also: Prolly needs some DX10 header includes? Which ones? Too many, I gave up. #if 0 // defined(__WXMSW__) && defined(_MSC_VER) wxDynamicLibrary dynlib( L"dxgi.dll" ); SomeFuncTypeIDunno isThisEvenTheRightFunctionNameIDunno = dynlib.GetSymbol("CreateDXGIFactory"); if( isThisEvenTheRightFunctionNameIDunno ) { // Is this how LoadLibrary for COM works? I dunno. I dont care. IDXGIFactory* pFactory; hr = isThisEvenTheRightFunctionNameIDunno(__uuidof(IDXGIFactory), (void**)(&pFactory) ); pFactory->MakeWindowAssociation((HWND)&pDsp, DXGI_MWA_NO_WINDOW_CHANGES); pFactory->Release(); } #endif m_PluginOpened = true; m_sem_OpenDone.Post(); GSsetGameCRC( ElfCRC, 0 ); }
std::shared_ptr<SwapChain> Device::createSwapChain(const Window& window) { std::shared_ptr<SwapChain> swapChain; IDXGIDevice* dxgiDevice = nullptr; if (SUCCEEDED(m_device->QueryInterface<IDXGIDevice>(&dxgiDevice))) { IDXGIAdapter* adapter = nullptr; if (SUCCEEDED(dxgiDevice->GetAdapter(&adapter))) { IDXGIFactory* dxgiFactory = nullptr; if (SUCCEEDED(adapter->GetParent(__uuidof(IDXGIFactory), reinterpret_cast<void**>(&dxgiFactory)))) { DXGI_SWAP_CHAIN_DESC sd; ZeroMemory(&sd, sizeof(sd)); sd.BufferCount = 1; sd.BufferDesc.Width = window.getWidth(); sd.BufferDesc.Height = window.getHeight(); sd.BufferDesc.Format = DXGI_FORMAT_B8G8R8A8_UNORM; sd.BufferDesc.RefreshRate.Numerator = 0; sd.BufferDesc.RefreshRate.Denominator = 1; sd.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT; sd.OutputWindow = window.getPlatformData()->getHandle(); sd.SampleDesc.Count = 1; sd.SampleDesc.Quality = 0; sd.Windowed = TRUE; IDXGISwapChain* nativeSwapChain = nullptr; if (SUCCEEDED(dxgiFactory->CreateSwapChain(m_device, &sd, &nativeSwapChain))) { ID3D11Texture2D* backBufferTexture = nullptr; if (SUCCEEDED(nativeSwapChain->GetBuffer(0, __uuidof(ID3D11Texture2D), reinterpret_cast<void**>(&backBufferTexture)))) { auto texture = std::make_shared<Texture2d>(backBufferTexture); auto backBufferRenderCommandEncoder = createRenderCommandEncoder(1, &texture, nullptr, false); swapChain = std::make_shared<SwapChain>(nativeSwapChain, backBufferRenderCommandEncoder); } dxgiFactory->Release(); } adapter->Release(); } } dxgiDevice->Release(); } return swapChain; }
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(); }
Error::E RenderSystem::CreateSwapChain(const Window &window) { assert(_device); _swapDesc = kDefaultSwapDesc; _swapDesc.SampleDesc.Count = 4; _swapDesc.SampleDesc.Quality = _msaaQualityLevel - 1; _swapDesc.OutputWindow = window.GetHandle(); _swapDesc.BufferDesc.Width = window.GetWidth(); _swapDesc.BufferDesc.Height = window.GetHeight(); IDXGIFactory *factory = FactoryFromDevice(_device); DEBUG_HR(factory->CreateSwapChain(_device, &_swapDesc, &_swapChain)); ReleaseCom(factory); return Error::OK; }
void D3DApplication::InitDirect3D() { // Create the device. UINT createDeviceFlags = 0; #if defined(DEBUG) || defined(_DEBUG) createDeviceFlags |= D3D10_CREATE_DEVICE_DEBUG; #endif HR(D3D10CreateDevice(0, m_DriverType, 0, createDeviceFlags, D3D10_SDK_VERSION, &m_pDevice)); IDXGIFactory* pFactory; HR(CreateDXGIFactory(__uuidof(IDXGIFactory), (void**)(&pFactory))); // Fill out a DXGI_SWAP_CHAIN_DESC to describe our swap chain. DXGI_SWAP_CHAIN_DESC swapChainDescription; swapChainDescription.BufferDesc.Width = m_ClientWidth; swapChainDescription.BufferDesc.Height = m_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; // No multisampling. swapChainDescription.SampleDesc.Count = 1; swapChainDescription.SampleDesc.Quality = 0; swapChainDescription.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT; swapChainDescription.BufferCount = 1; swapChainDescription.OutputWindow = m_hMainWindow; swapChainDescription.Windowed = true; swapChainDescription.SwapEffect = DXGI_SWAP_EFFECT_DISCARD; swapChainDescription.Flags = 0; HR(pFactory->CreateSwapChain(m_pDevice, &swapChainDescription, &m_pSwapChain)); HR(pFactory->MakeWindowAssociation(m_hMainWindow, DXGI_MWA_NO_WINDOW_CHANGES)); // 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(); }
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; }
void Setup::analizeSystem() { IDXGIFactory* factory = NULL; CreateDXGIFactory(__uuidof(IDXGIFactory), (void**)(&factory)); UINT i = 0; IDXGIAdapter* adapter; while(factory->EnumAdapters(i, &adapter) != DXGI_ERROR_NOT_FOUND) { AdapterSetting adapterSettings; adapterSettings.adapter = adapter; bool foundAnOutput = false; UINT j = 0; IDXGIOutput* output; while(adapter->EnumOutputs(j, &output) != DXGI_ERROR_NOT_FOUND) { OutputSetting outputSettings; ZeroMemory(&outputSettings, sizeof(OutputSetting)); outputSettings.output = output; getClosestDisplayModeToCurrent(output, &outputSettings.bufferDesc); /* Find the desktop coordinates of the window: */ DXGI_OUTPUT_DESC outputDesc; outputSettings.output->GetDesc(&outputDesc); outputSettings.windowPositionLeft = outputDesc.DesktopCoordinates.left; outputSettings.windowPositionTop = outputDesc.DesktopCoordinates.top; adapterSettings.outputSettings.push_back(outputSettings); foundAnOutput = true; ++j; } if(foundAnOutput) { mSettings.adapterSettings.push_back(adapterSettings); } ++i; } factory->Release(); }
size_t DXGI::GetAdapterPool (DXGI::GPUMemoryPool pool) { if (! NVAPI::CountPhysicalGPUs ()) { IDXGIFactory* pFactory = NULL; CreateDXGIFactory (__uuidof(IDXGIFactory), (void **)&pFactory); IDXGIAdapter * pDXGIAdapter; for (UINT i = 0; pFactory->EnumAdapters (i, &pDXGIAdapter) != DXGI_ERROR_NOT_FOUND; ++i) { DXGI_ADAPTER_DESC adapterDesc; pDXGIAdapter->GetDesc (&adapterDesc); // Skip Microsoft's virtual adapters... if (adapterDesc.VendorId != 0x1414) { pDXGIAdapter->Release (); pFactory->Release (); if (pool == GART) return adapterDesc.SharedSystemMemory; else return adapterDesc.DedicatedVideoMemory; } pDXGIAdapter->Release (); } pFactory->Release (); } else { DXGI_ADAPTER_DESC* adapter_descs = NVAPI::EnumGPUs_DXGI (); int i = 0; while (*adapter_descs [i].Description != L'\0') { if (pool == GART) return adapter_descs [i].SharedSystemMemory; else return adapter_descs [i].DedicatedVideoMemory; } } return 0; }
IDXGIAdapter* CDXGIManager::EnumAdapters( HWND hWND) { IDXGIFactory* pFactory; HRESULT hr = CreateDXGIFactory( IID_IDXGIFactory, (void**)&pFactory ); if( FAILED(hr) ) { MessageBox( hWND, L"Cambia de computadora", L"Error Fatal", MB_ICONERROR ); return NULL; } int iAdapter = 0; IDXGIAdapter* pAdapter = 0; while(1) { DXGI_ADAPTER_DESC dad; if( FAILED( pFactory->EnumAdapters( iAdapter, &pAdapter) ) ) break; TCHAR szMessage[ 1024 ]; pAdapter->GetDesc( &dad ); wsprintf( szMessage, L"Description: %s\r\nDedicated Memory: %d MB\r\nShared Memory: %d MB\r\nSystem Memory: %d", dad.Description, dad.DedicatedVideoMemory /(1024*1024), dad.SharedSystemMemory /(1024*1024), dad.DedicatedSystemMemory /(1024*1024) ); switch( MessageBox( hWND, szMessage, L"Do you wish to use this device?", MB_YESNOCANCEL | MB_ICONQUESTION ) ) { case IDYES: SAFE_RELEASE( pFactory ); return pAdapter; case IDNO: break; case IDCANCEL: SAFE_RELEASE( pFactory ); SAFE_RELEASE( pAdapter ); return NULL; } iAdapter++; } }
boolean RendererD3D11::assembleUnit() { ProcessingUnitPtr windowUnit = ProcessingUnitPtr::null; window->getData( windowUnit ); if( !windowUnit.isNull() ) { WindowPtr wnd = staticCast<Window>( windowUnit ); RenderDeviceD3D11* rd = static_cast<RenderDeviceD3D11*>( owner ); IDXGIFactory* dxgiFactory = rd->getDXGIFactory(); DXGI_SWAP_CHAIN_DESC desc; desc.BufferCount = 1; desc.BufferDesc.Width = wnd->getWidth(); desc.BufferDesc.Height = wnd->getHeight(); desc.BufferDesc.Format = MapperD3D11::mapPixelFormat( Render::PF_RGBA8UN ); desc.BufferDesc.RefreshRate.Numerator = 60; desc.BufferDesc.RefreshRate.Denominator = 1; desc.BufferDesc.Scaling = DXGI_MODE_SCALING_UNSPECIFIED; desc.BufferDesc.ScanlineOrdering = DXGI_MODE_SCANLINE_ORDER_UNSPECIFIED; desc.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT; desc.OutputWindow = (HWND)wnd->getHandle(); desc.SampleDesc.Count = 1; desc.SampleDesc.Quality = 0; desc.Windowed = !wnd->isFullscreen(); desc.SwapEffect = DXGI_SWAP_EFFECT_DISCARD; desc.Flags = DXGI_SWAP_CHAIN_FLAG_ALLOW_MODE_SWITCH; IDXGISwapChain* sc = 0; HRESULT hr = dxgiFactory->CreateSwapChain( rd->getD3DDevice(), &desc, &sc ); if( SUCCEEDED( hr ) ) { swapchains.add( sc ); wnd->setSwapChain( sc ); return true; } } return false; }
/** Enumerate through each adapter and its outputs adding references to the adapters and outputs @see EnumerateOutputs **/ void EnumAdapters::EnumerateAdapters() { UINT i = 0; IDXGIFactory* factory; IDXGIAdapter* padapter; HR(CreateDXGIFactory(__uuidof(IDXGIFactory), (void**)&factory)); while(factory->EnumAdapters(i, &padapter) != DXGI_ERROR_NOT_FOUND) { Adapter adapter(padapter); m_adapters.push_back(adapter); i++; } std::vector<Adapter>::iterator it; for(it = m_adapters.begin(); it != m_adapters.end(); it++) { it->EnumerateOutputs(); } factory->Release(); factory = 0; }
HRESULT STDMETHODCALLTYPE CDXGIFactoryDWM::CreateSwapChain(IUnknown *pDevice, DXGI_SWAP_CHAIN_DESC *pDesc, IDXGIOutput *pOutput, IDXGISwapChainDWM **ppSwapChain) { IDXGISwapChain *pSwapChain = NULL; if (retrace::forceWindowed) { pDesc->Windowed = TRUE; } HRESULT hr = m_pFactory->CreateSwapChain(pDevice, pDesc, &pSwapChain); if (SUCCEEDED(hr)) { if (!retrace::forceWindowed) { pSwapChain->SetFullscreenState(TRUE, pOutput); } *ppSwapChain = new CDXGISwapChainDWM(pSwapChain); } return hr; }
RenderDevice* Gfx_CreateDevice(Window* window, const RenderDeviceConfig& cfg) { (void)cfg; // TODO RenderDevice* dev = new RenderDevice; dev->window = window; dev->vsync = cfg.use_vertical_sync ? 1 : 0; dev->default_context = new RenderContext; dev->default_context->resources = &dev->resources; // create d3d11 device and essential resources HWND hwnd = *(HWND*)window->native_window_handle(); DXGI_SWAP_CHAIN_DESC sd; ZeroMemory( &sd, sizeof( sd ) ); sd.BufferCount = 1; sd.BufferDesc.Width = window->width(); sd.BufferDesc.Height = window->height(); 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 = hwnd; sd.SampleDesc.Count = 1; sd.SampleDesc.Quality = 0; sd.Windowed = TRUE; uint32 flags = D3D11_CREATE_DEVICE_SINGLETHREADED; #ifdef _DEBUG flags |= D3D11_CREATE_DEVICE_DEBUG; #endif //_DEBUG D3D_DRIVER_TYPE type = D3D_DRIVER_TYPE_HARDWARE; IDXGIAdapter* adapter = NULL; if( cfg.use_nvperfhud ) { IDXGIAdapter* enumerated_adapter = NULL; IDXGIFactory* factory = NULL; D3D_CALL( CreateDXGIFactory(__uuidof(IDXGIFactory),(void**)&factory) ); for( uint32 i=0; factory->EnumAdapters(i,&enumerated_adapter) != DXGI_ERROR_NOT_FOUND; ++i ) { DXGI_ADAPTER_DESC adapter_desc; if(enumerated_adapter->GetDesc(&adapter_desc) != S_OK) { continue; } if(wcsstr(adapter_desc.Description,L"PerfHUD") != 0) { type = D3D_DRIVER_TYPE_REFERENCE; adapter = enumerated_adapter; break; } } SafeRelease(factory); } D3D_FEATURE_LEVEL features[] = { 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 }; const uint32 num_features = sizeof(features) / sizeof(features[0]); D3D_FEATURE_LEVEL supported_features = D3D_FEATURE_LEVEL_9_1; // Create device D3D_CALL( D3D11CreateDeviceAndSwapChain( adapter, type, NULL, flags, features, num_features, D3D11_SDK_VERSION, &sd, &dev->swap_chain, &dev->native, &supported_features, &dev->default_context->native) ); // Set-up default Colour and Depth surfaces dx11_acquire_back_buffer(dev); dx11_setup_back_buffer(dev); // create default pixel and vertex constant buffers D3D11_BUFFER_DESC desc; desc.ByteWidth = MaxShaderConstants*sizeof(Vector4); desc.Usage = D3D11_USAGE_DYNAMIC; desc.BindFlags = D3D11_BIND_CONSTANT_BUFFER; desc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE; desc.MiscFlags = 0; desc.StructureByteStride = 0; D3D_CALL(dev->native->CreateBuffer(&desc, NULL, &dev->default_context->ps_cb)); D3D_CALL(dev->native->CreateBuffer(&desc, NULL, &dev->default_context->vs_cb)); // Hack -- enable scissor rect state by default D3D11_RASTERIZER_DESC rasterizer_desc = CD3D11_RASTERIZER_DESC(CD3D11_DEFAULT()); rasterizer_desc.ScissorEnable = TRUE; dev->native->CreateRasterizerState(&rasterizer_desc, &dev->rasterizer_state); dev->default_context->native->RSSetState(dev->rasterizer_state); // all done dev->resize_listener = new WindowResizeListener(window); return dev; }
bool D3D::Init(int screenWidth, int screenHeight, bool vsync, HWND hWnd, bool fullscreen, float screenDepth, float screenNear) { HRESULT result; IDXGIFactory* factory; IDXGIAdapter* adapter; IDXGIOutput* adapterOutput; unsigned int numModes, i, numerator, denominator, stringLength; DXGI_MODE_DESC* displayModeList; DXGI_ADAPTER_DESC adapterDesc; int error; DXGI_SWAP_CHAIN_DESC swapChainDesc; D3D_FEATURE_LEVEL featureLevel; ID3D11Texture2D* backBufferPtr; D3D11_TEXTURE2D_DESC depthBufferDesc; D3D11_DEPTH_STENCIL_DESC depthStencilDesc; D3D11_DEPTH_STENCIL_VIEW_DESC depthStencilViewDesc; D3D11_RASTERIZER_DESC rasterDesc; D3D11_VIEWPORT viewport; float fieldOfView, screenAspect; D3D11_DEPTH_STENCIL_DESC depthDisabledStencilDesc; D3D11_BLEND_DESC blendStateDesc; // Store the vsync setting. _vsyncEnabled = vsync; //Create a DirectX graphics interface factory result = CreateDXGIFactory(__uuidof(IDXGIFactory), (void**)&factory); if (FAILED(result)) return false; //Use the factory to create an adpater for the primary graphics interface (video card) result = factory->EnumAdapters(0, &adapter); if (FAILED(result)) return false; //Enumerate the primary adapter output (monitor) result = adapter->EnumOutputs(0, &adapterOutput); if (FAILED(result)) return false; //Get the number of modes that fix the DXGI_FORMAT_R8G8B8A8_UNORM display format for the adapter output (monitor) result = adapterOutput->GetDisplayModeList(DXGI_FORMAT_R8G8B8A8_UNORM, DXGI_ENUM_MODES_INTERLACED, &numModes, NULL); if (FAILED(result)) return false; //Create a list to hold all the possible display modes for this monitor/video card combination displayModeList = new DXGI_MODE_DESC[numModes]; if (!displayModeList) return false; //Now fill the display mode list structures result = adapterOutput->GetDisplayModeList(DXGI_FORMAT_R8G8B8A8_UNORM, DXGI_ENUM_MODES_INTERLACED, &numModes, displayModeList); if (FAILED(result)) return false; //Now go through all the displa modes and find the one that matches the screen width and height //When a match is found store the numerator and denominator of the refresh rate for that monitor 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; } } } //Get the adapter (video card) description result = adapter->GetDesc(&adapterDesc); if (FAILED(result)) return false; //Store the dedicated video card memory in mb _videoCardMemory = (int)(adapterDesc.DedicatedVideoMemory / 1024 / 1024); //Convert eh name of the video card to a char array and store error = wcstombs_s(&stringLength, _videoCardDescription, 128, adapterDesc.Description, 128); if (error != 0) return false; //Release the display mode list delete[] displayModeList; displayModeList = NULL; //Release the adapter output adapterOutput->Release(); adapterOutput = NULL; //release the adapater adapter->Release(); adapter = NULL; //Release the factory factory->Release(); factory = NULL; //Init the swap chain description ZeroMemory(&swapChainDesc, sizeof(swapChainDesc)); //Set to a single back buffer swapChainDesc.BufferCount = 1; //Set the width and height of the back buffer swapChainDesc.BufferDesc.Width = screenWidth; swapChainDesc.BufferDesc.Height = screenHeight; //Set regular 32 bit surface for the back buffer swapChainDesc.BufferDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM; //Set the refresh rate of the back buffer if(_vsyncEnabled) { swapChainDesc.BufferDesc.RefreshRate.Numerator = numerator; swapChainDesc.BufferDesc.RefreshRate.Denominator = denominator; } else { swapChainDesc.BufferDesc.RefreshRate.Numerator = 0; swapChainDesc.BufferDesc.RefreshRate.Denominator = 1; } //Set the usage of the back buffer swapChainDesc.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT; //Set the handle for the window to render to swapChainDesc.OutputWindow = hWnd; //Turn multisampling off swapChainDesc.SampleDesc.Count = 1; swapChainDesc.SampleDesc.Quality = 0; //Set to fullscreen/windows if (fullscreen) { swapChainDesc.Windowed = false; } else { swapChainDesc.Windowed = true; } //Set the scan line ordering and scaling to unspecified swapChainDesc.BufferDesc.ScanlineOrdering = DXGI_MODE_SCANLINE_ORDER_UNSPECIFIED; swapChainDesc.BufferDesc.Scaling = DXGI_MODE_SCALING_UNSPECIFIED; //Discard the back buffer contents after preseting swapChainDesc.SwapEffect = DXGI_SWAP_EFFECT_DISCARD; // Don't set the advanced flags. swapChainDesc.Flags = 0; // Set the feature level to DirectX 11. featureLevel = D3D_FEATURE_LEVEL_11_0; //Create the swap chain, Direct3D device, and device context result = D3D11CreateDeviceAndSwapChain(NULL, D3D_DRIVER_TYPE_HARDWARE, NULL, 0, &featureLevel, 1, D3D11_SDK_VERSION, &swapChainDesc, &_swapChain, &_device, NULL, &_deviceContext); if (FAILED(result)) return false; //Get the pointer to the back buffer result = _swapChain->GetBuffer(0, __uuidof(ID3D11Texture2D), (LPVOID*)&backBufferPtr); if (FAILED(result)) return false; //Create the render target view with the back buffer pointer result = _device->CreateRenderTargetView(backBufferPtr, NULL, &_renderTargetView); if (FAILED(result)) return false; //Release pointer to the back buffer as we no longer need it backBufferPtr->Release(); backBufferPtr = NULL; // Initialize the description of the depth buffer. ZeroMemory(&depthBufferDesc, sizeof(depthBufferDesc)); // Set up the description of the depth buffer. depthBufferDesc.Width = screenWidth; depthBufferDesc.Height = screenHeight; depthBufferDesc.MipLevels = 1; depthBufferDesc.ArraySize = 1; depthBufferDesc.Format = DXGI_FORMAT_D24_UNORM_S8_UINT; depthBufferDesc.SampleDesc.Count = 1; depthBufferDesc.SampleDesc.Quality = 0; depthBufferDesc.Usage = D3D11_USAGE_DEFAULT; depthBufferDesc.BindFlags = D3D11_BIND_DEPTH_STENCIL; depthBufferDesc.CPUAccessFlags = 0; depthBufferDesc.MiscFlags = 0; // Create the texture for the depth buffer using the filled out description. result = _device->CreateTexture2D(&depthBufferDesc, NULL, &_depthStencilBuffer); if(FAILED(result)) return false; // 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; // Create the depth stencil state. result = _device->CreateDepthStencilState(&depthStencilDesc, &_depthStencilState); if(FAILED(result)) return false; //Set the depth stencil state _deviceContext->OMSetDepthStencilState(_depthStencilState, 1); //Init the depth stencil view ZeroMemory(&depthStencilViewDesc, sizeof(depthStencilViewDesc)); //Set up the depth stencil view desc depthStencilViewDesc.Format = DXGI_FORMAT_D24_UNORM_S8_UINT; depthStencilViewDesc.ViewDimension = D3D11_DSV_DIMENSION_TEXTURE2D; depthStencilViewDesc.Texture2D.MipSlice = 0; // Create the depth stencil view. result = _device->CreateDepthStencilView(_depthStencilBuffer, &depthStencilViewDesc, &_depthStencilView); if(FAILED(result)) return false; // Bind the render target view and depth stencil buffer to the output render pipeline. _deviceContext->OMSetRenderTargets(1, &_renderTargetView, _depthStencilView); // Setup the raster description which will determine how and what polygons will be drawn. rasterDesc.AntialiasedLineEnable = false; rasterDesc.CullMode = D3D11_CULL_BACK; rasterDesc.DepthBias = 0; rasterDesc.DepthBiasClamp = 0.0f; rasterDesc.DepthClipEnable = true; rasterDesc.FillMode = D3D11_FILL_SOLID; rasterDesc.FrontCounterClockwise = false; rasterDesc.MultisampleEnable = false; rasterDesc.ScissorEnable = false; rasterDesc.SlopeScaledDepthBias = 0.0f; // Create the rasterizer state from the description we just filled out. result = _device->CreateRasterizerState(&rasterDesc, &_rasterState); if(FAILED(result)) { return false; } // Now set the rasterizer state. _deviceContext->RSSetState(_rasterState); // Setup the viewport for rendering. viewport.Width = (float)screenWidth; viewport.Height = (float)screenHeight; viewport.MinDepth = 0.0f; viewport.MaxDepth = 1.0f; viewport.TopLeftX = 0.0f; viewport.TopLeftY = 0.0f; // Create the viewport. _deviceContext->RSSetViewports(1, &viewport); // Setup the projection matrix. fieldOfView = (float)D3DX_PI / 4.0f; screenAspect = (float)screenWidth / (float)screenHeight; // Create the projection matrix for 3D rendering. D3DXMatrixPerspectiveFovLH(&_projectionMatrix, fieldOfView, screenAspect, screenNear, screenDepth); // Initialize the world matrix to the identity matrix. D3DXMatrixIdentity(&_worldMatrix); // Create an orthographic projection matrix for 2D rendering. D3DXMatrixOrthoLH(&_orthoMatrix, (float)screenWidth, (float)screenHeight, screenNear, screenDepth); //Clear the second depth stencil state before setting params ZeroMemory(&depthDisabledStencilDesc, sizeof(depthDisabledStencilDesc)); // Now create a second depth stencil state which turns off the Z buffer for 2D rendering. The only difference is // that DepthEnable is set to false, all other parameters are the same as the other depth stencil state. depthDisabledStencilDesc.DepthEnable = false; depthDisabledStencilDesc.DepthWriteMask = D3D11_DEPTH_WRITE_MASK_ALL; depthDisabledStencilDesc.DepthFunc = D3D11_COMPARISON_LESS; depthDisabledStencilDesc.StencilEnable = true; depthDisabledStencilDesc.StencilReadMask = 0xFF; depthDisabledStencilDesc.StencilWriteMask = 0xFF; depthDisabledStencilDesc.FrontFace.StencilFailOp = D3D11_STENCIL_OP_KEEP; depthDisabledStencilDesc.FrontFace.StencilDepthFailOp = D3D11_STENCIL_OP_INCR; depthDisabledStencilDesc.FrontFace.StencilPassOp = D3D11_STENCIL_OP_KEEP; depthDisabledStencilDesc.FrontFace.StencilFunc = D3D11_COMPARISON_ALWAYS; depthDisabledStencilDesc.BackFace.StencilFailOp = D3D11_STENCIL_OP_KEEP; depthDisabledStencilDesc.BackFace.StencilDepthFailOp = D3D11_STENCIL_OP_DECR; depthDisabledStencilDesc.BackFace.StencilPassOp = D3D11_STENCIL_OP_KEEP; depthDisabledStencilDesc.BackFace.StencilFunc = D3D11_COMPARISON_ALWAYS; //Create the state using the device result = _device->CreateDepthStencilState(&depthDisabledStencilDesc, &_depthDisabledStencilState); if (FAILED(result)) return false; //Clear the blend state desc ZeroMemory(&blendStateDesc, sizeof(D3D11_BLEND_DESC)); // Create an alpha enabled blend state description. blendStateDesc.RenderTarget[0].BlendEnable = TRUE; blendStateDesc.RenderTarget[0].SrcBlend = D3D11_BLEND_ONE; 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 = 0x0f; //Create the blend state using the desciption result = _device->CreateBlendState(&blendStateDesc, &_aEnableBlendingState); if (FAILED(result)) return false; //Modify the desciption to create an alpha disabled blend state desc blendStateDesc.RenderTarget[0].BlendEnable = FALSE; //Create the blend state using the desc result = _device->CreateBlendState(&blendStateDesc, &_aDisableBlendingState); if (FAILED(result)) return false; return true; }