LWJGL - Get part of image byte buffer

114 views Asked by At

Hello I am fairly new to OpenGL and LWJGL

I have loaded an Image into a ByteBuffer using the STBImage binding in LWJGL. I can draw the image to the screen, this works perfectly fine.

Now I want to "slice" an image into multiple smaller images. I need it for my Tileset system

I only got it working to slice the image into the individual tiles. But they are not correctly drawn. I think I know what the problem is, but I don't really get it to work how it should.

I think this is the problem:

int s = x * 4 + y * 4;

Here is the entire slicing function.
private void sliceTileset(Image[] images, float tileWidth, float tileHeight) {
  // The pixelbuffer of the entire tileset image (Loaded via STBImage.stbi_load)
  ByteBuffer tilesetPixelBuffer = tilesetImage.getPixelBuffer();

  int xOffset = 0;
  int yOffset = 0;
  // Loop over all available tile slots ((tileSetWidth / tileWidth) +
  // (tileSetHeight / tileHeight))
  for (int i = 0; i < images.length; i++) {
    ByteBuffer buffer = ByteBuffer.allocateDirect((int) (tileWidth * tileHeight * 4));
    for (int y = 0; y < tileHeight; y++) {
      for (int x = xOffset; x < tileWidth + xOffset; x++) {
        int s = x * 4 + y * 4;

        // get the pixel from the tileset image buffer
        int r = tilesetPixelBuffer.get(s);
        int g = tilesetPixelBuffer.get(s + 1);
        int b = tilesetPixelBuffer.get(s + 2);
        int a = tilesetPixelBuffer.get(s + 3);

        // put it into the tile image buffer
        buffer.put((byte) r);
        buffer.put((byte) g);
        buffer.put((byte) b);
        buffer.put((byte) a);
      }
    }
    // Create a new image with the tile image buffer
    images[i] = new Image(buffer, tileWidth, tileHeight);
    buffer.flip();

    // Offset the x-position for the next tile
    xOffset += tileWidth;
    // Offset the y-position for the next tile
    yOffset += tileHeight; // Currently does nothing
  }
}

If your need more information just ask for it!

0

There are 0 answers