@Override
  public void onBulletHitBullet(BulletHitBulletEvent event) {
    Point2D bulletPosition = new Point2D.Double(event.getBullet().getX(), event.getBullet().getY());

    GBulletFiredEvent hittedWave = null;
    for (GBulletFiredEvent wave : waves.getWaves()) {
      if (Math.abs(
              bulletPosition.distance(wave.getFiringPosition())
                  - ((getTime() - wave.getFiringTime()) * event.getBullet().getVelocity()))
          < 20) {
        hittedWave = wave;
        break;
      }
    }

    if (hittedWave == null) return;

    double firingOffset =
        org.pattern.utils.Utils.firingOffset(
            hittedWave.getFiringPosition(), hittedWave.getTargetPosition(), bulletPosition);
    double mae = firingOffset > 0 ? hittedWave.getMaxMAE() : hittedWave.getMinMAE();
    double gf = firingOffset > 0 ? firingOffset / mae : -firingOffset / mae;

    storages.get(event.getBullet().getName()).visit(gf);
    waves.getWaves().remove(hittedWave);
    return;
  }
  /**
   * Constructs a <code>LinearGradientPaint</code>.
   *
   * @param start the gradient axis start <code>Point</code> in user space
   * @param end the gradient axis end <code>Point</code> in user space
   * @param fractions numbers ranging from 0.0 to 1.0 specifying the distribution of colors along
   *     the gradient
   * @param colors array of colors corresponding to each fractional value
   * @param cycleMethod either NO_CYCLE, REFLECT, or REPEAT
   * @param colorSpace which colorspace to use for interpolation, either SRGB or LINEAR_RGB
   * @param gradientTransform transform to apply to the gradient
   * @throws NullPointerException if one of the points is null, or gradientTransform is null
   * @throws IllegalArgumentException if start and end points are the same points, or if
   *     fractions.length != colors.length, or if colors is less than 2 in size.
   */
  public LinearGradientPaint(
      Point2D start,
      Point2D end,
      float[] fractions,
      Color[] colors,
      CycleMethodEnum cycleMethod,
      ColorSpaceEnum colorSpace,
      AffineTransform gradientTransform) {
    super(fractions, colors, cycleMethod, colorSpace, gradientTransform);

    //
    // Check input parameters
    //
    if (start == null || end == null) {
      throw new NullPointerException("Start and end points must be" + "non-null");
    }

    if (start.equals(end)) {
      throw new IllegalArgumentException("Start point cannot equal" + "endpoint");
    }

    // copy the points...
    this.start = (Point2D) start.clone();

    this.end = (Point2D) end.clone();
  }
Example #3
0
  public static BufferedImage rotateImage(BufferedImage image, double theta) {
    int degrees = (int) Math.abs(Math.toDegrees(theta));
    double xCenter = image.getWidth() / 2;
    double yCenter = image.getHeight() / 2;
    AffineTransform rotateTransform = AffineTransform.getRotateInstance(-theta, xCenter, yCenter);

    // Translation adjustments so image still centered after rotate width/height changes
    if (image.getHeight() != image.getWidth() && degrees != 180 && degrees != 0) {
      Point2D origin = new Point2D.Double(0.0, 0.0);
      origin = rotateTransform.transform(origin, null);
      double yTranslate = origin.getY();

      Point2D yMax = new Point2D.Double(0, image.getHeight());
      yMax = rotateTransform.transform(yMax, null);
      double xTranslate = yMax.getX();

      AffineTransform translationAdjustment =
          AffineTransform.getTranslateInstance(-xTranslate, -yTranslate);
      rotateTransform.preConcatenate(translationAdjustment);
    }

    AffineTransformOp op = new AffineTransformOp(rotateTransform, AffineTransformOp.TYPE_BILINEAR);
    // Have to recopy image because of JDK bug #4723021, AffineTransformationOp throwing exception
    // sometimes
    image = copyImage(image, BufferedImage.TYPE_INT_ARGB);

    // Need to create filter dest image ourselves since AffineTransformOp's own dest image creation
    // throws exceptions in some cases.
    Rectangle bounds = op.getBounds2D(image).getBounds();
    BufferedImage finalImage =
        new BufferedImage(
            (int) bounds.getWidth(), (int) bounds.getHeight(), BufferedImage.TYPE_INT_ARGB);

    return op.filter(image, finalImage);
  }
Example #4
0
  /** Force this handle to relocate itself using its locator. */
  public void relocateHandle() {
    if (locator != null) {
      final PBounds b = getBoundsReference();
      final Point2D aPoint = locator.locatePoint(null);

      if (locator instanceof PNodeLocator) {
        final PNode located = ((PNodeLocator) locator).getNode();
        final PNode parent = getParent();

        located.localToGlobal(aPoint);
        globalToLocal(aPoint);

        if (parent != located && parent instanceof PCamera) {
          ((PCamera) parent).viewToLocal(aPoint);
        }
      }

      final double newCenterX = aPoint.getX();
      final double newCenterY = aPoint.getY();

      if (newCenterX != b.getCenterX() || newCenterY != b.getCenterY()) {
        centerBoundsOnPoint(newCenterX, newCenterY);
      }
    }
  }
  private void doMovement() {
    Point2D actualPosition = new Point2D.Double(getX(), getY());

    if (nextPosition == null) nextPosition = actualPosition;

    if (corner) {
      goToCorner();
      out.println("corner");
    } else if (nextPosition == null
        || nextPosition.equals(actualPosition)
        || nextPosition.distance(actualPosition) < 15) {
      try {
        // PositionFinder f = new PositionFinder(enemies, this);
        // nextPosition = f.generateRandomPoint();
        // nextPosition = f.findBestPointInRangeWithRandomOffset(500);
        gotoPointandSmooth();
      } catch (Exception e) {
        System.out.println(e);
      }

    } else {
      gotoPointandSmooth();
    }
    lastPosition = actualPosition;
  }
Example #6
0
 public int compare(Point2D left, Point2D right) {
   if (left.getX() < right.getX()) return -1;
   if (left.getX() > right.getX()) return 1;
   if (left.getY() < right.getY()) return -1;
   if (left.getY() > right.getY()) return 1;
   return 0;
 }
  /**
   * returns a point that is a google tile reference for the tile containing the lat/lng and at the
   * zoom level.
   *
   * @param lat
   * @param lng
   * @param zoom
   * @return
   */
  public static Point toTileXY(double lat, double lng, int zoom) {
    Point2D normalised = toNormalisedPixelCoords(lat, lng);
    int scale = 1 << zoom;

    // can just truncate to integer, this looses the fractional "pixel offset"
    return new Point((int) (normalised.getX() * scale), (int) (normalised.getY() * scale));
  }
Example #8
0
  public void drawGame() {
    StdDraw.clear(StdDraw.GRAY);

    // Set Color
    StdDraw.setPenColor(StdDraw.YELLOW);
    // Set Font
    setFont(new Font("SansSerif", Font.PLAIN, 32));
    // X, Y, String, rotation degree
    // Write String
    this.text(1 - 0.3, 1 - 0.1, blockP.x + ", " + blockP.y, 0);
    // Set Color
    StdDraw.setPenColor(StdDraw.ORANGE);
    // Set Font
    setFont(new Font("SansSerif", Font.PLAIN, 50));
    // Write String
    this.text(1 - 0.3, 1 - 0.3, "START!", 20);

    StdDraw.setPenColor(StdDraw.BLACK);

    for (int i = 0; i < map.length; i++) {
      for (int j = 0; j < map[i].length; j++) {
        if (map[i][j] > 0) {
          Point2D vLoc = map2Visual(i, j);
          System.out.println(i + ", " + j + ", " + vLoc);
          StdDraw.filledCircle(vLoc.getX(), vLoc.getY(), radius);
        }
      }
    }
  }
    // ~ Methods ------------------------------------------------------------
    // Retrieve the distance with proper staff border
    @Override
    protected double getValue(GlyphContext context) {
      Glyph stick = context.stick;
      Point2D stop = stick.getStopPoint(VERTICAL);

      // Which staff area contains the bottom of the stick?
      StaffInfo staff = staffManager.getStaffAt(stop);

      // How far are we from the stop of the staff?
      double staffBottom = staff.getLastLine().yAt(stop.getX());
      double dy = sheet.getScale().pixelsToFrac(Math.abs(staffBottom - stop.getY()));

      // Change limits according to rough & partDefining
      if (rough && context.isPartDefining) {
        setLowHigh(constants.maxStaffShiftDyLowRough, constants.maxStaffShiftDyHighRough);
      } else {
        setLowHigh(constants.maxStaffShiftDyLow, constants.maxStaffShiftDyHigh);
      }

      // Side-effect
      if (dy <= getLow()) {
        context.botStaff = context.bottomArea;
      }

      return dy;
    }
Example #10
0
  private void draw(Graphics2D g2, Point2D cursor, double width, double height) {

    double widthFactor = 0.95f;
    double heightFactor = 0.95f;

    double yAxeWidth = width - (width * widthFactor);
    double xAxeHeight = height - height * heightFactor;

    Point2D.Double localCursor = new Point2D.Double(cursor.getX(), cursor.getY());
    localCursor.x += yAxeWidth;

    plot.draw(g2, localCursor, width * widthFactor, height * heightFactor);

    Range plotYRange = plot.getPlotModel().getYRange();

    AxisState yAxisState =
        yAxis.build(g2, cursor, yAxeWidth, height * heightFactor, plot.getPlotArea(), plotYRange);

    localCursor.y += height * heightFactor;

    Range plotXRange = plot.getPlotModel().getXRange();

    AxisState xAxisState =
        xAxis.build(
            g2, localCursor, width * widthFactor, xAxeHeight, plot.getPlotArea(), plotXRange);

    synFontSize(xAxisState, yAxisState);

    xAxis.draw();
    yAxis.draw();

    gridRenderer.draw(g2, plot.getPlotArea(), xAxisState, yAxisState);
  }
Example #11
0
  /**
   * Cuando soltamos el botón del ratón desplazamos la imagen a la posición de destino calculando el
   * extent nuevamente.
   */
  public void mouseReleased(MouseEvent e) throws BehaviorException {
    if (!isActiveTool()) return;
    if (e.getButton() == MouseEvent.BUTTON1 && isMoveable) {
      FLyrRasterSE lyr = grBehavior.getLayer();
      if (lyr == null) return;

      ViewPort vp = grBehavior.getMapControl().getMapContext().getViewPort();
      ptoFin = vp.toMapPoint(e.getPoint());

      // Asignamos la nueva matriz de transformación a la capa
      AffineTransform atOld = lyr.getAffineTransform();
      AffineTransform atNew = null;

      double distX = ptoFin.getX() - ptoIni.getX();
      double distY = ptoFin.getY() - ptoIni.getY();

      // La nueva matriz de transformación es la vieja más la distancia desplazada
      atNew =
          new AffineTransform(
              atOld.getScaleX(),
              atOld.getShearY(),
              atOld.getShearX(),
              atOld.getScaleY(),
              atOld.getTranslateX() + distX,
              atOld.getTranslateY() + distY);
      lyr.setAffineTransform(atNew);

      grBehavior.getMapControl().getMapContext().invalidate();
      isMoveable = false;
      super.mouseReleased(e);
    }
  }
Example #12
0
File: Z.java Project: adamldavis/z
  private void updateSubLocations(ZNode node, boolean immediate, Point2D loc) {
    final Point center = new Point((int) Math.round(loc.getX()), (int) Math.round(loc.getY()));
    // make bigger when more nodes
    final float factor =
        selectedNode == node ? (1.3f + logSize(node.getSubmodules().size()) / 2.2f) : 1.2f;
    int size = Math.round(sizeMap.get(node) * factor);
    final float xRatio = display.getWidth() / display.getHeight();
    Map<ZNode, Point2D> map =
        new PixelZNodePositioner(
                center,
                new Dimension((int) (size * xRatio), size),
                new DirectionZNodePositioner(direction, makeNodePositioner()))
            .getNewPositions(node);

    for (ZNode sub : node.getSubmodules()) {
      pointMap.put(sub, map.get(sub));
      if (immediate) sub.setLocation((java.awt.geom.Point2D.Float) map.get(sub));

      updateSubLocations(sub, immediate, map.get(sub));
    }
    if (node == selectedNode)
      for (ZNode dep : node.getDependencies()) {
        pointMap.put(dep, map.get(dep));
        if (immediate) dep.setLocation((java.awt.geom.Point2D.Float) map.get(dep));
      }
  }
Example #13
0
  /**
   * check if the given position collides with the flashlight.
   *
   * @param point
   * @return
   */
  public boolean flashlightCollision(Point2D point) {

    flY23 = flY2 - flY3;
    flX32 = flX3 - flX2;
    flY31 = flY3 - flY1;
    flX13 = flX1 - flX3;
    flDet = flY23 * flX13 - flX32 * flY31;
    flMinD = Math.min(flDet, 0);
    flMaxD = Math.max(flDet, 0);

    double x = point.getX();
    double y = point.getY();
    double dx = x - flX3;
    double dy = y - flY3;
    double a = flY23 * dx + flX32 * dy;
    if (a < flMinD || a > flMaxD) {
      return false;
    }
    double b = flY31 * dx + flX13 * dy;
    if (b < flMinD || b > flMaxD) {
      return false;
    }
    double c = flDet - a - b;
    return !(c < flMinD || c > flMaxD);
  }
Example #14
0
  /**
   * Renders an image on the device
   *
   * @param tx the image location on the screen, x coordinate
   * @param ty the image location on the screen, y coordinate
   * @param img the image
   * @param rotation the image rotatation
   */
  private static void renderImage(
      Graphics2D graphics, double x, double y, Image image, double rotation, float opacity) {
    AffineTransform temp = graphics.getTransform();
    AffineTransform markAT = new AffineTransform();
    Point2D mapCentre = new java.awt.geom.Point2D.Double(x, y);
    Point2D graphicCentre = new java.awt.geom.Point2D.Double();
    temp.transform(mapCentre, graphicCentre);
    markAT.translate(graphicCentre.getX(), graphicCentre.getY());

    double shearY = temp.getShearY();
    double scaleY = temp.getScaleY();

    double originalRotation = Math.atan(shearY / scaleY);

    markAT.rotate(rotation);
    graphics.setTransform(markAT);
    graphics.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, opacity));

    // we moved the origin to the centre of the image.
    graphics.drawImage(image, -image.getWidth(null) / 2, -image.getHeight(null) / 2, null);

    graphics.setTransform(temp);

    return;
  }
 public void drawU(UGraphic ug) {
   ug.apply(new UChangeBackColor(ug.getParam().getColor())).draw(polygon);
   ug.apply(new UStroke(1.5))
       .apply(new UChangeBackColor(HtmlColorUtils.WHITE))
       .apply(new UTranslate(dest.getX() - radius, dest.getY() - radius))
       .draw(new UEllipse(radius * 2, radius * 2));
 }
  /**
   * Method paint. Paints the rings on the graph.
   *
   * @param g Graphics - the graphics to be painted.
   */
  @Override
  public void paint(Graphics g) {
    Collection<Double> depths = getDepths();
    g.setColor(Color.gray);
    Graphics2D g2d = (Graphics2D) g;
    Point2D center = radialLayout.getCenter();

    Ellipse2D ellipse = new Ellipse2D.Double();
    for (double d : depths) {
      ellipse.setFrameFromDiagonal(
          center.getX() - d, center.getY() - d, center.getX() + d, center.getY() + d);
      AffineTransform at = AffineTransform.getTranslateInstance(0, 0);
      Shape shape = at.createTransformedShape(ellipse);
      // Shape shape =
      //	vv.getRenderContext().getMultiLayerTransformer().transform(ellipse);
      //
      //	vv.getRenderContext().getMultiLayerTransformer().getTransformer(Layer.LAYOUT).transform(ellipse);

      MutableTransformer viewTransformer =
          vv.getRenderContext().getMultiLayerTransformer().getTransformer(Layer.VIEW);

      if (viewTransformer instanceof MutableTransformerDecorator) {
        shape = vv.getRenderContext().getMultiLayerTransformer().transform(shape);
      } else {
        shape = vv.getRenderContext().getMultiLayerTransformer().transform(Layer.LAYOUT, shape);
      }
      g2d.draw(shape);
    }
  }
Example #17
0
    public void paint(Graphics g) {
      g.setColor(Color.gray);

      Graphics2D g2d = (Graphics2D) g;

      Ellipse2D ellipse = new Ellipse2D.Double();
      for (String v : layout.getGraph().getVertices()) {
        Double radius = layout.getRadii().get(v);
        if (radius == null) {
          continue;
        }
        Point2D p = layout.transform(v);
        ellipse.setFrame(-radius, -radius, 2 * radius, 2 * radius);
        AffineTransform at = AffineTransform.getTranslateInstance(p.getX(), p.getY());
        Shape shape = at.createTransformedShape(ellipse);

        MutableTransformer viewTransformer =
            vv.getRenderContext().getMultiLayerTransformer().getTransformer(Layer.VIEW);

        if (viewTransformer instanceof MutableTransformerDecorator) {
          shape = vv.getRenderContext().getMultiLayerTransformer().transform(shape);
        } else {
          shape = vv.getRenderContext().getMultiLayerTransformer().transform(Layer.LAYOUT, shape);
        }

        g2d.draw(shape);
      }
    }
Example #18
0
  public Point2D getClosestIntersectionToStart(Shape withThisShape) {
    // first, get the sides of the shape
    List<LineSegment> shapeSides = Utilities.getSides(withThisShape);

    // go through all the sides, and see if there are any intersections
    // there may be more than 1
    List<Point2D> shapeIntersectionPoints = new ArrayList<Point2D>();

    for (Line2D curSide : shapeSides) {
      if (curSide.intersectsLine(this)) {
        Point2D intersectionPoint = Utilities.getIntersectionPoint(this, curSide);
        shapeIntersectionPoints.add(intersectionPoint);
      }
    }

    if (shapeIntersectionPoints.size() <= 0) {
      return null;
    } else if (shapeIntersectionPoints.size() == 1) {
      return shapeIntersectionPoints.get(0);
    } else {
      // get the point closest to P1
      Point2D closestIntersectionPoint = null;
      double closestIntersectionPointDistSq = java.lang.Double.MAX_VALUE;
      for (Point2D curPoint : shapeIntersectionPoints) {
        double curDistSq = curPoint.distanceSq(this.getP1());
        if (curDistSq < closestIntersectionPointDistSq) {
          closestIntersectionPointDistSq = curDistSq;
          closestIntersectionPoint = curPoint;
        }
      }
      return closestIntersectionPoint;
    }
  }
Example #19
0
 final double getMindist(Point2D.Double pt) {
   double result = Double.MAX_VALUE;
   for (Point2D p : points.keySet()) {
     if (pt.equals(p)) {
       continue;
     }
     final double v = p.distance(pt);
     if (v < 1E-4) {
       throw new IllegalStateException();
     }
     result = Math.min(result, v);
   }
   for (Line2D line : lines) {
     if (line.getP1().equals(pt) || line.getP2().equals(pt)) {
       continue;
     }
     final double v = line.ptSegDist(pt);
     if (result < 1E-4) {
       throw new IllegalStateException("pt=" + pt + " line=" + GeomUtils.toString(line));
     }
     result = Math.min(result, v);
   }
   if (result == 0) {
     throw new IllegalStateException();
   }
   // Log.println("getMindist=" + result);
   return result;
 }
  /**
   * Draws an item label.
   *
   * @param g2 the graphics device.
   * @param orientation the orientation.
   * @param dataset the dataset.
   * @param series the series index (zero-based).
   * @param item the item index (zero-based).
   * @param x the x coordinate (in Java2D space).
   * @param y the y coordinate (in Java2D space).
   * @param negative indicates a negative value (which affects the item label position).
   */
  private void drawAdditionalItemLabel(
      Graphics2D g2,
      PlotOrientation orientation,
      XYDataset dataset,
      int series,
      int item,
      double x,
      double y) {

    if (this.additionalItemLabelGenerator == null) {
      return;
    }

    Font labelFont = getItemLabelFont(series, item);
    Paint paint = getItemLabelPaint(series, item);
    g2.setFont(labelFont);
    g2.setPaint(paint);
    String label = this.additionalItemLabelGenerator.generateLabel(dataset, series, item);

    ItemLabelPosition position = getNegativeItemLabelPosition(series, item);
    Point2D anchorPoint =
        calculateLabelAnchorPoint(position.getItemLabelAnchor(), x, y, orientation);
    TextUtilities.drawRotatedString(
        label,
        g2,
        (float) anchorPoint.getX(),
        (float) anchorPoint.getY(),
        position.getTextAnchor(),
        position.getAngle(),
        position.getRotationAnchor());
  }
Example #21
0
  /** make new shape polygon */
  private void reMakePolygonShape() {
    ConvexHull convexHull;

    List<Point> newPoints = new ArrayList<Point>();

    for (int j = 0; j < polygon.npoints; j++) {

      if (mainClusterShape.contains(polygon.xpoints[j], polygon.ypoints[j])) {
        newPoints.add(new Point(polygon.xpoints[j], polygon.ypoints[j]));
      }
    }

    for (Point2D point2D : getIntersectPoint()) {
      newPoints.add(new Point((int) point2D.getX(), (int) point2D.getY()));
    }

    for (int i = 0; i < mainClusterShape.npoints; i++) {
      if (polygon.contains(mainClusterShape.xpoints[i], mainClusterShape.ypoints[i])) {
        Point point = new Point(mainClusterShape.xpoints[i], mainClusterShape.ypoints[i]);
        newPoints.add(point);
      }
    }

    convexHull = new ConvexHull();

    for (Point point : newPoints) {
      convexHull.addPoint((int) point.getX(), (int) point.getY());
    }

    setPolygon(convexHull.convex());
    newPoints.clear();
  }
Example #22
0
 /**
  * Return the raster coordinate denoted by the given world coordinate. This method is CENTER and
  * OUTER aware.
  *
  * @param worldX x position in the world coordinate system, for which raster coordinates should be
  *     calculated.
  * @param worldY y position in the world coordinate system, for which raster coordinates should be
  *     calculated.
  * @return the (rounded) raster coordinate which the given world coordinate maps to.
  */
 public int[] getRasterCoordinate(double worldX, double worldY) {
   Point2D rslt = invTransform.transform(new Point2D.Double(worldX, worldY), null);
   if (location == CENTER) {
     return new int[] {(int) round(rslt.getX()), (int) round(rslt.getY())};
   }
   return new int[] {(int) floor(rslt.getX()), (int) floor(rslt.getY())};
 }
Example #23
0
 private static Point2D vectorToLocation(
     double angle, double length, Point2D sourceLocation, Point2D targetLocation) {
   targetLocation.setLocation(
       sourceLocation.getX() + Math.sin(angle) * length,
       sourceLocation.getY() + Math.cos(angle) * length);
   return targetLocation;
 }
Example #24
0
  /**
   * creates a svg element by specifiying its parameters
   *
   * @param handle the current svg handle
   * @param text the text for the new element
   * @return the created svg element
   */
  public Element createElement(SVGHandle handle, String text) {

    // the edited document
    Document doc = handle.getScrollPane().getSVGCanvas().getDocument();

    // creating the text element
    final Element element =
        doc.createElementNS(doc.getDocumentElement().getNamespaceURI(), handledElementTagName);

    // getting the last color that has been used by the user
    String colorString = Editor.getColorChooser().getColorString(ColorManager.getCurrentColor());
    element.setAttributeNS(null, "style", "fill:" + colorString + ";stroke:none;");
    element.setAttributeNS(null, "style", "font-size:12pt;fill:" + colorString + ";");

    EditorToolkit.setAttributeValue(element, xAtt, drawingPoint.getX());
    EditorToolkit.setAttributeValue(element, yAtt, drawingPoint.getY());

    // creating the text node
    Text textValue = doc.createTextNode(text);
    element.appendChild(textValue);

    // inserting the element in the document and handling the undo/redo
    // support
    insertShapeElement(handle, element);
    handle.getSelection().handleSelection(element, false, false);

    return element;
  }
    /**
     * Hook for subclassers to paint the background page(s).
     *
     * @param g2 The graphics object to paint the background page(s) on.
     */
    protected void paintBackgroundPages(Graphics2D g2) {
      Point2D p = graph.toScreen(new Point2D.Double(pageFormat.getWidth(), pageFormat.getHeight()));
      Dimension pSize = graph.getPreferredSize();
      int w = (int) (p.getX() * pageScale);
      int h = (int) (p.getY() * pageScale);
      int cols = (int) Math.max(Math.ceil((double) (pSize.width - 5) / (double) w), 1);
      int rows = (int) Math.max(Math.ceil((double) (pSize.height - 5) / (double) h), 1);
      g2.setColor(graph.getHandleColor());

      // Draws the pages.
      Point offset = getViewPosition();
      g2.translate(-offset.x, -offset.y);
      g2.fillRect(0, 0, graph.getWidth(), graph.getHeight());
      g2.setColor(Color.darkGray);
      g2.fillRect(3, 3, cols * w, rows * h);
      g2.setColor(getGraph().getBackground());
      g2.fillRect(1, 1, cols * w - 1, rows * h - 1);

      // Draws the pagebreaks.
      Stroke previousStroke = g2.getStroke();
      g2.setStroke(
          new BasicStroke(
              1, BasicStroke.CAP_BUTT, BasicStroke.JOIN_MITER, 10.0f, new float[] {1, 2}, 0));
      g2.setColor(Color.darkGray);
      for (int i = 1; i < cols; i++) g2.drawLine(i * w, 1, i * w, rows * h - 1);
      for (int i = 1; i < rows; i++) g2.drawLine(1, i * h, cols * w - 1, i * h);

      // Restores the graphics.
      g2.setStroke(previousStroke);
      g2.translate(offset.x, offset.y);
      g2.clipRect(0, 0, cols * w - 1 - offset.x, rows * h - 1 - offset.y);
    }
  /** Redraws the image. */
  private void redrawImage() {
    ScreenToWorldPointConverter converter = null;
    try {
      converter =
          new ScreenToWorldPointConverter(
              currWXMin, currWYMin, currWXMax, currWYMax, 0, 0, width - 1, height - 1);
    } catch (Exception e) {
      throw new IllegalStateException(e);
    }

    Point2D P = null;
    Point2D.Double screenPoint = new Point2D.Double();
    ComplexNumber C = null;
    Color theColor = null;
    int colorIndex = 0;
    for (int i = 0; i < width; ++i) {
      for (int j = 0; j < height; ++j) {
        screenPoint.setLocation(i, j);
        P = converter.getWorldCoordinates(screenPoint);
        C = new ComplexNumber(new RealNumber(P.getX()), new RealNumber(P.getY()));
        colorIndex = Mandelbrot.divergenceIndex(C);
        if (colorIndex < 0) {
          theColor = Color.black;
        } else {
          theColor = Mandelbrot.getColor(colorIndex);
        }
        img.paintPixel(i, j, theColor.getRGB());
      }
    }
  }
Example #27
0
  public static void main(String[] args) {
    Scanner scanRadius = new Scanner(System.in);
    Scanner scanCenter = new Scanner(System.in);
    Point2D centerA = new Point2D.Double();
    Point2D centerB = new Point2D.Double();
    double x, y, radiusA = 0, radiusB = 0;

    for (char i = 'A'; i <= 'B'; i++) {
      System.out.print("\nCircle " + i);
      System.out.print("\nEnter center cordinates:" + "\n(x): ");
      x = scanCenter.nextDouble();
      System.out.print("(y): ");
      y = scanCenter.nextDouble();

      System.out.print("Enter radius: ");
      if (i == 'A') {
        radiusA = scanCenter.nextDouble();
        centerA.setLocation(x, y);
      } else if (i == 'B') {
        radiusB = scanCenter.nextDouble();
        centerB.setLocation(x, y);
      }
    }
    scanRadius.close();
    scanCenter.close();

    double distance = distance(centerA, centerB);

    if (distance == (radiusA + radiusB)) System.out.println("\nThe two circles are touching");
    else if ((distance < Math.abs(radiusA - radiusB)))
      System.out.println("\nOne circle encloses another");
    else if (distance < (radiusA + radiusB)) System.out.println("\nThe two circles overlap");
    else if (distance > (radiusA + radiusB)) System.out.println("\nThe two circles are separate");
  }
Example #28
0
 private Point2D getImageOffset(ImageListViewCell cell) {
   Point2D imgSize = getScaledImageSize(cell);
   Dimension latestSize = cell.getLatestSize();
   return new Point2D.Double(
       (latestSize.width + 2 * cell.getCenterOffset().getX() - (int) imgSize.getX()) / 2,
       (latestSize.height + 2 * cell.getCenterOffset().getY() - (int) imgSize.getY()) / 2);
 }
Example #29
0
 @Override
 protected void paintComponent(Graphics g) {
   super.paintComponent(g);
   Graphics2D g2 = (Graphics2D) g;
   if (moveThread != null) {
     if (moveThread.isRunning()) {
       Point2D p = moveThread.getCurrentPosition();
       currentDirection = moveThread.getDirection();
       this.setBounds((int) p.getX() - 32, (int) p.getY() - 32, 96, 64);
     } else {
       if (currentDirection == HeroDirection.MOVING_BACK) {
         currentDirection = HeroDirection.IDLE_BACK;
       } else if (currentDirection == HeroDirection.MOVING_FRONT) {
         currentDirection = HeroDirection.IDLE_FRONT;
       } else if (currentDirection == HeroDirection.MOVING_LEFT) {
         currentDirection = HeroDirection.IDLE_LEFT;
       } else if (currentDirection == HeroDirection.MOVING_RIGHT) {
         currentDirection = HeroDirection.IDLE_RIGHT;
       }
       moveThread = null;
       isMoveFinished = true;
     }
   }
   g2.drawImage(animation.getCurrentFrame(currentDirection), 0, 0, null);
 }
Example #30
-1
  private void doShooting() {
    PositionFinder p = new PositionFinder(enemies, this);
    en = p.findNearest();
    if (en == null) return;

    Point2D myPos = new Point2D.Double(getX(), getY());

    if (HoT) {
      /* Perform head on target for gun movement */
      aimingPoint = new Point2D.Double(en.getX(), en.getY());
      double turnGunAmt = (getHeadingRadians() + en.getBearingRadians() - getGunHeadingRadians());
      turnGunAmt = Utils.normalRelativeAngle(turnGunAmt);
      setTurnGunRightRadians(turnGunAmt);
    } else {
      /* Perform circular targeting */
      Rectangle2D battlefield =
          new Rectangle2D.Double(0, 0, getBattleFieldWidth(), getBattleFieldHeight());
      long when = calcTimeToReachEnemy();
      aimingPoint = org.pattern.utils.Utils.getFuturePoint(en, when);
      if (!battlefield.contains(aimingPoint)) {
        HoT = true;
        return;
      }
      double theta =
          Utils.normalAbsoluteAngle(
              Math.atan2(aimingPoint.getX() - getX(), aimingPoint.getY() - getY()));
      setTurnGunRightRadians(Utils.normalRelativeAngle(theta - getGunHeadingRadians()));
    }

    if (getGunHeat() == 0) {
      double firePower = 3.0;
      fire(firePower);
    }
  }