ecspresso 0.14.2 → 0.14.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.js +2 -2
- package/dist/index.js.map +1 -1
- package/dist/plugins/ai/flocking.js +2 -2
- package/dist/plugins/ai/flocking.js.map +4 -4
- package/dist/plugins/physics/collision.js +2 -2
- package/dist/plugins/physics/collision.js.map +4 -4
- package/dist/plugins/physics/collision3D.js +2 -2
- package/dist/plugins/physics/collision3D.js.map +6 -6
- package/dist/plugins/physics/physics2D.js +2 -2
- package/dist/plugins/physics/physics2D.js.map +4 -4
- package/dist/plugins/physics/physics3D.js +2 -2
- package/dist/plugins/physics/physics3D.js.map +4 -4
- package/dist/plugins/rendering/renderer3D.js +20 -20
- package/dist/plugins/rendering/renderer3D.js.map +3 -3
- package/dist/plugins/spatial/camera3D.d.ts +1 -0
- package/dist/plugins/spatial/camera3D.js +2 -2
- package/dist/plugins/spatial/camera3D.js.map +3 -3
- package/dist/plugins/spatial/spatial-index3D.js +2 -2
- package/dist/plugins/spatial/spatial-index3D.js.map +3 -3
- package/package.json +14 -2
|
@@ -2,11 +2,11 @@
|
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../src/plugins/physics/physics2D.ts", "../src/utils/narrowphase.ts", "../src/plugins/ai/flocking.ts"],
|
|
4
4
|
"sourcesContent": [
|
|
5
|
-
"/**\n * Physics 2D Plugin for ECSpresso\n *\n * Provides ECS-native arcade physics: gravity, forces, drag, semi-implicit Euler\n * integration, and impulse-based collision response with friction.\n *\n * Reuses collider types from the collision plugin for shape definitions.\n * Has its own collision detection in fixedUpdate for physics response;\n * the existing collision plugin can still run in postUpdate for game logic events.\n */\n\nimport { definePlugin } from 'ecspresso';\nimport type { SystemPhase } from 'ecspresso';\nimport type { TransformComponentTypes, TransformWorldConfig } from '../spatial/transform';\nimport type { CollisionComponentTypes, LayerFactories } from './collision';\nimport type { Vector2D } from 'ecspresso';\nimport { fillBaseColliderInfo, detectCollisions, AABB_SHAPE, type Contact, type BaseColliderInfo } from '../../utils/narrowphase';\nimport type { SpatialIndex } from '../../utils/spatial-hash';\n\n// ==================== Component Types ====================\n\n/**\n * Rigid body types for physics simulation.\n * - 'dynamic': Fully simulated (gravity, forces, collisions)\n * - 'kinematic': Moves via velocity only (ignores gravity/forces, immovable in collisions)\n * - 'static': Immovable (ignores gravity, forces, and velocity)\n */\nexport type BodyType = 'dynamic' | 'kinematic' | 'static';\n\n/**\n * Rigid body component controlling physics behavior.\n */\nexport interface RigidBody {\n\ttype: BodyType;\n\t/** Mass in arbitrary units. Affects force→acceleration. Infinity = immovable. */\n\tmass: number;\n\t/** Linear velocity damping coefficient (units/sec, 0 = none) */\n\tdrag: number;\n\t/** Bounciness 0–1 (0 = no bounce, 1 = perfectly elastic) */\n\trestitution: number;\n\t/** Surface friction coefficient 0–1 */\n\tfriction: number;\n\t/** Per-entity gravity multiplier (0 = no gravity) */\n\tgravityScale: number;\n}\n\n/**\n * Component types directly provided by the physics plugin.\n */\nexport interface Physics2DOwnComponentTypes {\n\trigidBody: RigidBody;\n\tvelocity: Vector2D;\n\tforce: Vector2D;\n}\n\n/**\n * Full component types available when using the physics plugin\n * (own components + transform + collision dependencies).\n * Convenience alias for consumer code.\n */\nexport interface Physics2DComponentTypes<L extends string = never> extends TransformComponentTypes, CollisionComponentTypes<L>, Physics2DOwnComponentTypes {}\n\n// ==================== Resource Types ====================\n\n/**\n * Physics configuration resource.\n */\nexport interface Physics2DConfig {\n\tgravity: Vector2D;\n}\n\nexport interface Physics2DResourceTypes {\n\tphysicsConfig: Physics2DConfig;\n}\n\n// ==================== Event Types ====================\n\n/**\n * Event emitted for each physics collision pair.\n *\n * Normal components are flattened (`normalX`/`normalY`) rather than nested\n * in a `Vector2D` to avoid a per-event allocation in the physics hot path.\n */\nexport interface Physics2DCollisionEvent {\n\tentityA: number;\n\tentityB: number;\n\t/** Unit normal X, pointing from A toward B */\n\tnormalX: number;\n\t/** Unit normal Y, pointing from A toward B */\n\tnormalY: number;\n\t/** Penetration depth (positive) */\n\tdepth: number;\n}\n\nexport interface Physics2DEventTypes {\n\tphysicsCollision: Physics2DCollisionEvent;\n}\n\n// ==================== Plugin Options ====================\n\nexport interface Physics2DPluginOptions<G extends string = 'physics2D', CG extends string = never> {\n\t/** World gravity vector (default: {x: 0, y: 0}) */\n\tgravity?: Vector2D;\n\t/** System group name (default: 'physics2D') */\n\tsystemGroup?: G;\n\t/** Additional group for the collision system only (default: none).\n\t * When set, the collision system belongs to both `systemGroup` and this group,\n\t * allowing independent enable/disable of collision detection. */\n\tcollisionSystemGroup?: CG;\n\t/** Priority for integration system (default: 1000) */\n\tintegrationPriority?: number;\n\t/** Priority for collision system (default: 900) */\n\tcollisionPriority?: number;\n\t/** Execution phase (default: 'fixedUpdate') */\n\tphase?: SystemPhase;\n}\n\n// ==================== Helper Functions ====================\n\nexport interface RigidBodyOptions {\n\tmass?: number;\n\tdrag?: number;\n\trestitution?: number;\n\tfriction?: number;\n\tgravityScale?: number;\n}\n\n/**\n * Create a rigid body + force component pair.\n * Static bodies automatically get mass=Infinity.\n */\nexport function createRigidBody(\n\ttype: BodyType,\n\toptions?: RigidBodyOptions,\n): { rigidBody: RigidBody; force: Vector2D } {\n\treturn {\n\t\trigidBody: {\n\t\t\ttype,\n\t\t\tmass: type === 'static' ? Infinity : (options?.mass ?? 1),\n\t\t\tdrag: options?.drag ?? 0,\n\t\t\trestitution: options?.restitution ?? 0,\n\t\t\tfriction: options?.friction ?? 0,\n\t\t\tgravityScale: options?.gravityScale ?? 1,\n\t\t},\n\t\tforce: { x: 0, y: 0 },\n\t};\n}\n\n/**\n * Create a force component with initial values.\n */\nexport function createForce(x: number, y: number): { force: Vector2D } {\n\treturn { force: { x, y } };\n}\n\n/**\n * Accumulate a force onto an entity's force component.\n */\nexport function applyForce(\n\tecs: { getComponent(id: number, name: 'force'): Vector2D | undefined },\n\tentityId: number,\n\tfx: number,\n\tfy: number,\n): void {\n\tconst force = ecs.getComponent(entityId, 'force');\n\tif (!force) return;\n\tforce.x += fx;\n\tforce.y += fy;\n}\n\n/**\n * Apply an instantaneous impulse: velocity += impulse / mass.\n */\nexport function applyImpulse(\n\tecs: {\n\t\tgetComponent(id: number, name: 'velocity'): Vector2D | undefined;\n\t\tgetComponent(id: number, name: 'rigidBody'): RigidBody | undefined;\n\t},\n\tentityId: number,\n\tix: number,\n\tiy: number,\n): void {\n\tconst velocity = ecs.getComponent(entityId, 'velocity');\n\tconst rigidBody = ecs.getComponent(entityId, 'rigidBody');\n\tif (!velocity || !rigidBody) return;\n\tif (rigidBody.mass === Infinity || rigidBody.mass === 0) return;\n\tvelocity.x += ix / rigidBody.mass;\n\tvelocity.y += iy / rigidBody.mass;\n}\n\n/**\n * Directly set an entity's velocity.\n */\nexport function setVelocity(\n\tecs: { getComponent(id: number, name: 'velocity'): Vector2D | undefined },\n\tentityId: number,\n\tvx: number,\n\tvy: number,\n): void {\n\tconst velocity = ecs.getComponent(entityId, 'velocity');\n\tif (!velocity) return;\n\tvelocity.x = vx;\n\tvelocity.y = vy;\n}\n\n// ==================== Internal: Collider Info ====================\n\ninterface Physics2DColliderInfo<L extends string = string> extends BaseColliderInfo<L> {\n\trigidBody: RigidBody;\n\tvelocity: Vector2D;\n}\n\n// ==================== Collision Response ====================\n\n/**\n * Module-level reusable physics collision event. Subscribers must consume\n * synchronously — same contract as the shared narrowphase Contact.\n */\nconst _physicsCollisionEvent: Physics2DCollisionEvent = {\n\tentityA: 0, entityB: 0, normalX: 0, normalY: 0, depth: 0,\n};\n\ninterface PhysicsEcsLike {\n\tgetComponent(id: number, name: 'localTransform'): { x: number; y: number } | undefined;\n\teventBus: { publish(event: 'physicsCollision', data: Physics2DCollisionEvent): void };\n\tmarkChanged(entityId: number, componentName: 'localTransform' | 'velocity'): void;\n}\n\n/**\n * Resolve a physics collision pair: position correction, impulse response, event.\n */\nfunction resolvePhysicsContact(\n\ta: Physics2DColliderInfo,\n\tb: Physics2DColliderInfo,\n\tcontact: Contact,\n\tecs: PhysicsEcsLike,\n): void {\n\tconst invMassA = (a.rigidBody.type === 'dynamic' && a.rigidBody.mass > 0 && a.rigidBody.mass !== Infinity)\n\t\t? 1 / a.rigidBody.mass\n\t\t: 0;\n\tconst invMassB = (b.rigidBody.type === 'dynamic' && b.rigidBody.mass > 0 && b.rigidBody.mass !== Infinity)\n\t\t? 1 / b.rigidBody.mass\n\t\t: 0;\n\tconst totalInvMass = invMassA + invMassB;\n\n\t// Position correction\n\tif (totalInvMass > 0) {\n\t\tconst correctionScale = contact.depth / totalInvMass;\n\n\t\tif (invMassA > 0) {\n\t\t\tconst ltA = ecs.getComponent(a.entityId, 'localTransform');\n\t\t\tif (!ltA) return;\n\t\t\tltA.x -= correctionScale * invMassA * contact.normalX;\n\t\t\tltA.y -= correctionScale * invMassA * contact.normalY;\n\t\t\t// Update cached position for subsequent pairs (collider offset already baked in)\n\t\t\ta.x = ltA.x;\n\t\t\tecs.markChanged(a.entityId, 'localTransform');\n\t\t}\n\n\t\tif (invMassB > 0) {\n\t\t\tconst ltB = ecs.getComponent(b.entityId, 'localTransform');\n\t\t\tif (!ltB) return;\n\t\t\tltB.x += correctionScale * invMassB * contact.normalX;\n\t\t\tltB.y += correctionScale * invMassB * contact.normalY;\n\t\t\tecs.markChanged(b.entityId, 'localTransform');\n\t\t}\n\n\t\t// Velocity response (impulse-based)\n\t\tconst relVelX = b.velocity.x - a.velocity.x;\n\t\tconst relVelY = b.velocity.y - a.velocity.y;\n\t\tconst velAlongNormal = relVelX * contact.normalX + relVelY * contact.normalY;\n\n\t\tif (velAlongNormal < 0) {\n\t\t\tconst restitution = Math.min(a.rigidBody.restitution, b.rigidBody.restitution);\n\t\t\tconst normalImpulse = -(1 + restitution) * velAlongNormal / totalInvMass;\n\n\t\t\ta.velocity.x -= normalImpulse * invMassA * contact.normalX;\n\t\t\ta.velocity.y -= normalImpulse * invMassA * contact.normalY;\n\t\t\tb.velocity.x += normalImpulse * invMassB * contact.normalX;\n\t\t\tb.velocity.y += normalImpulse * invMassB * contact.normalY;\n\n\t\t\t// Friction (tangential impulse)\n\t\t\tconst tangentX = relVelX - velAlongNormal * contact.normalX;\n\t\t\tconst tangentY = relVelY - velAlongNormal * contact.normalY;\n\t\t\tconst tangentSpeed = Math.sqrt(tangentX * tangentX + tangentY * tangentY);\n\n\t\t\tif (tangentSpeed > 1e-6) {\n\t\t\t\tconst tangentNX = tangentX / tangentSpeed;\n\t\t\t\tconst tangentNY = tangentY / tangentSpeed;\n\t\t\t\tconst friction = Math.sqrt(a.rigidBody.friction * b.rigidBody.friction);\n\t\t\t\tconst maxFrictionImpulse = friction * Math.abs(normalImpulse);\n\t\t\t\tconst tangentImpulse = Math.min(tangentSpeed / totalInvMass, maxFrictionImpulse);\n\n\t\t\t\ta.velocity.x += tangentImpulse * invMassA * tangentNX;\n\t\t\t\ta.velocity.y += tangentImpulse * invMassA * tangentNY;\n\t\t\t\tb.velocity.x -= tangentImpulse * invMassB * tangentNX;\n\t\t\t\tb.velocity.y -= tangentImpulse * invMassB * tangentNY;\n\t\t\t}\n\t\t}\n\n\t\tecs.markChanged(a.entityId, 'velocity');\n\t\tecs.markChanged(b.entityId, 'velocity');\n\t}\n\n\t_physicsCollisionEvent.entityA = a.entityId;\n\t_physicsCollisionEvent.entityB = b.entityId;\n\t_physicsCollisionEvent.normalX = contact.normalX;\n\t_physicsCollisionEvent.normalY = contact.normalY;\n\t_physicsCollisionEvent.depth = contact.depth;\n\tecs.eventBus.publish('physicsCollision', _physicsCollisionEvent);\n}\n\n// ==================== Plugin Factory ====================\n\n/**\n * Create a 2D physics plugin for ECSpresso.\n *\n * Provides:\n * - Semi-implicit Euler integration (gravity, forces, drag → velocity → position)\n * - Impulse-based collision response with restitution and friction\n * - physicsCollision events with contact normal and depth\n *\n * @example\n * ```typescript\n * const ecs = ECSpresso.create()\n * .withPlugin(createTransformPlugin())\n * .withPlugin(createPhysics2DPlugin({ gravity: { x: 0, y: 980 } }))\n * .withFixedTimestep(1/60)\n * .build();\n *\n * ecs.spawn({\n * ...createTransform(100, 200),\n * ...createRigidBody('dynamic', { mass: 1, restitution: 0.5 }),\n * velocity: { x: 0, y: 0 },\n * ...createAABBCollider(32, 32),\n * ...createCollisionLayer('player', ['ground']),\n * });\n * ```\n */\n\ntype Physics2DProvides<L extends string = never> = Physics2DOwnComponentTypes & CollisionComponentTypes<L>;\n\nexport function createPhysics2DPlugin<L extends string = never, G extends string = 'physics2D', CG extends string = never>(\n\toptions?: Physics2DPluginOptions<G, CG> & { layers?: LayerFactories<Record<L, readonly string[]>> },\n) {\n\tconst {\n\t\tgravity = { x: 0, y: 0 },\n\t\tsystemGroup = 'physics2D',\n\t\tcollisionSystemGroup,\n\t\tintegrationPriority = 1000,\n\t\tcollisionPriority = 900,\n\t\tphase = 'fixedUpdate',\n\t} = options ?? {};\n\n\treturn definePlugin('physics2D')\n\t\t.withComponentTypes<Physics2DProvides<L>>()\n\t\t.withEventTypes<Physics2DEventTypes>()\n\t\t.withResourceTypes<Physics2DResourceTypes>()\n\t\t.withLabels<'physics2D-integration' | 'physics2D-collision'>()\n\t\t.withGroups<G | CG>()\n\t\t.requires<TransformWorldConfig>()\n\t\t.install((world) => {\n\t\t\t// rigidBody requires velocity and force — auto-add with zero defaults\n\t\t\tworld.registerRequired('rigidBody', 'velocity', () => ({ x: 0, y: 0 }));\n\t\t\tworld.registerRequired('rigidBody', 'force', () => ({ x: 0, y: 0 }));\n\n\t\t\tworld.addResource('physicsConfig', { gravity: { x: gravity.x, y: gravity.y } });\n\n\t\t\t// ==================== Integration System ====================\n\n\t\t\tworld\n\t\t\t\t.addSystem('physics2D-integration')\n\t\t\t\t.setPriority(integrationPriority)\n\t\t\t\t.inPhase(phase)\n\t\t\t\t.inGroup(systemGroup)\n\t\t\t\t.addQuery('bodies', {\n\t\t\t\t\twith: ['localTransform', 'velocity', 'rigidBody', 'force'],\n\t\t\t\t})\n\t\t\t\t.setProcess(({ queries, dt, ecs }) => {\n\t\t\t\t\tconst { gravity: g } = ecs.getResource('physicsConfig');\n\t\t\t\t\tconst gx = g.x;\n\t\t\t\t\tconst gy = g.y;\n\n\t\t\t\t\tfor (const entity of queries.bodies) {\n\t\t\t\t\t\tconst { localTransform, velocity, rigidBody, force } = entity.components;\n\n\t\t\t\t\t\t// Static bodies: skip entirely\n\t\t\t\t\t\tif (rigidBody.type === 'static') continue;\n\n\t\t\t\t\t\t// Dynamic bodies: apply gravity, forces, drag\n\t\t\t\t\t\tif (rigidBody.type === 'dynamic') {\n\t\t\t\t\t\t\t// 1. Gravity\n\t\t\t\t\t\t\tvelocity.x += gx * rigidBody.gravityScale * dt;\n\t\t\t\t\t\t\tvelocity.y += gy * rigidBody.gravityScale * dt;\n\n\t\t\t\t\t\t\t// 2. Forces (F = ma → a = F/m)\n\t\t\t\t\t\t\tif (rigidBody.mass > 0 && rigidBody.mass !== Infinity) {\n\t\t\t\t\t\t\t\tvelocity.x += (force.x / rigidBody.mass) * dt;\n\t\t\t\t\t\t\t\tvelocity.y += (force.y / rigidBody.mass) * dt;\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t// 3. Drag\n\t\t\t\t\t\t\tif (rigidBody.drag > 0) {\n\t\t\t\t\t\t\t\tconst damping = Math.max(0, 1 - rigidBody.drag * dt);\n\t\t\t\t\t\t\t\tvelocity.x *= damping;\n\t\t\t\t\t\t\t\tvelocity.y *= damping;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\t// Both dynamic and kinematic: integrate position\n\t\t\t\t\t\tlocalTransform.x += velocity.x * dt;\n\t\t\t\t\t\tlocalTransform.y += velocity.y * dt;\n\n\t\t\t\t\t\t// Clear accumulated forces\n\t\t\t\t\t\tforce.x = 0;\n\t\t\t\t\t\tforce.y = 0;\n\n\t\t\t\t\t\tecs.markChanged(entity.id, 'localTransform');\n\t\t\t\t\t}\n\t\t\t\t});\n\n\t\t\t// ==================== Collision System ====================\n\n\t\t\tconst collisionSystem = world\n\t\t\t\t.addSystem('physics2D-collision')\n\t\t\t\t.setPriority(collisionPriority)\n\t\t\t\t.inPhase(phase)\n\t\t\t\t.inGroup(systemGroup);\n\n\t\t\tif (collisionSystemGroup) {\n\t\t\t\tcollisionSystem.inGroup(collisionSystemGroup);\n\t\t\t}\n\n\t\t\t// Grow-only pool of Physics2DColliderInfo slots reused across frames.\n\t\t\t// Steady-state: zero allocations per frame once the pool is warm.\n\t\t\tconst colliderPool: Physics2DColliderInfo<L>[] = [];\n\t\t\t// Reusable entityId → collider lookup for the broadphase path.\n\t\t\tconst broadphaseMap = new Map<number, Physics2DColliderInfo<L>>();\n\t\t\t// Cached spatial index reference (resolved once on first frame).\n\t\t\tlet cachedSI: SpatialIndex | undefined;\n\t\t\tlet siResolved = false;\n\n\t\t\tcollisionSystem\n\t\t\t\t.addQuery('collidables', {\n\t\t\t\t\twith: ['localTransform', 'rigidBody', 'velocity', '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 { localTransform, rigidBody, velocity, collisionLayer } = entity.components;\n\t\t\t\t\t\tconst aabb = ecs.getComponent(entity.id, 'aabbCollider');\n\t\t\t\t\t\tconst circle = aabb ? undefined : 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: localTransform.x,\n\t\t\t\t\t\t\t\ty: localTransform.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\trigidBody,\n\t\t\t\t\t\t\t\tvelocity,\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} else {\n\t\t\t\t\t\t\tslot.rigidBody = rigidBody;\n\t\t\t\t\t\t\tslot.velocity = velocity;\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, localTransform.x, localTransform.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\tif (!siResolved) {\n\t\t\t\t\t\tcachedSI = ecs.tryGetResource<SpatialIndex>('spatialIndex');\n\t\t\t\t\t\tsiResolved = true;\n\t\t\t\t\t}\n\t\t\t\t\tdetectCollisions(colliderPool, count, broadphaseMap, cachedSI, resolvePhysicsContact, ecs);\n\t\t\t\t});\n\t\t});\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",
|
|
5
|
+
"/**\n * Physics 2D Plugin for ECSpresso\n *\n * Provides ECS-native arcade physics: gravity, forces, drag, semi-implicit Euler\n * integration, and impulse-based collision response with friction.\n *\n * Reuses collider types from the collision plugin for shape definitions.\n * Has its own collision detection in fixedUpdate for physics response;\n * the existing collision plugin can still run in postUpdate for game logic events.\n */\n\nimport { definePlugin } from 'ecspresso';\nimport type { SystemPhase } from 'ecspresso';\nimport type { TransformComponentTypes, TransformWorldConfig } from '../spatial/transform';\nimport type { CollisionComponentTypes, LayerFactories } from './collision';\nimport type { Vector2D } from 'ecspresso';\nimport { fillBaseColliderInfo, detectCollisions, AABB_SHAPE, type Contact, type BaseColliderInfo } from '../../utils/narrowphase';\nimport type { SpatialIndex } from '../../utils/spatial-hash';\n\n// ==================== Component Types ====================\n\n/**\n * Rigid body types for physics simulation.\n * - 'dynamic': Fully simulated (gravity, forces, collisions)\n * - 'kinematic': Moves via velocity only (ignores gravity/forces, immovable in collisions)\n * - 'static': Immovable (ignores gravity, forces, and velocity)\n */\nexport type BodyType = 'dynamic' | 'kinematic' | 'static';\n\n/**\n * Rigid body component controlling physics behavior.\n */\nexport interface RigidBody {\n\ttype: BodyType;\n\t/** Mass in arbitrary units. Affects force→acceleration. Infinity = immovable. */\n\tmass: number;\n\t/** Linear velocity damping coefficient (units/sec, 0 = none) */\n\tdrag: number;\n\t/** Bounciness 0–1 (0 = no bounce, 1 = perfectly elastic) */\n\trestitution: number;\n\t/** Surface friction coefficient 0–1 */\n\tfriction: number;\n\t/** Per-entity gravity multiplier (0 = no gravity) */\n\tgravityScale: number;\n}\n\n/**\n * Component types directly provided by the physics plugin.\n */\nexport interface Physics2DOwnComponentTypes {\n\trigidBody: RigidBody;\n\tvelocity: Vector2D;\n\tforce: Vector2D;\n}\n\n/**\n * Full component types available when using the physics plugin\n * (own components + transform + collision dependencies).\n * Convenience alias for consumer code.\n */\nexport interface Physics2DComponentTypes<L extends string = never> extends TransformComponentTypes, CollisionComponentTypes<L>, Physics2DOwnComponentTypes {}\n\n// ==================== Resource Types ====================\n\n/**\n * Physics configuration resource.\n */\nexport interface Physics2DConfig {\n\tgravity: Vector2D;\n}\n\nexport interface Physics2DResourceTypes {\n\tphysicsConfig: Physics2DConfig;\n}\n\n// ==================== Event Types ====================\n\n/**\n * Event emitted for each physics collision pair.\n *\n * Normal components are flattened (`normalX`/`normalY`) rather than nested\n * in a `Vector2D` to avoid a per-event allocation in the physics hot path.\n */\nexport interface Physics2DCollisionEvent {\n\tentityA: number;\n\tentityB: number;\n\t/** Unit normal X, pointing from A toward B */\n\tnormalX: number;\n\t/** Unit normal Y, pointing from A toward B */\n\tnormalY: number;\n\t/** Penetration depth (positive) */\n\tdepth: number;\n}\n\nexport interface Physics2DEventTypes {\n\tphysicsCollision: Physics2DCollisionEvent;\n}\n\n// ==================== Plugin Options ====================\n\nexport interface Physics2DPluginOptions<G extends string = 'physics2D', CG extends string = never> {\n\t/** World gravity vector (default: {x: 0, y: 0}) */\n\tgravity?: Vector2D;\n\t/** System group name (default: 'physics2D') */\n\tsystemGroup?: G;\n\t/** Additional group for the collision system only (default: none).\n\t * When set, the collision system belongs to both `systemGroup` and this group,\n\t * allowing independent enable/disable of collision detection. */\n\tcollisionSystemGroup?: CG;\n\t/** Priority for integration system (default: 1000) */\n\tintegrationPriority?: number;\n\t/** Priority for collision system (default: 900) */\n\tcollisionPriority?: number;\n\t/** Execution phase (default: 'fixedUpdate') */\n\tphase?: SystemPhase;\n}\n\n// ==================== Helper Functions ====================\n\nexport interface RigidBodyOptions {\n\tmass?: number;\n\tdrag?: number;\n\trestitution?: number;\n\tfriction?: number;\n\tgravityScale?: number;\n}\n\n/**\n * Create a rigid body + force component pair.\n * Static bodies automatically get mass=Infinity.\n */\nexport function createRigidBody(\n\ttype: BodyType,\n\toptions?: RigidBodyOptions,\n): { rigidBody: RigidBody; force: Vector2D } {\n\treturn {\n\t\trigidBody: {\n\t\t\ttype,\n\t\t\tmass: type === 'static' ? Infinity : (options?.mass ?? 1),\n\t\t\tdrag: options?.drag ?? 0,\n\t\t\trestitution: options?.restitution ?? 0,\n\t\t\tfriction: options?.friction ?? 0,\n\t\t\tgravityScale: options?.gravityScale ?? 1,\n\t\t},\n\t\tforce: { x: 0, y: 0 },\n\t};\n}\n\n/**\n * Create a force component with initial values.\n */\nexport function createForce(x: number, y: number): { force: Vector2D } {\n\treturn { force: { x, y } };\n}\n\n/**\n * Accumulate a force onto an entity's force component.\n */\nexport function applyForce(\n\tecs: { getComponent(id: number, name: 'force'): Vector2D | undefined },\n\tentityId: number,\n\tfx: number,\n\tfy: number,\n): void {\n\tconst force = ecs.getComponent(entityId, 'force');\n\tif (!force) return;\n\tforce.x += fx;\n\tforce.y += fy;\n}\n\n/**\n * Apply an instantaneous impulse: velocity += impulse / mass.\n */\nexport function applyImpulse(\n\tecs: {\n\t\tgetComponent(id: number, name: 'velocity'): Vector2D | undefined;\n\t\tgetComponent(id: number, name: 'rigidBody'): RigidBody | undefined;\n\t},\n\tentityId: number,\n\tix: number,\n\tiy: number,\n): void {\n\tconst velocity = ecs.getComponent(entityId, 'velocity');\n\tconst rigidBody = ecs.getComponent(entityId, 'rigidBody');\n\tif (!velocity || !rigidBody) return;\n\tif (rigidBody.mass === Infinity || rigidBody.mass === 0) return;\n\tvelocity.x += ix / rigidBody.mass;\n\tvelocity.y += iy / rigidBody.mass;\n}\n\n/**\n * Directly set an entity's velocity.\n */\nexport function setVelocity(\n\tecs: { getComponent(id: number, name: 'velocity'): Vector2D | undefined },\n\tentityId: number,\n\tvx: number,\n\tvy: number,\n): void {\n\tconst velocity = ecs.getComponent(entityId, 'velocity');\n\tif (!velocity) return;\n\tvelocity.x = vx;\n\tvelocity.y = vy;\n}\n\n// ==================== Internal: Collider Info ====================\n\ninterface Physics2DColliderInfo<L extends string = string> extends BaseColliderInfo<L> {\n\trigidBody: RigidBody;\n\tvelocity: Vector2D;\n}\n\n// ==================== Collision Response ====================\n\n/**\n * Module-level reusable physics collision event. Subscribers must consume\n * synchronously — same contract as the shared narrowphase Contact.\n */\nconst _physicsCollisionEvent: Physics2DCollisionEvent = {\n\tentityA: 0, entityB: 0, normalX: 0, normalY: 0, depth: 0,\n};\n\ninterface PhysicsEcsLike {\n\tgetComponent(id: number, name: 'localTransform'): { x: number; y: number } | undefined;\n\teventBus: { publish(event: 'physicsCollision', data: Physics2DCollisionEvent): void };\n\tmarkChanged(entityId: number, componentName: 'localTransform' | 'velocity'): void;\n}\n\n/**\n * Resolve a physics collision pair: position correction, impulse response, event.\n */\nfunction resolvePhysicsContact(\n\ta: Physics2DColliderInfo,\n\tb: Physics2DColliderInfo,\n\tcontact: Contact,\n\tecs: PhysicsEcsLike,\n): void {\n\tconst invMassA = (a.rigidBody.type === 'dynamic' && a.rigidBody.mass > 0 && a.rigidBody.mass !== Infinity)\n\t\t? 1 / a.rigidBody.mass\n\t\t: 0;\n\tconst invMassB = (b.rigidBody.type === 'dynamic' && b.rigidBody.mass > 0 && b.rigidBody.mass !== Infinity)\n\t\t? 1 / b.rigidBody.mass\n\t\t: 0;\n\tconst totalInvMass = invMassA + invMassB;\n\n\t// Position correction\n\tif (totalInvMass > 0) {\n\t\tconst correctionScale = contact.depth / totalInvMass;\n\n\t\tif (invMassA > 0) {\n\t\t\tconst ltA = ecs.getComponent(a.entityId, 'localTransform');\n\t\t\tif (!ltA) return;\n\t\t\tconst corrA = correctionScale * invMassA;\n\t\t\tltA.x -= corrA * contact.normalX;\n\t\t\tltA.y -= corrA * contact.normalY;\n\t\t\t// Sync cached position so subsequent pairs in this frame use corrected values\n\t\t\ta.x = ltA.x;\n\t\t\ta.y = ltA.y;\n\t\t\tecs.markChanged(a.entityId, 'localTransform');\n\t\t}\n\n\t\tif (invMassB > 0) {\n\t\t\tconst ltB = ecs.getComponent(b.entityId, 'localTransform');\n\t\t\tif (!ltB) return;\n\t\t\tconst corrB = correctionScale * invMassB;\n\t\t\tltB.x += corrB * contact.normalX;\n\t\t\tltB.y += corrB * contact.normalY;\n\t\t\tb.x = ltB.x;\n\t\t\tb.y = ltB.y;\n\t\t\tecs.markChanged(b.entityId, 'localTransform');\n\t\t}\n\n\t\t// Velocity response (impulse-based)\n\t\tconst relVelX = b.velocity.x - a.velocity.x;\n\t\tconst relVelY = b.velocity.y - a.velocity.y;\n\t\tconst velAlongNormal = relVelX * contact.normalX + relVelY * contact.normalY;\n\n\t\tif (velAlongNormal < 0) {\n\t\t\tconst restitution = Math.min(a.rigidBody.restitution, b.rigidBody.restitution);\n\t\t\tconst normalImpulse = -(1 + restitution) * velAlongNormal / totalInvMass;\n\n\t\t\ta.velocity.x -= normalImpulse * invMassA * contact.normalX;\n\t\t\ta.velocity.y -= normalImpulse * invMassA * contact.normalY;\n\t\t\tb.velocity.x += normalImpulse * invMassB * contact.normalX;\n\t\t\tb.velocity.y += normalImpulse * invMassB * contact.normalY;\n\n\t\t\t// Friction (tangential impulse)\n\t\t\tconst tangentX = relVelX - velAlongNormal * contact.normalX;\n\t\t\tconst tangentY = relVelY - velAlongNormal * contact.normalY;\n\t\t\tconst tangentSpeed = Math.sqrt(tangentX * tangentX + tangentY * tangentY);\n\n\t\t\tif (tangentSpeed > 1e-6) {\n\t\t\t\tconst tangentNX = tangentX / tangentSpeed;\n\t\t\t\tconst tangentNY = tangentY / tangentSpeed;\n\t\t\t\tconst friction = Math.sqrt(a.rigidBody.friction * b.rigidBody.friction);\n\t\t\t\tconst maxFrictionImpulse = friction * Math.abs(normalImpulse);\n\t\t\t\tconst tangentImpulse = Math.min(tangentSpeed / totalInvMass, maxFrictionImpulse);\n\n\t\t\t\ta.velocity.x += tangentImpulse * invMassA * tangentNX;\n\t\t\t\ta.velocity.y += tangentImpulse * invMassA * tangentNY;\n\t\t\t\tb.velocity.x -= tangentImpulse * invMassB * tangentNX;\n\t\t\t\tb.velocity.y -= tangentImpulse * invMassB * tangentNY;\n\t\t\t}\n\t\t}\n\n\t\tecs.markChanged(a.entityId, 'velocity');\n\t\tecs.markChanged(b.entityId, 'velocity');\n\t}\n\n\t_physicsCollisionEvent.entityA = a.entityId;\n\t_physicsCollisionEvent.entityB = b.entityId;\n\t_physicsCollisionEvent.normalX = contact.normalX;\n\t_physicsCollisionEvent.normalY = contact.normalY;\n\t_physicsCollisionEvent.depth = contact.depth;\n\tecs.eventBus.publish('physicsCollision', _physicsCollisionEvent);\n}\n\n// ==================== Plugin Factory ====================\n\n/**\n * Create a 2D physics plugin for ECSpresso.\n *\n * Provides:\n * - Semi-implicit Euler integration (gravity, forces, drag → velocity → position)\n * - Impulse-based collision response with restitution and friction\n * - physicsCollision events with contact normal and depth\n *\n * @example\n * ```typescript\n * const ecs = ECSpresso.create()\n * .withPlugin(createTransformPlugin())\n * .withPlugin(createPhysics2DPlugin({ gravity: { x: 0, y: 980 } }))\n * .withFixedTimestep(1/60)\n * .build();\n *\n * ecs.spawn({\n * ...createTransform(100, 200),\n * ...createRigidBody('dynamic', { mass: 1, restitution: 0.5 }),\n * velocity: { x: 0, y: 0 },\n * ...createAABBCollider(32, 32),\n * ...createCollisionLayer('player', ['ground']),\n * });\n * ```\n */\n\ntype Physics2DProvides<L extends string = never> = Physics2DOwnComponentTypes & CollisionComponentTypes<L>;\n\nexport function createPhysics2DPlugin<L extends string = never, G extends string = 'physics2D', CG extends string = never>(\n\toptions?: Physics2DPluginOptions<G, CG> & { layers?: LayerFactories<Record<L, readonly string[]>> },\n) {\n\tconst {\n\t\tgravity = { x: 0, y: 0 },\n\t\tsystemGroup = 'physics2D',\n\t\tcollisionSystemGroup,\n\t\tintegrationPriority = 1000,\n\t\tcollisionPriority = 900,\n\t\tphase = 'fixedUpdate',\n\t} = options ?? {};\n\n\treturn definePlugin('physics2D')\n\t\t.withComponentTypes<Physics2DProvides<L>>()\n\t\t.withEventTypes<Physics2DEventTypes>()\n\t\t.withResourceTypes<Physics2DResourceTypes>()\n\t\t.withLabels<'physics2D-integration' | 'physics2D-collision'>()\n\t\t.withGroups<G | CG>()\n\t\t.requires<TransformWorldConfig>()\n\t\t.install((world) => {\n\t\t\t// rigidBody requires velocity and force — auto-add with zero defaults\n\t\t\tworld.registerRequired('rigidBody', 'velocity', () => ({ x: 0, y: 0 }));\n\t\t\tworld.registerRequired('rigidBody', 'force', () => ({ x: 0, y: 0 }));\n\n\t\t\tworld.addResource('physicsConfig', { gravity: { x: gravity.x, y: gravity.y } });\n\n\t\t\t// ==================== Integration System ====================\n\n\t\t\tworld\n\t\t\t\t.addSystem('physics2D-integration')\n\t\t\t\t.setPriority(integrationPriority)\n\t\t\t\t.inPhase(phase)\n\t\t\t\t.inGroup(systemGroup)\n\t\t\t\t.addQuery('bodies', {\n\t\t\t\t\twith: ['localTransform', 'velocity', 'rigidBody', 'force'],\n\t\t\t\t})\n\t\t\t\t.setProcess(({ queries, dt, ecs }) => {\n\t\t\t\t\tconst { gravity: g } = ecs.getResource('physicsConfig');\n\t\t\t\t\tconst gx = g.x;\n\t\t\t\t\tconst gy = g.y;\n\n\t\t\t\t\t// TODO(perf): no early-out for \"sleeping\" dynamic bodies — a packed\n\t\t\t\t\t// pile of resting entities still runs gravity/drag/force-clear/\n\t\t\t\t\t// markChanged every step. A sleep flag on RigidBody that latches\n\t\t\t\t\t// after N frames of near-zero velocity (and clears on impulse or\n\t\t\t\t\t// applied force) would let most of a stabilized scene skip the\n\t\t\t\t\t// full per-entity body of this loop. Keep in sync with physics3D.\n\t\t\t\t\tfor (const entity of queries.bodies) {\n\t\t\t\t\t\tconst { localTransform, velocity, rigidBody, force } = entity.components;\n\n\t\t\t\t\t\t// Static bodies: skip entirely\n\t\t\t\t\t\tif (rigidBody.type === 'static') continue;\n\n\t\t\t\t\t\t// Dynamic bodies: apply gravity, forces, drag\n\t\t\t\t\t\tif (rigidBody.type === 'dynamic') {\n\t\t\t\t\t\t\t// 1. Gravity\n\t\t\t\t\t\t\tconst gsdt = rigidBody.gravityScale * dt;\n\t\t\t\t\t\t\tvelocity.x += gx * gsdt;\n\t\t\t\t\t\t\tvelocity.y += gy * gsdt;\n\n\t\t\t\t\t\t\t// 2. Forces (F = ma → a = F/m)\n\t\t\t\t\t\t\tconst mass = rigidBody.mass;\n\t\t\t\t\t\t\tif (mass > 0 && mass !== Infinity) {\n\t\t\t\t\t\t\t\tconst invMassDt = dt / mass;\n\t\t\t\t\t\t\t\tvelocity.x += force.x * invMassDt;\n\t\t\t\t\t\t\t\tvelocity.y += force.y * invMassDt;\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t// 3. Drag\n\t\t\t\t\t\t\tif (rigidBody.drag > 0) {\n\t\t\t\t\t\t\t\tconst damping = Math.max(0, 1 - rigidBody.drag * dt);\n\t\t\t\t\t\t\t\tvelocity.x *= damping;\n\t\t\t\t\t\t\t\tvelocity.y *= damping;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\t// Both dynamic and kinematic: integrate position\n\t\t\t\t\t\tlocalTransform.x += velocity.x * dt;\n\t\t\t\t\t\tlocalTransform.y += velocity.y * dt;\n\n\t\t\t\t\t\t// Clear accumulated forces\n\t\t\t\t\t\tforce.x = 0;\n\t\t\t\t\t\tforce.y = 0;\n\n\t\t\t\t\t\tecs.markChanged(entity.id, 'localTransform');\n\t\t\t\t\t}\n\t\t\t\t});\n\n\t\t\t// ==================== Collision System ====================\n\n\t\t\tconst collisionSystem = world\n\t\t\t\t.addSystem('physics2D-collision')\n\t\t\t\t.setPriority(collisionPriority)\n\t\t\t\t.inPhase(phase)\n\t\t\t\t.inGroup(systemGroup);\n\n\t\t\tif (collisionSystemGroup) {\n\t\t\t\tcollisionSystem.inGroup(collisionSystemGroup);\n\t\t\t}\n\n\t\t\t// Grow-only pool of Physics2DColliderInfo slots reused across frames.\n\t\t\t// Steady-state: zero allocations per frame once the pool is warm.\n\t\t\tconst colliderPool: Physics2DColliderInfo<L>[] = [];\n\t\t\t// Reusable entityId → collider lookup for the broadphase path.\n\t\t\tconst broadphaseMap = new Map<number, Physics2DColliderInfo<L>>();\n\t\t\t// Cached spatial index reference (resolved once on first frame).\n\t\t\tlet cachedSI: SpatialIndex | undefined;\n\t\t\tlet siResolved = false;\n\n\t\t\tcollisionSystem\n\t\t\t\t.addQuery('collidables', {\n\t\t\t\t\twith: ['localTransform', 'rigidBody', 'velocity', '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\t// TODO(perf): collider shape is discovered via two ecs.getComponent\n\t\t\t\t\t// calls per entity per frame because the query can't express\n\t\t\t\t\t// \"aabbCollider OR circleCollider\". Splitting into two queries\n\t\t\t\t\t// (aabb-bearing, circle-bearing) would eliminate these lookups at\n\t\t\t\t\t// the cost of two pool-fill passes. Keep in sync with physics3D.\n\t\t\t\t\tfor (const entity of queries.collidables) {\n\t\t\t\t\t\tconst { localTransform, rigidBody, velocity, collisionLayer } = entity.components;\n\t\t\t\t\t\tconst aabb = ecs.getComponent(entity.id, 'aabbCollider');\n\t\t\t\t\t\tconst circle = aabb ? undefined : 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: localTransform.x,\n\t\t\t\t\t\t\t\ty: localTransform.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\trigidBody,\n\t\t\t\t\t\t\t\tvelocity,\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} else {\n\t\t\t\t\t\t\tslot.rigidBody = rigidBody;\n\t\t\t\t\t\t\tslot.velocity = velocity;\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, localTransform.x, localTransform.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\tif (!siResolved) {\n\t\t\t\t\t\tcachedSI = ecs.tryGetResource<SpatialIndex>('spatialIndex');\n\t\t\t\t\t\tsiResolved = true;\n\t\t\t\t\t}\n\t\t\t\t\tdetectCollisions(colliderPool, count, broadphaseMap, cachedSI, resolvePhysicsContact, ecs);\n\t\t\t\t});\n\t\t});\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\t// TODO(perf): mirrors narrowphase3D — dense grids add every candidate\n\t\t// (including `a` itself and lower-ID entities) to the set before the\n\t\t// filter below discards ~half of them. Emitting only pairs with larger\n\t\t// IDs at query time would remove the post-hoc filter. Keep in sync with\n\t\t// whatever fix lands in narrowphase3D.\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
|
"/**\n * Flocking Plugin for ECSpresso\n *\n * Classic boid simulation — separation, alignment, cohesion. Produces\n * emergent group movement from simple per-entity steering forces.\n *\n * Composes with the physics2D plugin: flocking computes steering forces\n * and feeds them through `applyForce()`. Physics integration handles\n * velocity and position updates.\n *\n * Requires the spatial-index plugin for efficient neighbor queries.\n * Entities must have a `circleCollider` (or `aabbCollider`) to appear\n * in spatial index queries.\n */\n\nimport { definePlugin, type BasePluginOptions } from 'ecspresso';\nimport type { WorldConfigFrom } from 'ecspresso';\nimport type { TransformWorldConfig } from '../spatial/transform';\nimport type { Physics2DOwnComponentTypes } from '../physics/physics2D';\nimport { applyForce } from '../physics/physics2D';\nimport type { SpatialIndexResourceTypes } from '../spatial/spatial-index';\n\n// ==================== Component Types ====================\n\n/**\n * Configures flocking behavior for a boid entity.\n *\n * Entities with this component must also have:\n * - `localTransform` + `worldTransform` (transform plugin)\n * - `velocity` + `force` + `rigidBody` (physics2D plugin)\n * - `circleCollider` with radius >= perceptionRadius (for spatial index queries)\n */\nexport interface FlockingAgent {\n\t/** Radius within which neighbors are detected */\n\tperceptionRadius: number;\n\t/** Separation weight — steer away from nearby neighbors (default: 1.5) */\n\tseparationWeight: number;\n\t/** Alignment weight — match average heading of neighbors (default: 1.0) */\n\talignmentWeight: number;\n\t/** Cohesion weight — steer toward average position of neighbors (default: 1.0) */\n\tcohesionWeight: number;\n\t/** Maximum steering force magnitude per frame */\n\tmaxForce: number;\n\t/** Maximum velocity magnitude (hard speed cap) */\n\tmaxSpeed: number;\n\t/** Flock group ID for independent flocks (default: 0) */\n\tflockGroup: number;\n}\n\n/**\n * Component types provided by the flocking plugin.\n */\nexport interface FlockingComponentTypes {\n\tflockingAgent: FlockingAgent;\n}\n\n// ==================== WorldConfig ====================\n\n/**\n * WorldConfig representing the flocking plugin's provided types.\n */\nexport type FlockingWorldConfig = WorldConfigFrom<FlockingComponentTypes>;\n\n// ==================== Plugin Options ====================\n\nexport interface FlockingPluginOptions<G extends string = 'ai'> extends BasePluginOptions<G> {\n\t/** Priority for the heading/speed-clamp system (default: 200) */\n\theadingPriority?: number;\n}\n\n// ==================== Helper Functions ====================\n\n/**\n * Create a flockingAgent component with sensible defaults.\n *\n * Entities must also have a `circleCollider` with radius >= perceptionRadius\n * for the spatial index to find them as neighbors.\n *\n * @param options Partial overrides for flocking agent fields\n * @returns Component object suitable for spreading into spawn()\n *\n * @example\n * ```typescript\n * ecs.spawn({\n * ...createFlockingAgent({ perceptionRadius: 80, maxSpeed: 150 }),\n * ...createRigidBody('dynamic', { mass: 1, drag: 1, gravityScale: 0 }),\n * ...createCircleCollider(80),\n * ...createGraphicsComponents(boidGraphics, { x: 100, y: 200 }),\n * });\n * ```\n */\nexport function createFlockingAgent(\n\toptions?: Partial<FlockingAgent>,\n): Pick<FlockingComponentTypes, 'flockingAgent'> {\n\treturn {\n\t\tflockingAgent: {\n\t\t\tperceptionRadius: options?.perceptionRadius ?? 100,\n\t\t\tseparationWeight: options?.separationWeight ?? 1.5,\n\t\t\talignmentWeight: options?.alignmentWeight ?? 1.0,\n\t\t\tcohesionWeight: options?.cohesionWeight ?? 1.0,\n\t\t\tmaxForce: options?.maxForce ?? 400,\n\t\t\tmaxSpeed: options?.maxSpeed ?? 200,\n\t\t\tflockGroup: options?.flockGroup ?? 0,\n\t\t},\n\t};\n}\n\n// ==================== Plugin Factory ====================\n\n// Module-scoped reusable set to reduce GC pressure in neighbor queries\nconst _neighborSet = new Set<number>();\n\nconst SPEED_EPSILON = 0.01;\n\n/**\n * Create a flocking plugin for ECSpresso.\n *\n * Installs two systems:\n * - `flocking-forces` — computes separation/alignment/cohesion and applies via applyForce()\n * - `flocking-heading` — clamps speed to maxSpeed and orients rotation to match velocity\n *\n * Requires the transform, physics2D, and spatial-index plugins to be installed.\n *\n * @example\n * ```typescript\n * const ecs = ECSpresso.create()\n * .withPlugin(createRenderer2DPlugin({ background: '#0a0a2e' }))\n * .withPlugin(createPhysics2DPlugin())\n * .withPlugin(createSpatialIndexPlugin())\n * .withPlugin(createFlockingPlugin())\n * .build();\n * ```\n */\nexport function createFlockingPlugin<G extends string = 'ai'>(\n\toptions?: FlockingPluginOptions<G>,\n) {\n\tconst {\n\t\tsystemGroup = 'ai',\n\t\tpriority = 500,\n\t\tphase = 'update',\n\t\theadingPriority = 200,\n\t} = options ?? {};\n\n\treturn definePlugin('flocking')\n\t\t.withComponentTypes<FlockingComponentTypes>()\n\t\t.withLabels<'flocking-forces' | 'flocking-heading'>()\n\t\t.withGroups<G>()\n\t\t.requires<\n\t\t\tTransformWorldConfig &\n\t\t\tWorldConfigFrom<Pick<Physics2DOwnComponentTypes, 'velocity' | 'force'>> &\n\t\t\tWorldConfigFrom<{}, {}, SpatialIndexResourceTypes>\n\t\t>()\n\t\t.install((world) => {\n\t\t\t// --- System 1: Compute and apply flocking forces ---\n\t\t\tworld\n\t\t\t\t.addSystem('flocking-forces')\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('boids', {\n\t\t\t\t\twith: ['flockingAgent', 'worldTransform', 'velocity', 'force'],\n\t\t\t\t})\n\t\t\t\t.setProcess(({ queries, ecs }) => {\n\t\t\t\t\tconst spatialIndex = ecs.getResource('spatialIndex');\n\n\t\t\t\t\tfor (const entity of queries.boids) {\n\t\t\t\t\t\tconst { flockingAgent, worldTransform, velocity } = entity.components;\n\t\t\t\t\t\tconst { perceptionRadius, separationWeight, alignmentWeight, cohesionWeight, maxForce, flockGroup } = flockingAgent;\n\n\t\t\t\t\t\t// Query neighbors via spatial index\n\t\t\t\t\t\t_neighborSet.clear();\n\t\t\t\t\t\tspatialIndex.queryRadiusInto(worldTransform.x, worldTransform.y, perceptionRadius, _neighborSet);\n\n\t\t\t\t\t\t// Accumulate steering forces — all inline scalars, no allocations\n\t\t\t\t\t\tlet sepX = 0, sepY = 0, sepCount = 0;\n\t\t\t\t\t\tlet alignX = 0, alignY = 0, alignCount = 0;\n\t\t\t\t\t\tlet cohX = 0, cohY = 0, cohCount = 0;\n\n\t\t\t\t\t\tconst separationRadius = perceptionRadius * 0.5;\n\t\t\t\t\t\tconst separationRadiusSq = separationRadius * separationRadius;\n\n\t\t\t\t\t\tfor (const neighborId of _neighborSet) {\n\t\t\t\t\t\t\tif (neighborId === entity.id) continue;\n\n\t\t\t\t\t\t\tconst neighborAgent = ecs.getComponent(neighborId, 'flockingAgent');\n\t\t\t\t\t\t\tif (!neighborAgent) continue;\n\t\t\t\t\t\t\tif (neighborAgent.flockGroup !== flockGroup) continue;\n\n\t\t\t\t\t\t\tconst neighborTransform = ecs.getComponent(neighborId, 'worldTransform');\n\t\t\t\t\t\t\tif (!neighborTransform) continue;\n\n\t\t\t\t\t\t\tconst dx = worldTransform.x - neighborTransform.x;\n\t\t\t\t\t\t\tconst dy = worldTransform.y - neighborTransform.y;\n\t\t\t\t\t\t\tconst distSq = dx * dx + dy * dy;\n\n\t\t\t\t\t\t\t// Separation — closer neighbors push harder\n\t\t\t\t\t\t\tif (distSq > 0 && distSq < separationRadiusSq) {\n\t\t\t\t\t\t\t\tconst dist = Math.sqrt(distSq);\n\t\t\t\t\t\t\t\tsepX += dx / dist;\n\t\t\t\t\t\t\t\tsepY += dy / dist;\n\t\t\t\t\t\t\t\tsepCount++;\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t// Alignment — average velocity of neighbors\n\t\t\t\t\t\t\tconst neighborVel = ecs.getComponent(neighborId, 'velocity');\n\t\t\t\t\t\t\tif (neighborVel) {\n\t\t\t\t\t\t\t\talignX += neighborVel.x;\n\t\t\t\t\t\t\t\talignY += neighborVel.y;\n\t\t\t\t\t\t\t\talignCount++;\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t// Cohesion — average position of neighbors\n\t\t\t\t\t\t\tcohX += neighborTransform.x;\n\t\t\t\t\t\t\tcohY += neighborTransform.y;\n\t\t\t\t\t\t\tcohCount++;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tlet totalFx = 0, totalFy = 0;\n\n\t\t\t\t\t\t// Separation: steer away from crowded neighbors\n\t\t\t\t\t\tif (sepCount > 0) {\n\t\t\t\t\t\t\ttotalFx += (sepX / sepCount) * separationWeight;\n\t\t\t\t\t\t\ttotalFy += (sepY / sepCount) * separationWeight;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\t// Alignment: steer toward average heading\n\t\t\t\t\t\tif (alignCount > 0) {\n\t\t\t\t\t\t\tconst avgVx = alignX / alignCount;\n\t\t\t\t\t\t\tconst avgVy = alignY / alignCount;\n\t\t\t\t\t\t\t// Desired = average velocity - current velocity\n\t\t\t\t\t\t\ttotalFx += (avgVx - velocity.x) * alignmentWeight;\n\t\t\t\t\t\t\ttotalFy += (avgVy - velocity.y) * alignmentWeight;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\t// Cohesion: steer toward average position\n\t\t\t\t\t\tif (cohCount > 0) {\n\t\t\t\t\t\t\tconst avgPx = cohX / cohCount;\n\t\t\t\t\t\t\tconst avgPy = cohY / cohCount;\n\t\t\t\t\t\t\t// Desired = direction to center of mass - current velocity\n\t\t\t\t\t\t\ttotalFx += (avgPx - worldTransform.x - velocity.x) * cohesionWeight;\n\t\t\t\t\t\t\ttotalFy += (avgPy - worldTransform.y - velocity.y) * cohesionWeight;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\t// Clamp total steering force to maxForce\n\t\t\t\t\t\tconst forceMagSq = totalFx * totalFx + totalFy * totalFy;\n\t\t\t\t\t\tif (forceMagSq > maxForce * maxForce) {\n\t\t\t\t\t\t\tconst forceMag = Math.sqrt(forceMagSq);\n\t\t\t\t\t\t\ttotalFx = (totalFx / forceMag) * maxForce;\n\t\t\t\t\t\t\ttotalFy = (totalFy / forceMag) * maxForce;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tapplyForce(ecs, entity.id, totalFx, totalFy);\n\t\t\t\t\t}\n\t\t\t\t});\n\n\t\t\t// --- System 2: Clamp speed and orient heading from velocity ---\n\t\t\tworld\n\t\t\t\t.addSystem('flocking-heading')\n\t\t\t\t.setPriority(headingPriority)\n\t\t\t\t.inPhase(phase)\n\t\t\t\t.inGroup(systemGroup)\n\t\t\t\t.addQuery('boids', {\n\t\t\t\t\twith: ['flockingAgent', 'velocity', 'localTransform'],\n\t\t\t\t})\n\t\t\t\t.setProcess(({ queries, ecs }) => {\n\t\t\t\t\tfor (const entity of queries.boids) {\n\t\t\t\t\t\tconst { flockingAgent, velocity, localTransform } = entity.components;\n\t\t\t\t\t\tconst { maxSpeed } = flockingAgent;\n\n\t\t\t\t\t\t// Clamp velocity to maxSpeed\n\t\t\t\t\t\tconst speedSq = velocity.x * velocity.x + velocity.y * velocity.y;\n\t\t\t\t\t\tif (speedSq > maxSpeed * maxSpeed) {\n\t\t\t\t\t\t\tconst speed = Math.sqrt(speedSq);\n\t\t\t\t\t\t\tvelocity.x = (velocity.x / speed) * maxSpeed;\n\t\t\t\t\t\t\tvelocity.y = (velocity.y / speed) * maxSpeed;\n\t\t\t\t\t\t\tecs.markChanged(entity.id, 'velocity');\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\t// Orient rotation to match velocity heading\n\t\t\t\t\t\tif (speedSq > SPEED_EPSILON * SPEED_EPSILON) {\n\t\t\t\t\t\t\tconst heading = Math.atan2(velocity.y, velocity.x);\n\t\t\t\t\t\t\tif (heading !== localTransform.rotation) {\n\t\t\t\t\t\t\t\tlocalTransform.rotation = heading;\n\t\t\t\t\t\t\t\tecs.markChanged(entity.id, 'localTransform');\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t});\n\t\t});\n}\n"
|
|
8
8
|
],
|
|
9
|
-
"mappings": "mdAWA,uBAAS,mBCsBT,IAAM,EAA0B,CAAE,QAAS,EAAG,QAAS,EAAG,MAAO,CAAE,EAKtD,EAAa,EAsCnB,SAAS,CAAsC,CACrD,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACU,CAKV,GAJA,EAAK,SAAW,EAChB,EAAK,MAAQ,EACb,EAAK,aAAe,EAEhB,EAOH,OANA,EAAK,EAAI,GAAK,EAAK,SAAW,GAC9B,EAAK,EAAI,GAA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AAW,EAC1B,EAAI,YAAY,EAAO,GAAI,gBAAgB,IAI9C,EACF",
|
|
10
|
+
"debugId": "86EF73C7B0F16E1564756E2164756E21",
|
|
11
11
|
"names": []
|
|
12
12
|
}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
var
|
|
1
|
+
var _=Object.defineProperty;var k=(z)=>z;function C(z,J){this[z]=k.bind(null,J)}var h=(z,J)=>{for(var Z in J)_(z,Z,{get:J[Z],enumerable:!0,configurable:!0,set:C.bind(J,Z)})};var d=(z,J)=>()=>(z&&(J=z(z=0)),J);var b=((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 p}from"ecspresso";var M={normalX:0,normalY:0,depth:0},S=0;function A(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 X(z,J,Z,N,V,O,$,Q,U){let T=V-z,G=O-J,j=Z+$-Math.abs(T),F=N+Q-Math.abs(G);if(j<=0||F<=0)return!1;if(j<F)return U.normalX=T>=0?1:-1,U.normalY=0,U.depth=j,!0;return U.normalX=0,U.normalY=G>=0?1:-1,U.depth=F,!0}function Y(z,J,Z,N,V,O,$){let Q=N-z,U=V-J,T=Q*Q+U*U,G=Z+O;if(T>=G*G)return!1;let j=Math.sqrt(T);if(j===0)return $.normalX=1,$.normalY=0,$.depth=G,!0;return $.normalX=Q/j,$.normalY=U/j,$.depth=G-j,!0}function R(z,J,Z,N,V,O,$,Q){let U=Math.max(z-Z,Math.min(V,z+Z)),T=Math.max(J-N,Math.min(O,J+N)),G=V-U,j=O-T,F=G*G+j*j;if(F>=$*$)return!1;if(F===0){let g=V-(z-Z),H=z+Z-V,L=O-(J-N),K=J+N-O,P=Math.min(g,H,L,K);if(P===H)return Q.normalX=1,Q.normalY=0,Q.depth=H+$,!0;if(P===g)return Q.normalX=-1,Q.normalY=0,Q.depth=g+$,!0;if(P===K)return Q.normalX=0,Q.normalY=1,Q.depth=K+$,!0;return Q.normalX=0,Q.normalY=-1,Q.depth=L+$,!0}let q=Math.sqrt(F);return Q.normalX=G/q,Q.normalY=j/q,Q.depth=$-q,!0}function I(z,J,Z){if(z.shape===0&&J.shape===0)return X(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 Y(z.x,z.y,z.radius,J.x,J.y,J.radius,Z);if(z.shape===0&&J.shape===1)return R(z.x,z.y,z.halfWidth,z.halfHeight,J.x,J.y,J.radius,Z);if(!R(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 W=new Set,E=!1,w=50;function B(z,J,Z,N,V,O){if(N)x(z,J,Z,N,V,O);else v(z,J,V,O)}function v(z,J,Z,N){if(!E&&J>=w)E=!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(!I(O,Q,M))continue;Z(O,Q,M,N)}}}function x(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 U=Q.shape===0?Q.halfWidth:Q.radius,T=Q.shape===0?Q.halfHeight:Q.radius;W.clear(),N.queryRectInto(Q.x-U,Q.y-T,Q.x+U,Q.y+T,W);for(let G of W){if(G<=Q.entityId)continue;let j=Z.get(G);if(!j)continue;if(!Q.collidesWith.includes(j.layer)&&!j.collidesWith.includes(Q.layer))continue;if(!I(Q,j,M))continue;V(Q,j,M,O)}}}function l(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 c(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 y(z,J){return{collisionLayer:{layer:z,collidesWith:J}}}function i(z){let J={};for(let Z of Object.keys(z)){let N=z[Z];J[Z]=()=>y(Z,N)}return J}function m(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 t(z){let J=new Map,Z=new Set;for(let N of Object.keys(z))m(N),Z.add(N);for(let N of Object.keys(z)){let[V,O]=m(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)}}var D={entityA:0,entityB:0,layerA:"",layerB:"",normalX:0,normalY:0,depth:0};function f(z,J,Z,N){D.entityA=z.entityId,D.entityB=J.entityId,D.layerA=z.layer,D.layerB=J.layer,D.normalX=Z.normalX,D.normalY=Z.normalY,D.depth=Z.depth,N.publish("collision",D)}function a(z){let{systemGroup:J="physics",priority:Z=0,phase:N="postUpdate"}=z;return p("collision").withComponentTypes().withEventTypes().withLabels().withGroups().requires().install((V)=>{let O=[],$=new Map,Q,U=!1;V.addSystem("collision-detection").setPriority(Z).inPhase(N).inGroup(J).addQuery("collidables",{with:["worldTransform","collisionLayer"]}).setProcess(({queries:T,ecs:G})=>{let j=0;for(let F of T.collidables){let{worldTransform:q,collisionLayer:g}=F.components,H=G.getComponent(F.id,"aabbCollider"),L=H?void 0:G.getComponent(F.id,"circleCollider");if(!H&&!L)continue;let K=O[j];if(!K)K={entityId:F.id,x:q.x,y:q.y,layer:g.layer,collidesWith:g.collidesWith,shape:S,halfWidth:0,halfHeight:0,radius:0},O[j]=K;if(!A(K,F.id,q.x,q.y,g.layer,g.collidesWith,H,L))continue;j++}if(!U)Q=G.tryGetResource("spatialIndex"),U=!0;B(O,j,$,Q,f,G.eventBus)})})}export{i as defineCollisionLayers,a as createCollisionPlugin,t as createCollisionPairHandler,y as createCollisionLayer,c as createCircleCollider,l as createAABBCollider};
|
|
2
2
|
|
|
3
|
-
//# debugId=
|
|
3
|
+
//# debugId=399824DE1BC8F1D064756E2164756E21
|
|
4
4
|
//# sourceMappingURL=collision.js.map
|
|
@@ -2,10 +2,10 @@
|
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../src/plugins/physics/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 BasePluginOptions } from 'ecspresso';\nimport type { TransformWorldConfig } from '../spatial/transform';\nimport { fillBaseColliderInfo, detectCollisions, AABB_SHAPE, type Contact, type BaseColliderInfo } from '../../utils/narrowphase';\nimport type { SpatialIndex } from '../../utils/spatial-hash';\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\n/**\n * Module-level reusable collision event. Subscribers must consume\n * synchronously — same contract as the shared narrowphase Contact.\n */\nconst _collisionEvent: CollisionEvent<string> = {\n\tentityA: 0, entityB: 0, layerA: '', layerB: '',\n\tnormalX: 0, normalY: 0, depth: 0,\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\t_collisionEvent.entityA = a.entityId;\n\t_collisionEvent.entityB = b.entityId;\n\t_collisionEvent.layerA = a.layer;\n\t_collisionEvent.layerB = b.layer;\n\t_collisionEvent.normalX = contact.normalX;\n\t_collisionEvent.normalY = contact.normalY;\n\t_collisionEvent.depth = contact.depth;\n\teventBus.publish('collision', _collisionEvent as CollisionEvent<L>);\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\t\t\t// Cached spatial index reference (resolved once on first frame).\n\t\t\tlet cachedSI: SpatialIndex | undefined;\n\t\t\tlet siResolved = false;\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 = aabb ? undefined : 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\tif (!siResolved) {\n\t\t\t\t\t\tcachedSI = ecs.tryGetResource<SpatialIndex>('spatialIndex');\n\t\t\t\t\t\tsiResolved = true;\n\t\t\t\t\t}\n\t\t\t\t\tdetectCollisions(colliderPool, count, broadphaseMap, cachedSI, 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"
|
|
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 '../spatial/transform';\nimport { fillBaseColliderInfo, detectCollisions, AABB_SHAPE, type Contact, type BaseColliderInfo } from '../../utils/narrowphase';\nimport type { SpatialIndex } from '../../utils/spatial-hash';\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\n/**\n * Module-level reusable collision event. Subscribers must consume\n * synchronously — same contract as the shared narrowphase Contact.\n */\nconst _collisionEvent: CollisionEvent<string> = {\n\tentityA: 0, entityB: 0, layerA: '', layerB: '',\n\tnormalX: 0, normalY: 0, depth: 0,\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\t_collisionEvent.entityA = a.entityId;\n\t_collisionEvent.entityB = b.entityId;\n\t_collisionEvent.layerA = a.layer;\n\t_collisionEvent.layerB = b.layer;\n\t_collisionEvent.normalX = contact.normalX;\n\t_collisionEvent.normalY = contact.normalY;\n\t_collisionEvent.depth = contact.depth;\n\teventBus.publish('collision', _collisionEvent as CollisionEvent<L>);\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\t\t\t// Cached spatial index reference (resolved once on first frame).\n\t\t\tlet cachedSI: SpatialIndex | undefined;\n\t\t\tlet siResolved = false;\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\t// TODO(perf): collider shape is discovered via two ecs.getComponent\n\t\t\t\t\t// calls per entity per frame because the query can't express\n\t\t\t\t\t// \"aabbCollider OR circleCollider\". Splitting into two queries\n\t\t\t\t\t// (aabb-bearing, circle-bearing) would eliminate these lookups at\n\t\t\t\t\t// the cost of two pool-fill passes. Keep in sync with collision3D.\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 = aabb ? undefined : 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\tif (!siResolved) {\n\t\t\t\t\t\tcachedSI = ecs.tryGetResource<SpatialIndex>('spatialIndex');\n\t\t\t\t\t\tsiResolved = true;\n\t\t\t\t\t}\n\t\t\t\t\tdetectCollisions(colliderPool, count, broadphaseMap, cachedSI, 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\t// TODO(perf): mirrors narrowphase3D — dense grids add every candidate\n\t\t// (including `a` itself and lower-ID entities) to the set before the\n\t\t// filter below discards ~half of them. Emitting only pairs with larger\n\t\t// IDs at query time would remove the post-hoc filter. Keep in sync with\n\t\t// whatever fix lands in narrowphase3D.\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": "4cAQA,uBAAS,kBCyBT,IAAM,EAA0B,CAAE,QAAS,EAAG,QAAS,EAAG,MAAO,CAAE,EAKtD,EAAa,EAsCnB,SAAS,CAAsC,CACrD,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACU,CAKV,GAJA,EAAK,SAAW,EAChB,EAAK,MAAQ,EACb,EAAK,aAAe,EAEhB,EAOH,OANA,EAAK,EAAI,GAAK,EAAK,SAAW,GAC9B,EAAK,EAAI,GAAK,EAAK,SAAW,GAC9B,EAAK,MAvDmB,EAwDxB,EAAK,UAAY,EAAK,MAAQ,EAC9B,EAAK,WAAa,EAAK,OAAS,EAChC,EAAK,OAAS,EACP,GAGR,GAAI,EAOH,OANA,EAAK,EAAI,GAAK,EAAO,SAAW,GAChC,EAAK,EAAI,GAAK,EAAO,SAAW,GAChC,EAAK,MAhEqB,EAiE1B,EAAK,UAAY,EACjB,EAAK,WAAa,EAClB,EAAK,OAAS,EAAO,OACd,GAGR,MAAO,GAsBD,SAAS,CAAiB,CAChC,EAAY,EAAY,EAAa,EACrC,EAAY,EAAY,EAAa,EACrC,EACU,CACV,IAAM,EAAK,EAAK,EACV,EAAK,EAAK,EACV,EAAY,EAAM,EAAO,KAAK,IAAI,CAAE,EACpC,EAAY,EAAM,EAAO,KAAK,IAAI,CAAE,EAE1C,GAAI,GAAY,GAAK,GAAY,EAAG,MAAO,GAE3C,GAAI,EA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vB,GAAI,CAAC,EACJ,EACA,EAAO,GAAI,EAAe,EAAG,EAAe,EAC5C,EAAe,MAAO,EAAe,aACrC,EAAM,CACP,EAAG,SAEH,IAGD,GAAI,CAAC,EACJ,EAAW,EAAI,eAA6B,cAAc,EAC1D,EAAa,GAEd,EAAiB,EAAc,EAAO,EAAe,EAAU,EAAwB,EAAI,QAAQ,EACnG,EACF",
|
|
9
|
+
"debugId": "399824DE1BC8F1D064756E2164756E21",
|
|
10
10
|
"names": []
|
|
11
11
|
}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
var l=Object.defineProperty;var r=(J)=>J;function s(J,Q){this[J]=r.bind(null,Q)}var qJ=(J,Q)=>{for(var N in Q)l(J,N,{get:Q[N],enumerable:!0,configurable:!0,set:s.bind(Q,N)})};var TJ=(J,Q)=>()=>(J&&(Q=J(J=0)),Q);var WJ=((J)=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(J,{get:(Q,N)=>(typeof require<"u"?require:Q)[N]}):J)(function(J){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+J+'" is not supported')});import{definePlugin as JJ}from"ecspresso";var A={normalX:0,normalY:0,depth:0},w=0;function v(J,Q,N,O,j,G,V,$){if(J.entityId=Q,J.layer=j,J.collidesWith=G,V)return J.x=N+(V.offsetX??0),J.y=O+(V.offsetY??0),J.shape=0,J.halfWidth=V.width/2,J.halfHeight=V.height/2,J.radius=0,!0;if($)return J.x=N+($.offsetX??0),J.y=O+($.offsetY??0),J.shape=1,J.halfWidth=0,J.halfHeight=0,J.radius=$.radius,!0;return!1}function i(J,Q,N,O,j,G,V,$,F){let T=j-J,K=G-Q,q=N+V-Math.abs(T),U=O+$-Math.abs(K);if(q<=0||U<=0)return!1;if(q<U)return F.normalX=T>=0?1:-1,F.normalY=0,F.depth=q,!0;return F.normalX=0,F.normalY=K>=0?1:-1,F.depth=U,!0}function t(J,Q,N,O,j,G,V){let $=O-J,F=j-Q,T=$*$+F*F,K=N+G;if(T>=K*K)return!1;let q=Math.sqrt(T);if(q===0)return V.normalX=1,V.normalY=0,V.depth=K,!0;return V.normalX=$/q,V.normalY=F/q,V.depth=K-q,!0}function Y(J,Q,N,O,j,G,V,$){let F=Math.max(J-N,Math.min(j,J+N)),T=Math.max(Q-O,Math.min(G,Q+O)),K=j-F,q=G-T,U=K*K+q*q;if(U>=V*V)return!1;if(U===0){let W=j-(J-N),H=J+N-j,P=G-(Q-O),z=Q+O-G,M=Math.min(W,H,P,z);if(M===H)return $.normalX=1,$.normalY=0,$.depth=H+V,!0;if(M===W)return $.normalX=-1,$.normalY=0,$.depth=W+V,!0;if(M===z)return $.normalX=0,$.normalY=1,$.depth=z+V,!0;return $.normalX=0,$.normalY=-1,$.depth=P+V,!0}let L=Math.sqrt(U);return $.normalX=K/L,$.normalY=q/L,$.depth=V-L,!0}function x(J,Q,N){if(J.shape===0&&Q.shape===0)return i(J.x,J.y,J.halfWidth,J.halfHeight,Q.x,Q.y,Q.halfWidth,Q.halfHeight,N);if(J.shape===1&&Q.shape===1)return t(J.x,J.y,J.radius,Q.x,Q.y,Q.radius,N);if(J.shape===0&&Q.shape===1)return Y(J.x,J.y,J.halfWidth,J.halfHeight,Q.x,Q.y,Q.radius,N);if(!Y(Q.x,Q.y,Q.halfWidth,Q.halfHeight,J.x,J.y,J.radius,N))return!1;return N.normalX=-N.normalX,N.normalY=-N.normalY,!0}var D=new Set,m=!1,e=50;function y(J,Q,N,O,j,G){if(O)o(J,Q,N,O,j,G);else a(J,Q,j,G)}function a(J,Q,N,O){if(!m&&Q>=e)m=!0,console.warn(`[ecspresso] Collision detection is using O(n²) brute force with ${Q} colliders. For better performance, install createSpatialIndexPlugin() alongside your collision or physics2D plugin.`);for(let j=0;j<Q;j++){let G=J[j];if(!G)continue;for(let V=j+1;V<Q;V++){let $=J[V];if(!$)continue;if(!G.collidesWith.includes($.layer)&&!$.collidesWith.includes(G.layer))continue;if(!x(G,$,A))continue;N(G,$,A,O)}}}function o(J,Q,N,O,j,G){N.clear();for(let V=0;V<Q;V++){let $=J[V];if(!$)continue;N.set($.entityId,$)}for(let V=0;V<Q;V++){let $=J[V];if(!$)continue;let F=$.shape===0?$.halfWidth:$.radius,T=$.shape===0?$.halfHeight:$.radius;D.clear(),O.queryRectInto($.x-F,$.y-T,$.x+F,$.y+T,D);for(let K of D){if(K<=$.entityId)continue;let q=N.get(K);if(!q)continue;if(!$.collidesWith.includes(q.layer)&&!q.collidesWith.includes($.layer))continue;if(!x($,q,A))continue;j($,q,A,G)}}}function MJ(J,Q,N,O){let j={width:J,height:Q};if(N!==void 0)j.offsetX=N;if(O!==void 0)j.offsetY=O;return{aabbCollider:j}}function RJ(J,Q,N){let O={radius:J};if(Q!==void 0)O.offsetX=Q;if(N!==void 0)O.offsetY=N;return{circleCollider:O}}function p(J,Q){return{collisionLayer:{layer:J,collidesWith:Q}}}function QJ(J){let Q={};for(let N of Object.keys(J)){let O=J[N];Q[N]=()=>p(N,O)}return Q}function f(J){let Q=J.indexOf(":");if(Q===-1)throw Error(`Invalid collision pair key "${J}": must contain a colon separator (e.g. "player:enemy")`);let N=J.slice(0,Q),O=J.slice(Q+1);if(N===""||O==="")throw Error(`Invalid collision pair key "${J}": layer names must not be empty`);return[N,O]}function $J(J){let Q=new Map,N=new Set;for(let O of Object.keys(J))f(O),N.add(O);for(let O of Object.keys(J)){let[j,G]=f(O),V=J[O];if(!V)continue;Q.set(O,{callback:V,swapped:!1});let $=`${G}:${j}`;if($!==O&&!N.has($))Q.set($,{callback:V,swapped:!0})}return function({data:j,ecs:G}){let V=Q.get(j.layerA+":"+j.layerB);if(!V)return;if(V.swapped)V.callback(j.entityB,j.entityA,G);else V.callback(j.entityA,j.entityB,G)}}var E={entityA:0,entityB:0,layerA:"",layerB:"",normalX:0,normalY:0,depth:0};function NJ(J,Q,N,O){E.entityA=J.entityId,E.entityB=Q.entityId,E.layerA=J.layer,E.layerB=Q.layer,E.normalX=N.normalX,E.normalY=N.normalY,E.depth=N.depth,O.publish("collision",E)}function EJ(J){let{systemGroup:Q="physics",priority:N=0,phase:O="postUpdate"}=J;return JJ("collision").withComponentTypes().withEventTypes().withLabels().withGroups().requires().install((j)=>{let G=[],V=new Map,$,F=!1;j.addSystem("collision-detection").setPriority(N).inPhase(O).inGroup(Q).addQuery("collidables",{with:["worldTransform","collisionLayer"]}).setProcess(({queries:T,ecs:K})=>{let q=0;for(let U of T.collidables){let{worldTransform:L,collisionLayer:W}=U.components,H=K.getComponent(U.id,"aabbCollider"),P=H?void 0:K.getComponent(U.id,"circleCollider");if(!H&&!P)continue;let z=G[q];if(!z)z={entityId:U.id,x:L.x,y:L.y,layer:W.layer,collidesWith:W.collidesWith,shape:w,halfWidth:0,halfHeight:0,radius:0},G[q]=z;if(!v(z,U.id,L.x,L.y,W.layer,W.collidesWith,H,P))continue;q++}if(!F)$=K.tryGetResource("spatialIndex"),F=!0;y(G,q,V,$,NJ,K.eventBus)})})}import{definePlugin as FJ}from"ecspresso";var Z={normalX:0,normalY:0,normalZ:0,depth:0},d=0;function u(J,Q,N,O,j,G,V,$,F){if(J.entityId=Q,J.layer=G,J.collidesWith=V,$)return J.x=N+($.offsetX??0),J.y=O+($.offsetY??0),J.z=j+($.offsetZ??0),J.shape=0,J.halfWidth=$.width/2,J.halfHeight=$.height/2,J.halfDepth=$.depth/2,J.radius=0,!0;if(F)return J.x=N+(F.offsetX??0),J.y=O+(F.offsetY??0),J.z=j+(F.offsetZ??0),J.shape=1,J.halfWidth=0,J.halfHeight=0,J.halfDepth=0,J.radius=F.radius,!0;return!1}function VJ(J,Q,N,O,j,G,V,$,F,T,K,q,U){let L=V-J,W=$-Q,H=F-N,P=O+T-Math.abs(L),z=j+K-Math.abs(W),M=G+q-Math.abs(H);if(P<=0||z<=0||M<=0)return!1;if(P<=z&&P<=M)return U.normalX=L>=0?1:-1,U.normalY=0,U.normalZ=0,U.depth=P,!0;if(z<=M)return U.normalX=0,U.normalY=W>=0?1:-1,U.normalZ=0,U.depth=z,!0;return U.normalX=0,U.normalY=0,U.normalZ=H>=0?1:-1,U.depth=M,!0}function OJ(J,Q,N,O,j,G,V,$,F){let T=j-J,K=G-Q,q=V-N,U=T*T+K*K+q*q,L=O+$;if(U>=L*L)return!1;let W=Math.sqrt(U);if(W===0)return F.normalX=1,F.normalY=0,F.normalZ=0,F.depth=L,!0;return F.normalX=T/W,F.normalY=K/W,F.normalZ=q/W,F.depth=L-W,!0}function h(J,Q,N,O,j,G,V,$,F,T,K){let q=Math.max(J-O,Math.min(V,J+O)),U=Math.max(Q-j,Math.min($,Q+j)),L=Math.max(N-G,Math.min(F,N+G)),W=V-q,H=$-U,P=F-L,z=W*W+H*H+P*P;if(z>=T*T)return!1;if(z===0){let S=V-(J-O),B=J+O-V,k=$-(Q-j),I=Q+j-$,X=F-(N-G),_=N+G-F,g=Math.min(S,B,k,I,X,_);if(g===B)return K.normalX=1,K.normalY=0,K.normalZ=0,K.depth=B+T,!0;if(g===S)return K.normalX=-1,K.normalY=0,K.normalZ=0,K.depth=S+T,!0;if(g===I)return K.normalX=0,K.normalY=1,K.normalZ=0,K.depth=I+T,!0;if(g===k)return K.normalX=0,K.normalY=-1,K.normalZ=0,K.depth=k+T,!0;if(g===_)return K.normalX=0,K.normalY=0,K.normalZ=1,K.depth=_+T,!0;return K.normalX=0,K.normalY=0,K.normalZ=-1,K.depth=X+T,!0}let M=Math.sqrt(z);return K.normalX=W/M,K.normalY=H/M,K.normalZ=P/M,K.depth=T-M,!0}function c(J,Q,N){if(J.shape===0&&Q.shape===0)return VJ(J.x,J.y,J.z,J.halfWidth,J.halfHeight,J.halfDepth,Q.x,Q.y,Q.z,Q.halfWidth,Q.halfHeight,Q.halfDepth,N);if(J.shape===1&&Q.shape===1)return OJ(J.x,J.y,J.z,J.radius,Q.x,Q.y,Q.z,Q.radius,N);if(J.shape===0&&Q.shape===1)return h(J.x,J.y,J.z,J.halfWidth,J.halfHeight,J.halfDepth,Q.x,Q.y,Q.z,Q.radius,N);if(!h(Q.x,Q.y,Q.z,Q.halfWidth,Q.halfHeight,Q.halfDepth,J.x,J.y,J.z,J.radius,N))return!1;return N.normalX=-N.normalX,N.normalY=-N.normalY,N.normalZ=-N.normalZ,!0}var C=new Set,b=!1,jJ=50;function n(J,Q,N,O,j,G){if(O)GJ(J,Q,N,O,j,G);else KJ(J,Q,j,G)}function KJ(J,Q,N,O){if(!b&&Q>=jJ)b=!0,console.warn(`[ecspresso] 3D collision detection is using O(n²) brute force with ${Q} colliders. For better performance, install createSpatialIndex3DPlugin() alongside your collision or physics3D plugin.`);for(let j=0;j<Q;j++){let G=J[j];if(!G)continue;for(let V=j+1;V<Q;V++){let $=J[V];if(!$)continue;if(!G.collidesWith.includes($.layer)&&!$.collidesWith.includes(G.layer))continue;if(!c(G,$,Z))continue;N(G,$,Z,O)}}}function GJ(J,Q,N,O,j,G){N.clear();for(let V=0;V<Q;V++){let $=J[V];if(!$)continue;N.set($.entityId,$)}for(let V=0;V<Q;V++){let $=J[V];if(!$)continue;let F=$.shape===0?$.halfWidth:$.radius,T=$.shape===0?$.halfHeight:$.radius,K=$.shape===0?$.halfDepth:$.radius;C.clear(),O.queryBoxInto($.x-F,$.y-T,$.z-K,$.x+F,$.y+T,$.z+K,C);for(let q of C){if(q<=$.entityId)continue;let U=N.get(q);if(!U)continue;if(!$.collidesWith.includes(U.layer)&&!U.collidesWith.includes($.layer))continue;if(!c($,U,Z))continue;j($,U,Z,G)}}}function kJ(J,Q,N,O,j,G){let V={width:J,height:Q,depth:N};if(O!==void 0)V.offsetX=O;if(j!==void 0)V.offsetY=j;if(G!==void 0)V.offsetZ=G;return{aabb3DCollider:V}}function IJ(J,Q,N,O){let j={radius:J};if(Q!==void 0)j.offsetX=Q;if(N!==void 0)j.offsetY=N;if(O!==void 0)j.offsetZ=O;return{sphereCollider:j}}var R={entityA:0,entityB:0,layerA:"",layerB:"",normalX:0,normalY:0,normalZ:0,depth:0};function UJ(J,Q,N,O){R.entityA=J.entityId,R.entityB=Q.entityId,R.layerA=J.layer,R.layerB=Q.layer,R.normalX=N.normalX,R.normalY=N.normalY,R.normalZ=N.normalZ,R.depth=N.depth,O.publish("collision3D",R)}function _J(J){let{systemGroup:Q="physics",priority:N=0,phase:O="postUpdate"}=J;return FJ("collision3D").withComponentTypes().withEventTypes().withLabels().withGroups().requires().install((j)=>{let G=[],V=new Map,$,F=!1;j.addSystem("collision3D-detection").setPriority(N).inPhase(O).inGroup(Q).addQuery("collidables",{with:["worldTransform3D","collisionLayer"]}).setProcess(({queries:T,ecs:K})=>{let q=0;for(let U of T.collidables){let{worldTransform3D:L,collisionLayer:W}=U.components,H=K.getComponent(U.id,"aabb3DCollider"),P=H?void 0:K.getComponent(U.id,"sphereCollider");if(!H&&!P)continue;let z=G[q];if(!z)z={entityId:U.id,x:L.x,y:L.y,z:L.z,layer:W.layer,collidesWith:W.collidesWith,shape:d,halfWidth:0,halfHeight:0,halfDepth:0,radius:0},G[q]=z;if(!u(z,U.id,L.x,L.y,L.z,W.layer,W.collidesWith,H,P))continue;q++}if(!F)$=K.tryGetResource("spatialIndex3D"),F=!0;n(G,q,V,$,UJ,K.eventBus)})})}export{QJ as defineCollisionLayers,IJ as createSphereCollider,$J as createCollisionPairHandler,p as createCollisionLayer,_J as createCollision3DPlugin,kJ as createAABB3DCollider};
|
|
1
|
+
var u=Object.defineProperty;var r=(J)=>J;function s(J,Q){this[J]=r.bind(null,Q)}var qJ=(J,Q)=>{for(var N in Q)u(J,N,{get:Q[N],enumerable:!0,configurable:!0,set:s.bind(Q,N)})};var TJ=(J,Q)=>()=>(J&&(Q=J(J=0)),Q);var gJ=((J)=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(J,{get:(Q,N)=>(typeof require<"u"?require:Q)[N]}):J)(function(J){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+J+'" is not supported')});import{definePlugin as JJ}from"ecspresso";var A={normalX:0,normalY:0,depth:0},w=0;function v(J,Q,N,O,j,U,V,$){if(J.entityId=Q,J.layer=j,J.collidesWith=U,V)return J.x=N+(V.offsetX??0),J.y=O+(V.offsetY??0),J.shape=0,J.halfWidth=V.width/2,J.halfHeight=V.height/2,J.radius=0,!0;if($)return J.x=N+($.offsetX??0),J.y=O+($.offsetY??0),J.shape=1,J.halfWidth=0,J.halfHeight=0,J.radius=$.radius,!0;return!1}function i(J,Q,N,O,j,U,V,$,K){let T=j-J,G=U-Q,q=N+V-Math.abs(T),F=O+$-Math.abs(G);if(q<=0||F<=0)return!1;if(q<F)return K.normalX=T>=0?1:-1,K.normalY=0,K.depth=q,!0;return K.normalX=0,K.normalY=G>=0?1:-1,K.depth=F,!0}function e(J,Q,N,O,j,U,V){let $=O-J,K=j-Q,T=$*$+K*K,G=N+U;if(T>=G*G)return!1;let q=Math.sqrt(T);if(q===0)return V.normalX=1,V.normalY=0,V.depth=G,!0;return V.normalX=$/q,V.normalY=K/q,V.depth=G-q,!0}function X(J,Q,N,O,j,U,V,$){let K=Math.max(J-N,Math.min(j,J+N)),T=Math.max(Q-O,Math.min(U,Q+O)),G=j-K,q=U-T,F=G*G+q*q;if(F>=V*V)return!1;if(F===0){let g=j-(J-N),L=J+N-j,z=U-(Q-O),M=Q+O-U,H=Math.min(g,L,z,M);if(H===L)return $.normalX=1,$.normalY=0,$.depth=L+V,!0;if(H===g)return $.normalX=-1,$.normalY=0,$.depth=g+V,!0;if(H===M)return $.normalX=0,$.normalY=1,$.depth=M+V,!0;return $.normalX=0,$.normalY=-1,$.depth=z+V,!0}let W=Math.sqrt(F);return $.normalX=G/W,$.normalY=q/W,$.depth=V-W,!0}function x(J,Q,N){if(J.shape===0&&Q.shape===0)return i(J.x,J.y,J.halfWidth,J.halfHeight,Q.x,Q.y,Q.halfWidth,Q.halfHeight,N);if(J.shape===1&&Q.shape===1)return e(J.x,J.y,J.radius,Q.x,Q.y,Q.radius,N);if(J.shape===0&&Q.shape===1)return X(J.x,J.y,J.halfWidth,J.halfHeight,Q.x,Q.y,Q.radius,N);if(!X(Q.x,Q.y,Q.halfWidth,Q.halfHeight,J.x,J.y,J.radius,N))return!1;return N.normalX=-N.normalX,N.normalY=-N.normalY,!0}var _=new Set,Y=!1,t=50;function y(J,Q,N,O,j,U){if(O)o(J,Q,N,O,j,U);else a(J,Q,j,U)}function a(J,Q,N,O){if(!Y&&Q>=t)Y=!0,console.warn(`[ecspresso] Collision detection is using O(n²) brute force with ${Q} colliders. For better performance, install createSpatialIndexPlugin() alongside your collision or physics2D plugin.`);for(let j=0;j<Q;j++){let U=J[j];if(!U)continue;for(let V=j+1;V<Q;V++){let $=J[V];if(!$)continue;if(!U.collidesWith.includes($.layer)&&!$.collidesWith.includes(U.layer))continue;if(!x(U,$,A))continue;N(U,$,A,O)}}}function o(J,Q,N,O,j,U){N.clear();for(let V=0;V<Q;V++){let $=J[V];if(!$)continue;N.set($.entityId,$)}for(let V=0;V<Q;V++){let $=J[V];if(!$)continue;let K=$.shape===0?$.halfWidth:$.radius,T=$.shape===0?$.halfHeight:$.radius;_.clear(),O.queryRectInto($.x-K,$.y-T,$.x+K,$.y+T,_);for(let G of _){if(G<=$.entityId)continue;let q=N.get(G);if(!q)continue;if(!$.collidesWith.includes(q.layer)&&!q.collidesWith.includes($.layer))continue;if(!x($,q,A))continue;j($,q,A,U)}}}function HJ(J,Q,N,O){let j={width:J,height:Q};if(N!==void 0)j.offsetX=N;if(O!==void 0)j.offsetY=O;return{aabbCollider:j}}function PJ(J,Q,N){let O={radius:J};if(Q!==void 0)O.offsetX=Q;if(N!==void 0)O.offsetY=N;return{circleCollider:O}}function f(J,Q){return{collisionLayer:{layer:J,collidesWith:Q}}}function QJ(J){let Q={};for(let N of Object.keys(J)){let O=J[N];Q[N]=()=>f(N,O)}return Q}function p(J){let Q=J.indexOf(":");if(Q===-1)throw Error(`Invalid collision pair key "${J}": must contain a colon separator (e.g. "player:enemy")`);let N=J.slice(0,Q),O=J.slice(Q+1);if(N===""||O==="")throw Error(`Invalid collision pair key "${J}": layer names must not be empty`);return[N,O]}function $J(J){let Q=new Map,N=new Set;for(let O of Object.keys(J))p(O),N.add(O);for(let O of Object.keys(J)){let[j,U]=p(O),V=J[O];if(!V)continue;Q.set(O,{callback:V,swapped:!1});let $=`${U}:${j}`;if($!==O&&!N.has($))Q.set($,{callback:V,swapped:!0})}return function({data:j,ecs:U}){let V=Q.get(j.layerA+":"+j.layerB);if(!V)return;if(V.swapped)V.callback(j.entityB,j.entityA,U);else V.callback(j.entityA,j.entityB,U)}}var R={entityA:0,entityB:0,layerA:"",layerB:"",normalX:0,normalY:0,depth:0};function NJ(J,Q,N,O){R.entityA=J.entityId,R.entityB=Q.entityId,R.layerA=J.layer,R.layerB=Q.layer,R.normalX=N.normalX,R.normalY=N.normalY,R.depth=N.depth,O.publish("collision",R)}function RJ(J){let{systemGroup:Q="physics",priority:N=0,phase:O="postUpdate"}=J;return JJ("collision").withComponentTypes().withEventTypes().withLabels().withGroups().requires().install((j)=>{let U=[],V=new Map,$,K=!1;j.addSystem("collision-detection").setPriority(N).inPhase(O).inGroup(Q).addQuery("collidables",{with:["worldTransform","collisionLayer"]}).setProcess(({queries:T,ecs:G})=>{let q=0;for(let F of T.collidables){let{worldTransform:W,collisionLayer:g}=F.components,L=G.getComponent(F.id,"aabbCollider"),z=L?void 0:G.getComponent(F.id,"circleCollider");if(!L&&!z)continue;let M=U[q];if(!M)M={entityId:F.id,x:W.x,y:W.y,layer:g.layer,collidesWith:g.collidesWith,shape:w,halfWidth:0,halfHeight:0,radius:0},U[q]=M;if(!v(M,F.id,W.x,W.y,g.layer,g.collidesWith,L,z))continue;q++}if(!K)$=G.tryGetResource("spatialIndex"),K=!0;y(U,q,V,$,NJ,G.eventBus)})})}import{definePlugin as KJ}from"ecspresso";var k={normalX:0,normalY:0,normalZ:0,depth:0},b=0;function n(J,Q,N,O,j,U,V,$,K){if(J.entityId=Q,J.layer=U,J.collidesWith=V,$)return J.x=N+($.offsetX??0),J.y=O+($.offsetY??0),J.z=j+($.offsetZ??0),J.shape=0,J.halfWidth=$.width/2,J.halfHeight=$.height/2,J.halfDepth=$.depth/2,J.radius=0,!0;if(K)return J.x=N+(K.offsetX??0),J.y=O+(K.offsetY??0),J.z=j+(K.offsetZ??0),J.shape=1,J.halfWidth=0,J.halfHeight=0,J.halfDepth=0,J.radius=K.radius,!0;return!1}function VJ(J,Q,N,O,j,U,V,$,K,T,G,q,F){let W=V-J,g=$-Q,L=K-N,z=O+T-Math.abs(W),M=j+G-Math.abs(g),H=U+q-Math.abs(L);if(z<=0||M<=0||H<=0)return!1;if(z<=M&&z<=H)return F.normalX=W>=0?1:-1,F.normalY=0,F.normalZ=0,F.depth=z,!0;if(M<=H)return F.normalX=0,F.normalY=g>=0?1:-1,F.normalZ=0,F.depth=M,!0;return F.normalX=0,F.normalY=0,F.normalZ=L>=0?1:-1,F.depth=H,!0}function OJ(J,Q,N,O,j,U,V,$,K){let T=j-J,G=U-Q,q=V-N,F=T*T+G*G+q*q,W=O+$;if(F>=W*W)return!1;let g=Math.sqrt(F);if(g===0)return K.normalX=1,K.normalY=0,K.normalZ=0,K.depth=W,!0;return K.normalX=T/g,K.normalY=G/g,K.normalZ=q/g,K.depth=W-g,!0}function h(J,Q,N,O,j,U,V,$,K,T,G){let q=Math.max(J-O,Math.min(V,J+O)),F=Math.max(Q-j,Math.min($,Q+j)),W=Math.max(N-U,Math.min(K,N+U)),g=V-q,L=$-F,z=K-W,M=g*g+L*L+z*z;if(M>=T*T)return!1;if(M===0){let I=V-(J-O),Z=J+O-V,S=$-(Q-j),B=Q+j-$,D=K-(N-U),m=N+U-K,E=Math.min(I,Z,S,B,D,m);if(E===Z)return G.normalX=1,G.normalY=0,G.normalZ=0,G.depth=Z+T,!0;if(E===I)return G.normalX=-1,G.normalY=0,G.normalZ=0,G.depth=I+T,!0;if(E===B)return G.normalX=0,G.normalY=1,G.normalZ=0,G.depth=B+T,!0;if(E===S)return G.normalX=0,G.normalY=-1,G.normalZ=0,G.depth=S+T,!0;if(E===m)return G.normalX=0,G.normalY=0,G.normalZ=1,G.depth=m+T,!0;return G.normalX=0,G.normalY=0,G.normalZ=-1,G.depth=D+T,!0}let H=Math.sqrt(M);return G.normalX=g/H,G.normalY=L/H,G.normalZ=z/H,G.depth=T-H,!0}function c(J,Q,N){if(J.shape===0&&Q.shape===0)return VJ(J.x,J.y,J.z,J.halfWidth,J.halfHeight,J.halfDepth,Q.x,Q.y,Q.z,Q.halfWidth,Q.halfHeight,Q.halfDepth,N);if(J.shape===1&&Q.shape===1)return OJ(J.x,J.y,J.z,J.radius,Q.x,Q.y,Q.z,Q.radius,N);if(J.shape===0&&Q.shape===1)return h(J.x,J.y,J.z,J.halfWidth,J.halfHeight,J.halfDepth,Q.x,Q.y,Q.z,Q.radius,N);if(!h(Q.x,Q.y,Q.z,Q.halfWidth,Q.halfHeight,Q.halfDepth,J.x,J.y,J.z,J.radius,N))return!1;return N.normalX=-N.normalX,N.normalY=-N.normalY,N.normalZ=-N.normalZ,!0}var C=new Set,d=!1,jJ=50;function l(J,Q,N,O,j,U){if(O)UJ(J,Q,N,O,j,U);else GJ(J,Q,j,U)}function GJ(J,Q,N,O){if(!d&&Q>=jJ)d=!0,console.warn(`[ecspresso] 3D collision detection is using O(n²) brute force with ${Q} colliders. For better performance, install createSpatialIndex3DPlugin() alongside your collision or physics3D plugin.`);for(let j=0;j<Q;j++){let U=J[j];if(!U)continue;for(let V=j+1;V<Q;V++){let $=J[V];if(!$)continue;if(!U.collidesWith.includes($.layer)&&!$.collidesWith.includes(U.layer))continue;if(!c(U,$,k))continue;N(U,$,k,O)}}}function UJ(J,Q,N,O,j,U){N.clear();for(let V=0;V<Q;V++){let $=J[V];if(!$)continue;N.set($.entityId,$)}for(let V=0;V<Q;V++){let $=J[V];if(!$)continue;let K=$.shape===0?$.halfWidth:$.radius,T=$.shape===0?$.halfHeight:$.radius,G=$.shape===0?$.halfDepth:$.radius;C.clear(),O.queryBoxInto($.x-K,$.y-T,$.z-G,$.x+K,$.y+T,$.z+G,C);for(let q of C){if(q<=$.entityId)continue;let F=N.get(q);if(!F)continue;if(!$.collidesWith.includes(F.layer)&&!F.collidesWith.includes($.layer))continue;if(!c($,F,k))continue;j($,F,k,U)}}}function SJ(J,Q,N,O,j,U){let V={width:J,height:Q,depth:N};if(O!==void 0)V.offsetX=O;if(j!==void 0)V.offsetY=j;if(U!==void 0)V.offsetZ=U;return{aabb3DCollider:V}}function BJ(J,Q,N,O){let j={radius:J};if(Q!==void 0)j.offsetX=Q;if(N!==void 0)j.offsetY=N;if(O!==void 0)j.offsetZ=O;return{sphereCollider:j}}var P={entityA:0,entityB:0,layerA:"",layerB:"",normalX:0,normalY:0,normalZ:0,depth:0};function FJ(J,Q,N,O){P.entityA=J.entityId,P.entityB=Q.entityId,P.layerA=J.layer,P.layerB=Q.layer,P.normalX=N.normalX,P.normalY=N.normalY,P.normalZ=N.normalZ,P.depth=N.depth,O.publish("collision3D",P)}function mJ(J){let{systemGroup:Q="physics",priority:N=0,phase:O="postUpdate"}=J;return KJ("collision3D").withComponentTypes().withEventTypes().withLabels().withGroups().requires().install((j)=>{let U=[],V=new Map,$,K=!1;j.addSystem("collision3D-detection").setPriority(N).inPhase(O).inGroup(Q).addQuery("collidables",{with:["worldTransform3D","collisionLayer"]}).setProcess(({queries:T,ecs:G})=>{let q=0;for(let F of T.collidables){let{worldTransform3D:W,collisionLayer:g}=F.components,L=G.getComponent(F.id,"aabb3DCollider"),z=L?void 0:G.getComponent(F.id,"sphereCollider");if(!L&&!z)continue;let M=U[q];if(!M)M={entityId:F.id,x:W.x,y:W.y,z:W.z,layer:g.layer,collidesWith:g.collidesWith,shape:b,halfWidth:0,halfHeight:0,halfDepth:0,radius:0},U[q]=M;if(!n(M,F.id,W.x,W.y,W.z,g.layer,g.collidesWith,L,z))continue;q++}if(!K)$=G.tryGetResource("spatialIndex3D"),K=!0;l(U,q,V,$,FJ,G.eventBus)})})}export{QJ as defineCollisionLayers,BJ as createSphereCollider,$J as createCollisionPairHandler,f as createCollisionLayer,mJ as createCollision3DPlugin,SJ as createAABB3DCollider};
|
|
2
2
|
|
|
3
|
-
//# debugId=
|
|
3
|
+
//# debugId=24B2DF3C8952804E64756E2164756E21
|
|
4
4
|
//# sourceMappingURL=collision3D.js.map
|