Guest User

Untitled

a guest
Jun 25th, 2014
320
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.26 KB | None | 0 0
  1. ...package declairation
  2.  
  3. import java.awt.image.BufferedImage;
  4. import java.io.File;
  5. import java.io.IOException;
  6. import java.nio.ByteBuffer;
  7.  
  8. import javax.imageio.ImageIO;
  9.  
  10. import org.lwjgl.BufferUtils;
  11. import org.lwjgl.opengl.GL11;
  12. import org.lwjgl.opengl.GL12;
  13. import org.lwjgl.opengl.GL13;
  14.  
  15. public class Texture {
  16. public BufferedImage source;
  17. public int id;
  18.  
  19. public Texture(){
  20. id = GL11.glGenTextures();
  21. }
  22.  
  23. public void bind(){
  24. GL11.glBindTexture(GL11.GL_TEXTURE_2D, id);
  25. }
  26.  
  27. public void unbind(){
  28. GL11.glBindTexture(GL11.GL_TEXTURE_2D, 0);
  29. }
  30.  
  31. public int getID(){
  32. return id;
  33. }
  34.  
  35. public void dispose() {
  36. GL11.glDeleteTextures(id);
  37. }
  38.  
  39. public static Texture loadTexture(String resourceName){
  40. Texture texture = new Texture();
  41.  
  42. BufferedImage image = null;
  43.  
  44. try {
  45. image = ImageIO.read(new File(resourceName));
  46. } catch (IOException e) {
  47. e.printStackTrace();
  48. }
  49.  
  50. int[] pixels = new int[image.getWidth() * image.getHeight()];
  51. image.getRGB(0, 0, image.getWidth(), image.getHeight(), pixels, 0,
  52. image.getWidth());
  53.  
  54. ByteBuffer buffer = BufferUtils.createByteBuffer(image.getWidth() * image.getHeight() * 4); // 4 for RGBA, 3 for RGB
  55.  
  56. for (int y = 0; y < image.getHeight(); y++) {
  57. for (int x = 0; x < image.getWidth(); x++) {
  58. int pixel = pixels[y * image.getWidth() + x];
  59. buffer.put((byte) ((pixel >> 16) & 0xFF));
  60. buffer.put((byte) ((pixel >> 8) & 0xFF));
  61. buffer.put((byte) (pixel & 0xFF));
  62. buffer.put((byte) ((pixel >> 24) & 0xFF));
  63. }
  64. }
  65.  
  66. buffer.flip();
  67.  
  68. texture.id = GL11.glGenTextures();
  69. texture.bind();
  70.  
  71. // Setup wrap mode
  72. GL11.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_WRAP_S, GL12.GL_CLAMP_TO_EDGE);
  73. GL11.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_WRAP_T, GL12.GL_CLAMP_TO_EDGE);
  74.  
  75. // Setup texture scaling filtering
  76. GL11.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_MIN_FILTER, GL11.GL_NEAREST);
  77. GL11.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_MAG_FILTER, GL11.GL_NEAREST);
  78.  
  79. // Send texel data to OpenGL
  80. GL11.glTexImage2D(GL11.GL_TEXTURE_2D, 0, GL11.GL_RGBA8, image.getWidth(), image.getHeight(), 0, GL11.GL_RGBA, GL11.GL_UNSIGNED_BYTE, buffer);
  81. texture.unbind();
  82. return texture;
  83. }
  84. }
Advertisement
Add Comment
Please, Sign In to add comment