신준섭
신준섭

Reputation: 33

OpenGL, GLSL fragment shader can't read Sampler2D texture

I'm currently using OpenGL for my project, and struggling on sending texture data to sampler2D.

I want to read a texture at fragment shader as a mask, but when I get my pixel value using texelFetch, I can only get vec4(0, 0, 0, 1).

Here is my code.

In my initialization:

#pragma region mask_creation

glActiveTexture(GL_TEXTURE0);
GLuint mask_texture;
glGenTextures(1, &mask_texture);
glBindTexture(GL_TEXTURE_2D, mask_texture);

constexpr auto channel = 4;
constexpr size_t size = width * height * channel;
auto texture_data =  new float[size];

for (auto i = 0; i < size; ++i) {
    texture_data[i] = 0.7f;
}

glTexSubImage2D(GL_TEXTURE_2D,
    0, 
    0, 0, 
    width, height,
    GL_RGBA, 
    GL_FLOAT, 
    texture_data);

delete[] texture_data;

glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);

GLuint mask_ID = glGetUniformLocation(programID, "mask");

In rendering (which is in while(true) loop):

glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, mask_texture);
glUniform1i(mask_ID, 0);

in my fragment shader

bool is_masked = (mask_val.x > 0.5) && (mask_val.y > 0.5) && (mask_val.z > 0.5);
if (original_depth < depth_threshold) {
    vec3 N = normalize(fs_in.N);
    vec3 L = normalize(fs_in.L);
    vec3 V = normalize(fs_in.V);

    vec3 R = reflect(-L, N);

    vec3 diffuse = max(dot(N, L), 0.0) * diffuse_albedo;
    vec3 specular = pow(max(dot(R, V), 0.0), specular_power) * specular_albedo;

    color = vec4(diffuse + specular, 1.0);
}
else {
    if (is_masked) {
        color = vec4(0, 0, 0, 1);
    }
    else {
        vec3 N = normalize(fs_in.N);
        vec3 L = normalize(fs_in.L);
        vec3 V = normalize(fs_in.V);

        vec3 R = reflect(-L, N);

        vec3 diffuse = max(dot(N, L), 0.0) * diffuse_albedo;
        vec3 specular = pow(max(dot(R, V), 0.0), specular_power) * specular_albedo;

        color = vec4(diffuse + specular, 1.0);
    }
}

I guess the texture hasn't been sent to fragment shader, and when I test ..

vec4 mask_val = texelFetch(mask, ivec2(gl_FragCoord.xy), 0);

if (mask_val.x == 0 && mask_val.y == 0 && mask_val.z == 0 && mask_val.w == 1) {
    color = vec4(1, 1, 1, 1);
}

I get a white circle (which my modeling is a sphere).

Upvotes: 1

Views: 560

Answers (1)

Rabbid76
Rabbid76

Reputation: 210928

The data store of the texture image is not defined. To define a 2 dimensional texture image you would have to call glTexImage2D.
glTexSubImage2D initializes the data in a region of the texture image only.

glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0, GL_RGBA, GL_FLOAT, texture_data);

Note, glTexImage2D also specifies the internal format of the texture data. e.g it is possible to use a sized internal format (3rd parameter) such as GL_RGBA8 or GL_RGBA32F.

Upvotes: 1

Related Questions