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.

feat(engine): editor world-space reference grid (EditorGrid + pre-scene pass)

esengine86b167d36be6
diff --git a/sdk/src/camera/EditorGrid.ts b/sdk/src/camera/EditorGrid.ts
new file mode 100644
index 000000000..3206f2dc7
--- /dev/null
+++ b/sdk/src/camera/EditorGrid.ts
@@ -0,0 +1,49 @@
+/**
+ * @file EditorGrid.ts
+ * @brief Editor viewport reference grid — an editor-only render feature.
+ *
+ * Like EditorView, this is NOT a scene entity: never serialized, never on the
+ * undo stack, never part of a shipped game (which leaves `enabled` false and so
+ * never pays for it). The editor flips `enabled` / `spacing` from its Show-Flags
+ * and Snap controls; the grid renderer (installEditorGrid) draws an infinite
+ * world-space grid through the editor camera's view-projection in the pre-scene
+ * pass — so it pans / zooms with the view and is occluded by scene entities,
+ * exactly like a UE5 / Unity scene grid.
+ *
+ * Colors are straight-alpha RGBA in 0..1. `spacing` is the minor line spacing in
+ * world units; every `majorEvery`-th line is a heavier major line. The world
+ * x=0 / y=0 axis lines use the axis colors (red X / green Y) so the origin reads
+ * at a glance.
+ */
+import { defineResource } from '../resource';
+
+export type GridColor = [number, number, number, number];
+
+export interface EditorGridData {
+ /** When true (editor only), the grid renderer draws the grid this frame. */
+ enabled: boolean;
+ /** Minor grid line spacing, world units. */
+ spacing: number;
+ /** Every Nth line is drawn as a heavier major line. */
+ majorEvery: number;
+ /** Minor line color. */
+ color: GridColor;
+ /** Major line color. */
+ majorColor: GridColor;
+ /** World y=0 (horizontal) X-axis line color. */
+ axisX: GridColor;
+ /** World x=0 (vertical) Y-axis line color. */
+ axisY: GridColor;
+}
+
+export const DEFAULT_EDITOR_GRID: EditorGridData = {
+ enabled: false,
+ spacing: 32,
+ majorEvery: 10,
+ color: [1, 1, 1, 0.05],
+ majorColor: [1, 1, 1, 0.1],
+ axisX: [0.812, 0.357, 0.325, 0.55], // --ax-x #cf5b53
+ axisY: [0.502, 0.725, 0.29, 0.55], // --ax-y #80b94a
+};
+
+export const EditorGrid = defineResource<EditorGridData>({ ...DEFAULT_EDITOR_GRID }, 'EditorGrid');
diff --git a/sdk/src/camera/editorGridRenderer.ts b/sdk/src/camera/editorGridRenderer.ts
new file mode 100644
index 000000000..5d11383fe
--- /dev/null
+++ b/sdk/src/camera/editorGridRenderer.ts
@@ -0,0 +1,144 @@
+/**
+ * @file editorGridRenderer.ts
+ * @brief Infinite world-space editor grid, drawn through the editor camera.
+ *
+ * `installEditorGrid(app)` registers a pre-scene draw callback (see customDraw /
+ * RenderPipeline): each editor frame, when `EditorGrid.enabled` and the
+ * `EditorView` is active, it draws one full-viewport quad whose fragment shader
+ * paints minor / major / axis lines in WORLD space. Because it runs in the
+ * pre-scene pass, scene entities occlude the grid (UE5 / Unity behaviour).
+ *
+ * The quad is a unit quad scaled+translated by `u_model` to cover the camera's
+ * visible world rect (centre = EditorView.x/y, half-extent = orthoSize * aspect
+ * by orthoSize), so the fragment's interpolated world position is exact and no
+ * inverse view-projection is needed. Line width and minor-line density fade are
+ * driven by `worldPerPixel` (= 2·orthoSize / viewportHeight), so the grid stays
+ * crisp and moiré-free at every zoom without relying on GLSL derivatives.
+ *
+ * Frontends just install this once and flip the `EditorGrid` resource — the web
+ * editor and the headless render host (pixel verification) get the grid for free.
+ */
+import type { App } from '../app';
+import { Draw } from '../draw';
+import { Geometry, type GeometryHandle } from '../geometry';
+import { Material, type MaterialHandle } from '../material';
+import { BlendMode } from '../blend';
+import { registerPreSceneDrawCallback } from '../customDraw';
+import { EditorView } from './EditorView';
+import { EditorGrid, DEFAULT_EDITOR_GRID } from './EditorGrid';
+
+const GRID_VERT = `
+attribute vec2 a_position;
+uniform mat4 u_projection;
+uniform mat4 u_model;
+varying vec2 v_world;
+void main() {
+ vec4 wp = u_model * vec4(a_position, 0.0, 1.0);
+ v_world = wp.xy;
+ gl_Position = u_projection * wp;
+}
+`;
+
+const GRID_FRAG = `
+precision highp float;
+varying vec2 v_world;
+uniform float u_param0; // minor spacing (world units)
+uniform float u_param1; // major every Nth line
+uniform float u_param2; // worldPerPixel
+uniform vec4 u_color; // minor line color
+uniform vec4 u_vec0; // major line color
+uniform vec4 u_vec1; // X axis (world y=0) color
+uniform vec4 u_vec2; // Y axis (world x=0) color
+
+float lineCov(float coord, float sp, float lw, float aa) {
+ float d = abs(mod(coord + sp * 0.5, sp) - sp * 0.5);
+ return 1.0 - smoothstep(lw, lw + aa, d);
+}
+
+vec4 over(vec4 top, vec4 bot) {
+ float a = top.a + bot.a * (1.0 - top.a);
+ if (a <= 0.0) return vec4(0.0);
+ vec3 rgb = (top.rgb * top.a + bot.rgb * bot.a * (1.0 - top.a)) / a;
+ return vec4(rgb, a);
+}
+
+void main() {
+ float sp = u_param0;
+ float major = sp * u_param1;
+ float aa = u_param2; // ~1px in world units
+ float lw = aa * 0.5; // ~1px line
+
+ // Fade minor lines out as they crowd below a few pixels apart (anti-moiré).
+ float minorFade = smoothstep(3.0, 9.0, sp / max(u_param2, 1e-6));
+ float minorC = max(lineCov(v_world.x, sp, lw, aa), lineCov(v_world.y, sp, lw, aa)) * minorFade;
+ float majorC = max(lineCov(v_world.x, major, lw, aa), lineCov(v_world.y, major, lw, aa));
+ float axisXC = 1.0 - smoothstep(lw, lw + aa, abs(v_world.y)); // world y=0
+ float axisYC = 1.0 - smoothstep(lw, lw + aa, abs(v_world.x)); // world x=0
+
+ vec4 c = vec4(0.0);
+ c = over(vec4(u_color.rgb, u_color.a * minorC), c);
+ c = over(vec4(u_vec0.rgb, u_vec0.a * majorC), c);
+ c = over(vec4(u_vec1.rgb, u_vec1.a * axisXC), c);
+ c = over(vec4(u_vec2.rgb, u_vec2.a * axisYC), c);
+ if (c.a <= 0.0) discard;
+ gl_FragColor = c;
+}
+`;
+
+let quad_: GeometryHandle = 0;
+let material_: MaterialHandle = 0;
+// Reused column-major translate·scale model matrix (no per-frame allocation).
+const model_ = new Float32Array(16);
+
+function ensureResources(): boolean {
+ if (material_) return true;
+ const shader = Material.createShader(GRID_VERT, GRID_FRAG);
+ if (!shader) return false;
+ quad_ = Geometry.createQuad(2, 2); // [-1, 1] unit quad
+ material_ = Material.create({ shader, blendMode: BlendMode.Normal, depthTest: false });
+ return true;
+}
+
+// translate(tx,ty) · scale(sx,sy) as a column-major 4x4.
+function setModel(m: Float32Array, tx: number, ty: number, sx: number, sy: number): void {
+ m.fill(0);
+ m[0] = sx;
+ m[5] = sy;
+ m[10] = 1;
+ m[15] = 1;
+ m[12] = tx;
+ m[13] = ty;
+}
+
+/**
+ * Register the editor grid renderer on this App. Idempotent per App: inserts the
+ * default `EditorGrid` resource if absent and registers the pre-scene draw pass.
+ * The grid only draws when the resource is `enabled` and the `EditorView` active.
+ */
+export function installEditorGrid(app: App): void {
+ if (!app.hasResource(EditorGrid)) {
+ app.insertResource(EditorGrid, { ...DEFAULT_EDITOR_GRID });
+ }
+ registerPreSceneDrawCallback('editor:grid', ({ width, height }) => {
+ if (height <= 0 || !app.hasResource(EditorGrid) || !app.hasResource(EditorView)) return;
+ const grid = app.getResource(EditorGrid);
+ const view = app.getResource(EditorView);
+ if (!grid.enabled || !view.active || grid.spacing <= 0) return;
+ if (!ensureResources()) return;
+
+ const halfH = view.orthoSize;
+ const halfW = halfH * (width / height);
+ const worldPerPixel = (2 * halfH) / height;
+ setModel(model_, view.x, view.y, halfW, halfH);
+
+ Material.setUniform(material_, 'u_param0', grid.spacing);
+ Material.setUniform(material_, 'u_param1', grid.majorEvery);
+ Material.setUniform(material_, 'u_param2', worldPerPixel);
+ Material.setUniform(material_, 'u_color', grid.color);
+ Material.setUniform(material_, 'u_vec0', grid.majorColor);
+ Material.setUniform(material_, 'u_vec1', grid.axisX);
+ Material.setUniform(material_, 'u_vec2', grid.axisY);
+
+ Draw.drawMeshWithMaterial(quad_, material_, model_);
+ });
+}
diff --git a/sdk/src/core-render.ts b/sdk/src/core-render.ts
index bfa9292bb..b56f68c29 100644
--- a/sdk/src/core-render.ts
+++ b/sdk/src/core-render.ts
@@ -40,6 +40,9 @@ export { TextureFilter, TextureWrap, setTextureFilter, setTextureWrap, setTextur
export { CameraView, CameraViewApi } from './camera/Camera';
export { EditorView, DEFAULT_EDITOR_VIEW } from './camera/EditorView';
export type { EditorViewData } from './camera/EditorView';
+export { EditorGrid, DEFAULT_EDITOR_GRID } from './camera/EditorGrid';
+export type { EditorGridData, GridColor } from './camera/EditorGrid';
+export { installEditorGrid } from './camera/editorGridRenderer';
export { CameraDirector, setViewTarget, shakeCamera, BlendCurve } from './camera/CameraDirector';
export { FollowTarget } from './camera/FollowTarget';
export type { FollowTargetData } from './camera/FollowTarget';
@@ -159,4 +162,8 @@ export {
unregisterDrawCallback,
clearDrawCallbacks,
type DrawCallback,
+ registerPreSceneDrawCallback,
+ unregisterPreSceneDrawCallback,
+ type PreSceneDrawCallback,
+ type PreSceneDrawInfo,
} from './customDraw';
diff --git a/sdk/src/customDraw.ts b/sdk/src/customDraw.ts
index 5680fd84f..8d23c96ea 100644
--- a/sdk/src/customDraw.ts
+++ b/sdk/src/customDraw.ts
@@ -30,3 +30,37 @@ export function clearSceneDrawCallbacks(sceneName: string): void {
export function getDrawCallbacks(): ReadonlyMap<string, { fn: DrawCallback; scene: string }> {
return callbacks;
}
+
+// =============================================================================
+// Pre-scene draw callbacks
+// =============================================================================
+//
+// These run BEFORE the scene's sprites are flushed (see RenderPipeline), so what
+// they draw is occluded by scene entities — the seam an editor underlay (grid,
+// world-space guides) needs. The post-scene `DrawCallback`s above draw on top.
+// Callbacks receive the camera's pixel viewport so they can derive aspect / zoom.
+
+export interface PreSceneDrawInfo {
+ /** Camera viewport width in pixels (drives aspect). */
+ width: number;
+ /** Camera viewport height in pixels. */
+ height: number;
+ /** Seconds since app start (same clock as the post-scene callbacks). */
+ elapsed: number;
+}
+
+export type PreSceneDrawCallback = (info: PreSceneDrawInfo) => void;
+
+const preSceneCallbacks = new Map<string, PreSceneDrawCallback>();
+
+export function registerPreSceneDrawCallback(id: string, fn: PreSceneDrawCallback): void {
+ preSceneCallbacks.set(id, fn);
+}
+
+export function unregisterPreSceneDrawCallback(id: string): void {
+ preSceneCallbacks.delete(id);
+}
+
+export function getPreSceneDrawCallbacks(): ReadonlyMap<string, PreSceneDrawCallback> {
+ return preSceneCallbacks;
+}
diff --git a/sdk/src/renderPipeline.ts b/sdk/src/renderPipeline.ts
index d3b1dd404..605ad4b17 100644
--- a/sdk/src/renderPipeline.ts
+++ b/sdk/src/renderPipeline.ts
@@ -8,7 +8,12 @@ import type { Entity } from './types';
import { Renderer } from './renderer';
import type { PostProcessApi } from './postprocess';
import { Draw } from './draw';
-import { getDrawCallbacks, unregisterDrawCallback } from './customDraw';
+import {
+ getDrawCallbacks,
+ unregisterDrawCallback,
+ getPreSceneDrawCallbacks,
+ unregisterPreSceneDrawCallback,
+} from './customDraw';
import { log } from './logger';
export interface Viewport {
@@ -88,6 +93,10 @@ export class RenderPipeline {
viewport: Viewport,
_elapsed: number,
): void {
+ // Underlays (editor grid / world-space guides) draw first so the scene's
+ // sprites, flushed below, occlude them.
+ this.executePreSceneDrawCallbacks(viewProjection, viewport, _elapsed);
+
Renderer.updateTransforms(registry);
Renderer.submitAll(registry, 0, viewport.x, viewport.y, viewport.w, viewport.h);
for (const cb of this.preFlushCallbacks_) cb(registry);
@@ -141,6 +150,29 @@ export class RenderPipeline {
}
}
+ private executePreSceneDrawCallbacks(
+ viewProjection: Float32Array,
+ viewport: Viewport,
+ elapsed: number,
+ ): void {
+ const cbs = getPreSceneDrawCallbacks();
+ if (cbs.size === 0) return;
+ Draw.begin(viewProjection);
+ const failed: string[] = [];
+ for (const [id, fn] of cbs.entries()) {
+ try {
+ fn({ width: viewport.w, height: viewport.h, elapsed });
+ } catch (e) {
+ log.error('render', `pre-scene callback '${id}' error`, e);
+ failed.push(id);
+ }
+ }
+ Draw.end();
+ for (const id of failed) {
+ unregisterPreSceneDrawCallback(id);
+ }
+ }
+
private executeDrawCallbacks(viewProjection: Float32Array, elapsed: number): void {
const cbs = getDrawCallbacks();
if (cbs.size > 0) {
diff --git a/sdk/tests/editor-grid.test.ts b/sdk/tests/editor-grid.test.ts
new file mode 100644
index 000000000..a17d30d2b
--- /dev/null
+++ b/sdk/tests/editor-grid.test.ts
@@ -0,0 +1,84 @@
+/**
+ * @file editor-grid.test.ts
+ * @brief Editor reference grid: resource defaults, the pre-scene draw registry,
+ * and installEditorGrid's wiring + disabled-state no-op (no GL needed).
+ *
+ * The enabled draw path needs a live WebGL/wasm context (shader + mesh), so it is
+ * a live feel-check, not a unit test. Here we prove the resource contract, the
+ * pre-scene seam, and that the grid stays a safe no-op until enabled + active.
+ */
+import { describe, expect, it, beforeEach } from 'vitest';
+import { EditorGrid, DEFAULT_EDITOR_GRID } from '../src/camera/EditorGrid';
+import { EditorView } from '../src/camera/EditorView';
+import { installEditorGrid } from '../src/camera/editorGridRenderer';
+import {
+ registerPreSceneDrawCallback,
+ unregisterPreSceneDrawCallback,
+ getPreSceneDrawCallbacks,
+} from '../src/customDraw';
+
+// Minimal App surface installEditorGrid + the grid callback actually touch.
+function stubApp() {
+ const res = new Map<unknown, unknown>();
+ return {
+ hasResource: (d: unknown) => res.has(d),
+ insertResource: (d: unknown, v: unknown) => {
+ res.set(d, v);
+ },
+ getResource: (d: unknown) => res.get(d),
+ };
+}
+
+describe('EditorGrid resource', () => {
+ it('ships disabled with a 32-unit minor / 10× major grid', () => {
+ expect(DEFAULT_EDITOR_GRID.enabled).toBe(false);
+ expect(DEFAULT_EDITOR_GRID.spacing).toBe(32);
+ expect(DEFAULT_EDITOR_GRID.majorEvery).toBe(10);
+ expect(DEFAULT_EDITOR_GRID.color).toHaveLength(4);
+ });
+});
+
+describe('pre-scene draw registry', () => {
+ beforeEach(() => {
+ unregisterPreSceneDrawCallback('editor:grid');
+ unregisterPreSceneDrawCallback('t');
+ });
+
+ it('register / get / unregister a pre-scene callback', () => {
+ const fn = () => {
+ /* noop */
+ };
+ registerPreSceneDrawCallback('t', fn);
+ expect(getPreSceneDrawCallbacks().get('t')).toBe(fn);
+ unregisterPreSceneDrawCallback('t');
+ expect(getPreSceneDrawCallbacks().has('t')).toBe(false);
+ });
+});
+
+describe('installEditorGrid', () => {
+ beforeEach(() => {
+ unregisterPreSceneDrawCallback('editor:grid');
+ });
+
+ it('inserts the EditorGrid resource and registers the pre-scene grid pass', () => {
+ const app = stubApp();
+ installEditorGrid(app as never);
+ expect(app.hasResource(EditorGrid)).toBe(true);
+ expect(getPreSceneDrawCallbacks().has('editor:grid')).toBe(true);
+ });
+
+ it('does not overwrite an existing EditorGrid resource', () => {
+ const app = stubApp();
+ app.insertResource(EditorGrid, { ...DEFAULT_EDITOR_GRID, spacing: 64 });
+ installEditorGrid(app as never);
+ expect((app.getResource(EditorGrid) as { spacing: number }).spacing).toBe(64);
+ });
+
+ it('the grid pass is a safe no-op while disabled (touches no GL)', () => {
+ const app = stubApp();
+ app.insertResource(EditorView, { active: true, x: 0, y: 0, orthoSize: 360 });
+ installEditorGrid(app as never); // inserts EditorGrid disabled by default
+ const cb = getPreSceneDrawCallbacks().get('editor:grid')!;
+ expect(() => cb({ width: 800, height: 600, elapsed: 0 })).not.toThrow();
+ });
+});
diff --git a/sdk/tests/renderPipeline.test.ts b/sdk/tests/renderPipeline.test.ts
index ed722c12f..8800bf89c 100644
--- a/sdk/tests/renderPipeline.test.ts
+++ b/sdk/tests/renderPipeline.test.ts
@@ -51,9 +51,12 @@ vi.mock('../src/draw', () => ({
}));
const mockCallbacks = new Map<string, { fn: (elapsed: number) => void; scene: string }>();
+const mockPreSceneCallbacks = new Map<string, (info: unknown) => void>();
vi.mock('../src/customDraw', () => ({
getDrawCallbacks: vi.fn(() => mockCallbacks),
unregisterDrawCallback: vi.fn(),
+ getPreSceneDrawCallbacks: vi.fn(() => mockPreSceneCallbacks),
+ unregisterPreSceneDrawCallback: vi.fn(),
}));
import { RenderPipeline } from '../src/renderPipeline';