home | projects

Bird flocking algortim using HLSL

For a few months in coronavirus, I developed many iterations of this algortim. I read ‘The Garden in the Machine’ by Claus Emmeche and loved the ideas so much. My first attempt was made by following the Coding Train video on boids by Daniel Schiffman (amazing host). After that, I experimented with 2D and 3D vectors in a 2D space and multiple output methods. What I landed on was a 2D vector used for the boids where one number was used as the magnitude, and the other for direction (as opposed to one for an x value and one for a y value). The final output methods I chose were a 2D texture and a 3D mesh. The texture shows pixels that represent boids, with the colour of the pixels representing the density of the boids in that area. The mesh also showed the density of the boids in that area as the height of vertices, which makes for smooth graph shapes.


My first few attempts at Boids used C# inside Unity for each agent’s logic. Later iterations used my GPU with compute shaders written in HLSL. The use of compute shaders (which are still magic to me) sent the boid-count from hundreds to hundreds of thousands. But, it was very annoying to do. Learning to write shader code was very rewarding but not having a print or console to write to was painful.


Below are some videos from the final version of my program. I think because of my use of compute shaders, I cannot upload an interactive version of my program here using OpenGL or something similar but I will try soon. Some of the shader code is also included below.


This is an example of the output mesh that samples the density of the boids in an area. it uses the relative desnity as the height of the vertices in the area.


    

This is a sample of the output texture of the boids without the output mesh. This example is using around 50,000 boids thanks to the compute shaders, although it is hard to see.


    

Another example of the mesh and Boid texture interacting, this time with the control panel that I was using visible. The exposed variables allowed me to pass information to the compute shaders in real time which was really cool because you could see the immediate results in the texture.


    

In this video I am testing the effect of the variables without the output mesh.


    

This is the example from earlier but with the controls cropped out.


    

The program was written in C# and HLSL.