> show canvas only <


/* built with Studio Sketchpad: 
 *   https://sketchpad.cc
 * 
 * observe the evolution of this sketch: 
 *   https://studio.sketchpad.cc/sp/pad/view/ro.4C2KtUSXylf/rev.1540
 * 
 * authors: 
 *   lonnen

 * license (unless otherwise specified): 
 *   creative commons attribution-share alike 3.0 license.
 *   https://creativecommons.org/licenses/by-sa/3.0/ 
 */ 



Splittable root;

void setup() { 
  size(300, 300);
  smooth();
  noLoop();
  root = new Splittable(0, 0, width, height);
  
  stroke(180);
  fill(66);
} 

void draw() {
  background(180);
  root.render();    
}

void mouseClicked() {
  root.clicked();
  redraw();
}

class Splittable {
  float x, y, w, h;
  ArrayList children;
  
  Splittable(x, y, w, h) {
    this.x=x;
    this.y=y;
    this.w=w;
    this.h=h;
    children = new ArrayList();
  }
  
  void clicked() {
    if (x     > mouseX ||
        x + w < mouseX ||
        y     > mouseY ||
        y + h < mouseY) {
      return;
    }
    
    for(int i = 0; i < children.size(); i++) {
      this.getChild(i).clicked();
    }
    
    if (children.size() == 0) {
      this.fracture();
    }
  }
  
  void fracture() {
    x1 = mouseX - x;
    x2 = w - x1;
    y1 = mouseY - y;
    y2 = h - y1;

    Splittable q1 = new Splittable(x + x1, y, x2, y1);
    Splittable q2 = new Splittable(x, y, x1, y1);
    Splittable q3 = new Splittable(x, y + y1, x1, y2);
    Splittable q4 = new Splittable(x + x1, y + y1, x2, y2);
    
    children.add(q1);
    children.add(q2);
    children.add(q3);
    children.add(q4);
  }
  
  Splittable getChild(int i) {
    if (i > children.size() || i < 0) { 
      return;
    }

    return (Splittable) children.get(i);
  }
  
  void render() {
    for (int i=0; i < children.size(); i++) {
      this.getChild(i).render();
    }
    
    if (children.size() == 0) {
      rect(x, y, w, h);
    }
  }
}