@oasys/oecs 0.3.0 → 0.4.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/README.md +196 -267
- package/dist/array-CxbPyiHO.cjs +1 -0
- package/dist/array-uFR7Q8fU.js +132 -0
- package/dist/core/ecs/access_check.d.ts +77 -0
- package/dist/core/ecs/access_check.d.ts.map +1 -0
- package/dist/core/ecs/archetype.d.ts +474 -0
- package/dist/core/ecs/archetype.d.ts.map +1 -0
- package/dist/core/ecs/builtin_relations.d.ts +43 -0
- package/dist/core/ecs/builtin_relations.d.ts.map +1 -0
- package/dist/core/ecs/command_log.d.ts +113 -0
- package/dist/core/ecs/command_log.d.ts.map +1 -0
- package/dist/core/ecs/component.d.ts +106 -0
- package/dist/core/ecs/component.d.ts.map +1 -0
- package/dist/core/ecs/compute_backend.d.ts +37 -0
- package/dist/core/ecs/compute_backend.d.ts.map +1 -0
- package/dist/core/ecs/dispatch_trace.d.ts +93 -0
- package/dist/core/ecs/dispatch_trace.d.ts.map +1 -0
- package/dist/core/ecs/ecs.d.ts +533 -0
- package/dist/core/ecs/ecs.d.ts.map +1 -0
- package/dist/core/ecs/ecs_memory.d.ts +179 -0
- package/dist/core/ecs/ecs_memory.d.ts.map +1 -0
- package/dist/core/ecs/entity.d.ts +28 -0
- package/dist/core/ecs/entity.d.ts.map +1 -0
- package/dist/core/ecs/event.d.ts +54 -0
- package/dist/core/ecs/event.d.ts.map +1 -0
- package/dist/core/ecs/frame_trace.d.ts +133 -0
- package/dist/core/ecs/frame_trace.d.ts.map +1 -0
- package/dist/core/ecs/host_commands.d.ts +252 -0
- package/dist/core/ecs/host_commands.d.ts.map +1 -0
- package/dist/core/ecs/index.d.ts +41 -0
- package/dist/core/ecs/index.d.ts.map +1 -0
- package/dist/core/ecs/observer.d.ts +142 -0
- package/dist/core/ecs/observer.d.ts.map +1 -0
- package/dist/core/ecs/query.d.ts +557 -0
- package/dist/core/ecs/query.d.ts.map +1 -0
- package/dist/core/ecs/ref.d.ts +31 -0
- package/dist/core/ecs/ref.d.ts.map +1 -0
- package/dist/core/ecs/relation.d.ts +231 -0
- package/dist/core/ecs/relation.d.ts.map +1 -0
- package/dist/core/ecs/resource.d.ts +33 -0
- package/dist/core/ecs/resource.d.ts.map +1 -0
- package/dist/core/ecs/resume.d.ts +85 -0
- package/dist/core/ecs/resume.d.ts.map +1 -0
- package/dist/core/ecs/run_condition.d.ts +75 -0
- package/dist/core/ecs/run_condition.d.ts.map +1 -0
- package/dist/core/ecs/schedule.d.ts +133 -0
- package/dist/core/ecs/schedule.d.ts.map +1 -0
- package/dist/core/ecs/sparse_store.d.ts +107 -0
- package/dist/core/ecs/sparse_store.d.ts.map +1 -0
- package/dist/core/ecs/store.d.ts +1149 -0
- package/dist/core/ecs/store.d.ts.map +1 -0
- package/dist/core/ecs/store_layout_listener.d.ts +23 -0
- package/dist/core/ecs/store_layout_listener.d.ts.map +1 -0
- package/dist/core/ecs/system.d.ts +134 -0
- package/dist/core/ecs/system.d.ts.map +1 -0
- package/dist/core/ecs/utils/arrays.d.ts +7 -0
- package/dist/core/ecs/utils/arrays.d.ts.map +1 -0
- package/dist/core/ecs/utils/constants.d.ts +12 -0
- package/dist/core/ecs/utils/constants.d.ts.map +1 -0
- package/dist/core/ecs/utils/error.d.ts +51 -0
- package/dist/core/ecs/utils/error.d.ts.map +1 -0
- package/dist/core/reactive/array.d.ts +24 -0
- package/dist/core/reactive/array.d.ts.map +1 -0
- package/dist/core/reactive/index.cjs +1 -0
- package/dist/core/reactive/index.d.ts +10 -0
- package/dist/core/reactive/index.d.ts.map +1 -0
- package/dist/core/reactive/index.js +17 -0
- package/dist/core/reactive/interop.d.ts +19 -0
- package/dist/core/reactive/interop.d.ts.map +1 -0
- package/dist/core/reactive/kernel.d.ts +71 -0
- package/dist/core/reactive/kernel.d.ts.map +1 -0
- package/dist/core/reactive/map.d.ts +16 -0
- package/dist/core/reactive/map.d.ts.map +1 -0
- package/dist/core/reactive/struct.d.ts +10 -0
- package/dist/core/reactive/struct.d.ts.map +1 -0
- package/dist/core/store/__generated__/abi.d.ts +43 -0
- package/dist/core/store/__generated__/abi.d.ts.map +1 -0
- package/dist/core/store/action_ring.d.ts +136 -0
- package/dist/core/store/action_ring.d.ts.map +1 -0
- package/dist/core/store/allocator.d.ts +238 -0
- package/dist/core/store/allocator.d.ts.map +1 -0
- package/dist/core/store/buffer_backed_column.d.ts +69 -0
- package/dist/core/store/buffer_backed_column.d.ts.map +1 -0
- package/dist/core/store/column_store.d.ts +265 -0
- package/dist/core/store/column_store.d.ts.map +1 -0
- package/dist/core/store/command_dispatch.d.ts +52 -0
- package/dist/core/store/command_dispatch.d.ts.map +1 -0
- package/dist/core/store/command_ring.d.ts +107 -0
- package/dist/core/store/command_ring.d.ts.map +1 -0
- package/dist/core/store/descriptor.d.ts +80 -0
- package/dist/core/store/descriptor.d.ts.map +1 -0
- package/dist/core/store/entity_index.d.ts +108 -0
- package/dist/core/store/entity_index.d.ts.map +1 -0
- package/dist/core/store/event_ring.d.ts +95 -0
- package/dist/core/store/event_ring.d.ts.map +1 -0
- package/dist/core/store/extend.d.ts +109 -0
- package/dist/core/store/extend.d.ts.map +1 -0
- package/dist/core/store/grow.d.ts +39 -0
- package/dist/core/store/grow.d.ts.map +1 -0
- package/dist/core/store/header.d.ts +64 -0
- package/dist/core/store/header.d.ts.map +1 -0
- package/dist/core/store/index.d.ts +16 -0
- package/dist/core/store/index.d.ts.map +1 -0
- package/dist/core/store/region_table.d.ts +74 -0
- package/dist/core/store/region_table.d.ts.map +1 -0
- package/dist/core/store/snapshot.d.ts +43 -0
- package/dist/core/store/snapshot.d.ts.map +1 -0
- package/dist/core/store/state_hash.d.ts +38 -0
- package/dist/core/store/state_hash.d.ts.map +1 -0
- package/dist/core/store/store_regions.d.ts +38 -0
- package/dist/core/store/store_regions.d.ts.map +1 -0
- package/dist/extensions/editor/editor.d.ts +149 -0
- package/dist/extensions/editor/editor.d.ts.map +1 -0
- package/dist/extensions/editor/field_handle.d.ts +35 -0
- package/dist/extensions/editor/field_handle.d.ts.map +1 -0
- package/dist/extensions/editor/index.cjs +1 -0
- package/dist/extensions/editor/index.d.ts +21 -0
- package/dist/extensions/editor/index.d.ts.map +1 -0
- package/dist/extensions/editor/index.js +209 -0
- package/dist/extensions/reactive/ecs_sync.d.ts +210 -0
- package/dist/extensions/reactive/ecs_sync.d.ts.map +1 -0
- package/dist/extensions/reactive/index.cjs +1 -0
- package/dist/extensions/reactive/index.d.ts +23 -0
- package/dist/extensions/reactive/index.d.ts.map +1 -0
- package/dist/extensions/reactive/index.js +225 -0
- package/dist/extensions/solid/index.cjs +1 -0
- package/dist/extensions/solid/index.d.ts +6 -0
- package/dist/extensions/solid/index.d.ts.map +1 -0
- package/dist/extensions/solid/index.js +32 -0
- package/dist/extensions/solid/kernel_solid.d.ts +42 -0
- package/dist/extensions/solid/kernel_solid.d.ts.map +1 -0
- package/dist/index.cjs +2 -1
- package/dist/index.d.ts +16 -12
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +8563 -1233
- package/dist/interop-CT-REx0W.cjs +1 -0
- package/dist/interop-CcY6ASQc.js +18 -0
- package/dist/kernel-DgyrLFjW.js +227 -0
- package/dist/kernel-yWV3XnAb.cjs +1 -0
- package/dist/log/console_sink.d.ts +4 -0
- package/dist/log/console_sink.d.ts.map +1 -0
- package/dist/log/index.d.ts +3 -0
- package/dist/log/index.d.ts.map +1 -0
- package/dist/log/logger.d.ts +27 -0
- package/dist/log/logger.d.ts.map +1 -0
- package/dist/primitives.cjs +1 -0
- package/dist/primitives.d.ts +18 -0
- package/dist/primitives.d.ts.map +1 -0
- package/dist/primitives.js +44 -0
- package/dist/shared-BXSZnxx4.cjs +1 -0
- package/dist/shared-C678TAPY.js +99 -0
- package/dist/shared.cjs +1 -0
- package/dist/shared.d.ts +22 -0
- package/dist/shared.d.ts.map +1 -0
- package/dist/shared.js +7 -0
- package/dist/topological_sort-DlRpSrxu.js +391 -0
- package/dist/topological_sort-WAT-VHb-.cjs +1 -0
- package/dist/type_primitives/assertions.d.ts +12 -8
- package/dist/type_primitives/assertions.d.ts.map +1 -1
- package/dist/type_primitives/binary_heap/binary_heap.d.ts +6 -2
- package/dist/type_primitives/binary_heap/binary_heap.d.ts.map +1 -1
- package/dist/type_primitives/bitset/bitset.d.ts +16 -4
- package/dist/type_primitives/bitset/bitset.d.ts.map +1 -1
- package/dist/type_primitives/brand.d.ts +6 -1
- package/dist/type_primitives/brand.d.ts.map +1 -1
- package/dist/type_primitives/error.d.ts +4 -0
- package/dist/type_primitives/error.d.ts.map +1 -1
- package/dist/type_primitives/index.d.ts +3 -0
- package/dist/type_primitives/index.d.ts.map +1 -1
- package/dist/type_primitives/sparse_map/sparse_map.d.ts +7 -3
- package/dist/type_primitives/sparse_map/sparse_map.d.ts.map +1 -1
- package/dist/type_primitives/sparse_set/sparse_set.d.ts +4 -0
- package/dist/type_primitives/sparse_set/sparse_set.d.ts.map +1 -1
- package/dist/type_primitives/topological_sort/topological_sort.d.ts +7 -3
- package/dist/type_primitives/topological_sort/topological_sort.d.ts.map +1 -1
- package/dist/type_primitives/typed_arrays/typed_arrays.d.ts +53 -16
- package/dist/type_primitives/typed_arrays/typed_arrays.d.ts.map +1 -1
- package/dist/utils/arrays.d.ts +1 -1
- package/dist/utils/arrays.d.ts.map +1 -1
- package/dist/utils/error.d.ts +2 -20
- package/dist/utils/error.d.ts.map +1 -1
- package/package.json +36 -9
- package/dist/archetype.d.ts +0 -101
- package/dist/archetype.d.ts.map +0 -1
- package/dist/component.d.ts +0 -45
- package/dist/component.d.ts.map +0 -1
- package/dist/ecs.d.ts +0 -104
- package/dist/ecs.d.ts.map +0 -1
- package/dist/entity.d.ts +0 -11
- package/dist/entity.d.ts.map +0 -1
- package/dist/event.d.ts +0 -30
- package/dist/event.d.ts.map +0 -1
- package/dist/query.d.ts +0 -90
- package/dist/query.d.ts.map +0 -1
- package/dist/ref.d.ts +0 -23
- package/dist/ref.d.ts.map +0 -1
- package/dist/resource.d.ts +0 -23
- package/dist/resource.d.ts.map +0 -1
- package/dist/schedule.d.ts +0 -45
- package/dist/schedule.d.ts.map +0 -1
- package/dist/store.d.ts +0 -118
- package/dist/store.d.ts.map +0 -1
- package/dist/system.d.ts +0 -16
- package/dist/system.d.ts.map +0 -1
package/dist/index.cjs
CHANGED
|
@@ -1 +1,2 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});class nt extends Error{constructor(t,e,s){super(t),this.is_operational=e,this.context=s,this.name=this.constructor.name,Error.captureStackTrace(this,this.constructor)}}var D=(a=>(a.EID_MAX_INDEX_OVERFLOW="EID_MAX_INDEX_OVERFLOW",a.EID_MAX_GEN_OVERFLOW="EID_MAX_GEN_OVERFLOW",a.COMPONENT_NOT_REGISTERED="COMPONENT_NOT_REGISTERED",a.ENTITY_NOT_ALIVE="ENTITY_NOT_ALIVE",a.CIRCULAR_SYSTEM_DEPENDENCY="CIRCULAR_SYSTEM_DEPENDENCY",a.DUPLICATE_SYSTEM="DUPLICATE_SYSTEM",a.ARCHETYPE_NOT_FOUND="ARCHETYPE_NOT_FOUND",a.RESOURCE_NOT_REGISTERED="RESOURCE_NOT_REGISTERED",a.RESOURCE_ALREADY_REGISTERED="RESOURCE_ALREADY_REGISTERED",a.EVENT_ALREADY_REGISTERED="EVENT_ALREADY_REGISTERED",a.EVENT_NOT_REGISTERED="EVENT_NOT_REGISTERED",a))(D||{});class O extends nt{constructor(t,e,s){super(e??t,!0,s),this.category=t}}function F(a,t,e){return a}const S=5,I=31,rt=2166136261,it=16777619,_t=4;class k{_words;constructor(t){this._words=t??new Array(_t).fill(0)}has(t){const e=t>>>S;return e>=this._words.length?!1:(this._words[e]&1<<(t&I))!==0}set(t){const e=t>>>S;e>=this._words.length&&this.grow(e+1),this._words[e]|=1<<(t&I)}clear(t){const e=t>>>S;e>=this._words.length||(this._words[e]&=~(1<<(t&I)))}overlaps(t){const e=this._words,s=t._words,n=e.length<s.length?e.length:s.length;for(let r=0;r<n;r++)if((e[r]&s[r])!==0)return!0;return!1}contains(t){const e=t._words,s=this._words,n=s.length;for(let r=0;r<e.length;r++){const i=e[r];if(i!==0&&(r>=n||(s[r]&i)!==i))return!1}return!0}equals(t){const e=this._words,s=t._words,n=e.length>s.length?e.length:s.length;for(let r=0;r<n;r++){const i=r<e.length?e[r]:0,c=r<s.length?s[r]:0;if(i!==c)return!1}return!0}copy(){return new k(this._words.slice())}copy_with_set(t){const e=t>>>S,s=e+1,n=this._words.length>s?this._words.length:s,r=new Array(n).fill(0);for(let i=0;i<this._words.length;i++)r[i]=this._words[i];return r[e]|=1<<(t&I),new k(r)}copy_with_clear(t){const e=this._words.slice(),s=t>>>S;return s<e.length&&(e[s]&=~(1<<(t&I))),new k(e)}hash(){let t=rt;const e=this._words;let s=e.length-1;for(;s>=0&&e[s]===0;)s--;for(let n=0;n<=s;n++)t^=e[n],t=Math.imul(t,it);return t}for_each(t){const e=this._words;for(let s=0;s<e.length;s++){let n=e[s];if(n===0)continue;const r=s<<S;for(;n!==0;){const i=n&-n>>>0,c=I-Math.clz32(i);t(r+c),n^=i}}}grow(t){let e=this._words.length;for(;e<t;)e*=2;const s=new Array(e).fill(0);for(let n=0;n<this._words.length;n++)s[n]=this._words[n];this._words=s}}const b=16,j=2;class A{constructor(t,e=16){this._ctor=t,this._buf=new t(e)}_buf;_len=0;get length(){return this._len}push(t){this._len>=this._buf.length&&this._grow(),this._buf[this._len++]=t}pop(){return this._buf[--this._len]}get(t){return this._buf[t]}set_at(t,e){this._buf[t]=e}swap_remove(t){const e=this._buf[t];return this._buf[t]=this._buf[--this._len],e}clear(){this._len=0}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}}}}ensure_capacity(t){if(t<=this._buf.length)return;let e=this._buf.length||1;for(;e<t;)e*=j;const s=new this._ctor(e);s.set(this._buf.subarray(0,this._len)),this._buf=s}bulk_append(t,e,s){this.ensure_capacity(this._len+s),this._buf.set(t.subarray(e,e+s),this._len),this._len+=s}bulk_append_zeroes(t){this.ensure_capacity(this._len+t),this._buf.fill(0,this._len,this._len+t),this._len+=t}_grow(){const t=new this._ctor(this._buf.length*j);t.set(this._buf),this._buf=t}}class ot extends A{constructor(t=b){super(Float32Array,t)}}class ct extends A{constructor(t=b){super(Float64Array,t)}}class ht extends A{constructor(t=b){super(Int8Array,t)}}class at extends A{constructor(t=b){super(Int16Array,t)}}class lt extends A{constructor(t=b){super(Int32Array,t)}}class dt extends A{constructor(t=b){super(Uint8Array,t)}}class ut extends A{constructor(t=b){super(Uint16Array,t)}}class Q extends A{constructor(t=b){super(Uint32Array,t)}}const ft={f32:ot,f64:ct,i8:ht,i16:at,i32:lt,u8:dt,u16:ut,u32:Q};class gt{_compare;_data=[];constructor(t){this._compare=t}get size(){return this._data.length}peek(){return this._data[0]}push(t){this._data.push(t),this._sift_up(this._data.length-1)}pop(){const t=this._data;if(t.length===0)return;const s=t[0],n=t.pop();return t.length>0&&(t[0]=n,this._sift_down(0)),s}clear(){this._data.length=0}_sift_up(t){const e=this._data,s=this._compare,n=e[t];for(;t>0;){const r=t-1>>1;if(s(n,e[r])>=0)break;e[t]=e[r],t=r}e[t]=n}_sift_down(t){const e=this._data,s=this._compare,n=e.length,r=n>>1,i=e[t];for(;t<r;){let c=(t<<1)+1;const o=c+1;if(o<n&&s(e[o],e[c])<0&&(c=o),s(e[c],i)>=0)break;e[t]=e[c],t=c}e[t]=i}}function yt(a,t,e,s){const n=s??(o=>String(o)),r=new Map;for(let o=0;o<a.length;o++)r.set(a[o],0);for(const[,o]of t)for(let _=0;_<o.length;_++){const h=o[_];r.has(h)&&r.set(h,r.get(h)+1)}const i=new gt(e);for(let o=0;o<a.length;o++)r.get(a[o])===0&&i.push(a[o]);const c=[];for(;i.size>0;){const o=i.pop();c.push(o);const _=t.get(o);if(_!==void 0)for(let h=0;h<_.length;h++){const l=_[h];if(!r.has(l))continue;const d=r.get(l)-1;r.set(l,d),d===0&&i.push(l)}}if(c.length!==a.length){const o=[];for(const[_,h]of r)h>0&&o.push(n(_));throw new globalThis.TypeError(`Cycle detected in topological sort. Nodes still pending: ${o.join(", ")}`)}return c}const E=-1,m=-1,U=Object.freeze(Object.create(null)),mt=2654435769,pt=1367130551,H=1024,X=0,wt=31,vt=1/60,Et=4,kt=0,R=20,G=(1<<R)-1,Tt=wt-R,V=(1<<Tt)-1,bt=(a,t)=>t<<R|a,y=a=>a&G,z=a=>a>>R,At=a=>F(a),xt=a=>F(a);class St{field_names;columns;reader;constructor(t){this.field_names=t,this.columns=[];for(let s=0;s<t.length;s++)this.columns.push([]);const e={length:0};for(let s=0;s<t.length;s++)e[t[s]]=this.columns[s];this.reader=e}emit(t){const e=this.field_names,s=this.columns;for(let n=0;n<e.length;n++)s[n].push(t[e[n]]);this.reader.length++}emit_signal(){this.reader.length++}clear(){this.reader.length=0;const t=this.columns;for(let e=0;e<t.length;e++)t[e].length=0}}function It(a){return Symbol(a)}function Dt(a){return Symbol(a)}const Rt=a=>F(a);class Nt{id;mask;has_columns;_entity_ids;length=0;edges=[];_flat_columns=[];_col_offset=[];_field_count=[];_field_index=[];_field_names=[];column_groups=[];_column_ids=[];_changed_tick=[];constructor(t,e,s,n=H){if(this.id=t,this.mask=e,this._entity_ids=new Q(n),s){let r=0;for(let i=0;i<s.length;i++){const c=s[i],o=c.component_id,_=new Array(c.field_names.length);this._col_offset[o]=r,this._field_count[o]=c.field_names.length,this._field_index[o]=c.field_index,this._field_names[o]=c.field_names;for(let h=0;h<c.field_names.length;h++){const l=new ft[c.field_types[h]](n);_[h]=l,this._flat_columns[r++]=l}this.column_groups[o]={layout:c,columns:_},this._column_ids.push(o),this._changed_tick[o]=0}}this.has_columns=this._column_ids.length>0}get entity_count(){return this.length}get entity_ids(){return this._entity_ids.buf}get entity_list(){return this._entity_ids.view()}has_component(t){return this.mask.has(t)}matches(t){return this.mask.contains(t)}get_column(t,e){const s=t,n=this._field_index[s][e];return this._flat_columns[this._col_offset[s]+n].buf}get_column_mut(t,e,s){const n=t;this._changed_tick[n]=s;const r=this._field_index[n][e];return this._flat_columns[this._col_offset[n]+r].buf}write_fields(t,e,s,n){const r=e,i=this._col_offset[r];if(i===void 0)return;this._changed_tick[r]=n;const c=this._field_names[r],o=this._flat_columns;for(let _=0;_<c.length;_++)o[i+_].buf[t]=s[c[_]]}write_fields_positional(t,e,s,n){const r=e,i=this._col_offset[r];if(i===void 0)return;this._changed_tick[r]=n;const c=this._flat_columns;for(let o=0;o<s.length;o++)c[i+o].buf[t]=s[o]}read_field(t,e,s){const n=e,r=this._col_offset[n];if(r===void 0)return NaN;const i=this._field_index[n][s];return i===void 0?NaN:this._flat_columns[r+i].buf[t]}copy_shared_from(t,e,s,n){const r=t._col_offset,i=t._field_count,c=t._flat_columns,o=this._flat_columns,_=this._column_ids;for(let h=0;h<_.length;h++){const l=_[h],d=r[l];if(d===void 0)continue;this._changed_tick[l]=n;const u=this._col_offset[l],g=i[l];for(let p=0;p<g;p++)o[u+p].buf[s]=c[d+p].buf[e]}}add_entity(t){const e=this.length;this._entity_ids.push(t);const s=this._flat_columns;for(let n=0;n<s.length;n++)s[n].push(0);return this.length++,e}remove_entity(t){const e=this.length-1;let s=m;const n=this._flat_columns,r=this._entity_ids.buf;if(t!==e){r[t]=r[e],s=y(r[t]);for(let i=0;i<n.length;i++)n[i].swap_remove(t)}else for(let i=0;i<n.length;i++)n[i].pop();return this._entity_ids.pop(),this.length--,s}add_entity_tag(t){const e=this.length;return this._entity_ids.push(t),this.length++,e}remove_entity_tag(t){const e=this.length-1;let s=m;const n=this._entity_ids.buf;return t!==e&&(n[t]=n[e],s=y(n[t])),this._entity_ids.pop(),this.length--,s}move_entity_from(t,e,s,n,r){const i=this.length;this._entity_ids.push(s);const c=this._flat_columns,o=t._flat_columns;for(let l=0;l<c.length;l++){const d=n[l];c[l].push(d>=0?o[d].buf[e]:0)}const _=this._column_ids;for(let l=0;l<_.length;l++)this._changed_tick[_[l]]=r;this.length++;const h=t.has_columns?t.remove_entity(e):t.remove_entity_tag(e);f[0]=i,f[1]=h}move_entity_from_tag(t,e,s){const n=this.length;this._entity_ids.push(s),this.length++;const r=t.remove_entity_tag(e);f[0]=n,f[1]=r}bulk_move_all_from(t,e,s){const n=t.length;if(n===0)return this.length;const r=this.length,i=this._flat_columns,c=t._flat_columns;this._entity_ids.bulk_append(t._entity_ids.buf,0,n);for(let _=0;_<i.length;_++){const h=e[_];h>=0?i[_].bulk_append(c[h].buf,0,n):i[_].bulk_append_zeroes(n)}const o=this._column_ids;for(let _=0;_<o.length;_++)this._changed_tick[o[_]]=s;this.length+=n,t.length=0,t._entity_ids.clear();for(let _=0;_<c.length;_++)c[_].clear();return r}get_edge(t){return this.edges[t]}set_edge(t,e){this.edges[t]=e}}const f=[0,m];function M(a,t){const e=t._flat_columns,s=new Int16Array(e.length),n=t._column_ids,r=a._col_offset,i=t._col_offset,c=t._field_count;for(let o=0;o<n.length;o++){const _=n[o],h=i[_],l=c[_],d=r[_];if(d!==void 0)for(let u=0;u<l;u++)s[h+u]=d+u;else for(let u=0;u<l;u++)s[h+u]=-1}return s}function $(a,t,e){const s=a.get(t);s!==void 0?s.push(e):a.set(t,[e])}class Pt{entity_generations=[];entity_high_water=0;entity_free_indices=[];entity_alive_count=0;component_metas=[];component_count=0;event_channels=[];event_count=0;archetypes=[];archetype_map=new Map;next_archetype_id=0;component_index=new Map;registered_queries=[];empty_archetype_id;entity_archetype=[];entity_row=[];pending_destroy=[];pending_add_ids=[];pending_add_defs=[];pending_add_values=[];pending_remove_ids=[];pending_remove_defs=[];_tick=0;initial_capacity;constructor(t){this.initial_capacity=t??H,this.empty_archetype_id=this.arch_get_or_create_from_mask(new k)}arch_get(t){return this.archetypes[t]}arch_get_or_create_from_mask(t){const e=t.hash(),s=this.archetype_map.get(e);if(s!==void 0){for(let o=0;o<s.length;o++)if(this.archetypes[s[o]].mask.equals(t))return s[o]}const n=Rt(this.next_archetype_id++),r=[];t.for_each(o=>{const _=o,h=this.component_metas[_];h&&h.field_names.length>0&&r.push({component_id:_,field_names:h.field_names,field_index:h.field_index,field_types:h.field_types})});const i=new Nt(n,t,r,this.initial_capacity);this.archetypes.push(i),$(this.archetype_map,e,n),t.for_each(o=>{const _=o;let h=this.component_index.get(_);h||(h=new Set,this.component_index.set(_,h)),h.add(n)});const c=this.registered_queries;for(let o=0;o<c.length;o++){const _=c[o];i.matches(_.include_mask)&&(!_.exclude_mask||!i.mask.overlaps(_.exclude_mask))&&(!_.any_of_mask||i.mask.overlaps(_.any_of_mask))&&(_.result.push(i),_.query?.mark_non_empty_dirty())}return n}arch_resolve_add(t,e){const s=this.arch_get(t);if(s.mask.has(e))return t;const n=s.get_edge(e);if(n?.add!=null)return n.add;const r=this.arch_get_or_create_from_mask(s.mask.copy_with_set(e));return this.arch_cache_edge(s,this.arch_get(r),e),r}arch_resolve_remove(t,e){const s=this.arch_get(t);if(!s.mask.has(e))return t;const n=s.get_edge(e);if(n?.remove!=null)return n.remove;const r=this.arch_get_or_create_from_mask(s.mask.copy_with_clear(e));return this.arch_cache_edge(this.arch_get(r),s,e),r}arch_cache_edge(t,e,s){const n=t.get_edge(s)??{add:null,remove:null,add_map:null,remove_map:null};n.add=e.id,n.add_map=M(t,e),t.set_edge(s,n);const r=e.get_edge(s)??{add:null,remove:null,add_map:null,remove_map:null};r.remove=t.id,r.remove_map=M(e,t),e.set_edge(s,r)}create_entity(){let t,e;this.entity_free_indices.length>0?(t=this.entity_free_indices.pop(),e=this.entity_generations[t]):(t=this.entity_high_water++,this.entity_generations[t]=X,e=X),this.entity_alive_count++;const s=bt(t,e);return this.entity_archetype[t]=this.empty_archetype_id,this.entity_row[t]=E,s}destroy_entity(t){if(!this.is_alive(t))return;const e=y(t),s=this.entity_row[e];if(s!==E){const i=this.arch_get(this.entity_archetype[e]).remove_entity(s);i!==m&&(this.entity_row[i]=s)}this.entity_archetype[e]=E,this.entity_row[e]=E;const n=z(t);this.entity_generations[e]=n+1&V,this.entity_free_indices.push(e),this.entity_alive_count--}is_alive(t){const e=y(t);return e<this.entity_high_water&&this.entity_generations[e]===z(t)}get entity_count(){return this.entity_alive_count}_mark_queries_dirty(){const t=this.registered_queries;for(let e=0;e<t.length;e++)t[e].query?.mark_non_empty_dirty()}destroy_entity_deferred(t){this.pending_destroy.push(t)}flush_destroyed(){const t=this.pending_destroy;if(t.length===0)return;const e=this.entity_archetype,s=this.entity_row,n=this.entity_generations,r=this.archetypes,i=this.entity_high_water;for(let c=0;c<t.length;c++){const o=t[c],_=o&G,h=o>>R;if(_>=i||n[_]!==h)continue;const l=s[_];if(l!==E){const d=r[e[_]],u=d.has_columns?d.remove_entity(l):d.remove_entity_tag(l);u!==m&&(s[u]=l)}e[_]=E,s[_]=E,n[_]=h+1&V,this.entity_free_indices.push(_),this.entity_alive_count--}t.length=0,this._mark_queries_dirty()}get pending_destroy_count(){return this.pending_destroy.length}add_component_deferred(t,e,s){this.pending_add_ids.push(t),this.pending_add_defs.push(e),this.pending_add_values.push(s??U)}remove_component_deferred(t,e){this.pending_remove_ids.push(t),this.pending_remove_defs.push(e)}flush_structural(){const t=this.pending_add_ids.length>0,e=this.pending_remove_ids.length>0;t&&this._flush_adds(),e&&this._flush_removes(),(t||e)&&this._mark_queries_dirty()}_flush_adds(){const t=this.pending_add_ids,e=this.pending_add_defs,s=this.pending_add_values,n=t.length,r=this.entity_archetype,i=this.entity_row,c=this.entity_generations,o=this.archetypes,_=this.component_metas,h=this.entity_high_water,l=this._tick;for(let d=0;d<n;d++){const u=t[d],g=u&G,p=u>>R;if(g>=h||c[g]!==p)continue;const T=r[g],w=e[d],v=o[T];if(v.mask.has(w)){_[w].field_names.length>0&&v.write_fields(i[g],w,s[d],l);continue}const N=this.arch_resolve_add(T,w),x=o[N],P=i[g],Y=!x.has_columns&&!v.has_columns;let q;if(P!==E){if(Y)x.move_entity_from_tag(v,P,u);else{const st=v.get_edge(w);x.move_entity_from(v,P,u,st.add_map,l)}q=f[0],f[1]!==m&&(i[f[1]]=P)}else q=Y?x.add_entity_tag(u):x.add_entity(u);_[w].field_names.length>0&&x.write_fields(q,w,s[d],l),r[g]=N,i[g]=q}t.length=0,e.length=0,s.length=0}_flush_removes(){const t=this.pending_remove_ids,e=this.pending_remove_defs,s=t.length,n=this.entity_archetype,r=this.entity_row,i=this.entity_generations,c=this.archetypes,o=this.entity_high_water,_=this._tick;for(let h=0;h<s;h++){const l=t[h],d=l&G,u=l>>R;if(d>=o||i[d]!==u)continue;const g=n[d],p=e[h],T=c[g];if(!T.mask.has(p))continue;const w=this.arch_resolve_remove(g,p),v=c[w],N=r[d];if(!v.has_columns&&!T.has_columns)v.move_entity_from_tag(T,N,l);else{const P=T.get_edge(p);v.move_entity_from(T,N,l,P.remove_map,_)}f[1]!==m&&(r[f[1]]=N),n[d]=w,r[d]=f[0]}t.length=0,e.length=0}get pending_structural_count(){return this.pending_add_ids.length+this.pending_remove_ids.length}register_component(t){const e=At(this.component_count++),s=Object.keys(t),n=new Array(s.length),r=Object.create(null);for(let i=0;i<s.length;i++)r[s[i]]=i,n[i]=t[s[i]];return this.component_metas.push({field_names:s,field_index:r,field_types:n}),e}add_component(t,e,s){if(!this.is_alive(t))return;const n=y(t),r=this.entity_archetype[n],i=this.arch_get(r);if(i.has_component(e)){i.write_fields(this.entity_row[n],e,s,this._tick);return}const c=this.arch_resolve_add(r,e),o=this.arch_get(c),_=this.entity_row[n];let h;if(_!==E){const l=i.get_edge(e);!o.has_columns&&!i.has_columns?o.move_entity_from_tag(i,_,t):o.move_entity_from(i,_,t,l.add_map,this._tick),h=f[0],f[1]!==m&&(this.entity_row[f[1]]=_)}else h=o.has_columns?o.add_entity(t):o.add_entity_tag(t);o.write_fields(h,e,s,this._tick),this.entity_archetype[n]=c,this.entity_row[n]=h,this._mark_queries_dirty()}add_components(t,e){if(!this.is_alive(t))return;const s=y(t),n=this.entity_archetype[s];let r=n;for(let i=0;i<e.length;i++)r=this.arch_resolve_add(r,e[i].def);if(r!==n){const i=this.arch_get(n),c=this.arch_get(r),o=this.entity_row[s];let _;if(o!==E){const h=M(i,c);c.move_entity_from(i,o,t,h,this._tick),_=f[0],f[1]!==m&&(this.entity_row[f[1]]=o)}else _=c.add_entity(t);for(let h=0;h<e.length;h++)c.write_fields(_,e[h].def,e[h].values??U,this._tick);this.entity_archetype[s]=r,this.entity_row[s]=_,this._mark_queries_dirty()}else{const i=this.arch_get(n),c=this.entity_row[s];for(let o=0;o<e.length;o++)i.write_fields(c,e[o].def,e[o].values??U,this._tick)}}remove_component(t,e){if(!this.is_alive(t))return;const s=y(t),n=this.entity_archetype[s],r=this.arch_get(n);if(!r.has_component(e))return;const i=this.arch_resolve_remove(n,e),c=this.arch_get(i),o=this.entity_row[s],_=r.get_edge(e);!c.has_columns&&!r.has_columns?c.move_entity_from_tag(r,o,t):c.move_entity_from(r,o,t,_.remove_map,this._tick),f[1]!==m&&(this.entity_row[f[1]]=o),this.entity_archetype[s]=i,this.entity_row[s]=f[0],this._mark_queries_dirty()}remove_components(t,e){if(!this.is_alive(t))return;const s=y(t),n=this.entity_archetype[s];let r=n;for(let h=0;h<e.length;h++)r=this.arch_resolve_remove(r,e[h]);if(r===n)return;const i=this.arch_get(n),c=this.arch_get(r),o=this.entity_row[s],_=M(i,c);c.move_entity_from(i,o,t,_,this._tick),f[1]!==m&&(this.entity_row[f[1]]=o),this.entity_archetype[s]=r,this.entity_row[s]=f[0],this._mark_queries_dirty()}has_component(t,e){if(!this.is_alive(t))return!1;const s=y(t);return this.arch_get(this.entity_archetype[s]).has_component(e)}batch_add_component(t,e,s){if(t.length===0)return;const n=e;if(t.mask.has(n))return;const r=this.arch_resolve_add(t.id,n),i=this.arch_get(r),c=t.get_edge(n),o=t.length,_=this.entity_archetype,h=this.entity_row,l=i.bulk_move_all_from(t,c.add_map,this._tick);for(let u=0;u<o;u++){const g=y(i.entity_ids[l+u]);_[g]=r,h[g]=l+u}if(this.component_metas[n].field_names.length>0&&s)for(let u=0;u<o;u++)i.write_fields(l+u,n,s,this._tick);this._mark_queries_dirty()}batch_remove_component(t,e){if(t.length===0)return;const s=e;if(!t.mask.has(s))return;const n=this.arch_resolve_remove(t.id,s),r=this.arch_get(n),i=t.get_edge(s),c=t.length,o=r.bulk_move_all_from(t,i.remove_map,this._tick),_=this.entity_archetype,h=this.entity_row;for(let l=0;l<c;l++){const d=y(r.entity_ids[o+l]);_[d]=n,h[d]=o+l}this._mark_queries_dirty()}get_entity_archetype(t){return this.arch_get(this.entity_archetype[y(t)])}get_entity_row(t){return this.entity_row[y(t)]}get_matching_archetypes(t,e,s){const n=t._words;let r=!1;for(let _=0;_<n.length;_++)if(n[_]!==0){r=!0;break}if(!r)return this.archetypes.filter(_=>(!e||!_.mask.overlaps(e))&&(!s||_.mask.overlaps(s)));let i,c=!1;for(let _=0;_<n.length;_++){let h=n[_];if(h===0)continue;const l=_<<S;for(;h!==0;){const d=h&-h>>>0,u=l+(I-Math.clz32(d));h^=d;const g=this.component_index.get(u);if(!g||g.size===0){c=!0;break}(!i||g.size<i.size)&&(i=g)}if(c)break}if(c||!i)return[];const o=[];for(const _ of i){const h=this.arch_get(_);h.matches(t)&&(!e||!h.mask.overlaps(e))&&(!s||h.mask.overlaps(s))&&o.push(h)}return o}register_query(t,e,s){const n=this.get_matching_archetypes(t,e,s);return this.registered_queries.push({include_mask:t.copy(),exclude_mask:e?e.copy():null,any_of_mask:s?s.copy():null,result:n,query:null}),n}update_query_ref(t,e){const s=this.registered_queries;for(let n=0;n<s.length;n++)if(s[n].result===t){s[n].query=e;return}}get archetype_count(){return this.archetypes.length}register_event(t){const e=xt(this.event_count++),s=new St(t);return this.event_channels.push(s),e}emit_event(t,e){this.event_channels[t].emit(e)}emit_signal(t){this.event_channels[t].emit_signal()}get_event_reader(t){return this.event_channels[t].reader}clear_events(){const t=this.event_channels;for(let e=0;e<t.length;e++)t[e].clear()}event_key_map=new Map;register_event_by_key(t,e){if(this.event_key_map.has(t))throw new O(D.EVENT_ALREADY_REGISTERED,"Event key already registered");const s=this.register_event(e);return this.event_key_map.set(t,s),s}get_event_def_by_key(t){const e=this.event_key_map.get(t);if(e===void 0)throw new O(D.EVENT_NOT_REGISTERED,"Event key not registered");return e}has_event_key(t){return this.event_key_map.has(t)}resource_key_map=new Map;register_resource(t,e){if(this.resource_key_map.has(t))throw new O(D.RESOURCE_ALREADY_REGISTERED,"Resource key already registered");this.resource_key_map.set(t,e)}get_resource(t){if(!this.resource_key_map.has(t))throw new O(D.RESOURCE_NOT_REGISTERED,"Resource key not registered");return this.resource_key_map.get(t)}set_resource(t,e){if(!this.resource_key_map.has(t))throw new O(D.RESOURCE_NOT_REGISTERED,"Resource key not registered");this.resource_key_map.set(t,e)}has_resource(t){return this.resource_key_map.has(t)}}var K=(a=>(a.PRE_STARTUP="PRE_STARTUP",a.STARTUP="STARTUP",a.POST_STARTUP="POST_STARTUP",a.FIXED_UPDATE="FIXED_UPDATE",a.PRE_UPDATE="PRE_UPDATE",a.UPDATE="UPDATE",a.POST_UPDATE="POST_UPDATE",a))(K||{});const L=["PRE_STARTUP","STARTUP","POST_STARTUP"],C=["PRE_UPDATE","UPDATE","POST_UPDATE"];class Ot{label_systems=new Map;sorted_cache=new Map;system_index=new Map;system_last_run=new Map;next_insertion_order=0;constructor(){for(let t=0;t<L.length;t++)this.label_systems.set(L[t],[]);this.label_systems.set("FIXED_UPDATE",[]);for(let t=0;t<C.length;t++)this.label_systems.set(C[t],[])}add_systems(t,...e){for(const s of e){const n="system"in s?s.system:s,r="system"in s?s.ordering:void 0,i={descriptor:n,insertion_order:this.next_insertion_order++,before:new Set(r?.before??[]),after:new Set(r?.after??[])};this.label_systems.get(t).push(i),this.system_index.set(n,t),this.system_last_run.set(n,0),this.sorted_cache.delete(t)}}remove_system(t){const e=this.system_index.get(t);if(e===void 0)return;const s=this.label_systems.get(e),n=s.findIndex(r=>r.descriptor===t);if(n!==-1){const r=s.length-1;n!==r&&(s[n]=s[r]),s.pop();for(const i of s)i.before.delete(t),i.after.delete(t)}this.system_index.delete(t),this.system_last_run.delete(t),this.sorted_cache.delete(e)}run_startup(t,e){for(const s of L)this.run_label(s,t,kt,e)}run_update(t,e,s){for(const n of C)this.run_label(n,t,e,s)}run_fixed_update(t,e,s){this.run_label("FIXED_UPDATE",t,e,s)}has_fixed_systems(){return this.label_systems.get("FIXED_UPDATE").length>0}get_all_systems(){const t=[];for(const e of this.label_systems.values())for(const s of e)t.push(s.descriptor);return t}has_system(t){return this.system_index.has(t)}clear(){for(const t of this.label_systems.values())t.length=0;this.sorted_cache.clear(),this.system_index.clear(),this.system_last_run.clear()}run_label(t,e,s,n){const r=this.get_sorted(t);for(let i=0;i<r.length;i++)this.system_last_run.set(r[i],n),e.last_run_tick=n,r[i].fn(e,s);e.flush()}get_sorted(t){const e=this.sorted_cache.get(t);if(e!==void 0)return e;const s=this.label_systems.get(t),n=this.sort_systems(s,t);return this.sorted_cache.set(t,n),n}sort_systems(t,e){if(t.length===0)return[];const s=[],n=new Map,r=new Set;for(const _ of t)s.push(_.descriptor),n.set(_.descriptor,_.insertion_order),r.add(_.descriptor);const i=new Map;for(const _ of t)i.set(_.descriptor,[]);for(const _ of t){for(const h of _.before)r.has(h)&&i.get(_.descriptor).push(h);for(const h of _.after)r.has(h)&&i.get(h).push(_.descriptor)}const c=(_,h)=>n.get(_)-n.get(h),o=_=>_.name??`system_${_.id}`;try{return yt(s,i,c,o)}catch(_){throw _ instanceof TypeError?new O(D.CIRCULAR_SYSTEM_DEPENDENCY,`Circular system dependency detected in ${e}: ${_.message}`):_}}}const W=new WeakMap;function B(a,t){let e=W.get(a);if(!e){e=Object.create(null);const{field_names:r}=a.layout;for(let i=0;i<r.length;i++){const c=i;Object.defineProperty(e,r[i],{get(){return this._columns[c][this._row]},set(o){this._columns[c][this._row]=o},enumerable:!0,configurable:!1})}W.set(a,e)}const s=Object.create(e),n=new Array(a.columns.length);for(let r=0;r<a.columns.length;r++)n[r]=a.columns[r].buf;return s._columns=n,s._row=t,s}class J{_archetypes;_defs;_resolver;_include;_exclude;_any_of;_non_empty_archetypes=[];_non_empty_dirty=!0;constructor(t,e,s,n,r,i){this._archetypes=t,this._defs=e,this._resolver=s,this._include=n,this._exclude=r,this._any_of=i}get archetype_count(){return this._archetypes.length}count(){const t=this._archetypes;let e=0;for(let s=0;s<t.length;s++)e+=t[s].entity_count;return e}get archetypes(){return this._archetypes}and(...t){const e=this._include.copy(),s=this._defs.slice();for(let n=0;n<t.length;n++)e.has(t[n])||(e.set(t[n]),s.push(t[n]));return this._resolver._resolve_query(e,this._exclude,this._any_of,s)}not(...t){const e=this._exclude?this._exclude.copy():new k;for(let s=0;s<t.length;s++)e.set(t[s]);return this._resolver._resolve_query(this._include,e,this._any_of,this._defs)}for_each(t){const e=this._non_empty();for(let s=0;s<e.length;s++)t(e[s])}mark_non_empty_dirty(){this._non_empty_dirty=!0}_non_empty(){if(this._non_empty_dirty){const t=this._archetypes,e=this._non_empty_archetypes;e.length=0;for(let s=0;s<t.length;s++)t[s].entity_count>0&&e.push(t[s]);this._non_empty_dirty=!1}return this._non_empty_archetypes}any_of(...t){const e=this._any_of?this._any_of.copy():new k;for(let s=0;s<t.length;s++)e.set(t[s]);return this._resolver._resolve_query(this._include,this._exclude,e,this._defs)}changed(...t){const e=new Array(t.length);for(let s=0;s<t.length;s++)e[s]=t[s];return new et(this,e)}_ctx_last_run_tick(){return this._resolver._get_last_run_tick()}}class Z{constructor(t){this._resolver=t}every(...t){const e=new k;for(let s=0;s<t.length;s++)e.set(t[s]);return this._resolver._resolve_query(e,null,null,t)}}class tt{store;last_run_tick=0;get world_tick(){return this.store._tick}constructor(t){this.store=t}create_entity(){return this.store.create_entity()}get_field(t,e,s){const n=this.store.get_entity_archetype(t),r=this.store.get_entity_row(t);return n.read_field(r,e,s)}set_field(t,e,s,n){const r=this.store.get_entity_archetype(t),i=this.store.get_entity_row(t),c=r.get_column_mut(e,s,this.store._tick);c[i]=n}ref(t,e){const s=this.store.get_entity_archetype(e),n=this.store.get_entity_row(e);return B(s.column_groups[t],n)}ref_mut(t,e){const s=this.store.get_entity_archetype(e),n=this.store.get_entity_row(e);return s._changed_tick[t]=this.store._tick,B(s.column_groups[t],n)}destroy_entity(t){return this.store.destroy_entity_deferred(t),this}add_component(t,e,s){return this.store.add_component_deferred(t,e,s??U),this}remove_component(t,e){return this.store.remove_component_deferred(t,e),this}flush(){this.store.flush_structural(),this.store.flush_destroyed()}emit(t,e){const s=this.store.get_event_def_by_key(t);e===void 0?this.store.emit_signal(s):this.store.emit_event(s,e)}read(t){const e=this.store.get_event_def_by_key(t);return this.store.get_event_reader(e)}resource(t){return this.store.get_resource(t)}set_resource(t,e){this.store.set_resource(t,e)}has_resource(t){return this.store.has_resource(t)}}class et{_query;_changed_ids;constructor(t,e){this._query=t,this._changed_ids=e}for_each(t){const e=this._query._ctx_last_run_tick(),s=this._query._non_empty(),n=this._changed_ids;for(let r=0;r<s.length;r++){const i=s[r];for(let c=0;c<n.length;c++)if(i._changed_tick[n[c]]>=e){t(i);break}}}}const Ut=a=>F(a);class qt{store;schedule;ctx;systems=new Set;next_system_id=0;_tick=0;_fixed_timestep;_accumulator=0;_max_fixed_steps;query_cache=new Map;scratch_mask=new k;constructor(t){this.store=new Pt(t?.initial_capacity),this.schedule=new Ot,this.ctx=new tt(this.store),this._fixed_timestep=t?.fixed_timestep??vt,this._max_fixed_steps=t?.max_fixed_steps??Et}get fixed_timestep(){return this._fixed_timestep}set fixed_timestep(t){this._fixed_timestep=t}get fixed_alpha(){return this._accumulator/this._fixed_timestep}register_component(t,e){if(Array.isArray(t)){const s=e??"f64",n=Object.create(null);for(const r of t)n[r]=s;return this.store.register_component(n)}return this.store.register_component(t)}register_tag(){return this.store.register_component({})}register_event(t,e){this.store.register_event_by_key(t,e)}register_signal(t){this.store.register_event_by_key(t,[])}register_resource(t,e){this.store.register_resource(t,e)}resource(t){return this.store.get_resource(t)}set_resource(t,e){this.store.set_resource(t,e)}has_resource(t){return this.store.has_resource(t)}create_entity(){return this.store.create_entity()}destroy_entity_deferred(t){this.store.destroy_entity_deferred(t)}is_alive(t){return this.store.is_alive(t)}get entity_count(){return this.store.entity_count}add_component(t,e,s){return this.store.add_component(t,e,s??U),this}add_components(t,e){this.store.add_components(t,e)}remove_component(t,e){return this.store.remove_component(t,e),this}remove_components(t,...e){this.store.remove_components(t,e)}has_component(t,e){return this.store.has_component(t,e)}batch_add_component(t,e,s){this.store.batch_add_component(t,e,s)}batch_remove_component(t,e){this.store.batch_remove_component(t,e)}get_field(t,e,s){const n=this.store.get_entity_archetype(t),r=this.store.get_entity_row(t);return n.read_field(r,e,s)}set_field(t,e,s,n){const r=this.store.get_entity_archetype(t),i=this.store.get_entity_row(t),c=r.get_column_mut(e,s,this.store._tick);c[i]=n}emit(t,e){const s=this.store.get_event_def_by_key(t);e===void 0?this.store.emit_signal(s):this.store.emit_event(s,e)}read(t){const e=this.store.get_event_def_by_key(t);return this.store.get_event_reader(e)}query(...t){const e=this.scratch_mask;e._words.fill(0);for(let s=0;s<t.length;s++)e.set(t[s]);return this._resolve_query(e.copy(),null,null,t)}_get_last_run_tick(){return this.ctx.last_run_tick}_resolve_query(t,e,s,n){const r=t.hash(),i=e?e.hash():0,c=s?s.hash():0,o=r^Math.imul(i,mt)^Math.imul(c,pt)|0,_=this._find_cached(o,t,e,s);if(_!==void 0)return _.query;const h=this.store.register_query(t,e??void 0,s??void 0),l=new J(h,n,this,t.copy(),e?.copy()??null,s?.copy()??null);return this.store.update_query_ref(h,l),$(this.query_cache,o,{include_mask:t.copy(),exclude_mask:e?.copy()??null,any_of_mask:s?.copy()??null,query:l}),l}_find_cached(t,e,s,n){const r=this.query_cache.get(t);if(r)for(let i=0;i<r.length;i++){const c=r[i];if(!(!c.include_mask.equals(e)||!(s===null?c.exclude_mask===null:c.exclude_mask!==null&&c.exclude_mask.equals(s))||!(n===null?c.any_of_mask===null:c.any_of_mask!==null&&c.any_of_mask.equals(n))))return c}}register_system(t,e){let s;if(typeof t=="function")if(e!==void 0){const i=e(new Z(this)),c=this.ctx,o=t;s={fn:(_,h)=>o(i,c,h)}}else s={fn:t};else s=t;const n=Ut(this.next_system_id++),r=Object.freeze(Object.assign({id:n},s));return this.systems.add(r),r}add_systems(t,...e){return this.schedule.add_systems(t,...e),this}remove_system(t){this.schedule.remove_system(t),t.on_removed?.(),this.systems.delete(t)}get system_count(){return this.systems.size}startup(){for(const t of this.systems.values())t.on_added?.(this.ctx);this.schedule.run_startup(this.ctx,this._tick)}update(t){if(this.store._tick=this._tick,this.schedule.has_fixed_systems()){this._accumulator+=t;const e=this._max_fixed_steps*this._fixed_timestep;for(this._accumulator>e&&(this._accumulator=e);this._accumulator>=this._fixed_timestep;)this.schedule.run_fixed_update(this.ctx,this._fixed_timestep,this._tick),this._accumulator-=this._fixed_timestep}this.schedule.run_update(this.ctx,t,this._tick),this.store.clear_events(),this._tick++}flush(){this.ctx.flush()}dispose(){for(const t of this.systems.values())t.dispose?.(),t.on_removed?.();this.systems.clear(),this.schedule.clear()}}function Mt(a){return Symbol(a)}exports.ChangedQuery=et;exports.ECS=qt;exports.Query=J;exports.QueryBuilder=Z;exports.SCHEDULE=K;exports.SystemContext=tt;exports.event_key=It;exports.resource_key=Mt;exports.signal_key=Dt;
|
|
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;
|
package/dist/index.d.ts
CHANGED
|
@@ -1,13 +1,17 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
1
|
+
/**
|
|
2
|
+
* # oecs — archetype Entity Component System for TypeScript
|
|
3
|
+
*
|
|
4
|
+
* Re-derived from the oasys engine ECS. A determinism-capable archetype ECS
|
|
5
|
+
* with a topo-sorted scheduler, system sets + run conditions, per-component
|
|
6
|
+
* observers, relations (with wildcards), sparse storage, templates, and a
|
|
7
|
+
* typed host→ECS write seam.
|
|
8
|
+
*
|
|
9
|
+
* Storage runs over a backing-neutral column store (`ColumnStore`). The default
|
|
10
|
+
* profile is **pure-TS heap** — a plain resizable `ArrayBuffer`, so no
|
|
11
|
+
* `SharedArrayBuffer` and no cross-origin isolation (COOP/COEP) are required.
|
|
12
|
+
* The opt-in `SharedArrayBuffer` + WASM profile lives at `@oasys/oecs/shared`.
|
|
13
|
+
*
|
|
14
|
+
* @module oecs
|
|
15
|
+
*/
|
|
16
|
+
export * from './core/ecs';
|
|
13
17
|
//# sourceMappingURL=index.d.ts.map
|
package/dist/index.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG;AACH,cAAc,YAAY,CAAC"}
|