A town simulation in pale isometric line art, implemented with Ritmo ECS and PixiJs 3D
Run on WebGPU where the browser has it, and draw shared models as plain meshes
Zyie8324a5969ddd
diff --git a/DEVELOPMENT.md b/DEVELOPMENT.mdindex 9aac015..678773b 100644--- a/DEVELOPMENT.md+++ b/DEVELOPMENT.md@@ -4,7 +4,7 @@Inkline Town is a TypeScript game. The simulation runs on the[Ritmo](https://github.com/typeonce-dev/ritmo) ECS at a fixed step and-knows nothing of the page; [PixiJS 3D](https://github.com/pixijs/3d) (`@pixi/3d`, on WebGL) draws the 3D world;+knows nothing of the page; [PixiJS 3D](https://github.com/pixijs/3d) (`@pixi/3d`, on WebGPU where the browser has it and WebGL elsewhere) draws the 3D world;Pixi renders the original menu thumbnails; saving iswritten with [Effect](https://effect.website).@@ -267,11 +267,15 @@ One frame runs three schedules: `simulate` (at the chosen speed), then `project`- `src/render/pixi3d/`: the live renderer: `services.ts` (its scene and view registries), `sync.ts` (a viewfor each entity), `draw/` (the land, the ground, the map view, the preview, animation, the townsfolk),`schedule.ts` (`draw`), `scene.ts` (camera and frame source), `input.ts` (map input), `views.ts`,- `pool.ts` (shared models: one `BatchedMesh3D` a model, per-copy colour and surface state, picking against- each copy's triangles), `thumbnails.ts` and `portrait.ts` (the pictures the page's menus show, drawn offscreen+ `pool.ts` (shared models: each copy is plain meshes that share the model's geometry, with materials of its+ own for its colour and surface state, and picking against each copy's triangles), `thumbnails.ts` and `portrait.ts` (the pictures the page's menus show, drawn offscreenby the same renderer), the effects, `bits.ts` (the shader bits: instances, silhouettes, ink ribbons, the- surface shading, and the faces' depth offset) and `materials.ts`. It runs on WebGL, so each bit carries GLSL- only. `mesh/` is geometry and maths with no renderer in it, which the tests use in Node.+ surface shading, and the faces' depth offset) and `materials.ts` (which also draws every picture, `draw`, so+ the faces know its size in pixels). It runs on WebGPU where the browser has it and on WebGL elsewhere+ (`?renderer=webgl` in the page's address asks for WebGL), so each bit carries its code twice: `gpu` in WGSL+ and `gl` in GLSL. A bit without one half draws nothing of its own on that renderer, with no error, so change+ both. `mesh/` is geometry and maths with+ no renderer in it, which the tests use in Node.- `assets/`: the models, drawn in code: buildings, homes, people, the land, parks (`town-props.ts`),services (`services.ts`: grain hoist, fish racks, watch tower, herbs, medical signs, noticeboard, builder'sequipment), and `appearance.ts` (material state metadata for catalogue presets; wear, neighbourhood,diff --git a/src/labs/effects-lab/main.ts b/src/labs/effects-lab/main.tsindex aed3b6b..34d2e99 100644--- a/src/labs/effects-lab/main.ts+++ b/src/labs/effects-lab/main.ts@@ -23,7 +23,6 @@ root.innerHTML=`<header><a href="/model-review.html">Inkline Town</a><span>LIVEconst grid=root.querySelector<HTMLElement>(".grid")!,pool=new ModelPool()// One canvas over the page; each card's picture is the one view drawn into the card's rectangle.const viewer=await labViewer(document.body,{width:innerWidth,height:innerHeight,className:"rendering"}),camera=viewer.camera,scene=viewer.view.root-scene.addChild(pool.root)const views=cases.map((c,i)=>{const card=document.createElement("article")card.innerHTML=`<div class="render-view" role="img" aria-label="${c.title}"></div><div class="caption"><h2>${c.title}</h2><p>${c.note}</p></div>`;grid.append(card)@@ -58,9 +57,9 @@ function render(){const r=v.view.getBoundingClientRect();if(r.bottom<=0||r.top>=innerHeight)returnplace(i,r.width,r.height)camera.viewport.set(r.left/innerWidth,r.top/innerHeight,r.width/innerWidth,r.height/innerHeight)- viewer.app.renderer.render({container:viewer.view,clear:first});first=false+ viewer.draw(first);first=false})- if(first)viewer.app.renderer.render({container:viewer.view,clear:true})+ if(first)viewer.draw(true)camera.viewport.set(0,0,1,1)root.querySelector("#stats")!.textContent=`1 active house mesh · ${views.length} instances · ${time.toFixed(1)} s`frames++diff --git a/src/labs/model-review/main.ts b/src/labs/model-review/main.tsindex c780a51..00a500d 100644--- a/src/labs/model-review/main.ts+++ b/src/labs/model-review/main.ts@@ -71,9 +71,9 @@ function render() {if (r.bottom <= 0 || r.top >= innerHeight) continueplace(model, r.width, r.height)camera.viewport.set(r.left / innerWidth, r.top / innerHeight, r.width / innerWidth, r.height / innerHeight)- viewer.app.renderer.render({ container: viewer.view, clear: first }); first = false+ viewer.draw(first); first = false}- if (first) { for (const m of models) m.built.group.visible = false; viewer.app.renderer.render({ container: viewer.view, clear: true }) }+ if (first) { for (const m of models) m.built.group.visible = false; viewer.draw(true) }camera.viewport.set(0, 0, 1, 1)root.querySelector("output")!.textContent = `${Math.round(yaw)}°`; rotation.value = String(yaw); renders++}diff --git a/src/labs/model-review/proportions.ts b/src/labs/model-review/proportions.tsindex 03c150a..37f666a 100644--- a/src/labs/model-review/proportions.ts+++ b/src/labs/model-review/proportions.ts@@ -106,7 +106,7 @@ function render(){pair.forEach((p,j)=>{p.scene.visible=i===j})for(const b of [built,person])b.updateEffects(1.2)camera.viewport.set(i/2,0,1/2,1)- viewer.app.renderer.render({container:viewer.view,clear:i===0})+ viewer.draw(i===0)})camera.viewport.set(0,0,1,1)root.querySelector("output")!.textContent=`${yaw}°`diff --git a/src/labs/viewer.ts b/src/labs/viewer.tsindex 7c3b4f3..a82c8a7 100644--- a/src/labs/viewer.ts+++ b/src/labs/viewer.ts@@ -6,7 +6,8 @@import { View3D, type Camera3D } from "@pixi/3d"import { Application, RenderTexture } from "pixi.js"import { cross, dot, normalize, scale, sub, add, type Vec3 } from "../render/pixi3d/mesh/vec3.ts"-import { channels } from "../render/pixi3d/gpu.ts"+import { backend, channels } from "../render/pixi3d/gpu.ts"+import { draw, sizeFaces } from "../render/pixi3d/materials.ts"export interface LabViewer {readonly app: Application@@ -19,6 +20,8 @@ export interface LabViewer {/** Sizes the canvas buffer (CSS pixels times the pixel ratio) and the view; the stylesheet sizes it on the page. */resize(width: number, height: number): voidrender(): void+ /** Draws the view into its camera's viewport, for a page that draws one view into many places; `clear` wipes the canvas first. */+ draw(clear: boolean): void/*** The view drawn offscreen at `width` × `height`, `resolution` pixels a CSS* pixel, on `background` (or transparent for `null`), as a canvas of its own.@@ -31,7 +34,7 @@ export async function labViewer(mount: HTMLElement, options: { width: number; heconst background = options.background === undefined ? null : options.backgroundconst app = new Application()await app.init({- preference: "webgl",+ preference: await backend(),antialias: true,backgroundColor: background ?? 0xffffff,backgroundAlpha: background === null ? 0 : 1,@@ -67,7 +70,11 @@ export async function labViewer(mount: HTMLElement, options: { width: number; heapp.renderer.resize(width, height)view.setSize(width, height)},+ draw(clear) {+ draw(app.renderer, view, { clear })+ },render() {+ sizeFaces(app.renderer, view)app.render()},snapshot(width, height, resolution = 1, fill = background) {@@ -75,7 +82,7 @@ export async function labViewer(mount: HTMLElement, options: { width: number; heview.setSize(width, height)const target = RenderTexture.create({ width, height, resolution, antialias: true })const [r, g, b] = channels(fill ?? 0)- app.renderer.render({ container: view, target, clearColor: [r, g, b, fill === null ? 0 : 1] })+ draw(app.renderer, view, { target, clearColor: [r, g, b, fill === null ? 0 : 1] })const out = document.createElement("canvas")out.width = Math.round(width * resolution)out.height = Math.round(height * resolution)diff --git a/src/render/pixi3d/assets/renderer.ts b/src/render/pixi3d/assets/renderer.tsindex 578a420..5fad26f 100644--- a/src/render/pixi3d/assets/renderer.ts+++ b/src/render/pixi3d/assets/renderer.ts@@ -15,7 +15,7 @@ import { floorScale, vertex3 } from "./space.ts"import { lineGeometry, toGeometry } from "../gpu.ts"import { bounds } from "../mesh/geometry.ts"import { add, type Vec3 } from "../mesh/vec3.ts"-import { partMaterial, setSurface } from "../materials.ts"+import { partMaterial, releaseMaterial, setSurface } from "../materials.ts"import { SmokePlume } from "../smoke-effects.ts"import { FountainWater } from "../fountain-effects.ts"@@ -82,7 +82,7 @@ export function buildAsset(asset: InkAsset, options: InkMeshOptions & { surfaceEfor (const { mesh } of parts) {const material = mesh.materialmesh.destroy({ geometry: true })- material.destroy()+ releaseMaterial(material)}group.removeFromParent()group.destroy()diff --git a/src/render/pixi3d/bits.ts b/src/render/pixi3d/bits.tsindex a3b9b7d..264de82 100644--- a/src/render/pixi3d/bits.ts+++ b/src/render/pixi3d/bits.ts@@ -3,8 +3,9 @@* `custom-shaders`). Every material here is a `FlatMaterial`, unlit, drawn in* display space: colours are written as authored, as three.js showed them.*- * The renderer runs on WebGL (`scene.ts` asks for it), so each bit carries its- * GLSL half only.+ * The renderer runs on WebGPU where the browser has it and on WebGL elsewhere+ * (`backend` in `gpu.ts`), so each bit carries its code twice: `gpu` in WGSL+ * and `gl` in GLSL. A change to one half belongs in the other too.*/import type { ShaderBit } from "@pixi/3d"@@ -16,32 +17,50 @@ vec3 inkRGB(vec3 c){ return pow(c,vec3(2.2)); }float inkHash(vec2 p){ return fract(sin(dot(p,vec2(127.1,311.7)))*43758.5453); }float inkNoise(vec2 p){ vec2 i=floor(p),f=fract(p); f=f*f*(3.0-2.0*f); return mix(mix(inkHash(i),inkHash(i+vec2(1,0)),f.x),mix(inkHash(i+vec2(0,1)),inkHash(i+vec2(1,1)),f.x),f.y); }`+const colourSpaceGpu = `+fn inkToLinear(c: vec3<f32>) -> vec3<f32> { return select(pow(c*0.9478672986+vec3<f32>(0.0521327014),vec3<f32>(2.4)), c*0.0773993808, c<vec3<f32>(0.04045)); }+fn inkToDisplay(c: vec3<f32>) -> vec3<f32> { return select(pow(c,vec3<f32>(0.41666))*1.055-vec3<f32>(0.055), c*12.92, c<=vec3<f32>(0.0031308)); }+fn inkRGB(c: vec3<f32>) -> vec3<f32> { return pow(c,vec3<f32>(2.2)); }+fn inkHash(p: vec2<f32>) -> f32 { return fract(sin(dot(p,vec2<f32>(127.1,311.7)))*43758.5453); }+fn inkNoise(p: vec2<f32>) -> f32 { let i=floor(p); var f=fract(p); f=f*f*(3.0-2.0*f); return mix(mix(inkHash(i),inkHash(i+vec2<f32>(1.0,0.0)),f.x),mix(inkHash(i+vec2<f32>(0.0,1.0)),inkHash(i+vec2<f32>(1.0,1.0)),f.x),f.y); }+`/** Helpers every bit can call; required by the bits that use them. */-export const inkCommonBit: ShaderBit = { name: "inkline-common", gl: { header: colourSpace } }+export const inkCommonBit: ShaderBit = { name: "inkline-common", gpu: { header: colourSpaceGpu }, gl: { header: colourSpace } }/*** Faces sit a little behind their ink, so a stroke drawn on a face's edge- * always shows: three.js's polygon offset (factor 6, units 2), written into- * the fragment's depth so it scales with the face's slope as that did.+ * always shows: three.js's polygon offset (factor 6, units 2), scaled with+ * the face's slope as that was.+ *+ * WebGL writes it into the fragment's depth. A Pixi 3D material can't write a+ * fragment's depth on WebGPU, so there each vertex is moved back instead, by+ * the slope its face's normal gives under an orthographic camera: the same+ * depth, for a flat face. That needs the picture's size in pixels+ * (`facePixels`, which `draw` in `materials.ts` keeps).*/export const faceBiasBit: ShaderBit = {name: "inkline-face-bias",+ bindings: { material: { facePixels: "vec2<f32>" } },+ gpu: {+ vertex: {+ afterTransform: `{+ let faceN = (camera.uViewMatrix * vec4<f32>(worldNormal, 0.0)).xyz;+ let faceP = camera.uProjectionMatrix;+ let faceAcross = abs(faceN.x) / abs(faceP[0][0] * material.facePixels.x);+ let faceUp = abs(faceN.y) / abs(faceP[1][1] * material.facePixels.y);+ let faceSlope = abs(faceP[2][2]) * 2.0 * max(faceAcross, faceUp) / max(abs(faceN.z), 1e-6);+ clipPosition.z = min(clipPosition.z + (6.0 * faceSlope + 2.0 / 16777216.0) * clipPosition.w, clipPosition.w);+ }`+ }+ },gl: { fragment: { end: `{ float faceSlope = max(abs(dFdx(gl_FragCoord.z)), abs(dFdy(gl_FragCoord.z))); gl_FragDepth = gl_FragCoord.z + 6.0 * faceSlope + 2.0 / 16777216.0; }` } }}-/**- * Shared models in the live town: each copy's colour (already tinted) and- * opacity, and its building's wear, hazards and size for `surfaceBit`.- */-export const instanceBit: ShaderBit = {- name: "inkline-instance",- bindings: { instance: { tint: "vec4<f32>", state: "vec4<f32>", hazards: "vec4<f32>", bounds: "vec4<f32>" }, material: { opacity: "f32" } },- gl: { fragment: { material: `{ albedo = instance.tint.rgb; alpha = instance.tint.a * material.opacity; }` } }-}-/** One model drawn alone: its colour and opacity from the material. */+/** A copy of a shared model in the live town: its colour (already tinted) and opacity from its own material. */export const plainBit: ShaderBit = {name: "inkline-plain",bindings: { material: { color: "vec4<f32>" } },+ gpu: { fragment: { material: `{ albedo = material.color.rgb; alpha = material.color.a; }` } },gl: { fragment: { material: `{ albedo = material.color.rgb; alpha = material.color.a; }` } }}@@ -53,6 +72,16 @@ export const inkSilhouetteBit: ShaderBit = {name: "inkline-silhouette",attributes: { aInkNormalA: "float32x3", aInkNormalB: "float32x3" },interStage: { vInkEdge: "f32" },+ gpu: {+ vertex: {+ beforeTransform: `{+ let toCamera = vec3<f32>(camera.uViewMatrix[0][2], camera.uViewMatrix[1][2], camera.uViewMatrix[2][2]);+ let turn = mat3x3<f32>(modelMatrix[0].xyz, modelMatrix[1].xyz, modelMatrix[2].xyz);+ output.vInkEdge = step(0.0, -dot(turn * input.aInkNormalA, toCamera) * dot(turn * input.aInkNormalB, toCamera));+ }`+ },+ fragment: { material: `{ if (input.vInkEdge < 0.5) { discard; } }` }+ },gl: {vertex: {beforeTransform: `{@@ -75,6 +104,40 @@ export const inkLineBit: ShaderBit = {attributes: { aLineStart: "float32x3", aLineEnd: "float32x3", aLineCorner: "float32x2" },interStage: { vLineAlong: "f32", vLineAcross: "f32", vLineLength: "f32" },bindings: { material: { lineWidth: "f32", lineAlpha: "f32" } },+ gpu: {+ vertex: {+ afterTransform: `{+ let lineView = camera.uViewMatrix * modelMatrix;+ let lineA = (lineView * vec4<f32>(input.aLineStart, 1.0)).xyz;+ let lineB = (lineView * vec4<f32>(input.aLineEnd, 1.0)).xyz;+ let lineD = lineB.xy - lineA.xy;+ let lineL = length(lineD);+ var lineDir = vec2<f32>(1.0, 0.0);+ if (lineL > 1e-6) { lineDir = lineD / lineL; }+ let linePerp = vec2<f32>(-lineDir.y, lineDir.x);+ // One world unit beyond the stroke on every side, for its soft edge at any zoom.+ let lineReach = material.lineWidth * 0.5 + 1.0;+ let lineFar = input.aLineCorner.x > 0.5;+ let lineExt = select(-lineReach, lineReach, lineFar);+ let lineP = select(lineA, lineB, lineFar) + vec3<f32>(lineDir * lineExt + linePerp * input.aLineCorner.y * lineReach, 0.0);+ output.vLineAlong = select(0.0, lineL, lineFar) + lineExt;+ output.vLineAcross = input.aLineCorner.y * lineReach;+ output.vLineLength = lineL;+ clipPosition = camera.uProjectionMatrix * vec4<f32>(lineP, 1.0);+ }`+ },+ fragment: {+ material: `{+ var lineD = abs(input.vLineAcross);+ if (input.vLineAlong < 0.0) { lineD = length(vec2<f32>(input.vLineAlong, input.vLineAcross)); }+ else if (input.vLineAlong > input.vLineLength) { lineD = length(vec2<f32>(input.vLineAlong - input.vLineLength, input.vLineAcross)); }+ let lineNorm = lineD / max(material.lineWidth, 1e-4);+ let lineSoft = 0.5 * fwidth(lineNorm);+ alpha = (1.0 - smoothstep(0.5 - lineSoft, 0.5 + lineSoft, lineNorm)) * material.lineAlpha;+ if (alpha < 0.004) { discard; }+ }`+ }+ },gl: {vertex: {afterTransform: `{@@ -153,29 +216,77 @@ if(surfBounds.w>0.5){albedo=inkToDisplay(dc);}`+/** `shade` in WGSL, line for line. */+const shadeGpu = `+if(surfBounds.w>0.5){+ var dc=inkToLinear(albedo);+ let p=input.vSurfacePosition; let n=normalize(input.vSurfaceNormal);+ let H=surfBounds.y; let halfWidth=surfBounds.x;+ let wear=surfState.x; let care=surfState.y; let snow=surfState.z; let burn=surfState.w;+ let fireRisk=surfHazards.x; let health=surfHazards.y; let order=surfHazards.z; let sick=surfHazards.w;+ let roof=step(H-0.15,p.y)*smoothstep(0.12,0.45,abs(n.y));+ let wall=(1.0-roof)*step(0.1,p.y)*step(p.y,H+0.1)*(1.0-surfGlass);+ let uv=select(p.xy,p.zy,abs(n.x)>abs(n.z));+ let g=inkNoise(uv*0.32+surfBounds.z);+ let lower=1.0-smoothstep(0.0,H*0.7,p.y);+ let dirt=wear*wall*(0.16+0.45*lower+0.20*g);+ dc=mix(dc,inkRGB(vec3<f32>(0.60,0.62,0.52)),dirt);+ let plaster=wear*wall*smoothstep(0.58,0.76,g)*(0.4+0.6*lower);+ let course=floor(uv.y/1.8);+ let brick=vec2<f32>((uv.x+(course-2.0*floor(course*0.5))*1.8)/3.6,uv.y/1.8);+ let mortar=max(1.0-smoothstep(0.025,0.08,fract(brick.y)),1.0-smoothstep(0.025,0.06,fract(brick.x)));+ dc=mix(dc,inkRGB(mix(vec3<f32>(0.68,0.53,0.40),vec3<f32>(0.84,0.79,0.68),mortar)),plaster*0.9);+ let crack=abs(uv.x-halfWidth*0.36-sin(uv.y*0.64)*0.48-sin(uv.y*1.5)*0.16);+ let crackMask=(1.0-smoothstep(0.045,0.10,crack))*smoothstep(H*0.25,H*0.4,p.y)*step(p.y,H*0.92);+ dc=mix(dc,inkRGB(vec3<f32>(0.39,0.43,0.36)),crackMask*wear*wall*0.85);+ let moss=roof*wear*smoothstep(0.3,0.8,inkNoise(p.xz*0.30))*0.45;+ dc=mix(dc,inkRGB(vec3<f32>(0.47,0.54,0.37)),moss);+ dc=mix(dc,inkRGB(vec3<f32>(0.97,0.96,0.90)),care*wall*0.12);+ let damp=(health*0.45+sick*0.65)*wall*lower*smoothstep(0.35,0.75,g);+ dc=mix(dc,inkRGB(vec3<f32>(0.48,0.59,0.43)),damp);+ if(surfGlass>0.5){+ let fissure=abs(fract((uv.x+uv.y*0.38+sin(uv.y*2.0)*0.18)/3.2)-0.5);+ let broken=(1.0-smoothstep(0.025,0.065,fissure))*order;+ dc=mix(dc,inkRGB(vec3<f32>(0.25,0.31,0.29)),broken*0.95);+ dc=mix(dc,inkRGB(vec3<f32>(0.58,0.69,0.45)),sick*0.35);+ let warm=care*0.6+burn*(0.75+0.15*sin(surfTime*9.0+p.x*2.0));+ dc=mix(dc,inkRGB(vec3<f32>(1.0,0.76,0.36)),warm);+ }+ let soot=(roof+wall*0.5)*burn*(0.35+inkNoise(p.xz*0.27)*0.50);+ dc=mix(dc,inkRGB(vec3<f32>(0.28,0.31,0.27)),soot);+ let heat=roof*burn*pow(inkNoise(p.xz*0.45+vec2<f32>(0.0,-surfTime*1.3)),5.0);+ dc=mix(dc,inkRGB(vec3<f32>(0.99,0.49,0.19)),heat*0.75);+ dc=mix(dc,inkRGB(vec3<f32>(0.80,0.63,0.43)),roof*fireRisk*0.15*(0.7+0.3*sin(surfTime*3.0)));+ let frost=roof*snow*smoothstep(-0.05,0.22,inkNoise(p.xz*0.65)+smoothstep(H,H+2.0,p.y)*0.15);+ dc=mix(dc,inkRGB(vec3<f32>(0.97,0.98,0.96)),frost);+ albedo=inkToDisplay(dc);+}+`/**- * A structure's surface, worn, cared for, snowed on, burning: from each- * shared copy's instance values in the town, or from the material's own for- * one model drawn alone (the catalogue and the labs).+ * A structure's surface, worn, cared for, snowed on, burning, from its+ * material's state. Its time is the view's clock for a copy in the town+ * (`clock`), or the material's own for a model the catalogue and the labs+ * draw at a time they choose (`material`).*/-export function surfaceBit(from: "instance" | "material"): ShaderBit {- const read = from === "instance"- ? `vec4 surfState=instance.state; vec4 surfHazards=instance.hazards; vec4 surfBounds=instance.bounds; float surfTime=uTime;`- : `vec4 surfState=material.surfaceState; vec4 surfHazards=material.surfaceHazards; vec4 surfBounds=material.surfaceBounds; float surfTime=material.surfaceTime;`+export function surfaceBit(time: "clock" | "material"): ShaderBit {+ const read = `vec4 surfState=material.surfaceState; vec4 surfHazards=material.surfaceHazards; vec4 surfBounds=material.surfaceBounds; float surfTime=${time === "clock" ? "uTime" : "material.surfaceTime"};`+ const readGpu = `let surfState=material.surfaceState; let surfHazards=material.surfaceHazards; let surfBounds=material.surfaceBounds; let surfTime=${time === "clock" ? "global.uTime" : "material.surfaceTime"};`return {- name: `inkline-surface-${from}`,+ name: `inkline-surface-${time}`,requires: [inkCommonBit],interStage: { vSurfacePosition: "vec3<f32>", vSurfaceNormal: "vec3<f32>" },- bindings: from === "instance"- ? { instance: { tint: "vec4<f32>", state: "vec4<f32>", hazards: "vec4<f32>", bounds: "vec4<f32>" }, material: { surfaceGlass: "f32" } }- : { material: { surfaceGlass: "f32", surfaceState: "vec4<f32>", surfaceHazards: "vec4<f32>", surfaceBounds: "vec4<f32>", surfaceTime: "f32" } },+ bindings: { material: { surfaceGlass: "f32", surfaceState: "vec4<f32>", surfaceHazards: "vec4<f32>", surfaceBounds: "vec4<f32>", ...(time === "material" ? { surfaceTime: "f32" as const } : {}) } },+ gpu: {+ vertex: { beforeTransform: `{ output.vSurfacePosition = position.xyz; output.vSurfaceNormal = normal; }` },+ fragment: { material: `{ ${readGpu} let surfGlass=material.surfaceGlass; ${shadeGpu} }` }+ },gl: {vertex: { beforeTransform: `{ vSurfacePosition = position.xyz; vSurfaceNormal = normal; }` },fragment: { material: `{ ${read} float surfGlass=material.surfaceGlass; ${shade} }` }}}}-export const instanceSurfaceBit = surfaceBit("instance")export const materialSurfaceBit = surfaceBit("material")+export const copySurfaceBit = surfaceBit("clock")/** Glass and lit-window colours: the surface shading treats them as panes, not walls. */export const GLASS = [0xdbe6ea, 0xf3dca6, 0xc9d6ee, 0xd5dae4, 0xdbe9e7]diff --git a/src/render/pixi3d/fish-effects.ts b/src/render/pixi3d/fish-effects.tsindex 2d02d1b..4c05135 100644--- a/src/render/pixi3d/fish-effects.ts+++ b/src/render/pixi3d/fish-effects.ts@@ -13,6 +13,26 @@ const fishBit: ShaderBit = {attributes: { aFishPoint: "float32x2", aFishSeed: "float32" },interStage: { vFishPoint: "vec2<f32>", vFishPhase: "f32" },bindings: { material: { time: "f32" } },+ gpu: {+ vertex: {+ beforeTransform: `{ output.vFishPoint = input.aFishPoint; output.vFishPhase = input.aFishSeed; }`+ },+ fragment: {+ material: `{+ let at = input.vFishPoint - vec2<f32>(fract(input.vFishPhase * 7.13) - 0.5, fract(input.vFishPhase * 3.71) - 0.5) * 0.5;+ let d = length(at);+ let age = fract(material.time * 0.058 + input.vFishPhase) / 0.3;+ if (age > 1.0) { discard; }+ let r = 0.08 + age * 0.5;+ let ring = 1.0 - smoothstep(0.0, 0.03, abs(d - r));+ let fade = smoothstep(0.0, 0.15, age) * (1.0 - age);+ let edge = 1.0 - smoothstep(0.85, 1.0, max(abs(input.vFishPoint.x), abs(input.vFishPoint.y)));+ alpha = ring * fade * edge * 0.38;+ if (alpha < 0.01) { discard; }+ albedo = inkToDisplay(inkRGB(vec3<f32>(0.32, 0.45, 0.52)));+ }`+ }+ },gl: {vertex: {beforeTransform: `{ vFishPoint = aFishPoint; vFishPhase = aFishSeed; }`diff --git a/src/render/pixi3d/fountain-effects.ts b/src/render/pixi3d/fountain-effects.tsindex 07487d2..8740ad9 100644--- a/src/render/pixi3d/fountain-effects.ts+++ b/src/render/pixi3d/fountain-effects.ts@@ -14,6 +14,24 @@ const dropsBit: ShaderBit = {attributes: { aWaterPhase: "float32", aJetAngle: "float32" },interStage: { vDropAge: "f32", vDropPhase: "f32" },bindings: { material: { time: "f32", radius: "f32", level: "f32", nozzle: "f32" } },+ gpu: {+ vertex: {+ beforeTransform: `{+ let age = fract(material.time * 0.85 + input.aWaterPhase);+ let reach = material.radius * 0.84 * age;+ let h = mix(material.nozzle, material.level, age) + 4.0 * age * (1.0 - age) * 6.9282;+ let centre = vec3<f32>(cos(input.aJetAngle) * reach, h, sin(input.aJetAngle) * reach);+ position = vec4<f32>(position.xyz * vec3<f32>(0.8, 1.7, 0.8) + centre, 1.0);+ output.vDropAge = age; output.vDropPhase = input.aWaterPhase;+ }`+ },+ fragment: {+ material: `{+ alpha = smoothstep(0.0, 0.07, input.vDropAge) * (1.0 - smoothstep(0.94, 1.0, input.vDropAge)) * 0.68;+ albedo = inkToDisplay(inkRGB(mix(vec3<f32>(0.65, 0.78, 0.82), vec3<f32>(0.96, 0.99, 0.96), fract(input.vDropPhase * 13.0))));+ }`+ }+ },gl: {vertex: {beforeTransform: `{@@ -39,6 +57,23 @@ const poolBit: ShaderBit = {requires: [inkCommonBit],interStage: { vPoolPoint: "vec2<f32>" },bindings: { material: { time: "f32", radius: "f32" } },+ gpu: {+ vertex: { beforeTransform: `{ output.vPoolPoint = position.xz / material.radius; }` },+ fragment: {+ material: `{+ var waves = 0.0;+ for (var i = 0; i < 4; i++) {+ let a = f32(i) * 1.5707963 + 0.7853982;+ let d = length(input.vPoolPoint - vec2<f32>(cos(a), sin(a)) * 0.84);+ waves += pow(max(0.0, sin(d * 28.0 - material.time * 6.0)), 14.0) * exp(-d * 7.0);+ }+ let edge = 1.0 - smoothstep(0.96, 1.0, length(input.vPoolPoint));+ let shimmer = sin(input.vPoolPoint.x * 17.0 + material.time) * sin(input.vPoolPoint.y * 13.0 - material.time * 0.7) * 0.015;+ albedo = inkToDisplay(inkRGB(vec3<f32>(0.94, 0.98, 0.97)));+ alpha = edge * (0.025 + waves * 0.28 + shimmer);+ }`+ }+ },gl: {vertex: { beforeTransform: `{ vPoolPoint = position.xz / material.radius; }` },fragment: {diff --git a/src/render/pixi3d/gpu.ts b/src/render/pixi3d/gpu.tsindex b76e35d..788a607 100644--- a/src/render/pixi3d/gpu.ts+++ b/src/render/pixi3d/gpu.ts@@ -11,6 +11,17 @@ import { Buffer, BufferUsage, type Attribute, type VertexFormat } from "pixi.js"import { bounds, type MeshData } from "./mesh/geometry.ts"import type { Vec3 } from "./mesh/vec3.ts"+/**+ * The renderer to ask Pixi for: WebGPU where the browser's GPU can run Pixi 3D on it, WebGL elsewhere.+ * `?renderer=webgl` in the page's address asks for WebGL outright.+ */+export async function backend(): Promise<"webgpu" | "webgl"> {+ if (new URLSearchParams(location.search).get("renderer") === "webgl") return "webgl"+ // Pixi 3D needs this feature on WebGPU, and Pixi would not fall back to WebGL by itself without it.+ const adapter = await navigator.gpu?.requestAdapter().catch(() => null)+ return adapter?.features.has("indirect-first-instance") ? "webgpu" : "webgl"+}+const formats: Record<number, VertexFormat> = { 1: "float32", 2: "float32x2", 3: "float32x3", 4: "float32x4" }const attribute = (data: Float32Array, size: number): Attribute => ({buffer: new Buffer({ data, usage: BufferUsage.VERTEX | BufferUsage.COPY_DST }),diff --git a/src/render/pixi3d/materials.ts b/src/render/pixi3d/materials.tsindex 2c3d22a..beb2e6e 100644--- a/src/render/pixi3d/materials.ts+++ b/src/render/pixi3d/materials.ts@@ -4,12 +4,13 @@** - `partMaterial` for one model drawn alone (the map's ground layers, the* catalogue, the labs): its colour on the material.- * - `instanceMaterial` for the town's shared models (`pool.ts`): colour,- * opacity and surface state per copy, so one material serves every model- * with the same kind of part.+ * - `copyMaterial` for the town's shared models (`pool.ts`): each copy's+ * parts have materials of their own, with its colour, opacity and surface+ * state.*/-import { FlatMaterial, type ShaderBit } from "@pixi/3d"-import { faceBiasBit, GLASS, inkLineBit, inkSilhouetteBit, instanceBit, instanceSurfaceBit, materialSurfaceBit } from "./bits.ts"+import { FlatMaterial, type ShaderBit, type View3D } from "@pixi/3d"+import type { Renderer, RenderTexture } from "pixi.js"+import { copySurfaceBit, faceBiasBit, GLASS, inkLineBit, inkSilhouetteBit, materialSurfaceBit, plainBit } from "./bits.ts"import type { InkPart, PartRole } from "./assets/ink-mesh.ts"import type { SurfaceState } from "./surface-state.ts"@@ -17,6 +18,35 @@ const roleBits: Record<PartRole, ReadonlyArray<ShaderBit>> = { fill: [faceBiasBiconst ribbon = (role: PartRole) => role === "line" || role === "edge"const doubleSided = (role: PartRole) => role === "fill" || ribbon(role)+/** The materials with faces, which `faceBiasBit` moves back by the size in pixels of the picture being drawn. */+const faces = new Set<FlatMaterial>()+let pixels: readonly [number, number] = [1, 1]+function face(material: FlatMaterial) {+ material.data.facePixels = pixels+ faces.add(material)+}+/**+ * Tells the faces the size in pixels of `view`'s next picture: the part of the view its camera's viewport takes,+ * at `target`'s pixels to a unit, or the canvas's.+ */+export function sizeFaces(renderer: Renderer, view: View3D, target?: RenderTexture) {+ const resolution = target?.source.resolution ?? renderer.resolution+ const width = view.width * view.camera.viewport.width * resolution, height = view.height * view.camera.viewport.height * resolution+ if (width === pixels[0] && height === pixels[1]) return+ pixels = [width, height]+ for (const material of faces) material.data.facePixels = pixels+}+/** Draws `view` on the canvas, or into `options.target`. Draw every picture through here (or after `sizeFaces`), so its faces sit behind their ink. */+export function draw(renderer: Renderer, view: View3D, options: { target?: RenderTexture; clear?: boolean; clearColor?: [number, number, number, number] } = {}) {+ sizeFaces(renderer, view, options.target)+ renderer.render({ container: view, ...options })+}+/** Destroys a material `partMaterial` or `copyMaterial` made. */+export function releaseMaterial(material: FlatMaterial) {+ faces.delete(material)+ material.destroy()+}+/** A part of one model; `surface` gives its faces the structure shading, with its own state. */export function partMaterial(part: InkPart, surface: boolean): FlatMaterial {const material = new FlatMaterial({@@ -35,6 +65,7 @@ export function partMaterial(part: InkPart, surface: boolean): FlatMaterial {material.data.surfaceGlass = Number(GLASS.includes(part.color))material.data.surfaceTime = 0}+ if (part.role === "fill") face(material)return material}/** Writes a structure's surface state, its size (`bounds`: half width, height, seed, on) and the time into its material. */@@ -45,21 +76,16 @@ export function setSurface(material: FlatMaterial, state: SurfaceState, bounds:material.data.surfaceTime = time}-const shared = new Map<string, FlatMaterial>()-/** The material every shared copy of such a part draws with: `blend` for a copy fading or see-through. */-export function instanceMaterial(part: InkPart, blend: boolean): FlatMaterial {- const glass = part.role === "fill" && GLASS.includes(part.color)- const key = `${part.role}/${part.opacity}/${glass}/${blend}`- let material = shared.get(key)- if (!material) {- material = new FlatMaterial({- alphaMode: blend ? "blend" : "opaque",- doubleSided: doubleSided(part.role),- extraBits: [instanceBit, ...(part.role === "fill" ? [instanceSurfaceBit] : []), ...roleBits[part.role]]- })- material.data.opacity = part.opacity- if (part.role === "fill") material.data.surfaceGlass = Number(glass)- shared.set(key, material)+/** The material of one part of one copy of a shared model: its colour, opacity and surface state are its own. */+export function copyMaterial(part: InkPart, blend: boolean): FlatMaterial {+ const material = new FlatMaterial({+ alphaMode: blend ? "blend" : "opaque",+ doubleSided: doubleSided(part.role),+ extraBits: [plainBit, ...(part.role === "fill" ? [copySurfaceBit] : []), ...roleBits[part.role]]+ })+ if (part.role === "fill") {+ material.data.surfaceGlass = Number(GLASS.includes(part.color))+ face(material)}return material}diff --git a/src/render/pixi3d/pool.ts b/src/render/pixi3d/pool.tsindex d4c94ff..4d136b1 100644--- a/src/render/pixi3d/pool.ts+++ b/src/render/pixi3d/pool.ts@@ -1,9 +1,9 @@-import { BatchedMesh3D, Container3D, Matrix4, RenderPassBit, type FlatMaterial, type Geometry3D } from "@pixi/3d"+import { Container3D, Matrix4, Mesh3D, type FlatMaterial, type Geometry3D } from "@pixi/3d"import type { InkAsset } from "./assets/primitives.ts"import { inkMesh, type InkPart } from "./assets/ink-mesh.ts"import { surfaceState, type SurfaceState } from "./surface-state.ts"import { tinted, toGeometry } from "./gpu.ts"-import { instanceMaterial } from "./materials.ts"+import { copyMaterial, releaseMaterial } from "./materials.ts"import { bounds, triangleCount, type MeshData } from "./mesh/geometry.ts"import { rayHitsBox, rayTriangle, type Ray } from "./mesh/ray.ts"import type { Vec3 } from "./mesh/vec3.ts"@@ -11,8 +11,6 @@ import type { Vec3 } from "./mesh/vec3.ts"interface Part {readonly part: InkPartreadonly geometry: Geometry3D- readonly opaque: FlatMaterial- readonly blend: FlatMaterial}interface Template {readonly key: string@@ -21,16 +19,22 @@ interface Template {readonly box: readonly [Vec3, Vec3]readonly triangles: numberreadonly handles: Set<ModelHandle>- batch: BatchedMesh3D | null- capacity: number- /** Each slot's material: 0 none (drawn by no pass), 1 opaque, 2 blended. */- modes: Uint8Array- /** The copies drawn at the last flush, in slot order. */+ /** The copies drawn at the last flush. */drawn: Array<ModelHandle>+ /** The copies holding meshes of this model, shown or hidden. */+ readonly dressed: Set<ModelHandle>used: number}+/** One part of one copy: a mesh under the copy's root, with materials of its own. */+interface Piece {+ readonly part: InkPart+ readonly mesh: Mesh3D+ readonly opaque: FlatMaterial+ /** Made the first time the copy fades. */+ blend: FlatMaterial | null+}-/** One logical model. Its root owns transforms; shared GPU instances draw it. */+/** One logical model. Its root owns transforms; its parts are meshes under it that share the model's geometry. */export class ModelHandle {readonly root = new Container3D()/** A colour over the whole model (sRGB hex), multiplied in linear light. */@@ -42,6 +46,11 @@ export class ModelHandle {/** Its structure's half width and height (world units), a noise seed, and 1 to shade it as one; or all 0. */effectBounds: [number, number, number, number] = [0, 0, 0, 0]template: Template | null = null+ pieces: Array<Piece> = []+ /** Its meshes for every model it has been, hidden while it is another: a walker steps through a few, over and over. */+ readonly sets = new Map<Template, Array<Piece>>()+ /** What its materials were last given, to write them only when something changes. */+ sent: { values: Float64Array; colors: ReadonlyMap<number, number> | null } | null = nullreadonly pool: ModelPoolreadonly entity: number | nullreadonly pickCell: { x: number; y: number } | null@@ -52,9 +61,22 @@ export class ModelHandle {}use(key: string, create: () => InkAsset) {if (this.template?.key === key) return- this.pool.release(this)- this.template = this.pool.acquire(key, create)- this.template.handles.add(this)+ this.pool.leave(this)+ const template = this.pool.acquire(key, create)+ this.template = template+ template.handles.add(this)+ let pieces = this.sets.get(template)+ if (!pieces) {+ pieces = template.parts.map(({ part, geometry }) => {+ const opaque = copyMaterial(part, false), mesh = new Mesh3D({ geometry, material: opaque, castShadow: false })+ this.root.addChild(mesh)+ return { part, mesh, opaque, blend: null }+ })+ this.sets.set(template, pieces)+ template.dressed.add(this)+ }+ this.pieces = pieces+ this.sent = null}dispose() {this.pool.release(this)@@ -66,20 +88,19 @@ const visible = (node: Container3D) => {for (let p: Container3D | null = node; p; p = p.parent) if (!p.visible) return falsereturn true}-const pass = (mode: number) => (mode === 2 ? RenderPassBit.TRANSPARENT : mode === 1 ? RenderPassBit.OPAQUE : 0)/**- * Geometry and materials are built once per visual state. Repeated homes,- * trees and walkers share one batch a model, a slot for each part of each- * copy, with entity IDs kept for picking. Unused construction and animation- * states have a bounded cache.+ * Geometry is built once per visual state and shared by every copy. Each copy+ * is plain meshes under its own root, so the scene graph places it and the+ * engine draws the copies of a part together. Entity IDs are kept for picking.+ * Unused construction and animation states have a bounded cache.*/export class ModelPool {- readonly root = new Container3D({ label: "models" })private templates = new Map<string, Template>()private stamp = 0private matrix = new Matrix4()private inverse = new Matrix4()+ private color = new Float32Array(4)acquire(key: string, create: () => InkAsset): Template {let entry = this.templates.get(key)if (!entry) {@@ -89,17 +110,15 @@ export class ModelPool {const extents = solid.map((p) => bounds(p.mesh))entry = {key,- parts: solid.map((part) => ({ part, geometry: toGeometry(part.mesh), opaque: instanceMaterial(part, false), blend: instanceMaterial(part, true) })),+ parts: solid.map((part) => ({ part, geometry: toGeometry(part.mesh) })),box: [[Math.min(...extents.map((e) => e[0][0])), Math.min(...extents.map((e) => e[0][1])), Math.min(...extents.map((e) => e[0][2]))],[Math.max(...extents.map((e) => e[1][0])), Math.max(...extents.map((e) => e[1][1])), Math.max(...extents.map((e) => e[1][2]))]],triangles: solid.reduce((n, p) => n + triangleCount(p.mesh), 0),handles: new Set(),- batch: null,- capacity: 0,- modes: new Uint8Array(),drawn: [],+ dressed: new Set(),used: ++this.stamp}this.templates.set(key, entry)@@ -107,70 +126,56 @@ export class ModelPool {entry.used = ++this.stampreturn entry}- release(handle: ModelHandle) {+ /** The copy stops being its model, and keeps that model's meshes hidden. */+ leave(handle: ModelHandle) {if (!handle.template) return+ for (const { mesh } of handle.pieces) mesh.visible = false+ handle.pieces = []handle.template.handles.delete(handle)handle.template.used = ++this.stamphandle.template = null}+ private strip(handle: ModelHandle, template: Template) {+ for (const { mesh, opaque, blend } of handle.sets.get(template) ?? []) {+ mesh.destroy()+ releaseMaterial(opaque)+ if (blend) releaseMaterial(blend)+ }+ handle.sets.delete(template)+ template.dressed.delete(handle)+ }+ release(handle: ModelHandle) {+ this.leave(handle)+ for (const template of [...handle.sets.keys()]) this.strip(handle, template)+ }+ /** Gives each copy's materials its colour, opacity and surface state, where they changed. */flush() {for (const entry of this.templates.values()) {- const handles = [...entry.handles].filter((h) => h.alpha > 0 && visible(h.root))- entry.drawn = handles- if (!handles.length || !entry.parts.length) {- if (entry.batch) entry.batch.visible = false- continue- }- const P = entry.parts.length- if (entry.capacity < handles.length) {- entry.batch?.destroy()- entry.capacity = 2 ** Math.ceil(Math.log2(Math.max(4, handles.length)))- const vec4 = (value: [number, number, number, number]) => ({ value, type: "vec4<f32>" as const })- entry.batch = new BatchedMesh3D({- size: entry.capacity * P,- label: entry.key,- // Copies off screen are skipped: most of a large town is, close in.- cull: "gpu",- instanceData: { tint: vec4([1, 1, 1, 1]), state: vec4([0, 0, 0, 0]), hazards: vec4([0, 0, 0, 0]), bounds: vec4([0, 0, 0, 0]) }- })- for (let slot = 0; slot < entry.capacity * P; slot++) entry.batch.setGeometryAt(slot, entry.parts[slot % P]!.geometry)- entry.modes = new Uint8Array(entry.capacity * P)- this.root.addChild(entry.batch)- }- const batch = entry.batch!- batch.visible = true- const matrices = batch.matrices, data = batch.instanceData, f = data.fields- handles.forEach((handle, i) => {- const world = handle.root.getGlobalTransform(this.matrix).elements+ entry.drawn = [...entry.handles].filter((h) => h.alpha > 0 && visible(h.root))+ for (const handle of entry.handles) {const alpha = Math.min(1, Math.max(0, handle.alpha)), e = handle.effects, b = handle.effectBounds- for (let p = 0; p < P; p++) {- const slot = i * P + p, part = entry.parts[p]!.part- matrices.data.set(world, matrices.offset + slot * matrices.stride)- const o = data.offset + slot * data.stride- tinted(handle.colors?.get(part.color) ?? part.color, handle.tint, data.data, o + f.tint!)- data.data[o + f.tint! + 3] = alpha- data.data.set([e.wear, e.care, e.snow, e.burning], o + f.state!)- data.data.set([e.fireRisk, e.health, e.order, e.sick], o + f.hazards!)- data.data.set(b, o + f.bounds!)- const mode = alpha < 1 || part.opacity < 1 ? 2 : 1- if (entry.modes[slot] !== mode) {- batch.setMaterialAt(slot, mode === 2 ? entry.parts[p]!.blend : entry.parts[p]!.opaque)- batch.setPassesAt(slot, pass(mode))- entry.modes[slot] = mode+ const values = [handle.tint, alpha, e.wear, e.care, e.snow, e.burning, e.fireRisk, e.health, e.order, e.sick, b[0], b[1], b[2], b[3]]+ if (handle.sent && handle.sent.colors === handle.colors && values.every((v, i) => v === handle.sent!.values[i])) continue+ handle.sent = { values: Float64Array.from(values), colors: handle.colors }+ for (const piece of handle.pieces) {+ const { part, mesh } = piece+ if (mesh.visible !== alpha > 0) mesh.visible = alpha > 0+ const material = alpha < 1 || part.opacity < 1 ? (piece.blend ??= copyMaterial(part, true)) : piece.opaque+ if (mesh.material !== material) mesh.material = material+ tinted(handle.colors?.get(part.color) ?? part.color, handle.tint, this.color, 0)+ material.data.color = [this.color[0]!, this.color[1]!, this.color[2]!, alpha * part.opacity]+ if (part.role === "fill") {+ material.data.surfaceState = [e.wear, e.care, e.snow, e.burning]+ material.data.surfaceHazards = [e.fireRisk, e.health, e.order, e.sick]+ material.data.surfaceBounds = [...b]}}- })- for (let slot = handles.length * P; slot < entry.capacity * P; slot++)- if (entry.modes[slot] !== 0) {- batch.setPassesAt(slot, 0)- entry.modes[slot] = 0- }- matrices.update()- data.update()+ }}const idle = [...this.templates.values()].filter((e) => !e.handles.size).sort((a, b) => a.used - b.used)for (const entry of idle.slice(0, Math.max(0, idle.length - 64))) {- this.disposeEntry(entry)+ for (const handle of [...entry.dressed]) this.strip(handle, entry)+ for (const { geometry } of entry.parts) geometry.destroy()this.templates.delete(entry.key)}}@@ -207,12 +212,11 @@ export class ModelPool {triangles: drawn.reduce((n, e) => n + e.triangles * e.drawn.length, 0)}}- private disposeEntry(entry: Template) {- entry.batch?.destroy()- for (const { geometry } of entry.parts) geometry.destroy()- }dispose() {- for (const entry of this.templates.values()) this.disposeEntry(entry)+ for (const entry of this.templates.values()) {+ for (const handle of [...entry.dressed]) this.release(handle)+ for (const { geometry } of entry.parts) geometry.destroy()+ }this.templates.clear()}}diff --git a/src/render/pixi3d/portrait.ts b/src/render/pixi3d/portrait.tsindex 2efcef8..756ce51 100644--- a/src/render/pixi3d/portrait.ts+++ b/src/render/pixi3d/portrait.ts@@ -8,6 +8,7 @@import { View3D } from "@pixi/3d"import { RenderTexture, type Renderer } from "pixi.js"import { buildAsset } from "./assets/renderer.ts"+import { draw } from "./materials.ts"import type { InkAsset } from "./assets/primitives.ts"import { add, cross, dot, normalize, scale as times, sub, type Vec3 } from "./mesh/vec3.ts"@@ -36,7 +37,7 @@ export function portrait(renderer: Renderer, asset: InkAsset, scale = 2, marginview.camera.lookAt({ x: shift[0], y: shift[1], z: shift[2] })view.root.addChild(model.group)const target = RenderTexture.create({ width, height, resolution: scale, antialias: true })- renderer.render({ container: view, target, clearColor: [0, 0, 0, 0] })+ draw(renderer, view, { target, clearColor: [0, 0, 0, 0] })const url = (renderer.extract.canvas(target) as HTMLCanvasElement).toDataURL("image/png")target.destroy(true)model.dispose()diff --git a/src/render/pixi3d/scene.ts b/src/render/pixi3d/scene.tsindex c1b0819..34908b8 100644--- a/src/render/pixi3d/scene.ts+++ b/src/render/pixi3d/scene.ts@@ -13,7 +13,8 @@ import { ModelHandle, ModelPool } from "./pool.ts"import { groundAsset, landAsset, overlayAsset, previewAsset } from "./models.ts"import { parkAsset } from "./assets/town-props.ts"import { FishWater } from "./fish-effects.ts"-import { channels } from "./gpu.ts"+import { backend, channels } from "./gpu.ts"+import { draw, sizeFaces } from "./materials.ts"import type { ParkCell } from "../../game/world/appeal.ts"/** Where the camera stands: the grid cell it looks at, its zoom, and its angles. */@@ -37,7 +38,8 @@ const LAND = 0xe2e9e6, FROSTED = 0xe6edf1/*** Counts what the GPU is asked to draw each frame (Pixi has no `renderer.info`):- * draw calls, and triangles, instances included.+ * draw calls, and triangles, instances included. On WebGL only: on WebGPU the+ * GPU culls the copies and decides the counts itself, so both stay 0.*/export function drawCounter(renderer: Renderer) {const counts = { calls: 0, triangles: 0 }@@ -109,7 +111,7 @@ export class GameScene {static async create(mount: HTMLElement) {const app = new Application()await app.init({- preference: "webgl",+ preference: await backend(),antialias: true,backgroundColor: LAND,// The page's stylesheet sizes the canvas; its buffer follows the pixel ratio.@@ -135,7 +137,7 @@ export class GameScene {canvas.setAttribute("aria-label", "Inkline Town 3D map. Drag to pan, right-drag to rotate, wheel to zoom.")canvas.tabIndex = 0mount.append(canvas)- this.world.root.addChild(this.objects, this.pool.root, this.fish.group)+ this.world.root.addChild(this.objects, this.fish.group)this.observer = new ResizeObserver(() => this.resize())this.observer.observe(mount)this.camera.zoom = innerWidth >= 1000 ? 1 : 0.65@@ -336,6 +338,7 @@ export class GameScene {this.pool.flush()this.counter.calls = 0this.counter.triangles = 0+ sizeFaces(this.app.renderer, this.world)this.app.render()this.drawn = { ...this.counter }}@@ -357,6 +360,7 @@ export class GameScene {const pool = this.pool.stats()return {renderer: "pixi3d",+ backend: this.app.renderer.name,frames: this.frames,frameMS: this.frameMS,drawCalls: this.drawn.calls,@@ -403,7 +407,7 @@ export class GameScene {this.camera.zoom = Math.max(0.3, zoom * fit)const target = RenderTexture.create({ width, height, resolution: scale, antialias: true })const [r, g, b] = channels(this.frost ? FROSTED : LAND)- this.app.renderer.render({ container: this.world, target, clearColor: [r, g, b, 1] })+ draw(this.app.renderer, this.world, { target, clearColor: [r, g, b, 1] })const out = document.createElement("canvas")out.width = width * scaleout.height = height * scalediff --git a/src/render/pixi3d/smoke-effects.ts b/src/render/pixi3d/smoke-effects.tsindex 986caaf..9bc57f5 100644--- a/src/render/pixi3d/smoke-effects.ts+++ b/src/render/pixi3d/smoke-effects.ts@@ -10,6 +10,30 @@ const smokeBit: ShaderBit = {attributes: { aPuffSeed: "float32" },interStage: { vSmokeAge: "f32", vSmokeSeed: "f32" },bindings: { material: { time: "f32", power: "f32" } },+ gpu: {+ vertex: {+ afterTransform: `{+ let age = fract(material.time / 3.8 + input.aPuffSeed);+ var c = camera.uViewMatrix * modelMatrix * vec4<f32>(0.0, 0.0, 0.0, 1.0);+ c.y += age * 29.0;+ c.x += age * age * 6.0 + sin(age * 5.0 + input.aPuffSeed * 29.0) * age * 2.0;+ let size = 4.0 + age * 11.0;+ c = vec4<f32>(c.xy + position.xy * vec2<f32>(size, size * 1.18), c.zw);+ clipPosition = camera.uProjectionMatrix * c;+ output.vSmokeAge = age; output.vSmokeSeed = input.aPuffSeed;+ }`+ },+ fragment: {+ material: `{+ let p = (input.vUV - 0.5) * 2.0;+ let cloud = inkNoise(input.vUV * 3.0 + input.vSmokeSeed * 13.0 + vec2<f32>(0.0, material.time * 0.13)) * 0.65 + inkNoise(input.vUV * 7.0 + input.vSmokeSeed * 9.0) * 0.35;+ let edge = 1.0 - smoothstep(0.35, 1.0, length(p) + cloud * 0.24);+ alpha = edge * sin(input.vSmokeAge * 3.14159) * 0.19 * material.power;+ if (alpha < 0.008) { discard; }+ albedo = inkToDisplay(inkRGB(mix(vec3<f32>(0.40, 0.45, 0.39), vec3<f32>(0.68, 0.70, 0.63), input.vSmokeAge)));+ }`+ }+ },gl: {vertex: {afterTransform: `{diff --git a/src/render/pixi3d/structure-effects.ts b/src/render/pixi3d/structure-effects.tsindex d90b49e..b6098a9 100644--- a/src/render/pixi3d/structure-effects.ts+++ b/src/render/pixi3d/structure-effects.ts@@ -13,6 +13,47 @@ const fireBit: ShaderBit = {attributes: { aEffectAt: "float32x3", aEffectScale: "float32x2", aEffectSeed: "float32" },interStage: { vFireAge: "f32", vFireSeed: "f32" },bindings: { material: { time: "f32", power: "f32", mode: "f32" } },+ gpu: {+ vertex: {+ afterTransform: `{+ let mode = material.mode; let seed = input.aEffectSeed;+ let life = select(select(2.8, 4.2, mode < 1.5), 1.8, mode < 0.5);+ let age = fract(material.time / life + seed);+ var c = camera.uViewMatrix * modelMatrix * vec4<f32>(input.aEffectAt, 1.0);+ c.y += select(select(age * 35.0, age * 32.0, mode < 1.5), 0.0, mode < 0.5);+ c.x += sin(seed * 43.0 + age * 4.0) * select(3.0, 0.7, mode < 0.5) * age;+ let size = select(select(1.0, 0.55 + age * 1.15, mode < 1.5), (0.8 + 0.2 * sin(material.time * 8.0 + seed * 31.0)) * material.power, mode < 0.5);+ if (mode < 0.5) { c.y += input.aEffectScale.y * size * 0.5; }+ c = vec4<f32>(c.xy + (position.xy * input.aEffectScale) * size, c.zw);+ clipPosition = camera.uProjectionMatrix * c;+ output.vFireAge = age; output.vFireSeed = seed;+ }`+ },+ fragment: {+ material: `{+ let p = input.vUV; var a = 0.0; var color = vec3<f32>(0.0); let mode = material.mode; let t = material.time;+ if (mode < 0.5) {+ let y = p.y; let curl = sin(y * 8.0 - t * 4.5 + input.vFireSeed * 39.0) * 0.11 * y;+ let body = abs(p.x - 0.5 - curl) / (0.46 * (1.0 - y * 0.86));+ let edge = 1.0 - smoothstep(0.45, 1.0, body + inkNoise(vec2<f32>(p.x * 6.0, y * 5.0 - t * 3.5) + input.vFireSeed * 10.0) * 0.27);+ a = edge * smoothstep(0.0, 0.10, y) * (1.0 - smoothstep(0.82, 1.0, y)) * 0.82;+ let core = (1.0 - body) * pow(1.0 - y, 0.7);+ color = mix(vec3<f32>(0.87, 0.33, 0.12), vec3<f32>(1.0, 0.83, 0.38), smoothstep(0.0, 0.8, core));+ } else if (mode < 1.5) {+ let d = length((p - 0.5) * vec2<f32>(2.0, 1.8));+ let cloud = inkNoise(p * 3.0 + vec2<f32>(input.vFireSeed * 9.0, t * 0.12)) * 0.65 + inkNoise(p * 7.0 + input.vFireSeed * 11.0) * 0.35;+ a = (1.0 - smoothstep(0.3, 1.0, d + cloud * 0.24)) * sin(input.vFireAge * 3.14159) * 0.24 * material.power;+ color = mix(vec3<f32>(0.35, 0.39, 0.33), vec3<f32>(0.64, 0.66, 0.58), input.vFireAge);+ } else {+ a = (1.0 - smoothstep(0.05, 0.5, length(p - 0.5))) * sin(input.vFireAge * 3.14159) * material.power;+ color = vec3<f32>(1.0, 0.67, 0.24);+ }+ if (a < 0.015) { discard; }+ alpha = a;+ albedo = inkToDisplay(inkRGB(color));+ }`+ }+ },gl: {vertex: {afterTransform: `{diff --git a/test/render3d.test.ts b/test/render3d.test.tsindex 906448a..9f1d301 100644--- a/test/render3d.test.ts+++ b/test/render3d.test.ts@@ -1,6 +1,6 @@import assert from "node:assert/strict"import { test } from "node:test"-import { BatchedMesh3D, Container3D } from "@pixi/3d"+import { Container3D, Mesh3D } from "@pixi/3d"import { kindIds, kinds } from "../src/game/content/index.ts"import { U } from "../src/game/world/iso.ts"import { dressed } from "../src/render/pixi3d/assets/upgrade-dress.ts"@@ -142,16 +142,15 @@ test("shared geometry retains independent colours, transforms and entity pickingpool.flush()assert.equal(built, 1)assert.equal(pool.stats().models, 2)- // One batch for the box: a slot for each part of each copy, the fill first.- const batch = pool.root.children[0]- assert.ok(batch instanceof BatchedMesh3D)- const data = batch.instanceData, parts = batch.size / 4- const hex = (slot: number) => {- const o = data.offset + slot * data.stride + data.fields.tint!- return [0, 1, 2].reduce((n, k) => (n << 8) | Math.round(data.data[o + k]! * 255), 0)+ // Each copy is meshes of its own under its root, the fill first: they share the box's geometry, and each has its own colour.+ assert.ok(a.root.children[0] instanceof Mesh3D)+ assert.equal(a.pieces[0]!.mesh.geometry, b.pieces[0]!.mesh.geometry)+ const hex = (handle: ModelHandle) => {+ const color = handle.pieces[0]!.opaque.data.color as ArrayLike<number>+ return [0, 1, 2].reduce((n, k) => (n << 8) | Math.round(color[k]! * 255), 0)}- assert.equal(hex(0), 0x89aabb)- assert.equal(hex(parts), 0x663311)+ assert.equal(hex(a), 0x89aabb)+ assert.equal(hex(b), 0x663311)const hit = pool.pick({ origin: [30, 10, 0], direction: [0, -1, 0] })assert.ok(hit)assert.equal(hit.handle.entity, 29)@@ -211,12 +210,10 @@ test("different surface states share geometry and remain independent per instanca.effectBounds=[12,30,0.1,1];b.effectBounds=[...a.effectBounds]a.effects=surfaceState({snow:1});b.effects=surfaceState({wear:0.9,burning:1})pool.flush()- // Non-pickable effects use the same pool; inspect the render batch directly: slot 0 is a's first part, and b's- // first part follows a's parts.- const batch=pool.root.children[0]- assert.ok(batch instanceof BatchedMesh3D)- const data=batch.instanceData,parts=batch.size/4,state=(slot:number,k:number)=>data.data[data.offset+slot*data.stride+data.fields.state!+k]- assert.equal(state(0,2),1);assert.equal(state(parts,0),Math.fround(0.9));assert.equal(state(parts,3),1)+ // Non-pickable effects use the same pool; inspect each copy's face material directly.+ const state=(handle:ModelHandle,k:number)=>(handle.pieces.find(p=>p.part.role==="fill")!.opaque.data.surfaceState as ArrayLike<number>)[k]+ assert.equal(a.pieces[0]!.mesh.geometry,b.pieces[0]!.mesh.geometry)+ assert.equal(state(a,2),1);assert.equal(state(b,0),Math.fround(0.9));assert.equal(state(b,3),1)for(let i=0;i<100;i++){a.effects=surfaceState({wear:i/100});pool.flush()}assert.equal(built,1);assert.equal(pool.stats().templates,1)const particles=new StructureEffects(create(),26)