#include "svg.h"

#define SQRT3_6 0.28867513459481288225457439025098

int color;
int dcolor = 1;

double aux(int n) {
    double r = 1;
    int i;
    for (i=0; i<n; i++) {
        r /= 2;
    }
    return r;
}

void spaceFillingTree(int n, double x0, double y0, double x2, double y2) {
    if (n==0) {
        return;
    }  else {
        double d = aux(n+1);
        double xA = (0.5+d)*x0+(0.5-d)*x2, yA = (0.5+d)*y0+(0.5-d)*y2;
        double xB = (0.5-d)*x0+(0.5+d)*x2, yB = (0.5-d)*y0+(0.5+d)*y2;
        double x1 = (x0+x2)/2, y1 = (y0+y2)/2;
        line(xA, yA, xB, yB);
        stroke(color = rotateH360(color, dcolor));
        line(xA, yB, xB, yA);
        stroke(color = rotateH360(color, dcolor));
        spaceFillingTree(n-1, x0, y0, x1, y1);
        spaceFillingTree(n-1, x1, y0, x2, y1);
        spaceFillingTree(n-1, x0, y1, x1, y2);
        spaceFillingTree(n-1, x1, y1, x2, y2);
    }
}

int main(void) {
    start();
    stroke(color = hsb360(0, 100, 100));
    strokeWeight(0.5);
    noFill();
    spaceFillingTree(6, 40, 30, 257, 180);
    finish();
    return 0;
}
