[英]OpenGL / LWJGL texture loads, but texture won't render on quad
我开始在 Java 中使用 LWJGL/OpenGL 来创建 2D 游戏,但是我很难渲染一个简单的 32x32 四边形(正方形)有纹理。 我已经创建了一个纹理加载系统并遵循了正确的纹理说明,但纹理不会显示。 我的代码如下:
devBlock64.bind();
glEnable(GL_TEXTURE_2D);
GL11.glBegin(GL11.GL_QUADS);
GL11.glTexCoord2f(0, 0);
GL11.glVertex2f(0, 0);
GL11.glTexCoord2f(0, 1);
GL11.glVertex2f(32, 0);
GL11.glTexCoord2f(1, 1);
GL11.glVertex2f(32, 32);
GL11.glTexCoord2f(1, 0);
GL11.glVertex2f(0, 32);
GL11.glEnd();
glDisable(GL_TEXTURE_2D);
以上是每次调用“render”时的代码。 “devBlock64”只是一个加载了 64x64 纹理的 Texture 对象(但在这种情况下它是 32x32,因为我将它保存为错误的大小)
此外,这是我在加载纹理并生成其纹理 ID 后调用的选项和函数:
this.bind();
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, buffer);
图像加载正确,但不会显示。 this.bind();
调用我的函数,它只是这样做: glBindTexture(GL_TEXTURE_2D, id):
而且,如果有人好奇,我的游戏循环,其他一切都是根据 OpenGL 设置窗口的教程完成的:
public void loop() {
// Binds GLFW with OpenGL
GL.createCapabilities();
glOrtho(0f, 800, 600, 0f, 0f, 1f);
glClearColor(1.0f, 1f, 1f, 1f);
//glLoadIdentity();
world.loadTextures();
while(!hasWindowRequestedClose()) {
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
world.onUpdate();
world.render();
glfwSwapBuffers(handle);
glfwPollEvents();
}
destroy();
}
嘿,我已经检查了你的代码,一切似乎都很好。 我有几个建议。
你用的是哪个opengl版本? glBegin()
和glEnd()
从较新的版本(3.2 以后)中删除。 相反,您需要将顶点数据上传到顶点缓冲区对象。 然后使用 glVertexAttribPointer 告诉 openGL 数据是如何布局的。
更好的方法是使用着色器并将纹理绑定到着色器。
这是我加载纹理的代码。
public static int loadTexture(String path) {
int[] pixels = null;
int width = 0;
int height = 0;
try {
InputStream resourceBuff = Loader.class.getResourceAsStream(path);
BufferedImage image = ImageIO.read(resourceBuff);
width = image.getWidth();
height = image.getHeight();
pixels = new int[width * height];
image.getRGB(0, 0, width, height, pixels, 0, width);
} catch (IOException e) {
e.printStackTrace();
}
int[] data = new int[width * height];
for (int i = 0; i < width * height; i++) {
int a = (pixels[i] & 0xff000000) >> 24;
int r = (pixels[i] & 0xff0000) >> 16;
int g = (pixels[i] & 0xff00) >> 8;
int b = (pixels[i] & 0xff);
data[i] = a << 24 | b << 16 | g << 8 | r;
}
int result = glGenTextures();
glBindTexture(GL_TEXTURE_2D, result);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE,
storeDataInIntBuffer((data)));
glBindTexture(GL_TEXTURE_2D, 0);
return result;
}
希望这会帮助你。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.