Sign in to follow this  

OpenGL Directional light and matrix issues

Recommended Posts

KaiserJohan    2317

I'm trying to implement basic directional lightning in OpenGL 3.3 by emulating the logic shown in this guide:


I do not understand what matrix to send to the vertex shader to use for calculating lightning effects. The guide says modelView matrix, but to me, and when I'm running the game, it dosn't make sense; when I orient myself in the world with mouse and keyboard, the lightning direction gets altered aswell!



Here's the items to which I fill my 'render queue', which contains all data needed to draw the models:


/* RenderItem definition */
    struct RenderItem
        VertexBufferPtr mVertexBuffer;
        const Vec4 mColor;
        const Mat4 mMVP;
        const Mat3 mMVMatrix;    // I used model-view matrix here, but I dont know really which one to use

        const Vec4 mLightIntensity;
        const Vec3 mDirToLight;

       // simply extracts all the struct data into one buffer to be uploaded as UniformBuffer to shader
        void CopyUniformData(std::vector<float>& buffer) const
            std::vector<float> colorValues = GetTypeValues(mColor);
            std::vector<float> mvpMatrixValues = GetTypeValues(mMVP);
            std::vector<float> mvMatrixValues = GetTypeValues(mMVMatrix);
            std::vector<float> lightIntensityMatrixValues = GetTypeValues(mLightIntensity);
            std::vector<float> dirToLightMatrixValues = GetTypeValues(mDirToLight);

            buffer.insert(buffer.end(), colorValues.begin(), colorValues.end());
            buffer.insert(buffer.end(), mvpMatrixValues.begin(), mvpMatrixValues.end());
            buffer.insert(buffer.end(), mvMatrixValues.begin(), mvMatrixValues.end());
            buffer.insert(buffer.end(), lightIntensityMatrixValues.begin(), lightIntensityMatrixValues.end());
            buffer.insert(buffer.end(), dirToLightMatrixValues.begin(), dirToLightMatrixValues.end());

        RenderItem(VertexBufferPtr vertexBuffer, const Vec4& color, const Mat4& mvp, const Mat3& mv, const Vec4& lightIntensity, const Vec3& dirToLight);



Here's where I create all the RenderItems for my renderqueue:


void Engine::CreateModelRenderables(const Model* model, const Mat4& viewMatrix, const Mat4& perspectiveMatrix, const Mat4& nodeTransform, std::vector<RenderItem>& renderQueue, const std::vector<LightPtr>& activeLights)
        const Mat4 modelMatrix = nodeTransform * model->mTransform;       // 'nodeTransform' is the SceneNodes transform, while model->mTransform is the models transform... so this gives the model-world matrix
        const Mat4 modelViewMatrix = viewMatrix * modelMatrix;
        const Mat4 modelViewProjMatrix = perspectiveMatrix * modelViewMatrix;

        // 'activelights' is a vector, but for now only one light is supported, so I just pick the first element

        // TODO: handle multiple lights
        BOOST_FOREACH(const Mesh& mesh, model->mMeshes)
            if (activeLights.size() >= 1)
                renderQueue.push_back(RenderItem(mesh.mVertexBuffer, Vec4(1.0f, 0.3f, 0.3f, 1.0f), modelViewProjMatrix, Mat3(....???....), activeLights.front()->mLightIntensity, activeLights.front()->mLightDirection));
                renderQueue.push_back(RenderItem(mesh.mVertexBuffer, Vec4(1.0f, 0.3f, 0.3f, 1.0f), modelViewProjMatrix, Mat3(....???....), Vec4(0.0f), Vec3(0.0f)));

        BOOST_FOREACH(const Model& childModel, model->mChildren)
            CreateModelRenderables(&childModel, viewMatrix, perspectiveMatrix, modelMatrix, renderQueue, activeLights);





for drawing, I just loop over the renderitems, update the UniformBuffer object and glDrawElements (vertexbuffer->render):


void OpenGLRenderer::DrawRenderables(const std::vector<RenderItem>& renderQueue)
        BOOST_FOREACH(const RenderItem& renderItem, renderQueue)





this is my vertex shader:


 const std::string gVertexShader =	"#version 330								                \n	\
                                                                                                    \n  \
                                        layout(std140) uniform DefaultUniform                       \n  \
                                        {                                                           \n  \
                                            vec4 Color;                                             \n  \
                                            mat4 MVPMatrix;                                         \n  \
                                            mat3 MVMatrix;                                          \n  \
                                                                                                    \n  \
                                            vec4 LightIntensity;                                    \n  \
                                            vec3 DirToLight;                                        \n  \
                                        };                                                          \n  \
                                                                                                    \n	\
                                        layout(location = 0) in vec3 vert_position;				    \n	\
                                        layout(location = 1) in vec3 vert_normal;					\n	\
                                        out vec4 frag_color;                                        \n	\
                                                                                                    \n	\
                                        void main()									                \n	\
                                        {											                \n	\
                                            gl_Position = MVPMatrix * vec4(vert_position, 1.0f);    \n  \
                                                                                                    \n  \
                                            vec3 normCamSpace = normalize(MVMatrix * vert_normal);  \n  \
                                            float angIncidence = dot(normCamSpace, DirToLight);     \n  \
                                            angIncidence = clamp(angIncidence, 0, 1);               \n  \
                                                                                                    \n  \
                                            frag_color = LightIntensity * Color * angIncidence;     \n  \
                                        }											                \n";



the fragment shader simply passes-through the frag_color..



SO, my question is, what matrix should the MVMatrix be in the vertex shader? The guide says the 'modelToCameraMatrix', which I suppose is my modelViewMatrix in Engine::CreateModelRenderables(), but I don't want the lights direction to change when I re-orient my camera!



EDIT: Here is my camera class used to generate the viewMatrix through getCameraTransform(), in case there might be something wrong there? 

I don't think so though, as I can move around in the world with WASD + mouse just as expected, its just the lightning that is wierd...


Camera::Camera() : mTranslation(0.0f), mHorizontalAngle(0.0f), mVerticalAngle(0.0f)

    void Camera::SetPosition(const Vec3& position)
        mTranslation = position;

    void Camera::TranslateCamera(const Vec3& translateVec)
        mTranslation += translateVec;
    void Camera::RotateCamera(const float offsetHorizontalAngle, const float offsetVerticalAngle)
        mHorizontalAngle += offsetHorizontalAngle;
        mVerticalAngle   += offsetVerticalAngle;

    Vec3 Camera::Forward() const
        Vec4 forward = Inverse(Orientation()) * Vec4(0, 0, 1, 1);

        return Vec3(forward);

    Vec3 Camera::Right() const
        Vec4 right = Inverse(Orientation()) * Vec4(-1, 0, 0, 1);

        return Vec3(right);

    Mat4 Camera::Orientation() const
        Quaternion rotation;
        rotation = AngleAxisToQuaternion(mVerticalAngle, Vec3(1.0f, 0.0f, 0.0f));
        rotation = rotation * AngleAxisToQuaternion(mHorizontalAngle, Vec3(0.0f, 1.0f, 0.0f));

        return QuaternionToMat4(rotation);

    Mat4 Camera::GetCameraTransform() const
        Mat4 viewMatrix(1.0f);
        viewMatrix = Orientation() * Translate(viewMatrix, mTranslation);

        return viewMatrix;
Edited by KaiserJohan

Share this post

Link to post
Share on other sites
KaiserJohan    2317

I added the camera class which is used to get the viewMatrix aswell, but I dont think that is the problem since I can navigate with keyboard and mouse naturally as in any FPS

Share this post

Link to post
Share on other sites
TheChubu    9446

Is your "dirToLight" vec3 in camera space?


I think you might have a dirToLight (an unit vector I guess) specified in word space, and since you're doing your lighting in camera space, you get weird lighting from it.


Since its an uniform, its better if you transform your dirToLight to camera space (MVMatrix * dirToLight) in the CPU and then pass it as an uniform to the GPU.

Share this post

Link to post
Share on other sites
KaiserJohan    2317

I don't want the light direction to change when I orient/move my camera around; that happens when I try to do lighting in camera space right?


EDIT: So I tried doing the lighting normalization in world space. So, the LightDir is unchanged (its specified in world space) and then as 'MVMatrix' I actually pass the 'modelMatrix', and otherwise the code is unchanged.

As a result, I see only light being applied when I increase the X-values of LightDir; changing Y and Z values dosn't cause any lightning whatsoever. Why could this be?

Edited by KaiserJohan

Share this post

Link to post
Share on other sites
KaiserJohan    2317

Alright, I solved it.


For those interested, I can do the lighting calculations in world space just fine if I supply a mat4 model-to-world matrix rather than a mat3 model-to-world matrix to the vertexshader. I believe it has something to do with translation, since the objects in question were translated away abit from the camera, but if anyone has a complete answer I would be happy to hear it. 



EDIT: One thing itches me though, why do people/guides do all lighting transformations in camera space rather than world space?

Edited by KaiserJohan

Share this post

Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this  

  • Similar Content

    • By Kjell Andersson
      I'm trying to get some legacy OpenGL code to run with a shader pipeline,
      The legacy code uses glVertexPointer(), glColorPointer(), glNormalPointer() and glTexCoordPointer() to supply the vertex information.
      I know that it should be using setVertexAttribPointer() etc to clearly define the layout but that is not an option right now since the legacy code can't be modified to that extent.
      I've got a version 330 vertex shader to somewhat work:
      #version 330 uniform mat4 osg_ModelViewProjectionMatrix; uniform mat4 osg_ModelViewMatrix; layout(location = 0) in vec4 Vertex; layout(location = 2) in vec4 Normal; // Velocity layout(location = 3) in vec3 TexCoord; // TODO: is this the right layout location? out VertexData { vec4 color; vec3 velocity; float size; } VertexOut; void main(void) { vec4 p0 = Vertex; vec4 p1 = Vertex + vec4(Normal.x, Normal.y, Normal.z, 0.0f); vec3 velocity = (osg_ModelViewProjectionMatrix * p1 - osg_ModelViewProjectionMatrix * p0).xyz; VertexOut.velocity = velocity; VertexOut.size = TexCoord.y; gl_Position = osg_ModelViewMatrix * Vertex; } What works is the Vertex and Normal information that the legacy C++ OpenGL code seem to provide in layout location 0 and 2. This is fine.
      What I'm not getting to work is the TexCoord information that is supplied by a glTexCoordPointer() call in C++.
      What layout location is the old standard pipeline using for glTexCoordPointer()? Or is this undefined?
      Side note: I'm trying to get an OpenSceneGraph 3.4.0 particle system to use custom vertex, geometry and fragment shaders for rendering the particles.
    • By markshaw001
      Hi i am new to this forum  i wanted to ask for help from all of you i want to generate real time terrain using a 32 bit heightmap i am good at c++ and have started learning Opengl as i am very interested in making landscapes in opengl i have looked around the internet for help about this topic but i am not getting the hang of the concepts and what they are doing can some here suggests me some good resources for making terrain engine please for example like tutorials,books etc so that i can understand the whole concept of terrain generation.
    • By KarimIO
      Hey guys. I'm trying to get my application to work on my Nvidia GTX 970 desktop. It currently works on my Intel HD 3000 laptop, but on the desktop, every bind textures specifically from framebuffers, I get half a second of lag. This is done 4 times as I have three RGBA textures and one depth 32F buffer. I tried to use debugging software for the first time - RenderDoc only shows SwapBuffers() and no OGL calls, while Nvidia Nsight crashes upon execution, so neither are helpful. Without binding it runs regularly. This does not happen with non-framebuffer binds.
      GLFramebuffer::GLFramebuffer(FramebufferCreateInfo createInfo) { glGenFramebuffers(1, &fbo); glBindFramebuffer(GL_FRAMEBUFFER, fbo); textures = new GLuint[createInfo.numColorTargets]; glGenTextures(createInfo.numColorTargets, textures); GLenum *DrawBuffers = new GLenum[createInfo.numColorTargets]; for (uint32_t i = 0; i < createInfo.numColorTargets; i++) { glBindTexture(GL_TEXTURE_2D, textures[i]); GLint internalFormat; GLenum format; TranslateFormats(createInfo.colorFormats[i], format, internalFormat); // returns GL_RGBA and GL_RGBA glTexImage2D(GL_TEXTURE_2D, 0, internalFormat, createInfo.width, createInfo.height, 0, format, GL_FLOAT, 0); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); DrawBuffers[i] = GL_COLOR_ATTACHMENT0 + i; glBindTexture(GL_TEXTURE_2D, 0); glFramebufferTexture(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0 + i, textures[i], 0); } if (createInfo.depthFormat != FORMAT_DEPTH_NONE) { GLenum depthFormat; switch (createInfo.depthFormat) { case FORMAT_DEPTH_16: depthFormat = GL_DEPTH_COMPONENT16; break; case FORMAT_DEPTH_24: depthFormat = GL_DEPTH_COMPONENT24; break; case FORMAT_DEPTH_32: depthFormat = GL_DEPTH_COMPONENT32; break; case FORMAT_DEPTH_24_STENCIL_8: depthFormat = GL_DEPTH24_STENCIL8; break; case FORMAT_DEPTH_32_STENCIL_8: depthFormat = GL_DEPTH32F_STENCIL8; break; } glGenTextures(1, &depthrenderbuffer); glBindTexture(GL_TEXTURE_2D, depthrenderbuffer); glTexImage2D(GL_TEXTURE_2D, 0, depthFormat, createInfo.width, createInfo.height, 0, GL_DEPTH_COMPONENT, GL_FLOAT, 0); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); glBindTexture(GL_TEXTURE_2D, 0); glFramebufferTexture(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, depthrenderbuffer, 0); } if (createInfo.numColorTargets > 0) glDrawBuffers(createInfo.numColorTargets, DrawBuffers); else glDrawBuffer(GL_NONE); if (glCheckFramebufferStatus(GL_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE) std::cout << "Framebuffer Incomplete\n"; glBindFramebuffer(GL_FRAMEBUFFER, 0); width = createInfo.width; height = createInfo.height; } // ... // FBO Creation FramebufferCreateInfo gbufferCI; gbufferCI.colorFormats =; gbufferCI.depthFormat = FORMAT_DEPTH_32; gbufferCI.numColorTargets = gbufferCFs.size(); gbufferCI.width = engine.settings.resolutionX; gbufferCI.height = engine.settings.resolutionY; gbufferCI.renderPass = nullptr; gbuffer = graphicsWrapper->CreateFramebuffer(gbufferCI); // Bind glBindFramebuffer(GL_DRAW_FRAMEBUFFER, fbo); // Draw here... // Bind to textures glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D, textures[0]); glActiveTexture(GL_TEXTURE1); glBindTexture(GL_TEXTURE_2D, textures[1]); glActiveTexture(GL_TEXTURE2); glBindTexture(GL_TEXTURE_2D, textures[2]); glActiveTexture(GL_TEXTURE3); glBindTexture(GL_TEXTURE_2D, depthrenderbuffer); Here is an extract of my code. I can't think of anything else to include. I've really been butting my head into a wall trying to think of a reason but I can think of none and all my research yields nothing. Thanks in advance!
    • By Adrianensis
      Hi everyone, I've shared my 2D Game Engine source code. It's the result of 4 years working on it (and I still continue improving features ) and I want to share with the community. You can see some videos on youtube and some demo gifs on my twitter account.
      This Engine has been developed as End-of-Degree Project and it is coded in Javascript, WebGL and GLSL. The engine is written from scratch.
      This is not a professional engine but it's for learning purposes, so anyone can review the code an learn basis about graphics, physics or game engine architecture. Source code on this GitHub repository.
      I'm available for a good conversation about Game Engine / Graphics Programming
    • By C0dR
      I would like to introduce the first version of my physically based camera rendering library, written in C++, called PhysiCam.
      Physicam is an open source OpenGL C++ library, which provides physically based camera rendering and parameters. It is based on OpenGL and designed to be used as either static library or dynamic library and can be integrated in existing applications.
      The following features are implemented:
      Physically based sensor and focal length calculation Autoexposure Manual exposure Lense distortion Bloom (influenced by ISO, Shutter Speed, Sensor type etc.) Bokeh (influenced by Aperture, Sensor type and focal length) Tonemapping  
      You can find the repository at
      I would be happy about feedback, suggestions or contributions.

  • Popular Now