package com.javamarcher.util; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.nio.ByteBuffer; import org.lwjgl.opengl.GL11; import org.lwjgl.opengl.GL13; import org.lwjgl.opengl.GL20; import org.lwjgl.opengl.GL30; import de.matthiasmann.twl.utils.PNGDecoder; import de.matthiasmann.twl.utils.PNGDecoder.Format; public class TextureUnit { private final int textureId; private final int shaderProgramId; private int width = 0; private int height = 0; private ByteBuffer textureBuffer = null; public TextureUnit(String fileName, int textureUnit, int shaderProgramId, int samplerPosition, String uniformName) { textureId = loadTextures(fileName, textureUnit); this.shaderProgramId = shaderProgramId; linkToShader(samplerPosition, uniformName); } private void linkToShader(final int samplerPosition, final String uniformName) { GL20.glUseProgram(shaderProgramId); int noiseTex = GL20.glGetUniformLocation(shaderProgramId, uniformName); GL20.glUniform1i(noiseTex, samplerPosition); GL20.glUseProgram(0); } private int loadTextures(String filename, int textureUnit) { try { // Open the PNG file as an InputStream InputStream in = new FileInputStream(filename); // Link the PNG decoder to this stream PNGDecoder decoder = new PNGDecoder(in); // Get the width and height of the texture width = decoder.getWidth(); height = decoder.getHeight(); // Decode the PNG file in a ByteBuffer textureBuffer = ByteBuffer.allocateDirect(4 * decoder.getWidth() * decoder.getHeight()); decoder.decode(textureBuffer, decoder.getWidth() * 4, Format.RGBA); textureBuffer.flip(); in.close(); } catch (IOException e) { e.printStackTrace(); System.exit(-1); } // Create a new texture object in memory and bind it int texId = GL11.glGenTextures(); GL13.glActiveTexture(textureUnit); GL11.glBindTexture(GL11.GL_TEXTURE_2D, texId); // All RGB bytes are aligned to each other and each component is 1 byte GL11.glPixelStorei(GL11.GL_UNPACK_ALIGNMENT, 1); // Upload the texture data and generate mip maps (for scaling) GL11.glTexImage2D(GL11.GL_TEXTURE_2D, 0, GL11.GL_RGB, width, height, 0, GL11.GL_RGBA, GL11.GL_UNSIGNED_BYTE, textureBuffer); GL30.glGenerateMipmap(GL11.GL_TEXTURE_2D); // Setup the ST coordinate system // GL11.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_WRAP_S, GL11.GL_REPEAT); // GL11.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_WRAP_T, GL11.GL_REPEAT); // Setup what to do when the texture has to be scaled GL11.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_MIN_FILTER, GL11.GL_LINEAR); GL11.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_MAG_FILTER, GL11.GL_LINEAR); return texId; } public int getTextureId() { return textureId; } public int getWidth() { return width; } public int getHeight() { return height; } }