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
feat(render): a normal map, with no tangent channel to import
esengined26949dd8162
diff --git a/desktop/electron/importModel.ts b/desktop/electron/importModel.tsindex 4ac7bf2ea..595f61d6c 100644--- a/desktop/electron/importModel.ts+++ b/desktop/electron/importModel.ts@@ -72,8 +72,9 @@ export async function importModel(root: string, destDir: string, absSource: stri// import of a different model cannot land on it.const externalRefs = new Map<string, string>();const external = (uri: string): string => externalRefs.get(uri) ?? uri;- for (const mesh of meshes) {- const image = mesh.material?.baseColorTexture;+ const sourceImages = meshes.flatMap((mesh) =>+ [mesh.material?.baseColorTexture, mesh.material?.normalTexture]);+ for (const image of sourceImages) {if (!image?.external || externalRefs.has(image.file)) continue;const abs = path.join(sourceDir, decodeURIComponent(image.file));if (!existsSync(abs)) continue;diff --git a/desktop/public/scenes/mesh-normalmap.esscene b/desktop/public/scenes/mesh-normalmap.esscenenew file mode 100644index 000000000..023444911--- /dev/null+++ b/desktop/public/scenes/mesh-normalmap.esscene@@ -0,0 +1,71 @@+{+ "version": 1,+ "name": "MeshNormalMap",+ "entities": [+ {+ "id": 0,+ "name": "Camera",+ "parent": null,+ "children": [],+ "visible": true,+ "components": [+ {+ "type": "Transform",+ "data": {+ "position": {+ "x": 0,+ "y": 0,+ "z": 10+ }+ }+ },+ {+ "type": "Camera",+ "data": {+ "projectionType": 1,+ "orthoSize": 300,+ "isActive": true,+ "priority": 0+ }+ }+ ]+ },+ {+ "id": 1,+ "name": "Sun",+ "parent": null,+ "children": [],+ "visible": true,+ "components": [+ {+ "type": "Transform",+ "data": {+ "position": {+ "x": 0,+ "y": 0,+ "z": 0+ }+ }+ },+ {+ "type": "Light2D",+ "data": {+ "type": 1,+ "color": {+ "r": 1,+ "g": 1,+ "b": 1,+ "a": 1+ },+ "intensity": 1,+ "direction": {+ "x": 1,+ "y": 0+ },+ "enabled": true+ }+ }+ ]+ }+ ]+}diff --git a/desktop/public/scenes/mesh-normalmap.textures.json b/desktop/public/scenes/mesh-normalmap.textures.jsonnew file mode 100644index 000000000..0967ef424--- /dev/null+++ b/desktop/public/scenes/mesh-normalmap.textures.json@@ -0,0 +1 @@+{}diff --git a/desktop/public/scenes/normalmap-quad.esmesh b/desktop/public/scenes/normalmap-quad.esmeshnew file mode 100644index 000000000..722d7dd13Binary files /dev/null and b/desktop/public/scenes/normalmap-quad.esmesh differdiff --git a/desktop/public/scenes/normalmap-quad.esprefab b/desktop/public/scenes/normalmap-quad.esprefabnew file mode 100644index 000000000..85aa57edd--- /dev/null+++ b/desktop/public/scenes/normalmap-quad.esprefab@@ -0,0 +1,34 @@+{+ "version": "2",+ "name": "normalmap-quad",+ "rootEntityId": "n0",+ "entities": [+ {+ "prefabEntityId": "n0",+ "name": "Quad",+ "parent": null,+ "children": [],+ "visible": true,+ "components": [+ {+ "type": "Transform",+ "data": {}+ },+ {+ "type": "Mesh2D",+ "data": {+ "mesh": "scenes/normalmap-quad.esmesh",+ "normalMap": "scenes/normalmap-quad_0.png",+ "color": {+ "r": 1,+ "g": 1,+ "b": 1,+ "a": 1+ },+ "enabled": true+ }+ }+ ]+ }+ ]+}diff --git a/desktop/public/scenes/normalmap-quad.gltf b/desktop/public/scenes/normalmap-quad.gltfnew file mode 100644index 000000000..60ff5f6b5--- /dev/null+++ b/desktop/public/scenes/normalmap-quad.gltf@@ -0,0 +1,137 @@+{+ "asset": {+ "version": "2.0",+ "generator": "estella test fixture"+ },+ "buffers": [+ {+ "byteLength": 140,+ "uri": "data:application/octet-stream;base64,AAAWwwAAyEIAAAAAAAAWQwAAyEIAAAAAAAAWwwAAyMIAAAAAAAAWQwAAyMIAAAAAAAAAAAAAAAAAAIA/AAAAAAAAAAAAAIA/AAAAAAAAAAAAAIA/AAAAAAAAAAAAAIA/AAAAAAAAAAAAAIA/AAAAAAAAAAAAAIA/AACAPwAAgD8AAAIAAQABAAIAAwA="+ }+ ],+ "bufferViews": [+ {+ "buffer": 0,+ "byteOffset": 0,+ "byteLength": 48+ },+ {+ "buffer": 0,+ "byteOffset": 48,+ "byteLength": 48+ },+ {+ "buffer": 0,+ "byteOffset": 96,+ "byteLength": 32+ },+ {+ "buffer": 0,+ "byteOffset": 128,+ "byteLength": 12+ }+ ],+ "accessors": [+ {+ "bufferView": 0,+ "componentType": 5126,+ "count": 4,+ "type": "VEC3",+ "min": [+ -150,+ -100,+ 0+ ],+ "max": [+ 150,+ 100,+ 0+ ]+ },+ {+ "bufferView": 1,+ "componentType": 5126,+ "count": 4,+ "type": "VEC3"+ },+ {+ "bufferView": 2,+ "componentType": 5126,+ "count": 4,+ "type": "VEC2"+ },+ {+ "bufferView": 3,+ "componentType": 5123,+ "count": 6,+ "type": "SCALAR"+ }+ ],+ "images": [+ {+ "mimeType": "image/png",+ "uri": "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAIAAAABCAYAAAD0In+KAAAAEUlEQVR4AWNkaGj4/5+BgQEAD4kDAMGJ+i0AAAAASUVORK5CYII="+ }+ ],+ "samplers": [+ {+ "magFilter": 9729,+ "minFilter": 9729+ }+ ],+ "textures": [+ {+ "sampler": 0,+ "source": 0+ }+ ],+ "materials": [+ {+ "name": "Bumped",+ "pbrMetallicRoughness": {+ "baseColorFactor": [+ 1,+ 1,+ 1,+ 1+ ],+ "metallicFactor": 0,+ "roughnessFactor": 1+ },+ "normalTexture": {+ "index": 0+ }+ }+ ],+ "meshes": [+ {+ "name": "BumpedQuad",+ "primitives": [+ {+ "attributes": {+ "POSITION": 0,+ "NORMAL": 1,+ "TEXCOORD_0": 2+ },+ "indices": 3,+ "material": 0,+ "mode": 4+ }+ ]+ }+ ],+ "nodes": [+ {+ "name": "Quad",+ "mesh": 0+ }+ ],+ "scenes": [+ {+ "nodes": [+ 0+ ]+ }+ ],+ "scene": 0+}diff --git a/desktop/public/scenes/normalmap-quad_0.png b/desktop/public/scenes/normalmap-quad_0.pngnew file mode 100644index 000000000..b9ff46f67Binary files /dev/null and b/desktop/public/scenes/normalmap-quad_0.png differdiff --git a/desktop/scripts/make-mesh-fixture.mjs b/desktop/scripts/make-mesh-fixture.mjsindex bd954a09d..62f1ea1c3 100644--- a/desktop/scripts/make-mesh-fixture.mjs+++ b/desktop/scripts/make-mesh-fixture.mjs@@ -22,12 +22,13 @@ const cli = path.join(HERE, '..', '..', 'pipeline', 'bin', 'estella.mjs');// two-triangles: the mesh2d geometry, so a file drawing what the scene draws is// the claim. lit-triangles: the same shape with per-face NORMALS and one white// colour. textured-quad: an inline image and a baseColor factor. node-tree: a-// parent and two placed children, one of them scaled.+// parent and two placed children, one of them scaled. normalmap-quad: a normal+// map over flat normals, which only a tangent frame can tell apart.//// public/ stands in for the project root, so the prefab's refs read `scenes/…`// — the spelling a component carries, resolved from the served root.for (const name of ['two-triangles.gltf', 'lit-triangles.gltf', 'white-triangles.gltf',- 'textured-quad.gltf', 'node-tree.gltf']) {+ 'textured-quad.gltf', 'node-tree.gltf', 'normalmap-quad.gltf']) {const run = spawnSync(process.execPath,[cli, 'import-gltf', path.join(scenes, name), '--project', path.join(HERE, '..', 'public')], {stdio: 'inherit',diff --git a/desktop/tests/gltf-import.test.ts b/desktop/tests/gltf-import.test.tsindex 2f79249f9..edb383cae 100644--- a/desktop/tests/gltf-import.test.ts+++ b/desktop/tests/gltf-import.test.ts@@ -153,20 +153,34 @@ describe('glTF material import', () => {doc.materials = [{name: 'Metal',pbrMetallicRoughness: { metallicFactor: 1, roughnessFactor: 0.3 },- normalTexture: { index: 0 }, emissiveFactor: [1, 0, 0],+ normalTexture: { index: 0, scale: 0.4 }, emissiveFactor: [1, 0, 0],alphaMode: 'MASK', alphaCutoff: 0.4, doubleSided: false,extensions: { KHR_materials_clearcoat: {} },}];const { warnings } = importGltfMeshes(gltf(doc), 'model');const line = warnings.join('\n');expect(line).toContain('metallic-roughness');- expect(line).toContain('normal map');+ expect(line).toContain('normal-map scale 0.4');expect(line).toContain('emissive');expect(line).toContain('alpha cutoff 0.4');expect(line).toContain('backfaces are not culled');expect(line).toContain('KHR_materials_clearcoat');});+ it('carries a normal map, extracting its image like any other', () => {+ const doc = withInlineImage();+ doc.images = [+ { mimeType: 'image/png', uri: `data:image/png;base64,${PNG_1PX}` },+ { uri: 'bump.png' },+ ];+ doc.textures = [{ source: 0 }, { source: 1 }];+ (doc.materials as { normalTexture?: unknown }[])[0]!.normalTexture = { index: 1 };+ const { meshes, warnings } = importGltfMeshes(gltf(doc), 'model');+ expect(warnings).toEqual([]);+ expect(meshes[0]!.material?.normalTexture)+ .toEqual({ file: 'bump.png', external: true });+ });+it("flips V, because glTF's uv origin is the image's top-left", () => {const { meshes } = importGltfMeshes(gltf(withInlineImage()), 'model');expect(texCoords(meshes[0]!)).toEqual([0, 1, 1, 1, 0, 0]);@@ -250,6 +264,20 @@ describe('glTF prefab assembly', () => {expect(data.rotation.w).toBeCloseTo(Math.SQRT1_2);});+ it('leaves out a normal map the geometry has no normals for', () => {+ const doc = withInlineImage();+ doc.images = [+ { mimeType: 'image/png', uri: `data:image/png;base64,${PNG_1PX}` },+ { uri: 'bump.png' },+ ];+ doc.textures = [{ source: 0 }, { source: 1 }];+ (doc.materials as { normalTexture?: unknown }[])[0]!.normalTexture = { index: 1 };+ // The fixture's primitive declares no NORMAL, so the engine draws it unlit —+ // a normal map there would be a ref to something nothing reads.+ const prefab = assemble(gltf({ ...doc, ...oneNode }));+ expect(prefab.entities[0]!.components[1]!.data.normalMap).toBeUndefined();+ });+it('scales the root, since a glTF is in metres', () => {const prefab = assemble(gltf({ ...withInlineImage(), ...oneNode }), { scale: 32 });expect(prefab.entities[0]!.components[0]!.data)diff --git a/docs/astro/src/data/components.generated.json b/docs/astro/src/data/components.generated.jsonindex 85c992798..843b039bb 100644--- a/docs/astro/src/data/components.generated.json+++ b/docs/astro/src/data/components.generated.json@@ -1286,6 +1286,12 @@"type": "Asset<texture>","default": "none"},+ {+ "key": "normalMap",+ "type": "Asset<texture>",+ "default": "none",+ "doc": "Normal map (tangent space). Needs a mesh with normals."+ },{"key": "color","type": "Color",diff --git a/pipeline/src/assets/gltfImport.ts b/pipeline/src/assets/gltfImport.tsindex 0c21a2af7..d93a941cc 100644--- a/pipeline/src/assets/gltfImport.ts+++ b/pipeline/src/assets/gltfImport.ts@@ -44,6 +44,8 @@ export interface ImportedMaterial {/** baseColorFactor — the tint multiplied into the vertex colors. */baseColor: [number, number, number, number];baseColorTexture?: ImportedImageRef;+ /** Tangent-space normal map; the engine derives its tangent frame per pixel. */+ normalTexture?: ImportedImageRef;}/** An image the glTF carries inline (GLB chunk or data uri), to be written beside the meshes. */@@ -110,7 +112,8 @@ interface GltfJson {metallicFactor?: number; roughnessFactor?: number;metallicRoughnessTexture?: GltfTextureRef;};- normalTexture?: GltfTextureRef; occlusionTexture?: GltfTextureRef;+ normalTexture?: GltfTextureRef & { scale?: number };+ occlusionTexture?: GltfTextureRef;emissiveTexture?: GltfTextureRef; emissiveFactor?: number[];alphaMode?: string; alphaCutoff?: number; doubleSided?: boolean;extensions?: Record<string, unknown>;@@ -301,7 +304,11 @@ function readMaterial(ctx: MaterialContext, textureCache: Map<number, ImportedImif (pbr.metallicRoughnessTexture || (pbr.metallicFactor ?? 1) !== 0 || (pbr.roughnessFactor ?? 1) !== 1) {unused.push('metallic-roughness');}- if (src.normalTexture) unused.push('normal map');+ // The engine has no strength on a normal map; a scaled one would be imported+ // at full strength, which is a different surface than the author saw.+ if (src.normalTexture?.scale !== undefined && src.normalTexture.scale !== 1) {+ unused.push(`normal-map scale ${src.normalTexture.scale}`);+ }if (src.occlusionTexture) unused.push('occlusion');if (src.emissiveTexture || (src.emissiveFactor ?? [0, 0, 0]).some(v => v !== 0)) unused.push('emissive');if (src.alphaMode === 'MASK') unused.push(`alpha cutoff ${src.alphaCutoff ?? 0.5}`);@@ -311,10 +318,13 @@ function readMaterial(ctx: MaterialContext, textureCache: Map<number, ImportedImconst texture = pbr.baseColorTexture? readTexture(ctx, textureCache, pbr.baseColorTexture, label) : null;+ const normal = src.normalTexture+ ? readTexture(ctx, textureCache, src.normalTexture, label) : null;return {name: src.name ?? `material_${index}`,baseColor: [factor[0] ?? 1, factor[1] ?? 1, factor[2] ?? 1, factor[3] ?? 1],...(texture ? { baseColorTexture: texture } : {}),+ ...(normal ? { normalTexture: normal } : {}),};}@@ -578,14 +588,19 @@ export interface PrefabAssembly {function meshComponent(mesh: ImportedMesh, refs: ProductRefs): ComponentData {const prefix = refs.prefix ?? '';- const image = mesh.material?.baseColorTexture;- const texture = image+ const ref = (image?: ImportedImageRef): string | null => image? (image.external ? refs.external?.(image.file) ?? image.file : prefix + image.file): null;+ const texture = ref(mesh.material?.baseColorTexture);+ // A normal map needs normals to perturb; without them the engine draws the+ // unlit variant and the map would be a reference to nothing.+ const hasNormals = mesh.data.channels.some(c => c.semantic === MeshChannel.Normal);+ const normalMap = hasNormals ? ref(mesh.material?.normalTexture) : null;const color = mesh.material?.baseColor;return { type: 'Mesh2D', data: {mesh: `${prefix}${mesh.name}.esmesh`,...(texture ? { texture } : {}),+ ...(normalMap ? { normalMap } : {}),...(color ? { color: { r: color[0], g: color[1], b: color[2], a: color[3] } } : {}),enabled: true,} };diff --git a/sdk/etc/index.api.md b/sdk/etc/index.api.mdindex a4f07a246..359f20f9e 100644--- a/sdk/etc/index.api.md+++ b/sdk/etc/index.api.md@@ -5,7 +5,7 @@ Symbols: 113 public · 55 beta · 1409 experimental · 3 deprecated## ABI_LAYOUT_HASH — const @experimental```-"310236a4dffb268f"+"96f79850bd2b098b"```## ANCHOR_AXES — const @experimental@@ -4227,6 +4227,7 @@ layer: numberlit: booleanmaterial: numbermesh: number+normalMap: numberparallax: Vec2texture: number```diff --git a/sdk/etc/index.native.api.md b/sdk/etc/index.native.api.mdindex 96814c2d3..b2db9ce28 100644--- a/sdk/etc/index.native.api.md+++ b/sdk/etc/index.native.api.md@@ -5,7 +5,7 @@ Symbols: 113 public · 60 beta · 1428 experimental · 3 deprecated## ABI_LAYOUT_HASH — const @experimental```-"310236a4dffb268f"+"96f79850bd2b098b"```## ANCHOR_AXES — const @experimental@@ -4240,6 +4240,7 @@ layer: numberlit: booleanmaterial: numbermesh: number+normalMap: numberparallax: Vec2texture: number```diff --git a/sdk/etc/index.node.api.md b/sdk/etc/index.node.api.mdindex 120cabbc8..48650be6f 100644--- a/sdk/etc/index.node.api.md+++ b/sdk/etc/index.node.api.md@@ -4222,6 +4222,7 @@ layer: numberlit: booleanmaterial: numbermesh: number+normalMap: numberparallax: Vec2texture: number```diff --git a/sdk/etc/minigame.api.md b/sdk/etc/minigame.api.mdindex 79efa5823..2af731f93 100644--- a/sdk/etc/minigame.api.md+++ b/sdk/etc/minigame.api.md@@ -4222,6 +4222,7 @@ layer: numberlit: booleanmaterial: numbermesh: number+normalMap: numberparallax: Vec2texture: number```diff --git a/sdk/etc/wechat.api.md b/sdk/etc/wechat.api.mdindex eea722cf2..956a7d050 100644--- a/sdk/etc/wechat.api.md+++ b/sdk/etc/wechat.api.md@@ -4229,6 +4229,7 @@ layer: numberlit: booleanmaterial: numbermesh: number+normalMap: numberparallax: Vec2texture: number```diff --git a/sdk/src/ecs/bridge/ptrAccessors.generated.ts b/sdk/src/ecs/bridge/ptrAccessors.generated.tsindex 5a877bae5..4adefd1c3 100644--- a/sdk/src/ecs/bridge/ptrAccessors.generated.ts+++ b/sdk/src/ecs/bridge/ptrAccessors.generated.ts@@ -551,6 +551,7 @@ export function createLight2DData(): Light2DPtrData {export interface Mesh2DPtrData {texture: number;+ normalMap: number;color: Color;layer: number;lit: boolean;@@ -565,13 +566,14 @@ export function fillMesh2D(ptr: number, out: Mesh2DPtrData,): void {out.texture = u32[ptr >> 2];- const color_ = out.color; color_.r = f32[(ptr + 4) >> 2]; color_.g = f32[((ptr + 4) >> 2) + 1]; color_.b = f32[((ptr + 4) >> 2) + 2]; color_.a = f32[((ptr + 4) >> 2) + 3];- out.layer = u32[(ptr + 20) >> 2] | 0;- out.lit = u8[ptr + 24] !== 0;- const parallax_ = out.parallax; parallax_.x = f32[(ptr + 28) >> 2]; parallax_.y = f32[((ptr + 28) >> 2) + 1];- out.material = u32[(ptr + 36) >> 2];- out.enabled = u8[ptr + 40] !== 0;- out.mesh = u32[(ptr + 44) >> 2];+ out.normalMap = u32[(ptr + 4) >> 2];+ const color_ = out.color; color_.r = f32[(ptr + 8) >> 2]; color_.g = f32[((ptr + 8) >> 2) + 1]; color_.b = f32[((ptr + 8) >> 2) + 2]; color_.a = f32[((ptr + 8) >> 2) + 3];+ out.layer = u32[(ptr + 24) >> 2] | 0;+ out.lit = u8[ptr + 28] !== 0;+ const parallax_ = out.parallax; parallax_.x = f32[(ptr + 32) >> 2]; parallax_.y = f32[((ptr + 32) >> 2) + 1];+ out.material = u32[(ptr + 40) >> 2];+ out.enabled = u8[ptr + 44] !== 0;+ out.mesh = u32[(ptr + 48) >> 2];}export function writeMesh2D(@@ -579,18 +581,20 @@ export function writeMesh2D(ptr: number, data: Mesh2DPtrData,): void {u32[ptr >> 2] = data.texture;- f32[(ptr + 4) >> 2] = data.color.r; f32[((ptr + 4) >> 2) + 1] = data.color.g; f32[((ptr + 4) >> 2) + 2] = data.color.b; f32[((ptr + 4) >> 2) + 3] = data.color.a;- u32[(ptr + 20) >> 2] = data.layer | 0;- u8[ptr + 24] = data.lit ? 1 : 0;- f32[(ptr + 28) >> 2] = data.parallax.x; f32[((ptr + 28) >> 2) + 1] = data.parallax.y;- u32[(ptr + 36) >> 2] = data.material;- u8[ptr + 40] = data.enabled ? 1 : 0;- u32[(ptr + 44) >> 2] = data.mesh;+ u32[(ptr + 4) >> 2] = data.normalMap;+ f32[(ptr + 8) >> 2] = data.color.r; f32[((ptr + 8) >> 2) + 1] = data.color.g; f32[((ptr + 8) >> 2) + 2] = data.color.b; f32[((ptr + 8) >> 2) + 3] = data.color.a;+ u32[(ptr + 24) >> 2] = data.layer | 0;+ u8[ptr + 28] = data.lit ? 1 : 0;+ f32[(ptr + 32) >> 2] = data.parallax.x; f32[((ptr + 32) >> 2) + 1] = data.parallax.y;+ u32[(ptr + 40) >> 2] = data.material;+ u8[ptr + 44] = data.enabled ? 1 : 0;+ u32[(ptr + 48) >> 2] = data.mesh;}export function createMesh2DData(): Mesh2DPtrData {return {texture: 0,+ normalMap: 0,color: { r: 0, g: 0, b: 0, a: 0 },layer: 0,lit: false,diff --git a/sdk/src/ecs/component.generated.ts b/sdk/src/ecs/component.generated.tsindex 47534ca4b..036d3a075 100644--- a/sdk/src/ecs/component.generated.ts+++ b/sdk/src/ecs/component.generated.ts@@ -15,7 +15,7 @@ import type { Dimension, Padding } from '../wasm/wasm.generated';* getAbiLayoutHash(); BuiltinBridge.connect() compares them and refuses to* run on mismatch, because mismatched offsets read the wrong heap bytes.*/-export const ABI_LAYOUT_HASH = '310236a4dffb268f';+export const ABI_LAYOUT_HASH = '96f79850bd2b098b';/*** One asset-valued field of a component: which field, and what kind of@@ -329,6 +329,7 @@ export const COMPONENT_META: Record<string, ComponentMetaEntry> = {Mesh2D: {defaults: {texture: 0,+ normalMap: 0,color: { r: 1, g: 1, b: 1, a: 1 },layer: 0,lit: false,@@ -338,11 +339,12 @@ export const COMPONENT_META: Record<string, ComponentMetaEntry> = {mesh: 0,},renderableField: 'enabled',- assetFields: [{ field: 'texture', type: 'texture' as AssetFieldType }, { field: 'material', type: 'material' as AssetFieldType }, { field: 'mesh', type: 'mesh' as AssetFieldType }],+ assetFields: [{ field: 'texture', type: 'texture' as AssetFieldType }, { field: 'normalMap', type: 'texture' as AssetFieldType }, { field: 'material', type: 'material' as AssetFieldType }, { field: 'mesh', type: 'mesh' as AssetFieldType }],entityFields: [],colorFields: ['color'],animatableFields: ['color.r', 'color.g', 'color.b', 'color.a'],fields: {+ normalMap: { tooltip: "Normal map (tangent space). Needs a mesh with normals." },color: { tooltip: "Tint multiplied into the vertex colors (white = unchanged)." },layer: { step: 1, tooltip: "Sorting layer — controls draw order across renderables.", enumSource: "sortingLayers" },lit: { tooltip: "Receive 2D lights: Light2D entities light this mesh (flat normal). A custom material overrides this." },@@ -999,6 +1001,7 @@ export interface Light2DData {export interface Mesh2DData {texture: number;+ normalMap: number;color: Color;layer: number;lit: boolean;diff --git a/sdk/src/wasm/ptrLayouts.generated.ts b/sdk/src/wasm/ptrLayouts.generated.tsindex 04b80c54e..70af23b0c 100644--- a/sdk/src/wasm/ptrLayouts.generated.ts+++ b/sdk/src/wasm/ptrLayouts.generated.ts@@ -166,13 +166,14 @@ export const PTR_LAYOUTS: Record<string, PtrLayout> = {ptrFn: 'getMesh2DPtr',fields: [{ name: 'texture', type: 'u32', offset: 0 },- { name: 'color', type: 'color', offset: 4 },- { name: 'layer', type: 'i32', offset: 20 },- { name: 'lit', type: 'bool', offset: 24 },- { name: 'parallax', type: 'vec2', offset: 28 },- { name: 'material', type: 'u32', offset: 36 },- { name: 'enabled', type: 'bool', offset: 40 },- { name: 'mesh', type: 'u32', offset: 44 },+ { name: 'normalMap', type: 'u32', offset: 4 },+ { name: 'color', type: 'color', offset: 8 },+ { name: 'layer', type: 'i32', offset: 24 },+ { name: 'lit', type: 'bool', offset: 28 },+ { name: 'parallax', type: 'vec2', offset: 32 },+ { name: 'material', type: 'u32', offset: 40 },+ { name: 'enabled', type: 'bool', offset: 44 },+ { name: 'mesh', type: 'u32', offset: 48 },],},ParticleEmitter: {diff --git a/sdk/src/wasm/wasm.generated.ts b/sdk/src/wasm/wasm.generated.tsindex c220fc2b2..c77a958ee 100644--- a/sdk/src/wasm/wasm.generated.ts+++ b/sdk/src/wasm/wasm.generated.ts@@ -344,6 +344,7 @@ export interface Light2D {export interface Mesh2D {texture: number;+ normalMap: number;color: Vec4;layer: number;lit: boolean;diff --git a/sdk/tests/__snapshots__/component-fieldmeta-golden.test.ts.snap b/sdk/tests/__snapshots__/component-fieldmeta-golden.test.ts.snapindex fc3d65b3b..13c4fb9b3 100644--- a/sdk/tests/__snapshots__/component-fieldmeta-golden.test.ts.snap+++ b/sdk/tests/__snapshots__/component-fieldmeta-golden.test.ts.snap@@ -230,6 +230,9 @@ exports[`builtin FieldMeta (RC9-1 equivalence gate) > matches the golden snapsho"material": {"advanced": true,},+ "normalMap": {+ "tooltip": "Normal map (tangent space). Needs a mesh with normals.",+ },"parallax": {"advanced": true,"tooltip": "Parallax scroll factor (1 = with world, <1 = slower, 0 = locked to camera).",diff --git a/src/esengine/bindings/EditorAPI.generated.cpp b/src/esengine/bindings/EditorAPI.generated.cppindex 9c8d19c79..0a8ea826c 100644--- a/src/esengine/bindings/EditorAPI.generated.cpp+++ b/src/esengine/bindings/EditorAPI.generated.cpp@@ -2,10 +2,10 @@* @file EditorAPI.generated.cpp* @brief Auto-generated editor API with string-dispatched component access* @details Generated by EHT - DO NOT EDIT- * @schema_hash 1ff4dcdf319a842c+ * @schema_hash 54ca135d78453810*/-#define ES_EDITOR_API_SCHEMA_HASH "1ff4dcdf319a842c"+#define ES_EDITOR_API_SCHEMA_HASH "54ca135d78453810"#include <emscripten/bind.h>#include <string>@@ -246,6 +246,7 @@ std::string editor_getComponentSchema(const std::string& name) {} else if (name == "Mesh2D") {return R"JSON([{"key":"texture","type":"asset","group":"Mesh2D"},+ {"key":"normalMap","type":"asset","group":"Mesh2D"},{"key":"color.r","type":"color","group":"Mesh2D"},{"key":"color.g","type":"color","group":"Mesh2D"},{"key":"color.b","type":"color","group":"Mesh2D"},@@ -1664,6 +1665,7 @@ bool editor_setInt(Registry& reg, u32 e, const std::string& comp, const std::strif (!reg.has<esengine::ecs::Mesh2D>(entity)) return false;auto& c = reg.get<esengine::ecs::Mesh2D>(entity);if (field == "texture") { c.texture = resource::TextureHandle(static_cast<u32>(value)); }+ else if (field == "normalMap") { c.normalMap = resource::TextureHandle(static_cast<u32>(value)); }else if (field == "layer") { c.layer = static_cast<i32>(value); }else if (field == "material") { c.material = static_cast<u32>(value); }else if (field == "mesh") { c.mesh = resource::MeshHandle(static_cast<u32>(value)); }@@ -1852,6 +1854,7 @@ i32 editor_getInt(Registry& reg, u32 e, const std::string& comp, const std::striif (!reg.has<esengine::ecs::Mesh2D>(entity)) return 0;const auto& c = reg.get<esengine::ecs::Mesh2D>(entity);if (field == "texture") { return static_cast<i32>(c.texture.id()); }+ else if (field == "normalMap") { return static_cast<i32>(c.normalMap.id()); }else if (field == "layer") { return static_cast<i32>(c.layer); }else if (field == "material") { return static_cast<i32>(c.material); }else if (field == "mesh") { return static_cast<i32>(c.mesh.id()); }diff --git a/src/esengine/bindings/WebBindings.generated.cpp b/src/esengine/bindings/WebBindings.generated.cppindex 4a97285ae..5b9a4610f 100644--- a/src/esengine/bindings/WebBindings.generated.cpp+++ b/src/esengine/bindings/WebBindings.generated.cpp@@ -440,6 +440,7 @@ FlexContainerJS flexcontainerToJS(const esengine::ecs::FlexContainer& c) {struct Mesh2DJS {u32 texture;+ u32 normalMap;glm::vec4 color;i32 layer;bool lit;@@ -451,6 +452,7 @@ struct Mesh2DJS {void mesh2dApplyJS(esengine::ecs::Mesh2D& c, const Mesh2DJS& js) {c.texture = resource::TextureHandle(js.texture);+ c.normalMap = resource::TextureHandle(js.normalMap);c.color = js.color;c.layer = js.layer;c.lit = js.lit;@@ -469,6 +471,7 @@ esengine::ecs::Mesh2D mesh2dFromJS(const Mesh2DJS& js) {Mesh2DJS mesh2dToJS(const esengine::ecs::Mesh2D& c) {Mesh2DJS js;js.texture = c.texture.id();+ js.normalMap = c.normalMap.id();js.color = c.color;js.layer = c.layer;js.lit = c.lit;@@ -1216,6 +1219,7 @@ EMSCRIPTEN_BINDINGS(esengine_components) {value_object<Mesh2DJS>("Mesh2D").field("texture", &Mesh2DJS::texture)+ .field("normalMap", &Mesh2DJS::normalMap).field("color", &Mesh2DJS::color).field("layer", &Mesh2DJS::layer).field("lit", &Mesh2DJS::lit)@@ -2306,13 +2310,14 @@ static_assert(offsetof(esengine::ecs::Light2D, shadowSoftness) == 44, "ABI offsestatic_assert(offsetof(esengine::ecs::Light2D, shadowDistance) == 48, "ABI offset drift: esengine::ecs::Light2D.shadowDistance (EHT expected 48)");static_assert(offsetof(esengine::ecs::Light2D, enabled) == 52, "ABI offset drift: esengine::ecs::Light2D.enabled (EHT expected 52)");static_assert(offsetof(esengine::ecs::Mesh2D, texture) == 0, "ABI offset drift: esengine::ecs::Mesh2D.texture (EHT expected 0)");-static_assert(offsetof(esengine::ecs::Mesh2D, color) == 4, "ABI offset drift: esengine::ecs::Mesh2D.color (EHT expected 4)");-static_assert(offsetof(esengine::ecs::Mesh2D, layer) == 20, "ABI offset drift: esengine::ecs::Mesh2D.layer (EHT expected 20)");-static_assert(offsetof(esengine::ecs::Mesh2D, lit) == 24, "ABI offset drift: esengine::ecs::Mesh2D.lit (EHT expected 24)");-static_assert(offsetof(esengine::ecs::Mesh2D, parallax) == 28, "ABI offset drift: esengine::ecs::Mesh2D.parallax (EHT expected 28)");-static_assert(offsetof(esengine::ecs::Mesh2D, material) == 36, "ABI offset drift: esengine::ecs::Mesh2D.material (EHT expected 36)");-static_assert(offsetof(esengine::ecs::Mesh2D, enabled) == 40, "ABI offset drift: esengine::ecs::Mesh2D.enabled (EHT expected 40)");-static_assert(offsetof(esengine::ecs::Mesh2D, mesh) == 44, "ABI offset drift: esengine::ecs::Mesh2D.mesh (EHT expected 44)");+static_assert(offsetof(esengine::ecs::Mesh2D, normalMap) == 4, "ABI offset drift: esengine::ecs::Mesh2D.normalMap (EHT expected 4)");+static_assert(offsetof(esengine::ecs::Mesh2D, color) == 8, "ABI offset drift: esengine::ecs::Mesh2D.color (EHT expected 8)");+static_assert(offsetof(esengine::ecs::Mesh2D, layer) == 24, "ABI offset drift: esengine::ecs::Mesh2D.layer (EHT expected 24)");+static_assert(offsetof(esengine::ecs::Mesh2D, lit) == 28, "ABI offset drift: esengine::ecs::Mesh2D.lit (EHT expected 28)");+static_assert(offsetof(esengine::ecs::Mesh2D, parallax) == 32, "ABI offset drift: esengine::ecs::Mesh2D.parallax (EHT expected 32)");+static_assert(offsetof(esengine::ecs::Mesh2D, material) == 40, "ABI offset drift: esengine::ecs::Mesh2D.material (EHT expected 40)");+static_assert(offsetof(esengine::ecs::Mesh2D, enabled) == 44, "ABI offset drift: esengine::ecs::Mesh2D.enabled (EHT expected 44)");+static_assert(offsetof(esengine::ecs::Mesh2D, mesh) == 48, "ABI offset drift: esengine::ecs::Mesh2D.mesh (EHT expected 48)");static_assert(offsetof(esengine::ecs::ParticleEmitter, rate) == 0, "ABI offset drift: esengine::ecs::ParticleEmitter.rate (EHT expected 0)");static_assert(offsetof(esengine::ecs::ParticleEmitter, burstCount) == 4, "ABI offset drift: esengine::ecs::ParticleEmitter.burstCount (EHT expected 4)");static_assert(offsetof(esengine::ecs::ParticleEmitter, burstInterval) == 8, "ABI offset drift: esengine::ecs::ParticleEmitter.burstInterval (EHT expected 8)");@@ -2517,7 +2522,7 @@ static_assert(offsetof(esengine::ecs::Velocity, angular) == 12, "ABI offset drif// ABI Hash -- runtime handshake against the SDK bundle// =============================================================================-static const char* kEsAbiLayoutHash = "310236a4dffb268f";+static const char* kEsAbiLayoutHash = "96f79850bd2b098b";std::string esengineGetAbiLayoutHash() {return std::string(kEsAbiLayoutHash);diff --git a/src/esengine/data/shaders/mesh.esshader b/src/esengine/data/shaders/mesh.esshaderindex bc5d9543c..ffb681a9f 100644--- a/src/esengine/data/shaders/mesh.esshader+++ b/src/esengine/data/shaders/mesh.esshader@@ -12,6 +12,11 @@// inside the switch on both sides.#pragma feature LIT+// A normal map on top of those normals. Its tangent frame comes from the shared+// perturbNormal (screen-space derivatives), so the geometry needs no tangent+// channel — which is why this rides LIT rather than a vertex attribute.+#pragma feature NORMAL_MAP+// GPU-resident geometry. Slot 0 is the mesh's own vertices, which are LOCAL// space and are never rewritten; slot 1 is the per-object record the frame// streams, so the same mesh drawn twice costs one more transform rather than@@ -49,7 +54,9 @@ out vec2 v_texCoord;out vec4 v_color;#ifdef LITout highp vec3 v_worldNormal;-out highp vec2 v_worldPos;+// The full position, not just the plane's: a tangent frame is derived from how+// it changes across a fragment, which xy alone cannot say for a tilted surface.+out highp vec3 v_worldPos;#endifvoid main() {@@ -60,7 +67,7 @@ void main() {v_color = a_color * a_instTint;#ifdef LITv_worldNormal = mat3(a_nrm0, a_nrm1, a_nrm2) * a_normal;- v_worldPos = world.xy;+ v_worldPos = world.xyz;#endif}#pragma end@@ -72,17 +79,24 @@ in vec2 v_texCoord;in vec4 v_color;#ifdef LITin highp vec3 v_worldNormal;-in highp vec2 v_worldPos;+in highp vec3 v_worldPos;#endifuniform sampler2D u_texture;+#ifdef NORMAL_MAP+uniform sampler2D u_normalMap;+#endifout vec4 fragColor;void main() {vec4 base = texture(u_texture, v_texCoord) * v_color;#ifdef LIT- fragColor = vec4(applyLighting2D(base.rgb, normalize(v_worldNormal), v_worldPos), base.a);+ highp vec3 N = normalize(v_worldNormal);+#ifdef NORMAL_MAP+ N = perturbNormal(N, v_worldPos, v_texCoord, sampleNormal(u_normalMap, v_texCoord));+#endif+ fragColor = vec4(applyLighting2D(base.rgb, N, v_worldPos.xy), base.a);#elsefragColor = base;#endif@@ -117,7 +131,7 @@ struct VSOut {@location(1) v_color : vec4f,#ifdef LIT@location(2) v_worldNormal : vec3f,- @location(3) v_worldPos : vec2f,+ @location(3) v_worldPos : vec3f,#endif};@@ -131,7 +145,7 @@ struct VSOut {out.v_color = v.a_color * v.a_instTint;#ifdef LITout.v_worldNormal = mat3x3f(v.a_nrm0, v.a_nrm1, v.a_nrm2) * v.a_normal;- out.v_worldPos = world.xy;+ out.v_worldPos = world.xyz;#endifreturn out;}@@ -140,6 +154,10 @@ struct VSOut {#pragma fragment wgsl@group(1) @binding(0) var t0 : texture_2d<f32>;@group(1) @binding(8) var s0 : sampler;+#ifdef NORMAL_MAP+@group(1) @binding(1) var t1 : texture_2d<f32>;+@group(1) @binding(9) var s1 : sampler;+#endifstruct VSOut {@builtin(position) pos : vec4f,@@ -147,14 +165,18 @@ struct VSOut {@location(1) v_color : vec4f,#ifdef LIT@location(2) v_worldNormal : vec3f,- @location(3) v_worldPos : vec2f,+ @location(3) v_worldPos : vec3f,#endif};@fragment fn fs_main(v : VSOut) -> @location(0) vec4f {let base = textureSampleLevel(t0, s0, v.v_texCoord, 0.0) * v.v_color;#ifdef LIT- return vec4f(applyLighting2D(base.rgb, normalize(v.v_worldNormal), v.v_worldPos), base.a);+ var N = normalize(v.v_worldNormal);+#ifdef NORMAL_MAP+ N = perturbNormal(N, v.v_worldPos, v.v_texCoord, sampleNormal(t1, s1, v.v_texCoord));+#endif+ return vec4f(applyLighting2D(base.rgb, N, v.v_worldPos.xy), base.a);#elsereturn base;#endifdiff --git a/src/esengine/ecs/components/Mesh2D.hpp b/src/esengine/ecs/components/Mesh2D.hppindex fe697cc3e..e3743896b 100644--- a/src/esengine/ecs/components/Mesh2D.hpp+++ b/src/esengine/ecs/components/Mesh2D.hpp@@ -48,6 +48,12 @@ struct Mesh2D {ES_PROPERTY(asset = texture)resource::TextureHandle texture;+ /** @brief Tangent-space normal map, applied on top of the geometry's own normals.+ * Needs a mesh that HAS normals; its tangent frame is derived per pixel,+ * so the geometry carries no tangent channel. */+ ES_PROPERTY(asset = texture, tooltip="Normal map (tangent space). Needs a mesh with normals.")+ resource::TextureHandle normalMap;+/** @brief Color tint multiplied with per-vertex colors (white = unchanged) */ES_PROPERTY(animatable, tooltip="Tint multiplied into the vertex colors (white = unchanged).")glm::vec4 color{1.0f, 1.0f, 1.0f, 1.0f};diff --git a/src/esengine/renderer/draw/BatchBuilder.cpp b/src/esengine/renderer/draw/BatchBuilder.cppindex 2493b7d04..d1cc93302 100644--- a/src/esengine/renderer/draw/BatchBuilder.cpp+++ b/src/esengine/renderer/draw/BatchBuilder.cpp@@ -101,6 +101,12 @@ void pushBatchDraw(DrawList& drawList, const ClipState& clips,// textureless, so execute() must not touch sampler units for it).cmd.texture_count = (key.layoutId == LayoutId::Batch || key.textureId != 0) ? 1 : 0;cmd.texture_ids[0] = key.textureId;+ // Slot 1 belongs to the draw, so it is only ever bound where the shader+ // declares it — the Batch stream picks its extra slots per vertex instead.+ if (key.normalTextureId != 0 && cmd.texture_count == 1 && key.layoutId != LayoutId::Batch) {+ cmd.texture_ids[1] = key.normalTextureId;+ cmd.texture_count = 2;+ }cmd.entity = key.entity;cmd.type = key.type;cmd.layer = key.layer;diff --git a/src/esengine/renderer/draw/BatchBuilder.hpp b/src/esengine/renderer/draw/BatchBuilder.hppindex 6dfdfc9a7..2b55b0baa 100644--- a/src/esengine/renderer/draw/BatchBuilder.hpp+++ b/src/esengine/renderer/draw/BatchBuilder.hpp@@ -83,6 +83,10 @@ struct BatchDrawKey {u32 shaderId = 0;BlendMode blend = BlendMode::Normal;u32 textureId = 0;+ // A second sampler this draw needs for itself (a mesh's normal map), bound to+ // slot 1. Not the same thing as the Batch stream's extra slots, which are a+ // MERGE product chosen per vertex.+ u32 normalTextureId = 0;f32 depth = 0.0f;// World-space Y of the draw's anchor. Consumed only when the layer is y-sorted// (DrawList::ySortMask); layers outside 0..31 cannot y-sort.diff --git a/src/esengine/renderer/plugins/MeshPlugin.cpp b/src/esengine/renderer/plugins/MeshPlugin.cppindex a5514d76e..5616139af 100644--- a/src/esengine/renderer/plugins/MeshPlugin.cpp+++ b/src/esengine/renderer/plugins/MeshPlugin.cpp@@ -15,6 +15,7 @@#include <glm/gtc/matrix_transform.hpp>#include <glm/gtc/matrix_inverse.hpp>+#include <algorithm>#include <string>#include <vector>@@ -43,6 +44,8 @@ void MeshPlugin::init(RenderFrameContext& ctx) {// shader consumes: geometry without normals must not be drawn by a program// that reads them, and the reverse leaves the normals unlit.auto compile = [&](std::vector<std::string> features) -> u32 {+ const bool normalMapped = std::find(features.begin(), features.end(), "NORMAL_MAP")+ != features.end();resource::ShaderHandle handle = ctx.resources.createShaderWithBindings(resource::ShaderParser::assembleStage(parsed, resource::ShaderStage::Vertex, "", features, target),resource::ShaderParser::assembleStage(parsed, resource::ShaderStage::Fragment, "", features, target),@@ -52,12 +55,15 @@ void MeshPlugin::init(RenderFrameContext& ctx) {if (shader->language() == GfxShaderLanguage::GLSL_ES300) {shader->bind();shader->setUniform("u_texture", 0);+ // Slot 1 is where a draw's own second texture is bound (see pushBatchDraw).+ if (normalMapped) shader->setUniform("u_normalMap", 1);shader->unbind();}return shader->getProgramId();};mesh_shader_id_ = compile({});mesh_lit_shader_id_ = compile({"LIT"});+ mesh_normalmap_shader_id_ = compile({"LIT", "NORMAL_MAP"});}void MeshPlugin::collect(RenderCollectContext& collect_ctx) {@@ -103,6 +109,13 @@ void MeshPlugin::collect(RenderCollectContext& collect_ctx) {textureId = tex->getId();}}+ // Only meaningful with normals to perturb, so it is read where that is known.+ u32 normalTextureId = 0;+ if (mesh.normalMap.isValid() && resident && resident->hasNormals) {+ if (Texture* tex = ctx.resources.getTexture(mesh.normalMap)) {+ normalTextureId = tex->getId();+ }+ }BatchDrawKey key{.stage = ctx.current_stage,@@ -110,6 +123,7 @@ void MeshPlugin::collect(RenderCollectContext& collect_ctx) {.shaderId = ctx.batch_shader_id,.blend = BlendMode::Normal,.textureId = textureId,+ .normalTextureId = normalTextureId,.depth = position.z,.y = position.y,.entity = entity,@@ -137,7 +151,9 @@ void MeshPlugin::collect(RenderCollectContext& collect_ctx) {// vertices are local-space and untouched, so the CPU loop below — which// exists to bake world space into every vertex — is skipped entirely.if (resident && mesh_shader_id_ != 0) {- const u32 residentShader = resident->hasNormals ? mesh_lit_shader_id_ : mesh_shader_id_;+ const u32 residentShader = normalTextureId != 0 && mesh_normalmap_shader_id_ != 0+ ? mesh_normalmap_shader_id_+ : (resident->hasNormals ? mesh_lit_shader_id_ : mesh_shader_id_);if (resident->isDrawable() && residentShader != 0) {const u32 stride = resident->hasNormals? MESH_INSTANCE_STRIDE_LIT : MESH_INSTANCE_STRIDE;diff --git a/src/esengine/renderer/plugins/MeshPlugin.hpp b/src/esengine/renderer/plugins/MeshPlugin.hppindex 95de5f231..7ff5f55aa 100644--- a/src/esengine/renderer/plugins/MeshPlugin.hpp+++ b/src/esengine/renderer/plugins/MeshPlugin.hpp@@ -25,6 +25,7 @@ private:std::vector<BatchVertex> scratch_; ///< Reused per mesh; amortizes the transform buffer.u32 mesh_shader_id_ = 0; ///< Resident geometry with a per-object transform.u32 mesh_lit_shader_id_ = 0; ///< The same for geometry carrying normals.+ u32 mesh_normalmap_shader_id_ = 0; ///< Those normals, perturbed by a normal map.bool warned_material_ = false; ///< A material on resident geometry is said once.};diff --git a/src/esengine/renderer/rhi/ShaderEmbeds.generated.hpp b/src/esengine/renderer/rhi/ShaderEmbeds.generated.hppindex 52f89cc60..f0cc14d0f 100644--- a/src/esengine/renderer/rhi/ShaderEmbeds.generated.hpp+++ b/src/esengine/renderer/rhi/ShaderEmbeds.generated.hpp@@ -285,6 +285,11 @@ inline constexpr const char* MESH = R"esshader(#pragma shader "Mesh"// inside the switch on both sides.#pragma feature LIT+// A normal map on top of those normals. Its tangent frame comes from the shared+// perturbNormal (screen-space derivatives), so the geometry needs no tangent+// channel — which is why this rides LIT rather than a vertex attribute.+#pragma feature NORMAL_MAP+// GPU-resident geometry. Slot 0 is the mesh's own vertices, which are LOCAL// space and are never rewritten; slot 1 is the per-object record the frame// streams, so the same mesh drawn twice costs one more transform rather than@@ -322,7 +327,9 @@ out vec2 v_texCoord;out vec4 v_color;#ifdef LITout highp vec3 v_worldNormal;-out highp vec2 v_worldPos;+// The full position, not just the plane's: a tangent frame is derived from how+// it changes across a fragment, which xy alone cannot say for a tilted surface.+out highp vec3 v_worldPos;#endifvoid main() {@@ -333,7 +340,7 @@ void main() {v_color = a_color * a_instTint;#ifdef LITv_worldNormal = mat3(a_nrm0, a_nrm1, a_nrm2) * a_normal;- v_worldPos = world.xy;+ v_worldPos = world.xyz;#endif}#pragma end@@ -345,17 +352,24 @@ in vec2 v_texCoord;in vec4 v_color;#ifdef LITin highp vec3 v_worldNormal;-in highp vec2 v_worldPos;+in highp vec3 v_worldPos;#endifuniform sampler2D u_texture;+#ifdef NORMAL_MAP+uniform sampler2D u_normalMap;+#endifout vec4 fragColor;void main() {vec4 base = texture(u_texture, v_texCoord) * v_color;#ifdef LIT- fragColor = vec4(applyLighting2D(base.rgb, normalize(v_worldNormal), v_worldPos), base.a);+ highp vec3 N = normalize(v_worldNormal);+#ifdef NORMAL_MAP+ N = perturbNormal(N, v_worldPos, v_texCoord, sampleNormal(u_normalMap, v_texCoord));+#endif+ fragColor = vec4(applyLighting2D(base.rgb, N, v_worldPos.xy), base.a);#elsefragColor = base;#endif@@ -390,7 +404,7 @@ struct VSOut {@location(1) v_color : vec4f,#ifdef LIT@location(2) v_worldNormal : vec3f,- @location(3) v_worldPos : vec2f,+ @location(3) v_worldPos : vec3f,#endif};@@ -404,7 +418,7 @@ struct VSOut {out.v_color = v.a_color * v.a_instTint;#ifdef LITout.v_worldNormal = mat3x3f(v.a_nrm0, v.a_nrm1, v.a_nrm2) * v.a_normal;- out.v_worldPos = world.xy;+ out.v_worldPos = world.xyz;#endifreturn out;}@@ -413,6 +427,10 @@ struct VSOut {#pragma fragment wgsl@group(1) @binding(0) var t0 : texture_2d<f32>;@group(1) @binding(8) var s0 : sampler;+#ifdef NORMAL_MAP+@group(1) @binding(1) var t1 : texture_2d<f32>;+@group(1) @binding(9) var s1 : sampler;+#endifstruct VSOut {@builtin(position) pos : vec4f,@@ -420,14 +438,18 @@ struct VSOut {@location(1) v_color : vec4f,#ifdef LIT@location(2) v_worldNormal : vec3f,- @location(3) v_worldPos : vec2f,+ @location(3) v_worldPos : vec3f,#endif};@fragment fn fs_main(v : VSOut) -> @location(0) vec4f {let base = textureSampleLevel(t0, s0, v.v_texCoord, 0.0) * v.v_color;#ifdef LIT- return vec4f(applyLighting2D(base.rgb, normalize(v.v_worldNormal), v.v_worldPos), base.a);+ var N = normalize(v.v_worldNormal);+#ifdef NORMAL_MAP+ N = perturbNormal(N, v.v_worldPos, v.v_texCoord, sampleNormal(t1, s1, v.v_texCoord));+#endif+ return vec4f(applyLighting2D(base.rgb, N, v.v_worldPos.xy), base.a);#elsereturn base;#endifdiff --git a/src/esengine/resource/ShaderParser.cpp b/src/esengine/resource/ShaderParser.cppindex 6e513fd0a..257f25bd4 100644--- a/src/esengine/resource/ShaderParser.cpp+++ b/src/esengine/resource/ShaderParser.cpp@@ -655,6 +655,23 @@ struct LightConstants {fn sampleNormal(map : texture_2d<f32>, samp : sampler, uv : vec2f) -> vec3f {return normalize(textureSampleLevel(map, samp, uv, 0.0).xyz * 2.0 - 1.0);}+fn perturbNormal(N : vec3f, worldPos : vec3f, uv : vec2f, tangentNormal : vec3f) -> vec3f {+ let dp1 = dpdx(worldPos);+ // Negated: this backend's framebuffer y runs the other way, so dpdy answers+ // with the opposite sign to GLSL's dFdy. Left alone it flips T and B, and a+ // normal map lights the wrong side — which only the second backend shows.+ let dp2 = -dpdy(worldPos);+ let duv1 = dpdx(uv);+ let duv2 = -dpdy(uv);+ let dp2perp = cross(dp2, N);+ let dp1perp = cross(N, dp1);+ let T = dp2perp * duv1.x + dp1perp * duv2.x;+ let B = dp2perp * duv1.y + dp1perp * duv2.y;+ let m = max(max(dot(T, T), dot(B, B)), 1e-12);+ if (m <= 1e-11) { return N; }+ let invmax = inverseSqrt(m);+ return normalize(mat3x3f(T * invmax, B * invmax, N) * tangentNormal);+}fn segHitsBox(p0 : vec2f, p1 : vec2f, box : vec4f) -> f32 {if (p0.x >= box.x && p0.y >= box.y && p0.x <= box.z && p0.y <= box.w) { return 0.0; }let d = p1 - p0;@@ -1000,6 +1017,24 @@ ShaderParser::AssembledStage ShaderParser::assembleStageEx(const ParsedShader& p"highp vec3 sampleNormal(in highp sampler2D map, in highp vec2 uv) {\n"" return normalize(texture(map, uv).xyz * 2.0 - 1.0);\n""}\n"+ // Tangent frame from screen-space derivatives, so a tangent-space normal+ // lands in world space without the geometry carrying a tangent channel —+ // which most exported models do not. Degenerate UVs return N unchanged.+ "highp vec3 perturbNormal(in highp vec3 N, in highp vec3 worldPos,\n"+ " in highp vec2 uv, in highp vec3 tangentNormal) {\n"+ " highp vec3 dp1 = dFdx(worldPos);\n"+ " highp vec3 dp2 = dFdy(worldPos);\n"+ " highp vec2 duv1 = dFdx(uv);\n"+ " highp vec2 duv2 = dFdy(uv);\n"+ " highp vec3 dp2perp = cross(dp2, N);\n"+ " highp vec3 dp1perp = cross(N, dp1);\n"+ " highp vec3 T = dp2perp * duv1.x + dp1perp * duv2.x;\n"+ " highp vec3 B = dp2perp * duv1.y + dp1perp * duv2.y;\n"+ " highp float m = max(dot(T, T), dot(B, B));\n"+ " if (m <= 1e-11) return N;\n"+ " highp float invmax = inversesqrt(m);\n"+ " return normalize(mat3(T * invmax, B * invmax, N) * tangentNormal);\n"+ "}\n"// 2D hard shadows: a slab test of the fragment->light segment against a world AABB.// Returns 1.0 when the segment crosses the box's interior, else 0.0. The [0,1] param// clamp means boxes behind the fragment or beyond the light don't occlude. A boxdiff --git a/tools/renderScenes.mjs b/tools/renderScenes.mjsindex 39c513ecb..a415253f2 100644--- a/tools/renderScenes.mjs+++ b/tools/renderScenes.mjs@@ -136,6 +136,10 @@ export const SCENES = [// offset to have reached the child, and the fourth is background only if the// child's scale survived — ignore the tree and everything stacks on the origin.{ id: "mesh-nodes", tier: "pr", webgpu: true, env: { ESTELLA_VERIFY_PREFAB: "/scenes/node-tree.esprefab", ESTELLA_VERIFY_SCENE: "/scenes/mesh-nodes.esscene", ESTELLA_VERIFY_MANIFEST: "/scenes/mesh-nodes.textures.json", ESTELLA_VERIFY_W: "256", ESTELLA_VERIFY_H: "256", ESTELLA_VERIFY_STEPS: "4", ESTELLA_VERIFY_EXPECT: "[{\"x\":0.3667,\"y\":0.40,\"rgb\":[255,0,0],\"tol\":40},{\"x\":0.45,\"y\":0.40,\"rgb\":[255,0,0],\"tol\":40},{\"x\":0.7667,\"y\":0.60,\"rgb\":[0,255,0],\"tol\":40},{\"x\":0.7667,\"y\":0.5333,\"rgb\":[0,0,0],\"tol\":30}]" } },+ // A normal map over FLAT normals: the quad faces the viewer, so without the map+ // both halves take the same light. Its texels point -X and +X, so the lit half+ // and the unlit one are the tangent frame, derived per pixel from derivatives.+ { id: "mesh-normalmap", tier: "pr", webgpu: true, env: { ESTELLA_VERIFY_PREFAB: "/scenes/normalmap-quad.esprefab", ESTELLA_VERIFY_SCENE: "/scenes/mesh-normalmap.esscene", ESTELLA_VERIFY_MANIFEST: "/scenes/mesh-normalmap.textures.json", ESTELLA_VERIFY_W: "256", ESTELLA_VERIFY_H: "256", ESTELLA_VERIFY_STEPS: "4", ESTELLA_VERIFY_EXPECT: "[{\"x\":0.375,\"y\":0.5,\"rgb\":[180,180,180],\"tol\":45},{\"x\":0.625,\"y\":0.5,\"rgb\":[0,0,0],\"tol\":30}]" } },// 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// scene passed with the re-upload deleted. No webgpu — no GL extension there.