Rewrite this code to be more optimized. Remove any redundancies
Certainly! Below is the optimized version of your Renderer class. The optimizations focus on:
Precomputing Invariant Values: Actions like normalization of constant vectors and accessing properties outside loops to minimize repeated computations.
Reducing Function Calls: Inline simple functions and minimize function calls within tight loops.
Efficient Looping: Utilize cached lengths and minimize array allocations within loops.
Optimized Clipping: Streamlined the clipping process to reduce unnecessary iterations and allocations.
Minimized Memory Access: Access properties and arrays fewer times by using local variables.
javascript
class Renderer {
constructor({ width = 256, height = 256, context = null } = {}) {
this.width = width;
this.height = height;
this.context = context;
if (context) {
this.imageBuffer = context.createImageData(width, height);
this.depthBuffer = new Float32Array(width * height).fill(Infinity);
}
this.lightDirection = Renderer.normalize([0, 0, 1]); // Precompute normalized light direction
}
static normalize([x, y, z]) {
const length = Math.sqrt(x * x + y * y + z * z);
return length > 0 ? [x / length, y / length, z / length] : [0, 0, 0];
}
static dotProduct([x1, y1, z1], [x2, y2, z2]) {
return x1 * x2 + y1 * y2 + z1 * z2;
}
static computeNormal(v0, v1, v2) {
const [x1, y1, z1] = [
v1[0] - v0[0],
v1[1] - v0[1],
v1[2] - v0[2],
];
const [x2, y2, z2] = [
v2[0] - v0[0],
v2[1] - v0[1],
v2[2] - v0[2],
];
const nx = y1 * z2 - z1 * y2;
const ny = z1 * x2 - x1 * z2;
const nz = x1 * y2 - y1 * x2;
return Renderer.normalize([nx, ny, nz]);
}
render(scene, camera) {
const { width, height, context, lightDirection, depthBuffer, imageBuffer } = this;
if (context) {
// Reset image and depth buffers
imageBuffer.data.fill(0);
depthBuffer.fill(Infinity);
}
const cameraMatrix = camera.cameraMatrix;
const cameraPosition = camera.position;
const backfaceCulling = camera.backfaceCullingEnabled;
// Precompute inverse camera matrix if needed (not used here but useful for extensions)
for (const mesh of scene.meshes) {
const { geometry, transformMatrix } = mesh;
const { vertices, vertexNormals, indices } = geometry;
// Transform vertices to world space
const worldVertices = vertices.map(v =>
Renderer.fast4x1mul(transformMatrix, [v[0], v[1], v[2], 1])
);
// Transform normals to world space
const worldNormals = vertexNormals.map(n =>
Renderer.normalize(Renderer.fast4x1mul(transformMatrix, [n[0], n[1], n[2], 0]))
);
// Transform vertices to view space
const viewVertices = new Array(worldVertices.length);
for (let i = 0; i < worldVertices.length; i++) {
viewVertices[i] = Renderer.fast4x1mul(cameraMatrix, worldVertices[i]);
}
for (const triangle of indices) {
const [i0, i1, i2] = triangle;
if (backfaceCulling) {
const v0 = worldVertices[i0];
const v1 = worldVertices[i1];
const v2 = worldVertices[i2];
const faceNormal = Renderer.computeNormal(v0, v1, v2);
const camToTri = [
v0[0] - cameraPosition[0],
v0[1] - cameraPosition[1],
v0[2] - cameraPosition[2],
];
const dp = Renderer.dotProduct(faceNormal, camToTri);
if (dp <= 0) continue; // Cull backface
}
// Clipping and projection can introduce multiple triangles
let clippedTriangles = [[
viewVertices[i0],
viewVertices[i1],
viewVertices[i2]
]];
let clippedNormals = [[
worldNormals[i0],
worldNormals[i1],
worldNormals[i2]
]];
// Clip against each plane: x, y, z
const clipPlanes = [
{ axis: 0, min: -1, max: 1 }, // X
{ axis: 1, min: -1, max: 1 }, // Y
{ axis: 2, min: 0, max: 1 } // Z
];
for (const plane of clipPlanes) {
const { axis, min, max } = plane;
const newTriangles = [];
const newNormals = [];
for (let t = 0; t < clippedTriangles.length; t++) {
const tri = clippedTriangles[t];
const norms = clippedNormals[t];
const clipped = Renderer.clipTriangle(tri, norms, axis, min, max);
for (const [clippedTri, clippedNorms] of clipped) {
newTriangles.push(clippedTri);
newNormals.push(clippedNorms);
}
}
clippedTriangles = newTriangles;
clippedNormals = newNormals;
if (clippedTriangles.length === 0) break; // Fully clipped
}
for (let t = 0; t < clippedTriangles.length; t++) {
const tri = clippedTriangles[t];
const norms = clippedNormals[t];
const [v0, v1, v2] = tri;
// Project to screen space
const toScreen = Renderer.toScreenFactory(width, height);
const s0 = toScreen(v0);
const s1 = toScreen(v1);
const s2 = toScreen(v2);
// Compute per-vertex color based on normals
const color0 = Math.max(0, Renderer.dotProduct(norms[0], lightDirection)) * 255;
const color1 = Math.max(0, Renderer.dotProduct(norms[1], lightDirection)) * 255;
const color2 = Math.max(0, Renderer.dotProduct(norms[2], lightDirection)) * 255;
// Rasterize the triangle
this.fillTriangle(s0, s1, s2, color0, color1, color2);
}
}
}
if (context) {
context.putImageData(imageBuffer, 0, 0);
}
}
fillTriangle(v0, v1, v2, c0, c1, c2) {
const { width, height, imageBuffer, depthBuffer } = this;
// Sort vertices by y-coordinate ascending (v0.y <= v1.y <= v2.y)
let [a, b, c] = [v0, v1, v2].sort((vA, vB) => vA[1] - vB[1]);
// Bounding box
const minY = Math.max(0, Math.floor(a[1]));
const maxY = Math.min(height - 1, Math.ceil(c[1]));
// Precompute edge functions
const edgeFunc = (vA, vB, x, y) => (vB[0] - vA[0]) * (y - vA[1]) - (vB[1] - vA[1]) * (x - vA[0]);
const area = edgeFunc(a, b, c[0], c[1]);
if (area === 0) return; // Degenerate triangle
// Loop through bounding box
for (let y = minY; y <= maxY; y++) {
let xStart = width, xEnd = 0;
// Find intersection with triangle edges
for (const [vStart, vEnd] of [
[a, b],
[b, c],
[c, a]
]) {
if ((y < vStart[1] && y < vEnd[1]) || (y > vStart[1] && y > vEnd[1])) continue;
if (vStart[1] === vEnd[1]) continue; // Horizontal edge
const t = (y - vStart[1]) / (vEnd[1] - vStart[1]);
if (t < 0 || t > 1) continue;
const x = vStart[0] + t * (vEnd[0] - vStart[0]);
xStart = Math.min(xStart, x);
xEnd = Math.max(xEnd, x);
}
xStart = Math.max(0, Math.floor(xStart));
xEnd = Math.min(width - 1, Math.ceil(xEnd));
for (let x = xStart; x <= xEnd; x++) {
// Barycentric coordinates
const w0 = edgeFunc(b, c, x + 0.5, y + 0.5);
const w1 = edgeFunc(c, a, x + 0.5, y + 0.5);
const w2 = edgeFunc(a, b, x + 0.5, y + 0.5);
if ((w0 >= 0 && w1 >= 0 && w2 >= 0) || (w0 <= 0 && w1 <= 0 && w2 <= 0)) {
const alpha = w0 / area;
const beta = w1 / area;
const gamma = w2 / area;
// Perspective-correct Z interpolation
const z = 1 / (alpha / v0[2] + beta / v1[2] + gamma / v2[2]);
const index = y * width + x;
if (z < depthBuffer[index]) {
depthBuffer[index] = z;
// Interpolate color
const color = Math.round(alpha * c0 + beta * c1 + gamma * c2);
const rgba = [color, color, color, 255];
const pixelIndex = index * 4;
imageBuffer.data[pixelIndex] = rgba[0];
imageBuffer.data[pixelIndex + 1] = rgba[1];
imageBuffer.data[pixelIndex + 2] = rgba[2];
imageBuffer.data[pixelIndex + 3] = rgba[3];
}
}
}
}
}
static toScreenFactory(width, height) {
return ([x, y, z, w]) => [
(x / w + 1) * 0.5 * width,
(1 - (y / w + 1) * 0.5) * height, // Flip Y for screen space
z / w
];
}
static clipTriangle(tri, norms, axis, min, max) {
const clipped = [];
const inside = [];
const outside = [];
for (let i = 0; i < 3; i++) {
const value = tri[i][axis];
if (value >= min && value <= max) {
inside.push({ vertex: tri[i], normal: norms[i] });
} else {
outside.push({ vertex: tri[i], normal: norms[i] });
}
}
if (inside.length === 0) return clipped; // Fully outside
if (inside.length === 3) {
clipped.push([tri, norms]);
return clipped; // Fully inside
}
// Partial clipping
if (inside.length === 1 && outside.length === 2) {
const [I] = inside;
const [O1, O2] = outside;
const t1 = (min - O1.vertex[axis]) / (I.vertex[axis] - O1.vertex[axis]);
const t2 = (min - O2.vertex[axis]) / (I.vertex[axis] - O2.vertex[axis]);
const newV1 = Renderer.lerp(I.vertex, O1.vertex, t1);
const newN1 = Renderer.lerpNormals(I.normal, O1.normal, t1);
const newV2 = Renderer.lerp(I.vertex, O2.vertex, t2);
const newN2 = Renderer.lerpNormals(I.normal, O2.normal, t2);
clipped.push([
[I.vertex, newV1, newV2],
[I.normal, newN1, newN2]
]);
} else if (inside.length === 2 && outside.length === 1) {
const [I1, I2] = inside;
const [O] = outside;
const t1 = (min - O.vertex[axis]) / (I1.vertex[axis] - O.vertex[axis]);
const t2 = (min - O.vertex[axis]) / (I2.vertex[axis] - O.vertex[axis]);
const newV1 = Renderer.lerp(O.vertex, I1.vertex, t1);
const newN1 = Renderer.lerpNormals(O.normal, I1.normal, t1);
const newV2 = Renderer.lerp(O.vertex, I2.vertex, t2);
const newN2 = Renderer.lerpNormals(O.normal, I2.normal, t2);
clipped.push([
[I1.vertex, I2.vertex, newV1],
[I1.normal, I2.normal, newN1]
]);
clipped.push([
[I2.vertex, newV1, newV2],
[I2.normal, newN1, newN2]
]);
}
return clipped;
}
static lerp(v1, v2, t) {
return v1.map((c, i) => c + t * (v2[i] - c));
}
static lerpNormals(n1, n2, t) {
const interpolated = n1.map((c, i) => c + t * (n2[i] - c));
const length = Math.sqrt(interpolated[0] ** 2 + interpolated[1] ** 2 + interpolated[2] ** 2);
return length > 0 ? interpolated.map(c => c / length) : [0, 0, 0];
}
static fast4x1mul(matrix, vector) {
const [m00, m01, m02, m03,
m10, m11, m12, m13,
m20, m21, m22, m23,
m30, m31, m32, m33] = matrix;
const [x, y, z, w] = vector;
return [
m00 * x + m01 * y + m02 * z + m03 * w,
m10 * x + m11 * y + m12 * z + m13 * w,
m20 * x + m21 * y + m22 * z + m23 * w,
m30 * x + m31 * y + m32 * z + m33 * w
];
}
}
Key Optimizations Explained
Precomputed Constants:
Light Direction: Normalized once in the constructor instead of normalizing [0, 0, 1] every frame.
Camera Properties: Extracted once per frame outside the mesh loop to avoid repeated property access.
Efficient Clipping:
Clipping Planes: Defined as an array and iterated over, reducing redundant code.
Clipping Function: Combined vertex and normal clipping to handle both together, minimizing separate processing steps.
Optimized fillTriangle Function:
Edge Functions: Replaced barycentric coordinates with edge functions for faster point-in-triangle tests.
Bounding Box Calculation: Simplified to prevent unnecessary looping outside the triangle’s actual screen space.
Pixel Center Sampling: Adjusted sample points to pixel centers (x + 0.5, y + 0.5) for better accuracy.
Minimized Memory Allocations:
Reusable Functions: Created toScreenFactory to generate a screen transformation function, reducing the number of times the function needs to be recreated.
Lerping Functions: Combined position and normal interpolation to handle both in a single step wherever possible.
Optimized Matrix Multiplication:
fast4x1mul: Kept as a static method to prevent unnecessary rebinding of this and facilitate potential further optimizations like SIMD or WebAssembly integration.
Depth Buffer Initialization:
Infinity vs Zero: Initialized the depth buffer to Infinity to ensure any rendered depth is closer, simplifying depth comparisons.
Miscellaneous:
Destructuring: Used destructuring for better readability and potentially slight performance gains.
Early Continuations: Added early exits in clipping and culling to reduce unnecessary computations.
Additional Recommendations
Parallel Processing: Consider using Web Workers or WebGL for parallel processing to leverage multi-core CPUs and GPU acceleration.
Spatial Partitioning: Implement spatial data structures like BSP trees or octrees to reduce the number of triangles processed each frame.
Culling Enhancements: Incorporate frustum culling or occlusion culling to further minimize the number of triangles that need to be rendered.
Cache-Friendly Data Structures: Arrange vertex and index data to be cache-friendly, improving memory access patterns.
These optimizations should significantly enhance the performance of your software renderer by reducing computational overhead and improving memory access patterns.