ecspresso 0.12.7 → 0.13.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (55) hide show
  1. package/README.md +11 -0
  2. package/dist/index.js +2 -2
  3. package/dist/index.js.map +5 -5
  4. package/dist/plugin.d.ts +89 -22
  5. package/dist/plugins/audio.d.ts +2 -3
  6. package/dist/plugins/audio.js +2 -2
  7. package/dist/plugins/audio.js.map +3 -3
  8. package/dist/plugins/bounds.d.ts +2 -3
  9. package/dist/plugins/bounds.js +2 -2
  10. package/dist/plugins/bounds.js.map +3 -3
  11. package/dist/plugins/camera.d.ts +1 -2
  12. package/dist/plugins/camera.js +2 -2
  13. package/dist/plugins/camera.js.map +3 -3
  14. package/dist/plugins/collision.d.ts +9 -8
  15. package/dist/plugins/collision.js +2 -2
  16. package/dist/plugins/collision.js.map +4 -4
  17. package/dist/plugins/coroutine.d.ts +2 -3
  18. package/dist/plugins/coroutine.js +2 -2
  19. package/dist/plugins/coroutine.js.map +3 -3
  20. package/dist/plugins/diagnostics.d.ts +1 -3
  21. package/dist/plugins/diagnostics.js +2 -2
  22. package/dist/plugins/diagnostics.js.map +3 -3
  23. package/dist/plugins/input.d.ts +11 -3
  24. package/dist/plugins/input.js +2 -2
  25. package/dist/plugins/input.js.map +3 -3
  26. package/dist/plugins/particles.d.ts +2 -2
  27. package/dist/plugins/particles.js +2 -2
  28. package/dist/plugins/particles.js.map +3 -3
  29. package/dist/plugins/physics2D.d.ts +8 -5
  30. package/dist/plugins/physics2D.js +2 -2
  31. package/dist/plugins/physics2D.js.map +4 -4
  32. package/dist/plugins/renderers/renderer2D.d.ts +36 -9
  33. package/dist/plugins/renderers/renderer2D.js +2 -2
  34. package/dist/plugins/renderers/renderer2D.js.map +3 -3
  35. package/dist/plugins/spatial-index.d.ts +1 -4
  36. package/dist/plugins/spatial-index.js +2 -2
  37. package/dist/plugins/spatial-index.js.map +4 -4
  38. package/dist/plugins/sprite-animation.d.ts +2 -3
  39. package/dist/plugins/sprite-animation.js +2 -2
  40. package/dist/plugins/sprite-animation.js.map +3 -3
  41. package/dist/plugins/state-machine.d.ts +2 -3
  42. package/dist/plugins/state-machine.js +2 -2
  43. package/dist/plugins/state-machine.js.map +3 -3
  44. package/dist/plugins/timers.d.ts +2 -3
  45. package/dist/plugins/timers.js +2 -2
  46. package/dist/plugins/timers.js.map +3 -3
  47. package/dist/plugins/transform.d.ts +3 -3
  48. package/dist/plugins/transform.js +2 -2
  49. package/dist/plugins/transform.js.map +3 -3
  50. package/dist/plugins/tween.d.ts +2 -3
  51. package/dist/plugins/tween.js +2 -2
  52. package/dist/plugins/tween.js.map +3 -3
  53. package/dist/utils/narrowphase.d.ts +60 -19
  54. package/dist/utils/spatial-hash.d.ts +11 -1
  55. package/package.json +6 -3
@@ -5,8 +5,7 @@
5
5
  * Uses worldTransform for position (world-space collision).
6
6
  * Supports AABB and circle colliders.
7
7
  */
8
- import { type Plugin, type BasePluginOptions } from 'ecspresso';
9
- import type { WorldConfigFrom } from '../type-utils';
8
+ import { type BasePluginOptions } from 'ecspresso';
10
9
  import type { TransformWorldConfig } from './transform';
11
10
  /**
12
11
  * Axis-Aligned Bounding Box collider.
@@ -60,6 +59,9 @@ export interface CollisionComponentTypes<L extends string = never> {
60
59
  }
61
60
  /**
62
61
  * Event fired when two entities collide.
62
+ *
63
+ * Normal components are flattened (`normalX`/`normalY`) rather than nested
64
+ * in a sub-object to avoid a per-event allocation in the collision hot path.
63
65
  */
64
66
  export interface CollisionEvent<L extends string = never> {
65
67
  /** First entity in the collision */
@@ -70,11 +72,10 @@ export interface CollisionEvent<L extends string = never> {
70
72
  layerA: L;
71
73
  /** Layer of the second entity */
72
74
  layerB: L;
73
- /** Contact normal pointing from entityA toward entityB */
74
- normal: {
75
- x: number;
76
- y: number;
77
- };
75
+ /** Contact normal X, pointing from entityA toward entityB */
76
+ normalX: number;
77
+ /** Contact normal Y, pointing from entityA toward entityB */
78
+ normalY: number;
78
79
  /** Penetration depth (positive = overlapping) */
79
80
  depth: number;
80
81
  }
@@ -281,5 +282,5 @@ export declare function createCollisionPairHandler<W = unknown, L extends string
281
282
  */
282
283
  export declare function createCollisionPlugin<L extends string, G extends string = 'physics'>(options: CollisionPluginOptions<G> & {
283
284
  layers: LayerFactories<Record<L, readonly string[]>>;
284
- }): Plugin<WorldConfigFrom<CollisionComponentTypes<L>, CollisionEventTypes<L>>, TransformWorldConfig, 'collision-detection', G>;
285
+ }): import("ecspresso").Plugin<import("ecspresso").WithEvents<import("ecspresso").WithComponents<import("ecspresso").EmptyConfig, CollisionComponentTypes<L>>, CollisionEventTypes<L>>, TransformWorldConfig, "collision-detection", G, never, never>;
285
286
  export {};
@@ -1,4 +1,4 @@
1
- var X=((z)=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(z,{get:(N,O)=>(typeof require<"u"?require:N)[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 B}from"ecspresso";function W(z,N,O,Q,Z,$,J){if(!$&&!J)return null;let F={entityId:z,x:N,y:O,layer:Q,collidesWith:Z};if($)F.x+=$.offsetX??0,F.y+=$.offsetY??0,F.aabb={halfWidth:$.width/2,halfHeight:$.height/2};if(J)F.x+=J.offsetX??0,F.y+=J.offsetY??0,F.circle={radius:J.radius};return F}function q(z){return z("spatialIndex")}function g(z,N,O,Q,Z,$,J,F){let E=Z-z,M=$-N,V=O+J-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 I(z,N,O,Q,Z,$){let J=Q-z,F=Z-N,E=J*J+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:J/V,normalY:F/V,depth:M-V}}function T(z,N,O,Q,Z,$,J){let F=Math.max(z-O,Math.min(Z,z+O)),E=Math.max(N-Q,Math.min($,N+Q)),M=Z-F,V=$-E,j=M*M+V*V;if(j>=J*J)return null;if(j===0){let U=Z-(z-O),G=z+O-Z,K=$-(N-Q),R=N+Q-$,H=Math.min(U,G,K,R);if(H===G)return{normalX:1,normalY:0,depth:G+J};if(H===U)return{normalX:-1,normalY:0,depth:U+J};if(H===R)return{normalX:0,normalY:1,depth:R+J};return{normalX:0,normalY:-1,depth:K+J}}let _=Math.sqrt(j);return{normalX:M/_,normalY:V/_,depth:J-_}}function L(z,N){if(z.aabb&&N.aabb)return g(z.x,z.y,z.aabb.halfWidth,z.aabb.halfHeight,N.x,N.y,N.aabb.halfWidth,N.aabb.halfHeight);if(z.circle&&N.circle)return I(z.x,z.y,z.circle.radius,N.x,N.y,N.circle.radius);if(z.aabb&&N.circle)return T(z.x,z.y,z.aabb.halfWidth,z.aabb.halfHeight,N.x,N.y,N.circle.radius);if(z.circle&&N.aabb){let O=T(N.x,N.y,N.aabb.halfWidth,N.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 D=new Set;function P(z,N,O,Q){if(N)k(z,N,O,Q);else A(z,O,Q)}function A(z,N,O){for(let Q=0;Q<z.length;Q++){let Z=z[Q];if(!Z)continue;for(let $=Q+1;$<z.length;$++){let J=z[$];if(!J)continue;if(!Z.collidesWith.includes(J.layer)&&!J.collidesWith.includes(Z.layer))continue;let F=L(Z,J);if(!F)continue;N(Z,J,F,O)}}}function k(z,N,O,Q){let Z=new Map;for(let $=0;$<z.length;$++){let J=z[$];if(!J)continue;Z.set(J.entityId,J)}for(let $=0;$<z.length;$++){let J=z[$];if(!J)continue;let F=J.aabb?J.aabb.halfWidth:J.circle?J.circle.radius:0,E=J.aabb?J.aabb.halfHeight:J.circle?J.circle.radius:0;D.clear(),N.queryRectInto(J.x-F,J.y-E,J.x+F,J.y+E,D);for(let M of D){if(M<=J.entityId)continue;let V=Z.get(M);if(!V)continue;if(!J.collidesWith.includes(V.layer)&&!V.collidesWith.includes(J.layer))continue;let j=L(J,V);if(!j)continue;O(J,V,j,Q)}}}function f(z,N,O,Q){let Z={width:z,height:N};if(O!==void 0)Z.offsetX=O;if(Q!==void 0)Z.offsetY=Q;return{aabbCollider:Z}}function u(z,N,O){let Q={radius:z};if(N!==void 0)Q.offsetX=N;if(O!==void 0)Q.offsetY=O;return{circleCollider:Q}}function v(z,N){return{collisionLayer:{layer:z,collidesWith:N}}}function h(z){let N={};for(let O of Object.keys(z)){let Q=z[O];N[O]=()=>v(O,Q)}return N}function S(z){let N=z.indexOf(":");if(N===-1)throw Error(`Invalid collision pair key "${z}": must contain a colon separator (e.g. "player:enemy")`);let O=z.slice(0,N),Q=z.slice(N+1);if(O===""||Q==="")throw Error(`Invalid collision pair key "${z}": layer names must not be empty`);return[O,Q]}function p(z){let N=new Map,O=new Set;for(let Q of Object.keys(z))S(Q),O.add(Q);for(let Q of Object.keys(z)){let[Z,$]=S(Q),J=z[Q];if(!J)continue;N.set(Q,{callback:J,swapped:!1});let F=`${$}:${Z}`;if(F!==Q&&!O.has(F))N.set(F,{callback:J,swapped:!0})}return function({data:Z,ecs:$}){let J=N.get(Z.layerA+":"+Z.layerB);if(!J)return;if(J.swapped)J.callback(Z.entityB,Z.entityA,$);else J.callback(Z.entityA,Z.entityB,$)}}function C(z,N,O,Q){Q.publish("collision",{entityA:z.entityId,entityB:N.entityId,layerA:z.layer,layerB:N.layer,normal:{x:O.normalX,y:O.normalY},depth:O.depth})}function y(z){let{systemGroup:N="physics",priority:O=0,phase:Q="postUpdate"}=z;return B({id:"collision",install(Z){Z.addSystem("collision-detection").setPriority(O).inPhase(Q).inGroup(N).addQuery("collidables",{with:["worldTransform","collisionLayer"]}).setProcess(({queries:$,ecs:J})=>{let F=[];for(let M of $.collidables){let{worldTransform:V,collisionLayer:j}=M.components,_=W(M.id,V.x,V.y,j.layer,j.collidesWith,J.getComponent(M.id,"aabbCollider"),J.getComponent(M.id,"circleCollider"));if(_)F.push(_)}let E=q(J.tryGetResource.bind(J));P(F,E,C,J.eventBus)})}})}export{h as defineCollisionLayers,y as createCollisionPlugin,p as createCollisionPairHandler,v as createCollisionLayer,u as createCircleCollider,f as createAABBCollider};
1
+ var p=((z)=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(z,{get:(J,Z)=>(typeof require<"u"?require:J)[Z]}):z)(function(z){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+z+'" is not supported')});import{definePlugin as v}from"ecspresso";var H={normalX:0,normalY:0,depth:0},S=0;function g(z,J,Z,N,V,O,$,Q){if(z.entityId=J,z.layer=V,z.collidesWith=O,$)return z.x=Z+($.offsetX??0),z.y=N+($.offsetY??0),z.shape=0,z.halfWidth=$.width/2,z.halfHeight=$.height/2,z.radius=0,!0;if(Q)return z.x=Z+(Q.offsetX??0),z.y=N+(Q.offsetY??0),z.shape=1,z.halfWidth=0,z.halfHeight=0,z.radius=Q.radius,!0;return!1}function _(z){return z("spatialIndex")}function m(z,J,Z,N,V,O,$,Q,E){let G=V-z,F=O-J,j=Z+$-Math.abs(G),U=N+Q-Math.abs(F);if(j<=0||U<=0)return!1;if(j<U)return E.normalX=G>=0?1:-1,E.normalY=0,E.depth=j,!0;return E.normalX=0,E.normalY=F>=0?1:-1,E.depth=U,!0}function C(z,J,Z,N,V,O,$){let Q=N-z,E=V-J,G=Q*Q+E*E,F=Z+O;if(G>=F*F)return!1;let j=Math.sqrt(G);if(j===0)return $.normalX=1,$.normalY=0,$.depth=F,!0;return $.normalX=Q/j,$.normalY=E/j,$.depth=F-j,!0}function W(z,J,Z,N,V,O,$,Q){let E=Math.max(z-Z,Math.min(V,z+Z)),G=Math.max(J-N,Math.min(O,J+N)),F=V-E,j=O-G,U=F*F+j*j;if(U>=$*$)return!1;if(U===0){let T=V-(z-Z),q=z+Z-V,K=O-(J-N),L=J+N-O,P=Math.min(T,q,K,L);if(P===q)return Q.normalX=1,Q.normalY=0,Q.depth=q+$,!0;if(P===T)return Q.normalX=-1,Q.normalY=0,Q.depth=T+$,!0;if(P===L)return Q.normalX=0,Q.normalY=1,Q.depth=L+$,!0;return Q.normalX=0,Q.normalY=-1,Q.depth=K+$,!0}let D=Math.sqrt(U);return Q.normalX=F/D,Q.normalY=j/D,Q.depth=$-D,!0}function A(z,J,Z){if(z.shape===0&&J.shape===0)return m(z.x,z.y,z.halfWidth,z.halfHeight,J.x,J.y,J.halfWidth,J.halfHeight,Z);if(z.shape===1&&J.shape===1)return C(z.x,z.y,z.radius,J.x,J.y,J.radius,Z);if(z.shape===0&&J.shape===1)return W(z.x,z.y,z.halfWidth,z.halfHeight,J.x,J.y,J.radius,Z);if(!W(J.x,J.y,J.halfWidth,J.halfHeight,z.x,z.y,z.radius,Z))return!1;return Z.normalX=-Z.normalX,Z.normalY=-Z.normalY,!0}var R=new Set,M=!1,k=50;function B(z,J,Z,N,V,O){if(N)Y(z,J,Z,N,V,O);else X(z,J,V,O)}function X(z,J,Z,N){if(!M&&J>=k)M=!0,console.warn(`[ecspresso] Collision detection is using O(n²) brute force with ${J} colliders. For better performance, install createSpatialIndexPlugin() alongside your collision or physics2D plugin.`);for(let V=0;V<J;V++){let O=z[V];if(!O)continue;for(let $=V+1;$<J;$++){let Q=z[$];if(!Q)continue;if(!O.collidesWith.includes(Q.layer)&&!Q.collidesWith.includes(O.layer))continue;if(!A(O,Q,H))continue;Z(O,Q,H,N)}}}function Y(z,J,Z,N,V,O){Z.clear();for(let $=0;$<J;$++){let Q=z[$];if(!Q)continue;Z.set(Q.entityId,Q)}for(let $=0;$<J;$++){let Q=z[$];if(!Q)continue;let E=Q.shape===0?Q.halfWidth:Q.radius,G=Q.shape===0?Q.halfHeight:Q.radius;R.clear(),N.queryRectInto(Q.x-E,Q.y-G,Q.x+E,Q.y+G,R);for(let F of R){if(F<=Q.entityId)continue;let j=Z.get(F);if(!j)continue;if(!Q.collidesWith.includes(j.layer)&&!j.collidesWith.includes(Q.layer))continue;if(!A(Q,j,H))continue;V(Q,j,H,O)}}}function d(z,J,Z,N){let V={width:z,height:J};if(Z!==void 0)V.offsetX=Z;if(N!==void 0)V.offsetY=N;return{aabbCollider:V}}function u(z,J,Z){let N={radius:z};if(J!==void 0)N.offsetX=J;if(Z!==void 0)N.offsetY=Z;return{circleCollider:N}}function w(z,J){return{collisionLayer:{layer:z,collidesWith:J}}}function n(z){let J={};for(let Z of Object.keys(z)){let N=z[Z];J[Z]=()=>w(Z,N)}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 Z=z.slice(0,J),N=z.slice(J+1);if(Z===""||N==="")throw Error(`Invalid collision pair key "${z}": layer names must not be empty`);return[Z,N]}function s(z){let J=new Map,Z=new Set;for(let N of Object.keys(z))I(N),Z.add(N);for(let N of Object.keys(z)){let[V,O]=I(N),$=z[N];if(!$)continue;J.set(N,{callback:$,swapped:!1});let Q=`${O}:${V}`;if(Q!==N&&!Z.has(Q))J.set(Q,{callback:$,swapped:!0})}return function({data:V,ecs:O}){let $=J.get(V.layerA+":"+V.layerB);if(!$)return;if($.swapped)$.callback(V.entityB,V.entityA,O);else $.callback(V.entityA,V.entityB,O)}}function x(z,J,Z,N){N.publish("collision",{entityA:z.entityId,entityB:J.entityId,layerA:z.layer,layerB:J.layer,normalX:Z.normalX,normalY:Z.normalY,depth:Z.depth})}function l(z){let{systemGroup:J="physics",priority:Z=0,phase:N="postUpdate"}=z;return v("collision").withComponentTypes().withEventTypes().withLabels().withGroups().requires().install((V)=>{let O=[],$=new Map;V.addSystem("collision-detection").setPriority(Z).inPhase(N).inGroup(J).addQuery("collidables",{with:["worldTransform","collisionLayer"]}).setProcess(({queries:Q,ecs:E})=>{let G=0;for(let j of Q.collidables){let{worldTransform:U,collisionLayer:D}=j.components,T=E.getComponent(j.id,"aabbCollider"),q=E.getComponent(j.id,"circleCollider");if(!T&&!q)continue;let K=O[G];if(!K)K={entityId:j.id,x:U.x,y:U.y,layer:D.layer,collidesWith:D.collidesWith,shape:S,halfWidth:0,halfHeight:0,radius:0},O[G]=K;if(!g(K,j.id,U.x,U.y,D.layer,D.collidesWith,T,q))continue;G++}let F=_(E.tryGetResource.bind(E));B(O,G,$,F,x,E.eventBus)})})}export{n as defineCollisionLayers,l as createCollisionPlugin,s as createCollisionPairHandler,w as createCollisionLayer,u as createCircleCollider,d as createAABBCollider};
2
2
 
3
- //# debugId=7ADE1421E2F39B1D64756E2164756E21
3
+ //# debugId=F585870CBB7BB34564756E2164756E21
4
4
  //# sourceMappingURL=collision.js.map
@@ -2,10 +2,10 @@
2
2
  "version": 3,
3
3
  "sources": ["../src/plugins/collision.ts", "../src/utils/narrowphase.ts"],
4
4
  "sourcesContent": [
5
- "/**\n * Collision Plugin for ECSpresso\n *\n * Provides layer-based collision detection with events.\n * Uses worldTransform for position (world-space collision).\n * Supports AABB and circle colliders.\n */\n\nimport { definePlugin, type Plugin, type BasePluginOptions } from 'ecspresso';\nimport type { WorldConfigFrom } from '../type-utils';\nimport type { TransformWorldConfig } from './transform';\nimport { buildBaseColliderInfo, detectCollisions, tryGetSpatialIndex, type Contact, type BaseColliderInfo } from '../utils/narrowphase';\n\n// ==================== Component Types ====================\n\n/**\n * Axis-Aligned Bounding Box collider.\n */\nexport interface AABBCollider {\n\t/** Width of the bounding box */\n\twidth: number;\n\t/** Height of the bounding box */\n\theight: number;\n\t/** X offset from entity position (default: 0) */\n\toffsetX?: number;\n\t/** Y offset from entity position (default: 0) */\n\toffsetY?: number;\n}\n\n/**\n * Circle collider.\n */\nexport interface CircleCollider {\n\t/** Radius of the circle */\n\tradius: number;\n\t/** X offset from entity position (default: 0) */\n\toffsetX?: number;\n\t/** Y offset from entity position (default: 0) */\n\toffsetY?: number;\n}\n\n/**\n * Collision layer configuration.\n */\nexport interface CollisionLayer<L extends string = never> {\n\t/** The layer this entity belongs to */\n\tlayer: L;\n\t/** Layers this entity can collide with */\n\tcollidesWith: readonly L[];\n}\n\n/**\n * Component types provided by the collision plugin.\n * Included automatically via `.withPlugin(createCollisionPlugin())`.\n *\n * @example\n * ```typescript\n * const ecs = ECSpresso.create()\n * .withPlugin(createCollisionPlugin())\n * .withComponentTypes<{ sprite: Sprite; enemy: boolean }>()\n * .build();\n * ```\n */\nexport interface CollisionComponentTypes<L extends string = never> {\n\taabbCollider: AABBCollider;\n\tcircleCollider: CircleCollider;\n\tcollisionLayer: CollisionLayer<L>;\n}\n\n// ==================== Event Types ====================\n\n/**\n * Event fired when two entities collide.\n */\nexport interface CollisionEvent<L extends string = never> {\n\t/** First entity in the collision */\n\tentityA: number;\n\t/** Second entity in the collision */\n\tentityB: number;\n\t/** Layer of the first entity */\n\tlayerA: L;\n\t/** Layer of the second entity */\n\tlayerB: L;\n\t/** Contact normal pointing from entityA toward entityB */\n\tnormal: { x: number; y: number };\n\t/** Penetration depth (positive = overlapping) */\n\tdepth: number;\n}\n\n/**\n * Event types provided by the collision plugin.\n */\nexport interface CollisionEventTypes<L extends string = never> {\n\tcollision: CollisionEvent<L>;\n}\n\n// ==================== Plugin Options ====================\n\n/**\n * Configuration options for the collision plugin.\n */\nexport interface CollisionPluginOptions<G extends string = 'physics'> extends BasePluginOptions<G> {\n\t/** Name of the collision event (default: 'collision') */\n\tcollisionEventName?: string;\n}\n\n// ==================== Helper Functions ====================\n\n/**\n * Create an AABB collider component.\n *\n * @param width Width of the bounding box\n * @param height Height of the bounding box\n * @param offsetX X offset from entity position\n * @param offsetY Y offset from entity position\n * @returns Component object suitable for spreading into spawn()\n *\n * @example\n * ```typescript\n * ecs.spawn({\n * ...createTransform(100, 200),\n * ...createAABBCollider(50, 30),\n * });\n * ```\n */\nexport function createAABBCollider(\n\twidth: number,\n\theight: number,\n\toffsetX?: number,\n\toffsetY?: number\n): { aabbCollider: AABBCollider } {\n\tconst collider: AABBCollider = { width, height };\n\tif (offsetX !== undefined) collider.offsetX = offsetX;\n\tif (offsetY !== undefined) collider.offsetY = offsetY;\n\treturn { aabbCollider: collider };\n}\n\n/**\n * Create a circle collider component.\n *\n * @param radius Radius of the circle\n * @param offsetX X offset from entity position\n * @param offsetY Y offset from entity position\n * @returns Component object suitable for spreading into spawn()\n *\n * @example\n * ```typescript\n * ecs.spawn({\n * ...createTransform(100, 200),\n * ...createCircleCollider(25),\n * });\n * ```\n */\nexport function createCircleCollider(\n\tradius: number,\n\toffsetX?: number,\n\toffsetY?: number\n): { circleCollider: CircleCollider } {\n\tconst collider: CircleCollider = { radius };\n\tif (offsetX !== undefined) collider.offsetX = offsetX;\n\tif (offsetY !== undefined) collider.offsetY = offsetY;\n\treturn { circleCollider: collider };\n}\n\n/**\n * Create a collision layer component.\n *\n * @param layer The layer this entity belongs to\n * @param collidesWith Layers this entity can collide with\n * @returns Component object suitable for spreading into spawn()\n *\n * @example\n * ```typescript\n * ecs.spawn({\n * ...createTransform(100, 200),\n * ...createAABBCollider(50, 30),\n * ...createCollisionLayer('player', ['enemy', 'obstacle']),\n * });\n * ```\n */\nexport function createCollisionLayer<L extends string>(\n\tlayer: L,\n\tcollidesWith: readonly L[]\n): Pick<CollisionComponentTypes<L>, 'collisionLayer'> {\n\treturn {\n\t\tcollisionLayer: { layer, collidesWith },\n\t};\n}\n\n/**\n * Layer factory result from defineCollisionLayers.\n */\nexport type LayerFactories<T extends Record<string, readonly string[]>> = {\n\t[K in keyof T]: () => Pick<CollisionComponentTypes<Extract<keyof T, string>>, 'collisionLayer'>;\n};\n\n/**\n * Extract layer names from a `defineCollisionLayers` result for use with\n * `createCollisionPairHandler`'s `L` type parameter.\n *\n * @example\n * ```typescript\n * const layers = defineCollisionLayers({ player: ['enemy'], enemy: ['player'] });\n * type Layer = LayersOf<typeof layers>;\n * const handler = createCollisionPairHandler<ECS, Layer>({\n * 'player:enemy': (playerId, enemyId, ecs) => { ... },\n * });\n * ```\n */\nexport type LayersOf<T> = Extract<keyof T, string>;\n\n/**\n * Define collision layer relationships and get factory functions.\n *\n * @param rules Object mapping layer names to arrays of layers they collide with\n * @returns Object with factory functions for each layer\n *\n * @example\n * ```typescript\n * const layers = defineCollisionLayers({\n * player: ['enemy', 'enemyProjectile'],\n * playerProjectile: ['enemy'],\n * enemy: ['playerProjectile'],\n * enemyProjectile: ['player'],\n * });\n *\n * // Usage\n * ecs.spawn({\n * ...createTransform(100, 200),\n * ...createAABBCollider(50, 30),\n * ...layers.player(),\n * });\n * ```\n */\n/**\n * Validates that all `collidesWith` values reference actual layer keys.\n * Catches typos at compile time.\n */\ntype ValidateCollidesWith<T> = {\n\t[K in keyof T]: T[K] extends readonly (infer V)[]\n\t\t? [V] extends [Extract<keyof T, string>] ? T[K] : readonly Extract<keyof T, string>[]\n\t\t: never;\n};\n\nexport function defineCollisionLayers<const T extends Record<string, readonly string[]>>(\n\trules: T & ValidateCollidesWith<T>\n): LayerFactories<T> {\n\ttype L = Extract<keyof T, string>;\n\tconst factories = {} as LayerFactories<T>;\n\n\tfor (const layer of Object.keys(rules) as Array<L>) {\n\t\tconst collidesWith = rules[layer] as readonly L[];\n\t\tfactories[layer] = () => createCollisionLayer<L>(layer, collidesWith);\n\t}\n\n\treturn factories;\n}\n\n// ==================== Collision Pair Handler ====================\n\n/**\n * Callback for a collision pair handler.\n *\n * @param firstEntityId Entity belonging to the first layer in the pair key\n * @param secondEntityId Entity belonging to the second layer in the pair key\n * @param ecs The ECS world instance (passed through from the subscriber)\n */\nexport type CollisionPairCallback<W = unknown> = (\n\tfirstEntityId: number,\n\tsecondEntityId: number,\n\tecs: W,\n) => void;\n\ninterface PairEntry<W> {\n\tcallback: CollisionPairCallback<W>;\n\tswapped: boolean;\n}\n\nfunction parsePairKey(key: string): [string, string] {\n\tconst colonIndex = key.indexOf(':');\n\tif (colonIndex === -1) {\n\t\tthrow new Error(`Invalid collision pair key \"${key}\": must contain a colon separator (e.g. \"player:enemy\")`);\n\t}\n\tconst layerA = key.slice(0, colonIndex);\n\tconst layerB = key.slice(colonIndex + 1);\n\tif (layerA === '' || layerB === '') {\n\t\tthrow new Error(`Invalid collision pair key \"${key}\": layer names must not be empty`);\n\t}\n\treturn [layerA, layerB];\n}\n\n/**\n * Create a collision pair handler that routes collision events to\n * layer-pair-specific callbacks.\n *\n * Registering `\"a:b\"` automatically handles both `(layerA=a, layerB=b)` and\n * `(layerA=b, layerB=a)`. Entity arguments are swapped to match the declared\n * key order. If both `\"a:b\"` and `\"b:a\"` are explicitly registered, each gets\n * its own handler with no implicit reverse.\n *\n * @typeParam W - The ECS world type (e.g. `ECSpresso<C, E, R>`). Defaults to `unknown`.\n * @typeParam L - Union of valid layer names. Defaults to `string`.\n * Provide specific layer names for compile-time key validation:\n * `createCollisionPairHandler<ECS, keyof typeof layers>({...})`\n *\n * @param pairs Object mapping `\"layerA:layerB\"` keys to callbacks\n * @returns A dispatch function to call with collision event data and ECS instance\n *\n * @example\n * ```typescript\n * // Basic usage:\n * const handler = createCollisionPairHandler<ECS>({\n * 'playerProjectile:enemy': (projectileId, enemyId, ecs) => {\n * ecs.commands.removeEntity(projectileId);\n * },\n * });\n *\n * // With layer name validation:\n * const layers = defineCollisionLayers({ player: ['enemy'], enemy: ['player'] });\n * type Layer = LayersOf<typeof layers>;\n * const handler = createCollisionPairHandler<ECS, Layer>({\n * 'player:enemy': (playerId, enemyId, ecs) => { ... },\n * });\n *\n * ecs.eventBus.subscribe('collision', (data) => handler({ data, ecs }));\n * ```\n */\nexport function createCollisionPairHandler<W = unknown, L extends string = string>(\n\tpairs: { [K in `${L}:${L}`]?: CollisionPairCallback<W> }\n): (ctx: { data: CollisionEvent<L>; ecs: W }) => void;\nexport function createCollisionPairHandler<W = unknown>(\n\tpairs: Record<string, CollisionPairCallback<W> | undefined>\n): (ctx: { data: CollisionEvent<string>; ecs: W }) => void {\n\tconst lookup = new Map<string, PairEntry<W>>();\n\tconst explicitKeys = new Set<string>();\n\n\t// First pass: collect all explicit keys\n\tfor (const key of Object.keys(pairs)) {\n\t\tparsePairKey(key); // validate\n\t\texplicitKeys.add(key);\n\t}\n\n\t// Second pass: build lookup with forward + conditional reverse entries\n\tfor (const key of Object.keys(pairs)) {\n\t\tconst [layerA, layerB] = parsePairKey(key);\n\t\tconst callback = pairs[key];\n\t\tif (!callback) continue;\n\n\t\t// Forward entry\n\t\tlookup.set(key, { callback, swapped: false });\n\n\t\t// Reverse entry (only if the reverse key wasn't explicitly registered\n\t\t// and it's not a self-collision where forward === reverse)\n\t\tconst reverseKey = `${layerB}:${layerA}`;\n\t\tif (reverseKey !== key && !explicitKeys.has(reverseKey)) {\n\t\t\tlookup.set(reverseKey, { callback, swapped: true });\n\t\t}\n\t}\n\n\treturn function collisionPairDispatch({ data: event, ecs }: { data: CollisionEvent<string>; ecs: W }): void {\n\t\tconst entry = lookup.get(event.layerA + ':' + event.layerB);\n\t\tif (!entry) return;\n\n\t\tif (entry.swapped) {\n\t\t\tentry.callback(event.entityB, event.entityA, ecs);\n\t\t} else {\n\t\t\tentry.callback(event.entityA, event.entityB, ecs);\n\t\t}\n\t};\n}\n\n// ==================== Dependency Types ====================\n\n// ==================== Module-level Collision Callback ====================\n\ninterface CollisionEventBus<L extends string> {\n\tpublish(event: 'collision', data: CollisionEvent<L>): void;\n}\n\nfunction onCollisionDetected<L extends string>(\n\ta: BaseColliderInfo<L>,\n\tb: BaseColliderInfo<L>,\n\tcontact: Contact,\n\teventBus: CollisionEventBus<L>,\n): void {\n\teventBus.publish('collision', {\n\t\tentityA: a.entityId,\n\t\tentityB: b.entityId,\n\t\tlayerA: a.layer,\n\t\tlayerB: b.layer,\n\t\tnormal: { x: contact.normalX, y: contact.normalY },\n\t\tdepth: contact.depth,\n\t});\n}\n\n// ==================== Plugin Factory ====================\n\n/**\n * Create a collision plugin for ECSpresso.\n *\n * This plugin provides:\n * - Collision detection between entities with colliders\n * - AABB-AABB, circle-circle, and AABB-circle collision\n * - Layer-based filtering for collision pairs\n * - Deduplication of A-B / B-A collisions\n * - Automatic broadphase acceleration when spatialIndex resource is present\n *\n * Uses worldTransform for position (world-space collision detection).\n * The `layers` parameter is required for type inference — at runtime the\n * plugin does not consume it.\n *\n * @example\n * ```typescript\n * const layers = defineCollisionLayers({ player: ['enemy'], enemy: ['player'] });\n * const ecs = ECSpresso\n * .create()\n * .withPlugin(createTransformPlugin())\n * .withPlugin(createCollisionPlugin({ layers }))\n * .build();\n *\n * // Entity with collision\n * ecs.spawn({\n * ...createTransform(100, 200),\n * ...createAABBCollider(50, 30),\n * ...layers.player(),\n * });\n * ```\n */\nexport function createCollisionPlugin<L extends string, G extends string = 'physics'>(\n\toptions: CollisionPluginOptions<G> & { layers: LayerFactories<Record<L, readonly string[]>> }\n): Plugin<WorldConfigFrom<CollisionComponentTypes<L>, CollisionEventTypes<L>>, TransformWorldConfig, 'collision-detection', G> {\n\tconst {\n\t\tsystemGroup = 'physics',\n\t\tpriority = 0,\n\t\tphase = 'postUpdate',\n\t} = options;\n\n\treturn definePlugin<WorldConfigFrom<CollisionComponentTypes<L>, CollisionEventTypes<L>>, TransformWorldConfig, 'collision-detection', G>({\n\t\tid: 'collision',\n\t\tinstall(world) {\n\t\t\tworld\n\t\t\t\t.addSystem('collision-detection')\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('collidables', {\n\t\t\t\t\twith: ['worldTransform', 'collisionLayer'],\n\t\t\t\t})\n\t\t\t\t.setProcess(({ queries, ecs }) => {\n\t\t\t\t\tconst colliders: BaseColliderInfo<L>[] = [];\n\n\t\t\t\t\tfor (const entity of queries.collidables) {\n\t\t\t\t\t\tconst { worldTransform, collisionLayer } = entity.components;\n\t\t\t\t\t\tconst info = buildBaseColliderInfo(\n\t\t\t\t\t\t\tentity.id, worldTransform.x, worldTransform.y,\n\t\t\t\t\t\t\tcollisionLayer.layer, collisionLayer.collidesWith,\n\t\t\t\t\t\t\tecs.getComponent(entity.id, 'aabbCollider'),\n\t\t\t\t\t\t\tecs.getComponent(entity.id, 'circleCollider'),\n\t\t\t\t\t\t);\n\t\t\t\t\t\tif (info) colliders.push(info);\n\t\t\t\t\t}\n\n\t\t\t\t\tconst si = tryGetSpatialIndex(ecs.tryGetResource.bind(ecs));\n\t\t\t\t\tdetectCollisions(colliders, si, onCollisionDetected<L>, ecs.eventBus);\n\t\t\t\t});\n\t\t},\n\t});\n}\n\n",
6
- "/**\n * Shared Narrowphase Module\n *\n * Provides contact-computing narrowphase tests and a generic collision\n * iteration pipeline used by both the collision plugin (event-only) and\n * the physics2D plugin (impulse response).\n */\n\nimport type { SpatialIndex } from './spatial-hash';\n\n// ==================== Contact ====================\n\n/** Contact result from a narrowphase test. Normal points from A toward B. */\nexport interface Contact {\n\tnormalX: number;\n\tnormalY: number;\n\t/** Penetration depth (positive = overlapping) */\n\tdepth: number;\n}\n\n// ==================== BaseColliderInfo ====================\n\n/** Minimum collider data shared by collision and physics bundles. */\nexport interface BaseColliderInfo<L extends string = string> {\n\tentityId: number;\n\tx: number;\n\ty: number;\n\tlayer: L;\n\tcollidesWith: readonly L[];\n\taabb?: { halfWidth: number; halfHeight: number };\n\tcircle?: { radius: number };\n}\n\n// ==================== Collider Construction ====================\n\n/**\n * Build a BaseColliderInfo from raw entity/collider component data.\n * Returns null if the entity has neither an AABB nor circle collider.\n * Shared by collision plugin (event-only) and physics2D plugin (impulse response).\n */\nexport function buildBaseColliderInfo<L extends string>(\n\tentityId: number,\n\tx: number,\n\ty: number,\n\tlayer: L,\n\tcollidesWith: readonly L[],\n\taabb: { width: number; height: number; offsetX?: number; offsetY?: number } | undefined,\n\tcircle: { radius: number; offsetX?: number; offsetY?: number } | undefined,\n): BaseColliderInfo<L> | null {\n\tif (!aabb && !circle) return null;\n\n\tconst info: BaseColliderInfo<L> = { entityId, x, y, layer, collidesWith };\n\n\tif (aabb) {\n\t\tinfo.x += aabb.offsetX ?? 0;\n\t\tinfo.y += aabb.offsetY ?? 0;\n\t\tinfo.aabb = { halfWidth: aabb.width / 2, halfHeight: aabb.height / 2 };\n\t}\n\n\tif (circle) {\n\t\tinfo.x += circle.offsetX ?? 0;\n\t\tinfo.y += circle.offsetY ?? 0;\n\t\tinfo.circle = { radius: circle.radius };\n\t}\n\n\treturn info;\n}\n\n// ==================== Spatial Index Lookup ====================\n\n/**\n * Retrieve the optional spatialIndex resource, returning undefined when absent.\n * Centralizes the cross-plugin typed lookup so individual plugins don't each\n * need to import SpatialIndex or repeat the tryGetResource pattern.\n */\nexport function tryGetSpatialIndex(\n\ttryGetResource: <T>(key: string) => T | undefined,\n): SpatialIndex | undefined {\n\treturn tryGetResource<SpatialIndex>('spatialIndex');\n}\n\n// ==================== Narrowphase Tests ====================\n\nexport function computeAABBvsAABB(\n\tax: number, ay: number, ahw: number, ahh: number,\n\tbx: number, by: number, bhw: number, bhh: number,\n): Contact | null {\n\tconst dx = bx - ax;\n\tconst dy = by - ay;\n\tconst overlapX = (ahw + bhw) - Math.abs(dx);\n\tconst overlapY = (ahh + bhh) - Math.abs(dy);\n\n\tif (overlapX <= 0 || overlapY <= 0) return null;\n\n\tif (overlapX < overlapY) {\n\t\treturn {\n\t\t\tnormalX: dx >= 0 ? 1 : -1,\n\t\t\tnormalY: 0,\n\t\t\tdepth: overlapX,\n\t\t};\n\t}\n\treturn {\n\t\tnormalX: 0,\n\t\tnormalY: dy >= 0 ? 1 : -1,\n\t\tdepth: overlapY,\n\t};\n}\n\nexport function computeCircleVsCircle(\n\tax: number, ay: number, ar: number,\n\tbx: number, by: number, br: number,\n): Contact | null {\n\tconst dx = bx - ax;\n\tconst dy = by - ay;\n\tconst distSq = dx * dx + dy * dy;\n\tconst radiusSum = ar + br;\n\n\tif (distSq >= radiusSum * radiusSum) return null;\n\n\tconst dist = Math.sqrt(distSq);\n\tif (dist === 0) {\n\t\treturn { normalX: 1, normalY: 0, depth: radiusSum };\n\t}\n\treturn {\n\t\tnormalX: dx / dist,\n\t\tnormalY: dy / dist,\n\t\tdepth: radiusSum - dist,\n\t};\n}\n\nexport function computeAABBvsCircle(\n\taabbX: number, aabbY: number, ahw: number, ahh: number,\n\tcircleX: number, circleY: number, radius: number,\n): Contact | null {\n\tconst closestX = Math.max(aabbX - ahw, Math.min(circleX, aabbX + ahw));\n\tconst closestY = Math.max(aabbY - ahh, Math.min(circleY, aabbY + ahh));\n\n\tconst dx = circleX - closestX;\n\tconst dy = circleY - closestY;\n\tconst distSq = dx * dx + dy * dy;\n\n\tif (distSq >= radius * radius) return null;\n\n\t// Circle center inside AABB\n\tif (distSq === 0) {\n\t\tconst pushLeft = (circleX - (aabbX - ahw));\n\t\tconst pushRight = ((aabbX + ahw) - circleX);\n\t\tconst pushUp = (circleY - (aabbY - ahh));\n\t\tconst pushDown = ((aabbY + ahh) - circleY);\n\t\tconst minPush = Math.min(pushLeft, pushRight, pushUp, pushDown);\n\n\t\tif (minPush === pushRight) return { normalX: 1, normalY: 0, depth: pushRight + radius };\n\t\tif (minPush === pushLeft) return { normalX: -1, normalY: 0, depth: pushLeft + radius };\n\t\tif (minPush === pushDown) return { normalX: 0, normalY: 1, depth: pushDown + radius };\n\t\treturn { normalX: 0, normalY: -1, depth: pushUp + radius };\n\t}\n\n\tconst dist = Math.sqrt(distSq);\n\treturn {\n\t\tnormalX: dx / dist,\n\t\tnormalY: dy / dist,\n\t\tdepth: radius - dist,\n\t};\n}\n\n// ==================== Contact Dispatcher ====================\n\nexport function computeContact(a: BaseColliderInfo, b: BaseColliderInfo): Contact | null {\n\tif (a.aabb && b.aabb) {\n\t\treturn computeAABBvsAABB(\n\t\t\ta.x, a.y, a.aabb.halfWidth, a.aabb.halfHeight,\n\t\t\tb.x, b.y, b.aabb.halfWidth, b.aabb.halfHeight,\n\t\t);\n\t}\n\n\tif (a.circle && b.circle) {\n\t\treturn computeCircleVsCircle(\n\t\t\ta.x, a.y, a.circle.radius,\n\t\t\tb.x, b.y, b.circle.radius,\n\t\t);\n\t}\n\n\tif (a.aabb && b.circle) {\n\t\treturn computeAABBvsCircle(\n\t\t\ta.x, a.y, a.aabb.halfWidth, a.aabb.halfHeight,\n\t\t\tb.x, b.y, b.circle.radius,\n\t\t);\n\t}\n\n\tif (a.circle && b.aabb) {\n\t\tconst contact = computeAABBvsCircle(\n\t\t\tb.x, b.y, b.aabb.halfWidth, b.aabb.halfHeight,\n\t\t\ta.x, a.y, a.circle.radius,\n\t\t);\n\t\tif (!contact) return null;\n\t\treturn {\n\t\t\tnormalX: -contact.normalX,\n\t\t\tnormalY: -contact.normalY,\n\t\t\tdepth: contact.depth,\n\t\t};\n\t}\n\n\treturn null;\n}\n\n// ==================== Collision Iteration ====================\n\n/** Module-level reusable set for broadphase candidates. */\nconst _broadphaseCandidates = new Set<number>();\n\n/**\n * Generic collision detection pipeline: brute-force or broadphase,\n * with layer filtering and contact computation.\n *\n * Uses a context parameter forwarded to the callback to avoid\n * per-frame closure allocation.\n */\nexport function detectCollisions<I extends BaseColliderInfo, C>(\n\tcolliders: I[],\n\tspatialIndex: SpatialIndex | undefined,\n\tonContact: (a: I, b: I, contact: Contact, context: C) => void,\n\tcontext: C,\n): void {\n\tif (spatialIndex) {\n\t\tbroadphaseDetect(colliders, spatialIndex, onContact, context);\n\t} else {\n\t\tbruteForceDetect(colliders, onContact, context);\n\t}\n}\n\nfunction bruteForceDetect<I extends BaseColliderInfo, C>(\n\tcolliders: I[],\n\tonContact: (a: I, b: I, contact: Contact, context: C) => void,\n\tcontext: C,\n): void {\n\tfor (let i = 0; i < colliders.length; i++) {\n\t\tconst a = colliders[i];\n\t\tif (!a) continue;\n\n\t\tfor (let j = i + 1; j < colliders.length; j++) {\n\t\t\tconst b = colliders[j];\n\t\t\tif (!b) continue;\n\n\t\t\tif (!a.collidesWith.includes(b.layer) && !b.collidesWith.includes(a.layer)) continue;\n\n\t\t\tconst contact = computeContact(a, b);\n\t\t\tif (!contact) continue;\n\n\t\t\tonContact(a, b, contact, context);\n\t\t}\n\t}\n}\n\nfunction broadphaseDetect<I extends BaseColliderInfo, C>(\n\tcolliders: I[],\n\tspatialIndex: SpatialIndex,\n\tonContact: (a: I, b: I, contact: Contact, context: C) => void,\n\tcontext: C,\n): void {\n\tconst colliderMap = new Map<number, I>();\n\tfor (let i = 0; i < colliders.length; i++) {\n\t\tconst c = colliders[i];\n\t\tif (!c) continue;\n\t\tcolliderMap.set(c.entityId, c);\n\t}\n\n\tfor (let i = 0; i < colliders.length; i++) {\n\t\tconst a = colliders[i];\n\t\tif (!a) continue;\n\n\t\tconst aHalfW = a.aabb ? a.aabb.halfWidth : (a.circle ? a.circle.radius : 0);\n\t\tconst aHalfH = a.aabb ? a.aabb.halfHeight : (a.circle ? a.circle.radius : 0);\n\n\t\t_broadphaseCandidates.clear();\n\t\tspatialIndex.queryRectInto(\n\t\t\ta.x - aHalfW, a.y - aHalfH,\n\t\t\ta.x + aHalfW, a.y + aHalfH,\n\t\t\t_broadphaseCandidates,\n\t\t);\n\n\t\tfor (const bId of _broadphaseCandidates) {\n\t\t\tif (bId <= a.entityId) continue;\n\n\t\t\tconst b = colliderMap.get(bId);\n\t\t\tif (!b) continue;\n\n\t\t\tif (!a.collidesWith.includes(b.layer) && !b.collidesWith.includes(a.layer)) continue;\n\n\t\t\tconst contact = computeContact(a, b);\n\t\t\tif (!contact) continue;\n\n\t\t\tonContact(a, b, contact, context);\n\t\t}\n\t}\n}\n"
5
+ "/**\n * Collision Plugin for ECSpresso\n *\n * Provides layer-based collision detection with events.\n * Uses worldTransform for position (world-space collision).\n * Supports AABB and circle colliders.\n */\n\nimport { definePlugin, type BasePluginOptions } from 'ecspresso';\nimport type { TransformWorldConfig } from './transform';\nimport { fillBaseColliderInfo, detectCollisions, tryGetSpatialIndex, AABB_SHAPE, type Contact, type BaseColliderInfo } from '../utils/narrowphase';\n\n// ==================== Component Types ====================\n\n/**\n * Axis-Aligned Bounding Box collider.\n */\nexport interface AABBCollider {\n\t/** Width of the bounding box */\n\twidth: number;\n\t/** Height of the bounding box */\n\theight: number;\n\t/** X offset from entity position (default: 0) */\n\toffsetX?: number;\n\t/** Y offset from entity position (default: 0) */\n\toffsetY?: number;\n}\n\n/**\n * Circle collider.\n */\nexport interface CircleCollider {\n\t/** Radius of the circle */\n\tradius: number;\n\t/** X offset from entity position (default: 0) */\n\toffsetX?: number;\n\t/** Y offset from entity position (default: 0) */\n\toffsetY?: number;\n}\n\n/**\n * Collision layer configuration.\n */\nexport interface CollisionLayer<L extends string = never> {\n\t/** The layer this entity belongs to */\n\tlayer: L;\n\t/** Layers this entity can collide with */\n\tcollidesWith: readonly L[];\n}\n\n/**\n * Component types provided by the collision plugin.\n * Included automatically via `.withPlugin(createCollisionPlugin())`.\n *\n * @example\n * ```typescript\n * const ecs = ECSpresso.create()\n * .withPlugin(createCollisionPlugin())\n * .withComponentTypes<{ sprite: Sprite; enemy: boolean }>()\n * .build();\n * ```\n */\nexport interface CollisionComponentTypes<L extends string = never> {\n\taabbCollider: AABBCollider;\n\tcircleCollider: CircleCollider;\n\tcollisionLayer: CollisionLayer<L>;\n}\n\n// ==================== Event Types ====================\n\n/**\n * Event fired when two entities collide.\n *\n * Normal components are flattened (`normalX`/`normalY`) rather than nested\n * in a sub-object to avoid a per-event allocation in the collision hot path.\n */\nexport interface CollisionEvent<L extends string = never> {\n\t/** First entity in the collision */\n\tentityA: number;\n\t/** Second entity in the collision */\n\tentityB: number;\n\t/** Layer of the first entity */\n\tlayerA: L;\n\t/** Layer of the second entity */\n\tlayerB: L;\n\t/** Contact normal X, pointing from entityA toward entityB */\n\tnormalX: number;\n\t/** Contact normal Y, pointing from entityA toward entityB */\n\tnormalY: number;\n\t/** Penetration depth (positive = overlapping) */\n\tdepth: number;\n}\n\n/**\n * Event types provided by the collision plugin.\n */\nexport interface CollisionEventTypes<L extends string = never> {\n\tcollision: CollisionEvent<L>;\n}\n\n// ==================== Plugin Options ====================\n\n/**\n * Configuration options for the collision plugin.\n */\nexport interface CollisionPluginOptions<G extends string = 'physics'> extends BasePluginOptions<G> {\n\t/** Name of the collision event (default: 'collision') */\n\tcollisionEventName?: string;\n}\n\n// ==================== Helper Functions ====================\n\n/**\n * Create an AABB collider component.\n *\n * @param width Width of the bounding box\n * @param height Height of the bounding box\n * @param offsetX X offset from entity position\n * @param offsetY Y offset from entity position\n * @returns Component object suitable for spreading into spawn()\n *\n * @example\n * ```typescript\n * ecs.spawn({\n * ...createTransform(100, 200),\n * ...createAABBCollider(50, 30),\n * });\n * ```\n */\nexport function createAABBCollider(\n\twidth: number,\n\theight: number,\n\toffsetX?: number,\n\toffsetY?: number\n): { aabbCollider: AABBCollider } {\n\tconst collider: AABBCollider = { width, height };\n\tif (offsetX !== undefined) collider.offsetX = offsetX;\n\tif (offsetY !== undefined) collider.offsetY = offsetY;\n\treturn { aabbCollider: collider };\n}\n\n/**\n * Create a circle collider component.\n *\n * @param radius Radius of the circle\n * @param offsetX X offset from entity position\n * @param offsetY Y offset from entity position\n * @returns Component object suitable for spreading into spawn()\n *\n * @example\n * ```typescript\n * ecs.spawn({\n * ...createTransform(100, 200),\n * ...createCircleCollider(25),\n * });\n * ```\n */\nexport function createCircleCollider(\n\tradius: number,\n\toffsetX?: number,\n\toffsetY?: number\n): { circleCollider: CircleCollider } {\n\tconst collider: CircleCollider = { radius };\n\tif (offsetX !== undefined) collider.offsetX = offsetX;\n\tif (offsetY !== undefined) collider.offsetY = offsetY;\n\treturn { circleCollider: collider };\n}\n\n/**\n * Create a collision layer component.\n *\n * @param layer The layer this entity belongs to\n * @param collidesWith Layers this entity can collide with\n * @returns Component object suitable for spreading into spawn()\n *\n * @example\n * ```typescript\n * ecs.spawn({\n * ...createTransform(100, 200),\n * ...createAABBCollider(50, 30),\n * ...createCollisionLayer('player', ['enemy', 'obstacle']),\n * });\n * ```\n */\nexport function createCollisionLayer<L extends string>(\n\tlayer: L,\n\tcollidesWith: readonly L[]\n): Pick<CollisionComponentTypes<L>, 'collisionLayer'> {\n\treturn {\n\t\tcollisionLayer: { layer, collidesWith },\n\t};\n}\n\n/**\n * Layer factory result from defineCollisionLayers.\n */\nexport type LayerFactories<T extends Record<string, readonly string[]>> = {\n\t[K in keyof T]: () => Pick<CollisionComponentTypes<Extract<keyof T, string>>, 'collisionLayer'>;\n};\n\n/**\n * Extract layer names from a `defineCollisionLayers` result for use with\n * `createCollisionPairHandler`'s `L` type parameter.\n *\n * @example\n * ```typescript\n * const layers = defineCollisionLayers({ player: ['enemy'], enemy: ['player'] });\n * type Layer = LayersOf<typeof layers>;\n * const handler = createCollisionPairHandler<ECS, Layer>({\n * 'player:enemy': (playerId, enemyId, ecs) => { ... },\n * });\n * ```\n */\nexport type LayersOf<T> = Extract<keyof T, string>;\n\n/**\n * Define collision layer relationships and get factory functions.\n *\n * @param rules Object mapping layer names to arrays of layers they collide with\n * @returns Object with factory functions for each layer\n *\n * @example\n * ```typescript\n * const layers = defineCollisionLayers({\n * player: ['enemy', 'enemyProjectile'],\n * playerProjectile: ['enemy'],\n * enemy: ['playerProjectile'],\n * enemyProjectile: ['player'],\n * });\n *\n * // Usage\n * ecs.spawn({\n * ...createTransform(100, 200),\n * ...createAABBCollider(50, 30),\n * ...layers.player(),\n * });\n * ```\n */\n/**\n * Validates that all `collidesWith` values reference actual layer keys.\n * Catches typos at compile time.\n */\ntype ValidateCollidesWith<T> = {\n\t[K in keyof T]: T[K] extends readonly (infer V)[]\n\t\t? [V] extends [Extract<keyof T, string>] ? T[K] : readonly Extract<keyof T, string>[]\n\t\t: never;\n};\n\nexport function defineCollisionLayers<const T extends Record<string, readonly string[]>>(\n\trules: T & ValidateCollidesWith<T>\n): LayerFactories<T> {\n\ttype L = Extract<keyof T, string>;\n\tconst factories = {} as LayerFactories<T>;\n\n\tfor (const layer of Object.keys(rules) as Array<L>) {\n\t\tconst collidesWith = rules[layer] as readonly L[];\n\t\tfactories[layer] = () => createCollisionLayer<L>(layer, collidesWith);\n\t}\n\n\treturn factories;\n}\n\n// ==================== Collision Pair Handler ====================\n\n/**\n * Callback for a collision pair handler.\n *\n * @param firstEntityId Entity belonging to the first layer in the pair key\n * @param secondEntityId Entity belonging to the second layer in the pair key\n * @param ecs The ECS world instance (passed through from the subscriber)\n */\nexport type CollisionPairCallback<W = unknown> = (\n\tfirstEntityId: number,\n\tsecondEntityId: number,\n\tecs: W,\n) => void;\n\ninterface PairEntry<W> {\n\tcallback: CollisionPairCallback<W>;\n\tswapped: boolean;\n}\n\nfunction parsePairKey(key: string): [string, string] {\n\tconst colonIndex = key.indexOf(':');\n\tif (colonIndex === -1) {\n\t\tthrow new Error(`Invalid collision pair key \"${key}\": must contain a colon separator (e.g. \"player:enemy\")`);\n\t}\n\tconst layerA = key.slice(0, colonIndex);\n\tconst layerB = key.slice(colonIndex + 1);\n\tif (layerA === '' || layerB === '') {\n\t\tthrow new Error(`Invalid collision pair key \"${key}\": layer names must not be empty`);\n\t}\n\treturn [layerA, layerB];\n}\n\n/**\n * Create a collision pair handler that routes collision events to\n * layer-pair-specific callbacks.\n *\n * Registering `\"a:b\"` automatically handles both `(layerA=a, layerB=b)` and\n * `(layerA=b, layerB=a)`. Entity arguments are swapped to match the declared\n * key order. If both `\"a:b\"` and `\"b:a\"` are explicitly registered, each gets\n * its own handler with no implicit reverse.\n *\n * @typeParam W - The ECS world type (e.g. `ECSpresso<C, E, R>`). Defaults to `unknown`.\n * @typeParam L - Union of valid layer names. Defaults to `string`.\n * Provide specific layer names for compile-time key validation:\n * `createCollisionPairHandler<ECS, keyof typeof layers>({...})`\n *\n * @param pairs Object mapping `\"layerA:layerB\"` keys to callbacks\n * @returns A dispatch function to call with collision event data and ECS instance\n *\n * @example\n * ```typescript\n * // Basic usage:\n * const handler = createCollisionPairHandler<ECS>({\n * 'playerProjectile:enemy': (projectileId, enemyId, ecs) => {\n * ecs.commands.removeEntity(projectileId);\n * },\n * });\n *\n * // With layer name validation:\n * const layers = defineCollisionLayers({ player: ['enemy'], enemy: ['player'] });\n * type Layer = LayersOf<typeof layers>;\n * const handler = createCollisionPairHandler<ECS, Layer>({\n * 'player:enemy': (playerId, enemyId, ecs) => { ... },\n * });\n *\n * ecs.eventBus.subscribe('collision', (data) => handler({ data, ecs }));\n * ```\n */\nexport function createCollisionPairHandler<W = unknown, L extends string = string>(\n\tpairs: { [K in `${L}:${L}`]?: CollisionPairCallback<W> }\n): (ctx: { data: CollisionEvent<L>; ecs: W }) => void;\nexport function createCollisionPairHandler<W = unknown>(\n\tpairs: Record<string, CollisionPairCallback<W> | undefined>\n): (ctx: { data: CollisionEvent<string>; ecs: W }) => void {\n\tconst lookup = new Map<string, PairEntry<W>>();\n\tconst explicitKeys = new Set<string>();\n\n\t// First pass: collect all explicit keys\n\tfor (const key of Object.keys(pairs)) {\n\t\tparsePairKey(key); // validate\n\t\texplicitKeys.add(key);\n\t}\n\n\t// Second pass: build lookup with forward + conditional reverse entries\n\tfor (const key of Object.keys(pairs)) {\n\t\tconst [layerA, layerB] = parsePairKey(key);\n\t\tconst callback = pairs[key];\n\t\tif (!callback) continue;\n\n\t\t// Forward entry\n\t\tlookup.set(key, { callback, swapped: false });\n\n\t\t// Reverse entry (only if the reverse key wasn't explicitly registered\n\t\t// and it's not a self-collision where forward === reverse)\n\t\tconst reverseKey = `${layerB}:${layerA}`;\n\t\tif (reverseKey !== key && !explicitKeys.has(reverseKey)) {\n\t\t\tlookup.set(reverseKey, { callback, swapped: true });\n\t\t}\n\t}\n\n\treturn function collisionPairDispatch({ data: event, ecs }: { data: CollisionEvent<string>; ecs: W }): void {\n\t\tconst entry = lookup.get(event.layerA + ':' + event.layerB);\n\t\tif (!entry) return;\n\n\t\tif (entry.swapped) {\n\t\t\tentry.callback(event.entityB, event.entityA, ecs);\n\t\t} else {\n\t\t\tentry.callback(event.entityA, event.entityB, ecs);\n\t\t}\n\t};\n}\n\n// ==================== Dependency Types ====================\n\n// ==================== Module-level Collision Callback ====================\n\ninterface CollisionEventBus<L extends string> {\n\tpublish(event: 'collision', data: CollisionEvent<L>): void;\n}\n\nfunction onCollisionDetected<L extends string>(\n\ta: BaseColliderInfo<L>,\n\tb: BaseColliderInfo<L>,\n\tcontact: Contact,\n\teventBus: CollisionEventBus<L>,\n): void {\n\teventBus.publish('collision', {\n\t\tentityA: a.entityId,\n\t\tentityB: b.entityId,\n\t\tlayerA: a.layer,\n\t\tlayerB: b.layer,\n\t\tnormalX: contact.normalX,\n\t\tnormalY: contact.normalY,\n\t\tdepth: contact.depth,\n\t});\n}\n\n// ==================== Plugin Factory ====================\n\n/**\n * Create a collision plugin for ECSpresso.\n *\n * This plugin provides:\n * - Collision detection between entities with colliders\n * - AABB-AABB, circle-circle, and AABB-circle collision\n * - Layer-based filtering for collision pairs\n * - Deduplication of A-B / B-A collisions\n * - Automatic broadphase acceleration when spatialIndex resource is present\n *\n * Uses worldTransform for position (world-space collision detection).\n * The `layers` parameter is required for type inference — at runtime the\n * plugin does not consume it.\n *\n * @example\n * ```typescript\n * const layers = defineCollisionLayers({ player: ['enemy'], enemy: ['player'] });\n * const ecs = ECSpresso\n * .create()\n * .withPlugin(createTransformPlugin())\n * .withPlugin(createCollisionPlugin({ layers }))\n * .build();\n *\n * // Entity with collision\n * ecs.spawn({\n * ...createTransform(100, 200),\n * ...createAABBCollider(50, 30),\n * ...layers.player(),\n * });\n * ```\n */\nexport function createCollisionPlugin<L extends string, G extends string = 'physics'>(\n\toptions: CollisionPluginOptions<G> & { layers: LayerFactories<Record<L, readonly string[]>> }\n) {\n\tconst {\n\t\tsystemGroup = 'physics',\n\t\tpriority = 0,\n\t\tphase = 'postUpdate',\n\t} = options;\n\n\treturn definePlugin('collision')\n\t\t.withComponentTypes<CollisionComponentTypes<L>>()\n\t\t.withEventTypes<CollisionEventTypes<L>>()\n\t\t.withLabels<'collision-detection'>()\n\t\t.withGroups<G>()\n\t\t.requires<TransformWorldConfig>()\n\t\t.install((world) => {\n\t\t\t// Grow-only pool of BaseColliderInfo slots reused across frames.\n\t\t\t// Steady-state: zero allocations per frame once the pool is warm.\n\t\t\tconst colliderPool: BaseColliderInfo<L>[] = [];\n\t\t\t// Reusable entityId → collider lookup for the broadphase path.\n\t\t\tconst broadphaseMap = new Map<number, BaseColliderInfo<L>>();\n\n\t\t\tworld\n\t\t\t\t.addSystem('collision-detection')\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('collidables', {\n\t\t\t\t\twith: ['worldTransform', 'collisionLayer'],\n\t\t\t\t})\n\t\t\t\t.setProcess(({ queries, ecs }) => {\n\t\t\t\t\tlet count = 0;\n\n\t\t\t\t\tfor (const entity of queries.collidables) {\n\t\t\t\t\t\tconst { worldTransform, collisionLayer } = entity.components;\n\t\t\t\t\t\tconst aabb = ecs.getComponent(entity.id, 'aabbCollider');\n\t\t\t\t\t\tconst circle = ecs.getComponent(entity.id, 'circleCollider');\n\t\t\t\t\t\tif (!aabb && !circle) continue;\n\n\t\t\t\t\t\tlet slot = colliderPool[count];\n\t\t\t\t\t\tif (!slot) {\n\t\t\t\t\t\t\tslot = {\n\t\t\t\t\t\t\t\tentityId: entity.id,\n\t\t\t\t\t\t\t\tx: worldTransform.x,\n\t\t\t\t\t\t\t\ty: worldTransform.y,\n\t\t\t\t\t\t\t\tlayer: collisionLayer.layer,\n\t\t\t\t\t\t\t\tcollidesWith: collisionLayer.collidesWith,\n\t\t\t\t\t\t\t\tshape: AABB_SHAPE,\n\t\t\t\t\t\t\t\thalfWidth: 0,\n\t\t\t\t\t\t\t\thalfHeight: 0,\n\t\t\t\t\t\t\t\tradius: 0,\n\t\t\t\t\t\t\t};\n\t\t\t\t\t\t\tcolliderPool[count] = slot;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tif (!fillBaseColliderInfo(\n\t\t\t\t\t\t\tslot,\n\t\t\t\t\t\t\tentity.id, worldTransform.x, worldTransform.y,\n\t\t\t\t\t\t\tcollisionLayer.layer, collisionLayer.collidesWith,\n\t\t\t\t\t\t\taabb, circle,\n\t\t\t\t\t\t)) continue;\n\n\t\t\t\t\t\tcount++;\n\t\t\t\t\t}\n\n\t\t\t\t\tconst si = tryGetSpatialIndex(ecs.tryGetResource.bind(ecs));\n\t\t\t\t\tdetectCollisions(colliderPool, count, broadphaseMap, si, onCollisionDetected<L>, ecs.eventBus);\n\t\t\t\t});\n\t\t});\n}\n\n",
6
+ "/**\n * Shared Narrowphase Module\n *\n * Provides contact-computing narrowphase tests and a generic collision\n * iteration pipeline used by both the collision plugin (event-only) and\n * the physics2D plugin (impulse response).\n */\n\nimport type { SpatialIndex } from './spatial-hash';\n\n// ==================== Contact ====================\n\n/**\n * Contact result from a narrowphase test. Normal points from A toward B.\n *\n * Narrowphase functions use this as an out-parameter: the caller owns the\n * struct, the function writes fields in place and returns `true` on hit.\n * The `onContact` callback in `detectCollisions` receives a shared module-\n * level instance — **subscribers must consume it synchronously and must not\n * retain the reference across frames**.\n */\nexport interface Contact {\n\tnormalX: number;\n\tnormalY: number;\n\t/** Penetration depth (positive = overlapping) */\n\tdepth: number;\n}\n\n/**\n * Module-level reusable Contact passed down from `detectCollisions` into\n * narrowphase tests and forwarded to the `onContact` callback. Reused across\n * every pair in every frame — zero allocation in the narrowphase hot path.\n */\nconst _sharedContact: Contact = { normalX: 0, normalY: 0, depth: 0 };\n\n// ==================== BaseColliderInfo ====================\n\n/** Collider shape discriminator for the flattened BaseColliderInfo layout. */\nexport const AABB_SHAPE = 0;\nexport const CIRCLE_SHAPE = 1;\nexport type ColliderShape = typeof AABB_SHAPE | typeof CIRCLE_SHAPE;\n\n/**\n * Minimum collider data shared by collision and physics bundles.\n *\n * Flat layout (no nested `aabb` / `circle` sub-objects): the `shape`\n * discriminator tells you whether to read `halfWidth`/`halfHeight`\n * (AABB) or `radius` (Circle). Unused fields are set to 0.\n *\n * This shape is pool-friendly — all fields are assigned in place each\n * frame without allocating nested objects.\n */\nexport interface BaseColliderInfo<L extends string = string> {\n\tentityId: number;\n\tx: number;\n\ty: number;\n\tlayer: L;\n\tcollidesWith: readonly L[];\n\tshape: ColliderShape;\n\thalfWidth: number;\n\thalfHeight: number;\n\tradius: number;\n}\n\n// ==================== Collider Construction ====================\n\n/**\n * Populate a `BaseColliderInfo` slot in place from raw component data.\n * Returns `true` if the slot was filled, `false` if the entity has no\n * collider (caller should skip it).\n *\n * If an entity has both AABB and circle colliders, AABB wins and only\n * the AABB offset is applied. This matches the dispatch precedence in\n * `computeContact`; the previous implementation stacked both offsets,\n * which was a bug.\n */\nexport function fillBaseColliderInfo<L extends string>(\n\tinfo: BaseColliderInfo<L>,\n\tentityId: number,\n\tx: number,\n\ty: number,\n\tlayer: L,\n\tcollidesWith: readonly L[],\n\taabb: { width: number; height: number; offsetX?: number; offsetY?: number } | undefined,\n\tcircle: { radius: number; offsetX?: number; offsetY?: number } | undefined,\n): boolean {\n\tinfo.entityId = entityId;\n\tinfo.layer = layer;\n\tinfo.collidesWith = collidesWith;\n\n\tif (aabb) {\n\t\tinfo.x = x + (aabb.offsetX ?? 0);\n\t\tinfo.y = y + (aabb.offsetY ?? 0);\n\t\tinfo.shape = AABB_SHAPE;\n\t\tinfo.halfWidth = aabb.width / 2;\n\t\tinfo.halfHeight = aabb.height / 2;\n\t\tinfo.radius = 0;\n\t\treturn true;\n\t}\n\n\tif (circle) {\n\t\tinfo.x = x + (circle.offsetX ?? 0);\n\t\tinfo.y = y + (circle.offsetY ?? 0);\n\t\tinfo.shape = CIRCLE_SHAPE;\n\t\tinfo.halfWidth = 0;\n\t\tinfo.halfHeight = 0;\n\t\tinfo.radius = circle.radius;\n\t\treturn true;\n\t}\n\n\treturn false;\n}\n\n// ==================== Spatial Index Lookup ====================\n\n/**\n * Retrieve the optional spatialIndex resource, returning undefined when absent.\n * Centralizes the cross-plugin typed lookup so individual plugins don't each\n * need to import SpatialIndex or repeat the tryGetResource pattern.\n */\nexport function tryGetSpatialIndex(\n\ttryGetResource: <T>(key: string) => T | undefined,\n): SpatialIndex | undefined {\n\treturn tryGetResource<SpatialIndex>('spatialIndex');\n}\n\n// ==================== Narrowphase Tests ====================\n\n/**\n * Write an AABB-AABB contact into `out`. Returns `true` if the shapes\n * overlap (out was filled), `false` otherwise.\n */\nexport function computeAABBvsAABB(\n\tax: number, ay: number, ahw: number, ahh: number,\n\tbx: number, by: number, bhw: number, bhh: number,\n\tout: Contact,\n): boolean {\n\tconst dx = bx - ax;\n\tconst dy = by - ay;\n\tconst overlapX = (ahw + bhw) - Math.abs(dx);\n\tconst overlapY = (ahh + bhh) - Math.abs(dy);\n\n\tif (overlapX <= 0 || overlapY <= 0) return false;\n\n\tif (overlapX < overlapY) {\n\t\tout.normalX = dx >= 0 ? 1 : -1;\n\t\tout.normalY = 0;\n\t\tout.depth = overlapX;\n\t\treturn true;\n\t}\n\tout.normalX = 0;\n\tout.normalY = dy >= 0 ? 1 : -1;\n\tout.depth = overlapY;\n\treturn true;\n}\n\nexport function computeCircleVsCircle(\n\tax: number, ay: number, ar: number,\n\tbx: number, by: number, br: number,\n\tout: Contact,\n): boolean {\n\tconst dx = bx - ax;\n\tconst dy = by - ay;\n\tconst distSq = dx * dx + dy * dy;\n\tconst radiusSum = ar + br;\n\n\tif (distSq >= radiusSum * radiusSum) return false;\n\n\tconst dist = Math.sqrt(distSq);\n\tif (dist === 0) {\n\t\tout.normalX = 1;\n\t\tout.normalY = 0;\n\t\tout.depth = radiusSum;\n\t\treturn true;\n\t}\n\tout.normalX = dx / dist;\n\tout.normalY = dy / dist;\n\tout.depth = radiusSum - dist;\n\treturn true;\n}\n\nexport function computeAABBvsCircle(\n\taabbX: number, aabbY: number, ahw: number, ahh: number,\n\tcircleX: number, circleY: number, radius: number,\n\tout: Contact,\n): boolean {\n\tconst closestX = Math.max(aabbX - ahw, Math.min(circleX, aabbX + ahw));\n\tconst closestY = Math.max(aabbY - ahh, Math.min(circleY, aabbY + ahh));\n\n\tconst dx = circleX - closestX;\n\tconst dy = circleY - closestY;\n\tconst distSq = dx * dx + dy * dy;\n\n\tif (distSq >= radius * radius) return false;\n\n\t// Circle center inside AABB\n\tif (distSq === 0) {\n\t\tconst pushLeft = (circleX - (aabbX - ahw));\n\t\tconst pushRight = ((aabbX + ahw) - circleX);\n\t\tconst pushUp = (circleY - (aabbY - ahh));\n\t\tconst pushDown = ((aabbY + ahh) - circleY);\n\t\tconst minPush = Math.min(pushLeft, pushRight, pushUp, pushDown);\n\n\t\tif (minPush === pushRight) {\n\t\t\tout.normalX = 1; out.normalY = 0; out.depth = pushRight + radius;\n\t\t\treturn true;\n\t\t}\n\t\tif (minPush === pushLeft) {\n\t\t\tout.normalX = -1; out.normalY = 0; out.depth = pushLeft + radius;\n\t\t\treturn true;\n\t\t}\n\t\tif (minPush === pushDown) {\n\t\t\tout.normalX = 0; out.normalY = 1; out.depth = pushDown + radius;\n\t\t\treturn true;\n\t\t}\n\t\tout.normalX = 0; out.normalY = -1; out.depth = pushUp + radius;\n\t\treturn true;\n\t}\n\n\tconst dist = Math.sqrt(distSq);\n\tout.normalX = dx / dist;\n\tout.normalY = dy / dist;\n\tout.depth = radius - dist;\n\treturn true;\n}\n\n// ==================== Contact Dispatcher ====================\n\n/**\n * Dispatch to the correct narrowphase function for the given pair and\n * write the contact into `out`. Returns `true` if the pair overlaps.\n */\nexport function computeContact(a: BaseColliderInfo, b: BaseColliderInfo, out: Contact): boolean {\n\tif (a.shape === AABB_SHAPE && b.shape === AABB_SHAPE) {\n\t\treturn computeAABBvsAABB(\n\t\t\ta.x, a.y, a.halfWidth, a.halfHeight,\n\t\t\tb.x, b.y, b.halfWidth, b.halfHeight,\n\t\t\tout,\n\t\t);\n\t}\n\n\tif (a.shape === CIRCLE_SHAPE && b.shape === CIRCLE_SHAPE) {\n\t\treturn computeCircleVsCircle(\n\t\t\ta.x, a.y, a.radius,\n\t\t\tb.x, b.y, b.radius,\n\t\t\tout,\n\t\t);\n\t}\n\n\tif (a.shape === AABB_SHAPE && b.shape === CIRCLE_SHAPE) {\n\t\treturn computeAABBvsCircle(\n\t\t\ta.x, a.y, a.halfWidth, a.halfHeight,\n\t\t\tb.x, b.y, b.radius,\n\t\t\tout,\n\t\t);\n\t}\n\n\t// a is Circle, b is AABB — compute as AABB-vs-Circle, then flip normal in place\n\tif (!computeAABBvsCircle(\n\t\tb.x, b.y, b.halfWidth, b.halfHeight,\n\t\ta.x, a.y, a.radius,\n\t\tout,\n\t)) return false;\n\tout.normalX = -out.normalX;\n\tout.normalY = -out.normalY;\n\treturn true;\n}\n\n// ==================== Collision Iteration ====================\n\n/** Module-level reusable set for broadphase candidates. */\nconst _broadphaseCandidates = new Set<number>();\n\nlet _bruteForceWarned = false;\nconst BRUTE_FORCE_WARN_THRESHOLD = 50;\n\n/**\n * Generic collision detection pipeline: brute-force or broadphase,\n * with layer filtering and contact computation.\n *\n * `count` is the number of live entries at the front of `colliders`.\n * The array itself may be a grow-only pool — only indices `[0, count)`\n * are iterated, so trailing pool slots are ignored.\n *\n * `workingMap` is a caller-owned `Map<number, I>` used by the broadphase\n * path as an entityId → collider lookup. It is cleared and repopulated on\n * each call; callers should allocate it once and pass the same instance\n * every frame. Unused by the brute-force path but still required so that\n * typed reuse is the default, not an opt-in.\n *\n * Uses a context parameter forwarded to the callback to avoid\n * per-frame closure allocation.\n */\nexport function detectCollisions<I extends BaseColliderInfo, C>(\n\tcolliders: I[],\n\tcount: number,\n\tworkingMap: Map<number, I>,\n\tspatialIndex: SpatialIndex | undefined,\n\tonContact: (a: I, b: I, contact: Contact, context: C) => void,\n\tcontext: C,\n): void {\n\tif (spatialIndex) {\n\t\tbroadphaseDetect(colliders, count, workingMap, spatialIndex, onContact, context);\n\t} else {\n\t\tbruteForceDetect(colliders, count, onContact, context);\n\t}\n}\n\nfunction bruteForceDetect<I extends BaseColliderInfo, C>(\n\tcolliders: I[],\n\tcount: number,\n\tonContact: (a: I, b: I, contact: Contact, context: C) => void,\n\tcontext: C,\n): void {\n\tif (!_bruteForceWarned && count >= BRUTE_FORCE_WARN_THRESHOLD) {\n\t\t_bruteForceWarned = true;\n\t\tconsole.warn(\n\t\t\t`[ecspresso] Collision detection is using O(n²) brute force with ${count} colliders. ` +\n\t\t\t`For better performance, install createSpatialIndexPlugin() alongside your collision or physics2D plugin.`,\n\t\t);\n\t}\n\n\tfor (let i = 0; i < count; i++) {\n\t\tconst a = colliders[i];\n\t\tif (!a) continue;\n\n\t\tfor (let j = i + 1; j < count; j++) {\n\t\t\tconst b = colliders[j];\n\t\t\tif (!b) continue;\n\n\t\t\tif (!a.collidesWith.includes(b.layer) && !b.collidesWith.includes(a.layer)) continue;\n\n\t\t\tif (!computeContact(a, b, _sharedContact)) continue;\n\n\t\t\tonContact(a, b, _sharedContact, context);\n\t\t}\n\t}\n}\n\nfunction broadphaseDetect<I extends BaseColliderInfo, C>(\n\tcolliders: I[],\n\tcount: number,\n\tcolliderMap: Map<number, I>,\n\tspatialIndex: SpatialIndex,\n\tonContact: (a: I, b: I, contact: Contact, context: C) => void,\n\tcontext: C,\n): void {\n\tcolliderMap.clear();\n\tfor (let i = 0; i < count; i++) {\n\t\tconst c = colliders[i];\n\t\tif (!c) continue;\n\t\tcolliderMap.set(c.entityId, c);\n\t}\n\n\tfor (let i = 0; i < count; i++) {\n\t\tconst a = colliders[i];\n\t\tif (!a) continue;\n\n\t\tconst aHalfW = a.shape === AABB_SHAPE ? a.halfWidth : a.radius;\n\t\tconst aHalfH = a.shape === AABB_SHAPE ? a.halfHeight : a.radius;\n\n\t\t_broadphaseCandidates.clear();\n\t\tspatialIndex.queryRectInto(\n\t\t\ta.x - aHalfW, a.y - aHalfH,\n\t\t\ta.x + aHalfW, a.y + aHalfH,\n\t\t\t_broadphaseCandidates,\n\t\t);\n\n\t\tfor (const bId of _broadphaseCandidates) {\n\t\t\tif (bId <= a.entityId) continue;\n\n\t\t\tconst b = colliderMap.get(bId);\n\t\t\tif (!b) continue;\n\n\t\t\tif (!a.collidesWith.includes(b.layer) && !b.collidesWith.includes(a.layer)) continue;\n\n\t\t\tif (!computeContact(a, b, _sharedContact)) continue;\n\n\t\t\tonContact(a, b, _sharedContact, context);\n\t\t}\n\t}\n}\n"
7
7
  ],
8
- "mappings": "2PAQA,uBAAS,kBCgCF,SAAS,CAAuC,CACtD,EACA,EACA,EACA,EACA,EACA,EACA,E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next(dt)`. Helper generators (`waitSeconds`, `waitFrames`, `waitUntil`,
7
7
  * `waitForEvent`, `parallel`, `race`) compose via `yield*`.
8
8
  */
9
- import { type Plugin, type BasePluginOptions } from 'ecspresso';
9
+ import { type BasePluginOptions } from 'ecspresso';
10
10
  import type { EventsOfWorld, AnyECSpresso } from 'ecspresso';
11
- import type { WorldConfigFrom, EmptyConfig } from '../type-utils';
12
11
  /**
13
12
  * Yields void, returns void, receives deltaTime (number) via `.next(dt)`.
14
13
  * First `.next(dt)` initializes the generator (runs to first yield, dt discarded per JS spec).
@@ -123,4 +122,4 @@ export declare function createCoroutineHelpers<W extends AnyECSpresso>(_world?:
123
122
  * - `onComplete` callback invocation
124
123
  * - Component removal on completion
125
124
  */
126
- export declare function createCoroutinePlugin<G extends string = 'coroutines'>(options?: CoroutinePluginOptions<G>): Plugin<WorldConfigFrom<CoroutineComponentTypes>, EmptyConfig, 'coroutine-update', G>;
125
+ export declare function createCoroutinePlugin<G extends string = 'coroutines'>(options?: CoroutinePluginOptions<G>): import("ecspresso").Plugin<import("ecspresso").WithComponents<import("ecspresso").EmptyConfig, CoroutineComponentTypes>, import("ecspresso").EmptyConfig, "coroutine-update", G, never, never>;
@@ -1,4 +1,4 @@
1
- var V=((j)=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(j,{get:(z,x)=>(typeof require<"u"?require:z)[x]}):j)(function(j){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+j+'" is not supported')});import{definePlugin as R}from"ecspresso";function S(j,z){return{coroutine:{generator:j,onComplete:z?.onComplete}}}function*Y(j){if(j<=0)return;let z=0;while(z<j){let x=yield;z+=x}}function*Z(j){for(let z=0;z<j;z++)yield}function*_(j){while(!j())yield}function*$(...j){if(j.length===0)return;let z=j.map((x)=>{return x.next(0),{gen:x,done:!1}});while(z.some((x)=>!x.done)){let x=yield;for(let D of z){if(D.done)continue;if(D.gen.next(x).done)D.done=!0}}}function*A(...j){if(j.length===0)return;let z=j.map((x)=>{return x.next(0),{gen:x,done:!1}});try{while(!0){let x=yield;for(let D of z){if(D.done)continue;if(D.gen.next(x).done){D.done=!0;for(let K of z)if(!K.done)K.gen.return(),K.done=!0;return}}}}finally{for(let x of z)if(!x.done)x.gen.return(),x.done=!0}}function*U(j,z,x){let D=!1,H=j.subscribe(z,(K)=>{if(!x||x(K))D=!0});try{while(!D)yield}finally{H()}}function C(j,z){let x=j.getComponent(z,"coroutine");if(!x)return!1;return x.generator.return(),j.commands.removeComponent(z,"coroutine"),!0}function E(j){return{createCoroutine:S,waitForEvent:U}}function F(j){let{systemGroup:z="coroutines",priority:x=0,phase:D="update"}=j??{},H=new Set;return R({id:"coroutines",install(K){K.registerDispose("coroutine",({value:L,entityId:M})=>{L.generator.return(),H.delete(M)}),K.addSystem("coroutine-update").setPriority(x).inPhase(D).inGroup(z).addQuery("coroutines",{with:["coroutine"]}).setOnEntityEnter("coroutines",({entity:L})=>{L.components.coroutine.generator.next(0)}).setProcess(({queries:L,dt:M,ecs:N})=>{for(let J of L.coroutines){if(H.has(J.id)){H.delete(J.id);continue}let O=J.components.coroutine;try{if(O.generator.next(M).done)H.add(J.id),O.onComplete?.({entityId:J.id}),N.commands.removeComponent(J.id,"coroutine")}catch(Q){console.warn(`Coroutine error on entity ${J.id}:`,Q),H.add(J.id),N.commands.removeComponent(J.id,"coroutine")}}})}})}export{_ as waitUntil,Y as waitSeconds,Z as waitFrames,U as waitForEvent,A as race,$ as parallel,F as createCoroutinePlugin,E as createCoroutineHelpers,S as createCoroutine,C as cancelCoroutine};
1
+ var V=((j)=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(j,{get:(z,x)=>(typeof require<"u"?require:z)[x]}):j)(function(j){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+j+'" is not supported')});import{definePlugin as R}from"ecspresso";function S(j,z){return{coroutine:{generator:j,onComplete:z?.onComplete}}}function*Y(j){if(j<=0)return;let z=0;while(z<j){let x=yield;z+=x}}function*Z(j){for(let z=0;z<j;z++)yield}function*_(j){while(!j())yield}function*$(...j){if(j.length===0)return;let z=j.map((x)=>{return x.next(0),{gen:x,done:!1}});while(z.some((x)=>!x.done)){let x=yield;for(let D of z){if(D.done)continue;if(D.gen.next(x).done)D.done=!0}}}function*A(...j){if(j.length===0)return;let z=j.map((x)=>{return x.next(0),{gen:x,done:!1}});try{while(!0){let x=yield;for(let D of z){if(D.done)continue;if(D.gen.next(x).done){D.done=!0;for(let K of z)if(!K.done)K.gen.return(),K.done=!0;return}}}}finally{for(let x of z)if(!x.done)x.gen.return(),x.done=!0}}function*U(j,z,x){let D=!1,H=j.subscribe(z,(K)=>{if(!x||x(K))D=!0});try{while(!D)yield}finally{H()}}function C(j,z){let x=j.getComponent(z,"coroutine");if(!x)return!1;return x.generator.return(),j.commands.removeComponent(z,"coroutine"),!0}function E(j){return{createCoroutine:S,waitForEvent:U}}function F(j){let{systemGroup:z="coroutines",priority:x=0,phase:D="update"}=j??{},H=new Set;return R("coroutines").withComponentTypes().withLabels().withGroups().install((K)=>{K.registerDispose("coroutine",({value:L,entityId:M})=>{L.generator.return(),H.delete(M)}),K.addSystem("coroutine-update").setPriority(x).inPhase(D).inGroup(z).addQuery("coroutines",{with:["coroutine"]}).setOnEntityEnter("coroutines",({entity:L})=>{L.components.coroutine.generator.next(0)}).setProcess(({queries:L,dt:M,ecs:N})=>{for(let J of L.coroutines){if(H.has(J.id)){H.delete(J.id);continue}let O=J.components.coroutine;try{if(O.generator.next(M).done)H.add(J.id),O.onComplete?.({entityId:J.id}),N.commands.removeComponent(J.id,"coroutine")}catch(Q){console.warn(`Coroutine error on entity ${J.id}:`,Q),H.add(J.id),N.commands.removeComponent(J.id,"coroutine")}}})})}export{_ as waitUntil,Y as waitSeconds,Z as waitFrames,U as waitForEvent,A as race,$ as parallel,F as createCoroutinePlugin,E as createCoroutineHelpers,S as createCoroutine,C as cancelCoroutine};
2
2
 
3
- //# debugId=40FBD1090402AE0164756E2164756E21
3
+ //# debugId=0C9EF6AEE9641CFF64756E2164756E21
4
4
  //# sourceMappingURL=coroutine.js.map
@@ -2,9 +2,9 @@
2
2
  "version": 3,
3
3
  "sources": ["../src/plugins/coroutine.ts"],
4
4
  "sourcesContent": [
5
- "/**\n * Coroutine Plugin for ECSpresso\n *\n * ES6 generator-based coroutines for multi-step, frame-spanning scripted sequences.\n * A `coroutine` component holds a live generator. A system ticks all generators each\n * frame via `.next(dt)`. Helper generators (`waitSeconds`, `waitFrames`, `waitUntil`,\n * `waitForEvent`, `parallel`, `race`) compose via `yield*`.\n */\n\nimport { definePlugin, type Plugin, type BasePluginOptions } from 'ecspresso';\nimport type { EventsOfWorld, AnyECSpresso } from 'ecspresso';\nimport type { WorldConfigFrom, EmptyConfig } from '../type-utils';\n\n// ==================== Generator Protocol ====================\n\n/**\n * Yields void, returns void, receives deltaTime (number) via `.next(dt)`.\n * First `.next(dt)` initializes the generator (runs to first yield, dt discarded per JS spec).\n * Subsequent `.next(dt)` resume from yield with dt as the yield expression value.\n */\nexport type CoroutineGenerator = Generator<void, void, number>;\n\n// ==================== Event Types ====================\n\nexport interface CoroutineEventData {\n\tentityId: number;\n}\n\n\n// ==================== Component Types ====================\n\nexport interface CoroutineState {\n\tgenerator: CoroutineGenerator;\n\tonComplete?: (data: CoroutineEventData) => void;\n}\n\nexport interface CoroutineComponentTypes {\n\tcoroutine: CoroutineState;\n}\n\n// ==================== Plugin Options ====================\n\nexport interface CoroutinePluginOptions<G extends string = 'coroutines'> extends BasePluginOptions<G> {}\n\n// ==================== Component Factory ====================\n\nexport interface CoroutineOptions {\n\tonComplete?: (data: CoroutineEventData) => void;\n}\n\n/**\n * Create a coroutine component for spawning or adding to an entity.\n *\n * @param generator - The generator function to drive\n * @param options - Optional configuration (onComplete event)\n * @returns Component object suitable for spreading into spawn()\n */\nexport function createCoroutine(\n\tgenerator: CoroutineGenerator,\n\toptions?: CoroutineOptions,\n): Pick<CoroutineComponentTypes, 'coroutine'> {\n\treturn {\n\t\tcoroutine: {\n\t\t\tgenerator,\n\t\t\tonComplete: options?.onComplete,\n\t\t},\n\t};\n}\n\n// ==================== Helper Generators (standalone) ====================\n\n/**\n * Wait for a specified number of seconds. Accumulates dt until elapsed >= seconds.\n * If seconds <= 0, returns immediately.\n */\nexport function* waitSeconds(seconds: number): CoroutineGenerator {\n\tif (seconds <= 0) return;\n\tlet elapsed = 0;\n\twhile (elapsed < seconds) {\n\t\tconst dt: number = yield;\n\t\telapsed += dt;\n\t}\n}\n\n/**\n * Wait for a specified number of frames. Yields `frames` times.\n * If frames <= 0, returns immediately.\n */\nexport function* waitFrames(frames: number): CoroutineGenerator {\n\tfor (let i = 0; i < frames; i++) {\n\t\tyield;\n\t}\n}\n\n/**\n * Wait until a predicate returns true. Yields each frame until predicate is satisfied.\n * User closes over ecs if needed for state checks.\n */\nexport function* waitUntil(predicate: () => boolean): CoroutineGenerator {\n\twhile (!predicate()) {\n\t\tyield;\n\t}\n}\n\n/**\n * Run multiple coroutines in parallel. Completes when all finish.\n * Initializes all sub-generators, ticks all each frame.\n * Empty array = immediate return.\n */\nexport function* parallel(...coroutines: CoroutineGenerator[]): CoroutineGenerator {\n\tif (coroutines.length === 0) return;\n\n\t// Initialize all generators\n\tconst active = coroutines.map(gen => {\n\t\tgen.next(0);\n\t\treturn { gen, done: false };\n\t});\n\n\twhile (active.some(entry => !entry.done)) {\n\t\tconst dt: number = yield;\n\t\tfor (const entry of active) {\n\t\t\tif (entry.done) continue;\n\t\t\tconst result = entry.gen.next(dt);\n\t\t\tif (result.done) {\n\t\t\t\tentry.done = true;\n\t\t\t}\n\t\t}\n\t}\n}\n\n/**\n * Run multiple coroutines, completing when the first one finishes.\n * Calls `.return()` on remaining generators (triggers finally blocks).\n * Empty array = immediate return.\n */\nexport function* race(...coroutines: CoroutineGenerator[]): CoroutineGenerator {\n\tif (coroutines.length === 0) return;\n\n\t// Initialize all generators\n\tconst entries = coroutines.map(gen => {\n\t\tgen.next(0);\n\t\treturn { gen, done: false };\n\t});\n\n\ttry {\n\t\twhile (true) {\n\t\t\tconst dt: number = yield;\n\t\t\tfor (const entry of entries) {\n\t\t\t\tif (entry.done) continue;\n\t\t\t\tconst result = entry.gen.next(dt);\n\t\t\t\tif (result.done) {\n\t\t\t\t\tentry.done = true;\n\t\t\t\t\t// Cancel all others\n\t\t\t\t\tfor (const other of entries) {\n\t\t\t\t\t\tif (!other.done) {\n\t\t\t\t\t\t\tother.gen.return();\n\t\t\t\t\t\t\tother.done = true;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t} finally {\n\t\t// Clean up all on external cancellation\n\t\tfor (const entry of entries) {\n\t\t\tif (!entry.done) {\n\t\t\t\tentry.gen.return();\n\t\t\t\tentry.done = true;\n\t\t\t}\n\t\t}\n\t}\n}\n\n// ==================== Helper Generator (ECS-dependent) ====================\n\n/**\n * Wait until a matching event fires on the event bus.\n * Subscribes via eventBus.subscribe, yields until event received, unsubscribes in finally block.\n *\n * @param eventBus - Object with subscribe method (typically ecs.eventBus)\n * @param eventType - Event type name to listen for\n * @param filter - Optional predicate to filter events\n */\nexport function* waitForEvent<ET extends Record<string, any>, E extends keyof ET & string>(\n\teventBus: { subscribe(type: E, cb: (data: ET[E]) => void): () => void },\n\teventType: E,\n\tfilter?: (data: ET[E]) => boolean,\n): CoroutineGenerator {\n\tlet received = false;\n\tconst unsubscribe = eventBus.subscribe(eventType, (data: ET[E]) => {\n\t\tif (!filter || filter(data)) {\n\t\t\treceived = true;\n\t\t}\n\t});\n\ttry {\n\t\twhile (!received) {\n\t\t\tyield;\n\t\t}\n\t} finally {\n\t\tunsubscribe();\n\t}\n}\n\n// ==================== Cancellation ====================\n\n/**\n * Structural interface for ECS methods used by cancelCoroutine.\n */\nexport interface CoroutineWorld {\n\tgetComponent(entityId: number, componentName: string): unknown | undefined;\n\tcommands: {\n\t\tremoveComponent(entityId: number, componentName: string): void;\n\t};\n}\n\n/**\n * Cancel a running coroutine on an entity. Calls generator.return() (triggers finally blocks)\n * and queues component removal.\n *\n * @returns true if the entity had a coroutine that was cancelled, false otherwise\n */\nexport function cancelCoroutine(ecs: CoroutineWorld, entityId: number): boolean {\n\tconst state = ecs.getComponent(entityId, 'coroutine') as CoroutineState | undefined;\n\tif (!state) return false;\n\tstate.generator.return();\n\tecs.commands.removeComponent(entityId, 'coroutine');\n\treturn true;\n}\n\n// ==================== Typed Helpers (replaces Kit Pattern) ====================\n\n/**\n * Type-safe coroutine helpers that validate event names against a world's event types.\n * Use `createCoroutineHelpers<typeof ecs>()` to get compile-time validation.\n */\nexport interface CoroutineHelpers<W extends AnyECSpresso> {\n\tcreateCoroutine: (\n\t\tgenerator: CoroutineGenerator,\n\t\toptions?: { onComplete?: (data: CoroutineEventData) => void },\n\t) => Pick<CoroutineComponentTypes, 'coroutine'>;\n\twaitForEvent: <E extends keyof EventsOfWorld<W> & string>(\n\t\teventBus: { subscribe(type: E, cb: (data: EventsOfWorld<W>[E]) => void): () => void },\n\t\teventType: E,\n\t\tfilter?: (data: EventsOfWorld<W>[E]) => boolean,\n\t) => CoroutineGenerator;\n}\n\n/**\n * Create typed coroutine helpers that validate event names at compile time.\n *\n * @example\n * ```typescript\n * const { createCoroutine, waitForEvent } = createCoroutineHelpers<typeof ecs>();\n * ecs.spawn({ ...createCoroutine(myGen(), { onComplete: (data) => console.log(data.entityId) }) });\n * ```\n */\nexport function createCoroutineHelpers<W extends AnyECSpresso>(_world?: W): CoroutineHelpers<W> {\n\treturn {\n\t\tcreateCoroutine: createCoroutine as CoroutineHelpers<W>['createCoroutine'],\n\t\twaitForEvent: waitForEvent as CoroutineHelpers<W>['waitForEvent'],\n\t};\n}\n\n// ==================== Plugin Factory ====================\n\n/**\n * Create a coroutine plugin for ECSpresso.\n *\n * This plugin provides:\n * - Coroutine system that ticks all generator-based coroutines each frame\n * - Automatic cleanup via dispose callback (triggers generator finally blocks)\n * - `onComplete` callback invocation\n * - Component removal on completion\n */\nexport function createCoroutinePlugin<G extends string = 'coroutines'>(\n\toptions?: CoroutinePluginOptions<G>,\n): Plugin<WorldConfigFrom<CoroutineComponentTypes>, EmptyConfig, 'coroutine-update', G> {\n\tconst {\n\t\tsystemGroup = 'coroutines',\n\t\tpriority = 0,\n\t\tphase = 'update',\n\t} = options ?? {};\n\n\t// Tracks entities whose coroutine completed this frame to prevent re-ticking\n\t// before the command buffer removes the component.\n\tconst finished = new Set<number>();\n\n\treturn definePlugin<WorldConfigFrom<CoroutineComponentTypes>, EmptyConfig, 'coroutine-update', G>({\n\t\tid: 'coroutines',\n\t\tinstall(world) {\n\t\t\tworld.registerDispose('coroutine', ({ value, entityId }) => {\n\t\t\t\tvalue.generator.return();\n\t\t\t\tfinished.delete(entityId);\n\t\t\t});\n\n\t\t\tworld\n\t\t\t\t.addSystem('coroutine-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('coroutines', {\n\t\t\t\t\twith: ['coroutine'],\n\t\t\t\t})\n\t\t\t\t.setOnEntityEnter('coroutines', ({ entity }) => {\n\t\t\t\t\tentity.components.coroutine.generator.next(0);\n\t\t\t\t})\n\t\t\t\t.setProcess(({ queries, dt, ecs }) => {\n\t\t\t\t\tfor (const entity of queries.coroutines) {\n\t\t\t\t\t\t// Already completed — skip until command buffer removes the component\n\t\t\t\t\t\tif (finished.has(entity.id)) {\n\t\t\t\t\t\t\tfinished.delete(entity.id);\n\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tconst state = entity.components.coroutine;\n\n\t\t\t\t\t\t// Tick the generator\n\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\tconst result = state.generator.next(dt);\n\t\t\t\t\t\t\tif (result.done) {\n\t\t\t\t\t\t\t\tfinished.add(entity.id);\n\t\t\t\t\t\t\t\tstate.onComplete?.({ entityId: entity.id });\n\t\t\t\t\t\t\t\tecs.commands.removeComponent(entity.id, 'coroutine');\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t} catch (error) {\n\t\t\t\t\t\t\tconsole.warn(`Coroutine error on entity ${entity.id}:`, error);\n\t\t\t\t\t\t\tfinished.add(entity.id);\n\t\t\t\t\t\t\tecs.commands.removeComponent(entity.id, 'coroutine');\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"
5
+ "/**\n * Coroutine Plugin for ECSpresso\n *\n * ES6 generator-based coroutines for multi-step, frame-spanning scripted sequences.\n * A `coroutine` component holds a live generator. A system ticks all generators each\n * frame via `.next(dt)`. Helper generators (`waitSeconds`, `waitFrames`, `waitUntil`,\n * `waitForEvent`, `parallel`, `race`) compose via `yield*`.\n */\n\nimport { definePlugin, type BasePluginOptions } from 'ecspresso';\nimport type { EventsOfWorld, AnyECSpresso } from 'ecspresso';\n\n// ==================== Generator Protocol ====================\n\n/**\n * Yields void, returns void, receives deltaTime (number) via `.next(dt)`.\n * First `.next(dt)` initializes the generator (runs to first yield, dt discarded per JS spec).\n * Subsequent `.next(dt)` resume from yield with dt as the yield expression value.\n */\nexport type CoroutineGenerator = Generator<void, void, number>;\n\n// ==================== Event Types ====================\n\nexport interface CoroutineEventData {\n\tentityId: number;\n}\n\n\n// ==================== Component Types ====================\n\nexport interface CoroutineState {\n\tgenerator: CoroutineGenerator;\n\tonComplete?: (data: CoroutineEventData) => void;\n}\n\nexport interface CoroutineComponentTypes {\n\tcoroutine: CoroutineState;\n}\n\n// ==================== Plugin Options ====================\n\nexport interface CoroutinePluginOptions<G extends string = 'coroutines'> extends BasePluginOptions<G> {}\n\n// ==================== Component Factory ====================\n\nexport interface CoroutineOptions {\n\tonComplete?: (data: CoroutineEventData) => void;\n}\n\n/**\n * Create a coroutine component for spawning or adding to an entity.\n *\n * @param generator - The generator function to drive\n * @param options - Optional configuration (onComplete event)\n * @returns Component object suitable for spreading into spawn()\n */\nexport function createCoroutine(\n\tgenerator: CoroutineGenerator,\n\toptions?: CoroutineOptions,\n): Pick<CoroutineComponentTypes, 'coroutine'> {\n\treturn {\n\t\tcoroutine: {\n\t\t\tgenerator,\n\t\t\tonComplete: options?.onComplete,\n\t\t},\n\t};\n}\n\n// ==================== Helper Generators (standalone) ====================\n\n/**\n * Wait for a specified number of seconds. Accumulates dt until elapsed >= seconds.\n * If seconds <= 0, returns immediately.\n */\nexport function* waitSeconds(seconds: number): CoroutineGenerator {\n\tif (seconds <= 0) return;\n\tlet elapsed = 0;\n\twhile (elapsed < seconds) {\n\t\tconst dt: number = yield;\n\t\telapsed += dt;\n\t}\n}\n\n/**\n * Wait for a specified number of frames. Yields `frames` times.\n * If frames <= 0, returns immediately.\n */\nexport function* waitFrames(frames: number): CoroutineGenerator {\n\tfor (let i = 0; i < frames; i++) {\n\t\tyield;\n\t}\n}\n\n/**\n * Wait until a predicate returns true. Yields each frame until predicate is satisfied.\n * User closes over ecs if needed for state checks.\n */\nexport function* waitUntil(predicate: () => boolean): CoroutineGenerator {\n\twhile (!predicate()) {\n\t\tyield;\n\t}\n}\n\n/**\n * Run multiple coroutines in parallel. Completes when all finish.\n * Initializes all sub-generators, ticks all each frame.\n * Empty array = immediate return.\n */\nexport function* parallel(...coroutines: CoroutineGenerator[]): CoroutineGenerator {\n\tif (coroutines.length === 0) return;\n\n\t// Initialize all generators\n\tconst active = coroutines.map(gen => {\n\t\tgen.next(0);\n\t\treturn { gen, done: false };\n\t});\n\n\twhile (active.some(entry => !entry.done)) {\n\t\tconst dt: number = yield;\n\t\tfor (const entry of active) {\n\t\t\tif (entry.done) continue;\n\t\t\tconst result = entry.gen.next(dt);\n\t\t\tif (result.done) {\n\t\t\t\tentry.done = true;\n\t\t\t}\n\t\t}\n\t}\n}\n\n/**\n * Run multiple coroutines, completing when the first one finishes.\n * Calls `.return()` on remaining generators (triggers finally blocks).\n * Empty array = immediate return.\n */\nexport function* race(...coroutines: CoroutineGenerator[]): CoroutineGenerator {\n\tif (coroutines.length === 0) return;\n\n\t// Initialize all generators\n\tconst entries = coroutines.map(gen => {\n\t\tgen.next(0);\n\t\treturn { gen, done: false };\n\t});\n\n\ttry {\n\t\twhile (true) {\n\t\t\tconst dt: number = yield;\n\t\t\tfor (const entry of entries) {\n\t\t\t\tif (entry.done) continue;\n\t\t\t\tconst result = entry.gen.next(dt);\n\t\t\t\tif (result.done) {\n\t\t\t\t\tentry.done = true;\n\t\t\t\t\t// Cancel all others\n\t\t\t\t\tfor (const other of entries) {\n\t\t\t\t\t\tif (!other.done) {\n\t\t\t\t\t\t\tother.gen.return();\n\t\t\t\t\t\t\tother.done = true;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t} finally {\n\t\t// Clean up all on external cancellation\n\t\tfor (const entry of entries) {\n\t\t\tif (!entry.done) {\n\t\t\t\tentry.gen.return();\n\t\t\t\tentry.done = true;\n\t\t\t}\n\t\t}\n\t}\n}\n\n// ==================== Helper Generator (ECS-dependent) ====================\n\n/**\n * Wait until a matching event fires on the event bus.\n * Subscribes via eventBus.subscribe, yields until event received, unsubscribes in finally block.\n *\n * @param eventBus - Object with subscribe method (typically ecs.eventBus)\n * @param eventType - Event type name to listen for\n * @param filter - Optional predicate to filter events\n */\nexport function* waitForEvent<ET extends Record<string, any>, E extends keyof ET & string>(\n\teventBus: { subscribe(type: E, cb: (data: ET[E]) => void): () => void },\n\teventType: E,\n\tfilter?: (data: ET[E]) => boolean,\n): CoroutineGenerator {\n\tlet received = false;\n\tconst unsubscribe = eventBus.subscribe(eventType, (data: ET[E]) => {\n\t\tif (!filter || filter(data)) {\n\t\t\treceived = true;\n\t\t}\n\t});\n\ttry {\n\t\twhile (!received) {\n\t\t\tyield;\n\t\t}\n\t} finally {\n\t\tunsubscribe();\n\t}\n}\n\n// ==================== Cancellation ====================\n\n/**\n * Structural interface for ECS methods used by cancelCoroutine.\n */\nexport interface CoroutineWorld {\n\tgetComponent(entityId: number, componentName: string): unknown | undefined;\n\tcommands: {\n\t\tremoveComponent(entityId: number, componentName: string): void;\n\t};\n}\n\n/**\n * Cancel a running coroutine on an entity. Calls generator.return() (triggers finally blocks)\n * and queues component removal.\n *\n * @returns true if the entity had a coroutine that was cancelled, false otherwise\n */\nexport function cancelCoroutine(ecs: CoroutineWorld, entityId: number): boolean {\n\tconst state = ecs.getComponent(entityId, 'coroutine') as CoroutineState | undefined;\n\tif (!state) return false;\n\tstate.generator.return();\n\tecs.commands.removeComponent(entityId, 'coroutine');\n\treturn true;\n}\n\n// ==================== Typed Helpers (replaces Kit Pattern) ====================\n\n/**\n * Type-safe coroutine helpers that validate event names against a world's event types.\n * Use `createCoroutineHelpers<typeof ecs>()` to get compile-time validation.\n */\nexport interface CoroutineHelpers<W extends AnyECSpresso> {\n\tcreateCoroutine: (\n\t\tgenerator: CoroutineGenerator,\n\t\toptions?: { onComplete?: (data: CoroutineEventData) => void },\n\t) => Pick<CoroutineComponentTypes, 'coroutine'>;\n\twaitForEvent: <E extends keyof EventsOfWorld<W> & string>(\n\t\teventBus: { subscribe(type: E, cb: (data: EventsOfWorld<W>[E]) => void): () => void },\n\t\teventType: E,\n\t\tfilter?: (data: EventsOfWorld<W>[E]) => boolean,\n\t) => CoroutineGenerator;\n}\n\n/**\n * Create typed coroutine helpers that validate event names at compile time.\n *\n * @example\n * ```typescript\n * const { createCoroutine, waitForEvent } = createCoroutineHelpers<typeof ecs>();\n * ecs.spawn({ ...createCoroutine(myGen(), { onComplete: (data) => console.log(data.entityId) }) });\n * ```\n */\nexport function createCoroutineHelpers<W extends AnyECSpresso>(_world?: W): CoroutineHelpers<W> {\n\treturn {\n\t\tcreateCoroutine: createCoroutine as CoroutineHelpers<W>['createCoroutine'],\n\t\twaitForEvent: waitForEvent as CoroutineHelpers<W>['waitForEvent'],\n\t};\n}\n\n// ==================== Plugin Factory ====================\n\n/**\n * Create a coroutine plugin for ECSpresso.\n *\n * This plugin provides:\n * - Coroutine system that ticks all generator-based coroutines each frame\n * - Automatic cleanup via dispose callback (triggers generator finally blocks)\n * - `onComplete` callback invocation\n * - Component removal on completion\n */\nexport function createCoroutinePlugin<G extends string = 'coroutines'>(\n\toptions?: CoroutinePluginOptions<G>,\n) {\n\tconst {\n\t\tsystemGroup = 'coroutines',\n\t\tpriority = 0,\n\t\tphase = 'update',\n\t} = options ?? {};\n\n\t// Tracks entities whose coroutine completed this frame to prevent re-ticking\n\t// before the command buffer removes the component.\n\tconst finished = new Set<number>();\n\n\treturn definePlugin('coroutines')\n\t\t.withComponentTypes<CoroutineComponentTypes>()\n\t\t.withLabels<'coroutine-update'>()\n\t\t.withGroups<G>()\n\t\t.install((world) => {\n\t\t\tworld.registerDispose('coroutine', ({ value, entityId }) => {\n\t\t\t\tvalue.generator.return();\n\t\t\t\tfinished.delete(entityId);\n\t\t\t});\n\n\t\t\tworld\n\t\t\t\t.addSystem('coroutine-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('coroutines', {\n\t\t\t\t\twith: ['coroutine'],\n\t\t\t\t})\n\t\t\t\t.setOnEntityEnter('coroutines', ({ entity }) => {\n\t\t\t\t\tentity.components.coroutine.generator.next(0);\n\t\t\t\t})\n\t\t\t\t.setProcess(({ queries, dt, ecs }) => {\n\t\t\t\t\tfor (const entity of queries.coroutines) {\n\t\t\t\t\t\t// Already completed — skip until command buffer removes the component\n\t\t\t\t\t\tif (finished.has(entity.id)) {\n\t\t\t\t\t\t\tfinished.delete(entity.id);\n\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tconst state = entity.components.coroutine;\n\n\t\t\t\t\t\t// Tick the generator\n\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\tconst result = state.generator.next(dt);\n\t\t\t\t\t\t\tif (result.done) {\n\t\t\t\t\t\t\t\tfinished.add(entity.id);\n\t\t\t\t\t\t\t\tstate.onComplete?.({ entityId: entity.id });\n\t\t\t\t\t\t\t\tecs.commands.removeComponent(entity.id, 'coroutine');\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t} catch (error) {\n\t\t\t\t\t\t\tconsole.warn(`Coroutine error on entity ${entity.id}:`, error);\n\t\t\t\t\t\t\tfinished.add(entity.id);\n\t\t\t\t\t\t\tecs.commands.removeComponent(entity.id, 'coroutine');\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t});\n\t\t});\n}\n"
6
6
  ],
7
- "mappings": "2PASA,uBAAS,kBAgDF,SAAS,CAAe,CAC9B,EACA,EAC6C,CAC7C,MAAO,CACN,UAAW,CACV,YACA,WAAY,GAAS,UACtB,CACD,EASM,SAAU,CAAW,CAAC,EAAqC,CACjE,GAAI,GAAW,EAAG,OAClB,IAAI,EAAU,EACd,MAAO,EAAU,EAAS,CACzB,IAAM,EAAa,MACnB,GAAW,GAQN,SAAU,CAAU,CAAC,EAAoC,CAC/D,QAAS,EAAI,EAAG,EAAI,EAAQ,IAC3B,MAQK,SAAU,CAAS,CAAC,EAA8C,CACxE,MAAO,CAAC,EAAU,EACjB,MASK,SAAU,CAAQ,IAAI,EAAsD,CAClF,GAAI,EAAW,SAAW,EAAG,OAG7B,IAAM,EAAS,EAAW,IAAI,KAAO,CAEpC,OADA,EAAI,KAAK,CAAC,EACH,CAAE,MAAK,KAAM,EAAM,EAC1B,EAED,MAAO,EAAO,KAAK,KAAS,CAAC,EAAM,IAAI,EAAG,CACzC,IAAM,EAAa,MACnB,QAAW,KAAS,EAAQ,CAC3B,GAAI,EAAM,KAAM,SAEhB,GADe,EAAM,IAAI,KAAK,CAAE,EACrB,KACV,EAAM,KAAO,KAWV,SAAU,CAAI,IAAI,EAAsD,CAC9E,GAAI,EAAW,SAAW,EAAG,OAG7B,IAAM,EAAU,EAAW,IAAI,KAAO,CAErC,OADA,EAAI,KAAK,CAAC,EACH,CAAE,MAAK,KAAM,EAAM,EAC1B,EAED,GAAI,CACH,MAAO,GAA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Ac,EACd,QAAQ,CAAC,IAAU,CACnB,EAAM,gBAAgB,YAAa,EAAG,QAAO,cAAe,CAC3D,EAAM,UAAU,OAAO,EACvB,EAAS,OAAO,CAAQ,EACxB,EAED,EACE,UAAU,kBAAkB,EAC5B,YAAY,CAAQ,EACpB,QAAQ,CAAK,EACb,QAAQ,CAAW,EACnB,SAAS,aAAc,CACvB,KAAM,CAAC,WAAW,CACnB,CAAC,EACA,iBAAiB,aAAc,EAAG,YAAa,CAC/C,EAAO,WAAW,UAAU,UAAU,KAAK,CAAC,EAC5C,EACA,WAAW,EAAG,UAAS,KAAI,SAAU,CACrC,QAAW,KAAU,EAAQ,WAAY,CAExC,GAAI,EAAS,IAAI,EAAO,EAAE,EAAG,CAC5B,EAAS,OAAO,EAAO,EAAE,EACzB,SAGD,IAAM,EAAQ,EAAO,WAAW,UAGhC,GAAI,CAEH,GADe,EAAM,UAAU,KAAK,CAAE,EAC3B,KACV,EAAS,IAAI,EAAO,EAAE,EACtB,EAAM,aAAa,CAAE,SAAU,EAAO,EAAG,CAAC,EAC1C,EAAI,SAAS,gBAAgB,EAAO,GAAI,WAAW,EAEnD,MAAO,EAAO,CACf,QAAQ,KAAK,6BAA6B,EAAO,MAAO,CAAK,EAC7D,EAAS,IAAI,EAAO,EAAE,EACtB,EAAI,SAAS,gBAAgB,EAAO,GAAI,WAAW,IAGrD,EACF",
8
+ "debugId": "0C9EF6AEE9641CFF64756E2164756E21",
9
9
  "names": []
10
10
  }
@@ -4,9 +4,7 @@
4
4
  * Runtime diagnostics: FPS, entity count, per-system timing, per-phase timing,
5
5
  * and an optional DOM overlay for visual debugging.
6
6
  */
7
- import { type Plugin } from 'ecspresso';
8
7
  import type { SystemPhase } from 'ecspresso';
9
- import type { WorldConfigFrom, EmptyConfig } from '../type-utils';
10
8
  export interface DiagnosticsData {
11
9
  fps: number;
12
10
  entityCount: number;
@@ -35,7 +33,7 @@ export interface DiagnosticsOverlayOptions {
35
33
  /** Maximum systems to show in overlay (default: 10) */
36
34
  maxSystemsShown?: number;
37
35
  }
38
- export declare function createDiagnosticsPlugin<G extends string = 'diagnostics'>(options?: DiagnosticsPluginOptions<G>): Plugin<WorldConfigFrom<{}, {}, DiagnosticsResourceTypes>, EmptyConfig, 'diagnostics-collect', G>;
36
+ export declare function createDiagnosticsPlugin<G extends string = 'diagnostics'>(options?: DiagnosticsPluginOptions<G>): import("ecspresso").Plugin<import("ecspresso").WithResources<import("ecspresso").EmptyConfig, DiagnosticsResourceTypes>, import("ecspresso").EmptyConfig, "diagnostics-collect", G, never, never>;
39
37
  /**
40
38
  * Create a DOM overlay that displays diagnostics data.
41
39
  * Returns a cleanup function that removes the element and clears the interval.
@@ -1,5 +1,5 @@
1
- var L=((j)=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(j,{get:(F,k)=>(typeof require<"u"?require:F)[k]}):j)(function(j){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+j+'" is not supported')});import{definePlugin as $}from"ecspresso";function A(j){let F=new Float64Array(j),k=0,q=0;return{push(Q){if(F[k]=Q,k=(k+1)%j,q<j)q++},computeFps(){if(q<2)return 0;let Q=F[(k-1+j)%j]??0,U=F[(k-q+j)%j]??0,z=Q-U;if(z<=0)return 0;return(q-1)/z*1000},computeAverageFrameTime(){if(q<2)return 0;let Q=F[(k-1+j)%j]??0,U=F[(k-q+j)%j]??0,z=Q-U;if(z<=0)return 0;return z/(q-1)},get size(){return q}}}function Y(j){let{systemGroup:F="diagnostics",enableTimingOnInit:k=!0,fpsSampleCount:q=60}=j??{},Q={fps:0,entityCount:0,systemTimings:new Map,phaseTimings:{preUpdate:0,fixedUpdate:0,update:0,postUpdate:0,render:0},averageFrameTime:0},U=A(q);return $({id:"diagnostics",install(z){z.addResource("diagnostics",Q),z.addSystem("diagnostics-collect").setPriority(-999999).inPhase("render").inGroup(F).setOnInitialize((J)=>{if(k)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 G={"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 _(j,F){let{position:k="top-left",updateInterval:q=200,showSystemTimings:Q=!0,maxSystemsShown:U=10}=F??{},z=document.createElement("div");z.style.cssText=`position:fixed;${G[k]};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(z);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 Z=[...V.systemTimings.entries()].sort((W,X)=>X[1]-W[1]).slice(0,U);for(let[W,X]of Z)K.push(` ${W}: ${X.toFixed(3)}ms`)}z.textContent=K.join(`
1
+ var L=((j)=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(j,{get:(F,k)=>(typeof require<"u"?require:F)[k]}):j)(function(j){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+j+'" is not supported')});import{definePlugin as $}from"ecspresso";function A(j){let F=new Float64Array(j),k=0,q=0;return{push(Q){if(F[k]=Q,k=(k+1)%j,q<j)q++},computeFps(){if(q<2)return 0;let Q=F[(k-1+j)%j]??0,U=F[(k-q+j)%j]??0,z=Q-U;if(z<=0)return 0;return(q-1)/z*1000},computeAverageFrameTime(){if(q<2)return 0;let Q=F[(k-1+j)%j]??0,U=F[(k-q+j)%j]??0,z=Q-U;if(z<=0)return 0;return z/(q-1)},get size(){return q}}}function Y(j){let{systemGroup:F="diagnostics",enableTimingOnInit:k=!0,fpsSampleCount:q=60}=j??{},Q={fps:0,entityCount:0,systemTimings:new Map,phaseTimings:{preUpdate:0,fixedUpdate:0,update:0,postUpdate:0,render:0},averageFrameTime:0},U=A(q);return $("diagnostics").withResourceTypes().withLabels().withGroups().install((z)=>{z.addResource("diagnostics",Q),z.addSystem("diagnostics-collect").setPriority(-999999).inPhase("render").inGroup(F).setOnInitialize((J)=>{if(k)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 G={"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 _(j,F){let{position:k="top-left",updateInterval:q=200,showSystemTimings:Q=!0,maxSystemsShown:U=10}=F??{},z=document.createElement("div");z.style.cssText=`position:fixed;${G[k]};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(z);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 Z=[...V.systemTimings.entries()].sort((W,X)=>X[1]-W[1]).slice(0,U);for(let[W,X]of Z)K.push(` ${W}: ${X.toFixed(3)}ms`)}z.textContent=K.join(`
2
2
  `)},q);return()=>{clearInterval(J),z.remove()}}export{Y as createDiagnosticsPlugin,_ as createDiagnosticsOverlay};
3
3
 
4
- //# debugId=F11DE79F88C173D964756E2164756E21
4
+ //# debugId=93AA75AE725BACCC64756E2164756E21
5
5
  //# sourceMappingURL=diagnostics.js.map
@@ -2,9 +2,9 @@
2
2
  "version": 3,
3
3
  "sources": ["../src/plugins/diagnostics.ts"],
4
4
  "sourcesContent": [
5
- "/**\n * Diagnostics Plugin for ECSpresso\n *\n * Runtime diagnostics: FPS, entity count, per-system timing, per-phase timing,\n * and an optional DOM overlay for visual debugging.\n */\n\nimport { definePlugin, type Plugin } from 'ecspresso';\nimport type { SystemPhase } from 'ecspresso';\nimport type { WorldConfigFrom, EmptyConfig } from '../type-utils';\n\n// ==================== Types ====================\n\nexport interface DiagnosticsData {\n\tfps: number;\n\tentityCount: number;\n\tsystemTimings: ReadonlyMap<string, number>;\n\tphaseTimings: Readonly<Record<SystemPhase, number>>;\n\taverageFrameTime: number;\n}\n\nexport interface DiagnosticsResourceTypes {\n\tdiagnostics: DiagnosticsData;\n}\n\nexport interface DiagnosticsPluginOptions<G extends string = 'diagnostics'> {\n\t/** System group name (default: 'diagnostics') */\n\tsystemGroup?: G;\n\t/** Enable timing collection on initialize (default: true) */\n\tenableTimingOnInit?: boolean;\n\t/** Number of frames to sample for FPS average (default: 60) */\n\tfpsSampleCount?: number;\n}\n\nexport interface DiagnosticsOverlayOptions {\n\t/** Corner position (default: 'top-left') */\n\tposition?: 'top-left' | 'top-right' | 'bottom-left' | 'bottom-right';\n\t/** Milliseconds between DOM updates (default: 200) */\n\tupdateInterval?: number;\n\t/** Show per-system timings (default: true) */\n\tshowSystemTimings?: boolean;\n\t/** Maximum systems to show in overlay (default: 10) */\n\tmaxSystemsShown?: number;\n}\n\n// ==================== Ring Buffer ====================\n\n/**\n * Fixed-size circular buffer for frame timestamps.\n * Avoids Array.shift() allocation on every frame.\n */\nfunction createRingBuffer(capacity: number) {\n\tconst buffer = new Float64Array(capacity);\n\tlet writeIndex = 0;\n\tlet count = 0;\n\n\treturn {\n\t\tpush(value: number): void {\n\t\t\tbuffer[writeIndex] = value;\n\t\t\twriteIndex = (writeIndex + 1) % capacity;\n\t\t\tif (count < capacity) count++;\n\t\t},\n\n\t\t/** Compute FPS from stored timestamps */\n\t\tcomputeFps(): number {\n\t\t\tif (count < 2) return 0;\n\t\t\tconst newest = buffer[(writeIndex - 1 + capacity) % capacity] ?? 0;\n\t\t\tconst oldest = buffer[(writeIndex - count + capacity) % capacity] ?? 0;\n\t\t\tconst elapsed = newest - oldest;\n\t\t\tif (elapsed <= 0) return 0;\n\t\t\treturn ((count - 1) / elapsed) * 1000;\n\t\t},\n\n\t\t/** Compute average frame time in ms */\n\t\tcomputeAverageFrameTime(): number {\n\t\t\tif (count < 2) return 0;\n\t\t\tconst newest = buffer[(writeIndex - 1 + capacity) % capacity] ?? 0;\n\t\t\tconst oldest = buffer[(writeIndex - count + capacity) % capacity] ?? 0;\n\t\t\tconst elapsed = newest - oldest;\n\t\t\tif (elapsed <= 0) return 0;\n\t\t\treturn elapsed / (count - 1);\n\t\t},\n\n\t\tget size(): number {\n\t\t\treturn count;\n\t\t},\n\t};\n}\n\n// ==================== Plugin Factory ====================\n\nexport function createDiagnosticsPlugin<G extends string = 'diagnostics'>(\n\toptions?: DiagnosticsPluginOptions<G>,\n): Plugin<WorldConfigFrom<{}, {}, DiagnosticsResourceTypes>, EmptyConfig, 'diagnostics-collect', G> {\n\tconst {\n\t\tsystemGroup = 'diagnostics',\n\t\tenableTimingOnInit = true,\n\t\tfpsSampleCount = 60,\n\t} = options ?? {};\n\n\tconst initialData: DiagnosticsData = {\n\t\tfps: 0,\n\t\tentityCount: 0,\n\t\tsystemTimings: new Map(),\n\t\tphaseTimings: { preUpdate: 0, fixedUpdate: 0, update: 0, postUpdate: 0, render: 0 },\n\t\taverageFrameTime: 0,\n\t};\n\n\tconst ringBuffer = createRingBuffer(fpsSampleCount);\n\n\treturn definePlugin<WorldConfigFrom<{}, {}, DiagnosticsResourceTypes>, EmptyConfig, 'diagnostics-collect', G>({\n\t\tid: 'diagnostics',\n\t\tinstall(world) {\n\t\t\tworld.addResource('diagnostics', initialData);\n\n\t\t\tworld\n\t\t\t\t.addSystem('diagnostics-collect')\n\t\t\t\t.setPriority(-999999)\n\t\t\t\t.inPhase('render')\n\t\t\t\t.inGroup(systemGroup)\n\t\t\t\t.setOnInitialize((ecs) => {\n\t\t\t\t\tif (enableTimingOnInit) {\n\t\t\t\t\t\tecs.enableDiagnostics(true);\n\t\t\t\t\t}\n\t\t\t\t})\n\t\t\t\t.setOnDetach((ecs) => {\n\t\t\t\t\tecs.enableDiagnostics(false);\n\t\t\t\t})\n\t\t\t\t.setProcess(({ ecs }) => {\n\t\t\t\t\tconst now = performance.now();\n\t\t\t\t\tringBuffer.push(now);\n\n\t\t\t\t\tconst resource = ecs.getResource('diagnostics');\n\t\t\t\t\tconst updated: DiagnosticsData = {\n\t\t\t\t\t\tfps: ringBuffer.computeFps(),\n\t\t\t\t\t\tentityCount: ecs.entityCount,\n\t\t\t\t\t\tsystemTimings: ecs.systemTimings,\n\t\t\t\t\t\tphaseTimings: ecs.phaseTimings,\n\t\t\t\t\t\taverageFrameTime: ringBuffer.computeAverageFrameTime(),\n\t\t\t\t\t};\n\n\t\t\t\t\t// Mutate fields on the existing resource object to avoid allocation\n\t\t\t\t\t(resource as { -readonly [K in keyof DiagnosticsData]: DiagnosticsData[K] }).fps = updated.fps;\n\t\t\t\t\t(resource as { -readonly [K in keyof DiagnosticsData]: DiagnosticsData[K] }).entityCount = updated.entityCount;\n\t\t\t\t\t(resource as { -readonly [K in keyof DiagnosticsData]: DiagnosticsData[K] }).systemTimings = updated.systemTimings;\n\t\t\t\t\t(resource as { -readonly [K in keyof DiagnosticsData]: DiagnosticsData[K] }).phaseTimings = updated.phaseTimings;\n\t\t\t\t\t(resource as { -readonly [K in keyof DiagnosticsData]: DiagnosticsData[K] }).averageFrameTime = updated.averageFrameTime;\n\t\t\t\t});\n\t\t},\n\t});\n}\n\n// ==================== Overlay Helper ====================\n\nconst POSITION_STYLES: Record<NonNullable<DiagnosticsOverlayOptions['position']>, string> = {\n\t'top-left': 'top:8px;left:8px',\n\t'top-right': 'top:8px;right:8px',\n\t'bottom-left': 'bottom:8px;left:8px',\n\t'bottom-right': 'bottom:8px;right:8px',\n} as const;\n\n/**\n * Create a DOM overlay that displays diagnostics data.\n * Returns a cleanup function that removes the element and clears the interval.\n *\n * @param ecs An ECSpresso instance with the diagnostics resource\n * @param options Overlay configuration\n * @returns Cleanup function\n */\nexport function createDiagnosticsOverlay<\n\tR extends DiagnosticsResourceTypes,\n>(\n\tecs: { getResource<K extends keyof R>(key: K): R[K] },\n\toptions?: DiagnosticsOverlayOptions,\n): () => void {\n\tconst {\n\t\tposition = 'top-left',\n\t\tupdateInterval = 200,\n\t\tshowSystemTimings = true,\n\t\tmaxSystemsShown = 10,\n\t} = options ?? {};\n\n\tconst el = document.createElement('div');\n\tel.style.cssText = `position:fixed;${POSITION_STYLES[position]};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`;\n\tdocument.body.appendChild(el);\n\n\tconst intervalId = setInterval(() => {\n\t\tconst d = ecs.getResource('diagnostics' as keyof R) as DiagnosticsData;\n\n\t\tconst lines: string[] = [\n\t\t\t`FPS: ${d.fps.toFixed(0)}`,\n\t\t\t`Frame: ${d.averageFrameTime.toFixed(2)}ms`,\n\t\t\t`Entities: ${d.entityCount}`,\n\t\t];\n\n\t\tconst phases = d.phaseTimings;\n\t\tlines.push(\n\t\t\t`Phases: pre=${phases.preUpdate.toFixed(2)} fix=${phases.fixedUpdate.toFixed(2)} upd=${phases.update.toFixed(2)} post=${phases.postUpdate.toFixed(2)} ren=${phases.render.toFixed(2)}`,\n\t\t);\n\n\t\tif (showSystemTimings && d.systemTimings.size > 0) {\n\t\t\tlines.push('--- Systems ---');\n\t\t\tconst sorted = [...d.systemTimings.entries()]\n\t\t\t\t.sort((a, b) => b[1] - a[1])\n\t\t\t\t.slice(0, maxSystemsShown);\n\t\t\tfor (const [label, ms] of sorted) {\n\t\t\t\tlines.push(` ${label}: ${ms.toFixed(3)}ms`);\n\t\t\t}\n\t\t}\n\n\t\tel.textContent = lines.join('\\n');\n\t}, updateInterval);\n\n\treturn () => {\n\t\tclearInterval(intervalId);\n\t\tel.remove();\n\t};\n}\n"
5
+ "/**\n * Diagnostics Plugin for ECSpresso\n *\n * Runtime diagnostics: FPS, entity count, per-system timing, per-phase timing,\n * and an optional DOM overlay for visual debugging.\n */\n\nimport { definePlugin } from 'ecspresso';\nimport type { SystemPhase } from 'ecspresso';\n\n// ==================== Types ====================\n\nexport interface DiagnosticsData {\n\tfps: number;\n\tentityCount: number;\n\tsystemTimings: ReadonlyMap<string, number>;\n\tphaseTimings: Readonly<Record<SystemPhase, number>>;\n\taverageFrameTime: number;\n}\n\nexport interface DiagnosticsResourceTypes {\n\tdiagnostics: DiagnosticsData;\n}\n\nexport interface DiagnosticsPluginOptions<G extends string = 'diagnostics'> {\n\t/** System group name (default: 'diagnostics') */\n\tsystemGroup?: G;\n\t/** Enable timing collection on initialize (default: true) */\n\tenableTimingOnInit?: boolean;\n\t/** Number of frames to sample for FPS average (default: 60) */\n\tfpsSampleCount?: number;\n}\n\nexport interface DiagnosticsOverlayOptions {\n\t/** Corner position (default: 'top-left') */\n\tposition?: 'top-left' | 'top-right' | 'bottom-left' | 'bottom-right';\n\t/** Milliseconds between DOM updates (default: 200) */\n\tupdateInterval?: number;\n\t/** Show per-system timings (default: true) */\n\tshowSystemTimings?: boolean;\n\t/** Maximum systems to show in overlay (default: 10) */\n\tmaxSystemsShown?: number;\n}\n\n// ==================== Ring Buffer ====================\n\n/**\n * Fixed-size circular buffer for frame timestamps.\n * Avoids Array.shift() allocation on every frame.\n */\nfunction createRingBuffer(capacity: number) {\n\tconst buffer = new Float64Array(capacity);\n\tlet writeIndex = 0;\n\tlet count = 0;\n\n\treturn {\n\t\tpush(value: number): void {\n\t\t\tbuffer[writeIndex] = value;\n\t\t\twriteIndex = (writeIndex + 1) % capacity;\n\t\t\tif (count < capacity) count++;\n\t\t},\n\n\t\t/** Compute FPS from stored timestamps */\n\t\tcomputeFps(): number {\n\t\t\tif (count < 2) return 0;\n\t\t\tconst newest = buffer[(writeIndex - 1 + capacity) % capacity] ?? 0;\n\t\t\tconst oldest = buffer[(writeIndex - count + capacity) % capacity] ?? 0;\n\t\t\tconst elapsed = newest - oldest;\n\t\t\tif (elapsed <= 0) return 0;\n\t\t\treturn ((count - 1) / elapsed) * 1000;\n\t\t},\n\n\t\t/** Compute average frame time in ms */\n\t\tcomputeAverageFrameTime(): number {\n\t\t\tif (count < 2) return 0;\n\t\t\tconst newest = buffer[(writeIndex - 1 + capacity) % capacity] ?? 0;\n\t\t\tconst oldest = buffer[(writeIndex - count + capacity) % capacity] ?? 0;\n\t\t\tconst elapsed = newest - oldest;\n\t\t\tif (elapsed <= 0) return 0;\n\t\t\treturn elapsed / (count - 1);\n\t\t},\n\n\t\tget size(): number {\n\t\t\treturn count;\n\t\t},\n\t};\n}\n\n// ==================== Plugin Factory ====================\n\nexport function createDiagnosticsPlugin<G extends string = 'diagnostics'>(\n\toptions?: DiagnosticsPluginOptions<G>,\n) {\n\tconst {\n\t\tsystemGroup = 'diagnostics',\n\t\tenableTimingOnInit = true,\n\t\tfpsSampleCount = 60,\n\t} = options ?? {};\n\n\tconst initialData: DiagnosticsData = {\n\t\tfps: 0,\n\t\tentityCount: 0,\n\t\tsystemTimings: new Map(),\n\t\tphaseTimings: { preUpdate: 0, fixedUpdate: 0, update: 0, postUpdate: 0, render: 0 },\n\t\taverageFrameTime: 0,\n\t};\n\n\tconst ringBuffer = createRingBuffer(fpsSampleCount);\n\n\treturn definePlugin('diagnostics')\n\t\t.withResourceTypes<DiagnosticsResourceTypes>()\n\t\t.withLabels<'diagnostics-collect'>()\n\t\t.withGroups<G>()\n\t\t.install((world) => {\n\t\t\tworld.addResource('diagnostics', initialData);\n\n\t\t\tworld\n\t\t\t\t.addSystem('diagnostics-collect')\n\t\t\t\t.setPriority(-999999)\n\t\t\t\t.inPhase('render')\n\t\t\t\t.inGroup(systemGroup)\n\t\t\t\t.setOnInitialize((ecs) => {\n\t\t\t\t\tif (enableTimingOnInit) {\n\t\t\t\t\t\tecs.enableDiagnostics(true);\n\t\t\t\t\t}\n\t\t\t\t})\n\t\t\t\t.setOnDetach((ecs) => {\n\t\t\t\t\tecs.enableDiagnostics(false);\n\t\t\t\t})\n\t\t\t\t.setProcess(({ ecs }) => {\n\t\t\t\t\tconst now = performance.now();\n\t\t\t\t\tringBuffer.push(now);\n\n\t\t\t\t\tconst resource = ecs.getResource('diagnostics');\n\t\t\t\t\tconst updated: DiagnosticsData = {\n\t\t\t\t\t\tfps: ringBuffer.computeFps(),\n\t\t\t\t\t\tentityCount: ecs.entityCount,\n\t\t\t\t\t\tsystemTimings: ecs.systemTimings,\n\t\t\t\t\t\tphaseTimings: ecs.phaseTimings,\n\t\t\t\t\t\taverageFrameTime: ringBuffer.computeAverageFrameTime(),\n\t\t\t\t\t};\n\n\t\t\t\t\t// Mutate fields on the existing resource object to avoid allocation\n\t\t\t\t\t(resource as { -readonly [K in keyof DiagnosticsData]: DiagnosticsData[K] }).fps = updated.fps;\n\t\t\t\t\t(resource as { -readonly [K in keyof DiagnosticsData]: DiagnosticsData[K] }).entityCount = updated.entityCount;\n\t\t\t\t\t(resource as { -readonly [K in keyof DiagnosticsData]: DiagnosticsData[K] }).systemTimings = updated.systemTimings;\n\t\t\t\t\t(resource as { -readonly [K in keyof DiagnosticsData]: DiagnosticsData[K] }).phaseTimings = updated.phaseTimings;\n\t\t\t\t\t(resource as { -readonly [K in keyof DiagnosticsData]: DiagnosticsData[K] }).averageFrameTime = updated.averageFrameTime;\n\t\t\t\t});\n\t\t});\n}\n\n// ==================== Overlay Helper ====================\n\nconst POSITION_STYLES: Record<NonNullable<DiagnosticsOverlayOptions['position']>, string> = {\n\t'top-left': 'top:8px;left:8px',\n\t'top-right': 'top:8px;right:8px',\n\t'bottom-left': 'bottom:8px;left:8px',\n\t'bottom-right': 'bottom:8px;right:8px',\n} as const;\n\n/**\n * Create a DOM overlay that displays diagnostics data.\n * Returns a cleanup function that removes the element and clears the interval.\n *\n * @param ecs An ECSpresso instance with the diagnostics resource\n * @param options Overlay configuration\n * @returns Cleanup function\n */\nexport function createDiagnosticsOverlay<\n\tR extends DiagnosticsResourceTypes,\n>(\n\tecs: { getResource<K extends keyof R>(key: K): R[K] },\n\toptions?: DiagnosticsOverlayOptions,\n): () => void {\n\tconst {\n\t\tposition = 'top-left',\n\t\tupdateInterval = 200,\n\t\tshowSystemTimings = true,\n\t\tmaxSystemsShown = 10,\n\t} = options ?? {};\n\n\tconst el = document.createElement('div');\n\tel.style.cssText = `position:fixed;${POSITION_STYLES[position]};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`;\n\tdocument.body.appendChild(el);\n\n\tconst intervalId = setInterval(() => {\n\t\tconst d = ecs.getResource('diagnostics' as keyof R) as DiagnosticsData;\n\n\t\tconst lines: string[] = [\n\t\t\t`FPS: ${d.fps.toFixed(0)}`,\n\t\t\t`Frame: ${d.averageFrameTime.toFixed(2)}ms`,\n\t\t\t`Entities: ${d.entityCount}`,\n\t\t];\n\n\t\tconst phases = d.phaseTimings;\n\t\tlines.push(\n\t\t\t`Phases: pre=${phases.preUpdate.toFixed(2)} fix=${phases.fixedUpdate.toFixed(2)} upd=${phases.update.toFixed(2)} post=${phases.postUpdate.toFixed(2)} ren=${phases.render.toFixed(2)}`,\n\t\t);\n\n\t\tif (showSystemTimings && d.systemTimings.size > 0) {\n\t\t\tlines.push('--- Systems ---');\n\t\t\tconst sorted = [...d.systemTimings.entries()]\n\t\t\t\t.sort((a, b) => b[1] - a[1])\n\t\t\t\t.slice(0, maxSystemsShown);\n\t\t\tfor (const [label, ms] of sorted) {\n\t\t\t\tlines.push(` ${label}: ${ms.toFixed(3)}ms`);\n\t\t\t}\n\t\t}\n\n\t\tel.textContent = lines.join('\\n');\n\t}, updateInterval);\n\n\treturn () => {\n\t\tclearInterval(intervalId);\n\t\tel.remove();\n\t};\n}\n"
6
6
  ],
7
- "mappings": "2PAOA,uBAAS,kBA4CT,SAAS,CAAgB,CAAC,EAAkB,CAC3C,IAAM,EAAS,IAAI,aAAa,CAAQ,EACpC,EAAa,EACb,EAAQ,EAEZ,MAAO,CACN,IAAI,CAAC,EAAqB,CAGzB,GAFA,EAAO,GAAc,EACrB,GAAc,EAAa,GAAK,EAC5B,EAAQ,EAAU,KAIvB,UAAU,EAAW,CACpB,GAAI,EAAQ,EAAG,MAAO,GACtB,IAAM,EAAS,EAAQ,GAAa,EAAI,GAAY,IAAa,EAC3D,EAAS,EAAQ,GAAa,EAAQ,GAAY,IAAa,EAC/D,EAAU,EAAS,EACzB,GAAI,GAAW,EAAG,MAAO,GACzB,OAAS,EAAQ,GAAK,EAAW,MAIlC,uBAAuB,EAAW,CACjC,GAAI,EAAQ,EAAG,MAAO,GACtB,IAAM,EAAS,EAAQ,GAAa,EAAI,GAAY,IAAa,EAC3D,EAAS,EAAQ,GAAa,EAAQ,GAAY,IAAa,EAC/D,EAAU,EAAS,EACzB,GAAI,GAAW,EAAG,MAAO,GACzB,OAAO,GAAW,EAAQ,OAGvB,KAAI,EAAW,CAClB,OAAO,EAET,EAKM,SAAS,CAAyD,CACxE,EACmG,CACnG,IACC,cAAc,cACd,qBAAqB,GACrB,iBA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AAmB,EAAQ,iBACxG,EACF,EAKH,IAAM,EAAsF,CAC3F,WAAY,mBACZ,YAAa,oBACb,cAAe,sBACf,eAAgB,sBACjB,EAUO,SAAS,CAEf,CACA,EACA,EACa,CACb,IACC,WAAW,WACX,iBAAiB,IACjB,oBAAoB,GACpB,kBAAkB,IACf,GAAW,CAAC,EAEV,EAAK,SAAS,cAAc,KAAK,EACvC,EAAG,MAAM,QAAU,kBAAkB,EAAgB,yJACrD,SAAS,KAAK,YAAY,CAAE,EAE5B,IAAM,EAAa,YAAY,IAAM,CACpC,IAAM,EAAI,EAAI,YAAY,aAAwB,EAE5C,EAAkB,CACvB,QAAQ,EAAE,IAAI,QAAQ,CAAC,IACvB,UAAU,EAAE,iBAAiB,QAAQ,CAAC,MACtC,aAAa,EAAE,aAChB,EAEM,EAAS,EAAE,aAKjB,GAJA,EAAM,KACL,eAAe,EAAO,UAAU,QAAQ,CAAC,SAAS,EAAO,YAAY,QAAQ,CAAC,SAAS,EAAO,OAAO,QAAQ,CAAC,UAAU,EAAO,WAAW,QAAQ,CAAC,SAAS,EAAO,OAAO,QAAQ,CAAC,GACpL,EAEI,GAAqB,EAAE,cAAc,KAAO,EAAG,CAClD,EAAM,KAAK,iBAAiB,EAC5B,IAAM,EAAS,CAAC,GAAG,EAAE,cAAc,QAAQ,CAAC,EAC1C,KAAK,CAAC,EAAG,IAAM,EAAE,GAAK,EAAE,EAAE,EAC1B,MAAM,EAAG,CAAe,EAC1B,QAAY,EAAO,KAAO,EACzB,EAAM,KAAK,KAAK,MAAU,EAAG,QAAQ,CAAC,KAAK,EAI7C,EAAG,YAAc,EAAM,KAAK;AAAA,CAAI,GAC9B,CAAc,EAEjB,MAAO,IAAM,CACZ,cAAc,CAAU,EACxB,EAAG,OAAO",
8
+ "debugId": "93AA75AE725BACCC64756E2164756E21",
9
9
  "names": []
10
10
  }
@@ -8,8 +8,7 @@
8
8
  * DOM events are accumulated between frames and snapshotted once per frame
9
9
  * in the system's process step, so all systems see consistent state.
10
10
  */
11
- import { type Plugin, type BasePluginOptions } from 'ecspresso';
12
- import type { WorldConfigFrom, EmptyConfig } from '../type-utils';
11
+ import { type BasePluginOptions } from 'ecspresso';
13
12
  export interface Vec2 {
14
13
  x: number;
15
14
  y: number;
@@ -73,6 +72,15 @@ export interface InputPluginOptions<A extends string = string, G extends string
73
72
  actions?: ActionMap<A>;
74
73
  /** EventTarget to attach listeners to (default: globalThis). Pass a custom target for testability. */
75
74
  target?: EventTarget;
75
+ /**
76
+ * Optional conversion from raw DOM client coordinates to the space `inputState.pointer.position` should report.
77
+ * Renderer-agnostic: wire to `clientToLogical(...)` from renderer2D when using `screenScale`, or to a renderer-specific helper.
78
+ * When omitted, pointer coords remain raw `clientX`/`clientY` (not canvas-relative).
79
+ */
80
+ coordinateTransform?: (clientX: number, clientY: number) => {
81
+ x: number;
82
+ y: number;
83
+ };
76
84
  }
77
85
  /**
78
86
  * Create a single action binding.
@@ -107,5 +115,5 @@ export declare function createActionBinding(binding: ActionBinding): ActionBindi
107
115
  * if (input.keyboard.isDown('ArrowRight')) { ... }
108
116
  * ```
109
117
  */
110
- export declare function createInputPlugin<A extends string = string, G extends string = 'input'>(options?: InputPluginOptions<A, G>): Plugin<WorldConfigFrom<{}, {}, InputResourceTypes<A>>, EmptyConfig, 'input-state', G>;
118
+ export declare function createInputPlugin<A extends string = string, G extends string = 'input'>(options?: InputPluginOptions<A, G>): import("ecspresso").Plugin<import("ecspresso").WithResources<import("ecspresso").EmptyConfig, InputResourceTypes<A>>, import("ecspresso").EmptyConfig, "input-state", G, never, never>;
111
119
  export {};
@@ -1,4 +1,4 @@
1
- var S=((z)=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(z,{get:(Q,V)=>(typeof require<"u"?require:Q)[V]}):z)(function(z){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+z+'" is not supported')});import{definePlugin as N}from"ecspresso";function k(z){return z}function Y(){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,B=new Set;function A(){return{keysDown:K,keysPressed:K,keysReleased:K,buttonsDown:B,buttonsPressed:B,buttonsReleased:B,pointerX:0,pointerY:0,pointerDeltaX:0,pointerDeltaY:0,actionsActive:K,prevActionsActive:K}}function D(z,Q,V){let W=new Set;for(let[$,Z]of Object.entries(z)){let J=Z.keys?.some((O)=>Q.has(O))??!1,H=Z.buttons?.some((O)=>V.has(O))??!1;if(J||H)W.add($)}return W}function R(z,Q,V){let W=new Set(z.keysDown),$=new Set(z.keysPressed),Z=new Set(z.keysReleased),J=new Set(z.buttonsDown),H=new Set(z.buttonsPressed),O=new Set(z.buttonsReleased),f=z.pointerMoved?z.pointerX-z.lastPointerX:0,j=z.pointerMoved?z.pointerY-z.lastPointerY:0,x=D(V,W,J),F={keysDown:W,keysPressed:$,keysReleased:Z,buttonsDown:J,buttonsPressed:H,buttonsReleased:O,pointerX:z.pointerX,pointerY:z.pointerY,pointerDeltaX:f,pointerDeltaY:j,actionsActive:x,prevActionsActive:Q};return z.keysPressed=[],z.keysReleased=[],z.buttonsPressed=[],z.buttonsReleased=[],z.lastPointerX=z.pointerX,z.lastPointerY=z.pointerY,z.pointerMoved=!1,F}function E(z){let{systemGroup:Q="input",priority:V=100,phase:W="preUpdate",actions:$={},target:Z=globalThis}=z??{},J=Y(),H=A(),O={...$},f=[],j={x:0,y:0},x={x:0,y:0},m={keyboard:{isDown:(q)=>H.keysDown.has(q),justPressed:(q)=>H.keysPressed.has(q),justReleased:(q)=>H.keysReleased.has(q)},pointer:{position:j,delta:x,isDown:(q)=>H.buttonsDown.has(q),justPressed:(q)=>H.buttonsPressed.has(q),justReleased:(q)=>H.buttonsReleased.has(q)},actions:{isActive:(q)=>H.actionsActive.has(q),justActivated:(q)=>H.actionsActive.has(q)&&!H.prevActionsActive.has(q),justDeactivated:(q)=>!H.actionsActive.has(q)&&H.prevActionsActive.has(q)},setActionMap(q){O={...q}},getActionMap(){return{...O}}};function L(q){let C=q;if(C.repeat)return;J.keysDown.add(C.key),J.keysPressed.push(C.key)}function G(q){let C=q;J.keysDown.delete(C.key),J.keysReleased.push(C.key)}function I(q){let C=q;J.buttonsDown.add(C.button),J.buttonsPressed.push(C.button)}function U(q){let C=q;J.pointerX=C.clientX,J.pointerY=C.clientY,J.pointerMoved=!0}function g(q){let C=q;J.buttonsDown.delete(C.button),J.buttonsReleased.push(C.button)}function X(q,C){Z.addEventListener(q,C),f.push(()=>{Z.removeEventListener(q,C)})}return N({id:"input",install(q){q.addResource("inputState",m),q.addSystem("input-state").setPriority(V).inPhase(W).inGroup(Q).setOnInitialize(()=>{X("keydown",L),X("keyup",G),X("pointerdown",I),X("pointermove",U),X("pointerup",g)}).setOnDetach(()=>{for(let C of f)C();f.length=0}).setProcess(()=>{let C=H.actionsActive;H=R(J,C,O),j.x=H.pointerX,j.y=H.pointerY,x.x=H.pointerDeltaX,x.y=H.pointerDeltaY})}})}export{E as createInputPlugin,k as createActionBinding};
1
+ var k=((z)=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(z,{get:(O,Q)=>(typeof require<"u"?require:O)[Q]}):z)(function(z){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+z+'" is not supported')});import{definePlugin as A}from"ecspresso";function u(z){return z}function D(){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 B=new Set,F=new Set;function R(){return{keysDown:B,keysPressed:B,keysReleased:B,buttonsDown:F,buttonsPressed:F,buttonsReleased:F,pointerX:0,pointerY:0,pointerDeltaX:0,pointerDeltaY:0,actionsActive:B,prevActionsActive:B}}function v(z,O,Q){let V=new Set;for(let[$,W]of Object.entries(z)){let Z=W.keys?.some((H)=>O.has(H))??!1,J=W.buttons?.some((H)=>Q.has(H))??!1;if(Z||J)V.add($)}return V}function P(z,O,Q){let V=new Set(z.keysDown),$=new Set(z.keysPressed),W=new Set(z.keysReleased),Z=new Set(z.buttonsDown),J=new Set(z.buttonsPressed),H=new Set(z.buttonsReleased),j=z.pointerMoved?z.pointerX-z.lastPointerX:0,X=z.pointerMoved?z.pointerY-z.lastPointerY:0,x=v(Q,V,Z),K={keysDown:V,keysPressed:$,keysReleased:W,buttonsDown:Z,buttonsPressed:J,buttonsReleased:H,pointerX:z.pointerX,pointerY:z.pointerY,pointerDeltaX:j,pointerDeltaY:X,actionsActive:x,prevActionsActive:O};return z.keysPressed=[],z.keysReleased=[],z.buttonsPressed=[],z.buttonsReleased=[],z.lastPointerX=z.pointerX,z.lastPointerY=z.pointerY,z.pointerMoved=!1,K}function l(z){let{systemGroup:O="input",priority:Q=100,phase:V="preUpdate",actions:$={},target:W=globalThis,coordinateTransform:Z}=z??{},J=D(),H=R(),j={...$},X=[],x={x:0,y:0},K={x:0,y:0},L={keyboard:{isDown:(q)=>H.keysDown.has(q),justPressed:(q)=>H.keysPressed.has(q),justReleased:(q)=>H.keysReleased.has(q)},pointer:{position:x,delta:K,isDown:(q)=>H.buttonsDown.has(q),justPressed:(q)=>H.buttonsPressed.has(q),justReleased:(q)=>H.buttonsReleased.has(q)},actions:{isActive:(q)=>H.actionsActive.has(q),justActivated:(q)=>H.actionsActive.has(q)&&!H.prevActionsActive.has(q),justDeactivated:(q)=>!H.actionsActive.has(q)&&H.prevActionsActive.has(q)},setActionMap(q){j={...q}},getActionMap(){return{...j}}};function m(q){let C=q;if(C.repeat)return;J.keysDown.add(C.key),J.keysPressed.push(C.key)}function G(q){let C=q;J.keysDown.delete(C.key),J.keysReleased.push(C.key)}function I(q){let C=q;J.buttonsDown.add(C.button),J.buttonsPressed.push(C.button)}function U(q){let C=q;if(Z){let{x:N,y:Y}=Z(C.clientX,C.clientY);J.pointerX=N,J.pointerY=Y}else J.pointerX=C.clientX,J.pointerY=C.clientY;J.pointerMoved=!0}function g(q){let C=q;J.buttonsDown.delete(C.button),J.buttonsReleased.push(C.button)}function f(q,C){W.addEventListener(q,C),X.push(()=>{W.removeEventListener(q,C)})}return A("input").withResourceTypes().withLabels().withGroups().install((q)=>{q.addResource("inputState",L),q.addSystem("input-state").setPriority(Q).inPhase(V).inGroup(O).setOnInitialize(()=>{f("keydown",m),f("keyup",G),f("pointerdown",I),f("pointermove",U),f("pointerup",g)}).setOnDetach(()=>{for(let C of X)C();X.length=0}).setProcess(()=>{let C=H.actionsActive;H=P(J,C,j),x.x=H.pointerX,x.y=H.pointerY,K.x=H.pointerDeltaX,K.y=H.pointerDeltaY})})}export{l as createInputPlugin,u as createActionBinding};
2
2
 
3
- //# debugId=513EE3E4CA561E4664756E2164756E21
3
+ //# debugId=E7F2EB68AF3B74CD64756E2164756E21
4
4
  //# sourceMappingURL=input.js.map