Schlagwort-Archive: flocking

Die Geburt der Sonne


Processing 2.0

Hierbei handelt es sich um eine Kombination der Techniken Additive Blending und Flocking. Es werden Partikel erzeugt, die sich dann in der Mitte verdichten.

Der Sketch wäre vielleicht in Processing 2.x auch mit anderen Techniken zu realisieren. Ich habe ihn aber nur von der Version 1.5 portiert.

/** Copyright 2014 Thomas Koberger
 */
// based on a flocking algorithm by Daniel Shiffman
// https://lernprocessing.wordpress.com/
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

import processing.opengl.*;
import peasy.*;
import javax.media.opengl.*;
import javax.media.opengl.GL2;
import java.util.*;

// Flock
Flock flock;
Stars stars;

GL2 gl; 
PGraphicsOpenGL pgl;

PVector l[];
float str;

void setup() {
 size(1280, 720, OPENGL);

 // Create Flock
 flock = new Flock();
 stars = new Stars(400);

 for (int x = 0; x < 350; x+=1) {
 flock.addBoid(new Boid(new PVector(random(-500, 500), random(-500, 500)), random(5.0, 2), 0.5, 10000));
 Boid b = (Boid) flock.boids.get(flock.boids.size()-1);
 b.desiredseparation=random(3, 20);
 }

 for (int x = 0; x < 15; x+=1) {
 flock.addBoid(new Boid(new PVector(random(-500, 500), random(-500, 500)), random(29.0, 2), 0.5, 10000));
 Boid b = (Boid) flock.boids.get(flock.boids.size()-1);
 b.desiredseparation=random(20, 50);
 }
}

void draw() {
 hint(DISABLE_DEPTH_TEST);
 fill(0, 15);
 rect(-width, -height, width*2, height*2);
 translate(width/2, height/2, 300);

 pgl = (PGraphicsOpenGL) g; // g may change
 gl = ((PJOGL)beginPGL()).gl.getGL2();

 gl.glEnable( GL.GL_BLEND ); 
 gl.glEnable(GL.GL_LINE_SMOOTH); 

 // This fixes the overlap issue
 gl.glDisable(GL.GL_DEPTH_TEST);

 // Define the blend mode
 gl.glBlendFunc(GL.GL_SRC_ALPHA, GL.GL_ONE);

 stars.drawStars(gl);
 flock.run(gl);

 gl.glDisable(GL.GL_BLEND);
 endPGL();
 if (frameCount%100==1) println("Rate: "+frameRate);
 //saveFrame("line-####.jpg");
}

void keyReleased() {
 //if (key == DELETE || key == BACKSPACE) background(360);
 if (key == 's' || key == 'S') saveFrame(timestamp()+"_##.jpg");
} 

// timestamp
String timestamp() {
 Calendar now = Calendar.getInstance();
 println("Frame saved");
 return String.format("%1$ty%1$tm%1$td_%1$tH%1$tM%1$tS", now);
}
// The Boid class

class Boid {

 PVector loc;
 PVector vel;
 PVector acc;

 float maxforce; // Maximum steering force
 float maxspeed; // Maximum speed
 float maxVertspeed; // Maximum speed vertical
 float maxVertforce; // Maximum speed vertical
 int lifeTime;

 float desiredseparation;// Distance to separate from neighbours
 float neighbordistAlgn; // Distance to align with neighbours
 float neighbordist; // Distance to stick to neighbours
 float desiredAvoidDist; // Distance to avoid Avoid Hunters

 float r, g, b, alpha;

 Boid(PVector l, float ms, float mf, int lt) {
 acc = new PVector(0, 0, 0 );
 vel = new PVector(0, 0, 0);
 loc = l.get();
 r = 2.0;
 maxspeed = ms;
 maxforce = mf;
 lifeTime= lt;
 maxVertspeed=ms*3;

 desiredseparation = 30.0;
 neighbordistAlgn = 15.0;
 neighbordist = 40.0;
 desiredAvoidDist = 300;
 }

 void run(ArrayList boids, GL2 gl) {
 flock(boids, gl);
 update();
 render(gl);
 lifeTime-=1;
 }

 // We accumulate a new acceleration each time based on three rules
 void flock(ArrayList boids, GL2 gl) {
 PVector sep = separate(boids); // Separation
 PVector ali = align(boids); // Alignment
 PVector coh = cohesion(boids, gl); // Cohesion
 PVector target = target(); // Food
 // Arbitrarily weight these forces
 sep.mult(2);
 ali.mult(0.5);
 coh.mult(1.0);
 target.mult(1.0);
 // Add the force vectors to acceleration
 acc.add(sep);
 acc.add(ali);
 acc.add(coh);
 acc.add(target);
 }

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

 void render(GL2 gl) {
 PVector modelOrientation = new PVector(0, 0, 1); 
 PVector heading=new PVector(vel.x, vel.y, vel.z);
 heading.mult(2);

 if (PVector.dist(loc, new PVector(0, 0, 0))>70) {
 int lines=5;
 gl.glBlendFunc(GL.GL_SRC_ALPHA, GL.GL_ONE);

 for (int i=lines;i>0;i-=4) {
 gl.glLineWidth(i);
 gl.glColor4f(float(1-i/lines), 0.5-i/lines, 0.2+i/lines, 
 alpha/i);
 gl.glBegin(GL.GL_LINES); 
 gl.glVertex2f(loc.x-heading.x, loc.y-heading.y);
 gl.glVertex2f(loc.x, loc.y);
 gl.glEnd();
 }
 }
 }

 void seek(PVector target) {
 acc.add(steer(target, false));
 }

 void arrive(PVector target) {
 acc.add(steer(target, true));
 }

 // A method that calculates a steering vector towards a target
 // Takes a second argument, if true, it slows down as it approaches the target
 PVector steer(PVector target, boolean slowdown) {
 PVector steer; // The steering vector
 PVector desired = target.sub(target, loc); // A vector pointing from the location to the target
 float d = desired.mag(); // Distance from the target is the magnitude of the vector
 // If the distance is greater than 0, calc steering (otherwise return zero vector)
 if (d > 0) {
 // Normalize desired
 desired.normalize();
 // Two options for desired vector magnitude (1 -- based on distance, 2 -- maxspeed)
 if ((slowdown) && (d < 100.0)) desired.mult(maxspeed*(d/100.0)); // This damping is somewhat arbitrary
 else desired.mult(maxspeed);
 // Steering = Desired minus Velocity
 steer = target.sub(desired, vel);
 steer.limit(maxforce); // Limit to maximum steering force
 } 
 else {
 steer = new PVector(0, 0, 0);
 }
 return steer;
 }

 // Separation
 // Method checks for nearby boids and steers away
 PVector separate (ArrayList boids) {
 PVector steer = new PVector(0, 0, 0);
 int count = 0;
 // For every boid in the system, check if it's too close
 for (int i = 0 ; i < boids.size(); i++) {
 Boid other = (Boid) boids.get(i);
 float d = PVector.dist(loc, other.loc);

 //verändert, damit der Scwarm besser zusammenhält
 // If the distance is greater than 0 and less than an arbitrary amount (0 when you are yourself)
 if ((d > 0) && (d < desiredseparation/3)) {
 // Calculate vector pointing away from neighbor
 PVector diff = PVector.sub(loc, other.loc);
 diff.normalize();
 diff.div(d*10); // Weight by distance
 steer.add(diff);
 count++; // Keep track of how many
 }

 if ((d > 0) && (d < desiredseparation)) {
 // Calculate vector pointing away from neighbor
 PVector diff = PVector.sub(loc, other.loc);
 diff.normalize();
 diff.div(d/16); // 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) {
 // Implement Reynolds: Steering = Desired - Velocity
 steer.normalize();
 steer.mult(maxspeed);
 steer.sub(vel);
 steer.limit(maxforce);
 }
 return steer;
 }

 // Alignment
 // For every nearby boid in the system, calculate the average velocity
 PVector align (ArrayList boids) {
 PVector steer = new PVector(0, 0, 0);
 int count = 0;
 for (int i = 0 ; i < boids.size(); i++) {
 Boid other = (Boid) boids.get(i);
 float d = PVector.dist(loc, other.loc);
 if ((d > 0) && (d < neighbordistAlgn)) {
 steer.add(other.vel);
 count++;
 }
 }
 if (count > 0) {
 steer.div((float)count);
 }
 // As long as the vector is greater than 0
 if (steer.mag() > 0) {
 // Implement Reynolds: Steering = Desired - Velocity
 steer.normalize();
 steer.mult(maxspeed);
 steer.sub(vel);
 steer.limit(maxforce);
 }
 return steer;
 }

 // Cohesion
 // For the average location (i.e. center) of all nearby boids, calculate steering vector towards that location
 PVector cohesion (ArrayList boids, GL2 gl) {
 PVector sum = new PVector(0, 0, 0); // Start with empty vector to accumulate all locations
 int count = 0;

 gl.glEnable( GL.GL_BLEND ); 
 gl.glColor4f(0.95, 0.3, 0.2, 0.007);
 gl.glLineWidth(6);
 gl.glBegin(GL2.GL_POLYGON); 
 gl.glVertex2f(loc.x, loc.y);
 for (int i = 0 ; i < boids.size(); i++) {
 Boid other = (Boid) boids.get(i);
 float d = loc.dist(other.loc); 

 if ((d > 0) && (d < neighbordist)) {
 sum.add(other.loc); // Add location
 count++;

 gl.glVertex2f(other.loc.x, other.loc.y);
 }
 }
 gl.glDisable( GL.GL_BLEND );
 gl.glEnd();

 // für Farbverdichtungen
 alpha = map(count, 0, 50, 0, 0.9);

 if (count > 0) {
 sum.div((float)count);
 return steer(sum, true); // Steer towards the location
 }
 return sum;
 }

 // Move Towards Target
 PVector target () {
 PVector sum = new PVector(0, 0, 0); // Start with empty vector to accumulate all locations
 //sum.limit(maxforce);
 return steer(sum, true); // Steer towards the location
 }

 boolean alive() {
 if (lifeTime<0) return false;
 else return true;
 }
}

// The Flock (a list of Boid objects)

class Flock {
 ArrayList boids; // An arraylist for all the boids

 Flock() {
 boids = new ArrayList(); // Initialize the arraylist
 }

 void run(ArrayList hunters, GL gl) {
 for (int i = 0; i < boids.size(); i++) {
 Boid b = (Boid) boids.get(i);
 }
 }
 void run(GL2 gl) {

 for (int i = 0; i < boids.size(); i++) {
 Boid b = (Boid) boids.get(i); 

 b.run(boids, gl); // Passing the entire list of boids to each boid individually

 if (!b.alive()) boids.remove(i);
 }
 }


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

// The Boid class

class Stars {

 PVector [] stars; 

 Stars(int amt) {

 stars = new PVector [amt];
 
 for (int i=0; i < amt; i++) {
 stars[i] = new PVector (random(-width/2, width/2), random(-height/2, height/2), 0);
 }
 }

 void drawStars(GL2 gl) {
 for (int i=0; i<stars.length;i++) {
 if(frameCount%5==0){
 gl.glColor4f(1, 1, 1, random(0.02, 0.2));
 float w=random(0.3, 1.2);
 gl.glLineWidth(w*2);
 gl.glBegin(GL.GL_LINES); 
 gl.glVertex3f(stars[i].x-w/2, stars[i].y, stars[i].z);
 gl.glVertex3f(stars[i].x+w/2, stars[i].y, stars[i].z);
 gl.glVertex3f(stars[i].x, stars[i].y-w/2, stars[i].z);
 gl.glVertex3f(stars[i].x, stars[i].y+w/2, stars[i].z);
 gl.glEnd();
 }
 }
 }
}


 

Advertisements

Polarlichter


Processing 2.0

Hierbei handelt es sich um eine Kombination der Techniken Additive Blending und Flocking. Es werden an zufälligen Koordinaten Partikelschwärme erzeugt, deren Partikel dann mit Linien verbunden werden. Diese werden dann additiv übereinander geblendet und ergeben farbliche Verdichtungen, die mich an Polarlichter erinnern. Außerdem werden im Hintergrund Sterne gezeichnet.

Der Sketch wäre vielleicht in Processing 2.x auch mit anderen Techniken zu realisieren. Ich habe ihn aber nur von der Version 1.5 portiert.

/** Copyright 2014 Thomas Koberger
 */
// based on a flocking algorithm by Daniel Shiffman
// https://lernprocessing.wordpress.com/
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

import processing.opengl.*;
import javax.media.opengl.*;
import javax.media.opengl.GL2;
import java.util.*;

Flock flock;
Stars stars;

//Über diese Objekte kann man auf OPENGL features zugreifen
GL2 gl;
PGraphicsOpenGL pgl;

PVector l[];
float str;

void setup() {
 size(1280, 720, OPENGL);

 //Sterne und Schwarm erzeugen
 flock = new Flock();
 stars = new Stars(350);
}

void draw() {
 //Verhindert, dass Objekte am Schirm, die von anderen verdeckt werden nicht gezeichnet werden
 hint(DISABLE_DEPTH_TEST);
 fill(0, 20);
 rect(-width, -height, width*2, height*2);
 translate (width/2, height/2, -200);

 // OpenGL Object Setup
 pgl = (PGraphicsOpenGL) g; // g may change
 gl = ((PJOGL)beginPGL()).gl.getGL2();
 gl.glEnable( GL.GL_BLEND );
 gl.glEnable(GL.GL_LINE_SMOOTH); 

 // This fixes the overlap issue
 gl.glDisable(GL.GL_DEPTH_TEST);

 // Define the blend mode
 gl.glBlendFunc(GL.GL_SRC_ALPHA, GL.GL_ONE);

 //zeichne Sterne
 stars.drawStars(gl);

 if (frameCount%6==0) {
 //Add an initial set of boids into the system
 float x=random(-width/1.3, width/1.3);
 float y=random(-height/1.3, height/1.3);
 for (int i =(int) random(5,25); i > 0; i-=1) {
 flock.addBoid(new Boid(new PVector(x, y, 0), 10.0, 0.1, 300));
 }
 } 

 flock.run(gl);
 gl.glDisable(GL.GL_BLEND);
 endPGL();
 if (frameCount%100==1) println("Rate: "+frameRate);

 //einkommentieren, wenn man die Frames speichern will
 //saveFrame(timestamp()+"_##.jpg");
}

void mousePressed() {
 //fügt neue Boids hinzu
 if ( mouseButton==LEFT) {
 for (int x = 0; x < 30; x+=1) {
 flock.addBoid(new Boid(new PVector(mouseX-width*2/3, mouseY-height*2/3), 10.0, 0.1, 500));
 }
 }
}

void keyReleased() {
 //if (key == DELETE || key == BACKSPACE) background(360);
 if (key == 's' || key == 'S') saveFrame(timestamp()+"_##.jpg");
} 

// timestamp
String timestamp() {
 Calendar now = Calendar.getInstance();
 println("Frame saved");
 return String.format("%1$ty%1$tm%1$td_%1$tH%1$tM%1$tS", now);
}

// The Boid class
// Original by Danial Shiffman modified by Thomas Koberger

class Boid {

 PVector loc;
 PVector vel;
 PVector acc;
 //float r;
 float maxforce; // Maximum steering force
 float maxspeed; // Maximum speed
 float maxVertspeed; // Maximum speed vertical
 float maxVertforce; // Maximum speed vertical
 int lifeTime;

 float desiredseparation;// Distance to separate from neighbours
 float neighbordistAlgn; // Distance to align with neighbours
 float neighbordist; // Distance to stick to neighbours
 float desiredAvoidDist; // Distance to avoid Avoid Hunters

 float r, g, b, alpha; 

 Boid(PVector l, float ms, float mf, int lt) {
 acc = new PVector(0, 0, 0 );
 vel = new PVector(0, 0, 0);
 loc = l.get();
 r = 2.0;
 maxspeed = ms;
 maxforce = mf;

 //definiert eine Lebensspanne für die einzelnen Boids
 lifeTime= lt;

 //definiert die Abstände, innerhalb derer sich die einzelnen Boids gegenseitig beeinflussen
 maxVertspeed=ms*3;
 desiredseparation = 8.0;
 neighbordistAlgn = 100.0;
 neighbordist = 60.0;
 }

 void run(ArrayList boids, GL2 gl) {
 flock(boids, gl);
 update();
 //borders();
 render(gl);
 lifeTime-=1;
 }

 // We accumulate a new acceleration each time based on three rules
 void flock(ArrayList boids, GL2 gl) {
 PVector sep = separate(boids); // Separation
 PVector ali = align(boids); // Alignment
 PVector coh = cohesion(boids, gl); // Cohesion
 PVector target = target(); // Food
 // Arbitrarily weight these forces
 sep.mult(2);
 ali.mult(1.0);
 coh.mult(0.1);
 target.mult(0.6);
 // Add the force vectors to acceleration
 acc.add(sep);
 acc.add(ali);
 acc.add(coh);
 acc.add(target);
 }

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

 //Zeichne die Boids
 void render(GL2 gl) {
 PVector modelOrientation = new PVector(0, 0, 1);
 PVector heading=new PVector(vel.x, vel.y, vel.z);
 heading.mult(2);

 int lines=1;
 gl.glBlendFunc(GL.GL_SRC_ALPHA, GL.GL_ONE);
 for (int i=lines;i>0;i-=4) {
 gl.glLineWidth(i);
 gl.glColor4f(1-alpha*i/lines, 0.5-alpha*i/lines, alpha*i/lines,
 alpha/8);
 gl.glBegin(GL.GL_LINES);
 gl.glVertex2f(loc.x-heading.x, loc.y-heading.y);
 gl.glVertex2f(loc.x, loc.y);
 gl.glEnd();
 }
 }

 void seek(PVector target) {
 acc.add(steer(target, false));
 }

 void arrive(PVector target) {
 acc.add(steer(target, true));
 }

 // A method that calculates a steering vector towards a target
 // Takes a second argument, if true, it slows down as it approaches the target
 PVector steer(PVector target, boolean slowdown) {
 PVector steer; // The steering vector
 PVector desired = target.sub(target, loc); // A vector pointing from the location to the target
 float d = desired.mag(); // Distance from the target is the magnitude of the vector
 // If the distance is greater than 0, calc steering (otherwise return zero vector)
 if (d > 0) {
 // Normalize desired
 desired.normalize();
 // Two options for desired vector magnitude (1 -- based on distance, 2 -- maxspeed)
 if ((slowdown) && (d < 100.0)) desired.mult(maxspeed*(d/100.0)); // This damping is somewhat arbitrary
 else desired.mult(maxspeed);
 // Steering = Desired minus Velocity
 steer = target.sub(desired, vel);
 steer.limit(maxforce); // Limit to maximum steering force
 }
 else {
 steer = new PVector(0, 0, 0);
 }
 return steer;
 }

 // Separation
 // Method checks for nearby boids and steers away
 PVector separate (ArrayList boids) {
 PVector steer = new PVector(0, 0, 0);
 int count = 0;
 // For every boid in the system, check if it's too close
 for (int i = 0 ; i < boids.size(); i++) {
 Boid other = (Boid) boids.get(i);
 float d = PVector.dist(loc, other.loc);

 //verändert, damit der Scwarm besser zusammenhält
 // If the distance is greater than 0 and less than an arbitrary amount (0 when you are yourself)
 if ((d > 0) && (d < desiredseparation/3)) {
 // Calculate vector pointing away from neighbor
 PVector diff = PVector.sub(loc, other.loc);
 diff.normalize();
 diff.div(d*10); // Weight by distance
 steer.add(diff);
 count++; // Keep track of how many
 }

 if ((d > 0) && (d < desiredseparation)) {
 // Calculate vector pointing away from neighbor
 PVector diff = PVector.sub(loc, other.loc);
 diff.normalize();
 diff.div(d/16); // 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) {
 // Implement Reynolds: Steering = Desired - Velocity
 steer.normalize();
 steer.mult(maxspeed);
 steer.sub(vel);
 steer.limit(maxforce);
 }
 return steer;
 }

 // Alignment
 // For every nearby boid in the system, calculate the average velocity
 PVector align (ArrayList boids) {
 PVector steer = new PVector(0, 0, 0);
 int count = 0;
 for (int i = 0 ; i < boids.size(); i++) {
 Boid other = (Boid) boids.get(i);
 float d = PVector.dist(loc, other.loc);
 if ((d > 0) && (d < neighbordistAlgn)) {
 steer.add(other.vel);
 count++;
 }
 }
 if (count > 0) {
 steer.div((float)count);
 }
 //definiert den Rot Wert
 r=map(steer.mag(), 0, 10, 0, 0.9);
 // As long as the vector is greater than 0
 if (steer.mag() > 0) {
 // Implement Reynolds: Steering = Desired - Velocity
 steer.normalize();
 steer.mult(maxspeed);
 steer.sub(vel);
 steer.limit(maxforce);
 }
 return steer;
 }

 // Cohesion
 // For the average location (i.e. center) of all nearby boids, calculate steering vector towards that location
 PVector cohesion (ArrayList boids, GL2 gl) {
 PVector sum = new PVector(0, 0, 0); // Start with empty vector to accumulate all locations
 int count = 0;

 // Define the blend mode
 gl.glEnable( GL.GL_BLEND );
 gl.glColor4f(r, g, b, 0.004);
 gl.glLineWidth(8);
 gl.glBegin(GL2.GL_POLYGON);
 gl.glVertex2f(loc.x, loc.y);
 for (int i = 0 ; i < boids.size(); i++) {
 Boid other = (Boid) boids.get(i);
 float d = loc.dist(other.loc);

 //definiert den Blau und Grün Wert
 b=map(d, 0, neighbordist*12, 0, 0.9);
 g=map(vel.mag(), 0, 10, 0, 0.9);

 if ((d > 0) && (d < neighbordist)) {
 sum.add(other.loc); // Add location
 count++;

 gl.glVertex2f(other.loc.x, other.loc.y);
 }
 }
 gl.glEnd();

 // für Farbverdichtungen
 alpha = map(count, 0, 50, 0, 1);

 if (count > 0) {
 sum.div((float)count);
 return steer(sum, true); // Steer towards the location
 }
 return sum;
 }

 // Move Towards Target
 PVector target () {
 PVector sum = new PVector(0, 0, 0); // Start with empty vector to accumulate all locations
 return steer(sum, true); // Steer towards the location
 }

 boolean alive() {
 if (lifeTime<0) return false;
 else return true;
 }
}

// The Flock (a list of Boid objects)

class Flock {
 ArrayList boids; // An arraylist for all the boids

 Flock() {
 boids = new ArrayList(); // Initialize the arraylist
 }

 void run(ArrayList hunters) {
 for (int i = 0; i < boids.size(); i++) {
 Boid b = (Boid) boids.get(i);
 }
 }
 void run(GL2 gl) {
 for (int i = 0; i < boids.size(); i++) {
 Boid b = (Boid) boids.get(i);
 b.run(boids, gl); // Passing the entire list of boids to each boid individually

 //Elimiert Boids, wenn sie den sichbaren bereich verlassen
 if (!b.alive() || b.loc.x>1200 || b.loc.x<-1200 || b.loc.y>1200 || b.loc.y<-1200) {
 boids.remove(i);
 }
 }
 }

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

// The Boid class

class Stars {

 PVector [] stars; 

 Stars(int amt) {

 stars = new PVector [amt];

 for (int i=0; i < amt; i++) {
 stars[i] = new PVector (random(-width, width), random(-height, height), 0);
 }
 }

 void drawStars(GL2 gl) {
 for (int i=0; i<stars.length;i++) {
 if(frameCount%5==0){
 gl.glColor4f(1, 1, 1, random(0.02, 0.2));
 float w=random(0.3, 1.2);
 gl.glLineWidth(w*2);
 gl.glBegin(GL.GL_LINES);
 gl.glVertex3f(stars[i].x-w/2, stars[i].y, stars[i].z);
 gl.glVertex3f(stars[i].x+w/2, stars[i].y, stars[i].z);
 gl.glVertex3f(stars[i].x, stars[i].y-w/2, stars[i].z);
 gl.glVertex3f(stars[i].x, stars[i].y+w/2, stars[i].z);
 gl.glEnd();
 }
 }
 }
}

 

The Hunt


Processing 2.0

Für dieses Projekt habe ich den Flocking Algorithmus von Daniel Shiffman um eine Dimension erweitert um damit eine 3 dimensionale Szene erzeugen zu können. Darin gibt es Schwarmfische und Haie.

  • Die Schwarmfische bewegen sich nach den Regeln aus dem Flocking Artikel und 2 zusätzlichen Regeln. Sie bewegen sich immer zum Ursprung des Koordinatensystems und weichen den Haien aus.
  • Die Haie bewegen sich nach einem reduzierten Satz von Regeln. Sie halten einen bestimmten Abstand zueinander und sie bewegen sich in Richtung der durchschnittlichen Position der Schwarmfische in ihrer Nähe.

Die 3D Modelle der Fische stammen von http://www.turbosquid.com/ . Ich habe dann die Szene noch entsprechend ausgeleuchtet (–> siehe Artikel 3D Oberflächen und Licht).

Download Source

Flocking


Processing 2.0

Mit Flocking Algorithmen lassen sich sehr imposante Graphiken und Animationen erstellen. Flocking Algorithmen versuchen das Verhalten von Tieren in Schwärmen nachzubilden.

Dafür erstellt man eine Klasse, die ein Individuum repräsentiert, das sich in seinen Bewegungen an den, in der Nähe befindlichen Individuen orientiert. Dabei folgt jedes Individuum einigen einfachen Regeln.

In einer einfachen Implementierung von Daniel Shiffman auf http://processing.org/learning/topics/flocking.html sind das folgende:

  1. Separation (Aufteilung); wähle eine Richtung, die einer Häufung von Individuen entgegenwirkt.
    2 Individuen dürfen sich nicht am selben Ort befinden. Deshalb müssen sie einander ausweichen, wenn sie einen bestimmten Abstand unterschreiten.
  2. Alignment (Angleichung): wähle eine Richtung, die der mittleren Richtung der benachbarten Individuen entspricht.
    Jedes Individuum richtet seine Bewegungsrichtung nach den Nachbarn aus. D.h. es wird eine durchschnittl. Bewegungsrichtung der, innerhalb eines bestimmten Abstands befindlichen Individuen errechnet. Die eigenen Bewegungsrichtung passt sich dieser an.
  3. Cohesion (Zusammenhalt): wähle eine Richtung, die der mittleren Position der benachbarten Individuen entspricht.
    Alle Individuen immerhalb eines bestimmten Bereichs bewegen sich Richtung dessen Zentrum.

Diese 3 Regeln führen zu einem Verhalten, wie im untenstehenden Sketch von Daniel Shiffman. Es können bei Bedarf natürlich noch weitere Regeln definiert werden.

Starte Applet

Flock flock;

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

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);
    velocity = new PVector(random(-1,1),random(-1,1));
    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(1.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 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,location);  // A vector pointing from the location to the target
    // Normalize desired and scale to maximum speed
    desired.normalize();
    desired.mult(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);
    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
        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) {
      // Implement Reynolds: Steering = Desired - Velocity
      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);
      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);
  }
}

Erläuterungen zur Boid Klasse:

  • Die Vektoren location, velocity und acceleration kontrollieren Position, Geschwindigkeit und Beschleunigung.
  • In jedem draw() Durchlauf wird die acceleration (Beschleunigung) basierend auf der 3 Kräfte Separation, Alignment und Cohesion neu berechnet.
  • Separation: Es werden alle Boids durchlaufen und ein Distanzvektor errechnet. Weiters wird aus allen Distanzvektoren, die größer 0 und kleiner als ein desiredseparation genannter Wert sind, ein Durchsschnittdistanzsvektor namens steer errechnet. Von diesem wird dann noch der aktuelle Geschwindigkeitsvektor abgezogen.
  • Alignment: Auch hier werden wieder alle Boids durchlaufen. Dabei wird ein durchschnittlicher  Geschwindigkeitsvektor aller Boids errechnet, die sich innerhalb einer bestimmten Distanz (neighbordist) befinden. Auch von diesem wird dann wieder der Boid eigene Geschwindigkeitsvektor abgezogen.
  • Cohesion: Bei der Cohesion wird ein durchschnittlicher Positionsvektor aller, sich innerhalb einer best. Distanz befindenen Boids errechnet. In diese Richtung wird dann gesteuert.
  • In der flock-Methode der Boid Klasse werden dann alle Kräfte gewichtet und zur aktuellen Beschleunigung aufsummiert.
  • In update wird dann die aktuelle Beschleunigung zur aktuellen Geschwindigkeit hinzugerechnet. Dann wird noch die Geschwindigkeit auf die Maximalgeschwindigkeit begrenzt und die Beschleunigung auf 0 gesetzt.