Beispiel #1
0
  protected GameState.SystemSides findSystemSide(
      Point2D point, double rotationAngleInDegrees, double fieldWidth, double fieldHeight) {
    double centerX = point.getX(), centerY = point.getY();
    double angle = (rotationAngleInDegrees + 360) % 360;

    double angleLimits[] = new double[4];
    angleLimits[0] = Math.atan2(-centerY, fieldWidth - centerX);
    angleLimits[1] = Math.atan2(fieldHeight - centerY, fieldWidth - centerX);
    angleLimits[2] = Math.atan2(fieldHeight - centerY, -centerX);
    angleLimits[3] = Math.atan2(-centerY, -centerX);

    for (int i = 0; i < 4; i++) {
      angleLimits[i] = (Math.toDegrees(angleLimits[i]) + 360) % 360;
    }

    if (angle >= angleLimits[0] || angle <= angleLimits[1]) {
      return GameState.SystemSides.Right;
    } else if (angle < angleLimits[2]) {
      return GameState.SystemSides.Down;
    } else if (angle <= angleLimits[3]) {
      return GameState.SystemSides.Left;
    } else {
      return GameState.SystemSides.Up;
    }
  }
  /**
   * Rotate the oriented bounding box of the 3D image about the specified axis with the specified
   * angle.
   *
   * @param transform The transform and its matrix by which to rotate the image.
   */
  public void rotateFrameBy(Transform3D transform) {

    double rY, rX, rZ;
    double sinrX, sinrY, sinrZ, cosrX, cosrY, cosrZ;
    Matrix3d matrix = new Matrix3d();

    transform.get(matrix);

    rY = -Math.asin(matrix.m02);

    if (Math.cos(rY) != 0) {
      rX = -Math.atan2(matrix.m12, matrix.m22);
      rZ = Math.atan2(matrix.m01, matrix.m00);
    } else {
      rX = -Math.atan2(matrix.m10, matrix.m11);
      rZ = 0;
    }

    cosrX = Math.cos(rX);
    sinrX = Math.sin(rX);
    cosrY = Math.cos(rY);
    sinrY = Math.sin(rY);
    cosrZ = Math.cos(rZ);
    sinrZ = Math.sin(rZ);

    matrix.m00 = cosrZ * cosrY;
    matrix.m01 = -sinrZ * cosrY;
    matrix.m02 = sinrY;

    matrix.m10 = (cosrZ * sinrY * sinrX) + (sinrZ * cosrX);
    matrix.m11 = (-sinrZ * sinrY * sinrX) + (cosrZ * cosrX);
    matrix.m12 = -cosrY * sinrX;

    matrix.m20 = (-cosrZ * sinrY * cosrX) + (sinrZ * sinrX);
    matrix.m21 = (sinrZ * sinrY * cosrX) + (cosrZ * sinrX);
    matrix.m22 = cosrY * cosrX;

    m_kRotate.set(matrix);
    m_akAxis[0] = new Vector3f(1.0f, 0.0f, 0.0f);
    m_akAxis[1] = new Vector3f(0.0f, 1.0f, 0.0f);
    m_akAxis[2] = new Vector3f(0.0f, 0.0f, 1.0f);

    for (int i = 0; i < 3; i++) {
      m_kRotate.transform(m_akAxis[i]);
    }

    orthonormalize(m_akAxis);

    for (int i = 0; i < 3; i++) {
      setAxis(i, m_akAxis[i]);
    }
  }
Beispiel #3
0
  /**
   * Uses the Haversine formula to calculate the distnace between to lat-long coordinates
   *
   * @param latitude1 The first point's latitude
   * @param longitude1 The first point's longitude
   * @param latitude2 The second point's latitude
   * @param longitude2 The second point's longitude
   * @return The distance between the two points in meters
   */
  public static double CalculateDistance(
      double latitude1, double longitude1, double latitude2, double longitude2) {
    /*
    Haversine formula:
    A = sin²(Δlat/2) + cos(lat1).cos(lat2).sin²(Δlong/2)
    C = 2.atan2(√a, √(1−a))
    D = R.c
    R = radius of earth, 6371 km.
    All angles are in radians
    */

    double deltaLatitude = Math.toRadians(Math.abs(latitude1 - latitude2));
    double deltaLongitude = Math.toRadians(Math.abs(longitude1 - longitude2));
    double latitude1Rad = Math.toRadians(latitude1);
    double latitude2Rad = Math.toRadians(latitude2);

    double a =
        Math.pow(Math.sin(deltaLatitude / 2), 2)
            + (Math.cos(latitude1Rad)
                * Math.cos(latitude2Rad)
                * Math.pow(Math.sin(deltaLongitude / 2), 2));

    double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));

    return 6371 * c * 1000; // Distance in meters
  }
Beispiel #4
0
  // From: http://forum.java.sun.com/thread.jspa?threadID=378460&tstart=135
  void drawArrow(
      Graphics2D g2d,
      int xCenter,
      int yCenter,
      int x,
      int y,
      float stroke,
      BasicStroke drawStroke) {
    double aDir = Math.atan2(xCenter - x, yCenter - y);
    // Line can be dashed.
    g2d.setStroke(drawStroke);
    g2d.drawLine(x, y, xCenter, yCenter);
    // make the arrow head solid even if dash pattern has been specified
    g2d.setStroke(lineStroke);
    Polygon tmpPoly = new Polygon();
    int i1 = 12 + (int) (stroke * 2);
    // make the arrow head the same size regardless of the length length
    int i2 = 6 + (int) stroke;
    tmpPoly.addPoint(x, y);
    tmpPoly.addPoint(x + xCor(i1, aDir + .5), y + yCor(i1, aDir + .5));
    tmpPoly.addPoint(x + xCor(i2, aDir), y + yCor(i2, aDir));
    tmpPoly.addPoint(x + xCor(i1, aDir - .5), y + yCor(i1, aDir - .5));
    tmpPoly.addPoint(x, y); // arrow tip
    g2d.drawPolygon(tmpPoly);

    // Remove this line to leave arrow head unpainted:
    g2d.fillPolygon(tmpPoly);
  }
 public void mouseDragged(MouseEvent e) {
   middleX = (int) player.getX() + (int) player.get_spr_w() / 2;
   middleY = (int) player.getY() + (int) player.get_spr_h() / 2;
   angleX = ((e.getX() - middleX)) / 100.0f;
   angleY = ((e.getY() - middleY)) / 100.0f;
   angle = Math.atan2(angleY, angleX) * 180 / 3.14;
 }
Beispiel #6
0
 public void mousecoord(Atom[] args) {
   mousecoord = new float[] {args[0].toFloat(), args[1].toFloat(), args[2].toFloat()};
   double r =
       Math.sqrt(
           (args[0].toFloat() * args[0].toFloat()) + (args[1].toFloat() * args[1].toFloat()));
   double d = Math.atan2(args[1].toFloat(), args[0].toFloat());
 }
Beispiel #7
0
    public boolean stopdrag(float[] mc) {
      double r = Math.sqrt((mc[0] * mc[0]) + (mc[1] * mc[1]));
      double d = Math.atan2(mc[1], mc[0]);

      polar[0] = (Math.round(d * 100.00)) / 100.00;
      polar[1] = r;

      return r > 0.8;
    }
Beispiel #8
0
 /**
  * Overrides TPoint showCoordinates method.
  *
  * @param vidPanel the video panel
  */
 public void showCoordinates(VideoPanel vidPanel) {
   // put values into pointmass x and y fields
   Point2D p = getWorldPosition(vidPanel);
   track.xField.setValue(p.getX());
   track.yField.setValue(p.getY());
   track.magField.setValue(p.distance(0, 0));
   double theta = Math.atan2(p.getY(), p.getX());
   track.angleField.setValue(theta);
   super.showCoordinates(vidPanel);
 }
Beispiel #9
0
        public void mousePressed(MouseEvent e) {
          requestFocus();
          Point p = e.getPoint();
          int size =
              Math.min(
                  MAX_SIZE,
                  Math.min(
                      getWidth() - imagePadding.left - imagePadding.right,
                      getHeight() - imagePadding.top - imagePadding.bottom));
          p.translate(-(getWidth() / 2 - size / 2), -(getHeight() / 2 - size / 2));
          if (mode == ColorPicker.BRI || mode == ColorPicker.SAT) {
            // the two circular views:
            double radius = ((double) size) / 2.0;
            double x = p.getX() - size / 2.0;
            double y = p.getY() - size / 2.0;
            double r = Math.sqrt(x * x + y * y) / radius;
            double theta = Math.atan2(y, x) / (Math.PI * 2.0);

            if (r > 1) r = 1;

            if (mode == ColorPicker.BRI) {
              setHSB((float) (theta + .25f), (float) (r), bri);
            } else {
              setHSB((float) (theta + .25f), sat, (float) (r));
            }
          } else if (mode == ColorPicker.HUE) {
            float s = ((float) p.x) / ((float) size);
            float b = ((float) p.y) / ((float) size);
            if (s < 0) s = 0;
            if (s > 1) s = 1;
            if (b < 0) b = 0;
            if (b > 1) b = 1;
            setHSB(hue, s, b);
          } else {
            int x2 = p.x * 255 / size;
            int y2 = p.y * 255 / size;
            if (x2 < 0) x2 = 0;
            if (x2 > 255) x2 = 255;
            if (y2 < 0) y2 = 0;
            if (y2 > 255) y2 = 255;

            if (mode == ColorPicker.RED) {
              setRGB(red, x2, y2);
            } else if (mode == ColorPicker.GREEN) {
              setRGB(x2, green, y2);
            } else {
              setRGB(x2, y2, blue);
            }
          }
        }
 /**
  * @author Bogdan Sliptsov
  *     <p>Calculates the distance in km between two lat/long points using the haversine formula
  */
 public double distanceGPS(double lat1, double lng1, double lat2, double lng2) {
   int r = 6371; // average radius of the Earth in km
   double dLat = Math.toRadians(lat2 - lat1);
   double dLon = Math.toRadians(lng2 - lng1);
   double a =
       Math.sin(dLat / 2) * Math.sin(dLat / 2)
           + Math.cos(Math.toRadians(lat1))
               * Math.cos(Math.toRadians(lat2))
               * Math.sin(dLon / 2)
               * Math.sin(dLon / 2);
   double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
   double d = r * c;
   return d;
 }
Beispiel #11
0
  private Point teleport(Point location, double offset, Map<Integer, Point> id_lut) {
    Point self = id_lut.get(self_id);
    double x = Math.max(Math.min(location.x, 20), 0);
    double y = Math.max(Math.min(location.y, 20), 0);
    double dx = x - self.x;
    double dy = y - self.y;
    double r = Math.hypot(dx, dy) - offset;
    if (Math.abs(r) > 6) {
      r = Math.signum(r) * 6;
    }
    double th = Math.atan2(dy, dx);

    return new Point(r * Math.cos(th), r * Math.sin(th), self_id);
  }
Beispiel #12
0
    SeqNode(float _x, float _y, float _z, float _size, String _name) {
      coords = new float[] {_x, _y, _z};

      double r = Math.sqrt((_x * _x) + (_y * _y));
      double d = Math.atan2(_y, _x);

      polar = new double[] {d, r};
      polar[0] = (Math.round(d * 100.00)) / 100.00;

      size = _size;
      hover = false;
      triggered = false;
      selected = false;
      name = _name;
    }
  /** Inform all registered MeasureToolListeners of a new distance. */
  private void reportDistance(boolean finalDistance) {
    if (dragStartPos == null || dragCurrentPos == null) return;

    final double dx = dragCurrentPos.x - dragStartPos.x;
    final double dy = dragCurrentPos.y - dragStartPos.y;
    final double d = Math.sqrt(dx * dx + dy * dy);
    final double angle = Math.atan2(dy, dx);

    Iterator iterator = this.listeners.iterator();
    while (iterator.hasNext()) {
      MeasureToolListener listener = (MeasureToolListener) iterator.next();
      if (finalDistance) listener.newDistance(d, angle, this.mapComponent);
      else listener.distanceChanged(d, angle, this.mapComponent);
    }
  }
Beispiel #14
0
  public static void main(String[] argv) {
    // Random seed for generation.
    UniformRandom.set_seed(System.currentTimeMillis());

    // Start with a random unit length vector: a random angle.
    double theta = UniformRandom.uniform(0, 2.0 * Math.PI);
    double[] x = new double[2];
    x[0] = Math.cos(theta);
    x[1] = Math.sin(theta);

    // Find perpendicular unit length vector by adding 90-deg
    double[] y = new double[2];
    y[0] = Math.cos(theta + Math.PI / 2);
    y[1] = Math.sin(theta + Math.PI / 2);

    // Test.
    double xDoty = MatrixTool.dotProduct(x, y);
    System.out.println("x dot y = " + xDoty);

    // Make the matrix with x and y as columns.
    double[][] A = new double[2][2];
    A[0][0] = x[0];
    A[1][0] = x[1];
    A[0][1] = y[0];
    A[1][1] = y[1];

    double delTheta = 0.1;
    double[] u = new double[2];
    Function F = new Function("alpha vs theta");
    for (theta = 0; theta <= 2 * Math.PI; theta += delTheta) {
      // Generate next vector along unit circle.
      u[0] = Math.cos(theta);
      u[1] = Math.sin(theta);
      // Apply A to u.
      double[] z = MatrixTool.matrixVectorMult(A, u);
      double alpha = Math.atan2(z[1], z[0]);
      // Get z's angle.
      alpha = fixAngle(alpha);
      // Add to data set.
      F.add(theta, alpha);
    }

    // Plot data set.
    F.show();
  }
Beispiel #15
0
  public void navigateRobot() {
    System.out.println("Path Index: " + pathIndex);
    System.out.println("goalPath Size: " + goalPath.size());
    System.out.println("locX, locY, locTheta" + locX + ", " + locY + ", " + locTheta);
    System.out.println("goalX, goalY, goalTheta: " + goalX + ", " + goalY + ", " + goalTheta);
    if (goalPath.size() > 0 && !done) {
      if (pathIndex < goalPath.size() - 1
          && Math.abs(goalX - locX) < 0.2
          && Math.abs(goalY - locY) < 0.2) {
        pathIndex++;
      }
      if (pathIndex == goalPath.size() - 1
          && Math.abs(goalX - locX) < 0.05
          && Math.abs(goalY - locY) < 0.05) {
        pathIndex++;
      }
      if (pathIndex >= goalPath.size()) {
        done = true;
        setVelocities(0.0, 0.0);
      }

      goalX = goalPath.get(pathIndex).x;
      goalY = goalPath.get(pathIndex).y;
      goalTheta = Math.atan2(goalY - locY, goalX - locX);
      if (goalTheta < 0) {
        goalTheta += 2 * Math.PI;
      }

      double error = goalTheta - locTheta;
      if (error > Math.PI) {
        error -= 2 * Math.PI;
      } else if (error < -Math.PI) {
        error += 2 * Math.PI;
      }
      if (Math.abs(error) < Math.PI / 8.0) {
        setVelocities(0.3, anglePID.update(error));
      } else {
        setVelocities(0, anglePID.update(error));
      }
      // setVelocities(0.2, anglePID.update(error));
    }
  }
Beispiel #16
0
  public int filterRGB(int x, int y, int rgb) {
    float dx = x - centreX;
    float dy = y - centreY;
    float distance = dx * dx + dy * dy;
    float angle = (float) Math.atan2(dy, dx);
    float d = (angle + ImageMath.PI) / (ImageMath.TWO_PI) * rays;
    int i = (int) d;
    float f = d - i;

    if (radius != 0) {
      float length = ImageMath.lerp(f, rayLengths[i % rays], rayLengths[(i + 1) % rays]);
      float g = length * length / (distance + 0.0001f);
      g = (float) Math.pow(g, (100 - amount) / 50.0);
      f -= 0.5f;
      //			f *= amount/50.0f;
      f = 1 - f * f;
      f *= g;
    }
    f = ImageMath.clamp(f, 0, 1);
    return ImageMath.mixColors(f, rgb, color);
  }
Beispiel #17
0
  private static LinkedList<Point2D> getCirclePoints(
      double centerLat, double centerLong, int numberOfPoints, double radius) {

    LinkedList<Point2D> Point2Ds = new LinkedList<Point2D>();

    double lat1, long1;
    double d_rad;
    double delta_pts;
    double radial, lat_rad, dlon_rad, lon_rad;

    // convert coordinates to radians
    lat1 = Math.toRadians(centerLat);
    long1 = Math.toRadians(centerLong);

    // radius is in meters
    d_rad = radius / 6378137;

    // loop through the array and write points
    for (int i = 0; i <= numberOfPoints; i++) {
      delta_pts = 360 / (double) numberOfPoints;
      radial = Math.toRadians((double) i * delta_pts);

      // This algorithm is limited to distances such that dlon < pi/2
      lat_rad =
          Math.asin(
              Math.sin(lat1) * Math.cos(d_rad)
                  + Math.cos(lat1) * Math.sin(d_rad) * Math.cos(radial));
      dlon_rad =
          Math.atan2(
              Math.sin(radial) * Math.sin(d_rad) * Math.cos(lat1),
              Math.cos(d_rad) - Math.sin(lat1) * Math.sin(lat_rad));
      lon_rad = ((long1 + dlon_rad + Math.PI) % (2 * Math.PI)) - Math.PI;

      Point2Ds.add(new Point2D.Double(Math.toDegrees(lat_rad), Math.toDegrees(lon_rad)));
    }
    return Point2Ds;
  }
Beispiel #18
0
  public float evaluate(float x, float y) {
    for (int j = 0; j < results.length; j++) results[j].distance = Float.POSITIVE_INFINITY;

    int ix = (int) x;
    int iy = (int) y;
    float fx = x - ix;
    float fy = y - iy;

    float d = checkCube(fx, fy, ix, iy, results);
    if (d > fy) d = checkCube(fx, fy + 1, ix, iy - 1, results);
    if (d > 1 - fy) d = checkCube(fx, fy - 1, ix, iy + 1, results);
    if (d > fx) {
      checkCube(fx + 1, fy, ix - 1, iy, results);
      if (d > fy) d = checkCube(fx + 1, fy + 1, ix - 1, iy - 1, results);
      if (d > 1 - fy) d = checkCube(fx + 1, fy - 1, ix - 1, iy + 1, results);
    }
    if (d > 1 - fx) {
      d = checkCube(fx - 1, fy, ix + 1, iy, results);
      if (d > fy) d = checkCube(fx - 1, fy + 1, ix + 1, iy - 1, results);
      if (d > 1 - fy) d = checkCube(fx - 1, fy - 1, ix + 1, iy + 1, results);
    }

    float t = 0;
    for (int i = 0; i < 3; i++) t += coefficients[i] * results[i].distance;
    if (angleCoefficient != 0) {
      float angle = (float) Math.atan2(y - results[0].y, x - results[0].x);
      if (angle < 0) angle += 2 * (float) Math.PI;
      angle /= 4 * (float) Math.PI;
      t += angleCoefficient * angle;
    }
    if (gradientCoefficient != 0) {
      float a = 1 / (results[0].dy + results[0].dx);
      t += gradientCoefficient * a;
    }
    return t;
  }
Beispiel #19
0
  public void step() {
    // This will be the new plant when we are done
    StringBuilder newplant = new StringBuilder("");

    // Simulate the current plant position
    double x = params.startx;
    double y = params.starty;
    double dir = params.startdir;

    Stack<Pos> stack = new Stack<Pos>();

    if (verbose) System.out.println("***************");

    for (int i = 0; i < plant.length(); i++) {
      // Next character
      char cur = plant.charAt(i);
      boolean step = false;

      // always cap the dir
      while (dir < Math.PI * -1) dir += 2 * Math.PI;
      while (dir > Math.PI) dir -= 2 * Math.PI;

      // Go Forward
      for (int k = 0; k < params.lenAlphabet.length && !step; k++) {
        // Straight Lines is where the GROWING happens!
        if (cur == params.lenAlphabet[k]) {
          // calculate which side the sun is on (and to what degree it is on that side)
          double sundir = Math.atan2(y - suny, x - sunx) * -1;
          double diff = dir - sundir;

          while (diff < Math.PI * -1) diff += 2 * Math.PI;
          while (diff > Math.PI) diff -= 2 * Math.PI;

          if (verbose)
            System.out.printf(
                "(%.2f,%.2f) sundir: %.2f dir: %.2f diff: %.2f\n", x, y, sundir, dir, diff);

          // turn left
          if (diff < 0) {
            newplant.append("aa-[-a+a+a]+[+a-a-a]");
          }
          // turn right
          else {
            newplant.append("aa+[+a-a-a]-[-a+a+a]");
          }

          // we end up moving twice the distance
          x += 2 * params.length[k] * Math.cos(dir);
          y += 2 * params.length[k] * Math.sin(dir);
          step = true;
        }
      }

      // make sure we don't double print the straight lines
      if (step) continue;

      // Turn Right
      for (int k = 0; k < params.lenAlphabet.length && !step; k++) {
        if (cur == params.angAlphabetR[k]) {
          dir = (dir + params.angle[k]) % (Math.PI * 2);
          step = true;
        }
      }

      // Turn Left
      for (int k = 0; k < params.lenAlphabet.length && !step; k++) {
        if (cur == params.angAlphabetL[k]) {
          dir -= params.angle[k];
          if (dir < 0.0) dir += Math.PI * 2;

          step = true;
        }
      }

      // recursive steps
      // add to stack
      if (cur == '[') {
        stack.push(new Pos(x, y, dir));
      }

      // pop from stack and go back to that position
      if (cur == ']') {
        Pos back = stack.pop();
        x = back.x;
        y = back.y;
        dir = back.dir;
      }

      // Print Out
      newplant.append(cur);
    }

    plant = newplant;
  }
Beispiel #20
0
  public void paint(Graphics g) {
    super.paint(g);
    Graphics2D g2d = (Graphics2D) g;
    c.getAlpha();
    g.setFont(font2);
    g.setColor(c);
    g.drawImage(fon, 0, 0, 1024, 700, null);

    if (type_bullet1 == true) g.drawImage(pointer, 30, 550, 49, 47, null);

    image_bullet = new Sphere();
    g.drawImage(image_bullet.getImage(), 40, 600, 24, 24, null);
    g.drawString(Integer.toString(count_sphere), 35, 650);

    if (type_bullet2 == true) g.drawImage(pointer, 85, 550, 49, 47, null);
    image_bullet = new FireBall();
    g.drawImage(image_bullet.getImage(), 95, 600, 24, 24, null);
    g.drawString(Integer.toString(count_fireball), 95, 650);

    if (type_bullet3 == true) g.drawImage(pointer, 140, 550, 49, 47, null);
    image_bullet = new Rocket();
    g.drawImage(image_bullet.getImage(), 145, 595, 40, 40, null);
    g.drawString(Integer.toString(count_rocket), 150, 650);
    distance = 10;
    // Draw life
    for (int i = 0; i < player_live; i++) {
      g.drawImage(live, distance, 10, 11, 57, null);
      distance += 20;
    }
    // Create bullet
    for (int i = 0; i < bullet.size(); i++) {
      if (type_bullet1 == true && count_sphere > 0) {
        g2d.drawImage(
            bullet.get(i).getImage(),
            (int) bullet.get(i).bullet_x,
            (int) bullet.get(i).bullet_y,
            this);
      }
      if (type_bullet2 == true && count_fireball > 0) {
        g2d.drawImage(
            bullet.get(i).getImage(),
            (int) bullet.get(i).bullet_x,
            (int) bullet.get(i).bullet_y,
            this);
      }
      if (type_bullet3 == true && count_rocket != 0) {
        bullet.get(i).set_rotate(angle);
        g2d.setTransform(bullet.get(i).rotateX());
        g2d.drawImage(
            bullet.get(i).getImage(),
            (int) bullet.get(i).bullet_x,
            (int) bullet.get(i).bullet_y,
            this);
      }
    }
    g2d.setTransform(player.rotateX(angle));
    g2d.drawImage(player.getImage(), (int) player.getX(), (int) player.getY(), this);
    for (int i = 0; i < v_explosion.size(); i++) {
      g.drawImage(explosion, (int) v_explosion.get(i).x, (int) v_explosion.get(i).y, 59, 57, null);
    }
    for (int i = 0; i < enemy.size(); i++) {
      double povorot3 =
          Math.atan2(player.getY() - enemy.get(i).getY(), player.getX() - enemy.get(i).getX())
              * 180
              / 3.14;
      g2d.setTransform(enemy.get(i).rotateX(povorot3)); // new	
      g2d.drawImage(
          enemy.get(i).getImage(), (int) enemy.get(i).getX(), (int) enemy.get(i).getY(), this);
      g2d.setTransform(enemy.get(i).rotateX(0)); // new
      g.drawString(
          Integer.toString(enemy.get(i).get_live()),
          (int) enemy.get(i).getX() + (int) enemy.get(i).get_spr_w() / 2,
          (int) enemy.get(i).getY());
    }
    g.setFont(font);
    g2d.setTransform(affine);
    g.drawString("Level: " + Integer.toString(level), 710, 50);
    g.drawString("Next level: " + Integer.toString(time_level), 710, 90);
  }
Beispiel #21
0
  public void compute() {
    for (int i = 0; i < bullet.size(); i++) {
      bullet.get(i).bullet_x = bullet.get(i).bullet_x + 3 * bullet.get(i).current_direction_x;
      bullet.get(i).bullet_y = bullet.get(i).bullet_y + 3 * bullet.get(i).current_direction_y;
    }
    for (int i = 0; i < bullet.size(); i++) {
      if (bullet.get(i).bullet_x > 1366
          || bullet.get(i).bullet_x < 0
          || bullet.get(i).bullet_y > 768
          || bullet.get(i).bullet_y < 0) bullet.remove(i);
    }
    // Check collision bullet with enemy
    for (int i = 0; i < bullet.size(); i++) {
      for (int j = 0; j < enemy.size(); j++) {
        if (collision.collision_bullet_enemy(
                18,
                (int) bullet.get(i).bullet_x + 18,
                (int) bullet.get(i).bullet_y + 18, // bullet
                (int) enemy.get(j).getX(),
                (int) enemy.get(j).getY(), // point x1, y1
                (int) enemy.get(j).getX() + (int) enemy.get(j).get_spr_w(),
                (int) enemy.get(j).getY(), // point x2, y2
                (int) enemy.get(j).getX() + (int) enemy.get(j).get_spr_w(),
                (int) enemy.get(j).getY() + (int) enemy.get(j).get_spr_h(),
                (int) enemy.get(j).getX(),
                (int) enemy.get(j).getY() + (int) enemy.get(j).get_spr_h() // point x4, y4
                )
            == true) {
          //	create_explosion(bullet.get(i).bullet_x, bullet.get(i).bullet_y);
          if (bullet.get(i).get_type() == 's') // simple bullet
          {
            enemy.get(j).dec_live();
          }
          if (bullet.get(i).get_type() == 'f') // fireball
          {
            enemy.get(j).dec_live();
            enemy.get(j).dec_live();
          }
          if (bullet.get(i).get_type() == 'r') // rocket
          {
            enemy.get(j).dec_live();
            enemy.get(j).dec_live();
            enemy.get(j).dec_live();
          }
          if (enemy.get(j).get_live() <= 0) {
            enemy.remove(j);
          } else // push enemy
          {
            enemy.get(j).push();
          }
          bullet.remove(i);
          break;
        }
      }
    }
    // Преследование игрока
    for (int i = 0; i < enemy.size(); i++) {
      if (enemy.get(i).get_type() == "enemy1"
          || enemy.get(i).get_type() == "enemy2"
          || enemy.get(i).get_type() == "enemy3") {
        angle2 =
            Math.atan2(player.getY() - enemy.get(i).getY(), player.getX() - enemy.get(i).getX())
                * 180
                / 3.14;
        double a = player.getX() - enemy.get(i).getX();
        double b = player.getY() - enemy.get(i).getY();
        double kvadrat = Math.sqrt((a * a + b * b));
        double tempx = a / kvadrat;
        double tempy = Math.sqrt(1 - tempx * tempx);
        if (b < 0) tempy = -tempy;
        enemy.get(i).v_x = enemy.get(i).speed * tempx;
        enemy.get(i).v_y = enemy.get(i).speed * tempy;
        enemy.get(i).setX((enemy.get(i).getX() + enemy.get(i).speed * tempx));
        enemy.get(i).setY((enemy.get(i).getY() + enemy.get(i).speed * tempy));
      } else {
        if (enemy.get(i).created == false) {
          angle2 =
              Math.atan2(player.getY() - enemy.get(i).getY(), player.getX() - enemy.get(i).getX())
                  * 180
                  / 3.14;
          double a = player.getX() - enemy.get(i).getX();
          double b = player.getY() - enemy.get(i).getY();
          double kvadrat = Math.sqrt((a * a + b * b));
          double tempx = a / kvadrat;
          double tempy = Math.sqrt(1 - tempx * tempx);
          if (b < 0) tempy = -tempy;
          enemy.get(i).v_x = enemy.get(i).speed * tempx;
          enemy.get(i).v_y = enemy.get(i).speed * tempy;
          enemy.get(i).created = true;
        }
        enemy.get(i).setX((enemy.get(i).getX() + enemy.get(i).get_vx()));
        enemy.get(i).setY((enemy.get(i).getY() + enemy.get(i).get_vy()));
      }
    }
    for (int j = 0; j < enemy.size(); j++) {
      if (collision.collision_with_box(
              (int) player.getX() + 14,
              (int) player.getY() + 28,
              (int) player.getX() + 114,
              (int) player.getY() + 95,
              (int) enemy.get(j).getX() + 22,
              (int) enemy.get(j).getY() + 30,
              (int) enemy.get(j).getX() + 102,
              (int) enemy.get(j).getY() + 96)
          == true) {
        enemy.remove(j);
        player_live--;
        if (player_live == 0) {
          JOptionPane.showMessageDialog(null, "Game over!");
          start_game();
        }
      }
    }
    if (time_game > frequency) {
      generate_enemy();
      time_game = 0;
    }
    if (left_mouse_pressed == true && allow_shoot == true) {}

    time_game += 0.01;
    frequency -= 0.0001;
  }
Beispiel #22
0
    /*
     * Take a collection of vertices and edges between them,
     * and return the minimum area polygon containing all of them.
     *
     * ArrayList<Mat> vertices = the list of vertices
     *
     * ArrayList<TreeSet<Integer>> edgesTo = To find the edges connecting to a point indexed i in vertices,
     *                                       look in edgesTo.get(i). There you will find a list of indicies
     *                                       into vertices, which are the endpoints of the edges. This data
     *                                       structure is slow to write, but fast to read.
     */
    public static Polygon perimeter(ArrayList<Mat> vertices, ArrayList<TreeSet<Integer>> edgesTo) {
      // Find a point guaranteed to be on the perimeter of the polygon, so we can start tracing it
      // out
      double dist;
      double maxDist = -1;
      int farPoint = -1;
      for (int i = 0; i < vertices.size(); i++) {
        dist =
            Math.pow(
                Math.pow(vertices.get(i).data[0][0], 2) + Math.pow(vertices.get(i).data[1][0], 2),
                0.5);
        if (dist > maxDist) {
          maxDist = dist;
          farPoint = i;
        }
      }

      // Trace out the perimeter of the polygon
      int vertexStart = farPoint;
      int vertex = vertexStart;
      int prevVertex = -1;
      double prevAngle =
          Math.atan2(vertices.get(vertex).data[0][0], vertices.get(vertex).data[1][0]);
      double edgeAngle;
      double angleDiff;
      double minAngleDiff;
      int nextVertex = -1;
      double nextAngle = -1;
      Mat e0, e1;
      ArrayList<Mat> perimeter = new ArrayList<Mat>();
      while (vertex != vertexStart || prevVertex == -1) {
        minAngleDiff = 3 * Math.PI;
        System.err.println("v:" + vertex);
        e0 = vertices.get(vertex);
        //	System.err.println(edgesTo.get(vertex));
        //	Mat.print(System.err, e0);
        perimeter.add(e0);

        if (perimeter.size() > 100) {
          // F**K!
          try {
            throw new Exception();
          } catch (Exception e) {
            e.printStackTrace();
            System.err.println("hey there");
            System.exit(1);
          }
        }

        for (int edgeVertex : edgesTo.get(vertex)) {
          e1 = vertices.get(edgeVertex);
          edgeAngle = Math.atan2(e1.data[0][0] - e0.data[0][0], e1.data[1][0] - e0.data[1][0]);
          angleDiff = edgeAngle - prevAngle;
          if (angleDiff < 0) {
            angleDiff += 2 * Math.PI;
          }
          if (angleDiff > 2 * Math.PI) {
            angleDiff -= 2 * Math.PI;
          }
          if (angleDiff < minAngleDiff && edgeVertex != prevVertex) {
            minAngleDiff = angleDiff;
            nextVertex = edgeVertex;
            nextAngle = edgeAngle;
          }
        }

        System.err.println("PERIMETER ITERATION:");
        System.err.println("vertexStart = " + vertexStart);
        System.err.println("prevVertex = " + prevVertex);
        System.err.println("vertex = " + vertex);
        System.err.println("nextVertex = " + nextVertex);
        System.err.println("");

        if (nextAngle > 0) {
          prevAngle = nextAngle - Math.PI;
        } else {
          prevAngle = nextAngle + Math.PI;
        }
        prevVertex = vertex;
        vertex = nextVertex;
      }

      return new Polygon(perimeter);
    }
 /**
  * Returns the angle of this point in polar coordinates.
  *
  * @return the angle (in radians) of this point in polar coordiantes (between -pi/2 and pi/2)
  */
 public double theta() {
   return Math.atan2(y, x);
 }
Beispiel #24
0
    public Shape createStrokedShape(Shape shape) {
      GeneralPath result = new GeneralPath();
      PathIterator it = new FlatteningPathIterator(shape.getPathIterator(null), FLATNESS);
      float points[] = new float[6];
      float moveX = 0, moveY = 0;
      float lastX = 0, lastY = 0;
      float thisX = 0, thisY = 0;
      int type = 0;
      boolean first = false;
      float next = 0;
      int phase = 0;

      float factor = 1;

      while (!it.isDone()) {
        type = it.currentSegment(points);
        switch (type) {
          case PathIterator.SEG_MOVETO:
            moveX = lastX = points[0];
            moveY = lastY = points[1];
            result.moveTo(moveX, moveY);
            first = true;
            next = wavelength / 2;
            break;

          case PathIterator.SEG_CLOSE:
            points[0] = moveX;
            points[1] = moveY;
            // Fall into....

          case PathIterator.SEG_LINETO:
            thisX = points[0];
            thisY = points[1];
            float dx = thisX - lastX;
            float dy = thisY - lastY;
            float distance = (float) Math.sqrt(dx * dx + dy * dy);
            if (distance >= next) {
              float r = 1.0f / distance;
              float angle = (float) Math.atan2(dy, dx);
              while (distance >= next) {
                float x = lastX + next * dx * r;
                float y = lastY + next * dy * r;
                float tx = amplitude * dy * r;
                float ty = amplitude * dx * r;
                if ((phase & 1) == 0) result.lineTo(x + amplitude * dy * r, y - amplitude * dx * r);
                else result.lineTo(x - amplitude * dy * r, y + amplitude * dx * r);
                next += wavelength;
                phase++;
              }
            }
            next -= distance;
            first = false;
            lastX = thisX;
            lastY = thisY;
            if (type == PathIterator.SEG_CLOSE) result.closePath();
            break;
        }
        it.next();
      }

      // return stroke.createStrokedShape( result );
      return result;
    }
  public void run() {
    setAllColors(Color.GREEN);
    setTurnRadarRight(Double.POSITIVE_INFINITY);

    double robotX, robotY;
    double robotHeading, angleToGoal, angleToObs;
    double adjustment;
    double obsAngle, obsAdjustment;
    double angleDiff;
    double speedToGoal, speedFromObs;

    Enemy temp;
    obstacles = new HashMap<String, Enemy>(10);

    while (true) {
      if (foundGoal) {
        robotX = getX();
        robotY = getY();
        goalX = obstacles.get(GOAL_NAME).x;
        goalY = obstacles.get(GOAL_NAME).y;

        // Adjust robocode's returned heading so that 0 aligns with the positive x-axis instead of
        // the positive y-axis.
        // Also make it so that positive angle indicates a counter clockwise rotation instead of the
        // clockwise style
        // returned by robocode.
        robotHeading = 360 - (getHeading() - 90);
        angleToGoal = Math.toDegrees(Math.atan2(goalY - robotY, goalX - robotX));
        if (angleToGoal < 0) {
          angleToGoal += 360;
        }

        adjustment = angleToGoal - robotHeading;
        adjustment = normalizeAngle(adjustment);
        speedToGoal = calcRobotSpeedLinear(robotX, robotY, goalX, goalY);

        // Calculate how the robot's heading and speed should be affected by objects that it has
        // located
        // as it explores the world.
        Iterator it = obstacles.entrySet().iterator();
        while (it.hasNext()) {
          System.out.println("Iterating through objects.");

          Map.Entry pairs = (Map.Entry) it.next();

          // If the current item in the Iterator isn't the goal.
          if (!pairs.getKey().equals(GOAL_NAME)) {
            temp = (Enemy) pairs.getValue();
            speedFromObs = calcObjRepulseSpeed(robotX, robotY, temp.x, temp.y);

            // If the robot is in range of the object to be affected by it's repulsion.
            if (speedFromObs != 0) {
              obsAngle = Math.toDegrees(Math.atan2(robotY - temp.y, robotX - temp.x));
              if (obsAngle < 0) obsAngle += 360;

              angleDiff = obsAngle - angleToGoal;
              angleDiff = normalizeAngle(angleDiff);
              adjustment += (angleDiff * (speedFromObs / speedToGoal));
              speedToGoal -= speedFromObs;
            }
          }

          // Was getting a null pointer exception when using this. The internet lied about its
          // usefulness.
          // it.remove(); // avoids a ConcurrentModificationException
        }

        adjustment = normalizeAngle(adjustment);
        setTurnLeft(adjustment);
        // ahead(speedToGoal);
        setAhead(speedToGoal);
      }

      execute();
    }
  }
  /**
   * getBestEvadeDirection returns the largest approximate gap to escape. This gap is approximated
   * by finding the gaps between all potential collideable objects around the Bucketbot, and
   * weighting them positively by size and weighting them inversely by both distance and gapsize.
   * The direction bisecting the largest of these weighted gaps is returned.
   *
   * @param visible_distance how far the Bucketbot can see
   * @return best direction to evade
   */
  public float getBestEvadeDirection(float visible_distance) {
    alphabetsoup.framework.Map map = SimulationWorldSimpleExample.getSimulationWorld().getMap();
    // get visible objects within the distance of the next planned update
    Collection<Circle> visible_objects =
        map.getBucketbotsWithinDistance(getX(), getY(), visible_distance);
    if (getBucket() != null)
      visible_objects.addAll(map.getBucketsWithinDistance(getX(), getY(), visible_distance));

    // if nothing other than bucketbot (and bucket if applicable), keep going in same direction
    if ((getBucket() == null && visible_objects.size() <= 1)
        || (getBucket() != null && visible_objects.size() <= 2)) return getDirection();

    List<CollideableObject> objects = new ArrayList<CollideableObject>();
    // get object distances and directions
    for (Circle c : visible_objects) {
      if (c == this || c == getBucket()) continue;

      float object_direction = (float) Math.atan2(c.getY() - getY(), c.getX() - getX());
      objects.add(
          new CollideableObject(
              2 * c.getRadius(), getDistance(c.getX(), c.getY()), object_direction));
    }

    // add 4 walls
    if (getX() < visible_distance)
      objects.add(
          new CollideableObject(
              (float) (2 * Math.sqrt(visible_distance * visible_distance - getX() * getX())),
              getX(),
              (float) Math.PI));
    if (map.getWidth() - getX() < visible_distance)
      objects.add(
          new CollideableObject(
              (float)
                  (2
                      * Math.sqrt(
                          visible_distance * visible_distance
                              - (map.getWidth() - getX()) * (map.getWidth() - getX()))),
              map.getWidth() - getX(),
              0.0f));

    if (getY() < visible_distance)
      objects.add(
          new CollideableObject(
              (float) (2 * Math.sqrt(visible_distance * visible_distance - getY() * getY())),
              getY(),
              (float) (3 * Math.PI / 2)));
    if (map.getHeight() - getY() < visible_distance)
      objects.add(
          new CollideableObject(
              (float)
                  (2
                      * Math.sqrt(
                          visible_distance * visible_distance
                              - (map.getHeight() - getY()) * (map.getHeight() - getY()))),
              map.getHeight() - getY(),
              (float) Math.PI / 2));

    // if no objects, then nothing to collide with
    if (objects.size() == 0) return getDirection();

    // sort objects by direction, so between each two objects is the smallest real gaps
    Collections.sort(objects, objects.get(0));

    // add beginning one again
    objects.add(
        new CollideableObject(
            objects.get(0).size,
            objects.get(0).distance,
            (float) (objects.get(0).direction + 2 * Math.PI)));

    // find maximal gap
    // start with first gap
    float evade_direction = (objects.get(0).direction + objects.get(1).direction) / 2;
    double weight =
        ((objects.get(0).size + objects.get(1).size) / 2)
            / (((objects.get(0).distance + objects.get(1).distance) / 2)
                * (objects.get(1).direction - objects.get(0).direction));

    // for all after the first gap
    for (int i = 1; i < objects.size() - 1; i++) {
      // get weight (a heuristic for speed)
      float w =
          ((objects.get(i).size + objects.get(i + 1).size) / 2)
              / (((objects.get(i).distance + objects.get(i + 1).distance) / 2)
                  * (objects.get(i + 1).direction - objects.get(i).direction));
      // if better direction, then choose direction bisecting the two objects
      if (w < weight) {
        weight = w;
        evade_direction = (objects.get(i).direction + objects.get(i + 1).direction) / 2;
      }
    }
    return evade_direction;
  }
    public void act(BucketbotBase self) {
      alphabetsoup.framework.Map map = SimulationWorldSimpleExample.getSimulationWorld().getMap();
      float cur_speed = getSpeed(); // called once for code efficiency (since getSpeed does a sqrt)

      // find distance to be covered before next planned update
      getNextEventTime(curTime);
      double time_interval = Math.max(getMinUntil() - curTime, 0.001);
      float distance_to_be_covered =
          (float) (Math.max(cur_speed, getTargetSpeed()) * time_interval);
      distance_to_be_covered +=
          2 * getRadius(); // count its radius and the radius of another object
      // make sure see at least a minimal distance regardless of speed
      float min_visible_distance = 3 * getRadius();
      distance_to_be_covered = Math.max(distance_to_be_covered, min_visible_distance);

      // get visible objects within the distance of the next planned update
      Collection<Circle> visible_objects =
          map.getBucketbotsWithinDistance(getX(), getY(), distance_to_be_covered);
      if (self.getBucket() != null)
        visible_objects.addAll(
            map.getBucketsWithinDistance(getX(), getY(), distance_to_be_covered));

      // don't want to do anything yet,
      // unless something is now visible that wasn't before,
      // a collision occured (speed == 0)
      // timer is ready to do something else
      if (((getBucket() == null && visible_objects.size() == 1)
              || (getBucket() != null && visible_objects.size() == 2))
          && cur_speed > 0.0f
          && curTime < cruiseUntil) return;

      // if something other than bucketbot (and bucket if applicable) is near, evade
      if ((getBucket() == null && visible_objects.size() > 1)
          || (getBucket() != null && visible_objects.size() > 2)) {

        // find closest object
        float min_dist2 = Float.POSITIVE_INFINITY; // minimum distance squared
        for (Circle c : visible_objects) {
          if (c == self || c == self.getBucket()) continue;

          // see if infront of bucketbot
          float object_direction = (float) Math.atan2(c.getY() - getY(), c.getX() - getX());
          float relative_direction = angleDifference(object_direction, getDirection());
          if (Math.abs(relative_direction)
              > Math.PI / 4 + 0.5) // just beyond 1/4 circle, to make sure they don't get stuck
          continue;

          // see if it's closer than any other
          float dist2 =
              (getX() - c.getX()) * (getX() - c.getX()) + (getY() - c.getY()) * (getY() - c.getY());
          if (dist2 < min_dist2) min_dist2 = dist2;
        }

        // if anything is closer than this constant value, then evade...
        if (min_dist2 < min_visible_distance * min_visible_distance) {
          float new_direction = getBestEvadeDirection(min_visible_distance);

          if (getDirection() != new_direction) setDirection(new_direction);

          setTargetSpeed(getMaxVelocity());
          cruiseUntil = curTime + 0.25f;

          frustration = 0.0f;
          stateQueue.add(0, bucketbotEvade);
          return;
        }
      }

      // if trying to move, but can't try evading
      if (cur_speed > 0.0f) {
        stuckCount = 0;
      } else { // not moving...
        stuckCount++;
        if (stuckCount > 3) {
          frustration = 0.0f;
          stateQueue.add(0, bucketbotEvade);
          return;
        }
      }

      // find distance to goal
      float goal_distance = getDistance(moveToX, moveToY);

      // make sure tolerance is less than the map's tolerance/3 to make sure that if it sets a
      // bucket down,
      // the next one bucketbot will be able to pick it up (and could also be tolerance/3 away)
      // better fudge factor than tolerance / 2 (which is the minimum that will work)
      float tolerance = map.getTolerance() / 3;

      // if close enough to goal and stopped moving, then do next action
      if (goal_distance < tolerance && cur_speed == 0.0f) {
        frustration = 0.0f;

        stateQueue.remove(0);
        if (stateQueue.size() > 0) stateQueue.get(0).act(self);
        return;
      }

      // if not facing the right way (within tolerance), or heading outside of the map, turn so it
      // is a good direction
      double projected_x = getX() + goal_distance * Math.cos(getDirection());
      double projected_y = getY() + goal_distance * Math.sin(getDirection());
      if ((projected_x - moveToX) * (projected_x - moveToX)
                  + (projected_y - moveToY) * (projected_y - moveToY)
              >= tolerance * tolerance
          || projected_x + getRadius() > map.getWidth()
          || projected_x - getRadius() < 0.0
          || projected_y + getRadius() > map.getHeight()
          || projected_y - getRadius() < 0.0) {

        setDirection((float) Math.atan2(moveToY - getY(), moveToX - getX()));
        if (cur_speed > 0) setTargetSpeed(0.0f);
        cruiseUntil = getAccelerateUntil();
        return;
      }

      // going the right direction -now figure out speed

      // if too close to stop, then stop as fast as possible
      float decel_time = cur_speed / getMaxAcceleration();
      float decel_distance = getMaxAcceleration() / 2 * decel_time * decel_time;
      if (cur_speed > 0.0f && decel_distance > goal_distance) {
        setTargetSpeed(0.0f);
        cruiseUntil = getAccelerateUntil();
        frustration = (frustration + 1.0f) / 2;
        return;
      }

      // get new velocity based on frustration
      float cur_vel = getMaxVelocity() * Math.max(1.0f - frustration, 0.0078125f);
      setTargetSpeed(cur_vel);

      // see if have room to accelerate to full speed and still decelerate
      float accel_time = getTargetSpeedDifference() / getMaxAcceleration();
      float accel_distance =
          cur_speed * accel_time + getMaxAcceleration() / 2 * accel_time * accel_time;
      decel_time = cur_vel / getMaxAcceleration();
      decel_distance = getMaxAcceleration() / 2 * accel_time * accel_time;

      // if enough room to fully accelerate, do so
      if (accel_distance + decel_distance <= goal_distance) cruiseUntil = getAccelerateUntil();
      else { // don't have time to fully accelerate
        // having this code spread out with sub-steps dramatically helps the java compiler have
        // better performance
        double cos_dir = Math.cos(getDirection());
        double sin_dir = Math.sin(getDirection());
        double x_accel = getMaxAcceleration() * cos_dir;
        double y_accel = getMaxAcceleration() * sin_dir;
        if (Math.abs(x_accel) > Math.abs(y_accel)) {
          double x_goal = goal_distance * cos_dir;
          cruiseUntil =
              curTime
                  + sqrt2
                      * (Math.sqrt(2 * x_accel * x_goal + getXVelocity() * getXVelocity())
                          - sqrt2 * getXVelocity())
                      / (2 * x_accel);
        } else {
          double y_goal = goal_distance * sin_dir;
          cruiseUntil =
              curTime
                  + sqrt2
                      * (Math.sqrt(2 * y_accel * y_goal + getYVelocity() * getYVelocity())
                          - sqrt2 * getYVelocity())
                      / (2 * y_accel);
        }
      }
    } // act()
Beispiel #28
0
  /** Regenerates the image. */
  private synchronized void regenerateImage() {
    int size =
        Math.min(
            MAX_SIZE,
            Math.min(
                getWidth() - imagePadding.left - imagePadding.right,
                getHeight() - imagePadding.top - imagePadding.bottom));

    if (mode == ColorPicker.BRI || mode == ColorPicker.SAT) {
      float bri2 = this.bri;
      float sat2 = this.sat;
      float radius = ((float) size) / 2f;
      float hue2;
      float k = 1.2f; // the number of pixels to antialias
      for (int y = 0; y < size; y++) {
        float y2 = (y - size / 2f);
        for (int x = 0; x < size; x++) {
          float x2 = (x - size / 2f);
          double theta = Math.atan2(y2, x2) - 3 * Math.PI / 2.0;
          if (theta < 0) theta += 2 * Math.PI;

          double r = Math.sqrt(x2 * x2 + y2 * y2);
          if (r <= radius) {
            if (mode == ColorPicker.BRI) {
              hue2 = (float) (theta / (2 * Math.PI));
              sat2 = (float) (r / radius);
            } else { // SAT
              hue2 = (float) (theta / (2 * Math.PI));
              bri2 = (float) (r / radius);
            }
            row[x] = Color.HSBtoRGB(hue2, sat2, bri2);
            if (r > radius - k) {
              int alpha = (int) (255 - 255 * (r - radius + k) / k);
              if (alpha < 0) alpha = 0;
              if (alpha > 255) alpha = 255;
              row[x] = row[x] & 0xffffff + (alpha << 24);
            }
          } else {
            row[x] = 0x00000000;
          }
        }
        image.getRaster().setDataElements(0, y, size, 1, row);
      }
    } else if (mode == ColorPicker.HUE) {
      float hue2 = this.hue;
      for (int y = 0; y < size; y++) {
        float y2 = ((float) y) / ((float) size);
        for (int x = 0; x < size; x++) {
          float x2 = ((float) x) / ((float) size);
          row[x] = Color.HSBtoRGB(hue2, x2, y2);
        }
        image.getRaster().setDataElements(0, y, image.getWidth(), 1, row);
      }
    } else { // mode is RED, GREEN, or BLUE
      int red2 = red;
      int green2 = green;
      int blue2 = blue;
      for (int y = 0; y < size; y++) {
        float y2 = ((float) y) / ((float) size);
        for (int x = 0; x < size; x++) {
          float x2 = ((float) x) / ((float) size);
          if (mode == ColorPicker.RED) {
            green2 = (int) (x2 * 255 + .49);
            blue2 = (int) (y2 * 255 + .49);
          } else if (mode == ColorPicker.GREEN) {
            red2 = (int) (x2 * 255 + .49);
            blue2 = (int) (y2 * 255 + .49);
          } else {
            red2 = (int) (x2 * 255 + .49);
            green2 = (int) (y2 * 255 + .49);
          }
          row[x] = 0xFF000000 + (red2 << 16) + (green2 << 8) + blue2;
        }
        image.getRaster().setDataElements(0, y, size, 1, row);
      }
    }
    repaint();
  }
  public void func_70071_h_() {
    if (!field_70170_p.field_72995_K
        && (field_70235_a != null && field_70235_a.field_70128_L
            || !field_70170_p.func_72899_e(
                (int) field_70165_t, (int) field_70163_u, (int) field_70161_v))) {
      func_70106_y();
      return;
    }
    super.func_70071_h_();
    func_70015_d(1);
    if (field_70238_i) {
      int i = field_70170_p.func_72798_a(field_70231_e, field_70228_f, field_70229_g);
      if (i == field_70237_h) {
        field_70236_j++;
        if (field_70236_j == 600) {
          func_70106_y();
        }
        return;
      }
      field_70238_i = false;
      field_70159_w *= field_70146_Z.nextFloat() * 0.2F;
      field_70181_x *= field_70146_Z.nextFloat() * 0.2F;
      field_70179_y *= field_70146_Z.nextFloat() * 0.2F;
      field_70236_j = 0;
      field_70234_an = 0;
    } else {
      field_70234_an++;
    }
    Vec3 vec3 = Vec3.func_72437_a().func_72345_a(field_70165_t, field_70163_u, field_70161_v);
    Vec3 vec3_1 =
        Vec3.func_72437_a()
            .func_72345_a(
                field_70165_t + field_70159_w,
                field_70163_u + field_70181_x,
                field_70161_v + field_70179_y);
    MovingObjectPosition movingobjectposition = field_70170_p.func_72933_a(vec3, vec3_1);
    vec3 = Vec3.func_72437_a().func_72345_a(field_70165_t, field_70163_u, field_70161_v);
    vec3_1 =
        Vec3.func_72437_a()
            .func_72345_a(
                field_70165_t + field_70159_w,
                field_70163_u + field_70181_x,
                field_70161_v + field_70179_y);
    if (movingobjectposition != null) {
      vec3_1 =
          Vec3.func_72437_a()
              .func_72345_a(
                  movingobjectposition.field_72307_f.field_72450_a,
                  movingobjectposition.field_72307_f.field_72448_b,
                  movingobjectposition.field_72307_f.field_72449_c);
    }
    Entity entity = null;
    List list =
        field_70170_p.func_72839_b(
            this,
            field_70121_D
                .func_72321_a(field_70159_w, field_70181_x, field_70179_y)
                .func_72314_b(1.0D, 1.0D, 1.0D));
    double d = 0.0D;
    Iterator iterator = list.iterator();
    do {
      if (!iterator.hasNext()) {
        break;
      }
      Entity entity1 = (Entity) iterator.next();
      if (entity1.func_70067_L()
          && (!entity1.func_70028_i(field_70235_a) || field_70234_an >= 25)) {
        float f2 = 0.3F;
        AxisAlignedBB axisalignedbb = entity1.field_70121_D.func_72314_b(f2, f2, f2);
        MovingObjectPosition movingobjectposition1 = axisalignedbb.func_72327_a(vec3, vec3_1);
        if (movingobjectposition1 != null) {
          double d1 = vec3.func_72438_d(movingobjectposition1.field_72307_f);
          if (d1 < d || d == 0.0D) {
            entity = entity1;
            d = d1;
          }
        }
      }
    } while (true);
    if (entity != null) {
      movingobjectposition = new MovingObjectPosition(entity);
    }
    if (movingobjectposition != null) {
      func_70227_a(movingobjectposition);
    }
    field_70165_t += field_70159_w;
    field_70163_u += field_70181_x;
    field_70161_v += field_70179_y;
    float f =
        MathHelper.func_76133_a(field_70159_w * field_70159_w + field_70179_y * field_70179_y);
    field_70177_z =
        (float) ((Math.atan2(field_70159_w, field_70179_y) * 180D) / 3.1415927410125732D);
    for (field_70125_A = (float) ((Math.atan2(field_70181_x, f) * 180D) / 3.1415927410125732D);
        field_70125_A - field_70127_C < -180F;
        field_70127_C -= 360F) {}
    for (; field_70125_A - field_70127_C >= 180F; field_70127_C += 360F) {}
    for (; field_70177_z - field_70126_B < -180F; field_70126_B -= 360F) {}
    for (; field_70177_z - field_70126_B >= 180F; field_70126_B += 360F) {}
    field_70125_A = field_70127_C + (field_70125_A - field_70127_C) * 0.2F;
    field_70177_z = field_70126_B + (field_70177_z - field_70126_B) * 0.2F;
    float f1 = 0.95F;
    if (func_70090_H()) {
      for (int j = 0; j < 4; j++) {
        float f3 = 0.25F;
        field_70170_p.func_72869_a(
            "bubble",
            field_70165_t - field_70159_w * (double) f3,
            field_70163_u - field_70181_x * (double) f3,
            field_70161_v - field_70179_y * (double) f3,
            field_70159_w,
            field_70181_x,
            field_70179_y);
      }

      f1 = 0.8F;
    }
    field_70159_w += field_70232_b;
    field_70181_x += field_70233_c;
    field_70179_y += field_70230_d;
    field_70159_w *= f1;
    field_70181_x *= f1;
    field_70179_y *= f1;
    field_70170_p.func_72869_a(
        "smoke", field_70165_t, field_70163_u + 0.5D, field_70161_v, 0.0D, 0.0D, 0.0D);
    func_70107_b(field_70165_t, field_70163_u, field_70161_v);
  }
 /**
  * Returns the angle between this point and that point.
  *
  * @return the angle in radians (between -pi and pi) between this point and that point (0 if
  *     equal)
  */
 private double angleTo(Point2D that) {
   double dx = that.x - this.x;
   double dy = that.y - this.y;
   return Math.atan2(dy, dx);
 }