如何在OpenGL 3.2中使用GL_TEXTURE_2D_ARRAY

时间:2012-09-11 14:29:44

标签: opengl glsl textures

所以我尝试了docs,但是我似乎无法使纹理2D数组工作。

-(GLint)buildTextureArray:(NSArray *)arrayOfImages
{
    GLImage *sample = [GLImage imageWithImageName:[arrayOfImages objectAtIndex:0] shouldFlip:NO]; //Creates a sample to examine texture width and height
    int width = sample.width, height = sample.height;
    GLsizei count = (GLsizei)arrayOfImages.count; 

    GLuint texture3D;
    glGenTextures(1, &texture3D);
    glBindTexture(GL_TEXTURE_2D_ARRAY, texture3D);

    glPixelStorei(GL_UNPACK_ROW_LENGTH, width);
    glPixelStorei(GL_UNPACK_ALIGNMENT, 1);

    glTexParameteri(GL_TEXTURE_2D_ARRAY,GL_TEXTURE_MIN_FILTER,GL_LINEAR_MIPMAP_LINEAR);
    glTexParameteri(GL_TEXTURE_2D_ARRAY,GL_TEXTURE_MAG_FILTER,GL_LINEAR);
    glTexParameteri(GL_TEXTURE_2D_ARRAY,GL_TEXTURE_WRAP_S,GL_REPEAT);
    glTexParameteri(GL_TEXTURE_2D_ARRAY,GL_TEXTURE_WRAP_T,GL_REPEAT);
    glTexImage3D(GL_TEXTURE_2D_ARRAY, 0, GL_RGBA8, width, height, count, 0, GL_BGRA, GL_UNSIGNED_INT_8_8_8_8_REV, NULL);

    int i = 0;
    for (NSString *name in arrayOfImages) //Loops through everything in arrayOfImages
    {
        GLImage *image = [GLImage imageWithImageName:name shouldFlip:NO]; //My own class that loads an image
        glTexSubImage3D(GL_TEXTURE_2D_ARRAY, 0, 0, 0, i, image.width, image.height, 1, GL_RGBA, GL_UNSIGNED_BYTE, image.data);
        i++;
    }
    return texture3D;
}

//Setting Uniform elsewhere
glBindTexture(GL_TEXTURE_2D_ARRAY, textureArray);
glUniform1i(textures, 0);    


//Fragment Shader
#version 150

in vec3 texCoords;

uniform sampler2DArray textures;

out vec3 color;

void main()
{
    color = texture(textures, texCoords.stp, 0).rgb;
}

我能够使用相同的纹理参数加载单个纹理,但我无法使用纹理2D数组。我得到的只是黑色纹理。为什么会这样?

2 个答案:

答案 0 :(得分:2)

glTexParameteri(GL_TEXTURE_2D_ARRAY,GL_TEXTURE_MIN_FILTER,GL_LINEAR_MIPMAP_LINEAR);

你的纹理实际上有mipmap。所以不要再告诉OpenGL它了。

此外, 始终 为您的纹理设置mipmap range parameters (GL_TEXTURE_BASE_LAYER and GL_TEXTURE_MAX_LAYER)。或者更好的是,使用texture storage to allocate your texture's storage,它会为你做。

答案 1 :(得分:0)

对于2d_array纹理'v'组成的texcoords从0高度变化,'w'从0深度变化(因为它表示图层)。尝试更改这些texcordinates。