/* Point.c 2-D point */ #include #include #include #include #include #ifndef PI #define PI M_PI #endif struct point { double x; double y; }; #define EPS 1.0e-8 #define ABS(x) (((x)>=0.0)?(x):(-(x))) #include "Point.h" Point ConsPoint( double x, double y ) { Point p; p = malloc( sizeof( struct point ) ); if ( p != NULL ) { p->x = x; p->y = y; } return p; } Point ConsPointRT( double r, double theta ) { Point p; assert( r >= 0.0 ); p = malloc( sizeof( struct point ) ); if ( p != NULL ) { p->x = r*cos( theta ); p->y = r*sin( theta ); } return p; } Point CopyPoint( Point p ) { Point p1; assert( p != NULL ); p1 = malloc( sizeof( struct point ) ); if ( p1 != NULL ) { memcpy( p1, p, sizeof( struct point ) ); } return p1; } void DeletePoint( Point p ) { assert( p != NULL ); free( p ); } void SetPoint2( Point p, Point p1 ) { assert( p != NULL ); assert( p1 != NULL ); memcpy( p, p1, sizeof( struct point ) ); } void FreePoint( Point p ) { assert( p != NULL ); free( p ); } void SetPoint( Point p, double x, double y ) { assert( p != NULL ); p->x = x; p->y = y; } double XCoord( Point p ) { assert( p != NULL ); return p->x; } double YCoord( Point p ) { assert( p != NULL ); return p->y; } double RPolar( Point p ) { double x, y; assert( p != NULL ); x = p->x; y = p->y; return sqrt( x*x + y*y ); } double TPolar( Point p ) { assert( p != NULL ); if ( ABS(p->y) < EPS ) { return 0.0; } else { if ( ABS(p->x) < EPS ) { return M_PI/2.0; } } return atan2( p->y, p->x ); } double Dist( Point p1, Point p2 ) { double dx, dy, d; assert( p1 != NULL ); assert( p2 != NULL ); dx = p1->x - p2->x; dy = p1->y - p2->y; d = sqrt( dx*dx + dy*dy ); return d; } void Displace( Point p, Point delta ) { /* Displace p by delta: p := p+delta */ assert( p != NULL ); assert( delta != NULL ); p->x = p->x + delta->x; p->y = p->y + delta->y; } /* Direction (radians) from p1 to p2 */ double Direction( Point p1, Point p2 ) { double t; assert( p1 != NULL ); assert( p2 != NULL ); t = atan2( p2->y - p1->y, p2->x - p1->x ); return t; } double AngleBetween( Point p1, Point p2, Point p3 ) { double t; assert( p1 != NULL ); assert( p2 != NULL ); assert( p3 != NULL ); t = Direction( p2, p1 ) - Direction( p2, p3 ); if ( t < 0 ) t += (2.0*PI); return t; } void PrintPoint ( char *s, Point p ) { assert( p != NULL ); fprintf( stderr, "%s (%6.2f,%6.2f)", s, p->x, p->y ); fflush( stderr ); }