Boids are a common swarm simulation program. Each entity (called a boid) accelerates based only on what the nearby boids are doing. Each boid tries to keep close to it's neighbors while maintaining a safe distance. It will adjust to try to move in the same direction as it's neighbors. Even though boids only act based on their neighbors, they can still navigate as a whole group and can form some interesting patterns. In this version, I've added some basic obstacle avoidance. The boids will move to avoid the mouse pointer.
I started this project to learn more about Web Assembly (wasm). Wasm is a portable binary format for code that modern browsers can run. You can compile Rust and C++, for example, to wasm and cut out the cost of running a garbage collector. This makes it a good choice performance intensive code.
There were still a few challenges to make this run smoothly. After running and profiling the code, I discovered that a considerable amount of time was spent allocating and freeing space for the array of neighbors for a boid. Rewriting the code to reuse the same allocated space gave the algorithm a 20% speedup. For reference, this was just a bit less than the time that it takes to actually calculate the neighbors for the boids using the brute force O(n2) algorithm.
Returning the boids' positions to JavaScript was another performance bottleneck. Values returned from wasm must be copied and converted to JS values. Fortunately, JS can directly read wasm's memory, which allows JS to read all the positions without copying them.