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
test(aot): the C++ road answers the interpreter, not a twin written beside it
yhh213c3d0b0bf1
diff --git a/.github/workflows/build.yml b/.github/workflows/build.ymlindex d003a778c..d41591b69 100644--- a/.github/workflows/build.yml+++ b/.github/workflows/build.yml@@ -31,7 +31,7 @@ env:test_compressed_format test_batch_builder test_boundary_span test_webgpu_devicetest_clip_depth test_shadow_atlastest_text_edit test_render_graph test_device_loss test_physics_interpolation- test_bitmap_font test_texture_cache test_aot_host+ test_bitmap_font test_texture_cache test_aot_host test_aot_conformancejobs:build-emscripten:diff --git a/sdk/tests/aot-conformance.test.ts b/sdk/tests/aot-conformance.test.tsindex d8e83d62b..93f91078e 100644--- a/sdk/tests/aot-conformance.test.ts+++ b/sdk/tests/aot-conformance.test.ts@@ -16,7 +16,7 @@*/import { describe, it, expect } from 'vitest';import { spawnSync } from 'node:child_process';-import { mkdtempSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';+import { mkdtempSync, mkdirSync, existsSync, readFileSync, writeFileSync } from 'node:fs';import { tmpdir } from 'node:os';import path from 'node:path';@@ -34,6 +34,7 @@ import { createMockModule } from './mocks/wasm';import { FakeEngine } from './fakeEngine';import { useBytesPlatform } from './helpers/aotFade';import { Schedule } from '../src/ecs/system';+import { Time } from '../src/ecs/resource';import type { AotManifest } from '../src/ecs/aot/AotSystems';import type { Entity } from '../src/types';@@ -42,6 +43,17 @@ const FIXTURE = path.resolve(__dirname, 'fixtures/conformance-systems.ts');const FRAMES = 12;const DT = 1 / 60;+/** The seed world, at module scope because two readers need the same one: the+ * suite that plays it, and the header the native harness starts from. */+const SEEDS: readonly (readonly [number, number])[] =+ [[0, 120], [9.5, 60], [-9.5, -60], [3, -300]];++/** Where the native harness reads its inputs. Its own directory: the emitted C+ * includes `estella_offsets.h` by that name and guards it by that name, so two+ * fixtures cannot share one. */+const NATIVE_DIR = path.resolve(__dirname, '../../tests/aot/generated/conformance');+const WRITE = process.env['ESTELLA_AOT_WRITE'] === '1';+/** The artifact a build makes of the fixture: the module, and what it declares. */function compileFixture(emcc: string): { wasm: Uint8Array; manifest: AotManifest } {const lowered = lowerProgram([FIXTURE], builtinShapes());@@ -77,7 +89,7 @@ function compileFixture(emcc: string): { wasm: Uint8Array; manifest: AotManifesttype Trace = number[][][];async function play(compiled: { wasm: Uint8Array; manifest: AotManifest } | null): Promise<{- trace: Trace; calls: number;+ trace: Trace; calls: number; delta: number;}> {// One context for both roads on purpose: the fixture's `defineComponent`// runs once, at import, and a road that reset the registry under it would@@ -100,8 +112,7 @@ async function play(compiled: { wasm: Uint8Array; manifest: AotManifest } | nullruntime = (app as unknown as { aot_: { systems: { calls: number } } }).aot_;}- const seeds: [number, number][] = [[0, 120], [9.5, 60], [-9.5, -60], [3, -300]];- const entities: Entity[] = seeds.map(([x, speed]) => {+ const entities: Entity[] = SEEDS.map(([x, speed]) => {const e = app.world.spawn();app.world.insert(e, fixture.Mover, { x, speed, bounces: 0 });return e;@@ -115,7 +126,12 @@ async function play(compiled: { wasm: Uint8Array; manifest: AotManifest } | nullreturn [m.x, m.speed, m.bounces];}));}- return { trace, calls: runtime?.systems.calls ?? 0 };+ // The delta the interpreter was HANDED, which is what the native harness is+ // given: `tick` scales what it is asked for, and a harness restating 1/60+ // would be a second opinion about the frame rather than a reading of it.+ const time = (app as unknown as { resources_: { get: (r: unknown) => { delta: number } } })+ .resources_.get(Time);+ return { trace, calls: runtime?.systems.calls ?? 0, delta: time.delta };}describe.skipIf(!EMCC)('one source, interpreted and compiled', () => {@@ -143,3 +159,125 @@ describe.skipIf(!EMCC)('one source, interpreted and compiled', () => {expect(interpreted.trace[FRAMES - 1]).not.toEqual(interpreted.trace[0]);});});++/**+ * The same lowering the wasm road takes, at the width a LOADING host uses.+ *+ * One source, two machines: the C is byte for byte the same file either way+ * and the width is a typedef the building compiler picks, so this is the same+ * artifact rather than a second one written for the harness.+ */+function nativeArtifact(): ReturnType<typeof emitC> {+ const lowered = lowerProgram([FIXTURE], builtinShapes());+ expect(brokenPromises(lowered), 'the fixture must compile').toEqual([]);+ const inlined = lowered.module.systems.map((s) => inlineSystem(s, lowered.module.fns));+ return emitC(lowered.module, packLayout(lowered.module.comps), inlined, 8);+}++/** A checked-in input to the C++ harness. Regenerate them all with+ * `ESTELLA_AOT_WRITE=1 pnpm --filter @estella/sdk test aot-conformance`. */+function artifact(name: string, want: string): void {+ const at = path.join(NATIVE_DIR, name);+ if (WRITE) {+ mkdirSync(NATIVE_DIR, { recursive: true });+ writeFileSync(at, want);+ return;+ }+ expect(existsSync(at), `${name} is missing — regenerate with ESTELLA_AOT_WRITE=1`).toBe(true);+ // Normalised: git may have handed the working tree CRLF, and the difference+ // is not one anybody wants a diff about.+ const have = readFileSync(at, 'utf8').replace(/\r\n/g, '\n');+ expect(have, `${name} is stale — regenerate with ESTELLA_AOT_WRITE=1`).toBe(want);+}++/** A double as C source. Shortest round-trip: both languages read a decimal to+ * the NEAREST binary64, so what JS prints is the number C gets back. `-0` is+ * the one value JS prints without its sign, and `-speed` can produce it. */+function cDouble(v: number): string {+ if (Object.is(v, -0)) return '-0.0';+ const s = String(v);+ return /[.eE]/.test(s) ? s : `${s}.0`;+}++/** The handshake the harness compares the artifact's own baked numbers against.+ * From the same function the artifact's come from, so the harness carries no+ * second opinion about what this engine or this build is. */+function handshakeHeader(h: { engineAbi: string; moduleContract: string }): string {+ return [+ '/* GENERATED by sdk/tests/aot-conformance.test.ts — do not edit. */',+ '/* The contract half of the handshake. The width half is the harness. */',+ `#define ES_CONF_EXPECTED_CONTRACT_HASH 0x${h.engineAbi}ULL`,+ '/* And which BUILD the artifact beside this one is. */',+ `#define ES_CONF_EXPECTED_MODULE_CONTRACT 0x${h.moduleContract}ULL`,+ '',+ ].join('\n');+}++/**+ * The interpreter's answer, as a header the native harness includes.+ *+ * The point is WHOSE answer it is: the harness held a twin loop written in C++,+ * which only ever asked whether two C-family readings of one struct agree.+ * This asks what the author's closure does.+ */+function traceHeader(run: { trace: Trace; delta: number }): string {+ return [+ '/* GENERATED by sdk/tests/aot-conformance.test.ts — do not edit. */',+ '/* What the INTERPRETER makes of sdk/tests/fixtures/conformance-systems.ts,',+ ' frame by frame, so a divergence names the frame it began on. */',+ '#ifndef ESTELLA_CONFORMANCE_TRACE_H',+ '#define ESTELLA_CONFORMANCE_TRACE_H',+ '',+ `#define ES_CONF_ENTITIES ${SEEDS.length}u`,+ `#define ES_CONF_FRAMES ${FRAMES}u`,+ '/* x, speed, bounces — ConfMover in declaration order, which is the order',+ ' the ABI lays a script record out in. */',+ '#define ES_CONF_FIELDS 3u',+ '/* The delta the interpreter was handed, rather than the one it asked for. */',+ `#define ES_CONF_DELTA ${cDouble(run.delta)}`,+ '',+ 'static const double ES_CONF_SEED[ES_CONF_ENTITIES][ES_CONF_FIELDS] = {',+ ...SEEDS.map(([x, speed]) => ` { ${cDouble(x)}, ${cDouble(speed)}, 0.0 },`),+ '};',+ '',+ '/* After each frame, both systems having run in the order the schedule has',+ ' them: ConfDrift, then ConfClamp. */',+ 'static const double ES_CONF_EXPECT[ES_CONF_FRAMES][ES_CONF_ENTITIES][ES_CONF_FIELDS] = {',+ ...run.trace.flatMap((frame, f) => [+ ` { /* frame ${f} */`,+ ...frame.map((m) => ` { ${m.map(cDouble).join(', ')} },`),+ ' },',+ ]),+ '};',+ '',+ '#endif',+ '',+ ].join('\n');+}++/**+ * The third road's inputs, written where a C++ harness can build them.+ *+ * Not behind emsdk: this is the compiler and the interpreter, and a machine+ * without emscripten still has to notice that the checked-in artifacts have+ * gone stale — otherwise the only gate on them is a road it cannot walk.+ */+describe('the inputs a loading host builds against', () => {+ it('the C the compiler makes of the fixture, at the loading width', () => {+ const c = nativeArtifact();+ artifact('estella_offsets.h', c.offsets);+ artifact('systems.c', c.source);+ artifact('systems_decl.c', c.decls);+ artifact('handshake.h', handshakeHeader(c.handshake));+ });++ it('and the answer the interpreter gives, for the harness to hold it against', async () => {+ setDefaultContext(new AppContext());+ setEditorMode(false);+ setPlayMode(false);+ const run = await play(null);+ // A seed world that ends where it started proves nothing on any road.+ expect(run.trace[FRAMES - 1]).not.toEqual(run.trace[0]);+ artifact('trace.h', traceHeader(run));+ });+});diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txtindex 72ff431c7..f689783b1 100644--- a/tests/CMakeLists.txt+++ b/tests/CMakeLists.txt@@ -94,6 +94,37 @@ if(NOT EMSCRIPTEN))endif()+# AOT: the same compiled TypeScript against the INTERPRETER's answer instead of+# against a twin loop written in C++. Both the C and the expected frames are+# generated by sdk/tests/aot-conformance.test.ts and checked in, which is what+# lets a C++ harness hold a JS closure's answer without running one.+#+# Its own generated directory, and NOT tests/aot/generated: the emitted C+# includes `estella_offsets.h` by that name and guards it by that name, so two+# fixtures sharing one include path would quietly take each other's offsets.+add_executable(test_aot_conformance+ aot/test_aot_conformance.cpp+ aot/generated/conformance/systems.c+ aot/generated/conformance/systems_decl.c+ ${CMAKE_SOURCE_DIR}/src/esengine/core/Log.cpp+)+target_include_directories(test_aot_conformance PRIVATE+ ${CMAKE_SOURCE_DIR}/src+ ${CMAKE_SOURCE_DIR}/src/esengine/aot+ ${CMAKE_SOURCE_DIR}/tests/aot+ ${CMAKE_SOURCE_DIR}/tests/aot/generated/conformance+ ${CMAKE_SOURCE_DIR}/third_party/glm+)+# -ffp-contract=off is part of the contract, not a preference: a fused+# multiply-add is more accurate than the two roundings JS does, and more+# accurate is still a different number (compiler/src/codegen.ts CFLAGS).+target_compile_options(test_aot_conformance PRIVATE+ $<$<C_COMPILER_ID:GNU,Clang,AppleClang>:-ffp-contract=off>+ $<$<CXX_COMPILER_ID:GNU,Clang,AppleClang>:-ffp-contract=off>+ $<$<CXX_COMPILER_ID:MSVC>:/fp:precise>+)+add_test(NAME test_aot_conformance COMMAND test_aot_conformance)+# SparseSet testsadd_executable(test_sparse_setecs/test_sparse_set.cppdiff --git a/tests/aot/generated/conformance/estella_offsets.h b/tests/aot/generated/conformance/estella_offsets.hnew file mode 100644index 000000000..c1d368a03--- /dev/null+++ b/tests/aot/generated/conformance/estella_offsets.h@@ -0,0 +1,13 @@+/* GENERATED by @estella/compiler — do not edit. */+/* Field offsets from EHT, for the systems this program compiled. The+ engine side asserts its own offsetof against these: a disagreement is+ a read of a DIFFERENT FIELD, not an error. */+#ifndef ESTELLA_OFFSETS_H+#define ESTELLA_OFFSETS_H++#define ES_OFF_ConfMover_bounces 16u+#define ES_OFF_ConfMover_speed 8u+#define ES_OFF_ConfMover_x 0u+#define ES_OFF_Time_delta 0u++#endif /* ESTELLA_OFFSETS_H */diff --git a/tests/aot/generated/conformance/handshake.h b/tests/aot/generated/conformance/handshake.hnew file mode 100644index 000000000..b44e597a1--- /dev/null+++ b/tests/aot/generated/conformance/handshake.h@@ -0,0 +1,5 @@+/* GENERATED by sdk/tests/aot-conformance.test.ts — do not edit. */+/* The contract half of the handshake. The width half is the harness. */+#define ES_CONF_EXPECTED_CONTRACT_HASH 0xaa8849ed8d31d9a0ULL+/* And which BUILD the artifact beside this one is. */+#define ES_CONF_EXPECTED_MODULE_CONTRACT 0x1b0366c7f77a6dadULLdiff --git a/tests/aot/generated/conformance/systems.c b/tests/aot/generated/conformance/systems.cnew file mode 100644index 000000000..1fbe63a1f--- /dev/null+++ b/tests/aot/generated/conformance/systems.c@@ -0,0 +1,50 @@+/* GENERATED by @estella/compiler — do not edit. */+/* This file calls the engine zero times, and holds no data of its own. */+#include "estella_abi.h"+#include "estella_offsets.h"++/* Which BUILD this is, for a loader holding the sidecar written beside+ it. The two digests above answer "is this engine right" and "are the+ project shapes right"; neither answers "are these two the same pair". */+ES_EXPORT uint32_t es_module_contract_lo(void) { return 0xf77a6dadu; }+ES_EXPORT uint32_t es_module_contract_hi(void) { return 0x1b0366c7u; }++ES_EXPORT void es_sys_ConfDrift(es_addr_t es_ctx) {+ const EsSysCtx *es_c = (const EsSysCtx *)ES_PTR(es_ctx);+ const EsQueryRows *es_queries = (const EsQueryRows *)ES_PTR(es_c->queries);+ const es_addr_t *es_resources = (const es_addr_t *)ES_PTR(es_c->resources);+ unsigned char *time_1 = ES_PTR(es_resources[0]);+ {+ const es_addr_t *es_rows0 = (const es_addr_t *)ES_PTR(es_queries[0].rows);+ const es_addr_t es_n0 = es_queries[0].count;+ for (es_addr_t es_i0 = 0; es_i0 < es_n0; ++es_i0) {+ const es_addr_t *es_row0 = es_rows0 + es_i0 * 2u;+ unsigned char *m_2 = ES_PTR(es_row0[1]);+ es_set_f64(m_2 + ES_OFF_ConfMover_x, (es_f64(m_2 + ES_OFF_ConfMover_x) + (es_f64(m_2 + ES_OFF_ConfMover_speed) * es_f64(time_1 + ES_OFF_Time_delta))));+ }+ }+}++ES_EXPORT void es_sys_ConfClamp(es_addr_t es_ctx) {+ const EsSysCtx *es_c = (const EsSysCtx *)ES_PTR(es_ctx);+ const EsQueryRows *es_queries = (const EsQueryRows *)ES_PTR(es_c->queries);+ {+ const es_addr_t *es_rows0 = (const es_addr_t *)ES_PTR(es_queries[0].rows);+ const es_addr_t es_n0 = es_queries[0].count;+ for (es_addr_t es_i0 = 0; es_i0 < es_n0; ++es_i0) {+ const es_addr_t *es_row0 = es_rows0 + es_i0 * 2u;+ unsigned char *m_1 = ES_PTR(es_row0[1]);+ if ((es_f64(m_1 + ES_OFF_ConfMover_x) > 10.0)) {+ es_set_f64(m_1 + ES_OFF_ConfMover_x, 10.0);+ es_set_f64(m_1 + ES_OFF_ConfMover_speed, (-es_f64(m_1 + ES_OFF_ConfMover_speed)));+ es_set_f64(m_1 + ES_OFF_ConfMover_bounces, (es_f64(m_1 + ES_OFF_ConfMover_bounces) + 1.0));+ } else {+ if ((es_f64(m_1 + ES_OFF_ConfMover_x) < (-10.0))) {+ es_set_f64(m_1 + ES_OFF_ConfMover_x, (-10.0));+ es_set_f64(m_1 + ES_OFF_ConfMover_speed, (-es_f64(m_1 + ES_OFF_ConfMover_speed)));+ es_set_f64(m_1 + ES_OFF_ConfMover_bounces, (es_f64(m_1 + ES_OFF_ConfMover_bounces) + 1.0));+ }+ }+ }+ }+}diff --git a/tests/aot/generated/conformance/systems_decl.c b/tests/aot/generated/conformance/systems_decl.cnew file mode 100644index 000000000..a88746189--- /dev/null+++ b/tests/aot/generated/conformance/systems_decl.c@@ -0,0 +1,34 @@+/* GENERATED by @estella/compiler — do not edit. */+/* The static half: what this module is, for a host that reads it out of+ the artifact rather than out of a manifest beside it. Separate because+ a wasm module sharing the ENGINE's memory must carry no data section —+ its bytes would land at a link-time address the engine already owns. */+#include "estella_abi.h"++/* What this module baked in about the engine it was built for. A+ host compares before it maps anything — a mismatch is not a wrong+ answer, it is a read of a different field. The address width belongs+ to the MACHINE, so it mixes in here rather than in the compiler and a+ 32-bit artifact cannot load into a 64-bit host. */+#define ES_ABI_ENGINE_DIGEST 0xaa8849ed8d31d9a0ULL+ES_EXPORT const uint64_t es_abi_hash =+ ES_ABI_ENGINE_DIGEST ^ (0x9e3779b97f4a7c15ULL * (uint64_t)sizeof(es_addr_t));++ES_EXPORT void es_sys_ConfDrift(es_addr_t es_ctx);+ES_EXPORT void es_sys_ConfClamp(es_addr_t es_ctx);++/* The systems in this file, and what each one needs filled in. */+static const char *const es_sys_ConfDrift_q0_comps[] = { "ConfMover" };+static const unsigned char es_sys_ConfDrift_q0_mut[] = { 1u };+static const EsQueryDecl es_sys_ConfDrift_queries[] = { { es_sys_ConfDrift_q0_comps, es_sys_ConfDrift_q0_mut, 1u } };+static const char *const es_sys_ConfDrift_resources[] = { "Time" };+static const unsigned char es_sys_ConfDrift_resources_mut[] = { 0u };+static const char *const es_sys_ConfClamp_q0_comps[] = { "ConfMover" };+static const unsigned char es_sys_ConfClamp_q0_mut[] = { 1u };+static const EsQueryDecl es_sys_ConfClamp_queries[] = { { es_sys_ConfClamp_q0_comps, es_sys_ConfClamp_q0_mut, 1u } };++ES_EXPORT const EsSystemDecl es_systems[] = {+ { "ConfDrift", es_sys_ConfDrift, es_sys_ConfDrift_queries, es_sys_ConfDrift_resources, es_sys_ConfDrift_resources_mut, 1u, 1u },+ { "ConfClamp", es_sys_ConfClamp, es_sys_ConfClamp_queries, NULL, NULL, 1u, 0u },+};+ES_EXPORT const uint32_t es_system_count = 2u;diff --git a/tests/aot/generated/conformance/trace.h b/tests/aot/generated/conformance/trace.hnew file mode 100644index 000000000..fdc35d63e--- /dev/null+++ b/tests/aot/generated/conformance/trace.h@@ -0,0 +1,99 @@+/* GENERATED by sdk/tests/aot-conformance.test.ts — do not edit. */+/* What the INTERPRETER makes of sdk/tests/fixtures/conformance-systems.ts,+ frame by frame, so a divergence names the frame it began on. */+#ifndef ESTELLA_CONFORMANCE_TRACE_H+#define ESTELLA_CONFORMANCE_TRACE_H++#define ES_CONF_ENTITIES 4u+#define ES_CONF_FRAMES 12u+/* x, speed, bounces — ConfMover in declaration order, which is the order+ the ABI lays a script record out in. */+#define ES_CONF_FIELDS 3u+/* The delta the interpreter was handed, rather than the one it asked for. */+#define ES_CONF_DELTA 0.016666666666666666++static const double ES_CONF_SEED[ES_CONF_ENTITIES][ES_CONF_FIELDS] = {+ { 0.0, 120.0, 0.0 },+ { 9.5, 60.0, 0.0 },+ { -9.5, -60.0, 0.0 },+ { 3.0, -300.0, 0.0 },+};++/* After each frame, both systems having run in the order the schedule has+ them: ConfDrift, then ConfClamp. */+static const double ES_CONF_EXPECT[ES_CONF_FRAMES][ES_CONF_ENTITIES][ES_CONF_FIELDS] = {+ { /* frame 0 */+ { 2.0, 120.0, 0.0 },+ { 10.0, -60.0, 1.0 },+ { -10.0, 60.0, 1.0 },+ { -2.0, -300.0, 0.0 },+ },+ { /* frame 1 */+ { 4.0, 120.0, 0.0 },+ { 9.0, -60.0, 1.0 },+ { -9.0, 60.0, 1.0 },+ { -7.0, -300.0, 0.0 },+ },+ { /* frame 2 */+ { 6.0, 120.0, 0.0 },+ { 8.0, -60.0, 1.0 },+ { -8.0, 60.0, 1.0 },+ { -10.0, 300.0, 1.0 },+ },+ { /* frame 3 */+ { 8.0, 120.0, 0.0 },+ { 7.0, -60.0, 1.0 },+ { -7.0, 60.0, 1.0 },+ { -5.0, 300.0, 1.0 },+ },+ { /* frame 4 */+ { 10.0, 120.0, 0.0 },+ { 6.0, -60.0, 1.0 },+ { -6.0, 60.0, 1.0 },+ { 0.0, 300.0, 1.0 },+ },+ { /* frame 5 */+ { 10.0, -120.0, 1.0 },+ { 5.0, -60.0, 1.0 },+ { -5.0, 60.0, 1.0 },+ { 5.0, 300.0, 1.0 },+ },+ { /* frame 6 */+ { 8.0, -120.0, 1.0 },+ { 4.0, -60.0, 1.0 },+ { -4.0, 60.0, 1.0 },+ { 10.0, 300.0, 1.0 },+ },+ { /* frame 7 */+ { 6.0, -120.0, 1.0 },+ { 3.0, -60.0, 1.0 },+ { -3.0, 60.0, 1.0 },+ { 10.0, -300.0, 2.0 },+ },+ { /* frame 8 */+ { 4.0, -120.0, 1.0 },+ { 2.0, -60.0, 1.0 },+ { -2.0, 60.0, 1.0 },+ { 5.0, -300.0, 2.0 },+ },+ { /* frame 9 */+ { 2.0, -120.0, 1.0 },+ { 1.0, -60.0, 1.0 },+ { -1.0, 60.0, 1.0 },+ { 0.0, -300.0, 2.0 },+ },+ { /* frame 10 */+ { 0.0, -120.0, 1.0 },+ { 0.0, -60.0, 1.0 },+ { 0.0, 60.0, 1.0 },+ { -5.0, -300.0, 2.0 },+ },+ { /* frame 11 */+ { -2.0, -120.0, 1.0 },+ { -1.0, -60.0, 1.0 },+ { 1.0, 60.0, 1.0 },+ { -10.0, -300.0, 2.0 },+ },+};++#endifdiff --git a/tests/aot/test_aot_conformance.cpp b/tests/aot/test_aot_conformance.cppnew file mode 100644index 000000000..eb74ee8c6--- /dev/null+++ b/tests/aot/test_aot_conformance.cpp@@ -0,0 +1,207 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file test_aot_conformance.cpp+ * @brief The compiled module against the INTERPRETER's answer, frame for frame.+ *+ * @details `test_aot_host` asks whether the emitted C moves a Registry the way+ * the same loop written in C++ moves it. That is a real question, and+ * it is a question between two C-family readings of one struct: the+ * oracle is a twin written beside the harness, so a lowering that+ * misread the AUTHOR would agree with a twin that misread it the same+ * way.+ *+ * This asks the other one. The oracle here is the interpreter -- the+ * closures the App actually runs -- recorded by+ * sdk/tests/aot-conformance.test.ts over the same seed world and+ * checked in as `trace.h`. Same source, same seeds, same delta; the+ * only difference is which road executes it.+ *+ * Compared after EVERY frame rather than at the end, so a divergence+ * names the frame it began on. `bounces` is in the comparison on+ * purpose: it moves only on a frame a branch is taken, so a road that+ * took the other arm is loud rather than merely off by a little.+ *+ * Width 8 and LINKED, not loaded: the loading road is `test_aot_host`'s+ * module case, and what is asked here is what the code computes.+ */+#define DOCTEST_CONFIG_IMPLEMENT_WITH_MAIN+#include <doctest.h>++#include <cstddef>+#include <cstdint>+#include <cstring>+#include <span>+#include <vector>++#include "esengine/aot/AotHost.hpp"+#include "esengine/core/Types.hpp"++#include "generated/conformance/estella_offsets.h"+#include "generated/conformance/handshake.h"+#include "generated/conformance/trace.h"++extern "C" {+/** What the artifact says it was built for, and which build it is. */+extern const std::uint64_t es_abi_hash;+std::uint32_t es_module_contract_lo(void);+std::uint32_t es_module_contract_hi(void);+/** The manifest the artifact carries: what its systems need filled in. */+extern const EsSystemDecl es_systems[];+extern const std::uint32_t es_system_count;+}++using namespace esengine;++namespace {++/** `defineComponent('ConfMover', ...)` lands in ScriptStorage, so the ABI lays+ * it out: declaration order, f64 each, because a JS record has no narrower. */+struct MoverRow {+ double x;+ double speed;+ double bounces;+};+static_assert(offsetof(MoverRow, x) == ES_OFF_ConfMover_x, "ConfMover.x moved");+static_assert(offsetof(MoverRow, speed) == ES_OFF_ConfMover_speed, "ConfMover.speed moved");+static_assert(offsetof(MoverRow, bounces) == ES_OFF_ConfMover_bounces, "ConfMover.bounces moved");++/** The resource, host-side. Only `delta` is reached here. */+struct TimeRow {+ double delta;+};+static_assert(offsetof(TimeRow, delta) == ES_OFF_Time_delta, "Time.delta moved");++/**+ * The world the trace was recorded over, held the way ScriptStorage holds one:+ * rows at a stride, a sparse table of slot+1 by entity index, and the dense side+ * a query narrows itself by.+ */+struct World {+ std::vector<MoverRow> movers;+ std::vector<std::uint32_t> sparse;+ std::vector<std::uint32_t> owners;+ TimeRow time{ES_CONF_DELTA};++ aot::RowSpan span() {+ return aot::RowSpan{+ sparse.data(),+ static_cast<std::uint32_t>(sparse.size()),+ reinterpret_cast<unsigned char*>(movers.data()),+ static_cast<std::uint32_t>(sizeof(MoverRow)),+ Entity::Layout::INDEX_MASK,+ owners.data(),+ static_cast<std::uint32_t>(owners.size()),+ };+ }+};++/** The seed rows are the header's, not a second list: the numbers the+ * interpreter started from are the numbers this starts from. */+World seedWorld() {+ World w;+ for (std::uint32_t i = 0; i < ES_CONF_ENTITIES; ++i) {+ // Version 0, so a raw id and its index are the same number here.+ const std::uint32_t e = i + 1u;+ w.movers.push_back(MoverRow{ES_CONF_SEED[i][0], ES_CONF_SEED[i][1], ES_CONF_SEED[i][2]});+ if (e >= w.sparse.size()) w.sparse.resize(e + 1u, 0u);+ w.sparse[e] = static_cast<std::uint32_t>(w.movers.size()); // slot + 1+ w.owners.push_back(e);+ }+ return w;+}++/** Handed over as memory, so nothing here calls back into the language that owns+ * the rows -- which is the whole reason a script pool can be compiled at all. */+aot::ComponentLookup componentsOf(World& w) {+ return [&w](const char* name) -> aot::ComponentAt {+ return std::strcmp(name, "ConfMover") == 0 ? aot::fromRows(w.span()) : aot::ComponentAt{};+ };+}++aot::ResourceLookup resourcesOf(World& w) {+ return [&w](const char* name) -> void* {+ return std::strcmp(name, "Time") == 0 ? &w.time : nullptr;+ };+}++/** The dense side, so a query narrows to its column instead of being offered+ * every entity this host knows. */+aot::CandidateLookup candidatesOf(World& w) {+ return [&w](const char* name) -> aot::CandidatesOf {+ if (std::strcmp(name, "ConfMover") != 0) return {};+ return [&w]() -> aot::Candidates {+ return std::span<const std::uint32_t>(w.owners.data(), w.owners.size());+ };+ };+}++const EsSystemDecl* declOf(const char* name) {+ for (std::uint32_t i = 0; i < es_system_count; ++i) {+ if (std::strcmp(es_systems[i].name, name) == 0) return &es_systems[i];+ }+ return nullptr;+}++} // namespace++TEST_CASE("the host and the artifact agree on the handshake") {+ CHECK(es_abi_hash == aot::abiHash(ES_CONF_EXPECTED_CONTRACT_HASH));+ const std::uint64_t said =+ (static_cast<std::uint64_t>(es_module_contract_hi()) << 32) | es_module_contract_lo();+ CHECK(said == ES_CONF_EXPECTED_MODULE_CONTRACT);+}++TEST_CASE("the module answers the interpreter's world after every frame") {+ World w = seedWorld();++ // Bound by NAME rather than by table position: the order they run in is the+ // schedule's, and the artifact is free to declare them in any other.+ const EsSystemDecl* driftDecl = declOf("ConfDrift");+ const EsSystemDecl* clampDecl = declOf("ConfClamp");+ REQUIRE(driftDecl != nullptr);+ REQUIRE(clampDecl != nullptr);+ const aot::BoundSystem drift =+ aot::bind(*driftDecl, componentsOf(w), resourcesOf(w), candidatesOf(w));+ const aot::BoundSystem clamp =+ aot::bind(*clampDecl, componentsOf(w), resourcesOf(w), candidatesOf(w));+ // An unbound system is not run at all, and a differential against a world+ // nothing touched reads as a disagreement about arithmetic.+ REQUIRE(drift.fn != nullptr);+ REQUIRE(clamp.fn != nullptr);++ const std::vector<std::uint32_t> every = w.owners;+ aot::CallArena arena;+ const aot::ResourceLookup resources = resourcesOf(w);++ for (std::uint32_t f = 0; f < ES_CONF_FRAMES; ++f) {+ // The order the trace was recorded in: drift moves, then clamp reflects+ // whatever left the interval.+ CHECK(aot::runBound(drift, every, resources, arena).empty());+ CHECK(aot::runBound(clamp, every, resources, arena).empty());++ for (std::uint32_t i = 0; i < ES_CONF_ENTITIES; ++i) {+ const MoverRow& got = w.movers[i];+ const double* want = ES_CONF_EXPECT[f][i];+ INFO("frame ", f, ", entity ", i);+ // Exact: both roads do the same operations in the same order on+ // binary64, which is what -ffp-contract=off is here to keep true.+ CHECK(got.x == want[0]);+ CHECK(got.speed == want[1]);+ CHECK(got.bounces == want[2]);+ }+ }+}++TEST_CASE("the fixture has somewhere to diverge") {+ // A trace that never moves, or never branches, agrees on every road: these+ // are the properties that make the comparison above worth running.+ bool moved = false;+ bool bounced = false;+ for (std::uint32_t i = 0; i < ES_CONF_ENTITIES; ++i) {+ if (ES_CONF_EXPECT[ES_CONF_FRAMES - 1u][i][0] != ES_CONF_SEED[i][0]) moved = true;+ if (ES_CONF_EXPECT[ES_CONF_FRAMES - 1u][i][2] != 0.0) bounced = true;+ }+ CHECK(moved);+ CHECK(bounced);+}diff --git a/tools/lib/contractFacts.mjs b/tools/lib/contractFacts.mjsindex 244813796..9bc00432a 100644--- a/tools/lib/contractFacts.mjs+++ b/tools/lib/contractFacts.mjs@@ -124,6 +124,29 @@ export const FACTS = [],digest: { name: 'engine-abi', path: 'tests/aot/generated/move_system_hash.h', probe: /ES_EXPECTED_CONTRACT_HASH/ },},+ {+ id: 'aotConformanceFixture',+ what: 'One source read twice — as the closures an App runs, and as the module compiled from them.',+ surface: 'runtime-aot-abi',+ // The SOURCE is the authority, and both roads are readings of it. The+ // trace is the interpreter's reading, projected so a C++ harness can+ // hold a compiled module against it without running a JS closure.+ authors: [+ { path: 'sdk/tests/fixtures/conformance-systems.ts', probe: /@compiled/, kind: 'semantic' },+ ],+ projections: [+ 'tests/aot/generated/conformance/estella_offsets.h',+ 'tests/aot/generated/conformance/systems.c',+ 'tests/aot/generated/conformance/systems_decl.c',+ 'tests/aot/generated/conformance/handshake.h',+ 'tests/aot/generated/conformance/trace.h',+ ],+ verification: [+ { path: 'sdk/tests/aot-conformance.test.ts', how: 'test', probe: /interpreted and compiled/ },+ { path: 'tests/aot/test_aot_conformance.cpp', how: 'test', probe: /after every frame/ },+ ],+ digest: { name: 'engine-abi', path: 'tests/aot/generated/conformance/handshake.h', probe: /ES_CONF_EXPECTED_CONTRACT_HASH/ },+ },{id: 'entityRepresentation',what: 'How an entity handle packs an index and a generation into one u32.',