Move horizontally over the tank to orbit the school.

0:01 / 0:30
Playback speed

Boids · a 3D school of fish

Turn off separation. Where do fish bunch up? Scrub back to the start with only alignment enabled and watch which fish take the same heading.

Interactive demo#MotionAndFeelABZÛ

Thirty-six fish form a school by steering toward nearby fish, matching headings and keeping some space.

Each fish reads the previous simulation step’s positions and velocities in three dimensions. Within its neighbourhood it turns toward the group’s centre and matches the average velocity. At close range it pushes away more strongly. The tank also turns fish back at the edges. Pause and orbit the school to see fish that overlap on screen but are far apart in depth.

Code

src/demos/boids.goose
namespace boids_lesson;
import stage;
import math;
import std;

struct Fish { pos: f64[3], vel: f64[3] }
const count = 36;
var school: Fish[36] = [Fish { pos: [0.0;3], vel: [0.0;3] };36];
var tick = -1;

fn initialize() {
    for i in count {
        let a = i * 2.4;
        school[i] = Fish {
            pos: [sin(a) * (10 + i % 20), sin(i * 1.37) * 15, cos(a) * 23],
            vel: [12 * cos(a), 4 * sin(i * 0.8), -12 * sin(a)]
        };
    }
    tick = 0;
}

fn step(separate: bool, align: bool, cohere: bool) {
    // Read a snapshot so every fish sees its neighbours at the same instant.
    let previous = school;
    for fish, i in previous {
        var away = [0.0;3];
        var headings = [0.0;3];
        var offsets = [0.0;3];
        var neighbours = 0;
        for other, j in previous {
            if i == j { continue; }
            let delta = other.pos - fish.pos;
            let d2 = delta[0]*delta[0] + delta[1]*delta[1] + delta[2]*delta[2];
            if d2 > 21 * 21 { continue; }
            neighbours += 1;
            headings += other.vel;
            offsets += delta;
            if d2 < 9 * 9 {
                for axis in 3 { away[axis] -= delta[axis] / max(0.1, d2); }
            }
        }
        var v = fish.vel;
        let bounds = [38.0, 19.0, 31.0];
        for axis in 3 {
            let p = fish.pos[axis];
            var force = (clamp(p, -bounds[axis], bounds[axis]) - p) * 3.2;
            if separate { force += away[axis] * 78; }
            if neighbours > 0 {
                if align { force += (headings[axis] / neighbours - v[axis]) * 1.35; }
                if cohere { force += offsets[axis] / neighbours * 0.8; }
            }
            v[axis] += force / 30;
        }
        let speed = max(0.001, sqrt(v[0]*v[0] + v[1]*v[1] + v[2]*v[2]));
        for axis in 3 {
            v[axis] *= clamp(speed, 10.0, 20.0) / speed;
            school[i].pos[axis] += v[axis] / 30;
        }
        school[i].vel = v;
    }
    tick += 1;
}

// Rotate around the school, then divide by camera depth for perspective.
fn project(pos: f64[3], cs: f64, sn: f64) -> f64[3] {
    let depth = 106 + pos[0]*sn + pos[2]*cs;
    let scale = 130 / max(25.0, depth);
    return [80 + (pos[0]*cs - pos[2]*sn)*scale, 50 - pos[1]*scale, scale];
}

// Draw the outward face of a triangular facet on the fish's convex body.
fn facet(a: f64[3], b: f64[3], c: f64[3], colour: const u8[:]) {
    let winding = (b[0] - a[0]) * (c[1] - a[1]) - (b[1] - a[1]) * (c[0] - a[0]);
    if winding > 0 { quad(a[0], a[1], b[0], b[1], c[0], c[1], a[0], a[1], colour); }
}

export "boids" fn draw(time: f64, dt: f64, px: f64, py: f64, hover: bool) {
    let target = floor(time * 30) as i64;
    if tick < 0 || target < tick { initialize(); }
    let separate = toggle("separation");
    let align = toggle("alignment");
    let cohere = toggle("cohesion");
    while tick < target { step(separate, align, cohere); }
    let angle = if hover { (px / 160 - 0.5) * 2 * PI } else { time * 0.12 + 0.25 };
    let cs = cos(angle);
    let sn = sin(angle);
    artwork("reef");
    for i in 8 {
        let x = (i * 31 + 6 * sin(time + i)) % 170;
        let y = 99 - (time * 7 + i * 21) % 100;
        ring(x, y, 1.2, "#438598");
    }
    // Painter's order, far to near.
    var order: i64[36] = [0;36];
    var positions: f64[3][36] = [[0.0;3];36];
    for fish, i in school {
        positions[i] = project(fish.pos, cs, sn);
        var slot = i;
        while slot > 0 && positions[order[slot - 1]][2] > positions[i][2] {
            order[slot] = order[slot - 1];
            slot -= 1;
        }
        order[slot] = i;
    }
    for i in order {
        let fish = school[i];
        let v = fish.vel;
        let speed = sqrt(v[0]*v[0] + v[1]*v[1] + v[2]*v[2]);
        let f = [v[0]/speed, v[1]/speed, v[2]/speed];
        let flat = max(0.001, sqrt(f[0]*f[0] + f[2]*f[2]));
        let side = [-f[2]/flat, 0.0, f[0]/flat];
        let up = [-f[1]*f[0]/flat, flat, -f[1]*f[2]/flat];
        // Four tapered rings give the school a rounded shoulder, slender tailstock and silver belly.
        let sizes = [0.90, 1.02, 0.95, 1.12, 0.87];
        let k = sizes[i % 5];
        let sway = sin(time * (7.5 + speed * 0.12) + i) * k;
        let nose = project(fish.pos + f * [5.0 * k;3], cs, sn);
        let station = [2.7, 0.0, -2.8, -4.6];
        let girth = [1.1, 1.4, 0.93, 0.32];
        let height = [1.65, 2.1, 1.38, 0.4];
        let breadth = [1.0, 0.55, -0.55, -1.0, -0.52, 0.52];
        let profile = [0.02, 0.92, 0.92, 0.02, -0.90, -0.90];
        var mesh: f64[3][6][4] = [[[0.0;3];6];4];
        for j in 4 {
            let bend = sway * [0.0, 0.06, 0.28, 0.70][j];
            let centre = fish.pos + f * [station[j] * k;3] + side * [bend;3];
            for vtx in 6 {
                mesh[j][vtx] = project(centre + side * [breadth[vtx] * girth[j] * k;3]
                    + up * [profile[vtx] * height[j] * k;3], cs, sn);
            }
        }
        let tail = fish.pos - f * [4.5 * k;3] + side * [sway * 0.7;3];
        let fan = tail - f * [2.45 * k;3] + side * [sway * 1.05;3];
        let joint = project(tail, cs, sn);
        let notch = project(fan + f * [1.25 * k;3], cs, sn);
        let upper = project(fan + up * [1.95 * k;3], cs, sn);
        let lower = project(fan - up * [1.55 * k;3], cs, sn);
        quad(joint[0], joint[1], upper[0], upper[1], notch[0], notch[1], lower[0], lower[1], "#d78a49");
        let dorsal = project(fish.pos - f * [1.55 * k;3] + up * [3.05 * k;3], cs, sn);
        let root = mesh[1][1];
        let end = mesh[2][1];
        quad(root[0], root[1], dorsal[0], dorsal[1], end[0], end[1], root[0], root[1], "#266878");
        for j in 6 {
            let next = (j + 1) % 6;
            let colour = match j { 0 => "#4daca6", 1 => "#236e7c", 2 => "#449e9e",
                                   3 => "#c6ddbf", 4 => "#f4e7bc", _ => "#bad8be" };
            facet(nose, mesh[0][j], mesh[0][next], colour);
            for part in 3 {
                let a = mesh[part][j];
                let b = mesh[part+1][j];
                let c = mesh[part+1][next];
                let d = mesh[part][next];
                let winding = (b[0]-a[0])*(d[1]-a[1]) - (b[1]-a[1])*(d[0]-a[0]);
                if winding > 0 { quad(a[0],a[1],b[0],b[1],c[0],c[1],d[0],d[1],colour); }
            }
        }
        let flank = if mesh[0][0][2] > mesh[0][3][2] { 0 } else { 3 };
        let gill = mesh[0][flank];
        let belt = mesh[1][flank];
        let taper = mesh[2][flank];
        quad(gill[0],gill[1],belt[0],belt[1]-0.38*k*belt[2],taper[0],taper[1],belt[0],belt[1]+0.18*k*belt[2],"#efd79b");
        let eye_x = mix_value(gill[0], nose[0], 0.37);
        let eye_y = mix_value(gill[1], nose[1], 0.37) - 0.29 * k * gill[2];
        ell(eye_x, eye_y, 0.56*k*gill[2], 0.56*k*gill[2], "#d5ae66");
        ell(eye_x, eye_y, 0.32*k*gill[2], 0.32*k*gill[2], "#172e39");
    }
}

Stage drawing helpers · All demos on GitHub

Comments

No comments yet.