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
fix(modeling): a model's report is its steps as written, and names a step that undoes a decimate - the report listed every plain step a repeat came to (a tree of thirteen rows of branches was a hundred and thirty-eight entries) under indexes no edit takes, and said nothing when a patterned stain after a decimate split 1100 triangles into 214,534; a repeat is one entry counted, each step says the triangles it left, and such a step is a warning naming both
yhh1a56a09b96c2
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex d646fad7d..ded434ee3 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -36,6 +36,7 @@ published separately; it ships inside the editor.### Fixed+- **A model's report is its steps as written, and names a step that undoes a decimate.** `report.steps` of a baked model listed every plain step its repeats came to, by an index among those: a spruce of thirteen rows of branches reported a hundred and thirty-eight steps, most the same line, and none under the index `model_edit` takes. It is now one entry for each step as written, by that index, a repeat counted once with how many steps it `made`, and each entry says the `triangles` the mesh had after it. And a step that splits faces to carry its own detail (a stain by a pattern, a displace, a sculpt) after a `decimate` took the decimate's triangles back in silence: a rock thinned to 1100 came out at 214,534, under the 300,000 the report calls heavy, and a field of them would have been gigabytes. The report now warns of each such step, with what it was given, what it left and which decimate it undid, and says how to keep the detail (before the decimate, carried by `normalBake`) or bound it (`detail`). The test also notes what the advice costs: a pattern stained before a decimate leaves colour seams the decimate will not cross, so it is `normalBake`'s `color: true` that carries it.- **A playable's start-screen bar moves through the whole boot.** The bar's stages were weighed for a web page, most of whose start is fetching the engine. A playable has the engine inlined, so its bar stood at 82% within a second and crawled to 95% over the twenty-five that followed. A playable now weighs its own stages (the scene's is four fifths of the bar), and that stage is followed in three stretches: assets being read and made (eased by the clock, since nothing counts them), shaders compiled against the most seen compiling, and the world prepared against the most its makers said was left. For that, a hold given to `holdShaderWarmup` may answer a number (pages, cells) where it answered yes, and `warmShaders` passes the sum to `onProgress`; Terrain and Foliage count theirs. One lake scene's bar went from 18% to 95% over its 22 seconds, with one stretch of four seconds standing still. `attachSplash` takes the weights.- **An effect chain keeps its uniform buffers from frame to frame.** A camera's post-process chain is said again every frame, and each of its passes made a uniform buffer for its parameters and deleted it when the chain was cleared: seventeen buffers created and seventeen deleted every frame for a lake scene with a volume's usual effects, counted in the GL calls of an exported page. The buffers of a cleared chain are now taken over by the passes of the next chain that need one the same size, and one that nothing has taken in eight clears is deleted. The same scene creates none in a steady frame.- **A shadow map is drawn again only when what it holds changed.** Every shadow-casting mesh was drawn into the shadow atlas every frame for every light, though in most frames nothing in a map had moved: Bistro drew 891 casters a frame for a sun and a scene that were both still. The atlas is now kept from frame to frame, and the frame compares what its squares would draw (where each looks from, the casters, their transforms, bones and shapes, the materials of cut-out casters) with what was last drawn into them, and skips the pass when they are the same. A caster that moves, a light that turns, a camera that walks the sun's cascades on to the next texel, a lost device or geometry rewritten in place draw it again. A material that moves its vertices (wind, a ground's height) is assumed to move them every frame, so a map it casts into is always drawn. On Bistro at 640x360 the WebGL calls a frame went from 7,139 to 3,627 and the renderer's CPU time from 3.3 to 2.3 ms. `render.shadow.reused` says whether a frame drew the atlas.diff --git a/pipeline/src/modeling/modelBake.ts b/pipeline/src/modeling/modelBake.tsindex c397ce7e6..f985d60c2 100644--- a/pipeline/src/modeling/modelBake.ts+++ b/pipeline/src/modeling/modelBake.ts@@ -15,7 +15,7 @@ import { triangulateFace } from './triangulate';import { faceUvs } from './modelUv';import { adjustWeights, bindMatrices, computeWeights, computeWornWeights, drapeRig, resolveJoints, shapeDeltas, type ControllerIk, type RigGoal, type RigJoint, type RigSpring, type SkinWeights } from './rig';import type { NormalBakeReport } from './normalBake';-import { buildPolyMesh, expandModelSource, validateModelSource, type ModelSource, type StepReport } from './modelSource';+import { buildPolyMesh, expandModelSource, validateModelSource, writtenStepReports, type ModelSource, type StepReport } from './modelSource';import {boundsOf, collectEdges, cross, dot, faceArea, faceNormal, length, normalize, sub,type PolyMesh, type Vec3, compact,@@ -24,6 +24,8 @@ import {const DEFAULT_SMOOTH_ANGLE = 30;const DEFAULT_NORMAL_SIZE = 1024;const HEAVY_TRIANGLES = 300000;+/** How many times over a step has to multiply the triangles after a decimate before the report says it undid one. */+const REFINED_PAST_DECIMATE = 2;export const HAIR_CUTOFF = 0.35;const LIGHTMAP_TRIANGLES = 150000;@@ -340,7 +342,8 @@ export function modelMaterialDoc(source: ModelSource, cullBackfaces: boolean, ma/** Validates, builds and bakes @p raw. Throws a ModelBuildError naming the step that failed; writes nothing, so a failure leaves nothing half made. */export function bakeModel(raw: unknown): BakedModel {// The plain steps: the report counts them, and a step's own fields are read back by its index among them.- const source = expandModelSource(validateModelSource(raw));+ const asWritten = validateModelSource(raw);+ const source = expandModelSource(asWritten);const built = buildPolyMesh(source);const { steps, high, notes } = built;// A fractured model is two things: its pieces, which the report and the views are of, and the model before the cut,@@ -436,14 +439,27 @@ export function bakeModel(raw: unknown): BakedModel {if (idle.length) warnings.push(`joint${idle.length > 1 ? 's' : ''} ${idle.join(', ')} move${idle.length > 1 ? '' : 's'} no vertex the most: too near another, or outside the surface`);}- // The engine's delta texture is 2048 square, the most WebGL2 guarantees; past it the mesh draws, but never changes shape.+ // A decimate is the triangles its author means the model to have. A step after it that splits faces to carry its own detail (a+ // patterned stain, a displace, a sculpt) takes them back without saying so: a rock decimated to 1100 came out at 214,534, and a+ // field of them was gigabytes. Said once for each such step, against what the decimate before it left.+ let decimated: { label: string; triangles: number } | null = null;+ let was = 0;+ for (const s of steps) {+ if (s.op === 'decimate' && source.steps[s.index]!.faces === undefined) decimated = { label: s.label, triangles: s.triangles };+ else if (decimated && s.triangles > was * REFINED_PAST_DECIMATE && s.triangles > decimated.triangles * REFINED_PAST_DECIMATE) {+ warnings.push(`${s.label} split the ${was} triangles it was given into ${s.triangles}, after ${decimated.label} had left ${decimated.triangles}: its detail wants finer faces than the decimate kept. Put it before the decimate and let \`normalBake\` carry it to the thinned surface (\`color: true\` for a stain's colours), or give it a \`detail\` no finer than the faces it is given (a larger number)`);+ }+ was = s.triangles;+ }+for (const s of steps) {const step = source.steps[s.index]!;if (s.op !== 'decimate' || step.faces !== undefined) continue;const target = (step.triangles as number | undefined) ?? Math.round(s.trianglesBefore! * (step.ratio as number));- if (s.trianglesAfter! > target * 1.1) warnings.push(`step ${s.index} (decimate) stopped at ${s.trianglesAfter} triangles of the ${target} asked: the surface would have moved more than \`error\` allows. Raise it to go further`);+ if (s.trianglesAfter! > target * 1.1) warnings.push(`${s.label} stopped at ${s.trianglesAfter} triangles of the ${target} asked: the surface would have moved more than \`error\` allows. Raise it to go further`);}+ // The engine's delta texture is 2048 square, the most WebGL2 guarantees; past it the mesh draws, but never changes shape.if (shapes && shapes.names.length * unwrapped.vertexCount * 2 > 2048 * 2048) {warnings.push(`${shapes.names.length} shapes over ${unwrapped.vertexCount} vertices is more than the engine holds (${2048 * 2048} deltas, two each): it would draw but never change shape. Lower the resolution or use fewer shapes`);}@@ -486,7 +502,7 @@ export function bakeModel(raw: unknown): BakedModel {size: roundVec(sub(max, min)),center: roundVec([(min[0] + max[0]) / 2, (min[1] + max[1]) / 2, (min[2] + max[2]) / 2]),},- tags, openEdges, nonManifoldEdges, flippedEdges, degenerateFaces, insideOutShells, steps, ...(jointReport ? { joints: jointReport } : {}), ...(shards.length ? { pieces: shards.length } : {}), warnings,+ tags, openEdges, nonManifoldEdges, flippedEdges, degenerateFaces, insideOutShells, steps: writtenStepReports(steps, asWritten), ...(jointReport ? { joints: jointReport } : {}), ...(shards.length ? { pieces: shards.length } : {}), warnings,},};}diff --git a/pipeline/src/modeling/modelSource.ts b/pipeline/src/modeling/modelSource.tsindex b52eff6c5..6e9729974 100644--- a/pipeline/src/modeling/modelSource.ts+++ b/pipeline/src/modeling/modelSource.ts@@ -496,7 +496,7 @@ function validatePlain(raw: unknown): ModelSource {continue;}if (key === 'texture') {- if (typeof value !== 'string' || !/\.(png|jpg|jpeg|webp)$/i.test(value)) throw new ModelBuildError('material.texture must be a project path to a picture (.png, .jpg, .webp)', null, null, null);+ if (typeof value !== 'string' || !/.(png|jpg|jpeg|webp)$/i.test(value)) throw new ModelBuildError('material.texture must be a project path to a picture (.png, .jpg, .webp)', null, null, null);continue;}if (!['roughness', 'metallic', 'cutoff'].includes(key)) throw new ModelBuildError(`material has an unknown field "${key}"; it takes roughness, metallic, alpha, cutoff, emissive, texture`, null, null, null);@@ -564,20 +564,60 @@ function validatePlain(raw: unknown): ModelSource {return { version: MODEL_SOURCE_VERSION, ...(source as unknown as Omit<ModelSource, 'version'>) };}+/** What one step of the source as written did: a repeat is one step, however many plain steps its rows came to. */export interface StepReport {+ /** Its place in the source as written, which is what an edit names. */index: number;id?: string;op: string;+ /** The plain steps it came to, where that is more than one: a repeat's rows times its steps. */+ made?: number;/** Faces in the mesh after it ran. */faces: number;+ /** Triangles in the mesh after it ran: what a step cost is this against the step before. */+ triangles: number;/** A decimate: triangles it was given, and triangles it left. */trianglesBefore?: number;trianglesAfter?: number;}+/** What one plain step did: a step of the source with its names, sums and repeats worked out, by its index among those. */+export interface PlainStepReport extends Omit<StepReport, 'made'> {+ /** The step of the source as written that it came from. */+ written: number;+ /** How it is named when something is said of it: where it was written, a repeat's row included. */+ label: string;+}++/**+ * The plain steps' reports as the source was written: the steps a repeat made are one entry, counted, with the mesh as its last+ * left it. A tree of thirteen rows of branches reported a hundred and thirty-eight steps, most of them the same line.+ */+export function writtenStepReports(plain: readonly PlainStepReport[], written: ModelSource): StepReport[] {+ const out: StepReport[] = [];+ let last = -1, made = 0;+ for (const s of plain) {+ const { written: at, label: _label, index: _index, ...rest } = s;+ if (at === last) {+ const entry = out[out.length - 1]!;+ entry.made = ++made;+ entry.faces = s.faces;+ entry.triangles = s.triangles;+ continue;+ }+ last = at; made = 1;+ const step = written.steps[at] as Partial<ModelStep> | undefined;+ const op = (step?.op as string | undefined) ?? s.op;+ // A repeat's own entry is the repeat: the op and id of one of the steps inside it would name a step no edit can reach.+ out.push(op === s.op ? { index: at, ...rest } : { index: at, ...(step?.id ? { id: step.id as string } : {}), op, faces: s.faces, triangles: s.triangles });+ }+ return out;+}+export interface ModelBuild {mesh: PolyMesh;- steps: StepReport[];+ /** One for each plain step, in order. */+ steps: PlainStepReport[];/** The surface `normalBake` carries, as the steps stood then. */high?: PolyMesh;/** What steps wanted said, in their order. */@@ -588,7 +628,7 @@ export interface ModelBuild {export function buildPolyMesh(written: ModelSource): ModelBuild {const source = expandModelSource(written);let mesh: PolyMesh = { positions: [], faces: [] };- const steps: StepReport[] = [];+ const steps: PlainStepReport[] = [];const bake = source.normalBake;// After this step, the surface is the one to carry: the one named, or the one before the last decimate.const highAfter = !bake ? -2 : bake.from !== undefined ? source.steps.findIndex((s) => s.id === bake.from) : source.steps.map((s) => s.op).lastIndexOf('decimate') - 1;@@ -615,7 +655,11 @@ export function buildPolyMesh(written: ModelSource): ModelBuild {// What a fracture leaves beside its pieces stays with them: it is not a note.mesh = { positions: mesh.positions, faces: mesh.faces, ...(mesh.whole ? { whole: mesh.whole } : {}) };}- steps.push({ index, ...(id ? { id } : {}), op, faces: mesh.faces.length, ...(op === 'decimate' ? { trianglesBefore: before, trianglesAfter: triangleCount(mesh) } : {}) });+ const triangles = triangleCount(mesh);+ steps.push({+ index, written: writtenIndex(step, index), label: stepLabel(step, index), ...(id ? { id } : {}), op, faces: mesh.faces.length, triangles,+ ...(op === 'decimate' ? { trianglesBefore: before, trianglesAfter: triangles } : {}),+ });if (index === highAfter) high = compact(mesh);if (id && wanted.has(id)) kept.set(id, mesh);});diff --git a/pipeline/tests/modeling-report.test.ts b/pipeline/tests/modeling-report.test.tsnew file mode 100644index 000000000..b1cd28f2c--- /dev/null+++ b/pipeline/tests/modeling-report.test.ts@@ -0,0 +1,86 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * What a model's report says of its steps: one entry for each step as written, what each cost in triangles, and that a step which+ * takes back what a decimate left is named.+ */+import { describe, expect, it } from 'vitest';+import { applyModelEdits, bakeModel, validateModelSource, type ModelSource } from '../src/modeling';++describe('a model report\'s steps', () => {+ const tree: ModelSource = {+ version: 1,+ steps: [+ { id: 'trunk', op: 'cylinder', radius: 0.1, height: 2, sides: 6, at: [0, 1, 0] },+ { op: 'repeat', over: [{ y: 0.5, k: 3 }, { y: 1, k: 4 }, { y: 1.5, k: 2 }], steps: [+ { op: 'repeat', count: '=k', steps: [+ { op: 'box', size: [0.4, 0.05, 0.1], at: '=polar(i * 360 / k, 0.3, y)' },+ ] },+ ] },+ { id: 'top', op: 'cone', radius: 0.1, height: 0.3, sides: 6, at: [0, 2.15, 0] },+ ] as ModelSource['steps'],+ };++ it('are the steps as written: a repeat is one, counted, and an index is what an edit names', () => {+ const { report } = bakeModel(tree);+ expect(report.steps.map((s) => [s.index, s.op, s.id, s.made])).toEqual([+ [0, 'cylinder', 'trunk', undefined],+ // Nine boxes, from three rows of three, four and two.+ [1, 'repeat', undefined, 9],+ [2, 'cone', 'top', undefined],+ ]);+ // The repeat's entry is the mesh as its last box left it.+ expect(report.steps[1]!.faces - report.steps[0]!.faces).toBe(9 * 6);+ expect(report.steps.at(-1)!.triangles).toBe(report.triangles);++ // And the index is the one an edit takes: the step it names is the step the report meant.+ const edited = applyModelEdits(validateModelSource(tree), [{ op: 'remove', step: report.steps[2]!.index }]);+ expect(edited.steps.map((s) => s.op)).toEqual(['cylinder', 'repeat']);+ });++ it('say what each step left in triangles', () => {+ const { report } = bakeModel({ version: 1, steps: [+ { op: 'sphere', radius: 1, rings: 12, sides: 16 },+ { id: 'thin', op: 'decimate', triangles: 120 },+ ] });+ expect(report.steps[0]!.triangles).toBeGreaterThan(300);+ expect(report.steps[1]).toMatchObject({ index: 1, id: 'thin', op: 'decimate', trianglesBefore: report.steps[0]!.triangles });+ expect(report.steps[1]!.triangles).toBe(report.steps[1]!.trianglesAfter);+ });++ it('name a step that splits what a decimate left, and say nothing of one that does not', () => {+ const rock = (after: ModelSource['steps']): string[] => bakeModel({ version: 1, steps: [+ { id: 'body', op: 'sphere', radius: 1, rings: 16, sides: 24, tag: 'rock' },+ { id: 'thin', op: 'decimate', triangles: 200 },+ ...after,+ ] as ModelSource['steps'] }).report.warnings;++ // A stain by a pattern is as fine as its pattern: it splits the faces the decimate kept.+ const said = rock([{ id: 'lichen', op: 'stain', faces: 'rock', color: [0.3, 0.4, 0.2], pattern: 'bumps', scale: 0.12 }]);+ const warning = said.find((w) => w.includes('lichen'));+ expect(warning).toBeDefined();+ expect(warning).toMatch(/split the \d+ triangles it was given into \d+/);+ expect(warning).toContain('"thin"');+ expect(warning).toContain('before the decimate');+ expect(warning).toContain('normalBake');++ // One by shape or by facing is as fine as the faces already are.+ expect(rock([{ id: 'moss', op: 'stain', faces: 'rock', color: [0.1, 0.2, 0.1], facing: [0, 1, 0] }]).some((w) => w.includes('split'))).toBe(false);+ // And a pattern before the decimate takes nothing back.+ const before = bakeModel({ version: 1, steps: [+ { id: 'body', op: 'sphere', radius: 1, rings: 16, sides: 24, tag: 'rock' },+ { id: 'lichen', op: 'stain', faces: 'rock', color: [0.3, 0.4, 0.2], pattern: 'bumps', scale: 0.12 },+ { id: 'thin', op: 'decimate', triangles: 200 },+ ] });+ expect(before.report.warnings.some((w) => w.includes('split'))).toBe(false);+ });+});++describe('a model\'s picture', () => {+ it('may be a recipe as well as an image, and nothing else', () => {+ const withTexture = (texture: string): unknown => ({ version: 1, material: { texture }, steps: [{ op: 'box', size: [1, 1, 1] }] });+ expect(() => validateModelSource(withTexture('assets/textures/bough.png'))).not.toThrow();+ expect(() => validateModelSource(withTexture('assets/textures/bough.esimage'))).not.toThrow();+ expect(() => validateModelSource(withTexture('assets/textures/bough.esmaterial'))).toThrow(/\.esimage/);+ });+});diff --git a/tools/releaseNotes.mjs b/tools/releaseNotes.mjsindex 3b9835f2d..30b417bbc 100644--- a/tools/releaseNotes.mjs+++ b/tools/releaseNotes.mjs@@ -4796,4 +4796,6 @@ export const NOTED = {{"note": "A playable's start-screen bar moves through the whole boot."},"perf(render): a shadow map is drawn again only when what it holds changed - every caster of every light was drawn into the atlas every frame, still or not; the frame keeps its atlas and a hash of what each square would draw, and skips the pass when nothing in it moved":{"note": "A shadow map is drawn again only when what it holds changed."},+ "fix(modeling): a model's report is its steps as written, and names a step that undoes a decimate - the report listed every plain step a repeat came to (a tree of thirteen rows of branches was a hundred and thirty-eight entries) under indexes no edit takes, and said nothing when a patterned stain after a decimate split 1100 triangles into 214,534; a repeat is one entry counted, each step says the triangles it left, and such a step is a warning naming both":+ {"note": "A model's report is its steps as written, and names a step that undoes a decimate."},};