PocketMatrix forums

A read-only archive of the PocketMatrix forums (2001–2014). Posting and accounts are closed.

Handling creation/deletion of units within game

I'm developing a game that has units which are continually created and deleted as units are built and destroyed and am running into problems with objects referencing units.

For instance, a smart missile has a lock target of type Unit. It's locked target may actually get destroyed before the missile gets to it etc causing access violations. I tried a quick fix by adding an "Active" property which helped a bit but doesn't catch all cases and is messy to work with.

Units are currently stored in the player class, ie. Player -> Units.

So I am thinking about having a "Unit Register" which is basically an array of all units. As new units are created they are added to the register, and as destroyed they are deleted, and instead of referrencing the unit directly it referrences the element in the unit register array.

I thought I would post here before implementing just to see if anyone knows of a better way ... any suggestions?
Peter Balogh · 13 Apr 2004, 09:28 UTC
I don't see how that would fix your problems. Sure, it'd get rid of access violations, but you'd have a rather high chance of confusion in the game. E.g. the index of the unit your rocket is targeting would be freed after the target is destroyed and would be shortly reused for another rocket objects, etc... The way to do it is either keep a reverse list of objects referencing each unit, so when something happens to the unit it can call a HandleEvent function in all the objects referencing it, so they can all handle the situation in their own fashion. (Like a target-locked rocket could self-destroy or find a new target, etc)

Cheers,
Peter of PDAmill
Peter: I was trying to save on lists per object, but you are right. I will give the suggestion a go. Thanks.
You shouldn't be allocating objects dynamically at runtime (malloc, new), but instead have a pool of objects that is created during initialization. It is a very simply task to write your own allocation and deallocation routine to flag those objects as used or unused. Since the object is never deallocated there is no harm is accessing it after is is deallocated (via your custom deallocate routine) to see if it is still valid. The same flag would be used by your allocation routine which scans through the pool of objects to find an unused slot. The only potential issue is if an object is freed and then allocated to something else between calls to the handler that referred the original object. However in your allocation scheme you could simply step through the pool starting at the item <i>following</i> the last freed item, so the last freed item would be the last item to be allocated again.

You could also use a serial number system. Instead of using a simple flag to show that an object is valid, you use an integer that is incremented each time an object is allocated. A serial number of 0 would indicate an unused slot. Then your handler would store a pointer to the object plus its serial number, and if the serial number does not match then the object is unused or refers to a different object.

That will solve your problem, plus you will have better performance by not using malloc or new during runtime.

Dan East
I used the approach Dan East described in my last game.
Pool of objects and serial IDs ( a static counter for all objects)
Any reference to another object would also store that object's ID - if, in the meantime, the referenced object was reused for something else , Ids wouldn't mach and thus the reference could be dropped.

Pool of objects is pretty much a must if you are talking about creating thousands of objects at a run time- otherwise you will experience extreme (and hard to debug ) slow downs later on when your app heap gets fragmented ( something that happens very easily on Pocket PC devices.)
Thanks Dan and warmi. Currently my units are structured like:

Code:

TUnit
-> TLandUnit
-> TTank
-> TMissileLauncher
-> ...
-> TAirUnit
-> THelicopter
-> TSmartMissile
-> ...


(excuse the Delphi conventions)

A pool seems like a good idea, but it's a bit of pain with the various unit types. What I will do is have a TUnitPool class with New(TUnitType Type) and Delete(TUnit* Unit) as well is Get(int SequenceNo).

New() will see if there is an available unit (where seq no = 0) of specified type for use, and if not dynamically create one.

Get() will attempt to find a unit with that seq number and return it if available.

Delete() will reset the sequence number to 0.

Also, I might add to TUnit a function for resetting default values, but this function will need to belong on the inheriting classes too I guess, although can't be virtual.

I don't even think I will set the pool to a specific size initially because each level will have a different balance of units. The speed hit on most of the allocation is just as each level starts which won't be a problem, and I think the upper limits for the pool for each unit type will quickly be established.

Thanks for your help.
I personally prefer to keep a list of free objects and then when an objects is requested simply detach one from the list and return pointer to it.
When it is time to delete it , it will simply be appended back to the list of available objects.
This way there is no need to scan for available objects or anything like that - simply return the last pointer on the list and be done with it.
The ID ( a static variable) is set to 0 at the start of the program and then simply increased by one every time object is requested and the current value is used by this objects as its ID. When the object is deleted - its ID gets reset to -1.This has nothing to do with the allocation or object polling - it is simply a way to uniquely identify objects. Using pointer is not enough since these object will be reused but ID is guaranteed to be unique.
Also when doing initial allocation , it is often better to allocate sizeof(object) * num_objects and then simply divide that memory by "hand" as opposed to looping and calling new(...) for each of these objects.
Peter Balogh · 14 Apr 2004, 06:24 UTC
PPC gets awfully slow when it comes to allocating lots of small blocks of memory. There's 2 ways around it, one is using pools of objects. The other is making a small block heap, which you use only for small (say less than 256 bytes) of objects.
I've made a very fast small block heap and overrode malloc/new/realloc/free/delete/strdup/etc, so dynamic allocation of objects, strings, etc come at no extra cost when compared to using pools, yet the simplicity remains. I can also just disable this small block heap when debugging on a PC, so I can use conventional tools devtools to find leaks and other memory-related bugs in codes.
When working with 1000-3000 memory blocks I've found my implementation 300-500 times faster than using the built-in malloc/free routines.

Cheers,
Peter of PDAmill
Dan and warmi have pretty much described the general idea.
It is actually well-known design pattern called "Flyweight".
You can find more on it here:
http://home.earthlink.net/~huston2/dp/patterns.html