Hello everyone,
I have been building a 2D shooter game for several months now and recently decided to switch my graphics from Java2D to JOGL. I have already had much success with it, but I have hit a snag with images for sprites:
I am using this code(adapted from an example on the sun forums) to load up images into the prescribed ByteBuffer to pass to glDrawPixels():
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package GamePackage;
/**
*
* @author Legendre
*/
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.color.ColorSpace;
import java.awt.geom.AffineTransform;
import java.awt.image.BufferedImage;
import java.awt.image.ComponentColorModel;
import java.awt.image.DataBuffer;
import java.awt.image.DataBufferByte;
import java.awt.image.Raster;
import java.awt.image.WritableRaster;
import java.nio.ByteBuffer;
import javax.swing.ImageIcon;
import javax.imageio.ImageIO;
import java.io.IOException;
import java.io.File;
public class OGLimage {
ByteBuffer oglimage;
int imgWidth, imgHeight;
public OGLimage(String url)
{
String fileSep = System.getProperty("file.separator");
Image timg;
Image img = null;
try {
timg = ImageIO.read(new File("media" + fileSep + "images" + fileSep + url));
img=new ImageIcon(timg).getImage();
imgWidth = img.getWidth(null);
imgHeight = img.getHeight(null);
} catch (IOException e) { }
// use a byte array to keep the color values properly arranged
WritableRaster raster = Raster.createInterleavedRaster(
DataBuffer.TYPE_BYTE,
imgWidth,
imgHeight,
4,
null);
ComponentColorModel colorModel = new ComponentColorModel(
ColorSpace.getInstance(ColorSpace.CS_sRGB),
new int[] {8, 8, 8, 8},
true,
false,
ComponentColorModel.TRANSLUCENT,
DataBuffer.TYPE_BYTE);
BufferedImage bufImg = new BufferedImage(
colorModel,
raster,
false,
null);
// transform the image upside down
// = correct direction in OGL
Graphics2D g = bufImg.createGraphics();
AffineTransform gt = new AffineTransform();
gt.translate (0, imgHeight);
gt.scale (1, -1d);
g.transform (gt);
g.drawImage (img, null, null);
// fetch byte-Array from the Raster
DataBufferByte dataBuf = (DataBufferByte)raster.getDataBuffer();
oglimage = ByteBuffer.wrap(dataBuf.getData());
}
public ByteBuffer getBuffer(){
return oglimage;
}
public int getWidth(){
return imgWidth;
}
public int getHeight(){
return imgHeight;
}
}
My problem is that I run out of heap space within the loading of two 1024x768 jpgs. But if I try to only load images into bytebuffers as they are needed my game runs way too slowly. I cant figure out what the middle ground is that I am missing. Or am I misusing the loading procedure?
This is really frustrating because by comparison image work was so easy in Java2D. Any help is greatly appreciated!