Jump to content

  • Log In with Google      Sign In   
  • Create Account

- - - - -

Creotex Engine ~ Part 2

Posted by , 03 September 2012 · 1,161 views

Engine Programming Games Creotex
Hello ladies and gentlemen,

Welcome to my journal!
If some of you guys are following me to create your own game engine, you should have a window by now so let's continue. And if you are just watching what I'm coding, next I'll put all DirectX stuff into my engine.

It was hard to find to get, an almost full, initialization of DirectX but I've some decent pieces of code which I have put into my code.

bool Graphics::Initialize(Window* pWindow)
	HRESULT result;
	IDXGIFactory* pFactory = nullptr;
	IDXGIAdapter* pAdapter = nullptr;
	IDXGIOutput* pAdapterOutput = nullptr;
	DXGI_MODE_DESC* pDisplayModeList = nullptr;
	D3D_FEATURE_LEVEL featureLevel;
	D3D11_TEXTURE2D_DESC depthBufferDesc;
	D3D11_DEPTH_STENCIL_DESC depthStencilDesc;
	D3D11_DEPTH_STENCIL_DESC depthDisableStencilDesc;
	D3D11_DEPTH_STENCIL_VIEW_DESC depthStencilViewDesc;
	D3D11_RASTERIZER_DESC rasterDesc;
	D3D11_BLEND_DESC blendStateDescription;
	unsigned int numModes = 0, numerator = 0, denominator = 0;
	float fieldOfView = 0.0f, screenAspect = 0.0f;

	// Store the pointer of the window
	m_pWindow = pWindow;

	// Create a DirectX graphics interface factory
	result = CreateDXGIFactory(__uuidof(IDXGIFactory), (void**)&pFactory);
	  return ErrorMessage(_T("Graphics"), _T("Initialize"), _T("CreateDXGIFactory"));

	// Use the factory to create an adapter for the primary graphics interface ( video card )
	result = pFactory->EnumAdapters(0, &pAdapter);
	  return ErrorMessage(_T("Graphics"), _T("Initialize"), _T("Set EnumAdapters factory"));

	// Enumerate the primary adapted output ( monitor )
	result = pAdapter->EnumOutputs(0, &pAdapterOutput);
	  return ErrorMessage(_T("Graphics"), _T("Initialize"), _T("Set EnumOutputs adapter"));

	// Get the numbder of modes that fit in the display the the adapter output ( monitor )
	result = pAdapterOutput->GetDisplayModeList(DXGI_FORMAT_R8G8B8A8_UNORM, DXGI_ENUM_MODES_INTERLACED, &numModes, NULL);
	  return ErrorMessage(_T("Graphics"), _T("Initialize"), _T("Set GetDisplayModeList adapter"));

	// Create  list to hold all possible display modes for this monitor/video card combinatior
	pDisplayModeList = new DXGI_MODE_DESC[numModes];
	  return ErrorMessage(_T("Graphics"), _T("Initialize"), _T("creating DisplayModeList"));

	// Now fill the fisplay mode list structures
	result = pAdapterOutput->GetDisplayModeList(DXGI_FORMAT_R8G8B8A8_UNORM, DXGI_ENUM_MODES_INTERLACED, &numModes, pDisplayModeList);
	  return ErrorMessage(_T("Graphics"), _T("Initialize"), _T("GetDisplayModeList adapter"));

	// Now go through all the display modes and find the one that mathces the screen width and height
	// When a match is found store the numerator and denominator of the refresh rate for that monitor
	for(int i=0; i<(int)numModes; ++i)
	   if(pDisplayModeList[i].Width == (unsigned int)m_pWindow->GetWindowWidth())
		  if(pDisplayModeList[i].Height == (unsigned int)m_pWindow->GetWindowHeight())
			 numerator = pDisplayModeList[i].RefreshRate.Numerator;
			 denominator = pDisplayModeList[i].RefreshRate.Denominator;

	// Get the adapter ( video card ) description
	result = pAdapter->GetDesc(&adapterDesc);
	  return ErrorMessage(_T("Graphics"), _T("Initialize"), _T("GetDesc adapter"));

	// Store the dedicated video card memory in megabytes
	m_VideoCardMemory = (int)(adapterDesc.DedicatedSystemMemory/1024/1024);

	// Store the video card name
	m_VideoCardDescription = adapterDesc.Description;

	// Release the display list, adapter output, adapter, factory

	// Create a struct to hold information about the swap chain

	// Clear out the struct for use
	ZeroMemory(&swapChainDesc, sizeof(swapChainDesc));

	// Fill the swap chain description struct
	swapChainDesc.BufferCount = 1;		 // 1 Back buffer
	swapChainDesc.BufferDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM; // Use 32-bit color
	swapChainDesc.BufferDesc.Width = m_pWindow->GetWindowWidth(); // Set the back buffer width
	swapChainDesc.BufferDesc.Height = m_pWindow->GetWindowHeight(); // Set the back buffer height
	  swapChainDesc.BufferDesc.RefreshRate.Numerator = numerator;
	  swapChainDesc.BufferDesc.RefreshRate.Denominator = denominator;
	  swapChainDesc.BufferDesc.RefreshRate.Numerator = 0;
	  swapChainDesc.BufferDesc.RefreshRate.Denominator = 1;
	swapChainDesc.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT; // How the chain is to be used
	swapChainDesc.OutputWindow = m_pWindow->GetHandleToWindow(); // The window to be used

	// Turn multisampling off
	swapChainDesc.SampleDesc.Count = 1;		// How many multisamples
	swapChainDesc.SampleDesc.Quality = 0;
	swapChainDesc.Windowed = !m_pWindow->GetFullscreen();   // Windowed/Fullscreen mode
	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 to DirectX 11
	featureLevel = D3D_FEATURE_LEVEL_11_0;
	// Create a device, device context and swap chain using the information in the swapChainDesc struct
	D3D11CreateDeviceAndSwapChain( NULL,
			 &m_pDeviceContext );

	// Get the adress of the back buffer
	ID3D11Texture2D* pBackBuffer;
	m_pSwapChain->GetBuffer(0, __uuidof(ID3D11Texture2D), (LPVOID*)&pBackBuffer);

	// Use the back buffer address to create the render target
	m_pDevice->CreateRenderTargetView(pBackBuffer, NULL, &m_pRenderTargetView);

	// Set the render target as the back buffer
	m_pDeviceContext->OMSetRenderTargets(1, &m_pBackBuffer, NULL);

	// Release back buffer

	// Initialize the description of the depth buffer
	ZeroMemory( &depthBufferDesc, sizeof(depthBufferDesc) );

	// Set up the description of the depth buffer
	depthBufferDesc.Width = m_pWindow->GetWindowWidth();
	depthBufferDesc.Height = m_pWindow->GetWindowHeight();
	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_pDevice->CreateTexture2D(&depthBufferDesc, NULL, &m_pDepthStencilBuffer);
	  return ErrorMessage(_T("Graphics"), _T("Initialize"), _T("CreateTexture2D depthBufferDesc"));
	// 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;
	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 the depth stencil state
	result = m_pDevice->CreateDepthStencilState(&depthStencilDesc, &m_pDepthStencilState);
	  return ErrorMessage(_T("Graphics"), _T("Initialize"), _T("CreateDepthStencilState depthStencilDesc"));

	// Set the depth stencil state
	m_pDeviceContext->OMSetDepthStencilState(m_pDepthStencilState, 1);

	// Initialize the depth stencil view
	ZeroMemory(&depthStencilViewDesc, sizeof(depthStencilViewDesc));
	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_pDevice->CreateDepthStencilView(m_pDepthStencilBuffer, &depthStencilViewDesc, &m_pDepthStencilView);
	  return ErrorMessage(_T("Graphics"), _T("Initialize"), _T("CreateDepthStencilView m_pDepthStencilBuffer"));

	// Bind the render target view and depth stencil buffer to the output render pipeline
	m_pDeviceContext->OMSetRenderTargets(1, &m_pRenderTargetView, m_pDepthStencilView);
	// 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;

	result = m_pDevice->CreateRasterizerState(&rasterDesc, &m_pRasterState);
	  return ErrorMessage(_T("Graphics"), _T("Initialize"), _T("CreateRasterizerState rasterDesc"));

	// Now set the rasterizer state

	// Set the viewport for rendering
	D3D11_VIEWPORT viewPort;
	ZeroMemory(&viewPort, sizeof(D3D11_VIEWPORT));
	viewPort.MinDepth = 0.0f;
	viewPort.MaxDepth = 1.0f;
	viewPort.TopLeftX = 0;
	viewPort.TopLeftY = 0;
	viewPort.Width = (float)m_pWindow->GetWindowWidth();
	viewPort.Height = (float)m_pWindow->GetWindowHeight();
	m_pDeviceContext->RSSetViewports(1, &viewPort);

	// Setup Projection matrix
	fieldOfView = (float)D3DX_PI/4.0f;
	screenAspect = (float)m_pWindow->GetWindowWidth()/(float)m_pWindow->GetWindowHeight();

	// Create the projection matrix for 3D rendering
	D3DXMatrixPerspectiveFovLH(&m_ProjectionMatrix, fieldOfView, screenAspect, SCREEN_NEAR, SCREEN_DEPTH);

	// Initialize the world matrix to identity matrix

	// Create an orthographic projection matrix for 2D rendering
	D3DXMatrixOrthoLH(&m_OrthoMatrix, (float)m_pWindow->GetWindowWidth(), (float)m_pWindow->GetWindowHeight(), SCREEN_NEAR, SCREEN_DEPTH);

	// Clear the memory
	ZeroMemory(&depthDisableStencilDesc, sizeof(depthDisableStencilDesc));
	// Set up the description of the stencil state
	depthDisableStencilDesc.DepthEnable = false;
	depthDisableStencilDesc.DepthWriteMask = D3D11_DEPTH_WRITE_MASK_ALL;
	depthDisableStencilDesc.DepthFunc = D3D11_COMPARISON_LESS;
	depthDisableStencilDesc.StencilEnable = true;
	depthDisableStencilDesc.StencilReadMask = 0xFF;
	depthDisableStencilDesc.StencilWriteMask = 0xFF;
	depthDisableStencilDesc.FrontFace.StencilFailOp = D3D11_STENCIL_OP_KEEP;
	depthDisableStencilDesc.FrontFace.StencilDepthFailOp = D3D11_STENCIL_OP_INCR;
	depthDisableStencilDesc.FrontFace.StencilPassOp = D3D11_STENCIL_OP_KEEP;
	depthDisableStencilDesc.FrontFace.StencilFunc = D3D11_COMPARISON_ALWAYS;
	depthDisableStencilDesc.BackFace.StencilFailOp = D3D11_STENCIL_OP_KEEP;
	depthDisableStencilDesc.BackFace.StencilDepthFailOp = D3D11_STENCIL_OP_DECR;
	depthDisableStencilDesc.BackFace.StencilPassOp = D3D11_STENCIL_OP_KEEP;
   depthDisableStencilDesc.BackFace.StencilFunc = D3D11_COMPARISON_ALWAYS;

	// Create the depth stencil state
	result = m_pDevice->CreateDepthStencilState(&depthDisableStencilDesc, &m_pDepthDisableStencilState);
	  return ErrorMessage(_T("Graphics"), _T("Initialize"), _T("CreateDepthStencilState depthDisableStencilDesc"));
	ZeroMemory(&blendStateDescription, sizeof(D3D11_BLEND_DESC));
	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;

	result = m_pDevice->CreateBlendState(&blendStateDescription, &m_AlphaEnableBlendingState);
	  return ErrorMessage(_T("Graphics"), _T("Initialize"), _T("CreateBlendState blendStateDescription"));
	blendStateDescription.RenderTarget[0].BlendEnable = FALSE;
	result = m_pDevice->CreateBlendState(&blendStateDescription, &m_AlphaDisableBlendingState);
	  return ErrorMessage(_T("Graphics"), _T("Initialize"), _T("CreateBlendState blendStateDescription"));
	return true;

As I've said in the previous entry my Application creates the core(window, system, graphics), so you should be able to initialize these graphics all by yourself. ;)

But when you have all initialization ready don't run it yet! don't fly when you can't walk. Else you would forget that you also need to deallocate what you have allocated! ;)

void Graphics::Shutdown()
	if(m_pSwapChain != nullptr)
	  m_pSwapChain->SetFullscreenState(false, NULL);


SafeRelease is a template, I love clear readable code!:
template<class T>
inline void SafeRelease(T &pObject)
	if(pObject != nullptr){
	  pObject = nullptr;

This took a very long time to get and understand all that code. I think I've deserved a break! ^^

By the way my window class you saw last entry is buggy.
In case you didn't read the reply there: I was casting the HWND to my Window* so I could call the method 'HandleEvents(...) in the WndProc function. But as soon I changed a data member in the HandleEvents method the application wouldn't start anymore. So needed to change this and this is what I've made:
if(msg == WM_CREATE) { SetWindowLong(hWnd, GWL_USERDATA, (LONG)((LPCREATESTRUCT)lParam)->lpCreateParams); }
  Window* pWindow = (Window*)GetWindowLong(hWnd, GWL_USERDATA);
  if(pWindow) { return pWindow->HandleEvents(hWnd, msg, wParam, lParam); }

return DefWindowProc(hWnd, msg, wParam, lParam);

So that was it for the graphics class. I hope you guys enjoy the code! If you want to see more follow my blog to keep in touch. And following this blog also means people are interested in these codes.Posted Image

So next entry will be my system class. But that won't be for today! First I'm going to enjoy my break ^^
So thank you ladies and gentlemen and see you in the next entry!

January 2017 »

151617 18 192021

Recent Entries

Recent Comments