From 87711eff19ff94686e51dd548d9363b1e52f0bb3 Mon Sep 17 00:00:00 2001 From: Ukendio Date: Fri, 10 May 2024 20:35:41 +0200 Subject: [PATCH] Register components as entities --- lib/init.lua | 26 ++++++++++++++------------ tests/world.lua | 14 +++++++------- 2 files changed, 21 insertions(+), 19 deletions(-) diff --git a/lib/init.lua b/lib/init.lua index 166e3b6..ea1154b 100644 --- a/lib/init.lua +++ b/lib/init.lua @@ -291,6 +291,16 @@ local function ecs_get_target(entityIndex, e) return getAlive(entityIndex, ECS_PAIR_SECOND(e)) end +local function nextEntityId(entityIndex, index: i24) + local id = newId(index, 0) + entityIndex.sparse[id] = { + dense = index + } :: Record + entityIndex.dense[index] = id + + return id +end + function World.component(world: World) local componentId = world.nextComponentId + 1 if componentId > HI_COMPONENT_ID then @@ -299,21 +309,13 @@ function World.component(world: World) error("Too many components, consider using world:entity() instead to create components.") end world.nextComponentId = componentId - return componentId + return nextEntityId(world.entityIndex, componentId) end function World.entity(world: World) - local nextEntityId = world.nextEntityId + 1 - world.nextEntityId = nextEntityId - local index = nextEntityId + REST - local id = newId(index, 0) - local entityIndex = world.entityIndex - entityIndex.sparse[id] = { - dense = index - } :: Record - entityIndex.dense[index] = id - - return id + local entityId = world.nextEntityId + 1 + world.nextEntityId = entityId + return nextEntityId(world.entityIndex, entityId + REST) end -- should reuse this logic in World.set instead of swap removing in transition archetype diff --git a/tests/world.lua b/tests/world.lua index 5dd3f95..d95097d 100644 --- a/tests/world.lua +++ b/tests/world.lua @@ -5,8 +5,8 @@ local ECS_GENERATION_INC = jecs.ECS_GENERATION_INC local IS_PAIR = jecs.IS_PAIR local ECS_PAIR = jecs.ECS_PAIR local getAlive = jecs.getAlive -local ecs_pair_first = jecs.ecs_pair_first -local ecs_pair_second = jecs.ecs_pair_second +local ecs_get_source = jecs.ecs_get_source +local ecs_get_target = jecs.ecs_get_target local REST = 256 + 4 local TEST, CASE, CHECK, FINISH, SKIP = testkit.test() @@ -39,12 +39,12 @@ TEST("world", function() elseif id == eAB then CHECK(data[A] == true) CHECK(data[B] == true) - else - error("unknown entity", id) end end - CHECK(count == 3) + -- components are registered in the entity index as well + -- so this test has to add 2 to account for them + CHECK(count == 3 + 2) end do CASE "should query all matching entities" @@ -199,8 +199,8 @@ TEST("world", function() local pair = ECS_PAIR(e2, e3) CHECK(IS_PAIR(pair) == true) - CHECK(ecs_pair_first(world.entityIndex, pair) == e2) - CHECK(ecs_pair_second(world.entityIndex, pair) == e3) + CHECK(ecs_get_source(world.entityIndex, pair) == e2) + CHECK(ecs_get_target(world.entityIndex, pair) == e3) end end)