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
fix(editor): a rotation you can edit on all three axes
esengine9cf582006bf1
diff --git a/desktop/src/engine/EditorControlSurface.ts b/desktop/src/engine/EditorControlSurface.tsindex 77d65d754..7dcaec0ab 100644--- a/desktop/src/engine/EditorControlSurface.ts+++ b/desktop/src/engine/EditorControlSurface.ts@@ -254,6 +254,7 @@ export function coerceFieldValue(const n = Number(value);return Number.isFinite(n) ? n : fail('degrees as a number');}+case 'bool':// String forms arrive from text transports; "false"/"0" must not read truthy.return typeof value === 'string' ? !['false', '0', ''].includes(value.trim().toLowerCase()) : Boolean(value);@@ -261,10 +262,11 @@ export function coerceFieldValue(case 'select':case 'asset':return typeof value === 'string' ? value : String(value);+ case 'euler':case 'vec2':case 'vec3':case 'vec4': {- const n = declared === 'vec2' ? 2 : declared === 'vec3' ? 3 : 4;+ const n = declared === 'vec2' ? 2 : declared === 'vec4' ? 4 : 3;let v: unknown = value;if (typeof v === 'string') v = parseJsonText(v);if (v !== null && typeof v === 'object' && !Array.isArray(v)) {@@ -272,7 +274,9 @@ export function coerceFieldValue(v = n === 2 ? [o.x, o.y] : n === 3 ? [o.x, o.y, o.z] : [o.x, o.y, o.z, o.w];}if (!Array.isArray(v) || v.length < n || v.slice(0, n).some((c) => typeof c !== 'number' || !Number.isFinite(c))) {- const example = n === 2 ? '[16, 16]' : n === 3 ? '[0, 0, 0]' : '[0, 0, 1, 1]';+ const example = n === 2 ? '[16, 16]'+ : declared === 'euler' ? '[0, 45, 0] (degrees)'+ : n === 3 ? '[0, 0, 0]' : '[0, 0, 1, 1]';return fail(`${n} numbers (e.g. ${example})`);}return v.slice(0, n) as InspectorFieldValue;diff --git a/desktop/src/engine/SceneCommands.ts b/desktop/src/engine/SceneCommands.tsindex 4d614f918..5df4e278b 100644--- a/desktop/src/engine/SceneCommands.ts+++ b/desktop/src/engine/SceneCommands.ts@@ -15,7 +15,8 @@ import {componentDefaults,defaultDataFor,userSchema,- angleZToQuat,+ eulerToQuat,+ setAngleZ,hexToRgba,prettyLabel,clampFieldValue,@@ -153,8 +154,12 @@ export function toModelValue(// A whole Vec2[] replacement (polygon vertices / chain points) — normalized to// plain {x,y} so a dragged vertex writes clean data; coalesced to one undo step.return (value as Array<{ x: number; y: number }>).map((p) => ({ x: p.x, y: p.y }));+ case 'euler':+ return eulerToQuat(value as number[]);+ // Only the Z turn, keeping the other two axes: the rotate gizmo and any+ // caller that thinks in 2D degrees must not flatten a 3D pose.case 'angle':- return angleZToQuat(Number(value));+ return setAngleZ(cur[key] as { x: number; y: number; z: number; w: number } | undefined, Number(value));case 'color':// The hex carries alpha (#rrggbbaa), so it fully describes RGBA.return { ...(cur[key] as object), ...hexToRgba(String(value)) };diff --git a/desktop/src/engine/schema.ts b/desktop/src/engine/schema.tsindex b5cf24bbf..183992dd2 100644--- a/desktop/src/engine/schema.ts+++ b/desktop/src/engine/schema.ts@@ -175,16 +175,55 @@ export const prettyLabel = (key: string) =>.replace(/^./, (c) => c.toUpperCase()).trim();-// 2D rotation lives in a quaternion's z/w; surface it as a Z angle in degrees.-const quatToAngleZ = (q: { z: number; w: number }) =>- Math.round(Math.atan2(q.z, q.w) * 2 * RAD2DEG * 100) / 100;-export const angleZToQuat = (deg: number) => {- const h = (deg * DEG2RAD) / 2;+type Quat = { x: number; y: number; z: number; w: number };++/**+ * A rotation as three degrees, applied X then Y then Z about fixed axes — the+ * order every DCC's inspector shows. A rotation purely about Z reads back as+ * (0, 0, angle) and rebuilds exactly, so 2D content is untouched by this+ * existing; what it adds is the two axes a 2D control silently zeroed.+ */+export const quatToEuler = (q: Quat): [number, number, number] => {+ const { x, y, z, w } = q;+ const r00 = 1 - 2 * (y * y + z * z);+ const r10 = 2 * (x * y + w * z);+ const r20 = 2 * (x * z - w * y);+ const r21 = 2 * (y * z + w * x);+ const r22 = 1 - 2 * (x * x + y * y);+ // `+ 0` normalizes a negative zero, which an inspector would show as "-0".+ const round = (rad: number) => Math.round(rad * RAD2DEG * 100) / 100 + 0;+ const pitch = Math.asin(Math.max(-1, Math.min(1, -r20)));+ // At a pole the outer two axes name the same turn; charge it all to Z, so the+ // one a 2D scene uses is the one that survives a round trip through the pole.+ if (Math.abs(r20) > 0.999999) {+ const r01 = 2 * (x * y - w * z);+ const r11 = 1 - 2 * (x * x + z * z);+ return [0, round(pitch), round(Math.atan2(-r01, r11))];+ }+ return [round(Math.atan2(r21, r22)), round(pitch), round(Math.atan2(r10, r00))];+};++export const eulerToQuat = (deg: readonly number[]): Quat => {+ const [hx, hy, hz] = [0, 1, 2].map((i) => ((deg[i] ?? 0) * DEG2RAD) / 2);+ const [cx, cy, cz] = [Math.cos(hx!), Math.cos(hy!), Math.cos(hz!)];+ const [sx, sy, sz] = [Math.sin(hx!), Math.sin(hy!), Math.sin(hz!)];// w-FIRST key order on purpose: the quaternion discriminator treats a w-first// layout as a rotation, so a USER component's quaternion field (not named- // rotation/worldRotation) keeps its angle control after an edit instead of+ // rotation/worldRotation) keeps its rotation control after an edit instead of// flipping to four vec4 boxes. The engine reads x/y/z/w by name — order is free.- return { w: Math.cos(h), x: 0, y: 0, z: Math.sin(h) };+ return {+ w: cx * cy * cz + sx * sy * sz,+ x: sx * cy * cz - cx * sy * sz,+ y: cx * sy * cz + sx * cy * sz,+ z: cx * cy * sz - sx * sy * cz,+ };+};++/** Set the Z turn of a rotation, keeping whatever the other two axes say. What+ * the viewport's rotate gizmo writes, so a drag cannot flatten a 3D pose. */+export const setAngleZ = (q: Quat | undefined, deg: number): Quat => {+ const e = q ? quatToEuler(q) : [0, 0, 0];+ return eulerToQuat([e[0], e[1], deg]);};// A rotation quaternion and a vec4 (Camera viewport rect, a 9-slice border) share the@@ -228,7 +267,7 @@ export function inferField(key: string, v: unknown, isColor: boolean): Inspectorconst o = v as Record<string, number>;if ('w' in o && 'z' in o && 'x' in o) {return isQuaternion(key, o)- ? { key, label, type: 'angle', value: quatToAngleZ(o as { z: number; w: number }) }+ ? { key, label, type: 'euler', value: quatToEuler(o as unknown as Quat) }: { key, label, type: 'vec4', value: [o.x, o.y ?? 0, o.z, o.w] };}if ('z' in o && 'x' in o && 'y' in o) return { key, label, type: 'vec3', value: [o.x, o.y, o.z] };diff --git a/desktop/src/panels/Details.tsx b/desktop/src/panels/Details.tsxindex 7aa2fa8ce..6bcba9aa6 100644--- a/desktop/src/panels/Details.tsx+++ b/desktop/src/panels/Details.tsx@@ -464,6 +464,7 @@ function FieldRow({ entities, comp, field: rawField, write, extra }: { entities:case 'angle':control = <NumField value={field.value as number} suffix="°" mixed={mixed} step={field.step} onBegin={begin} onEnd={end} onCancel={cancel} onCommit={apply} />;break;+ case 'euler':case 'vec2':case 'vec3':case 'vec4':diff --git a/desktop/src/types.ts b/desktop/src/types.tsindex e60d3e293..1c20338a7 100644--- a/desktop/src/types.ts+++ b/desktop/src/types.ts@@ -41,7 +41,8 @@ export type InspectorFieldType =| 'vec3'| 'vec4' // four editable numbers (Camera viewport rect, a 9-slice border) — NOT a rotation quaternion (see 'angle')| 'vec2list' // a whole Vec2[] written at once (polygon vertices / chain points) — viewport vertex drag- | 'angle' // 2D rotation: a quaternion shown/edited as Z degrees+ | 'angle' // a quaternion's Z turn in degrees, written WITHOUT disturbing the other two+ | 'euler' // a rotation quaternion shown/edited as three degrees (X, Y, Z)| 'color'| 'enum' // an int field with named options, shown as a dropdown| 'select' // a string field with a fixed choice set, shown as a dropdowndiff --git a/desktop/tests/inspector-vec4-quat.test.ts b/desktop/tests/inspector-vec4-quat.test.tsindex 3b357cb1f..a40433cba 100644--- a/desktop/tests/inspector-vec4-quat.test.ts+++ b/desktop/tests/inspector-vec4-quat.test.ts@@ -7,19 +7,19 @@* (atan2(z=1, w=1)·2 = 90°).*/import { describe, it, expect } from 'vitest';-import { inferField, inspectorFields, angleZToQuat } from '@/engine/schema';+import { inferField, inspectorFields, eulerToQuat } from '@/engine/schema';describe('quaternion vs vec4 inference', () => {- it('a rotation quaternion (w-first) reads as an angle', () => {- expect(inferField('rotation', { w: 1, x: 0, y: 0, z: 0 }, false)!.type).toBe('angle');+ it('a rotation quaternion (w-first) reads as three degrees', () => {+ expect(inferField('rotation', { w: 1, x: 0, y: 0, z: 0 }, false)!.type).toBe('euler');// A user component quaternion (w-first layout) is caught even without the name.- expect(inferField('orient', { w: 1, x: 0, y: 0, z: 0 }, false)!.type).toBe('angle');+ expect(inferField('orient', { w: 1, x: 0, y: 0, z: 0 }, false)!.type).toBe('euler');});it('a vec4 (x-first) reads as four numbers, not an angle', () => {const viewport = inferField('viewport', { x: 0, y: 0, z: 1, w: 1 }, false)!;expect(viewport.type).toBe('vec4');- expect(viewport.value).toEqual([0, 0, 1, 1]); // NOT quatToAngleZ → 90+ expect(viewport.value).toEqual([0, 0, 1, 1]); // NOT a rotation → not degreesconst border = inferField('sliceBorder', { x: 4, y: 4, z: 4, w: 4 }, false)!;expect(border.type).toBe('vec4');expect(border.value).toEqual([4, 4, 4, 4]);@@ -32,17 +32,18 @@ describe('quaternion vs vec4 inference', () => {expect(viewport!.value).toEqual([0, 0, 1, 1]);});- it('a user quaternion stays an angle after an angle EDIT (angleZToQuat is w-first)', () => {- // Editing the angle rewrites the field via angleZToQuat; if it emitted x-first,- // the next inference would mis-classify the field as a vec4 and drop the control.- const edited = angleZToQuat(45);+ it('a user quaternion keeps its control after an EDIT (eulerToQuat is w-first)', () => {+ // Editing rewrites the field via eulerToQuat; if it emitted x-first, the next+ // inference would mis-classify the field as a vec4 and drop the control.+ const edited = eulerToQuat([0, 0, 45]);expect(Object.keys(edited)[0]).toBe('w'); // w-first layout preserved- expect(inferField('orient', edited, false)!.type).toBe('angle');+ expect(inferField('orient', edited, false)!.type).toBe('euler');});- it("end-to-end: the Transform's rotation stays an angle", () => {+ it("end-to-end: the Transform's rotation is three degrees", () => {const data = { position: { x: 0, y: 0, z: 0 }, rotation: { w: 1, x: 0, y: 0, z: 0 }, scale: { x: 1, y: 1, z: 1 } };const rot = inspectorFields('Transform', data).find((f) => f.key === 'rotation')!;- expect(rot.type).toBe('angle');+ expect(rot.type).toBe('euler');+ expect(rot.value).toEqual([0, 0, 0]);});});diff --git a/desktop/tests/inspector-write-values.test.ts b/desktop/tests/inspector-write-values.test.tsindex 3a3eb9ad5..0ca062811 100644--- a/desktop/tests/inspector-write-values.test.ts+++ b/desktop/tests/inspector-write-values.test.ts@@ -13,7 +13,7 @@import { describe, it, expect } from 'vitest';import { toModelValue } from '@/engine/SceneCommands';import { coerceFieldValue, splitFieldMember, patchFieldMember } from '@/engine/EditorControlSurface';-import { coerceEnumInput } from '@/engine/schema';+import { coerceEnumInput, eulerToQuat, quatToEuler } from '@/engine/schema';import type { InspectorFieldValue } from '@/types';describe('toModelValue', () => {@@ -215,3 +215,23 @@ describe('coerceEnumInput (what an enum field may be handed)', () => {expect(coerceEnumInput('', ANIMS, true)).toBeNull();});});++describe('a rotation written through the field door', () => {+ it('takes three degrees and stores a quaternion', () => {+ const q = toModelValue({ rotation: eulerToQuat([0, 0, 0]) }, 'euler', 'rotation', [25, -40, 15]);+ quatToEuler(q as { x: number; y: number; z: number; w: number })+ .forEach((v, i) => expect(v).toBeCloseTo([25, -40, 15][i]!, 2));+ });++ it('keeps the other two axes when only the Z turn is written', () => {+ // The viewport's rotate gizmo writes degrees about Z. Building a whole+ // quaternion from that angle alone would flatten the pose of anything+ // imported with one — a model turned by a drag would lose its tilt.+ const cur = { rotation: eulerToQuat([30, -45, 10]) };+ const turned = quatToEuler(toModelValue(cur, 'angle', 'rotation', 90) as+ { x: number; y: number; z: number; w: number });+ expect(turned[0]).toBeCloseTo(30, 2);+ expect(turned[1]).toBeCloseTo(-45, 2);+ expect(turned[2]).toBeCloseTo(90, 2);+ });+});diff --git a/desktop/tests/schema.test.ts b/desktop/tests/schema.test.tsindex 4132aedd5..acf5ce86b 100644--- a/desktop/tests/schema.test.ts+++ b/desktop/tests/schema.test.ts@@ -6,7 +6,7 @@* the JSON-first rewrite (REARCH_SERIALIZATION.md) will lean on.*/import { describe, it, expect } from 'vitest';-import { prettyLabel, hexToRgba, angleZToQuat, inferField, assetFieldType, spineSlotType, isRenderComponent } from '@/engine/schema';+import { prettyLabel, hexToRgba, eulerToQuat, quatToEuler, setAngleZ, inferField, assetFieldType, spineSlotType, isRenderComponent } from '@/engine/schema';describe('prettyLabel', () => {it('splits camelCase and capitalizes', () => {@@ -38,18 +38,40 @@ describe('hexToRgba', () => {});});-describe('angleZToQuat', () => {- it('round-trips 0° to identity', () => {- const q = angleZToQuat(0);- expect(q.x).toBe(0);- expect(q.y).toBe(0);- expect(q.z).toBeCloseTo(0, 6);- expect(q.w).toBeCloseTo(1, 6);- });- it('encodes 90° into z/w', () => {- const q = angleZToQuat(90);- expect(q.z).toBeCloseTo(Math.SQRT1_2, 6);- expect(q.w).toBeCloseTo(Math.SQRT1_2, 6);+describe('a rotation as three degrees', () => {+ it('is the 2D quaternion exactly when only Z turns', () => {+ // The 2D case has to come out of the general one unchanged, or every+ // existing scene shifts the day the other two axes become editable.+ const q = eulerToQuat([0, 0, 90]);+ expect(q.x).toBeCloseTo(0, 12);+ expect(q.y).toBeCloseTo(0, 12);+ expect(q.z).toBeCloseTo(Math.SQRT1_2, 12);+ expect(q.w).toBeCloseTo(Math.SQRT1_2, 12);+ expect(quatToEuler(q)).toEqual([0, 0, 90]);+ });++ it('round-trips a pose that turns about all three', () => {+ for (const e of [[0, 0, 0], [30, -45, 60], [-12.5, 80, 175], [0, 45, 0]]) {+ const back = quatToEuler(eulerToQuat(e));+ back.forEach((v, i) => expect(v).toBeCloseTo(e[i]!, 2));+ }+ });++ it('keeps the other two axes when only the Z turn is set', () => {+ // What the viewport's rotate gizmo writes. Zeroing X and Y here is how a+ // model imported with a 3D pose got flattened by a drag.+ const posed = eulerToQuat([30, -45, 10]);+ const turned = quatToEuler(setAngleZ(posed, 90));+ expect(turned[0]).toBeCloseTo(30, 2);+ expect(turned[1]).toBeCloseTo(-45, 2);+ expect(turned[2]).toBeCloseTo(90, 2);+ });++ it('charges a pole to Z, so a 2D turn survives one', () => {+ const [x, y, z] = quatToEuler(eulerToQuat([0, 90, 35]));+ expect(x).toBe(0);+ expect(y).toBeCloseTo(90, 2);+ expect(z).toBeCloseTo(35, 2);});});diff --git a/docs/astro/src/data/components.generated.json b/docs/astro/src/data/components.generated.jsonindex d5628635b..8ad1b4c34 100644--- a/docs/astro/src/data/components.generated.json+++ b/docs/astro/src/data/components.generated.json@@ -3403,7 +3403,7 @@"key": "rotation","type": "Quat","default": "(0, 0, 0, 1)",- "doc": "Rotation about the Z axis, in degrees.",+ "doc": "Local rotation in degrees, applied X then Y then Z. 2D content turns about Z alone.","replicated": true},{diff --git a/sdk/src/ecs/component.generated.ts b/sdk/src/ecs/component.generated.tsindex 5ba1f39eb..bc4ac9c63 100644--- a/sdk/src/ecs/component.generated.ts+++ b/sdk/src/ecs/component.generated.ts@@ -737,7 +737,7 @@ export const COMPONENT_META: Record<string, ComponentMetaEntry> = {readonlyFields: ['worldPosition', 'worldRotation', 'worldScale'],fields: {position: { tooltip: "Local position in world units, relative to the parent." },- rotation: { tooltip: "Rotation about the Z axis, in degrees." },+ rotation: { tooltip: "Local rotation in degrees, applied X then Y then Z. 2D content turns about Z alone." },scale: { tooltip: "Local scale per axis (1 = original size; negative flips)." },},},diff --git a/sdk/tests/__snapshots__/component-fieldmeta-golden.test.ts.snap b/sdk/tests/__snapshots__/component-fieldmeta-golden.test.ts.snapindex e98d942fd..9b487122c 100644--- a/sdk/tests/__snapshots__/component-fieldmeta-golden.test.ts.snap+++ b/sdk/tests/__snapshots__/component-fieldmeta-golden.test.ts.snap@@ -841,7 +841,7 @@ exports[`builtin FieldMeta (RC9-1 equivalence gate) > matches the golden snapsho"tooltip": "Local position in world units, relative to the parent.",},"rotation": {- "tooltip": "Rotation about the Z axis, in degrees.",+ "tooltip": "Local rotation in degrees, applied X then Y then Z. 2D content turns about Z alone.",},"scale": {"tooltip": "Local scale per axis (1 = original size; negative flips).",diff --git a/src/esengine/ecs/components/Transform.hpp b/src/esengine/ecs/components/Transform.hppindex 864f48026..6cbd62de1 100644--- a/src/esengine/ecs/components/Transform.hpp+++ b/src/esengine/ecs/components/Transform.hpp@@ -43,7 +43,7 @@ struct Transform {ES_PROPERTY(animatable, anim_override, replicated, tooltip="Local position in world units, relative to the parent.")glm::vec3 position{0.0f, 0.0f, 0.0f};- ES_PROPERTY(animatable, anim_override, replicated, tooltip="Rotation about the Z axis, in degrees.")+ ES_PROPERTY(animatable, anim_override, replicated, tooltip="Local rotation in degrees, applied X then Y then Z. 2D content turns about Z alone.")glm::quat rotation{1.0f, 0.0f, 0.0f, 0.0f};ES_PROPERTY(animatable, anim_override, replicated, tooltip="Local scale per axis (1 = original size; negative flips).")