gpt4 book ai didi

java - LWJGL:从具有多个纹理的 .png 中获取纹理

转载 作者:行者123 更新时间:2023-11-30 08:15:09 26 4
gpt4 key购买 nike

我正在使用 LWJGL 制作游戏,并使用 openGL,我相信我最好的选择是使用纹理并使用四边形渲染它们。但是,我似乎只能找到有关从图像加载纹理的信息,其中整个图像只有一个纹理。我想做的是读取整个 Sprite 表并能够将其分成不同的纹理。有没有一种简单的方法可以做到这一点?

最佳答案

您可以加载图像,例如将 .png 文件转换为 BufferedImage 并使用

public static BufferedImage loadImage(String location)
{
try {
BufferedImage image = ImageIO.read(new File(location));
return image;
} catch (IOException e) {
System.out.println("Could not load texture: " + location);
}
return null;
}

现在您可以在生成的 BufferedImage 上调用 getSubimage(int x, int y, int w, int h),从而获得单独的部分。您现在只需要创建 BufferedImage 的纹理。此代码应该完成以下工作:

public static int loadTexture(BufferedImage image){
if (image == null) {
return 0;
}

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() * BYTES_PER_PIXEL); //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(); //FOR THE LOVE OF GOD DO NOT FORGET THIS

// You now have a ByteBuffer filled with the color data of each pixel.
// Now just create a texture ID and bind it. Then you can load it using
// whatever OpenGL method you want, for example:

int textureID = glGenTextures();
glBindTexture(GL_TEXTURE_2D, textureID);

//setup wrap mode
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL12.GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL12.GL_CLAMP_TO_EDGE);

//setup texture scaling filtering
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);

//Send texel data to OpenGL
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, image.getWidth(), image.getHeight(), 0, GL_RGBA, GL_UNSIGNED_BYTE, buffer); //GL_RGBA8 was GL_RGB8A

return textureID;
}

如果您需要纹理,现在可以将返回的 textureIDglBindTexture(GL_TEXTURE_2D,textureID); 绑定(bind)。这样您只需将 BufferedImage 分割为所需的部分即可。

我建议阅读此内容:LWJGL Textures and Strings

关于java - LWJGL:从具有多个纹理的 .png 中获取纹理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29760666/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com