@oasys/oecs 0.4.0 → 0.5.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 +553 -0
- package/README.md +42 -31
- package/dist/core/ecs/access_check.d.cts +77 -0
- package/dist/core/ecs/access_check.d.ts +8 -8
- package/dist/core/ecs/access_check.d.ts.map +1 -1
- package/dist/core/ecs/archetype.d.cts +486 -0
- package/dist/core/ecs/archetype.d.ts +23 -11
- package/dist/core/ecs/archetype.d.ts.map +1 -1
- package/dist/core/ecs/archetype_graph.d.cts +96 -0
- package/dist/core/ecs/archetype_graph.d.ts +96 -0
- package/dist/core/ecs/archetype_graph.d.ts.map +1 -0
- package/dist/core/ecs/builtin_relations.d.cts +43 -0
- package/dist/core/ecs/builtin_relations.d.ts +8 -8
- package/dist/core/ecs/builtin_relations.d.ts.map +1 -1
- package/dist/core/ecs/command_log.d.cts +116 -0
- package/dist/core/ecs/command_log.d.ts +13 -10
- package/dist/core/ecs/command_log.d.ts.map +1 -1
- package/dist/core/ecs/component.d.cts +176 -0
- package/dist/core/ecs/component.d.ts +75 -5
- package/dist/core/ecs/component.d.ts.map +1 -1
- package/dist/core/ecs/compute_backend.d.cts +37 -0
- package/dist/core/ecs/compute_backend.d.ts +2 -2
- package/dist/core/ecs/debug_names.d.cts +7 -0
- package/dist/core/ecs/debug_names.d.ts +7 -0
- package/dist/core/ecs/debug_names.d.ts.map +1 -0
- package/dist/core/ecs/deferred_commands.d.cts +55 -0
- package/dist/core/ecs/deferred_commands.d.ts +55 -0
- package/dist/core/ecs/deferred_commands.d.ts.map +1 -0
- package/dist/core/ecs/dispatch_trace.d.cts +93 -0
- package/dist/core/ecs/dispatch_trace.d.ts +3 -3
- package/dist/core/ecs/ecs.d.cts +562 -0
- package/dist/core/ecs/ecs.d.ts +314 -285
- package/dist/core/ecs/ecs.d.ts.map +1 -1
- package/dist/core/ecs/ecs_memory.d.cts +179 -0
- package/dist/core/ecs/ecs_memory.d.ts +1 -1
- package/dist/core/ecs/entity.d.cts +34 -0
- package/dist/core/ecs/entity.d.ts +7 -1
- package/dist/core/ecs/entity.d.ts.map +1 -1
- package/dist/core/ecs/entity_allocator.d.cts +59 -0
- package/dist/core/ecs/entity_allocator.d.ts +59 -0
- package/dist/core/ecs/entity_allocator.d.ts.map +1 -0
- package/dist/core/ecs/event.d.cts +79 -0
- package/dist/core/ecs/event.d.ts +36 -11
- package/dist/core/ecs/event.d.ts.map +1 -1
- package/dist/core/ecs/event_registry.d.cts +22 -0
- package/dist/core/ecs/event_registry.d.ts +22 -0
- package/dist/core/ecs/event_registry.d.ts.map +1 -0
- package/dist/core/ecs/facades.d.cts +158 -0
- package/dist/core/ecs/facades.d.ts +158 -0
- package/dist/core/ecs/facades.d.ts.map +1 -0
- package/dist/core/ecs/frame_stepper.d.cts +58 -0
- package/dist/core/ecs/frame_stepper.d.ts +58 -0
- package/dist/core/ecs/frame_stepper.d.ts.map +1 -0
- package/dist/core/ecs/frame_trace.d.cts +133 -0
- package/dist/core/ecs/frame_trace.d.ts +5 -5
- package/dist/core/ecs/frame_trace.d.ts.map +1 -1
- package/dist/core/ecs/host_commands.d.cts +274 -0
- package/dist/core/ecs/host_commands.d.ts +53 -31
- package/dist/core/ecs/host_commands.d.ts.map +1 -1
- package/dist/core/ecs/index.d.cts +46 -0
- package/dist/core/ecs/index.d.ts +45 -40
- package/dist/core/ecs/index.d.ts.map +1 -1
- package/dist/core/ecs/observer.d.cts +173 -0
- package/dist/core/ecs/observer.d.ts +43 -12
- package/dist/core/ecs/observer.d.ts.map +1 -1
- package/dist/core/ecs/query.d.cts +718 -0
- package/dist/core/ecs/query.d.ts +251 -90
- package/dist/core/ecs/query.d.ts.map +1 -1
- package/dist/core/ecs/ref.d.cts +31 -0
- package/dist/core/ecs/ref.d.ts +3 -3
- package/dist/core/ecs/relation.d.cts +243 -0
- package/dist/core/ecs/relation.d.ts +26 -14
- package/dist/core/ecs/relation.d.ts.map +1 -1
- package/dist/core/ecs/relation_service.d.cts +235 -0
- package/dist/core/ecs/relation_service.d.ts +235 -0
- package/dist/core/ecs/relation_service.d.ts.map +1 -0
- package/dist/core/ecs/resource.d.cts +53 -0
- package/dist/core/ecs/resource.d.ts +25 -5
- package/dist/core/ecs/resource.d.ts.map +1 -1
- package/dist/core/ecs/resource_registry.d.cts +20 -0
- package/dist/core/ecs/resource_registry.d.ts +20 -0
- package/dist/core/ecs/resource_registry.d.ts.map +1 -0
- package/dist/core/ecs/resume.d.cts +85 -0
- package/dist/core/ecs/resume.d.ts +6 -6
- package/dist/core/ecs/resume.d.ts.map +1 -1
- package/dist/core/ecs/run_condition.d.cts +81 -0
- package/dist/core/ecs/run_condition.d.ts +15 -9
- package/dist/core/ecs/run_condition.d.ts.map +1 -1
- package/dist/core/ecs/schedule.d.cts +142 -0
- package/dist/core/ecs/schedule.d.ts +15 -6
- package/dist/core/ecs/schedule.d.ts.map +1 -1
- package/dist/core/ecs/snapshot_service.d.cts +94 -0
- package/dist/core/ecs/snapshot_service.d.ts +94 -0
- package/dist/core/ecs/snapshot_service.d.ts.map +1 -0
- package/dist/core/ecs/sparse_store.d.cts +110 -0
- package/dist/core/ecs/sparse_store.d.ts +5 -2
- package/dist/core/ecs/sparse_store.d.ts.map +1 -1
- package/dist/core/ecs/store.d.cts +950 -0
- package/dist/core/ecs/store.d.ts +143 -342
- package/dist/core/ecs/store.d.ts.map +1 -1
- package/dist/core/ecs/store_layout_listener.d.cts +23 -0
- package/dist/core/ecs/system.d.cts +250 -0
- package/dist/core/ecs/system.d.ts +138 -22
- package/dist/core/ecs/system.d.ts.map +1 -1
- package/dist/{utils/arrays.d.ts → core/ecs/utils/arrays.d.cts} +1 -0
- package/dist/core/ecs/utils/error.d.cts +61 -0
- package/dist/core/ecs/utils/error.d.ts +12 -2
- package/dist/core/ecs/utils/error.d.ts.map +1 -1
- package/dist/core/store/action_ring.d.cts +136 -0
- package/dist/core/store/allocator.d.cts +238 -0
- package/dist/core/store/allocator.d.ts.map +1 -1
- package/dist/core/store/buffer_backed_column.d.cts +69 -0
- package/dist/core/store/buffer_backed_column.d.ts +2 -2
- package/dist/core/store/column_store.d.cts +273 -0
- package/dist/core/store/column_store.d.ts +18 -10
- package/dist/core/store/column_store.d.ts.map +1 -1
- package/dist/core/store/command_dispatch.d.cts +52 -0
- package/dist/core/store/command_ring.d.cts +107 -0
- package/dist/core/store/descriptor.d.cts +80 -0
- package/dist/core/store/descriptor.d.ts +1 -1
- package/dist/core/store/descriptor.d.ts.map +1 -1
- package/dist/core/store/entity_index.d.cts +108 -0
- package/dist/core/store/event_ring.d.cts +95 -0
- package/dist/core/store/extend.d.cts +39 -0
- package/dist/core/store/extend.d.ts +3 -73
- package/dist/core/store/extend.d.ts.map +1 -1
- package/dist/core/store/grow.d.cts +34 -0
- package/dist/core/store/grow.d.ts +4 -9
- package/dist/core/store/grow.d.ts.map +1 -1
- package/dist/core/store/header.d.cts +64 -0
- package/dist/core/store/header.d.ts +1 -1
- package/dist/core/store/header.d.ts.map +1 -1
- package/dist/core/store/index.d.cts +17 -0
- package/dist/core/store/index.d.ts +16 -15
- package/dist/core/store/index.d.ts.map +1 -1
- package/dist/core/store/layout_ops.d.cts +152 -0
- package/dist/core/store/layout_ops.d.ts +152 -0
- package/dist/core/store/layout_ops.d.ts.map +1 -0
- package/dist/core/store/region_table.d.cts +74 -0
- package/dist/core/store/region_table.d.ts +1 -1
- package/dist/core/store/region_table.d.ts.map +1 -1
- package/dist/core/store/snapshot.d.cts +43 -0
- package/dist/core/store/snapshot.d.ts +2 -2
- package/dist/core/store/state_hash.d.cts +38 -0
- package/dist/core/store/state_hash.d.ts +1 -1
- package/dist/core/store/store_regions.d.cts +38 -0
- package/dist/core/store/store_regions.d.ts +1 -1
- package/dist/core/store/vendored_abi/abi.d.ts +43 -0
- package/dist/core/store/{__generated__ → vendored_abi}/abi.d.ts.map +1 -1
- package/dist/dev_flag.d.cts +17 -0
- package/dist/dev_flag.d.ts +17 -0
- package/dist/dev_flag.d.ts.map +1 -0
- package/dist/extensions/editor/editor.d.cts +170 -0
- package/dist/extensions/editor/editor.d.ts +43 -22
- package/dist/extensions/editor/editor.d.ts.map +1 -1
- package/dist/extensions/editor/field_handle.d.cts +40 -0
- package/dist/extensions/editor/field_handle.d.ts +8 -3
- package/dist/extensions/editor/field_handle.d.ts.map +1 -1
- package/dist/extensions/editor/index.cjs +1 -1
- package/dist/extensions/editor/index.d.cts +21 -0
- package/dist/extensions/editor/index.d.ts +2 -2
- package/dist/extensions/editor/index.js +116 -88
- package/dist/extensions/reactive/ecs_sync.d.cts +214 -0
- package/dist/extensions/reactive/ecs_sync.d.ts +26 -22
- package/dist/extensions/reactive/ecs_sync.d.ts.map +1 -1
- package/dist/extensions/reactive/index.cjs +1 -1
- package/dist/extensions/reactive/index.d.cts +23 -0
- package/dist/extensions/reactive/index.d.ts +1 -1
- package/dist/extensions/reactive/index.js +106 -116
- package/dist/extensions/solid/index.cjs +1 -1
- package/dist/extensions/solid/index.d.cts +6 -0
- package/dist/extensions/solid/index.d.ts +2 -2
- package/dist/extensions/solid/index.js +8 -4
- package/dist/extensions/solid/kernel_solid.d.cts +45 -0
- package/dist/extensions/solid/kernel_solid.d.ts +6 -3
- package/dist/extensions/solid/kernel_solid.d.ts.map +1 -1
- package/dist/host_commands-BF8QMi3c.cjs +1 -0
- package/dist/host_commands-i4cAeyL5.js +2318 -0
- package/dist/index.cjs +1 -2
- package/dist/index.d.cts +66 -0
- package/dist/index.d.ts +50 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +4469 -5933
- package/dist/internal.cjs +2 -0
- package/dist/internal.d.cts +20 -0
- package/dist/internal.d.ts +20 -0
- package/dist/internal.d.ts.map +1 -0
- package/dist/internal.js +141 -0
- package/dist/primitives.cjs +1 -1
- package/dist/primitives.d.cts +18 -0
- package/dist/primitives.d.ts +6 -6
- package/dist/primitives.js +24 -23
- package/dist/reactive/array.d.ts +24 -0
- package/dist/reactive/array.d.ts.map +1 -0
- package/dist/reactive/index.cjs +1 -0
- package/dist/reactive/index.d.cts +11 -0
- package/dist/reactive/index.d.ts +11 -0
- package/dist/reactive/index.d.ts.map +1 -0
- package/dist/reactive/index.js +18 -0
- package/dist/reactive/interop.d.cts +19 -0
- package/dist/{core/reactive → reactive}/interop.d.ts +1 -1
- package/dist/reactive/interop.d.ts.map +1 -0
- package/dist/reactive/kernel.d.cts +73 -0
- package/dist/{core/reactive → reactive}/kernel.d.ts +5 -3
- package/dist/reactive/kernel.d.ts.map +1 -0
- package/dist/reactive/map.d.ts +16 -0
- package/dist/reactive/map.d.ts.map +1 -0
- package/dist/reactive/shallow.d.cts +11 -0
- package/dist/reactive/shallow.d.ts +11 -0
- package/dist/reactive/shallow.d.ts.map +1 -0
- package/dist/reactive/struct.d.cts +10 -0
- package/dist/{core/reactive → reactive}/struct.d.ts +1 -1
- package/dist/reactive/struct.d.ts.map +1 -0
- package/dist/shallow-DQ8aG51_.cjs +1 -0
- package/dist/shallow-DfnAm9vG.js +150 -0
- package/dist/shared-BU1Cd40h.js +103 -0
- package/dist/shared-BymrGTyR.cjs +1 -0
- package/dist/shared.cjs +1 -1
- package/dist/shared.d.cts +22 -0
- package/dist/shared.d.ts +2 -2
- package/dist/shared.js +1 -1
- package/dist/topological_sort-BDvEyb9W.cjs +1 -0
- package/dist/topological_sort-DK6EjpWa.js +135 -0
- package/dist/type_primitives/assertions.d.cts +32 -0
- package/dist/type_primitives/assertions.d.ts +13 -1
- package/dist/type_primitives/assertions.d.ts.map +1 -1
- package/dist/type_primitives/binary_heap/binary_heap.d.cts +37 -0
- package/dist/type_primitives/bitset/bitset.d.cts +54 -0
- package/dist/type_primitives/brand.d.cts +23 -0
- package/dist/type_primitives/error.d.cts +16 -0
- package/dist/type_primitives/error.d.ts +4 -3
- package/dist/type_primitives/error.d.ts.map +1 -1
- package/dist/type_primitives/index.d.cts +13 -0
- package/dist/type_primitives/index.d.ts +9 -9
- package/dist/type_primitives/sparse_map/sparse_map.d.cts +30 -0
- package/dist/type_primitives/sparse_set/sparse_set.d.cts +28 -0
- package/dist/type_primitives/topological_sort/topological_sort.d.cts +29 -0
- package/dist/type_primitives/typed_arrays/typed_arrays.d.cts +127 -0
- package/dist/typed_arrays-BcXcnzB4.js +258 -0
- package/dist/typed_arrays-D3NmwtCG.cjs +1 -0
- package/dist/utils/error.d.cts +6 -0
- package/dist/version.d.cts +10 -0
- package/dist/version.d.ts +10 -0
- package/dist/version.d.ts.map +1 -0
- package/package.json +102 -19
- package/dist/array-CxbPyiHO.cjs +0 -1
- package/dist/array-uFR7Q8fU.js +0 -132
- package/dist/core/reactive/array.d.ts.map +0 -1
- package/dist/core/reactive/index.cjs +0 -1
- package/dist/core/reactive/index.d.ts +0 -10
- package/dist/core/reactive/index.d.ts.map +0 -1
- package/dist/core/reactive/index.js +0 -17
- package/dist/core/reactive/interop.d.ts.map +0 -1
- package/dist/core/reactive/kernel.d.ts.map +0 -1
- package/dist/core/reactive/map.d.ts.map +0 -1
- package/dist/core/reactive/struct.d.ts.map +0 -1
- package/dist/log/console_sink.d.ts +0 -4
- package/dist/log/console_sink.d.ts.map +0 -1
- package/dist/log/index.d.ts +0 -3
- package/dist/log/index.d.ts.map +0 -1
- package/dist/log/logger.d.ts +0 -27
- package/dist/log/logger.d.ts.map +0 -1
- package/dist/shared-BXSZnxx4.cjs +0 -1
- package/dist/shared-C678TAPY.js +0 -99
- package/dist/topological_sort-DlRpSrxu.js +0 -391
- package/dist/topological_sort-WAT-VHb-.cjs +0 -1
- package/dist/utils/arrays.d.ts.map +0 -1
- package/dist/utils/constants.d.ts.map +0 -1
- /package/dist/{utils/constants.d.ts → core/ecs/utils/constants.d.cts} +0 -0
- /package/dist/core/store/{__generated__/abi.d.ts → vendored_abi/abi.d.cts} +0 -0
- /package/dist/{core/reactive/array.d.ts → reactive/array.d.cts} +0 -0
- /package/dist/{core/reactive/map.d.ts → reactive/map.d.cts} +0 -0
package/dist/index.cjs
CHANGED
|
@@ -1,2 +1 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const U=require("./topological_sort-WAT-VHb-.cjs"),B=require("./shared-BXSZnxx4.cjs");class Ls extends Error{constructor(e,t,s){super(e),this.isOperational=t,this.context=s,this.name=this.constructor.name,Error.captureStackTrace(this,this.constructor)}}function Ye(i,e,t){return i}var I=(i=>(i.EID_MAX_INDEX_OVERFLOW="EID_MAX_INDEX_OVERFLOW",i.EID_MAX_GEN_OVERFLOW="EID_MAX_GEN_OVERFLOW",i.COMPONENT_NOT_REGISTERED="COMPONENT_NOT_REGISTERED",i.COMPONENT_LIMIT_EXCEEDED="COMPONENT_LIMIT_EXCEEDED",i.ENTITY_NOT_ALIVE="ENTITY_NOT_ALIVE",i.CIRCULAR_SYSTEM_DEPENDENCY="CIRCULAR_SYSTEM_DEPENDENCY",i.DUPLICATE_SYSTEM="DUPLICATE_SYSTEM",i.ARCHETYPE_NOT_FOUND="ARCHETYPE_NOT_FOUND",i.RESOURCE_NOT_REGISTERED="RESOURCE_NOT_REGISTERED",i.RESOURCE_ALREADY_REGISTERED="RESOURCE_ALREADY_REGISTERED",i.EVENT_ALREADY_REGISTERED="EVENT_ALREADY_REGISTERED",i.EVENT_NOT_REGISTERED="EVENT_NOT_REGISTERED",i.FIELD_NOT_REGISTERED="FIELD_NOT_REGISTERED",i.RELATION_NOT_REGISTERED="RELATION_NOT_REGISTERED",i.RELATION_MODE_INVALID="RELATION_MODE_INVALID",i.RELATION_MODE_MISMATCH="RELATION_MODE_MISMATCH",i.RELATION_CYCLE="RELATION_CYCLE",i.SPARSE_CACHE_KEY_OVERFLOW="SPARSE_CACHE_KEY_OVERFLOW",i.SPARSE_QUERY_DENSE_PATH="SPARSE_QUERY_DENSE_PATH",i.HIERARCHY_ALREADY_SET="HIERARCHY_ALREADY_SET",i.HIERARCHY_INVALID_MAX_DEPTH="HIERARCHY_INVALID_MAX_DEPTH",i.OBSERVER_NON_CONVERGENT="OBSERVER_NON_CONVERGENT",i.OBSERVER_INVALID_CONFIG="OBSERVER_INVALID_CONFIG",i.OBSERVER_ONSET_EMIT="OBSERVER_ONSET_EMIT",i.INVALID_FIXED_TIMESTEP="INVALID_FIXED_TIMESTEP",i.INVALID_MAX_FIXED_STEPS="INVALID_MAX_FIXED_STEPS",i.INVALID_RECORDER_SCHEDULE="INVALID_RECORDER_SCHEDULE",i.EMPTY_ARCHETYPE_MATERIALIZE="EMPTY_ARCHETYPE_MATERIALIZE",i.COMPONENT_INDEX_INVARIANT="COMPONENT_INDEX_INVARIANT",i.OPTIONAL_TERM_NOT_DECLARED="OPTIONAL_TERM_NOT_DECLARED",i.QUERY_ACCESS_UNDECLARED="QUERY_ACCESS_UNDECLARED",i.SYSTEM_FN_ARITY="SYSTEM_FN_ARITY",i.PARTITION_APPEND_NEEDS_ENTITY_ROW="PARTITION_APPEND_NEEDS_ENTITY_ROW",i.PARTITION_BULK_INTO_DISABLED="PARTITION_BULK_INTO_DISABLED",i.ENTITY_NOT_DISABLED="ENTITY_NOT_DISABLED",i.BACKEND_ALREADY_ATTACHED="BACKEND_ALREADY_ATTACHED",i.DETERMINISM_DISABLED="DETERMINISM_DISABLED",i.NON_DETERMINISTIC_COLUMN_TYPE="NON_DETERMINISTIC_COLUMN_TYPE",i.INVALID_MEMORY_OPTIONS="INVALID_MEMORY_OPTIONS",i.STORE_CAP_EXCEEDED="STORE_CAP_EXCEEDED",i.REGION_NOT_DECLARED="REGION_NOT_DECLARED",i.COMMAND_LOG_TAG_COLLISION="COMMAND_LOG_TAG_COLLISION",i))(I||{});class A extends Ls{constructor(e,t,s){super(t??e,!0,s),this.category=e}}function Us(i){return i instanceof A}const T=-1,ne=-1,re=Object.freeze(Object.create(null)),$s=2654435769,Bs=1367130551,q=1024,De=0,Ps=31,Fs=1/60,Gs=4,Hs=0,Z=20,j=(1<<Z)-1,se=j,Vs=Ps-Z,We=(1<<Vs)-1,le=We,Ys=We-1,$e=We<<Z|se,ie=(i,e)=>e<<Z|i,C=i=>i&j,ct=i=>i>>Z,ts=i=>Ye(i),Et=Object.freeze({});function ss(i){const e=(t=>({def:e,values:t??Et}));return Object.defineProperty(e,"id",{value:i,enumerable:!1}),e}function Ws(i,e){return{def:i,values:e??Et}}function ht(i){return typeof i=="function"?i:i.def}function lt(i){return typeof i=="function"?Et:i.values}const Ce=827148627,Ie=0,fe=4,Ae=52,b={magic:0,sim_abi_version:4,view_stamp:8,capacity:12,archetype_count:16,layout_descriptor_off:20,command_ring_off:24,action_ring_off:28,entity_index_off:32,event_ring_off:36,region_table_off:40,region_table_count:44,bindings_off:48},ve=12,J={region_id:0,byte_offset:4,byte_length:8},ze=16,G={component_id:0,field_id:2,type_tag:4,byte_off:8,stride:12},qe=36,N={archetype_id:0,component_mask:4,row_count:20,row_capacity:24,column_count:28,enabled_count:32};function zs(i,e){i.setUint32(b.magic,e.magic,!0),i.setUint32(b.sim_abi_version,e.simAbiVersion,!0),i.setUint32(b.view_stamp,e.viewStamp,!0),i.setUint32(b.capacity,e.capacity,!0),i.setUint32(b.archetype_count,e.archetypeCount,!0),i.setUint32(b.layout_descriptor_off,e.layoutDescriptorOff,!0),i.setUint32(b.command_ring_off,e.commandRingOff,!0),i.setUint32(b.action_ring_off,e.actionRingOff,!0),i.setUint32(b.entity_index_off,e.entityIndexOff,!0),i.setUint32(b.event_ring_off,e.eventRingOff,!0),i.setUint32(b.region_table_off,e.regionTableOff,!0),i.setUint32(b.region_table_count,e.regionTableCount,!0),i.setUint32(b.bindings_off,e.bindingsOff,!0)}function ns(i){return{magic:i.getUint32(b.magic,!0),simAbiVersion:i.getUint32(b.sim_abi_version,!0),viewStamp:i.getUint32(b.view_stamp,!0),capacity:i.getUint32(b.capacity,!0),archetypeCount:i.getUint32(b.archetype_count,!0),layoutDescriptorOff:i.getUint32(b.layout_descriptor_off,!0),commandRingOff:i.getUint32(b.command_ring_off,!0),actionRingOff:i.getUint32(b.action_ring_off,!0),entityIndexOff:i.getUint32(b.entity_index_off,!0),eventRingOff:i.getUint32(b.event_ring_off,!0),regionTableOff:i.getUint32(b.region_table_off,!0),regionTableCount:i.getUint32(b.region_table_count,!0),bindingsOff:i.getUint32(b.bindings_off,!0)}}const O={u8:0,i8:1,u16:2,i16:3,u32:4,i32:5,f32:6,f64:7},dt=Object.freeze({[O.u8]:1,[O.i8]:1,[O.u16]:2,[O.i16]:2,[O.u32]:4,[O.i32]:4,[O.f32]:4,[O.f64]:8}),qs={u8:O.u8,i8:O.i8,u16:O.u16,i16:O.i16,u32:O.u32,i32:O.i32,f32:O.f32,f64:O.f64};function js(i,e,t){i.setUint16(e+G.component_id,t.componentId,!0),i.setUint16(e+G.field_id,t.fieldId,!0),i.setUint8(e+G.type_tag,t.typeTag),i.setUint32(e+G.byte_off,t.byteOff,!0),i.setUint16(e+G.stride,t.stride,!0)}function Xs(i,e){return{componentId:i.getUint16(e+G.component_id,!0),fieldId:i.getUint16(e+G.field_id,!0),typeTag:i.getUint8(e+G.type_tag),byteOff:i.getUint32(e+G.byte_off,!0),stride:i.getUint16(e+G.stride,!0)}}const ke=fe*32;function Se(i){return qe+i*ze}function bt(i,e,t){i.setUint32(e+N.archetype_id,t.archetypeId,!0);for(let n=0;n<fe;n++)i.setUint32(e+N.component_mask+n*4,t.componentMask[n]??0,!0);i.setUint32(e+N.row_count,t.rowCount,!0),i.setUint32(e+N.row_capacity,t.rowCapacity,!0),i.setUint32(e+N.column_count,t.columns.length,!0),i.setUint32(e+N.enabled_count,t.enabledCount,!0);let s=e+qe;for(let n=0;n<t.columns.length;n++)js(i,s,t.columns[n]),s+=ze;return s}function Ks(i,e){const t=i.getUint32(e+N.column_count,!0),s=new Array(t);let n=e+qe;for(let o=0;o<t;o++)s[o]=Xs(i,n),n+=ze;const r=new Array(fe);for(let o=0;o<fe;o++)r[o]=i.getUint32(e+N.component_mask+o*4,!0);return{archetypeId:i.getUint32(e+N.archetype_id,!0),componentMask:r,rowCount:i.getUint32(e+N.row_count,!0),rowCapacity:i.getUint32(e+N.row_capacity,!0),enabledCount:i.getUint32(e+N.enabled_count,!0),columns:s}}function Qs(i,e,t){let s=e;for(let n=0;n<t.length;n++)s=bt(i,s,t[n]);return s}function is(i,e,t){const s=new Array(t);let n=e;for(let r=0;r<t;r++){const o=Ks(i,n);s[r]=o,n+=Se(o.columns.length)}return s}function Zs(i){let e=0;for(let t=0;t<i.length;t++)e+=Se(i[t].columns.length);return e}const rs=16,oe=16,Js=256,H={write_head:0,read_head:4,capacity_slots:8,overflow_flag:12},Ct=0;function kt(i){return rs+i*oe}function en(i){return i>0&&(i&i-1)===0}class W extends Error{constructor(e){super(e),this.name="CommandRingError"}}function tn(i,e,t){if(!en(t))throw new W(`command ring capacity_slots must be a positive power of two (got ${t})`);i.setUint32(e+H.write_head,0,!0),i.setUint32(e+H.read_head,0,!0),i.setUint32(e+H.capacity_slots,t,!0),i.setUint32(e+H.overflow_flag,0,!0)}function sn(i,e){return i.getUint32(e+H.write_head,!0)}function nn(i,e){return i.getUint32(e+H.read_head,!0)}function rn(i,e){return i.getUint32(e+H.capacity_slots,!0)}function on(i,e,t){if(t.byteLength!==oe-1)throw new W(`out_payload must be ${oe-1} bytes (got ${t.byteLength})`);const s=sn(i,e),n=nn(i,e);if(s===n)return Ct;const r=rn(i,e),o=n&r-1,a=e+rs+o*oe,c=i.getUint8(a),h=new Uint8Array(i.buffer,a+1,oe-1);return t.set(h),i.setUint32(e+H.read_head,n+1>>>0,!0),c}function an(i,e,t){let s=0;const n=new Uint8Array(oe-1);for(;;){const r=on(i,e,n);if(r===Ct)return s;t(r,n.slice()),s++}}const Re=16,P=12,ee={length:0,capacity:4},V=1<<20;function xt(i){if(i<0||!Number.isInteger(i))throw new os(`entity_index capacity must be a non-negative integer (got ${i})`);return Re+i*P}function cn(i){return i+Re}function hn(i,e){return i+Re+e*4}function ln(i,e){return i+Re+e*8}class os extends Error{constructor(e){super(e),this.name="EntityIndexError"}}function dn(i,e,t){if(t<0||!Number.isInteger(t))throw new os(`entity_index capacity must be a non-negative integer (got ${t})`);i.setUint32(e+ee.length,0,!0),i.setUint32(e+ee.capacity,t,!0)}function Mt(i,e,t){return{generations:new Int32Array(i,cn(e),t),archetypes:new Int32Array(i,hn(e,t),t),rows:new Int32Array(i,ln(e,t),t)}}const un=16,fn=16,_n=256,ue={write_head:0,read_head:4,capacity_slots:8,overflow_flag:12};function Nt(i){return un+i*fn}function pn(i){return i>0&&(i&i-1)===0}class gn extends Error{constructor(e){super(e),this.name="EventRingError"}}function yn(i,e,t){if(!pn(t))throw new gn(`event ring capacity_slots must be a positive power of two (got ${t})`);i.setUint32(e+ue.write_head,0,!0),i.setUint32(e+ue.read_head,0,!0),i.setUint32(e+ue.capacity_slots,t,!0),i.setUint32(e+ue.overflow_flag,0,!0)}const mn=16,wn=16,En=256,_e={write_head:0,read_head:4,capacity_slots:8,overflow_flag:12},bn=_e.write_head/4,Cn=_e.read_head/4,In=_e.capacity_slots/4,An=_e.overflow_flag/4;function Sn(i,e){return new Int32Array(i.buffer,i.byteOffset+e,4)}function Lt(i){return mn+i*wn}function vn(i){return i>0&&(i&i-1)===0}class Ut extends Error{constructor(e){super(e),this.name="ActionRingError"}}function Rn(i,e,t){if(!vn(t))throw new Ut(`action ring capacity_slots must be a positive power of two (got ${t})`);if((i.byteOffset+e)%4!==0)throw new Ut(`action ring header must be 4-byte aligned for Atomics (view.byteOffset ${i.byteOffset} + ring_off ${e} is not a multiple of 4)`);const s=Sn(i,e);Atomics.store(s,bn,0),Atomics.store(s,Cn,0),Atomics.store(s,In,t),Atomics.store(s,An,0)}const K=[{name:"command_ring",headerOff:"command_ring_off",sizeFromOptions:i=>i.commandRingCapacitySlots!==void 0?kt(i.commandRingCapacitySlots):0,init:(i,e,t)=>tn(i,e,t.commandRingCapacitySlots),regionBytes:(i,e)=>kt(i.getUint32(e+H.capacity_slots,!0)),readOptions:(i,e,t)=>{t.commandRingCapacitySlots=i.getUint32(e+H.capacity_slots,!0)}},{name:"entity_index",headerOff:"entity_index_off",sizeFromOptions:i=>i.entityIndexCapacity!==void 0?xt(i.entityIndexCapacity):0,init:(i,e,t)=>dn(i,e,t.entityIndexCapacity),regionBytes:(i,e)=>xt(i.getUint32(e+ee.capacity,!0)),readOptions:(i,e,t)=>{t.entityIndexCapacity=i.getUint32(e+ee.capacity,!0)}},{name:"event_ring",headerOff:"event_ring_off",sizeFromOptions:i=>i.eventRingCapacitySlots!==void 0?Nt(i.eventRingCapacitySlots):0,init:(i,e,t)=>yn(i,e,t.eventRingCapacitySlots),regionBytes:(i,e)=>Nt(i.getUint32(e+ue.capacity_slots,!0)),readOptions:(i,e,t)=>{t.eventRingCapacitySlots=i.getUint32(e+ue.capacity_slots,!0)}},{name:"action_ring",headerOff:"action_ring_off",sizeFromOptions:i=>i.actionRingCapacitySlots!==void 0?Lt(i.actionRingCapacitySlots):0,init:(i,e,t)=>Rn(i,e,t.actionRingCapacitySlots),regionBytes:(i,e)=>Lt(i.getUint32(e+_e.capacity_slots,!0)),readOptions:(i,e,t)=>{t.actionRingCapacitySlots=i.getUint32(e+_e.capacity_slots,!0)}}];class Le extends Error{constructor(e){super(e),this.name="RegionRegistryError"}}function as(i){return i*ve}function It(i,e){const t=i.getUint32(b.region_table_count,!0);if(e+as(t)>i.byteLength)throw new Le(`region table of ${t} entries at byte ${e} overruns the buffer (${i.byteLength} bytes)`);return t}function Tn(i){const e=new Set;for(let t=0;t<i.length;t++){const s=i[t];if(!Number.isInteger(s.id)||s.id<=0)throw new Le(`region "${s.name}" has invalid id ${s.id} — region ids must be positive integers (0 is the absent sentinel)`);if(e.has(s.id))throw new Le(`duplicate region id ${s.id} (region "${s.name}") — ids must be distinct within a consumer's region set`);if(e.add(s.id),!Number.isInteger(s.bytes)||s.bytes<=0)throw new Le(`region "${s.name}" (id ${s.id}) has invalid byte size ${s.bytes} — must be a positive integer`)}}function On(i,e,t){i.setUint32(e+J.region_id,t.regionId,!0),i.setUint32(e+J.byte_offset,t.byteOffset,!0),i.setUint32(e+J.byte_length,t.byteLength,!0)}function cs(i,e){return{regionId:i.getUint32(e+J.region_id,!0),byteOffset:i.getUint32(e+J.byte_offset,!0),byteLength:i.getUint32(e+J.byte_length,!0)}}function Dn(i,e,t){for(let s=0;s<t.length;s++)On(i,e+s*ve,t[s])}function kn(i,e,t){const s=new Array(t);for(let n=0;n<t;n++)s[n]=cs(i,e+n*ve);return s}function hs(i){const e=i.getUint32(b.region_table_off,!0);if(e===0)return[];const t=It(i,e);return kn(i,e,t)}function ls(i,e){const t=i.getUint32(b.region_table_off,!0);if(t===0)return 0;const s=It(i,t);for(let n=0;n<s;n++){const r=t+n*ve;if(i.getUint32(r+J.region_id,!0)===e)return i.getUint32(r+J.byte_offset,!0)}return 0}function xn(i,e){const t=i.getUint32(b.region_table_off,!0);if(t===0)return null;const s=It(i,t);for(let n=0;n<s;n++){const r=cs(i,t+n*ve);if(r.regionId===e)return r}return null}function ds(i,e){return i<<16|e}const Te=2**31;class je extends Error{constructor(e){super(`SAB column layout offset ${e} reaches or exceeds the 2³¹ (${Te}-byte) ceiling. Past 2 GiB the signed-32-bit bitwise alignment math wraps to negative/misaligned offsets. This is a structural limit independent of the (default 256 MiB) allocator cap — a single SAB cannot back more than ~2 GiB of column data (#382).`),this.name="StoreLayoutOverflowError"}}function Xe(i,e){if(i+e>Te)throw new je(i);return i+(e-1)&~(e-1)}function Mn(i,e,t,s){switch(e){case O.u8:return new Uint8Array(i,t,s);case O.i8:return new Int8Array(i,t,s);case O.u16:return new Uint16Array(i,t,s);case O.i16:return new Int16Array(i,t,s);case O.u32:return new Uint32Array(i,t,s);case O.i32:return new Int32Array(i,t,s);case O.f32:return new Float32Array(i,t,s);case O.f64:return new Float64Array(i,t,s)}}function Nn(i,e,t=0){const n=Zs(i.map(a=>({archetypeId:a.archetypeId,componentMask:a.componentMask,rowCount:0,enabledCount:0,rowCapacity:a.rowCapacity,columns:a.columns.map(c=>({componentId:c.componentId,fieldId:c.fieldId,typeTag:c.typeTag,byteOff:0,stride:dt[c.typeTag]}))})))+t;let r=e+n;const o=new Array(i.length);for(let a=0;a<i.length;a++){const c=i[a],h=new Array(c.columns.length);for(let l=0;l<c.columns.length;l++){const d=c.columns[l],u=dt[d.typeTag];r=Xe(r,u),h[l]={componentId:d.componentId,fieldId:d.fieldId,typeTag:d.typeTag,byteOff:r,stride:u},r+=u*c.rowCapacity}o[a]={archetypeId:c.archetypeId,componentMask:c.componentMask,rowCount:0,enabledCount:0,rowCapacity:c.rowCapacity,columns:h}}if(r>Te)throw new je(r);return{descriptors:o,totalBytes:r,regionBytes:n}}function At(i,e=B.DEFAULT_SAB_ALLOCATOR,t={}){const s={};let n=Ae;for(let S=0;S<K.length;S++){const E=K[S],v=E.sizeFromOptions(t);s[E.headerOff]=v===0?0:n,n+=v}const r=t.regions??[];Tn(r);const o=r.length,a=o>0?n:0;n+=as(o);const c=new Array(o);for(let S=0;S<r.length;S++){const E=r[S];c[S]={regionId:E.id,byteOffset:n,byteLength:E.bytes},n+=E.bytes}const h=t.bindingsRegionBytes??0,l=h===0?0:n;n+=h;const d=n,{descriptors:u,totalBytes:f,regionBytes:y}=Nn(i,d,t.reservedDescriptorBytes??0),_=e(f),g=new DataView(_),p={magic:Ce,simAbiVersion:Ie,viewStamp:0,capacity:f,archetypeCount:i.length,layoutDescriptorOff:d,bindingsOff:l,regionTableOff:a,regionTableCount:o,commandRingOff:s.command_ring_off,entityIndexOff:s.entity_index_off,eventRingOff:s.event_ring_off,actionRingOff:s.action_ring_off};zs(g,p),h>0&&new Uint8Array(_,l,h).fill(0);for(let S=0;S<K.length;S++){const E=K[S],v=s[E.headerOff];v!==0&&E.init(g,v,t)}a!==0&&Dn(g,a,c);for(let S=0;S<r.length;S++)r[S].init(g,c[S].byteOffset);Qs(g,d,u);const m=Ke(_,u);return{buffer:_,view:g,header:p,archetypes:m,_regionBytes:y,_allocator:e,_reservedDescriptorBytes:t.reservedDescriptorBytes??0}}function Ke(i,e){const t=new Map;for(let s=0;s<e.length;s++){const n=e[s],r=new Array(n.columns.length),o=new Map;for(let a=0;a<n.columns.length;a++){const c=n.columns[a],h={componentId:c.componentId,fieldId:c.fieldId,typeTag:c.typeTag,byteOff:c.byteOff,stride:c.stride,view:Mn(i,c.typeTag,c.byteOff,n.rowCapacity)};r[a]=h,o.set(ds(c.componentId,c.fieldId),h)}t.set(n.archetypeId,{archetypeId:n.archetypeId,componentMask:n.componentMask,rowCapacity:n.rowCapacity,columns:o,columnsInOrder:r})}return t}class ye extends Error{constructor(e){super(e),this.name="StoreRestoreError"}}function Ln(i){const e=i.view.getUint32(b.capacity,!0);return new Uint8Array(i.buffer,0,e)}function Un(i,e=B.DEFAULT_SAB_ALLOCATOR){const t=new DataView(i.buffer,i.byteOffset,i.byteLength);if(i.byteLength<Ae)throw new ye(`snapshot too small: ${i.byteLength} bytes (header alone needs ${Ae})`);const s=t.getUint32(b.magic,!0);if(s!==Ce)throw new ye(`bad magic: 0x${s.toString(16).padStart(8,"0")} (expected 0x${Ce.toString(16).padStart(8,"0")})`);const n=t.getUint32(b.sim_abi_version,!0);if(n!==Ie)throw new ye(`incompatible sim_abi_version: snapshot=${n}, build=${Ie}`);const r=e(i.byteLength);new Uint8Array(r).set(i);const o=new DataView(r),a=ns(o);if(a.layoutDescriptorOff<0||a.layoutDescriptorOff>r.byteLength)throw new ye(`layout_descriptor_off ${a.layoutDescriptorOff} is outside the snapshot (${r.byteLength} bytes)`);try{const c=is(o,a.layoutDescriptorOff,a.archetypeCount),h=Ke(r,c);return{buffer:r,view:o,header:a,archetypes:h}}catch(c){throw c instanceof RangeError?new ye(`snapshot layout is corrupt or truncated: a descriptor offset or column extent reads past the ${r.byteLength}-byte buffer (${c.message})`):c}}const us=2166136261,Be=16777619;function Je(i,e){return i=(i^e&255)>>>0,Math.imul(i,Be)>>>0}function $(i,e){return i=(i^e>>>0)>>>0,Math.imul(i,Be)>>>0}class $n{_data=new U.SparseMap;fieldNames;fieldTypes;fieldIndex;constructor(e,t){this.fieldNames=e,this.fieldTypes=t;const s=Object.create(null);for(let n=0;n<e.length;n++)s[e[n]]=n;this.fieldIndex=s}get size(){return this._data.size}get indices(){return this._data.keys}canonicalIndices(){return this._data.keys.slice().sort((e,t)=>e-t)}getRow(e){return this._data.get(e)}clear(){this._data.clear()}setRawRow(e,t){this._data.set(e,t)}has(e){return this._data.has(e)}setRow(e,t){const s=this.fieldNames,n=new Array(s.length);for(let r=0;r<s.length;r++){const o=t[s[r]];n[r]=o===void 0?0:o}this._data.set(e,n)}remove(e){return this._data.delete(e)}getField(e,t){const s=this._data.get(e);return s===void 0?void 0:s[t]}setField(e,t,s){const n=this._data.get(e);return n===void 0?!1:(n[t]=s,!0)}}class D extends Error{constructor(e){super(e),this.name="SparseRestoreError"}}const St=12,vt=4,pe=8;function Rt(i,e){let t=us;const s=n=>{for(let r=0;r<n.length;r++)t=Je(t,n.charCodeAt(r))};for(let n=0;n<i.length;n++)s(i[n]),t=Je(t,31),s(e[n]),t=Je(t,30);return t>>>0}function Bn(i){let e=4;for(let r=0;r<i.length;r++){const o=i[r],a=o.fieldNames.length;e+=St+o.size*(vt+a*pe)}const t=new Uint8Array(e),s=new DataView(t.buffer);let n=0;s.setUint32(n,i.length,!0),n+=4;for(let r=0;r<i.length;r++){const o=i[r],a=o.fieldNames.length,c=o.canonicalIndices();s.setUint32(n,a,!0),n+=4,s.setUint32(n,Rt(o.fieldNames,o.fieldTypes),!0),n+=4,s.setUint32(n,c.length,!0),n+=4;for(let h=0;h<c.length;h++){const l=c[h];s.setUint32(n,l,!0),n+=4;const d=o.getRow(l);for(let u=0;u<a;u++)s.setFloat64(n,d[u],!0),n+=pe}}return t}function Pn(i,e){const t=new DataView(e.buffer,e.byteOffset,e.byteLength),s=e.byteLength;let n=0;const r=a=>{if(n+a>s)throw new D(`sparse snapshot truncated: need ${a} more bytes at offset ${n}, have ${s-n}`)};r(4);const o=t.getUint32(n,!0);if(n+=4,o!==i.length)throw new D(`sparse store count mismatch: snapshot=${o}, registered=${i.length}`);for(let a=0;a<i.length;a++){const c=i[a];r(St);const h=t.getUint32(n,!0);n+=4;const l=t.getUint32(n,!0);n+=4;const d=t.getUint32(n,!0);if(n+=4,h!==c.fieldNames.length)throw new D(`sparse store ${a} field-count mismatch: snapshot=${h}, registered=${c.fieldNames.length}`);const u=Rt(c.fieldNames,c.fieldTypes);if(l!==u)throw new D(`sparse store ${a} schema identity mismatch: snapshot hash=${l}, registered=${u} (same field count, different field names/types — likely a registration-order divergence between the snapshot and restore worlds)`);c.clear();for(let f=0;f<d;f++){r(vt+h*pe);const y=t.getUint32(n,!0);if(n+=4,y>se)throw new D(`sparse store ${a} member ${f} entity index ${y} exceeds MAX_INDEX (${se})`);const _=new Array(h);for(let g=0;g<h;g++)_[g]=t.getFloat64(n,!0),n+=pe;c.setRawRow(y,_)}}if(n!==s)throw new D(`sparse snapshot has ${s-n} trailing bytes after the last store (not a canonical encoding)`)}function Fn(i,e){const t=new DataView(e.buffer,e.byteOffset,e.byteLength),s=e.byteLength;let n=0;const r=a=>{if(n+a>s)throw new D(`sparse snapshot truncated: need ${a} more bytes at offset ${n}, have ${s-n}`)};r(4);const o=t.getUint32(n,!0);if(n+=4,o!==i.length)throw new D(`sparse store count mismatch: snapshot=${o}, registered=${i.length}`);for(let a=0;a<i.length;a++){const c=i[a];r(St);const h=t.getUint32(n,!0);n+=4;const l=t.getUint32(n,!0);n+=4;const d=t.getUint32(n,!0);if(n+=4,h!==c.fieldNames.length)throw new D(`sparse store ${a} field-count mismatch: snapshot=${h}, registered=${c.fieldNames.length}`);const u=Rt(c.fieldNames,c.fieldTypes);if(l!==u)throw new D(`sparse store ${a} schema identity mismatch: snapshot hash=${l}, registered=${u} (same field count, different field names/types — likely a registration-order divergence between the snapshot and restore worlds)`);for(let f=0;f<d;f++){r(vt+h*pe);const y=t.getUint32(n,!0);if(n+=4,y>se)throw new D(`sparse store ${a} member ${f} entity index ${y} exceeds MAX_INDEX (${se})`);n+=h*pe}}if(n!==s)throw new D(`sparse snapshot has ${s-n} trailing bytes after the last store (not a canonical encoding)`)}const ut=2147483647,Gn="orphan",fs="target",Hn=Object.freeze({});class _s{exclusive;sparse;onDeleteTarget;_store;_reverse=new Map;constructor(e,t,s,n){this.exclusive=e,this.sparse=t,this._store=s,this.onDeleteTarget=n}linkReverse(e,t){let s=this._reverse.get(e);s===void 0&&(s=new Set,this._reverse.set(e,s)),s.add(t)}unlinkReverse(e,t){const s=this._reverse.get(e);s!==void 0&&(s.delete(t),s.size===0&&this._reverse.delete(e))}pruneDeadReverse(e){let t=0;for(const s of this._reverse.keys())e(s)||(this._reverse.delete(s),t++);return t}sourcesOf(e){const t=this._reverse.get(e);if(t===void 0||t.size===0)return[];const s=new Array(t.size);let n=0;return t.forEach(r=>{s[n++]=r}),s.sort((r,o)=>r-o),s}resetIndices(){this._reverse.clear(),this._resetForward()}}class Vn extends _s{constructor(e,t,s){super(!0,e,t,s)}_resetForward(){}link(e,t){const s=C(e),n=this._store.getField(s,0);if(n!==void 0){if(n===t)return;this.unlinkReverse(n,e)}this._store.setRow(s,{[fs]:t}),this.linkReverse(t,e)}unlink(e,t){const s=C(e),n=this._store.getField(s,0);n!==void 0&&(t!==void 0&&n!==t||(this.unlinkReverse(n,e),this._store.remove(s)))}purgeSource(e){const t=C(e),s=this._store.getField(t,0);s!==void 0&&this.unlinkReverse(s,e)}singleTarget(e){const t=this._store.getField(e,0);return t===void 0?void 0:t}targetsOf(e){const t=this._store.getField(e,0);return t===void 0?[]:[t]}has(e){return this._store.has(e)}forEachCanonicalTargetSet(e){}forEachCanonicalPair(e,t){const s=this._store.canonicalIndices();for(let n=0;n<s.length;n++){const r=s[n];t(e(r),this._store.getField(r,0))}}rebuildReverseFromForward(e){const t=this._store.indices;for(let s=0;s<t.length;s++){const n=t[s];this.linkReverse(this._store.getField(n,0),e(n))}}restoreAddTarget(){throw new D("exclusive relation has no multi forward sources to restore (snapshot header should have guarded this)")}}class Yn extends _s{_forward=new Map;constructor(e,t,s){super(!1,e,t,s)}_resetForward(){this._forward.clear()}link(e,t){const s=C(e);let n=this._forward.get(s);n===void 0&&(n=new Set,this._forward.set(s,n),this._store.setRow(s,Hn)),n.add(t),this.linkReverse(t,e)}unlink(e,t){const s=C(e),n=this._forward.get(s);if(n!==void 0){if(t===void 0){this._forward.delete(s),n.forEach(r=>this.unlinkReverse(r,e)),this._store.remove(s);return}n.has(t)&&(n.delete(t),this.unlinkReverse(t,e),n.size===0&&(this._forward.delete(s),this._store.remove(s)))}}purgeSource(e){const t=C(e),s=this._forward.get(t);s!==void 0&&(this._forward.delete(t),s.forEach(n=>this.unlinkReverse(n,e)))}singleTarget(){}targetsOf(e){const t=this._forward.get(e);if(t===void 0||t.size===0)return[];const s=new Array(t.size);let n=0;return t.forEach(r=>{s[n++]=r}),s.sort((r,o)=>r-o),s}has(e){return this._store.has(e)}forEachCanonicalTargetSet(e){const t=Array.from(this._forward.keys()).sort((s,n)=>s-n);for(let s=0;s<t.length;s++){const n=this.targetsOf(t[s]);n.length!==0&&e(t[s],n)}}forEachCanonicalPair(e,t){this.forEachCanonicalTargetSet((s,n)=>{const r=e(s);for(let o=0;o<n.length;o++)t(r,n[o])})}rebuildReverseFromForward(){}restoreAddTarget(e,t,s){let n=this._forward.get(e);n===void 0&&(n=new Set,this._forward.set(e,n)),n.add(t),this.linkReverse(t,s)}}function Wn(i,e,t,s){return i?new Vn(e,t,s):new Yn(e,t,s)}const ps=4,gs=4,ys=8,Pe=8;function zn(i){const e=new Array(i.length);let t=4;for(let o=0;o<i.length;o++){t+=ps;const a=i[o];if(a.exclusive){e[o]=null;continue}const c=[];a.forEachCanonicalTargetSet((h,l)=>c.push([h,l])),e[o]=c,t+=gs;for(let h=0;h<c.length;h++)t+=ys+c[h][1].length*Pe}const s=new Uint8Array(t),n=new DataView(s.buffer);let r=0;n.setUint32(r,i.length,!0),r+=4;for(let o=0;o<i.length;o++){n.setUint32(r,i[o].exclusive?0:1,!0),r+=4;const a=e[o];if(a!==null){n.setUint32(r,a.length,!0),r+=4;for(let c=0;c<a.length;c++){const h=a[c][0],l=a[c][1];n.setUint32(r,h,!0),r+=4,n.setUint32(r,l.length,!0),r+=4;for(let d=0;d<l.length;d++)n.setFloat64(r,l[d],!0),r+=Pe}}}return s}function qn(i,e,t){const s=new DataView(e.buffer,e.byteOffset,e.byteLength),n=e.byteLength;let r=0;const o=c=>{if(r+c>n)throw new D(`relation snapshot truncated: need ${c} more bytes at offset ${r}, have ${n-r}`)};for(let c=0;c<i.length;c++)i[c].resetIndices();o(4);const a=s.getUint32(r,!0);if(r+=4,a!==i.length)throw new D(`relation count mismatch: snapshot=${a}, registered=${i.length}`);for(let c=0;c<i.length;c++){const h=i[c];o(ps);const l=s.getUint32(r,!0);if(r+=4,l===1===h.exclusive)throw new D(`relation ${c} cardinality mismatch: snapshot ${l?"multi":"exclusive"}, registered ${h.exclusive?"exclusive":"multi"}`);if(h.exclusive)continue;o(gs);const d=s.getUint32(r,!0);r+=4;for(let u=0;u<d;u++){o(ys);const f=s.getUint32(r,!0);r+=4;const y=s.getUint32(r,!0);if(r+=4,f>se)throw new D(`relation ${c} source index ${f} exceeds MAX_INDEX (${se})`);o(y*Pe);const _=t(f);for(let g=0;g<y;g++){const p=s.getFloat64(r,!0);r+=Pe;const m=p;if(!Number.isInteger(m)||m<0||m>$e)throw new D(`relation ${c} target ${m} is not a well-formed packed EntityID (expected an integer in [0, ${$e}])`);h.restoreAddTarget(f,p,_)}}}if(r!==n)throw new D(`relation snapshot has ${n-r} trailing bytes after the last relation (not a canonical encoding)`)}const jn=i=>Ye(i);class Xn{fieldNames;columns;reader;constructor(e){this.fieldNames=e,this.columns=[];for(let s=0;s<e.length;s++)this.columns.push([]);const t={};for(let s=0;s<e.length;s++)t[e[s]]=this.columns[s];this.reader={length:0,...t}}emit(e){const t=this.fieldNames,s=this.columns;for(let n=0;n<t.length;n++)s[n].push(e[t[n]]);this.reader.length++}emitSignal(){this.reader.length++}clear(){this.reader.length=0;const e=this.columns;for(let t=0;t<e.length;t++)e[t].length=0}}function Kn(i){return Symbol(i)}function Qn(i){return Symbol(i)}class xe extends Error{capacity;requested;constructor(e,t){super(`BufferBackedColumn overflow: requested length ${t} exceeds capacity ${e}`),this.name="StoreColumnOverflowError",this.capacity=e,this.requested=t}}class Zn{_buf;_capacity;_len=0;constructor(e){this._buf=e,this._capacity=e.length}refreshView(e){if(e.length<this._len)throw new xe(e.length,this._len);this._buf=e,this._capacity=e.length}get length(){return this._len}get capacity(){return this._capacity}push(e){if(this._len>=this._capacity)throw new xe(this._capacity,this._len+1);this._buf[this._len++]=e}pop(){return this._buf[--this._len]}get(e){return this._buf[e]}setAt(e,t){this._buf[e]=t}swapRemove(e){const t=this._buf[e];return this._buf[e]=this._buf[--this._len],t}clear(){this._len=0}setLength(e){if(e>this._capacity)throw new xe(this._capacity,e);this._len=e}get buf(){return this._buf}view(){return this._buf.subarray(0,this._len)}[Symbol.iterator](){let e=0;const t=this._buf,s=this._len;return{next(){return e<s?{value:t[e++],done:!1}:{value:0,done:!0}}}}ensureCapacity(e){if(e>this._capacity)throw new xe(this._capacity,e)}bulkAppend(e,t,s){this.ensureCapacity(this._len+s),this._buf.set(e.subarray(t,t+s),this._len),this._len+=s}bulkAppendZeroes(e){this.ensureCapacity(this._len+e),this._buf.fill(0,this._len,this._len+e),this._len+=e}bulkAppendValue(e,t){this.ensureCapacity(this._len+t),this._buf.fill(e,this._len,this._len+t),this._len+=t}}const $t=new WeakMap;function Jn(i){const e=new Set,t=new Set,s=new Set,n=new Set,r=new Set,o=new Set,a=new Set,c=new Set,h=new Set,l=new Set;for(let _=0;_<i.writes.length;_++){const g=i.writes[_].id;t.add(g),e.add(g),s.add(g)}for(let _=0;_<i.reads.length;_++)e.add(i.reads[_].id);for(let _=0;_<i.spawns.length;_++){const g=i.spawns[_];for(let p=0;p<g.length;p++)s.add(g[p].id)}for(let _=0;_<i.transitions.length;_++){const g=i.transitions[_];if(g.add)for(let p=0;p<g.add.length;p++)s.add(g.add[p].id);if(g.remove)for(let p=0;p<g.remove.length;p++)n.add(g.remove[p].id)}for(let _=0;_<i.despawns.length;_++)n.add(i.despawns[_].id);for(let _=0;_<i.resourceReads.length;_++)r.add(i.resourceReads[_]);for(let _=0;_<i.resourceWrites.length;_++){const g=i.resourceWrites[_];o.add(g),r.add(g)}const d=i.sparseWrites;if(d!==void 0)for(let _=0;_<d.length;_++){const g=d[_];c.add(g),a.add(g)}const u=i.sparseReads;if(u!==void 0)for(let _=0;_<u.length;_++)a.add(u[_]);const f=i.relationWrites;if(f!==void 0)for(let _=0;_<f.length;_++){const g=f[_];l.add(g),h.add(g)}const y=i.relationReads;if(y!==void 0)for(let _=0;_<y.length;_++)h.add(y[_]);return{reads:e,writes:t,addAllowed:s,removeAllowed:n,hasDespawns:i.despawns.length>0,resourceReads:r,resourceWrites:o,sparseReads:a,sparseWrites:c,relationReads:h,relationWrites:l}}function ei(i){const e=$t.get(i);if(e!==void 0)return e;const t=Jn(i);return $t.set(i,t),t}const Bt=new WeakMap;function ti(i){const e=new Set,t=new Set;if(i.reads!==void 0)for(let s=0;s<i.reads.length;s++)e.add(i.reads[s].id);if(i.resourceReads!==void 0)for(let s=0;s<i.resourceReads.length;s++)t.add(i.resourceReads[s]);return{reads:e,writes:new Set,addAllowed:new Set,removeAllowed:new Set,hasDespawns:!1,resourceReads:t,resourceWrites:new Set,sparseReads:new Set,sparseWrites:new Set,relationReads:new Set,relationWrites:new Set}}function si(i){const e=Bt.get(i);if(e!==void 0)return e;const t=ti(i);return Bt.set(i,t),t}class ni{active=null;sets=null;activeName=null;exclusive=!1;enter(e){this.active=e,this.activeName=e.name??`system_${e.id}`,this.exclusive=e.exclusive===!0,this.sets=this.exclusive?null:ei(e)}enterCondition(e){this.active=null,this.activeName=e.name,this.sets=si(e)}leave(){this.active=null,this.activeName=null,this.sets=null,this.exclusive=!1}isActive(){return this.sets!==null||this.exclusive}current(){return this.active}checkRead(e){if(this.sets===null)return;const t=e.id;this.sets.reads.has(t)||this.failComponent("read",t,"reads")}checkWrite(e){if(this.sets===null)return;const t=e.id;this.sets.writes.has(t)||this.failComponent("write",t,"writes")}checkAdd(e){if(this.sets===null)return;const t=e.id;this.sets.addAllowed.has(t)||this.failComponent("add_component",t,"spawns / transitions.add / writes")}checkRemove(e){if(this.sets===null)return;const t=e.id;this.sets.removeAllowed.has(t)||this.failComponent("remove_component",t,"despawns / transitions.remove")}checkDestroy(){if(this.sets===null||this.sets.hasDespawns)return;const e=this.activeName;throw new A(I.COMPONENT_NOT_REGISTERED,`system '${e}' called destroyEntity but didn't declare any despawns (Phase B of issue #213 — declare the components this system removes via destroyEntity)`)}checkResourceRead(e){if(this.sets===null)return;const t=e;this.sets.resourceReads.has(t)||this.failResource("read",e,"resource_reads")}checkResourceWrite(e){if(this.sets===null)return;const t=e;this.sets.resourceWrites.has(t)||this.failResource("write",e,"resource_writes")}checkSparseRead(e){if(this.sets===null)return;const t=e;this.sets.sparseReads.has(t)||this.failSparse("read",t,"sparse_reads")}checkSparseWrite(e){if(this.sets===null)return;const t=e;this.sets.sparseWrites.has(t)||this.failSparse("write",t,"sparse_writes")}checkRelationRead(e){if(this.sets===null)return;const t=e;this.sets.relationReads.has(t)||this.failRelation("read",t,"relation_reads")}checkRelationWrite(e){if(this.sets===null)return;const t=e;this.sets.relationWrites.has(t)||this.failRelation("write",t,"relation_writes")}checkRelationReadAny(){this.sets!==null&&(this.sets.relationReads.has(ut)||this.failRelation("(*, T) wildcard read",ut,"relation_reads (as ANY_RELATION)"))}optionalScopes=[];enterOptionalScope(e){this.optionalScopes.push(e)}leaveOptionalScope(){this.optionalScopes.pop()}checkOptionalFetch(e){const t=this.optionalScopes.length;if(t===0)return;const s=this.optionalScopes[t-1],n=e.id;for(let r=0;r<s.length;r++)if(s[r]===n)return;throw new A(I.OPTIONAL_TERM_NOT_DECLARED,`getOptionalColumnRead fetched optional component ${n} but the iterating query didn't declare it — add .optional(component) to the query before fetching it (#592)`)}failComponent(e,t,s){const n=this.activeName;throw new A(I.COMPONENT_NOT_REGISTERED,`system '${n}' performed ${e} on component ${t} but didn't declare it (Phase B of issue #213 — add component ${t} to '${s}')`)}failSparse(e,t,s){const n=this.activeName;throw new A(I.COMPONENT_NOT_REGISTERED,`system '${n}' performed ${e} on sparse component ${t} but didn't declare it (issue #496 — add it to '${s}')`)}failRelation(e,t,s){const n=this.activeName;throw new A(I.RELATION_NOT_REGISTERED,`system '${n}' performed ${e} on relation ${t} but didn't declare it (issue #496 — add it to '${s}')`)}failResource(e,t,s){const n=this.activeName,r=t.description??"<unnamed>";throw new A(I.RESOURCE_NOT_REGISTERED,`system '${n}' performed resource ${e} on '${r}' but didn't declare it (Phase B of issue #213 — add the resource key to '${s}')`)}}const ft=new ni,Pt=i=>Ye(i);class Tt{id;mask;hasColumns;materializesRows;_entityIds;length=0;enabledCount=0;_flushSeenEpoch=-1;_flushPreLen=0;_flushPreEnabled=0;edges=[];batchTransitionMaps=new Map;compositeAddEdges=null;_flatColumns=[];_storeArchetypeId=null;_colOffset=[];_fieldCount=[];_fieldIndex=[];_fieldNames=[];columnGroups=[];_columnIds=[];_changedTick=[];_mutGroupCache=[];_readGroupCache=[];growHandler=null;constructor(e,t,s,n=q,r){if(this.id=e,this.mask=t,this._entityIds=new U.GrowableUint32Array(n),s){let o=0;for(let a=0;a<s.length;a++){const c=s[a],h=c.componentId,l=new Array(c.fieldNames.length);if(this._colOffset[h]=o,this._fieldCount[h]=c.fieldNames.length,this._fieldIndex[h]=c.fieldIndex,this._fieldNames[h]=c.fieldNames,c.fieldNames.length>0&&!r)throw new A(I.COMPONENT_NOT_REGISTERED,`Archetype ${e}: layouts with fields require a column_factory (the legacy heap path was removed in #171 §6.1.9 Phase 4 — use Archetype.from_column_store for SAB-backed columns, or pass a heap factory explicitly in tests)`);for(let d=0;d<c.fieldNames.length;d++){const u=c.fieldTypes[d],f=r(c.componentId,d,u);l[d]=f,this._flatColumns[o++]=f}this.columnGroups[h]={layout:c,columns:l},this._columnIds.push(h),this._changedTick[h]=0}}this.hasColumns=this._columnIds.length>0,this.materializesRows=!t.isEmpty()}static fromColumnStore(e,t,s,n,r){const o=n.archetypes.get(r);if(!o)throw new A(I.COMPONENT_NOT_REGISTERED,`ColumnStore has no archetype ${r}`);const a=(h,l)=>{const d=o.columns.get(ds(h,l));if(!d)throw new A(I.COMPONENT_NOT_REGISTERED,`ColumnStore archetype ${r} has no column for (${h}, ${l})`);return new Zn(d.view)},c=new Tt(e,t,s,o.rowCapacity,a);return c._storeArchetypeId=r,c}get isBufferBacked(){return this._storeArchetypeId!==null}refreshViews(e){if(this._storeArchetypeId===null)throw new A(I.COMPONENT_NOT_REGISTERED,`Archetype ${this.id} is not SAB-backed`);const t=e.archetypes.get(this._storeArchetypeId);if(!t)throw new A(I.COMPONENT_NOT_REGISTERED,`new ColumnStore has no archetype ${this._storeArchetypeId}`);const s=t.columnsInOrder,n=this._flatColumns;for(let r=0;r<s.length;r++)n[r].refreshView(s[r].view)}get entityCount(){return _t?this.length:this.enabledCount}get totalCount(){return this.length}get disabledCount(){return this.length-this.enabledCount}get entityIds(){return this._entityIds.buf}swapRows(e,t){if(e===t)return;const s=this._entityIds.buf,n=s[e];s[e]=s[t],s[t]=n;const r=this._flatColumns;for(let o=0;o<r.length;o++){const a=r[o].buf,c=a[e];a[e]=a[t],a[t]=c}}_placeTail(e,t){const s=this.enabledCount;if(s===e)return this.enabledCount=e+1,e;if(this.swapRows(s,e),t!==void 0){const n=this._entityIds.buf;t[C(n[e])]=e}return this.enabledCount=s+1,s}_placeTailBulk(e,t){return this.enabledCount+=t,e}disableRow(e,t){const s=this.enabledCount-1;if(e!==s){this.swapRows(e,s);const n=this._entityIds.buf;t[C(n[e])]=e,t[C(n[s])]=s}this.enabledCount=s}enableRow(e,t){const s=this.enabledCount;if(e!==s){this.swapRows(e,s);const n=this._entityIds.buf;t[C(n[e])]=e,t[C(n[s])]=s}this.enabledCount=s+1}removeRow(e,t){if(this.enabledCount===this.length){const s=this._entityIds.buf,n=this.length-1;if(e!==n){if(s[e]=s[n],this.hasColumns){const r=this._flatColumns;for(let o=0;o<r.length;o++)r[o].swapRemove(e)}t[C(s[e])]=e}else if(this.hasColumns){const r=this._flatColumns;for(let o=0;o<r.length;o++)r[o].pop()}this._entityIds.pop(),this.length=n,this.enabledCount=n;return}this._removeRowPartitioned(e,t)}_removeRowPartitioned(e,t){const s=this._entityIds.buf,n=this.hasColumns,r=this.enabledCount,o=this.length-1;if(e>=r){if(e!==o){if(s[e]=s[o],n){const c=this._flatColumns;for(let h=0;h<c.length;h++)c[h].swapRemove(e)}t[C(s[e])]=e}else if(n){const c=this._flatColumns;for(let h=0;h<c.length;h++)c[h].pop()}this._entityIds.pop(),this.length--;return}const a=r-1;if(e!==a&&(this.swapRows(e,a),t[C(s[e])]=e),a!==o){if(s[a]=s[o],n){const c=this._flatColumns;for(let h=0;h<c.length;h++)c[h].swapRemove(a)}t[C(s[a])]=a}else if(n){const c=this._flatColumns;for(let h=0;h<c.length;h++)c[h].pop()}this._entityIds.pop(),this.length--,this.enabledCount=a}get entityList(){return this._entityIds.view()}hasComponent(e){return this.mask.has(e)}matches(e){return this.mask.contains(e)}getColumnRead(e,t){const s=e.id,n=this._fieldIndex[s][t];return this._flatColumns[this._colOffset[s]+n].buf}getColumnsRead(e,...t){return t.map(n=>this.getColumnRead(e,n))}getOptionalColumnRead(e,t){const s=e.id,n=this._colOffset[s];if(n===void 0)return;const r=this._fieldIndex[s][t];return this._flatColumns[n+r].buf}getColumn(e,t,s){const n=e.id;this._changedTick[n]=s;const r=this._fieldIndex[n][t];return this._flatColumns[this._colOffset[n]+r].buf}columnGroupMut(e,t){const s=e.id;this._changedTick[s]=t;const n=this._colOffset[s],r=this._fieldNames[s],o=this._flatColumns;let a=this._mutGroupCache[s];a===void 0&&(a={},this._mutGroupCache[s]=a);for(let c=0;c<r.length;c++)a[r[c]]=o[n+c].buf;return a}columnGroupRead(e){const t=e.id,s=this._colOffset[t],n=this._fieldNames[t],r=this._flatColumns;let o=this._readGroupCache[t];o===void 0&&(o={},this._readGroupCache[t]=o);for(let a=0;a<n.length;a++)o[n[a]]=r[s+a].buf;return o}writeFields(e,t,s,n){const r=t,o=this._colOffset[r];if(o===void 0)return;this._changedTick[r]=n;const a=this._fieldNames[r],c=this._flatColumns;for(let h=0;h<a.length;h++)c[o+h].buf[e]=s[a[h]]??0}bulkWriteFields(e,t,s,n,r){const o=s,a=this._colOffset[o];if(a===void 0)return;this._changedTick[o]=r;const c=this._fieldNames[o],h=this._flatColumns,l=e+t;for(let d=0;d<c.length;d++)h[a+d].buf.fill(n[c[d]]??0,e,l)}writeFieldsPositional(e,t,s,n){const r=t,o=this._colOffset[r];if(o===void 0)return;this._changedTick[r]=n;const a=this._flatColumns;for(let c=0;c<s.length;c++)a[o+c].buf[e]=s[c]}readField(e,t,s){const n=t,r=this._colOffset[n];if(r===void 0)return NaN;const o=this._fieldIndex[n][s];return o===void 0?NaN:this._flatColumns[r+o].buf[e]}copySharedFrom(e,t,s,n){const r=e._colOffset,o=e._fieldCount,a=e._flatColumns,c=this._flatColumns,h=this._columnIds;for(let l=0;l<h.length;l++){const d=h[l],u=r[d];if(u===void 0)continue;this._changedTick[d]=n;const f=this._colOffset[d],y=o[d];for(let _=0;_<y;_++)c[f+_].buf[s]=a[u+_].buf[t]}}addEntity(e,t){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(e);for(let r=0;r<s.length;r++)s[r].push(0);return this.length++,this._placeTail(n,t)}removeEntity(e){const t=this.length-1;let s=ne;const n=this._flatColumns,r=this._entityIds.buf;if(e!==t){r[e]=r[t],s=C(r[e]);for(let o=0;o<n.length;o++)n[o].swapRemove(e)}else for(let o=0;o<n.length;o++)n[o].pop();return this._entityIds.pop(),this.length--,e<this.enabledCount&&this.enabledCount--,s}addEntityTag(e,t){const s=this.length;return this._entityIds.push(e),this.length++,this._placeTail(s,t)}addEntities(e,t=e.length){if(t===0)return this.length;const s=this._flatColumns;s.length>0&&this.length+t>s[0].buf.length&&this.growHandler!==null&&this.growHandler(this,t);const n=this.length;this._entityIds.bulkAppend(e,0,t);for(let r=0;r<s.length;r++)s[r].bulkAppendZeroes(t);return this.length+=t,this._placeTailBulk(n,t)}addEntitiesTag(e,t=e.length){if(t===0)return this.length;const s=this.length;return this._entityIds.bulkAppend(e,0,t),this.length+=t,this._placeTailBulk(s,t)}ensureRowCapacity(e){const t=this._flatColumns;t.length>0&&this.length+e>t[0].buf.length&&this.growHandler!==null&&this.growHandler(this,e)}addEntityWithValues(e,t,s,n){const r=this._flatColumns;r.length>0&&this.length>=r[0].buf.length&&this.growHandler!==null&&this.growHandler(this,1);const o=this.length;this._entityIds.push(e);for(let c=0;c<r.length;c++)r[c].push(t[c]);this.length++;const a=this._columnIds;for(let c=0;c<a.length;c++)this._changedTick[a[c]]=s;return this._placeTail(o,n)}addEntitiesWithValues(e,t,s,n){if(t===0)return this.length;const r=this._flatColumns;r.length>0&&this.length+t>r[0].buf.length&&this.growHandler!==null&&this.growHandler(this,t);const o=this.length;this._entityIds.bulkAppend(e,0,t);for(let c=0;c<r.length;c++)r[c].bulkAppendValue(s[c],t);this.length+=t;const a=this._columnIds;for(let c=0;c<a.length;c++)this._changedTick[a[c]]=n;return this._placeTailBulk(o,t)}removeEntityTag(e){const t=this.length-1;let s=ne;const n=this._entityIds.buf;return e!==t&&(n[e]=n[t],s=C(n[e])),this._entityIds.pop(),this.length--,e<this.enabledCount&&this.enabledCount--,s}moveEntityFrom(e,t,s,n,r,o){const a=t>=e.enabledCount;if(!this.materializesRows){e.removeRow(t,o),L[0]=T,L[1]=ne;return}const c=this._flatColumns;c.length>0&&this.length>=c[0].buf.length&&this.growHandler!==null&&this.growHandler(this,1);const h=this.length;this._entityIds.push(s);const l=e._flatColumns;for(let f=0;f<c.length;f++){const y=n[f];c[f].push(y>=0?l[y].buf[t]:0)}const d=this._columnIds;for(let f=0;f<d.length;f++)this._changedTick[d[f]]=r;this.length++;const u=a?h:this._placeTail(h,o);e.removeRow(t,o),L[0]=u,L[1]=ne}moveEntityFromTag(e,t,s,n){const r=t>=e.enabledCount;if(!this.materializesRows){e.removeRow(t,n),L[0]=T,L[1]=ne;return}const o=this.length;this._entityIds.push(s),this.length++;const a=r?o:this._placeTail(o,n);e.removeRow(t,n),L[0]=a,L[1]=ne}bulkMoveAllFrom(e,t,s){const n=e.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 o=this.length,a=e._flatColumns;this._entityIds.bulkAppend(e._entityIds.buf,0,n);for(let h=0;h<r.length;h++){const l=t[h];l>=0?r[h].bulkAppend(a[l].buf,0,n):r[h].bulkAppendZeroes(n)}const c=this._columnIds;for(let h=0;h<c.length;h++)this._changedTick[c[h]]=s;return this.length+=n,this.enabledCount=o+e.enabledCount,e.clearRows(),o}clearRows(){this.length=0,this.enabledCount=0,this._entityIds.clear();const e=this._flatColumns;for(let t=0;t<e.length;t++)e[t].clear()}restoreHostRows(e,t){const s=e.length;this._entityIds.clear(),this._entityIds.ensureCapacity(s);for(let r=0;r<s;r++)this._entityIds.push(e[r]);const n=this._flatColumns;for(let r=0;r<n.length;r++)n[r].setLength(s);this.length=s,this.enabledCount=t}getEdge(e){return this.edges[e]}setEdge(e,t){this.edges[e]=t}getBatchTransitionMap(e){const t=this.batchTransitionMaps.get(e.id);if(t!==void 0)return t;const s=pt(this,e);return this.batchTransitionMaps.set(e.id,s),s}getCompositeAddEdge(e){return this.compositeAddEdges===null?void 0:this.compositeAddEdges.get(e)}cacheCompositeAddEdge(e,t,s){(this.compositeAddEdges??=new Map).set(e,{target:t,map:s})}}const L=[0,ne];let _t=!1;function X(i){const e=_t;return _t=i,e}function pt(i,e){const t=e._flatColumns,s=new Int16Array(t.length),n=e._columnIds,r=i._colOffset,o=e._colOffset,a=e._fieldCount;for(let c=0;c<n.length;c++){const h=n[c],l=o[h],d=a[h],u=r[h];if(u!==void 0)for(let f=0;f<d;f++)s[l+f]=u+f;else for(let f=0;f<d;f++)s[l+f]=-1}return s}const ms=i=>Ye(i),me=Object.freeze([]);function Ft(i){return typeof i=="object"&&!Array.isArray(i)}function ii(i){let e=me;i.spawns!==void 0&&i.spawns.length>0&&(e=i.spawns.map(s=>Ft(s)?s.defs:s));let t=me;if(i.despawns!==void 0&&i.despawns.length>0){const s=[];for(const n of i.despawns)Ft(n)?s.push(...n.defs):s.push(n);t=s}return{reads:i.reads,writes:i.writes,spawns:e,despawns:t,transitions:i.transitions??me,resourceReads:i.resourceReads??me,resourceWrites:i.resourceWrites??me,sparseReads:i.sparseReads,sparseWrites:i.sparseWrites,relationReads:i.relationReads,relationWrites:i.relationWrites}}const gt=Object.freeze({reads:Object.freeze([]),writes:Object.freeze([]),spawns:Object.freeze([]),despawns:Object.freeze([]),transitions:Object.freeze([]),resourceReads:Object.freeze([]),resourceWrites:Object.freeze([]),sparseReads:Object.freeze([]),sparseWrites:Object.freeze([]),relationReads:Object.freeze([]),relationWrites:Object.freeze([])}),et=(1<<20)-1;let ri=0;function oi(i,e){const t={...gt,...e,id:ms(ri++),name:i,fn:ai};return Object.freeze(t)}function ai(){}function Gt(i){const e=new Set;if(i)for(let t=0;t<i.length;t++)e.add(i[t].id);return e}function ci(i){const e=(o,a)=>o.cid-a.cid||o.id-a.id,t=new Map,s=new Map;for(const o of i)t.set(o,[]),s.set(o,0);for(const o of i)if(o.writes.size!==0)for(const a of i){if(o===a)continue;let c=!1;for(const h of o.writes)if(a.reads.has(h)){c=!0;break}c&&(t.get(o).push(a),s.set(a,s.get(a)+1))}const n=i.filter(o=>s.get(o)===0).sort(e),r=[];for(;n.length>0;){const o=n.shift();r.push(o);for(const a of t.get(o)){const c=s.get(a)-1;s.set(a,c),c===0&&(n.push(a),n.sort(e))}}if(r.length!==i.length){const o=new Set(r);for(const a of i.slice().sort(e))o.has(a)||r.push(a)}return r}class hi{constructor(e,t){this.store=e,this.ctx=t}entries=[];byCid=new Map;_topo=null;_addBuckets=new Map;_remBuckets=new Map;_disBuckets=new Map;_enaBuckets=new Map;_radixOut=[];_radixC0=new Int32Array(1024);_radixC1=new Int32Array(1024);_setDrainCache=new Map;get count(){return this.entries.length}descriptors(){const e=new Array(this.entries.length);for(let t=0;t<this.entries.length;t++)e[t]=this.entries[t].descriptor;return e}register(e,t){const s=e.id,n=t.granularity??"archetype",r=t.onSet!==void 0&&n==="entity",o=t.onSet!==void 0&&n!=="entity",a=t.access??{},c=oi(`observer(${s})`,a),h={id:c.id,cid:s,def:e,onAdd:t.onAdd,onRemove:t.onRemove,onDisable:t.onDisable,onEnable:t.onEnable,onSetEntity:r?t.onSet:void 0,onSetArch:o?t.onSet:void 0,descriptor:c,writes:Gt(a.writes),reads:Gt(a.reads),yieldExisting:t.yieldExisting??!1,lastSetTick:0,disposed:!1};this.entries.push(h);let l=this.byCid.get(s);return l===void 0&&(l=[],this.byCid.set(s,l)),l.push(h),this._topo=null,this._reconfigureComponent(s),h.yieldExisting&&h.onAdd!==void 0&&this._yieldExisting(h),{dispose:()=>this._dispose(h)}}_dispose(e){if(e.disposed)return;e.disposed=!0;const t=this.entries.indexOf(e);t>=0&&this.entries.splice(t,1);const s=this.byCid.get(e.cid);if(s!==void 0){const n=s.indexOf(e);n>=0&&s.splice(n,1),s.length===0&&this.byCid.delete(e.cid)}this._topo=null,this._reconfigureComponent(e.cid)}_reconfigureComponent(e){const t=this.byCid.get(e);let s=!1,n=!1,r=!1,o=!1,a=!1;if(t!==void 0)for(let c=0;c<t.length;c++){const h=t[c];h.onAdd!==void 0&&(s=!0),h.onRemove!==void 0&&(n=!0),h.onDisable!==void 0&&(r=!0),h.onEnable!==void 0&&(o=!0),h.onSetEntity!==void 0&&(a=!0)}this.store._configureComponentObservation(e,s,n,r,o,a)}getTopo(){return this._topo===null&&(this._topo=ci(this.entries)),this._topo}dispatchStructural(e){this._bucket(e.addComp,e.addEid,e.addLen,this._addBuckets),this._bucket(e.remComp,e.remEid,e.remLen,this._remBuckets),this._bucket(e.disComp,e.disEid,e.disLen,this._disBuckets),this._bucket(e.enaComp,e.enaEid,e.enaLen,this._enaBuckets);const t=this.getTopo();for(let s=0;s<t.length;s++){const n=t[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(e,t,s,n){Ue(s,this._radixOut,this._radixC0,this._radixC1);try{for(let o=0;o<s.length;o++)t(s[o],this.ctx)}finally{}}_bucket(e,t,s,n){for(let r=0;r<s;r++){const o=e[r];let a=n.get(o);a===void 0&&(a=[],n.set(o,a)),a.push(t[r])}}_clearBuckets(e){for(const t of e.values())t.length=0}dispatchSet(e){if(this.entries.length===0)return;const t=this.getTopo(),s=this._setDrainCache;for(let n=0;n<t.length;n++){const r=t[n];r.onSetEntity!==void 0?this._dispatchSetEntity(r,s):r.onSetArch!==void 0&&this._dispatchSetArch(r,e)}for(const n of s.values())n.length=0;s.clear()}_dispatchSetEntity(e,t){let s=t.get(e.cid);if(s===void 0&&(s=this.store._takeDirty(e.cid),Ue(s,this._radixOut,this._radixC0,this._radixC1),t.set(e.cid,s)),s.length===0)return;const n=e.def,r=e.onSetEntity;try{for(let o=0;o<s.length;o++){const a=s[o];this.store.isAlive(a)&&this.store.hasComponent(a,n)&&!this.store.isDisabled(a)&&r(a,this.ctx)}}finally{}}_dispatchSetArch(e,t){const s=e.onSetArch,n=e.lastSetTick;try{this.store._forEachChangedArchetype(e.cid,n,r=>{s(r,this.ctx)})}finally{}e.lastSetTick=t+1}_yieldExisting(e){const t=e.onAdd,s=this.store._collectEntitiesWithComponent(e.cid);if(s.length!==0){Ue(s,this._radixOut,this._radixC0,this._radixC1);try{for(let n=0;n<s.length;n++)t(s[n],this.ctx)}finally{}}}}function Ue(i,e,t,s){const n=i.length;if(!(n<2)){e.length<n&&(e.length=n),t.fill(0),s.fill(0);for(let r=0;r<n;r++){const o=i[r]&et;t[o&1023]++,s[o>>10&1023]++}for(let r=1;r<1024;r++)t[r]+=t[r-1],s[r]+=s[r-1];for(let r=n-1;r>=0;r--){const o=i[r];e[--t[o&et&1023]]=o}for(let r=n-1;r>=0;r--){const o=e[r];i[--s[(o&et)>>10&1023]]=o}}}function ws(i,e,t){const s=i.get(e);s!==void 0?s.push(t):i.set(e,[t])}function Es(i){const e={};for(let r=0;r<K.length;r++){const o=K[r],a=i.view.getUint32(b[o.headerOff],!0);a!==0&&o.readOptions(i.view,a,e)}const t=hs(i.view);t.length>0&&(e.regions=t.map(r=>({id:r.regionId,name:`region:${r.regionId}`,bytes:r.byteLength,init:()=>{}})));const s=i.view.getUint32(b.bindings_off,!0);if(s!==0){const r=i.view.getUint32(b.layout_descriptor_off,!0);e.bindingsRegionBytes=r-s}const n=i._reservedDescriptorBytes;return n!==void 0&&n>0&&(e.reservedDescriptorBytes=n),e}function bs(i){const e=new Map;for(let n=0;n<K.length;n++){const r=K[n],o=i.view.getUint32(b[r.headerOff],!0);if(o===0)continue;const a=r.regionBytes(i.view,o);e.set(r.headerOff,new Uint8Array(i.buffer,o,a).slice())}const t=new Map,s=hs(i.view);for(let n=0;n<s.length;n++){const r=s[n];t.set(r.regionId,new Uint8Array(i.buffer,r.byteOffset,r.byteLength).slice())}return{mechanism:e,consumer:t}}function Cs(i,e){for(const[t,s]of e.mechanism){const n=i.view.getUint32(b[t],!0);new Uint8Array(i.buffer,n,s.byteLength).set(s)}for(const[t,s]of e.consumer){const n=ls(i.view,t);if(n===0)continue;new Uint8Array(i.buffer,n,s.byteLength).set(s)}}function Is(i,e){const t=new Map;for(const[s,n]of i.archetypes){const r=e.get(s)??0;if(r===0)continue;const o=[];for(let a=0;a<n.columnsInOrder.length;a++){const c=n.columnsInOrder[a],h=r*c.stride,l=new Uint8Array(h);l.set(new Uint8Array(c.view.buffer,c.view.byteOffset,h)),o.push(l)}t.set(s,o)}return t}function As(i,e){for(const[t,s]of e){const n=i.archetypes.get(t);if(n===void 0)throw new Error(`restore_column_snapshots: new store missing archetype ${t} (internal)`);const r=n.columnsInOrder;for(let o=0;o<s.length;o++){const a=r[o].view;new Uint8Array(a.buffer,a.byteOffset,s[o].byteLength).set(s[o])}}}class ce extends Error{constructor(e){super(e),this.name="StoreExtendError"}}function li(i,e,t){if(e.newArchetypes.length===0)throw new ce("extend plan has no new archetypes; use grow_column_store for resizes");const s=new Set;for(let _=0;_<e.newArchetypes.length;_++){const g=e.newArchetypes[_].archetypeId;if(s.has(g))throw new ce(`duplicate archetype_id ${g} in extend plan`);if(i.archetypes.has(g))throw new ce(`archetype_id ${g} already exists in the SAB; use grow_column_store to resize it`);s.add(g)}const n=new Map;if(e.existing)for(let _=0;_<e.existing.length;_++){const g=e.existing[_];if(!i.archetypes.has(g.archetypeId))throw new ce(`existing row_count names unknown archetype_id ${g.archetypeId}`);if(g.rowCount<0)throw new ce(`archetype ${g.archetypeId}: row_count must be non-negative (got ${g.rowCount})`);if(g.rowCount>0){const p=i.archetypes.get(g.archetypeId);if(g.rowCount>p.rowCapacity)throw new ce(`archetype ${g.archetypeId}: row_count ${g.rowCount} > old row_capacity ${p.rowCapacity}`)}n.set(g.archetypeId,g.rowCount)}const r=i;if(t?.isInPlace===!0&&r._allocator===t&&typeof r._regionBytes=="number"){const _=i.view.getUint32(b.layout_descriptor_off,!0);let g=0;for(const[,m]of i.archetypes)g+=Se(m.columnsInOrder.length);let p=0;for(let m=0;m<e.newArchetypes.length;m++)p+=Se(e.newArchetypes[m].columns.length);if(g+p<=r._regionBytes)return di(i,e.newArchetypes,_,g)}const a=[];for(const[_,g]of i.archetypes)a.push({archetypeId:_,componentMask:g.componentMask,rowCapacity:g.rowCapacity,columns:g.columnsInOrder});for(let _=0;_<e.newArchetypes.length;_++)a.push(e.newArchetypes[_]);const c=i.view.getUint32(b.view_stamp,!0),h=Is(i,n),l=bs(i),d=Es(i),u=At(a,t,d);As(u,h),Cs(u,l);const f=c+1>>>0;return u.view.setUint32(b.view_stamp,f,!0),{store:{...u,header:{...u.header,viewStamp:f}},oldViewStamp:c,newViewStamp:f,viewsPreserved:!1}}function di(i,e,t,s){let n=i.buffer.byteLength;const r=new Array(e.length);for(let p=0;p<e.length;p++){const m=e[p],w=new Array(m.columns.length);for(let S=0;S<m.columns.length;S++){const E=m.columns[S],v=dt[E.typeTag];n=Xe(n,v),w[S]={componentId:E.componentId,fieldId:E.fieldId,typeTag:E.typeTag,byteOff:n,stride:v},n+=v*m.rowCapacity}r[p]={archetypeId:m.archetypeId,componentMask:m.componentMask,rowCount:0,enabledCount:0,rowCapacity:m.rowCapacity,columns:w}}const o=n;if(o>Te)throw new je(o);const a=i._allocator(o),h=a!==i.buffer?new DataView(a):i.view;let l=t+s;for(let p=0;p<r.length;p++)l=bt(h,l,r[p]);const d=h.getUint32(b.view_stamp,!0),u=i.archetypes.size+e.length;h.setUint32(b.archetype_count,u,!0),h.setUint32(b.capacity,o,!0);const f=d+1>>>0;h.setUint32(b.view_stamp,f,!0);const y=Ke(a,r),_=new Map;for(const[p,m]of i.archetypes)_.set(p,m);for(const[p,m]of y)_.set(p,m);return{store:{buffer:a,view:h,header:{...i.header,viewStamp:f,capacity:o,archetypeCount:u},archetypes:_,_regionBytes:i._regionBytes,_allocator:i._allocator,_reservedDescriptorBytes:i._reservedDescriptorBytes},oldViewStamp:d,newViewStamp:f,viewsPreserved:!0}}function ui(i,e,t){let s=i.buffer.byteLength;const n=new Map;for(let p=0;p<e.length;p++){const m=e[p],w=i.archetypes.get(m.archetypeId),S=new Array(w.columnsInOrder.length);for(let E=0;E<w.columnsInOrder.length;E++){const v=w.columnsInOrder[E];s=Xe(s,v.stride),S[E]={componentId:v.componentId,fieldId:v.fieldId,typeTag:v.typeTag,byteOff:s,stride:v.stride},s+=v.stride*m.newRowCapacity}n.set(m.archetypeId,{archetypeId:m.archetypeId,componentMask:w.componentMask,rowCount:0,enabledCount:0,rowCapacity:m.newRowCapacity,columns:S})}const r=s;if(r>Te)throw new je(r);const o=i._allocator(r),c=o!==i.buffer?new DataView(o):i.view,h=new Uint8Array(o);for(let p=0;p<e.length;p++){const m=e[p],w=i.archetypes.get(m.archetypeId),S=n.get(m.archetypeId);for(let E=0;E<w.columnsInOrder.length;E++){const v=w.columnsInOrder[E],R=m.rowCount*v.stride;R>0&&h.copyWithin(S.columns[E].byteOff,v.byteOff,v.byteOff+R)}}let l=t;for(const[p,m]of i.archetypes){const w=n.get(p);w!==void 0&&bt(c,l,w),l+=Se(m.columnsInOrder.length)}const d=c.getUint32(b.view_stamp,!0),u=d+1>>>0;c.setUint32(b.view_stamp,u,!0),c.setUint32(b.capacity,r,!0);const f=Ke(o,[...n.values()]),y=new Map;for(const[p,m]of i.archetypes){const w=f.get(p);y.set(p,w??m)}const _={buffer:o,view:c,header:{...i.header,viewStamp:u,capacity:r},archetypes:y,_regionBytes:i._regionBytes,_allocator:i._allocator,_reservedDescriptorBytes:i._reservedDescriptorBytes},g=new Array(e.length);for(let p=0;p<e.length;p++)g[p]=e[p].archetypeId;return{store:_,oldViewStamp:d,newViewStamp:u,viewsPreserved:!0,grownArchetypeIds:g}}class tt extends Error{constructor(e){super(e),this.name="StoreGrowError"}}function fi(i,e,t){const s=new Map;for(let g=0;g<e.archetypes.length;g++){const p=e.archetypes[g];s.set(p.archetypeId,p)}const n=[],r=[];for(const[g,p]of i.archetypes){const m=s.get(g),w=m?.newRowCapacity??p.rowCapacity;if(w<(m?.rowCount??0))throw new tt(`archetype ${g}: new_row_capacity ${w} < row_count ${m?.rowCount}`);if(w<p.rowCapacity)throw new tt(`archetype ${g}: shrinking from ${p.rowCapacity} to ${w} is not supported`);w>p.rowCapacity&&r.push({archetypeId:g,newRowCapacity:w,rowCount:m?.rowCount??0}),n.push({archetypeId:g,componentMask:p.componentMask,rowCapacity:w,columns:p.columnsInOrder})}const o=new Map;for(const[g,p]of i.archetypes){const w=s.get(g)?.rowCount??0;if(w>p.rowCapacity)throw new tt(`archetype ${g}: row_count ${w} > old row_capacity ${p.rowCapacity}`);w>0&&o.set(g,w)}const a=i;if(t?.isInPlace===!0&&a._allocator===t&&r.length>0){const g=i.view.getUint32(b.layout_descriptor_off,!0);return ui(i,r,g)}const h=i.view.getUint32(b.view_stamp,!0),l=Is(i,o),d=bs(i),u=Es(i),f=At(n,t,u);As(f,l),Cs(f,d);const y=h+1>>>0;return f.view.setUint32(b.view_stamp,y,!0),{store:{...f,header:{...f.header,viewStamp:y}},oldViewStamp:h,newViewStamp:y,viewsPreserved:!1,grownArchetypeIds:[]}}const yt=810766935,Fe=1;class k extends Error{constructor(e){super(e),this.name="WorldRestoreError"}}const ge=4;function _i(i){const e=i.freeIndices.length,t=i.archetypeRows.length,s=ge*(4+e+1+t*3),n=new Uint8Array(s),r=new DataView(n.buffer);let o=0;const a=c=>{r.setUint32(o,c,!0),o+=ge};a(i.tick),a(i.entityHighWater),a(i.entityAliveCount),a(e);for(let c=0;c<e;c++)a(i.freeIndices[c]);a(t);for(let c=0;c<t;c++){const h=i.archetypeRows[c];a(h.archetypeId),a(h.length),a(h.enabledCount)}return n}function pi(i){const e=new DataView(i.buffer,i.byteOffset,i.byteLength),t=i.byteLength;let s=0;const n=f=>{if(s+f>t)throw new k(`host-state truncated: need ${f} more bytes at offset ${s}, have ${t-s}`)},r=()=>{n(ge);const f=e.getUint32(s,!0);return s+=ge,f},o=r(),a=r(),c=r(),h=r(),l=new Array(h);for(let f=0;f<h;f++)l[f]=r();const d=r(),u=new Array(d);for(let f=0;f<d;f++){const y=r(),_=r(),g=r();u[f]={archetypeId:y,length:_,enabledCount:g}}if(s!==t)throw new k(`host-state has ${t-s} trailing bytes after the last archetype (not a canonical encoding)`);return{tick:o,entityHighWater:a,entityAliveCount:c,freeIndices:l,archetypeRows:u}}function gi(i,e,t){const s=ge*5,n=new Uint8Array(s+i.length+e.length+t.length),r=new DataView(n.buffer);return r.setUint32(0,yt,!0),r.setUint32(4,Fe,!0),r.setUint32(8,i.length,!0),r.setUint32(12,e.length,!0),r.setUint32(16,t.length,!0),n.set(i,s),n.set(e,s+i.length),n.set(t,s+i.length+e.length),n}function yi(i){const e=ge*5;if(i.byteLength<e)throw new k(`world snapshot too small: ${i.byteLength} bytes (frame header needs ${e})`);const t=new DataView(i.buffer,i.byteOffset,i.byteLength),s=t.getUint32(0,!0);if(s!==yt)throw new k(`bad world-snapshot magic: 0x${s.toString(16).padStart(8,"0")} (expected 0x${yt.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=t.getUint32(4,!0);if(n!==Fe)throw new k(`incompatible world-snapshot version: snapshot=${n}, build=${Fe}`);const r=t.getUint32(8,!0),o=t.getUint32(12,!0),a=t.getUint32(16,!0);if(e+r+o+a!==i.byteLength)throw new k(`world-snapshot frame mismatch: header declares ${e}+${r}+${o}+${a}=${e+r+o+a} bytes, buffer is ${i.byteLength}`);const c=i.byteOffset,h=i.buffer;return{dense:new Uint8Array(h,c+e,r),sparse:new Uint8Array(h,c+e+r,o),host:new Uint8Array(h,c+e+r+o,a)}}function mi(i,e,t){if(i.byteLength<Ae)throw new k(`dense section too small: ${i.byteLength} bytes (SAB header needs ${Ae})`);const s=new DataView(i.buffer,i.byteOffset,i.byteLength),n=s.getUint32(b.magic,!0);if(n!==Ce)throw new k(`dense section bad magic: 0x${n.toString(16).padStart(8,"0")} (expected SAB magic 0x${Ce.toString(16).padStart(8,"0")})`);const r=s.getUint32(b.sim_abi_version,!0);if(r!==Ie)throw new k(`dense section incompatible sim_abi_version: snapshot=${r}, build=${Ie}`);const o=ns(s);if(o.layoutDescriptorOff<0||o.layoutDescriptorOff>i.byteLength)throw new k(`dense layoutDescriptorOff ${o.layoutDescriptorOff} is outside the section (${i.byteLength} bytes)`);const a=o.entityIndexOff;if(a<0||a+Re>i.byteLength)throw new k(`dense entityIndexOff ${a} is outside the section (${i.byteLength} bytes)`);const c=s.getUint32(a+ee.capacity,!0);if(c!==t)throw new k(`entity-index capacity mismatch: live=${t}, snapshot=${c}`);let h;try{h=is(s,o.layoutDescriptorOff,o.archetypeCount)}catch(l){throw l instanceof RangeError?new k(`dense section layout is corrupt or truncated: a descriptor reads past the ${i.byteLength}-byte section (${l.message})`):l}if(e.size!==h.length)throw new k(`archetype-set mismatch: the live world has ${e.size} SAB archetypes, the snapshot has ${h.length}. restoreInto requires an identical archetype set (prewarm the world so its archetype set is stable, per ADR on no-lazy archetypes).`);for(let l=0;l<h.length;l++){const d=h[l],u=e.get(d.archetypeId);if(u===void 0)throw new k(`archetype-set mismatch: snapshot archetype ${d.archetypeId} is absent from the live world`);if(!wi(u.componentMask,d.componentMask))throw new k(`archetype ${d.archetypeId} component-mask mismatch between the live world and the snapshot (different component registration)`);const f=u.columnsInOrder,y=d.columns;if(f.length!==y.length)throw new k(`archetype ${d.archetypeId} column-count mismatch: live=${f.length}, snapshot=${y.length}`);for(let _=0;_<f.length;_++)if(f[_].componentId!==y[_].componentId||f[_].fieldId!==y[_].fieldId||f[_].typeTag!==y[_].typeTag)throw new k(`archetype ${d.archetypeId} column ${_} layout mismatch: live=(c${f[_].componentId},f${f[_].fieldId},t${f[_].typeTag}), snapshot=(c${y[_].componentId},f${y[_].fieldId},t${y[_].typeTag})`)}}function wi(i,e){if(i.length!==e.length)return!1;for(let t=0;t<i.length;t++)if(i[t]!==e[t])return!1;return!0}const Ht=65536,Ei=[],Vt=-1,st=new DataView(new ArrayBuffer(8)),Yt=129,bi=7,nt=-1;class Ci{entityGenerations;entityHighWater=0;entityFreeIndices=[];entityAliveCount=0;componentMetas=[];componentCount=0;sparseStores=[];relations=[];_hasTargetCleanup=!1;eventChannels=[];dirtyEventChannels=[];eventCount=0;archetypes=[];archetypeMap=new Map;nextArchetypeId=0;componentIndex=[];registeredQueries=[];emptyArchetypeId;entityArchetype;entityRow;pendingDestroy=[];pendingAddIds=[];pendingAddDefs=[];pendingAddValues=[];pendingRemoveIds=[];pendingRemoveDefs=[];pendingToggleIds=[];pendingToggleDisable=[];_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;_flushingStructural=!1;_collectDestroyEid=0;_collectDestroyRemoveBit=e=>{if(!this.componentMetas[e].obsRem)return;const t=this._obsEvents;t.remComp[t.remLen]=e,t.remEid[t.remLen]=this._collectDestroyEid,t.remLen++};_collectToggleEid=0;_collectDisableBit=e=>{if(!this.componentMetas[e].obsDisable)return;const t=this._obsEvents;t.disComp[t.disLen]=e,t.disEid[t.disLen]=this._collectToggleEid,t.disLen++};_collectEnableBit=e=>{if(!this.componentMetas[e].obsEnable)return;const t=this._obsEvents;t.enaComp[t.enaLen]=e,t.enaEid[t.enaLen]=this._collectToggleEid,t.enaLen++};_toggleInitial=new Map;_anyDirtyTracked=!1;_dirtyTrackedCids=[];_dirtyLists=[];_dirtyMarks=[];_rowCountsDirty=!1;_queryDirtyEpoch=0;initialCapacity;_scratchTargetMask=new U.BitSet;_hierarchyRadixOut=[];_hierarchyRadixC0=new Int32Array(1024);_hierarchyRadixC1=new Int32Array(1024);_columnStore;_entityIndexLengthView;_growHandler=(e,t)=>{const s=e.id,n=this._columnStore.archetypes.get(s);if(n===void 0)throw new A(I.ARCHETYPE_NOT_FOUND,`grow_handler invoked on archetype ${s} which has no SAB region`);const r=n.rowCapacity,o=e.length+t;let a=r>0?r:1;for(;a<o;)a=a*2;const c=[],h=this.archetypes;for(let d=0;d<h.length;d++){const u=h[d],f=this._columnStore.archetypes.get(u.id);f!==void 0&&c.push({archetypeId:u.id,newRowCapacity:u.id===s?a:f.rowCapacity,rowCount:u.hasColumns?u.length:0})}let l;try{l=fi(this._columnStore,{archetypes:c},this._bufferAllocator)}catch(d){throw d instanceof B.StoreCapExceededError?this._capExceededError(d):d}if(this._columnStore=l.store,l.viewsPreserved){const d=l.grownArchetypeIds;for(let u=0;u<d.length;u++){const f=this.archGet(d[u]);f.isBufferBacked&&f.refreshViews(this._columnStore)}}else for(let d=0;d<h.length;d++)h[d].isBufferBacked&&h[d].refreshViews(this._columnStore);this._handleBufferResized()};_capExceededError(e){const t=this._capContext,s=this.entityAliveCount,n=`SAB grow refused: requested ${e.requestedBytes} bytes exceeds `+(e.capBytes!==null?`the ${e.capBytes}-byte cap.`:"the backing's ceiling.");let r;if(t===void 0)r=` The ECS holds ${s} live entities (no sizing intent declared).`;else if(t.budgetEntities!==null){const o=(s/t.budgetEntities).toFixed(1);r=` Declared ${t.intentLabel}; the ECS holds ${s} live entities (${o}× the budget) — runaway entity creation upstream, or an under-declared budget. Raise the budget only if a ${s}-entity ECS is intended.`}else r=` Declared ${t.intentLabel}; the ECS holds ${s} live entities.`;return new A(I.STORE_CAP_EXCEEDED,n+r+` The cap is a hard ceiling with no grow-beyond fallback (#380) — diagnose growth before raising it. Caused by: ${e.message}`)}_bufferAllocator;_capContext;_onBufferResized;constructor(e){const t=typeof e=="number"?{initialCapacity:e}:e??{};if(this.initialCapacity=t.initialCapacity??q,this._bufferAllocator=t.bufferAllocator??B.growableSabAllocator(),this._bufferAllocator.isInPlace!==!0)throw new A(I.INVALID_MEMORY_OPTIONS,"Store requires an in-place SAB allocator (ADR-0008): the flush loops keep writing through hoisted entity-index views across grows, so a non-in-place allocator (e.g. DEFAULT_SAB_ALLOCATOR) corrupts the entity→row mapping. Use growable_sab_allocator / wasm_memory_allocator; non-in-place allocators are snapshot/test sizing utilities only.");this._capContext=t.capContext,this._onBufferResized=t.onBufferResized,this._entityIndexCapacity=t.entityIndexCapacity??V,this._regions=t.regions,this._bindingsRegionBytes=t.bindingsRegionBytes??0,this._deterministic=t.deterministic??!1,this._columnStore=At([],this._bufferAllocator,{reservedDescriptorBytes:64*1024,entityIndexCapacity:this._entityIndexCapacity,eventRingCapacitySlots:_n,commandRingCapacitySlots:Js,actionRingCapacitySlots:En,regions:this._regions,bindingsRegionBytes:this._bindingsRegionBytes});const s=Mt(this._columnStore.buffer,this._columnStore.header.entityIndexOff,this._entityIndexCapacity);this.entityGenerations=s.generations,this.entityArchetype=s.archetypes,this.entityRow=s.rows,this._entityIndexLengthView=new Uint32Array(this._columnStore.buffer,this._columnStore.header.entityIndexOff+ee.length,1),this.emptyArchetypeId=this.archGetOrCreateFromMask(new U.BitSet)}_entityIndexCapacity;_regions;_bindingsRegionBytes;_deterministic;get deterministic(){return this._deterministic}_requireDeterministic(e){if(!this._deterministic)throw new A(I.DETERMINISM_DISABLED,`${e} requires determinism — construct the Store/ECS with { deterministic: true }. The canonical-ordering determinism surface (state_hash / snapshot_sparse / restore_sparse) is opt-in; see ADR-0020.`)}_rejectNonDeterministicFields(e,t,s){if(this._deterministic)for(let n=0;n<t.length;n++){const r=t[n];if(r==="f32"||r==="f64")throw new A(I.NON_DETERMINISTIC_COLUMN_TYPE,`Cannot register ${s} field "${e[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:e[n],type:r,kind:s})}}_refreshEntityIndexViews(){const e=this._columnStore.view.getUint32(b.entity_index_off,!0),t=Mt(this._columnStore.buffer,e,this._entityIndexCapacity);this.entityGenerations=t.generations,this.entityArchetype=t.archetypes,this.entityRow=t.rows,this._entityIndexLengthView=new Uint32Array(this._columnStore.buffer,e+ee.length,1)}_handleBufferResized(){this._refreshEntityIndexViews(),this._entityIndexLengthView[0]=this.entityHighWater,this._onBufferResized?.()}get columnStore(){return this._columnStore}regionOffset(e){return ls(this._columnStore.view,e)}regionHandle(e){const t=xn(this._columnStore.view,e);return t===null?null:{buffer:this._columnStore.buffer,view:this._columnStore.view,offset:t.byteOffset,bytes:t.byteLength}}publishRowCountsToDescriptor(){if(!this._rowCountsDirty)return;const e=this._columnStore.view;let t=e.getUint32(b.layout_descriptor_off,!0);const s=this.archetypes;for(let n=0;n<s.length;n++){const r=s[n];if(!r.isBufferBacked)continue;const o=e.getUint32(t+N.column_count,!0);e.setUint32(t+N.row_count,r.hasColumns?r.length:0,!0),e.setUint32(t+N.enabled_count,r.hasColumns?r.enabledCount:0,!0),t+=qe+o*ze}this._rowCountsDirty=!1}stateHash(){this._requireDeterministic("state_hash()");let e=us;const t=this.archetypes;for(let r=0;r<t.length;r++){const o=t[r],a=o.id,c=o.length;if(e=$(e,a),e=$(e,c),e=$(e,o.enabledCount),c===0)continue;const h=o._flatColumns;for(let l=0;l<h.length;l++){const d=h[l].buf,u=c*d.BYTES_PER_ELEMENT,f=new Uint8Array(d.buffer,d.byteOffset,u),y=u>>>2;let _=0;for(let p=0;p<y;p++){const m=(f[_]|f[_+1]<<8|f[_+2]<<16|f[_+3]<<24)>>>0;e=(e^m)>>>0,e=Math.imul(e,Be),_+=4}const g=u&3;if(g!==0){let p=f[_];g>1&&(p|=f[_+1]<<8),g>2&&(p|=f[_+2]<<16),e=(e^p>>>0)>>>0,e=Math.imul(e,Be)}}}const s=this.sparseStores;for(let r=0;r<s.length;r++){const o=s[r];e=$(e,r),e=$(e,o.size);const a=o.canonicalIndices();for(let c=0;c<a.length;c++){const h=a[c];e=$(e,h);const l=o.getRow(h);for(let d=0;d<l.length;d++)st.setFloat64(0,l[d],!0),e=$(e,st.getUint32(0,!0)),e=$(e,st.getUint32(4,!0))}}const n=this.relations;for(let r=0;r<n.length;r++){const o=n[r];o.exclusive||(e=$(e,r),o.forEachCanonicalTargetSet((a,c)=>{e=$(e,a),e=$(e,c.length);for(let h=0;h<c.length;h++)e=$(e,c[h])}))}return e>>>0}archGet(e){return this.archetypes[e]}entityIdAtRow(e,t){return this.archGet(e).entityIds[t]}archGetOrCreateFromMask(e){const t=e.hash(),s=this.archLookup(e,t);if(s!==null)return s;const n=Pt(this.nextArchetypeId++),r=this.archBuildLayouts(e);return this.archExtendStoreWithNewSpecs([Wt(n,e,r,this.initialCapacity)]),this.archInstall(n,e,r,t),n}archCreateManyFromMasks(e){const t=new Array(e.length),s=[],n=[],r=[],o=[];for(let c=0;c<e.length;c++){const h=e[c],l=h.hash(),d=this.archLookup(h,l);if(d!==null){t[c]=d;continue}let u=!1;for(let y=0;y<s.length;y++)if(n[y]===l&&s[y].equals(h)){t[c]=o[y],u=!0;break}if(u)continue;const f=Pt(this.nextArchetypeId++);s.push(h),n.push(l),r.push(this.archBuildLayouts(h)),o.push(f),t[c]=f}if(s.length===0)return t;const a=new Array(s.length);for(let c=0;c<s.length;c++)a[c]=Wt(o[c],s[c],r[c],this.initialCapacity);this.archExtendStoreWithNewSpecs(a);for(let c=0;c<s.length;c++)this.archInstall(o[c],s[c],r[c],n[c]);return t}archLookup(e,t){const s=this.archetypeMap.get(t);if(s===void 0)return null;for(let n=0;n<s.length;n++)if(this.archetypes[s[n]].mask.equals(e))return s[n];return null}archBuildLayouts(e){const t=[];return e.forEach(s=>{const n=s,r=this.componentMetas[n];r&&r.fieldNames.length>0&&t.push({componentId:n,fieldNames:r.fieldNames,fieldIndex:r.fieldIndex,fieldTypes:r.fieldTypes})}),t}archExtendStoreWithNewSpecs(e){const t=[],s=this.archetypes;for(let r=0;r<s.length;r++){const o=s[r],a=this._columnStore.archetypes.get(o.id);a!==void 0&&t.push({archetypeId:o.id,newRowCapacity:a.rowCapacity,rowCount:o.hasColumns?o.length:0})}let n;try{n=li(this._columnStore,{newArchetypes:e,existing:t},this._bufferAllocator)}catch(r){throw r instanceof B.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()}archInstall(e,t,s,n){const r=t.copy(),o=Tt.fromColumnStore(e,r,s,this._columnStore,e);o.growHandler=this._growHandler,this.archetypes.push(o),ws(this.archetypeMap,n,e),t.forEach(c=>{const h=c;let l=this.componentIndex[h];l===void 0&&(l=[],this.componentIndex[h]=l),l.push(e)});const a=this.registeredQueries;for(let c=0;c<a.length;c++){const h=a[c];o.matches(h.includeMask)&&(!h.excludeMask||!o.mask.overlaps(h.excludeMask))&&(!h.anyOfMask||o.mask.overlaps(h.anyOfMask))&&h.result.push(o)}}archResolveAdd(e,t){const s=this.archGet(e);if(s.mask.has(t))return e;const n=s.getEdge(t);if(n?.add!=null)return n.add;const r=this.archGetOrCreateFromMask(s.mask.copyWithSet(t));return this.archCacheEdge(s,this.archGet(r),t),r}archResolveRemove(e,t){const s=this.archGet(e);if(!s.mask.has(t))return e;const n=s.getEdge(t);if(n?.remove!=null)return n.remove;const r=this.archGetOrCreateFromMask(s.mask.copyWithClear(t));return this.archCacheEdge(this.archGet(r),s,t),r}archCacheEdge(e,t,s){const n=e.getEdge(s)??{add:null,remove:null,addMap:null,removeMap:null};n.add=t.id,n.addMap=pt(e,t),e.setEdge(s,n);const r=t.getEdge(s)??{add:null,remove:null,addMap:null,removeMap:null};r.remove=e.id,r.removeMap=pt(t,e),t.setEdge(s,r)}createEntity(){let e,t;if(this.entityFreeIndices.length>0)e=this.entityFreeIndices.pop(),t=this.entityGenerations[e];else{if(this.entityHighWater>=this._entityIndexCapacity)throw new A(I.EID_MAX_INDEX_OVERFLOW,`entity_index_capacity (${this._entityIndexCapacity}) exhausted; raise StoreOptions.entity_index_capacity or destroy unused entities`);e=this.entityHighWater++,this.entityGenerations[e]=De,t=De,this._entityIndexLengthView[0]=this.entityHighWater}this.entityAliveCount++;const s=ie(e,t);return this.entityArchetype[e]=this.emptyArchetypeId,this.entityRow[e]=T,s}_spawnIndex=0;_allocEntity(){let e,t;if(this.entityFreeIndices.length>0)e=this.entityFreeIndices.pop(),t=this.entityGenerations[e];else{if(this.entityHighWater>=this._entityIndexCapacity)throw new A(I.EID_MAX_INDEX_OVERFLOW,`entity_index_capacity (${this._entityIndexCapacity}) exhausted; raise StoreOptions.entity_index_capacity or destroy unused entities`);e=this.entityHighWater++,this.entityGenerations[e]=De,t=De,this._entityIndexLengthView[0]=this.entityHighWater}return this.entityAliveCount++,this._spawnIndex=e,ie(e,t)}_ensureEntityIndexCapacity(e){const t=e-this.entityFreeIndices.length;if(t>0&&this.entityHighWater+t>this._entityIndexCapacity)throw new A(I.EID_MAX_INDEX_OVERFLOW,`entity_index_capacity (${this._entityIndexCapacity}) cannot fit ${e} new entities (${this.entityFreeIndices.length} free, high-water ${this.entityHighWater}); raise StoreOptions.entity_index_capacity or destroy unused entities`)}resolveTemplate(e){const t=new U.BitSet;for(let c=0;c<e.length;c++)t.set(e[c].def.id);const s=this.archGetOrCreateFromMask(t),n=this.archGet(s),r=new Array(n._flatColumns.length).fill(0),o=new Map,a=new Array(e.length);for(let c=0;c<e.length;c++){a[c]=e[c].def;const h=e[c].def.id,l=this.componentMetas[h];if(l===void 0)throw new A(I.COMPONENT_NOT_REGISTERED,`template: component ${h} is not registered`);const d=e[c].values??re,u=n._colOffset[h];for(let f=0;f<l.fieldNames.length;f++){const y=l.fieldNames[f];r[u+f]=d[y]??0,o.set(y,o.has(y)?Vt:u+f)}}return{archetypeId:s,flatValues:r,overrideIndex:o,defs:a}}_applyOverrides(e,t,s,n){const r=e._flatColumns;for(const o in n){if(n[o]===void 0)continue;const a=s.overrideIndex.get(o);a!==void 0&&a!==Vt&&(r[a].buf[t]=n[o])}}spawn(e,t){const s=this.archetypes[e.archetypeId];s.materializesRows&&s.ensureRowCapacity(1);const n=this._allocEntity(),r=this._spawnIndex;if(!s.materializesRows)return this.entityArchetype[r]=e.archetypeId,this.entityRow[r]=T,n;const o=s.length,a=s.enabledCount,c=s.addEntityWithValues(n,e.flatValues,this._tick,this.entityRow);return t!==void 0&&this._applyOverrides(s,c,e,t),this.entityArchetype[r]=e.archetypeId,this.entityRow[r]=c,this._onArchGrow(s,o,a),n}spawnMany(e,t){if(t<=0)return[];const s=this.archetypes[e.archetypeId];this._ensureEntityIndexCapacity(t),s.ensureRowCapacity(t);const n=new Array(t),r=new Uint32Array(t);for(let d=0;d<t;d++){const u=this._allocEntity();r[d]=u,n[d]=u}const o=this.entityArchetype,a=this.entityRow;if(!s.materializesRows){for(let d=0;d<t;d++){const u=C(n[d]);o[u]=e.archetypeId,a[u]=T}return n}const c=s.length,h=s.enabledCount;if(s.disabledCount>0){for(let d=0;d<t;d++){const u=s.addEntityWithValues(n[d],e.flatValues,this._tick,a),f=C(n[d]);o[f]=e.archetypeId,a[f]=u}return this._onArchGrow(s,c,h),n}const l=s.addEntitiesWithValues(r,t,e.flatValues,this._tick);for(let d=0;d<t;d++){const u=C(n[d]);o[u]=e.archetypeId,a[u]=l+d}return this._onArchGrow(s,c,h),n}destroyEntity(e){if(!this.isAlive(e))return;if(!this._hasTargetCleanup){this._destroyOne(e,null);return}const t=[e];for(let s=0;s<t.length;s++){const n=t[s];this.isAlive(n)&&this._destroyOne(n,t)}}_destroyOne(e,t){const s=C(e),n=this.entityRow[s];if(n!==T){const o=this.archGet(this.entityArchetype[s]),a=o.length;o.removeRow(n,this.entityRow),this._onArchLenChange(o,a)}this.entityArchetype[s]=T,this.entityRow[s]=T,this.relations.length>0&&(this._purgeRelations(e),t!==null&&this._cleanupRelationTargets(e,t)),this.sparseStores.length>0&&this._purgeSparse(s),this._anyDirtyTracked&&this._clearDirtyForIndex(s);const r=ct(e)+1;r<le?(this.entityGenerations[s]=r,this.entityFreeIndices.push(s)):this.entityGenerations[s]=le,this.entityAliveCount--}isAlive(e){if(e<0||e>$e)return!1;const t=ct(e);if(t===le)return!1;const s=C(e);return s<this.entityHighWater&&this.entityGenerations[s]===t}get entityCount(){return this.entityAliveCount}_onArchLenChange(e,t){this._rowCountsDirty=!0,t===0!=(e.length===0)&&this._queryDirtyEpoch++}_onArchGrow(e,t,s){this._rowCountsDirty=!0,(t===0||s===0&&e.enabledCount!==0)&&this._queryDirtyEpoch++}_onArchEnabledChange(e,t){this._rowCountsDirty=!0,t===0!=(e.enabledCount===0)&&this._queryDirtyEpoch++}disableEntity(e){if(!this.isAlive(e))return;const t=C(e),s=this.entityRow[t];if(s===T)return;const n=this.archGet(this.entityArchetype[t]);if(s>=n.enabledCount)return;const r=n.enabledCount;n.disableRow(s,this.entityRow),this._onArchEnabledChange(n,r)}enableEntity(e){if(!this.isAlive(e))return;const t=C(e),s=this.entityRow[t];if(s===T)return;const n=this.archGet(this.entityArchetype[t]);if(s<n.enabledCount)return;const r=n.enabledCount;n.enableRow(s,this.entityRow),this._onArchEnabledChange(n,r)}isDisabled(e){if(!this.isAlive(e))return!1;const t=C(e),s=this.entityRow[t];if(s===T)return!1;const n=this.archGet(this.entityArchetype[t]);return s>=n.enabledCount}_flushEpoch=0;_flushTouched=[];_settleFlushDirty(){const e=this._flushTouched;if(e.length===0)return;this._rowCountsDirty=!0;let t=!1;for(let s=0;s<e.length;s++){const n=e[s];(n._flushPreLen===0!=(n.length===0)||n._flushPreEnabled===0!=(n.enabledCount===0))&&(t=!0)}t&&this._queryDirtyEpoch++,e.length=0,this._flushEpoch++}destroyEntityDeferred(e){this.pendingDestroy.push(e)}disableEntityDeferred(e){this.pendingToggleIds.push(e),this.pendingToggleDisable.push(!0)}enableEntityDeferred(e){this.pendingToggleIds.push(e),this.pendingToggleDisable.push(!1)}_flushToggles(){const e=this.pendingToggleIds,t=this.pendingToggleDisable,s=e.length;if(!(this._toggleObserverCount>0)){for(let o=0;o<s;o++){const a=e[o];this.isAlive(a)&&(t[o]?this.disableEntity(a):this.enableEntity(a))}e.length=0,t.length=0;return}const r=this._toggleInitial;for(let o=0;o<s;o++){const a=e[o];this.isAlive(a)&&(r.has(a)||r.set(a,this.isDisabled(a)))}for(let o=0;o<s;o++){const a=e[o];this.isAlive(a)&&(t[o]?this.disableEntity(a):this.enableEntity(a))}e.length=0,t.length=0;for(const[o,a]of r){if(!this.isAlive(o))continue;const c=this.isDisabled(o);a!==c&&this._collectToggle(o,c)}r.clear()}_collectToggle(e,t){const s=C(e);if(this.entityRow[s]===T)return;const n=this.archGet(this.entityArchetype[s]);this._collectToggleEid=e,n.mask.forEach(t?this._collectDisableBit:this._collectEnableBit)}get pendingToggleCount(){return this.pendingToggleIds.length}flushDestroyed(){this._flushingStructural||this._drainDestroyed()}_drainDestroyed(){const e=this.pendingDestroy;if(e.length===0)return;const t=this.entityArchetype,s=this.entityRow,n=this.entityGenerations,r=this.archetypes,o=this.entityHighWater,a=this.entityFreeIndices;let c=!1,h=!1;const l=this.sparseStores.length>0,d=this.relations.length>0,u=d&&this._hasTargetCleanup,f=this._anyDirtyTracked,y=this._structuralObserverCount>0;for(let _=0;_<e.length;_++){const g=e[_],p=g&j,m=g>>Z;if(p>=o||n[p]!==m)continue;const w=s[p];if(w!==T){const E=r[t[p]];y&&(this._collectDestroyEid=g,E.mask.forEach(this._collectDestroyRemoveBit)),E.removeRow(w,s),c=!0,E.length===0&&(h=!0)}d&&this._purgeRelations(g),u&&this._cleanupRelationTargets(g,e),l&&this._purgeSparse(p),f&&this._clearDirtyForIndex(p),t[p]=T,s[p]=T;const S=m+1;S<le?(n[p]=S,a.push(p)):n[p]=le,this.entityAliveCount--}e.length=0,c&&(this._rowCountsDirty=!0,h&&this._queryDirtyEpoch++)}get pendingDestroyCount(){return this.pendingDestroy.length}addComponentDeferred(e,t,s){this.pendingAddIds.push(e),this.pendingAddDefs.push(t),this.pendingAddValues.push(s??re)}removeComponentDeferred(e,t){this.pendingRemoveIds.push(e),this.pendingRemoveDefs.push(t)}flushStructural(){if(this._structuralObserverCount===0&&this._toggleObserverCount===0){this.pendingAddIds.length>0&&this._flushAdds(),this.pendingRemoveIds.length>0&&this._flushRemoves(),this.pendingToggleIds.length>0&&this._flushToggles();return}if(this._flushingStructural)return;this._flushingStructural=!0;const e=this._obsEvents,t=this._structuralObserverHook;try{let s=0;for(;this.pendingAddIds.length>0||this.pendingRemoveIds.length>0||this.pendingDestroy.length>0||this.pendingToggleIds.length>0;){if(++s>Ht)throw new A(I.OBSERVER_NON_CONVERGENT,`observer cascade did not converge after ${Ht} rounds — two observers likely enqueue each other's structural ops forever`);e.addLen=0,e.remLen=0,e.disLen=0,e.enaLen=0,this.pendingAddIds.length>0||this.pendingRemoveIds.length>0?(this.pendingAddIds.length>0&&this._flushAdds(),this.pendingRemoveIds.length>0&&this._flushRemoves()):this.pendingDestroy.length>0?this._drainDestroyed():this._flushToggles(),t!==null&&(e.addLen>0||e.remLen>0||e.disLen>0||e.enaLen>0)&&t(e)}}finally{this._flushingStructural=!1}}_flushAdds(){const e=this.pendingAddIds,t=this.pendingAddDefs,s=this.pendingAddValues,n=e.length,r=this.entityArchetype,o=this.entityRow,a=this.entityGenerations,c=this.archetypes,h=this.componentMetas,l=this.entityHighWater,d=this._tick,u=this._flushEpoch,f=this._flushTouched,y=this._structuralObserverCount>0,_=this._obsEvents;for(let g=0;g<n;g++){const p=e[g],m=p&j,w=p>>Z;if(m>=l||a[m]!==w)continue;const S=r[m],E=t[g].id,v=c[S],R=h[E];if(v.mask.has(E)){R.fieldNames.length>0&&v.writeFields(o[m],E,s[g],d);continue}const z=this.archResolveAdd(S,E),x=c[z],ae=o[m],Dt=!x.hasColumns&&!v.hasColumns;ae!==T&&v._flushSeenEpoch!==u&&(v._flushSeenEpoch=u,v._flushPreLen=v.length,v._flushPreEnabled=v.enabledCount,f.push(v)),x._flushSeenEpoch!==u&&(x._flushSeenEpoch=u,x._flushPreLen=x.length,x._flushPreEnabled=x.enabledCount,f.push(x));let Oe;if(ae!==T){if(Dt)x.moveEntityFromTag(v,ae,p,o);else{const Ns=v.getEdge(E);x.moveEntityFrom(v,ae,p,Ns.addMap,d,o)}Oe=L[0]}else Oe=Dt?x.addEntityTag(p,o):x.addEntity(p,o);R.fieldNames.length>0&&x.writeFields(Oe,E,s[g],d),r[m]=z,o[m]=Oe,y&&R.obsAdd&&(_.addComp[_.addLen]=E,_.addEid[_.addLen]=p,_.addLen++)}e.length=0,t.length=0,s.length=0,this._settleFlushDirty()}_flushRemoves(){const e=this.pendingRemoveIds,t=this.pendingRemoveDefs,s=e.length,n=this.entityArchetype,r=this.entityRow,o=this.entityGenerations,a=this.archetypes,c=this.entityHighWater,h=this._tick,l=this._flushEpoch,d=this._flushTouched,u=this.componentMetas,f=this._structuralObserverCount>0,y=this._obsEvents;for(let _=0;_<s;_++){const g=e[_],p=g&j,m=g>>Z;if(p>=c||o[p]!==m)continue;const w=n[p],S=t[_].id,E=a[w];if(!E.mask.has(S))continue;const v=this.archResolveRemove(w,S),R=a[v],z=r[p],x=!R.hasColumns&&!E.hasColumns;if(E._flushSeenEpoch!==l&&(E._flushSeenEpoch=l,E._flushPreLen=E.length,E._flushPreEnabled=E.enabledCount,d.push(E)),R._flushSeenEpoch!==l&&(R._flushSeenEpoch=l,R._flushPreLen=R.length,R._flushPreEnabled=R.enabledCount,d.push(R)),x)R.moveEntityFromTag(E,z,g,r);else{const ae=E.getEdge(S);R.moveEntityFrom(E,z,g,ae.removeMap,h,r)}n[p]=v,r[p]=L[0],f&&u[S].obsRem&&(y.remComp[y.remLen]=S,y.remEid[y.remLen]=g,y.remLen++)}e.length=0,t.length=0,this._settleFlushDirty()}get pendingStructuralCount(){return this.pendingAddIds.length+this.pendingRemoveIds.length}_configureComponentObservation(e,t,s,n,r,o){const a=this.componentMetas[e];if(a===void 0)throw new A(I.COMPONENT_NOT_REGISTERED,`observe(): component ${e} is not registered`);const c=a.obsAdd||a.obsRem;a.obsAdd=t,a.obsRem=s;const h=t||s;c&&!h?this._structuralObserverCount--:!c&&h&&this._structuralObserverCount++;const l=a.obsDisable||a.obsEnable;a.obsDisable=n,a.obsEnable=r;const d=n||r;if(l&&!d?this._toggleObserverCount--:!l&&d&&this._toggleObserverCount++,o&&!a.trackDirty)a.trackDirty=!0,this._dirtyLists[e]===void 0&&(this._dirtyLists[e]=[],this._dirtyMarks[e]=new Uint8Array(Math.max(1,this.entityGenerations.length))),this._dirtyTrackedCids.push(e),this._anyDirtyTracked=!0;else if(!o&&a.trackDirty){a.trackDirty=!1;const u=this._dirtyTrackedCids.indexOf(e);u>=0&&this._dirtyTrackedCids.splice(u,1),this._anyDirtyTracked=this._dirtyTrackedCids.length>0;const f=this._dirtyLists[e],y=this._dirtyMarks[e];if(f!==void 0&&y!==void 0){for(let _=0;_<f.length;_++)y[f[_]&j]=0;f.length=0}}}_noteSet(e,t){const s=e.id,n=this.componentMetas[s];if(n===void 0||!n.trackDirty)return;const r=t&j;let o=this._dirtyMarks[s];r>=o.length&&(o=this._growDirtyMarks(s,r)),o[r]===0&&(o[r]=1,this._dirtyLists[s].push(t))}_growDirtyMarks(e,t){const s=this._dirtyMarks[e];let n=Math.max(1,s.length);for(;n<=t;)n*=2;const r=new Uint8Array(n);return r.set(s),this._dirtyMarks[e]=r,r}_takeDirty(e){const t=this._dirtyLists[e];if(t===void 0||t.length===0)return Ei;this._dirtyLists[e]=[];const s=this._dirtyMarks[e];for(let n=0;n<t.length;n++)s[t[n]&j]=0;return t}_clearDirtyForIndex(e){const t=this._dirtyTrackedCids;for(let s=0;s<t.length;s++){const n=this._dirtyMarks[t[s]];n!==void 0&&e<n.length&&(n[e]=0)}}_forEachChangedArchetype(e,t,s){const n=this.componentIndex[e];if(n===void 0)return;const r=this.archetypes;for(let o=0;o<n.length;o++){const a=r[n[o]];a.length>0&&a._changedTick[e]>=t&&s(a)}}_collectEntitiesWithComponent(e){const t=[],s=this.componentIndex[e];if(s===void 0)return t;const n=this.archetypes;for(let r=0;r<s.length;r++){const o=n[s[r]],a=o.entityIds;for(let c=0;c<o.enabledCount;c++)t.push(a[c])}return t}registerComponent(e){if(this.componentCount>=ke)throw new A(I.COMPONENT_LIMIT_EXCEEDED,`Cannot register more than ${ke} components: the SAB archetype descriptor mask is ${ke} bits wide. Widen the descriptor mask (descriptor.ts + abi.zig, a SIM_ABI_VERSION bump) to raise it.`,{componentCount:this.componentCount,limit:ke});const t=Object.keys(e),s=new Array(t.length),n=Object.create(null);for(let o=0;o<t.length;o++)n[t[o]]=o,s[o]=e[t[o]];this._rejectNonDeterministicFields(t,s,"component");const r=ts(this.componentCount++);return this.componentMetas.push({fieldNames:t,fieldIndex:n,fieldTypes:s,obsAdd:!1,obsRem:!1,obsDisable:!1,obsEnable:!1,trackDirty:!1}),ss(r)}fieldIdOf(e,t){const s=e.id,n=this.componentMetas[s];if(n===void 0)throw new A(I.COMPONENT_NOT_REGISTERED,`field_id_of: component ${s} is not registered`);const r=n.fieldIndex[t];if(r===void 0)throw new A(I.FIELD_NOT_REGISTERED,`field_id_of: component ${s} has no field "${t}"`);return r}registerSparseComponent(e){const t=Object.keys(e),s=new Array(t.length);for(let n=0;n<t.length;n++)s[n]=e[t[n]];return this._rejectNonDeterministicFields(t,s,"sparse component"),this._pushSparseStore(t,s)}_pushSparseStore(e,t){const s=this.sparseStores.length;return this.sparseStores.push(new $n(e,t)),s}sparseStoreOf(e){const t=e,s=this.sparseStores[t];if(s===void 0)throw new A(I.COMPONENT_NOT_REGISTERED,`sparse component ${t} is not registered`);return s}addSparse(e,t,s){this.isAlive(e)&&this.sparseStoreOf(t).setRow(C(e),s??re)}removeSparse(e,t){this.isAlive(e)&&this.sparseStoreOf(t).remove(C(e))}hasSparse(e,t){return this.isAlive(e)?this.sparseStoreOf(t).has(C(e)):!1}getSparseField(e,t,s){const n=this.sparseStoreOf(t),r=n.fieldIndex[s];if(r===void 0)return 0;const o=n.getField(C(e),r);return o===void 0?0:o}setSparseField(e,t,s,n){const r=this.sparseStoreOf(t),o=r.fieldIndex[s];o!==void 0&&r.setField(C(e),o,n)}_purgeSparse(e){const t=this.sparseStores;for(let s=0;s<t.length;s++)t[s].remove(e)}snapshotSparse(){this._requireDeterministic("snapshot_sparse()");const e=Bn(this.sparseStores),t=zn(this.relations),s=new Uint8Array(8+e.length+t.length),n=new DataView(s.buffer);return n.setUint32(0,e.length,!0),n.setUint32(4,t.length,!0),s.set(e,8),s.set(t,8+e.length),s}restoreSparse(e){this._requireDeterministic("restore_sparse()");const t=new DataView(e.buffer,e.byteOffset,e.byteLength);if(e.byteLength<8)throw new D(`sparse snapshot truncated: need 8 header bytes, have ${e.byteLength}`);const s=t.getUint32(0,!0),n=t.getUint32(4,!0);if(8+s+n!==e.byteLength)throw new D(`sparse snapshot frame mismatch: header declares 8+${s}+${n}=${8+s+n} bytes, buffer is ${e.byteLength}`);Pn(this.sparseStores,e.subarray(8,8+s)),this._rebuildRelationIndices(e.subarray(8+s,8+s+n))}_rebuildRelationIndices(e){const t=this.entityGenerations,s=r=>ie(r,t[r]);qn(this.relations,e,s);const n=this.relations;for(let r=0;r<n.length;r++)n[r].rebuildReverseFromForward(s)}snapshot(){this._requireDeterministic("snapshot()"),this.publishRowCountsToDescriptor();const e=new Uint8Array(Ln(this._columnStore)),t=this.snapshotSparse(),s=_i(this._collectHostState());return gi(e,t,s)}_collectHostState(){const e=[],t=this.archetypes;for(let s=0;s<t.length;s++){const n=t[s];n.isBufferBacked&&e.push({archetypeId:n.id,length:n.length,enabledCount:n.enabledCount})}return{tick:this._tick,entityHighWater:this.entityHighWater,entityAliveCount:this.entityAliveCount,freeIndices:this.entityFreeIndices.slice(),archetypeRows:e}}restoreInto(e){this._requireDeterministic("restoreInto()");const t=yi(e),s=pi(t.host);mi(t.dense,this._columnStore.archetypes,this._entityIndexCapacity),this._assertSparseSectionMatches(t.sparse);const n=Un(t.dense,this._bufferAllocator);this._columnStore=n;const r=this.archetypes;for(let o=0;o<r.length;o++)r[o].isBufferBacked&&r[o].refreshViews(this._columnStore);this.entityHighWater=n.view.getUint32(n.header.entityIndexOff+ee.length,!0),this._handleBufferResized(),this._reconstructHostRows(s),this.entityFreeIndices.length=0;for(let o=0;o<s.freeIndices.length;o++)this.entityFreeIndices.push(s.freeIndices[o]);this.entityAliveCount=s.entityAliveCount,this._tick=s.tick,this._queryDirtyEpoch++,this._rowCountsDirty=!0,this.restoreSparse(t.sparse)}_assertSparseSectionMatches(e){const t=new DataView(e.buffer,e.byteOffset,e.byteLength);if(e.byteLength<8)throw new D(`sparse snapshot truncated: need 8 header bytes, have ${e.byteLength}`);const s=t.getUint32(0,!0),n=t.getUint32(4,!0);if(8+s+n!==e.byteLength)throw new D(`sparse snapshot frame mismatch: header declares 8+${s}+${n}=${8+s+n} bytes, buffer is ${e.byteLength}`);Fn(this.sparseStores,e.subarray(8,8+s))}_reconstructHostRows(e){const t=this.entityHighWater,s=this.entityArchetype,n=this.entityRow,r=this.entityGenerations,o=new Map;for(let a=0;a<t;a++){const c=s[a];if(c===T)continue;const h=n[a];if(h===T)continue;let l=o.get(c);l===void 0&&(l=[],o.set(c,l)),l[h]=ie(a,r[a])}for(let a=0;a<e.archetypeRows.length;a++){const c=e.archetypeRows[a],h=this.archGet(c.archetypeId),l=o.get(c.archetypeId)??[];h.restoreHostRows(l,c.enabledCount)}}registerRelation(e){const t=e?.multi===!0,s=e?.exclusive===!0;if(t&&s)throw new A(I.RELATION_MODE_INVALID,"register_relation: a relation cannot be both exclusive and multi-target");const n=!t,r=e?.onDeleteTarget??Gn,o=n?this._pushSparseStore([fs],["f64"]):this._pushSparseStore([],[]),a=this.relations.length;return this.relations.push(Wn(n,o,this.sparseStoreOf(o),r)),r!=="orphan"&&(this._hasTargetCleanup=!0),a}relationOf(e){const t=e,s=this.relations[t];if(s===void 0)throw new A(I.RELATION_NOT_REGISTERED,`relation ${t} is not registered`);return s}get relationCount(){return this.relations.length}addRelation(e,t,s){const n=this.relationOf(t);this.isAlive(e)&&this.isAlive(s)&&n.link(e,s)}removeRelation(e,t,s){const n=this.relationOf(t);this.isAlive(e)&&n.unlink(e,s)}targetOf(e,t){return this.relationOf(t).singleTarget(C(e))}targetsOf(e,t){return this.relationOf(t).targetsOf(C(e))}sourcesOf(e,t){return this.relationOf(e).sourcesOf(t)}hasRelation(e,t){return this.hasSparse(e,this.relationOf(t).sparse)}pairsOf(e){const t=this.relationOf(e),s=[],n=this.entityGenerations;return t.forEachCanonicalPair(r=>ie(r,n[r]),(r,o)=>s.push([r,o])),s}sourcesOfAny(e){const t=[],s=this.relations;for(let n=0;n<s.length;n++){const r=n,o=s[n].sourcesOf(e);for(let a=0;a<o.length;a++)t.push([r,o[a]])}return t}relationBackingSparseId(e){return this.relationOf(e).sparse}_forEachRelationTargetMatch(e,t,s,n,r,o,a,c){const h=this.relations;if(h.length===0)return;const l=new Set;for(let g=0;g<h.length;g++){const p=h[g].sourcesOf(e);for(let m=0;m<p.length;m++)l.add(p[m])}if(l.size===0)return;const d=Array.from(l).sort((g,p)=>g-p),u=this.sparseStores,f=this.entityArchetype,y=this.entityRow,_=this.archetypes;for(let g=0;g<d.length;g++){const p=d[g],m=C(p),w=f[m];if(w===T)continue;const S=_[w],E=S.mask;if(!E.contains(t)||s!==null&&E.overlaps(s)||n!==null&&!E.overlaps(n))continue;let v=!0;for(let R=0;R<r.length;R++)if(!u[r[R]].has(m)){v=!1;break}if(v){for(let R=0;R<o.length;R++)if(u[o[R]].has(m)){v=!1;break}if(v){if(!a){const R=y[m];if(R!==T&&R>=S.enabledCount)continue}c(p)}}}}compactRelations(){const e=this.relations;if(e.length===0)return 0;const t=n=>this.isAlive(n);let s=0;for(let n=0;n<e.length;n++)s+=e[n].pruneDeadReverse(t);return s}ancestorsOf(e,t){const s=this.relationOf(t),n=this.sparseStoreOf(s.sparse),r=[e],o=new Set([C(e)]);let a=e;for(;;){const c=n.getField(C(a),0);if(c===void 0)break;const h=c;if(!this.isAlive(h)){r.push(h);break}const l=C(h);if(o.has(l))break;o.add(l),a=h,r.push(a)}return r}rootOf(e,t){const s=this.ancestorsOf(e,t);return s[s.length-1]}cascadeOf(e,t){const s=this.relationOf(t),n=[e],r=new Set([C(e)]);for(let o=0;o<n.length;o++){const a=s.sourcesOf(n[o]);for(let c=0;c<a.length;c++){const h=a[c],l=C(h);r.has(l)||(r.add(l),n.push(h))}}return n}_purgeRelations(e){const t=this.relations;for(let s=0;s<t.length;s++)t[s].purgeSource(e)}_cleanupRelationTargets(e,t){const s=this.relations;for(let n=0;n<s.length;n++){const r=s[n];if(r.onDeleteTarget==="orphan")continue;const o=r.sourcesOf(e);if(o.length!==0){if(r.onDeleteTarget==="delete"){for(let a=0;a<o.length;a++)t.push(o[a]);continue}for(let a=0;a<o.length;a++)r.unlink(o[a],e)}}}_forEachSparseMatch(e,t,s,n,r,o,a,c){const h=this.sparseStores;if(n.length>0){let d=h[n[0]];for(let p=1;p<n.length;p++){const m=h[n[p]];m.size<d.size&&(d=m)}const u=d.indices,f=this.entityGenerations,y=this.entityArchetype,_=this.entityRow,g=this.archetypes;for(let p=0;p<u.length;p++){const m=u[p];let w=!0;for(let R=0;R<n.length;R++){const z=h[n[R]];if(z!==d&&!z.has(m)){w=!1;break}}if(!w)continue;for(let R=0;R<r.length;R++)if(h[r[R]].has(m)){w=!1;break}if(!w)continue;const S=y[m];if(S===T)continue;const E=g[S],v=E.mask;if(v.contains(e)&&!(t!==null&&v.overlaps(t))&&!(s!==null&&!v.overlaps(s))){if(!c){const R=_[m];if(R!==T&&R>=E.enabledCount)continue}a(ie(m,f[m]))}}return}const l=r.length>0;for(let d=0;d<o.length;d++){const u=o[d],f=u.entityIds,y=c?u.totalCount:u.enabledCount;for(let _=0;_<y;_++){const g=f[_];if(l){const p=C(g);let m=!1;for(let w=0;w<r.length;w++)if(h[r[w]].has(p)){m=!0;break}if(m)continue}a(g)}}}_forEachHierarchyMatch(e,t,s,n,r,o,a,c,h,l){const d=this.relationOf(a),u=[];if(this._forEachSparseMatch(e,t,s,n,r,o,p=>u.push(p),h),u.length===0)return;Ue(u,this._hierarchyRadixOut,this._hierarchyRadixC0,this._hierarchyRadixC1);const f=this.sparseStoreOf(d.sparse),y=new Map,_=new Set,g=[];for(let p=0;p<u.length;p++){const m=u[p],w=this._hierarchyDepthOf(C(m),f,y,_);if(w>c)continue;let S=g[w];S===void 0&&(S=[],g[w]=S),S.push(m)}for(let p=0;p<g.length;p++){const m=g[p];if(m!==void 0)for(let w=0;w<m.length;w++)l(m[w])}}_hierarchyDepthOf(e,t,s,n){const r=[];let o=e,a=0;for(;;){const h=s.get(o);if(h!==void 0){a=h;break}const l=t.getField(o,0);let d=-1;if(l!==void 0){const u=l;this.isAlive(u)&&(d=C(u))}if(d===-1){s.set(o,0),a=0;break}if(n.has(d)){s.set(o,0),a=0;break}r.push(o),n.add(o),o=d}let c=a;for(let h=r.length-1;h>=0;h--)c+=1,s.set(r[h],c),n.delete(r[h]);return s.get(e)}addComponent(e,t,s){if(!this.isAlive(e))return;const n=C(e),r=this.entityArchetype[n],o=this.archGet(r);if(o.hasComponent(t.id)){o.writeFields(this.entityRow[n],t.id,s,this._tick);return}const a=this.archResolveAdd(r,t.id),c=this.archGet(a),h=this.entityRow[n];let l;if(h!==T){const d=o.length,u=c.length,f=c.enabledCount,y=o.getEdge(t.id);!c.hasColumns&&!o.hasColumns?c.moveEntityFromTag(o,h,e,this.entityRow):c.moveEntityFrom(o,h,e,y.addMap,this._tick,this.entityRow),l=L[0],this._onArchLenChange(o,d),this._onArchGrow(c,u,f)}else{const d=c.length,u=c.enabledCount;l=c.hasColumns?c.addEntity(e,this.entityRow):c.addEntityTag(e,this.entityRow),this._onArchGrow(c,d,u)}c.writeFields(l,t.id,s,this._tick),this.entityArchetype[n]=a,this.entityRow[n]=l}addComponents(e,t){if(!this.isAlive(e))return;const s=C(e),n=this.entityArchetype[s],r=this.archGet(n),o=t.length;let a=o;for(let u=0;u<o;u++){const f=t[u].def.id;if(f>=Yt-1||o>bi){a=nt;break}a=a*Yt+(f+1)}if(a!==nt){const u=r.getCompositeAddEdge(a);if(u!==void 0){this._addComponentsInto(e,s,r,this.archGet(u.target),u.target,u.map,t);return}}let c=null;for(let u=0;u<o;u++){const f=t[u].def.id;c!==null?c.set(f):r.mask.has(f)||(c=r.mask.copyInto(this._scratchTargetMask),c.set(f))}if(c===null){const u=this.entityRow[s];for(let f=0;f<o;f++)r.writeFields(u,t[f].def.id,t[f].values??re,this._tick);return}const h=this.archGetOrCreateFromMask(c),l=this.archGet(h),d=r.getBatchTransitionMap(l);a!==nt&&r.cacheCompositeAddEdge(a,h,d),this._addComponentsInto(e,s,r,l,h,d,t)}_addComponentsInto(e,t,s,n,r,o,a){const c=this.entityRow[t];let h;if(c!==T){const l=s.length,d=n.length,u=n.enabledCount;n.moveEntityFrom(s,c,e,o,this._tick,this.entityRow),h=L[0],this._onArchLenChange(s,l),this._onArchGrow(n,d,u)}else{const l=n.length,d=n.enabledCount;h=n.addEntity(e,this.entityRow),this._onArchGrow(n,l,d)}for(let l=0;l<a.length;l++)n.writeFields(h,a[l].def.id,a[l].values??re,this._tick);this.entityArchetype[t]=r,this.entityRow[t]=h}removeComponent(e,t){if(!this.isAlive(e))return;const s=C(e),n=this.entityArchetype[s],r=this.archGet(n);if(!r.hasComponent(t.id))return;const o=this.archResolveRemove(n,t.id),a=this.archGet(o),c=this.entityRow[s],h=r.getEdge(t.id),l=!a.hasColumns&&!r.hasColumns,d=r.length,u=a.length,f=a.enabledCount;l?a.moveEntityFromTag(r,c,e,this.entityRow):a.moveEntityFrom(r,c,e,h.removeMap,this._tick,this.entityRow),this.entityArchetype[s]=o,this.entityRow[s]=L[0],this._onArchLenChange(r,d),this._onArchGrow(a,u,f)}removeComponents(e,t){if(!this.isAlive(e))return;const s=C(e),n=this.entityArchetype[s],r=this.archGet(n);let o=null;for(let y=0;y<t.length;y++){const _=t[y].id;o!==null?o.clear(_):r.mask.has(_)&&(o=r.mask.copyInto(this._scratchTargetMask),o.clear(_))}if(o===null)return;const a=this.archGetOrCreateFromMask(o),c=this.archGet(a),h=this.entityRow[s],l=r.length,d=c.length,u=c.enabledCount,f=r.getBatchTransitionMap(c);c.moveEntityFrom(r,h,e,f,this._tick,this.entityRow),this.entityArchetype[s]=a,this.entityRow[s]=L[0],this._onArchLenChange(r,l),this._onArchGrow(c,d,u)}hasComponent(e,t){if(!this.isAlive(e))return!1;const s=C(e);return this.archGet(this.entityArchetype[s]).hasComponent(t.id)}batchAddComponent(e,t,s){const n=this.archGet(e);if(n.length===0)return;const r=t.id;if(n.mask.has(r))return;const o=this.archResolveAdd(n.id,r),a=this.archGet(o);if(n.disabledCount>0||a.disabledCount>0)throw new A(I.PARTITION_BULK_INTO_DISABLED,"batchAddComponent is unsupported on archetypes with disabled entities (#577) — enable them first or use per-entity addComponent");const c=n.getEdge(r),h=n.length,l=h,d=a.length,u=a.enabledCount,f=this.entityArchetype,y=this.entityRow,_=a.bulkMoveAllFrom(n,c.addMap,this._tick);for(let p=0;p<h;p++){const m=C(a.entityIds[_+p]);f[m]=o,y[m]=_+p}this.componentMetas[r].fieldNames.length>0&&s&&a.bulkWriteFields(_,h,r,s,this._tick),this._onArchLenChange(n,l),this._onArchGrow(a,d,u)}batchRemoveComponent(e,t){const s=this.archGet(e);if(s.length===0)return;const n=t.id;if(!s.mask.has(n))return;const r=this.archResolveRemove(s.id,n),o=this.archGet(r);if(s.disabledCount>0||o.disabledCount>0)throw new A(I.PARTITION_BULK_INTO_DISABLED,"batchRemoveComponent is unsupported on archetypes with disabled entities (#577) — enable them first or use per-entity removeComponent");const a=s.getEdge(n),c=s.length,h=c,l=this.entityArchetype,d=this.entityRow;if(!o.materializesRows){const _=s.entityIds;for(let g=0;g<c;g++){const p=C(_[g]);l[p]=r,d[p]=T}s.clearRows(),this._onArchLenChange(s,h);return}const u=o.length,f=o.enabledCount,y=o.bulkMoveAllFrom(s,a.removeMap,this._tick);for(let _=0;_<c;_++){const g=C(o.entityIds[y+_]);l[g]=r,d[g]=y+_}this._onArchLenChange(s,h),this._onArchGrow(o,u,f)}getEntityArchetype(e){return this.archGet(this.entityArchetype[C(e)])}getEntityRow(e){return this.entityRow[C(e)]}getMatchingArchetypes(e,t,s){const n=e._words;let r=!1;for(let h=0;h<n.length;h++)if(n[h]!==0){r=!0;break}if(!r){const h=this.archetypes,l=[];for(let d=0;d<h.length;d++){const u=h[d];(!t||!u.mask.overlaps(t))&&(!s||u.mask.overlaps(s))&&l.push(u)}return l}let o,a=!1;for(let h=0;h<n.length;h++){let l=n[h];if(l===0)continue;const d=h<<U.BITS_PER_WORD_SHIFT;for(;l!==0;){const u=l&-l>>>0,f=d+(U.BITS_PER_WORD_MASK-Math.clz32(u));l^=u;const y=this.componentIndex[f];if(y===void 0||y.length===0){a=!0;break}(!o||y.length<o.length)&&(o=y)}if(a)break}if(a||!o)return[];const c=[];for(let h=0;h<o.length;h++){const l=this.archGet(o[h]);l.matches(e)&&(!t||!l.mask.overlaps(t))&&(!s||l.mask.overlaps(s))&&c.push(l)}return c}registerQuery(e,t,s){const n=this.getMatchingArchetypes(e,t,s);return this.registeredQueries.push({includeMask:e.copy(),excludeMask:t?t.copy():null,anyOfMask:s?s.copy():null,result:n,query:null}),n}updateQueryRef(e,t){const s=this.registeredQueries;for(let n=0;n<s.length;n++)if(s[n].result===e){s[n].query=t;return}}get archetypeCount(){return this.archetypes.length}registerEvent(e){const t=jn(this.eventCount++),s=new Xn(e);return this.eventChannels.push(s),t}emitEvent(e,t){const s=e,n=this.eventChannels[s],r=n.reader.length===0;n.emit(t),r&&this.dirtyEventChannels.push(s)}emitSignal(e){const t=e,s=this.eventChannels[t],n=s.reader.length===0;s.emitSignal(),n&&this.dirtyEventChannels.push(t)}getEventReader(e){return this.eventChannels[e].reader}clearEvents(){const e=this.dirtyEventChannels,t=this.eventChannels;for(let s=0;s<e.length;s++)t[e[s]].clear();e.length=0}_devBufferedEventCount(){const e=this.dirtyEventChannels,t=this.eventChannels;let s=0;for(let n=0;n<e.length;n++)s+=t[e[n]].reader.length;return s}eventKeyMap=new Map;registerEventByKey(e,t){if(this.eventKeyMap.has(e))throw new A(I.EVENT_ALREADY_REGISTERED,"Event key already registered");const s=this.registerEvent(t);return this.eventKeyMap.set(e,s),s}getEventDefByKey(e){const t=this.eventKeyMap.get(e);if(t===void 0)throw new A(I.EVENT_NOT_REGISTERED,"Event key not registered");return t}hasEventKey(e){return this.eventKeyMap.has(e)}resourceKeyMap=new Map;registerResource(e,t){if(this.resourceKeyMap.has(e))throw new A(I.RESOURCE_ALREADY_REGISTERED,"Resource key already registered");this.resourceKeyMap.set(e,t)}getResource(e){if(!this.resourceKeyMap.has(e))throw new A(I.RESOURCE_NOT_REGISTERED,"Resource key not registered");return this.resourceKeyMap.get(e)}setResource(e,t){if(!this.resourceKeyMap.has(e))throw new A(I.RESOURCE_NOT_REGISTERED,"Resource key not registered");this.resourceKeyMap.set(e,t)}removeResource(e){if(!this.resourceKeyMap.has(e))throw new A(I.RESOURCE_NOT_REGISTERED,"Resource key not registered");this.resourceKeyMap.delete(e)}hasResource(e){return this.resourceKeyMap.has(e)}}function Wt(i,e,t,s){const n=[];for(let a=0;a<t.length;a++){const c=t[a],h=c.fieldTypes;for(let l=0;l<h.length;l++)n.push({componentId:c.componentId,fieldId:l,typeTag:qs[h[l]]})}const r=e._words,o=new Array(fe);for(let a=0;a<fe;a++)o[a]=(r[a]??0)>>>0;return{archetypeId:i,componentMask:o,rowCapacity:s,columns:n}}const Ii={CAPACITY:256};var Ss=(i=>(i.ECS="ECS",i))(Ss||{});class Ai{_entries=[];_capacity;_sinks=new Set;constructor(e=Ii.CAPACITY){this._capacity=e}get capacity(){return this._capacity}setCapacity(e){for(this._capacity=e;this._entries.length>this._capacity;)this._entries.shift()}get entries(){return this._entries.slice()}log(e,t){const s={timestamp:performance.now(),wallTime:Date.now(),category:e,message:t};this._entries.push(s),this._entries.length>this._capacity&&this._entries.shift();for(const n of this._sinks)n(s)}clear(){this._entries=[]}subscribe(e){return this._sinks.add(e),()=>{this._sinks.delete(e)}}}const Si=new Ai;var te=(i=>(i.PRE_STARTUP="PRE_STARTUP",i.STARTUP="STARTUP",i.POST_STARTUP="POST_STARTUP",i.FIXED_UPDATE="FIXED_UPDATE",i.PRE_UPDATE="PRE_UPDATE",i.UPDATE="UPDATE",i.POST_UPDATE="POST_UPDATE",i))(te||{});const it=["PRE_STARTUP","STARTUP","POST_STARTUP"],rt=["PRE_UPDATE","UPDATE","POST_UPDATE"];function vi(i){return Object.freeze({name:i})}function Ri(i){return!("fn"in i)}const Ee=Object.freeze([]);function ot(i){return i===void 0?Ee:Array.isArray(i)?i:[i]}class Ti{labelSystems=new Map;sortedCache=new Map;systemIndex=new Map;systemLastRun=new Map;gatedSystems=new Map;setConditions=new Map;setOrdering=new Map;nextInsertionOrder=0;_backend=null;constructor(){for(let e=0;e<it.length;e++)this.labelSystems.set(it[e],[]);this.labelSystems.set("FIXED_UPDATE",[]);for(let e=0;e<rt.length;e++)this.labelSystems.set(rt[e],[])}addSystems(e,...t){for(const s of t){const n="system"in s,r=n?s.system:s,o=n?s.ordering:void 0,a=n?ot(s.runIf):Ee,c=n?ot(s.set):Ee,h={descriptor:r,insertionOrder:this.nextInsertionOrder++,before:new Set(o?.before??[]),after:new Set(o?.after??[]),conditions:a,sets:c};this.labelSystems.get(e).push(h),this.systemIndex.set(r,e),this.systemLastRun.set(r,0),(a.length>0||c.length>0)&&this.gatedSystems.set(r,h),this.sortedCache.delete(e)}}configureSet(e,t){const s=ot(t.runIf);if(s.length>0){const n=this.setConditions.get(e);n===void 0?this.setConditions.set(e,[...s]):n.push(...s)}if(t.before!==void 0||t.after!==void 0){let n=this.setOrdering.get(e);n===void 0&&(n={before:new Set,after:new Set},this.setOrdering.set(e,n));for(const r of t.before??Ee)n.before.add(r);for(const r of t.after??Ee)n.after.add(r);this.sortedCache.clear()}}removeSystem(e){const t=this.systemIndex.get(e);if(t===void 0)return;const s=this.labelSystems.get(t),n=s.findIndex(r=>r.descriptor===e);if(n!==-1){const r=s.length-1;n!==r&&(s[n]=s[r]),s.pop();for(const o of s)o.before.delete(e),o.after.delete(e)}this.systemIndex.delete(e),this.systemLastRun.delete(e),this.gatedSystems.delete(e),this.sortedCache.delete(t)}setBackend(e){this._backend=e}runStartup(e,t){for(const s of it)this.runLabel(s,e,Hs,t)}runUpdate(e,t,s){for(const n of rt)this.runLabel(n,e,t,s)}runFixedUpdate(e,t,s){this.runLabel("FIXED_UPDATE",e,t,s)}hasFixedSystems(){return this.labelSystems.get("FIXED_UPDATE").length>0}getAllSystems(){const e=[];for(const t of this.labelSystems.values())for(const s of t)e.push(s.descriptor);return e}hasSystem(e){return this.systemIndex.has(e)}clear(){for(const e of this.labelSystems.values())e.length=0;this.sortedCache.clear(),this.systemIndex.clear(),this.systemLastRun.clear(),this.gatedSystems.clear(),this.setConditions.clear(),this.setOrdering.clear()}runLabel(e,t,s,n){const r=this.getSorted(e),o=this.gatedSystems.size>0,a=this._backend,c=o?new Map:void 0;for(let h=0;h<r.length;h++){const l=r[h];if(o){const u=this.gatedSystems.get(l);if(u!==void 0&&!this.shouldRun(u,t,c))continue}t.lastRunTick=this.systemLastRun.get(l)??0;const d=a!==null?l.backendHandle:void 0;try{d!==void 0?a.run(d):l.fn(t,s)}finally{}this.systemLastRun.set(l,n)}t.flush()}shouldRun(e,t,s){if(e.conditions.length>0&&!this.evalConditions(e.conditions,t))return!1;for(let n=0;n<e.sets.length;n++){const r=e.sets[n];let o=s.get(r);if(o===void 0){const a=this.setConditions.get(r);o=a===void 0||a.length===0?!0:this.evalConditions(a,t),s.set(r,o)}if(!o)return!1}return!0}evalConditions(e,t){for(let s=0;s<e.length;s++){const n=e[s];let r;try{r=n.evaluate(t)}finally{}if(!r)return!1}return!0}getSorted(e){const t=this.sortedCache.get(e);if(t!==void 0)return t;const s=this.labelSystems.get(e),n=this.sortSystems(s,e);return this.sortedCache.set(e,n),n}sortSystems(e,t){if(e.length===0)return[];const s=[],n=new Map,r=new Set,o=new Map;for(const l of e){s.push(l.descriptor),n.set(l.descriptor,l.insertionOrder),r.add(l.descriptor);for(let d=0;d<l.sets.length;d++){const u=l.sets[d];let f=o.get(u);f===void 0&&(f=[],o.set(u,f)),f.push(l.descriptor)}}const a=new Map;for(const l of e)a.set(l.descriptor,[]);for(const l of e){this.resolveEdges(l.descriptor,l.before,"before",r,o,a,t),this.resolveEdges(l.descriptor,l.after,"after",r,o,a,t);for(let d=0;d<l.sets.length;d++){const u=this.setOrdering.get(l.sets[d]);u!==void 0&&(this.resolveEdges(l.descriptor,u.before,"before",r,o,a,t),this.resolveEdges(l.descriptor,u.after,"after",r,o,a,t))}}const c=(l,d)=>n.get(l)-n.get(d),h=l=>l.name??`system_${l.id}`;try{return U.topologicalSort(s,a,c,h)}catch(l){throw l instanceof TypeError?new A(I.CIRCULAR_SYSTEM_DEPENDENCY,`Circular system dependency detected in ${t}: ${l.message}`):l}}resolveEdges(e,t,s,n,r,o,a){for(const c of t){if(Ri(c)){const h=r.get(c);if(h===void 0)continue;for(let l=0;l<h.length;l++){const d=h[l];d!==e&&this.addDirectedEdge(e,d,s,o)}continue}n.has(c)&&this.addDirectedEdge(e,c,s,o)}}addDirectedEdge(e,t,s,n){s==="before"?n.get(e).push(t):n.get(t).push(e)}warnDroppedEdge(e,t,s,n){if(this.systemIndex.has(t))return;const r=o=>o.name??`system_${o.id}`;Si.log(Ss.ECS,`Schedule[${n}]: \`${r(e)}\` declares \`${s}\` ordering against \`${r(t)}\`, which is not registered in any phase — the constraint is ignored. Check for a typo or a missing add_systems() call.`)}}const zt=new WeakMap;function qt(i,e){let t=zt.get(i);if(!t){t=Object.create(null);const{fieldNames:n}=i.layout;for(let r=0;r<n.length;r++){const o=i.columns[r];Object.defineProperty(t,n[r],{get(){return o.buf[this._row]},set(a){o.buf[this._row]=a},enumerable:!0,configurable:!1})}zt.set(i,t)}const s=Object.create(t);return s._row=e,s}const Oi="/packages/engine/src/core/ecs/";class Di{activeCache=null;repoRootCache=null;buf=new Map;callsiteCache=new Map;isActive(){if(this.activeCache!==null)return this.activeCache;const t=globalThis.process?.env?.VISUAL_INTEL_TRACE;return this.activeCache=t==="1"||t==="true"}repoRoot(){if(this.repoRootCache!==null)return this.repoRootCache;const e=globalThis.process;return this.repoRootCache=e?.cwd?.()??""}resolveCallsite(){return xi(new Error().stack??null,this.repoRoot(),this.callsiteCache)}record(e,t,s){const n=this.resolveCallsite();if(!n)return;const r=`${e} ${t} ${s} ${n}`;this.buf.set(r,(this.buf.get(r)??0)+1)}recordEmit(e){this.record("ecs-events","emit",e)}recordRead(e){this.record("ecs-events","read",e)}recordResourceRead(e){this.record("resources","read",e)}recordResourceWrite(e){this.record("resources","write",e)}recordResourceRegister(e){this.record("resources","register",e)}recordResourceRemove(e){this.record("resources","remove",e)}recordSendAction(e){this.record("actions","send_action",e)}recordHandleAction(e){this.record("actions","handle_action",e)}snapshot(){const e={"ecs-events":{emit:[],read:[]},actions:{send_action:[],handle_action:[]},resources:{read:[],write:[],register:[],remove:[]}};for(const[t,s]of this.buf.entries()){const[n,r,o,a]=t.split(" ");if(!n||!r||a===void 0)continue;const h={key:n==="actions"?Number(o):o,file:a,count:s},d=e[n][r];d&&d.push(h)}for(const t of Object.values(e))for(const s of Object.values(t))s.sort((n,r)=>{if(n.file!==r.file)return n.file<r.file?-1:1;const o=String(n.key),a=String(r.key);return o<a?-1:o>a?1:0});return{schemaVersion:1,capturedAt:new Date().toISOString(),channels:e}}reset(){this.buf.clear(),this.callsiteCache.clear(),this.activeCache=null,this.repoRootCache=null}}function ki(i){const e=/\(([^)]+):\d+:\d+\)\s*$/.exec(i);if(e)return e[1]??null;const t=/at\s+([^\s][^()]*?):\d+:\d+\s*$/.exec(i);return t&&(t[1]??"").trim()||null}function xi(i,e,t){if(!i)return null;const s=i.split(`
|
|
2
|
-
`);for(let n=0;n<s.length;n++){const r=s[n],o=t?.get(r);if(o!==void 0){if(o===null)continue;return o}const a=ki(r);if(!a){t?.set(r,null);continue}if(a.includes(Oi)){t?.set(r,null);continue}const c=Mi(a,e);return t?.set(r,c),c}return null}function Mi(i,e){let t=i;return t.startsWith("file://")&&(t=t.slice(7)),e&&t.startsWith(e+"/")&&(t=t.slice(e.length+1)),t.replace(/\\/g,"/")}const Ni=new Di,jt=Object.freeze([]),Li=Object.freeze([]),Xt=Object.freeze([]),mt=Number.POSITIVE_INFINITY;function we(i,e){return(i<<16|e)>>>0}function Me(i,e){for(let t=0;t<i.length;t++)if(i[t]===e)return i;return[...i,e]}function Ui(i,e){for(let t=0;t<i.length;t++)if(i[t]===e)return i;return[...i,e]}function Kt(i,e){for(let t=0;t<i.length;t++)if(i[t]===e)return i;return[...i,e]}class vs{_arch;_tick=0;mut(e){return this._arch.columnGroupMut(e,this._tick)}read(e){return this._arch.columnGroupRead(e)}}class Y{_archetypes;_defs;_resolver;_include;_exclude;_anyOf;_nonEmptyArchetypes=[];_lastSeenEpoch=-1;_id;_sparseInclude;_sparseExclude;_optional;_includeDisabled;_relationIncludes;_relationExcludes;_hierarchy;constructor(e,t,s,n,r,o,a,c=jt,h=jt,l=Li,d=!1,u=Xt,f=Xt,y=null){this._archetypes=e,this._defs=t,this._resolver=s,this._include=n,this._exclude=r,this._anyOf=o,this._id=a,this._sparseInclude=c,this._sparseExclude=h,this._optional=l,this._includeDisabled=d,this._relationIncludes=u,this._relationExcludes=f,this._hierarchy=y}_assertDenseOnly(e){if(this._sparseInclude.length>0||this._sparseExclude.length>0||this._relationIncludes.length>0||this._relationExcludes.length>0||this._hierarchy!==null)throw new A(I.SPARSE_QUERY_DENSE_PATH,`Query.${e} ignores sparse / relation-wildcard / hierarchy terms (withSparse / withoutSparse / withRelation / withoutRelation / hierarchy) — it walks only the dense archetype list and would return the wrong result (a hierarchy term has no per-archetype span — its order spans archetypes). Iterate this query with forEachEntity instead.`)}get archetypeCount(){return this._archetypes.length}count(){const e=this._nonEmpty();let t=0;if(this._includeDisabled)for(let s=0;s<e.length;s++)t+=e[s].totalCount;else for(let s=0;s<e.length;s++)t+=e[s].enabledCount;return t}get archetypes(){return this._archetypes}_carryNondense(e){return this._optional.length===0&&this._sparseInclude.length===0&&this._sparseExclude.length===0&&!this._includeDisabled&&this._relationIncludes.length===0&&this._relationExcludes.length===0&&this._hierarchy===null?e:new Y(e._archetypes,e._defs,this._resolver,e._include,e._exclude,e._anyOf,this._resolver._nextQueryId(),this._sparseInclude,this._sparseExclude,this._optional,this._includeDisabled,this._relationIncludes,this._relationExcludes,this._hierarchy)}and(...e){if(e.length===1){const s=e[0].id,n=(this._id<<16|s)>>>0,r=this._resolver._andSingleCache.get(n);return r!==void 0?r:this._andMiss(e[0],s,n)}let t=this;for(let s=0;s<e.length;s++)t=t.and(e[s]);return t}_andMiss(e,t,s){const n=this._include.copy(),r=this._defs.slice();n.has(t)||(n.set(t),r.push(e));const o=this._carryNondense(this._resolver._resolveQuery(n,this._exclude,this._anyOf,r));return this._resolver._andSingleCache.set(s,o),o}without(...e){if(e.length===1){const s=e[0].id,n=(this._id<<16|s)>>>0,r=this._resolver._notSingleCache.get(n);return r!==void 0?r:this._notMiss(s,n)}let t=this;for(let s=0;s<e.length;s++)t=t.without(e[s]);return t}_notMiss(e,t){const s=this._exclude?this._exclude.copy():new U.BitSet;s.set(e);const n=this._carryNondense(this._resolver._resolveQuery(this._include,s,this._anyOf,this._defs));return this._resolver._notSingleCache.set(t,n),n}withSparse(...e){if(e.length===1)return this._withSparseOne(e[0]);let t=this;for(let s=0;s<e.length;s++)t=t._withSparseOne(e[s]);return t}_withSparseOne(e){const t=we(this._id,e),s=this._resolver._withSparseSingleCache,n=s.get(t);if(n!==void 0)return n;const r=this._deriveSparse(Me(this._sparseInclude,e),this._sparseExclude);return s.set(t,r),r}withoutSparse(...e){if(e.length===1)return this._withoutSparseOne(e[0]);let t=this;for(let s=0;s<e.length;s++)t=t._withoutSparseOne(e[s]);return t}_withoutSparseOne(e){const t=we(this._id,e),s=this._resolver._withoutSparseSingleCache,n=s.get(t);if(n!==void 0)return n;const r=this._deriveSparse(this._sparseInclude,Me(this._sparseExclude,e));return s.set(t,r),r}_deriveSparse(e,t){return new Y(this._archetypes,this._defs,this._resolver,this._include,this._exclude,this._anyOf,this._resolver._nextQueryId(),e,t,this._optional,this._includeDisabled,this._relationIncludes,this._relationExcludes,this._hierarchy)}withRelation(...e){if(e.length===1)return this._withRelationOne(e[0]);let t=this;for(let s=0;s<e.length;s++)t=t._withRelationOne(e[s]);return t}_withRelationOne(e){const t=we(this._id,e),s=this._resolver._withRelationSingleCache,n=s.get(t);if(n!==void 0)return n;const r=this._resolver._relationBackingSparseId(e),o=this._deriveRelation(Me(this._sparseInclude,r),this._sparseExclude,Kt(this._relationIncludes,e),this._relationExcludes);return s.set(t,o),o}withoutRelation(...e){if(e.length===1)return this._withoutRelationOne(e[0]);let t=this;for(let s=0;s<e.length;s++)t=t._withoutRelationOne(e[s]);return t}_withoutRelationOne(e){const t=we(this._id,e),s=this._resolver._withoutRelationSingleCache,n=s.get(t);if(n!==void 0)return n;const r=this._resolver._relationBackingSparseId(e),o=this._deriveRelation(this._sparseInclude,Me(this._sparseExclude,r),this._relationIncludes,Kt(this._relationExcludes,e));return s.set(t,o),o}_deriveRelation(e,t,s,n){return new Y(this._archetypes,this._defs,this._resolver,this._include,this._exclude,this._anyOf,this._resolver._nextQueryId(),e,t,this._optional,this._includeDisabled,s,n,this._hierarchy)}hierarchy(e,t=mt){if(t===mt){const s=we(this._id,e),n=this._resolver._hierarchySingleCache,r=n.get(s);if(r!==void 0)return r;const o=this._deriveHierarchy({relation:e,maxDepth:t});return n.set(s,o),o}return this._deriveHierarchy({relation:e,maxDepth:t})}_deriveHierarchy(e){return new Y(this._archetypes,this._defs,this._resolver,this._include,this._exclude,this._anyOf,this._resolver._nextQueryId(),this._sparseInclude,this._sparseExclude,this._optional,this._includeDisabled,this._relationIncludes,this._relationExcludes,e)}_checkRelationAccess(){for(let e=0;e<this._relationIncludes.length;e++)ft.checkRelationRead(this._relationIncludes[e]);for(let e=0;e<this._relationExcludes.length;e++)ft.checkRelationRead(this._relationExcludes[e])}forEachRelatedTo(e,t){this._resolver._forEachRelationTargetMatch(e,this._include,this._exclude,this._anyOf,this._sparseInclude,this._sparseExclude,this._includeDisabled,t)}optional(...e){if(e.length===1)return this._optionalOne(e[0].id);let t=this;for(let s=0;s<e.length;s++)t=t._optionalOne(e[s].id);return t}_optionalOne(e){const t=(this._id<<16|e)>>>0,s=this._resolver._optionalSingleCache,n=s.get(t);if(n!==void 0)return n;const r=this._deriveOptional(Ui(this._optional,e));return s.set(t,r),r}_deriveOptional(e){return new Y(this._archetypes,this._defs,this._resolver,this._include,this._exclude,this._anyOf,this._resolver._nextQueryId(),this._sparseInclude,this._sparseExclude,e,this._includeDisabled,this._relationIncludes,this._relationExcludes,this._hierarchy)}includeDisabled(){if(this._includeDisabled)return this;const e=this._resolver._includeDisabledSingleCache,t=e.get(this._id);if(t!==void 0)return t;const s=new Y(this._archetypes,this._defs,this._resolver,this._include,this._exclude,this._anyOf,this._resolver._nextQueryId(),this._sparseInclude,this._sparseExclude,this._optional,!0,this._relationIncludes,this._relationExcludes,this._hierarchy);return e.set(this._id,s),s}forEach(e){if(this._includeDisabled){this._forEachIncludeDisabled(e);return}const t=this._nonEmpty();for(let s=0;s<t.length;s++)e(t[s])}_forEachIncludeDisabled(e){const t=X(!0);try{this._forEachInner(e)}finally{X(t)}}eachChunk(e){if(this._includeDisabled){const t=X(!0);try{this._eachChunkInner(e)}finally{X(t)}return}this._eachChunkInner(e)}_eachChunkInner(e){const t=new vs;t._tick=this._resolver._getCurrentTick();const s=this._nonEmpty();for(let n=0;n<s.length;n++)t._arch=s[n],e(t,s[n].entityCount)}forEachUntil(e){if(this._includeDisabled){const t=X(!0);try{return this._forEachUntilInner(e)}finally{X(t)}}return this._forEachUntilInner(e)}_forEachUntilInner(e){const t=this._nonEmpty();for(let s=0;s<t.length;s++)if(e(t[s]))return!0;return!1}_forEachInner(e){const t=this._nonEmpty();for(let s=0;s<t.length;s++)e(t[s])}forEachEntity(e){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,e);return}this._resolver._forEachSparseMatch(this._include,this._exclude,this._anyOf,this._sparseInclude,this._sparseExclude,this._nonEmpty(),e,this._includeDisabled)}_nonEmpty(){const e=this._resolver._getQueryDirtyEpoch();return this._lastSeenEpoch!==e&&this._rebuildNonEmpty(e),this._nonEmptyArchetypes}_rebuildNonEmpty(e){const t=this._archetypes,s=[];if(this._includeDisabled)for(let n=0;n<t.length;n++)t[n].totalCount>0&&s.push(t[n]);else for(let n=0;n<t.length;n++)t[n].enabledCount>0&&s.push(t[n]);this._nonEmptyArchetypes=s,this._lastSeenEpoch=e}anyOf(...e){if(e.length===1){const s=e[0].id,n=(this._id<<16|s)>>>0,r=this._resolver._anyOfSingleCache.get(n);return r!==void 0?r:this._anyOfMiss(s,n)}let t=this;for(let s=0;s<e.length;s++)t=t.anyOf(e[s]);return t}_anyOfMiss(e,t){const s=this._anyOf?this._anyOf.copy():new U.BitSet;s.set(e);const n=this._carryNondense(this._resolver._resolveQuery(this._include,this._exclude,s,this._defs));return this._resolver._anyOfSingleCache.set(t,n),n}changed(...e){if(e.length===1){const s=e[0].id,n=(this._id<<16|s)>>>0,r=this._resolver._changedSingleCache.get(n);return r!==void 0?r:this._changedMiss(s,n)}const t=new Array(e.length);for(let s=0;s<e.length;s++)t[s]=e[s].id;return new Q(this,t)}_changedMiss(e,t){const s=new Q(this,[e]);return this._resolver._changedSingleCache.set(t,s),s}_ctxLastRunTick(){return this._resolver._getLastRunTick()}}class Rs{constructor(e){this._resolver=e}with(...e){const t=new U.BitSet;for(let s=0;s<e.length;s++)t.set(e[s].id);return this._resolver._resolveQuery(t,null,null,e)}}class Ts{constructor(e){this.store=e}spawn(...e){const t=this.store.createEntity();for(let s=0;s<e.length;s++){const n=ht(e[s]);this.store.addComponentDeferred(t,n,lt(e[s]))}return t}add(e,...t){for(let s=0;s<t.length;s++){const n=ht(t[s]);this.store.addComponentDeferred(e,n,lt(t[s]))}return this}remove(e,t){return this.store.removeComponentDeferred(e,t),this}despawn(e){return this.store.destroyEntityDeferred(e),this}disable(e){return this.store.disableEntityDeferred(e),this}enable(e){return this.store.enableEntityDeferred(e),this}}class Os{constructor(e){this.store=e,this.commands=new Ts(e)}lastRunTick=0;commands;get ecsTick(){return this.store._tick}get _trace(){return this.store._trace}createEntity(){return this.store.createEntity()}isAlive(e){return this.store.isAlive(e)}hasComponent(e,t){return this.store.hasComponent(e,t)}getField(e,t,s){const n=this.store.getEntityArchetype(e),r=this.store.getEntityRow(e);return n.readField(r,t.id,s)}setField(e,t,s,n){const r=this.store.getEntityArchetype(e),o=this.store.getEntityRow(e),a=r.getColumn(t,s,this.store._tick);a[o]=n,this.store._anyDirtyTracked&&this.store._noteSet(t,e)}updateField(e,t,s,n){const r=n(this.getField(e,t,s));return this.setField(e,t,s,r),r}markChanged(e,t){this.store._anyDirtyTracked&&this.store._noteSet(t,e)}ref(e,t){const s=this.store.getEntityArchetype(t),n=this.store.getEntityRow(t);return s._changedTick[e.id]=this.store._tick,qt(s.columnGroups[e.id],n)}refRead(e,t){const s=this.store.getEntityArchetype(t),n=this.store.getEntityRow(t);return qt(s.columnGroups[e.id],n)}destroyEntity(e){return this.store.destroyEntityDeferred(e),this}addComponent(e,t,s){return this.store.addComponentDeferred(e,t,s??re),this}removeComponent(e,t){return this.store.removeComponentDeferred(e,t),this}disable(e){return this.store.disableEntityDeferred(e),this}enable(e){return this.store.enableEntityDeferred(e),this}isDisabled(e){return this.store.isDisabled(e)}addSparse(e,t,s){return this.store.addSparse(e,t,s),this}removeSparse(e,t){return this.store.removeSparse(e,t),this}hasSparse(e,t){return this.store.hasSparse(e,t)}getSparseField(e,t,s){return this.store.getSparseField(e,t,s)}setSparseField(e,t,s,n){this.store.setSparseField(e,t,s,n)}addRelation(e,t,s){return this.store.addRelation(e,t,s),this}removeRelation(e,t,s){return this.store.removeRelation(e,t,s),this}targetOf(e,t){return this.store.targetOf(e,t)}targetsOf(e,t){return this.store.targetsOf(e,t)}sourcesOf(e,t){return this.store.sourcesOf(e,t)}hasRelation(e,t){return this.store.hasRelation(e,t)}flush(){this.store.flushStructural(),this.store.flushDestroyed(),this.store.publishRowCountsToDescriptor()}emit(e,t){const s=this.store.getEventDefByKey(e);t===void 0?this.store.emitSignal(s):this.store.emitEvent(s,t)}read(e){const t=this.store.getEventDefByKey(e);return this.store.getEventReader(t)}resource(e){return this.store.getResource(e)}setResource(e,t){this.store.setResource(e,t)}removeResource(e){this.store.removeResource(e)}hasResource(e){return this.store.hasResource(e)}}class Q{_query;_changedIds;constructor(e,t){this._query=e,this._changedIds=t}and(...e){return new Q(this._query.and(...e),this._changedIds)}without(...e){return new Q(this._query.without(...e),this._changedIds)}anyOf(...e){return new Q(this._query.anyOf(...e),this._changedIds)}optional(...e){return new Q(this._query.optional(...e),this._changedIds)}forEach(e){if(this._query._includeDisabled){this._forEachIncludeDisabled(e);return}const t=this._query._ctxLastRunTick(),s=this._query._nonEmpty(),n=this._changedIds;for(let r=0;r<s.length;r++){const o=s[r];for(let a=0;a<n.length;a++)if(o._changedTick[n[a]]>=t){e(o);break}}}_forEachIncludeDisabled(e){const t=X(!0);try{this._forEachInner(e)}finally{X(t)}}_forEachInner(e){const t=this._query._ctxLastRunTick(),s=this._query._nonEmpty(),n=this._changedIds;for(let r=0;r<s.length;r++){const o=s[r];for(let a=0;a<n.length;a++)if(o._changedTick[n[a]]>=t){e(o);break}}}}const Ge=1024,He=1024*Ge,Qt=64*Ge,de=256*He,wt=3,Ds=64,ks=8,Zt=4*He,Jt=i=>2**Math.ceil(Math.log2(Math.max(1,i))),Ne=i=>2**Math.floor(Math.log2(Math.max(1,i))),he=(i,e,t)=>Math.min(t,Math.max(e,i)),M=i=>i>=He?`${(i/He).toFixed(1)} MiB`:i>=Ge?`${(i/Ge).toFixed(0)} KiB`:`${i} B`;function F(i,e){if(!Number.isInteger(e)||e<=0)throw new A(I.INVALID_MEMORY_OPTIONS,`memory.${i} must be a positive integer (got ${e})`)}function xs(i){const e=["budget","maxBytes","wasm","allocator","heap","shared"].filter(n=>i!==void 0&&i[n]!==void 0);if(e.length>1)throw new A(I.INVALID_MEMORY_OPTIONS,`memory takes at most one of budget | max_bytes | wasm | allocator | heap | shared (got: ${e.join(", ")})`);const t=i?.columnCapacity;if(t!==void 0&&F("column_capacity",t),i?.budget!==void 0){const{entities:n}=i.budget,r=i.budget.archetypes??ks,o=i.budget.bytesPerEntity??Ds;if(F("budget.entities",n),F("budget.archetypes",r),F("budget.bytes_per_entity",o),n>1<<20)throw new A(I.INVALID_MEMORY_OPTIONS,`memory.budget.entities=${n} exceeds the EntityID index space (1<<20 = ${1<<20})`);const a=t??he(Jt(Math.ceil(n/r)),64,1<<20),c=he(Jt(n*2),4096,1<<20),h=c*P,l=n*o*wt,d=Xe(Math.max(h+l,Zt),Qt);return{source:"budget",allocator:B.heapArraybufferAllocator(d),columnCapacity:a,entityIndexCapacity:c,capBytes:d,intentLabel:`budget of ${n} entities`,budgetEntities:n,derivation:[`column_capacity = ${t!==void 0?`${a} (pinned)`:`pow2(${n}/${r} per archetype) = ${a}`}`,`entity_index = pow2(2 × ${n}) = ${c} slots × ${P} B = ${M(h)}`,`columns = ${n} × ${o} B × ${wt} (double+holes headroom) = ${M(l)}`,`cap = align64K(max(index + columns, ${M(Zt)} floor)) = ${M(d)}`],wasmMemory:null}}if(i?.maxBytes!==void 0){F("max_bytes",i.maxBytes);const n=t??q,r=he(Ne(i.maxBytes/4/P),4096,V);return{source:"max_bytes",allocator:B.heapArraybufferAllocator(i.maxBytes),columnCapacity:n,entityIndexCapacity:r,capBytes:i.maxBytes,intentLabel:`explicit cap of ${M(i.maxBytes)}`,budgetEntities:null,derivation:[`cap = ${M(i.maxBytes)} (caller-declared)`,`column_capacity = ${n} (${t!==void 0?"pinned":"default"})`,`entity_index = floor_pow2(cap/4 ÷ ${P} B) = ${r} slots`],wasmMemory:null}}if(i?.wasm!==void 0){const n=i.wasm,r=t??q;if(n.memory!==void 0){if(!(n.memory.buffer instanceof SharedArrayBuffer))throw new A(I.INVALID_MEMORY_OPTIONS,"memory.wasm.memory must be constructed with `shared: true` — the SAB substrate requires a SharedArrayBuffer-backed WebAssembly.Memory (ADR-0004 / ADR-0018)");return{source:"wasm",allocator:B.wasmMemoryAllocator(n.memory),columnCapacity:r,entityIndexCapacity:V,capBytes:null,intentLabel:"caller-supplied WebAssembly.Memory",budgetEntities:null,derivation:["backing = wasm_memory_allocator(memory) — zero-copy with the sim (is_in_place ✓)","cap = the Memory's own `maximum` (declared by the caller; not readable from JS)",`column_capacity = ${r} (${t!==void 0?"pinned":"default"})`],wasmMemory:n.memory}}F("wasm.maximum_pages",n.maximumPages);const o=n.initialPages??Math.min(32,n.maximumPages);if(F("wasm.initial_pages",o),o>n.maximumPages)throw new A(I.INVALID_MEMORY_OPTIONS,`memory.wasm.initial_pages (${o}) exceeds maximum_pages (${n.maximumPages})`);const a=new WebAssembly.Memory({initial:o,maximum:n.maximumPages,shared:!0}),c=n.maximumPages*Qt,h=he(Ne(c/4/P),4096,V);return{source:"wasm",allocator:B.wasmMemoryAllocator(a),columnCapacity:r,entityIndexCapacity:h,capBytes:c,intentLabel:`engine-constructed WebAssembly.Memory (max ${n.maximumPages} pages)`,budgetEntities:null,derivation:[`cap = ${n.maximumPages} pages × 64 KiB = ${M(c)} (Memory maximum)`,`initial = ${o} pages (${n.initialPages!==void 0?"declared":"default"})`,`entity_index = floor_pow2(cap/4 ÷ ${P} B) = ${h} slots`,`column_capacity = ${r} (${t!==void 0?"pinned":"default"})`],wasmMemory:a}}if(i?.allocator!==void 0){if(i.allocator.isInPlace!==!0)throw new A(I.INVALID_MEMORY_OPTIONS,"memory.allocator must declare `is_in_place: true` (ADR-0008): a live Store's flush loops hoist 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 only.");const n=t??q,r=i.capBytesHint;return r!==void 0&&F("cap_bytes_hint",r),{source:"allocator",allocator:i.allocator,columnCapacity:n,entityIndexCapacity:V,capBytes:r??null,intentLabel:r!==void 0?`custom in-place allocator (cap hint ${M(r)})`:"custom in-place allocator",budgetEntities:null,derivation:["backing = caller allocator (is_in_place ✓ checked at construction)",r!==void 0?`cap = ${M(r)} (caller hint — diagnostics only; the allocator owns the real cap)`:"cap = allocator-owned (no hint)",`column_capacity = ${n} (${t!==void 0?"pinned":"default"})`],wasmMemory:null}}if(i?.heap!==void 0){i.heap.maxBytes!==void 0&&F("heap.max_bytes",i.heap.maxBytes);const n=i.heap.maxBytes??de,r=t??q,o=he(Ne(n/4/P),4096,V);return{source:"heap",allocator:B.heapArraybufferAllocator(n),columnCapacity:r,entityIndexCapacity:o,capBytes:n,intentLabel:`pure-TS heap backing (${M(n)} growable cap, no SharedArrayBuffer)`,budgetEntities:null,derivation:[`backing = heap_arraybuffer_allocator(${M(n)}) — resizable ArrayBuffer, no SAB / no COOP+COEP (is_in_place ✓)`,"trade-off: no worker offload / no WASM backend (both need a transferable SharedArrayBuffer)",`column_capacity = ${r} (${t!==void 0?"pinned":"default"})`,`entity_index = floor_pow2(cap/4 ÷ ${P} B) = ${o} slots`],wasmMemory:null}}if(i?.shared!==void 0){i.shared.maxBytes!==void 0&&F("shared.max_bytes",i.shared.maxBytes);const n=i.shared.maxBytes??de,r=t??q,o=he(Ne(n/4/P),4096,V);return{source:"shared",allocator:B.growableSabAllocator(n),columnCapacity:r,entityIndexCapacity:o,capBytes:n,intentLabel:`shared SharedArrayBuffer backing (${M(n)} growable cap, needs COOP/COEP)`,budgetEntities:null,derivation:[`backing = growable_sab_allocator(${M(n)}) — growable SharedArrayBuffer (is_in_place ✓); needs cross-origin isolation`,"enables worker offload + a WASM compute backend (transferable SharedArrayBuffer)",`column_capacity = ${r} (${t!==void 0?"pinned":"default"})`,`entity_index = floor_pow2(cap/4 ÷ ${P} B) = ${o} slots`],wasmMemory:null}}const s=t??q;return{source:"default",allocator:B.heapArraybufferAllocator(),columnCapacity:s,entityIndexCapacity:V,capBytes:de,intentLabel:`default sizing (${M(de)} growable cap)`,budgetEntities:null,derivation:[`cap = ${M(de)} (heap_arraybuffer_allocator default)`,`column_capacity = ${s} (${t!==void 0?"pinned":"DEFAULT_COLUMN_CAPACITY"})`,`entity_index = ${V} slots (full EntityID space, ~12 MiB virtual)`],wasmMemory:null}}function es(i){if(!(i>0)||!Number.isFinite(i))throw new A(I.INVALID_FIXED_TIMESTEP,`fixed_timestep must be a finite number > 0, got ${i}`);return i}function $i(i){if(!Number.isInteger(i)||i<1)throw new A(I.INVALID_MAX_FIXED_STEPS,`max_fixed_steps must be an integer >= 1, got ${i}`);return i}class Bi{store;schedule;ctx;_observers;systems=new Set;nextSystemId=0;_tick=0;_fixedTimestep;_accumulator=0;_maxFixedSteps;queryCache=new Map;scratchMask=new U.BitSet;_nextQueryIdCounter=0;_andSingleCache=new Map;_notSingleCache=new Map;_anyOfSingleCache=new Map;_changedSingleCache=new Map;_withSparseSingleCache=new Map;_withoutSparseSingleCache=new Map;_withRelationSingleCache=new Map;_withoutRelationSingleCache=new Map;_optionalSingleCache=new Map;_includeDisabledSingleCache=new Map;_hierarchySingleCache=new Map;_layoutSubscribers=[];_backend=null;_memory;get memoryPlan(){return this._memory}get wasmMemory(){return this._memory.wasmMemory}constructor(e){const t=Object.prototype.hasOwnProperty;if(e!==void 0&&(t.call(e,"initial_capacity")||t.call(e,"buffer_allocator")))throw new A(I.INVALID_MEMORY_OPTIONS,"ECSOptions.initial_capacity / buffer_allocator were replaced by ECSOptions.memory (#682): initial_capacity → memory.columnCapacity (or memory.budget); buffer_allocator → memory.wasm (WASM-backed) or memory.allocator (custom in-place).");const s=xs(e?.memory);this._memory=s,this.store=new Ci({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:e?.regions,bindingsRegionBytes:e?.bindingsRegionBytes,deterministic:e?.deterministic}),this.schedule=new Ti,this.ctx=new Os(this.store),this._observers=new hi(this.store,this.ctx),this.store._structuralObserverHook=n=>this._observers.dispatchStructural(n),this._fixedTimestep=es(e?.fixedTimestep??Fs),this._maxFixedSteps=$i(e?.maxFixedSteps??Gs)}regionOffset(e){return this.store.regionOffset(e)}regionHandle(e){return this.store.regionHandle(e)}regionHandles(...e){const t=new Array(e.length);let s=null;for(let n=0;n<e.length;n++){const r=this.store.regionHandle(e[n]);r===null?(s??=[]).push(e[n]):t[n]=r}if(s!==null)throw new A(I.REGION_NOT_DECLARED,`region_handles: region id(s) [${s.join(", ")}] not declared — pass them via ECSOptions.regions`);return t}onStoreLayoutPublished(e){return this._layoutSubscribers.push(e),e.setLayout(0),()=>{const t=this._layoutSubscribers.indexOf(e);t>=0&&this._layoutSubscribers.splice(t,1)}}attachBackend(e){this._backend=e,this.schedule.setBackend(e);const t=this.onStoreLayoutPublished(e);return()=>{t(),this._backend===e&&(this._backend=null,this.schedule.setBackend(null))}}fieldId(e,t){return this.store.fieldIdOf(e,t)}entityIdAtRow(e,t){return this.store.entityIdAtRow(e,t)}get fixedTimestep(){return this._fixedTimestep}set fixedTimestep(e){this._fixedTimestep=es(e)}get fixedAlpha(){return this._accumulator/this._fixedTimestep}get columnStore(){return this.store.columnStore}get archetypeCount(){return this.store.archetypeCount}get relationCount(){return this.store.relationCount}get deterministic(){return this.store.deterministic}setTrace(e){}stateHash(){return this.store.stateHash()}snapshotSparse(){return this.store.snapshotSparse()}restoreSparse(e){this.store.restoreSparse(e)}snapshot(){return this.store.snapshot()}restoreInto(e){this.store.restoreInto(e)}registerComponent(e,t){if(Array.isArray(e)){const s=t??"f64",n=Object.create(null);for(const r of e)n[r]=s;return this.store.registerComponent(n)}return this.store.registerComponent(e)}registerTag(){return this.store.registerComponent({})}registerSparseComponent(e,t){if(Array.isArray(e)){const s=t??"f64",n=Object.create(null);for(const r of e)n[r]=s;return this.store.registerSparseComponent(n)}return this.store.registerSparseComponent(e)}registerSparseTag(){return this.store.registerSparseComponent({})}registerEvent(e,t){this.store.registerEventByKey(e,t)}registerSignal(e){this.store.registerEventByKey(e,[])}registerResource(e,t){this.store.registerResource(e,t)}resource(e){return this.store.getResource(e)}setResource(e,t){this.store.setResource(e,t)}removeResource(e){this.store.removeResource(e)}hasResource(e){return this.store.hasResource(e)}createEntity(e,t){return e===void 0?this.store.createEntity():this.store.spawn(e,t)}template(e){return this.store.resolveTemplate(e)}createEntities(e,t){return this.store.spawnMany(e,t)}spawnBundle(...e){const t=this.store.createEntity();for(let s=0;s<e.length;s++){const n=ht(e[s]);this.store.addComponent(t,n,lt(e[s]))}return t}destroyEntity(e){this.store.destroyEntityDeferred(e)}isAlive(e){return this.store.isAlive(e)}get entityCount(){return this.store.entityCount}addComponent(e,t,s){return this.store.addComponent(e,t,s??re),this}addComponents(e,t){this.store.addComponents(e,t)}removeComponent(e,t){return this.store.removeComponent(e,t),this}removeComponents(e,t){this.store.removeComponents(e,t)}hasComponent(e,t){return this.store.hasComponent(e,t)}disable(e){return this.store.disableEntity(e),this}enable(e){return this.store.enableEntity(e),this}isDisabled(e){return this.store.isDisabled(e)}addSparse(e,t,s){return this.store.addSparse(e,t,s),this}removeSparse(e,t){return this.store.removeSparse(e,t),this}hasSparse(e,t){return this.store.hasSparse(e,t)}getSparseField(e,t,s){return this.store.getSparseField(e,t,s)}setSparseField(e,t,s,n){this.store.setSparseField(e,t,s,n)}registerRelation(e){return this.store.registerRelation(e)}addRelation(e,t,s){return this.store.addRelation(e,t,s),this}removeRelation(e,t,s){return this.store.removeRelation(e,t,s),this}targetOf(e,t){return this.store.targetOf(e,t)}targetsOf(e,t){return this.store.targetsOf(e,t)}sourcesOf(e,t){return this.store.sourcesOf(e,t)}hasRelation(e,t){return this.store.hasRelation(e,t)}pairsOf(e){return this.store.pairsOf(e)}sourcesOfAny(e){return this.store.sourcesOfAny(e)}compactRelations(){return this.store.compactRelations()}ancestorsOf(e,t){return this.store.ancestorsOf(e,t)}rootOf(e,t){return this.store.rootOf(e,t)}cascadeOf(e,t){return this.store.cascadeOf(e,t)}batchAddComponent(e,t,s){this.store.batchAddComponent(e,t,s)}batchRemoveComponent(e,t){this.store.batchRemoveComponent(e,t)}getField(e,t,s){const n=this.store.getEntityArchetype(e),r=this.store.getEntityRow(e);return n.readField(r,t.id,s)}setField(e,t,s,n){const r=this.store.getEntityArchetype(e),o=this.store.getEntityRow(e),a=r.getColumn(t,s,this.store._tick);a[o]=n,this.store._anyDirtyTracked&&this.store._noteSet(t,e)}updateField(e,t,s,n){const r=n(this.getField(e,t,s));return this.setField(e,t,s,r),r}emit(e,t){const s=this.store.getEventDefByKey(e);t===void 0?this.store.emitSignal(s):this.store.emitEvent(s,t)}read(e){const t=this.store.getEventDefByKey(e);return this.store.getEventReader(t)}query(...e){const t=this.scratchMask;t._words.fill(0);for(let s=0;s<e.length;s++)t.set(e[s].id);return this._resolveQuery(t.copy(),null,null,e)}_getLastRunTick(){return this.ctx.lastRunTick}_getCurrentTick(){return this.store._tick}_getQueryDirtyEpoch(){return this.store._queryDirtyEpoch}_nextQueryId(){return this._nextQueryIdCounter++}_forEachSparseMatch(e,t,s,n,r,o,a,c){this.store._forEachSparseMatch(e,t,s,n,r,o,a,c)}_relationBackingSparseId(e){return this.store.relationBackingSparseId(e)}_forEachRelationTargetMatch(e,t,s,n,r,o,a,c){this.store._forEachRelationTargetMatch(e,t,s,n,r,o,a,c)}_forEachHierarchyMatch(e,t,s,n,r,o,a,c,h,l){this.store._forEachHierarchyMatch(e,t,s,n,r,o,a,c,h,l)}_resolveQuery(e,t,s,n){const r=e.hash(),o=t?t.hash():0,a=s?s.hash():0,c=r^Math.imul(o,$s)^Math.imul(a,Bs)|0,h=this._findCached(c,e,t,s);if(h!==void 0)return h.query;const l=this.store.registerQuery(e,t??void 0,s??void 0),d=new Y(l,n,this,e.copy(),t?.copy()??null,s?.copy()??null,this._nextQueryIdCounter++);return this.store.updateQueryRef(l,d),ws(this.queryCache,c,{includeMask:e.copy(),excludeMask:t?.copy()??null,anyOfMask:s?.copy()??null,query:d}),d}_findCached(e,t,s,n){const r=this.queryCache.get(e);if(r)for(let o=0;o<r.length;o++){const a=r[o];if(!(!a.includeMask.equals(t)||!(s===null?a.excludeMask===null:a.excludeMask!==null&&a.excludeMask.equals(s))||!(n===null?a.anyOfMask===null:a.anyOfMask!==null&&a.anyOfMask.equals(n))))return a}}registerSystem(e,t){let s;if(typeof e=="function")if(t!==void 0){const o=t(new Rs(this)),a=this.ctx,c=e;s={...gt,fn:(h,l)=>c(o,a,l)}}else s={...gt,fn:e};else s=e;const n=ms(this.nextSystemId++),r=Object.freeze({...s,...ii(s),id:n});return this.systems.add(r),r}addSystems(e,...t){return this.schedule.addSystems(e,...t),this}configureSet(e,t){return this.schedule.configureSet(e,t),this}removeSystem(e){this.schedule.removeSystem(e),e.onRemoved?.(),this.systems.delete(e)}get systemCount(){return this.systems.size}observe(e,t){return this._observers.register(e,t)}startup(){this.prewarmArchetypes();for(const e of this.systems.values())if(e.onAdded!==void 0)try{e.onAdded(this.ctx)}finally{}this.schedule.runStartup(this.ctx,this._tick),this.store.clearEvents()}prewarmArchetypes(){const e=Pi([...this.systems,...this._observers.descriptors()]);e.length!==0&&this.store.archCreateManyFromMasks(e)}update(e){try{if(this.store._tick=this._tick,this.store.publishRowCountsToDescriptor(),this.schedule.hasFixedSystems()){this._accumulator+=e;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,e,this._tick);const t=0;this._observers.dispatchSet(this._tick),this.store.clearEvents(),this._tick++}finally{}}publishArchetypeRowCounts(){this.store.publishRowCountsToDescriptor()}flush(){this.ctx.flush()}dispose(){for(const e of this.systems.values())e.dispose?.(),e.onRemoved?.();this.systems.clear(),this.schedule.clear()}}function Pi(i){const e=new Map,t=[],s=a=>{const c=a.hash(),h=e.get(c);if(h!==void 0){for(let l=0;l<h.length;l++)if(h[l].equals(a))return;h.push(a)}else e.set(c,[a]);t.push(a)},n=a=>{const c=new U.BitSet;for(let h=0;h<a.length;h++)c.set(a[h].id);return c},r=[];for(const a of i){const c=a.transitions;for(let h=0;h<c.length;h++){const l=c[h];r.push({whenHas:n(l.whenHas),add:l.add,remove:l.remove})}}for(const a of i){const c=a.spawns;for(let h=0;h<c.length;h++)s(n(c[h]))}for(;t.length>0;){const a=t.pop();for(let c=0;c<r.length;c++){const h=r[c];if(!a.contains(h.whenHas))continue;const l=a.copy();if(h.add!==void 0)for(let d=0;d<h.add.length;d++)l.set(h.add[d].id);if(h.remove!==void 0)for(let d=0;d<h.remove.length;d++)l.clear(h.remove[d].id);s(l)}}const o=[];for(const a of e.values())for(let c=0;c<a.length;c++)o.push(a[c]);return o}function Fi(i,e){return{name:`run_if_resource_eq(${i.description??"?"})`,resourceReads:[i],evaluate:t=>t.resource(i)===e}}function Gi(i,e=0){const t=(e%i+i)%i;return{name:`run_every_n_ticks(${i}${t!==0?`, +${t}`:""})`,evaluate:s=>(s.ecsTick-t)%i===0}}function Hi(i){return{name:"run_if_any_match",reads:i._defs,evaluate:()=>i.count()>0}}function Vi(i,e){return{def:i,values:e}}function Ve(i,e){switch(e.kind){case"spawn":{const t=i.createEntity();for(const s of e.components)i.addComponent(t,s.def,s.values);return e.onSpawned?.(t),t}case"despawn":i.destroyEntity(e.eid);return;case"add_component":i.addComponent(e.eid,e.def,e.values);return;case"remove_component":i.removeComponent(e.eid,e.def);return;case"set_field":i.setField(e.eid,e.def,e.field,e.value);return;case"disable":i.disable(e.eid);return;case"enable":i.enable(e.eid);return}}class Ms{queued=[];spawn(e,t){this.queued.push({kind:"spawn",components:e,onSpawned:t})}despawn(e){this.queued.push({kind:"despawn",eid:e})}addComponent(e,t,s){this.queued.push({kind:"add_component",eid:e,def:t,values:s})}removeComponent(e,t){this.queued.push({kind:"remove_component",eid:e,def:t})}setField(e,t,s,n){this.queued.push({kind:"set_field",eid:e,def:t,field:s,value:n})}disable(e){this.queued.push({kind:"disable",eid:e})}enable(e){this.queued.push({kind:"enable",eid:e})}push(e){this.queued.push(e)}pending(){return this.queued.length}drain(e,t){const s=this.queued.length;if(s===0)return 0;if(t===void 0)for(let n=0;n<s;n++)Ve(e,this.queued[n]);else for(let n=0;n<s;n++){const r=this.queued[n];t(r),Ve(e,r)}return this.queued.splice(0,s),s}}const Ot=oe-1;function Yi(i){if(i===Ct)throw new W("cannot bind op_code 0 (reserved as the command-ring empty-slot marker)");if(i<0||i>255||!Number.isInteger(i))throw new W(`command op_code must be a u8 in [1, 255] (got ${i})`)}function Qe(i){const e=new Uint8Array(Ot);return new DataView(e.buffer).setUint32(0,i,!0),e}function Ze(i){return new DataView(i.buffer,i.byteOffset,i.byteLength).getUint32(0,!0)}function Wi(i,e){return{encode(t){if(t.kind!=="set_field")throw new W(`ringSetFieldCodec encodes a "set_field" command (got "${t.kind}")`);const s=new Uint8Array(Ot),n=new DataView(s.buffer);return n.setUint32(0,t.eid,!0),n.setFloat64(4,t.value,!0),s},decode(t){const s=new DataView(t.buffer,t.byteOffset,t.byteLength);return{kind:"set_field",eid:s.getUint32(0,!0),def:i,field:e,value:s.getFloat64(4,!0)}}}}function zi(){return{encode(i){if(i.kind!=="despawn")throw new W(`ring_despawn_codec encodes a "despawn" command (got "${i.kind}")`);return Qe(i.eid)},decode:i=>({kind:"despawn",eid:Ze(i)})}}function qi(){return{encode(i){if(i.kind!=="disable")throw new W(`ring_disable_codec encodes a "disable" command (got "${i.kind}")`);return Qe(i.eid)},decode:i=>({kind:"disable",eid:Ze(i)})}}function ji(){return{encode(i){if(i.kind!=="enable")throw new W(`ring_enable_codec encodes an "enable" command (got "${i.kind}")`);return Qe(i.eid)},decode:i=>({kind:"enable",eid:Ze(i)})}}function Xi(i){return{encode(e){if(e.kind!=="remove_component")throw new W(`ringRemoveComponentCodec encodes a "remove_component" command (got "${e.kind}")`);return Qe(e.eid)},decode:e=>({kind:"remove_component",eid:Ze(e),def:i})}}class Ki{appliers=new Map;on(e,t){return Yi(e),this.appliers.set(e,t),this}onCommand(e,t){return this.on(e,(s,n,r)=>{const o=t.decode(n);r?.(o),Ve(s,o)})}drain(e,t,s,n){return an(t,s,(r,o)=>{const a=this.appliers.get(r);a!==void 0&&a(e,o,n)})}}const Qi=new Set([te.PRE_STARTUP,te.STARTUP,te.POST_STARTUP]);function Zi(i,e){const t=new Ms,s=e?.name??"host_command_apply",n=e?.ring,r=e?.recorder,o=r?.record,a=e?.schedules??[te.PRE_STARTUP,te.PRE_UPDATE];if(r!==void 0&&a.includes(te.FIXED_UPDATE))throw new A(I.INVALID_RECORDER_SCHEDULE,"install_host_command_seam: a recorder cannot drain on SCHEDULE.FIXED_UPDATE — it would log the fixed-step dt instead of the host update(dt) and diverge on replay. Use a variable-update phase (PRE_UPDATE/UPDATE/POST_UPDATE).");for(const c of a){const h=!Qi.has(c),l=i.registerSystem({name:`${s}:${c}`,reads:[],writes:[],exclusive:!0,fn:(d,u)=>{if(r!==void 0&&h&&r.openTick(d.ecsTick,u),t.drain(d,o),n!==void 0){const f=i.columnStore,y=f.header.commandRingOff;y!==0&&n.drain(d,f.view,y,o)}}});i.addSystems(c,l)}return t}function Ji(i){return i.kind==="spawn"&&i.onSpawned!==void 0?{kind:"spawn",components:i.components}:i}class er{seed;_startup=[];_ticks=[];sink=this._startup;constructor(e=0){this.seed=e}openTick(e,t){const s=this._ticks[this._ticks.length-1];if(s!==void 0&&s.tick===e){this.sink=s.commands;return}const n=[];this._ticks.push({tick:e,dt:t,commands:n}),this.sink=n}record=e=>{this.sink.push(Ji(e))};log(){return{seed:this.seed,startup:this._startup,ticks:this._ticks}}}const be="__component_def";function tr(i){return JSON.stringify(i,(e,t)=>{if(typeof t=="function"&&"id"in t)return{[be]:t.id};if(t!==null&&typeof t=="object"&&be in t)throw new A(I.COMMAND_LOG_TAG_COLLISION,`Cannot serialize the command log: a value object owns a field named "${be}", the reserved tag the serializer uses for component defs. Rename that component field so the log can round-trip losslessly.`);return t})}function sr(i){return JSON.parse(i,(e,t)=>t!==null&&typeof t=="object"&&be in t?ss(ts(t[be])):t)}function nr(i,e,t,s){for(const o of t.startup)e.push(o);i.startup();const n=s?.hash??i.deterministic,r=[];for(const o of t.ticks){for(const a of o.commands)e.push(a);i.update(o.dt),n&&r.push(i.stateHash())}return{startupCommands:t.startup.length,ticks:t.ticks.length,stateHashes:r}}function at(i){return i.name??`system#${i.id}`}class ir{_frames=[];_current=null;tickBegin(e,t){const s={tick:e,dt:t,events:[]};this._current=s,this._frames.push(s)}tickEnd(e){this._current=null}systemStart(e,t){this._current?.events.push({kind:"system_start",system:at(e),phase:t})}systemEnd(e){this._current?.events.push({kind:"system_end",system:at(e)})}commandQueued(e,t,s){this._current?.events.push({kind:"command_queued",op:e,entity:t,component:s})}flushBegin(e){this._current?.events.push({kind:"flush_begin",phase:e})}flushEnd(e){this._current?.events.push({kind:"flush_end",phase:e})}phaseBoundary(e){}observerFired(e,t,s,n){this._current?.events.push({kind:"observer_fired",op:e,component:t,entity:s,observer:at(n)})}eventEmitted(e){this._current?.events.push({kind:"event_emitted",key:e})}eventRead(e,t){this._current?.events.push({kind:"event_read",key:e,count:t})}frames(){return this._frames}reset(){this._frames.length=0,this._current=null}}function rr(i,e){return i.registerRelation({exclusive:!0,onDeleteTarget:e?.onDeleteTarget??"clear"})}function or(i,e){return i.registerRelation({exclusive:!0,onDeleteTarget:e?.onDeleteTarget??"delete"})}function ar(i){return Symbol(i)}exports.ANY_RELATION=ut;exports.BUDGET_DEFAULT_ARCHETYPES=ks;exports.BUDGET_DEFAULT_BYTES_PER_ENTITY=Ds;exports.BUDGET_GROWTH_HEADROOM=wt;exports.ChangedQuery=Q;exports.ChunkColumns=vs;exports.Commands=Ts;exports.DEFAULT_ECS_CAP_BYTES=de;exports.ECS=Bi;exports.ECSError=A;exports.ECS_ERROR=I;exports.FrameTraceRecorder=ir;exports.HIERARCHY_UNBOUNDED=mt;exports.HOST_COMMAND_PAYLOAD_BYTES=Ot;exports.HostCommandDispatcher=Ki;exports.HostCommandQueue=Ms;exports.HostCommandRecorder=er;exports.MAX_ENTITY_ID=$e;exports.MAX_GENERATION=We;exports.MAX_INDEX=se;exports.MAX_LIVE_GENERATION=Ys;exports.Query=Y;exports.QueryBuilder=Rs;exports.RETIRED_GENERATION=le;exports.SCHEDULE=te;exports.SparseRestoreError=D;exports.SystemContext=Os;exports.WORLD_SNAPSHOT_VERSION=Fe;exports.WorldRestoreError=k;exports.accessCheck=ft;exports.applyHostCommand=Ve;exports.bundle=Ws;exports.createEntityId=ie;exports.deserializeCommandLog=sr;exports.dispatchTrace=Ni;exports.eventKey=Kn;exports.getEntityGeneration=ct;exports.getEntityIndex=C;exports.installHostCommandSeam=Zi;exports.isEcsError=Us;exports.registerChildOf=or;exports.registerIsA=rr;exports.replayCommandLog=nr;exports.resolveECSMemory=xs;exports.resourceKey=ar;exports.ringDespawnCodec=zi;exports.ringDisableCodec=qi;exports.ringEnableCodec=ji;exports.ringRemoveComponentCodec=Xi;exports.ringSetFieldCodec=Wi;exports.runEveryNTicks=Gi;exports.runIfAnyMatch=Hi;exports.runIfResourceEq=Fi;exports.serializeCommandLog=tr;exports.signalKey=Qn;exports.spawnEntry=Vi;exports.systemSet=vi;
|
|
1
|
+
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const h=require("./host_commands-BF8QMi3c.cjs"),T=require("./typed_arrays-D3NmwtCG.cjs"),U=require("./shared-BymrGTyR.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 Ft(c,...t){return{def:c,values:t[0]??ht}}function j(c){return typeof c=="function"?c:c.def}function Y(c){return typeof c=="function"?ht:c.values}class B extends Error{constructor(t){super(t),this.name="StoreRestoreError"}}function Lt(c){const t=c.view.getUint32(h.STORE_HEADER_OFFSETS.capacity,!0);return new Uint8Array(c.buffer,0,t)}function Bt(c,t=U.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 Gt=c=>h.validateAndCast(c);class $t{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 Pt(c){return h.unsafeCast(Symbol(c))}function Ut(c){return h.unsafeCast(Symbol(c))}class Ht{channels=[];dirtyChannels=[];count=0;keyMap=new Map;registerEvent(t){const e=Gt(this.count++),s=new $t(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 Vt{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 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 qt{_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]}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 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}}}}ensureCapacity(t){if(t>this._capacity)throw new q(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 qt(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),$=Object.freeze([]);function dt(c){return typeof c=="object"&&!Array.isArray(c)}function Wt(c){let t=$;c.spawns!==void 0&&c.spawns.length>0&&(t=c.spawns.map(s=>dt(s)?s.defs:s));let e=$;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??$,resourceReads:c.resourceReads??$,resourceWrites:c.resourceWrites??$,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([])}),zt=Symbol.dispose??Symbol.for("Symbol.dispose"),X=(1<<20)-1;let jt=0;function Yt(c,t){const e={...nt,...t,id:bt(jt++),name:c,fn:Kt};return Object.freeze(e)}function Kt(){}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 Xt(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 Qt{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=Yt(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,[zt]: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=Xt(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){z(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),z(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){z(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 z(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 Zt{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;z(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 Jt{_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 te{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 ee(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 se(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 ne(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 re(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 ie(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 Ot(c,t,e,s){const n=c.view.getUint32(h.STORE_HEADER_OFFSETS.view_stamp,!0),r=re(c,e),i=se(c),o=ee(c),a=h.createColumnStore(t,s,o);ie(a,r),ne(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 oe(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(c.buffer.byteLength,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 he(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 oe(c,r,u)}const{store:o,oldViewStamp:a,newViewStamp:l}=Ot(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 ae(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 ce(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}=Ot(c,r,n,e);return{store:i,oldViewStamp:o,newViewStamp:a,viewsPreserved:!1}}function ce(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(c.buffer.byteLength,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 G=4;function le(c){const t=c.freeIndices.length,e=c.archetypeRows.length,s=G*(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+=G};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 ue(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(G);const p=t.getUint32(s,!0);return s+=G,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 de(c,t,e){const s=G*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 fe(c){const t=G*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 pe(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(!_e(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 _e(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 ge{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(Lt(this.host.columnStore())),e=this.snapshotSparse(),s=le(this.collectHostState());return de(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=fe(t),s=ue(e.host);pe(e.dense,this.host.columnStore().archetypes,this.host.entityIndexCapacity()),this.assertSparseSectionMatches(e.sparse);const n=Bt(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 Tt(c,t,e){const s=c.get(t);s!==void 0?s.push(e):c.set(t,[e])}class ye{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),Tt(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 Ee=[],gt=-1,Z=new DataView(new ArrayBuffer(8)),yt=129,me=7,J=-1;class we{entityAllocator;componentMetas=[];componentCount=0;sparseStores=[];sparseNames=[];relationService;events=new Ht;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=he(this._columnStore,{archetypes:a},this._bufferAllocator)}catch(d){throw d instanceof U.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??U.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 te({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 Zt({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 Jt(this._entityIndexCapacity,s.generations,new Uint32Array(this._columnStore.buffer,this._columnStore.header.entityIndexOff+h.ENTITY_INDEX_HEADER_OFFSETS.length,1)),this._snapshots=new ge({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 ye({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=ae(this._columnStore,{newArchetypes:t,existing:e},this._bufferAllocator)}catch(r){throw r instanceof U.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 V;if(F!==h.UNASSIGNED){if(lt)I.moveEntityFromTag(R,F,_,i);else{const Nt=R.getEdge(C);I.moveEntityFrom(R,F,_,Nt.addMap,d,i)}V=A[0]}else V=lt?I.addEntityTag(_,i):I.addEntity(_,i);w.fieldNames.length>0&&I.writeFields(V,C,s[E],d),r[m]=k,i[m]=V,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 Ee;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>me){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 Vt;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 Se{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 Ce{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 Re{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 ve{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 be{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){Tt(this.dedup,t,e)}}const mt=Object.freeze([]),Ie=Object.freeze([]),wt=Object.freeze([]),ot=Number.POSITIVE_INFINITY;function P(c,t){return(c<<16|t)>>>0}function W(c,t){for(let e=0;e<c.length;e++)if(c[e]===t)return c;return[...c,t]}function Ae(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 Dt{_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=Ie,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=P(this._id,t),s=this._resolver._caches.withSparseSingle,n=s.get(e);if(n!==void 0)return n;const r=this._deriveSparse(W(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=P(this._id,t),s=this._resolver._caches.withoutSparseSingle,n=s.get(e);if(n!==void 0)return n;const r=this._deriveSparse(this._sparseInclude,W(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=P(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(W(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=P(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,W(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=P(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(Ae(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 Dt;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 kt{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 xt{constructor(t){this.store=t}spawn(...t){const e=this.store.createEntity();for(let s=0;s<t.length;s++){const n=j(t[s]);this.store.addComponentDeferred(e,n,Y(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=j(n);this.store.addComponentDeferred(t,r,Y(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 Mt{constructor(t){this.store=t,this.commands=new xt(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)}resource(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 Oe(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 Te{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 be;_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 we({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 Se(this.store),this.events=new Ce(this.store),this.resources=new Re(this.store),this.snapshots=new ve(this.store),this.ctx=new Mt(this.store),this._observers=new Qt(this.store,this.ctx),this.store.setStructuralObserverHook(n=>this._observers.dispatchStructural(n)),this._fixedTimestep=Ct(t?.fixedTimestep??h.DEFAULT_FIXED_TIMESTEP),this._maxFixedSteps=Oe(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=j(t[s]);this.store.addComponent(e,n,Y(t[s]))}return e}_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){this.store.destroyEntity(t)}disable(t){return this.store.disableEntity(t),this}enable(t){return this.store.enableEntity(t),this}addComponent(t,e,s){const n=j(e);return this.store.addComponent(t,n,s??Y(e)),this}addComponents(t,e){return this.store.addComponents(t,e),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 kt(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,...Wt(s),id:n});return this.systems.add(r),r}removeSystem(t){this.schedule.removeSystem(t),t.onRemoved?.(),this.systems.delete(t)}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=De([...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()}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({})}template(t){return this.store.resolveTemplate(t)}spawnMany(t,e,s){return this.store.spawnMany(t,e,s)}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 De(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 ke(c,t){return{name:`runIfResourceEq(${c.description??"?"})`,resourceReads:[c],evaluate:e=>e.resource(c)===t}}function xe(c,t=0){const e=(t%c+c)%c;return{name:`runEveryNTicks(${c}${e!==0?`, +${e}`:""})`,evaluate:s=>(s.ecsTick-e)%c===0}}function Me(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 Ne(c){return{name:`not(${c.name})`,...ct([c]),evaluate:t=>!c.evaluate(t)}}function Fe(...c){return{name:`allOf(${c.map(t=>t.name).join(", ")})`,...ct(c),evaluate:t=>c.every(e=>e.evaluate(t))}}function Le(...c){return{name:`anyOf(${c.map(t=>t.name).join(", ")})`,...ct(c),evaluate:t=>c.some(e=>e.evaluate(t))}}function Be(c){return c.kind==="spawn"&&c.onSpawned!==void 0?{kind:"spawn",components:c.components}:c}class Ge{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(Be(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 H="__component_def";function $e(c){return JSON.stringify(c,(t,e)=>{if(typeof e=="function"&&"id"in e)return{[H]:e.id};if(e!==null&&typeof e=="object"&&H 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 "${H}", the reserved tag the serializer uses for component defs. Rename that component field so the log can round-trip losslessly.`);return e})}function Pe(c){return JSON.parse(c,(t,e)=>e!==null&&typeof e=="object"&&H in e?vt(Rt(e[H])):e)}function Ue(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 He{_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 Ve(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 qe{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){Ve(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 We(c,t){return c.relations.register({exclusive:!0,onDeleteTarget:t?.onDeleteTarget??"clear"})}function ze(c,t){return c.relations.register({exclusive:!0,onDeleteTarget:t?.onDeleteTarget??"delete"})}function je(c){return h.unsafeCast(Symbol(c))}const Ye="0.5.0";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=U.SabUnavailableError;exports.ChangedQuery=M;exports.ChunkColumns=Dt;exports.Commands=xt;exports.ECS=Te;exports.ECSRestoreError=b;exports.ECS_SNAPSHOT_VERSION=K;exports.FrameStepper=qe;exports.FrameTraceRecorder=He;exports.HIERARCHY_UNBOUNDED=ot;exports.HostCommandRecorder=Ge;exports.Query=D;exports.QueryBuilder=kt;exports.StoreRestoreError=B;exports.SystemContext=Mt;exports.VERSION=Ye;exports.allOf=Fe;exports.anyOf=Le;exports.bundle=Ft;exports.deserializeCommandLog=Pe;exports.eventKey=Pt;exports.not=Ne;exports.registerChildOf=ze;exports.registerIsA=We;exports.replayCommandLog=Ue;exports.resourceKey=je;exports.runEveryNTicks=xe;exports.runIfAnyMatch=Me;exports.runIfResourceEq=ke;exports.serializeCommandLog=$e;exports.signalKey=Ut;
|