-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpathtracer.ts
More file actions
281 lines (251 loc) · 10.5 KB
/
Copy pathpathtracer.ts
File metadata and controls
281 lines (251 loc) · 10.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
/**
* A path tracer, in one compute dispatch.
*
* bun run examples/pathtracer.ts # → pathtracer.png
* bun run examples/pathtracer.ts out.png
*
* A Cornell-style box with a spherical light, traced with cosine-weighted diffuse bounces and a
* dielectric and a metal to make the difference between the two visible. 1 024 samples per pixel,
* 8 bounces, at 900×900 — the kind of workload that is a coffee break on a CPU and about a second
* here.
*
* Why it belongs in this package's examples: this is the shape of the work a headless GPU binding
* is *for*. There is no frame loop, no interactivity and no window; there is one very large amount
* of arithmetic, and then an image. Everything about the pipeline is the boring part — a uniform
* buffer, one storage texture, one dispatch — and that is the point.
*
* The whole scene lives in the shader as constants. That keeps the example about the GPU rather
* than about a scene format, and it lets the compiler see the geometry, which is worth a good deal
* of the speed.
*/
import { create, globals } from "wgpu-bun";
import { saveTexturePng } from "wgpu-bun/image";
Object.assign(globalThis, globals);
const WIDTH = 900;
const HEIGHT = 900;
const SAMPLES = 4096;
const BOUNCES = 8;
const WGSL = /* wgsl */ `
struct Params {
width: u32,
height: u32,
samples: u32,
bounces: u32,
}
@group(0) @binding(0) var<uniform> p: Params;
@group(0) @binding(1) var image: texture_storage_2d<rgba8unorm, write>;
// ── material kinds ─────────────────────────────────────────────────────────────────────────────
const DIFFUSE: u32 = 0u;
const METAL: u32 = 1u;
const GLASS: u32 = 2u;
struct Sphere {
centre: vec3f,
radius: f32,
albedo: vec3f,
kind: u32,
emission: vec3f,
fuzz: f32,
}
/// The box is five enormous spheres, which is a trick worth knowing: a sphere of radius 10 000 is
/// flat to within a rounding error over a two-metre room, so the whole scene needs one intersection
/// routine instead of two. Planes would be cheaper and would double the code.
const SCENE = array<Sphere, 9>(
// walls
Sphere(vec3f( 0.0, -10000.0, 0.0), 10000.0, vec3f(0.73, 0.73, 0.73), DIFFUSE, vec3f(0.0), 0.0),
Sphere(vec3f( 0.0, 10002.0, 0.0), 10000.0, vec3f(0.73, 0.73, 0.73), DIFFUSE, vec3f(0.0), 0.0),
Sphere(vec3f( 0.0, 0.0, -10002.0), 10000.0, vec3f(0.73, 0.73, 0.73), DIFFUSE, vec3f(0.0), 0.0),
Sphere(vec3f(-10001.0, 0.0, 0.0), 10000.0, vec3f(0.75, 0.16, 0.16), DIFFUSE, vec3f(0.0), 0.0),
Sphere(vec3f( 10001.0, 0.0, 0.0), 10000.0, vec3f(0.16, 0.45, 0.75), DIFFUSE, vec3f(0.0), 0.0),
// light — a sphere rather than a quad, so the soft shadow comes from real area sampling
Sphere(vec3f( 0.0, 2.42, -0.6), 0.55, vec3f(0.0), DIFFUSE, vec3f(14.0, 12.4, 10.4), 0.0),
// contents
Sphere(vec3f(-0.42, 0.34, -1.05), 0.34, vec3f(0.99, 0.99, 0.99), GLASS, vec3f(0.0), 0.0),
Sphere(vec3f( 0.42, 0.38, -0.55), 0.38, vec3f(0.95, 0.85, 0.55), METAL, vec3f(0.0), 0.03),
Sphere(vec3f(-0.10, 0.20, -0.15), 0.20, vec3f(0.30, 0.72, 0.45), DIFFUSE, vec3f(0.0), 0.0),
);
// ── rng ────────────────────────────────────────────────────────────────────────────────────────
// PCG. A weak hash shows up as visible structure in the noise — correlated pixels look like a
// pattern in the image, not like grain — and at 1 024 samples there is nowhere for it to hide.
var<private> rngState: u32;
fn rand() -> f32 {
rngState = rngState * 747796405u + 2891336453u;
var word = ((rngState >> ((rngState >> 28u) + 4u)) ^ rngState) * 277803737u;
word = (word >> 22u) ^ word;
return f32(word) * 2.3283064365386963e-10;
}
/// Cosine-weighted hemisphere direction, built by normalising a point on a unit sphere offset by
/// the normal. Cosine weighting is what lets the diffuse BRDF's cosθ/π factor cancel against the pdf,
/// so a bounce costs one multiply by the albedo and nothing else.
fn cosineHemisphere(n: vec3f) -> vec3f {
let z = rand() * 2.0 - 1.0;
let a = rand() * 6.28318530718;
let r = sqrt(1.0 - z * z);
return normalize(n + vec3f(r * cos(a), r * sin(a), z));
}
struct Hit {
t: f32,
point: vec3f,
normal: vec3f,
index: u32,
front: bool,
}
fn intersect(origin: vec3f, dir: vec3f) -> Hit {
var best: Hit;
best.t = 1e30;
best.index = 0u;
for (var i = 0u; i < 9u; i = i + 1u) {
let s = SCENE[i];
let oc = origin - s.centre;
let b = dot(oc, dir);
let c = dot(oc, oc) - s.radius * s.radius;
let disc = b * b - c;
if (disc < 0.0) { continue; }
let sq = sqrt(disc);
var t = -b - sq;
if (t < 0.001) { t = -b + sq; }
if (t < 0.001 || t >= best.t) { continue; }
best.t = t;
best.index = i;
best.point = origin + dir * t;
let outward = (best.point - s.centre) / s.radius;
best.front = dot(dir, outward) < 0.0;
best.normal = select(-outward, outward, best.front);
}
return best;
}
/// Schlick's approximation to the Fresnel term — the reason a glass ball is a mirror at its rim and
/// a window at its centre.
fn schlick(cosine: f32, ratio: f32) -> f32 {
var r0 = (1.0 - ratio) / (1.0 + ratio);
r0 = r0 * r0;
return r0 + (1.0 - r0) * pow(1.0 - cosine, 5.0);
}
fn trace(startOrigin: vec3f, startDir: vec3f) -> vec3f {
var origin = startOrigin;
var dir = startDir;
var radiance = vec3f(0.0);
var throughput = vec3f(1.0);
for (var bounce = 0u; bounce < p.bounces; bounce = bounce + 1u) {
let hit = intersect(origin, dir);
if (hit.t >= 1e29) {
// Nothing outside the box. A grey environment here would light the scene through the walls'
// seams and quietly flatten everything.
break;
}
let s = SCENE[hit.index];
radiance = radiance + throughput * s.emission;
if (s.kind == DIFFUSE) {
throughput = throughput * s.albedo;
dir = cosineHemisphere(hit.normal);
} else if (s.kind == METAL) {
throughput = throughput * s.albedo;
dir = normalize(reflect(dir, hit.normal) + cosineHemisphere(hit.normal) * s.fuzz);
if (dot(dir, hit.normal) <= 0.0) { break; }
} else {
// Glass: refract, or reflect when Snell has no solution or Fresnel says so.
let ratio = select(1.5, 1.0 / 1.5, hit.front);
let cosTheta = min(dot(-dir, hit.normal), 1.0);
let sinTheta = sqrt(1.0 - cosTheta * cosTheta);
if (ratio * sinTheta > 1.0 || schlick(cosTheta, ratio) > rand()) {
dir = reflect(dir, hit.normal);
} else {
dir = refract(dir, hit.normal, ratio);
}
}
origin = hit.point + hit.normal * select(-0.0005, 0.0005, dot(dir, hit.normal) > 0.0);
// Russian roulette. Without it the loop always runs to the bounce limit and spends most of its
// time on paths that carry almost no energy; with it, the estimator stays unbiased because the
// survivors are scaled by exactly the probability that killed the others.
if (bounce > 2u) {
let q = max(throughput.x, max(throughput.y, throughput.z));
if (rand() > q) { break; }
throughput = throughput / max(q, 1e-4);
}
}
return radiance;
}
fn tonemapACES(x: vec3f) -> vec3f {
let a = 2.51; let b = 0.03; let c = 2.43; let d = 0.59; let e = 0.14;
return clamp((x * (a * x + b)) / (x * (c * x + d) + e), vec3f(0.0), vec3f(1.0));
}
fn encodeSrgb(x: vec3f) -> vec3f {
let lo = x * 12.92;
let hi = 1.055 * pow(max(x, vec3f(1e-5)), vec3f(1.0 / 2.4)) - 0.055;
return select(hi, lo, x <= vec3f(0.0031308));
}
@compute @workgroup_size(8, 8, 1)
fn main(@builtin(global_invocation_id) gid: vec3u) {
if (gid.x >= p.width || gid.y >= p.height) { return; }
rngState = gid.x * 1973u + gid.y * 9277u + 26699u;
let origin = vec3f(0.0, 1.0, 3.2);
let aspect = f32(p.width) / f32(p.height);
let tanHalfFov = tan(0.5 * 0.72);
var colour = vec3f(0.0);
for (var s = 0u; s < p.samples; s = s + 1u) {
// Jitter inside the pixel: the same stratification that antialiases the edges also antialiases
// the shadow boundaries, for free, because both are just more samples of the same integral.
let px = (f32(gid.x) + rand()) / f32(p.width) * 2.0 - 1.0;
let py = 1.0 - (f32(gid.y) + rand()) / f32(p.height) * 2.0;
let dir = normalize(vec3f(px * tanHalfFov * aspect, py * tanHalfFov, -1.0));
colour = colour + trace(origin, dir);
}
colour = colour / f32(p.samples);
textureStore(image, vec2i(gid.xy), vec4f(encodeSrgb(tonemapACES(colour)), 1.0));
}
`;
const gpu = create([]);
const adapter = await gpu.requestAdapter();
if (!adapter) throw new Error("no GPU adapter on this host");
const device = await adapter.requestDevice();
device.pushErrorScope("validation");
const module = device.createShaderModule({ label: "pathtracer", code: WGSL });
const pipeline = device.createComputePipeline({
label: "pathtracer",
layout: "auto",
compute: { module, entryPoint: "main" },
});
const params = new ArrayBuffer(16);
{
const view = new DataView(params);
view.setUint32(0, WIDTH, true);
view.setUint32(4, HEIGHT, true);
view.setUint32(8, SAMPLES, true);
view.setUint32(12, BOUNCES, true);
}
const paramsBuffer = device.createBuffer({
size: params.byteLength,
usage: GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_DST,
});
device.queue.writeBuffer(paramsBuffer, 0, params);
const image = device.createTexture({
label: "image",
size: [WIDTH, HEIGHT],
format: "rgba8unorm",
usage: GPUTextureUsage.STORAGE_BINDING | GPUTextureUsage.COPY_SRC,
});
const encoder = device.createCommandEncoder();
const pass = encoder.beginComputePass({ label: "trace" });
pass.setPipeline(pipeline);
pass.setBindGroup(
0,
device.createBindGroup({
layout: pipeline.getBindGroupLayout(0),
entries: [
{ binding: 0, resource: { buffer: paramsBuffer } },
{ binding: 1, resource: image.createView() },
],
}),
);
pass.dispatchWorkgroups(Math.ceil(WIDTH / 8), Math.ceil(HEIGHT / 8));
pass.end();
device.queue.submit([encoder.finish()]);
const error = await device.popErrorScope();
if (error) throw new Error(error.message);
const started = performance.now();
const out = process.argv[2] ?? "pathtracer.png";
await saveTexturePng(device, image, out);
const seconds = ((performance.now() - started) / 1000).toFixed(1);
console.log(
`wrote ${out} — ${WIDTH}×${HEIGHT}, ${SAMPLES} spp × ${BOUNCES} bounces ` +
`(${((WIDTH * HEIGHT * SAMPLES) / 1e6).toFixed(0)} M primary rays, ${seconds}s to readback)`,
);