shader判断点是否在多边形内

var points = [];

//由于shader只能传固定长度,所以这里的长度要写成定好的,并且不能长度不能为0;
//二三维一样的,改下类型就行了,一般只用判断是否在平面内
var shader = `bool pointInPolygon(vec3 p, vec3 points[${points.length}]){
  bool inside = false;
  const int length = ${points.length};
  for (int i = 0; i < length; i++) {
    float xi = points[i].x;
    float yi = points[i].y;
    float xj;
    float yj;
    if (i == 0) {
      xj = points[length - 1].x;
      yj = points[length - 1].y;
    } else {
      xj = points[i - 1].x;
      yj = points[i - 1].y; 
    }
    bool intersect = ((yi > p.y) != (yj > p.y)) && (p.x < (xj - xi) * (p.y - yi) / (yj - yi) + xi);
    if (intersect) {
      inside = !inside;
    }
  }
  return inside;
}`



 

你可能感兴趣的:(shader判断点是否在多边形内)