@daneren2005/shared-memory-ecs 1.8.1 → 1.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -20,11 +20,13 @@ export interface PerformanceStats {
20
20
  }
21
21
  export interface PerformanceTimingOptions {
22
22
  ticksBetweenUpdates?: number;
23
+ autoUpdate?: boolean;
23
24
  }
24
25
  export default class PerformanceTiming<C extends ComponentMap = ComponentMap> extends EventEmitter {
25
26
  world: BaseWorld<ComponentDefinitionMap, C>;
26
27
  ticksBetweenUpdates: number;
27
28
  stats: PerformanceStats;
29
+ private readonly autoUpdate;
28
30
  private ticks;
29
31
  private updateStart;
30
32
  private updateTimes;
@@ -40,5 +42,5 @@ export default class PerformanceTiming<C extends ComponentMap = ComponentMap> ex
40
42
  private onSystemRemoved;
41
43
  private trackSystem;
42
44
  private untrackSystem;
43
- private recalculate;
45
+ flush(): PerformanceStats;
44
46
  }
@@ -0,0 +1,53 @@
1
+ import type { ComponentMap } from '../component-definition';
2
+ import type System from '../systems/system';
3
+ import type { Scheduler, SchedulerContext, SchedulerEffects, SchedulerUpdateResult } from './scheduler';
4
+ export interface ConflictSchedule<C extends ComponentMap = ComponentMap> {
5
+ readonly order: ReadonlyArray<System<C>>;
6
+ readonly batches: ReadonlyArray<ReadonlyArray<System<C>>>;
7
+ }
8
+ export default class ConflictScheduler<C extends ComponentMap = ComponentMap> implements Scheduler<C> {
9
+ private compiled;
10
+ private registeredSystems;
11
+ private access;
12
+ private nodes;
13
+ private tails;
14
+ private frontiers;
15
+ private creators;
16
+ private creationReaders;
17
+ private exclusiveTail;
18
+ private running;
19
+ private ready;
20
+ private readyIndex;
21
+ private gameTime;
22
+ private pumping;
23
+ private resumeQueued;
24
+ private continuationTimer;
25
+ private generation;
26
+ private publications;
27
+ private publicationReady;
28
+ private publishing;
29
+ get schedule(): ConflictSchedule<C>;
30
+ rebuild(context: SchedulerContext<C>): ConflictSchedule<C>;
31
+ systemAdded(context: SchedulerContext<C>): void;
32
+ systemRemoved(context: SchedulerContext<C>): void;
33
+ update(context: SchedulerContext<C>, elapsedTime: number): SchedulerUpdateResult;
34
+ runCompleted(context: SchedulerContext<C>, system: System<C>): void;
35
+ pause(context: SchedulerContext<C>): void;
36
+ private scheduleContinuation;
37
+ private isSliced;
38
+ reset(): void;
39
+ beforeClear(): void;
40
+ prepareEffects(context: SchedulerContext<C>, system: System<C>): (effects: SchedulerEffects) => void;
41
+ private publish;
42
+ destroy(): void;
43
+ private refreshMembership;
44
+ private pump;
45
+ private enqueue;
46
+ private frontier;
47
+ private complete;
48
+ private dispatch;
49
+ private prepare;
50
+ private dispatchAllowed;
51
+ private observesCreation;
52
+ private conflicts;
53
+ }
@@ -0,0 +1,5 @@
1
+ import type { ComponentMap } from '../component-definition';
2
+ import type { Scheduler, SchedulerContext, SchedulerUpdateResult } from './scheduler';
3
+ export default class DefaultScheduler<C extends ComponentMap = ComponentMap> implements Scheduler<C> {
4
+ update(context: SchedulerContext<C>, elapsedTime: number): SchedulerUpdateResult;
5
+ }
@@ -0,0 +1,28 @@
1
+ import type { EventEmitter } from 'eventemitter3';
2
+ import type { ComponentMap } from '../component-definition';
3
+ import type System from '../systems/system';
4
+ export interface SchedulerContext<C extends ComponentMap = ComponentMap> extends Pick<EventEmitter, 'emit'> {
5
+ readonly systems: Array<System<C>>;
6
+ readonly gameTime?: number;
7
+ readonly paused?: boolean;
8
+ readonly dispatchAllowed?: boolean;
9
+ prepareForSystemDispatch?(): boolean;
10
+ }
11
+ export interface SchedulerUpdateResult {
12
+ lastSystemError?: Error | null;
13
+ }
14
+ export interface SchedulerEffects {
15
+ apply(): void;
16
+ discard(): void;
17
+ }
18
+ export interface Scheduler<C extends ComponentMap = ComponentMap> {
19
+ update(context: SchedulerContext<C>, elapsedTime: number): SchedulerUpdateResult;
20
+ pause?(context: SchedulerContext<C>): void;
21
+ systemAdded?(context: SchedulerContext<C>, system: System<C>): void;
22
+ systemRemoved?(context: SchedulerContext<C>, system: System<C>): void;
23
+ reset?(context: SchedulerContext<C>): void;
24
+ destroy?(context: SchedulerContext<C>): void;
25
+ runCompleted?(context: SchedulerContext<C>, system: System<C>): void;
26
+ prepareEffects?(context: SchedulerContext<C>, system: System<C>): (effects: SchedulerEffects) => void;
27
+ beforeClear?(context: SchedulerContext<C>): void;
28
+ }
@@ -19,8 +19,11 @@ export default abstract class EntitySystem<C extends ComponentMap, T extends Bas
19
19
  checkAddEntity(entity: BaseEntity<C>): boolean;
20
20
  removeEntity(entity: BaseEntity<C>): void;
21
21
  shouldRun(): boolean;
22
+ get creationReadComponents(): ReadonlyArray<PropertyKey> | undefined;
23
+ get creationReadQueries(): ReadonlyArray<ReadonlyArray<PropertyKey>> | undefined;
24
+ get readComponents(): ReadonlyArray<PropertyKey> | undefined;
22
25
  }
23
- export interface EntitySystemConfig<C extends ComponentMap> extends IterableSystemConfig {
26
+ export interface EntitySystemConfig<C extends ComponentMap> extends IterableSystemConfig<C> {
24
27
  components?: Array<keyof C>;
25
28
  updateEntityOnAdd?: boolean;
26
29
  }
@@ -12,9 +12,14 @@ export default abstract class EntityWorkerSystem<C extends ComponentMap, T exten
12
12
  isWorkerThread: boolean;
13
13
  private initialized;
14
14
  private initPromise;
15
+ private initError;
15
16
  private loadingPromise;
16
17
  private runCompletePromise;
17
18
  private isRunning;
19
+ private workPass;
20
+ private timingBatch;
21
+ private pendingEffects;
22
+ private completeEffects;
18
23
  private generation;
19
24
  protected queryEntities: {
20
25
  [key: string]: Map<number, BaseEntity<C>>;
@@ -23,12 +28,19 @@ export default abstract class EntityWorkerSystem<C extends ComponentMap, T exten
23
28
  addDataToWorld?(world: W): void;
24
29
  constructor(world: BaseWorld<ComponentDefinitionMap, C>, options: EntityWorkerSystemConfig<C, T, W, D>);
25
30
  private initWorker;
31
+ private applyWorkerEffects;
32
+ private discardWorkerAllocations;
26
33
  init(): Promise<void> | void;
27
34
  finishLoading(): Promise<void>;
28
35
  clear(): void;
29
36
  update(elapsedTime: number): boolean;
30
37
  protected onRunFinished(): void;
31
38
  isCurrentlyRunning(): boolean;
39
+ get readComponents(): ReadonlyArray<PropertyKey>;
40
+ get requiresExclusiveScheduling(): boolean;
41
+ get createdComponents(): ReadonlyArray<PropertyKey>;
42
+ get creationReadComponents(): ReadonlyArray<PropertyKey>;
43
+ get creationReadQueries(): ReadonlyArray<ReadonlyArray<PropertyKey>> | undefined;
32
44
  waitForRunToComplete(): void | Promise<void>;
33
45
  run(elapsedTime: number): void;
34
46
  private buildQueryDelta;
@@ -62,10 +74,11 @@ type EntityUpdateFunctionImpl<C extends ComponentMap, T extends EntityUpdateComp
62
74
  export type EntityUpdateFunction<C extends ComponentMap, T extends EntityUpdateComponents<C>, W extends EntityWorkerSystemWorld = EntityWorkerSystemWorld, D = unknown> = EntityUpdateFunctionImpl<C, T, W> & {
63
75
  queryChanged?: EntityQueryChangedFunction<C, W>;
64
76
  preRun?: EntityUpdatePreRunFunction<C, T, W>;
77
+ preBatch?: EntityUpdatePreRunFunction<C, T, W>;
65
78
  entityRemoved?: EntityRemovedFunction<C, W>;
66
- init?: EntityUpdateInitFunction<W, D>;
79
+ init?: EntityUpdateInitFunction<W, D, C, T>;
67
80
  };
68
- export type EntityUpdateInitFunction<W extends EntityWorkerSystemWorld = EntityWorkerSystemWorld, D = unknown> = (data: D | undefined) => Partial<W> | void;
81
+ export type EntityUpdateInitFunction<W extends EntityWorkerSystemWorld = EntityWorkerSystemWorld, D = unknown, C extends ComponentMap = ComponentMap, T extends EntityUpdateComponents<C> = EntityUpdateComponents<C>> = (world: EntityWorkerSystemInitWorld, data: D | undefined, entities: Array<UpdateEntityConfigObject<T>>, queries: EntityQueryComponents<C>) => Partial<W> | void;
69
82
  export type EntityUpdatePreRunFunction<C extends ComponentMap, T extends EntityUpdateComponents<C>, W extends EntityWorkerSystemWorld = EntityWorkerSystemWorld> = (world: W, entities: Array<UpdateEntityConfigObject<T>>, queries: EntityQueryComponents<C>, callbacks: EntityWorkerSystemCallbacks<C>) => void;
70
83
  export type EntityQueryChangedFunction<C extends ComponentMap = ComponentMap, W extends EntityWorkerSystemWorld = EntityWorkerSystemWorld> = (world: W, queryName: string, delta: QueryDelta<EntityUpdateComponents<C>>, callbacks: EntityWorkerSystemCallbacks<C>) => void;
71
84
  export type EntityRemovedFunction<C extends ComponentMap = ComponentMap, W extends EntityWorkerSystemWorld = EntityWorkerSystemWorld> = (world: W, entityId: number, callbacks: EntityWorkerSystemCallbacks<C>) => void;
@@ -82,6 +95,7 @@ export interface WorkerAllocator {
82
95
  allocateEid(): number;
83
96
  allocateComponentBlock(name: string, values: Array<number>): number;
84
97
  }
98
+ export type EntityWorkerSystemInitWorld = Pick<EntityWorkerSystemWorld, 'gameTime' | 'getString' | 'heap'>;
85
99
  export interface EntityWorkerSystemWorld {
86
100
  gameTime: number;
87
101
  elapsedTime: number;
@@ -134,12 +148,13 @@ export interface EntityWorkerSystemQuery<C extends ComponentMap = ComponentMap>
134
148
  not?: Array<keyof C>;
135
149
  filter?: (entity: BaseEntity<C>) => boolean;
136
150
  }
137
- export interface EntityWorkerSystemConfig<C extends ComponentMap, T extends EntityUpdateComponents<C>, W extends EntityWorkerSystemWorld = EntityWorkerSystemWorld, D = unknown> extends SystemConfig, EntityWorkerSystemQuery<C> {
151
+ export interface EntityWorkerSystemConfig<C extends ComponentMap, T extends EntityUpdateComponents<C>, W extends EntityWorkerSystemWorld = EntityWorkerSystemWorld, D = unknown> extends SystemConfig<C>, EntityWorkerSystemQuery<C> {
152
+ workBatchSize?: number;
138
153
  updateFunction: EntityUpdateFunction<C, T, W, D>;
139
154
  getWorker: () => Worker;
140
155
  forceMainThread?: boolean;
141
156
  getInitData?: () => D;
142
- createsEntities?: boolean;
157
+ createsEntities?: boolean | ReadonlyArray<keyof C>;
143
158
  addsComponents?: boolean;
144
159
  queries?: {
145
160
  [key: string]: EntityWorkerSystemQuery<C>;
@@ -6,7 +6,7 @@ export default abstract class IterableSystem<C extends ComponentMap, T> extends
6
6
  remainingInstancesStartTime: number | null;
7
7
  iterationsPerCheck: number;
8
8
  maxMsPerFrame: number;
9
- constructor(world: BaseWorld<ComponentDefinitionMap, C>, options: IterableSystemConfig);
9
+ constructor(world: BaseWorld<ComponentDefinitionMap, C>, options: IterableSystemConfig<C>);
10
10
  clear(): void;
11
11
  update(elapsedTime: number): boolean;
12
12
  run(elapsedTime: number): void;
@@ -18,7 +18,7 @@ export default abstract class IterableSystem<C extends ComponentMap, T> extends
18
18
  abstract getIterables(): Array<T>;
19
19
  abstract updateIterable(iterable: T, elapsedTime: number): void;
20
20
  }
21
- export interface IterableSystemConfig extends SystemConfig {
21
+ export interface IterableSystemConfig<C extends ComponentMap = ComponentMap> extends SystemConfig<C> {
22
22
  iterationsPerCheck?: number;
23
23
  maxMsPerFrame?: number;
24
24
  }
@@ -8,11 +8,17 @@ export default abstract class System<C extends ComponentMap = ComponentMap> exte
8
8
  currentDelta: number;
9
9
  deltaBetweenRuns: number;
10
10
  firstRun: boolean;
11
- constructor(world: BaseWorld<ComponentDefinitionMap, C>, options?: SystemConfig);
11
+ readonly reads?: ReadonlyArray<PropertyKey>;
12
+ readonly writes?: ReadonlyArray<PropertyKey>;
13
+ private readonly exclusive;
14
+ private scheduledGameTime;
15
+ constructor(world: BaseWorld<ComponentDefinitionMap, C>, options?: SystemConfig<C>);
12
16
  init(): void | Promise<void>;
13
17
  clear(): void;
14
18
  finishLoading(): void | Promise<void>;
15
19
  addEntities(batch: EntityBatch<C>): void;
20
+ get gameTime(): number;
21
+ withGameTime<T>(gameTime: number, update: () => T): T;
16
22
  update(elapsedTime: number): boolean;
17
23
  abstract run(elapsedTime: number): void;
18
24
  protected onError(error: Error, context?: {
@@ -23,6 +29,11 @@ export default abstract class System<C extends ComponentMap = ComponentMap> exte
23
29
  isCurrentlyRunning(): boolean;
24
30
  waitForRunToComplete(): void | Promise<void>;
25
31
  shouldRun(): boolean;
32
+ get readComponents(): ReadonlyArray<PropertyKey> | undefined;
33
+ get requiresExclusiveScheduling(): boolean;
34
+ get createdComponents(): ReadonlyArray<PropertyKey>;
35
+ get creationReadComponents(): ReadonlyArray<PropertyKey> | undefined;
36
+ get creationReadQueries(): ReadonlyArray<ReadonlyArray<PropertyKey>> | undefined;
26
37
  destroy(): void;
27
38
  }
28
39
  export interface EntityBatch<C extends ComponentMap = ComponentMap> {
@@ -31,12 +42,15 @@ export interface EntityBatch<C extends ComponentMap = ComponentMap> {
31
42
  groups: Array<BaseEntity<C>>;
32
43
  }
33
44
  export declare function forEachInMatchingGroups<C extends ComponentMap>(batch: EntityBatch<C>, matchesGroup: (representative: BaseEntity<C>) => boolean, callback: (entity: BaseEntity<C>) => void): void;
34
- export interface SystemConfig {
45
+ export interface SystemConfig<C extends ComponentMap = ComponentMap> {
35
46
  name: string;
36
47
  deltaBetweenRuns?: number;
37
48
  firstRun?: boolean;
49
+ reads?: ReadonlyArray<keyof C>;
50
+ writes?: ReadonlyArray<keyof C>;
51
+ exclusive?: boolean;
38
52
  }
39
- export type SystemErrorPhase = 'queryChanged' | 'preRun' | 'update' | 'entityRemoved' | 'run' | 'died';
53
+ export type SystemErrorPhase = 'queryChanged' | 'preRun' | 'preBatch' | 'update' | 'entityRemoved' | 'run' | 'died';
40
54
  export interface SystemError {
41
55
  system: string;
42
56
  error: Error;
@@ -2,20 +2,20 @@ import type BaseWorld from '../world';
2
2
  import type { ComponentDefinitionMap, ComponentMap } from '../component-definition';
3
3
  import type { SystemConfig } from './system';
4
4
  import EntityWorkerSystem, { type EntityWorkerSystemQuery, type EntityWorkerSystemWorld, type EntityUpdateComponents } from './entity-worker-system';
5
- import { type WorkerSystemRunFunction } from './workers/create-system-worker';
5
+ import { type WorkerSystemInitFunction, type WorkerSystemRunFunction } from './workers/create-system-worker';
6
6
  export default class WorkerSystem<C extends ComponentMap, W extends EntityWorkerSystemWorld = EntityWorkerSystemWorld, D = unknown> extends EntityWorkerSystem<C, EntityUpdateComponents<C>, W, D> {
7
7
  constructor(world: BaseWorld<ComponentDefinitionMap, C>, options: WorkerSystemConfig<C, W, D>);
8
8
  protected get tracksMainQuery(): boolean;
9
9
  shouldRun(): boolean;
10
10
  }
11
- export interface WorkerSystemConfig<C extends ComponentMap, W extends EntityWorkerSystemWorld = EntityWorkerSystemWorld, D = unknown> extends SystemConfig {
11
+ export interface WorkerSystemConfig<C extends ComponentMap, W extends EntityWorkerSystemWorld = EntityWorkerSystemWorld, D = unknown> extends SystemConfig<C> {
12
12
  updateFunction: WorkerSystemRunFunction<C, W, D>;
13
13
  getWorker: () => Worker;
14
14
  forceMainThread?: boolean;
15
15
  getInitData?: () => D;
16
- createsEntities?: boolean;
16
+ createsEntities?: boolean | ReadonlyArray<keyof C>;
17
17
  queries?: {
18
18
  [key: string]: EntityWorkerSystemQuery<C>;
19
19
  };
20
20
  }
21
- export type { WorkerSystemRunFunction };
21
+ export type { WorkerSystemInitFunction, WorkerSystemRunFunction };
@@ -4,5 +4,6 @@ import type { EntityWorkerSystemWorld, EntityUpdateComponents, EntityUpdateFunct
4
4
  export interface EntitySystemWorkerScope {
5
5
  onmessage: ((e: MessageEvent) => void) | null;
6
6
  postMessage(message: EntitySystemWorkerMessage): void;
7
+ addEventListener?(type: 'unhandledrejection', listener: (event: PromiseRejectionEvent) => void): void;
7
8
  }
8
9
  export default function createEntitySystemWorker<C extends ComponentMap, T extends EntityUpdateComponents<C>, W extends EntityWorkerSystemWorld = EntityWorkerSystemWorld, D = unknown>(scope: EntitySystemWorkerScope, updateFunction: EntityUpdateFunction<C, T, W, D>, definitions?: ComponentDefinitionMap): void;
@@ -1,10 +1,11 @@
1
1
  import { type EntitySystemWorkerScope } from './create-entity-system-worker';
2
2
  import type { ComponentDefinitionMap, ComponentMap } from '../../component-definition';
3
- import type { EntityWorkerSystemCallbacks, EntityWorkerSystemWorld, EntityQueryComponents, EntityUpdateComponents, EntityUpdateFunction, EntityUpdateInitFunction, EntityRemovedFunction, EntityQueryChangedFunction } from '../entity-worker-system';
3
+ import type { EntityWorkerSystemCallbacks, EntityWorkerSystemInitWorld, EntityWorkerSystemWorld, EntityQueryComponents, EntityUpdateComponents, EntityUpdateFunction, EntityRemovedFunction, EntityQueryChangedFunction } from '../entity-worker-system';
4
4
  export type WorkerSystemRunFunction<C extends ComponentMap, W extends EntityWorkerSystemWorld = EntityWorkerSystemWorld, D = unknown> = ((world: W, queries: EntityQueryComponents<C>, callbacks: EntityWorkerSystemCallbacks<C>) => void) & {
5
- init?: EntityUpdateInitFunction<W, D>;
5
+ init?: WorkerSystemInitFunction<C, W, D>;
6
6
  queryChanged?: EntityQueryChangedFunction<C, W>;
7
7
  entityRemoved?: EntityRemovedFunction<C, W>;
8
8
  };
9
+ export type WorkerSystemInitFunction<C extends ComponentMap, W extends EntityWorkerSystemWorld = EntityWorkerSystemWorld, D = unknown> = (world: EntityWorkerSystemInitWorld, data: D | undefined, queries: EntityQueryComponents<C>) => Partial<W> | void;
9
10
  export declare function toEntityUpdateFunction<C extends ComponentMap, W extends EntityWorkerSystemWorld = EntityWorkerSystemWorld, D = unknown>(run: WorkerSystemRunFunction<C, W, D>): EntityUpdateFunction<C, EntityUpdateComponents<C>, W, D>;
10
11
  export default function createSystemWorker<C extends ComponentMap, W extends EntityWorkerSystemWorld = EntityWorkerSystemWorld, D = unknown>(scope: EntitySystemWorkerScope, runFunction: WorkerSystemRunFunction<C, W, D>, definitions?: ComponentDefinitionMap): void;
@@ -6,6 +6,7 @@ import type { EntityWorkerSystemWorld, EntityUpdateComponents, EntityUpdateFunct
6
6
  export default class EntitySystemWebWorker<C extends ComponentMap, T extends EntityUpdateComponents<C>, W extends EntityWorkerSystemWorld = EntityWorkerSystemWorld, D = unknown> extends WebWorker {
7
7
  private updateFunction;
8
8
  private entities;
9
+ private workState;
9
10
  private queryEntities;
10
11
  private worldExtension;
11
12
  private world;
@@ -13,6 +14,7 @@ export default class EntitySystemWebWorker<C extends ComponentMap, T extends Ent
13
14
  private createsEntities;
14
15
  private addsComponents;
15
16
  constructor(updateFunction: EntityUpdateFunction<C, T, W, D>, world: BaseWorld<ComponentDefinitionMap, C>, createsEntities?: boolean, addsComponents?: boolean);
17
+ private getString;
16
18
  postMessage(message: EntitySystemWorkerMessage<W, D>): void;
17
19
  onMessageTyped(message: EntitySystemWorkerMessage<W, D>): void;
18
20
  }
@@ -5,12 +5,17 @@ import type { WorkerEntityClassRegistry } from '../../entity-class';
5
5
  interface InitMessage {
6
6
  type: 'init';
7
7
  }
8
+ interface UnhandledRejectionMessage {
9
+ type: 'unhandled-rejection';
10
+ error: Error;
11
+ }
8
12
  interface InitCompleteMessage {
9
13
  type: 'init-complete';
10
14
  }
11
- interface LoadMessage<D = unknown> {
15
+ interface LoadMessage<D = unknown> extends LoadDeltas {
12
16
  type: 'load';
13
17
  data?: D;
18
+ gameTime: number;
14
19
  heap?: MemoryHeapMemory;
15
20
  sharedMemory?: WorldSharedMemory;
16
21
  factoryConfigs?: {
@@ -19,6 +24,12 @@ interface LoadMessage<D = unknown> {
19
24
  factoryClasses?: WorkerEntityClassRegistry;
20
25
  addsComponents?: boolean;
21
26
  }
27
+ export interface LoadDeltas {
28
+ entities: QueryDelta;
29
+ queries: {
30
+ [key: string]: QueryDelta;
31
+ };
32
+ }
22
33
  interface GrowBufferMessage {
23
34
  type: 'grow-buffer';
24
35
  buffer: GrowBufferData;
@@ -41,6 +52,12 @@ interface RunUpdateMessage<W extends EntityWorkerSystemWorld = EntityWorkerSyste
41
52
  queries: {
42
53
  [key: string]: QueryDelta;
43
54
  };
55
+ workBatch?: EntityWorkBatch;
56
+ }
57
+ export interface EntityWorkBatch {
58
+ entityIds: Array<number>;
59
+ first: boolean;
60
+ last: boolean;
44
61
  }
45
62
  export interface EntityEvent {
46
63
  entityId: number;
@@ -49,7 +66,7 @@ export interface EntityEvent {
49
66
  }
50
67
  export interface WorkerRunError {
51
68
  error: Error;
52
- phase: 'queryChanged' | 'preRun' | 'update' | 'entityRemoved';
69
+ phase: 'queryChanged' | 'preRun' | 'preBatch' | 'update' | 'entityRemoved';
53
70
  entityId?: number;
54
71
  }
55
72
  export type SystemEvents = {
@@ -64,6 +81,7 @@ interface EntityEventsMessage {
64
81
  created: Array<WorkerCreatedEntity>;
65
82
  componentChanges: Array<WorkerComponentChange>;
66
83
  errors: Array<WorkerRunError>;
84
+ workFailed?: boolean;
67
85
  }
68
- type EntitySystemWorkerMessage<W extends EntityWorkerSystemWorld = EntityWorkerSystemWorld, D = unknown> = InitMessage | InitCompleteMessage | LoadMessage<D> | LoadedMessage | ResetMessage | GrowBufferMessage | GrowBufferFromWorkerMessage | RunUpdateMessage<W> | EntityEventsMessage;
86
+ type EntitySystemWorkerMessage<W extends EntityWorkerSystemWorld = EntityWorkerSystemWorld, D = unknown> = InitMessage | InitCompleteMessage | UnhandledRejectionMessage | LoadMessage<D> | LoadedMessage | ResetMessage | GrowBufferMessage | GrowBufferFromWorkerMessage | RunUpdateMessage<W> | EntityEventsMessage;
69
87
  export default EntitySystemWorkerMessage;
@@ -0,0 +1,10 @@
1
+ import type { EntityUpdateComponents, EntityWorkerSystemWorld, QueryDelta, UpdateEntityConfigObject } from '../entity-worker-system';
2
+ import type { EntityWorkBatch } from './entity-system-worker-message';
3
+ export default class EntityWorkBatchState<T extends EntityUpdateComponents, W extends EntityWorkerSystemWorld> {
4
+ private world;
5
+ private entities;
6
+ getWorld(world: W, batch: EntityWorkBatch | undefined): W;
7
+ getEntities(entities: Array<UpdateEntityConfigObject<T>>, delta: QueryDelta<T>, batch: EntityWorkBatch | undefined): Array<UpdateEntityConfigObject<T>>;
8
+ finish(batch: EntityWorkBatch | undefined, failed: boolean): void;
9
+ clear(): void;
10
+ }
package/dist/worker.d.ts CHANGED
@@ -1,7 +1,7 @@
1
1
  export { default as createEntitySystemWorker } from './systems/workers/create-entity-system-worker';
2
2
  export type { EntitySystemWorkerScope } from './systems/workers/create-entity-system-worker';
3
3
  export { default as createSystemWorker } from './systems/workers/create-system-worker';
4
- export type { WorkerSystemRunFunction } from './systems/workers/create-system-worker';
4
+ export type { WorkerSystemRunFunction, WorkerSystemInitFunction } from './systems/workers/create-system-worker';
5
5
  export { default as createEntityWorker } from './actions/create-entity-worker';
6
6
  export { default as addComponentWorker } from './actions/add-component-worker';
7
7
  export { default as removeComponentWorker } from './actions/remove-component-worker';
@@ -9,4 +9,4 @@ export { default as killEntityWorker } from './actions/kill-entity-worker';
9
9
  export { CLASS_INDEX, DEAD_INDEX, TYPE_INDEX } from './entity-component';
10
10
  export type { default as EntitySystemWorkerMessage } from './systems/workers/entity-system-worker-message';
11
11
  export type { EntityEvent, SystemEvents } from './systems/workers/entity-system-worker-message';
12
- export type { EntityWorkerSystemWorld, EntityWorkerSystemCallbacks, WorkerAllocator, WorkerCreateEntityConfig, WorkerCreatedEntity, WorkerCreatedComponent, WorkerComponentChange, EntityUpdateComponents, EntityQueryComponents, EntityUpdateFunction, EntityUpdateInitFunction, EntityUpdatePreRunFunction, EntityQueryChangedFunction, QueryDelta, EntityRemovedFunction, UpdateEntityConfigObject, } from './systems/entity-worker-system';
12
+ export type { EntityWorkerSystemWorld, EntityWorkerSystemCallbacks, WorkerAllocator, WorkerCreateEntityConfig, WorkerCreatedEntity, WorkerCreatedComponent, WorkerComponentChange, EntityUpdateComponents, EntityQueryComponents, EntityUpdateFunction, EntityUpdateInitFunction, EntityWorkerSystemInitWorld, EntityUpdatePreRunFunction, EntityQueryChangedFunction, QueryDelta, EntityRemovedFunction, UpdateEntityConfigObject, } from './systems/entity-worker-system';
package/dist/worker.js CHANGED
@@ -1,2 +1,2 @@
1
- import { a as e, c as t, d as n, i as r, l as i, o as a, r as o, s, t as c } from "./create-system-worker-C4aS3-3R.js";
1
+ import { a as e, c as t, d as n, i as r, l as i, o as a, r as o, s, t as c } from "./create-system-worker-CNpRs2FO.js";
2
2
  export { t as CLASS_INDEX, i as DEAD_INDEX, n as TYPE_INDEX, e as addComponentWorker, o as createEntitySystemWorker, a as createEntityWorker, c as createSystemWorker, s as killEntityWorker, r as removeComponentWorker };
package/dist/world.d.ts CHANGED
@@ -11,9 +11,11 @@ import type { WorkerCreatedEntity } from './systems/entity-worker-system';
11
11
  import type { ComponentDefinitionMap, ComponentMap, ComponentsOf, EntityConfigOf, RegisteredComponentDefinition, RegisteredComponentRegistry } from './component-definition';
12
12
  import { type EntityComponent } from './entity-component';
13
13
  import EntityFactory from './entity-factory';
14
+ import type { Scheduler, SchedulerUpdateResult } from './scheduling/scheduler';
14
15
  export interface WorldOptions<C extends ComponentMap = ComponentMap, Cfg = any, E extends BaseEntity<C, Cfg> = BaseEntity<C, Cfg>> {
15
16
  heapSize?: number;
16
17
  factory?: EntityFactory<C, Cfg, E>;
18
+ scheduler?: Scheduler<C>;
17
19
  }
18
20
  export interface WorldConfig<Cfg = any> {
19
21
  entities: Array<Cfg>;
@@ -37,15 +39,17 @@ export default class BaseWorld<R extends ComponentDefinitionMap = ComponentDefin
37
39
  factory: EntityFactory<C, Cfg, E>;
38
40
  entities: Map<number, E>;
39
41
  systems: Array<System<C>>;
42
+ readonly scheduler: Scheduler<C>;
40
43
  gameTime: number;
41
44
  playerTime: number;
42
45
  timeScale: number;
43
- paused: boolean;
46
+ private isPaused;
44
47
  destroyed: boolean;
45
48
  pristine: boolean;
46
49
  isBulkLoading: boolean;
47
50
  private activeFreeBuffer;
48
51
  private nextFreeBuffer;
52
+ private clearing;
49
53
  constructor(registry: R, options?: WorldOptions<C, Cfg, E>);
50
54
  allocateEid(): number;
51
55
  getSharedComponentMemory(): WorldSharedMemory;
@@ -56,7 +60,7 @@ export default class BaseWorld<R extends ComponentDefinitionMap = ComponentDefin
56
60
  addEntity(entity: E, created?: boolean): E;
57
61
  loadEntity(config: Cfg, created?: boolean): E;
58
62
  adoptEntity(descriptor: WorkerCreatedEntity): E;
59
- load(config: WorldConfig<Cfg>): void;
63
+ load(config: WorldConfig<Cfg>): Promise<void>;
60
64
  clear(): Promise<void>;
61
65
  removeEntity(entity: E): void;
62
66
  onEntityDied(entity: E): void;
@@ -72,11 +76,13 @@ export default class BaseWorld<R extends ComponentDefinitionMap = ComponentDefin
72
76
  addSystem<T extends System<C>>(system: T): T;
73
77
  addSystemIfNotExists(system: System<C>): void;
74
78
  removeSystem(name: string): void;
75
- update(elapsedTime: number): {
76
- lastSystemError?: Error | null;
77
- };
79
+ update(elapsedTime: number): SchedulerUpdateResult;
78
80
  private runUpdate;
79
81
  pause(): void;
82
+ get paused(): boolean;
83
+ set paused(paused: boolean);
84
+ prepareForSystemDispatch(): boolean;
85
+ get dispatchAllowed(): boolean;
80
86
  resume(): void;
81
87
  addEntityToEntityWorkerSystem(entity: BaseEntity<C>, component: keyof C): void;
82
88
  removeEntityFromEntityWorkerSystem(entity: BaseEntity<C>, component: keyof C): void;
package/package.json CHANGED
@@ -2,7 +2,7 @@
2
2
  "name": "@daneren2005/shared-memory-ecs",
3
3
  "description": "A small, reusable Entity/Component/System core backed by shared memory.",
4
4
  "author": "Scott Jackson",
5
- "version": "1.8.1",
5
+ "version": "1.9.0",
6
6
  "type": "module",
7
7
  "sideEffects": false,
8
8
  "license": "MIT",
@@ -60,21 +60,21 @@
60
60
  "eventemitter3": "^5.0.4"
61
61
  },
62
62
  "devDependencies": {
63
- "@semantic-release/git": "^10.0.1",
63
+ "@semantic-release/git": "^11.0.1",
64
64
  "@stylistic/eslint-plugin": "^5.10.0",
65
- "@types/node": "^26.6.1",
65
+ "@types/node": "^26.6.2",
66
66
  "@vitest/web-worker": "^5.0.1",
67
67
  "cross-env": "^10.1.0",
68
68
  "husky": "^9.1.7",
69
69
  "lint-staged": "^17.5.1",
70
- "oxlint": "^1.83.0",
71
- "oxlint-tsgolint": "^7.0.2001",
70
+ "oxlint": "^1.85.0",
71
+ "oxlint-tsgolint": "^7.0.2002",
72
72
  "semantic-release": "^25.0.9",
73
73
  "typescript": "^7.0.2",
74
74
  "vite": "^8.3.0",
75
75
  "vitest": "^5.0.1"
76
76
  },
77
77
  "peerDependencies": {
78
- "@daneren2005/shared-memory-objects": "^1.5.2"
78
+ "@daneren2005/shared-memory-objects": "^1.6.0"
79
79
  }
80
80
  }
@@ -1 +0,0 @@
1
- {"version":3,"file":"create-system-worker-C4aS3-3R.js","names":[],"sources":["../src/memory-component.ts","../src/constant-string-cache.ts","../src/systems/workers/apply-query-delta.ts","../src/actions/build-worker-entity.ts","../src/component.ts","../src/entity-component.ts","../src/actions/kill-entity-worker.ts","../src/actions/create-entity-worker.ts","../src/actions/add-component-worker.ts","../src/actions/remove-component-worker.ts","../src/systems/workers/create-entity-system-worker.ts","../src/systems/workers/create-system-worker.ts"],"sourcesContent":["import SharedPool from '@daneren2005/shared-memory-objects/shared-pool';\nimport type { SharedPoolMemory } from '@daneren2005/shared-memory-objects/shared-pool';\nimport type MemoryHeap from '@daneren2005/shared-memory-objects/memory-heap';\nimport type { TypedArrayConstructor } from '@daneren2005/shared-memory-objects/interfaces/typed-array-constructor';\n\nexport type ComponentTypedArray = Uint32Array | Int32Array | Float32Array | Float64Array;\n\n// Backed by a SharedPool: all bookkeeping lives in the shared heap, so a worker can reconstruct a handle over\n// the same pool (pass the owner's getSharedMemory() as `memory`) and allocate/read blocks off-thread.\nexport default class MemoryComponent<T extends ComponentTypedArray = ComponentTypedArray> {\n\theap: MemoryHeap;\n\tpool: SharedPool<T>;\n\n\tconstructor(heap: MemoryHeap, type: TypedArrayConstructor<T>, dataLength: number, memory?: SharedPoolMemory) {\n\t\tthis.heap = heap;\n\t\tthis.pool = memory\n\t\t\t? new SharedPool<T>(heap, memory)\n\t\t\t: new SharedPool<T>(heap, {\n\t\t\t\ttype,\n\t\t\t\tdataLength,\n\t\t\t});\n\t}\n\n\t// Reconstructs a handle over an existing pool (from the owner's getSharedMemory()) — used in a worker, where the\n\t// pool's type/dataLength are already recorded in the heap header, so no definition is needed.\n\tstatic fromSharedMemory<T extends ComponentTypedArray = ComponentTypedArray>(heap: MemoryHeap, memory: SharedPoolMemory): MemoryComponent<T> {\n\t\treturn new MemoryComponent<T>(heap, Uint32Array as unknown as TypedArrayConstructor<T>, 1, memory);\n\t}\n\n\tgetSharedMemory(): SharedPoolMemory {\n\t\treturn this.pool.getSharedMemory();\n\t}\n\n\tget length() {\n\t\treturn this.pool.length;\n\t}\n\tget rawLength() {\n\t\treturn this.pool.bufferLength;\n\t}\n\n\tcreate(values: Array<number>): number {\n\t\treturn this.pool.push(values);\n\t}\n\n\tgetBlock(index: number): T {\n\t\treturn this.pool.at(index);\n\t}\n\tget(index: number, dataIndex: number): number {\n\t\treturn this.pool.get(index, dataIndex);\n\t}\n\tset(index: number, dataIndex: number, value: number) {\n\t\tlet array = this.pool.at(index);\n\t\tarray[dataIndex] = value;\n\t}\n\n\tdelete(index: number) {\n\t\tthis.pool.deleteIndex(index);\n\t}\n\tclear() {\n\t\tthis.pool.clear();\n\t}\n}\n","import ConstantString from '@daneren2005/shared-memory-objects/constant-string';\nimport { getPointer } from '@daneren2005/shared-memory-objects/utils/pointer';\nimport type MemoryHeap from '@daneren2005/shared-memory-objects/memory-heap';\n\n// Interns immutable strings in the heap and resolves them back from a pointer. Every distinct value is allocated\n// once as a single ConstantString shared by all users (15 \"Space Ship\" entities point at one allocation), and a\n// pointer resolves to its string through a Map hit before ever rebuilding it from memory. Both sides of the\n// worker boundary hold one: the main thread creates + interns; a worker (with a heap reconstructed from the same\n// SharedArrayBuffers) only ever resolves pointers and caches the results.\nexport default class ConstantStringCache {\n\tprivate heap: MemoryHeap;\n\t// value -> the one interned allocation. Only the creating (main) thread populates this; it owns the memory.\n\tprivate byValue = new Map<string, ConstantString>();\n\t// pointer -> value: the fast lookup every thread checks before touching memory.\n\tprivate byPointer = new Map<number, string>();\n\n\tconstructor(heap: MemoryHeap) {\n\t\tthis.heap = heap;\n\t}\n\n\t// Dedupes on value, so repeated types share a single ConstantString. Main-thread only.\n\tgetOrCreate(value: string): ConstantString {\n\t\tlet existing = this.byValue.get(value);\n\t\tif(existing) {\n\t\t\treturn existing;\n\t\t}\n\n\t\tconst string = new ConstantString(this.heap, value);\n\t\tthis.byValue.set(value, string);\n\t\tthis.byPointer.set(string.pointer, value);\n\n\t\treturn string;\n\t}\n\n\t// pointer -> string, checking the cache before rebuilding from memory. A pointer of 0 is the empty string; a\n\t// pointer into a buffer that has not synced to this thread yet returns undefined.\n\tgetString(pointer: number): string | undefined {\n\t\tif(pointer === 0) {\n\t\t\treturn '';\n\t\t}\n\n\t\tlet cached = this.byPointer.get(pointer);\n\t\tif(cached !== undefined) {\n\t\t\treturn cached;\n\t\t}\n\n\t\tconst memory = getPointer(pointer, this.heap.positionBits);\n\t\tif(this.heap.buffers[memory.bufferPosition] === undefined) {\n\t\t\treturn undefined;\n\t\t}\n\n\t\tconst value = new ConstantString(this.heap, memory).value;\n\t\tthis.byPointer.set(pointer, value);\n\n\t\treturn value;\n\t}\n\n\t// Frees every allocation this cache owns and empties the lookups. A worker's cache owns nothing (it only ever\n\t// resolved views), so this just drops its pointer lookups.\n\tclear() {\n\t\tthis.byValue.forEach(string => string.free());\n\t\tthis.byValue.clear();\n\t\tthis.byPointer.clear();\n\t}\n}\n","import type { EntityUpdateComponents, QueryDelta, UpdateEntityConfigObject } from '../entity-worker-system';\n\n// Applies a run's delta to a query's persistent list: drop the entities that left, upsert those that joined or\n// changed. A steady-state run carries empty arrays and returns the list untouched. Returns the list (removals\n// rebuild it via filter), so callers must store the returned reference back.\nexport function applyQueryDelta<T extends EntityUpdateComponents>(\n\tlist: Array<UpdateEntityConfigObject<T>>,\n\tdelta: QueryDelta<T>,\n): Array<UpdateEntityConfigObject<T>> {\n\tif(delta.removed.length) {\n\t\tconst removedSet = new Set(delta.removed);\n\t\tlist = list.filter(entry => !removedSet.has(entry.entityId));\n\t}\n\n\tif(delta.added.length) {\n\t\t// Index existing members so a re-added entity replaces its entry in place instead of duplicating.\n\t\tconst indexByEid = new Map<number, number>();\n\t\tlist.forEach((entry, index) => indexByEid.set(entry.entityId, index));\n\n\t\tfor(let entity of delta.added) {\n\t\t\tconst existing = indexByEid.get(entity.entityId);\n\t\t\tif(existing !== undefined) {\n\t\t\t\tlist[existing] = entity;\n\t\t\t} else {\n\t\t\t\tindexByEid.set(entity.entityId, list.length);\n\t\t\t\tlist.push(entity);\n\t\t\t}\n\t\t}\n\t}\n\n\treturn list;\n}\n","import type { WorkerAllocator, WorkerCreateEntityConfig, WorkerCreatedComponent, WorkerCreatedEntity } from '../systems/entity-worker-system';\nimport type { WorkerEntityClassRegistry } from '../entity-class';\n\n// The slice of a component definition worker-side creation needs. Both the game's ComponentDefinitionMap and the\n// world's RegisteredComponentRegistry satisfy it.\nexport interface WorkerCreatableComponent {\n\tloadProperties: Array<string>\n\tloadInFinishLoading?: boolean\n\ttoBlock(config: Record<string, unknown>): Array<number>\n}\nexport type WorkerCreateRegistry = { [name: string]: WorkerCreatableComponent };\nexport type FactoryConfigs = { [type: string]: Record<string, unknown> };\n\n// Turns a factory-style config ({ type, ...overrides }) into a WorkerCreatedEntity, off-thread: layers the type's\n// factory template under the overrides, mints an id, and allocates + writes each triggered component's block via its\n// toBlock(). The always-present `entity` component is NOT built here - the main thread builds it on adopt (interning\n// the type is main-thread-only), reading `type`/`isStatic` off this descriptor. Shared by the real worker and the\n// main-thread fallback so both behave identically.\nexport function buildWorkerEntity(\n\tconfig: WorkerCreateEntityConfig,\n\tfactoryConfigs: FactoryConfigs,\n\tregistry: WorkerCreateRegistry,\n\tallocator: WorkerAllocator,\n\tclasses?: WorkerEntityClassRegistry,\n): WorkerCreatedEntity {\n\tconst template = factoryConfigs[config.type] ?? {};\n\tif(classes && Object.prototype.hasOwnProperty.call(config, 'class')) {\n\t\tthrow new Error('Entity class comes from its type template and cannot be supplied by a worker config');\n\t}\n\tconst merged: Record<string, unknown> = { ...template, ...config };\n\tconst entityClass = typeof template.class === 'string' ? template.class : undefined;\n\tlet componentNames = Object.keys(registry);\n\tif(classes) {\n\t\tif(template.type !== config.type) {\n\t\t\tthrow new Error(`Entity template ${config.type} must declare the same type`);\n\t\t}\n\t\tconst definition = entityClass ? classes[entityClass] : undefined;\n\t\tif(!definition) {\n\t\t\tthrow new Error(`Entity type ${config.type} has unknown class ${entityClass ?? ''}`);\n\t\t}\n\t\tcomponentNames = definition.components;\n\t}\n\n\tconst eid = allocator.allocateEid();\n\tconst components: { [name: string]: number } = {};\n\tfor(let name of componentNames) {\n\t\t// The entity component is always built on the main thread when the descriptor is adopted (interning the type),\n\t\t// never off-thread - skip it here whether or not the registry includes it.\n\t\tif(name === 'entity') {\n\t\t\tcontinue;\n\t\t}\n\t\tconst definition = registry[name];\n\t\tif(!definition) {\n\t\t\tthrow new Error(`Entity class ${entityClass ?? ''} contains unknown component ${name}`);\n\t\t}\n\t\t// Deferred components need the whole world (other entities) that a worker doesn't have; skip them.\n\t\tif(definition.loadInFinishLoading) {\n\t\t\tcontinue;\n\t\t}\n\t\tif(definition.loadProperties.some(prop => prop in merged)) {\n\t\t\tcomponents[name] = allocator.allocateComponentBlock(name, definition.toBlock(merged));\n\t\t}\n\t}\n\n\treturn {\n\t\teid,\n\t\ttype: config.type,\n\t\tclass: entityClass,\n\t\tisStatic: merged.isStatic as boolean | undefined,\n\t\tcomponents,\n\t};\n}\n\nexport function buildWorkerComponent(\n\tname: string,\n\tconfig: Record<string, unknown>,\n\tregistry: WorkerCreateRegistry,\n\tallocator: WorkerAllocator,\n): WorkerCreatedComponent {\n\tif(name === 'entity') {\n\t\tthrow new Error('The entity component cannot be added at runtime');\n\t}\n\tconst definition = registry[name];\n\tif(!definition) {\n\t\tthrow new Error(`Unknown component: ${name}`);\n\t}\n\tif(definition.loadInFinishLoading) {\n\t\tthrow new Error(`Component ${name} requires main-thread finishLoading and cannot be added in a worker`);\n\t}\n\n\treturn {\n\t\tname,\n\t\tindex: allocator.allocateComponentBlock(name, definition.toBlock(config)),\n\t};\n}\n","import type { ComponentTypedArray } from './memory-component';\nimport type { BaseComponent } from './component-definition';\n\n// Base class for a memory-backed component accessor. Subclass it, declare prototype get/set accessors over\n// `this.block` indexed by the component's exported *_INDEX constants, and return `new YourComponent(block, index)`\n// from `attach`. Because the accessors live on one shared prototype - not fresh closures captured per entity -\n// reads off thousands of entities every frame stay monomorphic and inline, and constructing a component allocates\n// just the instance instead of a closure per accessor. Components that own no extra memory need nothing else; a\n// subclass that does can take more constructor args (the entity, another pool) and store them as fields.\nexport default abstract class Component<T extends ComponentTypedArray = ComponentTypedArray> implements BaseComponent {\n\treadonly index: number;\n\treadonly block: T;\n\n\tconstructor(block: T, index: number) {\n\t\tthis.block = block;\n\t\tthis.index = index;\n\t}\n}\n","import type { ComponentDefinition } from './component-definition';\nimport Component from './component';\nimport type ConstantStringCache from './constant-string-cache';\n\nexport interface EntityComponent {\n\tindex: number\n\treadonly type: string\n\treadonly class: string\n\tdead: boolean\n\tisStatic: boolean\n}\n\nexport interface EntityComponentConfig {\n\ttype: string\n\tisStatic?: boolean\n}\n\nexport interface EntityClassConfig {\n\treadonly class: string\n}\n\nexport interface EntityComponentSerialization {\n\ttype?: string\n\tdead?: boolean\n}\n\nexport const DEAD_INDEX = 0;\nexport const STATIC_INDEX = 1;\nexport const TYPE_INDEX = 2;\nexport const CLASS_INDEX = 3;\n\n// Identity strings are interned, so the accessor needs the world's cache to resolve their pointers.\nclass EntityComponentImpl extends Component<Uint32Array> implements EntityComponent {\n\tprivate cache: ConstantStringCache;\n\n\tconstructor(block: Uint32Array, index: number, cache: ConstantStringCache) {\n\t\tsuper(block, index);\n\t\tthis.cache = cache;\n\t}\n\n\tget type() {\n\t\treturn this.cache.getString(this.block[TYPE_INDEX]) ?? '';\n\t}\n\tget class() {\n\t\treturn this.cache.getString(this.block[CLASS_INDEX]) ?? '';\n\t}\n\tget dead() {\n\t\treturn this.block[DEAD_INDEX] === 1;\n\t}\n\tset dead(value: boolean) {\n\t\tthis.block[DEAD_INDEX] = value ? 1 : 0;\n\t}\n\tget isStatic() {\n\t\treturn this.block[STATIC_INDEX] === 1;\n\t}\n\tset isStatic(value: boolean) {\n\t\tthis.block[STATIC_INDEX] = value ? 1 : 0;\n\t}\n}\n\nexport const entityDefinition: ComponentDefinition<EntityComponent, Uint32Array, EntityComponentConfig & Partial<EntityClassConfig>, EntityComponentSerialization> = {\n\ttype: Uint32Array,\n\tsize: 4,\n\tloadProperties: ['type', 'isStatic'],\n\t// The only component that reads the entity (never worker-created): it interns its identity strings through the heap and\n\t// stores the pointer. `entity` is always passed here since loadComponent runs on the main thread.\n\ttoBlock(config, entity) {\n\t\tconst cache = entity!.world.constantStrings;\n\t\tconst typePointer = config.type ? cache.getOrCreate(config.type).pointer : 0;\n\t\tconst classPointer = config.class ? cache.getOrCreate(config.class).pointer : 0;\n\t\treturn [config.dead ? 1 : 0, config.isStatic ? 1 : 0, typePointer, classPointer];\n\t},\n\tattach(entity, memory, index) {\n\t\treturn new EntityComponentImpl(memory.getBlock(index), index, entity.world.constantStrings);\n\t},\n\tsave(component) {\n\t\tconst config: EntityComponentSerialization = {};\n\t\tif(component.type) {\n\t\t\tconfig.type = component.type;\n\t\t}\n\t\tif(component.dead) {\n\t\t\tconfig.dead = true;\n\t\t}\n\n\t\treturn config;\n\t},\n};\n","import type { ComponentTypedArray } from '../memory-component';\nimport type { EntityWorkerSystemCallbacks, EntityUpdateComponents } from '../systems/entity-worker-system';\nimport { DEAD_INDEX } from '../entity-component';\n\n// Worker-side killEntity: flags the entity dead in its block and reports the death back via callbacks. The\n// entity component must be in the system's query for its block to be available here.\nexport default function killEntityWorker(entityId: number, components: EntityUpdateComponents, callbacks: EntityWorkerSystemCallbacks): void {\n\tconst block = (components as { entity?: ComponentTypedArray }).entity;\n\tif(block) {\n\t\tblock[DEAD_INDEX] = 1;\n\t}\n\n\tcallbacks.entityDied(entityId);\n}\n","import type { EntityWorkerSystemCallbacks, EntityWorkerSystemWorld, WorkerCreateEntityConfig } from '../systems/entity-worker-system';\n\n// Worker-side entity creation from a factory config. The worker merges the selected type template, resolves its\n// optional class, mints a unique id, and allocates + writes every allowed, triggered component block\n// directly into the shared pools (off-thread) via each component's toBlock(). It reports the descriptor back; the main\n// thread adopts it on run-complete (world.adoptEntity), building the `entity` component and class wrapper there\n// worker-written blocks, so the entity first exists on the following frame.\n//\n// Requires the system to be registered with `createsEntities: true` and its worker entry to pass the component\n// registry to createEntitySystemWorker (so the worker has each component's toBlock).\nexport default function createEntityWorker(world: EntityWorkerSystemWorld, config: WorkerCreateEntityConfig, callbacks: EntityWorkerSystemCallbacks): void {\n\tif(!world.buildEntityDescriptor) {\n\t\tthrow new Error('createEntityWorker requires the system to be registered with createsEntities: true and the component registry passed to createEntitySystemWorker');\n\t}\n\n\tcallbacks.createEntity(world.buildEntityDescriptor(config));\n}\n","import type { ComponentMap } from '../component-definition';\nimport type { EntityWorkerSystemCallbacks, EntityWorkerSystemWorld } from '../systems/entity-worker-system';\n\n// Allocates a component block in the worker and asks the main thread to attach it after the run. The entity's\n// current query snapshot is intentionally unchanged until the next run.\nexport default function addComponentWorker<C extends ComponentMap, K extends keyof C>(\n\tworld: EntityWorkerSystemWorld,\n\tentityId: number,\n\tcomponentName: K,\n\tconfig: Record<string, unknown>,\n\tcallbacks: EntityWorkerSystemCallbacks<C>,\n): void {\n\tif(!world.buildComponentDescriptor) {\n\t\tthrow new Error('addComponentWorker requires addsComponents: true and the component registry passed to createEntitySystemWorker');\n\t}\n\n\tcallbacks.addComponent(entityId, world.buildComponentDescriptor(String(componentName), config));\n}\n","import type { ComponentMap } from '../component-definition';\nimport type { EntityWorkerSystemCallbacks } from '../systems/entity-worker-system';\n\n// Requests a main-thread detach after the worker run. Shared memory is freed only after every system that could\n// still hold the old block has completed a run.\nexport default function removeComponentWorker<C extends ComponentMap, K extends keyof C>(\n\tentityId: number,\n\tcomponentName: K,\n\tcallbacks: EntityWorkerSystemCallbacks<C>,\n): void {\n\tcallbacks.removeComponent(entityId, componentName);\n}\n","import MemoryHeap from '@daneren2005/shared-memory-objects/memory-heap';\nimport type AllocatedMemory from '@daneren2005/shared-memory-objects/allocated-memory';\nimport type EntitySystemWorkerMessage from './entity-system-worker-message';\nimport type { EntityEvent, SystemEvents, WorkerRunError } from './entity-system-worker-message';\nimport ConstantStringCache from '../../constant-string-cache';\nimport MemoryComponent from '../../memory-component';\nimport type { ComponentDefinitionMap, ComponentMap } from '../../component-definition';\nimport type {\n\tEntityWorkerSystemCallbacks, EntityWorkerSystemWorld, EntityQueryComponents, EntityUpdateComponents,\n\tEntityUpdateFunction, QueryDelta, UpdateEntityConfigObject, WorkerComponentChange, WorkerCreatedEntity,\n} from '../entity-worker-system';\nimport { buildWorkerComponent, buildWorkerEntity, type FactoryConfigs } from '../../actions/build-worker-entity';\nimport type { WorkerEntityClassRegistry } from '../../entity-class';\nimport { applyQueryDelta } from './apply-query-delta';\n\n// The slice of the worker global scope createEntitySystemWorker touches. Passing `self` explicitly (rather than\n// using the global) lets runners like @vitest/web-worker, which inject `self` as a module local, drive it.\nexport interface EntitySystemWorkerScope {\n\tonmessage: ((e: MessageEvent) => void) | null\n\tpostMessage(message: EntitySystemWorkerMessage): void\n}\n\nexport default function createEntitySystemWorker<\n\tC extends ComponentMap,\n\tT extends EntityUpdateComponents<C>,\n\tW extends EntityWorkerSystemWorld = EntityWorkerSystemWorld,\n\tD = unknown,\n>(scope: EntitySystemWorkerScope, updateFunction: EntityUpdateFunction<C, T, W, D>, definitions?: ComponentDefinitionMap) {\n\t// Persistent lists, carried across runs and mutated by each run's delta (see applyQueryDelta).\n\tlet entities: Array<UpdateEntityConfigObject<T>> = [];\n\tconst queryEntities: { [key: string]: Array<UpdateEntityConfigObject<T>> } = {};\n\t// What updateFunction.init returned: persistent state (e.g. a seeded RNG) merged onto `world` each run.\n\tlet worldExtension: Partial<W> | undefined;\n\tlet heap: MemoryHeap | undefined;\n\tlet stringCache: ConstantStringCache | undefined;\n\t// Reconstructed pool handles over the world's shared state, plus the factory templates - for off-thread entity\n\t// allocation. `definitions` (passed by the game's worker entry) supplies each component's toBlock/loadProperties.\n\tlet pools: { [name: string]: MemoryComponent } = {};\n\tlet eidCounter: AllocatedMemory | undefined;\n\tlet factoryConfigs: FactoryConfigs | undefined;\n\tlet factoryClasses: WorkerEntityClassRegistry | undefined;\n\tlet addsComponents = false;\n\tconst getString = (pointer: number): string => stringCache?.getString(pointer) ?? '';\n\n\tscope.onmessage = function(e) {\n\t\tconst message = e.data as EntitySystemWorkerMessage<W, D>;\n\n\t\tif(message.type === 'init') {\n\t\t\tpostMessageTyped(scope, {\n\t\t\t\ttype: 'init-complete',\n\t\t\t});\n\t\t} else if(message.type === 'load') {\n\t\t\tif(message.heap) {\n\t\t\t\theap = new MemoryHeap(message.heap);\n\t\t\t\tstringCache = new ConstantStringCache(heap);\n\t\t\t\t// Report any buffer this worker grows (while allocating off-thread) back to the main thread, which adopts\n\t\t\t\t// it and fans it out to sibling workers.\n\t\t\t\theap.addOnGrowBufferHandlers(buffer => postMessageTyped(scope, { type: 'grow-buffer-from-worker', buffer }));\n\t\t\t}\n\t\t\tif(heap && message.sharedMemory) {\n\t\t\t\tpools = {};\n\t\t\t\tfor(const name of Object.keys(message.sharedMemory.components)) {\n\t\t\t\t\tpools[name] = MemoryComponent.fromSharedMemory(heap, message.sharedMemory.components[name]);\n\t\t\t\t}\n\t\t\t\teidCounter = heap.getSharedAlloc(message.sharedMemory.eidCounter);\n\t\t\t}\n\t\t\tfactoryConfigs = message.factoryConfigs;\n\t\t\tfactoryClasses = message.factoryClasses;\n\t\t\taddsComponents = !!message.addsComponents;\n\t\t\tworldExtension = updateFunction.init?.(message.data) ?? undefined;\n\t\t\tpostMessageTyped(scope, {\n\t\t\t\ttype: 'loaded',\n\t\t\t});\n\t\t} else if(message.type === 'grow-buffer') {\n\t\t\t// Never replace a buffer this worker already holds: the main thread fans a worker-grown buffer back out to\n\t\t\t// every worker (including the one that grew it), and overwriting our own live MemoryBuffer would discard its\n\t\t\t// allocation bookkeeping. The SharedArrayBuffer at that position is already the same one.\n\t\t\tif(heap && heap.buffers[message.buffer.bufferPosition] === undefined) {\n\t\t\t\theap.addSharedBuffer(message.buffer);\n\t\t\t}\n\t\t} else if(message.type === 'reset') {\n\t\t\t// Drop the persistent lists so a reused world starts empty; worldExtension is refreshed by the next load.\n\t\t\tentities = [];\n\t\t\tfor(const key of Object.keys(queryEntities)) {\n\t\t\t\tdelete queryEntities[key];\n\t\t\t}\n\t\t\tworldExtension = undefined;\n\t\t} else if(message.type === 'run') {\n\t\t\tif(worldExtension) {\n\t\t\t\tObject.assign(message.world, worldExtension);\n\t\t\t}\n\t\t\tmessage.world.getString = getString;\n\t\t\tmessage.world.heap = heap;\n\t\t\tconst allocator = {\n\t\t\t\tallocateEid: () => eidCounter ? Atomics.add(eidCounter.data, 0, 1) + 1 : 0,\n\t\t\t\tallocateComponentBlock: (name: string, values: Array<number>) => pools[name].create(values),\n\t\t\t};\n\t\t\tmessage.world.allocate = allocator;\n\t\t\t// Only a system registered with createsEntities (factoryConfigs shipped) whose worker entry passed the\n\t\t\t// component definitions can create entities from a config.\n\t\t\tif(factoryConfigs && definitions) {\n\t\t\t\tmessage.world.buildEntityDescriptor = config => buildWorkerEntity(config, factoryConfigs!, definitions, allocator, factoryClasses);\n\t\t\t}\n\t\t\tif(addsComponents && definitions) {\n\t\t\t\tmessage.world.buildComponentDescriptor = (name, config) => buildWorkerComponent(name, config, definitions, allocator);\n\t\t\t}\n\t\t\tconst start = performance.now();\n\t\t\tlet entityEvents: Array<EntityEvent> = [];\n\t\t\tlet systemEvents: SystemEvents = {};\n\t\t\tlet createdEntities: Array<WorkerCreatedEntity> = [];\n\t\t\tlet componentChanges: Array<WorkerComponentChange> = [];\n\t\t\tlet errors: Array<WorkerRunError> = [];\n\n\t\t\tentities = applyQueryDelta(entities, message.entities as QueryDelta<T>);\n\n\t\t\tlet queries: EntityQueryComponents<C> = {};\n\t\t\tObject.entries(message.queries).forEach(([queryKey, delta]) => {\n\t\t\t\tconst list = applyQueryDelta(queryEntities[queryKey] ?? [], delta as QueryDelta<T>);\n\t\t\t\tqueryEntities[queryKey] = list;\n\t\t\t\tqueries[queryKey] = list;\n\t\t\t});\n\n\t\t\tlet callbacks: EntityWorkerSystemCallbacks<C> = {\n\t\t\t\tentityComponentChanged<K extends keyof C, P extends keyof C[K]>(entityId: number, componentName: K, prop: P, value: C[K][P]) {\n\t\t\t\t\tentityEvents.push({\n\t\t\t\t\t\tentityId,\n\t\t\t\t\t\tevent: 'component-property-updated',\n\t\t\t\t\t\targs: [componentName, prop, value],\n\t\t\t\t\t});\n\t\t\t\t},\n\t\t\t\temitEntityEvent(entityId: number, event: string, ...args: Array<unknown>) {\n\t\t\t\t\tentityEvents.push({\n\t\t\t\t\t\tentityId,\n\t\t\t\t\t\tevent,\n\t\t\t\t\t\targs,\n\t\t\t\t\t});\n\t\t\t\t},\n\t\t\t\temitSystemEvent(event: string, entityId: number) {\n\t\t\t\t\t(systemEvents[event] ?? (systemEvents[event] = [])).push(entityId);\n\t\t\t\t},\n\t\t\t\tentityDied(entityId: number) {\n\t\t\t\t\tentityEvents.push({\n\t\t\t\t\t\tentityId,\n\t\t\t\t\t\tevent: 'death',\n\t\t\t\t\t\targs: [],\n\t\t\t\t\t});\n\t\t\t\t},\n\t\t\t\tcreateEntity(entity: WorkerCreatedEntity) {\n\t\t\t\t\tcreatedEntities.push(entity);\n\t\t\t\t},\n\t\t\t\taddComponent(entityId, component) {\n\t\t\t\t\tcomponentChanges.push({ type: 'add', entityId, component });\n\t\t\t\t},\n\t\t\t\tremoveComponent(entityId, componentName) {\n\t\t\t\t\tcomponentChanges.push({ type: 'remove', entityId, componentName: String(componentName) });\n\t\t\t\t},\n\t\t\t};\n\t\t\tif(updateFunction.queryChanged) {\n\t\t\t\tfor(const [queryName, delta] of Object.entries(message.queries)) {\n\t\t\t\t\tif(!delta.added.length && !delta.removed.length) {\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\t\t\t\t\ttry {\n\t\t\t\t\t\tupdateFunction.queryChanged(message.world, queryName, delta, callbacks);\n\t\t\t\t\t} catch(err) {\n\t\t\t\t\t\terrors.push({ error: err as Error, phase: 'queryChanged' });\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tlet preRunFailed = false;\n\t\t\tif(updateFunction.preRun) {\n\t\t\t\ttry {\n\t\t\t\t\tupdateFunction.preRun(message.world, entities, queries, callbacks);\n\t\t\t\t} catch(err) {\n\t\t\t\t\tpreRunFailed = true;\n\t\t\t\t\terrors.push({ error: err as Error, phase: 'preRun' });\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// preRun sets up the run's state; if it threw, skip the entity loop rather than run over half-prepared data.\n\t\t\tif(!preRunFailed) {\n\t\t\t\tentities.forEach(entity => {\n\t\t\t\t\ttry {\n\t\t\t\t\t\tupdateFunction(message.world, entity.entityId, entity.components, queries, callbacks);\n\t\t\t\t\t} catch(err) {\n\t\t\t\t\t\t// One entity failing must not stop the rest of the run.\n\t\t\t\t\t\terrors.push({ error: err as Error, phase: 'update', entityId: entity.entityId });\n\t\t\t\t\t}\n\t\t\t\t});\n\t\t\t}\n\n\t\t\tif(updateFunction.entityRemoved) {\n\t\t\t\tmessage.entities.removed.forEach(entityId => {\n\t\t\t\t\ttry {\n\t\t\t\t\t\tupdateFunction.entityRemoved!(message.world, entityId, callbacks);\n\t\t\t\t\t} catch(err) {\n\t\t\t\t\t\terrors.push({ error: err as Error, phase: 'entityRemoved', entityId });\n\t\t\t\t\t}\n\t\t\t\t});\n\t\t\t}\n\t\t\tconst runTime = performance.now() - start;\n\n\t\t\tpostMessageTyped(scope, {\n\t\t\t\ttype: 'run-complete',\n\t\t\t\tgeneration: message.generation,\n\t\t\t\trunTime,\n\t\t\t\tevents: entityEvents,\n\t\t\t\tsystemEvents,\n\t\t\t\tcreated: createdEntities,\n\t\t\t\tcomponentChanges,\n\t\t\t\terrors,\n\t\t\t});\n\t\t}\n\t};\n}\n\nfunction postMessageTyped(scope: EntitySystemWorkerScope, message: EntitySystemWorkerMessage) {\n\tscope.postMessage(message);\n}\n","import createEntitySystemWorker, { type EntitySystemWorkerScope } from './create-entity-system-worker';\nimport type { ComponentDefinitionMap, ComponentMap } from '../../component-definition';\nimport type {\n\tEntityWorkerSystemCallbacks, EntityWorkerSystemWorld, EntityQueryComponents, EntityUpdateComponents,\n\tEntityUpdateFunction, EntityUpdateInitFunction, EntityRemovedFunction, EntityQueryChangedFunction,\n} from '../entity-worker-system';\n\n// A WorkerSystem's single per-run function: called once per run over the named sub-queries, not once per entity.\n// Optional `init`/`queryChanged`/`entityRemoved` mirror EntityUpdateFunction's hooks.\nexport type WorkerSystemRunFunction<\n\tC extends ComponentMap,\n\tW extends EntityWorkerSystemWorld = EntityWorkerSystemWorld,\n\tD = unknown,\n> = ((world: W, queries: EntityQueryComponents<C>, callbacks: EntityWorkerSystemCallbacks<C>) => void) & {\n\tinit?: EntityUpdateInitFunction<W, D>\n\tqueryChanged?: EntityQueryChangedFunction<C, W>\n\tentityRemoved?: EntityRemovedFunction<C, W>\n};\n\n// A WorkerSystem reuses the EntityWorkerSystem worker machinery: the single run function becomes `preRun` (which runs\n// once with query access) and the per-entity body is a no-op, since a WorkerSystem never populates its main query.\nexport function toEntityUpdateFunction<\n\tC extends ComponentMap,\n\tW extends EntityWorkerSystemWorld = EntityWorkerSystemWorld,\n\tD = unknown,\n>(run: WorkerSystemRunFunction<C, W, D>): EntityUpdateFunction<C, EntityUpdateComponents<C>, W, D> {\n\tconst updateFunction = (() => {}) as EntityUpdateFunction<C, EntityUpdateComponents<C>, W, D>;\n\tupdateFunction.preRun = (world, _entities, queries, callbacks) => run(world, queries, callbacks);\n\tif(run.init) {\n\t\tupdateFunction.init = run.init;\n\t}\n\tif(run.queryChanged) {\n\t\tupdateFunction.queryChanged = run.queryChanged;\n\t}\n\tif(run.entityRemoved) {\n\t\tupdateFunction.entityRemoved = run.entityRemoved;\n\t}\n\n\treturn updateFunction;\n}\n\n// Worker entry helper for a WorkerSystem (mirrors createEntitySystemWorker). Pass the component registry only for a\n// worker that creates entities.\nexport default function createSystemWorker<\n\tC extends ComponentMap,\n\tW extends EntityWorkerSystemWorld = EntityWorkerSystemWorld,\n\tD = unknown,\n>(scope: EntitySystemWorkerScope, runFunction: WorkerSystemRunFunction<C, W, D>, definitions?: ComponentDefinitionMap) {\n\tcreateEntitySystemWorker(scope, toEntityUpdateFunction(runFunction), definitions);\n}\n"],"mappings":";;;;;AASA,IAAqB,IAArB,MAAqB,EAAqE;CACzF;CACA;CAEA,YAAY,GAAkB,GAAgC,GAAoB,GAA2B;EAE5G,AADA,KAAK,OAAO,GACZ,KAAK,OAAO,IACT,IAAI,EAAc,GAAM,CAAM,IAC9B,IAAI,EAAc,GAAM;GACzB;GACA;EACD,CAAC;CACH;CAIA,OAAO,iBAAsE,GAAkB,GAA8C;EAC5I,OAAO,IAAI,EAAmB,GAAM,aAAoD,GAAG,CAAM;CAClG;CAEA,kBAAoC;EACnC,OAAO,KAAK,KAAK,gBAAgB;CAClC;CAEA,IAAI,SAAS;EACZ,OAAO,KAAK,KAAK;CAClB;CACA,IAAI,YAAY;EACf,OAAO,KAAK,KAAK;CAClB;CAEA,OAAO,GAA+B;EACrC,OAAO,KAAK,KAAK,KAAK,CAAM;CAC7B;CAEA,SAAS,GAAkB;EAC1B,OAAO,KAAK,KAAK,GAAG,CAAK;CAC1B;CACA,IAAI,GAAe,GAA2B;EAC7C,OAAO,KAAK,KAAK,IAAI,GAAO,CAAS;CACtC;CACA,IAAI,GAAe,GAAmB,GAAe;EACpD,IAAI,IAAQ,KAAK,KAAK,GAAG,CAAK;EAC9B,EAAM,KAAa;CACpB;CAEA,OAAO,GAAe;EACrB,KAAK,KAAK,YAAY,CAAK;CAC5B;CACA,QAAQ;EACP,KAAK,KAAK,MAAM;CACjB;AACD,GCpDqB,IAArB,MAAyC;CACxC;CAEA,0BAAkB,IAAI,IAA4B;CAElD,4BAAoB,IAAI,IAAoB;CAE5C,YAAY,GAAkB;EAC7B,KAAK,OAAO;CACb;CAGA,YAAY,GAA+B;EAC1C,IAAI,IAAW,KAAK,QAAQ,IAAI,CAAK;EACrC,IAAG,GACF,OAAO;EAGR,IAAM,IAAS,IAAI,EAAe,KAAK,MAAM,CAAK;EAIlD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