API.md
August 18, 2025 ยท View on GitHub
Table of Contents
- ComponentRef
- ComponentData
- registerComponent
- registerComponents
- hasComponent
- getComponent
- set
- recursivelyInherit
- ComponentSetter
- setComponent
- addComponent
- addComponents
- removeComponent
- removeComponents
- addPrefab
- addEntity
- removeEntity
- getEntityComponents
- entityExists
- EntityIndex
- getId
- getVersion
- incrementVersion
- withVersioning
- createEntityIndex
- addEntityId
- removeEntityId
- isEntityIdAlive
- growDepthsArray
- updateDepthCache
- updateMaxDepth
- setEntityDepth
- invalidateQueryCache
- getHierarchyData
- populateExistingDepths
- ensureDepthTracking
- calculateEntityDepth
- getEntityDepthWithVisited
- getEntityDepth
- markChildrenDirty
- updateHierarchyDepth
- invalidateHierarchyDepth
- invalidateSubtree
- flushDirtyDepths
- queryHierarchy
- queryHierarchyDepth
- getHierarchyDepth
- getMaxHierarchyDepth
- QueryResult
- QueryOptions
- Query
- QueryOperatorType
- $opType
- $opTerms
- OpReturnType
- QueryOperator
- QueryTerm
- HierarchyTerm
- Hierarchy
- Cascade
- QueryModifier
- ObservableHook
- observe
- queryHash
- registerQuery
- queryInternal
- query
- queryCheckEntity
- queryCheckComponent
- queryAddEntity
- queryCommitRemovals
- commitRemovals
- queryRemoveEntity
- removeQuery
- OnTargetRemovedCallback
- RelationTarget
- $relation
- $pairTarget
- $isPairComponent
- $relationData
- RelationData
- Relation
- createBaseRelation
- withStore
- makeExclusive
- withAutoRemoveSubject
- withOnTargetRemoved
- withValidation
- Pair
- getRelationTargets
- createRelation
- createRelation
- $wildcard
- createWildcardRelation
- getWildcard
- Wildcard
- createIsARelation
- getIsA
- IsA
- isWildcard
- isRelation
- createWorld
- resetWorld
- deleteWorld
- getWorldComponents
- getAllEntities
ComponentRef
Represents a reference to a component.
Type: any
ComponentData
Represents the data associated with a component.
Properties
idnumber The unique identifier for the component.generationIdnumber The generation ID of the component.bitflagnumber The bitflag used for component masking.refComponentRef Reference to the component.queriesSet<Query> Set of queries associated with the component.setObservableObservable Observable for component changes.
registerComponent
Registers a component with the world.
Parameters
worldWorld The world object.componentComponentRef The component to register.
- Throws Error If the component is null or undefined.
Returns ComponentData The registered component data.
registerComponents
Registers multiple components with the world.
Parameters
worldWorld The world object.componentsArray<ComponentRef> Array of components to register.
hasComponent
Checks if an entity has a specific component.
Parameters
worldWorld The world object.eidnumber The entity ID.componentComponentRef The component to check for.
Returns boolean True if the entity has the component, false otherwise.
getComponent
Retrieves the data associated with a component for a specific entity.
Parameters
worldWorld The world object.eidEntityId The entity ID.componentComponentRef The component to retrieve data for.
Returns any The component data, or undefined if the component is not found or the entity doesn't have the component.
set
Helper function to set component data.
Parameters
componentComponentRef The component to set.dataany The data to set for the component.
Returns {component: ComponentRef, data: any} An object containing the component and its data.
recursivelyInherit
Recursvely inherits components from one entity to another.
Parameters
ctxWorldContextworldWorld The world object.baseEidnumber The ID of the entity inheriting components.inheritedEidnumber The ID of the entity being inherited from.visited(optional, defaultnew Set<EntityId>())isFirstSuperboolean Whether this is the first super in the inheritance chain.
Returns void
ComponentSetter
Represents a component with data to be set on an entity.
Type: {component: ComponentRef, data: T}
Properties
componentComponentRefdataT
setComponent
Sets component data on an entity. Always calls the setter observable even if entity already has the component.
Parameters
worldWorld The world object.eidEntityId The entity ID.componentComponentRef The component to set.dataany The data to set for the component.
- Throws Error If the entity does not exist in the world.
Returns void
addComponent
Adds a single component to an entity.
Parameters
worldWorld The world object.eidEntityId The entity ID.componentOrSet(ComponentRef | ComponentSetter) Component to add or set.
- Throws Error If the entity does not exist in the world.
Returns boolean True if component was added, false if it already existed.
addComponents
Adds multiple components to an entity.
Parameters
worldWorld The world object.eidEntityId The entity ID.components(Array<(ComponentRef | ComponentSetter)> | ComponentRef | ComponentSetter) Components to add or set (array or spread args).
- Throws Error If the entity does not exist in the world.
Returns void
removeComponent
Removes one or more components from an entity.
Parameters
worldWorld The world object.eidnumber The entity ID.components...ComponentRef Components to remove.
- Throws Error If the entity does not exist in the world.
removeComponents
Removes one or more components from an entity. This is an alias for removeComponent.
Parameters
worldWorld The world object.eidEntityId The entity ID.components...ComponentRef Components to remove.
- Throws Error If the entity does not exist in the world.
addPrefab
Creates a new prefab entity in the world. Prefabs are special entities marked with the Prefab component that are excluded from normal queries and can be used as templates for creating other entities.
Parameters
worldWorld The world object to create the prefab in.
Returns EntityId The entity ID of the created prefab.
addEntity
Adds a new entity to the specified world.
Parameters
worldWorld
Returns number eid
removeEntity
Removes an existing entity from the specified world.
Parameters
worldWorldeidnumber
getEntityComponents
Returns an array of components that an entity possesses.
Parameters
worldanyeidany
Returns Array<ComponentRef>
entityExists
Checks the existence of an entity in a world
Parameters
worldWorldeidnumber
EntityIndex
Represents the structure for managing entity IDs.
Type: {aliveCount: number, dense: Array<number>, sparse: Array<number>, maxId: number, versioning: boolean, versionBits: number, entityMask: number, versionShift: number, versionMask: number}
Properties
aliveCountnumberdenseArray<number>sparseArray<number>maxIdnumberversioningbooleanversionBitsnumberentityMasknumberversionShiftnumberversionMasknumber
aliveCount
The number of currently alive entities.
Type: number
dense
Array of entity IDs, densely packed.
sparse
Sparse array mapping entity IDs to their index in the dense array.
maxId
The highest entity ID that has been assigned.
Type: number
versioning
Flag indicating if versioning is enabled.
Type: boolean
versionBits
Number of bits used for versioning.
Type: number
entityMask
Bit mask for entity ID.
Type: number
versionShift
Bit shift for version.
Type: number
versionMask
Bit mask for version.
Type: number
getId
Extracts the entity ID from a versioned entity ID by stripping off the version.
Parameters
indexEntityIndex The EntityIndex containing the masks.idnumber The versioned entity ID.
Returns number The entity ID without the version.
getVersion
Extracts the version from an entity ID.
Parameters
indexEntityIndex The EntityIndex containing the masks and shifts.idnumber The entity ID.
Returns number The version.
incrementVersion
Increments the version of an entity ID.
Parameters
indexEntityIndex The EntityIndex containing the masks and shifts.idnumber The entity ID.
Returns number The new entity ID with incremented version.
withVersioning
Creates configuration options for entity ID recycling with versioning.
Parameters
versionBitsnumber? Optional number of bits to use for version numbers. Defaults to 8 if not specified.
Returns object Configuration object with versioning enabled and specified version bits.
createEntityIndex
Creates and initializes a new EntityIndex.
Parameters
-
options(object | function)? Optional configuration object from withVersioning() or withVersioning function.
Returns EntityIndex A new EntityIndex object.
addEntityId
Adds a new entity ID to the index or recycles an existing one.
Parameters
indexEntityIndex The EntityIndex to add to.
Returns number The new or recycled entity ID.
removeEntityId
Removes an entity ID from the index.
Parameters
indexEntityIndex The EntityIndex to remove from.idnumber The entity ID to remove.
Returns void
isEntityIdAlive
Checks if an entity ID is currently alive in the index.
Parameters
indexEntityIndex The EntityIndex to check.idnumber The entity ID to check.
Returns boolean True if the entity ID is alive, false otherwise.
growDepthsArray
Grows the depths array to accommodate a specific entity
Parameters
hierarchyDataHierarchyDataentityEntityId
Returns Uint32Array
updateDepthCache
Updates the depthToEntities cache when an entity's depth changes
Parameters
Returns void
updateMaxDepth
Updates max depth if the new depth is greater
Parameters
hierarchyDataHierarchyDatadepthnumber
Returns void
setEntityDepth
Sets entity depth and updates all related caches
Parameters
Returns void
invalidateQueryCache
Invalidates hierarchy query cache for a relation
Parameters
worldWorldrelationComponentRef
Returns void
getHierarchyData
Gets hierarchy data for a relation, activating tracking if needed
Parameters
worldWorldrelationComponentRef
Returns HierarchyData
populateExistingDepths
Populates depth calculations for all existing entities with this relation
Parameters
worldWorldrelationComponentRef
Returns void
ensureDepthTracking
Ensures depth tracking is initialized for a relation. This must be called before using hierarchy features for a specific relation component.
Parameters
worldWorld The world object.relationComponentRef The relation component to initialize tracking for.
Returns void
calculateEntityDepth
Calculates the hierarchy depth of an entity for a given relation. Depth is measured as the distance from the root entities (entities with no parent relations).
Parameters
worldWorld The world object.relationComponentRef The relation component to calculate depth for.entityEntityId The entity ID to calculate depth for.visitedSet<EntityId>? Internal set to track visited entities for cycle detection. (optional, defaultnew Set<EntityId>())
Returns number The hierarchy depth of the entity.
getEntityDepthWithVisited
Internal helper to get entity depth with cycle detection
Parameters
worldWorldrelationComponentRefentityEntityIdvisitedSet<EntityId>
Returns number
getEntityDepth
Gets the cached depth of an entity, calculating if needed
Parameters
worldWorldrelationComponentRefentityEntityId
Returns number
markChildrenDirty
Marks an entity and its children as needing depth recalculation. This is used internally when hierarchy changes occur.
Parameters
worldWorld The world object.relationComponentRef The relation component.parentEntityId The parent entity ID.dirtySparseSet The set to mark dirty entities in.visitedSparseSet? Internal set to track visited entities for cycle detection. (optional, defaultcreateSparseSet())
Returns void
updateHierarchyDepth
Updates hierarchy depth when a relation is added. This function is called automatically when components are added to maintain accurate depth tracking.
Parameters
worldWorld The world object.relationComponentRef The relation component.entityEntityId The entity ID that had a relation added.parentEntityId? The parent entity ID in the relation.updatingSet<EntityId>? Internal set to track entities being updated. (optional, defaultnew Set<EntityId>())
Returns void
invalidateHierarchyDepth
Invalidates hierarchy depth when a relation is removed. This function is called automatically when components are removed to maintain accurate depth tracking.
Parameters
worldWorld The world object.relationComponentRef The relation component.entityEntityId The entity ID that had a relation removed.
Returns void
invalidateSubtree
Recursively invalidates an entire subtree
Parameters
worldWorldrelationComponentRefentityEntityIddepthsUint32ArrayvisitedSparseSet
Returns void
flushDirtyDepths
Processes all dirty depth calculations for a relation. This ensures all cached depth values are up to date before performing hierarchy operations.
Parameters
worldWorld The world object.relationComponentRef The relation component to flush dirty depths for.
Returns void
queryHierarchy
Query entities in hierarchical order (depth-based ordering). Returns entities grouped by depth: all depth 0, then depth 1, then depth 2, etc. This ensures parents always come before their children.
Parameters
-
worldWorld The world object. -
relationComponentRef The relation component that defines the hierarchy. -
componentsArray<ComponentRef> Additional components to filter by. -
optionsObject? Query options. (optional, default{})options.bufferedboolean? Whether to return results as Uint32Array instead of number[].
Returns QueryResult Array or Uint32Array of entity IDs in hierarchical order.
queryHierarchyDepth
Get all entities at a specific depth level in the hierarchy.
Parameters
-
worldWorld The world object. -
relationComponentRef The relation component that defines the hierarchy. -
depthnumber The specific depth level to query (0 = root level). -
optionsObject? Query options. (optional, default{})options.bufferedboolean? Whether to return results as Uint32Array instead of number[].
Returns QueryResult Array or Uint32Array of entity IDs at the specified depth.
getHierarchyDepth
Get the hierarchy depth of a specific entity for a given relation.
Parameters
worldWorld The world object.entityEntityId The entity ID to get depth for.relationComponentRef The relation component that defines the hierarchy.
Returns number The depth of the entity (0 = root level, higher numbers = deeper).
getMaxHierarchyDepth
Get the maximum depth in the hierarchy for a given relation.
Parameters
worldWorld The world object.relationComponentRef The relation component that defines the hierarchy.
Returns number The maximum depth found in the hierarchy.
QueryResult
The result of a query, either as a Uint32Array or a readonly array of numbers.
Type: (Uint32Array | any)
QueryOptions
Options for configuring query behavior.
Type: Object
Properties
commitboolean? Whether to commit pending entity removals before querying.bufferedboolean? Whether to return results as Uint32Array instead of number[].
Query
Represents a query in the ECS using original blazing-fast bitmask evaluation.
Type: Object
Properties
allComponentsArray<ComponentRef> All components referenced in the query.orComponentsArray<ComponentRef> Components in an OR relationship.notComponentsArray<ComponentRef> Components that should not be present.masksRecord<number, number> Bitmasks for each component generation.orMasksRecord<number, number> OR bitmasks for each component generation.notMasksRecord<number, number> NOT bitmasks for each component generation.hasMasksRecord<number, number> HAS bitmasks for each component generation.generationsArray<number> Component generations.toRemoveSparseSet Set of entities to be removed.
QueryOperatorType
Types of query operators.
Type: ("Or" | "And" | "Not")
$opType
Symbol for query operator type.
Type: Symbol
$opTerms
Symbol for query operator terms.
Type: Symbol
OpReturnType
Type: Object
Properties
$opTypesymbol? The type of the operator.$opTermssymbol? The components involved in the operation.
QueryOperator
A function that creates a query operator.
Type: Function
Parameters
components...ComponentRef The components to apply the operator to.
Returns OpReturnType The result of the operator.
QueryTerm
A term in a query, either a component reference, query operator, or hierarchy term.
Type: (ComponentRef | QueryOperator | HierarchyTerm)
HierarchyTerm
Represents a hierarchy query term for topological ordering.
Type: Object
Properties
$hierarchyTypesymbol? Always 'Hierarchy'.$hierarchyRelComponentRef? The relation component for hierarchy.$hierarchyDepthnumber? Optional depth limit.
Hierarchy
Creates a hierarchy query term for topological ordering (parents before children).
Parameters
relationComponentRef The relation component (e.g., ChildOf).depthnumber? Optional depth limit.
Returns HierarchyTerm The hierarchy term.
Cascade
Alias for Hierarchy - creates a hierarchy query term for topological ordering.
Parameters
relationComponentRef The relation component (e.g., ChildOf).depthnumber? Optional depth limit.
Returns HierarchyTerm The hierarchy term.
QueryModifier
Represents a query modifier that can be mixed into query terms.
Type: Object
Properties
$modifierTypesymbol? The type of modifier ('buffer' | 'nested').
ObservableHook
A function that creates an observable hook for queries.
Type: Function
Parameters
terms...QueryTerm The query terms to observe.
observe
Observes changes in entities based on specified components.
Parameters
worldWorld The world object.hookObservableHook The observable hook.callbackfunction (number): any The callback function to execute when changes occur.
Returns function (): void A function to unsubscribe from the observation.
queryHash
Generates a hash for a query based on its terms.
Parameters
Returns string The generated hash.
registerQuery
Registers a new query in the world using unified clause-mask compilation.
Parameters
-
worldWorld The world object. -
optionsObject? Additional options.options.bufferedboolean? Whether the query should be buffered.
Returns Query The registered query.
queryInternal
Internal implementation for nested queries.
Parameters
-
worldWorld The world object. -
optionsObject? Additional options.options.bufferedboolean? Whether the query should be buffered.
Returns QueryResult The result of the query.
query
Performs a unified query operation with configurable options.
Parameters
worldWorld The world object.termsArray<QueryTerm> The query terms.modifiers...QueryModifier Query modifiers (asBuffer, isNested, etc.).
Returns QueryResult The result of the query.
queryCheckEntity
Original blazing-fast query evaluation using simple bitmasks.
Parameters
worldWorld The world object.queryQuery The query to check against.eidnumber The entity ID to check.
Returns boolean True if the entity matches the query, false otherwise.
queryCheckComponent
Checks if a component matches a query.
Parameters
queryQuery The query to check against.cComponentData The component data to check.
Returns boolean True if the component matches the query, false otherwise.
queryAddEntity
Adds an entity to a query.
Parameters
queryCommitRemovals
Commits removals for a query.
Parameters
queryQuery The query to commit removals for.
commitRemovals
Commits all pending removals for queries in the world.
Parameters
worldWorld The world object.
queryRemoveEntity
Removes an entity from a query.
Parameters
worldWorld The world object.queryQuery The query to remove the entity from.eidnumber The entity ID to remove.
removeQuery
Removes a query from the world.
Parameters
OnTargetRemovedCallback
Callback function type for when a target is removed from a relation.
Type: Function
Parameters
RelationTarget
Possible types for a relation target.
Type: (number | "*" | any)
$relation
Symbol for accessing the relation of a component.
Type: Symbol
$pairTarget
Symbol for accessing the pair target of a component.
Type: Symbol
$isPairComponent
Symbol for checking if a component is a pair component.
Type: Symbol
$relationData
Symbol for accessing the relation data of a component.
Type: Symbol
RelationData
Interface for relation data.
Relation
Type definition for a Relation function.
Type: function
Parameters
targetRelationTarget The target of the relation.
Returns T The relation component.
createBaseRelation
Creates a base relation.
Returns Relation<T> The created base relation.
withStore
Adds a store to a relation.
Parameters
createStorefunction (): T Function to create the store.
Returns function (Relation<T>): Relation<T> A function that modifies the relation.
makeExclusive
Makes a relation exclusive.
Parameters
relationRelation<T> The relation to make exclusive.
Returns Relation<T> The modified relation.
withAutoRemoveSubject
Adds auto-remove subject behavior to a relation.
Parameters
relationRelation<T> The relation to modify.
Returns Relation<T> The modified relation.
withOnTargetRemoved
Adds an onTargetRemoved callback to a relation.
Parameters
onRemoveOnTargetRemovedCallback The callback to add.
Returns function (Relation<T>): Relation<T> A function that modifies the relation.
withValidation
Adds validation to a relation.
Parameters
validateFnfunction (T): boolean The validation function.
Returns function (Relation<T>): Relation<T> A function that modifies the relation.
Pair
Creates a pair from a relation and a target.
Parameters
relationRelation<T> The relation.targetRelationTarget The target.
- Throws Error If the relation is undefined.
Returns T The created pair.
getRelationTargets
Gets the relation targets for an entity.
Parameters
worldWorld The world object.eidnumber The entity ID.relationRelation<any> The relation to get targets for.
Returns Array<any> An array of relation targets.
createRelation
Creates a new relation.
Parameters
Returns Relation<T> The created relation.
createRelation
Creates a new relation with options.
Parameters
-
optionsObject Options for creating the relation.options.storefunction (): T? Function to create the store.options.exclusiveboolean? Whether the relation is exclusive.options.autoRemoveSubjectboolean? Whether to auto-remove the subject.options.onTargetRemovedOnTargetRemovedCallback? Callback for when a target is removed.
Returns Relation<T> The created relation.
$wildcard
Symbol used to mark a relation as a wildcard relation
createWildcardRelation
Creates a wildcard relation that matches any target.
Returns Relation<T> The created wildcard relation.
getWildcard
Gets the singleton wildcard instance.
Returns Relation<any> The global wildcard relation instance.
Wildcard
Wildcard relation.
Type: Relation<any>
createIsARelation
Creates an IsA relation.
Returns Relation<T> The created IsA relation.
getIsA
Gets the singleton IsA instance.
Returns Relation<any> The global IsA relation instance.
IsA
IsA relation.
Type: Relation<any>
isWildcard
Checks if a relation is a wildcard relation.
Parameters
relationany The relation to check.
Returns boolean True if the relation is a wildcard relation, false otherwise.
isRelation
Checks if a component is a relation.
Parameters
componentany The component to check.
Returns boolean True if the component is a relation, false otherwise.
createWorld
Creates a new world with various configurations.
Parameters
args...Array<(EntityIndex | object)> EntityIndex, context object, or both.
Returns World<T> The created world.
resetWorld
Resets a world.
Parameters
worldWorld
Returns object
deleteWorld
Deletes a world by removing its internal data.
Parameters
worldWorld The world to be deleted.
getWorldComponents
Returns all components registered to a world
Parameters
worldWorld
Returns any Array
getAllEntities
Returns all existing entities in a world
Parameters
worldWorld
Returns any Array