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.

5.7 KB
Raw Blame
#!/usr/bin/env node
// SPDX-License-Identifier: Apache-2.0
// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
/**
 * @file  gen-retained-text-cases.mjs — what the TS text culling keeps, for the C++ copy of it to agree with.
 *
 * A label's glyph quads are clipped against the view in two places: sdk/src/ui/text/text-culling.ts, which the path that hands every label over
 * every frame still runs, and renderer/draw/RetainedText.hpp, which the engine runs on the labels it keeps. They must keep the same quads, and
 * the only way to say so is to run both on the same inputs. This writes random batches, views and models with the quads the TS one keeps, in
 * tests/renderer/data/retained_text_cases.txt, which test_retained_text reads.
 *
 *   node tools/gen-retained-text-cases.mjs          rewrite the file
 *   node tools/gen-retained-text-cases.mjs --check  exit 1 if the file is not what this writes now
 */
import { build } from 'esbuild';
import { mkdtemp, readFile, rm, writeFile } from 'node:fs/promises';
import { tmpdir } from 'node:os';
import path from 'node:path';
import { fileURLToPath, pathToFileURL } from 'node:url';

const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
const OUT = path.join(ROOT, 'tests', 'renderer', 'data', 'retained_text_cases.txt');

const dir = await mkdtemp(path.join(tmpdir(), 'retained-text-'));
let culling;
try {
    const outfile = path.join(dir, 'text-culling.mjs');
    await build({ entryPoints: [path.join(ROOT, 'sdk', 'src', 'ui', 'text', 'text-culling.ts')], outfile, bundle: true, format: 'esm', logLevel: 'error' });
    culling = await import(pathToFileURL(outfile).href);
} finally {
    await rm(dir, { recursive: true, force: true, maxRetries: 10, retryDelay: 50 });
}

// A generator that does not change: the file is committed, and --check must be able to say it is current.
let seed = 20261027;
const rnd = () => { seed = (Math.imul(seed, 1664525) + 1013904223) >>> 0; return (seed >>> 8) / 16777216; };
const range = (lo, hi) => lo + (hi - lo) * rnd();
// Nine significant digits name one float32 exactly, which is all the file has to carry.
const f32 = (x) => Math.fround(x).toPrecision(9);

const VERTEX_FLOATS = 9;
const lines = ['# retained_text_cases v1: generated by tools/gen-retained-text-cases.mjs from sdk/src/ui/text/text-culling.ts; do not edit.'];
const CASES = 120;
for (let c = 0; c < CASES; c++) {
    // A column-major orthographic or perspective-ish view-projection, then a model that places the label.
    const view = new Float32Array(16);
    const sx = range(0.002, 0.02), sy = range(0.002, 0.02), tx = range(-1, 1), ty = range(-1, 1);
    view[0] = sx; view[5] = sy; view[10] = range(-0.02, -0.001); view[12] = tx; view[13] = ty; view[14] = range(-1, 1); view[15] = 1;
    if (rnd() < 0.4) { view[11] = range(-0.01, 0.01); view[15] = range(0.5, 2); }
    const model = new Float32Array(16);
    const scale = range(0.3, 3);
    model[0] = scale; model[5] = scale; model[10] = 1; model[15] = 1; model[12] = range(-400, 400); model[13] = range(-400, 400); model[14] = range(-5, 5);
    if (rnd() < 0.3) { const a = range(0, 6.28); model[0] = Math.cos(a) * scale; model[1] = Math.sin(a) * scale; model[4] = -Math.sin(a) * scale; model[5] = Math.cos(a) * scale; }
    const quads = 1 + Math.floor(rnd() * (rnd() < 0.2 ? 140 : 40));
    const vertices = new Float32Array(quads * 4 * VERTEX_FLOATS);
    const indices = new Uint16Array(quads * 6);
    for (let q = 0; q < quads; q++) {
        const x = range(-250, 250), y = range(-250, 250), w = range(4, 30), h = range(4, 30);
        const corners = [[x, y], [x + w, y], [x + w, y + h], [x, y + h]];
        for (let k = 0; k < 4; k++) {
            const o = (q * 4 + k) * VERTEX_FLOATS;
            vertices[o] = corners[k][0]; vertices[o + 1] = corners[k][1];
            vertices[o + 2] = rnd(); vertices[o + 3] = rnd();
            vertices[o + 4] = 1; vertices[o + 5] = 1; vertices[o + 6] = 1; vertices[o + 7] = 1;
        }
        const b = q * 4;
        indices.set([b, b + 1, b + 2, b + 2, b + 3, b], q * 6);
    }
    const planes = new Float64Array(36);
    const ok = culling.textClipPlanes(planes, view, model);
    const geometry = culling.createTextCullGeometry(vertices, indices);
    // The quads the TS keeps: its output holds them in order, so match them back by their first vertex.
    let kept = 'all';
    if (ok) {
        const result = culling.clipTextGeometry(geometry, planes);
        if (!result) kept = 'none';
        else if (result.vertices.length === vertices.length) kept = 'all';
        else {
            const list = [];
            for (let q = 0; q < quads; q++) if (geometry.visible[q]) list.push(q);
            kept = list.join(',');
        }
    }
    lines.push(`case ${quads} ${ok ? 1 : 0}`);
    lines.push(`view ${[...view].map((v) => f32(v)).join(' ')}`);
    lines.push(`model ${[...model].map((v) => f32(v)).join(' ')}`);
    // Only the corners a quad's bounds come from carry its shape; the engine reads x,y of vertices 0 and 2, so all four go in.
    const xy = [];
    for (let v = 0; v < quads * 4; v++) xy.push(f32(vertices[v * VERTEX_FLOATS]), f32(vertices[v * VERTEX_FLOATS + 1]));
    lines.push(`xy ${xy.join(' ')}`);
    lines.push(`kept ${kept}`);
}
const text = lines.join('\n') + '\n';

if (process.argv.includes('--check')) {
    const current = await readFile(OUT, 'utf8').catch(() => '');
    if (current.replace(/\r\n/g, '\n') !== text) {
        console.error('tests/renderer/data/retained_text_cases.txt is not what the TS text culling gives now; run: node tools/gen-retained-text-cases.mjs');
        process.exit(1);
    }
    console.log(`retained text cases current (${CASES} cases).`);
} else {
    await writeFile(OUT, text, 'utf8');
    console.log(`wrote ${path.relative(ROOT, OUT)}: ${CASES} cases`);
}