LWJGL中的opengl Java绑定纹理导致白色屏幕
最近我一直在尝试实现我自己的PNG纹理解码器/加载器,但是像我之前的几次尝试一样,结果是一样的。。。没有纹理。 以下是我当前用于加载图像的代码(不是我的!我忘记了网站):
public static TextureObject loadTexture(BufferedImage image)
{
int[] pixels = new int[image.getWidth() * image.getHeight()];
image.getRGB(0, 0, image.getWidth(), image.getHeight(), pixels, 0, image.getWidth());
ByteBuffer buffer = BufferUtils.createByteBuffer(image.getWidth() * image.getHeight() * 4); //4 for RGBA, 3 for RGB
for(int y = 0; y < image.getHeight(); y++){
for(int x = 0; x < image.getWidth(); x++){
int pixel = pixels[y * image.getWidth() + x];
buffer.put((byte) ((pixel >> 16) & 0xFF)); // Red component
buffer.put((byte) ((pixel >> 8) & 0xFF)); // Green component
buffer.put((byte) (pixel & 0xFF)); // Blue component
buffer.put((byte) ((pixel >> 24) & 0xFF)); // Alpha component. Only for RGBA
}
}
buffer.flip();
GL11.glEnable(GL11.GL_TEXTURE_2D);
int textureID = GL11.glGenTextures();
GL11.glTexImage2D(GL11.GL_TEXTURE_2D, 0, GL11.GL_RGBA8, image.getWidth(), image.getHeight(), 0, GL11.GL_RGBA, GL11.GL_UNSIGNED_BYTE, buffer);
return new TextureObject(textureID, image.getWidth(), image.getHeight());
}
搜索类似的问题都返回了相同的原因,但没有启用GL_TEXTURE_2D
我已经启用了这一功能,并给出了我的四边形纹理坐标
当我绑定纹理并尝试渲染时,opengl决定将整个屏幕变成白色。我在我的项目中使用了Slick Util进行测试,它使事情变得很好
但是,如果我的render()
函数中有以下代码:
GL11.glColor3f(1.0F, 1.0F, 1.0F);
if(RenderUtil.fontTexture != null) RenderUtil.renderTexturedQuad(RenderUtil.fontTexture, 40, 40, 150, 150);
Main.t.bind();
GL11.glBegin(GL11.GL_QUADS);
GL11.glTexCoord2f(0, 0);
GL11.glVertex2f(0, 0);
GL11.glTexCoord2f(0, 1);
GL11.glVertex2f(0, 512);
GL11.glTexCoord2f(1, 1);
GL11.glVertex2f(512, 512);
GL11.glTexCoord2f(1, 0);
GL11.glVertex2f(512, 0);
GL11.glEnd();
。。。主要是if(RenderUtil.fontTexture != null) RenderUtil.renderTexturedQuad(RenderUtil.fontTexture, 40, 40, 150, 150)
,OpenGL不会呈现任何内容。即使绑定光滑的纹理并尝试渲染,也会失败。以下是renderTexturedQuad()
方法的全文:
public static void renderTexturedQuad(TextureObject texture, int x, int y, int w, int h)
{
GL11.glColor3f(1.0F, 1.0F, 1.0F);
GL11.glEnable(GL11.GL_TEXTURE_2D);
TextureUtil.bind(texture);
GL11.glPushMatrix();
GL11.glTranslatef(x, y, 0);
GL11.glBegin(GL11.GL_QUADS);
GL11.glTexCoord2f(0, 0);
GL11.glVertex2f(0, 0);
GL11.glTexCoord2f(0, 1);
GL11.glVertex2f(0, h);
GL11.glTexCoord2f(1, 1);
GL11.glVertex2f(w, h);
GL11.glTexCoord2f(1, 0);
GL11.glVertex2f(w, 0);
GL11.glEnd();
GL11.glPopMatrix();
}
我唯一看到的可能是设置错误的东西是我的纹理绑定
如果你不推荐我去图书馆或其他类似的地方,我更希望这是一次学习经历:)
# 1 楼答案
在加载图像数据之前,需要先绑定纹理。如果不知道,glTexImage2D不知道在哪里加载数据
可以通过调用以下命令绑定纹理:
之前:
加载图像数据后,还应调用以下行: