Ownership surfaces
Hey all,
We have a little dispute here: Right now, a sprite is constructed using a surface (usually). However, the sprite does not 'own' the surface, wich means that it will not delete the surface. So basically, right now the application is responsible for this. This has two drawbacks:
1. In many cases (in our current apps) a sprite is the only object that uses a particular surface. Managing that surface in the application is unneccessary hassle.
2. If you forget to delete the surface, there is no crash, no warning, just a memory leak.
So, I suggested to the other guys to make the sprite owner of surfaces, unless explicitly told otherwise. That way, the sprite cleans up it's own mess. If you accidentally delete the sprite in the app too, you get a crash, wich is better than a leak.
However, suppose we have 15 bullet sprites using the same surface. This is not as unlogical as it sounds at first: The only thing that a sprite adds to the surface class are it's coordinates. If you use 15 pointers to the same sprite and store the coordinates in the bullet actor or whatever, there is no reason anymore to use a sprite at all, you could just as well use a surface. So, we have 15 sprites using the same surface. Who's the owner? The app is.
That's the discussion. Any good ideas / opinions on this?
- Jacco.
Ah, the old ownership problem :). Create a unique elegant solution for this and you'll be a nobel-prize winner.
Anyway the solutions:
1. The current situation
Sprites are not owner of a surface, unless explicitly specified by doing sprite->SetFlags( OWNER );
Pro's: Surface-sharing between sprites made easy.
Con's: Easy memory-leakage.
2. Surfaces passed to the sprite constructor are eplicitly owned. Surfaces passed to the the sprite by using sprite->SetSurface() are not owned.
Pro's: Both options are possible, of which the most obvious policy causes a crash when it's violated.
Con's: Inconsistent intentions, i.e. unclear why there is a difference between the constructors argument and the sprite->SetSurface argument (unless documented)
3. Both the Sprite constructor and the sprite->SetSurface() method get a second parameter which is a boolean telling the sprite whether or not the sprite becomes the owner. This boolean has NO default value to force the client to think about ownership.
Pro's: Forces the client to think, and consistency is improved over option 2 (see above).
Con's: Laziness (using false everywhere) might still lead to memoryleaks.
4. Intrusive-smart-pointers, which means using a reference-count inside the surface. Each sprite or other source using the surface bumps the reference count up by one.
Pro's: Surfaces are automatically deleted when they aren't used anymore. Thus no memory leaks.
Con's: Requires additional methods in the surface interface, and carefull client addref and release usage.
5. Non-intrusive-smart-pointers, which means you use a smart-pointer where the ref-count is actually inside the pointer itself.
Con's: Passing a surface-pointer to a sprite now becomes passing a smart-pointer to a sprite, thus requires a certain amount of C++ experience. Smart-pointer-fanatics might be scared of this.
Pro's: No changes needed in the surface-interface. Very easy to use, does not require the client to do Addref and Release calls, so very difficult to f*ck up.
And that's about all I can come up with for now. Personally I favour option 5, but I can understand that smart-pointers scares many C-with-classes C++ coders. So to keep things clean and simple I suggest using option 3 then. It strikes the right balance between the amount of changes required, the understanding required from the client and the amount of automation offered by the library.
Cheers,
Jape
Hi Jape,
Option 5 and 4 both sound okay... how about this:
It is the sprite code who bumps up the refcounter of the surface. If you make a new sprite using the same surface, the surface gets his refcounter increased automatically.
then when you delete the sprite, it will decrease the ref counter of the surface. if the surface hits 0 it will be deleted too.
No user interaction required.
The only way this goes horribly wrong is when the user deletes the surface himself while it is still in use by a sprite. But this can be easily checked (in th debug build) by using a static list of all surfaces currently 'new'ed
R
I like this very much, but there's one problem: The reference count is ONLY used for sprites. In that case, it's ugly (imho) to have that attribute in the surface class. Then again, it solves all problems without the need for ugly C++ expert tricks.

You're right, most of the AddRef and Release code will remain in the library itself. But previous COM experience showed that once an interface publishes reference-count mechanisms you're doomed to use it in unforeseen places. Example:
What if no sprite holds a reference to the surface, but there might be one in the future? You do not want to recreate the surface again then. No, instead you want to manually force the reference-count to be one, until a sprite uses it again. Hence the client will have to explicitly AddRef the surface.
Besides, solution 4 still requires changes in the surface interface (intrusive, remember?).
IMHO, from a design perspective solution 5 is better than 4 in all cases....
Cheers,
Jape
I don't see your point Jape.
If you create a surface, the ref count is zero. No one uses it.
Then if you attach it to a sprite or a whatever future object, this object will increase the reference count.
than if that object is deleted, it will decrease the ref count, and delete the object.
I think it is an elegant solution.
R
I'd like to vote for option 3. It's simple, clean, requires no changes.
While option 4 is attractive and looks clean from the outset, it just doesn't work that way in practive. One only needs to look at all the COM-derived auto-refcount managers (take a look at some ATL classes if you want nightmares) to see what an interface based addref and release can lead to....
Cheers,
Jape
Hm, I don't agree Jaap. We already have separated implementations from interfaces, and the refcount stuff could be added to SurfaceImpl.h. That way, the client app can't touch the refcounting stuff, and the interface appears to stay the same.
The case you described where you want to use a surface later on without reloading it can be solved by explicitly telling the sprite NOT to delete the surface, even if it's refcount is zero. There's no reason for skipping that mechanism, even when we add refcounting.
"If you create a surface, the ref count is zero. No one uses it."
Theoritically this is incorrect. First of all, objects with a zero-refcount have no right to exist. When you create an object its refcount is one, because the place where you created it has a reference (until it goes out of scope, that is).
"Then if that object is deleted, it will decrease the ref count, and delete the object."
I assume that what you mean is that the sprite will decrease the surface's refcount, and when the surface's refcount equals zero the surface deletes itself.
However, imagine the following case:
Suppose you have a character able to shoot bullets. Obviously all bullets can share the same surface. However, where does the surface exist when no bullets are fired? Since no bullet-sprites exist, no references to the surface exist, and hence the surface will delete itself. This is undesired because you don't want to reload the surface when you shoot a new bullet.
Hence, you have to maintain a persistent reference. The only way you can do this is by a manual AddRef in your client-application.
Hence the client code WILL need to do his own AddRef and Release in some places.
Good hand-written refcounting IS a HARD problem and difficult to maintain. At first reference-counting seems an easy solution to memory-leaks, but in practice it doesn't work that way. It is too easy to lose a reference without releasing it, especially without scoped_references (yuck, another scoped class, please...)
Cheers,
Jape
If you want consistency I would go with option 1: sprites are never the owner unless specifically mentioned with the 'setowner' command.
this way it is easy to remember: anything you NEW, you must DELETE
R
p.s. We can than add a very easy debugging memoryleak detector where the filename and linenumber of any new'ed surface or sprite is stored and is later displayed when exitting the library.
Heck, let's take it even further and explicitly dissallow giving ownership of the surface to the sprite! How often are we going to use it anyway? It's not too difficult to maintain both the surface and sprite resource in one place, and sharing is too common anyway!
Thus, remove the sprite->SetFlag( OWNER ) option.
This also agrees with the common C++ RAII (resource aquisition is initialization) idiom.
Mmmm, thinking about this, I think this is indeed the best solution. It is easy, clean and forces the user to think about surface-lifetimes.
About the memory-manager. I have one lying here from a previous hobby-project. It doesn't use the STL (try writing one which uses the STL. It's nearly impossible since the STL uses its own allocators in combination with (placement) new and delete), and should be very easy to fit in. Because if overrrides global new and delete it can be used immmediately.
Cheers,
Jape
Why would you want a memory allocater?
if it is for debugging alone, you can also add some debugging funtions without adding a full fledged memory allocater now couldn't you?
I think (hope) windows can do memory allocations much better then we can...
R
Whoops, slight misunderstanding here. My bad.
I meant a simple memory-tracker. Something that just overloads global new and delete and gets the line and file as two extra (implicit, hidden through a macro) parameters. These are just passed on to malloc and free after being put in a list to track them...
Cheers,
Jape
I don't think that would help a lot since this is already present in VisualC if you run it in debug mode.
The preoblem with your suggested scheme is that the surface an sprite class are NEW'ed in the DLL, everytime on the exact same place. It would thus be more convenient to know which source called the appropriate factory method
R
Don't mean to interrupt the conversation but...
you guys are like sitting in the same office, right?
neway, please continue

We programmers are by nature very shy and don't dare to say anything to someones face directly, so we revert to chatting and posting messages ;^)
no all kidding aside, Jape is working at home and Jacco is indeed sitting a few metres away from me.
By setting the discussion online, other people can add their 2 cents where possible.
Although we are omnipotent, we do sometimes ask the others for input

Ehm, no, well, actually, Reinier and I are in the same office. Jaap is 'working' from his home at the moment. That's because he can't afford an apartment at a decent distance from the office with his salary, hehe.
Well, actually I'm trying to study for my Politics and Philosophyie exam of tomorrow, but these discussions are just too interesting to leave alone...
One day I might be able to afford an appartment in the kartonnen-dozen straat near the office :) hehe.
Cheers,
Jape
All ideas are crap..
You´re loosing the OO thinking here.. Why should the end user have to struggle with smart pointers and surface memory allocations just to draw a sprite?
I believe a referencing / subclassing system like the one used in 3dsmax would be most efficient, and I will be implementing a similar one in gapidraw (sprites are so easy to do, but still everyone feels that sprite support is important for a library).
(1) Let each sprite be a surface. Draw to the sprite and you draw the surface. Delete the sprite and you delete the surface. Use subclassing to inherit from a surface to the sprite.
(2) 15 similar bullets? Create a new sprite and pass an option to let it reference to the first one. The referencing could be done using simple multiple-to-multiple references (change base -> all references change, change reference->all other changes). Draw a change to one of the bullets and all other bullets will change instantly. Going the 3dsmax way, one could also add an option that it you can override some properties of the base object, and the ones not overridden will still be used as they are in the base (change base -> all references change, change reference->no other change).
(3) What happens if I delete the "base sprite".. Won't that crash the application? Not if you use an internal referencing system (delete base -> notifies all childs, delete child -> notifies base).
[Edited - changed some errors in (2)]
/Johan
"You´re loosing the OO thinking here."
Maybe so, but OO is highly overrated anyway. It may be the trendy-paradigm of the 90s and the first couple of years in the twentyfirst century, but people will find out that different paradigms work for different problems. OO is not the end of all means. If meta-programming, generic-programming, functional-programming, imperative-programming, object oriented-programming, generative programming or any other yet-to-be-discovered or ancient paradigm fits my problem better, you can be fairly certain I'll be using it instead.
"Why in the earth should the end user have to struggle with smart pointers and surface memory allocations just to draw a sprite?"
I agree. In fact, why in the earth should the end user have to worry about anything? Instead, let's provide a FrameGame::DoFunky3DQuakeClone() to the user. He'll call that and his game is done. Simple eh :).
Kidding aside, we want to provide flexibility yet ease of use to the client. These are two contradicting wishes, and we have to maintain a balance. Whether we/you/anybody thinks smartpointers belong on the other side of the balance is one of the reasons of this discussion.
We can't ignore that smartpointers provide a easy and effective solution to many ownership-difficulties. But they come at a cost, and in reallife situations the client will end up with smartpointers too. So in that regard, you are correct.
However, I'm at a complete loss on your proposed solution.
How do you implement such a subclassing technique? You can't inherit a bullet from a sprite such that all 15 bullets will share the surface.
Could you elaborate, maybe with a simple code sample?
Thanks,
Jape
Hi,
I wrote the first post while eating breakfast and watching tv..

I changed my proposed solution..

Uhmm....
how exactly does your solution not rely on smartpointers? I agree, your referencecount (or -link) and the pointer itself are stored in different locations, but the fact remains that you are keeping track of the amount of reference to a particular resource.
Smartpointers just provide a different syntax for your proposal, but maintain the same semantics.
With one big difference however. Your solution has an explicit owner. So we have 15 bullets, of which one is the boss. What if that bullets collides with a wall first and then explodes. It has no reason to exist anymore, but its children will. What to do?
Create 16 bullets? One eternall living one, and 15 referencing bullets? That's how we have it now. You create an eternal surface and let the sprites reference it.
Cheers,
Jape
p.s. where eternall means: "as long as possible future sprites may want to use it"
Um. Yeah. I think I actually ended up with the same solution as the one you already have. 16 bullets.
I should get back to my documentation project now I guess..

hmm...I implemented something like what you guys are discussing for the game I'm working on.
The way I have it is that I give a unique ID for each sprite. I had it so that the filename contains a number used as an ID (I know it's kinda hacked...) then I just check if that ID exist, if so then just add a reference. I could've used the filename as an ID but that would take too much space.
I'm thinking that the for the smart pointer, just let the client manually add references. Short and simple.
So is this going to be added to 0.99?
All proposed solutions are quite simple, so we should be able to add this tomorrow once we all agree (or once I decice;) ). So yes, this should be in 0.99.
There will be more of course. But it looks like the libraries are stabilizing. Most of the time is going to the GPRS stuff. That is such a disaster to code for.

We have a round trip delay of 1.6sec minimum, we have a 'permanent connection' that needs to be set up using a shabby API with lousy documentation, we have to protect the stuff so we don't get hacked in the first week, we want slow comms in threads and so on and so on. All stuff that you guys won't be using, but it has to be done and it has to be done well.
Why am I whining about this here? Sorry.
