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(animation): a rotation can be animated on all three axes

esengine388cacac8e2e
diff --git a/desktop/src/engine/schema.ts b/desktop/src/engine/schema.ts
index 183992dd2..fe1e35e63 100644
--- a/desktop/src/engine/schema.ts
+++ b/desktop/src/engine/schema.ts
@@ -1,6 +1,6 @@
// SPDX-License-Identifier: Apache-2.0
// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
-import { getComponentRegistry, getUserComponents, getComponent, getComponentAssetFieldDescriptors, getComponentSkeletalFieldDescriptor, getComponentFieldMeta, Light2DType, usesStagger, isHexOrientation } from 'esengine';
+import { getComponentRegistry, getUserComponents, getComponent, getComponentAssetFieldDescriptors, getComponentSkeletalFieldDescriptor, getComponentFieldMeta, Light2DType, usesStagger, isHexOrientation, q } from 'esengine';
import type { App, SceneData } from 'esengine';
import type { NodeKind, EntityId, InspectorField, InspectorFieldValue, EnumOption, GradientValue, CurveValue } from '@/types';
import { t } from '@/i18n';
@@ -161,8 +161,6 @@ export function componentCategory(name: string, isUser = false): string {
// — Field value inference (matches the JS data shape world.get/set use) —
-const RAD2DEG = 180 / Math.PI;
-const DEG2RAD = Math.PI / 180;
const cap = (s: string) => s.charAt(0).toUpperCase() + s.slice(1);
// Word-split identifiers with acronym + digit-suffix awareness, so 'UIVisual'
@@ -183,48 +181,24 @@ type Quat = { x: number; y: number; z: number; w: number };
* (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))];
+/**
+ * The engine's euler conversion, rounded for display: two decimals, `+ 0` for a
+ * negative zero shown as "-0". Presentation, which is why it is not in the maths.
+ */
+export const quatToEuler = (rot: Quat): [number, number, number] => {
+ const round = (deg: number) => Math.round(deg * 100) / 100 + 0;
+ const [x, y, z] = q.toEuler(rot);
+ return [round(x), round(y), round(z)];
};
-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 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: 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,
- };
-};
+// The engine's Quat is w-FIRST, which is what `isQuaternion` keys on: a user
+// component's rotation field keeps its rotation control after an edit rather
+// than flipping to four vec4 boxes.
+export const eulerToQuat = (deg: readonly number[]): Quat => q.fromEuler(deg);
/** 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]);
-};
+export const setAngleZ = (rot: Quat | undefined, deg: number): Quat => q.setAngleZ(rot, deg);
// A rotation quaternion and a vec4 (Camera viewport rect, a 9-slice border) share the
// exact {x,y,z,w} shape, so value-shape alone can't tell them apart — the engine's only
diff --git a/docs/astro/src/data/apiStability.generated.json b/docs/astro/src/data/apiStability.generated.json
index 90ec4f9e7..427e140c4 100644
--- a/docs/astro/src/data/apiStability.generated.json
+++ b/docs/astro/src/data/apiStability.generated.json
@@ -3,10 +3,10 @@
"counts": {
"public": 113,
"beta": 65,
- "experimental": 1531,
+ "experimental": 1533,
"deprecated": 3
},
- "total": 1709,
+ "total": 1711,
"subsystems": [
{
"id": "ecs",
diff --git a/docs/astro/src/data/components.generated.json b/docs/astro/src/data/components.generated.json
index e2ea19836..751dc70ca 100644
--- a/docs/astro/src/data/components.generated.json
+++ b/docs/astro/src/data/components.generated.json
@@ -3431,7 +3431,11 @@
"position.x",
"position.y",
"position.z",
+ "rotation.x",
+ "rotation.y",
"rotation.z",
+ "rotation.w",
+ "rotation.angle",
"scale.x",
"scale.y",
"scale.z"
diff --git a/sdk/etc/index.api.md b/sdk/etc/index.api.md
index 53d5d3779..23b220e49 100644
--- a/sdk/etc/index.api.md
+++ b/sdk/etc/index.api.md
@@ -1,7 +1,7 @@
# API surface — esengine/index
<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->
-Symbols: 113 public · 58 beta · 1416 experimental · 3 deprecated
+Symbols: 113 public · 58 beta · 1418 experimental · 3 deprecated
## ABI_LAYOUT_HASH — const @experimental
```
@@ -7241,6 +7241,11 @@ number
8191
```
+## TIMELINE_FORMAT_VERSION — const @experimental
+```
+"1.2"
+```
+
## TParams — type @experimental
```
Record<string, string | number>
@@ -10732,6 +10737,11 @@ PrefabsPlugin
(n: number) => Dimension
```
+## q — const @experimental
+```
+{ create(w?: number, x?: number, y?: number, z?: number): Quat; clone(a: Quat): Quat; mul(a: Quat, b: Quat): Quat; axis(axis: "x" | "y" | "z", rad: number): Quat; normalize(a: Quat): Quat; dot(a: Quat, b: Quat): number; neg(a: Quat): Quat; toEuler(a: Quat): [number, number, number]; fromEuler(deg: readonly number[]): Quat; setAngleZ(a: Quat | undefined, deg: number): Quat; angleZ(a: Pick<Quat, "z" | "w">): number; }
+```
+
## quat — const @experimental
```
(w?: number, x?: number, y?: number, z?: number) => Quat
diff --git a/sdk/etc/index.native.api.md b/sdk/etc/index.native.api.md
index ef1cd187e..a7b0cdcba 100644
--- a/sdk/etc/index.native.api.md
+++ b/sdk/etc/index.native.api.md
@@ -1,7 +1,7 @@
# API surface — esengine/index.native
<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->
-Symbols: 113 public · 63 beta · 1435 experimental · 3 deprecated
+Symbols: 113 public · 63 beta · 1437 experimental · 3 deprecated
## ABI_LAYOUT_HASH — const @experimental
```
@@ -7434,6 +7434,11 @@ number
8191
```
+## TIMELINE_FORMAT_VERSION — const @experimental
+```
+"1.2"
+```
+
## TParams — type @experimental
```
Record<string, string | number>
@@ -10975,6 +10980,11 @@ PrefabsPlugin
(n: number) => Dimension
```
+## q — const @experimental
+```
+{ create(w?: number, x?: number, y?: number, z?: number): Quat; clone(a: Quat): Quat; mul(a: Quat, b: Quat): Quat; axis(axis: "x" | "y" | "z", rad: number): Quat; normalize(a: Quat): Quat; dot(a: Quat, b: Quat): number; neg(a: Quat): Quat; toEuler(a: Quat): [number, number, number]; fromEuler(deg: readonly number[]): Quat; setAngleZ(a: Quat | undefined, deg: number): Quat; angleZ(a: Pick<Quat, "z" | "w">): number; }
+```
+
## quat — const @experimental
```
(w?: number, x?: number, y?: number, z?: number) => Quat
diff --git a/sdk/etc/index.node.api.md b/sdk/etc/index.node.api.md
index 778c1ec77..4d5cdc728 100644
--- a/sdk/etc/index.node.api.md
+++ b/sdk/etc/index.node.api.md
@@ -1,7 +1,7 @@
# API surface — esengine/index.node
<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->
-Symbols: 113 public · 60 beta · 1415 experimental · 3 deprecated
+Symbols: 113 public · 60 beta · 1417 experimental · 3 deprecated
## ANCHOR_AXES — const @experimental
```
@@ -7236,6 +7236,11 @@ number
8191
```
+## TIMELINE_FORMAT_VERSION — const @experimental
+```
+"1.2"
+```
+
## TParams — type @experimental
```
Record<string, string | number>
@@ -10737,6 +10742,11 @@ PrefabsPlugin
(n: number) => Dimension
```
+## q — const @experimental
+```
+{ create(w?: number, x?: number, y?: number, z?: number): Quat; clone(a: Quat): Quat; mul(a: Quat, b: Quat): Quat; axis(axis: "x" | "y" | "z", rad: number): Quat; normalize(a: Quat): Quat; dot(a: Quat, b: Quat): number; neg(a: Quat): Quat; toEuler(a: Quat): [number, number, number]; fromEuler(deg: readonly number[]): Quat; setAngleZ(a: Quat | undefined, deg: number): Quat; angleZ(a: Pick<Quat, "z" | "w">): number; }
+```
+
## quat — const @experimental
```
(w?: number, x?: number, y?: number, z?: number) => Quat
diff --git a/sdk/etc/minigame.api.md b/sdk/etc/minigame.api.md
index 97608e179..d23a43cf5 100644
--- a/sdk/etc/minigame.api.md
+++ b/sdk/etc/minigame.api.md
@@ -1,7 +1,7 @@
# API surface — esengine/minigame
<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->
-Symbols: 113 public · 58 beta · 1436 experimental · 3 deprecated
+Symbols: 113 public · 58 beta · 1438 experimental · 3 deprecated
## ANCHOR_AXES — const @experimental
```
@@ -7481,6 +7481,11 @@ number
8191
```
+## TIMELINE_FORMAT_VERSION — const @experimental
+```
+"1.2"
+```
+
## TParams — type @experimental
```
Record<string, string | number>
@@ -10987,6 +10992,11 @@ PrefabsPlugin
(n: number) => Dimension
```
+## q — const @experimental
+```
+{ create(w?: number, x?: number, y?: number, z?: number): Quat; clone(a: Quat): Quat; mul(a: Quat, b: Quat): Quat; axis(axis: "x" | "y" | "z", rad: number): Quat; normalize(a: Quat): Quat; dot(a: Quat, b: Quat): number; neg(a: Quat): Quat; toEuler(a: Quat): [number, number, number]; fromEuler(deg: readonly number[]): Quat; setAngleZ(a: Quat | undefined, deg: number): Quat; angleZ(a: Pick<Quat, "z" | "w">): number; }
+```
+
## quat — const @experimental
```
(w?: number, x?: number, y?: number, z?: number) => Quat
diff --git a/sdk/etc/wechat.api.md b/sdk/etc/wechat.api.md
index deb7475e1..5c7919a57 100644
--- a/sdk/etc/wechat.api.md
+++ b/sdk/etc/wechat.api.md
@@ -1,7 +1,7 @@
# API surface — esengine/wechat
<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->
-Symbols: 113 public · 58 beta · 1426 experimental · 3 deprecated
+Symbols: 113 public · 58 beta · 1428 experimental · 3 deprecated
## ANCHOR_AXES — const @experimental
```
@@ -7243,6 +7243,11 @@ number
8191
```
+## TIMELINE_FORMAT_VERSION — const @experimental
+```
+"1.2"
+```
+
## TParams — type @experimental
```
Record<string, string | number>
@@ -10759,6 +10764,11 @@ PrefabsPlugin
(n: number) => Dimension
```
+## q — const @experimental
+```
+{ create(w?: number, x?: number, y?: number, z?: number): Quat; clone(a: Quat): Quat; mul(a: Quat, b: Quat): Quat; axis(axis: "x" | "y" | "z", rad: number): Quat; normalize(a: Quat): Quat; dot(a: Quat, b: Quat): number; neg(a: Quat): Quat; toEuler(a: Quat): [number, number, number]; fromEuler(deg: readonly number[]): Quat; setAngleZ(a: Quat | undefined, deg: number): Quat; angleZ(a: Pick<Quat, "z" | "w">): number; }
+```
+
## quat — const @experimental
```
(w?: number, x?: number, y?: number, z?: number) => Quat
diff --git a/sdk/src/core-content.ts b/sdk/src/core-content.ts
index c029cc6e8..a182f9945 100644
--- a/sdk/src/core-content.ts
+++ b/sdk/src/core-content.ts
@@ -804,7 +804,7 @@ export {
export {
sampleTimeline, sampleTimelineInWorld, evaluateChannel, applyWrapMode,
serializeTimelineAsset, serializeTimelineToJson, resolveChildEntity, parseAnimationClip,
- TrackType, InterpType, WrapMode,
+ TrackType, InterpType, WrapMode, TIMELINE_FORMAT_VERSION,
type SampleWorld, type SampleDeps, type SampleOptions,
type TimelineAsset, type Track, type PropertyTrack, type PropertyChannel, type Keyframe,
type SpriteAnimTrack, type AudioTrack, type ActivationTrack, type SpineTrack, type AnimFramesTrack,
diff --git a/sdk/src/core-sys.ts b/sdk/src/core-sys.ts
index 25f1516f1..dd3bd7842 100644
--- a/sdk/src/core-sys.ts
+++ b/sdk/src/core-sys.ts
@@ -16,7 +16,7 @@
// Math (scalar / Vec2 / Vec3 helpers on the canonical types)
// =============================================================================
-export { scalar, v2, v3, col } from './math';
+export { scalar, v2, v3, q, col } from './math';
// =============================================================================
// Localization (i18n)
diff --git a/sdk/src/ecs/component.generated.ts b/sdk/src/ecs/component.generated.ts
index 3e49dc75d..a12be48a7 100644
--- a/sdk/src/ecs/component.generated.ts
+++ b/sdk/src/ecs/component.generated.ts
@@ -730,7 +730,7 @@ export const COMPONENT_META: Record<string, ComponentMetaEntry> = {
assetFields: [],
entityFields: [],
colorFields: [],
- animatableFields: ['position.x', 'position.y', 'position.z', 'rotation.z', 'scale.x', 'scale.y', 'scale.z'],
+ animatableFields: ['position.x', 'position.y', 'position.z', 'rotation.x', 'rotation.y', 'rotation.z', 'rotation.w', 'rotation.angle', 'scale.x', 'scale.y', 'scale.z'],
replicatedFields: ['position', 'rotation', 'scale'],
readonlyFields: ['worldPosition', 'worldRotation', 'worldScale'],
fields: {
diff --git a/sdk/src/math/index.ts b/sdk/src/math/index.ts
index 7b8d3f3d8..59ec1a659 100644
--- a/sdk/src/math/index.ts
+++ b/sdk/src/math/index.ts
@@ -9,4 +9,5 @@
export { scalar } from './scalar';
export { v2 } from './vec2';
export { v3 } from './vec3';
+export { q } from './quat';
export { col } from './color';
diff --git a/sdk/src/math/quat.ts b/sdk/src/math/quat.ts
new file mode 100644
index 000000000..4fb28c0cc
--- /dev/null
+++ b/sdk/src/math/quat.ts
@@ -0,0 +1,109 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file quat.ts
+ * @brief Quaternion helpers operating on the canonical `Quat` ({w,x,y,z})
+ * type. Pure: every op returns a new Quat. Exposed as the `q` namespace.
+ *
+ * A rotation is a quaternion everywhere it is stored, and every place that lets
+ * someone name one in a friendlier way — a Z angle in a 2D scene, three euler
+ * degrees in the inspector, a rotation channel in a timeline — is a way IN, not
+ * a second representation. Each such entry point that rebuilt the whole
+ * quaternion from its own axis flattened the other two; keeping the conversions
+ * here is what lets those entries compose instead of overwrite.
+ */
+
+import type { Quat } from '../types';
+
+const DEG2RAD = Math.PI / 180;
+const RAD2DEG = 180 / Math.PI;
+
+export const q = {
+ create(w = 1, x = 0, y = 0, z = 0): Quat { return { w, x, y, z }; },
+ clone(a: Quat): Quat { return { w: a.w, x: a.x, y: a.y, z: a.z }; },
+
+ /** `a` applied after `b` (a·b) — a world-space turn composes on the left. */
+ mul(a: Quat, b: Quat): Quat {
+ return {
+ w: a.w * b.w - a.x * b.x - a.y * b.y - a.z * b.z,
+ x: a.w * b.x + a.x * b.w + a.y * b.z - a.z * b.y,
+ y: a.w * b.y - a.x * b.z + a.y * b.w + a.z * b.x,
+ z: a.w * b.z + a.x * b.y - a.y * b.x + a.z * b.w,
+ };
+ },
+
+ /** A turn of `rad` about one axis. */
+ axis(axis: 'x' | 'y' | 'z', rad: number): Quat {
+ const s = Math.sin(rad / 2);
+ return {
+ w: Math.cos(rad / 2),
+ x: axis === 'x' ? s : 0,
+ y: axis === 'y' ? s : 0,
+ z: axis === 'z' ? s : 0,
+ };
+ },
+
+ /**
+ * Unit length. Interpolating quaternions component-wise leaves a shorter
+ * one, and writing that scales the model — so anything that lerps must end
+ * here.
+ */
+ normalize(a: Quat): Quat {
+ const len = Math.hypot(a.w, a.x, a.y, a.z);
+ if (len === 0) return { w: 1, x: 0, y: 0, z: 0 };
+ return { w: a.w / len, x: a.x / len, y: a.y / len, z: a.z / len };
+ },
+
+ dot(a: Quat, b: Quat): number { return a.w * b.w + a.x * b.x + a.y * b.y + a.z * b.z; },
+
+ /** Negated. `-q` and `q` are the same rotation; which one is stored decides
+ * whether a component-wise interpolation takes the short arc or the long one. */
+ neg(a: Quat): Quat { return { w: -a.w, x: -a.x, y: -a.y, z: -a.z }; },
+
+ /**
+ * 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.
+ */
+ toEuler(a: Quat): [number, number, number] {
+ const { x, y, z, w } = a;
+ 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);
+ 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 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, pitch * RAD2DEG, Math.atan2(-r01, r11) * RAD2DEG];
+ }
+ return [Math.atan2(r21, r22) * RAD2DEG, pitch * RAD2DEG, Math.atan2(r10, r00) * RAD2DEG];
+ },
+
+ /** Inverse of {@link toEuler}. */
+ fromEuler(deg: readonly number[]): Quat {
+ const hx = ((deg[0] ?? 0) * DEG2RAD) / 2;
+ const hy = ((deg[1] ?? 0) * DEG2RAD) / 2;
+ const hz = ((deg[2] ?? 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)];
+ 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, keeping whatever the other two axes say — the 2D way in. */
+ setAngleZ(a: Quat | undefined, deg: number): Quat {
+ const e = a ? this.toEuler(a) : [0, 0, 0];
+ return this.fromEuler([e[0], e[1], deg]);
+ },
+
+ /** The Z turn of a 2D rotation, in radians. */
+ angleZ(a: Pick<Quat, 'z' | 'w'>): number { return 2 * Math.atan2(a.z, a.w); },
+};
diff --git a/sdk/src/timeline/TimelineEvaluator.ts b/sdk/src/timeline/TimelineEvaluator.ts
index 2d3bfea60..b23b8bba8 100644
--- a/sdk/src/timeline/TimelineEvaluator.ts
+++ b/sdk/src/timeline/TimelineEvaluator.ts
@@ -23,9 +23,12 @@
import { TrackType, InterpType, WrapMode, type TimelineAsset, type PropertyChannel } from './TimelineTypes';
import { setNestedProperty, resolveChildEntity } from './TimelineRuntime';
import { getComponent, type AnyComponentDef } from '../ecs/component';
+import { q } from '../math/quat';
import type { Entity } from '../types';
import type { World } from '../ecs/world';
+const RAD2DEG = 180 / Math.PI;
+
// ---------------------------------------------------------------------------
// Core math — 1:1 port of TimelineSystem.cpp (keep in lock-step)
// ---------------------------------------------------------------------------
@@ -118,19 +121,36 @@ type FieldWriter = (data: any, value: number) => void;
/**
* Per-field writers for animatable paths whose JS shape differs from the raw
- * dot-path (so a generic `setNestedProperty` would corrupt them). This is the
- * TS seed of L1's generated reflection writer table; for now the only such case
- * is Transform rotation. Mirrors animTargets.generated.hpp exactly (value is the
- * full Z angle in radians; the quaternion uses the half-angle) so editor preview
- * matches the C++ runtime bit-for-bit.
+ * dot-path, so a generic `setNestedProperty` would corrupt them.
+ *
+ * `rotation.angle` is the Z turn in radians, and it COMPOSES: the other two axes
+ * survive it, so a clip turning a model about Z cannot flatten its pose. The
+ * four components are written raw, normalized in {@link finishQuaternions}.
*/
const WRITER_OVERRIDES: Record<string, FieldWriter> = {
- 'Transform.rotation.z': (data, v) => {
- const h = v * 0.5;
- data.rotation = { w: Math.cos(h), x: 0, y: 0, z: Math.sin(h) };
+ 'Transform.rotation.angle': (data, v) => {
+ data.rotation = q.setAngleZ(data.rotation, v * RAD2DEG);
},
};
+/** Component fields written component-wise that must end up unit length. */
+const QUATERNION_FIELDS: Record<string, readonly string[]> = {
+ Transform: ['rotation'],
+};
+
+/**
+ * Renormalize any quaternion a track wrote component-wise. Interpolating the
+ * four numbers independently lands INSIDE the unit sphere — about 0.92 halfway
+ * between two rotations 90° apart — and writing that scales the object.
+ * Normalized it traces the arc slerp would, differing only in angular speed.
+ */
+function finishQuaternions(data: any, component: string, touched: Set<string>): void {
+ for (const field of QUATERNION_FIELDS[component] ?? []) {
+ if (!touched.has(field)) continue;
+ data[field] = q.normalize(data[field]);
+ }
+}
+
function applyField(data: any, component: string, property: string, value: number): boolean {
const override = WRITER_OVERRIDES[`${component}.${property}`];
if (override) {
@@ -182,13 +202,20 @@ export function sampleTimeline(
const data = deps.world.get(entity, def);
let changed = false;
+ const touched = new Set<string>();
for (const ch of track.channels) {
if (!ch.keyframes || ch.keyframes.length === 0) continue;
if (opts?.skipChannel?.(track.childPath, track.component, ch.property)) continue;
const v = evaluateChannel(ch, time);
- if (applyField(data, track.component, ch.property, v)) changed = true;
+ if (applyField(data, track.component, ch.property, v)) {
+ changed = true;
+ touched.add(ch.property.split('.')[0]!);
+ }
+ }
+ if (changed) {
+ finishQuaternions(data, track.component, touched);
+ deps.world.set(entity, def, data);
}
- if (changed) deps.world.set(entity, def, data);
}
}
diff --git a/sdk/src/timeline/TimelineLoader.ts b/sdk/src/timeline/TimelineLoader.ts
index 776e3bf74..527831af6 100644
--- a/sdk/src/timeline/TimelineLoader.ts
+++ b/sdk/src/timeline/TimelineLoader.ts
@@ -3,6 +3,7 @@
import {
wrapModeFromName,
TrackType,
+ TIMELINE_FORMAT_VERSION,
type TimelineAsset,
type Track,
type PropertyTrack,
@@ -16,8 +17,6 @@ import {
} from './TimelineTypes';
import { log } from '../util/logger';
-const CURRENT_VERSION = '1.1';
-
const STEP_TANGENT_THRESHOLD = 1e5;
type MigrationFn = (raw: any) => void;
@@ -38,6 +37,17 @@ const MIGRATIONS: [string, string, MigrationFn][] = [
}
}
}],
+ // `rotation.z` named the Z EULER angle, not the quaternion's z component —
+ // the name a 3D rotation channel needs. The angle keeps its meaning under
+ // the name that says so, and a document written before this reads the same.
+ ['1.1', '1.2', (raw: any) => {
+ for (const track of raw.tracks ?? []) {
+ if (track.type !== TrackType.Property) continue;
+ for (const ch of track.channels ?? []) {
+ if (ch.property === 'rotation.z') ch.property = 'rotation.angle';
+ }
+ }
+ }],
];
function migrateAsset(raw: any): void {
@@ -50,7 +60,7 @@ function migrateAsset(raw: any): void {
}
}
- raw.version = CURRENT_VERSION;
+ raw.version = TIMELINE_FORMAT_VERSION;
}
function parseTrack(raw: any): Track {
@@ -147,7 +157,7 @@ export function parseTimelineAsset(rawJson: unknown): TimelineAsset {
migrateAsset(raw);
return {
- version: CURRENT_VERSION,
+ version: TIMELINE_FORMAT_VERSION,
type: 'timeline',
duration: raw.duration ?? 0,
wrapMode: wrapModeFromName(raw.wrapMode),
diff --git a/sdk/src/timeline/TimelineSerializer.ts b/sdk/src/timeline/TimelineSerializer.ts
index b53c5c973..90464a320 100644
--- a/sdk/src/timeline/TimelineSerializer.ts
+++ b/sdk/src/timeline/TimelineSerializer.ts
@@ -12,9 +12,7 @@
* reads `raw.animFrames` into the in-memory `frames`).
*/
-import { wrapModeToName, TrackType, type TimelineAsset, type Track } from './TimelineTypes';
-
-const CURRENT_VERSION = '1.1';
+import { wrapModeToName, TrackType, TIMELINE_FORMAT_VERSION, type TimelineAsset, type Track } from './TimelineTypes';
function serializeTrack(track: Track): Record<string, unknown> {
const base = { type: track.type, name: track.name, childPath: track.childPath };
@@ -58,7 +56,7 @@ function serializeTrack(track: Track): Record<string, unknown> {
/** Serialize to a plain JSON-ready object (the `.estimeline` document shape). */
export function serializeTimelineAsset(asset: TimelineAsset): Record<string, unknown> {
return {
- version: CURRENT_VERSION,
+ version: TIMELINE_FORMAT_VERSION,
type: 'timeline',
duration: asset.duration,
wrapMode: wrapModeToName(asset.wrapMode),
diff --git a/sdk/src/timeline/TimelineTypes.ts b/sdk/src/timeline/TimelineTypes.ts
index 608f5696d..502f18ad9 100644
--- a/sdk/src/timeline/TimelineTypes.ts
+++ b/sdk/src/timeline/TimelineTypes.ts
@@ -1,5 +1,12 @@
// SPDX-License-Identifier: Apache-2.0
// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * The `.estimeline` format version. What the serializer stamps and what the
+ * loader migrates up to: two constants would let a document be written at a
+ * version its own reader thinks needs migrating.
+ */
+export const TIMELINE_FORMAT_VERSION = '1.2';
+
export const WrapMode = {
Once: 0,
Loop: 1,
diff --git a/sdk/src/timeline/index.ts b/sdk/src/timeline/index.ts
index 166ac71e9..1faf6fab8 100644
--- a/sdk/src/timeline/index.ts
+++ b/sdk/src/timeline/index.ts
@@ -1,6 +1,7 @@
// SPDX-License-Identifier: Apache-2.0
// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
export {
+ TIMELINE_FORMAT_VERSION,
WrapMode,
TrackType,
InterpType,
diff --git a/sdk/src/ui/util/math.ts b/sdk/src/ui/util/math.ts
index 77b2428d5..1881ae98c 100644
--- a/sdk/src/ui/util/math.ts
+++ b/sdk/src/ui/util/math.ts
@@ -4,6 +4,7 @@
// undoes; re-exported here because this module is where the UI already reaches
// for it.
import { invertMatrix4 } from '../../math/mat4';
+import { q } from '../../math/quat';
export { invertMatrix4 };
@@ -91,7 +92,7 @@ export function pointInWorldRect(
}
export function quaternionToAngle2D(rz: number, rw: number): number {
- return 2 * Math.atan2(rz, rw);
+ return q.angleZ({ z: rz, w: rw });
}
/**
diff --git a/sdk/tests/timeline-evaluator.test.ts b/sdk/tests/timeline-evaluator.test.ts
index ef03d252e..ea04566a5 100644
--- a/sdk/tests/timeline-evaluator.test.ts
+++ b/sdk/tests/timeline-evaluator.test.ts
@@ -14,6 +14,7 @@ import {
type PropertyChannel,
type TimelineAsset,
} from '../src/timeline/TimelineTypes';
+import { q } from '../src/math/quat';
function ch(keyframes: PropertyChannel['keyframes'], property = 'value'): PropertyChannel {
return { property, keyframes };
@@ -144,31 +145,64 @@ describe('sampleTimeline', () => {
expect(store.get('Transform').position.y).toBe(0); // muted → untouched
});
- it('rotation.z writes a half-angle quaternion (matches the C++ runtime)', () => {
+ /** A one-track clip on Transform, its channels given by the caller. */
+ const rotationClip = (channels: PropertyChannel[]): TimelineAsset => ({
+ version: '1.2',
+ type: 'timeline',
+ duration: 1,
+ wrapMode: WrapMode.Once,
+ tracks: [{
+ type: TrackType.Property, name: 'Spin', childPath: '', component: 'Transform', channels,
+ }],
+ });
+
+ it('rotation.angle writes a half-angle quaternion (matches the C++ runtime)', () => {
const defs = { Transform: { __name: 'Transform' } };
const store = new Map<string, any>([
['Transform', { position: { x: 0, y: 0, z: 0 }, rotation: { w: 1, x: 0, y: 0, z: 0 } }],
]);
const angle = Math.PI / 2; // 90°
- const asset: TimelineAsset = {
- version: '1.1',
- type: 'timeline',
- duration: 1,
- wrapMode: WrapMode.Once,
- tracks: [{
- type: TrackType.Property,
- name: 'Spin',
- childPath: '',
- component: 'Transform',
- channels: [ch([{ time: 0, value: angle, inTangent: 0, outTangent: 0 }], 'rotation.z')],
- }],
- };
+ const asset = rotationClip([ch([{ time: 0, value: angle, inTangent: 0, outTangent: 0 }], 'rotation.angle')]);
+
+ sampleTimeline(asset, 0, 1 as Entity, mockDeps(store, defs));
+ const rot = store.get('Transform').rotation;
+ expect(rot.w).toBeCloseTo(Math.cos(angle / 2), 5);
+ expect(rot.z).toBeCloseTo(Math.sin(angle / 2), 5);
+ expect(rot.x).toBeCloseTo(0, 5);
+ expect(rot.y).toBeCloseTo(0, 5);
+ });
+
+ it('rotation.angle keeps the other two axes — a clip cannot flatten a pose', () => {
+ const defs = { Transform: { __name: 'Transform' } };
+ // Pitched 30° about X, the pose an imported model arrives with.
+ const pitch = { w: Math.cos(Math.PI / 12), x: Math.sin(Math.PI / 12), y: 0, z: 0 };
+ const store = new Map<string, any>([['Transform', { rotation: { ...pitch } }]]);
+ const asset = rotationClip([ch([{ time: 0, value: Math.PI / 2, inTangent: 0, outTangent: 0 }], 'rotation.angle')]);
sampleTimeline(asset, 0, 1 as Entity, mockDeps(store, defs));
- const q = store.get('Transform').rotation;
- expect(q.w).toBeCloseTo(Math.cos(angle / 2), 5);
- expect(q.z).toBeCloseTo(Math.sin(angle / 2), 5);
- expect(q.x).toBe(0);
- expect(q.y).toBe(0);
+ const [ex, ey, ez] = q.toEuler(store.get('Transform').rotation);
+ expect(ex).toBeCloseTo(30, 4);
+ expect(ey).toBeCloseTo(0, 4);
+ expect(ez).toBeCloseTo(90, 4);
+ });
+
+ it('the four components interpolate to a unit quaternion', () => {
+ const defs = { Transform: { __name: 'Transform' } };
+ const store = new Map<string, any>([['Transform', { rotation: { w: 1, x: 0, y: 0, z: 0 } }]]);
+ // Identity → 90° about Y, sampled at the midpoint. Component-wise that
+ // lands at length ~0.924; normalized it is the 45° turn slerp gives.
+ const kf = (time: number, value: number) => ({ time, value, inTangent: 0, outTangent: 0, interpolation: InterpType.Linear });
+ const half = Math.SQRT1_2;
+ const asset = rotationClip([
+ ch([kf(0, 0), kf(1, 0)], 'rotation.x'),
+ ch([kf(0, 0), kf(1, half)], 'rotation.y'),
+ ch([kf(0, 0), kf(1, 0)], 'rotation.z'),
+ ch([kf(0, 1), kf(1, half)], 'rotation.w'),
+ ]);
+
+ sampleTimeline(asset, 0.5, 1 as Entity, mockDeps(store, defs));
+ const rot = store.get('Transform').rotation;
+ expect(Math.hypot(rot.w, rot.x, rot.y, rot.z)).toBeCloseTo(1, 6);
+ expect(q.toEuler(rot)[1]).toBeCloseTo(45, 1);
});
});
diff --git a/sdk/tests/timeline-loader.test.ts b/sdk/tests/timeline-loader.test.ts
index 78f564e76..9a24f65a2 100644
--- a/sdk/tests/timeline-loader.test.ts
+++ b/sdk/tests/timeline-loader.test.ts
@@ -2,7 +2,9 @@
// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
import { describe, it, expect } from 'vitest';
import { parseTimelineAsset, extractTimelineAssetPaths } from '../src/timeline/TimelineLoader';
+import { sampleTimeline } from '../src/timeline/TimelineEvaluator';
import { WrapMode, TrackType, type TimelineAsset } from '../src/timeline/TimelineTypes';
+import type { Entity } from '../src/types';
const MINIMAL_TIMELINE = {
version: '1.0',
@@ -136,6 +138,43 @@ describe('TimelineLoader', () => {
});
});
+ describe('migration', () => {
+ // A clip carrying the old channel name must still turn the same way, so
+ // this SAMPLES it rather than comparing the two names.
+ it('renames the Z euler channel and leaves the rotation it produces alone', () => {
+ const legacy = {
+ version: '1.1', type: 'timeline', duration: 1, wrapMode: 'once',
+ tracks: [{
+ type: 'property', name: 'Spin', childPath: '', component: 'Transform',
+ channels: [{
+ property: 'rotation.z',
+ keyframes: [{ time: 0, value: Math.PI / 2, inTangent: 0, outTangent: 0 }],
+ }],
+ }],
+ };
+
+ const asset = parseTimelineAsset(legacy);
+ const track = asset.tracks[0];
+ if (track.type !== TrackType.Property) throw new Error('Expected property track');
+ expect(track.channels[0].property).toBe('rotation.angle');
+
+ const store = new Map<string, any>([['Transform', { rotation: { w: 1, x: 0, y: 0, z: 0 } }]]);
+ const defs: Record<string, any> = { Transform: { __name: 'Transform' } };
+ sampleTimeline(asset, 0, 1 as Entity, {
+ world: {
+ has: () => true,
+ get: (_e, d) => store.get((d as any).__name),
+ set: (_e, d, data) => { store.set((d as any).__name, data); },
+ },
+ getComponent: (name) => defs[name],
+ resolveChild: (root) => root,
+ });
+ const rot = store.get('Transform').rotation;
+ expect(rot.w).toBeCloseTo(Math.cos(Math.PI / 4), 5);
+ expect(rot.z).toBeCloseTo(Math.sin(Math.PI / 4), 5);
+ });
+ });
+
describe('extractTimelineAssetPaths', () => {
it('should extract audio clip paths', () => {
const asset = parseTimelineAsset(FULL_TIMELINE);
diff --git a/sdk/tests/timeline-serializer.test.ts b/sdk/tests/timeline-serializer.test.ts
index e897ba066..bc6b53875 100644
--- a/sdk/tests/timeline-serializer.test.ts
+++ b/sdk/tests/timeline-serializer.test.ts
@@ -3,10 +3,10 @@
import { describe, it, expect } from 'vitest';
import { serializeTimelineAsset, serializeTimelineToJson } from '../src/timeline/TimelineSerializer';
import { parseTimelineAsset } from '../src/timeline/TimelineLoader';
-import { WrapMode, TrackType, InterpType, type TimelineAsset } from '../src/timeline/TimelineTypes';
+import { WrapMode, TrackType, InterpType, TIMELINE_FORMAT_VERSION, type TimelineAsset } from '../src/timeline/TimelineTypes';
const ASSET: TimelineAsset = {
- version: '1.1',
+ version: '1.2',
type: 'timeline',
duration: 5,
wrapMode: WrapMode.Loop,
@@ -42,7 +42,7 @@ const ASSET: TimelineAsset = {
describe('TimelineSerializer', () => {
it('encodes wrapMode as a string and AnimFrames under the on-disk key', () => {
const doc = serializeTimelineAsset(ASSET) as any;
- expect(doc.version).toBe('1.1');
+ expect(doc.version).toBe(TIMELINE_FORMAT_VERSION);
expect(doc.wrapMode).toBe('loop');
const frames = doc.tracks.find((t: any) => t.type === 'animFrames');
expect(frames.animFrames).toHaveLength(2);
diff --git a/tools/eht/generators/metadata.py b/tools/eht/generators/metadata.py
index c7078bd79..c2c1cc404 100644
--- a/tools/eht/generators/metadata.py
+++ b/tools/eht/generators/metadata.py
@@ -189,7 +189,13 @@ class MetadataGenerator:
else:
fields.extend([f'{prop.name}.x', f'{prop.name}.y', f'{prop.name}.z', f'{prop.name}.w'])
elif t == 'glm::quat':
- fields.append(f'{prop.name}.z')
+ # The components, plus `.angle` for the Z turn a 2D scene thinks
+ # in. `.angle` is a way IN (it keeps the other two axes), not a
+ # second representation — a channel named `.z` for the Z EULER
+ # angle would take the name the z COMPONENT needs, and a 3D
+ # rotation could then only be animated by flattening it.
+ fields.extend([f'{prop.name}.x', f'{prop.name}.y', f'{prop.name}.z',
+ f'{prop.name}.w', f'{prop.name}.angle'])
else:
fields.append(prop.name)
return fields