1// WebGPU rendering of the displacement field: a 2D color map or a lit 3D height field.
3import { type Grid, type PhysParams } from "../params.ts";
4import { lookAt, multiply, perspective } from "./mat4.ts";
5import shaderCode from "./shaders.wgsl?raw";
7export type ViewMode = "2d" | "3d";
9export class Renderer {
10 mode: ViewMode = "2d";
11 /** Vertical exaggeration of the 3D view. */
12 exaggeration = 4;
13 /** Color range |w| [m]; 0 means automatic (from the current maximum). */
14 colorRange = 0;
15 /** Add the stress-free initial shape to the 3D height field. */
16 showShape = false;
17 camera = { yaw: 0.6, pitch: 0.5, dist: 1.0 };
19 private device: GPUDevice;
20 private canvas: HTMLCanvasElement;
21 private ctx: GPUCanvasContext;
22 private format: GPUTextureFormat;
23 private uniform: GPUBuffer;
24 private pipe2d: GPURenderPipeline;
25 private pipe3d: GPURenderPipeline;
26 private bgLayout: GPUBindGroupLayout;
27 private index: GPUBuffer;
28 private indexCount: number;
29 private depth: GPUTexture | null = null;
30 private grid: Grid;
31 private params: PhysParams;
32 private bindGroups = new Map<GPUBuffer, GPUBindGroup>();
34 private w0: GPUBuffer;
36 constructor(device: GPUDevice, canvas: HTMLCanvasElement, grid: Grid, params: PhysParams, w0: GPUBuffer) {
37 this.device = device;
38 this.w0 = w0;
39 this.canvas = canvas;
40 this.grid = grid;
41 this.params = params;
42 this.ctx = canvas.getContext("webgpu") as GPUCanvasContext;
43 this.format = navigator.gpu.getPreferredCanvasFormat();
44 this.ctx.configure({ device, format: this.format, alphaMode: "opaque" });
45 this.uniform = device.createBuffer({ size: 144, usage: GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_DST });
46 const module = device.createShaderModule({ code: shaderCode });
47 this.bgLayout = device.createBindGroupLayout({
48 entries: [
49 { binding: 0, visibility: GPUShaderStage.VERTEX | GPUShaderStage.FRAGMENT, buffer: { type: "uniform" } },
50 { binding: 1, visibility: GPUShaderStage.VERTEX | GPUShaderStage.FRAGMENT, buffer: { type: "read-only-storage" } },
51 { binding: 2, visibility: GPUShaderStage.VERTEX | GPUShaderStage.FRAGMENT, buffer: { type: "read-only-storage" } },
52 ],
53 });
54 const layout = device.createPipelineLayout({ bindGroupLayouts: [this.bgLayout] });
55 this.pipe2d = device.createRenderPipeline({
56 layout,
57 vertex: { module, entryPoint: "vs2d" },
58 fragment: { module, entryPoint: "fs2d", targets: [{ format: this.format }] },
59 primitive: { topology: "triangle-list" },
60 });
61 this.pipe3d = device.createRenderPipeline({
62 layout,
63 vertex: { module, entryPoint: "vs3d" },
64 fragment: { module, entryPoint: "fs3d", targets: [{ format: this.format }] },
65 primitive: { topology: "triangle-list", cullMode: "none" },
66 depthStencil: { format: "depth24plus", depthWriteEnabled: true, depthCompare: "less" },
67 });
68 // Triangle indices of the height field.
69 const { nx, ny } = grid;
70 const idx = new Uint32Array((nx - 1) * (ny - 1) * 6);
71 let k = 0;
72 for (let j = 0; j < ny - 1; j++) {
73 for (let i = 0; i < nx - 1; i++) {
74 const a = j * nx + i, b = a + 1, c = a + nx, d = c + 1;
75 idx[k++] = a; idx[k++] = b; idx[k++] = d;
76 idx[k++] = a; idx[k++] = d; idx[k++] = c;
77 }
78 }
79 this.indexCount = idx.length;
80 this.index = device.createBuffer({ size: idx.byteLength, usage: GPUBufferUsage.INDEX | GPUBufferUsage.COPY_DST });
81 device.queue.writeBuffer(this.index, 0, idx);
82 this.installControls();
83 }
85 private installControls(): void {
86 let dragging = false, lastX = 0, lastY = 0;
87 this.canvas.addEventListener("pointerdown", (e) => {
88 dragging = true; lastX = e.clientX; lastY = e.clientY;
89 this.canvas.setPointerCapture(e.pointerId);
90 });
91 this.canvas.addEventListener("pointerup", () => (dragging = false));
92 this.canvas.addEventListener("pointermove", (e) => {
93 if (!dragging || this.mode !== "3d") return;
94 this.camera.yaw += (e.clientX - lastX) * 0.01;
95 this.camera.pitch = Math.max(-1.5, Math.min(1.5, this.camera.pitch + (e.clientY - lastY) * 0.01));
96 lastX = e.clientX; lastY = e.clientY;
97 });
98 this.canvas.addEventListener("wheel", (e) => {
99 if (this.mode !== "3d") return;
100 e.preventDefault();
101 this.camera.dist *= Math.exp(e.deltaY * 0.001);
102 this.camera.dist = Math.max(0.2, Math.min(5, this.camera.dist));
103 }, { passive: false });
104 }
106 private resize(): void {
107 const dpr = window.devicePixelRatio || 1;
108 const w = Math.max(1, Math.floor(this.canvas.clientWidth * dpr));
109 const h = Math.max(1, Math.floor(this.canvas.clientHeight * dpr));
110 if (this.canvas.width !== w || this.canvas.height !== h || !this.depth) {
111 this.canvas.width = w;
112 this.canvas.height = h;
113 this.depth?.destroy();
114 this.depth = this.device.createTexture({ size: [w, h], format: "depth24plus", usage: GPUTextureUsage.RENDER_ATTACHMENT });
115 }
116 }
118 /** Renders the w field held in `wBuffer` (f32 per node). `wmax` drives the automatic color range. */
119 render(encoder: GPUCommandEncoder, wBuffer: GPUBuffer, wmax: number): void {
120 this.resize();
121 const aspect = this.canvas.width / this.canvas.height;
122 const range = this.colorRange > 0 ? this.colorRange : Math.max(wmax, 1e-6);
123 const u = new Float32Array(36);
124 const ui = new Uint32Array(u.buffer);
125 const eye = [
126 this.camera.dist * Math.cos(this.camera.pitch) * Math.sin(this.camera.yaw),
127 this.camera.dist * Math.sin(this.camera.pitch),
128 this.camera.dist * Math.cos(this.camera.pitch) * Math.cos(this.camera.yaw),
129 ];
130 const mvp = multiply(perspective(0.7, aspect, 0.02, 20), lookAt(eye, [0, 0, 0], [0, 1, 0]));
131 u.set(mvp, 0);
132 ui[16] = this.grid.nx; ui[17] = this.grid.ny;
133 u[18] = this.grid.hx; u[19] = this.grid.hy;
134 u[20] = this.exaggeration; u[21] = range; u[22] = aspect;
135 ui[23] = this.mode === "3d" ? 1 : 0;
136 const p = this.params;
137 u[24] = -p.Lx / 2 + p.holeInset; u[25] = p.Ly / 2 - p.holeInset;
138 u[26] = p.Lx / 2; u[27] = -p.Ly / 2;
139 u[28] = p.fingerRadius;
140 u[29] = 0.4; u[30] = 0.5; u[31] = 1.0;
141 ui[32] = this.showShape ? 1 : 0;
142 this.device.queue.writeBuffer(this.uniform, 0, u);
144 let bg = this.bindGroups.get(wBuffer);
145 if (!bg) {
146 bg = this.device.createBindGroup({
147 layout: this.bgLayout,
148 entries: [
149 { binding: 0, resource: { buffer: this.uniform } },
150 { binding: 1, resource: { buffer: wBuffer } },
151 { binding: 2, resource: { buffer: this.w0 } },
152 ],
153 });
154 this.bindGroups.set(wBuffer, bg);
155 }
156 const view = this.ctx.getCurrentTexture().createView();
157 const clear = { r: 0.11, g: 0.12, b: 0.14, a: 1 };
158 if (this.mode === "2d") {
159 const pass = encoder.beginRenderPass({ colorAttachments: [{ view, clearValue: clear, loadOp: "clear", storeOp: "store" }] });
160 pass.setPipeline(this.pipe2d);
161 pass.setBindGroup(0, bg);
162 pass.draw(3);
163 pass.end();
164 } else {
165 const pass = encoder.beginRenderPass({
166 colorAttachments: [{ view, clearValue: clear, loadOp: "clear", storeOp: "store" }],
167 depthStencilAttachment: { view: this.depth!.createView(), depthClearValue: 1, depthLoadOp: "clear", depthStoreOp: "store" },
168 });
169 pass.setPipeline(this.pipe3d);
170 pass.setBindGroup(0, bg);
171 pass.setIndexBuffer(this.index, "uint32");
172 pass.drawIndexed(this.indexCount);
173 pass.end();
174 }
175 }
176}