## NOC: Week 9 – Cellular Automata

Mar 302011

Flocking
- “neu” examples
- optimization

Cellular Automata
- What
- Wolfram 1D
Class 1-4
- Game of life 2D
2D array
OOP?
- Eduges
- Variations
– hexagonal
– probabilistic
– continuous
– historical
– moving?

### ALIGNMENT
- average velocity
###COHESION

- Average Location
Calculate the center of everyone and apply force

PVector cohesion (ArrayList boids) {
PVector sum = newPVector(0,0);
or(Boid b: boids) {
}
sum.div(boids.size());
PVector force = seek(sum);
return force;
}

Interesting to consider, Boids that had eyes and had periphery. Map out it’s peripheral view and maybe have it move or attract accordingly.

Collision: Can make the computational part overwhelming and frame rate will plummet.
How can we make it more effecient?

1. ArrayList to keep track of every element ONCE
2. ArrayList of a grid of screen?
-or-
1. Each “thing” register in grid
2. Check for intersection

Random suggestion:
Making a sin/cos look up table
- useful if you need more speed (less computational work)

###CELLULAR AUTOMATA
Definition:
- grid of cells 1D, 2D, 3D…?
- each cell has a finite number of states
– 0 or 1 ([on/off??] encoding & expression/genotype & phenotype)
– a state can drive the behavior of an object
- each cell has a neighborhood
– in flocking, the state has a lot to do with what’s happening w/ neighbor and neighborhood
___ eg. one member in flock dies, surrounding dies, etc. States change from 1 to 0 or whatever.
___ eg. water coloring sketch. Center pixel has color, but surrounding cells fade out to imitate the spread of color (a lot you can do with pixels based on CA rules)
- good reading: game of life

WOLFRAM’S SYSTEM
Have to have at least 1 dimension
Does the neighborhood include itself? Yes
1. 8 combinations of 3 digits of zeros and ones: 2^3 = 8
2. 8 combinations of 2 digits of zeros and ones 2^8 = 256 total combinations

These combinations can be divided into 4 classes:
class 1 – homogenous
class 2 – oscillating (“pattern”)
class 3 – random (“chaotic”)
class 4 – 2&3 together (“complexity”)
Though this really really basic process of 1s & 0s, we can generate patterns of randomness.
mathworld.wolfram.com/ElementaryCellularAutomaton.html

“Digital Physics” – can all of our world be descibed in a series of zeros and ones.
- there’s a book about it that starts with a Z.

EDGES: They may not have neighbors. What to do?
Common Options:
1. Treat them as a constant
2. Create an edge rule set
3. Wrap around **most common solution**

Why relevant to projects we may do:

1D CA vs 2D CA
1D – look to your neighbors left & right: 3 cells total
2D – look up, down, left, right (all around): 9 cells total

1- (0 or 1)
0 – (1 or 0)

3 real possible outcomes.
Birth
Death
Stasis

2D array
array [][]

Reads the old array, writes a new array, then re-writes to the original
int[][] old_board, new_board;
-or-
OOP
Cell[][] grid;

- You can explore a hexagonal pattern
- Or a probabilistic approach. Having a 90% chance of dying instead of just dying. They dont’ have to be so precise and accurate
- maybe determine things based on it’s history. How long it’s been around etc. If it’s been alive for 50 frames in a row, maybe it’s brighter etc.

3D – 27 neighbors!!
- just a lot more coding to do

FRACTAL – shape that when broken into parts, parts, approximate the whole
- when broken into small parts, is identical to whole

Fractal Broccoli

- natural forms that cannot be described Euclidian geometry
- self-similar structure
- defined with a recursive function (code friendly)
- fine structures at small scales
– when you zoom into fractal the pattern repeats itself

Production rule
1. line segment
2. cut into 4 lines
3. each of those segments are then cut into 4 lines again… and repeat

Koch Curve -or- Koch Snowflake

Theoretically, INFINITE lines being created in a limited space – may explain why this pattern appears so often in nature. Evolutions, tends towards it…blood vessels, leopard spots, ferns…
Because of this parado of infinite growth in limited space sometimes called Koch Monster

CONTINUATION OF TREE DATA/LISTSERV VIZ:
Fractal tree: has to control, but in combination with ArrayLists, to draw leaves/ellipses at the ends of the branches

LSYSTEM

“Strangely foreshadowing… cellular automata…au-tah-mah-tah? auto-mah-tah? *mumbles away*”

## NOC: Week 8 – Complex Systems

Mar 232011

Steering
- seek/arrive (pursue?)
- wander
- flow field
- path following
– DOT PRODUCT

Groups
- complex systems?
- self-ogranizing?
- flocking

CA
- wolfram
- GOL

Complex system
- non-linear
- parallel
- “emergent”

*nesting
- “memory”
- genetic algorith
*cooperation & competition

##STEERING
SEEK/ARRIVE
1. What is my target?
*2. What is my “desired” velocity?

Craig Reynolds: www.red3d.com/cwr/steer

class Vehicle {
loc, vel, accel (vectors)
maxspeed (float)
maxforce(float)
steer(PVector target, boolean slowdown) (steer target true, slow down, steer target false, go fast)

}

STEERING = DESIRED – VELOCITY
- when you’re moving in one direction and want to change directions, you need to steer to compensate for the direction change

WANDER
You can use two points on a circle. The target is somewhere on the circle, the vehicle is on another side, and as the angle of where the target sits on the circle changes, the vehicle’s direction changes.
steering: change in velocity
turning: change in direction

FLOW FIELD
A grid of cells, in which each cell has an arrow in it that represents a velocity
No target in this case, just desired velocity
The desired velocity is really the cell it is going to be in, rather than the cell it is in?????
One reason to use a flow field: fluid simulation eg. flow of blood throughout the body or a birds-eye stampede…
Maps out a 2D space (could be 3D too)

PATH FOLLOWING
- not path finding (in AI)

The black dot is the future spot

- find the shortest distance between a point and the line (path)
You need:
1. The future location
2. The normal location
3. And the future location on the path

DOT PRODUCT

The 2nd equation is the simpler and more useful one.
- angle between processing
a = ______________
b = ______________
b.normalize();
float length = a.dot(b);
b.mult(length) ***

How do we know which line to find the shortest distance between?
- there are an array of points and it normalizes all the points
If you really really do need to use a curve, you can always find the tangent (highest point of a curve) as the “normal” point.

1. Vehicles can see other vehicles
2. Combining & Weighting behaviors
3. Complex systems

Flocking – “Boid”
Alignment – move with our neighbors
Cohesion – stay with your neighbors
Separation – stay away from your neighbors

Now’s the time to start reading chapter 15-19 of the book with planes on it?

“Nice guy…he looks like a nice guy. I’ve never met him, but I’ve emailed him once… it was pretty exciting” -Shiffman on Craig Reynolds
“Words are just words. They can’t hurt me.”

## NOC: Week 6 – BOX2D & Toxiclibs

Mar 022011

Box2D
- Joints
- Filter group Index
- multi shapes
- moving “manually”
- Contact Listener & Interface!

Toxiclibs
- vs. Box2D
- using inhabitance
-what is verlet physics
- connected systems
- force directed graphs

Complex Systems
- simple units
- parallel
- emergence

Autonomous Agent
- limited perception of environment (predict future)
- process & calculate action

Vehicle
- Action/Selection
- Path Determination
- Locomotion

Goals/Strategy
- week
- flee
- hug wall
- braitenby??
##BOX2D
Review:
World (contains) Body (contains) Shapes

JOINT: Connects 2 bodies (not shape)
Joint definitions:
- distance joint
— imagine an inflexible steel rod
— NOT a shape. No substance
— can be springy
- revolute joint
— for turning stuff
— like the revolutionary point in transformice
- mouse joint*
— DJDO: Distance Joint Def Object
jd.body1=__________
jd.body2=__________

Filtering collisions
sd.filter.groupIndex = 1-8
If snowman & snow are both 8, they’ll collide with each other
-8 and 8 = Do not collide with each other

How to build more complex shapes in box2d
[] setAsBox();
O CircleDef

What if you wanted to make a O=||<< (person sideways)
1. Define the shape
- set properties: local position
2. Define the body
- set properties
3. Attach shape to body
- n times
To attach many shapes to body.
Define shape multiple times & attach to body
4. However: Every single shape is going to be attached at the center unless you set the 'local position' of the shape

MANUAL MOVEMENT
How to move paddle with mouse?

Set an object's location
Convert X/Y to WORLD coordinates
EVEN SO
- If you don't, BOX2D will think of things as teleportation.
- It cannot figure out the physics for it, so just jumps it

You need to connect a joint from the paddle to the mouse. So when you pull the mouse it pull the paddle.

In BOX2D, the "ground" is not the bottom of the screen. It's a Plane, so it's actually 'itself' or what we see.

Attach paddle to Mouse AND Ground. One to anchor it?
MouseJointDef mjd = ____
mjd.body1 = box.body;
mjd.body2 = box2d.getGroundBody(); <--
MouseJoint m; = _____
mj.setTarget(___,___); <--

INTERFACE

The only way BOX2D can tell processing when a collision is happening you have to conform to its standard and add required functions:
void persist(){}
void remove(){}
void results(){}

You don't have to have anything in it, but you have to write all of them!

MyListener ml;

}

To make a particle turn red
Contact point btwn shape 1 & shape 2 --> bodies –> particle object
body –> particle
getUserData

box & particle
shape 1 & shape 2

filter vs ContactListener
grouping particles vs. collision of specific particles

##TOXICLIBS: A giant collection of libaries
BOX2D
World, Body, Shape, Joint
TOXICLIBS – Verlet physics packet
Verlet physics, V. Particle, X (no shape. Does not too collision), – V. Spring
— 3 kinds of springs:
– Verlet Spring
– constitutional????
– min distance
- Has it’s own vector class: Vec2D, Vec3D
- You can lock(); a particle
- boundaries in toxiclibs is the “background” in processing
-

Toxiclibs PRO:
+ 3D – has 3D capabilities. Box2d…2d only
+ Designed for Processing
+ Good documentation
+ Uses pixel coordinates (no headache conversions)
+ Faster (because it doesn’t do collisions?)
+ Connected systems (Genevieve’s string on balloon)
+ Inheritance – Toxiclibs has a nice big library we can use and we EXTENDS it.

Coding it up: //elegant processign coding
class Particle extends Verlet Particle {
void display(){
ellipse(x,y,10,10);
}
}

## COMPLEX SYSTEMS
- examples stock market
- many small parts moving to get a group composition

Our “Vehicle” has locomotion, a path, and actions that we creatively use, but the key is it needs to have GOALS (seek, flee etc.)

Craig Reynolds: seek, flee, water, flow field, path crowd path, float. (Maker of these behaviors in movies, games etc.)

1. Competition: Up to you to make a combination of competing behaviors of the above drives
2. Make up stuff

Back to Craig: STEERING BEHAVIOR

Steering force = Desire – Velocity
An embeded “perception of the environment” meaning there’s a sense the object understand and interacts around/with environment. Eg. Obstacle avoidance = obvious ‘perception of envi’

Desire Vector = Target Vector – Loc Vector
Desired velocity want to hit max velocity. (there has to be an acceleration and directional change)

maximum force: determines steerablility to garget

float maxspeed;
float maxforce;

##TARGET SEEKING – basic seekign behavior

Books: Casey Reeves – Vehicles (emotional drives rather than hug wall etc.)
Turbles termites & traffic jams

“Animal a, new animal…we are so amazing, we can make an animal.” (mumbled 2nd half)

“How this scenario is giogn to pan out…i’ve already rehearesd this in my head…”
“We really shouldn’t do this but i can’t resist”
“This looks kind of right, but clearly not at all.” (box2d physics. body&image incongruent)
“That class was a big time energy suck…in a good way” (Big screens)

“And say you want the snow to bounce off the snowman… I don’t know if that really makes sense, but pretend you want the snow to bounce off the snow man”

“Lollipop…what was it thhe lollipop….gang?”
“guild”

## NOC: Week 5 – Physics Libraries

Feb 232011

Inheritance
Polymorphism
Interface
BOX2D
World
- coordinate system
Body
Shape
- density
-friction
-restitution
Joint
TOXICLIBS

bullet/unity – game engines

###INHERITANCE/POLYMORPHISM
You don’t want multiple arrayLists if you can just have ONE to manage both:
ArrayList
ArrayList
Works, but inconvenient. This is where inheritance/polymorphism helps

class Cat{
void sleeps(){}
void eat(){}
}

class Dog{
void sleeps(){}
void eat(){}
}

Annoying to be copying large chunks of code over and over.
class Animal {
void sleep(){}
void ea()t{}
|

class Cat extends Animal {
**Automatically, Cat inherits Animal functions!!**
**Cat can also have its OWN function like:**
void meow (){}
}

Basically:
1. Inherit vars & funct: You write ‘extends’ and you get to inherit qualities from the parent/super qualities to the child/sub.
2. “Augment”: Cats have animal qualities + unique (meow)
3. Override: Change/override something like the “display”. Base code is same, but make some tweaks.
4. 3+2: Override + Augment. Doing what’s in the parent & my own thing.
eg.
child:
void sleep(0 {
println(“purr”);
super.sleep(); <-- takes parent sleep quality
}

parent:
void sleep() {
println("zzz");
}

5. Cannot inherit a constructor.
int age/int whiskers
Animal(){}
Cat(){super();} //calls parent constructor required
void sleep(){
}

Everything Java kind of uses inheritance. Processing inherits from PApplet. That's why we can make things like ellipse, rect, line etc.

Polymorphism:
Animal a = new Animal();
Dog d = new Dog();
Animal a = new Dog(); // Can be done IF dog extends from Animal.
If there is a relationship built on inheritance it CAN BE DONE!

Animal[]animals = new Animal [100];
animal[0] = new Dog();
animal[1] = new Cat();

INTERFACE:
Box2d - contact listener
A mechanism for something like inheritance where you can extend multiple things.

JOGL - Java + OpenGL development info

###BOX 2D
- Good for collisions
Where to find it
- box2d.org --> C++ engine
- jbox2d.org –> what we’re usng
- pbox2d –> helper class for jbox2d (by shiffman)
- find on gethub or for now on wiki/google code
- documentation:
– c++ manual
– good actionscript tutorials

World (the physics world) will give you
- code:
PBox2D box2d = new Pbox2d(this);
2box2d.createworld();
- AABB: access aline bounding box (fancy term for a square grid)
- Gravity: 1 global force provided by default
- doSleep: by default set to “true” meaning the objects at rest won’t be moving/computing movement

Body –> Location
Shape (attach to body)
- Geometry – the shapes are just an underlying engine for you, you can place any image on top of it
–box2d sees a connected system of circles & squares, but you can overlay something on top of it
- friction
- density: density of 0: fixed immovable object. No physics, just stuck in place. Great for boundaries and stuff.
– toxiclibs = lock()
- restitution: bounce level
Joint
- things that allow things to attach to each other
- side note: can be used for mouse interaction. Acts as a spring, you can pull and drag items

//note. Cannot make concave shape in box2d. It doesn’t know how to make collisions for it. You’d have to make it out of multiple shapes.

World <--Fill with Bodies <-- Constructed with shapes <--attached with Joints

Processing --> Box2D
locations:
dimensions:
1. set up world
PBox2D box2d;
2. Define the body
Body Def bd = new BodyDef();
2a. Set properties
bd.position.set(x,y);
2b. Screen to world: convert position to world coordinates
Vec2 loc = box2d.screenToWorld(x,y);
bd.position.set(loc);
2c. Create body
body = box2d.createBody(bd);
3. Create a shape
3a. Define shape
PolygonDef sd = new PolygodDef();
3b. Properties – density, friction, restitution
sd.setAsBox(w,h);
float box2dw = box2d.scaleScreenToWorld(w); //making something to put into box2d world. Thinking of pixels –> world
float box2dh = box2d.scaleScreenToWorld(h);
sd.setAsBox(box2dw,box2dh);

density
sd.density = 1.0;
sd.restitution = 0.3;
sd.friction = 0.2;

4. Attach shape to body
body.createShape(sd);
body.setMassFromShapes();
//IMPT: Tells box2D, i’m finished, now figure out the mass of these shapes.
5a. don’t forget box2d.step(); //step forward in time put in DRAW
5b. Then add properties as you will. Don’t forget positive is now negative

“This relates to the…still looking at that cookie…This relates…”
“it can spin like confetti…i don’t know if confetti spins….but in this example it does”
“lets say you want to make a cute, cuddly, gelatinous, creature with eyes, mouth, some hair, maybe some weird ear.”

## Nature of Code: Class 3 – Forces & Oscillation

Feb 092011

OOP
- static vs non-static
- pass by ref vs copy
FORCES
- make it up!
- friction/drag
-graviational attraction
OSCILLATION
- trig review
- polar vs cartesian
- ang velocity/accerelation
- simple harmonic motion
- pendulum
- spring

Vector forces
##OOP

Steering force – (like a car in a racing game)
You desire to reach the target, but have a velocity going one way, so you need the steer force (turning force required) to get there.
steer = desired – velocity

Important side note in Vector math (when an object needs forces manipulated but also to keep it’s original values) (apparently needed for gravity/friction)
int z = x + y/PVector c = PVector.add(a,b);
- this actually initiates c to the value of a + b
- it creates a NEW PVector

int x=5;
int y=x;
x = x*2
Without linking them in the code,
x = 10, and y = 5

with objects will share/reference a variable (x & y would both be 10)[or (a = 10,0) (b = 10,0)]
which is generally good, but you don’t generally want this with vectors.

PVector f = force.get(); //get is making the COPY
f.div(mass);

So it opens up a copied space for “f”
I think we do this in data rep too.

PVector f = PVector.div(force,mass); //does exactly the same thing as the above

##FORCES pt 2
Friction = -C * N *(V^)
(kinetic friction means its movign vs static, which isn’t[eraser on desk])
-C (coefficient) is a constant
N = 1 (could be seen as another constant… i guess kind of negligible)
(V^) – the interesting target

Magnitude: float c = 0.01;
Velocity.normalize();

PVector fine = vel.get();
force.normalize();
force.mult(c);

Friction is fairly simple to model. We know the direction (opposite of moving direction)

Friction in processing:
- just dampens movements
- can also just x velocity by .9 or something, but this makes it a specific force
- reversing it makes it a super bouncy environment

- air resistance
- terminal velocity
- hw – model terminal velocity
- take out constants for our general air resistance purposes, -1/2, rho(densities), A, Ca
- interested in (v^2)
- difference btwn drag and friction in processing: drag will never stop the object from moving. It will hit a terminal velocity, friction, if unrealistically strong enough will stop it
- impt to keep in mind differences in real life & differences in programming
- direction also opposite of velocity in this case

- both friction & drag not as interesting in velocity, all about magnitude, but attraction has direction
- float m = (G * massA * mass B)/d * d
–normalize…it??
- PVector dir = PVector.sub(loc B, locA);
float d = dir.mag();
dir.normalize();
(bahhh…something about if you have multiple things attracted to somethign)
- dir.div(d);
- constrain can be useful in controlling the magnitude of the forces

##TRIG & OSCILLATION
(angular/rotational momentum)
The math behind sohcahtoa is relevant to vectors
Cartesian vs Polar

- Polar is good for moving something on an angular path

But processing will only take cartesian points.
Convert:
- sin(Θ) = y/r
- cos(Θ) = x/r

- x=r*cos(Θ)
- y=r*sin(Θ)

example:
variables set as:
float x = r *cos(theta);
float y = r *sin(theta);

line(0,0,x,y);
ellipse(x,y,16,16);
(ball on string rotating in circle)