Smarkus

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

10 posts in this topic

//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

0

Share this post


Link to post
Share on other sites

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
3

Share this post


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

0

Share this post


Link to post
Share on other sites

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.

2

Share this post


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

 

2

Share this post


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

0

Share this post


Link to post
Share on other sites

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.

1

Share this post


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

3

Share this post


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

0

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 Geri
      This is a Visual Novel Engine.
      Its FREE.
      It supports Android, Linux, and Windows. This engine allows you to create Visual Novels without programming knowledge.

       
      Its capable of north/east/south/west orientation, and have a simple bult-in battle system with 
      attack, HP, and escape (teleport) system. The engine is capable of item handling and room teleporting.


      To make a game, you have to do a directory for every room (map), then copy the background in, and 
      create a text file to describe the room with text. You need an apk editor to change the files in the
      Android package. By default, it contains a minigame to show you the things. 
       
      -It supports the most common image and sound formats (jpg, png, wav, ogg). 
      -room (map) based movement
      -jpg and png backgrounds
      -hero avatar
      -It supports battle system with escape system (also good for creating custom dialogs) including HP management
      -enemy avatar
      -ogg and was music play as background music per rooms and battles
      -teleportation
      -item usage, and item existence based teleportation
      -gameover/happy game-end
      -linux, and windows executables
      -android apk (you must edit the files into it),
      -its free.
       
      download: http://VisualNovelEngine.tk 
       
       
    • By OmicronStudio
       
       
      Deus Vult - Arena is an Action Adventure and TPS with Stealth elements and a combat system based on the tactical ability and quick reflexes of the player.
      Deys Vult - Arena is the realization of a dream born playing the great masterpieces of our childhood like 'Soul Reaver', 'Metal Gear Solid', 'Doom' and a little touch of 'The Legend Of Zelda'
      The beating heart of the DVA experience is the dualism of its gameplay. The Main Characters will be 2; Lulu and Minocar, trapped in an indissoluble link! They will need each others to proceed in the adventure. With Lulu we will face the phases of Exploration, Stealth, Puzzle. And transformed in Minocar we will take on the Arenas! Making our way through hordes of enemies with viciousness, tearing and absorbing their spirits to increase our power.
      We will move our first steps impersonating Lulu, a spirit with a dark past that doesnt have any memories or consciousness of who he is or why he is there. Then we will meet Minocar, a mysterious talking skull with an axe stuck in his cranium, to whom Lulu will speak as his master.
      The story of DVA starts in Lythra, a place devastated by a supernatural catacylsm and populated by hostile creatures and deadly traps! The players goal will be to escape Lythra, to do so he will need to explore every corner of his prison, following the clues that Minocar will give him and learning to make use of his immense power!
      Lythra is an infernal dimension twisted by a supernatural cataclysm, the player will discover what really happened through clues scattered around the map, and talking with the Pure Spirits and with Minocar during the course of the adventure.
      Deus Vult-Arena is a game with a persistent world, thoroughly walkable from one end to the other without interruptions, the map in its actual state has 6 dungeons linked with various shortcuts and secret passages between one area and the other, in every dungeon there are many arenas and secret zones, only accessible through solving of ambiental puzzles or looting specific items:
       
      Minocar and Lulu togheter will be able to acquire a physical body:
      The main goal of the combat system of Deus Vult - Arena is to increase our power through absorption of the enemies spirits! To do so, the player will have first of all to destroy the physical body of the enemy, making his spirit vulnerable and allowing us to break it and absorb the fragments of his spirit to become stronger:
      But destroying and absorbing wont be so easy, because the enemy spirits, once deprived of their body will immediately look for a way to reincarnate themself:
      The same fate will await the player if he is defeated while fighting in the form of Minocar We will lose Minocar's skull that will remain on the point of our death and we will have to retrieve it
      Once back in the form of Lulu we will be defensless against most enemies, but also invisible to them, however, right when we will lose our physical form the Guardian Eyes will descend from the sky to hunt us down The Eyes will be able to see Lulu and once spotted they will make him visible to all other enemies, putting us at risk of GameOver
      We will have many ways at our disposal to deny and trick the Guardian Eyes
      The level design of DVA makes so that there will be places that Minocar will be able to reach only in the form of Lulu. So we will have to use our wit to find the best way to access areas inaccessible to physical beings.
      Many riddles will require the combined use of both Lulu and Minocar:
      Combat System When we will be in our Minocar form we will have at our disposal alot of abilities, many of which will be unlocked with the increase of our power:
      In the form of Minocar we will be able to change the elemental state instantaneously at every time, each elemental state will change the preset of all of our moves, giving life to brutal and kickass combos At the peak of his power Minocar will have 4 elemental states Primigenial, Fervor, Gelu, Fulgur:
      Minocar will be able to summon various weapons depending on his state and the used attack, from a fearsome Spiked Mace to a devastating Arquebus
      In the game there will be NPCs called the Pure Spirits, they will be hidden in various locations of the game world and will spawn when we kill certain enemies There are two ways to interact with the Pure Spirits: talk to them, or absorb them! It will be possible to talk with the Pure Spirits only in the form of LuLu and if Minocar is not present, they will give insight about the history of Lythra and what happened to its inhabitants... Talking with a Pure Spirit will make us lose affinity with Minocar, if, otherwise, we will absorb them; we will gain affinity points that can be used to unlock new abilities!
       
      Do us many questions and tell us your impressions!
    • By INTwindwolf
      DESCRIPTION
      The team is in need of an assistant Art Team Director that will assist the Project Lead and Art Director in the development of the game. The position does require you to have knowledge of the Unity Game Engine, 3D asset creation software, and a desire for project management.
      The INT team is a large, international team, focused on the development of a core demo which will showcase RPG elements and core features for fundraising and investors. We are a friendly and passionate bunch and hope you will apply soon to be part of our team. Please review the job requirements and responsibilities below.

      Starboard Games LLC is looking for a highly professional, qualified, indie team developer to join our ambitious INT project.
       
      As the INT Assistant Art Team Director you will report directly to the Project Lead and Art Lead. In the occurrence of an emergency you would become the acting Art Lead. The position does require a knowledge of the Unity game engine. This is because we would like our Assistant Art Team Director to have a knowledge of the game engine, and the ability to create scenes to showcase assets.
      Furthermore, you would need to be able to create assets for the core demo in a 3D modeling suite. Many of our artists use blender, but if you have a commercial license for another program then that would be acceptable as well. You will also need to possess team management abilities. This means you will be reviewing 3D artist work, 3D artist samples and test submissions, 2D concepts, and possess an understanding of the ‘big picture’ for INT which will be shared with you by our store, lore, and Project Directors.
      Responsibilities:
      1. Report to Art and Project Lead.
      2. Act as Acting Art Lead in the event of an emergency.
      3. Ability to think creatively.
      4. Ability to communicate effectively and work with other team leads.
      5. Desire to see the project through to completion.
      REQUIREMENTS
      1. Knowledge of the Unity Game Engine.
      2. Experience using Unity.
      3. Experience using 3D asset creation suites.
      4. Experience managing a team or being part of a team environment.
      5. Must be able to take feedback constructively.
      6. Must be able to interpret and decipher maps and notes.
      7. Must be able to work from 2D art.
      8. Commitment to the Project and the ability to spend large chunks of time working towards the completion of the project.
      BENEFITS
      We offer revenue-sharing generated from crowd-funding to team members who maintain consistent communication on company projects and meet Starboard Games deadlines. Currently we are unable to offer wages or per-item payments. Your understanding is greatly appreciated.
      Thank you for your time! We look forward to hearing from you!
      TO APPLY
      Please send your CV/Resume, as well as (the link to) your portfolio to: JohnHR@int-game.net.
      Kindest regards,
      John Shen
      HR Lead
      Starboard Games LLC
    • By INTwindwolf
      DESCRIPTION

      Starboard Games LLC is looking for a highly professional, qualified, indie team developer to join our ambitious INT project.
      INT is an upcoming Science Fiction RPG that has been in continual development for several years. The team is in need of a Level Editor and Designer to join the team to work on the development of the game. This position does not require you to be a programmer or 3D artist.
      The INT team is a large, international team, focused on the development of a core demo which will showcase RPG elements and core features for fundraising and investors. We are a friendly and passionate bunch and hope you will apply soon to be part of our team. Please review the job requirements and responsibilities below.
      As the INT Level Editor and Designer you will be the individual on the team who received art assets and builds the level to Game Dev requirements. This position will require a knowledge of the Unity Game Engine, but not programming or art asset creation knowledge.
      Our levels have been mapped out and annotated with setup notes. While these setup notes and blueprints should be followed, as our Designer you can feel free to be creative in the setup process. When you place assets and design exterior and interior spaces you can be creative in how you build these spaces out.
      Responsibilities:
      1. Report to team Leads.
      2. Report to weekly Dev Meeting.
      3. Ability to think creatively and design portions of the level when required.
      REQUIREMENTS
      1. Knowledge of the Unity Game Engine
      2. Experience using Unity and importing/setting up levels in Unity 
      3. Experience optimizing levels in Unity 
      4. Ability to work under Team Leads
      5. Must be able to take feedback constructively 
      6. Must be able to interpret and decipher maps and notes to set up the level
      BENEFITS
      We offer revenue-sharing generated from crowd-funding to team members who maintain consistent communication on company projects and meet Starboard Games deadlines. Currently we are unable to offer wages or per-item payments. Your understanding is greatly appreciated.
      Thank you for your time! We look forward to hearing from you!
      TO APPLY
      Please send your CV/Resume, as well as (the link to) your portfolio to: JohnHR@int-game.net.
      Kindest regards,
      John Shen
      HR Lead
      Starboard Games LLC
    • By esenthel
      Check out latest tech-demo of Esenthel Engine, a high performance, cross-platform game engine, in development since year 2000, it's available for licensing at http://esenthel.com/
      This is also going to be a game! See the game's facebook page here: https://www.facebook.com/EsenthelWorld/
      Try the demo by yourself: http://esenthel.com/?id=store&item=111