Make ant colony simulator in Babylon.js, use algorithm and add many parameters that user…
- User
Make ant colony simulator in Babylon.js, use algorithm and add many parameters that user can change on website, provide full code in one file
- Assistant
Make ant colony simulator in Babylon.js, use algorithm and add many parameters that user can change on website, provide full code in one file
Sure! Below is the full code for an ant colony simulator using Babylon.js. The simulator allows users to adjust various parameters in real-time through a simple user interface. To run the simulator, save the code below into a file with an .html extension (e.g., ant_colony_simulator.html) and open it in a modern web browser.
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Ant Colony Simulator</title>
<style>
html, body {
overflow: hidden;
width: 100%;
height: 100%;
margin: 0;
padding: 0;
}
#renderCanvas {
width: 100%;
height: 100%;
touch-action: none;
}
#controls {
position: absolute;
top: 10px;
left: 10px;
background: rgba(255,255,255,0.8);
padding: 10px;
border-radius: 5px;
z-index: 10;
}
#controls label {
display: block;
margin-top: 5px;
}
#controls input[type=range] {
width: 100%;
}
</style>
</head>
<body>
<canvas id="renderCanvas"></canvas>
<div id="controls">
<label>
Number of Ants: <span id="numAntsLabel">50</span>
<input type="range" id="numAnts" min="10" max="200" value="50">
</label>
<label>
Pheromone Evaporation Rate: <span id="evaporationRateLabel">0.01</span>
<input type="range" id="evaporationRate" min="0.001" max="0.1" step="0.001" value="0.01">
</label>
<label>
Ant Speed: <span id="antSpeedLabel">1</span>
<input type="range" id="antSpeed" min="0.5" max="5" step="0.1" value="1">
</label>
<label>
Pheromone Intensity: <span id="pheromoneIntensityLabel">1</span>
<input type="range" id="pheromoneIntensity" min="0.1" max="5" step="0.1" value="1">
</label>
</div>
<!-- Babylon.js CDN -->
<script src="https://cdn.babylonjs.com/babylon.js"></script>
<!-- Babylon.js GUI -->
<script src="https://cdn.babylonjs.com/gui/babylon.gui.min.js"></script>
<script>
// Get the canvas element
const canvas = document.getElementById('renderCanvas');
// Generate the Babylon.js engine
const engine = new BABYLON.Engine(canvas, true);
// Global variables
let scene;
let ants = [];
let pheromones = [];
let pheromoneMesh;
const antSize = 0.1;
const gridSize = 50;
let pheromoneGrid = [];
// Simulation parameters
let numAnts = parseInt(document.getElementById('numAnts').value);
let evaporationRate = parseFloat(document.getElementById('evaporationRate').value);
let antSpeed = parseFloat(document.getElementById('antSpeed').value);
let pheromoneIntensity = parseFloat(document.getElementById('pheromoneIntensity').value);
// Create the scene
const createScene = function () {
scene = new BABYLON.Scene(engine);
// Setup camera
const camera = new BABYLON.ArcRotateCamera("Camera", Math.PI / 2, Math.PI / 2.5, 60, BABYLON.Vector3.Zero(), scene);
camera.attachControl(canvas, true);
// Add lights
const light = new BABYLON.HemisphericLight("light1", new BABYLON.Vector3(1, 1, 0), scene);
// Ground
const ground = BABYLON.MeshBuilder.CreateGround("ground", { width: gridSize, height: gridSize }, scene);
// Initialize pheromone grid
initializePheromoneGrid();
// Create pheromone visualization
pheromoneMesh = createPheromoneMesh();
// Create ants
createAnts();
return scene;
};
// Initialize pheromone grid
function initializePheromoneGrid() {
pheromoneGrid = [];
for (let x = 0; x < gridSize; x++) {
pheromoneGrid[x] = [];
for (let z = 0; z < gridSize; z++) {
pheromoneGrid[x][z] = 0;
}
}
}
// Create pheromone mesh for visualization
function createPheromoneMesh() {
const customMesh = new BABYLON.Mesh("custom", scene);
const positions = [];
const colors = [];
const indices = [];
for (let x = 0; x < gridSize; x++) {
for (let z = 0; z < gridSize; z++) {
positions.push(x - gridSize / 2, 0.01, z - gridSize / 2);
colors.push(0, 0, 0, 1);
}
}
const vertexData = new BABYLON.VertexData();
vertexData.positions = positions;
vertexData.colors = colors;
vertexData.applyToMesh(customMesh);
return customMesh;
}
// Update pheromone visualization
function updatePheromoneMesh() {
const colors = pheromoneMesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
let index = 0;
for (let x = 0; x < gridSize; x++) {
for (let z = 0; z < gridSize; z++) {
const intensity = pheromoneGrid[x][z];
colors[index * 4] = intensity; // R
colors[index * 4 + 1] = 0; // G
colors[index * 4 + 2] = 1 - intensity; // B
colors[index * 4 + 3] = 1; // A
index++;
}
}
pheromoneMesh.updateVerticesData(BABYLON.VertexBuffer.ColorKind, colors);
}
// Create ant agents
function createAnts() {
ants.forEach(ant => ant.mesh.dispose());
ants = [];
for (let i = 0; i < numAnts; i++) {
const ant = {
position: new BABYLON.Vector3(
(Math.random() - 0.5) * gridSize,
0.1,
(Math.random() - 0.5) * gridSize
),
direction: new BABYLON.Vector3(
Math.random() - 0.5,
0,
Math.random() - 0.5
).normalize(),
mesh: BABYLON.MeshBuilder.CreateBox("ant" + i, { size: antSize }, scene)
};
ant.mesh.position = ant.position.clone();
ants.push(ant);
}
}
// Update ants' movement
function updateAnts() {
ants.forEach(ant => {
// Random motion with influence from pheromones
const gridX = Math.floor(ant.position.x + gridSize / 2);
const gridZ = Math.floor(ant.position.z + gridSize / 2);
let pheromoneDirection = new BABYLON.Vector3(0, 0, 0);
for (let dx = -1; dx <= 1; dx++) {
for (let dz = -1; dz <= 1; dz++) {
const nx = gridX + dx;
const nz = gridZ + dz;
if (nx >= 0 && nx < gridSize && nz >= 0 && nz < gridSize) {
const intensity = pheromoneGrid[nx][nz];
const dir = new BABYLON.Vector3(dx, 0, dz).normalize();
pheromoneDirection.addInPlace(dir.scale(intensity));
}
}
}
pheromoneDirection.normalize();
const randomDirection = new BABYLON.Vector3(
(Math.random() - 0.5) * 0.1,
0,
(Math.random() - 0.5) * 0.1
);
ant.direction = ant.direction.add(pheromoneDirection).add(randomDirection).normalize();
ant.position.addInPlace(ant.direction.scale(antSpeed * 0.1));
// Wrap around edges
if (ant.position.x < -gridSize / 2) ant.position.x += gridSize;
if (ant.position.x > gridSize / 2) ant.position.x -= gridSize;
if (ant.position.z < -gridSize / 2) ant.position.z += gridSize;
if (ant.position.z > gridSize / 2) ant.position.z -= gridSize;
ant.mesh.position = ant.position.clone();
ant.mesh.rotation.y = Math.atan2(ant.direction.x, ant.direction.z);
// Deposit pheromones
const px = Math.floor(ant.position.x + gridSize / 2);
const pz = Math.floor(ant.position.z + gridSize / 2);
if (px >= 0 && px < gridSize && pz >= 0 && pz < gridSize) {
pheromoneGrid[px][pz] += pheromoneIntensity * 0.05;
if (pheromoneGrid[px][pz] > 1) pheromoneGrid[px][pz] = 1;
}
});
}
// Evaporate pheromones
function evaporatePheromones() {
for (let x = 0; x < gridSize; x++) {
for (let z = 0; z < gridSize; z++) {
pheromoneGrid[x][z] *= (1 - evaporationRate);
if (pheromoneGrid[x][z] < 0) pheromoneGrid[x][z] = 0;
}
}
}
// Run the render loop
const sceneToRender = createScene();
engine.runRenderLoop(function () {
updateAnts();
evaporatePheromones();
updatePheromoneMesh();
scene.render();
});
// Resize the engine when the window is resized
window.addEventListener('resize', function () {
engine.resize();
});
// Update parameters when controls change
document.getElementById('numAnts').addEventListener('input', function (e) {
numAnts = parseInt(e.target.value);
document.getElementById('numAntsLabel').innerText = numAnts;
createAnts();
});
document.getElementById('evaporationRate').addEventListener('input', function (e) {
evaporationRate = parseFloat(e.target.value);
document.getElementById('evaporationRateLabel').innerText = evaporationRate;
});
document.getElementById('antSpeed').addEventListener('input', function (e) {
antSpeed = parseFloat(e.target.value);
document.getElementById('antSpeedLabel').innerText = antSpeed;
});
document.getElementById('pheromoneIntensity').addEventListener('input', function (e) {
pheromoneIntensity = parseFloat(e.target.value);
document.getElementById('pheromoneIntensityLabel').innerText = pheromoneIntensity;
});
</script>
</body>
</html>
Save the Code: Copy the entire code above and paste it into a new file. Save the file with an .html extension, such as ant_colony_simulator.html.
Open in Browser: Open the saved file in a modern web browser such as Chrome, Firefox, or Edge.
Adjust Parameters: Use the controls at the top-left corner to adjust the simulation parameters:
Observe: Watch how the ants interact and how the pheromone trails evolve over time.
Number of Ants: Increasing the number of ants can lead to more complex behavior and pronounced pheromone trails.
Pheromone Evaporation Rate: A higher evaporation rate means pheromones disappear faster, which can prevent trails from dominating but might also disrupt path formation.
Ant Speed: Faster ants cover more ground quickly but might not follow pheromone trails as accurately.
Pheromone Intensity: Determines how much pheromone ants deposit. Higher intensity leads to stronger trails that influence ant movement more significantly.
Scene Setup: Initializes the Babylon.js scene, camera, and light sources.
Pheromone Grid: A 2D grid represents the pheromone concentration in the environment.
Ant Agents: Each ant is represented by an object containing its position, direction, and mesh.
Ant Movement: Ants move based on a combination of their current direction, random perturbations, and the pheromone concentration in their vicinity.
Pheromone Deposition: As ants move, they deposit pheromones on the grid.
Pheromone Evaporation: Pheromones evaporate over time based on the evaporation rate.
Visualization: Pheromone levels are visualized by coloring the ground mesh. Higher concentrations appear more red.
User Interface: HTML range inputs allow users to adjust simulation parameters in real-time.
This simulator demonstrates basic principles of ant colony behavior and pheromone-based pathfinding. By adjusting the parameters, you can observe how ant colonies optimize paths and how pheromone dynamics affect their collective movement.
Feel free to experiment with the code and modify it to explore more complex behaviors or visualizations!
Not yet included in a published release.