Sign in to follow this  

OpenGL Creating a DirectX 9.0 window class in C++

Recommended Posts

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,

Share this post

Link to post
Share on other sites
That's more or less the approach I use. One note though, you need one unique D3D device per [i]fullscreen [/i]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.

Share this post

Link to post
Share on other sites
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.


Share this post

Link to post
Share on other sites
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.


Share this post

Link to post
Share on other sites
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.

Share this post

Link to post
Share on other sites
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.

Share this post

Link to post
Share on other sites
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; = 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();

returnStatus = false;

return returnStatus;

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 */
PostQuitMessage (0); /* send a WM_QUIT to the message queue */
default: /* for messages that we don't deal with */
return DefWindowProc (p_hwnd, message, wParam, lParam);

//return 0;

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,

Share this post

Link to post
Share on other sites
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 [url=""]ShowWindow[/url] anywhere, and if you just create the window without calling that it won't actually show up.

Share this post

Link to post
Share on other sites
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);



while (PeekMessage (&messages, NULL, 0, 0, PM_REMOVE))
/* Translates Messages from GetMessage Function */
/* Dipatches Messages */


return messages.wParam;

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,

Share this post

Link to post
Share on other sites
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 [color="#000000"]ST_Window[/color] constructor and ShowThisWindow functions.

Share this post

Link to post
Share on other sites
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 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);

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);

Here is My DeviceManager class code:

[source lang="cpp"]#include "ST_DeviceManager.h"

deviceCount = 0;
this->d3d = NULL;

for(int i = 0; i < devices.size(); i++)


void ST_DeviceManager::CreateDevice(ST_Window &targetWindow)
if (this->d3d == NULL)
this->d3d = Direct3DCreate9(D3D_SDK_VERSION);

RECT clientWindowRect;

//get system desktop color depth
LPDIRECT3DSURFACE9 newbackbuffer;
LPD3DXSPRITE new_sprite_handler;

this->d3d->GetAdapterDisplayMode(D3DADAPTER_DEFAULT, &dm);

//set configuration options for Direct3D
ZeroMemory(&d3dpp, sizeof(d3dpp));
d3dpp.Windowed = targetWindow.IsFullScreen();
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


newDevice->GetBackBuffer(0, 0, D3DBACKBUFFER_TYPE_MONO, &newbackbuffer);

newDevice->SetRenderState(D3DRS_ZENABLE, TRUE);
newDevice->SetRenderState(D3DRS_FILLMODE, D3DFILL_SOLID);
newDevice->SetRenderState(D3DRS_LIGHTING, true);


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 = 0;
newbackbuffer = 0;
new_sprite_handler = 0;

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.

Share this post

Link to post
Share on other sites
Holy Shit, I made such a stupid error.

check line 41 of the [color=#000000][font=Consolas,]ST_DeviceManager::CreateDevice(ST_Window &targetWindow) code. I set [/font][/color][color=#000000][font=Consolas,]d3dpp.Windowed [/font][/color][color=#000000][font=Consolas,]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 [/font][/color][color=#000000][font=Consolas,]d3dpp.Windowed = !targetWindow.IsFullScreen(); and [/font][/color][color=#000000][font=Consolas,]The windows open and the devices are created correctly.[/font][/color]

[color=#000000][font=Consolas,]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 = ??? [/font][/color]

[color=#000000][font=Consolas,]Very strange.[/font][/color]

[color=#000000][font=Consolas,]Thank you so much for your help and im sorry if its seems like I wasted your time.[/font][/color]

[color=#000000][font=Consolas,]All the best,[/font][/color]

Share this post

Link to post
Share on other sites
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 [i]possibly [/i]make a mistake so simple [img][/img]

Look into [url=""]rubber duck debugging[/url] - 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):

if (devicemanager.device == null)
m_device = devicemanager.CreateDevice()
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.

Share this post

Link to post
Share on other sites
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.

Share this post

Link to post
Share on other sites
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. ;)

Share this post

Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this  

  • Announcements

  • Forum Statistics

    • Total Topics
    • Total Posts
  • Similar Content

    • By test opty
      Hi all,
      I'm starting OpenGL using a tut on the Web. But at this point I would like to know the primitives needed for creating a window using OpenGL. So on Windows and using MS VS 2017, what is the simplest code required to render a window with the title of "First Rectangle", please?
    • By DejayHextrix
      Hi, New here. 
      I need some help. My fiance and I like to play this mobile game online that goes by real time. Her and I are always working but when we have free time we like to play this game. We don't always got time throughout the day to Queue Buildings, troops, Upgrades....etc.... 
      I was told to look into DLL Injection and OpenGL/DirectX Hooking. Is this true? Is this what I need to learn? 
      How do I read the Android files, or modify the files, or get the in-game tags/variables for the game I want? 
      Any assistance on this would be most appreciated. I been everywhere and seems no one knows or is to lazy to help me out. It would be nice to have assistance for once. I don't know what I need to learn. 
      So links of topics I need to learn within the comment section would be SOOOOO.....Helpful. Anything to just get me started. 
      Dejay Hextrix 
    • By mellinoe
      Hi all,
      First time poster here, although I've been reading posts here for quite a while. This place has been invaluable for learning graphics programming -- thanks for a great resource!
      Right now, I'm working on a graphics abstraction layer for .NET which supports D3D11, Vulkan, and OpenGL at the moment. I have implemented most of my planned features already, and things are working well. Some remaining features that I am planning are Compute Shaders, and some flavor of read-write shader resources. At the moment, my shaders can just get simple read-only access to a uniform (or constant) buffer, a texture, or a sampler. Unfortunately, I'm having a tough time grasping the distinctions between all of the different kinds of read-write resources that are available. In D3D alone, there seem to be 5 or 6 different kinds of resources with similar but different characteristics. On top of that, I get the impression that some of them are more or less "obsoleted" by the newer kinds, and don't have much of a place in modern code. There seem to be a few pivots:
      The data source/destination (buffer or texture) Read-write or read-only Structured or unstructured (?) Ordered vs unordered (?) These are just my observations based on a lot of MSDN and OpenGL doc reading. For my library, I'm not interested in exposing every possibility to the user -- just trying to find a good "middle-ground" that can be represented cleanly across API's which is good enough for common scenarios.
      Can anyone give a sort of "overview" of the different options, and perhaps compare/contrast the concepts between Direct3D, OpenGL, and Vulkan? I'd also be very interested in hearing how other folks have abstracted these concepts in their libraries.
    • By aejt
      I recently started getting into graphics programming (2nd try, first try was many years ago) and I'm working on a 3d rendering engine which I hope to be able to make a 3D game with sooner or later. I have plenty of C++ experience, but not a lot when it comes to graphics, and while it's definitely going much better this time, I'm having trouble figuring out how assets are usually handled by engines.
      I'm not having trouble with handling the GPU resources, but more so with how the resources should be defined and used in the system (materials, models, etc).
      This is my plan now, I've implemented most of it except for the XML parts and factories and those are the ones I'm not sure of at all:
      I have these classes:
      For GPU resources:
      Geometry: holds and manages everything needed to render a geometry: VAO, VBO, EBO. Texture: holds and manages a texture which is loaded into the GPU. Shader: holds and manages a shader which is loaded into the GPU. For assets relying on GPU resources:
      Material: holds a shader resource, multiple texture resources, as well as uniform settings. Mesh: holds a geometry and a material. Model: holds multiple meshes, possibly in a tree structure to more easily support skinning later on? For handling GPU resources:
      ResourceCache<T>: T can be any resource loaded into the GPU. It owns these resources and only hands out handles to them on request (currently string identifiers are used when requesting handles, but all resources are stored in a vector and each handle only contains resource's index in that vector) Resource<T>: The handles given out from ResourceCache. The handles are reference counted and to get the underlying resource you simply deference like with pointers (*handle).  
      And my plan is to define everything into these XML documents to abstract away files:
      Resources.xml for ref-counted GPU resources (geometry, shaders, textures) Resources are assigned names/ids and resource files, and possibly some attributes (what vertex attributes does this geometry have? what vertex attributes does this shader expect? what uniforms does this shader use? and so on) Are reference counted using ResourceCache<T> Assets.xml for assets using the GPU resources (materials, meshes, models) Assets are not reference counted, but they hold handles to ref-counted resources. References the resources defined in Resources.xml by names/ids. The XMLs are loaded into some structure in memory which is then used for loading the resources/assets using factory classes:
      Factory classes for resources:
      For example, a texture factory could contain the texture definitions from the XML containing data about textures in the game, as well as a cache containing all loaded textures. This means it has mappings from each name/id to a file and when asked to load a texture with a name/id, it can look up its path and use a "BinaryLoader" to either load the file and create the resource directly, or asynchronously load the file's data into a queue which then can be read from later to create the resources synchronously in the GL context. These factories only return handles.
      Factory classes for assets:
      Much like for resources, these classes contain the definitions for the assets they can load. For example, with the definition the MaterialFactory will know which shader, textures and possibly uniform a certain material has, and with the help of TextureFactory and ShaderFactory, it can retrieve handles to the resources it needs (Shader + Textures), setup itself from XML data (uniform values), and return a created instance of requested material. These factories return actual instances, not handles (but the instances contain handles).
      Is this a good or commonly used approach? Is this going to bite me in the ass later on? Are there other more preferable approaches? Is this outside of the scope of a 3d renderer and should be on the engine side? I'd love to receive and kind of advice or suggestions!
    • By nedondev
      I 'm learning how to create game by using opengl with c/c++ coding, so here is my fist game. In video description also have game contain in Dropbox. May be I will make it better in future.
  • Popular Now