Repository navigation
Expand file tree
/
Copy pathchapter-2.html
More file actions
763 lines (674 loc) · 32.1 KB
/
Copy pathchapter-2.html
File metadata and controls
763 lines (674 loc) · 32.1 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
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
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Ray Tracing: The Next Week</title>
<style>
body { background-color: #1a1a1a; color: white; font-family: sans-serif; display: flex; flex-direction: column; align-items: center; margin-top: 1rem; }
canvas { background-color: black; box-shadow: 0 4px 15px rgba(0,0,0,0.8); border-radius: 4px; margin-bottom: 1rem; }
.dashboard { display: flex; gap: 2rem; flex-wrap: wrap; justify-content: center; max-width: 900px; }
.control-panel { background: #2a2a2a; padding: 1.5rem; border-radius: 8px; display: flex; flex-direction: column; gap: 1rem; flex: 1; min-width: 250px; }
.panel-title { font-weight: bold; margin-bottom: 0.5rem; color: #4CAF50; border-bottom: 1px solid #444; padding-bottom: 0.5rem; text-align: center; }
.control-group { display: flex; justify-content: space-between; align-items: center; font-size: 0.9em; }
input[type="range"] { cursor: pointer; width: 120px; }
input[type="checkbox"] { cursor: pointer; height: 25px; border: none; border-radius: 4px; background: none; }
#status { font-family: monospace; color: #ffeb3b; font-weight: bold; margin-bottom: 1rem; font-size: 1.1em; }
</style>
</head>
<body>
<h2>Ray Tracing: The Next Week</h2>
<div id="status">Ready</div>
<canvas id="renderCanvas" width="500" height="500"></canvas>
<div class="dashboard">
<div class="control-panel">
<div class="panel-title">Renderer Limits</div>
<div class="control-group">
<label>Enable Two-phase simple denoiser:</label>
<input type="checkbox" id="denoiseToggle">
</div>
<div class="control-group">
<label>Samples/Pixel:</label>
<div><span id="samplesVal">20</span> <input type="range" id="samplesSlider" min="5" max="200" step="5" value="20"></div>
</div>
<div class="control-group">
<label>Max Bounces:</label>
<div><span id="depthVal">8</span> <input type="range" id="depthSlider" min="2" max="40" step="1" value="8"></div>
</div>
</div>
<div class="control-panel">
<div class="panel-title">Volumetric Controls</div>
<div class="control-group">
<label>Global Fog Density:</label>
<div><span id="globalFogVal">0.0001</span> <input type="range" id="globalFogSlider" min="0.0000" max="0.0010" step="0.0001" value="0.0001"></div>
</div>
<div class="control-group">
<label>Blue Sphere Fog:</label>
<div><span id="fogVal">0.20</span> <input type="range" id="fogSlider" min="0.01" max="1.0" step="0.05" value="0.20"></div>
</div>
</div>
</div>
<script>
const workerScript = `
class Vec3 {
constructor(x, y, z) { this.x = x; this.y = y; this.z = z; }
add(v) { return new Vec3(this.x + v.x, this.y + v.y, this.z + v.z); }
sub(v) { return new Vec3(this.x - v.x, this.y - v.y, this.z - v.z); }
mul(t) { return new Vec3(this.x * t, this.y * t, this.z * t); }
mulV(v) { return new Vec3(this.x * v.x, this.y * v.y, this.z * v.z); }
div(t) { return this.mul(1/t); }
lengthSq() { return this.x*this.x + this.y*this.y + this.z*this.z; }
length() { return Math.sqrt(this.lengthSq()); }
normalize() { return this.div(this.length()); }
static dot(u, v) { return u.x*v.x + u.y*v.y + u.z*v.z; }
static cross(u, v) { return new Vec3(u.y*v.z - u.z*v.y, u.z*v.x - u.x*v.z, u.x*v.y - u.y*v.x); }
static random(min=0, max=1) { return new Vec3(min + Math.random()*(max-min), min + Math.random()*(max-min), min + Math.random()*(max-min)); }
static randomInUnitSphere() {
while (true) { let p = Vec3.random(-1, 1); if (p.lengthSq() < 1) return p; }
}
static randomUnitVector() { return Vec3.randomInUnitSphere().normalize(); }
static reflect(v, n) { return v.sub(n.mul(2 * Vec3.dot(v, n))); }
static refract(uv, n, etai_over_etat) {
let cos_theta = Math.min(Vec3.dot(uv.mul(-1), n), 1.0);
let r_out_perp = uv.add(n.mul(cos_theta)).mul(etai_over_etat);
let r_out_parallel = n.mul(-Math.sqrt(Math.abs(1.0 - r_out_perp.lengthSq())));
return r_out_perp.add(r_out_parallel);
}
}
class Ray {
constructor(origin, direction, time = 0.0) { this.origin = origin; this.direction = direction; this.time = time; }
at(t) { return this.origin.add(this.direction.mul(t)); }
}
// --- PRE-COMPUTED LUT OPTIMIZATION ---
function computeHaltonLUT(base, size) {
let lut = new Float32Array(size);
for (let k = 0; k < size; k++) {
let result = 0;
let f = 1.0 / base;
let i = k + 1;
while (i > 0) {
result = result + f * (i % base);
i = Math.floor(i / base);
f = f / base;
}
lut[k] = result;
}
return lut;
}
// We pre-compute 1024 values per dimension just once when the worker spawns!
const LUT_SIZE = 1024;
const halton2 = computeHaltonLUT(2, LUT_SIZE);
const halton3 = computeHaltonLUT(3, LUT_SIZE);
const halton5 = computeHaltonLUT(5, LUT_SIZE);
// --- QUASI-MONTE CARLO (HALTON SEQUENCE) ---
// NOTE: The halton() function is no longer used in the main rendering loop,
// but is kept here for reference and educational purposes. The actual sampling
// now uses the pre-computed LUTs for performance reasons. ---
function halton(index, base) {
let result = 0;
let f = 1.0 / base;
let i = index;
while (i > 0) {
result = result + f * (i % base);
i = Math.floor(i / base);
f = f / base;
}
return result;
}
// --- TEXTURES ---
class SolidColor {
constructor(color) { this.color = color; }
value(u, v, p) { return this.color; }
}
class NoiseTexture {
constructor(scale) { this.scale = scale; }
value(u, v, p) {
let s = this.scale;
let n = Math.sin(s * p.z + 5 * Math.sin(s * p.x) + 5 * Math.sin(s * p.y));
return new Vec3(1,1,1).mul(0.5 * (1 + n));
}
}
// --- MATERIALS ---
class Material {
emitted(front_face) { return new Vec3(0, 0, 0); }
scatter(ray, rec) { return null; }
}
class Lambertian extends Material {
constructor(texture) { super(); this.albedo = texture; }
scatter(ray, rec) {
let scatter_dir = rec.normal.add(Vec3.randomUnitVector());
if (scatter_dir.lengthSq() < 1e-8) scatter_dir = rec.normal;
return { ray: new Ray(rec.p, scatter_dir, ray.time), attenuation: this.albedo.value(rec.u, rec.v, rec.p) };
}
}
class Metal extends Material {
constructor(albedo, fuzz) { super(); this.albedo = albedo; this.fuzz = fuzz; }
scatter(ray, rec) {
let reflected = Vec3.reflect(ray.direction.normalize(), rec.normal);
let scattered = new Ray(rec.p, reflected.add(Vec3.randomInUnitSphere().mul(this.fuzz)), ray.time);
if (Vec3.dot(scattered.direction, rec.normal) > 0) return { ray: scattered, attenuation: this.albedo };
return null;
}
}
class Dielectric extends Material {
constructor(ir) { super(); this.ir = ir; }
scatter(ray, rec) {
let refraction_ratio = rec.front_face ? (1.0 / this.ir) : this.ir;
let unit_direction = ray.direction.normalize();
let cos_theta = Math.min(Vec3.dot(unit_direction.mul(-1), rec.normal), 1.0);
let sin_theta = Math.sqrt(1.0 - cos_theta*cos_theta);
let direction = (refraction_ratio * sin_theta > 1.0 || this.reflectance(cos_theta, refraction_ratio) > Math.random())
? Vec3.reflect(unit_direction, rec.normal)
: Vec3.refract(unit_direction, rec.normal, refraction_ratio);
return { ray: new Ray(rec.p, direction, ray.time), attenuation: new Vec3(1.0, 1.0, 1.0) };
}
reflectance(cosine, ref_idx) {
let r0 = (1 - ref_idx) / (1 + ref_idx); r0 = r0 * r0;
return r0 + (1 - r0) * Math.pow((1 - cosine), 5);
}
}
class DiffuseLight extends Material {
constructor(color) { super(); this.color = color; }
scatter(ray, rec) { return null; }
emitted(front_face) { return front_face ? this.color : new Vec3(0,0,0); }
}
class Isotropic extends Material {
constructor(color) { super(); this.albedo = color; }
scatter(ray, rec) {
return { ray: new Ray(rec.p, Vec3.randomUnitVector(), ray.time), attenuation: this.albedo };
}
}
// --- GEOMETRY & VOLUMES ---
class Sphere {
constructor(center, radius, material) { this.center = center; this.radius = radius; this.material = material; }
hit(ray, t_min, t_max) {
let oc = ray.origin.sub(this.center);
let a = ray.direction.lengthSq();
let half_b = Vec3.dot(oc, ray.direction);
let c = oc.lengthSq() - this.radius * this.radius;
let discriminant = half_b * half_b - a * c;
if (discriminant < 0) return null;
let sqrtd = Math.sqrt(discriminant);
let root = (-half_b - sqrtd) / a;
if (root <= t_min || t_max <= root) {
root = (-half_b + sqrtd) / a;
if (root <= t_min || t_max <= root) return null;
}
let p = ray.at(root);
let outward_normal = p.sub(this.center).div(this.radius);
let front_face = Vec3.dot(ray.direction, outward_normal) < 0;
return { t: root, p: p, normal: front_face ? outward_normal : outward_normal.mul(-1), front_face: front_face, material: this.material };
}
}
class MovingSphere {
constructor(center0, center1, time0, time1, radius, material) {
this.center0 = center0; this.center1 = center1;
this.time0 = time0; this.time1 = time1;
this.radius = radius; this.material = material;
}
center(time) {
let t = (time - this.time0) / (this.time1 - this.time0);
return this.center0.add(this.center1.sub(this.center0).mul(t));
}
hit(ray, t_min, t_max) {
let current_center = this.center(ray.time);
let oc = ray.origin.sub(current_center);
let a = ray.direction.lengthSq();
let half_b = Vec3.dot(oc, ray.direction);
let c = oc.lengthSq() - this.radius * this.radius;
let discriminant = half_b * half_b - a * c;
if (discriminant < 0) return null;
let sqrtd = Math.sqrt(discriminant);
let root = (-half_b - sqrtd) / a;
if (root <= t_min || t_max <= root) {
root = (-half_b + sqrtd) / a;
if (root <= t_min || t_max <= root) return null;
}
let p = ray.at(root);
let outward_normal = p.sub(current_center).div(this.radius);
let front_face = Vec3.dot(ray.direction, outward_normal) < 0;
return { t: root, p: p, normal: front_face ? outward_normal : outward_normal.mul(-1), front_face: front_face, material: this.material };
}
}
class Quad {
constructor(Q, u, v, material) {
this.Q = Q; this.u = u; this.v = v; this.material = material;
let n = Vec3.cross(u, v);
this.normal = n.normalize();
this.D = Vec3.dot(this.normal, Q);
this.w = n.div(Vec3.dot(n, n));
}
hit(ray, t_min, t_max) {
let denom = Vec3.dot(this.normal, ray.direction);
if (Math.abs(denom) < 1e-8) return null;
let t = (this.D - Vec3.dot(this.normal, ray.origin)) / denom;
if (t < t_min || t > t_max) return null;
let intersection = ray.at(t);
let planar_hitpt_vector = intersection.sub(this.Q);
let alpha = Vec3.dot(this.w, Vec3.cross(planar_hitpt_vector, this.v));
let beta = Vec3.dot(this.w, Vec3.cross(this.u, planar_hitpt_vector));
if (alpha < 0 || alpha > 1 || beta < 0 || beta > 1) return null;
let front_face = Vec3.dot(ray.direction, this.normal) < 0;
return { t: t, p: intersection, normal: front_face ? this.normal : this.normal.mul(-1), front_face: front_face, material: this.material };
}
}
class ConstantMedium {
constructor(boundary, density, color) {
this.boundary = boundary;
this.neg_inv_density = -1.0 / density;
this.phase_function = new Isotropic(color);
}
hit(ray, t_min, t_max) {
let rec1 = this.boundary.hit(ray, -Infinity, Infinity);
if (!rec1) return null;
let rec2 = this.boundary.hit(ray, rec1.t + 0.0001, Infinity);
if (!rec2) return null;
let t1 = Math.max(rec1.t, t_min);
let t2 = Math.min(rec2.t, t_max);
if (t1 >= t2) return null;
t1 = Math.max(t1, 0);
let ray_length = ray.direction.length();
let distance_inside_boundary = (t2 - t1) * ray_length;
let hit_distance = this.neg_inv_density * Math.log(Math.random());
if (hit_distance > distance_inside_boundary) return null;
let t = t1 + hit_distance / ray_length;
return { t: t, p: ray.at(t), normal: new Vec3(1,0,0), front_face: true, material: this.phase_function };
}
}
class Translate {
constructor(obj, offset) { this.obj = obj; this.offset = offset; }
hit(ray, t_min, t_max) {
let offset_ray = new Ray(ray.origin.sub(this.offset), ray.direction, ray.time);
let rec = this.obj.hit(offset_ray, t_min, t_max);
if (!rec) return null;
rec.p = rec.p.add(this.offset);
return rec;
}
}
class RotateY {
constructor(obj, angle) {
this.obj = obj;
let radians = (Math.PI / 180.0) * angle;
this.sin_theta = Math.sin(radians);
this.cos_theta = Math.cos(radians);
}
hit(ray, t_min, t_max) {
let origin = new Vec3(
this.cos_theta * ray.origin.x - this.sin_theta * ray.origin.z,
ray.origin.y,
this.sin_theta * ray.origin.x + this.cos_theta * ray.origin.z
);
let direction = new Vec3(
this.cos_theta * ray.direction.x - this.sin_theta * ray.direction.z,
ray.direction.y,
this.sin_theta * ray.direction.x + this.cos_theta * ray.direction.z
);
let rotated_r = new Ray(origin, direction, ray.time);
let rec = this.obj.hit(rotated_r, t_min, t_max);
if (!rec) return null;
let p = new Vec3(
this.cos_theta * rec.p.x + this.sin_theta * rec.p.z,
rec.p.y,
-this.sin_theta * rec.p.x + this.cos_theta * rec.p.z
);
let normal = new Vec3(
this.cos_theta * rec.normal.x + this.sin_theta * rec.normal.z,
rec.normal.y,
-this.sin_theta * rec.normal.x + this.cos_theta * rec.normal.z
);
return { t: rec.t, p: p, normal: normal, front_face: rec.front_face, material: rec.material };
}
}
class HittableList {
constructor() { this.objects = []; }
add(obj) { this.objects.push(obj); }
hit(ray, t_min, t_max) {
let temp_rec = null, closest_so_far = t_max;
for (let obj of this.objects) {
let rec = obj.hit(ray, t_min, closest_so_far);
if (rec) { closest_so_far = rec.t; temp_rec = rec; }
}
return temp_rec;
}
}
class BoundingNode {
constructor(hittable, min, max) {
this.hittable = hittable;
this.min = min; this.max = max;
}
hit(ray, t_min, t_max) {
for (let a = 0; a < 3; a++) {
let invD = 1.0 / (a===0 ? ray.direction.x : (a===1 ? ray.direction.y : ray.direction.z));
let origin = a===0 ? ray.origin.x : (a===1 ? ray.origin.y : ray.origin.z);
let minVal = a===0 ? this.min.x : (a===1 ? this.min.y : this.min.z);
let maxVal = a===0 ? this.max.x : (a===1 ? this.max.y : this.max.z);
let t0 = (minVal - origin) * invD;
let t1 = (maxVal - origin) * invD;
if (invD < 0.0) { let tmp = t0; t0 = t1; t1 = tmp; }
t_min = t0 > t_min ? t0 : t_min;
t_max = t1 < t_max ? t1 : t_max;
if (t_max <= t_min) return null;
}
return this.hittable.hit(ray, t_min, t_max);
}
}
function box(a, b, mat) {
let sides = new HittableList();
let min = new Vec3(Math.min(a.x, b.x), Math.min(a.y, b.y), Math.min(a.z, b.z));
let max = new Vec3(Math.max(a.x, b.x), Math.max(a.y, b.y), Math.max(a.z, b.z));
let dx = new Vec3(max.x - min.x, 0, 0);
let dy = new Vec3(0, max.y - min.y, 0);
let dz = new Vec3(0, 0, max.z - min.z);
sides.add(new Quad(new Vec3(min.x, min.y, max.z), dx, dy, mat));
sides.add(new Quad(new Vec3(max.x, min.y, max.z), dz.mul(-1), dy, mat));
sides.add(new Quad(new Vec3(max.x, min.y, min.z), dx.mul(-1), dy, mat));
sides.add(new Quad(new Vec3(min.x, min.y, min.z), dz, dy, mat));
sides.add(new Quad(new Vec3(min.x, max.y, max.z), dx, dz.mul(-1), mat));
sides.add(new Quad(new Vec3(min.x, min.y, min.z), dx, dz, mat));
return sides;
}
function rayColor(ray, world, depth) {
if (depth <= 0) return new Vec3(0, 0, 0);
let rec = world.hit(ray, 0.001, Infinity);
if (!rec) return new Vec3(0, 0, 0);
let emitted = rec.material.emitted(rec.front_face);
let scatterResult = rec.material.scatter(ray, rec);
if (scatterResult) {
let colorFromBounce = rayColor(scatterResult.ray, world, depth - 1);
return emitted.add(scatterResult.attenuation.mulV(colorFromBounce));
}
return emitted;
}
function buildScene(cfg) {
let world = new HittableList();
let seed = 9876543;
function seededRandom(min=0, max=1) {
seed = (seed * 9301 + 49297) % 233280;
return min + (seed / 233280) * (max - min);
}
// 1. GROUND BOXES
let boxes1 = new HittableList();
let groundMat = new Lambertian(new SolidColor(new Vec3(0.48, 0.83, 0.53)));
let boxes_per_side = 20;
for(let i=0; i<boxes_per_side; i++) {
for(let j=0; j<boxes_per_side; j++) {
let w = 100.0;
let x0 = -1000.0 + i*w; let z0 = -1000.0 + j*w; let y0 = 0.0;
let x1 = x0 + w;
let y1 = seededRandom(1, 101);
let z1 = z0 + w;
boxes1.add(box(new Vec3(x0,y0,z0), new Vec3(x1,y1,z1), groundMat));
}
}
world.add(new BoundingNode(boxes1, new Vec3(-1000, 0, -1000), new Vec3(1000, 102, 1000)));
// 2. LIGHT Panel
let light = new DiffuseLight(new Vec3(7, 7, 7));
world.add(new Quad(new Vec3(123,554,147), new Vec3(300,0,0), new Vec3(0,0,265), light));
// 3. Central Spheres
let center1 = new Vec3(400, 400, 200);
let center2 = center1.add(new Vec3(30, 0, 0));
world.add(new MovingSphere(center1, center2, 0, 1, 50, new Lambertian(new SolidColor(new Vec3(0.7, 0.3, 0.1)))));
world.add(new Sphere(new Vec3(260, 150, 45), 50, new Dielectric(1.5)));
world.add(new Sphere(new Vec3(0, 150, 145), 50, new Metal(new Vec3(0.8, 0.8, 0.9), 1.0)));
// 4. Blue Fog Volume
let boundary = new Sphere(new Vec3(360, 150, 145), 70, new Dielectric(1.5));
world.add(boundary);
world.add(new ConstantMedium(boundary, cfg.fog, new Vec3(0.2, 0.4, 0.9)));
// 5. GLOBAL FOG
let universe = new Sphere(new Vec3(0,0,0), 5000, new Dielectric(1.5));
world.add(new ConstantMedium(universe, cfg.globalFog, new Vec3(1, 1, 1)));
// 6. Two Noise Spheres
let noiseMat = new Lambertian(new NoiseTexture(0.2));
world.add(new Sphere(new Vec3(220, 280, 300), 80, noiseMat));
let earthMat = new Lambertian(new SolidColor(new Vec3(0.2, 0.3, 0.6)));
world.add(new Sphere(new Vec3(400, 200, 400), 100, earthMat));
// 7. Translated & Rotated Block Cluster
let boxes2 = new HittableList();
let white = new Lambertian(new SolidColor(new Vec3(0.73, 0.73, 0.73)));
for(let j=0; j<1000; j++) {
let rx = seededRandom(0, 165);
let ry = seededRandom(0, 165);
let rz = seededRandom(0, 165);
boxes2.add(new Sphere(new Vec3(rx, ry, rz), 10, white));
}
let clusterNode = new BoundingNode(boxes2, new Vec3(0,0,0), new Vec3(175,175,175));
world.add(new Translate(new RotateY(clusterNode, 15), new Vec3(-100, 270, 395)));
return world;
}
self.onmessage = function(e) {
const { startX, startY, tileWidth, tileHeight, imageWidth, imageHeight, cfg } = e.data;
const buffer = new Uint8ClampedArray(tileWidth * tileHeight * 4);
const world = buildScene(cfg);
let lookfrom = new Vec3(478, 278, -600);
let lookat = new Vec3(278, 278, 0);
let vup = new Vec3(0, 1, 0);
let theta = 40 * Math.PI / 180.0;
let h = Math.tan(theta/2);
let viewport_height = 2.0 * h;
let viewport_width = viewport_height * (imageWidth / imageHeight);
let w = lookfrom.sub(lookat).normalize();
let u = Vec3.cross(vup, w).normalize();
let v = Vec3.cross(w, u);
let origin = lookfrom;
let horizontal = u.mul(viewport_width);
let vertical = v.mul(viewport_height);
let lower_left_corner = origin.sub(horizontal.div(2)).sub(vertical.div(2)).sub(w);
let endY = startY + tileHeight;
let endX = startX + tileWidth;
let ptr = 0;
for (let j = endY - 1; j >= startY; --j) {
for (let i = startX; i < endX; ++i) {
// CRANLEY-PATTERSON ROTATION
let pixel_hash = (i * 73856093) ^ (j * 19349663);
let rand_offset_x = (pixel_hash & 0xFFFF) / 65535.0;
let rand_offset_y = ((pixel_hash >> 16) & 0xFFFF) / 65535.0;
// Add a hash dimension for time offsets as well!
let rand_offset_t = ((pixel_hash * 39916801) & 0xFFFF) / 65535.0;
let pixel_color = new Vec3(0, 0, 0);
for (let s = 0; s < cfg.samples; ++s) {
// FAST PRE-COMPUTED LUT LOOKUP
let s_idx = s % LUT_SIZE;
let u_offset = (halton2[s_idx] + rand_offset_x) % 1.0;
let v_offset = (halton3[s_idx] + rand_offset_y) % 1.0;
let t_offset = (halton5[s_idx] + rand_offset_t) % 1.0;
let s_u = (i + u_offset) / (imageWidth - 1);
let s_v = (j + v_offset) / (imageHeight - 1);
let dir = lower_left_corner.add(horizontal.mul(s_u)).add(vertical.mul(s_v)).sub(origin);
// Assign Halton time for smooth Motion Blur
let r = new Ray(origin, dir, t_offset);
pixel_color = pixel_color.add(rayColor(r, world, cfg.depth));
}
let scale = 1.0 / cfg.samples;
let c_r = Math.sqrt(pixel_color.x * scale);
let c_g = Math.sqrt(pixel_color.y * scale);
let c_b = Math.sqrt(pixel_color.z * scale);
buffer[ptr++] = 256 * Math.max(0.0, Math.min(0.999, c_r));
buffer[ptr++] = 256 * Math.max(0.0, Math.min(0.999, c_g));
buffer[ptr++] = 256 * Math.max(0.0, Math.min(0.999, c_b));
buffer[ptr++] = 255;
}
}
self.postMessage({ startX, startY, tileWidth, tileHeight, buffer }, [buffer.buffer]);
};
`;
const canvas = document.getElementById('renderCanvas');
const ctx = canvas.getContext('2d');
const statusText = document.getElementById('status');
const blob = new Blob([workerScript], { type: 'application/javascript' });
const workerUrl = URL.createObjectURL(blob);
const elements = {
samples: document.getElementById('samplesSlider'),
depth: document.getElementById('depthSlider'),
globalFog: document.getElementById('globalFogSlider'),
fog: document.getElementById('fogSlider'),
denoise: document.getElementById('denoiseToggle')
};
let workers = [];
let activeWorkers = 0;
let taskQueue = [];
let rawImageData = null;
function applyDenoiser() {
if (!rawImageData) return;
statusText.innerText = "Applying Advanced 2-Pass Denoiser...";
setTimeout(() => {
const width = canvas.width;
const height = canvas.height;
const data = rawImageData.data;
const size = width * height * 4;
// PASS 1: FIREFLY REJECTION
const clampedData = new Uint8ClampedArray(size);
for (let y = 0; y < height; y++) {
for (let x = 0; x < width; x++) {
const idx = (y * width + x) * 4;
if (x === 0 || x === width - 1 || y === 0 || y === height - 1) {
clampedData[idx] = data[idx]; clampedData[idx+1] = data[idx+1];
clampedData[idx+2] = data[idx+2]; clampedData[idx+3] = 255; continue;
}
let minR = 255, minG = 255, minB = 255;
let maxR = 0, maxG = 0, maxB = 0;
for (let dy = -1; dy <= 1; dy++) {
for (let dx = -1; dx <= 1; dx++) {
if (dx === 0 && dy === 0) continue;
const nIdx = ((y + dy) * width + (x + dx)) * 4;
const r = data[nIdx], g = data[nIdx+1], b = data[nIdx+2];
if (r < minR) minR = r; if (r > maxR) maxR = r;
if (g < minG) minG = g; if (g > maxG) maxG = g;
if (b < minB) minB = b; if (b > maxB) maxB = b;
}
}
clampedData[idx] = Math.max(minR, Math.min(maxR, data[idx]));
clampedData[idx+1] = Math.max(minG, Math.min(maxG, data[idx+1]));
clampedData[idx+2] = Math.max(minB, Math.min(maxB, data[idx+2]));
clampedData[idx+3] = 255;
}
}
// PASS 2: BILATERAL FILTER
const output = new Uint8ClampedArray(size);
const radius = 2;
const sigmaSpatial = 2.0;
const sigmaColor = 0.25 * 255;
const spatialWeights = [];
for (let dy = -radius; dy <= radius; dy++) {
for (let dx = -radius; dx <= radius; dx++) {
spatialWeights.push(Math.exp(-(dx*dx + dy*dy) / (2 * sigmaSpatial * sigmaSpatial)));
}
}
for (let y = 0; y < height; y++) {
for (let x = 0; x < width; x++) {
const idx = (y * width + x) * 4;
const r = clampedData[idx]; const g = clampedData[idx+1]; const b = clampedData[idx+2];
let rSum = 0, gSum = 0, bSum = 0, wSum = 0; let wIdx = 0;
for (let dy = -radius; dy <= radius; dy++) {
const ny = y + dy;
if (ny < 0 || ny >= height) { wIdx += (radius*2+1); continue; }
const rowOffset = ny * width;
for (let dx = -radius; dx <= radius; dx++) {
const nx = x + dx;
if (nx < 0 || nx >= width) { wIdx++; continue; }
const nIdx = (rowOffset + nx) * 4;
const nr = clampedData[nIdx]; const ng = clampedData[nIdx+1]; const nb = clampedData[nIdx+2];
const distColorSq = (r-nr)*(r-nr) + (g-ng)*(g-ng) + (b-nb)*(b-nb);
const colorWeight = Math.exp(-distColorSq / (2 * sigmaColor * sigmaColor));
const weight = spatialWeights[wIdx++] * colorWeight;
rSum += nr * weight; gSum += ng * weight; bSum += nb * weight;
wSum += weight;
}
}
output[idx] = rSum / wSum; output[idx+1] = gSum / wSum;
output[idx+2] = bSum / wSum; output[idx+3] = 255;
}
}
ctx.putImageData(new ImageData(output, width, height), 0, 0);
statusText.innerText = "Render & Denoise Complete";
}, 10);
}
function startRender() {
workers.forEach(w => w.terminate());
workers = [];
activeWorkers = 0;
taskQueue = [];
rawImageData = null;
ctx.fillStyle = "black";
ctx.fillRect(0, 0, canvas.width, canvas.height);
const cfg = {
samples: parseInt(elements.samples.value),
depth: parseInt(elements.depth.value),
globalFog: parseFloat(elements.globalFog.value),
fog: parseFloat(elements.fog.value)
};
const width = canvas.width;
const height = canvas.height;
const TILE_SIZE = 64;
for (let y = 0; y < height; y += TILE_SIZE) {
for (let x = 0; x < width; x += TILE_SIZE) {
taskQueue.push({
startX: x,
startY: y,
tileWidth: Math.min(TILE_SIZE, width - x),
tileHeight: Math.min(TILE_SIZE, height - y)
});
}
}
taskQueue.sort((a, b) => {
let distA = Math.pow(a.startX - width/2, 2) + Math.pow(a.startY - height/2, 2);
let distB = Math.pow(b.startX - width/2, 2) + Math.pow(b.startY - height/2, 2);
return distA - distB;
});
const numCores = navigator.hardwareConcurrency || 4;
statusText.innerText = `Calculating Final Scene... (${numCores} threads)`;
let startTime = performance.now();
function assignNextTask(worker) {
if (taskQueue.length > 0) {
const task = taskQueue.shift();
worker.postMessage({
...task, imageWidth: width, imageHeight: height, cfg
});
} else {
worker.terminate();
activeWorkers--;
if (activeWorkers === 0) {
rawImageData = ctx.getImageData(0, 0, canvas.width, canvas.height);
if (elements.denoise.checked) {
applyDenoiser();
} else {
statusText.innerText = `Render Finished in ${((performance.now() - startTime) / 1000).toFixed(2)}s`;
}
}
}
}
for (let i = 0; i < numCores; i++) {
if (taskQueue.length === 0) break;
const worker = new Worker(workerUrl);
workers.push(worker);
activeWorkers++;
worker.onmessage = (e) => {
const { startX, startY, tileWidth, tileHeight, buffer } = e.data;
const imageData = new ImageData(new Uint8ClampedArray(buffer), tileWidth, tileHeight);
const canvasY = height - startY - tileHeight;
ctx.putImageData(imageData, startX, canvasY);
assignNextTask(worker);
};
assignNextTask(worker);
}
}
Object.keys(elements).forEach(key => {
if (key === 'denoise') {
elements[key].addEventListener('change', (e) => {
if (activeWorkers > 0) return;
if (e.target.checked) applyDenoiser();
else if (rawImageData) {
ctx.putImageData(rawImageData, 0, 0);
statusText.innerText = "Denoiser Disabled (Showing Raw Output)";
}
});
return;
}
elements[key].addEventListener('change', (e) => {
const valSpan = document.getElementById(key + 'Val');
if(valSpan) { valSpan.innerText = e.target.value; }
startRender();
});
});
startRender();
</script>
</body>
</html>