Java Code Examples for com.jme3.texture.Image#getData()

The following examples show how to use com.jme3.texture.Image#getData() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: PaintTerrainToolControl.java    From jmonkeybuilder with Apache License 2.0 6 votes vote down vote up
/**
 * Start making changes.
 */
@JmeThread
private void startChange() {

    final Array<ColorPoint> colorPoints = getColorPoints();
    colorPoints.clear();

    final Texture alphaTexture = notNull(getAlphaTexture());
    final Image image = alphaTexture.getImage();
    final ByteBuffer data = image.getData(0);

    if (prevBuffer == null) {
        prevBuffer = BufferUtils.createByteBuffer(data.capacity());
    } else if (prevBuffer.capacity() < data.capacity()) {
        BufferUtils.destroyDirectBuffer(prevBuffer);
        prevBuffer = BufferUtils.createByteBuffer(data.capacity());
    }

    final int position = data.position();
    data.position(0);
    prevBuffer.clear();
    prevBuffer.put(data);
    prevBuffer.flip();
    data.position(position);
}
 
Example 2
Source File: SkyFactory.java    From MikuMikuStudio with BSD 2-Clause "Simplified" License 5 votes vote down vote up
private static void checkImagesForCubeMap(Image... images) {
    if (images.length == 1) {
        return;
    }

    Format fmt = images[0].getFormat();
    int width = images[0].getWidth();
    int height = images[0].getHeight();
    
    ByteBuffer data = images[0].getData(0);
    int size = data != null ? data.capacity() : 0;

    checkImage(images[0]);

    for (int i = 1; i < images.length; i++) {
        Image image = images[i];
        checkImage(images[i]);
        if (image.getFormat() != fmt) {
            throw new IllegalArgumentException("Images must have same format");
        }
        if (image.getWidth() != width || image.getHeight() != height)  {
            throw new IllegalArgumentException("Images must have same resolution");
        }
        ByteBuffer data2 = image.getData(0);
        if (data2 != null){
            if (data2.capacity() != size) {
                throw new IllegalArgumentException("Images must have same size");
            }
        }
    }
}
 
Example 3
Source File: ImageFlipper.java    From MikuMikuStudio with BSD 2-Clause "Simplified" License 5 votes vote down vote up
public static void flipImage(Image img, int index){
    if (img.getFormat().isCompressed())
        throw new UnsupportedOperationException("Flipping compressed " +
                                                "images is unsupported.");

    int w = img.getWidth();
    int h = img.getHeight();
    int halfH = h / 2;

    // bytes per pixel
    int bpp = img.getFormat().getBitsPerPixel() / 8;
    int scanline = w * bpp;

    ByteBuffer data = img.getData(index);
    ByteBuffer temp = BufferUtils.createByteBuffer(scanline);
    
    data.rewind();
    for (int y = 0; y < halfH; y++){
        int oppY = h - y - 1;
        // read in scanline
        data.position(y * scanline);
        data.limit(data.position() + scanline);

        temp.rewind();
        temp.put(data);

    }
}
 
Example 4
Source File: LuminancePixelInputOutput.java    From MikuMikuStudio with BSD 2-Clause "Simplified" License 5 votes vote down vote up
public void write(Image image, int layer, TexturePixel pixel, int index) {
    ByteBuffer data = image.getData(layer);
    data.put(index, pixel.getInt());
    switch (image.getFormat()) {
        case Luminance8:
            data.put(index, pixel.getInt());
            break;
        case Luminance8Alpha8:
            data.put(index, pixel.getInt());
            data.put(index + 1, pixel.getA8());
            break;
        case Luminance16:
            data.putShort(index, (short) (pixel.intensity * 65535.0f));
            break;
        case Luminance16Alpha16:
            data.putShort(index, (short) (pixel.intensity * 65535.0f));
            data.putShort(index + 2, (short) (pixel.alpha * 65535.0f));
            break;
        case Luminance16F:
            data.putShort(index, FastMath.convertFloatToHalf(pixel.intensity));
            break;
        case Luminance16FAlpha16F:
            data.putShort(index, FastMath.convertFloatToHalf(pixel.intensity));
            data.putShort(index + 2, FastMath.convertFloatToHalf(pixel.alpha));
            break;
        case Luminance32F:
            data.putInt(index, Float.floatToIntBits(pixel.intensity));
            break;
        default:
            throw new IllegalStateException("Unknown luminance format type.");
    }
}
 
Example 5
Source File: LuminancePixelInputOutput.java    From MikuMikuStudio with BSD 2-Clause "Simplified" License 5 votes vote down vote up
public void read(Image image, int layer, TexturePixel pixel, int index) {
    ByteBuffer data = image.getData(layer);
    switch (image.getFormat()) {
        case Luminance8:
            pixel.fromIntensity(data.get(index));
            break;
        case Luminance8Alpha8:
            pixel.fromIntensity(data.get(index));
            pixel.setAlpha(data.get(index + 1));
            break;
        case Luminance16:
            pixel.fromIntensity(data.getShort(index));
            break;
        case Luminance16Alpha16:
            pixel.fromIntensity(data.getShort(index));
            pixel.setAlpha(data.getShort(index + 2));
            break;
        case Luminance16F:
            pixel.intensity = FastMath.convertHalfToFloat(data.getShort(index));
            break;
        case Luminance16FAlpha16F:
            pixel.intensity = FastMath.convertHalfToFloat(data.getShort(index));
            pixel.alpha = FastMath.convertHalfToFloat(data.getShort(index + 2));
            break;
        case Luminance32F:
            pixel.intensity = Float.intBitsToFloat(data.getInt(index));
            break;
        default:
            throw new IllegalStateException("Unknown luminance format type.");
    }
}
 
Example 6
Source File: SkyFactory.java    From jmonkeyengine with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
private static void checkImagesForCubeMap(Image... images) {
    if (images.length == 1) {
        return;
    }

    Format fmt = images[0].getFormat();
    int width = images[0].getWidth();
    int height = images[0].getHeight();
    
    ByteBuffer data = images[0].getData(0);
    int size = data != null ? data.capacity() : 0;

    checkImage(images[0]);

    for (int i = 1; i < images.length; i++) {
        Image image = images[i];
        checkImage(images[i]);
        if (image.getFormat() != fmt) {
            throw new IllegalArgumentException("Images must have same format");
        }
        if (image.getWidth() != width || image.getHeight() != height)  {
            throw new IllegalArgumentException("Images must have same resolution");
        }
        ByteBuffer data2 = image.getData(0);
        if (data2 != null){
            if (data2.capacity() != size) {
                throw new IllegalArgumentException("Images must have same size");
            }
        }
    }
}
 
Example 7
Source File: MipMapImageRaster.java    From jmonkeyengine with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
public MipMapImageRaster(Image image, int slice) {
    this.image = image;
    this.slice = slice;
    this.buffer = image.getData(slice);
    this.codec = ImageCodec.lookup(image.getFormat());
    if (image.hasMipmaps()) {
        int nbMipMap = image.getMipMapSizes().length;
        this.width = new int[nbMipMap];
        this.height = new int[nbMipMap];
        this.offsets = new int[nbMipMap];
        for (int i = 0; i < nbMipMap; i++) {
            width[i] = Math.max(1, image.getWidth() >> i);
            height[i] = Math.max(1, image.getHeight() >> i);
            if (i > 0) {
                offsets[i] = image.getMipMapSizes()[i - 1] + offsets[i - 1];
            }
        }

    } else {
        throw new IllegalArgumentException("Image must have MipMapSizes initialized.");
    }

    if (codec instanceof ByteAlignedImageCodec || codec instanceof ByteOffsetImageCodec) {
        this.temp = new byte[codec.bpp];
    } else {
        this.temp = null;
    }
}
 
Example 8
Source File: DefaultImageRaster.java    From jmonkeyengine with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
public DefaultImageRaster(Image image, int slice, int mipMapLevel, boolean convertToLinear) {
    int[] mipMapSizes = image.getMipMapSizes();
    int availableMips = mipMapSizes != null ? mipMapSizes.length : 1;
    
    if (mipMapLevel >= availableMips) {
        throw new IllegalStateException("Cannot create image raster for mipmap level #" + mipMapLevel + ". "
                                      + "Image only has " + availableMips + " mipmap levels.");
    }
    
    if (image.hasMipmaps()) {
        this.width  = Math.max(1, image.getWidth()  >> mipMapLevel);
        this.height = Math.max(1, image.getHeight() >> mipMapLevel);
        
        int mipOffset = 0;
        for (int i = 0; i < mipMapLevel; i++) {
            mipOffset += mipMapSizes[i];
        }
        
        this.offset = mipOffset;
    } else {
        this.width = image.getWidth();
        this.height = image.getHeight();
        this.offset = 0;
    }
    
    this.image = image;
    this.slice = slice;
    
    // Conversion to linear only needed if image's color space is sRGB.
    this.convertToLinear = convertToLinear && image.getColorSpace() == ColorSpace.sRGB;
    
    this.buffer = image.getData(slice);
    this.codec = ImageCodec.lookup(image.getFormat());
    
    if (codec instanceof ByteAlignedImageCodec || codec instanceof ByteOffsetImageCodec) {
        this.temp = new byte[codec.bpp];
    } else {
        this.temp = null;
    }
}
 
Example 9
Source File: ImageFlipper.java    From jmonkeyengine with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
public static void flipImage(Image img, int index){
    if (img.getFormat().isCompressed())
        throw new UnsupportedOperationException("Flipping compressed " +
                                                "images is unsupported.");

    int w = img.getWidth();
    int h = img.getHeight();
    int halfH = h / 2;

    // bytes per pixel
    int bpp = img.getFormat().getBitsPerPixel() / 8;
    int scanline = w * bpp;

    ByteBuffer data = img.getData(index);
    ByteBuffer temp = BufferUtils.createByteBuffer(scanline);
    
    data.rewind();
    for (int y = 0; y < halfH; y++){
        int oppY = h - y - 1;
        // read in scanline
        data.position(y * scanline);
        data.limit(data.position() + scanline);

        temp.rewind();
        temp.put(data);

    }
}
 
Example 10
Source File: DefaultImageRaster.java    From MikuMikuStudio with BSD 2-Clause "Simplified" License 5 votes vote down vote up
public DefaultImageRaster(Image image, int slice) {
    this.image = image;
    this.slice = slice;
    this.buffer = image.getData(slice);
    this.codec = ImageCodec.lookup(image.getFormat());
    this.width = image.getWidth();
    this.height = image.getHeight();
    if (codec instanceof ByteAlignedImageCodec || codec instanceof ByteOffsetImageCodec) {
        this.temp = new byte[codec.bpp];
    } else {
        this.temp = null;
    }
}
 
Example 11
Source File: OGLESShaderRenderer.java    From MikuMikuStudio with BSD 2-Clause "Simplified" License 4 votes vote down vote up
/**
 * <code>updateTexImageData</code> activates and binds the texture
 * @param img
 * @param type
 * @param mips
 */
public void updateTexImageData(Image img, Texture.Type type, boolean mips) {
    int texId = img.getId();
    if (texId == -1) {
        // create texture
        if (verboseLogging) {
            logger.info("GLES20.glGenTexture(1, buffer)");
        }

        GLES20.glGenTextures(1, intBuf1);
        texId = intBuf1.get(0);
        img.setId(texId);
        objManager.registerForCleanup(img);

        statistics.onNewTexture();
    }

    // bind texture
    int target = convertTextureType(type);
    if (context.boundTextureUnit != 0) {
        if (verboseLogging) {
            logger.info("GLES20.glActiveTexture(GLES20.GL_TEXTURE0)");
        }

        GLES20.glActiveTexture(GLES20.GL_TEXTURE0);
        context.boundTextureUnit = 0;
    }
    if (context.boundTextures[0] != img) {

        if (verboseLogging) {
            logger.info("GLES20.glBindTexture(" + target + ", " + texId + ")");
        }

        GLES20.glBindTexture(target, texId);
        context.boundTextures[0] = img;
    }


    if (target == GLES20.GL_TEXTURE_CUBE_MAP) {
        // Upload a cube map / sky box
        @SuppressWarnings("unchecked")
        List<Bitmap> bmps = (List<Bitmap>) img.getEfficentData();
        if (bmps != null) {
            // Native android bitmap                                       
            if (bmps.size() != 6) {
                throw new UnsupportedOperationException("Invalid texture: " + img
                        + "Cubemap textures must contain 6 data units.");
            }
            for (int i = 0; i < 6; i++) {
                TextureUtil.uploadTextureBitmap(GLES20.GL_TEXTURE_CUBE_MAP_POSITIVE_X + i, bmps.get(i), false, powerOf2);
            }
        } else {
            // Standard jme3 image data
            List<ByteBuffer> data = img.getData();
            if (data.size() != 6) {
                logger.log(Level.WARNING, "Invalid texture: {0}\n"
                        + "Cubemap textures must contain 6 data units.", img);
                return;
            }
            for (int i = 0; i < 6; i++) {
                TextureUtil.uploadTexture(img, GLES20.GL_TEXTURE_CUBE_MAP_POSITIVE_X + i, i, 0, tdc, false, powerOf2);
            }
        }
    } else {
        TextureUtil.uploadTexture(img, target, 0, 0, tdc, false, powerOf2);

        if (verboseLogging) {
            logger.info("GLES20.glTexParameteri(" + target + "GLES11.GL_GENERATE_MIMAP, GLES20.GL_TRUE)");
        }

        if (!img.hasMipmaps() && mips) {
            // No pregenerated mips available,
            // generate from base level if required
            if (verboseLogging) {
                logger.info("GLES20.glGenerateMipmap(GLES20.GL_TEXTURE_2D)");
            }
            GLES20.glGenerateMipmap(GLES20.GL_TEXTURE_2D);
        }
    }

    img.clearUpdateNeeded();
}
 
Example 12
Source File: AWTPixelInputOutput.java    From MikuMikuStudio with BSD 2-Clause "Simplified" License 4 votes vote down vote up
public void write(Image image, int layer, TexturePixel pixel, int index) {
    ByteBuffer data = image.getData(layer);
    switch (image.getFormat()) {
        case RGBA8:
            data.put(index, pixel.getR8());
            data.put(index + 1, pixel.getG8());
            data.put(index + 2, pixel.getB8());
            data.put(index + 3, pixel.getA8());
            break;
        case ABGR8:
            data.put(index, pixel.getA8());
            data.put(index + 1, pixel.getB8());
            data.put(index + 2, pixel.getG8());
            data.put(index + 3, pixel.getR8());
            break;
        case BGR8:
            data.put(index, pixel.getB8());
            data.put(index + 1, pixel.getG8());
            data.put(index + 2, pixel.getR8());
            break;
        case RGB8:
            data.put(index, pixel.getR8());
            data.put(index + 1, pixel.getG8());
            data.put(index + 2, pixel.getB8());
            break;
        case RGB565:
            data.putShort(RGB565.ARGB8_to_RGB565(pixel.toARGB8()));
            break;
        case RGB5A1:
            int argb8 = pixel.toARGB8();
            short r = (short) ((argb8 & 0x00F80000) >> 8);
            short g = (short) ((argb8 & 0x0000F800) >> 5);
            short b = (short) ((argb8 & 0x000000F8) >> 2);
            short a = (short) ((short) ((argb8 & 0xFF000000) >> 24) > 0 ? 1 : 0);
            data.putShort(index, (short) (r | g | b | a));
            break;
        case RGB16:
            data.putShort(index, pixel.getR16());
            data.putShort(index + 2, pixel.getG16());
            data.putShort(index + 4, pixel.getB16());
            break;
        case RGBA16:
            data.putShort(index, pixel.getR16());
            data.putShort(index + 2, pixel.getG16());
            data.putShort(index + 4, pixel.getB16());
            data.putShort(index + 6, pixel.getA16());
            break;
        case RGB16F:
        case RGB16F_to_RGB111110F:
        case RGB16F_to_RGB9E5:
            data.putShort(index, FastMath.convertFloatToHalf(pixel.red));
            data.putShort(index + 2, FastMath.convertFloatToHalf(pixel.green));
            data.putShort(index + 4, FastMath.convertFloatToHalf(pixel.blue));
            break;
        case RGBA16F:
            data.putShort(index, FastMath.convertFloatToHalf(pixel.red));
            data.putShort(index + 2, FastMath.convertFloatToHalf(pixel.green));
            data.putShort(index + 4, FastMath.convertFloatToHalf(pixel.blue));
            data.putShort(index + 6, FastMath.convertFloatToHalf(pixel.blue));
            break;
        case RGB32F:
        case RGB111110F:// this data is stored as 32-bit unsigned int
            data.putInt(index, Float.floatToIntBits(pixel.red));
            data.putInt(index + 2, Float.floatToIntBits(pixel.green));
            data.putInt(index + 4, Float.floatToIntBits(pixel.blue));
            break;
        case RGBA32F:
            data.putInt(index, Float.floatToIntBits(pixel.red));
            data.putInt(index + 2, Float.floatToIntBits(pixel.green));
            data.putInt(index + 4, Float.floatToIntBits(pixel.blue));
            data.putInt(index + 6, Float.floatToIntBits(pixel.alpha));
            break;
        case RGB10:
        case RGB9E5:// TODO: support these
            throw new IllegalStateException("Not supported image type for IO operations: " + image.getFormat());
        default:
            throw new IllegalStateException("Unknown image format: " + image.getFormat());
    }
}
 
Example 13
Source File: TextureBlenderLuminance.java    From MikuMikuStudio with BSD 2-Clause "Simplified" License 4 votes vote down vote up
public Image blend(Image image, Image baseImage, BlenderContext blenderContext) {
    this.prepareImagesForBlending(image, baseImage);

    Format format = image.getFormat();
    PixelInputOutput basePixelIO = null;
    TexturePixel basePixel = null;
    float[] materialColor = this.materialColor;
    if (baseImage != null) {
        basePixelIO = PixelIOFactory.getPixelIO(baseImage.getFormat());
        materialColor = new float[this.materialColor.length];
        basePixel = new TexturePixel();
    }

    int width = image.getWidth();
    int height = image.getHeight();
    int depth = image.getDepth();
    if (depth == 0) {
        depth = 1;
    }
    ArrayList<ByteBuffer> dataArray = new ArrayList<ByteBuffer>(depth);

    float[] resultPixel = new float[4];
    float[] tinAndAlpha = new float[2];
    for (int dataLayerIndex = 0; dataLayerIndex < depth; ++dataLayerIndex) {
        ByteBuffer data = image.getData(dataLayerIndex);
        data.rewind();
        ByteBuffer newData = BufferUtils.createByteBuffer(width * height * 4);

        int dataIndex = 0, x = 0, y = 0;
        while (data.hasRemaining()) {
            // getting the proper material color if the base texture is applied
            if (basePixelIO != null) {
                basePixelIO.read(baseImage, dataLayerIndex, basePixel, x, y);
                basePixel.toRGBA(materialColor);
            }

            this.getTinAndAlpha(data, format, negateTexture, tinAndAlpha);
            this.blendPixel(resultPixel, materialColor, color, tinAndAlpha[0], blendFactor, blendType, blenderContext);
            newData.put(dataIndex++, (byte) (resultPixel[0] * 255.0f));
            newData.put(dataIndex++, (byte) (resultPixel[1] * 255.0f));
            newData.put(dataIndex++, (byte) (resultPixel[2] * 255.0f));
            newData.put(dataIndex++, (byte) (tinAndAlpha[1] * 255.0f));

            ++x;
            if (x >= width) {
                x = 0;
                ++y;
            }
        }
        dataArray.add(newData);
    }

    Image result = depth > 1 ? new Image(Format.RGBA8, width, height, depth, dataArray) : new Image(Format.RGBA8, width, height, dataArray.get(0));
    if (image.getMipMapSizes() != null) {
        result.setMipMapSizes(image.getMipMapSizes().clone());
    }
    return result;
}
 
Example 14
Source File: TextureBlenderAWT.java    From MikuMikuStudio with BSD 2-Clause "Simplified" License 4 votes vote down vote up
@Override
public Image blend(Image image, Image baseImage, BlenderContext blenderContext) {
    this.prepareImagesForBlending(image, baseImage);

    float[] pixelColor = new float[] { color[0], color[1], color[2], 1.0f };
    Format format = image.getFormat();

    PixelInputOutput basePixelIO = null, pixelReader = PixelIOFactory.getPixelIO(format);
    TexturePixel basePixel = null, pixel = new TexturePixel();
    float[] materialColor = this.materialColor;
    if (baseImage != null) {
        basePixelIO = PixelIOFactory.getPixelIO(baseImage.getFormat());
        materialColor = new float[this.materialColor.length];
        basePixel = new TexturePixel();
    }

    int width = image.getWidth();
    int height = image.getHeight();
    int depth = image.getDepth();
    if (depth == 0) {
        depth = 1;
    }
    ArrayList<ByteBuffer> dataArray = new ArrayList<ByteBuffer>(depth);

    float[] resultPixel = new float[4];
    for (int dataLayerIndex = 0; dataLayerIndex < depth; ++dataLayerIndex) {
        ByteBuffer data = image.getData(dataLayerIndex);
        data.rewind();
        ByteBuffer newData = BufferUtils.createByteBuffer(width * height * 4);

        int dataIndex = 0, x = 0, y = 0, index = 0;
        while (index < data.limit()) {
            // getting the proper material color if the base texture is applied
            if (basePixelIO != null) {
                basePixelIO.read(baseImage, dataLayerIndex, basePixel, x, y);
                basePixel.toRGBA(materialColor);
            }

            // reading the current texture's pixel
            pixelReader.read(image, dataLayerIndex, pixel, index);
            index += image.getFormat().getBitsPerPixel() >> 3;
            pixel.toRGBA(pixelColor);
            if (negateTexture) {
                pixel.negate();
            }

            this.blendPixel(resultPixel, materialColor, pixelColor, blenderContext);
            newData.put(dataIndex++, (byte) (resultPixel[0] * 255.0f));
            newData.put(dataIndex++, (byte) (resultPixel[1] * 255.0f));
            newData.put(dataIndex++, (byte) (resultPixel[2] * 255.0f));
            newData.put(dataIndex++, (byte) (pixelColor[3] * 255.0f));

            ++x;
            if (x >= width) {
                x = 0;
                ++y;
            }
        }
        dataArray.add(newData);
    }

    Image result = depth > 1 ? new Image(Format.RGBA8, width, height, depth, dataArray) : new Image(Format.RGBA8, width, height, dataArray.get(0));
    if (image.getMipMapSizes() != null) {
        result.setMipMapSizes(image.getMipMapSizes().clone());
    }
    return result;
}
 
Example 15
Source File: ImageToAwt.java    From MikuMikuStudio with BSD 2-Clause "Simplified" License 4 votes vote down vote up
/**
     * Convert the image from the given format to the output format.
     * It is assumed that both images have buffers with the appropriate
     * number of elements and that both have the same dimensions.
     *
     * @param input
     * @param output
     */
    public static void convert(Image input, Image output){
        DecodeParams inParams  = params.get(input.getFormat());
        DecodeParams outParams = params.get(output.getFormat());

        if (inParams == null || outParams == null)
            throw new UnsupportedOperationException();

        int width  = input.getWidth();
        int height = input.getHeight();

        if (width != output.getWidth() || height != output.getHeight())
            throw new IllegalArgumentException();

        ByteBuffer inData = input.getData(0);

        boolean inAlpha = false;
        boolean inLum = false;
        boolean inRGB = false;
        if (inParams.am != 0) {
            inAlpha = true;
        }

        if (inParams.rm != 0 && inParams.gm == 0 && inParams.bm == 0) {
            inLum = true;
        } else if (inParams.rm != 0 && inParams.gm != 0 && inParams.bm != 0) {
            inRGB = true;
        }

        int expansionA = 8 - Integer.bitCount(inParams.am);
        int expansionR = 8 - Integer.bitCount(inParams.rm);
        int expansionG = 8 - Integer.bitCount(inParams.gm);
        int expansionB = 8 - Integer.bitCount(inParams.bm);

        int inputPixel;
        for (int y = 0; y < height; y++){
            for (int x = 0; x < width; x++){
                int i = Ix(x, y, width) * inParams.bpp;
                inputPixel = (readPixel(inData, i, inParams.bpp) & inParams.im) >> inParams.is;
                
                int a = (inputPixel & inParams.am) >> inParams.as;
                int r = (inputPixel & inParams.rm) >> inParams.rs;
                int g = (inputPixel & inParams.gm) >> inParams.gs;
                int b = (inputPixel & inParams.bm) >> inParams.bs;

                r = r & 0xff;
                g = g & 0xff;
                b = b & 0xff;
                a = a & 0xff;

                a = a << expansionA;
                r = r << expansionR;
                g = g << expansionG;
                b = b << expansionB;

                if (inLum)
                    b = g = r;

                if (!inAlpha)
                    a = 0xff;

//                int argb = (a << 24) | (r << 16) | (g << 8) | b;
//                out.setRGB(x, y, argb);
            }
        }
    }
 
Example 16
Source File: TextureUtil.java    From jmonkeyengine with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
public void uploadSubTexture(int target, Image src, int index, int targetX, int targetY, int areaX, int areaY, int areaWidth, int areaHeight, boolean linearizeSrgb) {
    if (target != GL.GL_TEXTURE_2D || src.getDepth() > 1) {
        throw new UnsupportedOperationException("Updating non-2D texture is not supported");
    }

    if (src.getMipMapSizes() != null) {
        throw new UnsupportedOperationException("Updating mip-mappped images is not supported");
    }

    if (src.getMultiSamples() > 1) {
        throw new UnsupportedOperationException("Updating multisampled images is not supported");
    }

    Image.Format jmeFormat = src.getFormat();

    if (jmeFormat.isCompressed()) {
        throw new UnsupportedOperationException("Updating compressed images is not supported");
    } else if (jmeFormat.isDepthFormat()) {
        throw new UnsupportedOperationException("Updating depth images is not supported");
    }

    boolean getSrgbFormat = src.getColorSpace() == ColorSpace.sRGB && linearizeSrgb;
    GLImageFormat oglFormat = getImageFormatWithError(jmeFormat, getSrgbFormat);

    ByteBuffer data = src.getData(index);

    if (data == null) {
        throw new IndexOutOfBoundsException("The image index " + index + " is not valid for the given image");
    }

    int Bpp = src.getFormat().getBitsPerPixel() / 8;

    int srcWidth = src.getWidth();
    int cpos = data.position();
    int skip = areaX;
    skip += areaY * srcWidth;
    skip *= Bpp;

    data.position(skip);

    boolean needsStride = srcWidth != areaWidth;

    if (needsStride && (!supportUnpackRowLength)) { // doesn't support stride, copy row by row (slower).
        for (int i = 0; i < areaHeight; i++) {
            data.position(skip + (srcWidth * Bpp * i));
            gl.glTexSubImage2D(target, 0, targetX, targetY + i, areaWidth, 1, oglFormat.format, oglFormat.dataType, data);
        }
    } else {
        if (needsStride)
            gl2.glPixelStorei(GL.GL_UNPACK_ROW_LENGTH, srcWidth);
        gl.glTexSubImage2D(target, 0, targetX, targetY, areaWidth, areaHeight, oglFormat.format, oglFormat.dataType, data);
        if (needsStride)
            gl2.glPixelStorei(GL.GL_UNPACK_ROW_LENGTH, 0);
    }
    data.position(cpos);

}
 
Example 17
Source File: TextureUtil.java    From jmonkeyengine with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
/**
 * @deprecated Use uploadSubTexture(int target,  Image src, int index,int targetX, int targetY,int srcX,int srcY,  int areaWidth,int areaHeight, boolean linearizeSrgb) 
 */
@Deprecated
public void uploadSubTexture(Image image, int target, int index, int x, int y, boolean linearizeSrgb) {
    if (target != GL.GL_TEXTURE_2D || image.getDepth() > 1) {
        throw new UnsupportedOperationException("Updating non-2D texture is not supported");
    }
    
    if (image.getMipMapSizes() != null) {
        throw new UnsupportedOperationException("Updating mip-mapped images is not supported");
    }
    
    if (image.getMultiSamples() > 1) {
        throw new UnsupportedOperationException("Updating multisampled images is not supported");
    }
    
    Image.Format jmeFormat = image.getFormat();
    
    if (jmeFormat.isCompressed()) {
        throw new UnsupportedOperationException("Updating compressed images is not supported");
    } else if (jmeFormat.isDepthFormat()) {
        throw new UnsupportedOperationException("Updating depth images is not supported");
    }
    
    boolean getSrgbFormat = image.getColorSpace() == ColorSpace.sRGB && linearizeSrgb;
    GLImageFormat oglFormat = getImageFormatWithError(jmeFormat, getSrgbFormat);
    
    ByteBuffer data = null;
    
    if (index >= 0) {
        data = image.getData(index);
    }
    
    if (data == null) {
        throw new IndexOutOfBoundsException("The image index " + index + " is not valid for the given image");
    }

    data.position(0);
    data.limit(data.capacity());
    
    gl.glTexSubImage2D(target, 0, x, y, image.getWidth(), image.getHeight(), 
                       oglFormat.format, oglFormat.dataType, data);
}
 
Example 18
Source File: TextureUtil.java    From jmonkeyengine with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
public void uploadTexture(Image image,
                          int target,
                          int index,
                          boolean linearizeSrgb) {

    boolean getSrgbFormat = image.getColorSpace() == ColorSpace.sRGB && linearizeSrgb;
    Image.Format jmeFormat = image.getFormat();
    GLImageFormat oglFormat = getImageFormatWithError(jmeFormat, getSrgbFormat);

    ByteBuffer data = null;
    int sliceCount = 1;
    
    if (index >= 0) {
        data = image.getData(index);
    }
    
    if (image.getData() != null && image.getData().size() > 0) {
        sliceCount = image.getData().size();
    }

    int width = image.getWidth();
    int height = image.getHeight();
    int depth = image.getDepth();
    
    int[] mipSizes = image.getMipMapSizes();
    int pos = 0;
    // TODO: Remove unnecessary allocation
    if (mipSizes == null) {
        if (data != null) {
            mipSizes = new int[]{data.capacity()};
        } else {
            mipSizes = new int[]{width * height * jmeFormat.getBitsPerPixel() / 8};
        }
    }

    int samples = image.getMultiSamples();
    
    // For OGL3 core: setup texture swizzle.
    if (oglFormat.swizzleRequired) {
        setupTextureSwizzle(target, jmeFormat);
    }

    for (int i = 0; i < mipSizes.length; i++) {
        int mipWidth = Math.max(1, width >> i);
        int mipHeight = Math.max(1, height >> i);
        int mipDepth = Math.max(1, depth >> i);

        if (data != null) {
            data.position(pos);
            data.limit(pos + mipSizes[i]);
        }

        uploadTextureLevel(oglFormat, target, i, index, sliceCount, mipWidth, mipHeight, mipDepth, samples, data);

        pos += mipSizes[i];
    }
}
 
Example 19
Source File: ImageToAwt.java    From jmonkeyengine with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
/**
     * Convert the image from the given format to the output format.
     * It is assumed that both images have buffers with the appropriate
     * number of elements and that both have the same dimensions.
     *
     * @param input
     * @param output
     */
    public static void convert(Image input, Image output){
        DecodeParams inParams  = params.get(input.getFormat());
        DecodeParams outParams = params.get(output.getFormat());

        if (inParams == null || outParams == null)
            throw new UnsupportedOperationException();

        int width  = input.getWidth();
        int height = input.getHeight();

        if (width != output.getWidth() || height != output.getHeight())
            throw new IllegalArgumentException();

        ByteBuffer inData = input.getData(0);

        boolean inAlpha = false;
        boolean inLum = false;
        boolean inRGB = false;
        if (inParams.am != 0) {
            inAlpha = true;
        }

        if (inParams.rm != 0 && inParams.gm == 0 && inParams.bm == 0) {
            inLum = true;
        } else if (inParams.rm != 0 && inParams.gm != 0 && inParams.bm != 0) {
            inRGB = true;
        }

        int expansionA = 8 - Integer.bitCount(inParams.am);
        int expansionR = 8 - Integer.bitCount(inParams.rm);
        int expansionG = 8 - Integer.bitCount(inParams.gm);
        int expansionB = 8 - Integer.bitCount(inParams.bm);

        int inputPixel;
        for (int y = 0; y < height; y++){
            for (int x = 0; x < width; x++){
                int i = Ix(x, y, width) * inParams.bpp;
                inputPixel = (readPixel(inData, i, inParams.bpp) & inParams.im) >> inParams.is;
                
                int a = (inputPixel & inParams.am) >> inParams.as;
                int r = (inputPixel & inParams.rm) >> inParams.rs;
                int g = (inputPixel & inParams.gm) >> inParams.gs;
                int b = (inputPixel & inParams.bm) >> inParams.bs;

                r = r & 0xff;
                g = g & 0xff;
                b = b & 0xff;
                a = a & 0xff;

                a = a << expansionA;
                r = r << expansionR;
                g = g << expansionG;
                b = b << expansionB;

                if (inLum)
                    b = g = r;

                if (!inAlpha)
                    a = 0xff;

//                int argb = (a << 24) | (r << 16) | (g << 8) | b;
//                out.setRGB(x, y, argb);
            }
        }
    }
 
Example 20
Source File: PaintTerrainToolControl.java    From jmonkeybuilder with Apache License 2.0 4 votes vote down vote up
/**
 * Goes through each pixel in the image. At each pixel it looks to see if the UV mouse coordinate is within the
 * of the brush. If it is in the brush radius, it gets the existing color from that pixel so it can add/subtract to/from it.
 * Essentially it does a radius check and adds in a fade value. It does this to the color value returned by the
 * first pixel color query.
 * Next it sets the color of that pixel. If it was within the radius, the color will change. If it was outside
 * the radius, then nothing will change, the color will be the same; but it will set it nonetheless. Not efficient.
 * <p>
 * If the mouse is being dragged with the button down, then the dragged value should be set to true. This will reduce
 * the intensity of the brush to 10% of what it should be per spray. Otherwise it goes to 100% opacity within a few pixels.
 * This makes it work a little more realistically.
 *
 * @param colorFunction the color function.
 * @param image         to manipulate
 * @param uv            the world x,z coordinate
 * @param radius        in percentage so it can be translated to the image dimensions
 * @param erase         true if the tool should remove the paint instead of add it
 * @param fadeFalloff   the percentage of the radius when the paint begins to start fading
 */
@JmeThread
private void doPaintAction(@NotNull final ObjectFloatObjectConsumer<ColorRGBA, Boolean> colorFunction,
                           @NotNull final Image image, @NotNull final Vector2f uv, @NotNull final Vector2f temp,
                           @NotNull final ColorRGBA color, final float radius, final boolean erase,
                           final float fadeFalloff) {

    final ByteBuffer buffer = image.getData(0);

    final int width = image.getWidth();
    final float height = image.getHeight();

    // convert percents to pixels to limit how much we iterate
    final int minX = (int) Math.max(0, (uv.getX() * width - radius * width));
    final int maxX = (int) Math.min(width, (uv.getX() * width + radius * width));
    final int minY = (int) Math.max(0, (uv.getY() * height - radius * height));
    final int maxY = (int) Math.min(height, (uv.getY() * height + radius * height));

    final float radiusSquared = radius * radius;

    // go through each pixel, in the radius of the tool, in the image
    for (int y = minY; y < maxY; y++) {
        for (int x = minX; x < maxX; x++) {

            // gets the position in percentage so it can compare with the mouse UV coordinate
            temp.set((float) x / width, (float) y / height);

            float dist = temp.distanceSquared(uv);

            // if the pixel is within the distance of the radius, set a color (distance times intensity)
            if (dist < radiusSquared) {

                final int position = (y * width + x) * 4;
                if (position > buffer.capacity() - 1 || position < 0) {
                    continue;
                }

                // gets the color at that location (false means don't write to the buffer)
                manipulatePixel(image, buffer, color, position, false);

                // calculate the fade falloff intensity
                final float intensity = (1.0f - (dist / radiusSquared)) * fadeFalloff;

                colorFunction.accept(color, intensity, erase);
                color.clamp();

                change(position, color);

                // set the new color
                manipulatePixel(image, buffer, color, position, true);
            }
        }
    }

    image.getData(0).rewind();
}