Search code examples
c#openglopentk

OpenGL texture+lightning+blending trouble


I'm using OpenTK and there is a difficulty for me to understand the concept of openGL enabling functions. The perspective Matrix is in onResize function.

I am trying to show the texture.

My Render Function:

        GL.ClearColor(0.5f, 0.5f, 0.5f, 1.0f); 
        GL.Clear(ClearBufferMask.ColorBufferBit | ClearBufferMask.DepthBufferBit);
        GL.MatrixMode(MatrixMode.Modelview);
        GL.LoadIdentity();
        GL.Enable(EnableCap.Texture2D);
        GL.Enable(EnableCap.DepthTest);
        Ground.Draw();

My Ground.Draw() function(sizeXZ.Z, sizeXZ.Y are constants):

        GL.PushMatrix();
        GL.Translate(new Vector3(-sizeXZ.X / 2, -1, sizeXZ.Y / 2));
        GL.BindTexture(TextureTarget.Texture2D, Textures.GetTextureId(textureName));
        GL.Begin(PrimitiveType.Quads);
        GL.Color3(1,1,1);
        GL.Normal3(0, 1, 0);
        GL.TexCoord2(1f, 1f); GL.Vertex3(0, 0, 0);
        GL.TexCoord2(1f, 0f); GL.Vertex3(sizeXZ.X, 0, 0);
        GL.TexCoord2(0f, 0f); GL.Vertex3(sizeXZ.X, 0, -sizeXZ.Y);
        GL.TexCoord2(0f, 1f); GL.Vertex3(0, 0, -sizeXZ.Y);
        GL.End();
        GL.PopMatrix();

It shows a black non-textured quad. When I add some light the texture appears, but disappears the color of some quads:

GL.BindTexture(TextureTarget.Texture2D, Textures.GetTextureId(textureName));
GL.Begin(PrimitiveType.Quads);
GL.Normal3(0, 0, 1);
if (true) GL.Color4(0,1,0,1); // it appears to be the background color, not green
if (false) GL.TexCoord2(1f, 0f); GL.Vertex3(0, 0, 0);
if (false) GL.TexCoord2(1f, 1f); GL.Vertex3(3f, 0, 0);
if (false) GL.TexCoord2(0f, 1f); GL.Vertex3(3f, 3f, 0);
if (false) GL.TexCoord2(0f, 0f); GL.Vertex3(0, 3f, 0);
GL.Color4(1, 1, 1, 1);
GL.End();

Solution

  • There are two problems in your program:

    1. Usage of Color3

    Looking at the OpenTK Color3 documentation, you will notice that there are two overloads of this function:

    Color3  (Double red, Double green, Double blue)
    Color3  (SByte red, SByte green, SByte blue)
    

    The reason why GL.Color3(1,1,1) gives you a black object is, that this uses the SByte version where values are assumed to be in the range [0, 255]. Thus 1 is very dark. Note that GL.Color3(1.0,1.0,1.0) calls the Double overload.

    2. GL_TEXTURE_ENV_MODE

    By default this is set to GL_MODULATE which multiplies the texture color with the vertex color. Together with 1., this makes your texture disappear. More details on this are given here