public int countImagesInSector(Sector sector, int levelNumber) {
    if (sector == null) {
      String msg = Logging.getMessage("nullValue.SectorIsNull");
      Logging.logger().severe(msg);
      throw new IllegalArgumentException(msg);
    }

    Level targetLevel = this.levels.getLastLevel();
    if (levelNumber >= 0) {
      for (int i = levelNumber; i < this.getLevels().getLastLevel().getLevelNumber(); i++) {
        if (this.levels.isLevelEmpty(i)) continue;

        targetLevel = this.levels.getLevel(i);
        break;
      }
    }

    // Collect all the tiles intersecting the input sector.
    LatLon delta = targetLevel.getTileDelta();
    Angle latOrigin = this.levels.getTileOrigin().getLatitude();
    Angle lonOrigin = this.levels.getTileOrigin().getLongitude();
    final int nwRow = Tile.computeRow(delta.getLatitude(), sector.getMaxLatitude(), latOrigin);
    final int nwCol = Tile.computeColumn(delta.getLongitude(), sector.getMinLongitude(), lonOrigin);
    final int seRow = Tile.computeRow(delta.getLatitude(), sector.getMinLatitude(), latOrigin);
    final int seCol = Tile.computeColumn(delta.getLongitude(), sector.getMaxLongitude(), lonOrigin);

    int numRows = nwRow - seRow + 1;
    int numCols = seCol - nwCol + 1;

    return numRows * numCols;
  }
  private MercatorTextureTile[][] getTilesInSector(Sector sector, int levelNumber) {
    if (sector == null) {
      String msg = Logging.getMessage("nullValue.SectorIsNull");
      Logging.logger().severe(msg);
      throw new IllegalArgumentException(msg);
    }

    Level targetLevel = this.levels.getLastLevel();
    if (levelNumber >= 0) {
      for (int i = levelNumber; i < this.getLevels().getLastLevel().getLevelNumber(); i++) {
        if (this.levels.isLevelEmpty(i)) continue;

        targetLevel = this.levels.getLevel(i);
        break;
      }
    }

    // Collect all the tiles intersecting the input sector.
    LatLon delta = targetLevel.getTileDelta();
    Angle latOrigin = this.levels.getTileOrigin().getLatitude();
    Angle lonOrigin = this.levels.getTileOrigin().getLongitude();
    final int nwRow = Tile.computeRow(delta.getLatitude(), sector.getMaxLatitude(), latOrigin);
    final int nwCol = Tile.computeColumn(delta.getLongitude(), sector.getMinLongitude(), lonOrigin);
    final int seRow = Tile.computeRow(delta.getLatitude(), sector.getMinLatitude(), latOrigin);
    final int seCol = Tile.computeColumn(delta.getLongitude(), sector.getMaxLongitude(), lonOrigin);

    int numRows = nwRow - seRow + 1;
    int numCols = seCol - nwCol + 1;
    MercatorTextureTile[][] sectorTiles = new MercatorTextureTile[numRows][numCols];

    for (int row = nwRow; row >= seRow; row--) {
      for (int col = nwCol; col <= seCol; col++) {
        TileKey key =
            new TileKey(targetLevel.getLevelNumber(), row, col, targetLevel.getCacheName());
        Sector tileSector = this.levels.computeSectorForKey(key);
        MercatorSector mSector = MercatorSector.fromSector(tileSector); // TODO: check
        sectorTiles[nwRow - row][col - nwCol] =
            new MercatorTextureTile(mSector, targetLevel, row, col);
      }
    }

    return sectorTiles;
  }
  private boolean needToSplit(DrawContext dc, Sector sector) {
    Vec4[] corners = sector.computeCornerPoints(dc.getGlobe(), dc.getVerticalExaggeration());
    Vec4 centerPoint = sector.computeCenterPoint(dc.getGlobe(), dc.getVerticalExaggeration());

    View view = dc.getView();
    double d1 = view.getEyePoint().distanceTo3(corners[0]);
    double d2 = view.getEyePoint().distanceTo3(corners[1]);
    double d3 = view.getEyePoint().distanceTo3(corners[2]);
    double d4 = view.getEyePoint().distanceTo3(corners[3]);
    double d5 = view.getEyePoint().distanceTo3(centerPoint);

    double minDistance = d1;
    if (d2 < minDistance) minDistance = d2;
    if (d3 < minDistance) minDistance = d3;
    if (d4 < minDistance) minDistance = d4;
    if (d5 < minDistance) minDistance = d5;

    double cellSize =
        (Math.PI * sector.getDeltaLatRadians() * dc.getGlobe().getRadius()) / 20; // TODO

    return !(Math.log10(cellSize) <= (Math.log10(minDistance) - this.splitScale));
  }
    public URL getURL(Tile tile, String altImageFormat) throws MalformedURLException {
      StringBuffer sb;
      if (this.URLTemplate == null) {
        sb = new StringBuffer(WWXML.fixGetMapString(tile.getLevel().getService()));

        if (!sb.toString().toLowerCase().contains("service=wms")) sb.append("service=WMS");
        sb.append("&request=GetMap");
        sb.append("&version=").append(this.wmsVersion);
        sb.append(this.crs);
        sb.append("&layers=").append(this.layerNames);
        sb.append("&styles=").append(this.styleNames != null ? this.styleNames : "");
        sb.append("&transparent=TRUE");
        if (this.backgroundColor != null) sb.append("&bgcolor=").append(this.backgroundColor);

        this.URLTemplate = sb.toString();
      } else {
        sb = new StringBuffer(this.URLTemplate);
      }

      String format = (altImageFormat != null) ? altImageFormat : this.imageFormat;
      if (null != format) sb.append("&format=").append(format);

      sb.append("&width=").append(tile.getWidth());
      sb.append("&height=").append(tile.getHeight());

      Sector s = tile.getSector();
      sb.append("&bbox=");
      sb.append(s.getMinLongitude().getDegrees());
      sb.append(",");
      sb.append(s.getMinLatitude().getDegrees());
      sb.append(",");
      sb.append(s.getMaxLongitude().getDegrees());
      sb.append(",");
      sb.append(s.getMaxLatitude().getDegrees());
      //            sb.append("&"); // terminate the query string

      return new java.net.URL(sb.toString().replace(" ", "%20"));
    }
  protected static void legacyWmsRestoreStateToParams(
      RestorableSupport rs, RestorableSupport.StateObject context, AVList params) {
    // WMSTiledImageLayer has historically used a different format for storing LatLon and Sector
    // properties
    // in the restorable state XML documents. Although WMSTiledImageLayer no longer writes these
    // properties,
    // we must provide support for reading them here.
    Double lat = rs.getStateValueAsDouble(context, AVKey.LEVEL_ZERO_TILE_DELTA + ".Latitude");
    Double lon = rs.getStateValueAsDouble(context, AVKey.LEVEL_ZERO_TILE_DELTA + ".Longitude");
    if (lat != null && lon != null)
      params.setValue(AVKey.LEVEL_ZERO_TILE_DELTA, LatLon.fromDegrees(lat, lon));

    Double minLat = rs.getStateValueAsDouble(context, AVKey.SECTOR + ".MinLatitude");
    Double minLon = rs.getStateValueAsDouble(context, AVKey.SECTOR + ".MinLongitude");
    Double maxLat = rs.getStateValueAsDouble(context, AVKey.SECTOR + ".MaxLatitude");
    Double maxLon = rs.getStateValueAsDouble(context, AVKey.SECTOR + ".MaxLongitude");
    if (minLat != null && minLon != null && maxLat != null && maxLon != null)
      params.setValue(AVKey.SECTOR, Sector.fromDegrees(minLat, maxLat, minLon, maxLon));
  }
  public BufferedImage composeImageForSector(
      Sector sector,
      int imageWidth,
      int imageHeight,
      int levelNumber,
      String mimeType,
      boolean abortOnError,
      BufferedImage image) {
    if (sector == null) {
      String message = Logging.getMessage("nullValue.SectorIsNull");
      Logging.logger().severe(message);
      throw new IllegalStateException(message);
    }

    if (levelNumber < 0) {
      levelNumber = this.levels.getLastLevel().getLevelNumber();
    } else if (levelNumber > this.levels.getLastLevel().getLevelNumber()) {
      Logging.logger()
          .warning(
              Logging.getMessage(
                  "generic.LevelRequestedGreaterThanMaxLevel",
                  levelNumber,
                  this.levels.getLastLevel().getLevelNumber()));
      levelNumber = this.levels.getLastLevel().getLevelNumber();
    }

    MercatorTextureTile[][] tiles = this.getTilesInSector(sector, levelNumber);

    if (tiles.length == 0 || tiles[0].length == 0) {
      Logging.logger().severe(Logging.getMessage("layers.TiledImageLayer.NoImagesAvailable"));
      return null;
    }

    if (image == null)
      image = new BufferedImage(imageWidth, imageHeight, BufferedImage.TYPE_INT_RGB);

    Graphics2D g = image.createGraphics();

    for (MercatorTextureTile[] row : tiles) {
      for (MercatorTextureTile tile : row) {
        if (tile == null) continue;

        BufferedImage tileImage;
        try {
          tileImage = this.getImage(tile, mimeType);

          double sh =
              ((double) imageHeight / (double) tileImage.getHeight())
                  * (tile.getSector().getDeltaLat().divide(sector.getDeltaLat()));
          double sw =
              ((double) imageWidth / (double) tileImage.getWidth())
                  * (tile.getSector().getDeltaLon().divide(sector.getDeltaLon()));

          double dh =
              imageHeight
                  * (-tile.getSector().getMaxLatitude().subtract(sector.getMaxLatitude()).degrees
                      / sector.getDeltaLat().degrees);
          double dw =
              imageWidth
                  * (tile.getSector().getMinLongitude().subtract(sector.getMinLongitude()).degrees
                      / sector.getDeltaLon().degrees);

          AffineTransform txf = g.getTransform();
          g.translate(dw, dh);
          g.scale(sw, sh);
          g.drawImage(tileImage, 0, 0, null);
          g.setTransform(txf);
        } catch (Exception e) {
          if (abortOnError) throw new RuntimeException(e);

          String message =
              Logging.getMessage("generic.ExceptionWhileRequestingImage", tile.getPath());
          Logging.logger().log(java.util.logging.Level.WARNING, message, e);
        }
      }
    }

    return image;
  }