読者です 読者をやめる 読者になる 読者になる

Daily Creative Coding

元「30 min. Processing」。毎日、Creative Codingします。

L-System(コッホ曲線)

f:id:aa_debdeb:20160207094855j:plain
/**
* L-system (Koch Curve)
*
* @author aa_debdeb
* @date 2016/02/14
*/

LSystem lsystem;

void setup(){
  size(500, 500);
  lsystem = new LSystem();
  
}

void draw(){
  println("step: " + frameCount);
  lsystem.draw();
  lsystem.step();
  
}


class LSystem{

  float d;
  float delta;
  String string;
  HashMap<Character, String> rules;
  float iniDir;
  PVector iniPos;
  
  LSystem(){    
    d = 0.6;
    delta = 90;
    string = "-F";
    rules = new HashMap<Character, String>();
    rules.put('F', "F+F-F-F+F");
    iniDir = -90;
    iniPos = new PVector(-220, 100);
  }
  
  void step(){
    String nextString = "";
    for(int i = 0; i < string.length(); i++){
      char c = string.charAt(i);
      if(rules.containsKey(c)){
        nextString += rules.get(c);
      } else {
        nextString += c;
      }
    } 
    string = nextString;
  }
  
  void draw(){
    background(0);
    stroke(255);
    translate(width / 2, height / 2);
    translate(iniPos.x, iniPos.y);
    rotate(radians(iniDir));
    for(int i = 0; i < string.length(); i++){
      char c = string.charAt(i);
      switch(c){
        case 'F':
          line(0, 0, d, 0);
          translate(d, 0);
          break;
        case 'f':
          translate(d, 0);
          break;
        case '+':
          rotate(radians(-delta));
          break;
        case '-':
          rotate(radians(delta));
          break;
      }
    }  
  }
}