The renderer is not using the texture in Open TK

2019-09-01 01:02发布

问题:

Hi I'm trying to use Textures in OpenGL using Open TK. I got a basic example from the official page of OpenTK Framework, but didn't work. I searched here on stackoverflow for some help and changed some parts of the code, but still is not working. (Found and tested: OpenTk texture not display the image)

So far I came with this snippet, but this is not displaying the texture (display white instead):

UPDATED (With @The Fiddler suggestions)

In OpenTK.GLControl.Load event handler:

GL.ClearColor(Color.MidnightBlue);
GL.Enable(EnableCap.Texture2D);

GL.Viewport(0, 0, control.Width, control.Height);

GL.MatrixMode(MatrixMode.Projection);
GL.LoadIdentity();
GL.Ortho(0, 4, 0, 3, -1, 1);

GL.Hint(HintTarget.PerspectiveCorrectionHint, HintMode.Nicest);

GL.GenTextures(1, out textureId);
GL.BindTexture(TextureTarget.Texture2D, textureId);
GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMinFilter, (int)TextureMinFilter.Linear);
GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMagFilter, (int)TextureMagFilter.Linear);

var bmp = new Bitmap(@"C:\myfolder\texture.png");
var data = bmp.LockBits(new System.Drawing.Rectangle(0, 0, bmp.Width, bmp.Height),
    ImageLockMode.ReadOnly, System.Drawing.Imaging.PixelFormat.Format32bppArgb);

GL.TexImage2D(TextureTarget.Texture2D, 0, PixelInternalFormat.Rgba, data.Width, data.Height, 0,
    OpenTK.Graphics.OpenGL.PixelFormat.Bgra, PixelType.UnsignedByte, data.Scan0);

System.Windows.Forms.MessageBox.Show("Erro: " + GL.GetError());

bmp.UnlockBits(data);

In OpenTK.GLControl.Paint event handler:

GL.Clear(ClearBufferMask.ColorBufferBit);

GL.MatrixMode(MatrixMode.Modelview);
GL.LoadIdentity();
GL.BindTexture(TextureTarget.Texture2D, textureId);

GL.Begin(BeginMode.Quads);

GL.TexCoord2(0, 0); GL.Vertex2(0, 0);
GL.TexCoord2(0, 1); GL.Vertex2(0, 1);
GL.TexCoord2(1, 1); GL.Vertex2(1, 1);
GL.TexCoord2(1, 0); GL.Vertex2(1, 0);

GL.End();

control.SwapBuffers();

The erro code get in first part is: 1281 = ErrorCode.InvalidValue. Does anyone have any idea why it isn't rendering the texture?

回答1:

A white texture typically means (a) an incomplete texture definition or (b) an OpenGL error state messing up with your rendering. Your texture definitions looks correct, so try calling GL.GetError() to check if any OpenGL errors crop up.

Note that PixelInternalFormat.Rgb8 requires OpenGL 3.x, so you need to check if OpenGL 3.x is supported before using that. Alternatively, try using PixelInternalFormat.Rgb or PixelInternalFormat.Rgba which are supported all the way back to OpenGL 1.1.

Edit: you can find a complete working example at "Texture.cs". You can run this through the example browser in your OpenTK installation (OpenGL -> 1.x -> Textures).