@oasys/oecs 0.5.3 → 0.6.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.
- package/CHANGELOG.md +1399 -276
- package/README.md +327 -169
- package/dist/core/ecs/access_check.d.cts +31 -31
- package/dist/core/ecs/access_check.d.ts +31 -31
- package/dist/core/ecs/access_check.d.ts.map +1 -1
- package/dist/core/ecs/archetype.d.cts +273 -205
- package/dist/core/ecs/archetype.d.ts +273 -205
- package/dist/core/ecs/archetype.d.ts.map +1 -1
- package/dist/core/ecs/archetype_closure.d.cts +23 -0
- package/dist/core/ecs/archetype_closure.d.ts +23 -0
- package/dist/core/ecs/archetype_closure.d.ts.map +1 -0
- package/dist/core/ecs/archetype_graph.d.cts +34 -34
- package/dist/core/ecs/archetype_graph.d.ts +34 -34
- package/dist/core/ecs/archetype_graph.d.ts.map +1 -1
- package/dist/core/ecs/archetype_types.d.cts +55 -0
- package/dist/core/ecs/archetype_types.d.ts +55 -0
- package/dist/core/ecs/archetype_types.d.ts.map +1 -0
- package/dist/core/ecs/change_feed.d.cts +53 -0
- package/dist/core/ecs/change_feed.d.ts +53 -0
- package/dist/core/ecs/change_feed.d.ts.map +1 -0
- package/dist/core/ecs/changed_query.d.cts +36 -0
- package/dist/core/ecs/changed_query.d.ts +36 -0
- package/dist/core/ecs/changed_query.d.ts.map +1 -0
- package/dist/core/ecs/chunk_columns.d.cts +49 -0
- package/dist/core/ecs/chunk_columns.d.ts +49 -0
- package/dist/core/ecs/chunk_columns.d.ts.map +1 -0
- package/dist/core/ecs/command_log.d.cts +30 -30
- package/dist/core/ecs/command_log.d.ts +30 -30
- package/dist/core/ecs/command_log.d.ts.map +1 -1
- package/dist/core/ecs/component.d.cts +45 -44
- package/dist/core/ecs/component.d.ts +45 -44
- package/dist/core/ecs/component.d.ts.map +1 -1
- package/dist/core/ecs/component_registry.d.cts +53 -0
- package/dist/core/ecs/component_registry.d.ts +53 -0
- package/dist/core/ecs/component_registry.d.ts.map +1 -0
- package/dist/core/ecs/compute_backend.d.cts +18 -7
- package/dist/core/ecs/compute_backend.d.ts +18 -7
- package/dist/core/ecs/compute_backend.d.ts.map +1 -1
- package/dist/core/ecs/deferred_commands.d.cts +15 -14
- package/dist/core/ecs/deferred_commands.d.ts +15 -14
- package/dist/core/ecs/deferred_commands.d.ts.map +1 -1
- package/dist/core/ecs/dispatch_trace.d.cts +32 -31
- package/dist/core/ecs/dispatch_trace.d.ts +32 -31
- package/dist/core/ecs/dispatch_trace.d.ts.map +1 -1
- package/dist/core/ecs/ecs.d.cts +337 -276
- package/dist/core/ecs/ecs.d.ts +337 -276
- package/dist/core/ecs/ecs.d.ts.map +1 -1
- package/dist/core/ecs/ecs_memory.d.cts +134 -136
- package/dist/core/ecs/ecs_memory.d.ts +134 -136
- package/dist/core/ecs/ecs_memory.d.ts.map +1 -1
- package/dist/core/ecs/ecs_options.d.cts +89 -0
- package/dist/core/ecs/ecs_options.d.ts +89 -0
- package/dist/core/ecs/ecs_options.d.ts.map +1 -0
- package/dist/core/ecs/entity.d.cts +4 -4
- package/dist/core/ecs/entity.d.ts +4 -4
- package/dist/core/ecs/entity_allocator.d.cts +24 -22
- package/dist/core/ecs/entity_allocator.d.ts +24 -22
- package/dist/core/ecs/entity_allocator.d.ts.map +1 -1
- package/dist/core/ecs/event.d.cts +37 -23
- package/dist/core/ecs/event.d.ts +37 -23
- package/dist/core/ecs/event.d.ts.map +1 -1
- package/dist/core/ecs/facades.d.cts +12 -126
- package/dist/core/ecs/facades.d.ts +12 -126
- package/dist/core/ecs/facades.d.ts.map +1 -1
- package/dist/core/ecs/frame_stepper.d.cts +12 -12
- package/dist/core/ecs/frame_stepper.d.ts +12 -12
- package/dist/core/ecs/frame_stepper.d.ts.map +1 -1
- package/dist/core/ecs/frame_trace.d.cts +34 -34
- package/dist/core/ecs/frame_trace.d.ts +34 -34
- package/dist/core/ecs/frame_trace.d.ts.map +1 -1
- package/dist/core/ecs/host_commands.d.cts +107 -89
- package/dist/core/ecs/host_commands.d.ts +107 -89
- package/dist/core/ecs/host_commands.d.ts.map +1 -1
- package/dist/core/ecs/index.d.cts +22 -12
- package/dist/core/ecs/index.d.ts +22 -12
- package/dist/core/ecs/index.d.ts.map +1 -1
- package/dist/core/ecs/observer.d.cts +41 -122
- package/dist/core/ecs/observer.d.ts +41 -122
- package/dist/core/ecs/observer.d.ts.map +1 -1
- package/dist/core/ecs/phase.d.cts +79 -0
- package/dist/core/ecs/phase.d.ts +79 -0
- package/dist/core/ecs/phase.d.ts.map +1 -0
- package/dist/core/ecs/plugin.d.cts +125 -0
- package/dist/core/ecs/plugin.d.ts +125 -0
- package/dist/core/ecs/plugin.d.ts.map +1 -0
- package/dist/core/ecs/plugin_slots.d.cts +26 -0
- package/dist/core/ecs/plugin_slots.d.ts +26 -0
- package/dist/core/ecs/plugin_slots.d.ts.map +1 -0
- package/dist/core/ecs/query.d.cts +219 -568
- package/dist/core/ecs/query.d.ts +219 -568
- package/dist/core/ecs/query.d.ts.map +1 -1
- package/dist/core/ecs/query_cache.d.cts +130 -0
- package/dist/core/ecs/query_cache.d.ts +130 -0
- package/dist/core/ecs/query_cache.d.ts.map +1 -0
- package/dist/core/ecs/query_registry.d.cts +47 -0
- package/dist/core/ecs/query_registry.d.ts +47 -0
- package/dist/core/ecs/query_registry.d.ts.map +1 -0
- package/dist/core/ecs/query_terms.d.cts +126 -0
- package/dist/core/ecs/query_terms.d.ts +126 -0
- package/dist/core/ecs/query_terms.d.ts.map +1 -0
- package/dist/core/ecs/ref.d.cts +129 -16
- package/dist/core/ecs/ref.d.ts +129 -16
- package/dist/core/ecs/ref.d.ts.map +1 -1
- package/dist/core/ecs/relation.d.cts +105 -186
- package/dist/core/ecs/relation.d.ts +105 -186
- package/dist/core/ecs/relation.d.ts.map +1 -1
- package/dist/core/ecs/resource.d.cts +14 -14
- package/dist/core/ecs/resource.d.ts +14 -14
- package/dist/core/ecs/resource_registry.d.cts +6 -6
- package/dist/core/ecs/resource_registry.d.ts +6 -6
- package/dist/core/ecs/resource_registry.d.ts.map +1 -1
- package/dist/core/ecs/row_kinds.d.cts +24 -0
- package/dist/core/ecs/row_kinds.d.ts +24 -0
- package/dist/core/ecs/row_kinds.d.ts.map +1 -0
- package/dist/core/ecs/run_condition.d.cts +23 -23
- package/dist/core/ecs/run_condition.d.ts +23 -23
- package/dist/core/ecs/run_condition.d.ts.map +1 -1
- package/dist/core/ecs/schedule.d.cts +98 -114
- package/dist/core/ecs/schedule.d.ts +98 -114
- package/dist/core/ecs/schedule.d.ts.map +1 -1
- package/dist/core/ecs/schedule_plan.d.cts +33 -0
- package/dist/core/ecs/schedule_plan.d.ts +33 -0
- package/dist/core/ecs/schedule_plan.d.ts.map +1 -0
- package/dist/core/ecs/snapshot.d.cts +77 -0
- package/dist/core/ecs/snapshot.d.ts +77 -0
- package/dist/core/ecs/snapshot.d.ts.map +1 -0
- package/dist/core/ecs/snapshot_mount.d.cts +42 -0
- package/dist/core/ecs/snapshot_mount.d.ts +42 -0
- package/dist/core/ecs/snapshot_mount.d.ts.map +1 -0
- package/dist/core/ecs/sparse_store.d.cts +110 -53
- package/dist/core/ecs/sparse_store.d.ts +110 -53
- package/dist/core/ecs/sparse_store.d.ts.map +1 -1
- package/dist/core/ecs/store.d.cts +644 -511
- package/dist/core/ecs/store.d.ts +644 -511
- package/dist/core/ecs/store.d.ts.map +1 -1
- package/dist/core/ecs/store_layout_listener.d.cts +8 -8
- package/dist/core/ecs/store_layout_listener.d.ts +8 -8
- package/dist/core/ecs/store_types.d.cts +122 -0
- package/dist/core/ecs/store_types.d.ts +122 -0
- package/dist/core/ecs/store_types.d.ts.map +1 -0
- package/dist/core/ecs/system.d.cts +151 -66
- package/dist/core/ecs/system.d.ts +151 -66
- package/dist/core/ecs/system.d.ts.map +1 -1
- package/dist/core/ecs/system_context.d.cts +296 -0
- package/dist/core/ecs/system_context.d.ts +296 -0
- package/dist/core/ecs/system_context.d.ts.map +1 -0
- package/dist/core/ecs/system_set.d.cts +48 -0
- package/dist/core/ecs/system_set.d.ts +48 -0
- package/dist/core/ecs/system_set.d.ts.map +1 -0
- package/dist/core/ecs/utils/arrays.d.cts +15 -1
- package/dist/core/ecs/utils/arrays.d.ts +15 -1
- package/dist/core/ecs/utils/arrays.d.ts.map +1 -1
- package/dist/core/ecs/utils/error.d.cts +87 -4
- package/dist/core/ecs/utils/error.d.ts +87 -4
- package/dist/core/ecs/utils/error.d.ts.map +1 -1
- package/dist/core/ecs/utils/plugin_error.d.cts +10 -0
- package/dist/core/ecs/utils/plugin_error.d.ts +10 -0
- package/dist/core/ecs/utils/plugin_error.d.ts.map +1 -0
- package/dist/core/restore_errors.d.cts +30 -0
- package/dist/core/restore_errors.d.ts +30 -0
- package/dist/core/restore_errors.d.ts.map +1 -0
- package/dist/core/store/action_ring.d.cts +48 -49
- package/dist/core/store/action_ring.d.ts +48 -49
- package/dist/core/store/action_ring.d.ts.map +1 -1
- package/dist/core/store/allocator.d.cts +166 -114
- package/dist/core/store/allocator.d.ts +166 -114
- package/dist/core/store/allocator.d.ts.map +1 -1
- package/dist/core/store/buffer_backed_column.d.cts +21 -22
- package/dist/core/store/buffer_backed_column.d.ts +21 -22
- package/dist/core/store/buffer_backed_column.d.ts.map +1 -1
- package/dist/core/store/column_store.d.cts +138 -100
- package/dist/core/store/column_store.d.ts +138 -100
- package/dist/core/store/column_store.d.ts.map +1 -1
- package/dist/core/store/command_dispatch.d.cts +14 -15
- package/dist/core/store/command_dispatch.d.ts +14 -15
- package/dist/core/store/command_dispatch.d.ts.map +1 -1
- package/dist/core/store/command_ring.d.cts +41 -45
- package/dist/core/store/command_ring.d.ts +41 -45
- package/dist/core/store/command_ring.d.ts.map +1 -1
- package/dist/core/store/descriptor.d.cts +35 -18
- package/dist/core/store/descriptor.d.ts +35 -18
- package/dist/core/store/descriptor.d.ts.map +1 -1
- package/dist/core/store/entity_index.d.cts +34 -35
- package/dist/core/store/entity_index.d.ts +34 -35
- package/dist/core/store/entity_index.d.ts.map +1 -1
- package/dist/core/store/event_ring.d.cts +40 -42
- package/dist/core/store/event_ring.d.ts +40 -42
- package/dist/core/store/event_ring.d.ts.map +1 -1
- package/dist/core/store/extend.d.cts +15 -9
- package/dist/core/store/extend.d.ts +15 -9
- package/dist/core/store/extend.d.ts.map +1 -1
- package/dist/core/store/grow.d.cts +3 -3
- package/dist/core/store/grow.d.ts +3 -3
- package/dist/core/store/grow.d.ts.map +1 -1
- package/dist/core/store/header.d.cts +37 -33
- package/dist/core/store/header.d.ts +37 -33
- package/dist/core/store/header.d.ts.map +1 -1
- package/dist/core/store/index.d.cts +10 -10
- package/dist/core/store/index.d.ts +10 -10
- package/dist/core/store/index.d.ts.map +1 -1
- package/dist/core/store/layout_ops.d.cts +72 -63
- package/dist/core/store/layout_ops.d.ts +72 -63
- package/dist/core/store/layout_ops.d.ts.map +1 -1
- package/dist/core/store/region_table.d.cts +28 -21
- package/dist/core/store/region_table.d.ts +28 -21
- package/dist/core/store/region_table.d.ts.map +1 -1
- package/dist/core/store/snapshot.d.cts +31 -16
- package/dist/core/store/snapshot.d.ts +31 -16
- package/dist/core/store/snapshot.d.ts.map +1 -1
- package/dist/core/store/state_hash.d.cts +14 -14
- package/dist/core/store/state_hash.d.ts +14 -14
- package/dist/core/store/state_hash.d.ts.map +1 -1
- package/dist/core/store/store_regions.d.cts +10 -10
- package/dist/core/store/store_regions.d.ts +10 -10
- package/dist/core/store/store_regions.d.ts.map +1 -1
- package/dist/core/store/vendored_abi/abi.d.cts +27 -2
- package/dist/core/store/vendored_abi/abi.d.ts +27 -2
- package/dist/core/store/vendored_abi/abi.d.ts.map +1 -1
- package/dist/host_commands-B2KMx8O2.cjs +1 -0
- package/dist/host_commands-ClVPvhSa.cjs +2 -0
- package/dist/host_commands-CwxVQS1z.js +1524 -0
- package/dist/host_commands-nJvTy88E.js +1667 -0
- package/dist/index.cjs +1 -1
- package/dist/index.d.cts +16 -11
- package/dist/index.d.ts +16 -11
- package/dist/index.d.ts.map +1 -1
- package/dist/index.development.cjs +1 -1
- package/dist/index.development.js +6709 -5729
- package/dist/index.js +5664 -4743
- package/dist/internal.cjs +2 -2
- package/dist/internal.d.cts +5 -2
- package/dist/internal.d.ts +5 -2
- package/dist/internal.d.ts.map +1 -1
- package/dist/internal.development.cjs +1 -1
- package/dist/internal.development.js +70 -20
- package/dist/internal.js +138 -83
- package/dist/plugins/abi-D3V-QUSf.cjs +1 -0
- package/dist/plugins/abi-NP8pNxpd.js +42 -0
- package/dist/plugins/arrays-Dr_1hCjL.js +28 -0
- package/dist/plugins/arrays-Dt-Joc4i.cjs +1 -0
- package/dist/plugins/assertions-gtDVfbnQ.js +6 -0
- package/dist/plugins/assertions-z5GQd_bB.cjs +1 -0
- package/dist/{extensions → plugins}/editor/editor.d.cts +56 -56
- package/dist/{extensions → plugins}/editor/editor.d.ts +56 -56
- package/dist/plugins/editor/editor.d.ts.map +1 -0
- package/dist/{extensions → plugins}/editor/field_handle.d.cts +13 -13
- package/dist/{extensions → plugins}/editor/field_handle.d.ts +13 -13
- package/dist/plugins/editor/field_handle.d.ts.map +1 -0
- package/dist/plugins/editor/index.d.cts +22 -0
- package/dist/plugins/editor/index.d.ts +22 -0
- package/dist/plugins/editor/index.d.ts.map +1 -0
- package/dist/plugins/editor.cjs +1 -0
- package/dist/plugins/editor.d.cts +1 -0
- package/dist/plugins/editor.d.ts +1 -0
- package/dist/plugins/editor.development.cjs +1 -0
- package/dist/{extensions/editor/index.development.js → plugins/editor.development.js} +83 -66
- package/dist/{extensions/editor/index.js → plugins/editor.js} +83 -66
- package/dist/plugins/events/event_channel.d.cts +13 -0
- package/dist/plugins/events/event_channel.d.ts +13 -0
- package/dist/plugins/events/event_channel.d.ts.map +1 -0
- package/dist/plugins/events/event_registry.d.cts +22 -0
- package/dist/plugins/events/event_registry.d.ts +22 -0
- package/dist/plugins/events/event_registry.d.ts.map +1 -0
- package/dist/plugins/events/facade.d.cts +26 -0
- package/dist/plugins/events/facade.d.ts +26 -0
- package/dist/plugins/events/facade.d.ts.map +1 -0
- package/dist/plugins/events/index.d.cts +10 -0
- package/dist/plugins/events/index.d.ts +10 -0
- package/dist/plugins/events/index.d.ts.map +1 -0
- package/dist/plugins/events.cjs +1 -0
- package/dist/plugins/events.d.cts +1 -0
- package/dist/plugins/events.d.ts +1 -0
- package/dist/plugins/events.development.cjs +1 -0
- package/dist/plugins/events.development.js +174 -0
- package/dist/plugins/events.js +159 -0
- package/dist/plugins/observers/index.d.cts +23 -0
- package/dist/plugins/observers/index.d.ts +23 -0
- package/dist/plugins/observers/index.d.ts.map +1 -0
- package/dist/plugins/observers/observer_registry.d.cts +101 -0
- package/dist/plugins/observers/observer_registry.d.ts +101 -0
- package/dist/plugins/observers/observer_registry.d.ts.map +1 -0
- package/dist/plugins/observers.cjs +1 -0
- package/dist/plugins/observers.d.cts +1 -0
- package/dist/plugins/observers.d.ts +1 -0
- package/dist/plugins/observers.development.cjs +1 -0
- package/dist/plugins/observers.development.js +431 -0
- package/dist/plugins/observers.js +403 -0
- package/dist/plugins/relation_store-BsoegrZh.js +313 -0
- package/dist/plugins/relation_store-DQKSnxsm.cjs +1 -0
- package/dist/plugins/relation_store-RBhpcE28.cjs +1 -0
- package/dist/plugins/relation_store-RqW5Snx6.js +328 -0
- package/dist/plugins/relations/builtin_relations.d.cts +48 -0
- package/dist/plugins/relations/builtin_relations.d.ts +48 -0
- package/dist/plugins/relations/builtin_relations.d.ts.map +1 -0
- package/dist/plugins/relations/facade.d.cts +73 -0
- package/dist/plugins/relations/facade.d.ts +73 -0
- package/dist/plugins/relations/facade.d.ts.map +1 -0
- package/dist/plugins/relations/index.d.cts +11 -0
- package/dist/plugins/relations/index.d.ts +11 -0
- package/dist/plugins/relations/index.d.ts.map +1 -0
- package/dist/{core/ecs → plugins/relations}/relation_service.d.cts +93 -105
- package/dist/{core/ecs → plugins/relations}/relation_service.d.ts +93 -105
- package/dist/plugins/relations/relation_service.d.ts.map +1 -0
- package/dist/plugins/relations/relation_store.d.cts +177 -0
- package/dist/plugins/relations/relation_store.d.ts +177 -0
- package/dist/plugins/relations/relation_store.d.ts.map +1 -0
- package/dist/plugins/relations.cjs +1 -0
- package/dist/plugins/relations.d.cts +1 -0
- package/dist/plugins/relations.d.ts +1 -0
- package/dist/plugins/relations.development.cjs +1 -0
- package/dist/plugins/relations.development.js +603 -0
- package/dist/plugins/relations.js +553 -0
- package/dist/plugins/snapshots/index.d.cts +33 -0
- package/dist/plugins/snapshots/index.d.ts +33 -0
- package/dist/plugins/snapshots/index.d.ts.map +1 -0
- package/dist/plugins/snapshots/resume.d.cts +57 -0
- package/dist/plugins/snapshots/resume.d.ts +57 -0
- package/dist/plugins/snapshots/resume.d.ts.map +1 -0
- package/dist/plugins/snapshots/snapshot_service.d.cts +59 -0
- package/dist/plugins/snapshots/snapshot_service.d.ts +59 -0
- package/dist/plugins/snapshots/snapshot_service.d.ts.map +1 -0
- package/dist/plugins/snapshots.cjs +1 -0
- package/dist/plugins/snapshots.d.cts +1 -0
- package/dist/plugins/snapshots.d.ts +1 -0
- package/dist/plugins/snapshots.development.cjs +1 -0
- package/dist/plugins/snapshots.development.js +737 -0
- package/dist/plugins/snapshots.js +737 -0
- package/dist/plugins/solid/index.d.cts +8 -0
- package/dist/plugins/solid/index.d.ts +8 -0
- package/dist/plugins/solid/index.d.ts.map +1 -0
- package/dist/plugins/solid/solid.d.cts +97 -0
- package/dist/plugins/solid/solid.d.ts +97 -0
- package/dist/plugins/solid/solid.d.ts.map +1 -0
- package/dist/plugins/solid.cjs +1 -0
- package/dist/plugins/solid.d.cts +1 -0
- package/dist/plugins/solid.d.ts +1 -0
- package/dist/plugins/solid.development.cjs +1 -0
- package/dist/plugins/solid.development.js +319 -0
- package/dist/plugins/solid.js +319 -0
- package/dist/plugins/workers/index.d.cts +75 -0
- package/dist/plugins/workers/index.d.ts +75 -0
- package/dist/plugins/workers/index.d.ts.map +1 -0
- package/dist/plugins/workers/node_threads.d.cts +25 -0
- package/dist/plugins/workers/node_threads.d.ts +25 -0
- package/dist/plugins/workers/node_threads.d.ts.map +1 -0
- package/dist/plugins/workers/plan.d.cts +61 -0
- package/dist/plugins/workers/plan.d.ts +61 -0
- package/dist/plugins/workers/plan.d.ts.map +1 -0
- package/dist/plugins/workers/pool.d.cts +144 -0
- package/dist/plugins/workers/pool.d.ts +144 -0
- package/dist/plugins/workers/pool.d.ts.map +1 -0
- package/dist/plugins/workers/protocol.d.cts +112 -0
- package/dist/plugins/workers/protocol.d.ts +112 -0
- package/dist/plugins/workers/protocol.d.ts.map +1 -0
- package/dist/plugins/workers/worker_bind.d.cts +64 -0
- package/dist/plugins/workers/worker_bind.d.ts +64 -0
- package/dist/plugins/workers/worker_bind.d.ts.map +1 -0
- package/dist/plugins/workers/worker_loop.d.cts +14 -0
- package/dist/plugins/workers/worker_loop.d.ts +14 -0
- package/dist/plugins/workers/worker_loop.d.ts.map +1 -0
- package/dist/plugins/workers.cjs +1 -0
- package/dist/plugins/workers.d.cts +1 -0
- package/dist/plugins/workers.d.ts +1 -0
- package/dist/plugins/workers.development.cjs +1 -0
- package/dist/plugins/workers.development.js +596 -0
- package/dist/plugins/workers.js +474 -0
- package/dist/primitives.cjs +1 -1
- package/dist/primitives.d.cts +4 -4
- package/dist/primitives.d.ts +4 -4
- package/dist/primitives.development.cjs +1 -1
- package/dist/primitives.development.js +66 -22
- package/dist/primitives.js +66 -22
- package/dist/shared-BKl12xF1.js +132 -0
- package/dist/shared-Dk-pACZT.cjs +1 -0
- package/dist/shared.cjs +1 -1
- package/dist/shared.d.cts +7 -7
- package/dist/shared.d.ts +7 -7
- package/dist/shared.d.ts.map +1 -1
- package/dist/shared.development.cjs +1 -1
- package/dist/shared.development.js +4 -3
- package/dist/shared.js +4 -3
- package/dist/topological_sort-Cc_yXqPT.js +346 -0
- package/dist/topological_sort-vp1imU6D.cjs +1 -0
- package/dist/type_primitives/assertions.d.cts +12 -16
- package/dist/type_primitives/assertions.d.ts +12 -16
- package/dist/type_primitives/assertions.d.ts.map +1 -1
- package/dist/type_primitives/binary_heap/binary_heap.d.cts +2 -6
- package/dist/type_primitives/binary_heap/binary_heap.d.ts +2 -6
- package/dist/type_primitives/binary_heap/binary_heap.d.ts.map +1 -1
- package/dist/type_primitives/bitset/bitset.d.cts +7 -11
- package/dist/type_primitives/bitset/bitset.d.ts +7 -11
- package/dist/type_primitives/bitset/bitset.d.ts.map +1 -1
- package/dist/type_primitives/brand.d.cts +2 -7
- package/dist/type_primitives/brand.d.ts +2 -7
- package/dist/type_primitives/brand.d.ts.map +1 -1
- package/dist/type_primitives/error.d.cts +1 -2
- package/dist/type_primitives/error.d.ts +1 -2
- package/dist/type_primitives/error.d.ts.map +1 -1
- package/dist/type_primitives/index.d.cts +1 -1
- package/dist/type_primitives/index.d.ts +1 -1
- package/dist/type_primitives/sparse_map/sparse_map.d.cts +3 -7
- package/dist/type_primitives/sparse_map/sparse_map.d.ts +3 -7
- package/dist/type_primitives/sparse_map/sparse_map.d.ts.map +1 -1
- package/dist/type_primitives/sparse_set/sparse_set.d.cts +2 -6
- package/dist/type_primitives/sparse_set/sparse_set.d.ts +2 -6
- package/dist/type_primitives/sparse_set/sparse_set.d.ts.map +1 -1
- package/dist/type_primitives/topological_sort/topological_sort.d.cts +1 -5
- package/dist/type_primitives/topological_sort/topological_sort.d.ts +1 -5
- package/dist/type_primitives/topological_sort/topological_sort.d.ts.map +1 -1
- package/dist/type_primitives/typed_arrays/typed_arrays.d.cts +18 -17
- package/dist/type_primitives/typed_arrays/typed_arrays.d.ts +18 -17
- package/dist/type_primitives/typed_arrays/typed_arrays.d.ts.map +1 -1
- package/dist/utils/error.d.ts.map +1 -1
- package/dist/version.d.cts +4 -4
- package/dist/version.d.ts +4 -4
- package/dist/worker.cjs +1 -0
- package/dist/worker.d.cts +17 -0
- package/dist/worker.d.ts +17 -0
- package/dist/worker.d.ts.map +1 -0
- package/dist/worker.development.cjs +1 -0
- package/dist/worker.development.js +253 -0
- package/dist/worker.js +253 -0
- package/package.json +363 -191
- package/dist/core/ecs/builtin_relations.d.cts +0 -43
- package/dist/core/ecs/builtin_relations.d.ts +0 -43
- package/dist/core/ecs/builtin_relations.d.ts.map +0 -1
- package/dist/core/ecs/event_registry.d.cts +0 -22
- package/dist/core/ecs/event_registry.d.ts +0 -22
- package/dist/core/ecs/event_registry.d.ts.map +0 -1
- package/dist/core/ecs/relation_service.d.ts.map +0 -1
- package/dist/core/ecs/resume.d.cts +0 -85
- package/dist/core/ecs/resume.d.ts +0 -85
- package/dist/core/ecs/resume.d.ts.map +0 -1
- package/dist/core/ecs/snapshot_service.d.cts +0 -94
- package/dist/core/ecs/snapshot_service.d.ts +0 -94
- package/dist/core/ecs/snapshot_service.d.ts.map +0 -1
- package/dist/extensions/editor/editor.d.ts.map +0 -1
- package/dist/extensions/editor/field_handle.d.ts.map +0 -1
- package/dist/extensions/editor/index.cjs +0 -1
- package/dist/extensions/editor/index.d.cts +0 -21
- package/dist/extensions/editor/index.d.ts +0 -21
- package/dist/extensions/editor/index.d.ts.map +0 -1
- package/dist/extensions/editor/index.development.cjs +0 -1
- package/dist/extensions/reactive/ecs_sync.d.cts +0 -214
- package/dist/extensions/reactive/ecs_sync.d.ts +0 -214
- package/dist/extensions/reactive/ecs_sync.d.ts.map +0 -1
- package/dist/extensions/reactive/index.cjs +0 -1
- package/dist/extensions/reactive/index.d.cts +0 -23
- package/dist/extensions/reactive/index.d.ts +0 -23
- package/dist/extensions/reactive/index.d.ts.map +0 -1
- package/dist/extensions/reactive/index.development.cjs +0 -1
- package/dist/extensions/reactive/index.development.js +0 -215
- package/dist/extensions/reactive/index.js +0 -215
- package/dist/extensions/solid/index.cjs +0 -1
- package/dist/extensions/solid/index.d.cts +0 -6
- package/dist/extensions/solid/index.d.ts +0 -6
- package/dist/extensions/solid/index.d.ts.map +0 -1
- package/dist/extensions/solid/index.development.cjs +0 -1
- package/dist/extensions/solid/index.development.js +0 -40
- package/dist/extensions/solid/index.js +0 -36
- package/dist/extensions/solid/kernel_solid.d.cts +0 -45
- package/dist/extensions/solid/kernel_solid.d.ts +0 -45
- package/dist/extensions/solid/kernel_solid.d.ts.map +0 -1
- package/dist/host_commands-3jyFfWNg.js +0 -2326
- package/dist/host_commands-DNf0f6ko.cjs +0 -1
- package/dist/internal-C9jjL90H.js +0 -2485
- package/dist/internal-RZN14uMw.cjs +0 -2
- package/dist/interop-CT-REx0W.cjs +0 -1
- package/dist/interop-CcY6ASQc.js +0 -18
- package/dist/interop-DqxleBo7.js +0 -18
- package/dist/interop-T1HZ-Dpa.cjs +0 -1
- package/dist/kernel-Cz2Kxlwl.js +0 -240
- package/dist/kernel-DgyrLFjW.js +0 -227
- package/dist/kernel-sw7ScKWu.cjs +0 -1
- package/dist/kernel-yWV3XnAb.cjs +0 -1
- package/dist/reactive/array.d.cts +0 -24
- package/dist/reactive/array.d.ts +0 -24
- package/dist/reactive/array.d.ts.map +0 -1
- package/dist/reactive/index.cjs +0 -1
- package/dist/reactive/index.d.cts +0 -11
- package/dist/reactive/index.d.ts +0 -11
- package/dist/reactive/index.d.ts.map +0 -1
- package/dist/reactive/index.development.cjs +0 -1
- package/dist/reactive/index.development.js +0 -18
- package/dist/reactive/index.js +0 -18
- package/dist/reactive/interop.d.cts +0 -19
- package/dist/reactive/interop.d.ts +0 -19
- package/dist/reactive/interop.d.ts.map +0 -1
- package/dist/reactive/kernel.d.cts +0 -73
- package/dist/reactive/kernel.d.ts +0 -73
- package/dist/reactive/kernel.d.ts.map +0 -1
- package/dist/reactive/map.d.cts +0 -16
- package/dist/reactive/map.d.ts +0 -16
- package/dist/reactive/map.d.ts.map +0 -1
- package/dist/reactive/shallow.d.cts +0 -11
- package/dist/reactive/shallow.d.ts +0 -11
- package/dist/reactive/shallow.d.ts.map +0 -1
- package/dist/reactive/struct.d.cts +0 -10
- package/dist/reactive/struct.d.ts +0 -10
- package/dist/reactive/struct.d.ts.map +0 -1
- package/dist/shallow-9S1pY_Iw.js +0 -159
- package/dist/shallow-C5YmTbtb.cjs +0 -1
- package/dist/shallow-DQ8aG51_.cjs +0 -1
- package/dist/shallow-DfnAm9vG.js +0 -150
- package/dist/shared-BMXh9hxm.cjs +0 -1
- package/dist/shared-DQKK0i-E.js +0 -109
- package/dist/topological_sort-BDvEyb9W.cjs +0 -1
- package/dist/topological_sort-DK6EjpWa.js +0 -135
- package/dist/typed_arrays-BcXcnzB4.js +0 -258
- package/dist/typed_arrays-D3NmwtCG.cjs +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const i=require("./internal-RZN14uMw.cjs"),T=require("./typed_arrays-D3NmwtCG.cjs"),W=require("./shared-BMXh9hxm.cjs"),I=!0,Te=c=>i.validateAndCast(c,i.isNonNegativeInteger,"ComponentID must be a non-negative integer"),le=Object.freeze({});function De(c){const e=(t=>({def:e,values:t??le}));return Object.defineProperty(e,"id",{value:c,enumerable:!1}),e}function Ue(c,...e){return{def:c,values:e[0]??le}}function G(c){return typeof c=="function"?c:c.def}function P(c){return typeof c=="function"?le:c.values}class B extends Error{constructor(e){super(e),this.name="StoreRestoreError"}}function Ve(c){const e=c.view.getUint32(i.STORE_HEADER_OFFSETS.capacity,!0);return new Uint8Array(c.buffer,0,e)}function qe(c,e=W.DEFAULT_SAB_ALLOCATOR){const t=new DataView(c.buffer,c.byteOffset,c.byteLength);if(c.byteLength<i.STORE_HEADER_BYTES)throw new B(`snapshot too small: ${c.byteLength} bytes (header alone needs ${i.STORE_HEADER_BYTES})`);const s=t.getUint32(i.STORE_HEADER_OFFSETS.magic,!0);if(s!==i.STORE_MAGIC)throw new B(`bad magic: 0x${s.toString(16).padStart(8,"0")} (expected 0x${i.STORE_MAGIC.toString(16).padStart(8,"0")})`);const r=t.getUint32(i.STORE_HEADER_OFFSETS.sim_abi_version,!0);if(r!==i.SIM_ABI_VERSION)throw new B(`incompatible sim_abi_version: snapshot=${r}, build=${i.SIM_ABI_VERSION}`);const n=e(c.byteLength);new Uint8Array(n).set(c);const o=new DataView(n),a=i.readStoreHeader(o);if(a.layoutDescriptorOff<0||a.layoutDescriptorOff>n.byteLength)throw new B(`layout_descriptor_off ${a.layoutDescriptorOff} is outside the snapshot (${n.byteLength} bytes)`);try{const h=i.readLayoutDescriptorRegion(o,a.layoutDescriptorOff,a.archetypeCount),l=i.buildArchetypeViews(n,h);return{buffer:n,view:o,header:a,archetypes:l}}catch(h){throw h instanceof RangeError?new B(`snapshot layout is corrupt or truncated: a descriptor offset or column extent reads past the ${n.byteLength}-byte buffer (${h.message})`):h}}const We=c=>i.validateAndCast(c,i.isNonNegativeInteger,"EventID must be a non-negative integer");class Ye{fieldNames;columns;reader;_readerLen;constructor(e){this.fieldNames=e,this.columns=[];for(let r=0;r<e.length;r++)this.columns.push([]);const t={};for(let r=0;r<e.length;r++)t[e[r]]=this.columns[r];const s={length:0,...t};this._readerLen=s,this.reader=s}emit(e){const t=this.fieldNames,s=this.columns;for(let r=0;r<t.length;r++)if(!(t[r]in e))throw new i.ECSError(i.ECS_ERROR.FIELD_NOT_REGISTERED,`emit: event field "${t[r]}" missing from values`);for(let r=0;r<t.length;r++)s[r].push(e[t[r]]);this._readerLen.length++}emitSignal(){this._readerLen.length++}clear(){this._readerLen.length=0;const e=this.columns;for(let t=0;t<e.length;t++)e[t].length=0}}function ze(c){return i.unsafeCast(Symbol(c))}function je(c){return i.unsafeCast(Symbol(c))}class Qe{channels=[];dirtyChannels=[];count=0;keyMap=new Map;registerEvent(e){const t=We(this.count++),s=new Ye(e);return this.channels.push(s),i.unsafeCast(t)}emitEvent(e,t){const s=e,r=this.channels[s],n=r.reader.length===0;r.emit(t),n&&this.dirtyChannels.push(s)}emitSignal(e){const t=e,s=this.channels[t],r=s.reader.length===0;s.emitSignal(),r&&this.dirtyChannels.push(t)}getEventReader(e){return this.channels[e].reader}clearEvents(){const e=this.dirtyChannels,t=this.channels;for(let s=0;s<e.length;s++)t[e[s]].clear();e.length=0}devBufferedEventCount(){const e=this.dirtyChannels,t=this.channels;let s=0;for(let r=0;r<e.length;r++)s+=t[e[r]].reader.length;return s}registerEventByKey(e,t){if(this.keyMap.has(e))throw new i.ECSError(i.ECS_ERROR.EVENT_ALREADY_REGISTERED,`event '${e.description??"<unnamed>"}' is already registered`,{event:e.description});const s=this.registerEvent(t);return this.keyMap.set(e,s),s}getEventDefByKey(e){const t=this.keyMap.get(e);if(t===void 0)throw new i.ECSError(i.ECS_ERROR.EVENT_NOT_REGISTERED,`event '${e.description??"<unnamed>"}' is not registered — call ecs.events.register(key, fields) at world setup`,{event:e.description});return t}hasEventKey(e){return this.keyMap.has(e)}}class Ke{map=new Map;register(e,t){if(this.map.has(e))throw new i.ECSError(i.ECS_ERROR.RESOURCE_ALREADY_REGISTERED,`resource '${e.description??"<unnamed>"}' is already registered — remove() it first if you meant to replace it`,{resource:e.description});this.map.set(e,t)}get(e){if(!this.map.has(e))throw new i.ECSError(i.ECS_ERROR.RESOURCE_NOT_REGISTERED,`resource read: '${e.description??"<unnamed>"}' is not registered — call ecs.resources.register(key, value) at world setup`,{resource:e.description});return this.map.get(e)}set(e,t){if(!this.map.has(e))throw new i.ECSError(i.ECS_ERROR.RESOURCE_NOT_REGISTERED,`resource write: '${e.description??"<unnamed>"}' is not registered — call ecs.resources.register(key, value) at world setup`,{resource:e.description});this.map.set(e,t)}remove(e){if(!this.map.has(e))throw new i.ECSError(i.ECS_ERROR.RESOURCE_NOT_REGISTERED,`resource remove: '${e.description??"<unnamed>"}' is not registered — call ecs.resources.register(key, value) at world setup`,{resource:e.description});this.map.delete(e)}has(e){return this.map.has(e)}}class j extends Error{capacity;requested;constructor(e,t){super(`BufferBackedColumn overflow: requested length ${t} exceeds capacity ${e}`),this.name="StoreColumnOverflowError",this.capacity=e,this.requested=t}}class pe{_buf;_capacity;_len=0;constructor(e){this._buf=e,this._capacity=e.length}refreshView(e){if(e.length<this._len)throw new j(e.length,this._len);this._buf=e,this._capacity=e.length}get length(){return this._len}get capacity(){return this._capacity}push(e){if(this._len>=this._capacity)throw new j(this._capacity,this._len+1);this._buf[this._len++]=e}pop(){return this._buf[--this._len]}get(e){return this._buf[e]}setAt(e,t){this._buf[e]=t}swapRemove(e){const t=this._buf[e];return this._buf[e]=this._buf[--this._len],t}clear(){this._len=0}setLength(e){if(e>this._capacity)throw new j(this._capacity,e);this._len=e}get buf(){return this._buf}view(){return this._buf.subarray(0,this._len)}[Symbol.iterator](){let e=0;const t=this._buf,s=this._len;return{next(){return e<s?{value:t[e++],done:!1}:{value:0,done:!0}}}}ensureCapacity(e){if(e>this._capacity)throw new j(this._capacity,e)}bulkAppend(e,t,s){this.ensureCapacity(this._len+s),this._buf.set(e.subarray(t,t+s),this._len),this._len+=s}bulkAppendZeroes(e){this.ensureCapacity(this._len+e),this._buf.fill(0,this._len,this._len+e),this._len+=e}bulkAppendValue(e,t){this.ensureCapacity(this._len+t),this._buf.fill(e,this._len,this._len+t),this._len+=t}}const _e=c=>i.validateAndCast(c,i.isNonNegativeInteger,"ArchetypeID must be a non-negative integer");class ue{id;mask;hasColumns;materializesRows;_entityIds;length=0;enabledCount=0;_flushSeenEpoch=-1;_flushPreLen=0;_flushPreEnabled=0;_iterDepth=0;edges=[];batchTransitionMaps=new Map;compositeAddEdges=null;_flatColumns=[];_storeArchetypeId=null;_colOffset=[];_fieldCount=[];_fieldIndex=[];_fieldNames=[];columnGroups=[];_columnIds=[];_changedTick=[];_mutGroupCache=[];_readGroupCache=[];growHandler=null;constructor(e,t,s,r=i.DEFAULT_COLUMN_CAPACITY,n){if(this.id=e,this.mask=t,this._entityIds=new T.GrowableUint32Array(r),s){let o=0;for(let a=0;a<s.length;a++){const h=s[a],l=h.componentId,u=new Array(h.fieldNames.length);if(this._colOffset[l]=o,this._fieldCount[l]=h.fieldNames.length,this._fieldIndex[l]=h.fieldIndex,this._fieldNames[l]=h.fieldNames,h.fieldNames.length>0&&!n)throw new i.ECSError(i.ECS_ERROR.COMPONENT_NOT_REGISTERED,`Archetype ${e}: layouts with fields require a columnFactory — use Archetype.fromColumnStore for SAB-backed columns, or pass a heap factory explicitly in tests`);for(let d=0;d<h.fieldNames.length;d++){const f=h.fieldTypes[d],p=n(h.componentId,d,f);u[d]=p,this._flatColumns[o++]=p}this.columnGroups[l]={layout:h,columns:u},this._columnIds.push(l),this._changedTick[l]=0}}this.hasColumns=this._columnIds.length>0,this.materializesRows=!t.isEmpty()}static fromColumnStore(e,t,s,r,n){const o=r.archetypes.get(n);if(!o)throw new i.ECSError(i.ECS_ERROR.COMPONENT_NOT_REGISTERED,`ColumnStore has no archetype ${n}`);const a=(l,u)=>{const d=o.columns.get(i.columnKey(l,u));if(!d)throw new i.ECSError(i.ECS_ERROR.COMPONENT_NOT_REGISTERED,`ColumnStore archetype ${n} has no column for (${l}, ${u})`);return new pe(d.view)},h=new ue(e,t,s,o.rowCapacity,a);return h._storeArchetypeId=n,h}get isBufferBacked(){return this._storeArchetypeId!==null}refreshViews(e){if(this._storeArchetypeId===null)throw new i.ECSError(i.ECS_ERROR.COMPONENT_NOT_REGISTERED,`Archetype ${this.id} is not SAB-backed`);const t=e.archetypes.get(this._storeArchetypeId);if(!t)throw new i.ECSError(i.ECS_ERROR.COMPONENT_NOT_REGISTERED,`new ColumnStore has no archetype ${this._storeArchetypeId}`);const s=t.columnsInOrder,r=this._flatColumns;for(let n=0;n<s.length;n++)if(!(r[n]instanceof pe))throw new i.ECSError(i.ECS_ERROR.COMPONENT_NOT_REGISTERED,`Archetype ${this.id} column at index ${n} is not SAB-backed (internal)`);for(let n=0;n<s.length;n++)r[n].refreshView(s[n].view)}get entityCount(){return ie?this.length:this.enabledCount}get totalCount(){return this.length}get disabledCount(){return this.length-this.enabledCount}get entityIds(){return this._entityIds.buf}swapRows(e,t){if(e===t)return;const s=this._entityIds.buf,r=s[e];s[e]=s[t],s[t]=r;const n=this._flatColumns;for(let o=0;o<n.length;o++){const a=n[o].buf,h=a[e];a[e]=a[t],a[t]=h}}_placeTail(e,t){const s=this.enabledCount;if(s===e)return this.enabledCount=e+1,e;if(t===void 0)throw Xe();if(this.swapRows(s,e),t!==void 0){const r=this._entityIds.buf;t[i.getEntityIndex(r[e])]=e}return this.enabledCount=s+1,s}_placeTailBulk(e,t){if(this.enabledCount!==e)throw Ee();return this.enabledCount+=t,e}disableRow(e,t){if(this._iterDepth>0)throw U("disable");const s=this.enabledCount-1;if(e!==s){this.swapRows(e,s);const r=this._entityIds.buf;t[i.getEntityIndex(r[e])]=e,t[i.getEntityIndex(r[s])]=s}this.enabledCount=s}enableRow(e,t){if(this._iterDepth>0)throw U("enable");const s=this.enabledCount;if(e!==s){this.swapRows(e,s);const r=this._entityIds.buf;t[i.getEntityIndex(r[e])]=e,t[i.getEntityIndex(r[s])]=s}this.enabledCount=s+1}removeRow(e,t){if(this._iterDepth>0)throw U("removeRow");if(this.enabledCount===this.length){const s=this._entityIds.buf,r=this.length-1;if(e!==r){if(s[e]=s[r],this.hasColumns){const n=this._flatColumns;for(let o=0;o<n.length;o++)n[o].swapRemove(e)}t[i.getEntityIndex(s[e])]=e}else if(this.hasColumns){const n=this._flatColumns;for(let o=0;o<n.length;o++)n[o].pop()}this._entityIds.pop(),this.length=r,this.enabledCount=r;return}this._removeRowPartitioned(e,t)}_removeRowPartitioned(e,t){const s=this._entityIds.buf,r=this.hasColumns,n=this.enabledCount,o=this.length-1;if(e>=n){if(e!==o){if(s[e]=s[o],r){const h=this._flatColumns;for(let l=0;l<h.length;l++)h[l].swapRemove(e)}t[i.getEntityIndex(s[e])]=e}else if(r){const h=this._flatColumns;for(let l=0;l<h.length;l++)h[l].pop()}this._entityIds.pop(),this.length--;return}const a=n-1;if(e!==a&&(this.swapRows(e,a),t[i.getEntityIndex(s[e])]=e),a!==o){if(s[a]=s[o],r){const h=this._flatColumns;for(let l=0;l<h.length;l++)h[l].swapRemove(a)}t[i.getEntityIndex(s[a])]=a}else if(r){const h=this._flatColumns;for(let l=0;l<h.length;l++)h[l].pop()}this._entityIds.pop(),this.length--,this.enabledCount=a}get entityList(){return this._entityIds.view()}hasComponent(e){return this.mask.has(e)}matches(e){return this.mask.contains(e)}getColumnRead(e,t){const s=e.id;if(i.accessCheck.checkRead(e),this._colOffset[s]===void 0)throw new i.ECSError(i.ECS_ERROR.COMPONENT_NOT_REGISTERED,`Component ${e} not in archetype ${this.id}`);const r=this._fieldIndex[s][t];if(r===void 0)throw new i.ECSError(i.ECS_ERROR.COMPONENT_NOT_REGISTERED,`Field "${t}" does not exist on component`);return this._flatColumns[this._colOffset[s]+r].buf}getColumnsRead(e,...t){return t.map(r=>this.getColumnRead(e,r))}getOptionalColumnRead(e,t){const s=e.id;i.accessCheck.checkRead(e),i.accessCheck.checkOptionalFetch(e);const r=this._colOffset[s];if(r===void 0)return;const n=this._fieldIndex[s][t];if(n===void 0)throw new i.ECSError(i.ECS_ERROR.COMPONENT_NOT_REGISTERED,`Field "${t}" does not exist on component`);return this._flatColumns[r+n].buf}getColumn(e,t,s){const r=e.id;if(i.accessCheck.checkWrite(e),this._colOffset[r]===void 0)throw new i.ECSError(i.ECS_ERROR.COMPONENT_NOT_REGISTERED,`Component ${e} not in archetype ${this.id}`);this._changedTick[r]=s;const n=this._fieldIndex[r][t];if(n===void 0)throw new i.ECSError(i.ECS_ERROR.COMPONENT_NOT_REGISTERED,`Field "${t}" does not exist on component`);return this._flatColumns[this._colOffset[r]+n].buf}columnGroupMut(e,t){const s=e.id;if(i.accessCheck.checkWrite(e),this._colOffset[s]===void 0)throw new i.ECSError(i.ECS_ERROR.COMPONENT_NOT_REGISTERED,`Component ${e} not in archetype ${this.id}`);this._changedTick[s]=t;const r=this._colOffset[s],n=this._fieldNames[s],o=this._flatColumns;let a=this._mutGroupCache[s];a===void 0&&(a={},this._mutGroupCache[s]=a);for(let h=0;h<n.length;h++)a[n[h]]=o[r+h].buf;return a}columnGroupRead(e){const t=e.id;if(i.accessCheck.checkRead(e),this._colOffset[t]===void 0)throw new i.ECSError(i.ECS_ERROR.COMPONENT_NOT_REGISTERED,`Component ${e} not in archetype ${this.id}`);const s=this._colOffset[t],r=this._fieldNames[t],n=this._flatColumns;let o=this._readGroupCache[t];o===void 0&&(o={},this._readGroupCache[t]=o);for(let a=0;a<r.length;a++)o[r[a]]=n[s+a].buf;return o}writeFields(e,t,s,r){const n=t,o=this._colOffset[n];if(o===void 0)return;this._changedTick[n]=r;const a=this._fieldNames[n],h=this._flatColumns;for(let l=0;l<a.length;l++)h[o+l].buf[e]=s[a[l]]??0}bulkWriteFields(e,t,s,r,n){const o=s,a=this._colOffset[o];if(a===void 0)return;this._changedTick[o]=n;const h=this._fieldNames[o],l=this._flatColumns,u=e+t;for(let d=0;d<h.length;d++)l[a+d].buf.fill(r[h[d]]??0,e,u)}writeFieldsPositional(e,t,s,r){const n=t,o=this._colOffset[n];if(o===void 0)return;this._changedTick[n]=r;const a=this._flatColumns;for(let h=0;h<s.length;h++)a[o+h].buf[e]=s[h]}readField(e,t,s){const r=t,n=this._colOffset[r];if(n===void 0)throw new i.ECSError(i.ECS_ERROR.COMPONENT_NOT_REGISTERED,`readField: component ${r} has no column in this archetype — the entity doesn't hold it`,{component:r,field:s});const o=this._fieldIndex[r][s];if(o===void 0)throw new i.ECSError(i.ECS_ERROR.FIELD_NOT_REGISTERED,`readField: component ${r} has no field "${s}" — check the schema passed to registerComponent`,{component:r,field:s});return this._flatColumns[n+o].buf[e]}copySharedFrom(e,t,s,r){const n=e._colOffset,o=e._fieldCount,a=e._flatColumns,h=this._flatColumns,l=this._columnIds;for(let u=0;u<l.length;u++){const d=l[u],f=n[d];if(f===void 0)continue;this._changedTick[d]=r;const p=this._colOffset[d],g=o[d];for(let E=0;E<g;E++)h[p+E].buf[s]=a[f+E].buf[t]}}addEntity(e,t){if(!this.materializesRows)throw M();const s=this._flatColumns;s.length>0&&this.length>=s[0].buf.length&&this.growHandler!==null&&this.growHandler(this,1);const r=this.length;this._entityIds.push(e);for(let n=0;n<s.length;n++)s[n].push(0);return this.length++,this._placeTail(r,t)}removeEntity(e){const t=this.length-1;let s=i.NO_SWAP;const r=this._flatColumns,n=this._entityIds.buf;if(e!==t){n[e]=n[t],s=i.getEntityIndex(n[e]);for(let o=0;o<r.length;o++)r[o].swapRemove(e)}else for(let o=0;o<r.length;o++)r[o].pop();return this._entityIds.pop(),this.length--,e<this.enabledCount&&this.enabledCount--,s}addEntityTag(e,t){if(!this.materializesRows)throw M();const s=this.length;return this._entityIds.push(e),this.length++,this._placeTail(s,t)}addEntities(e,t=e.length){if(t===0)return this.length;if(!this.materializesRows)throw M();const s=this._flatColumns;s.length>0&&this.length+t>s[0].buf.length&&this.growHandler!==null&&this.growHandler(this,t);const r=this.length;this._entityIds.bulkAppend(e,0,t);for(let n=0;n<s.length;n++)s[n].bulkAppendZeroes(t);return this.length+=t,this._placeTailBulk(r,t)}addEntitiesTag(e,t=e.length){if(t===0)return this.length;if(!this.materializesRows)throw M();const s=this.length;return this._entityIds.bulkAppend(e,0,t),this.length+=t,this._placeTailBulk(s,t)}ensureRowCapacity(e){const t=this._flatColumns;t.length>0&&this.length+e>t[0].buf.length&&this.growHandler!==null&&this.growHandler(this,e)}addEntityWithValues(e,t,s,r){if(!this.materializesRows)throw M();const n=this._flatColumns;n.length>0&&this.length>=n[0].buf.length&&this.growHandler!==null&&this.growHandler(this,1);const o=this.length;this._entityIds.push(e);for(let h=0;h<n.length;h++)n[h].push(t[h]);this.length++;const a=this._columnIds;for(let h=0;h<a.length;h++)this._changedTick[a[h]]=s;return this._placeTail(o,r)}addEntitiesWithValues(e,t,s,r){if(t===0)return this.length;if(!this.materializesRows)throw M();const n=this._flatColumns;n.length>0&&this.length+t>n[0].buf.length&&this.growHandler!==null&&this.growHandler(this,t);const o=this.length;this._entityIds.bulkAppend(e,0,t);for(let h=0;h<n.length;h++)n[h].bulkAppendValue(s[h],t);this.length+=t;const a=this._columnIds;for(let h=0;h<a.length;h++)this._changedTick[a[h]]=r;return this._placeTailBulk(o,t)}removeEntityTag(e){const t=this.length-1;let s=i.NO_SWAP;const r=this._entityIds.buf;return e!==t&&(r[e]=r[t],s=i.getEntityIndex(r[e])),this._entityIds.pop(),this.length--,e<this.enabledCount&&this.enabledCount--,s}moveEntityFrom(e,t,s,r,n,o){if(e._iterDepth>0)throw U("moveEntityFrom");const a=t>=e.enabledCount;if(!this.materializesRows){e.removeRow(t,o),b[0]=i.UNASSIGNED,b[1]=i.NO_SWAP;return}const h=this._flatColumns;h.length>0&&this.length>=h[0].buf.length&&this.growHandler!==null&&this.growHandler(this,1);const l=this.length;this._entityIds.push(s);const u=e._flatColumns;for(let p=0;p<h.length;p++){const g=r[p];h[p].push(g>=0?u[g].buf[t]:0)}const d=this._columnIds;for(let p=0;p<d.length;p++)this._changedTick[d[p]]=n;this.length++;const f=a?l:this._placeTail(l,o);e.removeRow(t,o),b[0]=f,b[1]=i.NO_SWAP}moveEntityFromTag(e,t,s,r){if(e._iterDepth>0)throw U("moveEntityFrom");const n=t>=e.enabledCount;if(!this.materializesRows){e.removeRow(t,r),b[0]=i.UNASSIGNED,b[1]=i.NO_SWAP;return}const o=this.length;this._entityIds.push(s),this.length++;const a=n?o:this._placeTail(o,r);e.removeRow(t,r),b[0]=a,b[1]=i.NO_SWAP}bulkMoveAllFrom(e,t,s){const r=e.length;if(r===0)return this.length;if(!this.materializesRows)throw M();const n=this._flatColumns;n.length>0&&this.length+r>n[0].buf.length&&this.growHandler!==null&&this.growHandler(this,r);const o=this.length,a=e._flatColumns;this._entityIds.bulkAppend(e._entityIds.buf,0,r);for(let l=0;l<n.length;l++){const u=t[l];u>=0?n[l].bulkAppend(a[u].buf,0,r):n[l].bulkAppendZeroes(r)}const h=this._columnIds;for(let l=0;l<h.length;l++)this._changedTick[h[l]]=s;if(this.length+=r,this.enabledCount!==o)throw Ee();return this.enabledCount=o+e.enabledCount,e.clearRows(),o}clearRows(){this.length=0,this.enabledCount=0,this._entityIds.clear();const e=this._flatColumns;for(let t=0;t<e.length;t++)e[t].clear()}restoreHostRows(e,t){const s=e.length;if(t<0||t>s)throw new i.ECSError(i.ECS_ERROR.COMPONENT_NOT_REGISTERED,`Archetype ${this.id}: restore enabledCount ${t} out of range [0, ${s}]`);this._entityIds.clear(),this._entityIds.ensureCapacity(s);for(let n=0;n<s;n++)this._entityIds.push(e[n]);const r=this._flatColumns;for(let n=0;n<r.length;n++)r[n].setLength(s);this.length=s,this.enabledCount=t}getEdge(e){return this.edges[e]}setEdge(e,t){this.edges[e]=t}getBatchTransitionMap(e){const t=this.batchTransitionMaps.get(e.id);if(t!==void 0)return t;const s=oe(this,e);return this.batchTransitionMaps.set(e.id,s),s}getCompositeAddEdge(e){return this.compositeAddEdges===null?void 0:this.compositeAddEdges.get(e)}cacheCompositeAddEdge(e,t,s){(this.compositeAddEdges??=new Map).set(e,{target:t,map:s})}}const b=[0,i.NO_SWAP];let ie=!1;function N(c){const e=ie;return ie=c,e}function M(){return new i.ECSError(i.ECS_ERROR.EMPTY_ARCHETYPE_MATERIALIZE,"the empty archetype must not materialise rows: a component-less entity is unplaced (entity_row === UNASSIGNED). A Store mutation path is missing its rowless-destination branch.")}function U(c){return new i.ECSError(i.ECS_ERROR.STRUCTURAL_DURING_ITERATION,`${c} hit an archetype a live query iteration is visiting — immediate structural mutation mid-walk relocates rows under the iterator (entities get skipped or visited twice). Collect ids during the walk and mutate after it; inside a system use the deferred ctx.commands.`)}function Xe(){return new i.ECSError(i.ECS_ERROR.PARTITION_APPEND_NEEDS_ENTITY_ROW,"appending into a disabled-bearing archetype requires the entity_row map (to repoint the displaced disabled row). A Store append path is missing its entity_row argument.")}function Ee(){return new i.ECSError(i.ECS_ERROR.PARTITION_BULK_INTO_DISABLED,"bulk append/move into a disabled-bearing archetype is unsupported — the caller must fall back to per-entity placement to keep the enabled prefix contiguous.")}function oe(c,e){const t=e._flatColumns,s=new Int16Array(t.length),r=e._columnIds,n=c._colOffset,o=e._colOffset,a=e._fieldCount;for(let h=0;h<r.length;h++){const l=r[h],u=o[l],d=a[l],f=n[l];if(f!==void 0)for(let p=0;p<d;p++)s[u+p]=f+p;else for(let p=0;p<d;p++)s[u+p]=-1}return s}const ke=c=>i.validateAndCast(c,i.isNonNegativeInteger,"SystemID must be a non-negative integer"),V=Object.freeze([]);function ge(c){return typeof c=="object"&&!Array.isArray(c)}function Ze(c){let e=V;c.spawns!==void 0&&c.spawns.length>0&&(e=c.spawns.map(s=>ge(s)?s.defs:s));let t=V;if(c.despawns!==void 0&&c.despawns.length>0){const s=[];for(const r of c.despawns)ge(r)?s.push(...r.defs):s.push(r);t=s}return{reads:c.reads,writes:c.writes,spawns:e,despawns:t,transitions:c.transitions??V,resourceReads:c.resourceReads??V,resourceWrites:c.resourceWrites??V,sparseReads:c.sparseReads,sparseWrites:c.sparseWrites,relationReads:c.relationReads,relationWrites:c.relationWrites}}function Je(c){const e=c.queries;if(e===void 0||c.exclusive===!0)return;const t=new Set;for(const n of c.reads)t.add(n.id);for(const n of c.writes)t.add(n.id);const s=new Set;for(const n of e)for(const o of n)t.has(o.id)||s.add(o.id);if(s.size===0)return;const r=c.name!==void 0?`'${c.name}' `:"";throw new i.ECSError(i.ECS_ERROR.QUERY_ACCESS_UNDECLARED,`system ${r}declares queries over component id(s) [${[...s].join(", ")}] not in reads ∪ writes. A query term reads each listed component, so add the id(s) to 'reads' (or to 'writes' if the system also mutates them).`)}const ae=Object.freeze({reads:Object.freeze([]),writes:Object.freeze([]),spawns:Object.freeze([]),despawns:Object.freeze([]),transitions:Object.freeze([]),resourceReads:Object.freeze([]),resourceWrites:Object.freeze([]),sparseReads:Object.freeze([]),sparseWrites:Object.freeze([]),relationReads:Object.freeze([]),relationWrites:Object.freeze([])}),et=Symbol.dispose??Symbol.for("Symbol.dispose"),ee=(1<<20)-1;let tt=0;function st(c,e){const t={...ae,...e,id:ke(tt++),name:c,fn:rt};return Object.freeze(t)}function rt(){}function ye(c){const e=new Set;if(c)for(let t=0;t<c.length;t++)e.add(c[t].id);return e}function nt(c){const e=(o,a)=>o.cid-a.cid||o.id-a.id,t=new Map,s=new Map;for(const o of c)t.set(o,[]),s.set(o,0);for(const o of c)if(o.writes.size!==0)for(const a of c){if(o===a)continue;let h=!1;for(const l of o.writes)if(a.reads.has(l)){h=!0;break}h&&(t.get(o).push(a),s.set(a,s.get(a)+1))}const r=c.filter(o=>s.get(o)===0).sort(e),n=[];for(;r.length>0;){const o=r.shift();n.push(o);for(const a of t.get(o)){const h=s.get(a)-1;s.set(a,h),h===0&&(r.push(a),r.sort(e))}}if(n.length!==c.length){const o=new Set(n);for(const a of c.slice().sort(e))o.has(a)||n.push(a)}return n}class it{constructor(e,t){this.store=e,this.ctx=t}entries=[];byCid=new Map;_topo=null;_addBuckets=new Map;_remBuckets=new Map;_disBuckets=new Map;_enaBuckets=new Map;_radixOut=[];_radixC0=new Int32Array(1024);_radixC1=new Int32Array(1024);_setDrainCache=new Map;get count(){return this.entries.length}descriptors(){const e=new Array(this.entries.length);for(let t=0;t<this.entries.length;t++)e[t]=this.entries[t].descriptor;return e}register(e,t){const s=e.id,r=t.granularity??"archetype",n=t.onSet!==void 0&&r==="entity",o=t.onSet!==void 0&&r!=="entity";if(t.onSet===void 0&&t.granularity!==void 0)throw new i.ECSError(i.ECS_ERROR.OBSERVER_INVALID_CONFIG,"observe(): `granularity` is meaningless without `onSet`");if(t.onAdd===void 0&&t.onRemove===void 0&&t.onDisable===void 0&&t.onEnable===void 0&&t.onSet===void 0)throw new i.ECSError(i.ECS_ERROR.OBSERVER_INVALID_CONFIG,"observe(): at least one of onAdd / onRemove / onDisable / onEnable / onSet is required");const a=t.access??{},h=st(t.name??`observer(${i.componentDebugName(e)??s})`,a),l={id:h.id,cid:s,def:e,onAdd:t.onAdd,onRemove:t.onRemove,onDisable:t.onDisable,onEnable:t.onEnable,onSetEntity:n?t.onSet:void 0,onSetArch:o?t.onSet:void 0,descriptor:h,writes:ye(a.writes),reads:ye(a.reads),yieldExisting:t.yieldExisting??!1,lastSetTick:0,disposed:!1};this.entries.push(l);let u=this.byCid.get(s);u===void 0&&(u=[],this.byCid.set(s,u)),u.push(l),this._topo=null,this._reconfigureComponent(s),l.yieldExisting&&l.onAdd!==void 0&&this._yieldExisting(l);const d=()=>this._dispose(l);return{dispose:d,[et]:d}}_dispose(e){if(e.disposed)return;e.disposed=!0;const t=this.entries.indexOf(e);t>=0&&this.entries.splice(t,1);const s=this.byCid.get(e.cid);if(s!==void 0){const r=s.indexOf(e);r>=0&&s.splice(r,1),s.length===0&&this.byCid.delete(e.cid)}this._topo=null,this._reconfigureComponent(e.cid)}_reconfigureComponent(e){const t=this.byCid.get(e);let s=!1,r=!1,n=!1,o=!1,a=!1;if(t!==void 0)for(let h=0;h<t.length;h++){const l=t[h];l.onAdd!==void 0&&(s=!0),l.onRemove!==void 0&&(r=!0),l.onDisable!==void 0&&(n=!0),l.onEnable!==void 0&&(o=!0),l.onSetEntity!==void 0&&(a=!0)}this.store._configureComponentObservation(e,s,r,n,o,a)}getTopo(){return this._topo===null&&(this._topo=nt(this.entries)),this._topo}dispatchStructural(e){this._bucket(e.addComp,e.addEid,e.addLen,this._addBuckets),this._bucket(e.remComp,e.remEid,e.remLen,this._remBuckets),this._bucket(e.disComp,e.disEid,e.disLen,this._disBuckets),this._bucket(e.enaComp,e.enaEid,e.enaLen,this._enaBuckets);const t=this.getTopo(),s=i.accessCheck.current();for(let r=0;r<t.length;r++){const n=t[r];if(!n.disposed){if(n.onRemove!==void 0){const o=this._remBuckets.get(n.cid);o!==void 0&&o.length>0&&this._fireEach(n,n.onRemove,o,"remove")}if(n.onAdd!==void 0){const o=this._addBuckets.get(n.cid);o!==void 0&&o.length>0&&this._fireEach(n,n.onAdd,o,"add")}if(n.onDisable!==void 0){const o=this._disBuckets.get(n.cid);o!==void 0&&o.length>0&&this._fireEach(n,n.onDisable,o,"disable")}if(n.onEnable!==void 0){const o=this._enaBuckets.get(n.cid);o!==void 0&&o.length>0&&this._fireEach(n,n.onEnable,o,"enable")}}}s!==null&&i.accessCheck.enter(s),this._clearBuckets(this._addBuckets),this._clearBuckets(this._remBuckets),this._clearBuckets(this._disBuckets),this._clearBuckets(this._enaBuckets)}_fireEach(e,t,s,r){K(s,this._radixOut,this._radixC0,this._radixC1),i.accessCheck.enter(e.descriptor);try{const n=I?this.store._trace:null;for(let o=0;o<s.length;o++)t(i.unsafeCast(s[o]),this.ctx),I&&n?.observerFired(r,e.cid,s[o],e.descriptor)}finally{i.accessCheck.leave()}}_bucket(e,t,s,r){for(let n=0;n<s;n++){const o=e[n];let a=r.get(o);a===void 0&&(a=[],r.set(o,a)),a.push(t[n])}}_clearBuckets(e){for(const t of e.values())t.length=0}dispatchSet(e){if(this.entries.length===0)return;const t=i.accessCheck.current(),s=this.getTopo(),r=this._setDrainCache;for(let n=0;n<s.length;n++){const o=s[n];o.onSetEntity!==void 0?this._dispatchSetEntity(o,r):o.onSetArch!==void 0&&this._dispatchSetArch(o,e)}for(const n of r.values())n.length=0;r.clear(),t!==null&&i.accessCheck.enter(t)}_dispatchSetEntity(e,t){let s=t.get(e.cid);if(s===void 0&&(s=this.store._takeDirty(e.cid),K(s,this._radixOut,this._radixC0,this._radixC1),t.set(e.cid,s)),s.length===0)return;const r=e.def,n=e.onSetEntity;i.accessCheck.enter(e.descriptor);try{for(let o=0;o<s.length;o++){const a=i.unsafeCast(s[o]);this.store.isAlive(a)&&this.store.hasComponent(a,r)&&!this.store.isDisabled(a)&&(n(a,this.ctx),I&&this.store._trace?.observerFired("set",e.cid,a,e.descriptor))}}finally{i.accessCheck.leave()}}_dispatchSetArch(e,t){const s=e.onSetArch,r=e.lastSetTick;i.accessCheck.enter(e.descriptor);try{this.store._forEachChangedArchetype(e.cid,r,n=>{s(n,this.ctx),I&&this.store._trace?.observerFired("set",e.cid,-1,e.descriptor)})}finally{i.accessCheck.leave()}e.lastSetTick=t+1}_yieldExisting(e){const t=e.onAdd,s=this.store._collectEntitiesWithComponent(e.cid);if(s.length===0)return;K(s,this._radixOut,this._radixC0,this._radixC1);const r=i.accessCheck.current();i.accessCheck.enter(e.descriptor);try{for(let n=0;n<s.length;n++)t(i.unsafeCast(s[n]),this.ctx)}finally{i.accessCheck.leave(),r!==null&&i.accessCheck.enter(r)}}}function K(c,e,t,s){const r=c.length;if(!(r<2)){e.length<r&&(e.length=r),t.fill(0),s.fill(0);for(let n=0;n<r;n++){const o=c[n]ⅇt[o&1023]++,s[o>>10&1023]++}for(let n=1;n<1024;n++)t[n]+=t[n-1],s[n]+=s[n-1];for(let n=r-1;n>=0;n--){const o=c[n];e[--t[o&ee&1023]]=o}for(let n=r-1;n>=0;n--){const o=e[n];c[--s[(o&ee)>>10&1023]]=o}}}class ot{constructor(e){this.host=e}relations=[];_hasTargetCleanup=!1;_hierarchyRadixOut=[];_hierarchyRadixC0=new Int32Array(1024);_hierarchyRadixC1=new Int32Array(1024);get stores(){return this.relations}get count(){return this.relations.length}get hasTargetCleanup(){return this._hasTargetCleanup}registerRelation(e){const t=e?.multi===!0,s=e?.exclusive===!0;if(t&&s)throw new i.ECSError(i.ECS_ERROR.RELATION_MODE_INVALID,"register_relation: a relation cannot be both exclusive and multi-target");const r=!t,n=e?.onDeleteTarget??i.DEFAULT_ON_DELETE_TARGET,o=r?this.host.pushSparseStore([i.RELATION_TARGET_FIELD],["f64"]):this.host.pushSparseStore([],[]),a=this.relations.length;return this.relations.push(i.makeRelationStore(r,o,this.host.sparseStoreOf(o),n)),n!=="orphan"&&(this._hasTargetCleanup=!0),i.unsafeCast(a)}relationOf(e){const t=e,s=this.relations[t];if(s===void 0)throw new i.ECSError(i.ECS_ERROR.RELATION_NOT_REGISTERED,`relation ${t} is not registered`);return s}addRelation(e,t,s){const r=this.relationOf(t);if(!this.host.isAlive(e))throw i.entityNotAliveError("addRelation",e,"source");if(!this.host.isAlive(s))throw i.entityNotAliveError("addRelation",s,"target");r.link(e,s)}removeRelation(e,t,s){const r=this.relationOf(t);if(!this.host.isAlive(e))throw i.entityNotAliveError("removeRelation",e,"source");r.unlink(e,s)}targetOf(e,t){const s=this.relationOf(t);{if(!s.exclusive)throw new i.ECSError(i.ECS_ERROR.RELATION_MODE_MISMATCH,"targetOf: relation is multi-target — use targetsOf");if(!this.host.isAlive(e))throw i.entityNotAliveError("targetOf",e)}return s.singleTarget(i.getEntityIndex(e))}targetsOf(e,t){const s=this.relationOf(t);if(!this.host.isAlive(e))throw i.entityNotAliveError("targetsOf",e);return s.targetsOf(i.getEntityIndex(e))}sourcesOf(e,t){return this.relationOf(t).sourcesOf(e)}hasRelation(e,t){return this.host.hasSparse(e,this.relationOf(t).sparse)}pairsOf(e){const t=this.relationOf(e),s=[],r=this.host.entityGenerations();return t.forEachCanonicalPair(n=>i.createEntityId(n,r[n]),(n,o)=>s.push([n,o])),s}sourcesOfAny(e){const t=[],s=this.relations;for(let r=0;r<s.length;r++){const n=i.unsafeCast(r),o=s[r].sourcesOf(e);for(let a=0;a<o.length;a++)t.push([n,o[a]])}return t}relationBackingSparseId(e){return this.relationOf(e).sparse}forEachRelationTargetMatch(e,t,s,r,n,o,a,h){const l=this.relations;if(l.length===0)return;const u=new Set;for(let y=0;y<l.length;y++){const _=l[y].sourcesOf(e);for(let m=0;m<_.length;m++)u.add(_[m])}if(u.size===0)return;const d=Array.from(u).sort((y,_)=>y-_),f=this.host.sparseStores(),p=this.host.entityArchetype(),g=this.host.entityRow(),E=this.host.archetypes();for(let y=0;y<d.length;y++){const _=i.unsafeCast(d[y]),m=i.getEntityIndex(_),S=p[m];if(S===i.UNASSIGNED)continue;const v=E[S],R=v.mask;if(!R.contains(t)||s!==null&&R.overlaps(s)||r!==null&&!R.overlaps(r))continue;let C=!0;for(let w=0;w<n.length;w++)if(!f[n[w]].has(m)){C=!1;break}if(C){for(let w=0;w<o.length;w++)if(f[o[w]].has(m)){C=!1;break}if(C){if(!a){const w=g[m];if(w!==i.UNASSIGNED&&w>=v.enabledCount)continue}h(_)}}}}compactRelations(){const e=this.relations;if(e.length===0)return 0;const t=r=>this.host.isAlive(r);let s=0;for(let r=0;r<e.length;r++)s+=e[r].pruneDeadReverse(t);return s}ancestorsOf(e,t){const s=this.relationOf(t);{if(!s.exclusive)throw new i.ECSError(i.ECS_ERROR.RELATION_MODE_MISMATCH,"ancestorsOf: relation is multi-target — traversal needs an exclusive (parent) chain");if(!this.host.isAlive(e))throw i.entityNotAliveError("ancestorsOf",e)}const r=this.host.sparseStoreOf(s.sparse),n=[e],o=new Set([i.getEntityIndex(e)]);let a=e;for(;;){const h=r.getField(i.getEntityIndex(a),0);if(h===void 0)break;const l=i.unsafeCast(h);if(!this.host.isAlive(l)){n.push(l);break}const u=i.getEntityIndex(l);if(o.has(u))throw new i.ECSError(i.ECS_ERROR.RELATION_CYCLE,`ancestors_of: cycle in relation chain at entity index ${u}`);o.add(u),a=l,n.push(a)}return n}rootOf(e,t){const s=this.ancestorsOf(e,t);return s[s.length-1]}cascadeOf(e,t){const s=this.relationOf(t);{if(!s.exclusive)throw new i.ECSError(i.ECS_ERROR.RELATION_MODE_MISMATCH,"cascadeOf: relation is multi-target — traversal needs an exclusive (parent) chain");if(!this.host.isAlive(e))throw i.entityNotAliveError("cascadeOf",e)}const r=[e],n=new Set([i.getEntityIndex(e)]);for(let o=0;o<r.length;o++){const a=s.sourcesOf(r[o]);for(let h=0;h<a.length;h++){const l=a[h],u=i.getEntityIndex(l);if(n.has(u))throw new i.ECSError(i.ECS_ERROR.RELATION_CYCLE,`cascade_of: cycle in relation chain at entity index ${u}`);n.add(u),r.push(l)}}return r}purgeSource(e){const t=this.relations;for(let s=0;s<t.length;s++)t[s].purgeSource(e)}cleanupTarget(e,t){const s=this.relations;for(let r=0;r<s.length;r++){const n=s[r];if(n.onDeleteTarget==="orphan")continue;const o=n.sourcesOf(e);if(o.length!==0){if(n.onDeleteTarget==="delete"){for(let a=0;a<o.length;a++)t.push(o[a]);continue}for(let a=0;a<o.length;a++)n.unlink(o[a],e)}}}forEachHierarchyMatch(e,t,s,r,n,o,a,h,l,u){const d=this.relationOf(a);if(!d.exclusive)throw new i.ECSError(i.ECS_ERROR.RELATION_MODE_MISMATCH,"hierarchy(): relation is multi-target — depth ordering needs an exclusive (parent) chain");const f=[];if(this.host.forEachSparseMatch(e,t,s,r,n,o,_=>f.push(_),l),f.length===0)return;K(f,this._hierarchyRadixOut,this._hierarchyRadixC0,this._hierarchyRadixC1);const p=this.host.sparseStoreOf(d.sparse),g=new Map,E=new Set,y=[];for(let _=0;_<f.length;_++){const m=f[_],S=this._hierarchyDepthOf(i.getEntityIndex(m),p,g,E);if(S>h)continue;let v=y[S];v===void 0&&(v=[],y[S]=v),v.push(m)}for(let _=0;_<y.length;_++){const m=y[_];if(m!==void 0)for(let S=0;S<m.length;S++)u(m[S])}}_hierarchyDepthOf(e,t,s,r){const n=[];let o=e,a=0;for(;;){const l=s.get(o);if(l!==void 0){a=l;break}const u=t.getField(o,0);let d=-1;if(u!==void 0){const f=i.unsafeCast(u);this.host.isAlive(f)&&(d=i.getEntityIndex(f))}if(d===-1){s.set(o,0),a=0;break}if(r.has(d))throw new i.ECSError(i.ECS_ERROR.RELATION_CYCLE,`hierarchy(): cycle in relation chain at entity index ${d}`);n.push(o),r.add(o),o=d}let h=a;for(let l=n.length-1;l>=0;l--)h+=1,s.set(n[l],h),r.delete(n[l]);return s.get(e)}}class at{_generations;_lengthView;_highWater=0;_freeIndices=[];_aliveCount=0;_capacity;lastIndex=0;constructor(e,t,s){this._capacity=e,this._generations=t,this._lengthView=s}replantViews(e,t){this._generations=e,this._lengthView=t}get generations(){return this._generations}get highWater(){return this._highWater}get aliveCount(){return this._aliveCount}get freeCount(){return this._freeIndices.length}alloc(){let e,t;if(this._freeIndices.length>0)e=this._freeIndices.pop(),t=this._generations[e];else{if(this._highWater>=this._capacity)throw new i.ECSError(i.ECS_ERROR.EID_MAX_INDEX_OVERFLOW,`entityIndexCapacity (${this._capacity}) exhausted; raise it in ECSOptions.memory or destroy unused entities`);e=this._highWater++,this._generations[e]=i.INITIAL_GENERATION,t=i.INITIAL_GENERATION,this._lengthView[0]=this._highWater}return this._aliveCount++,this.lastIndex=e,i.createEntityId(e,t)}ensureCapacity(e){const t=e-this._freeIndices.length;if(t>0&&this._highWater+t>this._capacity)throw new i.ECSError(i.ECS_ERROR.EID_MAX_INDEX_OVERFLOW,`entityIndexCapacity (${this._capacity}) cannot fit ${e} new entities (${this._freeIndices.length} free, high-water ${this._highWater}); raise it in ECSOptions.memory or destroy unused entities`)}recycle(e,t){const s=t+1;s<i.RETIRED_GENERATION?(this._generations[e]=s,this._freeIndices.push(e)):this._generations[e]=i.RETIRED_GENERATION,this._aliveCount--}isAliveIndex(e,t){return e<this._highWater&&this._generations[e]===t}publishLength(){this._lengthView[0]=this._highWater}snapshotFreeIndices(){return this._freeIndices.slice()}setHighWater(e){this._highWater=e}restoreHostState(e,t){this._freeIndices.length=0;for(let s=0;s<e.length;s++)this._freeIndices.push(e[s]);this._aliveCount=t}}const me=65536;class ht{destroyIds=[];addIds=[];addDefs=[];addValues=[];removeIds=[];removeDefs=[];toggleIds=[];toggleDisable=[];_flushing=!1;host;obsEvents;constructor(e,t){this.host=e,this.obsEvents=t}queueDestroy(e){this.destroyIds.push(e)}queueAdd(e,t,s){this.addIds.push(e),this.addDefs.push(t),this.addValues.push(s)}queueRemove(e,t){this.removeIds.push(e),this.removeDefs.push(t)}queueToggle(e,t){this.toggleIds.push(e),this.toggleDisable.push(t)}get destroyCount(){return this.destroyIds.length}get structuralCount(){return this.addIds.length+this.removeIds.length}get toggleCount(){return this.toggleIds.length}flushDestroyed(){this._flushing||this.host.applyDestroys()}flushStructural(){if(this.host.structuralObserverCount()===0&&this.host.toggleObserverCount()===0){this.addIds.length>0&&this.host.applyAdds(),this.removeIds.length>0&&this.host.applyRemoves(),this.toggleIds.length>0&&this.host.applyToggles();return}if(this._flushing)return;this._flushing=!0;const e=this.obsEvents,t=this.host.structuralObserverHook();try{let s=0;for(;this.addIds.length>0||this.removeIds.length>0||this.destroyIds.length>0||this.toggleIds.length>0;){if(++s>me)throw new i.ECSError(i.ECS_ERROR.OBSERVER_NON_CONVERGENT,`observer cascade did not converge after ${me} rounds — two observers likely enqueue each other's structural ops forever`);e.addLen=0,e.remLen=0,e.disLen=0,e.enaLen=0,this.addIds.length>0||this.removeIds.length>0?(this.addIds.length>0&&this.host.applyAdds(),this.removeIds.length>0&&this.host.applyRemoves()):this.destroyIds.length>0?this.host.applyDestroys():this.host.applyToggles(),t!==null&&(e.addLen>0||e.remLen>0||e.disLen>0||e.enaLen>0)&&t(e)}}finally{this._flushing=!1}}}function Ne(c,e){let t=c;const s=new Array(e.length);for(let r=0;r<e.length;r++){const n=e[r],o=new Array(n.columns.length);for(let a=0;a<n.columns.length;a++){const h=n.columns[a];t=i.alignUp(t,h.stride),o[a]={componentId:h.componentId,fieldId:h.fieldId,typeTag:h.typeTag,byteOff:t,stride:h.stride},t+=h.stride*n.rowCapacity}s[r]={archetypeId:n.archetypeId,componentMask:n.componentMask,rowCount:0,enabledCount:0,rowCapacity:n.rowCapacity,columns:o}}if(t>i.STORE_MAX_BYTE_OFFSET)throw new i.StoreLayoutOverflowError(t);return{descriptors:s,newTotal:t}}function xe(c,e){const t=c._allocator(e),s=t!==c.buffer?new DataView(t):c.view;return{grownBuffer:t,newView:s}}function Me(c){return c.buffer instanceof ArrayBuffer?c.view.getUint32(i.STORE_HEADER_OFFSETS.capacity,!0):c.buffer.byteLength}function ct(c){const e={};for(let r=0;r<i.STORE_PREFIX_REGIONS.length;r++){const n=i.STORE_PREFIX_REGIONS[r],o=c.view.getUint32(i.STORE_HEADER_OFFSETS[n.headerOff],!0);o!==0&&n.readOptions(c.view,o,e)}const t=i.readHeaderRegionTable(c.view);t.length>0&&(e.regions=t.map(r=>({id:r.regionId,name:`region:${r.regionId}`,bytes:r.byteLength,init:()=>{}})));const s=c.view.getUint32(i.STORE_HEADER_OFFSETS.bindings_off,!0);if(s!==0){const r=c.view.getUint32(i.STORE_HEADER_OFFSETS.layout_descriptor_off,!0);e.bindingsRegionBytes=r-s}return i.isColumnStoreInternal(c)&&c._reservedDescriptorBytes>0&&(e.reservedDescriptorBytes=c._reservedDescriptorBytes),e}function lt(c){const e=new Map;for(let r=0;r<i.STORE_PREFIX_REGIONS.length;r++){const n=i.STORE_PREFIX_REGIONS[r],o=c.view.getUint32(i.STORE_HEADER_OFFSETS[n.headerOff],!0);if(o===0)continue;const a=n.regionBytes(c.view,o);e.set(n.headerOff,new Uint8Array(c.buffer,o,a).slice())}const t=new Map,s=i.readHeaderRegionTable(c.view);for(let r=0;r<s.length;r++){const n=s[r];t.set(n.regionId,new Uint8Array(c.buffer,n.byteOffset,n.byteLength).slice())}return{mechanism:e,consumer:t}}function ut(c,e){for(const[t,s]of e.mechanism){const r=c.view.getUint32(i.STORE_HEADER_OFFSETS[t],!0);new Uint8Array(c.buffer,r,s.byteLength).set(s)}for(const[t,s]of e.consumer){const r=i.findRegionOffset(c.view,t);if(r===0)continue;new Uint8Array(c.buffer,r,s.byteLength).set(s)}}function dt(c,e){const t=new Map;for(const[s,r]of c.archetypes){const n=e.get(s)??0;if(n===0)continue;const o=[];for(let a=0;a<r.columnsInOrder.length;a++){const h=r.columnsInOrder[a],l=n*h.stride,u=new Uint8Array(l);u.set(new Uint8Array(h.view.buffer,h.view.byteOffset,l)),o.push(u)}t.set(s,o)}return t}function ft(c,e){for(const[t,s]of e){const r=c.archetypes.get(t);if(r===void 0)throw new Error(`restore_column_snapshots: new store missing archetype ${t} (internal)`);const n=r.columnsInOrder;for(let o=0;o<s.length;o++){const a=n[o].view;new Uint8Array(a.buffer,a.byteOffset,s[o].byteLength).set(s[o])}}}function Le(c,e,t,s){const r=c.view.getUint32(i.STORE_HEADER_OFFSETS.view_stamp,!0),n=dt(c,t),o=lt(c),a=ct(c),h=i.createColumnStore(e,s,a);ft(h,n),ut(h,o);const l=r+1>>>0;return h.view.setUint32(i.STORE_HEADER_OFFSETS.view_stamp,l,!0),{store:{...h,header:{...h.header,viewStamp:l}},oldViewStamp:r,newViewStamp:l}}function pt(c,e,t){const s=new Array(e.length);for(let _=0;_<e.length;_++){const m=e[_],S=c.archetypes.get(m.archetypeId);s[_]={archetypeId:m.archetypeId,componentMask:S.componentMask,rowCapacity:m.newRowCapacity,columns:S.columnsInOrder}}const{descriptors:r,newTotal:n}=Ne(Me(c),s),o=new Map;for(let _=0;_<r.length;_++)o.set(r[_].archetypeId,r[_]);const{grownBuffer:a,newView:h}=xe(c,n),l=new Uint8Array(a);for(let _=0;_<e.length;_++){const m=e[_],S=c.archetypes.get(m.archetypeId),v=o.get(m.archetypeId);for(let R=0;R<S.columnsInOrder.length;R++){const C=S.columnsInOrder[R],w=m.rowCount*C.stride;w>0&&l.copyWithin(v.columns[R].byteOff,C.byteOff,C.byteOff+w)}}let u=t;for(const[_,m]of c.archetypes){{const v=h.getUint32(u+i.ARCHETYPE_DESCRIPTOR_OFFSETS.archetype_id,!0);if(v!==_)throw new X(`descriptor cursor desync at byte ${u}: store holds archetype ${v}, expected ${_} (Map order diverged from on-store write order)`)}const S=o.get(_);S!==void 0&&i.writeArchetypeDescriptor(h,u,S),u+=i.archetypeDescriptorBytes(m.columnsInOrder.length)}const d=h.getUint32(i.STORE_HEADER_OFFSETS.view_stamp,!0),f=d+1>>>0;h.setUint32(i.STORE_HEADER_OFFSETS.view_stamp,f,!0),h.setUint32(i.STORE_HEADER_OFFSETS.capacity,n,!0);const p=i.buildArchetypeViews(a,[...o.values()]),g=new Map;for(const[_,m]of c.archetypes){const S=p.get(_);g.set(_,S??m)}const E={buffer:a,view:h,header:{...c.header,viewStamp:f,capacity:n},archetypes:g,_regionBytes:c._regionBytes,_allocator:c._allocator,_reservedDescriptorBytes:c._reservedDescriptorBytes},y=new Array(e.length);for(let _=0;_<e.length;_++)y[_]=e[_].archetypeId;return{store:E,oldViewStamp:d,newViewStamp:f,viewsPreserved:!0,grownArchetypeIds:y}}class X extends Error{constructor(e){super(e),this.name="StoreGrowError"}}function _t(c,e,t){const s=new Map;for(let u=0;u<e.archetypes.length;u++){const d=e.archetypes[u];s.set(d.archetypeId,d)}const r=[],n=[];for(const[u,d]of c.archetypes){const f=s.get(u),p=f?.newRowCapacity??d.rowCapacity;if(p<(f?.rowCount??0))throw new X(`archetype ${u}: new_row_capacity ${p} < row_count ${f?.rowCount}`);if(p<d.rowCapacity)throw new X(`archetype ${u}: shrinking from ${d.rowCapacity} to ${p} is not supported`);p>d.rowCapacity&&n.push({archetypeId:u,newRowCapacity:p,rowCount:f?.rowCount??0}),r.push({archetypeId:u,componentMask:d.componentMask,rowCapacity:p,columns:d.columnsInOrder})}const o=new Map;for(const[u,d]of c.archetypes){const p=s.get(u)?.rowCount??0;if(p>d.rowCapacity)throw new X(`archetype ${u}: row_count ${p} > old row_capacity ${d.rowCapacity}`);p>0&&o.set(u,p)}if(t?.isInPlace===!0&&i.isColumnStoreInternal(c)&&c._allocator===t&&n.length>0){const u=c.view.getUint32(i.STORE_HEADER_OFFSETS.layout_descriptor_off,!0);return pt(c,n,u)}const{store:a,oldViewStamp:h,newViewStamp:l}=Le(c,r,o,t);return{store:a,oldViewStamp:h,newViewStamp:l,viewsPreserved:!1,grownArchetypeIds:[]}}class $ extends Error{constructor(e){super(e),this.name="StoreExtendError"}}function Et(c,e,t){if(e.newArchetypes.length===0)throw new $("extend plan has no new archetypes; use grow_column_store for resizes");const s=new Set;for(let l=0;l<e.newArchetypes.length;l++){const u=e.newArchetypes[l].archetypeId;if(s.has(u))throw new $(`duplicate archetype_id ${u} in extend plan`);if(c.archetypes.has(u))throw new $(`archetype_id ${u} already exists in the SAB; use grow_column_store to resize it`);s.add(u)}const r=new Map;if(e.existing)for(let l=0;l<e.existing.length;l++){const u=e.existing[l];if(!c.archetypes.has(u.archetypeId))throw new $(`existing row_count names unknown archetype_id ${u.archetypeId}`);if(u.rowCount<0)throw new $(`archetype ${u.archetypeId}: row_count must be non-negative (got ${u.rowCount})`);if(u.rowCount>0){const d=c.archetypes.get(u.archetypeId);if(u.rowCount>d.rowCapacity)throw new $(`archetype ${u.archetypeId}: row_count ${u.rowCount} > old row_capacity ${d.rowCapacity}`)}r.set(u.archetypeId,u.rowCount)}if(t?.isInPlace===!0&&i.isColumnStoreInternal(c)&&c._allocator===t){const l=c.view.getUint32(i.STORE_HEADER_OFFSETS.layout_descriptor_off,!0);let u=0;for(const[,f]of c.archetypes)u+=i.archetypeDescriptorBytes(f.columnsInOrder.length);let d=0;for(let f=0;f<e.newArchetypes.length;f++)d+=i.archetypeDescriptorBytes(e.newArchetypes[f].columns.length);if(u+d<=c._regionBytes)return gt(c,e.newArchetypes,l,u)}const n=[];for(const[l,u]of c.archetypes)n.push({archetypeId:l,componentMask:u.componentMask,rowCapacity:u.rowCapacity,columns:u.columnsInOrder});for(let l=0;l<e.newArchetypes.length;l++)n.push(e.newArchetypes[l]);const{store:o,oldViewStamp:a,newViewStamp:h}=Le(c,n,r,t);return{store:o,oldViewStamp:a,newViewStamp:h,viewsPreserved:!1}}function gt(c,e,t,s){const r=new Array(e.length);for(let y=0;y<e.length;y++){const _=e[y];r[y]={archetypeId:_.archetypeId,componentMask:_.componentMask,rowCapacity:_.rowCapacity,columns:_.columns.map(m=>({componentId:m.componentId,fieldId:m.fieldId,typeTag:m.typeTag,stride:i.TYPE_TAG_STRIDE[m.typeTag]}))}}const{descriptors:n,newTotal:o}=Ne(Me(c),r),{grownBuffer:a,newView:h}=xe(c,o);let l=t+s;for(let y=0;y<n.length;y++)l=i.writeArchetypeDescriptor(h,l,n[y]);const u=h.getUint32(i.STORE_HEADER_OFFSETS.view_stamp,!0),d=c.archetypes.size+e.length;h.setUint32(i.STORE_HEADER_OFFSETS.archetype_count,d,!0),h.setUint32(i.STORE_HEADER_OFFSETS.capacity,o,!0);const f=u+1>>>0;h.setUint32(i.STORE_HEADER_OFFSETS.view_stamp,f,!0);const p=i.buildArchetypeViews(a,n),g=new Map;for(const[y,_]of c.archetypes)g.set(y,_);for(const[y,_]of p)g.set(y,_);return{store:{buffer:a,view:h,header:{...c.header,viewStamp:f,capacity:o,archetypeCount:d},archetypes:g,_regionBytes:c._regionBytes,_allocator:c._allocator,_reservedDescriptorBytes:c._reservedDescriptorBytes},oldViewStamp:u,newViewStamp:f,viewsPreserved:!0}}const he=810766935,J=1;class O extends Error{constructor(e){super(e),this.name="ECSRestoreError"}}const H=4;function yt(c){const e=c.freeIndices.length,t=c.archetypeRows.length,s=H*(4+e+1+t*3),r=new Uint8Array(s),n=new DataView(r.buffer);let o=0;const a=h=>{n.setUint32(o,h,!0),o+=H};a(c.tick),a(c.entityHighWater),a(c.entityAliveCount),a(e);for(let h=0;h<e;h++)a(c.freeIndices[h]);a(t);for(let h=0;h<t;h++){const l=c.archetypeRows[h];a(l.archetypeId),a(l.length),a(l.enabledCount)}return r}function mt(c){const e=new DataView(c.buffer,c.byteOffset,c.byteLength),t=c.byteLength;let s=0;const r=p=>{if(s+p>t)throw new O(`host-state truncated: need ${p} more bytes at offset ${s}, have ${t-s}`)},n=()=>{r(H);const p=e.getUint32(s,!0);return s+=H,p},o=n(),a=n(),h=n(),l=n(),u=new Array(l);for(let p=0;p<l;p++)u[p]=n();const d=n(),f=new Array(d);for(let p=0;p<d;p++){const g=n(),E=n(),y=n();f[p]={archetypeId:g,length:E,enabledCount:y}}if(s!==t)throw new O(`host-state has ${t-s} trailing bytes after the last archetype (not a canonical encoding)`);return{tick:o,entityHighWater:a,entityAliveCount:h,freeIndices:u,archetypeRows:f}}function wt(c,e,t){const s=H*5,r=new Uint8Array(s+c.length+e.length+t.length),n=new DataView(r.buffer);return n.setUint32(0,he,!0),n.setUint32(4,J,!0),n.setUint32(8,c.length,!0),n.setUint32(12,e.length,!0),n.setUint32(16,t.length,!0),r.set(c,s),r.set(e,s+c.length),r.set(t,s+c.length+e.length),r}function St(c){const e=H*5;if(c.byteLength<e)throw new O(`world snapshot too small: ${c.byteLength} bytes (frame header needs ${e})`);const t=new DataView(c.buffer,c.byteOffset,c.byteLength),s=t.getUint32(0,!0);if(s!==he)throw new O(`bad world-snapshot magic: 0x${s.toString(16).padStart(8,"0")} (expected 0x${he.toString(16).padStart(8,"0")}). A bare dense (SAB) snapshot is not a combined world snapshot — pass the bytes from ECS.snapshot(), not snapshotColumnStore().`);const r=t.getUint32(4,!0);if(r!==J)throw new O(`incompatible world-snapshot version: snapshot=${r}, build=${J}`);const n=t.getUint32(8,!0),o=t.getUint32(12,!0),a=t.getUint32(16,!0);if(e+n+o+a!==c.byteLength)throw new O(`world-snapshot frame mismatch: header declares ${e}+${n}+${o}+${a}=${e+n+o+a} bytes, buffer is ${c.byteLength}`);const h=c.byteOffset,l=c.buffer;return{dense:new Uint8Array(l,h+e,n),sparse:new Uint8Array(l,h+e+n,o),host:new Uint8Array(l,h+e+n+o,a)}}function Rt(c,e,t){if(c.byteLength<i.STORE_HEADER_BYTES)throw new O(`dense section too small: ${c.byteLength} bytes (SAB header needs ${i.STORE_HEADER_BYTES})`);const s=new DataView(c.buffer,c.byteOffset,c.byteLength),r=s.getUint32(i.STORE_HEADER_OFFSETS.magic,!0);if(r!==i.STORE_MAGIC)throw new O(`dense section bad magic: 0x${r.toString(16).padStart(8,"0")} (expected SAB magic 0x${i.STORE_MAGIC.toString(16).padStart(8,"0")})`);const n=s.getUint32(i.STORE_HEADER_OFFSETS.sim_abi_version,!0);if(n!==i.SIM_ABI_VERSION)throw new O(`dense section incompatible sim_abi_version: snapshot=${n}, build=${i.SIM_ABI_VERSION}`);const o=i.readStoreHeader(s);if(o.layoutDescriptorOff<0||o.layoutDescriptorOff>c.byteLength)throw new O(`dense layoutDescriptorOff ${o.layoutDescriptorOff} is outside the section (${c.byteLength} bytes)`);const a=o.entityIndexOff;if(a<0||a+i.ENTITY_INDEX_HEADER_BYTES>c.byteLength)throw new O(`dense entityIndexOff ${a} is outside the section (${c.byteLength} bytes)`);const h=s.getUint32(a+i.ENTITY_INDEX_HEADER_OFFSETS.capacity,!0);if(h!==t)throw new O(`entity-index capacity mismatch: live=${t}, snapshot=${h}`);let l;try{l=i.readLayoutDescriptorRegion(s,o.layoutDescriptorOff,o.archetypeCount)}catch(u){throw u instanceof RangeError?new O(`dense section layout is corrupt or truncated: a descriptor reads past the ${c.byteLength}-byte section (${u.message})`):u}if(e.size!==l.length)throw new O(`archetype-set mismatch: the live world has ${e.size} SAB archetypes, the snapshot has ${l.length}. restoreInto requires an identical archetype set (prewarm the world so its archetype set is stable, per ADR on no-lazy archetypes).`);for(let u=0;u<l.length;u++){const d=l[u],f=e.get(d.archetypeId);if(f===void 0)throw new O(`archetype-set mismatch: snapshot archetype ${d.archetypeId} is absent from the live world`);if(!Ct(f.componentMask,d.componentMask))throw new O(`archetype ${d.archetypeId} component-mask mismatch between the live world and the snapshot (different component registration)`);const p=f.columnsInOrder,g=d.columns;if(p.length!==g.length)throw new O(`archetype ${d.archetypeId} column-count mismatch: live=${p.length}, snapshot=${g.length}`);for(let E=0;E<p.length;E++)if(p[E].componentId!==g[E].componentId||p[E].fieldId!==g[E].fieldId||p[E].typeTag!==g[E].typeTag)throw new O(`archetype ${d.archetypeId} column ${E} layout mismatch: live=(c${p[E].componentId},f${p[E].fieldId},t${p[E].typeTag}), snapshot=(c${g[E].componentId},f${g[E].fieldId},t${g[E].typeTag})`)}}function Ct(c,e){if(c.length!==e.length)return!1;for(let t=0;t<c.length;t++)if(c[t]!==e[t])return!1;return!0}class vt{host;allocator;constructor(e,t){this.host=e,this.allocator=t}snapshotSparse(){const e=i.snapshotSparseStores(this.host.sparseStores()),t=i.snapshotRelations(this.host.relationStores()),s=new Uint8Array(8+e.length+t.length),r=new DataView(s.buffer);return r.setUint32(0,e.length,!0),r.setUint32(4,t.length,!0),s.set(e,8),s.set(t,8+e.length),s}restoreSparse(e){const t=new DataView(e.buffer,e.byteOffset,e.byteLength);if(e.byteLength<8)throw new i.SparseRestoreError(`sparse snapshot truncated: need 8 header bytes, have ${e.byteLength}`);const s=t.getUint32(0,!0),r=t.getUint32(4,!0);if(8+s+r!==e.byteLength)throw new i.SparseRestoreError(`sparse snapshot frame mismatch: header declares 8+${s}+${r}=${8+s+r} bytes, buffer is ${e.byteLength}`);i.restoreSparseStores(this.host.sparseStores(),e.subarray(8,8+s)),this.rebuildRelationIndices(e.subarray(8+s,8+s+r))}rebuildRelationIndices(e){const t=this.host.generations(),s=n=>i.createEntityId(n,t[n]),r=this.host.relationStores();i.restoreRelations(r,e,s);for(let n=0;n<r.length;n++)r[n].rebuildReverseFromForward(s)}snapshot(){this.host.publishRowCounts();const e=new Uint8Array(Ve(this.host.columnStore())),t=this.snapshotSparse(),s=yt(this.collectHostState());return wt(e,t,s)}collectHostState(){const e=[],t=this.host.archetypes();for(let s=0;s<t.length;s++){const r=t[s];r.isBufferBacked&&e.push({archetypeId:r.id,length:r.length,enabledCount:r.enabledCount})}return{tick:this.host.tick(),entityHighWater:this.allocator.highWater,entityAliveCount:this.allocator.aliveCount,freeIndices:this.allocator.snapshotFreeIndices(),archetypeRows:e}}restoreInto(e){const t=St(e),s=mt(t.host);Rt(t.dense,this.host.columnStore().archetypes,this.host.entityIndexCapacity()),this.assertSparseSectionMatches(t.sparse);const r=qe(t.dense,this.host.bufferAllocator());this.host.mountRestoredDense(r),this.host.reconstructHostRows(s),this.allocator.restoreHostState(s.freeIndices,s.entityAliveCount),this.host.setTick(s.tick),this.host.invalidateQueryCaches(),this.restoreSparse(t.sparse)}assertSparseSectionMatches(e){const t=new DataView(e.buffer,e.byteOffset,e.byteLength);if(e.byteLength<8)throw new i.SparseRestoreError(`sparse snapshot truncated: need 8 header bytes, have ${e.byteLength}`);const s=t.getUint32(0,!0),r=t.getUint32(4,!0);if(8+s+r!==e.byteLength)throw new i.SparseRestoreError(`sparse snapshot frame mismatch: header declares 8+${s}+${r}=${8+s+r} bytes, buffer is ${e.byteLength}`);i.validateSparseStores(this.host.sparseStores(),e.subarray(8,8+s))}}function Fe(c,e,t){const s=c.get(e);s!==void 0?s.push(t):c.set(e,[t])}class Ot{archetypes=[];componentIndex=[];archetypeMap=new Map;nextArchetypeId=0;host;constructor(e){this.host=e}get(e){if(e<0||e>=this.archetypes.length)throw new i.ECSError(i.ECS_ERROR.ARCHETYPE_NOT_FOUND,`Archetype with ID ${e} not found`);return this.archetypes[e]}getOrCreateFromMask(e){const t=e.hash(),s=this.lookup(e,t);if(s!==null)return s;const r=_e(this.nextArchetypeId++),n=this.buildLayouts(e);return this.host.extendStore([we(r,e,n,this.host.initialCapacity())]),this.install(r,e,n,t),r}createManyFromMasks(e){const t=new Array(e.length),s=[],r=[],n=[],o=[];for(let h=0;h<e.length;h++){const l=e[h],u=l.hash(),d=this.lookup(l,u);if(d!==null){t[h]=d;continue}let f=!1;for(let g=0;g<s.length;g++)if(r[g]===u&&s[g].equals(l)){t[h]=o[g],f=!0;break}if(f)continue;const p=_e(this.nextArchetypeId++);s.push(l),r.push(u),n.push(this.buildLayouts(l)),o.push(p),t[h]=p}if(s.length===0)return t;const a=new Array(s.length);for(let h=0;h<s.length;h++)a[h]=we(o[h],s[h],n[h],this.host.initialCapacity());this.host.extendStore(a);for(let h=0;h<s.length;h++)this.install(o[h],s[h],n[h],r[h]);return t}lookup(e,t){const s=this.archetypeMap.get(t);if(s===void 0)return null;for(let r=0;r<s.length;r++)if(this.archetypes[s[r]].mask.equals(e))return s[r];return null}buildLayouts(e){const t=[],s=this.host.componentMetas();return e.forEach(r=>{const n=r,o=s[n];o&&o.fieldNames.length>0&&t.push({componentId:n,fieldNames:o.fieldNames,fieldIndex:o.fieldIndex,fieldTypes:o.fieldTypes})}),t}install(e,t,s,r){const n=t.copy(),o=this.host.materialize(e,n,s);this.archetypes.push(o),Fe(this.archetypeMap,r,e),t.forEach(a=>{const h=a;let l=this.componentIndex[h];if(l===void 0&&(l=[],this.componentIndex[h]=l),l.length>0&&e<=l[l.length-1])throw new i.ECSError(i.ECS_ERROR.COMPONENT_INDEX_INVARIANT,`component_index bucket for component ${h} received archetype ${e} out of ascending order (last = ${l[l.length-1]}). Buckets are duplicate-free and ascending by construction (see install / ADR-0015) — this means install ran twice for an id, or a second writer of component_index was introduced.`);l.push(e)}),this.host.fanIntoQueries(o)}resolveAdd(e,t){const s=this.get(e);if(s.mask.has(t))return e;const r=s.getEdge(t);if(r?.add!=null)return r.add;const n=this.getOrCreateFromMask(s.mask.copyWithSet(t));return this.cacheEdge(s,this.get(n),t),n}resolveRemove(e,t){const s=this.get(e);if(!s.mask.has(t))return e;const r=s.getEdge(t);if(r?.remove!=null)return r.remove;const n=this.getOrCreateFromMask(s.mask.copyWithClear(t));return this.cacheEdge(this.get(n),s,t),n}cacheEdge(e,t,s){const r=e.getEdge(s)??{add:null,remove:null,addMap:null,removeMap:null};r.add=t.id,r.addMap=oe(e,t),e.setEdge(s,r);const n=t.getEdge(s)??{add:null,remove:null,addMap:null,removeMap:null};n.remove=e.id,n.removeMap=oe(t,e),t.setEdge(s,n)}}function we(c,e,t,s){const r=[];for(let a=0;a<t.length;a++){const h=t[a],l=h.fieldTypes;for(let u=0;u<l.length;u++)r.push({componentId:h.componentId,fieldId:u,typeTag:i.TYPED_ARRAY_TAG_TO_TYPE_TAG[l[u]]})}const n=e._words,o=new Array(i.COMPONENT_MASK_WORDS);for(let a=0;a<i.COMPONENT_MASK_WORDS;a++)o[a]=(n[a]??0)>>>0;return{archetypeId:c,componentMask:o,rowCapacity:s,columns:r}}const At=[],Se=-1,te=new DataView(new ArrayBuffer(8)),Re=129,bt=7,se=-1;class It{entityAllocator;componentMetas=[];componentCount=0;sparseStores=[];sparseNames=[];relationService;events=new Qe;archGraph;registeredQueries=[];emptyArchetypeId;entityArchetype;entityRow;_deferred;_snapshots;_tick=0;_trace=null;_structuralObserverCount=0;_toggleObserverCount=0;_obsEvents={addComp:[],addEid:[],addLen:0,remComp:[],remEid:[],remLen:0,disComp:[],disEid:[],disLen:0,enaComp:[],enaEid:[],enaLen:0};_structuralObserverHook=null;setStructuralObserverHook(e){this._structuralObserverHook=e}_collectDestroyEid=0;_collectDestroyRemoveBit=e=>{if(!this.componentMetas[e].obsRem)return;const t=this._obsEvents;t.remComp[t.remLen]=e,t.remEid[t.remLen]=this._collectDestroyEid,t.remLen++};_collectToggleEid=0;_collectDisableBit=e=>{if(!this.componentMetas[e].obsDisable)return;const t=this._obsEvents;t.disComp[t.disLen]=e,t.disEid[t.disLen]=this._collectToggleEid,t.disLen++};_collectEnableBit=e=>{if(!this.componentMetas[e].obsEnable)return;const t=this._obsEvents;t.enaComp[t.enaLen]=e,t.enaEid[t.enaLen]=this._collectToggleEid,t.enaLen++};_toggleInitial=new Map;_anyDirtyTracked=!1;_dirtyTrackedCids=[];_dirtyLists=[];_dirtyMarks=[];_rowCountsDirty=!1;_queryDirtyEpoch=0;initialCapacity;_scratchTargetMask=new T.BitSet;_columnStore;_growHandler=(e,t)=>{const s=e.id,r=this._columnStore.archetypes.get(s);if(r===void 0)throw new i.ECSError(i.ECS_ERROR.ARCHETYPE_NOT_FOUND,`grow_handler invoked on archetype ${s} which has no SAB region`);const n=r.rowCapacity,o=e.length+t;let a=n>0?n:1;for(;a<o;)a=a*2;const h=[],l=this.archGraph.archetypes;for(let d=0;d<l.length;d++){const f=l[d],p=this._columnStore.archetypes.get(f.id);p!==void 0&&h.push({archetypeId:f.id,newRowCapacity:f.id===s?a:p.rowCapacity,rowCount:f.hasColumns?f.length:0})}let u;try{u=_t(this._columnStore,{archetypes:h},this._bufferAllocator)}catch(d){throw d instanceof W.StoreCapExceededError?this._capExceededError(d):d}if(this._columnStore=u.store,u.viewsPreserved){const d=u.grownArchetypeIds;for(let f=0;f<d.length;f++){const p=this.archGet(d[f]);p.isBufferBacked&&p.refreshViews(this._columnStore)}}else for(let d=0;d<l.length;d++)l[d].isBufferBacked&&l[d].refreshViews(this._columnStore);this._handleBufferResized()};_capExceededError(e){const t=this._capContext,s=this.entityAllocator.aliveCount,r=`SAB grow refused: requested ${e.requestedBytes} bytes exceeds `+(e.capBytes!==null?`the ${e.capBytes}-byte cap.`:"the backing's ceiling.");let n;if(t===void 0)n=` The ECS holds ${s} live entities (no sizing intent declared).`;else if(t.budgetEntities!==null){const o=(s/t.budgetEntities).toFixed(1);n=` Declared ${t.intentLabel}; the ECS holds ${s} live entities (${o}× the budget) — runaway entity creation upstream, or an under-declared budget. Raise the budget only if a ${s}-entity ECS is intended.`}else n=` Declared ${t.intentLabel}; the ECS holds ${s} live entities.`;return new i.ECSError(i.ECS_ERROR.STORE_CAP_EXCEEDED,r+n+` The cap is a hard ceiling with no grow-beyond fallback (#380) — diagnose growth before raising it. Caused by: ${e.message}`)}_bufferAllocator;_capContext;_onBufferResized;constructor(e){const t=typeof e=="number"?{initialCapacity:e}:e??{};if(this.initialCapacity=t.initialCapacity??i.DEFAULT_COLUMN_CAPACITY,this._bufferAllocator=t.bufferAllocator??W.growableSabAllocator(),this._bufferAllocator.isInPlace!==!0)throw new i.ECSError(i.ECS_ERROR.INVALID_MEMORY_OPTIONS,"Store requires an in-place SAB allocator (ADR-0008): the flush loops keep writing through hoisted entity-index views across grows, so a non-in-place allocator (e.g. DEFAULT_SAB_ALLOCATOR) corrupts the entity→row mapping. Use growable_sab_allocator / wasm_memory_allocator; non-in-place allocators are snapshot/test sizing utilities only.");this._capContext=t.capContext,this._onBufferResized=t.onBufferResized,this._entityIndexCapacity=t.entityIndexCapacity??i.ENTITY_INDEX_DEFAULT_CAPACITY,this._regions=t.regions,this._bindingsRegionBytes=t.bindingsRegionBytes??0,this._deterministic=t.deterministic??!1,this._deferred=new ht({applyAdds:()=>this._flushAdds(),applyRemoves:()=>this._flushRemoves(),applyDestroys:()=>this._drainDestroyed(),applyToggles:()=>this._flushToggles(),structuralObserverCount:()=>this._structuralObserverCount,toggleObserverCount:()=>this._toggleObserverCount,structuralObserverHook:()=>this._structuralObserverHook},this._obsEvents),this.relationService=new ot({isAlive:r=>this.isAlive(r),hasSparse:(r,n)=>this.hasSparse(r,n),pushSparseStore:(r,n)=>this._pushSparseStore(r,n),sparseStoreOf:r=>this.sparseStoreOf(r),sparseStores:()=>this.sparseStores,entityGenerations:()=>this.entityAllocator.generations,entityArchetype:()=>this.entityArchetype,entityRow:()=>this.entityRow,archetypes:()=>this.archGraph.archetypes,forEachSparseMatch:(r,n,o,a,h,l,u,d)=>this._forEachSparseMatch(r,n,o,a,h,l,u,d)}),this._columnStore=i.createColumnStore([],this._bufferAllocator,{reservedDescriptorBytes:64*1024,entityIndexCapacity:this._entityIndexCapacity,eventRingCapacitySlots:i.EVENT_RING_DEFAULT_CAPACITY_SLOTS,commandRingCapacitySlots:i.COMMAND_RING_DEFAULT_CAPACITY_SLOTS,actionRingCapacitySlots:i.ACTION_RING_DEFAULT_CAPACITY_SLOTS,regions:this._regions,bindingsRegionBytes:this._bindingsRegionBytes});const s=i.buildEntityIndexViews(this._columnStore.buffer,this._columnStore.header.entityIndexOff,this._entityIndexCapacity);this.entityArchetype=s.archetypes,this.entityRow=s.rows,this.entityAllocator=new at(this._entityIndexCapacity,s.generations,new Uint32Array(this._columnStore.buffer,this._columnStore.header.entityIndexOff+i.ENTITY_INDEX_HEADER_OFFSETS.length,1)),this._snapshots=new vt({sparseStores:()=>this.sparseStores,relationStores:()=>this.relationService.stores,generations:()=>this.entityAllocator.generations,archetypes:()=>this.archGraph.archetypes,columnStore:()=>this._columnStore,bufferAllocator:()=>this._bufferAllocator,entityIndexCapacity:()=>this._entityIndexCapacity,tick:()=>this._tick,setTick:r=>{this._tick=r},publishRowCounts:()=>this.publishRowCountsToDescriptor(),mountRestoredDense:r=>this._mountRestoredDense(r),reconstructHostRows:r=>this._reconstructHostRows(r),invalidateQueryCaches:()=>{this._queryDirtyEpoch++,this._rowCountsDirty=!0}},this.entityAllocator),this.archGraph=new Ot({componentMetas:()=>this.componentMetas,initialCapacity:()=>this.initialCapacity,extendStore:r=>this._archExtendStoreWithNewSpecs(r),materialize:(r,n,o)=>this._materializeArchetype(r,n,o),fanIntoQueries:r=>this._fanIntoQueries(r)}),this.emptyArchetypeId=this.archGetOrCreateFromMask(new T.BitSet)}_entityIndexCapacity;_regions;_bindingsRegionBytes;_deterministic;get deterministic(){return this._deterministic}_requireDeterministic(e){if(!this._deterministic)throw new i.ECSError(i.ECS_ERROR.DETERMINISM_DISABLED,`${e} requires determinism — construct the Store/ECS with { deterministic: true }. The canonical-ordering determinism surface (state_hash / snapshot_sparse / restore_sparse) is opt-in; see ADR-0020.`)}_rejectNonDeterministicFields(e,t,s){if(this._deterministic)for(let r=0;r<t.length;r++){const n=t[r];if(n==="f32"||n==="f64")throw new i.ECSError(i.ECS_ERROR.NON_DETERMINISTIC_COLUMN_TYPE,`Cannot register ${s} field "${e[r]}" as "${n}" on a { deterministic: true } world: floating-point columns round differently across V8 / Bun / Zig (1-ULP IEEE-754), breaking cross-host state_hash agreement (ADR-0020). Use an integer type (e.g. "i32") — represent fractional quantities as fixed-point (Q16.16). Note the array shorthand defaults to "f64", so pass an explicit integer type there.`,{field:e[r],type:n,kind:s})}}_refreshEntityIndexViews(){const e=this._columnStore.view.getUint32(i.STORE_HEADER_OFFSETS.entity_index_off,!0),t=i.buildEntityIndexViews(this._columnStore.buffer,e,this._entityIndexCapacity);this.entityArchetype=t.archetypes,this.entityRow=t.rows,this.entityAllocator.replantViews(t.generations,new Uint32Array(this._columnStore.buffer,e+i.ENTITY_INDEX_HEADER_OFFSETS.length,1))}_handleBufferResized(){this._refreshEntityIndexViews(),this.entityAllocator.publishLength(),this._onBufferResized?.()}get columnStore(){return this._columnStore}regionOffset(e){return i.findRegionOffset(this._columnStore.view,e)}regionHandle(e){const t=i.findRegionEntry(this._columnStore.view,e);return t===null?null:{buffer:this._columnStore.buffer,view:this._columnStore.view,offset:t.byteOffset,bytes:t.byteLength}}publishRowCountsToDescriptor(){if(!this._rowCountsDirty)return;const e=this._columnStore.view;let t=e.getUint32(i.STORE_HEADER_OFFSETS.layout_descriptor_off,!0);const s=this.archGraph.archetypes;for(let r=0;r<s.length;r++){const n=s[r];if(!n.isBufferBacked)continue;const o=e.getUint32(t+i.ARCHETYPE_DESCRIPTOR_OFFSETS.column_count,!0);{const a=e.getUint32(t+i.ARCHETYPE_DESCRIPTOR_OFFSETS.archetype_id,!0);if(a!==n.id)throw new Error(`descriptor order drift: archetypes[${r}].id=${n.id} but descriptor at +${t} reports archetype_id=${a}`)}e.setUint32(t+i.ARCHETYPE_DESCRIPTOR_OFFSETS.row_count,n.hasColumns?n.length:0,!0),e.setUint32(t+i.ARCHETYPE_DESCRIPTOR_OFFSETS.enabled_count,n.hasColumns?n.enabledCount:0,!0),t+=i.ARCHETYPE_DESCRIPTOR_HEADER_BYTES+o*i.COLUMN_DESCRIPTOR_BYTES}this._rowCountsDirty=!1}stateHash(){this._requireDeterministic("state_hash()");let e=i.FNV1A_OFFSET_BASIS;const t=this.archGraph.archetypes;for(let n=0;n<t.length;n++){const o=t[n],a=o.id,h=o.length;if(e=i.fnv1aStepWord(e,a),e=i.fnv1aStepWord(e,h),e=i.fnv1aStepWord(e,o.enabledCount),h===0)continue;const l=o._flatColumns;for(let u=0;u<l.length;u++){const d=l[u].buf,f=h*d.BYTES_PER_ELEMENT,p=new Uint8Array(d.buffer,d.byteOffset,f),g=f>>>2;let E=0;for(let _=0;_<g;_++){const m=(p[E]|p[E+1]<<8|p[E+2]<<16|p[E+3]<<24)>>>0;e=(e^m)>>>0,e=Math.imul(e,i.FNV1A_PRIME),E+=4}const y=f&3;if(y!==0){let _=p[E];y>1&&(_|=p[E+1]<<8),y>2&&(_|=p[E+2]<<16),e=(e^_>>>0)>>>0,e=Math.imul(e,i.FNV1A_PRIME)}}}const s=this.sparseStores;for(let n=0;n<s.length;n++){const o=s[n];e=i.fnv1aStepWord(e,n),e=i.fnv1aStepWord(e,o.size);const a=o.canonicalIndices();for(let h=0;h<a.length;h++){const l=a[h];e=i.fnv1aStepWord(e,l);const u=o.getRow(l);for(let d=0;d<u.length;d++)te.setFloat64(0,u[d],!0),e=i.fnv1aStepWord(e,te.getUint32(0,!0)),e=i.fnv1aStepWord(e,te.getUint32(4,!0))}}const r=this.relationService.stores;for(let n=0;n<r.length;n++){const o=r[n];o.exclusive||(e=i.fnv1aStepWord(e,n),o.forEachCanonicalTargetSet((a,h)=>{e=i.fnv1aStepWord(e,a),e=i.fnv1aStepWord(e,h.length);for(let l=0;l<h.length;l++)e=i.fnv1aStepWord(e,h[l])}))}return e>>>0}archGet(e){return this.archGraph.get(e)}entityIdAtRow(e,t){const s=this.archGet(e);if(t<0||t>=s.entityCount)throw new i.ECSError(i.ECS_ERROR.ARCHETYPE_NOT_FOUND,`entity_id_at_row: archetype ${e} has ${s.entityCount} rows, requested row ${t}`);return s.entityIds[t]}archGetOrCreateFromMask(e){return this.archGraph.getOrCreateFromMask(e)}archCreateManyFromMasks(e){return this.archGraph.createManyFromMasks(e)}_archExtendStoreWithNewSpecs(e){const t=[],s=this.archGraph.archetypes;for(let n=0;n<s.length;n++){const o=s[n],a=this._columnStore.archetypes.get(o.id);a!==void 0&&t.push({archetypeId:o.id,newRowCapacity:a.rowCapacity,rowCount:o.hasColumns?o.length:0})}let r;try{r=Et(this._columnStore,{newArchetypes:e,existing:t},this._bufferAllocator)}catch(n){throw n instanceof W.StoreCapExceededError?this._capExceededError(n):n}if(this._columnStore=r.store,!r.viewsPreserved)for(let n=0;n<s.length;n++)s[n].isBufferBacked&&s[n].refreshViews(this._columnStore);this._handleBufferResized()}_materializeArchetype(e,t,s){const r=ue.fromColumnStore(e,t,s,this._columnStore,e);return r.growHandler=this._growHandler,r}_fanIntoQueries(e){const t=this.registeredQueries;for(let s=0;s<t.length;s++){const r=t[s];e.matches(r.includeMask)&&(!r.excludeMask||!e.mask.overlaps(r.excludeMask))&&(!r.anyOfMask||e.mask.overlaps(r.anyOfMask))&&r.result.push(e)}}archResolveAdd(e,t){return this.archGraph.resolveAdd(e,t)}archResolveRemove(e,t){return this.archGraph.resolveRemove(e,t)}createEntity(){const e=this.entityAllocator.alloc(),t=this.entityAllocator.lastIndex;return this.entityArchetype[t]=this.emptyArchetypeId,this.entityRow[t]=i.UNASSIGNED,e}_allocEntity(){return this.entityAllocator.alloc()}_ensureEntityIndexCapacity(e){this.entityAllocator.ensureCapacity(e)}resolveTemplate(e){const t=new T.BitSet;for(let h=0;h<e.length;h++)t.set(e[h].def.id);const s=this.archGetOrCreateFromMask(t),r=this.archGet(s),n=new Array(r._flatColumns.length).fill(0),o=new Map,a=new Array(e.length);for(let h=0;h<e.length;h++){a[h]=e[h].def;const l=e[h].def.id,u=this.componentMetas[l];if(u===void 0)throw new i.ECSError(i.ECS_ERROR.COMPONENT_NOT_REGISTERED,`template: component ${l} is not registered`);const d=e[h].values??i.EMPTY_VALUES,f=r._colOffset[l];for(let p=0;p<u.fieldNames.length;p++){const g=u.fieldNames[p];n[f+p]=d[g]??0,o.set(g,o.has(g)?Se:f+p)}}return{archetypeId:s,flatValues:n,overrideIndex:o,defs:a}}_resolveOverrideColumn(e,t){const s=e.overrideIndex.get(t);if(s===void 0)throw new i.ECSError(i.ECS_ERROR.FIELD_NOT_REGISTERED,`template override: no field "${t}" in this template`);if(s===Se)throw new i.ECSError(i.ECS_ERROR.FIELD_NOT_REGISTERED,`template override: field "${t}" is ambiguous (owned by more than one component in this template); set it via the template defaults instead of a flat override`);return s}_applyOverrides(e,t,s,r){const n=e._flatColumns;for(const o in r){if(r[o]===void 0)continue;const a=this._resolveOverrideColumn(s,o);a>=0&&(n[a].buf[t]=r[o])}}_applyOverridesRange(e,t,s,r,n){const o=e._flatColumns;for(const a in n){if(n[a]===void 0)continue;const h=this._resolveOverrideColumn(r,a);h>=0&&o[h].buf.fill(n[a],t,t+s)}}spawn(e,t){const s=this.archGraph.archetypes[e.archetypeId];s.materializesRows&&s.ensureRowCapacity(1);const r=this._allocEntity(),n=this.entityAllocator.lastIndex;if(!s.materializesRows)return this.entityArchetype[n]=e.archetypeId,this.entityRow[n]=i.UNASSIGNED,r;const o=s.length,a=s.enabledCount,h=s.addEntityWithValues(r,e.flatValues,this._tick,this.entityRow);return t!==void 0&&this._applyOverrides(s,h,e,t),this.entityArchetype[n]=e.archetypeId,this.entityRow[n]=h,this._onArchGrow(s,o,a),r}spawnMany(e,t,s){if(t<=0)return[];const r=this.archGraph.archetypes[e.archetypeId];this._ensureEntityIndexCapacity(t),r.ensureRowCapacity(t);const n=new Array(t),o=new Uint32Array(t);for(let f=0;f<t;f++){const p=this._allocEntity();o[f]=p,n[f]=p}const a=this.entityArchetype,h=this.entityRow;if(!r.materializesRows){for(let f=0;f<t;f++){const p=i.getEntityIndex(n[f]);a[p]=e.archetypeId,h[p]=i.UNASSIGNED}return n}const l=r.length,u=r.enabledCount;if(r.disabledCount>0){for(let f=0;f<t;f++){const p=r.addEntityWithValues(n[f],e.flatValues,this._tick,h),g=i.getEntityIndex(n[f]);a[g]=e.archetypeId,h[g]=p,s!==void 0&&this._applyOverrides(r,p,e,s)}return this._onArchGrow(r,l,u),n}const d=r.addEntitiesWithValues(o,t,e.flatValues,this._tick);for(let f=0;f<t;f++){const p=i.getEntityIndex(n[f]);a[p]=e.archetypeId,h[p]=d+f}return s!==void 0&&this._applyOverridesRange(r,d,t,e,s),this._onArchGrow(r,l,u),n}destroyEntity(e){if(!this.isAlive(e))throw i.entityNotAliveError("destroyEntity",e);if(!this.relationService.hasTargetCleanup){this._destroyOne(e,null);return}const t=[e];for(let s=0;s<t.length;s++){const r=t[s];this.isAlive(r)&&this._destroyOne(r,t)}}_destroyOne(e,t){const s=i.getEntityIndex(e),r=this.entityRow[s];if(r!==i.UNASSIGNED){const n=this.archGet(this.entityArchetype[s]),o=n.length;n.removeRow(r,this.entityRow),this._onArchLenChange(n,o)}this.entityArchetype[s]=i.UNASSIGNED,this.entityRow[s]=i.UNASSIGNED,this.relationService.count>0&&(this.relationService.purgeSource(e),t!==null&&this.relationService.cleanupTarget(e,t)),this.sparseStores.length>0&&this._purgeSparse(s),this._anyDirtyTracked&&this._clearDirtyForIndex(s),this.entityAllocator.recycle(s,i.getEntityGeneration(e))}isAlive(e){if(e<0||e>i.MAX_ENTITY_ID)return!1;const t=i.getEntityGeneration(e);if(t===i.RETIRED_GENERATION)return!1;const s=i.getEntityIndex(e);return this.entityAllocator.isAliveIndex(s,t)}get entityCount(){return this.entityAllocator.aliveCount}_onArchLenChange(e,t){this._rowCountsDirty=!0,t===0!=(e.length===0)&&this._queryDirtyEpoch++}_onArchGrow(e,t,s){this._rowCountsDirty=!0,(t===0||s===0&&e.enabledCount!==0)&&this._queryDirtyEpoch++}_onArchEnabledChange(e,t){this._rowCountsDirty=!0,t===0!=(e.enabledCount===0)&&this._queryDirtyEpoch++}disableEntity(e){if(!this.isAlive(e))throw i.entityNotAliveError("disableEntity",e);const t=i.getEntityIndex(e),s=this.entityRow[t];if(s===i.UNASSIGNED)throw new i.ECSError(i.ECS_ERROR.ENTITY_NOT_ALIVE,"cannot disable a component-less entity: it occupies no archetype row; add a component first");const r=this.archGet(this.entityArchetype[t]);if(s>=r.enabledCount)return;const n=r.enabledCount;r.disableRow(s,this.entityRow),this._onArchEnabledChange(r,n)}enableEntity(e){if(!this.isAlive(e))throw i.entityNotAliveError("enableEntity",e);const t=i.getEntityIndex(e),s=this.entityRow[t];if(s===i.UNASSIGNED)return;const r=this.archGet(this.entityArchetype[t]);if(s<r.enabledCount)return;const n=r.enabledCount;r.enableRow(s,this.entityRow),this._onArchEnabledChange(r,n)}isDisabled(e){if(!this.isAlive(e))throw i.entityNotAliveError("isDisabled",e);const t=i.getEntityIndex(e),s=this.entityRow[t];if(s===i.UNASSIGNED)return!1;const r=this.archGet(this.entityArchetype[t]);return s>=r.enabledCount}_flushEpoch=0;_flushTouched=[];_settleFlushDirty(){const e=this._flushTouched;if(e.length===0)return;this._rowCountsDirty=!0;let t=!1;for(let s=0;s<e.length;s++){const r=e[s];(r._flushPreLen===0!=(r.length===0)||r._flushPreEnabled===0!=(r.enabledCount===0))&&(t=!0)}t&&this._queryDirtyEpoch++,e.length=0,this._flushEpoch++}destroyEntityDeferred(e){if(!this.isAlive(e))throw i.entityNotAliveError("destroyEntityDeferred",e);this._deferred.queueDestroy(e)}disableEntityDeferred(e){if(!this.isAlive(e))throw i.entityNotAliveError("disableEntityDeferred",e);this._deferred.queueToggle(e,!0)}enableEntityDeferred(e){if(!this.isAlive(e))throw i.entityNotAliveError("enableEntityDeferred",e);this._deferred.queueToggle(e,!1)}_flushToggles(){const e=this._deferred.toggleIds,t=this._deferred.toggleDisable,s=e.length;if(!(this._toggleObserverCount>0)){for(let o=0;o<s;o++){const a=e[o];this.isAlive(a)&&(t[o]?this.disableEntity(a):this.enableEntity(a))}e.length=0,t.length=0;return}const n=this._toggleInitial;for(let o=0;o<s;o++){const a=e[o];this.isAlive(a)&&(n.has(a)||n.set(a,this.isDisabled(a)))}for(let o=0;o<s;o++){const a=e[o];this.isAlive(a)&&(t[o]?this.disableEntity(a):this.enableEntity(a))}e.length=0,t.length=0;for(const[o,a]of n){if(!this.isAlive(o))continue;const h=this.isDisabled(o);a!==h&&this._collectToggle(o,h)}n.clear()}_collectToggle(e,t){const s=i.getEntityIndex(e);if(this.entityRow[s]===i.UNASSIGNED)return;const r=this.archGet(this.entityArchetype[s]);this._collectToggleEid=e,r.mask.forEach(t?this._collectDisableBit:this._collectEnableBit)}get pendingToggleCount(){return this._deferred.toggleCount}flushDestroyed(){this._deferred.flushDestroyed()}_drainDestroyed(){const e=this._deferred.destroyIds;if(e.length===0)return;const t=this.entityAllocator,s=this.entityArchetype,r=this.entityRow,n=t.generations,o=this.archGraph.archetypes,a=t.highWater;let h=!1,l=!1;const u=this.sparseStores.length>0,d=this.relationService.count>0,f=d&&this.relationService.hasTargetCleanup,p=this._anyDirtyTracked,g=this._structuralObserverCount>0;for(let E=0;E<e.length;E++){const y=e[E],_=y&i.INDEX_MASK,m=y>>i.INDEX_BITS;if(_>=a||n[_]!==m)continue;const S=r[_];if(S!==i.UNASSIGNED){const v=o[s[_]];g&&(this._collectDestroyEid=y,v.mask.forEach(this._collectDestroyRemoveBit)),v.removeRow(S,r),h=!0,v.length===0&&(l=!0)}d&&this.relationService.purgeSource(y),f&&this.relationService.cleanupTarget(y,e),u&&this._purgeSparse(_),p&&this._clearDirtyForIndex(_),s[_]=i.UNASSIGNED,r[_]=i.UNASSIGNED,t.recycle(_,m)}e.length=0,h&&(this._rowCountsDirty=!0,l&&this._queryDirtyEpoch++)}get pendingDestroyCount(){return this._deferred.destroyCount}addComponentDeferred(e,t,s){if(!this.isAlive(e))throw i.entityNotAliveError("addComponentDeferred",e,this.componentLabel(t.id));this._deferred.queueAdd(e,t,s??i.EMPTY_VALUES)}removeComponentDeferred(e,t){if(!this.isAlive(e))throw i.entityNotAliveError("removeComponentDeferred",e,this.componentLabel(t.id));this._deferred.queueRemove(e,t)}flushStructural(){this._deferred.flushStructural()}_flushAdds(){const e=this._deferred.addIds,t=this._deferred.addDefs,s=this._deferred.addValues,r=e.length,n=this.entityArchetype,o=this.entityRow,a=this.entityAllocator.generations,h=this.archGraph.archetypes,l=this.componentMetas,u=this.entityAllocator.highWater,d=this._tick,f=this._flushEpoch,p=this._flushTouched,g=this._structuralObserverCount>0,E=this._obsEvents;for(let y=0;y<r;y++){const _=e[y],m=_&i.INDEX_MASK,S=_>>i.INDEX_BITS;if(m>=u||a[m]!==S)continue;const v=n[m],R=t[y].id,C=h[v],w=l[R];if(C.mask.has(R)){w.fieldNames.length>0&&C.writeFields(o[m],R,s[y],d);continue}const k=this.archResolveAdd(v,R),A=h[k],F=o[m],fe=!A.hasColumns&&!C.hasColumns;F!==i.UNASSIGNED&&C._flushSeenEpoch!==f&&(C._flushSeenEpoch=f,C._flushPreLen=C.length,C._flushPreEnabled=C.enabledCount,p.push(C)),A._flushSeenEpoch!==f&&(A._flushSeenEpoch=f,A._flushPreLen=A.length,A._flushPreEnabled=A.enabledCount,p.push(A));let z;if(F!==i.UNASSIGNED){if(fe)A.moveEntityFromTag(C,F,_,o);else{const He=C.getEdge(R);A.moveEntityFrom(C,F,_,He.addMap,d,o)}z=b[0]}else z=fe?A.addEntityTag(_,o):A.addEntity(_,o);w.fieldNames.length>0&&A.writeFields(z,R,s[y],d),n[m]=k,o[m]=z,g&&w.obsAdd&&(E.addComp[E.addLen]=R,E.addEid[E.addLen]=_,E.addLen++)}e.length=0,t.length=0,s.length=0,this._settleFlushDirty()}_flushRemoves(){const e=this._deferred.removeIds,t=this._deferred.removeDefs,s=e.length,r=this.entityArchetype,n=this.entityRow,o=this.entityAllocator.generations,a=this.archGraph.archetypes,h=this.entityAllocator.highWater,l=this._tick,u=this._flushEpoch,d=this._flushTouched,f=this.componentMetas,p=this._structuralObserverCount>0,g=this._obsEvents;for(let E=0;E<s;E++){const y=e[E],_=y&i.INDEX_MASK,m=y>>i.INDEX_BITS;if(_>=h||o[_]!==m)continue;const S=r[_],v=t[E].id,R=a[S];if(!R.mask.has(v))continue;const C=this.archResolveRemove(S,v),w=a[C],k=n[_],A=!w.hasColumns&&!R.hasColumns;if(R._flushSeenEpoch!==u&&(R._flushSeenEpoch=u,R._flushPreLen=R.length,R._flushPreEnabled=R.enabledCount,d.push(R)),w._flushSeenEpoch!==u&&(w._flushSeenEpoch=u,w._flushPreLen=w.length,w._flushPreEnabled=w.enabledCount,d.push(w)),A)w.moveEntityFromTag(R,k,y,n);else{const F=R.getEdge(v);w.moveEntityFrom(R,k,y,F.removeMap,l,n)}r[_]=C,n[_]=b[0],p&&f[v].obsRem&&(g.remComp[g.remLen]=v,g.remEid[g.remLen]=y,g.remLen++)}e.length=0,t.length=0,this._settleFlushDirty()}get pendingStructuralCount(){return this._deferred.structuralCount}_configureComponentObservation(e,t,s,r,n,o){const a=this.componentMetas[e];if(a===void 0)throw new i.ECSError(i.ECS_ERROR.COMPONENT_NOT_REGISTERED,`observe(): component ${e} is not registered`);const h=a.obsAdd||a.obsRem;a.obsAdd=t,a.obsRem=s;const l=t||s;h&&!l?this._structuralObserverCount--:!h&&l&&this._structuralObserverCount++;const u=a.obsDisable||a.obsEnable;a.obsDisable=r,a.obsEnable=n;const d=r||n;if(u&&!d?this._toggleObserverCount--:!u&&d&&this._toggleObserverCount++,o&&!a.trackDirty)a.trackDirty=!0,this._dirtyLists[e]===void 0&&(this._dirtyLists[e]=[],this._dirtyMarks[e]=new Uint8Array(Math.max(1,this.entityAllocator.generations.length))),this._dirtyTrackedCids.push(e),this._anyDirtyTracked=!0;else if(!o&&a.trackDirty){a.trackDirty=!1;const f=this._dirtyTrackedCids.indexOf(e);f>=0&&this._dirtyTrackedCids.splice(f,1),this._anyDirtyTracked=this._dirtyTrackedCids.length>0;const p=this._dirtyLists[e],g=this._dirtyMarks[e];if(p!==void 0&&g!==void 0){for(let E=0;E<p.length;E++)g[p[E]&i.INDEX_MASK]=0;p.length=0}}}_noteSet(e,t){const s=e.id,r=this.componentMetas[s];if(r===void 0||!r.trackDirty)return;const n=t&i.INDEX_MASK;let o=this._dirtyMarks[s];n>=o.length&&(o=this._growDirtyMarks(s,n)),o[n]===0&&(o[n]=1,this._dirtyLists[s].push(t))}_growDirtyMarks(e,t){const s=this._dirtyMarks[e];let r=Math.max(1,s.length);for(;r<=t;)r*=2;const n=new Uint8Array(r);return n.set(s),this._dirtyMarks[e]=n,n}_takeDirty(e){const t=this._dirtyLists[e];if(t===void 0||t.length===0)return At;this._dirtyLists[e]=[];const s=this._dirtyMarks[e];for(let r=0;r<t.length;r++)s[t[r]&i.INDEX_MASK]=0;return t}_clearDirtyForIndex(e){const t=this._dirtyTrackedCids;for(let s=0;s<t.length;s++){const r=this._dirtyMarks[t[s]];r!==void 0&&e<r.length&&(r[e]=0)}}_forEachChangedArchetype(e,t,s){const r=this.archGraph.componentIndex[e];if(r===void 0)return;const n=this.archGraph.archetypes;for(let o=0;o<r.length;o++){const a=n[r[o]];a.length>0&&a._changedTick[e]>=t&&s(a)}}_collectEntitiesWithComponent(e){const t=[],s=this.archGraph.componentIndex[e];if(s===void 0)return t;const r=this.archGraph.archetypes;for(let n=0;n<s.length;n++){const o=r[s[n]],a=o.entityIds;for(let h=0;h<o.enabledCount;h++)t.push(i.unsafeCast(a[h]))}return t}registerComponent(e,t){if(this.componentCount>=i.STORE_DESCRIPTOR_COMPONENT_LIMIT)throw new i.ECSError(i.ECS_ERROR.COMPONENT_LIMIT_EXCEEDED,`Cannot register more than ${i.STORE_DESCRIPTOR_COMPONENT_LIMIT} components: the SAB archetype descriptor mask is ${i.STORE_DESCRIPTOR_COMPONENT_LIMIT} bits wide. Widen the descriptor mask (descriptor.ts + abi.zig, a SIM_ABI_VERSION bump) to raise it.`,{componentCount:this.componentCount,limit:i.STORE_DESCRIPTOR_COMPONENT_LIMIT});const s=Object.keys(e),r=new Array(s.length),n=Object.create(null);for(let h=0;h<s.length;h++)n[s[h]]=h,r[h]=e[s[h]];this._rejectNonDeterministicFields(s,r,"component");const o=Te(this.componentCount++);this.componentMetas.push({name:t,fieldNames:s,fieldIndex:n,fieldTypes:r,obsAdd:!1,obsRem:!1,obsDisable:!1,obsEnable:!1,trackDirty:!1});const a=De(o);return t!==void 0&&i.setComponentDebugName(a,t),a}componentLabel(e){const t=this.componentMetas[e]?.name;return t!==void 0?`'${t}' (component ${e})`:`component ${e}`}fieldIdOf(e,t){const s=e.id,r=this.componentMetas[s];if(r===void 0)throw new i.ECSError(i.ECS_ERROR.COMPONENT_NOT_REGISTERED,`field_id_of: component ${s} is not registered`);const n=r.fieldIndex[t];if(n===void 0)throw new i.ECSError(i.ECS_ERROR.FIELD_NOT_REGISTERED,`field_id_of: component ${s} has no field "${t}"`);return n}registerSparseComponent(e,t){const s=Object.keys(e),r=new Array(s.length);for(let n=0;n<s.length;n++)r[n]=e[s[n]];return this._rejectNonDeterministicFields(s,r,"sparse component"),this._pushSparseStore(s,r,t)}sparseLabel(e){const t=this.sparseNames[e];return t!==void 0?`'${t}' (sparse component ${e})`:`sparse component ${e}`}_pushSparseStore(e,t,s){const r=this.sparseStores.length;return this.sparseStores.push(new i.SparseComponentStore(e,t)),this.sparseNames.push(s),i.unsafeCast(r)}sparseStoreOf(e){const t=e,s=this.sparseStores[t];if(s===void 0)throw new i.ECSError(i.ECS_ERROR.COMPONENT_NOT_REGISTERED,`sparse component ${t} is not registered`);return s}addSparse(e,t,s){if(!this.isAlive(e))throw i.entityNotAliveError("addSparse",e,this.sparseLabel(t));this.sparseStoreOf(t).setRow(i.getEntityIndex(e),s??i.EMPTY_VALUES)}removeSparse(e,t){if(!this.isAlive(e))throw i.entityNotAliveError("removeSparse",e,this.sparseLabel(t));this.sparseStoreOf(t).remove(i.getEntityIndex(e))}hasSparse(e,t){return this.isAlive(e)?this.sparseStoreOf(t).has(i.getEntityIndex(e)):!1}getSparseField(e,t,s){if(!this.isAlive(e))throw i.entityNotAliveError("getSparseField",e,`${this.sparseLabel(t)}.${s}`);const r=this.sparseStoreOf(t),n=r.fieldIndex[s];if(n===void 0)throw new i.ECSError(i.ECS_ERROR.FIELD_NOT_REGISTERED,`sparse component has no field "${s}"`);const o=r.getField(i.getEntityIndex(e),n);if(o===void 0)throw new i.ECSError(i.ECS_ERROR.COMPONENT_NOT_REGISTERED,"entity does not hold this sparse component");return o}setSparseField(e,t,s,r){if(!this.isAlive(e))throw i.entityNotAliveError("setSparseField",e,`${this.sparseLabel(t)}.${s}`);const n=this.sparseStoreOf(t),o=n.fieldIndex[s];if(o===void 0)throw new i.ECSError(i.ECS_ERROR.FIELD_NOT_REGISTERED,`sparse component has no field "${s}"`);if(!n.setField(i.getEntityIndex(e),o,r))throw new i.ECSError(i.ECS_ERROR.COMPONENT_NOT_REGISTERED,"entity does not hold this sparse component")}_purgeSparse(e){const t=this.sparseStores;for(let s=0;s<t.length;s++)t[s].remove(e)}snapshotSparse(){return this._requireDeterministic("snapshot_sparse()"),this._snapshots.snapshotSparse()}restoreSparse(e){this._requireDeterministic("restore_sparse()"),this._snapshots.restoreSparse(e)}snapshot(){return this._requireDeterministic("snapshot()"),this._snapshots.snapshot()}restoreInto(e){this._requireDeterministic("restoreInto()"),this._snapshots.restoreInto(e)}_mountRestoredDense(e){this._columnStore=e;const t=this.archGraph.archetypes;for(let s=0;s<t.length;s++)t[s].isBufferBacked&&t[s].refreshViews(this._columnStore);this.entityAllocator.setHighWater(e.view.getUint32(e.header.entityIndexOff+i.ENTITY_INDEX_HEADER_OFFSETS.length,!0)),this._handleBufferResized()}_reconstructHostRows(e){const t=this.entityAllocator.highWater,s=this.entityArchetype,r=this.entityRow,n=this.entityAllocator.generations,o=new Map;for(let a=0;a<t;a++){const h=s[a];if(h===i.UNASSIGNED)continue;const l=r[a];if(l===i.UNASSIGNED)continue;let u=o.get(h);u===void 0&&(u=[],o.set(h,u)),u[l]=i.createEntityId(a,n[a])}for(let a=0;a<e.archetypeRows.length;a++){const h=e.archetypeRows[a],l=this.archGet(h.archetypeId),u=o.get(h.archetypeId)??[];{if(u.length!==h.length)throw new O(`archetype ${h.archetypeId} row-count mismatch on restore: scan found ${u.length} rows, host-state recorded ${h.length}`);for(let d=0;d<u.length;d++)if(u[d]===void 0)throw new O(`archetype ${h.archetypeId} has a hole at row ${d} after restore (entity-index region inconsistent)`)}l.restoreHostRows(u,h.enabledCount)}}registerRelation(e){return this.relationService.registerRelation(e)}get relationCount(){return this.relationService.count}addRelation(e,t,s){this.relationService.addRelation(e,t,s)}removeRelation(e,t,s){this.relationService.removeRelation(e,t,s)}targetOf(e,t){return this.relationService.targetOf(e,t)}targetsOf(e,t){return this.relationService.targetsOf(e,t)}sourcesOf(e,t){return this.relationService.sourcesOf(e,t)}hasRelation(e,t){return this.relationService.hasRelation(e,t)}pairsOf(e){return this.relationService.pairsOf(e)}sourcesOfAny(e){return this.relationService.sourcesOfAny(e)}relationBackingSparseId(e){return this.relationService.relationBackingSparseId(e)}_forEachRelationTargetMatch(e,t,s,r,n,o,a,h){this.relationService.forEachRelationTargetMatch(e,t,s,r,n,o,a,h)}compactRelations(){return this.relationService.compactRelations()}ancestorsOf(e,t){return this.relationService.ancestorsOf(e,t)}rootOf(e,t){return this.relationService.rootOf(e,t)}cascadeOf(e,t){return this.relationService.cascadeOf(e,t)}_forEachSparseMatch(e,t,s,r,n,o,a,h){const l=this.sparseStores;{for(let d=0;d<r.length;d++)if(l[r[d]]===void 0)throw new i.ECSError(i.ECS_ERROR.COMPONENT_NOT_REGISTERED,`sparse component ${r[d]} is not registered`);for(let d=0;d<n.length;d++)if(l[n[d]]===void 0)throw new i.ECSError(i.ECS_ERROR.COMPONENT_NOT_REGISTERED,`sparse component ${n[d]} is not registered`)}if(r.length>0){let d=l[r[0]];for(let _=1;_<r.length;_++){const m=l[r[_]];m.size<d.size&&(d=m)}const f=d.indices,p=this.entityAllocator.generations,g=this.entityArchetype,E=this.entityRow,y=this.archGraph.archetypes;for(let _=0;_<f.length;_++){const m=f[_];let S=!0;for(let w=0;w<r.length;w++){const k=l[r[w]];if(k!==d&&!k.has(m)){S=!1;break}}if(!S)continue;for(let w=0;w<n.length;w++)if(l[n[w]].has(m)){S=!1;break}if(!S)continue;const v=g[m];if(v===i.UNASSIGNED)continue;const R=y[v],C=R.mask;if(C.contains(e)&&!(t!==null&&C.overlaps(t))&&!(s!==null&&!C.overlaps(s))){if(!h){const w=E[m];if(w!==i.UNASSIGNED&&w>=R.enabledCount)continue}a(i.createEntityId(m,p[m]))}}return}const u=n.length>0;for(let d=0;d<o.length;d++){const f=o[d],p=f.entityIds,g=h?f.totalCount:f.enabledCount;for(let E=0;E<g;E++){const y=p[E];if(u){const _=i.getEntityIndex(y);let m=!1;for(let S=0;S<n.length;S++)if(l[n[S]].has(_)){m=!0;break}if(m)continue}a(y)}}}_forEachHierarchyMatch(e,t,s,r,n,o,a,h,l,u){this.relationService.forEachHierarchyMatch(e,t,s,r,n,o,a,h,l,u)}addComponent(e,t,s){if(!this.isAlive(e))throw i.entityNotAliveError("addComponent",e,this.componentLabel(t.id));const r=i.getEntityIndex(e),n=this.entityArchetype[r],o=this.archGet(n);if(o.hasComponent(t.id)){o.writeFields(this.entityRow[r],t.id,s,this._tick);return}const a=this.archResolveAdd(n,t.id),h=this.archGet(a),l=this.entityRow[r];let u;if(l!==i.UNASSIGNED){const d=o.length,f=h.length,p=h.enabledCount,g=o.getEdge(t.id);!h.hasColumns&&!o.hasColumns?h.moveEntityFromTag(o,l,e,this.entityRow):h.moveEntityFrom(o,l,e,g.addMap,this._tick,this.entityRow),u=b[0],this._onArchLenChange(o,d),this._onArchGrow(h,f,p)}else{const d=h.length,f=h.enabledCount;u=h.hasColumns?h.addEntity(e,this.entityRow):h.addEntityTag(e,this.entityRow),this._onArchGrow(h,d,f)}h.writeFields(u,t.id,s,this._tick),this.entityArchetype[r]=a,this.entityRow[r]=u}addComponents(e,t){if(!this.isAlive(e))throw i.entityNotAliveError("addComponents",e);const s=i.getEntityIndex(e),r=this.entityArchetype[s],n=this.archGet(r),o=t.length;let a=o;for(let f=0;f<o;f++){const p=t[f].def.id;if(p>=Re-1||o>bt){a=se;break}a=a*Re+(p+1)}if(a!==se){const f=n.getCompositeAddEdge(a);if(f!==void 0){this._addComponentsInto(e,s,n,this.archGet(f.target),f.target,f.map,t);return}}let h=null;for(let f=0;f<o;f++){const p=t[f].def.id;h!==null?h.set(p):n.mask.has(p)||(h=n.mask.copyInto(this._scratchTargetMask),h.set(p))}if(h===null){const f=this.entityRow[s];for(let p=0;p<o;p++)n.writeFields(f,t[p].def.id,t[p].values??i.EMPTY_VALUES,this._tick);return}const l=this.archGetOrCreateFromMask(h),u=this.archGet(l),d=n.getBatchTransitionMap(u);a!==se&&n.cacheCompositeAddEdge(a,l,d),this._addComponentsInto(e,s,n,u,l,d,t)}_addComponentsInto(e,t,s,r,n,o,a){const h=this.entityRow[t];let l;if(h!==i.UNASSIGNED){const u=s.length,d=r.length,f=r.enabledCount;r.moveEntityFrom(s,h,e,o,this._tick,this.entityRow),l=b[0],this._onArchLenChange(s,u),this._onArchGrow(r,d,f)}else{const u=r.length,d=r.enabledCount;l=r.addEntity(e,this.entityRow),this._onArchGrow(r,u,d)}for(let u=0;u<a.length;u++)r.writeFields(l,a[u].def.id,a[u].values??i.EMPTY_VALUES,this._tick);this.entityArchetype[t]=n,this.entityRow[t]=l}removeComponent(e,t){if(!this.isAlive(e))throw i.entityNotAliveError("removeComponent",e,this.componentLabel(t.id));const s=i.getEntityIndex(e),r=this.entityArchetype[s],n=this.archGet(r);if(!n.hasComponent(t.id))return;const o=this.archResolveRemove(r,t.id),a=this.archGet(o),h=this.entityRow[s],l=n.getEdge(t.id),u=!a.hasColumns&&!n.hasColumns,d=n.length,f=a.length,p=a.enabledCount;u?a.moveEntityFromTag(n,h,e,this.entityRow):a.moveEntityFrom(n,h,e,l.removeMap,this._tick,this.entityRow),this.entityArchetype[s]=o,this.entityRow[s]=b[0],this._onArchLenChange(n,d),this._onArchGrow(a,f,p)}removeComponents(e,t){if(!this.isAlive(e))throw i.entityNotAliveError("removeComponents",e);const s=i.getEntityIndex(e),r=this.entityArchetype[s],n=this.archGet(r);let o=null;for(let g=0;g<t.length;g++){const E=t[g].id;o!==null?o.clear(E):n.mask.has(E)&&(o=n.mask.copyInto(this._scratchTargetMask),o.clear(E))}if(o===null)return;const a=this.archGetOrCreateFromMask(o),h=this.archGet(a),l=this.entityRow[s],u=n.length,d=h.length,f=h.enabledCount,p=n.getBatchTransitionMap(h);h.moveEntityFrom(n,l,e,p,this._tick,this.entityRow),this.entityArchetype[s]=a,this.entityRow[s]=b[0],this._onArchLenChange(n,u),this._onArchGrow(h,d,f)}hasComponent(e,t){if(!this.isAlive(e))return!1;const s=i.getEntityIndex(e);return this.archGet(this.entityArchetype[s]).hasComponent(t.id)}batchAddComponent(e,t,s){const r=this.archGet(e);if(r.length===0)return;const n=t.id;if(r.mask.has(n))return;const o=this.archResolveAdd(r.id,n),a=this.archGet(o);if(r.disabledCount>0||a.disabledCount>0)throw new i.ECSError(i.ECS_ERROR.PARTITION_BULK_INTO_DISABLED,"batchAddComponent is unsupported on archetypes with disabled entities — enable them first or use per-entity addComponent");const h=r.getEdge(n),l=r.length,u=l,d=a.length,f=a.enabledCount,p=this.entityArchetype,g=this.entityRow,E=a.bulkMoveAllFrom(r,h.addMap,this._tick);for(let _=0;_<l;_++){const m=i.getEntityIndex(a.entityIds[E+_]);p[m]=o,g[m]=E+_}this.componentMetas[n].fieldNames.length>0&&s&&a.bulkWriteFields(E,l,n,s,this._tick),this._onArchLenChange(r,u),this._onArchGrow(a,d,f)}batchRemoveComponent(e,t){const s=this.archGet(e);if(s.length===0)return;const r=t.id;if(!s.mask.has(r))return;const n=this.archResolveRemove(s.id,r),o=this.archGet(n);if(s.disabledCount>0||o.disabledCount>0)throw new i.ECSError(i.ECS_ERROR.PARTITION_BULK_INTO_DISABLED,"batchRemoveComponent is unsupported on archetypes with disabled entities — enable them first or use per-entity removeComponent");const a=s.getEdge(r),h=s.length,l=h,u=this.entityArchetype,d=this.entityRow;if(!o.materializesRows){const E=s.entityIds;for(let y=0;y<h;y++){const _=i.getEntityIndex(E[y]);u[_]=n,d[_]=i.UNASSIGNED}s.clearRows(),this._onArchLenChange(s,l);return}const f=o.length,p=o.enabledCount,g=o.bulkMoveAllFrom(s,a.removeMap,this._tick);for(let E=0;E<h;E++){const y=i.getEntityIndex(o.entityIds[g+E]);u[y]=n,d[y]=g+E}this._onArchLenChange(s,l),this._onArchGrow(o,f,p)}getEntityArchetype(e){return this.archGet(this.entityArchetype[i.getEntityIndex(e)])}getEntityRow(e){return this.entityRow[i.getEntityIndex(e)]}getMatchingArchetypes(e,t,s){const r=e._words;let n=!1;for(let l=0;l<r.length;l++)if(r[l]!==0){n=!0;break}if(!n){const l=this.archGraph.archetypes,u=[];for(let d=0;d<l.length;d++){const f=l[d];(!t||!f.mask.overlaps(t))&&(!s||f.mask.overlaps(s))&&u.push(f)}return u}let o,a=!1;for(let l=0;l<r.length;l++){let u=r[l];if(u===0)continue;const d=l<<T.BITS_PER_WORD_SHIFT;for(;u!==0;){const f=u&-u>>>0,p=d+(T.BITS_PER_WORD_MASK-Math.clz32(f));u^=f;const g=this.archGraph.componentIndex[p];if(g===void 0||g.length===0){a=!0;break}(!o||g.length<o.length)&&(o=g)}if(a)break}if(a||!o)return[];const h=[];for(let l=0;l<o.length;l++){const u=this.archGet(o[l]);u.matches(e)&&(!t||!u.mask.overlaps(t))&&(!s||u.mask.overlaps(s))&&h.push(u)}return h}registerQuery(e,t,s){const r=this.getMatchingArchetypes(e,t,s);return this.registeredQueries.push({includeMask:e.copy(),excludeMask:t?t.copy():null,anyOfMask:s?s.copy():null,result:r,query:null}),r}updateQueryRef(e,t){const s=this.registeredQueries;for(let r=0;r<s.length;r++)if(s[r].result===e){s[r].query=t;return}}get archetypeCount(){return this.archGraph.archetypes.length}registerEvent(e){return this.events.registerEvent(e)}emitEvent(e,t){this.events.emitEvent(e,t)}emitSignal(e){this.events.emitSignal(e)}getEventReader(e){return this.events.getEventReader(e)}clearEvents(){this.events.clearEvents()}_devBufferedEventCount(){return this.events.devBufferedEventCount()}registerEventByKey(e,t){return this.events.registerEventByKey(e,t)}getEventDefByKey(e){return this.events.getEventDefByKey(e)}hasEventKey(e){return this.events.hasEventKey(e)}resources=new Ke;registerResource(e,t){this.resources.register(e,t)}getResource(e){return this.resources.get(e)}setResource(e,t){this.resources.set(e,t)}removeResource(e){this.resources.remove(e)}hasResource(e){return this.resources.has(e)}}class Tt{store;constructor(e){this.store=e}register(e){return this.store.registerRelation(e)}get count(){return this.store.relationCount}add(e,t,s){return this.store.addRelation(e,t,s),this}remove(e,t,s){return this.store.removeRelation(e,t,s),this}has(e,t){return this.store.hasRelation(e,t)}targetOf(e,t){return this.store.targetOf(e,t)}targetsOf(e,t){return this.store.targetsOf(e,t)}sourcesOf(e,t){return this.store.sourcesOf(e,t)}pairsOf(e){return this.store.pairsOf(e)}sourcesOfAny(e){return this.store.sourcesOfAny(e)}ancestorsOf(e,t){return this.store.ancestorsOf(e,t)}rootOf(e,t){return this.store.rootOf(e,t)}cascadeOf(e,t){return this.store.cascadeOf(e,t)}compact(){return this.store.compactRelations()}}class Dt{store;constructor(e){this.store=e}register(e,t){this.store.registerEventByKey(e,t)}registerSignal(e){this.store.registerEventByKey(e,[])}emit(e,t){i.dispatchTrace.isActive()&&i.dispatchTrace.recordEmit(e.description??"");const s=this.store.getEventDefByKey(e);t===void 0?this.store.emitSignal(s):this.store.emitEvent(s,t)}read(e){i.dispatchTrace.isActive()&&i.dispatchTrace.recordRead(e.description??"");const t=this.store.getEventDefByKey(e);return this.store.getEventReader(t)}}class kt{store;constructor(e){this.store=e}register(e,t){i.dispatchTrace.isActive()&&i.dispatchTrace.recordResourceRegister(e.description??""),this.store.registerResource(e,t)}get(e){return i.accessCheck.checkResourceRead(e),i.dispatchTrace.isActive()&&i.dispatchTrace.recordResourceRead(e.description??""),i.unsafeCast(this.store.getResource(e))}set(e,t){i.accessCheck.checkResourceWrite(e),i.dispatchTrace.isActive()&&i.dispatchTrace.recordResourceWrite(e.description??""),this.store.setResource(e,t)}remove(e){i.accessCheck.checkResourceWrite(e),i.dispatchTrace.isActive()&&i.dispatchTrace.recordResourceRemove(e.description??""),this.store.removeResource(e)}has(e){return this.store.hasResource(e)}}class Nt{store;constructor(e){this.store=e}get deterministic(){return this.store.deterministic}stateHash(){return this.store.stateHash()}capture(){return this.store.snapshot()}restore(e){this.store.restoreInto(e)}captureSparse(){return this.store.snapshotSparse()}restoreSparse(e){this.store.restoreSparse(e)}}const Ce=new WeakMap;function ce(c,e){let t=Ce.get(c);if(!t){t=Object.create(null);const{fieldNames:r}=c.layout;for(let n=0;n<r.length;n++){const o=c.columns[n];Object.defineProperty(t,r[n],{get(){return o.buf[this._row]},set(a){o.buf[this._row]=a},enumerable:!0,configurable:!1})}Ce.set(c,t)}const s=Object.create(t);return s._row=e,s}class xt{dedup=new Map;andSingle=new Map;notSingle=new Map;anyOfSingle=new Map;changedSingle=new Map;optionalSingle=new Map;withSparseSingle=new Map;withoutSparseSingle=new Map;withRelationSingle=new Map;withoutRelationSingle=new Map;includeDisabledSingle=new Map;hierarchySingle=new Map;findDedup(e,t,s,r){const n=this.dedup.get(e);if(n)for(let o=0;o<n.length;o++){const a=n[o];if(!(!a.includeMask.equals(t)||!(s===null?a.excludeMask===null:a.excludeMask!==null&&a.excludeMask.equals(s))||!(r===null?a.anyOfMask===null:a.anyOfMask!==null&&a.anyOfMask.equals(r))))return a}}addDedup(e,t){Fe(this.dedup,e,t)}}const ve=Object.freeze([]),Mt=Object.freeze([]),Oe=Object.freeze([]),Z=Number.POSITIVE_INFINITY,re=65536;function q(c,e){if(c>=re||e>=re)throw new i.ECSError(i.ECS_ERROR.SPARSE_CACHE_KEY_OVERFLOW,`sparse query cache key would overflow: query_id=${c}, sparse_id=${e} (each must be < ${re})`);return(c<<16|e)>>>0}function Q(c,e){for(let t=0;t<c.length;t++)if(c[t]===e)return c;return[...c,e]}function Lt(c,e){for(let t=0;t<c.length;t++)if(c[t]===e)return c;return[...c,e]}function Ae(c,e){for(let t=0;t<c.length;t++)if(c[t]===e)return c;return[...c,e]}class $e{_arch;_tick=0;mut(e){return this._arch.columnGroupMut(e,this._tick)}read(e){return this._arch.columnGroupRead(e)}}class D{_archetypes;_defs;_resolver;_include;_exclude;_anyOf;_nonEmptyArchetypes=[];_lastSeenEpoch=-1;_id;_sparseInclude;_sparseExclude;_optional;_includeDisabled;_relationIncludes;_relationExcludes;_hierarchy;constructor(e,t,s,r,n,o,a,h=ve,l=ve,u=Mt,d=!1,f=Oe,p=Oe,g=null){this._archetypes=e,this._defs=t,this._resolver=s,this._include=r,this._exclude=n,this._anyOf=o,this._id=a,this._sparseInclude=h,this._sparseExclude=l,this._optional=u,this._includeDisabled=d,this._relationIncludes=f,this._relationExcludes=p,this._hierarchy=g}_assertDenseOnly(e){if(this._sparseInclude.length>0||this._sparseExclude.length>0||this._relationIncludes.length>0||this._relationExcludes.length>0||this._hierarchy!==null)throw new i.ECSError(i.ECS_ERROR.SPARSE_QUERY_DENSE_PATH,`Query.${e} ignores sparse / relation-wildcard / hierarchy terms (withSparse / withoutSparse / withRelation / withoutRelation / hierarchy) — it walks only the dense archetype list and would return the wrong result (a hierarchy term has no per-archetype span — its order spans archetypes). Iterate this query with forEachEntity instead.`)}_isDenseOnly(){return this._sparseInclude.length===0&&this._sparseExclude.length===0&&this._relationIncludes.length===0&&this._relationExcludes.length===0&&this._hierarchy===null}firstEntity(){if(this._isDenseOnly()){const t=this._nonEmpty();for(let s=0;s<t.length;s++)if((this._includeDisabled?t[s].totalCount:t[s].enabledCount)>0)return t[s].entityIds[0];return}let e;return this.forEachEntity(t=>{e===void 0&&(e=t)}),e}singleEntity(){{const e=this._isDenseOnly()?this.entityCount:this._countViaWalk();if(e!==1)throw new i.ECSError(i.ECS_ERROR.QUERY_NOT_SINGLETON,`Query.singleEntity: expected exactly 1 matching entity, found ${e}`,{count:e})}return this.firstEntity()}_countViaWalk(){let e=0;return this.forEachEntity(()=>{e++}),e}get archetypeCount(){return this._assertDenseOnly("archetypeCount"),this._archetypes.length}get entityCount(){this._assertDenseOnly("entityCount");const e=this._nonEmpty();let t=0;if(this._includeDisabled)for(let s=0;s<e.length;s++)t+=e[s].totalCount;else for(let s=0;s<e.length;s++)t+=e[s].enabledCount;return t}get archetypes(){return this._archetypes}_carryNondense(e){return this._optional.length===0&&this._sparseInclude.length===0&&this._sparseExclude.length===0&&!this._includeDisabled&&this._relationIncludes.length===0&&this._relationExcludes.length===0&&this._hierarchy===null?e:new D(e._archetypes,e._defs,this._resolver,e._include,e._exclude,e._anyOf,this._resolver._nextQueryId(),this._sparseInclude,this._sparseExclude,this._optional,this._includeDisabled,this._relationIncludes,this._relationExcludes,this._hierarchy)}and(...e){if(e.length===1){const s=e[0].id,r=(this._id<<16|s)>>>0,n=this._resolver._caches.andSingle.get(r);return n!==void 0?n:this._andMiss(e[0],s,r)}let t=this;for(let s=0;s<e.length;s++)t=t.and(e[s]);return t}_andMiss(e,t,s){const r=this._include.copy(),n=this._defs.slice();r.has(t)||(r.set(t),n.push(e));const o=this._carryNondense(this._resolver._resolveQuery(r,this._exclude,this._anyOf,n));return this._resolver._caches.andSingle.set(s,o),o}without(...e){if(e.length===1){const s=e[0].id,r=(this._id<<16|s)>>>0,n=this._resolver._caches.notSingle.get(r);return n!==void 0?n:this._notMiss(s,r)}let t=this;for(let s=0;s<e.length;s++)t=t.without(e[s]);return t}_notMiss(e,t){const s=this._exclude?this._exclude.copy():new T.BitSet;s.set(e);const r=this._carryNondense(this._resolver._resolveQuery(this._include,s,this._anyOf,this._defs));return this._resolver._caches.notSingle.set(t,r),r}withSparse(...e){if(e.length===1)return this._withSparseOne(e[0]);let t=this;for(let s=0;s<e.length;s++)t=t._withSparseOne(e[s]);return t}_withSparseOne(e){const t=q(this._id,e),s=this._resolver._caches.withSparseSingle,r=s.get(t);if(r!==void 0)return r;const n=this._deriveSparse(Q(this._sparseInclude,e),this._sparseExclude);return s.set(t,n),n}withoutSparse(...e){if(e.length===1)return this._withoutSparseOne(e[0]);let t=this;for(let s=0;s<e.length;s++)t=t._withoutSparseOne(e[s]);return t}_withoutSparseOne(e){const t=q(this._id,e),s=this._resolver._caches.withoutSparseSingle,r=s.get(t);if(r!==void 0)return r;const n=this._deriveSparse(this._sparseInclude,Q(this._sparseExclude,e));return s.set(t,n),n}_deriveSparse(e,t){return new D(this._archetypes,this._defs,this._resolver,this._include,this._exclude,this._anyOf,this._resolver._nextQueryId(),e,t,this._optional,this._includeDisabled,this._relationIncludes,this._relationExcludes,this._hierarchy)}withRelation(...e){if(e.length===1)return this._withRelationOne(e[0]);let t=this;for(let s=0;s<e.length;s++)t=t._withRelationOne(e[s]);return t}_withRelationOne(e){const t=q(this._id,e),s=this._resolver._caches.withRelationSingle,r=s.get(t);if(r!==void 0)return r;const n=this._resolver._relationBackingSparseId(e),o=this._deriveRelation(Q(this._sparseInclude,n),this._sparseExclude,Ae(this._relationIncludes,e),this._relationExcludes);return s.set(t,o),o}withoutRelation(...e){if(e.length===1)return this._withoutRelationOne(e[0]);let t=this;for(let s=0;s<e.length;s++)t=t._withoutRelationOne(e[s]);return t}_withoutRelationOne(e){const t=q(this._id,e),s=this._resolver._caches.withoutRelationSingle,r=s.get(t);if(r!==void 0)return r;const n=this._resolver._relationBackingSparseId(e),o=this._deriveRelation(this._sparseInclude,Q(this._sparseExclude,n),this._relationIncludes,Ae(this._relationExcludes,e));return s.set(t,o),o}_deriveRelation(e,t,s,r){return new D(this._archetypes,this._defs,this._resolver,this._include,this._exclude,this._anyOf,this._resolver._nextQueryId(),e,t,this._optional,this._includeDisabled,s,r,this._hierarchy)}hierarchy(e,t=Z){{if(this._hierarchy!==null)throw new i.ECSError(i.ECS_ERROR.HIERARCHY_ALREADY_SET,"hierarchy() is already set on this query — a query carries a single depth ordering");if(t!==Z&&(!Number.isInteger(t)||t<0))throw new i.ECSError(i.ECS_ERROR.HIERARCHY_INVALID_MAX_DEPTH,`hierarchy() max_depth must be HIERARCHY_UNBOUNDED or a non-negative integer, got ${t}`)}if(t===Z){const s=q(this._id,e),r=this._resolver._caches.hierarchySingle,n=r.get(s);if(n!==void 0)return n;const o=this._deriveHierarchy({relation:e,maxDepth:t});return r.set(s,o),o}return this._deriveHierarchy({relation:e,maxDepth:t})}_deriveHierarchy(e){return new D(this._archetypes,this._defs,this._resolver,this._include,this._exclude,this._anyOf,this._resolver._nextQueryId(),this._sparseInclude,this._sparseExclude,this._optional,this._includeDisabled,this._relationIncludes,this._relationExcludes,e)}_checkRelationAccess(){for(let e=0;e<this._relationIncludes.length;e++)i.accessCheck.checkRelationRead(this._relationIncludes[e]);for(let e=0;e<this._relationExcludes.length;e++)i.accessCheck.checkRelationRead(this._relationExcludes[e])}forEachRelatedTo(e,t){i.accessCheck.checkRelationReadAny(),this._checkRelationAccess(),this._resolver._forEachRelationTargetMatch(e,this._include,this._exclude,this._anyOf,this._sparseInclude,this._sparseExclude,this._includeDisabled,t)}optional(...e){if(e.length===1)return this._optionalOne(e[0].id);let t=this;for(let s=0;s<e.length;s++)t=t._optionalOne(e[s].id);return t}_optionalOne(e){const t=(this._id<<16|e)>>>0,s=this._resolver._caches.optionalSingle,r=s.get(t);if(r!==void 0)return r;const n=this._deriveOptional(Lt(this._optional,e));return s.set(t,n),n}_deriveOptional(e){return new D(this._archetypes,this._defs,this._resolver,this._include,this._exclude,this._anyOf,this._resolver._nextQueryId(),this._sparseInclude,this._sparseExclude,e,this._includeDisabled,this._relationIncludes,this._relationExcludes,this._hierarchy)}includeDisabled(){if(this._includeDisabled)return this;const e=this._resolver._caches.includeDisabledSingle,t=e.get(this._id);if(t!==void 0)return t;const s=new D(this._archetypes,this._defs,this._resolver,this._include,this._exclude,this._anyOf,this._resolver._nextQueryId(),this._sparseInclude,this._sparseExclude,this._optional,!0,this._relationIncludes,this._relationExcludes,this._hierarchy);return e.set(this._id,s),s}forEach(e){if(this._includeDisabled){this._forEachIncludeDisabled(e);return}{this._assertDenseOnly("forEach"),i.accessCheck.enterOptionalScope(this._optional);try{const t=this._nonEmpty();for(let s=0;s<t.length;s++){const r=t[s];r._iterDepth++;try{e(r)}finally{r._iterDepth--}}}finally{i.accessCheck.leaveOptionalScope()}return}}_forEachIncludeDisabled(e){const t=N(!0);try{this._forEachInner(e)}finally{N(t)}}eachChunk(e){if(this._includeDisabled){const t=N(!0);try{this._eachChunkInner(e)}finally{N(t)}return}this._eachChunkInner(e)}_eachChunkInner(e){const t=new $e;t._tick=this._resolver._getCurrentTick();{this._assertDenseOnly("eachChunk"),i.accessCheck.enterOptionalScope(this._optional);try{const s=this._nonEmpty();for(let r=0;r<s.length;r++){const n=s[r];t._arch=n,n._iterDepth++;try{e(t,n.entityCount)}finally{n._iterDepth--}}}finally{i.accessCheck.leaveOptionalScope()}return}}forEachUntil(e){if(this._includeDisabled){const t=N(!0);try{return this._forEachUntilInner(e)}finally{N(t)}}return this._forEachUntilInner(e)}_forEachUntilInner(e){{this._assertDenseOnly("forEachUntil"),i.accessCheck.enterOptionalScope(this._optional);try{const s=this._nonEmpty();for(let r=0;r<s.length;r++){const n=s[r];n._iterDepth++;try{if(e(n))return!0}finally{n._iterDepth--}}return!1}finally{i.accessCheck.leaveOptionalScope()}}const t=this._nonEmpty();for(let s=0;s<t.length;s++)if(e(t[s]))return!0;return!1}_forEachInner(e){{this._assertDenseOnly("forEach"),i.accessCheck.enterOptionalScope(this._optional);try{const t=this._nonEmpty();for(let s=0;s<t.length;s++){const r=t[s];r._iterDepth++;try{e(r)}finally{r._iterDepth--}}}finally{i.accessCheck.leaveOptionalScope()}return}}forEachEntity(e){if(this._checkRelationAccess(),this._hierarchy!==null){i.accessCheck.checkRelationRead(this._hierarchy.relation),this._resolver._forEachHierarchyMatch(this._include,this._exclude,this._anyOf,this._sparseInclude,this._sparseExclude,this._nonEmpty(),this._hierarchy.relation,this._hierarchy.maxDepth,this._includeDisabled,e);return}this._resolver._forEachSparseMatch(this._include,this._exclude,this._anyOf,this._sparseInclude,this._sparseExclude,this._nonEmpty(),e,this._includeDisabled)}_nonEmpty(){const e=this._resolver._getQueryDirtyEpoch();return this._lastSeenEpoch!==e&&this._rebuildNonEmpty(e),this._nonEmptyArchetypes}_rebuildNonEmpty(e){const t=this._archetypes,s=[];if(this._includeDisabled)for(let r=0;r<t.length;r++)t[r].totalCount>0&&s.push(t[r]);else for(let r=0;r<t.length;r++)t[r].enabledCount>0&&s.push(t[r]);this._nonEmptyArchetypes=s,this._lastSeenEpoch=e}anyOf(...e){if(e.length===1){const s=e[0].id,r=(this._id<<16|s)>>>0,n=this._resolver._caches.anyOfSingle.get(r);return n!==void 0?n:this._anyOfMiss(s,r)}let t=this;for(let s=0;s<e.length;s++)t=t.anyOf(e[s]);return t}_anyOfMiss(e,t){const s=this._anyOf?this._anyOf.copy():new T.BitSet;s.set(e);const r=this._carryNondense(this._resolver._resolveQuery(this._include,this._exclude,s,this._defs));return this._resolver._caches.anyOfSingle.set(t,r),r}changed(...e){if(e.length===1){const s=e[0].id,r=(this._id<<16|s)>>>0,n=this._resolver._caches.changedSingle.get(r);return n!==void 0?n:this._changedMiss(s,r)}const t=new Array(e.length);for(let s=0;s<e.length;s++)t[s]=e[s].id;return new x(this,t)}_changedMiss(e,t){const s=new x(this,[e]);return this._resolver._caches.changedSingle.set(t,s),s}_ctxLastRunTick(){return this._resolver._getLastRunTick()}}class Be{constructor(e){this._resolver=e}with(...e){const t=new T.BitSet;for(let s=0;s<e.length;s++)t.set(e[s].id);return this._resolver._resolveQuery(t,null,null,e)}}class Ge{constructor(e){this.store=e}spawn(...e){const t=this.store.createEntity();this.store._trace?.commandQueued("spawn",t,null);for(let s=0;s<e.length;s++){const r=G(e[s]);i.accessCheck.checkAdd(r),this.store.addComponentDeferred(t,r,P(e[s])),this.store._trace?.commandQueued("add",t,r.id)}return t}add(e,...t){if(t.length===2&&typeof t[0]=="function"&&t[1]!==null&&typeof t[1]=="object"&&typeof t[1].def!="function"){const s=t[0];return i.accessCheck.checkAdd(s),this.store.addComponentDeferred(e,s,t[1]),this.store._trace?.commandQueued("add",e,s.id),this}for(let s=0;s<t.length;s++){const r=t[s],n=G(r);i.accessCheck.checkAdd(n),this.store.addComponentDeferred(e,n,P(r)),this.store._trace?.commandQueued("add",e,n.id)}return this}remove(e,t){return i.accessCheck.checkRemove(t),this.store.removeComponentDeferred(e,t),this.store._trace?.commandQueued("remove",e,t.id),this}despawn(e){i.accessCheck.checkDestroy();const t=e;return this.store.destroyEntityDeferred(t),this.store._trace?.commandQueued("despawn",t,null),this}disable(e){return this.store.disableEntityDeferred(e),this.store._trace?.commandQueued("disable",e,null),this}enable(e){return this.store.enableEntityDeferred(e),this.store._trace?.commandQueued("enable",e,null),this}}class Pe{constructor(e){this.store=e,this.commands=new Ge(e)}lastRunTick=0;commands;get ecsTick(){return this.store._tick}get _trace(){return this.store._trace}isAlive(e){return this.store.isAlive(e)}hasComponent(e,t){return this.store.hasComponent(e,t)}getField(e,t,s){if(i.accessCheck.checkRead(t),!this.store.isAlive(e))throw i.entityNotAliveError("ctx.getField",e,i.componentLabel(t));const r=this.store.getEntityArchetype(e),n=this.store.getEntityRow(e);return r.readField(n,t.id,s)}tryGetField(e,t,s){if(i.accessCheck.checkRead(t),!this.store.hasComponent(e,t))return;const r=this.store.getEntityArchetype(e),n=this.store.getEntityRow(e);return r.readField(n,t.id,s)}setField(e,t,s,r){if(!this.store.isAlive(e))throw i.entityNotAliveError("ctx.setField",e,i.componentLabel(t));const n=this.store.getEntityArchetype(e),o=this.store.getEntityRow(e),a=n.getColumn(t,s,this.store._tick);a[o]=r,this.store._anyDirtyTracked&&this.store._noteSet(t,e)}updateField(e,t,s,r){if(i.accessCheck.checkRead(t),!this.store.isAlive(e))throw i.entityNotAliveError("ctx.updateField",e,i.componentLabel(t));const n=this.store.getEntityArchetype(e),o=this.store.getEntityRow(e),a=r(n.readField(o,t.id,s)),h=n.getColumn(t,s,this.store._tick);return h[o]=a,this.store._anyDirtyTracked&&this.store._noteSet(t,e),a}markChanged(e,t){this.store._anyDirtyTracked&&this.store._noteSet(t,e)}ref(e,t){if(i.accessCheck.checkWrite(e),!this.store.isAlive(t))throw i.entityNotAliveError("ctx.ref",t,i.componentLabel(e));const s=this.store.getEntityArchetype(t),r=this.store.getEntityRow(t);if(s.columnGroups[e.id]===void 0)throw new i.ECSError(i.ECS_ERROR.COMPONENT_NOT_REGISTERED,`ctx.ref: ${i.componentLabel(e)} has no columns in this archetype — the entity doesn't hold it, or it is a tag (no fields to ref)`,{component:e.id,entity:t});return s._changedTick[e.id]=this.store._tick,ce(s.columnGroups[e.id],r)}refRead(e,t){if(i.accessCheck.checkRead(e),!this.store.isAlive(t))throw i.entityNotAliveError("ctx.refRead",t,i.componentLabel(e));const s=this.store.getEntityArchetype(t),r=this.store.getEntityRow(t);if(s.columnGroups[e.id]===void 0)throw new i.ECSError(i.ECS_ERROR.COMPONENT_NOT_REGISTERED,`ctx.refRead: ${i.componentLabel(e)} has no columns in this archetype — the entity doesn't hold it, or it is a tag (no fields to ref)`,{component:e.id,entity:t});return ce(s.columnGroups[e.id],r)}isDisabled(e){return this.store.isDisabled(e)}addSparse(e,t,...s){return i.accessCheck.checkSparseWrite(t),this.store.addSparse(e,t,s[0]),this}removeSparse(e,t){return i.accessCheck.checkSparseWrite(t),this.store.removeSparse(e,t),this}hasSparse(e,t){return this.store.hasSparse(e,t)}getSparseField(e,t,s){return i.accessCheck.checkSparseRead(t),this.store.getSparseField(e,t,s)}setSparseField(e,t,s,r){i.accessCheck.checkSparseWrite(t),this.store.setSparseField(e,t,s,r)}addRelation(e,t,s){return i.accessCheck.checkRelationWrite(t),this.store.addRelation(e,t,s),this}removeRelation(e,t,s){return i.accessCheck.checkRelationWrite(t),this.store.removeRelation(e,t,s),this}targetOf(e,t){return i.accessCheck.checkRelationRead(t),this.store.targetOf(e,t)}targetsOf(e,t){return i.accessCheck.checkRelationRead(t),this.store.targetsOf(e,t)}sourcesOf(e,t){return i.accessCheck.checkRelationRead(t),this.store.sourcesOf(e,t)}hasRelation(e,t){return this.store.hasRelation(e,t)}flush(){this.store.flushStructural(),this.store.flushDestroyed(),this.store.publishRowCountsToDescriptor()}emit(e,t){i.dispatchTrace.isActive()&&i.dispatchTrace.recordEmit(e.description??""),this.store._trace?.eventEmitted(e.description??"");const s=this.store.getEventDefByKey(e);t===void 0?this.store.emitSignal(s):this.store.emitEvent(s,t)}read(e){i.dispatchTrace.isActive()&&i.dispatchTrace.recordRead(e.description??"");const t=this.store.getEventDefByKey(e),s=this.store.getEventReader(t);return this.store._trace?.eventRead(e.description??"",s.length),s}getResource(e){return i.accessCheck.checkResourceRead(e),i.dispatchTrace.isActive()&&i.dispatchTrace.recordResourceRead(e.description??""),i.unsafeCast(this.store.getResource(e))}setResource(e,t){i.accessCheck.checkResourceWrite(e),i.dispatchTrace.isActive()&&i.dispatchTrace.recordResourceWrite(e.description??""),this.store.setResource(e,t)}removeResource(e){i.accessCheck.checkResourceWrite(e),i.dispatchTrace.isActive()&&i.dispatchTrace.recordResourceRemove(e.description??""),this.store.removeResource(e)}hasResource(e){return this.store.hasResource(e)}}class x{_query;_changedIds;constructor(e,t){this._query=e,this._changedIds=t;for(let s=0;s<t.length;s++)if(!e._include.has(t[s]))throw new i.ECSError(i.ECS_ERROR.COMPONENT_NOT_REGISTERED,`changed() component ${t[s]} is not in query's include mask`)}and(...e){return new x(this._query.and(...e),this._changedIds)}without(...e){return new x(this._query.without(...e),this._changedIds)}anyOf(...e){return new x(this._query.anyOf(...e),this._changedIds)}optional(...e){return new x(this._query.optional(...e),this._changedIds)}forEach(e){if(this._query._includeDisabled){this._forEachIncludeDisabled(e);return}const t=this._query._ctxLastRunTick(),s=this._query._nonEmpty(),r=this._changedIds;{i.accessCheck.enterOptionalScope(this._query._optional);try{for(let n=0;n<s.length;n++){const o=s[n];for(let a=0;a<r.length;a++)if(o._changedTick[r[a]]>=t){o._iterDepth++;try{e(o)}finally{o._iterDepth--}break}}}finally{i.accessCheck.leaveOptionalScope()}return}}_forEachIncludeDisabled(e){const t=N(!0);try{this._forEachInner(e)}finally{N(t)}}_forEachInner(e){const t=this._query._ctxLastRunTick(),s=this._query._nonEmpty(),r=this._changedIds;{i.accessCheck.enterOptionalScope(this._query._optional);try{for(let n=0;n<s.length;n++){const o=s[n];for(let a=0;a<r.length;a++)if(o._changedTick[r[a]]>=t){o._iterDepth++;try{e(o)}finally{o._iterDepth--}break}}}finally{i.accessCheck.leaveOptionalScope()}return}}}const be=new Set(["fixedTimestep","maxFixedSteps","onWarn","memory","regions","bindingsRegionBytes","deterministic"]);function Ie(c){if(!(c>0)||!Number.isFinite(c))throw new i.ECSError(i.ECS_ERROR.INVALID_FIXED_TIMESTEP,`fixedTimestep must be a finite number > 0, got ${c}`);return c}function Ft(c){if(!Number.isInteger(c)||c<1)throw new i.ECSError(i.ECS_ERROR.INVALID_MAX_FIXED_STEPS,`maxFixedSteps must be an integer >= 1, got ${c}`);return c}class $t{store;schedule;ctx;_observers;relations;events;resources;snapshots;systems=new Set;nextSystemId=0;_tick=0;_updating=!1;_fixedTimestep;_accumulator=0;_maxFixedSteps;scratchMask=new T.BitSet;_nextQueryIdCounter=0;_caches=new xt;_layoutSubscribers=[];_backend=null;_memory;get memoryPlan(){return this._memory}get wasmMemory(){return this._memory.wasmMemory}constructor(e){const t=Object.prototype.hasOwnProperty;if(e!==void 0&&(t.call(e,"initial_capacity")||t.call(e,"buffer_allocator")))throw new i.ECSError(i.ECS_ERROR.INVALID_MEMORY_OPTIONS,"ECSOptions.initial_capacity / buffer_allocator were replaced by ECSOptions.memory: initial_capacity → memory.columnCapacity (or memory.budget); buffer_allocator → memory.wasm (WASM-backed) or memory.allocator (custom in-place).");if(e!==void 0)for(const r of Object.keys(e))be.has(r)||(e.onWarn??console.warn)(`ECSOptions: unknown option '${r}' ignored — known options: ${[...be].join(", ")}`);const s=i.resolveECSMemory(e?.memory);this._memory=s,this.store=new It({initialCapacity:s.columnCapacity,bufferAllocator:s.allocator,entityIndexCapacity:s.entityIndexCapacity,capContext:{capBytes:s.capBytes,intentLabel:s.intentLabel,budgetEntities:s.budgetEntities},onBufferResized:()=>{const r=this._layoutSubscribers;for(let n=0;n<r.length;n++)r[n].setLayout(0)},regions:e?.regions,bindingsRegionBytes:e?.bindingsRegionBytes,deterministic:e?.deterministic}),this.schedule=new i.Schedule(e?.onWarn),this.relations=new Tt(this.store),this.events=new Dt(this.store),this.resources=new kt(this.store),this.snapshots=new Nt(this.store),this.ctx=new Pe(this.store),this._observers=new it(this.store,this.ctx),this.store.setStructuralObserverHook(r=>this._observers.dispatchStructural(r)),this._fixedTimestep=Ie(e?.fixedTimestep??i.DEFAULT_FIXED_TIMESTEP),this._maxFixedSteps=Ft(e?.maxFixedSteps??i.DEFAULT_MAX_FIXED_STEPS)}regionHandles(...e){const t=new Array(e.length);let s=null;for(let r=0;r<e.length;r++){const n=this.store.regionHandle(e[r]);n===null?(s??=[]).push(e[r]):t[r]=n}if(s!==null)throw new i.ECSError(i.ECS_ERROR.REGION_NOT_DECLARED,`region_handles: region id(s) [${s.join(", ")}] not declared — pass them via ECSOptions.regions`);return t}onStoreLayoutPublished(e){return this._layoutSubscribers.push(e),e.setLayout(0),()=>{const t=this._layoutSubscribers.indexOf(e);t>=0&&this._layoutSubscribers.splice(t,1)}}attachBackend(e){if(this._backend!==null)throw new i.ECSError(i.ECS_ERROR.BACKEND_ALREADY_ATTACHED,"A ComputeBackend is already attached; detach it before attaching another (one backend per ECS).");this._backend=e,this.schedule.setBackend(e);const t=this.onStoreLayoutPublished(e);return()=>{t(),this._backend===e&&(this._backend=null,this.schedule.setBackend(null))}}get fixedTimestep(){return this._fixedTimestep}set fixedTimestep(e){this._fixedTimestep=Ie(e)}get fixedAlpha(){return this._accumulator/this._fixedTimestep}setTrace(e){this.store._trace=e}registerComponent(e,t,s){if(Array.isArray(e)){const n=typeof t=="string"?t:"f64",o=Object.create(null);for(const a of e)o[a]=n;return this.store.registerComponent(o,s?.name)}const r=typeof t=="object"?t:s;return this.store.registerComponent(e,r?.name)}registerSparseComponent(e,t,s){if(Array.isArray(e)){const n=typeof t=="string"?t:"f64",o=Object.create(null);for(const a of e)o[a]=n;return this.store.registerSparseComponent(o,s?.name)}const r=typeof t=="object"?t:s;return this.store.registerSparseComponent(e,r?.name)}spawn(e,t){return this._assertHostMutationOutsideSystem("spawn","ctx.commands.spawn (deferred to the phase flush)"),e===void 0?this.store.createEntity():this.store.spawn(e,t)}spawnBundle(...e){this._assertHostMutationOutsideSystem("spawnBundle","ctx.commands.spawn (deferred to the phase flush)");const t=this.store.createEntity();for(let s=0;s<e.length;s++){const r=e[s],n=G(r);i.accessCheck.checkAdd(n),this.store.addComponent(t,n,P(r))}return t}spawnMany(e,t,s){return this._assertHostMutationOutsideSystem("spawnMany","ctx.commands.spawn (deferred to the phase flush)"),this.store.spawnMany(e,t,s)}_assertHostMutationOutsideSystem(e,t){if(this._updating&&i.accessCheck.current()!==null){const s=i.accessCheck.current(),r=s.name??`system_${s.id}`;throw new i.ECSError(i.ECS_ERROR.ACCESS_UNDECLARED,`ecs.${e} called from inside system '${r}' — host ${e} is immediate and unsafe mid-iteration (and invisible to observers); use ${t} instead`,{op:e})}}despawn(e){return this._assertHostMutationOutsideSystem("despawn","ctx.commands.despawn (deferred to the phase flush)"),this.store.destroyEntity(e),this}disable(e){return this._assertHostMutationOutsideSystem("disable","ctx.commands.disable (deferred to the phase flush)"),this.store.disableEntity(e),this}enable(e){return this._assertHostMutationOutsideSystem("enable","ctx.commands.enable (deferred to the phase flush)"),this.store.enableEntity(e),this}addComponent(e,t,s){const r=G(t);return this._assertHostMutationOutsideSystem("addComponent","ctx.commands.add (deferred to the phase flush)"),i.accessCheck.checkAdd(r),this.store.addComponent(e,r,s??P(t)),this}addComponents(e,...t){const s=[];for(let r=0;r<t.length;r++){const n=t[r];s.push({def:G(n),values:P(n)})}{this._assertHostMutationOutsideSystem("addComponents","ctx.commands.add (deferred to the phase flush)");for(let r=0;r<s.length;r++)i.accessCheck.checkAdd(s[r].def)}return this.store.addComponents(e,s),this}removeComponent(e,t){return this._assertHostMutationOutsideSystem("removeComponent","ctx.commands.remove (deferred to the phase flush)"),i.accessCheck.checkRemove(t),this.store.removeComponent(e,t),this}removeComponents(e,...t){{this._assertHostMutationOutsideSystem("removeComponents","ctx.commands.remove (deferred to the phase flush)");for(let s=0;s<t.length;s++)i.accessCheck.checkRemove(t[s])}return this.store.removeComponents(e,t),this}batchAddComponent(e,t,s){return this._assertHostMutationOutsideSystem("batchAddComponent","ctx.commands.add per entity, or the batch after update() returns"),i.accessCheck.checkAdd(t),this.store.batchAddComponent(e,t,s),this}batchRemoveComponent(e,t){return this._assertHostMutationOutsideSystem("batchRemoveComponent","ctx.commands.remove per entity, or the batch after update() returns"),i.accessCheck.checkRemove(t),this.store.batchRemoveComponent(e,t),this}getField(e,t,s){if(i.accessCheck.checkRead(t),!this.store.isAlive(e))throw i.entityNotAliveError("getField",e,i.componentLabel(t));const r=this.store.getEntityArchetype(e),n=this.store.getEntityRow(e);return r.readField(n,t.id,s)}refRead(e,t){if(i.accessCheck.checkRead(e),!this.store.isAlive(t))throw i.entityNotAliveError("refRead",t,i.componentLabel(e));const s=this.store.getEntityArchetype(t),r=this.store.getEntityRow(t);if(s.columnGroups[e.id]===void 0)throw new i.ECSError(i.ECS_ERROR.COMPONENT_NOT_REGISTERED,`refRead: ${i.componentLabel(e)} has no columns in this archetype — the entity doesn't hold it, or it is a tag (no fields to ref)`,{component:e.id,entity:t});return ce(s.columnGroups[e.id],r)}tryGetField(e,t,s){if(i.accessCheck.checkRead(t),!this.store.hasComponent(e,t))return;const r=this.store.getEntityArchetype(e),n=this.store.getEntityRow(e);return r.readField(n,t.id,s)}setField(e,t,s,r){if(!this.store.isAlive(e))throw i.entityNotAliveError("setField",e,i.componentLabel(t));const n=this.store.getEntityArchetype(e),o=this.store.getEntityRow(e),a=n.getColumn(t,s,this.store._tick);a[o]=r,this.store._anyDirtyTracked&&this.store._noteSet(t,e)}updateField(e,t,s,r){const n=r(this.getField(e,t,s));return this.setField(e,t,s,n),n}query(...e){const t=this.scratchMask;t._words.fill(0);for(let s=0;s<e.length;s++)t.set(e[s].id);return this._resolveQuery(t.copy(),null,null,e)}_nextQueryId(){return this._nextQueryIdCounter++}_resolveQuery(e,t,s,r){const n=e.hash(),o=t?t.hash():0,a=s?s.hash():0,h=n^Math.imul(o,i.HASH_GOLDEN_RATIO)^Math.imul(a,i.HASH_SECONDARY_PRIME)|0,l=this._caches.findDedup(h,e,t,s);if(l!==void 0)return l.query;const u=this.store.registerQuery(e,t??void 0,s??void 0),d=new D(u,r,this,e.copy(),t?.copy()??null,s?.copy()??null,this._nextQueryIdCounter++);return this.store.updateQueryRef(u,d),this._caches.addDedup(h,{includeMask:e.copy(),excludeMask:t?.copy()??null,anyOfMask:s?.copy()??null,query:d}),d}registerSystem(e,t){let s;if(typeof e=="function")if(t!==void 0){const o=t(new Be(this)),a=this.ctx,h=e;s={...ae,fn:(l,u)=>h(o,a,u)}}else{if(e.length>=3)throw new i.ECSError(i.ECS_ERROR.SYSTEM_FN_ARITY,`registerSystem was passed a ${e.length}-parameter function with no query builder. A bare system function is (ctx, dt); a query system is (q, ctx, dt) and needs the query builder as the second argument: registerSystem((q, ctx, dt) => …, (qb) => qb.with(…)). Without it, q would receive the SystemContext and dt would be undefined.`);s={...ae,fn:e}}else s=e;if(Je(s),s.fn===void 0&&s.backendHandle===void 0)throw new i.ECSError(i.ECS_ERROR.SYSTEM_FN_ARITY,`registerSystem: config${s.name?` '${s.name}'`:""} has neither 'fn' nor 'backendHandle' — provide a system body, or a backend handle for backend execution`);const r=ke(this.nextSystemId++),n=Object.freeze({...s,...Ze(s),id:r});return this.systems.add(n),n}removeSystem(e){return this.schedule.removeSystem(e),e.onRemoved?.(),this.systems.delete(e),this}get systemCount(){return this.systems.size}startup(){this.prewarmArchetypes(),this._updating=!0;try{for(const e of this.systems.values())if(e.onAdded!==void 0){I&&i.accessCheck.enter(e);try{e.onAdded(this.ctx)}finally{I&&i.accessCheck.leave()}}this.schedule.runStartup(this.ctx,this._tick)}finally{this._updating=!1}this.store.clearEvents()}prewarmArchetypes(){const e=Bt([...this.systems,...this._observers.descriptors()]);e.length!==0&&this.store.archCreateManyFromMasks(e)}update(e){const t=i.accessCheck.current();try{if(I&&(this._updating=!0),this.store._tick=this._tick,I&&this.store._trace?.tickBegin(this._tick,e),this.store.publishRowCountsToDescriptor(),this.schedule.hasFixedSystems()){this._accumulator+=e;const r=this._maxFixedSteps*this._fixedTimestep;for(this._accumulator>r&&(this._accumulator=r);this._accumulator>=this._fixedTimestep;)this.schedule.runFixedUpdate(this.ctx,this._fixedTimestep,this._tick),this._accumulator-=this._fixedTimestep}this.schedule.runUpdate(this.ctx,e,this._tick);const s=I?this.store._devBufferedEventCount():0;if(this._observers.dispatchSet(this._tick),I&&this.store._devBufferedEventCount()!==s)throw new i.ECSError(i.ECS_ERROR.OBSERVER_ONSET_EMIT,"onSet observer emitted an event; onSet runs at the tick tail and its emissions would be dropped at clear_events. Emit from a system instead.");this.store.clearEvents(),I&&this.store._trace?.tickEnd(this._tick),this._tick++}finally{this._updating=!1,t!==null&&i.accessCheck.enter(t)}}dispose(){for(const e of this.systems.values())e.dispose?.(),e.onRemoved?.();this.systems.clear(),this.schedule.clear()}template(...e){const t=[];for(let s=0;s<e.length;s++){const r=e[s];t.push({def:G(r),values:P(r)})}return this.store.resolveTemplate(t)}regionOffset(e){return this.store.regionOffset(e)}regionHandle(e){return this.store.regionHandle(e)}fieldId(e,t){return this.store.fieldIdOf(e,t)}entityIdAtRow(e,t){return this.store.entityIdAtRow(e,t)}get columnStore(){return this.store.columnStore}get archetypeCount(){return this.store.archetypeCount}registerTag(){return this.store.registerComponent({})}registerSparseTag(){return this.store.registerSparseComponent({})}isAlive(e){return this.store.isAlive(e)}get entityCount(){return this.store.entityCount}hasComponent(e,t){return this.store.hasComponent(e,t)}isDisabled(e){return this.store.isDisabled(e)}addSparse(e,t,s){return this.store.addSparse(e,t,s),this}removeSparse(e,t){return this.store.removeSparse(e,t),this}hasSparse(e,t){return this.store.hasSparse(e,t)}getSparseField(e,t,s){return this.store.getSparseField(e,t,s)}setSparseField(e,t,s,r){this.store.setSparseField(e,t,s,r)}_getLastRunTick(){return this.ctx.lastRunTick}_getCurrentTick(){return this.store._tick}_getQueryDirtyEpoch(){return this.store._queryDirtyEpoch}_forEachSparseMatch(e,t,s,r,n,o,a,h){this.store._forEachSparseMatch(e,t,s,r,n,o,a,h)}_relationBackingSparseId(e){return this.store.relationBackingSparseId(e)}_forEachRelationTargetMatch(e,t,s,r,n,o,a,h){this.store._forEachRelationTargetMatch(e,t,s,r,n,o,a,h)}_forEachHierarchyMatch(e,t,s,r,n,o,a,h,l,u){this.store._forEachHierarchyMatch(e,t,s,r,n,o,a,h,l,u)}addSystems(e,...t){return this.schedule.addSystems(e,...t),this}configureSet(e,t){return this.schedule.configureSet(e,t),this}observe(e,t){return this._observers.register(e,t)}publishArchetypeRowCounts(){this.store.publishRowCountsToDescriptor()}flush(){this.ctx.flush()}}function Bt(c){const e=new Map,t=[],s=a=>{const h=a.hash(),l=e.get(h);if(l!==void 0){for(let u=0;u<l.length;u++)if(l[u].equals(a))return;l.push(a)}else e.set(h,[a]);t.push(a)},r=a=>{const h=new T.BitSet;for(let l=0;l<a.length;l++)h.set(a[l].id);return h},n=[];for(const a of c){const h=a.transitions;for(let l=0;l<h.length;l++){const u=h[l];n.push({whenHas:r(u.whenHas),add:u.add,remove:u.remove})}}for(const a of c){const h=a.spawns;for(let l=0;l<h.length;l++)s(r(h[l]))}for(;t.length>0;){const a=t.pop();for(let h=0;h<n.length;h++){const l=n[h];if(!a.contains(l.whenHas))continue;const u=a.copy();if(l.add!==void 0)for(let d=0;d<l.add.length;d++)u.set(l.add[d].id);if(l.remove!==void 0)for(let d=0;d<l.remove.length;d++)u.clear(l.remove[d].id);s(u)}}const o=[];for(const a of e.values())for(let h=0;h<a.length;h++)o.push(a[h]);return o}function Gt(c,e){return typeof e=="object"&&e!==null&&console.warn(`runIfResourceEq('${c.description??"?"}'): 'expected' is an object — comparison is by reference identity (===), so the gate only fires when the resource is set to this exact instance. Prefer a primitive phase value.`),{name:`runIfResourceEq(${c.description??"?"})`,resourceReads:[c],evaluate:t=>t.getResource(c)===e}}function Pt(c,e=0){if(!Number.isInteger(c)||c<1)throw new i.ECSError(i.ECS_ERROR.INVALID_RUN_CONDITION,`runEveryNTicks: n must be a positive integer, got ${c}`);if(!Number.isInteger(e))throw new i.ECSError(i.ECS_ERROR.INVALID_RUN_CONDITION,`runEveryNTicks: offset must be an integer, got ${e}`);const t=(e%c+c)%c;return{name:`runEveryNTicks(${c}${t!==0?`, +${t}`:""})`,evaluate:s=>(s.ecsTick-t)%c===0}}function Ht(c){return{name:"runIfAnyMatch",reads:c._defs,evaluate:()=>c.entityCount>0}}function de(c){const e=[],t=[];for(const s of c)s.reads&&e.push(...s.reads),s.resourceReads&&t.push(...s.resourceReads);return{...e.length>0?{reads:e}:{},...t.length>0?{resourceReads:t}:{}}}function Ut(c){return{name:`not(${c.name})`,...de([c]),evaluate:e=>!c.evaluate(e)}}function Vt(...c){return{name:`allOf(${c.map(e=>e.name).join(", ")})`,...de(c),evaluate:e=>c.every(t=>t.evaluate(e))}}function qt(...c){return{name:`anyOf(${c.map(e=>e.name).join(", ")})`,...de(c),evaluate:e=>c.some(t=>t.evaluate(e))}}function Wt(c){return c.kind==="spawn"&&c.onSpawned!==void 0?{kind:"spawn",components:c.components}:c}class Yt{seed;_startup=[];_ticks=[];sink=this._startup;constructor(e=0){this.seed=e}openTick(e,t){const s=this._ticks[this._ticks.length-1];if(s!==void 0&&s.tick===e){this.sink=s.commands;return}const r=[];this._ticks.push({tick:e,dt:t,commands:r}),this.sink=r}record=e=>{this.sink.push(Wt(e))};log(){return{seed:this.seed,startup:this._startup,ticks:this._ticks}}snapshotLog(){return{seed:this.seed,startup:this._startup.map(e=>({...e})),ticks:this._ticks.map(e=>({...e,commands:e.commands.map(t=>({...t}))}))}}}const Y="__component_def";function zt(c){return JSON.stringify(c,(e,t)=>{if(typeof t=="function"&&"id"in t)return{[Y]:t.id};if(t!==null&&typeof t=="object"&&Y in t)throw new i.ECSError(i.ECS_ERROR.COMMAND_LOG_TAG_COLLISION,`Cannot serialize the command log: a value object owns a field named "${Y}", the reserved tag the serializer uses for component defs. Rename that component field so the log can round-trip losslessly.`);return t})}function jt(c){return JSON.parse(c,(e,t)=>t!==null&&typeof t=="object"&&Y in t?De(Te(t[Y])):t)}function Qt(c,e,t,s){for(const o of t.startup)e.push(o);c.startup();const r=s?.hash??c.snapshots.deterministic,n=[];for(const o of t.ticks){for(const a of o.commands)e.push(a);c.update(o.dt),r&&n.push(c.snapshots.stateHash())}return{startupCommands:t.startup.length,ticks:t.ticks.length,stateHashes:n}}function ne(c){return c.name??`system#${c.id}`}class Kt{_frames=[];_current=null;tickBegin(e,t){const s={tick:e,dt:t,events:[]};this._current=s,this._frames.push(s)}tickEnd(e){this._current=null}systemStart(e,t){this._current?.events.push({kind:"system_start",system:ne(e),phase:t})}systemEnd(e){this._current?.events.push({kind:"system_end",system:ne(e)})}commandQueued(e,t,s){this._current?.events.push({kind:"command_queued",op:e,entity:t,component:s})}flushBegin(e){this._current?.events.push({kind:"flush_begin",phase:e})}flushEnd(e){this._current?.events.push({kind:"flush_end",phase:e})}phaseBoundary(e){}observerFired(e,t,s,r){this._current?.events.push({kind:"observer_fired",op:e,component:t,entity:s,observer:ne(r)})}eventEmitted(e){this._current?.events.push({kind:"event_emitted",key:e})}eventRead(e,t){this._current?.events.push({kind:"event_read",key:e,count:t})}frames(){return this._frames}reset(){this._frames.length=0,this._current=null}}function L(c,e){if(!(e>=0)||!Number.isFinite(e))throw new i.ECSError(i.ECS_ERROR.INVALID_FRAME_STEP,`${c} must be a finite number >= 0, got ${e}`);return e}function Xt(c){if(!Number.isInteger(c)||c<0)throw new i.ECSError(i.ECS_ERROR.INVALID_FRAME_STEP,`frame count must be an integer >= 0, got ${c}`);return c}class Zt{ecs;requestFrame;cancelFrame;frameHandle=null;lastTimestampMs=null;running=!1;_fixedDt;_maxDt;constructor(e,t={}){this.ecs=e,this._fixedDt=L("fixedDt",t.fixedDt??1/60),this._maxDt=L("maxDt",t.maxDt??.25);const s=globalThis;this.requestFrame=t.requestFrame??s.requestAnimationFrame?.bind(globalThis),this.cancelFrame=t.cancelFrame??s.cancelAnimationFrame?.bind(globalThis),t.autoStart===!0&&this.play()}get fixedDt(){return this._fixedDt}set fixedDt(e){this._fixedDt=L("fixedDt",e)}get maxDt(){return this._maxDt}set maxDt(e){this._maxDt=L("maxDt",e)}get isRunning(){return this.running}step(e=this._fixedDt){this.ecs.update(L("dt",e))}stepFrames(e,t=this._fixedDt){Xt(e);const s=L("dt",t);for(let r=0;r<e;r++)this.ecs.update(s)}play(){if(!this.running){if(this.requestFrame===void 0)throw new i.ECSError(i.ECS_ERROR.INVALID_FRAME_STEP,"FrameStepper.play() requires requestAnimationFrame or a requestFrame option");this.running=!0,this.lastTimestampMs=null,this.scheduleNextFrame()}}pause(){this.running=!1,this.lastTimestampMs=null,this.frameHandle!==null&&this.cancelFrame!==void 0&&this.cancelFrame(this.frameHandle),this.frameHandle=null}toggle(){this.running?this.pause():this.play()}dispose(){this.pause()}scheduleNextFrame(){this.frameHandle=this.requestFrame?.(this.onFrame)??null}onFrame=e=>{if(!this.running)return;const t=this.lastTimestampMs===null?this._fixedDt:(e-this.lastTimestampMs)/1e3;this.lastTimestampMs=e,this.ecs.update(Math.min(L("dt",t),this._maxDt)),this.running&&this.scheduleNextFrame()}}function Jt(c,e){return c.relations.register({exclusive:!0,onDeleteTarget:e?.onDeleteTarget??"clear"})}function es(c,e){return c.relations.register({exclusive:!0,onDeleteTarget:e?.onDeleteTarget??"delete"})}function ts(c){return i.unsafeCast(Symbol(c))}const ss="0.5.3";exports.ANY_RELATION=i.ANY_RELATION;exports.ECSError=i.ECSError;exports.ECS_ERROR=i.ECS_ERROR;exports.HostCommandQueue=i.HostCommandQueue;exports.SCHEDULE=i.SCHEDULE;exports.SparseRestoreError=i.SparseRestoreError;exports.applyHostCommand=i.applyHostCommand;exports.getEntityIndex=i.getEntityIndex;exports.installHostCommandSeam=i.installHostCommandSeam;exports.isEcsError=i.isEcsError;exports.spawnEntry=i.spawnEntry;exports.systemSet=i.systemSet;exports.uninstallHostCommandSeam=i.uninstallHostCommandSeam;exports.SabUnavailableError=W.SabUnavailableError;exports.ChangedQuery=x;exports.ChunkColumns=$e;exports.Commands=Ge;exports.ECS=$t;exports.ECSRestoreError=O;exports.ECS_SNAPSHOT_VERSION=J;exports.FrameStepper=Zt;exports.FrameTraceRecorder=Kt;exports.HIERARCHY_UNBOUNDED=Z;exports.HostCommandRecorder=Yt;exports.Query=D;exports.QueryBuilder=Be;exports.StoreRestoreError=B;exports.SystemContext=Pe;exports.VERSION=ss;exports.allOf=Vt;exports.anyOf=qt;exports.bundle=Ue;exports.deserializeCommandLog=jt;exports.eventKey=ze;exports.not=Ut;exports.registerChildOf=es;exports.registerIsA=Jt;exports.replayCommandLog=Qt;exports.resourceKey=ts;exports.runEveryNTicks=Pt;exports.runIfAnyMatch=Ht;exports.runIfResourceEq=Gt;exports.serializeCommandLog=zt;exports.signalKey=je;
|
|
1
|
+
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const i=require("./host_commands-ClVPvhSa.cjs"),I=require("./topological_sort-vp1imU6D.cjs"),ne=require("./shared-Dk-pACZT.cjs"),P=!0,rt=i.TYPE_TAG.f64,Se=i.TYPE_TAG.f32,Ce=i.TYPE_TAG.i32,nt=i.TYPE_TAG.u32,ve=i.TYPE_TAG.i16,it=i.TYPE_TAG.u16,ot=i.TYPE_TAG.i8,vt=i.TYPE_TAG.u8;function Tt(a,e){switch(a){case ot:return new Uint8Array(e.buffer,e.byteOffset,e.length);case ve:return new Uint16Array(e.buffer,e.byteOffset,e.length);case Ce:case Se:return new Uint32Array(e.buffer,e.byteOffset,e.length);default:return e}}const at=new Float32Array(1),At=new Uint32Array(at.buffer);function Ot(a,e){switch(a){case rt:return e;case Se:return at[0]=e,At[0];case Ce:case nt:return e>>>0;case ve:case it:return e&65535;default:return e&255}}function bt(a,e){switch(a.constructor){case Float64Array:return a[e];case Float32Array:return a[e];case Int32Array:return a[e];case Uint32Array:return a[e];case Int16Array:return a[e];case Uint16Array:return a[e];case Int8Array:return a[e];default:return a[e]}}function It(a,e,t){switch(a.constructor){case Float64Array:a[e]=t;return;case Float32Array:a[e]=t;return;case Int32Array:a[e]=t;return;case Uint32Array:a[e]=t;return;case Int16Array:a[e]=t;return;case Uint16Array:a[e]=t;return;case Int8Array:a[e]=t;return;default:a[e]=t;return}}function K(a,e,t,s){switch(a){case rt:e[t]=s;return;case Se:e[t]=s;return;case Ce:e[t]=s;return;case nt:e[t]=s;return;case ve:e[t]=s;return;case it:e[t]=s;return;case ot:e[t]=s;return;case vt:e[t]=s;return}}const Fe=i.INDEX_MASK,kt=["__cols","__row"],le=new Map,ue=new Map,U=Object.create(null);function Dt(a,e){let t=le.get(a);if(t===void 0)return t=le.size,le.set(a,t),ue.set(a,e),Object.defineProperty(U,a,Nt[e](t,a)),t;const s=ue.get(a);return s!==null&&s!==e&&(ue.set(a,null),Object.defineProperty(U,a,xt(t,a))),t}function ct(a,e){const t=a.length,s=new Int32Array(t);for(let r=0;r<t;r++)s[r]=Dt(a[r],e[r]);return s}const Te=new Float64Array(0);function O(a,e,t){if(a===ae)throw new i.ECSError(i.ECS_ERROR.FIELD_NOT_REGISTERED,`Field "${t}" was read from a cursor before its first at(entity). Point the cursor at an entity first`,{field:t});const s=a[e];if(s===void 0||s===Te)throw new i.ECSError(i.ECS_ERROR.FIELD_NOT_REGISTERED,`Field "${t}" is not a field of the component this accessor reads. Check the schema passed to registerComponent`,{field:t});return s}const Nt={f64:(a,e)=>({get(){const t=this.__cols;return O(t,a,e)[this.__row]},set(t){const s=this.__cols;O(s,a,e)[this.__row]=t},enumerable:!0,configurable:!0}),f32:(a,e)=>({get(){const t=this.__cols;return O(t,a,e)[this.__row]},set(t){const s=this.__cols;O(s,a,e)[this.__row]=t},enumerable:!0,configurable:!0}),i32:(a,e)=>({get(){const t=this.__cols;return O(t,a,e)[this.__row]},set(t){const s=this.__cols;O(s,a,e)[this.__row]=t},enumerable:!0,configurable:!0}),u32:(a,e)=>({get(){const t=this.__cols;return O(t,a,e)[this.__row]},set(t){const s=this.__cols;O(s,a,e)[this.__row]=t},enumerable:!0,configurable:!0}),i16:(a,e)=>({get(){const t=this.__cols;return O(t,a,e)[this.__row]},set(t){const s=this.__cols;O(s,a,e)[this.__row]=t},enumerable:!0,configurable:!0}),u16:(a,e)=>({get(){const t=this.__cols;return O(t,a,e)[this.__row]},set(t){const s=this.__cols;O(s,a,e)[this.__row]=t},enumerable:!0,configurable:!0}),i8:(a,e)=>({get(){const t=this.__cols;return O(t,a,e)[this.__row]},set(t){const s=this.__cols;O(s,a,e)[this.__row]=t},enumerable:!0,configurable:!0}),u8:(a,e)=>({get(){const t=this.__cols;return O(t,a,e)[this.__row]},set(t){const s=this.__cols;O(s,a,e)[this.__row]=t},enumerable:!0,configurable:!0})},xt=(a,e)=>({get(){const t=this.__cols;return bt(O(t,a,e),this.__row)},set(t){const s=this.__cols;It(O(s,a,e),this.__row,t)},enumerable:!0,configurable:!0});function ye(a,e){const t=Object.create(U);return t.__cols=a,t.__row=e,t}const M="at",ae=[];function Mt(){const a=[],e=Object.create(U);e.__cols=ae,e.__row=0,e.__cols=a,e.__row=1;const t=Object.create(U);t.__cols=ae,t.__row=0,Object.defineProperty(t,M,{value:function(){},writable:!1,enumerable:!1,configurable:!1}),t.__cols=a,t.__row=1}Mt();function ce(a,e,t=ae){for(let r=0;r<a.length;r++)if(a[r]===M)throw new i.ECSError(i.ECS_ERROR.FIELD_NOT_REGISTERED,`A component with a field named "${M}" cannot be read through a cursor, the name collides with the cursor's own \`${M}(entity)\` method. Rename the field, or read this component with getField or ref instead.`,{field:a[r]});const s=Object.create(U);return s.__cols=t,s.__row=0,Object.defineProperty(s,M,{value:function(n){return e(this,n),this},writable:!1,enumerable:!1,configurable:!1}),s}function he(a,e,t,s=null,r=null){for(let c=0;c<a.length;c++)if(a[c]===M)throw new i.ECSError(i.ECS_ERROR.FIELD_NOT_REGISTERED,`A component with a field named "${M}" cannot be read through a cursor, the name collides with the cursor's own \`${M}(entity)\` method. Rename the field, or read this component with getSparseField instead.`,{field:a[c]});const n=Object.create(U);return n.__cols=e,n.__row=0,Object.defineProperty(n,M,{value:s===null?function(h){return t(h),this.__row=h&Fe,this}:function(h){t(h);const l=h&Fe;this.__row=l;const u=s.ticks;if(u!==null){const d=r.changeTick;u[l]=d,s.changedTick=d}return this},writable:!1,enumerable:!1,configurable:!1}),n}const ht=a=>i.validateAndCast(a,i.isNonNegativeInteger,"ComponentID must be a non-negative integer"),Ae=Object.freeze({});function lt(a){const e=(t=>({def:e,values:t??Ae}));return Object.defineProperty(e,"id",{value:a,enumerable:!1}),e}function Ft(a,...e){return{def:a,values:e[0]??Ae}}function W(a){return typeof a=="function"?a:a.def}function V(a){return typeof a=="function"?Ae:a.values}function ut(a,e){for(let t=0;t<a.length;t++)if(kt.includes(a[t]))throw new i.ECSError(i.ECS_ERROR.FIELD_NOT_REGISTERED,`Cannot register ${e} field "${a[t]}": the name is reserved for the state of a ref or cursor. Rename the field.`,{field:a[t],kind:e})}function dt(a,e,t,s){if(a)for(let r=0;r<t.length;r++){const n=t[r];if(n==="f32"||n==="f64")throw new i.ECSError(i.ECS_ERROR.NON_DETERMINISTIC_COLUMN_TYPE,`Cannot register ${s} field "${e[r]}" as "${n}" on a { deterministic: true } world: floating-point columns round differently across hosts, breaking cross-host stateHash agreement. Use an integer type (e.g. "i32"), or represent fractional quantities as fixed-point (Q16.16). The array shorthand defaults to "f64", so pass an explicit integer type there.`,{field:e[r],type:n,kind:s})}}function Pt(a,e,t,s){if(a.length>=i.STORE_DESCRIPTOR_COMPONENT_LIMIT)throw new i.ECSError(i.ECS_ERROR.COMPONENT_LIMIT_EXCEEDED,`registerComponent exceeds the dense component limit of ${i.STORE_DESCRIPTOR_COMPONENT_LIMIT}, because the archetype descriptor mask is that many bits wide. Register this component with registerSparseComponent, which keeps its own id space and costs no mask bit.`,{componentCount:a.length,limit:i.STORE_DESCRIPTOR_COMPONENT_LIMIT});const r=Object.keys(t),n=new Array(r.length),o=Object.create(null);for(let l=0;l<r.length;l++)o[r[l]]=l,n[l]=t[r[l]];ut(r,"component"),dt(e,r,n,"component");const c=ht(a.length);a.push({name:s,fieldNames:r,fieldIndex:o,fieldTypes:n,fieldGid:ct(r,n),obsAdd:!1,obsRem:!1,obsDisable:!1,obsEnable:!1,rowTicks:!1,trackDirty:!1,drainTick:0,scanTick:0,listCap:0,lastDrainRun:0});const h=lt(c);return s!==void 0&&i.setComponentDebugName(h,s),h}function Bt(a,e){const t=a[e]?.name;return t!==void 0?`'${t}' (component ${e})`:`component ${e}`}function Lt(a,e,t){const s=e.id,r=a[s];if(r===void 0)throw new i.ECSError(i.ECS_ERROR.COMPONENT_NOT_REGISTERED,`fieldId: component ${s} is not registered`);const n=r.fieldIndex[t];if(n===void 0)throw new i.ECSError(i.ECS_ERROR.FIELD_NOT_REGISTERED,`fieldId: component ${s} has no field "${t}"`);return n}class Gt extends Error{constructor(e){super(e),this.name="StoreRestoreError"}}class $t extends Error{constructor(e){super(e),this.name="SparseRestoreError"}}const Ut=2166136261,ge=16777619;function k(a,e){return a=(a^e>>>0)>>>0,Math.imul(a,ge)>>>0}const Pe={f64:Float64Array,f32:Float32Array,i32:Int32Array,u32:Uint32Array,i16:Int16Array,u16:Uint16Array,i8:Int8Array,u8:Uint8Array},Z=64,Be=i.MAX_INDEX+1,Ht=Object.freeze([]);class qt{fieldNames;fieldTypes;fieldIndex;accCols;_cols;_kinds;_allF64;_gids;_cap;_pos;_dense;_size=0;ticks=null;changedTick=0;drainTick=0;lastDrainRun=0;constructor(e,t){this.fieldNames=e,this.fieldTypes=t;const s=Object.create(null);for(let h=0;h<e.length;h++)s[e[h]]=h;this.fieldIndex=s;const r=e.length,n=new Uint8Array(r);let o=!0;for(let h=0;h<r;h++)n[h]=i.TYPED_ARRAY_TAG_TO_TYPE_TAG[t[h]],n[h]!==i.TYPE_TAG.f64&&(o=!1);this._kinds=n,this._allF64=o,this._gids=ct(e,t);let c=-1;for(let h=0;h<r;h++)this._gids[h]>c&&(c=this._gids[h]);this.accCols=new Array(c+1).fill(Te),this._cap=Z,this._cols=new Array(r);for(let h=0;h<r;h++){const l=new Pe[t[h]](Z);this._cols[h]=l,this.accCols[this._gids[h]]=l}this._pos=new Int32Array(Z).fill(-1),this._dense=new Uint32Array(Z)}get size(){return this._size}get indices(){return this._dense.subarray(0,this._size)}indexAt(e){return this._dense[e]}canonicalIndices(){const e=new Array(this._size);for(let t=0;t<this._size;t++)e[t]=this._dense[t];return e.sort((t,s)=>t-s)}getRow(e){if(!(this._pos[e]>=0))return;const t=this._cols.length;if(t===0)return Ht;const s=new Array(t);for(let r=0;r<t;r++)s[r]=this._cols[r][e];return s}clear(){this._pos.fill(-1),this._size=0}setRawRow(e,t){this._join(e);const s=this._cols,r=this._kinds;for(let n=0;n<s.length;n++)K(r[n],s[n],e,t[n])}has(e){return this._pos[e]>=0}setRow(e,t){this._join(e);const s=this.fieldNames,r=this._cols;if(this._allF64){for(let o=0;o<s.length;o++)r[o][e]=t[s[o]]??0;return}const n=this._kinds;for(let o=0;o<s.length;o++)K(n[o],r[o],e,t[s[o]]??0)}remove(e){const t=this._pos[e];if(!(t>=0))return!1;const s=--this._size,r=this._dense[s];return this._dense[t]=r,this._pos[r]=t,this._pos[e]=-1,!0}getField(e,t){if(this._pos[e]>=0)return this._cols[t][e]}setField(e,t,s,r){if(!(this._pos[e]>=0))return!1;K(this._kinds[t],this._cols[t],e,s);const n=this.ticks;return n!==null&&(n[e]=r,this.changedTick=r),!0}trackTicks(){this.ticks===null&&(this.ticks=new Uint32Array(this._cap))}resetTicks(){this.ticks!==null&&this.ticks.fill(0),this.changedTick=0}_join(e){if(e>=this._cap&&this._growToFit(e),!(this._pos[e]>=0)){if(this.ticks!==null&&(this.ticks[e]=0),this._size===this._dense.length){const t=new Uint32Array(this._dense.length*2);t.set(this._dense),this._dense=t}this._pos[e]=this._size,this._dense[this._size++]=e}}_growToFit(e){let t=this._cap;for(;t<=e;)t*=2;t>Be&&(t=Be);const s=this._cols;for(let n=0;n<s.length;n++){const o=new Pe[this.fieldTypes[n]](t);o.set(s[n]),s[n]=o,this.accCols[this._gids[n]]=o}const r=new Int32Array(t).fill(-1);if(r.set(this._pos),this._pos=r,this.ticks!==null){const n=new Uint32Array(t);n.set(this.ticks),this.ticks=n}this._cap=t}}class Yt{_values=new Map;register(e,t){if(this._values.has(e))throw new i.ECSError(i.ECS_ERROR.RESOURCE_ALREADY_REGISTERED,`resource '${e.description??"<unnamed>"}' is already registered, remove() it first if you meant to replace it`,{resource:e.description});this._values.set(e,t)}get(e){if(!this._values.has(e))throw new i.ECSError(i.ECS_ERROR.RESOURCE_NOT_REGISTERED,`resource read: '${e.description??"<unnamed>"}' is not registered, call ecs.resources.register(key, value) at world setup`,{resource:e.description});return this._values.get(e)}set(e,t){if(!this._values.has(e))throw new i.ECSError(i.ECS_ERROR.RESOURCE_NOT_REGISTERED,`resource write: '${e.description??"<unnamed>"}' is not registered, call ecs.resources.register(key, value) at world setup`,{resource:e.description});this._values.set(e,t)}remove(e){if(!this._values.has(e))throw new i.ECSError(i.ECS_ERROR.RESOURCE_NOT_REGISTERED,`resource remove: '${e.description??"<unnamed>"}' is not registered, call ecs.resources.register(key, value) at world setup`,{resource:e.description});this._values.delete(e)}has(e){return this._values.has(e)}}class Wt{_registered=[];_host;constructor(e){this._host=e}matching(e,t,s){const r=e.words;let n=!1;for(let u=0;u<r.length;u++)if(r[u]!==0){n=!0;break}if(!n){const u=this._host.archetypes(),d=[];for(let _=0;_<u.length;_++){const f=u[_];(!t||!f.mask.overlaps(t))&&(!s||f.mask.overlaps(s))&&d.push(f)}return d}const o=this._host.componentIndex();let c,h=!1;for(let u=0;u<r.length;u++){let d=r[u];if(d===0)continue;const _=u<<I.BITS_PER_WORD_SHIFT;for(;d!==0;){const f=d&-d>>>0,y=_+(I.BITS_PER_WORD_MASK-Math.clz32(f));d^=f;const E=o[y];if(E===void 0||E.length===0){h=!0;break}(!c||E.length<c.length)&&(c=E)}if(h)break}if(h||!c)return[];const l=[];for(let u=0;u<c.length;u++){const d=this._host.archetypeAt(c[u]);d.matches(e)&&(!t||!d.mask.overlaps(t))&&(!s||d.mask.overlaps(s))&&l.push(d)}return l}register(e,t,s){const r=this.matching(e,t,s);return this._registered.push({includeMask:e.copy(),excludeMask:t?t.copy():null,anyOfMask:s?s.copy():null,result:r,query:null}),r}updateRef(e,t){const s=this._registered;for(let r=0;r<s.length;r++)if(s[r].result===e){s[r].query=t;return}}fanIn(e){const t=this._registered;for(let s=0;s<t.length;s++){const r=t[s];e.matches(r.includeMask)&&(!r.excludeMask||!e.mask.overlaps(r.excludeMask))&&(!r.anyOfMask||e.mask.overlaps(r.anyOfMask))&&r.result.push(e)}}}class ee extends Error{capacity;requested;constructor(e,t){super(`BufferBackedColumn overflow: requested length ${t} exceeds capacity ${e}`),this.name="StoreColumnOverflowError",this.capacity=e,this.requested=t}}class Le{_buf;_capacity;_len=0;constructor(e){this._buf=e,this._capacity=e.length}refreshView(e){if(e.length<this._len)throw new ee(e.length,this._len);this._buf=e,this._capacity=e.length}get length(){return this._len}get capacity(){return this._capacity}push(e){if(this._len>=this._capacity)throw new ee(this._capacity,this._len+1);this._buf[this._len++]=e}pop(){return this._buf[--this._len]}getAt(e){return this._buf[e]}setAt(e,t){this._buf[e]=t}swapRemove(e){const t=this._buf[e];return this._buf[e]=this._buf[--this._len],t}clear(){this._len=0}setLength(e){if(e>this._capacity)throw new ee(this._capacity,e);this._len=e}get buf(){return this._buf}view(){return this._buf.subarray(0,this._len)}[Symbol.iterator](){let e=0;const t=this._buf,s=this._len;return{next(){return e<s?{value:t[e++],done:!1}:{value:0,done:!0}}}}reserve(e){if(e>this._capacity)throw new ee(this._capacity,e)}bulkAppend(e,t,s){this.reserve(this._len+s),this._buf.set(e.subarray(t,t+s),this._len),this._len+=s}bulkAppendZeroes(e){this.reserve(this._len+e),this._buf.fill(0,this._len,this._len+e),this._len+=e}bulkAppendValue(e,t){this.reserve(this._len+t),this._buf.fill(e,this._len,this._len+t),this._len+=t}}const G=i.NO_SWAP,Ge=i.UNASSIGNED,Vt=2147483647,jt=new Uint8Array(0),$e=i.TYPE_TAG.f64;function zt(a){const e=new Int32Array(a);for(let t=0;t<a;t++)e[t]=t;return e}const Ue=a=>i.validateAndCast(a,i.isNonNegativeInteger,"ArchetypeID must be a non-negative integer");class Oe{id;mask;hasColumns;materializesRows;_entityIds;length=0;enabledCount=0;flushSeenEpoch=-1;flushPreLen=0;flushPreEnabled=0;iterDepth=0;_edges=[];_batchTransitionMaps=new Map;_compositeAddEdges=null;flatColumns=[];bufs=[];_widthBufs=[];rowTicks=[];_tickBufs=[];_tickCids=[];_colKind=jt;_allF64=!0;_eids;_rowCap=0;_colCap=0;_storeArchetypeId=null;colOffset=[];fieldCount=[];_fieldIndex=[];_fieldNames=[];accessorColumns=[];_fieldGid=[];columnIds=[];changedTick=[];_mutGroupCache=[];_readGroupCache=[];growHandler=null;constructor(e,t,s,r=i.DEFAULT_COLUMN_CAPACITY,n){if(this.id=e,this.mask=t,this._entityIds=new I.GrowableUint32Array(r),s){let o=0;const c=[];for(let h=0;h<s.length;h++){const l=s[h],u=l.componentId,d=new Array(l.fieldNames.length);if(this.colOffset[u]=o,this.fieldCount[u]=l.fieldNames.length,this._fieldIndex[u]=l.fieldIndex,this._fieldNames[u]=l.fieldNames,this._fieldGid[u]=l.fieldGid??zt(l.fieldNames.length),l.fieldNames.length>0&&!n)throw new i.ECSError(i.ECS_ERROR.COMPONENT_NOT_REGISTERED,`Archetype ${e}: layouts with fields require a columnFactory, use Archetype.fromColumnStore for SAB-backed columns, or pass a heap factory explicitly in tests`);for(let _=0;_<l.fieldNames.length;_++){const f=l.fieldTypes[_],y=n(l.componentId,_,f);d[_]=y,c.push(i.TYPED_ARRAY_TAG_TO_TYPE_TAG[f]),this.flatColumns[o++]=y}this.columnIds.push(u),this.changedTick[u]=0}this._colKind=Uint8Array.from(c);for(let h=0;h<c.length;h++)if(c[h]!==i.TYPE_TAG.f64){this._allF64=!1;break}}this.hasColumns=this.columnIds.length>0,this.materializesRows=!t.isEmpty(),this._syncRowPlane()}_copyRowFrom(e,t,s,r){const n=this._widthBufs,o=e._widthBufs,c=t.length;for(let h=0;h<c;h++){const l=t[h];n[h][s]=l>=0?o[l][r]:0}c!==n.length&&this._copyTicksFrom(e,s,r)}_copyTicksFrom(e,t,s){const r=this._tickCids,n=this._tickBufs;for(let o=0;o<r.length;o++){const c=e.rowTicks[r[o]];n[o][t]=c!==void 0?c[s]:0}}installTicks(e){if(this.rowTicks[e]!==void 0)return;const t=this.fieldCount[e];if(t===void 0||t===0)return;const s=new Uint32Array(Math.max(1,this._rowCap));this.rowTicks[e]=s,this._tickCids.push(e),this._tickBufs.push(s),this._syncRowPlane()}resetTicks(){const e=this._tickBufs;for(let t=0;t<e.length;t++)e[t].fill(0)}_syncTicks(e,t){const s=this._tickCids,r=this._tickBufs,n=this._rowCap;for(let o=0;o<r.length;o++){let c=r[o];if(c.length<n){const h=new Uint32Array(n);h.set(c),c=r[o]=h,this.rowTicks[s[o]]=h}e[t+o]=c}}_moveRow(e,t){const s=this._widthBufs;for(let r=0;r<s.length;r++)s[r][e]=s[r][t]}_swapRow(e,t){const s=this._widthBufs;for(let r=0;r<s.length;r++){const n=s[r],o=n[e];n[e]=n[t],n[t]=o}}_zeroRow(e){const t=this._widthBufs;for(let s=0;s<t.length;s++)t[s][e]=0}_writeRowBits(e,t){const s=this._widthBufs,r=t.length;for(let n=0;n<r;n++)s[n][e]=t[n];for(let n=r;n<s.length;n++)s[n][e]=0}_syncRowPlane(){const e=this.flatColumns;let t=this.bufs;t.length!==e.length&&(t=this.bufs=new Array(e.length));let s=this._widthBufs;const r=e.length+this._tickBufs.length;s.length!==r&&(s=this._widthBufs=new Array(r));const n=this._colKind;this._eids=this._entityIds.buf;let o=Vt;for(let h=0;h<e.length;h++){const l=e[h].buf;t[h]=l,s[h]=Tt(n[h],l),l.length<o&&(o=l.length)}this._colCap=o;const c=this._eids.length;this._rowCap=c<o?c:o,this._tickBufs.length!==0&&this._syncTicks(s,e.length),this._refreshColumnCaches()}_refreshColumnCaches(){const e=this.columnIds,t=this.bufs;for(let s=0;s<e.length;s++){const r=e[s];let n=this._mutGroupCache[r];n===void 0&&(n=this._mutGroupCache[r]={});let o=this._readGroupCache[r];o===void 0&&(o=this._readGroupCache[r]={});const c=this.colOffset[r],h=this._fieldGid[r];let l=this.accessorColumns[r];if(l===void 0){let d=-1;for(let _=0;_<h.length;_++)h[_]>d&&(d=h[_]);l=this.accessorColumns[r]=new Array(d+1).fill(Te)}const u=this._fieldNames[r];for(let d=0;d<u.length;d++){const _=t[c+d];n[u[d]]=_,o[u[d]]=_,l[h[d]]=_}}}_assertRowPlaneFresh(e){const t=this.flatColumns;if(this._eids!==this._entityIds.buf||t.length>0&&this.bufs[0]!==t[0].buf)throw new i.ECSError(i.ECS_ERROR.ARCHETYPE_ROW_INVARIANT,`Archetype ${this.id}: cached row plane is stale at ${e}, a buffer changed identity without a _syncRowPlane`)}reserveRows(e){this.length+e>this._rowCap&&this._growRows(e)}_growRows(e){const t=this.length+e;if(this._entityIds.setLength(this.length),this._entityIds.reserve(t),t<=this._colCap){this._syncRowPlane();return}try{if(this.growHandler!==null)this.growHandler(this,e);else{this._publishRowCounts();const s=this.flatColumns;for(let r=0;r<s.length;r++)s[r].reserve(t)}}finally{this._syncRowPlane()}if(t>this._rowCap)throw new i.ECSError(i.ECS_ERROR.ARCHETYPE_ROW_INVARIANT,`Archetype ${this.id}: reserve of ${e} row(s) left capacity ${this._rowCap} below the required ${t}`)}_publishRowCounts(){const e=this.flatColumns,t=this.length;for(let s=0;s<e.length;s++)e[s].setLength(t);this._entityIds.setLength(t)}static fromColumnStore(e,t,s,r,n){const o=r.archetypes.get(n);if(!o)throw new i.ECSError(i.ECS_ERROR.COMPONENT_NOT_REGISTERED,`ColumnStore has no archetype ${n}`);const c=(l,u)=>{const d=o.columns.get(i.columnKey(l,u));if(!d)throw new i.ECSError(i.ECS_ERROR.COMPONENT_NOT_REGISTERED,`ColumnStore archetype ${n} has no column for (${l}, ${u})`);return new Le(d.view)},h=new Oe(e,t,s,o.rowCapacity,c);return h._storeArchetypeId=n,h}get isBufferBacked(){return this._storeArchetypeId!==null}refreshViews(e){if(this._storeArchetypeId===null)throw new i.ECSError(i.ECS_ERROR.COMPONENT_NOT_REGISTERED,`Archetype ${this.id} is not SAB-backed`);const t=e.archetypes.get(this._storeArchetypeId);if(!t)throw new i.ECSError(i.ECS_ERROR.COMPONENT_NOT_REGISTERED,`new ColumnStore has no archetype ${this._storeArchetypeId}`);const s=t.columnsInOrder,r=this.flatColumns;this._publishRowCounts();for(let n=0;n<s.length;n++)if(!(r[n]instanceof Le))throw new i.ECSError(i.ECS_ERROR.COMPONENT_NOT_REGISTERED,`Archetype ${this.id} column at index ${n} is not SAB-backed (internal)`);for(let n=0;n<s.length;n++)r[n].refreshView(s[n].view);this._syncRowPlane()}get entityCount(){return me?this.length:this.enabledCount}get totalCount(){return this.length}get disabledCount(){return this.length-this.enabledCount}get entityIds(){return this._eids}swapRows(e,t){if(e===t)return;const s=this._eids,r=s[e];s[e]=s[t],s[t]=r,this._swapRow(e,t)}_placeTail(e,t){const s=this.enabledCount;if(s===e)return this.enabledCount=e+1,e;if(t===void 0)throw Qt();if(this.swapRows(s,e),t!==void 0){const r=this._eids;t[i.getEntityIndex(r[e])]=e}return this.enabledCount=s+1,s}_placeTailBulk(e,t){if(this.enabledCount!==e)throw He();return this.enabledCount+=t,e}disableRow(e,t){if(this.iterDepth>0)throw j("disable");const s=this.enabledCount-1;if(e!==s){this.swapRows(e,s);const r=this._eids;t[i.getEntityIndex(r[e])]=e,t[i.getEntityIndex(r[s])]=s}this.enabledCount=s}enableRow(e,t){if(this.iterDepth>0)throw j("enable");const s=this.enabledCount;if(e!==s){this.swapRows(e,s);const r=this._eids;t[i.getEntityIndex(r[e])]=e,t[i.getEntityIndex(r[s])]=s}this.enabledCount=s+1}removeRow(e,t){if(this.iterDepth>0)throw j("removeRow");if(this.enabledCount===this.length){const s=this._eids,r=this.length-1;e!==r&&(s[e]=s[r],this._moveRow(e,r),t[i.getEntityIndex(s[e])]=e),this.length=r,this.enabledCount=r;return}this._removeRowPartitioned(e,t)}_removeRowPartitioned(e,t){const s=this._eids,r=this.enabledCount,n=this.length-1;if(e>=r){e!==n&&(s[e]=s[n],this._moveRow(e,n),t[i.getEntityIndex(s[e])]=e),this.length--;return}const o=r-1;e!==o&&(this.swapRows(e,o),t[i.getEntityIndex(s[e])]=e),o!==n&&(s[o]=s[n],this._moveRow(o,n),t[i.getEntityIndex(s[o])]=o),this.length--,this.enabledCount=o}get rowEntityIds(){return this._eids.subarray(0,this.length)}hasComponent(e){return this.mask.has(e)}matches(e){return this.mask.contains(e)}getColumnRead(e,t){const s=e.id;{if(i.accessCheck.assertRead(e),this.colOffset[s]===void 0)throw new i.ECSError(i.ECS_ERROR.COMPONENT_NOT_REGISTERED,`Component ${e} not in archetype ${this.id}`);this._assertRowPlaneFresh("getColumnRead")}const r=this._fieldIndex[s][t];if(r===void 0)throw new i.ECSError(i.ECS_ERROR.COMPONENT_NOT_REGISTERED,`Field "${t}" does not exist on component`);return this.flatColumns[this.colOffset[s]+r].buf}getColumnsRead(e,...t){return t.map(r=>this.getColumnRead(e,r))}getOptionalColumnRead(e,t){const s=e.id;i.accessCheck.assertRead(e),i.accessCheck.assertOptionalFetch(e);const r=this.colOffset[s];if(r===void 0)return;const n=this._fieldIndex[s][t];if(n===void 0)throw new i.ECSError(i.ECS_ERROR.COMPONENT_NOT_REGISTERED,`Field "${t}" does not exist on component`);return this.flatColumns[r+n].buf}getColumnMut(e,t,s){const r=e.id;if(i.accessCheck.assertWrite(e),this.colOffset[r]===void 0)throw new i.ECSError(i.ECS_ERROR.COMPONENT_NOT_REGISTERED,`Component ${e} not in archetype ${this.id}`);this.changedTick[r]=s;const n=this._fieldIndex[r][t];if(n===void 0)throw new i.ECSError(i.ECS_ERROR.COMPONENT_NOT_REGISTERED,`Field "${t}" does not exist on component`);return this.flatColumns[this.colOffset[r]+n].buf}columnGroupMut(e,t){const s=e.id;if(i.accessCheck.assertWrite(e),this.colOffset[s]===void 0)throw new i.ECSError(i.ECS_ERROR.COMPONENT_NOT_REGISTERED,`Component ${e} not in archetype ${this.id}`);return this.changedTick[s]=t,this._mutGroupCache[s]}columnGroupRead(e){const t=e.id;if(i.accessCheck.assertRead(e),this.colOffset[t]===void 0)throw new i.ECSError(i.ECS_ERROR.COMPONENT_NOT_REGISTERED,`Component ${e} not in archetype ${this.id}`);return this._readGroupCache[t]}writeFields(e,t,s,r){const n=t,o=this.colOffset[n];if(o===void 0)return;this._assertRowPlaneFresh("writeFields"),this.changedTick[n]=r;const c=this._fieldNames[n],h=this.bufs;if(this._allF64){for(let u=0;u<c.length;u++)h[o+u][e]=s[c[u]]??0;return}const l=this._colKind;for(let u=0;u<c.length;u++){const d=s[c[u]]??0,_=l[o+u];_===$e?h[o+u][e]=d:K(_,h[o+u],e,d)}}bulkWriteFields(e,t,s,r,n){const o=s,c=this.colOffset[o];if(c===void 0)return;this.changedTick[o]=n;const h=this._fieldNames[o],l=this.flatColumns,u=e+t;for(let d=0;d<h.length;d++)l[c+d].buf.fill(r[h[d]]??0,e,u)}writeFieldsPositional(e,t,s,r){const n=t,o=this.colOffset[n];if(o===void 0)return;this.changedTick[n]=r;const c=this.flatColumns;for(let h=0;h<s.length;h++)c[o+h].buf[e]=s[h]}readField(e,t,s){const r=t,n=this.colOffset[r];if(n===void 0)throw new i.ECSError(i.ECS_ERROR.COMPONENT_NOT_REGISTERED,`readField: component ${r} has no column in this archetype, the entity doesn't hold it`,{component:r,field:s});const o=this._fieldIndex[r][s];if(o===void 0)throw new i.ECSError(i.ECS_ERROR.FIELD_NOT_REGISTERED,`readField: component ${r} has no field "${s}", check the schema passed to registerComponent`,{component:r,field:s});return this._assertRowPlaneFresh("readField"),this.bufs[n+o][e]}copySharedFrom(e,t,s,r){const n=e.colOffset,o=e.fieldCount,c=e.flatColumns,h=this.flatColumns,l=this.columnIds;for(let u=0;u<l.length;u++){const d=l[u],_=n[d];if(_===void 0)continue;this.changedTick[d]=r;const f=this.colOffset[d],y=o[d];for(let E=0;E<y;E++)h[f+E].buf[s]=c[_+E].buf[t]}this._tickBufs.length!==0&&this._copyTicksFrom(e,s,t)}addEntity(e,t){if(!this.materializesRows)throw B();this.reserveRows(1);const s=this.length;return this._eids[s]=e,this._zeroRow(s),this.length++,this._placeTail(s,t)}swapRemoveRow(e){const t=this.length-1;let s=G;const r=this._eids;return e!==t&&(r[e]=r[t],s=i.getEntityIndex(r[e]),this._moveRow(e,t)),this.length--,e<this.enabledCount&&this.enabledCount--,s}addEntityTag(e,t){if(!this.materializesRows)throw B();this.reserveRows(1);const s=this.length;return this._eids[s]=e,this.length++,this._placeTail(s,t)}addEntities(e,t=e.length){if(t===0)return this.length;if(!this.materializesRows)throw B();this.reserveRows(t);const s=this.length;this._eids.set(e.subarray(0,t),s);const r=this.bufs,n=s+t;for(let c=0;c<r.length;c++)r[c].fill(0,s,n);const o=this._tickBufs;for(let c=0;c<o.length;c++)o[c].fill(0,s,n);return this.length+=t,this._placeTailBulk(s,t)}addEntitiesTag(e,t=e.length){if(t===0)return this.length;if(!this.materializesRows)throw B();this.reserveRows(t);const s=this.length;return this._eids.set(e.subarray(0,t),s),this.length+=t,this._placeTailBulk(s,t)}addEntityWithBits(e,t,s,r){if(!this.materializesRows)throw B();this.reserveRows(1);const n=this.length;this._eids[n]=e,this._writeRowBits(n,t),this.length++;const o=this.columnIds;for(let c=0;c<o.length;c++)this.changedTick[o[c]]=s;return this._placeTail(n,r)}widthBits(e){const t=this._colKind,s=new Float64Array(e.length);for(let r=0;r<e.length;r++)s[r]=Ot(t[r],e[r]);return s}writeFlatElem(e,t,s){this._assertRowPlaneFresh("writeFlatElem");const r=this._colKind[e];r===$e?this.bufs[e][t]=s:K(r,this.bufs[e],t,s)}addEntitiesWithValues(e,t,s,r){if(t===0)return this.length;if(!this.materializesRows)throw B();this.reserveRows(t);const n=this.length;this._eids.set(e.subarray(0,t),n);const o=this.bufs,c=n+t;for(let u=0;u<o.length;u++)o[u].fill(s[u],n,c);const h=this._tickBufs;for(let u=0;u<h.length;u++)h[u].fill(0,n,c);this.length+=t;const l=this.columnIds;for(let u=0;u<l.length;u++)this.changedTick[l[u]]=r;return this._placeTailBulk(n,t)}swapRemoveRowTag(e){const t=this.length-1;let s=G;const r=this._eids;return e!==t&&(r[e]=r[t],s=i.getEntityIndex(r[e])),this.length--,e<this.enabledCount&&this.enabledCount--,s}moveEntityFrom(e,t,s,r,n,o){if(e.iterDepth>0)throw j("moveEntityFrom");const c=t>=e.enabledCount;if(!this.materializesRows){e.removeRow(t,o),b[0]=Ge,b[1]=G;return}this.reserveRows(1);const h=this.length;this._eids[h]=s,this._copyRowFrom(e,r,h,t);const l=this.columnIds;for(let d=0;d<l.length;d++)this.changedTick[l[d]]=n;this.length++;const u=c?h:this._placeTail(h,o);e.removeRow(t,o),b[0]=u,b[1]=G}moveEntityFromTag(e,t,s,r){if(e.iterDepth>0)throw j("moveEntityFrom");const n=t>=e.enabledCount;if(!this.materializesRows){e.removeRow(t,r),b[0]=Ge,b[1]=G;return}this.reserveRows(1);const o=this.length;this._eids[o]=s,this.length++;const c=n?o:this._placeTail(o,r);e.removeRow(t,r),b[0]=c,b[1]=G}bulkMoveAllFrom(e,t,s){const r=e.length;if(r===0)return this.length;if(!this.materializesRows)throw B();this.reserveRows(r);const n=this.length,o=this.bufs,c=e.bufs;this._eids.set(e._eids.subarray(0,r),n);for(let u=0;u<o.length;u++){const d=t[u];d>=0?o[u].set(c[d].subarray(0,r),n):o[u].fill(0,n,n+r)}const h=this._tickCids;for(let u=0;u<h.length;u++){const d=e.rowTicks[h[u]],_=this._tickBufs[u];d!==void 0?_.set(d.subarray(0,r),n):_.fill(0,n,n+r)}const l=this.columnIds;for(let u=0;u<l.length;u++)this.changedTick[l[u]]=s;if(this.length+=r,this.enabledCount!==n)throw He();return this.enabledCount=n+e.enabledCount,e.clearRows(),n}clearRows(){this.length=0,this.enabledCount=0,this._entityIds.clear();const e=this.flatColumns;for(let t=0;t<e.length;t++)e[t].clear()}restoreHostRows(e,t){const s=e.length;if(t<0||t>s)throw new i.ECSError(i.ECS_ERROR.ARCHETYPE_ROW_INVARIANT,`Archetype ${this.id}: restore enabledCount ${t} out of range [0, ${s}]`);this._entityIds.clear(),this._entityIds.reserve(s),this._entityIds.setLength(s),this._syncRowPlane();const r=this._eids;for(let o=0;o<s;o++)r[o]=e[o];const n=this.flatColumns;for(let o=0;o<n.length;o++)n[o].setLength(s);this.length=s,this.enabledCount=t}getEdge(e){return this._edges[e]}setEdge(e,t){this._edges[e]=t}transitionMapTo(e){const t=this._batchTransitionMaps.get(e.id);if(t!==void 0)return t;const s=we(this,e);return this._batchTransitionMaps.set(e.id,s),s}getCompositeAddEdge(e){return this._compositeAddEdges===null?void 0:this._compositeAddEdges.get(e)}cacheCompositeAddEdge(e,t,s){(this._compositeAddEdges??=new Map).set(e,{target:t,map:s})}}const b=[0,G];let me=!1;function x(a){const e=me;return me=a,e}function B(){return new i.ECSError(i.ECS_ERROR.EMPTY_ARCHETYPE_MATERIALIZE,"the empty archetype must not materialise rows: a component-less entity is unplaced (entityRows[index] === UNASSIGNED). A Store mutation path is missing its rowless-destination branch.")}function j(a){return new i.ECSError(i.ECS_ERROR.STRUCTURAL_DURING_ITERATION,`${a} hit an archetype a live query iteration is visiting. An immediate structural mutation mid-walk relocates rows under the iterator, so entities get skipped or visited twice. Collect ids during the walk and mutate after it. Inside a system, use the deferred ctx.commands`)}function Qt(){return new i.ECSError(i.ECS_ERROR.PARTITION_APPEND_NEEDS_ENTITY_ROW,"appending into a disabled-bearing archetype requires the entityRows map (to repoint the displaced disabled row). A Store append path is missing its entityRows argument.")}function He(){return new i.ECSError(i.ECS_ERROR.PARTITION_BULK_INTO_DISABLED,"bulk append and move into a disabled-bearing archetype is unsupported, the caller must fall back to per-entity placement to keep the enabled prefix contiguous.")}function we(a,e){const t=e.flatColumns,s=new Int16Array(t.length),r=e.columnIds,n=a.colOffset,o=e.colOffset,c=e.fieldCount;for(let h=0;h<r.length;h++){const l=r[h],u=o[l],d=c[l],_=n[l];if(_!==void 0)for(let f=0;f<d;f++)s[u+f]=_+f;else for(let f=0;f<d;f++)s[u+f]=-1}return s}class Kt{_generations;_lengthView;_highWater=0;_freeIndices=[];_aliveCount=0;_capacity;lastIndex=0;constructor(e,t,s){this._capacity=e,this._generations=t,this._lengthView=s}replantViews(e,t){this._generations=e,this._lengthView=t}get generations(){return this._generations}get highWater(){return this._highWater}get aliveCount(){return this._aliveCount}get freeCount(){return this._freeIndices.length}alloc(){let e,t;if(this._freeIndices.length>0)e=this._freeIndices.pop(),t=this._generations[e];else{if(this._highWater>=this._capacity)throw new i.ECSError(i.ECS_ERROR.EID_MAX_INDEX_OVERFLOW,`entityIndexCapacity (${this._capacity}) is exhausted. Raise it in ECSOptions.memory, or destroy unused entities`);e=this._highWater++,this._generations[e]=i.INITIAL_GENERATION,t=i.INITIAL_GENERATION,this._lengthView[0]=this._highWater}return this._aliveCount++,this.lastIndex=e,i.createEntityId(e,t)}assertCapacity(e){const t=e-this._freeIndices.length;if(t>0&&this._highWater+t>this._capacity)throw new i.ECSError(i.ECS_ERROR.EID_MAX_INDEX_OVERFLOW,`entityIndexCapacity (${this._capacity}) cannot fit ${e} new entities (${this._freeIndices.length} free, high-water ${this._highWater}). Raise it in ECSOptions.memory, or destroy unused entities`)}release(e,t){const s=t+1;s<i.RETIRED_GENERATION?(this._generations[e]=s,this._freeIndices.push(e)):this._generations[e]=i.RETIRED_GENERATION,this._aliveCount--}isAliveIndex(e,t){return e<this._highWater&&this._generations[e]===t}publishLength(){this._lengthView[0]=this._highWater}snapshotFreeIndices(){return this._freeIndices.slice()}setHighWater(e){this._highWater=e}restoreHostState(e,t){this._freeIndices.length=0;for(let s=0;s<e.length;s++)this._freeIndices.push(e[s]);this._aliveCount=t}}const qe=65536;class Xt{destroyIds=[];addIds=[];addDefs=[];addValues=[];removeIds=[];removeDefs=[];toggleIds=[];toggleDisable=[];_flushing=!1;_host;_observerEvents;constructor(e,t){this._host=e,this._observerEvents=t}queueDestroy(e){this.destroyIds.push(e)}queueAdd(e,t,s){this.addIds.push(e),this.addDefs.push(t),this.addValues.push(s)}queueRemove(e,t){this.removeIds.push(e),this.removeDefs.push(t)}queueToggle(e,t){this.toggleIds.push(e),this.toggleDisable.push(t)}get destroyCount(){return this.destroyIds.length}get addRemoveCount(){return this.addIds.length+this.removeIds.length}get toggleCount(){return this.toggleIds.length}flushDestroys(){this._flushing||this._host.applyDestroys()}flushStructural(){if(this._host.structuralObserverCount()===0&&this._host.toggleObserverCount()===0){this.addIds.length>0&&this._host.applyAdds(),this.removeIds.length>0&&this._host.applyRemoves(),this.toggleIds.length>0&&this._host.applyToggles();return}if(this._flushing)return;this._flushing=!0;const e=this._observerEvents,t=this._host.structuralHooks(),s=t.length;try{let r=0;for(;this.addIds.length>0||this.removeIds.length>0||this.destroyIds.length>0||this.toggleIds.length>0;){if(++r>qe)throw new i.ECSError(i.ECS_ERROR.OBSERVER_NON_CONVERGENT,`observer cascade did not converge after ${qe} rounds, two observers likely enqueue each other's structural ops forever`);if(e.addLen=0,e.remLen=0,e.disLen=0,e.enaLen=0,this.addIds.length>0||this.removeIds.length>0?(this.addIds.length>0&&this._host.applyAdds(),this.removeIds.length>0&&this._host.applyRemoves()):this.destroyIds.length>0?this._host.applyDestroys():this._host.applyToggles(),s>0&&(e.addLen>0||e.remLen>0||e.disLen>0||e.enaLen>0))for(let n=0;n<s;n++)t[n](e)}}finally{this._flushing=!1}}}function _t(a,e,t){const s=a.get(e);s!==void 0?s.push(t):a.set(e,[t])}function ft(a,e){let t=a;const s=new Array(e.length);for(let r=0;r<e.length;r++){const n=e[r],o=new Array(n.columns.length);for(let c=0;c<n.columns.length;c++){const h=n.columns[c];t=i.alignUp(t,h.stride),o[c]={componentId:h.componentId,fieldId:h.fieldId,typeTag:h.typeTag,byteOff:t,stride:h.stride},t+=h.stride*n.rowCapacity}s[r]={archetypeId:n.archetypeId,componentMask:n.componentMask,rowCount:0,enabledCount:0,rowCapacity:n.rowCapacity,columns:o}}if(t>i.STORE_MAX_BYTE_OFFSET)throw new i.StoreLayoutOverflowError(t);return{descriptors:s,newTotal:t}}function pt(a,e){const t=a._allocator(a.storeBase+e),s=t!==a.buffer?new DataView(t,a.storeBase):a.view;return{grownBuffer:t,newView:s}}function Et(a){return a._allocator.reservedAtCap===!0||a.buffer instanceof ArrayBuffer?a.view.getUint32(i.STORE_HEADER_OFFSETS.capacity,!0):a.buffer.byteLength-a.storeBase}function Jt(a){const e={};for(let r=0;r<i.STORE_PREFIX_REGIONS.length;r++){const n=i.STORE_PREFIX_REGIONS[r],o=a.view.getUint32(i.STORE_HEADER_OFFSETS[n.headerOff],!0);o!==0&&n.readOptions(a.view,o,e)}const t=i.readHeaderRegionTable(a.view);t.length>0&&(e.regions=t.map(r=>({id:r.regionId,name:`region:${r.regionId}`,bytes:r.byteLength,init:()=>{}})));const s=a.view.getUint32(i.STORE_HEADER_OFFSETS.bindings_off,!0);if(s!==0){const r=a.view.getUint32(i.STORE_HEADER_OFFSETS.layout_descriptor_off,!0);e.bindingsRegionBytes=r-s}return i.isColumnStoreInternal(a)&&a._reservedDescriptorBytes>0&&(e.reservedDescriptorBytes=a._reservedDescriptorBytes),e.storeBase=a.storeBase,e}function Zt(a){const e=new Map;for(let r=0;r<i.STORE_PREFIX_REGIONS.length;r++){const n=i.STORE_PREFIX_REGIONS[r],o=a.view.getUint32(i.STORE_HEADER_OFFSETS[n.headerOff],!0);if(o===0)continue;const c=n.regionBytes(a.view,o);e.set(n.headerOff,new Uint8Array(a.buffer,a.storeBase+o,c).slice())}const t=new Map,s=i.readHeaderRegionTable(a.view);for(let r=0;r<s.length;r++){const n=s[r];t.set(n.regionId,new Uint8Array(a.buffer,a.storeBase+n.byteOffset,n.byteLength).slice())}return{mechanism:e,consumer:t}}function es(a,e){for(const[t,s]of e.mechanism){const r=a.view.getUint32(i.STORE_HEADER_OFFSETS[t],!0);new Uint8Array(a.buffer,a.storeBase+r,s.byteLength).set(s)}for(const[t,s]of e.consumer){const r=i.findRegionOffset(a.view,t);if(r===0)continue;new Uint8Array(a.buffer,a.storeBase+r,s.byteLength).set(s)}}function ts(a,e){const t=new Map;for(const[s,r]of a.archetypes){const n=e.get(s)??0;if(n===0)continue;const o=[];for(let c=0;c<r.columnsInOrder.length;c++){const h=r.columnsInOrder[c],l=n*h.stride,u=new Uint8Array(l);u.set(new Uint8Array(h.view.buffer,h.view.byteOffset,l)),o.push(u)}t.set(s,o)}return t}function ss(a,e){for(const[t,s]of e){const r=a.archetypes.get(t);if(r===void 0)throw new Error(`restoreLiveColumns: the new store is missing archetype ${t}. Build the spec list so it carries every archetype the snapshot holds.`);const n=r.columnsInOrder;for(let o=0;o<s.length;o++){const c=n[o].view;new Uint8Array(c.buffer,c.byteOffset,s[o].byteLength).set(s[o])}}}function yt(a,e,t,s){const r=a.view.getUint32(i.STORE_HEADER_OFFSETS.view_stamp,!0),n=ts(a,t),o=Zt(a),c=Jt(a),h=i.createColumnStore(e,s,c);ss(h,n),es(h,o);const l=r+1>>>0;return h.view.setUint32(i.STORE_HEADER_OFFSETS.view_stamp,l,!0),{store:{...h,header:{...h.header,viewStamp:l}},oldViewStamp:r,newViewStamp:l}}function rs(a,e,t){const s=new Array(e.length);for(let p=0;p<e.length;p++){const g=e[p],R=a.archetypes.get(g.archetypeId);s[p]={archetypeId:g.archetypeId,componentMask:R.componentMask,rowCapacity:g.newRowCapacity,columns:R.columnsInOrder}}const{descriptors:r,newTotal:n}=ft(Et(a),s),o=new Map;for(let p=0;p<r.length;p++)o.set(r[p].archetypeId,r[p]);const{grownBuffer:c,newView:h}=pt(a,n),l=new Uint8Array(c,a.storeBase,n);for(let p=0;p<e.length;p++){const g=e[p],R=a.archetypes.get(g.archetypeId),S=o.get(g.archetypeId);for(let w=0;w<R.columnsInOrder.length;w++){const C=R.columnsInOrder[w],v=g.rowCount*C.stride;v>0&&l.copyWithin(S.columns[w].byteOff,C.byteOff,C.byteOff+v)}}let u=t;for(const[p,g]of a.archetypes){{const S=h.getUint32(u+i.ARCHETYPE_DESCRIPTOR_OFFSETS.archetype_id,!0);if(S!==p)throw new ie(`descriptor cursor desync at byte ${u}: store holds archetype ${S}, expected ${p} (Map order diverged from on-store write order)`)}const R=o.get(p);R!==void 0&&i.writeArchetypeDescriptor(h,u,R),u+=i.archetypeDescriptorBytes(g.columnsInOrder.length)}const d=h.getUint32(i.STORE_HEADER_OFFSETS.view_stamp,!0),_=d+1>>>0;h.setUint32(i.STORE_HEADER_OFFSETS.view_stamp,_,!0),h.setUint32(i.STORE_HEADER_OFFSETS.capacity,n,!0);const f=i.createArchetypeViews(c,a.storeBase,[...o.values()]),y=new Map;for(const[p,g]of a.archetypes){const R=f.get(p);y.set(p,R??g)}const E={buffer:c,view:h,header:{...a.header,viewStamp:_,capacity:n},storeBase:a.storeBase,archetypes:y,_regionBytes:a._regionBytes,_allocator:a._allocator,_reservedDescriptorBytes:a._reservedDescriptorBytes,_usedDescriptorBytes:a._usedDescriptorBytes},m=new Array(e.length);for(let p=0;p<e.length;p++)m[p]=e[p].archetypeId;return{store:E,oldViewStamp:d,newViewStamp:_,viewsPreserved:!0,grownArchetypeIds:m}}class ie extends Error{constructor(e){super(e),this.name="StoreGrowError"}}function ns(a,e,t){const s=new Map;for(let u=0;u<e.archetypes.length;u++){const d=e.archetypes[u];s.set(d.archetypeId,d)}const r=[],n=[];for(const[u,d]of a.archetypes){const _=s.get(u),f=_?.newRowCapacity??d.rowCapacity;if(f<(_?.rowCount??0))throw new ie(`archetype ${u}: newRowCapacity ${f} < rowCount ${_?.rowCount}`);if(f<d.rowCapacity)throw new ie(`archetype ${u}: shrinking from ${d.rowCapacity} to ${f} is not supported`);f>d.rowCapacity&&n.push({archetypeId:u,newRowCapacity:f,rowCount:_?.rowCount??0}),r.push({archetypeId:u,componentMask:d.componentMask,rowCapacity:f,columns:d.columnsInOrder})}const o=new Map;for(const[u,d]of a.archetypes){const f=s.get(u)?.rowCount??0;if(f>d.rowCapacity)throw new ie(`archetype ${u}: row_count ${f} > old row_capacity ${d.rowCapacity}`);f>0&&o.set(u,f)}if(t?.isInPlace===!0&&i.isColumnStoreInternal(a)&&a._allocator===t&&n.length>0){const u=a.view.getUint32(i.STORE_HEADER_OFFSETS.layout_descriptor_off,!0);return rs(a,n,u)}const{store:c,oldViewStamp:h,newViewStamp:l}=yt(a,r,o,t);return{store:c,oldViewStamp:h,newViewStamp:l,viewsPreserved:!1,grownArchetypeIds:[]}}class q extends Error{constructor(e){super(e),this.name="StoreExtendError"}}function is(a,e,t){if(e.newArchetypes.length===0)throw new q("extend plan has no new archetypes. Use growColumnStore to resize an existing one.");const s=new Set;for(let u=0;u<e.newArchetypes.length;u++){const d=e.newArchetypes[u].archetypeId;if(s.has(d))throw new q(`duplicate archetype_id ${d} in extend plan`);if(a.archetypes.has(d))throw new q(`archetype_id ${d} already exists in the store. Use growColumnStore to resize it.`);s.add(d)}if(t?.isInPlace===!0&&i.isColumnStoreInternal(a)&&a._allocator===t){const u=a.view.getUint32(i.STORE_HEADER_OFFSETS.layout_descriptor_off,!0),d=a._usedDescriptorBytes??i.usedDescriptorBytes(a.archetypes);let _=0;for(let f=0;f<e.newArchetypes.length;f++)_+=i.archetypeDescriptorBytes(e.newArchetypes[f].columns.length);if(d+_<=a._regionBytes)return os(a,e.newArchetypes,u,d,_)}const r=new Map,n=typeof e.existing=="function"?e.existing():e.existing;if(n)for(let u=0;u<n.length;u++){const d=n[u];if(!a.archetypes.has(d.archetypeId))throw new q(`existing row_count names unknown archetype_id ${d.archetypeId}`);if(d.rowCount<0)throw new q(`archetype ${d.archetypeId}: row_count must be non-negative (got ${d.rowCount})`);if(d.rowCount>0){const _=a.archetypes.get(d.archetypeId);if(d.rowCount>_.rowCapacity)throw new q(`archetype ${d.archetypeId}: row_count ${d.rowCount} > old row_capacity ${_.rowCapacity}`)}r.set(d.archetypeId,d.rowCount)}const o=[];for(const[u,d]of a.archetypes)o.push({archetypeId:u,componentMask:d.componentMask,rowCapacity:d.rowCapacity,columns:d.columnsInOrder});for(let u=0;u<e.newArchetypes.length;u++)o.push(e.newArchetypes[u]);const{store:c,oldViewStamp:h,newViewStamp:l}=yt(a,o,r,t);return{store:c,oldViewStamp:h,newViewStamp:l,viewsPreserved:!1}}function os(a,e,t,s,r){const n=new Array(e.length);for(let p=0;p<e.length;p++){const g=e[p];n[p]={archetypeId:g.archetypeId,componentMask:g.componentMask,rowCapacity:g.rowCapacity,columns:g.columns.map(R=>({componentId:R.componentId,fieldId:R.fieldId,typeTag:R.typeTag,stride:i.TYPE_TAG_STRIDE[R.typeTag]}))}}const{descriptors:o,newTotal:c}=ft(Et(a),n),{grownBuffer:h,newView:l}=pt(a,c);let u=t+s;for(let p=0;p<o.length;p++)u=i.writeArchetypeDescriptor(l,u,o[p]);const d=l.getUint32(i.STORE_HEADER_OFFSETS.view_stamp,!0),_=a.archetypes.size+e.length;l.setUint32(i.STORE_HEADER_OFFSETS.archetype_count,_,!0),l.setUint32(i.STORE_HEADER_OFFSETS.capacity,c,!0);const f=d+1>>>0;l.setUint32(i.STORE_HEADER_OFFSETS.view_stamp,f,!0);const y=i.createArchetypeViews(h,a.storeBase,o),E=a.archetypes;for(const[p,g]of y)E.set(p,g);return{store:{buffer:h,view:l,header:{...a.header,viewStamp:f,capacity:c,archetypeCount:_},storeBase:a.storeBase,archetypes:E,_regionBytes:a._regionBytes,_allocator:a._allocator,_reservedDescriptorBytes:a._reservedDescriptorBytes,_usedDescriptorBytes:s+r},oldViewStamp:d,newViewStamp:f,viewsPreserved:!0}}class as{archetypes=[];componentIndex=[];_archetypeMap=new Map;_nextArchetypeId=0;_host;constructor(e){this._host=e}get(e){if(e<0||e>=this.archetypes.length)throw new i.ECSError(i.ECS_ERROR.ARCHETYPE_NOT_FOUND,`Archetype with ID ${e} not found`);return this.archetypes[e]}getOrCreateFromMask(e){const t=e.hash(),s=this._lookup(e,t);if(s!==null)return s;const r=Ue(this._nextArchetypeId++),n=this._createLayouts(e);return this._host.extendStore([Ye(r,e,n,this._host.initialCapacity())]),this._install(r,e,n,t),r}getOrCreateFromMasks(e){const t=new Array(e.length),s=[],r=[],n=[],o=[];for(let h=0;h<e.length;h++){const l=e[h],u=l.hash(),d=this._lookup(l,u);if(d!==null){t[h]=d;continue}let _=!1;for(let y=0;y<s.length;y++)if(r[y]===u&&s[y].equals(l)){t[h]=o[y],_=!0;break}if(_)continue;const f=Ue(this._nextArchetypeId++);s.push(l),r.push(u),n.push(this._createLayouts(l)),o.push(f),t[h]=f}if(s.length===0)return t;const c=new Array(s.length);for(let h=0;h<s.length;h++)c[h]=Ye(o[h],s[h],n[h],this._host.initialCapacity());this._host.extendStore(c);for(let h=0;h<s.length;h++)this._install(o[h],s[h],n[h],r[h]);return t}_lookup(e,t){const s=this._archetypeMap.get(t);if(s===void 0)return null;for(let r=0;r<s.length;r++)if(this.archetypes[s[r]].mask.equals(e))return s[r];return null}_createLayouts(e){const t=[],s=this._host.componentMetas();return e.forEach(r=>{const n=r,o=s[n];o&&o.fieldNames.length>0&&t.push({componentId:n,fieldNames:o.fieldNames,fieldIndex:o.fieldIndex,fieldTypes:o.fieldTypes,fieldGid:o.fieldGid})}),t}_install(e,t,s,r){const n=t.copy(),o=this._host.materialize(e,n,s);this.archetypes.push(o),_t(this._archetypeMap,r,e),t.forEach(c=>{const h=c;let l=this.componentIndex[h];if(l===void 0&&(l=[],this.componentIndex[h]=l),l.length>0&&e<=l[l.length-1])throw new i.ECSError(i.ECS_ERROR.COMPONENT_INDEX_INVARIANT,`componentIndex bucket for component ${h} received archetype ${e} out of ascending order (last = ${l[l.length-1]}). Buckets are duplicate-free and ascending by construction (see install). This means install ran twice for an id, or a second writer of componentIndex was introduced.`);l.push(e)}),this._host.fanIntoQueries(o)}resolveAdd(e,t){const s=this.get(e);if(s.mask.has(t))return e;const r=s.getEdge(t);if(r?.add!=null)return r.add;const n=this.getOrCreateFromMask(s.mask.copyWithSet(t));return this._cacheEdge(s,this.get(n),t),n}resolveRemove(e,t){const s=this.get(e);if(!s.mask.has(t))return e;const r=s.getEdge(t);if(r?.remove!=null)return r.remove;const n=this.getOrCreateFromMask(s.mask.copyWithClear(t));return this._cacheEdge(this.get(n),s,t),n}_cacheEdge(e,t,s){const r=e.getEdge(s)??{add:null,remove:null,addMap:null,removeMap:null};r.add=t.id,r.addMap=we(e,t),e.setEdge(s,r);const n=t.getEdge(s)??{add:null,remove:null,addMap:null,removeMap:null};n.remove=e.id,n.removeMap=we(t,e),t.setEdge(s,n)}}function Ye(a,e,t,s){const r=[];for(let c=0;c<t.length;c++){const h=t[c],l=h.fieldTypes;for(let u=0;u<l.length;u++)r.push({componentId:h.componentId,fieldId:u,typeTag:i.TYPED_ARRAY_TAG_TO_TYPE_TAG[l[u]]})}const n=e.words,o=new Array(i.COMPONENT_MASK_WORDS);for(let c=0;c<i.COMPONENT_MASK_WORDS;c++)o[c]=(n[c]??0)>>>0;return{archetypeId:a,componentMask:o,rowCapacity:s,columns:r}}function cs(a,e,t){for(let s=0;s<e.length;s++)e[s].isBufferBacked&&e[s].refreshViews(a),e[s].resetTicks();t.setHighWater(a.view.getUint32(a.header.entityIndexOff+i.ENTITY_INDEX_HEADER_OFFSETS.length,!0))}function hs(a,e,t,s,r){const n=r.highWater,o=r.generations,c=new Map;for(let h=0;h<n;h++){const l=t[h];if(l===i.UNASSIGNED)continue;const u=s[h];if(u===i.UNASSIGNED)continue;let d=c.get(l);d===void 0&&(d=[],c.set(l,d)),d[u]=i.createEntityId(h,o[h])}for(let h=0;h<a.archetypeRows.length;h++){const l=a.archetypeRows[h],u=e(l.archetypeId),d=c.get(l.archetypeId)??[];{if(d.length!==l.length)throw new i.ECSRestoreError(`archetype ${l.archetypeId} row-count mismatch on restore. The scan found ${d.length} rows and the host state recorded ${l.length}`);for(let _=0;_<d.length;_++)if(d[_]===void 0)throw new i.ECSRestoreError(`archetype ${l.archetypeId} has a hole at row ${_} after restore (entity-index region inconsistent)`)}u.restoreHostRows(d,l.enabledCount)}}const te=i.INDEX_BITS,D=i.INDEX_MASK,ls=i.MAX_ENTITY_ID,us=i.RETIRED_GENERATION,We=-1,de=new DataView(new ArrayBuffer(8)),Ve=129,ds=7,_e=-1;class _s{_entityAllocator;_componentMetas=[];_sparseStores=[];_sparseNames=[];_sparseDrains=[];_relations;_events;_archGraph;_emptyArchetypeId;_entityArchetypes;_entityRows;_queries;_deferred;_snapshots;get relations(){if(this._relations===null)throw i.pluginMissingError("relations","ecs.relations");return this._relations}requireRelations(e){if(this._relations===null)throw i.pluginMissingError("relations",e);return this._relations}relationHost(){return{isAlive:e=>this.isAlive(e),hasSparse:(e,t)=>this.hasSparse(e,t),pushSparseStore:(e,t)=>this._pushSparseStore(e,t),sparseStoreOf:e=>this._sparseStoreOf(e),sparseStores:()=>this._sparseStores,generations:()=>this._entityAllocator.generations,entityArchetypes:()=>this._entityArchetypes,entityRows:()=>this._entityRows,archetypes:()=>this._archGraph.archetypes,forEachSparseMatch:(e,t,s,r,n,o)=>this.forEachSparseMatch(e,t,s,r,n,o)}}installRelations(e){if(this._relations!==null)throw i.pluginInstalledTwiceError("relations");this._relations=e}get events(){if(this._events===null)throw i.pluginMissingError("events","ecs.events");return this._events}requireEvents(e){if(this._events===null)throw i.pluginMissingError("events",e);return this._events}get hasEvents(){return this._events!==null}installEvents(e){if(this._events!==null)throw i.pluginInstalledTwiceError("events");this._events=e}snapshotHost(){return{sparseStores:()=>this._sparseStores,relationStores:()=>this._relations===null?[]:this._relations.stores,generations:()=>this._entityAllocator.generations,archetypes:()=>this._archGraph.archetypes,columnStore:()=>this._columnStore,bufferAllocator:()=>this._bufferAllocator,entityIndexCapacity:()=>this._entityIndexCapacity,tick:()=>this.tick,setTick:e=>{this.tick=e},publishRowCounts:()=>this.publishRowCounts(),mountRestoredDense:e=>this._mountRestoredDense(e),reconstructHostRows:e=>this._reconstructHostRows(e),invalidateCaches:()=>{this.queryDirtyEpoch++,this._rowCountsDirty=!0}}}get entityAllocator(){return this._entityAllocator}installSnapshots(e){if(this._snapshots!==null)throw i.pluginInstalledTwiceError("snapshots");this._snapshots=e}get snapshots(){if(this._snapshots===null)throw i.pluginMissingError("snapshots","snapshot()");return this._snapshots}get resources(){return this._resources}tick=0;changeTick=1;advanceChangeTick(){return++this.changeTick}trace=null;_structuralObserverCount=0;_toggleObserverCount=0;_observationFlags=new Map;_sparseObservationFlags=new Map;_obsEvents={addComp:[],addEid:[],addLen:0,remComp:[],remEid:[],remLen:0,disComp:[],disEid:[],disLen:0,enaComp:[],enaEid:[],enaLen:0};_structuralHooks=[];addStructuralHook(e){this._structuralHooks.push(e)}_collectDestroyEid=0;_collectDestroyRemoveBit=e=>{if(!this._componentMetas[e].obsRem)return;const t=this._obsEvents;t.remComp[t.remLen]=e,t.remEid[t.remLen]=this._collectDestroyEid,t.remLen++};_collectToggleEid=0;_collectDisableBit=e=>{if(!this._componentMetas[e].obsDisable)return;const t=this._obsEvents;t.disComp[t.disLen]=e,t.disEid[t.disLen]=this._collectToggleEid,t.disLen++};_collectEnableBit=e=>{if(!this._componentMetas[e].obsEnable)return;const t=this._obsEvents;t.enaComp[t.enaLen]=e,t.enaEid[t.enaLen]=this._collectToggleEid,t.enaLen++};_toggleInitial=new Map;anyDirtyTracked=!1;_dirtyTrackedCids=[];_dirtyLists=[];_drainResults=[];_rowCountsDirty=!1;queryDirtyEpoch=0;_columnStore;_initialCapacity;_growHandler=(e,t)=>{const s=e.id,r=this._columnStore.archetypes.get(s);if(r===void 0)throw new i.ECSError(i.ECS_ERROR.ARCHETYPE_NOT_FOUND,`growHandler invoked on archetype ${s} which has no SAB region`);const n=r.rowCapacity,o=e.length+t;let c=n>0?n:1;for(;c<o;)c=c*2;const h=[],l=this._archGraph.archetypes;for(let d=0;d<l.length;d++){const _=l[d],f=this._columnStore.archetypes.get(_.id);f!==void 0&&h.push({archetypeId:_.id,newRowCapacity:_.id===s?c:f.rowCapacity,rowCount:_.hasColumns?_.length:0})}let u;try{u=ns(this._columnStore,{archetypes:h},this._bufferAllocator)}catch(d){throw d instanceof ne.StoreCapExceededError?this._capExceededError(d):d}if(this._columnStore=u.store,u.viewsPreserved){const d=u.grownArchetypeIds;for(let _=0;_<d.length;_++){const f=this._archGet(d[_]);f.isBufferBacked&&f.refreshViews(this._columnStore)}}else for(let d=0;d<l.length;d++)l[d].isBufferBacked&&l[d].refreshViews(this._columnStore);this._handleBufferResized()};_capExceededError(e){const t=this._capContext,s=this._entityAllocator.aliveCount,r=`SAB grow refused: requested ${e.requestedBytes} bytes exceeds `+(e.capBytes!==null?`the ${e.capBytes}-byte cap.`:"the backing's ceiling.");let n;if(t===void 0)n=` The ECS holds ${s} live entities (no sizing intent declared).`;else if(t.budgetEntities!==null){const o=(s/t.budgetEntities).toFixed(1);n=` Declared ${t.intentLabel}. The ECS holds ${s} live entities (${o}× the budget), so either entity creation ran away upstream or the budget is under-declared. Raise the budget only if a ${s}-entity ECS is intended.`}else n=` Declared ${t.intentLabel}. The ECS holds ${s} live entities.`;return new i.ECSError(i.ECS_ERROR.STORE_CAP_EXCEEDED,r+n+` The cap is a hard ceiling with no grow-beyond fallback, diagnose growth before raising it. Caused by: ${e.message}`)}_bufferAllocator;_capContext;_onBufferResized;constructor(e){const t=typeof e=="number"?{initialCapacity:e}:e??{};if(this._initialCapacity=t.initialCapacity??i.DEFAULT_COLUMN_CAPACITY,this._bufferAllocator=t.bufferAllocator??ne.growableSabAllocator(),this._bufferAllocator.isInPlace!==!0)throw new i.ECSError(i.ECS_ERROR.INVALID_MEMORY_OPTIONS,"Store requires an in-place SAB allocator. The flush loops keep writing through hoisted entity-index views across grows, so an allocator that is not in-place (DEFAULT_SAB_ALLOCATOR, for example) corrupts the entity→row mapping. Use growableSabAllocator or wasmMemoryAllocator. An allocator that is not in-place is for snapshot or test sizing only.");this._capContext=t.capContext,this._onBufferResized=t.onBufferReplaced,this._entityIndexCapacity=t.entityIndexCapacity??i.ENTITY_INDEX_DEFAULT_CAPACITY,this._storeBase=t.storeBase??0,this._regions=t.regions,this._bindingsRegionBytes=t.bindingsRegionBytes??0,this._deterministic=t.deterministic??!1,this._deferred=new Xt({applyAdds:()=>this._flushAdds(),applyRemoves:()=>this._flushRemoves(),applyDestroys:()=>this._flushDestroys(),applyToggles:()=>this._flushToggles(),structuralObserverCount:()=>this._structuralObserverCount,toggleObserverCount:()=>this._toggleObserverCount,structuralHooks:()=>this._structuralHooks},this._obsEvents),this._snapshots=null,this._relations=null,this._events=null,this._columnStore=i.createColumnStore([],this._bufferAllocator,{storeBase:this._storeBase,reservedDescriptorBytes:64*1024,entityIndexCapacity:this._entityIndexCapacity,eventRingCapacitySlots:i.EVENT_RING_DEFAULT_CAPACITY_SLOTS,commandRingCapacitySlots:i.COMMAND_RING_DEFAULT_CAPACITY_SLOTS,actionRingCapacitySlots:i.ACTION_RING_DEFAULT_CAPACITY_SLOTS,regions:this._regions,bindingsRegionBytes:this._bindingsRegionBytes});const s=i.createEntityIndexViews(this._columnStore.buffer,this._storeBase+this._columnStore.header.entityIndexOff,this._entityIndexCapacity);this._entityArchetypes=s.archetypes,this._entityRows=s.rows,this._entityAllocator=new Kt(this._entityIndexCapacity,s.generations,new Uint32Array(this._columnStore.buffer,this._storeBase+this._columnStore.header.entityIndexOff+i.ENTITY_INDEX_HEADER_OFFSETS.length,1)),this._queries=new Wt({archetypes:()=>this._archGraph.archetypes,componentIndex:()=>this._archGraph.componentIndex,archetypeAt:r=>this._archGraph.get(r)}),this._archGraph=new as({componentMetas:()=>this._componentMetas,initialCapacity:()=>this._initialCapacity,extendStore:r=>this._extendStore(r),materialize:(r,n,o)=>this._materializeArchetype(r,n,o),fanIntoQueries:r=>this._queries.fanIn(r)}),this._emptyArchetypeId=this._archGetOrCreateFromMask(new I.BitSet)}_entityIndexCapacity;_storeBase;_regions;_bindingsRegionBytes;_deterministic;get deterministic(){return this._deterministic}_assertDeterministic(e){if(!this._deterministic)throw new i.ECSError(i.ECS_ERROR.DETERMINISM_DISABLED,`${e} requires determinism. Construct the world with { deterministic: true }. The canonical-ordering determinism surface is opt-in: stateHash, snapshotSparse, restoreSparse.`)}_refreshEntityIndexViews(){const e=this._columnStore.view.getUint32(i.STORE_HEADER_OFFSETS.entity_index_off,!0),t=this._columnStore.storeBase,s=i.createEntityIndexViews(this._columnStore.buffer,t+e,this._entityIndexCapacity);this._entityArchetypes=s.archetypes,this._entityRows=s.rows,this._entityAllocator.replantViews(s.generations,new Uint32Array(this._columnStore.buffer,t+e+i.ENTITY_INDEX_HEADER_OFFSETS.length,1))}_handleBufferResized(){this._refreshEntityIndexViews(),this._entityAllocator.publishLength(),this._onBufferResized?.()}get columnStore(){return this._columnStore}regionOffset(e){const t=i.findRegionOffset(this._columnStore.view,e);return t===0?0:this._columnStore.storeBase+t}regionHandle(e){const t=i.findRegionEntry(this._columnStore.view,e);return t===null?null:{buffer:this._columnStore.buffer,view:this._columnStore.view,offset:this._columnStore.storeBase+t.byteOffset,bytes:t.byteLength}}publishRowCounts(){if(!this._rowCountsDirty)return;const e=this._columnStore.view;let t=e.getUint32(i.STORE_HEADER_OFFSETS.layout_descriptor_off,!0);const s=this._archGraph.archetypes;for(let r=0;r<s.length;r++){const n=s[r];if(!n.isBufferBacked)continue;const o=e.getUint32(t+i.ARCHETYPE_DESCRIPTOR_OFFSETS.column_count,!0);{const c=e.getUint32(t+i.ARCHETYPE_DESCRIPTOR_OFFSETS.archetype_id,!0);if(c!==n.id)throw new Error(`descriptor order drift: archetypes[${r}].id=${n.id} but descriptor at +${t} reports archetype_id=${c}`)}e.setUint32(t+i.ARCHETYPE_DESCRIPTOR_OFFSETS.row_count,n.hasColumns?n.length:0,!0),e.setUint32(t+i.ARCHETYPE_DESCRIPTOR_OFFSETS.enabled_count,n.hasColumns?n.enabledCount:0,!0),t+=i.ARCHETYPE_DESCRIPTOR_HEADER_BYTES+o*i.COLUMN_DESCRIPTOR_BYTES}this._rowCountsDirty=!1}stateHash(){this._assertDeterministic("stateHash()");let e=Ut;const t=this._archGraph.archetypes;for(let n=0;n<t.length;n++){const o=t[n],c=o.id,h=o.length;if(e=k(e,c),e=k(e,h),e=k(e,o.enabledCount),h===0)continue;const l=o.flatColumns;for(let u=0;u<l.length;u++){const d=l[u].buf,_=h*d.BYTES_PER_ELEMENT,f=new Uint8Array(d.buffer,d.byteOffset,_),y=_>>>2;let E=0;for(let p=0;p<y;p++){const g=(f[E]|f[E+1]<<8|f[E+2]<<16|f[E+3]<<24)>>>0;e=(e^g)>>>0,e=Math.imul(e,ge),E+=4}const m=_&3;if(m!==0){let p=f[E];m>1&&(p|=f[E+1]<<8),m>2&&(p|=f[E+2]<<16),e=(e^p>>>0)>>>0,e=Math.imul(e,ge)}}}const s=this._sparseStores;for(let n=0;n<s.length;n++){const o=s[n];e=k(e,n),e=k(e,o.size);const c=o.canonicalIndices();for(let h=0;h<c.length;h++){const l=c[h];e=k(e,l);const u=o.getRow(l);for(let d=0;d<u.length;d++)de.setFloat64(0,u[d],!0),e=k(e,de.getUint32(0,!0)),e=k(e,de.getUint32(4,!0))}}const r=this._relations===null?[]:this._relations.stores;for(let n=0;n<r.length;n++){const o=r[n];o.exclusive||(e=k(e,n),o.forEachCanonicalTargetSet((c,h)=>{e=k(e,c),e=k(e,h.length);for(let l=0;l<h.length;l++)e=k(e,h[l])}))}return e>>>0}_archGet(e){return this._archGraph.get(e)}entityIdAtRow(e,t){const s=this._archGet(e);if(t<0||t>=s.entityCount)throw new i.ECSError(i.ECS_ERROR.ARCHETYPE_NOT_FOUND,`entity_id_at_row: archetype ${e} has ${s.entityCount} rows, requested row ${t}`);return s.entityIds[t]}_archGetOrCreateFromMask(e){return this._archGraph.getOrCreateFromMask(e)}archCreateManyFromMasks(e){return this._archGraph.getOrCreateFromMasks(e)}_extendStore(e){const t=()=>{const r=[],n=this._archGraph.archetypes;for(let o=0;o<n.length;o++){const c=n[o],h=this._columnStore.archetypes.get(c.id);h!==void 0&&r.push({archetypeId:c.id,newRowCapacity:h.rowCapacity,rowCount:c.hasColumns?c.length:0})}return r};let s;try{s=is(this._columnStore,{newArchetypes:e,existing:t},this._bufferAllocator)}catch(r){throw r instanceof ne.StoreCapExceededError?this._capExceededError(r):r}if(this._columnStore=s.store,!s.viewsPreserved){const r=this._archGraph.archetypes;for(let n=0;n<r.length;n++)r[n].isBufferBacked&&r[n].refreshViews(this._columnStore)}this._handleBufferResized()}_materializeArchetype(e,t,s){const r=Oe.fromColumnStore(e,t,s,this._columnStore,e);if(r.growHandler=this._growHandler,this.anyDirtyTracked){const n=this._dirtyTrackedCids;for(let o=0;o<n.length;o++)r.installTicks(n[o])}return r}_archResolveAdd(e,t){return this._archGraph.resolveAdd(e,t)}_archResolveRemove(e,t){return this._archGraph.resolveRemove(e,t)}createEntity(){const e=this._entityAllocator.alloc(),t=this._entityAllocator.lastIndex;return this._entityArchetypes[t]=this._emptyArchetypeId,this._entityRows[t]=i.UNASSIGNED,e}_allocEntity(){return this._entityAllocator.alloc()}_assertEntityIndexCapacity(e){this._entityAllocator.assertCapacity(e)}createTemplate(e){const t=new I.BitSet;for(let h=0;h<e.length;h++)t.set(e[h].def.id);const s=this._archGetOrCreateFromMask(t),r=this._archGet(s),n=new Array(r.flatColumns.length).fill(0),o=new Map,c=new Array(e.length);for(let h=0;h<e.length;h++){c[h]=e[h].def;const l=e[h].def.id,u=this._componentMetas[l];if(u===void 0)throw new i.ECSError(i.ECS_ERROR.COMPONENT_NOT_REGISTERED,`template: component ${l} is not registered`);const d=e[h].values??i.EMPTY_VALUES,_=r.colOffset[l];for(let f=0;f<u.fieldNames.length;f++){const y=u.fieldNames[f];n[_+f]=d[y]??0,o.set(y,o.has(y)?We:_+f)}}return{archetypeId:s,flatValues:n,flatBits:r.widthBits(n),overrideIndex:o,defs:c}}_resolveOverrideColumn(e,t){const s=e.overrideIndex.get(t);if(s===void 0)throw new i.ECSError(i.ECS_ERROR.FIELD_NOT_REGISTERED,`template override: no field "${t}" in this template`);if(s===We)throw new i.ECSError(i.ECS_ERROR.FIELD_NOT_REGISTERED,`template override: field "${t}" is ambiguous (owned by more than one component in this template); set it via the template defaults instead of a flat override`);return s}_applyOverrides(e,t,s,r){for(const n in r){const o=r[n];if(o===void 0)continue;const c=this._resolveOverrideColumn(s,n);c>=0&&e.writeFlatElem(c,t,o)}}_applyOverridesRange(e,t,s,r,n){const o=e.flatColumns;for(const c in n){if(n[c]===void 0)continue;const h=this._resolveOverrideColumn(r,c);h>=0&&o[h].buf.fill(n[c],t,t+s)}}spawn(e,t){const s=this._archGraph.archetypes[e.archetypeId];s.materializesRows&&s.reserveRows(1);const r=this._allocEntity(),n=this._entityAllocator.lastIndex;if(!s.materializesRows)return this._entityArchetypes[n]=e.archetypeId,this._entityRows[n]=i.UNASSIGNED,r;const o=s.length,c=s.enabledCount,h=s.addEntityWithBits(r,e.flatBits,this.changeTick,this._entityRows);return t!==void 0&&this._applyOverrides(s,h,e,t),this._entityArchetypes[n]=e.archetypeId,this._entityRows[n]=h,this._onArchGrow(s,o,c),r}spawnMany(e,t,s){if(t<=0)return[];const r=this._archGraph.archetypes[e.archetypeId];this._assertEntityIndexCapacity(t),r.reserveRows(t);const n=new Array(t),o=new Uint32Array(t);for(let _=0;_<t;_++){const f=this._allocEntity();o[_]=f,n[_]=f}const c=this._entityArchetypes,h=this._entityRows;if(!r.materializesRows){for(let _=0;_<t;_++){const f=i.getEntityIndex(n[_]);c[f]=e.archetypeId,h[f]=i.UNASSIGNED}return n}const l=r.length,u=r.enabledCount;if(r.disabledCount>0){for(let _=0;_<t;_++){const f=r.addEntityWithBits(n[_],e.flatBits,this.changeTick,h),y=i.getEntityIndex(n[_]);c[y]=e.archetypeId,h[y]=f,s!==void 0&&this._applyOverrides(r,f,e,s)}return this._onArchGrow(r,l,u),n}const d=r.addEntitiesWithValues(o,t,e.flatValues,this.changeTick);for(let _=0;_<t;_++){const f=i.getEntityIndex(n[_]);c[f]=e.archetypeId,h[f]=d+_}return s!==void 0&&this._applyOverridesRange(r,d,t,e,s),this._onArchGrow(r,l,u),n}destroyEntity(e){if(!this.isAlive(e))throw i.entityNotAliveError("destroyEntity",e);if(this._relations===null||!this._relations.hasTargetCleanup){this._destroyOne(e,null);return}const t=[e];for(let s=0;s<t.length;s++){const r=t[s];this.isAlive(r)&&this._destroyOne(r,t)}}_destroyOne(e,t){const s=i.getEntityIndex(e),r=this._entityRows[s];if(r!==i.UNASSIGNED){const o=this._archGet(this._entityArchetypes[s]),c=o.length;o.removeRow(r,this._entityRows),this._onArchShrink(o,c)}this._entityArchetypes[s]=i.UNASSIGNED,this._entityRows[s]=i.UNASSIGNED;const n=this._relations;n!==null&&n.count>0&&(n.purgeSource(e),t!==null&&n.cleanupTarget(e,t)),this._sparseStores.length>0&&this._purgeSparse(s),this._entityAllocator.release(s,i.getEntityGeneration(e))}isAlive(e){return this._liveIndex(e)>=0}_liveIndex(e){const t=e;if(t<0||t>ls)return-1;const s=t>>te;if(s===us)return-1;const r=t&D,n=this._entityAllocator;return r>=n.highWater||n.generations[r]!==s?-1:r}get entityCount(){return this._entityAllocator.aliveCount}_onArchShrink(e,t){this._rowCountsDirty=!0,t===0!=(e.length===0)&&this.queryDirtyEpoch++}_onArchGrow(e,t,s){this._rowCountsDirty=!0,(t===0||s===0&&e.enabledCount!==0)&&this.queryDirtyEpoch++}_onArchEnabledChange(e,t){this._rowCountsDirty=!0,t===0!=(e.enabledCount===0)&&this.queryDirtyEpoch++}disableEntity(e){if(!this.isAlive(e))throw i.entityNotAliveError("disableEntity",e);const t=i.getEntityIndex(e),s=this._entityRows[t];if(s===i.UNASSIGNED)throw new i.ECSError(i.ECS_ERROR.ENTITY_NOT_ALIVE,"cannot disable a component-less entity: it occupies no archetype row; add a component first");const r=this._archGet(this._entityArchetypes[t]);if(s>=r.enabledCount)return;const n=r.enabledCount;r.disableRow(s,this._entityRows),this._onArchEnabledChange(r,n)}enableEntity(e){if(!this.isAlive(e))throw i.entityNotAliveError("enableEntity",e);const t=i.getEntityIndex(e),s=this._entityRows[t];if(s===i.UNASSIGNED)return;const r=this._archGet(this._entityArchetypes[t]);if(s<r.enabledCount)return;const n=r.enabledCount;r.enableRow(s,this._entityRows),this._onArchEnabledChange(r,n)}isDisabled(e){if(!this.isAlive(e))throw i.entityNotAliveError("isDisabled",e);const t=i.getEntityIndex(e),s=this._entityRows[t];if(s===i.UNASSIGNED)return!1;const r=this._archGet(this._entityArchetypes[t]);return s>=r.enabledCount}_flushEpoch=0;_flushTouched=[];_settleFlushDirty(){const e=this._flushTouched;if(e.length===0)return;this._rowCountsDirty=!0;let t=!1;for(let s=0;s<e.length;s++){const r=e[s];(r.flushPreLen===0!=(r.length===0)||r.flushPreEnabled===0!=(r.enabledCount===0))&&(t=!0)}t&&this.queryDirtyEpoch++,e.length=0,this._flushEpoch++}destroyEntityDeferred(e){if(!this.isAlive(e))throw i.entityNotAliveError("destroyEntityDeferred",e);this._deferred.queueDestroy(e)}disableEntityDeferred(e){if(!this.isAlive(e))throw i.entityNotAliveError("disableEntityDeferred",e);this._deferred.queueToggle(e,!0)}enableEntityDeferred(e){if(!this.isAlive(e))throw i.entityNotAliveError("enableEntityDeferred",e);this._deferred.queueToggle(e,!1)}_flushToggles(){const e=this._deferred.toggleIds,t=this._deferred.toggleDisable,s=e.length;if(!(this._toggleObserverCount>0)){for(let o=0;o<s;o++){const c=e[o];this.isAlive(c)&&(t[o]?this.disableEntity(c):this.enableEntity(c))}e.length=0,t.length=0;return}const n=this._toggleInitial;for(let o=0;o<s;o++){const c=e[o];this.isAlive(c)&&(n.has(c)||n.set(c,this.isDisabled(c)))}for(let o=0;o<s;o++){const c=e[o];this.isAlive(c)&&(t[o]?this.disableEntity(c):this.enableEntity(c))}e.length=0,t.length=0;for(const[o,c]of n){if(!this.isAlive(o))continue;const h=this.isDisabled(o);c!==h&&this._collectToggle(o,h)}n.clear()}_collectToggle(e,t){const s=i.getEntityIndex(e);if(this._entityRows[s]===i.UNASSIGNED)return;const r=this._archGet(this._entityArchetypes[s]);this._collectToggleEid=e,r.mask.forEach(t?this._collectDisableBit:this._collectEnableBit)}get pendingToggleCount(){return this._deferred.toggleCount}flushDestroys(){this._deferred.flushDestroys()}_flushDestroys(){const e=this._deferred.destroyIds;if(e.length===0)return;const t=this._entityAllocator,s=this._entityArchetypes,r=this._entityRows,n=t.generations,o=this._archGraph.archetypes,c=t.highWater;let h=!1,l=!1;const u=this._sparseStores.length>0,d=this._relations,_=d!==null&&d.count>0,f=_&&d.hasTargetCleanup,y=this._structuralObserverCount>0;for(let E=0;E<e.length;E++){const m=e[E],p=m&D,g=m>>te;if(p>=c||n[p]!==g)continue;const R=r[p];if(R!==i.UNASSIGNED){const S=o[s[p]];y&&(this._collectDestroyEid=m,S.mask.forEach(this._collectDestroyRemoveBit)),S.removeRow(R,r),h=!0,S.length===0&&(l=!0)}_&&d.purgeSource(m),f&&d.cleanupTarget(m,e),u&&this._purgeSparse(p),s[p]=i.UNASSIGNED,r[p]=i.UNASSIGNED,t.release(p,g)}e.length=0,h&&(this._rowCountsDirty=!0,l&&this.queryDirtyEpoch++)}get pendingDestroyCount(){return this._deferred.destroyCount}addComponentDeferred(e,t,s){if(!this.isAlive(e))throw i.entityNotAliveError("addComponentDeferred",e,this.componentLabel(t.id));this._deferred.queueAdd(e,t,s??i.EMPTY_VALUES)}removeComponentDeferred(e,t){if(!this.isAlive(e))throw i.entityNotAliveError("removeComponentDeferred",e,this.componentLabel(t.id));this._deferred.queueRemove(e,t)}flushStructural(){this._deferred.flushStructural()}_flushAdds(){const e=this._deferred.addIds,t=this._deferred.addDefs,s=this._deferred.addValues,r=e.length,n=this._entityArchetypes,o=this._entityRows,c=this._entityAllocator.generations,h=this._archGraph.archetypes,l=this._componentMetas,u=this._entityAllocator.highWater,d=this.changeTick,_=this._flushEpoch,f=this._flushTouched,y=this._structuralObserverCount>0,E=this._obsEvents;for(let m=0;m<r;m++){const p=e[m],g=p&D,R=p>>te;if(g>=u||c[g]!==R)continue;const S=n[g],w=t[m].id,C=h[S],v=l[w];if(C.mask.has(w)){v.fieldNames.length>0&&C.writeFields(o[g],w,s[m],d);continue}const A=this._archResolveAdd(S,w),T=h[A],H=o[g],Me=!T.hasColumns&&!C.hasColumns;H!==i.UNASSIGNED&&C.flushSeenEpoch!==_&&(C.flushSeenEpoch=_,C.flushPreLen=C.length,C.flushPreEnabled=C.enabledCount,f.push(C)),T.flushSeenEpoch!==_&&(T.flushSeenEpoch=_,T.flushPreLen=T.length,T.flushPreEnabled=T.enabledCount,f.push(T));let J;if(H!==i.UNASSIGNED){if(Me)T.moveEntityFromTag(C,H,p,o);else{const Ct=C.getEdge(w);T.moveEntityFrom(C,H,p,Ct.addMap,d,o)}J=b[0]}else J=Me?T.addEntityTag(p,o):T.addEntity(p,o);v.fieldNames.length>0&&T.writeFields(J,w,s[m],d),n[g]=A,o[g]=J,y&&v.obsAdd&&(E.addComp[E.addLen]=w,E.addEid[E.addLen]=p,E.addLen++)}e.length=0,t.length=0,s.length=0,this._settleFlushDirty()}_flushRemoves(){const e=this._deferred.removeIds,t=this._deferred.removeDefs,s=e.length,r=this._entityArchetypes,n=this._entityRows,o=this._entityAllocator.generations,c=this._archGraph.archetypes,h=this._entityAllocator.highWater,l=this.changeTick,u=this._flushEpoch,d=this._flushTouched,_=this._componentMetas,f=this._structuralObserverCount>0,y=this._obsEvents;for(let E=0;E<s;E++){const m=e[E],p=m&D,g=m>>te;if(p>=h||o[p]!==g)continue;const R=r[p],S=t[E].id,w=c[R];if(!w.mask.has(S))continue;const C=this._archResolveRemove(R,S),v=c[C],A=n[p],T=!v.hasColumns&&!w.hasColumns;if(w.flushSeenEpoch!==u&&(w.flushSeenEpoch=u,w.flushPreLen=w.length,w.flushPreEnabled=w.enabledCount,d.push(w)),v.flushSeenEpoch!==u&&(v.flushSeenEpoch=u,v.flushPreLen=v.length,v.flushPreEnabled=v.enabledCount,d.push(v)),T)v.moveEntityFromTag(w,A,m,n);else{const H=w.getEdge(S);v.moveEntityFrom(w,A,m,H.removeMap,l,n)}r[p]=C,n[p]=b[0],f&&_[S].obsRem&&(y.remComp[y.remLen]=S,y.remEid[y.remLen]=m,y.remLen++)}e.length=0,t.length=0,this._settleFlushDirty()}get pendingStructuralCount(){return this._deferred.addRemoveCount}configureObservation(e,t,s){let r=this._observationFlags.get(e);r===void 0&&(r=[],this._observationFlags.set(e,r)),r[t]=s;let n=!1,o=!1,c=!1,h=!1,l=!1;for(const u of this._observationFlags.values()){const d=u[t];d!==void 0&&(d.add&&(n=!0),d.remove&&(o=!0),d.disable&&(c=!0),d.enable&&(h=!0),d.set&&(l=!0))}this._applyObservation(t,n,o,c,h,l)}_applyObservation(e,t,s,r,n,o){const c=this._componentMetas[e];if(c===void 0)throw new i.ECSError(i.ECS_ERROR.COMPONENT_NOT_REGISTERED,`observe(): component ${e} is not registered`);const h=c.obsAdd||c.obsRem;c.obsAdd=t,c.obsRem=s;const l=t||s;h&&!l?this._structuralObserverCount--:!h&&l&&this._structuralObserverCount++;const u=c.obsDisable||c.obsEnable;c.obsDisable=r,c.obsEnable=n;const d=r||n;u&&!d?this._toggleObserverCount--:!u&&d&&this._toggleObserverCount++,o&&!c.trackDirty?(this._trackRowsById(e),c.trackDirty=!0,this._dirtyLists[e]===void 0&&(this._dirtyLists[e]=[],this._drainResults[e]={scanned:[],listed:[]}),c.listCap=this._listCap(),c.drainTick=this.changeTick,c.scanTick=0):!o&&c.trackDirty&&(c.trackDirty=!1,this._dirtyLists[e].length=0,c.drainTick=this.changeTick,c.scanTick=0)}trackRows(e){if(typeof e=="number"){this._sparseStoreOf(e).trackTicks();return}const t=e.id;if(typeof t!="number")throw new i.ECSError(i.ECS_ERROR.COMPONENT_NOT_REGISTERED,"trackRows(): the definition is not a registered component. Track a dense or a sparse component");this._trackRowsById(t)}configureSparseObservation(e,t,s){let r=this._sparseObservationFlags.get(e);r===void 0&&(r=[],this._sparseObservationFlags.set(e,r)),r[t]=s;let n=!1;for(const o of this._sparseObservationFlags.values())o[t]===!0&&(n=!0);this._applySparseObservation(t,n)}_applySparseObservation(e,t){const s=this._sparseStores[e];if(s===void 0)throw new i.ECSError(i.ECS_ERROR.COMPONENT_NOT_REGISTERED,`observe(): sparse component ${e} is not registered`);t?(s.trackTicks(),this._sparseDrains[e]===void 0&&(this._sparseDrains[e]=[])):s.drainTick=this.changeTick}drainSparseSet(e,t){const s=this._sparseStores[e],r=this._sparseDrains[e];if(s.lastDrainRun===t)return r;s.lastDrainRun=t,r.length=0;const n=s.drainTick;if(s.drainTick=t-1,s.changedTick<=n)return r;const o=s.ticks,c=this._entityAllocator.generations,h=s.size;for(let l=0;l<h;l++){const u=s.indexAt(l);if(o[u]<=n)continue;const d=i.createEntityId(u,c[u]);this.isDisabled(d)||r.push(d)}return r}sparseTickOf(e,t){const s=this._sparseStoreOf(e),r=s.ticks;if(r===null)throw new i.ECSError(i.ECS_ERROR.ROW_TICKS_NOT_TRACKED,`sparseChanged: ${this.sparseLabel(e)} has no row ticks. Call ecs.trackRows(def), or register an onSet observer with granularity "entity", first`,{sparse:e});const n=t&D;return s.has(n)?r[n]:0}sparseTickPlane(e){return this._sparseStoreOf(e)}_trackRowsById(e){const t=this._componentMetas[e];if(t===void 0)throw new i.ECSError(i.ECS_ERROR.COMPONENT_NOT_REGISTERED,`trackRows(): component ${e} is not registered`);if(t.rowTicks||t.fieldNames.length===0)return;t.rowTicks=!0;const s=this._archGraph.componentIndex[e];if(s!==void 0){const r=this._archGraph.archetypes;for(let n=0;n<s.length;n++)r[s[n]].installTicks(e)}this._dirtyTrackedCids.push(e),this.anyDirtyTracked=!0}_listCap(){const e=this._entityAllocator.aliveCount>>>5;return e<64?64:e}noteSet(e,t,s,r){const n=this._componentMetas[e];if(!n.rowTicks)return;const o=t.rowTicks[e];if(n.trackDirty&&o[s]<=n.drainTick&&n.scanTick<=n.drainTick){const c=this._dirtyLists[e];c.push(r),c.length>n.listCap&&(n.scanTick=this.changeTick)}o[s]=this.changeTick}noteSetEntity(e,t){const s=e.id,r=this._componentMetas[s];if(r===void 0||!r.rowTicks||!this.isAlive(t))return;const n=t&D,c=this._archGet(this._entityArchetypes[n]).rowTicks[s];if(c===void 0)return;const h=this._entityRows[n];r.trackDirty&&c[h]<=r.drainTick&&this._dirtyLists[s].push(t),c[h]=this.changeTick}noteScan(e){const t=this._componentMetas[e];t.rowTicks&&(t.scanTick=this.changeTick)}drainSet(e,t){const s=this._componentMetas[e],r=this._drainResults[e];if(s.lastDrainRun===t)return r;s.lastDrainRun=t,r.scanned.length=0,r.listed.length=0;const n=s.drainTick;s.drainTick=t-1,s.listCap=this._listCap();const o=s.scanTick>n,c=this._archGraph.archetypes;if(o){const l=this._archGraph.componentIndex[e];if(l!==void 0)for(let u=0;u<l.length;u++){const d=c[l[u]];if(d.enabledCount===0||d.changedTick[e]<=n)continue;const _=d.rowTicks[e];if(_===void 0)continue;const f=d.entityIds,y=d.enabledCount;for(let E=0;E<y;E++)_[E]>n&&r.scanned.push(f[E])}}const h=this._dirtyLists[e];for(let l=0;l<h.length;l++){const u=h[l];if(o){const d=c[this._entityArchetypes[u&D]];if(d!==void 0&&d.changedTick[e]>n)continue}r.listed.push(u)}return h.length=0,r}forEachChangedArchetype(e,t,s){const r=this._archGraph.componentIndex[e];if(r===void 0)return;const n=this._archGraph.archetypes;for(let o=0;o<r.length;o++){const c=n[r[o]];c.length>0&&c.changedTick[e]>t&&s(c)}}collectEnabledWith(e){const t=[],s=this._archGraph.componentIndex[e];if(s===void 0)return t;const r=this._archGraph.archetypes;for(let n=0;n<s.length;n++){const o=r[s[n]],c=o.entityIds;for(let h=0;h<o.enabledCount;h++)t.push(i.unsafeCast(c[h]))}return t}registerComponent(e,t){return Pt(this._componentMetas,this._deterministic,e,t)}componentLabel(e){return Bt(this._componentMetas,e)}fieldIdOf(e,t){return Lt(this._componentMetas,e,t)}registerSparseComponent(e,t){const s=Object.keys(e),r=new Array(s.length);for(let n=0;n<s.length;n++)r[n]=e[s[n]];return ut(s,"sparse component"),dt(this._deterministic,s,r,"sparse component"),this._pushSparseStore(s,r,t)}sparseLabel(e){const t=this._sparseNames[e];return t!==void 0?`'${t}' (sparse component ${e})`:`sparse component ${e}`}_pushSparseStore(e,t,s){const r=this._sparseStores.length;return this._sparseStores.push(new qt(e,t)),this._sparseNames.push(s),i.unsafeCast(r)}_sparseStoreOf(e){const t=e,s=this._sparseStores[t];if(s===void 0)throw new i.ECSError(i.ECS_ERROR.COMPONENT_NOT_REGISTERED,`sparse component ${t} is not registered`);return s}addSparse(e,t,s){if(!this.isAlive(e))throw i.entityNotAliveError("addSparse",e,this.sparseLabel(t));this._sparseStoreOf(t).setRow(i.getEntityIndex(e),s??i.EMPTY_VALUES)}removeSparse(e,t){if(!this.isAlive(e))throw i.entityNotAliveError("removeSparse",e,this.sparseLabel(t));this._sparseStoreOf(t).remove(i.getEntityIndex(e))}hasSparse(e,t){return this.isAlive(e)?this._sparseStoreOf(t).has(i.getEntityIndex(e)):!1}getSparseField(e,t,s){if(!this.isAlive(e))throw i.entityNotAliveError("getSparseField",e,`${this.sparseLabel(t)}.${s}`);const r=this._sparseStoreOf(t),n=r.fieldIndex[s];if(n===void 0)throw new i.ECSError(i.ECS_ERROR.FIELD_NOT_REGISTERED,`sparse component has no field "${s}"`);const o=r.getField(i.getEntityIndex(e),n);if(o===void 0)throw new i.ECSError(i.ECS_ERROR.COMPONENT_NOT_REGISTERED,"entity does not hold this sparse component");return o}setSparseField(e,t,s,r){if(!this.isAlive(e))throw i.entityNotAliveError("setSparseField",e,`${this.sparseLabel(t)}.${s}`);const n=this._sparseStoreOf(t),o=n.fieldIndex[s];if(o===void 0)throw new i.ECSError(i.ECS_ERROR.FIELD_NOT_REGISTERED,`sparse component has no field "${s}"`);if(!n.setField(i.getEntityIndex(e),o,r,this.changeTick))throw new i.ECSError(i.ECS_ERROR.COMPONENT_NOT_REGISTERED,"entity does not hold this sparse component")}_purgeSparse(e){const t=this._sparseStores;for(let s=0;s<t.length;s++)t[s].remove(e)}sparseFieldNames(e){return this._sparseStoreOf(e).fieldNames}sparseAccessorColumns(e){return this._sparseStoreOf(e).accCols}sparseCursorCheck(e,t){const s=this._sparseStoreOf(e),r=e;return n=>{if(t?i.accessCheck.assertSparseWrite(e):i.accessCheck.assertSparseRead(e),!this.isAlive(n))throw i.entityNotAliveError("sparseCursor.at",n,this.sparseLabel(r));if(!s.has(n&D))throw new i.ECSError(i.ECS_ERROR.COMPONENT_NOT_REGISTERED,`sparseCursor.at: entity ${String(n)} does not hold ${this.sparseLabel(r)}`,{sparse:r,entity:n})}}snapshotSparse(){return this._assertDeterministic("snapshot_sparse()"),this.snapshots.snapshotSparse()}restoreSparse(e){this._assertDeterministic("restore_sparse()"),this.snapshots.restoreSparse(e),this._resetSparseTicks()}_resetSparseTicks(){const e=this._sparseStores;for(let t=0;t<e.length;t++)e[t].resetTicks()}snapshot(){return this._assertDeterministic("snapshot()"),this.snapshots.snapshot()}restore(e){this._assertDeterministic("restore()"),this.snapshots.restore(e),this._resetSparseTicks()}_mountRestoredDense(e){this._columnStore=e,cs(e,this._archGraph.archetypes,this._entityAllocator),this._handleBufferResized()}_reconstructHostRows(e){hs(e,t=>this._archGet(t),this._entityArchetypes,this._entityRows,this._entityAllocator)}forEachSparseMatch(e,t,s,r,n,o){const{sparseIncludes:c,sparseExcludes:h,includesDisabled:l}=r,u=this._sparseStores;{for(let _=0;_<c.length;_++)if(u[c[_]]===void 0)throw new i.ECSError(i.ECS_ERROR.COMPONENT_NOT_REGISTERED,`sparse component ${c[_]} is not registered`);for(let _=0;_<h.length;_++)if(u[h[_]]===void 0)throw new i.ECSError(i.ECS_ERROR.COMPONENT_NOT_REGISTERED,`sparse component ${h[_]} is not registered`)}if(c.length>0){let _=u[c[0]];for(let S=1;S<c.length;S++){const w=u[c[S]];w.size<_.size&&(_=w)}const f=this._entityAllocator.generations,y=this._entityArchetypes,E=this._entityRows,m=this._archGraph.archetypes;let p=-2,g=!1,R=0;for(let S=0;S<_.size;S++){const w=_.indexAt(S);let C=!0;for(let A=0;A<c.length;A++){const T=u[c[A]];if(T!==_&&!T.has(w)){C=!1;break}}if(!C)continue;for(let A=0;A<h.length;A++)if(u[h[A]].has(w)){C=!1;break}if(!C)continue;const v=y[w];if(v!==i.UNASSIGNED){if(v!==p){const A=m[v],T=A.mask;p=v,g=T.contains(e)&&(t===null||!T.overlaps(t))&&(s===null||T.overlaps(s)),R=A.enabledCount}if(g){if(!l){const A=E[w];if(A!==i.UNASSIGNED&&A>=R)continue}o(i.createEntityId(w,f[w]))}}}return}const d=h.length>0;for(let _=0;_<n.length;_++){const f=n[_],y=f.entityIds,E=l?f.totalCount:f.enabledCount;for(let m=0;m<E;m++){const p=y[m];if(d){const g=i.getEntityIndex(p);let R=!1;for(let S=0;S<h.length;S++)if(u[h[S]].has(g)){R=!0;break}if(R)continue}o(p)}}}forEachHierarchyMatch(e,t,s,r,n,o,c,h){this.requireRelations("query.hierarchy").forEachHierarchyMatch(e,t,s,r,n,o,c,h)}forEachTargetMatch(e,t,s,r,n,o){this.requireRelations("query.forEachRelatedTo").forEachTargetMatch(e,t,s,r,n,o)}relationBackingSparseId(e,t){return this.requireRelations(t).relationBackingSparseId(e)}_scratchTargetMask=new I.BitSet;addComponent(e,t,s){if(!this.isAlive(e))throw i.entityNotAliveError("addComponent",e,this.componentLabel(t.id));const r=i.getEntityIndex(e),n=this._entityArchetypes[r],o=this._archGet(n),c=o.getEdge(t.id);if(c===void 0||c.add===null){this._addComponentCold(e,r,o,n,t,s);return}const h=c.add,l=this._archGet(h),u=this._entityRows[r];let d;if(u!==i.UNASSIGNED){const _=o.length,f=l.length,y=l.enabledCount;!l.hasColumns&&!o.hasColumns?l.moveEntityFromTag(o,u,e,this._entityRows):l.moveEntityFrom(o,u,e,c.addMap,this.changeTick,this._entityRows),d=b[0],this._onArchShrink(o,_),this._onArchGrow(l,f,y)}else{const _=l.length,f=l.enabledCount;d=l.hasColumns?l.addEntity(e,this._entityRows):l.addEntityTag(e,this._entityRows),this._onArchGrow(l,_,f)}l.writeFields(d,t.id,s,this.changeTick),this._entityArchetypes[r]=h,this._entityRows[r]=d}_addComponentCold(e,t,s,r,n,o){if(s.hasComponent(n.id)){s.writeFields(this._entityRows[t],n.id,o,this.changeTick);return}this._archResolveAdd(r,n.id),this.addComponent(e,n,o)}addComponents(e,t){if(!this.isAlive(e))throw i.entityNotAliveError("addComponents",e);const s=i.getEntityIndex(e),r=this._entityArchetypes[s],n=this._archGet(r),o=t.length;let c=o;for(let _=0;_<o;_++){const f=t[_].def.id;if(f>=Ve-1||o>ds){c=_e;break}c=c*Ve+(f+1)}if(c!==_e){const _=n.getCompositeAddEdge(c);if(_!==void 0){this._addComponentsInto(e,s,n,this._archGet(_.target),_.target,_.map,t);return}}let h=null;for(let _=0;_<o;_++){const f=t[_].def.id;h!==null?h.set(f):n.mask.has(f)||(h=n.mask.copyInto(this._scratchTargetMask),h.set(f))}if(h===null){const _=this._entityRows[s];for(let f=0;f<o;f++)n.writeFields(_,t[f].def.id,t[f].values??i.EMPTY_VALUES,this.changeTick);return}const l=this._archGetOrCreateFromMask(h),u=this._archGet(l),d=n.transitionMapTo(u);c!==_e&&n.cacheCompositeAddEdge(c,l,d),this._addComponentsInto(e,s,n,u,l,d,t)}_addComponentsInto(e,t,s,r,n,o,c){const h=this._entityRows[t];let l;if(h!==i.UNASSIGNED){const u=s.length,d=r.length,_=r.enabledCount;r.moveEntityFrom(s,h,e,o,this.changeTick,this._entityRows),l=b[0],this._onArchShrink(s,u),this._onArchGrow(r,d,_)}else{const u=r.length,d=r.enabledCount;l=r.addEntity(e,this._entityRows),this._onArchGrow(r,u,d)}for(let u=0;u<c.length;u++)r.writeFields(l,c[u].def.id,c[u].values??i.EMPTY_VALUES,this.changeTick);this._entityArchetypes[t]=n,this._entityRows[t]=l}removeComponent(e,t){if(!this.isAlive(e))throw i.entityNotAliveError("removeComponent",e,this.componentLabel(t.id));const s=i.getEntityIndex(e),r=this._entityArchetypes[s],n=this._archGet(r),o=n.getEdge(t.id);if(o===void 0||o.remove===null){this._removeComponentCold(e,n,r,t);return}const c=o.remove,h=this._archGet(c),l=this._entityRows[s],u=!h.hasColumns&&!n.hasColumns,d=n.length,_=h.length,f=h.enabledCount;u?h.moveEntityFromTag(n,l,e,this._entityRows):h.moveEntityFrom(n,l,e,o.removeMap,this.changeTick,this._entityRows),this._entityArchetypes[s]=c,this._entityRows[s]=b[0],this._onArchShrink(n,d),this._onArchGrow(h,_,f)}_removeComponentCold(e,t,s,r){t.hasComponent(r.id)&&(this._archResolveRemove(s,r.id),this.removeComponent(e,r))}removeComponents(e,t){if(!this.isAlive(e))throw i.entityNotAliveError("removeComponents",e);const s=i.getEntityIndex(e),r=this._entityArchetypes[s],n=this._archGet(r);let o=null;for(let y=0;y<t.length;y++){const E=t[y].id;o!==null?o.clear(E):n.mask.has(E)&&(o=n.mask.copyInto(this._scratchTargetMask),o.clear(E))}if(o===null)return;const c=this._archGetOrCreateFromMask(o),h=this._archGet(c),l=this._entityRows[s],u=n.length,d=h.length,_=h.enabledCount,f=n.transitionMapTo(h);h.moveEntityFrom(n,l,e,f,this.changeTick,this._entityRows),this._entityArchetypes[s]=c,this._entityRows[s]=b[0],this._onArchShrink(n,u),this._onArchGrow(h,d,_)}hasComponent(e,t){const s=this._liveIndex(e);return s<0?!1:this._archGet(this._entityArchetypes[s]).hasComponent(t.id)}batchAddComponent(e,t,s){const r=this._archGet(e);if(r.length===0)return;const n=t.id;if(r.mask.has(n))return;const o=this._archResolveAdd(r.id,n),c=this._archGet(o);if(r.disabledCount>0||c.disabledCount>0)throw new i.ECSError(i.ECS_ERROR.PARTITION_BULK_INTO_DISABLED,"batchAddComponent is unsupported on archetypes with disabled entities, enable them first or use per-entity addComponent");const h=r.getEdge(n),l=r.length,u=l,d=c.length,_=c.enabledCount,f=this._entityArchetypes,y=this._entityRows,E=c.bulkMoveAllFrom(r,h.addMap,this.changeTick);for(let p=0;p<l;p++){const g=i.getEntityIndex(c.entityIds[E+p]);f[g]=o,y[g]=E+p}this._componentMetas[n].fieldNames.length>0&&s&&c.bulkWriteFields(E,l,n,s,this.changeTick),this._onArchShrink(r,u),this._onArchGrow(c,d,_)}batchRemoveComponent(e,t){const s=this._archGet(e);if(s.length===0)return;const r=t.id;if(!s.mask.has(r))return;const n=this._archResolveRemove(s.id,r),o=this._archGet(n);if(s.disabledCount>0||o.disabledCount>0)throw new i.ECSError(i.ECS_ERROR.PARTITION_BULK_INTO_DISABLED,"batchRemoveComponent is unsupported on archetypes with disabled entities, enable them first or use per-entity removeComponent");const c=s.getEdge(r),h=s.length,l=h,u=this._entityArchetypes,d=this._entityRows;if(!o.materializesRows){const E=s.entityIds;for(let m=0;m<h;m++){const p=i.getEntityIndex(E[m]);u[p]=n,d[p]=i.UNASSIGNED}s.clearRows(),this._onArchShrink(s,l);return}const _=o.length,f=o.enabledCount,y=o.bulkMoveAllFrom(s,c.removeMap,this.changeTick);for(let E=0;E<h;E++){const m=i.getEntityIndex(o.entityIds[y+E]);u[m]=n,d[m]=y+E}this._onArchShrink(s,l),this._onArchGrow(o,_,f)}getEntityArchetype(e){return this._archGet(this._entityArchetypes[i.getEntityIndex(e)])}getEntityRow(e){return this._entityRows[i.getEntityIndex(e)]}resolvedRow=0;resolveEntity(e){const t=e&D;return this.resolvedRow=this._entityRows[t],this._archGet(this._entityArchetypes[t])}cursorBinder(e,t){const s=e.id,r=D;return(n,o)=>{const c=o&r,h=this._archGet(this._entityArchetypes[c]);{if(t?i.accessCheck.assertWrite(e):i.accessCheck.assertRead(e),!this.isAlive(o))throw i.entityNotAliveError("cursor.at",o,this.componentLabel(s));if(h.accessorColumns[s]===void 0)throw new i.ECSError(i.ECS_ERROR.COMPONENT_NOT_REGISTERED,`cursor.at: ${this.componentLabel(s)} has no columns in the archetype of entity ${String(o)}, the entity doesn't hold it, or it is a tag (no fields to point at)`,{component:s,entity:o})}t&&(h.changedTick[s]=this.changeTick,this.anyDirtyTracked&&this.noteSet(s,h,this._entityRows[c],o)),n.__cols=h.accessorColumns[s],n.__row=this._entityRows[c]}}componentFieldNames(e){return this._componentMetas[e.id].fieldNames}getMatchingArchetypes(e,t,s){return this._queries.matching(e,t,s)}registerQuery(e,t,s){return this._queries.register(e,t,s)}updateQueryRef(e,t){this._queries.updateRef(e,t)}get archetypeCount(){return this._archGraph.archetypes.length}_resources=new Yt}class fs{_store;constructor(e){this._store=e}register(e,t){i.dispatchTrace.isActive()&&i.dispatchTrace.recordResourceRegister(e.description??""),this._store.resources.register(e,t)}get(e){return i.accessCheck.assertResourceRead(e),i.dispatchTrace.isActive()&&i.dispatchTrace.recordResourceRead(e.description??""),i.unsafeCast(this._store.resources.get(e))}set(e,t){i.accessCheck.assertResourceWrite(e),i.dispatchTrace.isActive()&&i.dispatchTrace.recordResourceWrite(e.description??""),this._store.resources.set(e,t)}remove(e){i.accessCheck.assertResourceWrite(e),i.dispatchTrace.isActive()&&i.dispatchTrace.recordResourceRemove(e.description??""),this._store.resources.remove(e)}has(e){return this._store.resources.has(e)}}class gt{_store;constructor(e){this._store=e}get deterministic(){return this._store.deterministic}stateHash(){return this._store.stateHash()}}for(const a of["capture","restore","captureSparse","restoreSparse"])gt.prototype[a]=function(){throw i.pluginMissingError("snapshots",`ecs.snapshots.${a}`)};function ps(a){return Object.freeze({name:a})}function Es(a){return!("fn"in a)}function ys(a,e,t,s,r){if(a.length===0)return[];const n=[],o=new Map,c=new Set,h=new Map;for(const _ of a){n.push(_.descriptor),o.set(_.descriptor,_.insertionOrder),c.add(_.descriptor);for(let f=0;f<_.sets.length;f++){const y=_.sets[f];let E=h.get(y);E===void 0&&(E=[],h.set(y,E)),E.push(_.descriptor)}}const l=new Map;for(const _ of a)l.set(_.descriptor,[]);for(const _ of a){se(_.descriptor,_.before,"before",c,h,l,e,s,r),se(_.descriptor,_.after,"after",c,h,l,e,s,r);for(let f=0;f<_.sets.length;f++){const y=t.get(_.sets[f]);y!==void 0&&(se(_.descriptor,y.before,"before",c,h,l,e,s,r),se(_.descriptor,y.after,"after",c,h,l,e,s,r))}}const u=(_,f)=>o.get(_)-o.get(f),d=_=>_.name??`system_${_.id}`;try{return I.topologicalSort(n,l,u,d)}catch(_){throw _ instanceof TypeError?new i.ECSError(i.ECS_ERROR.CIRCULAR_SYSTEM_DEPENDENCY,`Circular system dependency detected in ${e}: ${_.message}`):_}}function se(a,e,t,s,r,n,o,c,h){for(const l of e){if(Es(l)){const u=r.get(l);if(u===void 0)continue;for(let d=0;d<u.length;d++){const _=u[d];_!==a&&je(a,_,t,n)}continue}if(!s.has(l)){gs(a,l,t,o,c,h);continue}je(a,l,t,n)}}function je(a,e,t,s){t==="before"?s.get(a).push(e):s.get(e).push(a)}function gs(a,e,t,s,r,n){if(r.has(e))return;const o=c=>c.name??`system_${c.id}`;n(`Schedule[${s}]: \`${o(a)}\` declares \`${t}\` ordering against \`${o(e)}\`, which is not registered in any phase, the constraint is ignored. Check for a typo or a missing addSystems() call.`)}class ms{constructor(e,t,s,r){this.owner=e,this.name=t,this.loop=s,this.insertionOrder=r}nodes=[];plan=null;before=[];after=[]}const $=Object.freeze([]);function fe(a){return a===void 0?$:Array.isArray(a)?a:[a]}function Re(a,e,t){a(e,t)}function ws(){const a=[function(){},function(){},function(){},function(){},function(){}];for(let t=0;t<500;t++)for(let s=0;s<a.length;s++)Re(a[s],null,0)}ws();class Rs{_phases=[];_builtins=new Map;_startupOrder=[];_fixedOrder=[];_updateOrder=[];_phaseBySystem=new Map;_lastRunTicks=[];_slotBySystem=new Map;_freeSlots=[];_driveDepth=0;_gatedSystems=new Map;_conditionsBySet=new Map;_orderingBySet=new Map;_nextInsertionOrder=0;_backend=null;_route=null;_onWarn;_fixedSystemCount=0;_nextPhaseOrder=0;constructor(e){this._onWarn=e??(h=>console.warn(h));const t=this._declarePhase(i.SCHEDULE.PRE_STARTUP,"startup"),s=this._declarePhase(i.SCHEDULE.STARTUP,"startup");s.after.push(t),this._declarePhase(i.SCHEDULE.POST_STARTUP,"startup").after.push(s),this._declarePhase(i.SCHEDULE.FIXED_UPDATE,"fixed");const n=this._declarePhase(i.SCHEDULE.PRE_UPDATE,"update"),o=this._declarePhase(i.SCHEDULE.UPDATE,"update");o.after.push(n),this._declarePhase(i.SCHEDULE.POST_UPDATE,"update").after.push(o);for(const h of this._phases)this._builtins.set(h.name,h);this._resolveOrder("startup"),this._resolveOrder("fixed"),this._resolveOrder("update")}addPhase(e,t){const s=this._declarePhase(e,t.loop);for(const r of t.before??$)s.before.push(this._checkPhase(r));for(const r of t.after??$)s.after.push(this._checkPhase(r));return this._resolveOrder(t.loop),s}_declarePhase(e,t){const s=new ms(this,e,t,this._nextPhaseOrder++);return this._phases.push(s),s}_checkPhase(e){return this._resolvePhase(e),e}_resolvePhase(e){if(typeof e=="string"){const s=this._builtins.get(e);if(s!==void 0)return s;throw new i.ECSError(i.ECS_ERROR.UNKNOWN_PHASE,`${e} is not a phase of this world. Pass a SCHEDULE member, or the handle addPhase returned`)}const t=e;if(t.owner!==this)throw new i.ECSError(i.ECS_ERROR.UNKNOWN_PHASE,`phase ${t.name} belongs to another world. Call addPhase on the world you are scheduling into`);return t}_resolveOrder(e){const t=[];for(let o=0;o<this._phases.length;o++)this._phases[o].loop===e&&t.push(this._phases[o]);const s=new Map;for(const o of t)s.set(o,[]);const r=new Set(t);for(const o of t){for(const c of o.before){const h=this._resolvePhase(c);h!==o&&r.has(h)&&s.get(o).push(h)}for(const c of o.after){const h=this._resolvePhase(c);h!==o&&r.has(h)&&s.get(h).push(o)}}let n;try{n=I.topologicalSort(t,s,(o,c)=>o.insertionOrder-c.insertionOrder,o=>o.name)}catch(o){throw o instanceof TypeError?new i.ECSError(i.ECS_ERROR.CIRCULAR_PHASE_DEPENDENCY,`the ${e} phases cannot be ordered: ${o.message}. Drop one before or after from addPhase`):o}e==="startup"?this._startupOrder=n:e==="fixed"?this._fixedOrder=n:this._updateOrder=n}addSystems(e,...t){const s=this._resolvePhase(e);for(const r of t){const n="system"in r,o=n?r.system:r,c=n?r.ordering:void 0,h=n?fe(r.runIf):$,l=n?fe(r.set):$;if(this._phaseBySystem.has(o))throw new i.ECSError(i.ECS_ERROR.DUPLICATE_SYSTEM,`System ${o.name??o.id} is already scheduled`);const u={descriptor:o,insertionOrder:this._nextInsertionOrder++,before:new Set(c?.before??[]),after:new Set(c?.after??[]),conditions:h,sets:l};s.nodes.push(u),s.loop==="fixed"&&this._fixedSystemCount++,this._phaseBySystem.set(o,s),this._assignLastRunSlot(o),(h.length>0||l.length>0)&&this._gatedSystems.set(o,u),s.plan=null}}configureSet(e,t){const s=fe(t.runIf);if(s.length>0){const r=this._conditionsBySet.get(e);r===void 0?this._conditionsBySet.set(e,[...s]):r.push(...s)}if(t.before!==void 0||t.after!==void 0){let r=this._orderingBySet.get(e);r===void 0&&(r={before:new Set,after:new Set},this._orderingBySet.set(e,r));for(const n of t.before??$)r.before.add(n);for(const n of t.after??$)r.after.add(n);this._invalidatePlans()}}removeSystem(e){const t=this._phaseBySystem.get(e);if(t===void 0)return;const s=t.nodes,r=s.findIndex(o=>o.descriptor===e);if(r!==-1){const o=s.length-1;r!==o&&(s[r]=s[o]),s.pop(),t.loop==="fixed"&&this._fixedSystemCount--;for(const c of s)c.before.delete(e),c.after.delete(e)}this._phaseBySystem.delete(e);const n=this._slotBySystem.get(e);n!==void 0&&(this._lastRunTicks[n]=0,this._slotBySystem.delete(e),this._freeSlots.push(n)),this._gatedSystems.delete(e),this._invalidatePlans()}_invalidatePlans(){for(let e=0;e<this._phases.length;e++)this._phases[e].plan=null}setBackend(e){this._backend=e}setRoute(e){this._route=e}runStartup(e){this._driveDepth++;try{const t=this._startupOrder;for(let s=0;s<t.length;s++)this._runPhase(t[s],e,i.STARTUP_DELTA_TIME)}finally{this._driveDepth--}}runUpdate(e,t){this._driveDepth++;try{const s=this._updateOrder;for(let r=0;r<s.length;r++)this._runPhase(s[r],e,t)}finally{this._driveDepth--}}runFixedUpdate(e,t){this._driveDepth++;try{const s=this._fixedOrder;for(let r=0;r<s.length;r++)this._runPhase(s[r],e,t)}finally{this._driveDepth--}}hasFixedSystems(){return this._fixedSystemCount>0}getAllSystems(){const e=[];for(const t of this._phases)for(const s of t.nodes)e.push(s.descriptor);return e}hasSystem(e){return this._phaseBySystem.has(e)}_assignLastRunSlot(e){let t=this._slotBySystem.get(e);if(t===void 0){const s=this._driveDepth===0?this._freeSlots.pop():void 0;s!==void 0?(t=s,this._lastRunTicks[t]=0):(t=this._lastRunTicks.length,this._lastRunTicks.push(0)),this._slotBySystem.set(e,t)}return t}clear(){for(const e of this._phases)e.nodes.length=0,e.plan=null;this._fixedSystemCount=0,this._phaseBySystem.clear(),this._driveDepth===0?this._lastRunTicks.length=0:this._lastRunTicks.fill(0),this._slotBySystem.clear(),this._freeSlots.length=0,this._gatedSystems.clear(),this._conditionsBySet.clear(),this._orderingBySet.clear()}_runPhase(e,t,s){const r=e.plan,n=r!==null?r:this._buildPlan(e),o=n.sorted,c=n.slots,h=this._gatedSystems.size>0,l=this._backend,u=this._route,d=l!==null||u!==null,_=l!==null?t.ecsTick:0,f=h?new Map:void 0;for(let y=0;y<o.length;y++){const E=o[y];if(h){const p=this._gatedSystems.get(E);if(p!==void 0&&!this._shouldRun(p,t,f))continue}t.lastRunTick=this._lastRunTicks[c[y]];const m=t.advanceChangeTick();i.accessCheck.enter(E),t.trace?.systemBegin(E,e.name);try{if(d){const p=u!==null?E.routePlan:void 0;if(!(p!==void 0&&u.run(p,t,s,m))){const g=l!==null?E.backendHandle:void 0;g!==void 0?(t.publishRowCounts(),l.run(g,s,_)):E.fn!==void 0&&Re(E.fn,t,s)}}else E.fn!==void 0&&Re(E.fn,t,s)}finally{t.trace?.systemEnd(E),i.accessCheck.leave()}this._lastRunTicks[c[y]]=m}t.advanceChangeTick(),t.trace?.flushBegin(e.name),t.flush(),t.trace?.flushEnd(e.name),t.trace?.phaseBoundary(e.name)}_shouldRun(e,t,s){if(e.conditions.length>0&&!this._evalConditions(e.conditions,t))return!1;for(let r=0;r<e.sets.length;r++){const n=e.sets[r];let o=s.get(n);if(o===void 0){const c=this._conditionsBySet.get(n);o=c===void 0||c.length===0?!0:this._evalConditions(c,t),s.set(n,o)}if(!o)return!1}return!0}_evalConditions(e,t){for(let s=0;s<e.length;s++){const r=e[s];i.accessCheck.enterCondition(r);let n;try{n=r.evaluate(t)}finally{i.accessCheck.leave()}if(!n)return!1}return!0}_buildPlan(e){const t=ys(e.nodes,e.name,this._orderingBySet,this._phaseBySystem,this._onWarn),s=new Int32Array(t.length);for(let n=0;n<t.length;n++)s[n]=this._assignLastRunSlot(t[n]);const r={sorted:t,slots:s};return e.plan=r,r}}const ze=Object.freeze([]),Ss=Object.freeze([]),Qe=Object.freeze([]),Cs=Object.freeze([]);function be(a){if(typeof a=="function"){const e=a.id;return t=>t.has(e)}return e=>a.matches(e)}function Ie(a){return typeof a=="function"?i.componentDebugName(a)??`component ${a.id}`:a.name}function vs(...a){const e=a.map(be);return{name:`and(${a.map(Ie).join(", ")})`,matches(s){for(let r=0;r<e.length;r++)if(!e[r](s))return!1;return!0}}}function Ts(...a){const e=a.map(be);return{name:`or(${a.map(Ie).join(", ")})`,matches(s){for(let r=0;r<e.length;r++)if(e[r](s))return!0;return!1}}}function As(...a){const e=a.map(be);return{name:`not(${a.map(Ie).join(", ")})`,matches(s){for(let r=0;r<e.length;r++)if(e[r](s))return!1;return!0}}}const Ke=Object.freeze({sparseIncludes:ze,sparseExcludes:ze,optionalTerms:Ss,includesDisabled:!1,relationIncludes:Qe,relationExcludes:Qe,hierarchyTerm:null,archetypeTerms:Cs});function Y(a,e){return Object.freeze({sparseIncludes:e.sparseIncludes??a.sparseIncludes,sparseExcludes:e.sparseExcludes??a.sparseExcludes,optionalTerms:e.optionalTerms??a.optionalTerms,includesDisabled:e.includesDisabled??a.includesDisabled,relationIncludes:e.relationIncludes??a.relationIncludes,relationExcludes:e.relationExcludes??a.relationExcludes,hierarchyTerm:e.hierarchyTerm!==void 0?e.hierarchyTerm:a.hierarchyTerm,archetypeTerms:e.archetypeTerms??a.archetypeTerms})}const oe=Number.POSITIVE_INFINITY,pe=65536;function z(a,e){if(a>=pe||e>=pe)throw new i.ECSError(i.ECS_ERROR.SPARSE_CACHE_KEY_OVERFLOW,`sparse query cache key would overflow, queryId=${a} and sparseId=${e} must each be < ${pe}`);return(a<<16|e)>>>0}function re(a,e){for(let t=0;t<a.length;t++)if(a[t]===e)return a;return[...a,e]}function Os(a,e){for(let t=0;t<a.length;t++)if(a[t]===e)return a;return[...a,e]}function Xe(a,e){for(let t=0;t<a.length;t++)if(a[t]===e)return a;return[...a,e]}class ke{arch;tick=0;since=0;resolver;mut(e){return this.arch.columnGroupMut(e,this.tick)}read(e){return this.arch.columnGroupRead(e)}ticks(e){const t=this.arch,s=e.id,r=t.rowTicks[s];if(r===void 0)throw Je("cols.ticks",e,s);return i.accessCheck.assertWrite(e),t.changedTick[s]=this.tick,this.resolver.noteScan(s),r}ticksRead(e){const t=this.arch,s=e.id,r=t.rowTicks[s];if(r===void 0)throw Je("cols.ticksRead",e,s);return i.accessCheck.assertRead(e),r}}function Je(a,e,t){return new i.ECSError(i.ECS_ERROR.ROW_TICKS_NOT_TRACKED,`${a}: ${i.componentLabel(e)} has no row ticks. Call ecs.trackRows(def), or register an onSet observer with granularity "entity", before the loop`,{component:t})}class F{_query;_changedIds;constructor(e,t){this._query=e,this._changedIds=t;for(let s=0;s<t.length;s++)if(!e.include.has(t[s]))throw new i.ECSError(i.ECS_ERROR.COMPONENT_NOT_REGISTERED,`changed() component ${t[s]} is not in the query's include mask. Require it with and() before changed()`)}and(...e){return new F(this._query.and(...e),this._changedIds)}not(...e){return new F(this._query.not(...e),this._changedIds)}or(...e){return new F(this._query.or(...e),this._changedIds)}optional(...e){return new F(this._query.optional(...e),this._changedIds)}forEach(e){if(this._query.includesDisabled){this._forEachIncludeDisabled(e);return}const t=this._query.lastRunTick(),s=this._query.nonEmptyArchs(),r=this._changedIds;{i.accessCheck.enterOptionalScope(this._query.terms.optionalTerms);try{for(let n=0;n<s.length;n++){const o=s[n];for(let c=0;c<r.length;c++)if(o.changedTick[r[c]]>t){o.iterDepth++;try{e(o)}finally{o.iterDepth--}break}}}finally{i.accessCheck.leaveOptionalScope()}return}}forEachChunk(e){if(this._query.includesDisabled){const t=x(!0);try{this._forEachChunkInner(e)}finally{x(t)}return}this._forEachChunkInner(e)}_forEachChunkInner(e){const t=this._query,s=new ke;s.tick=t.changeTick(),s.since=t.lastRunTick(),s.resolver=t.resolver();const r=s.since,n=t.nonEmptyArchs(),o=this._changedIds;{t.assertDenseOnly("changed().forEachChunk"),i.accessCheck.enterOptionalScope(t.terms.optionalTerms);try{for(let c=0;c<n.length;c++){const h=n[c];for(let l=0;l<o.length;l++)if(h.changedTick[o[l]]>r){s.arch=h,h.iterDepth++;try{e(s,h.entityCount)}finally{h.iterDepth--}break}}}finally{i.accessCheck.leaveOptionalScope()}return}}_forEachIncludeDisabled(e){const t=x(!0);try{this._forEachInner(e)}finally{x(t)}}_forEachInner(e){const t=this._query.lastRunTick(),s=this._query.nonEmptyArchs(),r=this._changedIds;{i.accessCheck.enterOptionalScope(this._query.terms.optionalTerms);try{for(let n=0;n<s.length;n++){const o=s[n];for(let c=0;c<r.length;c++)if(o.changedTick[r[c]]>t){o.iterDepth++;try{e(o)}finally{o.iterDepth--}break}}}finally{i.accessCheck.leaveOptionalScope()}return}}}class N{_archetypes;defs;_resolver;include;_exclude;_anyOf;_nonEmptyArchetypes=[];_lastSeenEpoch=-1;id;terms;includesDisabled;constructor(e,t,s,r,n,o,c,h=Ke){this._archetypes=e,this.defs=t,this._resolver=s,this.include=r,this._exclude=n,this._anyOf=o,this.id=c,this.terms=h,this.includesDisabled=h.includesDisabled}_assertDenseOnly(e){if(this.terms.sparseIncludes.length>0||this.terms.sparseExcludes.length>0||this.terms.relationIncludes.length>0||this.terms.relationExcludes.length>0||this.terms.hierarchyTerm!==null)throw new i.ECSError(i.ECS_ERROR.SPARSE_QUERY_DENSE_PATH,`Query.${e} walks the dense archetype list alone, and this query carries a term it cannot see: andSparse, notSparse, andRelation, notRelation or hierarchy. Iterate it with forEachEntity instead.`)}_assertNoArchetypeTerm(e){const t=this.terms.archetypeTerms;if(t.length!==0)throw new i.ECSError(i.ECS_ERROR.QUERY_TERM_DENSE_PATH,`Query.${e} answers from the dense archetype list, and this query carries the archetype term ${t[0].name}, which narrows that list. Read the matched archetypes with forEach instead.`)}_isDenseOnly(){return this.terms.sparseIncludes.length===0&&this.terms.sparseExcludes.length===0&&this.terms.relationIncludes.length===0&&this.terms.relationExcludes.length===0&&this.terms.hierarchyTerm===null}firstEntity(){if(this._isDenseOnly()){const t=this.nonEmptyArchs();for(let s=0;s<t.length;s++)if((this.includesDisabled?t[s].totalCount:t[s].enabledCount)>0)return t[s].entityIds[0];return}let e;return this.forEachEntity(t=>{e===void 0&&(e=t)}),e}singleEntity(){{const e=this._isDenseOnly()?this.entityCount:this._countViaWalk();if(e!==1)throw new i.ECSError(i.ECS_ERROR.QUERY_NOT_SINGLETON,`Query.singleEntity requires exactly 1 matching entity, found ${e}`,{count:e})}return this.firstEntity()}_countViaWalk(){let e=0;return this.forEachEntity(()=>{e++}),e}get archetypeCount(){return this._assertDenseOnly("archetypeCount"),this._assertNoArchetypeTerm("archetypeCount"),this._archetypes.length}get entityCount(){this._assertDenseOnly("entityCount");const e=this.nonEmptyArchs();let t=0;if(this.includesDisabled)for(let s=0;s<e.length;s++)t+=e[s].totalCount;else for(let s=0;s<e.length;s++)t+=e[s].enabledCount;return t}get excludeWords(){return this._assertNoArchetypeTerm("excludeWords"),this._exclude===null?null:this._exclude.words}get archetypes(){return this._assertNoArchetypeTerm("archetypes"),this._archetypes}_carryNondense(e){return this.terms===Ke?e:new N(e._archetypes,e.defs,this._resolver,e.include,e._exclude,e._anyOf,this._resolver.nextQueryId(),this.terms)}and(...e){if(e.length===1){const s=e[0].id,r=(this.id<<16|s)>>>0,n=this._resolver.caches.andSingle.get(r);return n!==void 0?n:this._andMiss(e[0],s,r)}let t=this;for(let s=0;s<e.length;s++)t=t.and(e[s]);return t}_andMiss(e,t,s){const r=this.include.copy(),n=this.defs.slice();r.has(t)||(r.set(t),n.push(e));const o=this._carryNondense(this._resolver.resolveQuery(r,this._exclude,this._anyOf,n));return this._resolver.caches.andSingle.set(s,o),o}not(...e){if(e.length===1){const s=e[0].id,r=(this.id<<16|s)>>>0,n=this._resolver.caches.notSingle.get(r);return n!==void 0?n:this._notMiss(s,r)}let t=this;for(let s=0;s<e.length;s++)t=t.not(e[s]);return t}_notMiss(e,t){const s=this._exclude?this._exclude.copy():new I.BitSet;s.set(e);const r=this._carryNondense(this._resolver.resolveQuery(this.include,s,this._anyOf,this.defs));return this._resolver.caches.notSingle.set(t,r),r}andSparse(...e){if(e.length===1)return this._andSparseOne(e[0]);let t=this;for(let s=0;s<e.length;s++)t=t._andSparseOne(e[s]);return t}_andSparseOne(e){const t=z(this.id,e),s=this._resolver.caches.andSparseSingle,r=s.get(t);if(r!==void 0)return r;const n=this._deriveSparse(re(this.terms.sparseIncludes,e),this.terms.sparseExcludes);return s.set(t,n),n}notSparse(...e){if(e.length===1)return this._notSparseOne(e[0]);let t=this;for(let s=0;s<e.length;s++)t=t._notSparseOne(e[s]);return t}_notSparseOne(e){const t=z(this.id,e),s=this._resolver.caches.notSparseSingle,r=s.get(t);if(r!==void 0)return r;const n=this._deriveSparse(this.terms.sparseIncludes,re(this.terms.sparseExcludes,e));return s.set(t,n),n}_deriveSparse(e,t){return new N(this._archetypes,this.defs,this._resolver,this.include,this._exclude,this._anyOf,this._resolver.nextQueryId(),Y(this.terms,{sparseIncludes:e,sparseExcludes:t}))}where(e){const t=this._resolver.caches.whereSingle;let s=t.get(e);s===void 0&&(s=new Map,t.set(e,s));const r=s.get(this.id);if(r!==void 0)return r;const n=new N(this._archetypes,this.defs,this._resolver,this.include,this._exclude,this._anyOf,this._resolver.nextQueryId(),Y(this.terms,{archetypeTerms:[...this.terms.archetypeTerms,e]}));return s.set(this.id,n),n}andRelation(...e){if(e.length===1)return this._andRelationOne(e[0]);let t=this;for(let s=0;s<e.length;s++)t=t._andRelationOne(e[s]);return t}_andRelationOne(e){const t=z(this.id,e),s=this._resolver.caches.andRelationSingle,r=s.get(t);if(r!==void 0)return r;const n=this._resolver.relationBackingSparseId(e,"query.andRelation"),o=this._deriveRelation(re(this.terms.sparseIncludes,n),this.terms.sparseExcludes,Xe(this.terms.relationIncludes,e),this.terms.relationExcludes);return s.set(t,o),o}notRelation(...e){if(e.length===1)return this._notRelationOne(e[0]);let t=this;for(let s=0;s<e.length;s++)t=t._notRelationOne(e[s]);return t}_notRelationOne(e){const t=z(this.id,e),s=this._resolver.caches.notRelationSingle,r=s.get(t);if(r!==void 0)return r;const n=this._resolver.relationBackingSparseId(e,"query.notRelation"),o=this._deriveRelation(this.terms.sparseIncludes,re(this.terms.sparseExcludes,n),this.terms.relationIncludes,Xe(this.terms.relationExcludes,e));return s.set(t,o),o}_deriveRelation(e,t,s,r){return new N(this._archetypes,this.defs,this._resolver,this.include,this._exclude,this._anyOf,this._resolver.nextQueryId(),Y(this.terms,{sparseIncludes:e,sparseExcludes:t,relationIncludes:s,relationExcludes:r}))}hierarchy(e,t=oe){{if(this.terms.hierarchyTerm!==null)throw new i.ECSError(i.ECS_ERROR.HIERARCHY_ALREADY_SET,"hierarchy() is already set on this query, a query carries a single depth ordering");if(t!==oe&&(!Number.isInteger(t)||t<0))throw new i.ECSError(i.ECS_ERROR.HIERARCHY_INVALID_MAX_DEPTH,`hierarchy() maxDepth must be HIERARCHY_UNBOUNDED or a non-negative integer, got ${t}`)}if(t===oe){const s=z(this.id,e),r=this._resolver.caches.hierarchySingle,n=r.get(s);if(n!==void 0)return n;const o=this._deriveHierarchy({relation:e,maxDepth:t});return r.set(s,o),o}return this._deriveHierarchy({relation:e,maxDepth:t})}_deriveHierarchy(e){return new N(this._archetypes,this.defs,this._resolver,this.include,this._exclude,this._anyOf,this._resolver.nextQueryId(),Y(this.terms,{hierarchyTerm:e}))}_assertRelationAccess(){for(let e=0;e<this.terms.relationIncludes.length;e++)i.accessCheck.assertRelationRead(this.terms.relationIncludes[e]);for(let e=0;e<this.terms.relationExcludes.length;e++)i.accessCheck.assertRelationRead(this.terms.relationExcludes[e])}forEachRelatedTo(e,t){i.accessCheck.assertRelationReadAny(),this._assertRelationAccess(),this._resolver.forEachTargetMatch(e,this.include,this._exclude,this._anyOf,this.terms,t)}optional(...e){if(e.length===1)return this._optionalOne(e[0].id);let t=this;for(let s=0;s<e.length;s++)t=t._optionalOne(e[s].id);return t}_optionalOne(e){const t=(this.id<<16|e)>>>0,s=this._resolver.caches.optionalSingle,r=s.get(t);if(r!==void 0)return r;const n=this._deriveOptional(Os(this.terms.optionalTerms,e));return s.set(t,n),n}_deriveOptional(e){return new N(this._archetypes,this.defs,this._resolver,this.include,this._exclude,this._anyOf,this._resolver.nextQueryId(),Y(this.terms,{optionalTerms:e}))}includeDisabled(){if(this.includesDisabled)return this;const e=this._resolver.caches.includeDisabledSingle,t=e.get(this.id);if(t!==void 0)return t;const s=new N(this._archetypes,this.defs,this._resolver,this.include,this._exclude,this._anyOf,this._resolver.nextQueryId(),Y(this.terms,{includesDisabled:!0}));return e.set(this.id,s),s}forEach(e){if(this.includesDisabled){this._forEachIncludeDisabled(e);return}{this._assertDenseOnly("forEach"),i.accessCheck.enterOptionalScope(this.terms.optionalTerms);try{const t=this.nonEmptyArchs();for(let s=0;s<t.length;s++){const r=t[s];r.iterDepth++;try{e(r)}finally{r.iterDepth--}}}finally{i.accessCheck.leaveOptionalScope()}return}}_forEachIncludeDisabled(e){const t=x(!0);try{this._forEachInner(e)}finally{x(t)}}forEachChunk(e){if(this.includesDisabled){const t=x(!0);try{this._forEachChunkInner(e)}finally{x(t)}return}this._forEachChunkInner(e)}_forEachChunkInner(e){const t=new ke;t.tick=this._resolver.getChangeTick(),t.since=this._resolver.getLastRunTick(),t.resolver=this._resolver;{this._assertDenseOnly("forEachChunk"),i.accessCheck.enterOptionalScope(this.terms.optionalTerms);try{const s=this.nonEmptyArchs();for(let r=0;r<s.length;r++){const n=s[r];t.arch=n,n.iterDepth++;try{e(t,n.entityCount)}finally{n.iterDepth--}}}finally{i.accessCheck.leaveOptionalScope()}return}}some(e){if(this.includesDisabled){const t=x(!0);try{return this._someInner(e)}finally{x(t)}}return this._someInner(e)}_someInner(e){{this._assertDenseOnly("some"),i.accessCheck.enterOptionalScope(this.terms.optionalTerms);try{const s=this.nonEmptyArchs();for(let r=0;r<s.length;r++){const n=s[r];n.iterDepth++;try{if(e(n))return!0}finally{n.iterDepth--}}return!1}finally{i.accessCheck.leaveOptionalScope()}}const t=this.nonEmptyArchs();for(let s=0;s<t.length;s++)if(e(t[s]))return!0;return!1}_forEachInner(e){{this._assertDenseOnly("forEach"),i.accessCheck.enterOptionalScope(this.terms.optionalTerms);try{const t=this.nonEmptyArchs();for(let s=0;s<t.length;s++){const r=t[s];r.iterDepth++;try{e(r)}finally{r.iterDepth--}}}finally{i.accessCheck.leaveOptionalScope()}return}}forEachEntity(e){if(this._assertRelationAccess(),this.terms.hierarchyTerm!==null){i.accessCheck.assertRelationRead(this.terms.hierarchyTerm.relation),this._resolver.forEachHierarchyMatch(this.include,this._exclude,this._anyOf,this.terms,this.nonEmptyArchs(),this.terms.hierarchyTerm.relation,this.terms.hierarchyTerm.maxDepth,e);return}this._resolver.forEachSparseMatch(this.include,this._exclude,this._anyOf,this.terms,this.nonEmptyArchs(),e)}nonEmptyArchs(){const e=this._resolver.getQueryDirtyEpoch();return this._lastSeenEpoch!==e&&this._rebuildNonEmpty(e),this._nonEmptyArchetypes}_rebuildNonEmpty(e){if(this.terms.archetypeTerms.length!==0){this._rebuildFiltered(e);return}const t=this._archetypes,s=[];if(this.includesDisabled)for(let r=0;r<t.length;r++)t[r].totalCount>0&&s.push(t[r]);else for(let r=0;r<t.length;r++)t[r].enabledCount>0&&s.push(t[r]);this._nonEmptyArchetypes=s,this._lastSeenEpoch=e}_rebuildFiltered(e){const t=this._archetypes,s=this.terms.archetypeTerms,r=this.includesDisabled,n=[];e:for(let o=0;o<t.length;o++){const c=t[o];if((r?c.totalCount:c.enabledCount)!==0){for(let h=0;h<s.length;h++)if(!s[h].matches(c.mask))continue e;n.push(c)}}this._nonEmptyArchetypes=n,this._lastSeenEpoch=e}or(...e){if(e.length===1){const s=e[0].id,r=(this.id<<16|s)>>>0,n=this._resolver.caches.orSingle.get(r);return n!==void 0?n:this._orMiss(s,r)}let t=this;for(let s=0;s<e.length;s++)t=t.or(e[s]);return t}_orMiss(e,t){const s=this._anyOf?this._anyOf.copy():new I.BitSet;s.set(e);const r=this._carryNondense(this._resolver.resolveQuery(this.include,this._exclude,s,this.defs));return this._resolver.caches.orSingle.set(t,r),r}changed(...e){if(e.length===1){const s=e[0].id,r=(this.id<<16|s)>>>0,n=this._resolver.caches.changedSingle.get(r);return n!==void 0?n:this._changedMiss(s,r)}const t=new Array(e.length);for(let s=0;s<e.length;s++)t[s]=e[s].id;return new F(this,t)}_changedMiss(e,t){const s=new F(this,[e]);return this._resolver.caches.changedSingle.set(t,s),s}lastRunTick(){return this._resolver.getLastRunTick()}changeTick(){return this._resolver.getChangeTick()}resolver(){return this._resolver}assertDenseOnly(e){this._assertDenseOnly(e)}}class mt{constructor(e){this._resolver=e}and(...e){const t=new I.BitSet;for(let s=0;s<e.length;s++)t.set(e[s].id);return this._resolver.resolveQuery(t,null,null,e)}}class bs{_dedup=new Map;andSingle=new Map;notSingle=new Map;orSingle=new Map;changedSingle=new Map;optionalSingle=new Map;andSparseSingle=new Map;notSparseSingle=new Map;andRelationSingle=new Map;notRelationSingle=new Map;includeDisabledSingle=new Map;hierarchySingle=new Map;whereSingle=new WeakMap;findDedup(e,t,s,r){const n=this._dedup.get(e);if(n)for(let o=0;o<n.length;o++){const c=n[o];if(!(!c.includeMask.equals(t)||!(s===null?c.excludeMask===null:c.excludeMask!==null&&c.excludeMask.equals(s))||!(r===null?c.anyOfMask===null:c.anyOfMask!==null&&c.anyOfMask.equals(r))))return c}}addDedup(e,t){_t(this._dedup,e,t)}}class wt{constructor(e){this._store=e}spawn(...e){const t=this._store.createEntity();this._store.trace?.commandQueued("spawn",t,null);for(let s=0;s<e.length;s++){const r=W(e[s]);i.accessCheck.assertAdd(r),this._store.addComponentDeferred(t,r,V(e[s])),this._store.trace?.commandQueued("add",t,r.id)}return t}add(e,...t){if(t.length===2&&typeof t[0]=="function"&&t[1]!==null&&typeof t[1]=="object"&&typeof t[1].def!="function"){const s=t[0];return i.accessCheck.assertAdd(s),this._store.addComponentDeferred(e,s,t[1]),this._store.trace?.commandQueued("add",e,s.id),this}for(let s=0;s<t.length;s++){const r=t[s],n=W(r);i.accessCheck.assertAdd(n),this._store.addComponentDeferred(e,n,V(r)),this._store.trace?.commandQueued("add",e,n.id)}return this}remove(e,t){return i.accessCheck.assertRemove(t),this._store.removeComponentDeferred(e,t),this._store.trace?.commandQueued("remove",e,t.id),this}despawn(e){i.accessCheck.assertDespawn();const t=e;return this._store.destroyEntityDeferred(t),this._store.trace?.commandQueued("despawn",t,null),this}disable(e){return this._store.disableEntityDeferred(e),this._store.trace?.commandQueued("disable",e,null),this}enable(e){return this._store.enableEntityDeferred(e),this._store.trace?.commandQueued("enable",e,null),this}}class Rt{constructor(e){this._store=e,this.commands=new wt(e)}lastRunTick=0;commands;get ecsTick(){return this._store.tick}advanceChangeTick(){return this._store.advanceChangeTick()}publishRowCounts(){this._store.publishRowCounts()}get trace(){return this._store.trace}isAlive(e){return this._store.isAlive(e)}hasComponent(e,t){return this._store.hasComponent(e,t)}getField(e,t,s){if(i.accessCheck.assertRead(t),!this._store.isAlive(e))throw i.entityNotAliveError("ctx.getField",e,i.componentLabel(t));const r=this._store.resolveEntity(e),n=this._store.resolvedRow;return r.readField(n,t.id,s)}tryGetField(e,t,s){if(i.accessCheck.assertRead(t),!this._store.hasComponent(e,t))return;const r=this._store.resolveEntity(e),n=this._store.resolvedRow;return r.readField(n,t.id,s)}setField(e,t,s,r){if(!this._store.isAlive(e))throw i.entityNotAliveError("ctx.setField",e,i.componentLabel(t));const n=this._store.resolveEntity(e),o=this._store.resolvedRow,c=n.getColumnMut(t,s,this._store.changeTick);c[o]=r,this._store.anyDirtyTracked&&this._store.noteSet(t.id,n,o,e)}updateField(e,t,s,r){if(i.accessCheck.assertRead(t),!this._store.isAlive(e))throw i.entityNotAliveError("ctx.updateField",e,i.componentLabel(t));const n=this._store.resolveEntity(e),o=this._store.resolvedRow,c=r(n.readField(o,t.id,s)),h=n.getColumnMut(t,s,this._store.changeTick);return h[o]=c,this._store.anyDirtyTracked&&this._store.noteSet(t.id,n,o,e),c}markChanged(e,t){this._store.anyDirtyTracked&&this._store.noteSetEntity(t,e)}ref(e,t){if(i.accessCheck.assertWrite(e),!this._store.isAlive(t))throw i.entityNotAliveError("ctx.ref",t,i.componentLabel(e));const s=this._store.resolveEntity(t),r=this._store.resolvedRow;if(s.accessorColumns[e.id]===void 0)throw new i.ECSError(i.ECS_ERROR.COMPONENT_NOT_REGISTERED,`ctx.ref: ${i.componentLabel(e)} has no columns in this archetype, the entity doesn't hold it, or it is a tag (no fields to ref)`,{component:e.id,entity:t});return s.changedTick[e.id]=this._store.changeTick,this._store.anyDirtyTracked&&this._store.noteSet(e.id,s,r,t),ye(s.accessorColumns[e.id],r)}refRead(e,t){if(i.accessCheck.assertRead(e),!this._store.isAlive(t))throw i.entityNotAliveError("ctx.refRead",t,i.componentLabel(e));const s=this._store.resolveEntity(t),r=this._store.resolvedRow;if(s.accessorColumns[e.id]===void 0)throw new i.ECSError(i.ECS_ERROR.COMPONENT_NOT_REGISTERED,`ctx.refRead: ${i.componentLabel(e)} has no columns in this archetype, the entity doesn't hold it, or it is a tag (no fields to ref)`,{component:e.id,entity:t});return ye(s.accessorColumns[e.id],r)}cursor(e){return i.accessCheck.assertWrite(e),ce(this._store.componentFieldNames(e),this._store.cursorBinder(e,!0))}cursorRead(e){return i.accessCheck.assertRead(e),ce(this._store.componentFieldNames(e),this._store.cursorBinder(e,!1))}isDisabled(e){return this._store.isDisabled(e)}addSparse(e,t,...s){return i.accessCheck.assertSparseWrite(t),this._store.addSparse(e,t,s[0]),this}removeSparse(e,t){return i.accessCheck.assertSparseWrite(t),this._store.removeSparse(e,t),this}hasSparse(e,t){return this._store.hasSparse(e,t)}getSparseField(e,t,s){return i.accessCheck.assertSparseRead(t),this._store.getSparseField(e,t,s)}setSparseField(e,t,s,r){i.accessCheck.assertSparseWrite(t),this._store.setSparseField(e,t,s,r)}sparseCursor(e){return i.accessCheck.assertSparseWrite(e),he(this._store.sparseFieldNames(e),this._store.sparseAccessorColumns(e),this._store.sparseCursorCheck(e,!0),this._store.sparseTickPlane(e),this._store)}sparseChanged(e,t){return i.accessCheck.assertSparseRead(e),this._store.sparseTickOf(e,t)>this.lastRunTick}sparseCursorRead(e){return i.accessCheck.assertSparseRead(e),he(this._store.sparseFieldNames(e),this._store.sparseAccessorColumns(e),this._store.sparseCursorCheck(e,!1))}addRelation(e,t,s){return i.accessCheck.assertRelationWrite(t),this._store.requireRelations("ctx.addRelation").addRelation(e,t,s),this}removeRelation(e,t,s){return i.accessCheck.assertRelationWrite(t),this._store.requireRelations("ctx.removeRelation").removeRelation(e,t,s),this}targetOf(e,t){return i.accessCheck.assertRelationRead(t),this._store.requireRelations("ctx.targetOf").targetOf(e,t)}targetsOf(e,t){return i.accessCheck.assertRelationRead(t),this._store.requireRelations("ctx.targetsOf").targetsOf(e,t)}sourcesOf(e,t){return i.accessCheck.assertRelationRead(t),this._store.requireRelations("ctx.sourcesOf").sourcesOf(e,t)}hasRelation(e,t){return this._store.requireRelations("ctx.hasRelation").hasRelation(e,t)}flush(){this._store.flushStructural(),this._store.flushDestroys(),this._store.publishRowCounts()}emit(e,t){i.dispatchTrace.isActive()&&i.dispatchTrace.recordEventEmit(e.description??""),this._store.trace?.eventEmitted(e.description??"");const s=this._store.requireEvents("ctx.emit"),r=s.defByKey(e);t===void 0?s.emitSignal(r):s.emit(r,t)}readEvents(e){i.dispatchTrace.isActive()&&i.dispatchTrace.recordEventRead(e.description??"");const t=this._store.requireEvents("ctx.readEvents"),s=t.defByKey(e),r=t.reader(s);return this._store.trace?.eventRead(e.description??"",r.length),r}getResource(e){return i.accessCheck.assertResourceRead(e),i.dispatchTrace.isActive()&&i.dispatchTrace.recordResourceRead(e.description??""),i.unsafeCast(this._store.resources.get(e))}setResource(e,t){i.accessCheck.assertResourceWrite(e),i.dispatchTrace.isActive()&&i.dispatchTrace.recordResourceWrite(e.description??""),this._store.resources.set(e,t)}removeResource(e){i.accessCheck.assertResourceWrite(e),i.dispatchTrace.isActive()&&i.dispatchTrace.recordResourceRemove(e.description??""),this._store.resources.remove(e)}hasResource(e){return this._store.resources.has(e)}}const Is=a=>{if(!(Number.isInteger(a)&&a>=0))throw new i.ECSError(i.ECS_ERROR.INVALID_SYSTEM_ID,`system id must be an integer >= 0, got ${a}`);return i.unsafeCast(a)},Q=Object.freeze([]);function Ze(a){return typeof a=="object"&&!Array.isArray(a)}function ks(a){let e=Q;a.spawns!==void 0&&a.spawns.length>0&&(e=a.spawns.map(s=>Ze(s)?s.defs:s));let t=Q;if(a.despawns!==void 0&&a.despawns.length>0){const s=[];for(const r of a.despawns)Ze(r)?s.push(...r.defs):s.push(r);t=s}return{reads:a.reads,writes:a.writes,spawns:e,despawns:t,transitions:a.transitions??Q,resourceReads:a.resourceReads??Q,resourceWrites:a.resourceWrites??Q,sparseReads:a.sparseReads,sparseWrites:a.sparseWrites,relationReads:a.relationReads,relationWrites:a.relationWrites}}function Ds(a){const e=a.queries;if(e===void 0||a.exclusive===!0)return;const t=new Set;for(const n of a.reads)t.add(n.id);for(const n of a.writes)t.add(n.id);const s=new Set;for(const n of e)for(const o of n)t.has(o.id)||s.add(o.id);if(s.size===0)return;const r=a.name!==void 0?`'${a.name}' `:"";throw new i.ECSError(i.ECS_ERROR.QUERY_ACCESS_UNDECLARED,`system ${r}declares queries over component id(s) [${[...s].join(", ")}] not in reads ∪ writes. A query term reads each listed component, so add the id(s) to 'reads' (or to 'writes' if the system also mutates them).`)}const St=Object.freeze({reads:Object.freeze([]),writes:Object.freeze([]),spawns:Object.freeze([]),despawns:Object.freeze([]),transitions:Object.freeze([]),resourceReads:Object.freeze([]),resourceWrites:Object.freeze([]),sparseReads:Object.freeze([]),sparseWrites:Object.freeze([]),relationReads:Object.freeze([]),relationWrites:Object.freeze([])});function Ns(a){if(a.length>=3)throw new i.ECSError(i.ECS_ERROR.SYSTEM_FN_ARITY,`registerSystem got a ${a.length}-parameter function with no query builder. A bare system function is (ctx, dt), and a query system is (q, ctx, dt) with the query builder as the second argument, as in registerSystem((q, ctx, dt) => …, (qb) => qb.and(…)). Without it, q would receive the SystemContext and dt would be undefined.`);return{...St,fn:a}}function xs(a){if(a.fn===void 0&&a.backendHandle===void 0)throw new i.ECSError(i.ECS_ERROR.SYSTEM_FN_ARITY,`registerSystem: config${a.name?` '${a.name}'`:""} has neither 'fn' nor 'backendHandle'. Provide a system body, or a backend handle for backend execution`)}function Ms(a,e,t){return Object.freeze({...a,...ks(a),routePlan:e,id:Is(t)})}const et=new Set(["fixedTimestep","maxFixedSteps","onWarn","memory","regions","bindingsRegionBytes","deterministic","plugins"]);function tt(a){if(!(a>0)||!Number.isFinite(a))throw new i.ECSError(i.ECS_ERROR.INVALID_FIXED_TIMESTEP,`fixedTimestep must be a finite number > 0, got ${a}`);return a}function Fs(a){if(!Number.isInteger(a)||a<1)throw new i.ECSError(i.ECS_ERROR.INVALID_MAX_FIXED_STEPS,`maxFixedSteps must be an integer >= 1, got ${a}`);return a}function st(a,e){if(typeof a=="object"&&a!==null&&typeof a.archetypeId=="number")return;const t=typeof a=="function",s=typeof a=="object"&&a!==null&&"values"in a,r=t?"a component definition":s?"a bundle":Array.isArray(a)?"an array":`a ${typeof a}`,n=t||s?"Use `ecs.spawnBundle(...)` for components with no template, or build a template first with `ecs.template(Pos({ x: 0 }), Vel)`.":Array.isArray(a)?"`ecs.template` takes callable bundles, not an array of entries. Write `ecs.template(Pos({ x: 0 }), Vel)`.":"Build the template with `ecs.template(...)` first.";throw new i.ECSError(i.ECS_ERROR.INVALID_TEMPLATE,`${e}: expected a template from ecs.template(...), but got ${r}. ${n}`,{op:e,got:r})}function Ps(a){const e=new Map,t=[],s=c=>{const h=c.hash(),l=e.get(h);if(l!==void 0){for(let u=0;u<l.length;u++)if(l[u].equals(c))return;l.push(c)}else e.set(h,[c]);t.push(c)},r=c=>{const h=new I.BitSet;for(let l=0;l<c.length;l++)h.set(c[l].id);return h},n=[];for(const c of a){const h=c.transitions;for(let l=0;l<h.length;l++){const u=h[l];n.push({whenHas:r(u.whenHas),add:u.add,remove:u.remove})}}for(const c of a){const h=c.spawns;for(let l=0;l<h.length;l++)s(r(h[l]))}for(;t.length>0;){const c=t.pop();for(let h=0;h<n.length;h++){const l=n[h];if(!c.contains(l.whenHas))continue;const u=c.copy();if(l.add!==void 0)for(let d=0;d<l.add.length;d++)u.set(l.add[d].id);if(l.remove!==void 0)for(let d=0;d<l.remove.length;d++)u.clear(l.remove[d].id);s(u)}}const o=[];for(const c of e.values())for(let h=0;h<c.length;h++)o.push(c[h]);return o}function De(a){return Object.freeze(new Proxy(Object.freeze({}),{get(e,t){if(typeof t=="symbol"||t in Object.prototype||t==="toJSON"||t==="then")return Reflect.get(Object.prototype,t);throw i.pluginMissingError(a,`ecs.${a}.${t}`)}}))}const Bs=De("relations"),Ls=De("events"),Gs=De("workers"),$s=["relations","events","observe","snapshots","workers"];function Us(){throw i.pluginMissingError("observers","ecs.observe")}function Hs(a,e,t){const s=Object.keys(t);for(let r=0;r<s.length;r++){const n=s[r];if(!($s.indexOf(n)>=0)&&n in a)throw new i.ECSError(i.ECS_ERROR.PLUGIN_SURFACE_COLLISION,`the ${e} plugin contributes ${n}, and the world already carries that member. Rename the member the plugin adds`,{plugin:e,key:n})}}class Ne{static create(e){const t=new Ne(e),s=e?.plugins;if(s!==void 0){const r=new Set;for(let n=0;n<s.length;n++){const o=s[n],c=o.requires;if(c!==void 0){for(let l=0;l<c.length;l++)if(!r.has(c[l]))throw i.pluginMissingError(c[l],`${o.name} plugin`)}if(r.has(o.name))throw i.pluginInstalledTwiceError(o.name);r.add(o.name);const h=o.install(t._pluginHost());Hs(t,o.name,h),Object.assign(t,h)}}return t}_pluginHost(){return{store:this._store,changes:this._store,world:this,context:this._ctx,onSettle:e=>{this._settleHooks.push(e)},onPrewarm:e=>{this._prewarmSources.push(e)},onDispose:e=>{this._disposeHooks.push(e)},memory:this._pluginMemory(),installRoute:e=>{if(this._routePlanner!==null)throw i.pluginInstalledTwiceError("route");this._routePlanner=e;const t=this._schedule;return{route:s=>t.setRoute(s)}}}}_pluginMemory(){const e=this._memory,t=this._store;return{get backing(){if(e.wasmMemory!==null)return e.wasmMemory;const s=t.columnStore.buffer;return typeof SharedArrayBuffer<"u"&&s instanceof SharedArrayBuffer?s:null},backingSource:e.source,storeBase:e.storeBase}}_store;_schedule;_ctx;_prewarmSources=[];_disposeHooks=[];_settleHooks=[];resources;snapshots;_systems=new Set;_nextSystemId=0;_tick=0;_updating=!1;_fixedTimestep;_accumulator=0;_maxFixedSteps;_scratchMask=new I.BitSet;_nextQueryIdCounter=0;caches=new bs;_layoutSubscribers=[];_backend=null;_routePlanner=null;_memory;get memoryPlan(){return this._memory}get wasmMemory(){return this._memory.wasmMemory}constructor(e){const t=Object.prototype.hasOwnProperty;if(e!==void 0&&(t.call(e,"initial_capacity")||t.call(e,"buffer_allocator")))throw new i.ECSError(i.ECS_ERROR.INVALID_MEMORY_OPTIONS,"ECSOptions.initial_capacity and buffer_allocator were replaced by ECSOptions.memory. Pass initial_capacity as memory.columnCapacity (or memory.budget), and buffer_allocator as memory.wasm (WASM-backed) or memory.allocator (custom in-place)");if(e!==void 0)for(const n of Object.keys(e))et.has(n)||(e.onWarn??console.warn)(`ECSOptions: unknown option '${n}' ignored, known options: ${[...et].join(", ")}`);const s=i.resolveECSMemory(e?.memory);this._memory=s,this._store=new _s({initialCapacity:s.columnCapacity,bufferAllocator:s.allocator,entityIndexCapacity:s.entityIndexCapacity,capContext:{capBytes:s.capBytes,intentLabel:s.intentLabel,budgetEntities:s.budgetEntities},storeBase:s.storeBase,onBufferReplaced:()=>{const n=this._layoutSubscribers;for(let o=0;o<n.length;o++)n[o].setLayout(s.storeBase)},regions:e?.regions,bindingsRegionBytes:e?.bindingsRegionBytes,deterministic:e?.deterministic}),this._schedule=new Rs(e?.onWarn),this.resources=new fs(this._store),this.snapshots=new gt(this._store);const r=this;r.relations=Bs,r.events=Ls,r.observe=Us,r.workers=Gs,this._ctx=new Rt(this._store),this._fixedTimestep=tt(e?.fixedTimestep??i.DEFAULT_FIXED_TIMESTEP),this._maxFixedSteps=Fs(e?.maxFixedSteps??i.DEFAULT_MAX_FIXED_STEPS)}regionHandles(...e){const t=new Array(e.length);let s=null;for(let r=0;r<e.length;r++){const n=this._store.regionHandle(e[r]);n===null?(s??=[]).push(e[r]):t[r]=n}if(s!==null)throw new i.ECSError(i.ECS_ERROR.REGION_NOT_DECLARED,`regionHandles: region ids [${s.join(", ")}] are not declared. Pass them in ECSOptions.regions`);return t}subscribeLayout(e){return this._layoutSubscribers.push(e),e.setLayout(this._memory.storeBase),()=>{const t=this._layoutSubscribers.indexOf(e);t>=0&&this._layoutSubscribers.splice(t,1)}}attachBackend(e){if(this._backend!==null)throw new i.ECSError(i.ECS_ERROR.BACKEND_ALREADY_ATTACHED,"a ComputeBackend is already attached to this world. Detach it before attaching another, because a world holds one backend");this._backend=e,this._schedule.setBackend(e);const t=this.subscribeLayout(e);return()=>{t(),this._backend===e&&(this._backend=null,this._schedule.setBackend(null))}}get fixedTimestep(){return this._fixedTimestep}set fixedTimestep(e){this._fixedTimestep=tt(e)}get fixedAlpha(){return this._accumulator/this._fixedTimestep}setTrace(e){this._store.trace=e}registerComponent(e,t,s){if(Array.isArray(e)){const n=typeof t=="string"?t:"f64",o=Object.create(null);for(const c of e)o[c]=n;return this._store.registerComponent(o,s?.name)}const r=typeof t=="object"?t:s;return this._store.registerComponent(e,r?.name)}registerSparseComponent(e,t,s){if(Array.isArray(e)){const n=typeof t=="string"?t:"f64",o=Object.create(null);for(const c of e)o[c]=n;return this._store.registerSparseComponent(o,s?.name)}const r=typeof t=="object"?t:s;return this._store.registerSparseComponent(e,r?.name)}spawn(e,t){return this._assertOutsideSystem("spawn","ctx.commands.spawn (deferred to the phase flush)"),e!==void 0&&st(e,"spawn"),e===void 0?this._store.createEntity():this._store.spawn(e,t)}spawnBundle(...e){this._assertOutsideSystem("spawnBundle","ctx.commands.spawn (deferred to the phase flush)");const t=this._store.createEntity();for(let s=0;s<e.length;s++){const r=e[s],n=W(r);i.accessCheck.assertAdd(n),this._store.addComponent(t,n,V(r))}return t}spawnMany(e,t,s){return this._assertOutsideSystem("spawnMany","ctx.commands.spawn (deferred to the phase flush)"),st(e,"spawnMany"),this._store.spawnMany(e,t,s)}_assertOutsideSystem(e,t){if(this._updating&&i.accessCheck.current()!==null){const s=i.accessCheck.current(),r=s.name??`system_${s.id}`;throw new i.ECSError(i.ECS_ERROR.ACCESS_UNDECLARED,`ecs.${e} was called from inside system '${r}'. The host ${e} is immediate, unsafe mid-iteration, and invisible to observers. Use ${t} instead`,{op:e})}}despawn(e){return this._assertOutsideSystem("despawn","ctx.commands.despawn (deferred to the phase flush)"),this._store.destroyEntity(e),this}disable(e){return this._assertOutsideSystem("disable","ctx.commands.disable (deferred to the phase flush)"),this._store.disableEntity(e),this}enable(e){return this._assertOutsideSystem("enable","ctx.commands.enable (deferred to the phase flush)"),this._store.enableEntity(e),this}addComponent(e,t,s){const r=W(t);return this._assertOutsideSystem("addComponent","ctx.commands.add (deferred to the phase flush)"),i.accessCheck.assertAdd(r),this._store.addComponent(e,r,s??V(t)),this}addComponents(e,...t){const s=[];for(let r=0;r<t.length;r++){const n=t[r];s.push({def:W(n),values:V(n)})}{this._assertOutsideSystem("addComponents","ctx.commands.add (deferred to the phase flush)");for(let r=0;r<s.length;r++)i.accessCheck.assertAdd(s[r].def)}return this._store.addComponents(e,s),this}removeComponent(e,t){return this._assertOutsideSystem("removeComponent","ctx.commands.remove (deferred to the phase flush)"),i.accessCheck.assertRemove(t),this._store.removeComponent(e,t),this}removeComponents(e,...t){{this._assertOutsideSystem("removeComponents","ctx.commands.remove (deferred to the phase flush)");for(let s=0;s<t.length;s++)i.accessCheck.assertRemove(t[s])}return this._store.removeComponents(e,t),this}batchAddComponent(e,t,s){return this._assertOutsideSystem("batchAddComponent","ctx.commands.add per entity, or the batch after update() returns"),i.accessCheck.assertAdd(t),this._store.batchAddComponent(e,t,s),this}batchRemoveComponent(e,t){return this._assertOutsideSystem("batchRemoveComponent","ctx.commands.remove per entity, or the batch after update() returns"),i.accessCheck.assertRemove(t),this._store.batchRemoveComponent(e,t),this}getField(e,t,s){if(i.accessCheck.assertRead(t),!this._store.isAlive(e))throw i.entityNotAliveError("getField",e,i.componentLabel(t));return this._store.resolveEntity(e).readField(this._store.resolvedRow,t.id,s)}refRead(e,t){if(i.accessCheck.assertRead(e),!this._store.isAlive(t))throw i.entityNotAliveError("refRead",t,i.componentLabel(e));const s=this._store.resolveEntity(t),r=this._store.resolvedRow;if(s.accessorColumns[e.id]===void 0)throw new i.ECSError(i.ECS_ERROR.COMPONENT_NOT_REGISTERED,`refRead: ${i.componentLabel(e)} has no columns in this archetype, the entity doesn't hold it, or it is a tag (no fields to ref)`,{component:e.id,entity:t});return ye(s.accessorColumns[e.id],r)}cursor(e){return i.accessCheck.assertWrite(e),ce(this._store.componentFieldNames(e),this._store.cursorBinder(e,!0))}cursorRead(e){return i.accessCheck.assertRead(e),ce(this._store.componentFieldNames(e),this._store.cursorBinder(e,!1))}sparseCursor(e){return i.accessCheck.assertSparseWrite(e),he(this._store.sparseFieldNames(e),this._store.sparseAccessorColumns(e),this._store.sparseCursorCheck(e,!0),this._store.sparseTickPlane(e),this._store)}sparseCursorRead(e){return i.accessCheck.assertSparseRead(e),he(this._store.sparseFieldNames(e),this._store.sparseAccessorColumns(e),this._store.sparseCursorCheck(e,!1))}tryGetField(e,t,s){return i.accessCheck.assertRead(t),this._store.hasComponent(e,t)?this._store.resolveEntity(e).readField(this._store.resolvedRow,t.id,s):void 0}setField(e,t,s,r){if(!this._store.isAlive(e))throw i.entityNotAliveError("setField",e,i.componentLabel(t));const n=this._store.resolveEntity(e),o=this._store.resolvedRow,c=n.getColumnMut(t,s,this._store.changeTick);c[o]=r,this._store.anyDirtyTracked&&this._store.noteSet(t.id,n,o,e)}updateField(e,t,s,r){const n=r(this.getField(e,t,s));return this.setField(e,t,s,n),n}query(...e){const t=this._scratchMask;t.words.fill(0);for(let s=0;s<e.length;s++)t.set(e[s].id);return this.resolveQuery(t,null,null,e)}nextQueryId(){return this._nextQueryIdCounter++}resolveQuery(e,t,s,r){const n=e.hash(),o=t?t.hash():0,c=s?s.hash():0,h=n^Math.imul(o,i.HASH_GOLDEN_RATIO)^Math.imul(c,i.HASH_SECONDARY_PRIME)|0,l=this.caches.findDedup(h,e,t,s);if(l!==void 0)return l.query;const u=this._store.registerQuery(e,t??void 0,s??void 0),d=new N(u,r,this,e.copy(),t?.copy()??null,s?.copy()??null,this._nextQueryIdCounter++);return this._store.updateQueryRef(u,d),this.caches.addDedup(h,{includeMask:e.copy(),excludeMask:t?.copy()??null,anyOfMask:s?.copy()??null,query:d}),d}registerSystem(e,t){let s;if(typeof e=="function")if(t!==void 0){const c=t(new mt(this)),h=this._ctx,l=e;s={...St,fn:(u,d)=>l(c,h,d)}}else s=Ns(e);else s=e;Ds(s),xs(s);const r=this._routePlanner,n=r===null?void 0:r.plan(s),o=Ms(s,n,this._nextSystemId++);return this._systems.add(o),o}removeSystem(e){return this._schedule.removeSystem(e),e.onRemoved?.(),this._systems.delete(e),this}get systemCount(){return this._systems.size}startup(){this._prewarmArchetypes(),this._updating=!0;try{for(const e of this._systems.values())if(e.onAdded!==void 0){P&&i.accessCheck.enter(e);try{e.onAdded(this._ctx)}finally{P&&i.accessCheck.leave()}}this._schedule.runStartup(this._ctx)}finally{this._updating=!1}this._store.hasEvents&&this._store.events.clear()}_prewarmArchetypes(){const e=this._prewarmSources,t=[];for(let r=0;r<e.length;r++)t.push(...e[r]());const s=Ps([...this._systems,...t]);s.length!==0&&this._store.archCreateManyFromMasks(s)}update(e){const t=i.accessCheck.current();try{if(P&&(this._updating=!0),this._store.tick=this._tick,P&&this._store.trace?.tickBegin(this._tick,e),this._store.publishRowCounts(),this._schedule.hasFixedSystems()){this._accumulator+=e;const o=this._maxFixedSteps*this._fixedTimestep;for(this._accumulator>o&&(this._accumulator=o);this._accumulator>=this._fixedTimestep;)this._schedule.runFixedUpdate(this._ctx,this._fixedTimestep),this._accumulator-=this._fixedTimestep}this._schedule.runUpdate(this._ctx,e);const s=P&&this._store.hasEvents?this._store.events.devBufferedCount():0,r=this._store.advanceChangeTick(),n=this._settleHooks;for(let o=0;o<n.length;o++)n[o](r);if(P&&this._store.hasEvents&&this._store.events.devBufferedCount()!==s)throw new i.ECSError(i.ECS_ERROR.OBSERVER_ONSET_EMIT,"an onSet observer emitted an event. onSet runs at the tick tail, and events.clear() drops what it emits. Emit from a system instead");this._store.hasEvents&&this._store.events.clear(),P&&this._store.trace?.tickEnd(this._tick),this._tick++,this._store.advanceChangeTick()}finally{this._updating=!1,t!==null&&i.accessCheck.enter(t)}}dispose(){const e=this._disposeHooks;for(let t=0;t<e.length;t++)e[t]();for(const t of this._systems.values())t.dispose?.(),t.onRemoved?.();this._systems.clear(),this._schedule.clear()}template(...e){if(e.length===1&&Array.isArray(e[0]))throw new i.ECSError(i.ECS_ERROR.INVALID_TEMPLATE,"template: got an array. This is the pre-0.5 shape `template([{ def: Pos, values: { x: 0 } }])`, which no longer works. Pass callable bundles instead: `template(Pos({ x: 0 }), Vel)`.",{op:"template"});const t=[];for(let s=0;s<e.length;s++){const r=e[s];t.push({def:W(r),values:V(r)})}return this._store.createTemplate(t)}regionOffset(e){return this._store.regionOffset(e)}regionHandle(e){return this._store.regionHandle(e)}fieldId(e,t){return this._store.fieldIdOf(e,t)}entityIdAtRow(e,t){return this._store.entityIdAtRow(e,t)}get columnStore(){return this._store.columnStore}get archetypeCount(){return this._store.archetypeCount}registerTag(){return this._store.registerComponent({})}registerSparseTag(){return this._store.registerSparseComponent({})}isAlive(e){return this._store.isAlive(e)}get entityCount(){return this._store.entityCount}hasComponent(e,t){return this._store.hasComponent(e,t)}isDisabled(e){return this._store.isDisabled(e)}addSparse(e,t,s){return this._store.addSparse(e,t,s),this}removeSparse(e,t){return this._store.removeSparse(e,t),this}hasSparse(e,t){return this._store.hasSparse(e,t)}getSparseField(e,t,s){return this._store.getSparseField(e,t,s)}setSparseField(e,t,s,r){this._store.setSparseField(e,t,s,r)}getLastRunTick(){return this._ctx.lastRunTick}getChangeTick(){return this._store.changeTick}noteScan(e){this._store.noteScan(e)}getQueryDirtyEpoch(){return this._store.queryDirtyEpoch}forEachSparseMatch(e,t,s,r,n,o){this._store.forEachSparseMatch(e,t,s,r,n,o)}relationBackingSparseId(e,t){return this._store.relationBackingSparseId(e,t)}forEachTargetMatch(e,t,s,r,n,o){this._store.forEachTargetMatch(e,t,s,r,n,o)}forEachHierarchyMatch(e,t,s,r,n,o,c,h){this._store.forEachHierarchyMatch(e,t,s,r,n,o,c,h)}addSystems(e,...t){return this._schedule.addSystems(e,...t),this}addPhase(e,t){return this._schedule.addPhase(e,t)}configureSet(e,t){return this._schedule.configureSet(e,t),this}trackRows(e){this._store.trackRows(e)}publishRowCounts(){this._store.publishRowCounts()}flush(){this._ctx.flush()}}function qs(a,e){return typeof e=="object"&&e!==null&&console.warn(`runIfResourceEq('${a.description??"?"}'): 'expected' is an object, and the comparison is reference identity. The gate fires only while the resource holds this exact instance. Prefer a primitive phase value.`),{name:`runIfResourceEq(${a.description??"?"})`,resourceReads:[a],evaluate:t=>t.getResource(a)===e}}function Ys(a,e=0){if(!Number.isInteger(a)||a<1)throw new i.ECSError(i.ECS_ERROR.INVALID_RUN_CONDITION,`runEveryNTicks: n must be a positive integer, got ${a}`);if(!Number.isInteger(e))throw new i.ECSError(i.ECS_ERROR.INVALID_RUN_CONDITION,`runEveryNTicks: offset must be an integer, got ${e}`);const t=(e%a+a)%a;return{name:`runEveryNTicks(${a}${t!==0?`, +${t}`:""})`,evaluate:s=>(s.ecsTick-t)%a===0}}function Ws(a){return{name:"runIfAnyMatch",reads:a.defs,evaluate:()=>a.entityCount>0}}function xe(a){const e=[],t=[];for(const s of a)s.reads&&e.push(...s.reads),s.resourceReads&&t.push(...s.resourceReads);return{...e.length>0?{reads:e}:{},...t.length>0?{resourceReads:t}:{}}}function Vs(a){return{name:`runIfNot(${a.name})`,...xe([a]),evaluate:e=>!a.evaluate(e)}}function js(...a){return{name:`runIfAll(${a.map(e=>e.name).join(", ")})`,...xe(a),evaluate:e=>a.every(t=>t.evaluate(e))}}function zs(...a){return{name:`runIfAny(${a.map(e=>e.name).join(", ")})`,...xe(a),evaluate:e=>a.some(t=>t.evaluate(e))}}function Qs(a){return a.kind==="spawn"&&a.onSpawned!==void 0?{kind:"spawn",components:a.components}:a}class Ks{seed;_startup=[];_ticks=[];_sink=this._startup;constructor(e=0){this.seed=e}openTick(e,t){const s=this._ticks[this._ticks.length-1];if(s!==void 0&&s.tick===e){this._sink=s.commands;return}const r=[];this._ticks.push({tick:e,dt:t,commands:r}),this._sink=r}record=e=>{this._sink.push(Qs(e))};log(){return{seed:this.seed,startup:this._startup,ticks:this._ticks}}snapshotLog(){return{seed:this.seed,startup:this._startup.map(e=>({...e})),ticks:this._ticks.map(e=>({...e,commands:e.commands.map(t=>({...t}))}))}}}const X="__component_def";function Xs(a){return JSON.stringify(a,(e,t)=>{if(typeof t=="function"&&"id"in t)return{[X]:t.id};if(t!==null&&typeof t=="object"&&X in t)throw new i.ECSError(i.ECS_ERROR.COMMAND_LOG_TAG_COLLISION,`cannot serialize the command log, a value object owns a field named "${X}", the reserved tag the serializer uses for component defs. Rename that component field so the log can round-trip losslessly.`);return t})}function Js(a){return JSON.parse(a,(e,t)=>t!==null&&typeof t=="object"&&X in t?lt(ht(t[X])):t)}function Zs(a,e,t,s){for(const o of t.startup)e.push(o);a.startup();const r=s?.hash??a.snapshots.deterministic,n=[];for(const o of t.ticks){for(const c of o.commands)e.push(c);a.update(o.dt),r&&n.push(a.snapshots.stateHash())}return{startupCommands:t.startup.length,ticks:t.ticks.length,stateHashes:n}}function Ee(a){return a.name??`system#${a.id}`}class er{_frames=[];_current=null;tickBegin(e,t){const s={tick:e,dt:t,events:[]};this._current=s,this._frames.push(s)}tickEnd(e){this._current=null}systemBegin(e,t){this._current?.events.push({kind:"system_start",system:Ee(e),phase:t})}systemEnd(e){this._current?.events.push({kind:"system_end",system:Ee(e)})}commandQueued(e,t,s){this._current?.events.push({kind:"command_queued",op:e,entity:t,component:s})}flushBegin(e){this._current?.events.push({kind:"flush_begin",phase:e})}flushEnd(e){this._current?.events.push({kind:"flush_end",phase:e})}phaseBoundary(e){}observerFired(e,t,s,r){this._current?.events.push({kind:"observer_fired",op:e,component:t,entity:s,observer:Ee(r)})}eventEmitted(e){this._current?.events.push({kind:"event_emitted",key:e})}eventRead(e,t){this._current?.events.push({kind:"event_read",key:e,count:t})}frames(){return this._frames}reset(){this._frames.length=0,this._current=null}}function L(a,e){if(!(e>=0)||!Number.isFinite(e))throw new i.ECSError(i.ECS_ERROR.INVALID_FRAME_STEP,`${a} must be a finite number >= 0, got ${e}`);return e}function tr(a){if(!Number.isInteger(a)||a<0)throw new i.ECSError(i.ECS_ERROR.INVALID_FRAME_STEP,`frame count must be an integer >= 0, got ${a}`);return a}class sr{_ecs;_requestFrame;_cancelFrame;_frameHandle=null;_lastTimestampMs=null;_running=!1;_fixedDt;_maxDt;constructor(e,t={}){this._ecs=e,this._fixedDt=L("fixedDt",t.fixedDt??1/60),this._maxDt=L("maxDt",t.maxDt??.25);const s=globalThis;this._requestFrame=t.requestFrame??s.requestAnimationFrame?.bind(globalThis),this._cancelFrame=t.cancelFrame??s.cancelAnimationFrame?.bind(globalThis),t.autoStart===!0&&this.play()}get fixedDt(){return this._fixedDt}set fixedDt(e){this._fixedDt=L("fixedDt",e)}get maxDt(){return this._maxDt}set maxDt(e){this._maxDt=L("maxDt",e)}get isRunning(){return this._running}step(e=this._fixedDt){this._ecs.update(L("dt",e))}stepFrames(e,t=this._fixedDt){tr(e);const s=L("dt",t);for(let r=0;r<e;r++)this._ecs.update(s)}play(){if(!this._running){if(this._requestFrame===void 0)throw new i.ECSError(i.ECS_ERROR.INVALID_FRAME_STEP,"FrameStepper.play() requires requestAnimationFrame or a requestFrame option");this._running=!0,this._lastTimestampMs=null,this._requestNextFrame()}}pause(){this._running=!1,this._lastTimestampMs=null,this._frameHandle!==null&&this._cancelFrame!==void 0&&this._cancelFrame(this._frameHandle),this._frameHandle=null}toggle(){this._running?this.pause():this.play()}dispose(){this.pause()}_requestNextFrame(){this._frameHandle=this._requestFrame?.(this._onFrame)??null}_onFrame=e=>{if(!this._running)return;const t=this._lastTimestampMs===null?this._fixedDt:(e-this._lastTimestampMs)/1e3;this._lastTimestampMs=e,this._ecs.update(Math.min(L("dt",t),this._maxDt)),this._running&&this._requestNextFrame()}}const rr=1;function nr(a){return i.unsafeCast(Symbol(a))}function ir(a){return i.unsafeCast(Symbol(a))}function or(a){return i.unsafeCast(Symbol(a))}const ar="0.6.0";exports.ANY_RELATION=i.ANY_RELATION;exports.ECSError=i.ECSError;exports.ECSRestoreError=i.ECSRestoreError;exports.ECS_ERROR=i.ECS_ERROR;exports.HostCommandQueue=i.HostCommandQueue;exports.SCHEDULE=i.SCHEDULE;exports.applyHostCommand=i.applyHostCommand;exports.getEntityIndex=i.getEntityIndex;exports.installHostCommandSeam=i.installHostCommandSeam;exports.isEcsError=i.isEcsError;exports.spawnEntry=i.spawnEntry;exports.storeBaseAbove=i.storeBaseAbove;exports.uninstallHostCommandSeam=i.uninstallHostCommandSeam;exports.SabUnavailableError=ne.SabUnavailableError;exports.ChangedQuery=F;exports.ChunkColumns=ke;exports.Commands=wt;exports.ECS=Ne;exports.ECS_SNAPSHOT_VERSION=rr;exports.FrameStepper=sr;exports.FrameTraceRecorder=er;exports.HIERARCHY_UNBOUNDED=oe;exports.HostCommandRecorder=Ks;exports.Query=N;exports.QueryBuilder=mt;exports.SparseRestoreError=$t;exports.StoreRestoreError=Gt;exports.SystemContext=Rt;exports.VERSION=ar;exports.and=vs;exports.bundle=Ft;exports.deserializeCommandLog=Js;exports.eventKey=nr;exports.not=As;exports.or=Ts;exports.replayCommandLog=Zs;exports.resourceKey=or;exports.runEveryNTicks=Ys;exports.runIfAll=js;exports.runIfAny=zs;exports.runIfAnyMatch=Ws;exports.runIfNot=Vs;exports.runIfResourceEq=qs;exports.serializeCommandLog=Xs;exports.signalKey=ir;exports.systemSet=ps;
|