<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Optimized Verlet Particle Simulation</title>
<style>
body {
margin: 0;
overflow: hidden;
background-color: #111;
}
canvas {
display: block;
}
#info {
position: absolute;
top: 10px;
left: 10px;
color: white;
font-size: 12px;
pointer-events: none;
}
</style>
</head>
<body>
<canvas id="canvas"></canvas>
<div id="info"></div>
<script>
// Canvas setup
const canvas = document.getElementById('canvas');
const ctx = canvas.getContext('2d');
const infoElement = document.getElementById('info');
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
// Simulation parameters
const PARTICLE_RADIUS = 3;
const SUBSTEPS = 8;
const GRAVITY = 0.2;
const FRICTION = 0.99;
const MAX_PARTICLES = 2000;
const GRID_CELL_SIZE = PARTICLE_RADIUS * 2;
// Particle class
class Particle {
constructor(x, y, radius = PARTICLE_RADIUS) {
this.x = x;
this.y = y;
this.oldX = x;
this.oldY = y;
this.radius = radius;
this.color = `hsl(${Math.random() * 360}, 80%, 50%)`;
// Add a small random initial velocity
const angle = Math.random() * Math.PI * 2;
const speed = Math.random() * 2;
this.oldX = x - Math.cos(angle) * speed;
this.oldY = y - Math.sin(angle) * speed;
}
update() {
// Calculate current velocity
const vx = (this.x - this.oldX) * FRICTION;
const vy = (this.y - this.oldY) * FRICTION;
// Save current position
this.oldX = this.x;
this.oldY = this.y;
// Apply velocity
this.x += vx;
this.y += vy;
// Apply gravity
this.y += GRAVITY;
}
draw() {
ctx.beginPath();
ctx.arc(this.x, this.y, this.radius, 0, Math.PI * 2);
ctx.fillStyle = this.color;
ctx.fill();
}
}
// Spatial Grid for optimized collision detection
class SpatialGrid {
constructor(cellSize) {
this.cellSize = cellSize;
this.grid = {};
}
clear() {
this.grid = {};
}
getCellKey(x, y) {
const gridX = Math.floor(x / this.cellSize);
const gridY = Math.floor(y / this.cellSize);
return `${gridX},${gridY}`;
}
insert(particle) {
const key = this.getCellKey(particle.x, particle.y);
if (!this.grid[key]) {
this.grid[key] = [];
}
this.grid[key].push(particle);
}
getNearbyParticles(particle) {
const result = [];
const x = particle.x;
const y = particle.y;
// Check the cell and 8 neighboring cells
for (let i = -1; i <= 1; i++) {
for (let j = -1; j <= 1; j++) {
const gridX = Math.floor((x + i * this.cellSize) / this.cellSize);
const gridY = Math.floor((y + j * this.cellSize) / this.cellSize);
const key = `${gridX},${gridY}`;
if (this.grid[key]) {
result.push(...this.grid[key]);
}
}
}
return result;
}
}
// Physics system
class PhysicsSystem {
constructor() {
this.particles = [];
this.grid = new SpatialGrid(PARTICLE_RADIUS * 2);
this.mouse = {
x: 0,
y: 0,
radius: 15,
down: false,
prevX: 0,
prevY: 0
};
this.lastTime = 0;
this.deltaTime = 1/60;
this.frameCount = 0;
this.fps = 0;
this.lastFpsUpdate = 0;
// Initialize with particles
this.initializeParticles(100);
// Add event listeners
this.setupEventListeners();
// Start animation loop
this.animate();
}
initializeParticles(count) {
for (let i = 0; i < count; i++) {
const x = Math.random() * canvas.width;
const y = Math.random() * canvas.height / 2;
this.particles.push(new Particle(x, y));
}
}
setupEventListeners() {
// Mouse events
canvas.addEventListener('mousemove', (e) => {
this.mouse.prevX = this.mouse.x;
this.mouse.prevY = this.mouse.y;
this.mouse.x = e.clientX;
this.mouse.y = e.clientY;
});
canvas.addEventListener('mousedown', (e) => {
this.mouse.down = true;
this.mouse.x = e.clientX;
this.mouse.y = e.clientY;
this.addParticlesAt(this.mouse.x, this.mouse.y, 10);
});
canvas.addEventListener('mouseup', () => {
this.mouse.down = false;
});
// Touch events
canvas.addEventListener('touchmove', (e) => {
e.preventDefault();
this.mouse.prevX = this.mouse.x;
this.mouse.prevY = this.mouse.y;
this.mouse.x = e.touches[0].clientX;
this.mouse.y = e.touches[0].clientY;
}, { passive: false });
canvas.addEventListener('touchstart', (e) => {
e.preventDefault();
this.mouse.down = true;
this.mouse.x = e.touches[0].clientX;
this.mouse.y = e.touches[0].clientY;
this.addParticlesAt(this.mouse.x, this.mouse.y, 10);
}, { passive: false });
canvas.addEventListener('touchend', () => {
this.mouse.down = false;
});
// Window resize
window.addEventListener('resize', () => {
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
});
}
addParticlesAt(x, y, count) {
if (this.particles.length >= MAX_PARTICLES) return;
const actualCount = Math.min(count, MAX_PARTICLES - this.particles.length);
for (let i = 0; i < actualCount; i++) {
const angle = Math.random() * Math.PI * 2;
const distance = Math.random() * 20;
const px = x + Math.cos(angle) * distance;
const py = y + Math.sin(angle) * distance;
this.particles.push(new Particle(px, py));
}
}
update() {
// Update spatial grid
this.grid.clear();
// Verlet integration in multiple substeps
for (let s = 0; s < SUBSTEPS; s++) {
// Update particle positions
for (const particle of this.particles) {
particle.update();
}
// Add particles to spatial grid
for (const particle of this.particles) {
this.grid.insert(particle);
}
// Solve constraints
this.solveBoundaryConstraints();
this.solveParticleCollisions();
this.solveMouseInteraction();
}
}
solveBoundaryConstraints() {
for (const particle of this.particles) {
// Bottom boundary (with bounce)
if (particle.y + particle.radius > canvas.height) {
particle.y = canvas.height - particle.radius;
const vy = particle.y - particle.oldY;
particle.oldY = particle.y + vy * 0.5; // Dampen bounce
}
// Top boundary
if (particle.y - particle.radius < 0) {
particle.y = particle.radius;
const vy = particle.y - particle.oldY;
particle.oldY = particle.y - vy * 0.5;
}
// Left boundary
if (particle.x - particle.radius < 0) {
particle.x = particle.radius;
const vx = particle.x - particle.oldX;
particle.oldX = particle.x - vx * 0.5;
}
// Right boundary
if (particle.x + particle.radius > canvas.width) {
particle.x = canvas.width - particle.radius;
const vx = particle.x - particle.oldX;
particle.oldX = particle.x - vx * 0.5;
}
}
}
solveParticleCollisions() {
// Optimized collision detection using spatial grid
for (let i = 0; i < this.particles.length; i++) {
const particleA = this.particles[i];
const nearbyParticles = this.grid.getNearbyParticles(particleA);
for (let j = 0; j < nearbyParticles.length; j++) {
const particleB = nearbyParticles[j];
// Skip self-collision
if (particleA === particleB) continue;
// Calculate distance between particles
const dx = particleB.x - particleA.x;
const dy = particleB.y - particleA.y;
const distSq = dx * dx + dy * dy;
const minDist = particleA.radius + particleB.radius;
// Check for collision
if (distSq < minDist * minDist) {
const dist = Math.sqrt(distSq) || 0.001; // Avoid division by zero
const overlap = (minDist - dist) / dist * 0.5;
// Calculate displacement
const moveX = dx * overlap;
const moveY = dy * overlap;
// Resolve collision by moving both particles
particleA.x -= moveX;
particleA.y -= moveY;
particleB.x += moveX;
particleB.y += moveY;
}
}
}
}
solveMouseInteraction() {
if (!this.mouse.down) return;
const mouseVelX = this.mouse.x - this.mouse.prevX;
const mouseVelY = this.mouse.y - this.mouse.prevY;
for (const particle of this.particles) {
const dx = particle.x - this.mouse.x;
const dy = particle.y - this.mouse.y;
const distSq = dx * dx + dy * dy;
const minDist = particle.radius + this.mouse.radius;
if (distSq < minDist * minDist) {
const dist = Math.sqrt(distSq) || 0.001;
const factor = 1 - (dist / minDist);
// Push particle away + add some mouse velocity
particle.x += (dx / dist) * factor * 2 + mouseVelX * 0.2;
particle.y += (dy / dist) * factor * 2 + mouseVelY * 0.2;
}
}
}
draw() {
// Clear canvas
ctx.clearRect(0, 0, canvas.width, canvas.height);
// Draw particles
for (const particle of this.particles) {
particle.draw();
}
// Draw mouse interaction area when pressed
if (this.mouse.down) {
ctx.beginPath();
ctx.arc(this.mouse.x, this.mouse.y, this.mouse.radius, 0, Math.PI * 2);
ctx.strokeStyle = 'rgba(255, 255, 255, 0.5)';
ctx.stroke();
}
// Update and display info
this.frameCount++;
if (performance.now() - this.lastFpsUpdate > 1000) {
this.fps = Math.round(this.frameCount * 1000 / (performance.now() - this.lastFpsUpdate));
this.frameCount = 0;
this.lastFpsUpdate = performance.now();
}
infoElement.textContent = `Particles: ${this.particles.length} | FPS: ${this.fps}`;
}
animate(currentTime = 0) {
// Calculate delta time
if (this.lastTime) {
this.deltaTime = Math.min((currentTime - this.lastTime) * 0.001, 0.05);
}
this.lastTime = currentTime;
this.update();
this.draw();
requestAnimationFrame(this.animate.bind(this));
}
}
// Initialize the physics system when the window loads
window.onload = () => {
new PhysicsSystem();
};
</script>
</body>
</html>
Would you like me to explain or break down the code?