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

The following examples show how to use com.jme3.texture.Image#getFormat() . 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: SkyFactory.java    From jmonkeyengine with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/**
 * Create a cube-mapped sky using six textures.
 *
 * @param assetManager from which to load materials
 * @param west texture for the western face of the cube
 * @param east texture for the eastern face of the cube
 * @param north texture for the northern face of the cube
 * @param south texture for the southern face of the cube
 * @param up texture for the top face of the cube
 * @param down texture for the bottom face of the cube
 * @param normalScale The normal scale is multiplied by the 3D normal to get
 * a texture coordinate. Use Vector3f.UNIT_XYZ to not apply and
 * transformation to the normal.
 * @param sphereRadius the sky sphere's radius: for the sky to be visible,
 * its radius must fall between the near and far planes of the camera's
 * frustum
 * @return a new spatial representing the sky, ready to be attached to the
 * scene graph
 */
public static Spatial createSky(AssetManager assetManager, Texture west,
        Texture east, Texture north, Texture south, Texture up,
        Texture down, Vector3f normalScale, float sphereRadius) {

    Image westImg = west.getImage();
    Image eastImg = east.getImage();
    Image northImg = north.getImage();
    Image southImg = south.getImage();
    Image upImg = up.getImage();
    Image downImg = down.getImage();

    checkImagesForCubeMap(westImg, eastImg, northImg, southImg, upImg, downImg);

    Image cubeImage = new Image(westImg.getFormat(), westImg.getWidth(), westImg.getHeight(), null, westImg.getColorSpace());

    cubeImage.addData(westImg.getData(0));
    cubeImage.addData(eastImg.getData(0));
    cubeImage.addData(downImg.getData(0));
    cubeImage.addData(upImg.getData(0));
    cubeImage.addData(southImg.getData(0));
    cubeImage.addData(northImg.getData(0));
    
    TextureCubeMap cubeMap = new TextureCubeMap(cubeImage);
    return createSky(assetManager, cubeMap, normalScale, EnvMapType.CubeMap, sphereRadius);
}
 
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: 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 4
Source File: GLRenderer.java    From jmonkeyengine with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 * @deprecated Use modifyTexture(Texture2D dest, Image src, int destX, int destY, int srcX, int srcY, int areaW, int areaH)
 */
@Deprecated
@Override
public void modifyTexture(Texture tex, Image pixels, int x, int y) {
    setTexture(0, tex);
    if(caps.contains(Caps.OpenGLES20) && pixels.getFormat()!=tex.getImage().getFormat() ) {
        logger.log(Level.WARNING, "Incompatible texture subimage");
    }
    int target = convertTextureType(tex.getType(), pixels.getMultiSamples(), -1);
    texUtil.uploadSubTexture(target,pixels, 0, x, y,0,0,pixels.getWidth(),pixels.getHeight(), linearizeSrgbImages);     
}
 
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: TextureHelper.java    From MikuMikuStudio with BSD 2-Clause "Simplified" License 5 votes vote down vote up
/**
 * This method returns subimage of the give image. The subimage is
 * constrained by the rectangle coordinates. The source image is unchanged.
 * 
 * @param image
 *            the image to be subimaged
 * @param minX
 *            minimum X position
 * @param minY
 *            minimum Y position
 * @param maxX
 *            maximum X position
 * @param maxY
 *            maximum Y position
 * @return a part of the given image
 */
public Image getSubimage(Image image, int minX, int minY, int maxX, int maxY) {
    if (minY > maxY) {
        throw new IllegalArgumentException("Minimum Y value is higher than maximum Y value!");
    }
    if (minX > maxX) {
        throw new IllegalArgumentException("Minimum Y value is higher than maximum Y value!");
    }
    if (image.getData().size() > 1) {
        throw new IllegalArgumentException("Only flat images are allowed for subimage operation!");
    }
    if (image.getMipMapSizes() != null) {
        LOGGER.warning("Subimaging image with mipmaps is not yet supported!");
    }

    int width = maxX - minX;
    int height = maxY - minY;
    ByteBuffer data = BufferUtils.createByteBuffer(width * height * (image.getFormat().getBitsPerPixel() >> 3));

    Image result = new Image(image.getFormat(), width, height, data);
    PixelInputOutput pixelIO = PixelIOFactory.getPixelIO(image.getFormat());
    TexturePixel pixel = new TexturePixel();

    for (int x = minX; x < maxX; ++x) {
        for (int y = minY; y < maxY; ++y) {
            pixelIO.read(image, 0, pixel, x, y);
            pixelIO.write(result, 0, pixel, x - minX, y - minY);
        }
    }
    return result;
}
 
Example 8
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 9
Source File: SkyFactory.java    From MikuMikuStudio with BSD 2-Clause "Simplified" License 4 votes vote down vote up
public static Spatial createSky(AssetManager assetManager, Texture west, Texture east, Texture north, Texture south, Texture up, Texture down, Vector3f normalScale, int sphereRadius) {
    final Sphere sphereMesh = new Sphere(10, 10, sphereRadius, false, true);
    Geometry sky = new Geometry("Sky", sphereMesh);
    sky.setQueueBucket(Bucket.Sky);
    sky.setCullHint(Spatial.CullHint.Never);
    sky.setModelBound(new BoundingSphere(Float.POSITIVE_INFINITY, Vector3f.ZERO));

    Image westImg = west.getImage();
    Image eastImg = east.getImage();
    Image northImg = north.getImage();
    Image southImg = south.getImage();
    Image upImg = up.getImage();
    Image downImg = down.getImage();

    checkImagesForCubeMap(westImg, eastImg, northImg, southImg, upImg, downImg);

    Image cubeImage = new Image(westImg.getFormat(), westImg.getWidth(), westImg.getHeight(), null);

    cubeImage.addData(westImg.getData(0));
    cubeImage.addData(eastImg.getData(0));

    cubeImage.addData(downImg.getData(0));
    cubeImage.addData(upImg.getData(0));

    cubeImage.addData(southImg.getData(0));
    cubeImage.addData(northImg.getData(0));
    
    if (westImg.getEfficentData() != null){
        // also consilidate efficient data
        ArrayList<Object> efficientData = new ArrayList<Object>(6);
        efficientData.add(westImg.getEfficentData());
        efficientData.add(eastImg.getEfficentData());
        efficientData.add(downImg.getEfficentData());
        efficientData.add(upImg.getEfficentData());
        efficientData.add(southImg.getEfficentData());
        efficientData.add(northImg.getEfficentData());
        cubeImage.setEfficentData(efficientData);
    }

    TextureCubeMap cubeMap = new TextureCubeMap(cubeImage);
    cubeMap.setAnisotropicFilter(0);
    cubeMap.setMagFilter(Texture.MagFilter.Bilinear);
    cubeMap.setMinFilter(Texture.MinFilter.NearestNoMipMaps);
    cubeMap.setWrap(Texture.WrapMode.EdgeClamp);

    Material skyMat = new Material(assetManager, "Common/MatDefs/Misc/Sky.j3md");
    skyMat.setTexture("Texture", cubeMap);
    skyMat.setVector3("NormalScale", normalScale);
    sky.setMaterial(skyMat);

    return sky;
}
 
Example 10
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 11
Source File: AWTPixelInputOutput.java    From MikuMikuStudio with BSD 2-Clause "Simplified" License 4 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 RGBA8:
            pixel.fromARGB8(data.get(index + 3), data.get(index), data.get(index + 1), data.get(index + 2));
            break;
        case ABGR8:
            pixel.fromARGB8(data.get(index), data.get(index + 3), data.get(index + 2), data.get(index + 1));
            break;
        case BGR8:
            pixel.fromARGB8((byte) 0xFF, data.get(index + 2), data.get(index + 1), data.get(index));
            break;
        case RGB8:
            pixel.fromARGB8((byte) 0xFF, data.get(index), data.get(index + 1), data.get(index + 2));
            break;
        case RGB565:
            pixel.fromARGB8(RGB565.RGB565_to_ARGB8(data.getShort(index)));
            break;
        case RGB5A1:
            short rgb5a1 = data.getShort(index);
            byte a = (byte) (rgb5a1 & 0x01);
            int r = (rgb5a1 & 0xf800) >> 11 << 3;
            int g = (rgb5a1 & 0x07c0) >> 6 << 3;
            int b = (rgb5a1 & 0x001f) >> 1 << 3;
            pixel.fromARGB8(a == 1 ? (byte) 255 : 0, (byte) r, (byte) g, (byte) b);
            break;
        case RGB16:
            pixel.fromARGB16((short) 0xFFFF, data.getShort(index), data.getShort(index + 2), data.getShort(index + 4));
            break;
        case RGBA16:
            pixel.fromARGB16(data.getShort(index + 6), data.getShort(index), data.getShort(index + 2), data.getShort(index + 4));
            break;
        case RGB16F:
        case RGB16F_to_RGB111110F:
        case RGB16F_to_RGB9E5:
            pixel.fromARGB(1, FastMath.convertHalfToFloat(data.getShort(index)), FastMath.convertHalfToFloat(data.getShort(index + 2)), FastMath.convertHalfToFloat(data.getShort(index + 4)));
            break;
        case RGBA16F:
            pixel.fromARGB(FastMath.convertHalfToFloat(data.getShort(index + 6)), FastMath.convertHalfToFloat(data.getShort(index)), FastMath.convertHalfToFloat(data.getShort(index + 2)), FastMath.convertHalfToFloat(data.getShort(index + 4)));
            break;
        case RGBA32F:
            pixel.fromARGB(Float.intBitsToFloat(data.getInt(index + 12)), Float.intBitsToFloat(data.getInt(index)), Float.intBitsToFloat(data.getInt(index + 4)), Float.intBitsToFloat(data.getInt(index + 8)));
            break;
        case RGB111110F:// the data is stored as 32-bit unsigned int, that is why we cast the read data to long and remove MSB-bytes to get the positive value
            pixel.fromARGB(1, (float) Double.longBitsToDouble((long) data.getInt(index) & 0x00000000FFFFFFFF), (float) Double.longBitsToDouble((long) data.getInt(index + 4) & 0x00000000FFFFFFFF), (float) Double.longBitsToDouble((long) data.getInt(index + 8) & 0x00000000FFFFFFFF));
            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 12
Source File: CombinedTexture.java    From MikuMikuStudio with BSD 2-Clause "Simplified" License 4 votes vote down vote up
/**
 * This method determines if the given texture has no alpha channel.
 * 
 * @param texture
 *            the texture to check for alpha channel
 * @return <b>true</b> if the texture has no alpha channel and <b>false</b>
 *         otherwise
 */
private boolean isWithoutAlpha(TextureData textureData, BlenderContext blenderContext) {
    ColorBand colorBand = new ColorBand(textureData.textureStructure, blenderContext);
    if (!colorBand.hasTransparencies()) {
        int type = ((Number) textureData.textureStructure.getFieldValue("type")).intValue();
        if (type == TextureHelper.TEX_MAGIC) {
            return true;
        }
        if (type == TextureHelper.TEX_VORONOI) {
            int voronoiColorType = ((Number) textureData.textureStructure.getFieldValue("vn_coltype")).intValue();
            return voronoiColorType != 0;// voronoiColorType == 0:
                                         // intensity, voronoiColorType
                                         // != 0: col1, col2 or col3
        }
        if (type == TextureHelper.TEX_CLOUDS) {
            int sType = ((Number) textureData.textureStructure.getFieldValue("stype")).intValue();
            return sType == 1;// sType==0: without colors, sType==1: with
                              // colors
        }

        // checking the flat textures for alpha values presence
        if (type == TextureHelper.TEX_IMAGE) {
            Image image = textureData.texture.getImage();
            switch (image.getFormat()) {
                case BGR8:
                case DXT1:
                case Luminance16:
                case Luminance16F:
                case Luminance32F:
                case Luminance8:
                case RGB10:
                case RGB111110F:
                case RGB16:
                case RGB16F:
                case RGB32F:
                case RGB565:
                case RGB8:
                    return true;// these types have no alpha by definition
                case ABGR8:
                case DXT3:
                case DXT5:
                case Luminance16Alpha16:
                case Luminance16FAlpha16F:
                case Luminance8Alpha8:
                case RGBA16:
                case RGBA16F:
                case RGBA32F:
                case RGBA8:// with these types it is better to make sure if the texture is or is not transparent
                    PixelInputOutput pixelInputOutput = PixelIOFactory.getPixelIO(image.getFormat());
                    TexturePixel pixel = new TexturePixel();
                    int depth = image.getDepth() == 0 ? 1 : image.getDepth();
                    for (int layerIndex = 0; layerIndex < depth; ++layerIndex) {
                        for (int x = 0; x < image.getWidth(); ++x) {
                            for (int y = 0; y < image.getHeight(); ++y) {
                                pixelInputOutput.read(image, layerIndex, pixel, x, y);
                                if (pixel.alpha < 1.0f) {
                                    return false;
                                }
                            }
                        }
                    }
                    return true;
            }
        }
    }
    return false;
}
 
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: MipMapGenerator.java    From jmonkeyengine with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
public static void generateMipMaps(Image image){
    BufferedImage original = ImageToAwt.convert(image, false, true, 0);
    int width = original.getWidth();
    int height = original.getHeight();
    int level = 0;

    BufferedImage current = original;
    AWTLoader loader = new AWTLoader();
    ArrayList<ByteBuffer> output = new ArrayList<ByteBuffer>();
    int totalSize = 0;
    Format format = null;
    
    while (height >= 1 || width >= 1){
        Image converted = loader.load(current, false);
        format = converted.getFormat();
        output.add(converted.getData(0));
        totalSize += converted.getData(0).capacity();

        if(height == 1 || width == 1) {
          break;
        }

        level++;

        height /= 2;
        width /= 2;

        current = scaleDown(current, width, height);
    }

    ByteBuffer combinedData = BufferUtils.createByteBuffer(totalSize);
    int[] mipSizes = new int[output.size()];
    for (int i = 0; i < output.size(); i++){
        ByteBuffer data = output.get(i);
        data.clear();
        combinedData.put(data);
        mipSizes[i] = data.capacity();
    }
    combinedData.flip();

    // insert mip data into image
    image.setData(0, combinedData);
    image.setMipMapSizes(mipSizes);
    image.setFormat(format);
}
 
Example 15
Source File: MipMapGenerator.java    From MikuMikuStudio with BSD 2-Clause "Simplified" License 4 votes vote down vote up
public static void generateMipMaps(Image image){
    BufferedImage original = ImageToAwt.convert(image, false, true, 0);
    int width = original.getWidth();
    int height = original.getHeight();
    int level = 0;

    BufferedImage current = original;
    AWTLoader loader = new AWTLoader();
    ArrayList<ByteBuffer> output = new ArrayList<ByteBuffer>();
    int totalSize = 0;
    Format format = null;
    
    while (height >= 1 || width >= 1){
        Image converted = loader.load(current, false);
        format = converted.getFormat();
        output.add(converted.getData(0));
        totalSize += converted.getData(0).capacity();

        if(height == 1 || width == 1) {
          break;
        }

        level++;

        height /= 2;
        width /= 2;

        current = scaleDown(current, width, height);
    }

    ByteBuffer combinedData = BufferUtils.createByteBuffer(totalSize);
    int[] mipSizes = new int[output.size()];
    for (int i = 0; i < output.size(); i++){
        ByteBuffer data = output.get(i);
        data.clear();
        combinedData.put(data);
        mipSizes[i] = data.capacity();
    }
    combinedData.flip();

    // insert mip data into image
    image.setData(0, combinedData);
    image.setMipMapSizes(mipSizes);
    image.setFormat(format);
}
 
Example 16
Source File: MipMapGenerator.java    From jmonkeyengine with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
public static Image scaleImage(Image inputImage, int outputWidth, int outputHeight) {
    int size = outputWidth * outputHeight * inputImage.getFormat().getBitsPerPixel() / 8;
    ByteBuffer buffer = BufferUtils.createByteBuffer(size);
    Image outputImage = new Image(inputImage.getFormat(), 
                                  outputWidth, 
                                  outputHeight, 
                                  buffer, 
                                  inputImage.getColorSpace());
    
    ImageRaster input = ImageRaster.create(inputImage, 0, 0, false);
    ImageRaster output = ImageRaster.create(outputImage, 0, 0, false);
    
    float xRatio = ((float)(input.getWidth()  - 1)) / output.getWidth();
    float yRatio = ((float)(input.getHeight() - 1)) / output.getHeight();

    ColorRGBA outputColor = new ColorRGBA(0, 0, 0, 0);
    ColorRGBA bottomLeft = new ColorRGBA();
    ColorRGBA bottomRight = new ColorRGBA();
    ColorRGBA topLeft = new ColorRGBA();
    ColorRGBA topRight = new ColorRGBA();
    
    for (int y = 0; y < outputHeight; y++) {
        for (int x = 0; x < outputWidth; x++) {
            float x2f = x * xRatio;
            float y2f = y * yRatio;
            
            int x2 = (int)x2f;
            int y2 = (int)y2f;

            input.getPixel(x2,     y2,     bottomLeft);
            input.getPixel(x2 + 1, y2,     bottomRight);
            input.getPixel(x2,     y2 + 1, topLeft);
            input.getPixel(x2 + 1, y2 + 1, topRight);

            outputColor.set(bottomLeft).addLocal(bottomRight)
                       .addLocal(topLeft).addLocal(topRight);
            outputColor.multLocal(1f / 4f);
            output.setPixel(x, y, outputColor);
        }
    }
    return outputImage;
}
 
Example 17
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 18
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 19
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 20
Source File: GLRenderer.java    From jmonkeyengine with BSD 3-Clause "New" or "Revised" License 3 votes vote down vote up
/**
 * Copy a part of an image to a texture 2d.
 * @param dest The destination image, where the source will be copied
 * @param src The source image that contains the data to copy
 * @param destX First pixel of the destination image from where the src image will be drawn (x component)
 * @param destY First pixel of the destination image from where the src image will be drawn (y component)
 * @param srcX  First pixel to copy (x component)
 * @param srcY  First pixel to copy (y component)
 * @param areaW Width of the area to copy
 * @param areaH Height of the area to copy
 */
public void modifyTexture(Texture2D dest, Image src, int destX, int destY, int srcX, int srcY, int areaW, int areaH) {
    setTexture(0, dest);
    if(caps.contains(Caps.OpenGLES20) && src.getFormat()!=dest.getImage().getFormat() ) {
        logger.log(Level.WARNING, "Incompatible texture subimage");
    }
    int target = convertTextureType(dest.getType(), src.getMultiSamples(), -1);
    texUtil.uploadSubTexture(target, src, 0, destX, destY, srcX, srcY, areaW, areaH, linearizeSrgbImages);
}