Smarkus

[DirectX9 Bitmaps] Can someone help me out with a nullptr check?

Recommended Posts

Smarkus    141
//page 120
#include <Windows.h>
#include <windef.h>
#include <winuser.h>
#include <d3d9.h>
#include <d3dx9.h>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>

//#pragma comment (lib,"d3d9.lib")	//library's link
//#pragma comment (lib,"d3dx9.lib")
//#pragma comment (lib,"dxguid.lib")
//#pragma comment (lib,"winmm.lib")	//システム時刻取得に必要 | マルチメディアライブラリ(Windows Multimedia Library)
//#pragma comment (lib,"dinput8.lib")

#define APPTITLE "CreateSurface"

#define KEY_DOWN(vk_code)((GetAsyncKeyState(vk_code)&0x8000)?1:0)
#define KEY_UP(vk_code)((GetAsyncKeyState(vk_code)&0x8000)?1:0)

#define SCREEN_WIDTH 640
#define SCREEN_HEIGHT 480

//function prototypes
LRESULT WINAPI WinProc(HWND, UINT, WPARAM, LPARAM);
ATOM MyRegisterClass(HINSTANCE);
int GameInit(HWND);
void GameRun(HWND);
void GameEnd(HWND);

//Direct3D Objects
LPDIRECT3D9 d3d = NULL;
LPDIRECT3DDEVICE9 d3ddev = NULL;
LPDIRECT3DSURFACE9 surface = NULL;
LPDIRECT3DSURFACE9 backbuffer = NULL;

LRESULT WINAPI WinProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam)
{
	switch (msg)
	{
	case WM_QUIT:
		GameEnd(hWnd);
		PostQuitMessage(0);
		return 0;
	}
	return DefWindowProc(hWnd, msg, wParam, lParam);
}

//helper function to set up windows properties
ATOM MyRegisterClass(HINSTANCE hInstance)
{
	// create struucture
	WNDCLASSEX wc;
	wc.cbSize = sizeof(WNDCLASSEX);

	//fill the structure with information
	wc.style			= CS_HREDRAW | CS_VREDRAW;
	wc.lpfnWndProc		= (WNDPROC)WinProc;
	wc.cbClsExtra		= 0;
	wc.cbWndExtra		= 0;
	wc.hInstance		= hInstance;
	wc.hIcon			= NULL;
	wc.hCursor			= LoadCursor(NULL, IDC_ARROW);
	wc.hbrBackground	= (HBRUSH)GetStockObject(WHITE_BRUSH);
	wc.lpszMenuName		= NULL;
	wc.lpszClassName	= APPTITLE;
	wc.hIconSm			= NULL;

	//set up the window with the class info
	return RegisterClassEx(&wc);
}

//Entry point for a windows program
int WINAPI WinMain(HINSTANCE hInstance,
	HINSTANCE hPrevInstance,
	LPSTR lpCmdLine,
	int    nCmdShow)
{
	MSG msg;

	MyRegisterClass(hInstance);

	HWND hWnd;
	
	hWnd = CreateWindow(
		APPTITLE,
		APPTITLE,
		WS_EX_TOPMOST | WS_VISIBLE | WS_POPUP,
		CW_USEDEFAULT,
		CW_USEDEFAULT,
		SCREEN_WIDTH, SCREEN_HEIGHT,
		NULL, NULL,
		hInstance,
		NULL
	);

	if (!hWnd)
	{
		return FALSE;
	}

	ShowWindow(hWnd, nCmdShow);
	UpdateWindow(hWnd);
	
	if (!GameInit(hWnd))
	{
		return 0;
	}
	
	//Main Message loop
	int done = 0;

	while (!done)
	{
		if (PeekMessage(&msg, NULL, 0, 0, PM_REMOVE))
		{
			if (msg.message == WM_QUIT)
			{
				done = 1;
			}
			TranslateMessage(&msg);
			DispatchMessage(&msg);
		}
		else
		{
			GameRun(hWnd);
		}
	}
	return msg.wParam;
}

int GameInit(HWND hwnd)
{
	HRESULT result;

	//initialize Direct3D 
	d3d = Direct3DCreate9(D3D_SDK_VERSION); 
	
	if (d3d == NULL)
	{
		MessageBox(hwnd, "Error initializing Direct3D", "Error", MB_OK);
		return 0;
	}

	//set Direct3D presentation parameters 
	D3DPRESENT_PARAMETERS d3dpp;
	ZeroMemory(&d3dpp, sizeof(d3dpp));

	d3dpp.Windowed = TRUE; 
	d3dpp.SwapEffect = D3DSWAPEFFECT_DISCARD; 
	d3dpp.BackBufferFormat = D3DFMT_X8R8G8B8;
	d3dpp.BackBufferCount = 1;
	d3dpp.BackBufferWidth = SCREEN_WIDTH;
	d3dpp.BackBufferHeight = SCREEN_HEIGHT;
	d3dpp.hDeviceWindow = hwnd;

	//create Direct3D device 
	d3d->CreateDevice( D3DADAPTER_DEFAULT, D3DDEVTYPE_HAL, hwnd, D3DCREATE_SOFTWARE_VERTEXPROCESSING, &d3dpp, &d3ddev); 
	
	if (d3ddev = NULL)
	{
		MessageBox(hwnd, "Error creating Direct3D device", "Error", MB_OK); 
		return 0;
	}

	//set random number seed 
	srand(time(NULL));
	
	//Clear the backbuffer to black
	d3ddev->Clear(0, NULL, D3DCLEAR_TARGET, D3DCOLOR_XRGB(0, 0, 0), 1.0f, 0);
	//Create pointer to back buffer
	d3ddev->GetBackBuffer(0, 0, D3DBACKBUFFER_TYPE_MONO, &backbuffer);

	//create surface
	result = d3ddev->CreateOffscreenPlainSurface(
		100, 100,
		D3DFMT_X8R8G8B8,
		D3DPOOL_DEFAULT,
		&surface,
		NULL);

	if (result!=D3D_OK)
	{
		return 1;
	}

	//load surface from file
	result = D3DXLoadSurfaceFromFile(
		surface,
		NULL, NULL,
		"char.jpg",
		NULL,
		D3DX_DEFAULT,
		0, NULL);
	//make sure file was loaded fine
	if (result != D3D_OK)
	{
		return 1;
	}

	//draw surface to back buffer
	d3ddev->StretchRect(surface, NULL, backbuffer, NULL, D3DTEXF_NONE);

	//return okay
	return 1;
}

void GameRun(HWND hwnd)
{
	RECT rect;
	int r, g, b;

	if (d3ddev == NULL)
	{
		return;
	}

	if (d3ddev->BeginScene())
	{
		//Create pointer to the back buffer
		d3ddev->GetBackBuffer(0, 0, D3DBACKBUFFER_TYPE_MONO, &backbuffer);

		//draw surface to the back buffer
		d3ddev->StretchRect(surface, NULL, backbuffer, NULL, D3DTEXF_NONE);

		//stop rendering
		d3ddev->EndScene();
	}
	d3ddev->Present(NULL, NULL, NULL, NULL);

	//check for escape key to exit program
	if (KEY_DOWN(VK_ESCAPE))
	{
		PostMessage(hwnd, WM_DESTROY, 0, 0);
	}
}

void GameEnd(HWND hwnd)
{
	//free the surface
	surface->Release();

	if (d3ddev != NULL)
	{
		d3ddev->Release();
	}

	if (d3d != NULL)
	{
		d3d->Release();
	}
}

So this is the code. I'm following a book and I checked If I made any mistakes. The picture shows what the error is. Can someone help?

Also, what is the default location for a file/bitmap/jpg in my case?

gamdev.PNG

Share this post


Link to post
Share on other sites
markypooch    1315

Here goes one problem

if (d3ddev = NULL)
	{
		MessageBox(hwnd, "Error creating Direct3D device", "Error", MB_OK); 
		return 0;
	}

Use '==' to test for equivalancy. Which explains why you make it to the exception being thrown. I'm guessing this call is failing here. Make sure the values you are passing to this function are valid

d3d->CreateDevice( D3DADAPTER_DEFAULT, D3DDEVTYPE_HAL, hwnd, D3DCREATE_SOFTWARE_VERTEXPROCESSING, &d3dpp, &d3ddev);

 

 

Edited by markypooch

Share this post


Link to post
Share on other sites
Smarkus    141
3 minutes ago, markypooch said:

Here goes one problem


if (d3ddev = NULL)
	{
		MessageBox(hwnd, "Error creating Direct3D device", "Error", MB_OK); 
		return 0;
	}

Which explains why you make it to the exception being thrown.

I'm guessing this call is failing here. Make sure the values you are passing to this function are valid


d3d->CreateDevice( D3DADAPTER_DEFAULT, D3DDEVTYPE_HAL, hwnd, D3DCREATE_SOFTWARE_VERTEXPROCESSING, &d3dpp, &d3ddev);

 

 

Not sure if this is the problem, the book has the same code for device as mine. Is there anything that could possibly be wrong?

Share this post


Link to post
Share on other sites
markypooch    1315

Trust me on this one. All technical books have errata. In this case I'm very much assuming the technical editor missed this. Add the '==' to that if condition, and you should see that error message box popup telling you that device creation failed.

Share this post


Link to post
Share on other sites
fastcall22    10840
4 minutes ago, Jamal Nasir said:

Not sure if this is the problem, the book has the same code for device as mine.

Then it must be a typo, consider the following:

struct Foobar {
	int x;
	void frobnicate() {
		cout << this->x;
	}
};

int main() {
	Foobar* f = new Foobar {3};
	if ( f = nullptr ) { // Compiler should warn about this line
		return -1;
	}

	f->frobnicate(); // This will always crash
	delete f;
}

 

Share this post


Link to post
Share on other sites
Smarkus    141
3 minutes ago, markypooch said:

Trust me on this one. All technical books have errata. In this case I'm very much assuming the technical editor missed this. Add the '==' to that if condition, and you should see that error message box popup telling you that device creation failed.

Oh awesome! It works now, thank you so much!

Share this post


Link to post
Share on other sites
mhagain    13430

Rather than testing for NULL after CreateDevice you really should be testing the HRESULT it returns, using the SUCCEEDED and FAILED macros, with failure HRESULTs giving you some more info on why it failed.

You also have a nasty memory leak in that code - you need a surface->Release for each GetBackBuffer call. In this case it won't destroy the backbuffer because GetBackBuffer will increment the reference count for it, so Release will just decrement it; it doesn't get destroyed until the reference count goes to 0.

Share this post


Link to post
Share on other sites
Norman Barrows    7179
On 6/19/2017 at 0:14 PM, Smarkus said:

d3d = Direct3DCreate9(D3D_SDK_VERSION);

this creates a d3d device, and d3d points to it.

On 6/19/2017 at 0:14 PM, Smarkus said:

if (d3d = NULL)  { 

and then this sets d3d to NULL, then checks to see if d3d is zero or non-zero,  and executes the code block if its non-zero. Since it was just set to NULL (ie zero), its never non-zero, so the code block never executes, and you are always NULL-ing out your d3d device pointer. A guaranteed show stopper there.

this is because evaluating expressions inside the condition statement has a higher precedence (IE gets done first).

In the end its simply a typo quite common to c/c++.

lesson learned: always double check those == statements. its a typo that syntax checking can't pick up, which leads to a logic error. it can only be found by code inspection or testing (or both ?).

Share this post


Link to post
Share on other sites
mhagain    13430
18 hours ago, Adam_42 said:

I'd also recommend turning on the compiler warning that will catch this, by increasing the warning level to 4 in Visual Studio.

You could even go as far as turning that warning into an error by doing:


#pragma warning(error : 4706)

 

What might not be obvious is that you can make this an error even without bumping your warning level to 4 (although you should be compiling with warning level 2 or 3 at least, as well as with warnings-as-errors, anyway).

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


  • Similar Content

    • By LucKet
      Hey guys,
      I'm quite new to game development (had two small projects in university with Unity and libgdx and wrote quite a bunch of Minecraft plugins and mods but that's mostly it) and want to expand my knowledge in a cool project. I'd love to find a project I'm passionate to work on. I personally don't play any browser or mobile game, thus I'd prefer a desktop game. I'd love to dig into fields like graphics (already had DirectX in university but would love to learn more), AI and general game programming. I'm mostly playing open world, RTS, tycoon, simulation and MOBA games but am open to new genres and ideas. It doesn't have to be a game, if you have an interesting project like an engine or something else just tell me. Even though I'd love to be a proud player of the game we will create.
      If someone has a cool project just PM me, I'd love to hear about it and hopefully it will enthrall me as much as you!
    • By winnex RD
      Hello  forum.

      Am migrating a WD7 to WDK 10 (Environment is  Visual Studio  2015, Windows  10, windows Driver).
      In windows Driver filters are Folder capture.ong is the visual studio enviobement while  wdk7 folders is the original WDK7 folders.
      I just created a filters  and created the  necessary  files inside.
      I do want to know if i am doing the right thing.

      If am wrong would  gladly appreciate correction.
      Attached  are the  snapshots of my environment
       
      Thank you


    • By tope awolowo

      Good day  forum.

      Am trying to connvert a WDK 7 project (https://github.com/basil00/Divert. windowsdivert ) to WDK 10 (Environment is  Visual Studio  2015, Windows  10, windows Driver).
      In the template for  windows drivers Visual Studio  2015 which are :

      Kernel  Mode Driver (KMDF)
      Kernel  Mode Driver (KMDF)  EMPTY
      User  Mode Driver (UMDF V2)

      User Mode Empty  (UMDF V2).
      What is stressing is this, Would like to know  which should i use to start and populated the project.
      Should i use the Kernel  Mode Driver (KMDF)  EMPTY, then  populate it  with codes  from Windivert 
      Which  driver   template  should i use.
    • By Jesse "Chime" Collins
       

      This is only the beginning, VRm I right?
      Not unlike an arms race, the VR price war has only begun. Who has the best Equipment? Early this Summer, Oculus had a massive sale on their device, the Oculus Rift, ending in a permanent price drop. HTC is now following suit, cutting out the sale, dropping the price altogether on their Vive Head-Mounted Display.
      Yesterday, The HTC Vive took a hefty slash in price, dropping from their $799 price tag, down to $599. This comes as no surprise after the Oculus Rift dropped down to $399 earlier this Summer on sale. At the end of the sale, the price raised back up to $499 as the final price, $100 less than previous to the sale.
      The HTC Vive comes with plenty of their worth for the price, too. Along with the head-mounted display, accessories include two wireless controllers, two bases stations, comfort-related materials, and everything purchasers need to get going (cords, etc.). Additionally, the system comes with Google Tilt Brush, Everest VR, and Richie’s Plank Experience as promotional content, as well as one-month subscription to Viveport.
      Vive's Giving Away Some Free Content For New Owners

      As a breakdown of the free content, purchasers of the Vive get $53 of extra content from the promotional pack. Google Tilt Brush ($19.99 retail value) gives artists a full 360-degree canvas to paint massive murals and masterpieces. Everest VR ($14.99 retail value) allows people to climb Mount Everest in first-person, without the fear of dying from hypothermia. Richie’s Plank Experience is a starter “game” for new VR players, teaching balance using VR, as well as giving a couple extra modes like a sky-writing experience.
      But, that’s not all! Purchasers of the $600 system also get a free 1-month subscription to Viveport, HTC’s subscription service, valued at the incredibly pricey $6.99. Subscribers can choose five games/experiences to try out during their subscription period, with five more for each additional subscribed month. The list to choose from includes some amazing titles like ROM: Extraction, which has players shooting robots in a space station. But, people should research their potential options to maximise their potential. For instance, players can also choose the (somehow) award winning title, BUTTS: The VR Experience, which may or may not push virtual reality to its foremost limits (spoiler: it doesn’t).
      But, What About Me And You?

      The question to ask is “What does this mean for potential VR buyers?” Well, the war is in motion here, showing both of these price drops. Virtual Reality enthusiasts and companies are pushing that VR is the future. With this price drop, the Vive finally becomes more affordable to the masses, as well as the even more affordable Oculus Rift. But, alas, other companies are starting to get in on the game, as well.
      Some people just want entertainment instead of gaming. Artists want whitespace to create. Experiences can be strapped to a face for cheap. Google, the folks that bring the Daydream to the VR market, is pushing their own boundaries by teaming up with HTC and Lenovo for cost-effective standalone experiences. Microsoft’s HoloLens will take users into augmented reality, albeit from a much higher price. VRotica, an erotica-enabled standalone HMD device already on the market, costs a fraction of the price of other HMDs.
      Essentially, VR is getting cheaper. For those that have a device already, awesome. The experiences are unlike anything ever before. For potential buyers, as with all technology in history, VR is getting cheaper all the time. Thousands of games and experiences inhabit the SteamVR storefront and respective virtual shops.
      “VR Ready” Computers are coming down in price as well, eventually making the idea a non-issue. But, the average joe still has to fork out some cash for a game-capable machine, because cheap computers still can’t handle it. VR, at the moment, is for the elite, but it won’t be for too much longer.
      Is it the perfect time to grab a now $599 Vive, a recently dropped $499 Rift, or should buyers wait it out for even better prices and devices later?
    • By MarcusAseth
      I think shouldn't be far from true to say that often beginners feel lost and don't know the best way to improve their skills, especially if they are self-thaught in wathever they are learning, being it 2D, 3D, Programming or wathever. There could be many obstacles and pitfall to learning, it could be that since one is begginner he/she doesn't realize that the scope of his project is just too big, or maybe one can't come up with a good story/gameplay for his life so lack the motivation to even attempt doing anyting on his own, and maybe one is stuck in a situation where would like to have the story/gameplay aspect figured out by someone better at it (by joining a team) but lack the technical skill to join said team and has an hard time gaining said skill because is not in a team to begin with.
      So I thought, something that can help beginners grow faster is something I saw in other communities around the web, which is friendly competitions.
      The ones I know of are mostly 2D-3D related, for instance polycount.com "Bi-Monthly CHARACTER ART Challenge" and "Monthly Environment Art Challenge", or conceptart.org "Character of the Week", "Creature of the Week", "Environment of the Week".
      Of course there are many more of this challenges I would like to see come into existence related to programming and game engines, for instance challenges in making certain games (see usual tetris/pong but also something more unique and specific, given some guidelines) and challenges like "Create a Water shader in Unreal Engine", or "Create a water ripple particle effect" and so on.
      The cool thing about this is that begginner could compare each other works (professional hopefully join in the challenge as well) and see how the best resoult where obtained, with everyone focusing/researching on the same task and learning from the best examples. This stuff is not far from something like school exercise from my point of view, therefore something invaluable for self-taught beginners who are at higher risk of getting lost by lack of direction.
      And here's gamedev.net twist on the subject, by joining and completing the current challenges one would get "achievments" or "medals" that are visible in his profile and under his avatar, as a cool way to improve his rep and keep the community active
      This is the kind of place I would like to see, where one join, check the current challenges list and decide to join in and learn something new  or improve on the subject during that day/week. Also often I open the forum and there are no new topic that need to be replied, therefore this would keep us all busy in the free time
      Of course, maybe this sounds fun on digital paper but could end up not working, I have no idea if this stuff can work smoothly on sites that have less than a certain treshold of traffic, and it also require the time from someone actively creating this challenges content.
      Well anyway, I think it is worth thinking about it, let me know what do you think
  • Popular Now