xxxxxxxxxx
104
let seeds = [];
let grid = [];
let seed_count = 400;
let delaunay;
let voronoi;
function setup() {
createCanvas(400, 400);
for(let i = 0; i < seed_count; i++) {
let x = width/2 + random(0.001);
let y = height/2 + random(0.001);
seeds[i] = createVector(x, y);
}
}
function gridPoints() {
let x_max = round(sqrt(width / height * seed_count));
let y_max = round(seed_count / x_max);
seed_count = x_max * y_max;
for(let i = 0, y = 0; y < y_max; y++) {
for(let x = 0; x < x_max; x++, i++) {
let px = map(x, 0, x_max, 0, width);
let py = map(y, 0, y_max, 0, height);
grid[i] = createVector(px, py);
}
}
}
function draw() {
if(frameCount > 2000) {
noLoop();
print("Animation done");
}
background(255);
stroke(0);
delaunay = d3.Delaunay.from(seeds.map(p=>[p.x, p.y]));
voronoi = delaunay.voronoi([0,0,width,height]);
let polygons = voronoi.cellPolygons();
let cells = Array.from(polygons);
drawPolys(cells);
drawSeedPoints(seeds);
let centroids = polyCentroids(cells);
for(let i = 0; i < seeds.length; i++) {
seeds[i].lerp(centroids[i], 0.01);
}
}
function drawSeedPoints(seeds) {
strokeWeight(2);
for(let v of seeds) {
point(v.x, v.y);
}
}
function cheapRelax(seeds) {
}
function drawPolys(cells) {
strokeWeight(0.1);
noFill();
for(let poly of cells) {
beginShape();
for(let i = 0; i < poly.length; i++) {
vertex(poly[i][0], poly[i][1]);
}
endShape();
}
}
function polyCentroids(cells) {
let centroids = [];
for(let poly of cells) {
centroids.push(polyCentroid(poly));
}
return centroids;
}
function polyCentroid(poly) {
let area = 0;
let centroid = createVector(0, 0);
for(let i = 0; i < poly.length; i++) {
let v0 = poly[i];
let v1 = poly[(i+1) % poly.length];
let crossVal = (v0[0] * v1[1] - v1[0] * v0[1]);
area += crossVal;
centroid.x += (v0[0] + v1[0]) * crossVal;
centroid.y += (v0[1] + v1[1]) * crossVal;
}
area /= 2;
centroid.div(6 * area);
return centroid;
}