This repository has been archived on 2025-03-02. You can view files and clone it, but cannot push or open issues or pull requests.
neofx-zoomedit/Triangle.cpp

71 lines
2.1 KiB
C++
Raw Normal View History

#include "Triangle.h"
#include "Line.h"
#include <math.h>
#include <stdio.h>
Triangle::Direction Triangle::getDirection() const {
float c = (va.getX()-vb.getX())*(vc.getY()-vb.getY()) - (vc.getX()-vb.getX())*(va.getY()-vb.getY());
return (c < 0) ? CW : (c > 0) ? CCW : UNKNOWN;
}
float Triangle::area() const {
float a = vb.distanceSq(vc);
float b = vc.distanceSq(va);
float c = va.distanceSq(vb);
return sqrt((a+b+c)*a+b+c - 2*(a*a+b*b+c*c))/4;
}
float Triangle::perimeter() const {
return va.distance(vb) + vb.distance(vc) + vc.distance(va);
}
bool Triangle::contains(const Vertex &v) const {
float a = (v.getX()-vb.getX())*(vc.getY()-vb.getY()) - (vc.getX()-vb.getX())*(v.getY()-vb.getY());
float b = (v.getX()-vc.getX())*(va.getY()-vc.getY()) - (va.getX()-vc.getX())*(v.getY()-vc.getY());
float c = (v.getX()-va.getX())*(vb.getY()-va.getY()) - (vb.getX()-va.getX())*(v.getY()-va.getY());
switch(getDirection()) {
case CW:
return ((a < 1E-6) && (b < 1E-6) && (c < 1E-6));
case CCW:
return ((a > -1E-6) && (b > -1E-6) && (c > -1E-6));
2007-09-27 08:27:04 +00:00
default:
return false;
}
}
bool Triangle::onEdge(const Vertex &v) const {
return (Line(va, vb).contains(v) || Line(vb, vc).contains(v) || Line(vc, va).contains(v));
}
int Triangle::intersectionCount(const Line &l) const {
int ret = 0;
Vertex v1, v2, v3;
printf("Testing line: (%f %f) (%f %f)\n", l.getVertex1().getX(), l.getVertex1().getY(), l.getVertex2().getX(), l.getVertex2().getY());
if(Line(va, vb).intersects(l, &v1) == INTERSECTION_SEGMENT_SEGMENT) {
printf("Intersection: (%f %f)\n", v1.getX(), v1.getY());
ret++;
}
if(Line(vb, vc).intersects(l, &v2) == INTERSECTION_SEGMENT_SEGMENT) {
printf("Intersection: (%f %f)\n", v2.getX(), v2.getY());
if(v2.distanceSq(v1) >= 1E-6)
ret++;
}
if(Line(vc, va).intersects(l, &v3) == INTERSECTION_SEGMENT_SEGMENT) {
printf("Intersection: (%f %f)\n", v3.getX(), v3.getY());
if(v3.distanceSq(v1) >= 1E-6 && v3.distanceSq(v2) >= 1E-6)
ret++;
}
printf("Found %i intersections.\n", ret);
return ret;
}