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.

perf(text): cull cached glyph geometry per draw projection

yhh59a3a2c08916
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 31972ebaa..af5c661d3 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -28,6 +28,8 @@ published separately; it ships inside the editor.
- **AudioPlugin checks platform initialization before subscribing to host mute.** Independent audio backend tests and direct construction no longer fail while reading an optional platform capability.
+- **SDK text uploads only glyphs visible to the current draw pass.** Bitmap and SDF caches retain the complete layout while block bounds reject camera-excluded runs and partial runs compact vertices with rebased indices. Culling uses the actual camera or screen-overlay projection with the full model matrix, preserving shear, shadows and clip-edge intersections; invalid or omitted projections retain the legacy submission path.
+
- **Text measurement avoids GPU glyph pages.** Input caret measurements and inline rich-text layout retain the same rasterized glyph advances, bearings and dimensions in CPU caches without packing or uploading textures. Ordinary text drawing keeps its existing atlas; measurement-only atlases reject draw submission instead of emitting invalid texture references.
- **Inline rich text releases its own measurement atlas.** Cleanup belongs to each App, so closing an older preview cannot remove a newer preview's inline image children. Exiting releases measurement glyph pages and repeated cleanup remains safe.
diff --git a/sdk/etc/index.api.md b/sdk/etc/index.api.md
index 5ea152cf1..321fe794d 100644
--- a/sdk/etc/index.api.md
+++ b/sdk/etc/index.api.md
@@ -6896,8 +6896,8 @@ width: number
## RenderPipeline — class @experimental
```
-addPreFlushCallback: (cb: (registry: { _cpp: CppRegistry; }) => void) => void
-addScreenOverlayCallback: (cb: (registry: { _cpp: CppRegistry; }) => void) => void
+addPreFlushCallback: (cb: (registry: { _cpp: CppRegistry; }, viewProjection?: Float32Array) => void) => void
+addScreenOverlayCallback: (cb: (registry: { _cpp: CppRegistry; }, viewProjection?: Float32Array) => void) => void
beginFrame: (elapsedSec?: number) => void
beginScreenCapture: () => void
endFrame: () => void
@@ -6907,7 +6907,7 @@ render: (params: RenderParams) => void
renderCamera: (params: CameraRenderParams) => void
renderScreenOverlay: (registry: { _cpp: CppRegistry; }, overlay: ScreenOverlayData, target?: number) => void
renderingEnabled: boolean
-runPreFlushCallbacks: (registry: { _cpp: CppRegistry; }) => void
+runPreFlushCallbacks: (registry: { _cpp: CppRegistry; }, viewProjection?: Float32Array) => void
setActiveScenes: (scenes: Set<string> | null) => void
setPostProcess: (pp: PostProcessAPI | null) => void
setQuality: (quality: QualityController, apply?: () => void) => void
diff --git a/sdk/etc/index.native.api.md b/sdk/etc/index.native.api.md
index c8456b0ae..5fa7ca8ba 100644
--- a/sdk/etc/index.native.api.md
+++ b/sdk/etc/index.native.api.md
@@ -7109,8 +7109,8 @@ width: number
## RenderPipeline — class @experimental
```
-addPreFlushCallback: (cb: (registry: { _cpp: CppRegistry; }) => void) => void
-addScreenOverlayCallback: (cb: (registry: { _cpp: CppRegistry; }) => void) => void
+addPreFlushCallback: (cb: (registry: { _cpp: CppRegistry; }, viewProjection?: Float32Array) => void) => void
+addScreenOverlayCallback: (cb: (registry: { _cpp: CppRegistry; }, viewProjection?: Float32Array) => void) => void
beginFrame: (elapsedSec?: number) => void
beginScreenCapture: () => void
endFrame: () => void
@@ -7120,7 +7120,7 @@ render: (params: RenderParams) => void
renderCamera: (params: CameraRenderParams) => void
renderScreenOverlay: (registry: { _cpp: CppRegistry; }, overlay: ScreenOverlayData, target?: number) => void
renderingEnabled: boolean
-runPreFlushCallbacks: (registry: { _cpp: CppRegistry; }) => void
+runPreFlushCallbacks: (registry: { _cpp: CppRegistry; }, viewProjection?: Float32Array) => void
setActiveScenes: (scenes: Set<string> | null) => void
setPostProcess: (pp: PostProcessAPI | null) => void
setQuality: (quality: QualityController, apply?: () => void) => void
diff --git a/sdk/etc/index.node.api.md b/sdk/etc/index.node.api.md
index ca795fef1..2c6e4656d 100644
--- a/sdk/etc/index.node.api.md
+++ b/sdk/etc/index.node.api.md
@@ -6891,8 +6891,8 @@ width: number
## RenderPipeline — class @experimental
```
-addPreFlushCallback: (cb: (registry: { _cpp: CppRegistry; }) => void) => void
-addScreenOverlayCallback: (cb: (registry: { _cpp: CppRegistry; }) => void) => void
+addPreFlushCallback: (cb: (registry: { _cpp: CppRegistry; }, viewProjection?: Float32Array) => void) => void
+addScreenOverlayCallback: (cb: (registry: { _cpp: CppRegistry; }, viewProjection?: Float32Array) => void) => void
beginFrame: (elapsedSec?: number) => void
beginScreenCapture: () => void
endFrame: () => void
@@ -6902,7 +6902,7 @@ render: (params: RenderParams) => void
renderCamera: (params: CameraRenderParams) => void
renderScreenOverlay: (registry: { _cpp: CppRegistry; }, overlay: ScreenOverlayData, target?: number) => void
renderingEnabled: boolean
-runPreFlushCallbacks: (registry: { _cpp: CppRegistry; }) => void
+runPreFlushCallbacks: (registry: { _cpp: CppRegistry; }, viewProjection?: Float32Array) => void
setActiveScenes: (scenes: Set<string> | null) => void
setPostProcess: (pp: PostProcessAPI | null) => void
setQuality: (quality: QualityController, apply?: () => void) => void
diff --git a/sdk/etc/minigame.api.md b/sdk/etc/minigame.api.md
index 3f266ad47..902b7604a 100644
--- a/sdk/etc/minigame.api.md
+++ b/sdk/etc/minigame.api.md
@@ -7184,8 +7184,8 @@ width: number
## RenderPipeline — class @experimental
```
-addPreFlushCallback: (cb: (registry: { _cpp: CppRegistry; }) => void) => void
-addScreenOverlayCallback: (cb: (registry: { _cpp: CppRegistry; }) => void) => void
+addPreFlushCallback: (cb: (registry: { _cpp: CppRegistry; }, viewProjection?: Float32Array) => void) => void
+addScreenOverlayCallback: (cb: (registry: { _cpp: CppRegistry; }, viewProjection?: Float32Array) => void) => void
beginFrame: (elapsedSec?: number) => void
beginScreenCapture: () => void
endFrame: () => void
@@ -7195,7 +7195,7 @@ render: (params: RenderParams) => void
renderCamera: (params: CameraRenderParams) => void
renderScreenOverlay: (registry: { _cpp: CppRegistry; }, overlay: ScreenOverlayData, target?: number) => void
renderingEnabled: boolean
-runPreFlushCallbacks: (registry: { _cpp: CppRegistry; }) => void
+runPreFlushCallbacks: (registry: { _cpp: CppRegistry; }, viewProjection?: Float32Array) => void
setActiveScenes: (scenes: Set<string> | null) => void
setPostProcess: (pp: PostProcessAPI | null) => void
setQuality: (quality: QualityController, apply?: () => void) => void
diff --git a/sdk/etc/wechat.api.md b/sdk/etc/wechat.api.md
index 8627c5b3c..c1bf1638c 100644
--- a/sdk/etc/wechat.api.md
+++ b/sdk/etc/wechat.api.md
@@ -6898,8 +6898,8 @@ width: number
## RenderPipeline — class @experimental
```
-addPreFlushCallback: (cb: (registry: { _cpp: CppRegistry; }) => void) => void
-addScreenOverlayCallback: (cb: (registry: { _cpp: CppRegistry; }) => void) => void
+addPreFlushCallback: (cb: (registry: { _cpp: CppRegistry; }, viewProjection?: Float32Array) => void) => void
+addScreenOverlayCallback: (cb: (registry: { _cpp: CppRegistry; }, viewProjection?: Float32Array) => void) => void
beginFrame: (elapsedSec?: number) => void
beginScreenCapture: () => void
endFrame: () => void
@@ -6909,7 +6909,7 @@ render: (params: RenderParams) => void
renderCamera: (params: CameraRenderParams) => void
renderScreenOverlay: (registry: { _cpp: CppRegistry; }, overlay: ScreenOverlayData, target?: number) => void
renderingEnabled: boolean
-runPreFlushCallbacks: (registry: { _cpp: CppRegistry; }) => void
+runPreFlushCallbacks: (registry: { _cpp: CppRegistry; }, viewProjection?: Float32Array) => void
setActiveScenes: (scenes: Set<string> | null) => void
setPostProcess: (pp: PostProcessAPI | null) => void
setQuality: (quality: QualityController, apply?: () => void) => void
diff --git a/sdk/src/render/renderPipeline.ts b/sdk/src/render/renderPipeline.ts
index 50f8537d0..2cd3090e2 100644
--- a/sdk/src/render/renderPipeline.ts
+++ b/sdk/src/render/renderPipeline.ts
@@ -70,8 +70,8 @@ export class RenderPipeline {
private lastWidth_ = 0;
private lastHeight_ = 0;
private activeScenes_: Set<string> | null = null;
- private preFlushCallbacks_: ((registry: { _cpp: CppRegistry }) => void)[] = [];
- private screenOverlayCallbacks_: ((registry: { _cpp: CppRegistry }) => void)[] = [];
+ private preFlushCallbacks_: ((registry: { _cpp: CppRegistry }, viewProjection?: Float32Array) => void)[] = [];
+ private screenOverlayCallbacks_: ((registry: { _cpp: CppRegistry }, viewProjection?: Float32Array) => void)[] = [];
private postProcess_: PostProcessAPI | null = null;
private quality_: QualityController | null = null;
private applyQuality_: (() => void) | null = null;
@@ -101,7 +101,8 @@ export class RenderPipeline {
this.postProcess_ = pp;
}
- addPreFlushCallback(cb: (registry: { _cpp: CppRegistry }) => void): void {
+ /** The optional projection is the current pass; legacy manual hosts may omit it. */
+ addPreFlushCallback(cb: (registry: { _cpp: CppRegistry }, viewProjection?: Float32Array) => void): void {
this.preFlushCallbacks_.push(cb);
}
@@ -111,7 +112,7 @@ export class RenderPipeline {
* reason the two collects are: a callback that ran in both would put the same
* glyph in each list. Runs between the overlay's collect and its pass.
*/
- addScreenOverlayCallback(cb: (registry: { _cpp: CppRegistry }) => void): void {
+ addScreenOverlayCallback(cb: (registry: { _cpp: CppRegistry }, viewProjection?: Float32Array) => void): void {
this.screenOverlayCallbacks_.push(cb);
}
@@ -122,8 +123,8 @@ export class RenderPipeline {
* it directly at the same point, between collecting the scene and flushing,
* so text lands in the same frame either way.
*/
- runPreFlushCallbacks(registry: { _cpp: CppRegistry }): void {
- for (const cb of this.preFlushCallbacks_) cb(registry);
+ runPreFlushCallbacks(registry: { _cpp: CppRegistry }, viewProjection?: Float32Array): void {
+ for (const cb of this.preFlushCallbacks_) cb(registry, viewProjection);
}
beginFrame(elapsedSec = 0): void {
@@ -165,7 +166,7 @@ export class RenderPipeline {
// exactly as a camera's own mask is.
Renderer.setCullingMask(overlay.layerMask);
Renderer.submitScreenOverlay(registry);
- for (const cb of this.screenOverlayCallbacks_) cb(registry);
+ for (const cb of this.screenOverlayCallbacks_) cb(registry, overlay.projection);
Renderer.endScreenOverlay(target);
}
@@ -200,7 +201,7 @@ export class RenderPipeline {
Renderer.updateTransforms(registry);
Renderer.submitAll(registry, viewport.x, viewport.y, viewport.w, viewport.h);
- this.runPreFlushCallbacks(registry);
+ this.runPreFlushCallbacks(registry, viewProjection);
Renderer.flush();
this.executeDrawCallbacks(viewProjection, viewport, _elapsed);
diff --git a/sdk/src/ui/text/plugin.ts b/sdk/src/ui/text/plugin.ts
index fb9f8c4d4..83e48532d 100644
--- a/sdk/src/ui/text/plugin.ts
+++ b/sdk/src/ui/text/plugin.ts
@@ -149,8 +149,8 @@ export class TextPlugin implements Plugin {
// Two passes, because there are two lists: the world's glyphs go into the
// camera being collected, the screen's into the frame's overlay.
- pipeline.addPreFlushCallback(() => this.drawDomain(app, /*screen=*/false));
- pipeline.addScreenOverlayCallback(() => this.drawDomain(app, /*screen=*/true));
+ pipeline.addPreFlushCallback((_registry, projection) => this.drawDomain(app, /*screen=*/false, projection));
+ pipeline.addScreenOverlayCallback((_registry, projection) => this.drawDomain(app, /*screen=*/true, projection));
}
/**
@@ -160,11 +160,11 @@ export class TextPlugin implements Plugin {
* a UI subtree's root and inherited (UISystem::screenDomain), and a second
* spelling of that rule in TS is a second rule.
*/
- private drawDomain(app: App, screen: boolean): void {
+ private drawDomain(app: App, screen: boolean, projection?: Float32Array): void {
const appState = this.stateFor(app);
const api = engineApi(app);
if (!api?.transform_copyFlatRenderMatrix || !api.HEAPU8 || !api._malloc || !api._free) {
- this.drawDomainWithMatrix(app, screen);
+ this.drawDomainWithMatrix(app, screen, undefined, projection);
return;
}
const registry = app.world.getCppRegistry() as CppRegistry;
@@ -179,11 +179,11 @@ export class TextPlugin implements Plugin {
const offset = (heap.byteOffset + pointer) / 4;
for (let i = 0; i < 16; i++) appState.matrix[i] = appState.matrixHeap[offset + i]!;
return true;
- });
+ }, projection);
});
}
- private drawDomainWithMatrix(app: App, screen: boolean, readMatrix?: (entity: number) => boolean): void {
+ private drawDomainWithMatrix(app: App, screen: boolean, readMatrix?: (entity: number) => boolean, projection?: Float32Array): void {
const appState = this.stateFor(app);
const world = app.world;
const registry = world.getCppRegistry() as CppRegistry;
@@ -304,6 +304,7 @@ export class TextPlugin implements Plugin {
// and a z left on a screen root would otherwise outrank a sibling.
screen ? 0 : tr.worldPosition.z,
api?.ui_getCullBit?.(registry, entity as number) ?? 0,
+ projection,
);
}
diff --git a/sdk/src/ui/text/text-culling.ts b/sdk/src/ui/text/text-culling.ts
new file mode 100644
index 000000000..415e0e330
--- /dev/null
+++ b/sdk/src/ui/text/text-culling.ts
@@ -0,0 +1,117 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+import { TEXT_VERTEX_FLOATS } from './submit';
+
+const QUAD_FLOATS = 4 * TEXT_VERTEX_FLOATS;
+const BLOCK_QUADS = 64;
+const ROUNDING_MARGIN = 8 * 2 ** -23;
+
+export interface TextCullGeometry {
+ vertices: Float32Array;
+ indices: Uint16Array;
+ blocks: Float32Array;
+ visible: Uint8Array;
+ blockVisibility: Uint8Array;
+ clippedVertices?: Float32Array;
+ clippedIndices?: Uint16Array;
+}
+
+export function createTextCullGeometry(vertices: Float32Array, indices: Uint16Array): TextCullGeometry {
+ const count = vertices.length / QUAD_FLOATS;
+ const blocks = new Float32Array(Math.ceil(count / BLOCK_QUADS) * 4);
+ for (let start = 0; start < count; start += BLOCK_QUADS) {
+ let left = Infinity, bottom = Infinity, right = -Infinity, top = -Infinity;
+ const end = Math.min(count, start + BLOCK_QUADS) * QUAD_FLOATS;
+ for (let i = start * QUAD_FLOATS; i < end; i += TEXT_VERTEX_FLOATS) {
+ left = Math.min(left, vertices[i]); right = Math.max(right, vertices[i]);
+ bottom = Math.min(bottom, vertices[i + 1]); top = Math.max(top, vertices[i + 1]);
+ }
+ blocks.set([left, bottom, right, top], start / BLOCK_QUADS * 4);
+ }
+ return { vertices, indices, blocks, visible: new Uint8Array(count), blockVisibility: new Uint8Array(blocks.length / 4) };
+}
+
+/** Clip planes on the glyph's local z=0 plane. Error weights conservatively
+ * bound float32 model/projection roundoff, including cancellation. Near uses
+ * -w, which remains conservative for both OpenGL and zero-to-one depth. */
+export function textClipPlanes(out: Float64Array, view: Float32Array, model: Float32Array): boolean {
+ if (view.length < 16 || model.length < 16) return false;
+ for (let i = 0; i < 16; i++) if (!Number.isFinite(view[i]) || !Number.isFinite(model[i])) return false;
+ for (let plane = 0; plane < 6; plane++) {
+ const row = plane >> 1, sign = plane % 2 === 0 ? 1 : -1;
+ for (let slot = 0; slot < 3; slot++) {
+ const column = slot === 2 ? 12 : slot * 4;
+ let value = 0, error = 0;
+ for (let k = 0; k < 4; k++) {
+ const a = view[k * 4 + 3], b = view[k * 4 + row];
+ value += (a + sign * b) * model[column + k];
+ error += (Math.abs(a) + Math.abs(b)) * Math.abs(model[column + k]);
+ }
+ out[plane * 6 + slot] = value;
+ out[plane * 6 + slot + 3] = error * ROUNDING_MARGIN;
+ }
+ }
+ return true;
+}
+
+// 0 outside; 1 inside; 2 crossing a clip plane. Non-finite bounds stay visible.
+function classify(planes: Float64Array, left: number, bottom: number, right: number, top: number): number {
+ if (!Number.isFinite(left) || !Number.isFinite(bottom) || !Number.isFinite(right) || !Number.isFinite(top)) return 1;
+ let inside = true;
+ const x = Math.max(Math.abs(left), Math.abs(right)), y = Math.max(Math.abs(bottom), Math.abs(top));
+ for (let p = 0; p < 36; p += 6) {
+ const a = planes[p], b = planes[p + 1], c = planes[p + 2];
+ const margin = planes[p + 3] * x + planes[p + 4] * y + planes[p + 5];
+ const lo = a * (a >= 0 ? left : right) + b * (b >= 0 ? bottom : top) + c;
+ const hi = a * (a >= 0 ? right : left) + b * (b >= 0 ? top : bottom) + c;
+ if (hi < -margin) return 0;
+ if (lo < margin) inside = false;
+ }
+ return inside ? 1 : 2;
+}
+
+/** Preserve the full cache, copying only visible quads into reusable buffers. */
+export function clipTextGeometry(geometry: TextCullGeometry, planes: Float64Array | null):
+ { vertices: Float32Array; indices: Uint16Array } | null {
+ if (!planes) return geometry;
+ const count = geometry.vertices.length / QUAD_FLOATS;
+ let visibleCount = 0;
+ for (let start = 0; start < count; start += BLOCK_QUADS) {
+ const block = start / BLOCK_QUADS * 4;
+ const end = Math.min(count, start + BLOCK_QUADS);
+ const status = classify(planes, geometry.blocks[block], geometry.blocks[block + 1], geometry.blocks[block + 2], geometry.blocks[block + 3]);
+ geometry.blockVisibility[start / BLOCK_QUADS] = status;
+ if (status !== 2) {
+ geometry.visible.fill(status, start, end);
+ if (status === 1) visibleCount += end - start;
+ continue;
+ }
+ for (let quad = start; quad < end; quad++) {
+ const offset = quad * QUAD_FLOATS;
+ const x0 = geometry.vertices[offset], y0 = geometry.vertices[offset + 1];
+ const x1 = geometry.vertices[offset + 2 * TEXT_VERTEX_FLOATS], y1 = geometry.vertices[offset + 2 * TEXT_VERTEX_FLOATS + 1];
+ const survives = classify(planes, Math.min(x0, x1), Math.min(y0, y1), Math.max(x0, x1), Math.max(y0, y1)) !== 0;
+ geometry.visible[quad] = survives ? 1 : 0;
+ if (survives) visibleCount++;
+ }
+ }
+ if (visibleCount === 0) return null;
+ if (visibleCount === count) return geometry;
+ const floats = visibleCount * QUAD_FLOATS, indexCount = visibleCount * 6;
+ if (!geometry.clippedVertices || geometry.clippedVertices.length < floats) geometry.clippedVertices = new Float32Array(floats);
+ if (!geometry.clippedIndices || geometry.clippedIndices.length < indexCount) geometry.clippedIndices = new Uint16Array(indexCount);
+ let output = 0;
+ for (let start = 0; start < count; start += BLOCK_QUADS) {
+ if (geometry.blockVisibility[start / BLOCK_QUADS] === 0) continue;
+ const end = Math.min(count, start + BLOCK_QUADS);
+ for (let quad = start; quad < end; quad++) {
+ if (!geometry.visible[quad]) continue;
+ const source = quad * QUAD_FLOATS, target = output * QUAD_FLOATS;
+ for (let i = 0; i < QUAD_FLOATS; i++) geometry.clippedVertices[target + i] = geometry.vertices[source + i];
+ const base = output * 4, sourceBase = quad * 4;
+ for (let i = 0; i < 6; i++) geometry.clippedIndices[output * 6 + i] = geometry.indices[quad * 6 + i] - sourceBase + base;
+ output++;
+ }
+ }
+ return { vertices: geometry.clippedVertices.subarray(0, floats), indices: geometry.clippedIndices.subarray(0, indexCount) };
+}
diff --git a/sdk/src/ui/text/text-renderer.ts b/sdk/src/ui/text/text-renderer.ts
index 3cdef389c..9b343e1c3 100644
--- a/sdk/src/ui/text/text-renderer.ts
+++ b/sdk/src/ui/text/text-renderer.ts
@@ -10,6 +10,7 @@
* pages requires). `TextRenderer` wires it to the real Canvas2D rasterizer +
* engine page store + submitTextBatch.
*/
+import { createTextCullGeometry, textClipPlanes, clipTextGeometry, type TextCullGeometry } from './text-culling';
import type { ESEngineModule } from '../../wasm';
import { platformHasGlyphRasterizer } from '../../platform';
import { GlyphAtlas } from './glyph-atlas';
@@ -269,7 +270,7 @@ export interface TextRendererOptions extends CanvasGlyphRasterizerOptions {
}
/** One laid-out, tessellated page batch in the entity's local (untransformed) space. */
-interface CachedTextBatch {
+interface CachedTextBatch extends TextCullGeometry {
vertices: Float32Array;
indices: Uint16Array;
pageId: number;
@@ -289,6 +290,7 @@ export class SdfTextRenderer {
readonly atlas: GlyphAtlas;
private readonly sdf: boolean;
private readonly cache_ = new Map<number, TextCacheEntry>();
+ private readonly clipPlanes_ = new Float64Array(36);
/** `module` is null on the native core (no wasm heap); the glyph source is
* then the platform's own rasterizer, since there is no 2D canvas to draw
@@ -332,6 +334,7 @@ export class SdfTextRenderer {
layer: number,
depth: number,
cullBit = 0,
+ viewProjection?: Float32Array,
): void {
if (this.atlas.metricsOnly) throw new Error('Measurement atlases cannot submit text.');
const opacity = p.opacity ?? 1;
@@ -342,11 +345,12 @@ export class SdfTextRenderer {
if (!entry || entry.gen !== gen || entry.sig !== sig) {
const batches: CachedTextBatch[] = [];
drawTextWith(this.atlas, (vertices, indices, pageId) => {
- batches.push({ vertices, indices, pageId });
+ batches.push({ ...createTextCullGeometry(vertices, indices), pageId });
}, { ...p, opacity: 1 });
entry = { sig, gen, batches, opacity: 1 };
this.cache_.set(entity, entry);
}
+ const planes = viewProjection && textClipPlanes(this.clipPlanes_, viewProjection, transform) ? this.clipPlanes_ : null;
for (const b of entry.batches) {
if (entry.opacity !== opacity) {
if (!b.alphas) {
@@ -357,7 +361,8 @@ export class SdfTextRenderer {
b.vertices[i * TEXT_VERTEX_FLOATS + 7] = b.alphas[i] * opacity;
}
}
- submitTextBatch(this.module, b.vertices, b.indices, b.pageId, transform, entity, layer, depth, this.sdf, cullBit);
+ const visible = clipTextGeometry(b, planes);
+ if (visible) submitTextBatch(this.module, visible.vertices, visible.indices, b.pageId, transform, entity, layer, depth, this.sdf, cullBit);
}
entry.opacity = opacity;
}
diff --git a/sdk/tests/native-text.test.ts b/sdk/tests/native-text.test.ts
index f1b163e16..a71844978 100644
--- a/sdk/tests/native-text.test.ts
+++ b/sdk/tests/native-text.test.ts
@@ -178,6 +178,39 @@ function buildScene(app: ReturnType<typeof createNativeApp>, setScene: (canvas:
}
describe('a frame on the native core', () => {
+ it.each([true, false])('culls long cached glyphs and restores the complete layout (sdf=%s)', async sdf => {
+ const host = makeHostScope();
+ const app = createNativeApp(makeBridge(host.scope), host.scope);
+ await app.tick(0);
+ const renderer = new SdfTextRenderer(null, { sdf });
+ const parameters = { text: 'A'.repeat(65535) + 'Z', fontFamily: 'Arial', fontSizePx: 32, color: [1, 1, 1, 1] as const };
+ const matrix = new Float32Array([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]);
+ const projection = matrix.slice(); projection[0] = 1 / 32; projection[5] = 1 / 64;
+ renderer.drawText(parameters, matrix, 1, 0, 0, 0, projection);
+ expect(host.submitSpy).toHaveBeenCalledOnce();
+ expect(host.submitSpy.mock.calls[0][1]).toBeLessThanOrEqual(20);
+ const rasterizations = host.rasterizeSpy.mock.calls.length;
+ host.submitSpy.mockClear(); matrix[12] = 1e7;
+ renderer.drawText(parameters, matrix, 1, 0, 0, 0, projection);
+ expect(host.submitSpy).not.toHaveBeenCalled();
+ matrix[12] = -65535 * 16;
+ renderer.drawText({ ...parameters, opacity: 0.25 }, matrix, 1, 0, 0, 0, projection);
+ expect(host.submitSpy).toHaveBeenCalledOnce();
+ const tail = host.submitSpy.mock.calls[0];
+ expect(tail[1]).toBeLessThanOrEqual(20);
+ const vertices = tail[0] as Float32Array, indices = tail[2] as Uint16Array;
+ expect(vertices[vertices.length - 4 * TEXT_VERTEX_FLOATS]).toBe(65535 * 16);
+ expect(vertices[7]).toBe(0.25);
+ expect(Math.max(...indices)).toBeLessThan(tail[1] as number);
+ host.submitSpy.mockClear(); matrix[12] = 0; projection[0] = 1 / (65536 * 16);
+ renderer.drawText(parameters, matrix, 1, 0, 0, 0, projection);
+ expect(host.submitSpy.mock.calls.reduce((sum, args) => sum + (args[1] as number), 0)).toBe(65536 * 4);
+ expect(host.submitSpy.mock.calls.reduce((sum, args) => sum + (args[2] as Uint16Array).length, 0)).toBe(65536 * 6);
+ expect((host.submitSpy.mock.calls[0][0] as Float32Array)[7]).toBe(1);
+ expect(host.rasterizeSpy).toHaveBeenCalledTimes(rasterizations);
+ renderer.dispose(); app.quit({ keepRenderer: true });
+ });
+
it('measures native glyphs without allocating or uploading texture pages', async () => {
const host = makeHostScope();
const app = createNativeApp(makeBridge(host.scope), host.scope);
diff --git a/sdk/tests/renderPipeline.test.ts b/sdk/tests/renderPipeline.test.ts
index f74bb89a7..20b3374f1 100644
--- a/sdk/tests/renderPipeline.test.ts
+++ b/sdk/tests/renderPipeline.test.ts
@@ -22,6 +22,10 @@ vi.mock('../src/render/renderer', () => ({
setViewId: vi.fn(),
updateTransforms: vi.fn(),
beginFrame: vi.fn(),
+ hasScreenOverlay: vi.fn().mockReturnValue(true),
+ beginScreenOverlay: vi.fn(),
+ submitScreenOverlay: vi.fn(),
+ endScreenOverlay: vi.fn(),
},
}));
@@ -74,6 +78,7 @@ import { RenderPipeline } from '../src/render/renderPipeline';
import { Renderer } from '../src/render/renderer';
import { PostProcess, type PostProcessAPI } from '../src/postprocess';
import { Draw, endPresentedDraw } from '../src/render/draw';
+import { defaultScreenOverlay } from '../src/ui/core/screen-overlay';
import { unregisterDrawCallback } from '../src/render/customDraw';
const postProcessFixture = PostProcess as unknown as PostProcessAPI;
@@ -98,6 +103,25 @@ describe('RenderPipeline', () => {
viewProjection = new Float32Array(16);
});
+ it('passes each camera projection and the independent overlay projection to glyph callbacks', () => {
+ const world = vi.fn(), screen = vi.fn();
+ pipeline.addPreFlushCallback(world);
+ pipeline.addScreenOverlayCallback(screen);
+ const second = new Float32Array(16); second[12] = 17;
+ for (const projection of [viewProjection, second]) {
+ pipeline.renderCamera({ registry, viewProjection: projection,
+ viewportPixels: { x: 0, y: 0, w: 800, h: 600 }, clearFlags: 3, elapsed: 0 });
+ }
+ expect(world.mock.calls.map(call => call[1])).toEqual([viewProjection, second]);
+ const overlay = defaultScreenOverlay();
+ overlay.active = true; overlay.vpW = 800; overlay.vpH = 600;
+ pipeline.renderScreenOverlay(registry, overlay);
+ expect(screen).toHaveBeenCalledWith(registry, overlay.projection);
+ expect(world).toHaveBeenCalledTimes(2);
+ pipeline.runPreFlushCallbacks(registry);
+ expect(world).toHaveBeenLastCalledWith(registry, undefined);
+ });
+
describe('render() call sequence', () => {
it('calls rendering methods in correct order', () => {
const callOrder: string[] = [];
diff --git a/sdk/tests/text-culling.test.ts b/sdk/tests/text-culling.test.ts
new file mode 100644
index 000000000..c8c077095
--- /dev/null
+++ b/sdk/tests/text-culling.test.ts
@@ -0,0 +1,67 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+import { expect, it } from 'vitest';
+import { createTextCullGeometry, textClipPlanes, clipTextGeometry } from '../src/ui/text/text-culling';
+import { buildGlyphVertices, type LaidGlyph } from '../src/ui/text/layout';
+import { TEXT_VERTEX_FLOATS } from '../src/ui/text/submit';
+
+const identity = () => new Float32Array([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]);
+function makeQuads(count: number) {
+ const glyphs: LaidGlyph[] = Array.from({ length: count }, (_, i) => ({
+ pageId: 1, u0: 0, v0: 0, u1: 1, v1: 1,
+ x0: i * 2, x1: i * 2 + 0.5, y0: -0.5, y1: 0.5,
+ }));
+ const buffers = buildGlyphVertices(glyphs, [0.2, 0.4, 0.6, 0.7]);
+ return createTextCullGeometry(buffers.vertices, buffers.indices);
+}
+function planes(model = identity(), view = identity()) {
+ const result = new Float64Array(36);
+ expect(textClipPlanes(result, view, model)).toBe(true);
+ return result;
+}
+
+it('compacts a visible tail across cached blocks, preserving every vertex attribute and index order', () => {
+ const geometry = makeQuads(1024);
+ const model = identity(); model[12] = -2046;
+ const visible = clipTextGeometry(geometry, planes(model))!;
+ expect(visible.vertices).toEqual(geometry.vertices.slice(-4 * TEXT_VERTEX_FLOATS));
+ expect(visible.indices).toEqual(new Uint16Array([0,1,2,0,2,3]));
+ expect(geometry.vertices.length).toBe(1024 * 4 * TEXT_VERTEX_FLOATS);
+ const scratch = geometry.clippedVertices;
+ clipTextGeometry(geometry, planes(model));
+ expect(geometry.clippedVertices).toBe(scratch);
+ model[12] = 10;
+ expect(clipTextGeometry(geometry, planes(model))).toBeNull();
+ const wide = identity(); wide[0] = 1 / 4096;
+ expect(clipTextGeometry(geometry, planes(identity(), wide))).toBe(geometry);
+});
+
+it('keeps mirrored and sheared quads, including clip-edge and near-plane intersections', () => {
+ const geometry = makeQuads(2), model = identity();
+ model[0] = -1; model[4] = 0.5; model[12] = 2;
+ const visible = clipTextGeometry(geometry, planes(model))!;
+ expect(visible.vertices).toEqual(geometry.vertices.slice(4 * TEXT_VERTEX_FLOATS));
+ const edge = identity(); edge[12] = 1;
+ expect(clipTextGeometry(makeQuads(1), planes(edge))).not.toBeNull();
+ const near = identity(); near[2] = 4; near[14] = -1.5;
+ expect(clipTextGeometry(makeQuads(1), planes(near))).not.toBeNull();
+});
+
+it('keeps float32 cancellation and invalid projections conservative', () => {
+ const model = identity(); model[12] = 1e10;
+ const view = identity(); view[12] = -1e10;
+ expect(clipTextGeometry(makeQuads(1), planes(model, view))).not.toBeNull();
+ const out = new Float64Array(36); view[0] = NaN;
+ expect(textClipPlanes(out, view, model)).toBe(false);
+ const geometry = makeQuads(1);
+ expect(clipTextGeometry(geometry, null)).toBe(geometry);
+});
+
+it('retains a quad with reversed local corners that crosses the viewport edge', () => {
+ const glyphs: LaidGlyph[] = [
+ { pageId: 1, u0: 0, v0: 0, u1: 1, v1: 1, x0: 2.5, x1: 0.5, y0: 0.5, y1: -0.5 },
+ ];
+ const buffers = buildGlyphVertices(glyphs, [1, 1, 1, 1]);
+ const geometry = createTextCullGeometry(buffers.vertices, buffers.indices);
+ expect(clipTextGeometry(geometry, planes())).toBe(geometry);
+});
diff --git a/tools/releaseNotes.mjs b/tools/releaseNotes.mjs
index a04b7200c..b0eb246b3 100644
--- a/tools/releaseNotes.mjs
+++ b/tools/releaseNotes.mjs
@@ -32,6 +32,8 @@ export const NOTED = {
{ note: 'CrazyGames scores and saved training credits follow platform contracts.' },
'feat(settings): configure CrazyGames client score encryption key':
{ note: 'CrazyGames scores and saved training credits follow platform contracts.' },
+ 'perf(text): cull cached glyph geometry per draw projection':
+ { note: 'SDK text uploads only glyphs visible to the current draw pass.' },
'perf(ui): keep text measurement atlases off GPU':
{ note: 'Text measurement avoids GPU glyph pages.' },
'feat(crazygames): connect Web ads storage and host audio policy':