Certainly! You can adapt your existing code to support a dynamic number of fractal ranks by introducing a parameter that controls the depth of the fractal generation. Below, I'll guide you through the necessary modifications to achieve this functionality.
Overview
-
Introduce a maxRanks Parameter: This parameter will determine how many levels of the fractal pattern you want to generate.
-
Use Recursive Functionality: To handle multiple ranks efficiently, we'll utilize recursion to generate the fractal lines for each rank.
-
Manage Lines Dynamically: Instead of manually creating separate BufferGeometry and Line objects for each additional rank, we'll dynamically generate and manage them based on the maxRanks value.
Step-by-Step Implementation
Let's modify your original code to incorporate these enhancements.
1. Define the maxRanks Parameter
First, introduce a parameter that specifies the number of ranks (fractal levels) you want to generate.
const maxRanks = 3; // Change this value to generate more or fewer ranks
2. Refactor Line Management Using a Recursive Function
We'll create a function generateFractalLines that recursively generates lines for each rank. This approach makes it easier to manage an arbitrary number of ranks.
// Array to hold all line objects
const allLines = [];
// Function to generate fractal lines recursively
function generateFractalLines(start, end, rank) {
if (rank > maxRanks) return;
// Create a geometry for the current line segment
const geometry = new THREE.BufferGeometry().setFromPoints([start, end]);
const line = new THREE.Line(geometry, lineMaterial);
line.frustumCulled = false;
scene.add(line);
allLines.push(line);
// Calculate division points
const deltaX = end.x - start.x;
const deltaY = end.y - start.y;
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 newStart1 = new THREE.Vector3(start.x, start.y, start.z);
const newEnd1 = new THREE.Vector3(x0_2, y0_2, start.z);
const newStart2 = new THREE.Vector3(end.x, end.y, end.z);
const newEnd2 = new THREE.Vector3(x1_2, y1_2, end.z);
const connectorStart = new THREE.Vector3(x0_2, y0_2, start.z);
const connectorEnd = new THREE.Vector3(x1_2, y1_2, end.z);
// Recursively generate for the two new lines
generateFractalLines(newStart1, newEnd1, rank + 1);
generateFractalLines(newStart2, newEnd2, rank + 1);
generateFractalLines(connectorStart, connectorEnd, rank + 1);
}
3. Initialize the Fractal Lines
Replace the existing line1, line2, and line3 with dynamic generation based on the maxRanks parameter.
// Clear any existing lines beyond the main line
function clearFractalLines() {
for (let i = 0; i < allLines.length; i++) {
scene.remove(allLines[i]);
allLines[i].geometry.dispose();
allLines[i].material.dispose();
}
allLines.length = 0;
}
// Function to update all fractal lines based on the main line
function updateFractalLines() {
clearFractalLines();
const positions = lineGeometry.attributes.position.array;
const x0 = positions[0], y0 = positions[1], z0 = positions[2];
const x1 = positions[3], y1 = positions[4], z1 = positions[5];
const start = new THREE.Vector3(x0, y0, z0);
const end = new THREE.Vector3(x1, y1, z1);
// Start generating fractal lines from rank 1
generateFractalLines(start, end, 1);
}
4. Modify the Existing Rank 2 Update Function
Since we've refactored the rank generation, you no longer need separate updateRank2Lines and individual line1, line2, and line3. Instead, use the updateFractalLines function to handle all ranks.
// Replace the existing updateRank2Lines with updateFractalLines
// Remove the existing line1, line2, line3 geometries and lines
// Remove the existing updateRank2Lines function
// Initially generate fractal lines
updateFractalLines();
5. Update Fractal Lines When the Main Line Changes
Ensure that whenever the main line is updated (e.g., when dragging endpoints), the fractal lines are recalculated based on the new main line.
// Inside the onMouseMove function, replace updateRank2Lines with updateFractalLines
// ...
if (isDraggingEndpoint) {
// Existing code to update the main line's position
// ...
// Update fractal lines after changing the main line
updateFractalLines();
}
6. Final Adjustments
Ensure that all event listeners and rendering logic remain intact. Here's the complete modified script incorporating all the changes:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Three.js Draggable Line with 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);
}
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);
// Define maximum number of fractal ranks
const maxRanks = 3; // Change this value as needed
// Array to hold all fractal lines
const allLines = [];
// Function to clear existing fractal lines
function clearFractalLines() {
for (let i = 0; i < allLines.length; i++) {
scene.remove(allLines[i]);
allLines[i].geometry.dispose();
// Note: We reuse the same material, so no need to dispose it here
}
allLines.length = 0;
}
// Function to generate fractal lines recursively
function generateFractalLines(start, end, rank) {
if (rank > maxRanks) return;
// Create a geometry for the current line segment
const geometry = new THREE.BufferGeometry().setFromPoints([start, end]);
const lineSegment = new THREE.Line(geometry, lineMaterial);
lineSegment.frustumCulled = false;
scene.add(lineSegment);
allLines.push(lineSegment);
// Calculate division points
const deltaX = end.x - start.x;
const deltaY = end.y - start.y;
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 newStart1 = new THREE.Vector3(start.x, start.y, start.z);
const newEnd1 = new THREE.Vector3(x0_2, y0_2, start.z);
const newStart2 = new THREE.Vector3(end.x, end.y, end.z);
const newEnd2 = new THREE.Vector3(x1_2, y1_2, end.z);
const connectorStart = new THREE.Vector3(x0_2, y0_2, start.z);
const connectorEnd = new THREE.Vector3(x1_2, y1_2, end.z);
// Recursively generate for the two new lines and connector
generateFractalLines(newStart1, newEnd1, rank + 1);
generateFractalLines(newStart2, newEnd2, rank + 1);
generateFractalLines(connectorStart, connectorEnd, rank + 1);
}
// Function to update all fractal lines based on the main line
function updateFractalLines() {
clearFractalLines();
const positions = lineGeometry.attributes.position.array;
const x0 = positions[0], y0 = positions[1], z0 = positions[2];
const x1 = positions[3], y1 = positions[4], z1 = positions[5];
const start = new THREE.Vector3(x0, y0, z0);
const end = new THREE.Vector3(x1, y1, z1);
// Start generating fractal lines from rank 1
generateFractalLines(start, end, 1);
}
// Initially generate 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) { // Right mouse button for panning
isPanning = true;
previousMousePosition.set(event.clientX, event.clientY);
} else if (event.button === 0) { // Left mouse button 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(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(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
);
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(new THREE.Vector2(event.clientX, event.clientY));
// Update fractal lines after changing the main line
updateFractalLines();
}
}
// Mouse up event
function onMouseUp(event) {
if (event.button === 2) { // Right mouse button
isPanning = false;
} else if (event.button === 0) { // Left mouse button
isDraggingEndpoint = false;
}
}
// Add event listeners for mouse actions
window.addEventListener('mousedown', onMouseDown);
window.addEventListener('mousemove', onMouseMove);
window.addEventListener('mouseup', onMouseUp);
</script>
</body>
</html>
Explanation of Changes
-
Dynamic Rank Handling: Instead of manually defining line1, line2, and line3, we now dynamically generate lines based on the maxRanks parameter using the generateFractalLines recursive function.
-
Line Management: All fractal lines are stored in the allLines array, allowing easy management (e.g., clearing and regenerating) when the main line changes.
-
Updating Fractal Lines: Whenever the main line is moved (by dragging its endpoints), the updateFractalLines function is called to regenerate all fractal lines based on the new main line coordinates.
-
Flexibility: By changing the maxRanks variable, you can control how many levels of the fractal are generated. For example, setting maxRanks = 3 will create three levels of the fractal pattern.
Customizing the Fractal Pattern
The current fractal generation logic divides each line segment into three parts and creates additional lines based on your original code. Depending on the desired fractal pattern, you might need to adjust the division ratios (1/3 and 1/2 in this case) or the way new lines are generated.
Performance Considerations
Be cautious with high values of maxRanks, as the number of lines grows exponentially with each rank:
-
Number of Lines: For each rank, the number of lines increases by a factor based on how many subdivisions you perform. For example, if each line generates three new lines, the total number of lines grows as 3^rank.
-
Rendering Performance: High numbers of lines can impact rendering performance. Optimize by limiting maxRanks to a reasonable number (e.g., 4 or 5) and consider implementing level-of-detail (LOD) techniques if needed.
Conclusion
By refactoring your code to include a dynamic maxRanks parameter and utilizing recursion for fractal generation, you now have a flexible system that can handle any number of fractal ranks. This approach not only simplifies the management of lines but also makes your fractal pattern easily adjustable based on user-defined parameters.
Feel free to adjust the generateFractalLines function to tweak the fractal pattern to your liking. If you encounter any issues or need further customization, don't hesitate to ask!