Sign in to follow this  

DX11 Sluggish D3D on Init and Live Devices

This topic is 1909 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

Hello,

I have finally gotten my object oriented engine base to render a 2d image. I have also done this by following and amending tutorial 2 from the directx sdk documentation, and it worked smoothly in the tutorial (i.e. one source file, no objects).

In my oo program, there are live devices on shutdown and significant sluggishness in response. It takes a few seconds for the window to respond to movements on a top of the line system.

I will spend all day tomorrow finding out what the bug is here, but maybe one of you could spot it even faster? I have posted the source below in text and attached the entire project in .zip form as well.

Thanks in advance for your help.


/////////////////////////////////////////////////////////////////////////////////////////////
// Filename: D3DClass.cpp
// (c) Dave Ottley, 2012. All rights reserved.
/////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////
// INCLUDES
///////////////////////////
#include <Windows.h>
#include <iostream>
#include <fstream>
#include <assert.h>
#include <vector>
#include <memory>
#include <d3dcompiler.h>
#include <d3d11.h>
#include <D3DX11.h>
///////////////////////////
// MY INCLUDES
///////////////////////////
#include "D3DClass.h"
#include "Constants.h"
#include "WindowsClass.h"
#include "Util.h"
#include "WICTextureLoader.h"

#pragma comment(lib, "dxgi.lib")
#pragma comment(lib, "d3d11.lib")
#pragma comment(lib, "d3dx11.lib")
#pragma comment(lib, "dxerr.lib")
#pragma comment(lib, "d3dcompiler.lib")
/////////////////////////////////////////////////////////////////////////////////////////////
//
// CONSTRUCTOR / GET INSTANCE
//
/////////////////////////////////////////////////////////////////////////////////////////////
D3DClass::D3DClass()
:
mDevice(0),
mContext(0),
mSwapChain(0),
mRenderTargetView(0),
mDepthStencilView(0),
mDepthStencilBuffer(0),
mDepthEnabledStencilState(0),
mDepthDisabledStencilState(0),
mRasterizerState(0),
mVRam(0),
mRefreshNumerator(0),
mRefreshDenominator(0),
mPixelShader(0),
mVertexShader(0),
mSamplerLinear(0),
mAtlas(0),
mVertexBuffer(0),
mIndexBuffer(0),
mVertexLayout(0),
mVSBlob(0),
mPSBlob(0),
mVSync(VSYNC),
mFullscreen(FULL_SCREEN),
mNearPlane(NEAR_PLANE),
mFarPlane(FAR_PLANE),
mFeatureLevel(D3D_FEATURE_LEVEL_9_1),
mDriverType(D3D_DRIVER_TYPE_NULL)
{
ZeroMemory(mDriverTypeName, 200);
ZeroMemory(mFeatureLevelName, 200);

for(int i = 0; i < 256; ++i)
{
mVideoCardDescription[i] = 0;
}
XMVECTOR up = XMVectorSet(0.0f, 1.0f, 0.0f, 0.0f);
mCameraPos = XMFLOAT4(0.0f, 0.0f, -10.0f, 1.0f);
mCameraTarget = XMFLOAT4(0.0f, 0.0f, 1.0f, 1.0f);
XMMATRIX I = XMMatrixIdentity();
XMStoreFloat4x4(&mIWorld, I);
XMMATRIX O = XMMatrixOrthographicLH((float) WindowsCls->GetScreenWidth(), (float)WindowsCls->GetScreenHeight(), mNearPlane, mFarPlane);
XMStoreFloat4x4(&mOrtho, O);
XMMATRIX P = XMMatrixPerspectiveFovLH(FOV_ANGLE, GetAspectRatio(), mNearPlane, mFarPlane);
XMStoreFloat4x4(&mProj, P);
XMMATRIX V = XMMatrixLookAtLH(XMLoadFloat4(&mCameraPos), XMLoadFloat4(&mCameraTarget), up);
XMStoreFloat4x4(&mView, V);

}
D3DClass * D3DClass::GetInstance()
{
static D3DClass theOne;
return &theOne;
}
/////////////////////////////////////////////////////////////////////////////////////////////
//
// DESTRUCTOR / SHUTDOWN
//
/////////////////////////////////////////////////////////////////////////////////////////////
D3DClass::~D3DClass()
{

}
void D3DClass::Shutdown()
{
HRESULT hr = 0;
//Disable full screen before shutting down.
mSwapChain->SetFullscreenState(FALSE, NULL);
//Release all COM objects
ReleaseCOM(mVertexBuffer);
ReleaseCOM(mIndexBuffer);
ReleaseCOM(mVertexLayout);
ReleaseCOM(mVertexShader);
ReleaseCOM(mPixelShader);
ReleaseCOM(mAtlas);
//ReleaseCOM(mVSBlob);
//ReleaseCOM(mPSBlob);
ReleaseCOM(mRasterizerState);
ReleaseCOM(mDepthDisabledStencilState);
ReleaseCOM(mDepthEnabledStencilState);
ReleaseCOM(mDepthStencilBuffer);
ReleaseCOM(mDepthStencilView);
ReleaseCOM(mRenderTargetView);
ReleaseCOM(mSwapChain);
ReleaseCOM(mContext);
ReleaseCOM(mDevice);
ReleaseCOM(mSamplerLinear);

}

/////////////////////////////////////////////////////////////////////////////////////////////
//
// INITIALIZE
//
/////////////////////////////////////////////////////////////////////////////////////////////
bool D3DClass::Initialize()
{
if(!SetVideoCardInfo())
return false;
if(!CreateDeviceAndSwapChain())
return false;
if(!LoadCompiledShadersFromFile() )
return false;
if(!CreateRenderTargetView())
return false;
if(!CreateDepthStencilView())
return true;
if(!SetRasterizerState())
return false;
if(!CreateSamplerState())
return false;
if(!LoadMasterTextureAtlas())
return false;
if(!CreateBuffers())
return false;
SetViewport();
SetPrimitiveTopology();
return true;
}
/////////////////////////////////////////////////////////////////////////////////////////////
//
// ON RESIZE
//
/////////////////////////////////////////////////////////////////////////////////////////////
void D3DClass::OnResize()
{
//...
}
/////////////////////////////////////////////////////////////////////////////////////////////
//
// SET VIDEO CARD INFO
//
/////////////////////////////////////////////////////////////////////////////////////////////
bool D3DClass::SetVideoCardInfo()
{
HRESULT result;
IDXGIFactory * factory;
IDXGIAdapter * adapter;
IDXGIOutput * adapterOutput;
unsigned int numModes, stringLength;
DXGI_MODE_DESC * displayModeList;
DXGI_ADAPTER_DESC adapterDesc;
// 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(UINT i=0; i<numModes; i++)
{
if(displayModeList[i].Width == (unsigned int)WindowsCls->GetScreenWidth() )
{
if(displayModeList[i].Height == (unsigned int)WindowsCls->GetScreenHeight() )
{
mRefreshNumerator = displayModeList[i].RefreshRate.Numerator;
mRefreshDenominator = 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.
mVRam = (int)(adapterDesc.DedicatedVideoMemory / 1024 / 1024);
// Convert the name of the video card to a character array and store it.
int error = wcstombs_s(&stringLength, mVideoCardDescription, 128, adapterDesc.Description, 256);
if(error != 0)
{
return false;
}
// Release the display mode list.
delete [] displayModeList;
displayModeList = 0;
// Release the adapter output.
ReleaseCOM(adapterOutput);
// Release the adapter.
ReleaseCOM(adapter);
// Release the factory.
ReleaseCOM(factory);
return true;
}
/////////////////////////////////////////////////////////////////////////////////////////////
//
// CREATE DEVICE AND SWAP CHAIN
//
/////////////////////////////////////////////////////////////////////////////////////////////
bool D3DClass::CreateDeviceAndSwapChain()
{
// Variables
HRESULT result;
DXGI_SWAP_CHAIN_DESC swapChainDesc;
UINT createDeviceFlags = 0;
#if defined(DEBUG) || defined(_DEBUG)
createDeviceFlags |= D3D11_CREATE_DEVICE_DEBUG;
#endif

D3D_FEATURE_LEVEL featureLevels[] =
{
D3D_FEATURE_LEVEL_11_0, //try first
D3D_FEATURE_LEVEL_10_1, //and so on...
D3D_FEATURE_LEVEL_10_0,
D3D_FEATURE_LEVEL_9_3,
D3D_FEATURE_LEVEL_9_2,
D3D_FEATURE_LEVEL_9_1,
};
UINT numFeatureLevels = ARRAYSIZE( featureLevels );
D3D_DRIVER_TYPE driverTypes[] =
{
D3D_DRIVER_TYPE_HARDWARE, //try first
D3D_DRIVER_TYPE_WARP, //and so on...
D3D_DRIVER_TYPE_REFERENCE,
};
UINT numDriverTypes = ARRAYSIZE( driverTypes );
// Initialize the swap chain description.
ZeroMemory(&swapChainDesc, sizeof(swapChainDesc));
swapChainDesc.BufferCount = 1;
swapChainDesc.BufferDesc.Width = WindowsCls->GetScreenWidth();
swapChainDesc.BufferDesc.Height = WindowsCls->GetScreenHeight();
swapChainDesc.BufferDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
if(mVSync)
{
swapChainDesc.BufferDesc.RefreshRate.Numerator = mRefreshNumerator;
swapChainDesc.BufferDesc.RefreshRate.Denominator = mRefreshDenominator;
}
else
{
swapChainDesc.BufferDesc.RefreshRate.Numerator = 0;
swapChainDesc.BufferDesc.RefreshRate.Denominator = 1;
}
swapChainDesc.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT;
swapChainDesc.OutputWindow = WindowsCls->GetHwnd();
swapChainDesc.SampleDesc.Count = 1;
swapChainDesc.SampleDesc.Quality = 0;
swapChainDesc.Windowed = !mFullscreen;
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, Direct3D device, and Direct3D device context.
for( UINT driverTypeIndex = 0; driverTypeIndex < numDriverTypes; driverTypeIndex++ )
{
mDriverType = driverTypes[driverTypeIndex];
result = D3D11CreateDeviceAndSwapChain( NULL,
mDriverType,
NULL,
createDeviceFlags,
featureLevels,
numFeatureLevels,
D3D11_SDK_VERSION,
&swapChainDesc,
&mSwapChain,
&mDevice,
&mFeatureLevel,
&mContext);
if( SUCCEEDED(result))
{
switch(driverTypeIndex)
{
case 0:
wcscpy_s(mDriverTypeName, L"Hardware");
break;
case 1:
wcscpy_s(mDriverTypeName, L"WARP");
break;
default:
wcscpy_s(mDriverTypeName, L"Reference");
break;
}
switch(mFeatureLevel)
{
case D3D_FEATURE_LEVEL_11_0:
wcscpy_s(mFeatureLevelName, L"D3D_FEATURE_LEVEL_11_0");
break;
case D3D_FEATURE_LEVEL_10_1:
wcscpy_s(mFeatureLevelName, L"D3D_FEATURE_LEVEL_10_1");
break;
case D3D_FEATURE_LEVEL_10_0:
wcscpy_s(mFeatureLevelName, L"D3D_FEATURE_LEVEL_10_0");
break;
case D3D_FEATURE_LEVEL_9_3:
wcscpy_s(mFeatureLevelName, L"D3D_FEATURE_LEVEL_10_0");
break;
case D3D_FEATURE_LEVEL_9_2:
wcscpy_s(mFeatureLevelName, L"D3D_FEATURE_LEVEL_10_0");
break;
case D3D_FEATURE_LEVEL_9_1:
wcscpy_s(mFeatureLevelName, L"D3D_FEATURE_LEVEL_10_0");
break;
default:
wcscpy_s(mFeatureLevelName, L"Unsupported Feature Level");
break;
}
}
}
MakeWindowAssociation();
if(FAILED(result))
{
return false;
}
return true;
}

/////////////////////////////////////////////////////////////////////////////////////////////
//
// CREATE RENDER TARGET VIEW
//
/////////////////////////////////////////////////////////////////////////////////////////////
bool D3DClass::CreateRenderTargetView()
{
HRESULT result;
ID3D11Texture2D* backBufferPtr;
// Get the pointer to the back buffer.
result = mSwapChain->GetBuffer(0, __uuidof(ID3D11Texture2D), (LPVOID*)&backBufferPtr);
if(FAILED(result))
{
return false;
}
// Create the render target view with the back buffer pointer.
result = mDevice->CreateRenderTargetView(backBufferPtr, NULL, &mRenderTargetView);
if(FAILED(result))
{
return false;
}
// Release pointer to the back buffer as we no longer need it.
ReleaseCOM(backBufferPtr);
return true;
}
/////////////////////////////////////////////////////////////////////////////////////////////
//
// CREATE DEPTH STENCIL VIEW
//
/////////////////////////////////////////////////////////////////////////////////////////////
bool D3DClass::CreateDepthStencilView()
{
HRESULT result;
D3D11_TEXTURE2D_DESC depthBufferDesc;
D3D11_DEPTH_STENCIL_DESC depthStencilDesc;
D3D11_DEPTH_STENCIL_VIEW_DESC depthStencilViewDesc;
D3D11_DEPTH_STENCIL_DESC depthDisabledStencilDesc;
// Initialize the description of the depth buffer.
ZeroMemory(&depthBufferDesc, sizeof(depthBufferDesc));
// Set up the description of the depth buffer.
depthBufferDesc.Width = WindowsCls->GetScreenWidth();
depthBufferDesc.Height = WindowsCls->GetScreenHeight();
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 = mDevice->CreateTexture2D(&depthBufferDesc, NULL, &mDepthStencilBuffer);
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 = mDevice->CreateDepthStencilState(&depthStencilDesc, &mDepthEnabledStencilState);
if(FAILED(result))
{
return false;
}

// 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 = mDevice->CreateDepthStencilState(&depthDisabledStencilDesc, &mDepthDisabledStencilState);
if(FAILED(result))
{
return false;
}
// Set the depth stencil state.
mContext->OMSetDepthStencilState(mDepthDisabledStencilState, 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 = mDevice->CreateDepthStencilView(mDepthStencilBuffer, &depthStencilViewDesc, &mDepthStencilView);
if(FAILED(result))
{
return false;
}
// Bind the render target view and depth stencil view to the output render pipeline.
mContext->OMSetRenderTargets(1, &mRenderTargetView, mDepthStencilView);

return true;
}
/////////////////////////////////////////////////////////////////////////////////////////////
//
// SET RASTERIZER STATE
//
/////////////////////////////////////////////////////////////////////////////////////////////
bool D3DClass::SetRasterizerState()
{
HRESULT result;
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.
result = mDevice->CreateRasterizerState(&rasterDesc, &mRasterizerState);
if(FAILED(result))
{
return false;
}
// Now set the rasterizer state.
mContext->RSSetState(mRasterizerState);
return true;
}
/////////////////////////////////////////////////////////////////////////////////////////////
//
// SET VIEWPORT
//
/////////////////////////////////////////////////////////////////////////////////////////////
void D3DClass::SetViewport()
{
D3D11_VIEWPORT viewport;
// Setup the viewport for rendering.
viewport.Width = (float)WindowsCls->GetScreenWidth();
viewport.Height = (float)WindowsCls->GetScreenHeight();
viewport.MinDepth = 0.0f;
viewport.MaxDepth = 1.0f;
viewport.TopLeftX = 0.0f;
viewport.TopLeftY = 0.0f;
// Create the viewport.
mContext->RSSetViewports(1, &viewport);
}
/////////////////////////////////////////////////////////////////////////////////////////////
//
// CLEAR OLD SCREEN WITH PINK FOR DEBUGGING
//
/////////////////////////////////////////////////////////////////////////////////////////////
void D3DClass::ClearScreen()
{
//float ClearColor[4] = { 0.0f, 0.125f, 0.6f, 1.0f };
// Clear the back buffer.
mContext->ClearRenderTargetView(mRenderTargetView, reinterpret_cast<const float*>(&Colors::Magenta) );

// Clear the depth buffer.
mContext->ClearDepthStencilView(mDepthStencilView, D3D11_CLEAR_DEPTH, 1.0f, 0);
}
/////////////////////////////////////////////////////////////////////////////////////////////
//
// PREPARE THE SCREEN FOR PRESENTATION
//
/////////////////////////////////////////////////////////////////////////////////////////////
void D3DClass::UpdateD3DFrame()
{
//...
}
/////////////////////////////////////////////////////////////////////////////////////////////
//
// PRESENT SCREEN
//
/////////////////////////////////////////////////////////////////////////////////////////////
void D3DClass::Present()
{
HRESULT hr;
// Set vertex and pixel shaders, primitive topology, samplers, and master texture
GetContext()->VSSetShader(mVertexShader, NULL, 0);
GetContext()->PSSetShader(mPixelShader, NULL, 0);
GetContext()->IASetPrimitiveTopology( D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST );
GetContext()->PSSetShaderResources( 0, 1, &mAtlas );
GetContext()->PSSetSamplers( 0, 1, &mSamplerLinear);
GetContext()->DrawIndexed( 6, 0, 0 );
// Present the back buffer to the screen since rendering is complete.
if(mVSync)
{
// Lock to screen refresh rate.
// OCCLUDED NEVER HAPPENING
hr = mSwapChain->Present(1, 0);
if(hr == DXGI_STATUS_OCCLUDED)
ApplicationCls->Pause();
}
else
{
// Present as fast as possible.
// OCCLUDED NEVER HAPPENING
hr = mSwapChain->Present(0, 0);
if(hr == DXGI_STATUS_OCCLUDED)
ApplicationCls->Pause();
}
return;
}
/////////////////////////////////////////////////////////////////////////////////////////////
//
// TURN Z BUFFER ON
//
/////////////////////////////////////////////////////////////////////////////////////////////
void D3DClass::TurnZBufferOn()
{
mContext->OMSetDepthStencilState(mDepthEnabledStencilState, 1);
return;
}
/////////////////////////////////////////////////////////////////////////////////////////////
//
// TURN Z BUFFER OFF
//
/////////////////////////////////////////////////////////////////////////////////////////////
void D3DClass::TurnZBufferOff()
{
mContext->OMSetDepthStencilState(mDepthDisabledStencilState, 1);
return;
}
/////////////////////////////////////////////////////////////////////////////////////////////
//
// GET ASPECT RATIO
//
/////////////////////////////////////////////////////////////////////////////////////////////
const float D3DClass::GetAspectRatio() const
{
return (float) WindowsCls->GetScreenWidth() / WindowsCls->GetScreenHeight();
}

/////////////////////////////////////////////////////////////////////////////////////////////
//
// GET VIDEO CARD INFO
//
/////////////////////////////////////////////////////////////////////////////////////////////
void D3DClass::GetVideoCardInfo(char* cardName, int& memory) const
{
strcpy_s(cardName, 128, mVideoCardDescription);
memory = mVRam;
return;
}
/////////////////////////////////////////////////////////////////////////////////////////////
//
// GETTERS
//
/////////////////////////////////////////////////////////////////////////////////////////////
void D3DClass::GetProjectionMatrix(XMMATRIX& projectionMatrix)
{
projectionMatrix = XMLoadFloat4x4(&mProj);
return;
}

void D3DClass::GetIWorldMatrix(XMMATRIX& worldMatrix)
{
worldMatrix = XMLoadFloat4x4(&mIWorld);
return;
}

void D3DClass::GetOrthoMatrix(XMMATRIX& orthoMatrix)
{
orthoMatrix = XMLoadFloat4x4(&mOrtho);
return;
}
/////////////////////////////////////////////////////////////////////////////////////////////
//
// Disallow Alt-Enter detect. Custom Define.
//
/////////////////////////////////////////////////////////////////////////////////////////////
bool D3DClass::MakeWindowAssociation()
{
//COM queries to get at the correct IDXGIFactory instance used to create the device
//Query Interface
IDXGIDevice * dxgiDevice = 0;
mDevice->QueryInterface(__uuidof(IDXGIDevice), (void**) &dxgiDevice);
if(!dxgiDevice)
return false;
//Query Adapter
IDXGIAdapter * dxgiAdapter = 0;
dxgiDevice->GetParent(__uuidof(IDXGIAdapter), (void**) &dxgiAdapter);
if(!dxgiAdapter)
return false;
//Finally get the IDXGIFactory interface.
IDXGIFactory * dxgiFactory = 0;
dxgiAdapter->GetParent(__uuidof(IDXGIFactory), (void**) &dxgiFactory);
if(!dxgiFactory)
return false;
//Disallow Automatic Alt-Enter detect, custom define.
HR(dxgiFactory->MakeWindowAssociation(WindowsCls->GetHwnd(), DXGI_MWA_NO_WINDOW_CHANGES) );
//Release our acquired COM interfaces (because we are done with them).
ReleaseCOM(dxgiDevice);
ReleaseCOM(dxgiAdapter);
ReleaseCOM(dxgiFactory);
return true;
}
/////////////////////////////////////////////////////////////////////////////////////////////
//
// Load all shaders from pre-compiled .cso files in Assets
//
/////////////////////////////////////////////////////////////////////////////////////////////
bool D3DClass::LoadCompiledShadersFromFile()
{
HRESULT hr = 0;
//Load compiled shaders into memory
LoadShaderFromFile(VS_NAME, &mVSBlob );
LoadShaderFromFile(PS_NAME, &mPSBlob );
hr = GetDevice()->CreateVertexShader(mVSBlob->GetBufferPointer(), mVSBlob->GetBufferSize(), 0, &mVertexShader);
hr = GetDevice()->CreatePixelShader(mPSBlob->GetBufferPointer(), mPSBlob->GetBufferSize(), 0, &mPixelShader);
if(!CreateLayout(mVSBlob->GetBufferPointer(), mVSBlob->GetBufferSize()) )
return false;

ReleaseCOM(mVSBlob);
ReleaseCOM(mPSBlob);
return true;
}
bool D3DClass::LoadShaderFromFile(const wchar_t * filename, ID3DBlob ** blob)
{
HRESULT hr = 0;
std::wstring fullpath(AppendCurrentDirectory(filename) );
//MessageBox(WindowsCls->GetHwnd(), buffer, 0, 0);


std::ifstream fin(fullpath.c_str(), std::ios::binary);
assert(fin);

fin.seekg(0, std::ios_base::end);

int size = (int)fin.tellg();
fin.seekg(0, std::ios_base::beg);
hr = D3DCreateBlob(size, blob);
fin.read((char*) (*blob)->GetBufferPointer(), (*blob)->GetBufferSize());
fin.close();
return true;
}
std::wstring D3DClass::AppendCurrentDirectory(const wchar_t * filename)
{
wchar_t buffer[1000];
GetCurrentDirectory(1000, buffer);
wcsncat_s(buffer, filename, wcslen(filename) );
return std::wstring(buffer);
}
/////////////////////////////////////////////////////////////////////////////////////////////
//
// Create the sampler state
//
/////////////////////////////////////////////////////////////////////////////////////////////
bool D3DClass::CreateSamplerState()
{
D3D11_SAMPLER_DESC sampDesc;
HRESULT hr = 0;
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;
hr = GetDevice()->CreateSamplerState( &sampDesc, &mSamplerLinear );
if( FAILED( hr ) )
return false;
return true;
}
/////////////////////////////////////////////////////////////////////////////////////////////
//
// Load one master texture atlas for the game (may expand later)
//
/////////////////////////////////////////////////////////////////////////////////////////////
bool D3DClass::LoadMasterTextureAtlas()
{
HRESULT hr = 0;
std::wstring fullpath(AppendCurrentDirectory(MASTER_ATLAS_FILENAME) );
hr = D3DX11CreateShaderResourceViewFromFile( GetDevice(), fullpath.c_str(), NULL, NULL, &mAtlas, NULL );

//hr = CreateWICTextureFromFile(GetDevice(), GetContext(), MASTER_ATLAS_FILENAME, 0, &mAtlas, 0);
if( FAILED( hr ) )
return false;
return true;
}
/////////////////////////////////////////////////////////////////////////////////////////////
//
// Create Vertex and Index Buffers
//
/////////////////////////////////////////////////////////////////////////////////////////////
bool D3DClass::CreateBuffers()
{
HRESULT hr = 0;
// Create vertex buffer
SimpleVertex vertices[] =
{

{ XMFLOAT3( -1.0f, 1.0f, 1.0f ), XMFLOAT2( 0.0f, 0.0f) },
{ XMFLOAT3( 1.0f, 1.0f, 1.0f ), XMFLOAT2( 1.0f, 0.0f) },
{ XMFLOAT3( 1.0f, -1.0f, 1.0f ), XMFLOAT2( 1.0f, 1.0f) },
{ XMFLOAT3( -1.0f, -1.0f, 1.0f ), XMFLOAT2( 0.0f, 1.0f) },
};
D3D11_BUFFER_DESC bd;
ZeroMemory( &bd, sizeof(bd) );
bd.Usage = D3D11_USAGE_DEFAULT;
bd.ByteWidth = sizeof( SimpleVertex ) * 4;
bd.BindFlags = D3D11_BIND_VERTEX_BUFFER;
bd.CPUAccessFlags = 0;
D3D11_SUBRESOURCE_DATA InitData;
ZeroMemory( &InitData, sizeof(InitData) );
InitData.pSysMem = vertices;
hr = GetDevice()->CreateBuffer( &bd, &InitData, &mVertexBuffer );
if( FAILED( hr ) )
return false;
// Create index buffer
WORD indices[] =
{
0,1,2,
0,2,3,
};
bd.Usage = D3D11_USAGE_DEFAULT;
bd.ByteWidth = sizeof( WORD ) * 6; // 6 vertices needed
bd.BindFlags = D3D11_BIND_INDEX_BUFFER;
bd.CPUAccessFlags = 0;
InitData.pSysMem = indices;
hr = GetDevice()->CreateBuffer( &bd, &InitData, &mIndexBuffer );
if( FAILED( hr ) )
return false;
// Set index buffer
GetContext()->IASetIndexBuffer( mIndexBuffer, DXGI_FORMAT_R16_UINT, 0 );
// Set vertex buffer
UINT stride = sizeof( SimpleVertex );
UINT offset = 0;
GetContext()->IASetVertexBuffers( 0, 1, &mVertexBuffer, &stride, &offset );
return true;
}
/////////////////////////////////////////////////////////////////////////////////////////////
//
// Create Input Layout
//
/////////////////////////////////////////////////////////////////////////////////////////////
bool D3DClass::CreateLayout(const void * vertexBuffer, int size)
{
HRESULT hr = 0;
// Define the input layout
D3D11_INPUT_ELEMENT_DESC layout[] =
{
{ "POSITION", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 0, D3D11_INPUT_PER_VERTEX_DATA, 0 },
{ "TEXTURE", 0, DXGI_FORMAT_R32G32_FLOAT, 0, D3D11_APPEND_ALIGNED_ELEMENT, D3D11_INPUT_PER_VERTEX_DATA, 0 },
};
UINT numElements = ARRAYSIZE( layout );
// Create the input layout
hr = GetDevice()->CreateInputLayout( layout, numElements, vertexBuffer,
size, &mVertexLayout );
if( FAILED( hr ) )
return false;
// Set the input layout
GetContext()->IASetInputLayout( mVertexLayout );
return true;
}

void D3DClass::SetPrimitiveTopology()
{
// Set primitive topology
GetContext()->IASetPrimitiveTopology( D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST );
}

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Similar Content

    • By mister345
      Hi, can somebody please tell me in clear simple steps how to debug and step through an hlsl shader file?
      I already did Debug > Start Graphics Debugging > then captured some frames from Visual Studio and
      double clicked on the frame to open it, but no idea where to go from there.
       
      I've been searching for hours and there's no information on this, not even on the Microsoft Website!
      They say "open the  Graphics Pixel History window" but there is no such window!
      Then they say, in the "Pipeline Stages choose Start Debugging"  but the Start Debugging option is nowhere to be found in the whole interface.
      Also, how do I even open the hlsl file that I want to set a break point in from inside the Graphics Debugger?
       
      All I want to do is set a break point in a specific hlsl file, step thru it, and see the data, but this is so unbelievably complicated
      and Microsoft's instructions are horrible! Somebody please, please help.
       
       
       

    • By mister345
      I finally ported Rastertek's tutorial # 42 on soft shadows and blur shading. This tutorial has a ton of really useful effects and there's no working version anywhere online.
      Unfortunately it just draws a black screen. Not sure what's causing it. I'm guessing the camera or ortho matrix transforms are wrong, light directions, or maybe texture resources not being properly initialized.  I didnt change any of the variables though, only upgraded all types and functions DirectX3DVector3 to XMFLOAT3, and used DirectXTK for texture loading. If anyone is willing to take a look at what might be causing the black screen, maybe something pops out to you, let me know, thanks.
      https://github.com/mister51213/DX11Port_SoftShadows
       
      Also, for reference, here's tutorial #40 which has normal shadows but no blur, which I also ported, and it works perfectly.
      https://github.com/mister51213/DX11Port_ShadowMapping
       
    • By xhcao
      Is Direct3D 11 an api function like glMemoryBarrier in OpenGL? For example, if binds a texture to compute shader, compute shader writes some values to texture, then dispatchCompute, after that, read texture content to CPU side. I know, In OpenGL, we could call glMemoryBarrier before reading to assure that texture all content has been updated by compute shader.
      How to handle incoherent memory access in Direct3D 11? Thank you.
    • By _Engine_
      Atum engine is a newcomer in a row of game engines. Most game engines focus on render
      techniques in features list. The main task of Atum is to deliver the best toolset; that’s why,
      as I hope, Atum will be a good light weighted alternative to Unity for indie games. Atum already
      has fully workable editor that has an ability to play test edited scene. All system code has
      simple ideas behind them and focuses on easy to use functionality. That’s why code is minimized
      as much as possible.
      Currently the engine consists from:
      - Scene Editor with ability to play test edited scene;
      - Powerful system for binding properties into the editor;
      - Render system based on DX11 but created as multi API; so, adding support of another GAPI
        is planned;
      - Controls system based on aliases;
      - Font system based on stb_truetype.h;
      - Support of PhysX 3.0, there are samples in repo that use physics;
      - Network code which allows to create server/clinet; there is some code in repo which allows
        to create a simple network game
      I plan to use this engine in multiplayer game - so, I definitely will evolve the engine. Also
      I plan to add support for mobile devices. And of course, the main focus is to create a toolset
      that will ease games creation.
      Link to repo on source code is - https://github.com/ENgineE777/Atum
      Video of work process in track based editor can be at follow link: 
       
       

    • By mister345
      I made a spotlight that
      1. Projects 3d models onto a render target from each light POV to simulate shadows
      2. Cuts a circle out of the square of light that has been projected onto the render target
      as a result of the light frustum, then only lights up the pixels inside that circle 
      (except the shadowed parts of course), so you dont see the square edges of the projected frustum.
       
      After doing an if check to see if the dot product of light direction and light to vertex vector is greater than .95
      to get my initial cutoff, I then multiply the light intensity value inside the resulting circle by the same dot product value,
      which should range between .95 and 1.0.
       
      This should give the light inside that circle a falloff from 100% lit to 0% lit toward the edge of the circle. However,
      there is no falloff. It's just all equally lit inside the circle. Why on earth, I have no idea. If someone could take a gander
      and let me know, please help, thank you so much.
      float CalculateSpotLightIntensity(     float3 LightPos_VertexSpace,      float3 LightDirection_WS,      float3 SurfaceNormal_WS) {     //float3 lightToVertex = normalize(SurfacePosition - LightPos_VertexSpace);     float3 lightToVertex_WS = -LightPos_VertexSpace;          float dotProduct = saturate(dot(normalize(lightToVertex_WS), normalize(LightDirection_WS)));     // METALLIC EFFECT (deactivate for now)     float metalEffect = saturate(dot(SurfaceNormal_WS, normalize(LightPos_VertexSpace)));     if(dotProduct > .95 /*&& metalEffect > .55*/)     {         return saturate(dot(SurfaceNormal_WS, normalize(LightPos_VertexSpace)));         //return saturate(dot(SurfaceNormal_WS, normalize(LightPos_VertexSpace))) * dotProduct;         //return dotProduct;     }     else     {         return 0;     } } float4 LightPixelShader(PixelInputType input) : SV_TARGET {     float2 projectTexCoord;     float depthValue;     float lightDepthValue;     float4 textureColor;     // Set the bias value for fixing the floating point precision issues.     float bias = 0.001f;     // Set the default output color to the ambient light value for all pixels.     float4 lightColor = cb_ambientColor;     /////////////////// NORMAL MAPPING //////////////////     float4 bumpMap = shaderTextures[4].Sample(SampleType, input.tex);     // Expand the range of the normal value from (0, +1) to (-1, +1).     bumpMap = (bumpMap * 2.0f) - 1.0f;     // Change the COORDINATE BASIS of the normal into the space represented by basis vectors tangent, binormal, and normal!     float3 bumpNormal = normalize((bumpMap.x * input.tangent) + (bumpMap.y * input.binormal) + (bumpMap.z * input.normal));     //////////////// LIGHT LOOP ////////////////     for(int i = 0; i < NUM_LIGHTS; ++i)     {     // Calculate the projected texture coordinates.     projectTexCoord.x =  input.vertex_ProjLightSpace[i].x / input.vertex_ProjLightSpace[i].w / 2.0f + 0.5f;     projectTexCoord.y = -input.vertex_ProjLightSpace[i].y / input.vertex_ProjLightSpace[i].w / 2.0f + 0.5f;     if((saturate(projectTexCoord.x) == projectTexCoord.x) && (saturate(projectTexCoord.y) == projectTexCoord.y))     {         // Sample the shadow map depth value from the depth texture using the sampler at the projected texture coordinate location.         depthValue = shaderTextures[6 + i].Sample(SampleTypeClamp, projectTexCoord).r;         // Calculate the depth of the light.         lightDepthValue = input.vertex_ProjLightSpace[i].z / input.vertex_ProjLightSpace[i].w;         // Subtract the bias from the lightDepthValue.         lightDepthValue = lightDepthValue - bias;         float lightVisibility = shaderTextures[6 + i].SampleCmp(SampleTypeComp, projectTexCoord, lightDepthValue );         // Compare the depth of the shadow map value and the depth of the light to determine whether to shadow or to light this pixel.         // If the light is in front of the object then light the pixel, if not then shadow this pixel since an object (occluder) is casting a shadow on it.             if(lightDepthValue < depthValue)             {                 // Calculate the amount of light on this pixel.                 float lightIntensity = saturate(dot(bumpNormal, normalize(input.lightPos_LS[i])));                 if(lightIntensity > 0.0f)                 {                     // Determine the final diffuse color based on the diffuse color and the amount of light intensity.                     float spotLightIntensity = CalculateSpotLightIntensity(                         input.lightPos_LS[i], // NOTE - this is NOT NORMALIZED!!!                         cb_lights[i].lightDirection,                          bumpNormal/*input.normal*/);                     lightColor += cb_lights[i].diffuseColor*spotLightIntensity* .18f; // spotlight                     //lightColor += cb_lights[i].diffuseColor*lightIntensity* .2f; // square light                 }             }         }     }     // Saturate the final light color.     lightColor = saturate(lightColor);    // lightColor = saturate( CalculateNormalMapIntensity(input, lightColor, cb_lights[0].lightDirection));     // TEXTURE ANIMATION -  Sample pixel color from texture at this texture coordinate location.     input.tex.x += textureTranslation;     // BLENDING     float4 color1 = shaderTextures[0].Sample(SampleTypeWrap, input.tex);     float4 color2 = shaderTextures[1].Sample(SampleTypeWrap, input.tex);     float4 alphaValue = shaderTextures[3].Sample(SampleTypeWrap, input.tex);     textureColor = saturate((alphaValue * color1) + ((1.0f - alphaValue) * color2));     // Combine the light and texture color.     float4 finalColor = lightColor * textureColor;     /////// TRANSPARENCY /////////     //finalColor.a = 0.2f;     return finalColor; }  
      Light_vs.hlsl
      Light_ps.hlsl
  • Popular Now