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(render): material graph switches for variants, a live preview in the graph editor, and extracting a selection into a subgraph

yhh75aed52aa90a
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 5524f5ffd..ee1b572d2 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -16,7 +16,7 @@ published separately; it ships inside the editor.
### Changed
-- **Gizmos are redrawn.** The transform handles are larger and clearer: arrows have filled heads, rings dim on their far side, the scale handles are solid cubes, and the part under the cursor turns yellow while the others fall back as you drag. A chip beside the cursor reads the offset, angle or factor being applied (`X +120.0`, `Y 42.5°`, `X ×1.35`), a rotate drag fills the swept angle, a move leaves a ghost where it started and, with snapping on, ticks at each increment. The entity under the cursor is outlined faintly before you click it, and a selected entity's outline is a little heavier. A selected mesh shows corner brackets with the length of three edges and its triangle and vertex count in the readout, the Show menu can draw its wireframe and normals, and a skinned mesh or one of its bones shows the skeleton as bones with the chosen joint in yellow. A decal projector shows its box and the line it projects along, a light probe volume the grid of probes a bake would lay, a LOD group the level it is showing and the share of the screen it takes, and the Gizmo menu has a handle-size slider. A selected UI node shows its margin and padding as bands, the pinned insets of an absolutely placed node as dashed lines with their values, and a flex container's direction and the gaps between its children. The six faces of a light probe volume, reflection probe or decal projector are handles: drag one and that half of the box follows the cursor. A selected mesh is outlined along its own silhouette rather than a box, up to 80,000 triangles. The Show menu can draw wireframe on every mesh at once, and choosing a bone paints the surface it moves from blue to red, the rest left grey; convex colliders now draw with the other 3D colliders. A Hunter's attack range is drawn as a red ball, a Perceiver's sight as the cone it actually tests (a ball when its field of view is all round), and a ThirdPersonCamera's boom as a line from the point it looks at to where it ends up, with the probe swept along it as a ball at the end. A UI element drawn as 9-slice shows its picture under its Slice Border field with four guides to drag, as the texture inspector does; while the texture carries a border of its own, which the renderer prefers, it says so instead. A selected Spine or DragonBones entity shows its bones over the artwork as the 3D rigs do, laid where the runtime posed them this frame, with the entity's scale and flips applied; the Spine and DragonBones modules gained a call that lists the bone tree, so a module built before it still draws the skeleton and only the bones are absent. A selected tilemap layer reports its tile count and the size of the area its tiles cover in the viewport readout (`172 tiles · 32×17`), and on a square grid outlines that area, so an infinite layer's edge can be seen. The profiler is laid out as a module rail (Frame, CPU / GPU, Render, Counters, Memory, Systems, Spine) beside the module chosen: its timeline plots what the CPU was busy with and no longer the wait for the next frame, so a healthy window is no longer one flat block and a hitch is a tall column; clicking a column pins that frame and the strip beneath says in a sentence how far over budget it ran and where; the cost tree is a table of total, own cost and share of the frame, in columns; the toolbar is icon buttons with the live state as a pill. The frame debugger's draw list has column headers, a header per pass with its draw count, a swatch for each draw's type, a break-reason filter that starts with All, and the position of the selected draw in the capture. The sequencer's keyframes take the shape of how the curve leaves them (round smooth, diamond linear, square held, round with an arc eased) in the colour of their track, a group's row sums up the keys beneath it, each channel row shows its value at the playhead beside a swatch that is its curve's colour, the ruler marks seconds as well as frames, the playhead's flag carries the frame, the record button is red and the snap toggle says what it is; the curve view marks its grid and names the selected key's frame, value and interpolation. The sound event editor lists its variants as a table with each clip's waveform and the share of the draw its weight takes, groups its settings (playback, level and pitch, voices, space), draws volume and rate as ranges, plots the attenuation curve with the function the runtime uses, and leads its preview bar with the Trigger action. The Show menu also picks how the viewport shades meshes: as authored, as neutral clay (shape, without anyone's colours) or as flat albedo (base colour, no light); the engine takes it as per-view state, so a camera preview in the same frame keeps the authored look. A fourth shading, wireframe, draws every triangle edge on a dark surface with the hidden ones hidden; the engine's pipelines now carry a primitive topology, WebGL2 and WebGPU alike, and each mesh the editor loads keeps a line list of its distinct edges. Script graphs, material graphs and behavior trees share one node look: a header in the colour of what the node is for, an icon and a plain name with the stored id small beside it, round pins that are solid when wired and hollow when not (control pins are triangles), and wires coloured by the type they carry. A graph with no saved positions is laid out left to right when it opens and opens no smaller than half size, and an Arrange button lays any graph out again. A script graph's inputs, outputs and variables are a searchable list beside the canvas that shows how often each variable is read and written, lights the nodes that use the selected one, and lets you drag a variable onto the canvas to get or set it. The Lighting panel folds into groups with a short state beside each title, shows its warnings as a plain row with an amber edge rather than an amber box, and keeps the bake state, counts and the Bake button pinned at the bottom. The History panel draws a rule at the present, with undone steps below it. The scatter brush draws one real sample of itself to scale. The Plugins panel is a list grouped by origin, with search, beside the details of the plugin picked: its actions, declared capabilities, what it contributes and its health. The string table numbers its rows, marks a missing translation with an amber edge and totals its problems in a status bar. The Spine preview in the asset inspector uses the editor's own dropdowns and icon buttons, shows the time against the animation's length, and names the bounds drawn over it (fixed, unsaved, last scan). While a running game is inspected, the selected entity's outline carries its name, the move handles have arrowheads, and a chip beside the handle reads the position, turn or scale being applied. The Game panel says it is idle, starting or failed with an icon, and a failure shows its reason in a block that can be selected. The World panel is a short panel beside the Content Browser: a toolbar with the cell count and size, the persistent entities as a count that opens their list, and — while the game runs — what is in each residency state, the hit rate and the last demand-to-resident time; below it a table of cells with their entity count and, at runtime, state, prefetch result and demand-to-resident time, and the entities of the picked cell beside it. Picking a cell frames its entities in the viewport. The UI Widgets palette is a searchable list in groups (layout, display, input, popup, touch controls) with the Chinese name and the widget's own name on each row, instead of a grid of tiles. The UI debugger's four views are laid out alike: the Elements tree shows each element's main component and its picked element's size and components sit beside it; Text and Focus order are tables with a state dot per row and select on a click of the row; Events draws each dispatch's bubbling path as a chain from its target. Project Health's three counts filter the list, its findings are grouped by severity under folding headings, and the checks that could not run are listed with their reasons instead of in a tooltip. In the Agent panel each run's header carries a dot for how it came out (running, held, not held, stopped early, never checked), a run's steps hang on a rail with a dot each, the acceptance line is ruled off like the change set instead of boxed, and the key hints under the input show while you are typing. The Plugins panel lists the ids a plugin and another owner both claimed and who got them, filters the list to failed, awaiting-trust, incompatible or shadowed plugins, no longer offers a built-in plugin a trust withdrawal that cannot hold, and says what a plugin contributes before disabling it. A material graph can now use another graph as one node: a `.esmatsub` material subgraph has inputs (a name, a type and a default each) and one result, a graph that uses it fills the inputs by wire or by typing a number on the node, and the compiler inlines it, so one subgraph used twice makes two independent copies and saving a subgraph recompiles the shaders of the graphs that use it. New ones come from the Content Browser's New menu; the subgraph's own header says how many graphs use it. A material graph's output node takes the standard material's surface: normal, metallic, roughness, occlusion and emission ports (and an alpha port that also works on an unlit graph), with a typed number for any left unwired. Connecting any of them compiles the graph to the same lit mesh shading the built-in Model material uses — metal read from blue and roughness from green, occlusion on the ambient light only, emission added after lighting — and a graph with none of them compiles exactly as before. New nodes: Normal Map, which reads its texture as data and unpacks it the way the standard material does, and Channel, which takes one of R, G, B or A as a number; a texture node can be set to read its map as data. The output node also has a vertex offset port: a number moves each vertex along its normal, a vec2 or vec3 moves it by that displacement, so a graph can sway foliage or ripple water; the mesh's shadow bends the same way, and a Vertex bounds field on the node says how far the offset can reach so culling keeps a bent mesh that is still on screen. The offset runs on lit 3D meshes only, and its graph cannot sample textures or read the screen.
+- **Gizmos are redrawn.** The transform handles are larger and clearer: arrows have filled heads, rings dim on their far side, the scale handles are solid cubes, and the part under the cursor turns yellow while the others fall back as you drag. A chip beside the cursor reads the offset, angle or factor being applied (`X +120.0`, `Y 42.5°`, `X ×1.35`), a rotate drag fills the swept angle, a move leaves a ghost where it started and, with snapping on, ticks at each increment. The entity under the cursor is outlined faintly before you click it, and a selected entity's outline is a little heavier. A selected mesh shows corner brackets with the length of three edges and its triangle and vertex count in the readout, the Show menu can draw its wireframe and normals, and a skinned mesh or one of its bones shows the skeleton as bones with the chosen joint in yellow. A decal projector shows its box and the line it projects along, a light probe volume the grid of probes a bake would lay, a LOD group the level it is showing and the share of the screen it takes, and the Gizmo menu has a handle-size slider. A selected UI node shows its margin and padding as bands, the pinned insets of an absolutely placed node as dashed lines with their values, and a flex container's direction and the gaps between its children. The six faces of a light probe volume, reflection probe or decal projector are handles: drag one and that half of the box follows the cursor. A selected mesh is outlined along its own silhouette rather than a box, up to 80,000 triangles. The Show menu can draw wireframe on every mesh at once, and choosing a bone paints the surface it moves from blue to red, the rest left grey; convex colliders now draw with the other 3D colliders. A Hunter's attack range is drawn as a red ball, a Perceiver's sight as the cone it actually tests (a ball when its field of view is all round), and a ThirdPersonCamera's boom as a line from the point it looks at to where it ends up, with the probe swept along it as a ball at the end. A UI element drawn as 9-slice shows its picture under its Slice Border field with four guides to drag, as the texture inspector does; while the texture carries a border of its own, which the renderer prefers, it says so instead. A selected Spine or DragonBones entity shows its bones over the artwork as the 3D rigs do, laid where the runtime posed them this frame, with the entity's scale and flips applied; the Spine and DragonBones modules gained a call that lists the bone tree, so a module built before it still draws the skeleton and only the bones are absent. A selected tilemap layer reports its tile count and the size of the area its tiles cover in the viewport readout (`172 tiles · 32×17`), and on a square grid outlines that area, so an infinite layer's edge can be seen. The profiler is laid out as a module rail (Frame, CPU / GPU, Render, Counters, Memory, Systems, Spine) beside the module chosen: its timeline plots what the CPU was busy with and no longer the wait for the next frame, so a healthy window is no longer one flat block and a hitch is a tall column; clicking a column pins that frame and the strip beneath says in a sentence how far over budget it ran and where; the cost tree is a table of total, own cost and share of the frame, in columns; the toolbar is icon buttons with the live state as a pill. The frame debugger's draw list has column headers, a header per pass with its draw count, a swatch for each draw's type, a break-reason filter that starts with All, and the position of the selected draw in the capture. The sequencer's keyframes take the shape of how the curve leaves them (round smooth, diamond linear, square held, round with an arc eased) in the colour of their track, a group's row sums up the keys beneath it, each channel row shows its value at the playhead beside a swatch that is its curve's colour, the ruler marks seconds as well as frames, the playhead's flag carries the frame, the record button is red and the snap toggle says what it is; the curve view marks its grid and names the selected key's frame, value and interpolation. The sound event editor lists its variants as a table with each clip's waveform and the share of the draw its weight takes, groups its settings (playback, level and pitch, voices, space), draws volume and rate as ranges, plots the attenuation curve with the function the runtime uses, and leads its preview bar with the Trigger action. The Show menu also picks how the viewport shades meshes: as authored, as neutral clay (shape, without anyone's colours) or as flat albedo (base colour, no light); the engine takes it as per-view state, so a camera preview in the same frame keeps the authored look. A fourth shading, wireframe, draws every triangle edge on a dark surface with the hidden ones hidden; the engine's pipelines now carry a primitive topology, WebGL2 and WebGPU alike, and each mesh the editor loads keeps a line list of its distinct edges. Script graphs, material graphs and behavior trees share one node look: a header in the colour of what the node is for, an icon and a plain name with the stored id small beside it, round pins that are solid when wired and hollow when not (control pins are triangles), and wires coloured by the type they carry. A graph with no saved positions is laid out left to right when it opens and opens no smaller than half size, and an Arrange button lays any graph out again. A script graph's inputs, outputs and variables are a searchable list beside the canvas that shows how often each variable is read and written, lights the nodes that use the selected one, and lets you drag a variable onto the canvas to get or set it. The Lighting panel folds into groups with a short state beside each title, shows its warnings as a plain row with an amber edge rather than an amber box, and keeps the bake state, counts and the Bake button pinned at the bottom. The History panel draws a rule at the present, with undone steps below it. The scatter brush draws one real sample of itself to scale. The Plugins panel is a list grouped by origin, with search, beside the details of the plugin picked: its actions, declared capabilities, what it contributes and its health. The string table numbers its rows, marks a missing translation with an amber edge and totals its problems in a status bar. The Spine preview in the asset inspector uses the editor's own dropdowns and icon buttons, shows the time against the animation's length, and names the bounds drawn over it (fixed, unsaved, last scan). While a running game is inspected, the selected entity's outline carries its name, the move handles have arrowheads, and a chip beside the handle reads the position, turn or scale being applied. The Game panel says it is idle, starting or failed with an icon, and a failure shows its reason in a block that can be selected. The World panel is a short panel beside the Content Browser: a toolbar with the cell count and size, the persistent entities as a count that opens their list, and — while the game runs — what is in each residency state, the hit rate and the last demand-to-resident time; below it a table of cells with their entity count and, at runtime, state, prefetch result and demand-to-resident time, and the entities of the picked cell beside it. Picking a cell frames its entities in the viewport. The UI Widgets palette is a searchable list in groups (layout, display, input, popup, touch controls) with the Chinese name and the widget's own name on each row, instead of a grid of tiles. The UI debugger's four views are laid out alike: the Elements tree shows each element's main component and its picked element's size and components sit beside it; Text and Focus order are tables with a state dot per row and select on a click of the row; Events draws each dispatch's bubbling path as a chain from its target. Project Health's three counts filter the list, its findings are grouped by severity under folding headings, and the checks that could not run are listed with their reasons instead of in a tooltip. In the Agent panel each run's header carries a dot for how it came out (running, held, not held, stopped early, never checked), a run's steps hang on a rail with a dot each, the acceptance line is ruled off like the change set instead of boxed, and the key hints under the input show while you are typing. The Plugins panel lists the ids a plugin and another owner both claimed and who got them, filters the list to failed, awaiting-trust, incompatible or shadowed plugins, no longer offers a built-in plugin a trust withdrawal that cannot hold, and says what a plugin contributes before disabling it. A material graph can now use another graph as one node: a `.esmatsub` material subgraph has inputs (a name, a type and a default each) and one result, a graph that uses it fills the inputs by wire or by typing a number on the node, and the compiler inlines it, so one subgraph used twice makes two independent copies and saving a subgraph recompiles the shaders of the graphs that use it. New ones come from the Content Browser's New menu; the subgraph's own header says how many graphs use it. A material graph's output node takes the standard material's surface: normal, metallic, roughness, occlusion and emission ports (and an alpha port that also works on an unlit graph), with a typed number for any left unwired. Connecting any of them compiles the graph to the same lit mesh shading the built-in Model material uses — metal read from blue and roughness from green, occlusion on the ambient light only, emission added after lighting — and a graph with none of them compiles exactly as before. New nodes: Normal Map, which reads its texture as data and unpacks it the way the standard material does, and Channel, which takes one of R, G, B or A as a number; a texture node can be set to read its map as data. The output node also has a vertex offset port: a number moves each vertex along its normal, a vec2 or vec3 moves it by that displacement, so a graph can sway foliage or ripple water; the mesh's shadow bends the same way, and a Vertex bounds field on the node says how far the offset can reach so culling keeps a bent mesh that is still on screen. The offset runs on lit 3D meshes only, and its graph cannot sample textures or read the screen. A Switch node makes a variant: it takes two values and a switch name, and the material turns the switch on or off to choose which one its shader is compiled with, so the side not chosen costs nothing at run time. The graph editor draws the graph as it is now, on a ball, cube or quad in its corner, a moment after each edit and before saving, with a checkbox per switch to look at each variant. Select nodes with shift- or ctrl-click and Extract to subgraph moves them into a new `.esmatsub` beside the graph: every wire from outside becomes an input, the one node something outside reads becomes the result, and the graph keeps one node in their place.
- **A material's preview is a real shape.** Selecting a material shows it on a sphere, cube or plane (lit materials open on the sphere, sprite shaders on the plane), over a dark, checker or light background, with a sample image for shaders that sample a texture; the choice is remembered per kind. The header carries the ball as its icon and the name with a faint extension, the shader is a plain section with a link to make it unique, and the Content Browser's material thumbnails use the same preview. The engine's offscreen preview target now has a depth buffer, so a mesh drawn there is no longer drawn inside out.
- **The 2D animation editors are redrawn.** In the sprite animation editor the view's tools float over its corner, playback and the timeline are one panel, frame events are flags on an event track (click one to rename, move or remove it), the frame source folds into a strip that opens on an empty clip, and frame rate, loop and Save no longer appear a second time in the inspector. The animator controller shows states as cards with their clip and speed, wires between a pair of states run side by side with a pill for the condition (dashed when it waits for the exit time), and its inspector puts the selected state or transition first, with the controller's layers, typed parameters and a folded constraints section below.
- **The tile editor matches its design.** The layer and tileset menus sit on the raised surface, a picked tile has a 2px frame and shows its id on hover, the brush column shows the tile id, the replace dialog's button says Replace, and the tileset inspector shows one-way and trigger as switches, the layer opacity is a slim slider, and a collision layer's friction and bounce fields are flat with their own heading.
diff --git a/desktop b/desktop
index 5e35d68b0..2b81c8ef5 160000
--- a/desktop
+++ b/desktop
@@ -1 +1 @@
-Subproject commit 5e35d68b090a9ca686642d16e623f9487fc21768
+Subproject commit 2b81c8ef54f2b3c724c6c7eeac9cfde23dcb4d0f
diff --git a/sdk/etc/index.api.md b/sdk/etc/index.api.md
index ca4e38670..89724f6b2 100644
--- a/sdk/etc/index.api.md
+++ b/sdk/etc/index.api.md
@@ -1,7 +1,7 @@
# API surface — esengine/index
<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->
-Symbols: 115 public · 116 beta · 1604 experimental · 3 deprecated
+Symbols: 115 public · 117 beta · 1604 experimental · 3 deprecated
## ABI_LAYOUT_HASH — const @experimental
```
@@ -4236,6 +4236,7 @@ PlatformImage | PlatformCanvas | ImageBitmap
| 'normalMap' // sample a tangent-space normal map (read as data, unpacked like the standard material)
| 'channel' // one component (r/g/b/a) of a value, as a scalar
| 'literal' // a constant the compiler makes when a subgraph input is left unconnected
+ | 'switch' // a compile-time variant: one of two values, chosen by a #pragma switch the material turns on or off
| 'uv' // v_texCoord
| 'vertexColor' // v_color (the sprite's per-instance tint)
| 'time' // u_time.x — the injected engine frame clock (seconds)
@@ -5525,7 +5526,7 @@ send: (data: string | ArrayBuffer) => void
## NodeParamSpec — interface @beta
```
key: string
-kind: "texture" | "bool" | "float" | "channel" | "color"
+kind: "texture" | "text" | "bool" | "float" | "channel" | "color"
label: string
```
@@ -11651,6 +11652,11 @@ EventBindingPlugin
(entities: readonly ExtractEntity[], rootId: number, name: string, makeId?: (sourceId: number) => PrefabEntityId): PrefabData
```
+## extractSubgraph — function @beta
+```
+(g: MaterialGraph, ids: readonly string[], ref: string, name?: string): ExtractedSubgraph
+```
+
## fetchDecodePixels — function @experimental
```
(url: string, maxEdge?: number): Promise<DecodedPixels>
diff --git a/sdk/etc/index.native.api.md b/sdk/etc/index.native.api.md
index 5584d3eda..b08f90112 100644
--- a/sdk/etc/index.native.api.md
+++ b/sdk/etc/index.native.api.md
@@ -1,7 +1,7 @@
# API surface — esengine/index.native
<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->
-Symbols: 115 public · 121 beta · 1623 experimental · 3 deprecated
+Symbols: 115 public · 122 beta · 1623 experimental · 3 deprecated
## ABI_LAYOUT_HASH — const @experimental
```
@@ -4244,6 +4244,7 @@ PlatformImage | PlatformCanvas | ImageBitmap
| 'normalMap' // sample a tangent-space normal map (read as data, unpacked like the standard material)
| 'channel' // one component (r/g/b/a) of a value, as a scalar
| 'literal' // a constant the compiler makes when a subgraph input is left unconnected
+ | 'switch' // a compile-time variant: one of two values, chosen by a #pragma switch the material turns on or off
| 'uv' // v_texCoord
| 'vertexColor' // v_color (the sprite's per-instance tint)
| 'time' // u_time.x — the injected engine frame clock (seconds)
@@ -5723,7 +5724,7 @@ send: (data: string | ArrayBuffer) => void
## NodeParamSpec — interface @beta
```
key: string
-kind: "texture" | "bool" | "float" | "channel" | "color"
+kind: "texture" | "text" | "bool" | "float" | "channel" | "color"
label: string
```
@@ -11904,6 +11905,11 @@ EventBindingPlugin
(entities: readonly ExtractEntity[], rootId: number, name: string, makeId?: (sourceId: number) => PrefabEntityId): PrefabData
```
+## extractSubgraph — function @beta
+```
+(g: MaterialGraph, ids: readonly string[], ref: string, name?: string): ExtractedSubgraph
+```
+
## fetchDecodePixels — function @experimental
```
(url: string, maxEdge?: number): Promise<DecodedPixels>
diff --git a/sdk/etc/index.node.api.md b/sdk/etc/index.node.api.md
index 18671124e..26db0d129 100644
--- a/sdk/etc/index.node.api.md
+++ b/sdk/etc/index.node.api.md
@@ -1,7 +1,7 @@
# API surface — esengine/index.node
<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->
-Symbols: 115 public · 118 beta · 1603 experimental · 3 deprecated
+Symbols: 115 public · 119 beta · 1603 experimental · 3 deprecated
## ANCHOR_AXES — const @experimental
```
@@ -4231,6 +4231,7 @@ PlatformImage | PlatformCanvas | ImageBitmap
| 'normalMap' // sample a tangent-space normal map (read as data, unpacked like the standard material)
| 'channel' // one component (r/g/b/a) of a value, as a scalar
| 'literal' // a constant the compiler makes when a subgraph input is left unconnected
+ | 'switch' // a compile-time variant: one of two values, chosen by a #pragma switch the material turns on or off
| 'uv' // v_texCoord
| 'vertexColor' // v_color (the sprite's per-instance tint)
| 'time' // u_time.x — the injected engine frame clock (seconds)
@@ -5520,7 +5521,7 @@ send: (data: string | ArrayBuffer) => void
## NodeParamSpec — interface @beta
```
key: string
-kind: "texture" | "bool" | "float" | "channel" | "color"
+kind: "texture" | "text" | "bool" | "float" | "channel" | "color"
label: string
```
@@ -11646,6 +11647,11 @@ EventBindingPlugin
(entities: readonly ExtractEntity[], rootId: number, name: string, makeId?: (sourceId: number) => PrefabEntityId): PrefabData
```
+## extractSubgraph — function @beta
+```
+(g: MaterialGraph, ids: readonly string[], ref: string, name?: string): ExtractedSubgraph
+```
+
## fetchDecodePixels — function @experimental
```
(url: string, maxEdge?: number): Promise<DecodedPixels>
diff --git a/sdk/etc/minigame.api.md b/sdk/etc/minigame.api.md
index edb7dd6eb..41c88add5 100644
--- a/sdk/etc/minigame.api.md
+++ b/sdk/etc/minigame.api.md
@@ -1,7 +1,7 @@
# API surface — esengine/minigame
<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->
-Symbols: 115 public · 116 beta · 1625 experimental · 3 deprecated
+Symbols: 115 public · 117 beta · 1625 experimental · 3 deprecated
## ANCHOR_AXES — const @experimental
```
@@ -4231,6 +4231,7 @@ PlatformImage | PlatformCanvas | ImageBitmap
| 'normalMap' // sample a tangent-space normal map (read as data, unpacked like the standard material)
| 'channel' // one component (r/g/b/a) of a value, as a scalar
| 'literal' // a constant the compiler makes when a subgraph input is left unconnected
+ | 'switch' // a compile-time variant: one of two values, chosen by a #pragma switch the material turns on or off
| 'uv' // v_texCoord
| 'vertexColor' // v_color (the sprite's per-instance tint)
| 'time' // u_time.x — the injected engine frame clock (seconds)
@@ -5813,7 +5814,7 @@ send: (data: string | ArrayBuffer) => void
## NodeParamSpec — interface @beta
```
key: string
-kind: "texture" | "bool" | "float" | "channel" | "color"
+kind: "texture" | "text" | "bool" | "float" | "channel" | "color"
label: string
```
@@ -11950,6 +11951,11 @@ EventBindingPlugin
(entities: readonly ExtractEntity[], rootId: number, name: string, makeId?: (sourceId: number) => PrefabEntityId): PrefabData
```
+## extractSubgraph — function @beta
+```
+(g: MaterialGraph, ids: readonly string[], ref: string, name?: string): ExtractedSubgraph
+```
+
## fetchDecodePixels — function @experimental
```
(url: string, maxEdge?: number): Promise<DecodedPixels>
diff --git a/sdk/etc/wechat.api.md b/sdk/etc/wechat.api.md
index 59e86b875..5d6196e2e 100644
--- a/sdk/etc/wechat.api.md
+++ b/sdk/etc/wechat.api.md
@@ -1,7 +1,7 @@
# API surface — esengine/wechat
<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->
-Symbols: 115 public · 116 beta · 1616 experimental · 3 deprecated
+Symbols: 115 public · 117 beta · 1616 experimental · 3 deprecated
## ANCHOR_AXES — const @experimental
```
@@ -4231,6 +4231,7 @@ PlatformImage | PlatformCanvas | ImageBitmap
| 'normalMap' // sample a tangent-space normal map (read as data, unpacked like the standard material)
| 'channel' // one component (r/g/b/a) of a value, as a scalar
| 'literal' // a constant the compiler makes when a subgraph input is left unconnected
+ | 'switch' // a compile-time variant: one of two values, chosen by a #pragma switch the material turns on or off
| 'uv' // v_texCoord
| 'vertexColor' // v_color (the sprite's per-instance tint)
| 'time' // u_time.x — the injected engine frame clock (seconds)
@@ -5527,7 +5528,7 @@ send: (data: string | ArrayBuffer) => void
## NodeParamSpec — interface @beta
```
key: string
-kind: "texture" | "bool" | "float" | "channel" | "color"
+kind: "texture" | "text" | "bool" | "float" | "channel" | "color"
label: string
```
@@ -11677,6 +11678,11 @@ EventBindingPlugin
(entities: readonly ExtractEntity[], rootId: number, name: string, makeId?: (sourceId: number) => PrefabEntityId): PrefabData
```
+## extractSubgraph — function @beta
+```
+(g: MaterialGraph, ids: readonly string[], ref: string, name?: string): ExtractedSubgraph
+```
+
## fetchDecodePixels — function @experimental
```
(url: string, maxEdge?: number): Promise<DecodedPixels>
diff --git a/sdk/src/core-render.ts b/sdk/src/core-render.ts
index 4faeb4e7f..c0f22c01a 100644
--- a/sdk/src/core-render.ts
+++ b/sdk/src/core-render.ts
@@ -124,6 +124,7 @@ export {
newMaterialSubgraph,
flattenSubgraphs,
subgraphInputs,
+ extractSubgraph,
subgraphRefs,
validateSubgraph,
addNode,
diff --git a/sdk/src/render/materialGraph.ts b/sdk/src/render/materialGraph.ts
index 3057a888c..11455c472 100644
--- a/sdk/src/render/materialGraph.ts
+++ b/sdk/src/render/materialGraph.ts
@@ -28,6 +28,7 @@ export type GraphNodeType =
| 'normalMap' // sample a tangent-space normal map (read as data, unpacked like the standard material)
| 'channel' // one component (r/g/b/a) of a value, as a scalar
| 'literal' // a constant the compiler makes when a subgraph input is left unconnected
+ | 'switch' // a compile-time variant: one of two values, chosen by a #pragma switch the material turns on or off
| 'uv' // v_texCoord
| 'vertexColor' // v_color (the sprite's per-instance tint)
| 'time' // u_time.x — the injected engine frame clock (seconds)
@@ -296,6 +297,27 @@ export function compileMaterialGraph(source: MaterialGraph, resolve?: SubgraphRe
out = line('float', `${a.expr}.${ch}`, `${a.wexpr}.${ch}`);
break;
}
+ case 'switch': {
+ // Which value the material gets is decided when its shader is compiled, so the other side costs
+ // nothing at run time: both languages' #ifdef is resolved before the stage is assembled.
+ const feature = typeof n.params?.feature === 'string' ? n.params.feature : '';
+ if (!/^[A-Z][A-Z0-9_]*$/.test(feature)) throw new Error(`material graph: node "${id}" (switch) needs a name in capitals, digits and underscores, got "${feature}"`);
+ const on = input('on');
+ const off = input('off');
+ const same = on.type === off.type;
+ const type: GraphType = same ? on.type : 'vec4';
+ const gOn = same ? on.expr : toVec4(on.expr, on.type);
+ const gOff = same ? off.expr : toVec4(off.expr, off.type);
+ const wOn = same ? on.wexpr : toVec4W(on.wexpr, on.type);
+ const wOff = same ? off.wexpr : toVec4W(off.wexpr, off.type);
+ const decl = `#pragma switch ${feature}${n.params?.default === true ? ' default(on)' : ''}`;
+ if (!params.includes(decl)) params.push(decl);
+ const t = `n${tmp++}`;
+ body.push(`${type} ${t};`, `#ifdef ${feature}`, `${t} = ${gOn};`, '#else', `${t} = ${gOff};`, '#endif');
+ wbody.push(`var ${t} : ${WGSL_TYPE[type]};`, `#ifdef ${feature}`, `${t} = ${wOn};`, '#else', `${t} = ${wOff};`, '#endif');
+ out = { expr: t, wexpr: t, type };
+ break;
+ }
case 'literal': {
const v = typeof n.params?.value === 'number' && Number.isFinite(n.params.value) ? n.params.value : 0;
const ty = (['float', 'vec2', 'vec3', 'vec4'] as const).find((t) => t === n.params?.type) ?? 'float';
@@ -506,7 +528,7 @@ export interface NodePort {
export interface NodeParamSpec {
key: string;
label: string;
- kind: 'color' | 'float' | 'texture' | 'bool' | 'channel';
+ kind: 'color' | 'float' | 'texture' | 'bool' | 'channel' | 'text';
}
/** Static schema for a node type — the single source the palette, ports, and node inspector
@@ -526,6 +548,7 @@ export const NODE_SPECS: Record<GraphNodeType, NodeSpec> = {
subgraph: { label: 'Subgraph', inputs: [], output: 'float', params: [], addable: false },
subInput: { label: 'Subgraph Input', inputs: [], output: 'float', params: [], addable: false },
subOutput: { label: 'Subgraph Output', inputs: [{ name: 'value', type: 'float' }], output: null, params: [], addable: false },
+ switch: { label: 'Switch', inputs: [{ name: 'on', type: 'vec4' }, { name: 'off', type: 'vec4' }], output: 'vec4', params: [{ key: 'feature', label: 'Switch', kind: 'text' }, { key: 'default', label: 'Default on', kind: 'bool' }], addable: true },
literal: { label: 'Literal', inputs: [], output: 'float', params: [], addable: false },
output: {
label: 'Output',
@@ -587,6 +610,7 @@ function defaultParams(type: GraphNodeType, id: string): Record<string, unknown>
case 'textureSample': return { name: `u_${id}`, default: 'white' };
case 'normalMap': return { name: `u_${id}` };
case 'channel': return { channel: 'r' };
+ case 'switch': return { feature: `ES_${id.toUpperCase()}`, default: false };
case 'smoothstep': return { edge0: 0, edge1: 1 };
case 'noise': return { scale: 12 };
case 'panner': return { speedX: 0.1, speedY: 0 };
@@ -718,6 +742,107 @@ export function newMaterialSubgraph(): MaterialGraph {
};
}
+/** What a node hands to those that read it, as far as the editor can tell without opening a subgraph. */
+function outputTypeOf(n: MaterialGraphNode): GraphType {
+ if (n.type === 'literal') return (['float', 'vec2', 'vec3', 'vec4'] as const).find((t) => t === n.params?.type) ?? 'float';
+ if (n.type === 'subInput') return subgraphInputs({ nodes: [n], output: n.id })[0]!.type;
+ return NODE_SPECS[n.type]?.output ?? 'float';
+}
+
+export interface ExtractedSubgraph {
+ /** The new `.esmatsub`: the selection, with a `subInput` for each wire that came in from outside. */
+ sub: MaterialGraph;
+ /** The graph with the selection replaced by one `subgraph` node naming @p ref. */
+ graph: MaterialGraph;
+ /** The id of that node. */
+ nodeId: string;
+}
+
+/**
+ * Turn the nodes @p ids into a subgraph, and put one node using it in their place.
+ *
+ * Every wire from outside into the selection becomes an input (one per source node, named after the
+ * slot it fed), and the one selected node that something outside reads becomes the result. Throws if
+ * there is not exactly one such node — a subgraph has one result — or if the selection holds the
+ * output. A node's own param names carry over unchanged; the subgraph node prefixes them, so a
+ * material that set `u_tint` now finds it as `<node>_u_tint`.
+ */
+export function extractSubgraph(g: MaterialGraph, ids: readonly string[], ref: string, name = 'Subgraph'): ExtractedSubgraph {
+ const chosen = new Set(ids);
+ const picked = g.nodes.filter((n) => chosen.has(n.id));
+ if (picked.length === 0) throw new Error('material graph: nothing selected to extract');
+ if (picked.some((n) => n.type === 'output' || n.type === 'subOutput')) throw new Error('material graph: the output node cannot be moved into a subgraph');
+ if (g.kind === 'subgraph' && picked.some((n) => n.type === 'subInput')) throw new Error('material graph: a subgraph input cannot be moved into another subgraph');
+
+ // The selected nodes something outside reads: the result, and anything else is an error.
+ const readFromOutside = new Set<string>();
+ for (const n of g.nodes) {
+ if (chosen.has(n.id)) continue;
+ for (const src of Object.values(n.inputs ?? {})) if (chosen.has(src)) readFromOutside.add(src);
+ }
+ if (readFromOutside.size !== 1) {
+ throw new Error(readFromOutside.size === 0
+ ? 'material graph: nothing outside reads the selection, so it has no result'
+ : `material graph: the selection has ${readFromOutside.size} results (${[...readFromOutside].join(', ')}); a subgraph has one`);
+ }
+ const result = [...readFromOutside][0]!;
+
+ const byId = new Map(g.nodes.map((n) => [n.id, n]));
+ const subNodes: MaterialGraphNode[] = [];
+ const inputOf = new Map<string, string>(); // outside source id → the subInput that stands for it
+ const taken = new Set<string>();
+ const inputs: Record<string, string> = {}; // the subgraph node's slot → outside source id
+ let k = 0;
+ for (const n of picked) {
+ const rewired: Record<string, string> = {};
+ for (const [slot, src] of Object.entries(n.inputs ?? {})) {
+ if (chosen.has(src)) { rewired[slot] = src; continue; }
+ let inId = inputOf.get(src);
+ if (!inId) {
+ inId = `in${++k}`;
+ inputOf.set(src, inId);
+ let nm = slot;
+ for (let i = 2; taken.has(nm); i++) nm = `${slot}${i}`;
+ taken.add(nm);
+ const source = byId.get(src);
+ subNodes.push({ id: inId, type: 'subInput', params: { name: nm, type: source ? outputTypeOf(source) : 'float', default: 0 } });
+ inputs[nm] = src;
+ }
+ rewired[slot] = inId;
+ }
+ subNodes.push({ ...n, inputs: Object.keys(rewired).length ? rewired : undefined, params: n.params ? { ...n.params } : undefined });
+ }
+ const resultId = result === 'result' ? 'sub_result' : 'result';
+ subNodes.push({ id: resultId, type: 'subOutput', inputs: { value: result } });
+
+ // Lay the new graph out from the selection's own corner, inputs to the left of what they feed.
+ const placed = picked.filter((n) => typeof n.x === 'number' && typeof n.y === 'number');
+ const left = placed.length ? Math.min(...placed.map((n) => n.x!)) : 0;
+ const top = placed.length ? Math.min(...placed.map((n) => n.y!)) : 0;
+ const right = placed.length ? Math.max(...placed.map((n) => n.x!)) : 0;
+ for (const n of subNodes) {
+ if (typeof n.x === 'number') n.x = n.x - left + 260;
+ if (typeof n.y === 'number') n.y = n.y - top + 40;
+ }
+ let row = 0;
+ for (const n of subNodes) if (n.type === 'subInput') { n.x = 40; n.y = 40 + 110 * row++; }
+ const out = subNodes.find((n) => n.id === resultId)!;
+ out.x = right - left + 260 + 340;
+ out.y = 40;
+
+ const sub: MaterialGraph = { kind: 'subgraph', name, output: resultId, nodes: subNodes };
+
+ const used = new Set(g.nodes.map((n) => n.id));
+ let nodeId = 'subgraph1';
+ for (let i = 2; used.has(nodeId); i++) nodeId = `subgraph${i}`;
+ const rest: MaterialGraphNode[] = g.nodes.filter((n) => !chosen.has(n.id)).map((n) => ({
+ ...n,
+ inputs: n.inputs ? Object.fromEntries(Object.entries(n.inputs).map(([slot, src]) => [slot, src === result ? nodeId : src])) : undefined,
+ }));
+ rest.push({ id: nodeId, type: 'subgraph', x: placed.length ? right : undefined, y: placed.length ? top : undefined, params: { ref }, inputs: Object.keys(inputs).length ? inputs : undefined });
+ return { sub, graph: { ...g, nodes: rest }, nodeId };
+}
+
/** Whether @p sub compiles when used — checked by wrapping its output in a throwaway material output. */
export function validateSubgraph(sub: MaterialGraph, resolve: SubgraphResolver): void {
const probe: MaterialGraph = {
diff --git a/sdk/tests/materialPbr.test.ts b/sdk/tests/materialPbr.test.ts
index 16b40eba8..503539838 100644
--- a/sdk/tests/materialPbr.test.ts
+++ b/sdk/tests/materialPbr.test.ts
@@ -150,3 +150,34 @@ describe('vertex offset', () => {
expect(compileMaterialGraph(g)).toContain('texture(u_albedo, v_texCoord)');
});
});
+
+describe('static switch', () => {
+ const g = (feature = 'ES_FANCY', extra: Record<string, unknown> = {}): MaterialGraph => ({
+ name: 'Var', output: 'out',
+ nodes: [
+ { id: 'a', type: 'constColor', params: { name: 'u_a', value: [1, 0, 0, 1] } },
+ { id: 'b', type: 'constColor', params: { name: 'u_b', value: [0, 0, 1, 1] } },
+ { id: 'sw', type: 'switch', params: { feature, ...extra }, inputs: { on: 'a', off: 'b' } },
+ { id: 'out', type: 'output', inputs: { color: 'sw' } },
+ ],
+ });
+
+ it('declares the switch and picks a side with #ifdef in both languages', () => {
+ const src = compileMaterialGraph(g());
+ expect(src).toContain('#pragma switch ES_FANCY\n');
+ expect(src.match(/#ifdef ES_FANCY/g)).toHaveLength(2);
+ expect(src).toMatch(/n\d = u_a;/);
+ expect(src).toMatch(/n\d = mc\.u_b;/);
+ });
+
+ it('can start on, and declares a shared switch once', () => {
+ expect(compileMaterialGraph(g('ES_FANCY', { default: true }))).toContain('#pragma switch ES_FANCY default(on)');
+ const twin = g();
+ twin.nodes.push({ id: 'sw2', type: 'switch', params: { feature: 'ES_FANCY' }, inputs: { on: 'a', off: 'b' } });
+ expect(compileMaterialGraph(twin).match(/#pragma switch ES_FANCY/g)).toHaveLength(1);
+ });
+
+ it('refuses a name a #define cannot be', () => {
+ expect(() => compileMaterialGraph(g('fancy'))).toThrow(/needs a name in capitals/);
+ });
+});
diff --git a/sdk/tests/materialSubgraph.test.ts b/sdk/tests/materialSubgraph.test.ts
index 073065e73..d5e4c34b0 100644
--- a/sdk/tests/materialSubgraph.test.ts
+++ b/sdk/tests/materialSubgraph.test.ts
@@ -2,7 +2,7 @@
// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
import { describe, it, expect } from 'vitest';
import {
- compileMaterialGraph, flattenSubgraphs, subgraphInputs, subgraphRefs, validateSubgraph, newMaterialSubgraph, connect,
+ compileMaterialGraph, extractSubgraph, flattenSubgraphs, subgraphInputs, subgraphRefs, validateSubgraph, newMaterialSubgraph, connect,
type MaterialGraph, type SubgraphResolver,
} from '../src/render/materialGraph';
@@ -103,3 +103,47 @@ describe('subgraphs', () => {
expect(g.nodes.find((n) => n.id === 'w')!.inputs).toEqual({ time: 't', strength: 't' });
});
});
+
+describe('extracting a subgraph', () => {
+ const base = (): MaterialGraph => ({
+ name: 'G', output: 'out',
+ nodes: [
+ { id: 'a', type: 'constColor', x: 0, y: 0, params: { name: 'u_a', value: [1, 0, 0, 1] } },
+ { id: 'uv', type: 'uv', x: 0, y: 100 },
+ { id: 'n', type: 'noise', x: 200, y: 100, params: { scale: 8 }, inputs: { uv: 'uv' } },
+ { id: 'm', type: 'multiply', x: 400, y: 60, inputs: { a: 'a', b: 'n' } },
+ { id: 'out', type: 'output', x: 600, y: 60, inputs: { color: 'm' } },
+ ],
+ });
+
+ it('makes an input of each wire from outside and a node of the whole selection', () => {
+ const { sub, graph, nodeId } = extractSubgraph(base(), ['n', 'm'], 'noisy.esmatsub', 'Noisy');
+ expect(sub.kind).toBe('subgraph');
+ expect(subgraphInputs(sub).map((i) => [i.name, i.type])).toEqual([['uv', 'vec2'], ['a', 'vec4']]);
+ expect(graph.nodes.map((n) => n.id).sort()).toEqual(['a', 'out', nodeId, 'uv'].sort());
+ const used = graph.nodes.find((n) => n.id === nodeId)!;
+ expect(used.params?.ref).toBe('noisy.esmatsub');
+ expect(used.inputs).toEqual({ uv: 'uv', a: 'a' });
+ expect(graph.nodes.find((n) => n.id === 'out')!.inputs!.color).toBe(nodeId);
+ });
+
+ it('leaves a graph that compiles, to the same shader apart from the param it renamed', () => {
+ const g = base();
+ const { sub, graph } = extractSubgraph(g, ['n', 'm'], 'noisy.esmatsub');
+ const resolve: SubgraphResolver = (r) => (r === 'noisy.esmatsub' ? sub : null);
+ validateSubgraph(sub, resolve);
+ const before = compileMaterialGraph(g);
+ const after = compileMaterialGraph(graph, resolve);
+ expect(after).toContain('noise2d(');
+ expect(after.match(/#pragma param/g)).toEqual(before.match(/#pragma param/g));
+ });
+
+ it('refuses a selection with two results, none, or the output', () => {
+ expect(() => extractSubgraph(base(), ['n', 'a'], 'x')).toThrow(/2 results/);
+ expect(() => extractSubgraph(base(), ['uv', 'n', 'm', 'a'], 'x')).not.toThrow();
+ const g = base();
+ g.nodes.push({ id: 'dead', type: 'sin', inputs: { x: 'a' } });
+ expect(() => extractSubgraph(g, ['dead'], 'x')).toThrow(/nothing outside reads/);
+ expect(() => extractSubgraph(base(), ['m', 'out'], 'x')).toThrow(/output node/);
+ });
+});
diff --git a/tools/releaseNotes.mjs b/tools/releaseNotes.mjs
index adda2dae1..f8f02bfd1 100644
--- a/tools/releaseNotes.mjs
+++ b/tools/releaseNotes.mjs
@@ -154,6 +154,8 @@ export const NOTED = {
{ note: 'Material graphs can output a standard PBR surface.' },
'feat(render): material graphs gain a vertex offset output that bends the mesh and the shadow it casts':
{ note: 'Material graphs can bend a mesh and its shadow.' },
+ 'feat(render): material graph switches for variants, a live preview in the graph editor, and extracting a selection into a subgraph':
+ { note: 'Material graphs have switches, a live preview and extract-to-subgraph.' },
'feat(editor): an asset header names its kind and size, and a segmented switch is used only when its words fit':
{ note: "An asset's header names its kind and size." },
"feat(editor): asset inspectors take the board's finish — a card preview, ruled key-value rows, tinted actions, a kind icon in the header":