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 material's vertex hook hands the fragment the colour it leaves
yhh5f2c1711bba4
diff --git a/sdk/src/terrain/mesh.ts b/sdk/src/terrain/mesh.tsdeleted file mode 100644index 61d35b57d..000000000--- a/sdk/src/terrain/mesh.ts+++ /dev/null@@ -1,151 +0,0 @@-// SPDX-License-Identifier: Apache-2.0-// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team-/**- * @file mesh.ts- * @brief One square of the ground, as geometry, at as many levels of detail as it is wanted at.- *- * @details The terrain is cut into chunks and each chunk is built several times over, a grid a half- * as fine at every level. The engine's own level-of-detail picks among them by how large- * the chunk is on screen, so a hill in the distance costs a few hundred triangles and one- * underfoot a couple of thousand.- *- * Two neighbours at different levels have different numbers of vertices along the edge they- * share, so their surfaces part there — a crack the sky shows through. The cure is a skirt:- * a wall let down from each edge of the chunk, deep enough to hide the gap. It is cheap, it- * needs no knowledge of the neighbour (a chunk is built alone, and may change level without- * rebuilding anyone else), and it costs a ring of triangles that is never seen from above.- *- * Heights and normals are read from the one field at every level, so a chunk keeps its- * lighting as it coarsens; only its silhouette changes.- */-import { MeshChannel, MeshChannelType, packChannels, type MeshData } from '../asset/meshFormat';-import { sampleHeight, terrainNormal, type Heightfield } from './heightfield';--/** The size and cut of a terrain. */-export interface TerrainShape {- /** World extent along x and z. The terrain is centred on its entity. */- sizeX: number;- sizeZ: number;- /** World height of a field value of 1. */- height: number;- /** Chunks along each side. */- chunks: number;- /** Cells along a chunk's side at the finest level (a power of two reads best). */- chunkCells: number;-}--/** What a vertex is painted: the weights of four layers, or the colour of a terrain that has no material. */-export type TerrainPaint = (- u: number, v: number, height01: number, slope: number,-) => [number, number, number, number];--/** How many cells a chunk has a side at `lod`: half as many at each, never fewer than two. */-export function cellsAtLod(shape: TerrainShape, lod: number): number {- return Math.max(2, shape.chunkCells >> lod);-}--/** How many levels of detail a chunk is worth having, from the finest down to one that is still two cells across. */-export function lodCount(shape: TerrainShape, wanted = 4): number {- let levels = 1;- while (levels < wanted && cellsAtLod(shape, levels) < cellsAtLod(shape, levels - 1)) levels++;- return levels;-}--/** The centre of chunk (cx, cz) in the terrain's own space, which is centred on its origin. */-export function chunkCenter(shape: TerrainShape, cx: number, cz: number): [number, number] {- const w = shape.sizeX / shape.chunks, d = shape.sizeZ / shape.chunks;- return [-shape.sizeX / 2 + (cx + 0.5) * w, -shape.sizeZ / 2 + (cz + 0.5) * d];-}--/**- * Chunk (cx, cz) at level `lod`. Positions are relative to {@link chunkCenter}, so the entity that draws it is- * placed there and the mesh itself stays small and centred (which is what culling and sorting measure).- */-export function buildChunkMesh(- field: Heightfield, shape: TerrainShape, cx: number, cz: number, lod: number, paint: TerrainPaint,-): MeshData {- const cells = cellsAtLod(shape, lod);- const w = shape.sizeX / shape.chunks, d = shape.sizeZ / shape.chunks;- const stepX = w / cells, stepZ = d / cells;- const skirt = Math.max(stepX, stepZ) * 1.5 + shape.height * 0.02;- const row = cells + 1;-- const positions: number[] = [];- const uvs: number[] = [];- const normals: number[] = [];- const colors: number[] = [];- const indices: number[] = [];-- const addVertex = (i: number, j: number, drop: number): number => {- // The vertex's place in the whole terrain, 0 to 1.- const u = (cx * cells + i) / (shape.chunks * cells);- const v = (cz * cells + j) / (shape.chunks * cells);- const h = sampleHeight(field, u, v);- const n = terrainNormal(field, u, v, shape.sizeX, shape.sizeZ, shape.height);- positions.push(-w / 2 + i * stepX, h * shape.height - drop, -d / 2 + j * stepZ);- uvs.push(u, v);- normals.push(n[0], n[1], n[2]);- const c = paint(u, v, h, n[1]);- colors.push(c[0], c[1], c[2], c[3]);- return positions.length / 3 - 1;- };-- for (let j = 0; j <= cells; j++) for (let i = 0; i <= cells; i++) addVertex(i, j, 0);- const at = (i: number, j: number): number => j * row + i;- for (let j = 0; j < cells; j++) {- for (let i = 0; i < cells; i++) {- // Up is the way the face looks: a, then the next row, then the next column, runs counter-clockwise from above.- indices.push(at(i, j), at(i, j + 1), at(i + 1, j));- indices.push(at(i + 1, j), at(i, j + 1), at(i + 1, j + 1));- }- }-- // The skirt: a second row of vertices under each edge one, wound to face outward.- const wall = (edge: number[], flip: boolean): void => {- const below = edge.map((v) => {- const i = v % row, j = Math.floor(v / row);- return addVertex(i, j, skirt);- });- for (let k = 0; k < edge.length - 1; k++) {- const a = edge[k]!, b = edge[k + 1]!, c = below[k]!, e = below[k + 1]!;- if (flip) { indices.push(a, c, b); indices.push(b, c, e); }- else { indices.push(a, b, c); indices.push(b, e, c); }- }- };- const north: number[] = [], south: number[] = [], west: number[] = [], east: number[] = [];- for (let i = 0; i <= cells; i++) { north.push(at(i, 0)); south.push(at(i, cells)); }- for (let j = 0; j <= cells; j++) { west.push(at(0, j)); east.push(at(cells, j)); }- wall(north, false);- wall(south, true);- wall(west, true);- wall(east, false);-- 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 },- { semantic: MeshChannel.Normal, components: 3, type: MeshChannelType.Float32 },- ]);- const vertexCount = positions.length / 3;- const vertices = new Uint8Array(vertexCount * vertexStride);- const view = new DataView(vertices.buffer);- const posAt = channels[0]!.offset, uvAt = channels[1]!.offset, colorAt = channels[2]!.offset, normalAt = channels[3]!.offset;- const min: [number, number, number] = [Infinity, Infinity, Infinity];- const max: [number, number, number] = [-Infinity, -Infinity, -Infinity];- for (let i = 0; i < vertexCount; i++) {- const base = i * vertexStride;- for (let k = 0; k < 3; k++) {- const value = positions[i * 3 + k]!;- view.setFloat32(base + posAt + k * 4, value, true);- view.setFloat32(base + normalAt + k * 4, normals[i * 3 + k]!, true);- if (value < min[k]!) min[k] = value;- if (value > max[k]!) max[k] = value;- }- view.setFloat32(base + uvAt, uvs[i * 2]!, true);- view.setFloat32(base + uvAt + 4, uvs[i * 2 + 1]!, true);- for (let k = 0; k < 4; k++) {- view.setUint8(base + colorAt + k, Math.round(Math.min(Math.max(colors[i * 4 + k]!, 0), 1) * 255));- }- }- return { channels, vertexStride, vertexCount, vertices, indices: new Uint32Array(indices), aabbMin: min, aabbMax: max };-}diff --git a/sdk/tests/terrain-mesh.test.ts b/sdk/tests/terrain-mesh.test.tsdeleted file mode 100644index 90b4980a5..000000000--- a/sdk/tests/terrain-mesh.test.ts+++ /dev/null@@ -1,134 +0,0 @@-// SPDX-License-Identifier: Apache-2.0-// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team-import { describe, it, expect } from 'vitest';-import { MeshChannel } from '../src/asset/meshFormat';-import { heightfieldFromPixels, proceduralHeightfield, sampleHeight, terrainNormal } from '../src/terrain/heightfield';-import { buildChunkMesh, cellsAtLod, chunkCenter, lodCount, type TerrainShape } from '../src/terrain/mesh';--const SHAPE: TerrainShape = { sizeX: 800, sizeZ: 400, height: 100, chunks: 4, chunkCells: 16 };-const paint = (): [number, number, number, number] => [1, 0, 0, 1];--function positionsOf(mesh: ReturnType<typeof buildChunkMesh>): number[][] {- const pos = mesh.channels.find((c) => c.semantic === MeshChannel.Position)!;- const view = new DataView(mesh.vertices.buffer);- const out: number[][] = [];- for (let i = 0; i < mesh.vertexCount; i++) {- const at = i * mesh.vertexStride + pos.offset;- out.push([view.getFloat32(at, true), view.getFloat32(at + 4, true), view.getFloat32(at + 8, true)]);- }- return out;-}--describe('heightfield', () => {- it('reads a red channel as the height, and a green one as the low byte of a 16-bit height', () => {- const flat = heightfieldFromPixels(2, 2, [0, 0, 0, 255, 255, 255, 255, 255, 128, 0, 0, 255, 0, 0, 0, 255]);- expect(flat.data[0]).toBe(0);- expect(flat.data[1]).toBe(1);- expect(flat.data[2]).toBeCloseTo(128 / 255, 5);- const wide = heightfieldFromPixels(2, 1, [1, 0, 0, 255, 1, 7, 0, 255]);- expect(wide.data[1]!).toBeGreaterThan(wide.data[0]!);- expect(wide.data[1]).toBeCloseTo(263 / 65535, 6);- });-- it('makes the same ground from the same seed, different ground from another, spanning 0 to 1', () => {- const params = { resolution: 33, seed: 7, frequency: 3, octaves: 4, persistence: 0.5, ridged: 0 };- const a = proceduralHeightfield(params), b = proceduralHeightfield(params), c = proceduralHeightfield({ ...params, seed: 8 });- expect([...a.data]).toEqual([...b.data]);- expect([...a.data]).not.toEqual([...c.data]);- expect(Math.min(...a.data)).toBeCloseTo(0, 6);- expect(Math.max(...a.data)).toBeCloseTo(1, 6);- });-- it('is bilinear between samples and clamps outside the field', () => {- const f = heightfieldFromPixels(2, 2, [0, 0, 0, 255, 255, 0, 0, 255, 0, 0, 0, 255, 255, 0, 0, 255]);- expect(sampleHeight(f, 0.5, 0.5)).toBeCloseTo(0.5, 5);- expect(sampleHeight(f, -3, 0)).toBe(0);- expect(sampleHeight(f, 4, 0)).toBe(1);- });-- it('has an upward normal on level ground and one that leans away from a rise', () => {- const level = heightfieldFromPixels(4, 4, new Array(64).fill(0));- const n0 = terrainNormal(level, 0.5, 0.5, 100, 100, 50);- expect(n0[0]).toBeCloseTo(0, 6);- expect(n0[1]).toBeCloseTo(1, 6);- // Heights climb with x: the ground faces back toward -x and up.- const ramp = heightfieldFromPixels(4, 4, new Array(16).fill(0).flatMap((_, i) => [(i % 4) * 85, 0, 0, 255]));- const n = terrainNormal(ramp, 0.5, 0.5, 100, 100, 50);- expect(n[0]).toBeLessThan(-0.1);- expect(n[1]).toBeGreaterThan(0);- expect(Math.hypot(...n)).toBeCloseTo(1, 5);- });-});--describe('terrain chunk mesh', () => {- const field = proceduralHeightfield({ resolution: 65, seed: 3, frequency: 4, octaves: 4, persistence: 0.5, ridged: 0.3 });-- it('halves its grid at each level and keeps at least two cells', () => {- expect([0, 1, 2, 3].map((l) => cellsAtLod(SHAPE, l))).toEqual([16, 8, 4, 2]);- expect(lodCount(SHAPE, 4)).toBe(4);- expect(lodCount({ ...SHAPE, chunkCells: 2 }, 4)).toBe(1);- });-- it('has a surface of cells x cells x 2 triangles and a skirt of 8 x cells more', () => {- for (const lod of [0, 1, 2, 3]) {- const cells = cellsAtLod(SHAPE, lod);- const mesh = buildChunkMesh(field, SHAPE, 1, 2, lod, paint);- expect(mesh.indices.length / 3).toBe(cells * cells * 2 + cells * 8);- expect(mesh.vertexCount).toBe((cells + 1) ** 2 + 4 * (cells + 1));- for (const i of mesh.indices) expect(i).toBeLessThan(mesh.vertexCount);- }- });-- it('is centred on its own origin and spans one chunk', () => {- const mesh = buildChunkMesh(field, SHAPE, 0, 0, 0, paint);- expect(mesh.aabbMin[0]).toBeCloseTo(-100, 4);- expect(mesh.aabbMax[0]).toBeCloseTo(100, 4);- expect(mesh.aabbMin[2]).toBeCloseTo(-50, 4);- expect(mesh.aabbMax[2]).toBeCloseTo(50, 4);- expect(chunkCenter(SHAPE, 0, 0)).toEqual([-300, -150]);- expect(chunkCenter(SHAPE, 3, 3)).toEqual([300, 150]);- });-- it('faces its surface triangles up', () => {- const mesh = buildChunkMesh(field, SHAPE, 2, 1, 0, paint);- const p = positionsOf(mesh);- const cells = cellsAtLod(SHAPE, 0);- let up = 0;- for (let t = 0; t < cells * cells * 2; t++) {- const [a, b, c] = [mesh.indices[t * 3]!, mesh.indices[t * 3 + 1]!, mesh.indices[t * 3 + 2]!];- const u = [p[b]![0]! - p[a]![0]!, p[b]![1]! - p[a]![1]!, p[b]![2]! - p[a]![2]!];- const v = [p[c]![0]! - p[a]![0]!, p[c]![1]! - p[a]![1]!, p[c]![2]! - p[a]![2]!];- if (u[2]! * v[0]! - u[0]! * v[2]! < 0) up++;- }- expect(up).toBe(0);- });-- it('lets a skirt down below every edge so a coarser neighbour cannot show a crack', () => {- const mesh = buildChunkMesh(field, SHAPE, 1, 1, 1, paint);- const p = positionsOf(mesh);- const cells = cellsAtLod(SHAPE, 1);- const surface = (cells + 1) ** 2;- for (let k = 0; k < 4 * (cells + 1); k++) {- const drop = p[surface + k]!;- const edge = p.slice(0, surface).find((q) => q[0] === drop[0] && q[2] === drop[2]);- expect(edge).toBeDefined();- expect(edge![1]! - drop[1]!).toBeGreaterThan(0);- }- });-- it('agrees with its neighbour on the height of the corners they share, at every level', () => {- for (const lod of [0, 1, 2, 3]) {- const left = positionsOf(buildChunkMesh(field, SHAPE, 1, 1, lod, paint));- const right = positionsOf(buildChunkMesh(field, SHAPE, 2, 1, lod, paint));- const cells = cellsAtLod(SHAPE, lod);- const row = cells + 1;- for (let j = 0; j <= cells; j++) expect(left[j * row + cells]![1]).toBeCloseTo(right[j * row]![1]!, 4);- }- });-- it('carries the paint in the vertex colour', () => {- const mesh = buildChunkMesh(field, SHAPE, 0, 0, 3, () => [0, 0.5, 1, 1]);- const color = mesh.channels.find((c) => c.semantic === MeshChannel.Color)!;- expect([...mesh.vertices.slice(color.offset, color.offset + 4)]).toEqual([0, 128, 255, 255]);- });-});diff --git a/src/esengine/data/shaders/mesh.esshader b/src/esengine/data/shaders/mesh.esshaderindex 7ba88e054..ece7f6388 100644--- a/src/esengine/data/shaders/mesh.esshader+++ b/src/esengine/data/shaders/mesh.esshader@@ -207,7 +207,12 @@ void main() {#endifgl_Position = u_projection * world;v_texCoord = a_texCoord;+ // A material's hook may leave a colour of its own for the fragment (a terrain tells it where in its pages the vertex lies).+#ifdef ES_MATERIAL_VERTEX+ v_color = es_vertexColor * esInstanceTint();+#elsev_color = a_color * esInstanceTint();+#endif#if defined(WEIGHT_HEAT) && defined(SKINNED){uint chosen = uint(esInstanceTint().x);@@ -487,7 +492,11 @@ fn esPrevBone(joint : u32) -> mat4x4f {var out : VSOut;out.pos = frame.projection * world;out.v_texCoord = v.a_texCoord;+#ifdef ES_MATERIAL_VERTEX+ out.v_color = es_vertexColor * esInstanceTint();+#elseout.v_color = v.a_color * esInstanceTint();+#endif#ifdef WEIGHT_HEAT#ifdef SKINNED{diff --git a/src/esengine/resource/ShaderParser.cpp b/src/esengine/resource/ShaderParser.cppindex 24cb86c45..d2eb6e200 100644--- a/src/esengine/resource/ShaderParser.cpp+++ b/src/esengine/resource/ShaderParser.cpp@@ -343,7 +343,7 @@ std::string canonicalVertexStageWGSL(bool lit, const std::string& hook = {}) {" out.v_color = v.a_color * esInstanceTint();\n""#elif defined(MESH)\n"" let world = esInstanceModel() * vec4f(local, 1.0);\n"- " out.v_color = v.a_color * esInstanceTint();\n"+ " out.v_color = @@WGSL_MESH_COLOR@@ * esInstanceTint();\n""#else\n"" let world = vec4f(v.a_position, 1.0);\n"" out.v_color = v.a_color;\n"@@ -387,7 +387,9 @@ std::string canonicalVertexStageWGSL(bool lit, const std::string& hook = {}) {" return out;\n""}\n";// The vertex's own colour is the one per-vertex channel a hook has besides its position, normal and uv: wind sways a plant by- // a weight painted in it. A hook reads `es_vertexColor`; one that does not is not changed.+ // a weight painted in it. A hook reads `es_vertexColor`, and what it leaves there is the colour the fragment gets (a terrain+ // tells it where the vertex lies in its height pages); one that does not touch it is not changed.+ fillHook(src, "@@WGSL_MESH_COLOR@@", hook.empty() ? std::string("v.a_color") : std::string("es_vertexColor"));fillHook(src, "@@WGSL_HOOK@@", hook.empty() ? std::string() :"#ifdef MESH\nvar<private> es_vertexColor : vec4f;\n" + hook + "\n#endif\n");fillHook(src, "@@WGSL_CALL@@", hook.empty() ? std::string() :@@ -567,7 +569,7 @@ std::string canonicalVertexStage(bool lit, const std::string& hook = {}) {" v_color = a_color * esInstanceTint();\n""#elif defined(MESH)\n"" vec4 world = esInstanceModel() * vec4(local, 1.0);\n"- " v_color = a_color * esInstanceTint();\n"+ " v_color = @@GLSL_MESH_COLOR@@ * esInstanceTint();\n""#else\n"" vec4 world = vec4(a_position, 1.0);\n"" v_color = a_color;\n"@@ -608,6 +610,7 @@ std::string canonicalVertexStage(bool lit, const std::string& hook = {}) {src += " v_probeSlot = float(ES_INSTANCE_ID);\n";}src += "}\n";+ fillHook(src, "@@GLSL_MESH_COLOR@@", hook.empty() ? std::string("a_color") : std::string("es_vertexColor"));fillHook(src, "@@GLSL_HOOK@@", hook.empty() ? std::string() :"#ifdef MESH\nhighp vec4 es_vertexColor;\n" + hook + "\n#endif\n");fillHook(src, "@@GLSL_CALL@@", hook.empty() ? std::string() :