/* Segment de droite en 2D                      */
/*                                              */
/* Auteur: Nicolas JANEY                        */
/* nicolas.janey@univ-fcomte.fr                 */
/* Novembre 2012                                */

#include <stdlib.h>
#include <stdio.h>
#include <math.h>

#include "Segment2D.h"
#include "Position2D.h"
#include "TraceSegment.h"
#include "Rectangle2D.h"

/* Constructeurs                                */

Segment2D::Segment2D(void) {
  p1 = new Position2D();
  p2 = new Position2D();
}

Segment2D::Segment2D(Position2D *p1,Position2D *p2) {
  this->p1 = new Position2D(p1);
  this->p2 = new Position2D(p2);
}

Segment2D::Segment2D(Segment2D *s) {
  p1 = new Position2D(s->p1);
  p2 = new Position2D(s->p2);
}

/* Destructeur                                  */

Segment2D::~Segment2D(void) {
  delete(p1);
  delete(p2);
}

/* Dessin OpenGL                                */

void Segment2D::draw(void) {
  trace(p1,p2);
}

//////////////////////////////////////////////////

/* Abscisse correspondant a une ordonnee        */

double Segment2D::abscisse(double ordonnee) {
  if ( p1->c[0] == p2->c[0] )
    return(p1->c[0]);
  double a = (p1->c[1]-p2->c[1])/(p1->c[0]-p2->c[0]);
  double b = p1->c[1]-a*p1->c[0];
  return((ordonnee-b)/a);
}

/* Ordonnee correspondant a une abscisse        */

double Segment2D::ordonnee(double abscisse) {
  double a = (p1->c[1]-p2->c[1])/(p1->c[0]-p2->c[0]);
  double b = p1->c[1]-a*p1->c[0];
  return(a*abscisse+b);
}

/* Clipping de Cohen-Sutherland                 */

int Segment2D::clip(Rectangle2D *r){
  int c1 = r->code(p1);
  int c2 = r->code(p2);
  while ( ( ( c1 != 0 ) || ( c2 != 0 ) ) &&
          ( (c1&c2) == 0 ) ) {
    if ( c1 == 0 ) {
      { Position2D *aux = p1;
        p1 = p2;
        p2 = aux; }
      { int aux = c1;
        c1 = c2;
        c2 = aux; } }
    if ( (c1&1) != 0 ) {
      p1->c[1] = ordonnee(r->ig->c[0]);
      p1->c[0] = r->ig->c[0]; }
      else
      if ( (c1&2) != 0 ) {
        p1->c[1] = ordonnee(r->sd->c[0]);
        p1->c[0] = r->sd->c[0]; }
        else
        if ( (c1&4) != 0 ) {
          p1->c[0] = abscisse(r->ig->c[1]);
          p1->c[1] = r->ig->c[1]; }
          else {
          p1->c[0] = abscisse(r->sd->c[1]);
          p1->c[1] = r->sd->c[1]; }
    c1 = r->code(p1); }
  return(( c1 == 0 ) && ( c2 == 0 ));
}

//////////////////////////////////////////////////
