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.

fix(compiler): a field is where EHT says, and encoded the way EHT says

yhh33cc35f628ab
diff --git a/compiler/src/abi.ts b/compiler/src/abi.ts
index 0af5fd28b..a86408e35 100644
--- a/compiler/src/abi.ts
+++ b/compiler/src/abi.ts
@@ -19,7 +19,7 @@
* table the engine and the SDK's accessors already agree on.
*/
import { ehtStamp } from './builtins';
-import type { CompShape, EirSystem, EirType, QueryArg } from './eir';
+import { encBytes, type CompShape, type EirSystem, type EirType, type LeafEnc, type QueryArg } from './eir';
import { runSystemOn, type EirHost, type Fns } from './interp';
/** One command record: 16 bytes, four u32 (docs/REARCH_AOT_ABI.md §2.3). */
@@ -37,14 +37,14 @@ export const SYSCTX_WORDS = 6;
export const QUERYROWS_WORDS = 2;
/**
- * Where a field lives, and HOW WIDE it is. Component bytes are f32 because EHT
- * says the C++ structs are; a resource is a host-side record and `Time.delta` is
- * an f64 — packing it as f32 makes one side multiply by a rounded 1/30 and the
- * two drift apart. Width is part of the contract, not an implementation detail.
+ * Where a field lives and HOW it is encoded, both from the shape, which got them
+ * from EHT. Encoding is contract, not detail: `Time.delta` packed as f32 makes
+ * one side multiply by a rounded 1/30, and a bool byte read as a float takes
+ * three bytes of its neighbour with it.
*/
export interface Leaf {
readonly byteOffset: number;
- readonly bits: 32 | 64;
+ readonly enc: LeafEnc;
readonly type: EirType;
}
@@ -70,6 +70,7 @@ export class AbiMemory {
readonly f32: Float32Array;
readonly f64: Float64Array;
readonly u32: Uint32Array;
+ readonly u8: Uint8Array;
private next = 64;
private readonly compBase = new Map<string, Map<number, number>>();
private readonly resBase = new Map<string, number>();
@@ -85,6 +86,7 @@ export class AbiMemory {
this.f32 = new Float32Array(this.buffer);
this.f64 = new Float64Array(this.buffer);
this.u32 = new Uint32Array(this.buffer);
+ this.u8 = new Uint8Array(this.buffer);
this.scratchNext = bytes;
this.cmdBuf = this.alloc(this.cmdCap * CMD_WORDS * 4);
}
@@ -138,7 +140,7 @@ export class AbiMemory {
private writeLeaf(shape: FieldOffsets, base: number, path: string, v: number | boolean): void {
const leaf = shape.leaves.get(path);
if (!leaf) throw new Error(`ABI: no field '${path}'`);
- store(this, base + leaf.byteOffset, leaf.bits, v);
+ store(this, base + leaf.byteOffset, leaf.enc, v);
}
baseOf(comp: string, entity: number): number | undefined {
@@ -152,10 +154,10 @@ export class AbiMemory {
}
/** Read a leaf back, for a test to check what the run produced. */
- read(comp: string, entity: number, path: string): number {
+ read(comp: string, entity: number, path: string): number | boolean {
const shape = this.layout.comps.get(comp)!;
const leaf = shape.leaves.get(path)!;
- return load(this, this.baseOf(comp, entity)! + leaf.byteOffset, leaf.bits);
+ return load(this, this.baseOf(comp, entity)! + leaf.byteOffset, leaf.enc);
}
/** Drop an entity, as the host's flush would. */
@@ -166,13 +168,23 @@ export class AbiMemory {
}
}
-/** One load / one store, chosen by the width the contract declares. */
-function load(mem: AbiMemory, at: number, bits: 32 | 64): number {
- return bits === 64 ? mem.f64[at >> 3]! : mem.f32[at >> 2]!;
+/** One load / one store, chosen by the encoding the shape declares. */
+function load(mem: AbiMemory, at: number, enc: LeafEnc): number | boolean {
+ switch (enc) {
+ case 'f64': return mem.f64[at >> 3]!;
+ case 'f32': return mem.f32[at >> 2]!;
+ case 'bool8': return mem.u8[at] !== 0;
+ default: throw new Error(`ABI: nothing reads a ${enc} leaf yet`);
+ }
}
-function store(mem: AbiMemory, at: number, bits: 32 | 64, v: number | boolean): void {
- const n = typeof v === 'boolean' ? (v ? 1 : 0) : v;
- if (bits === 64) mem.f64[at >> 3] = n; else mem.f32[at >> 2] = n;
+
+function store(mem: AbiMemory, at: number, enc: LeafEnc, v: number | boolean): void {
+ switch (enc) {
+ case 'f64': mem.f64[at >> 3] = typeof v === 'boolean' ? (v ? 1 : 0) : v; break;
+ case 'f32': mem.f32[at >> 2] = typeof v === 'boolean' ? (v ? 1 : 0) : v; break;
+ case 'bool8': mem.u8[at] = v ? 1 : 0; break;
+ default: throw new Error(`ABI: nothing writes a ${enc} leaf yet`);
+ }
}
/**
@@ -297,11 +309,11 @@ export function abiHost(mem: AbiMemory, layout: AbiLayout, plan: SysPlan, call:
},
readField(base, owner, path) {
const leaf = leafAt(owner, path);
- return load(mem, (base as number) + leaf.byteOffset, leaf.bits);
+ return load(mem, (base as number) + leaf.byteOffset, leaf.enc);
},
writeField(base, owner, path, v) {
const leaf = leafAt(owner, path);
- store(mem, (base as number) + leaf.byteOffset, leaf.bits, v);
+ store(mem, (base as number) + leaf.byteOffset, leaf.enc, v);
},
resource(name) {
const k = plan.resources.indexOf(name);
@@ -363,7 +375,7 @@ export function abiHash(layout: AbiLayout, plans: readonly SysPlan[]): string {
];
const table = (kind: string, m: ReadonlyMap<string, FieldOffsets>): void => {
for (const [name, f] of m) {
- const leaves = [...f.leaves].map(([p, l]) => `${p}@${l.byteOffset}:${l.bits}`).join(',');
+ const leaves = [...f.leaves].map(([p, l]) => `${p}@${l.byteOffset}:${l.enc}`).join(',');
parts.push(`${kind} ${name} stride=${f.stride} ${leaves}`);
}
};
@@ -412,14 +424,23 @@ export function packLayout(shapes: ReadonlyMap<string, CompShape>): AbiLayout {
const resources = new Map<string, FieldOffsets>();
for (const [name, shape] of shapes) {
const leaves = new Map<string, Leaf>();
- let at = 0;
+ let end = 0;
+ let packed_at = 0;
for (const [path, spec] of shape.fields) {
- const width = spec.bits >> 3;
- at = (at + width - 1) & ~(width - 1);
- leaves.set(path, { byteOffset: at, bits: spec.bits, type: spec.type });
- at += width;
+ const width = encBytes(spec.enc);
+ // Where an engine field lives has ONE authority, and it is not this
+ // function. Only a host record, which has no C++ struct, is laid
+ // out here.
+ let at = spec.offset;
+ if (at === null) {
+ packed_at = (packed_at + width - 1) & ~(width - 1);
+ at = packed_at;
+ packed_at += width;
+ }
+ leaves.set(path, { byteOffset: at, enc: spec.enc, type: spec.type });
+ end = Math.max(end, at + width);
}
- const packed: FieldOffsets = { leaves, stride: Math.max(8, at) };
+ const packed: FieldOffsets = { leaves, stride: Math.max(8, (end + 7) & ~7) };
// A resource is addressed by field exactly as a component is, so the two
// tables differ only in which one a `Res(...)` parameter looks in.
(shape.storage === 'host' && RESOURCES.has(name) ? resources : comps).set(name, packed);
diff --git a/compiler/src/builtins.ts b/compiler/src/builtins.ts
index 4011287a3..1b55f2c96 100644
--- a/compiler/src/builtins.ts
+++ b/compiler/src/builtins.ts
@@ -14,9 +14,9 @@
* file exists to avoid.
*/
import { PTR_LAYOUTS } from '../../sdk/src/wasm/ptrLayouts.generated';
-import { BOOL, F64, storageBits, type CompShape, type EirType, type FieldSpec, type Storage } from './eir';
+import { BOOL, F64, HOST_ENC, type CompShape, type FieldSpec, type LeafEnc } from './eir';
-/** Leaf member names per composite field, in memory order. */
+/** Leaf member names per composite field, in memory order. Every one is f32. */
const MEMBERS: Record<string, readonly string[]> = {
vec2: ['x', 'y'],
vec3: ['x', 'y', 'z'],
@@ -25,8 +25,14 @@ const MEMBERS: Record<string, readonly string[]> = {
color: ['r', 'g', 'b', 'a'],
};
-function leafSpec(t: string, storage: Storage): FieldSpec {
- return { type: t === 'bool' ? BOOL : F64, bits: storageBits(storage) };
+/** EHT's field type -> how those bytes are encoded. */
+const ENC: Record<string, LeafEnc> = {
+ f32: 'f32', bool: 'bool8', i32: 'i32', u32: 'u32', u8: 'u8',
+};
+
+function engineLeaf(t: string, offset: number): FieldSpec {
+ const enc = ENC[t] ?? 'f32';
+ return { type: enc === 'bool8' ? BOOL : F64, enc, offset };
}
/**
@@ -41,11 +47,15 @@ export function builtinShapes(): Map<string, CompShape> {
for (const f of layout.fields) {
const members = MEMBERS[f.type];
if (members) {
- for (const m of members) fields.set(`${f.name}.${m}`, leafSpec('f32', 'engine'));
+ // A composite is four-byte members laid end to end from the
+ // field's own offset — the same arithmetic ptrAccessors does.
+ members.forEach((m, i) => fields.set(`${f.name}.${m}`, engineLeaf('f32', f.offset + i * 4)));
} else if (f.type === 'struct') {
- for (const m of f.members ?? []) fields.set(`${f.name}.${m.name}`, leafSpec(m.type, 'engine'));
+ for (const m of f.members ?? []) {
+ fields.set(`${f.name}.${m.name}`, engineLeaf(m.type, f.offset + m.offset));
+ }
} else {
- fields.set(f.name, leafSpec(f.type, 'engine'));
+ fields.set(f.name, engineLeaf(f.type, f.offset));
}
}
// EHT's table IS the engine's flat pools, so everything from it is
@@ -64,7 +74,7 @@ const TIME: CompShape = {
storage: 'host',
fields: new Map<string, FieldSpec>(
['delta', 'elapsed', 'frameCount', 'fixedDelta', 'fixedAlpha', 'fixedTick', 'scale', 'unscaledDelta']
- .map((k) => [k, { type: F64, bits: 64 }] as const)),
+ .map((k) => [k, { type: F64, enc: HOST_ENC, offset: null }] as const)),
};
/**
diff --git a/compiler/src/codegen.ts b/compiler/src/codegen.ts
index 8cfd38c63..515b5943a 100644
--- a/compiler/src/codegen.ts
+++ b/compiler/src/codegen.ts
@@ -35,7 +35,7 @@ import {
import {
BOOL, F64,
type EirFn, type EirModule, type EirSystem, type EirType, type Expr, type Local,
- type MathFn, type Place, type Stmt,
+ type LeafEnc, type MathFn, type Place, type Stmt,
} from './eir';
/**
@@ -147,6 +147,11 @@ static inline void es_set_f32(unsigned char *p, double v) { float f = (float)v;
static inline double es_f64(const unsigned char *p) { double v; memcpy(&v, p, 8); return v; }
static inline void es_set_f64(unsigned char *p, double v) { memcpy(p, &v, 8); }
+/* A bool in the C++ structs is ONE byte. Reading it as a float would read three
+ bytes of whatever follows it, which is a value rather than an error. */
+static inline int es_bool(const unsigned char *p) { return *p != 0; }
+static inline void es_set_bool(unsigned char *p, int v) { *p = (unsigned char)(v ? 1 : 0); }
+
/* ---------------------------------------------------------------------------
Math. Only the operations ECMAScript specifies EXACTLY are in the subset, but
"exactly specified" is not the same as "what libm does" — three of them
@@ -272,6 +277,16 @@ function num(v: number): string {
return /[.eE]/.test(s) ? s : `${s}.0`;
}
+/**
+ * One accessor per encoding the subset admits. The integer three are absent
+ * because the frontend refuses those leaves; if one reaches here it is a
+ * compiler bug, and an undefined index says so louder than a wrong load.
+ */
+const LOAD: Partial<Record<LeafEnc, string>> = { f32: 'es_f32', f64: 'es_f64', bool8: 'es_bool' };
+const STORE: Partial<Record<LeafEnc, string>> = {
+ f32: 'es_set_f32', f64: 'es_set_f64', bool8: 'es_set_bool',
+};
+
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',
@@ -396,8 +411,10 @@ class Emitter {
private read(p: Place, type: EirType): string {
if (p.p === 'local') return cName(this.local(p.id));
const { addr, leaf } = this.address(p.base, p.path);
- const load = leaf.bits === 64 ? `es_f64(${addr})` : `es_f32(${addr})`;
- return coerce(load, F64, type);
+ // The read's C type follows the ENCODING, and the coercion after it
+ // follows the EIR type: a bool byte reads as an int and never as 0.0f.
+ const read = `${LOAD[leaf.enc]}(${addr})`;
+ return coerce(read, leaf.enc === 'bool8' ? BOOL : F64, type);
}
/** An expression, parenthesised so composition never needs precedence rules. */
@@ -454,8 +471,9 @@ class Emitter {
break;
}
const { addr, leaf } = this.address(s.target.base, s.target.path);
- const store = leaf.bits === 64 ? 'es_set_f64' : 'es_set_f32';
- this.line(indent, `${store}(${addr}, ${coerce(this.expr(s.value), s.value.type, F64)});`);
+ const want = leaf.enc === 'bool8' ? BOOL : F64;
+ this.line(indent,
+ `${STORE[leaf.enc]}(${addr}, ${coerce(this.expr(s.value), s.value.type, want)});`);
break;
}
case 'if': {
diff --git a/compiler/src/eir.ts b/compiler/src/eir.ts
index 3cd920cd4..151b3a576 100644
--- a/compiler/src/eir.ts
+++ b/compiler/src/eir.ts
@@ -156,10 +156,32 @@ export interface EirSystem {
*/
export type Storage = 'engine' | 'host';
-/** One leaf field: what it computes as, and how wide it is stored. */
+/**
+ * How a leaf is stored. `f64` is a host record; the rest are what EHT says the
+ * C++ struct holds, and the integer three are here so a refusal can NAME them
+ * rather than the shape pretending the field does not exist.
+ */
+export type LeafEnc = 'f32' | 'f64' | 'bool8' | 'i32' | 'u32' | 'u8';
+
+export function encBytes(enc: LeafEnc): number {
+ switch (enc) {
+ case 'f64': return 8;
+ case 'bool8': case 'u8': return 1;
+ default: return 4;
+ }
+}
+
+/** One leaf field: what it computes as, how it is stored, and WHERE. */
export interface FieldSpec {
readonly type: EirType;
- readonly bits: 32 | 64;
+ readonly enc: LeafEnc;
+ /**
+ * EHT's byte offset in the C++ struct; `null` for a host record, which has
+ * no struct and is laid out by the ABI. Not derivable — a field EHT does
+ * not expose leaves a gap in front of the ones it does, and reading across
+ * it is a read of a DIFFERENT FIELD rather than an error.
+ */
+ readonly offset: number | null;
}
/** A component's field shape, flattened to leaf paths of one scalar each. */
@@ -170,10 +192,8 @@ export interface CompShape {
readonly fields: ReadonlyMap<string, FieldSpec>;
}
-/** Bits every field of a shape in this storage is stored at. */
-export function storageBits(storage: Storage): 32 | 64 {
- return storage === 'engine' ? 32 : 64;
-}
+/** What a host record's numbers are: JS objects, so f64 throughout. */
+export const HOST_ENC: LeafEnc = 'f64';
export interface EirModule {
readonly systems: readonly EirSystem[];
diff --git a/compiler/src/frontend.ts b/compiler/src/frontend.ts
index 49756b117..7d4e9bbb6 100644
--- a/compiler/src/frontend.ts
+++ b/compiler/src/frontend.ts
@@ -27,7 +27,7 @@
import { sep } from 'node:path';
import ts from 'typescript';
import {
- BOOL, ENTITY, F64,
+ BOOL, ENTITY, F64, HOST_ENC,
type CompShape, type EirModule, type EirSystem, type EirType,
MATH_FNS,
type FieldSpec, type EirFn, type Expr, type Local, type Place, type QueryArg, type Stmt, type BinOp, type LogicOp,
@@ -531,17 +531,32 @@ class SystemLowerer {
if (!shape) throw new NotInSubset(node, `no declared shape for component '${base.type.name}'`);
const f = shape.fields.get(key);
if (!f) throw new NotInSubset(node, `'${base.type.name}' has no field '${key}'`);
- return f.type;
+ return this.leafType(node, `${base.type.name}.${key}`, f);
}
if (base.type.k === 'res') {
const shape = this.comps.get(base.type.name);
const f = shape?.fields.get(key);
if (!f) throw new NotInSubset(node, `resource '${base.type.name}' has no field '${key}'`);
- return f.type;
+ return this.leafType(node, `${base.type.name}.${key}`, f);
}
throw new NotInSubset(node, `'${base.name}' has no fields to read`);
}
+ /**
+ * The EIR type a stored leaf reads as, or a refusal naming its encoding. An
+ * integer leaf is `pending`: what is missing is an EIR integer type, without
+ * which the two sides could not agree — C narrowing an out-of-range double
+ * is undefined where JS wraps.
+ */
+ private leafType(node: ts.Node, where: string, f: FieldSpec): EirType {
+ if (f.enc === 'i32' || f.enc === 'u32' || f.enc === 'u8') {
+ throw new NotInSubset(node,
+ `'${where}' is stored as ${f.enc}, and this subset has no integer type`
+ + ' — reading it as a double could not be reproduced bit-for-bit');
+ }
+ return f.type;
+ }
+
/**
* `Math.abs(x)` and friends. Only the operations ECMAScript specifies to the
* bit: sin/cos/tan/exp/log/pow are implementation-defined, so a native
@@ -685,9 +700,9 @@ function componentShape(call: ts.CallExpression): CompShape | null {
&& prop.initializer.operator === ts.SyntaxKind.MinusToken
? prop.initializer.operand
: prop.initializer;
- if (ts.isNumericLiteral(init)) fields.set(prop.name.text, { type: F64, bits: 64 });
+ if (ts.isNumericLiteral(init)) fields.set(prop.name.text, { type: F64, enc: HOST_ENC, offset: null });
else if (init.kind === ts.SyntaxKind.TrueKeyword || init.kind === ts.SyntaxKind.FalseKeyword) {
- fields.set(prop.name.text, { type: BOOL, bits: 64 });
+ fields.set(prop.name.text, { type: BOOL, enc: HOST_ENC, offset: null });
} else return null;
}
// defineComponent lands in ScriptStorage — a Map of JS objects — so its
@@ -700,7 +715,7 @@ function sameShape(a: CompShape, b: CompShape): boolean {
if (a.fields.size !== b.fields.size) return false;
for (const [k, f] of a.fields) {
const other = b.fields.get(k);
- if (other?.type.k !== f.type.k || other.bits !== f.bits) return false;
+ if (other?.type.k !== f.type.k || other.enc !== f.enc || other.offset !== f.offset) return false;
}
return true;
}
diff --git a/compiler/tests/codegen.test.ts b/compiler/tests/codegen.test.ts
index 0bbd955a0..c3f9ff9f5 100644
--- a/compiler/tests/codegen.test.ts
+++ b/compiler/tests/codegen.test.ts
@@ -48,6 +48,7 @@ import type { Row } from '../src/interp';
import { moveSystem } from '../../examples/ecs-basics/src/systems/move';
import { driftSystem } from './fixtures/in-subset';
import { PROBE } from './probe';
+import { builtinShapes as shapesForPins } from '../src/builtins';
import type { StubSystem } from './stubs/esengine';
const ROOT = resolve(fileURLToPath(new URL('../..', import.meta.url)));
@@ -293,6 +294,12 @@ function fixtureWorld(layout: AbiLayout): AbiMemory {
// The probe values are the point of this component, not a default: they
// are where libm and ECMAScript disagree.
mem.addComponent('FixtureMathProbe', i, { v: PROBE[(i - 1) % PROBE.length]! });
+ // An ENGINE component, so these land at EHT's offsets and encodings:
+ // fov at byte 4 (a repack would say 1) and isActive as one byte at 24.
+ mem.addComponent('Camera', i, {
+ fov: 40 + (i % 9) * 8, orthoSize: 1 + (i % 5), aspectRatio: 1.25 + (i % 3) * 0.5,
+ isActive: i % 3 !== 0,
+ });
}
return mem;
}
@@ -363,7 +370,8 @@ describe('the emitted C says what the interpreter says', () => {
// Every feature the subset gained after MoveSystem: branches and `&&`,
// 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']) {
+ for (const name of ['FixtureDrift', 'FixtureClampSys', 'FixtureTuned', 'FixtureHelpers',
+ 'FixtureMathOps', 'FixtureCamera']) {
it(`${name}: the whole image agrees with the interpreter`, () => {
const sys = systemOf(fixtures, name);
const layout = packLayout(fixtures.module.comps);
@@ -415,6 +423,34 @@ describe('the emitted C says what the interpreter says', () => {
}
});
+ it('an offset comes from EHT, and a repack cannot guess it', () => {
+ // Most engine layouts ARE dense once alignment is applied, which is why
+ // a repack agreed for so long. These four have a member EHT does not
+ // expose in front, so a repack reads into it.
+ const shapes = shapesForPins();
+ const at = (comp: string, path: string): number | null =>
+ shapes.get(comp)!.fields.get(path)!.offset;
+ expect(at('BitmapText', 'color.r'), 'a repack would say 0').toBe(12);
+ expect(at('DragonBonesAnimation', 'timeScale'), 'a repack would say 0').toBe(48);
+ expect(at('SpineAnimation', 'timeScale'), 'a repack would say 0').toBe(48);
+ expect(at('UINode', 'alignSelf'), 'a repack would say 73').toBe(76);
+ });
+
+ it('a bool is one byte, and an integer leaf is refused rather than guessed', () => {
+ const layout = packLayout(fixtures.module.comps);
+ const cam = layout.comps.get('Camera')!;
+ expect(cam.leaves.get('isActive')!.byteOffset).toBe(24);
+ expect(cam.leaves.get('isActive')!.enc).toBe('bool8');
+ expect(cam.leaves.get('priority')!.enc).toBe('i32');
+
+ const { source } = emitC(fixtures.module, layout, [systemOf(fixtures, 'FixtureCamera')]);
+ expect(source).toContain('#define ES_OFF_Camera_isActive 24u');
+ // One byte. Read as a float it would take three bytes of `priority` with
+ // it, and produce a number rather than an error.
+ expect(source).toMatch(/es_bool\(\w+ \+ ES_OFF_Camera_isActive\)/);
+ expect(source).toMatch(/es_set_bool\(\w+ \+ ES_OFF_Camera_isActive/);
+ });
+
it('the same source addressed as pointers gives the same image', () => {
// Why the address is a machine property: the C++ engine hands over
// 64-bit component pointers, which no 32-bit offset can name. Compiling
diff --git a/compiler/tests/fixtures/in-subset.ts b/compiler/tests/fixtures/in-subset.ts
index cb11f24e7..85d6fc00a 100644
--- a/compiler/tests/fixtures/in-subset.ts
+++ b/compiler/tests/fixtures/in-subset.ts
@@ -8,7 +8,7 @@
* by conformance.test.ts — a feature the frontend lowers but nobody
* runs both ways is a feature nobody has checked.
*/
-import { defineComponent, defineSystem, Query, Mut, Res, Time, Transform } from 'esengine';
+import { defineComponent, defineSystem, Query, Mut, Res, Camera, Time, Transform } from 'esengine';
export const Drift = defineComponent('FixtureDrift', { rate: 40, wrap: 100, enabled: true });
@@ -116,3 +116,24 @@ export const mathSystem = defineSystem(
},
{ name: 'FixtureMathOps' },
);
+
+/**
+ * An ENGINE component, so the offsets and encodings are EHT's rather than
+ * anything this compiler chose. `isActive` is ONE byte at 24; read as a float it
+ * would take three bytes of `priority` with it. Nothing else in the corpus
+ * reaches a bool in a C++ struct.
+ */
+export const cameraSystem = defineSystem(
+ [Query(Mut(Camera)), Res(Time)],
+ (query, time) => {
+ for (const [, camera] of query) {
+ if (camera.isActive) {
+ camera.fov = camera.fov + camera.aspectRatio * time.delta;
+ } else {
+ camera.orthoSize = Math.max(1, camera.orthoSize - time.delta);
+ }
+ camera.isActive = camera.fov < 90;
+ }
+ },
+ { name: 'FixtureCamera' },
+);
diff --git a/compiler/tests/fixtures/outside-subset.ts b/compiler/tests/fixtures/outside-subset.ts
index ced581587..5e40c2106 100644
--- a/compiler/tests/fixtures/outside-subset.ts
+++ b/compiler/tests/fixtures/outside-subset.ts
@@ -7,7 +7,7 @@
* @details Each names a rule from REARCH_AOT §3; subset.test.ts asserts the
* diagnostic points at the line and says why.
*/
-import { defineComponent, defineSystem, Query, Mut, Res, Time, Transform } from 'esengine';
+import { defineComponent, defineSystem, Query, Mut, Res, Camera, Time, Transform } from 'esengine';
export const Speed = defineComponent('FixtureSpeed', { value: 100 });
@@ -123,3 +123,18 @@ export const promiseKept = defineSystem(
},
{ name: 'FixturePromiseKept' },
);
+
+/**
+ * An integer leaf. `Camera.priority` is an i32 in the C++ struct, and this
+ * subset has no integer type — narrowing a double back into one is undefined in
+ * C where it wraps in JS, so the two could not be held to the same bits.
+ */
+export const integerField = defineSystem(
+ [Query(Mut(Camera))],
+ (query) => {
+ for (const [, camera] of query) {
+ camera.fov = camera.priority + 1;
+ }
+ },
+ { name: 'FixtureIntegerField' },
+);
diff --git a/compiler/tests/stubs/esengine.ts b/compiler/tests/stubs/esengine.ts
index c3f6d703c..c24961b90 100644
--- a/compiler/tests/stubs/esengine.ts
+++ b/compiler/tests/stubs/esengine.ts
@@ -35,6 +35,7 @@ export function Commands(): unknown {
return { kind: 'commands' };
}
export const Sprite = { _name: 'Sprite' };
+export const Camera = { _name: 'Camera' };
export function defineSystem(
params: readonly unknown[],
fn: (...args: any[]) => void,
diff --git a/compiler/tests/subset.test.ts b/compiler/tests/subset.test.ts
index 65332a740..cdac60f82 100644
--- a/compiler/tests/subset.test.ts
+++ b/compiler/tests/subset.test.ts
@@ -28,7 +28,7 @@ describe('the subset refuses, and says why', () => {
expect(result.seen).toEqual([
'FixtureLooping', 'FixtureTypo', 'FixtureTrig', 'FixtureCalling',
'FixtureWritesReadOnly', 'FixtureWritesConst',
- 'FixturePromised', 'FixturePromiseKept',
+ 'FixturePromised', 'FixturePromiseKept', 'FixtureIntegerField',
]);
});
@@ -38,6 +38,7 @@ describe('the subset refuses, and says why', () => {
['FixtureTrig', /Math\.sin is not exactly specified by ECMAScript/],
['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/],
])('refuses %s', (name, why) => {
const d = diagOf(name);
expect(d, `${name} compiled when it should not have`).toBeDefined();