Newer
Older
JumpingGame / src / main / java / views / Texture.java
package views;

import org.lwjgl.BufferUtils;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.nio.ByteBuffer;

import static org.lwjgl.opengl.GL11.*;


public class Texture {

    private int id;
    private int width;
    private int height;
    private String name;

    public Texture(String name, String path) {
        this.name = name;
        BufferedImage bi;
        try {
            bi = ImageIO.read(new File(path));
            width = bi.getWidth();
            height = bi.getHeight();

            int[] pixelsRaw;
            pixelsRaw = bi.getRGB(0, 0, width, height, null, 0, width);
            ByteBuffer pixels = BufferUtils.createByteBuffer(width * height * 4);

            for (int i = 0; i < height; ++i) {
                for (int j = 0; j < width; ++j) {
                    int p = pixelsRaw[i * width + j];
                    pixels.put((byte) ((p >> 16) & 0xFF));
                    pixels.put((byte) ((p >> 8) & 0xFF));
                    pixels.put((byte) (p & 0xFF));
                    pixels.put((byte) ((p >> 24) & 0xFF));
                }
            }
            pixels.flip();

            id = glGenTextures();
            glBindTexture(GL_TEXTURE_2D, id);
            glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, pixels); // 作成

            glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
            glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);

            glBindTexture(GL_TEXTURE_2D, 0);

        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public int getHeight() {
        return height;
    }

    public int getWidth() {
        return width;
    }

    public int getId() {
        return id;
    }

    public void delete() {
        glDeleteTextures(id);
    }
}