Search code examples
openglgraphicsglsltexturesvoxel

Are vertices getting discarded during rasterization and if so how to prevent it?


I am attempting to create a 2D pixelation of the stanford dragon, which I'll later extend to a 3D voxelazation.

The ideal output looks like this:

enter image description here

This image is generated using the following geometry shader:

#version 440

layout (triangles) in;
layout (triangle_strip, max_vertices=136) out;

in vec3 v_pos[];
in vec3 v_norm[];
in vec2 v_uv[];

out vec3 f_pos;
out vec3 f_norm;
out vec2 f_uv;

void main()
{
    vec3 side1 = v_pos[0] - v_pos[1];
    vec3 side2 = v_pos[1] - v_pos[2];

    vec3 tNorm = abs(cross(side1,side2));
    for(uint  i=0; i<3; i++)
    {
        f_pos = v_pos[i]/10;
        f_norm = v_norm[i];
        f_uv = v_uv[i];
        if(tNorm.x>tNorm.y && tNorm.x>tNorm.z)
        {
            gl_Position = vec4(f_pos.y, f_pos.z, 0, 1);
        }
        else if(tNorm.y>tNorm.x && tNorm.y>tNorm.z)
        {
            gl_Position = vec4(f_pos.x, f_pos.z, 0, 1);
        }
        else
        {
            gl_Position = vec4(f_pos.x, f_pos.y, 0, 1);
        }
        EmitVertex();
    }
    EndPrimitive();
}

And fragment shader:

#version 440

in vec3 f_pos;
in vec3 f_norm;
in vec2 f_uv;

uniform layout(binding=0, rgba8) image3D image;

out vec4 fragment_color;

void main()
{
    imageStore(image, ivec3(f_pos.xy*50 + vec2(100),0), vec4(1,0,1,1));

    fragment_color = vec4(1,1,1,0);
}

Howver this creates a really small dragon, the full texture that I created looks like this:

enter image description here

I thus tried to scale the dragon by a smaller factor to make a bigger image, this however results in the following image for a division factor of 3 (f_pos = v_pos[i]/3;):

enter image description here

As you can see, most of the dragon is there, but there's a lot of holes.

I beleive this happens because some of the vertices calculated in the geometry shader end outside of the (-1,1) valid coordinate range and thus get discarded, creating the holes.

is there a way to instruct the shaders to not discard vertices outside of said range during rasterization?


Solution

  • Shaders do not discard vertices; the post-transform rendering stage does. It is a fundamental part of how rendering works, and you cannot simply turn it off if it is inconvenient.

    You have to generate primitives that are within the bounds of clip-space. If you want the effect of a bigger clip space, then you have to scale things down before rasterization and reverse the scaling in your fragment shader.