Example usage for java.awt.geom Rectangle2D isEmpty

List of usage examples for java.awt.geom Rectangle2D isEmpty

Introduction

In this page you can find the example usage for java.awt.geom Rectangle2D isEmpty.

Prototype

public abstract boolean isEmpty();

Source Link

Document

Determines whether the RectangularShape is empty.

Usage

From source file:org.gumtree.vis.mask.ChartMaskingUtilities.java

private static void drawDomainMask(Graphics2D g2, Rectangle2D imageArea, RangeMask mask, RangeMask selectedMask,
        JFreeChart chart, double fontSizeRate, Color fillColor) {
    g2.clip(imageArea);//  w  ww . j a v  a 2  s .  co  m
    g2.setPaint(fillColor);
    Rectangle2D translatedRectangle = getDomainMaskFrame(mask, imageArea, chart);
    if (translatedRectangle == null || translatedRectangle.isEmpty()) {
        return;
    }
    drawMask(g2, translatedRectangle);
    if (mask == selectedMask) {
        drawMaskBoarder(g2, translatedRectangle);
    }
    drawMaskName(g2, mask, translatedRectangle, fontSizeRate);
}

From source file:com.gargoylesoftware.htmlunit.html.HtmlArea.java

private boolean isEmpty() {
    final String shape = StringUtils.defaultIfEmpty(getShapeAttribute(), "rect").toLowerCase(Locale.ROOT);

    if ("default".equals(shape) && getCoordsAttribute() != null) {
        return false;
    }/*w  w  w  .j a v a  2 s  .c o  m*/

    if ("rect".equals(shape) && getCoordsAttribute() != null) {
        final Rectangle2D rectangle = parseRect();
        return rectangle.isEmpty();
    }

    if ("circle".equals(shape) && getCoordsAttribute() != null) {
        final Ellipse2D ellipse = parseCircle();
        return ellipse.isEmpty();
    }

    if ("poly".equals(shape) && getCoordsAttribute() != null) {
        return false;
    }

    return false;
}

From source file:org.pentaho.plugin.jfreereport.reportcharts.JFreeChartReportDrawable.java

private AbstractImageMapEntry createMapEntry(final Shape area, final Rectangle2D dataArea) {
    if (buggyDrawArea) {
        if (area instanceof Ellipse2D) {
            final Ellipse2D ellipse2D = (Ellipse2D) area;
            if (ellipse2D.getWidth() == ellipse2D.getHeight()) {
                return new CircleImageMapEntry((float) (ellipse2D.getCenterX() + dataArea.getX()),
                        (float) (ellipse2D.getCenterY() + dataArea.getY()), (float) (ellipse2D.getWidth() / 2));
            }/*from  w w  w  . jav a 2s.  c  o  m*/
        } else if (area instanceof Rectangle2D) {
            final Rectangle2D rect = (Rectangle2D) area;
            return (new RectangleImageMapEntry((float) (rect.getX() + dataArea.getX()),
                    (float) (rect.getY() + dataArea.getY()), (float) (rect.getX() + rect.getWidth()),
                    (float) (rect.getY() + rect.getHeight())));
        }
    } else {
        if (area instanceof Ellipse2D) {
            final Ellipse2D ellipse2D = (Ellipse2D) area;
            if (ellipse2D.getWidth() == ellipse2D.getHeight()) {
                return new CircleImageMapEntry((float) (ellipse2D.getCenterX()),
                        (float) (ellipse2D.getCenterY()), (float) (ellipse2D.getWidth() / 2));
            }
        } else if (area instanceof Rectangle2D) {
            final Rectangle2D rect = (Rectangle2D) area;
            return (new RectangleImageMapEntry((float) (rect.getX()), (float) (rect.getY()),
                    (float) (rect.getX() + rect.getWidth()), (float) (rect.getY() + rect.getHeight())));
        }
    }

    final Area a = new Area(area);
    if (buggyDrawArea) {
        a.transform(AffineTransform.getTranslateInstance(dataArea.getX(), dataArea.getY()));
    }
    if (dataArea.isEmpty() == false) {
        a.intersect(new Area(dataArea));
    }
    final PathIterator pathIterator = a.getPathIterator(null, 2);
    final FloatList floats = new FloatList(100);
    final float[] coords = new float[6];
    while (pathIterator.isDone() == false) {
        final int retval = pathIterator.currentSegment(coords);
        if (retval == PathIterator.SEG_MOVETO || retval == PathIterator.SEG_LINETO) {
            floats.add(coords[0]);
            floats.add(coords[1]);
        }
        pathIterator.next();
    }

    if (floats.size() == 0) {
        return null;
    }
    return (new PolygonImageMapEntry(floats.toArray()));
}

From source file:org.gumtree.vis.hist2d.Hist2DPanel.java

protected int findCursorOnSelectedItem(int x, int y) {
    if (getSelectedMask() != null && !getSelectedMask().getRectangleFrame().isEmpty()) {
        Rectangle2D screenArea = getScreenDataArea();
        Rectangle2D maskArea = ChartMaskingUtilities
                .translateChartRectangle(getSelectedMask(), getScreenDataArea(), getChart())
                .getRectangleFrame();/*  w  ww.j a  va2 s .c om*/
        Rectangle2D intersect = screenArea.createIntersection(maskArea);
        Point2D point = new Point2D.Double(x, y);
        double minX = maskArea.getMinX();
        double maxX = maskArea.getMaxX();
        double minY = maskArea.getMinY();
        double maxY = maskArea.getMaxY();
        double width = maskArea.getWidth();
        double height = maskArea.getHeight();
        if (!intersect.isEmpty() && screenArea.contains(point)) {
            //              if (y > minY && y < maxY) {
            //                 if (minX > screenArea.getMinX() + 1 
            //                       && minX < screenArea.getMaxX() - 1) {
            //                       if (x > minX - 4 && x < minX + (width < 8 ? width / 2 : 4)) {
            //                          return Cursor.W_RESIZE_CURSOR;
            //                       } 
            //                 }
            //                 if (maxX > screenArea.getMinX() + 1 
            //                       && maxX < screenArea.getMaxX() - 1) {
            //                       if (x > maxX - (width < 8 ? width / 2 : 4) && x < maxX + 4) {
            //                          return Cursor.E_RESIZE_CURSOR;
            //                       } 
            //                 }
            //              }
            if (height > 8 && width > 8) {
                Rectangle2D center = new Rectangle2D.Double(minX + 4, minY + 4, width - 8, height - 8);
                if (screenArea.createIntersection(center).contains(point)) {
                    return Cursor.MOVE_CURSOR;
                }
            }
            if (height > 8) {
                Rectangle2D west = new Rectangle2D.Double(minX - 4, minY + 4, width < 8 ? width / 2 + 4 : 8,
                        height - 8);
                if (screenArea.createIntersection(west).contains(point)) {
                    return Cursor.W_RESIZE_CURSOR;
                }
                Rectangle2D east = new Rectangle2D.Double(maxX - (width < 8 ? width / 2 : 4), minY + 4,
                        width < 8 ? width / 2 + 4 : 8, height - 8);
                if (screenArea.createIntersection(east).contains(point)) {
                    return Cursor.E_RESIZE_CURSOR;
                }
            }
            if (width > 8) {
                Rectangle2D north = new Rectangle2D.Double(minX + 4, minY - 4, width - 8,
                        height < 8 ? height / 2 + 4 : 8);
                if (screenArea.createIntersection(north).contains(point)) {
                    return Cursor.N_RESIZE_CURSOR;
                }
                Rectangle2D south = new Rectangle2D.Double(minX + 4, maxY - (height < 8 ? height / 2 : 4),
                        width - 8, height < 8 ? height / 2 + 4 : 8);
                if (screenArea.createIntersection(south).contains(point)) {
                    return Cursor.S_RESIZE_CURSOR;
                }
            }
            Rectangle2D northwest = new Rectangle2D.Double(minX - 4, minY - 4, width < 8 ? width / 2 + 4 : 8,
                    height < 8 ? height / 2 + 4 : 8);
            if (screenArea.createIntersection(northwest).contains(point)) {
                return Cursor.NW_RESIZE_CURSOR;
            }
            Rectangle2D northeast = new Rectangle2D.Double(maxX - (width < 8 ? width / 2 : 4), minY - 4,
                    width < 8 ? width / 2 + 4 : 8, height < 8 ? height / 2 + 4 : 8);
            if (screenArea.createIntersection(northeast).contains(point)) {
                return Cursor.NE_RESIZE_CURSOR;
            }
            Rectangle2D southwest = new Rectangle2D.Double(minX - 4, maxY - (height < 8 ? height / 2 : 4),
                    width < 8 ? width / 2 + 4 : 8, height < 8 ? height / 2 + 4 : 8);
            if (screenArea.createIntersection(southwest).contains(point)) {
                return Cursor.SW_RESIZE_CURSOR;
            }
            Rectangle2D southeast = new Rectangle2D.Double(maxX - (width < 8 ? width / 2 : 4),
                    maxY - (height < 8 ? height / 2 : 4), width < 8 ? width / 2 + 4 : 8,
                    height < 8 ? height / 2 + 4 : 8);
            if (screenArea.createIntersection(southeast).contains(point)) {
                return Cursor.SE_RESIZE_CURSOR;
            }
        }
        //           System.out.println("intersect X:[" + intersect.getMinX() + ", " + 
        //                 (intersect.getMinX() + intersect.getWidth()) + 
        //                 "], Y:[" + intersect.getMinY() + ", " + 
        //                 (intersect.getMinY() + intersect.getHeight()) +
        //                 "], x=" + point.getX() + ", y=" + point.getY() + 
        //                 " " + intersect.contains(point));
    }
    return Cursor.DEFAULT_CURSOR;
}

From source file:org.gumtree.vis.plot1d.Plot1DPanel.java

protected int findCursorOnSelectedItem(int x, int y) {
    if (isInternalLegendEnabled && isInternalLegendSelected) {
        Rectangle2D screenArea = getScreenDataArea();
        Rectangle2D legendArea = new Rectangle2D.Double(screenArea.getMaxX() - internalLegendSetup.getMinX(),
                screenArea.getMinY() + internalLegendSetup.getMinY(), internalLegendSetup.getWidth(),
                internalLegendSetup.getHeight());
        Rectangle2D intersect = screenArea.createIntersection(legendArea);
        Point2D point = new Point2D.Double(x, y);
        double minX = legendArea.getMinX();
        double maxX = legendArea.getMaxX();
        double minY = legendArea.getMinY();
        double width = legendArea.getWidth();
        double height = legendArea.getHeight();
        if (!intersect.isEmpty() && screenArea.contains(point)) {
            if (width > 8) {
                Rectangle2D center = new Rectangle2D.Double(minX + 4, minY, width - 8, height);
                if (screenArea.createIntersection(center).contains(point)) {
                    return Cursor.MOVE_CURSOR;
                }/*w  w w  . j av  a  2 s  .  c  om*/
            }
            Rectangle2D west = new Rectangle2D.Double(minX - 4, minY, width < 8 ? width / 2 + 4 : 8, height);
            if (screenArea.createIntersection(west).contains(point)) {
                return Cursor.W_RESIZE_CURSOR;
            }
            Rectangle2D east = new Rectangle2D.Double(maxX - (width < 8 ? width / 2 : 4), minY,
                    width < 8 ? width / 2 + 4 : 8, height);
            if (screenArea.createIntersection(east).contains(point)) {
                return Cursor.E_RESIZE_CURSOR;
            }
        }
    } else if (getSelectedMask() != null && !getSelectedMask().isEmpty()) {
        Rectangle2D screenArea = getScreenDataArea();
        Rectangle2D maskArea = ChartMaskingUtilities.getDomainMaskFrame(getSelectedMask(), getScreenDataArea(),
                getChart());
        Rectangle2D intersect = screenArea.createIntersection(maskArea);
        Point2D point = new Point2D.Double(x, y);
        double minX = maskArea.getMinX();
        double maxX = maskArea.getMaxX();
        double minY = maskArea.getMinY();
        double width = maskArea.getWidth();
        double height = maskArea.getHeight();
        if (!intersect.isEmpty() && screenArea.contains(point)) {
            if (width > 8) {
                Rectangle2D center = new Rectangle2D.Double(minX + 4, minY, width - 8, height);
                if (screenArea.createIntersection(center).contains(point)) {
                    return Cursor.MOVE_CURSOR;
                }
            }
            Rectangle2D west = new Rectangle2D.Double(minX - 4, minY, width < 8 ? width / 2 + 4 : 8, height);
            if (screenArea.createIntersection(west).contains(point)) {
                return Cursor.W_RESIZE_CURSOR;
            }
            Rectangle2D east = new Rectangle2D.Double(maxX - (width < 8 ? width / 2 : 4), minY,
                    width < 8 ? width / 2 + 4 : 8, height);
            if (screenArea.createIntersection(east).contains(point)) {
                return Cursor.E_RESIZE_CURSOR;
            }
        }
    }
    return Cursor.DEFAULT_CURSOR;
}

From source file:org.esa.snap.graphbuilder.gpf.ui.worldmap.NestWorldMapPane.java

public void zoomToProduct(Product product) {
    final GeoPos[][] selGeoBoundaries = dataModel.getSelectedGeoBoundaries();
    if ((product == null || product.getSceneGeoCoding() == null) && selGeoBoundaries.length == 0) {
        return;//  www  .  j  ava  2  s.com
    }

    //NESTMOD
    final GeneralPath[] generalPaths;
    if (product != null && product.getSceneGeoCoding() != null) {
        generalPaths = getGeoBoundaryPaths(product);
    } else {
        final ArrayList<GeneralPath> pathList = assemblePathList(selGeoBoundaries[0]);
        generalPaths = pathList.toArray(new GeneralPath[pathList.size()]);
    }

    Rectangle2D modelArea = new Rectangle2D.Double();
    final Viewport viewport = layerCanvas.getViewport();
    for (GeneralPath generalPath : generalPaths) {
        final Rectangle2D rectangle2D = generalPath.getBounds2D();
        if (modelArea.isEmpty()) {
            if (!viewport.isModelYAxisDown()) {
                modelArea.setFrame(rectangle2D.getX(), rectangle2D.getMaxY(), rectangle2D.getWidth(),
                        rectangle2D.getHeight());
            }
            modelArea = rectangle2D;
        } else {
            modelArea.add(rectangle2D);
        }
    }
    Rectangle2D modelBounds = modelArea.getBounds2D();
    modelBounds.setFrame(modelBounds.getX() - 2, modelBounds.getY() - 2, modelBounds.getWidth() + 4,
            modelBounds.getHeight() + 4);

    modelBounds = cropToMaxModelBounds(modelBounds);

    viewport.zoom(modelBounds);
}

From source file:org.geotools.gce.imagemosaic.GranuleDescriptor.java

/**
* Load a specified a raster as a portion of the granule describe by this {@link GranuleDescriptor}.
* 
* @param imageReadParameters the {@link ImageReadParam} to use for reading.
* @param index the index to use for the {@link ImageReader}.
* @param cropBBox the bbox to use for cropping. 
* @param mosaicWorldToGrid the cropping grid to world transform.
* @param request the incoming request to satisfy.
* @param hints {@link Hints} to be used for creating this raster.
* @return a specified a raster as a portion of the granule describe by this {@link GranuleDescriptor}.
* @throws IOException in case an error occurs.
*///from   w w w.  j  av  a2s.  c o m
public GranuleLoadingResult loadRaster(final ImageReadParam imageReadParameters, final int index,
        final ReferencedEnvelope cropBBox, final MathTransform2D mosaicWorldToGrid,
        final RasterLayerRequest request, final Hints hints) throws IOException {

    if (LOGGER.isLoggable(java.util.logging.Level.FINER)) {
        final String name = Thread.currentThread().getName();
        LOGGER.finer("Thread:" + name + " Loading raster data for granuleDescriptor " + this.toString());
    }
    ImageReadParam readParameters = null;
    int imageIndex;
    final boolean useFootprint = roiProvider != null
            && request.getFootprintBehavior() != FootprintBehavior.None;
    Geometry inclusionGeometry = useFootprint ? roiProvider.getFootprint() : null;
    final ReferencedEnvelope bbox = useFootprint
            ? new ReferencedEnvelope(granuleBBOX.intersection(inclusionGeometry.getEnvelopeInternal()),
                    granuleBBOX.getCoordinateReferenceSystem())
            : granuleBBOX;
    boolean doFiltering = false;
    if (filterMe && useFootprint) {
        doFiltering = Utils.areaIsDifferent(inclusionGeometry, baseGridToWorld, granuleBBOX);
    }

    // intersection of this tile bound with the current crop bbox
    final ReferencedEnvelope intersection = new ReferencedEnvelope(bbox.intersection(cropBBox),
            cropBBox.getCoordinateReferenceSystem());
    if (intersection.isEmpty()) {
        if (LOGGER.isLoggable(java.util.logging.Level.FINE)) {
            LOGGER.fine(new StringBuilder("Got empty intersection for granule ").append(this.toString())
                    .append(" with request ").append(request.toString())
                    .append(" Resulting in no granule loaded: Empty result").toString());
        }
        return null;
    }

    // check if the requested bbox intersects or overlaps the requested area 
    if (useFootprint && inclusionGeometry != null && !JTS.toGeometry(cropBBox).intersects(inclusionGeometry)) {
        if (LOGGER.isLoggable(java.util.logging.Level.FINE)) {
            LOGGER.fine(new StringBuilder("Got empty intersection for granule ").append(this.toString())
                    .append(" with request ").append(request.toString())
                    .append(" Resulting in no granule loaded: Empty result").toString());
        }
        return null;
    }

    ImageInputStream inStream = null;
    ImageReader reader = null;
    try {
        //
        //get info about the raster we have to read
        //

        // get a stream
        assert cachedStreamSPI != null : "no cachedStreamSPI available!";
        inStream = cachedStreamSPI.createInputStreamInstance(granuleUrl, ImageIO.getUseCache(),
                ImageIO.getCacheDirectory());
        if (inStream == null)
            return null;

        // get a reader and try to cache the relevant SPI
        if (cachedReaderSPI == null) {
            reader = ImageIOExt.getImageioReader(inStream);
            if (reader != null)
                cachedReaderSPI = reader.getOriginatingProvider();
        } else
            reader = cachedReaderSPI.createReaderInstance();
        if (reader == null) {
            if (LOGGER.isLoggable(java.util.logging.Level.WARNING)) {
                LOGGER.warning(new StringBuilder("Unable to get s reader for granuleDescriptor ")
                        .append(this.toString()).append(" with request ").append(request.toString())
                        .append(" Resulting in no granule loaded: Empty result").toString());
            }
            return null;
        }
        // set input
        customizeReaderInitialization(reader, hints);
        reader.setInput(inStream);

        // Checking for heterogeneous granules
        if (request.isHeterogeneousGranules()) {
            // create read parameters
            readParameters = new ImageReadParam();

            //override the overviews controller for the base layer
            imageIndex = ReadParamsController.setReadParams(
                    request.spatialRequestHelper.getRequestedResolution(), request.getOverviewPolicy(),
                    request.getDecimationPolicy(), readParameters, request.rasterManager, overviewsController);
        } else {
            imageIndex = index;
            readParameters = imageReadParameters;
        }

        //get selected level and base level dimensions
        final GranuleOverviewLevelDescriptor selectedlevel = getLevel(imageIndex, reader);

        // now create the crop grid to world which can be used to decide
        // which source area we need to crop in the selected level taking
        // into account the scale factors imposed by the selection of this
        // level together with the base level grid to world transformation
        AffineTransform2D cropWorldToGrid = new AffineTransform2D(selectedlevel.gridToWorldTransformCorner);
        cropWorldToGrid = (AffineTransform2D) cropWorldToGrid.inverse();
        // computing the crop source area which lives into the
        // selected level raster space, NOTICE that at the end we need to
        // take into account the fact that we might also decimate therefore
        // we cannot just use the crop grid to world but we need to correct
        // it.
        final Rectangle sourceArea = CRS.transform(cropWorldToGrid, intersection).toRectangle2D().getBounds();
        //gutter
        if (selectedlevel.baseToLevelTransform.isIdentity()) {
            sourceArea.grow(2, 2);
        }
        XRectangle2D.intersect(sourceArea, selectedlevel.rasterDimensions, sourceArea);//make sure roundings don't bother us
        // is it empty??
        if (sourceArea.isEmpty()) {
            if (LOGGER.isLoggable(java.util.logging.Level.FINE)) {
                LOGGER.fine("Got empty area for granuleDescriptor " + this.toString() + " with request "
                        + request.toString() + " Resulting in no granule loaded: Empty result");

            }
            return null;

        } else if (LOGGER.isLoggable(java.util.logging.Level.FINER)) {
            LOGGER.finer("Loading level " + imageIndex + " with source region: " + sourceArea + " subsampling: "
                    + readParameters.getSourceXSubsampling() + "," + readParameters.getSourceYSubsampling()
                    + " for granule:" + granuleUrl);
        }

        // Setting subsampling 
        int newSubSamplingFactor = 0;
        final String pluginName = cachedReaderSPI.getPluginClassName();
        if (pluginName != null && pluginName.equals(ImageUtilities.DIRECT_KAKADU_PLUGIN)) {
            final int ssx = readParameters.getSourceXSubsampling();
            final int ssy = readParameters.getSourceYSubsampling();
            newSubSamplingFactor = ImageIOUtilities.getSubSamplingFactor2(ssx, ssy);
            if (newSubSamplingFactor != 0) {
                if (newSubSamplingFactor > maxDecimationFactor && maxDecimationFactor != -1) {
                    newSubSamplingFactor = maxDecimationFactor;
                }
                readParameters.setSourceSubsampling(newSubSamplingFactor, newSubSamplingFactor, 0, 0);
            }
        }

        // set the source region
        readParameters.setSourceRegion(sourceArea);
        RenderedImage raster;
        try {
            // read
            raster = request.getReadType().read(readParameters, imageIndex, granuleUrl,
                    selectedlevel.rasterDimensions, reader, hints, false);

        } catch (Throwable e) {
            if (LOGGER.isLoggable(java.util.logging.Level.FINE)) {
                LOGGER.log(java.util.logging.Level.FINE,
                        "Unable to load raster for granuleDescriptor " + this.toString() + " with request "
                                + request.toString() + " Resulting in no granule loaded: Empty result",
                        e);
            }
            return null;
        }

        // use fixed source area
        sourceArea.setRect(readParameters.getSourceRegion());

        //
        // setting new coefficients to define a new affineTransformation
        // to be applied to the grid to world transformation
        // -----------------------------------------------------------------------------------
        //
        // With respect to the original envelope, the obtained planarImage
        // needs to be rescaled. The scaling factors are computed as the
        // ratio between the cropped source region sizes and the read
        // image sizes.
        //
        // place it in the mosaic using the coords created above;
        double decimationScaleX = ((1.0 * sourceArea.width) / raster.getWidth());
        double decimationScaleY = ((1.0 * sourceArea.height) / raster.getHeight());
        final AffineTransform decimationScaleTranform = XAffineTransform.getScaleInstance(decimationScaleX,
                decimationScaleY);

        // keep into account translation  to work into the selected level raster space
        final AffineTransform afterDecimationTranslateTranform = XAffineTransform
                .getTranslateInstance(sourceArea.x, sourceArea.y);

        // now we need to go back to the base level raster space
        final AffineTransform backToBaseLevelScaleTransform = selectedlevel.baseToLevelTransform;

        // now create the overall transform
        final AffineTransform finalRaster2Model = new AffineTransform(baseGridToWorld);
        finalRaster2Model.concatenate(CoverageUtilities.CENTER_TO_CORNER);

        if (!XAffineTransform.isIdentity(backToBaseLevelScaleTransform, Utils.AFFINE_IDENTITY_EPS))
            finalRaster2Model.concatenate(backToBaseLevelScaleTransform);
        if (!XAffineTransform.isIdentity(afterDecimationTranslateTranform, Utils.AFFINE_IDENTITY_EPS))
            finalRaster2Model.concatenate(afterDecimationTranslateTranform);
        if (!XAffineTransform.isIdentity(decimationScaleTranform, Utils.AFFINE_IDENTITY_EPS))
            finalRaster2Model.concatenate(decimationScaleTranform);

        // adjust roi
        if (useFootprint) {

            ROIGeometry transformed;
            try {
                transformed = roiProvider.getTransformedROI(finalRaster2Model.createInverse());
                if (transformed.getAsGeometry().isEmpty()) {
                    // inset might have killed the geometry fully
                    return null;
                }

                PlanarImage pi = PlanarImage.wrapRenderedImage(raster);
                if (!transformed.intersects(pi.getBounds())) {
                    return null;
                }
                pi.setProperty("ROI", transformed);
                raster = pi;

            } catch (NoninvertibleTransformException e) {
                if (LOGGER.isLoggable(java.util.logging.Level.INFO))
                    LOGGER.info("Unable to create a granuleDescriptor " + this.toString()
                            + " due to a problem when managing the ROI");
                return null;
            }

        }
        // keep into account translation factors to place this tile
        finalRaster2Model.preConcatenate((AffineTransform) mosaicWorldToGrid);
        final Interpolation interpolation = request.getInterpolation();

        //paranoiac check to avoid that JAI freaks out when computing its internal layouT on images that are too small
        Rectangle2D finalLayout = ImageUtilities.layoutHelper(raster, (float) finalRaster2Model.getScaleX(),
                (float) finalRaster2Model.getScaleY(), (float) finalRaster2Model.getTranslateX(),
                (float) finalRaster2Model.getTranslateY(), interpolation);
        if (finalLayout.isEmpty()) {
            if (LOGGER.isLoggable(java.util.logging.Level.INFO))
                LOGGER.info("Unable to create a granuleDescriptor " + this.toString()
                        + " due to jai scale bug creating a null source area");
            return null;
        }

        // apply the affine transform  conserving indexed color model
        final RenderingHints localHints = new RenderingHints(JAI.KEY_REPLACE_INDEX_COLOR_MODEL,
                interpolation instanceof InterpolationNearest ? Boolean.FALSE : Boolean.TRUE);
        if (XAffineTransform.isIdentity(finalRaster2Model, Utils.AFFINE_IDENTITY_EPS)) {
            return new GranuleLoadingResult(raster, null, granuleUrl, doFiltering, pamDataset);
        } else {
            //
            // In case we are asked to use certain tile dimensions we tile
            // also at this stage in case the read type is Direct since
            // buffered images comes up untiled and this can affect the
            // performances of the subsequent affine operation.
            //
            final Dimension tileDimensions = request.getTileDimensions();
            if (tileDimensions != null && request.getReadType().equals(ReadType.DIRECT_READ)) {
                final ImageLayout layout = new ImageLayout();
                layout.setTileHeight(tileDimensions.width).setTileWidth(tileDimensions.height);
                localHints.add(new RenderingHints(JAI.KEY_IMAGE_LAYOUT, layout));
            } else {
                if (hints != null && hints.containsKey(JAI.KEY_IMAGE_LAYOUT)) {
                    final Object layout = hints.get(JAI.KEY_IMAGE_LAYOUT);
                    if (layout != null && layout instanceof ImageLayout) {
                        localHints
                                .add(new RenderingHints(JAI.KEY_IMAGE_LAYOUT, ((ImageLayout) layout).clone()));
                    }
                }
            }
            if (hints != null && hints.containsKey(JAI.KEY_TILE_CACHE)) {
                final Object cache = hints.get(JAI.KEY_TILE_CACHE);
                if (cache != null && cache instanceof TileCache)
                    localHints.add(new RenderingHints(JAI.KEY_TILE_CACHE, (TileCache) cache));
            }
            if (hints != null && hints.containsKey(JAI.KEY_TILE_SCHEDULER)) {
                final Object scheduler = hints.get(JAI.KEY_TILE_SCHEDULER);
                if (scheduler != null && scheduler instanceof TileScheduler)
                    localHints.add(new RenderingHints(JAI.KEY_TILE_SCHEDULER, (TileScheduler) scheduler));
            }
            boolean addBorderExtender = true;
            if (hints != null && hints.containsKey(JAI.KEY_BORDER_EXTENDER)) {
                final Object extender = hints.get(JAI.KEY_BORDER_EXTENDER);
                if (extender != null && extender instanceof BorderExtender) {
                    localHints.add(new RenderingHints(JAI.KEY_BORDER_EXTENDER, (BorderExtender) extender));
                    addBorderExtender = false;
                }
            }
            // BORDER extender
            if (addBorderExtender) {
                localHints.add(ImageUtilities.BORDER_EXTENDER_HINTS);
            }

            ImageWorker iw = new ImageWorker(raster);
            iw.setRenderingHints(localHints);
            iw.affine(finalRaster2Model, interpolation, request.getBackgroundValues());
            return new GranuleLoadingResult(iw.getRenderedImage(), null, granuleUrl, doFiltering, pamDataset);
        }

    } catch (IllegalStateException e) {
        if (LOGGER.isLoggable(java.util.logging.Level.WARNING)) {
            LOGGER.log(java.util.logging.Level.WARNING,
                    new StringBuilder("Unable to load raster for granuleDescriptor ").append(this.toString())
                            .append(" with request ").append(request.toString())
                            .append(" Resulting in no granule loaded: Empty result").toString(),
                    e);
        }
        return null;
    } catch (org.opengis.referencing.operation.NoninvertibleTransformException e) {
        if (LOGGER.isLoggable(java.util.logging.Level.WARNING)) {
            LOGGER.log(java.util.logging.Level.WARNING,
                    new StringBuilder("Unable to load raster for granuleDescriptor ").append(this.toString())
                            .append(" with request ").append(request.toString())
                            .append(" Resulting in no granule loaded: Empty result").toString(),
                    e);
        }
        return null;
    } catch (TransformException e) {
        if (LOGGER.isLoggable(java.util.logging.Level.WARNING)) {
            LOGGER.log(java.util.logging.Level.WARNING,
                    new StringBuilder("Unable to load raster for granuleDescriptor ").append(this.toString())
                            .append(" with request ").append(request.toString())
                            .append(" Resulting in no granule loaded: Empty result").toString(),
                    e);
        }
        return null;

    } finally {
        try {
            if (request.getReadType() != ReadType.JAI_IMAGEREAD && inStream != null) {
                inStream.close();
            }
        } finally {
            if (request.getReadType() != ReadType.JAI_IMAGEREAD && reader != null) {
                reader.dispose();
            }
        }
    }
}