8

I have a shader with a _color uniform and a sampler. Now I want to draw with _color ONLY if the sampler was not set. Is there any way to figure that our within the shader? (Unfortunately the sampler returns 1,1,1,1 when not assigned, which makes mixing it via alpha impossible)

pixartist
  • 1,137
  • 2
  • 18
  • 40

3 Answers3

7

You cannot do that. The sampler is an opaque handle which just references a texture unit. I'm not sure if the spec guarantees that (1,1,1,1) when sampling from a unit where no texture is bound, or if that is undefined behavior.

What you can do is just use another uniform to switch betwenn using the sampler or the uniform color, or just use different shaders and switch between those. There are also the possibilities of subprograms here, but I don't know if that would be the right appraoch for such a simple problem.

derhass
  • 43,833
  • 2
  • 57
  • 78
3

I stumbled over this question trying to solve a similar problem.

Since GLSL 4.30

int textureQueryLevels( gsamplerX sampler);

Is a build-in function. In the GLSL spec. p. 151 it says

The value zero will be returned if no texture or an incomplete texture is associated with sampler.

In the OpenGL-Forms I found an entry to this question suggesting to use

ivecY textureSize(gsamplerX sampler,int lod);

and testing if the texture size is greater than zero. But this is, to my understanding, not covered by the standard. In the section 11.1.3.4 of the OpenGL specification it is said that

If the computed texture image level is outside the range [levelbase,q], the results are undefined ...

Edit: I just tried this method on my problem and as it turns out nvidia has some issues with this function, resulting in a non zero value when no texture is bound. (See nvidia bug report from 2015)

22-42-7
  • 161
  • 3
-3

sampler2d affects x y and z so if check for those with the parametric w as fourth parameter u can check if u gave in texture

vec4 texturecolor ;
texturecolor=texture2D(sampler, uv)*vec4(color,1.0);
if( texturecolor == vec4(0,0,0,1))
{
     texturecolor = vec4(color,1.0);
}
  • 1
    No, this does not check whether a texture is available, it checks for the texture OR color being black. – derhass Dec 11 '20 at 16:53