Spaces:
Running
Running
File size: 8,011 Bytes
a32dc8b |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 |
// No direct THREE.js import needed
/**
* Crowd Simulation with Collision Avoidance for Villagers
*
* This implementation uses a combination of steering behaviors and spatial partitioning
* to efficiently manage crowd simulation with collision avoidance for multiple villagers.
*/
class CrowdManager {
constructor() {
this.villagers = [];
this.spatialGrid = new SpatialGrid(100, 100, 5); // 100x100 grid with 5 unit cells
}
/**
* Add a villager to the crowd simulation
* @param {Villager} villager - The villager to add
*/
addVillager(villager) {
this.villagers.push(villager);
this.spatialGrid.insert(villager);
}
/**
* Update all villagers in the crowd simulation
* @param {number} deltaTime - Time since last frame
*/
update(deltaTime) {
// Update spatial grid
this.spatialGrid.clear();
for (const villager of this.villagers) {
this.spatialGrid.insert(villager);
}
// Update each villager
for (const villager of this.villagers) {
// Get nearby villagers for collision avoidance
const nearby = this.spatialGrid.query(villager.position, 10);
// Calculate steering forces
const avoidanceForce = this.calculateAvoidanceForce(villager, nearby);
const steeringForce = this.calculateSteeringForce(villager);
// Apply forces to velocity (using arrays)
this.addScaledVector(villager.velocity, avoidanceForce, deltaTime);
this.addScaledVector(villager.velocity, steeringForce, deltaTime);
// Limit velocity
const speed = this.calculateVectorLength(villager.velocity);
if (speed > villager.maxSpeed) {
this.normalizeVector(villager.velocity);
this.scaleVectorInPlace(villager.velocity, villager.maxSpeed);
}
// Update position
const moveVector = this.scaleVector(villager.velocity, deltaTime);
this.addVectors(villager.position, moveVector);
}
}
/**
* Calculate avoidance force to prevent collisions
* @param {Villager} villager - The villager to calculate for
* @param {Array<Villager>} nearby - Nearby villagers
* @returns {Array} Avoidance force as [x, y, z]
*/
calculateAvoidanceForce(villager, nearby) {
const force = [0, 0, 0];
for (const neighbor of nearby) {
if (neighbor === villager) continue;
const distance = this.calculateDistance(villager.position, neighbor.position);
if (distance < villager.avoidanceRadius && distance > 0) {
// Calculate avoidance direction (away from neighbor)
const direction = this.subtractVectors(villager.position, neighbor.position);
this.normalizeVector(direction);
// Scale force by inverse of distance (stronger when closer)
const strength = (villager.avoidanceRadius - distance) / villager.avoidanceRadius;
this.addScaledVector(force, direction, strength);
}
}
return this.scaleVector(force, villager.avoidanceWeight);
}
/**
* Calculate distance between two positions
*/
calculateDistance(pos1, pos2) {
const dx = pos1[0] - pos2[0];
const dy = pos1[1] - pos2[1];
const dz = pos1[2] - pos2[2];
return Math.sqrt(dx * dx + dy * dy + dz * dz);
}
/**
* Subtract two vectors
*/
subtractVectors(vec1, vec2) {
return [
vec1[0] - vec2[0],
vec1[1] - vec2[1],
vec1[2] - vec2[2]
];
}
/**
* Normalize a vector
*/
normalizeVector(vec) {
const length = Math.sqrt(vec[0] * vec[0] + vec[1] * vec[1] + vec[2] * vec[2]);
if (length > 0) {
vec[0] /= length;
vec[1] /= length;
vec[2] /= length;
}
}
/**
* Add scaled vector to another vector
*/
addScaledVector(target, source, scale) {
target[0] += source[0] * scale;
target[1] += source[1] * scale;
target[2] += source[2] * scale;
}
/**
* Scale a vector
*/
scaleVector(vec, scale) {
return [
vec[0] * scale,
vec[1] * scale,
vec[2] * scale
];
}
/**
* Calculate vector length
*/
calculateVectorLength(vec) {
return Math.sqrt(vec[0] * vec[0] + vec[1] * vec[1] + vec[2] * vec[2]);
}
/**
* Scale vector in place
*/
scaleVectorInPlace(vec, scale) {
vec[0] *= scale;
vec[1] *= scale;
vec[2] *= scale;
}
/**
* Add two vectors
*/
addVectors(target, source) {
target[0] += source[0];
target[1] += source[1];
target[2] += source[2];
}
/**
* Calculate steering force to follow path
* @param {Villager} villager - The villager to calculate for
* @returns {Array} Steering force as [x, y, z]
*/
calculateSteeringForce(villager) {
if (villager.path.length === 0) return [0, 0, 0];
const target = villager.path[0];
const direction = this.subtractVectors(target, villager.position);
this.normalizeVector(direction);
const desired = this.scaleVector(direction, villager.maxSpeed);
const steer = this.subtractVectors(desired, villager.velocity);
return this.scaleVector(steer, villager.steeringWeight);
}
}
/**
* Spatial Grid for efficient neighbor queries
*/
class SpatialGrid {
constructor(width, height, cellSize) {
this.width = width;
this.height = height;
this.cellSize = cellSize;
this.grid = [];
// Initialize grid
const cols = Math.ceil(width / cellSize);
const rows = Math.ceil(height / cellSize);
for (let i = 0; i < cols * rows; i++) {
this.grid.push([]);
}
}
/**
* Get cell index for a position
* @param {Array} position - Position to get cell for [x, y, z]
* @returns {number} Cell index
*/
getCellIndex(position) {
const col = Math.floor(position[0] / this.cellSize);
const row = Math.floor(position[2] / this.cellSize);
return row * Math.ceil(this.width / this.cellSize) + col;
}
/**
* Insert an object into the grid
* @param {Object} obj - Object to insert
*/
insert(obj) {
const index = this.getCellIndex(obj.position);
if (index >= 0 && index < this.grid.length) {
this.grid[index].push(obj);
}
}
/**
* Clear the grid
*/
clear() {
for (let i = 0; i < this.grid.length; i++) {
this.grid[i] = [];
}
}
/**
* Query objects within a radius
* @param {Array} position - Center position [x, y, z]
* @param {number} radius - Query radius
* @returns {Array<Object>} Objects within radius
*/
query(position, radius) {
const results = [];
const col = Math.floor(position[0] / this.cellSize);
const row = Math.floor(position[2] / this.cellSize);
const radiusCells = Math.ceil(radius / this.cellSize);
const cols = Math.ceil(this.width / this.cellSize);
const rows = Math.ceil(this.height / this.cellSize);
// Check surrounding cells
for (let r = Math.max(0, row - radiusCells); r <= Math.min(rows - 1, row + radiusCells); r++) {
for (let c = Math.max(0, col - radiusCells); c <= Math.min(cols - 1, col + radiusCells); c++) {
const index = r * cols + c;
if (index >= 0 && index < this.grid.length) {
results.push(...this.grid[index]);
}
}
}
return results;
}
}
export default CrowdManager; |