Benjamin Yang · EAE 6320

Engine System Proposal: Collision

Box and sphere colliders defined in data files, enter / stay / exit events, solid objects that stop each other, and raycasts

The idea

My Engine System will be a collision system: a static library that knows where the solid parts of a game are and tells the game when they touch. Almost every final project game needs this, and it is something we haven't built yet: so far our objects pass straight through each other and through the floor.

From the point of view of a classmate making a game with it:

What it deliberately is not: a physics engine. It doesn't add gravity, forces, bouncing or rotation. Objects keep moving with the engine's existing sRigidBodyState (a game that wants gravity sets an acceleration, as we already can), and the collision system only detects contacts and keeps solid objects apart. This keeps the scope realistic and keeps the library easy to drop into any of our games.

How the pieces fit together, following the same pattern as the meshes in Assignments 06-08: human-readable files are checked and converted at build time, and the game only loads small binary files
How the pieces fit together, following the same pattern as the meshes in Assignments 06-08: human-readable files are checked and converted at build time, and the game only loads small binary files.

Features

What I expect to finish (the requirements I am holding myself to):

How someone would use it

1. Set up the solution. Add the Collision static library and the ColliderBuilder tool to the solution, add a reference from the game project to Collision, and make BuildMyGameAssets depend on ColliderBuilder (the same way it depends on MeshBuilder). The library has no dependencies beyond the engine projects we all have (Math, Physics, Platform, Results, Logging...).

2. Describe the layers. One file per game lists the layers and which of them interact:

-- MyGame_/Content/Collision/game.layers
return
{
	-- Every collider belongs to one of these layers (at most 32)
	layers = { "world", "player", "enemy", "pickup" },

	-- The pairs of layers that touch each other;
	-- colliders in any pair of layers that isn't listed pass through each other without events
	interactions =
	{
		{ "player", "world" },
		{ "player", "enemy" },
		{ "player", "pickup" },
		{ "enemy", "world" },
	},
}

3. Write a collider file for each kind of object. Only shape, its size and layer are required:

-- MyGame_/Content/Colliders/player.collider
return
{
	shape = "sphere",
	radius = 0.5,
	layer = "player",
	-- Optional values (shown with their defaults):
	-- center = { x = 0.0, y = 0.0, z = 0.0 },	-- offset from the object's position
	-- isTrigger = false,	-- true: report overlaps, but never push anything
	-- isStatic = false,	-- true: never moves and is never pushed (walls, floors)
}
-- MyGame_/Content/Colliders/floor.collider
return
{
	shape = "box",
	halfSize = { x = 4.0, y = 0.05, z = 4.0 },
	center = { x = 0.0, y = -0.05, z = 0.0 },	-- so the top of the box is at the object's position
	layer = "world",
	isStatic = true,
}

4. Tell the asset build about the files. This is what the user guide will tell people to add:

-- AssetBuildFunctions.lua (copy once; ColliderBuilder.exe builds both kinds of file)
NewAssetTypeInfo( "collisionlayers",
	{
		ConvertSourceRelativePathToBuiltRelativePath = function( i_sourceRelativePath )
			-- Collision/game.layers -> Collision/game.binlayers
			return ( i_sourceRelativePath:gsub( "%.layers$", ".binlayers" ) )
		end,
		GetBuilderRelativePath = function() return "ColliderBuilder.exe" end,
	}
)
NewAssetTypeInfo( "colliders",
	{
		ConvertSourceRelativePathToBuiltRelativePath = function( i_sourceRelativePath )
			-- Colliders/player.collider -> Colliders/player.bincollider
			return ( i_sourceRelativePath:gsub( "%.collider$", ".bincollider" ) )
		end,
		GetBuilderRelativePath = function() return "ColliderBuilder.exe" end,
		-- Layer names are checked against the layers file, so colliders are rebuilt whenever it changes
		ShouldTargetBeBuilt = function( i_lastWriteTime_builtAsset )
			return GetLastWriteTime( GameSourceContentDir .. "Collision/game.layers" ) > i_lastWriteTime_builtAsset
		end,
	}
)

-- AssetsToBuild.lua (list your own files)
	collisionlayers = { "Collision/game.layers" },
	colliders = { "Colliders/player.collider", "Colliders/floor.collider", "Colliders/coin.collider" },

5. Use it in the game. The public interface (everything platform-independent; the exact names may still change while I build it):

namespace eae6320
{
	namespace Collision
	{
		// Call from your game's Initialize() and CleanUp()
		cResult Initialize( const char* const i_path_layers );	// e.g. "data/Collision/game.binlayers"
		cResult CleanUp();

		// Call once per simulation update, after your objects have moved:
		// it pushes solid objects apart and then calls the event functions
		void Update();

		// What an event tells you
		struct sContact
		{
			cCollider* other;	// The collider that was touched
			Math::sVector normal;	// Points from the other collider toward this one
			float penetrationDepth;	// How far they overlapped before they were pushed apart
		};

		class cCollider
		{
		public:
			// Loads a built collider file and attaches it to a rigid body that your game object owns:
			// the collider reads its position from it, and if the collider is solid and not static
			// it moves the rigid body out of whatever it hits and stops its velocity into the surface
			static cResult Load( const char* const i_path, Physics::sRigidBodyState& io_rigidBody, cCollider*& o_collider );
			// (reference counted like cMesh: DecrementReferenceCount() removes it from the world)

			// Any of these can be left empty
			std::function<void( const sContact& )> OnEnter, OnStay, OnExit;
			// Lets you find your own object from inside an event
			void* userData = nullptr;

			void SetEnabled( const bool i_isEnabled );	// A disabled collider is ignored (and its touches end)
			bool IsTrigger() const;
			uint8_t GetLayer() const;
		};

		// Queries
		struct sRaycastHit { cCollider* collider; Math::sVector point, normal; float distance; };
		bool Raycast( const Math::sVector& i_origin, const Math::sVector& i_direction, const float i_maxDistance,
			sRaycastHit& o_hit, const uint32_t i_layerMask = ~0u );
		uint32_t GetLayerMask( const char* const i_layerName );	// e.g. to raycast only against "world"
	}
}

And a typical use in a game:

// cMyGame::Initialize()
Collision::Initialize( "data/Collision/game.binlayers" );
Collision::cCollider::Load( "data/Colliders/player.bincollider", m_player.rigidBodyState, m_player.collider );
Collision::cCollider::Load( "data/Colliders/floor.bincollider", m_floor.rigidBodyState, m_floor.collider );
Collision::cCollider::Load( "data/Colliders/coin.bincollider", m_coin.rigidBodyState, m_coin.collider );	// a trigger
m_coin.collider->userData = &m_coin;
m_player.collider->OnEnter = [this]( const Collision::sContact& i_contact )
{
	if ( i_contact.other->userData == &m_coin )
	{
		m_score += 1;
		m_coin.collider->SetEnabled( false );	// (and stop drawing it)
	}
};

// cMyGame::UpdateSimulationBasedOnTime()
m_player.rigidBodyState.Update( i_elapsedSecondCount_sinceLastUpdate );	// move everything as usual...
Collision::Update();	// ...then let the collision system fix overlaps and send the events

// Is the player standing on something? (e.g. before allowing a jump)
Collision::sRaycastHit hit;
const bool isOnGround = Collision::Raycast( m_player.rigidBodyState.position, Math::sVector( 0.0f, -1.0f, 0.0f ), 0.55f,
	hit, Collision::GetLayerMask( "world" ) );

What I expect to implement

MilestoneDatePlan
Update #1Nov 3Collision library and ColliderBuilder projects; both file formats with build-time errors; loading; overlap tests for all shape pairs; enter / stay / exit events printed to the log in MyGame.
Update #2Nov 10Solid response and velocity correction; triggers; layer table; raycasts; the MyGame demo; first version of the user guide.
Presentation / write-upNov 16 / Nov 19Support for anyone who has started using it, polish and documentation, then stretch goals as time allows.

Challenges I expect

Stretch goals