Skip to content

Instantly share code, notes, and snippets.

@INCHMAN1900
Created October 11, 2023 07:39
Show Gist options
  • Save INCHMAN1900/a3c8f37687a9d20b0f3f077a77d38fb9 to your computer and use it in GitHub Desktop.
Save INCHMAN1900/a3c8f37687a9d20b0f3f077a77d38fb9 to your computer and use it in GitHub Desktop.
Create Hilbert Curve in under 40 lines of code in Processing.
void setup() {
size(800, 800);
background(255);
noFill();
translate(width * 0.5, height * 0.5); // center of the curve.
hilbert_curve(6, width);
}
void hilbert_curve(int n, float size) {
if (n == 1) {
line(-size * 0.25, size * 0.25, -size * 0.25, -size * 0.25);
line(-size * 0.25, -size * 0.25, size * 0.25, -size * 0.25);
line(size * 0.25, size * 0.25, size * 0.25, -size * 0.25);
return;
}
hilbert_curve_part(new PVector(-size, -size).mult(0.25), n - 1, size * 0.5, 0);
hilbert_curve_part(new PVector(+size, -size).mult(0.25), n - 1, size * 0.5, 0);
hilbert_curve_part(new PVector(-size, +size).mult(0.25), n - 1, size * 0.5, HALF_PI);
hilbert_curve_part(new PVector(+size, +size).mult(0.25), n - 1, size * 0.5, -HALF_PI);
var tp_1 = pow(2, n) - 1;
var tpp_rec = 1.0 / pow(2, n + 1);
line(-size * tp_1 * tpp_rec, -size * tpp_rec, -size * tp_1 * tpp_rec, size * tpp_rec);
line(-size * tpp_rec, -size * tpp_rec, size * tpp_rec, -size * tpp_rec);
line(size * tp_1 * tpp_rec, -size * tpp_rec, size * tp_1 * tpp_rec, size * tpp_rec);
}
void hilbert_curve_part(PVector center, int n, float size, float rotation) {
pushMatrix();
stroke(random(100) + 150, random(80), random(255));
translate(center.x, center.y);
rotate(rotation);
hilbert_curve(n, size);
popMatrix();
}
@INCHMAN1900
Copy link
Author

screen-0033

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment