p5(s => {
class Triangle{
constructor(x1, y1, x2, y2, x3, y3, level){
this.x1 = x1;
this.y1 = y1;
this.x2 = x2;
this.y2 = y2;
this.x3 = x3;
this.y3 = y3;
this.level = level;
this.divided = false;
}
getLongest(){
let d12 = (this.x1 - this.x2) * (this.x1 - this.x2) + (this.y1 - this.y2) * (this.y1 - this.y2);
let d23 = (this.x3 - this.x2) * (this.x3 - this.x2) + (this.y3 - this.y2) * (this.y3 - this.y2);
let d13 = (this.x1 - this.x3) * (this.x1 - this.x3) + (this.y1 - this.y3) * (this.y1 - this.y3);
if (d12 > d23 && d12 > d13) {
return [this.x1, this.y1, this.x2, this.y2, this.x3, this.y3];
} else if (d23 > d13) {
return [this.x2, this.y2, this.x3, this.y3, this.x1, this.y1];
} else {
return [this.x1, this.y1, this.x3, this.y3, this.x2, this.y2];
}
}
divide(){
this.divided = true;
let longestEdge = this.getLongest();
let unchanged = [];
let newX = (longestEdge[0] + longestEdge[2]) / 2;
let newY = (longestEdge[1] + longestEdge[3]) / 2;
return [new Triangle(longestEdge[0],longestEdge[1], newX, newY, longestEdge[4], longestEdge[5], this.level + 1),
new Triangle(longestEdge[2],longestEdge[3], newX, newY, longestEdge[4], longestEdge[5], this.level + 1)];
}
}
s.setup = function(){
s.createCanvas(400,400);
s.strokeWeight(0.5);
let tris = [new Triangle(0,0,400,0,0,400, 0), new Triangle(0,400,400,400,400,0,0)];
for (let i = 0; i < tris.length; ++i) {
const t = tris[i];
if (Math.random() > 0.1 && t.level < 10) tris.push(...t.divide());
}
tris = tris.filter(t => !t.divided);
tris.forEach(t => s.triangle(t.x1, t.y1, t.x2, t.y2, t.x3, t.y3));
}
})