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(math): exact.sin and exact.cos, specified rather than delegated

esengine895ab035d148
diff --git a/CHANGELOG.md b/CHANGELOG.md
index c13c29f77..48d4e1b32 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -45,6 +45,17 @@ published separately; it ships inside the editor.
`UICameraInfo.viewProjection` is deliberately not in it, since a member has to
have a fixed width.
+ **`exact.sin` / `exact.cos`** (`@beta`) — trigonometry that answers the same
+ bits everywhere. `Math.sin` is implementation-defined, so an interpreted build
+ and a compiled one may both be right and disagree; a differential pixel gate
+ then goes red on trigonometry rather than on a bug. These are specified
+ instead — one range reduction, one polynomial, one order of operations,
+ written in `sdk/src/math/exact.ts` and again in the compiler's runtime header,
+ and held together bit for bit by a gate. The AOT subset admits them and still
+ refuses `Math.sin`, naming the replacement in the refusal. Determinism is the
+ promise, not accuracy: a very large argument loses digits, identically on both
+ sides.
+
A resource the PROJECT declares compiles as well, with no engine change per
resource: `defineResource({ value: 0 }, 'Score')` has literal defaults, so the
build derives the layout from the declaration the same way it does for a
diff --git a/compiler/src/codegen.ts b/compiler/src/codegen.ts
index 7d0553338..ac48285c7 100644
--- a/compiler/src/codegen.ts
+++ b/compiler/src/codegen.ts
@@ -234,6 +234,65 @@ static inline double es_ceil(double x) { return ceil(x); }
static inline double es_trunc(double x) { return trunc(x); }
static inline double es_sqrt(double x) { return sqrt(x); }
+/* ---------------------------------------------------------------------------
+ Trigonometry, SPECIFIED. Math.sin is implementation-defined, so an
+ interpreted build and a compiled one may both be right and disagree — which
+ for a differential pixel gate is a red frame with no bug behind it.
+
+ These are the same range reduction, the same polynomial and the same ORDER as
+ sdk/src/math/exact.ts, line for line. Reordering either side is a change to
+ the result, and a differential compares them bit for bit.
+ --------------------------------------------------------------------------- */
+#define ES_PIO2_HI 1.5707963267341256
+#define ES_PIO2_LO 6.077100506506192e-11
+#define ES_TWO_OVER_PI 0.6366197723675814
+
+static inline double es_kernel_sin(double x) {
+ double z = x * x;
+ double r = -1.6666666666666632e-01 + z * (8.333333333324894e-03
+ + z * (-1.984126982985795e-04 + z * (2.755731370707007e-06
+ + z * (-2.505076025340686e-08 + z * 1.5896909952115501e-10))));
+ return x + x * z * r;
+}
+
+static inline double es_kernel_cos(double x) {
+ double z = x * x;
+ double r = 4.1666666666666602e-02 + z * (-1.3888888888874109e-03
+ + z * (2.4801587289476730e-05 + z * (-2.7557314351390663e-07
+ + z * (2.0875723212981748e-09 + z * -1.1359647557788195e-11))));
+ return 1.0 - 0.5 * z + z * z * r;
+}
+
+/* Math.round's rule, as floor(x + 0.5) rather than es_round: the TS side
+ reduces with that same expression, and the two must agree on a tie. */
+static inline double es_trig_quadrant(double x, double *r) {
+ double n = floor(x * ES_TWO_OVER_PI + 0.5);
+ *r = (x - n * ES_PIO2_HI) - n * ES_PIO2_LO;
+ double q = fmod(n, 4.0);
+ if (q < 0.0) q += 4.0;
+ return q;
+}
+
+static inline double es_exact_sin(double x) {
+ if (!isfinite(x)) return (double)NAN;
+ double r;
+ double q = es_trig_quadrant(x, &r);
+ if (q == 0.0) return es_kernel_sin(r);
+ if (q == 1.0) return es_kernel_cos(r);
+ if (q == 2.0) return -es_kernel_sin(r);
+ return -es_kernel_cos(r);
+}
+
+static inline double es_exact_cos(double x) {
+ if (!isfinite(x)) return (double)NAN;
+ double r;
+ double q = es_trig_quadrant(x, &r);
+ if (q == 0.0) return es_kernel_cos(r);
+ if (q == 1.0) return -es_kernel_sin(r);
+ if (q == 2.0) return -es_kernel_cos(r);
+ return es_kernel_sin(r);
+}
+
/* Math.sign returns x itself for NaN and for both zeroes, so the sign of zero
survives — and the sign of zero is a distinct bit pattern in the image. */
static inline double es_sign(double x) {
@@ -360,6 +419,7 @@ const STORE: Partial<Record<LeafEnc, string>> = {
const MATH_C: Record<MathFn, string> = {
abs: 'es_abs', floor: 'es_floor', ceil: 'es_ceil', round: 'es_round',
trunc: 'es_trunc', sqrt: 'es_sqrt', sign: 'es_sign', min: 'es_min', max: 'es_max',
+ sin: 'es_exact_sin', cos: 'es_exact_cos',
};
// =============================================================================
diff --git a/compiler/src/eir.ts b/compiler/src/eir.ts
index 55bf26800..e10311153 100644
--- a/compiler/src/eir.ts
+++ b/compiler/src/eir.ts
@@ -107,8 +107,16 @@ export const MATH_CONSTS: readonly string[] = [
export const MATH_FNS = {
abs: 1, floor: 1, ceil: 1, round: 1, trunc: 1, sqrt: 1, sign: 1,
min: 2, max: 2,
+ sin: 1, cos: 1,
} as const;
+/**
+ * The ones ECMAScript leaves to the implementation, which the engine specifies
+ * instead: reachable as `exact.sin`, never as `Math.sin`. Two implementations
+ * of a trig function agreeing is luck; two of THESE agreeing is a gate.
+ */
+export const EXACT_FNS: readonly MathFn[] = ['sin', 'cos'];
+
export type MathFn = keyof typeof MATH_FNS;
export type Stmt =
diff --git a/compiler/src/frontend.ts b/compiler/src/frontend.ts
index 334d2a4c8..fcc4bc055 100644
--- a/compiler/src/frontend.ts
+++ b/compiler/src/frontend.ts
@@ -30,7 +30,7 @@ import { resourceMethodBit } from '../../sdk/src/ecs/resourceShapes';
import {
BOOL, ENTITY, F64, HOST_ENC,
type CompShape, type EirModule, type EirSystem, type EirType,
- MATH_CONSTS, MATH_FNS,
+ EXACT_FNS, MATH_CONSTS, MATH_FNS,
type FieldSpec, type EirFn, type Expr, type Local, type Place, type QueryArg, type Stmt, type BinOp, type LogicOp,
type MathFn,
} from './eir';
@@ -704,8 +704,9 @@ class SystemLowerer {
});
return { e: 'call', target: { k: 'fn', name: target.name }, args, type: target.ret };
}
- if (!ts.isPropertyAccessExpression(callee) || !ts.isIdentifier(callee.expression)
- || callee.expression.text !== 'Math') {
+ const receiver = ts.isPropertyAccessExpression(callee) && ts.isIdentifier(callee.expression)
+ ? callee.expression.text : null;
+ if (receiver !== 'Math' && receiver !== 'exact') {
// A method on a RESOURCE is pending: a service is meant to be read
// as memory, so `input.isKeyDown('KeyW')` is a bit at a known offset.
// On anything else it needs an object model, which there is none of.
@@ -729,8 +730,21 @@ class SystemLowerer {
}
throw new NotInSubset(node, 'CallExpression is not an expression this subset lowers', 'permanent');
}
- const fn = callee.name.text as MathFn;
+ const fn = (callee as ts.PropertyAccessExpression).name.text as MathFn;
const arity = (MATH_FNS as Record<string, number | undefined>)[fn];
+ const specified = EXACT_FNS.includes(fn);
+ // The two namespaces divide by who specifies the answer, and the message
+ // has to say so: refusing `Math.sin` without naming `exact.sin` reads as
+ // "trigonometry cannot be compiled", which is no longer true.
+ if (receiver === 'Math' && specified) {
+ throw new NotInSubset(node,
+ `Math.${fn} is implementation-defined, so a compiled build may disagree with the `
+ + `interpreter — call exact.${fn} instead, which the engine specifies`);
+ }
+ if (receiver === 'exact' && !specified) {
+ throw new NotInSubset(node, `exact.${fn} is not one the engine specifies`
+ + (arity === undefined ? '' : ` — Math.${fn} is exact already`));
+ }
if (arity === undefined) {
throw new NotInSubset(node,
`Math.${fn} is not exactly specified by ECMAScript, so a compiled build would be free to disagree with the interpreter`,
diff --git a/compiler/src/interp.ts b/compiler/src/interp.ts
index e23aacd18..232f9c255 100644
--- a/compiler/src/interp.ts
+++ b/compiler/src/interp.ts
@@ -13,6 +13,7 @@
* obviously correct, not fast; anything clever here would be a second
* place for a bug to hide from the backend it exists to check.
*/
+import { exact } from '../../sdk/src/math/exact';
import type { EirFn, EirSystem, Expr, Place, QueryArg, Stmt } from './eir';
/** The module's pure functions, threaded rather than held in a module global. */
@@ -121,8 +122,11 @@ function evalExpr(e: Expr, frame: Frame, fns: Fns, host: EirHost, owners: Owners
case 'call': {
const a = e.args.map((x) => evalExpr(x, frame, fns, host, owners));
if (e.target.k === 'math') {
- // The frontend admits only the exactly-specified operations, so
- // deferring to the host's Math is the same answer everywhere.
+ // The engine's own for the ones ECMAScript leaves open, and the
+ // host's Math for the rest — which is the same split the C side
+ // makes, and the reason the two agree.
+ const own = (exact as unknown as Record<string, ((x: number) => number) | undefined>)[e.target.fn];
+ if (own) return own(a[0] as number);
const fn = (Math as unknown as Record<string, (...xs: number[]) => number>)[e.target.fn]!;
return fn(...(a as number[]));
}
diff --git a/compiler/tests/codegen.test.ts b/compiler/tests/codegen.test.ts
index fbe67c984..58dfcadf7 100644
--- a/compiler/tests/codegen.test.ts
+++ b/compiler/tests/codegen.test.ts
@@ -406,7 +406,7 @@ describe('the emitted C says what the interpreter says', () => {
// ternaries, folded module constants with a shadowing local, an inlined
// helper, and the Math arguments where libm and ECMAScript disagree.
for (const name of ['FixtureDrift', 'FixtureClampSys', 'FixtureTuned', 'FixtureHelpers',
- 'FixtureMathOps', 'FixtureCamera', 'FixtureGate', 'FixturePong']) {
+ 'FixtureMathOps', 'FixtureCamera', 'FixtureGate', 'FixturePong', 'FixtureTrig']) {
it(`${name}: the whole image agrees with the interpreter`, () => {
const sys = systemOf(fixtures, name);
const layout = packLayout(fixtures.module.comps);
diff --git a/compiler/tests/coverage.test.ts b/compiler/tests/coverage.test.ts
index 3ca9ca535..8e854769c 100644
--- a/compiler/tests/coverage.test.ts
+++ b/compiler/tests/coverage.test.ts
@@ -52,7 +52,7 @@ const ROOT = resolve(fileURLToPath(new URL('../..', import.meta.url)));
/** Per-frame systems only. See the file header before lowering these. */
const FRAME_FLOOR = 15;
/** Per-frame systems the contract could take once the pending work is done. */
-const CEILING_FLOOR = 84;
+const CEILING_FLOOR = 96;
function walk(dir: string, out: string[] = []): string[] {
for (const name of readdirSync(dir)) {
diff --git a/compiler/tests/exact-trig.test.ts b/compiler/tests/exact-trig.test.ts
new file mode 100644
index 000000000..b74623823
--- /dev/null
+++ b/compiler/tests/exact-trig.test.ts
@@ -0,0 +1,111 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file exact-trig.test.ts
+ * @brief The two implementations of `exact.sin` are one implementation.
+ *
+ * @details The engine specifies trigonometry because ECMAScript does not, and
+ * a specification written twice is two specifications until something
+ * compares them. This compiles the C in the runtime header and holds
+ * it against the TypeScript, BIT for bit — not close, identical, since
+ * a differential pixel gate compares frames and one ulp is a pixel.
+ *
+ * The arguments are chosen where the two could part: the tie in the
+ * range reduction, the quadrant boundaries, arguments large enough for
+ * Cody-Waite to lose digits (identically, which is the promise), and
+ * the values that are their own answer.
+ */
+import { describe, it, expect } from 'vitest';
+import { execFileSync, spawnSync } from 'node:child_process';
+import { mkdtempSync, mkdirSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { CFLAGS, RUNTIME_H } from '../src/codegen';
+import { exact } from '../../sdk/src/math/exact';
+
+function findCC(): string | null {
+ for (const cc of ['clang', 'gcc', 'cc']) {
+ if (spawnSync(cc, ['--version'], { encoding: 'utf8' }).status === 0) return cc;
+ }
+ return null;
+}
+const CC = findCC();
+
+/** Where a range reduction, a quadrant choice or a polynomial could differ. */
+function arguments_(): number[] {
+ const out = [0, -0, 1e-300, -1e-300, 1e-8, -1e-8, 1, -1];
+ const HALF_PI = Math.PI / 2;
+ for (let q = -4; q <= 4; q++) {
+ // Either side of every quadrant boundary, and the boundary itself.
+ for (const d of [-1e-9, 0, 1e-9, -0.25, 0.25]) out.push(q * HALF_PI + d);
+ }
+ // The tie in `floor(x * 2/π + 0.5)`, which C and ECMAScript round apart.
+ for (let k = -3; k <= 3; k++) out.push((k + 0.5) * HALF_PI);
+ for (let i = -60; i <= 60; i++) out.push(i * 0.37);
+ // Big enough that the two-step reduction loses digits — identically.
+ for (const big of [1e6, -1e6, 12345.6789, -98765.4321, 1e10, -1e10]) out.push(big);
+ return out;
+}
+
+const ARGS = arguments_();
+
+/** The 64 bits of a double, which is what "identical" has to mean here. */
+function bitsOf(x: number): string {
+ const view = new DataView(new ArrayBuffer(8));
+ view.setFloat64(0, x);
+ return view.getBigUint64(0).toString(16).padStart(16, '0');
+}
+
+describe('the engine\'s trigonometry, on both sides of the compiler', () => {
+ it('reports whether this gate could run at all', () => {
+ if (!CC) console.warn('[exact-trig] NO C COMPILER — the comparison did NOT run.');
+ });
+
+ it.skipIf(!CC)('answers the same bits in C as in TypeScript', () => {
+ const dir = mkdtempSync(join(tmpdir(), 'estella-trig-'));
+ mkdirSync(dir, { recursive: true });
+ writeFileSync(join(dir, 'estella_abi.h'), RUNTIME_H);
+ writeFileSync(join(dir, 'main.c'), [
+ '#include <stdio.h>',
+ '#include <string.h>',
+ '#include "estella_abi.h"',
+ 'int main(void) {',
+ ` static const double xs[] = { ${ARGS.map((x) => x.toExponential(20)).join(', ')} };`,
+ ' for (unsigned i = 0; i < sizeof(xs) / sizeof(xs[0]); i++) {',
+ ' double s = es_exact_sin(xs[i]);',
+ ' double c = es_exact_cos(xs[i]);',
+ ' unsigned long long sb, cb;',
+ ' memcpy(&sb, &s, 8); memcpy(&cb, &c, 8);',
+ ' printf("%016llx %016llx\\n", sb, cb);',
+ ' }',
+ ' return 0;',
+ '}',
+ ].join('\n'));
+
+ const exe = join(dir, `trig${process.platform === 'win32' ? '.exe' : ''}`);
+ const built = spawnSync(CC!, [...CFLAGS, '-Wall', '-Wextra', '-o', exe,
+ join(dir, 'main.c'), '-lm'], { encoding: 'utf8' });
+ expect(built.status, built.stderr).toBe(0);
+ expect(built.stderr.trim()).toBe('');
+
+ const lines = execFileSync(exe, { encoding: 'utf8' }).trim().split('\n');
+ expect(lines).toHaveLength(ARGS.length);
+ const fromC = lines.map((l) => l.split(' '));
+ const fromTs = ARGS.map((x) => [bitsOf(exact.sin(x)), bitsOf(exact.cos(x))]);
+ // Compared as one array so a failure names the argument, not just a count.
+ expect(ARGS.map((x, i) => [x, ...fromC[i]!]))
+ .toEqual(ARGS.map((x, i) => [x, ...fromTs[i]!]));
+ });
+
+ it('stays within an ulp or so of the host Math, which is a sanity check not a contract', () => {
+ // Determinism is the promise; being WRONG would still be a bug, and a
+ // polynomial with a typo in it is exactly what this notices.
+ let worst = 0;
+ for (const x of ARGS) {
+ if (!Number.isFinite(x) || Math.abs(x) > 1e5) continue;
+ worst = Math.max(worst, Math.abs(exact.sin(x) - Math.sin(x)),
+ Math.abs(exact.cos(x) - Math.cos(x)));
+ }
+ expect(worst).toBeLessThan(1e-12);
+ });
+});
diff --git a/compiler/tests/fixtures/in-subset.ts b/compiler/tests/fixtures/in-subset.ts
index 9a48a4cd9..0ccaadfdf 100644
--- a/compiler/tests/fixtures/in-subset.ts
+++ b/compiler/tests/fixtures/in-subset.ts
@@ -10,7 +10,7 @@
*/
import {
defineComponent, defineEvent, defineSystem, EventReader, EventWriter,
- Query, Mut, Res, Camera, Input, Time, Transform,
+ exact, Query, Mut, Res, Camera, Input, Time, Transform,
} from 'esengine';
export const Drift = defineComponent('FixtureDrift', { rate: 40, wrap: 100, enabled: true });
@@ -186,3 +186,21 @@ export const pongSystem = defineSystem(
},
{ name: 'FixturePong' },
);
+
+/**
+ * Trigonometry the engine specifies. `Math.sin` is refused; this is what a
+ * system that wants to compile calls, and the differential is what says the
+ * two implementations of it are one implementation.
+ */
+export const trigSystem = defineSystem(
+ [Query(Mut(MathProbe))],
+ (query) => {
+ for (const [, p] of query) {
+ p.rounded = exact.sin(p.v);
+ p.truncated = exact.cos(p.v);
+ p.ceiled = exact.sin(p.v * 100);
+ p.floored = exact.cos(p.v * 100);
+ }
+ },
+ { name: 'FixtureTrig' },
+);
diff --git a/compiler/tests/stubs/esengine.ts b/compiler/tests/stubs/esengine.ts
index def840f5c..156e193a3 100644
--- a/compiler/tests/stubs/esengine.ts
+++ b/compiler/tests/stubs/esengine.ts
@@ -38,6 +38,7 @@ export function ResMut(resource: unknown): unknown {
return { kind: 'resmut', resource };
}
export const Input = { _name: 'Input' };
+export { exact } from '../../../sdk/src/math/exact';
export function defineEvent<T>(name: string): { _name: string } {
void (undefined as T | undefined);
return { _name: name };
diff --git a/compiler/tests/subset.test.ts b/compiler/tests/subset.test.ts
index dc80ad893..f676b1853 100644
--- a/compiler/tests/subset.test.ts
+++ b/compiler/tests/subset.test.ts
@@ -35,7 +35,7 @@ describe('the subset refuses, and says why', () => {
it.each([
['FixtureLooping', /WhileStatement is not a statement/],
['FixtureTypo', /has no field 'valeu'/],
- ['FixtureTrig', /Math\.sin is not exactly specified by ECMAScript/],
+ ['FixtureTrig', /Math\.sin is implementation-defined.*call exact\.sin instead/],
['FixtureCalling', /'damp' cannot be lowered: parameter 'v' needs a type annotation/],
['FixtureWritesConst', /'LIMIT' is a constant and cannot be assigned/],
['FixtureIntegerField', /'Camera\.priority' is stored as i32, and this subset has no integer type/],
@@ -89,7 +89,7 @@ describe('a promise the author wrote down', () => {
expect(promised.severity).toBe('error');
expect(unmarked.severity).toBe('note');
// The marker is not a second rule: both are refused for the same reason.
- expect(promised.message).toMatch(/Math\.cos is not exactly specified/);
+ expect(promised.message).toMatch(/Math\.cos is implementation-defined.*call exact\.cos instead/);
expect(promised.kind).toBe(unmarked.kind);
expect(promised.line).toBeGreaterThan(0);
});
diff --git a/pipeline/tests/build-compiled-systems.test.ts b/pipeline/tests/build-compiled-systems.test.ts
index 531ee4ea0..4112566eb 100644
--- a/pipeline/tests/build-compiled-systems.test.ts
+++ b/pipeline/tests/build-compiled-systems.test.ts
@@ -185,7 +185,7 @@ describe('the AOT build step', () => {
expect(out.wasmPath).toBeNull();
expect(out.errors).toHaveLength(1);
expect(out.errors[0]).toContain('BrokenSystem');
- expect(out.errors[0]).toMatch(/Math\.sin is not exactly specified/);
+ expect(out.errors[0]).toMatch(/Math\.sin is implementation-defined/);
expect(out.errors[0]).toMatch(/systems\.ts:\d+/);
});
diff --git a/sdk/etc/index.api.md b/sdk/etc/index.api.md
index 3f8fab584..5257ce257 100644
--- a/sdk/etc/index.api.md
+++ b/sdk/etc/index.api.md
@@ -2,6 +2,7 @@
<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->
Symbols: 113 public · 64 beta · 1514 experimental · 3 deprecated
+Symbols: 113 public · 65 beta · 1515 experimental · 3 deprecated
## ABI_LAYOUT_HASH — const @experimental
```
@@ -10377,6 +10378,11 @@ EventBindingPlugin
(handle: number): void
```
+## exact — const @beta
+```
+{ sin(x: number): number; cos(x: number): number; }
+```
+
## expandEntry — function @experimental
```
(prefab: PrefabData, entry: PrefabInstanceEntry, allocateId: () => number, loadPrefab?: SyncPrefabResolver): { entities: ProcessedEntity[]; rootId: number; }
diff --git a/sdk/etc/index.native.api.md b/sdk/etc/index.native.api.md
index 07bd00d8a..e918c50b1 100644
--- a/sdk/etc/index.native.api.md
+++ b/sdk/etc/index.native.api.md
@@ -2,6 +2,7 @@
<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->
Symbols: 113 public · 69 beta · 1533 experimental · 3 deprecated
+Symbols: 113 public · 70 beta · 1534 experimental · 3 deprecated
## ABI_LAYOUT_HASH — const @experimental
```
@@ -10610,6 +10611,11 @@ EventBindingPlugin
(handle: number): void
```
+## exact — const @beta
+```
+{ sin(x: number): number; cos(x: number): number; }
+```
+
## expandEntry — function @experimental
```
(prefab: PrefabData, entry: PrefabInstanceEntry, allocateId: () => number, loadPrefab?: SyncPrefabResolver): { entities: ProcessedEntity[]; rootId: number; }
diff --git a/sdk/etc/index.node.api.md b/sdk/etc/index.node.api.md
index 332e4e529..463cd5ef3 100644
--- a/sdk/etc/index.node.api.md
+++ b/sdk/etc/index.node.api.md
@@ -2,6 +2,7 @@
<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->
Symbols: 113 public · 66 beta · 1513 experimental · 3 deprecated
+Symbols: 113 public · 67 beta · 1514 experimental · 3 deprecated
## ANCHOR_AXES — const @experimental
```
@@ -10372,6 +10373,11 @@ EventBindingPlugin
(handle: number): void
```
+## exact — const @beta
+```
+{ sin(x: number): number; cos(x: number): number; }
+```
+
## expandEntry — function @experimental
```
(prefab: PrefabData, entry: PrefabInstanceEntry, allocateId: () => number, loadPrefab?: SyncPrefabResolver): { entities: ProcessedEntity[]; rootId: number; }
diff --git a/sdk/etc/minigame.api.md b/sdk/etc/minigame.api.md
index 9d0902a00..3a0fd8917 100644
--- a/sdk/etc/minigame.api.md
+++ b/sdk/etc/minigame.api.md
@@ -2,6 +2,7 @@
<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->
Symbols: 113 public · 64 beta · 1535 experimental · 3 deprecated
+Symbols: 113 public · 65 beta · 1536 experimental · 3 deprecated
## ANCHOR_AXES — const @experimental
```
@@ -10629,6 +10630,11 @@ EventBindingPlugin
(handle: number): void
```
+## exact — const @beta
+```
+{ sin(x: number): number; cos(x: number): number; }
+```
+
## expandEntry — function @experimental
```
(prefab: PrefabData, entry: PrefabInstanceEntry, allocateId: () => number, loadPrefab?: SyncPrefabResolver): { entities: ProcessedEntity[]; rootId: number; }
diff --git a/sdk/etc/wechat.api.md b/sdk/etc/wechat.api.md
index 53f547ec7..78ed39ddb 100644
--- a/sdk/etc/wechat.api.md
+++ b/sdk/etc/wechat.api.md
@@ -2,6 +2,7 @@
<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->
Symbols: 113 public · 64 beta · 1525 experimental · 3 deprecated
+Symbols: 113 public · 65 beta · 1526 experimental · 3 deprecated
## ANCHOR_AXES — const @experimental
```
@@ -10400,6 +10401,11 @@ EventBindingPlugin
(handle: number): void
```
+## exact — const @beta
+```
+{ sin(x: number): number; cos(x: number): number; }
+```
+
## expandEntry — function @experimental
```
(prefab: PrefabData, entry: PrefabInstanceEntry, allocateId: () => number, loadPrefab?: SyncPrefabResolver): { entities: ProcessedEntity[]; rootId: number; }
diff --git a/sdk/src/core-sys.ts b/sdk/src/core-sys.ts
index c6d6bb8b4..43ac348a3 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, q, col } from './math';
+export { exact, scalar, v2, v3, q, col } from './math';
// =============================================================================
// Localization (i18n)
diff --git a/sdk/src/math/exact.ts b/sdk/src/math/exact.ts
new file mode 100644
index 000000000..32f770709
--- /dev/null
+++ b/sdk/src/math/exact.ts
@@ -0,0 +1,98 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file exact.ts
+ * @brief Trigonometry that answers the same bits everywhere.
+ *
+ * @details `Math.sin` is implementation-defined: two engines may both be right
+ * and disagree in the last bit. That is fine until a system is
+ * COMPILED, because then the interpreted build and the shipped one are
+ * two implementations, and a pixel gate goes red on trigonometry
+ * rather than on a bug.
+ *
+ * So these are specified rather than delegated: one range reduction,
+ * one polynomial, one order of operations — written twice, in this file
+ * and in the compiler's runtime header, and held together by a
+ * bit-for-bit differential. `exact.sin` is what a system that wants to
+ * compile calls; `Math.sin` stays refused, and says so.
+ *
+ * Determinism is the promise, not accuracy. The reduction is two-step
+ * Cody-Waite, so a very large argument loses digits — identically on
+ * both sides, which is the property that matters here.
+ */
+
+/** π/2 in two pieces, so `x - n·π/2` keeps the bits a single constant loses. */
+const PIO2_HI = 1.5707963267341256;
+const PIO2_LO = 6.077100506506192e-11;
+/** 2/π, as one number both sides read from the same digits. */
+const TWO_OVER_PI = 0.6366197723675814;
+
+/** Minimax coefficients for sin on [-π/4, π/4] (fdlibm's kernel). */
+const S1 = -1.6666666666666632e-01;
+const S2 = 8.333333333324894e-03;
+const S3 = -1.984126982985795e-04;
+const S4 = 2.755731370707007e-06;
+const S5 = -2.505076025340686e-08;
+const S6 = 1.5896909952115501e-10;
+
+/** The same, for cos. */
+const C1 = 4.1666666666666602e-02;
+const C2 = -1.3888888888874109e-03;
+const C3 = 2.4801587289476730e-05;
+const C4 = -2.7557314351390663e-07;
+const C5 = 2.0875723212981748e-09;
+const C6 = -1.1359647557788195e-11;
+
+/**
+ * `Math.round`'s rule — ties toward +Infinity — spelled out, because C's
+ * `round` breaks ties away from zero and would disagree on every .5.
+ */
+function roundTiesUp(x: number): number {
+ return Math.floor(x + 0.5);
+}
+
+/** sin on [-π/4, π/4], by Horner in one fixed order. */
+function kernelSin(x: number): number {
+ const z = x * x;
+ const r = S1 + z * (S2 + z * (S3 + z * (S4 + z * (S5 + z * S6))));
+ return x + x * z * r;
+}
+
+/** cos on [-π/4, π/4], likewise. */
+function kernelCos(x: number): number {
+ const z = x * x;
+ const r = C1 + z * (C2 + z * (C3 + z * (C4 + z * (C5 + z * C6))));
+ return 1.0 - 0.5 * z + z * z * r;
+}
+
+/**
+ * Trigonometry a compiled system may call, answering the same bits as the
+ * interpreted build. `Math.sin` is refused by the AOT subset and says so.
+ *
+ * @beta
+ */
+export const exact = {
+ /** Sine, to the same bits in an interpreted build and a compiled one. */
+ sin(x: number): number {
+ if (!Number.isFinite(x)) return NaN;
+ const n = roundTiesUp(x * TWO_OVER_PI);
+ const r = (x - n * PIO2_HI) - n * PIO2_LO;
+ const q = ((n % 4) + 4) % 4;
+ if (q === 0) return kernelSin(r);
+ if (q === 1) return kernelCos(r);
+ if (q === 2) return -kernelSin(r);
+ return -kernelCos(r);
+ },
+
+ /** Cosine, to the same bits in an interpreted build and a compiled one. */
+ cos(x: number): number {
+ if (!Number.isFinite(x)) return NaN;
+ const n = roundTiesUp(x * TWO_OVER_PI);
+ const r = (x - n * PIO2_HI) - n * PIO2_LO;
+ const q = ((n % 4) + 4) % 4;
+ if (q === 0) return kernelCos(r);
+ if (q === 1) return -kernelSin(r);
+ if (q === 2) return -kernelCos(r);
+ return kernelSin(r);
+ },
+};
diff --git a/sdk/src/math/index.ts b/sdk/src/math/index.ts
index 59ec1a659..5f8a437de 100644
--- a/sdk/src/math/index.ts
+++ b/sdk/src/math/index.ts
@@ -6,6 +6,7 @@
* helpers, operating on the canonical types in `../types`.
*/
+export { exact } from './exact';
export { scalar } from './scalar';
export { v2 } from './vec2';
export { v3 } from './vec3';
diff --git a/src/esengine/aot/estella_abi.h b/src/esengine/aot/estella_abi.h
index 7688e2ab6..a0121fa3e 100644
--- a/src/esengine/aot/estella_abi.h
+++ b/src/esengine/aot/estella_abi.h
@@ -128,6 +128,65 @@ static inline double es_ceil(double x) { return ceil(x); }
static inline double es_trunc(double x) { return trunc(x); }
static inline double es_sqrt(double x) { return sqrt(x); }
+/* ---------------------------------------------------------------------------
+ Trigonometry, SPECIFIED. Math.sin is implementation-defined, so an
+ interpreted build and a compiled one may both be right and disagree — which
+ for a differential pixel gate is a red frame with no bug behind it.
+
+ These are the same range reduction, the same polynomial and the same ORDER as
+ sdk/src/math/exact.ts, line for line. Reordering either side is a change to
+ the result, and a differential compares them bit for bit.
+ --------------------------------------------------------------------------- */
+#define ES_PIO2_HI 1.5707963267341256
+#define ES_PIO2_LO 6.077100506506192e-11
+#define ES_TWO_OVER_PI 0.6366197723675814
+
+static inline double es_kernel_sin(double x) {
+ double z = x * x;
+ double r = -1.6666666666666632e-01 + z * (8.333333333324894e-03
+ + z * (-1.984126982985795e-04 + z * (2.755731370707007e-06
+ + z * (-2.505076025340686e-08 + z * 1.5896909952115501e-10))));
+ return x + x * z * r;
+}
+
+static inline double es_kernel_cos(double x) {
+ double z = x * x;
+ double r = 4.1666666666666602e-02 + z * (-1.3888888888874109e-03
+ + z * (2.4801587289476730e-05 + z * (-2.7557314351390663e-07
+ + z * (2.0875723212981748e-09 + z * -1.1359647557788195e-11))));
+ return 1.0 - 0.5 * z + z * z * r;
+}
+
+/* Math.round's rule, as floor(x + 0.5) rather than es_round: the TS side
+ reduces with that same expression, and the two must agree on a tie. */
+static inline double es_trig_quadrant(double x, double *r) {
+ double n = floor(x * ES_TWO_OVER_PI + 0.5);
+ *r = (x - n * ES_PIO2_HI) - n * ES_PIO2_LO;
+ double q = fmod(n, 4.0);
+ if (q < 0.0) q += 4.0;
+ return q;
+}
+
+static inline double es_exact_sin(double x) {
+ if (!isfinite(x)) return (double)NAN;
+ double r;
+ double q = es_trig_quadrant(x, &r);
+ if (q == 0.0) return es_kernel_sin(r);
+ if (q == 1.0) return es_kernel_cos(r);
+ if (q == 2.0) return -es_kernel_sin(r);
+ return -es_kernel_cos(r);
+}
+
+static inline double es_exact_cos(double x) {
+ if (!isfinite(x)) return (double)NAN;
+ double r;
+ double q = es_trig_quadrant(x, &r);
+ if (q == 0.0) return es_kernel_cos(r);
+ if (q == 1.0) return -es_kernel_sin(r);
+ if (q == 2.0) return -es_kernel_cos(r);
+ return es_kernel_sin(r);
+}
+
/* Math.sign returns x itself for NaN and for both zeroes, so the sign of zero
survives — and the sign of zero is a distinct bit pattern in the image. */
static inline double es_sign(double x) {