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
- Assistant
Make ant colony simulator in Babylon.js, use algorithm and add many parameters that user can change on website
Sure! Let's build an ant colony simulator using Babylon.js, a powerful 3D JavaScript framework. We'll simulate ant behavior and provide parameters that users can adjust on the website to influence the simulation.
Features:
Let's break down the steps:
First, include Babylon.js in your HTML file and create a basic scene.
HTML Setup:
<!DOCTYPE html>
<html>
<head>
<title>Ant Colony Simulator</title>
<style>
html, body { width: 100%; height: 100%; margin: 0; padding: 0; overflow: hidden; }
#renderCanvas { width: 100%; height: 100%; touch-action: none; }
#controlPanel { position: absolute; top: 10px; left: 10px; background: rgba(255,255,255,0.8); padding: 10px; }
</style>
</head>
<body>
<canvas id="renderCanvas"></canvas>
<div id="controlPanel">
<!-- Controls will go here -->
</div>
<!-- Include Babylon.js library -->
<script src="https://cdn.babylonjs.com/babylon.js"></script>
<!-- Include GUI extension -->
<script src="https://cdn.babylonjs.com/gui/babylon.gui.min.js"></script>
<!-- Your JavaScript code -->
<script src="app.js"></script>
</body>
</html>
JavaScript Setup (app.js):
const canvas = document.getElementById('renderCanvas');
const engine = new BABYLON.Engine(canvas, true);
const createScene = function () {
const scene = new BABYLON.Scene(engine);
// Camera
const camera = new BABYLON.ArcRotateCamera("Camera", Math.PI / 2, Math.PI / 2.5, 50, BABYLON.Vector3.Zero(), scene);
camera.attachControl(canvas, true);
// Light
const light = new BABYLON.HemisphericLight("light", new BABYLON.Vector3(0, 1, 0), scene);
// Ground
const ground = BABYLON.MeshBuilder.CreateGround("ground", {width: 50, height: 50}, scene);
return scene;
};
const scene = createScene();
engine.runRenderLoop(function () {
scene.render();
});
window.addEventListener('resize', function(){
engine.resize();
});
We need to represent ants and food in our simulation.
Ant Class:
class Ant {
constructor(id, scene, startPosition) {
this.id = id;
this.scene = scene;
this.mesh = BABYLON.MeshBuilder.CreateSphere(`ant_${id}`, {diameter: 0.5}, scene);
this.mesh.position = startPosition.clone();
this.direction = new BABYLON.Vector3(Math.random(), 0, Math.random()).normalize();
this.hasFood = false;
}
update() {
// Ant movement logic will go here
}
}
Food Source:
class Food {
constructor(id, scene, position) {
this.id = id;
this.scene = scene;
this.mesh = BABYLON.MeshBuilder.CreateBox(`food_${id}`, {size: 1}, scene);
this.mesh.position = position;
this.quantity = 100; // Arbitrary value
}
}
We'll implement basic ant behavior:
Pheromone Class:
class Pheromone {
constructor(position, scene) {
this.position = position.clone();
this.intensity = 1.0;
this.scene = scene;
this.mesh = BABYLON.MeshBuilder.CreateSphere('pheromone', {diameter: 0.2}, scene);
this.mesh.position = position.clone();
this.mesh.material = new BABYLON.StandardMaterial('pheromoneMat', scene);
this.mesh.material.diffuseColor = new BABYLON.Color3(0, 1, 0);
}
evaporate(evaporationRate) {
this.intensity -= evaporationRate;
this.mesh.material.alpha = this.intensity;
if (this.intensity <= 0) {
this.mesh.dispose();
return true;
}
return false;
}
}
Update Ant Movement Logic:
Ant.prototype.update = function () {
if (this.hasFood) {
// Move towards the nest
const toNest = nestPosition.subtract(this.mesh.position).normalize();
this.mesh.moveWithCollisions(toNest.scale(antSpeed));
// Drop pheromone
pheromones.push(new Pheromone(this.mesh.position, this.scene));
// Check if reached nest
if (BABYLON.Vector3.Distance(this.mesh.position, nestPosition) < 1) {
this.hasFood = false;
}
} else {
// Move randomly or follow pheromones
let moveDirection = this.direction;
// Check for nearby pheromones
pheromones.forEach(pheromone => {
const distance = BABYLON.Vector3.Distance(this.mesh.position, pheromone.position);
if (distance < pheromoneDetectionRange && pheromone.intensity > 0) {
moveDirection = pheromone.position.subtract(this.mesh.position).normalize();
}
});
this.mesh.moveWithCollisions(moveDirection.scale(antSpeed));
// Randomly change direction
if (Math.random() < 0.1) {
this.direction = new BABYLON.Vector3(Math.random() - 0.5, 0, Math.random() - 0.5).normalize();
}
// Check for food
foods.forEach(food => {
if (BABYLON.Vector3.Distance(this.mesh.position, food.mesh.position) < 1 && food.quantity > 0) {
food.quantity--;
this.hasFood = true;
}
});
}
};
We'll create an HTML control panel to adjust parameters like:
Add Controls to HTML:
<!-- In your controlPanel div -->
<label for="antCount">Number of Ants:</label>
<input type="number" id="antCount" value="50" min="1" max="200"><br>
<label for="antSpeed">Ant Speed:</label>
<input type="range" id="antSpeed" value="0.1" min="0.01" max="0.5" step="0.01"><br>
<label for="evaporationRate">Pheromone Evaporation Rate:</label>
<input type="range" id="evaporationRate" value="0.005" min="0.001" max="0.01" step="0.001"><br>
<label for="detectionRange">Pheromone Detection Range:</label>
<input type="range" id="detectionRange" value="5" min="1" max="10" step="0.5"><br>
<button id="startSimulation">Start Simulation</button>
Update JavaScript to Read Parameters:
let antCount = parseInt(document.getElementById('antCount').value);
let antSpeed = parseFloat(document.getElementById('antSpeed').value);
let evaporationRate = parseFloat(document.getElementById('evaporationRate').value);
let pheromoneDetectionRange = parseFloat(document.getElementById('detectionRange').value);
document.getElementById('startSimulation').addEventListener('click', () => {
// Read updated parameters
antCount = parseInt(document.getElementById('antCount').value);
antSpeed = parseFloat(document.getElementById('antSpeed').value);
evaporationRate = parseFloat(document.getElementById('evaporationRate').value);
pheromoneDetectionRange = parseFloat(document.getElementById('detectionRange').value);
startSimulation();
});
Initialize ants, food sources, and start the simulation loop.
Simulation Initialization:
let ants = [];
let foods = [];
let pheromones = [];
const nestPosition = new BABYLON.Vector3(0, 0, 0);
function startSimulation() {
// Clear previous simulation
ants.forEach(ant => ant.mesh.dispose());
foods.forEach(food => food.mesh.dispose());
pheromones.forEach(pheromone => pheromone.mesh.dispose());
ants = [];
foods = [];
pheromones = [];
// Create ants
for (let i = 0; i < antCount; i++) {
const ant = new Ant(i, scene, nestPosition);
ants.push(ant);
}
// Create food sources
foods.push(new Food(0, scene, new BABYLON.Vector3(20, 0, 20)));
}
engine.runRenderLoop(function () {
scene.render();
// Update ants
ants.forEach(ant => ant.update());
// Update pheromones
pheromones = pheromones.filter(pheromone => !pheromone.evaporate(evaporationRate));
});
index.html:
<!DOCTYPE html>
<html>
<head>
<title>Ant Colony Simulator</title>
<style>
html, body { width: 100%; height: 100%; margin: 0; padding: 0; overflow: hidden; }
#renderCanvas { width: 100%; height: 100%; touch-action: none; }
#controlPanel { position: absolute; top: 10px; left: 10px; background: rgba(255,255,255,0.8); padding: 10px; }
label { display: block; margin-top: 5px; }
</style>
</head>
<body>
<canvas id="renderCanvas"></canvas>
<div id="controlPanel">
<label for="antCount">Number of Ants:</label>
<input type="number" id="antCount" value="50" min="1" max="200"><br>
<label for="antSpeed">Ant Speed:</label>
<input type="range" id="antSpeed" value="0.1" min="0.01" max="0.5" step="0.01"><br>
<label for="evaporationRate">Pheromone Evaporation Rate:</label>
<input type="range" id="evaporationRate" value="0.005" min="0.001" max="0.01" step="0.001"><br>
<label for="detectionRange">Pheromone Detection Range:</label>
<input type="range" id="detectionRange" value="5" min="1" max="10" step="0.5"><br>
<button id="startSimulation">Start Simulation</button>
</div>
<script src="https://cdn.babylonjs.com/babylon.js"></script>
<script src="app.js"></script>
</body>
</html>
app.js:
const canvas = document.getElementById('renderCanvas');
const engine = new BABYLON.Engine(canvas, true);
let antCount, antSpeed, evaporationRate, pheromoneDetectionRange;
let ants = [];
let foods = [];
let pheromones = [];
const nestPosition = new BABYLON.Vector3(0, 0, 0);
const createScene = function () {
const scene = new BABYLON.Scene(engine);
// Camera
const camera = new BABYLON.ArcRotateCamera("Camera", Math.PI / 2, Math.PI / 2.5, 70, BABYLON.Vector3.Zero(), scene);
camera.attachControl(canvas, true);
// Light
const light = new BABYLON.HemisphericLight("light", new BABYLON.Vector3(0, 1, 0), scene);
// Ground
const ground = BABYLON.MeshBuilder.CreateGround("ground", {width: 50, height: 50}, scene);
// Nest visualization
const nest = BABYLON.MeshBuilder.CreateCylinder("nest", {diameter: 2, height: 0.5}, scene);
nest.position = nestPosition;
return scene;
};
const scene = createScene();
class Ant {
constructor(id, scene, startPosition) {
this.id = id;
this.scene = scene;
this.mesh = BABYLON.MeshBuilder.CreateSphere(`ant_${id}`, {diameter: 0.5}, scene);
this.mesh.position = startPosition.clone();
this.direction = new BABYLON.Vector3(Math.random(), 0, Math.random()).normalize();
this.hasFood = false;
this.update = this.update.bind(this);
}
update() {
if (this.hasFood) {
// Move towards the nest
const toNest = nestPosition.subtract(this.mesh.position).normalize();
this.mesh.moveWithCollisions(toNest.scale(antSpeed));
// Drop pheromone
pheromones.push(new Pheromone(this.mesh.position, this.scene));
// Check if reached nest
if (BABYLON.Vector3.Distance(this.mesh.position, nestPosition) < 1) {
this.hasFood = false;
}
} else {
// Move randomly or follow pheromones
let moveDirection = this.direction;
// Check for nearby pheromones
pheromones.forEach(pheromone => {
const distance = BABYLON.Vector3.Distance(this.mesh.position, pheromone.position);
if (distance < pheromoneDetectionRange && pheromone.intensity > 0) {
moveDirection = pheromone.position.subtract(this.mesh.position).normalize();
}
});
this.mesh.moveWithCollisions(moveDirection.scale(antSpeed));
// Randomly change direction
if (Math.random() < 0.1) {
this.direction = new BABYLON.Vector3(Math.random() - 0.5, 0, Math.random() - 0.5).normalize();
}
// Check for food
foods.forEach(food => {
if (BABYLON.Vector3.Distance(this.mesh.position, food.mesh.position) < 1 && food.quantity > 0) {
food.quantity--;
this.hasFood = true;
}
});
}
}
}
class Food {
constructor(id, scene, position) {
this.id = id;
this.scene = scene;
this.mesh = BABYLON.MeshBuilder.CreateBox(`food_${id}`, {size: 1}, scene);
this.mesh.position = position;
this.mesh.material = new BABYLON.StandardMaterial('foodMat', scene);
this.mesh.material.diffuseColor = new BABYLON.Color3(1, 0, 0);
this.quantity = 100; // Arbitrary value
}
}
class Pheromone {
constructor(position, scene) {
this.position = position.clone();
this.intensity = 1.0;
this.scene = scene;
this.mesh = BABYLON.MeshBuilder.CreateSphere('pheromone', {diameter: 0.2}, scene);
this.mesh.position = position.clone();
this.mesh.material = new BABYLON.StandardMaterial('pheromoneMat', scene);
this.mesh.material.diffuseColor = new BABYLON.Color3(0, 1, 0);
}
evaporate(evaporationRate) {
this.intensity -= evaporationRate;
this.mesh.material.alpha = this.intensity;
if (this.intensity <= 0) {
this.mesh.dispose();
return true;
}
return false;
}
}
function startSimulation() {
// Read updated parameters
antCount = parseInt(document.getElementById('antCount').value);
antSpeed = parseFloat(document.getElementById('antSpeed').value);
evaporationRate = parseFloat(document.getElementById('evaporationRate').value);
pheromoneDetectionRange = parseFloat(document.getElementById('detectionRange').value);
// Clear previous simulation
ants.forEach(ant => ant.mesh.dispose());
foods.forEach(food => food.mesh.dispose());
pheromones.forEach(pheromone => pheromone.mesh.dispose());
ants = [];
foods = [];
pheromones = [];
// Create ants
for (let i = 0; i < antCount; i++) {
const ant = new Ant(i, scene, nestPosition);
ants.push(ant);
}
// Create food sources
foods.push(new Food(0, scene, new BABYLON.Vector3(20, 0, 20)));
}
engine.runRenderLoop(function () {
scene.render();
// Update ants
ants.forEach(ant => ant.update());
// Update pheromones
pheromones = pheromones.filter(pheromone => !pheromone.evaporate(evaporationRate));
});
window.addEventListener('resize', function () {
engine.resize();
});
document.getElementById('startSimulation').addEventListener('click', startSimulation);
Note: Since this is a simplified simulation, you can expand upon this base by adding more complex behaviors, obstacle avoidance, multiple food sources, or improved pheromone mechanics.
You've now set up an ant colony simulator using Babylon.js, with an algorithm simulating ant behavior and user-adjustable parameters. Users can change parameters through the web interface and observe how they affect the simulation in real-time.
Next Steps:
Feel free to customize and build upon this foundation to create a rich and interactive ant colony simulation!