package p5;
import anar.*;




import processing.core.PApplet;

public class Test03uCircle extends PApplet {

  /*
   * Example for Anar library by Guillaume LaBelle + Julien Nembrini
   * http://anar.ch
   */


  Obj myObj;

  public void setup(){
    size(800,400,OPENGL);
    Anar.init(this);
    Anar.drawAxis();

    initForm();
  }

  public void initForm(){
    myObj = new Obj();

    Face triangle = new Face();

    triangle.add(Anar.PtRnd(100,100));
    triangle.add(Anar.PtRnd(100,100));
    triangle.add(Anar.PtRnd(100,100));
    
    myObj.add(triangle);

    Pt center = new PtBary(triangle);
    center.fill(255,0,0);
    myObj.add(center);

    Anar.camTarget(myObj);

    Pt circumcenter = circumCenter(triangle);
    circumcenter.fill(0,0,255);
    myObj.add(circumcenter);

    Face circle = new Circle(circumcenter,circumRadius(triangle),100);
    myObj.add(circle);

  }

  // http://en.wikipedia.org/wiki/Circumcircle
  Pt circumCenter(Face f){

    Vertex p1 = new Vertex(f.pt(0));
    Vertex p2 = new Vertex(f.pt(1));
    Vertex p3 = new Vertex(f.pt(2));

    float aLen = p2.lengthSq(p3);
    float bLen = p1.lengthSq(p3);
    float cLen = p1.lengthSq(p2);

    float sub = 2*Vertex.cross(p1.minus(p2),p2.minus(p3)).lengthSq();

    float a = aLen*Vertex.dot(p1.minus(p2),p1.minus(p3))/sub;
    float b = bLen*Vertex.dot(p2.minus(p1),p2.minus(p3))/sub;
    float c = cLen*Vertex.dot(p3.minus(p1),p3.minus(p2))/sub;

    Vertex result = (Vertex)p1.multiply(a).plus(p2.multiply(b)).plus(p3.multiply(c));

    return Anar.Pt(result);
  }

  // http://en.wikipedia.org/wiki/Circumcircle
  float circumRadius(Face f){

    float totalLength;

    // Isit general for polyfgons?
    totalLength = f.pt(0).length(f.pt(1));
    totalLength *= f.pt(1).length(f.pt(2));
    totalLength *= f.pt(2).length(f.pt(0));

    float area = f.area();

    println(area);

    println(totalLength);

    return totalLength/ (4*area);
  }


  public void draw(){
    background(155);
    myObj.draw();
  }

  public void keyPressed(){
    if(key==' ')
      initForm();
  }

  public static void main(String[] args){
    PApplet.main(new String[]{Test03uCircle.class.getName()});
  }
}

