• Create Account

## Creating a DirectX 9.0 window class in C++

Old topic!

Guest, the last post of this topic is over 60 days old and at this point you may not reply in this topic. If you wish to continue this conversation start a new topic.

15 replies to this topic

### #1MartinSmith160  Members

Posted 08 June 2012 - 03:08 AM

Hi All

I have read through Advanced2D development by J Harbour in which you create a 2D directX 9.0 game engine. The engine is based around a single window.

I was planning on doing it the following way but im not sure its the correct approach:

• Write a window class that has all the parameters to allow creation of different types and styles of window
• Each window will have its own D3D device
• Each window will be registered with windows
• Each window will have its own rendering portion, so each sprite on its draw command will pass in it's D3D device (like a GC in openGL)

This is what I plan to do but im not sure about handling the rendering properly. I also can never know how many windows a user could create so I am going to add them to a vector and then iterate over each whilst processing. I haven't really thought about sound yet.

My question is, is there anything blindingly I have missed out or really need to think about before I start this.

Thanks guys,

All the best,
Martin

### #2turch  Members

Posted 08 June 2012 - 07:21 AM

That's more or less the approach I use. One note though, you need one unique D3D device per fullscreen window. If you have multiple non-fullscreen windows, they should share a device. I have a window request a device from a device manager type class at window creation. If it is the first window, a device is created, otherwise the window is given an already created device.

### #3MartinSmith160  Members

Posted 08 June 2012 - 08:01 AM

Thanks turch. Yea each window will have its own device because I want to be able to run both windows in full screen. I'm going to be running my games on a multi monitor system. Thanks for the advice. I guess I will start planning.

Thanks.

### #4MartinSmith160  Members

Posted 12 June 2012 - 06:40 AM

Hi Turch,

Just a quick question, I currently on have one LPD3DXSPRITE which is use as a sprite handler and that is used to draw all the sprites. When I create my sprite handler I have to pass it the LPDIRECT3DDEVICE9

eg D3DXCreateSprite(this->p_device, &this->p_sprite_handler);

My question is, do I now need to create a LPD3DXSPRITE for every window similar to making one LPDIRECT3DDEVICE9 for each window.

Thanks,
Martin

### #5mhagain  Members

Posted 12 June 2012 - 07:15 AM

LPD3DXSPRITE is really nothing more than a regular vertex and index buffer together with some variables, cobbled together into what looks like a D3D interface. So based on that, you can see that the same rules apply for creating sprites as for creatng any other resource - the Create* call is specific to a device and the resource is specific to the device that created it.

Note that D3D9Ex allows for sharing of resources between more than one device, but it's only available on Vista or higher, and comes with a bunch of other restrictions regarding usage and memory pools. I'm not certain if the LPD3DXSPRITE interface exposes this capability for the resources it creates, though.

It appears that the gentleman thought C++ was extremely difficult and he was overjoyed that the machine was absorbing it; he understood that good C++ is difficult but the best C++ is well-nigh unintelligible.

### #6turch  Members

Posted 12 June 2012 - 07:18 AM

Yes you do, and you will also need to duplicate any other device bound objects if you want to use them in either window - vertex buffers, textures, etc will all need to be duplicated.

### #7MartinSmith160  Members

Posted 12 June 2012 - 09:40 AM

Hi Guys

Thanks for you advice. I am having a a few issues with my window creation though. I have created a window wrapper class. I thought it was working because the windows create, are the correct dimensions and positions correctly. BUT when I call CreateWindowEX() it returns a NULL HWND.

Here is my Create function which sets up the window:

[source lang="cpp"]bool ST_Window::Create(HINSTANCE instance, int cmnd){ bool returnStatus = true; appInstance = instance; cmndLineArgs = cmnd; wincl.hInstance = appInstance; wincl.lpszClassName = title; wincl.lpfnWndProc = WindowProc; wincl.style = CS_HREDRAW | CS_VREDRAW; wincl.cbSize = sizeof(WNDCLASSEX); wincl.hIcon = LoadIcon (NULL, IDI_APPLICATION); wincl.hIconSm = LoadIcon (NULL, IDI_APPLICATION); wincl.hCursor = LoadCursor (NULL, IDC_ARROW); wincl.lpszMenuName = NULL; wincl.cbClsExtra = 0; /* No extra bytes after the window class */ wincl.cbWndExtra = 0; /* structure or the window instance */ wincl.hbrBackground = NULL; /* Register the first windows class, and if it fails quit the program returning a 1 so that we know where it failed*/ if (!RegisterClassEx (&wincl)) return 1; hwnd = CreateWindowEx ( 0, /* Extended possibilites for variation */ title, /* Classname */ title, /* Title Text */ WS_OVERLAPPEDWINDOW, /* default window */ xPos, /* X position */ yPos, /* Y position */ width, /* The programs width */ height, /* and height in pixels */ 0, /* The window is a child-window to desktop */ 0, /* No menu */ appInstance, /* Program Instance handler */ 0 /* No Window Creation data */ ); DWORD error = GetLastError(); if(!hwnd) returnStatus = false; return returnStatus;}[/source]

Also here is my windows procedure, each object will have this but its a static function:

[source lang="java"]LRESULT CALLBACK ST_Window::WindowProc(HWND p_hwnd, UINT message, WPARAM wParam, LPARAM lParam){ switch (message) /* handle the messages */ { case WM_DESTROY: PostQuitMessage (0); /* send a WM_QUIT to the message queue */ break; default: /* for messages that we don't deal with */ return DefWindowProc (p_hwnd, message, wParam, lParam); } //return 0;}[/source]

Its really strange because the windows create but no handle is returned. Also I call GetLastError() and it returns 0. I cant setup up and DirectX without the HWNDs so im screwed. Any help would be awesome.

Thanks so much guys,

All the best,
Martin

### #8turch  Members

Posted 13 June 2012 - 06:39 AM

I ran that function in a default windows project and it returned a HWND. Post more code so we can see what's going on around it.

Are you sure the window that is created, is created by that code? You don't call ShowWindow anywhere, and if you just create the window without calling that it won't actually show up.

### #9MartinSmith160  Members

Posted 13 June 2012 - 07:20 AM

Hi Turch

Thats the create function of my window wrapper class. I have a winmain that calls ShowWindow() after its created. The window does show up so thats not the problem.

Here is my winmain code:

[source lang="cpp"]#pragma once#include "ST_Window.h"int WINAPI WinMain (HINSTANCE hThisInstance, HINSTANCE hPrevInstance, LPSTR lpszArgument, int nFunsterStil){ MSG messages; /* Here messages to the application are saved. This is shared in this example */ ST_Window window1("Window1", 0,0,800,600); ST_Window window2("Window2", 1000,0,800,600); window1.Create(hThisInstance,nFunsterStil); window2.Create(hThisInstance,nFunsterStil); window1.ShowThisWindow(); window2.ShowThisWindow(); while(true) { while (PeekMessage (&messages, NULL, 0, 0, PM_REMOVE)) { /* Translates Messages from GetMessage Function */ TranslateMessage(&messages); /* Dipatches Messages */ DispatchMessage(&messages); } //UPDATE ENGINE } return messages.wParam;}[/source]

I dont need to use the windows messaging so I dont mind that messages are shared between windows with the static WinProc. Its really strange, sometimes I get a HWND ok (Normally after a rebuild) but then after that i just get [unused] = ??? as the value.

I cant tell how great full I am for you help, im really stuck on this at the minute.

All the best,
Martin

### #10turch  Members

Posted 13 June 2012 - 07:44 AM

ShowWindow takes a HWND, so if the window shows up you must be passing a valid HWND. Where do you try to return the HWND that doesn't work? Post that code.

Also, post the ST_Window constructor and ShowThisWindow functions.

### #11MartinSmith160  Members

Posted 13 June 2012 - 08:20 AM

Hi Turch

Im getting the HWND later when I want to create the directX device for the window. Basically I pass the window into the device manager and it creates a device and gives it to the window. I took that code out to make it cleaner to read. That code isnt working yet either but I thought it was due to having an invalid HWND. Could it be that the debugger is just showing me the wrong value?

Here is the ST_Window constructors:

[source lang="cpp"]ST_Window::ST_Window(){ appInstance = 0; hwnd = 0; title = "DefaultWindow"; xPos = 0; yPos = 0; width = 800; height = 600; isFullScreen = false; cmndLineArgs = 0; window_device = 0; window_backbuffer = 0; window_sprite_handler = 0; window_ambient_color = D3DCOLOR_RGBA(255,255,255,0);}[/source]
[source lang="cpp"]ST_Window::ST_Window(char *title, int x, int y, int width, int height){ appInstance = 0; hwnd = 0; this->title = title; xPos = x; yPos = y; this->width = width; this->height = height; isFullScreen = false; cmndLineArgs = 0; window_device = 0; window_backbuffer = 0; window_sprite_handler = 0; window_ambient_color = D3DCOLOR_XRGB(255,255,255);}[/source]

Here is the ShowThisWindow() function ( It basically just calls the windows functions but uses the stored HWND)

[source lang="cpp"]bool ST_Window::ShowThisWindow(){ return ShowWindow(hwnd, cmndLineArgs);}[/source]

Here is My DeviceManager class code:

[source lang="cpp"]#include "ST_DeviceManager.h"ST_DeviceManager::ST_DeviceManager(){ deviceCount = 0; devices.clear(); this->d3d = NULL;}ST_DeviceManager::~ST_DeviceManager(){ for(int i = 0; i < devices.size(); i++) { devices[i]->Release(); } d3d->Release();}void ST_DeviceManager::CreateDevice(ST_Window &targetWindow){ if (this->d3d == NULL) { this->d3d = Direct3DCreate9(D3D_SDK_VERSION); } RECT clientWindowRect; GetClientRect(targetWindow.GetHWND(),&clientWindowRect); //get system desktop color depth D3DDISPLAYMODE dm; LPDIRECT3DDEVICE9 newDevice; LPDIRECT3DSURFACE9 newbackbuffer; LPD3DXSPRITE new_sprite_handler; this->d3d->GetAdapterDisplayMode(D3DADAPTER_DEFAULT, &dm); //set configuration options for Direct3D D3DPRESENT_PARAMETERS d3dpp; ZeroMemory(&d3dpp, sizeof(d3dpp)); d3dpp.Windowed = targetWindow.IsFullScreen(); d3dpp.SwapEffect = D3DSWAPEFFECT_DISCARD; d3dpp.EnableAutoDepthStencil = TRUE; d3dpp.AutoDepthStencilFormat = D3DFMT_D16; d3dpp.PresentationInterval = D3DPRESENT_INTERVAL_IMMEDIATE; d3dpp.BackBufferFormat = dm.Format; d3dpp.BackBufferCount = 1; d3dpp.BackBufferWidth = clientWindowRect.right; d3dpp.BackBufferHeight = clientWindowRect.bottom; d3dpp.hDeviceWindow = targetWindow.GetHWND(); //create Direct3D device this->d3d->CreateDevice( D3DADAPTER_DEFAULT, D3DDEVTYPE_HAL, targetWindow.GetHWND(), D3DCREATE_HARDWARE_VERTEXPROCESSING, &d3dpp, &newDevice); //TODO NEED TO ADD CLEAR SCREEN newDevice->GetBackBuffer(0, 0, D3DBACKBUFFER_TYPE_MONO, &newbackbuffer); newDevice->SetRenderState(D3DRS_ZENABLE, TRUE); newDevice->SetRenderState(D3DRS_FILLMODE, D3DFILL_SOLID); newDevice->SetRenderState(D3DRS_LIGHTING, true); newDevice->SetRenderState(D3DRS_AMBIENT,targetWindow.GetWindowAmbientColor()); D3DSURFACE_DESC bb_desc; newbackbuffer->GetDesc(&bb_desc); //SET DEFAULT MATERIAL D3DMATERIAL9 mat; memset(&mat, 0, sizeof(mat)); mat.Diffuse.r = mat.Ambient.r = 1.0f; mat.Diffuse.g = mat.Ambient.g = 1.0f; mat.Diffuse.b = mat.Ambient.b = 1.0f; mat.Diffuse.a = mat.Ambient.a = 1.0f; newDevice->SetMaterial(&mat); targetWindow.SetWindowDevice(newDevice); targetWindow.SetWindowBackBuffer(newbackbuffer); newDevice = 0; newbackbuffer = 0; new_sprite_handler = 0;}[/source]

Its very simplistic at this stage, I just wanted to get it working fundamentally. The DeviceManager::CreateDevice() is called after the window is created.

Sorry to bombard you with code. Basically if I call the CreateDevice() function my screen flashes black and the app locks up so I know something is majorly wrong but I thought its was not having a valid HWND. I stepped through the code for the CreateDevice() function and it locks up after this->d3d->CreateDevice() is called.

Thanks again for your help dude.
C:\Users\stormoffice\Desktop\HWND_Problem.png

### #12MartinSmith160  Members

Posted 13 June 2012 - 08:44 AM

Holy Shit, I made such a stupid error.

check line 41 of the ST_DeviceManager::CreateDevice(ST_Window &targetWindow) code. I set d3dpp.Windowed depending on the windows fulscreen status. As of now the isFullscreen variable is aslways false. so d3dpp.windowed was set to false making it try to go fullscreen but its not setup for it. I changed it to be d3dpp.Windowed = !targetWindow.IsFullScreen(); and The windows open and the devices are created correctly.

The HWND issue still confuses me though. The createDevice function works outs the correct window client area by getting the HWND from the window, but when I look at it in the debugger it still just says unused = ???

Very strange.

Thank you so much for your help and im sorry if its seems like I wasted your time.

All the best,
Martin

### #13turch  Members

Posted 13 June 2012 - 09:53 AM

Hah, I actually made the same error when I was testing it a second ago... I set windowed to false thinking it was "fullscreen" - don't worry, the most frustrating and time consuming bugs are the ones where you make a stupid mistake. You gloss over the mistake because you can't possibly make a mistake so simple

Look into rubber duck debugging - whenever I'm searching for a bug and I just can't find it, I call in another dev and start explaining the code to them. They don't do anything or participate or even listen, but the act of explaining it that way forces you to consider those details you overlook because they are so obvious ( if (condition = true) ).

As for the HWND issue, make sure you are compiling and running the debug configuration, not release. If you try debugging a release build, you usually get incorrect data / variable unused / not found / etc. because the compiler doesn't insert debug information and mangles the code quite a bit for optimizations, and thus it can't find the variable.

And just a few more random thoughts:

consider wrapping all your raw directx pointers like so
typedef CComPtr<IDirect3D9> D3DPtr;
typedef CComPtr<IDirect3DDevice9> D3DDevicePtr;


That way, you don't have to call remember when you need to call Release, it will save you tons of time looking for memory leaks. You just use D3DPtr in place of LPDIRECT3D9

You might want to create only one D3DDevice for all (non-fullscreen) windows. Almost everything (textures, vertex buffers, shaders) is device-bound, so if you want to use one texture in two devices, you have to create it twice and keep track of which one belongs to which device. I use something similar to this (pseudocode):

Window::Create(devicemanager)
if (devicemanager.device == null)
m_device = devicemanager.CreateDevice()
else
m_device = devicemanager.device


If you want multiple fullscreen windows, however, you have to use multiple devices. But most of the time all you really need multiple windows for is a level editor or other tools, and don't need them to run in fullscreen.

### #14MartinSmith160  Members

Posted 13 June 2012 - 10:41 AM

Thanks Turch

I am running in debug mode for sure. The thing is sometimes it shows the HWND value and sometimes it dosent. BUT it always has a hex value. if it was NULL I would assume the hex value would be like 0x000000 or summin but it has an actual value so maybe its so large that the debugger cant show it. I might be speaking bollocks but it was just a thought.

Thats great advice for the debugging and the DirectX pointers aswell so thanks, I will definitely use that.As far as fullscreen goes, I will always be running two windows both in fullscreen because the games I aim to develop are for a multi monitor platform.

Thanks for all you help dude, you have really helped.

### #15Khatharr  Members

Posted 13 June 2012 - 04:00 PM

The debugger recognizes the types of variables and displays them accordingly. There's no variable type that's too large for it. NULL is == (void*)0, so if the debugger says 0x00000000 for a pointer then that's a NULL. You can trust it on this kind of thing. ;)
void hurrrrrrrr() {__asm sub [ebp+4],5;}

There are ten kinds of people in this world: those who understand binary and those who don't.

### #16MartinSmith160  Members

Posted 14 June 2012 - 01:09 AM

Hi Khatharr

Thanks for the input, would you know of a reason then that when I look at my HWND values in the debugger its says 0x000109ba {unused = 0} but the handle still works.

All the best,
Martin.

Old topic!

Guest, the last post of this topic is over 60 days old and at this point you may not reply in this topic. If you wish to continue this conversation start a new topic.