Skip to content

A fast 2D and 3D game engine — TypeScript SDK, C++/WebAssembly core, visual editor. Ship one project to web, desktop, WeChat MiniGames, playable ads, and native Android / iOS.

9.3 KB
Raw Blame
// SPDX-License-Identifier: Apache-2.0
// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
/**
 * @file    Collider2DShape.ts
 * @brief   The single geometry projection over the collider components — the shared
 *          seam for BOTH visualizers (the runtime Physics2DDebugDraw and the editor's
 *          collider gizmo) and for tile-collision overlays. It does NOT touch the
 *          runtime physics model: colliders stay ordinary C++/TS components dispatched
 *          by presence in PhysicsSystem; this only READS them into a shape descriptor,
 *          computes the offset+rotation center once (previously duplicated 3×), and
 *          emits world-space outlines each backend renders in its own primitives.
 *
 * Units: shape fields are physics metres (as stored on the components); `ppu`
 * (pixels-per-unit) scales them to world pixels in shapeCenter / collider2DOutline.
 */
import type { Vec2 } from '../types';
import type { World } from '../ecs/world';
import {
    BoxCollider2D, CircleCollider2D, CapsuleCollider2D,
    SegmentCollider2D, PolygonCollider2D, ChainCollider2D,
} from './PhysicsComponents';
import type {
    BoxCollider2DData, CircleCollider2DData, CapsuleCollider2DData,
    SegmentCollider2DData, PolygonCollider2DData, ChainCollider2DData,
} from './PhysicsComponents';
import { decomposePolygon2D } from './polygonDecompose2D';

/** Semicircle-cap segment count for a capsule outline (matches the legacy debug draw). */
export const CAPSULE_ARC_SEGMENTS = 16;

/** Box2D builds no chain below four points; the editor may not author one either. */
export const MIN_CHAIN_POINTS = 4;

/** A collider's geometry, in physics metres. Offset (box/circle/capsule) is metres too;
 *  segment/polygon/chain carry their points directly and sit at the entity origin. */
export type Collider2DShape =
    | { kind: 'box'; halfExtents: Vec2; offset: Vec2 }
    | { kind: 'circle'; radius: number; offset: Vec2 }
    | { kind: 'capsule'; radius: number; halfHeight: number; offset: Vec2 }
    | { kind: 'segment'; point1: Vec2; point2: Vec2 }
    | { kind: 'polygon'; vertices: Vec2[] }
    | { kind: 'chain'; points: Vec2[]; isLoop: boolean };

/** A shape read off an entity, with the sensor flag the visualizers colour by and
 *  the enabled flag they decide by: a disabled collider is absent from the physics
 *  world, so the runtime overlay skips it while the editor keeps drawing it (you
 *  still author its geometry through the gizmo). */
export interface Collider2DInstance {
    shape: Collider2DShape;
    isSensor: boolean;
    enabled: boolean;
}

/** World-space (pixel) outline: straight runs as polylines + true circles left as
 *  {center, radius} so a backend can stroke them as arcs (SVG <circle> / circleOutline). */
export interface Collider2DOutline {
    polylines: Vec2[][];
    circles: { c: Vec2; r: number }[];
    /**
     * The authored outline where the solver does not have it — a concave polygon's
     * filled-in notch, or vertices past the eight Box2D takes. Absent when what was
     * drawn is what collides; every backend strokes it apart, or the viewport says
     * a shape exists where nothing can be hit.
     */
    declined?: Vec2[][];
}

const ZERO: Vec2 = { x: 0, y: 0 };

/** The collider's local offset in metres (0 for segment/polygon/chain, which have none). */
export function shapeOffset(shape: Collider2DShape): Vec2 {
    return (shape.kind === 'box' || shape.kind === 'circle' || shape.kind === 'capsule')
        ? shape.offset
        : ZERO;
}

/**
 * The shape's world-pixel centre = the entity's world position plus its collider offset
 * (metres × ppu) rotated by the entity angle. Every drawer of a collider goes through
 * here, so a gizmo and the solver cannot disagree about where the shape is.
 */
export function shapeCenter(shape: Collider2DShape, worldPos: Vec2, angle: number, ppu: number): Vec2 {
    const off = shapeOffset(shape);
    const ox = off.x * ppu;
    const oy = off.y * ppu;
    const cos = Math.cos(angle);
    const sin = Math.sin(angle);
    return { x: worldPos.x + ox * cos - oy * sin, y: worldPos.y + ox * sin + oy * cos };
}

/**
 * The shape's outline in world pixels, rotated by `angle` about `center` (see
 * {@link shapeCenter}). Straight-edged shapes return closed/open polylines; a circle
 * returns a single {c, r} for the backend to stroke as an arc.
 */
export function collider2DOutline(shape: Collider2DShape, center: Vec2, angle: number, ppu: number): Collider2DOutline {
    const cos = Math.cos(angle);
    const sin = Math.sin(angle);
    // local (px) → world (px), rotated about center.
    const w = (lx: number, ly: number): Vec2 => ({ x: center.x + lx * cos - ly * sin, y: center.y + lx * sin + ly * cos });

    switch (shape.kind) {
        case 'box': {
            const hx = shape.halfExtents.x * ppu;
            const hy = shape.halfExtents.y * ppu;
            const p = [w(-hx, -hy), w(hx, -hy), w(hx, hy), w(-hx, hy)];
            return { polylines: [[...p, p[0]]], circles: [] };
        }
        case 'circle':
            return { polylines: [], circles: [{ c: center, r: shape.radius * ppu }] };
        case 'capsule': {
            const r = shape.radius * ppu;
            const hh = shape.halfHeight * ppu;
            // One closed loop tracing: left side ↑, top cap arc →, right side ↓, bottom cap
            // arc ← — the exact same segment set the legacy drawCapsule emitted.
            const pts: Vec2[] = [w(-r, -hh), w(-r, hh)];
            for (let i = 1; i <= CAPSULE_ARC_SEGMENTS; i++) {
                const a = (i / CAPSULE_ARC_SEGMENTS) * Math.PI;
                pts.push(w(-r * Math.cos(a), hh + r * Math.sin(a)));
            }
            pts.push(w(r, -hh));
            for (let i = 1; i <= CAPSULE_ARC_SEGMENTS; i++) {
                const a = Math.PI + (i / CAPSULE_ARC_SEGMENTS) * Math.PI;
                pts.push(w(-r * Math.cos(a), -hh + r * Math.sin(a)));
            }
            return { polylines: [pts], circles: [] };
        }
        case 'segment':
            return {
                polylines: [[w(shape.point1.x * ppu, shape.point1.y * ppu), w(shape.point2.x * ppu, shape.point2.y * ppu)]],
                circles: [],
            };
        case 'polygon': {
            const ring = (vs: readonly Vec2[]): Vec2[][] => {
                const p = vs.map((v) => w(v.x * ppu, v.y * ppu));
                return p.length > 0 ? [[...p, p[0]]] : [];
            };
            // The ring is the collision boundary whenever it can be partitioned, and
            // the pieces behind it are how that boundary is built rather than a
            // different shape — so a concave collider draws as one outline, once.
            const { pieces, degenerate } = decomposePolygon2D(shape.vertices);
            if (!degenerate && pieces.length > 0) return { polylines: ring(shape.vertices), circles: [] };
            // It crosses itself, or has no area: what collides is not what was drawn.
            return {
                polylines: pieces.flatMap((piece) => ring(piece)),
                circles: [],
                declined: ring(shape.vertices),
            };
        }
        case 'chain': {
            const p = shape.points.map((v) => w(v.x * ppu, v.y * ppu));
            if (p.length < 2) return { polylines: [], circles: [] };
            return { polylines: [shape.isLoop ? [...p, p[0]] : p], circles: [] };
        }
    }
}

/**
 * Read every collider component present on `entity` into shape descriptors, in the same
 * order PhysicsSystem's addShapeForEntity dispatches (box, circle, capsule, segment,
 * polygon, chain). Chain has no sensor flag, so it reports isSensor: false.
 */
export function readCollider2DShapes(world: World, entity: number): Collider2DInstance[] {
    const out: Collider2DInstance[] = [];
    const isEnabled = (c: { enabled?: boolean }): boolean => c.enabled !== false;
    if (world.has(entity, BoxCollider2D)) {
        const b = world.get(entity, BoxCollider2D) as BoxCollider2DData;
        out.push({ shape: { kind: 'box', halfExtents: b.halfExtents, offset: b.offset }, isSensor: b.isSensor, enabled: isEnabled(b) });
    }
    if (world.has(entity, CircleCollider2D)) {
        const c = world.get(entity, CircleCollider2D) as CircleCollider2DData;
        out.push({ shape: { kind: 'circle', radius: c.radius, offset: c.offset }, isSensor: c.isSensor, enabled: isEnabled(c) });
    }
    if (world.has(entity, CapsuleCollider2D)) {
        const c = world.get(entity, CapsuleCollider2D) as CapsuleCollider2DData;
        out.push({ shape: { kind: 'capsule', radius: c.radius, halfHeight: c.halfHeight, offset: c.offset }, isSensor: c.isSensor, enabled: isEnabled(c) });
    }
    if (world.has(entity, SegmentCollider2D)) {
        const s = world.get(entity, SegmentCollider2D) as SegmentCollider2DData;
        out.push({ shape: { kind: 'segment', point1: s.point1, point2: s.point2 }, isSensor: s.isSensor, enabled: isEnabled(s) });
    }
    if (world.has(entity, PolygonCollider2D)) {
        const p = world.get(entity, PolygonCollider2D) as PolygonCollider2DData;
        out.push({ shape: { kind: 'polygon', vertices: p.vertices }, isSensor: p.isSensor, enabled: isEnabled(p) });
    }
    if (world.has(entity, ChainCollider2D)) {
        const c = world.get(entity, ChainCollider2D) as ChainCollider2DData;
        out.push({ shape: { kind: 'chain', points: c.points, isLoop: c.isLoop }, isSensor: false, enabled: isEnabled(c) });
    }
    return out;
}