Add queryNext

This commit is contained in:
Ukendio 2024-06-22 00:15:03 +02:00
parent ea12df96a4
commit 5bd43bddd4

View file

@ -652,14 +652,15 @@ setmetatable(EmptyQuery, EmptyQuery)
export type Query = typeof(EmptyQuery) export type Query = typeof(EmptyQuery)
type CompatibleArchetype = { archetype: Archetype, indices: { number } }
function World.query(world: World, ...): Query function World.query(world: World, ...): Query
-- breaking? -- breaking?
if (...) == nil then if (...) == nil then
error("Missing components") error("Missing components")
end end
type CompatibleArchetype = { archetype: Archetype, indices: { number } } local compatibleArchetypes: { CompatibleArchetype } = {}
local compatibleArchetypes = {} :: { CompatibleArchetype }
local length = 0 local length = 0
local components = { ... } local components = { ... }
@ -708,33 +709,38 @@ function World.query(world: World, ...): Query
} }
end end
local lastArchetype, compatibleArchetype: CompatibleArchetype = next(compatibleArchetypes :: any) local lastArchetype = 1
local compatibleArchetype: CompatibleArchetype = compatibleArchetypes[lastArchetype]
if not lastArchetype then if not compatibleArchetype then
return EmptyQuery return EmptyQuery
end end
local preparedQuery = {} local preparedQuery = {}
preparedQuery.__index = preparedQuery preparedQuery.__index = preparedQuery
local lastRow
local queryOutput = {} local queryOutput = {}
function preparedQuery:__iter() local i = 1
return function()
local function queryNext()
local archetype = compatibleArchetype.archetype local archetype = compatibleArchetype.archetype
local row: number = next(archetype.entities, lastRow) local entityId = archetype.entities[i]
while row == nil do
lastArchetype, compatibleArchetype = next(compatibleArchetypes, lastArchetype) while entityId == nil do
if lastArchetype == nil then lastArchetype += 1
if lastArchetype > #compatibleArchetypes then
return return
end end
compatibleArchetype = compatibleArchetypes[lastArchetype]
archetype = compatibleArchetype.archetype archetype = compatibleArchetype.archetype
row = next(archetype.entities, row) i = 1
entityId = archetype.entities[i]
end end
lastRow = row
local entityId = archetype.entities[row] local row = i
i+=1
local columns = archetype.columns local columns = archetype.columns
local tr = compatibleArchetype.indices local tr = compatibleArchetype.indices
@ -788,6 +794,13 @@ function World.query(world: World, ...): Query
return entityId, unpack(queryOutput :: any, 1, queryLength) return entityId, unpack(queryOutput :: any, 1, queryLength)
end end
function preparedQuery:__iter()
return queryNext
end
function preparedQuery:next()
return queryNext()
end end
function preparedQuery:without(...) function preparedQuery:without(...)