yesterday I had introduced that BufferObjects can be either Managed or Unmanaged.
The changes originate from the patches supplied by the user zergling_zzh made during the development of the Z-Studio game "ZDefense", which btw is super awesome and addictive
This works as follows:
When you create a Sprite, there are two BufferObjects involved:
- a VertexBuffer, holding the Geometry. (Created by the Sprite itself.)
- a TextureRegionBuffer, holding some Texture data. (Created when creating a TextureRegion)
These BufferObjects can be created as Managed (this is when AndEngine takes the work of loading and unloading from you) and Unmanaged (this is the do-it-yourself mode). Following are the technical details:
When the buffers are created as:
- When instanciated, they load themselves to the currently active BufferObjectManager.
- The object that is using the BufferObject will make sure, that once itself is garbage collected, the BufferObject is released.
- You have to load the BufferObject to the BufferObjectManager yourself.
- The object that is using the BufferObject will leave it alive, once itself is garbage collected!
For the VertexBuffers 'Managed' works perfectly fine and totally transparent to you, as every Sprite uses its own VertexBuffer (unless you don't pass one to its constructor).
For the TextureRegions is gets tricky, as quite often one TextureRegion is used by multiple Sprites. So when one Sprite gets garbage-collected, that has a Managed TextureRegionBuffer it unloads that TextureRegionBuffer and "destroys" all other Sprites using the same TextureRegion(Buffer), what is most likely not desired!
So what I decided to do is to make the VertexBuffers Managed by default. Also the TextureRegionBuffers are created as managed if you instanciate a TextureRegion yourself (you usually don't do that). BUT when using the TextureRegionFactory to create your TextureRegions (which is btw the desired way and 99.9% of the developers do it like this) they are created as managed, but after creation they are set to be unmanaged(!), what means that they have already loaded themselves, but they are not automatically unloaded to prevent the above "shared-destroying" issue!
I could have solved this by automatically by making the TextureRegion being cloned, when passed to the constructor of a Sprite, but I though it would be better this way. Which unfortunately means that there is a "little memory leak", when one is not adapting his code. This "little memory leak" is actually not a problem, as it is very small (a few bytes per TextureRegion, of which you usually don't have more than a dozen and more importantly it does not increase over time )
Changeset: http://code.google.com/p/andengine/sour ... c7789eae3f