本帖最后由 523066680 于 2014-8-18 21:33 编辑
- #include <stdio.h>
- #define bool int
- #define false 0
- #define true 1
-
- typedef struct {
- float x;
- float y;
- } Point;
-
- Point poly[]={
- 96.802,87.23,
- 89.094,78.623,
- 92.268,64.808,
- 115.391,61.863,
- 124.913,77.265,
- 115.845,90.174,
- 102.696,92.439,
- };
-
- float Cross(
- float x0, float y0,
- float x1, float y1
- ) {
- return (x0 * y1) - (x1 * y0);
- }
-
- int triangleIsCCW( //判断三个点的顺序是否为逆时针
- Point P0, Point P1, Point P2
- ) {
- auto cross = (
- Cross(
- P1.x-P0.x, P1.y-P0.y,
- P2.x-P0.x, P2.y-P0.y
- )
- );
- return cross >= 0;
- }
-
- bool pointInPolygon(
- Point vip, Point poly[], int n_poly
- ) {
- // points represented by [(x0,y0), ... (xn,yn)]
- int low = 0, high = n_poly;
- int mid;
- do {
- mid = (low + high) / 2;
- if (
- triangleIsCCW(poly[0], poly[mid], vip)
- ) {
- low = mid;
- } else {
- high = mid;
- }
- } while (low + 1 < high);
- if (low == 0 || high == n_poly) return false;
- return triangleIsCCW(poly[low], poly[high], vip);
- }
-
- int main(int argc, char *argv[])
- {
- FILE *fp = fopen("a.txt","r");
- FILE *wrt = fopen("inside.txt","w");
- Point vip;
- char s[1024];
- int n_poly = (sizeof(poly) / sizeof(poly[0].x)) / 2;
- int in_polygon;
- while ( ! feof(fp) ) {
- fgets(s, 1024, fp);
- if ( sscanf(s, "%f %f", &vip.x, &vip.y) < 2 ) {
- sscanf(s, "%f,%f", &vip.x, &vip.y);
- }
- in_polygon = pointInPolygon(vip, poly, n_poly);
- if ( in_polygon ) {
- printf("%.3f, %.3f\n", vip.x, vip.y);
- fprintf(wrt, "%.3f, %.3f\n", vip.x, vip.y);
- }
- }
- fclose(fp);
- fclose(wrt);
- return 0;
- }
复制代码 算法来自《实时碰撞检测算法技术》5.4.1 点与多边形之间的测试 P139
这段C的处理结果和Perl又那么一两个点的误差,主要是有些点几乎就在边缘上,
零点零几的区别 和 0 判断产生不同的结果。
────────┐
100.477, 85.911 │
96.747, 84.002 │
96.817, 75.030 │
105.692, 67.907 │
97.253, 70.233 │
115.392, 61.864 │
111.950, 80.117 │
105.931, 76.600 │
111.138, 85.624 │
114.157, 74.060 │
120.702, 70.397 │
92.268, 64.808 │
115.391, 61.863 │
────────┘ |