• Advertisement
Sign in to follow this  

OpenGL Quick texture array question

This topic is 1123 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

Generally, my method for creating/using texture arrays works fine. However, I've noticed that the use of arrays seemingly negates my ability to use any textures that are not part of the array, even if loaded separately. Specifically, I'm trying to access my depth texture for a shadow map. If I bind the diffuse/normal/specular maps individually, and not part of the array, things render as expected. If I bind using an array, the shadow map is not accessible. 

 

I'm wondering if binding the array overrides the non-arrayed shadow map or if I should be calling things differently.

 

I'm likely making a small mistake here, but is there a way to use both in a shader? The opengl docs don't mention this scenario.

 

pseudo-code example:

//binding
//shadow map
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, depthTexture);
glUniform1i(shadowMapID, 0);

//diffuse image
glActiveTexture(GL_TEXTURE1);
glBindTexture(GL_TEXTURE_2D_ARRAY, texturearray);
glUniform1i(LayerNumID1, imageIndex.x);

//normal map
glActiveTexture(GL_TEXTURE2);
glBindTexture(GL_TEXTURE_2D_ARRAY, texturearray);
glUniform1i(LayerNumID2, imageIndex.y);

//specular map
glActiveTexture(GL_TEXTURE3);
glBindTexture(GL_TEXTURE_2D_ARRAY, texturearray);
glUniform1i(LayerNumID3, imageIndex.z);

in fragment shader:

uniform sampler2DShadow shadowMap;
uniform sampler2DArray DiffuseTextureSampler;
uniform sampler2DArray NormalTextureSampler;
uniform sampler2DArray SpecularTextureSampler;
uniform int layer_index1;
uniform int layer_index2;
uniform int layer_index3;

Share this post


Link to post
Share on other sites
Advertisement

The general idea is certainly possible, buts its hard to tell from pseudo-code, youre binding "texturearray" to three different texture units, and using three different samplers in the shader? plus passing a 0 to the shader for the shadow uniform, not sure if you are actually doing that or this is just a mistake in the example code.

But in general you should be able to set active texture, bind, set active texture + 1, bind, etc.

Share this post


Link to post
Share on other sites

Ugh, have I been wrong about that all along? I was under the impression that that value was for the texture unit. I.e. if it's GL_TEXTURE0, then you bind 0, if it's GL_TEXTURE1, then you bind 1, unless it's an array, then you bind the index location \. 

I've looked at the opengl docs multiple times over this, but they seem...less than helpful in this instance. Though, perhaps I'm just not following the terminology correctly:

v0, v1, v2, v3
For the scalar commands, specifies the new values to be used for the specified uniform variable.

To your other comment. I've always just used the 3 samplers (my shaders are relatively simple) for diffuse/specular/normals. I gather from your comments it's possible to just bind one sampler array, and index it in the shader similarly as an array. I'll incorporate that. It definitely seems ideal.

Edited by Misantes

Share this post


Link to post
Share on other sites

As NumberXaero suggested, you bind the array to one location, say 1:

glActiveTexture(GL_TEXTURE1);
glBindTexture(GL_TEXTURE_2D_ARRAY, texturearray);
glUniform1i(location, 1);

In shaders you use

uniform sampler2DArray arrayTex;

/* ... */

void main()
{
 float index = 0.0;
 vec4 color = texture(arrayTex, vec3(texCoord.xy, index));
 /* ... */
}

The third component of the second argument to texture is the array index. Arrays are great for overcoming texture image unit limitations, although the layers will need to have the same properties

Share this post


Link to post
Share on other sites

Ok, I get that, and other than using multiple id's in the shader, I'm using them correctly, I believe. But, to the other question, when binding a single texture, the second value for the glUniform1i(), what actually goes there, if not the texture number (again, say 0 for GL_TEXTURE0)?

Share this post


Link to post
Share on other sites

Ok, I get that, and other than using multiple id's in the shader, I'm using them correctly, I believe. But, to the other question, when binding a single texture, the second value for the glUniform1i(), what actually goes there, if not the texture number (again, say 0 for GL_TEXTURE0)?

 

The value for glUniform1i() maps to the active texture unit, i.e., glUniform1i(textureUniformLoc, 4); corresponds to glActiveTexture(GL_TEXTURE4); This works the same for all types of textures. Only difference is how you access the texture data in the shaders. I usually set the uniform once during initialization when setting up the shaders.

Share this post


Link to post
Share on other sites

If this is what youre doing, as jmakitalo posted

 

As NumberXaero suggested, you bind the array to one location, say 1:

glActiveTexture(GL_TEXTURE1);
glBindTexture(GL_TEXTURE_2D_ARRAY, texturearray);
glUniform1i(location, 1);

In shaders you use

uniform sampler2DArray arrayTex;

/* ... */

void main()
{
 float index = 0.0;
 vec4 color = texture(arrayTex, vec3(texCoord.xy, index));
 /* ... */
}

The third component of the second argument to texture is the array index. Arrays are great for overcoming texture image unit limitations, although the layers will need to have the same properties

 

 

then thats correct. You generate an id and it goes to bind, you set an activate texture unit before bind, and pass that active index to the sampler location. Assuming

"texturearray" isnt a variable being changed between the bind calls, and assuming you are using three arrays containing the textures grouped by use

//binding
//shadow map
glActiveTexture(GL_TEXTURE0);                  // unit 0
glBindTexture(GL_TEXTURE_2D, depthTexture);    // GenTexture id
glUniform1i(shadowMapSamplerUniformLocation, 0);     // sampler (index)

//diffuse image
glActiveTexture(GL_TEXTURE1);                               // unit 1
glBindTexture(GL_TEXTURE_2D_ARRAY, texturearrayDiffuse);    // GenTexture id, bound to 1
glUniform1i(diffuseArraySamplerUniformLocation, 1);        // sampler (index)
glUniform1i(LayerNumID1, imageIndex.x);       // the diffuse you want to access I take it?

//normal image
glActiveTexture(GL_TEXTURE2);                               // unit 2
glBindTexture(GL_TEXTURE_2D_ARRAY, texturearrayNormal);    // GenTexture id, bound to 2
glUniform1i(normalArraySamplerUniformLocation, 2);        // sampler (index)
glUniform1i(LayerNumID2, imageIndex.y);       // the normal you want to access I take it?

// spec......

if "texturearray" is a big list of diffuse/normal/spec textures altogether then the shader would have a single, uniform sampler2DArray, rather then 3, and setup

glActiveTexture(GL_TEXTURE1); // unit 1
glBindTexture(GL_TEXTURE_2D_ARRAY, texturearray); // GenTexture id, bound to 1, the only array
glUniform1i(arraySamplerUniformLocation, 1); // sampler (index)
glUniform1i(LayerNumID1, imageIndex.x); // the diffuse you want to access?
glUniform1i(LayerNumID2, imageIndex.y); // the normal you want to access?
glUniform1i(LayerNumID3, imageIndex.z); // the spec you want to access?

Short version, the sampler uniform needs the texture unit index.

Share this post


Link to post
Share on other sites

In other words:

 

One has to make a distinction between the texture object name (the number generated by glGenTexture, and used as 2nd parameter to glBindTexture, for example), and the texture unit address (the trailing number at the symbolic constant when calling glActiveTexture or the 2nd parameter of glUniform1i in your case). The former names the texture, the latter the texture unit.

 

A texture unit is a part of the GPU hardware. From the outside, you bind a texture object to the texture unit, so saying "when this texture unit is accessed, then the returned data should come from this texture object"; that is done in 2 steps, first by glActiveTexture to specify the texture unit, then by glBindTexture to specify the texture object. Then, within your shader script, you have a sampler. The sampler works on a texture unit. So you need to call glUniform to specify which texture unit should be used by the specific sampler.

 

In the end you have an indirect access of the sampler onto the texture data, with the texture unit in-between:

          texture object --bound_to--> texture unit <--read_from-- sampler

Share this post


Link to post
Share on other sites

The second number to the call to glUniform1i is the texture unit the texture for the sampler is bound to. You cannot bind individual layers of an array texture to an sampler( just don't make any sense ). Also, I would recommend downloading the GL specification for the version you are using for reference. Its very handy to have whenever you need a little clarification.

Share this post


Link to post
Share on other sites

Hm, I think due to a misunderstanding and posting pseudo-code, we're becoming a little off-base here. I think there was some initial confusion between us about binding 0 to GL_TEXTURE0, which I think has been cleared up. And, while I wasn't aware you could use a single sampler for the array, that seems relatively straightforward.

 

However, the initial problem still exists where I'm unable to use the array with the depth texture.

 

For clarity here are the bind calls and shader (after adjustments for the single sampler, thank you)

glActiveTexture(GL_TEXTURE0); 
glBindTexture(GL_TEXTURE_2D, depthTexture); 
glUniform1i(ShadowMapID, 0); 

glActiveTexture(GL_TEXTURE1);
glBindTexture(GL_TEXTURE_2D_ARRAY, texturearray);
glUniform1i(ArrayID, 1);
glUniform1i(LayerNumID1, imageIndex.x);//array index numbers
glUniform1i(LayerNumID2, imageIndex.y);
glUniform1i(LayerNumID3, imageIndex.z);

fragment shader:

uniform sampler2DShadow shadowMap; //corresponds to ShadowMapID 
uniform sampler2DArray ArraySampler; //ArrayID
uniform int layer_index1;
uniform int layer_index2;
uniform int layer_index3;
void main()
{
    vec3 MaterialDiffuseColor = texture( ArraySampler,vec3(UV, layer_index1) ).rgb;
    visibility -= 0.3*(1.0-texture( shadowMap, vec3(ShadowCoord.xy + poissonDisk[index]/700.0,  (ShadowCoord.z-bias)/ShadowCoord.w) ));

Which doesn't work. The shadow map doesn't seem to be accessible. Again, the texture array on its own is working fine, and the shadow map, when bound with individual textures, works fine as well. But, when I try to use the shadow map, while using an array for the other textures, things aren't rendering properly. To be clear though, there are no errors reported, but the shader is clearly not reading the shadowmap correctly.

 

If this code looks relatively fine, then my issue is likely elsewhere.

Edited by Misantes

Share this post


Link to post
Share on other sites


Which doesn't work. The shadow map doesn't seem to be accessible. Again, the texture array on its own is working fine, and the shadow map, when bound with individual textures, works fine as well. But, when I try to use the shadow map, while using an array for the other textures, things aren't rendering properly. To be clear though, there are no errors reported, but the shader is clearly not reading the shadowmap correctly.
 
If this code looks relatively fine, then my issue is likely elsewhere.

 

The code looks fine to me as far as I can interpret it without further information. Are you sure that your uniform ids are properly resolved? Are you binding the shaders before calling glUniform etc?

Share this post


Link to post
Share on other sites

Are you setting tex parameter GL_TEXTURE_COMPARE_MODE and GL_TEXTURE_COMPARE_FUNC for the shadow map texture when using it with sampler2DShadow?

What GL context and GLSL version are you using?

Share this post


Link to post
Share on other sites

Are you setting tex parameter GL_TEXTURE_COMPARE_MODE and GL_TEXTURE_COMPARE_FUNC for the shadow map texture when using it with sampler2DShadow?

What GL context and GLSL version are you using?

I'm calling:

glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_COMPARE_FUNC, GL_LEQUAL);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_COMPARE_MODE, GL_COMPARE_R_TO_TEXTURE);

when creating the depth texture, but only then.

 

 


The code looks fine to me as far as I can interpret it without further information. Are you sure that your uniform ids are properly resolved? Are you binding the shaders before calling glUniform etc?

Yeah, I've triple checked the ids now, and am binding the shaders right before binding the uniforms.

 

Alright, so I think I must be goofing elsewhere. Thanks for the advice and effort everyone. If I come across more information on where I'm going wrong, I'll make a new thread.

 

Edit*

Yup. In adapting the changes, I made a mistake with an inherited class, and hadn't updated the virtual function that bound the layer indexes to the shader. >,<

Stupid.

 

Anyhow, I still appreciate the help from everyone. Looks like I was still going about things the wrong way (multiple samplers, not binding the sampler to the texture unit, etc), so I definitely learned a lot.

Cheers :)

Edited by Misantes

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement
  • Advertisement
  • Popular Tags

  • Advertisement
  • Popular Now

  • Similar Content

    • By QQemka
      Hello. I am coding a small thingy in my spare time. All i want to achieve is to load a heightmap (as the lowest possible walking terrain), some static meshes (elements of the environment) and a dynamic character (meaning i can move, collide with heightmap/static meshes and hold a varying item in a hand ). Got a bunch of questions, or rather problems i can't find solution to myself. Nearly all are deal with graphics/gpu, not the coding part. My c++ is on high enough level.
      Let's go:
      Heightmap - i obviously want it to be textured, size is hardcoded to 256x256 squares. I can't have one huge texture stretched over entire terrain cause every pixel would be enormous. Thats why i decided to use 2 specified textures. First will be a tileset consisting of 16 square tiles (u v range from 0 to 0.25 for first tile and so on) and second a 256x256 buffer with 0-15 value representing index of the tile from tileset for every heigtmap square. Problem is, how do i blend the edges nicely and make some computationally cheap changes so its not obvious there are only 16 tiles? Is it possible to generate such terrain with some existing program?
      Collisions - i want to use bounding sphere and aabb. But should i store them for a model or entity instance? Meaning i have 20 same trees spawned using the same tree model, but every entity got its own transformation (position, scale etc). Storing collision component per instance grats faster access + is precalculated and transformed (takes additional memory, but who cares?), so i stick with this, right? What should i do if object is dynamically rotated? The aabb is no longer aligned and calculating per vertex min/max everytime object rotates/scales is pretty expensive, right?
      Drawing aabb - problem similar to above (storing aabb data per instance or model). This time in my opinion per model is enough since every instance also does not have own vertex buffer but uses the shared one (so 20 trees share reference to one tree model). So rendering aabb is about taking the model's aabb, transforming with instance matrix and voila. What about aabb vertex buffer (this is more of a cosmetic question, just curious, bumped onto it in time of writing this). Is it better to make it as 8 points and index buffer (12 lines), or only 2 vertices with min/max x/y/z and having the shaders dynamically generate 6 other vertices and draw the box? Or maybe there should be just ONE 1x1x1 cube box template moved/scaled per entity?
      What if one model got a diffuse texture and a normal map, and other has only diffuse? Should i pass some bool flag to shader with that info, or just assume that my game supports only diffuse maps without fancy stuff?
      There were several more but i forgot/solved them at time of writing
      Thanks in advance
    • By RenanRR
      Hi All,
      I'm reading the tutorials from learnOpengl site (nice site) and I'm having a question on the camera (https://learnopengl.com/Getting-started/Camera).
      I always saw the camera being manipulated with the lookat, but in tutorial I saw the camera being changed through the MVP arrays, which do not seem to be camera, but rather the scene that changes:
      Vertex Shader:
      #version 330 core layout (location = 0) in vec3 aPos; layout (location = 1) in vec2 aTexCoord; out vec2 TexCoord; uniform mat4 model; uniform mat4 view; uniform mat4 projection; void main() { gl_Position = projection * view * model * vec4(aPos, 1.0f); TexCoord = vec2(aTexCoord.x, aTexCoord.y); } then, the matrix manipulated:
      ..... glm::mat4 projection = glm::perspective(glm::radians(fov), (float)SCR_WIDTH / (float)SCR_HEIGHT, 0.1f, 100.0f); ourShader.setMat4("projection", projection); .... glm::mat4 view = glm::lookAt(cameraPos, cameraPos + cameraFront, cameraUp); ourShader.setMat4("view", view); .... model = glm::rotate(model, glm::radians(angle), glm::vec3(1.0f, 0.3f, 0.5f)); ourShader.setMat4("model", model);  
      So, some doubts:
      - Why use it like that?
      - Is it okay to manipulate the camera that way?
      -in this way, are not the vertex's positions that changes instead of the camera?
      - I need to pass MVP to all shaders of object in my scenes ?
       
      What it seems, is that the camera stands still and the scenery that changes...
      it's right?
       
       
      Thank you
       
    • By dpadam450
      Sampling a floating point texture where the alpha channel holds 4-bytes of packed data into the float. I don't know how to cast the raw memory to treat it as an integer so I can perform bit-shifting operations.

      int rgbValue = int(textureSample.w);//4 bytes of data packed as color
      // algorithm might not be correct and endianness might need switching.
      vec3 extractedData = vec3(  rgbValue & 0xFF000000,  (rgbValue << 8) & 0xFF000000, (rgbValue << 16) & 0xFF000000);
      extractedData /= 255.0f;
    • By Devashish Khandelwal
      While writing a simple renderer using OpenGL, I faced an issue with the glGetUniformLocation function. For some reason, the location is coming to be -1.
      Anyone has any idea .. what should I do?
    • By Andrey OGL_D3D
      Hi all!
      I try to use the Sun shafts effects via post process in my 3DEngine, but i have some artefacts on final image(Please see attached images).
      The effect contains the following passes:
      1) Depth scene pass;
      2) "Shafts pass" Using DepthPass Texture + RGBA BackBuffer texture.
      3) Shafts pass texture +  RGBA BackBuffer texture.
      Shafts shader for 2 pass:
      // uniform sampler2D FullSampler; // RGBA Back Buffer uniform sampler2D DepthSampler; varying vec2 tex; #ifndef saturate float saturate(float val) {     return clamp(val, 0.0, 1.0); } #endif void main(void) {     vec2 uv = tex;     float sceneDepth = texture2D(DepthSampler, uv.xy).r;     vec4  scene        = texture2D(FullSampler, tex);     float fShaftsMask     = (1.0 - sceneDepth);     gl_FragColor = vec4( scene.xyz * saturate(sceneDepth), fShaftsMask ); } final shader:
      // uniform sampler2D FullSampler; // RGBA Back Buffer uniform sampler2D BlurSampler; // shafts sampler varying vec4 Sun_pos; const vec4    ShaftParams = vec4(0.1,2.0,0.1,2.0); varying vec2 Tex_UV; #ifndef saturate  float saturate(float val) {     return clamp(val, 0.0, 1.0); } #endif vec4 blendSoftLight(vec4 a, vec4 b) {   vec4 c = 2.0 * a * b + a * a * (1.0 - 2.0 * b);   vec4 d = sqrt(a) * (2.0 * b - 1.0) + 2.0 * a * (1.0 - b);       // TODO: To look in Crysis what it the shit???   //return ( b < 0.5 )? c : d;   return any(lessThan(b, vec4(0.5,0.5,0.5,0.5)))? c : d; } void main(void) {     vec4 sun_pos = Sun_pos;     vec2    sunPosProj = sun_pos.xy;     //float    sign = sun_pos.w;     float    sign = 1.0;     vec2    sunVec = sunPosProj.xy - (Tex_UV.xy - vec2(0.5, 0.5));     float    sunDist = saturate(sign) * saturate( 1.0 - saturate(length(sunVec) * ShaftParams.y ));     sunVec *= ShaftParams.x * sign;     vec4 accum;     vec2 tc = Tex_UV.xy;     tc += sunVec;     accum = texture2D(BlurSampler, tc);     tc += sunVec;     accum += texture2D(BlurSampler, tc) * 0.875;     tc += sunVec;     accum += texture2D(BlurSampler, tc) * 0.75;     tc += sunVec;     accum += texture2D(BlurSampler, tc) * 0.625;     tc += sunVec;     accum += texture2D(BlurSampler, tc) * 0.5;     tc += sunVec;     accum += texture2D(BlurSampler, tc) * 0.375;     tc += sunVec;     accum += texture2D(BlurSampler, tc) * 0.25;     tc += sunVec;     accum += texture2D(BlurSampler, tc) * 0.125;     accum  *= 0.25 * vec4(sunDist, sunDist, sunDist, 1.0);           accum.w += 1.0 - saturate(saturate(sign * 0.1 + 0.9));     vec4    cScreen = texture2D(FullSampler, Tex_UV.xy);           vec4    cSunShafts = accum;     float fShaftsMask = saturate(1.00001 - cSunShafts.w) * ShaftParams.z * 2.0;              float fBlend = cSunShafts.w;     vec4 sunColor = vec4(0.9, 0.8, 0.6, 1.0);     accum =  cScreen + cSunShafts.xyzz * ShaftParams.w * sunColor * (1.0 - cScreen);     accum = blendSoftLight(accum, sunColor * fShaftsMask * 0.5 + 0.5);     gl_FragColor = accum; } Demo project:
      Demo Project
      Shaders for postprocess Shaders/SunShaft/
      What i do wrong ?
      Thanks!
       


  • Advertisement