Flow fields code

Hi there! I am trying to learn about flow fields a with a nature of code tutorial.

https://natureofcode.com/book/chapter-6-autonomous-agents/

This is really difficult to me, but I would like to play with code looking for a progressive understanding. I have used this Code from the web but I can not make It work, could you please tell me what is wrong? Thank you so much.

class FlowField {
  PVector[][] field;
  int cols, rows;
  int resolution;
  
  
FlowField() {
  resolution = 10;
  cols = width / resolution;
  rows = height / resolution;
  field = new PVector[cols][rows];
}
}

for(int i = 0; i < cols; i++){
  for(int j = 0; j < rows; j++){
    field[i][j] = new PVector(1,0);
  }
}
 

 
1 Like

Is that all the code? Surely there’s more to it than what you posted.

As I see on the Page, that is the Code to do this:

please note that this is only a small part of the code

full code is here:

see GitHub - nature-of-code/noc-examples-processing: Repository for example code from The Nature of Code book

please note that the examples are in folders and sub-folders and that some of the examples have three files (tabs) that belong together.

I made a small version for you:


// The Nature of Code
// Daniel Shiffman
// http://natureofcode.com

// Flow Field Following


// Flow Field Following
// Via Reynolds: http://www.red3d.com/cwr/steer/FlowFollow.html

// Flowfield object
FlowField flowfield;

void setup() {
  size(640, 360);
  // Make a new flow field 
  flowfield = new FlowField();
}

void draw() {
  background(255);

  // Display the flowfield 
  flowfield.display();
}

// =========================

class FlowField {
  PVector[][] field;
  int cols, rows;
  int resolution;


  FlowField() {
    resolution = 20;
    cols = width / resolution;
    rows = height / resolution;
    field = new PVector[cols][rows];

    for (int i = 0; i < cols; i++) {
      for (int j = 0; j < rows; j++) {
        field[i][j] = new PVector(1, 0);
      }
    }
  }//constr 

  // Draw every vector
  void display() {
    for (int i = 0; i < cols; i++) {
      for (int j = 0; j < rows; j++) {
        drawVector(field[i][j], i*resolution, j*resolution, resolution-4);
      }
    }
  }//

  // Renders a vector object 'v' as an arrow and a position 'x,y'
  void drawVector(PVector v, float x, float y, float scayl) {
    pushMatrix();
    float arrowsize = 4;
    // Translate to position to render vector
    translate(x, y);
    stroke(0, 100);
    // Call vector heading function to get direction (note that pointing to the right is a heading of 0) and rotate
    rotate(v.heading2D());
    // Calculate length of vector & scale it to be bigger or smaller if necessary
    float len = v.mag()*scayl;
    // Draw three lines to make an arrow (draw pointing up since we've rotate to the proper direction)
    line(0, 0, len, 0);
    //line(len,0,len-arrowsize,+arrowsize/2);
    //line(len,0,len-arrowsize,-arrowsize/2);
    popMatrix();
  }
}
//


The LONG version from github

I think it’s noc-examples-processing/chp06_agents/NOC_6_04_Flow_Figures at master · nature-of-code/noc-examples-processing · GitHub or so





// The Nature of Code
// Daniel Shiffman
// http://natureofcode.com

// Flow Field Following


// The Nature of Code
// Daniel Shiffman
// http://natureofcode.com

// Flow Field Following
// Via Reynolds: http://www.red3d.com/cwr/steer/FlowFollow.html

// Using this variable to decide whether to draw all the stuff
boolean debug = true;

// Flowfield object
FlowField flowfield;
// An ArrayList of vehicles
ArrayList<Vehicle> vehicles;

void setup() {
  size(640, 360);
  // Make a new flow field with "resolution" of 16
  flowfield = new FlowField(20);
  vehicles = new ArrayList<Vehicle>();
  // Make a whole bunch of vehicles with random maxspeed and maxforce values
  for (int i = 0; i < 120; i++) {
    vehicles.add(new Vehicle(new PVector(random(width), random(height)), random(2, 5), random(0.1, 0.5)));
  }
}

void draw() {
  background(255);
  // Display the flowfield in "debug" mode
  if (debug) flowfield.display();
  // Tell all the vehicles to follow the flow field
  for (Vehicle v : vehicles) {
    v.follow(flowfield);
    v.run();
  }

  // Instructions
  fill(0);
  text("Hit space bar to toggle debugging lines.\nClick the mouse to generate a new flow field.", 10, height-20);
}


void keyPressed() {
  if (key == ' ') {
    debug = !debug;
  }
}

// Make a new flowfield
void mousePressed() {
  flowfield.init();
}

//============================

// The Nature of Code
// Daniel Shiffman
// http://natureofcode.com

// Flow Field Following

class Vehicle {

  // The usual stuff
  PVector position;
  PVector velocity;
  PVector acceleration;
  float r;
  float maxforce;    // Maximum steering force
  float maxspeed;    // Maximum speed

  Vehicle(PVector l, float ms, float mf) {
    position = l.get();
    r = 3.0;
    maxspeed = ms;
    maxforce = mf;
    acceleration = new PVector(0, 0);
    velocity = new PVector(0, 0);
  }

  public void run() {
    update();
    borders();
    display();
  }


  // Implementing Reynolds' flow field following algorithm
  // http://www.red3d.com/cwr/steer/FlowFollow.html
  void follow(FlowField flow) {
    // What is the vector at that spot in the flow field?
    PVector desired = flow.lookup(position);
    // Scale it up by maxspeed
    desired.mult(maxspeed);
    // Steering is desired minus velocity
    PVector steer = PVector.sub(desired, velocity);
    steer.limit(maxforce);  // Limit to maximum steering force
    applyForce(steer);
  }

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

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

  void display() {
    // Draw a triangle rotated in the direction of velocity
    float theta = velocity.heading2D() + radians(90);
    fill(175);
    stroke(0);
    pushMatrix();
    translate(position.x, position.y);
    rotate(theta);
    beginShape(TRIANGLES);
    vertex(0, -r*2);
    vertex(-r, r*2);
    vertex(r, r*2);
    endShape();
    popMatrix();
  }

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



// =========================

class FlowField {

  // A flow field is a two dimensional array of PVectors
  PVector[][] field;
  int cols, rows; // Columns and Rows
  int resolution; // How large is each "cell" of the flow field

  FlowField(int r) {
    resolution = r;
    // Determine the number of columns and rows based on sketch's width and height
    cols = width/resolution;
    rows = height/resolution;
    field = new PVector[cols][rows];
    init();
  }

  void init() {
    // Reseed noise so we get a new flow field every time
    noiseSeed((int)random(10000));
    float xoff = 0;
    for (int i = 0; i < cols; i++) {
      float yoff = 0;
      for (int j = 0; j < rows; j++) {
        float theta = map(noise(xoff, yoff), 0, 1, 0, TWO_PI);
        // Polar to cartesian coordinate transformation to get x and y components of the vector
        field[i][j] = new PVector(cos(theta), sin(theta));
        yoff += 0.1;
      }
      xoff += 0.1;
    }
  }

  // Draw every vector
  void display() {
    for (int i = 0; i < cols; i++) {
      for (int j = 0; j < rows; j++) {
        drawVector(field[i][j], i*resolution, j*resolution, resolution-2);
      }
    }
  }

  // Renders a vector object 'v' as an arrow and a position 'x,y'
  void drawVector(PVector v, float x, float y, float scayl) {
    pushMatrix();
    float arrowsize = 4;
    // Translate to position to render vector
    translate(x, y);
    stroke(0, 100);
    // Call vector heading function to get direction (note that pointing to the right is a heading of 0) and rotate
    rotate(v.heading2D());
    // Calculate length of vector & scale it to be bigger or smaller if necessary
    float len = v.mag()*scayl;
    // Draw three lines to make an arrow (draw pointing up since we've rotate to the proper direction)
    line(0, 0, len, 0);
    //line(len,0,len-arrowsize,+arrowsize/2);
    //line(len,0,len-arrowsize,-arrowsize/2);
    popMatrix();
  }

  PVector lookup(PVector lookup) {
    int column = int(constrain(lookup.x/resolution, 0, cols-1));
    int row = int(constrain(lookup.y/resolution, 0, rows-1));
    return field[column][row].get();
  }
}

1 Like

Oh, thank you so much for your help! With this and the reference I think I can start to undestand :star_struck:

1 Like

Hi again! I have been working with small version that @Chrisir made for me so kindly, but I hardly understand it :exploding_head:
Then I tried with another tutorial from youtube and I got some results, it is still too complex for me but at least I can experiment changing some values and seeing what happens. Now, I would like to draw these lines in only some cells of the grill, not in all of them. I guess I have to use random function somewhere, but I can not imagine where. Maybe inside the loops? Could you please help me?

float inc = 0.01;
float scl =30;
int cols, rows;

void setup() {
  size (900,900);
  cols = int(width / scl);
  rows = int(height /scl);

  
  
  background(255,0,255); 
}

void draw() {
  
  float yoff = 0;
  for ( int y = 0; y<rows; y++){
    float xoff = 0;
    for(int x = 0; x<cols; x++){
      float angle = noise(xoff, yoff)*TWO_PI;
      PVector vector = new PVector(0,0).fromAngle(angle).setMag(1);
      xoff += inc;
      stroke(0);
      pushMatrix();
      translate(x*scl, y*scl);
      rotate(vector.heading());
      strokeWeight(5);
      stroke(255,255,0);
      line(0,0,scl,0);
      popMatrix();
   
      //rect(x*scl, y*scl, scl, scl);
    }
    yoff += inc;
  }
}

in this version I have a String str1 that contains which numbers shall not be displayed (forbidden numbers)

You can fill str1 with random numbers in setup()

Then an if-clause is used to check counter (the number of each vector) against the String:

if (! str1.contains ( str(counter) )) {

The ! means “not”

Full Code


float inc = 0.01;
float scl =30;
int cols, rows;

String str1 ="0,1,2,3,4,5,6,7,20,30,40,50,60," ;

void setup() {
  size (900, 900);
  cols = int(width / scl);
  rows = int(height /scl);

  background(255, 0, 255);
}

void draw() {
  background(255, 0, 255);

  int counter=0; 

  float yoff = 0;
  for ( int y = 0; y<rows; y++) {
    float xoff = 0;
    for (int x = 0; x<cols; x++) {
      float angle = noise(xoff, yoff)*TWO_PI;
      PVector vector = new PVector(0, 0).fromAngle(angle).setMag(1);
      xoff += inc;
      stroke(0);
      if (! str1.contains ( str(counter) )) {
        pushMatrix();
        translate(x*scl+33, y*scl+33);
        rotate(vector.heading());
        strokeWeight(5);
        stroke(255, 255, 0);
        line(0, 0, scl, 0);
        popMatrix();
        //rect(x*scl, y*scl, scl, scl);
      }
      counter ++;
    }//for 
    yoff += inc;
  }
}
//

Please note that in the previous more complex versions we had a 2D array
(within the class, but you can have it also outside the class) that stored
the PVector:

Similarly you can also store IF an vector exists in an boolean array or its color

thank you so much, @Chrisir ! This solution really works, but if I want to delete many vectors, for example 400, it will be so arduous to write 400 numbers. And if I type random(400) on the string, it only removes 3 vectors, so how could I eliminate 400 randoms vectors without typing 400 numbers?

float inc = 0.01;
float scl =30;
int cols, rows;

String str1 ="random(400)";

void setup() {
  size (900, 900);
  cols = int(width / scl);
  rows = int(height /scl);

  background(255, 0, 255);
}

void draw() {
  background(255, 0, 255);

  int counter=0; 

  float yoff = 0;
  for ( int y = 0; y<rows; y++) {
    float xoff = 0;
    for (int x = 0; x<cols; x++) {
      float angle = noise(xoff, yoff)*TWO_PI;
      PVector vector = new PVector(0, 0).fromAngle(angle).setMag(1);
      xoff += inc;
      stroke(0);
      if (! str1.contains ( str(counter) )) {
        pushMatrix();
        translate(x*scl+33, y*scl+33);
        rotate(vector.heading());
        strokeWeight(5);
        stroke(255, 255, 0);
        line(0, 0, scl, 0);
        popMatrix();
        //rect(x*scl, y*scl, scl, scl);
      }
      counter ++;
    }//for 
    yoff += inc;
  }
}
//

Actually, I was looking for something as you can see in this work, where some vectors have random positions, that is way I was trying to remove some vectors

https://openprocessing.org/sketch/1339552



float inc = 0.01;
float scl = 30;
int cols, rows;

String str1 ="";

void setup() {
  size (900, 900);
  cols = int(width / scl);
  rows = int(height /scl);

  for ( int i = 0; i<400; i++) { 
    // append a random number to str1
    str1 +=
      str(int(random(rows*cols)));
  }

  strokeWeight(5);
  stroke(255, 255, 0);

  background(255, 0, 255);
}

void draw() {
  background(255, 0, 255);

  int counter=0; 
  float yoff = 0;

  for ( int y = 0; y<rows; y++) {
    float xoff = 0;
    for (int x = 0; x<cols; x++) {
      float angle = noise(xoff, yoff)*TWO_PI;
      PVector vector = new PVector(0, 0).fromAngle(angle).setMag(1);
      xoff += inc;
      if (! str1.contains ( str(counter) )) {
        pushMatrix();
        translate(x*scl+10, y*scl+10);
        rotate(vector.heading());
        line(0, 0, scl, 0);
        popMatrix();
        //rect(x*scl, y*scl, scl, scl);
      }//if
      counter ++;
    }//for 
    yoff += inc;
  }//for
}
//

here is another approach.

  • We have a list of vectors that we fill in setup() and draw in draw()
float scl = 30;
ArrayList<PVector> list = new ArrayList(); 

void setup() {
  size (900, 900);

  for ( int i = 0; i<100; i++) { 
    float x=(random(width/scl));
    float y=(random(height/scl));

    float angle = noise(x, y)*TWO_PI;
    PVector vector = new PVector(0, 0).fromAngle(angle).setMag(1);
    vector.set(x*scl+10, y*scl+10); 
    list.add(vector);
  }//for

  strokeWeight(5);
  stroke(255, 255, 0);

  background(255, 0, 255);
}

void draw() {
  background(255, 0, 255);

  for (PVector pv : list) {
    pushMatrix();
    translate(pv.x, pv.y);
    rotate(pv.heading());
    line(0, 0, scl, 0);
    popMatrix();
  }
}
//

:smiling_face_with_tear:
thank you so much, @Chrisir , that is a boost for me!
now, if I want to draw another layer or vectors over the first one, as you can see in the picture. What would be the best way? I guess that magic happens in this line of code: line(0, 0, scl, 0), should I made another variable as “scl”?

float inc = 0.01;
float scl = 30;
int cols, rows;

String str1 ="";

void setup() {
  size (900, 900);
  cols = int(width / scl);
  rows = int(height /scl);

  for ( int i = 0; i<400; i++) { 
    // append a random number to str1
    str1 +=
      str(int(random(rows*cols)));
  }

  

  background(255, 0, 255);
}

void draw() {
  background(255, 0, 255);

  int counter=0; 
  float yoff = 0;

  for ( int y = 0; y<rows; y++) {
    float xoff = 0;
    for (int x = 0; x<cols; x++) {
      float angle = noise(xoff, yoff)*TWO_PI;
      PVector vector = new PVector(0, 0).fromAngle(angle).setMag(1);
      xoff += inc;
      if (! str1.contains ( str(counter) )) {
        pushMatrix();
        translate(x*scl+10, y*scl+10);
        rotate(vector.heading());
        strokeWeight(5);
        stroke(255, 255, 0);
        line(0, 0, scl, 0);
        strokeWeight(2);
        stroke(0,255,0);
        line(0, 0, scl, 0);
        popMatrix();
        
      }//if
      counter ++;
    }//for 
    yoff += inc;
  }//for
}
//

I will study your second approach carefully

you need to fully understand the code first (or half of it)

different possibilities here.

The easiest: copy stuff:

after drawing list you want to draw list2 on top of it

First

just make a 2nd line here:

ArrayList<PVector> list2 = new ArrayList(); 

Now

Now fill list2

you need to copy the entire for loop in setup and fill list2 as well

  for ( int i = 0; i<100; i++) { 
    float x=(random(width/scl));
    float y=(random(height/scl));

    float angle = noise(x, y)*TWO_PI;
    PVector vector = new PVector(0, 0).fromAngle(angle).setMag(1);
    vector.set(x*scl+10, y*scl+10); 
    list2.add(vector); //     list2 !!!!
  }//for

OR change it (twice when you copied it)

  for ( int i = 0; i<100; i++) { 
    float x=(random(-60,60));
    float y=(random(-60,60));

    float angle = noise(x, y)*TWO_PI;
    PVector vector = new PVector(0, 0).fromAngle(angle).setMag(1);
    vector.set(x+width/2, y+height/2); 
    list2.add(vector); //     list2 !!!!
  }//for

Now

and copy the output in draw()

void draw() {
  background(255, 0, 255);


  strokeWeight(5);
  stroke(255, 255, 0);

  for (PVector pv : list) {
    pushMatrix();
    translate(pv.x, pv.y);
    rotate(pv.heading());
    line(0, 0, scl, 0);
    popMatrix();
  }


  strokeWeight(5);
  stroke(0, 255, 255);

  for (PVector pv : list2) {  // list2 !!!!!!!!!!!!!!!!!!!!!!!!!
    pushMatrix();
    translate(pv.x, pv.y);
    rotate(pv.heading());
    line(0, 0, scl, 0);
    popMatrix();
  }
}

Full Code


ArrayList<PVector> list = new ArrayList(); 
ArrayList<PVector> list2 = new ArrayList(); 

float scl = 30;

void setup() {

  size (900, 900);

  //  noiseSeed(int(random(110)));

  for ( int i = 0; i<120; i++) { 
    float x=(random(-160, 160));
    float y=(random(-160, 160));

    float angle = noise(x*100, y*10)*TWO_PI;
    PVector vector = new PVector(0, 0);//.fromAngle(angle);//.setMag(1);
    vector.rotate( angle );
    vector.set(x+width/2, y+height/2); 

    list.add(vector); //     list
  }//for

  noiseSeed(int(random(110)));

  for ( int i = 0; i<80; i++) { 
    float x=(random(-100, 100));
    float y=(random(-100, 100));

    float angle = noise(x, y)*TWO_PI;
    PVector vector = new PVector(0, 0).fromAngle(angle).setMag(1);
    vector.set(x+width/2, y+height/2); 
    list2.add(vector); //     list2 !!!!
  }//for
}

void draw() {
  background(255, 0, 255);

  strokeWeight(5);
  stroke(255, 255, 0);

  for (PVector pv : list) {
    pushMatrix();
    translate(pv.x, pv.y);
    rotate(pv.heading());
    line(0, 0, scl, 0);
    popMatrix();
  }

  //-----------------------------------------------------
  // for list2

  strokeWeight(9);
  stroke(0, 255, 255);

  if (! keyPressed) 
    for (PVector pv : list2) {  // list2 !!!!!!!!!!!!!!!!!!!!!!!!!
      pushMatrix();
      translate(pv.x, pv.y);
      rotate(pv.heading());
      line(0, 0, scl, 0);
      popMatrix();
    }
}

:sweat_smile: :sweat_smile: :sweat_smile:

I was trying to intuit first version because second one is even more complex for me now.

I have made something similar with first code, but why the string does not display vectors in the same way on second layer?

float inc = 0.01;
float scl = 30;
int cols, rows;

String str1 ="";

void setup() {
  size (900, 900);
  cols = int(width / scl);
  rows = int(height /scl);

  for ( int i = 0; i<400; i++) { 
    // append a random number to str1
    str1 +=
      str(int(random(rows*cols)));
  }

  

  background(255, 0, 255);
}

void draw() {
  background(255, 0, 255);

  int counter=0; 
  float yoff = 0;

  for ( int y = 0; y<rows; y++) {
    float xoff = 0;
    for (int x = 0; x<cols; x++) {
      float angle = noise(xoff, yoff)*TWO_PI;
      PVector vector = new PVector(0, 0).fromAngle(angle).setMag(1);
      xoff += inc;
      if (! str1.contains ( str(counter) )) {
        pushMatrix();
        translate(x*scl+10, y*scl+10);
        rotate(vector.heading());
        strokeWeight(5);
        stroke(255, 255, 0);
        line(0, 0, scl, 0);
        popMatrix();
                  
      }
      counter ++;
  


      if (! str1.contains ( str(counter) )) {
        pushMatrix();
        translate(x*scl+10, y*scl+10);
        rotate(vector.heading());
        strokeWeight(5);
        stroke(0, 255,255);
        line(0, 0, scl, 0);
        popMatrix();
          
      }
      counter ++;
    }
    yoff += inc;
  }
  
}
//

I am not sure you understand what you are doing here.

  • First str1 contains the numbers that are NOT displayed.

  • 2nd you use the same string for both groups of vectors (2 different colors)

  • 3rd you say counter ++; twice, so this doesn’t make sense

  • 4th when you draw one line and then the next in the same position, the 2nd line will cover the first. Bad.


Solution

Here is a code that addresses some of the issues:

It uses str1 and str 2 now.

Both contain numbers that ARE displayed now. (No ! in the code)

We have two separated nested for-loops now for str1 and for str2.


float inc = 0.01;
float scl = 30;
int cols, rows;

String str1 ="";
String str2 =""; //!!!!!!!!!!!!!!!!!!!!!!

void setup() {
  size (900, 900);
  cols = int(width / scl);
  rows = int(height /scl);

  for ( int i = 0; i<100; i++) { 
    // append a random number to str1
    str1 +=
      str(int(random(rows*cols)));
  }

  for ( int i = 0; i<40; i++) { 
    // append a random number to str2
    str2 +=
      str(int(random(rows*cols)));
  }

  background(255, 0, 255);
}

void draw() {
  background(255, 0, 255);

  int counter=0; 
  float yoff = 0;

  for ( int y = 0; y<rows; y++) {
    float xoff = 0;
    for (int x = 0; x<cols; x++) {
      float angle = noise(xoff, yoff)*TWO_PI;
      PVector vector = new PVector(0, 0).fromAngle(angle).setMag(1);
      xoff += inc;
      if ( str1.contains ( str(counter) )) {
        pushMatrix();
        translate(x*scl+10, y*scl+10);
        rotate(vector.heading());
        strokeWeight(5);
        stroke(255, 255, 0);
        line(0, 0, scl, 0);
        popMatrix();
      }
      counter ++;
    }
  }

  // -----------------------------------------------------------------

  counter=0; 
  yoff = 0;

  for ( int y = 0; y<rows; y++) {
    float xoff = 0;
    for (int x = 0; x<cols; x++) {
      float angle = noise(xoff, yoff)*TWO_PI;
      PVector vector = new PVector(0, 0).fromAngle(angle).setMag(1);
      xoff += inc;

      if ( str2.contains ( str(counter) )) {
        pushMatrix();
        translate(x*scl+16, y*scl+16);
        rotate(vector.heading());
        strokeWeight(9);
        stroke(0, 255, 255);
        line(0, 0, scl, 0);
        popMatrix();
      }
      counter ++;
    }
    yoff += inc;
  }
  //
  // -----------------------------------------------------------------
  //
}
//