#include #include "lighting.h" /* Find the distance between two points */ int dist(int x1, int y1, int x2, int y2) { return sqrt((x2 - x1) * (x2 - x1) + (y2 - y1) * (y2 - y1)); } /* Find the square of the distance between two points */ int sqr_dist(int x1, int y1, int x2, int y2) { return (x2 - x1) * (x2 - x1) + (y2 - y1) * (y2 - y1); } /* Returns 1 if (x1,y1) is between the other two, 2 if (x2,y2) is, and so on */ /* Returns 0 if two or more points are coincident */ /* Naturally, the points must be very close to collinear */ int middle_point(int x1, int y1, int x2, int y2, int x3, int y3) { /* Check for coincident points */ if ((x1 == x2 && y1 == y2) || (x1 == x3 && y1 == y3) || (x2 == x3 && y2 == y3)) return 0; /* See if point 3 is in the middle */ if ((x1 < x3 && x3 < x2) || (x2 < x3 && x3 < x1) || (y1 < y3 && y3 < y2) || (y2 < y3 && y3 < y1)) return 3; /* Okay, then, point 1 */ if ((x2 < x1 && x1 < x3) || (x3 < x1 && x1 < x2) || (y2 < y1 && y1 < y3) || (y3 < y1 && y1 < y2)) return 1; /* It must be 2 */ return 2; } /* Finds intersection and stores in (*_x, *_y); returns 0 if lines are skew */ /* If c == 0, (x1, y1) - (x2, y2) is treated as a ray */ int intersection(int x1, int y1, int x2, int y2, int x3, int y3, int x4, int y4, int* _x, int* _y, int c) { int den, num, x, y; den = (y4 - y3) * (x2 - x1) - (x4 - x3) * (y2 - y1); if (den == 0) return 0; num = (x4 - x3) * (y1 - y3) - (y4 - y3) * (x1 - x3); x = x1 + num * (x2 - x1) / den; if (c) {if (!((x1 <= x && x <= x2) || (x1 >= x && x >= x2))) return 0;} else if (!((x1 <= x && x1 <= x2) || (x1 >= x && x1 >= x2))) return 0; if (!((x3 <= x && x <= x4) || (x3 >= x && x >= x4))) return 0; y = y1 + num * (y2 - y1) / den; if (c) {if (!((y1 <= y && y <= y2) || (y1 >= y && y >= y2))) return 0;} else if (!((y1 <= y && y1 <= y2) || (y1 >= y && y1 >= y2))) return 0; if (!((y3 <= y && y <= y4) || (y3 >= y && y >= y4))) return 0; *_x = x; *_y = y; return 1; } /* True if (xa,ya) and (xb,yb) are on the same side of (x1,y1)-(x2,y2) */ int same_side(int x1, int y1, int x2, int y2, int xa, int ya, int xb, int yb) { int pa, pb; x2 -= x1; y2 -= y1; xa -= x1; ya -= y1; xb -= x1; yb -= y1; pa = xa * y2 - ya * x2; pb = xb * y2 - yb * x2; return (pa < 0 && pb < 0) || (pa == 0 && pb == 0) || (pa > 0 && pb > 0); } /* True if (x1,y1), (x2,y2), and (x3,y3) are (nearly) collinear */ int collinear(int x1, int y1, int x2, int y2, int x3, int y3) { unsigned int d = (x2 - x1) * (y3 - y1) - (y2 - y1) * (x3 - x1); return d * d <= sqr_dist(x1, y1, x3, y3); }