Jump to content

  • Log In with Google      Sign In   
  • Create Account

Jonathan's Journal

Creotex Engine ~ Part 2

Posted by , 03 September 2012 - - - - - - · 1,146 views
Engine, Programming, Games and 1 more...
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;
	DXGI_ADAPTER_DESC adapterDesc;
	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);
	if(FAILED(result))
	{
	  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);
	if(FAILED(result))
	{
	  return ErrorMessage(_T("Graphics"), _T("Initialize"), _T("Set EnumAdapters factory"));
	}

	// Enumerate the primary adapted output ( monitor )
	result = pAdapter->EnumOutputs(0, &pAdapterOutput);
	if(FAILED(result))
	{
	  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);
	if(FAILED(result))
	{
	  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];
	if(!pDisplayModeList)
	{
	  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);
	if(FAILED(result))
	{
	  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);
	if(FAILED(result))
	{
	  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
	SafeDeleteArray(pDisplayModeList);
	SafeRelease(pAdapterOutput);
	SafeRelease(pAdapter);
	SafeRelease(pFactory);

	// Create a struct to hold information about the swap chain
	DXGI_SWAP_CHAIN_DESC swapChainDesc;

	// 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
	if(m_pWindow->GetVSync())
	{
	  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; // 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,
			 D3D_DRIVER_TYPE_HARDWARE,
			 NULL,
			 0,
			 &featureLevel,
			 1,
			 D3D11_SDK_VERSION,
			 &swapChainDesc,
			 &m_pSwapChain,
			 &m_pDevice,
			 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
	pBackBuffer->Release();

	// 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);
	if(FAILED(result))
	{
	  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);
	if(FAILED(result))
	{
	  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);
	if(FAILED(result))
	{
	  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);
	if(FAILED(result))
	{
	  return ErrorMessage(_T("Graphics"), _T("Initialize"), _T("CreateRasterizerState rasterDesc"));
	}

	// Now set the rasterizer state
	m_pDeviceContext->RSSetState(m_pRasterState);

	// 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
	D3DXMatrixIdentity(&m_WorldMatrix);

	// 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);
	if(FAILED(result))
	{
	  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);
	if(FAILED(result))
	{
	  return ErrorMessage(_T("Graphics"), _T("Initialize"), _T("CreateBlendState blendStateDescription"));
	}
	blendStateDescription.RenderTarget[0].BlendEnable = FALSE;
	result = m_pDevice->CreateBlendState(&blendStateDescription, &m_AlphaDisableBlendingState);
	if(FAILED(result))
	{
	  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(m_AlphaDisableBlendingState);
	SafeRelease(m_AlphaEnableBlendingState);
	SafeRelease(m_pDepthDisableStencilState);
	SafeRelease(m_pDepthStencilBuffer);
	SafeRelease(m_pDepthStencilState);
	SafeRelease(m_pRenderTargetView);
	SafeRelease(m_pRasterState);
	SafeRelease(m_pBackBuffer);
	SafeRelease(m_pDeviceContext);
	SafeRelease(m_pDevice);
	SafeRelease(m_pSwapChain);
}

SafeRelease is a template, I love clear readable code!:
template<class T>
inline void SafeRelease(T &pObject)
{
	if(pObject != nullptr){
	  pObject->Release();
	  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); }
else
{
  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!


Creotex Engine ~ Part 1

Posted by , 31 August 2012 - - - - - - · 978 views
Engine, Programming, Games and 1 more...
Hello ladies and gentlemen,


Welcome to my journal!
So part 1 of writing an engine. I hope you guys are all so excited as me! Posted Image ( I know you do )

Before I step into DirectX graphics I first want to create a window.
For people who haven't learned DirectX yet, for popping up a window you don't need any DirectX libs.
DirectX will just need the handle and instance of the window and will turn everything to a 3D space.

By the way, didn't mentioned it before, I'm using Unicode!
Example:
#ifdef _UNICODE
	#define tstring wstring
#else
	#define tstring string
#endif

So.. Writing a game engine. How should I start? How should I write? How will my structure look like?
Don't worry already got the idea! Posted Image

The plan is that my WinMain function creates an Application, which handles the core and game.
This is how it looks like:
int WINAPI _tWinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, PTSTR pCmdLine, int nCmdShow)
{
	// Terminate if heap is corrupted
	HeapSetInformation(NULL, HeapEnableTerminationOnCorruption, NULL, 0);

	// Avoid warnings of unused parameters
	UNREFERENCED_PARAMETER(hPrevInstance);
	UNREFERENCED_PARAMETER(pCmdLine);

	// Allocate the application
	Application* pApplication = new Application();

	// Initialize and run the application
	if(pApplication->Initialize(hInstance))
	{
		pApplication->Run();
	}

	// Shutdown and deallocate the application
	SafeDeleteCore(pApplication);
	return TRUE;
}

So I'm Initializing the Application, running if succeeded, and shutting down.
And for those who wonder what "SafeDeleteCore" is:
template<class T>
inline void SafeDeleteCore(T &pObject)
{
	if(pObject != nullptr){
		pObject->Shutdown();
		delete pObject;
		pObject = nullptr;
	}
}

My application has 4 data members:
core: Window*, System*, Graphics*
game: Game*

I think you all know what to do with those data members when you have 3 methods... So not going to show such simple code....
Ok maybe a bit.. Because all of you are so lovely Posted Image
This is the Run method:
void Application::Run()
{
	// GameStart
	m_pGame->GameStart();


	MSG msg = {0};
	while(msg.message != WM_QUIT)
	{
		if(PeekMessage(&msg,NULL,NULL,NULL,PM_REMOVE))
		{
		   TranslateMessage(&msg);
		   DispatchMessage(&msg);
		}
		else
		{
		   // GameUpdate
		   m_pGame->GameUpdate();

		   // GameRender
		   m_pGame->GameRender();

		   Sleep(1);
		}
	}

	// GameEnd
	m_pGame->GameEnd();
}

So we got the WinMain, Application.... That was it I think?
Yes everything is done, we have written our engine. Now we can create games like Starcraft!!

Or is it? Posted Image
No there is more!!!! *screaming* *crying* *beating up the kid next door*

We still need that window on our screen! or maybe if you stare long enough it will magically appear.. You can give it a shot.
So for the window class. A window class needs to store some information about the window so you can easily change something on your screen.
class Window
{
public:
	/////////////////////////////////////////////////////
	// Constructor(s) & Destructor
	/////////////////////////////////////////////////////
	Window();
	virtual ~Window();

	/////////////////////////////////////////////////////
	// Public Methods
	/////////////////////////////////////////////////////
	bool Initialize(HINSTANCE hInstance);
	void Shutdown();
	void ShowWindow();

	LRESULT CALLBACK HandleEvents(HWND, UINT, WPARAM, LPARAM);

private:
	HWND  m_hMainWnd;
	HINSTANCE m_hInstance;
	tstring  m_sWindowTitle;
	int   m_iWindowWidth;
	int   m_iWindowHeight;
	bool  m_bFullscreen;
};

static LRESULT CALLBACK WndProc(HWND, UINT, WPARAM, LPARAM);


The Window.cpp is the largest piece of code I have at the moment. Here it comes!
bool Window::Initialize(HINSTANCE hInstance)
{
	// Store the instance of the application
	m_hInstance = hInstance;

	// Setup the window class with default settings
	WNDCLASSEX wndclass;
	wndclass.style   = CS_HREDRAW | CS_VREDRAW | CS_OWNDC | CS_DBLCLKS;
	wndclass.lpfnWndProc = WndProc;
	wndclass.cbClsExtra  = 0;
	wndclass.cbWndExtra  = 0;
	wndclass.hInstance  = m_hInstance;
	wndclass.hIcon   = LoadIcon(NULL, IDI_WINLOGO);
	wndclass.hIconSm  = wndclass.hIcon;
	wndclass.hCursor  = LoadCursor(NULL, IDC_ARROW);
	wndclass.hbrBackground = (HBRUSH)CreateSolidBrush(RGB(255,255,255));
	wndclass.lpszMenuName = m_sWindowTitle.c_str();
	wndclass.lpszClassName = m_sWindowTitle.c_str();
	wndclass.cbSize   = sizeof(WNDCLASSEX);

	// Register the window class
	if(!RegisterClassEx(&wndclass)) {
	  return false;
	}

	// Create new screen settings if fullscreen
	int posX = 0, posY = 0;
	if(m_bFullscreen)
	{
	  DEVMODE dmScreenSettings;
	  memset(&dmScreenSettings, 0,sizeof(dmScreenSettings));
	  dmScreenSettings.dmSize   = sizeof(dmScreenSettings);
	  dmScreenSettings.dmPelsWidth = (unsigned long)m_iWindowWidth;
	  dmScreenSettings.dmPelsHeight = (unsigned long)m_iWindowHeight;
	  dmScreenSettings.dmBitsPerPel = 32;
	  dmScreenSettings.dmFields  = DM_BITSPERPEL | DM_PELSWIDTH | DM_PELSHEIGHT;
	  ChangeDisplaySettings(&dmScreenSettings, CDS_FULLSCREEN);
	}
	else
	{
	  posX = (GetSystemMetrics(SM_CXSCREEN) - m_iWindowWidth) /2;
	  posY = (GetSystemMetrics(SM_CYSCREEN) - m_iWindowHeight) /2;
	}

	// Create the window with the screen settings and get the handle to it
	m_hMainWnd = CreateWindowEx(WS_EX_APPWINDOW, m_sWindowTitle.c_str(), m_sWindowTitle.c_str(),
		   WS_CAPTION | WS_POPUPWINDOW | WS_CLIPSIBLINGS | WS_CLIPCHILDREN | WS_POPUP | WS_MINIMIZEBOX,
		   posX, posY, m_iWindowWidth, m_iWindowHeight,
		   NULL, NULL, m_hInstance, NULL );

	if(!m_hMainWnd) {
	  return false;
	}

	// Set window as main focus ~ sets higher priority to this thread
	SetForegroundWindow(m_hMainWnd);
	SetFocus(m_hMainWnd);

	return true;
}
void Window::Shutdown()
{
	// Show the mouse cursor ~ just in case the mouse was hidden in run-time
	ShowCursor(true);

	// Fix the display settings if leaving full screen mode
	if(m_bFullscreen) {
	  ChangeDisplaySettings(NULL, 0);
	}

	// Remove the window
	DestroyWindow(m_hMainWnd);
	m_hMainWnd = NULL;

	// Remove the application's instance
	UnregisterClass(m_sWindowTitle.c_str(), m_hInstance);
	m_hInstance = NULL;
}
void Window::ShowWindow()
{
	::ShowWindow(m_hMainWnd, SW_SHOW);
	::UpdateWindow(m_hMainWnd);
}
LRESULT CALLBACK Window::HandleEvents(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam)
{
	return DefWindowProc(hWnd, msg, wParam, lParam);
}


////////////////////////////////////////////////////////////////////////////////
// Window Procedure
////////////////////////////////////////////////////////////////////////////////
static LRESULT CALLBACK WndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam)
{
	switch(msg)
	{
	case WM_DESTROY:
	  PostQuitMessage(0);
	  return 0;
	case WM_CLOSE:
	  PostQuitMessage(0);
	  return 0;
	}

	return ((Window*)GetWindow(hWnd, 0))->HandleEvents(hWnd, msg, wParam, lParam);
}

So now we should have a nice window appeared on our screen. If not, initialize you data members!
I initialized my data members on a default size 640*480 and title: Default Window

While I was re-programming my framework I found something cool but strange at the same time..
	return ((Window*)GetWindow(hWnd, 0))->HandleEvents(hWnd, msg, wParam, lParam);

This should crash normally but it doesn't. Posted Image
I never allocated that window, or received a pointer of an existing pointer and still. The HandleEvents() method can be called.
I'm sure I'm opening many eyes right now... Yes have a clear look at the code! Posted Image
I thought if was the SetFocus(); method at the start but they make no difference at all. Also you can leave out the "static" keyword. Still doesn't crash.

So this is creating new possibilities I think? You don't need a singleton anymore to call the HandleEvents. Or a static global pointer of your own class. Everything can be done now through this method.



So thank you for your time ladies and gentlemen!! Now I'm going to write the system and graphics class for the next entry. So be sure to have a look! Posted Image You can also follow this blog to make it easier. And so I also know people are interested.


Creotex Engine ~ Introduction

Posted by , 31 August 2012 - - - - - - · 1,293 views
Engine, Programming, Games and 1 more...
Hello ladies and gentlemen,

Welcome to my journal!
I would like to introduce myself before I get started. My name is Jonathan, student of Digital Arts & Entertainment.
I joined this forum about 2 weeks ago. I've been studying C++ for about 2 years now. And I think I'm ready to go to the next level.
In this journal I'll be writing a game engine and thereafter I'll write a game with that engine.
My engine will be supported by DirectX 11 and other supportive libraries.

If you have any questions or suggestions about my coding, feel free to comment!
For the questions , the answer will be given in the next entry through (Q: A:)
For the suggestions, my response will be given in the next entry through (S: A:)

I've been looking around for some tutorials, information about DirectX, engine structures and I happily share the links with you guys. Posted Image
Win32: http://msdn.microsoft.com/en-us/library/bb384843.aspx
Win32 tips&tricks http://www.catch22.net/tuts/win32-tips-tricks#FillArea
Optimizing: http://en.wikibooks.org/wiki/Optimizing_C%2B%2B/Code_optimization/Run-time_support
Game engine structure: http://lspiroengine.com/?p=351
Game engine structure: http://www.ttoprpg.com/gedisc.htm#gecodestruct
DirectX: http://channel9.msdn.com/coding4fun/articles/Beginning-Game-Development-Part-II-Introduction-to-DirectX
DirectX: http://www.directxtutorial.com/Tutorial11/tutorials.aspx
DirectX: http://www.rastertek.com/tutindex.html

In this entry I'm not going to post any code though. This is just the opening for a nice journal. Posted Image





December 2016 »

S M T W T F S
    123
456 7 8910
11121314151617
18192021222324
25262728293031

Recent Entries

Recent Comments