首页 文章

THREE.js / GLSL:WebGL着色器,根据世界空间位置对片段进行着色

提问于
浏览
6

我已经看到了基于颜色片段在屏幕空间或其本地对象空间中的位置的解决方案,如Three.js/GLSL - Convert Pixel Coordinate to World Coordinate .

那些正在使用屏幕坐标,并在相机移动或旋转时进行更改;或仅适用于本地对象空间 .

我想要完成的是基于它们在世界空间中的 position 来着色碎片(如在three.js场景图的世界空间中) .

即使相机移动,颜色也应保持不变 .

希望行为的示例:位于(x:0,y:0,z:2)世界空间中的1x1x1立方体将使其第三个成分(蓝色== z)始终在1.5 - 2.5之间 . 即使相机移动,这也应该是真的 .

到目前为止我得到了什么:

顶点着色器

varying vec4 worldPosition;

void main() {


  // The following changes on camera movement:
  worldPosition = projectionMatrix * modelViewMatrix * vec4(position, 1.0);

  // This is closer to what I want (colors dont change when camera moves)
  // but it is in local not world space:
  worldPosition = vec4(position, 1.0);

  // This works fine as long as the camera doesnt move:
  worldPosition = modelViewMatrix * vec4(position, 1.0);
  // Instead I'd like the above behaviour but without color changes on camera movement


  gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);

}

片段着色器

uniform vec2 u_resolution;
varying vec4 worldPosition;

void main(void)
{
    // I'd like to use worldPosition something like this:
    gl_FragColor = vec4(worldPosition.xyz * someScaling, 1.0);
    // Here this would mean that fragments xyz > 1.0 in world position would be white and black for <= 0.0; that would be fine because I can still divide it to compensate

}

这是我得到的:https://glitch.com/edit/#!/worldpositiontest?path=index.html:163:15

然而,如果你使用wasd移动,你可以看到颜色不喜欢它们 .

1 回答

  • 6

    你的 worldPosition 错了 . 您不应该在计算中暗示相机 . 这意味着,没有 projectionMatrix 也没有 viewMatrix .

    // The world poisition of your vertex: NO CAMERA
    vec4 worldPosition = modelMatrix * vec4(position, 1.0);
    
    // Position in normalized screen coords: ADD CAMERA
    gl_Position = projectionMatrix * viewMatrix * worldPosition;
    
    // Here you can compute the color based on worldPosition, for example:
    vColor = normalize(abs(worldPosition.xyz));
    

    检查this fiddle .


    注意

    请注意,此处用于颜色的 abs() 可能会为不同的位置提供相同的颜色,这可能不是您正在寻找的颜色 .

    Position coords to color coords

相关问题