Crackling Noise Bug

Hello,

I am working on a sketch that activates sound files, but after a while I get a crackling noise that then won’t go away. I believe this happens when too many files are attempted to be played at once. Instead of the code I am posting a video of the program, because the code will need audio files which you do not have. Error starts at 0:40.

Thanks in advance for any advice.

1 Like

Hi @LordCacops – this video says “Video unavailable: This video is private.” Did you make it unlisted on purpose, or was this an accident?

Without access to the code it will be hard to give you any advice on what might be happening. Are you using Sound Library or Minim? Are you using a Sampler? How many sound files, what length, how many at once? Et cetera.

Hi @jeremydouglass.

Sorry about the private thing. I have made it public.

I am using Sound Library.

There are four sound files. Two are two seconds long and two are three seconds long. There are 30 boids. Everytime they go out of the map, through the borders method at the Boid class, a sound file is played. Therefore, 30 files may be played at the same time. Is this too many? How do I make the thing more efficient?

Here is the code. It won’t work without the sound files though:

import processing.sound.*;

Flock flock;

SoundFile chaA;
SoundFile chaB;
SoundFile chaC;
SoundFile chaD;
SinOsc sineA;
SinOsc sineB;

TriOsc tri;

float freqA = 400;
float freqB = 400;

float theta;

  
float xoff = 0.0;
        float nois;

void setup() {
  size(1080, 910);
  //the flock stuff
  flock = new Flock();
  // Add an initial set of boids into the system
  for (int i = 0; i < 30; i++) {
    Boid b = new Boid(width/2, height/2);
    flock.addBoid(b);
  }

  //the sound stuff
  chaA = new SoundFile(this, "chaA.wav");
  chaA.amp(0.02);
  chaB = new SoundFile(this, "chaB.wav");
  chaB.amp(0.02);
  chaC = new SoundFile(this, "chaC.wav");
  chaC.amp(0.02);
  chaD = new SoundFile(this, "chaD.wav");
  chaD.amp(0.02);

  sineA = new SinOsc(this);
  sineA.amp(0.03);  
  sineA.play();

  sineB = new SinOsc(this);
  sineB.amp(0.03);
  sineB.play();
  
  tri = new TriOsc(this);
  tri.amp(0.02);
  tri.play();
  

}

void draw() {
  background(0);
  flock.run();

  // Instructions
  fill(0);
  text("Drag the mouse to generate new boids.", 10, height-16);

  float hertzA = map(mouseY, 0, 888, 666, 20);  //dont touch this beautiful mapping!
  float hertzB = map(mouseX, 0, 620, 20, 666);  
  float hertzNois = map(nois, 0, 1, 20, 333);
  sineA.freq(hertzA);
  sineB.freq(hertzB);
  tri.freq(hertzNois);
  
      fill(#2B6403);

  //TREE 1
  stroke(255);
  // Let's pick an angle 0 to 90 degrees based on the mouse position
  float a = (mouseX / (float) width) * 90f;
  // Convert it to radians
  theta = radians(a);
  // Start the tree from the bottom of the screen
  translate(width/2, height);
  // Draw a line 120 pixels
  line(0, 0, 0, -120);
  // Move to the end of that line
  translate(0, -120);
  // Start the recursive branching!
  branch(360);
  xoff = xoff + 0.01;
  
nois = noise(xoff);


}

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

void branch(float h) {
  // Each branch will be 2/3rds the size of the previous one
  h *= 0.66;

  // All recursive functions must have an exit condition!!!!
  // Here, ours is when the length of the branch is 2 pixels or less
  if (h > 2) {
    


    pushMatrix();    // Save the current state of transformation (i.e. where are we now)
    rotate(theta);   // Rotate by theta
    line(0, 0, 0, -h*nois);  // Draw the branch
    translate(0, -h*nois); // Move to the end of the branch
    branch(h*nois);       // Ok, now call myself to draw two new branches!!
    popMatrix();     // Whenever we get back here, we "pop" in order to restore the previous matrix state

    // Repeat the same thing, only branch off to the "left" this time!
    pushMatrix();
    rotate(-theta);
    line(0, 0, 0, -h);
    translate(0, -h);
    branch2(h*nois);
    popMatrix();
  }
}

void branch2(float h) {
  // Each branch will be 2/3rds the size of the previous one
  h *= 0.66;

  // All recursive functions must have an exit condition!!!!
  // Here, ours is when the length of the branch is 2 pixels or less
  if (h > 2) {
    pushMatrix();    // Save the current state of transformation (i.e. where are we now)
    rotate(theta);   // Rotate by theta
    line(0, 0, 0, h);  // Draw the branch
    translate(0, h); // Move to the end of the branch
    branch(-h);       // Ok, now call myself to draw two new branches!!
    popMatrix();     // Whenever we get back here, we "pop" in order to restore the previous matrix state

    // Repeat the same thing, only branch off to the "left" this time!
    pushMatrix();
    rotate(-theta);
    line(0, 0, 0, h);
    translate(0, h);
    branch(-h);
    popMatrix();
  }
}

class Boid {

  PVector position;
  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);
    velocity = new PVector(random(-1, 1), random(-1, 1));
    position = new PVector(x, y);
    r = 3.0;
    maxspeed = 3;
    maxforce = 0.05;
  }

  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(map(mouseX, 0, 640, 0, 4));
    ali.mult(1.0);
    coh.mult(map(mouseY, 0, 888, 0, 4));
    // Add the force vectors to acceleration
    applyForce(sep);
    applyForce(ali);
    applyForce(coh);
  }

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

  // A method that calculates and applies a steering force towards a target
  // STEER = DESIRED MINUS VELOCITY
  PVector seek(PVector target) {
    PVector desired = PVector.sub(target, position);  // A vector pointing from the position to the target
    // Normalize desired and scale to maximum speed
    desired.normalize();
    desired.mult(maxspeed);
    // Steering = Desired minus Velocity
    desired.sub(velocity); //elimine steer. en lugar queda desired. uso un vector menos!
    desired.limit(maxforce);  // Limit to maximum steering force
    return desired;
  }


  void render() {
    // Draw a triangle rotated in the direction of velocity
    float theta = velocity.heading() + radians(90);
    stroke(0);
    pushMatrix();
    translate(position.x, position.y);
    rotate(theta);
    fill(random(255), 0, random(255));
    rect(-3*r, 2*r, r, r); //he aca un gridsito pegado al triangulo que apunta a donde el monstruo quiere 
    fill(random(255), 0, random(255));
    rect(-2*r, 2*r, r, r); // el cual sera optado como indicador del fenotipo visual del animalin.
    fill(random(255), 0, random(255));
    rect(-1*r, 2*r, r, r);
    fill(random(255), 0, random(255));
    rect(0*r, 2*r, r, r);
    fill(random(255), 0, random(255));
    rect(1*r, 2*r, r, r);
    fill(random(255), 0, random(255));
    rect(2*r, 2*r, r, r);
    fill(random(255), 0, random(255));
    rect(-3*r, 3*r, r, r);
    fill(random(255), 0, random(255));
    rect(-2*r, 3*r, r, r);
    fill(random(255), 0, random(255));
    rect(-1*r, 3*r, r, r);
    fill(random(255), 0, random(255));
    rect(0*r, 3*r, r, r);
    fill(random(255), 0, random(255));
    rect(1*r, 3*r, r, r);
    fill(random(255), 0, random(255));
    rect(2*r, 3*r, r, r);
    fill(random(255), 0, random(255));
    rect(-3*r, 4*r, r, r);
    fill(random(255), 0, random(255));
    rect(-2*r, 4*r, r, r);
    fill(random(255), 0, random(255));
    rect(-1*r, 4*r, r, r);
    fill(random(255), 0, random(255));
    rect(0*r, 4*r, r, r);
    fill(random(255), 0, random(255));
    rect(1*r, 4*r, r, r);
    fill(random(255), 0, random(255));
    rect(2*r, 4*r, r, r);
    endShape();
    popMatrix();
  }

  // Wraparound and Charango activation
  void borders() {
    float rate;
    if (position.x < -r) {
      rate = map(position.y, 0, 888, 0.25, 4);
      position.x = width+r;
      chaA.rate(rate);
      chaA.play();
    }
    if (position.y < -r) {
      rate = map(position.x, 0, 640, 0.5, 2);
      position.y = height+r;
      chaB.rate(rate);
      chaB.play();
    }
    if (position.x > width+r) {
      rate = map(position.y, 0, 888, 0.25, 4);
      position.x = -r;
      chaC.rate(rate);
      chaC.play();
    }
    if (position.y > height+r) {
      rate = map(position.y, 0, 640, 0.5, 2);
      position.y = -r;
      chaD.rate(rate);
      chaD.play();
    }
  }

  // Separation
  // Method checks for nearby boids and steers away
  PVector separate (ArrayList<Boid> boids) {
    float desiredseparation = 25.0f;
    PVector desired = 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(position, other.position);
      // 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
        PVector diff = PVector.sub(position, other.position);
        diff.normalize();
        diff.div(d);        // Weight by distance
        desired.add(diff);
        count++;            // Keep track of how many
      }
    }
    // Average -- divide by how many
    if (count > 0) {
      desired.div((float)count);
    }

    // As long as the vector is greater than 0
    if (desired.mag() > 0) {
      // Implement Reynolds: Steering = Desired - Velocity
      desired.normalize();
      desired.mult(maxspeed);
      desired.sub(velocity);
      desired.limit(maxforce);
    }
    return desired;
  }

  // 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(position, other.position);
      if ((d > 0) && (d < neighbordist)) {
        sum.add(other.velocity);
        count++;
      }
    }
    if (count > 0) {
      sum.div((float)count);
      sum.normalize();
      sum.mult(maxspeed);
      PVector desired = PVector.sub(sum, velocity);
      desired.limit(maxforce);
      return desired;
    } else {
      return new PVector(0, 0);
    }
  }

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

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);
  }

}

I have had similar issues when generating AudioSamples.
The program runs just fine.
The audio clicks and scratches.

I have found that building an executable will also have these artifacts unless I build without “Embedding Java” and use the installed JRE on my computer.
With the default runtime environment I may hear a click at the beginning and end of an AudioSample.

Unfortunately, I also lose stereo sound when running from the installed JRE.
Left audio only.
Stereo samples… panning… no luck.

Processing IDE:
3.5.4
(Also tried experimental rev 4.0a1, same results)

Installed Java:
openjdk version “1.8.0_242”
OpenJDK Runtime Environment (build 1.8.0_242-8u242-b08-0ubuntu3~16.04-b08)
OpenJDK 64-Bit Server VM (build 25.242-b08, mixed mode)

Example sketch:

import processing.sound.*;

int SAMPLES_PER_SECOND = 44100;
float LENGTH_IN_SECONDS = 0.3;
int AUDIO_LENGTH = int(SAMPLES_PER_SECOND * LENGTH_IN_SECONDS);
float FREQ = 60;
float DEFAULT_VOLUME = 1.0;
float SCL = 1.0 / SAMPLES_PER_SECOND;
AudioSample bloop, bump; //beep


float getSample(float t, float mag, float freq)
{
  float out = mag * sin(freq * TWO_PI*t);
  return out;
}

void generateAudio()
{
  float[] signal = new float[AUDIO_LENGTH*2];
  for (int i=0; i<AUDIO_LENGTH; i++)
  {
    signal[i] = getSample(SCL * i, 0.1, FREQ + 4*300);
  }
  bloop = new AudioSample(this, signal, false, SAMPLES_PER_SECOND);
  bloop.amp(DEFAULT_VOLUME);
  bloop.pan(0.0);
  
  for (int i=0; i<AUDIO_LENGTH; i++)
  {
    signal[i] = getSample(SCL * i, 0.1, FREQ + 4*142);
  }
  bump = new AudioSample(this, signal, false, SAMPLES_PER_SECOND);
  bump.amp(DEFAULT_VOLUME);
  bump.pan(0.0);
}

void mouseClicked()
{
  float rnd = random(100);
  if (rnd < 75) // play more often
  {
    if (!bump.isPlaying())
    {
      bump.play();
    }
  }
  else
  {
    if (!bloop.isPlaying())
    {
      bloop.play();
    }
  }
}

void settings()
{
  size(640, 480, P2D);
  noSmooth();
}

void setup()
{
  fill(255);
  generateAudio();
}

void draw()
{
  background(0);
  text("click me",20,20);
}

I would rather have an answer but I hope this will provide clues to someone with a better understanding of the Sound library.

1 Like

I don’t know about the causes of crackling in Sound – but for a design like this, I highly recommend using a minim Sampler object with multiple voices. It is designed for exactly this kind of playback problem (short duration, many starts and stops, potential multi-self-overlapping).

2 Likes

OpenJDK on Ubuntu has a proper PulseAudio backend that is the default for JavaSound output. Oracle JDK as shipped with Processing does not (partly a license problem). This is the likely cause of your reported issue.

Lack of stereo output sounds odd though - try (installing and) using pavucontrol while playing and see if there’s an obvious problem.

1 Like

While watching pavucontrol, I notice the following:

Running from Processing, the audio source is (seeming randomly) displayed on pavucontrol’s UI.
As long as it is displayed, the audio quality is fine, otherwise static.

If running from OpenJDK, I get mono (left) output but is stable.

Volume bars update normally.

Have you tried unchecking that padlock icon and making sure both channels are set to the same volume? That’s an odd effect I’ve never seen before - I’ve come across most of the weird ways Java audio breaks! :smile:

Good thought but all channels were set to 100%. Also checked “Output devices” tab.

Maybe try those channels one-by-one. I wonder if left and right are somehow being routed to Front Left and Front Left of Center for some reason?

No luck. I am guessing that I just have strange configuration.

I recall seeing a bug in pulseaudio with a USB headset and mono output.
While my sound card is built in, maybe there is some combination of software and drivers that are not happy…

On another note, if you will pardon the phrase: the following is an equivalent generative sketch using Minim if anyone is interested.

import ddf.minim.*;
import ddf.minim.ugens.*;
import javax.sound.sampled.*;

Minim minim;

int SAMPLES_PER_SECOND = 44100;
float LENGTH_IN_SECONDS = 0.3;
int AUDIO_LENGTH = int(SAMPLES_PER_SECOND * LENGTH_IN_SECONDS);
float DEFAULT_VOLUME = 0.1;
float SCL = 1.0 / SAMPLES_PER_SECOND;

AudioSample bloop, bump;

float getSample(float t, float mag, float freq)
{
  float out = mag * sin(freq * TWO_PI*t);
  return out;
}

void buildAudio()
{
  float[] signal = new float[AUDIO_LENGTH];
  
  AudioFormat format = new AudioFormat( SAMPLES_PER_SECOND, // sample rate
                                        16,    // sample size in bits
                                        1,     // channels
                                        true,  // signed
                                        true   // bigEndian
                                      );
  
  for(int i=0; i<signal.length; i++)
  {
     signal[i] = getSample(SCL*i, DEFAULT_VOLUME, 1260);
  }
  bloop = minim.createSample( signal, // the samples
                              format,  // the format
                              1024     // the output buffer size
                            );
  
  for(int i=0; i<signal.length; i++)
  {
     signal[i] = getSample(SCL*i, DEFAULT_VOLUME, 628);
  }
  bump = minim.createSample( signal,
                              format,
                              1024
                            );
}

void mouseClicked()
{
  float rnd = random(100);
  
  if (rnd < 75)
  {
    bump.trigger();
  }
  else
  {
    bloop.trigger();
  }
}

void setup()
{
  size(395, 200);
  minim = new Minim(this);
  buildAudio();
}

void draw()
{
  background(0);
  fill(255);
  text("click me",20,20);
}

1 Like

@noahbuddy I think the problem you are getting is due to the characteristic quality of that sound. Clean oscillators like that often click at playon and playoff. I might suggest you go into an audio editing program like Audacity and create a suitable envelope for the sample, i.e. give the audio a fade-in and a fade-out.

I don’t know about the causes of crackling in Sound – but for a design like this, I highly recommend using a minim Sampler object with multiple voices. It is designed for exactly this kind of playback problem (short duration, many starts and stops, potential multi-self-overlapping).

Where can I find a reference for the creation or implementation of that object? The only one I found is this one.

When I run it I get an error at package ddf.minim.ugens;. To be honest I don’t even know what a package is, or how to get this one or install it.

Here is the reference page and the JavaDoc:

http://code.compartmental.net/minim/sampler_class_sampler.html

http://code.compartmental.net/minim/javadoc/ddf/minim/ugens/Sampler.html

You can install minim through PDE Contributions Manager under “minim”

1 Like

Thank you very much @jeremydouglass !

1 Like

I believe I am on the right track. I have made the agents trigger sounds from sampler. To get, using minim, a working version of what I had using sound, I need two things.

1.To know how to control the volume and/or gain of the samples or samplers, so that they don’t distort when they all try to sound at the same time.

and 2. A rate or pitch control that allows me to alter the pitch of each sound, as in my original version.

Here is the code. I have removed stuff that does not come into play. You will need to add your own .wavs (or .whatevers) if you desire to run it. Thanks!



import processing.sound.*;
import ddf.minim.*;
import ddf.minim.ugens.*;

Minim       minim;
AudioOutput out;

Flock flock;

Sampler chaA;
Sampler chaB;
Sampler chaC;
Sampler chaD;

SinOsc sineA;
SinOsc sineB;

float freqA = 400;
float freqB = 400;

int bpm = 120;




class Tick implements Instrument
{
  void noteOn(float dur  )
  {
  }

  void noteOff()
  {
  }
}

float theta; 




void setup() {
  size(640, 888);
  //the flock stuff
  flock = new Flock();
  // Add an initial set of boids into the system
  for (int i = 0; i < 15; i++) {
    Boid b = new Boid(width/2, height/2);
    flock.addBoid(b);
  }

  //the sound stuff
  minim = new Minim(this);
  out   = minim.getLineOut();

  chaA  = new Sampler( "chaA.wav", 15, minim );  
  chaB = new Sampler( "chaB.wav", 15, minim );
  chaC   = new Sampler( "chaC.wav", 15, minim );
  chaD   = new Sampler( "chaC.wav", 15, minim );


  chaA.patch( out );
  chaB.patch( out );
  chaC.patch( out );
  chaD.patch( out );




  out.setTempo( bpm );
  out.playNote( random(1), random(1), new Tick() );
}

void draw() {
  background(0);
  flock.run();




  // Instructions
  fill(0);
  text("Drag the mouse to generate new boids.", 10, height-16);


}

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

void branch(float h) {
  // Each branch will be 2/3rds the size of the previous one
  h *= 0.66;

  // All recursive functions must have an exit condition!!!!
  // Here, ours is when the length of the branch is 2 pixels or less
  if (h > 2) {
    pushMatrix();    // Save the current state of transformation (i.e. where are we now)
    rotate(theta);   // Rotate by theta
    line(0, 0, 0, -h);  // Draw the branch
    translate(0, -h); // Move to the end of the branch
    branch(h);       // Ok, now call myself to draw two new branches!!
    popMatrix();     // Whenever we get back here, we "pop" in order to restore the previous matrix state

    // Repeat the same thing, only branch off to the "left" this time!
    pushMatrix();
    rotate(-theta);
    line(0, 0, 0, -h);
    translate(0, -h);
    branch(h);
    popMatrix();
  }
}


class Boid {

  PVector position;
  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);
    velocity = new PVector(random(-1,1),random(-1,1));
    position = new PVector(x,y);
    r = 3.0;
    maxspeed = 3;
    maxforce = 0.05;
  }

  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(map(mouseX,0,640,0,4));
    ali.mult(1.0);
    coh.mult(map(mouseY,0,888,0,4));
    // Add the force vectors to acceleration
    applyForce(sep);
    applyForce(ali);
    applyForce(coh);
  }

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

  // A method that calculates and applies a steering force towards a target
  // STEER = DESIRED MINUS VELOCITY
  PVector seek(PVector target) {
    PVector desired = PVector.sub(target,position);  // A vector pointing from the position to the target
    // Normalize desired and scale to maximum speed
    desired.normalize();
    desired.mult(maxspeed);
    // Steering = Desired minus Velocity
    desired.sub(velocity); //elimine steer. en lugar queda desired. uso un vector menos!
    desired.limit(maxforce);  // Limit to maximum steering force
    return desired;
  }
  
  
  void render() {
    float theta = velocity.heading() + radians(90);
    stroke(0);
    pushMatrix();
    translate(position.x,position.y);
    rotate(theta);
    fill(random(255), 0, random(255));
    rect(-3*r, 2*r, r, r); //he aca un gridsito pegado al triangulo que apunta a donde el monstruo quiere 
        fill(random(255), 0, random(255));
    rect(-2*r, 2*r, r, r); // el cual sera optado como indicador del fenotipo visual del animalin.
        fill(random(255), 0, random(255));
    rect(-1*r, 2*r, r, r);
        fill(random(255), 0, random(255));
    rect(0*r, 2*r, r, r);
        fill(random(255), 0, random(255));
    rect(1*r, 2*r, r, r);
        fill(random(255), 0, random(255));
    rect(2*r, 2*r, r, r);
        fill(random(255), 0, random(255));
    rect(-3*r, 3*r, r, r);
        fill(random(255), 0, random(255));
    rect(-2*r, 3*r, r, r);
        fill(random(255), 0, random(255));
    rect(-1*r, 3*r, r, r);
        fill(random(255), 0, random(255));
    rect(0*r, 3*r, r, r);
        fill(random(255), 0, random(255));
    rect(1*r, 3*r, r, r);
        fill(random(255), 0, random(255));
    rect(2*r, 3*r, r, r);
       fill(random(255), 0, random(255));
    rect(-3*r, 4*r, r, r);
        fill(random(255), 0, random(255));
    rect(-2*r, 4*r, r, r);
       fill(random(255), 0, random(255));
    rect(-1*r, 4*r, r, r);
        fill(random(255), 0, random(255));
    rect(0*r, 4*r, r, r);
        fill(random(255), 0, random(255));
    rect(1*r, 4*r, r, r);
        fill(random(255), 0, random(255));
    rect(2*r, 4*r, r, r);
    endShape();
    popMatrix();
  }

  // Wraparound and Charango activation
  void borders() {
    if (position.x < -r) {
      position.x = width+r;
    chaA.trigger();
  }
    if (position.y < -r) {
      position.y = height+r;
     chaB.trigger(); 
    }
    if (position.x > width+r) {
      position.x = -r;
      chaC.trigger();
    }
    if (position.y > height+r) {
      position.y = -r;
      chaD.trigger();
    }
  }

  // Separation
  // Method checks for nearby boids and steers away
  PVector separate (ArrayList<Boid> boids) {
    float desiredseparation = 25.0f;
    PVector desired = 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(position,other.position);
      // 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
        PVector diff = PVector.sub(position,other.position);
        diff.normalize();
        diff.div(d);        // Weight by distance
        desired.add(diff);
        count++;            // Keep track of how many
      }
    }
    // Average -- divide by how many
    if (count > 0) {
      desired.div((float)count);
    }

    // As long as the vector is greater than 0
    if (desired.mag() > 0) {
      // Implement Reynolds: Steering = Desired - Velocity
      desired.normalize();
      desired.mult(maxspeed);
      desired.sub(velocity);
      desired.limit(maxforce);
    }
    return desired;
  }

  // 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(position,other.position);
      if ((d > 0) && (d < neighbordist)) {
        sum.add(other.velocity);
        count++;
      }
    }
    if (count > 0) {
      sum.div((float)count);
      sum.normalize();
      sum.mult(maxspeed);
      PVector desired = PVector.sub(sum,velocity);
      desired.limit(maxforce);
      return desired;
    } else {
      return new PVector(0,0);
    }
  }

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




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 Like