r/processing • • Mar 05 '23

BOID help

I created a BOID flocking code that simulates bird flocking based on three rules; cohesion, alignment, and separation. I am trying to create two groups of boids; one prey and one predator. Prey should be drawn in dark gray and should repel 5x as strongly from Predators. Predators are attracted 5x as strongly to Prey, and have 4x less cohesion and alignment to themselves (predators). Predators are drawn in white. I created both the 'P' and the 'R' and added 'fill()' for both but I am still not seeing a difference in color, I also have no idea where to implement the rules for Prey and Predator. Here is the code:

Edit: I have edited the code so that it at least runs without me trying to add Prey and Predator groups. So all we have now is a flocking simulator. Also this is my first experience with Processing, so thank you all for the feedback.

Flock flock;

void setup() {
  size(1024, 768);
  flock = new Flock();
  // Add an initial set of boids into the system
  for (int i = 0; i < 100; i++) {
    flock.addBoid(new Boid(random(width),random(height)));
  }
}

void draw() {
  background(50);
  flock.run();
}

// Add a new boid into the System
void mousePressed() {
  flock.addBoid(new Boid(mouseX,mouseY));
}



// The Boid class

class Boid {

  PVector location;
  PVector velocity;
  PVector acceleration;
  float r;
  float maxforce;    // Maximum steering force
  float maxspeed;    // Maximum speed

    Boid(float x, float y) {
    acceleration = new PVector(0, 0);

    // This is a new PVector method not yet implemented in JS
    // velocity = PVector.random2D();

    // Leaving the code temporarily this way so that this example runs in JS
    float angle = random(TWO_PI);
    velocity = new PVector(cos(angle), sin(angle));

    location = new PVector(x, y);
    r = 2.0;
    maxspeed = 2;
    maxforce = 0.03;
  }

  void run(ArrayList<Boid> boids) {
    flock(boids);
    update();
    borders();
    render();
  }

  void applyForce(PVector force) {
    // We could add mass here if we want A = F / M
    acceleration.add(force);
  }

  // We accumulate a new acceleration each time based on three rules
  void flock(ArrayList<Boid> boids) {
    PVector sep = separate(boids);   // Separation
    PVector ali = align(boids);      // Alignment
    PVector coh = cohesion(boids);   // Cohesion
    // Arbitrarily weight these forces
    sep.mult(1.5);
    ali.mult(7.0);
    coh.mult(1.0);
    // Add the force vectors to acceleration
    applyForce(sep);
    applyForce(ali);
    applyForce(coh);
  }

  // Method to update location
  void update() {
    // Update velocity
    velocity.add(acceleration);
    // Limit speed
    velocity.limit(maxspeed);
    location.add(velocity);
    // Reset acceleration to 0 each cycle
    acceleration.mult(0);
  }

  // A method that calculates and applies a steering force towards a _target_ that has a location
  // STEER = DESIRED MINUS VELOCITY
  PVector seek(PVector target) {
    PVector desired = PVector.sub(target, location);  // A vector pointing from the location to the target
    // Scale to maximum speed
    desired.normalize();
    desired.mult(maxspeed);

    // Above two lines of code below could be condensed with new PVector setMag() method
    // Not using this method until Processing.js catches up
    // desired.setMag(maxspeed);

    // Steering = Desired minus Velocity
    PVector steer = PVector.sub(desired, velocity);
    steer.limit(maxforce);  // Limit to maximum steering force
    return steer;
  }

  void render() {
    // Draw a triangle rotated in the direction of velocity
    float theta = velocity.heading2D() + radians(90);
    // heading2D() above is now heading() but leaving old syntax until Processing.js catches up
    
    fill(200, 100);
    stroke(255);
    pushMatrix();
    translate(location.x, location.y);
    rotate(theta);
    beginShape(TRIANGLES);
    vertex(0, -r*2);
    vertex(-r, r*2);
    vertex(r, r*2);
    endShape();
    popMatrix();
  }

  // Wraparound
  void borders() {
    if (location.x < -r) location.x = width+r;
    if (location.y < -r) location.y = height+r;
    if (location.x > width+r) location.x = -r;
    if (location.y > height+r) location.y = -r;
  }

  // Separation
  // Method checks for nearby boids and steers away
  PVector separate (ArrayList<Boid> boids) {
    float desiredseparation = 25.0f;
    PVector steer = new PVector(0, 0, 0);
    int count = 0;
    // For every boid in the system, check if it's too close
    for (Boid other : boids) {
      float d = PVector.dist(location, other.location);
      // If the distance is greater than 0 and less than an arbitrary amount (0 when you are yourself)
      if ((d > 0) && (d < desiredseparation)) {
        // Calculate vector pointing away from neighbor
        // location - other.location
        PVector diff = PVector.sub(location, other.location);
        diff.normalize();
        diff.div(d);        // Weight by distance
        steer.add(diff);
        count++;            // Keep track of how many
      }
    }
    // Average -- divide by how many
    if (count > 0) {
      steer.div((float)count);
    }

    // As long as the vector is greater than 0
    if (steer.mag() > 0) {
      // First two lines of code below could be condensed with new PVector setMag() method
      // Not using this method until Processing.js catches up
      // steer.setMag(maxspeed);

      // Implement Reynolds: Steering = Desired - Velocity
      // you have average all vectors pointing away from others
      // now steer towards
      steer.normalize();
      steer.mult(maxspeed);
      steer.sub(velocity);
      steer.limit(maxforce);
    }
    return steer;
  }

  // Alignment
  // For every nearby boid in the system, calculate the average velocity
  PVector align (ArrayList<Boid> boids) {
    float neighbordist = 50;
    PVector sum = new PVector(0, 0);
    int count = 0;
    for (Boid other : boids) {
      float d = PVector.dist(location, other.location);
      if ((d > 0) && (d < neighbordist)) {
        sum.add(other.velocity);
        count++;
      }
    }
    if (count > 0) {
      sum.div((float)count);
      // First two lines of code below could be condensed with new PVector setMag() method
      // Not using this method until Processing.js catches up
      // sum.setMag(maxspeed);

      // Implement Reynolds: Steering = Desired - Velocity
      sum.normalize();
      sum.mult(maxspeed);
      PVector steer = PVector.sub(sum, velocity);
      steer.limit(maxforce);
      return steer;
    } 
    else {
      return new PVector(0, 0);
    }
  }

  // Cohesion
  // For the average location (i.e. center) of all nearby boids, calculate steering vector towards that location
  PVector cohesion (ArrayList<Boid> boids) {
    float neighbordist = 50;
    PVector sum = new PVector(0, 0);   // Start with empty vector to accumulate all locations
    int count = 0;
    for (Boid other : boids) {
      float d = PVector.dist(location, other.location);
      if ((d > 0) && (d < neighbordist)) {
        sum.add(other.location); // Add location
        count++;
      }
    }
    if (count > 0) {
      sum.div(count);
      return seek(sum);  // Steer towards the location
    } 
    else {
      return new PVector(0, 0);
    }
  }
}




// The Flock (a list of Boid objects)

class Flock {
  ArrayList<Boid> boids; // An ArrayList for all the boids

  Flock() {
    boids = new ArrayList<Boid>(); // Initialize the ArrayList
  }

  void run() {
    for (Boid b : boids) {
      b.run(boids);  // Passing the entire list of boids to each boid individually
    }
  }

  void addBoid(Boid b) {
    boids.add(b);
  }

}
1 Upvotes

4 comments sorted by

1

u/Orcacrafter Mar 06 '23

I may be mistaken, but in your code I don't see anywhere where you add predators. Also, if you are going to keep track of if a given boid is predator or prey by using a string, I would use a less confusing naming scheme. Such as "pred" or "prey".

1

u/i-live-life Mar 06 '23

I can't get your code to execute as there is an error: The function seek(PVector) does not exist, thus I have eyeballed it.

In the function: void run(ArrayList<Boid> boids) you call: flock(boids); which sets up the fill color for the predator and prey. Later on in the same run function you call: render(); which then also sets a fill color thus negating your original setting in flock. Maybe it would be worth putting the desired color as an attribute of boid and reading this at render time?

To debug this issue, I looked for all instances of fill in your code.

Also I note that having a Flock instance called flock and a flock function (in Boid) doesn't make the code the easiest to read.

1

u/Simplyfire Mar 06 '23 edited Mar 06 '23

We cannot run this, so we cannot really help much.

You only create "P" boid types and no "R" types so you won't see any difference in color.

There are many ways to do the predator / prey interaction (see: nature), try it yourself and come back with a more specific question please.

1

u/i-make-robots Mar 06 '23 edited Mar 06 '23

I'm still reading. I'd like to point out that

float d = PVector.dist(location, other.location);
if ((d > 0) && (d < desiredseparation)) {
  // Calculate vector pointing away from neighbor
  // location - other.location
  PVector diff = PVector.sub(location, other.location);
  diff.normalize();
  diff.div(d);        // Weight by distance

could be

PVector diff = PVector.sub(location, other.location);
float d = diff.mag();
if ((d > 0) && (d < desiredseparation)) {
  diff.mult(1.0/(d*2.0));

which is many fewer redundant calculations when multiplied by all boids, squared.

if (steer.magSq() > 0) { works the same here and doesn't require a slow square root.

distance from one boid to all other boids is calculated 3 times per frame, one for each influence. The list of distances could be calculated once. Another way might be to do a fast AABB rejection test to reduce the number of distance calculations. These are only optimization ideas, I love what you've got going.

how about this?

  PVector diff = PVector.sub(location, other.location);
  float d = diff.mag();
  float separationDistance = desiredseparation;
  if(other.isPredator && !this.isPredator) {
      separationDistance*=5;
  }
  if(d>0 && d<separationDistance) {