Hey,
I have the following piece of code in Processing (programming language) that I am supposed to change and implement in new ways. However I just can't seem to understand it. I would love it if someone here explained it to me step by step. Here's the code:
// TREE L-Systems (Branching)
int SZ = 512; //screen size
int sz = SZ/2; //half screen size
float d = sz/128; // turtle line length
float ang = (25.7/180.0)*PI; //turtle rotation
float s = 1; //branch scale factor
float x = SZ/2; // initial pos x
float y = SZ; // initial pos y
float a = -HALF_PI; //initial rotation
String state = "F"; //initial state
String F_rule = "F[+F]F[-F]F"; //substitution rule
String H_rule = "";
String f_rule = "";
int L = 5; // number of times to substitute
void setup() {
size(SZ, SZ);
background(255);
stroke(0);
// Perform L substitutions
for (int k = 0; k < L; k++)
state = substitute(state, F_rule, H_rule, f_rule);
noLoop();
println(state);
}
void draw(){
translate(x, y);
rotate(a);
// Walk along state string, execute turtle command
for (int i = 0; i < state.length(); i++)
turtle(state.charAt(i));
}
void turtle(char c){
switch(c){
case 'F':
case 'H':
line(0, 0, d, 0);
translate(d, 0);
break;
case 'f':
translate(d, 0);
break;
case 's':
scale (s, s);
break;
case '+':
rotate(-ang);
break;
case '-':
rotate(ang);
break;
case '[':
pushMatrix();
break;
case ']':
popMatrix();
break;
default:
println("Bad character: " + c);
exit();
}
}
String substitute(String s, String F, String H, String f){
String s2 = new String();
for (int j = 0; j < s.length(); j++)
if (s.charAt(j)=='F')
s2 = s2 + F;
else if (s.charAt(j)=='H')
s2 = s2 + H;
else if (s.charAt(j)=='f')
s2 = s2 + f;
else
s2 = s2 + s.charAt(j);
return s2;
}
Okay, so my questions are:
- Is my understanding correct that x and y define the original position of where the line should start?
- F[+F]F[-F]F replaces F each time it is run through the loop?
- F[+F]F[-F]F means: 'F' = Create line, move cursor to where the line ends; '+' = rotate it left as per 'ang'; '-' = rotate right as per 'ang'? I do not understand push and pop Matrix, I have read the API but still don't get it so I would appreciate an explanation.
- Initial rotation for the line is to go up? Is that what 'a' defines?
- Are there simpler examples of this and is there a website or a book with detailed explanation of L-System as applied in Processing?
I would really appreciate help as I am completely stumped.