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(assets): a mesh is a file, loaded like every other asset

esenginea499327c4229
diff --git a/desktop/public/scenes/two-triangles.esmesh b/desktop/public/scenes/two-triangles.esmesh
new file mode 100644
index 000000000..ba24bef9e
Binary files /dev/null and b/desktop/public/scenes/two-triangles.esmesh differ
diff --git a/desktop/scripts/headless-verify.mjs b/desktop/scripts/headless-verify.mjs
index 3d20ccd87..4a21db943 100644
--- a/desktop/scripts/headless-verify.mjs
+++ b/desktop/scripts/headless-verify.mjs
@@ -124,7 +124,8 @@ function finish(result, server) {
const deviceLossOk = lossSeen && cameBack && drivenSteps && growthOk;
// Freezing nothing would pass every pixel assertion by not having changed the
// scene — the shape of a check that cannot fail.
- const meshOk = !result.meshResident || result.meshResident.frozen > 0;
+ const meshOk = (!result.meshResident || result.meshResident.frozen > 0)
+ && (!result.meshAsset || result.meshAsset.pointed > 0);
const renderedOk = result.capture?.rendered ?? false;
const ok = result.ok && renderedOk && (result.expect?.ok ?? true) &&
(result.resize?.ok ?? true) && (result.preview?.ok ?? true) && (result.grid?.ok ?? true) &&
@@ -162,6 +163,7 @@ app.whenReady().then(async () => {
const exec = (code) => win.webContents.executeJavaScript(code, true);
let deviceLoss = null;
let meshResident = null;
+ let meshAsset = null;
await exec('window.__estellaHeadless.ready');
const entityCount = await exec(
`window.__estellaHeadless.api.loadScene(${JSON.stringify(SCENE)}, ${JSON.stringify(MANIFEST)})`,
@@ -245,6 +247,18 @@ app.whenReady().then(async () => {
await exec(`window.__estellaHeadless.api.step(${STEPS}, 1 / 60)`);
}
+ // Loads an .esmesh through the asset layer and points the scene's meshes at
+ // it, replacing their inline geometry. The fixture holds the SAME vertices,
+ // so the assertions stand: a file drawing what the scene draws is the claim.
+ if (process.env.ESTELLA_VERIFY_MESH_ASSET) {
+ meshAsset = await exec(`(async () => {
+ const pointed = await window.__estellaHeadless.loadMeshAsset(
+ ${JSON.stringify(process.env.ESTELLA_VERIFY_MESH_ASSET)});
+ await window.__estellaHeadless.api.step(2, 1 / 60);
+ return { pointed };
+ })()`);
+ }
+
// Freezes the scene's inline geometry onto the GPU, keeping every other
// assertion: nothing about the geometry changes, so the frame after must
// equal the frame before. That equality IS the claim.
@@ -469,7 +483,7 @@ app.whenReady().then(async () => {
return { differingPixels: differing, ok: differing > 300 };
`);
}
- finish({ ok: true, entityCount, drawCalls, capture, expect, resize, preview, grid, deviceLoss, meshResident }, server);
+ finish({ ok: true, entityCount, drawCalls, capture, expect, resize, preview, grid, deviceLoss, meshResident, meshAsset }, server);
} catch (e) {
finish({ ok: false, error: String((e && e.stack) || e) }, server);
}
diff --git a/desktop/scripts/make-mesh-fixture.mjs b/desktop/scripts/make-mesh-fixture.mjs
new file mode 100644
index 000000000..f1124199d
--- /dev/null
+++ b/desktop/scripts/make-mesh-fixture.mjs
@@ -0,0 +1,58 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file Writes public/scenes/two-triangles.esmesh — the fixture behind the
+ * `mesh-asset` pixel gate.
+ *
+ * The geometry is the one scenes/mesh2d.esscene inlines, so the gate can assert
+ * the SAME points: a file that draws what the inline payload draws is the whole
+ * claim, and it would not be one if the two were different shapes. Written by
+ * the engine's own encoder, so the fixture cannot encode a format the loader
+ * does not read.
+ *
+ * node scripts/make-mesh-fixture.mjs
+ */
+import { writeFileSync } from 'node:fs';
+import path from 'node:path';
+import { fileURLToPath } from 'node:url';
+import { MeshChannel, MeshChannelType, packChannels, encodeMesh } from 'esengine';
+
+const positions = [-200, -100, -40, -100, -120, 100, 40, -100, 200, -100, 120, 100];
+const colors = [[1, 0, 0, 1], [1, 0, 0, 1], [1, 0, 0, 1], [0, 1, 0, 1], [0, 1, 0, 1], [0, 1, 0, 1]];
+const indices = new Uint32Array([0, 1, 2, 3, 4, 5]);
+
+const { channels, vertexStride } = packChannels([
+ { semantic: MeshChannel.Position, components: 3, type: MeshChannelType.Float32 },
+ { semantic: MeshChannel.TexCoord0, components: 2, type: MeshChannelType.Float32 },
+ { semantic: MeshChannel.Color, components: 4, type: MeshChannelType.UNorm8 },
+]);
+
+const count = positions.length / 2;
+const vertices = new Uint8Array(count * vertexStride);
+const view = new DataView(vertices.buffer);
+const min = [Infinity, Infinity, 0];
+const max = [-Infinity, -Infinity, 0];
+for (let i = 0; i < count; i++) {
+ const base = i * vertexStride;
+ const x = positions[i * 2];
+ const y = positions[i * 2 + 1];
+ view.setFloat32(base + channels[0].offset, x, true);
+ view.setFloat32(base + channels[0].offset + 4, y, true);
+ view.setFloat32(base + channels[0].offset + 8, 0, true);
+ view.setFloat32(base + channels[1].offset, 0, true);
+ view.setFloat32(base + channels[1].offset + 4, 0, true);
+ const c = colors[i];
+ for (let k = 0; k < 4; k++) view.setUint8(base + channels[2].offset + k, Math.round(c[k] * 255));
+ min[0] = Math.min(min[0], x);
+ min[1] = Math.min(min[1], y);
+ max[0] = Math.max(max[0], x);
+ max[1] = Math.max(max[1], y);
+}
+
+const bytes = encodeMesh({
+ channels, vertexStride, vertexCount: count, vertices, indices, aabbMin: min, aabbMax: max,
+});
+const out = path.resolve(path.dirname(fileURLToPath(import.meta.url)),
+ '..', 'public', 'scenes', 'two-triangles.esmesh');
+writeFileSync(out, bytes);
+console.log(`${path.basename(out)}: ${bytes.byteLength} bytes, stride ${vertexStride}, ${channels.length} channels`);
diff --git a/desktop/src/headless.ts b/desktop/src/headless.ts
index ac569069c..636bb0c59 100644
--- a/desktop/src/headless.ts
+++ b/desktop/src/headless.ts
@@ -43,6 +43,8 @@ declare global {
};
/** Freezes the scene's inline mesh geometry onto the GPU; returns how many. */
makeMeshesResident: () => number;
+ /** Loads an .esmesh and points every Mesh2D at it; returns how many. */
+ loadMeshAsset: (path: string) => Promise<number>;
};
}
}
@@ -157,6 +159,21 @@ window.__estellaHeadless = {
if (!m?.mesh2d_makeAllResident || !registry) return 0;
return m.mesh2d_makeAllResident(registry);
},
+ // Through the asset layer, not a side door: the file goes through the same
+ // load() every other asset type does, so what this proves is the format
+ // reaching the screen rather than a decoder wired straight to the engine.
+ loadMeshAsset: async (path: string) => {
+ const assets = EngineHost.getResource(Assets);
+ const m = EngineHost.module as unknown as {
+ mesh2d_setMeshAll?(registry: unknown, handle: number): number;
+ } | null;
+ const registry = EngineHost.mutableWorld()?.getCppRegistry();
+ if (!assets || !m?.mesh2d_setMeshAll || !registry) return 0;
+
+ const mesh = await assets.load<{ handle: number }>('mesh', path);
+ if (!mesh?.handle) return 0;
+ return m.mesh2d_setMeshAll(registry, mesh.handle);
+ },
};
// Referenced so the unused-import check sees it; DeviceStatus is the vocabulary
diff --git a/docs/astro/src/data/apiStability.generated.json b/docs/astro/src/data/apiStability.generated.json
index 6d2c5062a..6c33dd3de 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": 62,
- "experimental": 1515,
+ "experimental": 1524,
"deprecated": 3
},
- "total": 1690,
+ "total": 1699,
"subsystems": [
{
"id": "ecs",
diff --git a/sdk/etc/index.api.md b/sdk/etc/index.api.md
index ba4dc25bf..87a19f2ad 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 · 55 beta · 1400 experimental · 3 deprecated
+Symbols: 113 public · 55 beta · 1409 experimental · 3 deprecated
## ABI_LAYOUT_HASH — const @experimental
```
@@ -4248,6 +4248,40 @@ static new (): Mesh2DPlugin
static prototype: Mesh2DPlugin
```
+## MeshChannel — const @experimental
+```
+{ readonly Position: 0; readonly TexCoord0: 1; readonly Color: 2; readonly Normal: 3; readonly Tangent: 4; }
+```
+
+## MeshChannelDesc — interface @experimental
+```
+components: number
+offset: number
+semantic: number
+type: number
+```
+
+## MeshChannelType — const @experimental
+```
+{ readonly Float32: 0; readonly UNorm8: 1; }
+```
+
+## MeshData — interface @experimental
+```
+aabbMax: [number, number, number]
+aabbMin: [number, number, number]
+channels: MeshChannelDesc[]
+indices: Uint32Array<ArrayBufferLike>
+vertexCount: number
+vertexStride: number
+vertices: Uint8Array<ArrayBufferLike>
+```
+
+## MeshResult — interface @experimental
+```
+handle: number
+```
+
## Meshes2D — const @experimental
```
ResourceDef<Mesh2DAPI>
@@ -9383,6 +9417,11 @@ Plugin
(src: ImageBitmapSource): Promise<DecodedPixels>
```
+## decodeMesh — function @experimental
+```
+(bytes: Uint8Array): MeshData
+```
+
## decodeTilemapChunks — function @experimental
```
(blob: string): DecodedChunk[]
@@ -9518,6 +9557,16 @@ DragPlugin
(app: App): void
```
+## encodeChannelTable — function @experimental
+```
+(channels: MeshChannelDesc[]): Uint8Array
+```
+
+## encodeMesh — function @experimental
+```
+(data: MeshData): Uint8Array
+```
+
## encodeTile — function @experimental
```
(id: number, flags?: TileFlags): number
@@ -10353,6 +10402,11 @@ NavPlugin
(flags: TileFlags): Perm
```
+## packChannels — function @experimental
+```
+(semantics: { semantic: number; components: number; type: number; }[]): { channels: MeshChannelDesc[]; vertexStride: number; }
+```
+
## packCorners — function @experimental
```
(tl: number, tr: number, br: number, bl: number): number
diff --git a/sdk/etc/index.native.api.md b/sdk/etc/index.native.api.md
index 735f23940..da60da4c0 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 · 60 beta · 1419 experimental · 3 deprecated
+Symbols: 113 public · 60 beta · 1428 experimental · 3 deprecated
## ABI_LAYOUT_HASH — const @experimental
```
@@ -4261,6 +4261,40 @@ static new (): Mesh2DPlugin
static prototype: Mesh2DPlugin
```
+## MeshChannel — const @experimental
+```
+{ readonly Position: 0; readonly TexCoord0: 1; readonly Color: 2; readonly Normal: 3; readonly Tangent: 4; }
+```
+
+## MeshChannelDesc — interface @experimental
+```
+components: number
+offset: number
+semantic: number
+type: number
+```
+
+## MeshChannelType — const @experimental
+```
+{ readonly Float32: 0; readonly UNorm8: 1; }
+```
+
+## MeshData — interface @experimental
+```
+aabbMax: [number, number, number]
+aabbMin: [number, number, number]
+channels: MeshChannelDesc[]
+indices: Uint32Array<ArrayBufferLike>
+vertexCount: number
+vertexStride: number
+vertices: Uint8Array<ArrayBufferLike>
+```
+
+## MeshResult — interface @experimental
+```
+handle: number
+```
+
## Meshes2D — const @experimental
```
ResourceDef<Mesh2DAPI>
@@ -9616,6 +9650,11 @@ Plugin
(src: ImageBitmapSource): Promise<DecodedPixels>
```
+## decodeMesh — function @experimental
+```
+(bytes: Uint8Array): MeshData
+```
+
## decodeTilemapChunks — function @experimental
```
(blob: string): DecodedChunk[]
@@ -9751,6 +9790,16 @@ DragPlugin
(app: App): void
```
+## encodeChannelTable — function @experimental
+```
+(channels: MeshChannelDesc[]): Uint8Array
+```
+
+## encodeMesh — function @experimental
+```
+(data: MeshData): Uint8Array
+```
+
## encodeTile — function @experimental
```
(id: number, flags?: TileFlags): number
@@ -10596,6 +10645,11 @@ NavPlugin
(flags: TileFlags): Perm
```
+## packChannels — function @experimental
+```
+(semantics: { semantic: number; components: number; type: number; }[]): { channels: MeshChannelDesc[]; vertexStride: number; }
+```
+
## packCorners — function @experimental
```
(tl: number, tr: number, br: number, bl: number): number
diff --git a/sdk/etc/index.node.api.md b/sdk/etc/index.node.api.md
index 2c61c9455..cb32ff7fd 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 · 57 beta · 1399 experimental · 3 deprecated
+Symbols: 113 public · 57 beta · 1408 experimental · 3 deprecated
## ANCHOR_AXES — const @experimental
```
@@ -4243,6 +4243,40 @@ static new (): Mesh2DPlugin
static prototype: Mesh2DPlugin
```
+## MeshChannel — const @experimental
+```
+{ readonly Position: 0; readonly TexCoord0: 1; readonly Color: 2; readonly Normal: 3; readonly Tangent: 4; }
+```
+
+## MeshChannelDesc — interface @experimental
+```
+components: number
+offset: number
+semantic: number
+type: number
+```
+
+## MeshChannelType — const @experimental
+```
+{ readonly Float32: 0; readonly UNorm8: 1; }
+```
+
+## MeshData — interface @experimental
+```
+aabbMax: [number, number, number]
+aabbMin: [number, number, number]
+channels: MeshChannelDesc[]
+indices: Uint32Array<ArrayBufferLike>
+vertexCount: number
+vertexStride: number
+vertices: Uint8Array<ArrayBufferLike>
+```
+
+## MeshResult — interface @experimental
+```
+handle: number
+```
+
## Meshes2D — const @experimental
```
ResourceDef<Mesh2DAPI>
@@ -9378,6 +9412,11 @@ Plugin
(src: ImageBitmapSource): Promise<DecodedPixels>
```
+## decodeMesh — function @experimental
+```
+(bytes: Uint8Array): MeshData
+```
+
## decodeTilemapChunks — function @experimental
```
(blob: string): DecodedChunk[]
@@ -9513,6 +9552,16 @@ DragPlugin
(app: App): void
```
+## encodeChannelTable — function @experimental
+```
+(channels: MeshChannelDesc[]): Uint8Array
+```
+
+## encodeMesh — function @experimental
+```
+(data: MeshData): Uint8Array
+```
+
## encodeTile — function @experimental
```
(id: number, flags?: TileFlags): number
@@ -10358,6 +10407,11 @@ NodePlatformAdapter
(flags: TileFlags): Perm
```
+## packChannels — function @experimental
+```
+(semantics: { semantic: number; components: number; type: number; }[]): { channels: MeshChannelDesc[]; vertexStride: number; }
+```
+
## packCorners — function @experimental
```
(tl: number, tr: number, br: number, bl: number): number
diff --git a/sdk/etc/minigame.api.md b/sdk/etc/minigame.api.md
index 6ab70bddd..e3d9370a7 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 · 55 beta · 1420 experimental · 3 deprecated
+Symbols: 113 public · 55 beta · 1429 experimental · 3 deprecated
## ANCHOR_AXES — const @experimental
```
@@ -4243,6 +4243,40 @@ static new (): Mesh2DPlugin
static prototype: Mesh2DPlugin
```
+## MeshChannel — const @experimental
+```
+{ readonly Position: 0; readonly TexCoord0: 1; readonly Color: 2; readonly Normal: 3; readonly Tangent: 4; }
+```
+
+## MeshChannelDesc — interface @experimental
+```
+components: number
+offset: number
+semantic: number
+type: number
+```
+
+## MeshChannelType — const @experimental
+```
+{ readonly Float32: 0; readonly UNorm8: 1; }
+```
+
+## MeshData — interface @experimental
+```
+aabbMax: [number, number, number]
+aabbMin: [number, number, number]
+channels: MeshChannelDesc[]
+indices: Uint32Array<ArrayBufferLike>
+vertexCount: number
+vertexStride: number
+vertices: Uint8Array<ArrayBufferLike>
+```
+
+## MeshResult — interface @experimental
+```
+handle: number
+```
+
## Meshes2D — const @experimental
```
ResourceDef<Mesh2DAPI>
@@ -9628,6 +9662,11 @@ Plugin
(src: ImageBitmapSource): Promise<DecodedPixels>
```
+## decodeMesh — function @experimental
+```
+(bytes: Uint8Array): MeshData
+```
+
## decodeTilemapChunks — function @experimental
```
(blob: string): DecodedChunk[]
@@ -9763,6 +9802,16 @@ DragPlugin
(app: App): void
```
+## encodeChannelTable — function @experimental
+```
+(channels: MeshChannelDesc[]): Uint8Array
+```
+
+## encodeMesh — function @experimental
+```
+(data: MeshData): Uint8Array
+```
+
## encodeTile — function @experimental
```
(id: number, flags?: TileFlags): number
@@ -10608,6 +10657,11 @@ NavPlugin
(flags: TileFlags): Perm
```
+## packChannels — function @experimental
+```
+(semantics: { semantic: number; components: number; type: number; }[]): { channels: MeshChannelDesc[]; vertexStride: number; }
+```
+
## packCorners — function @experimental
```
(tl: number, tr: number, br: number, bl: number): number
diff --git a/sdk/etc/wasm.api.md b/sdk/etc/wasm.api.md
index 9b96f574e..3d618796f 100644
--- a/sdk/etc/wasm.api.md
+++ b/sdk/etc/wasm.api.md
@@ -262,7 +262,10 @@ mesh2d_makeAllResident: ((registry: CppRegistry) => number) | undefined
mesh2d_makeResident: ((registry: CppRegistry, entity: number) => number) | undefined
mesh2d_setGeometry: ((registry: CppRegistry, entity: number, posUvPtr: number, vertexCount: number, colorsPtr: number, indicesPtr: number, indexCount: number) => void) | undefined
mesh2d_setMesh: ((registry: CppRegistry, entity: number, meshHandle: number) => void) | undefined
+mesh2d_setMeshAll: ((registry: CppRegistry, meshHandle: number) => number) | undefined
mesh_create: ((posUvPtr: number, vertexCount: number, colorsPtr: number, indicesPtr: number, indexCount: number) => number) | undefined
+mesh_createFromChannels: ((channelsPtr: number, channelCount: number, vertexStride: number, vertexPtr: number, vertexBytes: number, indexPtr: number, indexCount: number, minX: number, minY: number, minZ: number, maxX: number, maxY: number, maxZ: number) => number) | undefined
+mesh_release: ((meshHandle: number) => void) | undefined
notifyDeviceLost: ((reason: number, message: string) => void) | undefined
particle_getAliveCount: ((entity: number) => number) | undefined
particle_play: ((registry: CppRegistry, entity: number) => void) | undefined
diff --git a/sdk/etc/wechat.api.md b/sdk/etc/wechat.api.md
index 88d8681f0..5cbff9e1f 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 · 55 beta · 1410 experimental · 3 deprecated
+Symbols: 113 public · 55 beta · 1419 experimental · 3 deprecated
## ANCHOR_AXES — const @experimental
```
@@ -4250,6 +4250,40 @@ static new (): Mesh2DPlugin
static prototype: Mesh2DPlugin
```
+## MeshChannel — const @experimental
+```
+{ readonly Position: 0; readonly TexCoord0: 1; readonly Color: 2; readonly Normal: 3; readonly Tangent: 4; }
+```
+
+## MeshChannelDesc — interface @experimental
+```
+components: number
+offset: number
+semantic: number
+type: number
+```
+
+## MeshChannelType — const @experimental
+```
+{ readonly Float32: 0; readonly UNorm8: 1; }
+```
+
+## MeshData — interface @experimental
+```
+aabbMax: [number, number, number]
+aabbMin: [number, number, number]
+channels: MeshChannelDesc[]
+indices: Uint32Array<ArrayBufferLike>
+vertexCount: number
+vertexStride: number
+vertices: Uint8Array<ArrayBufferLike>
+```
+
+## MeshResult — interface @experimental
+```
+handle: number
+```
+
## Meshes2D — const @experimental
```
ResourceDef<Mesh2DAPI>
@@ -9405,6 +9439,11 @@ Plugin
(src: ImageBitmapSource): Promise<DecodedPixels>
```
+## decodeMesh — function @experimental
+```
+(bytes: Uint8Array): MeshData
+```
+
## decodeTilemapChunks — function @experimental
```
(blob: string): DecodedChunk[]
@@ -9540,6 +9579,16 @@ DragPlugin
(app: App): void
```
+## encodeChannelTable — function @experimental
+```
+(channels: MeshChannelDesc[]): Uint8Array
+```
+
+## encodeMesh — function @experimental
+```
+(data: MeshData): Uint8Array
+```
+
## encodeTile — function @experimental
```
(id: number, flags?: TileFlags): number
@@ -10380,6 +10429,11 @@ NavPlugin
(flags: TileFlags): Perm
```
+## packChannels — function @experimental
+```
+(semantics: { semantic: number; components: number; type: number; }[]): { channels: MeshChannelDesc[]; vertexStride: number; }
+```
+
## packCorners — function @experimental
```
(tl: number, tr: number, br: number, bl: number): number
diff --git a/sdk/src/asset/Assets.ts b/sdk/src/asset/Assets.ts
index 61efd7d86..daa653d10 100644
--- a/sdk/src/asset/Assets.ts
+++ b/sdk/src/asset/Assets.ts
@@ -21,6 +21,7 @@ import { TextureLoader, textureResidencyKey } from './loaders/TextureLoader';
import { AssetRefLedger } from './AssetRefLedger';
import { SpineAssetLoader } from './loaders/SpineAssetLoader';
import { MaterialAssetLoader } from './loaders/MaterialAssetLoader';
+import { MeshAssetLoader } from './loaders/MeshAssetLoader';
import { FontAssetLoader } from './loaders/FontAssetLoader';
import { AudioAssetLoader } from './loaders/AudioAssetLoader';
import { AnimClipAssetLoader } from './loaders/AnimClipAssetLoader';
@@ -1679,6 +1680,7 @@ export class Assets {
this.materialLoader_ = new MaterialAssetLoader();
this.register(this.materialLoader_);
this.register(new FontAssetLoader());
+ this.register(new MeshAssetLoader(() => this.module_));
// The audio loader needs the AudioAPI outside load() too (unload /
// invalidate have no LoadContext), so it shares Assets' lazy accessor.
this.register(new AudioAssetLoader(() => this.getAudio_()));
diff --git a/sdk/src/asset/loaders/MeshAssetLoader.ts b/sdk/src/asset/loaders/MeshAssetLoader.ts
new file mode 100644
index 000000000..be83bdd34
--- /dev/null
+++ b/sdk/src/asset/loaders/MeshAssetLoader.ts
@@ -0,0 +1,59 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+import type { AssetLoader, LoadContext } from '../AssetLoader';
+import type { ESEngineModule } from '../../wasm';
+import { withScratch } from '../../wasm/wasmScratch';
+import { decodeMesh, encodeChannelTable } from '../meshFormat';
+
+/** A mesh uploaded to the GPU, named by the handle everything else references. */
+export interface MeshResult {
+ handle: number;
+}
+
+/**
+ * Loads `.esmesh` — geometry that goes to the GPU once and is drawn from there.
+ *
+ * The file describes its own channels, and that table crosses to the engine in
+ * the file's own byte layout: this layer owns the format, the engine owns the
+ * vertex layout it becomes, and neither restates the other.
+ */
+export class MeshAssetLoader implements AssetLoader<MeshResult> {
+ readonly type = 'mesh';
+ readonly extensions = ['.esmesh'];
+
+ /** Lazy like the audio loader's: unload/invalidate have no LoadContext. */
+ constructor(private readonly module_: () => ESEngineModule | null) {}
+
+ async load(path: string, ctx: LoadContext): Promise<MeshResult> {
+ const bytes = new Uint8Array(await ctx.loadBinary(ctx.catalog.getBuildPath(path)));
+ const mesh = decodeMesh(bytes);
+ const table = encodeChannelTable(mesh.channels);
+ const m = this.module_();
+ if (!m?.mesh_createFromChannels) {
+ throw new Error('this engine build carries no mesh_createFromChannels');
+ }
+
+ const handle = withScratch(m, (alloc) => {
+ const tablePtr = alloc(table.byteLength);
+ const vertexPtr = alloc(mesh.vertices.byteLength);
+ const indexPtr = alloc(mesh.indices.byteLength);
+ m.HEAPU8.set(table, tablePtr);
+ m.HEAPU8.set(mesh.vertices, vertexPtr);
+ m.HEAPU8.set(new Uint8Array(mesh.indices.buffer, mesh.indices.byteOffset,
+ mesh.indices.byteLength), indexPtr);
+ return m.mesh_createFromChannels!(
+ tablePtr, mesh.channels.length, mesh.vertexStride,
+ vertexPtr, mesh.vertices.byteLength,
+ indexPtr, mesh.indices.length,
+ mesh.aabbMin[0], mesh.aabbMin[1], mesh.aabbMin[2],
+ mesh.aabbMax[0], mesh.aabbMax[1], mesh.aabbMax[2]);
+ });
+
+ if (!handle) throw new Error(`the engine rejected the geometry in ${path}`);
+ return { handle };
+ }
+
+ unload(asset: MeshResult): void {
+ this.module_()?.mesh_release?.(asset.handle);
+ }
+}
diff --git a/sdk/src/asset/meshFormat.ts b/sdk/src/asset/meshFormat.ts
new file mode 100644
index 000000000..6037dec23
--- /dev/null
+++ b/sdk/src/asset/meshFormat.ts
@@ -0,0 +1,182 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file .esmesh — GPU-resident geometry on disk.
+ *
+ * Self-describing: the channel table is written out rather than implied by
+ * a mask, so a file states its own strides and offsets and a reader needs
+ * no table of its own. Adding a channel is then an append to the vocabulary
+ * below, not a format version — and a mesh without normals stays a file
+ * without normals instead of one carrying zeroes.
+ */
+
+/** Magic 'ESMH', little-endian. */
+const MAGIC = 0x484d5345;
+const VERSION = 1;
+const HEADER_BYTES = 44;
+const CHANNEL_BYTES = 8;
+
+/**
+ * What a channel means. The value IS the shader attribute location, so a shader
+ * reading normals at 3 reads them from any mesh that has them. Append only:
+ * these numbers are serialized.
+ */
+export const MeshChannel = {
+ Position: 0,
+ TexCoord0: 1,
+ Color: 2,
+ Normal: 3,
+ Tangent: 4,
+} as const;
+
+/** How a channel's components are stored. Append only — serialized. */
+export const MeshChannelType = {
+ Float32: 0,
+ UNorm8: 1,
+} as const;
+
+export interface MeshChannelDesc {
+ /** One of {@link MeshChannel}; also the attribute location. */
+ semantic: number;
+ /** 1..4. */
+ components: number;
+ /** One of {@link MeshChannelType}. */
+ type: number;
+ /** Byte offset of this channel within one vertex. */
+ offset: number;
+}
+
+export interface MeshData {
+ channels: MeshChannelDesc[];
+ vertexStride: number;
+ vertexCount: number;
+ /** Interleaved vertex bytes, `vertexCount * vertexStride` long. */
+ vertices: Uint8Array;
+ indices: Uint32Array;
+ aabbMin: [number, number, number];
+ aabbMax: [number, number, number];
+}
+
+/** Bytes one component of a channel type occupies. */
+function componentBytes(type: number): number {
+ return type === MeshChannelType.UNorm8 ? 1 : 4;
+}
+
+/**
+ * Byte size of one vertex for these channels, laid out in the order given.
+ *
+ * Rounded up to 4 so every channel starts aligned: WebGL rejects a float
+ * attribute at an unaligned offset, and a colour packed between two of them is
+ * exactly how that happens.
+ */
+export function packChannels(semantics: { semantic: number; components: number; type: number }[]): {
+ channels: MeshChannelDesc[];
+ vertexStride: number;
+} {
+ const channels: MeshChannelDesc[] = [];
+ let offset = 0;
+ for (const s of semantics) {
+ channels.push({ ...s, offset });
+ offset += s.components * componentBytes(s.type);
+ offset = (offset + 3) & ~3;
+ }
+ return { channels, vertexStride: offset };
+}
+
+export function encodeMesh(data: MeshData): Uint8Array {
+ const size = HEADER_BYTES + data.channels.length * CHANNEL_BYTES
+ + data.vertexCount * data.vertexStride + data.indices.length * 4;
+ const out = new Uint8Array(size);
+ const view = new DataView(out.buffer);
+
+ view.setUint32(0, MAGIC, true);
+ view.setUint16(4, VERSION, true);
+ view.setUint16(6, data.channels.length, true);
+ view.setUint32(8, data.vertexStride, true);
+ view.setUint32(12, data.vertexCount, true);
+ view.setUint32(16, data.indices.length, true);
+ for (let i = 0; i < 3; i++) {
+ view.setFloat32(20 + i * 4, data.aabbMin[i], true);
+ view.setFloat32(32 + i * 4, data.aabbMax[i], true);
+ }
+
+ let at = HEADER_BYTES;
+ for (const c of data.channels) {
+ view.setUint8(at, c.semantic);
+ view.setUint8(at + 1, c.components);
+ view.setUint8(at + 2, c.type);
+ view.setUint8(at + 3, c.type === MeshChannelType.UNorm8 ? 1 : 0);
+ view.setUint32(at + 4, c.offset, true);
+ at += CHANNEL_BYTES;
+ }
+
+ out.set(data.vertices.subarray(0, data.vertexCount * data.vertexStride), at);
+ at += data.vertexCount * data.vertexStride;
+ out.set(new Uint8Array(data.indices.buffer, data.indices.byteOffset, data.indices.length * 4), at);
+ return out;
+}
+
+export function decodeMesh(bytes: Uint8Array): MeshData {
+ const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
+ if (bytes.byteLength < HEADER_BYTES || view.getUint32(0, true) !== MAGIC) {
+ throw new Error('not an .esmesh file');
+ }
+ const version = view.getUint16(4, true);
+ // Refused rather than read leniently: a newer file's channel table may mean
+ // something this build does not know, and a mesh drawn from a guess is a
+ // wrong frame instead of an error.
+ if (version > VERSION) {
+ throw new Error(`.esmesh version ${version} is newer than this engine understands (${VERSION})`);
+ }
+
+ const channelCount = view.getUint16(6, true);
+ const vertexStride = view.getUint32(8, true);
+ const vertexCount = view.getUint32(12, true);
+ const indexCount = view.getUint32(16, true);
+ const aabbMin: [number, number, number] = [
+ view.getFloat32(20, true), view.getFloat32(24, true), view.getFloat32(28, true)];
+ const aabbMax: [number, number, number] = [
+ view.getFloat32(32, true), view.getFloat32(36, true), view.getFloat32(40, true)];
+
+ const channels: MeshChannelDesc[] = [];
+ let at = HEADER_BYTES;
+ for (let i = 0; i < channelCount; i++) {
+ channels.push({
+ semantic: view.getUint8(at),
+ components: view.getUint8(at + 1),
+ type: view.getUint8(at + 2),
+ offset: view.getUint32(at + 4, true),
+ });
+ at += CHANNEL_BYTES;
+ }
+
+ const vertexBytes = vertexCount * vertexStride;
+ const expected = at + vertexBytes + indexCount * 4;
+ if (bytes.byteLength < expected) {
+ throw new Error(`.esmesh is truncated: ${bytes.byteLength} bytes, header describes ${expected}`);
+ }
+ const vertices = bytes.subarray(at, at + vertexBytes);
+ // Copied, not viewed: the index data is not guaranteed 4-byte aligned within
+ // the file, and a Uint32Array view on an odd offset throws.
+ const indices = new Uint32Array(indexCount);
+ const indexBase = at + vertexBytes;
+ for (let i = 0; i < indexCount; i++) indices[i] = view.getUint32(indexBase + i * 4, true);
+
+ return { channels, vertexStride, vertexCount, vertices, indices, aabbMin, aabbMax };
+}
+
+/** The channel table as the engine takes it: one 8-byte record per channel. */
+export function encodeChannelTable(channels: MeshChannelDesc[]): Uint8Array {
+ const out = new Uint8Array(channels.length * CHANNEL_BYTES);
+ const view = new DataView(out.buffer);
+ let at = 0;
+ for (const c of channels) {
+ view.setUint8(at, c.semantic);
+ view.setUint8(at + 1, c.components);
+ view.setUint8(at + 2, c.type);
+ view.setUint8(at + 3, c.type === MeshChannelType.UNorm8 ? 1 : 0);
+ view.setUint32(at + 4, c.offset, true);
+ at += CHANNEL_BYTES;
+ }
+ return out;
+}
diff --git a/sdk/src/core-content.ts b/sdk/src/core-content.ts
index 1fc06d47e..262a3a2b2 100644
--- a/sdk/src/core-content.ts
+++ b/sdk/src/core-content.ts
@@ -106,6 +106,18 @@ export { setTextureBudget, getResourceStats, trimTextureCache, type ResourceStat
/** A texture whose content is a canvas SOMETHING ELSE draws on, re-taken on
* demand — the seam a service outside the engine needs to put another
* runtime's pixels (an open data context, a host overlay) on a quad. */
+/**
+ * The `.esmesh` read/write door. Public because writing one is what an importer
+ * does — a glTF cook, a plugin's own format — and reading one has to agree with
+ * it exactly. `@beta`.
+ *
+ * @beta
+ */
+export {
+ MeshChannel, MeshChannelType, packChannels, encodeMesh, decodeMesh, encodeChannelTable,
+ type MeshChannelDesc, type MeshData,
+} from './asset/meshFormat';
+export type { MeshResult } from './asset/loaders/MeshAssetLoader';
export { createCanvasTexture, type CanvasTexture } from './asset/canvasTexture';
export type { GlImageSource } from './asset/glTextureUpload';
diff --git a/sdk/src/wasm.ts b/sdk/src/wasm.ts
index 271a64e3a..d7bbdce54 100644
--- a/sdk/src/wasm.ts
+++ b/sdk/src/wasm.ts
@@ -232,6 +232,19 @@ export interface ESEngineModule {
*/
mesh_create?(posUvPtr: number, vertexCount: number, colorsPtr: number,
indicesPtr: number, indexCount: number): number;
+ /**
+ * Upload geometry described by an .esmesh channel table — 8 bytes per channel
+ * (semantic, components, type, normalized, offset) in the file's own layout,
+ * so the format stays the asset layer's and the vertex layout stays the
+ * engine's. A channel's semantic is its shader attribute location.
+ */
+ mesh_createFromChannels?(channelsPtr: number, channelCount: number, vertexStride: number,
+ vertexPtr: number, vertexBytes: number,
+ indexPtr: number, indexCount: number,
+ minX: number, minY: number, minZ: number,
+ maxX: number, maxY: number, maxZ: number): number;
+ /** Release a mesh and the buffers it owns. */
+ mesh_release?(meshHandle: number): void;
/** Point a Mesh2D at a resident mesh; 0 returns it to its inline payload. */
mesh2d_setMesh?(registry: CppRegistry, entity: number, meshHandle: number): void;
/**
@@ -242,6 +255,11 @@ export interface ESEngineModule {
mesh2d_makeResident?(registry: CppRegistry, entity: number): number;
/** The same for every Mesh2D in the world; returns how many were frozen. */
mesh2d_makeAllResident?(registry: CppRegistry): number;
+ /**
+ * Point every Mesh2D in the world at one resident mesh, clearing their
+ * inline payloads. Returns how many were pointed.
+ */
+ mesh2d_setMeshAll?(registry: CppRegistry, meshHandle: number): number;
recoverDevice?(): boolean;
/**
* Take up the replacement device left on `Module.pendingWebGPUDevice`. A
diff --git a/src/esengine/bindings/RendererBindings.cpp b/src/esengine/bindings/RendererBindings.cpp
index cc08fec83..e7f74d0a7 100644
--- a/src/esengine/bindings/RendererBindings.cpp
+++ b/src/esengine/bindings/RendererBindings.cpp
@@ -249,10 +249,69 @@ u32 mesh_create(uintptr_t posUvPtr, u32 vertexCount, uintptr_t colorsPtr,
return handle.id();
}
-// Freezes a Mesh2D's inline geometry onto the GPU: the same vertices, uploaded
-// once and drawn with a per-object transform instead of being rewritten into
-// every frame. The inline payload is cleared, so the two can never disagree.
+// Geometry from an .esmesh. The channel table arrives in the file's own layout
+// (8 bytes each), so the asset layer owns the FORMAT and the engine owns the
+// vertex layout it becomes. A channel's semantic is its attribute location.
+u32 mesh_createFromChannels(uintptr_t channelsPtr, u32 channelCount, u32 vertexStride,
+ uintptr_t vertexPtr, u32 vertexBytes,
+ uintptr_t indexPtr, u32 indexCount,
+ f32 minX, f32 minY, f32 minZ,
+ f32 maxX, f32 maxY, f32 maxZ) {
+ auto* rm = ctx().tryGet<resource::ResourceManager>();
+ if (!rm || channelCount == 0 || vertexStride == 0 || vertexBytes == 0 || indexCount == 0) return 0;
+ if (indexCount % 3 != 0) {
+ ES_LOG_WARN("mesh_createFromChannels: indexCount {} is not a triangle list", indexCount);
+ return 0;
+ }
+
+ const u8* table = boundarySpan<u8>(channelsPtr, static_cast<u64>(channelCount) * 8,
+ "mesh_createFromChannels.channels");
+ const u8* verts = boundarySpan<u8>(vertexPtr, vertexBytes, "mesh_createFromChannels.vertices");
+ const u32* indices = boundarySpan<u32>(indexPtr, indexCount, "mesh_createFromChannels.indices");
+ if (!table || !verts || !indices) return 0;
+
+ const u32 vertexCount = vertexBytes / vertexStride;
+ for (u32 i = 0; i < indexCount; ++i) {
+ if (indices[i] >= vertexCount) {
+ ES_LOG_WARN("mesh_createFromChannels: index {} out of range ({} vertices)",
+ indices[i], vertexCount);
+ return 0;
+ }
+ }
+
+ GfxVertexAttribute channels[MAX_VERTEX_ATTRIBUTES];
+ if (channelCount > MAX_VERTEX_ATTRIBUTES) return 0;
+ for (u32 i = 0; i < channelCount; ++i) {
+ const u8* c = table + i * 8;
+ channels[i] = GfxVertexAttribute{
+ .location = c[0],
+ .components = c[1],
+ .type = c[2] == 1 ? GfxDataType::UnsignedByte : GfxDataType::Float,
+ .normalized = c[3] != 0,
+ .offset = static_cast<u32>(c[4]) | (static_cast<u32>(c[5]) << 8)
+ | (static_cast<u32>(c[6]) << 16) | (static_cast<u32>(c[7]) << 24),
+ .bufferSlot = 0,
+ };
+ }
+
+ auto handle = rm->createMesh(ConstSpan<u8>(verts, vertexBytes),
+ ConstSpan<u32>(indices, indexCount),
+ ConstSpan<GfxVertexAttribute>(channels, channelCount), vertexStride,
+ glm::vec3(minX, minY, minZ), glm::vec3(maxX, maxY, maxZ));
+ return handle.id();
+}
+
+/** @brief Releases a mesh and the buffers it owns. */
+void mesh_release(u32 meshHandle) {
+ if (auto* rm = ctx().tryGet<resource::ResourceManager>()) {
+ rm->releaseMesh(resource::MeshHandle(meshHandle));
+ }
+}
+
namespace {
+// Freezes a Mesh2D's inline geometry onto the GPU: the same vertices, uploaded
+// once and drawn with a per-object transform. The inline payload is cleared, so
+// the two can never disagree.
u32 freezeMeshGeometry(ecs::Mesh2D* mesh) {
auto* rm = ctx().tryGet<resource::ResourceManager>();
if (!mesh || !rm || mesh->vertices.empty() || mesh->indices.empty()) return 0;
@@ -287,6 +346,21 @@ u32 mesh2d_makeResident(ecs::Registry& registry, u32 entity) {
return freezeMeshGeometry(registry.tryGet<ecs::Mesh2D>(Entity::fromRaw(entity)));
}
+u32 mesh2d_setMeshAll(ecs::Registry& registry, u32 meshHandle) {
+ u32 pointed = 0;
+ for (auto entity : registry.view<ecs::Mesh2D>()) {
+ auto* mesh = registry.tryGet<ecs::Mesh2D>(entity);
+ if (!mesh) continue;
+ mesh->mesh = resource::MeshHandle(meshHandle);
+ // Cleared: an entity carrying both draws the resident geometry, so a
+ // leftover payload would hide a mesh that never arrived.
+ mesh->vertices.clear();
+ mesh->indices.clear();
+ ++pointed;
+ }
+ return pointed;
+}
+
u32 mesh2d_makeAllResident(ecs::Registry& registry) {
u32 frozen = 0;
for (auto entity : registry.view<ecs::Mesh2D>()) {
diff --git a/src/esengine/bindings/RendererBindings.hpp b/src/esengine/bindings/RendererBindings.hpp
index 78bc50db1..d05c73925 100644
--- a/src/esengine/bindings/RendererBindings.hpp
+++ b/src/esengine/bindings/RendererBindings.hpp
@@ -69,6 +69,14 @@ void mesh2d_setGeometry(
uintptr_t colorsPtr,
uintptr_t indicesPtr, u32 indexCount
);
+/** @brief Geometry from an .esmesh channel table; returns its handle, 0 on failure. */
+u32 mesh_createFromChannels(uintptr_t channelsPtr, u32 channelCount, u32 vertexStride,
+ uintptr_t vertexPtr, u32 vertexBytes,
+ uintptr_t indexPtr, u32 indexCount,
+ f32 minX, f32 minY, f32 minZ,
+ f32 maxX, f32 maxY, f32 maxZ);
+/** @brief Releases a mesh and the buffers it owns. */
+void mesh_release(u32 meshHandle);
/** @brief Uploads geometry that stays on the GPU; returns its handle, 0 on failure. */
u32 mesh_create(uintptr_t posUvPtr, u32 vertexCount, uintptr_t colorsPtr,
uintptr_t indicesPtr, u32 indexCount);
@@ -78,6 +86,8 @@ void mesh2d_setMesh(ecs::Registry& registry, u32 entity, u32 meshHandle);
u32 mesh2d_makeResident(ecs::Registry& registry, u32 entity);
/** @brief Freezes every Mesh2D in the world; returns how many were frozen. */
u32 mesh2d_makeAllResident(ecs::Registry& registry);
+/** @brief Points every Mesh2D at one resident mesh; returns how many. */
+u32 mesh2d_setMeshAll(ecs::Registry& registry, u32 meshHandle);
#ifdef ES_ENABLE_PARTICLES
void renderer_submitParticles(ecs::Registry& registry);
#endif
diff --git a/src/esengine/bindings/WebSDKEntry.cpp b/src/esengine/bindings/WebSDKEntry.cpp
index f03f9876b..6e2358d1c 100644
--- a/src/esengine/bindings/WebSDKEntry.cpp
+++ b/src/esengine/bindings/WebSDKEntry.cpp
@@ -524,9 +524,12 @@ EMSCRIPTEN_BINDINGS(esengine_renderer) {
emscripten::function("renderer_submitTextBatch", &esengine::renderer_submitTextBatch);
emscripten::function("mesh2d_setGeometry", &esengine::mesh2d_setGeometry);
emscripten::function("mesh_create", &esengine::mesh_create);
+ emscripten::function("mesh_createFromChannels", &esengine::mesh_createFromChannels);
+ emscripten::function("mesh_release", &esengine::mesh_release);
emscripten::function("mesh2d_setMesh", &esengine::mesh2d_setMesh);
emscripten::function("mesh2d_makeResident", &esengine::mesh2d_makeResident);
emscripten::function("mesh2d_makeAllResident", &esengine::mesh2d_makeAllResident);
+ emscripten::function("mesh2d_setMeshAll", &esengine::mesh2d_setMeshAll);
emscripten::function("material_compileEsshader", &esengine::material_compileEsshader);
emscripten::function("esshader_cookInfo", &esengine::esshader_cookInfo);
diff --git a/src/esengine/data/shaders/mesh.esshader b/src/esengine/data/shaders/mesh.esshader
index 28601d52b..8b4fab82c 100644
--- a/src/esengine/data/shaders/mesh.esshader
+++ b/src/esengine/data/shaders/mesh.esshader
@@ -11,11 +11,13 @@ layout(location = 0) in vec3 a_position;
layout(location = 1) in vec2 a_texCoord;
layout(location = 2) in vec4 a_color;
-layout(location = 3) in vec4 a_model0;
-layout(location = 4) in vec4 a_model1;
-layout(location = 5) in vec4 a_model2;
-layout(location = 6) in vec4 a_model3;
-layout(location = 7) in vec4 a_instTint;
+// 8.. and not 3..: a channel's semantic IS its location, so adding normals to a
+// mesh must not move the per-object record (see MESH_INSTANCE_FIRST_LOCATION).
+layout(location = 8) in vec4 a_model0;
+layout(location = 9) in vec4 a_model1;
+layout(location = 10) in vec4 a_model2;
+layout(location = 11) in vec4 a_model3;
+layout(location = 12) in vec4 a_instTint;
layout(std140) uniform FrameConstants {
mat4 u_projection;
@@ -56,11 +58,11 @@ struct VSIn {
@location(0) a_position : vec3f,
@location(1) a_texCoord : vec2f,
@location(2) a_color : vec4f,
- @location(3) a_model0 : vec4f,
- @location(4) a_model1 : vec4f,
- @location(5) a_model2 : vec4f,
- @location(6) a_model3 : vec4f,
- @location(7) a_instTint : vec4f,
+ @location(8) a_model0 : vec4f,
+ @location(9) a_model1 : vec4f,
+ @location(10) a_model2 : vec4f,
+ @location(11) a_model3 : vec4f,
+ @location(12) a_instTint : vec4f,
};
struct VSOut {
@builtin(position) pos : vec4f,
diff --git a/src/esengine/renderer/rhi/GfxEnums.hpp b/src/esengine/renderer/rhi/GfxEnums.hpp
index 2eb9e9aea..b732158d2 100644
--- a/src/esengine/renderer/rhi/GfxEnums.hpp
+++ b/src/esengine/renderer/rhi/GfxEnums.hpp
@@ -93,6 +93,24 @@ static constexpr u32 LAYOUT_COUNT = 4;
static constexpr u32 MESH_INSTANCE_STRIDE = 68;
/// The attributes that record occupies (4 matrix rows + the tint).
static constexpr u32 MESH_INSTANCE_ATTRIBUTES = 5;
+/// Where those attributes start. FIXED, not "after the mesh's channels": a mesh
+/// that gains normals would otherwise move them, and every mesh shader with it.
+static constexpr u32 MESH_INSTANCE_FIRST_LOCATION = 8;
+
+/**
+ * @brief What a mesh vertex channel MEANS, and the attribute location it binds to.
+ * @details One vocabulary for the file format, the layout and the shaders: a
+ * channel's semantic IS its location, so a shader declaring a_normal at 3
+ * reads normals from any mesh that has them and never sees the ones that
+ * do not. Values are serialized in .esmesh — append only.
+ */
+enum class MeshChannel : u8 {
+ Position = 0,
+ TexCoord0 = 1,
+ Color = 2,
+ Normal = 3,
+ Tangent = 4,
+};
// =============================================================================
// Data Type (vertex attributes, index type, pixel data type)
diff --git a/src/esengine/renderer/rhi/ShaderEmbeds.generated.hpp b/src/esengine/renderer/rhi/ShaderEmbeds.generated.hpp
index fab670fae..d17456ba6 100644
--- a/src/esengine/renderer/rhi/ShaderEmbeds.generated.hpp
+++ b/src/esengine/renderer/rhi/ShaderEmbeds.generated.hpp
@@ -284,11 +284,13 @@ layout(location = 0) in vec3 a_position;
layout(location = 1) in vec2 a_texCoord;
layout(location = 2) in vec4 a_color;
-layout(location = 3) in vec4 a_model0;
-layout(location = 4) in vec4 a_model1;
-layout(location = 5) in vec4 a_model2;
-layout(location = 6) in vec4 a_model3;
-layout(location = 7) in vec4 a_instTint;
+// 8.. and not 3..: a channel's semantic IS its location, so adding normals to a
+// mesh must not move the per-object record (see MESH_INSTANCE_FIRST_LOCATION).
+layout(location = 8) in vec4 a_model0;
+layout(location = 9) in vec4 a_model1;
+layout(location = 10) in vec4 a_model2;
+layout(location = 11) in vec4 a_model3;
+layout(location = 12) in vec4 a_instTint;
layout(std140) uniform FrameConstants {
mat4 u_projection;
@@ -329,11 +331,11 @@ struct VSIn {
@location(0) a_position : vec3f,
@location(1) a_texCoord : vec2f,
@location(2) a_color : vec4f,
- @location(3) a_model0 : vec4f,
- @location(4) a_model1 : vec4f,
- @location(5) a_model2 : vec4f,
- @location(6) a_model3 : vec4f,
- @location(7) a_instTint : vec4f,
+ @location(8) a_model0 : vec4f,
+ @location(9) a_model1 : vec4f,
+ @location(10) a_model2 : vec4f,
+ @location(11) a_model3 : vec4f,
+ @location(12) a_instTint : vec4f,
};
struct VSOut {
@builtin(position) pos : vec4f,
diff --git a/src/esengine/resource/ResourceManager.cpp b/src/esengine/resource/ResourceManager.cpp
index 47a57d5a9..694ff7e3b 100644
--- a/src/esengine/resource/ResourceManager.cpp
+++ b/src/esengine/resource/ResourceManager.cpp
@@ -496,12 +496,11 @@ MeshHandle ResourceManager::createMesh(ConstSpan<u8> vertexBytes, ConstSpan<u32>
layout.strides[1] = MESH_INSTANCE_STRIDE;
layout.instanceStep[1] = true;
u32 next = static_cast<u32>(channels.size());
- const u32 firstInstanceLocation = next;
for (u32 row = 0; row < 4; ++row) {
- layout.attributes[next++] = {firstInstanceLocation + row, 4, GfxDataType::Float,
+ layout.attributes[next++] = {MESH_INSTANCE_FIRST_LOCATION + row, 4, GfxDataType::Float,
false, row * 16u, 1};
}
- layout.attributes[next++] = {firstInstanceLocation + 4, 4, GfxDataType::UnsignedByte,
+ layout.attributes[next++] = {MESH_INSTANCE_FIRST_LOCATION + 4, 4, GfxDataType::UnsignedByte,
true, 64, 1};
layout.attributeCount = next;
diff --git a/tools/renderScenes.mjs b/tools/renderScenes.mjs
index e10196ce9..aac86852f 100644
--- a/tools/renderScenes.mjs
+++ b/tools/renderScenes.mjs
@@ -115,6 +115,10 @@ export const SCENES = [
// mesh2d's scene and assertions, with its geometry frozen onto the GPU mid-run.
// Equal pixels IS the claim, so it borrows the assertions rather than restating
// them; a run that froze nothing fails on its own count.
+ // The same again, geometry arriving from a FILE: an .esmesh loaded through the
+ // asset layer replaces the inline payload. Its fixture is written by the
+ // engine's own encoder from this scene's vertices, so the assertions hold.
+ { id: "mesh-asset", tier: "pr", webgpu: true, env: { ESTELLA_VERIFY_MESH_ASSET: "/scenes/two-triangles.esmesh", ESTELLA_VERIFY_SCENE: "/scenes/mesh2d.esscene", ESTELLA_VERIFY_MANIFEST: "/scenes/mesh2d.textures.json", ESTELLA_VERIFY_W: "256", ESTELLA_VERIFY_H: "256", ESTELLA_VERIFY_STEPS: "4", ESTELLA_VERIFY_EXPECT: "[{\"x\":0.30,\"y\":0.556,\"rgb\":[255,0,0],\"tol\":40},{\"x\":0.70,\"y\":0.556,\"rgb\":[0,255,0],\"tol\":40},{\"x\":0.30,\"y\":0.40,\"rgb\":[255,0,0],\"tol\":40}]" } },
{ id: "mesh-resident", tier: "pr", webgpu: true, env: { ESTELLA_VERIFY_MESH_RESIDENT: "1", ESTELLA_VERIFY_SCENE: "/scenes/mesh2d.esscene", ESTELLA_VERIFY_MANIFEST: "/scenes/mesh2d.textures.json", ESTELLA_VERIFY_W: "256", ESTELLA_VERIFY_H: "256", ESTELLA_VERIFY_STEPS: "4", ESTELLA_VERIFY_EXPECT: "[{\"x\":0.30,\"y\":0.556,\"rgb\":[255,0,0],\"tol\":40},{\"x\":0.70,\"y\":0.556,\"rgb\":[0,255,0],\"tol\":40},{\"x\":0.30,\"y\":0.40,\"rgb\":[255,0,0],\"tol\":40}]" } },
// Takes the GPU away for real and captures AFTER the cycle: the four points
// sample the atlas, so they fail unless the content came back. A vertex-colour