-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathraytracer.wgsl
468 lines (380 loc) · 13.7 KB
/
raytracer.wgsl
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
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
const epsilon = 0.001f;
const pi = 3.1415927f;
const frac1Pi = 0.31830987f;
const fracPi2 = 1.5707964f;
const minT = 0.001f;
const maxT = 1000f;
const channelR = 0u;
const channelG = 1u;
const channelB = 2u;
@group(0) @binding(0) var<uniform> vertexUniforms: VertexUniforms;
@vertex
fn vsMain(model: VertexInput) -> VertexOutput {
return VertexOutput(
vertexUniforms.viewProjectionMat * vertexUniforms.modelMat * vec4<f32>(model.position, 0.0, 1.0),
model.texCoords
);
}
struct VertexUniforms {
viewProjectionMat: mat4x4<f32>,
modelMat: mat4x4<f32>,
}
struct VertexInput {
@location(0) position: vec2<f32>,
@location(1) texCoords: vec2<f32>,
}
struct VertexOutput {
@builtin(position) clipPosition: vec4<f32>,
@location(0) texCoords: vec2<f32>,
}
@group(1) @binding(0) var<uniform> imageDimensions: vec2<u32>;
@group(1) @binding(1) var<storage, read_write> imageBuffer: array<array<f32, 3>>;
@group(1) @binding(2) var<storage, read_write> rngStateBuffer: array<u32>;
@group(2) @binding(0) var<uniform> camera: Camera;
@group(2) @binding(1) var<uniform> samplingParams: SamplingParams;
@group(2) @binding(2) var<storage, read> skyState: SkyState;
@group(3) @binding(0) var<storage, read> spheres: array<Sphere>;
@group(3) @binding(1) var<storage, read> materials: array<Material>;
@group(3) @binding(2) var<storage, read> textures: array<array<f32, 3>>;
@fragment
fn fsMain(in: VertexOutput) -> @location(0) vec4<f32> {
let u = in.texCoords.x;
let v = in.texCoords.y;
let x = u32(u * f32(imageDimensions.x));
let y = u32(v * f32(imageDimensions.y));
let idx = imageDimensions.x * y + x;
var rngState = rngStateBuffer[idx];
var pixel = vec3(imageBuffer[idx][0u], imageBuffer[idx][1u], imageBuffer[idx][2u]);
{
if samplingParams.clearAccumulatedSamples == 1u {
pixel = vec3(0f);
}
let rgb = samplePixel(x, y, &rngState);
pixel += rgb;
}
imageBuffer[idx] = array<f32, 3>(pixel.r, pixel.g, pixel.b);
rngStateBuffer[idx] = rngState;
let invN = 1f / f32(samplingParams.accumulatedSamplesPerPixel);
return vec4(
uncharted2(invN * pixel),
1f
);
}
fn uncharted2(x: vec3<f32>) -> vec3<f32> {
// Based on uncharted2 tonemapping function
// https://dmnsgn.github.io/glsl-tone-map/
let exposureBias = 0.246; // determined experimentally for the scene
let curr = uncharted2Tonemap(exposureBias * x);
let w = 11.2;
let whiteScale = 1f / uncharted2Tonemap(vec3(w));
return whiteScale * curr;
}
fn uncharted2Tonemap(x: vec3<f32>) -> vec3<f32> {
let a = 0.15;
let b = 0.50;
let c = 0.10;
let d = 0.20;
let e = 0.02;
let f = 0.30;
let w = 11.2;
return ((x * (a * x + c * b) + d * e) / (x * (a * x + b) + d * f)) - e / f;
}
fn samplePixel(x: u32, y: u32, rngState: ptr<function, u32>) -> vec3<f32> {
let invWidth = 1f / f32(imageDimensions.x);
let invHeight = 1f / f32(imageDimensions.y);
let numSamples = samplingParams.numSamplesPerPixel;
var color = vec3(0f);
for (var i = 0u; i < numSamples; i += 1u) {
let u = (f32(x) + rngNextFloat(rngState)) * invWidth;
let v = (f32(y) + rngNextFloat(rngState)) * invHeight;
let primaryRay = cameraMakeRay(camera, rngState, u, 1f - v);
color += rayColor(primaryRay, rngState);
}
return color;
}
fn rayColor(primaryRay: Ray, rngState: ptr<function, u32>) -> vec3<f32> {
var ray = primaryRay;
var color = vec3(0f);
var throughput = vec3(1f);
for (var bounce = 0u; bounce < samplingParams.numBounces; bounce += 1u) {
var intersection = Intersection();
var materialIdx = 0u;
// Intersection test
var closestT = maxT;
for (var idx = 0u; idx < arrayLength(&spheres); idx = idx + 1u) {
let sphere = spheres[idx];
var testIntersect = Intersection();
if rayIntersectSphere(ray, sphere, minT, closestT, &testIntersect) {
closestT = testIntersect.t;
intersection = testIntersect;
materialIdx = sphere.materialIdx;
}
}
if closestT < maxT {
// Scatter the ray from the surface
let material = materials[materialIdx];
var scatter = scatterRay(ray, intersection, material, rngState);
ray = scatter.ray;
throughput *= scatter.albedo;
} else {
// The ray missed. Output background color.
let v = normalize(ray.direction);
let s = skyState.sunDirection;
let theta = acos(v.y);
let gamma = acos(clamp(dot(v, s), -1f, 1f));
color = vec3(
radiance(theta, gamma, channelR),
radiance(theta, gamma, channelG),
radiance(theta, gamma, channelB)
);
break;
}
}
return throughput * color;
}
fn scatterRay(rayIn: Ray, hit: Intersection, material: Material, rngState: ptr<function, u32>) -> Scatter {
switch material.id {
case 0u: {
return scatterLambertian(hit, material, rngState);
}
case 1u: {
return scatterMetal(rayIn, hit, material, rngState);
}
case 2u: {
return scatterDielectric(rayIn, hit, material, rngState);
}
case 3u: {
return scatterCheckerboard(rayIn, hit, material, rngState);
}
default: {
return scatterMissingMaterial(rayIn, hit, rngState);
}
}
}
fn scatterLambertian(hit: Intersection, material: Material, rngState: ptr<function, u32>) -> Scatter {
let scatterDirection = hit.n + rngNextVec3InUnitSphere(rngState);
let albedo = textureLookup(material.desc1, hit.u, hit.v);
return Scatter(Ray(hit.p, scatterDirection), albedo);
}
fn scatterMetal(rayIn: Ray, hit: Intersection, material: Material, rngState: ptr<function, u32>) -> Scatter {
let fuzz = material.x;
let scatterDirection = reflect(rayIn.direction, hit.n) + material.x * rngNextVec3InUnitSphere(rngState);
let albedo = textureLookup(material.desc1, hit.u, hit.v);
return Scatter(Ray(hit.p, scatterDirection), albedo);
}
fn scatterDielectric(rayIn: Ray, hit: Intersection, material: Material, rngState: ptr<function, u32>) -> Scatter {
let refractionIndex = material.x;
var outwardNormal = vec3(0f);
var niOverNt = 0f;
var cosine = 0f;
if dot(rayIn.direction, hit.n) > 0f {
outwardNormal = -hit.n;
niOverNt = refractionIndex;
cosine = refractionIndex * dot(normalize(rayIn.direction), hit.n);
} else {
outwardNormal = hit.n;
niOverNt = 1f / refractionIndex;
cosine = dot(normalize(-rayIn.direction), hit.n);
};
var refractedDirection = vec3(0f);
if refract(rayIn.direction, outwardNormal, niOverNt, &refractedDirection) {
let reflectionProb = schlick(cosine, refractionIndex);
var scatteredRay = refractedDirection;
if rngNextFloat(rngState) < reflectionProb {
reflect(rayIn.direction, hit.n);
}
return Scatter(Ray(hit.p, scatteredRay), vec3(1f));
}
let scatteredRay = reflect(rayIn.direction, hit.n);
return Scatter(Ray(hit.p, scatteredRay), vec3(1f));
}
fn scatterCheckerboard(rayIn: Ray, hit: Intersection, material: Material, rngState: ptr<function, u32>) -> Scatter {
let sines = sin(5f * hit.p.x) * sin(5f * hit.p.y) * sin(5f * hit.p.z);
var albedo: vec3<f32>;
if sines < 0f {
albedo = textureLookup(material.desc1, hit.u, hit.v);
} else {
albedo = textureLookup(material.desc2, hit.u, hit.v);
}
let scatterDirection = hit.n + rngNextVec3InUnitSphere(rngState);
return Scatter(Ray(hit.p, scatterDirection), albedo);
}
fn scatterMissingMaterial(rayIn: Ray, hit: Intersection, rngState: ptr<function, u32>) -> Scatter {
let scatterDirection = hit.n + rngNextVec3InUnitSphere(rngState);
// An aggressive pink color to indicate an error
let albedo = vec3(0.9921f, 0.24705f, 0.57254f);
return Scatter(Ray(hit.p, scatterDirection), albedo);
}
fn refract(v: vec3<f32>, n: vec3<f32>, niOverNt: f32, refractDirection: ptr<function, vec3<f32>>) -> bool {
// ni * sin(i) = nt * sin(t)
// sin(t) = sin(i) * (ni / nt)
let uv = normalize(v);
let dt = dot(uv, n);
let discriminant = 1f - niOverNt * niOverNt * (1f - dt * dt);
if discriminant > 0f {
*refractDirection = niOverNt * (uv - dt * n) - sqrt(discriminant) * n;
return true;
}
return false;
}
fn schlick(cosine: f32, refractionIndex: f32) -> f32 {
var r0 = (1f - refractionIndex) / (1f + refractionIndex);
r0 = r0 * r0;
return r0 + pow((1f - r0) * (1f - cosine), 5f);
}
fn radiance(theta: f32, gamma: f32, channel: u32) -> f32 {
let r = skyState.radiances[channel];
let idx = 9u * channel;
let p0 = skyState.params[idx + 0u];
let p1 = skyState.params[idx + 1u];
let p2 = skyState.params[idx + 2u];
let p3 = skyState.params[idx + 3u];
let p4 = skyState.params[idx + 4u];
let p5 = skyState.params[idx + 5u];
let p6 = skyState.params[idx + 6u];
let p7 = skyState.params[idx + 7u];
let p8 = skyState.params[idx + 8u];
let cosGamma = cos(gamma);
let cosGamma2 = cosGamma * cosGamma;
let cosTheta = abs(cos(theta));
let expM = exp(p4 * gamma);
let rayM = cosGamma2;
let mieMLhs = 1.0 + cosGamma2;
let mieMRhs = pow(1.0 + p8 * p8 - 2.0 * p8 * cosGamma, 1.5f);
let mieM = mieMLhs / mieMRhs;
let zenith = sqrt(cosTheta);
let radianceLhs = 1.0 + p0 * exp(p1 / (cosTheta + 0.01));
let radianceRhs = p2 + p3 * expM + p5 * rayM + p6 * mieM + p7 * zenith;
let radianceDist = radianceLhs * radianceRhs;
return r * radianceDist;
}
struct SkyState {
params: array<f32, 27>,
radiances: array<f32, 3>,
sunDirection: vec3<f32>,
};
struct SamplingParams {
numSamplesPerPixel: u32,
numBounces: u32,
accumulatedSamplesPerPixel: u32,
clearAccumulatedSamples: u32,
}
struct Sphere {
centerAndPad: vec4<f32>,
radius: f32,
materialIdx: u32,
}
struct Material {
id: u32,
desc1: TextureDescriptor,
desc2: TextureDescriptor,
x: f32,
}
struct TextureDescriptor {
width: u32,
height: u32,
offset: u32,
}
fn textureLookup(desc: TextureDescriptor, u: f32, v: f32) -> vec3<f32> {
let u = clamp(u, 0f, 1f);
let v = 1f - clamp(v, 0f, 1f);
let j = u32(u * f32(desc.width) - 1f);
let i = u32(v * f32(desc.height) - 1f);
let idx = i * desc.width + j;
let elem = textures[desc.offset + idx];
return vec3(elem[0u], elem[1u], elem[2u]);
}
struct Ray {
origin: vec3<f32>,
direction: vec3<f32>
}
struct Scatter {
ray: Ray,
albedo: vec3<f32>,
}
struct Intersection {
p: vec3<f32>,
n: vec3<f32>,
u: f32,
v: f32,
t: f32,
}
fn rayIntersectSphere(ray: Ray, sphere: Sphere, tmin: f32, tmax: f32, hit: ptr<function, Intersection>) -> bool {
let oc = ray.origin - sphere.centerAndPad.xyz;
let a = dot(ray.direction, ray.direction);
let b = dot(oc, ray.direction);
let c = dot(oc, oc) - sphere.radius * sphere.radius;
let discriminant = b * b - a * c;
if discriminant > 0f {
var t = (-b - sqrt(b * b - a * c)) / a;
if t < tmax && t > tmin {
*hit = sphereIntersection(ray, sphere, t);
return true;
}
t = (-b + sqrt(b * b - a * c)) / a;
if t < tmax && t > tmin {
*hit = sphereIntersection(ray, sphere, t);
return true;
}
}
return false;
}
fn sphereIntersection(ray: Ray, sphere: Sphere, t: f32) -> Intersection {
let p = rayPointAtParameter(ray, t);
let n = (1f / sphere.radius) * (p - sphere.centerAndPad.xyz);
let theta = acos(-n.y);
let phi = atan2(-n.z, n.x) + pi;
let u = 0.5 * frac1Pi * phi;
let v = frac1Pi * theta;
return Intersection(p, n, u, v, t);
}
fn rayPointAtParameter(ray: Ray, t: f32) -> vec3<f32> {
return ray.origin + t * ray.direction;
}
struct Camera {
eye: vec3<f32>,
horizontal: vec3<f32>,
vertical: vec3<f32>,
u: vec3<f32>,
v: vec3<f32>,
lensRadius: f32,
lowerLeftCorner: vec3<f32>,
}
fn cameraMakeRay(camera: Camera, rngState: ptr<function, u32>, u: f32, v: f32) -> Ray {
let randomPointInLens = camera.lensRadius * rngNextVec3InUnitDisk(rngState);
let lensOffset = randomPointInLens.x * camera.u + randomPointInLens.y * camera.v;
let origin = camera.eye + lensOffset;
let direction = camera.lowerLeftCorner + u * camera.horizontal + v * camera.vertical - origin;
return Ray(origin, direction);
}
fn rngNextVec3InUnitDisk(state: ptr<function, u32>) -> vec3<f32> {
// Generate numbers uniformly in a disk:
// https://stats.stackexchange.com/a/481559
// r^2 is distributed as U(0, 1).
let r = sqrt(rngNextFloat(state));
let alpha = 2f * pi * rngNextFloat(state);
let x = r * cos(alpha);
let y = r * sin(alpha);
return vec3(x, y, 0f);
}
fn rngNextVec3InUnitSphere(state: ptr<function, u32>) -> vec3<f32> {
// probability density is uniformly distributed over r^3
let r = pow(rngNextFloat(state), 0.33333f);
let theta = pi * rngNextFloat(state);
let phi = 2f * pi * rngNextFloat(state);
let x = r * sin(theta) * cos(phi);
let y = r * sin(theta) * sin(phi);
let z = r * cos(theta);
return vec3(x, y, z);
}
fn rngNextFloat(state: ptr<function, u32>) -> f32 {
rngNextInt(state);
return f32(*state) / f32(0xffffffffu);
}
fn rngNextInt(state: ptr<function, u32>) {
// PCG random number generator
// Based on https://www.shadertoy.com/view/XlGcRh
let oldState = *state + 747796405u + 2891336453u;
let word = ((oldState >> ((oldState >> 28u) + 4u)) ^ oldState) * 277803737u;
*state = (word >> 22u) ^ word;
}