使用三元运算符或多个着色器来避免分支语句。例如,下面的代码使用三元运算符来避免在圆角几何着色器中使用分支:
vec3 normal = normalize(cross(dFdx(position), dFdy(position)));
float curvature = dot(normal, normalize(geometry.vertices[0].xyz - position));
float d = distance(position, geometry.vertices[0].xyz);
float radius = d / curvature;
float cutoff = (1.0 - smoothstep(0.5, 1.0, radius)) * length(geometry.vertices[0].xyz - geometry.vertices[1].xyz);
float edge = smoothstep(0.0, cutoff, distance(position, geometry.vertices[0].xyz));
float corner = smoothstep(cutoff, 1.0, distance(position, geometry.vertices[1].xyz));
float weight = mix(edge, corner, smoothstep(0.0, 1.0, curvature));
gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);
在这个例子中,我们使用三元运算符来计算边缘和角落的权重,而不是使用分支语句。这样可以提高性能并避免分支延迟。
下一篇:避免在元素上绑定多个事件