美文网首页
2022-02-28 shader中计算点在面内

2022-02-28 shader中计算点在面内

作者: MrSwilder | 来源:发表于2022-02-28 19:42 被阅读0次
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;
}`

————————————————
版权声明:本文为CSDN博主「kingslayerzxs」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/qq_40043761/article/details/117700084

二、测试示例

1.顶点着色器

precision highp float;
attribute vec3 position;
attribute vec3 normal;
uniform mat3 normalMatrix;
uniform mat4 modelViewMatrix;
uniform mat4 projectionMatrix;
varying vec3 fNormal;
varying vec3 fPosition;

void main()
{
  fNormal = normalize(normalMatrix * normal);
  vec4 pos = modelViewMatrix * vec4(position, 1.0);
  fPosition = pos.xyz;
  gl_Position = projectionMatrix * pos;
}

2.片元着色器

precision highp float;
uniform float time;
uniform vec2 resolution;
varying vec3 fPosition;
varying vec3 fNormal;
bool pointInPolygon(vec3 p, vec3 points[3]){
  bool inside = false;
  const int length = 3;
  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;
}
void main(){
//   float coeff[3]=float[3](1.11,52.0,52.1);
  vec3 vec3Array[3];
  vec3Array[0] = vec3(1.0, 0.0, 0.0);
  vec3Array[1] = vec3(0.0, 1.0, 0.0);
  vec3Array[2] = vec3(1.0, 1.0, 0.0);
  vec3 point=vec3(gl_FragCoord.x/resolution.x,gl_FragCoord.y/resolution.y,0.0);
  bool isInside=pointInPolygon(point,vec3Array);
  
  
  if(isInside){
    gl_FragColor = vec4(fNormal, 1.0);
  }else{
    gl_FragColor = vec4(1.0,1.0,1.0, 0.2);
  }
  
}

结果:


image.png

相关文章

网友评论

      本文标题:2022-02-28 shader中计算点在面内

      本文链接:https://www.haomeiwen.com/subject/pexrrrtx.html