/* Segment en 2D */ /* */ /* Auteur: Nicolas JANEY */ /* nicolas.janey@univ-fcomte.fr */ /* Novembre 2011 */ #include #include #include #include "Segment2D.h" #include "Position2D.h" #include "Rectangle2D.h" Segment2D::Segment2D(void) { pi = new Position2D(); pf = new Position2D(); } Segment2D::Segment2D(Position2D *p1,Position2D *p2) { pi = new Position2D(p1); pf = new Position2D(p2); } Segment2D::Segment2D(Segment2D *s) { pi = new Position2D(s->pi); pf = new Position2D(s->pf); } Segment2D::~Segment2D(void) { delete(pi); delete(pf); } void Segment2D::print(void) { pi->print(); printf("\n"); pf->print(); printf("\n"); } static int round(double v) { return((int) (v + (( v > 0.0 ) ? 0.4999 : -0.4999))); } int code(Position2D *p,Rectangle2D *r) { int code = 0x0000; if ( p->c[0] < r->ig->c[0] ) code |= 0x0001; if ( p->c[0] > r->sd->c[0] ) code |= 0x0002; if ( p->c[1] < r->ig->c[1] ) code |= 0x0004; if ( p->c[1] > r->sd->c[1] ) code |= 0x0008; return(code); } double Segment2D::abscisse(double y) { double a = (pf->c[1]-pi->c[1])/(pf->c[0]-pi->c[0]); double b = pi->c[1] - a*pi->c[0]; return((y-b)/a); } double Segment2D::ordonnee(double x) { double a = (pf->c[1]-pi->c[1])/(pf->c[0]-pi->c[0]); double b = pi->c[1] - a*pi->c[0]; return(a*x+b); } int Segment2D::clip(Rectangle2D *r) { int c1,c2; c1 = code(pi,r); c2 = code(pf,r); while ( ( c1 || c2 ) && ( (c1&c2) == 0 ) ) { if ( !c1 ) { Position2D p = *pi; *pi = *pf; *pf = p; int aux = c1; c1 = c2; c2 = aux; } if ( (c1&0x0001) != 0 ) { pi->c[1] = ordonnee(r->ig->c[0]); pi->c[0] = r->ig->c[0]; } else if ( (c1&0x0002) != 0 ) { pi->c[1] = ordonnee(r->sd->c[0]); pi->c[0] = r->sd->c[0]; } else if ( (c1&0x0004) != 0 ) { pi->c[0] = abscisse(r->ig->c[1]); pi->c[1] = r->ig->c[1]; } else if ( (c1&0x0008) != 0 ) { pi->c[0] = abscisse(r->sd->c[1]); pi->c[1] = r->sd->c[1]; } c1 = code(pi,r); } return ( !c1 && !c2); }