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