At the moment, I'm attempting a basic game engine in OpenGL using immediate mode. I'm trying to render a cube. Cube is a class with the vertices, normals, and indices. Here is part of the Cube class:
// Note: I'm actually coding this in C# using a light OpenGL wrapper called OpenTK.
// But I'm giving my instructions in C++ for this post, for simplicity's sake:
// Please don't be confused if I switch between the two :-)
// C#:
Vertices = new Vector3[]
{
new Vector3(-1.0f, -1.0f, 1.0f),
new Vector3( 1.0f, -1.0f, 1.0f),
new Vector3( 1.0f, 1.0f, 1.0f),
new Vector3(-1.0f, 1.0f, 1.0f),
new Vector3(-1.0f, -1.0f, -1.0f),
new Vector3( 1.0f, -1.0f, -1.0f),
new Vector3( 1.0f, 1.0f, -1.0f),
new Vector3(-1.0f, 1.0f, -1.0f)
};
Indices = new int[]
{
// front face
0, 1, 2, 2, 3, 0,
// top face
3, 2, 6, 6, 7, 3,
// back face
7, 6, 5, 5, 4, 7,
// left face
4, 0, 3, 3, 7, 4,
// bottom face
0, 1, 5, 5, 4, 0,
// right face
1, 5, 6, 6, 2, 1
};
Normals = new Vector3[]
{
new Vector3(-1.0f, -1.0f, 1.0f),
new Vector3( 1.0f, -1.0f, 1.0f),
new Vector3( 1.0f, 1.0f, 1.0f),
new Vector3(-1.0f, 1.0f, 1.0f),
new Vector3(-1.0f, -1.0f, -1.0f),
new Vector3( 1.0f, -1.0f, -1.0f),
new Vector3( 1.0f, 1.0f, -1.0f),
new Vector3(-1.0f, 1.0f, -1.0f),
};
This all worked out fine. The sides of the cube are shadowed nicely, and all seems well. The inside looks like this (note, the lighting is actually coming from the top):
When I cull the 'non-visible' triangles with glEnable(GL_CULL_FACE);
it looks okay normally, but the bottom looks like this:
And if you move the camera to the 'inside' of the cube, you can see the missing bottom face by looking down! This seems to me like I'm confusing OpenGL by declaring my vertices in the clockwise direction, instead of anticlockwise.
This seems to be causing two problems. Firstly, my culling is all messed up. Secondly, remember how the light is actually coming from the top of the cube? Well, from the inside of the cube, it looks like the light is coming from the bottom. Weird.
I'm rendering my cube by doing the following:
GL.Begin(PrimitiveType.Triangles); // Translation: glBegin
foreach (Shape shape in shapes) {
foreach (int index in shape.Indices) {
GL.Normal3(shape.Normals[index]); // Translation: glNormal3f
GL.Vertex3(shape.Vertices[index]); // Translation: glVertex3f
}
}
GL.End();
How do I fix this culling problem? Do I need to be worried that the lighting is messed up from the inside? I think I might just need to swap my indices around, but I don't know how I do this. The rendering works by passing the vertices in the array 0-7, in the order shown by the indices array. Hopefully, getting my indices in the right order will fix the issue.
If my logic upto here is correct, what are the correct (anti-clockwise) indices for my cube class? How did you work this out?
Thanks a lot for any help in advance. I sure appreciate it.