Home My Page Projects Code Snippets Project Openings diderot

# SCM Repository

[diderot] View of /branches/lamont/test/flocking/flock.diderot
 [diderot] / branches / lamont / test / flocking / flock.diderot

# View of /branches/lamont/test/flocking/flock.diderot

Thu Feb 7 18:41:18 2013 UTC (6 years, 8 months ago) by lamonts
File size: 2321 byte(s)
`Fixed errors with reduction code`
```/*! \file flock.diderot
*
* \author Lamont Samuels
*
* This example is an implementation of Chris Reynolds, Boids algorithms. It represents an example of using spatail and global communication
*/
/*
* COPYRIGHT (c) 2012 The Diderot Project (http://diderot-language.cs.uchicago.edu)
*/
int numBoids = length(initVelocities)/2;
int strandSize = 2;
int MAX_SPEED = 2;
real MAX_FORCE = 0.05;
int stepsMax = 10000;

input int width;
input int height;

strand Boid(real vx, real vy) {
vec2 pos = [real(width)/2.0,real(height)/2.0];
vec2 vel = [vx,vy];
int steps = 0;
output vec4 boidInfo = [0.0,0.0,0.0,0.0];

update {
vec2 cohereVec = [0.0,0.0];
vec2 alignVec = [0.0,0.0];
vec2 seperateVec = [0.0,0.0];
int count = 0;

cohereVec += neighbor.pos;
alignVec += neighbor.vel;
real d  =  dist(pos,neighbor.pos);
seperateVec = seperateVec + (normalize(pos-neighbor.pos)/d);
count+=1;
}

cohereVec /= real(count);
alignVec /= real(count);
seperateVec /= real(count);
vec2 diff = cohereVec - pos;
real magnitude = sqrt(diff[0] * diff[0] + diff[1] * diff[1]);

if(magnitude > 0){
cohereVec = normalize(cohereVec);

if(magnitude < 100.0) {
cohereVec *= (MAX_SPEED*(magnitude/100.0));
}else {
cohereVec *= MAX_SPEED;
}

cohereVec -= vel;

// limit the force
magnitude = sqrt(cohereVec[0] * cohereVec[0] + cohereVec[1] * cohereVec[1]);
if (magnitude > MAX_FORCE) {
cohereVec = normalize(cohereVec);
cohereVec *= MAX_FORCE;
}
}
else {
cohereVec = [0.0,0.0];
}

vec2 acceleration = cohereVec + alignVec + seperateVec;
vel += acceleration;

magnitude = sqrt(vel[0] * vel[0] + vel[1] * vel[1]);

if (magnitude > MAX_SPEED){
vel = normalize(cohereVec);
vel *= MAX_SPEED;
}
pos += vel;
boidInfo = [pos[0], pos[1], vel[0], vel[1]];
}
}

initially {Boid(initVelocities{i*2},initVelocities{i*2+1}) | i in 0 .. numBoids-1 };

```