Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- struct SpriteNode{ //simple singly linked list, consider using a standard library one, I just did this to be explicit
- SpriteNode* next;
- int idx;
- }
- int peakCapacity=0; //represents the last element of the array that has been populated
- Sprite sprites[MAX_SPRITES];
- SpriteNode* freeList; //this is the first element of the freelist, no seperate head. null initialized
- //Don't add initially empty slots to the freelist, we keep a freelist to keep fragmentation low.
- //We always want the freelist to be the best choice for assigning to a new element
- void init(){
- for(int i=0;i<loadCount;i++){
- //just do whatever normal init you'd do for your sprites array
- sprites[i]=loadNewSprite();
- //then increment the peakCapacity so we keep track of where the iniitalized sprites end
- peakCapacity++;
- }
- }
- //This must be called whenever a sprite is considered an invalid entry in the sprites array.
- //for example your sprite dies. Wherever you would normally set is_used=0 basically
- void deadSprite(int idx){
- SpriteNode* tmp=new SpriteNode;
- tmp->idx=idx;
- tmp->next=freeList;
- freeList->next=null;
- freeList=tmp;
- return;
- }
- //called when we need to introduce a new sprite to the system
- //it returns the position where the calling code can introduce their new sprite
- int newSpriteIndex(){
- if(freelist){
- SpriteNode* tmpnode=freelist;
- freelist=freelist->next;
- int ret=tmpnode->idx;
- delete tmpnode;
- return ret;
- }
- if(peakCapacity<MAX_SPRITES){
- return ++peakCapacity;
- }
- return null; //we didn't have any free slots on the freelist or the array,
- //we've reached capacity with no holes.
- //you should probably increase the array size if this happens. The freelist remains fine because we made it referential by index not pointer
- }
- //This would be update/render code
- //notice how we don't loop through the entire array, we only go as far as we know there's sprites.
- for(int i=0;i<peakCapacity;i++){
- //do normal sprite-y things
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement