How to implement a billboard?

I am currently drawing a plane (triangular strip) in the 3D world. Now I want to draw it like a billboard - so that the face is aligned with the camera.

This is the code:

#version 330 core

layout(points) in;
layout(triangle_strip, max_vertices=4) out;
out vec2 tex_coord;

uniform mat4x4 model;
uniform mat4x4 view;
uniform mat4x4 projection;

uniform float size = 1.0;

// texture coordinates
const vec2 texc[4] = vec2[] (vec2(0, 0),
                             vec2(0, 1),
                             vec2(1, 0),
                             vec2(1, 1));

void main() {
    // vertex offsets from the center point
    float asize = size / 2;
    vec4 offset[4] = vec4[] (vec4(-asize, 0.0, -asize, 0.0),
                             vec4(-asize, 0.0,  asize, 0.0),
                             vec4( asize, 0.0, -asize, 0.0),
                             vec4( asize, 0.0,  asize, 0.0));
    int i, j;
    for(i = 0; i < gl_in.length(); ++i) {
        for(j = 0; j < 4; ++j) {

            // vector coordinates
            vec4 vertexpos = (gl_in[i].gl_Position + offset[j]);
            vec4 position = projection * view * model * vertexpos;
            gl_Position = position;

            tex_coord = texc[j];
            EmitVertex();
        }
        EndPrimitive();
    }
}

Obviously, the exit is just a plane:

enter image description here

How to change the code to draw a plane as a billboard? I know that I need to calculate the coordinates of the vertices (in the inner loop) using the view matrix, but I cannot figure out how to do this.

+4
source share
1 answer

Add offsetafter the project gl_in[i].gl_Position:

int i, j;
for(i = 0; i < gl_in.length(); ++i) 
{
    vec4 centerpt = projection * view * model * gl_in[i].gl_Position;
    for(j = 0; j < 4; ++j) 
    {
        gl_Position = centerpt + offset[j];
        tex_coord = texc[j];
        EmitVertex();
    }
    EndPrimitive();
}
+3
source

Source: https://habr.com/ru/post/1528203/


All Articles