Adds symmetic function add

This commit is contained in:
Ukendio 2024-05-04 15:47:26 +02:00
parent cda04ce5a9
commit fad2a21ac5

View file

@ -185,6 +185,8 @@ function World.new()
[ON_ADD] = {} [ON_ADD] = {}
} }
}, World) }, World)
local ROOT_ARCHETYPE = archetypeOf(self, {}, nil)
self.ROOT_ARCHETYPE = ROOT_ARCHETYPE
return self return self
end end
@ -266,14 +268,8 @@ local function ensureEdge(archetype: Archetype, componentId: i53)
end end
local function archetypeTraverseAdd(world: World, componentId: i53, from: Archetype): Archetype local function archetypeTraverseAdd(world: World, componentId: i53, from: Archetype): Archetype
if not from then from = from or world.ROOT_ARCHETYPE
-- If there was no source archetype then it should return the ROOT_ARCHETYPE
if not world.ROOT_ARCHETYPE then
local ROOT_ARCHETYPE = archetypeOf(world, {}, nil)
world.ROOT_ARCHETYPE = ROOT_ARCHETYPE
end
from = world.ROOT_ARCHETYPE
end
local edge = ensureEdge(from, componentId) local edge = ensureEdge(from, componentId)
if not edge.add then if not edge.add then
@ -293,10 +289,26 @@ local function ensureRecord(entityIndex, entityId: i53): Record
return entityIndex[id] :: Record return entityIndex[id] :: Record
end end
-- Symmetric
function World.add(world: World, entityId: i53, componentId: i53)
local record = ensureRecord(world.entityIndex, entityId)
local from = record.archetype
local to = archetypeTraverseAdd(world, entityId, from)
if from then
moveEntity(world.entityIndex, entityId, record, to)
else
if #to.types > 0 then
newEntity(entityId, record, to)
onNotifyAdd(world, to, from, record.row, { componentId })
end
end
end
-- Symmetric like `World.add` but idempotent
function World.set(world: World, entityId: i53, componentId: i53, data: unknown) function World.set(world: World, entityId: i53, componentId: i53, data: unknown)
local record = ensureRecord(world.entityIndex, entityId) local record = ensureRecord(world.entityIndex, entityId)
local from = record.archetype local from = record.archetype
local to = archetypeTraverseAdd(world, componentId, from) local to = archetypeTraverseAdd(world, entityId, from)
if from == to then if from == to then
-- If the archetypes are the same it can avoid moving the entity -- If the archetypes are the same it can avoid moving the entity
@ -317,7 +329,7 @@ function World.set(world: World, entityId: i53, componentId: i53, data: unknown)
onNotifyAdd(world, to, from, record.row, { componentId }) onNotifyAdd(world, to, from, record.row, { componentId })
end end
end end
local archetypeRecord = to.records[componentId] local archetypeRecord = to.records[componentId]
to.columns[archetypeRecord][record.row] = data to.columns[archetypeRecord][record.row] = data
end end