Sorted sprites

In the game engine thingie I’m writing I have game objects. Btw, game engine sounds way more fancy and pretentious than what this is. Anyways, in the game .. framework, that I’m writing, I have game objects. I want to be able to load a scenario from disk, and in this scenario there should be items, like enemies, pickups, etc..

So I’ve created the concept of game objects, which I explained previously. A game object is basically just an array of handles. In C language, it means an array of pointers. Each handle, or pointer, refer to another part of the memory where content is stored. So a game object can have a piece of memory that explain the world position of a game object, another piece of memory that explain the AI state, and a third piece that explain the animation state.

So it is a retained mode model where the game programmer doesn’t immediately tell the framework to draw a sprite. Instead the game programmer load a sprite and assign it to a game object and then the framework have its own draw function where all the enabled game objects are drawn. This allow the framework to sort the draw order for all game objects. And that is what I did today, I wrote the sorting function.

It is a quite simple bubble sort algorithm. So far performance isn’t a concern of mine. I just want to get something up and running so I can start experimenting with a gameplay mechanic.

Here is the implementation for the sorting:

// Reorder the draw list so they are drawn in the correct order.
// Simple bubble sort
subcall GameObjectManager_SortForDrawing
  DATA32 SlotIndex0
  DATA32 SlotIndex1

  DATA16 Sort0
  DATA16 Sort1

  HANDLE hGameObject0
  HANDLE hGameObject1

  DATA8 ContinueSorting

  MOVE32_32( 0, SlotIndex0 )
  MOVE32_32( 1, SlotIndex1 )

  // Assume this is the last iteration of the sort
  MOVE8_8( 0, ContinueSorting )

  // Read sort values
  ARRAY_READ( GOM_hDrawOrder, SlotIndex0, hGameObject0 )
  ARRAY_READ( GOM_hDrawOrder, SlotIndex1, hGameObject1 )
  JR_EQ16( -1, hGameObject1, EndOfList )

  CALL( Transform_GetSort, hGameObject0, Sort0 )
  CALL( Transform_GetSort, hGameObject1, Sort1 )

  // If object 0 have lower or equal sort value to object 1 we jump to SkipSort
  JR_LTEQ16( Sort0, Sort1, SkipSort )

  // These two needs to swap. That also means we need to do sort again.
  ARRAY_WRITE( GOM_hDrawOrder, SlotIndex0, hGameObject1 )
  ARRAY_WRITE( GOM_hDrawOrder, SlotIndex1, hGameObject0 )
  MOVE8_8( 1, ContinueSorting )

  ADD32( 1, SlotIndex0, SlotIndex0 )
  ADD32( 1, SlotIndex1, SlotIndex1 )

  // Check if we've reached the last index. If we haven't
  // reached the last index yet, jump to Loop.
  JR_LT32( SlotIndex1, GOM_MAXOBJECTS, Loop )

  // So this was the last entry. If the list was modified this iteration we need to do another iteration.
  JR_EQ8( 1, ContinueSorting, MainLoop )

Leave a Reply