Search code examples
c#openglgraphicsopentknormals

Matrix Translations with OpenGL Normals


I'm working with geometry in OpenGL and I'm now working with lighting. I'm noticing that if I translate my geometry, the normals don't follow and are thus useless.

How do you apply a tranformation matrix to geometry and maintain the normals?

Currently I'm using the following code:

        GL.PushMatrix();

        if (Offset != null)
        {
            GL.Translate(Offset.X, Offset.Y, Offset.Z);
        }
        GL.Begin(BeginMode.Triangles);
        foreach (var face in Faces)
        {
            foreach (var i in face)
            {
                var point = Points[i - 1];
                GL.Normal3(point);
                GL.Vertex3(point);
            }
        }
        GL.End();
        GL.PopMatrix();

When I give the geometry an offset, it doesn't render properly (e.g. the normals don't map correctly.

Any help would be excellent.

p.s., I'm using the OpenTK wrapper, but regular OpenGL translates directly across.

EDIT:

Ok, if I change the above code to the following:

        GL.PushMatrix();

        //if (Offset != null)
        //{
        //    GL.Translate(Offset.X, Offset.Y, Offset.Z);
        //}
        GL.Begin(BeginMode.Triangles);
        foreach (var face in Faces)
        {
            foreach (var i in face)
            {
                var point = Points[i - 1];
                if (Offset == null)
                {
                    GL.Normal3(point);
                    GL.Vertex3(point);
                }
                else
                {
                    var pt = new Vector3d(Offset.X + point.X, Offset.Y + point.Y, Offset.Z + point.Z);
                    GL.Normal3(pt);
                    GL.Vertex3(pt);
                }
            }
        }
        GL.End();
        GL.PopMatrix();

everything renders fine.

Here are some screenshots (respective to their code)

Shading not working Shading working


Solution

  • I suspect your normals are fine, but you aren't properly updating your light position and/or direction. Check out the OpenGL FAQ Chapter 18, 18.050 in particular.