Skip to content

A fast 2D and 3D game engine — TypeScript SDK, C++/WebAssembly core, visual editor. Ship one project to web, desktop, WeChat MiniGames, playable ads, and native Android / iOS.

perf: optimize query iteration, change detection, component creation and WASM conversion

esengine3e52c7753381
diff --git a/sdk/benchmarks/commands.bench.ts b/sdk/benchmarks/commands.bench.ts
new file mode 100644
index 000000000..b30894594
--- /dev/null
+++ b/sdk/benchmarks/commands.bench.ts
@@ -0,0 +1,71 @@
+import { bench, describe } from 'vitest';
+import { World } from '../src/world';
+import { defineComponent } from '../src/component';
+import { CommandsInstance } from '../src/commands';
+import { ResourceStorage } from '../src/resource';
+import { Entity } from '../src/types';
+
+const Position = defineComponent('CmdBenchPosition', { x: 0, y: 0 });
+const Velocity = defineComponent('CmdBenchVelocity', { vx: 0, vy: 0 });
+
+describe('Commands - Deferred spawn', () => {
+ bench('spawn 100 entities with 2 components', () => {
+ const world = new World();
+ const resources = new ResourceStorage();
+ const cmds = new CommandsInstance(world, resources);
+ for (let i = 0; i < 100; i++) {
+ cmds.spawn()
+ .insert(Position, { x: i, y: i })
+ .insert(Velocity, { vx: 1, vy: 1 });
+ }
+ cmds.flush();
+ });
+});
+
+describe('Commands - Deferred despawn', () => {
+ bench('despawn 100 entities', () => {
+ const world = new World();
+ const resources = new ResourceStorage();
+ const entities: Entity[] = [];
+ for (let i = 0; i < 100; i++) {
+ const e = world.spawn();
+ world.insert(e, Position, { x: i, y: i });
+ entities.push(e);
+ }
+ const cmds = new CommandsInstance(world, resources);
+ for (const e of entities) cmds.despawn(e);
+ cmds.flush();
+ });
+});
+
+describe('Commands - Deferred insert', () => {
+ bench('insert to 500 entities', () => {
+ const world = new World();
+ const resources = new ResourceStorage();
+ const entities: Entity[] = [];
+ for (let i = 0; i < 500; i++) entities.push(world.spawn());
+ const cmds = new CommandsInstance(world, resources);
+ for (const e of entities) {
+ cmds.entity(e).insert(Position, { x: 1, y: 1 });
+ }
+ cmds.flush();
+ });
+});
+
+describe('Commands - Mixed operations', () => {
+ bench('50 spawns + 20 despawns + 30 inserts', () => {
+ const world = new World();
+ const resources = new ResourceStorage();
+ const cmds = new CommandsInstance(world, resources);
+ const spawned: Entity[] = [];
+ for (let i = 0; i < 50; i++) {
+ const ec = cmds.spawn().insert(Position, { x: i, y: i });
+ spawned.push(ec.id());
+ }
+ for (let i = 0; i < 20; i++) cmds.despawn(spawned[i]);
+ for (let i = 20; i < 50; i++) {
+ cmds.entity(spawned[i]).insert(Velocity, { vx: 1, vy: 1 });
+ }
+ cmds.flush();
+ });
+});
diff --git a/sdk/benchmarks/component.bench.ts b/sdk/benchmarks/component.bench.ts
new file mode 100644
index 000000000..c8f1f5623
--- /dev/null
+++ b/sdk/benchmarks/component.bench.ts
@@ -0,0 +1,77 @@
+import { bench, describe } from 'vitest';
+import { defineComponent, getComponent, getAllRegisteredComponents, clearUserComponents } from '../src/component';
+import { computeQueryCacheKey } from '../src/world';
+
+describe('Component - Definition', () => {
+ bench('defineComponent (simple)', () => {
+ defineComponent(`BenchSimple_${Math.random()}`, { x: 0, y: 0 });
+ });
+
+ bench('defineComponent (nested objects)', () => {
+ defineComponent(`BenchNested_${Math.random()}`, {
+ position: { x: 0, y: 0 },
+ color: { r: 1, g: 1, b: 1, a: 1 },
+ });
+ });
+});
+
+describe('Component - create() (instance creation)', () => {
+ const Simple = defineComponent('BenchCreateSimple', { x: 0, y: 0, z: 0 });
+ const Nested = defineComponent('BenchCreateNested', {
+ position: { x: 0, y: 0 },
+ scale: { x: 1, y: 1 },
+ });
+
+ bench('create simple x1000', () => {
+ for (let i = 0; i < 1000; i++) Simple.create({ x: i, y: i });
+ });
+
+ bench('create nested x1000', () => {
+ for (let i = 0; i < 1000; i++) Nested.create({ position: { x: i, y: i } });
+ });
+
+ bench('create with defaults x1000', () => {
+ for (let i = 0; i < 1000; i++) Simple.create();
+ });
+});
+
+describe('Component - Registry lookup', () => {
+ for (let i = 0; i < 50; i++) {
+ defineComponent(`LookupComp_${i}`, { value: i });
+ }
+
+ bench('getComponent (existing) x1000', () => {
+ for (let i = 0; i < 1000; i++) getComponent(`LookupComp_${i % 50}`);
+ });
+
+ bench('getComponent (non-existing) x1000', () => {
+ for (let i = 0; i < 1000; i++) getComponent('NonExistent');
+ });
+
+ bench('getAllRegisteredComponents', () => {
+ getAllRegisteredComponents();
+ });
+});
+
+describe('computeQueryCacheKey', () => {
+ const A = defineComponent('CacheKeyA', {});
+ const B = defineComponent('CacheKeyB', {});
+ const C = defineComponent('CacheKeyC', {});
+ const D = defineComponent('CacheKeyD', {});
+
+ bench('2 components, no filters', () => {
+ computeQueryCacheKey([A, B]);
+ });
+
+ bench('3 components + with filter', () => {
+ computeQueryCacheKey([A, B, C], [D]);
+ });
+
+ bench('2 components + with + without', () => {
+ computeQueryCacheKey([A, B], [C], [D]);
+ });
+
+ bench('cache key x1000', () => {
+ for (let i = 0; i < 1000; i++) computeQueryCacheKey([A, B, C]);
+ });
+});
diff --git a/sdk/benchmarks/event.bench.ts b/sdk/benchmarks/event.bench.ts
new file mode 100644
index 000000000..eb160d9c9
--- /dev/null
+++ b/sdk/benchmarks/event.bench.ts
@@ -0,0 +1,69 @@
+import { bench, describe } from 'vitest';
+import { defineEvent, EventBus, EventRegistry, EventWriterInstance, EventReaderInstance } from '../src/event';
+
+interface DamageEvent {
+ target: number;
+ amount: number;
+}
+
+const DamageEvt = defineEvent<DamageEvent>('BenchDamage');
+
+describe('EventBus - Write', () => {
+ bench('send 1000 events', () => {
+ const bus = new EventBus<DamageEvent>();
+ for (let i = 0; i < 1000; i++) {
+ bus.send({ target: i, amount: 10 });
+ }
+ });
+});
+
+describe('EventBus - Read (1000 events)', () => {
+ const bus = new EventBus<DamageEvent>();
+ for (let i = 0; i < 1000; i++) bus.send({ target: i, amount: 10 });
+ bus.swap();
+
+ bench('iterate read buffer', () => {
+ const buf = bus.getReadBuffer();
+ let sum = 0;
+ for (const e of buf) sum += e.amount;
+ });
+});
+
+describe('EventBus - Swap', () => {
+ bench('swap buffers (100 events)', () => {
+ const bus = new EventBus<DamageEvent>();
+ for (let i = 0; i < 100; i++) bus.send({ target: i, amount: 10 });
+ bus.swap();
+ });
+});
+
+describe('EventRegistry - swapAll', () => {
+ const registry = new EventRegistry();
+ const events = [];
+ for (let i = 0; i < 20; i++) {
+ const evt = defineEvent(`BenchEvt${i}`);
+ registry.register(evt);
+ events.push(evt);
+ const bus = registry.getBus(evt);
+ for (let j = 0; j < 50; j++) bus.send({ data: j });
+ }
+
+ bench('swapAll (20 buses)', () => {
+ registry.swapAll();
+ });
+});
+
+describe('EventWriter/Reader - Full cycle', () => {
+ bench('write 100 + swap + read 100', () => {
+ const registry = new EventRegistry();
+ registry.register(DamageEvt);
+ const writer = new EventWriterInstance(registry.getBus(DamageEvt));
+ for (let i = 0; i < 100; i++) {
+ writer.send({ target: i, amount: 5 });
+ }
+ registry.swapAll();
+ const reader = new EventReaderInstance(registry.getBus(DamageEvt));
+ let sum = 0;
+ for (const e of reader) sum += (e as DamageEvent).amount;
+ });
+});
diff --git a/sdk/benchmarks/query.bench.ts b/sdk/benchmarks/query.bench.ts
new file mode 100644
index 000000000..f637c8f36
--- /dev/null
+++ b/sdk/benchmarks/query.bench.ts
@@ -0,0 +1,75 @@
+import { bench, describe } from 'vitest';
+import { World } from '../src/world';
+import { defineComponent } from '../src/component';
+import { QueryInstance, Query, Mut } from '../src/query';
+import { Entity } from '../src/types';
+
+const Position = defineComponent('QBenchPosition', { x: 0, y: 0 });
+const Velocity = defineComponent('QBenchVelocity', { vx: 0, vy: 0 });
+const Health = defineComponent('QBenchHealth', { hp: 100 });
+
+describe('Query - Iteration (5000 entities, 2 components)', () => {
+ const world = new World();
+ for (let i = 0; i < 5000; i++) {
+ const e = world.spawn();
+ world.insert(e, Position, { x: i, y: i });
+ world.insert(e, Velocity, { vx: 1, vy: 1 });
+ }
+
+ bench('forEach', () => {
+ world.resetQueryPool();
+ const q = new QueryInstance(world, Query(Position, Velocity));
+ q.forEach(() => {});
+ });
+
+ bench('for-of', () => {
+ world.resetQueryPool();
+ const q = new QueryInstance(world, Query(Position, Velocity));
+ for (const _ of q) { /* noop */ }
+ });
+
+ bench('toArray', () => {
+ world.resetQueryPool();
+ const q = new QueryInstance(world, Query(Position, Velocity));
+ q.toArray();
+ });
+
+ bench('count', () => {
+ world.resetQueryPool();
+ const q = new QueryInstance(world, Query(Position, Velocity));
+ q.count();
+ });
+});
+
+describe('Query - Mutable iteration (1000 entities)', () => {
+ const world = new World();
+ for (let i = 0; i < 1000; i++) {
+ const e = world.spawn();
+ world.insert(e, Position, { x: i, y: i });
+ world.insert(e, Velocity, { vx: 1, vy: 1 });
+ }
+
+ bench('Mut query', () => {
+ world.resetQueryPool();
+ const q = new QueryInstance(world, Query(Mut(Position), Velocity));
+ for (const [_e, pos, vel] of q) {
+ (pos as any).x += (vel as any).vx;
+ (pos as any).y += (vel as any).vy;
+ }
+ });
+});
+
+describe('Query - Sparse matching (100/10000 match)', () => {
+ const world = new World();
+ for (let i = 0; i < 10000; i++) {
+ const e = world.spawn();
+ world.insert(e, Position, { x: i, y: i });
+ if (i % 100 === 0) world.insert(e, Health, { hp: 50 });
+ }
+
+ bench('query sparse component', () => {
+ world.resetQueryPool();
+ const q = new QueryInstance(world, Query(Position, Health));
+ for (const _ of q) { /* noop */ }
+ });
+});
diff --git a/sdk/benchmarks/uiMath.bench.ts b/sdk/benchmarks/uiMath.bench.ts
new file mode 100644
index 000000000..3362f4328
--- /dev/null
+++ b/sdk/benchmarks/uiMath.bench.ts
@@ -0,0 +1,131 @@
+import { bench, describe } from 'vitest';
+import {
+ invertMatrix4,
+ screenToWorld,
+ worldToScreen,
+ pointInWorldRect,
+ pointInOBB,
+ intersectRects,
+ createInvVPCache,
+} from '../src/ui/uiMath';
+
+const identityMatrix = new Float32Array([
+ 1, 0, 0, 0,
+ 0, 1, 0, 0,
+ 0, 0, 1, 0,
+ 0, 0, 0, 1,
+]);
+
+const orthoMatrix = new Float32Array([
+ 0.002, 0, 0, 0,
+ 0, 0.003, 0, 0,
+ 0, 0, -0.002, 0,
+ -1, -1, -1, 1,
+]);
+
+const resultMatrix = new Float32Array(16);
+
+describe('uiMath - Matrix operations', () => {
+ bench('invertMatrix4 (identity)', () => {
+ invertMatrix4(identityMatrix, resultMatrix);
+ });
+
+ bench('invertMatrix4 (ortho projection)', () => {
+ invertMatrix4(orthoMatrix, resultMatrix);
+ });
+
+ bench('invertMatrix4 x100 (no result reuse)', () => {
+ for (let i = 0; i < 100; i++) {
+ invertMatrix4(orthoMatrix);
+ }
+ });
+
+ bench('invertMatrix4 x100 (result reuse)', () => {
+ for (let i = 0; i < 100; i++) {
+ invertMatrix4(orthoMatrix, resultMatrix);
+ }
+ });
+});
+
+describe('uiMath - Coordinate transforms', () => {
+ const invVP = new Float32Array(16);
+ invertMatrix4(orthoMatrix, invVP);
+
+ bench('screenToWorld x1000', () => {
+ for (let i = 0; i < 1000; i++) {
+ screenToWorld(400 + i * 0.1, 300, invVP, 0, 0, 800, 600);
+ }
+ });
+
+ bench('worldToScreen x1000', () => {
+ for (let i = 0; i < 1000; i++) {
+ worldToScreen(i * 0.5, 100, orthoMatrix, 0, 0, 800, 600);
+ }
+ });
+});
+
+describe('uiMath - Hit testing', () => {
+ bench('pointInWorldRect x10000', () => {
+ for (let i = 0; i < 10000; i++) {
+ pointInWorldRect(
+ 50 + (i % 100), 50,
+ 100, 100, 200, 150,
+ 0.5, 0.5,
+ );
+ }
+ });
+
+ bench('pointInOBB x10000', () => {
+ for (let i = 0; i < 10000; i++) {
+ pointInOBB(
+ 50 + (i % 100), 50,
+ 100, 100, 200, 150,
+ 0.5, 0.5,
+ 0.3826834, 0.9238795,
+ );
+ }
+ });
+
+ bench('pointInWorldRect vs pointInOBB ratio (AABB, no rotation)', () => {
+ for (let i = 0; i < 10000; i++) {
+ pointInOBB(
+ 50 + (i % 100), 50,
+ 100, 100, 200, 150,
+ 0.5, 0.5,
+ 0, 1,
+ );
+ }
+ });
+});
+
+describe('uiMath - Rect intersection', () => {
+ bench('intersectRects x10000', () => {
+ for (let i = 0; i < 10000; i++) {
+ intersectRects(
+ { x: 0, y: 0, w: 800, h: 600 },
+ { x: 100 + (i % 50), y: 100, w: 200, h: 150 },
+ );
+ }
+ });
+});
+
+describe('uiMath - InvVP cache', () => {
+ const cache = createInvVPCache();
+
+ bench('cache hit (same VP) x1000', () => {
+ cache.update(orthoMatrix);
+ for (let i = 0; i < 1000; i++) {
+ cache.update(orthoMatrix);
+ cache.getInverse(orthoMatrix);
+ }
+ });
+
+ bench('cache miss (changing VP) x100', () => {
+ const vp = new Float32Array(orthoMatrix);
+ for (let i = 0; i < 100; i++) {
+ vp[0] = 0.002 + i * 0.0001;
+ cache.update(vp);
+ cache.getInverse(vp);
+ }
+ });
+});
diff --git a/sdk/benchmarks/world.bench.ts b/sdk/benchmarks/world.bench.ts
new file mode 100644
index 000000000..2159e2ab9
--- /dev/null
+++ b/sdk/benchmarks/world.bench.ts
@@ -0,0 +1,130 @@
+import { bench, describe } from 'vitest';
+import { World } from '../src/world';
+import { defineComponent } from '../src/component';
+import { Entity } from '../src/types';
+
+const Position = defineComponent('BenchPosition', { x: 0, y: 0 });
+const Velocity = defineComponent('BenchVelocity', { vx: 0, vy: 0 });
+const Health = defineComponent('BenchHealth', { hp: 100, maxHp: 100 });
+const Tag = defineComponent('BenchTag', {});
+
+function createWorld(count: number, withVelocity = false, withHealth = false): { world: World; entities: Entity[] } {
+ const world = new World();
+ const entities: Entity[] = [];
+ for (let i = 0; i < count; i++) {
+ const e = world.spawn();
+ world.insert(e, Position, { x: i, y: i });
+ if (withVelocity) world.insert(e, Velocity, { vx: 1, vy: 1 });
+ if (withHealth && i % 2 === 0) world.insert(e, Health);
+ entities.push(e);
+ }
+ return { world, entities };
+}
+
+describe('World - Entity lifecycle', () => {
+ bench('spawn single entity', () => {
+ const world = new World();
+ world.spawn();
+ });
+
+ bench('spawn + despawn single entity', () => {
+ const world = new World();
+ const e = world.spawn();
+ world.despawn(e);
+ });
+
+ bench('spawn 1000 entities', () => {
+ const world = new World();
+ for (let i = 0; i < 1000; i++) {
+ world.spawn();
+ }
+ });
+});
+
+describe('World - Component insert', () => {
+ bench('insert 1 component to 1000 entities', () => {
+ const world = new World();
+ const entities: Entity[] = [];
+ for (let i = 0; i < 1000; i++) entities.push(world.spawn());
+ for (const e of entities) {
+ world.insert(e, Position, { x: 1, y: 2 });
+ }
+ });
+
+ bench('insert 3 components to 1000 entities', () => {
+ const world = new World();
+ const entities: Entity[] = [];
+ for (let i = 0; i < 1000; i++) entities.push(world.spawn());
+ for (const e of entities) {
+ world.insert(e, Position, { x: 1, y: 2 });
+ world.insert(e, Velocity, { vx: 3, vy: 4 });
+ world.insert(e, Health);
+ }
+ });
+});
+
+describe('World - Component access (1000 entities)', () => {
+ const { world, entities } = createWorld(1000, true, true);
+
+ bench('get x1000', () => {
+ for (const e of entities) world.get(e, Position);
+ });
+
+ bench('has x1000', () => {
+ for (const e of entities) world.has(e, Position);
+ });
+
+ bench('tryGet x1000', () => {
+ for (const e of entities) world.tryGet(e, Health);
+ });
+
+ bench('set x1000', () => {
+ for (const e of entities) world.set(e, Position, { x: 99, y: 99 });
+ });
+});
+
+describe('World - Query (5000 entities)', () => {
+ const world = new World();
+ for (let i = 0; i < 5000; i++) {
+ const e = world.spawn();
+ world.insert(e, Position, { x: i, y: i });
+ if (i % 2 === 0) world.insert(e, Velocity, { vx: 1, vy: 1 });
+ if (i % 3 === 0) world.insert(e, Health);
+ if (i % 5 === 0) world.insert(e, Tag);
+ }
+
+ bench('query 1 component (5000 match)', () => {
+ world.resetQueryPool();
+ world.getEntitiesWithComponents([Position]);
+ });
+
+ bench('query 2 components (2500 match)', () => {
+ world.resetQueryPool();
+ world.getEntitiesWithComponents([Position, Velocity]);
+ });
+
+ bench('query with filter (without)', () => {
+ world.resetQueryPool();
+ world.getEntitiesWithComponents([Position], [], [Health]);
+ });
+
+ bench('query cache hit (2nd call same version)', () => {
+ world.resetQueryPool();
+ world.getEntitiesWithComponents([Position, Velocity]);
+ world.resetQueryPool();
+ world.getEntitiesWithComponents([Position, Velocity]);
+ });
+});
+
+describe('World - Change detection (1000 entities)', () => {
+ const { world, entities } = createWorld(1000);
+ world.advanceTick();
+
+ bench('isAddedSince x1000', () => {
+ for (const e of entities) world.isAddedSince(e, Position, 0);
+ });
+
+ bench('isChangedSince x1000', () => {
+ for (const e of entities) world.isChangedSince(e, Position, 0);
+ });
+});
diff --git a/sdk/package.json b/sdk/package.json
index e58dfda77..8c06d910b 100644
--- a/sdk/package.json
+++ b/sdk/package.json
@@ -45,7 +45,9 @@
"prepublishOnly": "npm run clean && npm run build",
"test": "vitest run",
"test:watch": "vitest",
- "test:ui": "vitest --ui"
+ "test:ui": "vitest --ui",
+ "bench": "vitest bench",
+ "bench:watch": "vitest bench --watch"
},
"keywords": [
"game-engine",
diff --git a/sdk/src/component.ts b/sdk/src/component.ts
index b1812562d..f1a8a5214 100644
--- a/sdk/src/component.ts
+++ b/sdk/src/component.ts
@@ -37,12 +37,25 @@ function deepClone<T>(value: T): T {
let componentCounter = 0;
-function hasNestedObjects(obj: object): boolean {
+function classifyKeys(obj: object): { flatKeys: string[]; objectKeys: string[]; arrayKeys: string[] } | null {
+ const flatKeys: string[] = [];
+ const objectKeys: string[] = [];
+ const arrayKeys: string[] = [];
+ let hasNested = false;
for (const key in obj) {
const val = (obj as Record<string, unknown>)[key];
- if (val !== null && typeof val === 'object') return true;
+ if (val !== null && typeof val === 'object') {
+ hasNested = true;
+ if (Array.isArray(val)) {
+ arrayKeys.push(key);
+ } else {
+ objectKeys.push(key);
+ }
+ } else {
+ flatKeys.push(key);
+ }
}
- return false;
+ return hasNested ? { flatKeys, objectKeys, arrayKeys } : null;
}
function createComponentDef<T extends object>(
@@ -50,15 +63,20 @@ function createComponentDef<T extends object>(
defaults: T
): ComponentDef<T> {
const id = ++componentCounter;
- const needsDeepClone = hasNestedObjects(defaults);
+ const keyInfo = classifyKeys(defaults);
+ const defaultsRec = defaults as Record<string, unknown>;
return {
_id: Symbol(`Component_${id}_${name}`),
_name: name,
_default: defaults,
_builtin: false as const,
create(data?: Partial<T>): T {
- if (needsDeepClone) {
- return data ? { ...deepClone(defaults), ...data } : deepClone(defaults);
+ if (keyInfo) {
+ const result = { ...defaultsRec };
+ for (const k of keyInfo.objectKeys) result[k] = { ...(defaultsRec[k] as object) };
+ for (const k of keyInfo.arrayKeys) result[k] = (defaultsRec[k] as unknown[]).slice();
+ if (data) Object.assign(result, data);
+ return result as T;
}
return data ? { ...defaults, ...data } : { ...defaults };
}
@@ -133,6 +151,7 @@ export interface BuiltinComponentDef<T> {
readonly _cppName: string;
readonly _builtin: true;
readonly _default: T;
+ readonly _colorKeys: readonly string[];
}
// =============================================================================
@@ -159,13 +178,29 @@ export function getComponent(name: string): AnyComponentDef | undefined {
return componentRegistry.get(name) ?? getUserComponent(name);
}
+function detectColorKeys(defaults: unknown): readonly string[] {
+ if (defaults === null || typeof defaults !== 'object') return [];
+ const keys: string[] = [];
+ for (const key of Object.keys(defaults as Record<string, unknown>)) {
+ const val = (defaults as Record<string, unknown>)[key];
+ if (val !== null && typeof val === 'object' && !Array.isArray(val)) {
+ const rec = val as Record<string, unknown>;
+ if ('r' in rec && 'g' in rec && 'b' in rec && 'a' in rec) {
+ keys.push(key);
+ }
+ }
+ }
+ return keys;
+}
+
export function defineBuiltin<T>(name: string, defaults: T): BuiltinComponentDef<T> {
const def: BuiltinComponentDef<T> = {
_id: Symbol(`Builtin_${name}`),
_name: name,
_cppName: name,
_builtin: true,
- _default: defaults
+ _default: defaults,
+ _colorKeys: detectColorKeys(defaults),
};
componentRegistry.set(name, def);
return def;
diff --git a/sdk/src/query.ts b/sdk/src/query.ts
index 27cbda0aa..9a1096330 100644
--- a/sdk/src/query.ts
+++ b/sdk/src/query.ts
@@ -185,6 +185,12 @@ export class QueryInstance<C extends readonly QueryArg[]> implements Iterable<Qu
descriptor._with,
descriptor._without,
);
+ for (const f of descriptor._addedFilters) {
+ world.enableChangeTracking(f.component);
+ }
+ for (const f of descriptor._changedFilters) {
+ world.enableChangeTracking(f.component);
+ }
}
private passesChangeFilters_(entity: Entity): boolean {
@@ -200,7 +206,7 @@ export class QueryInstance<C extends readonly QueryArg[]> implements Iterable<Qu
return true;
}
- *[Symbol.iterator](): Iterator<QueryResult<C>> {
+ [Symbol.iterator](): Iterator<QueryResult<C>> {
const { _mutIndices } = this.descriptor_;
const actualComponents = this.actualComponents_;
const entities = this.world_.getEntitiesWithComponents(
@@ -215,46 +221,70 @@ export class QueryInstance<C extends readonly QueryArg[]> implements Iterable<Qu
const result = this.result_;
const mutData = this.mutData_;
const mutCount = mutData.length;
+ const world = this.world_;
+ const self = this;
+ let idx = 0;
let prevEntity: Entity | null = null;
+ let started = false;
+ let done = false;
- this.world_.beginIteration();
- try {
- for (const entity of entities) {
- if (hasChangeFilters && !this.passesChangeFilters_(entity)) {
- continue;
+ const finalize = () => {
+ if (done) return;
+ done = true;
+ world.endIteration();
+ if (prevEntity !== null && hasMut) {
+ for (let i = 0; i < mutCount; i++) {
+ const mut = mutData[i];
+ world.set(prevEntity, mut.component, mut.data);
}
+ }
+ };
- if (prevEntity !== null && hasMut) {
- for (let i = 0; i < mutCount; i++) {
- const mut = mutData[i];
- this.world_.set(prevEntity, mut.component, mut.data);
- }
+ return {
+ next(): IteratorResult<QueryResult<C>> {
+ if (!started) {
+ started = true;
+ world.beginIteration();
}
- result[0] = entity;
- for (let i = 0; i < compCount; i++) {
- result[i + 1] = this.world_.get(entity, actualComponents[i]);
- }
+ while (idx < entities.length) {
+ const entity = entities[idx++];
- if (hasMut) {
- for (let i = 0; i < mutCount; i++) {
- mutData[i].data = result[_mutIndices[i] + 1] as Record<string, unknown>;
+ if (hasChangeFilters && !self.passesChangeFilters_(entity)) {
+ continue;
}
- prevEntity = entity;
- }
- yield result as QueryResult<C>;
- }
- } finally {
- this.world_.endIteration();
- if (prevEntity !== null && hasMut) {
- for (let i = 0; i < mutCount; i++) {
- const mut = mutData[i];
- this.world_.set(prevEntity, mut.component, mut.data);
+ if (prevEntity !== null && hasMut) {
+ for (let i = 0; i < mutCount; i++) {
+ const mut = mutData[i];
+ world.set(prevEntity, mut.component, mut.data);
+ }
+ }
+
+ result[0] = entity;
+ for (let i = 0; i < compCount; i++) {
+ result[i + 1] = world.get(entity, actualComponents[i]);
+ }
+
+ if (hasMut) {
+ for (let i = 0; i < mutCount; i++) {
+ mutData[i].data = result[_mutIndices[i] + 1] as Record<string, unknown>;
+ }
+ prevEntity = entity;
+ }
+
+ return { value: result as QueryResult<C>, done: false };
}
- }
- }
+
+ finalize();
+ return { value: undefined as unknown as QueryResult<C>, done: true };
+ },
+ return(): IteratorResult<QueryResult<C>> {
+ finalize();
+ return { value: undefined as unknown as QueryResult<C>, done: true };
+ },
+ };
}
forEach(callback: (entity: Entity, ...components: ComponentsData<C>) => void): void {
@@ -311,6 +341,7 @@ export class RemovedQueryInstance<T extends AnyComponentDef> implements Iterable
this.world_ = world;
this.component_ = component;
this.lastRunTick_ = lastRunTick;
+ world.enableChangeTracking(component);
}
*[Symbol.iterator](): Iterator<Entity> {
diff --git a/sdk/src/ui/uiMath.ts b/sdk/src/ui/uiMath.ts
index cbbe176fe..fa10770ff 100644
--- a/sdk/src/ui/uiMath.ts
+++ b/sdk/src/ui/uiMath.ts
@@ -137,6 +137,10 @@ export function pointInOBB(
pivotX: number, pivotY: number,
rotationZ: number, rotationW: number,
): boolean {
+ if (rotationZ === 0 && rotationW === 1) {
+ return pointInWorldRect(px, py, worldX, worldY, worldW, worldH, pivotX, pivotY);
+ }
+
const angle = quaternionToAngle2D(rotationZ, rotationW);
const sin = Math.sin(-angle);
const cos = Math.cos(-angle);
diff --git a/sdk/src/world.ts b/sdk/src/world.ts
index 813ed0f7d..aba76d81c 100644
--- a/sdk/src/world.ts
+++ b/sdk/src/world.ts
@@ -11,74 +11,29 @@ import { handleWasmError } from './wasmError';
function convertFromWasm(
obj: Record<string, unknown>,
- defaults: Record<string, unknown>,
+ colorKeys: readonly string[],
): Record<string, unknown> {
- let needsConversion = false;
- for (const key of Object.keys(defaults)) {
- const def = defaults[key];
- if (def !== null && def !== undefined && typeof def === 'object' && !Array.isArray(def)) {
- const defRec = def as Record<string, unknown>;
- if ('r' in defRec && 'g' in defRec && 'b' in defRec && 'a' in defRec) {
- const val = obj[key];
- if (val !== null && val !== undefined && typeof val === 'object') {
- const valRec = val as Record<string, unknown>;
- if ('x' in valRec && !('r' in valRec)) {
- needsConversion = true;
- break;
- }
- }
- }
- }
- }
- if (!needsConversion) return obj;
-
- const result: Record<string, unknown> = {};
- for (const key of Object.keys(obj)) {
- const val = obj[key];
- const def = defaults[key];
- if (val !== null && val !== undefined && typeof val === 'object' && !Array.isArray(val) &&
- def !== null && def !== undefined && typeof def === 'object' && !Array.isArray(def)) {
- const valRec = val as Record<string, unknown>;
- const defRec = def as Record<string, unknown>;
- if ('r' in defRec && 'g' in defRec && 'b' in defRec && 'a' in defRec &&
- 'x' in valRec && !('r' in valRec)) {
- result[key] = { r: valRec.x, g: valRec.y, b: valRec.z, a: valRec.w };
- } else {
- result[key] = val;
- }
- } else {
- result[key] = val;
+ if (colorKeys.length === 0) return obj;
+ const result: Record<string, unknown> = { ...obj };
+ for (const key of colorKeys) {
+ const val = result[key] as Record<string, unknown> | null | undefined;
+ if (val && typeof val === 'object') {
+ result[key] = { r: val.x, g: val.y, b: val.z, a: val.w };
}
}
return result;
}
-function convertForWasm(obj: Record<string, unknown>): Record<string, unknown> {
- let needsConversion = false;
- for (const key of Object.keys(obj)) {
- const val = obj[key];
- if (val !== null && val !== undefined && typeof val === 'object' && !Array.isArray(val)) {
- const rec = val as Record<string, unknown>;
- if ('r' in rec && 'g' in rec && 'b' in rec && 'a' in rec && !('x' in rec)) {
- needsConversion = true;
- break;
- }
- }
- }
- if (!needsConversion) return obj;
-
- const result: Record<string, unknown> = {};
- for (const key of Object.keys(obj)) {
- const val = obj[key];
- if (val !== null && val !== undefined && typeof val === 'object' && !Array.isArray(val)) {
- const rec = val as Record<string, unknown>;
- if ('r' in rec && 'g' in rec && 'b' in rec && 'a' in rec && !('x' in rec)) {
- result[key] = { x: rec.r, y: rec.g, z: rec.b, w: rec.a };
- } else {
- result[key] = val;
- }
- } else {
- result[key] = val;
+function convertForWasm(
+ obj: Record<string, unknown>,
+ colorKeys: readonly string[],
+): Record<string, unknown> {
+ if (colorKeys.length === 0) return obj;
+ const result: Record<string, unknown> = { ...obj };
+ for (const key of colorKeys) {
+ const val = result[key] as Record<string, unknown> | null | undefined;
+ if (val && typeof val === 'object') {
+ result[key] = { x: val.r, y: val.g, z: val.b, w: val.a };
}
}
return result;
@@ -158,6 +113,7 @@ export class World {
private componentAddedTicks_ = new Map<symbol, Map<Entity, number>>();
private componentChangedTicks_ = new Map<symbol, Map<Entity, number>>();
private componentRemovedBuffer_ = new Map<symbol, Array<{ entity: Entity; tick: number }>>();
+ private trackedComponents_ = new Set<symbol>();
connectCpp(cppRegistry: CppRegistry, module?: ESEngineModule): void {
this.cppRegistry_ = cppRegistry;
@@ -362,7 +318,7 @@ export class World {
}
this.getBuiltinMethods(component._cppName).add(
entity,
- convertForWasm(wasmData)
+ convertForWasm(wasmData, component._colorKeys)
);
} catch (e) {
handleWasmError(e, `set(${component._name}, entity=${entity})`);
@@ -478,7 +434,7 @@ export class World {
try {
const methods = this.getBuiltinMethods(component._cppName);
isNew = !methods.has(entity);
- methods.add(entity, convertForWasm(merged as Record<string, unknown>));
+ methods.add(entity, convertForWasm(merged as Record<string, unknown>, component._colorKeys));
} catch (e) {
handleWasmError(e, `insertBuiltin(${component._name}, entity=${entity})`);
}
@@ -500,7 +456,7 @@ export class World {
const raw = this.getBuiltinMethods(component._cppName).get(entity);
return convertFromWasm(
raw as Record<string, unknown>,
- component._default as Record<string, unknown>,
+ component._colorKeys,
) as T;
} catch (e) {
handleWasmError(e, `getBuiltin(${component._name}, entity=${entity})`);
@@ -735,6 +691,10 @@ export class World {
return this.worldTick_;
}
+ enableChangeTracking(component: AnyComponentDef): void {
+ this.trackedComponents_.add(component._id);
+ }
+
isAddedSince(entity: Entity, component: AnyComponentDef, sinceTick: number): boolean {
const map = this.componentAddedTicks_.get(component._id);
if (!map) return false;
@@ -777,6 +737,7 @@ export class World {
}
private recordAddedTick_(component: AnyComponentDef, entity: Entity): void {
+ if (!this.trackedComponents_.has(component._id)) return;
let map = this.componentAddedTicks_.get(component._id);
if (!map) {
map = new Map();
@@ -786,6 +747,7 @@ export class World {
}
private recordChangedTick_(component: AnyComponentDef, entity: Entity): void {
+ if (!this.trackedComponents_.has(component._id)) return;
let map = this.componentChangedTicks_.get(component._id);
if (!map) {
map = new Map();
@@ -795,6 +757,7 @@ export class World {
}
private recordRemovedTick_(component: AnyComponentDef, entity: Entity): void {
+ if (!this.trackedComponents_.has(component._id)) return;
let buffer = this.componentRemovedBuffer_.get(component._id);
if (!buffer) {
buffer = [];
diff --git a/sdk/tests/query.test.ts b/sdk/tests/query.test.ts
index 8b64a0e2c..584b2dc37 100644
--- a/sdk/tests/query.test.ts
+++ b/sdk/tests/query.test.ts
@@ -360,6 +360,7 @@ describe('Query System', () => {
describe('Added query filtering', () => {
it('should only return entities added since last run tick', () => {
+ world.enableChangeTracking(Position);
const e1 = world.spawn();
world.insert(e1, Position, { x: 1, y: 1 });
@@ -375,6 +376,7 @@ describe('Query System', () => {
describe('Changed query filtering', () => {
it('should only return entities changed since last run tick', () => {
+ world.enableChangeTracking(Position);
const e1 = world.spawn();
world.insert(e1, Position, { x: 1, y: 1 });
@@ -517,6 +519,7 @@ describe('Query System', () => {
});
it('should iterate over removed entities', () => {
+ world.enableChangeTracking(Position);
const e1 = world.spawn();
world.insert(e1, Position, { x: 1, y: 1 });
world.remove(e1, Position);
@@ -527,6 +530,7 @@ describe('Query System', () => {
});
it('should report isEmpty correctly', () => {
+ world.enableChangeTracking(Position);
const instance = new RemovedQueryInstance(world, Position, Infinity);
expect(instance.isEmpty()).toBe(true);
@@ -539,6 +543,7 @@ describe('Query System', () => {
});
it('should be iterable', () => {
+ world.enableChangeTracking(Position);
const e1 = world.spawn();
world.insert(e1, Position, { x: 1, y: 1 });
world.remove(e1, Position);
diff --git a/sdk/tests/system.test.ts b/sdk/tests/system.test.ts
index b675d8b16..8b1525a68 100644
--- a/sdk/tests/system.test.ts
+++ b/sdk/tests/system.test.ts
@@ -56,6 +56,7 @@ function createMockWorld() {
isAddedSince: vi.fn(() => false),
isChangedSince: vi.fn(() => false),
getRemovedEntitiesSince: vi.fn(() => []),
+ enableChangeTracking: vi.fn(),
};
return { world: world as unknown as World, entities, worldTick };
diff --git a/sdk/tests/world.test.ts b/sdk/tests/world.test.ts
index c075e6a2d..942cb687b 100644
--- a/sdk/tests/world.test.ts
+++ b/sdk/tests/world.test.ts
@@ -526,6 +526,7 @@ describe('World', () => {
it('isAddedSince should detect newly added components', () => {
const w = new World();
+ w.enableChangeTracking(Position);
const e = w.spawn();
w.advanceTick();
w.insert(e, Position, { x: 1, y: 1 });
@@ -541,6 +542,7 @@ describe('World', () => {
it('isChangedSince should detect changed components', () => {
const w = new World();
+ w.enableChangeTracking(Position);
const e = w.spawn();
w.insert(e, Position, { x: 0, y: 0 });
w.advanceTick();
@@ -556,6 +558,7 @@ describe('World', () => {
it('getRemovedEntitiesSince should detect removed components', () => {
const w = new World();
+ w.enableChangeTracking(Position);
const e = w.spawn();
w.insert(e, Position, { x: 0, y: 0 });
w.advanceTick();
@@ -571,6 +574,7 @@ describe('World', () => {
it('cleanRemovedBuffer should remove old entries', () => {
const w = new World();
+ w.enableChangeTracking(Position);
const e1 = w.spawn();
w.insert(e1, Position, { x: 0, y: 0 });
w.remove(e1, Position);
@@ -590,6 +594,7 @@ describe('World', () => {
it('cleanRemovedBuffer should delete empty buffers', () => {
const w = new World();
+ w.enableChangeTracking(Position);
const e = w.spawn();
w.insert(e, Position, { x: 0, y: 0 });
w.remove(e, Position);
@@ -600,6 +605,8 @@ describe('World', () => {
it('despawn should record removed ticks for all components', () => {
const w = new World();
+ w.enableChangeTracking(Position);
+ w.enableChangeTracking(Velocity);
const e = w.spawn();
w.insert(e, Position, { x: 0, y: 0 });
w.insert(e, Velocity, { dx: 1, dy: 1 });
diff --git a/sdk/vitest.config.ts b/sdk/vitest.config.ts
index 1c96afbb4..c4a8a1890 100644
--- a/sdk/vitest.config.ts
+++ b/sdk/vitest.config.ts
@@ -7,6 +7,9 @@ export default defineConfig({
environment: 'happy-dom',
setupFiles: ['tests/setup.ts'],
include: ['tests/**/*.test.ts'],
+ benchmark: {
+ include: ['benchmarks/**/*.bench.ts'],
+ },
coverage: {
provider: 'v8',
reporter: ['text', 'json', 'html'],