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.
TypeScript 2d-game-engine3d3d-game-engineandroidcppecsgame-editorgame-enginegamedeviostypescriptwebassemblywebglwebgpuwechat-minigame
feat(editor): convert colliders between box / circle / polygon in place
yhhb61d5f7e4d39
diff --git a/desktop/src/engine/SceneCommands.ts b/desktop/src/engine/SceneCommands.tsindex e6b053196..5a3be6044 100644--- a/desktop/src/engine/SceneCommands.ts+++ b/desktop/src/engine/SceneCommands.ts@@ -18,6 +18,7 @@ import {clampFieldValue,} from './schema';import { normalizeFolder, folderParent, isFolderUnder, rebaseFolder } from '@/outliner/folders';+import { convertColliderData, COLLIDER_SHAPE_COMP, COMP_COLLIDER_SHAPE, type ColliderShapeKind } from './colliderConvert';type SceneEntity = SceneData['entities'][number];type SceneComponent = SceneEntity['components'][number];@@ -1025,6 +1026,40 @@ export class SceneCommandsImpl {this.history.batch(`Remove ${prettyLabel(compName)}`, ops);}+ /**+ * Convert an entity's collider to another authorable shape (box / circle / polygon),+ * preserving material / sensor / filter / enable and re-deriving the geometry so the+ * shape stays where it was drawn (see {@link convertColliderData}). One undo step.+ */+ convertCollider(sourceId: EntityId, toShape: ColliderShapeKind): void {+ const op = this.convertColliderOp_(sourceId, toShape);+ if (op) this.history.record('Convert Collider', op.forward, op.reverse);+ }++ /** Convert the collider on many entities (multi-select) as ONE undo step. */+ convertColliderMany(sourceIds: readonly EntityId[], toShape: ColliderShapeKind): void {+ const ops = sourceIds.map((id) => this.convertColliderOp_(id, toShape)).filter((o): o is UndoOp => !!o);+ if (ops.length) this.history.batch('Convert Collider', ops);+ }++ /** Eagerly swap the entity's current convertible collider (box/circle/polygon) for+ * `toShape`, returning the undo op. Null when it has none / is already that shape. */+ private convertColliderOp_(sourceId: EntityId, toShape: ColliderShapeKind): UndoOp | null {+ const cur = this.model.entityBySource(sourceId)?.components.find((c) => COMP_COLLIDER_SHAPE[c.type]);+ if (!cur) return null;+ const toComp = COLLIDER_SHAPE_COMP[toShape];+ if (cur.type === toComp) return null;+ const fromComp = cur.type;+ const oldData = structuredClone(cur.data) as Record<string, unknown>;+ const newData = convertColliderData(fromComp, toComp, oldData, this.defaultDataFor(toComp));+ this.model.removeComponent(sourceId, fromComp);+ this.model.setComponent(sourceId, toComp, structuredClone(newData));+ return {+ forward: () => { this.model.removeComponent(sourceId, fromComp); this.model.setComponent(sourceId, toComp, structuredClone(newData)); },+ reverse: () => { this.model.removeComponent(sourceId, toComp); this.model.setComponent(sourceId, fromComp, structuredClone(oldData)); },+ };+ }+/*** Paste a copied component's values onto every selected entity that has that* component (the Details "Paste Values"). Wholesale data replacement, one undodiff --git a/desktop/src/engine/colliderConvert.ts b/desktop/src/engine/colliderConvert.tsnew file mode 100644index 000000000..01c3c1afc--- /dev/null+++ b/desktop/src/engine/colliderConvert.ts@@ -0,0 +1,112 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file colliderConvert.ts+ * @brief Convert a collider between the three authorable shapes (box / circle / polygon)+ * without losing what matters: material (density/friction/restitution), sensor,+ * collision filter (categoryBits/maskBits) and enable carry across unchanged, and+ * the geometry is re-derived so the shape stays where it was drawn — a box/circle+ * offset bakes into the polygon's vertices, and a polygon's AABB centre comes back+ * out as an offset. Pure: `SceneCommands.convertCollider` wraps it in one undoable+ * model swap. capsule / segment / chain aren't offered (rare) — this is the+ * Box↔Circle↔Polygon triangle.+ */++export type ColliderShapeKind = 'box' | 'circle' | 'polygon';++/** The three convertible shapes ↔ their component names. */+export const COLLIDER_SHAPE_COMP: Record<ColliderShapeKind, string> = {+ box: 'BoxCollider',+ circle: 'CircleCollider',+ polygon: 'PolygonCollider',+};+/** Component name → shape kind, for the convertible three (undefined for the rest). */+export const COMP_COLLIDER_SHAPE: Record<string, ColliderShapeKind | undefined> = {+ BoxCollider: 'box',+ CircleCollider: 'circle',+ PolygonCollider: 'polygon',+};++// Material + sensor + filter + enable — carried across a conversion verbatim. Every+// convertible collider has all of these (chain lacks some, but chain isn't convertible).+const SHARED_KEYS = ['density', 'friction', 'restitution', 'isSensor', 'categoryBits', 'maskBits', 'enabled'] as const;++// Segments when sampling a circle into a polygon — smooth enough to read as round.+const CIRCLE_SEGMENTS = 16;++interface Vec2 { x: number; y: number }+const v = (x: number, y: number): Vec2 => ({ x, y });++function num(x: unknown, d: number): number {+ return typeof x === 'number' && Number.isFinite(x) ? x : d;+}+function vec(x: unknown, d: Vec2 = v(0, 0)): Vec2 {+ return x && typeof x === 'object' && 'x' in x && 'y' in x+ ? v(num((x as Vec2).x, d.x), num((x as Vec2).y, d.y))+ : d;+}+function vecArray(x: unknown): Vec2[] {+ return Array.isArray(x) ? x.map((p) => vec(p)) : [];+}+function boxVerts(c: Vec2, h: Vec2): Vec2[] {+ return [v(c.x - h.x, c.y - h.y), v(c.x + h.x, c.y - h.y), v(c.x + h.x, c.y + h.y), v(c.x - h.x, c.y + h.y)];+}++/**+ * The source collider abstracted to a common form: a centre (its offset), an AABB+ * half-size, a representative radius, and its outline vertices RELATIVE TO THE ENTITY+ * ORIGIN (offset baked in). Every target shape is realized from this, so a conversion+ * keeps the shape where it sat.+ */+function abstractGeometry(fromComp: string, d: Record<string, unknown>): { center: Vec2; half: Vec2; radius: number; verts: Vec2[] } {+ if (fromComp === 'CircleCollider') {+ const r = num(d.radius, 0.5);+ const o = vec(d.offset);+ const verts: Vec2[] = [];+ for (let i = 0; i < CIRCLE_SEGMENTS; i++) {+ const a = (i / CIRCLE_SEGMENTS) * Math.PI * 2;+ verts.push(v(o.x + r * Math.cos(a), o.y + r * Math.sin(a)));+ }+ return { center: o, half: v(r, r), radius: r, verts };+ }+ if (fromComp === 'PolygonCollider') {+ const verts = vecArray(d.vertices);+ if (verts.length === 0) return { center: v(0, 0), half: v(0.5, 0.5), radius: 0.5, verts: boxVerts(v(0, 0), v(0.5, 0.5)) };+ let minX = Infinity, minY = Infinity, maxX = -Infinity, maxY = -Infinity;+ for (const p of verts) { minX = Math.min(minX, p.x); minY = Math.min(minY, p.y); maxX = Math.max(maxX, p.x); maxY = Math.max(maxY, p.y); }+ const center = v((minX + maxX) / 2, (minY + maxY) / 2);+ const half = v((maxX - minX) / 2, (maxY - minY) / 2);+ let radius = 0;+ for (const p of verts) radius = Math.max(radius, Math.hypot(p.x - center.x, p.y - center.y));+ return { center, half, radius: radius || Math.max(half.x, half.y), verts };+ }+ // BoxCollider (or anything box-like): halfExtents + offset.+ const he = vec(d.halfExtents, v(0.5, 0.5));+ const o = vec(d.offset);+ return { center: o, half: he, radius: Math.max(he.x, he.y), verts: boxVerts(o, he) };+}++/** Realize the abstract geometry as the target collider's geometry fields. */+function realizeGeometry(toComp: string, g: { center: Vec2; half: Vec2; radius: number; verts: Vec2[] }): Record<string, unknown> {+ if (toComp === 'CircleCollider') return { radius: g.radius, offset: v(g.center.x, g.center.y) };+ if (toComp === 'PolygonCollider') return { vertices: g.verts.map((p) => v(p.x, p.y)) };+ return { halfExtents: v(g.half.x, g.half.y), offset: v(g.center.x, g.center.y) }; // Box+}++/**+ * The target collider's FULL data when converting `fromComp` → `toComp`: start from the+ * target's defaults (`toDefaults`), keep the shared material / sensor / filter / enable+ * fields the source set, then overwrite the geometry re-derived from the source. Pure —+ * no engine or model access; the caller supplies the target defaults.+ */+export function convertColliderData(+ fromComp: string,+ toComp: string,+ from: Record<string, unknown>,+ toDefaults: Record<string, unknown>,+): Record<string, unknown> {+ const out: Record<string, unknown> = { ...toDefaults };+ for (const k of SHARED_KEYS) if (k in from && k in out) out[k] = from[k];+ Object.assign(out, realizeGeometry(toComp, abstractGeometry(fromComp, from)));+ return out;+}diff --git a/desktop/src/i18n/messages/details.ts b/desktop/src/i18n/messages/details.tsindex ad785fa1e..ed8966a7f 100644--- a/desktop/src/i18n/messages/details.ts+++ b/desktop/src/i18n/messages/details.ts@@ -218,6 +218,10 @@ export const detailsMessages = defineMessages({'det.resetDefaults': { en: 'Reset to Defaults', zh: '重置为默认值' },'det.removeComponent': { en: 'Remove Component', zh: '移除组件' },'det.removeComponentN': { en: 'Remove Component ({count})', zh: '移除组件({count})' },+ 'det.colliderShape': { en: 'Shape', zh: '形状' },+ 'det.shapeBox': { en: 'Box', zh: '矩形' },+ 'det.shapeCircle': { en: 'Circle', zh: '圆形' },+ 'det.shapePolygon': { en: 'Polygon', zh: '多边形' },// — Add Component picker (AddComponentMenu.tsx) —'det.addComponentAria': { en: 'Add component', zh: '添加组件' },diff --git a/desktop/src/panels/Details.tsx b/desktop/src/panels/Details.tsxindex 79e98a80f..bdec4af3d 100644--- a/desktop/src/panels/Details.tsx+++ b/desktop/src/panels/Details.tsx@@ -8,11 +8,13 @@ import {Check,ChevronDown,ChevronRight,+ Circle,Code2,Component as ComponentIcon,Copy,ClipboardPaste,Filter,+ Hexagon,FolderOpen,Image as ImageIcon,MoreHorizontal,@@ -30,6 +32,7 @@ import {type LucideIcon,} from 'lucide-react';import { AssetIcon } from '@/components/icons';+import { COMP_COLLIDER_SHAPE, type ColliderShapeKind } from '@/engine/colliderConvert';import { AudioWavePreview } from '@/components/AudioWavePreview';import { Toasts } from '@/store/Toasts';import { baseName, assetTypeOf, IMAGE_RE } from '@/project/assetMeta';@@ -73,7 +76,7 @@ import { NumField, useScrub, fmt, type ControlGesture } from '@/components/NumFiimport { Popover, usePopover } from '@/components/Popover';import { SearchField } from '@/components/SearchField';import { Select } from '@/components/Select';-import { Segmented } from '@/components/Segmented';+import { Segmented, type SegmentedOption } from '@/components/Segmented';import { AddComponentMenu } from '@/components/AddComponentMenu';import type { InspectorComponent, InspectorField, InspectorFieldValue, EntityId, NodeKind, EnumOption, AssetType, GradientValue, GradientStop, CurveValue, CurveKey, DimensionValue } from '@/types';@@ -1313,6 +1316,35 @@ function FlowLayoutControls({ entities, comp }: { entities: EntityId[]; comp: In* never shows a meaningless "Custom" anchor; it shows how it sits in its parent's* flex layout instead. The mode switch writes `position` (flipping to Absolute bakes* the current on-screen box into px insets — see SceneCommands.setField). */+// The convertible collider shapes, shown as a segmented switch on the collider card's+// header. Converting preserves material / sensor / filter and re-derives geometry (see+// SceneCommands.convertCollider) — you can start with a box and turn it into a slope+// polygon without losing what you set.+const COLLIDER_SHAPE_OPTIONS: SegmentedOption<ColliderShapeKind>[] = [+ { value: 'box', label: t('det.shapeBox'), icon: <Square size={11} />, title: t('det.shapeBox') },+ { value: 'circle', label: t('det.shapeCircle'), icon: <Circle size={11} />, title: t('det.shapeCircle') },+ { value: 'polygon', label: t('det.shapePolygon'), icon: <Hexagon size={11} />, title: t('det.shapePolygon') },+];++// Shape switch for a box/circle/polygon collider card — click another shape to convert+// the collider on every selected entity (one undo step). Null for non-convertible cards.+function ColliderShapeControl({ entities, current }: { entities: EntityId[]; current: string }) {+ const kind = COMP_COLLIDER_SHAPE[current];+ if (!kind) return null;+ return (+ <div className="collider-shape">+ <span className="collider-shape-lbl">{t('det.colliderShape')}</span>+ <Segmented+ value={kind}+ options={COLLIDER_SHAPE_OPTIONS}+ ariaLabel={t('det.colliderShape')}+ grow+ onChange={(to) => { if (to !== kind) SceneCommands.convertColliderMany(entities, to); }}+ />+ </div>+ );+}+function UILayoutControl({ entities, comp }: { entities: EntityId[]; comp: InspectorComponent }) {const posField = comp.fields.find((f) => f.key === 'position');const absolute = Number(posField?.value ?? 0) === UIPositionType.Absolute;@@ -2636,7 +2668,13 @@ function EditorDetails() {onToggle={() => toggle(comp.name)}onMore={(e, name) => setCompMenu({ x: e.clientX, y: e.clientY, comp: name })}action={uiNodeCanvasAction(ids, comp)}- extra={comp.name === 'UINode' ? <UILayoutControl entities={ids} comp={comp} /> : undefined}+ extra={+ comp.name === 'UINode'+ ? <UILayoutControl entities={ids} comp={comp} />+ : COMP_COLLIDER_SHAPE[comp.name]+ ? <ColliderShapeControl entities={ids} current={comp.name} />+ : undefined+ }hideFields={comp.name === 'UINode'? uiLayoutOwnedFields(diff --git a/desktop/src/theme/inspector.css b/desktop/src/theme/inspector.cssindex 615b8158a..ff899e65a 100644--- a/desktop/src/theme/inspector.css+++ b/desktop/src/theme/inspector.css@@ -75,6 +75,10 @@.comp-notice { margin: 6px 8px 0; padding: 5px 8px; font-size: var(--fs-2xs); line-height: 1.45; color: var(--warn); background: rgba(214, 166, 90, 0.10); border: 1px solid rgba(214, 166, 90, 0.25); border-radius: var(--r-sm); }.comp-action { margin: 6px 8px 0; padding: 4px 8px; width: calc(100% - 16px); font-size: var(--fs-2xs); color: var(--text); background: var(--srf-3); border: 1px solid var(--border); border-radius: var(--r-sm); cursor: pointer; transition: background var(--t-fast), border-color var(--t-fast); }.comp-action:hover { background: var(--srf-4); border-color: var(--acc); }+/* Collider shape switch (Box/Circle/Polygon) on a collider card header — convert in place. */+.collider-shape { display: flex; align-items: center; gap: 8px; margin: 6px 8px 2px; }+.collider-shape-lbl { flex: 0 0 auto; font-size: var(--fs-2xs); color: var(--text-dim); }+.collider-shape .seg { flex: 1; }/* Anchor control (UINode): a live preview of where the element sits in its parent,beside two named Horizontal/Vertical pickers. Each axis is an independent labelleddiff --git a/desktop/tests/collider-convert.test.ts b/desktop/tests/collider-convert.test.tsnew file mode 100644index 000000000..1650266ab--- /dev/null+++ b/desktop/tests/collider-convert.test.ts@@ -0,0 +1,80 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file Collider shape conversion (unified-collision Phase 4): Box↔Circle↔Polygon+ * conversion preserves material / sensor / filter / enable and re-derives geometry+ * so the shape stays where it was drawn (offset ↔ polygon-vertex / AABB centre).+ */+import { describe, it, expect } from 'vitest';+import { convertColliderData, COMP_COLLIDER_SHAPE, COLLIDER_SHAPE_COMP } from '@/engine/colliderConvert';++const boxDef = { halfExtents: { x: 0.5, y: 0.5 }, offset: { x: 0, y: 0 }, radius: 0.05, density: 1, friction: 0.3, restitution: 0, isSensor: false, enabled: true, categoryBits: 1, maskBits: 65535 };+const circleDef = { radius: 0.5, offset: { x: 0, y: 0 }, density: 1, friction: 0.3, restitution: 0, isSensor: false, enabled: true, categoryBits: 1, maskBits: 65535 };+const polyDef = { vertices: [] as Array<{ x: number; y: number }>, radius: 0.05, density: 1, friction: 0.3, restitution: 0, isSensor: false, enabled: true, categoryBits: 1, maskBits: 65535 };++describe('collider shape maps', () => {+ it('the three convertible shapes round-trip name ↔ kind', () => {+ expect(COMP_COLLIDER_SHAPE.BoxCollider).toBe('box');+ expect(COMP_COLLIDER_SHAPE.CircleCollider).toBe('circle');+ expect(COMP_COLLIDER_SHAPE.PolygonCollider).toBe('polygon');+ expect(COMP_COLLIDER_SHAPE.ChainCollider).toBeUndefined(); // not offered+ expect(COLLIDER_SHAPE_COMP.polygon).toBe('PolygonCollider');+ });+});++describe('convertColliderData — geometry preservation', () => {+ const box = { ...boxDef, halfExtents: { x: 2, y: 1 }, offset: { x: 1, y: 0.5 } };++ it('box → circle: radius covers the box (max half extent), offset kept', () => {+ const r = convertColliderData('BoxCollider', 'CircleCollider', box, circleDef);+ expect(r.radius).toBe(2);+ expect(r.offset).toEqual({ x: 1, y: 0.5 });+ });++ it('box → polygon: four corners with the offset baked in, no offset field', () => {+ const r = convertColliderData('BoxCollider', 'PolygonCollider', box, polyDef);+ expect(r.vertices).toEqual([{ x: -1, y: -0.5 }, { x: 3, y: -0.5 }, { x: 3, y: 1.5 }, { x: -1, y: 1.5 }]);+ expect(r.offset).toBeUndefined();+ });++ it('circle → box: square half extents = radius, offset kept', () => {+ const c = { ...circleDef, radius: 1.5, offset: { x: -2, y: 0 } };+ const r = convertColliderData('CircleCollider', 'BoxCollider', c, boxDef);+ expect(r.halfExtents).toEqual({ x: 1.5, y: 1.5 });+ expect(r.offset).toEqual({ x: -2, y: 0 });+ });++ it('circle → polygon: sampled to 16 vertices, first at +radius', () => {+ const c = { ...circleDef, radius: 1, offset: { x: 0, y: 0 } };+ const r = convertColliderData('CircleCollider', 'PolygonCollider', c, polyDef);+ expect((r.vertices as unknown[]).length).toBe(16);+ expect((r.vertices as Array<{ x: number; y: number }>)[0]).toEqual({ x: 1, y: 0 });+ });++ it('polygon → box: AABB centre becomes the offset, AABB half the extents', () => {+ const poly = { ...polyDef, vertices: [{ x: 0, y: 0 }, { x: 4, y: 0 }, { x: 4, y: 2 }] };+ const r = convertColliderData('PolygonCollider', 'BoxCollider', poly, boxDef);+ expect(r.offset).toEqual({ x: 2, y: 1 });+ expect(r.halfExtents).toEqual({ x: 2, y: 1 });+ });++ it('polygon → circle: radius = farthest vertex from the AABB centre', () => {+ const poly = { ...polyDef, vertices: [{ x: 0, y: 0 }, { x: 4, y: 0 }, { x: 4, y: 2 }] };+ const r = convertColliderData('PolygonCollider', 'CircleCollider', poly, circleDef);+ expect(r.offset).toEqual({ x: 2, y: 1 });+ expect(r.radius as number).toBeCloseTo(Math.sqrt(5)); // (2,1)→(0,0) = √5+ });+});++describe('convertColliderData — material / sensor / filter carried across', () => {+ it('keeps density / friction / restitution / isSensor / categoryBits / maskBits / enabled', () => {+ const box = { ...boxDef, density: 3, friction: 0.8, restitution: 0.9, isSensor: true, categoryBits: 4, maskBits: 8, enabled: false };+ const r = convertColliderData('BoxCollider', 'PolygonCollider', box, polyDef);+ expect(r).toMatchObject({ density: 3, friction: 0.8, restitution: 0.9, isSensor: true, categoryBits: 4, maskBits: 8, enabled: false });+ });++ it('a field the target lacks (box radius/offset) is dropped, not forced onto polygon', () => {+ const r = convertColliderData('BoxCollider', 'PolygonCollider', boxDef, polyDef);+ expect('offset' in r).toBe(false); // polygon has no offset default → never added+ });+});diff --git a/desktop/tests/engine-commands.test.ts b/desktop/tests/engine-commands.test.tsindex 079b4bae3..6ce3b34e0 100644--- a/desktop/tests/engine-commands.test.ts+++ b/desktop/tests/engine-commands.test.ts@@ -14,7 +14,7 @@* ids; the World is asserted via session.model.runtimeFor.*/import { describe, it, expect, beforeAll, beforeEach, afterEach, vi } from 'vitest';-import { App, Transform, Parent, Children, Sprite, Interactable, PolygonCollider, BUILTIN_UI_PREFABS } from 'esengine';+import { App, Transform, Parent, Children, Sprite, Interactable, BoxCollider, CircleCollider, PolygonCollider, BUILTIN_UI_PREFABS } from 'esengine';import type { ESEngineModule } from 'esengine';import { loadWasmModule, HAS_WASM } from './helpers/loadWasm';@@ -120,6 +120,26 @@ describe.skipIf(!HAS_WASM)('SceneCommands / SceneQuery (headless World)', () =>expect((host.world.get(e, PolygonCollider).vertices as ArrayLike<unknown>).length).toBe(defLen);});+ it('convertCollider swaps the collider shape in the World, keeps material, re-derives geometry; undo restores', () => {+ const id = S.commands.addEntity()!;+ const e = rt(id);+ S.commands.addComponent(id, 'BoxCollider');+ S.commands.setField(id, 'BoxCollider', 'halfExtents', 'vec2', [2, 1]);+ S.commands.setField(id, 'BoxCollider', 'friction', 'number', 0.9);+ expect(host.world.has(e, BoxCollider)).toBe(true);++ S.commands.convertCollider(id, 'circle'); // box → circle+ expect(host.world.has(e, BoxCollider)).toBe(false);+ expect(host.world.has(e, CircleCollider)).toBe(true);+ expect((host.world.get(e, CircleCollider) as { radius: number }).radius).toBeCloseTo(2); // max half extent+ expect((host.world.get(e, CircleCollider) as { friction: number }).friction).toBeCloseTo(0.9); // material carried++ S.history.undo(); // one step back to the box+ expect(host.world.has(e, CircleCollider)).toBe(false);+ expect(host.world.has(e, BoxCollider)).toBe(true);+ expect((host.world.get(e, BoxCollider) as { halfExtents: { x: number; y: number } }).halfExtents).toMatchObject({ x: 2, y: 1 });+ });+it('deleteEntity removes the entity; undo re-creates it', () => {const id = S.commands.addEntity()!;expect(host.world.getAllEntities().length).toBe(1);