如何在OpenGL中将纹理加载到对象

时间:2011-06-17 16:42:48

标签: java opengl lwjgl

我想在java OpenGL(LWJGL)中将纹理加载到Object。你知道怎么做吗?

1 个答案:

答案 0 :(得分:2)

我在PNGDecoder (download link is here)类的帮助下使用了.png纹理。

我这样做的方式是实例化一个纹理整数字段,如下所示:

private int tex;

然后我使用我从this webpage

找到的这个方便的方法
private int setupTextures(String filename) {
    IntBuffer tmp = BufferUtils.createIntBuffer(1);
    GL11.glGenTextures(tmp);
    tmp.rewind();
    try {
        InputStream in = new FileInputStream(filename);
        PNGDecoder decoder = new PNGDecoder(in);

        System.out.println("width=" + decoder.getWidth());
        System.out.println("height=" + decoder.getHeight());

        ByteBuffer buf = ByteBuffer.allocateDirect(4 * decoder.getWidth() * decoder.getHeight());
        decoder.decode(buf, decoder.getWidth() * 4, PNGDecoder.Format.RGBA);
        buf.flip();

        GL11.glBindTexture(GL11.GL_TEXTURE_2D, tmp.get(0));
        GL11.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_MAG_FILTER,
                GL11.GL_NEAREST);
        GL11.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_MIN_FILTER,
                GL11.GL_NEAREST);
        GL11.glPixelStorei(GL11.GL_UNPACK_ALIGNMENT, 4);
        GL11.glTexImage2D(GL11.GL_TEXTURE_2D, 0, GL11.GL_RGBA, decoder.getWidth(), decoder.getHeight(), 0, GL11.GL_RGBA, GL11.GL_UNSIGNED_BYTE, buf);
        int unsigned = (buf.get(0) & 0xff);
        System.out.println(unsigned);
        System.out.println(buf.get(1));
        System.out.println(buf.get(2));
        System.out.println(buf.get(3));

    } catch (java.io.FileNotFoundException ex) {
        System.out.println("Error " + filename + " not found");
    } catch (java.io.IOException e) {
        System.out.println("Error decoding " + filename);
    }
    tmp.rewind();
    return tmp.get(0);
}

并将返回值分配给整数,如此(您只需要纹理的路径):

    tex = setupTextures(Main.class.getResource("images/Dirt.png").getPath());

然后你只需要绑定纹理:

    GL11.glBindTexture(GL11.GL_TEXTURE_2D, tex);

你们都准备好了!根据您的导入风格,您可以放弃java.io. [class],或者根本不导入任何内容,并在您的代码中使用该类型的语法。