void DXRenderer::InitializeDX(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 = 60, denominator = 1, stringLength; DXGI_MODE_DESC* displayModeList; DXGI_ADAPTER_DESC adapterDesc; int error; DXGI_SWAP_CHAIN_DESC swapChainDesc; 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; m_fScreenDepth = _screenDepth; m_fScreenNear = _screenNear; // Store the vsync setting. m_bVSyncEnabled = _vsync; // Create a DirectX graphics interface factory. result = CreateDXGIFactory(__uuidof(IDXGIFactory), (void**)&factory); if (FAILED(result)) { //return false; std::cout << "Error creating DXGIFactory" << std::endl; } // Use the factory to create an adapter 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 fit 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 display 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 megabytes. m_iVideoCardMemory = (int)(adapterDesc.DedicatedVideoMemory / 1024 / 1024); // Convert the name of the video card to a character array and store it. error = wcstombs_s(&stringLength, m_sVideoCardDescription, 128, adapterDesc.Description, 128); if (error != 0) { //return false; } std::cout << "Video Card: " << m_sVideoCardDescription << std::endl; //Ora si possono liberare tutti gli oggetti e strutture create per ottenere le informazioni sulla scheda video e refresh rate // Release the display mode list. delete[] displayModeList; displayModeList = 0; // Release the adapter output. adapterOutput->Release(); adapterOutput = 0; // Release the adapter. adapter->Release(); adapter = 0; // Release the factory. factory->Release(); factory = 0; //Ora inizializziamo DirectX! //Initialize 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 (m_bVSyncEnabled) { swapChainDesc.BufferDesc.RefreshRate.Numerator = numerator; swapChainDesc.BufferDesc.RefreshRate.Denominator = denominator; } else { swapChainDesc.BufferDesc.RefreshRate.Numerator = 60; 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 full screen or windowed mode. if (_fullScreen) { swapChainDesc.Windowed = false; } else { swapChainDesc.Windowed = true; } //Proviamo senza questa roba avanzata // 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 presenting. swapChainDesc.SwapEffect = DXGI_SWAP_EFFECT_DISCARD; // Don't set the advanced flags. swapChainDesc.Flags = 0; D3D_FEATURE_LEVEL featureLevel[] = { // TODO: Modify for supported Direct3D feature levels (see code below related to 11.1 fallback handling) D3D_FEATURE_LEVEL_11_1, D3D_FEATURE_LEVEL_11_0, D3D_FEATURE_LEVEL_10_1, D3D_FEATURE_LEVEL_10_0, D3D_FEATURE_LEVEL_9_3, D3D_FEATURE_LEVEL_9_2, D3D_FEATURE_LEVEL_9_1, }; D3D_DRIVER_TYPE driverTypes[] = { D3D_DRIVER_TYPE_HARDWARE, D3D_DRIVER_TYPE_REFERENCE, D3D_DRIVER_TYPE_SOFTWARE, }; UINT numDriverTypes = sizeof(driverTypes) / sizeof(driverTypes[0]); D3D_DRIVER_TYPE g_driverType; for (UINT driverTypeIndex = 0; driverTypeIndex < numDriverTypes; ++driverTypeIndex) { // Prova ad inizializzare per i tipi di driver definiti g_driverType = driverTypes[driverTypeIndex]; //result = D3D11CreateDevice(nullptr, g_driverType, nullptr, 0, nullptr, 0, D3D11_SDK_VERSION, &m_device, nullptr, &m_deviceContext); result = D3D11CreateDeviceAndSwapChain(nullptr, g_driverType, nullptr, 0, nullptr, 0, D3D11_SDK_VERSION, &swapChainDesc, &m_dSwapChain, &m_dDevice, nullptr, &m_dDeviceContext); // Appena funziona esci if (SUCCEEDED(result)) break; } if (FAILED(result)) { //return false; std::cout << "Error creating SwapChain" << std::endl; } else std::cout << "DirectX SwapChain created successfully." << std::endl; //D3D_FEATURE_LEVEL featureLevel = D3D_FEATURE_LEVEL_11_0; //Creiamo la swapchain, il device e il device context!! /* result = D3D11CreateDeviceAndSwapChain( NULL, D3D_DRIVER_TYPE_HARDWARE, NULL, 0, featureLevel, 1, D3D11_SDK_VERSION, &swapChainDesc, &m_swapChain, &m_device, NULL, &m_deviceContext); if (FAILED(result)) { return false; } */ // Get the pointer to the back buffer. result = m_dSwapChain->GetBuffer(0, __uuidof(ID3D11Texture2D), (LPVOID*)&backBufferPtr); if (FAILED(result)) { //return false; std::cout << "Error creating backbuffer" << std::endl; } // Create the render target view with the back buffer pointer. result = m_dDevice->CreateRenderTargetView(backBufferPtr, NULL, &m_dRenderTargetView); if (FAILED(result)) { //return false; std::cout << "Error creating Render Target View" << std::endl; } // Release pointer to the back buffer as we no longer need it. backBufferPtr->Release(); backBufferPtr = nullptr; // 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 = m_dDevice->CreateTexture2D(&depthBufferDesc, NULL, &m_dDepthStencilBuffer); 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 = m_dDevice->CreateDepthStencilState(&depthStencilDesc, &m_dDepthStencilState); if (FAILED(result)) { //return false; std::cout << "Error creating Depth Stencil State" << std::endl; } // Set the depth stencil state. m_dDeviceContext->OMSetDepthStencilState(m_dDepthStencilState, 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; // Create the depth stencil view. result = m_dDevice->CreateDepthStencilView(m_dDepthStencilBuffer, &depthStencilViewDesc, &m_dDepthStencilView); if (FAILED(result)) { //return false; std::cout << "Error creating Depth Stencil View" << std::endl; } // Bind the render target view and depth stencil buffer to the output render pipeline. m_dDeviceContext->OMSetRenderTargets(1, &m_dRenderTargetView, m_dDepthStencilView); // 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 = m_dDevice->CreateRasterizerState(&rasterDesc, &m_dRasterState); if (FAILED(result)) { //return false; } // Now set the rasterizer state. m_dDeviceContext->RSSetState(m_dRasterState); // 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. m_dDeviceContext->RSSetViewports(1, &viewport); // Setup the projection matrix. fieldOfView = (float)DirectX::XM_PI / 4.0f; screenAspect = (float)_screenWidth / (float)_screenHeight; //Create constant buffer for the vertex shader D3D11_BUFFER_DESC cbDesc; ZeroMemory(&cbDesc, sizeof(D3D11_BUFFER_DESC)); cbDesc.Usage = D3D11_USAGE_DEFAULT; cbDesc.ByteWidth = sizeof(GFX::ConstantObject); cbDesc.BindFlags = D3D11_BIND_CONSTANT_BUFFER; cbDesc.CPUAccessFlags = 0; cbDesc.MiscFlags = 0; D3D11_SAMPLER_DESC sampDesc; ZeroMemory(&sampDesc, sizeof(sampDesc)); sampDesc.Filter = D3D11_FILTER_MIN_MAG_MIP_LINEAR; sampDesc.AddressU = D3D11_TEXTURE_ADDRESS_WRAP; sampDesc.AddressV = D3D11_TEXTURE_ADDRESS_WRAP; sampDesc.AddressW = D3D11_TEXTURE_ADDRESS_WRAP; sampDesc.ComparisonFunc = D3D11_COMPARISON_NEVER; sampDesc.MinLOD = 0; sampDesc.MaxLOD = D3D11_FLOAT32_MAX; m_dDevice->CreateSamplerState(&sampDesc, &m_dSamplerState); m_dDevice->CreateBuffer(&cbDesc, NULL, &m_bConstObj); m_dDeviceContext->VSSetConstantBuffers(0, 1, &m_bConstObj); std::cout << "DirectX initialized successfully." << std::endl; }
bool D3DClass::Initialize(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; m_vsync_enabled = vsync; result = CreateDXGIFactory(__uuidof(IDXGIFactory), (void**)&factory); if (FAILED(result)) { return false; } result = factory->EnumAdapters(0, &adapter); if (FAILED(result)) { return false; } result = adapter->EnumOutputs(0, &adapterOutput); if (FAILED(result)) { return false; } result = adapterOutput->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 = adapterOutput->GetDisplayModeList(DXGI_FORMAT_R8G8B8A8_UNORM, DXGI_ENUM_MODES_INTERLACED, &numModes, displayModeList); if (FAILED(result)) { return false; } /*std::vector<UINT> numwidth;*/ for (i = 0; i<numModes; i++) { /*numwidth.push_back(displayModeList[i].Width);*/ 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 = adapter->GetDesc(&adapterDesc); if (FAILED(result)) { return false; } m_videoCardMemory = (int)(adapterDesc.DedicatedVideoMemory/1024/1024); error = wcstombs_s(&stringLength, m_videoCardDescription, 128, adapterDesc.Description,128); if (error != 0) { return false; } delete [] displayModeList; displayModeList = 0; adapterOutput->Release(); adapterOutput = 0; adapter->Release(); adapter = 0; factory->Release(); factory = 0; //initialize swap chain description ZeroMemory(&swapChainDesc, sizeof(swapChainDesc)); swapChainDesc.BufferCount = 1; swapChainDesc.BufferDesc.Width = screenWidth; swapChainDesc.BufferDesc.Height = screenHeight; swapChainDesc.BufferDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM; if (m_vsync_enabled) { swapChainDesc.BufferDesc.RefreshRate.Numerator = numerator; swapChainDesc.BufferDesc.RefreshRate.Denominator = denominator; } else { swapChainDesc.BufferDesc.RefreshRate.Numerator = 0; swapChainDesc.BufferDesc.RefreshRate.Denominator = 1; } swapChainDesc.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT; swapChainDesc.OutputWindow = hwnd; //turn multisampling off swapChainDesc.SampleDesc.Count = 1; swapChainDesc.SampleDesc.Quality = 0; if (fullscreen) { swapChainDesc.Windowed = false; }else { swapChainDesc.Windowed = true; } swapChainDesc.BufferDesc.ScanlineOrdering = DXGI_MODE_SCANLINE_ORDER_UNSPECIFIED; swapChainDesc.BufferDesc.Scaling = DXGI_MODE_SCALING_UNSPECIFIED; swapChainDesc.SwapEffect = DXGI_SWAP_EFFECT_DISCARD; swapChainDesc.Flags = 0; featureLevel = D3D_FEATURE_LEVEL_11_0; result = D3D11CreateDeviceAndSwapChain(NULL, D3D_DRIVER_TYPE_HARDWARE, NULL, 0, &featureLevel, 1, D3D11_SDK_VERSION, &swapChainDesc, &m_swapChain, &m_device, NULL, &m_deviceContext); if (FAILED(result)) { return false; } result = m_swapChain->GetBuffer(0, __uuidof(ID3D11Texture2D), (LPVOID*)&backBufferPtr); if (FAILED(result)) { return false; } result = m_device->CreateRenderTargetView(backBufferPtr, NULL, &m_rendertargetview); if (FAILED(result)) { return false; } backBufferPtr->Release(); backBufferPtr = 0; 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; result = m_device->CreateTexture2D(&depthBufferDesc, NULL, &m_depthStencilBuffer); if (FAILED(result)) { return false; } ZeroMemory(&depthStencilDesc, sizeof(depthStencilDesc)); depthStencilDesc.DepthEnable = true; depthStencilDesc.DepthWriteMask = D3D11_DEPTH_WRITE_MASK_ALL; depthStencilDesc.DepthFunc = D3D11_COMPARISON_LESS; depthStencilDesc.StencilEnable = true; depthStencilDesc.StencilReadMask = 0xFF; depthStencilDesc.StencilWriteMask = 0xFF; 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; depthStencilDesc.BackFace.StencilDepthFailOp = D3D11_STENCIL_OP_DECR; depthStencilDesc.BackFace.StencilFailOp = D3D11_STENCIL_OP_KEEP; depthStencilDesc.BackFace.StencilPassOp = D3D11_STENCIL_OP_KEEP; depthStencilDesc.BackFace.StencilFunc = D3D11_COMPARISON_ALWAYS; result = m_device->CreateDepthStencilState(&depthStencilDesc, &m_depthStencilState); if (FAILED(result)) { return false; } m_deviceContext->OMSetDepthStencilState(m_depthStencilState, 1); ZeroMemory(&depthStencilViewDesc, sizeof(depthStencilViewDesc)); depthStencilViewDesc.Format = DXGI_FORMAT_D24_UNORM_S8_UINT; depthStencilViewDesc.ViewDimension = D3D11_DSV_DIMENSION_TEXTURE2D; depthStencilViewDesc.Texture2D.MipSlice = 0; result = m_device->CreateDepthStencilView(m_depthStencilBuffer, &depthStencilViewDesc, &m_depthStencilView); if (FAILED(result)) { return false; } m_deviceContext->OMSetRenderTargets(1, &m_rendertargetview, m_depthStencilView); 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; result = m_device->CreateRasterizerState(&rasterDesc, &m_rasterState); if (FAILED(result)) { return false; } m_deviceContext->RSSetState(m_rasterState); viewport.Width = (float)screenWidth; viewport.Height = (float)screenHeight; viewport.MinDepth = 0.0f; viewport.MaxDepth = 1.0f; viewport.TopLeftX = 0.0f; viewport.TopLeftY = 0.0f; m_deviceContext->RSSetViewports(1, &viewport); fieldOfView = (float)D3DX_PI/4.0f; screenAspect = (float)screenWidth/(float)screenHeight; D3DXMatrixPerspectiveFovLH(&m_projectionMatrix, fieldOfView, screenAspect, screenNear, screenDepth); D3DXMatrixIdentity(&m_worldMatrix); D3DXMatrixOrthoLH(&m_orthoMatrix, (float)screenWidth, (float)screenHeight, screenNear, screenDepth); return true; }
HRESULT CVideoDevice::createDevice() { HRESULT hR = CreateDXGIFactory(__uuidof(IDXGIFactory), (void**)m_pFactory.inref()); if(FAILED(hR)) return hR; IDXGIAdapterPtr pAdapter; hR = m_pFactory->EnumAdapters(0, pAdapter.inref()); if(FAILED(hR)) return hR; // DXGI_ADAPTER_DESC descr; // memset(&descr, 0, sizeof(descr)); // hR = pAdapter->GetDesc(&descr); #ifdef _DEBUG UINT DX_FLAGS = D3D10_CREATE_DEVICE_DEBUG; #else UINT DX_FLAGS = 0; #endif static const D3D10_FEATURE_LEVEL1 LEVELS[] = { D3D10_FEATURE_LEVEL_10_1, D3D10_FEATURE_LEVEL_10_0, D3D10_FEATURE_LEVEL_9_3, D3D10_FEATURE_LEVEL_9_2, D3D10_FEATURE_LEVEL_9_1 }; int featureIdx = 0; D3D10_FEATURE_LEVEL1 level = LEVELS[0]; for(;;) { HRESULT hR = D3D10CreateDevice1(pAdapter, D3D10_DRIVER_TYPE_HARDWARE, NULL, DX_FLAGS, level, D3D10_1_SDK_VERSION, m_pDevice.inref()); if(SUCCEEDED(hR)) break; #ifdef _DEBUG if((hR == E_FAIL || hR == DXGI_ERROR_UNSUPPORTED) && (DX_FLAGS & D3D10_CREATE_DEVICE_DEBUG)) { // no debug layer available? DX_FLAGS &= ~D3D10_CREATE_DEVICE_DEBUG; continue; } DX_FLAGS |= D3D10_CREATE_DEVICE_DEBUG; #endif if(featureIdx < _countof(LEVELS)) { level = LEVELS[++featureIdx]; continue; } // request failed return hR; } // HRESULT hR = m_pDevice->QueryInterface(__uuidof(IDXGIDevice1), (void **)m_pDxgiDevice.inref()); switch(level) { case D3D10_FEATURE_LEVEL_9_1: m_driverLevel = 9.1f; break; case D3D10_FEATURE_LEVEL_9_2: m_driverLevel = 9.2f; break; case D3D10_FEATURE_LEVEL_9_3: m_driverLevel = 9.3f; break; case D3D10_FEATURE_LEVEL_10_0: m_driverLevel = 10.0f; break; case D3D10_FEATURE_LEVEL_10_1: m_driverLevel = 10.1f; break; } return S_OK; }
SettingsDialog::SettingsDialog(wxWindow* parent) : wxDialog(parent, wxID_ANY, "Settings", wxDefaultPosition) { // Load default config loaded = YAML::Load(g_cfg_defaults); // Incrementally load config.yml const fs::file config(fs::get_config_dir() + "/config.yml", fs::read + fs::write + fs::create); loaded += YAML::Load(config.to_string()); std::vector<std::unique_ptr<cfg_adapter>> pads; static const u32 width = 458; static const u32 height = 400; // Settings panels wxNotebook* nb_config = new wxNotebook(this, wxID_ANY, wxPoint(6, 6), wxSize(width, height)); wxPanel* p_system = new wxPanel(nb_config, wxID_ANY); wxPanel* p_core = new wxPanel(nb_config, wxID_ANY); wxPanel* p_graphics = new wxPanel(nb_config, wxID_ANY); wxPanel* p_audio = new wxPanel(nb_config, wxID_ANY); wxPanel* p_io = new wxPanel(nb_config, wxID_ANY); wxPanel* p_misc = new wxPanel(nb_config, wxID_ANY); wxPanel* p_networking = new wxPanel(nb_config, wxID_ANY); nb_config->AddPage(p_core, "Core"); nb_config->AddPage(p_graphics, "Graphics"); nb_config->AddPage(p_audio, "Audio"); nb_config->AddPage(p_io, "Input / Output"); nb_config->AddPage(p_misc, "Misc"); nb_config->AddPage(p_networking, "Networking"); nb_config->AddPage(p_system, "System"); wxBoxSizer* s_subpanel_core = new wxBoxSizer(wxHORIZONTAL); wxBoxSizer* s_subpanel_core1 = new wxBoxSizer(wxVERTICAL); wxBoxSizer* s_subpanel_core2 = new wxBoxSizer(wxVERTICAL); wxBoxSizer* s_subpanel_graphics = new wxBoxSizer(wxHORIZONTAL); wxBoxSizer* s_subpanel_graphics1 = new wxBoxSizer(wxVERTICAL); wxBoxSizer* s_subpanel_graphics2 = new wxBoxSizer(wxVERTICAL); wxBoxSizer* s_subpanel_audio = new wxBoxSizer(wxVERTICAL); wxBoxSizer* s_subpanel_io = new wxBoxSizer(wxHORIZONTAL); wxBoxSizer* s_subpanel_io1 = new wxBoxSizer(wxVERTICAL); wxBoxSizer* s_subpanel_io2 = new wxBoxSizer(wxVERTICAL); wxBoxSizer* s_subpanel_system = new wxBoxSizer(wxVERTICAL); wxBoxSizer* s_subpanel_misc = new wxBoxSizer(wxVERTICAL); wxBoxSizer* s_subpanel_networking = new wxBoxSizer(wxVERTICAL); // Core wxStaticBoxSizer* s_round_core_lle = new wxStaticBoxSizer(wxVERTICAL, p_core, "Load libraries"); chbox_list_core_lle = new wxCheckListBox(p_core, wxID_ANY, wxDefaultPosition, wxDefaultSize, {}, wxLB_EXTENDED); chbox_list_core_lle->Bind(wxEVT_CHECKLISTBOX, &SettingsDialog::OnModuleListItemToggled, this); wxTextCtrl* s_module_search_box = new wxTextCtrl(p_core, wxID_ANY, wxEmptyString, wxDefaultPosition, wxDefaultSize, {}); s_module_search_box->Bind(wxEVT_TEXT, &SettingsDialog::OnSearchBoxTextChanged, this); // Graphics wxStaticBoxSizer* s_round_gs_render = new wxStaticBoxSizer(wxVERTICAL, p_graphics, "Render"); wxStaticBoxSizer* s_round_gs_d3d_adapter = new wxStaticBoxSizer(wxVERTICAL, p_graphics, "D3D Adapter"); wxStaticBoxSizer* s_round_gs_res = new wxStaticBoxSizer(wxVERTICAL, p_graphics, "Resolution"); wxStaticBoxSizer* s_round_gs_aspect = new wxStaticBoxSizer(wxVERTICAL, p_graphics, "Aspect ratio"); wxStaticBoxSizer* s_round_gs_frame_limit = new wxStaticBoxSizer(wxVERTICAL, p_graphics, "Frame limit"); // Input / Output wxStaticBoxSizer* s_round_io_pad_handler = new wxStaticBoxSizer(wxVERTICAL, p_io, "Pad Handler"); wxStaticBoxSizer* s_round_io_keyboard_handler = new wxStaticBoxSizer(wxVERTICAL, p_io, "Keyboard Handler"); wxStaticBoxSizer* s_round_io_mouse_handler = new wxStaticBoxSizer(wxVERTICAL, p_io, "Mouse Handler"); wxStaticBoxSizer* s_round_io_camera = new wxStaticBoxSizer(wxVERTICAL, p_io, "Camera"); wxStaticBoxSizer* s_round_io_camera_type = new wxStaticBoxSizer(wxVERTICAL, p_io, "Camera type"); // Audio wxStaticBoxSizer* s_round_audio_out = new wxStaticBoxSizer(wxVERTICAL, p_audio, "Audio Out"); // Networking wxStaticBoxSizer* s_round_net_status = new wxStaticBoxSizer(wxVERTICAL, p_networking, "Connection status"); // System wxStaticBoxSizer* s_round_sys_lang = new wxStaticBoxSizer(wxVERTICAL, p_system, "Language"); wxRadioBox* rbox_ppu_decoder; wxRadioBox* rbox_spu_decoder; wxComboBox* cbox_gs_render = new wxComboBox(p_graphics, wxID_ANY, wxEmptyString, wxDefaultPosition, wxSize(150, -1), 0, NULL, wxCB_READONLY); wxComboBox* cbox_gs_d3d_adapter = new wxComboBox(p_graphics, wxID_ANY, wxEmptyString, wxDefaultPosition, wxSize(150, -1), 0, NULL, wxCB_READONLY); wxComboBox* cbox_gs_resolution = new wxComboBox(p_graphics, wxID_ANY, wxEmptyString, wxDefaultPosition, wxSize(150, -1), 0, NULL, wxCB_READONLY); wxComboBox* cbox_gs_aspect = new wxComboBox(p_graphics, wxID_ANY, wxEmptyString, wxDefaultPosition, wxSize(150, -1), 0, NULL, wxCB_READONLY); wxComboBox* cbox_gs_frame_limit = new wxComboBox(p_graphics, wxID_ANY, wxEmptyString, wxDefaultPosition, wxSize(150, -1), 0, NULL, wxCB_READONLY); wxComboBox* cbox_pad_handler = new wxComboBox(p_io, wxID_ANY, wxEmptyString, wxDefaultPosition, wxSize(150, -1), 0, NULL, wxCB_READONLY);; wxComboBox* cbox_keyboard_handler = new wxComboBox(p_io, wxID_ANY, wxEmptyString, wxDefaultPosition, wxSize(150, -1), 0, NULL, wxCB_READONLY); wxComboBox* cbox_mouse_handler = new wxComboBox(p_io, wxID_ANY, wxEmptyString, wxDefaultPosition, wxSize(150, -1), 0, NULL, wxCB_READONLY); wxComboBox* cbox_camera = new wxComboBox(p_io, wxID_ANY, wxEmptyString, wxDefaultPosition, wxSize(150, -1), 0, NULL, wxCB_READONLY); wxComboBox* cbox_camera_type = new wxComboBox(p_io, wxID_ANY, wxEmptyString, wxDefaultPosition, wxSize(150, -1), 0, NULL, wxCB_READONLY); wxComboBox* cbox_audio_out = new wxComboBox(p_audio, wxID_ANY, wxEmptyString, wxDefaultPosition, wxSize(150, -1), 0, NULL, wxCB_READONLY); wxComboBox* cbox_net_status = new wxComboBox(p_networking, wxID_ANY, wxEmptyString, wxDefaultPosition, wxDefaultSize, 0, NULL, wxCB_READONLY); wxComboBox* cbox_sys_lang = new wxComboBox(p_system, wxID_ANY, wxEmptyString, wxDefaultPosition, wxDefaultSize, 0, NULL, wxCB_READONLY); wxCheckBox* chbox_core_hook_stfunc = new wxCheckBox(p_core, wxID_ANY, "Hook static functions"); wxCheckBox* chbox_core_load_liblv2 = new wxCheckBox(p_core, wxID_ANY, "Load liblv2.sprx only"); wxCheckBox* chbox_vfs_enable_host_root = new wxCheckBox(p_system, wxID_ANY, "Enable /host_root/"); wxCheckBox* chbox_gs_log_prog = new wxCheckBox(p_graphics, wxID_ANY, "Log shader programs"); wxCheckBox* chbox_gs_dump_depth = new wxCheckBox(p_graphics, wxID_ANY, "Write Depth Buffer"); wxCheckBox* chbox_gs_dump_color = new wxCheckBox(p_graphics, wxID_ANY, "Write Color Buffers"); wxCheckBox* chbox_gs_read_color = new wxCheckBox(p_graphics, wxID_ANY, "Read Color Buffers"); wxCheckBox* chbox_gs_read_depth = new wxCheckBox(p_graphics, wxID_ANY, "Read Depth Buffer"); wxCheckBox* chbox_gs_vsync = new wxCheckBox(p_graphics, wxID_ANY, "VSync"); wxCheckBox* chbox_gs_debug_output = new wxCheckBox(p_graphics, wxID_ANY, "Debug Output"); wxCheckBox* chbox_gs_overlay = new wxCheckBox(p_graphics, wxID_ANY, "Debug overlay"); wxCheckBox* chbox_audio_dump = new wxCheckBox(p_audio, wxID_ANY, "Dump to file"); wxCheckBox* chbox_audio_conv = new wxCheckBox(p_audio, wxID_ANY, "Convert to 16 bit"); wxCheckBox* chbox_hle_exitonstop = new wxCheckBox(p_misc, wxID_ANY, "Exit RPCS3 when process finishes"); wxCheckBox* chbox_hle_always_start = new wxCheckBox(p_misc, wxID_ANY, "Always start after boot"); wxCheckBox* chbox_dbg_ap_systemcall = new wxCheckBox(p_misc, wxID_ANY, "Auto Pause at System Call"); wxCheckBox* chbox_dbg_ap_functioncall = new wxCheckBox(p_misc, wxID_ANY, "Auto Pause at Function Call"); { // Sort string vector alphabetically static const auto sort_string_vector = [](std::vector<std::string>& vec) { std::sort(vec.begin(), vec.end(), [](const std::string &str1, const std::string &str2) { return str1 < str2; }); }; auto&& data = loaded["Core"]["Load libraries"].as<std::vector<std::string>, std::initializer_list<std::string>>({}); sort_string_vector(data); // List selected modules first for (const auto& unk : data) { lle_module_list.insert(lle_module_list.end(), std::pair<std::string, bool>(unk, true)); chbox_list_core_lle->Check(chbox_list_core_lle->Append(unk)); } const std::string& lle_dir = Emu.GetLibDir(); // TODO std::unordered_set<std::string> set(data.begin(), data.end()); std::vector<std::string> lle_module_list_unselected; for (const auto& prxf : fs::dir(lle_dir)) { // List found unselected modules if (!prxf.is_directory && ppu_prx_object(fs::file(lle_dir + prxf.name)) == elf_error::ok && !set.count(prxf.name)) { lle_module_list_unselected.push_back(prxf.name); } } sort_string_vector(lle_module_list_unselected); for (const auto& prxf : lle_module_list_unselected) { lle_module_list.insert(lle_module_list.end(), std::pair<std::string, bool>(prxf, false)); chbox_list_core_lle->Check(chbox_list_core_lle->Append(prxf), false); } lle_module_list_unselected.clear(); } radiobox_pad_helper ppu_decoder_modes({ "Core", "PPU Decoder" }); rbox_ppu_decoder = new wxRadioBox(p_core, wxID_ANY, "PPU Decoder", wxDefaultPosition, wxSize(-1, -1), ppu_decoder_modes, 1); pads.emplace_back(std::make_unique<radiobox_pad>(std::move(ppu_decoder_modes), rbox_ppu_decoder)); radiobox_pad_helper spu_decoder_modes({ "Core", "SPU Decoder" }); rbox_spu_decoder = new wxRadioBox(p_core, wxID_ANY, "SPU Decoder", wxDefaultPosition, wxSize(-1, -1), spu_decoder_modes, 1); pads.emplace_back(std::make_unique<radiobox_pad>(std::move(spu_decoder_modes), rbox_spu_decoder)); rbox_spu_decoder->Enable(3, false); // TODO pads.emplace_back(std::make_unique<checkbox_pad>(cfg_location{ "Core", "Hook static functions" }, chbox_core_hook_stfunc)); pads.emplace_back(std::make_unique<checkbox_pad>(cfg_location{ "Core", "Load liblv2.sprx only" }, chbox_core_load_liblv2)); pads.emplace_back(std::make_unique<checkbox_pad>(cfg_location{ "VFS", "Enable /host_root/" }, chbox_vfs_enable_host_root)); pads.emplace_back(std::make_unique<combobox_pad>(cfg_location{ "Video", "Renderer" }, cbox_gs_render)); pads.emplace_back(std::make_unique<combobox_pad>(cfg_location{ "Video", "Resolution" }, cbox_gs_resolution)); pads.emplace_back(std::make_unique<combobox_pad>(cfg_location{ "Video", "Aspect ratio" }, cbox_gs_aspect)); pads.emplace_back(std::make_unique<combobox_pad>(cfg_location{ "Video", "Frame limit" }, cbox_gs_frame_limit)); pads.emplace_back(std::make_unique<checkbox_pad>(cfg_location{ "Video", "Log shader programs" }, chbox_gs_log_prog)); pads.emplace_back(std::make_unique<checkbox_pad>(cfg_location{ "Video", "Write Depth Buffer" }, chbox_gs_dump_depth)); pads.emplace_back(std::make_unique<checkbox_pad>(cfg_location{ "Video", "Write Color Buffers" }, chbox_gs_dump_color)); pads.emplace_back(std::make_unique<checkbox_pad>(cfg_location{ "Video", "Read Color Buffers" }, chbox_gs_read_color)); pads.emplace_back(std::make_unique<checkbox_pad>(cfg_location{ "Video", "Read Depth Buffer" }, chbox_gs_read_depth)); pads.emplace_back(std::make_unique<checkbox_pad>(cfg_location{ "Video", "VSync" }, chbox_gs_vsync)); pads.emplace_back(std::make_unique<checkbox_pad>(cfg_location{ "Video", "Debug output" }, chbox_gs_debug_output)); pads.emplace_back(std::make_unique<checkbox_pad>(cfg_location{ "Video", "Debug overlay" }, chbox_gs_overlay)); pads.emplace_back(std::make_unique<combobox_pad>(cfg_location{ "Audio", "Renderer" }, cbox_audio_out)); pads.emplace_back(std::make_unique<checkbox_pad>(cfg_location{ "Audio", "Dump to file" }, chbox_audio_dump)); pads.emplace_back(std::make_unique<checkbox_pad>(cfg_location{ "Audio", "Convert to 16 bit" }, chbox_audio_conv)); pads.emplace_back(std::make_unique<combobox_pad>(cfg_location{ "Input/Output", "Pad" }, cbox_pad_handler)); pads.emplace_back(std::make_unique<combobox_pad>(cfg_location{ "Input/Output", "Keyboard" }, cbox_keyboard_handler)); pads.emplace_back(std::make_unique<combobox_pad>(cfg_location{ "Input/Output", "Mouse" }, cbox_mouse_handler)); pads.emplace_back(std::make_unique<combobox_pad>(cfg_location{ "Input/Output", "Camera" }, cbox_camera)); pads.emplace_back(std::make_unique<combobox_pad>(cfg_location{ "Input/Output", "Camera type" }, cbox_camera_type)); pads.emplace_back(std::make_unique<combobox_pad>(cfg_location{ "Net", "Connection status" }, cbox_net_status)); pads.emplace_back(std::make_unique<combobox_pad>(cfg_location{ "System", "Language" }, cbox_sys_lang)); pads.emplace_back(std::make_unique<checkbox_pad>(cfg_location{ "Miscellaneous", "Exit RPCS3 when process finishes" }, chbox_hle_exitonstop)); pads.emplace_back(std::make_unique<checkbox_pad>(cfg_location{ "Miscellaneous", "Always start after boot" }, chbox_hle_always_start)); pads.emplace_back(std::make_unique<checkbox_pad>(cfg_location{ "Miscellaneous", "Auto Pause at System Call" }, chbox_dbg_ap_systemcall)); pads.emplace_back(std::make_unique<checkbox_pad>(cfg_location{ "Miscellaneous", "Auto Pause at Function Call" }, chbox_dbg_ap_functioncall)); #ifdef _MSC_VER Microsoft::WRL::ComPtr<IDXGIFactory4> dxgi_factory; if (SUCCEEDED(CreateDXGIFactory(IID_PPV_ARGS(&dxgi_factory)))) { Microsoft::WRL::ComPtr<IDXGIAdapter> adapter; for (UINT id = 0; dxgi_factory->EnumAdapters(id, adapter.ReleaseAndGetAddressOf()) != DXGI_ERROR_NOT_FOUND; id++) { DXGI_ADAPTER_DESC desc; adapter->GetDesc(&desc); cbox_gs_d3d_adapter->Append(desc.Description); } pads.emplace_back(std::make_unique<combobox_pad>(cfg_location{ "Video", "D3D12", "Adapter" }, cbox_gs_d3d_adapter)); } else #endif { cbox_gs_d3d_adapter->Enable(false); } // Core s_round_core_lle->Add(chbox_list_core_lle, wxSizerFlags().Border(wxALL, 5).Expand()); s_round_core_lle->Add(s_module_search_box, wxSizerFlags().Border(wxALL, 5).Expand()); // Rendering s_round_gs_render->Add(cbox_gs_render, wxSizerFlags().Border(wxALL, 5).Expand()); s_round_gs_d3d_adapter->Add(cbox_gs_d3d_adapter, wxSizerFlags().Border(wxALL, 5).Expand()); s_round_gs_res->Add(cbox_gs_resolution, wxSizerFlags().Border(wxALL, 5).Expand()); s_round_gs_aspect->Add(cbox_gs_aspect, wxSizerFlags().Border(wxALL, 5).Expand()); s_round_gs_frame_limit->Add(cbox_gs_frame_limit, wxSizerFlags().Border(wxALL, 5).Expand()); // Input/Output s_round_io_pad_handler->Add(cbox_pad_handler, wxSizerFlags().Border(wxALL, 5).Expand()); s_round_io_keyboard_handler->Add(cbox_keyboard_handler, wxSizerFlags().Border(wxALL, 5).Expand()); s_round_io_mouse_handler->Add(cbox_mouse_handler, wxSizerFlags().Border(wxALL, 5).Expand()); s_round_io_camera->Add(cbox_camera, wxSizerFlags().Border(wxALL, 5).Expand()); s_round_io_camera_type->Add(cbox_camera_type, wxSizerFlags().Border(wxALL, 5).Expand()); s_round_audio_out->Add(cbox_audio_out, wxSizerFlags().Border(wxALL, 5).Expand()); // Networking s_round_net_status->Add(cbox_net_status, wxSizerFlags().Border(wxALL, 5).Expand()); // System s_round_sys_lang->Add(cbox_sys_lang, wxSizerFlags().Border(wxALL, 5).Expand()); // Core s_subpanel_core1->Add(rbox_ppu_decoder, wxSizerFlags().Border(wxALL, 5).Expand()); s_subpanel_core1->Add(rbox_spu_decoder, wxSizerFlags().Border(wxALL, 5).Expand()); s_subpanel_core1->Add(chbox_core_hook_stfunc, wxSizerFlags().Border(wxALL, 5).Expand()); s_subpanel_core1->Add(chbox_core_load_liblv2, wxSizerFlags().Border(wxALL, 5).Expand()); s_subpanel_core2->Add(s_round_core_lle, wxSizerFlags().Border(wxALL, 5).Expand()); s_subpanel_core->Add(s_subpanel_core1); s_subpanel_core->Add(s_subpanel_core2); // Graphics s_subpanel_graphics1->Add(s_round_gs_render, wxSizerFlags().Border(wxALL, 5).Expand()); s_subpanel_graphics1->Add(s_round_gs_res, wxSizerFlags().Border(wxALL, 5).Expand()); s_subpanel_graphics1->Add(s_round_gs_d3d_adapter, wxSizerFlags().Border(wxALL, 5).Expand()); s_subpanel_graphics1->Add(chbox_gs_dump_color, wxSizerFlags().Border(wxALL, 5).Expand()); s_subpanel_graphics1->Add(chbox_gs_read_color, wxSizerFlags().Border(wxALL, 5).Expand()); s_subpanel_graphics1->Add(chbox_gs_dump_depth, wxSizerFlags().Border(wxALL, 5).Expand()); s_subpanel_graphics1->Add(chbox_gs_read_depth, wxSizerFlags().Border(wxALL, 5).Expand()); s_subpanel_graphics2->Add(s_round_gs_aspect, wxSizerFlags().Border(wxALL, 5).Expand()); s_subpanel_graphics2->Add(s_round_gs_frame_limit, wxSizerFlags().Border(wxALL, 5).Expand()); s_subpanel_graphics2->AddSpacer(68); s_subpanel_graphics2->Add(chbox_gs_debug_output, wxSizerFlags().Border(wxALL, 5).Expand()); s_subpanel_graphics2->Add(chbox_gs_overlay, wxSizerFlags().Border(wxALL, 5).Expand()); s_subpanel_graphics2->Add(chbox_gs_log_prog, wxSizerFlags().Border(wxALL, 5).Expand()); s_subpanel_graphics2->Add(chbox_gs_vsync, wxSizerFlags().Border(wxALL, 5).Expand()); s_subpanel_graphics->Add(s_subpanel_graphics1); s_subpanel_graphics->Add(s_subpanel_graphics2); // Input - Output s_subpanel_io1->Add(s_round_io_pad_handler, wxSizerFlags().Border(wxALL, 5).Expand()); s_subpanel_io1->Add(s_round_io_keyboard_handler, wxSizerFlags().Border(wxALL, 5).Expand()); s_subpanel_io1->Add(s_round_io_mouse_handler, wxSizerFlags().Border(wxALL, 5).Expand()); s_subpanel_io2->Add(s_round_io_camera, wxSizerFlags().Border(wxALL, 5).Expand()); s_subpanel_io2->Add(s_round_io_camera_type, wxSizerFlags().Border(wxALL, 5).Expand()); s_subpanel_io->Add(s_subpanel_io1); s_subpanel_io->Add(s_subpanel_io2); // Audio s_subpanel_audio->Add(s_round_audio_out, wxSizerFlags().Border(wxALL, 5).Expand()); s_subpanel_audio->Add(chbox_audio_dump, wxSizerFlags().Border(wxALL, 5).Expand()); s_subpanel_audio->Add(chbox_audio_conv, wxSizerFlags().Border(wxALL, 5).Expand()); // Miscellaneous s_subpanel_misc->Add(chbox_hle_exitonstop, wxSizerFlags().Border(wxALL, 5).Expand()); s_subpanel_misc->Add(chbox_hle_always_start, wxSizerFlags().Border(wxALL, 5).Expand()); // Auto Pause s_subpanel_misc->Add(chbox_dbg_ap_systemcall, wxSizerFlags().Border(wxALL, 5).Expand()); s_subpanel_misc->Add(chbox_dbg_ap_functioncall, wxSizerFlags().Border(wxALL, 5).Expand()); // Networking s_subpanel_networking->Add(s_round_net_status, wxSizerFlags().Border(wxALL, 5).Expand()); // System s_subpanel_system->Add(chbox_vfs_enable_host_root, wxSizerFlags().Border(wxALL, 5).Expand()); s_subpanel_system->Add(s_round_sys_lang, wxSizerFlags().Border(wxALL, 5).Expand()); // Buttons wxBoxSizer* s_b_panel(new wxBoxSizer(wxHORIZONTAL)); s_b_panel->Add(new wxButton(this, wxID_OK), wxSizerFlags().Border(wxALL, 5).Bottom()); s_b_panel->Add(new wxButton(this, wxID_CANCEL), wxSizerFlags().Border(wxALL, 5).Bottom()); // Resize panels SetSizerAndFit(s_subpanel_core, false); SetSizerAndFit(s_subpanel_graphics, false); SetSizerAndFit(s_subpanel_io, false); SetSizerAndFit(s_subpanel_audio, false); SetSizerAndFit(s_subpanel_misc, false); SetSizerAndFit(s_subpanel_networking, false); SetSizerAndFit(s_subpanel_system, false); SetSizerAndFit(s_b_panel, false); SetSize(width + 26, height + 80); if (ShowModal() == wxID_OK) { std::set<std::string> lle_selected; for (auto& i : lle_module_list) { if (i.second) // selected { lle_selected.emplace(i.first); } } saved.reset(); saved["Core"]["Load libraries"] = std::vector<std::string>(lle_selected.begin(), lle_selected.end()); for (auto& pad : pads) { pad->save(); } loaded += saved; YAML::Emitter out; emit(out, loaded); // Save config config.seek(0); config.trunc(0); config.write(out.c_str(), out.size()); } }
bool D3DClass::Initialize(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 blendStateDescription; // Store the vsync setting. m_vsync_enabled = vsync; // Create a DirectX graphics interface factory. result = CreateDXGIFactory(__uuidof(IDXGIFactory), (void**)&factory); if(FAILED(result)) { return false; } // Use the factory to create an adapter 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 fit 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 display 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 megabytes. m_videoCardMemory = (int)(adapterDesc.DedicatedVideoMemory / 1024 / 1024); // Convert the name of the video card to a character array and store it. error = wcstombs_s(&stringLength, m_videoCardDescription, 128, adapterDesc.Description, 128); if(error != 0) { return false; } // Release the display mode list. delete [] displayModeList; displayModeList = 0; // Release the adapter output. adapterOutput->Release(); adapterOutput = 0; // Release the adapter. adapter->Release(); adapter = 0; // Release the factory. factory->Release(); factory = 0; // Initialize 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(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 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 full screen or windowed mode. 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 presenting. 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 Direct3D device context. result = D3D11CreateDeviceAndSwapChain(NULL, D3D_DRIVER_TYPE_HARDWARE, NULL, 0, &featureLevel, 1, D3D11_SDK_VERSION, &swapChainDesc, &m_swapChain, &m_device, NULL, &m_deviceContext); if(FAILED(result)) { return false; } // Get the pointer to the back buffer. result = m_swapChain->GetBuffer(0, __uuidof(ID3D11Texture2D), (LPVOID*)&backBufferPtr); if(FAILED(result)) { return false; } // Create the render target view with the back buffer pointer. result = m_device->CreateRenderTargetView(backBufferPtr, NULL, &m_renderTargetView); if(FAILED(result)) { return false; } // Release pointer to the back buffer as we no longer need it. backBufferPtr->Release(); backBufferPtr = 0; // 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 = m_device->CreateTexture2D(&depthBufferDesc, NULL, &m_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 = m_device->CreateDepthStencilState(&depthStencilDesc, &m_depthStencilState); if(FAILED(result)) { return false; } // Set the depth stencil state. m_deviceContext->OMSetDepthStencilState(m_depthStencilState, 1); // Initialize 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; // Create the depth stencil view. result = m_device->CreateDepthStencilView(m_depthStencilBuffer, &depthStencilViewDesc, &m_depthStencilView); if(FAILED(result)) { return false; } // Bind the render target view and depth stencil buffer to the output render pipeline. m_deviceContext->OMSetRenderTargets(1, &m_renderTargetView, m_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 = m_device->CreateRasterizerState(&rasterDesc, &m_rasterState); if(FAILED(result)) { return false; } // Now set the rasterizer state. m_deviceContext->RSSetState(m_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. m_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(&m_projectionMatrix, fieldOfView, screenAspect, screenNear, screenDepth); // Initialize the world matrix to the identity matrix. D3DXMatrixIdentity(&m_worldMatrix); // Create an orthographic projection matrix for 2D rendering. D3DXMatrixOrthoLH(&m_orthoMatrix, (float)screenWidth, (float)screenHeight, screenNear, screenDepth); // Clear the second depth stencil state before setting the parameters. 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 = m_device->CreateDepthStencilState(&depthDisabledStencilDesc, &m_depthDisabledStencilState); if(FAILED(result)) { return false; } // Clear the blend state description. ZeroMemory(&blendStateDescription, sizeof(D3D11_BLEND_DESC)); // Create an alpha enabled blend state description. blendStateDescription.RenderTarget[0].BlendEnable = TRUE; blendStateDescription.RenderTarget[0].SrcBlend = D3D11_BLEND_ONE; blendStateDescription.RenderTarget[0].DestBlend = D3D11_BLEND_INV_SRC_ALPHA; blendStateDescription.RenderTarget[0].BlendOp = D3D11_BLEND_OP_ADD; blendStateDescription.RenderTarget[0].SrcBlendAlpha = D3D11_BLEND_ONE; blendStateDescription.RenderTarget[0].DestBlendAlpha = D3D11_BLEND_ZERO; blendStateDescription.RenderTarget[0].BlendOpAlpha = D3D11_BLEND_OP_ADD; blendStateDescription.RenderTarget[0].RenderTargetWriteMask = 0x0f; // Create the blend state using the description. result = m_device->CreateBlendState(&blendStateDescription, &m_alphaEnableBlendingState); if(FAILED(result)) { return false; } // Modify the description to create an alpha disabled blend state description. blendStateDescription.RenderTarget[0].BlendEnable = FALSE; // Create the second blend state using the description. result = m_device->CreateBlendState(&blendStateDescription, &m_alphaDisableBlendingState); if(FAILED(result)) { return false; } return true; }
result_t app_init_dxgi(const struct init_params* params, OUT IDXGIFactory** pfactory, OUT IDXGIAdapter** padapter, OUT ID3D11Device** pdev, OUT ID3D11DeviceContext** pcontext, OUT enum gfx_hwver* pver) { HRESULT dxhr; uint dev_flags = 0; D3D_FEATURE_LEVEL levels[3]; uint levels_cnt; D3D_FEATURE_LEVEL ft_level; IDXGIFactory* factory; IDXGIAdapter* adapter; ID3D11Device* dev; ID3D11DeviceContext* ctx = NULL; enum gfx_hwver gfxver; log_print(LOG_INFO, " init DXGI (D3D11) ..."); dxhr = CreateDXGIFactory(__uuidof(IDXGIFactory), (void**)&factory); if (FAILED(dxhr)) { err_print(__FILE__, __LINE__, "gfx-device init failed: could not create dx factory"); return RET_FAIL; } /* gfx dxgi_adapter */ dxhr = factory->EnumAdapters(params->gfx.adapter_id, &adapter); if (dxhr == DXGI_ERROR_NOT_FOUND) { factory->Release(); err_print(__FILE__, __LINE__, "gfx-device init failed: specified dxgi_adapter-id not found"); return RET_FAIL; } /* Flags */ if (BIT_CHECK(params->gfx.flags, GFX_FLAG_DEBUG)) BIT_ADD(dev_flags, D3D11_CREATE_DEVICE_DEBUG); /* Feature Levels */ if (params->gfx.hwver == GFX_HWVER_UNKNOWN) { levels[0] = D3D_FEATURE_LEVEL_11_0; levels[1] = D3D_FEATURE_LEVEL_10_1; levels[2] = D3D_FEATURE_LEVEL_10_0; levels_cnt = 3; } else { switch (params->gfx.hwver) { case GFX_HWVER_D3D10_0: levels[0] = D3D_FEATURE_LEVEL_10_0; break; case GFX_HWVER_D3D10_1: levels[0] = D3D_FEATURE_LEVEL_10_1; break; case GFX_HWVER_D3D11_0: case GFX_HWVER_D3D11_1: levels[0] = D3D_FEATURE_LEVEL_11_0; break; } levels_cnt = 1; } /* create device */ dxhr = D3D11CreateDevice(adapter, D3D_DRIVER_TYPE_UNKNOWN, NULL, dev_flags, levels, levels_cnt, D3D11_SDK_VERSION, &dev, &ft_level, &ctx); if (FAILED(dxhr)) { err_print(__FILE__, __LINE__, "app init failed: could not create d3d device"); return RET_FAIL; } switch (ft_level) { case D3D_FEATURE_LEVEL_10_0: gfxver = GFX_HWVER_D3D10_0; break; case D3D_FEATURE_LEVEL_10_1: gfxver = GFX_HWVER_D3D10_1; break; case D3D_FEATURE_LEVEL_11_0: gfxver = GFX_HWVER_D3D11_0; break; case D3D_FEATURE_LEVEL_11_1: gfxver = GFX_HWVER_D3D11_1; break; default: gfxver = GFX_HWVER_UNKNOWN; break; } /* elevate the API to d3d11.1 */ /* fetch context (currently not working because I don't have win8 dev system) */ /* ID3D11Device* dev1; dxhr = dev->QueryInterface(__uuidof(ID3D11Device), (void**)&dev1); if (FAILED(dxhr)) { err_print(__FILE__, __LINE__, "app init failed: could not create d3d11.1 device"); return RET_FAIL; } dev->Release(); ID3D11DeviceContext* ctx1; dev1->GetImmediateContext1(&ctx1); ctx->Release(); */ /* assign output values */ *pfactory = factory; *padapter = adapter; *pdev = dev; *pcontext = ctx; *pver = gfxver; return RET_OK; }
int DxApp::SetupDxResources() { HRESULT hr = S_OK; UINT createDeviceFlags = D3D11_CREATE_DEVICE_SINGLETHREADED | D3D11_CREATE_DEVICE_PREVENT_INTERNAL_THREADING_OPTIMIZATIONS; #ifdef _DEBUG createDeviceFlags |= D3D11_CREATE_DEVICE_DEBUG; #endif hr = CreateDXGIFactory(__uuidof(IDXGIFactory) ,(void**)&m_pFactory); if( FAILED( hr ) ) return hr; D3D_DRIVER_TYPE driverTypes[] = { D3D_DRIVER_TYPE_HARDWARE, D3D_DRIVER_TYPE_WARP, D3D_DRIVER_TYPE_REFERENCE, }; UINT numDriverTypes = ARRAYSIZE( driverTypes ); D3D_FEATURE_LEVEL featureLevels[] = { D3D_FEATURE_LEVEL_11_0 //11_1 could be added here but some windows 7 machines have video cards with support for 11_1 but with out 11_1 software being installed resulting in invalid args }; UINT numFeatureLevels = ARRAYSIZE( featureLevels ); DXGI_SWAP_CHAIN_DESC sd; ZeroMemory( &sd, sizeof( sd ) ); sd.BufferCount = 2; sd.BufferDesc.Width = m_settings.width; sd.BufferDesc.Height = m_settings.height; sd.BufferDesc.Format = m_settings.colour; sd.BufferDesc.RefreshRate.Numerator = m_settings.refreshRate!=0 ? m_settings.refreshRate : 60; sd.BufferDesc.RefreshRate.Denominator = 1; sd.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT; sd.OutputWindow = m_hWnd; sd.SampleDesc.Count = 1; sd.SampleDesc.Quality = 0; sd.Windowed = !(m_settings.fullscreen); for( UINT driverTypeIndex = 0; driverTypeIndex < numDriverTypes; driverTypeIndex++ ) { m_driverType = driverTypes[driverTypeIndex]; hr = D3D11CreateDeviceAndSwapChain( NULL, m_driverType, NULL, createDeviceFlags, featureLevels, numFeatureLevels, D3D11_SDK_VERSION, &sd, &m_pSwapChain, &m_pd3dDevice, &m_featureLevel, &m_pImmediateContext ); if( SUCCEEDED( hr ) ) break; else MessageBox(m_hWnd, L"Warning, Graphics isn't running in full hardware mode", NULL, NULL); } if( FAILED( hr ) ) return hr; DXGI_FORMAT activeFormat = DXGI_FORMAT_R32G32B32A32_FLOAT; D3D11_RASTERIZER_DESC drd = { D3D11_FILL_SOLID,//D3D11_FILL_MODE FillMode; D3D11_CULL_BACK,//D3D11_CULL_MODE CullMode; FALSE,//BOOL FrontCounterClockwise; 0,//INT DepthBias; 0.0,//FLOAT DepthBiasClamp; 0.0,//FLOAT SlopeScaledDepthBias; TRUE,//BOOL DepthClipEnable; FALSE,//BOOL ScissorEnable; TRUE,//BOOL MultisampleEnable; FALSE//BOOL AntialiasedLineEnable; }; #ifdef _DEBUG drd.CullMode=D3D11_CULL_NONE; #endif m_pd3dDevice->CreateRasterizerState(&drd, &m_pRasterizeDepth); drd.DepthClipEnable = FALSE; m_pd3dDevice->CreateRasterizerState(&drd, &m_pRasterizeNoDepth); m_pImmediateContext->RSSetState(m_pRasterizeNoDepth); D3D11_SAMPLER_DESC SamDesc = { D3D11_FILTER_MIN_MAG_MIP_LINEAR,// D3D11_FILTER Filter; D3D11_TEXTURE_ADDRESS_WRAP, //D3D11_TEXTURE_ADDRESS_MODE AddressU; D3D11_TEXTURE_ADDRESS_WRAP, //D3D11_TEXTURE_ADDRESS_MODE AddressV; D3D11_TEXTURE_ADDRESS_BORDER, //D3D11_TEXTURE_ADDRESS_MODE AddressW; 0,//FLOAT MipLODBias; 0,//UINT MaxAnisotropy; D3D11_COMPARISON_NEVER , //D3D11_COMPARISON_FUNC ComparisonFunc; 0.0,0.0,0.0,0.0,//FLOAT BorderColor[ 4 ]; 0,//FLOAT MinLOD; 0//FLOAT MaxLOD; }; m_pd3dDevice->CreateSamplerState( &SamDesc, &m_pSamplerState ); // Create a render target view ID3D11Texture2D* pBackBuffer = NULL; hr = m_pSwapChain->GetBuffer( 0, __uuidof( ID3D11Texture2D ), ( LPVOID* )&pBackBuffer ); if( FAILED( hr ) ) return hr; hr = m_pd3dDevice->CreateRenderTargetView( pBackBuffer, NULL, &m_pRenderFinalTargetView ); pBackBuffer->Release(); if( FAILED( hr ) ) return hr; ID3D11DepthStencilView *dsNullview = NULL; m_pImmediateContext->OMSetRenderTargets( 1, &m_pRenderFinalTargetView, dsNullview ); UINT offset = 0; ID3D11Buffer *vb = {NULL}; m_pImmediateContext->IASetInputLayout(NULL); m_pImmediateContext->IASetPrimitiveTopology( D3D_PRIMITIVE_TOPOLOGY_TRIANGLESTRIP ); LPVOID data; SIZE_T length; char tempbuffer[32768]; //max shader size.... FILE *FP; fopen_s(&FP, "VertexShader.cso", "rb"); length = fread(tempbuffer, 1, 32768, FP); fclose(FP); data = tempbuffer; hr = m_pd3dDevice->CreateVertexShader( data, length, NULL, &m_pVertexShader ); D3D11_INPUT_ELEMENT_DESC layouttex[] = { { "POSITION", 0, DXGI_FORMAT_R32G32_FLOAT, 0, 0, D3D11_INPUT_PER_VERTEX_DATA, 0 }, { "TEXCOORD", 0, DXGI_FORMAT_R32G32_FLOAT, 0, 8, D3D11_INPUT_PER_VERTEX_DATA, 0 } }; hr = m_pd3dDevice->CreateInputLayout( layouttex, 2, data, length, &m_pVertexInput ); fopen_s(&FP, "PixelShader.cso", "rb"); length = fread(tempbuffer, 1, 32768, FP); fclose(FP); data = tempbuffer; hr = m_pd3dDevice->CreatePixelShader( data, length, NULL, &m_pPixelShader ); fopen_s(&FP, "sim.cso", "rb"); length = fread(tempbuffer, 1, 32768, FP); fclose(FP); data = tempbuffer; hr = m_pd3dDevice->CreatePixelShader( data, length, NULL, &m_pSimShader ); fopen_s(&FP, "reset.cso", "rb"); length = fread(tempbuffer, 1, 32768, FP); fclose(FP); data = tempbuffer; hr = m_pd3dDevice->CreatePixelShader( data, length, NULL, &m_pResetShader ); fopen_s(&FP, "halt.cso", "rb"); length = fread(tempbuffer, 1, 32768, FP); fclose(FP); data = tempbuffer; hr = m_pd3dDevice->CreatePixelShader( data, length, NULL, &m_pHaltShader ); fopen_s(&FP, "CSsim.cso", "rb"); length = fread(tempbuffer, 1, 32768, FP); fclose(FP); data = tempbuffer; hr = m_pd3dDevice->CreateComputeShader( data, length, NULL, &m_pCSSimShader ); m_pImmediateContext->VSSetShader(m_pVertexShader, NULL, 0); m_pImmediateContext->CSSetShader(m_pCSSimShader, NULL, 0); m_pImmediateContext->PSSetSamplers(0, 1, &m_pSamplerState); D3D11_BUFFER_DESC bd; ZeroMemory(&bd, sizeof(D3D11_BUFFER_DESC)); bd.Usage = D3D11_USAGE_DEFAULT; bd.ByteWidth = 16; bd.BindFlags = D3D11_BIND_CONSTANT_BUFFER; bd.CPUAccessFlags = 0; m_pd3dDevice->CreateBuffer(&bd, NULL, &m_pConstantBuffer); m_pImmediateContext->UpdateSubresource( m_pConstantBuffer, 0, NULL, &m_settings.height, 0, 0 ); bd.ByteWidth = sizeof(SimInput); m_pd3dDevice->CreateBuffer(&bd, NULL, &m_pSimInput); bd.ByteWidth = 32; m_pd3dDevice->CreateBuffer(&bd, NULL, &m_pSimInfoCB); D3D11_TEXTURE2D_DESC descT; ZeroMemory( &descT, sizeof(descT) ); descT.Width = PARTNUM; descT.Height = PARTNUM; descT.MipLevels = 1; descT.ArraySize = 1; descT.Format = DXGI_FORMAT_R32G32B32A32_FLOAT; descT.SampleDesc.Count = 1; descT.SampleDesc.Quality = 0; descT.Usage = D3D11_USAGE_DEFAULT; descT.BindFlags = D3D11_BIND_RENDER_TARGET | D3D11_BIND_SHADER_RESOURCE | D3D11_BIND_UNORDERED_ACCESS; descT.CPUAccessFlags = 0; descT.MiscFlags = 0; float *initData = new float[PARTNUM*PARTNUM*4]; //dynamic because 64MB... int ix=0; int iy=0; for(int i=0; i<PARTNUM*PARTNUM*4; i+=4) { float px = ix; ix++; if(ix==PARTNUM) { ix=0; iy++; } float py = iy; px/=PARTNUM; py/=PARTNUM; px*=m_settings.width; py*=m_settings.height; initData[i] = 0.f; initData[i+1] = 0.f; initData[i+2] = px; initData[i+3] = py; } D3D11_SUBRESOURCE_DATA SRDesc = {initData, PARTNUM*4*4, NULL}; hr = m_pd3dDevice->CreateTexture2D( &descT, &SRDesc, &m_pTextureDataBuffer[0] ); delete [] initData; hr = m_pd3dDevice->CreateTexture2D( &descT, NULL, &m_pTextureDataBuffer[1] ); m_pd3dDevice->CreateShaderResourceView(m_pTextureDataBuffer[0], NULL, &m_pTextureDataView[0]); m_pd3dDevice->CreateShaderResourceView(m_pTextureDataBuffer[1], NULL, &m_pTextureDataView[1]); m_pd3dDevice->CreateRenderTargetView(m_pTextureDataBuffer[0], NULL, &m_pDataRenderTargetView[0]); m_pd3dDevice->CreateRenderTargetView(m_pTextureDataBuffer[1], NULL, &m_pDataRenderTargetView[1]); m_pd3dDevice->CreateUnorderedAccessView(m_pTextureDataBuffer[0], NULL, &m_pTextureDataUAView[0]); m_pd3dDevice->CreateUnorderedAccessView(m_pTextureDataBuffer[1], NULL, &m_pTextureDataUAView[1]); ID3D11Buffer *CBList[] = {m_pConstantBuffer, m_pSimInfoCB, m_pSimInput}; m_pImmediateContext->PSSetConstantBuffers(0, 3, CBList); m_oWidth = m_settings.width; m_oHeight = m_settings.height; m_scale = 1.f; return 0; }
HRESULT WINAPI D3D10CreateDevice(IDXGIAdapter *adapter, D3D10_DRIVER_TYPE driver_type, HMODULE swrast, UINT flags, UINT sdk_version, ID3D10Device **device) { IDXGIFactory *factory; HRESULT hr; TRACE("adapter %p, driver_type %s, swrast %p, flags %#x, sdk_version %d, device %p\n", adapter, debug_d3d10_driver_type(driver_type), swrast, flags, sdk_version, device); if (adapter) { IDXGIAdapter_AddRef(adapter); hr = IDXGIAdapter_GetParent(adapter, &IID_IDXGIFactory, (void **)&factory); if (FAILED(hr)) { WARN("Failed to get dxgi factory, returning %#x\n", hr); return hr; } } else { hr = CreateDXGIFactory(&IID_IDXGIFactory, (void **)&factory); if (FAILED(hr)) { WARN("Failed to create dxgi factory, returning %#x\n", hr); return hr; } switch(driver_type) { case D3D10_DRIVER_TYPE_HARDWARE: { hr = IDXGIFactory_EnumAdapters(factory, 0, &adapter); if (FAILED(hr)) { WARN("No adapters found, returning %#x\n", hr); IDXGIFactory_Release(factory); return hr; } break; } case D3D10_DRIVER_TYPE_NULL: FIXME("NULL device not implemented, falling back to refrast\n"); /* fall through, for now */ case D3D10_DRIVER_TYPE_REFERENCE: { HMODULE refrast = LoadLibraryA("d3d10ref.dll"); if (!refrast) { WARN("Failed to load refrast, returning E_FAIL\n"); IDXGIFactory_Release(factory); return E_FAIL; } hr = IDXGIFactory_CreateSoftwareAdapter(factory, refrast, &adapter); FreeLibrary(refrast); if (FAILED(hr)) { WARN("Failed to create a software adapter, returning %#x\n", hr); IDXGIFactory_Release(factory); return hr; } break; } case D3D10_DRIVER_TYPE_SOFTWARE: { if (!swrast) { WARN("Software device requested, but NULL swrast passed, returning E_FAIL\n"); IDXGIFactory_Release(factory); return E_FAIL; } hr = IDXGIFactory_CreateSoftwareAdapter(factory, swrast, &adapter); if (FAILED(hr)) { WARN("Failed to create a software adapter, returning %#x\n", hr); IDXGIFactory_Release(factory); return hr; } break; } } } hr = D3D10CoreCreateDevice(factory, adapter, flags, NULL, device); IDXGIAdapter_Release(adapter); IDXGIFactory_Release(factory); if (FAILED(hr)) { WARN("Failed to create a device, returning %#x\n", hr); return hr; } TRACE("Created ID3D10Device %p\n", *device); return hr; }
HRESULT DXManager::getVideoCardInfo() { HRESULT result; IDXGIFactory* factory; IDXGIAdapter* adapter; IDXGIOutput* adapterOutput; DXGI_MODE_DESC* displayModeList; DXGI_ADAPTER_DESC adapterDesc; unsigned int numModes, i, stringLength; int error; result = CreateDXGIFactory(__uuidof(IDXGIFactory), (void**)&factory); if (FAILED(result)) { return false; } result = factory->EnumAdapters(0, &adapter); if (FAILED(result)) { return false; } result = adapter->EnumOutputs(0, &adapterOutput); if (FAILED(result)) { return false; } result = adapterOutput->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 = adapterOutput->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)m_ScreenWidth) { if (displayModeList[i].Height == (unsigned int)m_ScreenHeight) { mNumerator = displayModeList[i].RefreshRate.Numerator; mDenominator = displayModeList[i].RefreshRate.Denominator; } } } result = adapter->GetDesc(&adapterDesc); if (FAILED(result)) { return false; } m_videoCardMemory = (int)(adapterDesc.DedicatedVideoMemory / 1024 / 1024); //MB Video Ram error = wcstombs_s(&stringLength, m_videoCardDescription, 128, adapterDesc.Description, 128); if (error != 0) { return false; } delete[] displayModeList; displayModeList = 0; adapterOutput->Release(); adapterOutput = 0; adapter->Release(); adapter = 0; factory->Release(); factory = 0; return S_OK; }
D3D11Interface::D3D11Interface(HWND hwnd, bool fullscreen, unsigned int width, unsigned int height, bool vsyncEnabled) { IDXGIFactory* factory = 0; IDXGIAdapter* adapter = 0; IDXGIOutput* adapterOutput = 0; DXGI_MODE_DESC* displayModeList = 0; DXGI_ADAPTER_DESC adapterDesc; DXGI_SWAP_CHAIN_DESC swapChainDesc; D3D_FEATURE_LEVEL featureLevel; D3D11_TEXTURE2D_DESC depthBufferDesc; D3D11_DEPTH_STENCIL_DESC depthStencilDesc; D3D11_DEPTH_STENCIL_VIEW_DESC dsViewDesc; unsigned int numModes; unsigned int numerator = 0, denominator = 1; //get the monitor refresh rate to prevent performance issues //create a DX graphics interface factory HRESULT m_lastError = CreateDXGIFactory(__uuidof(IDXGIFactory), (void**)&factory); if(FAILED(m_lastError)) { throw Kiwi::Exception(L"D3D11Interface::Initialize", L"Failed to create graphics interface factory"); return; } //now use it to create an adapter for the primary video card m_lastError = factory->EnumAdapters(0, &adapter); if(FAILED(m_lastError)) { throw Kiwi::Exception(L"D3D11Interface::Initialize", L"Failed to create graphics adapter"); return; } //enumerate the primary monitor m_lastError = adapter->EnumOutputs(0, &adapterOutput); if(FAILED(m_lastError)) { throw Kiwi::Exception(L"D3D11Interface::Initialize", L"Failed to enumerate primary monitor"); return; } //get the number of modes that fit the DXGI_FORMAT_R8G8B8A8_UNORM format m_lastError = adapterOutput->GetDisplayModeList(DXGI_FORMAT_R8G8B8A8_UNORM, DXGI_ENUM_MODES_INTERLACED, &numModes, NULL); if(FAILED(m_lastError)) { throw Kiwi::Exception(L"D3D11Interface::Initialize", L"Failed to get display mode list"); return; } //create a list of all the display modes for the monitor/video card displayModeList = new DXGI_MODE_DESC[numModes]; //fill the display mode lists m_lastError = adapterOutput->GetDisplayModeList(DXGI_FORMAT_R8G8B8A8_UNORM, DXGI_ENUM_MODES_INTERLACED, &numModes, displayModeList); if(FAILED(m_lastError)) { throw Kiwi::Exception(L"D3D11Interface::Initialize", L"Failed to fill display mode list"); return; } //find the correct display mode for(unsigned int i = 0; i < numModes; i++) { if(displayModeList[i].Width == width && displayModeList[i].Height == height) { numerator = displayModeList[i].RefreshRate.Numerator; denominator = displayModeList[i].RefreshRate.Denominator; } } //lastly, get the name of the video card and the amount of RAM m_lastError = adapter->GetDesc(&adapterDesc); if(FAILED(m_lastError)) { throw Kiwi::Exception(L"D3D11Interface::Initialize", L"Failed to get adapter info"); return; } //store video card RAM in megabytes m_videoCardInfo.totalRAM = (int)(adapterDesc.DedicatedVideoMemory / 1024 / 1024); //get the name of the video card m_videoCardInfo.name = adapterDesc.Description; delete [] displayModeList; displayModeList = 0; SAFE_RELEASE(adapterOutput); SAFE_RELEASE(adapter); SAFE_RELEASE(factory); //now initialize the swapchain/desc ZeroMemory(&swapChainDesc, sizeof(swapChainDesc)); swapChainDesc.BufferCount = 1; //single back buffer swapChainDesc.BufferDesc.Width = width; swapChainDesc.BufferDesc.Height = height; swapChainDesc.BufferDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM; //32-bit surface if(vsyncEnabled) { swapChainDesc.BufferDesc.RefreshRate.Numerator = numerator; swapChainDesc.BufferDesc.RefreshRate.Denominator = denominator; }else { swapChainDesc.BufferDesc.RefreshRate.Numerator = 0; swapChainDesc.BufferDesc.RefreshRate.Denominator = 1; } //using the back buffer as a render target swapChainDesc.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT; swapChainDesc.OutputWindow = hwnd; //turn off multisampling swapChainDesc.SampleDesc.Count = 1; swapChainDesc.SampleDesc.Quality = 0; swapChainDesc.Windowed = !fullscreen; swapChainDesc.BufferDesc.ScanlineOrdering = DXGI_MODE_SCANLINE_ORDER_UNSPECIFIED; swapChainDesc.BufferDesc.Scaling = DXGI_MODE_SCALING_UNSPECIFIED; swapChainDesc.SwapEffect = DXGI_SWAP_EFFECT_DISCARD; //discard back buffer contents after presenting swapChainDesc.Flags = 0; //using DX 11 featureLevel = D3D_FEATURE_LEVEL_11_0; //create the swapchain, direct3d device, and d3d context m_lastError = D3D11CreateDeviceAndSwapChain(NULL, D3D_DRIVER_TYPE_HARDWARE, NULL, D3D11_CREATE_DEVICE_DEBUG, &featureLevel, 1, D3D11_SDK_VERSION, &swapChainDesc, &m_swapChain, &m_device, NULL, &m_deviceContext); if(FAILED(m_lastError)) { std::wstring error = Kiwi::GetD3DErrorString(m_lastError); throw Kiwi::Exception(L"D3D11Interface::Initialize", L"Failed to create device/swap chain ("+error+L")"); return; } //get the back buffer and attach it to the swap chain m_lastError = m_swapChain->GetBuffer(0, __uuidof(ID3D11Texture2D), (LPVOID*)&m_backBuffer); if(FAILED(m_lastError)) { throw Kiwi::Exception(L"D3D11Interface::Initialize", L"Failed to attach back buffer"); } //create render target view m_lastError = m_device->CreateRenderTargetView(m_backBuffer, NULL, &m_backBufferRenderTargetView); if(FAILED(m_lastError)) { throw Kiwi::Exception(L"D3D11Interface::Initialize", L"Failed to create back buffer render target view");; } //create depth/stencil buffer to allow proper rendering in 3d space and allow for effects ZeroMemory(&depthBufferDesc, sizeof(depthBufferDesc)); depthBufferDesc.Width = width; depthBufferDesc.Height = height; 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; m_lastError = m_device->CreateTexture2D(&depthBufferDesc, NULL, &m_backBufferDepthBuffer); if(FAILED(m_lastError)) { throw Kiwi::Exception(L"D3D11Interface::Initialize", L"Failed to create back buffer depth stencil buffer");; } //now setup depth stencil to allow control of what type of depth test is done for each pixel ZeroMemory(&depthStencilDesc, sizeof(depthStencilDesc)); depthStencilDesc.DepthEnable = true; depthStencilDesc.DepthWriteMask = D3D11_DEPTH_WRITE_MASK_ALL; depthStencilDesc.DepthFunc = D3D11_COMPARISON_LESS; depthStencilDesc.StencilEnable = true; depthStencilDesc.StencilReadMask = 0xFF; depthStencilDesc.StencilWriteMask = 0xFF; //for front-facing pixels 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; //for back facing pixels 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_lastError = m_device->CreateDepthStencilState(&depthStencilDesc, &m_backBufferDepthState); if(FAILED(m_lastError)) { throw Kiwi::Exception(L"D3D11Interface::Initialize", L"Failed to create back buffer depth stencil state");; } //set the depth stencil state m_deviceContext->OMSetDepthStencilState(m_backBufferDepthState, 1); //setup the depth stencil buffer so DX will use the buffer as a depth stencil texture ZeroMemory(&dsViewDesc, sizeof(dsViewDesc)); dsViewDesc.Format = DXGI_FORMAT_D24_UNORM_S8_UINT; dsViewDesc.ViewDimension = D3D11_DSV_DIMENSION_TEXTURE2D; dsViewDesc.Texture2D.MipSlice = 0; m_lastError = m_device->CreateDepthStencilView(m_backBufferDepthBuffer, &dsViewDesc, &m_backBufferDepthView); if(FAILED(m_lastError)) { throw Kiwi::Exception(L"D3D11Interface::Initialize", L"Failed to create back buffer depth stencil view");; } //now bind the render target view and depth stencil buffer to the render pipeline m_deviceContext->OMSetRenderTargets(1, &m_backBufferRenderTargetView, m_backBufferDepthView); //by default, set the primitive type to triangle list m_deviceContext->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST); m_fullscreen = fullscreen; m_vSyncEnabled = vsyncEnabled; }
bool D3D10App::initAPI(const DXGI_FORMAT backBufferFmt, const DXGI_FORMAT depthBufferFmt, const int samples, const uint flags){ backBufferFormat = backBufferFmt; depthBufferFormat = depthBufferFmt; msaaSamples = samples; // if (screen >= GetSystemMetrics(SM_CMONITORS)) screen = 0; IDXGIFactory *dxgiFactory; if (FAILED(CreateDXGIFactory(__uuidof(IDXGIFactory), (void **) &dxgiFactory))){ ErrorMsg("Couldn't create DXGIFactory"); return false; } IDXGIAdapter *dxgiAdapter; if (dxgiFactory->EnumAdapters(0, &dxgiAdapter) == DXGI_ERROR_NOT_FOUND){ ErrorMsg("No adapters found"); return false; } // DXGI_ADAPTER_DESC adapterDesc; // dxgiAdapter->GetDesc(&adapterDesc); IDXGIOutput *dxgiOutput; if (dxgiAdapter->EnumOutputs(0, &dxgiOutput) == DXGI_ERROR_NOT_FOUND){ ErrorMsg("No outputs found"); return false; } DXGI_OUTPUT_DESC oDesc; dxgiOutput->GetDesc(&oDesc); // Find a suitable fullscreen format int targetHz = 85; DXGI_RATIONAL fullScreenRefresh; int fsRefresh = 60; fullScreenRefresh.Numerator = fsRefresh; fullScreenRefresh.Denominator = 1; char str[128]; uint nModes = 0; dxgiOutput->GetDisplayModeList(backBufferFormat, 0, &nModes, NULL); DXGI_MODE_DESC *modes = new DXGI_MODE_DESC[nModes]; dxgiOutput->GetDisplayModeList(backBufferFormat, 0, &nModes, modes); resolution->clear(); for (uint i = 0; i < nModes; i++){ if (modes[i].Width >= 640 && modes[i].Height >= 480){ sprintf(str, "%dx%d", modes[i].Width, modes[i].Height); int index = resolution->addItemUnique(str); if (int(modes[i].Width) == fullscreenWidth && int(modes[i].Height) == fullscreenHeight){ int refresh = modes[i].RefreshRate.Numerator / modes[i].RefreshRate.Denominator; if (abs(refresh - targetHz) < abs(fsRefresh - targetHz)){ fsRefresh = refresh; fullScreenRefresh = modes[i].RefreshRate; } resolution->selectItem(index); } } } delete modes; sprintf(str, "%s (%dx%d)", getTitle(), width, height); DWORD wndFlags = 0; int x, y, w, h; if (fullscreen){ wndFlags |= WS_POPUP; x = y = 0; w = width; h = height; } else { wndFlags |= WS_OVERLAPPEDWINDOW; RECT wRect; wRect.left = 0; wRect.right = width; wRect.top = 0; wRect.bottom = height; AdjustWindowRect(&wRect, wndFlags, FALSE); MONITORINFO monInfo; monInfo.cbSize = sizeof(monInfo); GetMonitorInfo(oDesc.Monitor, &monInfo); w = min(wRect.right - wRect.left, monInfo.rcWork.right - monInfo.rcWork.left); h = min(wRect.bottom - wRect.top, monInfo.rcWork.bottom - monInfo.rcWork.top); x = (monInfo.rcWork.left + monInfo.rcWork.right - w) / 2; y = (monInfo.rcWork.top + monInfo.rcWork.bottom - h) / 2; } hwnd = CreateWindow("Humus", str, wndFlags, x, y, w, h, HWND_DESKTOP, NULL, hInstance, NULL); RECT rect; GetClientRect(hwnd, &rect); // Create device and swap chain DXGI_SWAP_CHAIN_DESC sd; memset(&sd, 0, sizeof(sd)); sd.BufferDesc.Width = rect.right; sd.BufferDesc.Height = rect.bottom; sd.BufferDesc.Format = backBufferFormat; sd.BufferDesc.RefreshRate = fullScreenRefresh; sd.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT; sd.BufferCount = 1; sd.OutputWindow = hwnd; sd.Windowed = (BOOL) (!fullscreen); sd.SwapEffect = DXGI_SWAP_EFFECT_DISCARD; sd.Flags = DXGI_SWAP_CHAIN_FLAG_ALLOW_MODE_SWITCH; DWORD deviceFlags = D3D10_CREATE_DEVICE_SINGLETHREADED; #ifdef _DEBUG deviceFlags |= D3D10_CREATE_DEVICE_DEBUG; #endif if (FAILED(D3D10CreateDevice(dxgiAdapter, D3D10_DRIVER_TYPE_HARDWARE, NULL, deviceFlags, D3D10_SDK_VERSION, &device))){ ErrorMsg("Couldn't create D3D10 device"); return false; } while (msaaSamples > 0){ UINT nQuality; if (SUCCEEDED(device->CheckMultisampleQualityLevels(backBufferFormat, msaaSamples, &nQuality)) && nQuality > 0){ if ((flags & NO_SETTING_CHANGE) == 0) antiAliasSamples = msaaSamples; break; } else { msaaSamples -= 2; } } sd.SampleDesc.Count = msaaSamples; sd.SampleDesc.Quality = 0; if (FAILED(dxgiFactory->CreateSwapChain(device, &sd, &swapChain))){ ErrorMsg("Couldn't create swapchain"); return false; } // We'll handle Alt-Enter ourselves thank you very much ... dxgiFactory->MakeWindowAssociation(hwnd, DXGI_MWA_NO_WINDOW_CHANGES | DXGI_MWA_NO_ALT_ENTER); dxgiOutput->Release(); dxgiAdapter->Release(); dxgiFactory->Release(); if (!createBuffers()) return false; if (fullscreen){ captureMouse(!configDialog->isVisible()); } renderer = new Direct3D10Renderer(device); ((Direct3D10Renderer *) renderer)->setFrameBuffer(backBufferRTV, depthBufferDSV); antiAlias->selectItem(antiAliasSamples / 2); linearClamp = renderer->addSamplerState(LINEAR, CLAMP, CLAMP, CLAMP); defaultFont = renderer->addFont("../Textures/Fonts/Future.dds", "../Textures/Fonts/Future.font", linearClamp); blendSrcAlpha = renderer->addBlendState(SRC_ALPHA, ONE_MINUS_SRC_ALPHA); noDepthTest = renderer->addDepthState(false, false); noDepthWrite = renderer->addDepthState(true, false); cullNone = renderer->addRasterizerState(CULL_NONE); cullBack = renderer->addRasterizerState(CULL_BACK); cullFront = renderer->addRasterizerState(CULL_FRONT); return true; }
bool D3DManager::Initialize(int screenWidth, int screenHeight, bool vsync, HWND hwnd, bool fullScreen) { HRESULT result; IDXGIFactory * factory = nullptr; IDXGIAdapter * adapter = nullptr; IDXGIOutput * adapterOutput = nullptr; unsigned int numModes; unsigned int numerator = 0; unsigned int denominator = 0; unsigned int stringLenht; DXGI_MODE_DESC * displayModeList = nullptr; DXGI_ADAPTER_DESC adapterDesc; int error; ID3D11Texture2D * backBuffer = nullptr; // Guardo el vsycn m_vsync_enable = vsync; // Creo una interfas con DirectX (IDXGIFactory) result = CreateDXGIFactory(__uuidof(IDXGIFactory), (void**)&factory); if (FAILED(result)) { // TODO: Informar del Error return false; } // Uso el IDXGIFactory para crear un adapatador(Placa de Video) result = factory->EnumAdapters(0, &adapter); if (FAILED(result)) { // TODO: Informar del Error return false; } // Enumero la cantidad de monitores (Adaptador de salida) result = adapter->EnumOutputs(0, &adapterOutput); if (FAILED(result)) { // TODO: Informar del Error return false; } // Obtengo el numero de modos que se ajustan al formato DXGI_FORMAT_R8G8B8A8 para el monitor result = adapterOutput->GetDisplayModeList(DXGI_FORMAT_R8G8B8A8_UNORM, DXGI_ENUM_MODES_INTERLACED, &numModes, NULL); if (FAILED(result)) { // TODO: Informar del Error return false; } // Creo una lista con todos los posbles modos para esta combinacion placa de video monitor. displayModeList = new DXGI_MODE_DESC[numModes]; // Cargo la lista de display Mode result = adapterOutput->GetDisplayModeList(DXGI_FORMAT_R8G8B8A8_UNORM, DXGI_ENUM_MODES_INTERLACED, &numModes, displayModeList); if (FAILED(result)) { // TODO: Informar del Error return false; } for (int i = 0; i < (int)numModes; ++i) { if (displayModeList[i].Width == (unsigned int)screenWidth && displayModeList[i].Height == (unsigned int)screenHeight) { numerator = displayModeList[i].RefreshRate.Numerator; denominator = displayModeList[i].RefreshRate.Denominator; //TODO: Loquidar el for al encontrar el valor correcto } } if (numerator == 0 && denominator == 0) { // Informar Error return false; } // Obtengo la descripcion del adaptador result = adapter->GetDesc(&adapterDesc); if (FAILED(result)) { // TODO: Informar del Error return false; } // Guardo la cantidad de memorya de video m_videoCardMemory = adapterDesc.DedicatedVideoMemory; // Convierto el nombre de la VGA a string char tmp_string[128]; error = wcstombs_s(&stringLenht, tmp_string, 128, adapterDesc.Description, 128); if (error != 0) { // TODO: Informar del Error return false; } m_videoCardDescription = tmp_string; // Released Memory delete [] displayModeList; displayModeList = nullptr; adapterOutput->Release(); adapterOutput = nullptr; adapter->Release(); adapter = nullptr; factory->Release(); factory = nullptr; if (!InitializeSwapChain(hwnd, fullScreen, screenWidth, screenHeight, numerator, denominator)) { // Todo: Informar El Error return false; } // Obtengo el puntero al BackBuffer result = mp_swapChain->GetBuffer(0, __uuidof(ID3D11Texture2D), (LPVOID*)&backBuffer); if (FAILED(result)) { // TODO: Informar del Error return false; } // Creo el render Target View result = mp_device->CreateRenderTargetView(backBuffer, NULL, &mp_renderTargetView); if (FAILED(result)) { // TODO: Informar del Error return false; } // No te Nesesito MUERE backBuffer->Release(); backBuffer = nullptr; if (!InitializeDepthBuffer(screenWidth, screenHeight)) { // TODO: Informar del Error return false; } if (!InitializeDepthStencilBuffer()) { // TODO: Informar del Error return false; } if (!InitializeStencilView()) { // TODO: Informar del Error return false; } mp_deviceContext->OMSetRenderTargets(1, &mp_renderTargetView, mp_depthStencilView); if (!InitializeRasterizerStete()) { // TODO: Informar del Error return false; } InitializeViewport(screenWidth, screenHeight); if (!InitializeAlphaBlending()) { // TODO: Informar del Error return false; } if (!InitializeZBuffer()) { // TODO: Informar del Error return false; } return true; }
void D3D11::init( int screenWidth, int screenHeight, bool vsync, HWND hwnd, bool fullscreen, float screenDepth, float screenNear ) { m_vsyncEnabled = vsync; m_isWindows = fullscreen; IDXGIFactory * pfactory; if(FAILED(CreateDXGIFactory(__uuidof(IDXGIFactory),(void**)&pfactory))) return; IDXGIAdapter * pAdapter; if(FAILED(pfactory->EnumAdapters(0,&pAdapter))) return; IDXGIOutput * out; if(FAILED(pAdapter->EnumOutputs(0,&out))) return; int numModes; DXGI_MODE_DESC * displaymodeList; if(FAILED(out->GetDisplayModeList(DXGI_FORMAT_R8G8B8A8_UNORM,DXGI_ENUM_MODES_INTERLACED,&numModes,NULL))) return; displaymodeList = new DXGI_MODE_DESC[numModes]; if(FAILED(out->GetDisplayModeList(DXGI_FORMAT_R8G8B8A8_UNORM,DXGI_ENUM_MODES_INTERLACED,&numModes,displaymodeList))) return; int numerator,denomerator; for(int i = 0; i < numModes; ++i) { if(displaymodeList[i].Height == screenHeight && displaymodeList[i].Width == screenWidth) { numerator = displaymodeList[i].RefreshRate.Numerator; denomerator = displaymodeList[i].RefreshRate.Denominator; } } DXGI_ADAPTER_DESC desc; if(FAILED(pAdapter->GetDesc(&desc))) return; int length; m_videoCardMemory = static_cast<int>(desc.DedicatedVideoMemory/1024/1024); wcstombs_s(&length,m_videoCardDescription,128,desc.Description,128); delete[] displaymodeList; displaymodeList = NULL; out->Release(); out = NULL; pAdapter->Release(); pAdapter = NULL; pfactory->Release(); pfactory = NULL; DXGI_SWAP_CHAIN_DESC swapChainDesc; ZeroMemory(&swapChainDesc,sizeof(DXGI_SWAP_CHAIN_DESC)); swapChainDesc.BufferCount = 1; swapChainDesc.BufferDesc.Width = screenWidth; swapChainDesc.BufferDesc.Height = screenHeight; swapChainDesc.BufferDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM; if(m_vsyncEnabled) { swapChainDesc.BufferDesc.RefreshRate.Numerator = numerator; swapChainDesc.BufferDesc.RefreshRate.Denominator = denomerator; } else { swapChainDesc.BufferDesc.RefreshRate.Denominator = 1; swapChainDesc.BufferDesc.RefreshRate.Numerator = 0; } swapChainDesc.Windowed = m_isWindows; swapChainDesc.BufferDesc.ScanlineOrdering = DXGI_MODE_SCANLINE_ORDER_UNSPECIFIED; swapChainDesc.BufferDesc.Scaling = DXGI_MODE_SCALING_UNSPECIFIED; swapChainDesc.SwapEffect = DXGI_SWAP_EFFECT_DISCARD; D3D_FEATURE_LEVEL level = D3D_FEATURE_LEVEL_11_0; if(FAILED(D3D11CreateDeviceAndSwapChain(NULL,D3D_DRIVER_TYPE_HARDWARE,NULL,0, &level,1,D3D11_SDK_VERSION,&swapChainDesc,&m_swapChain,&m_device,NULL,&m_deviceContext))) return; ID3D11Texture2D *backbufferTex; if(FAILED(m_swapChain->GetBuffer(0,__uuidof(ID3D11Texture2D),(LPVOID*)&backbufferTex))) return; if(FAILED(m_device->CreateRenderTargetView(backbufferTex,NULL,&m_renderView))) return; backbufferTex->Release(); backbufferTex = 0; D3D11_TEXTURE2D_DESC depthBufferDesc; ZeroMemory(&depthBufferDesc, sizeof(depthBufferDesc)); 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; if(FAILED(m_device->CreateTexture2D(&depthBufferDesc, NULL, &m_depthStencilBuffer))) return ; D3D11_DEPTH_STENCIL_DESC depthStencilDesc; // 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. if(FAILED(m_device->CreateDepthStencilState(&depthStencilDesc, &m_depthStencilState))) return; // Set the depth stencil state. m_deviceContext->OMSetDepthStencilState(m_depthStencilState, 1); D3D11_DEPTH_STENCIL_VIEW_DESC depthStencilViewDesc; // Initialize 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; // Create the depth stencil view. if(FAILED(m_device->CreateDepthStencilView(m_depthStencilBuffer, &depthStencilViewDesc, &m_depthStencilView))) return ; // Bind the render target view and depth stencil buffer to the output render pipeline. m_deviceContext->OMSetRenderTargets(1, &m_renderView, m_depthStencilView); D3D11_RASTERIZER_DESC rasterDesc; // 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. if(FAILED(m_device->CreateRasterizerState(&rasterDesc, &m_rasterState))) return ; // Now set the rasterizer state. m_deviceContext->RSSetState(m_rasterState); D3D11_VIEWPORT viewport; // 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. m_deviceContext->RSSetViewports(1, &viewport); float fieldOfView, screenAspect; // Setup the projection matrix. fieldOfView = (float)D3DX_PI / 4.0f; screenAspect = (float)screenWidth / (float)screenHeight; // Create the projection matrix for 3D rendering. D3DXMatrixPerspectiveFovLH(&m_projMat, fieldOfView, screenAspect, screenNear, screenDepth); // Initialize the world matrix to the identity matrix. D3DXMatrixIdentity(&m_worldMat); // Create an orthographic projection matrix for 2D rendering. D3DXMatrixOrthoLH(&m_orthoMat, (float)screenWidth, (float)screenHeight, screenNear, screenDepth); }
bool CD3D11Driver::init(SCreationParameters& createParam) { HRESULT result; IDXGIFactory* factory; IDXGIAdapter* adapter; IDXGIOutput* adapterOutput; unsigned int numModes, i, numerator = 0, denominator = 1, stringLength; DXGI_MODE_DESC* displayModeList; DXGI_ADAPTER_DESC adapterDesc; int error; D3D11_TEXTURE2D_DESC depthBufferDesc; //D3D11_DEPTH_STENCIL_DESC depthStencilDesc; //D3D11_DEPTH_STENCIL_VIEW_DESC depthStencilViewDesc; //D3D11_RASTERIZER_DESC rasterDesc; //D3D11_VIEWPORT viewport; //const SCreationParameters& params = mDevice->getCreationParameters(); // Create a DirectX graphics interface factory. mBackBufferWidth = createParam.BackBufferWidth; mBackBufferHeight = createParam.BackBufferHeight; result = CreateDXGIFactory(__uuidof(IDXGIFactory), (void**)&factory); if (FAILED(result)) { return false; } // Use the factory to create an adapter 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 fit 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 display 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)createParam.BackBufferWidth) { if (displayModeList[i].Height == (unsigned int)createParam.BackBufferHeight) { 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 megabytes. mVideoCardMemory = (int)(adapterDesc.DedicatedVideoMemory / 1024 / 1024); // Convert the name of the video card to a character array and store it. error = wcstombs_s(&stringLength, mVideoCardDescription, 128, adapterDesc.Description, 128); if (error != 0) { return false; } // Release the display mode list. delete[] displayModeList; displayModeList = 0; // Release the adapter output. adapterOutput->Release(); adapterOutput = 0; // Release the adapter. adapter->Release(); adapter = 0; // Release the factory. factory->Release(); factory = 0; UINT createDeviceFlags = 0; #if defined(DEBUG) || defined(_DEBUG) createDeviceFlags |= D3D11_CREATE_DEVICE_DEBUG; #endif D3D_FEATURE_LEVEL featureLevel; /* 如果将这个标志设为DEBUG,则绘制效率大大降低,且帧频极不稳定 */ //createDeviceFlags = 0; HRESULT hr; hr = D3D11CreateDevice(NULL, D3D_DRIVER_TYPE_HARDWARE, NULL, createDeviceFlags, 0, 0, D3D11_SDK_VERSION, &md3dDevice, &featureLevel, &md3dDeviceContext); if (FAILED(hr)) return false; #if defined(DEBUG) || defined(_DEBUG) md3dDevice->QueryInterface(__uuidof(ID3D11Debug), reinterpret_cast<void**>(&md3dDebug)); #endif if (featureLevel != D3D_FEATURE_LEVEL_11_0) { throw std::runtime_error("DirectX11 is not supported!"); return false; } UINT numQualityLevels; md3dDevice->CheckMultisampleQualityLevels(DXGI_FORMAT_R8G8B8A8_UNORM, 4, &numQualityLevels); IDXGIDevice* dxgiDevice = 0; md3dDevice->QueryInterface(__uuidof(IDXGIDevice), (void**)&dxgiDevice); IDXGIAdapter* dxgiAdapter = 0; dxgiDevice->GetParent(__uuidof(IDXGIAdapter), (void**)&dxgiAdapter); IDXGIFactory* dxgiFactory = 0; dxgiAdapter->GetParent(__uuidof(IDXGIFactory), (void**)&dxgiFactory); DXGI_SWAP_CHAIN_DESC swapChainDesc; // Initialize the swap chain description. ZeroMemory(&swapChainDesc, sizeof(swapChainDesc)); // Set the width and height of the back buffer. swapChainDesc.BufferDesc.Width = createParam.BackBufferWidth; swapChainDesc.BufferDesc.Height = createParam.BackBufferHeight; // 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 (createParam.VsyncEnabled) { swapChainDesc.BufferDesc.RefreshRate.Numerator = numerator; swapChainDesc.BufferDesc.RefreshRate.Denominator = denominator; } else { swapChainDesc.BufferDesc.RefreshRate.Numerator = 0; swapChainDesc.BufferDesc.RefreshRate.Denominator = 1; } // Set multisampling. if (createParam.MultiSamplingQuality == 0) { swapChainDesc.SampleDesc.Count = 1; swapChainDesc.SampleDesc.Quality = 0; createParam.MultiSamplingCount = 1; } else { swapChainDesc.SampleDesc.Count = createParam.MultiSamplingCount; UINT numQualityLevels; md3dDevice->CheckMultisampleQualityLevels(DXGI_FORMAT_R8G8B8A8_UNORM, 4, &numQualityLevels); swapChainDesc.SampleDesc.Quality = min(numQualityLevels - 1, createParam.MultiSamplingQuality); createParam.MultiSamplingQuality = swapChainDesc.SampleDesc.Quality; } // set member attributes of class // Set to a single back buffer. swapChainDesc.BufferCount = 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)createParam.BackBufferWindowHandle; // Set to full screen or windowed mode. if (createParam.WindowStyle & EWS_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 presenting. swapChainDesc.SwapEffect = DXGI_SWAP_EFFECT_DISCARD; // Don't set the advanced flags. swapChainDesc.Flags = 0; hr = dxgiFactory->CreateSwapChain(md3dDevice, &swapChainDesc, &md3dSwapChain); if (FAILED(hr)) return false; ReleaseCOM(dxgiDevice); ReleaseCOM(dxgiAdapter); ReleaseCOM(dxgiFactory); // Get the pointer to the back buffer. ID3D11Texture2D* backBuffer; result = md3dSwapChain->GetBuffer(0, __uuidof(ID3D11Texture2D), (LPVOID*)&backBuffer); if (FAILED(result)) { return false; } md3dDevice->CreateRenderTargetView(backBuffer, 0, &mDefaultRenderTargetView); ReleaseCOM(backBuffer); mDefaultRenderTarget = new CD3D11RenderTarget(md3dDevice, md3dDeviceContext, mDefaultRenderTargetView, createParam.BackBufferWidth, createParam.BackBufferHeight); // Initialize the description of the depth buffer. ZeroMemory(&depthBufferDesc, sizeof(depthBufferDesc)); // Setup the viewport for rendering. setViewport(0, 0, static_cast<f32>(mBackBufferWidth), static_cast<f32>(mBackBufferHeight)); //create resource factory mResourceFactory = new CD3D11ResourceFactory( md3dDevice, md3dDeviceContext, this); IResourceFactory::_setInstance(mResourceFactory); //create geometry creator mGeometryCreator = new CGeometryCreator; IGeometryCreator::_setInstance(mGeometryCreator); //create material manager mMaterialManager = new CMaterialManager; IMaterialManager::_setInstance(mMaterialManager); //create sampler manager mSamplerManager = new CSamplerManager(mResourceFactory); ISamplerManager::_setInstance(mSamplerManager); // create shadermanager mShaderManager = new CShaderManager(mResourceFactory); IShaderManager::_setInstance(mShaderManager); // create inputlayout manager mInputLayoutManager = new CInputLayoutManager(mResourceFactory); IInputLayoutManager::_setInstance(mInputLayoutManager); //create texture manager mTextureManager = new CTextureManager(mDevice, mResourceFactory); ITextureManager::_setInstance(mTextureManager); //create render state manager mRenderStateManager = new CRenderStateManager(mResourceFactory); IRenderStateManager::_setInstance(mRenderStateManager); //create mesh manager mMeshManager = new CMeshManager(mResourceFactory, mGeometryCreator, mTextureManager); IMeshManager::_setInstance(mMeshManager); //create pipeline manager mPipeManager = new CPipelineManager(mResourceFactory); IPipelineManager::_setInstance(mPipeManager); //create resource group manager mResourceGroupManager = new CResourceGroupManager(mTextureManager, mShaderManager, mInputLayoutManager, mRenderStateManager, mPipeManager, mMaterialManager, mMeshManager, mSamplerManager); IResourceGroupManager::_setInstance(mResourceGroupManager); //mResourceFactory->setResourceGroupManager(mResourceGroupManager); // create default depth-stencil-buffer bool multiSampling = (createParam.MultiSamplingCount > 1); mDepthStencilSurface = mTextureManager->createDepthStencilSurface("_default_depth_stencil_surface", 0, 0, createParam.DepthBits, createParam.StencilBits, multiSampling, createParam.MultiSamplingCount, createParam.MultiSamplingQuality, true); if (!mDepthStencilSurface) { GF_PRINT_CONSOLE_INFO("Depth Stencil Surface has failed to be created.\n"); return false; } D3D11DriverState.DepthStencilSurface = mDepthStencilSurface; CD3D11DepthStencilSurface* d3dDepthStencilSurface = dynamic_cast<CD3D11DepthStencilSurface*>(mDepthStencilSurface); mDefaultDepthStencilView = d3dDepthStencilSurface->getDepthStencilView(); D3D11DriverState.DepthStencilView = mDefaultDepthStencilView; // create mShadowMapRasterizeState. This state is only for rendering shadow maps. D3D11_RASTERIZER_DESC shadowRasterizeState; shadowRasterizeState.FillMode = D3D11_FILL_SOLID; shadowRasterizeState.CullMode = D3D11_CULL_BACK; // RENDER BACK FACE shadowRasterizeState.FrontCounterClockwise = TRUE; shadowRasterizeState.DepthBiasClamp = 0.0f; //shadowRasterizeState.DepthBias = 100000; //shadowRasterizeState.SlopeScaledDepthBias = 1.0f; shadowRasterizeState.DepthBias = 0; shadowRasterizeState.SlopeScaledDepthBias = 0; shadowRasterizeState.DepthClipEnable = TRUE; shadowRasterizeState.ScissorEnable = FALSE; shadowRasterizeState.MultisampleEnable = FALSE; shadowRasterizeState.AntialiasedLineEnable = FALSE; hr = md3dDevice->CreateRasterizerState(&shadowRasterizeState, &mShadowMapRasterizeState); if (FAILED(hr)) return false; D3D11DriverState.ShadowMapRasterizerState = mShadowMapRasterizeState; return true; }
SettingsDialog::SettingsDialog(wxWindow *parent, rpcs3::config_t* cfg) : wxDialog(parent, wxID_ANY, "Settings", wxDefaultPosition) { const bool was_running = Emu.Pause(); if (was_running || Emu.IsReady()) cfg = &rpcs3::state.config; static const u32 width = 458; static const u32 height = 400; // Settings panels wxNotebook* nb_config = new wxNotebook(this, wxID_ANY, wxPoint(6, 6), wxSize(width, height)); wxPanel* p_system = new wxPanel(nb_config, wxID_ANY); wxPanel* p_core = new wxPanel(nb_config, wxID_ANY); wxPanel* p_graphics = new wxPanel(nb_config, wxID_ANY); wxPanel* p_audio = new wxPanel(nb_config, wxID_ANY); wxPanel* p_io = new wxPanel(nb_config, wxID_ANY); wxPanel* p_misc = new wxPanel(nb_config, wxID_ANY); wxPanel* p_networking = new wxPanel(nb_config, wxID_ANY); nb_config->AddPage(p_core, wxT("Core")); nb_config->AddPage(p_graphics, wxT("Graphics")); nb_config->AddPage(p_audio, wxT("Audio")); nb_config->AddPage(p_io, wxT("Input / Output")); nb_config->AddPage(p_misc, wxT("Miscellaneous")); nb_config->AddPage(p_networking, wxT("Networking")); nb_config->AddPage(p_system, wxT("System")); wxBoxSizer* s_subpanel_core = new wxBoxSizer(wxHORIZONTAL); wxBoxSizer* s_subpanel_core1 = new wxBoxSizer(wxVERTICAL); wxBoxSizer* s_subpanel_core2 = new wxBoxSizer(wxVERTICAL); wxBoxSizer* s_subpanel_graphics = new wxBoxSizer(wxHORIZONTAL); wxBoxSizer* s_subpanel_graphics1 = new wxBoxSizer(wxVERTICAL); wxBoxSizer* s_subpanel_graphics2 = new wxBoxSizer(wxVERTICAL); wxBoxSizer* s_subpanel_audio = new wxBoxSizer(wxVERTICAL); wxBoxSizer* s_subpanel_io = new wxBoxSizer(wxHORIZONTAL); wxBoxSizer* s_subpanel_io1 = new wxBoxSizer(wxVERTICAL); wxBoxSizer* s_subpanel_io2 = new wxBoxSizer(wxVERTICAL); wxBoxSizer* s_subpanel_system = new wxBoxSizer(wxVERTICAL); wxBoxSizer* s_subpanel_misc = new wxBoxSizer(wxVERTICAL); wxBoxSizer* s_subpanel_networking = new wxBoxSizer(wxVERTICAL); // Core settings wxStaticBoxSizer* s_round_llvm = new wxStaticBoxSizer(wxVERTICAL, p_core, _("LLVM config")); wxStaticBoxSizer* s_round_llvm_range = new wxStaticBoxSizer(wxHORIZONTAL, p_core, _("Excluded block range")); wxStaticBoxSizer* s_round_llvm_threshold = new wxStaticBoxSizer(wxHORIZONTAL, p_core, _("Compilation threshold")); // Graphics wxStaticBoxSizer* s_round_gs_render = new wxStaticBoxSizer(wxVERTICAL, p_graphics, _("Rendering API")); wxStaticBoxSizer* s_round_gs_d3d_adaptater = new wxStaticBoxSizer(wxVERTICAL, p_graphics, _("D3D Adapter")); wxStaticBoxSizer* s_round_gs_res = new wxStaticBoxSizer(wxVERTICAL, p_graphics, _("Resolution")); wxStaticBoxSizer* s_round_gs_aspect = new wxStaticBoxSizer(wxVERTICAL, p_graphics, _("Aspect ratio")); wxStaticBoxSizer* s_round_gs_frame_limit = new wxStaticBoxSizer(wxVERTICAL, p_graphics, _("Frame limit")); // Input / Output wxStaticBoxSizer* s_round_io_pad_handler = new wxStaticBoxSizer(wxVERTICAL, p_io, _("Controller handler")); wxStaticBoxSizer* s_round_io_keyboard_handler = new wxStaticBoxSizer(wxVERTICAL, p_io, _("Keyboard handler")); wxStaticBoxSizer* s_round_io_mouse_handler = new wxStaticBoxSizer(wxVERTICAL, p_io, _("Mouse handler")); wxStaticBoxSizer* s_round_io_camera = new wxStaticBoxSizer(wxVERTICAL, p_io, _("Camera")); wxStaticBoxSizer* s_round_io_camera_type = new wxStaticBoxSizer(wxVERTICAL, p_io, _("Camera type")); // Audio wxStaticBoxSizer* s_round_audio_out = new wxStaticBoxSizer(wxVERTICAL, p_audio, _("Audio out")); // Miscellaneous wxStaticBoxSizer* s_round_hle_log_lvl = new wxStaticBoxSizer(wxVERTICAL, p_misc, _("Log level")); // Networking wxStaticBoxSizer* s_round_net_status = new wxStaticBoxSizer(wxVERTICAL, p_networking, _("Connection status")); wxStaticBoxSizer* s_round_net_interface = new wxStaticBoxSizer(wxVERTICAL, p_networking, _("Network adapter")); // System wxStaticBoxSizer* s_round_sys_lang = new wxStaticBoxSizer(wxVERTICAL, p_system, _("Language")); wxRadioBox* rbox_ppu_decoder; wxRadioBox* rbox_spu_decoder; wxComboBox* cbox_gs_render = new wxComboBox(p_graphics, wxID_ANY, wxEmptyString, wxDefaultPosition, wxSize(150, -1), 0, NULL, wxCB_READONLY); wxComboBox* cbox_gs_d3d_adaptater = new wxComboBox(p_graphics, wxID_ANY, wxEmptyString, wxDefaultPosition, wxSize(150, -1), 0, NULL, wxCB_READONLY); wxComboBox* cbox_gs_resolution = new wxComboBox(p_graphics, wxID_ANY, wxEmptyString, wxDefaultPosition, wxSize(150, -1), 0, NULL, wxCB_READONLY); wxComboBox* cbox_gs_aspect = new wxComboBox(p_graphics, wxID_ANY, wxEmptyString, wxDefaultPosition, wxSize(150, -1), 0, NULL, wxCB_READONLY); wxComboBox* cbox_gs_frame_limit = new wxComboBox(p_graphics, wxID_ANY, wxEmptyString, wxDefaultPosition, wxSize(150, -1), 0, NULL, wxCB_READONLY); wxComboBox* cbox_pad_handler = new wxComboBox(p_io, wxID_ANY, wxEmptyString, wxDefaultPosition, wxSize(150, -1), 0, NULL, wxCB_READONLY);; wxComboBox* cbox_keyboard_handler = new wxComboBox(p_io, wxID_ANY, wxEmptyString, wxDefaultPosition, wxSize(150, -1), 0, NULL, wxCB_READONLY); wxComboBox* cbox_mouse_handler = new wxComboBox(p_io, wxID_ANY, wxEmptyString, wxDefaultPosition, wxSize(150, -1), 0, NULL, wxCB_READONLY); wxComboBox* cbox_camera = new wxComboBox(p_io, wxID_ANY, wxEmptyString, wxDefaultPosition, wxSize(150, -1), 0, NULL, wxCB_READONLY); wxComboBox* cbox_camera_type = new wxComboBox(p_io, wxID_ANY, wxEmptyString, wxDefaultPosition, wxSize(150, -1), 0, NULL, wxCB_READONLY); wxComboBox* cbox_audio_out = new wxComboBox(p_audio, wxID_ANY, wxEmptyString, wxDefaultPosition, wxSize(150, -1), 0, NULL, wxCB_READONLY); wxComboBox* cbox_hle_loglvl = new wxComboBox(p_misc, wxID_ANY, wxEmptyString, wxDefaultPosition, wxSize(150, -1), 0, NULL, wxCB_READONLY); wxComboBox* cbox_net_status = new wxComboBox(p_networking, wxID_ANY, wxEmptyString, wxDefaultPosition, wxDefaultSize, 0, NULL, wxCB_READONLY); wxComboBox* cbox_net_interface = new wxComboBox(p_networking, wxID_ANY, wxEmptyString, wxDefaultPosition, wxDefaultSize, 0, NULL, wxCB_READONLY); wxComboBox* cbox_sys_lang = new wxComboBox(p_system, wxID_ANY, wxEmptyString, wxDefaultPosition, wxDefaultSize, 0, NULL, wxCB_READONLY); wxCheckBox* chbox_core_llvm_exclud = new wxCheckBox(p_core, wxID_ANY, "Compiled blocks exclusion"); wxCheckBox* chbox_core_hook_stfunc = new wxCheckBox(p_core, wxID_ANY, "Hook static functions"); wxCheckBox* chbox_core_load_liblv2 = new wxCheckBox(p_core, wxID_ANY, "Load liblv2.sprx"); wxCheckBox* chbox_gs_log_prog = new wxCheckBox(p_graphics, wxID_ANY, "Log shader programs"); wxCheckBox* chbox_gs_dump_depth = new wxCheckBox(p_graphics, wxID_ANY, "Write depth buffer"); wxCheckBox* chbox_gs_dump_color = new wxCheckBox(p_graphics, wxID_ANY, "Write color buffers"); wxCheckBox* chbox_gs_read_color = new wxCheckBox(p_graphics, wxID_ANY, "Read color buffers"); wxCheckBox* chbox_gs_read_depth = new wxCheckBox(p_graphics, wxID_ANY, "Read depth buffer"); wxCheckBox* chbox_gs_vsync = new wxCheckBox(p_graphics, wxID_ANY, "VSync"); wxCheckBox* chbox_gs_debug_output = new wxCheckBox(p_graphics, wxID_ANY, "Debug output"); wxCheckBox* chbox_gs_3dmonitor = new wxCheckBox(p_graphics, wxID_ANY, "3D monitor"); wxCheckBox* chbox_gs_overlay = new wxCheckBox(p_graphics, wxID_ANY, "Debug overlay"); wxCheckBox* chbox_audio_dump = new wxCheckBox(p_audio, wxID_ANY, "Dump to file"); wxCheckBox* chbox_audio_conv = new wxCheckBox(p_audio, wxID_ANY, "Convert to 16-bit"); wxCheckBox* chbox_rsx_logging = new wxCheckBox(p_misc, wxID_ANY, "RSX logging"); wxCheckBox* chbox_hle_exitonstop = new wxCheckBox(p_misc, wxID_ANY, "Exit RPCS3 when process finishes"); wxCheckBox* chbox_hle_always_start = new wxCheckBox(p_misc, wxID_ANY, "Always start after boot"); wxCheckBox* chbox_hle_use_default_ini = new wxCheckBox(p_misc, wxID_ANY, "Use default configuration"); wxTextCtrl* txt_dbg_range_min = new wxTextCtrl(p_core, wxID_ANY, wxEmptyString, wxDefaultPosition, wxSize(55, 20)); wxTextCtrl* txt_dbg_range_max = new wxTextCtrl(p_core, wxID_ANY, wxEmptyString, wxDefaultPosition, wxSize(55, 20)); wxTextCtrl* txt_llvm_threshold = new wxTextCtrl(p_core, wxID_ANY, wxEmptyString, wxDefaultPosition, wxSize(55, 20)); //Auto Pause wxCheckBox* chbox_dbg_ap_systemcall = new wxCheckBox(p_misc, wxID_ANY, "Automatically pause at system call"); wxCheckBox* chbox_dbg_ap_functioncall = new wxCheckBox(p_misc, wxID_ANY, "Automatically pause at function call"); //Custom EmulationDir wxCheckBox* chbox_emulationdir_enable = new wxCheckBox(p_system, wxID_ANY, "Use path below as EmulationDir. (Restart required)"); wxTextCtrl* txt_emulationdir_path = new wxTextCtrl(p_system, wxID_ANY, fs::get_executable_dir()); wxArrayString ppu_decoder_modes; ppu_decoder_modes.Add("Interpreter"); ppu_decoder_modes.Add("Interpreter 2"); ppu_decoder_modes.Add("Recompiler (LLVM)"); rbox_ppu_decoder = new wxRadioBox(p_core, wxID_ANY, "PPU decoder", wxDefaultPosition, wxSize(215, -1), ppu_decoder_modes, 1); #if !defined(LLVM_AVAILABLE) rbox_ppu_decoder->Enable(2, false); #endif wxArrayString spu_decoder_modes; spu_decoder_modes.Add("Interpreter (precise)"); spu_decoder_modes.Add("Interpreter (fast)"); spu_decoder_modes.Add("Recompiler (ASMJIT)"); rbox_spu_decoder = new wxRadioBox(p_core, wxID_ANY, "SPU decoder", wxDefaultPosition, wxSize(215, -1), spu_decoder_modes, 1); cbox_gs_render->Append("Null"); cbox_gs_render->Append("OpenGL"); #ifdef _MSC_VER Microsoft::WRL::ComPtr<IDXGIFactory4> dxgiFactory; Microsoft::WRL::ComPtr<IDXGIAdapter> adapter; if (SUCCEEDED(CreateDXGIFactory(IID_PPV_ARGS(&dxgiFactory)))) { cbox_gs_render->Append("DirectX 12"); for (uint id = 0; dxgiFactory->EnumAdapters(id, adapter.GetAddressOf()) != DXGI_ERROR_NOT_FOUND; id++) { DXGI_ADAPTER_DESC adapterDesc; adapter->GetDesc(&adapterDesc); cbox_gs_d3d_adaptater->Append(adapterDesc.Description); } } else { cbox_gs_d3d_adaptater->Enable(false); chbox_gs_overlay->Enable(false); } #endif for (int i = 1; i < WXSIZEOF(ResolutionTable); ++i) { cbox_gs_resolution->Append(wxString::Format("%dx%d", ResolutionTable[i].width.value(), ResolutionTable[i].height.value())); } cbox_gs_aspect->Append("4:3"); cbox_gs_aspect->Append("16:9"); for (auto item : { "Off", "30", "50", "59.94", "60", "Auto" }) cbox_gs_frame_limit->Append(item); cbox_pad_handler->Append("Null"); cbox_pad_handler->Append("Windows"); #ifdef _MSC_VER cbox_pad_handler->Append("XInput"); #endif //cbox_pad_handler->Append("DirectInput"); cbox_keyboard_handler->Append("Null"); cbox_keyboard_handler->Append("Windows"); //cbox_keyboard_handler->Append("DirectInput"); cbox_mouse_handler->Append("Null"); cbox_mouse_handler->Append("Windows"); //cbox_mouse_handler->Append("DirectInput"); cbox_audio_out->Append("Null"); cbox_audio_out->Append("OpenAL"); #ifdef _MSC_VER cbox_audio_out->Append("XAudio2"); #endif cbox_camera->Append("Null"); cbox_camera->Append("Connected"); cbox_camera_type->Append("Unknown"); cbox_camera_type->Append("EyeToy"); cbox_camera_type->Append("PlayStation Eye"); cbox_camera_type->Append("USB Video Class 1.1"); cbox_hle_loglvl->Append("Nothing"); cbox_hle_loglvl->Append("Fatal"); cbox_hle_loglvl->Append("Error"); cbox_hle_loglvl->Append("TODO"); cbox_hle_loglvl->Append("Success"); cbox_hle_loglvl->Append("Warning"); cbox_hle_loglvl->Append("Notice"); cbox_hle_loglvl->Append("All"); cbox_net_status->Append("IP Obtained"); cbox_net_status->Append("Obtaining IP"); cbox_net_status->Append("Connecting"); cbox_net_status->Append("Disconnected"); for(const auto& adapterName : GetAdapters()) cbox_net_interface->Append(adapterName); static wxString s_langs[] = { "Japanese", "English (US)", "French", "Spanish", "German", "Italian", "Dutch", "Portuguese (PT)", "Russian", "Korean", "Chinese (Trad.)", "Chinese (Simp.)", "Finnish", "Swedish", "Danish", "Norwegian", "Polish", "English (UK)" }; for (const auto& lang : s_langs) cbox_sys_lang->Append(lang); chbox_core_llvm_exclud->SetValue(cfg->core.llvm.exclusion_range.value()); chbox_gs_log_prog->SetValue(rpcs3::config.rsx.log_programs.value()); chbox_gs_dump_depth->SetValue(cfg->rsx.opengl.write_depth_buffer.value()); chbox_gs_dump_color->SetValue(cfg->rsx.opengl.write_color_buffers.value()); chbox_gs_read_color->SetValue(cfg->rsx.opengl.read_color_buffers.value()); chbox_gs_read_depth->SetValue(cfg->rsx.opengl.read_depth_buffer.value()); chbox_gs_vsync->SetValue(rpcs3::config.rsx.vsync.value()); chbox_gs_debug_output->SetValue(cfg->rsx.d3d12.debug_output.value()); chbox_gs_3dmonitor->SetValue(rpcs3::config.rsx._3dtv.value()); chbox_gs_overlay->SetValue(cfg->rsx.d3d12.overlay.value()); chbox_audio_dump->SetValue(rpcs3::config.audio.dump_to_file.value()); chbox_audio_conv->SetValue(rpcs3::config.audio.convert_to_u16.value()); chbox_rsx_logging->SetValue(rpcs3::config.misc.log.rsx_logging.value()); chbox_hle_exitonstop->SetValue(rpcs3::config.misc.exit_on_stop.value()); chbox_hle_always_start->SetValue(rpcs3::config.misc.always_start.value()); chbox_hle_use_default_ini->SetValue(rpcs3::config.misc.use_default_ini.value()); chbox_core_hook_stfunc->SetValue(cfg->core.hook_st_func.value()); chbox_core_load_liblv2->SetValue(cfg->core.load_liblv2.value()); //Auto Pause related chbox_dbg_ap_systemcall->SetValue(rpcs3::config.misc.debug.auto_pause_syscall.value()); chbox_dbg_ap_functioncall->SetValue(rpcs3::config.misc.debug.auto_pause_func_call.value()); //Custom EmulationDir chbox_emulationdir_enable->SetValue(rpcs3::config.system.emulation_dir_path_enable.value()); txt_emulationdir_path->SetValue(rpcs3::config.system.emulation_dir_path.value()); rbox_ppu_decoder->SetSelection((int)cfg->core.ppu_decoder.value()); txt_dbg_range_min->SetValue(cfg->core.llvm.min_id.string_value()); txt_dbg_range_max->SetValue(cfg->core.llvm.max_id.string_value()); txt_llvm_threshold->SetValue(cfg->core.llvm.threshold.string_value()); rbox_spu_decoder->SetSelection((int)cfg->core.spu_decoder.value()); cbox_gs_render->SetSelection((int)cfg->rsx.renderer.value()); cbox_gs_d3d_adaptater->SetSelection(cfg->rsx.d3d12.adaptater.value()); cbox_gs_resolution->SetSelection(ResolutionIdToNum((int)cfg->rsx.resolution.value()) - 1); cbox_gs_aspect->SetSelection((int)cfg->rsx.aspect_ratio.value() - 1); cbox_gs_frame_limit->SetSelection((int)cfg->rsx.frame_limit.value()); cbox_pad_handler->SetSelection((int)cfg->io.pad_handler_mode.value()); cbox_keyboard_handler->SetSelection((int)cfg->io.keyboard_handler_mode.value()); cbox_mouse_handler->SetSelection((int)cfg->io.mouse_handler_mode.value()); cbox_audio_out->SetSelection((int)cfg->audio.out.value()); cbox_camera->SetSelection((int)cfg->io.camera.value()); cbox_camera_type->SetSelection((int)cfg->io.camera_type.value()); cbox_hle_loglvl->SetSelection((int)rpcs3::config.misc.log.level.value()); cbox_net_status->SetSelection((int)rpcs3::config.misc.net.status.value()); cbox_net_interface->SetSelection((int)rpcs3::config.misc.net._interface.value()); cbox_sys_lang->SetSelection((int)rpcs3::config.system.language.value()); // Core s_round_llvm->Add(chbox_core_llvm_exclud, wxSizerFlags().Border(wxALL, 5).Expand()); s_round_llvm_range->Add(txt_dbg_range_min, wxSizerFlags().Border(wxALL, 5).Expand()); s_round_llvm_range->Add(txt_dbg_range_max, wxSizerFlags().Border(wxALL, 5).Expand()); s_round_llvm->Add(s_round_llvm_range, wxSizerFlags().Border(wxALL, 5).Expand()); s_round_llvm_threshold->Add(txt_llvm_threshold, wxSizerFlags().Border(wxALL, 5).Expand()); s_round_llvm->Add(s_round_llvm_threshold, wxSizerFlags().Border(wxALL, 5).Expand()); // Rendering s_round_gs_render->Add(cbox_gs_render, wxSizerFlags().Border(wxALL, 5).Expand()); s_round_gs_d3d_adaptater->Add(cbox_gs_d3d_adaptater, wxSizerFlags().Border(wxALL, 5).Expand()); s_round_gs_res->Add(cbox_gs_resolution, wxSizerFlags().Border(wxALL, 5).Expand()); s_round_gs_aspect->Add(cbox_gs_aspect, wxSizerFlags().Border(wxALL, 5).Expand()); s_round_gs_frame_limit->Add(cbox_gs_frame_limit, wxSizerFlags().Border(wxALL, 5).Expand()); // Input/Output s_round_io_pad_handler->Add(cbox_pad_handler, wxSizerFlags().Border(wxALL, 5).Expand()); s_round_io_keyboard_handler->Add(cbox_keyboard_handler, wxSizerFlags().Border(wxALL, 5).Expand()); s_round_io_mouse_handler->Add(cbox_mouse_handler, wxSizerFlags().Border(wxALL, 5).Expand()); s_round_io_camera->Add(cbox_camera, wxSizerFlags().Border(wxALL, 5).Expand()); s_round_io_camera_type->Add(cbox_camera_type, wxSizerFlags().Border(wxALL, 5).Expand()); s_round_audio_out->Add(cbox_audio_out, wxSizerFlags().Border(wxALL, 5).Expand()); // Miscellaneous s_round_hle_log_lvl->Add(cbox_hle_loglvl, wxSizerFlags().Border(wxALL, 5).Expand()); // Networking s_round_net_status->Add(cbox_net_status, wxSizerFlags().Border(wxALL, 5).Expand()); s_round_net_interface->Add(cbox_net_interface, wxSizerFlags().Border(wxALL, 5).Expand()); s_round_sys_lang->Add(cbox_sys_lang, wxSizerFlags().Border(wxALL, 5).Expand()); // Core s_subpanel_core1->Add(rbox_ppu_decoder, wxSizerFlags().Border(wxALL, 5).Expand()); s_subpanel_core2->Add(rbox_spu_decoder, wxSizerFlags().Border(wxALL, 5).Expand()); s_subpanel_core1->Add(s_round_llvm, wxSizerFlags().Border(wxALL, 5).Expand()); s_subpanel_core1->Add(chbox_core_hook_stfunc, wxSizerFlags().Border(wxALL, 5).Expand()); s_subpanel_core1->Add(chbox_core_load_liblv2, wxSizerFlags().Border(wxALL, 5).Expand()); s_subpanel_core->Add(s_subpanel_core1); s_subpanel_core->Add(s_subpanel_core2); // Graphics s_subpanel_graphics1->Add(s_round_gs_render, wxSizerFlags().Border(wxALL, 5).Expand()); s_subpanel_graphics1->Add(s_round_gs_res, wxSizerFlags().Border(wxALL, 5).Expand()); s_subpanel_graphics1->Add(s_round_gs_d3d_adaptater, wxSizerFlags().Border(wxALL, 5).Expand()); s_subpanel_graphics1->Add(chbox_gs_dump_color, wxSizerFlags().Border(wxALL, 5).Expand()); s_subpanel_graphics1->Add(chbox_gs_read_color, wxSizerFlags().Border(wxALL, 5).Expand()); s_subpanel_graphics1->Add(chbox_gs_dump_depth, wxSizerFlags().Border(wxALL, 5).Expand()); s_subpanel_graphics1->Add(chbox_gs_read_depth, wxSizerFlags().Border(wxALL, 5).Expand()); s_subpanel_graphics1->Add(chbox_gs_vsync, wxSizerFlags().Border(wxALL, 5).Expand()); s_subpanel_graphics2->Add(s_round_gs_aspect, wxSizerFlags().Border(wxALL, 5).Expand()); s_subpanel_graphics2->Add(s_round_gs_frame_limit, wxSizerFlags().Border(wxALL, 5).Expand()); s_subpanel_graphics2->AddSpacer(68); s_subpanel_graphics2->Add(chbox_gs_debug_output, wxSizerFlags().Border(wxALL, 5).Expand()); s_subpanel_graphics2->Add(chbox_gs_3dmonitor, wxSizerFlags().Border(wxALL, 5).Expand()); s_subpanel_graphics2->Add(chbox_gs_overlay, wxSizerFlags().Border(wxALL, 5).Expand()); s_subpanel_graphics2->Add(chbox_gs_log_prog, wxSizerFlags().Border(wxALL, 5).Expand()); s_subpanel_graphics->Add(s_subpanel_graphics1); s_subpanel_graphics->Add(s_subpanel_graphics2); // Input - Output s_subpanel_io1->Add(s_round_io_pad_handler, wxSizerFlags().Border(wxALL, 5).Expand()); s_subpanel_io1->Add(s_round_io_keyboard_handler, wxSizerFlags().Border(wxALL, 5).Expand()); s_subpanel_io1->Add(s_round_io_mouse_handler, wxSizerFlags().Border(wxALL, 5).Expand()); s_subpanel_io2->Add(s_round_io_camera, wxSizerFlags().Border(wxALL, 5).Expand()); s_subpanel_io2->Add(s_round_io_camera_type, wxSizerFlags().Border(wxALL, 5).Expand()); s_subpanel_io->Add(s_subpanel_io1); s_subpanel_io->Add(s_subpanel_io2); // Audio s_subpanel_audio->Add(s_round_audio_out, wxSizerFlags().Border(wxALL, 5).Expand()); s_subpanel_audio->Add(chbox_audio_dump, wxSizerFlags().Border(wxALL, 5).Expand()); s_subpanel_audio->Add(chbox_audio_conv, wxSizerFlags().Border(wxALL, 5).Expand()); // Miscellaneous s_subpanel_misc->Add(s_round_hle_log_lvl, wxSizerFlags().Border(wxALL, 5).Expand()); s_subpanel_misc->Add(chbox_rsx_logging, wxSizerFlags().Border(wxALL, 5).Expand()); s_subpanel_misc->Add(chbox_hle_exitonstop, wxSizerFlags().Border(wxALL, 5).Expand()); s_subpanel_misc->Add(chbox_hle_always_start, wxSizerFlags().Border(wxALL, 5).Expand()); s_subpanel_misc->Add(chbox_hle_use_default_ini, wxSizerFlags().Border(wxALL, 5).Expand()); // Auto Pause s_subpanel_misc->Add(chbox_dbg_ap_systemcall, wxSizerFlags().Border(wxALL, 5).Expand()); s_subpanel_misc->Add(chbox_dbg_ap_functioncall, wxSizerFlags().Border(wxALL, 5).Expand()); // Networking s_subpanel_networking->Add(s_round_net_status, wxSizerFlags().Border(wxALL, 5).Expand()); s_subpanel_networking->Add(s_round_net_interface, wxSizerFlags().Border(wxALL, 5).Expand()); // System s_subpanel_system->Add(s_round_sys_lang, wxSizerFlags().Border(wxALL, 5).Expand()); // Custom EmulationDir s_subpanel_system->Add(chbox_emulationdir_enable, wxSizerFlags().Border(wxALL, 5).Expand()); s_subpanel_system->Add(txt_emulationdir_path, wxSizerFlags().Border(wxALL, 5).Expand()); // Buttons wxBoxSizer* s_b_panel(new wxBoxSizer(wxHORIZONTAL)); s_b_panel->Add(new wxButton(this, wxID_OK), wxSizerFlags().Border(wxALL, 5).Bottom()); s_b_panel->Add(new wxButton(this, wxID_CANCEL), wxSizerFlags().Border(wxALL, 5).Bottom()); // Resize panels SetSizerAndFit(s_subpanel_core, false); SetSizerAndFit(s_subpanel_graphics, false); SetSizerAndFit(s_subpanel_io, false); SetSizerAndFit(s_subpanel_audio, false); SetSizerAndFit(s_subpanel_misc, false); SetSizerAndFit(s_subpanel_networking, false); SetSizerAndFit(s_subpanel_system, false); SetSizerAndFit(s_b_panel, false); SetSize(width + 26, height + 80); if (ShowModal() == wxID_OK) { long llvmthreshold; long minllvmid, maxllvmid; txt_dbg_range_min->GetValue().ToLong(&minllvmid); txt_dbg_range_max->GetValue().ToLong(&maxllvmid); txt_llvm_threshold->GetValue().ToLong(&llvmthreshold); // individual settings cfg->core.ppu_decoder = rbox_ppu_decoder->GetSelection(); cfg->core.llvm.exclusion_range = chbox_core_llvm_exclud->GetValue(); cfg->core.llvm.min_id = minllvmid; cfg->core.llvm.max_id = maxllvmid; cfg->core.llvm.threshold = llvmthreshold; cfg->core.spu_decoder = rbox_spu_decoder->GetSelection(); cfg->core.hook_st_func = chbox_core_hook_stfunc->GetValue(); cfg->core.load_liblv2 = chbox_core_load_liblv2->GetValue(); cfg->rsx.renderer = cbox_gs_render->GetSelection(); cfg->rsx.d3d12.adaptater = cbox_gs_d3d_adaptater->GetSelection(); cfg->rsx.resolution = ResolutionNumToId(cbox_gs_resolution->GetSelection() + 1); cfg->rsx.aspect_ratio = cbox_gs_aspect->GetSelection() + 1; cfg->rsx.frame_limit = cbox_gs_frame_limit->GetSelection(); cfg->rsx.opengl.write_depth_buffer = chbox_gs_dump_depth->GetValue(); cfg->rsx.opengl.write_color_buffers = chbox_gs_dump_color->GetValue(); cfg->rsx.opengl.read_color_buffers = chbox_gs_read_color->GetValue(); cfg->rsx.opengl.read_depth_buffer = chbox_gs_read_depth->GetValue(); cfg->audio.out = cbox_audio_out->GetSelection(); cfg->io.pad_handler_mode = cbox_pad_handler->GetSelection(); cfg->io.keyboard_handler_mode = cbox_keyboard_handler->GetSelection(); cfg->io.mouse_handler_mode = cbox_mouse_handler->GetSelection(); cfg->io.camera = cbox_camera->GetSelection(); cfg->io.camera_type = cbox_camera_type->GetSelection(); // global settings rpcs3::config.rsx.log_programs = chbox_gs_log_prog->GetValue(); rpcs3::config.rsx.vsync = chbox_gs_vsync->GetValue(); rpcs3::config.rsx._3dtv = chbox_gs_3dmonitor->GetValue(); rpcs3::config.rsx.d3d12.debug_output = chbox_gs_debug_output->GetValue(); rpcs3::config.rsx.d3d12.overlay = chbox_gs_overlay->GetValue(); rpcs3::config.audio.dump_to_file = chbox_audio_dump->GetValue(); rpcs3::config.audio.convert_to_u16 = chbox_audio_conv->GetValue(); rpcs3::config.misc.log.level = cbox_hle_loglvl->GetSelection(); rpcs3::config.misc.log.rsx_logging = chbox_rsx_logging->GetValue(); rpcs3::config.misc.net.status = cbox_net_status->GetSelection(); rpcs3::config.misc.net._interface = cbox_net_interface->GetSelection(); rpcs3::config.misc.debug.auto_pause_syscall = chbox_dbg_ap_systemcall->GetValue(); rpcs3::config.misc.debug.auto_pause_func_call = chbox_dbg_ap_functioncall->GetValue(); rpcs3::config.misc.always_start = chbox_hle_always_start->GetValue(); rpcs3::config.misc.exit_on_stop = chbox_hle_exitonstop->GetValue(); rpcs3::config.misc.use_default_ini = chbox_hle_use_default_ini->GetValue(); rpcs3::config.system.language = cbox_sys_lang->GetSelection(); rpcs3::config.system.emulation_dir_path_enable = chbox_emulationdir_enable->GetValue(); rpcs3::config.system.emulation_dir_path = txt_emulationdir_path->GetValue().ToStdString(); rpcs3::config.save(); cfg->save(); } if (was_running) Emu.Resume(); }
bool D3DClass::Initialize(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; // vsync(수직동기화) 설정을 저장합니다. m_vsync_enabled = vsync; // DirectX 그래픽 인터페이스 팩토리를 만듭니다. result = CreateDXGIFactory(__uuidof(IDXGIFactory), (void**)&factory); if (FAILED(result)) { return false; } // 팩토리 객체를 사용하여 첫번째 그래픽 카드 인터페이스에 대한 아답터를 만듭니다. result = factory->EnumAdapters(0, &adapter); if (FAILED(result)) { return false; } // 출력(모니터)에 대한 첫번째 아답터를 나열합니다. result = adapter->EnumOutputs(0, &adapterOutput); if (FAILED(result)) { return false; } // DXGI_FORMAT_R8G8B8A8_UNORM 모니터 출력 디스플레이 포맷에 맞는 모드의 개수를 구합니다. result = adapterOutput->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 = adapterOutput->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; } } } // 아답터(그래픽카드)의 description을 가져옵니다. result = adapter->GetDesc(&adapterDesc); if (FAILED(result)) { return false; } // 현재 그래픽카드의 메모리 용량을 메가바이트 단위로 저장합니다. m_videoCardMemory = (int)(adapterDesc.DedicatedVideoMemory / 1024 / 1024); // 그래픽카드의 이름을 char형 문자열 배열로 바꾼 뒤 저장합니다. error = wcstombs_s(&stringLength, m_videoCardDescription, 128, adapterDesc.Description, 128); if (error != 0) { return false; } // 디스플레이 모드 리스트의 할당을 해제합니다. delete[] displayModeList; displayModeList = 0; // 출력 아답터를 할당 해제합니다. adapterOutput->Release(); adapterOutput = 0; // 아답터를 할당 해제합니다. adapter->Release(); adapter = 0; // 팩토리 객체를 할당 해제합니다. factory->Release(); factory = 0; // 스왑 체인 description을 초기화합니다. ZeroMemory(&swapChainDesc, sizeof(swapChainDesc)); // 하나의 백버퍼만을 사용하도록 합니다. swapChainDesc.BufferCount = 1; // 백버퍼의 너비와 높이를 설정합니다. swapChainDesc.BufferDesc.Width = screenWidth; swapChainDesc.BufferDesc.Height = screenHeight; // 백퍼버로 일반적인 32bit의 서페이스를 지정합니다. swapChainDesc.BufferDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM; // 백버퍼의 새로고침 비율을 설정합니다. if (m_vsync_enabled) { swapChainDesc.BufferDesc.RefreshRate.Numerator = numerator; swapChainDesc.BufferDesc.RefreshRate.Denominator = denominator; } else { swapChainDesc.BufferDesc.RefreshRate.Numerator = 0; swapChainDesc.BufferDesc.RefreshRate.Denominator = 1; } // 백버퍼의 용도를 설정합니다. swapChainDesc.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT; // 렌더링이 이루어질 윈도우의 핸들을 설정합니다. swapChainDesc.OutputWindow = hwnd; // 멀티샘플링을 끕니다. swapChainDesc.SampleDesc.Count = 1; swapChainDesc.SampleDesc.Quality = 0; // 윈도우 모드 또는 풀스크린 모드를 설정합니다. if (fullscreen) swapChainDesc.Windowed = false; else swapChainDesc.Windowed = true; // 스캔라인의 정렬과 스캔라이닝을 지정되지 않으므로 (unspecified) 설정합니다. swapChainDesc.BufferDesc.ScanlineOrdering = DXGI_MODE_SCANLINE_ORDER_UNSPECIFIED; swapChainDesc.BufferDesc.Scaling = DXGI_MODE_SCALING_UNSPECIFIED; // 출력된 이후의 백버퍼의 내용을 버리도록 합니다. swapChainDesc.SwapEffect = DXGI_SWAP_EFFECT_DISCARD; // 추가 옵션 플래그를 사용하지 않습니다. swapChainDesc.Flags = 0; // 피쳐 레벨을 DirectX 11로 설정합니다. featureLevel = D3D_FEATURE_LEVEL_11_0; // 스왑 체인, Direct3D 디바이스, Direct3D 디바이스 컨텍스트를 생성합니다. result = D3D11CreateDeviceAndSwapChain(NULL, D3D_DRIVER_TYPE_HARDWARE, NULL, 0, &featureLevel, 1, D3D11_SDK_VERSION, &swapChainDesc, &m_swapChain, &m_device, NULL, &m_deviceContext); if (FAILED(result)) return false; // 백버퍼의 포인터를 가져옵니다. result = m_swapChain->GetBuffer(0, __uuidof(ID3D11Texture2D), (LPVOID*)&backBufferPtr); if (FAILED(result)) return false; // 백버퍼의 포인터로 렌더타겟 뷰를 생성합니다. result = m_device->CreateRenderTargetView(backBufferPtr, NULL, &m_renderTargetView); if (FAILED(result)) return false; // 백버퍼 포인터를 더이상 사용하지 않으므로 할당 해제합니다. backBufferPtr->Release(); backBufferPtr = 0; // 깊이 버퍼의 description을 초기화합니다. ZeroMemory(&depthBufferDesc, sizeof(depthBufferDesc)); // 깊이 버퍼의 description을 작성합니다. 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; // description을 사용하여 깊이 버퍼의 텍스쳐를 생성합니다. result = m_device->CreateTexture2D(&depthBufferDesc, NULL, &m_depthStencilBuffer); if (FAILED(result)) return false; // 스텐실 상태의 description을 초기화합니다. ZeroMemory(&depthStencilDesc, sizeof(depthStencilDesc)); // 스텐실 상태의 description을 작성합니다. 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; // 깊이 - 스텐실 상태를 생성합니다. result = m_device->CreateDepthStencilState(&depthStencilDesc, &m_depthStencilState); if (FAILED(result)) return false; // 깊이 - 스텐실 상태를 설정합니다. m_deviceContext->OMSetDepthStencilState(m_depthStencilState, 1); // 깊이 - 스텐실 뷰의 description을 초기화 합니다. ZeroMemory(&depthStencilViewDesc, sizeof(depthStencilViewDesc)); // 깊이 - 스텐실 부의 description을 작성합니다. depthStencilViewDesc.Format = DXGI_FORMAT_D24_UNORM_S8_UINT; depthStencilViewDesc.ViewDimension = D3D11_DSV_DIMENSION_TEXTURE2D; depthStencilViewDesc.Texture2D.MipSlice = 0; // 깊이 - 스텐실 뷰를 생성합니다. result = m_device->CreateDepthStencilView(m_depthStencilBuffer, &depthStencilViewDesc, &m_depthStencilView); if (FAILED(result)) return false; // 렌더타겟 뷰와 깊이 - 스텐실 버퍼를 각각 출력 파이프라인에 바인딩합니다. m_deviceContext->OMSetRenderTargets(1, &m_renderTargetView, m_depthStencilView); // 어떤 도형을 어떻게 그릴 것인지 결정하는 래스터화기 description을 작성합니다. 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; // 작성한 description으로부터 래스터화기 상태를 생성합니다. result = m_device->CreateRasterizerState(&rasterDesc, &m_rasterState); if (FAILED(result)) return false; // 래스터화기 상태를 설정합니다. m_deviceContext->RSSetState(m_rasterState); // 렌더링을 위한 뷰포트를 설정합니다. viewport.Width = (float)screenWidth; viewport.Height = (float)screenHeight; viewport.MinDepth = 0.0f; viewport.MaxDepth = 1.0f; viewport.TopLeftX = 0.0f; viewport.TopLeftY = 0.0f; // 뷰포트를 생성합니다. m_deviceContext->RSSetViewports(1, &viewport); // 투영 행렬을 설정합니다. fieldOfView = (float)D3DX_PI / 4.0f; screenAspect = (float)screenWidth / (float)screenHeight; // 3D 렌더링을 위한 투영 행렬을 생성합니다. D3DXMatrixPerspectiveFovLH(&m_projectionMatrix, fieldOfView, screenAspect, screenNear, screenDepth); // 월드 행렬을 단위 행렬로 초기화 합니다. D3DXMatrixIdentity(&m_worldMatrix); // 2D 렌더링에 사용될 정사영 행렬을 생성합니다. D3DXMatrixOrthoLH(&m_orthoMatrix, (float)screenWidth, (float)screenHeight, screenNear, screenDepth); return true; }
void RenderSystem::init_device() { ////////////////////////Create buffer desc//////////////////////////// DXGI_MODE_DESC bufferDesc; ZeroMemory(&bufferDesc, sizeof(DXGI_MODE_DESC)); bufferDesc.Width = m_ScreenWidth; bufferDesc.Height = m_ScreenHeight; bufferDesc.RefreshRate.Numerator = 60; bufferDesc.RefreshRate.Denominator = 1; bufferDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM; bufferDesc.ScanlineOrdering = DXGI_MODE_SCANLINE_ORDER_UNSPECIFIED; bufferDesc.Scaling = DXGI_MODE_SCALING_UNSPECIFIED; //Create swapChain Desc DXGI_SWAP_CHAIN_DESC swapChainDesc; ZeroMemory(&swapChainDesc, sizeof(DXGI_SWAP_CHAIN_DESC)); swapChainDesc.BufferDesc = bufferDesc; swapChainDesc.SampleDesc.Count = 1; swapChainDesc.SampleDesc.Quality = 0; swapChainDesc.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT; swapChainDesc.BufferCount = 1; swapChainDesc.OutputWindow = GetHwnd(); swapChainDesc.Windowed = TRUE; swapChainDesc.SwapEffect = DXGI_SWAP_EFFECT_DISCARD; /////////////////////////////////////////////////////////////////////////// HRESULT hr; //Create the double buffer chain hr = D3D11CreateDeviceAndSwapChain(NULL, D3D_DRIVER_TYPE_HARDWARE, NULL, NULL, NULL, NULL, D3D11_SDK_VERSION, &swapChainDesc, &m_pSwapChain, &m_pD3D11Device, NULL, &m_pD3D11DeviceContext); //DebugHR(hr); //Create back buffer, buffer also is a texture ID3D11Texture2D *pBackBuffer; hr = m_pSwapChain->GetBuffer(0, __uuidof(ID3D11Texture2D), (void**)&pBackBuffer); hr = m_pD3D11Device->CreateRenderTargetView(pBackBuffer, NULL, &m_pRenderTargetView); pBackBuffer->Release(); //DebugHR(hr); ///////////////////// Set up the description of the depth buffer.//////////////////////// D3D11_TEXTURE2D_DESC depthBufferDesc; ZeroMemory(&depthBufferDesc, sizeof(depthBufferDesc)); depthBufferDesc.Width = m_ScreenWidth; depthBufferDesc.Height = m_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. hr = m_pD3D11Device->CreateTexture2D(&depthBufferDesc, NULL, &m_pDepthStencilBuffer); //////////////////////////// Initialize the description of the stencil state./////////////////////////////////////////////// D3D11_DEPTH_STENCIL_DESC depthStencilDesc; ZeroMemory(&depthStencilDesc, sizeof(depthStencilDesc)); depthStencilDesc.DepthEnable = true; depthStencilDesc.DepthWriteMask = D3D11_DEPTH_WRITE_MASK_ALL; depthStencilDesc.DepthFunc = D3D11_COMPARISON_LESS_EQUAL; 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. hr = m_pD3D11Device->CreateDepthStencilState(&depthStencilDesc, &m_pDepthStencilState); //DebugHR(hr); // Initialize the depth stencil view. D3D11_DEPTH_STENCIL_VIEW_DESC depthStencilViewDesc; ZeroMemory(&depthStencilViewDesc, sizeof(depthStencilViewDesc)); depthStencilViewDesc.Format = DXGI_FORMAT_D24_UNORM_S8_UINT; depthStencilViewDesc.ViewDimension = D3D11_DSV_DIMENSION_TEXTURE2D; depthStencilViewDesc.Texture2D.MipSlice = 0; hr = m_pD3D11Device->CreateDepthStencilView(m_pDepthStencilBuffer, &depthStencilViewDesc, &m_pDepthStencilView); //DebugHR(hr); // Setup the raster description which will determine how and what polygons will be drawn. D3D11_RASTERIZER_DESC rasterDesc; 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. hr = m_pD3D11Device->CreateRasterizerState(&rasterDesc, &m_pRasterState); //DebugHR(hr); /////////////////////////////////////////////////////////////////////////////// unsigned int numModes, i, numerator, denominator, stringLength; IDXGIFactory* factory; IDXGIAdapter* adapter; IDXGISurface *surface; DXGI_ADAPTER_DESC adapterDesc; // Create a DirectX graphics interface factory. CreateDXGIFactory(__uuidof(IDXGIFactory), (void**)&factory); // Use the factory to create an adapter for the primary graphics interface (video card). factory->EnumAdapters(0, &adapter); adapter->GetDesc(&adapterDesc); m_videoCardMemory = (int)(adapterDesc.DedicatedVideoMemory / 1024 / 1024); // Convert the name of the video card to a character array and store it. m_videoCardInfo = std::wstring(L"Video Card :") + adapterDesc.Description; }
int main() { UINT dpi = SetupDPI(); gRenderScale = 96.0 / double(dpi); // Scale default window size based on dpi gWindowWidth *= dpi / 96; gWindowHeight *= dpi / 96; // Create window { WNDCLASSEX wc; ZeroMemory(&wc, sizeof(wc)); wc.cbSize = sizeof(wc); wc.style = CS_HREDRAW | CS_VREDRAW; wc.lpfnWndProc = MyWndProc; wc.hInstance = GetModuleHandle(NULL); wc.hCursor = LoadCursor(NULL, IDC_ARROW); wc.hbrBackground = (HBRUSH)COLOR_BACKGROUND; wc.lpszClassName = TEXT("WindowClass"); CHECK_WIN32(RegisterClassEx(&wc)); RECT wr = { 0, 0, gWindowWidth, gWindowHeight }; CHECK_WIN32(AdjustWindowRect(&wr, WS_OVERLAPPEDWINDOW, FALSE)); ghWnd = CHECK_WIN32(CreateWindowEx( 0, TEXT("WindowClass"), TEXT("Spooky"), WS_OVERLAPPEDWINDOW, CW_USEDEFAULT, CW_USEDEFAULT, wr.right - wr.left, wr.bottom - wr.top, 0, 0, GetModuleHandle(NULL), 0)); } // Create D3D11 device and swap chain { ComPtr<IDXGIFactory> pFactory; CHECK_HR(CreateDXGIFactory(IID_PPV_ARGS(&pFactory))); UINT deviceFlags = D3D11_CREATE_DEVICE_BGRA_SUPPORT; #ifdef _DEBUG deviceFlags |= D3D11_CREATE_DEVICE_DEBUG; #endif RECT clientRect; GetClientRect(ghWnd, &clientRect); DXGI_SWAP_CHAIN_DESC scd{}; scd.BufferCount = kSwapChainBufferCount; scd.BufferDesc.Format = kSwapChainFormat; scd.BufferDesc.Width = clientRect.right - clientRect.left; scd.BufferDesc.Height = clientRect.bottom - clientRect.top; scd.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT; scd.OutputWindow = ghWnd; scd.Windowed = TRUE; scd.SampleDesc.Count = 1; scd.SwapEffect = DXGI_SWAP_EFFECT_FLIP_DISCARD; CHECK_HR(D3D11CreateDeviceAndSwapChain(NULL, D3D_DRIVER_TYPE_HARDWARE, NULL, deviceFlags, NULL, 0, D3D11_SDK_VERSION, &scd, &gpSwapChain, &gpDevice, NULL, &gpDeviceContext)); CHECK_HR(gpDevice.As(&gpDxgiDevice)); } InitApp(dpi); ShowWindow(ghWnd, SW_SHOWNORMAL); EnableMouseInPointer(TRUE); while (!gShouldClose) { // Handle all events MSG msg; while (PeekMessage(&msg, NULL, 0, 0, PM_REMOVE) > 0) { TranslateMessage(&msg); DispatchMessage(&msg); } UpdateApp(); RenderApp(); // Swap buffers CHECK_HR(gpSwapChain->Present(0, 0)); } CoUninitialize(); // <- this currently creates problems with the WIC Factory. CHECK_HR(gpSwapChain->SetFullscreenState(FALSE, NULL)); }
char* app_display_querymodes() { IDXGIFactory* factory; if (FAILED(CreateDXGIFactory(__uuidof(IDXGIFactory), (void**)&factory))) return NULL; IDXGIAdapter* adapter; uint adapter_id = 0; DXGI_ADAPTER_DESC desc; char gpu_desc[128]; size_t outsz; /* start json data (adapter array) */ json_t jroot = json_create_arr(); /* read adapters */ while (factory->EnumAdapters(adapter_id, &adapter) != DXGI_ERROR_NOT_FOUND) { adapter->GetDesc(&desc); str_widetomb(gpu_desc, desc.Description, sizeof(gpu_desc)); json_t jadapter = json_create_obj(); json_additem_toarr(jroot, jadapter); json_additem_toobj(jadapter, "name", json_create_str(gpu_desc)); json_additem_toobj(jadapter, "id", json_create_num((fl64)adapter_id)); /* enumerate monitors */ json_t joutputs = json_create_arr(); json_additem_toobj(jadapter, "outputs", joutputs); IDXGIOutput* output; uint output_id = 0; while (adapter->EnumOutputs(output_id, &output) != DXGI_ERROR_NOT_FOUND) { json_t joutput = json_create_obj(); json_additem_toarr(joutputs, joutput); json_additem_toobj(joutput, "id", json_create_num((fl64)output_id)); /* enumerate modes */ json_t jmodes = json_create_arr(); json_additem_toobj(joutput, "monitors", jmodes); uint mode_cnt; HRESULT hr = output->GetDisplayModeList(DEFAULT_DISPLAY_FORMAT, 0, &mode_cnt, NULL); if (SUCCEEDED(hr)) { DXGI_MODE_DESC* modes = (DXGI_MODE_DESC*)ALLOC(sizeof(DXGI_MODE_DESC) * mode_cnt, 0); ASSERT(modes); output->GetDisplayModeList(DEFAULT_DISPLAY_FORMAT, 0, &mode_cnt, modes); for (uint i = 0; i < mode_cnt; i++) { if (modes[i].RefreshRate.Denominator != 1) continue; json_t jmode = json_create_obj(); json_additem_toobj(jmode, "width", json_create_num((fl64)modes[i].Width)); json_additem_toobj(jmode, "height", json_create_num((fl64)modes[i].Height)); json_additem_toobj(jmode, "refresh-rate", json_create_num((fl64)modes[i].RefreshRate.Numerator)); json_additem_toarr(jmodes, jmode); } FREE(modes); } output_id ++; } adapter->Release(); adapter_id ++; } factory->Release(); char* r = json_savetobuffer(jroot, &outsz, FALSE); json_destroy(jroot); return r; }
bool D3D11::getScreenSettings( D3D11::ScreenMode & mode, int screenWidth, int screenHeight ) { HRESULT result; int error; IDXGIFactory* factory; IDXGIAdapter* adapter; IDXGIOutput* adapterOutput; DXGI_MODE_DESC* displayModeList; DXGI_ADAPTER_DESC adapterDesc; unsigned int numModes, i, stringLength; // Create a DirectX graphics interface factory. result = CreateDXGIFactory(__uuidof(IDXGIFactory), (void**)&factory); if(FAILED(result)) { return false; } // Use the factory to create an adapter 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 fit 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 display 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. mode.height = screenHeight; mode.width = screenWidth; for(i=0; i<numModes; i++) { if(displayModeList[i].Width == (unsigned int)screenWidth) { if(displayModeList[i].Height == (unsigned int)screenHeight) { mode.numerator = displayModeList[i].RefreshRate.Numerator; mode.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 megabytes. mVideoCardMemory = (int)(adapterDesc.DedicatedVideoMemory / 1024 / 1024); // Convert the name of the video card to a character array and store it. //todo: fix this for x64 builds //error = wcstombs_s(&stringLength, mVideoCardDescription, 128, adapterDesc.Description, 128); error = 0; if(error != 0) { return false; } // Release the display mode list. delete [] displayModeList; displayModeList = 0; // Release the adapter output. adapterOutput->Release(); adapterOutput = 0; // Release the adapter. adapter->Release(); adapter = 0; // Release the factory. factory->Release(); factory = 0; return true; }
bool D3D::InitializeD3D(int screenWidth, int screenHeight, bool vsync, HWND hwnd, bool fullscreen) { HRESULT result; //used to test things are created ok. vsync; //---------------------------------------------------------------------------------------------- // Fetch the numerator and denominator for refresh rate and video card description. // Create DirectX Graphics Interface factory. IDXGIFactory* factory; result = CreateDXGIFactory(__uuidof(IDXGIFactory), (void**)&factory); if(FAILED(result)) return false; // Create adapter. IDXGIAdapter* adapter; result = factory->EnumAdapters(0, &adapter); if(FAILED(result)) return false; // Enumerate primary adapter output (monitor). IDXGIOutput* adapterOutput; result = adapter->EnumOutputs(0, &adapterOutput); if(FAILED(result)) return false; // Get the number of modes that fit the DXGI_R8G8B8A8_UNORM display format for adpater output. unsigned int numModes; result = adapterOutput->GetDisplayModeList(DXGI_FORMAT_R8G8B8A8_UNORM, DXGI_ENUM_MODES_INTERLACED, &numModes, NULL); if(FAILED(result)) return false; // Create a list to hold all possible display modes. DXGI_MODE_DESC* displayModeList; displayModeList = new DXGI_MODE_DESC[numModes]; if(!displayModeList) return false; // Fill list. result = adapterOutput->GetDisplayModeList(DXGI_FORMAT_R8G8B8A8_UNORM, DXGI_ENUM_MODES_INTERLACED, &numModes, displayModeList); if(FAILED(result)) return false; // Loop through modes and find one that matches screen width and height, store numerator and // denominator for corresponding refresh rate. unsigned int numerator, denominator; for(unsigned int i = 0; i < numModes; ++i) { if(displayModeList[i].Width == (unsigned int)screenWidth && displayModeList[i].Height == (unsigned int)screenHeight) { numerator = displayModeList[i].RefreshRate.Numerator; denominator = displayModeList[i].RefreshRate.Denominator; } } // Get adapter description. DXGI_ADAPTER_DESC adapterDesc; result = adapter->GetDesc(&adapterDesc); if(FAILED(result)) return false; // Store dedicated video card memory (in mb). m_videoCardMemory = (int)(adapterDesc.DedicatedVideoMemory / 1024 / 1024); // Convert the name of the video card to char array and store. unsigned int stringLength; int error = wcstombs_s(&stringLength, m_videoCardDesc, 128, adapterDesc.Description, 128); if(error != 0) return false; // Release unneeded memory. delete[] displayModeList; displayModeList = 0; adapterOutput->Release(); adapterOutput = 0; adapter->Release(); adapter = 0; factory->Release(); factory = 0; //---------------------------------------------------------------------------------------------- //---------------------------------------------------------------------------------------------- // Set up SwapChain description and create swap chain. DXGI_SWAP_CHAIN_DESC swapChainDesc; ZeroMemory(&swapChainDesc, sizeof(swapChainDesc)); // Setup back buffer. swapChainDesc.BufferCount = 1; swapChainDesc.BufferDesc.Width = screenWidth; swapChainDesc.BufferDesc.Height = screenHeight; swapChainDesc.BufferDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM; // Refresh Rate. if(m_vsyncEnabled) { swapChainDesc.BufferDesc.RefreshRate.Numerator = numerator; swapChainDesc.BufferDesc.RefreshRate.Denominator = denominator; } else { // Draw as soon as possible. swapChainDesc.BufferDesc.RefreshRate.Numerator = 0; swapChainDesc.BufferDesc.RefreshRate.Denominator = 1; } swapChainDesc.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT; swapChainDesc.OutputWindow = hwnd; // Turn off multisampling. swapChainDesc.SampleDesc.Count = 1; swapChainDesc.SampleDesc.Quality = 0; swapChainDesc.Windowed = !fullscreen; swapChainDesc.BufferDesc.ScanlineOrdering = DXGI_MODE_SCANLINE_ORDER_UNSPECIFIED; swapChainDesc.BufferDesc.Scaling = DXGI_MODE_SCALING_UNSPECIFIED; swapChainDesc.SwapEffect = DXGI_SWAP_EFFECT_DISCARD; swapChainDesc.Flags = 0; // Create the swap chain. D3D_FEATURE_LEVEL featureLevel = D3D_FEATURE_LEVEL_11_0; result = D3D11CreateDeviceAndSwapChain(NULL, D3D_DRIVER_TYPE_HARDWARE, NULL, 0, &featureLevel, 1, D3D11_SDK_VERSION, &swapChainDesc, &m_swapChain, &m_device, NULL, &m_deviceContext); if(FAILED(result)) return false; //---------------------------------------------------------------------------------------------- //---------------------------------------------------------------------------------------------- // Set up render target view. ID3D11Texture2D* backBufferPtr; result = m_swapChain->GetBuffer(0, __uuidof(ID3D11Texture2D), (LPVOID*)&backBufferPtr); if(FAILED(result)) return false; // Create render target view with back buffer ptr. result = m_device->CreateRenderTargetView(backBufferPtr, NULL, &m_renderTargetView); if(FAILED(result)) return false; backBufferPtr->Release(); backBufferPtr = 0; //---------------------------------------------------------------------------------------------- //---------------------------------------------------------------------------------------------- // Set up depthStencilBuffer. D3D11_TEXTURE2D_DESC depthBufferDesc; ZeroMemory(&depthBufferDesc, sizeof(depthBufferDesc)); // Set up description. 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 depth/stencil buffer. result = m_device->CreateTexture2D(&depthBufferDesc, NULL, &m_depthStencilBuffer); if(FAILED(result)) return false; // Setup depth stencil description. D3D11_DEPTH_STENCIL_DESC depthStencilDesc; ZeroMemory(&depthStencilDesc, sizeof(depthStencilDesc)); depthStencilDesc.DepthEnable = true; depthStencilDesc.DepthWriteMask = D3D11_DEPTH_WRITE_MASK_ALL; depthStencilDesc.DepthFunc = D3D11_COMPARISON_LESS; depthStencilDesc.StencilEnable = true; depthStencilDesc.StencilReadMask = 0xFF; depthStencilDesc.StencilWriteMask = 0xFF; 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; 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 depth stencil state. result = m_device->CreateDepthStencilState(&depthStencilDesc, &m_depthStencilState); if(FAILED(result)) return false; // Set depth stencil state. m_deviceContext->OMSetDepthStencilState(m_depthStencilState, 1); //---------------------------------------------------------------------------------------------- //---------------------------------------------------------------------------------------------- // Create second depth stencil state with depth disabled. (for 2D rendering) D3D11_DEPTH_STENCIL_DESC depthDisabledStencilDesc; ZeroMemory(&depthDisabledStencilDesc, sizeof(depthDisabledStencilDesc)); 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_DECR; 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; result = m_device->CreateDepthStencilState(&depthDisabledStencilDesc, &m_depthDisabledStencilState); if(FAILED(result)) return false; //---------------------------------------------------------------------------------------------- //---------------------------------------------------------------------------------------------- // Create description of the view of the depth stencil buffer. // Do this so D3D knows to use the depth buffer as a depth stencil texture. D3D11_DEPTH_STENCIL_VIEW_DESC depthStencilViewDesc; ZeroMemory(&depthStencilViewDesc, sizeof(depthStencilViewDesc)); depthStencilViewDesc.Format = DXGI_FORMAT_D24_UNORM_S8_UINT; depthStencilViewDesc.ViewDimension = D3D11_DSV_DIMENSION_TEXTURE2D; depthStencilViewDesc.Texture2D.MipSlice = 0; result = m_device->CreateDepthStencilView(m_depthStencilBuffer, &depthStencilViewDesc, &m_depthStencilView); if(FAILED(result)) return false; // Bind render target view and depth stencil buffer to output render pipeline. m_deviceContext->OMSetRenderTargets(1, &m_renderTargetView, m_depthStencilView); //---------------------------------------------------------------------------------------------- //---------------------------------------------------------------------------------------------- // Create rasterizer state and viewport. D3D11_RASTERIZER_DESC rasterDesc; 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.0; result = m_device->CreateRasterizerState(&rasterDesc, &m_rasterState); if(FAILED(result)) return false; m_deviceContext->RSSetState(m_rasterState); // Create rasterizer state with wireframe fill mode. D3D11_RASTERIZER_DESC rasterWireframeDesc; rasterWireframeDesc.AntialiasedLineEnable = false; rasterWireframeDesc.CullMode = D3D11_CULL_BACK; rasterWireframeDesc.DepthBias = 0; rasterWireframeDesc.DepthBiasClamp = 0.0f; rasterWireframeDesc.DepthClipEnable = true; rasterWireframeDesc.FillMode = D3D11_FILL_WIREFRAME; rasterWireframeDesc.FrontCounterClockwise = false; rasterWireframeDesc.MultisampleEnable = false; rasterWireframeDesc.ScissorEnable = false; rasterWireframeDesc.SlopeScaledDepthBias = 0.0; result = m_device->CreateRasterizerState(&rasterWireframeDesc, &m_rasterStateWireframe); if(FAILED(result)) return false; // Set up viewport. D3D11_VIEWPORT viewport; viewport.Width = (float)screenWidth; viewport.Height = (float)screenHeight; viewport.MinDepth = 0.0f; viewport.MaxDepth = 1.0f; viewport.TopLeftX = 0.0f; viewport.TopLeftY = 0.0f; m_deviceContext->RSSetViewports(1, &viewport); //---------------------------------------------------------------------------------------------- //---------------------------------------------------------------------------------------------- // Create blend states. D3D11_BLEND_DESC blendStateDesc; ZeroMemory(&blendStateDesc, sizeof(D3D11_BLEND_DESC)); blendStateDesc.RenderTarget[0].BlendEnable = TRUE; blendStateDesc.RenderTarget[0].SrcBlend = D3D11_BLEND_ONE; blendStateDesc.RenderTarget[0].DestBlend = D3D11_BLEND_ONE; 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; result = m_device->CreateBlendState(&blendStateDesc, &m_alphaEnableBlendingState); if(FAILED(result)) { return false; } blendStateDesc.RenderTarget[0].BlendEnable = FALSE; result = m_device->CreateBlendState(&blendStateDesc, &m_alphaDisableBlendingState); if(FAILED(result)) { return false; } //---------------------------------------------------------------------------------------------- return true; }
bool D3DClass::Initialize(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; // 保存垂直同步设置 m_vsync_enabled = vsync; // 创建一个DirectX graphics 接口工厂 result = CreateDXGIFactory(__uuidof(IDXGIFactory), (void**)&factory); if(FAILED(result)) return false; // 用接口工厂创建一个主显卡的适配 result =factory->EnumAdapters(0, &adapter); if(FAILED(result)) return false; // 得到主适配器的输出 result = adapter->EnumOutputs(0, &adapterOutput); if(FAILED(result)) return false; //得到适合 DXGI_FORMAT_R8G8B8A8_UNORM 的显示模式 result = adapterOutput->GetDisplayModeList(DXGI_FORMAT_R8G8B8A8_UNORM, DXGI_ENUM_MODES_INTERLACED, &numModes, nullptr); if(FAILED(result)) return false; displayModeList = new DXGI_MODE_DESC[numModes]; if(!displayModeList) return false; // 保存显示模式到displayModeList中 result = adapterOutput->GetDisplayModeList(DXGI_FORMAT_R8G8B8A8_UNORM, DXGI_ENUM_MODES_INTERLACED, &numModes, displayModeList); if(FAILED(result)) return false; // 遍历所有显示模式,得到刷新率两个参数值numerator 和 denominator for (int i = 0; i < numModes; i++) { if(displayModeList[i].Width == screenWidth) { numerator = displayModeList[i].RefreshRate.Numerator; denominator = displayModeList[i].RefreshRate.Denominator; } } // 得到显卡描述 result = adapter->GetDesc(&adapterDesc); if(FAILED(result)) return false; // 保存显存大小 m_videoCardMemory = (int)(adapterDesc.DedicatedVideoMemory / 1024 / 1024); //保存显卡描述串 error = wcstombs_s(&stringLength, m_videoCardDescription, 128, adapterDesc.Description, 128); if(error != 0) return false; // 释放显示模式列表 delete[] displayModeList; displayModeList = nullptr; //释放适配器输出 adapterOutput->Release(); adapterOutput = nullptr; //释放适配器 adapter->Release(); adapter = nullptr; //释放接口工厂 factory->Release(); factory = nullptr; //初始化交换链描述 ZeroMemory(&swapChainDesc, sizeof(swapChainDesc)); // 用1个后缓冲 swapChainDesc.BufferCount = 1; // 帧缓冲的大小和应用程序窗口大小相等 swapChainDesc.BufferDesc.Width = screenWidth; swapChainDesc.BufferDesc.Height = screenHeight; // 后缓冲的surface的格式为DXGI_FORMAT_R8G8B8A8_UNORM swapChainDesc.BufferDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM; // 如果使用垂直同步,设置后缓冲的刷新率 if(m_vsync_enabled) { swapChainDesc.BufferDesc.RefreshRate.Numerator = numerator; swapChainDesc.BufferDesc.RefreshRate.Denominator = denominator; } else { swapChainDesc.BufferDesc.RefreshRate.Numerator = 0; swapChainDesc.BufferDesc.RefreshRate.Denominator = 1; } // 设置后缓冲的用途 // 我们的渲染目标缓冲为后缓冲 swapChainDesc.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT; // 后缓冲输出的窗口句柄 swapChainDesc.OutputWindow = hwnd; // 不使用多重采样 swapChainDesc.SampleDesc.Count = 1; swapChainDesc.SampleDesc.Quality = 0; // 设置全屏或者窗口模式 if(fullscreen) swapChainDesc.Windowed = false; else swapChainDesc.Windowed = true; // 设定扫描线ordering以及缩放为unspecified swapChainDesc.BufferDesc.ScanlineOrdering = DXGI_MODE_SCANLINE_ORDER_UNSPECIFIED; swapChainDesc.BufferDesc.Scaling = DXGI_MODE_SCALING_UNSPECIFIED; // 后缓冲内容呈现到屏幕后,放弃其内容 swapChainDesc.SwapEffect = DXGI_SWAP_EFFECT_DISCARD; //不设置标志 swapChainDesc.Flags = 0; // 设置feature level为D3D11 // 如果显卡不支持D3D11,我们能够通过设置这个参数,使用D3D10,或者9 featureLevel = D3D_FEATURE_LEVEL_11_0; // 创建交换链,设备以及设备上下文 result = D3D11CreateDeviceAndSwapChain(nullptr, D3D_DRIVER_TYPE_HARDWARE, nullptr, 0, &featureLevel, 1, D3D11_SDK_VERSION, &swapChainDesc, &m_swapChain, &m_device, nullptr, &m_deviceContext); if(FAILED(result)) return false; // 得到交换链中的后缓冲指针 result = m_swapChain->GetBuffer(0, __uuidof(ID3D11Texture2D), (void**)&backBufferPtr); if(FAILED(result)) return false; // 用后缓冲创建渲染目标视图 result = m_device->CreateRenderTargetView(backBufferPtr, nullptr, &m_renderTargetView); if(FAILED(result)) return false; //释放后缓冲(引用计数减1) backBufferPtr->Release(); backBufferPtr = nullptr; // 初始化深度缓冲描述 ZeroMemory(&depthBufferDesc, sizeof(depthBufferDesc)); //设置深度缓冲描述 depthBufferDesc.Width = screenWidth; depthBufferDesc.Height = screenHeight; depthBufferDesc.MipLevels = 1; //对于深度缓冲为1 depthBufferDesc.ArraySize = 1; //对于深度缓冲为1,对于纹理,这2个参数有更多用途 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; // 创建深度缓冲 result = m_device->CreateTexture2D(&depthBufferDesc, nullptr, &m_depthStencilBuffer); if(FAILED(result)) return false; // 初始化深度模版状态描述 ZeroMemory(&depthStencilDesc, sizeof(depthStencilDesc)); // 设置深度模版状态描述 depthStencilDesc.DepthEnable = true; depthStencilDesc.DepthWriteMask = D3D11_DEPTH_WRITE_MASK_ALL; // D3D11_DEPTH_WRITE_MASK_ZERO禁止写深度缓冲 depthStencilDesc.DepthFunc = D3D11_COMPARISON_LESS; depthStencilDesc.StencilEnable = true; depthStencilDesc.StencilReadMask = 0xFF; depthStencilDesc.StencilWriteMask = 0xFF; // 对于front face 像素使用的模版操作操作 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; // 对于back face像素使用的模版操作模式 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; //创建深度模版状态 result = m_device->CreateDepthStencilState(&depthStencilDesc, &m_depthStencilState); if(FAILED(result)) return false; // 设置深度模版状态,使其生效 m_deviceContext->OMSetDepthStencilState(m_depthStencilState, 1); // 初始化深度模版视图 ZeroMemory(&depthStencilViewDesc, sizeof(depthStencilViewDesc)); // 设置深度模版视图描述 depthStencilViewDesc.Format = DXGI_FORMAT_D24_UNORM_S8_UINT; depthStencilViewDesc.ViewDimension = D3D11_DSV_DIMENSION_TEXTURE2D; depthStencilViewDesc.Texture2D.MipSlice = 0; // 创建深度模版视图 result = m_device->CreateDepthStencilView(m_depthStencilBuffer, &depthStencilViewDesc, &m_depthStencilView); if(FAILED(result)) return false; // 绑定渲染目标视图和深度缓冲到渲染管线 m_deviceContext->OMSetRenderTargets(1, &m_renderTargetView, m_depthStencilView); // 设置光栅化描述,指定多边形如何被渲染 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; // 创建光栅化状态 result = m_device->CreateRasterizerState(&rasterDesc, &m_rasterState); if(FAILED(result)) return false; // 设置光栅化状态,使其生效 m_deviceContext->RSSetState(m_rasterState); // 设置视口,显示全部后缓冲内容 viewport.Width = (FLOAT)screenWidth; viewport.Height = (FLOAT)screenHeight; viewport.MinDepth = 0.0f; viewport.MaxDepth = 1.0f; viewport.TopLeftX = 0.0f; viewport.TopLeftY = 0.0f; // 创建视口 m_deviceContext->RSSetViewports(1, &viewport); // 设置透视投影矩阵 fieldOfView = (float)D3DX_PI / 4.0f; screenAspect = (float)screenWidth / (float)screenHeight; // 创建透视投影矩阵 D3DXMatrixPerspectiveFovLH(&m_projectionMatrix, fieldOfView, screenAspect, screenNear, screenDepth); //初始化world矩阵为单位矩阵 //该矩阵实现局部坐标到世界坐标的转换 D3DXMatrixIdentity(&m_worldMatrix); // 创建正交投影矩阵,主要用来实施2D渲染 D3DXMatrixOrthoLH(&m_orthoMatrix, (float)screenWidth, (float)screenHeight, screenNear, screenDepth); return true; }
bool graphicD3d::Initialize(int screenWidth, int screenHeight, bool vsync, HWND hwnd, bool fullscreen, float screenDepth, float screenNear) { HRESULT hr; IDXGIFactory* factory; IDXGIAdapter* adapter; IDXGIOutput* adapterOutput; UINT nummodes, numerator, denominator; DXGI_MODE_DESC* displayModelist; DXGI_ADAPTER_DESC adapterDesc; DXGI_SWAP_CHAIN_DESC swapchainDesc; D3D11_TEXTURE2D_DESC depthBufferDesc; D3D11_DEPTH_STENCIL_DESC depthStencilDesc; D3D11_DEPTH_STENCIL_VIEW_DESC depthStencilViewDesc; D3D11_RASTERIZER_DESC rasterDesc; D3D11_VIEWPORT viewport; // 수직동기화 설정 ( true / false ) m_vsync = vsync; //DirectX Graphic Infrastructure 인터페이스 팩토리 만들기. hr = CreateDXGIFactory(__uuidof(IDXGIFactory), (void**)&factory); if (FAILED(hr)) return false; //첫번째 그래픽 카드 어댑터 만들기. hr = factory->EnumAdapters(0, &adapter); if (FAILED(hr)) return false; //첫번째 모니터의 어댑터 만들기. hr = adapter->EnumOutputs(0, &adapterOutput); if (FAILED(hr)) return false; //DXGI_FORMAT_R8G8B8A8_UNORM 모니터 출력 포멧에 맞는 모드의 개수 구하기. hr = adapterOutput->GetDisplayModeList(DXGI_FORMAT_R8G8B8A8_UNORM, DXGI_ENUM_MODES_INTERLACED, &nummodes, NULL); if (FAILED(hr)) return false; //사용 가능한 모든 모니터와 그래픽카드 조합을 저장할 리스트 생성. displayModelist = new DXGI_MODE_DESC[nummodes]; if (!displayModelist) return false; //displayModelist 에 값들 채워넣기. hr = adapterOutput->GetDisplayModeList(DXGI_FORMAT_R8G8B8A8_UNORM, DXGI_ENUM_MODES_INTERLACED, &nummodes, displayModelist); if (FAILED(hr)) return false; //그래픽 카드와 모니터의 화면 너비/높이 조합을 찾기 완료. //모니터의 refresh rate 의 분모 와 분자 값을 저장. for (int i = 0; i < nummodes; i++) { if (displayModelist[i].Width == (UINT)screenWidth && displayModelist[i].Height == (UINT)screenHeight) { numerator = displayModelist[i].RefreshRate.Numerator; denominator = displayModelist[i].RefreshRate.Denominator; } } /* */ //그래픽 카드 정보 가져오기. hr = adapter->GetDesc(&adapterDesc); if (FAILED(hr)) return false; //그래픽 카드 메모리 크기 가져오기. ( MegaBytes ) m_videoMemory = UINT(adapterDesc.DedicatedVideoMemory / 1024 / 1024); //그래픽 카드 이름 가져오기. lstrcpynW(m_videoDescription, adapterDesc.Description, 128); /* */ // 원하는 정보 조회 끝나면, 해당 리소스들 해제 delete [] displayModelist; displayModelist = nullptr; //모니터 출력 어댑터 해제 adapterOutput->Release(); adapterOutput = nullptr; //그래픽카드 어댑터 해제 adapter->Release(); adapter = nullptr; //팩토리 해제 factory->Release(); factory = nullptr; /* 스왑체인 설정 */ ZeroMemory( &swapchainDesc, sizeof( swapchainDesc ) ); //백버퍼 개수를 1개로 설정. swapchainDesc.BufferCount = 1; swapchainDesc.BufferDesc.Width = screenWidth; swapchainDesc.BufferDesc.Height = screenHeight; swapchainDesc.BufferDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM; if (m_vsync) { //vsync 수치에 맞춰서 page flip 이 일어난다. swapchainDesc.BufferDesc.RefreshRate.Numerator = numerator; swapchainDesc.BufferDesc.RefreshRate.Denominator = denominator; } else { //vsync 와 상관없이 최대한 많이 그리게 한다. swapchainDesc.BufferDesc.RefreshRate.Numerator = 0; swapchainDesc.BufferDesc.RefreshRate.Denominator = 1; } // 백버퍼를 렌더 타겟 용도로 사용 설정. swapchainDesc.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT; swapchainDesc.OutputWindow = hwnd; //멀티샘플링 설정을 안함. swapchainDesc.SampleDesc.Count = 1; swapchainDesc.SampleDesc.Quality = 0; //전체화면 모드 창 모드 설정. if (fullscreen) { swapchainDesc.Windowed = FALSE; } else { swapchainDesc.Windowed = TRUE; } //스캔라인 정렬 및 사용여부를 안함 (unspecified) 으로 설정. swapchainDesc.BufferDesc.ScanlineOrdering = DXGI_MODE_SCANLINE_ORDER_UNSPECIFIED; swapchainDesc.BufferDesc.Scaling = DXGI_MODE_SCALING_UNSPECIFIED; //출력 후 백버퍼 내용 버림으로 설정. swapchainDesc.SwapEffect = DXGI_SWAP_EFFECT_DISCARD; //추가 옵션 플랙 사용 안함. swapchainDesc.Flags = 0; /* 디바이스 설정 */ UINT createDeviceFlags = 0; #ifdef _DEBUG createDeviceFlags |= D3D11_CREATE_DEVICE_DEBUG; #endif //그래픽 카드가 dx11 지원되면 HARDWARE, //실패하면 REFERENCE 로 처리된다. ( 속도는 HARDWARE 대비 1/1000 정도 느림 ) D3D_DRIVER_TYPE driverTypes[] = { D3D_DRIVER_TYPE_HARDWARE, D3D_DRIVER_TYPE_WARP, D3D_DRIVER_TYPE_REFERENCE, }; UINT numDriverTypes = ARRAYSIZE( driverTypes ); //directx 버젼 설정 D3D_FEATURE_LEVEL featureLevels[] = { D3D_FEATURE_LEVEL_11_0, D3D_FEATURE_LEVEL_10_1, D3D_FEATURE_LEVEL_10_0, }; UINT numFeatureLevels = ARRAYSIZE( featureLevels ); for( UINT driverTypeIndex = 0; driverTypeIndex < numDriverTypes; driverTypeIndex++ ) { m_driverType = driverTypes[driverTypeIndex]; hr = D3D11CreateDeviceAndSwapChain( NULL, m_driverType, NULL, createDeviceFlags, featureLevels, numFeatureLevels, D3D11_SDK_VERSION, &swapchainDesc, &m_swapChain, &m_device, &m_featureLevel, &m_deviceContext ); if( SUCCEEDED( hr ) ) break; } if( FAILED( hr ) ) return false; /* 렌더타겟뷰 (render target view) 만들기 */ //백버퍼 포인터를 가져오기. ID3D11Texture2D* pBackBuffer = NULL; hr = m_swapChain->GetBuffer(0, __uuidof(ID3D11Texture2D), (LPVOID*)&pBackBuffer); if( FAILED( hr ) ) return false; //백버퍼 포인터로 렌더타겟뷰 생성. hr = m_device->CreateRenderTargetView( pBackBuffer, NULL, &m_renderTargetView ); if( FAILED( hr ) ) return false; //렌더타겟 생성되면 백버퍼 포인터 필요없으므로 제거. pBackBuffer->Release(); pBackBuffer = nullptr; /* 깊이버퍼 (depth buffer) 만들기 (옵션) */ ZeroMemory(&depthBufferDesc, sizeof(depthBufferDesc)); 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; //깊이버퍼 2D텍스쳐 생성 hr = m_device->CreateTexture2D(&depthBufferDesc, NULL, &m_depthStencilbuffer); if (FAILED(hr)) return false; /* 깊이 스텐실 정의 (옵션) */ ZeroMemory(&depthStencilDesc, sizeof(depthStencilDesc)); depthStencilDesc.DepthEnable = true; depthStencilDesc.DepthWriteMask = D3D11_DEPTH_WRITE_MASK_ALL; depthStencilDesc.DepthFunc = D3D11_COMPARISON_LESS; depthStencilDesc.StencilEnable = true; depthStencilDesc.StencilReadMask = 0xFF; depthStencilDesc.StencilWriteMask = 0xFF; //픽셀 전면부 스텐실 연산 처리 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; //픽셀 후면부 스텐실 연산 처리 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; //깊이 스텐실 상태 생성 hr = m_device->CreateDepthStencilState(&depthStencilDesc, &m_depthStencilState); if (FAILED(hr)) return false; //디바이스 컨텍스트에 깊이 스텐실 상태 적용. m_deviceContext->OMSetDepthStencilState(m_depthStencilState, 1); /* 깊이 스텐실 뷰 만들기 */ ZeroMemory(&depthStencilViewDesc, sizeof(depthStencilViewDesc)); depthStencilViewDesc.Format = DXGI_FORMAT_D24_UNORM_S8_UINT; depthStencilViewDesc.ViewDimension = D3D11_DSV_DIMENSION_TEXTURE2D; depthStencilViewDesc.Texture2D.MipSlice = 0; // 깊이-스텐실 뷰를 생성. hr = m_device->CreateDepthStencilView(m_depthStencilbuffer, &depthStencilViewDesc, &m_depthStencilView); if (FAILED(hr)) return false; /* 디바이스 컨텍스트에 렌더타겟뷰 와 깊이스텐실뷰를 적용. */ m_deviceContext->OMSetRenderTargets(1, &m_renderTargetView, m_depthStencilView); /* 래스터라이징 설정 (옵션) - 도형을 어떻게 그릴지 결정 ( 와이어프레임, 2 side 렌더링 등등.. ) */ 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; //디바이스로 래스터라이징 상태 생성. hr = m_device->CreateRasterizerState(&rasterDesc, &m_rasterState); if (FAILED(hr)) return false; //디바이스 컨텍스트로 래스터라이징 상태 적용. m_deviceContext->RSSetState(m_rasterState); /* 뷰포트 생성 */ viewport.Width = (FLOAT)screenWidth; viewport.Height = (FLOAT)screenHeight; viewport.MinDepth = 0.0f; viewport.MaxDepth = 1.0f; viewport.TopLeftX = 0; viewport.TopLeftY = 0; m_deviceContext->RSSetViewports( 1, &viewport ); /* 투영 행렬 ( projection matrix ) 생성 - 3d 화면을 2d 뷰포트 공간으로 변환 - 복사본으로 셰이더에서 사용 할 수 있게 한다. */ float fieldOfView = (float)XM_PI / 4.0f; float screenAspect = (float)screenWidth / (float)screenHeight; m_projectionMatrix = XMMatrixPerspectiveFovLH(fieldOfView, screenAspect, screenNear, screenDepth); /* 월드 행렬 ( world matrix ) 생성 - 오브젝트들을 3d 좌표로 변환하기 위한 행렬 - 이동 / 회전 / 크기 에 사용. - 복사본으로 셰이더에 사용 할 수 있게 한다. */ // 월드 행렬을 단위 행렬로 초기화 m_worldMatrix = XMMatrixIdentity(); /* 뷰 행렬 ( view matrix ) - 카메라에서 따로 생성하기 위해 일단 생략. */ /* 정사영 행렬 ( Orthographic matix 생성 ) - 원근감이 없는 행렬 - 2d 이미지나 UI 등을 표현할 때 사용. */ // 2D 렌더링에 사용될 정사영 행렬을 생성. m_orthoMatrix = XMMatrixOrthographicLH((float)screenWidth, (float)screenHeight, screenNear, screenDepth); return true; }
// FIXME: split into multiple methods for readability bool D3DBase::init( int screenWidth, int screenHeight, const bool vsync, HWND hwnd, const bool fullscreen, const float screenDepth, const float screenNear ) { HRESULT result; m_vsyncEnabled = vsync; // Get refresh rates and find a correct one to use // ---------------------------------------------------------------------- ComPtr<IDXGIFactory> factory; ComPtr<IDXGIAdapter> adapter; ComPtr<IDXGIOutput> adapterOutput; unsigned int numModes; result = CreateDXGIFactory(__uuidof(IDXGIFactory), (void**)&factory); if (FAILED(result)) { return false; } result = factory->EnumAdapters(0, &adapter); if (FAILED(result)) { return false; } result = adapter->EnumOutputs(0, &adapterOutput); if (FAILED(result)) { return false; } result = adapterOutput->GetDisplayModeList(DXGI_FORMAT_B8G8R8A8_UNORM, DXGI_ENUM_MODES_INTERLACED, &numModes, NULL); if (FAILED(result)) { return false; } DXGI_MODE_DESC* displayModeList = new DXGI_MODE_DESC[numModes]; if(!displayModeList) { return false; } result = adapterOutput->GetDisplayModeList(DXGI_FORMAT_B8G8R8A8_UNORM, DXGI_ENUM_MODES_INTERLACED, &numModes, displayModeList); if (FAILED(result)) { return false; } // Find correct display mode unsigned int numerator; unsigned int denominator; for (unsigned int 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 GPU name and memory DXGI_ADAPTER_DESC adapterDesc; result = adapter->GetDesc(&adapterDesc); if (FAILED(result)) { return false; } // Store memory in megabytes m_gpuMemory = (int) (adapterDesc.DedicatedVideoMemory / 1000 / 1000); // Get GPU name char gpuDescription[128]; size_t stringLength; int error = wcstombs_s(&stringLength, gpuDescription, 128, adapterDesc.Description, 128); if (error != 0) { return false; } m_gpuDescription = std::string(gpuDescription); // Clean up delete[] displayModeList; adapterOutput = nullptr; adapter = nullptr; factory = nullptr; //------------------------------------------------------------------------------ // Start actual directx initialization // ------------------------------------------------------------------------------------ // Swap chain DXGI_SWAP_CHAIN_DESC swapChainDesc; ZeroMemory(&swapChainDesc, sizeof(swapChainDesc)); swapChainDesc.BufferCount = 1; swapChainDesc.BufferDesc.Width = screenWidth; swapChainDesc.BufferDesc.Height = screenHeight; swapChainDesc.BufferDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM; if (m_vsyncEnabled) { swapChainDesc.BufferDesc.RefreshRate.Numerator = numerator; swapChainDesc.BufferDesc.RefreshRate.Denominator = denominator; } else { swapChainDesc.BufferDesc.RefreshRate.Numerator = 0; swapChainDesc.BufferDesc.RefreshRate.Denominator = 1; } swapChainDesc.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT; swapChainDesc.OutputWindow = hwnd; // no multisampling = 1, 0 swapChainDesc.SampleDesc.Count = 1; swapChainDesc.SampleDesc.Quality = 0; if (fullscreen) { swapChainDesc.Windowed = false; } else { swapChainDesc.Windowed = true; } swapChainDesc.BufferDesc.ScanlineOrdering = DXGI_MODE_SCANLINE_ORDER_UNSPECIFIED; swapChainDesc.BufferDesc.Scaling = DXGI_MODE_SCALING_UNSPECIFIED; swapChainDesc.SwapEffect = DXGI_SWAP_EFFECT_DISCARD; swapChainDesc.Flags = 0; // Set the feature level (change to 10 or 9 for backwards compatibility) D3D_FEATURE_LEVEL featureLevel = D3D_FEATURE_LEVEL_11_0; // Finally create the device (note it's directX version specific) result = D3D11CreateDeviceAndSwapChain(NULL, D3D_DRIVER_TYPE_HARDWARE, NULL, D3D11_CREATE_DEVICE_DEBUG, &featureLevel, 1, D3D11_SDK_VERSION, &swapChainDesc, &m_swapChain, &m_device, NULL, &m_deviceContext); if (FAILED(result)) { return false; } // Back buffer ComPtr<ID3D11Texture2D> backBufferPtr; result = m_swapChain->GetBuffer(0, __uuidof(ID3D11Texture2D), (LPVOID*) &backBufferPtr); if (FAILED(result)) { return false; } result = m_device->CreateRenderTargetView(backBufferPtr.Get(), NULL, m_renderTargetView.GetAddressOf()); if (FAILED(result)) { return false; } backBufferPtr = nullptr; // -- Back buffer // Depth buffer // Initialize the description of the depth buffer. D3D11_TEXTURE2D_DESC depthBufferDesc; 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; // 1 depthBufferDesc.SampleDesc.Quality = 0; // 0 depthBufferDesc.Usage = D3D11_USAGE_DEFAULT; depthBufferDesc.BindFlags = D3D11_BIND_DEPTH_STENCIL; depthBufferDesc.CPUAccessFlags = 0; depthBufferDesc.MiscFlags = 0; result = m_device->CreateTexture2D(&depthBufferDesc, NULL, &m_depthStencilBuffer); if (FAILED(result)) { return false; } // -- Depth Stencil // Initialize the description of the stencil state. D3D11_DEPTH_STENCIL_DESC depthStencilDesc; 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 depth stencil state result = m_device->CreateDepthStencilState(&depthStencilDesc, &m_depthStencilState); if (FAILED(result)) { return false; } m_deviceContext->OMSetDepthStencilState(m_depthStencilState.Get(), 1); // Initialize depth stencil view D3D11_DEPTH_STENCIL_VIEW_DESC depthStencilViewDesc; ZeroMemory(&depthStencilViewDesc, sizeof(depthStencilViewDesc)); depthStencilViewDesc.Format = DXGI_FORMAT_D24_UNORM_S8_UINT; depthStencilViewDesc.ViewDimension = D3D11_DSV_DIMENSION_TEXTURE2D; depthStencilViewDesc.Texture2D.MipSlice = 0; // Create depth stencil view result = m_device->CreateDepthStencilView(m_depthStencilBuffer.Get(), &depthStencilViewDesc, &m_depthStencilView); // Bind render target view m_deviceContext->OMSetRenderTargets(1, m_renderTargetView.GetAddressOf(), m_depthStencilView.Get()); // -- Rasterizer state // Setup the raster description which will determine how and what polygons will be drawn. D3D11_RASTERIZER_DESC rasterizerDesc; rasterizerDesc.AntialiasedLineEnable = false; rasterizerDesc.CullMode = D3D11_CULL_BACK; rasterizerDesc.DepthBias = 0; rasterizerDesc.DepthBiasClamp = 0.0f; rasterizerDesc.DepthClipEnable = true; rasterizerDesc.FillMode = D3D11_FILL_SOLID; // D3D11_FILL_WIREFRAME for wireframe rasterizerDesc.FrontCounterClockwise = false; rasterizerDesc.MultisampleEnable = false; // false rasterizerDesc.ScissorEnable = false; rasterizerDesc.SlopeScaledDepthBias = 0.0f; result = m_device->CreateRasterizerState(&rasterizerDesc, &m_rasterizerState); if(FAILED(result)) { return false; } m_deviceContext->RSSetState(m_rasterizerState.Get()); // Setup the viewport D3D11_VIEWPORT viewport; viewport.Width = static_cast<float>(screenWidth); viewport.Height = static_cast<float>(screenHeight); viewport.MinDepth = 0.0f; viewport.MaxDepth = 1.0f; viewport.TopLeftX = 0; viewport.TopLeftY = 0; // Create the viewport. m_deviceContext->RSSetViewports(1, &viewport); // Setup projection matrix float fov = (float) D3DX_PI / 4.0f; float aspectRatio = (float) screenWidth / (float) screenHeight; D3DXMatrixPerspectiveFovLH(&m_projectionMatrix, fov, aspectRatio, screenNear, screenDepth); // Initialize world matrix D3DXMatrixIdentity(&m_worldMatrix); // Create camera here // Create an orthographic projection matrix for 2D rendering D3DXMatrixOrthoLH(&m_orthoMatrix, (float) screenWidth, (float) screenHeight, screenNear, screenDepth); // Depth stencil stuff // ---------------------------------------------------------------------------------------------- D3D11_DEPTH_STENCIL_DESC depthDisabledStencilDesc; ZeroMemory(&depthDisabledStencilDesc, sizeof(depthDisabledStencilDesc)); // Create second depth stencil state which turns off the Z buffer for 2D rendering 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 = m_device->CreateDepthStencilState(&depthDisabledStencilDesc, &m_disableDepthStencilState); if (FAILED(result)) { return false; } return true; }
//************************************************************************************************* // Create the device //************************************************************************************************* SBOOL RenderContext::createDevice() { // Create the device and device context UINT createDeviceFlags = 0; #if defined(DEBUG) || defined(_DEBUG) //createDeviceFlags |= D3D11_CREATE_DEVICE_DEBUG; #endif HRESULT hr = S_OK; // Set the desired feature level D3D_FEATURE_LEVEL featureLevel = D3D_FEATURE_LEVEL_11_0; D3D_FEATURE_LEVEL targetLevels[] = { D3D_FEATURE_LEVEL_11_0 }; SUINT numFeatureLevels = 1; // Create a device factory so that we can find a DX11 compatible device IDXGIFactory* factory = 0; IDXGIAdapter* adapter = 0; hr = CreateDXGIFactory(__uuidof(IDXGIFactory), reinterpret_cast<void**>(&factory)); if(FAILED(hr)) { MessageBox(0, "Failed to create IDXGIFactory.", 0, 0); return false; } // Get selected device if it is part of the config Configuration* config = ConfigurationManager::getSingletonPtr()->getConfiguration("Engine"); String configAdapter = config->retrieveValue("adapter"); // Iterate through adapters to find a compatible one DXGI_ADAPTER_DESC adapterDesc; for(SINT i = 0; factory->EnumAdapters(i, &adapter) != DXGI_ERROR_NOT_FOUND; ++i) { // Get the adapter description adapter->GetDesc(&adapterDesc); // See whether this adapter matches the one we selected if(configAdapter == adapterDesc.Description) { // Use this adapter break; } } if(adapter) { // Create the device using the specified adapter _d3dDriverType = D3D_DRIVER_TYPE_UNKNOWN; hr = D3D11CreateDevice( adapter, // Selected adapter _d3dDriverType, 0, createDeviceFlags, // Support debug mode targetLevels, // Target feature levels numFeatureLevels, // Number of supported feature levels D3D11_SDK_VERSION, &_d3dDevice, &featureLevel, &_d3dImmediateContext ); } else { _d3dDriverType = D3D_DRIVER_TYPE_HARDWARE; hr = D3D11CreateDevice( 0, _d3dDriverType, 0, createDeviceFlags, targetLevels, numFeatureLevels, D3D11_SDK_VERSION, &_d3dDevice, &featureLevel, &_d3dImmediateContext ); } if(FAILED(hr)) { MessageBox(0, "D3DCreateDevice Failed", 0, 0); return false; } // Check for DX11 support if(featureLevel != D3D_FEATURE_LEVEL_11_0) { MessageBox(0, "DirectX 11 is not supported on this device", 0, 0); return false; } // Creation of device succeeded return true; }
static void test_create_factory(void) { IDXGIFactory1 *factory; IUnknown *iface; HRESULT hr; iface = (void *)0xdeadbeef; hr = CreateDXGIFactory(&IID_IDXGIDevice, (void **)&iface); ok(hr == E_NOINTERFACE, "Got unexpected hr %#x.\n", hr); ok(!iface, "Got unexpected iface %p.\n", iface); hr = CreateDXGIFactory(&IID_IUnknown, (void **)&iface); ok(SUCCEEDED(hr), "Failed to create factory with IID_IUnknown, hr %#x.\n", hr); IUnknown_Release(iface); hr = CreateDXGIFactory(&IID_IDXGIObject, (void **)&iface); ok(SUCCEEDED(hr), "Failed to create factory with IID_IDXGIObject, hr %#x.\n", hr); IUnknown_Release(iface); factory = (void *)0xdeadbeef; hr = CreateDXGIFactory(&IID_IDXGIFactory, (void **)&iface); ok(SUCCEEDED(hr), "Failed to create factory with IID_IDXGIFactory, hr %#x.\n", hr); hr = IUnknown_QueryInterface(iface, &IID_IDXGIFactory1, (void **)&factory); ok(hr == E_NOINTERFACE, "Got unexpected hr %#x.\n", hr); ok(!factory, "Got unexpected factory %p.\n", factory); IUnknown_Release(iface); iface = (void *)0xdeadbeef; hr = CreateDXGIFactory(&IID_IDXGIFactory1, (void **)&iface); ok(hr == E_NOINTERFACE, "Got unexpected hr %#x.\n", hr); ok(!iface, "Got unexpected iface %p.\n", iface); if (!pCreateDXGIFactory1) { win_skip("CreateDXGIFactory1 not available, skipping tests.\n"); return; } iface = (void *)0xdeadbeef; hr = pCreateDXGIFactory1(&IID_IDXGIDevice, (void **)&iface); ok(hr == E_NOINTERFACE, "Got unexpected hr %#x.\n", hr); ok(!iface, "Got unexpected iface %p.\n", iface); hr = pCreateDXGIFactory1(&IID_IUnknown, (void **)&iface); ok(SUCCEEDED(hr), "Failed to create factory with IID_IUnknown, hr %#x.\n", hr); IUnknown_Release(iface); hr = pCreateDXGIFactory1(&IID_IDXGIObject, (void **)&iface); ok(SUCCEEDED(hr), "Failed to create factory with IID_IDXGIObject, hr %#x.\n", hr); IUnknown_Release(iface); hr = pCreateDXGIFactory1(&IID_IDXGIFactory, (void **)&iface); ok(SUCCEEDED(hr), "Failed to create factory with IID_IDXGIFactory, hr %#x.\n", hr); hr = IUnknown_QueryInterface(iface, &IID_IDXGIFactory1, (void **)&factory); ok(SUCCEEDED(hr), "Failed to query IDXGIFactory1 interface, hr %#x.\n", hr); IDXGIFactory1_Release(factory); IUnknown_Release(iface); hr = pCreateDXGIFactory1(&IID_IDXGIFactory1, (void **)&iface); ok(SUCCEEDED(hr), "Failed to create factory with IID_IDXGIFactory1, hr %#x.\n", hr); IUnknown_Release(iface); }
void D3D11Render::init_device() { ////////////////////////Create buffer desc//////////////////////////// RECT rect; GetClientRect(getHwnd(), &rect); DXGI_MODE_DESC bufferDesc; ZeroMemory(&bufferDesc, sizeof(DXGI_MODE_DESC)); bufferDesc.Width = rect.right - rect.left; bufferDesc.Height = rect.bottom - rect.top; bufferDesc.RefreshRate.Numerator = 60; bufferDesc.RefreshRate.Denominator = 1; bufferDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM; bufferDesc.ScanlineOrdering = DXGI_MODE_SCANLINE_ORDER_UNSPECIFIED; bufferDesc.Scaling = DXGI_MODE_SCALING_UNSPECIFIED; //Create swapChain Desc DXGI_SWAP_CHAIN_DESC swapChainDesc; ZeroMemory(&swapChainDesc, sizeof(DXGI_SWAP_CHAIN_DESC)); swapChainDesc.BufferDesc = bufferDesc; swapChainDesc.SampleDesc.Count = 1; swapChainDesc.SampleDesc.Quality = 0; swapChainDesc.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT; swapChainDesc.BufferCount = 1; swapChainDesc.OutputWindow = getHwnd(); swapChainDesc.Windowed = TRUE; swapChainDesc.SwapEffect = DXGI_SWAP_EFFECT_DISCARD; /////////////////////////////////////////////////////////////////////////// HRESULT hr; //Create the double buffer chain hr = D3D11CreateDeviceAndSwapChain(NULL, D3D_DRIVER_TYPE_HARDWARE, NULL, NULL, NULL, NULL, D3D11_SDK_VERSION, &swapChainDesc, &m_pSwapChain, &m_pD3D11Device, NULL, &m_pD3D11DeviceContext); //DebugHR(hr); //Create back buffer, buffer also is a texture ID3D11Texture2D *pBackBuffer; hr = m_pSwapChain->GetBuffer(0, __uuidof(ID3D11Texture2D), (void**)&pBackBuffer); hr = m_pD3D11Device->CreateRenderTargetView(pBackBuffer, NULL, &m_pRenderTargetView); pBackBuffer->Release(); //DebugHR(hr); ///////////////////////////Creaete Depth/Stencil Buffer///////////////////////////////// D3D11_TEXTURE2D_DESC depthStencilDesc; depthStencilDesc.Width = rect.right - rect.left; depthStencilDesc.Height = rect.bottom - rect.top; depthStencilDesc.MipLevels = 1; depthStencilDesc.ArraySize = 1; depthStencilDesc.Format = DXGI_FORMAT_D24_UNORM_S8_UINT; depthStencilDesc.SampleDesc.Count = 1; depthStencilDesc.SampleDesc.Quality = 0; depthStencilDesc.Usage = D3D11_USAGE_DEFAULT; depthStencilDesc.BindFlags = D3D11_BIND_DEPTH_STENCIL; depthStencilDesc.CPUAccessFlags = 0; depthStencilDesc.MiscFlags = 0; m_pD3D11Device->CreateTexture2D(&depthStencilDesc, NULL, &m_pDepthStencilBuffer); m_pD3D11Device->CreateDepthStencilView(m_pDepthStencilBuffer, NULL, &m_pDepthStencilView); m_pD3D11DeviceContext->OMSetRenderTargets(1, &m_pRenderTargetView, m_pDepthStencilView); // Setup the raster description which will determine how and what polygons will be drawn. D3D11_RASTERIZER_DESC rasterDesc; 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. hr = m_pD3D11Device->CreateRasterizerState(&rasterDesc, &m_pRasterState); //DebugHR(hr); /////////////////////////////////////////////////////////////////////////////// unsigned int numModes, i, numerator, denominator, stringLength; IDXGIFactory* factory; IDXGIAdapter* adapter; IDXGISurface *surface; DXGI_ADAPTER_DESC adapterDesc; // Create a DirectX graphics interface factory. CreateDXGIFactory(__uuidof(IDXGIFactory), (void**)&factory); // Use the factory to create an adapter for the primary graphics interface (video card). factory->EnumAdapters(0, &adapter); adapter->GetDesc(&adapterDesc); m_videoCardMemory = (int)(adapterDesc.DedicatedVideoMemory / 1024 / 1024); // Convert the name of the video card to a character array and store it. m_videoCardInfo = std::wstring(L"Video Card: ") + adapterDesc.Description; }
HRESULT WINAPI D3D11CreateDevice(IDXGIAdapter *adapter, D3D_DRIVER_TYPE driver_type, HMODULE swrast, UINT flags, const D3D_FEATURE_LEVEL *feature_levels, UINT levels, UINT sdk_version, ID3D11Device **device_out, D3D_FEATURE_LEVEL *obtained_feature_level, ID3D11DeviceContext **immediate_context) { IDXGIFactory *factory; ID3D11Device *device; HRESULT hr; TRACE("adapter %p, driver_type %s, swrast %p, flags %#x, feature_levels %p, levels %u, sdk_version %u, " "device %p, obtained_feature_level %p, immediate_context %p.\n", adapter, debug_d3d_driver_type(driver_type), swrast, flags, feature_levels, levels, sdk_version, device_out, obtained_feature_level, immediate_context); if (device_out) *device_out = NULL; if (obtained_feature_level) *obtained_feature_level = 0; if (immediate_context) *immediate_context = NULL; if (adapter) { IDXGIAdapter_AddRef(adapter); hr = IDXGIAdapter_GetParent(adapter, &IID_IDXGIFactory, (void **)&factory); if (FAILED(hr)) { WARN("Failed to get dxgi factory, returning %#x.\n", hr); return hr; } } else { hr = CreateDXGIFactory(&IID_IDXGIFactory, (void **)&factory); if (FAILED(hr)) { WARN("Failed to create dxgi factory, returning %#x.\n", hr); return hr; } switch(driver_type) { case D3D_DRIVER_TYPE_HARDWARE: { hr = IDXGIFactory_EnumAdapters(factory, 0, &adapter); if (FAILED(hr)) { WARN("No adapters found, returning %#x.\n", hr); IDXGIFactory_Release(factory); return hr; } break; } case D3D_DRIVER_TYPE_NULL: FIXME("NULL device not implemented, falling back to refrast.\n"); /* fall through, for now */ case D3D_DRIVER_TYPE_REFERENCE: { HMODULE refrast = LoadLibraryA("d3d11ref.dll"); if (!refrast) { WARN("Failed to load refrast, returning E_FAIL.\n"); IDXGIFactory_Release(factory); return E_FAIL; } hr = IDXGIFactory_CreateSoftwareAdapter(factory, refrast, &adapter); FreeLibrary(refrast); if (FAILED(hr)) { WARN("Failed to create a software adapter, returning %#x.\n", hr); IDXGIFactory_Release(factory); return hr; } break; } case D3D_DRIVER_TYPE_SOFTWARE: { if (!swrast) { WARN("Software device requested, but NULL swrast passed, returning E_FAIL.\n"); IDXGIFactory_Release(factory); return E_FAIL; } hr = IDXGIFactory_CreateSoftwareAdapter(factory, swrast, &adapter); if (FAILED(hr)) { WARN("Failed to create a software adapter, returning %#x.\n", hr); IDXGIFactory_Release(factory); return hr; } break; } default: FIXME("Unhandled driver type %#x.\n", driver_type); IDXGIFactory_Release(factory); return E_FAIL; } } hr = D3D11CoreCreateDevice(factory, adapter, flags, feature_levels, levels, &device); IDXGIAdapter_Release(adapter); IDXGIFactory_Release(factory); if (FAILED(hr)) { WARN("Failed to create a device, returning %#x.\n", hr); return hr; } TRACE("Created ID3D11Device %p.\n", device); if (obtained_feature_level) *obtained_feature_level = ID3D11Device_GetFeatureLevel(device); if (immediate_context) ID3D11Device_GetImmediateContext(device, immediate_context); if (device_out) *device_out = device; else ID3D11Device_Release(device); return S_OK; }
bool D3DRenderer::Initialize( int screenWidth, int screenHeight, bool vsync, HWND hwnd, bool fullscreen, float screenFar, float screenNear ) { // Store the vsync setting. m_vsync_enabled = vsync; // Create a DirectX graphics interface factory. IDXGIFactory* factory; CHECK( CreateDXGIFactory(__uuidof(IDXGIFactory), (void**)&factory) ); // Use the factory to create an adapter for the primary graphics interface (video card). IDXGIAdapter* adapter; CHECK( factory->EnumAdapters( 0, &adapter ) ); // Enumerate the primary adapter output (monitor). IDXGIOutput* adapterOutput; CHECK( adapter->EnumOutputs( 0, &adapterOutput ) ); // Get the number of modes that fit the DXGI_FORMAT_R8G8B8A8_UNORM display format for the adapter output (monitor). unsigned numModes; CHECK( adapterOutput->GetDisplayModeList( DXGI_FORMAT_R8G8B8A8_UNORM, DXGI_ENUM_MODES_INTERLACED, &numModes, 0 ) ); // Create a list to hold all the possible display modes for this monitor/video card combination. DXGI_MODE_DESC* displayModeList = new DXGI_MODE_DESC[numModes]; if(!displayModeList) return false; // Now fill the display mode list structures. CHECK( adapterOutput->GetDisplayModeList( DXGI_FORMAT_R8G8B8A8_UNORM, DXGI_ENUM_MODES_INTERLACED, &numModes, displayModeList ) ); // Now go through all the display 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. unsigned numerator, denominator; for( unsigned i = 0; i < numModes; ++i ) { if(displayModeList[i].Width == (unsigned)screenWidth) { if(displayModeList[i].Height == (unsigned)screenHeight) { numerator = displayModeList[i].RefreshRate.Numerator; denominator = displayModeList[i].RefreshRate.Denominator; } } } // Get the adapter (video card) description. DXGI_ADAPTER_DESC adapterDesc; CHECK( adapter->GetDesc(&adapterDesc) ); // Release the display mode list. delete [] displayModeList; displayModeList = 0; // Release the adapter output. ReleaseCOM(adapterOutput); ReleaseCOM(adapter); ReleaseCOM(factory); DXGI_SWAP_CHAIN_DESC swapChainDesc; // Initialize 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(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 of the back buffer. swapChainDesc.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT; // Set the handle for the window to render to. swapChainDesc.OutputWindow = hwnd; // Turn multi-sampling off. swapChainDesc.SampleDesc.Count = 1; swapChainDesc.SampleDesc.Quality = 0; // Set to full screen or windowed mode. 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 presenting. swapChainDesc.SwapEffect = DXGI_SWAP_EFFECT_DISCARD; // Don't set the advanced flags. swapChainDesc.Flags = 0; // Set the feature level to DirectX 11. D3D_FEATURE_LEVEL featureLevel = D3D_FEATURE_LEVEL_11_0; // Create the swap chain, Direct3D device, and Direct3D device context. CHECK( D3D11CreateDeviceAndSwapChain(0, D3D_DRIVER_TYPE_HARDWARE, 0, 0, &featureLevel, 1, D3D11_SDK_VERSION, &swapChainDesc, &m_swapChain, &m_device, 0, &m_deviceContext)); // Get the pointer to the back buffer. ID3D11Texture2D* backBufferPtr; CHECK( m_swapChain->GetBuffer(0, __uuidof(ID3D11Texture2D), (LPVOID*)&backBufferPtr) ); // Create the render target view with the back buffer pointer. CHECK( m_device->CreateRenderTargetView(backBufferPtr, 0, &m_renderTargetView) ); // Release pointer to the back buffer as we no longer need it. ReleaseCOM( backBufferPtr ); // Initialize the description of the depth buffer. D3D11_TEXTURE2D_DESC depthBufferDesc; 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 depth/stencil buffer CHECK( m_device->CreateTexture2D(&depthBufferDesc, 0, &m_depthStencilBuffer) ); // Initialize the description of the stencil state. D3D11_DEPTH_STENCIL_DESC depthStencilDesc; 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. CHECK( m_device->CreateDepthStencilState(&depthStencilDesc, &m_depthStencilState) ); // Set the depth stencil state. m_deviceContext->OMSetDepthStencilState(m_depthStencilState, 1); // Initialize the depth stencil view. D3D11_DEPTH_STENCIL_VIEW_DESC depthStencilViewDesc; 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; // Create the depth stencil view. CHECK( m_device->CreateDepthStencilView(m_depthStencilBuffer, &depthStencilViewDesc, &m_depthStencilView) ); // Bind the render target view and depth stencil buffer to the output render pipeline. m_deviceContext->OMSetRenderTargets(1, &m_renderTargetView, m_depthStencilView); // Setup the raster description which will determine how and what polygons will be drawn. D3D11_RASTERIZER_DESC rasterDesc; ZeroMemory(&rasterDesc, sizeof(rasterDesc)); 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. CHECK( m_device->CreateRasterizerState(&rasterDesc, &m_rasterState) ); // Now set the rasterizer state. m_deviceContext->RSSetState(m_rasterState); // Setup the viewport for rendering. D3D11_VIEWPORT viewport; 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. m_deviceContext->RSSetViewports(1, &viewport); // Setup the projection matrix. float fieldOfView, screenAspect; fieldOfView = (float)D3DX_PI / 4.0f; screenAspect = (float)screenWidth / (float)screenHeight; // Create the projection matrix for 3D rendering. D3DXMatrixPerspectiveFovLH(&m_projectionMatrix, fieldOfView, screenAspect, screenNear, screenFar); // Initialize the world matrix to the identity matrix. D3DXMatrixIdentity(&m_worldMatrix); // Create an orthographic projection matrix for 2D rendering. D3DXMatrixOrthoLH(&m_orthoMatrix, (float)screenWidth, (float)screenHeight, screenNear, screenFar); return true; }
bool PlatformD3D11::InitDeviceAndSwapChain(bool fullscreen) { IDXGIFactory* factory = NULL; IDXGIAdapter* adapter = NULL; IDXGIOutput* adapter_output = NULL; HRESULT hresult = S_OK; // Determine the resolution of the clients desktop screen. UInt32 screen_width = GetSystemMetrics(SM_CXSCREEN); UInt32 screen_height = GetSystemMetrics(SM_CYSCREEN); UInt32 numerator = 0; UInt32 denominator = 1; // Create a DirectX graphics interface factory. hresult = CreateDXGIFactory(__uuidof(IDXGIFactory), (void**)&factory); if(SUCCEEDED(hresult)) { // Use the factory to create an adapter for the primary graphics interface (video card). hresult = factory->EnumAdapters(0, &adapter); } // Enumerate the primary adapter output (monitor). if(SUCCEEDED(hresult)) hresult = adapter->EnumOutputs(0, &adapter_output); // Get the number of modes that fit the DXGI_FORMAT_R8G8B8A8_UNORM display format for the adapter output (monitor). UInt32 num_modes = 0; if(SUCCEEDED(hresult)) hresult = adapter_output->GetDisplayModeList(DXGI_FORMAT_R8G8B8A8_UNORM, DXGI_ENUM_MODES_INTERLACED, &num_modes, NULL); if(SUCCEEDED(hresult)) { // Create a list to hold all the possible display modes for this monitor/video card combination. DXGI_MODE_DESC* display_mode_list = new DXGI_MODE_DESC[num_modes]; // Now fill the display mode list structures. hresult = adapter_output->GetDisplayModeList(DXGI_FORMAT_R8G8B8A8_UNORM, DXGI_ENUM_MODES_INTERLACED, &num_modes, display_mode_list); if(SUCCEEDED(hresult)) { // Now go through all the display 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(UInt32 i=0; i<num_modes; i++) { if(display_mode_list[i].Width == (unsigned int)screen_width) { if(display_mode_list[i].Height == (unsigned int)screen_height) { numerator = display_mode_list[i].RefreshRate.Numerator; denominator = display_mode_list[i].RefreshRate.Denominator; } } } } // Release the display mode list. delete [] display_mode_list; display_mode_list = 0; } // Release the adapter output. ReleaseNull(adapter_output); ReleaseNull(adapter); ReleaseNull(factory); UINT create_device_flags = 0; #ifdef _DEBUG // causes a crash on lab PCs //create_device_flags |= D3D11_CREATE_DEVICE_DEBUG; #endif D3D_DRIVER_TYPE driver_types[] = { D3D_DRIVER_TYPE_HARDWARE, D3D_DRIVER_TYPE_REFERENCE, }; UINT num_driver_types = sizeof( driver_types ) / sizeof( driver_types[0] ); 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; if(vsync_enabled_) { sd.BufferDesc.RefreshRate.Numerator = numerator; sd.BufferDesc.RefreshRate.Denominator = denominator; } else { sd.BufferDesc.RefreshRate.Numerator = 0; sd.BufferDesc.RefreshRate.Denominator = 1; } sd.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT; sd.OutputWindow = window_->hwnd(); sd.SampleDesc.Count = 1; sd.SampleDesc.Quality = 0; sd.Windowed = fullscreen ? FALSE : TRUE; // Set the feature level to DirectX 11. D3D_FEATURE_LEVEL feature_levels[] = { D3D_FEATURE_LEVEL_11_0, D3D_FEATURE_LEVEL_10_1, D3D_FEATURE_LEVEL_10_0, }; UINT num_feature_levels = sizeof( feature_levels ) / sizeof( feature_levels[0] ); for( UINT driver_type_index = 0; driver_type_index < num_driver_types; driver_type_index++ ) { driver_type_ = driver_types[driver_type_index]; hresult = D3D11CreateDeviceAndSwapChain( NULL, this->driver_type_, NULL, create_device_flags, feature_levels, num_feature_levels, D3D11_SDK_VERSION, &sd, &swap_chain_, &device_, NULL, &device_context_); if( SUCCEEDED( hresult ) ) break; } if SUCCEEDED( hresult ) return true; else {