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

nyl*_*lki 7 glsl webgl three.js glsles

我已经看到了基于它们在屏幕空间或其本地对象空间中的位置的颜色片段的解决方案,如Three.js/GLSL - 将像素坐标转换为世界坐标.

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

我想要完成的是基于它们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);

}
Run Code Online (Sandbox Code Playgroud)

片段着色器

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

}
Run Code Online (Sandbox Code Playgroud)

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

如果您使用wasd移动,您可以看到颜色不会保留在原位.但是,我想要他们.

nee*_*eeh 7

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));
Run Code Online (Sandbox Code Playgroud)

检查这个小提琴.


注意

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

将坐标定位到颜色坐标