@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
package/dist/index.cjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const h=require("./host_commands-DNf0f6ko.cjs"),T=require("./typed_arrays-D3NmwtCG.cjs"),V=require("./shared-BMXh9hxm.cjs"),O=!1,Rt=c=>h.validateAndCast(c),ht=Object.freeze({});function vt(c){const t=(e=>({def:t,values:e??ht}));return Object.defineProperty(t,"id",{value:c,enumerable:!1}),t}function Lt(c,...t){return{def:c,values:t[0]??ht}}function G(c){return typeof c=="function"?c:c.def}function $(c){return typeof c=="function"?ht:c.values}class B extends Error{constructor(t){super(t),this.name="StoreRestoreError"}}function Bt(c){const t=c.view.getUint32(h.STORE_HEADER_OFFSETS.capacity,!0);return new Uint8Array(c.buffer,0,t)}function Gt(c,t=V.DEFAULT_SAB_ALLOCATOR){const e=new DataView(c.buffer,c.byteOffset,c.byteLength);if(c.byteLength<h.STORE_HEADER_BYTES)throw new B(`snapshot too small: ${c.byteLength} bytes (header alone needs ${h.STORE_HEADER_BYTES})`);const s=e.getUint32(h.STORE_HEADER_OFFSETS.magic,!0);if(s!==h.STORE_MAGIC)throw new B(`bad magic: 0x${s.toString(16).padStart(8,"0")} (expected 0x${h.STORE_MAGIC.toString(16).padStart(8,"0")})`);const n=e.getUint32(h.STORE_HEADER_OFFSETS.sim_abi_version,!0);if(n!==h.SIM_ABI_VERSION)throw new B(`incompatible sim_abi_version: snapshot=${n}, build=${h.SIM_ABI_VERSION}`);const r=t(c.byteLength);new Uint8Array(r).set(c);const i=new DataView(r),o=h.readStoreHeader(i);if(o.layoutDescriptorOff<0||o.layoutDescriptorOff>r.byteLength)throw new B(`layout_descriptor_off ${o.layoutDescriptorOff} is outside the snapshot (${r.byteLength} bytes)`);try{const a=h.readLayoutDescriptorRegion(i,o.layoutDescriptorOff,o.archetypeCount),l=h.buildArchetypeViews(r,a);return{buffer:r,view:i,header:o,archetypes:l}}catch(a){throw a instanceof RangeError?new B(`snapshot layout is corrupt or truncated: a descriptor offset or column extent reads past the ${r.byteLength}-byte buffer (${a.message})`):a}}const $t=c=>h.validateAndCast(c);class Pt{fieldNames;columns;reader;_readerLen;constructor(t){this.fieldNames=t,this.columns=[];for(let n=0;n<t.length;n++)this.columns.push([]);const e={};for(let n=0;n<t.length;n++)e[t[n]]=this.columns[n];const s={length:0,...e};this._readerLen=s,this.reader=s}emit(t){const e=this.fieldNames,s=this.columns;for(let n=0;n<e.length;n++)s[n].push(t[e[n]]);this._readerLen.length++}emitSignal(){this._readerLen.length++}clear(){this._readerLen.length=0;const t=this.columns;for(let e=0;e<t.length;e++)t[e].length=0}}function Ut(c){return h.unsafeCast(Symbol(c))}function Ht(c){return h.unsafeCast(Symbol(c))}class Vt{channels=[];dirtyChannels=[];count=0;keyMap=new Map;registerEvent(t){const e=$t(this.count++),s=new Pt(t);return this.channels.push(s),h.unsafeCast(e)}emitEvent(t,e){const s=t,n=this.channels[s],r=n.reader.length===0;n.emit(e),r&&this.dirtyChannels.push(s)}emitSignal(t){const e=t,s=this.channels[e],n=s.reader.length===0;s.emitSignal(),n&&this.dirtyChannels.push(e)}getEventReader(t){return this.channels[t].reader}clearEvents(){const t=this.dirtyChannels,e=this.channels;for(let s=0;s<t.length;s++)e[t[s]].clear();t.length=0}devBufferedEventCount(){const t=this.dirtyChannels,e=this.channels;let s=0;for(let n=0;n<t.length;n++)s+=e[t[n]].reader.length;return s}registerEventByKey(t,e){if(this.keyMap.has(t))throw new h.ECSError(h.ECS_ERROR.EVENT_ALREADY_REGISTERED,`event '${t.description??"<unnamed>"}' is already registered`,{event:t.description});const s=this.registerEvent(e);return this.keyMap.set(t,s),s}getEventDefByKey(t){const e=this.keyMap.get(t);if(e===void 0)throw new h.ECSError(h.ECS_ERROR.EVENT_NOT_REGISTERED,`event '${t.description??"<unnamed>"}' is not registered — call ecs.events.register(key, fields) at world setup`,{event:t.description});return e}hasEventKey(t){return this.keyMap.has(t)}}class qt{map=new Map;register(t,e){if(this.map.has(t))throw new h.ECSError(h.ECS_ERROR.RESOURCE_ALREADY_REGISTERED,`resource '${t.description??"<unnamed>"}' is already registered — remove() it first if you meant to replace it`,{resource:t.description});this.map.set(t,e)}get(t){if(!this.map.has(t))throw new h.ECSError(h.ECS_ERROR.RESOURCE_NOT_REGISTERED,`resource read: '${t.description??"<unnamed>"}' is not registered — call ecs.resources.register(key, value) at world setup`,{resource:t.description});return this.map.get(t)}set(t,e){if(!this.map.has(t))throw new h.ECSError(h.ECS_ERROR.RESOURCE_NOT_REGISTERED,`resource write: '${t.description??"<unnamed>"}' is not registered — call ecs.resources.register(key, value) at world setup`,{resource:t.description});this.map.set(t,e)}remove(t){if(!this.map.has(t))throw new h.ECSError(h.ECS_ERROR.RESOURCE_NOT_REGISTERED,`resource remove: '${t.description??"<unnamed>"}' is not registered — call ecs.resources.register(key, value) at world setup`,{resource:t.description});this.map.delete(t)}has(t){return this.map.has(t)}}class z extends Error{capacity;requested;constructor(t,e){super(`BufferBackedColumn overflow: requested length ${e} exceeds capacity ${t}`),this.name="StoreColumnOverflowError",this.capacity=t,this.requested=e}}class Wt{_buf;_capacity;_len=0;constructor(t){this._buf=t,this._capacity=t.length}refreshView(t){if(t.length<this._len)throw new z(t.length,this._len);this._buf=t,this._capacity=t.length}get length(){return this._len}get capacity(){return this._capacity}push(t){if(this._len>=this._capacity)throw new z(this._capacity,this._len+1);this._buf[this._len++]=t}pop(){return this._buf[--this._len]}get(t){return this._buf[t]}setAt(t,e){this._buf[t]=e}swapRemove(t){const e=this._buf[t];return this._buf[t]=this._buf[--this._len],e}clear(){this._len=0}setLength(t){if(t>this._capacity)throw new z(this._capacity,t);this._len=t}get buf(){return this._buf}view(){return this._buf.subarray(0,this._len)}[Symbol.iterator](){let t=0;const e=this._buf,s=this._len;return{next(){return t<s?{value:e[t++],done:!1}:{value:0,done:!0}}}}ensureCapacity(t){if(t>this._capacity)throw new z(this._capacity,t)}bulkAppend(t,e,s){this.ensureCapacity(this._len+s),this._buf.set(t.subarray(e,e+s),this._len),this._len+=s}bulkAppendZeroes(t){this.ensureCapacity(this._len+t),this._buf.fill(0,this._len,this._len+t),this._len+=t}bulkAppendValue(t,e){this.ensureCapacity(this._len+e),this._buf.fill(t,this._len,this._len+e),this._len+=e}}const ut=c=>h.validateAndCast(c);class at{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(t,e,s,n=h.DEFAULT_COLUMN_CAPACITY,r){if(this.id=t,this.mask=e,this._entityIds=new T.GrowableUint32Array(n),s){let i=0;for(let o=0;o<s.length;o++){const a=s[o],l=a.componentId,u=new Array(a.fieldNames.length);if(this._colOffset[l]=i,this._fieldCount[l]=a.fieldNames.length,this._fieldIndex[l]=a.fieldIndex,this._fieldNames[l]=a.fieldNames,a.fieldNames.length>0&&!r)throw new h.ECSError(h.ECS_ERROR.COMPONENT_NOT_REGISTERED,`Archetype ${t}: 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<a.fieldNames.length;d++){const f=a.fieldTypes[d],p=r(a.componentId,d,f);u[d]=p,this._flatColumns[i++]=p}this.columnGroups[l]={layout:a,columns:u},this._columnIds.push(l),this._changedTick[l]=0}}this.hasColumns=this._columnIds.length>0,this.materializesRows=!e.isEmpty()}static fromColumnStore(t,e,s,n,r){const i=n.archetypes.get(r);if(!i)throw new h.ECSError(h.ECS_ERROR.COMPONENT_NOT_REGISTERED,`ColumnStore has no archetype ${r}`);const o=(l,u)=>{const d=i.columns.get(h.columnKey(l,u));if(!d)throw new h.ECSError(h.ECS_ERROR.COMPONENT_NOT_REGISTERED,`ColumnStore archetype ${r} has no column for (${l}, ${u})`);return new Wt(d.view)},a=new at(t,e,s,i.rowCapacity,o);return a._storeArchetypeId=r,a}get isBufferBacked(){return this._storeArchetypeId!==null}refreshViews(t){if(this._storeArchetypeId===null)throw new h.ECSError(h.ECS_ERROR.COMPONENT_NOT_REGISTERED,`Archetype ${this.id} is not SAB-backed`);const e=t.archetypes.get(this._storeArchetypeId);if(!e)throw new h.ECSError(h.ECS_ERROR.COMPONENT_NOT_REGISTERED,`new ColumnStore has no archetype ${this._storeArchetypeId}`);const s=e.columnsInOrder,n=this._flatColumns;for(let r=0;r<s.length;r++)n[r].refreshView(s[r].view)}get entityCount(){return et?this.length:this.enabledCount}get totalCount(){return this.length}get disabledCount(){return this.length-this.enabledCount}get entityIds(){return this._entityIds.buf}swapRows(t,e){if(t===e)return;const s=this._entityIds.buf,n=s[t];s[t]=s[e],s[e]=n;const r=this._flatColumns;for(let i=0;i<r.length;i++){const o=r[i].buf,a=o[t];o[t]=o[e],o[e]=a}}_placeTail(t,e){const s=this.enabledCount;if(s===t)return this.enabledCount=t+1,t;if(this.swapRows(s,t),e!==void 0){const n=this._entityIds.buf;e[h.getEntityIndex(n[t])]=t}return this.enabledCount=s+1,s}_placeTailBulk(t,e){return this.enabledCount+=e,t}disableRow(t,e){const s=this.enabledCount-1;if(t!==s){this.swapRows(t,s);const n=this._entityIds.buf;e[h.getEntityIndex(n[t])]=t,e[h.getEntityIndex(n[s])]=s}this.enabledCount=s}enableRow(t,e){const s=this.enabledCount;if(t!==s){this.swapRows(t,s);const n=this._entityIds.buf;e[h.getEntityIndex(n[t])]=t,e[h.getEntityIndex(n[s])]=s}this.enabledCount=s+1}removeRow(t,e){if(this.enabledCount===this.length){const s=this._entityIds.buf,n=this.length-1;if(t!==n){if(s[t]=s[n],this.hasColumns){const r=this._flatColumns;for(let i=0;i<r.length;i++)r[i].swapRemove(t)}e[h.getEntityIndex(s[t])]=t}else if(this.hasColumns){const r=this._flatColumns;for(let i=0;i<r.length;i++)r[i].pop()}this._entityIds.pop(),this.length=n,this.enabledCount=n;return}this._removeRowPartitioned(t,e)}_removeRowPartitioned(t,e){const s=this._entityIds.buf,n=this.hasColumns,r=this.enabledCount,i=this.length-1;if(t>=r){if(t!==i){if(s[t]=s[i],n){const a=this._flatColumns;for(let l=0;l<a.length;l++)a[l].swapRemove(t)}e[h.getEntityIndex(s[t])]=t}else if(n){const a=this._flatColumns;for(let l=0;l<a.length;l++)a[l].pop()}this._entityIds.pop(),this.length--;return}const o=r-1;if(t!==o&&(this.swapRows(t,o),e[h.getEntityIndex(s[t])]=t),o!==i){if(s[o]=s[i],n){const a=this._flatColumns;for(let l=0;l<a.length;l++)a[l].swapRemove(o)}e[h.getEntityIndex(s[o])]=o}else if(n){const a=this._flatColumns;for(let l=0;l<a.length;l++)a[l].pop()}this._entityIds.pop(),this.length--,this.enabledCount=o}get entityList(){return this._entityIds.view()}hasComponent(t){return this.mask.has(t)}matches(t){return this.mask.contains(t)}getColumnRead(t,e){const s=t.id,n=this._fieldIndex[s][e];return this._flatColumns[this._colOffset[s]+n].buf}getColumnsRead(t,...e){return e.map(n=>this.getColumnRead(t,n))}getOptionalColumnRead(t,e){const s=t.id,n=this._colOffset[s];if(n===void 0)return;const r=this._fieldIndex[s][e];return this._flatColumns[n+r].buf}getColumn(t,e,s){const n=t.id;this._changedTick[n]=s;const r=this._fieldIndex[n][e];return this._flatColumns[this._colOffset[n]+r].buf}columnGroupMut(t,e){const s=t.id;this._changedTick[s]=e;const n=this._colOffset[s],r=this._fieldNames[s],i=this._flatColumns;let o=this._mutGroupCache[s];o===void 0&&(o={},this._mutGroupCache[s]=o);for(let a=0;a<r.length;a++)o[r[a]]=i[n+a].buf;return o}columnGroupRead(t){const e=t.id,s=this._colOffset[e],n=this._fieldNames[e],r=this._flatColumns;let i=this._readGroupCache[e];i===void 0&&(i={},this._readGroupCache[e]=i);for(let o=0;o<n.length;o++)i[n[o]]=r[s+o].buf;return i}writeFields(t,e,s,n){const r=e,i=this._colOffset[r];if(i===void 0)return;this._changedTick[r]=n;const o=this._fieldNames[r],a=this._flatColumns;for(let l=0;l<o.length;l++)a[i+l].buf[t]=s[o[l]]??0}bulkWriteFields(t,e,s,n,r){const i=s,o=this._colOffset[i];if(o===void 0)return;this._changedTick[i]=r;const a=this._fieldNames[i],l=this._flatColumns,u=t+e;for(let d=0;d<a.length;d++)l[o+d].buf.fill(n[a[d]]??0,t,u)}writeFieldsPositional(t,e,s,n){const r=e,i=this._colOffset[r];if(i===void 0)return;this._changedTick[r]=n;const o=this._flatColumns;for(let a=0;a<s.length;a++)o[i+a].buf[t]=s[a]}readField(t,e,s){const n=e,r=this._colOffset[n];if(r===void 0)return NaN;const i=this._fieldIndex[n][s];return i===void 0?NaN:this._flatColumns[r+i].buf[t]}copySharedFrom(t,e,s,n){const r=t._colOffset,i=t._fieldCount,o=t._flatColumns,a=this._flatColumns,l=this._columnIds;for(let u=0;u<l.length;u++){const d=l[u],f=r[d];if(f===void 0)continue;this._changedTick[d]=n;const p=this._colOffset[d],y=i[d];for(let g=0;g<y;g++)a[p+g].buf[s]=o[f+g].buf[e]}}addEntity(t,e){const s=this._flatColumns;s.length>0&&this.length>=s[0].buf.length&&this.growHandler!==null&&this.growHandler(this,1);const n=this.length;this._entityIds.push(t);for(let r=0;r<s.length;r++)s[r].push(0);return this.length++,this._placeTail(n,e)}removeEntity(t){const e=this.length-1;let s=h.NO_SWAP;const n=this._flatColumns,r=this._entityIds.buf;if(t!==e){r[t]=r[e],s=h.getEntityIndex(r[t]);for(let i=0;i<n.length;i++)n[i].swapRemove(t)}else for(let i=0;i<n.length;i++)n[i].pop();return this._entityIds.pop(),this.length--,t<this.enabledCount&&this.enabledCount--,s}addEntityTag(t,e){const s=this.length;return this._entityIds.push(t),this.length++,this._placeTail(s,e)}addEntities(t,e=t.length){if(e===0)return this.length;const s=this._flatColumns;s.length>0&&this.length+e>s[0].buf.length&&this.growHandler!==null&&this.growHandler(this,e);const n=this.length;this._entityIds.bulkAppend(t,0,e);for(let r=0;r<s.length;r++)s[r].bulkAppendZeroes(e);return this.length+=e,this._placeTailBulk(n,e)}addEntitiesTag(t,e=t.length){if(e===0)return this.length;const s=this.length;return this._entityIds.bulkAppend(t,0,e),this.length+=e,this._placeTailBulk(s,e)}ensureRowCapacity(t){const e=this._flatColumns;e.length>0&&this.length+t>e[0].buf.length&&this.growHandler!==null&&this.growHandler(this,t)}addEntityWithValues(t,e,s,n){const r=this._flatColumns;r.length>0&&this.length>=r[0].buf.length&&this.growHandler!==null&&this.growHandler(this,1);const i=this.length;this._entityIds.push(t);for(let a=0;a<r.length;a++)r[a].push(e[a]);this.length++;const o=this._columnIds;for(let a=0;a<o.length;a++)this._changedTick[o[a]]=s;return this._placeTail(i,n)}addEntitiesWithValues(t,e,s,n){if(e===0)return this.length;const r=this._flatColumns;r.length>0&&this.length+e>r[0].buf.length&&this.growHandler!==null&&this.growHandler(this,e);const i=this.length;this._entityIds.bulkAppend(t,0,e);for(let a=0;a<r.length;a++)r[a].bulkAppendValue(s[a],e);this.length+=e;const o=this._columnIds;for(let a=0;a<o.length;a++)this._changedTick[o[a]]=n;return this._placeTailBulk(i,e)}removeEntityTag(t){const e=this.length-1;let s=h.NO_SWAP;const n=this._entityIds.buf;return t!==e&&(n[t]=n[e],s=h.getEntityIndex(n[t])),this._entityIds.pop(),this.length--,t<this.enabledCount&&this.enabledCount--,s}moveEntityFrom(t,e,s,n,r,i){const o=e>=t.enabledCount;if(!this.materializesRows){t.removeRow(e,i),A[0]=h.UNASSIGNED,A[1]=h.NO_SWAP;return}const a=this._flatColumns;a.length>0&&this.length>=a[0].buf.length&&this.growHandler!==null&&this.growHandler(this,1);const l=this.length;this._entityIds.push(s);const u=t._flatColumns;for(let p=0;p<a.length;p++){const y=n[p];a[p].push(y>=0?u[y].buf[e]:0)}const d=this._columnIds;for(let p=0;p<d.length;p++)this._changedTick[d[p]]=r;this.length++;const f=o?l:this._placeTail(l,i);t.removeRow(e,i),A[0]=f,A[1]=h.NO_SWAP}moveEntityFromTag(t,e,s,n){const r=e>=t.enabledCount;if(!this.materializesRows){t.removeRow(e,n),A[0]=h.UNASSIGNED,A[1]=h.NO_SWAP;return}const i=this.length;this._entityIds.push(s),this.length++;const o=r?i:this._placeTail(i,n);t.removeRow(e,n),A[0]=o,A[1]=h.NO_SWAP}bulkMoveAllFrom(t,e,s){const n=t.length;if(n===0)return this.length;const r=this._flatColumns;r.length>0&&this.length+n>r[0].buf.length&&this.growHandler!==null&&this.growHandler(this,n);const i=this.length,o=t._flatColumns;this._entityIds.bulkAppend(t._entityIds.buf,0,n);for(let l=0;l<r.length;l++){const u=e[l];u>=0?r[l].bulkAppend(o[u].buf,0,n):r[l].bulkAppendZeroes(n)}const a=this._columnIds;for(let l=0;l<a.length;l++)this._changedTick[a[l]]=s;return this.length+=n,this.enabledCount=i+t.enabledCount,t.clearRows(),i}clearRows(){this.length=0,this.enabledCount=0,this._entityIds.clear();const t=this._flatColumns;for(let e=0;e<t.length;e++)t[e].clear()}restoreHostRows(t,e){const s=t.length;this._entityIds.clear(),this._entityIds.ensureCapacity(s);for(let r=0;r<s;r++)this._entityIds.push(t[r]);const n=this._flatColumns;for(let r=0;r<n.length;r++)n[r].setLength(s);this.length=s,this.enabledCount=e}getEdge(t){return this.edges[t]}setEdge(t,e){this.edges[t]=e}getBatchTransitionMap(t){const e=this.batchTransitionMaps.get(t.id);if(e!==void 0)return e;const s=st(this,t);return this.batchTransitionMaps.set(t.id,s),s}getCompositeAddEdge(t){return this.compositeAddEdges===null?void 0:this.compositeAddEdges.get(t)}cacheCompositeAddEdge(t,e,s){(this.compositeAddEdges??=new Map).set(t,{target:e,map:s})}}const A=[0,h.NO_SWAP];let et=!1;function x(c){const t=et;return et=c,t}function st(c,t){const e=t._flatColumns,s=new Int16Array(e.length),n=t._columnIds,r=c._colOffset,i=t._colOffset,o=t._fieldCount;for(let a=0;a<n.length;a++){const l=n[a],u=i[l],d=o[l],f=r[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 bt=c=>h.validateAndCast(c),U=Object.freeze([]);function dt(c){return typeof c=="object"&&!Array.isArray(c)}function zt(c){let t=U;c.spawns!==void 0&&c.spawns.length>0&&(t=c.spawns.map(s=>dt(s)?s.defs:s));let e=U;if(c.despawns!==void 0&&c.despawns.length>0){const s=[];for(const n of c.despawns)dt(n)?s.push(...n.defs):s.push(n);e=s}return{reads:c.reads,writes:c.writes,spawns:t,despawns:e,transitions:c.transitions??U,resourceReads:c.resourceReads??U,resourceWrites:c.resourceWrites??U,sparseReads:c.sparseReads,sparseWrites:c.sparseWrites,relationReads:c.relationReads,relationWrites:c.relationWrites}}const nt=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([])}),jt=Symbol.dispose??Symbol.for("Symbol.dispose"),X=(1<<20)-1;let Yt=0;function Kt(c,t){const e={...nt,...t,id:bt(Yt++),name:c,fn:Xt};return Object.freeze(e)}function Xt(){}function ft(c){const t=new Set;if(c)for(let e=0;e<c.length;e++)t.add(c[e].id);return t}function Qt(c){const t=(i,o)=>i.cid-o.cid||i.id-o.id,e=new Map,s=new Map;for(const i of c)e.set(i,[]),s.set(i,0);for(const i of c)if(i.writes.size!==0)for(const o of c){if(i===o)continue;let a=!1;for(const l of i.writes)if(o.reads.has(l)){a=!0;break}a&&(e.get(i).push(o),s.set(o,s.get(o)+1))}const n=c.filter(i=>s.get(i)===0).sort(t),r=[];for(;n.length>0;){const i=n.shift();r.push(i);for(const o of e.get(i)){const a=s.get(o)-1;s.set(o,a),a===0&&(n.push(o),n.sort(t))}}if(r.length!==c.length){const i=new Set(r);for(const o of c.slice().sort(t))i.has(o)||r.push(o)}return r}class Zt{constructor(t,e){this.store=t,this.ctx=e}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 t=new Array(this.entries.length);for(let e=0;e<this.entries.length;e++)t[e]=this.entries[e].descriptor;return t}register(t,e){const s=t.id,n=e.granularity??"archetype",r=e.onSet!==void 0&&n==="entity",i=e.onSet!==void 0&&n!=="entity",o=e.access??{},a=Kt(e.name??`observer(${h.componentDebugName(t)??s})`,o),l={id:a.id,cid:s,def:t,onAdd:e.onAdd,onRemove:e.onRemove,onDisable:e.onDisable,onEnable:e.onEnable,onSetEntity:r?e.onSet:void 0,onSetArch:i?e.onSet:void 0,descriptor:a,writes:ft(o.writes),reads:ft(o.reads),yieldExisting:e.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,[jt]:d}}_dispose(t){if(t.disposed)return;t.disposed=!0;const e=this.entries.indexOf(t);e>=0&&this.entries.splice(e,1);const s=this.byCid.get(t.cid);if(s!==void 0){const n=s.indexOf(t);n>=0&&s.splice(n,1),s.length===0&&this.byCid.delete(t.cid)}this._topo=null,this._reconfigureComponent(t.cid)}_reconfigureComponent(t){const e=this.byCid.get(t);let s=!1,n=!1,r=!1,i=!1,o=!1;if(e!==void 0)for(let a=0;a<e.length;a++){const l=e[a];l.onAdd!==void 0&&(s=!0),l.onRemove!==void 0&&(n=!0),l.onDisable!==void 0&&(r=!0),l.onEnable!==void 0&&(i=!0),l.onSetEntity!==void 0&&(o=!0)}this.store._configureComponentObservation(t,s,n,r,i,o)}getTopo(){return this._topo===null&&(this._topo=Qt(this.entries)),this._topo}dispatchStructural(t){this._bucket(t.addComp,t.addEid,t.addLen,this._addBuckets),this._bucket(t.remComp,t.remEid,t.remLen,this._remBuckets),this._bucket(t.disComp,t.disEid,t.disLen,this._disBuckets),this._bucket(t.enaComp,t.enaEid,t.enaLen,this._enaBuckets);const e=this.getTopo();for(let s=0;s<e.length;s++){const n=e[s];if(!n.disposed){if(n.onRemove!==void 0){const r=this._remBuckets.get(n.cid);r!==void 0&&r.length>0&&this._fireEach(n,n.onRemove,r,"remove")}if(n.onAdd!==void 0){const r=this._addBuckets.get(n.cid);r!==void 0&&r.length>0&&this._fireEach(n,n.onAdd,r,"add")}if(n.onDisable!==void 0){const r=this._disBuckets.get(n.cid);r!==void 0&&r.length>0&&this._fireEach(n,n.onDisable,r,"disable")}if(n.onEnable!==void 0){const r=this._enaBuckets.get(n.cid);r!==void 0&&r.length>0&&this._fireEach(n,n.onEnable,r,"enable")}}}this._clearBuckets(this._addBuckets),this._clearBuckets(this._remBuckets),this._clearBuckets(this._disBuckets),this._clearBuckets(this._enaBuckets)}_fireEach(t,e,s,n){Y(s,this._radixOut,this._radixC0,this._radixC1);try{const r=O?this.store._trace:null;for(let i=0;i<s.length;i++)e(h.unsafeCast(s[i]),this.ctx)}finally{}}_bucket(t,e,s,n){for(let r=0;r<s;r++){const i=t[r];let o=n.get(i);o===void 0&&(o=[],n.set(i,o)),o.push(e[r])}}_clearBuckets(t){for(const e of t.values())e.length=0}dispatchSet(t){if(this.entries.length===0)return;const e=this.getTopo(),s=this._setDrainCache;for(let n=0;n<e.length;n++){const r=e[n];r.onSetEntity!==void 0?this._dispatchSetEntity(r,s):r.onSetArch!==void 0&&this._dispatchSetArch(r,t)}for(const n of s.values())n.length=0;s.clear()}_dispatchSetEntity(t,e){let s=e.get(t.cid);if(s===void 0&&(s=this.store._takeDirty(t.cid),Y(s,this._radixOut,this._radixC0,this._radixC1),e.set(t.cid,s)),s.length===0)return;const n=t.def,r=t.onSetEntity;try{for(let i=0;i<s.length;i++){const o=h.unsafeCast(s[i]);this.store.isAlive(o)&&this.store.hasComponent(o,n)&&!this.store.isDisabled(o)&&r(o,this.ctx)}}finally{}}_dispatchSetArch(t,e){const s=t.onSetArch,n=t.lastSetTick;try{this.store._forEachChangedArchetype(t.cid,n,r=>{s(r,this.ctx)})}finally{}t.lastSetTick=e+1}_yieldExisting(t){const e=t.onAdd,s=this.store._collectEntitiesWithComponent(t.cid);if(s.length!==0){Y(s,this._radixOut,this._radixC0,this._radixC1);try{for(let n=0;n<s.length;n++)e(h.unsafeCast(s[n]),this.ctx)}finally{}}}}function Y(c,t,e,s){const n=c.length;if(!(n<2)){t.length<n&&(t.length=n),e.fill(0),s.fill(0);for(let r=0;r<n;r++){const i=c[r]&X;e[i&1023]++,s[i>>10&1023]++}for(let r=1;r<1024;r++)e[r]+=e[r-1],s[r]+=s[r-1];for(let r=n-1;r>=0;r--){const i=c[r];t[--e[i&X&1023]]=i}for(let r=n-1;r>=0;r--){const i=t[r];c[--s[(i&X)>>10&1023]]=i}}}class Jt{constructor(t){this.host=t}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(t){const e=t?.multi===!0,s=t?.exclusive===!0;if(e&&s)throw new h.ECSError(h.ECS_ERROR.RELATION_MODE_INVALID,"register_relation: a relation cannot be both exclusive and multi-target");const n=!e,r=t?.onDeleteTarget??h.DEFAULT_ON_DELETE_TARGET,i=n?this.host.pushSparseStore([h.RELATION_TARGET_FIELD],["f64"]):this.host.pushSparseStore([],[]),o=this.relations.length;return this.relations.push(h.makeRelationStore(n,i,this.host.sparseStoreOf(i),r)),r!=="orphan"&&(this._hasTargetCleanup=!0),h.unsafeCast(o)}relationOf(t){const e=t,s=this.relations[e];if(s===void 0)throw new h.ECSError(h.ECS_ERROR.RELATION_NOT_REGISTERED,`relation ${e} is not registered`);return s}addRelation(t,e,s){const n=this.relationOf(e);this.host.isAlive(t)&&this.host.isAlive(s)&&n.link(t,s)}removeRelation(t,e,s){const n=this.relationOf(e);this.host.isAlive(t)&&n.unlink(t,s)}targetOf(t,e){return this.relationOf(e).singleTarget(h.getEntityIndex(t))}targetsOf(t,e){return this.relationOf(e).targetsOf(h.getEntityIndex(t))}sourcesOf(t,e){return this.relationOf(e).sourcesOf(t)}hasRelation(t,e){return this.host.hasSparse(t,this.relationOf(e).sparse)}pairsOf(t){const e=this.relationOf(t),s=[],n=this.host.entityGenerations();return e.forEachCanonicalPair(r=>h.createEntityId(r,n[r]),(r,i)=>s.push([r,i])),s}sourcesOfAny(t){const e=[],s=this.relations;for(let n=0;n<s.length;n++){const r=h.unsafeCast(n),i=s[n].sourcesOf(t);for(let o=0;o<i.length;o++)e.push([r,i[o]])}return e}relationBackingSparseId(t){return this.relationOf(t).sparse}forEachRelationTargetMatch(t,e,s,n,r,i,o,a){const l=this.relations;if(l.length===0)return;const u=new Set;for(let E=0;E<l.length;E++){const _=l[E].sourcesOf(t);for(let m=0;m<_.length;m++)u.add(_[m])}if(u.size===0)return;const d=Array.from(u).sort((E,_)=>E-_),f=this.host.sparseStores(),p=this.host.entityArchetype(),y=this.host.entityRow(),g=this.host.archetypes();for(let E=0;E<d.length;E++){const _=h.unsafeCast(d[E]),m=h.getEntityIndex(_),S=p[m];if(S===h.UNASSIGNED)continue;const v=g[S],C=v.mask;if(!C.contains(e)||s!==null&&C.overlaps(s)||n!==null&&!C.overlaps(n))continue;let R=!0;for(let w=0;w<r.length;w++)if(!f[r[w]].has(m)){R=!1;break}if(R){for(let w=0;w<i.length;w++)if(f[i[w]].has(m)){R=!1;break}if(R){if(!o){const w=y[m];if(w!==h.UNASSIGNED&&w>=v.enabledCount)continue}a(_)}}}}compactRelations(){const t=this.relations;if(t.length===0)return 0;const e=n=>this.host.isAlive(n);let s=0;for(let n=0;n<t.length;n++)s+=t[n].pruneDeadReverse(e);return s}ancestorsOf(t,e){const s=this.relationOf(e),n=this.host.sparseStoreOf(s.sparse),r=[t],i=new Set([h.getEntityIndex(t)]);let o=t;for(;;){const a=n.getField(h.getEntityIndex(o),0);if(a===void 0)break;const l=h.unsafeCast(a);if(!this.host.isAlive(l)){r.push(l);break}const u=h.getEntityIndex(l);if(i.has(u))break;i.add(u),o=l,r.push(o)}return r}rootOf(t,e){const s=this.ancestorsOf(t,e);return s[s.length-1]}cascadeOf(t,e){const s=this.relationOf(e),n=[t],r=new Set([h.getEntityIndex(t)]);for(let i=0;i<n.length;i++){const o=s.sourcesOf(n[i]);for(let a=0;a<o.length;a++){const l=o[a],u=h.getEntityIndex(l);r.has(u)||(r.add(u),n.push(l))}}return n}purgeSource(t){const e=this.relations;for(let s=0;s<e.length;s++)e[s].purgeSource(t)}cleanupTarget(t,e){const s=this.relations;for(let n=0;n<s.length;n++){const r=s[n];if(r.onDeleteTarget==="orphan")continue;const i=r.sourcesOf(t);if(i.length!==0){if(r.onDeleteTarget==="delete"){for(let o=0;o<i.length;o++)e.push(i[o]);continue}for(let o=0;o<i.length;o++)r.unlink(i[o],t)}}}forEachHierarchyMatch(t,e,s,n,r,i,o,a,l,u){const d=this.relationOf(o),f=[];if(this.host.forEachSparseMatch(t,e,s,n,r,i,_=>f.push(_),l),f.length===0)return;Y(f,this._hierarchyRadixOut,this._hierarchyRadixC0,this._hierarchyRadixC1);const p=this.host.sparseStoreOf(d.sparse),y=new Map,g=new Set,E=[];for(let _=0;_<f.length;_++){const m=f[_],S=this._hierarchyDepthOf(h.getEntityIndex(m),p,y,g);if(S>a)continue;let v=E[S];v===void 0&&(v=[],E[S]=v),v.push(m)}for(let _=0;_<E.length;_++){const m=E[_];if(m!==void 0)for(let S=0;S<m.length;S++)u(m[S])}}_hierarchyDepthOf(t,e,s,n){const r=[];let i=t,o=0;for(;;){const l=s.get(i);if(l!==void 0){o=l;break}const u=e.getField(i,0);let d=-1;if(u!==void 0){const f=h.unsafeCast(u);this.host.isAlive(f)&&(d=h.getEntityIndex(f))}if(d===-1){s.set(i,0),o=0;break}if(n.has(d)){s.set(i,0),o=0;break}r.push(i),n.add(i),i=d}let a=o;for(let l=r.length-1;l>=0;l--)a+=1,s.set(r[l],a),n.delete(r[l]);return s.get(t)}}class te{_generations;_lengthView;_highWater=0;_freeIndices=[];_aliveCount=0;_capacity;lastIndex=0;constructor(t,e,s){this._capacity=t,this._generations=e,this._lengthView=s}replantViews(t,e){this._generations=t,this._lengthView=e}get generations(){return this._generations}get highWater(){return this._highWater}get aliveCount(){return this._aliveCount}get freeCount(){return this._freeIndices.length}alloc(){let t,e;if(this._freeIndices.length>0)t=this._freeIndices.pop(),e=this._generations[t];else{if(this._highWater>=this._capacity)throw new h.ECSError(h.ECS_ERROR.EID_MAX_INDEX_OVERFLOW,`entityIndexCapacity (${this._capacity}) exhausted; raise it in ECSOptions.memory or destroy unused entities`);t=this._highWater++,this._generations[t]=h.INITIAL_GENERATION,e=h.INITIAL_GENERATION,this._lengthView[0]=this._highWater}return this._aliveCount++,this.lastIndex=t,h.createEntityId(t,e)}ensureCapacity(t){const e=t-this._freeIndices.length;if(e>0&&this._highWater+e>this._capacity)throw new h.ECSError(h.ECS_ERROR.EID_MAX_INDEX_OVERFLOW,`entityIndexCapacity (${this._capacity}) cannot fit ${t} new entities (${this._freeIndices.length} free, high-water ${this._highWater}); raise it in ECSOptions.memory or destroy unused entities`)}recycle(t,e){const s=e+1;s<h.RETIRED_GENERATION?(this._generations[t]=s,this._freeIndices.push(t)):this._generations[t]=h.RETIRED_GENERATION,this._aliveCount--}isAliveIndex(t,e){return t<this._highWater&&this._generations[t]===e}publishLength(){this._lengthView[0]=this._highWater}snapshotFreeIndices(){return this._freeIndices.slice()}setHighWater(t){this._highWater=t}restoreHostState(t,e){this._freeIndices.length=0;for(let s=0;s<t.length;s++)this._freeIndices.push(t[s]);this._aliveCount=e}}const pt=65536;class ee{destroyIds=[];addIds=[];addDefs=[];addValues=[];removeIds=[];removeDefs=[];toggleIds=[];toggleDisable=[];_flushing=!1;host;obsEvents;constructor(t,e){this.host=t,this.obsEvents=e}queueDestroy(t){this.destroyIds.push(t)}queueAdd(t,e,s){this.addIds.push(t),this.addDefs.push(e),this.addValues.push(s)}queueRemove(t,e){this.removeIds.push(t),this.removeDefs.push(e)}queueToggle(t,e){this.toggleIds.push(t),this.toggleDisable.push(e)}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 t=this.obsEvents,e=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>pt)throw new h.ECSError(h.ECS_ERROR.OBSERVER_NON_CONVERGENT,`observer cascade did not converge after ${pt} rounds — two observers likely enqueue each other's structural ops forever`);t.addLen=0,t.remLen=0,t.disLen=0,t.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(),e!==null&&(t.addLen>0||t.remLen>0||t.disLen>0||t.enaLen>0)&&e(t)}}finally{this._flushing=!1}}}function It(c,t){let e=c;const s=new Array(t.length);for(let n=0;n<t.length;n++){const r=t[n],i=new Array(r.columns.length);for(let o=0;o<r.columns.length;o++){const a=r.columns[o];e=h.alignUp(e,a.stride),i[o]={componentId:a.componentId,fieldId:a.fieldId,typeTag:a.typeTag,byteOff:e,stride:a.stride},e+=a.stride*r.rowCapacity}s[n]={archetypeId:r.archetypeId,componentMask:r.componentMask,rowCount:0,enabledCount:0,rowCapacity:r.rowCapacity,columns:i}}if(e>h.STORE_MAX_BYTE_OFFSET)throw new h.StoreLayoutOverflowError(e);return{descriptors:s,newTotal:e}}function At(c,t){const e=c._allocator(t),s=e!==c.buffer?new DataView(e):c.view;return{grownBuffer:e,newView:s}}function Ot(c){return c.buffer instanceof ArrayBuffer?c.view.getUint32(h.STORE_HEADER_OFFSETS.capacity,!0):c.buffer.byteLength}function se(c){const t={};for(let n=0;n<h.STORE_PREFIX_REGIONS.length;n++){const r=h.STORE_PREFIX_REGIONS[n],i=c.view.getUint32(h.STORE_HEADER_OFFSETS[r.headerOff],!0);i!==0&&r.readOptions(c.view,i,t)}const e=h.readHeaderRegionTable(c.view);e.length>0&&(t.regions=e.map(n=>({id:n.regionId,name:`region:${n.regionId}`,bytes:n.byteLength,init:()=>{}})));const s=c.view.getUint32(h.STORE_HEADER_OFFSETS.bindings_off,!0);if(s!==0){const n=c.view.getUint32(h.STORE_HEADER_OFFSETS.layout_descriptor_off,!0);t.bindingsRegionBytes=n-s}return h.isColumnStoreInternal(c)&&c._reservedDescriptorBytes>0&&(t.reservedDescriptorBytes=c._reservedDescriptorBytes),t}function ne(c){const t=new Map;for(let n=0;n<h.STORE_PREFIX_REGIONS.length;n++){const r=h.STORE_PREFIX_REGIONS[n],i=c.view.getUint32(h.STORE_HEADER_OFFSETS[r.headerOff],!0);if(i===0)continue;const o=r.regionBytes(c.view,i);t.set(r.headerOff,new Uint8Array(c.buffer,i,o).slice())}const e=new Map,s=h.readHeaderRegionTable(c.view);for(let n=0;n<s.length;n++){const r=s[n];e.set(r.regionId,new Uint8Array(c.buffer,r.byteOffset,r.byteLength).slice())}return{mechanism:t,consumer:e}}function re(c,t){for(const[e,s]of t.mechanism){const n=c.view.getUint32(h.STORE_HEADER_OFFSETS[e],!0);new Uint8Array(c.buffer,n,s.byteLength).set(s)}for(const[e,s]of t.consumer){const n=h.findRegionOffset(c.view,e);if(n===0)continue;new Uint8Array(c.buffer,n,s.byteLength).set(s)}}function ie(c,t){const e=new Map;for(const[s,n]of c.archetypes){const r=t.get(s)??0;if(r===0)continue;const i=[];for(let o=0;o<n.columnsInOrder.length;o++){const a=n.columnsInOrder[o],l=r*a.stride,u=new Uint8Array(l);u.set(new Uint8Array(a.view.buffer,a.view.byteOffset,l)),i.push(u)}e.set(s,i)}return e}function oe(c,t){for(const[e,s]of t){const n=c.archetypes.get(e);if(n===void 0)throw new Error(`restore_column_snapshots: new store missing archetype ${e} (internal)`);const r=n.columnsInOrder;for(let i=0;i<s.length;i++){const o=r[i].view;new Uint8Array(o.buffer,o.byteOffset,s[i].byteLength).set(s[i])}}}function Tt(c,t,e,s){const n=c.view.getUint32(h.STORE_HEADER_OFFSETS.view_stamp,!0),r=ie(c,e),i=ne(c),o=se(c),a=h.createColumnStore(t,s,o);oe(a,r),re(a,i);const l=n+1>>>0;return a.view.setUint32(h.STORE_HEADER_OFFSETS.view_stamp,l,!0),{store:{...a,header:{...a.header,viewStamp:l}},oldViewStamp:n,newViewStamp:l}}function he(c,t,e){const s=new Array(t.length);for(let _=0;_<t.length;_++){const m=t[_],S=c.archetypes.get(m.archetypeId);s[_]={archetypeId:m.archetypeId,componentMask:S.componentMask,rowCapacity:m.newRowCapacity,columns:S.columnsInOrder}}const{descriptors:n,newTotal:r}=It(Ot(c),s),i=new Map;for(let _=0;_<n.length;_++)i.set(n[_].archetypeId,n[_]);const{grownBuffer:o,newView:a}=At(c,r),l=new Uint8Array(o);for(let _=0;_<t.length;_++){const m=t[_],S=c.archetypes.get(m.archetypeId),v=i.get(m.archetypeId);for(let C=0;C<S.columnsInOrder.length;C++){const R=S.columnsInOrder[C],w=m.rowCount*R.stride;w>0&&l.copyWithin(v.columns[C].byteOff,R.byteOff,R.byteOff+w)}}let u=e;for(const[_,m]of c.archetypes){const S=i.get(_);S!==void 0&&h.writeArchetypeDescriptor(a,u,S),u+=h.archetypeDescriptorBytes(m.columnsInOrder.length)}const d=a.getUint32(h.STORE_HEADER_OFFSETS.view_stamp,!0),f=d+1>>>0;a.setUint32(h.STORE_HEADER_OFFSETS.view_stamp,f,!0),a.setUint32(h.STORE_HEADER_OFFSETS.capacity,r,!0);const p=h.buildArchetypeViews(o,[...i.values()]),y=new Map;for(const[_,m]of c.archetypes){const S=p.get(_);y.set(_,S??m)}const g={buffer:o,view:a,header:{...c.header,viewStamp:f,capacity:r},archetypes:y,_regionBytes:c._regionBytes,_allocator:c._allocator,_reservedDescriptorBytes:c._reservedDescriptorBytes},E=new Array(t.length);for(let _=0;_<t.length;_++)E[_]=t[_].archetypeId;return{store:g,oldViewStamp:d,newViewStamp:f,viewsPreserved:!0,grownArchetypeIds:E}}class Q extends Error{constructor(t){super(t),this.name="StoreGrowError"}}function ae(c,t,e){const s=new Map;for(let u=0;u<t.archetypes.length;u++){const d=t.archetypes[u];s.set(d.archetypeId,d)}const n=[],r=[];for(const[u,d]of c.archetypes){const f=s.get(u),p=f?.newRowCapacity??d.rowCapacity;if(p<(f?.rowCount??0))throw new Q(`archetype ${u}: new_row_capacity ${p} < row_count ${f?.rowCount}`);if(p<d.rowCapacity)throw new Q(`archetype ${u}: shrinking from ${d.rowCapacity} to ${p} is not supported`);p>d.rowCapacity&&r.push({archetypeId:u,newRowCapacity:p,rowCount:f?.rowCount??0}),n.push({archetypeId:u,componentMask:d.componentMask,rowCapacity:p,columns:d.columnsInOrder})}const i=new Map;for(const[u,d]of c.archetypes){const p=s.get(u)?.rowCount??0;if(p>d.rowCapacity)throw new Q(`archetype ${u}: row_count ${p} > old row_capacity ${d.rowCapacity}`);p>0&&i.set(u,p)}if(e?.isInPlace===!0&&h.isColumnStoreInternal(c)&&c._allocator===e&&r.length>0){const u=c.view.getUint32(h.STORE_HEADER_OFFSETS.layout_descriptor_off,!0);return he(c,r,u)}const{store:o,oldViewStamp:a,newViewStamp:l}=Tt(c,n,i,e);return{store:o,oldViewStamp:a,newViewStamp:l,viewsPreserved:!1,grownArchetypeIds:[]}}class L extends Error{constructor(t){super(t),this.name="StoreExtendError"}}function ce(c,t,e){if(t.newArchetypes.length===0)throw new L("extend plan has no new archetypes; use grow_column_store for resizes");const s=new Set;for(let l=0;l<t.newArchetypes.length;l++){const u=t.newArchetypes[l].archetypeId;if(s.has(u))throw new L(`duplicate archetype_id ${u} in extend plan`);if(c.archetypes.has(u))throw new L(`archetype_id ${u} already exists in the SAB; use grow_column_store to resize it`);s.add(u)}const n=new Map;if(t.existing)for(let l=0;l<t.existing.length;l++){const u=t.existing[l];if(!c.archetypes.has(u.archetypeId))throw new L(`existing row_count names unknown archetype_id ${u.archetypeId}`);if(u.rowCount<0)throw new L(`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 L(`archetype ${u.archetypeId}: row_count ${u.rowCount} > old row_capacity ${d.rowCapacity}`)}n.set(u.archetypeId,u.rowCount)}if(e?.isInPlace===!0&&h.isColumnStoreInternal(c)&&c._allocator===e){const l=c.view.getUint32(h.STORE_HEADER_OFFSETS.layout_descriptor_off,!0);let u=0;for(const[,f]of c.archetypes)u+=h.archetypeDescriptorBytes(f.columnsInOrder.length);let d=0;for(let f=0;f<t.newArchetypes.length;f++)d+=h.archetypeDescriptorBytes(t.newArchetypes[f].columns.length);if(u+d<=c._regionBytes)return le(c,t.newArchetypes,l,u)}const r=[];for(const[l,u]of c.archetypes)r.push({archetypeId:l,componentMask:u.componentMask,rowCapacity:u.rowCapacity,columns:u.columnsInOrder});for(let l=0;l<t.newArchetypes.length;l++)r.push(t.newArchetypes[l]);const{store:i,oldViewStamp:o,newViewStamp:a}=Tt(c,r,n,e);return{store:i,oldViewStamp:o,newViewStamp:a,viewsPreserved:!1}}function le(c,t,e,s){const n=new Array(t.length);for(let E=0;E<t.length;E++){const _=t[E];n[E]={archetypeId:_.archetypeId,componentMask:_.componentMask,rowCapacity:_.rowCapacity,columns:_.columns.map(m=>({componentId:m.componentId,fieldId:m.fieldId,typeTag:m.typeTag,stride:h.TYPE_TAG_STRIDE[m.typeTag]}))}}const{descriptors:r,newTotal:i}=It(Ot(c),n),{grownBuffer:o,newView:a}=At(c,i);let l=e+s;for(let E=0;E<r.length;E++)l=h.writeArchetypeDescriptor(a,l,r[E]);const u=a.getUint32(h.STORE_HEADER_OFFSETS.view_stamp,!0),d=c.archetypes.size+t.length;a.setUint32(h.STORE_HEADER_OFFSETS.archetype_count,d,!0),a.setUint32(h.STORE_HEADER_OFFSETS.capacity,i,!0);const f=u+1>>>0;a.setUint32(h.STORE_HEADER_OFFSETS.view_stamp,f,!0);const p=h.buildArchetypeViews(o,r),y=new Map;for(const[E,_]of c.archetypes)y.set(E,_);for(const[E,_]of p)y.set(E,_);return{store:{buffer:o,view:a,header:{...c.header,viewStamp:f,capacity:i,archetypeCount:d},archetypes:y,_regionBytes:c._regionBytes,_allocator:c._allocator,_reservedDescriptorBytes:c._reservedDescriptorBytes},oldViewStamp:u,newViewStamp:f,viewsPreserved:!0}}const rt=810766935,K=1;class b extends Error{constructor(t){super(t),this.name="ECSRestoreError"}}const P=4;function ue(c){const t=c.freeIndices.length,e=c.archetypeRows.length,s=P*(4+t+1+e*3),n=new Uint8Array(s),r=new DataView(n.buffer);let i=0;const o=a=>{r.setUint32(i,a,!0),i+=P};o(c.tick),o(c.entityHighWater),o(c.entityAliveCount),o(t);for(let a=0;a<t;a++)o(c.freeIndices[a]);o(e);for(let a=0;a<e;a++){const l=c.archetypeRows[a];o(l.archetypeId),o(l.length),o(l.enabledCount)}return n}function de(c){const t=new DataView(c.buffer,c.byteOffset,c.byteLength),e=c.byteLength;let s=0;const n=p=>{if(s+p>e)throw new b(`host-state truncated: need ${p} more bytes at offset ${s}, have ${e-s}`)},r=()=>{n(P);const p=t.getUint32(s,!0);return s+=P,p},i=r(),o=r(),a=r(),l=r(),u=new Array(l);for(let p=0;p<l;p++)u[p]=r();const d=r(),f=new Array(d);for(let p=0;p<d;p++){const y=r(),g=r(),E=r();f[p]={archetypeId:y,length:g,enabledCount:E}}if(s!==e)throw new b(`host-state has ${e-s} trailing bytes after the last archetype (not a canonical encoding)`);return{tick:i,entityHighWater:o,entityAliveCount:a,freeIndices:u,archetypeRows:f}}function fe(c,t,e){const s=P*5,n=new Uint8Array(s+c.length+t.length+e.length),r=new DataView(n.buffer);return r.setUint32(0,rt,!0),r.setUint32(4,K,!0),r.setUint32(8,c.length,!0),r.setUint32(12,t.length,!0),r.setUint32(16,e.length,!0),n.set(c,s),n.set(t,s+c.length),n.set(e,s+c.length+t.length),n}function pe(c){const t=P*5;if(c.byteLength<t)throw new b(`world snapshot too small: ${c.byteLength} bytes (frame header needs ${t})`);const e=new DataView(c.buffer,c.byteOffset,c.byteLength),s=e.getUint32(0,!0);if(s!==rt)throw new b(`bad world-snapshot magic: 0x${s.toString(16).padStart(8,"0")} (expected 0x${rt.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 n=e.getUint32(4,!0);if(n!==K)throw new b(`incompatible world-snapshot version: snapshot=${n}, build=${K}`);const r=e.getUint32(8,!0),i=e.getUint32(12,!0),o=e.getUint32(16,!0);if(t+r+i+o!==c.byteLength)throw new b(`world-snapshot frame mismatch: header declares ${t}+${r}+${i}+${o}=${t+r+i+o} bytes, buffer is ${c.byteLength}`);const a=c.byteOffset,l=c.buffer;return{dense:new Uint8Array(l,a+t,r),sparse:new Uint8Array(l,a+t+r,i),host:new Uint8Array(l,a+t+r+i,o)}}function _e(c,t,e){if(c.byteLength<h.STORE_HEADER_BYTES)throw new b(`dense section too small: ${c.byteLength} bytes (SAB header needs ${h.STORE_HEADER_BYTES})`);const s=new DataView(c.buffer,c.byteOffset,c.byteLength),n=s.getUint32(h.STORE_HEADER_OFFSETS.magic,!0);if(n!==h.STORE_MAGIC)throw new b(`dense section bad magic: 0x${n.toString(16).padStart(8,"0")} (expected SAB magic 0x${h.STORE_MAGIC.toString(16).padStart(8,"0")})`);const r=s.getUint32(h.STORE_HEADER_OFFSETS.sim_abi_version,!0);if(r!==h.SIM_ABI_VERSION)throw new b(`dense section incompatible sim_abi_version: snapshot=${r}, build=${h.SIM_ABI_VERSION}`);const i=h.readStoreHeader(s);if(i.layoutDescriptorOff<0||i.layoutDescriptorOff>c.byteLength)throw new b(`dense layoutDescriptorOff ${i.layoutDescriptorOff} is outside the section (${c.byteLength} bytes)`);const o=i.entityIndexOff;if(o<0||o+h.ENTITY_INDEX_HEADER_BYTES>c.byteLength)throw new b(`dense entityIndexOff ${o} is outside the section (${c.byteLength} bytes)`);const a=s.getUint32(o+h.ENTITY_INDEX_HEADER_OFFSETS.capacity,!0);if(a!==e)throw new b(`entity-index capacity mismatch: live=${e}, snapshot=${a}`);let l;try{l=h.readLayoutDescriptorRegion(s,i.layoutDescriptorOff,i.archetypeCount)}catch(u){throw u instanceof RangeError?new b(`dense section layout is corrupt or truncated: a descriptor reads past the ${c.byteLength}-byte section (${u.message})`):u}if(t.size!==l.length)throw new b(`archetype-set mismatch: the live world has ${t.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=t.get(d.archetypeId);if(f===void 0)throw new b(`archetype-set mismatch: snapshot archetype ${d.archetypeId} is absent from the live world`);if(!ge(f.componentMask,d.componentMask))throw new b(`archetype ${d.archetypeId} component-mask mismatch between the live world and the snapshot (different component registration)`);const p=f.columnsInOrder,y=d.columns;if(p.length!==y.length)throw new b(`archetype ${d.archetypeId} column-count mismatch: live=${p.length}, snapshot=${y.length}`);for(let g=0;g<p.length;g++)if(p[g].componentId!==y[g].componentId||p[g].fieldId!==y[g].fieldId||p[g].typeTag!==y[g].typeTag)throw new b(`archetype ${d.archetypeId} column ${g} layout mismatch: live=(c${p[g].componentId},f${p[g].fieldId},t${p[g].typeTag}), snapshot=(c${y[g].componentId},f${y[g].fieldId},t${y[g].typeTag})`)}}function ge(c,t){if(c.length!==t.length)return!1;for(let e=0;e<c.length;e++)if(c[e]!==t[e])return!1;return!0}class ye{host;allocator;constructor(t,e){this.host=t,this.allocator=e}snapshotSparse(){const t=h.snapshotSparseStores(this.host.sparseStores()),e=h.snapshotRelations(this.host.relationStores()),s=new Uint8Array(8+t.length+e.length),n=new DataView(s.buffer);return n.setUint32(0,t.length,!0),n.setUint32(4,e.length,!0),s.set(t,8),s.set(e,8+t.length),s}restoreSparse(t){const e=new DataView(t.buffer,t.byteOffset,t.byteLength);if(t.byteLength<8)throw new h.SparseRestoreError(`sparse snapshot truncated: need 8 header bytes, have ${t.byteLength}`);const s=e.getUint32(0,!0),n=e.getUint32(4,!0);if(8+s+n!==t.byteLength)throw new h.SparseRestoreError(`sparse snapshot frame mismatch: header declares 8+${s}+${n}=${8+s+n} bytes, buffer is ${t.byteLength}`);h.restoreSparseStores(this.host.sparseStores(),t.subarray(8,8+s)),this.rebuildRelationIndices(t.subarray(8+s,8+s+n))}rebuildRelationIndices(t){const e=this.host.generations(),s=r=>h.createEntityId(r,e[r]),n=this.host.relationStores();h.restoreRelations(n,t,s);for(let r=0;r<n.length;r++)n[r].rebuildReverseFromForward(s)}snapshot(){this.host.publishRowCounts();const t=new Uint8Array(Bt(this.host.columnStore())),e=this.snapshotSparse(),s=ue(this.collectHostState());return fe(t,e,s)}collectHostState(){const t=[],e=this.host.archetypes();for(let s=0;s<e.length;s++){const n=e[s];n.isBufferBacked&&t.push({archetypeId:n.id,length:n.length,enabledCount:n.enabledCount})}return{tick:this.host.tick(),entityHighWater:this.allocator.highWater,entityAliveCount:this.allocator.aliveCount,freeIndices:this.allocator.snapshotFreeIndices(),archetypeRows:t}}restoreInto(t){const e=pe(t),s=de(e.host);_e(e.dense,this.host.columnStore().archetypes,this.host.entityIndexCapacity()),this.assertSparseSectionMatches(e.sparse);const n=Gt(e.dense,this.host.bufferAllocator());this.host.mountRestoredDense(n),this.host.reconstructHostRows(s),this.allocator.restoreHostState(s.freeIndices,s.entityAliveCount),this.host.setTick(s.tick),this.host.invalidateQueryCaches(),this.restoreSparse(e.sparse)}assertSparseSectionMatches(t){const e=new DataView(t.buffer,t.byteOffset,t.byteLength);if(t.byteLength<8)throw new h.SparseRestoreError(`sparse snapshot truncated: need 8 header bytes, have ${t.byteLength}`);const s=e.getUint32(0,!0),n=e.getUint32(4,!0);if(8+s+n!==t.byteLength)throw new h.SparseRestoreError(`sparse snapshot frame mismatch: header declares 8+${s}+${n}=${8+s+n} bytes, buffer is ${t.byteLength}`);h.validateSparseStores(this.host.sparseStores(),t.subarray(8,8+s))}}function Dt(c,t,e){const s=c.get(t);s!==void 0?s.push(e):c.set(t,[e])}class Ee{archetypes=[];componentIndex=[];archetypeMap=new Map;nextArchetypeId=0;host;constructor(t){this.host=t}get(t){return this.archetypes[t]}getOrCreateFromMask(t){const e=t.hash(),s=this.lookup(t,e);if(s!==null)return s;const n=ut(this.nextArchetypeId++),r=this.buildLayouts(t);return this.host.extendStore([_t(n,t,r,this.host.initialCapacity())]),this.install(n,t,r,e),n}createManyFromMasks(t){const e=new Array(t.length),s=[],n=[],r=[],i=[];for(let a=0;a<t.length;a++){const l=t[a],u=l.hash(),d=this.lookup(l,u);if(d!==null){e[a]=d;continue}let f=!1;for(let y=0;y<s.length;y++)if(n[y]===u&&s[y].equals(l)){e[a]=i[y],f=!0;break}if(f)continue;const p=ut(this.nextArchetypeId++);s.push(l),n.push(u),r.push(this.buildLayouts(l)),i.push(p),e[a]=p}if(s.length===0)return e;const o=new Array(s.length);for(let a=0;a<s.length;a++)o[a]=_t(i[a],s[a],r[a],this.host.initialCapacity());this.host.extendStore(o);for(let a=0;a<s.length;a++)this.install(i[a],s[a],r[a],n[a]);return e}lookup(t,e){const s=this.archetypeMap.get(e);if(s===void 0)return null;for(let n=0;n<s.length;n++)if(this.archetypes[s[n]].mask.equals(t))return s[n];return null}buildLayouts(t){const e=[],s=this.host.componentMetas();return t.forEach(n=>{const r=n,i=s[r];i&&i.fieldNames.length>0&&e.push({componentId:r,fieldNames:i.fieldNames,fieldIndex:i.fieldIndex,fieldTypes:i.fieldTypes})}),e}install(t,e,s,n){const r=e.copy(),i=this.host.materialize(t,r,s);this.archetypes.push(i),Dt(this.archetypeMap,n,t),e.forEach(o=>{const a=o;let l=this.componentIndex[a];l===void 0&&(l=[],this.componentIndex[a]=l),l.push(t)}),this.host.fanIntoQueries(i)}resolveAdd(t,e){const s=this.get(t);if(s.mask.has(e))return t;const n=s.getEdge(e);if(n?.add!=null)return n.add;const r=this.getOrCreateFromMask(s.mask.copyWithSet(e));return this.cacheEdge(s,this.get(r),e),r}resolveRemove(t,e){const s=this.get(t);if(!s.mask.has(e))return t;const n=s.getEdge(e);if(n?.remove!=null)return n.remove;const r=this.getOrCreateFromMask(s.mask.copyWithClear(e));return this.cacheEdge(this.get(r),s,e),r}cacheEdge(t,e,s){const n=t.getEdge(s)??{add:null,remove:null,addMap:null,removeMap:null};n.add=e.id,n.addMap=st(t,e),t.setEdge(s,n);const r=e.getEdge(s)??{add:null,remove:null,addMap:null,removeMap:null};r.remove=t.id,r.removeMap=st(e,t),e.setEdge(s,r)}}function _t(c,t,e,s){const n=[];for(let o=0;o<e.length;o++){const a=e[o],l=a.fieldTypes;for(let u=0;u<l.length;u++)n.push({componentId:a.componentId,fieldId:u,typeTag:h.TYPED_ARRAY_TAG_TO_TYPE_TAG[l[u]]})}const r=t._words,i=new Array(h.COMPONENT_MASK_WORDS);for(let o=0;o<h.COMPONENT_MASK_WORDS;o++)i[o]=(r[o]??0)>>>0;return{archetypeId:c,componentMask:i,rowCapacity:s,columns:n}}const me=[],gt=-1,Z=new DataView(new ArrayBuffer(8)),yt=129,we=7,J=-1;class Se{entityAllocator;componentMetas=[];componentCount=0;sparseStores=[];sparseNames=[];relationService;events=new Vt;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(t){this._structuralObserverHook=t}_collectDestroyEid=0;_collectDestroyRemoveBit=t=>{if(!this.componentMetas[t].obsRem)return;const e=this._obsEvents;e.remComp[e.remLen]=t,e.remEid[e.remLen]=this._collectDestroyEid,e.remLen++};_collectToggleEid=0;_collectDisableBit=t=>{if(!this.componentMetas[t].obsDisable)return;const e=this._obsEvents;e.disComp[e.disLen]=t,e.disEid[e.disLen]=this._collectToggleEid,e.disLen++};_collectEnableBit=t=>{if(!this.componentMetas[t].obsEnable)return;const e=this._obsEvents;e.enaComp[e.enaLen]=t,e.enaEid[e.enaLen]=this._collectToggleEid,e.enaLen++};_toggleInitial=new Map;_anyDirtyTracked=!1;_dirtyTrackedCids=[];_dirtyLists=[];_dirtyMarks=[];_rowCountsDirty=!1;_queryDirtyEpoch=0;initialCapacity;_scratchTargetMask=new T.BitSet;_columnStore;_growHandler=(t,e)=>{const s=t.id,n=this._columnStore.archetypes.get(s);if(n===void 0)throw new h.ECSError(h.ECS_ERROR.ARCHETYPE_NOT_FOUND,`grow_handler invoked on archetype ${s} which has no SAB region`);const r=n.rowCapacity,i=t.length+e;let o=r>0?r:1;for(;o<i;)o=o*2;const a=[],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&&a.push({archetypeId:f.id,newRowCapacity:f.id===s?o:p.rowCapacity,rowCount:f.hasColumns?f.length:0})}let u;try{u=ae(this._columnStore,{archetypes:a},this._bufferAllocator)}catch(d){throw d instanceof V.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(t){const e=this._capContext,s=this.entityAllocator.aliveCount,n=`SAB grow refused: requested ${t.requestedBytes} bytes exceeds `+(t.capBytes!==null?`the ${t.capBytes}-byte cap.`:"the backing's ceiling.");let r;if(e===void 0)r=` The ECS holds ${s} live entities (no sizing intent declared).`;else if(e.budgetEntities!==null){const i=(s/e.budgetEntities).toFixed(1);r=` Declared ${e.intentLabel}; the ECS holds ${s} live entities (${i}× the budget) — runaway entity creation upstream, or an under-declared budget. Raise the budget only if a ${s}-entity ECS is intended.`}else r=` Declared ${e.intentLabel}; the ECS holds ${s} live entities.`;return new h.ECSError(h.ECS_ERROR.STORE_CAP_EXCEEDED,n+r+` The cap is a hard ceiling with no grow-beyond fallback (#380) — diagnose growth before raising it. Caused by: ${t.message}`)}_bufferAllocator;_capContext;_onBufferResized;constructor(t){const e=typeof t=="number"?{initialCapacity:t}:t??{};if(this.initialCapacity=e.initialCapacity??h.DEFAULT_COLUMN_CAPACITY,this._bufferAllocator=e.bufferAllocator??V.growableSabAllocator(),this._bufferAllocator.isInPlace!==!0)throw new h.ECSError(h.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=e.capContext,this._onBufferResized=e.onBufferResized,this._entityIndexCapacity=e.entityIndexCapacity??h.ENTITY_INDEX_DEFAULT_CAPACITY,this._regions=e.regions,this._bindingsRegionBytes=e.bindingsRegionBytes??0,this._deterministic=e.deterministic??!1,this._deferred=new ee({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 Jt({isAlive:n=>this.isAlive(n),hasSparse:(n,r)=>this.hasSparse(n,r),pushSparseStore:(n,r)=>this._pushSparseStore(n,r),sparseStoreOf:n=>this.sparseStoreOf(n),sparseStores:()=>this.sparseStores,entityGenerations:()=>this.entityAllocator.generations,entityArchetype:()=>this.entityArchetype,entityRow:()=>this.entityRow,archetypes:()=>this.archGraph.archetypes,forEachSparseMatch:(n,r,i,o,a,l,u,d)=>this._forEachSparseMatch(n,r,i,o,a,l,u,d)}),this._columnStore=h.createColumnStore([],this._bufferAllocator,{reservedDescriptorBytes:64*1024,entityIndexCapacity:this._entityIndexCapacity,eventRingCapacitySlots:h.EVENT_RING_DEFAULT_CAPACITY_SLOTS,commandRingCapacitySlots:h.COMMAND_RING_DEFAULT_CAPACITY_SLOTS,actionRingCapacitySlots:h.ACTION_RING_DEFAULT_CAPACITY_SLOTS,regions:this._regions,bindingsRegionBytes:this._bindingsRegionBytes});const s=h.buildEntityIndexViews(this._columnStore.buffer,this._columnStore.header.entityIndexOff,this._entityIndexCapacity);this.entityArchetype=s.archetypes,this.entityRow=s.rows,this.entityAllocator=new te(this._entityIndexCapacity,s.generations,new Uint32Array(this._columnStore.buffer,this._columnStore.header.entityIndexOff+h.ENTITY_INDEX_HEADER_OFFSETS.length,1)),this._snapshots=new ye({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:n=>{this._tick=n},publishRowCounts:()=>this.publishRowCountsToDescriptor(),mountRestoredDense:n=>this._mountRestoredDense(n),reconstructHostRows:n=>this._reconstructHostRows(n),invalidateQueryCaches:()=>{this._queryDirtyEpoch++,this._rowCountsDirty=!0}},this.entityAllocator),this.archGraph=new Ee({componentMetas:()=>this.componentMetas,initialCapacity:()=>this.initialCapacity,extendStore:n=>this._archExtendStoreWithNewSpecs(n),materialize:(n,r,i)=>this._materializeArchetype(n,r,i),fanIntoQueries:n=>this._fanIntoQueries(n)}),this.emptyArchetypeId=this.archGetOrCreateFromMask(new T.BitSet)}_entityIndexCapacity;_regions;_bindingsRegionBytes;_deterministic;get deterministic(){return this._deterministic}_requireDeterministic(t){if(!this._deterministic)throw new h.ECSError(h.ECS_ERROR.DETERMINISM_DISABLED,`${t} 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(t,e,s){if(this._deterministic)for(let n=0;n<e.length;n++){const r=e[n];if(r==="f32"||r==="f64")throw new h.ECSError(h.ECS_ERROR.NON_DETERMINISTIC_COLUMN_TYPE,`Cannot register ${s} field "${t[n]}" as "${r}" 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:t[n],type:r,kind:s})}}_refreshEntityIndexViews(){const t=this._columnStore.view.getUint32(h.STORE_HEADER_OFFSETS.entity_index_off,!0),e=h.buildEntityIndexViews(this._columnStore.buffer,t,this._entityIndexCapacity);this.entityArchetype=e.archetypes,this.entityRow=e.rows,this.entityAllocator.replantViews(e.generations,new Uint32Array(this._columnStore.buffer,t+h.ENTITY_INDEX_HEADER_OFFSETS.length,1))}_handleBufferResized(){this._refreshEntityIndexViews(),this.entityAllocator.publishLength(),this._onBufferResized?.()}get columnStore(){return this._columnStore}regionOffset(t){return h.findRegionOffset(this._columnStore.view,t)}regionHandle(t){const e=h.findRegionEntry(this._columnStore.view,t);return e===null?null:{buffer:this._columnStore.buffer,view:this._columnStore.view,offset:e.byteOffset,bytes:e.byteLength}}publishRowCountsToDescriptor(){if(!this._rowCountsDirty)return;const t=this._columnStore.view;let e=t.getUint32(h.STORE_HEADER_OFFSETS.layout_descriptor_off,!0);const s=this.archGraph.archetypes;for(let n=0;n<s.length;n++){const r=s[n];if(!r.isBufferBacked)continue;const i=t.getUint32(e+h.ARCHETYPE_DESCRIPTOR_OFFSETS.column_count,!0);t.setUint32(e+h.ARCHETYPE_DESCRIPTOR_OFFSETS.row_count,r.hasColumns?r.length:0,!0),t.setUint32(e+h.ARCHETYPE_DESCRIPTOR_OFFSETS.enabled_count,r.hasColumns?r.enabledCount:0,!0),e+=h.ARCHETYPE_DESCRIPTOR_HEADER_BYTES+i*h.COLUMN_DESCRIPTOR_BYTES}this._rowCountsDirty=!1}stateHash(){this._requireDeterministic("state_hash()");let t=h.FNV1A_OFFSET_BASIS;const e=this.archGraph.archetypes;for(let r=0;r<e.length;r++){const i=e[r],o=i.id,a=i.length;if(t=h.fnv1aStepWord(t,o),t=h.fnv1aStepWord(t,a),t=h.fnv1aStepWord(t,i.enabledCount),a===0)continue;const l=i._flatColumns;for(let u=0;u<l.length;u++){const d=l[u].buf,f=a*d.BYTES_PER_ELEMENT,p=new Uint8Array(d.buffer,d.byteOffset,f),y=f>>>2;let g=0;for(let _=0;_<y;_++){const m=(p[g]|p[g+1]<<8|p[g+2]<<16|p[g+3]<<24)>>>0;t=(t^m)>>>0,t=Math.imul(t,h.FNV1A_PRIME),g+=4}const E=f&3;if(E!==0){let _=p[g];E>1&&(_|=p[g+1]<<8),E>2&&(_|=p[g+2]<<16),t=(t^_>>>0)>>>0,t=Math.imul(t,h.FNV1A_PRIME)}}}const s=this.sparseStores;for(let r=0;r<s.length;r++){const i=s[r];t=h.fnv1aStepWord(t,r),t=h.fnv1aStepWord(t,i.size);const o=i.canonicalIndices();for(let a=0;a<o.length;a++){const l=o[a];t=h.fnv1aStepWord(t,l);const u=i.getRow(l);for(let d=0;d<u.length;d++)Z.setFloat64(0,u[d],!0),t=h.fnv1aStepWord(t,Z.getUint32(0,!0)),t=h.fnv1aStepWord(t,Z.getUint32(4,!0))}}const n=this.relationService.stores;for(let r=0;r<n.length;r++){const i=n[r];i.exclusive||(t=h.fnv1aStepWord(t,r),i.forEachCanonicalTargetSet((o,a)=>{t=h.fnv1aStepWord(t,o),t=h.fnv1aStepWord(t,a.length);for(let l=0;l<a.length;l++)t=h.fnv1aStepWord(t,a[l])}))}return t>>>0}archGet(t){return this.archGraph.get(t)}entityIdAtRow(t,e){return this.archGet(t).entityIds[e]}archGetOrCreateFromMask(t){return this.archGraph.getOrCreateFromMask(t)}archCreateManyFromMasks(t){return this.archGraph.createManyFromMasks(t)}_archExtendStoreWithNewSpecs(t){const e=[],s=this.archGraph.archetypes;for(let r=0;r<s.length;r++){const i=s[r],o=this._columnStore.archetypes.get(i.id);o!==void 0&&e.push({archetypeId:i.id,newRowCapacity:o.rowCapacity,rowCount:i.hasColumns?i.length:0})}let n;try{n=ce(this._columnStore,{newArchetypes:t,existing:e},this._bufferAllocator)}catch(r){throw r instanceof V.StoreCapExceededError?this._capExceededError(r):r}if(this._columnStore=n.store,!n.viewsPreserved)for(let r=0;r<s.length;r++)s[r].isBufferBacked&&s[r].refreshViews(this._columnStore);this._handleBufferResized()}_materializeArchetype(t,e,s){const n=at.fromColumnStore(t,e,s,this._columnStore,t);return n.growHandler=this._growHandler,n}_fanIntoQueries(t){const e=this.registeredQueries;for(let s=0;s<e.length;s++){const n=e[s];t.matches(n.includeMask)&&(!n.excludeMask||!t.mask.overlaps(n.excludeMask))&&(!n.anyOfMask||t.mask.overlaps(n.anyOfMask))&&n.result.push(t)}}archResolveAdd(t,e){return this.archGraph.resolveAdd(t,e)}archResolveRemove(t,e){return this.archGraph.resolveRemove(t,e)}createEntity(){const t=this.entityAllocator.alloc(),e=this.entityAllocator.lastIndex;return this.entityArchetype[e]=this.emptyArchetypeId,this.entityRow[e]=h.UNASSIGNED,t}_allocEntity(){return this.entityAllocator.alloc()}_ensureEntityIndexCapacity(t){this.entityAllocator.ensureCapacity(t)}resolveTemplate(t){const e=new T.BitSet;for(let a=0;a<t.length;a++)e.set(t[a].def.id);const s=this.archGetOrCreateFromMask(e),n=this.archGet(s),r=new Array(n._flatColumns.length).fill(0),i=new Map,o=new Array(t.length);for(let a=0;a<t.length;a++){o[a]=t[a].def;const l=t[a].def.id,u=this.componentMetas[l];if(u===void 0)throw new h.ECSError(h.ECS_ERROR.COMPONENT_NOT_REGISTERED,`template: component ${l} is not registered`);const d=t[a].values??h.EMPTY_VALUES,f=n._colOffset[l];for(let p=0;p<u.fieldNames.length;p++){const y=u.fieldNames[p];r[f+p]=d[y]??0,i.set(y,i.has(y)?gt:f+p)}}return{archetypeId:s,flatValues:r,overrideIndex:i,defs:o}}_resolveOverrideColumn(t,e){const s=t.overrideIndex.get(e);return s===void 0||s===gt?-1:s}_applyOverrides(t,e,s,n){const r=t._flatColumns;for(const i in n){if(n[i]===void 0)continue;const o=this._resolveOverrideColumn(s,i);o>=0&&(r[o].buf[e]=n[i])}}_applyOverridesRange(t,e,s,n,r){const i=t._flatColumns;for(const o in r){if(r[o]===void 0)continue;const a=this._resolveOverrideColumn(n,o);a>=0&&i[a].buf.fill(r[o],e,e+s)}}spawn(t,e){const s=this.archGraph.archetypes[t.archetypeId];s.materializesRows&&s.ensureRowCapacity(1);const n=this._allocEntity(),r=this.entityAllocator.lastIndex;if(!s.materializesRows)return this.entityArchetype[r]=t.archetypeId,this.entityRow[r]=h.UNASSIGNED,n;const i=s.length,o=s.enabledCount,a=s.addEntityWithValues(n,t.flatValues,this._tick,this.entityRow);return e!==void 0&&this._applyOverrides(s,a,t,e),this.entityArchetype[r]=t.archetypeId,this.entityRow[r]=a,this._onArchGrow(s,i,o),n}spawnMany(t,e,s){if(e<=0)return[];const n=this.archGraph.archetypes[t.archetypeId];this._ensureEntityIndexCapacity(e),n.ensureRowCapacity(e);const r=new Array(e),i=new Uint32Array(e);for(let f=0;f<e;f++){const p=this._allocEntity();i[f]=p,r[f]=p}const o=this.entityArchetype,a=this.entityRow;if(!n.materializesRows){for(let f=0;f<e;f++){const p=h.getEntityIndex(r[f]);o[p]=t.archetypeId,a[p]=h.UNASSIGNED}return r}const l=n.length,u=n.enabledCount;if(n.disabledCount>0){for(let f=0;f<e;f++){const p=n.addEntityWithValues(r[f],t.flatValues,this._tick,a),y=h.getEntityIndex(r[f]);o[y]=t.archetypeId,a[y]=p,s!==void 0&&this._applyOverrides(n,p,t,s)}return this._onArchGrow(n,l,u),r}const d=n.addEntitiesWithValues(i,e,t.flatValues,this._tick);for(let f=0;f<e;f++){const p=h.getEntityIndex(r[f]);o[p]=t.archetypeId,a[p]=d+f}return s!==void 0&&this._applyOverridesRange(n,d,e,t,s),this._onArchGrow(n,l,u),r}destroyEntity(t){if(!this.isAlive(t))return;if(!this.relationService.hasTargetCleanup){this._destroyOne(t,null);return}const e=[t];for(let s=0;s<e.length;s++){const n=e[s];this.isAlive(n)&&this._destroyOne(n,e)}}_destroyOne(t,e){const s=h.getEntityIndex(t),n=this.entityRow[s];if(n!==h.UNASSIGNED){const r=this.archGet(this.entityArchetype[s]),i=r.length;r.removeRow(n,this.entityRow),this._onArchLenChange(r,i)}this.entityArchetype[s]=h.UNASSIGNED,this.entityRow[s]=h.UNASSIGNED,this.relationService.count>0&&(this.relationService.purgeSource(t),e!==null&&this.relationService.cleanupTarget(t,e)),this.sparseStores.length>0&&this._purgeSparse(s),this._anyDirtyTracked&&this._clearDirtyForIndex(s),this.entityAllocator.recycle(s,h.getEntityGeneration(t))}isAlive(t){if(t<0||t>h.MAX_ENTITY_ID)return!1;const e=h.getEntityGeneration(t);if(e===h.RETIRED_GENERATION)return!1;const s=h.getEntityIndex(t);return this.entityAllocator.isAliveIndex(s,e)}get entityCount(){return this.entityAllocator.aliveCount}_onArchLenChange(t,e){this._rowCountsDirty=!0,e===0!=(t.length===0)&&this._queryDirtyEpoch++}_onArchGrow(t,e,s){this._rowCountsDirty=!0,(e===0||s===0&&t.enabledCount!==0)&&this._queryDirtyEpoch++}_onArchEnabledChange(t,e){this._rowCountsDirty=!0,e===0!=(t.enabledCount===0)&&this._queryDirtyEpoch++}disableEntity(t){if(!this.isAlive(t))return;const e=h.getEntityIndex(t),s=this.entityRow[e];if(s===h.UNASSIGNED)return;const n=this.archGet(this.entityArchetype[e]);if(s>=n.enabledCount)return;const r=n.enabledCount;n.disableRow(s,this.entityRow),this._onArchEnabledChange(n,r)}enableEntity(t){if(!this.isAlive(t))return;const e=h.getEntityIndex(t),s=this.entityRow[e];if(s===h.UNASSIGNED)return;const n=this.archGet(this.entityArchetype[e]);if(s<n.enabledCount)return;const r=n.enabledCount;n.enableRow(s,this.entityRow),this._onArchEnabledChange(n,r)}isDisabled(t){if(!this.isAlive(t))return!1;const e=h.getEntityIndex(t),s=this.entityRow[e];if(s===h.UNASSIGNED)return!1;const n=this.archGet(this.entityArchetype[e]);return s>=n.enabledCount}_flushEpoch=0;_flushTouched=[];_settleFlushDirty(){const t=this._flushTouched;if(t.length===0)return;this._rowCountsDirty=!0;let e=!1;for(let s=0;s<t.length;s++){const n=t[s];(n._flushPreLen===0!=(n.length===0)||n._flushPreEnabled===0!=(n.enabledCount===0))&&(e=!0)}e&&this._queryDirtyEpoch++,t.length=0,this._flushEpoch++}destroyEntityDeferred(t){this._deferred.queueDestroy(t)}disableEntityDeferred(t){this._deferred.queueToggle(t,!0)}enableEntityDeferred(t){this._deferred.queueToggle(t,!1)}_flushToggles(){const t=this._deferred.toggleIds,e=this._deferred.toggleDisable,s=t.length;if(!(this._toggleObserverCount>0)){for(let i=0;i<s;i++){const o=t[i];this.isAlive(o)&&(e[i]?this.disableEntity(o):this.enableEntity(o))}t.length=0,e.length=0;return}const r=this._toggleInitial;for(let i=0;i<s;i++){const o=t[i];this.isAlive(o)&&(r.has(o)||r.set(o,this.isDisabled(o)))}for(let i=0;i<s;i++){const o=t[i];this.isAlive(o)&&(e[i]?this.disableEntity(o):this.enableEntity(o))}t.length=0,e.length=0;for(const[i,o]of r){if(!this.isAlive(i))continue;const a=this.isDisabled(i);o!==a&&this._collectToggle(i,a)}r.clear()}_collectToggle(t,e){const s=h.getEntityIndex(t);if(this.entityRow[s]===h.UNASSIGNED)return;const n=this.archGet(this.entityArchetype[s]);this._collectToggleEid=t,n.mask.forEach(e?this._collectDisableBit:this._collectEnableBit)}get pendingToggleCount(){return this._deferred.toggleCount}flushDestroyed(){this._deferred.flushDestroyed()}_drainDestroyed(){const t=this._deferred.destroyIds;if(t.length===0)return;const e=this.entityAllocator,s=this.entityArchetype,n=this.entityRow,r=e.generations,i=this.archGraph.archetypes,o=e.highWater;let a=!1,l=!1;const u=this.sparseStores.length>0,d=this.relationService.count>0,f=d&&this.relationService.hasTargetCleanup,p=this._anyDirtyTracked,y=this._structuralObserverCount>0;for(let g=0;g<t.length;g++){const E=t[g],_=E&h.INDEX_MASK,m=E>>h.INDEX_BITS;if(_>=o||r[_]!==m)continue;const S=n[_];if(S!==h.UNASSIGNED){const v=i[s[_]];y&&(this._collectDestroyEid=E,v.mask.forEach(this._collectDestroyRemoveBit)),v.removeRow(S,n),a=!0,v.length===0&&(l=!0)}d&&this.relationService.purgeSource(E),f&&this.relationService.cleanupTarget(E,t),u&&this._purgeSparse(_),p&&this._clearDirtyForIndex(_),s[_]=h.UNASSIGNED,n[_]=h.UNASSIGNED,e.recycle(_,m)}t.length=0,a&&(this._rowCountsDirty=!0,l&&this._queryDirtyEpoch++)}get pendingDestroyCount(){return this._deferred.destroyCount}addComponentDeferred(t,e,s){this._deferred.queueAdd(t,e,s??h.EMPTY_VALUES)}removeComponentDeferred(t,e){this._deferred.queueRemove(t,e)}flushStructural(){this._deferred.flushStructural()}_flushAdds(){const t=this._deferred.addIds,e=this._deferred.addDefs,s=this._deferred.addValues,n=t.length,r=this.entityArchetype,i=this.entityRow,o=this.entityAllocator.generations,a=this.archGraph.archetypes,l=this.componentMetas,u=this.entityAllocator.highWater,d=this._tick,f=this._flushEpoch,p=this._flushTouched,y=this._structuralObserverCount>0,g=this._obsEvents;for(let E=0;E<n;E++){const _=t[E],m=_&h.INDEX_MASK,S=_>>h.INDEX_BITS;if(m>=u||o[m]!==S)continue;const v=r[m],C=e[E].id,R=a[v],w=l[C];if(R.mask.has(C)){w.fieldNames.length>0&&R.writeFields(i[m],C,s[E],d);continue}const k=this.archResolveAdd(v,C),I=a[k],F=i[m],lt=!I.hasColumns&&!R.hasColumns;F!==h.UNASSIGNED&&R._flushSeenEpoch!==f&&(R._flushSeenEpoch=f,R._flushPreLen=R.length,R._flushPreEnabled=R.enabledCount,p.push(R)),I._flushSeenEpoch!==f&&(I._flushSeenEpoch=f,I._flushPreLen=I.length,I._flushPreEnabled=I.enabledCount,p.push(I));let W;if(F!==h.UNASSIGNED){if(lt)I.moveEntityFromTag(R,F,_,i);else{const Ft=R.getEdge(C);I.moveEntityFrom(R,F,_,Ft.addMap,d,i)}W=A[0]}else W=lt?I.addEntityTag(_,i):I.addEntity(_,i);w.fieldNames.length>0&&I.writeFields(W,C,s[E],d),r[m]=k,i[m]=W,y&&w.obsAdd&&(g.addComp[g.addLen]=C,g.addEid[g.addLen]=_,g.addLen++)}t.length=0,e.length=0,s.length=0,this._settleFlushDirty()}_flushRemoves(){const t=this._deferred.removeIds,e=this._deferred.removeDefs,s=t.length,n=this.entityArchetype,r=this.entityRow,i=this.entityAllocator.generations,o=this.archGraph.archetypes,a=this.entityAllocator.highWater,l=this._tick,u=this._flushEpoch,d=this._flushTouched,f=this.componentMetas,p=this._structuralObserverCount>0,y=this._obsEvents;for(let g=0;g<s;g++){const E=t[g],_=E&h.INDEX_MASK,m=E>>h.INDEX_BITS;if(_>=a||i[_]!==m)continue;const S=n[_],v=e[g].id,C=o[S];if(!C.mask.has(v))continue;const R=this.archResolveRemove(S,v),w=o[R],k=r[_],I=!w.hasColumns&&!C.hasColumns;if(C._flushSeenEpoch!==u&&(C._flushSeenEpoch=u,C._flushPreLen=C.length,C._flushPreEnabled=C.enabledCount,d.push(C)),w._flushSeenEpoch!==u&&(w._flushSeenEpoch=u,w._flushPreLen=w.length,w._flushPreEnabled=w.enabledCount,d.push(w)),I)w.moveEntityFromTag(C,k,E,r);else{const F=C.getEdge(v);w.moveEntityFrom(C,k,E,F.removeMap,l,r)}n[_]=R,r[_]=A[0],p&&f[v].obsRem&&(y.remComp[y.remLen]=v,y.remEid[y.remLen]=E,y.remLen++)}t.length=0,e.length=0,this._settleFlushDirty()}get pendingStructuralCount(){return this._deferred.structuralCount}_configureComponentObservation(t,e,s,n,r,i){const o=this.componentMetas[t];if(o===void 0)throw new h.ECSError(h.ECS_ERROR.COMPONENT_NOT_REGISTERED,`observe(): component ${t} is not registered`);const a=o.obsAdd||o.obsRem;o.obsAdd=e,o.obsRem=s;const l=e||s;a&&!l?this._structuralObserverCount--:!a&&l&&this._structuralObserverCount++;const u=o.obsDisable||o.obsEnable;o.obsDisable=n,o.obsEnable=r;const d=n||r;if(u&&!d?this._toggleObserverCount--:!u&&d&&this._toggleObserverCount++,i&&!o.trackDirty)o.trackDirty=!0,this._dirtyLists[t]===void 0&&(this._dirtyLists[t]=[],this._dirtyMarks[t]=new Uint8Array(Math.max(1,this.entityAllocator.generations.length))),this._dirtyTrackedCids.push(t),this._anyDirtyTracked=!0;else if(!i&&o.trackDirty){o.trackDirty=!1;const f=this._dirtyTrackedCids.indexOf(t);f>=0&&this._dirtyTrackedCids.splice(f,1),this._anyDirtyTracked=this._dirtyTrackedCids.length>0;const p=this._dirtyLists[t],y=this._dirtyMarks[t];if(p!==void 0&&y!==void 0){for(let g=0;g<p.length;g++)y[p[g]&h.INDEX_MASK]=0;p.length=0}}}_noteSet(t,e){const s=t.id,n=this.componentMetas[s];if(n===void 0||!n.trackDirty)return;const r=e&h.INDEX_MASK;let i=this._dirtyMarks[s];r>=i.length&&(i=this._growDirtyMarks(s,r)),i[r]===0&&(i[r]=1,this._dirtyLists[s].push(e))}_growDirtyMarks(t,e){const s=this._dirtyMarks[t];let n=Math.max(1,s.length);for(;n<=e;)n*=2;const r=new Uint8Array(n);return r.set(s),this._dirtyMarks[t]=r,r}_takeDirty(t){const e=this._dirtyLists[t];if(e===void 0||e.length===0)return me;this._dirtyLists[t]=[];const s=this._dirtyMarks[t];for(let n=0;n<e.length;n++)s[e[n]&h.INDEX_MASK]=0;return e}_clearDirtyForIndex(t){const e=this._dirtyTrackedCids;for(let s=0;s<e.length;s++){const n=this._dirtyMarks[e[s]];n!==void 0&&t<n.length&&(n[t]=0)}}_forEachChangedArchetype(t,e,s){const n=this.archGraph.componentIndex[t];if(n===void 0)return;const r=this.archGraph.archetypes;for(let i=0;i<n.length;i++){const o=r[n[i]];o.length>0&&o._changedTick[t]>=e&&s(o)}}_collectEntitiesWithComponent(t){const e=[],s=this.archGraph.componentIndex[t];if(s===void 0)return e;const n=this.archGraph.archetypes;for(let r=0;r<s.length;r++){const i=n[s[r]],o=i.entityIds;for(let a=0;a<i.enabledCount;a++)e.push(h.unsafeCast(o[a]))}return e}registerComponent(t,e){if(this.componentCount>=h.STORE_DESCRIPTOR_COMPONENT_LIMIT)throw new h.ECSError(h.ECS_ERROR.COMPONENT_LIMIT_EXCEEDED,`Cannot register more than ${h.STORE_DESCRIPTOR_COMPONENT_LIMIT} components: the SAB archetype descriptor mask is ${h.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:h.STORE_DESCRIPTOR_COMPONENT_LIMIT});const s=Object.keys(t),n=new Array(s.length),r=Object.create(null);for(let a=0;a<s.length;a++)r[s[a]]=a,n[a]=t[s[a]];this._rejectNonDeterministicFields(s,n,"component");const i=Rt(this.componentCount++);this.componentMetas.push({name:e,fieldNames:s,fieldIndex:r,fieldTypes:n,obsAdd:!1,obsRem:!1,obsDisable:!1,obsEnable:!1,trackDirty:!1});const o=vt(i);return e!==void 0&&h.setComponentDebugName(o,e),o}componentLabel(t){const e=this.componentMetas[t]?.name;return e!==void 0?`'${e}' (component ${t})`:`component ${t}`}fieldIdOf(t,e){const s=t.id,n=this.componentMetas[s];if(n===void 0)throw new h.ECSError(h.ECS_ERROR.COMPONENT_NOT_REGISTERED,`field_id_of: component ${s} is not registered`);const r=n.fieldIndex[e];if(r===void 0)throw new h.ECSError(h.ECS_ERROR.FIELD_NOT_REGISTERED,`field_id_of: component ${s} has no field "${e}"`);return r}registerSparseComponent(t,e){const s=Object.keys(t),n=new Array(s.length);for(let r=0;r<s.length;r++)n[r]=t[s[r]];return this._rejectNonDeterministicFields(s,n,"sparse component"),this._pushSparseStore(s,n,e)}sparseLabel(t){const e=this.sparseNames[t];return e!==void 0?`'${e}' (sparse component ${t})`:`sparse component ${t}`}_pushSparseStore(t,e,s){const n=this.sparseStores.length;return this.sparseStores.push(new h.SparseComponentStore(t,e)),this.sparseNames.push(s),h.unsafeCast(n)}sparseStoreOf(t){const e=t,s=this.sparseStores[e];if(s===void 0)throw new h.ECSError(h.ECS_ERROR.COMPONENT_NOT_REGISTERED,`sparse component ${e} is not registered`);return s}addSparse(t,e,s){this.isAlive(t)&&this.sparseStoreOf(e).setRow(h.getEntityIndex(t),s??h.EMPTY_VALUES)}removeSparse(t,e){this.isAlive(t)&&this.sparseStoreOf(e).remove(h.getEntityIndex(t))}hasSparse(t,e){return this.isAlive(t)?this.sparseStoreOf(e).has(h.getEntityIndex(t)):!1}getSparseField(t,e,s){const n=this.sparseStoreOf(e),r=n.fieldIndex[s];if(r===void 0)return 0;const i=n.getField(h.getEntityIndex(t),r);return i===void 0?0:i}setSparseField(t,e,s,n){const r=this.sparseStoreOf(e),i=r.fieldIndex[s];i!==void 0&&r.setField(h.getEntityIndex(t),i,n)}_purgeSparse(t){const e=this.sparseStores;for(let s=0;s<e.length;s++)e[s].remove(t)}snapshotSparse(){return this._requireDeterministic("snapshot_sparse()"),this._snapshots.snapshotSparse()}restoreSparse(t){this._requireDeterministic("restore_sparse()"),this._snapshots.restoreSparse(t)}snapshot(){return this._requireDeterministic("snapshot()"),this._snapshots.snapshot()}restoreInto(t){this._requireDeterministic("restoreInto()"),this._snapshots.restoreInto(t)}_mountRestoredDense(t){this._columnStore=t;const e=this.archGraph.archetypes;for(let s=0;s<e.length;s++)e[s].isBufferBacked&&e[s].refreshViews(this._columnStore);this.entityAllocator.setHighWater(t.view.getUint32(t.header.entityIndexOff+h.ENTITY_INDEX_HEADER_OFFSETS.length,!0)),this._handleBufferResized()}_reconstructHostRows(t){const e=this.entityAllocator.highWater,s=this.entityArchetype,n=this.entityRow,r=this.entityAllocator.generations,i=new Map;for(let o=0;o<e;o++){const a=s[o];if(a===h.UNASSIGNED)continue;const l=n[o];if(l===h.UNASSIGNED)continue;let u=i.get(a);u===void 0&&(u=[],i.set(a,u)),u[l]=h.createEntityId(o,r[o])}for(let o=0;o<t.archetypeRows.length;o++){const a=t.archetypeRows[o],l=this.archGet(a.archetypeId),u=i.get(a.archetypeId)??[];l.restoreHostRows(u,a.enabledCount)}}registerRelation(t){return this.relationService.registerRelation(t)}get relationCount(){return this.relationService.count}addRelation(t,e,s){this.relationService.addRelation(t,e,s)}removeRelation(t,e,s){this.relationService.removeRelation(t,e,s)}targetOf(t,e){return this.relationService.targetOf(t,e)}targetsOf(t,e){return this.relationService.targetsOf(t,e)}sourcesOf(t,e){return this.relationService.sourcesOf(t,e)}hasRelation(t,e){return this.relationService.hasRelation(t,e)}pairsOf(t){return this.relationService.pairsOf(t)}sourcesOfAny(t){return this.relationService.sourcesOfAny(t)}relationBackingSparseId(t){return this.relationService.relationBackingSparseId(t)}_forEachRelationTargetMatch(t,e,s,n,r,i,o,a){this.relationService.forEachRelationTargetMatch(t,e,s,n,r,i,o,a)}compactRelations(){return this.relationService.compactRelations()}ancestorsOf(t,e){return this.relationService.ancestorsOf(t,e)}rootOf(t,e){return this.relationService.rootOf(t,e)}cascadeOf(t,e){return this.relationService.cascadeOf(t,e)}_forEachSparseMatch(t,e,s,n,r,i,o,a){const l=this.sparseStores;if(n.length>0){let d=l[n[0]];for(let _=1;_<n.length;_++){const m=l[n[_]];m.size<d.size&&(d=m)}const f=d.indices,p=this.entityAllocator.generations,y=this.entityArchetype,g=this.entityRow,E=this.archGraph.archetypes;for(let _=0;_<f.length;_++){const m=f[_];let S=!0;for(let w=0;w<n.length;w++){const k=l[n[w]];if(k!==d&&!k.has(m)){S=!1;break}}if(!S)continue;for(let w=0;w<r.length;w++)if(l[r[w]].has(m)){S=!1;break}if(!S)continue;const v=y[m];if(v===h.UNASSIGNED)continue;const C=E[v],R=C.mask;if(R.contains(t)&&!(e!==null&&R.overlaps(e))&&!(s!==null&&!R.overlaps(s))){if(!a){const w=g[m];if(w!==h.UNASSIGNED&&w>=C.enabledCount)continue}o(h.createEntityId(m,p[m]))}}return}const u=r.length>0;for(let d=0;d<i.length;d++){const f=i[d],p=f.entityIds,y=a?f.totalCount:f.enabledCount;for(let g=0;g<y;g++){const E=p[g];if(u){const _=h.getEntityIndex(E);let m=!1;for(let S=0;S<r.length;S++)if(l[r[S]].has(_)){m=!0;break}if(m)continue}o(E)}}}_forEachHierarchyMatch(t,e,s,n,r,i,o,a,l,u){this.relationService.forEachHierarchyMatch(t,e,s,n,r,i,o,a,l,u)}addComponent(t,e,s){if(!this.isAlive(t))return;const n=h.getEntityIndex(t),r=this.entityArchetype[n],i=this.archGet(r);if(i.hasComponent(e.id)){i.writeFields(this.entityRow[n],e.id,s,this._tick);return}const o=this.archResolveAdd(r,e.id),a=this.archGet(o),l=this.entityRow[n];let u;if(l!==h.UNASSIGNED){const d=i.length,f=a.length,p=a.enabledCount,y=i.getEdge(e.id);!a.hasColumns&&!i.hasColumns?a.moveEntityFromTag(i,l,t,this.entityRow):a.moveEntityFrom(i,l,t,y.addMap,this._tick,this.entityRow),u=A[0],this._onArchLenChange(i,d),this._onArchGrow(a,f,p)}else{const d=a.length,f=a.enabledCount;u=a.hasColumns?a.addEntity(t,this.entityRow):a.addEntityTag(t,this.entityRow),this._onArchGrow(a,d,f)}a.writeFields(u,e.id,s,this._tick),this.entityArchetype[n]=o,this.entityRow[n]=u}addComponents(t,e){if(!this.isAlive(t))return;const s=h.getEntityIndex(t),n=this.entityArchetype[s],r=this.archGet(n),i=e.length;let o=i;for(let f=0;f<i;f++){const p=e[f].def.id;if(p>=yt-1||i>we){o=J;break}o=o*yt+(p+1)}if(o!==J){const f=r.getCompositeAddEdge(o);if(f!==void 0){this._addComponentsInto(t,s,r,this.archGet(f.target),f.target,f.map,e);return}}let a=null;for(let f=0;f<i;f++){const p=e[f].def.id;a!==null?a.set(p):r.mask.has(p)||(a=r.mask.copyInto(this._scratchTargetMask),a.set(p))}if(a===null){const f=this.entityRow[s];for(let p=0;p<i;p++)r.writeFields(f,e[p].def.id,e[p].values??h.EMPTY_VALUES,this._tick);return}const l=this.archGetOrCreateFromMask(a),u=this.archGet(l),d=r.getBatchTransitionMap(u);o!==J&&r.cacheCompositeAddEdge(o,l,d),this._addComponentsInto(t,s,r,u,l,d,e)}_addComponentsInto(t,e,s,n,r,i,o){const a=this.entityRow[e];let l;if(a!==h.UNASSIGNED){const u=s.length,d=n.length,f=n.enabledCount;n.moveEntityFrom(s,a,t,i,this._tick,this.entityRow),l=A[0],this._onArchLenChange(s,u),this._onArchGrow(n,d,f)}else{const u=n.length,d=n.enabledCount;l=n.addEntity(t,this.entityRow),this._onArchGrow(n,u,d)}for(let u=0;u<o.length;u++)n.writeFields(l,o[u].def.id,o[u].values??h.EMPTY_VALUES,this._tick);this.entityArchetype[e]=r,this.entityRow[e]=l}removeComponent(t,e){if(!this.isAlive(t))return;const s=h.getEntityIndex(t),n=this.entityArchetype[s],r=this.archGet(n);if(!r.hasComponent(e.id))return;const i=this.archResolveRemove(n,e.id),o=this.archGet(i),a=this.entityRow[s],l=r.getEdge(e.id),u=!o.hasColumns&&!r.hasColumns,d=r.length,f=o.length,p=o.enabledCount;u?o.moveEntityFromTag(r,a,t,this.entityRow):o.moveEntityFrom(r,a,t,l.removeMap,this._tick,this.entityRow),this.entityArchetype[s]=i,this.entityRow[s]=A[0],this._onArchLenChange(r,d),this._onArchGrow(o,f,p)}removeComponents(t,e){if(!this.isAlive(t))return;const s=h.getEntityIndex(t),n=this.entityArchetype[s],r=this.archGet(n);let i=null;for(let y=0;y<e.length;y++){const g=e[y].id;i!==null?i.clear(g):r.mask.has(g)&&(i=r.mask.copyInto(this._scratchTargetMask),i.clear(g))}if(i===null)return;const o=this.archGetOrCreateFromMask(i),a=this.archGet(o),l=this.entityRow[s],u=r.length,d=a.length,f=a.enabledCount,p=r.getBatchTransitionMap(a);a.moveEntityFrom(r,l,t,p,this._tick,this.entityRow),this.entityArchetype[s]=o,this.entityRow[s]=A[0],this._onArchLenChange(r,u),this._onArchGrow(a,d,f)}hasComponent(t,e){if(!this.isAlive(t))return!1;const s=h.getEntityIndex(t);return this.archGet(this.entityArchetype[s]).hasComponent(e.id)}batchAddComponent(t,e,s){const n=this.archGet(t);if(n.length===0)return;const r=e.id;if(n.mask.has(r))return;const i=this.archResolveAdd(n.id,r),o=this.archGet(i);if(n.disabledCount>0||o.disabledCount>0)throw new h.ECSError(h.ECS_ERROR.PARTITION_BULK_INTO_DISABLED,"batchAddComponent is unsupported on archetypes with disabled entities — enable them first or use per-entity addComponent");const a=n.getEdge(r),l=n.length,u=l,d=o.length,f=o.enabledCount,p=this.entityArchetype,y=this.entityRow,g=o.bulkMoveAllFrom(n,a.addMap,this._tick);for(let _=0;_<l;_++){const m=h.getEntityIndex(o.entityIds[g+_]);p[m]=i,y[m]=g+_}this.componentMetas[r].fieldNames.length>0&&s&&o.bulkWriteFields(g,l,r,s,this._tick),this._onArchLenChange(n,u),this._onArchGrow(o,d,f)}batchRemoveComponent(t,e){const s=this.archGet(t);if(s.length===0)return;const n=e.id;if(!s.mask.has(n))return;const r=this.archResolveRemove(s.id,n),i=this.archGet(r);if(s.disabledCount>0||i.disabledCount>0)throw new h.ECSError(h.ECS_ERROR.PARTITION_BULK_INTO_DISABLED,"batchRemoveComponent is unsupported on archetypes with disabled entities — enable them first or use per-entity removeComponent");const o=s.getEdge(n),a=s.length,l=a,u=this.entityArchetype,d=this.entityRow;if(!i.materializesRows){const g=s.entityIds;for(let E=0;E<a;E++){const _=h.getEntityIndex(g[E]);u[_]=r,d[_]=h.UNASSIGNED}s.clearRows(),this._onArchLenChange(s,l);return}const f=i.length,p=i.enabledCount,y=i.bulkMoveAllFrom(s,o.removeMap,this._tick);for(let g=0;g<a;g++){const E=h.getEntityIndex(i.entityIds[y+g]);u[E]=r,d[E]=y+g}this._onArchLenChange(s,l),this._onArchGrow(i,f,p)}getEntityArchetype(t){return this.archGet(this.entityArchetype[h.getEntityIndex(t)])}getEntityRow(t){return this.entityRow[h.getEntityIndex(t)]}getMatchingArchetypes(t,e,s){const n=t._words;let r=!1;for(let l=0;l<n.length;l++)if(n[l]!==0){r=!0;break}if(!r){const l=this.archGraph.archetypes,u=[];for(let d=0;d<l.length;d++){const f=l[d];(!e||!f.mask.overlaps(e))&&(!s||f.mask.overlaps(s))&&u.push(f)}return u}let i,o=!1;for(let l=0;l<n.length;l++){let u=n[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 y=this.archGraph.componentIndex[p];if(y===void 0||y.length===0){o=!0;break}(!i||y.length<i.length)&&(i=y)}if(o)break}if(o||!i)return[];const a=[];for(let l=0;l<i.length;l++){const u=this.archGet(i[l]);u.matches(t)&&(!e||!u.mask.overlaps(e))&&(!s||u.mask.overlaps(s))&&a.push(u)}return a}registerQuery(t,e,s){const n=this.getMatchingArchetypes(t,e,s);return this.registeredQueries.push({includeMask:t.copy(),excludeMask:e?e.copy():null,anyOfMask:s?s.copy():null,result:n,query:null}),n}updateQueryRef(t,e){const s=this.registeredQueries;for(let n=0;n<s.length;n++)if(s[n].result===t){s[n].query=e;return}}get archetypeCount(){return this.archGraph.archetypes.length}registerEvent(t){return this.events.registerEvent(t)}emitEvent(t,e){this.events.emitEvent(t,e)}emitSignal(t){this.events.emitSignal(t)}getEventReader(t){return this.events.getEventReader(t)}clearEvents(){this.events.clearEvents()}_devBufferedEventCount(){return this.events.devBufferedEventCount()}registerEventByKey(t,e){return this.events.registerEventByKey(t,e)}getEventDefByKey(t){return this.events.getEventDefByKey(t)}hasEventKey(t){return this.events.hasEventKey(t)}resources=new qt;registerResource(t,e){this.resources.register(t,e)}getResource(t){return this.resources.get(t)}setResource(t,e){this.resources.set(t,e)}removeResource(t){this.resources.remove(t)}hasResource(t){return this.resources.has(t)}}class Ce{store;constructor(t){this.store=t}register(t){return this.store.registerRelation(t)}get count(){return this.store.relationCount}add(t,e,s){return this.store.addRelation(t,e,s),this}remove(t,e,s){return this.store.removeRelation(t,e,s),this}has(t,e){return this.store.hasRelation(t,e)}targetOf(t,e){return this.store.targetOf(t,e)}targetsOf(t,e){return this.store.targetsOf(t,e)}sourcesOf(t,e){return this.store.sourcesOf(t,e)}pairsOf(t){return this.store.pairsOf(t)}sourcesOfAny(t){return this.store.sourcesOfAny(t)}ancestorsOf(t,e){return this.store.ancestorsOf(t,e)}rootOf(t,e){return this.store.rootOf(t,e)}cascadeOf(t,e){return this.store.cascadeOf(t,e)}compact(){return this.store.compactRelations()}}class Re{store;constructor(t){this.store=t}register(t,e){this.store.registerEventByKey(t,e)}registerSignal(t){this.store.registerEventByKey(t,[])}emit(t,e){const s=this.store.getEventDefByKey(t);e===void 0?this.store.emitSignal(s):this.store.emitEvent(s,e)}read(t){const e=this.store.getEventDefByKey(t);return this.store.getEventReader(e)}}class ve{store;constructor(t){this.store=t}register(t,e){this.store.registerResource(t,e)}get(t){return h.unsafeCast(this.store.getResource(t))}set(t,e){this.store.setResource(t,e)}remove(t){this.store.removeResource(t)}has(t){return this.store.hasResource(t)}}class be{store;constructor(t){this.store=t}get deterministic(){return this.store.deterministic}stateHash(){return this.store.stateHash()}capture(){return this.store.snapshot()}restore(t){this.store.restoreInto(t)}captureSparse(){return this.store.snapshotSparse()}restoreSparse(t){this.store.restoreSparse(t)}}const Et=new WeakMap;function it(c,t){let e=Et.get(c);if(!e){e=Object.create(null);const{fieldNames:n}=c.layout;for(let r=0;r<n.length;r++){const i=c.columns[r];Object.defineProperty(e,n[r],{get(){return i.buf[this._row]},set(o){i.buf[this._row]=o},enumerable:!0,configurable:!1})}Et.set(c,e)}const s=Object.create(e);return s._row=t,s}class Ie{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(t,e,s,n){const r=this.dedup.get(t);if(r)for(let i=0;i<r.length;i++){const o=r[i];if(!(!o.includeMask.equals(e)||!(s===null?o.excludeMask===null:o.excludeMask!==null&&o.excludeMask.equals(s))||!(n===null?o.anyOfMask===null:o.anyOfMask!==null&&o.anyOfMask.equals(n))))return o}}addDedup(t,e){Dt(this.dedup,t,e)}}const mt=Object.freeze([]),Ae=Object.freeze([]),wt=Object.freeze([]),ot=Number.POSITIVE_INFINITY;function H(c,t){return(c<<16|t)>>>0}function j(c,t){for(let e=0;e<c.length;e++)if(c[e]===t)return c;return[...c,t]}function Oe(c,t){for(let e=0;e<c.length;e++)if(c[e]===t)return c;return[...c,t]}function St(c,t){for(let e=0;e<c.length;e++)if(c[e]===t)return c;return[...c,t]}class kt{_arch;_tick=0;mut(t){return this._arch.columnGroupMut(t,this._tick)}read(t){return this._arch.columnGroupRead(t)}}class D{_archetypes;_defs;_resolver;_include;_exclude;_anyOf;_nonEmptyArchetypes=[];_lastSeenEpoch=-1;_id;_sparseInclude;_sparseExclude;_optional;_includeDisabled;_relationIncludes;_relationExcludes;_hierarchy;constructor(t,e,s,n,r,i,o,a=mt,l=mt,u=Ae,d=!1,f=wt,p=wt,y=null){this._archetypes=t,this._defs=e,this._resolver=s,this._include=n,this._exclude=r,this._anyOf=i,this._id=o,this._sparseInclude=a,this._sparseExclude=l,this._optional=u,this._includeDisabled=d,this._relationIncludes=f,this._relationExcludes=p,this._hierarchy=y}_assertDenseOnly(t){if(this._sparseInclude.length>0||this._sparseExclude.length>0||this._relationIncludes.length>0||this._relationExcludes.length>0||this._hierarchy!==null)throw new h.ECSError(h.ECS_ERROR.SPARSE_QUERY_DENSE_PATH,`Query.${t} 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 e=this._nonEmpty();for(let s=0;s<e.length;s++)if((this._includeDisabled?e[s].totalCount:e[s].enabledCount)>0)return e[s].entityIds[0];return}let t;return this.forEachEntity(e=>{t===void 0&&(t=e)}),t}singleEntity(){return this.firstEntity()}_countViaWalk(){let t=0;return this.forEachEntity(()=>{t++}),t}get archetypeCount(){return this._archetypes.length}get entityCount(){const t=this._nonEmpty();let e=0;if(this._includeDisabled)for(let s=0;s<t.length;s++)e+=t[s].totalCount;else for(let s=0;s<t.length;s++)e+=t[s].enabledCount;return e}get archetypes(){return this._archetypes}_carryNondense(t){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?t:new D(t._archetypes,t._defs,this._resolver,t._include,t._exclude,t._anyOf,this._resolver._nextQueryId(),this._sparseInclude,this._sparseExclude,this._optional,this._includeDisabled,this._relationIncludes,this._relationExcludes,this._hierarchy)}and(...t){if(t.length===1){const s=t[0].id,n=(this._id<<16|s)>>>0,r=this._resolver._caches.andSingle.get(n);return r!==void 0?r:this._andMiss(t[0],s,n)}let e=this;for(let s=0;s<t.length;s++)e=e.and(t[s]);return e}_andMiss(t,e,s){const n=this._include.copy(),r=this._defs.slice();n.has(e)||(n.set(e),r.push(t));const i=this._carryNondense(this._resolver._resolveQuery(n,this._exclude,this._anyOf,r));return this._resolver._caches.andSingle.set(s,i),i}without(...t){if(t.length===1){const s=t[0].id,n=(this._id<<16|s)>>>0,r=this._resolver._caches.notSingle.get(n);return r!==void 0?r:this._notMiss(s,n)}let e=this;for(let s=0;s<t.length;s++)e=e.without(t[s]);return e}_notMiss(t,e){const s=this._exclude?this._exclude.copy():new T.BitSet;s.set(t);const n=this._carryNondense(this._resolver._resolveQuery(this._include,s,this._anyOf,this._defs));return this._resolver._caches.notSingle.set(e,n),n}withSparse(...t){if(t.length===1)return this._withSparseOne(t[0]);let e=this;for(let s=0;s<t.length;s++)e=e._withSparseOne(t[s]);return e}_withSparseOne(t){const e=H(this._id,t),s=this._resolver._caches.withSparseSingle,n=s.get(e);if(n!==void 0)return n;const r=this._deriveSparse(j(this._sparseInclude,t),this._sparseExclude);return s.set(e,r),r}withoutSparse(...t){if(t.length===1)return this._withoutSparseOne(t[0]);let e=this;for(let s=0;s<t.length;s++)e=e._withoutSparseOne(t[s]);return e}_withoutSparseOne(t){const e=H(this._id,t),s=this._resolver._caches.withoutSparseSingle,n=s.get(e);if(n!==void 0)return n;const r=this._deriveSparse(this._sparseInclude,j(this._sparseExclude,t));return s.set(e,r),r}_deriveSparse(t,e){return new D(this._archetypes,this._defs,this._resolver,this._include,this._exclude,this._anyOf,this._resolver._nextQueryId(),t,e,this._optional,this._includeDisabled,this._relationIncludes,this._relationExcludes,this._hierarchy)}withRelation(...t){if(t.length===1)return this._withRelationOne(t[0]);let e=this;for(let s=0;s<t.length;s++)e=e._withRelationOne(t[s]);return e}_withRelationOne(t){const e=H(this._id,t),s=this._resolver._caches.withRelationSingle,n=s.get(e);if(n!==void 0)return n;const r=this._resolver._relationBackingSparseId(t),i=this._deriveRelation(j(this._sparseInclude,r),this._sparseExclude,St(this._relationIncludes,t),this._relationExcludes);return s.set(e,i),i}withoutRelation(...t){if(t.length===1)return this._withoutRelationOne(t[0]);let e=this;for(let s=0;s<t.length;s++)e=e._withoutRelationOne(t[s]);return e}_withoutRelationOne(t){const e=H(this._id,t),s=this._resolver._caches.withoutRelationSingle,n=s.get(e);if(n!==void 0)return n;const r=this._resolver._relationBackingSparseId(t),i=this._deriveRelation(this._sparseInclude,j(this._sparseExclude,r),this._relationIncludes,St(this._relationExcludes,t));return s.set(e,i),i}_deriveRelation(t,e,s,n){return new D(this._archetypes,this._defs,this._resolver,this._include,this._exclude,this._anyOf,this._resolver._nextQueryId(),t,e,this._optional,this._includeDisabled,s,n,this._hierarchy)}hierarchy(t,e=ot){if(e===ot){const s=H(this._id,t),n=this._resolver._caches.hierarchySingle,r=n.get(s);if(r!==void 0)return r;const i=this._deriveHierarchy({relation:t,maxDepth:e});return n.set(s,i),i}return this._deriveHierarchy({relation:t,maxDepth:e})}_deriveHierarchy(t){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,t)}_checkRelationAccess(){for(let t=0;t<this._relationIncludes.length;t++)h.accessCheck.checkRelationRead(this._relationIncludes[t]);for(let t=0;t<this._relationExcludes.length;t++)h.accessCheck.checkRelationRead(this._relationExcludes[t])}forEachRelatedTo(t,e){this._resolver._forEachRelationTargetMatch(t,this._include,this._exclude,this._anyOf,this._sparseInclude,this._sparseExclude,this._includeDisabled,e)}optional(...t){if(t.length===1)return this._optionalOne(t[0].id);let e=this;for(let s=0;s<t.length;s++)e=e._optionalOne(t[s].id);return e}_optionalOne(t){const e=(this._id<<16|t)>>>0,s=this._resolver._caches.optionalSingle,n=s.get(e);if(n!==void 0)return n;const r=this._deriveOptional(Oe(this._optional,t));return s.set(e,r),r}_deriveOptional(t){return new D(this._archetypes,this._defs,this._resolver,this._include,this._exclude,this._anyOf,this._resolver._nextQueryId(),this._sparseInclude,this._sparseExclude,t,this._includeDisabled,this._relationIncludes,this._relationExcludes,this._hierarchy)}includeDisabled(){if(this._includeDisabled)return this;const t=this._resolver._caches.includeDisabledSingle,e=t.get(this._id);if(e!==void 0)return e;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 t.set(this._id,s),s}forEach(t){if(this._includeDisabled){this._forEachIncludeDisabled(t);return}const e=this._nonEmpty();for(let s=0;s<e.length;s++)t(e[s])}_forEachIncludeDisabled(t){const e=x(!0);try{this._forEachInner(t)}finally{x(e)}}eachChunk(t){if(this._includeDisabled){const e=x(!0);try{this._eachChunkInner(t)}finally{x(e)}return}this._eachChunkInner(t)}_eachChunkInner(t){const e=new kt;e._tick=this._resolver._getCurrentTick();const s=this._nonEmpty();for(let n=0;n<s.length;n++)e._arch=s[n],t(e,s[n].entityCount)}forEachUntil(t){if(this._includeDisabled){const e=x(!0);try{return this._forEachUntilInner(t)}finally{x(e)}}return this._forEachUntilInner(t)}_forEachUntilInner(t){const e=this._nonEmpty();for(let s=0;s<e.length;s++)if(t(e[s]))return!0;return!1}_forEachInner(t){const e=this._nonEmpty();for(let s=0;s<e.length;s++)t(e[s])}forEachEntity(t){if(this._hierarchy!==null){this._resolver._forEachHierarchyMatch(this._include,this._exclude,this._anyOf,this._sparseInclude,this._sparseExclude,this._nonEmpty(),this._hierarchy.relation,this._hierarchy.maxDepth,this._includeDisabled,t);return}this._resolver._forEachSparseMatch(this._include,this._exclude,this._anyOf,this._sparseInclude,this._sparseExclude,this._nonEmpty(),t,this._includeDisabled)}_nonEmpty(){const t=this._resolver._getQueryDirtyEpoch();return this._lastSeenEpoch!==t&&this._rebuildNonEmpty(t),this._nonEmptyArchetypes}_rebuildNonEmpty(t){const e=this._archetypes,s=[];if(this._includeDisabled)for(let n=0;n<e.length;n++)e[n].totalCount>0&&s.push(e[n]);else for(let n=0;n<e.length;n++)e[n].enabledCount>0&&s.push(e[n]);this._nonEmptyArchetypes=s,this._lastSeenEpoch=t}anyOf(...t){if(t.length===1){const s=t[0].id,n=(this._id<<16|s)>>>0,r=this._resolver._caches.anyOfSingle.get(n);return r!==void 0?r:this._anyOfMiss(s,n)}let e=this;for(let s=0;s<t.length;s++)e=e.anyOf(t[s]);return e}_anyOfMiss(t,e){const s=this._anyOf?this._anyOf.copy():new T.BitSet;s.set(t);const n=this._carryNondense(this._resolver._resolveQuery(this._include,this._exclude,s,this._defs));return this._resolver._caches.anyOfSingle.set(e,n),n}changed(...t){if(t.length===1){const s=t[0].id,n=(this._id<<16|s)>>>0,r=this._resolver._caches.changedSingle.get(n);return r!==void 0?r:this._changedMiss(s,n)}const e=new Array(t.length);for(let s=0;s<t.length;s++)e[s]=t[s].id;return new M(this,e)}_changedMiss(t,e){const s=new M(this,[t]);return this._resolver._caches.changedSingle.set(e,s),s}_ctxLastRunTick(){return this._resolver._getLastRunTick()}}class xt{constructor(t){this._resolver=t}with(...t){const e=new T.BitSet;for(let s=0;s<t.length;s++)e.set(t[s].id);return this._resolver._resolveQuery(e,null,null,t)}}class Mt{constructor(t){this.store=t}spawn(...t){const e=this.store.createEntity();for(let s=0;s<t.length;s++){const n=G(t[s]);this.store.addComponentDeferred(e,n,$(t[s]))}return e}add(t,...e){if(e.length===2&&typeof e[0]=="function"&&e[1]!==null&&typeof e[1]=="object"&&typeof e[1].def!="function"){const s=e[0];return this.store.addComponentDeferred(t,s,e[1]),this}for(let s=0;s<e.length;s++){const n=e[s],r=G(n);this.store.addComponentDeferred(t,r,$(n))}return this}remove(t,e){return this.store.removeComponentDeferred(t,e),this}despawn(t){const e=t;return this.store.destroyEntityDeferred(e),this}disable(t){return this.store.disableEntityDeferred(t),this}enable(t){return this.store.enableEntityDeferred(t),this}}class Nt{constructor(t){this.store=t,this.commands=new Mt(t)}lastRunTick=0;commands;get ecsTick(){return this.store._tick}get _trace(){return this.store._trace}isAlive(t){return this.store.isAlive(t)}hasComponent(t,e){return this.store.hasComponent(t,e)}getField(t,e,s){const n=this.store.getEntityArchetype(t),r=this.store.getEntityRow(t);return n.readField(r,e.id,s)}tryGetField(t,e,s){if(!this.store.hasComponent(t,e))return;const n=this.store.getEntityArchetype(t),r=this.store.getEntityRow(t);return n.readField(r,e.id,s)}setField(t,e,s,n){const r=this.store.getEntityArchetype(t),i=this.store.getEntityRow(t),o=r.getColumn(e,s,this.store._tick);o[i]=n,this.store._anyDirtyTracked&&this.store._noteSet(e,t)}updateField(t,e,s,n){const r=this.store.getEntityArchetype(t),i=this.store.getEntityRow(t),o=n(r.readField(i,e.id,s)),a=r.getColumn(e,s,this.store._tick);return a[i]=o,this.store._anyDirtyTracked&&this.store._noteSet(e,t),o}markChanged(t,e){this.store._anyDirtyTracked&&this.store._noteSet(e,t)}ref(t,e){const s=this.store.getEntityArchetype(e),n=this.store.getEntityRow(e);return s._changedTick[t.id]=this.store._tick,it(s.columnGroups[t.id],n)}refRead(t,e){const s=this.store.getEntityArchetype(e),n=this.store.getEntityRow(e);return it(s.columnGroups[t.id],n)}isDisabled(t){return this.store.isDisabled(t)}addSparse(t,e,...s){return this.store.addSparse(t,e,s[0]),this}removeSparse(t,e){return this.store.removeSparse(t,e),this}hasSparse(t,e){return this.store.hasSparse(t,e)}getSparseField(t,e,s){return this.store.getSparseField(t,e,s)}setSparseField(t,e,s,n){this.store.setSparseField(t,e,s,n)}addRelation(t,e,s){return this.store.addRelation(t,e,s),this}removeRelation(t,e,s){return this.store.removeRelation(t,e,s),this}targetOf(t,e){return this.store.targetOf(t,e)}targetsOf(t,e){return this.store.targetsOf(t,e)}sourcesOf(t,e){return this.store.sourcesOf(t,e)}hasRelation(t,e){return this.store.hasRelation(t,e)}flush(){this.store.flushStructural(),this.store.flushDestroyed(),this.store.publishRowCountsToDescriptor()}emit(t,e){const s=this.store.getEventDefByKey(t);e===void 0?this.store.emitSignal(s):this.store.emitEvent(s,e)}read(t){const e=this.store.getEventDefByKey(t);return this.store.getEventReader(e)}getResource(t){return h.unsafeCast(this.store.getResource(t))}setResource(t,e){this.store.setResource(t,e)}removeResource(t){this.store.removeResource(t)}hasResource(t){return this.store.hasResource(t)}}class M{_query;_changedIds;constructor(t,e){this._query=t,this._changedIds=e}and(...t){return new M(this._query.and(...t),this._changedIds)}without(...t){return new M(this._query.without(...t),this._changedIds)}anyOf(...t){return new M(this._query.anyOf(...t),this._changedIds)}optional(...t){return new M(this._query.optional(...t),this._changedIds)}forEach(t){if(this._query._includeDisabled){this._forEachIncludeDisabled(t);return}const e=this._query._ctxLastRunTick(),s=this._query._nonEmpty(),n=this._changedIds;for(let r=0;r<s.length;r++){const i=s[r];for(let o=0;o<n.length;o++)if(i._changedTick[n[o]]>=e){t(i);break}}}_forEachIncludeDisabled(t){const e=x(!0);try{this._forEachInner(t)}finally{x(e)}}_forEachInner(t){const e=this._query._ctxLastRunTick(),s=this._query._nonEmpty(),n=this._changedIds;for(let r=0;r<s.length;r++){const i=s[r];for(let o=0;o<n.length;o++)if(i._changedTick[n[o]]>=e){t(i);break}}}}function Ct(c){if(!(c>0)||!Number.isFinite(c))throw new h.ECSError(h.ECS_ERROR.INVALID_FIXED_TIMESTEP,`fixedTimestep must be a finite number > 0, got ${c}`);return c}function Te(c){if(!Number.isInteger(c)||c<1)throw new h.ECSError(h.ECS_ERROR.INVALID_MAX_FIXED_STEPS,`maxFixedSteps must be an integer >= 1, got ${c}`);return c}class De{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 Ie;_layoutSubscribers=[];_backend=null;_memory;get memoryPlan(){return this._memory}get wasmMemory(){return this._memory.wasmMemory}constructor(t){const e=Object.prototype.hasOwnProperty;if(t!==void 0&&(e.call(t,"initial_capacity")||e.call(t,"buffer_allocator")))throw new h.ECSError(h.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).");const s=h.resolveECSMemory(t?.memory);this._memory=s,this.store=new Se({initialCapacity:s.columnCapacity,bufferAllocator:s.allocator,entityIndexCapacity:s.entityIndexCapacity,capContext:{capBytes:s.capBytes,intentLabel:s.intentLabel,budgetEntities:s.budgetEntities},onBufferResized:()=>{const n=this._layoutSubscribers;for(let r=0;r<n.length;r++)n[r].setLayout(0)},regions:t?.regions,bindingsRegionBytes:t?.bindingsRegionBytes,deterministic:t?.deterministic}),this.schedule=new h.Schedule(t?.onWarn),this.relations=new Ce(this.store),this.events=new Re(this.store),this.resources=new ve(this.store),this.snapshots=new be(this.store),this.ctx=new Nt(this.store),this._observers=new Zt(this.store,this.ctx),this.store.setStructuralObserverHook(n=>this._observers.dispatchStructural(n)),this._fixedTimestep=Ct(t?.fixedTimestep??h.DEFAULT_FIXED_TIMESTEP),this._maxFixedSteps=Te(t?.maxFixedSteps??h.DEFAULT_MAX_FIXED_STEPS)}regionHandles(...t){const e=new Array(t.length);let s=null;for(let n=0;n<t.length;n++){const r=this.store.regionHandle(t[n]);r===null?(s??=[]).push(t[n]):e[n]=r}if(s!==null)throw new h.ECSError(h.ECS_ERROR.REGION_NOT_DECLARED,`region_handles: region id(s) [${s.join(", ")}] not declared — pass them via ECSOptions.regions`);return e}onStoreLayoutPublished(t){return this._layoutSubscribers.push(t),t.setLayout(0),()=>{const e=this._layoutSubscribers.indexOf(t);e>=0&&this._layoutSubscribers.splice(e,1)}}attachBackend(t){this._backend=t,this.schedule.setBackend(t);const e=this.onStoreLayoutPublished(t);return()=>{e(),this._backend===t&&(this._backend=null,this.schedule.setBackend(null))}}get fixedTimestep(){return this._fixedTimestep}set fixedTimestep(t){this._fixedTimestep=Ct(t)}get fixedAlpha(){return this._accumulator/this._fixedTimestep}setTrace(t){}registerComponent(t,e,s){if(Array.isArray(t)){const r=typeof e=="string"?e:"f64",i=Object.create(null);for(const o of t)i[o]=r;return this.store.registerComponent(i,s?.name)}const n=typeof e=="object"?e:s;return this.store.registerComponent(t,n?.name)}registerSparseComponent(t,e,s){if(Array.isArray(t)){const r=typeof e=="string"?e:"f64",i=Object.create(null);for(const o of t)i[o]=r;return this.store.registerSparseComponent(i,s?.name)}const n=typeof e=="object"?e:s;return this.store.registerSparseComponent(t,n?.name)}spawn(t,e){return t===void 0?this.store.createEntity():this.store.spawn(t,e)}spawnBundle(...t){const e=this.store.createEntity();for(let s=0;s<t.length;s++){const n=t[s],r=G(n);this.store.addComponent(e,r,$(n))}return e}spawnMany(t,e,s){return this.store.spawnMany(t,e,s)}_assertHostMutationOutsideSystem(t,e){if(this._updating&&h.accessCheck.current()!==null){const s=h.accessCheck.current(),n=s.name??`system_${s.id}`;throw new h.ECSError(h.ECS_ERROR.ACCESS_UNDECLARED,`ecs.${t} called from inside system '${n}' — host ${t} is immediate and unsafe mid-iteration (and invisible to observers); use ${e} instead`,{op:t})}}despawn(t){return this.store.destroyEntity(t),this}disable(t){return this.store.disableEntity(t),this}enable(t){return this.store.enableEntity(t),this}addComponent(t,e,s){const n=G(e);return this.store.addComponent(t,n,s??$(e)),this}addComponents(t,...e){const s=[];for(let n=0;n<e.length;n++){const r=e[n];s.push({def:G(r),values:$(r)})}return this.store.addComponents(t,s),this}removeComponent(t,e){return this.store.removeComponent(t,e),this}removeComponents(t,...e){return this.store.removeComponents(t,e),this}batchAddComponent(t,e,s){return this.store.batchAddComponent(t,e,s),this}batchRemoveComponent(t,e){return this.store.batchRemoveComponent(t,e),this}getField(t,e,s){const n=this.store.getEntityArchetype(t),r=this.store.getEntityRow(t);return n.readField(r,e.id,s)}refRead(t,e){const s=this.store.getEntityArchetype(e),n=this.store.getEntityRow(e);return it(s.columnGroups[t.id],n)}tryGetField(t,e,s){if(!this.store.hasComponent(t,e))return;const n=this.store.getEntityArchetype(t),r=this.store.getEntityRow(t);return n.readField(r,e.id,s)}setField(t,e,s,n){const r=this.store.getEntityArchetype(t),i=this.store.getEntityRow(t),o=r.getColumn(e,s,this.store._tick);o[i]=n,this.store._anyDirtyTracked&&this.store._noteSet(e,t)}updateField(t,e,s,n){const r=n(this.getField(t,e,s));return this.setField(t,e,s,r),r}query(...t){const e=this.scratchMask;e._words.fill(0);for(let s=0;s<t.length;s++)e.set(t[s].id);return this._resolveQuery(e.copy(),null,null,t)}_nextQueryId(){return this._nextQueryIdCounter++}_resolveQuery(t,e,s,n){const r=t.hash(),i=e?e.hash():0,o=s?s.hash():0,a=r^Math.imul(i,h.HASH_GOLDEN_RATIO)^Math.imul(o,h.HASH_SECONDARY_PRIME)|0,l=this._caches.findDedup(a,t,e,s);if(l!==void 0)return l.query;const u=this.store.registerQuery(t,e??void 0,s??void 0),d=new D(u,n,this,t.copy(),e?.copy()??null,s?.copy()??null,this._nextQueryIdCounter++);return this.store.updateQueryRef(u,d),this._caches.addDedup(a,{includeMask:t.copy(),excludeMask:e?.copy()??null,anyOfMask:s?.copy()??null,query:d}),d}registerSystem(t,e){let s;if(typeof t=="function")if(e!==void 0){const i=e(new xt(this)),o=this.ctx,a=t;s={...nt,fn:(l,u)=>a(i,o,u)}}else s={...nt,fn:t};else s=t;const n=bt(this.nextSystemId++),r=Object.freeze({...s,...zt(s),id:n});return this.systems.add(r),r}removeSystem(t){return this.schedule.removeSystem(t),t.onRemoved?.(),this.systems.delete(t),this}get systemCount(){return this.systems.size}startup(){this.prewarmArchetypes();try{for(const t of this.systems.values())if(t.onAdded!==void 0)try{t.onAdded(this.ctx)}finally{}this.schedule.runStartup(this.ctx,this._tick)}finally{}this.store.clearEvents()}prewarmArchetypes(){const t=ke([...this.systems,...this._observers.descriptors()]);t.length!==0&&this.store.archCreateManyFromMasks(t)}update(t){try{if(this.store._tick=this._tick,this.store.publishRowCountsToDescriptor(),this.schedule.hasFixedSystems()){this._accumulator+=t;const s=this._maxFixedSteps*this._fixedTimestep;for(this._accumulator>s&&(this._accumulator=s);this._accumulator>=this._fixedTimestep;)this.schedule.runFixedUpdate(this.ctx,this._fixedTimestep,this._tick),this._accumulator-=this._fixedTimestep}this.schedule.runUpdate(this.ctx,t,this._tick);const e=O?this.store._devBufferedEventCount():0;this._observers.dispatchSet(this._tick),O&&this.store._devBufferedEventCount(),this.store.clearEvents(),this._tick++}finally{}}dispose(){for(const t of this.systems.values())t.dispose?.(),t.onRemoved?.();this.systems.clear(),this.schedule.clear()}template(...t){const e=[];for(let s=0;s<t.length;s++){const n=t[s];e.push({def:G(n),values:$(n)})}return this.store.resolveTemplate(e)}regionOffset(t){return this.store.regionOffset(t)}regionHandle(t){return this.store.regionHandle(t)}fieldId(t,e){return this.store.fieldIdOf(t,e)}entityIdAtRow(t,e){return this.store.entityIdAtRow(t,e)}get columnStore(){return this.store.columnStore}get archetypeCount(){return this.store.archetypeCount}registerTag(){return this.store.registerComponent({})}registerSparseTag(){return this.store.registerSparseComponent({})}isAlive(t){return this.store.isAlive(t)}get entityCount(){return this.store.entityCount}hasComponent(t,e){return this.store.hasComponent(t,e)}isDisabled(t){return this.store.isDisabled(t)}addSparse(t,e,s){return this.store.addSparse(t,e,s),this}removeSparse(t,e){return this.store.removeSparse(t,e),this}hasSparse(t,e){return this.store.hasSparse(t,e)}getSparseField(t,e,s){return this.store.getSparseField(t,e,s)}setSparseField(t,e,s,n){this.store.setSparseField(t,e,s,n)}_getLastRunTick(){return this.ctx.lastRunTick}_getCurrentTick(){return this.store._tick}_getQueryDirtyEpoch(){return this.store._queryDirtyEpoch}_forEachSparseMatch(t,e,s,n,r,i,o,a){this.store._forEachSparseMatch(t,e,s,n,r,i,o,a)}_relationBackingSparseId(t){return this.store.relationBackingSparseId(t)}_forEachRelationTargetMatch(t,e,s,n,r,i,o,a){this.store._forEachRelationTargetMatch(t,e,s,n,r,i,o,a)}_forEachHierarchyMatch(t,e,s,n,r,i,o,a,l,u){this.store._forEachHierarchyMatch(t,e,s,n,r,i,o,a,l,u)}addSystems(t,...e){return this.schedule.addSystems(t,...e),this}configureSet(t,e){return this.schedule.configureSet(t,e),this}observe(t,e){return this._observers.register(t,e)}publishArchetypeRowCounts(){this.store.publishRowCountsToDescriptor()}flush(){this.ctx.flush()}}function ke(c){const t=new Map,e=[],s=o=>{const a=o.hash(),l=t.get(a);if(l!==void 0){for(let u=0;u<l.length;u++)if(l[u].equals(o))return;l.push(o)}else t.set(a,[o]);e.push(o)},n=o=>{const a=new T.BitSet;for(let l=0;l<o.length;l++)a.set(o[l].id);return a},r=[];for(const o of c){const a=o.transitions;for(let l=0;l<a.length;l++){const u=a[l];r.push({whenHas:n(u.whenHas),add:u.add,remove:u.remove})}}for(const o of c){const a=o.spawns;for(let l=0;l<a.length;l++)s(n(a[l]))}for(;e.length>0;){const o=e.pop();for(let a=0;a<r.length;a++){const l=r[a];if(!o.contains(l.whenHas))continue;const u=o.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 i=[];for(const o of t.values())for(let a=0;a<o.length;a++)i.push(o[a]);return i}function xe(c,t){return{name:`runIfResourceEq(${c.description??"?"})`,resourceReads:[c],evaluate:e=>e.getResource(c)===t}}function Me(c,t=0){const e=(t%c+c)%c;return{name:`runEveryNTicks(${c}${e!==0?`, +${e}`:""})`,evaluate:s=>(s.ecsTick-e)%c===0}}function Ne(c){return{name:"runIfAnyMatch",reads:c._defs,evaluate:()=>c.entityCount>0}}function ct(c){const t=[],e=[];for(const s of c)s.reads&&t.push(...s.reads),s.resourceReads&&e.push(...s.resourceReads);return{...t.length>0?{reads:t}:{},...e.length>0?{resourceReads:e}:{}}}function Fe(c){return{name:`not(${c.name})`,...ct([c]),evaluate:t=>!c.evaluate(t)}}function Le(...c){return{name:`allOf(${c.map(t=>t.name).join(", ")})`,...ct(c),evaluate:t=>c.every(e=>e.evaluate(t))}}function Be(...c){return{name:`anyOf(${c.map(t=>t.name).join(", ")})`,...ct(c),evaluate:t=>c.some(e=>e.evaluate(t))}}function Ge(c){return c.kind==="spawn"&&c.onSpawned!==void 0?{kind:"spawn",components:c.components}:c}class $e{seed;_startup=[];_ticks=[];sink=this._startup;constructor(t=0){this.seed=t}openTick(t,e){const s=this._ticks[this._ticks.length-1];if(s!==void 0&&s.tick===t){this.sink=s.commands;return}const n=[];this._ticks.push({tick:t,dt:e,commands:n}),this.sink=n}record=t=>{this.sink.push(Ge(t))};log(){return{seed:this.seed,startup:this._startup,ticks:this._ticks}}snapshotLog(){return{seed:this.seed,startup:this._startup.map(t=>({...t})),ticks:this._ticks.map(t=>({...t,commands:t.commands.map(e=>({...e}))}))}}}const q="__component_def";function Pe(c){return JSON.stringify(c,(t,e)=>{if(typeof e=="function"&&"id"in e)return{[q]:e.id};if(e!==null&&typeof e=="object"&&q in e)throw new h.ECSError(h.ECS_ERROR.COMMAND_LOG_TAG_COLLISION,`Cannot serialize the command log: a value object owns a field named "${q}", the reserved tag the serializer uses for component defs. Rename that component field so the log can round-trip losslessly.`);return e})}function Ue(c){return JSON.parse(c,(t,e)=>e!==null&&typeof e=="object"&&q in e?vt(Rt(e[q])):e)}function He(c,t,e,s){for(const i of e.startup)t.push(i);c.startup();const n=s?.hash??c.snapshots.deterministic,r=[];for(const i of e.ticks){for(const o of i.commands)t.push(o);c.update(i.dt),n&&r.push(c.snapshots.stateHash())}return{startupCommands:e.startup.length,ticks:e.ticks.length,stateHashes:r}}function tt(c){return c.name??`system#${c.id}`}class Ve{_frames=[];_current=null;tickBegin(t,e){const s={tick:t,dt:e,events:[]};this._current=s,this._frames.push(s)}tickEnd(t){this._current=null}systemStart(t,e){this._current?.events.push({kind:"system_start",system:tt(t),phase:e})}systemEnd(t){this._current?.events.push({kind:"system_end",system:tt(t)})}commandQueued(t,e,s){this._current?.events.push({kind:"command_queued",op:t,entity:e,component:s})}flushBegin(t){this._current?.events.push({kind:"flush_begin",phase:t})}flushEnd(t){this._current?.events.push({kind:"flush_end",phase:t})}phaseBoundary(t){}observerFired(t,e,s,n){this._current?.events.push({kind:"observer_fired",op:t,component:e,entity:s,observer:tt(n)})}eventEmitted(t){this._current?.events.push({kind:"event_emitted",key:t})}eventRead(t,e){this._current?.events.push({kind:"event_read",key:t,count:e})}frames(){return this._frames}reset(){this._frames.length=0,this._current=null}}function N(c,t){if(!(t>=0)||!Number.isFinite(t))throw new h.ECSError(h.ECS_ERROR.INVALID_FRAME_STEP,`${c} must be a finite number >= 0, got ${t}`);return t}function qe(c){if(!Number.isInteger(c)||c<0)throw new h.ECSError(h.ECS_ERROR.INVALID_FRAME_STEP,`frame count must be an integer >= 0, got ${c}`);return c}class We{ecs;requestFrame;cancelFrame;frameHandle=null;lastTimestampMs=null;running=!1;_fixedDt;_maxDt;constructor(t,e={}){this.ecs=t,this._fixedDt=N("fixedDt",e.fixedDt??1/60),this._maxDt=N("maxDt",e.maxDt??.25);const s=globalThis;this.requestFrame=e.requestFrame??s.requestAnimationFrame?.bind(globalThis),this.cancelFrame=e.cancelFrame??s.cancelAnimationFrame?.bind(globalThis),e.autoStart===!0&&this.play()}get fixedDt(){return this._fixedDt}set fixedDt(t){this._fixedDt=N("fixedDt",t)}get maxDt(){return this._maxDt}set maxDt(t){this._maxDt=N("maxDt",t)}get isRunning(){return this.running}step(t=this._fixedDt){this.ecs.update(N("dt",t))}stepFrames(t,e=this._fixedDt){qe(t);const s=N("dt",e);for(let n=0;n<t;n++)this.ecs.update(s)}play(){if(!this.running){if(this.requestFrame===void 0)throw new h.ECSError(h.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=t=>{if(!this.running)return;const e=this.lastTimestampMs===null?this._fixedDt:(t-this.lastTimestampMs)/1e3;this.lastTimestampMs=t,this.ecs.update(Math.min(N("dt",e),this._maxDt)),this.running&&this.scheduleNextFrame()}}function ze(c,t){return c.relations.register({exclusive:!0,onDeleteTarget:t?.onDeleteTarget??"clear"})}function je(c,t){return c.relations.register({exclusive:!0,onDeleteTarget:t?.onDeleteTarget??"delete"})}function Ye(c){return h.unsafeCast(Symbol(c))}const Ke="0.5.3";exports.ANY_RELATION=h.ANY_RELATION;exports.ECSError=h.ECSError;exports.ECS_ERROR=h.ECS_ERROR;exports.HostCommandQueue=h.HostCommandQueue;exports.SCHEDULE=h.SCHEDULE;exports.SparseRestoreError=h.SparseRestoreError;exports.applyHostCommand=h.applyHostCommand;exports.getEntityIndex=h.getEntityIndex;exports.installHostCommandSeam=h.installHostCommandSeam;exports.isEcsError=h.isEcsError;exports.spawnEntry=h.spawnEntry;exports.systemSet=h.systemSet;exports.uninstallHostCommandSeam=h.uninstallHostCommandSeam;exports.SabUnavailableError=V.SabUnavailableError;exports.ChangedQuery=M;exports.ChunkColumns=kt;exports.Commands=Mt;exports.ECS=De;exports.ECSRestoreError=b;exports.ECS_SNAPSHOT_VERSION=K;exports.FrameStepper=We;exports.FrameTraceRecorder=Ve;exports.HIERARCHY_UNBOUNDED=ot;exports.HostCommandRecorder=$e;exports.Query=D;exports.QueryBuilder=xt;exports.StoreRestoreError=B;exports.SystemContext=Nt;exports.VERSION=Ke;exports.allOf=Le;exports.anyOf=Be;exports.bundle=Lt;exports.deserializeCommandLog=Ue;exports.eventKey=Ut;exports.not=Fe;exports.registerChildOf=je;exports.registerIsA=ze;exports.replayCommandLog=He;exports.resourceKey=Ye;exports.runEveryNTicks=Me;exports.runIfAnyMatch=Ne;exports.runIfResourceEq=xe;exports.serializeCommandLog=Pe;exports.signalKey=Ht;
|
|
1
|
+
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const c=require("./host_commands-B2KMx8O2.cjs"),I=require("./topological_sort-vp1imU6D.cjs"),et=require("./shared-Dk-pACZT.cjs"),F=!1,Wt=c.TYPE_TAG.f64,mt=c.TYPE_TAG.f32,Et=c.TYPE_TAG.i32,Kt=c.TYPE_TAG.u32,wt=c.TYPE_TAG.i16,Xt=c.TYPE_TAG.u16,Qt=c.TYPE_TAG.i8,ge=c.TYPE_TAG.u8;function ye(o,t){switch(o){case Qt:return new Uint8Array(t.buffer,t.byteOffset,t.length);case wt:return new Uint16Array(t.buffer,t.byteOffset,t.length);case Et:case mt:return new Uint32Array(t.buffer,t.byteOffset,t.length);default:return t}}const Jt=new Float32Array(1),me=new Uint32Array(Jt.buffer);function Ee(o,t){switch(o){case Wt:return t;case mt:return Jt[0]=t,me[0];case Et:case Kt:return t>>>0;case wt:case Xt:return t&65535;default:return t&255}}function we(o,t){switch(o.constructor){case Float64Array:return o[t];case Float32Array:return o[t];case Int32Array:return o[t];case Uint32Array:return o[t];case Int16Array:return o[t];case Uint16Array:return o[t];case Int8Array:return o[t];default:return o[t]}}function Se(o,t,e){switch(o.constructor){case Float64Array:o[t]=e;return;case Float32Array:o[t]=e;return;case Int32Array:o[t]=e;return;case Uint32Array:o[t]=e;return;case Int16Array:o[t]=e;return;case Uint16Array:o[t]=e;return;case Int8Array:o[t]=e;return;default:o[t]=e;return}}function Y(o,t,e,s){switch(o){case Wt:t[e]=s;return;case mt:t[e]=s;return;case Et:t[e]=s;return;case Kt:t[e]=s;return;case wt:t[e]=s;return;case Xt:t[e]=s;return;case Qt:t[e]=s;return;case ge:t[e]=s;return}}const kt=c.INDEX_MASK,Ce=["__cols","__row"],nt=new Map,it=new Map,L=Object.create(null);function Re(o,t){let e=nt.get(o);if(e===void 0)return e=nt.size,nt.set(o,e),it.set(o,t),Object.defineProperty(L,o,ve[t](e,o)),e;const s=it.get(o);return s!==null&&s!==t&&(it.set(o,null),Object.defineProperty(L,o,Te(e))),e}function Zt(o,t){const e=o.length,s=new Int32Array(e);for(let r=0;r<e;r++)s[r]=Re(o[r],t[r]);return s}const te=new Float64Array(0),ve={f64:(o,t)=>({get(){return this.__cols[o][this.__row]},set(e){const s=this.__cols;s[o][this.__row]=e},enumerable:!0,configurable:!0}),f32:(o,t)=>({get(){return this.__cols[o][this.__row]},set(e){const s=this.__cols;s[o][this.__row]=e},enumerable:!0,configurable:!0}),i32:(o,t)=>({get(){return this.__cols[o][this.__row]},set(e){const s=this.__cols;s[o][this.__row]=e},enumerable:!0,configurable:!0}),u32:(o,t)=>({get(){return this.__cols[o][this.__row]},set(e){const s=this.__cols;s[o][this.__row]=e},enumerable:!0,configurable:!0}),i16:(o,t)=>({get(){return this.__cols[o][this.__row]},set(e){const s=this.__cols;s[o][this.__row]=e},enumerable:!0,configurable:!0}),u16:(o,t)=>({get(){return this.__cols[o][this.__row]},set(e){const s=this.__cols;s[o][this.__row]=e},enumerable:!0,configurable:!0}),i8:(o,t)=>({get(){return this.__cols[o][this.__row]},set(e){const s=this.__cols;s[o][this.__row]=e},enumerable:!0,configurable:!0}),u8:(o,t)=>({get(){return this.__cols[o][this.__row]},set(e){const s=this.__cols;s[o][this.__row]=e},enumerable:!0,configurable:!0})},Te=(o,t)=>({get(){const e=this.__cols;return we(e[o],this.__row)},set(e){const s=this.__cols;Se(s[o],this.__row,e)},enumerable:!0,configurable:!0});function ut(o,t){const e=Object.create(L);return e.__cols=o,e.__row=t,e}const M="at",dt=[];function be(){const o=[],t=Object.create(L);t.__cols=dt,t.__row=0,t.__cols=o,t.__row=1;const e=Object.create(L);e.__cols=dt,e.__row=0,Object.defineProperty(e,M,{value:function(){},writable:!1,enumerable:!1,configurable:!1}),e.__cols=o,e.__row=1}be();function st(o,t,e=dt){for(let r=0;r<o.length;r++)if(o[r]===M)throw new c.ECSError(c.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:o[r]});const s=Object.create(L);return s.__cols=e,s.__row=0,Object.defineProperty(s,M,{value:function(n){return t(this,n),this},writable:!1,enumerable:!1,configurable:!1}),s}function rt(o,t,e,s=null,r=null){for(let h=0;h<o.length;h++)if(o[h]===M)throw new c.ECSError(c.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:o[h]});const n=Object.create(L);return n.__cols=t,n.__row=0,Object.defineProperty(n,M,{value:s===null?function(a){return this.__row=a&kt,this}:function(a){const l=a&kt;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 ee=o=>c.validateAndCast(o),St=Object.freeze({});function se(o){const t=(e=>({def:t,values:e??St}));return Object.defineProperty(t,"id",{value:o,enumerable:!1}),t}function Ae(o,...t){return{def:o,values:t[0]??St}}function q(o){return typeof o=="function"?o:o.def}function j(o){return typeof o=="function"?St:o.values}function re(o,t){for(let e=0;e<o.length;e++)if(Ce.includes(o[e]))throw new c.ECSError(c.ECS_ERROR.FIELD_NOT_REGISTERED,`Cannot register ${t} field "${o[e]}": the name is reserved for the state of a ref or cursor. Rename the field.`,{field:o[e],kind:t})}function ne(o,t,e,s){if(o)for(let r=0;r<e.length;r++){const n=e[r];if(n==="f32"||n==="f64")throw new c.ECSError(c.ECS_ERROR.NON_DETERMINISTIC_COLUMN_TYPE,`Cannot register ${s} field "${t[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:t[r],type:n,kind:s})}}function Ie(o,t,e,s){if(o.length>=c.STORE_DESCRIPTOR_COMPONENT_LIMIT)throw new c.ECSError(c.ECS_ERROR.COMPONENT_LIMIT_EXCEEDED,`registerComponent exceeds the dense component limit of ${c.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:o.length,limit:c.STORE_DESCRIPTOR_COMPONENT_LIMIT});const r=Object.keys(e),n=new Array(r.length),i=Object.create(null);for(let l=0;l<r.length;l++)i[r[l]]=l,n[l]=e[r[l]];re(r,"component"),ne(t,r,n,"component");const h=ee(o.length);o.push({name:s,fieldNames:r,fieldIndex:i,fieldTypes:n,fieldGid:Zt(r,n),obsAdd:!1,obsRem:!1,obsDisable:!1,obsEnable:!1,rowTicks:!1,trackDirty:!1,drainTick:0,scanTick:0,listCap:0,lastDrainRun:0});const a=se(h);return s!==void 0&&c.setComponentDebugName(a,s),a}function Oe(o,t){const e=o[t]?.name;return e!==void 0?`'${e}' (component ${t})`:`component ${t}`}function ke(o,t,e){const s=t.id,r=o[s];if(r===void 0)throw new c.ECSError(c.ECS_ERROR.COMPONENT_NOT_REGISTERED,`fieldId: component ${s} is not registered`);const n=r.fieldIndex[e];if(n===void 0)throw new c.ECSError(c.ECS_ERROR.FIELD_NOT_REGISTERED,`fieldId: component ${s} has no field "${e}"`);return n}class De extends Error{constructor(t){super(t),this.name="StoreRestoreError"}}class xe extends Error{constructor(t){super(t),this.name="SparseRestoreError"}}const Me=2166136261,_t=16777619;function O(o,t){return o=(o^t>>>0)>>>0,Math.imul(o,_t)>>>0}const Dt={f64:Float64Array,f32:Float32Array,i32:Int32Array,u32:Uint32Array,i16:Int16Array,u16:Uint16Array,i8:Int8Array,u8:Uint8Array},X=64,xt=c.MAX_INDEX+1,Ne=Object.freeze([]);class Fe{fieldNames;fieldTypes;fieldIndex;accCols;_cols;_kinds;_allF64;_gids;_cap;_pos;_dense;_size=0;ticks=null;changedTick=0;drainTick=0;lastDrainRun=0;constructor(t,e){this.fieldNames=t,this.fieldTypes=e;const s=Object.create(null);for(let a=0;a<t.length;a++)s[t[a]]=a;this.fieldIndex=s;const r=t.length,n=new Uint8Array(r);let i=!0;for(let a=0;a<r;a++)n[a]=c.TYPED_ARRAY_TAG_TO_TYPE_TAG[e[a]],n[a]!==c.TYPE_TAG.f64&&(i=!1);this._kinds=n,this._allF64=i,this._gids=Zt(t,e);let h=-1;for(let a=0;a<r;a++)this._gids[a]>h&&(h=this._gids[a]);this.accCols=new Array(h+1).fill(te),this._cap=X,this._cols=new Array(r);for(let a=0;a<r;a++){const l=new Dt[e[a]](X);this._cols[a]=l,this.accCols[this._gids[a]]=l}this._pos=new Int32Array(X).fill(-1),this._dense=new Uint32Array(X)}get size(){return this._size}get indices(){return this._dense.subarray(0,this._size)}indexAt(t){return this._dense[t]}canonicalIndices(){const t=new Array(this._size);for(let e=0;e<this._size;e++)t[e]=this._dense[e];return t.sort((e,s)=>e-s)}getRow(t){if(!(this._pos[t]>=0))return;const e=this._cols.length;if(e===0)return Ne;const s=new Array(e);for(let r=0;r<e;r++)s[r]=this._cols[r][t];return s}clear(){this._pos.fill(-1),this._size=0}setRawRow(t,e){this._join(t);const s=this._cols,r=this._kinds;for(let n=0;n<s.length;n++)Y(r[n],s[n],t,e[n])}has(t){return this._pos[t]>=0}setRow(t,e){this._join(t);const s=this.fieldNames,r=this._cols;if(this._allF64){for(let i=0;i<s.length;i++)r[i][t]=e[s[i]]??0;return}const n=this._kinds;for(let i=0;i<s.length;i++)Y(n[i],r[i],t,e[s[i]]??0)}remove(t){const e=this._pos[t];if(!(e>=0))return!1;const s=--this._size,r=this._dense[s];return this._dense[e]=r,this._pos[r]=e,this._pos[t]=-1,!0}getField(t,e){if(this._pos[t]>=0)return this._cols[e][t]}setField(t,e,s,r){if(!(this._pos[t]>=0))return!1;Y(this._kinds[e],this._cols[e],t,s);const n=this.ticks;return n!==null&&(n[t]=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(t){if(t>=this._cap&&this._growToFit(t),!(this._pos[t]>=0)){if(this.ticks!==null&&(this.ticks[t]=0),this._size===this._dense.length){const e=new Uint32Array(this._dense.length*2);e.set(this._dense),this._dense=e}this._pos[t]=this._size,this._dense[this._size++]=t}}_growToFit(t){let e=this._cap;for(;e<=t;)e*=2;e>xt&&(e=xt);const s=this._cols;for(let n=0;n<s.length;n++){const i=new Dt[this.fieldTypes[n]](e);i.set(s[n]),s[n]=i,this.accCols[this._gids[n]]=i}const r=new Int32Array(e).fill(-1);if(r.set(this._pos),this._pos=r,this.ticks!==null){const n=new Uint32Array(e);n.set(this.ticks),this.ticks=n}this._cap=e}}class Be{_values=new Map;register(t,e){if(this._values.has(t))throw new c.ECSError(c.ECS_ERROR.RESOURCE_ALREADY_REGISTERED,`resource '${t.description??"<unnamed>"}' is already registered, remove() it first if you meant to replace it`,{resource:t.description});this._values.set(t,e)}get(t){if(!this._values.has(t))throw new c.ECSError(c.ECS_ERROR.RESOURCE_NOT_REGISTERED,`resource read: '${t.description??"<unnamed>"}' is not registered, call ecs.resources.register(key, value) at world setup`,{resource:t.description});return this._values.get(t)}set(t,e){if(!this._values.has(t))throw new c.ECSError(c.ECS_ERROR.RESOURCE_NOT_REGISTERED,`resource write: '${t.description??"<unnamed>"}' is not registered, call ecs.resources.register(key, value) at world setup`,{resource:t.description});this._values.set(t,e)}remove(t){if(!this._values.has(t))throw new c.ECSError(c.ECS_ERROR.RESOURCE_NOT_REGISTERED,`resource remove: '${t.description??"<unnamed>"}' is not registered, call ecs.resources.register(key, value) at world setup`,{resource:t.description});this._values.delete(t)}has(t){return this._values.has(t)}}class Pe{_registered=[];_host;constructor(t){this._host=t}matching(t,e,s){const r=t.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[_];(!e||!f.mask.overlaps(e))&&(!s||f.mask.overlaps(s))&&d.push(f)}return d}const i=this._host.componentIndex();let h,a=!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 g=i[y];if(g===void 0||g.length===0){a=!0;break}(!h||g.length<h.length)&&(h=g)}if(a)break}if(a||!h)return[];const l=[];for(let u=0;u<h.length;u++){const d=this._host.archetypeAt(h[u]);d.matches(t)&&(!e||!d.mask.overlaps(e))&&(!s||d.mask.overlaps(s))&&l.push(d)}return l}register(t,e,s){const r=this.matching(t,e,s);return this._registered.push({includeMask:t.copy(),excludeMask:e?e.copy():null,anyOfMask:s?s.copy():null,result:r,query:null}),r}updateRef(t,e){const s=this._registered;for(let r=0;r<s.length;r++)if(s[r].result===t){s[r].query=e;return}}fanIn(t){const e=this._registered;for(let s=0;s<e.length;s++){const r=e[s];t.matches(r.includeMask)&&(!r.excludeMask||!t.mask.overlaps(r.excludeMask))&&(!r.anyOfMask||t.mask.overlaps(r.anyOfMask))&&r.result.push(t)}}}class Q extends Error{capacity;requested;constructor(t,e){super(`BufferBackedColumn overflow: requested length ${e} exceeds capacity ${t}`),this.name="StoreColumnOverflowError",this.capacity=t,this.requested=e}}class Ge{_buf;_capacity;_len=0;constructor(t){this._buf=t,this._capacity=t.length}refreshView(t){if(t.length<this._len)throw new Q(t.length,this._len);this._buf=t,this._capacity=t.length}get length(){return this._len}get capacity(){return this._capacity}push(t){if(this._len>=this._capacity)throw new Q(this._capacity,this._len+1);this._buf[this._len++]=t}pop(){return this._buf[--this._len]}getAt(t){return this._buf[t]}setAt(t,e){this._buf[t]=e}swapRemove(t){const e=this._buf[t];return this._buf[t]=this._buf[--this._len],e}clear(){this._len=0}setLength(t){if(t>this._capacity)throw new Q(this._capacity,t);this._len=t}get buf(){return this._buf}view(){return this._buf.subarray(0,this._len)}[Symbol.iterator](){let t=0;const e=this._buf,s=this._len;return{next(){return t<s?{value:e[t++],done:!1}:{value:0,done:!0}}}}reserve(t){if(t>this._capacity)throw new Q(this._capacity,t)}bulkAppend(t,e,s){this.reserve(this._len+s),this._buf.set(t.subarray(e,e+s),this._len),this._len+=s}bulkAppendZeroes(t){this.reserve(this._len+t),this._buf.fill(0,this._len,this._len+t),this._len+=t}bulkAppendValue(t,e){this.reserve(this._len+e),this._buf.fill(t,this._len,this._len+e),this._len+=e}}const P=c.NO_SWAP,Mt=c.UNASSIGNED,Le=2147483647,Ue=new Uint8Array(0),Nt=c.TYPE_TAG.f64;function He(o){const t=new Int32Array(o);for(let e=0;e<o;e++)t[e]=e;return t}const Ft=o=>c.validateAndCast(o);class Ct{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=Ue;_allF64=!0;_eids;_rowCap=0;_colCap=0;_storeArchetypeId=null;colOffset=[];fieldCount=[];_fieldIndex=[];_fieldNames=[];accessorColumns=[];_fieldGid=[];columnIds=[];changedTick=[];_mutGroupCache=[];_readGroupCache=[];growHandler=null;constructor(t,e,s,r=c.DEFAULT_COLUMN_CAPACITY,n){if(this.id=t,this.mask=e,this._entityIds=new I.GrowableUint32Array(r),s){let i=0;const h=[];for(let a=0;a<s.length;a++){const l=s[a],u=l.componentId,d=new Array(l.fieldNames.length);if(this.colOffset[u]=i,this.fieldCount[u]=l.fieldNames.length,this._fieldIndex[u]=l.fieldIndex,this._fieldNames[u]=l.fieldNames,this._fieldGid[u]=l.fieldGid??He(l.fieldNames.length),l.fieldNames.length>0&&!n)throw new c.ECSError(c.ECS_ERROR.COMPONENT_NOT_REGISTERED,`Archetype ${t}: 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,h.push(c.TYPED_ARRAY_TAG_TO_TYPE_TAG[f]),this.flatColumns[i++]=y}this.columnIds.push(u),this.changedTick[u]=0}this._colKind=Uint8Array.from(h);for(let a=0;a<h.length;a++)if(h[a]!==c.TYPE_TAG.f64){this._allF64=!1;break}}this.hasColumns=this.columnIds.length>0,this.materializesRows=!e.isEmpty(),this._syncRowPlane()}_copyRowFrom(t,e,s,r){const n=this._widthBufs,i=t._widthBufs,h=e.length;for(let a=0;a<h;a++){const l=e[a];n[a][s]=l>=0?i[l][r]:0}h!==n.length&&this._copyTicksFrom(t,s,r)}_copyTicksFrom(t,e,s){const r=this._tickCids,n=this._tickBufs;for(let i=0;i<r.length;i++){const h=t.rowTicks[r[i]];n[i][e]=h!==void 0?h[s]:0}}installTicks(t){if(this.rowTicks[t]!==void 0)return;const e=this.fieldCount[t];if(e===void 0||e===0)return;const s=new Uint32Array(Math.max(1,this._rowCap));this.rowTicks[t]=s,this._tickCids.push(t),this._tickBufs.push(s),this._syncRowPlane()}resetTicks(){const t=this._tickBufs;for(let e=0;e<t.length;e++)t[e].fill(0)}_syncTicks(t,e){const s=this._tickCids,r=this._tickBufs,n=this._rowCap;for(let i=0;i<r.length;i++){let h=r[i];if(h.length<n){const a=new Uint32Array(n);a.set(h),h=r[i]=a,this.rowTicks[s[i]]=a}t[e+i]=h}}_moveRow(t,e){const s=this._widthBufs;for(let r=0;r<s.length;r++)s[r][t]=s[r][e]}_swapRow(t,e){const s=this._widthBufs;for(let r=0;r<s.length;r++){const n=s[r],i=n[t];n[t]=n[e],n[e]=i}}_zeroRow(t){const e=this._widthBufs;for(let s=0;s<e.length;s++)e[s][t]=0}_writeRowBits(t,e){const s=this._widthBufs,r=e.length;for(let n=0;n<r;n++)s[n][t]=e[n];for(let n=r;n<s.length;n++)s[n][t]=0}_syncRowPlane(){const t=this.flatColumns;let e=this.bufs;e.length!==t.length&&(e=this.bufs=new Array(t.length));let s=this._widthBufs;const r=t.length+this._tickBufs.length;s.length!==r&&(s=this._widthBufs=new Array(r));const n=this._colKind;this._eids=this._entityIds.buf;let i=Le;for(let a=0;a<t.length;a++){const l=t[a].buf;e[a]=l,s[a]=ye(n[a],l),l.length<i&&(i=l.length)}this._colCap=i;const h=this._eids.length;this._rowCap=h<i?h:i,this._tickBufs.length!==0&&this._syncTicks(s,t.length),this._refreshColumnCaches()}_refreshColumnCaches(){const t=this.columnIds,e=this.bufs;for(let s=0;s<t.length;s++){const r=t[s];let n=this._mutGroupCache[r];n===void 0&&(n=this._mutGroupCache[r]={});let i=this._readGroupCache[r];i===void 0&&(i=this._readGroupCache[r]={});const h=this.colOffset[r],a=this._fieldGid[r];let l=this.accessorColumns[r];if(l===void 0){let d=-1;for(let _=0;_<a.length;_++)a[_]>d&&(d=a[_]);l=this.accessorColumns[r]=new Array(d+1).fill(te)}const u=this._fieldNames[r];for(let d=0;d<u.length;d++){const _=e[h+d];n[u[d]]=_,i[u[d]]=_,l[a[d]]=_}}}_assertRowPlaneFresh(t){const e=this.flatColumns;if(this._eids!==this._entityIds.buf||e.length>0&&this.bufs[0]!==e[0].buf)throw new c.ECSError(c.ECS_ERROR.ARCHETYPE_ROW_INVARIANT,`Archetype ${this.id}: cached row plane is stale at ${t}, a buffer changed identity without a _syncRowPlane`)}reserveRows(t){this.length+t>this._rowCap&&this._growRows(t)}_growRows(t){const e=this.length+t;if(this._entityIds.setLength(this.length),this._entityIds.reserve(e),e<=this._colCap){this._syncRowPlane();return}try{if(this.growHandler!==null)this.growHandler(this,t);else{this._publishRowCounts();const s=this.flatColumns;for(let r=0;r<s.length;r++)s[r].reserve(e)}}finally{this._syncRowPlane()}}_publishRowCounts(){const t=this.flatColumns,e=this.length;for(let s=0;s<t.length;s++)t[s].setLength(e);this._entityIds.setLength(e)}static fromColumnStore(t,e,s,r,n){const i=r.archetypes.get(n);if(!i)throw new c.ECSError(c.ECS_ERROR.COMPONENT_NOT_REGISTERED,`ColumnStore has no archetype ${n}`);const h=(l,u)=>{const d=i.columns.get(c.columnKey(l,u));if(!d)throw new c.ECSError(c.ECS_ERROR.COMPONENT_NOT_REGISTERED,`ColumnStore archetype ${n} has no column for (${l}, ${u})`);return new Ge(d.view)},a=new Ct(t,e,s,i.rowCapacity,h);return a._storeArchetypeId=n,a}get isBufferBacked(){return this._storeArchetypeId!==null}refreshViews(t){if(this._storeArchetypeId===null)throw new c.ECSError(c.ECS_ERROR.COMPONENT_NOT_REGISTERED,`Archetype ${this.id} is not SAB-backed`);const e=t.archetypes.get(this._storeArchetypeId);if(!e)throw new c.ECSError(c.ECS_ERROR.COMPONENT_NOT_REGISTERED,`new ColumnStore has no archetype ${this._storeArchetypeId}`);const s=e.columnsInOrder,r=this.flatColumns;this._publishRowCounts();for(let n=0;n<s.length;n++)r[n].refreshView(s[n].view);this._syncRowPlane()}get entityCount(){return ft?this.length:this.enabledCount}get totalCount(){return this.length}get disabledCount(){return this.length-this.enabledCount}get entityIds(){return this._eids}swapRows(t,e){if(t===e)return;const s=this._eids,r=s[t];s[t]=s[e],s[e]=r,this._swapRow(t,e)}_placeTail(t,e){const s=this.enabledCount;if(s===t)return this.enabledCount=t+1,t;if(this.swapRows(s,t),e!==void 0){const r=this._eids;e[c.getEntityIndex(r[t])]=t}return this.enabledCount=s+1,s}_placeTailBulk(t,e){return this.enabledCount+=e,t}disableRow(t,e){const s=this.enabledCount-1;if(t!==s){this.swapRows(t,s);const r=this._eids;e[c.getEntityIndex(r[t])]=t,e[c.getEntityIndex(r[s])]=s}this.enabledCount=s}enableRow(t,e){const s=this.enabledCount;if(t!==s){this.swapRows(t,s);const r=this._eids;e[c.getEntityIndex(r[t])]=t,e[c.getEntityIndex(r[s])]=s}this.enabledCount=s+1}removeRow(t,e){if(this.enabledCount===this.length){const s=this._eids,r=this.length-1;t!==r&&(s[t]=s[r],this._moveRow(t,r),e[c.getEntityIndex(s[t])]=t),this.length=r,this.enabledCount=r;return}this._removeRowPartitioned(t,e)}_removeRowPartitioned(t,e){const s=this._eids,r=this.enabledCount,n=this.length-1;if(t>=r){t!==n&&(s[t]=s[n],this._moveRow(t,n),e[c.getEntityIndex(s[t])]=t),this.length--;return}const i=r-1;t!==i&&(this.swapRows(t,i),e[c.getEntityIndex(s[t])]=t),i!==n&&(s[i]=s[n],this._moveRow(i,n),e[c.getEntityIndex(s[i])]=i),this.length--,this.enabledCount=i}get rowEntityIds(){return this._eids.subarray(0,this.length)}hasComponent(t){return this.mask.has(t)}matches(t){return this.mask.contains(t)}getColumnRead(t,e){const s=t.id,r=this._fieldIndex[s][e];return this.flatColumns[this.colOffset[s]+r].buf}getColumnsRead(t,...e){return e.map(r=>this.getColumnRead(t,r))}getOptionalColumnRead(t,e){const s=t.id,r=this.colOffset[s];if(r===void 0)return;const n=this._fieldIndex[s][e];return this.flatColumns[r+n].buf}getColumnMut(t,e,s){const r=t.id;this.changedTick[r]=s;const n=this._fieldIndex[r][e];return this.flatColumns[this.colOffset[r]+n].buf}columnGroupMut(t,e){const s=t.id;return this.changedTick[s]=e,this._mutGroupCache[s]}columnGroupRead(t){const e=t.id;return this._readGroupCache[e]}writeFields(t,e,s,r){const n=e,i=this.colOffset[n];if(i===void 0)return;this.changedTick[n]=r;const h=this._fieldNames[n],a=this.bufs;if(this._allF64){for(let u=0;u<h.length;u++)a[i+u][t]=s[h[u]]??0;return}const l=this._colKind;for(let u=0;u<h.length;u++){const d=s[h[u]]??0,_=l[i+u];_===Nt?a[i+u][t]=d:Y(_,a[i+u],t,d)}}bulkWriteFields(t,e,s,r,n){const i=s,h=this.colOffset[i];if(h===void 0)return;this.changedTick[i]=n;const a=this._fieldNames[i],l=this.flatColumns,u=t+e;for(let d=0;d<a.length;d++)l[h+d].buf.fill(r[a[d]]??0,t,u)}writeFieldsPositional(t,e,s,r){const n=e,i=this.colOffset[n];if(i===void 0)return;this.changedTick[n]=r;const h=this.flatColumns;for(let a=0;a<s.length;a++)h[i+a].buf[t]=s[a]}readField(t,e,s){const r=e,n=this.colOffset[r];if(n===void 0)return NaN;const i=this._fieldIndex[r][s];return i===void 0?NaN:this.bufs[n+i][t]}copySharedFrom(t,e,s,r){const n=t.colOffset,i=t.fieldCount,h=t.flatColumns,a=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=i[d];for(let g=0;g<y;g++)a[f+g].buf[s]=h[_+g].buf[e]}this._tickBufs.length!==0&&this._copyTicksFrom(t,s,e)}addEntity(t,e){this.reserveRows(1);const s=this.length;return this._eids[s]=t,this._zeroRow(s),this.length++,this._placeTail(s,e)}swapRemoveRow(t){const e=this.length-1;let s=P;const r=this._eids;return t!==e&&(r[t]=r[e],s=c.getEntityIndex(r[t]),this._moveRow(t,e)),this.length--,t<this.enabledCount&&this.enabledCount--,s}addEntityTag(t,e){this.reserveRows(1);const s=this.length;return this._eids[s]=t,this.length++,this._placeTail(s,e)}addEntities(t,e=t.length){if(e===0)return this.length;this.reserveRows(e);const s=this.length;this._eids.set(t.subarray(0,e),s);const r=this.bufs,n=s+e;for(let h=0;h<r.length;h++)r[h].fill(0,s,n);const i=this._tickBufs;for(let h=0;h<i.length;h++)i[h].fill(0,s,n);return this.length+=e,this._placeTailBulk(s,e)}addEntitiesTag(t,e=t.length){if(e===0)return this.length;this.reserveRows(e);const s=this.length;return this._eids.set(t.subarray(0,e),s),this.length+=e,this._placeTailBulk(s,e)}addEntityWithBits(t,e,s,r){this.reserveRows(1);const n=this.length;this._eids[n]=t,this._writeRowBits(n,e),this.length++;const i=this.columnIds;for(let h=0;h<i.length;h++)this.changedTick[i[h]]=s;return this._placeTail(n,r)}widthBits(t){const e=this._colKind,s=new Float64Array(t.length);for(let r=0;r<t.length;r++)s[r]=Ee(e[r],t[r]);return s}writeFlatElem(t,e,s){const r=this._colKind[t];r===Nt?this.bufs[t][e]=s:Y(r,this.bufs[t],e,s)}addEntitiesWithValues(t,e,s,r){if(e===0)return this.length;this.reserveRows(e);const n=this.length;this._eids.set(t.subarray(0,e),n);const i=this.bufs,h=n+e;for(let u=0;u<i.length;u++)i[u].fill(s[u],n,h);const a=this._tickBufs;for(let u=0;u<a.length;u++)a[u].fill(0,n,h);this.length+=e;const l=this.columnIds;for(let u=0;u<l.length;u++)this.changedTick[l[u]]=r;return this._placeTailBulk(n,e)}swapRemoveRowTag(t){const e=this.length-1;let s=P;const r=this._eids;return t!==e&&(r[t]=r[e],s=c.getEntityIndex(r[t])),this.length--,t<this.enabledCount&&this.enabledCount--,s}moveEntityFrom(t,e,s,r,n,i){const h=e>=t.enabledCount;if(!this.materializesRows){t.removeRow(e,i),A[0]=Mt,A[1]=P;return}this.reserveRows(1);const a=this.length;this._eids[a]=s,this._copyRowFrom(t,r,a,e);const l=this.columnIds;for(let d=0;d<l.length;d++)this.changedTick[l[d]]=n;this.length++;const u=h?a:this._placeTail(a,i);t.removeRow(e,i),A[0]=u,A[1]=P}moveEntityFromTag(t,e,s,r){const n=e>=t.enabledCount;if(!this.materializesRows){t.removeRow(e,r),A[0]=Mt,A[1]=P;return}this.reserveRows(1);const i=this.length;this._eids[i]=s,this.length++;const h=n?i:this._placeTail(i,r);t.removeRow(e,r),A[0]=h,A[1]=P}bulkMoveAllFrom(t,e,s){const r=t.length;if(r===0)return this.length;this.reserveRows(r);const n=this.length,i=this.bufs,h=t.bufs;this._eids.set(t._eids.subarray(0,r),n);for(let u=0;u<i.length;u++){const d=e[u];d>=0?i[u].set(h[d].subarray(0,r),n):i[u].fill(0,n,n+r)}const a=this._tickCids;for(let u=0;u<a.length;u++){const d=t.rowTicks[a[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;return this.length+=r,this.enabledCount=n+t.enabledCount,t.clearRows(),n}clearRows(){this.length=0,this.enabledCount=0,this._entityIds.clear();const t=this.flatColumns;for(let e=0;e<t.length;e++)t[e].clear()}restoreHostRows(t,e){const s=t.length;this._entityIds.clear(),this._entityIds.reserve(s),this._entityIds.setLength(s),this._syncRowPlane();const r=this._eids;for(let i=0;i<s;i++)r[i]=t[i];const n=this.flatColumns;for(let i=0;i<n.length;i++)n[i].setLength(s);this.length=s,this.enabledCount=e}getEdge(t){return this._edges[t]}setEdge(t,e){this._edges[t]=e}transitionMapTo(t){const e=this._batchTransitionMaps.get(t.id);if(e!==void 0)return e;const s=pt(this,t);return this._batchTransitionMaps.set(t.id,s),s}getCompositeAddEdge(t){return this._compositeAddEdges===null?void 0:this._compositeAddEdges.get(t)}cacheCompositeAddEdge(t,e,s){(this._compositeAddEdges??=new Map).set(t,{target:e,map:s})}}const A=[0,P];let ft=!1;function x(o){const t=ft;return ft=o,t}function pt(o,t){const e=t.flatColumns,s=new Int16Array(e.length),r=t.columnIds,n=o.colOffset,i=t.colOffset,h=t.fieldCount;for(let a=0;a<r.length;a++){const l=r[a],u=i[l],d=h[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 $e{_generations;_lengthView;_highWater=0;_freeIndices=[];_aliveCount=0;_capacity;lastIndex=0;constructor(t,e,s){this._capacity=t,this._generations=e,this._lengthView=s}replantViews(t,e){this._generations=t,this._lengthView=e}get generations(){return this._generations}get highWater(){return this._highWater}get aliveCount(){return this._aliveCount}get freeCount(){return this._freeIndices.length}alloc(){let t,e;if(this._freeIndices.length>0)t=this._freeIndices.pop(),e=this._generations[t];else{if(this._highWater>=this._capacity)throw new c.ECSError(c.ECS_ERROR.EID_MAX_INDEX_OVERFLOW,`entityIndexCapacity (${this._capacity}) is exhausted. Raise it in ECSOptions.memory, or destroy unused entities`);t=this._highWater++,this._generations[t]=c.INITIAL_GENERATION,e=c.INITIAL_GENERATION,this._lengthView[0]=this._highWater}return this._aliveCount++,this.lastIndex=t,c.createEntityId(t,e)}assertCapacity(t){const e=t-this._freeIndices.length;if(e>0&&this._highWater+e>this._capacity)throw new c.ECSError(c.ECS_ERROR.EID_MAX_INDEX_OVERFLOW,`entityIndexCapacity (${this._capacity}) cannot fit ${t} new entities (${this._freeIndices.length} free, high-water ${this._highWater}). Raise it in ECSOptions.memory, or destroy unused entities`)}release(t,e){const s=e+1;s<c.RETIRED_GENERATION?(this._generations[t]=s,this._freeIndices.push(t)):this._generations[t]=c.RETIRED_GENERATION,this._aliveCount--}isAliveIndex(t,e){return t<this._highWater&&this._generations[t]===e}publishLength(){this._lengthView[0]=this._highWater}snapshotFreeIndices(){return this._freeIndices.slice()}setHighWater(t){this._highWater=t}restoreHostState(t,e){this._freeIndices.length=0;for(let s=0;s<t.length;s++)this._freeIndices.push(t[s]);this._aliveCount=e}}const Bt=65536;class qe{destroyIds=[];addIds=[];addDefs=[];addValues=[];removeIds=[];removeDefs=[];toggleIds=[];toggleDisable=[];_flushing=!1;_host;_observerEvents;constructor(t,e){this._host=t,this._observerEvents=e}queueDestroy(t){this.destroyIds.push(t)}queueAdd(t,e,s){this.addIds.push(t),this.addDefs.push(e),this.addValues.push(s)}queueRemove(t,e){this.removeIds.push(t),this.removeDefs.push(e)}queueToggle(t,e){this.toggleIds.push(t),this.toggleDisable.push(e)}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 t=this._observerEvents,e=this._host.structuralHooks(),s=e.length;try{let r=0;for(;this.addIds.length>0||this.removeIds.length>0||this.destroyIds.length>0||this.toggleIds.length>0;){if(++r>Bt)throw new c.ECSError(c.ECS_ERROR.OBSERVER_NON_CONVERGENT,`observer cascade did not converge after ${Bt} rounds, two observers likely enqueue each other's structural ops forever`);if(t.addLen=0,t.remLen=0,t.disLen=0,t.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&&(t.addLen>0||t.remLen>0||t.disLen>0||t.enaLen>0))for(let n=0;n<s;n++)e[n](t)}}finally{this._flushing=!1}}}function ie(o,t,e){const s=o.get(t);s!==void 0?s.push(e):o.set(t,[e])}function oe(o,t){let e=o;const s=new Array(t.length);for(let r=0;r<t.length;r++){const n=t[r],i=new Array(n.columns.length);for(let h=0;h<n.columns.length;h++){const a=n.columns[h];e=c.alignUp(e,a.stride),i[h]={componentId:a.componentId,fieldId:a.fieldId,typeTag:a.typeTag,byteOff:e,stride:a.stride},e+=a.stride*n.rowCapacity}s[r]={archetypeId:n.archetypeId,componentMask:n.componentMask,rowCount:0,enabledCount:0,rowCapacity:n.rowCapacity,columns:i}}if(e>c.STORE_MAX_BYTE_OFFSET)throw new c.StoreLayoutOverflowError(e);return{descriptors:s,newTotal:e}}function he(o,t){const e=o._allocator(o.storeBase+t),s=e!==o.buffer?new DataView(e,o.storeBase):o.view;return{grownBuffer:e,newView:s}}function ae(o){return o._allocator.reservedAtCap===!0||o.buffer instanceof ArrayBuffer?o.view.getUint32(c.STORE_HEADER_OFFSETS.capacity,!0):o.buffer.byteLength-o.storeBase}function je(o){const t={};for(let r=0;r<c.STORE_PREFIX_REGIONS.length;r++){const n=c.STORE_PREFIX_REGIONS[r],i=o.view.getUint32(c.STORE_HEADER_OFFSETS[n.headerOff],!0);i!==0&&n.readOptions(o.view,i,t)}const e=c.readHeaderRegionTable(o.view);e.length>0&&(t.regions=e.map(r=>({id:r.regionId,name:`region:${r.regionId}`,bytes:r.byteLength,init:()=>{}})));const s=o.view.getUint32(c.STORE_HEADER_OFFSETS.bindings_off,!0);if(s!==0){const r=o.view.getUint32(c.STORE_HEADER_OFFSETS.layout_descriptor_off,!0);t.bindingsRegionBytes=r-s}return c.isColumnStoreInternal(o)&&o._reservedDescriptorBytes>0&&(t.reservedDescriptorBytes=o._reservedDescriptorBytes),t.storeBase=o.storeBase,t}function ze(o){const t=new Map;for(let r=0;r<c.STORE_PREFIX_REGIONS.length;r++){const n=c.STORE_PREFIX_REGIONS[r],i=o.view.getUint32(c.STORE_HEADER_OFFSETS[n.headerOff],!0);if(i===0)continue;const h=n.regionBytes(o.view,i);t.set(n.headerOff,new Uint8Array(o.buffer,o.storeBase+i,h).slice())}const e=new Map,s=c.readHeaderRegionTable(o.view);for(let r=0;r<s.length;r++){const n=s[r];e.set(n.regionId,new Uint8Array(o.buffer,o.storeBase+n.byteOffset,n.byteLength).slice())}return{mechanism:t,consumer:e}}function Ve(o,t){for(const[e,s]of t.mechanism){const r=o.view.getUint32(c.STORE_HEADER_OFFSETS[e],!0);new Uint8Array(o.buffer,o.storeBase+r,s.byteLength).set(s)}for(const[e,s]of t.consumer){const r=c.findRegionOffset(o.view,e);if(r===0)continue;new Uint8Array(o.buffer,o.storeBase+r,s.byteLength).set(s)}}function Ye(o,t){const e=new Map;for(const[s,r]of o.archetypes){const n=t.get(s)??0;if(n===0)continue;const i=[];for(let h=0;h<r.columnsInOrder.length;h++){const a=r.columnsInOrder[h],l=n*a.stride,u=new Uint8Array(l);u.set(new Uint8Array(a.view.buffer,a.view.byteOffset,l)),i.push(u)}e.set(s,i)}return e}function We(o,t){for(const[e,s]of t){const r=o.archetypes.get(e);if(r===void 0)throw new Error(`restoreLiveColumns: the new store is missing archetype ${e}. Build the spec list so it carries every archetype the snapshot holds.`);const n=r.columnsInOrder;for(let i=0;i<s.length;i++){const h=n[i].view;new Uint8Array(h.buffer,h.byteOffset,s[i].byteLength).set(s[i])}}}function ce(o,t,e,s){const r=o.view.getUint32(c.STORE_HEADER_OFFSETS.view_stamp,!0),n=Ye(o,e),i=ze(o),h=je(o),a=c.createColumnStore(t,s,h);We(a,n),Ve(a,i);const l=r+1>>>0;return a.view.setUint32(c.STORE_HEADER_OFFSETS.view_stamp,l,!0),{store:{...a,header:{...a.header,viewStamp:l}},oldViewStamp:r,newViewStamp:l}}function Ke(o,t,e){const s=new Array(t.length);for(let p=0;p<t.length;p++){const m=t[p],S=o.archetypes.get(m.archetypeId);s[p]={archetypeId:m.archetypeId,componentMask:S.componentMask,rowCapacity:m.newRowCapacity,columns:S.columnsInOrder}}const{descriptors:r,newTotal:n}=oe(ae(o),s),i=new Map;for(let p=0;p<r.length;p++)i.set(r[p].archetypeId,r[p]);const{grownBuffer:h,newView:a}=he(o,n),l=new Uint8Array(h,o.storeBase,n);for(let p=0;p<t.length;p++){const m=t[p],S=o.archetypes.get(m.archetypeId),C=i.get(m.archetypeId);for(let w=0;w<S.columnsInOrder.length;w++){const R=S.columnsInOrder[w],v=m.rowCount*R.stride;v>0&&l.copyWithin(C.columns[w].byteOff,R.byteOff,R.byteOff+v)}}let u=e;for(const[p,m]of o.archetypes){const S=i.get(p);S!==void 0&&c.writeArchetypeDescriptor(a,u,S),u+=c.archetypeDescriptorBytes(m.columnsInOrder.length)}const d=a.getUint32(c.STORE_HEADER_OFFSETS.view_stamp,!0),_=d+1>>>0;a.setUint32(c.STORE_HEADER_OFFSETS.view_stamp,_,!0),a.setUint32(c.STORE_HEADER_OFFSETS.capacity,n,!0);const f=c.createArchetypeViews(h,o.storeBase,[...i.values()]),y=new Map;for(const[p,m]of o.archetypes){const S=f.get(p);y.set(p,S??m)}const g={buffer:h,view:a,header:{...o.header,viewStamp:_,capacity:n},storeBase:o.storeBase,archetypes:y,_regionBytes:o._regionBytes,_allocator:o._allocator,_reservedDescriptorBytes:o._reservedDescriptorBytes,_usedDescriptorBytes:o._usedDescriptorBytes},E=new Array(t.length);for(let p=0;p<t.length;p++)E[p]=t[p].archetypeId;return{store:g,oldViewStamp:d,newViewStamp:_,viewsPreserved:!0,grownArchetypeIds:E}}class ot extends Error{constructor(t){super(t),this.name="StoreGrowError"}}function Xe(o,t,e){const s=new Map;for(let u=0;u<t.archetypes.length;u++){const d=t.archetypes[u];s.set(d.archetypeId,d)}const r=[],n=[];for(const[u,d]of o.archetypes){const _=s.get(u),f=_?.newRowCapacity??d.rowCapacity;if(f<(_?.rowCount??0))throw new ot(`archetype ${u}: newRowCapacity ${f} < rowCount ${_?.rowCount}`);if(f<d.rowCapacity)throw new ot(`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 i=new Map;for(const[u,d]of o.archetypes){const f=s.get(u)?.rowCount??0;if(f>d.rowCapacity)throw new ot(`archetype ${u}: row_count ${f} > old row_capacity ${d.rowCapacity}`);f>0&&i.set(u,f)}if(e?.isInPlace===!0&&c.isColumnStoreInternal(o)&&o._allocator===e&&n.length>0){const u=o.view.getUint32(c.STORE_HEADER_OFFSETS.layout_descriptor_off,!0);return Ke(o,n,u)}const{store:h,oldViewStamp:a,newViewStamp:l}=ce(o,r,i,e);return{store:h,oldViewStamp:a,newViewStamp:l,viewsPreserved:!1,grownArchetypeIds:[]}}class H extends Error{constructor(t){super(t),this.name="StoreExtendError"}}function Qe(o,t,e){if(t.newArchetypes.length===0)throw new H("extend plan has no new archetypes. Use growColumnStore to resize an existing one.");const s=new Set;for(let u=0;u<t.newArchetypes.length;u++){const d=t.newArchetypes[u].archetypeId;if(s.has(d))throw new H(`duplicate archetype_id ${d} in extend plan`);if(o.archetypes.has(d))throw new H(`archetype_id ${d} already exists in the store. Use growColumnStore to resize it.`);s.add(d)}if(e?.isInPlace===!0&&c.isColumnStoreInternal(o)&&o._allocator===e){const u=o.view.getUint32(c.STORE_HEADER_OFFSETS.layout_descriptor_off,!0),d=o._usedDescriptorBytes??c.usedDescriptorBytes(o.archetypes);let _=0;for(let f=0;f<t.newArchetypes.length;f++)_+=c.archetypeDescriptorBytes(t.newArchetypes[f].columns.length);if(d+_<=o._regionBytes)return Je(o,t.newArchetypes,u,d,_)}const r=new Map,n=typeof t.existing=="function"?t.existing():t.existing;if(n)for(let u=0;u<n.length;u++){const d=n[u];if(!o.archetypes.has(d.archetypeId))throw new H(`existing row_count names unknown archetype_id ${d.archetypeId}`);if(d.rowCount<0)throw new H(`archetype ${d.archetypeId}: row_count must be non-negative (got ${d.rowCount})`);if(d.rowCount>0){const _=o.archetypes.get(d.archetypeId);if(d.rowCount>_.rowCapacity)throw new H(`archetype ${d.archetypeId}: row_count ${d.rowCount} > old row_capacity ${_.rowCapacity}`)}r.set(d.archetypeId,d.rowCount)}const i=[];for(const[u,d]of o.archetypes)i.push({archetypeId:u,componentMask:d.componentMask,rowCapacity:d.rowCapacity,columns:d.columnsInOrder});for(let u=0;u<t.newArchetypes.length;u++)i.push(t.newArchetypes[u]);const{store:h,oldViewStamp:a,newViewStamp:l}=ce(o,i,r,e);return{store:h,oldViewStamp:a,newViewStamp:l,viewsPreserved:!1}}function Je(o,t,e,s,r){const n=new Array(t.length);for(let p=0;p<t.length;p++){const m=t[p];n[p]={archetypeId:m.archetypeId,componentMask:m.componentMask,rowCapacity:m.rowCapacity,columns:m.columns.map(S=>({componentId:S.componentId,fieldId:S.fieldId,typeTag:S.typeTag,stride:c.TYPE_TAG_STRIDE[S.typeTag]}))}}const{descriptors:i,newTotal:h}=oe(ae(o),n),{grownBuffer:a,newView:l}=he(o,h);let u=e+s;for(let p=0;p<i.length;p++)u=c.writeArchetypeDescriptor(l,u,i[p]);const d=l.getUint32(c.STORE_HEADER_OFFSETS.view_stamp,!0),_=o.archetypes.size+t.length;l.setUint32(c.STORE_HEADER_OFFSETS.archetype_count,_,!0),l.setUint32(c.STORE_HEADER_OFFSETS.capacity,h,!0);const f=d+1>>>0;l.setUint32(c.STORE_HEADER_OFFSETS.view_stamp,f,!0);const y=c.createArchetypeViews(a,o.storeBase,i),g=o.archetypes;for(const[p,m]of y)g.set(p,m);return{store:{buffer:a,view:l,header:{...o.header,viewStamp:f,capacity:h,archetypeCount:_},storeBase:o.storeBase,archetypes:g,_regionBytes:o._regionBytes,_allocator:o._allocator,_reservedDescriptorBytes:o._reservedDescriptorBytes,_usedDescriptorBytes:s+r},oldViewStamp:d,newViewStamp:f,viewsPreserved:!0}}class Ze{archetypes=[];componentIndex=[];_archetypeMap=new Map;_nextArchetypeId=0;_host;constructor(t){this._host=t}get(t){return this.archetypes[t]}getOrCreateFromMask(t){const e=t.hash(),s=this._lookup(t,e);if(s!==null)return s;const r=Ft(this._nextArchetypeId++),n=this._createLayouts(t);return this._host.extendStore([Pt(r,t,n,this._host.initialCapacity())]),this._install(r,t,n,e),r}getOrCreateFromMasks(t){const e=new Array(t.length),s=[],r=[],n=[],i=[];for(let a=0;a<t.length;a++){const l=t[a],u=l.hash(),d=this._lookup(l,u);if(d!==null){e[a]=d;continue}let _=!1;for(let y=0;y<s.length;y++)if(r[y]===u&&s[y].equals(l)){e[a]=i[y],_=!0;break}if(_)continue;const f=Ft(this._nextArchetypeId++);s.push(l),r.push(u),n.push(this._createLayouts(l)),i.push(f),e[a]=f}if(s.length===0)return e;const h=new Array(s.length);for(let a=0;a<s.length;a++)h[a]=Pt(i[a],s[a],n[a],this._host.initialCapacity());this._host.extendStore(h);for(let a=0;a<s.length;a++)this._install(i[a],s[a],n[a],r[a]);return e}_lookup(t,e){const s=this._archetypeMap.get(e);if(s===void 0)return null;for(let r=0;r<s.length;r++)if(this.archetypes[s[r]].mask.equals(t))return s[r];return null}_createLayouts(t){const e=[],s=this._host.componentMetas();return t.forEach(r=>{const n=r,i=s[n];i&&i.fieldNames.length>0&&e.push({componentId:n,fieldNames:i.fieldNames,fieldIndex:i.fieldIndex,fieldTypes:i.fieldTypes,fieldGid:i.fieldGid})}),e}_install(t,e,s,r){const n=e.copy(),i=this._host.materialize(t,n,s);this.archetypes.push(i),ie(this._archetypeMap,r,t),e.forEach(h=>{const a=h;let l=this.componentIndex[a];l===void 0&&(l=[],this.componentIndex[a]=l),l.push(t)}),this._host.fanIntoQueries(i)}resolveAdd(t,e){const s=this.get(t);if(s.mask.has(e))return t;const r=s.getEdge(e);if(r?.add!=null)return r.add;const n=this.getOrCreateFromMask(s.mask.copyWithSet(e));return this._cacheEdge(s,this.get(n),e),n}resolveRemove(t,e){const s=this.get(t);if(!s.mask.has(e))return t;const r=s.getEdge(e);if(r?.remove!=null)return r.remove;const n=this.getOrCreateFromMask(s.mask.copyWithClear(e));return this._cacheEdge(this.get(n),s,e),n}_cacheEdge(t,e,s){const r=t.getEdge(s)??{add:null,remove:null,addMap:null,removeMap:null};r.add=e.id,r.addMap=pt(t,e),t.setEdge(s,r);const n=e.getEdge(s)??{add:null,remove:null,addMap:null,removeMap:null};n.remove=t.id,n.removeMap=pt(e,t),e.setEdge(s,n)}}function Pt(o,t,e,s){const r=[];for(let h=0;h<e.length;h++){const a=e[h],l=a.fieldTypes;for(let u=0;u<l.length;u++)r.push({componentId:a.componentId,fieldId:u,typeTag:c.TYPED_ARRAY_TAG_TO_TYPE_TAG[l[u]]})}const n=t.words,i=new Array(c.COMPONENT_MASK_WORDS);for(let h=0;h<c.COMPONENT_MASK_WORDS;h++)i[h]=(n[h]??0)>>>0;return{archetypeId:o,componentMask:i,rowCapacity:s,columns:r}}function ts(o,t,e){for(let s=0;s<t.length;s++)t[s].isBufferBacked&&t[s].refreshViews(o),t[s].resetTicks();e.setHighWater(o.view.getUint32(o.header.entityIndexOff+c.ENTITY_INDEX_HEADER_OFFSETS.length,!0))}function es(o,t,e,s,r){const n=r.highWater,i=r.generations,h=new Map;for(let a=0;a<n;a++){const l=e[a];if(l===c.UNASSIGNED)continue;const u=s[a];if(u===c.UNASSIGNED)continue;let d=h.get(l);d===void 0&&(d=[],h.set(l,d)),d[u]=c.createEntityId(a,i[a])}for(let a=0;a<o.archetypeRows.length;a++){const l=o.archetypeRows[a],u=t(l.archetypeId),d=h.get(l.archetypeId)??[];u.restoreHostRows(d,l.enabledCount)}}const J=c.INDEX_BITS,k=c.INDEX_MASK,ss=c.MAX_ENTITY_ID,rs=c.RETIRED_GENERATION,Gt=-1,ht=new DataView(new ArrayBuffer(8)),Lt=129,ns=7,at=-1;class is{_entityAllocator;_componentMetas=[];_sparseStores=[];_sparseNames=[];_sparseDrains=[];_relations;_events;_archGraph;_emptyArchetypeId;_entityArchetypes;_entityRows;_queries;_deferred;_snapshots;get relations(){if(this._relations===null)throw c.pluginMissingError("relations","ecs.relations");return this._relations}requireRelations(t){if(this._relations===null)throw c.pluginMissingError("relations",t);return this._relations}relationHost(){return{isAlive:t=>this.isAlive(t),hasSparse:(t,e)=>this.hasSparse(t,e),pushSparseStore:(t,e)=>this._pushSparseStore(t,e),sparseStoreOf:t=>this._sparseStoreOf(t),sparseStores:()=>this._sparseStores,generations:()=>this._entityAllocator.generations,entityArchetypes:()=>this._entityArchetypes,entityRows:()=>this._entityRows,archetypes:()=>this._archGraph.archetypes,forEachSparseMatch:(t,e,s,r,n,i)=>this.forEachSparseMatch(t,e,s,r,n,i)}}installRelations(t){if(this._relations!==null)throw c.pluginInstalledTwiceError("relations");this._relations=t}get events(){if(this._events===null)throw c.pluginMissingError("events","ecs.events");return this._events}requireEvents(t){if(this._events===null)throw c.pluginMissingError("events",t);return this._events}get hasEvents(){return this._events!==null}installEvents(t){if(this._events!==null)throw c.pluginInstalledTwiceError("events");this._events=t}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:t=>{this.tick=t},publishRowCounts:()=>this.publishRowCounts(),mountRestoredDense:t=>this._mountRestoredDense(t),reconstructHostRows:t=>this._reconstructHostRows(t),invalidateCaches:()=>{this.queryDirtyEpoch++,this._rowCountsDirty=!0}}}get entityAllocator(){return this._entityAllocator}installSnapshots(t){if(this._snapshots!==null)throw c.pluginInstalledTwiceError("snapshots");this._snapshots=t}get snapshots(){if(this._snapshots===null)throw c.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(t){this._structuralHooks.push(t)}_collectDestroyEid=0;_collectDestroyRemoveBit=t=>{if(!this._componentMetas[t].obsRem)return;const e=this._obsEvents;e.remComp[e.remLen]=t,e.remEid[e.remLen]=this._collectDestroyEid,e.remLen++};_collectToggleEid=0;_collectDisableBit=t=>{if(!this._componentMetas[t].obsDisable)return;const e=this._obsEvents;e.disComp[e.disLen]=t,e.disEid[e.disLen]=this._collectToggleEid,e.disLen++};_collectEnableBit=t=>{if(!this._componentMetas[t].obsEnable)return;const e=this._obsEvents;e.enaComp[e.enaLen]=t,e.enaEid[e.enaLen]=this._collectToggleEid,e.enaLen++};_toggleInitial=new Map;anyDirtyTracked=!1;_dirtyTrackedCids=[];_dirtyLists=[];_drainResults=[];_rowCountsDirty=!1;queryDirtyEpoch=0;_columnStore;_initialCapacity;_growHandler=(t,e)=>{const s=t.id,r=this._columnStore.archetypes.get(s);if(r===void 0)throw new c.ECSError(c.ECS_ERROR.ARCHETYPE_NOT_FOUND,`growHandler invoked on archetype ${s} which has no SAB region`);const n=r.rowCapacity,i=t.length+e;let h=n>0?n:1;for(;h<i;)h=h*2;const a=[],l=this._archGraph.archetypes;for(let d=0;d<l.length;d++){const _=l[d],f=this._columnStore.archetypes.get(_.id);f!==void 0&&a.push({archetypeId:_.id,newRowCapacity:_.id===s?h:f.rowCapacity,rowCount:_.hasColumns?_.length:0})}let u;try{u=Xe(this._columnStore,{archetypes:a},this._bufferAllocator)}catch(d){throw d instanceof et.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(t){const e=this._capContext,s=this._entityAllocator.aliveCount,r=`SAB grow refused: requested ${t.requestedBytes} bytes exceeds `+(t.capBytes!==null?`the ${t.capBytes}-byte cap.`:"the backing's ceiling.");let n;if(e===void 0)n=` The ECS holds ${s} live entities (no sizing intent declared).`;else if(e.budgetEntities!==null){const i=(s/e.budgetEntities).toFixed(1);n=` Declared ${e.intentLabel}. The ECS holds ${s} live entities (${i}× 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 ${e.intentLabel}. The ECS holds ${s} live entities.`;return new c.ECSError(c.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: ${t.message}`)}_bufferAllocator;_capContext;_onBufferResized;constructor(t){const e=typeof t=="number"?{initialCapacity:t}:t??{};if(this._initialCapacity=e.initialCapacity??c.DEFAULT_COLUMN_CAPACITY,this._bufferAllocator=e.bufferAllocator??et.growableSabAllocator(),this._bufferAllocator.isInPlace!==!0)throw new c.ECSError(c.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=e.capContext,this._onBufferResized=e.onBufferReplaced,this._entityIndexCapacity=e.entityIndexCapacity??c.ENTITY_INDEX_DEFAULT_CAPACITY,this._storeBase=e.storeBase??0,this._regions=e.regions,this._bindingsRegionBytes=e.bindingsRegionBytes??0,this._deterministic=e.deterministic??!1,this._deferred=new qe({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=c.createColumnStore([],this._bufferAllocator,{storeBase:this._storeBase,reservedDescriptorBytes:64*1024,entityIndexCapacity:this._entityIndexCapacity,eventRingCapacitySlots:c.EVENT_RING_DEFAULT_CAPACITY_SLOTS,commandRingCapacitySlots:c.COMMAND_RING_DEFAULT_CAPACITY_SLOTS,actionRingCapacitySlots:c.ACTION_RING_DEFAULT_CAPACITY_SLOTS,regions:this._regions,bindingsRegionBytes:this._bindingsRegionBytes});const s=c.createEntityIndexViews(this._columnStore.buffer,this._storeBase+this._columnStore.header.entityIndexOff,this._entityIndexCapacity);this._entityArchetypes=s.archetypes,this._entityRows=s.rows,this._entityAllocator=new $e(this._entityIndexCapacity,s.generations,new Uint32Array(this._columnStore.buffer,this._storeBase+this._columnStore.header.entityIndexOff+c.ENTITY_INDEX_HEADER_OFFSETS.length,1)),this._queries=new Pe({archetypes:()=>this._archGraph.archetypes,componentIndex:()=>this._archGraph.componentIndex,archetypeAt:r=>this._archGraph.get(r)}),this._archGraph=new Ze({componentMetas:()=>this._componentMetas,initialCapacity:()=>this._initialCapacity,extendStore:r=>this._extendStore(r),materialize:(r,n,i)=>this._materializeArchetype(r,n,i),fanIntoQueries:r=>this._queries.fanIn(r)}),this._emptyArchetypeId=this._archGetOrCreateFromMask(new I.BitSet)}_entityIndexCapacity;_storeBase;_regions;_bindingsRegionBytes;_deterministic;get deterministic(){return this._deterministic}_assertDeterministic(t){if(!this._deterministic)throw new c.ECSError(c.ECS_ERROR.DETERMINISM_DISABLED,`${t} requires determinism. Construct the world with { deterministic: true }. The canonical-ordering determinism surface is opt-in: stateHash, snapshotSparse, restoreSparse.`)}_refreshEntityIndexViews(){const t=this._columnStore.view.getUint32(c.STORE_HEADER_OFFSETS.entity_index_off,!0),e=this._columnStore.storeBase,s=c.createEntityIndexViews(this._columnStore.buffer,e+t,this._entityIndexCapacity);this._entityArchetypes=s.archetypes,this._entityRows=s.rows,this._entityAllocator.replantViews(s.generations,new Uint32Array(this._columnStore.buffer,e+t+c.ENTITY_INDEX_HEADER_OFFSETS.length,1))}_handleBufferResized(){this._refreshEntityIndexViews(),this._entityAllocator.publishLength(),this._onBufferResized?.()}get columnStore(){return this._columnStore}regionOffset(t){const e=c.findRegionOffset(this._columnStore.view,t);return e===0?0:this._columnStore.storeBase+e}regionHandle(t){const e=c.findRegionEntry(this._columnStore.view,t);return e===null?null:{buffer:this._columnStore.buffer,view:this._columnStore.view,offset:this._columnStore.storeBase+e.byteOffset,bytes:e.byteLength}}publishRowCounts(){if(!this._rowCountsDirty)return;const t=this._columnStore.view;let e=t.getUint32(c.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 i=t.getUint32(e+c.ARCHETYPE_DESCRIPTOR_OFFSETS.column_count,!0);t.setUint32(e+c.ARCHETYPE_DESCRIPTOR_OFFSETS.row_count,n.hasColumns?n.length:0,!0),t.setUint32(e+c.ARCHETYPE_DESCRIPTOR_OFFSETS.enabled_count,n.hasColumns?n.enabledCount:0,!0),e+=c.ARCHETYPE_DESCRIPTOR_HEADER_BYTES+i*c.COLUMN_DESCRIPTOR_BYTES}this._rowCountsDirty=!1}stateHash(){this._assertDeterministic("stateHash()");let t=Me;const e=this._archGraph.archetypes;for(let n=0;n<e.length;n++){const i=e[n],h=i.id,a=i.length;if(t=O(t,h),t=O(t,a),t=O(t,i.enabledCount),a===0)continue;const l=i.flatColumns;for(let u=0;u<l.length;u++){const d=l[u].buf,_=a*d.BYTES_PER_ELEMENT,f=new Uint8Array(d.buffer,d.byteOffset,_),y=_>>>2;let g=0;for(let p=0;p<y;p++){const m=(f[g]|f[g+1]<<8|f[g+2]<<16|f[g+3]<<24)>>>0;t=(t^m)>>>0,t=Math.imul(t,_t),g+=4}const E=_&3;if(E!==0){let p=f[g];E>1&&(p|=f[g+1]<<8),E>2&&(p|=f[g+2]<<16),t=(t^p>>>0)>>>0,t=Math.imul(t,_t)}}}const s=this._sparseStores;for(let n=0;n<s.length;n++){const i=s[n];t=O(t,n),t=O(t,i.size);const h=i.canonicalIndices();for(let a=0;a<h.length;a++){const l=h[a];t=O(t,l);const u=i.getRow(l);for(let d=0;d<u.length;d++)ht.setFloat64(0,u[d],!0),t=O(t,ht.getUint32(0,!0)),t=O(t,ht.getUint32(4,!0))}}const r=this._relations===null?[]:this._relations.stores;for(let n=0;n<r.length;n++){const i=r[n];i.exclusive||(t=O(t,n),i.forEachCanonicalTargetSet((h,a)=>{t=O(t,h),t=O(t,a.length);for(let l=0;l<a.length;l++)t=O(t,a[l])}))}return t>>>0}_archGet(t){return this._archGraph.get(t)}entityIdAtRow(t,e){return this._archGet(t).entityIds[e]}_archGetOrCreateFromMask(t){return this._archGraph.getOrCreateFromMask(t)}archCreateManyFromMasks(t){return this._archGraph.getOrCreateFromMasks(t)}_extendStore(t){const e=()=>{const r=[],n=this._archGraph.archetypes;for(let i=0;i<n.length;i++){const h=n[i],a=this._columnStore.archetypes.get(h.id);a!==void 0&&r.push({archetypeId:h.id,newRowCapacity:a.rowCapacity,rowCount:h.hasColumns?h.length:0})}return r};let s;try{s=Qe(this._columnStore,{newArchetypes:t,existing:e},this._bufferAllocator)}catch(r){throw r instanceof et.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(t,e,s){const r=Ct.fromColumnStore(t,e,s,this._columnStore,t);if(r.growHandler=this._growHandler,this.anyDirtyTracked){const n=this._dirtyTrackedCids;for(let i=0;i<n.length;i++)r.installTicks(n[i])}return r}_archResolveAdd(t,e){return this._archGraph.resolveAdd(t,e)}_archResolveRemove(t,e){return this._archGraph.resolveRemove(t,e)}createEntity(){const t=this._entityAllocator.alloc(),e=this._entityAllocator.lastIndex;return this._entityArchetypes[e]=this._emptyArchetypeId,this._entityRows[e]=c.UNASSIGNED,t}_allocEntity(){return this._entityAllocator.alloc()}_assertEntityIndexCapacity(t){this._entityAllocator.assertCapacity(t)}createTemplate(t){const e=new I.BitSet;for(let a=0;a<t.length;a++)e.set(t[a].def.id);const s=this._archGetOrCreateFromMask(e),r=this._archGet(s),n=new Array(r.flatColumns.length).fill(0),i=new Map,h=new Array(t.length);for(let a=0;a<t.length;a++){h[a]=t[a].def;const l=t[a].def.id,u=this._componentMetas[l];if(u===void 0)throw new c.ECSError(c.ECS_ERROR.COMPONENT_NOT_REGISTERED,`template: component ${l} is not registered`);const d=t[a].values??c.EMPTY_VALUES,_=r.colOffset[l];for(let f=0;f<u.fieldNames.length;f++){const y=u.fieldNames[f];n[_+f]=d[y]??0,i.set(y,i.has(y)?Gt:_+f)}}return{archetypeId:s,flatValues:n,flatBits:r.widthBits(n),overrideIndex:i,defs:h}}_resolveOverrideColumn(t,e){const s=t.overrideIndex.get(e);return s===void 0||s===Gt?-1:s}_applyOverrides(t,e,s,r){for(const n in r){const i=r[n];if(i===void 0)continue;const h=this._resolveOverrideColumn(s,n);h>=0&&t.writeFlatElem(h,e,i)}}_applyOverridesRange(t,e,s,r,n){const i=t.flatColumns;for(const h in n){if(n[h]===void 0)continue;const a=this._resolveOverrideColumn(r,h);a>=0&&i[a].buf.fill(n[h],e,e+s)}}spawn(t,e){const s=this._archGraph.archetypes[t.archetypeId];s.materializesRows&&s.reserveRows(1);const r=this._allocEntity(),n=this._entityAllocator.lastIndex;if(!s.materializesRows)return this._entityArchetypes[n]=t.archetypeId,this._entityRows[n]=c.UNASSIGNED,r;const i=s.length,h=s.enabledCount,a=s.addEntityWithBits(r,t.flatBits,this.changeTick,this._entityRows);return e!==void 0&&this._applyOverrides(s,a,t,e),this._entityArchetypes[n]=t.archetypeId,this._entityRows[n]=a,this._onArchGrow(s,i,h),r}spawnMany(t,e,s){if(e<=0)return[];const r=this._archGraph.archetypes[t.archetypeId];this._assertEntityIndexCapacity(e),r.reserveRows(e);const n=new Array(e),i=new Uint32Array(e);for(let _=0;_<e;_++){const f=this._allocEntity();i[_]=f,n[_]=f}const h=this._entityArchetypes,a=this._entityRows;if(!r.materializesRows){for(let _=0;_<e;_++){const f=c.getEntityIndex(n[_]);h[f]=t.archetypeId,a[f]=c.UNASSIGNED}return n}const l=r.length,u=r.enabledCount;if(r.disabledCount>0){for(let _=0;_<e;_++){const f=r.addEntityWithBits(n[_],t.flatBits,this.changeTick,a),y=c.getEntityIndex(n[_]);h[y]=t.archetypeId,a[y]=f,s!==void 0&&this._applyOverrides(r,f,t,s)}return this._onArchGrow(r,l,u),n}const d=r.addEntitiesWithValues(i,e,t.flatValues,this.changeTick);for(let _=0;_<e;_++){const f=c.getEntityIndex(n[_]);h[f]=t.archetypeId,a[f]=d+_}return s!==void 0&&this._applyOverridesRange(r,d,e,t,s),this._onArchGrow(r,l,u),n}destroyEntity(t){if(!this.isAlive(t))return;if(this._relations===null||!this._relations.hasTargetCleanup){this._destroyOne(t,null);return}const e=[t];for(let s=0;s<e.length;s++){const r=e[s];this.isAlive(r)&&this._destroyOne(r,e)}}_destroyOne(t,e){const s=c.getEntityIndex(t),r=this._entityRows[s];if(r!==c.UNASSIGNED){const i=this._archGet(this._entityArchetypes[s]),h=i.length;i.removeRow(r,this._entityRows),this._onArchShrink(i,h)}this._entityArchetypes[s]=c.UNASSIGNED,this._entityRows[s]=c.UNASSIGNED;const n=this._relations;n!==null&&n.count>0&&(n.purgeSource(t),e!==null&&n.cleanupTarget(t,e)),this._sparseStores.length>0&&this._purgeSparse(s),this._entityAllocator.release(s,c.getEntityGeneration(t))}isAlive(t){return this._liveIndex(t)>=0}_liveIndex(t){const e=t;if(e<0||e>ss)return-1;const s=e>>J;if(s===rs)return-1;const r=e&k,n=this._entityAllocator;return r>=n.highWater||n.generations[r]!==s?-1:r}get entityCount(){return this._entityAllocator.aliveCount}_onArchShrink(t,e){this._rowCountsDirty=!0,e===0!=(t.length===0)&&this.queryDirtyEpoch++}_onArchGrow(t,e,s){this._rowCountsDirty=!0,(e===0||s===0&&t.enabledCount!==0)&&this.queryDirtyEpoch++}_onArchEnabledChange(t,e){this._rowCountsDirty=!0,e===0!=(t.enabledCount===0)&&this.queryDirtyEpoch++}disableEntity(t){if(!this.isAlive(t))return;const e=c.getEntityIndex(t),s=this._entityRows[e];if(s===c.UNASSIGNED)return;const r=this._archGet(this._entityArchetypes[e]);if(s>=r.enabledCount)return;const n=r.enabledCount;r.disableRow(s,this._entityRows),this._onArchEnabledChange(r,n)}enableEntity(t){if(!this.isAlive(t))return;const e=c.getEntityIndex(t),s=this._entityRows[e];if(s===c.UNASSIGNED)return;const r=this._archGet(this._entityArchetypes[e]);if(s<r.enabledCount)return;const n=r.enabledCount;r.enableRow(s,this._entityRows),this._onArchEnabledChange(r,n)}isDisabled(t){if(!this.isAlive(t))return!1;const e=c.getEntityIndex(t),s=this._entityRows[e];if(s===c.UNASSIGNED)return!1;const r=this._archGet(this._entityArchetypes[e]);return s>=r.enabledCount}_flushEpoch=0;_flushTouched=[];_settleFlushDirty(){const t=this._flushTouched;if(t.length===0)return;this._rowCountsDirty=!0;let e=!1;for(let s=0;s<t.length;s++){const r=t[s];(r.flushPreLen===0!=(r.length===0)||r.flushPreEnabled===0!=(r.enabledCount===0))&&(e=!0)}e&&this.queryDirtyEpoch++,t.length=0,this._flushEpoch++}destroyEntityDeferred(t){this._deferred.queueDestroy(t)}disableEntityDeferred(t){this._deferred.queueToggle(t,!0)}enableEntityDeferred(t){this._deferred.queueToggle(t,!1)}_flushToggles(){const t=this._deferred.toggleIds,e=this._deferred.toggleDisable,s=t.length;if(!(this._toggleObserverCount>0)){for(let i=0;i<s;i++){const h=t[i];this.isAlive(h)&&(e[i]?this.disableEntity(h):this.enableEntity(h))}t.length=0,e.length=0;return}const n=this._toggleInitial;for(let i=0;i<s;i++){const h=t[i];this.isAlive(h)&&(n.has(h)||n.set(h,this.isDisabled(h)))}for(let i=0;i<s;i++){const h=t[i];this.isAlive(h)&&(e[i]?this.disableEntity(h):this.enableEntity(h))}t.length=0,e.length=0;for(const[i,h]of n){if(!this.isAlive(i))continue;const a=this.isDisabled(i);h!==a&&this._collectToggle(i,a)}n.clear()}_collectToggle(t,e){const s=c.getEntityIndex(t);if(this._entityRows[s]===c.UNASSIGNED)return;const r=this._archGet(this._entityArchetypes[s]);this._collectToggleEid=t,r.mask.forEach(e?this._collectDisableBit:this._collectEnableBit)}get pendingToggleCount(){return this._deferred.toggleCount}flushDestroys(){this._deferred.flushDestroys()}_flushDestroys(){const t=this._deferred.destroyIds;if(t.length===0)return;const e=this._entityAllocator,s=this._entityArchetypes,r=this._entityRows,n=e.generations,i=this._archGraph.archetypes,h=e.highWater;let a=!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 g=0;g<t.length;g++){const E=t[g],p=E&k,m=E>>J;if(p>=h||n[p]!==m)continue;const S=r[p];if(S!==c.UNASSIGNED){const C=i[s[p]];y&&(this._collectDestroyEid=E,C.mask.forEach(this._collectDestroyRemoveBit)),C.removeRow(S,r),a=!0,C.length===0&&(l=!0)}_&&d.purgeSource(E),f&&d.cleanupTarget(E,t),u&&this._purgeSparse(p),s[p]=c.UNASSIGNED,r[p]=c.UNASSIGNED,e.release(p,m)}t.length=0,a&&(this._rowCountsDirty=!0,l&&this.queryDirtyEpoch++)}get pendingDestroyCount(){return this._deferred.destroyCount}addComponentDeferred(t,e,s){this._deferred.queueAdd(t,e,s??c.EMPTY_VALUES)}removeComponentDeferred(t,e){this._deferred.queueRemove(t,e)}flushStructural(){this._deferred.flushStructural()}_flushAdds(){const t=this._deferred.addIds,e=this._deferred.addDefs,s=this._deferred.addValues,r=t.length,n=this._entityArchetypes,i=this._entityRows,h=this._entityAllocator.generations,a=this._archGraph.archetypes,l=this._componentMetas,u=this._entityAllocator.highWater,d=this.changeTick,_=this._flushEpoch,f=this._flushTouched,y=this._structuralObserverCount>0,g=this._obsEvents;for(let E=0;E<r;E++){const p=t[E],m=p&k,S=p>>J;if(m>=u||h[m]!==S)continue;const C=n[m],w=e[E].id,R=a[C],v=l[w];if(R.mask.has(w)){v.fieldNames.length>0&&R.writeFields(i[m],w,s[E],d);continue}const b=this._archResolveAdd(C,w),T=a[b],U=i[m],Ot=!T.hasColumns&&!R.hasColumns;U!==c.UNASSIGNED&&R.flushSeenEpoch!==_&&(R.flushSeenEpoch=_,R.flushPreLen=R.length,R.flushPreEnabled=R.enabledCount,f.push(R)),T.flushSeenEpoch!==_&&(T.flushSeenEpoch=_,T.flushPreLen=T.length,T.flushPreEnabled=T.enabledCount,f.push(T));let K;if(U!==c.UNASSIGNED){if(Ot)T.moveEntityFromTag(R,U,p,i);else{const pe=R.getEdge(w);T.moveEntityFrom(R,U,p,pe.addMap,d,i)}K=A[0]}else K=Ot?T.addEntityTag(p,i):T.addEntity(p,i);v.fieldNames.length>0&&T.writeFields(K,w,s[E],d),n[m]=b,i[m]=K,y&&v.obsAdd&&(g.addComp[g.addLen]=w,g.addEid[g.addLen]=p,g.addLen++)}t.length=0,e.length=0,s.length=0,this._settleFlushDirty()}_flushRemoves(){const t=this._deferred.removeIds,e=this._deferred.removeDefs,s=t.length,r=this._entityArchetypes,n=this._entityRows,i=this._entityAllocator.generations,h=this._archGraph.archetypes,a=this._entityAllocator.highWater,l=this.changeTick,u=this._flushEpoch,d=this._flushTouched,_=this._componentMetas,f=this._structuralObserverCount>0,y=this._obsEvents;for(let g=0;g<s;g++){const E=t[g],p=E&k,m=E>>J;if(p>=a||i[p]!==m)continue;const S=r[p],C=e[g].id,w=h[S];if(!w.mask.has(C))continue;const R=this._archResolveRemove(S,C),v=h[R],b=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,b,E,n);else{const U=w.getEdge(C);v.moveEntityFrom(w,b,E,U.removeMap,l,n)}r[p]=R,n[p]=A[0],f&&_[C].obsRem&&(y.remComp[y.remLen]=C,y.remEid[y.remLen]=E,y.remLen++)}t.length=0,e.length=0,this._settleFlushDirty()}get pendingStructuralCount(){return this._deferred.addRemoveCount}configureObservation(t,e,s){let r=this._observationFlags.get(t);r===void 0&&(r=[],this._observationFlags.set(t,r)),r[e]=s;let n=!1,i=!1,h=!1,a=!1,l=!1;for(const u of this._observationFlags.values()){const d=u[e];d!==void 0&&(d.add&&(n=!0),d.remove&&(i=!0),d.disable&&(h=!0),d.enable&&(a=!0),d.set&&(l=!0))}this._applyObservation(e,n,i,h,a,l)}_applyObservation(t,e,s,r,n,i){const h=this._componentMetas[t];if(h===void 0)throw new c.ECSError(c.ECS_ERROR.COMPONENT_NOT_REGISTERED,`observe(): component ${t} is not registered`);const a=h.obsAdd||h.obsRem;h.obsAdd=e,h.obsRem=s;const l=e||s;a&&!l?this._structuralObserverCount--:!a&&l&&this._structuralObserverCount++;const u=h.obsDisable||h.obsEnable;h.obsDisable=r,h.obsEnable=n;const d=r||n;u&&!d?this._toggleObserverCount--:!u&&d&&this._toggleObserverCount++,i&&!h.trackDirty?(this._trackRowsById(t),h.trackDirty=!0,this._dirtyLists[t]===void 0&&(this._dirtyLists[t]=[],this._drainResults[t]={scanned:[],listed:[]}),h.listCap=this._listCap(),h.drainTick=this.changeTick,h.scanTick=0):!i&&h.trackDirty&&(h.trackDirty=!1,this._dirtyLists[t].length=0,h.drainTick=this.changeTick,h.scanTick=0)}trackRows(t){if(typeof t=="number"){this._sparseStoreOf(t).trackTicks();return}const e=t.id;if(typeof e!="number")throw new c.ECSError(c.ECS_ERROR.COMPONENT_NOT_REGISTERED,"trackRows(): the definition is not a registered component. Track a dense or a sparse component");this._trackRowsById(e)}configureSparseObservation(t,e,s){let r=this._sparseObservationFlags.get(t);r===void 0&&(r=[],this._sparseObservationFlags.set(t,r)),r[e]=s;let n=!1;for(const i of this._sparseObservationFlags.values())i[e]===!0&&(n=!0);this._applySparseObservation(e,n)}_applySparseObservation(t,e){const s=this._sparseStores[t];if(s===void 0)throw new c.ECSError(c.ECS_ERROR.COMPONENT_NOT_REGISTERED,`observe(): sparse component ${t} is not registered`);e?(s.trackTicks(),this._sparseDrains[t]===void 0&&(this._sparseDrains[t]=[])):s.drainTick=this.changeTick}drainSparseSet(t,e){const s=this._sparseStores[t],r=this._sparseDrains[t];if(s.lastDrainRun===e)return r;s.lastDrainRun=e,r.length=0;const n=s.drainTick;if(s.drainTick=e-1,s.changedTick<=n)return r;const i=s.ticks,h=this._entityAllocator.generations,a=s.size;for(let l=0;l<a;l++){const u=s.indexAt(l);if(i[u]<=n)continue;const d=c.createEntityId(u,h[u]);this.isDisabled(d)||r.push(d)}return r}sparseTickOf(t,e){const s=this._sparseStoreOf(t),r=s.ticks;if(r===null)throw new c.ECSError(c.ECS_ERROR.ROW_TICKS_NOT_TRACKED,`sparseChanged: ${this.sparseLabel(t)} has no row ticks. Call ecs.trackRows(def), or register an onSet observer with granularity "entity", first`,{sparse:t});const n=e&k;return s.has(n)?r[n]:0}sparseTickPlane(t){return this._sparseStoreOf(t)}_trackRowsById(t){const e=this._componentMetas[t];if(e===void 0)throw new c.ECSError(c.ECS_ERROR.COMPONENT_NOT_REGISTERED,`trackRows(): component ${t} is not registered`);if(e.rowTicks||e.fieldNames.length===0)return;e.rowTicks=!0;const s=this._archGraph.componentIndex[t];if(s!==void 0){const r=this._archGraph.archetypes;for(let n=0;n<s.length;n++)r[s[n]].installTicks(t)}this._dirtyTrackedCids.push(t),this.anyDirtyTracked=!0}_listCap(){const t=this._entityAllocator.aliveCount>>>5;return t<64?64:t}noteSet(t,e,s,r){const n=this._componentMetas[t];if(!n.rowTicks)return;const i=e.rowTicks[t];if(n.trackDirty&&i[s]<=n.drainTick&&n.scanTick<=n.drainTick){const h=this._dirtyLists[t];h.push(r),h.length>n.listCap&&(n.scanTick=this.changeTick)}i[s]=this.changeTick}noteSetEntity(t,e){const s=t.id,r=this._componentMetas[s];if(r===void 0||!r.rowTicks||!this.isAlive(e))return;const n=e&k,h=this._archGet(this._entityArchetypes[n]).rowTicks[s];if(h===void 0)return;const a=this._entityRows[n];r.trackDirty&&h[a]<=r.drainTick&&this._dirtyLists[s].push(e),h[a]=this.changeTick}noteScan(t){const e=this._componentMetas[t];e.rowTicks&&(e.scanTick=this.changeTick)}drainSet(t,e){const s=this._componentMetas[t],r=this._drainResults[t];if(s.lastDrainRun===e)return r;s.lastDrainRun=e,r.scanned.length=0,r.listed.length=0;const n=s.drainTick;s.drainTick=e-1,s.listCap=this._listCap();const i=s.scanTick>n,h=this._archGraph.archetypes;if(i){const l=this._archGraph.componentIndex[t];if(l!==void 0)for(let u=0;u<l.length;u++){const d=h[l[u]];if(d.enabledCount===0||d.changedTick[t]<=n)continue;const _=d.rowTicks[t];if(_===void 0)continue;const f=d.entityIds,y=d.enabledCount;for(let g=0;g<y;g++)_[g]>n&&r.scanned.push(f[g])}}const a=this._dirtyLists[t];for(let l=0;l<a.length;l++){const u=a[l];if(i){const d=h[this._entityArchetypes[u&k]];if(d!==void 0&&d.changedTick[t]>n)continue}r.listed.push(u)}return a.length=0,r}forEachChangedArchetype(t,e,s){const r=this._archGraph.componentIndex[t];if(r===void 0)return;const n=this._archGraph.archetypes;for(let i=0;i<r.length;i++){const h=n[r[i]];h.length>0&&h.changedTick[t]>e&&s(h)}}collectEnabledWith(t){const e=[],s=this._archGraph.componentIndex[t];if(s===void 0)return e;const r=this._archGraph.archetypes;for(let n=0;n<s.length;n++){const i=r[s[n]],h=i.entityIds;for(let a=0;a<i.enabledCount;a++)e.push(c.unsafeCast(h[a]))}return e}registerComponent(t,e){return Ie(this._componentMetas,this._deterministic,t,e)}componentLabel(t){return Oe(this._componentMetas,t)}fieldIdOf(t,e){return ke(this._componentMetas,t,e)}registerSparseComponent(t,e){const s=Object.keys(t),r=new Array(s.length);for(let n=0;n<s.length;n++)r[n]=t[s[n]];return re(s,"sparse component"),ne(this._deterministic,s,r,"sparse component"),this._pushSparseStore(s,r,e)}sparseLabel(t){const e=this._sparseNames[t];return e!==void 0?`'${e}' (sparse component ${t})`:`sparse component ${t}`}_pushSparseStore(t,e,s){const r=this._sparseStores.length;return this._sparseStores.push(new Fe(t,e)),this._sparseNames.push(s),c.unsafeCast(r)}_sparseStoreOf(t){const e=t,s=this._sparseStores[e];if(s===void 0)throw new c.ECSError(c.ECS_ERROR.COMPONENT_NOT_REGISTERED,`sparse component ${e} is not registered`);return s}addSparse(t,e,s){this.isAlive(t)&&this._sparseStoreOf(e).setRow(c.getEntityIndex(t),s??c.EMPTY_VALUES)}removeSparse(t,e){this.isAlive(t)&&this._sparseStoreOf(e).remove(c.getEntityIndex(t))}hasSparse(t,e){return this.isAlive(t)?this._sparseStoreOf(e).has(c.getEntityIndex(t)):!1}getSparseField(t,e,s){const r=this._sparseStoreOf(e),n=r.fieldIndex[s];if(n===void 0)return 0;const i=r.getField(c.getEntityIndex(t),n);return i===void 0?0:i}setSparseField(t,e,s,r){const n=this._sparseStoreOf(e),i=n.fieldIndex[s];i!==void 0&&n.setField(c.getEntityIndex(t),i,r,this.changeTick)}_purgeSparse(t){const e=this._sparseStores;for(let s=0;s<e.length;s++)e[s].remove(t)}sparseFieldNames(t){return this._sparseStoreOf(t).fieldNames}sparseAccessorColumns(t){return this._sparseStoreOf(t).accCols}sparseCursorCheck(t,e){const s=this._sparseStoreOf(t),r=t;return n=>{if(e?c.accessCheck.assertSparseWrite(t):c.accessCheck.assertSparseRead(t),!this.isAlive(n))throw c.entityNotAliveError("sparseCursor.at",n,this.sparseLabel(r));if(!s.has(n&k))throw new c.ECSError(c.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(t){this._assertDeterministic("restore_sparse()"),this.snapshots.restoreSparse(t),this._resetSparseTicks()}_resetSparseTicks(){const t=this._sparseStores;for(let e=0;e<t.length;e++)t[e].resetTicks()}snapshot(){return this._assertDeterministic("snapshot()"),this.snapshots.snapshot()}restore(t){this._assertDeterministic("restore()"),this.snapshots.restore(t),this._resetSparseTicks()}_mountRestoredDense(t){this._columnStore=t,ts(t,this._archGraph.archetypes,this._entityAllocator),this._handleBufferResized()}_reconstructHostRows(t){es(t,e=>this._archGet(e),this._entityArchetypes,this._entityRows,this._entityAllocator)}forEachSparseMatch(t,e,s,r,n,i){const{sparseIncludes:h,sparseExcludes:a,includesDisabled:l}=r,u=this._sparseStores;if(h.length>0){let _=u[h[0]];for(let C=1;C<h.length;C++){const w=u[h[C]];w.size<_.size&&(_=w)}const f=this._entityAllocator.generations,y=this._entityArchetypes,g=this._entityRows,E=this._archGraph.archetypes;let p=-2,m=!1,S=0;for(let C=0;C<_.size;C++){const w=_.indexAt(C);let R=!0;for(let b=0;b<h.length;b++){const T=u[h[b]];if(T!==_&&!T.has(w)){R=!1;break}}if(!R)continue;for(let b=0;b<a.length;b++)if(u[a[b]].has(w)){R=!1;break}if(!R)continue;const v=y[w];if(v!==c.UNASSIGNED){if(v!==p){const b=E[v],T=b.mask;p=v,m=T.contains(t)&&(e===null||!T.overlaps(e))&&(s===null||T.overlaps(s)),S=b.enabledCount}if(m){if(!l){const b=g[w];if(b!==c.UNASSIGNED&&b>=S)continue}i(c.createEntityId(w,f[w]))}}}return}const d=a.length>0;for(let _=0;_<n.length;_++){const f=n[_],y=f.entityIds,g=l?f.totalCount:f.enabledCount;for(let E=0;E<g;E++){const p=y[E];if(d){const m=c.getEntityIndex(p);let S=!1;for(let C=0;C<a.length;C++)if(u[a[C]].has(m)){S=!0;break}if(S)continue}i(p)}}}forEachHierarchyMatch(t,e,s,r,n,i,h,a){this.requireRelations("query.hierarchy").forEachHierarchyMatch(t,e,s,r,n,i,h,a)}forEachTargetMatch(t,e,s,r,n,i){this.requireRelations("query.forEachRelatedTo").forEachTargetMatch(t,e,s,r,n,i)}relationBackingSparseId(t,e){return this.requireRelations(e).relationBackingSparseId(t)}_scratchTargetMask=new I.BitSet;addComponent(t,e,s){if(!this.isAlive(t))return;const r=c.getEntityIndex(t),n=this._entityArchetypes[r],i=this._archGet(n),h=i.getEdge(e.id);if(h===void 0||h.add===null){this._addComponentCold(t,r,i,n,e,s);return}const a=h.add,l=this._archGet(a),u=this._entityRows[r];let d;if(u!==c.UNASSIGNED){const _=i.length,f=l.length,y=l.enabledCount;!l.hasColumns&&!i.hasColumns?l.moveEntityFromTag(i,u,t,this._entityRows):l.moveEntityFrom(i,u,t,h.addMap,this.changeTick,this._entityRows),d=A[0],this._onArchShrink(i,_),this._onArchGrow(l,f,y)}else{const _=l.length,f=l.enabledCount;d=l.hasColumns?l.addEntity(t,this._entityRows):l.addEntityTag(t,this._entityRows),this._onArchGrow(l,_,f)}l.writeFields(d,e.id,s,this.changeTick),this._entityArchetypes[r]=a,this._entityRows[r]=d}_addComponentCold(t,e,s,r,n,i){if(s.hasComponent(n.id)){s.writeFields(this._entityRows[e],n.id,i,this.changeTick);return}this._archResolveAdd(r,n.id),this.addComponent(t,n,i)}addComponents(t,e){if(!this.isAlive(t))return;const s=c.getEntityIndex(t),r=this._entityArchetypes[s],n=this._archGet(r),i=e.length;let h=i;for(let _=0;_<i;_++){const f=e[_].def.id;if(f>=Lt-1||i>ns){h=at;break}h=h*Lt+(f+1)}if(h!==at){const _=n.getCompositeAddEdge(h);if(_!==void 0){this._addComponentsInto(t,s,n,this._archGet(_.target),_.target,_.map,e);return}}let a=null;for(let _=0;_<i;_++){const f=e[_].def.id;a!==null?a.set(f):n.mask.has(f)||(a=n.mask.copyInto(this._scratchTargetMask),a.set(f))}if(a===null){const _=this._entityRows[s];for(let f=0;f<i;f++)n.writeFields(_,e[f].def.id,e[f].values??c.EMPTY_VALUES,this.changeTick);return}const l=this._archGetOrCreateFromMask(a),u=this._archGet(l),d=n.transitionMapTo(u);h!==at&&n.cacheCompositeAddEdge(h,l,d),this._addComponentsInto(t,s,n,u,l,d,e)}_addComponentsInto(t,e,s,r,n,i,h){const a=this._entityRows[e];let l;if(a!==c.UNASSIGNED){const u=s.length,d=r.length,_=r.enabledCount;r.moveEntityFrom(s,a,t,i,this.changeTick,this._entityRows),l=A[0],this._onArchShrink(s,u),this._onArchGrow(r,d,_)}else{const u=r.length,d=r.enabledCount;l=r.addEntity(t,this._entityRows),this._onArchGrow(r,u,d)}for(let u=0;u<h.length;u++)r.writeFields(l,h[u].def.id,h[u].values??c.EMPTY_VALUES,this.changeTick);this._entityArchetypes[e]=n,this._entityRows[e]=l}removeComponent(t,e){if(!this.isAlive(t))return;const s=c.getEntityIndex(t),r=this._entityArchetypes[s],n=this._archGet(r),i=n.getEdge(e.id);if(i===void 0||i.remove===null){this._removeComponentCold(t,n,r,e);return}const h=i.remove,a=this._archGet(h),l=this._entityRows[s],u=!a.hasColumns&&!n.hasColumns,d=n.length,_=a.length,f=a.enabledCount;u?a.moveEntityFromTag(n,l,t,this._entityRows):a.moveEntityFrom(n,l,t,i.removeMap,this.changeTick,this._entityRows),this._entityArchetypes[s]=h,this._entityRows[s]=A[0],this._onArchShrink(n,d),this._onArchGrow(a,_,f)}_removeComponentCold(t,e,s,r){e.hasComponent(r.id)&&(this._archResolveRemove(s,r.id),this.removeComponent(t,r))}removeComponents(t,e){if(!this.isAlive(t))return;const s=c.getEntityIndex(t),r=this._entityArchetypes[s],n=this._archGet(r);let i=null;for(let y=0;y<e.length;y++){const g=e[y].id;i!==null?i.clear(g):n.mask.has(g)&&(i=n.mask.copyInto(this._scratchTargetMask),i.clear(g))}if(i===null)return;const h=this._archGetOrCreateFromMask(i),a=this._archGet(h),l=this._entityRows[s],u=n.length,d=a.length,_=a.enabledCount,f=n.transitionMapTo(a);a.moveEntityFrom(n,l,t,f,this.changeTick,this._entityRows),this._entityArchetypes[s]=h,this._entityRows[s]=A[0],this._onArchShrink(n,u),this._onArchGrow(a,d,_)}hasComponent(t,e){const s=this._liveIndex(t);return s<0?!1:this._archGet(this._entityArchetypes[s]).hasComponent(e.id)}batchAddComponent(t,e,s){const r=this._archGet(t);if(r.length===0)return;const n=e.id;if(r.mask.has(n))return;const i=this._archResolveAdd(r.id,n),h=this._archGet(i);if(r.disabledCount>0||h.disabledCount>0)throw new c.ECSError(c.ECS_ERROR.PARTITION_BULK_INTO_DISABLED,"batchAddComponent is unsupported on archetypes with disabled entities, enable them first or use per-entity addComponent");const a=r.getEdge(n),l=r.length,u=l,d=h.length,_=h.enabledCount,f=this._entityArchetypes,y=this._entityRows,g=h.bulkMoveAllFrom(r,a.addMap,this.changeTick);for(let p=0;p<l;p++){const m=c.getEntityIndex(h.entityIds[g+p]);f[m]=i,y[m]=g+p}this._componentMetas[n].fieldNames.length>0&&s&&h.bulkWriteFields(g,l,n,s,this.changeTick),this._onArchShrink(r,u),this._onArchGrow(h,d,_)}batchRemoveComponent(t,e){const s=this._archGet(t);if(s.length===0)return;const r=e.id;if(!s.mask.has(r))return;const n=this._archResolveRemove(s.id,r),i=this._archGet(n);if(s.disabledCount>0||i.disabledCount>0)throw new c.ECSError(c.ECS_ERROR.PARTITION_BULK_INTO_DISABLED,"batchRemoveComponent is unsupported on archetypes with disabled entities, enable them first or use per-entity removeComponent");const h=s.getEdge(r),a=s.length,l=a,u=this._entityArchetypes,d=this._entityRows;if(!i.materializesRows){const g=s.entityIds;for(let E=0;E<a;E++){const p=c.getEntityIndex(g[E]);u[p]=n,d[p]=c.UNASSIGNED}s.clearRows(),this._onArchShrink(s,l);return}const _=i.length,f=i.enabledCount,y=i.bulkMoveAllFrom(s,h.removeMap,this.changeTick);for(let g=0;g<a;g++){const E=c.getEntityIndex(i.entityIds[y+g]);u[E]=n,d[E]=y+g}this._onArchShrink(s,l),this._onArchGrow(i,_,f)}getEntityArchetype(t){return this._archGet(this._entityArchetypes[c.getEntityIndex(t)])}getEntityRow(t){return this._entityRows[c.getEntityIndex(t)]}resolvedRow=0;resolveEntity(t){const e=t&k;return this.resolvedRow=this._entityRows[e],this._archGet(this._entityArchetypes[e])}cursorBinder(t,e){const s=t.id,r=k;return(n,i)=>{const h=i&r,a=this._archGet(this._entityArchetypes[h]);e&&(a.changedTick[s]=this.changeTick,this.anyDirtyTracked&&this.noteSet(s,a,this._entityRows[h],i)),n.__cols=a.accessorColumns[s],n.__row=this._entityRows[h]}}componentFieldNames(t){return this._componentMetas[t.id].fieldNames}getMatchingArchetypes(t,e,s){return this._queries.matching(t,e,s)}registerQuery(t,e,s){return this._queries.register(t,e,s)}updateQueryRef(t,e){this._queries.updateRef(t,e)}get archetypeCount(){return this._archGraph.archetypes.length}_resources=new Be}class os{_store;constructor(t){this._store=t}register(t,e){this._store.resources.register(t,e)}get(t){return c.unsafeCast(this._store.resources.get(t))}set(t,e){this._store.resources.set(t,e)}remove(t){this._store.resources.remove(t)}has(t){return this._store.resources.has(t)}}class le{_store;constructor(t){this._store=t}get deterministic(){return this._store.deterministic}stateHash(){return this._store.stateHash()}}for(const o of["capture","restore","captureSparse","restoreSparse"])le.prototype[o]=function(){throw c.pluginMissingError("snapshots",`ecs.snapshots.${o}`)};function hs(o){return Object.freeze({name:o})}function as(o){return!("fn"in o)}function cs(o,t,e,s,r){if(o.length===0)return[];const n=[],i=new Map,h=new Set,a=new Map;for(const _ of o){n.push(_.descriptor),i.set(_.descriptor,_.insertionOrder),h.add(_.descriptor);for(let f=0;f<_.sets.length;f++){const y=_.sets[f];let g=a.get(y);g===void 0&&(g=[],a.set(y,g)),g.push(_.descriptor)}}const l=new Map;for(const _ of o)l.set(_.descriptor,[]);for(const _ of o){Z(_.descriptor,_.before,"before",h,a,l),Z(_.descriptor,_.after,"after",h,a,l);for(let f=0;f<_.sets.length;f++){const y=e.get(_.sets[f]);y!==void 0&&(Z(_.descriptor,y.before,"before",h,a,l),Z(_.descriptor,y.after,"after",h,a,l))}}const u=(_,f)=>i.get(_)-i.get(f),d=_=>_.name??`system_${_.id}`;try{return I.topologicalSort(n,l,u,d)}catch(_){throw _ instanceof TypeError?new c.ECSError(c.ECS_ERROR.CIRCULAR_SYSTEM_DEPENDENCY,`Circular system dependency detected in ${t}: ${_.message}`):_}}function Z(o,t,e,s,r,n,i,h,a){for(const l of t){if(as(l)){const u=r.get(l);if(u===void 0)continue;for(let d=0;d<u.length;d++){const _=u[d];_!==o&&Ut(o,_,e,n)}continue}s.has(l)&&Ut(o,l,e,n)}}function Ut(o,t,e,s){e==="before"?s.get(o).push(t):s.get(t).push(o)}class ls{constructor(t,e,s,r){this.owner=t,this.name=e,this.loop=s,this.insertionOrder=r}nodes=[];plan=null;before=[];after=[]}const G=Object.freeze([]);function ct(o){return o===void 0?G:Array.isArray(o)?o:[o]}function gt(o,t,e){o(t,e)}function us(){const o=[function(){},function(){},function(){},function(){},function(){}];for(let e=0;e<500;e++)for(let s=0;s<o.length;s++)gt(o[s],null,0)}us();class ds{_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(t){this._onWarn=t??(a=>console.warn(a));const e=this._declarePhase(c.SCHEDULE.PRE_STARTUP,"startup"),s=this._declarePhase(c.SCHEDULE.STARTUP,"startup");s.after.push(e),this._declarePhase(c.SCHEDULE.POST_STARTUP,"startup").after.push(s),this._declarePhase(c.SCHEDULE.FIXED_UPDATE,"fixed");const n=this._declarePhase(c.SCHEDULE.PRE_UPDATE,"update"),i=this._declarePhase(c.SCHEDULE.UPDATE,"update");i.after.push(n),this._declarePhase(c.SCHEDULE.POST_UPDATE,"update").after.push(i);for(const a of this._phases)this._builtins.set(a.name,a);this._resolveOrder("startup"),this._resolveOrder("fixed"),this._resolveOrder("update")}addPhase(t,e){const s=this._declarePhase(t,e.loop);for(const r of e.before??G)s.before.push(this._checkPhase(r));for(const r of e.after??G)s.after.push(this._checkPhase(r));return this._resolveOrder(e.loop),s}_declarePhase(t,e){const s=new ls(this,t,e,this._nextPhaseOrder++);return this._phases.push(s),s}_checkPhase(t){return this._resolvePhase(t),t}_resolvePhase(t){if(typeof t=="string"){const s=this._builtins.get(t);if(s!==void 0)return s;throw new c.ECSError(c.ECS_ERROR.UNKNOWN_PHASE,`${t} is not a phase of this world. Pass a SCHEDULE member, or the handle addPhase returned`)}const e=t;if(e.owner!==this)throw new c.ECSError(c.ECS_ERROR.UNKNOWN_PHASE,`phase ${e.name} belongs to another world. Call addPhase on the world you are scheduling into`);return e}_resolveOrder(t){const e=[];for(let i=0;i<this._phases.length;i++)this._phases[i].loop===t&&e.push(this._phases[i]);const s=new Map;for(const i of e)s.set(i,[]);const r=new Set(e);for(const i of e){for(const h of i.before){const a=this._resolvePhase(h);a!==i&&r.has(a)&&s.get(i).push(a)}for(const h of i.after){const a=this._resolvePhase(h);a!==i&&r.has(a)&&s.get(a).push(i)}}let n;try{n=I.topologicalSort(e,s,(i,h)=>i.insertionOrder-h.insertionOrder,i=>i.name)}catch(i){throw i instanceof TypeError?new c.ECSError(c.ECS_ERROR.CIRCULAR_PHASE_DEPENDENCY,`the ${t} phases cannot be ordered: ${i.message}. Drop one before or after from addPhase`):i}t==="startup"?this._startupOrder=n:t==="fixed"?this._fixedOrder=n:this._updateOrder=n}addSystems(t,...e){const s=this._resolvePhase(t);for(const r of e){const n="system"in r,i=n?r.system:r,h=n?r.ordering:void 0,a=n?ct(r.runIf):G,l=n?ct(r.set):G,u={descriptor:i,insertionOrder:this._nextInsertionOrder++,before:new Set(h?.before??[]),after:new Set(h?.after??[]),conditions:a,sets:l};s.nodes.push(u),s.loop==="fixed"&&this._fixedSystemCount++,this._phaseBySystem.set(i,s),this._assignLastRunSlot(i),(a.length>0||l.length>0)&&this._gatedSystems.set(i,u),s.plan=null}}configureSet(t,e){const s=ct(e.runIf);if(s.length>0){const r=this._conditionsBySet.get(t);r===void 0?this._conditionsBySet.set(t,[...s]):r.push(...s)}if(e.before!==void 0||e.after!==void 0){let r=this._orderingBySet.get(t);r===void 0&&(r={before:new Set,after:new Set},this._orderingBySet.set(t,r));for(const n of e.before??G)r.before.add(n);for(const n of e.after??G)r.after.add(n);this._invalidatePlans()}}removeSystem(t){const e=this._phaseBySystem.get(t);if(e===void 0)return;const s=e.nodes,r=s.findIndex(i=>i.descriptor===t);if(r!==-1){const i=s.length-1;r!==i&&(s[r]=s[i]),s.pop(),e.loop==="fixed"&&this._fixedSystemCount--;for(const h of s)h.before.delete(t),h.after.delete(t)}this._phaseBySystem.delete(t);const n=this._slotBySystem.get(t);n!==void 0&&(this._lastRunTicks[n]=0,this._slotBySystem.delete(t),this._freeSlots.push(n)),this._gatedSystems.delete(t),this._invalidatePlans()}_invalidatePlans(){for(let t=0;t<this._phases.length;t++)this._phases[t].plan=null}setBackend(t){this._backend=t}setRoute(t){this._route=t}runStartup(t){this._driveDepth++;try{const e=this._startupOrder;for(let s=0;s<e.length;s++)this._runPhase(e[s],t,c.STARTUP_DELTA_TIME)}finally{this._driveDepth--}}runUpdate(t,e){this._driveDepth++;try{const s=this._updateOrder;for(let r=0;r<s.length;r++)this._runPhase(s[r],t,e)}finally{this._driveDepth--}}runFixedUpdate(t,e){this._driveDepth++;try{const s=this._fixedOrder;for(let r=0;r<s.length;r++)this._runPhase(s[r],t,e)}finally{this._driveDepth--}}hasFixedSystems(){return this._fixedSystemCount>0}getAllSystems(){const t=[];for(const e of this._phases)for(const s of e.nodes)t.push(s.descriptor);return t}hasSystem(t){return this._phaseBySystem.has(t)}_assignLastRunSlot(t){let e=this._slotBySystem.get(t);if(e===void 0){const s=this._driveDepth===0?this._freeSlots.pop():void 0;s!==void 0?(e=s,this._lastRunTicks[e]=0):(e=this._lastRunTicks.length,this._lastRunTicks.push(0)),this._slotBySystem.set(t,e)}return e}clear(){for(const t of this._phases)t.nodes.length=0,t.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(t,e,s){const r=t.plan,n=r!==null?r:this._buildPlan(t),i=n.sorted,h=n.slots,a=this._gatedSystems.size>0,l=this._backend,u=this._route,d=l!==null||u!==null,_=l!==null?e.ecsTick:0,f=a?new Map:void 0;for(let y=0;y<i.length;y++){const g=i[y];if(a){const p=this._gatedSystems.get(g);if(p!==void 0&&!this._shouldRun(p,e,f))continue}e.lastRunTick=this._lastRunTicks[h[y]];const E=e.advanceChangeTick();try{if(d){const p=u!==null?g.routePlan:void 0;if(!(p!==void 0&&u.run(p,e,s,E))){const m=l!==null?g.backendHandle:void 0;m!==void 0?(e.publishRowCounts(),l.run(m,s,_)):g.fn!==void 0&>(g.fn,e,s)}}else g.fn!==void 0&>(g.fn,e,s)}finally{}this._lastRunTicks[h[y]]=E}e.advanceChangeTick(),e.flush()}_shouldRun(t,e,s){if(t.conditions.length>0&&!this._evalConditions(t.conditions,e))return!1;for(let r=0;r<t.sets.length;r++){const n=t.sets[r];let i=s.get(n);if(i===void 0){const h=this._conditionsBySet.get(n);i=h===void 0||h.length===0?!0:this._evalConditions(h,e),s.set(n,i)}if(!i)return!1}return!0}_evalConditions(t,e){for(let s=0;s<t.length;s++){const r=t[s];let n;try{n=r.evaluate(e)}finally{}if(!n)return!1}return!0}_buildPlan(t){const e=cs(t.nodes,t.name,this._orderingBySet,this._phaseBySystem,this._onWarn),s=new Int32Array(e.length);for(let n=0;n<e.length;n++)s[n]=this._assignLastRunSlot(e[n]);const r={sorted:e,slots:s};return t.plan=r,r}}const Ht=Object.freeze([]),_s=Object.freeze([]),$t=Object.freeze([]),fs=Object.freeze([]);function Rt(o){if(typeof o=="function"){const t=o.id;return e=>e.has(t)}return t=>o.matches(t)}function vt(o){return typeof o=="function"?c.componentDebugName(o)??`component ${o.id}`:o.name}function ps(...o){const t=o.map(Rt);return{name:`and(${o.map(vt).join(", ")})`,matches(s){for(let r=0;r<t.length;r++)if(!t[r](s))return!1;return!0}}}function gs(...o){const t=o.map(Rt);return{name:`or(${o.map(vt).join(", ")})`,matches(s){for(let r=0;r<t.length;r++)if(t[r](s))return!0;return!1}}}function ys(...o){const t=o.map(Rt);return{name:`not(${o.map(vt).join(", ")})`,matches(s){for(let r=0;r<t.length;r++)if(t[r](s))return!1;return!0}}}const qt=Object.freeze({sparseIncludes:Ht,sparseExcludes:Ht,optionalTerms:_s,includesDisabled:!1,relationIncludes:$t,relationExcludes:$t,hierarchyTerm:null,archetypeTerms:fs});function $(o,t){return Object.freeze({sparseIncludes:t.sparseIncludes??o.sparseIncludes,sparseExcludes:t.sparseExcludes??o.sparseExcludes,optionalTerms:t.optionalTerms??o.optionalTerms,includesDisabled:t.includesDisabled??o.includesDisabled,relationIncludes:t.relationIncludes??o.relationIncludes,relationExcludes:t.relationExcludes??o.relationExcludes,hierarchyTerm:t.hierarchyTerm!==void 0?t.hierarchyTerm:o.hierarchyTerm,archetypeTerms:t.archetypeTerms??o.archetypeTerms})}const yt=Number.POSITIVE_INFINITY;function z(o,t){return(o<<16|t)>>>0}function tt(o,t){for(let e=0;e<o.length;e++)if(o[e]===t)return o;return[...o,t]}function ms(o,t){for(let e=0;e<o.length;e++)if(o[e]===t)return o;return[...o,t]}function jt(o,t){for(let e=0;e<o.length;e++)if(o[e]===t)return o;return[...o,t]}class Tt{arch;tick=0;since=0;resolver;mut(t){return this.arch.columnGroupMut(t,this.tick)}read(t){return this.arch.columnGroupRead(t)}ticks(t){const e=this.arch,s=t.id,r=e.rowTicks[s];if(r===void 0)throw zt("cols.ticks",t,s);return e.changedTick[s]=this.tick,this.resolver.noteScan(s),r}ticksRead(t){const e=this.arch,s=t.id,r=e.rowTicks[s];if(r===void 0)throw zt("cols.ticksRead",t,s);return r}}function zt(o,t,e){return new c.ECSError(c.ECS_ERROR.ROW_TICKS_NOT_TRACKED,`${o}: ${c.componentLabel(t)} has no row ticks. Call ecs.trackRows(def), or register an onSet observer with granularity "entity", before the loop`,{component:e})}class N{_query;_changedIds;constructor(t,e){this._query=t,this._changedIds=e}and(...t){return new N(this._query.and(...t),this._changedIds)}not(...t){return new N(this._query.not(...t),this._changedIds)}or(...t){return new N(this._query.or(...t),this._changedIds)}optional(...t){return new N(this._query.optional(...t),this._changedIds)}forEach(t){if(this._query.includesDisabled){this._forEachIncludeDisabled(t);return}const e=this._query.lastRunTick(),s=this._query.nonEmptyArchs(),r=this._changedIds;for(let n=0;n<s.length;n++){const i=s[n];for(let h=0;h<r.length;h++)if(i.changedTick[r[h]]>e){t(i);break}}}forEachChunk(t){if(this._query.includesDisabled){const e=x(!0);try{this._forEachChunkInner(t)}finally{x(e)}return}this._forEachChunkInner(t)}_forEachChunkInner(t){const e=this._query,s=new Tt;s.tick=e.changeTick(),s.since=e.lastRunTick(),s.resolver=e.resolver();const r=s.since,n=e.nonEmptyArchs(),i=this._changedIds;for(let h=0;h<n.length;h++){const a=n[h];for(let l=0;l<i.length;l++)if(a.changedTick[i[l]]>r){s.arch=a,t(s,a.entityCount);break}}}_forEachIncludeDisabled(t){const e=x(!0);try{this._forEachInner(t)}finally{x(e)}}_forEachInner(t){const e=this._query.lastRunTick(),s=this._query.nonEmptyArchs(),r=this._changedIds;for(let n=0;n<s.length;n++){const i=s[n];for(let h=0;h<r.length;h++)if(i.changedTick[r[h]]>e){t(i);break}}}}class D{_archetypes;defs;_resolver;include;_exclude;_anyOf;_nonEmptyArchetypes=[];_lastSeenEpoch=-1;id;terms;includesDisabled;constructor(t,e,s,r,n,i,h,a=qt){this._archetypes=t,this.defs=e,this._resolver=s,this.include=r,this._exclude=n,this._anyOf=i,this.id=h,this.terms=a,this.includesDisabled=a.includesDisabled}_assertDenseOnly(t){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 c.ECSError(c.ECS_ERROR.SPARSE_QUERY_DENSE_PATH,`Query.${t} 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(t){const e=this.terms.archetypeTerms;if(e.length!==0)throw new c.ECSError(c.ECS_ERROR.QUERY_TERM_DENSE_PATH,`Query.${t} answers from the dense archetype list, and this query carries the archetype term ${e[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 e=this.nonEmptyArchs();for(let s=0;s<e.length;s++)if((this.includesDisabled?e[s].totalCount:e[s].enabledCount)>0)return e[s].entityIds[0];return}let t;return this.forEachEntity(e=>{t===void 0&&(t=e)}),t}singleEntity(){return this.firstEntity()}_countViaWalk(){let t=0;return this.forEachEntity(()=>{t++}),t}get archetypeCount(){return this._archetypes.length}get entityCount(){const t=this.nonEmptyArchs();let e=0;if(this.includesDisabled)for(let s=0;s<t.length;s++)e+=t[s].totalCount;else for(let s=0;s<t.length;s++)e+=t[s].enabledCount;return e}get excludeWords(){return this._exclude===null?null:this._exclude.words}get archetypes(){return this._archetypes}_carryNondense(t){return this.terms===qt?t:new D(t._archetypes,t.defs,this._resolver,t.include,t._exclude,t._anyOf,this._resolver.nextQueryId(),this.terms)}and(...t){if(t.length===1){const s=t[0].id,r=(this.id<<16|s)>>>0,n=this._resolver.caches.andSingle.get(r);return n!==void 0?n:this._andMiss(t[0],s,r)}let e=this;for(let s=0;s<t.length;s++)e=e.and(t[s]);return e}_andMiss(t,e,s){const r=this.include.copy(),n=this.defs.slice();r.has(e)||(r.set(e),n.push(t));const i=this._carryNondense(this._resolver.resolveQuery(r,this._exclude,this._anyOf,n));return this._resolver.caches.andSingle.set(s,i),i}not(...t){if(t.length===1){const s=t[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 e=this;for(let s=0;s<t.length;s++)e=e.not(t[s]);return e}_notMiss(t,e){const s=this._exclude?this._exclude.copy():new I.BitSet;s.set(t);const r=this._carryNondense(this._resolver.resolveQuery(this.include,s,this._anyOf,this.defs));return this._resolver.caches.notSingle.set(e,r),r}andSparse(...t){if(t.length===1)return this._andSparseOne(t[0]);let e=this;for(let s=0;s<t.length;s++)e=e._andSparseOne(t[s]);return e}_andSparseOne(t){const e=z(this.id,t),s=this._resolver.caches.andSparseSingle,r=s.get(e);if(r!==void 0)return r;const n=this._deriveSparse(tt(this.terms.sparseIncludes,t),this.terms.sparseExcludes);return s.set(e,n),n}notSparse(...t){if(t.length===1)return this._notSparseOne(t[0]);let e=this;for(let s=0;s<t.length;s++)e=e._notSparseOne(t[s]);return e}_notSparseOne(t){const e=z(this.id,t),s=this._resolver.caches.notSparseSingle,r=s.get(e);if(r!==void 0)return r;const n=this._deriveSparse(this.terms.sparseIncludes,tt(this.terms.sparseExcludes,t));return s.set(e,n),n}_deriveSparse(t,e){return new D(this._archetypes,this.defs,this._resolver,this.include,this._exclude,this._anyOf,this._resolver.nextQueryId(),$(this.terms,{sparseIncludes:t,sparseExcludes:e}))}where(t){const e=this._resolver.caches.whereSingle;let s=e.get(t);s===void 0&&(s=new Map,e.set(t,s));const r=s.get(this.id);if(r!==void 0)return r;const n=new D(this._archetypes,this.defs,this._resolver,this.include,this._exclude,this._anyOf,this._resolver.nextQueryId(),$(this.terms,{archetypeTerms:[...this.terms.archetypeTerms,t]}));return s.set(this.id,n),n}andRelation(...t){if(t.length===1)return this._andRelationOne(t[0]);let e=this;for(let s=0;s<t.length;s++)e=e._andRelationOne(t[s]);return e}_andRelationOne(t){const e=z(this.id,t),s=this._resolver.caches.andRelationSingle,r=s.get(e);if(r!==void 0)return r;const n=this._resolver.relationBackingSparseId(t,"query.andRelation"),i=this._deriveRelation(tt(this.terms.sparseIncludes,n),this.terms.sparseExcludes,jt(this.terms.relationIncludes,t),this.terms.relationExcludes);return s.set(e,i),i}notRelation(...t){if(t.length===1)return this._notRelationOne(t[0]);let e=this;for(let s=0;s<t.length;s++)e=e._notRelationOne(t[s]);return e}_notRelationOne(t){const e=z(this.id,t),s=this._resolver.caches.notRelationSingle,r=s.get(e);if(r!==void 0)return r;const n=this._resolver.relationBackingSparseId(t,"query.notRelation"),i=this._deriveRelation(this.terms.sparseIncludes,tt(this.terms.sparseExcludes,n),this.terms.relationIncludes,jt(this.terms.relationExcludes,t));return s.set(e,i),i}_deriveRelation(t,e,s,r){return new D(this._archetypes,this.defs,this._resolver,this.include,this._exclude,this._anyOf,this._resolver.nextQueryId(),$(this.terms,{sparseIncludes:t,sparseExcludes:e,relationIncludes:s,relationExcludes:r}))}hierarchy(t,e=yt){if(e===yt){const s=z(this.id,t),r=this._resolver.caches.hierarchySingle,n=r.get(s);if(n!==void 0)return n;const i=this._deriveHierarchy({relation:t,maxDepth:e});return r.set(s,i),i}return this._deriveHierarchy({relation:t,maxDepth:e})}_deriveHierarchy(t){return new D(this._archetypes,this.defs,this._resolver,this.include,this._exclude,this._anyOf,this._resolver.nextQueryId(),$(this.terms,{hierarchyTerm:t}))}_assertRelationAccess(){for(let t=0;t<this.terms.relationIncludes.length;t++)c.accessCheck.assertRelationRead(this.terms.relationIncludes[t]);for(let t=0;t<this.terms.relationExcludes.length;t++)c.accessCheck.assertRelationRead(this.terms.relationExcludes[t])}forEachRelatedTo(t,e){this._resolver.forEachTargetMatch(t,this.include,this._exclude,this._anyOf,this.terms,e)}optional(...t){if(t.length===1)return this._optionalOne(t[0].id);let e=this;for(let s=0;s<t.length;s++)e=e._optionalOne(t[s].id);return e}_optionalOne(t){const e=(this.id<<16|t)>>>0,s=this._resolver.caches.optionalSingle,r=s.get(e);if(r!==void 0)return r;const n=this._deriveOptional(ms(this.terms.optionalTerms,t));return s.set(e,n),n}_deriveOptional(t){return new D(this._archetypes,this.defs,this._resolver,this.include,this._exclude,this._anyOf,this._resolver.nextQueryId(),$(this.terms,{optionalTerms:t}))}includeDisabled(){if(this.includesDisabled)return this;const t=this._resolver.caches.includeDisabledSingle,e=t.get(this.id);if(e!==void 0)return e;const s=new D(this._archetypes,this.defs,this._resolver,this.include,this._exclude,this._anyOf,this._resolver.nextQueryId(),$(this.terms,{includesDisabled:!0}));return t.set(this.id,s),s}forEach(t){if(this.includesDisabled){this._forEachIncludeDisabled(t);return}const e=this.nonEmptyArchs();for(let s=0;s<e.length;s++)t(e[s])}_forEachIncludeDisabled(t){const e=x(!0);try{this._forEachInner(t)}finally{x(e)}}forEachChunk(t){if(this.includesDisabled){const e=x(!0);try{this._forEachChunkInner(t)}finally{x(e)}return}this._forEachChunkInner(t)}_forEachChunkInner(t){const e=new Tt;e.tick=this._resolver.getChangeTick(),e.since=this._resolver.getLastRunTick(),e.resolver=this._resolver;const s=this.nonEmptyArchs();for(let r=0;r<s.length;r++)e.arch=s[r],t(e,s[r].entityCount)}some(t){if(this.includesDisabled){const e=x(!0);try{return this._someInner(t)}finally{x(e)}}return this._someInner(t)}_someInner(t){const e=this.nonEmptyArchs();for(let s=0;s<e.length;s++)if(t(e[s]))return!0;return!1}_forEachInner(t){const e=this.nonEmptyArchs();for(let s=0;s<e.length;s++)t(e[s])}forEachEntity(t){if(this.terms.hierarchyTerm!==null){this._resolver.forEachHierarchyMatch(this.include,this._exclude,this._anyOf,this.terms,this.nonEmptyArchs(),this.terms.hierarchyTerm.relation,this.terms.hierarchyTerm.maxDepth,t);return}this._resolver.forEachSparseMatch(this.include,this._exclude,this._anyOf,this.terms,this.nonEmptyArchs(),t)}nonEmptyArchs(){const t=this._resolver.getQueryDirtyEpoch();return this._lastSeenEpoch!==t&&this._rebuildNonEmpty(t),this._nonEmptyArchetypes}_rebuildNonEmpty(t){if(this.terms.archetypeTerms.length!==0){this._rebuildFiltered(t);return}const e=this._archetypes,s=[];if(this.includesDisabled)for(let r=0;r<e.length;r++)e[r].totalCount>0&&s.push(e[r]);else for(let r=0;r<e.length;r++)e[r].enabledCount>0&&s.push(e[r]);this._nonEmptyArchetypes=s,this._lastSeenEpoch=t}_rebuildFiltered(t){const e=this._archetypes,s=this.terms.archetypeTerms,r=this.includesDisabled,n=[];t:for(let i=0;i<e.length;i++){const h=e[i];if((r?h.totalCount:h.enabledCount)!==0){for(let a=0;a<s.length;a++)if(!s[a].matches(h.mask))continue t;n.push(h)}}this._nonEmptyArchetypes=n,this._lastSeenEpoch=t}or(...t){if(t.length===1){const s=t[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 e=this;for(let s=0;s<t.length;s++)e=e.or(t[s]);return e}_orMiss(t,e){const s=this._anyOf?this._anyOf.copy():new I.BitSet;s.set(t);const r=this._carryNondense(this._resolver.resolveQuery(this.include,this._exclude,s,this.defs));return this._resolver.caches.orSingle.set(e,r),r}changed(...t){if(t.length===1){const s=t[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 e=new Array(t.length);for(let s=0;s<t.length;s++)e[s]=t[s].id;return new N(this,e)}_changedMiss(t,e){const s=new N(this,[t]);return this._resolver.caches.changedSingle.set(e,s),s}lastRunTick(){return this._resolver.getLastRunTick()}changeTick(){return this._resolver.getChangeTick()}resolver(){return this._resolver}assertDenseOnly(t){this._assertDenseOnly(t)}}class ue{constructor(t){this._resolver=t}and(...t){const e=new I.BitSet;for(let s=0;s<t.length;s++)e.set(t[s].id);return this._resolver.resolveQuery(e,null,null,t)}}class Es{_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(t,e,s,r){const n=this._dedup.get(t);if(n)for(let i=0;i<n.length;i++){const h=n[i];if(!(!h.includeMask.equals(e)||!(s===null?h.excludeMask===null:h.excludeMask!==null&&h.excludeMask.equals(s))||!(r===null?h.anyOfMask===null:h.anyOfMask!==null&&h.anyOfMask.equals(r))))return h}}addDedup(t,e){ie(this._dedup,t,e)}}class de{constructor(t){this._store=t}spawn(...t){const e=this._store.createEntity();for(let s=0;s<t.length;s++){const r=q(t[s]);this._store.addComponentDeferred(e,r,j(t[s]))}return e}add(t,...e){if(e.length===2&&typeof e[0]=="function"&&e[1]!==null&&typeof e[1]=="object"&&typeof e[1].def!="function"){const s=e[0];return this._store.addComponentDeferred(t,s,e[1]),this}for(let s=0;s<e.length;s++){const r=e[s],n=q(r);this._store.addComponentDeferred(t,n,j(r))}return this}remove(t,e){return this._store.removeComponentDeferred(t,e),this}despawn(t){const e=t;return this._store.destroyEntityDeferred(e),this}disable(t){return this._store.disableEntityDeferred(t),this}enable(t){return this._store.enableEntityDeferred(t),this}}class _e{constructor(t){this._store=t,this.commands=new de(t)}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(t){return this._store.isAlive(t)}hasComponent(t,e){return this._store.hasComponent(t,e)}getField(t,e,s){const r=this._store.resolveEntity(t),n=this._store.resolvedRow;return r.readField(n,e.id,s)}tryGetField(t,e,s){if(!this._store.hasComponent(t,e))return;const r=this._store.resolveEntity(t),n=this._store.resolvedRow;return r.readField(n,e.id,s)}setField(t,e,s,r){const n=this._store.resolveEntity(t),i=this._store.resolvedRow,h=n.getColumnMut(e,s,this._store.changeTick);h[i]=r,this._store.anyDirtyTracked&&this._store.noteSet(e.id,n,i,t)}updateField(t,e,s,r){const n=this._store.resolveEntity(t),i=this._store.resolvedRow,h=r(n.readField(i,e.id,s)),a=n.getColumnMut(e,s,this._store.changeTick);return a[i]=h,this._store.anyDirtyTracked&&this._store.noteSet(e.id,n,i,t),h}markChanged(t,e){this._store.anyDirtyTracked&&this._store.noteSetEntity(e,t)}ref(t,e){const s=this._store.resolveEntity(e),r=this._store.resolvedRow;return s.changedTick[t.id]=this._store.changeTick,this._store.anyDirtyTracked&&this._store.noteSet(t.id,s,r,e),ut(s.accessorColumns[t.id],r)}refRead(t,e){const s=this._store.resolveEntity(e),r=this._store.resolvedRow;return ut(s.accessorColumns[t.id],r)}cursor(t){return st(this._store.componentFieldNames(t),this._store.cursorBinder(t,!0))}cursorRead(t){return st(this._store.componentFieldNames(t),this._store.cursorBinder(t,!1))}isDisabled(t){return this._store.isDisabled(t)}addSparse(t,e,...s){return this._store.addSparse(t,e,s[0]),this}removeSparse(t,e){return this._store.removeSparse(t,e),this}hasSparse(t,e){return this._store.hasSparse(t,e)}getSparseField(t,e,s){return this._store.getSparseField(t,e,s)}setSparseField(t,e,s,r){this._store.setSparseField(t,e,s,r)}sparseCursor(t){return rt(this._store.sparseFieldNames(t),this._store.sparseAccessorColumns(t),this._store.sparseCursorCheck(t,!0),this._store.sparseTickPlane(t),this._store)}sparseChanged(t,e){return this._store.sparseTickOf(t,e)>this.lastRunTick}sparseCursorRead(t){return rt(this._store.sparseFieldNames(t),this._store.sparseAccessorColumns(t),this._store.sparseCursorCheck(t,!1))}addRelation(t,e,s){return this._store.requireRelations("ctx.addRelation").addRelation(t,e,s),this}removeRelation(t,e,s){return this._store.requireRelations("ctx.removeRelation").removeRelation(t,e,s),this}targetOf(t,e){return this._store.requireRelations("ctx.targetOf").targetOf(t,e)}targetsOf(t,e){return this._store.requireRelations("ctx.targetsOf").targetsOf(t,e)}sourcesOf(t,e){return this._store.requireRelations("ctx.sourcesOf").sourcesOf(t,e)}hasRelation(t,e){return this._store.requireRelations("ctx.hasRelation").hasRelation(t,e)}flush(){this._store.flushStructural(),this._store.flushDestroys(),this._store.publishRowCounts()}emit(t,e){const s=this._store.requireEvents("ctx.emit"),r=s.defByKey(t);e===void 0?s.emitSignal(r):s.emit(r,e)}readEvents(t){const e=this._store.requireEvents("ctx.readEvents"),s=e.defByKey(t);return e.reader(s)}getResource(t){return c.unsafeCast(this._store.resources.get(t))}setResource(t,e){this._store.resources.set(t,e)}removeResource(t){this._store.resources.remove(t)}hasResource(t){return this._store.resources.has(t)}}const ws=o=>c.unsafeCast(o),V=Object.freeze([]);function Vt(o){return typeof o=="object"&&!Array.isArray(o)}function Ss(o){let t=V;o.spawns!==void 0&&o.spawns.length>0&&(t=o.spawns.map(s=>Vt(s)?s.defs:s));let e=V;if(o.despawns!==void 0&&o.despawns.length>0){const s=[];for(const r of o.despawns)Vt(r)?s.push(...r.defs):s.push(r);e=s}return{reads:o.reads,writes:o.writes,spawns:t,despawns:e,transitions:o.transitions??V,resourceReads:o.resourceReads??V,resourceWrites:o.resourceWrites??V,sparseReads:o.sparseReads,sparseWrites:o.sparseWrites,relationReads:o.relationReads,relationWrites:o.relationWrites}}const fe=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 Cs(o){return{...fe,fn:o}}function Rs(o,t,e){return Object.freeze({...o,...Ss(o),routePlan:t,id:ws(e)})}function Yt(o){if(!(o>0)||!Number.isFinite(o))throw new c.ECSError(c.ECS_ERROR.INVALID_FIXED_TIMESTEP,`fixedTimestep must be a finite number > 0, got ${o}`);return o}function vs(o){if(!Number.isInteger(o)||o<1)throw new c.ECSError(c.ECS_ERROR.INVALID_MAX_FIXED_STEPS,`maxFixedSteps must be an integer >= 1, got ${o}`);return o}function Ts(o){const t=new Map,e=[],s=h=>{const a=h.hash(),l=t.get(a);if(l!==void 0){for(let u=0;u<l.length;u++)if(l[u].equals(h))return;l.push(h)}else t.set(a,[h]);e.push(h)},r=h=>{const a=new I.BitSet;for(let l=0;l<h.length;l++)a.set(h[l].id);return a},n=[];for(const h of o){const a=h.transitions;for(let l=0;l<a.length;l++){const u=a[l];n.push({whenHas:r(u.whenHas),add:u.add,remove:u.remove})}}for(const h of o){const a=h.spawns;for(let l=0;l<a.length;l++)s(r(a[l]))}for(;e.length>0;){const h=e.pop();for(let a=0;a<n.length;a++){const l=n[a];if(!h.contains(l.whenHas))continue;const u=h.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 i=[];for(const h of t.values())for(let a=0;a<h.length;a++)i.push(h[a]);return i}function bt(o){return Object.freeze(new Proxy(Object.freeze({}),{get(t,e){if(typeof e=="symbol"||e in Object.prototype||e==="toJSON"||e==="then")return Reflect.get(Object.prototype,e);throw c.pluginMissingError(o,`ecs.${o}.${e}`)}}))}const bs=bt("relations"),As=bt("events"),Is=bt("workers");function Os(){throw c.pluginMissingError("observers","ecs.observe")}class At{static create(t){const e=new At(t),s=t?.plugins;if(s!==void 0){const r=new Set;for(let n=0;n<s.length;n++){const i=s[n],h=i.requires;if(h!==void 0){for(let l=0;l<h.length;l++)if(!r.has(h[l]))throw c.pluginMissingError(h[l],`${i.name} plugin`)}if(r.has(i.name))throw c.pluginInstalledTwiceError(i.name);r.add(i.name);const a=i.install(e._pluginHost());Object.assign(e,a)}}return e}_pluginHost(){return{store:this._store,changes:this._store,world:this,context:this._ctx,onSettle:t=>{this._settleHooks.push(t)},onPrewarm:t=>{this._prewarmSources.push(t)},onDispose:t=>{this._disposeHooks.push(t)},memory:this._pluginMemory(),installRoute:t=>{if(this._routePlanner!==null)throw c.pluginInstalledTwiceError("route");this._routePlanner=t;const e=this._schedule;return{route:s=>e.setRoute(s)}}}}_pluginMemory(){const t=this._memory,e=this._store;return{get backing(){if(t.wasmMemory!==null)return t.wasmMemory;const s=e.columnStore.buffer;return typeof SharedArrayBuffer<"u"&&s instanceof SharedArrayBuffer?s:null},backingSource:t.source,storeBase:t.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 Es;_layoutSubscribers=[];_backend=null;_routePlanner=null;_memory;get memoryPlan(){return this._memory}get wasmMemory(){return this._memory.wasmMemory}constructor(t){const e=Object.prototype.hasOwnProperty;if(t!==void 0&&(e.call(t,"initial_capacity")||e.call(t,"buffer_allocator")))throw new c.ECSError(c.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)");const s=c.resolveECSMemory(t?.memory);this._memory=s,this._store=new is({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 i=0;i<n.length;i++)n[i].setLayout(s.storeBase)},regions:t?.regions,bindingsRegionBytes:t?.bindingsRegionBytes,deterministic:t?.deterministic}),this._schedule=new ds(t?.onWarn),this.resources=new os(this._store),this.snapshots=new le(this._store);const r=this;r.relations=bs,r.events=As,r.observe=Os,r.workers=Is,this._ctx=new _e(this._store),this._fixedTimestep=Yt(t?.fixedTimestep??c.DEFAULT_FIXED_TIMESTEP),this._maxFixedSteps=vs(t?.maxFixedSteps??c.DEFAULT_MAX_FIXED_STEPS)}regionHandles(...t){const e=new Array(t.length);let s=null;for(let r=0;r<t.length;r++){const n=this._store.regionHandle(t[r]);n===null?(s??=[]).push(t[r]):e[r]=n}if(s!==null)throw new c.ECSError(c.ECS_ERROR.REGION_NOT_DECLARED,`regionHandles: region ids [${s.join(", ")}] are not declared. Pass them in ECSOptions.regions`);return e}subscribeLayout(t){return this._layoutSubscribers.push(t),t.setLayout(this._memory.storeBase),()=>{const e=this._layoutSubscribers.indexOf(t);e>=0&&this._layoutSubscribers.splice(e,1)}}attachBackend(t){this._backend=t,this._schedule.setBackend(t);const e=this.subscribeLayout(t);return()=>{e(),this._backend===t&&(this._backend=null,this._schedule.setBackend(null))}}get fixedTimestep(){return this._fixedTimestep}set fixedTimestep(t){this._fixedTimestep=Yt(t)}get fixedAlpha(){return this._accumulator/this._fixedTimestep}setTrace(t){}registerComponent(t,e,s){if(Array.isArray(t)){const n=typeof e=="string"?e:"f64",i=Object.create(null);for(const h of t)i[h]=n;return this._store.registerComponent(i,s?.name)}const r=typeof e=="object"?e:s;return this._store.registerComponent(t,r?.name)}registerSparseComponent(t,e,s){if(Array.isArray(t)){const n=typeof e=="string"?e:"f64",i=Object.create(null);for(const h of t)i[h]=n;return this._store.registerSparseComponent(i,s?.name)}const r=typeof e=="object"?e:s;return this._store.registerSparseComponent(t,r?.name)}spawn(t,e){return t===void 0?this._store.createEntity():this._store.spawn(t,e)}spawnBundle(...t){const e=this._store.createEntity();for(let s=0;s<t.length;s++){const r=t[s],n=q(r);this._store.addComponent(e,n,j(r))}return e}spawnMany(t,e,s){return this._store.spawnMany(t,e,s)}_assertOutsideSystem(t,e){if(this._updating&&c.accessCheck.current()!==null){const s=c.accessCheck.current(),r=s.name??`system_${s.id}`;throw new c.ECSError(c.ECS_ERROR.ACCESS_UNDECLARED,`ecs.${t} was called from inside system '${r}'. The host ${t} is immediate, unsafe mid-iteration, and invisible to observers. Use ${e} instead`,{op:t})}}despawn(t){return this._store.destroyEntity(t),this}disable(t){return this._store.disableEntity(t),this}enable(t){return this._store.enableEntity(t),this}addComponent(t,e,s){const r=q(e);return this._store.addComponent(t,r,s??j(e)),this}addComponents(t,...e){const s=[];for(let r=0;r<e.length;r++){const n=e[r];s.push({def:q(n),values:j(n)})}return this._store.addComponents(t,s),this}removeComponent(t,e){return this._store.removeComponent(t,e),this}removeComponents(t,...e){return this._store.removeComponents(t,e),this}batchAddComponent(t,e,s){return this._store.batchAddComponent(t,e,s),this}batchRemoveComponent(t,e){return this._store.batchRemoveComponent(t,e),this}getField(t,e,s){return this._store.resolveEntity(t).readField(this._store.resolvedRow,e.id,s)}refRead(t,e){const s=this._store.resolveEntity(e),r=this._store.resolvedRow;return ut(s.accessorColumns[t.id],r)}cursor(t){return st(this._store.componentFieldNames(t),this._store.cursorBinder(t,!0))}cursorRead(t){return st(this._store.componentFieldNames(t),this._store.cursorBinder(t,!1))}sparseCursor(t){return rt(this._store.sparseFieldNames(t),this._store.sparseAccessorColumns(t),this._store.sparseCursorCheck(t,!0),this._store.sparseTickPlane(t),this._store)}sparseCursorRead(t){return rt(this._store.sparseFieldNames(t),this._store.sparseAccessorColumns(t),this._store.sparseCursorCheck(t,!1))}tryGetField(t,e,s){return this._store.hasComponent(t,e)?this._store.resolveEntity(t).readField(this._store.resolvedRow,e.id,s):void 0}setField(t,e,s,r){const n=this._store.resolveEntity(t),i=this._store.resolvedRow,h=n.getColumnMut(e,s,this._store.changeTick);h[i]=r,this._store.anyDirtyTracked&&this._store.noteSet(e.id,n,i,t)}updateField(t,e,s,r){const n=r(this.getField(t,e,s));return this.setField(t,e,s,n),n}query(...t){const e=this._scratchMask;e.words.fill(0);for(let s=0;s<t.length;s++)e.set(t[s].id);return this.resolveQuery(e,null,null,t)}nextQueryId(){return this._nextQueryIdCounter++}resolveQuery(t,e,s,r){const n=t.hash(),i=e?e.hash():0,h=s?s.hash():0,a=n^Math.imul(i,c.HASH_GOLDEN_RATIO)^Math.imul(h,c.HASH_SECONDARY_PRIME)|0,l=this.caches.findDedup(a,t,e,s);if(l!==void 0)return l.query;const u=this._store.registerQuery(t,e??void 0,s??void 0),d=new D(u,r,this,t.copy(),e?.copy()??null,s?.copy()??null,this._nextQueryIdCounter++);return this._store.updateQueryRef(u,d),this.caches.addDedup(a,{includeMask:t.copy(),excludeMask:e?.copy()??null,anyOfMask:s?.copy()??null,query:d}),d}registerSystem(t,e){let s;if(typeof t=="function")if(e!==void 0){const h=e(new ue(this)),a=this._ctx,l=t;s={...fe,fn:(u,d)=>l(h,a,d)}}else s=Cs(t);else s=t;const r=this._routePlanner,n=r===null?void 0:r.plan(s),i=Rs(s,n,this._nextSystemId++);return this._systems.add(i),i}removeSystem(t){return this._schedule.removeSystem(t),t.onRemoved?.(),this._systems.delete(t),this}get systemCount(){return this._systems.size}startup(){this._prewarmArchetypes();try{for(const t of this._systems.values())if(t.onAdded!==void 0)try{t.onAdded(this._ctx)}finally{}this._schedule.runStartup(this._ctx)}finally{}this._store.hasEvents&&this._store.events.clear()}_prewarmArchetypes(){const t=this._prewarmSources,e=[];for(let r=0;r<t.length;r++)e.push(...t[r]());const s=Ts([...this._systems,...e]);s.length!==0&&this._store.archCreateManyFromMasks(s)}update(t){try{if(this._store.tick=this._tick,this._store.publishRowCounts(),this._schedule.hasFixedSystems()){this._accumulator+=t;const n=this._maxFixedSteps*this._fixedTimestep;for(this._accumulator>n&&(this._accumulator=n);this._accumulator>=this._fixedTimestep;)this._schedule.runFixedUpdate(this._ctx,this._fixedTimestep),this._accumulator-=this._fixedTimestep}this._schedule.runUpdate(this._ctx,t);const e=F&&this._store.hasEvents?this._store.events.devBufferedCount():0,s=this._store.advanceChangeTick(),r=this._settleHooks;for(let n=0;n<r.length;n++)r[n](s);F&&this._store.hasEvents&&this._store.events.devBufferedCount(),this._store.hasEvents&&this._store.events.clear(),this._tick++,this._store.advanceChangeTick()}finally{}}dispose(){const t=this._disposeHooks;for(let e=0;e<t.length;e++)t[e]();for(const e of this._systems.values())e.dispose?.(),e.onRemoved?.();this._systems.clear(),this._schedule.clear()}template(...t){const e=[];for(let s=0;s<t.length;s++){const r=t[s];e.push({def:q(r),values:j(r)})}return this._store.createTemplate(e)}regionOffset(t){return this._store.regionOffset(t)}regionHandle(t){return this._store.regionHandle(t)}fieldId(t,e){return this._store.fieldIdOf(t,e)}entityIdAtRow(t,e){return this._store.entityIdAtRow(t,e)}get columnStore(){return this._store.columnStore}get archetypeCount(){return this._store.archetypeCount}registerTag(){return this._store.registerComponent({})}registerSparseTag(){return this._store.registerSparseComponent({})}isAlive(t){return this._store.isAlive(t)}get entityCount(){return this._store.entityCount}hasComponent(t,e){return this._store.hasComponent(t,e)}isDisabled(t){return this._store.isDisabled(t)}addSparse(t,e,s){return this._store.addSparse(t,e,s),this}removeSparse(t,e){return this._store.removeSparse(t,e),this}hasSparse(t,e){return this._store.hasSparse(t,e)}getSparseField(t,e,s){return this._store.getSparseField(t,e,s)}setSparseField(t,e,s,r){this._store.setSparseField(t,e,s,r)}getLastRunTick(){return this._ctx.lastRunTick}getChangeTick(){return this._store.changeTick}noteScan(t){this._store.noteScan(t)}getQueryDirtyEpoch(){return this._store.queryDirtyEpoch}forEachSparseMatch(t,e,s,r,n,i){this._store.forEachSparseMatch(t,e,s,r,n,i)}relationBackingSparseId(t,e){return this._store.relationBackingSparseId(t,e)}forEachTargetMatch(t,e,s,r,n,i){this._store.forEachTargetMatch(t,e,s,r,n,i)}forEachHierarchyMatch(t,e,s,r,n,i,h,a){this._store.forEachHierarchyMatch(t,e,s,r,n,i,h,a)}addSystems(t,...e){return this._schedule.addSystems(t,...e),this}addPhase(t,e){return this._schedule.addPhase(t,e)}configureSet(t,e){return this._schedule.configureSet(t,e),this}trackRows(t){this._store.trackRows(t)}publishRowCounts(){this._store.publishRowCounts()}flush(){this._ctx.flush()}}function ks(o,t){return{name:`runIfResourceEq(${o.description??"?"})`,resourceReads:[o],evaluate:e=>e.getResource(o)===t}}function Ds(o,t=0){const e=(t%o+o)%o;return{name:`runEveryNTicks(${o}${e!==0?`, +${e}`:""})`,evaluate:s=>(s.ecsTick-e)%o===0}}function xs(o){return{name:"runIfAnyMatch",reads:o.defs,evaluate:()=>o.entityCount>0}}function It(o){const t=[],e=[];for(const s of o)s.reads&&t.push(...s.reads),s.resourceReads&&e.push(...s.resourceReads);return{...t.length>0?{reads:t}:{},...e.length>0?{resourceReads:e}:{}}}function Ms(o){return{name:`runIfNot(${o.name})`,...It([o]),evaluate:t=>!o.evaluate(t)}}function Ns(...o){return{name:`runIfAll(${o.map(t=>t.name).join(", ")})`,...It(o),evaluate:t=>o.every(e=>e.evaluate(t))}}function Fs(...o){return{name:`runIfAny(${o.map(t=>t.name).join(", ")})`,...It(o),evaluate:t=>o.some(e=>e.evaluate(t))}}function Bs(o){return o.kind==="spawn"&&o.onSpawned!==void 0?{kind:"spawn",components:o.components}:o}class Ps{seed;_startup=[];_ticks=[];_sink=this._startup;constructor(t=0){this.seed=t}openTick(t,e){const s=this._ticks[this._ticks.length-1];if(s!==void 0&&s.tick===t){this._sink=s.commands;return}const r=[];this._ticks.push({tick:t,dt:e,commands:r}),this._sink=r}record=t=>{this._sink.push(Bs(t))};log(){return{seed:this.seed,startup:this._startup,ticks:this._ticks}}snapshotLog(){return{seed:this.seed,startup:this._startup.map(t=>({...t})),ticks:this._ticks.map(t=>({...t,commands:t.commands.map(e=>({...e}))}))}}}const W="__component_def";function Gs(o){return JSON.stringify(o,(t,e)=>{if(typeof e=="function"&&"id"in e)return{[W]:e.id};if(e!==null&&typeof e=="object"&&W in e)throw new c.ECSError(c.ECS_ERROR.COMMAND_LOG_TAG_COLLISION,`cannot serialize the command log, a value object owns a field named "${W}", the reserved tag the serializer uses for component defs. Rename that component field so the log can round-trip losslessly.`);return e})}function Ls(o){return JSON.parse(o,(t,e)=>e!==null&&typeof e=="object"&&W in e?se(ee(e[W])):e)}function Us(o,t,e,s){for(const i of e.startup)t.push(i);o.startup();const r=s?.hash??o.snapshots.deterministic,n=[];for(const i of e.ticks){for(const h of i.commands)t.push(h);o.update(i.dt),r&&n.push(o.snapshots.stateHash())}return{startupCommands:e.startup.length,ticks:e.ticks.length,stateHashes:n}}function lt(o){return o.name??`system#${o.id}`}class Hs{_frames=[];_current=null;tickBegin(t,e){const s={tick:t,dt:e,events:[]};this._current=s,this._frames.push(s)}tickEnd(t){this._current=null}systemBegin(t,e){this._current?.events.push({kind:"system_start",system:lt(t),phase:e})}systemEnd(t){this._current?.events.push({kind:"system_end",system:lt(t)})}commandQueued(t,e,s){this._current?.events.push({kind:"command_queued",op:t,entity:e,component:s})}flushBegin(t){this._current?.events.push({kind:"flush_begin",phase:t})}flushEnd(t){this._current?.events.push({kind:"flush_end",phase:t})}phaseBoundary(t){}observerFired(t,e,s,r){this._current?.events.push({kind:"observer_fired",op:t,component:e,entity:s,observer:lt(r)})}eventEmitted(t){this._current?.events.push({kind:"event_emitted",key:t})}eventRead(t,e){this._current?.events.push({kind:"event_read",key:t,count:e})}frames(){return this._frames}reset(){this._frames.length=0,this._current=null}}function B(o,t){if(!(t>=0)||!Number.isFinite(t))throw new c.ECSError(c.ECS_ERROR.INVALID_FRAME_STEP,`${o} must be a finite number >= 0, got ${t}`);return t}function $s(o){if(!Number.isInteger(o)||o<0)throw new c.ECSError(c.ECS_ERROR.INVALID_FRAME_STEP,`frame count must be an integer >= 0, got ${o}`);return o}class qs{_ecs;_requestFrame;_cancelFrame;_frameHandle=null;_lastTimestampMs=null;_running=!1;_fixedDt;_maxDt;constructor(t,e={}){this._ecs=t,this._fixedDt=B("fixedDt",e.fixedDt??1/60),this._maxDt=B("maxDt",e.maxDt??.25);const s=globalThis;this._requestFrame=e.requestFrame??s.requestAnimationFrame?.bind(globalThis),this._cancelFrame=e.cancelFrame??s.cancelAnimationFrame?.bind(globalThis),e.autoStart===!0&&this.play()}get fixedDt(){return this._fixedDt}set fixedDt(t){this._fixedDt=B("fixedDt",t)}get maxDt(){return this._maxDt}set maxDt(t){this._maxDt=B("maxDt",t)}get isRunning(){return this._running}step(t=this._fixedDt){this._ecs.update(B("dt",t))}stepFrames(t,e=this._fixedDt){$s(t);const s=B("dt",e);for(let r=0;r<t;r++)this._ecs.update(s)}play(){if(!this._running){if(this._requestFrame===void 0)throw new c.ECSError(c.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=t=>{if(!this._running)return;const e=this._lastTimestampMs===null?this._fixedDt:(t-this._lastTimestampMs)/1e3;this._lastTimestampMs=t,this._ecs.update(Math.min(B("dt",e),this._maxDt)),this._running&&this._requestNextFrame()}}const js=1;function zs(o){return c.unsafeCast(Symbol(o))}function Vs(o){return c.unsafeCast(Symbol(o))}function Ys(o){return c.unsafeCast(Symbol(o))}const Ws="0.6.0";exports.ANY_RELATION=c.ANY_RELATION;exports.ECSError=c.ECSError;exports.ECSRestoreError=c.ECSRestoreError;exports.ECS_ERROR=c.ECS_ERROR;exports.HostCommandQueue=c.HostCommandQueue;exports.SCHEDULE=c.SCHEDULE;exports.applyHostCommand=c.applyHostCommand;exports.getEntityIndex=c.getEntityIndex;exports.installHostCommandSeam=c.installHostCommandSeam;exports.isEcsError=c.isEcsError;exports.spawnEntry=c.spawnEntry;exports.storeBaseAbove=c.storeBaseAbove;exports.uninstallHostCommandSeam=c.uninstallHostCommandSeam;exports.SabUnavailableError=et.SabUnavailableError;exports.ChangedQuery=N;exports.ChunkColumns=Tt;exports.Commands=de;exports.ECS=At;exports.ECS_SNAPSHOT_VERSION=js;exports.FrameStepper=qs;exports.FrameTraceRecorder=Hs;exports.HIERARCHY_UNBOUNDED=yt;exports.HostCommandRecorder=Ps;exports.Query=D;exports.QueryBuilder=ue;exports.SparseRestoreError=xe;exports.StoreRestoreError=De;exports.SystemContext=_e;exports.VERSION=Ws;exports.and=ps;exports.bundle=Ae;exports.deserializeCommandLog=Ls;exports.eventKey=zs;exports.not=ys;exports.or=gs;exports.replayCommandLog=Us;exports.resourceKey=Ys;exports.runEveryNTicks=Ds;exports.runIfAll=Ns;exports.runIfAny=Fs;exports.runIfAnyMatch=xs;exports.runIfNot=Ms;exports.runIfResourceEq=ks;exports.serializeCommandLog=Gs;exports.signalKey=Vs;exports.systemSet=hs;
|