Sure! Below is an optimized version of your fillTriangle function. The optimizations focus on:
- Using Arrays Instead of Objects: Replaced JSON objects with separate arrays for vertex positions and colors to reduce overhead.
- Manual Sorting: Implemented a manual sort for three vertices to eliminate the overhead of the
.sort() method.
- Precomputing Invariants: Calculated values that remain constant outside loops to avoid redundant computations.
- Loop Unrolling and Minimizing Conditionals: Streamlined inner loops to reduce conditional checks and improve cache performance.
- Using Typed Arrays: Utilized typed arrays (
Uint8ClampedArray) for image buffers to enhance performance.
Optimized fillTriangle Function
fillTriangle(v0, v1, v2, color0, color1, color2) {
const { width, height, imageBuffer, depthBuffer } = this;
// Extract vertex positions and colors
let x0 = v0[0], y0 = v0[1], z0 = v0[2], c0 = color0;
let x1 = v1[0], y1 = v1[1], z1 = v1[2], c1 = color1;
let x2 = v2[0], y2 = v2[1], z2 = v2[2], c2 = color2;
// Manual sort of the vertices by y-coordinate ascending
if (y1 < y0 || (y1 === y0 && x1 < x0)) {
[x0, y0, z0, c0, x1, y1, z1, c1] = [x1, y1, z1, c1, x0, y0, z0, c0];
}
if (y2 < y0 || (y2 === y0 && x2 < x0)) {
[x0, y0, z0, c0, x2, y2, z2, c2] = [x2, y2, z2, c2, x0, y0, z0, c0];
}
if (y2 < y1 || (y2 === y1 && x2 < x1)) {
[x1, y1, z1, c1, x2, y2, z2, c2] = [x2, y2, z2, c2, x1, y1, z1, c1];
}
// Calculate the denominator for barycentric coordinates
const denom = (y1 - y2) * (x0 - x2) + (x2 - x1) * (y0 - y2);
if (denom === 0) return; // Degenerate triangle
const invDenom = 1 / denom;
// Bounding box in y-direction
const yStart = Math.max(0, Math.ceil(y0));
const yEnd = Math.min(height - 1, Math.floor(y2));
// Precompute edge data to avoid recomputing inside the loop
const edges = [
{ x1, y1, x2, y2 },
{ x1: x1, y1: y1, x2: x2, y2: y2 },
{ x1: x2, y1: y2, x2: x0, y2: y0 }
];
// Cache imageData and depthBuffer data for faster access
const imageData = imageBuffer.data;
const depthData = depthBuffer;
for (let y = yStart; y <= yEnd; y++) {
let xMin = width, xMax = 0;
// Find intersection points with triangle edges
for (let i = 0; i < 3; i++) {
const edge = edges[i];
const v1y = edge.y1, v2y = edge.y2;
if (y < Math.min(v1y, v2y) || y > Math.max(v1y, v2y)) continue;
const dy = v2y - v1y;
if (dy === 0) continue; // Horizontal edge
const t = (y - v1y) / dy;
const x = edge.x1 + t * (edge.x2 - edge.x1);
if (x < xMin) xMin = x;
if (x > xMax) xMax = x;
}
// Define the horizontal span for the current scanline
const xStart = Math.max(0, Math.ceil(xMin));
const xEnd = Math.min(width - 1, Math.floor(xMax));
const baseIndex = y * width;
for (let x = xStart; x <= xEnd; x++) {
// Calculate barycentric weights
const w0 = ((y1 - y2) * (x - x2) + (x2 - x1) * (y - y2)) * invDenom;
const w1 = ((y2 - y0) * (x - x2) + (x0 - x2) * (y - y2)) * invDenom;
const w2 = 1 - w0 - w1;
// Check if the point is inside the triangle
if (w0 < 0 || w1 < 0 || w2 < 0) continue;
// Perspective-correct interpolation for depth
const zInterpolated = 1 / (w0 / z0 + w1 / z1 + w2 / z2);
const index = baseIndex + x;
// Depth test
if (zInterpolated < depthData[index]) {
depthData[index] = zInterpolated;
// Interpolate color (assuming grayscale)
const interpolatedColor = (w0 * c0 + w1 * c1 + w2 * c2) / (w0 + w1 + w2);
const shadedColor = interpolatedColor | 0; // Convert to integer
const bufferIndex = index * 4;
imageData[bufferIndex] = shadedColor; // R
imageData[bufferIndex + 1] = shadedColor; // G
imageData[bufferIndex + 2] = shadedColor; // B
imageData[bufferIndex + 3] = 255; // A
}
}
}
}
Key Optimizations Explained
-
Manual Vertex Sorting:
- Instead of using
Array.prototype.sort(), which introduces overhead, manually sort the three vertices based on their y-coordinates. This is more efficient for a fixed small number of elements.
-
Edge Representation:
- Edges are stored as separate variables with minimal structure, reducing object creation overhead.
-
Precomputed Variables:
denom and invDenom are computed once since they don't change within the loops.
edges are precomputed and reused for each scanline.
-
Typed Arrays for Buffers:
- Accessing
imageBuffer.data and depthBuffer directly speeds up memory access. Ensure that imageBuffer.data is a Uint8ClampedArray and depthBuffer is a typed array like Float32Array for optimal performance.
-
Minimized Conditional Checks:
- Conditional checks inside the inner loop are minimized. For example, the check
if (w0 < 0 || w1 < 0 || w2 < 0) is necessary but kept as simple as possible.
-
Integer Operations Where Possible:
- The color is converted to an integer using bitwise OR (
| 0) for faster assignment to the imageBuffer.
-
Loop Unrolling and Cache Optimization:
- By iterating over
y and then x, memory access patterns are more cache-friendly, which can lead to significant performance gains, especially for large images.
Additional Recommendations
-
Use Fixed-Point Arithmetic: If performance is still an issue, consider using fixed-point arithmetic for barycentric calculations to reduce floating-point operations.
-
Parallel Processing: Utilize Web Workers or GPU-based rendering (e.g., WebGL) for further performance improvements, especially for rendering multiple triangles or larger images.
-
Early Rejection: Implement more advanced techniques like bounding box checks or back-face culling to ignore triangles that don't contribute to the final image.
Implementing these optimizations should significantly enhance the performance of your triangle filling function, especially in environments where rendering speed is critical.