Three.js/GLSL - 将像素坐标转换为世界坐标 [英] Three.js/GLSL - Convert Pixel Coordinate to World Coordinate
问题描述
我的 Three.js 应用程序中有一个简单的着色器,它将屏幕着色为红色.但是,我想将给定世界位置右侧的所有像素着色为不同的颜色.
I have a simple shader in my Three.js application that colors the screen red. However, I want to color all pixels to the right of a given world position to to a different color.
我看过一些 答案 建议使用改变 vec4 worldCoord = gl_ModelViewMatrix * gl_Vertex;
,但由于 WebGL 使用 GLSLES,我无法使用 gl_Vertex 之类的变量.
I have seen some answers that suggest using varying vec4 worldCoord = gl_ModelViewMatrix * gl_Vertex;
, but since WebGL using GLSLES, variables like gl_Vertex are not available to me.
顶点着色器
<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 中的世界位置?
推荐答案
来自 WestLangley's Fiddle 的答案在这里:http://jsfiddle.net/ST4aM/2/.
Answer derived from WestLangley's Fiddle here: 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>
这篇关于Three.js/GLSL - 将像素坐标转换为世界坐标的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!