Skip to content
This repository has been archived by the owner on Dec 13, 2022. It is now read-only.

Queries

Eric McDaniel edited this page Oct 25, 2021 · 6 revisions

Query Types

Harmony provides two kinds of queries: dynamic and static.

Dynamic queries are the most commonly used query type. They listen for updates to the archetype graph and automatically create live records of entities and component data when a new archetype is inserted. This means that dynamic queries can (and should) be re-used.

Query.make returns a dynamic query:

import { Query, Entity } from "harmony-ecs"

const Kinetic = [Position, Velocity] as const
const kinetics = Query.make(world, Kinetic)
const entity = Entity.make(world, Kinetic)
// `kinetics` tracks `entity`

Although dynamic queries update automatically, the number of dynamic queries in your program will not affect performance much thanks to optimizations within the archetype graph.

Static queries do not update when new archetypes are inserted. They are still fairly fast. If you prefer fewer side effects in your program, static queries provide a more functional programming-friendly approach to querying.

Query.makeStatic returns a static query:

const entityA = Entity.make(world, [Position])
const entityB = Entity.make(world, [Position, Rotation])
const kinetics = Query.makeStatic(world, [Position])
const entityC = Entity.make(world, [Position, Rotation, Velocity])
// `kinetics` tracks `entityA` and `entityB`, but not `entityC`

Iteration

Iteration of a query involves two loops – an outer loop to iterate an array of archetype records, and an inner loop to iterate the entities and component data of a single record.

for (let i = 0; i < kinetics.length; i++) {
  const [entities, [p, v]] = kinetics[i]
  for (let j = 0; j < entities.length; j++) {
    p[i].x += v[i].x
    p[i].x += v[i].x
  }
}

This style of iteration leaks the implementation details of archetype storage. You can write your own helpers to improve the ergonomics of iteration, but this may degrade performance, particularly when iterating archetypes containing binary components.

Clone this wiki locally