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.

20.6 KB
Raw Blame
// SPDX-License-Identifier: Apache-2.0
// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
/**
 * @file drawTextWith grouping, index-safe batches and effect geometry over a
 *       mock-backed GlyphAtlas, without Canvas or GL.
 */
import { describe, it, expect, vi } from 'vitest';

import { TEXT_VERTEX_FLOATS } from '../src/ui/text/submit';
import {
    GlyphAtlas, type GlyphRasterizer, type AtlasPageStore, type RasterGlyph,
} from '../src/ui/text/glyph-atlas';
import { drawTextWith, shadowTaps, signatureOf, tapAlpha } from '../src/ui/text/text-renderer';
import type { DrawTextParams } from '../src/ui/text/text-renderer';

function makeAtlas(pageSize: number, spread = 6, metricsOnly = false): GlyphAtlas {
    const rasterizer: GlyphRasterizer = {
        renderSize: 48,
        spread,
        rasterize: (cp: number): RasterGlyph | null => {
            if (cp === 32) return { pixels: new Uint8Array(0), width: 0, height: 0, advance: 12, bearingX: 0, bearingY: 0 };
            return { pixels: new Uint8Array(10 * 12 * 4), width: 10, height: 12, advance: 11, bearingX: 1, bearingY: 10 };
        },
    };
    let next = 1000;
    const store: AtlasPageStore = { createPage: () => next++, uploadSubRegion: () => {} };
    return new GlyphAtlas(rasterizer, metricsOnly ? null : store, { pageSize, padding: 1 });
}

describe('REARCH_GUI P1.3b: drawTextWith', () => {
    it('rejects measurement glyphs before emitting invalid texture references', () => {
        const sink = vi.fn();
        expect(() => drawTextWith(makeAtlas(64, 6, true), sink, {
            text: 'A', fontFamily: 'Arial', fontSizePx: 24, color: [1, 1, 1, 1],
        })).toThrow('Measurement atlases cannot submit text');
        expect(sink).not.toHaveBeenCalled();
    });

    it.each([16384, 16385, 32769])('preserves every glyph when one atlas page carries %i quads', count => {
        const batches: Array<{ vertices: Float32Array; indices: Uint16Array }> = [];
        drawTextWith(makeAtlas(1024), (vertices, indices) => batches.push({ vertices, indices }), {
            text: 'A'.repeat(count), fontFamily: 'Arial', fontSizePx: 24, color: [1, 1, 1, 1],
        });
        expect(batches).toHaveLength(Math.ceil(count / 16384));
        let emitted = 0;
        for (const { vertices, indices } of batches) {
            const glyphs = vertices.length / (4 * TEXT_VERTEX_FLOATS);
            expect(glyphs).toBeLessThanOrEqual(16384);
            expect(indices).toHaveLength(glyphs * 6);
            expect(indices[0]).toBe(0);
            expect(indices.at(-1)).toBe(glyphs * 4 - 1);
            expect(vertices[0]).toBeCloseTo(emitted * 5.5 + 0.5);
            emitted += glyphs;
        }
        expect(emitted).toBe(count);
    });

    it('keeps all shadow and outline chunks behind an oversized fill', () => {
        const sink = vi.fn();
        drawTextWith(makeAtlas(1024), sink, {
            text: 'A'.repeat(16385), fontFamily: 'Arial', fontSizePx: 24,
            color: [1, 1, 1, 0.8], opacity: 0.5,
            shadow: { color: [0, 0, 0, 0.6], dx: 2, dy: 2 },
            outline: { color: [0, 1, 0, 0.4], width: 1 },
        });
        expect(sink).toHaveBeenCalledTimes(6);
        // Shadow and outline fade with the fill's own alpha (0.8), then opacity (0.5).
        const alpha = [0.24, 0.24, 0.16, 0.16, 0.4, 0.4];
        for (let i = 0; i < 6; i++) {
            const vertices = sink.mock.calls[i][0] as Float32Array;
            const indices = sink.mock.calls[i][1] as Uint16Array;
            expect(vertices.length / TEXT_VERTEX_FLOATS).toBeLessThanOrEqual(65536);
            expect(indices.at(-1)).toBe(vertices.length / TEXT_VERTEX_FLOATS - 1);
            expect(vertices[7]).toBeCloseTo(alpha[i]);
        }
    });

    it('draws no shadow or outline for a label faded out by its colour', () => {
        const sink = vi.fn();
        drawTextWith(makeAtlas(1024), sink, {
            text: 'Hi', fontFamily: 'Arial', fontSizePx: 24, color: [1, 1, 1, 0],
            shadow: { color: [0, 0, 0, 0.6], dx: 2, dy: 2 },
            outline: { color: [0, 1, 0, 0.4], width: 1 },
        });
        for (const [vertices] of sink.mock.calls as Array<[Float32Array]>) {
            for (let i = 7; i < vertices.length; i += TEXT_VERTEX_FLOATS) expect(vertices[i]).toBe(0);
        }
    });

    it('keeps rich fill colors out of shadow and outline passes on both atlas modes', () => {
        for (const spread of [0, 6]) {
            for (const blur of [0, 2]) {
                const sink = vi.fn();
                drawTextWith(makeAtlas(1024, spread), sink, {
                    text: '<color=#ff000080>A</color>B', richText: true,
                    fontFamily: 'Arial', fontSizePx: 24, color: [1, 1, 1, 1], opacity: 0.5,
                    shadow: { color: [0, 0, 0, 0.6], dx: 2, dy: 2, blur },
                    outline: { color: [0, 1, 0, 0.4], width: 1 },
                });
                const shadows = blur > 0 ? 9 : 1;
                const outlines = spread > 0 ? 1 : 8;
                expect(sink).toHaveBeenCalledTimes(shadows + outlines + 1);
                for (let batch = 0; batch < shadows + outlines; ++batch) {
                    const vertices = sink.mock.calls[batch][0] as Float32Array;
                    const shadow = batch < shadows;
                    const alpha = shadow ? tapAlpha(0.6, shadows) * 0.5 : 0.2;
                    for (let i = 4; i < vertices.length; i += TEXT_VERTEX_FLOATS) {
                        expect(Array.from(vertices.subarray(i, i + 3))).toEqual(shadow ? [0, 0, 0] : [0, 1, 0]);
                        expect(vertices[i + 3]).toBeCloseTo(alpha);
                    }
                }
                const fill = sink.mock.calls[shadows + outlines][0] as Float32Array;
                expect(Array.from(fill.subarray(4, 7))).toEqual([1, 0, 0]);
                expect(fill[7]).toBeCloseTo(128 / 255 * 0.5);
                expect(Array.from(fill.subarray(4 * TEXT_VERTEX_FLOATS + 4, 4 * TEXT_VERTEX_FLOATS + 7))).toEqual([1, 1, 1]);
                expect(fill[4 * TEXT_VERTEX_FLOATS + 7]).toBeCloseTo(0.5);
            }
        }
    });

    it('applies inherited opacity to explicit rich colors and invalidates cached geometry', () => {
        const atlas = makeAtlas(1024);
        const sink = vi.fn();
        const params: DrawTextParams = {
            text: '<color=#ff000080>A</color>', fontFamily: 'Arial', fontSizePx: 24,
            color: [1, 1, 1, 1], richText: true, opacity: 0.5,
        };
        drawTextWith(atlas, sink, params);
        expect(sink).toHaveBeenCalledTimes(1);
        expect((sink.mock.calls[0][0] as Float32Array)[7]).toBeCloseTo(128 / 255 * 0.5);
        expect(signatureOf(params)).not.toBe(signatureOf({ ...params, opacity: 1 }));
        expect(signatureOf({ ...params, opacity: undefined })).toBe(signatureOf({ ...params, opacity: 1 }));
        sink.mockClear();
        drawTextWith(atlas, sink, { ...params, opacity: 0 });
        expect(sink).not.toHaveBeenCalled();
    });

    it('emits one batch covering all glyphs when they fit on a single page', () => {
        const atlas = makeAtlas(1024);
        const sink = vi.fn();
        drawTextWith(atlas, sink, { text: 'AB', fontFamily: 'Arial', fontSizePx: 24, color: [1, 1, 1, 1] });
        expect(sink).toHaveBeenCalledTimes(1);
        const [vertices, indices, pageId] = sink.mock.calls[0];
        expect(vertices.length).toBe(2 * 4 * TEXT_VERTEX_FLOATS);
        expect(indices.length).toBe(2 * 6);
        expect(pageId).toBe(1000);
    });

    it('groups into one batch per atlas page when glyphs span pages', () => {
        // pageSize 32 ⇒ ~4 glyphs/page; 6 distinct glyphs ⇒ 2 pages.
        const atlas = makeAtlas(32);
        const sink = vi.fn();
        drawTextWith(atlas, sink, { text: 'ABCDEF', fontFamily: 'Arial', fontSizePx: 24, color: [1, 1, 1, 1] });
        expect(atlas.pageCount).toBe(2);
        expect(sink).toHaveBeenCalledTimes(2);
        const pages = sink.mock.calls.map(c => c[2]);
        expect(new Set(pages).size).toBe(2);                       // distinct pages
        const totalVerts = sink.mock.calls.reduce((s, c) => s + c[0].length, 0);
        expect(totalVerts).toBe(6 * 4 * TEXT_VERTEX_FLOATS);                        // all 6 glyphs emitted
    });

    it('emits shadow + outline passes behind the fill (REARCH_GUI F8)', () => {
        const atlas = makeAtlas(1024);
        const sink = vi.fn();
        drawTextWith(atlas, sink, {
            text: 'AB', fontFamily: 'Arial', fontSizePx: 24, color: [1, 1, 1, 1],
            shadow: { color: [0, 0, 0, 1], dx: 2, dy: 2 },
            outline: { color: [0, 0, 0, 1], width: 1 },
        });
        // 1 shadow + 1 dilated outline + 1 fill = 3 single-page batches.
        expect(sink).toHaveBeenCalledTimes(3);
        // Shadow (first pass) is offset on x by dx; fill (last pass) is not.
        const shadowX = sink.mock.calls[0][0][0];
        const fillX = sink.mock.calls[2][0][0];
        expect(shadowX - fillX).toBeCloseTo(2, 5);
    });

    it('outlines a distance-field glyph by moving its edge, not by stamping it', () => {
        // One pass, sitting exactly on the fill, carrying a positive edge shift —
        // the glyph grown by its own distance field. Eight offset copies of a wide
        // outline stop resembling the glyph; one dilation cannot.
        const sink = vi.fn();
        drawTextWith(makeAtlas(1024), sink, {
            text: 'AB', fontFamily: 'Arial', fontSizePx: 24, color: [1, 1, 1, 1],
            outline: { color: [0, 0, 0, 1], width: 3 },
        });
        expect(sink).toHaveBeenCalledTimes(2); // outline + fill
        const [outline, , ] = sink.mock.calls[0];
        const [fill] = sink.mock.calls[1];
        expect(outline[0]).toBeCloseTo(fill[0], 5);          // not offset
        // 3px at 24px display off a 48px/6-spread atlas: 3 × (48/24) × (0.5/6).
        expect(outline[8]).toBeCloseTo(0.5, 6);
        expect(fill[8]).toBe(0);
    });

    it('outlines coverage glyphs with one pass of grown cells, not eight stamped copies', () => {
        // A bitmap atlas has no distance to move. Stamping the glyph around itself
        // drew the label eight more times, and at a game label's width (#104: 3-8px)
        // that reads as ghosts, not a ring — so each glyph is grown into a cell of its own.
        const ink = new Uint8Array(10 * 12 * 4);
        for (let i = 3; i < ink.length; i += 4) ink[i] = 255;
        const rasterizer: GlyphRasterizer = {
            renderSize: 48,
            spread: 0,
            rasterize: (): RasterGlyph =>
                ({ pixels: ink, width: 10, height: 12, advance: 11, bearingX: 1, bearingY: 10 }),
        };
        let next = 2000;
        const uploads: Array<{ w: number; h: number }> = [];
        const store: AtlasPageStore = { createPage: () => next++, uploadSubRegion: (_p, _x, _y, w, h) => { uploads.push({ w, h }); } };
        const atlas = new GlyphAtlas(rasterizer, store, { pageSize: 1024, padding: 1, sdf: false });
        const sink = vi.fn();
        drawTextWith(atlas, sink, {
            text: 'AB', fontFamily: 'Arial', fontSizePx: 24, color: [1, 1, 1, 1],
            outline: { color: [0, 0, 0, 1], width: 3 },
        });
        expect(sink).toHaveBeenCalledTimes(2); // the ring, then the fill
        const [ring, fill] = sink.mock.calls.map((c) => c[0] as Float32Array);
        // Same glyph count, each ring quad wider than its glyph by the outline on both sides.
        expect(ring.length).toBe(fill.length);
        const widthOf = (v: Float32Array) => v[TEXT_VERTEX_FLOATS] - v[0];
        expect(widthOf(ring) - widthOf(fill)).toBeGreaterThanOrEqual(2 * 3);
        // The ring was placed as cells of its own: two glyphs, and each grown once.
        expect(uploads.length).toBe(4);
    });

    it('keeps the stamp for glyphs it cannot grow', () => {
        // A quad cut from no atlas entry of this atlas (here: every glyph comes from
        // an atlas whose outlined() answers null) still gets an outline.
        const rasterizer: GlyphRasterizer = {
            renderSize: 48,
            spread: 0,
            rasterize: (): RasterGlyph =>
                ({ pixels: new Uint8Array(10 * 12 * 4), width: 10, height: 12, advance: 11, bearingX: 1, bearingY: 10 }),
        };
        let next = 2000;
        const store: AtlasPageStore = { createPage: () => next++, uploadSubRegion: () => {} };
        const atlas = new GlyphAtlas(rasterizer, store, { pageSize: 1024, padding: 1, sdf: false });
        atlas.outlined = () => null;
        const sink = vi.fn();
        drawTextWith(atlas, sink, {
            text: 'AB', fontFamily: 'Arial', fontSizePx: 24, color: [1, 1, 1, 1],
            outline: { color: [0, 0, 0, 1], width: 1 },
        });
        expect(sink).toHaveBeenCalledTimes(9); // 8 directions + fill
    });

    // One ring of eight is a blur of a few pixels. A title set large with a blur of eighteen drew its nine copies fourteen pixels
    // apart: the label over and over, in blocks, where a soft shadow was asked for.
    it('draws a wide blur as enough copies that none stands apart from the rest', () => {
        const small = shadowTaps(3, 24);
        expect(small.length).toBe(9);
        const wide = shadowTaps(18, 84);
        expect(wide.length).toBeGreaterThan(9);
        expect(wide.length).toBeLessThanOrEqual(64);
        // All within the blur, and each within a stroke's thickness of another.
        const stroke = 84 * 0.07 * 1.6;
        for (const [x, y] of wide) {
            expect(Math.hypot(x, y)).toBeLessThanOrEqual(18);
            const nearest = Math.min(...wide.filter((t) => t[0] !== x || t[1] !== y).map((t) => Math.hypot(t[0] - x, t[1] - y)));
            expect(nearest).toBeLessThanOrEqual(stroke);
        }
        // However wide the blur and small the type, the copies are counted: each is the whole label again.
        expect(shadowTaps(60, 12).length).toBeLessThanOrEqual(64);
    });

    it('spreads a blurred shadow into a ring, still behind the fill', () => {
        const atlas = makeAtlas(1024);
        const sink = vi.fn();
        drawTextWith(atlas, sink, {
            text: 'AB', fontFamily: 'Arial', fontSizePx: 24, color: [1, 1, 1, 1],
            shadow: { color: [0, 0, 0, 0.5], dx: 0, dy: 4, blur: 3 },
        });
        // 9 shadow taps + 1 fill.
        expect(sink).toHaveBeenCalledTimes(10);
        // Every tap sits within the blur radius of the offset, and none of them
        // is the full-strength colour — that is what stops a blurred shadow from
        // reading as several stamps of the text.
        const fillX = sink.mock.calls[9][0][0];
        for (let i = 0; i < 9; i++) {
            const verts = sink.mock.calls[i][0];
            expect(Math.abs(verts[0] - fillX)).toBeLessThanOrEqual(3.0001);
            expect(verts[7]).toBeLessThan(0.5); // per-tap alpha
        }
    });

    it('composites the ring back to the requested shadow alpha', () => {
        // Nine layers of a/9 would land at 1-(1-a/9)^9, well under a.
        expect(1 - Math.pow(1 - tapAlpha(0.5, 9), 9)).toBeCloseTo(0.5, 6);
        expect(1 - Math.pow(1 - tapAlpha(0.37, 9), 9)).toBeCloseTo(0.37, 6);
        expect(tapAlpha(0.5, 1)).toBe(0.5);
    });

    it('a blur with no offset is a halo, not a skipped shadow', () => {
        const atlas = makeAtlas(1024);
        const sink = vi.fn();
        drawTextWith(atlas, sink, {
            text: 'AB', fontFamily: 'Arial', fontSizePx: 24, color: [1, 1, 1, 1],
            shadow: { color: [0, 0, 0, 1], dx: 0, dy: 0, blur: 2 },
        });
        expect(sink).toHaveBeenCalledTimes(10);
    });

    it('skips shadow/outline passes when transparent or zero-width', () => {
        const atlas = makeAtlas(1024);
        const sink = vi.fn();
        drawTextWith(atlas, sink, {
            text: 'AB', fontFamily: 'Arial', fontSizePx: 24, color: [1, 1, 1, 1],
            shadow: { color: [0, 0, 0, 0], dx: 2, dy: 2 }, // transparent → skip
            outline: { color: [0, 0, 0, 1], width: 0 },    // zero width → skip
        });
        expect(sink).toHaveBeenCalledTimes(1); // fill only
    });

    it('emits nothing for empty / whitespace-only text', () => {
        const atlas = makeAtlas(1024);
        const sink = vi.fn();
        drawTextWith(atlas, sink, { text: '', fontFamily: 'Arial', fontSizePx: 24, color: [1, 1, 1, 1] });
        drawTextWith(atlas, sink, { text: '   ', fontFamily: 'Arial', fontSizePx: 24, color: [1, 1, 1, 1] });
        expect(sink).not.toHaveBeenCalled();
    });

    // The first vertex x/y of the fill (last) pass — the block's anchor moves it.
    const drawFirst = (extra: Record<string, unknown>): { x: number; y: number } => {
        const sink = vi.fn();
        drawTextWith(makeAtlas(1024), sink, { text: 'AB', fontFamily: 'Arial', fontSizePx: 24, color: [1, 1, 1, 1], ...extra });
        const verts = sink.mock.calls.at(-1)![0] as Float32Array;
        return { x: verts[0], y: verts[1] };
    };

    it('a boxless label anchors the block to the origin by horizontal align (no UINode box)', () => {
        // No boxWidth ⇒ world-space label: align shifts the whole block, not silently a no-op.
        const left = drawFirst({ align: 0 }).x;
        const center = drawFirst({ align: 1 }).x;
        const right = drawFirst({ align: 2 }).x;
        expect(center).toBeLessThan(left); // centered → block moved left of the origin
        expect(right).toBeLessThan(center); // right edge on the origin → moved further left
    });

    it('a boxless label anchors the block to the origin by vertical align', () => {
        const top = drawFirst({ verticalAlign: 0 }).y;
        const middle = drawFirst({ verticalAlign: 1 }).y;
        const bottom = drawFirst({ verticalAlign: 2 }).y;
        expect(middle).toBeGreaterThan(top); // y-up: middle raises the block toward the origin
        expect(bottom).toBeGreaterThan(middle);
    });

    it('centres on the em box, not on the baseline, so leading does not push text up', () => {
        // A lineHeight above 1em adds space around the line; half belongs above the
        // first baseline. Charge it all below and every centred label rides
        // (lineHeight - 1em)/2 too high — 0.1em at the 1.2 default, which is what a
        // 60px label showed as a visible 6px.
        const box = { boxHeight: 200, verticalAlign: 1, fontSizePx: 24 };
        const tight = drawFirst({ ...box, lineHeight: 24 }).y;   // 1.0em: no leading to split
        const loose = drawFirst({ ...box, lineHeight: 24 * 1.2 }).y;
        expect(loose).toBeCloseTo(tight, 5); // y-up: extra leading must not raise the block
    });

    it('horizontal align works inside a fixed box even with word-wrap off (boxWidth, no maxWidth)', () => {
        // boxWidth aligns within the box independently of maxWidth (wrap). The block was
        // previously left-anchored whenever wrap was off — align silently did nothing.
        const leftInBox = drawFirst({ align: 0, boxWidth: 400 }).x;
        const rightInBox = drawFirst({ align: 2, boxWidth: 400 }).x;
        expect(rightInBox).toBeGreaterThan(leftInBox + 100); // pushed toward the box's right edge
    });
});

describe('text cache signature completeness', () => {
    const base: DrawTextParams = {
        text: 'AB', fontFamily: 'Arial', fontSizePx: 24, color: [1, 1, 1, 1],
    };

    it('is stable for identical params (so a static label stays a cache hit)', () => {
        expect(signatureOf({ ...base })).toBe(signatureOf({ ...base }));
    });

    // Every field that changes the laid-out, colored geometry MUST change the
    // signature — otherwise a mutated label would reuse stale cached quads.
    it.each<[string, Partial<DrawTextParams>]>([
        ['text', { text: 'AC' }],
        ['fontFamily', { fontFamily: 'Times' }],
        ['fontSizePx', { fontSizePx: 25 }],
        ['style', { style: 1 }],
        ['richText', { richText: true }],
        ['align', { align: 2 }],
        ['verticalAlign', { verticalAlign: 1 }],
        ['lineHeight', { lineHeight: 30 }],
        ['letterSpacing', { letterSpacing: 2 }],
        ['maxWidth', { maxWidth: 200 }],
        ['boxWidth', { boxWidth: 400 }],
        ['boxHeight', { boxHeight: 100 }],
        ['overflow', { overflow: 2 }],
        ['originX', { originX: 5 }],
        ['originY', { originY: 5 }],
        ['color', { color: [1, 0, 0, 1] }],
        ['shadow', { shadow: { color: [0, 0, 0, 1], dx: 2, dy: 2 } }],
        // The blur changes the geometry (a ring instead of one copy), so a label
        // whose blur alone changed must not keep the cached quads.
        ['shadow blur', { shadow: { color: [0, 0, 0, 1], dx: 2, dy: 2, blur: 3 } }],
        ['outline', { outline: { color: [0, 0, 0, 1], width: 1 } }],
    ])('changes when %s changes', (_field, override) => {
        expect(signatureOf({ ...base, ...override })).not.toBe(signatureOf(base));
    });
});