OpenGL Renderer crashes when I delete anything

If you are a new Irrlicht Engine user, and have a newbie-question, this is the forum for you. You may also post general programming questions here.
Kamerik
Posts: 10
Joined: Tue Oct 18, 2022 5:44 pm

OpenGL Renderer crashes when I delete anything

Post by Kamerik »

Hi,

I'm having a huge problem using the OpenGL renderer with Irrlicht and it's driving me insane, I'd appreciate any help with it.

So I'm working on a very basic game engine for my university coursework and I'm using Irrlicht for the graphics part. I've set up a basic scene with a few models and some simple movement and it's mostly working fine. I wanted to add some GUI elements so at the suggestion of someone who did this module before me, I've implemented IrrIMGUI: https://github.com/ZahlGraf/IrrIMGUI

Problem is that it only seems to work with the OpenGL renderer. I was using EDT_BURNINGSVIDEO software renderer so I switched it out for OpenGL and now everything is broken. As soon as I start the scene, I get this error:

Image

This is very vague and I spent several hours just trying to figure out what the problem is. I figured I'd set up something wrong in Irrlicht and there might be extra steps for OpenGL or something because it was working so well before I changed the renderer. But it turns out the problem is actually this:

Image

As part of this module, we're required to implement certain features such as splitting graphics, physics etc into subsystems and utilising an event queue. The above is part of my Graphics Subsystem's HandleEvent() function and allows the player to look around using the mouse. I noticed it didn't crash as long as I didn't move my mouse into the game window. If I comment out "delete event;", my program runs fine without any issues apart from obviously not functioning correctly as I'm not deleting events. I don't get the invalid address error.

I have no clue why deleting my events was fine with the software renderer but it freaks out when I do it with the OpenGL renderer. It also crashes when I try to spawn in any new models after initialization. I have implemented code to spawn a projectile when left mouse is clicked also. Again, this was working fine with the software renderer and now crashes with "Access violation reading location" with the OpenGL renderer. I haven't changed anything about my code to add a model to the scene and adding models works fine during initialization. I'd greatly appreciate any explanation for why this happens and any solutions I can implement to resolve it because I'm not sure how to handle events in my queue otherwise.
CuteAlien
Admin
Posts: 9643
Joined: Mon Mar 06, 2006 2:25 pm
Location: Tübingen, Germany
Contact:

Re: OpenGL Renderer crashes when I delete anything

Post by CuteAlien »

Sorry, I am not familiar with IrrIMGUI (heard the name before, but that's it). Are you supposed to delete event there? I don't know how event was allocated. For example if IrrIMGUI is used as DLL and was allocated in there, then it might not be OK for you to deallocate it in your main application, but you'll have to use dll-functions which tell it to delete the event again (going accross dll-borders with memory is tricky).

Can be any other reason, hard to tell with memory errors. The tricky to debug such stuff is usually divide & conquer. Aka - reduce the problem by removing everything that is not related. Reduce it until you can reproduce it with a handful of lines. If you still can't see the bug by then you'll at least have a simple complete example to post.

I did a quick look at the examples of IrrIMGUI - and those seem to pass events as references (so no way you are allowed to delete them). So I suppose your code somehow looks different.
IRC: #irrlicht on irc.libera.chat
Code snippet repository: https://github.com/mzeilfelder/irr-playground-micha
Free racer made with Irrlicht: http://www.irrgheist.com/hcraftsource.htm
Kamerik
Posts: 10
Joined: Tue Oct 18, 2022 5:44 pm

Re: OpenGL Renderer crashes when I delete anything

Post by Kamerik »

Apologies, I should have taken a clearer snip and explained it better.

The event I'm deleting isn't an IrrIMGUI event, it's my own event class I have created for this project. I have an Event Handler class with a list of Event pointers which I retrieve with GetEvents(). When I press a key, move the mouse etc, it creates an event and adds it to a the list. My Graphics Subsystem where I initialise the device, driver etc loops through this event list to check for any valid events (e.g. mouse movement), reacts accordingly (e.g. moves the camera) and then deletes the event once done. Or at least it's supposed to, but with OpenGL, deleting the event crashes, when it didn't with the software renderer before.

This is the case even with the IrrIMGUI stuff commented out. Below, is the relevant code. UpdateSubsystem is called every frame and HandleEvent is called at the end of that.

Code: Select all

void GraphicsSubsystem::UpdateSubsystem()
{
	driver->beginScene(true, true, irr::video::SColor(255, 100, 101, 140));

	// create the GUI elements
	//pGUI->startGUI();
	//ImGui::Begin("My first Window");
	//ImGui::Text("Hello World!");
	//if (ImGui::Button("Exit", ImVec2(40, 20)))
	//{
		//device->closeDevice();
	//}
	//ImGui::End();

	// render your scene
	smgr->drawAll();

	// render the GUI
	//pGUI->drawAll();

	driver->endScene();

	//Work out delta time.
	float time = clock();
	deltaTime = time - lastFrame;
	lastFrame = time;

	//Work out camera vectors.
	cameraPos = camera->getPosition();
	cameraTarget = camera->getTarget();

	cameraForward = (cameraTarget - cameraPos).normalize();
	cameraRight = (cameraUp.crossProduct(cameraForward));

	HandleEvent();
}

void GraphicsSubsystem::HandleEvent()
{
	//Handle the events in the event queue.
	for (Event* event : EventHandler::GetEvents())
	{
		switch (event->GetEventType())
		{
			case EventType::KeyPressed:
			{
				vector3df movement;

				//Move forward.
				if (event->GetKeyPressed() == 0)
				{
					movement += cameraForward * movementSpeed * deltaTime;
				}

				//Move left.
				if (event->GetKeyPressed() == 1)
				{
					movement -= cameraRight * movementSpeed * deltaTime;
				}

				//Move backward.
				if (event->GetKeyPressed() == 2)
				{
					movement -= cameraForward * movementSpeed * deltaTime;
				}

				//Move right.
				if (event->GetKeyPressed() == 3)
				{
					movement += cameraRight * movementSpeed * deltaTime;
				}

				cameraPos += vector3df(movement.X, 0, movement.Z);
				cameraTarget += vector3df(movement.X, 0, movement.Z);

				camera->setPosition(cameraPos);
				camera->setTarget(cameraTarget);

				delete event; //IF I COMMENT THIS OUT, MY PROGRAM DOESN'T CRASH
				break;
			}
		}
	}
}
Don't think I've messed up anything here, but this is my initialization code. device etc. are declared in the header file.

Code: Select all

//Create the game window.
	SIrrlichtCreationParameters IrrlichtParams;
	IrrlichtParams.DriverType = video::EDT_OPENGL;
	IrrlichtParams.WindowSize = core::dimension2d<u32>(1024, 800);
	IrrlichtParams.Fullscreen = false;
	IrrlichtParams.Stencilbuffer = true;
	IrrlichtParams.AntiAlias = 16;
	IrrlichtParams.Vsync = false;

	// Create standard event receiver for the IrrIMGUI
	CIMGUIEventReceiver EventReceiver;
	IrrlichtParams.EventReceiver = &EventReceiver;

	device = createDeviceEx(IrrlichtParams);

	pGUI = createIMGUI(device, &EventReceiver);

	//if (!device)
		//Add Error Handling here.

	//Store the driver, scene manager and gui environment for reuse.
	driver = device->getVideoDriver();
	smgr = device->getSceneManager();

	device->setWindowCaption(std::wstring(titleString.begin(), titleString.end()).c_str());

	//Add lighting to the scene.
	smgr->addLightSceneNode(0, vector3df(0, 0, 0),
		video::SColorf(0.5f, 1.0f, 0.5f, 0.0f), 8000.0f);

	//smgr->setAmbientLight(video::SColorf(0.86f, 0.86f, 0.86f));

	//Add a camera to the scene.
	camera = smgr->addCameraSceneNode(0, vector3df(0, 0, -4));
	camera->bindTargetAndRotation(true);

	//Lock the cursor.
	cursor = device->getCursorControl();
	cursor->setVisible(false);

	//Load Mouse Sensitivity here later.
	mouseSensitivity = 0.5f;
CuteAlien
Admin
Posts: 9643
Joined: Mon Mar 06, 2006 2:25 pm
Location: Tübingen, Germany
Contact:

Re: OpenGL Renderer crashes when I delete anything

Post by CuteAlien »

That other code looks all fine. The most suspicious one is your event handler. Event handling code deleting the event object memory sounds super risky. Like how does your event-handler now know that event object got deleted? And every event that is not handled is an automatic memory leak?
IRC: #irrlicht on irc.libera.chat
Code snippet repository: https://github.com/mzeilfelder/irr-playground-micha
Free racer made with Irrlicht: http://www.irrgheist.com/hcraftsource.htm
Seven
Posts: 1030
Joined: Mon Nov 14, 2005 2:03 pm

Re: OpenGL Renderer crashes when I delete anything

Post by Seven »

i am not sure but i'll take a guess....

how does the EventHandler::GetEvents() know that you deleted one of the events?

you seem to be looping through a list? but that list is being changed during the loop so the iterator might be getting confused?
CuteAlien
Admin
Posts: 9643
Joined: Mon Mar 06, 2006 2:25 pm
Location: Tübingen, Germany
Contact:

Re: OpenGL Renderer crashes when I delete anything

Post by CuteAlien »

The list is only changed if GetEvents is a reference and the events are de-registering from the EventHandler in their destructor (edit: on further thinking even if GetEvents is not a reference but a copy, events de-registering themself in the destructor could still mess things up).

But well, all guessing around. Post it all :-) Maybe create a quick repository on github or so.
IRC: #irrlicht on irc.libera.chat
Code snippet repository: https://github.com/mzeilfelder/irr-playground-micha
Free racer made with Irrlicht: http://www.irrgheist.com/hcraftsource.htm
Kamerik
Posts: 10
Joined: Tue Oct 18, 2022 5:44 pm

Re: OpenGL Renderer crashes when I delete anything

Post by Kamerik »

Sorry for the delay in responding.

I've changed my Event Handler and the way I dispose of events a bit and it seems to be working now though I still have no idea what the problem is and I still can't spawn in new GameObjects. The reason I'm so confused is the same exact code for the Event Handler I shared WAS working before without issue with the software renderer. It only started getting confused when I changed the renderer to OpenGL even though nothing else changed.

But anyway, maybe this will help us pin down the issue better. Here's my code for handling an event that allows the player to fire a projectile:

Image

And here's my GameObject constructor which causes this error when I click and try to spawn in a projectile:

Image

So obviously the problem is that I'm doing something wrong in the GameObject class right? Well, here's me instantiating several GameObjects in my GraphicsSubsystem constructor, which works completely fine.

Image

Again all of this was working 100% fine without any issues whatsoever before I changed renderer. And I don't think it can be something wrong with how I've set GameObject up considering the models in the for loop before I draw the scene all instantiate and render completely fine.
CuteAlien
Admin
Posts: 9643
Joined: Mon Mar 06, 2006 2:25 pm
Location: Tübingen, Germany
Contact:

Re: OpenGL Renderer crashes when I delete anything

Post by CuteAlien »

I'd recommend compiling Irrlicht in debug, so the debugger can break inside the engine.
In the given line there's at least 2 options that can go wrong. Easiest one would be "manager" not pointing to something valid.
But the crash saying something about Irrlicht.dll could also mean it's crashing within Irrlicht for some reason and unless it's compiled in debug VS might not step in there. Thought if you load the mesh in other places as well and it works there, that's pretty unlikely.

As for changes causing crashing - can be related or not. Basically if you mess up memory handling somewhere anything can happen. And any change in memory allocations can hide crashes for a while (so crashes might go away simply by adding another variable in another place etc). Memory allocation errors won't crash as long as the memory accessed is owned by your application - even if it's maybe for a wrong object and it's happily writing all over your variables.

Which is why I recommended divide & conquer earlier. Kick out as much as you can of your application without stopping the crash. Easier to see bugs then.

But for a start - just set a breakpoint in that line and check if all variables look as expected. Especially manager.

As for the new code you posted - I see nothing obvious wrong. But haven't had to do with LUA in over a decade, so can't really remember much about that ;-) Speed hint for later on (once you fixed the bugs, it's not causing them) - it's mostly better in c++ to pass larger variables (like std::string) as const references. Otherwise you are causing expensive copy operations (just tiny costs with simply structs, but in this case it even triggers memory allocations which are always costly).
IRC: #irrlicht on irc.libera.chat
Code snippet repository: https://github.com/mzeilfelder/irr-playground-micha
Free racer made with Irrlicht: http://www.irrgheist.com/hcraftsource.htm
Seven
Posts: 1030
Joined: Mon Nov 14, 2005 2:03 pm

Re: OpenGL Renderer crashes when I delete anything

Post by Seven »

although the debugger is a great tool, I also use printf statements regularly for debugging even in release mode using a _DEBUG define

#define IGE_DEBUG_ENABLED
#ifdef IGE_DEBUG_ENABLED
#define IGE_LOG(x) printf("%s", stringc(x).c_str());
#else
#define IGE_LOG(x) // compiles to nothing if IGE_DEBUG_ENABLED is not defined
#endif

in this example I would just place
if (!manager) { IGE_LOG("Manager not valid\n") return; }
just to validate to myself that the smgr is valid.

helps me keep my sanity.

without all of the code it is difficult and just guessing but my guess is that the smgr is not valid.
CuteAlien
Admin
Posts: 9643
Joined: Mon Mar 06, 2006 2:25 pm
Location: Tübingen, Germany
Contact:

Re: OpenGL Renderer crashes when I delete anything

Post by CuteAlien »

That works if manager is set to 0. But crash address doesn't look like that. So my guess is more along of pointer pointing to something bad. Which is harder to debug - you basically can just check a bunch of variables in the debugger and see if they look sane. If all values in the object look totally strange then it's probably not pointing to a good object.
IRC: #irrlicht on irc.libera.chat
Code snippet repository: https://github.com/mzeilfelder/irr-playground-micha
Free racer made with Irrlicht: http://www.irrgheist.com/hcraftsource.htm
Seven
Posts: 1030
Joined: Mon Nov 14, 2005 2:03 pm

Re: OpenGL Renderer crashes when I delete anything

Post by Seven »

I believe you are more correct but the debug printf's help me regularly. I had also thought maybe a dll version issue. maybe irrlicht was debug but app is release or such. hard to know without more code i think.
CuteAlien
Admin
Posts: 9643
Joined: Mon Mar 06, 2006 2:25 pm
Location: Tübingen, Germany
Contact:

Re: OpenGL Renderer crashes when I delete anything

Post by CuteAlien »

Sure, I also use lots of text logging in my code.
IRC: #irrlicht on irc.libera.chat
Code snippet repository: https://github.com/mzeilfelder/irr-playground-micha
Free racer made with Irrlicht: http://www.irrgheist.com/hcraftsource.htm
Kamerik
Posts: 10
Joined: Tue Oct 18, 2022 5:44 pm

Re: OpenGL Renderer crashes when I delete anything

Post by Kamerik »

I tried what Seven suggested and it didn't return or log anything so I tried what CuteAlien suggested and compiled Irrlicht in Debug mode.

Thank you so much, I should have thought of this earlier but I'm an idiot. With Irrlicht compiled in Debug Mode, this is where the exception is thrown:

Image

I thought this was kind of strange and still wasn't sure why it was throwing an exception at first but the event part made me remember something. I commented out most of the IrrIMGUI code except for the initialization (because again, I'm an idiot) and part of this initialization is this:

Image

If I comment out those lines except the createDeviceEx, my projectiles work again! Seems like it was a problem with IrrIMGUI's event receiver. The IrrIMGUI tutorial/example sets up the event receiver like that so I didn't think much about it, but I can call createIMGUI with just the device instead. And if I do that, nothing breaks AND my GUI renders. I'm not sure whether not having an EventReceiver will cause issues with what I'm trying to do later down the line but for now I'm just glad to have it working again.

Thank you so much for the help and for putting up with my idiocy!

Also, thanks for the speed hint!
CuteAlien
Admin
Posts: 9643
Joined: Mon Mar 06, 2006 2:25 pm
Location: Tübingen, Germany
Contact:

Re: OpenGL Renderer crashes when I delete anything

Post by CuteAlien »

Maybe your EventReceiver is in the wrong scope? For example a variable in a local function? Make sure it exists as long as the device (for example creating it in the main function - or in some class which exists always).
IRC: #irrlicht on irc.libera.chat
Code snippet repository: https://github.com/mzeilfelder/irr-playground-micha
Free racer made with Irrlicht: http://www.irrgheist.com/hcraftsource.htm
Kamerik
Posts: 10
Joined: Tue Oct 18, 2022 5:44 pm

Re: OpenGL Renderer crashes when I delete anything

Post by Kamerik »

Yeah, you were right. I moved the EventReceiver to my GraphicsSubsystem class in the header file and I can use it without any errors. I won't be making that mistake again. :oops:
Post Reply