ecspresso 0.16.1 → 0.16.2
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 +4 -4
- package/dist/plugins/ai/detection.js +2 -2
- package/dist/plugins/ai/detection.js.map +3 -3
- package/dist/plugins/ai/flocking.js +2 -2
- package/dist/plugins/ai/flocking.js.map +7 -6
- package/dist/plugins/physics/collision.js +2 -2
- package/dist/plugins/physics/collision.js.map +6 -5
- package/dist/plugins/physics/collision3D.js +2 -2
- package/dist/plugins/physics/collision3D.js.map +8 -7
- package/dist/plugins/physics/physics2D.js +2 -2
- package/dist/plugins/physics/physics2D.js.map +6 -5
- package/dist/plugins/physics/physics3D.js +2 -2
- package/dist/plugins/physics/physics3D.js.map +6 -5
- package/dist/plugins/spatial/spatial-index.js +2 -2
- package/dist/plugins/spatial/spatial-index.js.map +4 -4
- package/dist/plugins/spatial/spatial-index3D.js +2 -2
- package/dist/plugins/spatial/spatial-index3D.js.map +4 -4
- package/dist/query-cache.d.ts +7 -7
- package/dist/utils/layer-bit-registry.d.ts +17 -0
- package/dist/utils/narrowphase.d.ts +31 -6
- package/dist/utils/narrowphase3D.d.ts +10 -0
- package/dist/utils/spatial-hash.d.ts +49 -14
- package/dist/utils/spatial-hash3D.d.ts +49 -14
- package/package.json +1 -1
|
@@ -1,11 +1,12 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
|
-
"sources": ["../src/plugins/physics/collision.ts", "../src/utils/narrowphase.ts"],
|
|
3
|
+
"sources": ["../src/plugins/physics/collision.ts", "../src/utils/layer-bit-registry.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\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"
|
|
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, createBroadphaseScratch, 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\tconst broadphaseScratch = createBroadphaseScratch<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\tlayerBit: 0,\n\t\t\t\t\t\t\t\tcollidesWithMask: 0,\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, broadphaseScratch, cachedSI, onCollisionDetected<L>, ecs.eventBus);\n\t\t\t\t});\n\t\t});\n}\n\n",
|
|
6
|
+
"/**\n * Lazy monotonic registry mapping layer name → unique bit. Lets pair\n * filtering use a single `(a.collidesWithMask & b.layerBit)` check\n * instead of `Array.includes` on every collision pair.\n *\n * One registry per dimension (2D and 3D) — user-defined layer namespaces\n * are independent, so bits should not be shared across systems.\n *\n * Maximum 32 layers per registry (one per bit in a 32-bit signed int).\n * Crossing the limit throws on the next `getLayerBit` call.\n */\nexport interface LayerBitRegistry {\n\tgetLayerBit(layer: string): number;\n\t/** OR of `getLayerBit` for every entry. Cached by array reference. */\n\tgetCollidesWithMask(collidesWith: readonly string[]): number;\n}\n\nexport function createLayerBitRegistry(label: string): LayerBitRegistry {\n\tconst layerBits = new Map<string, number>();\n\tconst maskCache = new WeakMap<readonly string[], number>();\n\tlet nextBit = 1;\n\n\tfunction getLayerBit(layer: string): number {\n\t\tconst existing = layerBits.get(layer);\n\t\tif (existing !== undefined) return existing;\n\t\tif (nextBit === 0) {\n\t\t\tthrow new Error(\n\t\t\t\t`[ecspresso] ${label} layer bitmask overflow: more than 32 distinct layers registered`,\n\t\t\t);\n\t\t}\n\t\tconst bit = nextBit;\n\t\tlayerBits.set(layer, bit);\n\t\t// `<<= 1` rolls 1<<31 to 0, which is detected on the next call.\n\t\tnextBit <<= 1;\n\t\treturn bit;\n\t}\n\n\tfunction getCollidesWithMask(collidesWith: readonly string[]): number {\n\t\tconst cached = maskCache.get(collidesWith);\n\t\tif (cached !== undefined) return cached;\n\t\tlet mask = 0;\n\t\tfor (let i = 0; i < collidesWith.length; i++) {\n\t\t\tmask |= getLayerBit(collidesWith[i]!);\n\t\t}\n\t\tmaskCache.set(collidesWith, mask);\n\t\treturn mask;\n\t}\n\n\treturn { getLayerBit, getCollidesWithMask };\n}\n",
|
|
7
|
+
"/**\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';\nimport { createLayerBitRegistry } from './layer-bit-registry';\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\t/**\n\t * Bit assigned to `layer` from the lazy layer registry. Populated by\n\t * `fillBaseColliderInfo`. Used together with `collidesWithMask` to\n\t * replace per-pair `Array.includes` layer checks with a single AND.\n\t */\n\tlayerBit: number;\n\t/** OR of `getLayerBit` for every entry in `collidesWith`. */\n\tcollidesWithMask: number;\n\tshape: ColliderShape;\n\thalfWidth: number;\n\thalfHeight: number;\n\tradius: number;\n}\n\n// ==================== Layer Bit Registry ====================\n\nconst _layerRegistry = createLayerBitRegistry('Collision');\nexport const getLayerBit = _layerRegistry.getLayerBit;\nexport const getCollidesWithMask = _layerRegistry.getCollidesWithMask;\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\tinfo.layerBit = getLayerBit(layer);\n\tinfo.collidesWithMask = getCollidesWithMask(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\nconst _broadphaseCandidates: number[] = [];\n\n/**\n * Per-caller scratch for the broadphase entityId → collider lookup.\n *\n * Dense `arr` indexed by entityId, paired with a `gen` stamp array that marks\n * which slots are live this call. Bumping `current` invalidates all prior\n * entries without clearing — replaces the per-frame `Map.clear()` + N\n * `Map.set()` allocation churn that a `Map<number, I>` would incur.\n *\n * Owned per plugin instance (alongside its `colliderPool`), so concurrent\n * worlds don't share state and `I` stays fully typed without erasure.\n */\nexport interface BroadphaseScratch<I extends BaseColliderInfo> {\n\tarr: (I | undefined)[];\n\tgen: number[];\n\tcurrent: number;\n}\n\nexport function createBroadphaseScratch<I extends BaseColliderInfo>(): BroadphaseScratch<I> {\n\treturn { arr: [], gen: [], current: 0 };\n}\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 * `scratch` is a caller-owned `BroadphaseScratch<I>` used by the broadphase\n * path as an entityId → collider lookup. Allocate it once per plugin instance\n * and pass the same reference every call.\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\tscratch: BroadphaseScratch<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, scratch, 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.collidesWithMask & b.layerBit) | (b.collidesWithMask & a.layerBit)) === 0) 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\tscratch: BroadphaseScratch<I>,\n\tspatialIndex: SpatialIndex,\n\tonContact: (a: I, b: I, contact: Contact, context: C) => void,\n\tcontext: C,\n): void {\n\tconst arr = scratch.arr;\n\tconst stamps = scratch.gen;\n\tconst gen = ++scratch.current;\n\tfor (let i = 0; i < count; i++) {\n\t\tconst c = colliders[i];\n\t\tif (!c) continue;\n\t\tconst id = c.entityId;\n\t\tarr[id] = c;\n\t\tstamps[id] = gen;\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.length = 0;\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\ta.entityId,\n\t\t);\n\n\t\tfor (const bId of _broadphaseCandidates) {\n\t\t\tif (stamps[bId] !== gen) continue;\n\t\t\tconst b = arr[bId];\n\t\t\tif (!b) continue;\n\n\t\t\tif (((a.collidesWithMask & b.layerBit) | (b.collidesWithMask & a.layerBit)) === 0) 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
8
|
],
|
|
8
|
-
"mappings": "2PAQA,uBAAS,
|
|
9
|
-
"debugId": "
|
|
9
|
+
"mappings": "2PAQA,uBAAS,kBCSF,SAAS,CAAsB,CAAC,EAAiC,CACvE,IAAM,EAAY,IAAI,IAChB,EAAY,IAAI,QAClB,EAAU,EAEd,SAAS,CAAW,CAAC,EAAuB,CAC3C,IAAM,EAAW,EAAU,IAAI,CAAK,EACpC,GAAI,IAAa,OAAW,OAAO,EACnC,GAAI,IAAY,EACf,MAAU,MACT,eAAe,mEAChB,EAED,IAAM,EAAM,EAIZ,OAHA,EAAU,IAAI,EAAO,CAAG,EAExB,IAAY,EACL,EAGR,SAAS,CAAmB,CAAC,EAAyC,CACrE,IAAM,EAAS,EAAU,IAAI,CAAY,EACzC,GAAI,IAAW,OAAW,OAAO,EACjC,IAAI,EAAO,EACX,QAAS,EAAI,EAAG,EAAI,EAAa,OAAQ,IACxC,GAAQ,EAAY,EAAa,EAAG,EAGrC,OADA,EAAU,IAAI,EAAc,CAAI,EACzB,EAGR,MAAO,CAAE,cAAa,qBAAoB,ECd3C,IAAM,EAA0B,CAAE,QAAS,EAAG,QAAS,EAAG,MAAO,CAAE,EAKtD,EAAa,EACb,EAAe,EAmCtB,EAAiB,EAAuB,WAAW,EAC5C,EAAc,EAAe,YAC7B,EAAsB,EAAe,oBAc3C,SAAS,C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,EAAO,EAAa,GACxB,GAAI,CAAC,EACJ,EAAO,CACN,SAAU,EAAO,GACjB,EAAG,EAAe,EAClB,EAAG,EAAe,EAClB,MAAO,EAAe,MACtB,aAAc,EAAe,aAC7B,SAAU,EACV,iBAAkB,EAClB,MAAO,EACP,UAAW,EACX,WAAY,EACZ,OAAQ,CACT,EACA,EAAa,GAAS,EAGvB,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,EAAmB,EAAU,EAAwB,EAAI,QAAQ,EACvG,EACF",
|
|
10
|
+
"debugId": "8CAA9F9ACA53BC0264756E2164756E21",
|
|
10
11
|
"names": []
|
|
11
12
|
}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
var UJ=((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 t}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 u(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 r(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 u(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 r(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,s=50;function y(J,Q,N,O,j,U){if(O)e(J,Q,N,O,j,U);else i(J,Q,j,U)}function i(J,Q,N,O){if(!Y&&Q>=s)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 e(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 gJ(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 WJ(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 a(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 o(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 JJ(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 MJ(J){let{systemGroup:Q="physics",priority:N=0,phase:O="postUpdate"}=J;return t("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,$,JJ,G.eventBus)})})}import{definePlugin as jJ}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 QJ(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 $J(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 QJ(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 $J(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,NJ=50;function l(J,Q,N,O,j,U){if(O)OJ(J,Q,N,O,j,U);else VJ(J,Q,j,U)}function VJ(J,Q,N,O){if(!d&&Q>=NJ)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 OJ(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 EJ(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 AJ(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 GJ(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 kJ(J){let{systemGroup:Q="physics",priority:N=0,phase:O="postUpdate"}=J;return jJ("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,$,GJ,G.eventBus)})})}export{a as defineCollisionLayers,AJ as createSphereCollider,o as createCollisionPairHandler,f as createCollisionLayer,kJ as createCollision3DPlugin,EJ as createAABB3DCollider};
|
|
1
|
+
var RJ=((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 OJ}from"ecspresso";function X(J){let Q=new Map,N=new WeakMap,j=1;function G(O){let $=Q.get(O);if($!==void 0)return $;if(j===0)throw Error(`[ecspresso] ${J} layer bitmask overflow: more than 32 distinct layers registered`);let U=j;return Q.set(O,U),j<<=1,U}function K(O){let $=N.get(O);if($!==void 0)return $;let U=0;for(let q=0;q<O.length;q++)U|=G(O[q]);return N.set(O,U),U}return{getLayerBit:G,getCollidesWithMask:K}}var E={normalX:0,normalY:0,depth:0},g=0,Y=1,f=X("Collision"),a=f.getLayerBit,o=f.getCollidesWithMask;function h(J,Q,N,j,G,K,O,$){if(J.entityId=Q,J.layer=G,J.collidesWith=K,J.layerBit=a(G),J.collidesWithMask=o(K),O)return J.x=N+(O.offsetX??0),J.y=j+(O.offsetY??0),J.shape=g,J.halfWidth=O.width/2,J.halfHeight=O.height/2,J.radius=0,!0;if($)return J.x=N+($.offsetX??0),J.y=j+($.offsetY??0),J.shape=Y,J.halfWidth=0,J.halfHeight=0,J.radius=$.radius,!0;return!1}function JJ(J,Q,N,j,G,K,O,$,U){let q=G-J,V=K-Q,M=N+O-Math.abs(q),F=j+$-Math.abs(V);if(M<=0||F<=0)return!1;if(M<F)return U.normalX=q>=0?1:-1,U.normalY=0,U.depth=M,!0;return U.normalX=0,U.normalY=V>=0?1:-1,U.depth=F,!0}function QJ(J,Q,N,j,G,K,O){let $=j-J,U=G-Q,q=$*$+U*U,V=N+K;if(q>=V*V)return!1;let M=Math.sqrt(q);if(M===0)return O.normalX=1,O.normalY=0,O.depth=V,!0;return O.normalX=$/M,O.normalY=U/M,O.depth=V-M,!0}function y(J,Q,N,j,G,K,O,$){let U=Math.max(J-N,Math.min(G,J+N)),q=Math.max(Q-j,Math.min(K,Q+j)),V=G-U,M=K-q,F=V*V+M*M;if(F>=O*O)return!1;if(F===0){let T=G-(J-N),Z=J+N-G,W=K-(Q-j),L=Q+j-K,R=Math.min(T,Z,W,L);if(R===Z)return $.normalX=1,$.normalY=0,$.depth=Z+O,!0;if(R===T)return $.normalX=-1,$.normalY=0,$.depth=T+O,!0;if(R===L)return $.normalX=0,$.normalY=1,$.depth=L+O,!0;return $.normalX=0,$.normalY=-1,$.depth=W+O,!0}let z=Math.sqrt(F);return $.normalX=V/z,$.normalY=M/z,$.depth=O-z,!0}function b(J,Q,N){if(J.shape===g&&Q.shape===g)return JJ(J.x,J.y,J.halfWidth,J.halfHeight,Q.x,Q.y,Q.halfWidth,Q.halfHeight,N);if(J.shape===Y&&Q.shape===Y)return QJ(J.x,J.y,J.radius,Q.x,Q.y,Q.radius,N);if(J.shape===g&&Q.shape===Y)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 B=[];function d(){return{arr:[],gen:[],current:0}}var p=!1,$J=50;function u(J,Q,N,j,G,K){if(j)VJ(J,Q,N,j,G,K);else NJ(J,Q,G,K)}function NJ(J,Q,N,j){if(!p&&Q>=$J)p=!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 G=0;G<Q;G++){let K=J[G];if(!K)continue;for(let O=G+1;O<Q;O++){let $=J[O];if(!$)continue;if((K.collidesWithMask&$.layerBit|$.collidesWithMask&K.layerBit)===0)continue;if(!b(K,$,E))continue;N(K,$,E,j)}}}function VJ(J,Q,N,j,G,K){let{arr:O,gen:$}=N,U=++N.current;for(let q=0;q<Q;q++){let V=J[q];if(!V)continue;let M=V.entityId;O[M]=V,$[M]=U}for(let q=0;q<Q;q++){let V=J[q];if(!V)continue;let M=V.shape===g?V.halfWidth:V.radius,F=V.shape===g?V.halfHeight:V.radius;B.length=0,j.queryRectInto(V.x-M,V.y-F,V.x+M,V.y+F,B,V.entityId);for(let z of B){if($[z]!==U)continue;let T=O[z];if(!T)continue;if((V.collidesWithMask&T.layerBit|T.collidesWithMask&V.layerBit)===0)continue;if(!b(V,T,E))continue;G(V,T,E,K)}}}function YJ(J,Q,N,j){let G={width:J,height:Q};if(N!==void 0)G.offsetX=N;if(j!==void 0)G.offsetY=j;return{aabbCollider:G}}function EJ(J,Q,N){let j={radius:J};if(Q!==void 0)j.offsetX=Q;if(N!==void 0)j.offsetY=N;return{circleCollider:j}}function c(J,Q){return{collisionLayer:{layer:J,collidesWith:Q}}}function jJ(J){let Q={};for(let N of Object.keys(J)){let j=J[N];Q[N]=()=>c(N,j)}return Q}function n(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),j=J.slice(Q+1);if(N===""||j==="")throw Error(`Invalid collision pair key "${J}": layer names must not be empty`);return[N,j]}function GJ(J){let Q=new Map,N=new Set;for(let j of Object.keys(J))n(j),N.add(j);for(let j of Object.keys(J)){let[G,K]=n(j),O=J[j];if(!O)continue;Q.set(j,{callback:O,swapped:!1});let $=`${K}:${G}`;if($!==j&&!N.has($))Q.set($,{callback:O,swapped:!0})}return function({data:G,ecs:K}){let O=Q.get(G.layerA+":"+G.layerB);if(!O)return;if(O.swapped)O.callback(G.entityB,G.entityA,K);else O.callback(G.entityA,G.entityB,K)}}var H={entityA:0,entityB:0,layerA:"",layerB:"",normalX:0,normalY:0,depth:0};function KJ(J,Q,N,j){H.entityA=J.entityId,H.entityB=Q.entityId,H.layerA=J.layer,H.layerB=Q.layer,H.normalX=N.normalX,H.normalY=N.normalY,H.depth=N.depth,j.publish("collision",H)}function SJ(J){let{systemGroup:Q="physics",priority:N=0,phase:j="postUpdate"}=J;return OJ("collision").withComponentTypes().withEventTypes().withLabels().withGroups().requires().install((G)=>{let K=[],O=d(),$,U=!1;G.addSystem("collision-detection").setPriority(N).inPhase(j).inGroup(Q).addQuery("collidables",{with:["worldTransform","collisionLayer"]}).setProcess(({queries:q,ecs:V})=>{let M=0;for(let F of q.collidables){let{worldTransform:z,collisionLayer:T}=F.components,Z=V.getComponent(F.id,"aabbCollider"),W=Z?void 0:V.getComponent(F.id,"circleCollider");if(!Z&&!W)continue;let L=K[M];if(!L)L={entityId:F.id,x:z.x,y:z.y,layer:T.layer,collidesWith:T.collidesWith,layerBit:0,collidesWithMask:0,shape:g,halfWidth:0,halfHeight:0,radius:0},K[M]=L;if(!h(L,F.id,z.x,z.y,T.layer,T.collidesWith,Z,W))continue;M++}if(!U)$=V.tryGetResource("spatialIndex"),U=!0;u(K,M,O,$,KJ,V.eventBus)})})}import{definePlugin as ZJ}from"ecspresso";var D={normalX:0,normalY:0,normalZ:0,depth:0},I=0,S=1,s=X("3D collision"),UJ=s.getLayerBit,FJ=s.getCollidesWithMask;function i(J,Q,N,j,G,K,O,$,U){if(J.entityId=Q,J.layer=K,J.collidesWith=O,J.layerBit=UJ(K),J.collidesWithMask=FJ(O),$)return J.x=N+($.offsetX??0),J.y=j+($.offsetY??0),J.z=G+($.offsetZ??0),J.shape=I,J.halfWidth=$.width/2,J.halfHeight=$.height/2,J.halfDepth=$.depth/2,J.radius=0,!0;if(U)return J.x=N+(U.offsetX??0),J.y=j+(U.offsetY??0),J.z=G+(U.offsetZ??0),J.shape=S,J.halfWidth=0,J.halfHeight=0,J.halfDepth=0,J.radius=U.radius,!0;return!1}function qJ(J,Q,N,j,G,K,O,$,U,q,V,M,F){let z=O-J,T=$-Q,Z=U-N,W=j+q-Math.abs(z),L=G+V-Math.abs(T),R=K+M-Math.abs(Z);if(W<=0||L<=0||R<=0)return!1;if(W<=L&&W<=R)return F.normalX=z>=0?1:-1,F.normalY=0,F.normalZ=0,F.depth=W,!0;if(L<=R)return F.normalX=0,F.normalY=T>=0?1:-1,F.normalZ=0,F.depth=L,!0;return F.normalX=0,F.normalY=0,F.normalZ=Z>=0?1:-1,F.depth=R,!0}function MJ(J,Q,N,j,G,K,O,$,U){let q=G-J,V=K-Q,M=O-N,F=q*q+V*V+M*M,z=j+$;if(F>=z*z)return!1;let T=Math.sqrt(F);if(T===0)return U.normalX=1,U.normalY=0,U.normalZ=0,U.depth=z,!0;return U.normalX=q/T,U.normalY=V/T,U.normalZ=M/T,U.depth=z-T,!0}function l(J,Q,N,j,G,K,O,$,U,q,V){let M=Math.max(J-j,Math.min(O,J+j)),F=Math.max(Q-G,Math.min($,Q+G)),z=Math.max(N-K,Math.min(U,N+K)),T=O-M,Z=$-F,W=U-z,L=T*T+Z*Z+W*W;if(L>=q*q)return!1;if(L===0){let m=O-(J-j),C=J+j-O,w=$-(Q-G),_=Q+G-$,x=U-(N-K),v=N+K-U,P=Math.min(m,C,w,_,x,v);if(P===C)return V.normalX=1,V.normalY=0,V.normalZ=0,V.depth=C+q,!0;if(P===m)return V.normalX=-1,V.normalY=0,V.normalZ=0,V.depth=m+q,!0;if(P===_)return V.normalX=0,V.normalY=1,V.normalZ=0,V.depth=_+q,!0;if(P===w)return V.normalX=0,V.normalY=-1,V.normalZ=0,V.depth=w+q,!0;if(P===v)return V.normalX=0,V.normalY=0,V.normalZ=1,V.depth=v+q,!0;return V.normalX=0,V.normalY=0,V.normalZ=-1,V.depth=x+q,!0}let R=Math.sqrt(L);return V.normalX=T/R,V.normalY=Z/R,V.normalZ=W/R,V.depth=q-R,!0}function t(J,Q,N){if(J.shape===I&&Q.shape===I)return qJ(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===S&&Q.shape===S)return MJ(J.x,J.y,J.z,J.radius,Q.x,Q.y,Q.z,Q.radius,N);if(J.shape===I&&Q.shape===S)return l(J.x,J.y,J.z,J.halfWidth,J.halfHeight,J.halfDepth,Q.x,Q.y,Q.z,Q.radius,N);if(!l(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 A=[],r=!1,TJ=50;function e(J,Q,N,j,G,K){if(j)LJ(J,Q,N,j,G,K);else zJ(J,Q,G,K)}function zJ(J,Q,N,j){if(!r&&Q>=TJ)r=!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 G=0;G<Q;G++){let K=J[G];if(!K)continue;for(let O=G+1;O<Q;O++){let $=J[O];if(!$)continue;if((K.collidesWithMask&$.layerBit|$.collidesWithMask&K.layerBit)===0)continue;if(!t(K,$,D))continue;N(K,$,D,j)}}}function LJ(J,Q,N,j,G,K){N.clear();for(let O=0;O<Q;O++){let $=J[O];if(!$)continue;N.set($.entityId,$)}for(let O=0;O<Q;O++){let $=J[O];if(!$)continue;let U=$.shape===I?$.halfWidth:$.radius,q=$.shape===I?$.halfHeight:$.radius,V=$.shape===I?$.halfDepth:$.radius;A.length=0,j.queryBoxInto($.x-U,$.y-q,$.z-V,$.x+U,$.y+q,$.z+V,A,$.entityId);for(let M of A){let F=N.get(M);if(!F)continue;if(($.collidesWithMask&F.layerBit|F.collidesWithMask&$.layerBit)===0)continue;if(!t($,F,D))continue;G($,F,D,K)}}}function BJ(J,Q,N,j,G,K){let O={width:J,height:Q,depth:N};if(j!==void 0)O.offsetX=j;if(G!==void 0)O.offsetY=G;if(K!==void 0)O.offsetZ=K;return{aabb3DCollider:O}}function AJ(J,Q,N,j){let G={radius:J};if(Q!==void 0)G.offsetX=Q;if(N!==void 0)G.offsetY=N;if(j!==void 0)G.offsetZ=j;return{sphereCollider:G}}var k={entityA:0,entityB:0,layerA:"",layerB:"",normalX:0,normalY:0,normalZ:0,depth:0};function WJ(J,Q,N,j){k.entityA=J.entityId,k.entityB=Q.entityId,k.layerA=J.layer,k.layerB=Q.layer,k.normalX=N.normalX,k.normalY=N.normalY,k.normalZ=N.normalZ,k.depth=N.depth,j.publish("collision3D",k)}function xJ(J){let{systemGroup:Q="physics",priority:N=0,phase:j="postUpdate"}=J;return ZJ("collision3D").withComponentTypes().withEventTypes().withLabels().withGroups().requires().install((G)=>{let K=[],O=new Map,$,U=!1;G.addSystem("collision3D-detection").setPriority(N).inPhase(j).inGroup(Q).addQuery("collidables",{with:["worldTransform3D","collisionLayer"]}).setProcess(({queries:q,ecs:V})=>{let M=0;for(let F of q.collidables){let{worldTransform3D:z,collisionLayer:T}=F.components,Z=V.getComponent(F.id,"aabb3DCollider"),W=Z?void 0:V.getComponent(F.id,"sphereCollider");if(!Z&&!W)continue;let L=K[M];if(!L)L={entityId:F.id,x:z.x,y:z.y,z:z.z,layer:T.layer,collidesWith:T.collidesWith,layerBit:0,collidesWithMask:0,shape:I,halfWidth:0,halfHeight:0,halfDepth:0,radius:0},K[M]=L;if(!i(L,F.id,z.x,z.y,z.z,T.layer,T.collidesWith,Z,W))continue;M++}if(!U)$=V.tryGetResource("spatialIndex3D"),U=!0;e(K,M,O,$,WJ,V.eventBus)})})}export{jJ as defineCollisionLayers,AJ as createSphereCollider,GJ as createCollisionPairHandler,c as createCollisionLayer,xJ as createCollision3DPlugin,BJ as createAABB3DCollider};
|
|
2
2
|
|
|
3
|
-
//# debugId=
|
|
3
|
+
//# debugId=397322863DC03B6264756E2164756E21
|
|
4
4
|
//# sourceMappingURL=collision3D.js.map
|