4

我的 Three.js 应用程序中有一个简单的着色器,可以将屏幕染成红色。但是,我想将给定世界位置右侧的所有像素着色为不同的颜色。

我已经看到一些 建议使用的答案varying vec4 worldCoord = gl_ModelViewMatrix * gl_Vertex;,但是由于 WebGL 使用 GLSLES,所以我无法使用 gl_Vertex 等变量。


顶点着色器

<script type="x-shader/x-vertex" id="vertexshader">
    #ifdef GL_ES
    precision highp float;
    #endif

    void main()
    {
        gl_Position = projectionMatrix * modelViewMatrix * vec4(position,1.0);
    }
</script>

片段着色器

<script type="x-shader/x-fragment" id="fragmentshader">
    #ifdef GL_ES
    precision highp float;
    #endif

    float worldX = 10.0; //Or some other position in the WebGL world

    void main()
    {
        if(gl_FragCoord.x > worldX) //FragCoord gives me coordinates relative to the screen
        {
            gl_FragColor = vec4(0.0, 1.0, 0.0, 1);
        }

        else
        {
            gl_FragColor = vec4(1.0, 0.0, 0.0, 1);
        }
    }
</script>

问:如何使用 Three.js 将像素的位置转换为 WebGL 中的世界位置?


4

1 回答 1

1

来自 WestLangley 的 Fiddle 的答案在这里:http: //jsfiddle.net/ST4aM/2/


顶点着色器

<script type="x-shader/x-vertex" id="vertexshader">
    #ifdef GL_ES
    precision highp float;
    #endif

    varying float x;
    varying float y;
    void main()
    {
        gl_Position = projectionMatrix * modelViewMatrix * vec4(position,1.0);
        x = position.x;
        y = position.y;
    }
</script>

片段着色器

<script type="x-shader/x-fragment" id="fragmentshader">
    #ifdef GL_ES
    precision highp float;
    #endif

    varying float x;
    varying float y;

    void main()
    {
        if(x > somePosition)
        {
            gl_FragColor = vec4(0.0, 1.0, 0.0, 1);
        }

        else
        {
            gl_FragColor = vec4(1.0, 0.0, 0.0, 1);
        }
    }
</script>

于 2013-12-01T02:27:57.503 回答