dcgrid 0.2.1 → 0.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +33 -19
- package/dist/dcgrid.wasm +0 -0
- package/dist/index.d.ts +61 -9
- package/dist/index.js +185 -10
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -2,19 +2,36 @@
|
|
|
2
2
|
|
|
3
3
|
Adaptive-grid smoke simulation on WebGPU: [DCGrid](https://graphics.tudelft.nl/~klaus/papers/DCGrid.pdf) compiled to WebAssembly, on a `GPUDevice` you own.
|
|
4
4
|
|
|
5
|
+

|
|
6
|
+
|
|
7
|
+
*The "Clouds over mountains" preset after 300 steps: the render (left) and the resolution view (right), where each checkerboard square is one grid cell. The grid refines where the flow needs it. [Try it in the browser](https://dcgrid.vercel.app).*
|
|
8
|
+
|
|
5
9
|
```ts
|
|
6
|
-
import { DCGrid } from "dcgrid";
|
|
7
|
-
|
|
8
|
-
const adapter = await navigator.gpu.requestAdapter();
|
|
9
|
-
const device = await adapter!.requestDevice({
|
|
10
|
-
requiredLimits: {
|
|
11
|
-
maxStorageBuffersPerShaderStage: adapter!.limits.maxStorageBuffersPerShaderStage,
|
|
12
|
-
maxStorageBufferBindingSize: adapter!.limits.maxStorageBufferBindingSize,
|
|
13
|
-
maxBufferSize: adapter!.limits.maxBufferSize,
|
|
14
|
-
},
|
|
15
|
-
});
|
|
10
|
+
import { DCGrid, orbitCamera, sceneOrbit } from "dcgrid";
|
|
16
11
|
|
|
12
|
+
const device = await DCGrid.requestDevice(); // the limits large grids need (DCGrid.requiredLimits)
|
|
17
13
|
const dcgrid = await DCGrid.load();
|
|
14
|
+
|
|
15
|
+
const context = canvas.getContext("webgpu")!;
|
|
16
|
+
context.configure({ device, format: navigator.gpu.getPreferredCanvasFormat() });
|
|
17
|
+
|
|
18
|
+
const scene = dcgrid.describeScene("Open plume", 64);
|
|
19
|
+
const sim = dcgrid.create(device, scene.desc);
|
|
20
|
+
sim.applyScene("Open plume");
|
|
21
|
+
const renderer = sim.createRenderer();
|
|
22
|
+
await renderer.whenReady();
|
|
23
|
+
|
|
24
|
+
for (;;) {
|
|
25
|
+
sim.poll();
|
|
26
|
+
if (sim.stepsInFlight < 2) sim.step();
|
|
27
|
+
if (!renderer.busy) renderer.render(orbitCamera(sceneOrbit(scene.view)), scene.render, context);
|
|
28
|
+
await new Promise(requestAnimationFrame);
|
|
29
|
+
}
|
|
30
|
+
```
|
|
31
|
+
|
|
32
|
+
[examples/basic](../examples/basic) is this as a Vite app. Your own scene instead of a preset:
|
|
33
|
+
|
|
34
|
+
```ts
|
|
18
35
|
const sim = dcgrid.create(device, {
|
|
19
36
|
size: [128, 256, 128], // cells
|
|
20
37
|
cellSize: 40, // meters
|
|
@@ -22,12 +39,6 @@ const sim = dcgrid.create(device, {
|
|
|
22
39
|
faces: { "-y": { type: "inflow", velocity: [0, 100, 0], density: 0.002 } },
|
|
23
40
|
});
|
|
24
41
|
await sim.whenReady();
|
|
25
|
-
|
|
26
|
-
for (;;) {
|
|
27
|
-
sim.poll();
|
|
28
|
-
if (sim.stepsInFlight < 2) sim.step();
|
|
29
|
-
await new Promise(requestAnimationFrame);
|
|
30
|
-
}
|
|
31
42
|
```
|
|
32
43
|
|
|
33
44
|
## Scenes
|
|
@@ -36,18 +47,21 @@ for (;;) {
|
|
|
36
47
|
- **Solids**: `sim.setSolids({ size, data })`, a signed distance in meters (negative inside).
|
|
37
48
|
- **Sources**: `sim.setSources(density, velocity)`, rates per second added every step.
|
|
38
49
|
|
|
39
|
-
Volumes span the domain at any resolution, x fastest, with voxels on the domain's corners. `dcgrid.describeScene(
|
|
50
|
+
Volumes span the domain at any resolution, x fastest, with voxels on the domain's corners. `dcgrid.describeScene(scene, resolution)` and `sim.applyScene(scene)` load the five preset scenes of the demo by index or by name (`dcgrid.scenes`: sphere obstacle, open plume, wind over hills, wildfire, clouds over mountains; the last two use the weather extension). A preset scene's inflow maps follow later changes to their faces' velocity and density in `sim.setStepParams`; maps you set with `setInflowMap` are kept as given.
|
|
40
51
|
|
|
41
52
|
## Output
|
|
42
53
|
|
|
43
54
|
- `await sim.sampleField("density" | "velocity" | "fluidity" | "cell_size", texture)` resamples a field into a 3D `GPUTexture` (`r32float`, `rgba16float` or `rgba32float` with `STORAGE_BINDING`) for your own renderer.
|
|
44
|
-
- `sim.createRenderer()` is the optional raymarcher of the demo
|
|
55
|
+
- `sim.createRenderer()` is the optional raymarcher of the demo. `renderer.render(camera, settings, context, { scale })` draws into a canvas over `settings.backgroundColor`, raymarching at `scale` times the canvas size. `renderer.render(camera, settings, texture)` writes into an `rgba8unorm` texture with `STORAGE_BINDING` instead, with alpha for your own compositing. Renders are asynchronous: skip a frame while `renderer.busy`.
|
|
56
|
+
- Cameras: `orbitCamera({ target, distance, yaw, pitch }, { fov })` builds the `Camera` the renderer takes, and `sceneOrbit(scene.view)` frames a preset scene.
|
|
45
57
|
|
|
46
58
|
## Behavior
|
|
47
59
|
|
|
48
60
|
Nothing blocks. `create` and `reset` return at once; `whenReady()` resolves once the pipelines are compiled and the grid is initialized. `step()` submits to the device queue without waiting. The adaptive grid reads refinement scores back asynchronously and applies them in a later step; `stepsInFlight` counts a step until its readback has arrived. Errors are `DCGridError`s with a `code` (`invalid_argument`, `unsupported`, `not_ready`, `device`).
|
|
49
61
|
|
|
50
|
-
`dcgrid.wasm` is loaded from next to `dcgrid.mjs` (bundlers that handle `new URL(..., import.meta.url)` pick it up; Vite needs `optimizeDeps.exclude: ["dcgrid"]
|
|
62
|
+
`dcgrid.wasm` is loaded from next to `dcgrid.mjs` (bundlers that handle `new URL(..., import.meta.url)` pick it up; Vite needs `optimizeDeps.exclude: ["dcgrid"]`, see [the example's config](../examples/basic/vite.config.ts)). `DCGrid.load({ wasm })` takes another URL or the bytes.
|
|
63
|
+
|
|
64
|
+
The adaptive grid binds 9 storage buffers per shader stage and the uniform grid 5, above WebGPU's default of 8 for the adaptive grid; `DCGrid.requestDevice(adapter?)` and `DCGrid.requiredLimits(adapter)` request what the adapter allows.
|
|
51
65
|
|
|
52
66
|
## Building
|
|
53
67
|
|
package/dist/dcgrid.wasm
CHANGED
|
Binary file
|
package/dist/index.d.ts
CHANGED
|
@@ -101,6 +101,7 @@ export interface RenderSettings {
|
|
|
101
101
|
antialiasing: number;
|
|
102
102
|
shadowSamples: number;
|
|
103
103
|
ambient: number;
|
|
104
|
+
/** Behind the scene when rendering into a canvas (texture targets get alpha instead). */
|
|
104
105
|
backgroundColor: Vec3;
|
|
105
106
|
floorColor: Vec3;
|
|
106
107
|
smokeColor: Vec3;
|
|
@@ -123,6 +124,27 @@ export interface SceneInfo {
|
|
|
123
124
|
};
|
|
124
125
|
render: RenderSettings;
|
|
125
126
|
}
|
|
127
|
+
/** A preset scene by index or by name (one of `DCGrid.scenes`). */
|
|
128
|
+
export type SceneRef = number | string;
|
|
129
|
+
/** A camera orbiting `target` (meters) at `distance`; yaw about +y and pitch above the horizon in radians. */
|
|
130
|
+
export interface Orbit {
|
|
131
|
+
target: Vec3;
|
|
132
|
+
distance: number;
|
|
133
|
+
yaw: number;
|
|
134
|
+
pitch: number;
|
|
135
|
+
}
|
|
136
|
+
/** The sunlight direction of the preset scenes. */
|
|
137
|
+
export declare const DEFAULT_SUN_DIRECTION: Vec3;
|
|
138
|
+
/**
|
|
139
|
+
* The render camera of an orbit. `fov` is the field of view in degrees along the longer image side
|
|
140
|
+
* (default 100, as in the demo).
|
|
141
|
+
*/
|
|
142
|
+
export declare function orbitCamera(orbit: Orbit, options?: {
|
|
143
|
+
fov?: number;
|
|
144
|
+
sunDirection?: Vec3;
|
|
145
|
+
}): Camera;
|
|
146
|
+
/** The orbit that frames a preset scene (`SceneInfo.view`), for a field of view of 100°. */
|
|
147
|
+
export declare function sceneOrbit(view: SceneInfo["view"]): Orbit;
|
|
126
148
|
export type ErrorCode = "invalid_argument" | "unsupported" | "not_ready" | "device";
|
|
127
149
|
export declare class DCGridError extends Error {
|
|
128
150
|
readonly code: ErrorCode;
|
|
@@ -150,18 +172,31 @@ export declare class DCGrid {
|
|
|
150
172
|
static load(options?: {
|
|
151
173
|
wasm?: string | URL | ArrayBuffer;
|
|
152
174
|
}): Promise<DCGrid>;
|
|
175
|
+
/**
|
|
176
|
+
* Device limits to request for the largest grids the adapter can run: its own maximum storage
|
|
177
|
+
* buffers per shader stage (the adaptive grid needs 9, the uniform grid 5), storage binding size
|
|
178
|
+
* and buffer size.
|
|
179
|
+
*/
|
|
180
|
+
static requiredLimits(adapter: GPUAdapter): Record<string, number>;
|
|
181
|
+
/**
|
|
182
|
+
* Requests a high-performance adapter (unless one is given) and a device with `requiredLimits`.
|
|
183
|
+
* Throws an "unsupported" DCGridError without WebGPU.
|
|
184
|
+
*/
|
|
185
|
+
static requestDevice(adapter?: GPUAdapter): Promise<GPUDevice>;
|
|
153
186
|
/** Default description and render settings: 128³ cells of 78 m, adaptive, 40000 blocks, no-slip walls. */
|
|
154
187
|
defaults(): {
|
|
155
188
|
desc: Required<SimulationDesc>;
|
|
156
189
|
render: RenderSettings;
|
|
157
190
|
};
|
|
158
191
|
/**
|
|
159
|
-
* A preset scene at `resolution` cells per 10 km. `base` keeps grid, maxBlocks, criterion and
|
|
192
|
+
* A preset scene (index or name) at `resolution` cells per 10 km. `base` keeps grid, maxBlocks, criterion and
|
|
160
193
|
* densityScale (other settings come from the scene).
|
|
161
194
|
*/
|
|
162
|
-
describeScene(scene:
|
|
195
|
+
describeScene(scene: SceneRef, resolution: number, base?: Partial<SimulationDesc>): SceneInfo;
|
|
163
196
|
/** Creates a simulation on `device`; it builds in the background (see Simulation.whenReady). */
|
|
164
197
|
create(device: GPUDevice, desc: SimulationDesc): Simulation;
|
|
198
|
+
/** The index of a preset scene; throws an "invalid_argument" DCGridError for unknown ones. */
|
|
199
|
+
sceneIndex(scene: SceneRef): number;
|
|
165
200
|
/** @internal */
|
|
166
201
|
get module(): Module;
|
|
167
202
|
/** @internal */
|
|
@@ -183,12 +218,14 @@ export declare class Simulation {
|
|
|
183
218
|
private readonly dcgrid;
|
|
184
219
|
/** @internal */ readonly ptr: number;
|
|
185
220
|
/** @internal */ readonly device: number;
|
|
221
|
+
/** The device the simulation records into. */ readonly gpuDevice: GPUDevice;
|
|
186
222
|
private sources;
|
|
187
223
|
private destroyed;
|
|
188
224
|
/** @internal */
|
|
189
225
|
constructor(dcgrid: DCGrid,
|
|
190
226
|
/** @internal */ ptr: number,
|
|
191
|
-
/** @internal */ device: number
|
|
227
|
+
/** @internal */ device: number,
|
|
228
|
+
/** The device the simulation records into. */ gpuDevice: GPUDevice);
|
|
192
229
|
private get m();
|
|
193
230
|
/** Processes finished GPU work: advances building, resetting and the adaptation. Call once per frame. */
|
|
194
231
|
poll(): void;
|
|
@@ -219,8 +256,11 @@ export declare class Simulation {
|
|
|
219
256
|
* first axis fastest. null returns to the face's uniform values.
|
|
220
257
|
*/
|
|
221
258
|
setInflowMap(face: FaceName, values: Float32Array | null): void;
|
|
222
|
-
/**
|
|
223
|
-
|
|
259
|
+
/**
|
|
260
|
+
* Uploads a preset scene's solids, sources and inflow maps (for a simulation described by it).
|
|
261
|
+
* The scene's inflow maps follow later changes to their faces' velocity and density.
|
|
262
|
+
*/
|
|
263
|
+
applyScene(scene: SceneRef): void;
|
|
224
264
|
stats(): Stats;
|
|
225
265
|
/**
|
|
226
266
|
* Resamples a field into a 3D texture (r32float, rgba16float or rgba32float with STORAGE_BINDING),
|
|
@@ -239,21 +279,33 @@ export declare class Renderer {
|
|
|
239
279
|
private readonly sim;
|
|
240
280
|
private readonly ptr;
|
|
241
281
|
private destroyed;
|
|
282
|
+
/** Canvas output: the raymarched image and the pipeline drawing it, per canvas format. */
|
|
283
|
+
private image;
|
|
284
|
+
private present;
|
|
285
|
+
private presentResources;
|
|
286
|
+
private defaultBackground;
|
|
242
287
|
/** @internal */
|
|
243
288
|
constructor(dcgrid: DCGrid, sim: Simulation, ptr: number);
|
|
244
289
|
private get m();
|
|
245
290
|
get ready(): boolean;
|
|
246
291
|
whenReady(): Promise<void>;
|
|
247
292
|
/**
|
|
248
|
-
* Records and submits a render
|
|
249
|
-
*
|
|
250
|
-
*
|
|
293
|
+
* Records and submits a render. Settings not given take their defaults. Throws a "not_ready"
|
|
294
|
+
* DCGridError until the simulation and the render pipelines are ready.
|
|
295
|
+
*
|
|
296
|
+
* - A texture target (rgba8unorm with STORAGE_BINDING) receives the image with alpha: 0 where the
|
|
297
|
+
* view sees only background. `backgroundColor` does not apply.
|
|
298
|
+
* - A canvas context (configured on the simulation's device) receives the image over
|
|
299
|
+
* `backgroundColor`, raymarched at `scale` times the canvas size (default 1) and scaled up.
|
|
251
300
|
*/
|
|
252
|
-
render(camera: Camera, settings: Partial<RenderSettings>, target: GPUTexture
|
|
301
|
+
render(camera: Camera, settings: Partial<RenderSettings>, target: GPUTexture | GPUCanvasContext, options?: {
|
|
302
|
+
scale?: number;
|
|
303
|
+
}): void;
|
|
253
304
|
/** The last submitted render is still running on the GPU. */
|
|
254
305
|
get busy(): boolean;
|
|
255
306
|
/** Recomputes the sun transmittance volume at the next render. */
|
|
256
307
|
invalidate(): void;
|
|
257
308
|
destroy(): void;
|
|
309
|
+
private renderToCanvas;
|
|
258
310
|
}
|
|
259
311
|
export {};
|
package/dist/index.js
CHANGED
|
@@ -6,6 +6,8 @@
|
|
|
6
6
|
* await sim.whenReady();
|
|
7
7
|
* sim.step();
|
|
8
8
|
*
|
|
9
|
+
* To draw into a canvas: `sim.createRenderer().render(orbitCamera(orbit), settings, canvasContext)`.
|
|
10
|
+
*
|
|
9
11
|
* Nothing blocks: creating and resetting a simulation return at once and `whenReady()` resolves once
|
|
10
12
|
* the pipelines are compiled and the grid is initialized. Steps are submitted to the device queue
|
|
11
13
|
* without waiting; the adaptive grid reads its refinement scores back asynchronously.
|
|
@@ -13,6 +15,65 @@
|
|
|
13
15
|
import createDCGridModule from "./dcgrid.mjs";
|
|
14
16
|
export const FACE_NAMES = ["-x", "+x", "-y", "+y", "-z", "+z"];
|
|
15
17
|
const FIELDS = ["density", "velocity", "fluidity", "cell_size"];
|
|
18
|
+
/** The sunlight direction of the preset scenes. */
|
|
19
|
+
export const DEFAULT_SUN_DIRECTION = (() => {
|
|
20
|
+
const p = -2.5, y = -2.1;
|
|
21
|
+
return [-Math.cos(p) * Math.cos(y), -Math.sin(p), -Math.cos(p) * Math.sin(y)];
|
|
22
|
+
})();
|
|
23
|
+
const sub = (a, b) => [a[0] - b[0], a[1] - b[1], a[2] - b[2]];
|
|
24
|
+
const cross = (a, b) => [a[1] * b[2] - a[2] * b[1], a[2] * b[0] - a[0] * b[2], a[0] * b[1] - a[1] * b[0]];
|
|
25
|
+
const normalize = (a) => {
|
|
26
|
+
const l = Math.hypot(...a) || 1;
|
|
27
|
+
return [a[0] / l, a[1] / l, a[2] / l];
|
|
28
|
+
};
|
|
29
|
+
/**
|
|
30
|
+
* The render camera of an orbit. `fov` is the field of view in degrees along the longer image side
|
|
31
|
+
* (default 100, as in the demo).
|
|
32
|
+
*/
|
|
33
|
+
export function orbitCamera(orbit, options = {}) {
|
|
34
|
+
const { fov = 100, sunDirection = DEFAULT_SUN_DIRECTION } = options;
|
|
35
|
+
const cp = Math.cos(orbit.pitch);
|
|
36
|
+
const offset = [cp * Math.sin(orbit.yaw), Math.sin(orbit.pitch), cp * Math.cos(orbit.yaw)];
|
|
37
|
+
const eye = orbit.target.map((t, i) => t + orbit.distance * offset[i]);
|
|
38
|
+
const forward = normalize(sub(orbit.target, eye));
|
|
39
|
+
const right = normalize(cross(forward, [0, 1, 0]));
|
|
40
|
+
const up = cross(right, forward);
|
|
41
|
+
return { eye, right, up, forward, sunDirection, fovScale: Math.sin((fov / 2) * (Math.PI / 180)) };
|
|
42
|
+
}
|
|
43
|
+
/** The orbit that frames a preset scene (`SceneInfo.view`), for a field of view of 100°. */
|
|
44
|
+
export function sceneOrbit(view) {
|
|
45
|
+
const domain = view.shape.map((s) => s * 10000); // meters
|
|
46
|
+
return {
|
|
47
|
+
target: [domain[0] / 2, domain[1] / 2, domain[2] / 2],
|
|
48
|
+
distance: (view.zoom * Math.max(domain[0], domain[1])) / Math.sin((50 * Math.PI) / 180),
|
|
49
|
+
yaw: view.yaw,
|
|
50
|
+
pitch: view.pitch,
|
|
51
|
+
};
|
|
52
|
+
}
|
|
53
|
+
// ------------------------------------------------------------------ canvas output
|
|
54
|
+
/** Draws an rgba8unorm render over a background color into a canvas texture. */
|
|
55
|
+
const PRESENT_WGSL = /* wgsl */ `
|
|
56
|
+
@group(0) @binding(0) var tex: texture_2d<f32>;
|
|
57
|
+
@group(0) @binding(1) var samp: sampler;
|
|
58
|
+
@group(0) @binding(2) var<uniform> background: vec4f;
|
|
59
|
+
|
|
60
|
+
struct VOut { @builtin(position) pos: vec4f, @location(0) uv: vec2f }
|
|
61
|
+
|
|
62
|
+
@vertex
|
|
63
|
+
fn vs(@builtin(vertex_index) i: u32) -> VOut {
|
|
64
|
+
let p = vec2f(f32((i << 1u) & 2u), f32(i & 2u));
|
|
65
|
+
var o: VOut;
|
|
66
|
+
o.pos = vec4f(p * 2.0 - 1.0, 0.0, 1.0);
|
|
67
|
+
o.uv = vec2f(p.x, 1.0 - p.y);
|
|
68
|
+
return o;
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
@fragment
|
|
72
|
+
fn fs(in: VOut) -> @location(0) vec4f {
|
|
73
|
+
let c = textureSample(tex, samp, in.uv);
|
|
74
|
+
return vec4f(c.rgb * c.a + background.rgb * (1.0 - c.a), 1.0);
|
|
75
|
+
}
|
|
76
|
+
`;
|
|
16
77
|
const CODES = { 1: "invalid_argument", 2: "unsupported", 3: "not_ready", 4: "device" };
|
|
17
78
|
export class DCGridError extends Error {
|
|
18
79
|
code;
|
|
@@ -46,16 +107,44 @@ export class DCGrid {
|
|
|
46
107
|
settings.locateFile = (file) => (file.endsWith(".wasm") ? String(options.wasm) : file);
|
|
47
108
|
return new DCGrid((await createDCGridModule(settings)));
|
|
48
109
|
}
|
|
110
|
+
/**
|
|
111
|
+
* Device limits to request for the largest grids the adapter can run: its own maximum storage
|
|
112
|
+
* buffers per shader stage (the adaptive grid needs 9, the uniform grid 5), storage binding size
|
|
113
|
+
* and buffer size.
|
|
114
|
+
*/
|
|
115
|
+
static requiredLimits(adapter) {
|
|
116
|
+
const L = adapter.limits;
|
|
117
|
+
return {
|
|
118
|
+
maxStorageBuffersPerShaderStage: L.maxStorageBuffersPerShaderStage,
|
|
119
|
+
maxStorageBufferBindingSize: L.maxStorageBufferBindingSize,
|
|
120
|
+
maxBufferSize: L.maxBufferSize,
|
|
121
|
+
};
|
|
122
|
+
}
|
|
123
|
+
/**
|
|
124
|
+
* Requests a high-performance adapter (unless one is given) and a device with `requiredLimits`.
|
|
125
|
+
* Throws an "unsupported" DCGridError without WebGPU.
|
|
126
|
+
*/
|
|
127
|
+
static async requestDevice(adapter) {
|
|
128
|
+
if (!adapter) {
|
|
129
|
+
if (typeof navigator === "undefined" || !navigator.gpu)
|
|
130
|
+
throw new DCGridError("WebGPU is not available", "unsupported");
|
|
131
|
+
adapter = (await navigator.gpu.requestAdapter({ powerPreference: "high-performance" })) ?? undefined;
|
|
132
|
+
if (!adapter)
|
|
133
|
+
throw new DCGridError("No WebGPU adapter found", "unsupported");
|
|
134
|
+
}
|
|
135
|
+
return adapter.requestDevice({ requiredLimits: DCGrid.requiredLimits(adapter) });
|
|
136
|
+
}
|
|
49
137
|
/** Default description and render settings: 128³ cells of 78 m, adaptive, 40000 blocks, no-slip walls. */
|
|
50
138
|
defaults() {
|
|
51
139
|
return this.json(this.m._dcgridJsDefaults());
|
|
52
140
|
}
|
|
53
141
|
/**
|
|
54
|
-
* A preset scene at `resolution` cells per 10 km. `base` keeps grid, maxBlocks, criterion and
|
|
142
|
+
* A preset scene (index or name) at `resolution` cells per 10 km. `base` keeps grid, maxBlocks, criterion and
|
|
55
143
|
* densityScale (other settings come from the scene).
|
|
56
144
|
*/
|
|
57
145
|
describeScene(scene, resolution, base = {}) {
|
|
58
|
-
const
|
|
146
|
+
const index = this.sceneIndex(scene);
|
|
147
|
+
const ptr = this.withString(JSON.stringify(base), (s) => this.m._dcgridJsDescribeScene(index, resolution, s));
|
|
59
148
|
if (!ptr)
|
|
60
149
|
throw this.error(1);
|
|
61
150
|
return this.json(ptr);
|
|
@@ -66,7 +155,14 @@ export class DCGrid {
|
|
|
66
155
|
const ptr = this.withString(JSON.stringify(desc), (s) => this.m._dcgridJsCreate(devicePtr, s));
|
|
67
156
|
if (!ptr)
|
|
68
157
|
throw this.error(1);
|
|
69
|
-
return new Simulation(this, ptr, devicePtr);
|
|
158
|
+
return new Simulation(this, ptr, devicePtr, device);
|
|
159
|
+
}
|
|
160
|
+
/** The index of a preset scene; throws an "invalid_argument" DCGridError for unknown ones. */
|
|
161
|
+
sceneIndex(scene) {
|
|
162
|
+
const index = typeof scene === "number" ? scene : this.scenes.indexOf(scene);
|
|
163
|
+
if (!Number.isInteger(index) || index < 0 || index >= this.scenes.length)
|
|
164
|
+
throw new DCGridError(`Unknown scene ${JSON.stringify(scene)} (scenes: ${this.scenes.join(", ")})`, "invalid_argument");
|
|
165
|
+
return index;
|
|
70
166
|
}
|
|
71
167
|
// ---------------------------------------------------------------- internals for Simulation/Renderer
|
|
72
168
|
/** @internal */
|
|
@@ -138,15 +234,18 @@ export class Simulation {
|
|
|
138
234
|
dcgrid;
|
|
139
235
|
ptr;
|
|
140
236
|
device;
|
|
237
|
+
gpuDevice;
|
|
141
238
|
sources = { density: null, velocity: null };
|
|
142
239
|
destroyed = false;
|
|
143
240
|
/** @internal */
|
|
144
241
|
constructor(dcgrid,
|
|
145
242
|
/** @internal */ ptr,
|
|
146
|
-
/** @internal */ device
|
|
243
|
+
/** @internal */ device,
|
|
244
|
+
/** The device the simulation records into. */ gpuDevice) {
|
|
147
245
|
this.dcgrid = dcgrid;
|
|
148
246
|
this.ptr = ptr;
|
|
149
247
|
this.device = device;
|
|
248
|
+
this.gpuDevice = gpuDevice;
|
|
150
249
|
}
|
|
151
250
|
get m() {
|
|
152
251
|
return this.dcgrid.module;
|
|
@@ -223,9 +322,12 @@ export class Simulation {
|
|
|
223
322
|
const f = FACE_NAMES.indexOf(face);
|
|
224
323
|
this.dcgrid.check(this.dcgrid.withFloats(values, (p) => this.m._dcgridSetInflowMap(this.ptr, f, p)));
|
|
225
324
|
}
|
|
226
|
-
/**
|
|
325
|
+
/**
|
|
326
|
+
* Uploads a preset scene's solids, sources and inflow maps (for a simulation described by it).
|
|
327
|
+
* The scene's inflow maps follow later changes to their faces' velocity and density.
|
|
328
|
+
*/
|
|
227
329
|
applyScene(scene) {
|
|
228
|
-
this.dcgrid.check(this.m._dcgridSceneApply(this.ptr, scene));
|
|
330
|
+
this.dcgrid.check(this.m._dcgridSceneApply(this.ptr, this.dcgrid.sceneIndex(scene)));
|
|
229
331
|
this.sources = { density: null, velocity: null };
|
|
230
332
|
}
|
|
231
333
|
stats() {
|
|
@@ -284,6 +386,11 @@ export class Renderer {
|
|
|
284
386
|
sim;
|
|
285
387
|
ptr;
|
|
286
388
|
destroyed = false;
|
|
389
|
+
/** Canvas output: the raymarched image and the pipeline drawing it, per canvas format. */
|
|
390
|
+
image = null;
|
|
391
|
+
present = null;
|
|
392
|
+
presentResources = null;
|
|
393
|
+
defaultBackground = null;
|
|
287
394
|
/** @internal */
|
|
288
395
|
constructor(dcgrid, sim, ptr) {
|
|
289
396
|
this.dcgrid = dcgrid;
|
|
@@ -307,11 +414,19 @@ export class Renderer {
|
|
|
307
414
|
}
|
|
308
415
|
}
|
|
309
416
|
/**
|
|
310
|
-
* Records and submits a render
|
|
311
|
-
*
|
|
312
|
-
*
|
|
417
|
+
* Records and submits a render. Settings not given take their defaults. Throws a "not_ready"
|
|
418
|
+
* DCGridError until the simulation and the render pipelines are ready.
|
|
419
|
+
*
|
|
420
|
+
* - A texture target (rgba8unorm with STORAGE_BINDING) receives the image with alpha: 0 where the
|
|
421
|
+
* view sees only background. `backgroundColor` does not apply.
|
|
422
|
+
* - A canvas context (configured on the simulation's device) receives the image over
|
|
423
|
+
* `backgroundColor`, raymarched at `scale` times the canvas size (default 1) and scaled up.
|
|
313
424
|
*/
|
|
314
|
-
render(camera, settings, target) {
|
|
425
|
+
render(camera, settings, target, options = {}) {
|
|
426
|
+
if ("getCurrentTexture" in target) {
|
|
427
|
+
this.renderToCanvas(camera, settings, target, options.scale ?? 1);
|
|
428
|
+
return;
|
|
429
|
+
}
|
|
315
430
|
const c = new Float32Array([...camera.eye, ...camera.right, ...camera.up, ...camera.forward, camera.fovScale, ...camera.sunDirection]);
|
|
316
431
|
const code = this.dcgrid.withFloats(c, (cam) => this.dcgrid.withString(JSON.stringify(settings), (s) => this.dcgrid.withTexture(target, this.sim.device, (t) => this.m._dcgridJsRender(this.ptr, cam, s, t))));
|
|
317
432
|
this.dcgrid.check(code);
|
|
@@ -329,5 +444,65 @@ export class Renderer {
|
|
|
329
444
|
return;
|
|
330
445
|
this.destroyed = true;
|
|
331
446
|
this.m._dcgridRendererDestroy(this.ptr);
|
|
447
|
+
this.image?.destroy();
|
|
448
|
+
this.presentResources?.background.destroy();
|
|
449
|
+
}
|
|
450
|
+
renderToCanvas(camera, settings, context, scale) {
|
|
451
|
+
const device = this.sim.gpuDevice;
|
|
452
|
+
const canvas = context.canvas;
|
|
453
|
+
const w = Math.max(1, Math.round(canvas.width * scale));
|
|
454
|
+
const h = Math.max(1, Math.round(canvas.height * scale));
|
|
455
|
+
const format = context.getConfiguration?.()?.format ?? navigator.gpu.getPreferredCanvasFormat();
|
|
456
|
+
if (!this.image || this.image.width !== w || this.image.height !== h) {
|
|
457
|
+
this.image?.destroy();
|
|
458
|
+
this.image = device.createTexture({
|
|
459
|
+
label: "dcgrid render",
|
|
460
|
+
size: [w, h],
|
|
461
|
+
format: "rgba8unorm",
|
|
462
|
+
usage: GPUTextureUsage.STORAGE_BINDING | GPUTextureUsage.TEXTURE_BINDING,
|
|
463
|
+
});
|
|
464
|
+
if (this.present)
|
|
465
|
+
this.present.bindGroup = null;
|
|
466
|
+
}
|
|
467
|
+
this.render(camera, settings, this.image);
|
|
468
|
+
if (!this.presentResources)
|
|
469
|
+
this.presentResources = {
|
|
470
|
+
sampler: device.createSampler({ magFilter: "linear", minFilter: "linear" }),
|
|
471
|
+
background: device.createBuffer({ size: 16, usage: GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_DST }),
|
|
472
|
+
};
|
|
473
|
+
if (this.present?.format !== format) {
|
|
474
|
+
const module = device.createShaderModule({ code: PRESENT_WGSL });
|
|
475
|
+
this.present = {
|
|
476
|
+
format,
|
|
477
|
+
pipeline: device.createRenderPipeline({
|
|
478
|
+
label: "dcgrid present",
|
|
479
|
+
layout: "auto",
|
|
480
|
+
vertex: { module, entryPoint: "vs" },
|
|
481
|
+
fragment: { module, entryPoint: "fs", targets: [{ format }] },
|
|
482
|
+
}),
|
|
483
|
+
bindGroup: null,
|
|
484
|
+
};
|
|
485
|
+
}
|
|
486
|
+
const present = this.present;
|
|
487
|
+
present.bindGroup ??= device.createBindGroup({
|
|
488
|
+
layout: present.pipeline.getBindGroupLayout(0),
|
|
489
|
+
entries: [
|
|
490
|
+
{ binding: 0, resource: this.image.createView() },
|
|
491
|
+
{ binding: 1, resource: this.presentResources.sampler },
|
|
492
|
+
{ binding: 2, resource: { buffer: this.presentResources.background } },
|
|
493
|
+
],
|
|
494
|
+
});
|
|
495
|
+
this.defaultBackground ??= this.dcgrid.defaults().render.backgroundColor;
|
|
496
|
+
const background = settings.backgroundColor ?? this.defaultBackground;
|
|
497
|
+
device.queue.writeBuffer(this.presentResources.background, 0, new Float32Array([...background, 1]));
|
|
498
|
+
const encoder = device.createCommandEncoder();
|
|
499
|
+
const pass = encoder.beginRenderPass({
|
|
500
|
+
colorAttachments: [{ view: context.getCurrentTexture().createView(), loadOp: "clear", storeOp: "store", clearValue: [0, 0, 0, 1] }],
|
|
501
|
+
});
|
|
502
|
+
pass.setPipeline(present.pipeline);
|
|
503
|
+
pass.setBindGroup(0, present.bindGroup);
|
|
504
|
+
pass.draw(3);
|
|
505
|
+
pass.end();
|
|
506
|
+
device.queue.submit([encoder.finish()]);
|
|
332
507
|
}
|
|
333
508
|
}
|