/*
Viviani's theorem, named after Vincenzo Viviani, states that the sum of the distances from any interior point to the sides of an equilateral triangle equals the length of the triangle's altitude.[1]
*/
float r = 150;
PVector[] v = new PVector[3];
PVector[] p = new PVector[3];
color[] c = new color[3];
void setup() {
size(400, 400);
for (int i = 0; i < 3; i++) {
float ang = -PI / 2 + radians(i * 360 / 3);
float x = width / 2 + r * cos(ang);
float y = height / 2 + r * sin(ang);
v[i] = (new PVector(x, y));
}
c[0] = color(241, 241, 241);
c[1] = color(250, 44, 50);
c[2] = color(0, 189, 100);
}
void draw() {
background(44, 62, 80);
stroke(255);
noFill();
beginShape();
for (int i = 0; i < v.length; i++) {
vertex(v[i].x, v[i].y);
}
endShape(CLOSE);
p[0] = pointOnLine(v[0].x, v[0].y, v[1].x, v[1].y, mouseX, mouseY);
p[1] = pointOnLine(v[1].x, v[1].y, v[2].x, v[2].y, mouseX, mouseY);
p[2] = pointOnLine(v[2].x, v[2].y, v[0].x, v[0].y, mouseX, mouseY);
ellipse(mouseX, mouseY, 5, 5);
drawPerpendicular(p[0].x, p[0].y, c[0]);
drawPerpendicular(p[1].x, p[1].y, c[1]);
drawPerpendicular(p[2].x, p[2].y, c[2]);
float d1 = dist(p[0].x, p[0].y, mouseX, mouseY);
float d2 = dist(p[1].x, p[1].y, mouseX, mouseY);
float d3 = dist(p[2].x, p[2].y, mouseX, mouseY);
pushMatrix();
translate(30, 50);
drawTotalLines(d1, d2, d3);
popMatrix();
stroke(255);
line(0, 50, width, 50);
line(0, 50 + d1 + d2 + d3, width, 50 + d1 + d2 + d3);
}
PVector pointOnLine(float x1, float y1, float x2, float y2, float mx, float my) {
float m = (y2 - y1) / (x2 - x1);
float x = (mx + my * m + sq(m) * x1 - y1 * m) / (1 + sq(m));
float y = m * (x - x1) + y1;
return new PVector(x, y);
}
void drawPerpendicular(float x, float y, color f) {
noStroke();
fill(f);
ellipse(x, y, 5, 5);
stroke(f);
pushMatrix();
strokeWeight(4);
line(x, y, mouseX, mouseY);
popMatrix();
}
void drawTotalLines(float d1, float d2, float d3) {
pushMatrix();
strokeWeight(4);
stroke(c[0]);
line(0, 0, 0, d1);
stroke(c[1]);
line(0, d1, 0, d1 + d2);
stroke(c[2]);
line(0, d1 + d2, 0, d1 + d2 + d3);
popMatrix();
}