package graphics.draw2d;



import java.awt.*;

public class Oval2d extends Shape
    implements Intersects {
  int x1 = 0;
  int y1 = 0;
  int h = 1;
  int w = 1;
  int xc = 0;
  int yc = 0;
  Vec2d center;

  public Vec2d intersect(Ray2d ray) {

    double t1, t2,          /* where the ray intersects */
        // vDotV = distance square from sphere center to
        // ray origin
        vDotV,
        dDotV,
        dDotD,
        thc;        // length sqare of the half chord


    Vec2d v;    // vector to the center of the sphere from  ray origin
    Vec2d d;    // Direction vector

    /* use the closest approach algorithm */
    v = new Vec2d(-center.v[0], -center.v[1]);
    d = new Vec2d(ray.d.v[0], ray.d.v[1]);
    v.add(ray.p);
    int wOn2 = w / 2;
    int hOn2 = h / 2;
    v.v[0] = (double) (v.v[0] / wOn2);
    v.v[1] = (double) (v.v[1] / hOn2);
    d.v[0] = (double) (d.v[0] / wOn2);
    d.v[1] = (double) (d.v[1] / hOn2);

    // v = v - ray.p
    // loc = v^2
    vDotV = v.dot(v);
    dDotD = d.dot(d);

    // dDotV = D dot V =
    // cos(angle between ray and vec to center);
    dDotV = v.dot(d);   /* find the closest approach */


    /* compute the half chord square from the ray intersection to the
       intersection normal. */
    thc = (dDotV * dDotV) - dDotD * (vDotV - 1);

    if (thc < 0.0)
      return null;   /* ray misses the sphere */

    /* find the ray intersection */
    t1 = (-dDotV + Math.sqrt(thc)) / (dDotD);
    t2 = (-dDotV - Math.sqrt(thc)) / (dDotD);
    if ((t1 > 0) && (t2 > 0)) {
      if (t1 < t2)
        return ray.vecOnLine((double) t1);
      else
        return ray.vecOnLine((double) t2);
    } else if (t1 > 0)
      return ray.vecOnLine((double) t1);
    else if (t2 > 0)
      return ray.vecOnLine((double) t2);
    else
      return null;      // object behind
  }

  public Oval2d(int _x1, int _y1, int _x2, int _y2) {
    x1 = _x1;
    y1 = _y1;
    w = Math.abs(_x2 - x1);
    h = Math.abs(_y2 - y1);
    if (_x1 > _x2) x1 = _x2;
    if (_y1 > _y2) y1 = _y2;
    xc = x1 + w / 2;
    yc = y1 + h / 2;
    center =
        new Vec2d(xc, yc);
  }

  public void paint(Graphics g) {
    g.drawOval(x1, y1, w, h);
    g.fillOval(xc, yc, 2, 2);
    g.drawString("(" + xc + "," + yc + ")", xc + 3, yc + 3);
    g.drawLine(xc, yc, xc, yc - h / 2);
    g.drawLine(xc, yc, xc - w / 2, yc);
  }
}