Billboarding sphere labels in OpenGL

Viewed 116

I am new to OpenGL, so question could be quite silly. I am trying to write molecule visualizer. Atoms are rendered as SphereImpostors. It is implemented according to Lies and Impostors Tutorial. Labels are rendered as bitmap textures generated from TrueType font.

The vertex shader is written as follows:

#version 330

uniform mat4 Model;
uniform mat4 Projection;

in vec3  sphere_position;
in float sphere_radius;
in vec4  sphere_color;
in vec2  texCoords;

out vec4 color;
out vec2 TexCoords;

void main()
{

    vec4 real_coords = Model*vec4(sphere_position, 1.0);
    vec4 outer = 0.5*Projection*vec4(sphere_radius, sphere_radius, real_coords.z, 1.0);

    float apply = -outer.x/3;

    vec4 shift;
    switch(gl_VertexID % 4)
    {
    case 0:
        shift = vec4(-outer.x, -outer.y, apply, 0.);
        break;
    case 1:
        shift = vec4( outer.x, -outer.y, apply, 0.);
        break;
    case 2:
        shift = vec4( outer.x,  outer.y, apply, 0.);
        break;
    case 3:
        shift = vec4(-outer.x,  outer.y, apply, 0.);
        break;
    }

    TexCoords = texCoords;
    color = sphere_color;
    gl_Position = Projection*Model*vec4(sphere_position, 1.0) + shift;
}

Fragment shader is very simple

#version 330

in vec4 color;
in vec2 TexCoords;

uniform sampler2D myTexture;


void main()
{
    gl_FragColor = vec4(1.0, 1.0, 1.0, texture(myTexture, TexCoords).r)*color;
}

The problem is shown in Figure enter image description here

Label textures overlay the cylinders (see marked with blue). It just means that I do not estimate Z-shift correctly. The futher sphere is, the bigger shift must be. The multiplier is found empirically.

My concept was to find the Z coordinate of the sphere in World coordinates

vec4 real_coords = Model*vec4(sphere_position, 1.0);

compute the sphere radius at this Z coordinate

Projection*vec4(sphere_radius, sphere_radius, real_coords.z, 1.0);

and then use it as a shift. Such approach is incorrect according to given picture. I have read a lot of tutorials, but my understanding suffers from poor math and spatial imagination. How can I estimate correct shift for the label it to be always on the surface of the sphere and does not overlay the part of the cylinder?

In the commerial visualizer, everything is fine with labels (since it works very fast, my assumption that spheres are also rendered as impostors).

enter image description here

0 Answers
Related