ecspresso 0.12.1 → 0.12.3
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/dist/ecspresso.d.ts +21 -0
- package/dist/index.js +4 -0
- package/dist/{src/index.js.map → index.js.map} +4 -4
- package/dist/plugins/audio.js +4 -0
- package/dist/{src/plugins → plugins}/audio.js.map +2 -2
- package/dist/plugins/bounds.js +4 -0
- package/dist/{src/plugins → plugins}/bounds.js.map +2 -2
- package/dist/plugins/camera.js +4 -0
- package/dist/{src/plugins → plugins}/camera.js.map +2 -2
- package/dist/plugins/collision.js +4 -0
- package/dist/{src/plugins → plugins}/collision.js.map +2 -2
- package/dist/plugins/coroutine.js +4 -0
- package/dist/{src/plugins → plugins}/coroutine.js.map +2 -2
- package/dist/plugins/diagnostics.js +5 -0
- package/dist/{src/plugins → plugins}/diagnostics.js.map +2 -2
- package/dist/plugins/input.js +4 -0
- package/dist/{src/plugins → plugins}/input.js.map +2 -2
- package/dist/plugins/particles.js +4 -0
- package/dist/{src/plugins → plugins}/particles.js.map +2 -2
- package/dist/plugins/physics2D.js +4 -0
- package/dist/{src/plugins → plugins}/physics2D.js.map +2 -2
- package/dist/plugins/renderers/renderer2D.js +4 -0
- package/dist/{src/plugins → plugins}/renderers/renderer2D.js.map +2 -2
- package/dist/plugins/spatial-index.js +4 -0
- package/dist/{src/plugins → plugins}/spatial-index.js.map +2 -2
- package/dist/plugins/sprite-animation.js +4 -0
- package/dist/{src/plugins → plugins}/sprite-animation.js.map +2 -2
- package/dist/plugins/state-machine.js +4 -0
- package/dist/{src/plugins → plugins}/state-machine.js.map +2 -2
- package/dist/plugins/timers.js +4 -0
- package/dist/{src/plugins → plugins}/timers.js.map +2 -2
- package/dist/plugins/transform.js +4 -0
- package/dist/{src/plugins → plugins}/transform.js.map +2 -2
- package/dist/plugins/tween.js +4 -0
- package/dist/{src/plugins → plugins}/tween.js.map +2 -2
- package/dist/resource-manager.d.ts +16 -0
- package/package.json +1 -1
- package/dist/src/index.js +0 -4
- package/dist/src/plugins/audio.js +0 -4
- package/dist/src/plugins/bounds.js +0 -4
- package/dist/src/plugins/camera.js +0 -4
- package/dist/src/plugins/collision.js +0 -4
- package/dist/src/plugins/coroutine.js +0 -4
- package/dist/src/plugins/diagnostics.js +0 -5
- package/dist/src/plugins/input.js +0 -4
- package/dist/src/plugins/particles.js +0 -4
- package/dist/src/plugins/physics2D.js +0 -4
- package/dist/src/plugins/renderers/renderer2D.js +0 -4
- package/dist/src/plugins/spatial-index.js +0 -4
- package/dist/src/plugins/sprite-animation.js +0 -4
- package/dist/src/plugins/state-machine.js +0 -4
- package/dist/src/plugins/timers.js +0 -4
- package/dist/src/plugins/transform.js +0 -4
- package/dist/src/plugins/tween.js +0 -4
|
@@ -4,7 +4,7 @@
|
|
|
4
4
|
"sourcesContent": [
|
|
5
5
|
"/**\n * State Machine Plugin for ECSpresso\n *\n * Provides ECS-native finite state machines with guard-based transitions,\n * event-driven transitions, and lifecycle hooks (onEnter, onExit, onUpdate).\n *\n * Each entity gets a `stateMachine` component referencing a shared definition.\n * One system processes all state machine entities each tick.\n */\n\nimport { definePlugin, type Plugin, type BasePluginOptions } from 'ecspresso';\nimport type { BaseWorld } from 'ecspresso';\nimport type { WorldConfigFrom, EmptyConfig } from '../type-utils';\n\n/** BaseWorld narrowed to state-machine components for typed access in helpers. */\ntype StateMachineWorld = BaseWorld<StateMachineComponentTypes>;\n\n// ==================== State Config ====================\n\n/**\n * Configuration for a single state in a state machine definition.\n *\n * @template S - Union of state name strings\n * @template W - World interface type for hooks/guards (default: StateMachineWorld)\n */\nexport interface StateConfig<S extends string, W extends BaseWorld<StateMachineComponentTypes> = StateMachineWorld> {\n\t/** Called when entering this state */\n\tonEnter?(ctx: { ecs: W; entityId: number }): void;\n\t/** Called when exiting this state */\n\tonExit?(ctx: { ecs: W; entityId: number }): void;\n\t/** Called each tick while in this state */\n\tonUpdate?(ctx: { ecs: W; entityId: number; dt: number }): void;\n\t/** Guard-based transitions evaluated each tick. First passing guard wins. */\n\ttransitions?: ReadonlyArray<{\n\t\ttarget: S;\n\t\tguard(ctx: { ecs: W; entityId: number }): boolean;\n\t}>;\n\t/** Event-based transition map: eventName → target state or guarded transition */\n\ton?: Record<string, S | { target: S; guard(ctx: { ecs: W; entityId: number }): boolean }>;\n}\n\n// ==================== State Machine Definition ====================\n\n/**\n * Immutable definition of a state machine. Shared across entities.\n *\n * @template S - Union of state name strings\n */\nexport interface StateMachineDefinition<S extends string> {\n\treadonly id: string;\n\treadonly initial: S;\n\treadonly states: { readonly [K in S]: StateConfig<S> };\n}\n\n// ==================== Component ====================\n\n/**\n * Runtime state machine component stored on each entity.\n *\n * @template S - Union of state name strings (default: string)\n */\nexport interface StateMachine<S extends string = string> {\n\treadonly definition: StateMachineDefinition<string>;\n\tcurrent: S;\n\tprevious: S | null;\n\tstateTime: number;\n}\n\n/**\n * Component types provided by the state machine plugin.\n *\n * @template S - Union of state name strings (default: string)\n */\nexport interface StateMachineComponentTypes<S extends string = string> {\n\tstateMachine: StateMachine<S>;\n}\n\n// ==================== Event Types ====================\n\n/**\n * Event published on every state transition.\n *\n * @template S - Union of state name strings (default: string)\n */\nexport interface StateTransitionEvent<S extends string = string> {\n\tentityId: number;\n\tfrom: S;\n\tto: S;\n\tdefinitionId: string;\n}\n\n/**\n * Event types provided by the state machine plugin.\n *\n * @template S - Union of state name strings (default: string)\n */\nexport interface StateMachineEventTypes<S extends string = string> {\n\tstateTransition: StateTransitionEvent<S>;\n}\n\n/**\n * Extract the state name union from a StateMachineDefinition.\n *\n * @example\n * ```typescript\n * const enemyFSM = defineStateMachine('enemy', { initial: 'idle', states: { idle: {}, chase: {} } });\n * type EnemyStates = StatesOf<typeof enemyFSM>; // 'idle' | 'chase'\n * type AllStates = StatesOf<typeof enemyFSM> | StatesOf<typeof playerFSM>;\n * ```\n */\nexport type StatesOf<D> = D extends StateMachineDefinition<infer S> ? S : never;\n\n// ==================== Plugin Options ====================\n\n/**\n * Configuration options for the state machine plugin.\n */\nexport interface StateMachinePluginOptions<G extends string = 'stateMachine'> extends BasePluginOptions<G> {}\n\n// ==================== Helper Functions ====================\n\n/**\n * Define a state machine with type-safe state names.\n *\n * @template S - Union of state name strings, inferred from `states` keys\n * @param id - Unique identifier for this definition\n * @param config - Initial state and state configurations\n * @returns A frozen StateMachineDefinition\n *\n * @example\n * ```typescript\n * const enemyFSM = defineStateMachine('enemy', {\n * initial: 'idle',\n * states: {\n * idle: {\n * onEnter: ({ ecs, entityId }) => { ... },\n * transitions: [{ target: 'chase', guard: ({ ecs, entityId }) => playerNearby(ecs, entityId) }],\n * },\n * chase: {\n * onUpdate: ({ ecs, entityId, dt }) => { ... },\n * on: { playerLost: 'idle' },\n * },\n * },\n * });\n * ```\n */\nexport function defineStateMachine<S extends string>(\n\tid: string,\n\tconfig: { initial: NoInfer<S>; states: Record<S, StateConfig<NoInfer<S>>> },\n): StateMachineDefinition<S> {\n\treturn Object.freeze({\n\t\tid,\n\t\tinitial: config.initial,\n\t\tstates: Object.freeze(config.states),\n\t}) as StateMachineDefinition<S>;\n}\n\n/**\n * Create a stateMachine component from a definition.\n *\n * @param definition - The state machine definition to use\n * @param options - Optional overrides (e.g., initial state)\n * @returns Component object suitable for spreading into spawn()\n *\n * @example\n * ```typescript\n * ecs.spawn({\n * ...createStateMachine(enemyFSM),\n * position: { x: 100, y: 200 },\n * });\n * ```\n */\nexport function createStateMachine<S extends string>(\n\tdefinition: StateMachineDefinition<S>,\n\toptions?: { initial?: S },\n): Pick<StateMachineComponentTypes<S>, 'stateMachine'> {\n\tconst initial = options?.initial ?? definition.initial;\n\treturn {\n\t\tstateMachine: {\n\t\t\tdefinition,\n\t\t\tcurrent: initial,\n\t\t\tprevious: null,\n\t\t\tstateTime: 0,\n\t\t},\n\t};\n}\n\n// ==================== Internal: Shared Transition Logic ====================\n\n/**\n * Perform a state transition: onExit → update fields → onEnter → markChanged → publish event.\n * Returns true if the target state exists, false otherwise.\n */\nfunction performTransition(\n\tecs: StateMachineWorld,\n\tentityId: number,\n\tsm: StateMachine,\n\ttargetState: string,\n): boolean {\n\tconst states = sm.definition.states as Record<string, StateConfig<string>>;\n\tconst currentConfig = states[sm.current];\n\tconst targetConfig = states[targetState];\n\n\tif (!targetConfig) return false;\n\n\tcurrentConfig?.onExit?.({ ecs, entityId });\n\n\tsm.previous = sm.current;\n\tsm.current = targetState;\n\tsm.stateTime = 0;\n\n\ttargetConfig.onEnter?.({ ecs, entityId });\n\n\tecs.markChanged(entityId, 'stateMachine');\n\tecs.eventBus.publish('stateTransition', {\n\t\tentityId,\n\t\tfrom: sm.previous,\n\t\tto: sm.current,\n\t\tdefinitionId: sm.definition.id,\n\t} satisfies StateTransitionEvent);\n\n\treturn true;\n}\n\n// ==================== Utility Functions ====================\n\n/**\n * Directly transition an entity's state machine to a target state.\n * Fires onExit, onEnter hooks and publishes stateTransition event.\n *\n * @param ecs - ECS instance (structural typing)\n * @param entityId - Entity to transition\n * @param targetState - State to transition to\n * @returns true if transition succeeded, false if entity has no stateMachine or target state doesn't exist\n */\nexport function transitionTo(\n\tecs: StateMachineWorld,\n\tentityId: number,\n\ttargetState: string,\n): boolean {\n\tconst sm = ecs.getComponent(entityId, 'stateMachine');\n\tif (!sm) return false;\n\treturn performTransition(ecs, entityId, sm, targetState);\n}\n\n/**\n * Send a named event to an entity's state machine.\n * Checks the current state's `on` handlers for a matching event.\n *\n * @param ecs - ECS instance (structural typing)\n * @param entityId - Entity to send event to\n * @param eventName - Event name to match against `on` handlers\n * @returns true if a transition occurred, false otherwise\n */\nexport function sendEvent(\n\tecs: StateMachineWorld,\n\tentityId: number,\n\teventName: string,\n): boolean {\n\tconst sm = ecs.getComponent(entityId, 'stateMachine');\n\tif (!sm) return false;\n\n\tconst states = sm.definition.states as Record<string, StateConfig<string>>;\n\tconst currentConfig = states[sm.current];\n\tif (!currentConfig?.on) return false;\n\n\tconst handler = currentConfig.on[eventName];\n\tif (handler === undefined) return false;\n\n\tif (typeof handler === 'string') {\n\t\treturn performTransition(ecs, entityId, sm, handler);\n\t}\n\n\tif (!handler.guard({ ecs, entityId })) return false;\n\treturn performTransition(ecs, entityId, sm, handler.target);\n}\n\n/**\n * Get the current state of an entity's state machine.\n *\n * @param ecs - ECS instance (structural typing)\n * @param entityId - Entity to query\n * @returns The current state string, or undefined if entity has no stateMachine\n */\nexport function getStateMachineState(\n\tecs: StateMachineWorld,\n\tentityId: number,\n): string | undefined {\n\tconst sm = ecs.getComponent(entityId, 'stateMachine');\n\treturn sm?.current;\n}\n\n// ==================== State Machine Helpers ====================\n\n/**\n * Typed helpers for the state machine plugin.\n * Creates helpers that validate hook parameters against the world type W.\n * Call after .build() using typeof ecs.\n */\nexport interface StateMachineHelpers<W extends BaseWorld<StateMachineComponentTypes>> {\n\tdefineStateMachine: <S extends string>(\n\t\tid: string,\n\t\tconfig: { initial: NoInfer<S>; states: Record<S, StateConfig<NoInfer<S>, W>> },\n\t) => StateMachineDefinition<S>;\n}\n\nexport function createStateMachineHelpers<W extends BaseWorld<StateMachineComponentTypes> = StateMachineWorld>(_world?: W): StateMachineHelpers<W> {\n\treturn {\n\t\tdefineStateMachine: defineStateMachine as StateMachineHelpers<W>['defineStateMachine'],\n\t};\n}\n\n// ==================== Plugin Factory ====================\n\n/**\n * Create a state machine plugin for ECSpresso.\n *\n * Provides:\n * - Lifecycle hooks (onEnter, onExit, onUpdate) per state\n * - Guard-based automatic transitions evaluated each tick\n * - Event-based transitions via `sendEvent()`\n * - Direct transitions via `transitionTo()`\n * - stateTransition events published on every transition\n *\n * @example\n * ```typescript\n * const ecs = ECSpresso.create()\n * .withPlugin(createStateMachinePlugin())\n * .build();\n *\n * const fsm = defineStateMachine('enemy', {\n * initial: 'idle',\n * states: {\n * idle: {\n * transitions: [{ target: 'chase', guard: ({ ecs, entityId }) => playerNearby(ecs, entityId) }],\n * },\n * chase: {\n * onUpdate: ({ ecs, entityId, dt }) => moveTowardPlayer(ecs, entityId, dt),\n * on: { playerLost: 'idle' },\n * },\n * },\n * });\n *\n * ecs.spawn({\n * ...createStateMachine(fsm),\n * position: { x: 0, y: 0 },\n * });\n * ```\n */\nexport function createStateMachinePlugin<S extends string = string, G extends string = 'stateMachine'>(\n\toptions?: StateMachinePluginOptions<G>,\n): Plugin<WorldConfigFrom<StateMachineComponentTypes<S>, StateMachineEventTypes<S>>, EmptyConfig, 'state-machine-update', G> {\n\tconst {\n\t\tsystemGroup = 'stateMachine',\n\t\tpriority = 0,\n\t\tphase = 'update',\n\t} = options ?? {};\n\n\treturn definePlugin<WorldConfigFrom<StateMachineComponentTypes<S>, StateMachineEventTypes<S>>, EmptyConfig, 'state-machine-update', G>({\n\t\tid: 'stateMachine',\n\t\tinstall(world) {\n\t\t\tworld\n\t\t\t\t.addSystem('state-machine-update')\n\t\t\t\t.setPriority(priority)\n\t\t\t\t.inPhase(phase)\n\t\t\t\t.inGroup(systemGroup)\n\t\t\t\t.addQuery('machines', {\n\t\t\t\t\twith: ['stateMachine'],\n\t\t\t\t})\n\t\t\t\t.setOnEntityEnter('machines', ({ entity, ecs }) => {\n\t\t\t\t\tconst sm = entity.components.stateMachine;\n\t\t\t\t\tconst states = sm.definition.states as Record<string, StateConfig<string>>;\n\t\t\t\t\tconst world: StateMachineWorld = ecs;\n\t\t\t\t\tstates[sm.current]?.onEnter?.({ ecs: world, entityId: entity.id });\n\t\t\t\t})\n\t\t\t\t.setProcess(({ queries, dt, ecs }) => {\n\t\t\t\t\t// Pre-allocated context reused across entities to avoid per-entity-per-frame allocations\n\t\t\t\t\tconst world: StateMachineWorld = ecs;\n\t\t\t\t\tconst hookCtx = { ecs: world, entityId: 0, dt: 0 };\n\n\t\t\t\t\tfor (const entity of queries.machines) {\n\t\t\t\t\t\tconst sm = entity.components.stateMachine;\n\t\t\t\t\t\tconst states = sm.definition.states as Record<string, StateConfig<string>>;\n\n\t\t\t\t\t\thookCtx.entityId = entity.id;\n\t\t\t\t\t\thookCtx.dt = dt;\n\n\t\t\t\t\t\t// Accumulate state time\n\t\t\t\t\t\tsm.stateTime += dt;\n\n\t\t\t\t\t\t// onUpdate hook\n\t\t\t\t\t\tstates[sm.current]?.onUpdate?.(hookCtx);\n\n\t\t\t\t\t\t// Evaluate guard transitions (first passing guard wins)\n\t\t\t\t\t\tconst currentConfig = states[sm.current];\n\t\t\t\t\t\tif (currentConfig?.transitions) {\n\t\t\t\t\t\t\tfor (const transition of currentConfig.transitions) {\n\t\t\t\t\t\t\t\tif (transition.guard(hookCtx)) {\n\t\t\t\t\t\t\t\t\tperformTransition(hookCtx.ecs, entity.id, sm, transition.target);\n\t\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t});\n\t\t},\n\t});\n}\n"
|
|
6
6
|
],
|
|
7
|
-
"mappings": "
|
|
8
|
-
"debugId": "
|
|
7
|
+
"mappings": "i0BAUA,uBAAS,kBAwIF,SAAS,CAAoC,CACnD,EACA,EAC4B,CAC5B,OAAO,OAAO,OAAO,CACpB,KACA,QAAS,EAAO,QAChB,OAAQ,OAAO,OAAO,EAAO,MAAM,CACpC,CAAC,EAkBK,SAAS,CAAoC,CACnD,EACA,EACsD,CACtD,IAAM,EAAU,GAAS,SAAW,EAAW,QAC/C,MAAO,CACN,aAAc,CACb,aACA,QAAS,EACT,SAAU,KACV,UAAW,CACZ,CACD,EASD,SAAS,CAAiB,CACzB,EACA,EACA,EACA,EACU,CACV,IAAM,EAAS,EAAG,WAAW,OACvB,EAAgB,EAAO,EAAG,SAC1B,EAAe,EAAO,GAE5B,GAAI,CAAC,EAAc,MAAO,GAkB1B,OAhBA,GAAe,SAAS,CAAE,MAAK,UAAS,CAAC,EAEzC,EAAG,SAAW,EAAG,QACjB,EAAG,QAAU,EACb,EAAG,UAAY,EAEf,EAAa,UAAU,CAAE,MAAK,UAAS,CAAC,EAExC,EAAI,YAAY,EAAU,cAAc,EACxC,EAAI,SAAS,QAAQ,kBAAmB,CACvC,WACA,KAAM,EAAG,SACT,GAAI,EAAG,QACP,aAAc,EAAG,WAAW,EAC7B,CAAgC,EAEzB,GAcD,SAAS,CAAY,CAC3B,EACA,EACA,EACU,CACV,IAAM,EAAK,EAAI,aAAa,EAAU,cAAc,EACpD,GAAI,CAAC,EAAI,MAAO,GAChB,OAAO,EAAkB,EAAK,EAAU,EAAI,CAAW,EAYjD,SAAS,CAAS,CACxB,EACA,EACA,EACU,CACV,IAAM,EAAK,EAAI,aAAa,EAAU,cAAc,EACpD,GAAI,CAAC,EAAI,MAAO,GAGhB,IAAM,EADS,EAAG,WAAW,OACA,EAAG,SAChC,GAAI,CAAC,GAAe,GAAI,MAAO,GAE/B,IAAM,EAAU,EAAc,GAAG,GACjC,GAAI,IAAY,OAAW,MAAO,GAElC,GAAI,OAAO,IAAY,SACtB,OAAO,EAAkB,EAAK,EAAU,EAAI,CAAO,EAGpD,GAAI,CAAC,EAAQ,MAAM,CAAE,MAAK,UAAS,CAAC,EAAG,MAAO,GAC9C,OAAO,EAAkB,EAAK,EAAU,EAAI,EAAQ,MAAM,EAUpD,SAAS,CAAoB,CACnC,EACA,EACqB,CAErB,OADW,EAAI,aAAa,EAAU,cAAc,GACzC,QAiBL,SAAS,CAA8F,CAAC,EAAoC,CAClJ,MAAO,CACN,mBAAoB,CACrB,EAwCM,SAAS,CAAsF,CACrG,EAC4H,CAC5H,IACC,cAAc,eACd,WAAW,EACX,QAAQ,UACL,GAAW,CAAC,EAEhB,OAAO,EAAgI,CACtI,GAAI,eACJ,OAAO,CAAC,EAAO,CACd,EACE,UAAU,sBAAsB,EAChC,YAAY,CAAQ,EACpB,QAAQ,CAAK,EACb,QAAQ,CAAW,EACnB,SAAS,WAAY,CACrB,KAAM,CAAC,cAAc,CACtB,CAAC,EACA,iBAAiB,WAAY,EAAG,SAAQ,SAAU,CAClD,IAAM,EAAK,EAAO,WAAW,aACvB,EAAS,EAAG,WAAW,OACvB,EAA2B,EACjC,EAAO,EAAG,UAAU,UAAU,CAAE,IAAK,EAAO,SAAU,EAAO,EAAG,CAAC,EACjE,EACA,WAAW,EAAG,UAAS,KAAI,SAAU,CAGrC,IAAM,EAAU,CAAE,IADe,EACH,SAAU,EAAG,GAAI,CAAE,EAEjD,QAAW,KAAU,EAAQ,SAAU,CACtC,IAAM,EAAK,EAAO,WAAW,aACvB,EAAS,EAAG,WAAW,OAE7B,EAAQ,SAAW,EAAO,GAC1B,EAAQ,GAAK,EAGb,EAAG,WAAa,EAGhB,EAAO,EAAG,UAAU,WAAW,CAAO,EAGtC,IAAM,EAAgB,EAAO,EAAG,SAChC,GAAI,GAAe,aAClB,QAAW,KAAc,EAAc,YACtC,GAAI,EAAW,MAAM,CAAO,EAAG,CAC9B,EAAkB,EAAQ,IAAK,EAAO,GAAI,EAAI,EAAW,MAAM,EAC/D,SAKJ,EAEJ,CAAC",
|
|
8
|
+
"debugId": "6AFCBD8BBDD0D01164756E2164756E21",
|
|
9
9
|
"names": []
|
|
10
10
|
}
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
var{defineProperty:C,getOwnPropertyNames:K,getOwnPropertyDescriptor:L}=Object,M=Object.prototype.hasOwnProperty;function N(j){return this[j]}var V=(j)=>{var k=(D??=new WeakMap).get(j),z;if(k)return k;if(k=C({},"__esModule",{value:!0}),j&&typeof j==="object"||typeof j==="function"){for(var A of K(j))if(!M.call(k,A))C(k,A,{get:N.bind(j,A),enumerable:!(z=L(j,A))||z.enumerable})}return D.set(j,k),k},D;var Q=(j)=>j;function S(j,k){this[j]=Q.bind(null,k)}var W=(j,k)=>{for(var z in k)C(j,z,{get:k[z],enumerable:!0,configurable:!0,set:S.bind(k,z)})};var X=(j,k)=>()=>(j&&(k=j(j=0)),k);var Y=((j)=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(j,{get:(k,z)=>(typeof require<"u"?require:k)[z]}):j)(function(j){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+j+'" is not supported')});import{definePlugin as U}from"ecspresso";function $(j,k){return{timer:{elapsed:0,duration:j,repeat:!1,active:!0,justFinished:!1,onComplete:k?.onComplete}}}function b(j,k){return{timer:{elapsed:0,duration:j,repeat:!0,active:!0,justFinished:!1,onComplete:k?.onComplete}}}function v(j){let{systemGroup:k="timers",priority:z=0,phase:A="preUpdate"}=j??{};return U({id:"timers",install(E){E.addSystem("timer-update").setPriority(z).inPhase(A).inGroup(k).addQuery("timers",{with:["timer"]}).setProcess(({queries:F,dt:H,ecs:J})=>{for(let B of F.timers){let{timer:x}=B.components;if(x.justFinished=!1,!x.active)continue;if(x.elapsed+=H,x.elapsed<x.duration)continue;if(x.repeat)while(x.elapsed>=x.duration)x.justFinished=!0,x.onComplete?.({entityId:B.id,duration:x.duration,elapsed:x.elapsed}),x.elapsed-=x.duration;else x.justFinished=!0,x.onComplete?.({entityId:B.id,duration:x.duration,elapsed:x.elapsed}),x.active=!1,J.commands.removeEntity(B.id)}})}})}export{v as createTimerPlugin,$ as createTimer,b as createRepeatingTimer};
|
|
2
|
+
|
|
3
|
+
//# debugId=6A5A1FAC31B4745C64756E2164756E21
|
|
4
|
+
//# sourceMappingURL=timers.js.map
|
|
@@ -4,7 +4,7 @@
|
|
|
4
4
|
"sourcesContent": [
|
|
5
5
|
"/**\n * Timer Plugin for ECSpresso\n *\n * Provides ECS-native timers following the \"data, not callbacks\" philosophy.\n * Timers are components processed each frame, automatically cleaned up when entities are removed.\n */\n\nimport { definePlugin, type Plugin, type BasePluginOptions } from 'ecspresso';\nimport type { WorldConfigFrom, EmptyConfig } from '../type-utils';\n\n// ==================== Event Types ====================\n\n/**\n * Data structure passed to onComplete callbacks when a timer completes.\n *\n * @example\n * ```typescript\n * createTimer(1.5, {\n * onComplete: (data) => {\n * console.log(`Timer on entity ${data.entityId} finished after ${data.elapsed}s`);\n * }\n * });\n * ```\n */\nexport interface TimerEventData {\n\t/** The entity ID that the timer belongs to */\n\tentityId: number;\n\t/** The timer's configured duration in seconds */\n\tduration: number;\n\t/** The actual elapsed time (may exceed duration slightly) */\n\telapsed: number;\n}\n\n// ==================== Component Types ====================\n\n\n/**\n * Timer component data structure.\n * Use `justFinished` to detect timer completion in your systems.\n */\nexport interface Timer {\n\t/** Time accumulated so far (seconds) */\n\telapsed: number;\n\t/** Target duration (seconds) */\n\tduration: number;\n\t/** Whether timer repeats after completion */\n\trepeat: boolean;\n\t/** Whether timer is currently running */\n\tactive: boolean;\n\t/** True for one frame after timer completes */\n\tjustFinished: boolean;\n\t/** Optional callback invoked when timer completes */\n\tonComplete?: (data: TimerEventData) => void;\n}\n\n/**\n * Component types provided by the timer plugin.\n * Included automatically via `.withPlugin(createTimerPlugin())`.\n *\n * @example\n * ```typescript\n * const ecs = ECSpresso.create()\n * .withPlugin(createTimerPlugin())\n * .withComponentTypes<{ velocity: { x: number; y: number }; player: true }>()\n * .build();\n * ```\n */\nexport interface TimerComponentTypes {\n\ttimer: Timer;\n}\n\n// ==================== Plugin Options ====================\n\n/**\n * Configuration options for the timer plugin.\n */\nexport interface TimerPluginOptions<G extends string = 'timers'> extends BasePluginOptions<G> {}\n\n// ==================== Helper Functions ====================\n\n/**\n * Options for timer creation\n */\nexport interface TimerOptions {\n\t/** Callback invoked when timer completes */\n\tonComplete?: (data: TimerEventData) => void;\n}\n\n/**\n * Create a one-shot timer that fires once after the specified duration.\n *\n * @param duration Duration in seconds until the timer completes\n * @param options Optional configuration including onComplete callback\n * @returns Component object suitable for spreading into spawn()\n *\n * @example\n * ```typescript\n * // Timer without callback\n * ecs.spawn({\n * ...createTimer(2),\n * explosion: true,\n * });\n *\n * // Timer with onComplete callback\n * ecs.spawn({\n * ...createTimer(1.5, { onComplete: (data) => console.log('done', data.entityId) }),\n * });\n * ```\n */\nexport function createTimer(\n\tduration: number,\n\toptions?: TimerOptions\n): Pick<TimerComponentTypes, 'timer'> {\n\treturn {\n\t\ttimer: {\n\t\t\telapsed: 0,\n\t\t\tduration,\n\t\t\trepeat: false,\n\t\t\tactive: true,\n\t\t\tjustFinished: false,\n\t\t\tonComplete: options?.onComplete,\n\t\t},\n\t};\n}\n\n/**\n * Create a repeating timer that fires every `duration` seconds.\n *\n * @param duration Duration in seconds between each timer completion\n * @param options Optional configuration including onComplete callback\n * @returns Component object suitable for spreading into spawn()\n *\n * @example\n * ```typescript\n * // Timer without callback\n * ecs.spawn({\n * ...createRepeatingTimer(5),\n * spawner: true,\n * });\n *\n * // Repeating timer with onComplete callback\n * ecs.spawn({\n * ...createRepeatingTimer(3, { onComplete: (data) => console.log('cycle', data.elapsed) }),\n * });\n * ```\n */\nexport function createRepeatingTimer(\n\tduration: number,\n\toptions?: TimerOptions\n): Pick<TimerComponentTypes, 'timer'> {\n\treturn {\n\t\ttimer: {\n\t\t\telapsed: 0,\n\t\t\tduration,\n\t\t\trepeat: true,\n\t\t\tactive: true,\n\t\t\tjustFinished: false,\n\t\t\tonComplete: options?.onComplete,\n\t\t},\n\t};\n}\n\n// ==================== Plugin Factory ====================\n\n/**\n * Create a timer plugin for ECSpresso.\n *\n * This plugin provides:\n * - Timer update system that processes all timer components each frame\n * - `justFinished` flag pattern for one-frame completion detection\n * - Automatic cleanup when entities are removed\n *\n * @example\n * ```typescript\n * const ecs = ECSpresso\n * .create<Components, Events, Resources>()\n * .withPlugin(createTimerPlugin())\n * .build();\n *\n * // Spawn entity with timer\n * ecs.spawn({\n * ...createRepeatingTimer(5),\n * spawner: true,\n * });\n *\n * // React to timer completion in a system\n * ecs.addSystem('spawn-on-timer')\n * .addQuery('spawners', { with: ['timer', 'spawner'] })\n * .setProcess((queries, _dt, ecs) => {\n * for (const { components } of queries.spawners) {\n * if (components.timer.justFinished) {\n * ecs.spawn({ enemy: true });\n * }\n * }\n * });\n * ```\n */\nexport function createTimerPlugin<G extends string = 'timers'>(\n\toptions?: TimerPluginOptions<G>\n): Plugin<WorldConfigFrom<TimerComponentTypes>, EmptyConfig, 'timer-update', G> {\n\tconst {\n\t\tsystemGroup = 'timers',\n\t\tpriority = 0,\n\t\tphase = 'preUpdate',\n\t} = options ?? {};\n\n\treturn definePlugin<WorldConfigFrom<TimerComponentTypes>, EmptyConfig, 'timer-update', G>({\n\t\tid: 'timers',\n\t\tinstall(world) {\n\t\t\tworld\n\t\t\t\t.addSystem('timer-update')\n\t\t\t\t.setPriority(priority)\n\t\t\t\t.inPhase(phase)\n\t\t\t\t.inGroup(systemGroup)\n\t\t\t\t.addQuery('timers', {\n\t\t\t\t\twith: ['timer'],\n\t\t\t\t})\n\t\t\t\t.setProcess(({ queries, dt, ecs }) => {\n\t\t\t\t\tfor (const entity of queries.timers) {\n\t\t\t\t\t\tconst { timer } = entity.components;\n\n\t\t\t\t\t\t// Reset justFinished flag from previous frame\n\t\t\t\t\t\ttimer.justFinished = false;\n\n\t\t\t\t\t\t// Skip inactive timers\n\t\t\t\t\t\tif (!timer.active) continue;\n\n\t\t\t\t\t\t// Accumulate time\n\t\t\t\t\t\ttimer.elapsed += dt;\n\n\t\t\t\t\t\t// Check if timer completed\n\t\t\t\t\t\tif (timer.elapsed < timer.duration) continue;\n\n\t\t\t\t\t\t// Timer completed - handle based on repeat mode\n\t\t\t\t\t\tif (timer.repeat) {\n\t\t\t\t\t\t\t// Handle multiple cycles in one frame\n\t\t\t\t\t\t\twhile (timer.elapsed >= timer.duration) {\n\t\t\t\t\t\t\t\ttimer.justFinished = true;\n\t\t\t\t\t\t\t\ttimer.onComplete?.({ entityId: entity.id, duration: timer.duration, elapsed: timer.elapsed });\n\t\t\t\t\t\t\t\ttimer.elapsed -= timer.duration;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t// One-shot timer\n\t\t\t\t\t\t\ttimer.justFinished = true;\n\t\t\t\t\t\t\ttimer.onComplete?.({ entityId: entity.id, duration: timer.duration, elapsed: timer.elapsed });\n\t\t\t\t\t\t\ttimer.active = false;\n\t\t\t\t\t\t\t// Auto-remove one-shot timer entities after completion.\n\t\t\t\t\t\t\t// If configurability is needed in the future, add an autoRemove option to TimerOptions.\n\t\t\t\t\t\t\tecs.commands.removeEntity(entity.id);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t});\n\t\t},\n\t});\n}\n"
|
|
6
6
|
],
|
|
7
|
-
"mappings": "
|
|
8
|
-
"debugId": "
|
|
7
|
+
"mappings": "i0BAOA,uBAAS,kBAsGF,SAAS,CAAW,CAC1B,EACA,EACqC,CACrC,MAAO,CACN,MAAO,CACN,QAAS,EACT,WACA,OAAQ,GACR,OAAQ,GACR,aAAc,GACd,WAAY,GAAS,UACtB,CACD,EAwBM,SAAS,CAAoB,CACnC,EACA,EACqC,CACrC,MAAO,CACN,MAAO,CACN,QAAS,EACT,WACA,OAAQ,GACR,OAAQ,GACR,aAAc,GACd,WAAY,GAAS,UACtB,CACD,EAsCM,SAAS,CAA8C,CAC7D,EAC+E,CAC/E,IACC,cAAc,SACd,WAAW,EACX,QAAQ,aACL,GAAW,CAAC,EAEhB,OAAO,EAAmF,CACzF,GAAI,SACJ,OAAO,CAAC,EAAO,CACd,EACE,UAAU,cAAc,EACxB,YAAY,CAAQ,EACpB,QAAQ,CAAK,EACb,QAAQ,CAAW,EACnB,SAAS,SAAU,CACnB,KAAM,CAAC,OAAO,CACf,CAAC,EACA,WAAW,EAAG,UAAS,KAAI,SAAU,CACrC,QAAW,KAAU,EAAQ,OAAQ,CACpC,IAAQ,SAAU,EAAO,WAMzB,GAHA,EAAM,aAAe,GAGjB,CAAC,EAAM,OAAQ,SAMnB,GAHA,EAAM,SAAW,EAGb,EAAM,QAAU,EAAM,SAAU,SAGpC,GAAI,EAAM,OAET,MAAO,EAAM,SAAW,EAAM,SAC7B,EAAM,aAAe,GACrB,EAAM,aAAa,CAAE,SAAU,EAAO,GAAI,SAAU,EAAM,SAAU,QAAS,EAAM,OAAQ,CAAC,EAC5F,EAAM,SAAW,EAAM,SAIxB,OAAM,aAAe,GACrB,EAAM,aAAa,CAAE,SAAU,EAAO,GAAI,SAAU,EAAM,SAAU,QAAS,EAAM,OAAQ,CAAC,EAC5F,EAAM,OAAS,GAGf,EAAI,SAAS,aAAa,EAAO,EAAE,GAGrC,EAEJ,CAAC",
|
|
8
|
+
"debugId": "6A5A1FAC31B4745C64756E2164756E21",
|
|
9
9
|
"names": []
|
|
10
10
|
}
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
var{defineProperty:F,getOwnPropertyNames:M,getOwnPropertyDescriptor:N}=Object,O=Object.prototype.hasOwnProperty;function Q(j){return this[j]}var $=(j)=>{var k=(J??=new WeakMap).get(j),q;if(k)return k;if(k=F({},"__esModule",{value:!0}),j&&typeof j==="object"||typeof j==="function"){for(var v of M(j))if(!O.call(k,v))F(k,v,{get:Q.bind(j,v),enumerable:!(q=N(j,v))||q.enumerable})}return J.set(j,k),k},J;var S=(j)=>j;function U(j,k){this[j]=S.bind(null,k)}var A=(j,k)=>{for(var q in k)F(j,q,{get:k[q],enumerable:!0,configurable:!0,set:U.bind(k,q)})};var E=(j,k)=>()=>(j&&(k=j(j=0)),k);var G=((j)=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(j,{get:(k,q)=>(typeof require<"u"?require:k)[q]}):j)(function(j){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+j+'" is not supported')});import{definePlugin as V}from"ecspresso";var b={x:0,y:0,rotation:0,scaleX:1,scaleY:1},g={x:0,y:0,rotation:0,scaleX:1,scaleY:1};function h(j,k){return{localTransform:{x:j,y:k,rotation:0,scaleX:1,scaleY:1}}}function u(j,k){return{worldTransform:{x:j,y:k,rotation:0,scaleX:1,scaleY:1}}}function W(j,k,q){let v=q?.scale??q?.scaleX??1,C=q?.scale??q?.scaleY??1,z=q?.rotation??0,B={x:j,y:k,rotation:z,scaleX:v,scaleY:C};return{localTransform:{...B},worldTransform:{...B}}}function L(j){let{systemGroup:k="transform",priority:q=500,phase:v="postUpdate"}=j??{};return V({id:"transform",install(C){C.registerRequired("localTransform","worldTransform",(z)=>({x:z.x,y:z.y,rotation:z.rotation,scaleX:z.scaleX,scaleY:z.scaleY})),C.addSystem("transform-propagation").setPriority(q).inPhase(v).inGroup(k).setProcess(({ecs:z})=>{Z(z)})}})}function Z(j){let k=j.entityManager;j.forEachInHierarchy((v,C)=>{let z=k.getComponent(v,"localTransform"),B=k.getComponent(v,"worldTransform");if(!z||!B)return;if(C===null)H(z,B);else{let D=k.getComponent(C,"worldTransform");if(D)_(D,z,B);else H(z,B)}j.markChanged(v,"worldTransform")});let q=j.getEntitiesWithQuery(["localTransform","worldTransform"]);for(let v of q)if(j.getParent(v.id)===null&&j.getChildren(v.id).length===0){let{localTransform:z,worldTransform:B}=v.components;H(z,B),j.markChanged(v.id,"worldTransform")}}function H(j,k){k.x=j.x,k.y=j.y,k.rotation=j.rotation,k.scaleX=j.scaleX,k.scaleY=j.scaleY}function _(j,k,q){let v=k.x*j.scaleX,C=k.y*j.scaleY,z=Math.cos(j.rotation),B=Math.sin(j.rotation),D=v*z-C*B,K=v*B+C*z;q.x=j.x+D,q.y=j.y+K,q.rotation=j.rotation+k.rotation,q.scaleX=j.scaleX*k.scaleX,q.scaleY=j.scaleY*k.scaleY}export{u as createWorldTransform,L as createTransformPlugin,W as createTransform,h as createLocalTransform,g as DEFAULT_WORLD_TRANSFORM,b as DEFAULT_LOCAL_TRANSFORM};
|
|
2
|
+
|
|
3
|
+
//# debugId=C63DD170F03CB2AB64756E2164756E21
|
|
4
|
+
//# sourceMappingURL=transform.js.map
|
|
@@ -4,7 +4,7 @@
|
|
|
4
4
|
"sourcesContent": [
|
|
5
5
|
"/**\n * Transform Plugin for ECSpresso\n *\n * Provides hierarchical transform propagation following Bevy's Transform/GlobalTransform pattern.\n * LocalTransform is modified by user code; WorldTransform is computed automatically.\n *\n * @see https://docs.rs/bevy/latest/bevy/transform/components/struct.GlobalTransform.html\n */\n\nimport { definePlugin, type Plugin, type BasePluginOptions } from 'ecspresso';\nimport type ECSpresso from 'ecspresso';\nimport type { WorldConfigFrom, EmptyConfig } from '../type-utils';\n\n// ==================== Component Types ====================\n\n/**\n * Local transform relative to parent (or world if no parent).\n * This is the transform you modify directly.\n */\nexport interface LocalTransform {\n\tx: number;\n\ty: number;\n\trotation: number;\n\tscaleX: number;\n\tscaleY: number;\n}\n\n/**\n * Computed world transform (accumulated from parent chain).\n * Read-only - managed by the transform propagation system.\n */\nexport interface WorldTransform {\n\tx: number;\n\ty: number;\n\trotation: number;\n\tscaleX: number;\n\tscaleY: number;\n}\n\n/**\n * Component types provided by the transform plugin.\n * Included automatically via `.withPlugin(createTransformPlugin())`.\n *\n * @example\n * ```typescript\n * const ecs = ECSpresso.create()\n * .withPlugin(createTransformPlugin())\n * .withComponentTypes<{ sprite: Sprite; velocity: { x: number; y: number } }>()\n * .build();\n * ```\n */\nexport interface TransformComponentTypes {\n\tlocalTransform: LocalTransform;\n\tworldTransform: WorldTransform;\n}\n\n/**\n * WorldConfig representing the transform plugin's provided components.\n * Used as the `Requires` type parameter by plugins that depend on transform.\n */\nexport type TransformWorldConfig = WorldConfigFrom<TransformComponentTypes>;\n\n// ==================== Plugin Options ====================\n\n/**\n * Configuration options for the transform plugin.\n */\nexport interface TransformPluginOptions<G extends string = 'transform'> extends BasePluginOptions<G> {}\n\n// ==================== Default Values ====================\n\n/**\n * Default local transform values.\n */\nexport const DEFAULT_LOCAL_TRANSFORM: Readonly<LocalTransform> = {\n\tx: 0,\n\ty: 0,\n\trotation: 0,\n\tscaleX: 1,\n\tscaleY: 1,\n};\n\n/**\n * Default world transform values.\n */\nexport const DEFAULT_WORLD_TRANSFORM: Readonly<WorldTransform> = {\n\tx: 0,\n\ty: 0,\n\trotation: 0,\n\tscaleX: 1,\n\tscaleY: 1,\n};\n\n// ==================== Helper Functions ====================\n\n/**\n * Create a local transform component with position only.\n * Uses default rotation (0) and scale (1, 1).\n *\n * @param x The x coordinate\n * @param y The y coordinate\n * @returns Component object suitable for spreading into spawn()\n *\n * @example\n * ```typescript\n * ecs.spawn({\n * ...createLocalTransform(100, 200),\n * sprite,\n * });\n * ```\n */\nexport function createLocalTransform(x: number, y: number): Pick<TransformComponentTypes, 'localTransform'> {\n\treturn {\n\t\tlocalTransform: {\n\t\t\tx,\n\t\t\ty,\n\t\t\trotation: 0,\n\t\t\tscaleX: 1,\n\t\t\tscaleY: 1,\n\t\t},\n\t};\n}\n\n/**\n * Create a world transform component with position only.\n * Typically used alongside createLocalTransform for initial state.\n *\n * @param x The x coordinate\n * @param y The y coordinate\n * @returns Component object suitable for spreading into spawn()\n */\nexport function createWorldTransform(x: number, y: number): Pick<TransformComponentTypes, 'worldTransform'> {\n\treturn {\n\t\tworldTransform: {\n\t\t\tx,\n\t\t\ty,\n\t\t\trotation: 0,\n\t\t\tscaleX: 1,\n\t\t\tscaleY: 1,\n\t\t},\n\t};\n}\n\n/**\n * Options for creating a full transform.\n */\nexport interface TransformOptions {\n\trotation?: number;\n\tscaleX?: number;\n\tscaleY?: number;\n\t/** Uniform scale (overrides scaleX/scaleY if provided) */\n\tscale?: number;\n}\n\n/**\n * Create both local and world transform components.\n * World transform is initialized to match local transform.\n *\n * @param x The x coordinate\n * @param y The y coordinate\n * @param options Optional rotation and scale\n * @returns Component object suitable for spreading into spawn()\n *\n * @example\n * ```typescript\n * ecs.spawn({\n * ...createTransform(100, 200),\n * sprite,\n * });\n *\n * // With rotation and scale\n * ecs.spawn({\n * ...createTransform(100, 200, { rotation: Math.PI / 4, scale: 2 }),\n * sprite,\n * });\n * ```\n */\nexport function createTransform(\n\tx: number,\n\ty: number,\n\toptions?: TransformOptions\n): TransformComponentTypes {\n\tconst scaleX = options?.scale ?? options?.scaleX ?? 1;\n\tconst scaleY = options?.scale ?? options?.scaleY ?? 1;\n\tconst rotation = options?.rotation ?? 0;\n\n\tconst transform = {\n\t\tx,\n\t\ty,\n\t\trotation,\n\t\tscaleX,\n\t\tscaleY,\n\t};\n\n\treturn {\n\t\tlocalTransform: { ...transform },\n\t\tworldTransform: { ...transform },\n\t};\n}\n\n// ==================== Plugin Factory ====================\n\n/**\n * Create a transform plugin for ECSpresso.\n *\n * This plugin provides:\n * - Transform propagation system that computes world transforms from local transforms\n * - Parent-first traversal ensures parents are processed before children\n * - Supports full transform hierarchy (position, rotation, scale)\n *\n * @example\n * ```typescript\n * const ecs = ECSpresso\n * .create<Components, Events, Resources>()\n * .withPlugin(createTransformPlugin())\n * .withPlugin(createPhysics2DPlugin())\n * .build();\n *\n * // Spawn entity with transform\n * ecs.spawn({\n * ...createTransform(100, 200),\n * velocity: { x: 50, y: 0 },\n * });\n * ```\n */\nexport function createTransformPlugin<G extends string = 'transform'>(\n\toptions?: TransformPluginOptions<G>\n): Plugin<WorldConfigFrom<TransformComponentTypes>, EmptyConfig, 'transform-propagation', G> {\n\tconst {\n\t\tsystemGroup = 'transform',\n\t\tpriority = 500,\n\t\tphase = 'postUpdate',\n\t} = options ?? {};\n\n\treturn definePlugin<WorldConfigFrom<TransformComponentTypes>, EmptyConfig, 'transform-propagation', G>({\n\t\tid: 'transform',\n\t\tinstall(world) {\n\t\t\t// localTransform requires worldTransform — initialize from localTransform values\n\t\t\tworld.registerRequired('localTransform', 'worldTransform', (lt) => ({\n\t\t\t\tx: lt.x, y: lt.y, rotation: lt.rotation, scaleX: lt.scaleX, scaleY: lt.scaleY,\n\t\t\t}));\n\n\t\t\tworld\n\t\t\t\t.addSystem('transform-propagation')\n\t\t\t\t.setPriority(priority)\n\t\t\t\t.inPhase(phase)\n\t\t\t\t.inGroup(systemGroup)\n\t\t\t\t.setProcess(({ ecs }) => {\n\t\t\t\t\tpropagateTransforms(ecs);\n\t\t\t\t});\n\t\t},\n\t});\n}\n\n/**\n * Propagate transforms through the hierarchy.\n * Parent-first traversal ensures parents are computed before children.\n *\n * Runs unconditionally for all entities with transforms — user code can\n * freely mutate localTransform without needing to call markChanged.\n * Marks worldTransform as changed so downstream systems (e.g. renderer\n * sync) pick up the updated values.\n */\nfunction propagateTransforms(ecs: ECSpresso<WorldConfigFrom<TransformComponentTypes>>): void {\n\tconst em = ecs.entityManager;\n\n\t// Use parent-first traversal for entities in hierarchy\n\tecs.forEachInHierarchy((entityId, parentId) => {\n\t\tconst localTransform = em.getComponent(entityId, 'localTransform');\n\t\tconst worldTransform = em.getComponent(entityId, 'worldTransform');\n\n\t\tif (!localTransform || !worldTransform) return;\n\n\t\tif (parentId === null) {\n\t\t\t// Root entity: world transform equals local transform\n\t\t\tcopyTransform(localTransform, worldTransform);\n\t\t} else {\n\t\t\t// Child entity: combine with parent's world transform\n\t\t\tconst parentWorld = em.getComponent(parentId, 'worldTransform');\n\t\t\tif (parentWorld) {\n\t\t\t\tcombineTransforms(parentWorld, localTransform, worldTransform);\n\t\t\t} else {\n\t\t\t\t// Parent has no world transform, treat as root\n\t\t\t\tcopyTransform(localTransform, worldTransform);\n\t\t\t}\n\t\t}\n\n\t\tecs.markChanged(entityId, 'worldTransform');\n\t});\n\n\t// Process orphaned entities (not in hierarchy but have transforms)\n\tconst orphanedEntities = ecs.getEntitiesWithQuery(['localTransform', 'worldTransform']);\n\tfor (const entity of orphanedEntities) {\n\t\tconst parentId = ecs.getParent(entity.id);\n\t\t// Only process if truly orphaned (no parent and not a root with children)\n\t\tif (parentId === null && ecs.getChildren(entity.id).length === 0) {\n\t\t\tconst { localTransform, worldTransform } = entity.components;\n\t\t\tcopyTransform(localTransform, worldTransform);\n\t\t\tecs.markChanged(entity.id, 'worldTransform');\n\t\t}\n\t}\n}\n\n/**\n * Copy transform values from source to destination.\n */\nfunction copyTransform(src: LocalTransform, dest: WorldTransform): void {\n\tdest.x = src.x;\n\tdest.y = src.y;\n\tdest.rotation = src.rotation;\n\tdest.scaleX = src.scaleX;\n\tdest.scaleY = src.scaleY;\n}\n\n/**\n * Combine parent world transform with child local transform into child world transform.\n */\nfunction combineTransforms(\n\tparent: WorldTransform,\n\tlocal: LocalTransform,\n\tworld: WorldTransform\n): void {\n\t// Apply parent's scale to local position\n\tconst scaledLocalX = local.x * parent.scaleX;\n\tconst scaledLocalY = local.y * parent.scaleY;\n\n\t// Rotate local position by parent's rotation\n\tconst cos = Math.cos(parent.rotation);\n\tconst sin = Math.sin(parent.rotation);\n\tconst rotatedX = scaledLocalX * cos - scaledLocalY * sin;\n\tconst rotatedY = scaledLocalX * sin + scaledLocalY * cos;\n\n\t// Add to parent's position\n\tworld.x = parent.x + rotatedX;\n\tworld.y = parent.y + rotatedY;\n\tworld.rotation = parent.rotation + local.rotation;\n\tworld.scaleX = parent.scaleX * local.scaleX;\n\tworld.scaleY = parent.scaleY * local.scaleY;\n}\n"
|
|
6
6
|
],
|
|
7
|
-
"mappings": "
|
|
8
|
-
"debugId": "
|
|
7
|
+
"mappings": "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",
|
|
8
|
+
"debugId": "C63DD170F03CB2AB64756E2164756E21",
|
|
9
9
|
"names": []
|
|
10
10
|
}
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
var{defineProperty:$,getOwnPropertyNames:b,getOwnPropertyDescriptor:h}=Object,E=Object.prototype.hasOwnProperty;function K(z){return this[z]}var C=(z)=>{var D=(q??=new WeakMap).get(z),H;if(D)return D;if(D=$({},"__esModule",{value:!0}),z&&typeof z==="object"||typeof z==="function"){for(var J of b(z))if(!E.call(D,J))$(D,J,{get:K.bind(z,J),enumerable:!(H=h(z,J))||H.enumerable})}return q.set(z,D),D},q;var T=(z)=>z;function A(z,D){this[z]=T.bind(null,D)}var d=(z,D)=>{for(var H in D)$(z,H,{get:D[H],enumerable:!0,configurable:!0,set:A.bind(D,H)})};var m=(z,D)=>()=>(z&&(D=z(z=0)),D);var l=((z)=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(z,{get:(D,H)=>(typeof require<"u"?require:D)[H]}):z)(function(z){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+z+'" is not supported')});import{definePlugin as x}from"ecspresso";function G(z){return z}var P=1.70158,c=P*1.525,w=P+1;var r=2*Math.PI/3,i=2*Math.PI/4.5;function _(z,D,H,J,M){let{from:N,easing:U=G,loop:W="once",loops:Y=1,onComplete:X}=M??{};return{tween:{steps:[{targets:[{component:z,path:D.split("."),from:N??null,to:H}],duration:J,easing:U}],currentStep:0,elapsed:0,loop:W,totalLoops:Y,completedLoops:0,direction:1,state:"pending",onComplete:X,justFinished:!1}}}function B(z,D){let{loop:H="once",loops:J=1,onComplete:M}=D??{};return{tween:{steps:z.map((N)=>({targets:N.targets.map((U)=>({component:U.component,path:U.field.split("."),from:U.from??null,to:U.to})),duration:N.duration,easing:N.easing??G})),currentStep:0,elapsed:0,loop:H,totalLoops:J,completedLoops:0,direction:1,state:"pending",onComplete:M,justFinished:!1}}}function s(z){return{createTween:_,createTweenSequence:B}}var V={parent:{},key:""};function j(z,D){let H=D.length-1,J=z;for(let N=0;N<H;N++){let U=D[N];if(U===void 0)return null;let W=J[U];if(W===null||W===void 0||typeof W!=="object")return null;J=W}let M=D[H];if(M===void 0)return null;if(!(M in J))return null;return V.parent=J,V.key=M,V}function F(z,D){let H=j(z,D);if(!H)return null;let J=H.parent[H.key];return typeof J==="number"?J:null}function Q(z,D,H){let J=j(z,D);if(!J)return!1;return J.parent[J.key]=H,!0}function O(z,D,H){return z<D?D:z>H?H:z}function v(z,D){for(let H of z.steps)for(let J of H.targets){if(J.from!==null)continue;let M=D[J.component];if(!M||typeof M!=="object")continue;let N=F(M,J.path);if(N!==null)J.from=N;else J.from=0}}function S(z,D,H,J,M){let N=z.easing(D);for(let U of z.targets){let W=H[U.component];if(!W||typeof W!=="object")continue;let Y=U.from??0,X=Y+(U.to-Y)*N;if(Q(W,U.path,X))M.markChanged(J,U.component)}}function k(z,D,H,J){for(let M of z.targets){let N=D[M.component];if(!N||typeof N!=="object")continue;if(Q(N,M.path,M.to))J.markChanged(H,M.component)}}function f(z){for(let D of z.steps)for(let H of D.targets){let J=H.from??0;H.from=H.to,H.to=J}}function L(z,D,H){z.state="complete",z.justFinished=!0,z.onComplete?.({entityId:D,stepCount:z.steps.length}),H.commands.removeComponent(D,"tween")}function g(z,D,H){if(z.completedLoops++,z.loop==="once")return L(z,D,H),!1;if(z.totalLoops>0&&z.completedLoops>=z.totalLoops)return L(z,D,H),!1;if(z.loop==="yoyo")z.direction=z.direction===1?-1:1,f(z);return z.currentStep=0,z.elapsed>0}function R(z,D,H,J){let M=z.currentStep+1;if(M<z.steps.length){z.currentStep=M;let N=z.steps[M];if(N)for(let U of N.targets){if(U.from!==null)continue;let W=D[U.component];if(!W||typeof W!=="object")continue;let Y=F(W,U.path);U.from=Y??0}return!0}return g(z,H,J)}function I(z,D,H,J){while(!0){let M=z.steps[z.currentStep];if(!M)return;if(M.duration<=0){if(k(M,D,H,J),z.elapsed=0,!R(z,D,H,J))return;continue}if(z.elapsed>=M.duration){k(M,D,H,J);let U=z.elapsed-M.duration;if(z.elapsed=U,!R(z,D,H,J))return;continue}let N=O(z.elapsed/M.duration,0,1);S(M,N,D,H,J);return}}function n(z){let{systemGroup:D="tweens",priority:H=0,phase:J="update"}=z??{};return x({id:"tweens",install(M){M.addSystem("tween-update").setPriority(H).inPhase(J).inGroup(D).addQuery("tweens",{with:["tween"]}).setProcess(({queries:N,dt:U,ecs:W})=>{for(let Y of N.tweens){let X=Y.components.tween,Z=Y.components;if(X.justFinished){X.justFinished=!1;continue}if(X.state==="complete")continue;if(X.state==="pending")v(X,Z),X.state="active";if(!X.steps[X.currentStep])continue;X.elapsed+=U,I(X,Z,Y.id,W)}})}})}export{B as createTweenSequence,n as createTweenPlugin,s as createTweenHelpers,_ as createTween};
|
|
2
|
+
|
|
3
|
+
//# debugId=337A12D65456A62F64756E2164756E21
|
|
4
|
+
//# sourceMappingURL=tween.js.map
|
|
@@ -5,7 +5,7 @@
|
|
|
5
5
|
"/**\n * Tween Plugin for ECSpresso\n *\n * Declarative property animation within the ECS. Tween any numeric component\n * field over time with standard easing functions, sequences, and completion events.\n */\n\nimport { definePlugin, type Plugin, type BasePluginOptions } from 'ecspresso';\nimport type { ComponentsOfWorld, AnyECSpresso } from 'ecspresso';\nimport type { WorldConfigFrom, EmptyConfig } from '../type-utils';\nimport { linear, type EasingFn } from '../utils/easing';\n\n// ==================== Event Types ====================\n\n/**\n * Data structure published when a tween completes.\n * Use this type when defining tween completion events in your EventTypes interface.\n */\nexport interface TweenEventData {\n\t/** The entity ID the tween belongs to */\n\tentityId: number;\n\t/** Number of steps in the tween */\n\tstepCount: number;\n}\n\n\n// ==================== Component Types ====================\n\nexport interface TweenTarget {\n\t/** Component name on the entity */\n\tcomponent: string;\n\t/** Pre-split field path (e.g., ['position', 'x']) */\n\tpath: readonly string[];\n\t/** Starting value. null = resolve from current value on first tick */\n\tfrom: number | null;\n\t/** Target value */\n\tto: number;\n}\n\nexport interface TweenStep {\n\ttargets: TweenTarget[];\n\tduration: number;\n\teasing: EasingFn;\n}\n\nexport interface Tween {\n\tsteps: TweenStep[];\n\tcurrentStep: number;\n\telapsed: number;\n\tloop: LoopMode;\n\ttotalLoops: number;\n\tcompletedLoops: number;\n\tdirection: 1 | -1;\n\tstate: 'pending' | 'active' | 'complete';\n\tonComplete?: (data: TweenEventData) => void;\n\tjustFinished: boolean;\n}\n\nexport type LoopMode = 'once' | 'loop' | 'yoyo';\n\n/**\n * Component types provided by the tween plugin.\n */\nexport interface TweenComponentTypes {\n\ttween: Tween;\n}\n\n// ==================== Plugin Options ====================\n\nexport interface TweenPluginOptions<G extends string = 'tweens'> extends BasePluginOptions<G> {}\n\n// ==================== Helper Functions ====================\n\nexport interface TweenOptions {\n\t/** Explicit starting value (default: captures current value on first tick) */\n\tfrom?: number;\n\t/** Easing function (default: linear) */\n\teasing?: EasingFn;\n\t/** Loop mode (default: 'once') */\n\tloop?: LoopMode;\n\t/** Number of loops. -1 = infinite (default: 1) */\n\tloops?: number;\n\t/** Callback invoked when tween completes */\n\tonComplete?: (data: TweenEventData) => void;\n}\n\n/**\n * Create a single-target tween component.\n *\n * @param component Component name on the entity\n * @param field Field path (dot-separated for nested, e.g. 'position.x')\n * @param to Target value\n * @param duration Duration in seconds\n * @param options Optional configuration\n * @returns Component object suitable for spreading into spawn()\n */\nexport function createTween(\n\tcomponent: string,\n\tfield: string,\n\tto: number,\n\tduration: number,\n\toptions?: TweenOptions,\n): Pick<TweenComponentTypes, 'tween'> {\n\tconst {\n\t\tfrom,\n\t\teasing = linear,\n\t\tloop = 'once',\n\t\tloops = 1,\n\t\tonComplete,\n\t} = options ?? {};\n\n\treturn {\n\t\ttween: {\n\t\t\tsteps: [{\n\t\t\t\ttargets: [{\n\t\t\t\t\tcomponent,\n\t\t\t\t\tpath: field.split('.'),\n\t\t\t\t\tfrom: from ?? null,\n\t\t\t\t\tto,\n\t\t\t\t}],\n\t\t\t\tduration,\n\t\t\t\teasing,\n\t\t\t}],\n\t\t\tcurrentStep: 0,\n\t\t\telapsed: 0,\n\t\t\tloop,\n\t\t\ttotalLoops: loops,\n\t\t\tcompletedLoops: 0,\n\t\t\tdirection: 1,\n\t\t\tstate: 'pending',\n\t\t\tonComplete,\n\t\t\tjustFinished: false,\n\t\t},\n\t};\n}\n\nexport interface TweenSequenceStepInput {\n\ttargets: ReadonlyArray<{\n\t\tcomponent: string;\n\t\tfield: string;\n\t\tto: number;\n\t\tfrom?: number;\n\t}>;\n\tduration: number;\n\teasing?: EasingFn;\n}\n\nexport interface TweenSequenceOptions {\n\t/** Loop mode (default: 'once') */\n\tloop?: LoopMode;\n\t/** Number of loops. -1 = infinite (default: 1) */\n\tloops?: number;\n\t/** Callback invoked when tween completes */\n\tonComplete?: (data: TweenEventData) => void;\n}\n\n/**\n * Create a multi-step tween sequence. Each step can have parallel targets.\n *\n * @param steps Array of step definitions\n * @param options Optional configuration\n * @returns Component object suitable for spreading into spawn()\n */\nexport function createTweenSequence(\n\tsteps: ReadonlyArray<TweenSequenceStepInput>,\n\toptions?: TweenSequenceOptions,\n): Pick<TweenComponentTypes, 'tween'> {\n\tconst {\n\t\tloop = 'once',\n\t\tloops = 1,\n\t\tonComplete,\n\t} = options ?? {};\n\n\treturn {\n\t\ttween: {\n\t\t\tsteps: steps.map((step) => ({\n\t\t\t\ttargets: step.targets.map((target) => ({\n\t\t\t\t\tcomponent: target.component,\n\t\t\t\t\tpath: target.field.split('.'),\n\t\t\t\t\tfrom: target.from ?? null,\n\t\t\t\t\tto: target.to,\n\t\t\t\t})),\n\t\t\t\tduration: step.duration,\n\t\t\t\teasing: step.easing ?? linear,\n\t\t\t})),\n\t\t\tcurrentStep: 0,\n\t\t\telapsed: 0,\n\t\t\tloop,\n\t\t\ttotalLoops: loops,\n\t\t\tcompletedLoops: 0,\n\t\t\tdirection: 1,\n\t\t\tstate: 'pending',\n\t\t\tonComplete,\n\t\t\tjustFinished: false,\n\t\t},\n\t};\n}\n\n// ==================== Kit Types ====================\n\n/**\n * Recursively produce a union of dot-separated paths that resolve to `number`\n * within type T. Depth-limited to 4 levels to prevent TS recursion errors.\n *\n * @example\n * NumericPaths<{ x: number; y: number }> // 'x' | 'y'\n * NumericPaths<{ position: { x: number }; rotation: number }> // 'position.x' | 'rotation'\n */\nexport type NumericPaths<T, Depth extends readonly unknown[] = []> =\n\tDepth['length'] extends 4 ? never :\n\tT extends readonly unknown[] ? never :\n\tT extends Record<string, unknown>\n\t\t? { [K in keyof T & string]:\n\t\t\tNonNullable<T[K]> extends number\n\t\t\t\t? K\n\t\t\t\t: NonNullable<T[K]> extends readonly unknown[]\n\t\t\t\t\t? never\n\t\t\t\t\t: NonNullable<T[K]> extends Record<string, unknown>\n\t\t\t\t\t\t? `${K}.${NumericPaths<NonNullable<T[K]>, [...Depth, unknown]>}`\n\t\t\t\t\t\t: never\n\t\t}[keyof T & string]\n\t\t: never;\n\n/**\n * Discriminated union over component names: each variant constrains `field`\n * to the numeric paths of that component. TS narrows inline object literals\n * by `component` discriminant — zero runtime overhead.\n */\nexport type TypedTweenTargetInput<C extends Record<string, any>> = {\n\t[K in keyof C & string]: {\n\t\tcomponent: K;\n\t\tfield: NumericPaths<C[K]>;\n\t\tto: number;\n\t\tfrom?: number;\n\t}\n}[keyof C & string];\n\nexport interface TypedTweenSequenceStepInput<C extends Record<string, any>> {\n\ttargets: ReadonlyArray<TypedTweenTargetInput<C>>;\n\tduration: number;\n\teasing?: EasingFn;\n}\n\nexport interface TweenHelpers<W extends AnyECSpresso> {\n\tcreateTween: <K extends keyof ComponentsOfWorld<W> & string>(\n\t\tcomponent: K,\n\t\tfield: NumericPaths<ComponentsOfWorld<W>[K]>,\n\t\tto: number,\n\t\tduration: number,\n\t\toptions?: {\n\t\t\tfrom?: number;\n\t\t\teasing?: EasingFn;\n\t\t\tloop?: LoopMode;\n\t\t\tloops?: number;\n\t\t\tonComplete?: (data: TweenEventData) => void;\n\t\t},\n\t) => Pick<TweenComponentTypes, 'tween'>;\n\tcreateTweenSequence: (\n\t\tsteps: ReadonlyArray<TypedTweenSequenceStepInput<ComponentsOfWorld<W>>>,\n\t\toptions?: {\n\t\t\tloop?: LoopMode;\n\t\t\tloops?: number;\n\t\t\tonComplete?: (data: TweenEventData) => void;\n\t\t},\n\t) => Pick<TweenComponentTypes, 'tween'>;\n}\n\nexport function createTweenHelpers<W extends AnyECSpresso>(_world?: W): TweenHelpers<W> {\n\treturn {\n\t\tcreateTween: createTween as TweenHelpers<W>['createTween'],\n\t\tcreateTweenSequence: createTweenSequence as TweenHelpers<W>['createTweenSequence'],\n\t};\n}\n\n// ==================== Field Path Resolution ====================\n\n/**\n * Module-scoped mutable result to avoid per-call allocation in hot path.\n */\nconst _fieldRef: { parent: Record<string, unknown>; key: string } = { parent: {} as Record<string, unknown>, key: '' };\n\n/**\n * Traverse an object by path segments. Returns the parent object and final key\n * for read/write, or null if any segment is missing.\n */\nfunction resolveField(obj: Record<string, unknown>, path: readonly string[]): typeof _fieldRef | null {\n\tconst lastIdx = path.length - 1;\n\tlet current: Record<string, unknown> = obj;\n\n\tfor (let i = 0; i < lastIdx; i++) {\n\t\tconst segment = path[i];\n\t\tif (segment === undefined) return null;\n\t\tconst next = current[segment];\n\t\tif (next === null || next === undefined || typeof next !== 'object') return null;\n\t\tcurrent = next as Record<string, unknown>;\n\t}\n\n\tconst finalKey = path[lastIdx];\n\tif (finalKey === undefined) return null;\n\tif (!(finalKey in current)) return null;\n\n\t_fieldRef.parent = current;\n\t_fieldRef.key = finalKey;\n\treturn _fieldRef;\n}\n\nfunction readField(obj: Record<string, unknown>, path: readonly string[]): number | null {\n\tconst ref = resolveField(obj, path);\n\tif (!ref) return null;\n\tconst val = ref.parent[ref.key];\n\treturn typeof val === 'number' ? val : null;\n}\n\nfunction writeField(obj: Record<string, unknown>, path: readonly string[], value: number): boolean {\n\tconst ref = resolveField(obj, path);\n\tif (!ref) return false;\n\tref.parent[ref.key] = value;\n\treturn true;\n}\n\n// ==================== System Logic ====================\n\nfunction clamp(value: number, min: number, max: number): number {\n\treturn value < min ? min : value > max ? max : value;\n}\n\n/**\n * Resolve all null `from` values by reading current component field values.\n */\nfunction resolveFromValues(\n\ttween: Tween,\n\tentityComponents: Record<string, unknown>,\n): void {\n\tfor (const step of tween.steps) {\n\t\tfor (const target of step.targets) {\n\t\t\tif (target.from !== null) continue;\n\t\t\tconst comp = entityComponents[target.component];\n\t\t\tif (!comp || typeof comp !== 'object') continue;\n\t\t\tconst val = readField(comp as Record<string, unknown>, target.path);\n\t\t\tif (val !== null) {\n\t\t\t\ttarget.from = val;\n\t\t\t} else {\n\t\t\t\ttarget.from = 0;\n\t\t\t}\n\t\t}\n\t}\n}\n\n/**\n * Apply interpolation for a step's targets at a given progress.\n */\nfunction applyStep(\n\tstep: TweenStep,\n\tprogress: number,\n\tentityComponents: Record<string, unknown>,\n\tentityId: number,\n\tecs: { markChanged: (entityId: number, componentName: any) => void },\n): void {\n\tconst easedT = step.easing(progress);\n\n\tfor (const target of step.targets) {\n\t\tconst comp = entityComponents[target.component];\n\t\tif (!comp || typeof comp !== 'object') continue;\n\t\tconst from = target.from ?? 0;\n\t\tconst value = from + (target.to - from) * easedT;\n\t\tconst written = writeField(comp as Record<string, unknown>, target.path, value);\n\t\tif (written) {\n\t\t\tecs.markChanged(entityId, target.component);\n\t\t}\n\t}\n}\n\n/**\n * Snap all targets in a step to their final values (from or to depending on direction).\n */\nfunction snapStepToEnd(\n\tstep: TweenStep,\n\tentityComponents: Record<string, unknown>,\n\tentityId: number,\n\tecs: { markChanged: (entityId: number, componentName: any) => void },\n): void {\n\tfor (const target of step.targets) {\n\t\tconst comp = entityComponents[target.component];\n\t\tif (!comp || typeof comp !== 'object') continue;\n\t\tconst written = writeField(comp as Record<string, unknown>, target.path, target.to);\n\t\tif (written) {\n\t\t\tecs.markChanged(entityId, target.component);\n\t\t}\n\t}\n}\n\n/**\n * Reverse all from/to values in every step (for yoyo).\n */\nfunction reverseAllTargets(tween: Tween): void {\n\tfor (const step of tween.steps) {\n\t\tfor (const target of step.targets) {\n\t\t\tconst tmp = target.from ?? 0;\n\t\t\ttarget.from = target.to;\n\t\t\ttarget.to = tmp;\n\t\t}\n\t}\n}\n\n// ==================== Tween Processing Helpers ====================\n\ntype TweenEcs = { markChanged: (entityId: number, componentName: any) => void; commands: { removeComponent: (entityId: number, componentName: any) => void } };\n\nfunction completeTween(\n\ttween: Tween,\n\tentityId: number,\n\tecs: { commands: { removeComponent: (entityId: number, componentName: any) => void } },\n): void {\n\ttween.state = 'complete';\n\ttween.justFinished = true;\n\n\ttween.onComplete?.({ entityId, stepCount: tween.steps.length });\n\tecs.commands.removeComponent(entityId, 'tween');\n}\n\nfunction handleTweenEnd(\n\ttween: Tween,\n\tentityId: number,\n\tecs: TweenEcs,\n): boolean {\n\ttween.completedLoops++;\n\n\tif (tween.loop === 'once') {\n\t\tcompleteTween(tween, entityId, ecs);\n\t\treturn false;\n\t}\n\n\t// Check if finite loops exhausted\n\tif (tween.totalLoops > 0 && tween.completedLoops >= tween.totalLoops) {\n\t\tcompleteTween(tween, entityId, ecs);\n\t\treturn false;\n\t}\n\n\t// Loop continues\n\tif (tween.loop === 'yoyo') {\n\t\ttween.direction = tween.direction === 1 ? -1 : 1;\n\t\treverseAllTargets(tween);\n\t}\n\n\ttween.currentStep = 0;\n\n\t// For 'loop' mode, from values stay as-is so the animation replays identically.\n\t// For 'yoyo' mode, reverseAllTargets already swapped from/to.\n\n\treturn tween.elapsed > 0;\n}\n\n/**\n * Advance to next step. Returns true if there's more work to process,\n * false if the tween has completed or looped.\n */\nfunction advanceStep(\n\ttween: Tween,\n\tentityComponents: Record<string, unknown>,\n\tentityId: number,\n\tecs: TweenEcs,\n): boolean {\n\tconst nextStep = tween.currentStep + 1;\n\n\tif (nextStep < tween.steps.length) {\n\t\t// More steps — resolve from values for next step and continue\n\t\ttween.currentStep = nextStep;\n\t\tconst step = tween.steps[nextStep];\n\t\tif (step) {\n\t\t\tfor (const target of step.targets) {\n\t\t\t\tif (target.from !== null) continue;\n\t\t\t\tconst comp = entityComponents[target.component];\n\t\t\t\tif (!comp || typeof comp !== 'object') continue;\n\t\t\t\tconst val = readField(comp as Record<string, unknown>, target.path);\n\t\t\t\ttarget.from = val ?? 0;\n\t\t\t}\n\t\t}\n\t\treturn true;\n\t}\n\n\t// All steps done — handle loop/complete\n\treturn handleTweenEnd(tween, entityId, ecs);\n}\n\nfunction processTweenProgress(\n\ttween: Tween,\n\tentityComponents: Record<string, unknown>,\n\tentityId: number,\n\tecs: TweenEcs,\n): void {\n\t// eslint-disable-next-line no-constant-condition\n\twhile (true) {\n\t\tconst currentStep = tween.steps[tween.currentStep];\n\t\tif (!currentStep) return;\n\n\t\t// Zero-duration steps complete immediately\n\t\tif (currentStep.duration <= 0) {\n\t\t\tsnapStepToEnd(currentStep, entityComponents, entityId, ecs);\n\t\t\ttween.elapsed = 0;\n\n\t\t\tif (!advanceStep(tween, entityComponents, entityId, ecs)) return;\n\t\t\tcontinue;\n\t\t}\n\n\t\tif (tween.elapsed >= currentStep.duration) {\n\t\t\t// Step complete — snap to end and carry overflow\n\t\t\tsnapStepToEnd(currentStep, entityComponents, entityId, ecs);\n\t\t\tconst overflow = tween.elapsed - currentStep.duration;\n\t\t\ttween.elapsed = overflow;\n\n\t\t\tif (!advanceStep(tween, entityComponents, entityId, ecs)) return;\n\t\t\tcontinue;\n\t\t}\n\n\t\t// Step in progress — interpolate\n\t\tconst progress = clamp(tween.elapsed / currentStep.duration, 0, 1);\n\t\tapplyStep(currentStep, progress, entityComponents, entityId, ecs);\n\t\treturn;\n\t}\n}\n\n// ==================== Plugin Factory ====================\n\n/**\n * Create a tween plugin for ECSpresso.\n *\n * This plugin provides:\n * - Tween system that processes all tween components each frame\n * - Support for single-field, multi-target, and multi-step sequences\n * - 31 standard easing functions\n * - Loop modes: once, loop, yoyo\n * - `justFinished` flag for one-frame completion detection\n * - `onComplete` callback on completion\n * - Change detection via markChanged\n */\nexport function createTweenPlugin<G extends string = 'tweens'>(\n\toptions?: TweenPluginOptions<G>\n): Plugin<WorldConfigFrom<TweenComponentTypes>, EmptyConfig, 'tween-update', G> {\n\tconst {\n\t\tsystemGroup = 'tweens',\n\t\tpriority = 0,\n\t\tphase = 'update',\n\t} = options ?? {};\n\n\treturn definePlugin<WorldConfigFrom<TweenComponentTypes>, EmptyConfig, 'tween-update', G>({\n\t\tid: 'tweens',\n\t\tinstall(world) {\n\t\t\tworld\n\t\t\t\t.addSystem('tween-update')\n\t\t\t\t.setPriority(priority)\n\t\t\t\t.inPhase(phase)\n\t\t\t\t.inGroup(systemGroup)\n\t\t\t\t.addQuery('tweens', {\n\t\t\t\t\twith: ['tween'],\n\t\t\t\t})\n\t\t\t\t.setProcess(({ queries, dt, ecs }) => {\n\t\t\t\t\tfor (const entity of queries.tweens) {\n\t\t\t\t\t\tconst tween = entity.components.tween as Tween;\n\t\t\t\t\t\tconst entityComponents = entity.components as Record<string, unknown>;\n\n\t\t\t\t\t\t// Reset justFinished flag from previous frame\n\t\t\t\t\t\tif (tween.justFinished) {\n\t\t\t\t\t\t\ttween.justFinished = false;\n\t\t\t\t\t\t\t// Component removal was queued, skip processing\n\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\t// Skip completed tweens\n\t\t\t\t\t\tif (tween.state === 'complete') continue;\n\n\t\t\t\t\t\t// Resolve pending state: capture null from values\n\t\t\t\t\t\tif (tween.state === 'pending') {\n\t\t\t\t\t\t\tresolveFromValues(tween, entityComponents);\n\t\t\t\t\t\t\ttween.state = 'active';\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\t// Process active tween\n\t\t\t\t\t\tconst currentStep = tween.steps[tween.currentStep];\n\t\t\t\t\t\tif (!currentStep) continue;\n\n\t\t\t\t\t\ttween.elapsed += dt;\n\n\t\t\t\t\t\tprocessTweenProgress(tween, entityComponents, entity.id, ecs);\n\t\t\t\t\t}\n\t\t\t\t});\n\t\t},\n\t});\n}\n",
|
|
6
6
|
"/**\n * Easing Functions\n *\n * 31 standard easing functions for animation. Pure math, no dependencies.\n */\n\nexport type EasingFn = (t: number) => number;\n\nexport function linear(t: number): number {\n\treturn t;\n}\n\n// Quad\nexport function easeInQuad(t: number): number {\n\treturn t * t;\n}\n\nexport function easeOutQuad(t: number): number {\n\treturn t * (2 - t);\n}\n\nexport function easeInOutQuad(t: number): number {\n\treturn t < 0.5\n\t\t? 2 * t * t\n\t\t: -1 + (4 - 2 * t) * t;\n}\n\n// Cubic\nexport function easeInCubic(t: number): number {\n\treturn t * t * t;\n}\n\nexport function easeOutCubic(t: number): number {\n\tconst t1 = t - 1;\n\treturn t1 * t1 * t1 + 1;\n}\n\nexport function easeInOutCubic(t: number): number {\n\treturn t < 0.5\n\t\t? 4 * t * t * t\n\t\t: 1 + (t - 1) * (2 * t - 2) * (2 * t - 2);\n}\n\n// Quart\nexport function easeInQuart(t: number): number {\n\treturn t * t * t * t;\n}\n\nexport function easeOutQuart(t: number): number {\n\tconst t1 = t - 1;\n\treturn 1 - t1 * t1 * t1 * t1;\n}\n\nexport function easeInOutQuart(t: number): number {\n\treturn t < 0.5\n\t\t? 8 * t * t * t * t\n\t\t: 1 - 8 * (t - 1) * (t - 1) * (t - 1) * (t - 1);\n}\n\n// Quint\nexport function easeInQuint(t: number): number {\n\treturn t * t * t * t * t;\n}\n\nexport function easeOutQuint(t: number): number {\n\tconst t1 = t - 1;\n\treturn 1 + t1 * t1 * t1 * t1 * t1;\n}\n\nexport function easeInOutQuint(t: number): number {\n\treturn t < 0.5\n\t\t? 16 * t * t * t * t * t\n\t\t: 1 + 16 * (t - 1) * (t - 1) * (t - 1) * (t - 1) * (t - 1);\n}\n\n// Sine\nexport function easeInSine(t: number): number {\n\treturn 1 - Math.cos((t * Math.PI) / 2);\n}\n\nexport function easeOutSine(t: number): number {\n\treturn Math.sin((t * Math.PI) / 2);\n}\n\nexport function easeInOutSine(t: number): number {\n\treturn -(Math.cos(Math.PI * t) - 1) / 2;\n}\n\n// Expo\nexport function easeInExpo(t: number): number {\n\treturn t === 0 ? 0 : Math.pow(2, 10 * (t - 1));\n}\n\nexport function easeOutExpo(t: number): number {\n\treturn t === 1 ? 1 : 1 - Math.pow(2, -10 * t);\n}\n\nexport function easeInOutExpo(t: number): number {\n\tif (t === 0) return 0;\n\tif (t === 1) return 1;\n\treturn t < 0.5\n\t\t? Math.pow(2, 20 * t - 10) / 2\n\t\t: (2 - Math.pow(2, -20 * t + 10)) / 2;\n}\n\n// Circ\nexport function easeInCirc(t: number): number {\n\treturn 1 - Math.sqrt(1 - t * t);\n}\n\nexport function easeOutCirc(t: number): number {\n\tconst t1 = t - 1;\n\treturn Math.sqrt(1 - t1 * t1);\n}\n\nexport function easeInOutCirc(t: number): number {\n\treturn t < 0.5\n\t\t? (1 - Math.sqrt(1 - 4 * t * t)) / 2\n\t\t: (Math.sqrt(1 - (-2 * t + 2) * (-2 * t + 2)) + 1) / 2;\n}\n\n// Back\nconst BACK_C1 = 1.70158;\nconst BACK_C2 = BACK_C1 * 1.525;\nconst BACK_C3 = BACK_C1 + 1;\n\nexport function easeInBack(t: number): number {\n\treturn BACK_C3 * t * t * t - BACK_C1 * t * t;\n}\n\nexport function easeOutBack(t: number): number {\n\tconst t1 = t - 1;\n\treturn 1 + BACK_C3 * t1 * t1 * t1 + BACK_C1 * t1 * t1;\n}\n\nexport function easeInOutBack(t: number): number {\n\treturn t < 0.5\n\t\t? ((2 * t) * (2 * t) * ((BACK_C2 + 1) * 2 * t - BACK_C2)) / 2\n\t\t: ((2 * t - 2) * (2 * t - 2) * ((BACK_C2 + 1) * (t * 2 - 2) + BACK_C2) + 2) / 2;\n}\n\n// Elastic\nconst ELASTIC_C4 = (2 * Math.PI) / 3;\nconst ELASTIC_C5 = (2 * Math.PI) / 4.5;\n\nexport function easeInElastic(t: number): number {\n\tif (t === 0) return 0;\n\tif (t === 1) return 1;\n\treturn -Math.pow(2, 10 * t - 10) * Math.sin((10 * t - 10.75) * ELASTIC_C4);\n}\n\nexport function easeOutElastic(t: number): number {\n\tif (t === 0) return 0;\n\tif (t === 1) return 1;\n\treturn Math.pow(2, -10 * t) * Math.sin((10 * t - 0.75) * ELASTIC_C4) + 1;\n}\n\nexport function easeInOutElastic(t: number): number {\n\tif (t === 0) return 0;\n\tif (t === 1) return 1;\n\treturn t < 0.5\n\t\t? -(Math.pow(2, 20 * t - 10) * Math.sin((20 * t - 11.125) * ELASTIC_C5)) / 2\n\t\t: (Math.pow(2, -20 * t + 10) * Math.sin((20 * t - 11.125) * ELASTIC_C5)) / 2 + 1;\n}\n\n// Bounce\nexport function easeOutBounce(t: number): number {\n\tconst n1 = 7.5625;\n\tconst d1 = 2.75;\n\n\tif (t < 1 / d1) {\n\t\treturn n1 * t * t;\n\t} else if (t < 2 / d1) {\n\t\tconst t1 = t - 1.5 / d1;\n\t\treturn n1 * t1 * t1 + 0.75;\n\t} else if (t < 2.5 / d1) {\n\t\tconst t1 = t - 2.25 / d1;\n\t\treturn n1 * t1 * t1 + 0.9375;\n\t} else {\n\t\tconst t1 = t - 2.625 / d1;\n\t\treturn n1 * t1 * t1 + 0.984375;\n\t}\n}\n\nexport function easeInBounce(t: number): number {\n\treturn 1 - easeOutBounce(1 - t);\n}\n\nexport function easeInOutBounce(t: number): number {\n\treturn t < 0.5\n\t\t? (1 - easeOutBounce(1 - 2 * t)) / 2\n\t\t: (1 + easeOutBounce(2 * t - 1)) / 2;\n}\n\n/** Runtime lookup of all easing functions by name */\nexport const easings = {\n\tlinear,\n\teaseInQuad,\n\teaseOutQuad,\n\teaseInOutQuad,\n\teaseInCubic,\n\teaseOutCubic,\n\teaseInOutCubic,\n\teaseInQuart,\n\teaseOutQuart,\n\teaseInOutQuart,\n\teaseInQuint,\n\teaseOutQuint,\n\teaseInOutQuint,\n\teaseInSine,\n\teaseOutSine,\n\teaseInOutSine,\n\teaseInExpo,\n\teaseOutExpo,\n\teaseInOutExpo,\n\teaseInCirc,\n\teaseOutCirc,\n\teaseInOutCirc,\n\teaseInBack,\n\teaseOutBack,\n\teaseInOutBack,\n\teaseInElastic,\n\teaseOutElastic,\n\teaseInOutElastic,\n\teaseInBounce,\n\teaseOutBounce,\n\teaseInOutBounce,\n} as const;\n"
|
|
7
7
|
],
|
|
8
|
-
"mappings": "
|
|
9
|
-
"debugId": "
|
|
8
|
+
"mappings": "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",
|
|
9
|
+
"debugId": "337A12D65456A62F64756E2164756E21",
|
|
10
10
|
"names": []
|
|
11
11
|
}
|
|
@@ -40,6 +40,7 @@ export default class ResourceManager<ResourceTypes extends Record<string, any> =
|
|
|
40
40
|
private resourceDependencies;
|
|
41
41
|
private resourceDisposers;
|
|
42
42
|
private initializedResourceKeys;
|
|
43
|
+
private _changeSubscribers;
|
|
43
44
|
/**
|
|
44
45
|
* Add a resource to the manager.
|
|
45
46
|
*
|
|
@@ -129,6 +130,21 @@ export default class ResourceManager<ResourceTypes extends Record<string, any> =
|
|
|
129
130
|
* @returns True if the resource existed and was disposed, false if it didn't exist
|
|
130
131
|
*/
|
|
131
132
|
disposeResource<K extends keyof ResourceTypes>(label: K, ...args: ContextArgs<Context>): Promise<boolean>;
|
|
133
|
+
/**
|
|
134
|
+
* Subscribe to changes for a specific resource key.
|
|
135
|
+
* @param key The resource key to watch
|
|
136
|
+
* @param callback Function called with (newValue, oldValue) when the resource changes
|
|
137
|
+
* @returns Unsubscribe function
|
|
138
|
+
*/
|
|
139
|
+
onResourceChange<K extends keyof ResourceTypes>(key: K, callback: (newValue: ResourceTypes[K], oldValue: ResourceTypes[K]) => void): () => void;
|
|
140
|
+
/**
|
|
141
|
+
* Notify subscribers of a resource value change.
|
|
142
|
+
* Skips notification if the value is unchanged (via Object.is).
|
|
143
|
+
* @param key The resource key that changed
|
|
144
|
+
* @param newValue The new resource value
|
|
145
|
+
* @param oldValue The previous resource value
|
|
146
|
+
*/
|
|
147
|
+
notifyChange<K extends keyof ResourceTypes>(key: K, newValue: ResourceTypes[K], oldValue: ResourceTypes[K]): void;
|
|
132
148
|
/**
|
|
133
149
|
* Dispose all initialized resources in reverse dependency order.
|
|
134
150
|
* Resources that depend on others are disposed first.
|
package/package.json
CHANGED
package/dist/src/index.js
DELETED
|
@@ -1,4 +0,0 @@
|
|
|
1
|
-
var{defineProperty:C,getOwnPropertyNames:o,getOwnPropertyDescriptor:r}=Object,a=Object.prototype.hasOwnProperty;var h=new WeakMap,n=(j)=>{var $=h.get(j),J;if($)return $;if($=C({},"__esModule",{value:!0}),j&&typeof j==="object"||typeof j==="function")o(j).map((X)=>!a.call($,X)&&C($,X,{get:()=>j[X],enumerable:!(J=r(j,X))||J.enumerable}));return h.set(j,$),$};var t=(j,$)=>{for(var J in $)C(j,J,{get:$[J],enumerable:!0,configurable:!0,set:(X)=>$[J]=()=>X})};var V=(j,$)=>()=>(j&&($=j(j=0)),$);var Xj=((j)=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(j,{get:($,J)=>(typeof require<"u"?require:$)[J]}):j)(function(j){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+j+'" is not supported')});class H{parentMap=new Map;childrenMap=new Map;setParent(j,$){if(j===$)throw Error(`Cannot set entity ${j} as its own parent`);if(this.wouldCreateCycle(j,$))throw Error("Cannot set parent: would create circular reference");let J=this.parentMap.get(j);if(J!==void 0){let Y=this.childrenMap.get(J);if(Y){let Z=Y.indexOf(j);if(Z!==-1)Y.splice(Z,1)}}this.parentMap.set(j,$);let X=this.childrenMap.get($);if(X)X.push(j);else this.childrenMap.set($,[j]);return this}removeParent(j){let $=this.parentMap.get(j);if($===void 0)return!1;let J=this.childrenMap.get($);if(J){let X=J.indexOf(j);if(X!==-1)J.splice(X,1)}return this.parentMap.delete(j),!0}getParent(j){return this.parentMap.get(j)??null}getChildren(j){let $=this.childrenMap.get(j);return $?[...$]:[]}getChildAt(j,$){if($<0)return null;let J=this.childrenMap.get(j);if(!J||$>=J.length)return null;return J[$]??null}getChildIndex(j,$){let J=this.childrenMap.get(j);if(!J)return-1;return J.indexOf($)}removeEntity(j){let $=this.parentMap.get(j)??null;if($!==null){let Y=this.childrenMap.get($);if(Y){let Z=Y.indexOf(j);if(Z!==-1)Y.splice(Z,1)}}this.parentMap.delete(j);let J=this.childrenMap.get(j)??[],X=[...J];for(let Y of J)this.parentMap.delete(Y);return this.childrenMap.delete(j),{oldParent:$,orphanedChildren:X}}getAncestors(j){let $=[],J=this.parentMap.get(j);while(J!==void 0)$.push(J),J=this.parentMap.get(J);return $}getDescendants(j){let $=[],J=this.childrenMap.get(j);if(!J)return $;let X=J.slice().reverse();while(X.length>0){let Y=X.pop();$.push(Y);let Z=this.childrenMap.get(Y);if(Z)for(let W=Z.length-1;W>=0;W--)X.push(Z[W])}return $}getRoot(j){let $=j,J=this.parentMap.get($);while(J!==void 0)$=J,J=this.parentMap.get($);return $}getSiblings(j){let $=this.parentMap.get(j);if($===void 0)return[];let J=this.childrenMap.get($);if(!J)return[];return J.filter((X)=>X!==j)}isDescendantOf(j,$){if(j===$)return!1;let J=this.parentMap.get(j);while(J!==void 0){if(J===$)return!0;J=this.parentMap.get(J)}return!1}isAncestorOf(j,$){return this.isDescendantOf($,j)}getRootEntities(){let j=[];for(let $ of this.childrenMap.keys())if(!this.parentMap.has($))j.push($);return j}wouldCreateCycle(j,$){let J=$;while(J!==void 0){if(J===j)return!0;J=this.parentMap.get(J)}return!1}forEachInHierarchy(j,$){let J=$?.roots??this.getRootEntities(),X=[];for(let Y of J)X.push({entityId:Y,parentId:null,depth:0});for(let Y of X){j(Y.entityId,Y.parentId,Y.depth);let Z=this.childrenMap.get(Y.entityId);if(Z)for(let W of Z)X.push({entityId:W,parentId:Y.entityId,depth:Y.depth+1})}}*hierarchyIterator(j){let $=j?.roots??this.getRootEntities(),J=[];for(let X of $)J.push({entityId:X,parentId:null,depth:0});for(let X of J){yield X;let Y=this.childrenMap.get(X.entityId);if(Y)for(let Z of Y)J.push({entityId:Z,parentId:X.entityId,depth:X.depth+1})}}}class q{callbacks=[];_iterDepth=0;_pendingRemovals=[];add(j){this.callbacks.push(j)}remove(j){if(this._iterDepth>0){this._pendingRemovals.push(j);return}let $=this.callbacks.indexOf(j);if($!==-1)this.callbacks.splice($,1)}invoke(j){this._iterDepth++;let $=this.callbacks.length;for(let J=0;J<$;J++){let X=this.callbacks[J];if(X)X(j)}if(this._iterDepth--,this._iterDepth===0&&this._pendingRemovals.length>0){for(let J of this._pendingRemovals){let X=this.callbacks.indexOf(J);if(X!==-1)this.callbacks.splice(X,1)}this._pendingRemovals.length=0}}}class E{nextId=1;entities=new Map;componentIndices=new Map;addedCallbacks=new Map;removedCallbacks=new Map;hierarchyManager=new H;disposeCallbacks=new Map;changeSeqs=new Map;_changeSeq=0;_afterComponentAddedHooks=[];_afterEntityMutatedHooks=[];_afterComponentRemovedHooks=[];_beforeEntityRemovedHooks=[];_afterParentChangedHooks=[];_batchingDepth=0;_batchedEntityIds=new Set;_pendingBatchKeys=null;get entityCount(){return this.entities.size}createEntity(){let j=this.nextId++,$={id:j,components:{}};return this.entities.set(j,$),$}registerDispose(j,$){this.disposeCallbacks.set(j,$)}getDisposeCallbacks(){return this.disposeCallbacks}invokeDispose(j,$,J){let X=this.disposeCallbacks.get(j);if(!X)return;try{X({value:$,entityId:J})}catch(Y){console.warn(`Component dispose callback for '${String(j)}' threw:`,Y)}}addComponent(j,$,J){let X=this.entities.get(j);if(!X)throw Error(`Cannot add component '${String($)}': Entity with ID ${j} does not exist`);let Y=X.components[$];if(Y!==void 0)this.invokeDispose($,Y,X.id);if(X.components[$]=J,!this.componentIndices.has($))this.componentIndices.set($,new Set);this.componentIndices.get($)?.add(X.id);let Z=this.addedCallbacks.get($);if(Z)Z.invoke({value:J,entity:X});this._batchingDepth++;for(let W of this._afterComponentAddedHooks)W(X.id,$);if(this._batchedEntityIds.add(X.id),this._batchingDepth--,this._batchingDepth===0){for(let W of this._batchedEntityIds)for(let B of this._afterEntityMutatedHooks)B(W);this._batchedEntityIds.clear()}return this}addComponents(j,$){let J=this.entities.get(j);if(!J)throw Error(`Cannot add components: Entity with ID ${j} does not exist`);let X=this._pendingBatchKeys;this._pendingBatchKeys=new Set(Object.keys($)),this._batchingDepth++;for(let Y in $)this.addComponent(J.id,Y,$[Y]);if(this._batchingDepth--,this._pendingBatchKeys=X,this._batchingDepth===0){for(let Y of this._batchedEntityIds)for(let Z of this._afterEntityMutatedHooks)Z(Y);this._batchedEntityIds.clear()}return this}removeComponent(j,$){let J=this.entities.get(j);if(!J)throw Error(`Cannot remove component '${String($)}': Entity with ID ${j} does not exist`);let X=J.components[$];if(X!==void 0)this.invokeDispose($,X,J.id);delete J.components[$];let Y=this.removedCallbacks.get($);if(Y&&X!==void 0)Y.invoke({value:X,entity:J});if(this.componentIndices.get($)?.delete(J.id),X!==void 0)for(let Z of this._afterComponentRemovedHooks)Z(J.id,$);return this}getComponent(j,$){let J=this.entities.get(j);if(!J)throw Error(`Cannot get component '${String($)}': Entity with ID ${j} does not exist`);return J.components[$]}getEntitiesWithQuery(j=[],$=[],J,X,Y){let Z=J!==void 0&&J.length>0&&X!==void 0,W=Y!==void 0&&Y.length>0;if(j.length===0){if($.length===0&&!Z&&!W)return Array.from(this.entities.values());return Array.from(this.entities.values()).filter((D)=>{if($.length>0&&!$.every((_)=>!(_ in D.components)))return!1;if(Z){let _=this.changeSeqs.get(D.id);if(!_)return!1;if(!J.some((Q)=>(_.get(Q)??-1)>X))return!1}if(W&&!this.parentHasComponents(D.id,Y))return!1;return!0})}let B=j[0];if(B===void 0)return[];let K=j.reduce((D,_)=>{let Q=this.componentIndices.get(_)?.size??0,A=this.componentIndices.get(D)?.size??1/0;return Q<A?_:D},B),U=this.componentIndices.get(K);if(!U||U.size===0)return[];let G=[],F=$.length>0;for(let D of U){let _=this.entities.get(D);if(_&&j.every((Q)=>(Q in _.components))&&(!F||$.every((Q)=>!(Q in _.components)))){if(Z){let Q=this.changeSeqs.get(D);if(!Q||!J.some((A)=>(Q.get(A)??-1)>X))continue}if(W&&!this.parentHasComponents(D,Y))continue;G.push(_)}}return G}parentHasComponents(j,$){let J=this.hierarchyManager.getParent(j);if(J===null)return!1;let X=this.entities.get(J);if(!X)return!1;for(let Y of $)if(!(Y in X.components))return!1;return!0}removeEntity(j,$){let J=this.entities.get(j);if(!J)return!1;if($?.cascade??!0){let Y=this.hierarchyManager.getDescendants(J.id);for(let Z=Y.length-1;Z>=0;Z--){let W=Y[Z];if(W===void 0)continue;for(let B of this._beforeEntityRemovedHooks)B(W)}for(let Z of this._beforeEntityRemovedHooks)Z(J.id);for(let Z=Y.length-1;Z>=0;Z--){let W=Y[Z];if(W===void 0)continue;this.removeEntityInternal(W)}}else for(let Y of this._beforeEntityRemovedHooks)Y(J.id);return this.removeEntityInternal(J.id)}removeEntityInternal(j){let $=this.entities.get(j);if(!$)return!1;this.hierarchyManager.removeEntity(j);for(let J of Object.keys($.components)){let X=$.components[J];if(X!==void 0){this.invokeDispose(J,X,$.id);let Y=this.removedCallbacks.get(J);if(Y)Y.invoke({value:X,entity:$})}this.componentIndices.get(J)?.delete($.id)}return this.changeSeqs.delete($.id),this.entities.delete($.id)}getEntity(j){return this.entities.get(j)}onComponentAdded(j,$){let J=$,X=this.addedCallbacks.get(j);if(!X)X=new q,this.addedCallbacks.set(j,X);return X.add(J),()=>{this.addedCallbacks.get(j)?.remove(J)}}onComponentRemoved(j,$){let J=$,X=this.removedCallbacks.get(j);if(!X)X=new q,this.removedCallbacks.set(j,X);return X.add(J),()=>{this.removedCallbacks.get(j)?.remove(J)}}onAfterComponentAdded(j){return this._afterComponentAddedHooks.push(j),()=>{let $=this._afterComponentAddedHooks.indexOf(j);if($!==-1)this._afterComponentAddedHooks.splice($,1)}}onAfterEntityMutated(j){return this._afterEntityMutatedHooks.push(j),()=>{let $=this._afterEntityMutatedHooks.indexOf(j);if($!==-1)this._afterEntityMutatedHooks.splice($,1)}}onAfterComponentRemoved(j){return this._afterComponentRemovedHooks.push(j),()=>{let $=this._afterComponentRemovedHooks.indexOf(j);if($!==-1)this._afterComponentRemovedHooks.splice($,1)}}onBeforeEntityRemoved(j){return this._beforeEntityRemovedHooks.push(j),()=>{let $=this._beforeEntityRemovedHooks.indexOf(j);if($!==-1)this._beforeEntityRemovedHooks.splice($,1)}}onAfterParentChanged(j){return this._afterParentChangedHooks.push(j),()=>{let $=this._afterParentChangedHooks.indexOf(j);if($!==-1)this._afterParentChangedHooks.splice($,1)}}get changeSeq(){return this._changeSeq}markChanged(j,$){let J=++this._changeSeq,X=this.changeSeqs.get(j);if(!X)X=new Map,this.changeSeqs.set(j,X);X.set($,J)}getChangeSeq(j,$){return this.changeSeqs.get(j)?.get($)??-1}spawnChild(j,$){let J=this.createEntity();return this.addComponents(J.id,$),this.setParent(J.id,j),J}setParent(j,$){this.hierarchyManager.setParent(j,$);for(let J of this._afterParentChangedHooks)J(j);return this}removeParent(j){let $=this.hierarchyManager.removeParent(j);if($)for(let J of this._afterParentChangedHooks)J(j);return $}getParent(j){return this.hierarchyManager.getParent(j)}getChildren(j){return this.hierarchyManager.getChildren(j)}getChildAt(j,$){return this.hierarchyManager.getChildAt(j,$)}getChildIndex(j,$){return this.hierarchyManager.getChildIndex(j,$)}getAncestors(j){return this.hierarchyManager.getAncestors(j)}getDescendants(j){return this.hierarchyManager.getDescendants(j)}getRoot(j){return this.hierarchyManager.getRoot(j)}getSiblings(j){return this.hierarchyManager.getSiblings(j)}isDescendantOf(j,$){return this.hierarchyManager.isDescendantOf(j,$)}isAncestorOf(j,$){return this.hierarchyManager.isAncestorOf(j,$)}getRootEntities(){return this.hierarchyManager.getRootEntities()}forEachInHierarchy(j,$){this.hierarchyManager.forEachInHierarchy(j,$)}hierarchyIterator(j){return this.hierarchyManager.hierarchyIterator(j)}}var u=()=>{};class w{handlers=new Map;subscribe(j,$){return this.addHandler(j,$,!1)}once(j,$){return this.addHandler(j,$,!0)}unsubscribe(j,$){let J=this.handlers.get(j);if(!J)return!1;let X=J.findIndex((Y)=>Y.callback===$);if(X===-1)return!1;return J.splice(X,1),!0}addHandler(j,$,J){let X=this.handlers.get(j);if(!X)X=[],this.handlers.set(j,X);let Y={callback:$,once:J};return X.push(Y),()=>{let Z=this.handlers.get(j);if(Z){let W=Z.indexOf(Y);if(W!==-1)Z.splice(W,1)}}}publish(...[j,$]){let J=this.handlers.get(j);if(!J||J.length===0)return;let X=!1,Y=J.length;for(let Z=0;Z<Y&&Z<J.length;Z++){let W=J[Z];if(!W)continue;if(W.callback($),W.once)X=!0}if(X){for(let Z=J.length-1;Z>=0;Z--)if(J[Z]?.once)J.splice(Z,1)}}clear(){this.handlers.clear()}clearEvent(j){this.handlers.delete(j)}}function e(j){return{[v]:j}}function jj(j){return typeof j==="object"&&j!==null&&"factory"in j&&typeof j.factory==="function"}function $j(j){return typeof j==="object"&&j!==null&&v in j}function p(j,$){let J=[],X=new Set,Y=new Set;function Z(W,B=[]){if(X.has(W))return;if(Y.has(W))throw Error(`Circular resource dependency: ${[...B,W].join(" -> ")}`);Y.add(W);for(let K of $(W)){let U=j.find((G)=>G===K);if(U)Z(U,[...B,W])}Y.delete(W),X.add(W),J.push(W)}for(let W of j)Z(W);return J}class R{resources=new Map;resourceFactories=new Map;resourceDependencies=new Map;resourceDisposers=new Map;initializedResourceKeys=new Set;add(j,$){let J=(X)=>{this.resources.set(j,X),this.initializedResourceKeys.add(j),this.resourceDependencies.set(j,[])};if(jj($)){if(this.resourceFactories.set(j,$.factory),this.resourceDependencies.set(j,$.dependsOn??[]),$.onDispose)this.resourceDisposers.set(j,$.onDispose)}else if($j($))J($[v]);else if(typeof $==="function")this.resourceFactories.set(j,$),this.resourceDependencies.set(j,[]);else J($);return this}tryGet(j,...$){if(!this.has(j))return;return this.get(j,...$)}get(j,...$){let J=this.resources.get(j);if(J!==void 0)return J;let X=this.resourceFactories.get(j);if(X===void 0)throw Error(`Resource ${String(j)} not found`);let Y=$[0],Z=X(Y);if(!(Z instanceof Promise))this.resources.set(j,Z),this.initializedResourceKeys.add(j);return Z}has(j){return this.resources.has(j)||this.resourceFactories.has(j)}remove(j){let $=this.resources.delete(j),J=this.resourceFactories.delete(j);return this.resourceDependencies.delete(j),this.resourceDisposers.delete(j),this.initializedResourceKeys.delete(j),$||J}getKeys(){let j=new Set([...this.resources.keys(),...this.resourceFactories.keys()]);return Array.from(j)}needsInitialization(j){return this.resourceFactories.has(j)&&!this.initializedResourceKeys.has(j)}getPendingInitializationKeys(){return Array.from(this.resourceFactories.keys()).filter((j)=>!this.initializedResourceKeys.has(j))}async initializeResource(j,...$){if(!this.resourceFactories.has(j)||this.initializedResourceKeys.has(j))return;let J=this.resourceFactories.get(j);if(!J)return;let X=$[0],Y=await J(X);this.resources.set(j,Y),this.initializedResourceKeys.add(j),this.resourceFactories.delete(j)}async initializeResources(...j){let $=j.slice(1),J=$.length===0?this.getPendingInitializationKeys():$;if(J.length===0)return;let X=p(J,(Y)=>[...this.resourceDependencies.get(Y)??[]]);for(let Y of X)await this.initializeResource(Y,...j.slice(0,1))}getDependencies(j){return this.resourceDependencies.get(j)??[]}async disposeResource(j,...$){if(!this.resources.has(j)&&!this.resourceFactories.has(j))return!1;if(this.initializedResourceKeys.has(j)){let J=this.resourceDisposers.get(j),X=this.resources.get(j);if(J&&X!==void 0){let Y=$[0];await J(X,Y)}}return this.resources.delete(j),this.resourceFactories.delete(j),this.resourceDependencies.delete(j),this.resourceDisposers.delete(j),this.initializedResourceKeys.delete(j),!0}async disposeResources(...j){let $=Array.from(this.initializedResourceKeys);if($.length===0)return;let J=p($,(X)=>[...this.resourceDependencies.get(X)??[]]).reverse();for(let X of J)await this.disposeResource(X,...j)}}var v;var f=V(()=>{v=Symbol("resource-direct")});class S{queries=new Map;entityManager;_hasParentHasQueries=!1;constructor(j){this.entityManager=j}get hasParentHasQueries(){return this._hasParentHasQueries}addQuery(j,$){let J={definition:$,matchingEntities:new Set};if(this.queries.set(j,J),$.parentHas?.length)this._hasParentHasQueries=!0;let X=this.entityManager.getEntitiesWithQuery($.with,$.without??[]);for(let Y of X)if(this.entityMatchesQuery(Y,J.definition))J.matchingEntities.add(Y.id),J.definition.onEnter?.(Y)}removeQuery(j){let $=this.queries.delete(j);if($)this._recalcParentHasFlag();return $}entityMatchesQuery(j,$){for(let J of $.with)if(!(J in j.components))return!1;if($.without){for(let J of $.without)if(J in j.components)return!1}if($.parentHas?.length){let J=this.entityManager.getParent(j.id);if(J===null)return!1;let X=this.entityManager.getEntity(J);if(!X)return!1;for(let Y of $.parentHas)if(!(Y in X.components))return!1}return!0}_applyQueryTransition(j,$){let J=$.matchingEntities.has(j.id),X=this.entityMatchesQuery(j,$.definition);if(!J&&X)$.matchingEntities.add(j.id),$.definition.onEnter?.(j);else if(J&&!X)$.matchingEntities.delete(j.id),$.definition.onExit?.(j.id)}onComponentAdded(j,$){for(let[,J]of this.queries)this._applyQueryTransition(j,J);if(this._hasParentHasQueries)this._recheckChildren(j.id)}onComponentRemoved(j,$){for(let[,J]of this.queries)this._applyQueryTransition(j,J);if(this._hasParentHasQueries)this._recheckChildren(j.id)}onEntityRemoved(j){for(let[$,J]of this.queries)if(J.matchingEntities.has(j))J.matchingEntities.delete(j),J.definition.onExit?.(j)}recheckEntity(j){for(let[,$]of this.queries)this._applyQueryTransition(j,$)}recheckEntityAndChildren(j){if(this.recheckEntity(j),this._hasParentHasQueries)this._recheckChildren(j.id)}_recheckChildren(j){let $=this.entityManager.getChildren(j);for(let J of $){let X=this.entityManager.getEntity(J);if(X)this.recheckEntity(X)}}_recalcParentHasFlag(){this._hasParentHasQueries=!1;for(let[,j]of this.queries)if(j.definition.parentHas?.length){this._hasParentHasQueries=!0;return}}}class T{commands=[];removeEntity(j,$){this.commands.push((J)=>{J.removeEntity(j,$)})}addComponent(j,$,J){this.commands.push((X)=>{X.addComponent(j,$,J)})}removeComponent(j,$){this.commands.push((J)=>{J.removeComponent(j,$)})}spawn(j){this.commands.push(($)=>{$.spawn(j)})}spawnChild(j,$){this.commands.push((J)=>{J.spawnChild(j,$)})}addComponents(j,$){this.commands.push((J)=>{J.addComponents(j,$)})}setParent(j,$){this.commands.push((J)=>{J.setParent(j,$)})}mutateComponent(j,$,J){this.commands.push((X)=>{X.mutateComponent(j,$,J)})}markChanged(j,$){this.commands.push((J)=>{J.markChanged(j,$)})}removeParent(j){this.commands.push(($)=>{$.removeParent(j)})}playback(j){for(let $ of this.commands)try{$(j)}catch(J){console.warn("CommandBuffer: Command failed during playback:",J)}this.commands.length=0}clear(){this.commands.length=0}get length(){return this.commands.length}}function z(j){return j}class x{_label;queries={};processFunction;detachFunction;initializeFunction;eventHandlers;_priority=0;_phase="update";_groups=[];_inScreens;_excludeScreens;_requiredAssets;_runWhenEmpty=!1;_entityEnterHandlers={};_resourceKeys;constructor(j){this._label=j}get label(){return this._label}_createSystemObject(){let j={label:this._label,entityQueries:this.queries,priority:this._priority,phase:this._phase};if(this.processFunction)j.process=this.processFunction;if(this.detachFunction)j.onDetach=this.detachFunction;if(this.initializeFunction)j.onInitialize=this.initializeFunction;if(this.eventHandlers)j.eventHandlers=this.eventHandlers;if(this._groups.length>0)j.groups=[...this._groups];if(this._inScreens)j.inScreens=this._inScreens;if(this._excludeScreens)j.excludeScreens=this._excludeScreens;if(this._requiredAssets)j.requiredAssets=this._requiredAssets;if(this._runWhenEmpty)j.runWhenEmpty=!0;if(Object.keys(this._entityEnterHandlers).length>0)j.onEntityEnter={...this._entityEnterHandlers};return j}setPriority(j){return this._priority=j,this}inPhase(j){return this._phase=j,this}inGroup(j){if(!this._groups.includes(j))this._groups.push(j);return this}inScreens(j){return this._inScreens=[...j],this}excludeScreens(j){return this._excludeScreens=[...j],this}requiresAssets(j){return this._requiredAssets=[...j],this}runWhenEmpty(){return this._runWhenEmpty=!0,this}withResources(j){return this._resourceKeys=[...j],this}addQuery(j,$){let J=this;return J.queries={...this.queries,[j]:$},J}setProcess(j){if(this._resourceKeys?.length){let $=this._resourceKeys,J;this.processFunction=(X)=>{if(!J){J={};for(let Y of $)J[Y]=X.ecs.getResource(Y)}X.resources=J,j(X)}}else this.processFunction=j;return this}setOnEntityEnter(j,$){return this._entityEnterHandlers[j]=$,this}setOnDetach(j){return this.detachFunction=j,this}setOnInitialize(j){return this.initializeFunction=j,this}setEventHandlers(j){return this.eventHandlers=j,this}}function I(j,$,J){let X=new Set,Y=[$];while(Y.length>0){let Z=Y.pop();if(Z===void 0)break;if(Z===j)throw Error(`Circular required component dependency: '${String(j)}' -> '${String($)}' -> ... -> '${String(j)}'`);if(X.has(Z))continue;X.add(Z);let W=J(Z);if(W)for(let B of W)Y.push(B.component)}}var l="0.12.1";var m=()=>{};class O{assets=new Map;groups=new Map;eventBus=null;setEventBus(j){this.eventBus=j}register(j,$){if(this.assets.set(j,{definition:$,status:"pending"}),$.group){let J=this.groups.get($.group)??new Set;J.add(j),this.groups.set($.group,J)}}async loadEagerAssets(){let j=[];for(let[$,J]of this.assets)if(J.definition.eager&&J.status==="pending")j.push($);await Promise.all(j.map(($)=>this.loadAsset($)))}async loadAsset(j){let $=this.assets.get(j);if(!$)throw Error(`Asset '${String(j)}' not found`);if($.status==="loaded"&&$.value!==void 0)return $.value;if($.status==="loading"&&$.loadPromise)return $.loadPromise;if($.status==="failed")$.status="pending";$.status="loading",$.loadPromise=$.definition.loader();try{let J=await $.loadPromise;return $.value=J,$.status="loaded",$.loadPromise=void 0,this.eventBus?.publish("assetLoaded",{key:j}),this.checkGroupProgress($.definition.group),J}catch(J){let X=J instanceof Error?J:Error(String(J));throw $.status="failed",$.error=X,$.loadPromise=void 0,this.eventBus?.publish("assetFailed",{key:j,error:X}),X}}async loadAssetGroup(j){let $=this.groups.get(j);if(!$||$.size===0)throw Error(`Asset group '${j}' not found or empty`);await Promise.all(Array.from($).map((J)=>this.loadAsset(J)))}get(j){let $=this.assets.get(j);if(!$)throw Error(`Asset '${String(j)}' not found`);if($.status!=="loaded"||$.value===void 0)throw Error(`Asset '${String(j)}' is not loaded (status: ${$.status})`);return $.value}tryGet(j){let $=this.assets.get(j);if(!$||$.status!=="loaded")return;return $.value}getHandle(j){let $=this.assets.get(j);if(!$)throw Error(`Asset '${String(j)}' not found`);let J=this;return{get status(){return $.status},get isLoaded(){return $.status==="loaded"},get(){return J.get(j)},tryGet(){return J.tryGet(j)}}}getStatus(j){let $=this.assets.get(j);if(!$)throw Error(`Asset '${String(j)}' not found`);return $.status}isLoaded(j){return this.assets.get(j)?.status==="loaded"}isGroupLoaded(j){let $=this.groups.get(j);if(!$||$.size===0)return!1;for(let J of $){let X=this.assets.get(J);if(!X||X.status!=="loaded")return!1}return!0}getGroupProgress(j){return this.getGroupProgressDetails(j).progress}getGroupProgressDetails(j){let $=this.groups.get(j);if(!$||$.size===0)return{loaded:0,total:0,progress:0};let J=0;for(let Y of $)if(this.assets.get(Y)?.status==="loaded")J++;let X=$.size;return{loaded:J,total:X,progress:J/X}}checkGroupProgress(j){if(!j||!this.eventBus)return;let $=j,J=this.getGroupProgressDetails($);if(this.eventBus.publish("assetGroupProgress",{group:$,...J}),J.loaded===J.total)this.eventBus.publish("assetGroupLoaded",{group:$})}createResource(){let j=this;return{getStatus($){return j.getStatus($)},isLoaded($){return j.isLoaded($)},isGroupLoaded($){return j.isGroupLoaded($)},getGroupProgress($){return j.getGroupProgress($)},get($){return j.get($)},tryGet($){return j.tryGet($)},getHandle($){return j.getHandle($)}}}getKeys(){return Array.from(this.assets.keys())}getGroupNames(){return Array.from(this.groups.keys())}getGroupKeys(j){let $=this.groups.get(j);return $?Array.from($):[]}}class s{manager;constructor(j){this.manager=j}add(j,$){return this.manager.register(j,{loader:$,eager:!0}),this}addWithConfig(j,$){return this.manager.register(j,$),this}addGroup(j,$){for(let[J,X]of Object.entries($))this.manager.register(J,{loader:X,eager:!1,group:j});return this}getManager(){return this.manager}}function b(j){return new s(j??new O)}class P{screens=new Map;currentScreen=null;screenStack=[];eventBus=null;assetManager=null;ecs=null;setDependencies(j,$,J){this.eventBus=j,this.assetManager=$,this.ecs=J}requireEcs(){if(!this.ecs)throw Error("ScreenManager: dependencies not set. Call setDependencies() first.");return this.ecs}register(j,$){this.screens.set(j,{definition:$})}async setScreen(j,$){let J=this.screens.get(j);if(!J)throw Error(`Screen '${String(j)}' not found`);await this.verifyRequiredAssets(J.definition.requiredAssets,J.definition.requiredAssetGroups);while(this.screenStack.length>0){let Y=this.screenStack.pop();if(Y)await this.exitScreen(Y.name)}if(this.currentScreen)await this.exitScreen(this.currentScreen.name);let X=J.definition.initialState($);this.currentScreen={name:j,config:$,state:X},await J.definition.onEnter?.({config:$,ecs:this.requireEcs()}),this.eventBus?.publish("screenEnter",{screen:j,config:$})}async pushScreen(j,$){let J=this.screens.get(j);if(!J)throw Error(`Screen '${String(j)}' not found`);if(await this.verifyRequiredAssets(J.definition.requiredAssets,J.definition.requiredAssetGroups),this.currentScreen)this.screenStack.push(this.currentScreen);let X=J.definition.initialState($);this.currentScreen={name:j,config:$,state:X},await J.definition.onEnter?.({config:$,ecs:this.requireEcs()}),this.eventBus?.publish("screenPush",{screen:j,config:$})}async popScreen(){if(this.screenStack.length===0)throw Error("Cannot pop screen: stack is empty");if(this.currentScreen)await this.exitScreen(this.currentScreen.name),this.eventBus?.publish("screenPop",{screen:this.currentScreen.name});this.currentScreen=this.screenStack.pop()??null}async exitScreen(j){let $=this.screens.get(j);if($?.definition.onExit)await $.definition.onExit(this.requireEcs());this.eventBus?.publish("screenExit",{screen:j})}async verifyRequiredAssets(j,$){if(!this.assetManager)return;if(j){for(let J of j)if(!this.assetManager.isLoaded(J))await this.assetManager.loadAsset(J)}if($){for(let J of $)if(!this.assetManager.isGroupLoaded(J))await this.assetManager.loadAssetGroup(J)}}getCurrentScreen(){return this.currentScreen?.name??null}getConfig(j){if(!this.currentScreen)throw Error("No current screen");if(j!==void 0&&this.currentScreen.name!==j)throw Error(`Expected current screen '${String(j)}', but current is '${String(this.currentScreen.name)}'`);return this.currentScreen.config}tryGetConfig(j){if(!this.currentScreen)return;if(j!==void 0&&this.currentScreen.name!==j)return;return this.currentScreen.config}getState(j){if(!this.currentScreen)throw Error("No current screen");if(j!==void 0&&this.currentScreen.name!==j)throw Error(`Expected current screen '${String(j)}', but current is '${String(this.currentScreen.name)}'`);return this.currentScreen.state}tryGetState(j){if(!this.currentScreen)return;if(j!==void 0&&this.currentScreen.name!==j)return;return this.currentScreen.state}updateState(j,$){if(!this.currentScreen)throw Error("No current screen");if($!==void 0&&this.currentScreen.name!==$)throw Error(`Expected current screen '${String($)}', but current is '${String(this.currentScreen.name)}'`);let J=typeof j==="function"?j(this.currentScreen.state):j;this.currentScreen.state={...this.currentScreen.state,...J}}getStackDepth(){return this.screenStack.length}isOverlay(){return this.screenStack.length>0}isActive(j){if(this.currentScreen?.name===j)return!0;return this.screenStack.some(($)=>$.name===j)}isCurrent(j){return this.currentScreen?.name===j}createResource(){let j=this;return{get current(){return j.getCurrentScreen()},get config(){return j.tryGetConfig()??null},get state(){return j.tryGetState()??null},set state($){if(j.currentScreen&&$!==null)j.currentScreen.state=$},get stack(){return j.screenStack},get isOverlay(){return j.isOverlay()},get stackDepth(){return j.getStackDepth()},isActive($){return j.isActive($)},isCurrent($){return j.isCurrent($)}}}getScreenNames(){return Array.from(this.screens.keys())}hasScreen(j){return this.screens.has(j)}}class y{manager;constructor(j){this.manager=j}add(j,$){return this.manager.register(j,$),this}getManager(){return this.manager}}function N(j){return new y(j??new P)}class g{ecspresso;assetConfigurator=null;screenConfigurator=null;pendingResources=[];pendingDisposeCallbacks=[];pendingRequiredComponents=[];pendingPlugins=[];_fixedDt=null;constructor(){let{default:j}=(k(),n(c));this.ecspresso=new j}withPlugin(j){return this.pendingPlugins.push(j),this}withComponentTypes(){return this}withEventTypes(){return this}withResourceTypes(){return this}withResource(j,$){return this.pendingResources.push({key:j,value:$}),this}withDispose(j,$){return this.pendingDisposeCallbacks.push({key:j,callback:$}),this}withRequired(j,$,J){return this.pendingRequiredComponents.push({trigger:j,required:$,factory:J}),this}withAssets(j){let $=b();return j($),this.assetConfigurator=$,this}withScreens(j){let $=N();return j($),this.screenConfigurator=$,this}withFixedTimestep(j){return this._fixedDt=j,this}withReactiveQueryNames(){return this}pluginFactory(){return z}build(){for(let j of this.pendingPlugins)this.ecspresso.installPlugin(j);for(let{key:j,value:$}of this.pendingResources)this.ecspresso.addResource(j,$);for(let{key:j,callback:$}of this.pendingDisposeCallbacks)this.ecspresso.registerDispose(j,$);for(let{trigger:j,required:$,factory:J}of this.pendingRequiredComponents)this.ecspresso.registerRequired(j,$,J);if(this.assetConfigurator)this.ecspresso._setAssetManager(this.assetConfigurator.getManager());else if(this.ecspresso._hasPendingPluginAssets())this.ecspresso._setAssetManager(new O);if(this.screenConfigurator)this.ecspresso._setScreenManager(this.screenConfigurator.getManager());else if(this.ecspresso._hasPendingPluginScreens())this.ecspresso._setScreenManager(new P);if(this._fixedDt!==null)this.ecspresso._setFixedDt(this._fixedDt);return this.ecspresso}}var d=()=>{};var c={};t(c,{default:()=>M});var i,M;var k=V(()=>{u();f();m();d();i=["preUpdate","fixedUpdate","update","postUpdate","render"];M=class M{static VERSION=l;_entityManager;_eventBus;_resourceManager;_commandBuffer;_systems=[];_phaseSystems={preUpdate:[],fixedUpdate:[],update:[],postUpdate:[],render:[]};_installedPlugins=new Set;_disabledGroups=new Set;_assetManager=null;_screenManager=null;_reactiveQueryManager;_postUpdateHooks=[];_currentTick=0;_systemLastSeqs=new Map;_changeThreshold=0;_fixedDt=0.016666666666666666;_fixedAccumulator=0;_interpolationAlpha=0;_maxFixedSteps=8;_requiredComponents=new Map;_pendingPluginAssets=[];_pendingPluginScreens=[];_diagnosticsEnabled=!1;_systemTimings=new Map;_phaseTimings={preUpdate:0,fixedUpdate:0,update:0,postUpdate:0,render:0};_entityEnterTracking=new Map;_entityEnterFrameSet=new Set;_systemContexts=new WeakMap;_pendingFinalizers=[];_batchingRegistrations=!1;constructor(){this._entityManager=new E,this._eventBus=new w,this._resourceManager=new R,this._reactiveQueryManager=new S(this._entityManager),this._commandBuffer=new T,this._subscribeLifecycleHooks()}_subscribeLifecycleHooks(){this._entityManager.onAfterComponentAdded((j,$)=>{this._entityManager.markChanged(j,$);let J=this._requiredComponents.get($);if(J){let X=this._entityManager.getEntity(j);if(X){let Y=X.components[$];for(let{component:Z,factory:W}of J){if(this._entityManager._pendingBatchKeys?.has(Z))continue;if(!(Z in X.components))this._entityManager.addComponent(j,Z,W(Y))}}}}),this._entityManager.onAfterEntityMutated((j)=>{let $=this._entityManager.getEntity(j);if($)this._reactiveQueryManager.recheckEntityAndChildren($)}),this._entityManager.onAfterComponentRemoved((j,$)=>{let J=this._entityManager.getEntity(j);if(J)this._reactiveQueryManager.onComponentRemoved(J,$)}),this._entityManager.onBeforeEntityRemoved((j)=>{this._reactiveQueryManager.onEntityRemoved(j)}),this._entityManager.onAfterParentChanged((j)=>{if(this._reactiveQueryManager.hasParentHasQueries){let $=this._entityManager.getEntity(j);if($)this._reactiveQueryManager.recheckEntity($)}})}static create(){return new g}addSystem(j){let $=new x(j);return this._pendingFinalizers.push(()=>{this._registerSystem($._createSystemObject())}),$}_finalizePendingBuilders(){if(this._pendingFinalizers.length===0)return;this._batchingRegistrations=!0;while(this._pendingFinalizers.length>0){let j=this._pendingFinalizers;this._pendingFinalizers=[];for(let $ of j)$()}this._batchingRegistrations=!1,this._rebuildPhaseSystems()}update(j){this._finalizePendingBuilders();let $=this._screenManager?.getCurrentScreen()??null,J=this._diagnosticsEnabled;this._runPhase("preUpdate",j,$,J);let X=J?performance.now():0;this._fixedAccumulator+=j;let Y=0;while(this._fixedAccumulator>=this._fixedDt&&Y<this._maxFixedSteps)this._executePhase(this._phaseSystems.fixedUpdate,this._fixedDt,$),this._commandBuffer.playback(this),this._fixedAccumulator-=this._fixedDt,Y++;if(this._fixedAccumulator>=this._fixedDt)this._fixedAccumulator=0;if(J)this._phaseTimings.fixedUpdate=performance.now()-X;this._interpolationAlpha=this._fixedAccumulator/this._fixedDt,this._runPhase("update",j,$,J),this._runPhase("postUpdate",j,$,J);for(let Z of this._postUpdateHooks)Z({ecs:this,dt:j});this._runPhase("render",j,$,J),this._changeThreshold=this._entityManager.changeSeq,this._currentTick++}_executePhase(j,$,J){for(let X of j){if(!X.process&&!X.onEntityEnter)continue;if(X.groups?.length){let G=!1;for(let F of X.groups)if(this._disabledGroups.has(F)){G=!0;break}if(G)continue}if(X.inScreens?.length){if(J===null||!X.inScreens.includes(J))continue}if(X.excludeScreens?.length){if(J!==null&&X.excludeScreens.includes(J))continue}if(X.requiredAssets?.length&&this._assetManager){let G=!0;for(let F of X.requiredAssets)if(!this._assetManager.isLoaded(F)){G=!1;break}if(!G)continue}let Y=this._systemLastSeqs.get(X)??0;this._changeThreshold=Y;let Z=this._systemContexts.get(X);if(!Z)Z={queries:{},dt:0,ecs:this},this._systemContexts.set(X,Z);Z.dt=$;let W=Z.queries,B=!1,K=!1;if(X.entityQueries)for(let G in X.entityQueries){K=!0;let F=X.entityQueries[G];if(F){if(W[G]=this._entityManager.getEntitiesWithQuery(F.with,F.without||[],F.changed,F.changed?this._changeThreshold:void 0,F.parentHas),W[G].length)B=!0}}let U=this._entityEnterTracking.get(X);if(U&&X.onEntityEnter)for(let G in X.onEntityEnter){let F=W[G],D=U.get(G);if(!F||!D)continue;let _=X.onEntityEnter[G];if(!_)continue;let Q=this._entityEnterFrameSet;Q.clear();for(let A of F)if(Q.add(A.id),!D.has(A.id))D.add(A.id),_({entity:A,ecs:this});for(let A of D)if(!Q.has(A))D.delete(A)}if(X.process){if(this._diagnosticsEnabled){let G=performance.now();if(B||X.runWhenEmpty)X.process(Z);else if(!K)X.process(Z);this._systemTimings.set(X.label,performance.now()-G)}else if(B||X.runWhenEmpty)X.process(Z);else if(!K)X.process(Z)}this._systemLastSeqs.set(X,this._entityManager.changeSeq)}}_runPhase(j,$,J,X){if(X){let Y=performance.now();this._executePhase(this._phaseSystems[j],$,J),this._phaseTimings[j]=performance.now()-Y}else this._executePhase(this._phaseSystems[j],$,J);this._commandBuffer.playback(this)}async initialize(){if(this._finalizePendingBuilders(),await this.initializeResources(),this._assetManager)this._assetManager.setEventBus(this._eventBus),await this._assetManager.loadEagerAssets(),this._resourceManager.add("$assets",this._assetManager.createResource());if(this._screenManager)this._screenManager.setDependencies(this._eventBus,this._assetManager,this),this._resourceManager.add("$screen",this._screenManager.createResource());for(let j of this._systems)await j.onInitialize?.(this)}async initializeResources(...j){await this._resourceManager.initializeResources(this,...j)}_rebuildPhaseSystems(){for(let j of i)this._phaseSystems[j]=[];for(let j of this._systems){let $=j.phase??"update";this._phaseSystems[$].push(j)}for(let j of i)this._phaseSystems[j].sort(($,J)=>{let X=$.priority??0;return(J.priority??0)-X})}updateSystemPriority(j,$){this._finalizePendingBuilders();let J=this._systems.find((X)=>X.label===j);if(!J)return!1;return J.priority=$,this._rebuildPhaseSystems(),!0}updateSystemPhase(j,$){this._finalizePendingBuilders();let J=this._systems.find((X)=>X.label===j);if(!J)return!1;return J.phase=$,this._rebuildPhaseSystems(),!0}get interpolationAlpha(){return this._interpolationAlpha}get fixedDt(){return this._fixedDt}disableSystemGroup(j){this._disabledGroups.add(j)}enableSystemGroup(j){this._disabledGroups.delete(j)}isSystemGroupEnabled(j){return!this._disabledGroups.has(j)}getSystemsInGroup(j){return this._finalizePendingBuilders(),this._systems.filter(($)=>$.groups?.includes(j)).map(($)=>$.label)}removeSystem(j){this._finalizePendingBuilders();let $=this._systems.findIndex((X)=>X.label===j);if($===-1)return!1;let J=this._systems[$];if(!J)return!1;if(J.onDetach)J.onDetach(this);return this._systems.splice($,1),this._systemLastSeqs.delete(J),this._entityEnterTracking.delete(J),this._rebuildPhaseSystems(),!0}_registerSystem(j){if(this._systems.push(j),this._systemLastSeqs.set(j,this._changeThreshold),!this._batchingRegistrations)this._rebuildPhaseSystems();if(j.onEntityEnter){let $=new Map;for(let J in j.onEntityEnter)$.set(J,new Set);this._entityEnterTracking.set(j,$)}if(!j.eventHandlers)return;for(let $ in j.eventHandlers){let J=j.eventHandlers[$];if(J)this._eventBus.subscribe($,(X)=>{J({data:X,ecs:this})})}}hasResource(j){return this._resourceManager.has(j)}getResource(j){if(!this._resourceManager.has(j))throw Error(`Resource '${String(j)}' not found. Available resources: [${this.getResourceKeys().map(($)=>String($)).join(", ")}]`);return this._resourceManager.get(j,this)}tryGetResource(j){let $=j;if(!this._resourceManager.has($))return;return this._resourceManager.get($,this)}addResource(j,$){return this._resourceManager.add(j,$),this}removeResource(j){return this._resourceManager.remove(j)}async disposeResource(j){return this._resourceManager.disposeResource(j,this)}async disposeResources(){return this._resourceManager.disposeResources(this)}updateResource(j,$){let J=this.getResource(j),X=$(J);return this._resourceManager.add(j,X),this}getResourceKeys(){return this._resourceManager.getKeys()}resourceNeedsInitialization(j){return this._resourceManager.needsInitialization(j)}getComponent(j,$){return this._entityManager.getComponent(j,$)}addComponent(j,$,J){this._entityManager.addComponent(j,$,J)}addComponents(j,$){this._entityManager.addComponents(j,$)}removeComponent(j,$){this._entityManager.removeComponent(j,$)}hasComponent(j,$){return this._entityManager.getComponent(j,$)!==void 0}spawn(j){let $=this._entityManager.createEntity();return this._entityManager.addComponents($.id,j),$}getEntitiesWithQuery(j,$=[],J,X){return this._entityManager.getEntitiesWithQuery(j,$,J,J?this._changeThreshold:void 0,X)}getSingleton(j,$=[]){let J=this._entityManager.getEntitiesWithQuery(j,$);if(J.length===0)throw Error(`getSingleton: no entity matches query with=[${String(j)}] without=[${String($)}]`);if(J.length>1)throw Error(`getSingleton: expected 1 entity but found ${J.length} matching query with=[${String(j)}] without=[${String($)}]`);let X=J[0];if(!X)throw Error("getSingleton: unexpected empty result");return X}tryGetSingleton(j,$=[]){let J=this._entityManager.getEntitiesWithQuery(j,$);if(J.length===0)return;if(J.length>1)throw Error(`tryGetSingleton: expected 0 or 1 entity but found ${J.length} matching query with=[${String(j)}] without=[${String($)}]`);return J[0]}removeEntity(j,$){return this._entityManager.removeEntity(j,$)}spawnChild(j,$){let J=this._entityManager.spawnChild(j,$);return this._emitHierarchyChanged(J.id,null,j),J}setParent(j,$){let J=this._entityManager.getParent(j);return this._entityManager.setParent(j,$),this._emitHierarchyChanged(j,J,$),this}removeParent(j){let $=this._entityManager.getParent(j),J=this._entityManager.removeParent(j);if(J)this._emitHierarchyChanged(j,$,null);return J}getParent(j){return this._entityManager.getParent(j)}getChildren(j){return this._entityManager.getChildren(j)}getChildAt(j,$){return this._entityManager.getChildAt(j,$)}getChildIndex(j,$){return this._entityManager.getChildIndex(j,$)}getAncestors(j){return this._entityManager.getAncestors(j)}getDescendants(j){return this._entityManager.getDescendants(j)}getRoot(j){return this._entityManager.getRoot(j)}getSiblings(j){return this._entityManager.getSiblings(j)}isDescendantOf(j,$){return this._entityManager.isDescendantOf(j,$)}isAncestorOf(j,$){return this._entityManager.isAncestorOf(j,$)}getRootEntities(){return this._entityManager.getRootEntities()}forEachInHierarchy(j,$){this._entityManager.forEachInHierarchy(j,$)}hierarchyIterator(j){return this._entityManager.hierarchyIterator(j)}_emitHierarchyChanged(j,$,J){this._eventBus.publish("hierarchyChanged",{entityId:j,oldParent:$,newParent:J})}get installedPlugins(){return Array.from(this._installedPlugins)}get entityManager(){return this._entityManager}get eventBus(){return this._finalizePendingBuilders(),this._eventBus}get commands(){return this._commandBuffer}get currentTick(){return this._currentTick}get changeThreshold(){return this._changeThreshold}enableDiagnostics(j){if(this._diagnosticsEnabled=j,!j)this._systemTimings.clear(),this._phaseTimings={preUpdate:0,fixedUpdate:0,update:0,postUpdate:0,render:0}}get diagnosticsEnabled(){return this._diagnosticsEnabled}get systemTimings(){return this._systemTimings}get phaseTimings(){return this._phaseTimings}get entityCount(){return this._entityManager.entityCount}mutateComponent(j,$,J){let X=this._entityManager.getComponent(j,$);if(X===void 0)throw Error(`Entity ${j} does not have component "${String($)}"`);return J(X),this._entityManager.markChanged(j,$),X}markChanged(j,$){this._entityManager.markChanged(j,$)}registerDispose(j,$){this._entityManager.registerDispose(j,$)}registerRequired(j,$,J){if(String(j)===String($))throw Error(`Cannot require a component to depend on itself: '${String(j)}'`);let X=this._requiredComponents.get(j)??[];if(X.some((Y)=>Y.component===$))throw Error(`Required component '${String($)}' already registered for trigger '${String(j)}'`);this._checkRequiredCycle(j,$),X.push({component:$,factory:J}),this._requiredComponents.set(j,X)}_checkRequiredCycle(j,$){I(j,$,(J)=>this._requiredComponents.get(J))}onComponentAdded(j,$){return this._entityManager.onComponentAdded(j,$)}onComponentRemoved(j,$){return this._entityManager.onComponentRemoved(j,$)}addReactiveQuery(j,$){this._reactiveQueryManager.addQuery(j,$)}removeReactiveQuery(j){return this._reactiveQueryManager.removeQuery(j)}on(j,$){return this._eventBus.subscribe(j,$)}off(j,$){return this._eventBus.unsubscribe(j,$)}onPostUpdate(j){return this._postUpdateHooks.push(j),()=>{let $=this._postUpdateHooks.indexOf(j);if($!==-1)this._postUpdateHooks.splice($,1)}}requireAssetManager(){if(!this._assetManager)throw Error("Asset manager not configured. Use withAssets() in builder.");return this._assetManager}getAsset(j){return this.requireAssetManager().get(j)}tryGetAsset(j){return this._assetManager?.tryGet(j)}getAssetHandle(j){return this.requireAssetManager().getHandle(j)}isAssetLoaded(j){return this._assetManager?.isLoaded(j)??!1}async loadAsset(j){return this.requireAssetManager().loadAsset(j)}async loadAssetGroup(j){return this.requireAssetManager().loadAssetGroup(j)}isAssetGroupLoaded(j){return this._assetManager?.isGroupLoaded(j)??!1}getAssetGroupProgress(j){return this._assetManager?.getGroupProgress(j)??0}requireScreenManager(){if(!this._screenManager)throw Error("Screen manager not configured. Use withScreens() in builder.");return this._screenManager}async setScreen(j,$){return this.requireScreenManager().setScreen(j,$)}async pushScreen(j,$){return this.requireScreenManager().pushScreen(j,$)}async popScreen(){return this.requireScreenManager().popScreen()}getCurrentScreen(){return this._screenManager?.getCurrentScreen()??null}getScreenConfig(j){return this.requireScreenManager().getConfig(j)}tryGetScreenConfig(j){return this._screenManager?.tryGetConfig(j)??void 0}getScreenState(j){return this.requireScreenManager().getState(j)}tryGetScreenState(j){return this._screenManager?.tryGetState(j)??void 0}updateScreenState(j,$){if(typeof j==="string")this.requireScreenManager().updateState($,j);else this.requireScreenManager().updateState(j)}isCurrentScreen(j){return this._screenManager?.isCurrent(j)??!1}isScreenActive(j){return this._screenManager?.isActive(j)??!1}getScreenStackDepth(){return this._screenManager?.getStackDepth()??0}_setAssetManager(j){this._assetManager=j;for(let[$,J]of this._pendingPluginAssets)this._assetManager.register($,J);this._pendingPluginAssets=[]}_setScreenManager(j){this._screenManager=j;for(let[$,J]of this._pendingPluginScreens)this._screenManager.register($,J);this._pendingPluginScreens=[]}_hasPendingPluginAssets(){return this._pendingPluginAssets.length>0}_hasPendingPluginScreens(){return this._pendingPluginScreens.length>0}_setFixedDt(j){this._fixedDt=j}_registerAsset(j,$){this._pendingPluginAssets.push([j,$])}_registerScreen(j,$){this._pendingPluginScreens.push([j,$])}installPlugin(j){if(this._installedPlugins.has(j.id))return this;return this._installedPlugins.add(j.id),j.install(this),this}pluginFactory(){return z}getHelpers(j){return j(this)}}});k();function Nj(j){return j}function kj(j,$){return{x:j,y:$}}function hj(){return{x:0,y:0}}function uj(j,$){return{x:j.x+$.x,y:j.y+$.y}}function pj(j,$){return{x:j.x-$.x,y:j.y-$.y}}function Ij(j,$){return{x:j.x*$,y:j.y*$}}function mj(j){return{x:-j.x,y:-j.y}}function lj(j,$){return j.x*$.x+j.y*$.y}function sj(j,$){return j.x*$.y-j.y*$.x}function yj(j){return j.x*j.x+j.y*j.y}function dj(j){return Math.sqrt(j.x*j.x+j.y*j.y)}function cj(j){let $=Math.sqrt(j.x*j.x+j.y*j.y);if($===0)return{x:0,y:0};return{x:j.x/$,y:j.y/$}}function ij(j,$){let J=j.x-$.x,X=j.y-$.y;return J*J+X*X}function oj(j,$){let J=j.x-$.x,X=j.y-$.y;return Math.sqrt(J*J+X*X)}function rj(j,$,J=0.0000000001){return Math.abs(j.x-$.x)<=J&&Math.abs(j.y-$.y)<=J}f();var L2=M;export{hj as vec2Zero,pj as vec2Sub,Ij as vec2Scale,cj as vec2Normalize,mj as vec2Negate,yj as vec2LengthSq,dj as vec2Length,rj as vec2Equals,lj as vec2Dot,ij as vec2DistanceSq,oj as vec2Distance,sj as vec2Cross,uj as vec2Add,kj as vec2,e as directValue,z as definePlugin,L2 as default,N as createScreenConfigurator,Nj as createQueryDefinition,b as createAssetConfigurator,x as SystemBuilder,P as ScreenManager,O as AssetManager};
|
|
2
|
-
|
|
3
|
-
//# debugId=6A2072153E6A68CE64756E2164756E21
|
|
4
|
-
//# sourceMappingURL=index.js.map
|
|
@@ -1,4 +0,0 @@
|
|
|
1
|
-
var{defineProperty:P,getOwnPropertyNames:S,getOwnPropertyDescriptor:C}=Object,V=Object.prototype.hasOwnProperty;var A=new WeakMap,v=(F)=>{var K=A.get(F),U;if(K)return K;if(K=P({},"__esModule",{value:!0}),F&&typeof F==="object"||typeof F==="function")S(F).map((_)=>!V.call(K,_)&&P(K,_,{get:()=>F[_],enumerable:!(U=C(F,_))||U.enumerable}));return A.set(F,K),K};var p=(F,K)=>{for(var U in K)P(F,U,{get:K[U],enumerable:!0,configurable:!0,set:(_)=>K[U]=()=>_})};var y=(F,K)=>()=>(F&&(K=F(F=0)),K);var g=((F)=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(F,{get:(K,U)=>(typeof require<"u"?require:K)[U]}):F)(function(F){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+F+'" is not supported')});import{definePlugin as I}from"ecspresso";function r(F){return Object.freeze(F)}function f(F,K,U){return{audioSource:{sound:F,channel:K,volume:U?.volume??1,loop:U?.loop??!1,autoRemove:U?.autoRemove??!1,playing:!1,_soundId:-1}}}function i(F,K){return()=>import("howler").then(({Howl:U})=>new Promise((_,H)=>{let $,M=!1;if($=new U({src:Array.isArray(F)?F:[F],html5:K?.html5??!1,preload:K?.preload??!0,onload:()=>{M=!0,_($)},onloaderror:(Y,j)=>H(j instanceof Error?j:Error(String(j)))}),!M&&$.state?.()==="loaded")_($)}))}function d(F){let{channels:K,systemGroup:U="audio",priority:_=0,phase:H="update"}=F,$=new Map,M=new Map,Y=new Map,j=1,E=!1,N=[];for(let[z,q]of Object.entries(K))$.set(z,q.volume),N.push(z);let R=N[0];function T(z,q){if(E)return 0;let J=$.get(q)??1;return z*J*j}function b(z){for(let J of M.values()){if(J.channel!==z)continue;J.howl.volume(T(J.individualVolume,z),J.soundId)}let q=Y.get(z);if(q)q.howl.volume(T(q.individualVolume,z),q.soundId)}function W(){for(let z of N)b(z)}function x(z){let q=M.get(z);if(!q)return;q.howl.stop(z),M.delete(z)}let k=null,G=null,B={play(z,q){if(!G)return-1;let J=q?.channel??R,Z=q?.volume??1,Q=q?.loop??!1,X=G(z);X.volume(T(Z,J)),X.loop(Q);let L=X.play(),D={howl:X,soundId:L,channel:J,individualVolume:Z,assetKey:z,entityId:-1};return M.set(L,D),X.once("end",()=>{M.delete(L),k?.publish("soundEnded",{entityId:-1,soundId:L,sound:z})},L),L},stop(z){x(z)},playMusic(z,q){if(!G)return;let J=q?.channel??R,Z=q?.volume??1,Q=q?.loop??!0,X=Y.get(J);if(X)X.howl.stop(X.soundId),M.delete(X.soundId);let L=G(z);L.volume(T(Z,J)),L.loop(Q);let D=L.play(),O={howl:L,soundId:D,channel:J,individualVolume:Z,assetKey:z};Y.set(J,O),M.set(D,{...O,entityId:-1}),L.once("end",()=>{if(M.delete(D),Y.get(J)?.soundId===D)Y.delete(J)},D)},stopMusic(z){if(z!==void 0){let q=Y.get(z);if(q)q.howl.stop(q.soundId),M.delete(q.soundId),Y.delete(z)}else for(let[q,J]of Y)J.howl.stop(J.soundId),M.delete(J.soundId),Y.delete(q)},pauseMusic(z){if(z!==void 0){let q=Y.get(z);if(q)q.howl.pause(q.soundId)}else for(let q of Y.values())q.howl.pause(q.soundId)},resumeMusic(z){if(z!==void 0){let q=Y.get(z);if(q)q.howl.play(q.soundId)}else for(let q of Y.values())q.howl.play(q.soundId)},setChannelVolume(z,q){$.set(z,q),b(z)},getChannelVolume(z){return $.get(z)??1},setMasterVolume(z){j=z,W()},getMasterVolume(){return j},mute(){E=!0,W()},unmute(){E=!1,W()},toggleMute(){E=!E,W()},isMuted(){return E}};return I({id:"audio",install(z){z.addResource("audioState",B),z.registerDispose("audioSource",({value:q})=>{if(q._soundId!==-1)x(q._soundId)}),z.addSystem("audio-sync").setPriority(_).inPhase(H).inGroup(U).setOnInitialize((q)=>{k=q.eventBus;let J=q.tryGetResource("$assets");if(J)G=(Z)=>J.get(Z);q.addReactiveQuery("audio-sources",{with:["audioSource"],onEnter:(Z)=>{let Q=Z.components.audioSource;if(!G)return;if(Q._soundId!==-1)return;let X=G(Q.sound);X.volume(T(Q.volume,Q.channel)),X.loop(Q.loop);let L=X.play();Q._soundId=L,Q.playing=!0;let D={howl:X,soundId:L,channel:Q.channel,individualVolume:Q.volume,assetKey:Q.sound,entityId:Z.id};M.set(L,D),X.once("end",()=>{if(M.delete(L),Q.playing=!1,k?.publish("soundEnded",{entityId:Z.id,soundId:L,sound:Q.sound}),Q.autoRemove)q.commands.removeEntity(Z.id)},L)},onExit:(Z)=>{}})}).setEventHandlers({playSound({data:q,ecs:J}){J.getResource("audioState").play(q.sound,{channel:q.channel,volume:q.volume,loop:q.loop})},stopMusic({data:q,ecs:J}){J.getResource("audioState").stopMusic(q.channel)}}).setOnDetach(()=>{for(let q of M.values())q.howl.stop(q.soundId);M.clear(),Y.clear(),k=null,G=null})}})}function c(F){return{createAudioSource:f}}export{i as loadSound,r as defineAudioChannels,f as createAudioSource,d as createAudioPlugin,c as createAudioHelpers};
|
|
2
|
-
|
|
3
|
-
//# debugId=CFE62AB4B772A19F64756E2164756E21
|
|
4
|
-
//# sourceMappingURL=audio.js.map
|
|
@@ -1,4 +0,0 @@
|
|
|
1
|
-
var{defineProperty:K,getOwnPropertyNames:R,getOwnPropertyDescriptor:q}=Object,M=Object.prototype.hasOwnProperty;var E=new WeakMap,b=(j)=>{var k=E.get(j),z;if(k)return k;if(k=K({},"__esModule",{value:!0}),j&&typeof j==="object"||typeof j==="function")R(j).map((F)=>!M.call(k,F)&&K(k,F,{get:()=>j[F],enumerable:!(z=q(j,F))||z.enumerable}));return E.set(j,k),k};var w=(j,k)=>{for(var z in k)K(j,z,{get:k[z],enumerable:!0,configurable:!0,set:(F)=>k[z]=()=>F})};var y=(j,k)=>()=>(j&&(k=j(j=0)),k);var x=((j)=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(j,{get:(k,z)=>(typeof require<"u"?require:k)[z]}):j)(function(j){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+j+'" is not supported')});import{definePlugin as h}from"ecspresso";function f(j,k,z,F){let V={width:j,height:k};if(z!==void 0)V.x=z;if(F!==void 0)V.y=F;return V}function c(j){return{destroyOutOfBounds:j!==void 0?{padding:j}:{}}}function u(j){return{clampToBounds:j!==void 0?{margin:j}:{}}}function g(j){return{wrapAtBounds:j!==void 0?{padding:j}:{}}}function p(j){let{systemGroup:k="physics",priority:z=50,boundsResourceKey:F="bounds",autoRemove:V=!0,phase:U="postUpdate"}=j??{};return h({id:"bounds",install(G){G.addSystem("bounds-destroy").setPriority(z).inPhase(U).inGroup(k).addQuery("entities",{with:["worldTransform","destroyOutOfBounds"]}).setProcess(({queries:D,ecs:L})=>{let J=L.getResource(F),N=J.x??0,Q=J.y??0,v=N+J.width,A=Q+J.height;for(let S of D.entities){let{worldTransform:Z,destroyOutOfBounds:I}=S.components,P=I.padding??0,C=T(Z,N,Q,v,A,P);if(!C)continue;if(L.eventBus.publish("entityOutOfBounds",{entityId:S.id,exitEdge:C}),V)L.commands.removeEntity(S.id)}}),G.addSystem("bounds-clamp").setPriority(z-1).inPhase(U).inGroup(k).addQuery("entities",{with:["localTransform","worldTransform","clampToBounds"]}).setProcess(({queries:D,ecs:L})=>{let J=L.getResource(F),N=J.x??0,Q=J.y??0,v=N+J.width,A=Q+J.height;for(let S of D.entities){let{localTransform:Z,worldTransform:I,clampToBounds:P}=S.components,C=P.margin??0,_=N+C,$=Q+C,H=v-C,O=A-C,W=0,B=0;if(I.x<_)W=_-I.x;if(I.x>H)W=H-I.x;if(I.y<$)B=$-I.y;if(I.y>O)B=O-I.y;if(W!==0||B!==0)Z.x+=W,Z.y+=B,L.markChanged(S.id,"localTransform")}}),G.addSystem("bounds-wrap").setPriority(z-2).inPhase(U).inGroup(k).addQuery("entities",{with:["localTransform","worldTransform","wrapAtBounds"]}).setProcess(({queries:D,ecs:L})=>{let J=L.getResource(F),N=J.x??0,Q=J.y??0,v=N+J.width,A=Q+J.height;for(let S of D.entities){let{localTransform:Z,worldTransform:I,wrapAtBounds:P}=S.components,C=P.padding??0,_=0,$=0,H=v-N,O=A-Q;if(I.x>v+C)_=-(H+2*C);else if(I.x<N-C)_=H+2*C;if(I.y>A+C)$=-(O+2*C);else if(I.y<Q-C)$=O+2*C;if(_!==0||$!==0)Z.x+=_,Z.y+=$,L.markChanged(S.id,"localTransform")}})}})}function T(j,k,z,F,V,U){if(j.x>F+U)return"right";if(j.x<k-U)return"left";if(j.y>V+U)return"bottom";if(j.y<z-U)return"top";return null}export{g as createWrapAtBounds,c as createDestroyOutOfBounds,u as createClampToBounds,p as createBoundsPlugin,f as createBounds};
|
|
2
|
-
|
|
3
|
-
//# debugId=A325D8279974C1F064756E2164756E21
|
|
4
|
-
//# sourceMappingURL=bounds.js.map
|
|
@@ -1,4 +0,0 @@
|
|
|
1
|
-
var{defineProperty:H,getOwnPropertyNames:B,getOwnPropertyDescriptor:M}=Object,W=Object.prototype.hasOwnProperty;var S=new WeakMap,F=(j)=>{var C=S.get(j),A;if(C)return C;if(C=H({},"__esModule",{value:!0}),j&&typeof j==="object"||typeof j==="function")B(j).map((J)=>!W.call(C,J)&&H(C,J,{get:()=>j[J],enumerable:!(A=M(j,J))||A.enumerable}));return S.set(j,C),C};var k=(j,C)=>{for(var A in C)H(j,A,{get:C[A],enumerable:!0,configurable:!0,set:(J)=>C[A]=()=>J})};var X=(j,C)=>()=>(j&&(C=j(j=0)),C);var Y=((j)=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(j,{get:(C,A)=>(typeof require<"u"?require:C)[A]}):j)(function(j){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+j+'" is not supported')});import{definePlugin as v}from"ecspresso";var x={x:0,y:0,zoom:1,rotation:0},h={x:0,y:0,zoom:1,rotation:0,shakeOffsetX:0,shakeOffsetY:0,shakeRotation:0,viewportWidth:800,viewportHeight:600};function w(j=0,C=0,A=1,J=0){return{camera:{x:j,y:C,zoom:A,rotation:J}}}function f(j,C){return{cameraFollow:{target:j,smoothing:C?.smoothing??5,deadzoneX:C?.deadzoneX??0,deadzoneY:C?.deadzoneY??0,offsetX:C?.offsetX??0,offsetY:C?.offsetY??0}}}function y(j){return{cameraShake:{trauma:j?.trauma??0,traumaDecay:j?.traumaDecay??1,maxOffsetX:j?.maxOffsetX??10,maxOffsetY:j?.maxOffsetY??10,maxRotation:j?.maxRotation??0.05}}}function p(j,C,A,J){return{cameraBounds:{minX:j,minY:C,maxX:A,maxY:J}}}function d(j,C,A){let J=j.getComponent(C,"cameraShake");if(!J)return;J.trauma=Math.min(1,Math.max(0,J.trauma+A))}function l(j,C,A){let J=j-(A.x+A.shakeOffsetX),U=C-(A.y+A.shakeOffsetY),V=-(A.rotation+A.shakeRotation),R=Math.cos(V),N=Math.sin(V),E=J*R-U*N,T=J*N+U*R;return{x:E*A.zoom+A.viewportWidth/2,y:T*A.zoom+A.viewportHeight/2}}function m(j,C,A){let J=(j-A.viewportWidth/2)/A.zoom,U=(C-A.viewportHeight/2)/A.zoom,V=A.rotation+A.shakeRotation,R=Math.cos(V),N=Math.sin(V),E=J*R-U*N,T=J*N+U*R;return{x:E+A.x+A.shakeOffsetX,y:T+A.y+A.shakeOffsetY}}function i(j){let{viewportWidth:C=800,viewportHeight:A=600,systemGroup:J="camera",phase:U="postUpdate",randomFn:V=Math.random}=j??{};return v({id:"camera",install(R){R.addResource("cameraState",{x:0,y:0,zoom:1,rotation:0,shakeOffsetX:0,shakeOffsetY:0,shakeRotation:0,viewportWidth:C,viewportHeight:A}),R.addSystem("camera-follow").setPriority(400).inPhase(U).inGroup(J).addQuery("cameras",{with:["camera","cameraFollow"]}).setProcess(({queries:N,dt:E,ecs:T})=>{let Q=Math.min(1,E);for(let O of N.cameras){let{camera:K,cameraFollow:L}=O.components,Z;try{Z=T.getComponent(L.target,"worldTransform")}catch{continue}if(!Z)continue;if(!Z)continue;let P=Z.x+L.offsetX,b=Z.y+L.offsetY,_=P-K.x,$=b-K.y,G=Math.abs(_),q=Math.abs($);if(G>L.deadzoneX){let z=_>0?1:-1,D=_-z*L.deadzoneX,I=Math.min(1,L.smoothing*Q);K.x+=D*I}if(q>L.deadzoneY){let z=$>0?1:-1,D=$-z*L.deadzoneY,I=Math.min(1,L.smoothing*Q);K.y+=D*I}}}),R.addSystem("camera-shake-update").setPriority(390).inPhase(U).inGroup(J).addQuery("shakeCameras",{with:["camera","cameraShake"]}).setProcess(({queries:N,dt:E})=>{for(let T of N.shakeCameras){let{cameraShake:Q}=T.components;Q.trauma=Math.max(0,Q.trauma-Q.traumaDecay*E)}}),R.addSystem("camera-bounds").setPriority(380).inPhase(U).inGroup(J).addQuery("boundedCameras",{with:["camera","cameraBounds"]}).setProcess(({queries:N,ecs:E})=>{let T=E.getResource("cameraState");for(let Q of N.boundedCameras){let{camera:O,cameraBounds:K}=Q.components,L=T.viewportWidth/(2*O.zoom),Z=T.viewportHeight/(2*O.zoom),P=K.minX+L,b=K.maxX-L,_=K.minY+Z,$=K.maxY-Z;if(P>b)O.x=(K.minX+K.maxX)/2;else O.x=Math.max(P,Math.min(b,O.x));if(_>$)O.y=(K.minY+K.maxY)/2;else O.y=Math.max(_,Math.min($,O.y))}}),R.addSystem("camera-state-sync").setPriority(370).inPhase(U).inGroup(J).setProcess(({ecs:N})=>{let E=N.getResource("cameraState"),Q=N.getEntitiesWithQuery(["camera"])[0];if(!Q){E.x=0,E.y=0,E.zoom=1,E.rotation=0,E.shakeOffsetX=0,E.shakeOffsetY=0,E.shakeRotation=0;return}let O=Q.components.camera;E.x=O.x,E.y=O.y,E.zoom=O.zoom,E.rotation=O.rotation;let K=N.getComponent(Q.id,"cameraShake");if(K&&K.trauma>0){let L=K.trauma*K.trauma;E.shakeOffsetX=K.maxOffsetX*L*(V()*2-1),E.shakeOffsetY=K.maxOffsetY*L*(V()*2-1),E.shakeRotation=K.maxRotation*L*(V()*2-1)}else E.shakeOffsetX=0,E.shakeOffsetY=0,E.shakeRotation=0})}})}export{l as worldToScreen,m as screenToWorld,y as createCameraShake,i as createCameraPlugin,f as createCameraFollow,p as createCameraBounds,w as createCamera,d as addTrauma,h as DEFAULT_CAMERA_STATE,x as DEFAULT_CAMERA};
|
|
2
|
-
|
|
3
|
-
//# debugId=85631121506EC7F364756E2164756E21
|
|
4
|
-
//# sourceMappingURL=camera.js.map
|
|
@@ -1,4 +0,0 @@
|
|
|
1
|
-
var{defineProperty:D,getOwnPropertyNames:A,getOwnPropertyDescriptor:k}=Object,B=Object.prototype.hasOwnProperty;var W=new WeakMap,f=(z)=>{var J=W.get(z),O;if(J)return J;if(J=D({},"__esModule",{value:!0}),z&&typeof z==="object"||typeof z==="function")A(z).map((Q)=>!B.call(J,Q)&&D(J,Q,{get:()=>z[Q],enumerable:!(O=k(z,Q))||O.enumerable}));return W.set(z,J),J};var u=(z,J)=>{for(var O in J)D(z,O,{get:J[O],enumerable:!0,configurable:!0,set:(Q)=>J[O]=()=>Q})};var h=(z,J)=>()=>(z&&(J=z(z=0)),J);var p=((z)=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(z,{get:(J,O)=>(typeof require<"u"?require:J)[O]}):z)(function(z){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+z+'" is not supported')});import{definePlugin as m}from"ecspresso";function L(z,J,O,Q,Z,$,N){if(!$&&!N)return null;let F={entityId:z,x:J,y:O,layer:Q,collidesWith:Z};if($)F.x+=$.offsetX??0,F.y+=$.offsetY??0,F.aabb={halfWidth:$.width/2,halfHeight:$.height/2};if(N)F.x+=N.offsetX??0,F.y+=N.offsetY??0,F.circle={radius:N.radius};return F}function P(z){return z("spatialIndex")}function v(z,J,O,Q,Z,$,N,F){let E=Z-z,M=$-J,V=O+N-Math.abs(E),j=Q+F-Math.abs(M);if(V<=0||j<=0)return null;if(V<j)return{normalX:E>=0?1:-1,normalY:0,depth:V};return{normalX:0,normalY:M>=0?1:-1,depth:j}}function C(z,J,O,Q,Z,$){let N=Q-z,F=Z-J,E=N*N+F*F,M=O+$;if(E>=M*M)return null;let V=Math.sqrt(E);if(V===0)return{normalX:1,normalY:0,depth:M};return{normalX:N/V,normalY:F/V,depth:M-V}}function q(z,J,O,Q,Z,$,N){let F=Math.max(z-O,Math.min(Z,z+O)),E=Math.max(J-Q,Math.min($,J+Q)),M=Z-F,V=$-E,j=M*M+V*V;if(j>=N*N)return null;if(j===0){let U=Z-(z-O),G=z+O-Z,T=$-(J-Q),R=J+Q-$,H=Math.min(U,G,T,R);if(H===G)return{normalX:1,normalY:0,depth:G+N};if(H===U)return{normalX:-1,normalY:0,depth:U+N};if(H===R)return{normalX:0,normalY:1,depth:R+N};return{normalX:0,normalY:-1,depth:T+N}}let _=Math.sqrt(j);return{normalX:M/_,normalY:V/_,depth:N-_}}function S(z,J){if(z.aabb&&J.aabb)return v(z.x,z.y,z.aabb.halfWidth,z.aabb.halfHeight,J.x,J.y,J.aabb.halfWidth,J.aabb.halfHeight);if(z.circle&&J.circle)return C(z.x,z.y,z.circle.radius,J.x,J.y,J.circle.radius);if(z.aabb&&J.circle)return q(z.x,z.y,z.aabb.halfWidth,z.aabb.halfHeight,J.x,J.y,J.circle.radius);if(z.circle&&J.aabb){let O=q(J.x,J.y,J.aabb.halfWidth,J.aabb.halfHeight,z.x,z.y,z.circle.radius);if(!O)return null;return{normalX:-O.normalX,normalY:-O.normalY,depth:O.depth}}return null}var K=new Set;function g(z,J,O,Q){if(J)Y(z,J,O,Q);else X(z,O,Q)}function X(z,J,O){for(let Q=0;Q<z.length;Q++){let Z=z[Q];if(!Z)continue;for(let $=Q+1;$<z.length;$++){let N=z[$];if(!N)continue;if(!Z.collidesWith.includes(N.layer)&&!N.collidesWith.includes(Z.layer))continue;let F=S(Z,N);if(!F)continue;J(Z,N,F,O)}}}function Y(z,J,O,Q){let Z=new Map;for(let $=0;$<z.length;$++){let N=z[$];if(!N)continue;Z.set(N.entityId,N)}for(let $=0;$<z.length;$++){let N=z[$];if(!N)continue;let F=N.aabb?N.aabb.halfWidth:N.circle?N.circle.radius:0,E=N.aabb?N.aabb.halfHeight:N.circle?N.circle.radius:0;K.clear(),J.queryRectInto(N.x-F,N.y-E,N.x+F,N.y+E,K);for(let M of K){if(M<=N.entityId)continue;let V=Z.get(M);if(!V)continue;if(!N.collidesWith.includes(V.layer)&&!V.collidesWith.includes(N.layer))continue;let j=S(N,V);if(!j)continue;O(N,V,j,Q)}}}function s(z,J,O,Q){let Z={width:z,height:J};if(O!==void 0)Z.offsetX=O;if(Q!==void 0)Z.offsetY=Q;return{aabbCollider:Z}}function r(z,J,O){let Q={radius:z};if(J!==void 0)Q.offsetX=J;if(O!==void 0)Q.offsetY=O;return{circleCollider:Q}}function w(z,J){return{collisionLayer:{layer:z,collidesWith:J}}}function l(z){let J={};for(let O of Object.keys(z)){let Q=z[O];J[O]=()=>w(O,Q)}return J}function I(z){let J=z.indexOf(":");if(J===-1)throw Error(`Invalid collision pair key "${z}": must contain a colon separator (e.g. "player:enemy")`);let O=z.slice(0,J),Q=z.slice(J+1);if(O===""||Q==="")throw Error(`Invalid collision pair key "${z}": layer names must not be empty`);return[O,Q]}function o(z){let J=new Map,O=new Set;for(let Q of Object.keys(z))I(Q),O.add(Q);for(let Q of Object.keys(z)){let[Z,$]=I(Q),N=z[Q];if(!N)continue;J.set(Q,{callback:N,swapped:!1});let F=`${$}:${Z}`;if(F!==Q&&!O.has(F))J.set(F,{callback:N,swapped:!0})}return function({data:Z,ecs:$}){let N=J.get(Z.layerA+":"+Z.layerB);if(!N)return;if(N.swapped)N.callback(Z.entityB,Z.entityA,$);else N.callback(Z.entityA,Z.entityB,$)}}function x(z,J,O,Q){Q.publish("collision",{entityA:z.entityId,entityB:J.entityId,layerA:z.layer,layerB:J.layer,normal:{x:O.normalX,y:O.normalY},depth:O.depth})}function c(z){let{systemGroup:J="physics",priority:O=0,phase:Q="postUpdate"}=z;return m({id:"collision",install(Z){Z.addSystem("collision-detection").setPriority(O).inPhase(Q).inGroup(J).addQuery("collidables",{with:["worldTransform","collisionLayer"]}).setProcess(({queries:$,ecs:N})=>{let F=[];for(let M of $.collidables){let{worldTransform:V,collisionLayer:j}=M.components,_=L(M.id,V.x,V.y,j.layer,j.collidesWith,N.getComponent(M.id,"aabbCollider"),N.getComponent(M.id,"circleCollider"));if(_)F.push(_)}let E=P(N.tryGetResource.bind(N));g(F,E,x,N.eventBus)})}})}export{l as defineCollisionLayers,c as createCollisionPlugin,o as createCollisionPairHandler,w as createCollisionLayer,r as createCircleCollider,s as createAABBCollider};
|
|
2
|
-
|
|
3
|
-
//# debugId=BC18D3BFF907B0AC64756E2164756E21
|
|
4
|
-
//# sourceMappingURL=collision.js.map
|
|
@@ -1,4 +0,0 @@
|
|
|
1
|
-
var{defineProperty:N,getOwnPropertyNames:U,getOwnPropertyDescriptor:V}=Object,W=Object.prototype.hasOwnProperty;var S=new WeakMap,_=(j)=>{var x=S.get(j),z;if(x)return x;if(x=N({},"__esModule",{value:!0}),j&&typeof j==="object"||typeof j==="function")U(j).map((D)=>!W.call(x,D)&&N(x,D,{get:()=>j[D],enumerable:!(z=V(j,D))||z.enumerable}));return S.set(j,x),x};var $=(j,x)=>{for(var z in x)N(j,z,{get:x[z],enumerable:!0,configurable:!0,set:(D)=>x[z]=()=>D})};var A=(j,x)=>()=>(j&&(x=j(j=0)),x);var C=((j)=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(j,{get:(x,z)=>(typeof require<"u"?require:x)[z]}):j)(function(j){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+j+'" is not supported')});import{definePlugin as X}from"ecspresso";function Y(j,x){return{coroutine:{generator:j,onComplete:x?.onComplete}}}function*G(j){if(j<=0)return;let x=0;while(x<j){let z=yield;x+=z}}function*P(j){for(let x=0;x<j;x++)yield}function*k(j){while(!j())yield}function*q(...j){if(j.length===0)return;let x=j.map((z)=>{return z.next(0),{gen:z,done:!1}});while(x.some((z)=>!z.done)){let z=yield;for(let D of x){if(D.done)continue;if(D.gen.next(z).done)D.done=!0}}}function*B(...j){if(j.length===0)return;let x=j.map((z)=>{return z.next(0),{gen:z,done:!1}});try{while(!0){let z=yield;for(let D of x){if(D.done)continue;if(D.gen.next(z).done){D.done=!0;for(let K of x)if(!K.done)K.gen.return(),K.done=!0;return}}}}finally{for(let z of x)if(!z.done)z.gen.return(),z.done=!0}}function*Z(j,x,z){let D=!1,H=j.subscribe(x,(K)=>{if(!z||z(K))D=!0});try{while(!D)yield}finally{H()}}function b(j,x){let z=j.getComponent(x,"coroutine");if(!z)return!1;return z.generator.return(),j.commands.removeComponent(x,"coroutine"),!0}function T(j){return{createCoroutine:Y,waitForEvent:Z}}function w(j){let{systemGroup:x="coroutines",priority:z=0,phase:D="update"}=j??{},H=new Set;return X({id:"coroutines",install(K){K.registerDispose("coroutine",({value:L,entityId:M})=>{L.generator.return(),H.delete(M)}),K.addSystem("coroutine-update").setPriority(z).inPhase(D).inGroup(x).addQuery("coroutines",{with:["coroutine"]}).setOnEntityEnter("coroutines",({entity:L})=>{L.components.coroutine.generator.next(0)}).setProcess(({queries:L,dt:M,ecs:O})=>{for(let J of L.coroutines){if(H.has(J.id)){H.delete(J.id);continue}let Q=J.components.coroutine;try{if(Q.generator.next(M).done)H.add(J.id),Q.onComplete?.({entityId:J.id}),O.commands.removeComponent(J.id,"coroutine")}catch(R){console.warn(`Coroutine error on entity ${J.id}:`,R),H.add(J.id),O.commands.removeComponent(J.id,"coroutine")}}})}})}export{k as waitUntil,G as waitSeconds,P as waitFrames,Z as waitForEvent,B as race,q as parallel,w as createCoroutinePlugin,T as createCoroutineHelpers,Y as createCoroutine,b as cancelCoroutine};
|
|
2
|
-
|
|
3
|
-
//# debugId=3EF94FE7B5E8514A64756E2164756E21
|
|
4
|
-
//# sourceMappingURL=coroutine.js.map
|
|
@@ -1,5 +0,0 @@
|
|
|
1
|
-
var{defineProperty:Z,getOwnPropertyNames:G,getOwnPropertyDescriptor:L}=Object,M=Object.prototype.hasOwnProperty;var $=new WeakMap,D=(j)=>{var k=$.get(j),q;if(k)return k;if(k=Z({},"__esModule",{value:!0}),j&&typeof j==="object"||typeof j==="function")G(j).map((z)=>!M.call(k,z)&&Z(k,z,{get:()=>j[z],enumerable:!(q=L(j,z))||q.enumerable}));return $.set(j,k),k};var E=(j,k)=>{for(var q in k)Z(j,q,{get:k[q],enumerable:!0,configurable:!0,set:(z)=>k[q]=()=>z})};var P=(j,k)=>()=>(j&&(k=j(j=0)),k);var R=((j)=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(j,{get:(k,q)=>(typeof require<"u"?require:k)[q]}):j)(function(j){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+j+'" is not supported')});import{definePlugin as N}from"ecspresso";function Y(j){let k=new Float64Array(j),q=0,z=0;return{push(Q){if(k[q]=Q,q=(q+1)%j,z<j)z++},computeFps(){if(z<2)return 0;let Q=k[(q-1+j)%j]??0,U=k[(q-z+j)%j]??0,F=Q-U;if(F<=0)return 0;return(z-1)/F*1000},computeAverageFrameTime(){if(z<2)return 0;let Q=k[(q-1+j)%j]??0,U=k[(q-z+j)%j]??0,F=Q-U;if(F<=0)return 0;return F/(z-1)},get size(){return z}}}function T(j){let{systemGroup:k="diagnostics",enableTimingOnInit:q=!0,fpsSampleCount:z=60}=j??{},Q={fps:0,entityCount:0,systemTimings:new Map,phaseTimings:{preUpdate:0,fixedUpdate:0,update:0,postUpdate:0,render:0},averageFrameTime:0},U=Y(z);return N({id:"diagnostics",install(F){F.addResource("diagnostics",Q),F.addSystem("diagnostics-collect").setPriority(-999999).inPhase("render").inGroup(k).setOnInitialize((J)=>{if(q)J.enableDiagnostics(!0)}).setOnDetach((J)=>{J.enableDiagnostics(!1)}).setProcess(({ecs:J})=>{let V=performance.now();U.push(V);let K=J.getResource("diagnostics"),H={fps:U.computeFps(),entityCount:J.entityCount,systemTimings:J.systemTimings,phaseTimings:J.phaseTimings,averageFrameTime:U.computeAverageFrameTime()};K.fps=H.fps,K.entityCount=H.entityCount,K.systemTimings=H.systemTimings,K.phaseTimings=H.phaseTimings,K.averageFrameTime=H.averageFrameTime})}})}var _={"top-left":"top:8px;left:8px","top-right":"top:8px;right:8px","bottom-left":"bottom:8px;left:8px","bottom-right":"bottom:8px;right:8px"};function O(j,k){let{position:q="top-left",updateInterval:z=200,showSystemTimings:Q=!0,maxSystemsShown:U=10}=k??{},F=document.createElement("div");F.style.cssText=`position:fixed;${_[q]};z-index:999999;background:rgba(0,0,0,0.8);color:#0f0;font:12px/1.4 monospace;padding:8px 12px;border-radius:4px;pointer-events:none;white-space:pre`,document.body.appendChild(F);let J=setInterval(()=>{let V=j.getResource("diagnostics"),K=[`FPS: ${V.fps.toFixed(0)}`,`Frame: ${V.averageFrameTime.toFixed(2)}ms`,`Entities: ${V.entityCount}`],H=V.phaseTimings;if(K.push(`Phases: pre=${H.preUpdate.toFixed(2)} fix=${H.fixedUpdate.toFixed(2)} upd=${H.update.toFixed(2)} post=${H.postUpdate.toFixed(2)} ren=${H.render.toFixed(2)}`),Q&&V.systemTimings.size>0){K.push("--- Systems ---");let A=[...V.systemTimings.entries()].sort((W,X)=>X[1]-W[1]).slice(0,U);for(let[W,X]of A)K.push(` ${W}: ${X.toFixed(3)}ms`)}F.textContent=K.join(`
|
|
2
|
-
`)},z);return()=>{clearInterval(J),F.remove()}}export{T as createDiagnosticsPlugin,O as createDiagnosticsOverlay};
|
|
3
|
-
|
|
4
|
-
//# debugId=B57D6397BDB064BA64756E2164756E21
|
|
5
|
-
//# sourceMappingURL=diagnostics.js.map
|
|
@@ -1,4 +0,0 @@
|
|
|
1
|
-
var{defineProperty:B,getOwnPropertyNames:A,getOwnPropertyDescriptor:D}=Object,R=Object.prototype.hasOwnProperty;var L=new WeakMap,M=(q)=>{var C=L.get(q),Q;if(C)return C;if(C=B({},"__esModule",{value:!0}),q&&typeof q==="object"||typeof q==="function")A(q).map((V)=>!R.call(C,V)&&B(C,V,{get:()=>q[V],enumerable:!(Q=D(q,V))||Q.enumerable}));return L.set(q,C),C};var T=(q,C)=>{for(var Q in C)B(q,Q,{get:C[Q],enumerable:!0,configurable:!0,set:(V)=>C[Q]=()=>V})};var u=(q,C)=>()=>(q&&(C=q(q=0)),C);var y=((q)=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(q,{get:(C,Q)=>(typeof require<"u"?require:C)[Q]}):q)(function(q){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+q+'" is not supported')});import{definePlugin as v}from"ecspresso";function d(q){return q}function P(){return{keysDown:new Set,keysPressed:[],keysReleased:[],buttonsDown:new Set,buttonsPressed:[],buttonsReleased:[],pointerX:0,pointerY:0,pointerDeltaX:0,pointerDeltaY:0,lastPointerX:0,lastPointerY:0,pointerMoved:!1}}var K=new Set,F=new Set;function S(){return{keysDown:K,keysPressed:K,keysReleased:K,buttonsDown:F,buttonsPressed:F,buttonsReleased:F,pointerX:0,pointerY:0,pointerDeltaX:0,pointerDeltaY:0,actionsActive:K,prevActionsActive:K}}function _(q,C,Q){let V=new Set;for(let[$,Z]of Object.entries(q)){let O=Z.keys?.some((W)=>C.has(W))??!1,J=Z.buttons?.some((W)=>Q.has(W))??!1;if(O||J)V.add($)}return V}function b(q,C,Q){let V=new Set(q.keysDown),$=new Set(q.keysPressed),Z=new Set(q.keysReleased),O=new Set(q.buttonsDown),J=new Set(q.buttonsPressed),W=new Set(q.buttonsReleased),f=q.pointerMoved?q.pointerX-q.lastPointerX:0,j=q.pointerMoved?q.pointerY-q.lastPointerY:0,x=_(Q,V,O),m={keysDown:V,keysPressed:$,keysReleased:Z,buttonsDown:O,buttonsPressed:J,buttonsReleased:W,pointerX:q.pointerX,pointerY:q.pointerY,pointerDeltaX:f,pointerDeltaY:j,actionsActive:x,prevActionsActive:C};return q.keysPressed=[],q.keysReleased=[],q.buttonsPressed=[],q.buttonsReleased=[],q.lastPointerX=q.pointerX,q.lastPointerY=q.pointerY,q.pointerMoved=!1,m}function c(q){let{systemGroup:C="input",priority:Q=100,phase:V="preUpdate",actions:$={},target:Z=globalThis}=q??{},O=P(),J=S(),W={...$},f=[],j={x:0,y:0},x={x:0,y:0},G={keyboard:{isDown:(z)=>J.keysDown.has(z),justPressed:(z)=>J.keysPressed.has(z),justReleased:(z)=>J.keysReleased.has(z)},pointer:{position:j,delta:x,isDown:(z)=>J.buttonsDown.has(z),justPressed:(z)=>J.buttonsPressed.has(z),justReleased:(z)=>J.buttonsReleased.has(z)},actions:{isActive:(z)=>J.actionsActive.has(z),justActivated:(z)=>J.actionsActive.has(z)&&!J.prevActionsActive.has(z),justDeactivated:(z)=>!J.actionsActive.has(z)&&J.prevActionsActive.has(z)},setActionMap(z){W={...z}},getActionMap(){return{...W}}};function I(z){let H=z;if(H.repeat)return;O.keysDown.add(H.key),O.keysPressed.push(H.key)}function U(z){let H=z;O.keysDown.delete(H.key),O.keysReleased.push(H.key)}function g(z){let H=z;O.buttonsDown.add(H.button),O.buttonsPressed.push(H.button)}function N(z){let H=z;O.pointerX=H.clientX,O.pointerY=H.clientY,O.pointerMoved=!0}function Y(z){let H=z;O.buttonsDown.delete(H.button),O.buttonsReleased.push(H.button)}function X(z,H){Z.addEventListener(z,H),f.push(()=>{Z.removeEventListener(z,H)})}return v({id:"input",install(z){z.addResource("inputState",G),z.addSystem("input-state").setPriority(Q).inPhase(V).inGroup(C).setOnInitialize(()=>{X("keydown",I),X("keyup",U),X("pointerdown",g),X("pointermove",N),X("pointerup",Y)}).setOnDetach(()=>{for(let H of f)H();f.length=0}).setProcess(()=>{let H=J.actionsActive;J=b(O,H,W),j.x=J.pointerX,j.y=J.pointerY,x.x=J.pointerDeltaX,x.y=J.pointerDeltaY})}})}export{c as createInputPlugin,d as createActionBinding};
|
|
2
|
-
|
|
3
|
-
//# debugId=43414B185EC78B3864756E2164756E21
|
|
4
|
-
//# sourceMappingURL=input.js.map
|
|
@@ -1,4 +0,0 @@
|
|
|
1
|
-
var{defineProperty:W,getOwnPropertyNames:D,getOwnPropertyDescriptor:X}=Object,Y=Object.prototype.hasOwnProperty;var _=new WeakMap,v=(k)=>{var A=_.get(k),B;if(A)return A;if(A=W({},"__esModule",{value:!0}),k&&typeof k==="object"||typeof k==="function")D(k).map((Q)=>!Y.call(A,Q)&&W(A,Q,{get:()=>k[Q],enumerable:!(B=X(k,Q))||B.enumerable}));return _.set(k,A),A};var I=(k,A)=>{for(var B in A)W(k,B,{get:A[B],enumerable:!0,configurable:!0,set:(Q)=>A[B]=()=>Q})};var P=(k,A)=>()=>(k&&(A=k(k=0)),A);var T=((k)=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(k,{get:(A,B)=>(typeof require<"u"?require:A)[B]}):k)(function(k){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+k+'" is not supported')});import{definePlugin as C}from"ecspresso";function M(k){if(typeof k==="number")return k;let[A,B]=k;return A+Math.random()*(B-A)}function R(k,A,B){if(k===A)return k;let Q=k>>16&255,L=k>>8&255,q=k&255,H=A>>16&255,j=A>>8&255,$=A&255,V=Q+(H-Q)*B|0,Z=L+(j-L)*B|0,J=q+($-q)*B|0;return V<<16|Z<<8|J}var O=Math.PI*2;function G(k){let A=k.startSize??1,B=k.startTint??16777215;return Object.freeze({maxParticles:k.maxParticles,texture:k.texture,spawnRate:k.spawnRate??10,burstCount:k.burstCount??0,duration:k.duration??-1,lifetime:k.lifetime??1,speed:k.speed??100,angle:k.angle??[0,O],emissionShape:k.emissionShape??"point",emissionRadius:k.emissionRadius??0,gravity:Object.freeze(k.gravity??{x:0,y:0}),startSize:A,endSize:k.endSize??A,startAlpha:k.startAlpha??1,endAlpha:k.endAlpha??0,startTint:B,endTint:k.endTint??B,startRotation:k.startRotation??0,rotationSpeed:k.rotationSpeed??0,blendMode:k.blendMode??"normal",worldSpace:k.worldSpace??!0})}function g(k,A){return{particleEmitter:{config:k,activeCount:0,spawnAccumulator:0,elapsed:0,playing:A?.playing??!0,pendingBurst:0,finished:!1,onComplete:A?.onComplete}}}function f(k,A,B){let Q=k.getComponent(A,"particleEmitter");if(!Q)return!1;return Q.pendingBurst+=B??Q.config.burstCount,k.markChanged(A,"particleEmitter"),!0}function u(k,A){let B=k.getComponent(A,"particleEmitter");if(!B)return!1;return B.playing=!1,!0}function l(k,A){let B=k.getComponent(A,"particleEmitter");if(!B)return!1;return B.playing=!0,!0}function b(k,A,B,Q,L){k.active=!0;let q=M(A.lifetime);if(k.life=q,k.maxLife=q,A.emissionShape==="circle"&&A.emissionRadius>0){let $=Math.random()*O,V=Math.random()*A.emissionRadius;k.x=B+Math.cos($)*V,k.y=Q+Math.sin($)*V}else k.x=B,k.y=Q;let H=M(A.speed),j=M(A.angle)+L;k.vx=Math.cos(j)*H,k.vy=Math.sin(j)*H,k.startSize=M(A.startSize),k.endSize=M(A.endSize),k.size=k.startSize,k.startAlpha=M(A.startAlpha),k.endAlpha=M(A.endAlpha),k.alpha=k.startAlpha,k.tint=A.startTint,k.rotation=M(A.startRotation),k.rotationSpeed=M(A.rotationSpeed)}function w(k,A,B,Q,L,q){let H=k.config;k.elapsed+=B;let j=H.duration>=0&&k.elapsed>=H.duration;if(k.playing&&!j&&H.spawnRate>0){k.spawnAccumulator+=H.spawnRate*B;let F=Math.floor(k.spawnAccumulator);k.spawnAccumulator-=F;for(let U=0;U<F;U++){if(k.activeCount>=H.maxParticles)break;let z=A.particles[k.activeCount];if(!z)break;b(z,H,Q,L,q),k.activeCount++}}if(k.pendingBurst>0){let F=Math.min(k.pendingBurst,H.maxParticles-k.activeCount);for(let U=0;U<F;U++){let z=A.particles[k.activeCount];if(!z)break;b(z,H,Q,L,q),k.activeCount++}k.pendingBurst-=F}let V=H.gravity.x,Z=H.gravity.y,J=V!==0||Z!==0,N=H.startTint!==H.endTint,K=0;while(K<k.activeCount){let F=A.particles[K];if(!F)break;if(F.life-=B,F.life<=0){if(k.activeCount--,K<k.activeCount){let z=A.particles[k.activeCount];if(z){A.particles[K]=z,A.particles[k.activeCount]=F;let h=A.pixiParticles[K];A.pixiParticles[K]=A.pixiParticles[k.activeCount],A.pixiParticles[k.activeCount]=h}}F.active=!1;continue}if(J)F.vx+=V*B,F.vy+=Z*B;F.x+=F.vx*B,F.y+=F.vy*B;let U=1-F.life/F.maxLife;if(F.size=F.startSize+(F.endSize-F.startSize)*U,F.alpha=F.startAlpha+(F.endAlpha-F.startAlpha)*U,N)F.tint=R(H.startTint,H.endTint,U);F.rotation+=F.rotationSpeed*B,K++}}function E(k){let A=Array(k);for(let B=0;B<k;B++)A[B]={active:!1,x:0,y:0,vx:0,vy:0,life:0,maxLife:0,size:0,startSize:0,endSize:0,alpha:0,startAlpha:0,endAlpha:0,tint:16777215,rotation:0,rotationSpeed:0};return A}var d={explosion(k,A){return G({maxParticles:50,texture:k,spawnRate:0,burstCount:30,duration:1,lifetime:[0.3,0.8],speed:[100,300],angle:[0,O],startSize:[0.5,1.5],endSize:[0.1,0.3],startAlpha:1,endAlpha:0,...A})},smoke(k,A){return G({maxParticles:60,texture:k,spawnRate:15,duration:-1,lifetime:[1,3],speed:[20,60],angle:[-Math.PI/2-0.3,-Math.PI/2+0.3],startSize:[0.3,0.6],endSize:[1,2],startAlpha:0.4,endAlpha:0,...A})},fire(k,A){return G({maxParticles:80,texture:k,spawnRate:30,duration:-1,lifetime:[0.3,1],speed:[40,120],angle:[-Math.PI/2-0.5,-Math.PI/2+0.5],startSize:[0.5,1],endSize:[0.1,0.3],startAlpha:1,endAlpha:0,startTint:16746496,endTint:16720384,blendMode:"add",...A})},sparkle(k,A){return G({maxParticles:30,texture:k,spawnRate:10,duration:-1,lifetime:[0.5,1.5],speed:[10,40],angle:[0,O],startSize:[0.2,0.8],endSize:[0.1,0.4],startAlpha:[0.5,1],endAlpha:0,...A})},trail(k,A){return G({maxParticles:40,texture:k,spawnRate:20,duration:-1,lifetime:[0.3,0.8],speed:0,startSize:[0.5,1],endSize:[0.05,0.2],startAlpha:0.8,endAlpha:0,...A})}};function s(k){let{systemGroup:A="particles",priority:B=0,phase:Q="update"}=k??{},L=new Map;return C({id:"particles",install(q){q.registerRequired("particleEmitter","localTransform",()=>({x:0,y:0,rotation:0,scaleX:1,scaleY:1})),q.registerDispose("particleEmitter",({entityId:H})=>{let j=L.get(H);if(j){let $=j.pixiContainer;if($)$.removeFromParent?.(),$.destroy?.();L.delete(H)}}),q.addSystem("particle-update").setPriority(B).inPhase(Q).inGroup(A).addQuery("emitters",{with:["particleEmitter"]}).setProcess(({queries:H,dt:j,ecs:$})=>{for(let V of H.emitters){let Z=V.components.particleEmitter,J=L.get(V.id);if(!J)J={particles:E(Z.config.maxParticles),pixiContainer:null,pixiParticles:[]},L.set(V.id,J);let N=$.getComponent(V.id,"worldTransform"),K=N?.x??0,F=N?.y??0,U=N?.rotation??0;w(Z,J,j,K,F,U);let z=Z.config;if(z.duration>=0&&Z.elapsed>=z.duration&&Z.activeCount===0&&!Z.finished){if(Z.finished=!0,Z.onComplete)Z.onComplete({entityId:V.id});$.commands.removeComponent(V.id,"particleEmitter")}}}),q.addSystem("particle-render-sync").setPriority(400).inPhase("render").inGroup(A).setOnInitialize(async(H)=>{let j=await import("pixi.js"),$=j.ParticleContainer,V=j.Particle,Z=H.tryGetResource("rootContainer");H.addReactiveQuery("particle-emitters",{with:["particleEmitter"],onEnter:(J)=>{let K=J.components.particleEmitter.config,F=new $({dynamicProperties:{position:!0,rotation:!0,color:!0,vertex:!0}});F.blendMode=K.blendMode;let U=[];for(let h=0;h<K.maxParticles;h++){let S=new V({texture:K.texture});S.alpha=0,U.push(S),F.addParticle(S)}let z=E(K.maxParticles);if(Z)if(H.getComponent(J.id,"renderLayer"))Z.addChild(F);else Z.addChild(F);L.set(J.id,{particles:z,pixiContainer:F,pixiParticles:U})},onExit:(J)=>{let N=L.get(J);if(N){let K=N.pixiContainer;if(K)K.removeFromParent?.(),K.destroy?.();L.delete(J)}}})}).setProcess(({ecs:H})=>{for(let[j,$]of L){let V=H.getComponent(j,"particleEmitter");if(!V)continue;let Z=V.config;if(!Z.worldSpace){let J=H.getComponent(j,"worldTransform");if(J){let N=$.pixiContainer;N.position.set(J.x,J.y),N.rotation=J.rotation,N.scale.set(J.scaleX,J.scaleY)}}for(let J=0;J<V.activeCount;J++){let N=$.particles[J],K=$.pixiParticles[J];if(!N||!K)continue;K.x=N.x,K.y=N.y,K.scaleX=N.size,K.scaleY=N.size,K.rotation=N.rotation,K.tint=N.tint,K.alpha=N.alpha}for(let J=V.activeCount;J<Z.maxParticles;J++){let N=$.pixiParticles[J];if(N)N.alpha=0}}})}})}function m(k,A){return k.get(A)}export{u as stopEmitter,M as sampleRange,l as resumeEmitter,d as particlePresets,R as lerpTint,m as getEmitterData,G as defineParticleEffect,s as createParticlePlugin,g as createParticleEmitter,f as burstParticles};
|
|
2
|
-
|
|
3
|
-
//# debugId=2C024B5960E7854064756E2164756E21
|
|
4
|
-
//# sourceMappingURL=particles.js.map
|
|
@@ -1,4 +0,0 @@
|
|
|
1
|
-
var{defineProperty:N,getOwnPropertyNames:Y,getOwnPropertyDescriptor:w}=Object,I=Object.prototype.hasOwnProperty;var q=new WeakMap,u=(z)=>{var E=q.get(z),J;if(E)return E;if(E=N({},"__esModule",{value:!0}),z&&typeof z==="object"||typeof z==="function")Y(z).map((O)=>!I.call(E,O)&&N(E,O,{get:()=>z[O],enumerable:!(J=w(z,O))||J.enumerable}));return q.set(z,E),E};var p=(z,E)=>{for(var J in E)N(z,J,{get:E[J],enumerable:!0,configurable:!0,set:(O)=>E[J]=()=>O})};var y=(z,E)=>()=>(z&&(E=z(z=0)),E);var b=((z)=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(z,{get:(E,J)=>(typeof require<"u"?require:E)[J]}):z)(function(z){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+z+'" is not supported')});import{definePlugin as g}from"ecspresso";function M(z,E,J,O,Z,Q,K){if(!Q&&!K)return null;let k={entityId:z,x:E,y:J,layer:O,collidesWith:Z};if(Q)k.x+=Q.offsetX??0,k.y+=Q.offsetY??0,k.aabb={halfWidth:Q.width/2,halfHeight:Q.height/2};if(K)k.x+=K.offsetX??0,k.y+=K.offsetY??0,k.circle={radius:K.radius};return k}function S(z){return z("spatialIndex")}function B(z,E,J,O,Z,Q,K,k){let _=Z-z,j=Q-E,$=J+K-Math.abs(_),F=O+k-Math.abs(j);if($<=0||F<=0)return null;if($<F)return{normalX:_>=0?1:-1,normalY:0,depth:$};return{normalX:0,normalY:j>=0?1:-1,depth:F}}function f(z,E,J,O,Z,Q){let K=O-z,k=Z-E,_=K*K+k*k,j=J+Q;if(_>=j*j)return null;let $=Math.sqrt(_);if($===0)return{normalX:1,normalY:0,depth:j};return{normalX:K/$,normalY:k/$,depth:j-$}}function C(z,E,J,O,Z,Q,K){let k=Math.max(z-J,Math.min(Z,z+J)),_=Math.max(E-O,Math.min(Q,E+O)),j=Z-k,$=Q-_,F=j*j+$*$;if(F>=K*K)return null;if(F===0){let W=Z-(z-J),L=z+J-Z,R=Q-(E-O),V=E+O-Q,U=Math.min(W,L,R,V);if(U===L)return{normalX:1,normalY:0,depth:L+K};if(U===W)return{normalX:-1,normalY:0,depth:W+K};if(U===V)return{normalX:0,normalY:1,depth:V+K};return{normalX:0,normalY:-1,depth:R+K}}let T=Math.sqrt(F);return{normalX:j/T,normalY:$/T,depth:K-T}}function A(z,E){if(z.aabb&&E.aabb)return B(z.x,z.y,z.aabb.halfWidth,z.aabb.halfHeight,E.x,E.y,E.aabb.halfWidth,E.aabb.halfHeight);if(z.circle&&E.circle)return f(z.x,z.y,z.circle.radius,E.x,E.y,E.circle.radius);if(z.aabb&&E.circle)return C(z.x,z.y,z.aabb.halfWidth,z.aabb.halfHeight,E.x,E.y,E.circle.radius);if(z.circle&&E.aabb){let J=C(E.x,E.y,E.aabb.halfWidth,E.aabb.halfHeight,z.x,z.y,z.circle.radius);if(!J)return null;return{normalX:-J.normalX,normalY:-J.normalY,depth:J.depth}}return null}var P=new Set;function X(z,E,J,O){if(E)m(z,E,J,O);else x(z,J,O)}function x(z,E,J){for(let O=0;O<z.length;O++){let Z=z[O];if(!Z)continue;for(let Q=O+1;Q<z.length;Q++){let K=z[Q];if(!K)continue;if(!Z.collidesWith.includes(K.layer)&&!K.collidesWith.includes(Z.layer))continue;let k=A(Z,K);if(!k)continue;E(Z,K,k,J)}}}function m(z,E,J,O){let Z=new Map;for(let Q=0;Q<z.length;Q++){let K=z[Q];if(!K)continue;Z.set(K.entityId,K)}for(let Q=0;Q<z.length;Q++){let K=z[Q];if(!K)continue;let k=K.aabb?K.aabb.halfWidth:K.circle?K.circle.radius:0,_=K.aabb?K.aabb.halfHeight:K.circle?K.circle.radius:0;P.clear(),E.queryRectInto(K.x-k,K.y-_,K.x+k,K.y+_,P);for(let j of P){if(j<=K.entityId)continue;let $=Z.get(j);if(!$)continue;if(!K.collidesWith.includes($.layer)&&!$.collidesWith.includes(K.layer))continue;let F=A(K,$);if(!F)continue;J(K,$,F,O)}}}function s(z,E){return{rigidBody:{type:z,mass:z==="static"?1/0:E?.mass??1,drag:E?.drag??0,restitution:E?.restitution??0,friction:E?.friction??0,gravityScale:E?.gravityScale??1},force:{x:0,y:0}}}function i(z,E){return{force:{x:z,y:E}}}function o(z,E,J,O){let Z=z.getComponent(E,"force");if(!Z)return;Z.x+=J,Z.y+=O}function e(z,E,J,O){let Z=z.getComponent(E,"velocity"),Q=z.getComponent(E,"rigidBody");if(!Z||!Q)return;if(Q.mass===1/0||Q.mass===0)return;Z.x+=J/Q.mass,Z.y+=O/Q.mass}function c(z,E,J,O){let Z=z.getComponent(E,"velocity");if(!Z)return;Z.x=J,Z.y=O}function v(z,E,J,O){let Z=z.rigidBody.type==="dynamic"&&z.rigidBody.mass>0&&z.rigidBody.mass!==1/0?1/z.rigidBody.mass:0,Q=E.rigidBody.type==="dynamic"&&E.rigidBody.mass>0&&E.rigidBody.mass!==1/0?1/E.rigidBody.mass:0,K=Z+Q;if(K>0){let k=J.depth/K;if(Z>0){let F=O.getComponent(z.entityId,"localTransform");if(!F)return;F.x-=k*Z*J.normalX,F.y-=k*Z*J.normalY,z.x=F.x,O.markChanged(z.entityId,"localTransform")}if(Q>0){let F=O.getComponent(E.entityId,"localTransform");if(!F)return;F.x+=k*Q*J.normalX,F.y+=k*Q*J.normalY,O.markChanged(E.entityId,"localTransform")}let _=E.velocity.x-z.velocity.x,j=E.velocity.y-z.velocity.y,$=_*J.normalX+j*J.normalY;if($<0){let T=-(1+Math.min(z.rigidBody.restitution,E.rigidBody.restitution))*$/K;z.velocity.x-=T*Z*J.normalX,z.velocity.y-=T*Z*J.normalY,E.velocity.x+=T*Q*J.normalX,E.velocity.y+=T*Q*J.normalY;let W=_-$*J.normalX,L=j-$*J.normalY,R=Math.sqrt(W*W+L*L);if(R>0.000001){let V=W/R,U=L/R,G=Math.sqrt(z.rigidBody.friction*E.rigidBody.friction)*Math.abs(T),H=Math.min(R/K,G);z.velocity.x+=H*Z*V,z.velocity.y+=H*Z*U,E.velocity.x-=H*Q*V,E.velocity.y-=H*Q*U}}O.markChanged(z.entityId,"velocity"),O.markChanged(E.entityId,"velocity")}O.eventBus.publish("physicsCollision",{entityA:z.entityId,entityB:E.entityId,normal:{x:J.normalX,y:J.normalY},depth:J.depth})}function h(z,E,J,O){v(z,E,J,O)}function t(z){let{gravity:E={x:0,y:0},systemGroup:J="physics2D",collisionSystemGroup:O,integrationPriority:Z=1000,collisionPriority:Q=900,phase:K="fixedUpdate"}=z??{};return g({id:"physics2D",install(k){k.registerRequired("rigidBody","velocity",()=>({x:0,y:0})),k.registerRequired("rigidBody","force",()=>({x:0,y:0})),k.addResource("physicsConfig",{gravity:{x:E.x,y:E.y}}),k.addSystem("physics2D-integration").setPriority(Z).inPhase(K).inGroup(J).addQuery("bodies",{with:["localTransform","velocity","rigidBody","force"]}).setProcess(({queries:j,dt:$,ecs:F})=>{let T=F.getResource("physicsConfig"),W=T.gravity.x,L=T.gravity.y;for(let R of j.bodies){let{localTransform:V,velocity:U,rigidBody:D,force:G}=R.components;if(D.type==="static")continue;if(D.type==="dynamic"){if(U.x+=W*D.gravityScale*$,U.y+=L*D.gravityScale*$,D.mass>0&&D.mass!==1/0)U.x+=G.x/D.mass*$,U.y+=G.y/D.mass*$;if(D.drag>0){let H=Math.max(0,1-D.drag*$);U.x*=H,U.y*=H}}V.x+=U.x*$,V.y+=U.y*$,G.x=0,G.y=0,F.markChanged(R.id,"localTransform")}});let _=k.addSystem("physics2D-collision").setPriority(Q).inPhase(K).inGroup(J);if(O)_.inGroup(O);_.addQuery("collidables",{with:["localTransform","rigidBody","velocity","collisionLayer"]}).setProcess(({queries:j,ecs:$})=>{let F=[];for(let W of j.collidables){let{localTransform:L,rigidBody:R,velocity:V,collisionLayer:U}=W.components,D=M(W.id,L.x,L.y,U.layer,U.collidesWith,$.getComponent(W.id,"aabbCollider"),$.getComponent(W.id,"circleCollider"));if(!D)continue;F.push(Object.assign(D,{rigidBody:R,velocity:V}))}let T=S($.tryGetResource.bind($));X(F,T,h,$)})}})}export{c as setVelocity,s as createRigidBody,t as createPhysics2DPlugin,i as createForce,e as applyImpulse,o as applyForce};
|
|
2
|
-
|
|
3
|
-
//# debugId=C0942B5817EAD45864756E2164756E21
|
|
4
|
-
//# sourceMappingURL=physics2D.js.map
|
|
@@ -1,4 +0,0 @@
|
|
|
1
|
-
var{defineProperty:T,getOwnPropertyNames:h,getOwnPropertyDescriptor:w}=Object,y=Object.prototype.hasOwnProperty;var v=new WeakMap,a=(F)=>{var K=v.get(F),D;if(K)return K;if(K=T({},"__esModule",{value:!0}),F&&typeof F==="object"||typeof F==="function")h(F).map((E)=>!y.call(K,E)&&T(K,E,{get:()=>F[E],enumerable:!(D=w(F,E))||D.enumerable}));return v.set(F,K),K};var r=(F,K)=>{for(var D in K)T(F,D,{get:K[D],enumerable:!0,configurable:!0,set:(E)=>K[D]=()=>E})};var n=(F,K)=>()=>(F&&(K=F(F=0)),K);var C=((F)=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(F,{get:(K,D)=>(typeof require<"u"?require:K)[D]}):F)(function(F){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+F+'" is not supported')});import{definePlugin as d}from"ecspresso";import{createTransformPlugin as l}from"ecspresso/plugins/transform";import{createBounds as H}from"ecspresso/plugins/bounds";import{createTransform as Uz,createLocalTransform as Zz,createWorldTransform as _z,DEFAULT_LOCAL_TRANSFORM as $z,DEFAULT_WORLD_TRANSFORM as kz}from"ecspresso/plugins/transform";async function p(F){let{Application:K}=await import("pixi.js"),D=new K;return await D.init(F),D}function Y(F,K){let D=K?.scale,E=typeof D==="number"?D:D?.x??1,G=typeof D==="number"?D:D?.y??1;return{x:F?.x??0,y:F?.y??0,rotation:K?.rotation??0,scaleX:E,scaleY:G}}function S(F,K){let D=K?.scale,E=typeof D==="number"?D:D?.x??1,G=typeof D==="number"?D:D?.y??1;return{x:F?.x??0,y:F?.y??0,rotation:K?.rotation??0,scaleX:E,scaleY:G}}function P(F){return{visible:F?.visible??!0,alpha:F?.alpha}}function e(F,K,D){if(D?.anchor)F.anchor.set(D.anchor.x,D.anchor.y);return{sprite:F,localTransform:Y(K,D),worldTransform:S(K,D),visible:P(D)}}function zz(F,K,D){return{graphics:F,localTransform:Y(K,D),worldTransform:S(K,D),visible:P(D)}}function Dz(F,K,D){return{container:F,localTransform:Y(K,D),worldTransform:S(K,D),visible:P(D)}}var c={fit:(F,K)=>{let D=Math.min(F,K);return{scaleX:D,scaleY:D}},cover:(F,K)=>{let D=Math.max(F,K);return{scaleX:D,scaleY:D}},stretch:(F,K)=>({scaleX:F,scaleY:K})};function b(F,K,D,E,G){let V=F/D,j=K/E,{scaleX:X,scaleY:N}=c[G](V,j);return{scaleX:X,scaleY:N,offsetX:(F-D*X)/2,offsetY:(K-E*N)/2,physicalWidth:F,physicalHeight:K,designWidth:D,designHeight:E}}function Fz(F,K,D){return{x:(F-D.offsetX)/D.scaleX,y:(K-D.offsetY)/D.scaleY}}function Jz(F){let{rootContainer:K,systemGroup:D="renderer2d",renderSyncPriority:E=500,transform:G,startLoop:V=!0,renderLayers:j=[],camera:X=!1,screenScale:N}=F,q=N!==void 0,A=N?.width??0,L=N?.height??0,W=N?.mode??"fit",R=new Map,I=new Map,f=()=>{throw Error("renderer2D: createLayerContainer called before initialization")};function g(Z,J){let Q=I.get(Z);if(Q)return Q;let U=f(`layer:${Z}`);return I.set(Z,U),J.addChild(U),U}function u(Z,J){let Q=J.getResource("rootContainer"),U=J.getComponent(Z,"renderLayer");if(U)return g(U,Q);return Q}function O(Z,J,Q){let U=u(Z,Q);if(J.parent!==U)U.addChild(J)}function x(Z,J){let Q=R.get(Z);if(!Q)return;let U=u(Z,J);if(Q.parent!==U)Q.removeFromParent(),U.addChild(Q)}let m="init"in F&&F.init!==void 0;return d({id:"renderer2d",install(Z){if(Z.installPlugin(l(G)),m){let{init:J,container:Q}=F;if(Z.addResource("pixiApp",async()=>{let U=await p(J);if(Q){let _=typeof Q==="string"?document.querySelector(Q):Q;if(_)_.appendChild(U.canvas);else if(typeof Q==="string")console.warn(`Renderer2D plugin: container selector "${Q}" not found`)}return U}),Z.addResource("rootContainer",{dependsOn:["pixiApp"],factory:(U)=>K??U.getResource("pixiApp").stage}),Z.addResource("bounds",{dependsOn:["pixiApp"],factory:(U)=>{if(q)return H(A,L);let _=U.getResource("pixiApp");return H(_.screen.width,_.screen.height)}}),q)Z.addResource("viewportScale",{dependsOn:["pixiApp"],factory:(U)=>{let _=U.getResource("pixiApp");return b(_.screen.width,_.screen.height,A,L,W)}})}else{let J=F.app;if(Z.addResource("pixiApp",J),Z.addResource("rootContainer",K??J.stage),Z.addResource("bounds",q?H(A,L):H(J.screen.width,J.screen.height)),q)Z.addResource("viewportScale",b(J.screen.width,J.screen.height,A,L,W))}if(Z.registerDispose("sprite",({value:J})=>{J.removeFromParent()}),Z.registerDispose("graphics",({value:J})=>{J.removeFromParent()}),Z.registerDispose("container",({value:J})=>{J.removeFromParent()}),Z.registerRequired("sprite","localTransform",()=>Y()),Z.registerRequired("sprite","visible",()=>P()),Z.registerRequired("graphics","localTransform",()=>Y()),Z.registerRequired("graphics","visible",()=>P()),Z.registerRequired("container","localTransform",()=>Y()),Z.registerRequired("container","visible",()=>P()),Z.addSystem("renderer2d-sync").setPriority(E).inPhase("render").inGroup(D).addQuery("sprites",{with:["sprite","worldTransform"],changed:["worldTransform"]}).addQuery("graphics",{with:["graphics","worldTransform"],changed:["worldTransform"]}).addQuery("containers",{with:["container","worldTransform"],changed:["worldTransform"]}).setProcess(({queries:J,ecs:Q})=>{for(let U of J.sprites){let{sprite:_,worldTransform:$}=U.components;_.position.set($.x,$.y),_.rotation=$.rotation,_.scale.set($.scaleX,$.scaleY);let z=Q.getComponent(U.id,"visible");if(z){if(_.visible=z.visible,z.alpha!==void 0)_.alpha=z.alpha}}for(let U of J.graphics){let{graphics:_,worldTransform:$}=U.components;_.position.set($.x,$.y),_.rotation=$.rotation,_.scale.set($.scaleX,$.scaleY);let z=Q.getComponent(U.id,"visible");if(z){if(_.visible=z.visible,z.alpha!==void 0)_.alpha=z.alpha}}for(let U of J.containers){let{container:_,worldTransform:$}=U.components;_.position.set($.x,$.y),_.rotation=$.rotation,_.scale.set($.scaleX,$.scaleY);let z=Q.getComponent(U.id,"visible");if(z){if(_.visible=z.visible,z.alpha!==void 0)_.alpha=z.alpha}}}),Z.addSystem("renderer2d-scene-graph").setPriority(9999).inGroup(D).setOnInitialize(async(J)=>{let Q=J.getResource("pixiApp"),U=J.getResource("rootContainer"),{Container:_}=await import("pixi.js");f=(z)=>{let k=new _;return k.label=z,k};let $;if(q){$=new _,$.label="viewportContainer";let z=J.tryGetResource("viewportScale");if(!z)throw Error("renderer2D: viewportScale resource not found");$.position.set(z.offsetX,z.offsetY),$.scale.set(z.scaleX,z.scaleY);let k=new _;k.label="rootContainer",Q.stage.addChild($),$.addChild(k),J.updateResource("rootContainer",()=>k),U=k}for(let z of j){let k=f(`layer:${z}`);I.set(z,k),U.addChild(k)}if(J.addReactiveQuery("renderer2d-sprites",{with:["sprite"],onEnter:(z)=>{let k=z.components.sprite;R.set(z.id,k),O(z.id,k,J)},onExit:(z)=>{R.delete(z)}}),J.addReactiveQuery("renderer2d-graphics",{with:["graphics"],onEnter:(z)=>{let k=z.components.graphics;R.set(z.id,k),O(z.id,k,J)},onExit:(z)=>{R.delete(z)}}),J.addReactiveQuery("renderer2d-containers",{with:["container"],onEnter:(z)=>{let k=z.components.container;R.set(z.id,k),O(z.id,k,J)},onExit:(z)=>{R.delete(z)}}),J.on("hierarchyChanged",({entityId:z})=>{x(z,J)}),J.onComponentAdded("renderLayer",({entity:z})=>{x(z.id,J)}),J.onComponentRemoved("renderLayer",({entity:z})=>{x(z.id,J)}),X){let z=J.tryGetResource("cameraState");if(!z)throw Error("renderer2D: cameraState resource not found");z.viewportWidth=q?A:Q.screen.width,z.viewportHeight=q?L:Q.screen.height}if(Q.renderer.on("resize",(z,k)=>{if(q){let B=b(z,k,A,L,W),M=J.tryGetResource("viewportScale");if(!M)throw Error("renderer2D: viewportScale resource not found");if(M.scaleX=B.scaleX,M.scaleY=B.scaleY,M.offsetX=B.offsetX,M.offsetY=B.offsetY,M.physicalWidth=z,M.physicalHeight=k,$)$.position.set(B.offsetX,B.offsetY),$.scale.set(B.scaleX,B.scaleY)}else{let B=J.getResource("bounds");if(B.width=z,B.height=k,X){let M=J.tryGetResource("cameraState");if(!M)throw Error("renderer2D: cameraState resource not found");M.viewportWidth=z,M.viewportHeight=k}}}),V)Q.ticker.add((z)=>{J.update(z.deltaMS/1000)})}),X)Z.addSystem("renderer2d-camera-sync").setPriority(900).inPhase("render").inGroup(D).setProcess(({ecs:J})=>{let Q=J.tryGetResource("cameraState");if(!Q)throw Error("renderer2D: cameraState resource not found");let U=J.getResource("rootContainer"),[_,$]=q?[A,L]:[J.getResource("pixiApp").screen.width,J.getResource("pixiApp").screen.height];U.position.set(_/2-(Q.x+Q.shakeOffsetX)*Q.zoom,$/2-(Q.y+Q.shakeOffsetY)*Q.zoom),U.scale.set(Q.zoom),U.rotation=-(Q.rotation+Q.shakeRotation)})}})}export{Fz as physicalToLogical,_z as createWorldTransform,Uz as createTransform,e as createSpriteComponents,Jz as createRenderer2DPlugin,Zz as createLocalTransform,zz as createGraphicsComponents,Dz as createContainerComponents,b as computeViewportScale,kz as DEFAULT_WORLD_TRANSFORM,$z as DEFAULT_LOCAL_TRANSFORM};
|
|
2
|
-
|
|
3
|
-
//# debugId=807650CF91C1BBE864756E2164756E21
|
|
4
|
-
//# sourceMappingURL=renderer2D.js.map
|