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.

feat(editor): joint anchors and slide axes edit by direct drag

yhh7135e3df0975
diff --git a/desktop/src/engine/Reconciler.ts b/desktop/src/engine/Reconciler.ts
index 04eff7825..252355377 100644
--- a/desktop/src/engine/Reconciler.ts
+++ b/desktop/src/engine/Reconciler.ts
@@ -6,7 +6,7 @@ import type { EntityId } from '@/types';
import { EngineHost } from './EngineHost';
import { PerfMonitor } from './PerfMonitor';
import { SceneModel, SceneModelImpl, type ModelEvent } from './SceneModel';
-import { assetFieldType, spineSlotType, componentByName, componentDefaults, isRenderComponent, componentEnable, readonlyFieldsFor, type AnyComp, type WorldT } from './schema';
+import { assetFieldType, spineSlotType, componentByName, componentDefaults, componentEntityFields, isRenderComponent, componentEnable, readonlyFieldsFor, type AnyComp, type WorldT } from './schema';
/**
* Projects the model into the World.
@@ -216,6 +216,19 @@ export class ReconcilerImpl {
const list = Array.isArray(refs) ? refs.filter((r): r is string => typeof r === 'string' && r !== '') : [];
if (list.length > 0) TilemapLiveSync.setLayerTilesets(rt, list);
}
+ // …and re-project any spawned component whose entity-reference fields point at
+ // THIS entity — undo-of-delete can restore a joint's connected body after the
+ // joint itself, the same ordering the child re-link above repairs for the
+ // hierarchy. Without this, that component's World copy keeps a dead runtime id.
+ for (const other of this.model.allSourceEntities()) {
+ if (other.id === sourceId || this.model.runtimeFor(other.id) == null) continue;
+ for (const comp of other.components) {
+ const refs = componentEntityFields(componentByName(comp.type));
+ if (refs.some((f) => (comp.data as Record<string, unknown>)[f] === sourceId)) {
+ this.projectComponent(other.id, comp.type);
+ }
+ }
+ }
}
private despawnEntity(sourceId: number): void {
@@ -322,6 +335,17 @@ export class ReconcilerImpl {
}
out[key] = this.resolveFieldValue(type, key, data[key]);
}
+ // Entity-reference fields hold SOURCE ids in the model; the World speaks
+ // RUNTIME ids (the bulk load remaps via the scene loader's remapEntityFields).
+ // Re-projection must speak the same domain — a verbatim copy would flip an
+ // edited component's refs back into source ids, which the World reads as
+ // whatever runtime entity happens to wear that number. `v > 0` mirrors the
+ // loader: 0 is the SDK's INVALID_ENTITY sentinel, so a ref to source id 0
+ // stays inert on both paths (a known loader-convention quirk).
+ for (const f of componentEntityFields(def)) {
+ const v = out[f];
+ if (typeof v === 'number' && v > 0) out[f] = this.model.runtimeFor(v) ?? -1;
+ }
return out;
}
diff --git a/desktop/src/engine/SceneModel.ts b/desktop/src/engine/SceneModel.ts
index 11a255cc2..9dc050781 100644
--- a/desktop/src/engine/SceneModel.ts
+++ b/desktop/src/engine/SceneModel.ts
@@ -428,6 +428,11 @@ export class SceneModelImpl {
return this.data?.entities.find((e) => e.id === sourceId);
}
+ /** Every source entity record (live references, read-only by convention). */
+ allSourceEntities(): readonly SceneEntity[] {
+ return this.data?.entities ?? [];
+ }
+
/**
* A source id + all its descendants, **parent-before-child** — for recursive
* delete (the World despawns a parent's children too, so the model must remove
diff --git a/desktop/src/engine/ViewportController.ts b/desktop/src/engine/ViewportController.ts
index 0a0e53d9d..56a79501b 100644
--- a/desktop/src/engine/ViewportController.ts
+++ b/desktop/src/engine/ViewportController.ts
@@ -47,6 +47,14 @@ interface JointGizmoData {
enabled?: boolean;
}
+// Entity-reference fields in the projected World hold RUNTIME ids — the bulk load
+// remaps them (remapEntityFields) and the Reconciler's projectData mirrors that on
+// every re-projection. -1 (authored none) / 0 (loader INVALID sentinel) = unlinked.
+function jointConnectedRuntime(j: JointGizmoData): EntityId | null {
+ const cid = j.connectedEntity;
+ return typeof cid === 'number' && cid > 0 ? (cid as EntityId) : null;
+}
+
// Structural shape of the engine's CameraView resource (screen<->world).
interface CameraViewLike {
screenToWorld(x: number, y: number): { x: number; y: number } | null;
@@ -679,10 +687,10 @@ export const ViewportController = {
const b = anchorOn(id, j.anchorB ?? { x: 0, y: 0 });
if (!b) return null;
- const cid = j.connectedEntity as EntityId;
+ const cid = jointConnectedRuntime(j);
let a: { x: number; y: number } | null = null;
let axis: { dx: number; dy: number } | null = null;
- if (typeof cid === 'number' && cid >= 0 && world.valid(cid) && world.has(cid, Transform)) {
+ if (cid != null && world.valid(cid) && world.has(cid, Transform)) {
a = anchorOn(cid, j.anchorA ?? { x: 0, y: 0 });
if (j.axis) {
const len = Math.hypot(j.axis.x, j.axis.y);
@@ -703,6 +711,59 @@ export const ViewportController = {
return { b, a, axis, vel, on: j.enabled !== false };
},
+ /**
+ * The local frame a joint-anchor drag converts the cursor into: the world pose of
+ * the body that OWNS the anchor — the joint's entity for `anchorB` ('b'), the
+ * connected entity for `anchorA` ('a'). Null while the connected end is unset (an
+ * inert joint's `a` anchor has no frame to edit in).
+ */
+ jointAnchorFrame(
+ id: EntityId,
+ type: JointGizmoType,
+ end: 'a' | 'b',
+ ): { x: number; y: number; rot: number } | null {
+ const world = EngineHost.world;
+ const def = JOINT_GIZMO_DEFS[type];
+ if (!world || !def || !world.valid(id) || !world.has(id, def) || !world.has(id, Transform)) return null;
+ let eid = id;
+ if (end === 'a') {
+ const cid = jointConnectedRuntime(world.get(id, def) as JointGizmoData);
+ if (cid == null || !world.valid(cid) || !world.has(cid, Transform)) return null;
+ eid = cid;
+ }
+ const t = world.get(eid, Transform);
+ return {
+ x: t.worldPosition.x,
+ y: t.worldPosition.y,
+ rot: quatAngleZ(t.worldRotation as { w: number; x: number; y: number; z: number }),
+ };
+ },
+
+ /**
+ * The frame an axis drag (prismatic/wheel slide direction) works in: the world
+ * point of anchorA plus the CONNECTED body's rotation (the axis lives in body A's
+ * local frame — Box2D localFrameA). Null while unlinked.
+ */
+ jointAxisFrame(
+ id: EntityId,
+ type: JointGizmoType,
+ ): { x: number; y: number; rot: number } | null {
+ const world = EngineHost.world;
+ const def = JOINT_GIZMO_DEFS[type];
+ if (!world || !def || !world.valid(id) || !world.has(id, def)) return null;
+ const j = world.get(id, def) as JointGizmoData;
+ const cid = jointConnectedRuntime(j);
+ if (cid == null || !world.valid(cid) || !world.has(cid, Transform)) return null;
+ const t = world.get(cid, Transform);
+ const rot = quatAngleZ(t.worldRotation as { w: number; x: number; y: number; z: number });
+ const a = j.anchorA ?? { x: 0, y: 0 };
+ return {
+ x: t.worldPosition.x + a.x * Math.cos(rot) - a.y * Math.sin(rot),
+ y: t.worldPosition.y + a.x * Math.sin(rot) + a.y * Math.cos(rot),
+ rot,
+ };
+ },
+
/** Ids of entities carrying a ParticleEmitter — the emitter-gizmo set. */
particleEmitterIds(): EntityId[] {
const world = EngineHost.world;
diff --git a/desktop/src/engine/schema.ts b/desktop/src/engine/schema.ts
index 94d12cb94..9f53fa45b 100644
--- a/desktop/src/engine/schema.ts
+++ b/desktop/src/engine/schema.ts
@@ -64,6 +64,11 @@ export function componentDefaults(def: AnyComp): Record<string, unknown> {
return (def as unknown as { _default: Record<string, unknown> })._default;
}
+/** The component's entity-reference fields (source-id-valued in scene data), [] if none. */
+export function componentEntityFields(def: AnyComp | undefined): readonly string[] {
+ return (def as unknown as { entityFields?: readonly string[] } | undefined)?.entityFields ?? [];
+}
+
// Add-Component picker categories, in display order (the picker is grouped by
// category). Editor-side presentation policy — the engine has no category metadata
// today, so builtins are mapped/heuristic'd here; user/script components are
diff --git a/desktop/src/panels/Viewport.tsx b/desktop/src/panels/Viewport.tsx
index b8068eb97..1af35cd0e 100644
--- a/desktop/src/panels/Viewport.tsx
+++ b/desktop/src/panels/Viewport.tsx
@@ -256,6 +256,66 @@ function startAngleHandleDrag(rt: number, e: ReactPointerEvent): void {
window.addEventListener('pointerup', onUp);
}
+// Drag a joint anchor dot → its anchorA/anchorB vec2 (world px in the owning body's
+// local frame — the convention PhysicsSystem converts to meters with ×invPpu). 'b'
+// edits the joint entity's own anchor, 'a' the connected body's; MotorJoint has no
+// anchors so its dots aren't draggable. Same setField + gesture channel as all
+// on-canvas edits; px round to integers for clean inspector values.
+function startJointAnchorDrag(rt: number, type: JointGizmoType, end: 'a' | 'b', e: ReactPointerEvent): void {
+ if (e.button !== 0) return;
+ const src = SceneModel.sourceFor(rt);
+ const frame = ViewportController.jointAnchorFrame(rt, type, end);
+ if (src == null || !frame) return;
+ e.stopPropagation();
+ const cos = Math.cos(frame.rot), sin = Math.sin(frame.rot);
+ SceneCommands.beginGesture(`${type} anchor`);
+ const onMove = (ev: PointerEvent) => {
+ const w = ViewportController.canvasToWorld(ev.clientX, ev.clientY);
+ if (!w) return;
+ const dx = w.x - frame.x, dy = w.y - frame.y;
+ SceneCommands.setField(src, type, end === 'a' ? 'anchorA' : 'anchorB', 'vec2',
+ [Math.round(dx * cos + dy * sin), Math.round(-dx * sin + dy * cos)]);
+ };
+ const onUp = () => {
+ SceneCommands.endGesture();
+ window.removeEventListener('pointermove', onMove);
+ window.removeEventListener('pointerup', onUp);
+ };
+ window.addEventListener('pointermove', onMove);
+ window.addEventListener('pointerup', onUp);
+}
+
+// Drag the prismatic/wheel axis tip → the slide direction. The axis lives in the
+// CONNECTED body's local frame (Box2D localFrameA); written normalized so the
+// inspector shows a clean unit direction (C++ normalizes anyway).
+function startJointAxisDrag(rt: number, type: JointGizmoType, e: ReactPointerEvent): void {
+ if (e.button !== 0) return;
+ const src = SceneModel.sourceFor(rt);
+ const frame = ViewportController.jointAxisFrame(rt, type);
+ if (src == null || !frame) return;
+ e.stopPropagation();
+ const cos = Math.cos(frame.rot), sin = Math.sin(frame.rot);
+ SceneCommands.beginGesture(`${type} axis`);
+ const onMove = (ev: PointerEvent) => {
+ const w = ViewportController.canvasToWorld(ev.clientX, ev.clientY);
+ if (!w) return;
+ const dx = w.x - frame.x, dy = w.y - frame.y;
+ const lx = dx * cos + dy * sin;
+ const ly = -dx * sin + dy * cos;
+ const len = Math.hypot(lx, ly);
+ if (len < 1e-3) return; // a degenerate direction at the anchor itself — keep the last one
+ const r3 = (v: number) => Math.round((v / len) * 1000) / 1000;
+ SceneCommands.setField(src, type, 'axis', 'vec2', [r3(lx), r3(ly)]);
+ };
+ const onUp = () => {
+ SceneCommands.endGesture();
+ window.removeEventListener('pointermove', onMove);
+ window.removeEventListener('pointerup', onUp);
+ };
+ window.addEventListener('pointermove', onMove);
+ window.addEventListener('pointerup', onUp);
+}
+
// The interactive transform gizmo, drawn from the origin (= the selection pivot, the
// wrapper is translated there each frame). Its geometry mirrors the hit zones in
// gizmo.ts (GIZMO constants) so the handles a user aims at are the handles the tool
@@ -1122,6 +1182,18 @@ export function Viewport() {
axis.style.opacity = '0';
}
}
+ // Axis drag handle (prismatic/wheel only — the element exists just there)
+ // at the +axis tip of the visual line.
+ const axisHandle = svg.querySelector('.jt-axis-handle') as SVGCircleElement | null;
+ if (axisHandle) {
+ if (jg.a && jg.axis) {
+ axisHandle.setAttribute('cx', String(jg.a.x + jg.axis.dx * 26));
+ axisHandle.setAttribute('cy', String(jg.a.y + jg.axis.dy * 26));
+ axisHandle.style.display = '';
+ } else {
+ axisHandle.style.display = 'none';
+ }
+ }
// Motor target velocity: arrow out of the driven body's anchor.
if (jg.vel) {
const L = 30;
@@ -1696,8 +1768,32 @@ export function Viewport() {
<line className="jt-axis" x1="0" y1="0" x2="0" y2="0" />
<line className="jt-vel" x1="0" y1="0" x2="0" y2="0" />
<polygon className="jt-vel-head" points="" />
- <circle className="jt-b" cx="0" cy="0" r="3" />
- <circle className="jt-a" cx="0" cy="0" r="3" />
+ {/* Anchor dots double as drag handles (write anchorB/anchorA in the owning
+ body's local frame) — except for MotorJoint, which has no anchors. */}
+ <circle
+ className={type === 'MotorJoint' ? 'jt-b' : 'jt-b jt-drag'}
+ cx="0"
+ cy="0"
+ r={type === 'MotorJoint' ? 3 : 4}
+ onPointerDown={type === 'MotorJoint' ? undefined : (e) => startJointAnchorDrag(id, type, 'b', e)}
+ />
+ <circle
+ className={type === 'MotorJoint' ? 'jt-a' : 'jt-a jt-drag'}
+ cx="0"
+ cy="0"
+ r={type === 'MotorJoint' ? 3 : 4}
+ onPointerDown={type === 'MotorJoint' ? undefined : (e) => startJointAnchorDrag(id, type, 'a', e)}
+ />
+ {(type === 'PrismaticJoint' || type === 'WheelJoint') && (
+ <circle
+ className="jt-axis-handle"
+ cx="0"
+ cy="0"
+ r="5"
+ style={{ display: 'none' }}
+ onPointerDown={(e) => startJointAxisDrag(id, type, e)}
+ />
+ )}
</svg>
))}
diff --git a/desktop/src/theme/app.css b/desktop/src/theme/app.css
index 90867caeb..2ea0c4498 100644
--- a/desktop/src/theme/app.css
+++ b/desktop/src/theme/app.css
@@ -450,6 +450,22 @@ body.thumb-capture .viewport__play-stop {
stroke: var(--srf-2);
stroke-width: 1.25;
}
+/* Anchor dots as drag handles (anchorA/anchorB); axis tip drags the slide direction. */
+.viewport__joint-gizmo .jt-drag {
+ pointer-events: auto;
+ cursor: move;
+}
+.viewport__joint-gizmo .jt-drag:hover,
+.viewport__joint-gizmo .jt-axis-handle:hover {
+ fill: color-mix(in srgb, var(--gizmo-joint) 70%, white);
+}
+.viewport__joint-gizmo .jt-axis-handle {
+ fill: var(--gizmo-joint);
+ stroke: var(--srf-2);
+ stroke-width: 1.5;
+ pointer-events: auto;
+ cursor: crosshair;
+}
.viewport__joint-gizmo .jt-axis {
stroke: var(--gizmo-joint);
stroke-width: 1.25;