GLSL中对sampler2D调用'texture'函数会导致整个屏幕变灰。

3

我正在尝试在片元着色器中同时使用samplerBuffersampler2D

仅使用samplerBuffer时,它可以正常工作,代码如下:

#version 460
out vec4 FragColor;
in vec2 texcoord;

uniform sampler2D background;
uniform samplerBuffer OctreeData;

...

void main()
{    
    Ray ray = initRay();
    /*this function does raytraycing in octree and retrieves data
    from samplerBuffer using texelFetch function.*/
    Contact res = iterativeHitNodes(ray);

    if(res.hit)
      FragColor = assignNodeColor(res); //sets color of the node
    else
      FragColor = getBackground(origin, ray);
}

如果我在 main 函数的开头添加 FragColor = texture(background, texcoord.xy); return; 这行代码,它就能成功读取图像并显示出来。(A)

但当在 getBackground 函数中调用 texture 时,会显示灰色屏幕。结果发现,着色器根本没有起作用——即使我有意加载更多的模型,帧率也保持不变。但是没有着色器编译错误。

最大的“问题”是,即使从未调用 texture,屏幕仍然保持灰色。(B) 例如,当 backgroundType 始终为0且 getBackground 函数如下所示:

vec3 getBackground(vec3 from, vec3 direction)
{
    if(backgroundType == 0)
        return getSkyBackground(from, direction);
    else if(backgroundType == 1)
    {
        return texture(background, texcoord.xy).xyz;
    }

    return vec3(0);
}

看起来调用 texture 函数会丢弃片段。

P.S. 在调试模式下它的工作方式是正确的。由于某种原因,这个问题出现在发布模式中。

P.P.S. 大部分着色器代码在https://pastebin.com/SWCQ9HUw中。

1个回答

2
查看OpenGL Shading Language 4.60规范(HTML)-纹理函数
一些纹理函数(非“Lod”和非“Grad”版本)可能需要隐式导数。在非均匀控制流和非片段着色器纹理获取中,隐式导数是未定义的。
如果您正在使用纹理和{{link2:texture}}进行纹理查找,请确保调用组中的所有调用执行相同的控制流路径:
vec3 getBackground(vec3 from, vec3 direction, vec3 backgroundColor)
{
    if (backgroundType == 0)
        return getSkyBackground(from, direction);
    else if (backgroundType == 1)
        return backgroundColor;

    return vec3(0);
}

void main()
{
    vec3 backgroundColor = texture(background, texcoord.xy).xyz;
    
    Ray ray = initRay();
    /*this function does raytraycing in octree and retrieves data
    from samplerBuffer using texelFetch function.*/
    Contact res = iterativeHitNodes(ray);

    if(res.hit)
      FragColor = assignNodeColor(res); //sets color of the node
    else
      FragColor = getBackground(origin, ray, backgroundColor);
}

那就意味着我们不应该在分支条件中使用对 texture 的调用?但是如果所有分支都有对它的调用(可能具有不同的参数),那就没问题了? - Beko
1
@Beko:“如果所有分支都调用它(可能具有不同的参数),那么可以吗?” - 不行。在分支中计算纹理坐标,但在统一控制流中进行查找。 - Rabbid76
@Rabbid76 这次发现着色器在调用iterativeHitNodes(其中调用了texelFetch)后停止运行。如果我将其删除,则即使存在分支,texture似乎也能正常工作。 - Dr.Neo

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接