Repository navigation
Expand file tree
/
Copy pathchapter-1.html
More file actions
449 lines (387 loc) · 18.6 KB
/
Copy pathchapter-1.html
File metadata and controls
449 lines (387 loc) · 18.6 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
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Ray Tracing in One Weekend (Halton Sequence)</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 8px rgba(0,0,0,0.5); border-radius: 4px; margin-bottom: 1rem; }
.controls { display: flex; gap: 1.5rem; flex-wrap: wrap; justify-content: center; background: #2a2a2a; padding: 1rem; border-radius: 8px; max-width: 800px; }
.control-group { display: flex; flex-direction: column; align-items: center; gap: 0.5rem; font-size: 0.9em; }
input[type="range"] { cursor: pointer; width: 120px; }
#status { font-family: monospace; color: #4CAF50; font-weight: bold; margin-bottom: 1rem; }
</style>
</head>
<body>
<h2>Ray Tracing in One Weekend (Blue Noise / Halton)</h2>
<div id="status">Ready</div>
<canvas id="renderCanvas" width="600" height="337"></canvas>
<div class="controls">
<div class="control-group">
<label>Field of View: <span id="fovVal">20</span>°</label>
<input type="range" id="fovSlider" min="10" max="90" value="20">
</div>
<div class="control-group">
<label>Focus Distance: <span id="focusVal">10.0</span></label>
<input type="range" id="focusSlider" min="2" max="20" step="0.1" value="10.0">
</div>
<div class="control-group">
<label>Lens Blur: <span id="blurVal">0.6</span></label>
<input type="range" id="blurSlider" min="0" max="2" step="0.1" value="0.6">
</div>
<div class="control-group">
<label>Samples/Pixel: <span id="samplesVal">10</span></label>
<input type="range" id="samplesSlider" min="1" max="500" value="10">
</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) { this.origin = origin; this.direction = direction; }
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;
}
// Pre-compute 1024 values per dimension when the worker starts
const LUT_SIZE = 1024;
const halton2 = computeHaltonLUT(2, LUT_SIZE); // Pixel X
const halton3 = computeHaltonLUT(3, LUT_SIZE); // Pixel Y
const halton5 = computeHaltonLUT(5, LUT_SIZE); // Lens Blur U
const halton7 = computeHaltonLUT(7, LUT_SIZE); // Lens Blur V
// --- QUASI-MONTE CARLO (HALTON SEQUENCE) ---
// The halton() function is retained for educational purposes, but the main
// rendering loop 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;
}
class Lambertian {
constructor(albedo) { this.albedo = albedo; }
scatter(ray, rec) {
let scatter_direction = rec.normal.add(Vec3.randomUnitVector());
if (scatter_direction.lengthSq() < 1e-8) scatter_direction = rec.normal;
return { ray: new Ray(rec.p, scatter_direction), attenuation: this.albedo };
}
}
class Metal {
constructor(albedo, fuzz) { this.albedo = albedo; this.fuzz = fuzz < 1 ? fuzz : 1; }
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)));
if (Vec3.dot(scattered.direction, rec.normal) > 0) return { ray: scattered, attenuation: this.albedo };
return null;
}
}
class Dielectric {
constructor(ir) { 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 cannot_refract = refraction_ratio * sin_theta > 1.0;
let direction;
if (cannot_refract || this.reflectance(cos_theta, refraction_ratio) > Math.random()) {
direction = Vec3.reflect(unit_direction, rec.normal);
} else {
direction = Vec3.refract(unit_direction, rec.normal, refraction_ratio);
}
return { ray: new Ray(rec.p, direction), 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 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;
let normal = front_face ? outward_normal : outward_normal.mul(-1);
return { t: root, p: p, normal: normal, front_face: front_face, material: this.material };
}
}
class HittableList {
constructor() { this.objects = []; }
add(obj) { this.objects.push(obj); }
hit(ray, t_min, t_max) {
let temp_rec = null;
let 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;
}
}
function rayColor(ray, world, depth) {
if (depth <= 0) return new Vec3(0, 0, 0);
let rec = world.hit(ray, 0.001, Infinity);
if (rec) {
let scatterResult = rec.material.scatter(ray, rec);
if (scatterResult) {
let colorFromBounce = rayColor(scatterResult.ray, world, depth - 1);
return scatterResult.attenuation.mulV(colorFromBounce);
}
return new Vec3(0, 0, 0);
}
let unit_direction = ray.direction.normalize();
let t = 0.5 * (unit_direction.y + 1.0);
return new Vec3(1.0, 1.0, 1.0).mul(1.0 - t).add(new Vec3(0.5, 0.7, 1.0).mul(t));
}
function buildScene() {
let world = new HittableList();
world.add(new Sphere(new Vec3(0, -1000, 0), 1000, new Lambertian(new Vec3(0.5, 0.5, 0.5))));
let seed = 1234567;
function seededRandom() { seed = (seed * 9301 + 49297) % 233280; return seed / 233280; }
for (let a = -11; a < 11; a++) {
for (let b = -11; b < 11; b++) {
let choose_mat = seededRandom();
let center = new Vec3(a + 0.9 * seededRandom(), 0.2, b + 0.9 * seededRandom());
if (center.sub(new Vec3(4, 0.2, 0)).length() > 0.9) {
let sphere_material;
if (choose_mat < 0.8) {
let albedo = new Vec3(seededRandom(), seededRandom(), seededRandom()).mulV(new Vec3(seededRandom(), seededRandom(), seededRandom()));
sphere_material = new Lambertian(albedo);
} else if (choose_mat < 0.95) {
let albedo = new Vec3(0.5 + 0.5*seededRandom(), 0.5 + 0.5*seededRandom(), 0.5 + 0.5*seededRandom());
let fuzz = seededRandom() * 0.5;
sphere_material = new Metal(albedo, fuzz);
} else {
sphere_material = new Dielectric(1.5);
}
world.add(new Sphere(center, 0.2, sphere_material));
}
}
}
world.add(new Sphere(new Vec3(0, 1, 0), 1.0, new Dielectric(1.5)));
world.add(new Sphere(new Vec3(-4, 1, 0), 1.0, new Lambertian(new Vec3(0.4, 0.2, 0.1))));
world.add(new Sphere(new Vec3(4, 1, 0), 1.0, new Metal(new Vec3(0.7, 0.6, 0.5), 0.0)));
return world;
}
const world = buildScene();
self.onmessage = function(e) {
const { startX, startY, tileWidth, tileHeight, imageWidth, imageHeight, samples, maxDepth, camParams } = e.data;
const buffer = new Uint8ClampedArray(tileWidth * tileHeight * 4);
let theta = camParams.vfov * Math.PI / 180.0;
let h = Math.tan(theta/2);
let viewport_height = 2.0 * h * camParams.focus_dist;
let viewport_width = viewport_height * (imageWidth / imageHeight);
let lookfrom = new Vec3(camParams.lookfrom.x, camParams.lookfrom.y, camParams.lookfrom.z);
let lookat = new Vec3(camParams.lookat.x, camParams.lookat.y, camParams.lookat.z);
let vup = new Vec3(camParams.vup.x, camParams.vup.y, camParams.vup.z);
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.mul(camParams.focus_dist));
let defocus_radius = camParams.focus_dist * Math.tan((camParams.defocus_angle / 2) * Math.PI / 180.0);
let defocus_disk_u = u.mul(defocus_radius);
let defocus_disk_v = v.mul(defocus_radius);
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 hashes for the two lens dimensions
let rand_offset_lens_u = ((pixel_hash * 39916801) & 0xFFFF) / 65535.0;
let rand_offset_lens_v = ((pixel_hash * 26544357) & 0xFFFF) / 65535.0;
let pixel_color = new Vec3(0, 0, 0);
for (let s = 0; s < samples; ++s) {
// FAST PRE-COMPUTED LUT LOOKUP
let s_idx = s % LUT_SIZE;
// 1. Anti-aliasing pixel offsets
let u_offset = (halton2[s_idx] + rand_offset_x) % 1.0;
let v_offset = (halton3[s_idx] + rand_offset_y) % 1.0;
let s_u = (i + u_offset) / (imageWidth - 1);
let s_v = (j + v_offset) / (imageHeight - 1);
// 2. Lens Blur offsets
let lens_u = (halton5[s_idx] + rand_offset_lens_u) % 1.0;
let lens_v = (halton7[s_idx] + rand_offset_lens_v) % 1.0;
// Convert uniform square [0,1] to uniform circle
let r_lens = Math.sqrt(lens_u);
let theta_lens = 2.0 * Math.PI * lens_v;
let rd = new Vec3(r_lens * Math.cos(theta_lens), r_lens * Math.sin(theta_lens), 0).mul(defocus_radius);
let offset = defocus_disk_u.mul(rd.x).add(defocus_disk_v.mul(rd.y));
let ray_origin = (camParams.defocus_angle <= 0) ? origin : origin.add(offset);
let dir = lower_left_corner.add(horizontal.mul(s_u)).add(vertical.mul(s_v)).sub(ray_origin);
let r = new Ray(ray_origin, dir);
pixel_color = pixel_color.add(rayColor(r, world, maxDepth));
}
let scale = 1.0 / 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 fovSlider = document.getElementById('fovSlider');
const focusSlider = document.getElementById('focusSlider');
const blurSlider = document.getElementById('blurSlider');
const samplesSlider = document.getElementById('samplesSlider');
let workers = [];
let activeWorkers = 0;
let taskQueue = [];
function startRender() {
workers.forEach(w => w.terminate());
workers = [];
activeWorkers = 0;
taskQueue = [];
ctx.fillStyle = "black";
ctx.fillRect(0, 0, canvas.width, canvas.height);
const lookfrom = {x: 13, y: 2, z: 3};
const lookat = {x: 0, y: 0, z: 0};
const vup = {x: 0, y: 1, z: 0};
const maxDepth = 10;
const camParams = {
lookfrom, lookat, vup,
vfov: parseFloat(fovSlider.value),
focus_dist: parseFloat(focusSlider.value),
defocus_angle: parseFloat(blurSlider.value)
};
const samples = parseInt(samplesSlider.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)
});
}
}
// Sort from center outward
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 = `Rendering with ${numCores} threads... (${taskQueue.length} tiles)`;
let startTime = performance.now();
function assignNextTask(worker) {
if (taskQueue.length > 0) {
const task = taskQueue.shift();
worker.postMessage({
...task, imageWidth: width, imageHeight: height, samples, maxDepth, camParams
});
} else {
worker.terminate();
activeWorkers--;
if (activeWorkers === 0) {
statusText.innerText = `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);
}
}
[fovSlider, focusSlider, blurSlider, samplesSlider].forEach(slider => {
slider.addEventListener('input', (e) => {
document.getElementById(e.target.id.replace('Slider', 'Val')).innerText = e.target.value;
startRender();
});
});
startRender();
</script>
</body>
</html>