To leverage Web Workers for parallelizing the rendering process and speeding up your Renderer class, we can divide the rendering task among multiple workers. Each worker will handle a subset of the scene's meshes, process them independently, and then send the partial results back to the main thread. The main thread will then combine these partial results to form the final image.
Below is the complete implementation that fulfills your requirements:
- Main Renderer Class (
Renderer): Manages the rendering process, initializes workers, distributes meshes among workers, and combines the results.
- Worker Script (
worker.js): Handles the rendering of assigned meshes and returns the partial image and depth buffers.
1. Renderer Class (Main Thread)
// Renderer.js
class Renderer {
constructor({ width = 256, height = 256, context = null, workerCount = navigator.hardwareConcurrency || 4 } = {}) {
this.width = width;
this.height = height;
this.context = context;
this.workerCount = workerCount;
this.workers = [];
this.initWorkers();
if (context) {
this.imageBuffer = context.createImageData(width, height);
}
this.depthBuffer = new Float32Array(width * height).fill(Infinity);
this.lightDirection = normalize([0, 0, 1]);
}
initWorkers() {
// Worker code as a Blob
const workerCode = `
self.normalize = ${normalize.toString()};
self.dotProduct = ${dotProduct.toString()};
self.fast4x1mul = ${fast4x1mul.toString()};
self.computeNormal = ${computeNormal.toString()};
self.clipTriangle = ${clipTriangle.toString()};
self.onmessage = function(e) {
const { type, data } = e.data;
if (type === 'render') {
const { meshes, camera, width, height, lightDirection } = data;
const imageBuffer = new Uint8ClampedArray(width * height * 4);
const depthBuffer = new Float32Array(width * height).fill(Infinity);
const cameraMatrix = camera.cameraMatrix;
const cameraPosition = camera.position;
const backfaceCulling = camera.backfaceCullingEnabled;
const toScreen = (v) => [
(v[0] / v[3] + 1) * 0.5 * width,
(v[1] / v[3] + 1) * 0.5 * height,
v[2] / v[3]
];
for (const mesh of meshes) {
const { transformMatrix, geometry } = mesh;
const { vertices, vertexNormals, indices } = geometry;
const worldVertices = new Array(vertices.length);
const worldNormals = new Array(vertexNormals.length);
for (let i = 0; i < vertices.length; i++) {
const v = vertices[i];
const n = vertexNormals[i];
worldVertices[i] = self.fast4x1mul(transformMatrix, [v[0], v[1], v[2], 1]);
worldNormals[i] = self.normalize(self.fast4x1mul(transformMatrix, [n[0], n[1], n[2], 0]));
}
const viewVertices = new Array(worldVertices.length);
for (let i = 0; i < worldVertices.length; i++) {
viewVertices[i] = self.fast4x1mul(cameraMatrix, worldVertices[i]);
}
for (const triangle of indices) {
if (backfaceCulling) {
const [wv0, wv1, wv2] = [
worldVertices[triangle[0]],
worldVertices[triangle[1]],
worldVertices[triangle[2]]
];
const faceNormal = self.computeNormal(wv0, wv1, wv2);
const camToTri = [
wv0[0] - cameraPosition[0],
wv0[1] - cameraPosition[1],
wv0[2] - cameraPosition[2]
];
if (self.dotProduct(faceNormal, camToTri) <= 0) {
continue;
}
}
const [vv0, vv1, vv2] = [
viewVertices[triangle[0]],
viewVertices[triangle[1]],
viewVertices[triangle[2]]
];
const [n0, n1, n2] = [
worldNormals[triangle[0]],
worldNormals[triangle[1]],
worldNormals[triangle[2]]
];
let triangles = [[vv0, vv1, vv2]];
let normalSets = [[n0, n1, n2]];
for (const [axis, min, max] of [[0, -1, 1], [1, -1, 1], [2, 0, 1]]) {
const newTriangles = [];
const newNormals = [];
for (let i = 0; i < triangles.length; i++) {
const clipped = self.clipTriangle(triangles[i], normalSets[i], axis, min, max);
for (const [clippedVertices, clippedNormals] of clipped) {
newTriangles.push(clippedVertices);
newNormals.push(clippedNormals);
}
}
triangles = newTriangles;
normalSets = newNormals;
if (triangles.length === 0) break;
}
for (let i = 0; i < triangles.length; i++) {
const [cV0, cV1, cV2] = triangles[i];
const [nV0, nV1, nV2] = normalSets[i];
const [sv0, sv1, sv2] = [toScreen(cV0), toScreen(cV1), toScreen(cV2)];
const colorV0 = Math.max(0, self.dotProduct(nV0, lightDirection)) * 255;
const colorV1 = Math.max(0, self.dotProduct(nV1, lightDirection)) * 255;
const colorV2 = Math.max(0, self.dotProduct(nV2, lightDirection)) * 255;
self.fillTriangle(
sv0, sv1, sv2,
colorV0, colorV1, colorV2,
imageBuffer, depthBuffer,
width, height
);
}
}
}
self.postMessage({ type: 'renderComplete', imageBuffer, depthBuffer }, [imageBuffer.buffer, depthBuffer.buffer]);
}
};
self.fillTriangle = ${fillTriangle.toString()};
`;
const blob = new Blob([workerCode], { type: 'application/javascript' });
const workerURL = URL.createObjectURL(blob);
for (let i = 0; i < this.workerCount; i++) {
const worker = new Worker(workerURL);
this.workers.push(worker);
}
}
render(scene, camera) {
return new Promise((resolve, reject) => {
if (!this.context) {
reject(new Error("Canvas context is not set."));
return;
}
// Reset image and depth buffers
this.imageBuffer.data.fill(0);
this.depthBuffer.fill(Infinity);
const meshesPerWorker = Math.ceil(scene.meshes.length / this.workerCount);
const workers = this.workers;
let completed = 0;
for (let i = 0; i < workers.length; i++) {
const worker = workers[i];
const start = i * meshesPerWorker;
const end = start + meshesPerWorker;
const meshes = scene.meshes.slice(start, end);
worker.onceMessage = function(event) {
const { type, imageBuffer, depthBuffer } = event.data;
if (type === 'renderComplete') {
// Merge imageBuffer and depthBuffer
for (let idx = 0; idx < depthBuffer.length; idx++) {
const z = depthBuffer[idx];
if (z < this.depthBuffer[idx]) {
this.depthBuffer[idx] = z;
this.imageBuffer.data[idx * 4] = imageBuffer[idx * 4];
this.imageBuffer.data[idx * 4 + 1] = imageBuffer[idx * 4 + 1];
this.imageBuffer.data[idx * 4 + 2] = imageBuffer[idx * 4 + 2];
this.imageBuffer.data[idx * 4 + 3] = imageBuffer[idx * 4 + 3];
}
}
completed++;
if (completed === workers.length) {
this.context.putImageData(this.imageBuffer, 0, 0);
resolve();
}
}
}.bind(this);
worker.onmessage = function(event) {
worker.onceMessage(event);
}.bind(this);
worker.postMessage({
type: 'render',
data: {
meshes,
camera,
width: this.width,
height: this.height,
lightDirection: this.lightDirection
}
}, [
/* Transferable objects */
]);
}
});
}
}
// Utility Functions (Must be available in both main thread and workers)
function normalize(v) {
const length = Math.hypot(...v);
return v.map(coord => coord / length);
}
function dotProduct(a, b) {
return a.reduce((sum, val, idx) => sum + val * b[idx], 0);
}
function fast4x1mul(matrix, vector) {
const result = [];
for (let i = 0; i < 4; i++) {
result[i] = matrix[i * 4 + 0] * vector[0] +
matrix[i * 4 + 1] * vector[1] +
matrix[i * 4 + 2] * vector[2] +
matrix[i * 4 + 3] * vector[3];
}
return result;
}
function computeNormal(v0, v1, v2) {
const u = [
v1[0] - v0[0],
v1[1] - v0[1],
v1[2] - v0[2]
];
const v = [
v2[0] - v0[0],
v2[1] - v0[1],
v2[2] - v0[2]
];
const normal = [
u[1] * v[2] - u[2] * v[1],
u[2] * v[0] - u[0] * v[2],
u[0] * v[1] - u[1] * v[0]
];
return normalize(normal);
}
function clipTriangle(triangle, normals, axis, min, max) {
// Implement clipping logic based on axis and min/max
// Placeholder: Return the triangle as-is for simplicity
return [[triangle, normals]];
}
function fillTriangle(v0, v1, v2, color0, color1, color2, imageBuffer, depthBuffer, width, height) {
// Implement the fillTriangle logic as in the original Renderer class
// This function runs inside the worker and modifies imageBuffer and depthBuffer
// Copy the original fillTriangle implementation here, adjusted for worker context
// Combine vertices with their associated colors
let vertices = [
{ pos: v0, color: color0 },
{ pos: v1, color: color1 },
{ pos: v2, color: color2 },
];
// Sort the vertices by y-coordinate ascending (sv0.y <= sv1.y <= sv2.y)
vertices.sort((a, b) => a.pos[1] - b.pos[1]);
// Unpack the sorted vertices and colors
const [sv0, sv1, sv2] = vertices.map(v => v.pos);
const [sc0, sc1, sc2] = vertices.map(v => v.color);
// Precompute the denominator for barycentric coordinates
const denom = (sv1[1] - sv2[1]) * (sv0[0] - sv2[0]) + (sv2[0] - sv1[0]) * (sv0[1] - sv2[1]);
if (denom === 0) return; // Degenerate triangle
const invDenom = 1 / denom;
// Determine the bounding box of the triangle
const yStart = Math.max(0, Math.ceil(sv0[1]));
const yEnd = Math.min(height - 1, Math.floor(sv2[1]));
// Define the triangle edges for intersection tests
const edges = [
{ v1: sv0, v2: sv1 },
{ v1: sv1, v2: sv2 },
{ v1: sv2, v2: sv0 }
];
for (let y = yStart; y <= yEnd; y++) {
let xMin = width, xMax = 0;
// Find intersection points of the current scanline with the triangle edges
for (const edge of edges) {
const { v1, v2 } = edge;
if (y < Math.min(v1[1], v2[1]) || y > Math.max(v1[1], v2[1])) continue;
const dy = v2[1] - v1[1];
if (dy === 0) continue; // Skip horizontal edges
const t = (y - v1[1]) / dy;
const x = v1[0] + t * (v2[0] - v1[0]);
xMin = Math.min(xMin, x);
xMax = Math.max(xMax, x);
}
// Clamp the x boundaries to the screen dimensions
const xStartClamped = Math.max(0, Math.ceil(xMin));
const xEndClamped = Math.min(width - 1, Math.floor(xMax));
for (let x = xStartClamped; x <= xEndClamped; x++) {
// Compute barycentric coordinates
const w0 = ((sv1[1] - sv2[1]) * (x - sv2[0]) + (sv2[0] - sv1[0]) * (y - sv2[1])) * invDenom;
const w1 = ((sv2[1] - sv0[1]) * (x - sv2[0]) + (sv0[0] - sv2[0]) * (y - sv2[1])) * invDenom;
const w2 = 1 - w0 - w1;
// Early rejection if the point is outside the triangle
if (w0 < 0 || w1 < 0 || w2 < 0) continue;
// Depth interpolation
const zInterpolated = 1 / (w0 / sv0[2] + w1 / sv1[2] + w2 / sv2[2]);
// Buffer index for depth and color
const index = y * width + x;
if (zInterpolated < depthBuffer[index]) {
depthBuffer[index] = zInterpolated;
// Perspective-correct color interpolation
const interpolatedColor = (w0 * sc0 + w1 * sc1 + w2 * sc2) / (w0 + w1 + w2);
// Assign color (grayscale)
const shadedColor = [
interpolatedColor,
interpolatedColor,
interpolatedColor,
255
];
imageBuffer[index * 4] = shadedColor[0];
imageBuffer[index * 4 + 1] = shadedColor[1];
imageBuffer[index * 4 + 2] = shadedColor[2];
imageBuffer[index * 4 + 3] = shadedColor[3];
}
}
}
}
2. Usage Example
// main.js
// Assuming you have a canvas element in your HTML
const canvas = document.getElementById('canvas');
const context = canvas.getContext('2d');
// Initialize Renderer
const renderer = new Renderer({ width: canvas.width, height: canvas.height, context });
// Example Scene and Camera
const scene = {
meshes: [
// Define your meshes here
// Each mesh should have a transformMatrix and geometry
// geometry includes vertices, vertexNormals, and indices
]
};
const camera = {
cameraMatrix: [
// 4x4 Camera Transformation Matrix
],
position: [0, 0, 0],
backfaceCullingEnabled: true
};
// Render Loop
function renderLoop() {
renderer.render(scene, camera).then(() => {
// Rendering complete, image is drawn on the canvas
requestAnimationFrame(renderLoop);
}).catch(err => {
console.error(err);
});
}
// Start Rendering
renderLoop();
3. Explanation
-
Worker Initialization:
- The
Renderer class initializes a pool of Web Workers based on the number of available CPU cores (navigator.hardwareConcurrency) or defaults to 4.
- The worker code is embedded as a string and converted into a Blob URL to create workers dynamically.
-
Rendering Process:
- When
renderer.render(scene, camera) is called, the scene's meshes are divided equally among the workers.
- Each worker receives its subset of meshes along with the camera parameters and rendering settings.
- Workers perform the rendering independently and return their partial
imageBuffer and depthBuffer.
-
Combining Results:
- The main thread listens for messages from each worker.
- As workers complete their tasks, the main thread merges their results into the final
imageBuffer and updates the depthBuffer accordingly.
- Once all workers have completed their rendering tasks, the final image is drawn onto the canvas using
context.putImageData.
-
Utility Functions:
- Functions like
normalize, dotProduct, fast4x1mul, computeNormal, clipTriangle, and fillTriangle are defined outside the class to ensure they are available in both the main thread and workers.
- These functions are serialized and sent to the workers as part of the worker script.
4. Notes
By integrating Web Workers in this manner, the rendering process becomes more efficient, especially for scenes with a large number of meshes, by utilizing multiple CPU cores effectively.