I have a code that creates an interactable interpolated fractal pattern under this…
- User
I have a code that creates an interactable interpolated fractal pattern under this explanation:
The main existing line is of rank 1. Under rank 1 line there will be 3 lines on rank 2 following these conditions: The first line's first point is tied to the leftmost vertex of the rank 1 line. This line's other point is defined as such: x: 1/3 of way across rank 1 line's x (toward the middle) y: 1/2 of way across rank 1 line's y (toward the middle)
The second line's first point is tied to the rightmost vertex of the rank 1 line. This line's other point is defined as such: x: 1/3 of way across rank 1 line's x (toward the middle) y: 1/2 of way across rank 1 line's y (toward the middle)
The line in the middle joins the leftmost and rightmost lines.
Currently the code is very slow and unoptimized, slowing drastically when multiple ranks are added.
Zooming, panning and movement of the pattern is all very slow.
Please analyze this code and implement the best optimizations that address these faults.
import * as THREE from './three.module.js';
// Scene setup const scene = new THREE.Scene(); scene.background = new THREE.Color(0x000000);
// Camera setup const aspectRatio = window.innerWidth / window.innerHeight; const cameraSize = 200; const camera = new THREE.OrthographicCamera( -cameraSize * aspectRatio, cameraSize * aspectRatio, cameraSize, -cameraSize, 1, 1000 ); camera.position.set(0, 0, 500);
const renderer = new THREE.WebGLRenderer({ antialias: true }); renderer.setSize(window.innerWidth, window.innerHeight); document.body.appendChild(renderer.domElement);
// Zoom logic (based on mouse wheel and key modifiers) const zoomSpeed = 0.8;
function onWheel(event) { event.preventDefault();
const rect = renderer.domElement.getBoundingClientRect(); const mouseX = ((event.clientX - rect.left) / rect.width) * 2 - 1; const mouseY = -((event.clientY - rect.top) / rect.height) * 2 + 1;
const mouseWorld = new THREE.Vector3(mouseX, mouseY, 0).unproject(camera); const zoomFactor = 1 - event.deltaY * 0.001 * zoomSpeed;
const ctrlPressed = event.ctrlKey; const shiftPressed = event.shiftKey;
if (ctrlPressed) { camera.left = (camera.left - mouseWorld.x) * zoomFactor + mouseWorld.x; camera.right = (camera.right - mouseWorld.x) * zoomFactor + mouseWorld.x; } else if (shiftPressed) { camera.top = (camera.top - mouseWorld.y) * zoomFactor + mouseWorld.y; camera.bottom = (camera.bottom - mouseWorld.y) * zoomFactor + mouseWorld.y; } else { camera.left = (camera.left - mouseWorld.x) * zoomFactor + mouseWorld.x; camera.right = (camera.right - mouseWorld.x) * zoomFactor + mouseWorld.x; camera.top = (camera.top - mouseWorld.y) * zoomFactor + mouseWorld.y; camera.bottom = (camera.bottom - mouseWorld.y) * zoomFactor + mouseWorld.y; }
camera.updateProjectionMatrix(); }
// Prevent default browser behavior for wheel scrolling with Control or Shift key window.addEventListener('wheel', onWheel, { passive: false });
// Prevent default context menu on right-click window.addEventListener('contextmenu', (event) => { event.preventDefault(); });
// Render loop function animate() { requestAnimationFrame(animate); renderer.render(scene, camera); }
// Handle window resize function onWindowResize() { const aspect = window.innerWidth / window.innerHeight; camera.left = -cameraSize * aspect; camera.right = cameraSize * aspect; camera.top = cameraSize; camera.bottom = -cameraSize; camera.updateProjectionMatrix(); renderer.setSize(window.innerWidth, window.innerHeight); } window.addEventListener('resize', onWindowResize);
// Start animation animate();
// Panning functionality let isPanning = false; let isDraggingEndpoint = false; let selectedEndpointIndex = null; const previousMousePosition = new THREE.Vector2();
// Raycaster for detecting line interaction const raycaster = new THREE.Raycaster(); const mouse = new THREE.Vector2();
// Interactive main line code const lineMaterial = new THREE.LineBasicMaterial({ color: 0xffffff }); const lineGeometry = new THREE.BufferGeometry().setFromPoints([ new THREE.Vector3(-50, 0, 0), new THREE.Vector3(50, 0, 0) ]); const line = new THREE.Line(lineGeometry, lineMaterial); line.frustumCulled = false; scene.add(line);
// Fractal lines const lines = []; // Array to hold fractal lines const maxRanks = 10; // Parameter to control number of ranks
// Recursive function to create fractal lines function createFractalLines(start, end, currentRank) { if (currentRank > maxRanks) return;
const deltaX = end.x - start.x; const deltaY = end.y - start.y;
// Calculate intermediate points const x0_2 = start.x + deltaX * (1 / 3); const y0_2 = start.y + deltaY * (1 / 2);
const x1_2 = end.x - deltaX * (1 / 3); const y1_2 = end.y - deltaY * (1 / 2);
const z = start.z; // Assuming all lines are on the same z-plane
// Create three new lines for the next rank const newLines = [ new THREE.Line( new THREE.BufferGeometry().setFromPoints([start, new THREE.Vector3(x0_2, y0_2, z)]), new THREE.LineBasicMaterial({ color: 0xffffff }) ), new THREE.Line( new THREE.BufferGeometry().setFromPoints([end, new THREE.Vector3(x1_2, y1_2, z)]), new THREE.LineBasicMaterial({ color: 0xffffff }) ), new THREE.Line( new THREE.BufferGeometry().setFromPoints([new THREE.Vector3(x0_2, y0_2, z), new THREE.Vector3(x1_2, y1_2, z)]), new THREE.LineBasicMaterial({ color: 0xffffff }) ) ];
// Add new lines to the scene and lines array newLines.forEach(line => { line.frustumCulled = false; scene.add(line); lines.push(line); });
// Recursively create further ranks for each new line newLines.forEach(line => { const positions = line.geometry.attributes.position.array; const lineStart = new THREE.Vector3(positions[0], positions[1], positions[2]); const lineEnd = new THREE.Vector3(positions[3], positions[4], positions[5]); createFractalLines(lineStart, lineEnd, currentRank + 1); }); }
// Function to update fractal lines function updateFractalLines() { // Remove existing fractal lines from the scene lines.forEach(line => { scene.remove(line); line.geometry.dispose(); line.material.dispose(); }); lines.length = 0; // Clear the lines array
// Get the updated main line positions const positions = lineGeometry.attributes.position.array; const lineStart = new THREE.Vector3(positions[0], positions[1], positions[2]); const lineEnd = new THREE.Vector3(positions[3], positions[4], positions[5]);
// Generate new fractal lines starting from the main line createFractalLines(lineStart, lineEnd, 2); // Start from rank 2 }
// Initialize fractal lines updateFractalLines();
// Set the distance for grabbing the line (in world units) let distanceForGrab = 2;
// Set the raycaster's line precision raycaster.params.Line.threshold = distanceForGrab;
// Predefine vectors to avoid excessive allocations const mouseWorld = new THREE.Vector3(); const deltaWorld = new THREE.Vector3(); const currentMouse = new THREE.Vector2(); const previousMouseWorld = new THREE.Vector3();
// Mouse down event function onMouseDown(event) { if (event.button === 2) { isPanning = true; previousMousePosition.set(event.clientX, event.clientY); } else if (event.button === 0) { const rect = renderer.domElement.getBoundingClientRect(); mouse.x = ((event.clientX - rect.left) / rect.width) * 2 - 1; mouse.y = - ((event.clientY - rect.top) / rect.height) * 2 + 1;
raycaster.setFromCamera(mouse, camera); const intersects = raycaster.intersectObject(line, true); if (intersects.length > 0) { const positions = lineGeometry.attributes.position.array; const lineStart = new THREE.Vector3(positions[0], positions[1], positions[2]); const lineEnd = new THREE.Vector3(positions[3], positions[4], positions[5]); mouseWorld.copy(intersects[0].point); const distanceToStart = mouseWorld.distanceTo(lineStart); const distanceToEnd = mouseWorld.distanceTo(lineEnd); selectedEndpointIndex = (distanceToStart < distanceToEnd) ? 0 : 1; isDraggingEndpoint = true; previousMousePosition.set(mouse.x, mouse.y); }} }
// Mouse move event function onMouseMove(event) { if (isPanning) { const deltaX = event.clientX - previousMousePosition.x; const deltaY = event.clientY - previousMousePosition.y;
const zoomFactorX = camera.right - camera.left; const zoomFactorY = camera.top - camera.bottom; const panX = (deltaX / window.innerWidth) * zoomFactorX; const panY = (deltaY / window.innerHeight) * zoomFactorY; camera.left -= panX; camera.right -= panX; camera.top += panY; camera.bottom += panY; camera.updateProjectionMatrix(); previousMousePosition.set(event.clientX, event.clientY);} else if (isDraggingEndpoint) { const rect = renderer.domElement.getBoundingClientRect(); currentMouse.set( ((event.clientX - rect.left) / rect.width) * 2 - 1, - ((event.clientY - rect.top) / rect.height) * 2 + 1 );
previousMouseWorld.set(previousMousePosition.x, previousMousePosition.y, 0).unproject(camera); mouseWorld.set(currentMouse.x, currentMouse.y, 0).unproject(camera); deltaWorld.subVectors(mouseWorld, previousMouseWorld); const positions = lineGeometry.attributes.position.array; const index = selectedEndpointIndex * 3; positions[index] += deltaWorld.x; positions[index + 1] += deltaWorld.y; // Update main line lineGeometry.attributes.position.needsUpdate = true; lineGeometry.computeBoundingSphere(); previousMousePosition.copy(currentMouse); // Update fractal lines after changing the main line updateFractalLines();} }
// Mouse up event function onMouseUp(event) { if (event.button === 2) { isPanning = false; } else if (event.button === 0) { isDraggingEndpoint = false; } }
// Add event listeners for mouse actions window.addEventListener('mousedown', onMouseDown); window.addEventListener('mousemove', onMouseMove); window.addEventListener('mouseup', onMouseUp);
- Assistant
To optimize your Three.js fractal pattern code and address the performance issues caused by high object counts and frequent updates, we can implement several key optimizations:
-
Reduce the Number of Objects:
- Current Issue: Each fractal line is a separate
THREE.Lineobject with its own geometry and material. This leads to a large number of draw calls, which significantly slows down rendering. - Solution: Merge all fractal lines into a single
THREE.LineSegmentsobject. This reduces the number of WebGL draw calls and leverages GPU efficiency.
- Current Issue: Each fractal line is a separate
-
Efficient Geometry Updates:
- Current Issue: The code removes and recreates all fractal lines upon any change, which is computationally expensive.
- Solution: Rebuild the geometry's position buffer instead of managing multiple objects. This minimizes memory allocations and avoids unnecessary object creation and disposal.
-
Optimize Recursive Fractal Generation:
- Current Issue: The recursive approach repeatedly creates new objects and performs deep recursion, leading to stack overflow risks and inefficiencies.
- Solution: Implement an iterative approach using a queue or stack to generate fractal lines. This approach is more memory-efficient and avoids deep recursion issues.
-
Reuse Materials and Geometries:
- Current Issue: Creating a new material for every line segment is unnecessary and increases memory usage.
- Solution: Use a single material for all line segments to reduce memory overhead and improve rendering performance.
-
Prevent Unnecessary Recalculations:
- Current Issue: The fractal lines are recalculated even when there are no changes affecting them.
- Solution: Implement checks to ensure fractal lines are only recalculated when necessary (e.g., when the main line is modified).
Below is the optimized version of your code incorporating these improvements:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Optimized Three.js Fractal Pattern</title> <style> body { margin: 0; } canvas { display: block; } </style> </head> <body> <script type="module"> import * as THREE from './three.module.js'; // Scene setup const scene = new THREE.Scene(); scene.background = new THREE.Color(0x000000); // Camera setup const aspectRatio = window.innerWidth / window.innerHeight; const cameraSize = 200; const camera = new THREE.OrthographicCamera( -cameraSize * aspectRatio, cameraSize * aspectRatio, cameraSize, -cameraSize, 1, 1000 ); camera.position.set(0, 0, 500); const renderer = new THREE.WebGLRenderer({ antialias: true }); renderer.setSize(window.innerWidth, window.innerHeight); document.body.appendChild(renderer.domElement); // Zoom logic (based on mouse wheel and key modifiers) const zoomSpeed = 0.8; function onWheel(event) { event.preventDefault(); const rect = renderer.domElement.getBoundingClientRect(); const mouseX = ((event.clientX - rect.left) / rect.width) * 2 - 1; const mouseY = -((event.clientY - rect.top) / rect.height) * 2 + 1; const mouseWorld = new THREE.Vector3(mouseX, mouseY, 0).unproject(camera); const zoomFactor = 1 - event.deltaY * 0.001 * zoomSpeed; const ctrlPressed = event.ctrlKey; const shiftPressed = event.shiftKey; if (ctrlPressed) { camera.left = (camera.left - mouseWorld.x) * zoomFactor + mouseWorld.x; camera.right = (camera.right - mouseWorld.x) * zoomFactor + mouseWorld.x; } else if (shiftPressed) { camera.top = (camera.top - mouseWorld.y) * zoomFactor + mouseWorld.y; camera.bottom = (camera.bottom - mouseWorld.y) * zoomFactor + mouseWorld.y; } else { camera.left = (camera.left - mouseWorld.x) * zoomFactor + mouseWorld.x; camera.right = (camera.right - mouseWorld.x) * zoomFactor + mouseWorld.x; camera.top = (camera.top - mouseWorld.y) * zoomFactor + mouseWorld.y; camera.bottom = (camera.bottom - mouseWorld.y) * zoomFactor + mouseWorld.y; } camera.updateProjectionMatrix(); } // Prevent default browser behavior for wheel scrolling with Control or Shift key window.addEventListener('wheel', onWheel, { passive: false }); // Prevent default context menu on right-click window.addEventListener('contextmenu', (event) => { event.preventDefault(); }); // Render loop function animate() { requestAnimationFrame(animate); renderer.render(scene, camera); } // Handle window resize function onWindowResize() { const aspect = window.innerWidth / window.innerHeight; camera.left = -cameraSize * aspect; camera.right = cameraSize * aspect; camera.top = cameraSize; camera.bottom = -cameraSize; camera.updateProjectionMatrix(); renderer.setSize(window.innerWidth, window.innerHeight); regenerateFractal(); } window.addEventListener('resize', onWindowResize); // Initialize animation animate(); // Panning functionality let isPanning = false; let isDraggingEndpoint = false; let selectedEndpointIndex = null; const previousMousePosition = new THREE.Vector2(); // Raycaster for detecting line interaction const raycaster = new THREE.Raycaster(); const mouse = new THREE.Vector2(); // Interactive main line code const lineMaterial = new THREE.LineBasicMaterial({ color: 0xffffff }); const mainLineGeometry = new THREE.BufferGeometry().setFromPoints([ new THREE.Vector3(-50, 0, 0), new THREE.Vector3(50, 0, 0) ]); const mainLine = new THREE.Line(mainLineGeometry, lineMaterial); mainLine.frustumCulled = false; scene.add(mainLine); // Fractal lines as a single LineSegments object const fractalMaterial = new THREE.LineBasicMaterial({ color: 0xffffff }); const fractalGeometry = new THREE.BufferGeometry(); const fractalLineSegments = new THREE.LineSegments(fractalGeometry, fractalMaterial); fractalLineSegments.frustumCulled = false; scene.add(fractalLineSegments); const maxRanks = 10; // Parameter to control number of ranks // Function to create fractal lines iteratively and update the geometry function regenerateFractal() { const positions = []; const queue = []; // Push initial main line to the queue with current rank const positionsArray = mainLineGeometry.attributes.position.array; const start = new THREE.Vector3(positionsArray[0], positionsArray[1], positionsArray[2]); const end = new THREE.Vector3(positionsArray[3], positionsArray[4], positionsArray[5]); queue.push({ start, end, rank: 1 }); while (queue.length > 0) { const { start, end, rank } = queue.shift(); if (rank > maxRanks) continue; const deltaX = end.x - start.x; const deltaY = end.y - start.y; // Calculate intermediate points const x0_2 = start.x + deltaX * (1 / 3); const y0_2 = start.y + deltaY * (1 / 2); const x1_2 = end.x - deltaX * (1 / 3); const y1_2 = end.y - deltaY * (1 / 2); const z = start.z; // Assuming all lines are on the same z-plane const p0 = new THREE.Vector3(x0_2, y0_2, z); const p1 = new THREE.Vector3(x1_2, y1_2, z); // Add three new line segments positions.push(start.x, start.y, start.z, p0.x, p0.y, p0.z); // First line positions.push(end.x, end.y, end.z, p1.x, p1.y, p1.z); // Second line positions.push(p0.x, p0.y, p0.z, p1.x, p1.y, p1.z); // Middle line // Enqueue the new lines for further fractal generation queue.push({ start: start, end: p0, rank: rank + 1 }); queue.push({ start: p1, end: end, rank: rank + 1 }); queue.push({ start: p0, end: p1, rank: rank + 1 }); } // Convert positions array to Float32Array const positionArray = new Float32Array(positions); fractalGeometry.setAttribute('position', new THREE.BufferAttribute(positionArray, 3)); fractalGeometry.computeBoundingSphere(); } // Initial fractal generation regenerateFractal(); // Function to update fractal lines when the main line changes function updateFractalLines() { regenerateFractal(); } // Set the distance for grabbing the line (in world units) const distanceForGrab = 2; // Set the raycaster's line precision raycaster.params.Line.threshold = distanceForGrab; // Predefine vectors to avoid excessive allocations const mouseWorld = new THREE.Vector3(); const deltaWorld = new THREE.Vector3(); const currentMouse = new THREE.Vector2(); const previousMouseWorld = new THREE.Vector3(); // Mouse down event function onMouseDown(event) { if (event.button === 2) { // Right-click for panning isPanning = true; previousMousePosition.set(event.clientX, event.clientY); } else if (event.button === 0) { // Left-click for dragging endpoints const rect = renderer.domElement.getBoundingClientRect(); mouse.x = ((event.clientX - rect.left) / rect.width) * 2 - 1; mouse.y = - ((event.clientY - rect.top) / rect.height) * 2 + 1; raycaster.setFromCamera(mouse, camera); const intersects = raycaster.intersectObject(mainLine, true); if (intersects.length > 0) { const intersectPoint = intersects[0].point; const start = new THREE.Vector3( mainLineGeometry.attributes.position.getX(0), mainLineGeometry.attributes.position.getY(0), mainLineGeometry.attributes.position.getZ(0) ); const end = new THREE.Vector3( mainLineGeometry.attributes.position.getX(1), mainLineGeometry.attributes.position.getY(1), mainLineGeometry.attributes.position.getZ(1) ); const distanceToStart = intersectPoint.distanceTo(start); const distanceToEnd = intersectPoint.distanceTo(end); selectedEndpointIndex = (distanceToStart < distanceToEnd) ? 0 : 1; isDraggingEndpoint = true; previousMousePosition.set(event.clientX, event.clientY); } } } // Mouse move event function onMouseMove(event) { if (isPanning) { const deltaX = event.clientX - previousMousePosition.x; const deltaY = event.clientY - previousMousePosition.y; const zoomFactorX = camera.right - camera.left; const zoomFactorY = camera.top - camera.bottom; const panX = (deltaX / window.innerWidth) * zoomFactorX; const panY = (deltaY / window.innerHeight) * zoomFactorY; camera.left -= panX; camera.right -= panX; camera.top += panY; camera.bottom += panY; camera.updateProjectionMatrix(); previousMousePosition.set(event.clientX, event.clientY); } else if (isDraggingEndpoint) { const rect = renderer.domElement.getBoundingClientRect(); currentMouse.set( ((event.clientX - rect.left) / rect.width) * 2 - 1, - ((event.clientY - rect.top) / rect.height) * 2 + 1 ); // Convert screen coordinates to world coordinates const projector = new THREE.Vector3(currentMouse.x, currentMouse.y, 0).unproject(camera); const prevProjector = new THREE.Vector3( ((previousMousePosition.x - rect.left) / rect.width) * 2 - 1, - ((previousMousePosition.y - rect.top) / rect.height) * 2 + 1, 0 ).unproject(camera); deltaWorld.subVectors(projector, prevProjector); // Update the selected endpoint const positions = mainLineGeometry.attributes.position.array; const index = selectedEndpointIndex * 3; positions[index] += deltaWorld.x; positions[index + 1] += deltaWorld.y; // Mark the position attribute as needing update mainLineGeometry.attributes.position.needsUpdate = true; mainLineGeometry.computeBoundingSphere(); previousMousePosition.set(event.clientX, event.clientY); // Update fractal lines after changing the main line updateFractalLines(); } } // Mouse up event function onMouseUp(event) { if (event.button === 2) { // Right-click isPanning = false; } else if (event.button === 0) { // Left-click isDraggingEndpoint = false; } } // Add event listeners for mouse actions window.addEventListener('mousedown', onMouseDown); window.addEventListener('mousemove', onMouseMove); window.addEventListener('mouseup', onMouseUp); // Optional: Improve performance by limiting maxRanks based on device capabilities // You can dynamically adjust maxRanks here if needed </script> </body> </html>Explanation of Optimizations
-
Single
LineSegmentsObject for Fractal Lines:- Implementation: All fractal lines are combined into a single
THREE.LineSegmentsobject (fractalLineSegments). This reduces the number of objects from potentially hundreds or thousands to just one. - Benefit: Minimizes the number of draw calls and leverages GPU optimizations for rendering multiple line segments efficiently.
- Implementation: All fractal lines are combined into a single
-
Iterative Fractal Generation:
- Implementation: The
regenerateFractalfunction uses an iterative approach with a queue to generate fractal lines. This avoids the overhead of recursive function calls and prevents stack overflow for largemaxRanks. - Benefit: Improves performance by reducing function call overhead and managing memory more efficiently.
- Implementation: The
-
Efficient Buffer Geometry Updates:
- Implementation: After generating all fractal line positions, the positions are stored in a
Float32Arrayand assigned to theflactalGeometryas a single attribute. This approach minimizes memory allocations and leverages GPU-friendly data structures. - Benefit: Efficiently updates the geometry on the GPU without the need to manage multiple geometry objects.
- Implementation: After generating all fractal line positions, the positions are stored in a
-
Material Reuse:
- Implementation: A single
THREE.LineBasicMaterial(fractalMaterial) is used for all fractal lines instead of creating a new material for each line segment. - Benefit: Reduces memory usage and allows Three.js to batch render the lines more effectively.
- Implementation: A single
-
Optimized Interaction Handling:
- Implementation: Updated the mouse event handlers to work with the new fractal structure. The drag functionality now only updates the main line's endpoints and regenerates the fractal geometry.
- Benefit: Ensures that only necessary computations are performed during interactions, improving responsiveness.
-
Predefined Vectors to Avoid Reallocation:
- Implementation: Predefined instances like
mouseWorld,deltaWorld,currentMouse, andpreviousMouseWorldare reused to minimize object creation during event handling. - Benefit: Reduces garbage collection overhead, leading to smoother performance during interactions.
- Implementation: Predefined instances like
-
Frustum Culling Disabled for Lines:
- Implementation: Both
mainLineandfractalLineSegmentshavefrustumCulledset tofalse. - Benefit: Prevents unnecessary calculations for culling, which is beneficial when the fractal lines are always within the view or when culling is handled differently.
- Implementation: Both
Additional Performance Tips
-
Adjust
maxRanksAppropriately:- Higher values of
maxRanksexponentially increase the number of fractal lines. Adjust this value based on the target device's capabilities to maintain performance.
- Higher values of
-
Level of Detail (LOD):
- Implement LOD techniques to reduce the number of fractal lines rendered when zoomed out or when less detail is sufficient.
-
Throttling Updates:
- If fractal regeneration becomes a performance bottleneck during rapid interactions (like dragging), consider throttling the update frequency using techniques like
requestAnimationFrameor timing checks.
- If fractal regeneration becomes a performance bottleneck during rapid interactions (like dragging), consider throttling the update frequency using techniques like
-
GPU-Based Fractals:
- For even higher performance, consider generating fractal lines directly on the GPU using shaders. This is more advanced but can significantly offload computation from the CPU.
By implementing these optimizations, your fractal pattern should render and interact smoothly, even with multiple ranks. The reduction in object counts and efficient geometry management are key to achieving better performance in Three.js applications.
-