xxxxxxxxxx
77
const order = 3;
var N = 1 << order; // 2**order
var npts = N * N;
const path = [];
function setup() {
createCanvas(512, 512);
var L = width / N;
// console.log(pts[0]);
for (let i = 0; i < npts; i++) {
path[i] = hilbert(i);
path[i].mult(L);
path[i].add(L/2, L/2);
}
noLoop();
}
function draw() {
background(220);
stroke(20);
strokeWeight(3);
noFill();
beginShape();
for (let i = 0; i < npts; i++) {
vertex(path[i].x, path[i].y);
}
endShape();
}
function hilbert(p) {
const pts = [
new p5.Vector(0,0),
new p5.Vector(0,1),
new p5.Vector(1,1),
new p5.Vector(1,0)];
let mask = 3;
let index = p & mask;
let v = pts[index].copy();
for (let n = 1; n < order; n++) {
let lenfac = 2**n;
mask = mask << 2;
index = p & mask;
index = index >>> (2*n);
console.log(p,mask,index);
if (index == 0) {
let tmp = v.x;
v.x = v.y;
v.y = tmp;
}
if (index == 3) {
let tmp = lenfac-1-v.x;
v.x = lenfac-1-v.y;
v.y = tmp;
}
v.add(pts[index].mult(lenfac));
}
// let i = p >>> (2 * (order - 1));
// if (i == 0) {
// let tmp = v.x;
// v.x = v.y;
// v.y = tmp;
// }
// if (i == 3) {
// let tmp = -1-v.x;
// v.x = 1-v.y;
// v.y = tmp;
// }
// v.add(pts[i].mult(2));
return v;
}