A cheat sheet on matrices in the shader

This is not a useful snippet. However, this reveals the essence of the necessary matrices to transfer to the shader for rendering the object.

from direct.showbase.ShowBase import ShowBase
from panda3d.core import Shader

class Game(ShowBase):
    def __init__(self):
        ShowBase.__init__(self)

        base.disable_mouse()
        base.camera.set_pos(0, -5, 0)

        self.model = loader.load_model('box')
        self.model.set_scale(1, 1, 2)
        self.model.set_hpr(0, 0, 45)
        self.model.reparent_to(render)
        self.model.set_shader(Shader.load(Shader.SL_GLSL, vertex = "vert.glsl", fragment = "frag.glsl"))

        p3d_model_matrix = self.model.get_mat(render)
        model_matrix = p3d_model_matrix.y_to_z_up_mat()
        view_matrix = self.model.get_mat(camera)
        projection_matrix = base.cam.node().get_lens().get_projection_mat()

        self.model.set_shader_input("model_matrix", model_matrix)
        self.model.set_shader_input("view_matrix", view_matrix)
        self.model.set_shader_input("projection_matrix", projection_matrix)

app = Game()
app.run()

vert.glsl

#version 150

//uniform mat4 p3d_ModelViewProjectionMatrix;

//uniform mat4 p3d_ModelMatrix;
//uniform mat4 p3d_ViewMatrix;
//uniform mat4 p3d_ProjectionMatrix;

uniform mat4 model_matrix;
uniform mat4 view_matrix;
uniform mat4 projection_matrix;

in vec4 p3d_Vertex;
in vec2 p3d_MultiTexCoord0;

out vec2 texcoord;

void main() {

    //gl_Position =  p3d_ModelViewProjectionMatrix * p3d_Vertex;
    //gl_Position =  p3d_ProjectionMatrix * p3d_ViewMatrix * p3d_ModelMatrix * p3d_Vertex;
    gl_Position =  projection_matrix * view_matrix * model_matrix * p3d_Vertex;

    texcoord = p3d_MultiTexCoord0;
}

frag.glsl

#version 150

uniform sampler2D p3d_Texture0;

in vec2 texcoord;
out vec4 p3d_FragColor;

void main() {
  vec4 color = texture(p3d_Texture0, texcoord);
  p3d_FragColor = color.bgra;
}

At the moment, using p3d_ModelViewProjectionMatrix introduces ambiguity, since shader textbooks usually use three matrices. This example also shows how you can get these matrices yourself in Panda3D.

2 Likes