Destructor/Finalize for OpenGL resources

Monkey Forums/Monkey Programming/Destructor/Finalize for OpenGL resources

nullterm(Posted 2015) [#1]
Short version is I have a bunch of OpenGL resources (textures, vertex buffers) that I need to cleanup. But I'm fairly certain Monkey has no concept of destructors/finalize for objects. Right? So going from one level to the next, I need to cleanup everything myself, and can't rely reference counting to tell me when a texture is no long used.

So I need to implement discard functionality for all the different bits and manually manage when these non-GCed resources get deleted... ?

Just curious if anyone has thought up any nifty, reliable and/or time saving strategies to help make it a bit more auto-magic. I had the thought of keeping a list of specific resources that were loaded during the level, and at the level end then purge everything there. But I need to be careful of special cases like textures were loaded during the level, but will want to be re-used in the next level or in HUD or UI.


ziggy(Posted 2015) [#2]
I think you're out of luck. Most GC systems provide a "Dispose" or "Free" mechanism for this kind of resources and it needs to be handled manually. Even if there was finalize, it would not be called until the object is collected, which may be too late, and a destructor on a GC language... You could make all your image/resource handler objects implement a given interface ("iDisposable" or the like) and use reflection on each level "unload" to iterate any existing iDisposable field and call its "Free" method.
That's the most "automatic" I can think of.


nullterm(Posted 2015) [#3]
I ended up having Shader/Texture/VertexBuffer derive from a Resource class.

reload method - creates the OpenGL buffer/texture/shader from the path or data
unload method - deletes the OpenGL data
discard method - unload and also remove from

Each Shader/Texture/VertexBuffer overrides the reload/unload method to do it's specific gl() calls.

I separated reload/unload from discard because on Android when the app leaves/returns I need an easy way to restore all the GL data that gets wiped out. And...

Next step, adding some simple reference count. So calling release on an object decrements the ref count, if it's zero then discard (or wait until level finished). I have a load cache system so data is re-used across multiple objects. Need a way to allow different objects to say "I'm done with this texture" without discarding the data another object may be using.

It's also been helpful tracking down resource/memory leaks. I can call this function and it spits out everything currently loaded.



... like so...




ziggy(Posted 2015) [#4]
Looks like a nice approach