Hi, I was wondering if I could get some help with creating my web worker. Initially, I am simply trying to create a web worker to offload the heavy ray tracer rendering task to, when that's working, I will plan to implement multiple workers concurrently to accelerate the rendering. Currently I have this in my main file:
main.ts
import './style.css'
import Canvas from './canvas.ts'
import {viewTransform} from "./maths/transformations.ts";
import {point, vector} from "./maths/tuple.ts";
main();
function main() {
const canvas = new Canvas(
document.querySelector<HTMLCanvasElement>('#canvas')!,
100, 50);
const worker = new Worker(new URL('./worker.ts', import.meta.url));
const transform = viewTransform(point(0, 1.5, -5), point(0, 1, 0), vector(0, 1, 0))
worker.postMessage({
width: canvas.getWidth(),
height: canvas.getHeight(),
fieldOfView: Math.PI / 3,
transform: transform.elements
});
worker.onmessage = (event) => canvas.drawImage(event.data);
}
and a worker file:
import {camera} from "./camera.ts";
import spheres from "./scenes/spheres.ts";
import Matrix from "./maths/matrix.ts";
self.onmessage = (event) => {
const {width, height, fieldOfView, transform} = event.data;
const world = spheres();
const cam = camera(width, height, fieldOfView);
cam.transform = new Matrix(transform);
self.postMessage(cam.render(world));
};
cam.render(world) essentially just does the loop:
render(world: World): number[] {
const image: number[] = []
for (let y = 0; y < this.vSize; y++) {
for (let x = 0; x < this.hSize; x++) {
image.push(...world.colorAt(this.rayForPixel(x, y)).data());
}
}
return image;
};
}
eventually, I'll update y=0 to startY and endY for multiple workers, and I might have to think about how the data is pushed to the array. But for now, is there anything glaringly wrong?