r310: plotfile updates
[ctsim.git] / libctsim / phantom.cpp
1 /*****************************************************************************
2 ** FILE IDENTIFICATION
3 ** 
4 **     Name:                   phm.cpp
5 **     Purpose:                Routines for phantom objects
6 **     Progammer:              Kevin Rosenberg
7 **     Date Started:           Aug 1984
8 **
9 **  This is part of the CTSim program
10 **  Copyright (C) 1983-2000 Kevin Rosenberg
11 **
12 **  $Id: phantom.cpp,v 1.23 2000/12/21 03:40:58 kevin Exp $
13 **
14 **  This program is free software; you can redistribute it and/or modify
15 **  it under the terms of the GNU General Public License (version 2) as
16 **  published by the Free Software Foundation.
17 **
18 **  This program is distributed in the hope that it will be useful,
19 **  but WITHOUT ANY WARRANTY; without even the implied warranty of
20 **  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
21 **  GNU General Public License for more details.
22 **
23 **  You should have received a copy of the GNU General Public License
24 **  along with this program; if not, write to the Free Software
25 **  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
26 ******************************************************************************/
27
28 #include "ct.h"
29
30 const int PhantomElement::POINTS_PER_CIRCLE = 360;\r
31 const double PhantomElement::SCALE_PELEM_EXTENT=0.005;  // increase pelem limits by 0.5% \r
32
33 const int Phantom::PHM_INVALID = -1;
34 const int Phantom::PHM_HERMAN = 0;
35 const int Phantom::PHM_B_HERMAN = 1;
36 const int Phantom::PHM_SHEPP_LOGAN = 2;
37 const int Phantom::PHM_B_SHEPP_LOGAN = 3;
38 const int Phantom::PHM_UNITPULSE = 4;
39
40 const char* Phantom::s_aszPhantomName[] = 
41 {
42   {"herman"},
43   {"herman-b"},
44   {"shepp-logan"},
45   {"shepp-logan-b"},
46   {"unitpulse"},
47 };
48
49 const char* Phantom::s_aszPhantomTitle[] = 
50 {
51   {"Herman Head"},
52   {"Herman Head (Bordered)"},
53   {"Shepp-Logan"},
54   {"Shepp-Logan (Bordered)"},
55   {"Unit Pulse"},
56 };
57
58 const int Phantom::s_iPhantomCount = sizeof(s_aszPhantomName) / sizeof(const char*);
59
60
61 // CLASS IDENTIFICATION
62 //   Phantom
63 //
64
65 Phantom::Phantom ()
66 {
67   init ();
68 }
69
70
71 Phantom::Phantom (const char* const phmName)
72 {
73   init ();
74   createFromPhantom (phmName);
75 }
76
77 void 
78 Phantom::init ()
79 {
80   m_nPElem = 0;
81   m_xmin = 1E30;
82   m_xmax = -1E30;
83   m_ymin = 1E30;
84   m_ymax = -1E30;
85   m_diameter = 0;
86   m_composition = P_PELEMS;
87   m_fail = false;
88   m_id = PHM_INVALID;
89 }
90
91 Phantom::~Phantom ()
92 {
93   for (PElemIterator i = m_listPElem.begin(); i != m_listPElem.end(); i++) {
94     delete *i;
95   }
96 }
97
98
99 const char*
100 Phantom::convertPhantomIDToName (int phmID)
101 {
102   static const char *name = "";
103
104   if (phmID >= 0 && phmID < s_iPhantomCount)
105       return (s_aszPhantomName[phmID]);
106
107   return (name);
108 }
109
110 const char*
111 Phantom::convertPhantomIDToTitle (int phmID)
112 {
113   static const char *title = "";
114
115   if (phmID >= 0 && phmID < s_iPhantomCount)
116       return (s_aszPhantomName[phmID]);
117
118   return (title);
119 }
120       
121 int
122 Phantom::convertNameToPhantomID (const char* const phmName) 
123 {
124   int id = PHM_INVALID;
125
126   for (int i = 0; i < s_iPhantomCount; i++)
127       if (strcasecmp (phmName, s_aszPhantomName[i]) == 0) {
128           id = i;
129           break;
130       }
131
132   return (id);
133 }
134   
135
136 bool
137 Phantom::createFromPhantom (const char* const phmName)
138 {
139   int phmid = convertNameToPhantomID (phmName);
140   if (phmid == PHM_INVALID) {
141     m_fail = true;
142     m_failMessage = "Invalid phantom name ";
143     m_failMessage += phmName;
144     return false;
145   }
146
147   m_name = phmName;
148   createFromPhantom (phmid);
149   return true;
150 }
151
152 bool
153 Phantom::createFromPhantom (const int phmid)
154 {
155   switch (phmid) 
156     {
157     case PHM_HERMAN:
158       addStdHerman();
159       break;
160     case PHM_B_HERMAN:
161       addStdHermanBordered();
162       break;
163     case PHM_SHEPP_LOGAN:
164       addStdSheppLogan();
165       break;
166     case PHM_B_SHEPP_LOGAN:
167       addStdSheppLoganBordered();
168       break;
169     case PHM_UNITPULSE:
170       m_composition = P_UNIT_PULSE;
171       addPElem ("rectangle", 0., 0., 100., 100., 0., 0.);     // outline 
172       addPElem ("ellipse", 0., 0., 1., 1., 0., 1.);           // pulse 
173       break;
174     default:
175       m_fail = true;
176       m_failMessage = "Illegal phantom id ";
177       m_failMessage += phmid;
178       return false;
179     }
180
181   m_id = phmid;
182
183   return true;
184 }
185
186
187 /* METHOD IDENTIFICATION
188  *   createFromFile          Add PhantomElements from file
189  *
190  * SYNOPSIS
191  *   createFromFile (filename)
192  *
193  * RETURNS
194  *   true if pelem were added
195  *   false if an pelem not added
196  */
197
198 bool
199 Phantom::createFromFile (const char* const fname)
200 {
201   bool bGoodFile = true;
202   FILE *fp;
203
204   if ((fp = fopen (fname, "r")) == NULL)
205     return (false);
206
207   m_name = fname;
208
209   while (1) {
210     double cx, cy, u, v, rot, dens;
211     char pelemtype[80];
212
213     int status = fscanf (fp, "%79s %lf %lf %lf %lf %lf %lf", pelemtype, &cx, &cy, &u, &v, &rot, &dens);
214     
215     if (status == static_cast<int>(EOF)) 
216       break;
217     else if (status != 7) {
218       sys_error (ERR_WARNING, "Insufficient fields reading phantom file %s [Phantom::createFromFile]", fname);
219       bGoodFile = false;
220     }
221     addPElem (pelemtype, cx, cy, u, v, rot, dens);
222   }
223   
224   fclose (fp);
225
226   return (bGoodFile);
227 }
228
229
230 /* NAME
231  *   addPElem           Add pelem
232  *
233  * SYNOPSIS
234  *   addPElem (type, cx, cy, u, v, rot, atten)
235  *   char *type         type of pelem (box, ellipse, etc)
236  *   double cx, cy      pelem center
237  *   double u,v         pelem size
238  *   double rot         rotation angle of pelem (in degrees)
239  *   double atten       x-ray attenuation cooefficient
240  */
241
242 void 
243 Phantom::addPElem (const char *type, const double cx, const double cy, const double u, const double v, const double rot, const double atten)
244 {
245   PhantomElement *pelem = new PhantomElement (type, cx, cy, u, v, rot, atten);
246
247   m_listPElem.push_front (pelem);
248
249   // update phantom limits
250   if (m_xmin > pelem->xmin())    m_xmin = pelem->xmin();
251   if (m_xmax < pelem->xmax())    m_xmax = pelem->xmax();
252   if (m_ymin > pelem->ymin())    m_ymin = pelem->ymin();
253   if (m_ymax < pelem->ymax())    m_ymax = pelem->ymax();
254
255   if (m_diameter < pelem->diameter())
256     m_diameter = pelem->diameter();
257
258   //  m_diameter = lineLength(m_xmin, m_ymin, m_xmax, m_ymax);
259
260   m_nPElem++;
261 }
262
263
264 /*----------------------------------------------------------------------*/
265 /*                      Input-Output Routines                           */
266 /*----------------------------------------------------------------------*/
267
268
269 /* NAME
270  *   print                              Print vertices of Phantom pelems
271  *
272  * SYNOPSIS
273  *   print (phm)
274  */
275
276 void 
277 Phantom::print () const
278 {
279   printf("PRINTING Phantom\n\n");
280   printf("number of pelems in Phantom = %d\n", m_nPElem);
281   printf("limits: xmin=%8.2g  ymin=%8.2g  xmax=%8.2g  ymax=%8.2g\n",
282          m_xmin, m_ymin, m_xmax, m_ymax);
283   
284   for (PElemIterator i = m_listPElem.begin(); i != m_listPElem.end(); i++) {
285       printf("PELEM:\n");
286       printf("# pts=%3d atten = %7.4f   rot = %7.2f (deg)\n",
287              (*i)->nOutlinePoints(), (*i)->atten(), convertRadiansToDegrees ((*i)->rot()));
288     
289     printf("xmin=%7.3g  ymin=%7.3g  xmax=%7.3g  ymax=%7.3g\n",
290            (*i)->xmin(), (*i)->ymin(), (*i)->xmax(), (*i)->ymax());
291     
292     //    for (int i = 0; i < m_nPoints; i++)
293     //      printf("\t%8.3g    %8.3g\n", i->xOutline()[i], i->yOutline()[i]);
294   }
295 }
296
297
298 /* NAME
299  *   show               Show vector outline of Phantom to user
300  *
301  * SYNOPSIS
302  *   show (pic)
303  */
304
305 #ifdef HAVE_SGP
306 void 
307 Phantom::show () const
308 {
309   SGPDriver driverSGP ("Phantom Show");
310   SGP sgp (driverSGP);
311
312   show (sgp);
313
314   std::cout << "Press return to continue";
315   cio_kb_getc();
316 }
317
318 void 
319 Phantom::show (SGP& sgp) const
320 {
321   double wsize = m_xmax - m_xmin;
322   if ((m_ymax - m_ymin) > wsize) 
323       wsize = m_ymax - m_ymin;
324   wsize *= 1.01;
325   double halfWindow = wsize / 2;
326
327   double xcent = m_xmin + (m_xmax - m_xmin) / 2;
328   double ycent = m_ymin + (m_ymax - m_ymin) / 2;
329
330   sgp.setWindow (xcent - halfWindow, ycent - halfWindow, xcent + halfWindow, ycent + halfWindow);
331
332   draw (sgp);
333 }
334 #endif
335
336
337 /* NAME
338  *   draw               Draw vector outline of Phantom
339  *
340  * SYNOPSIS
341  *   draw ()
342  */
343
344 #ifdef HAVE_SGP
345 void 
346 Phantom::draw (SGP& sgp) const
347 {
348   for (PElemIterator i = m_listPElem.begin(); i != m_listPElem.end(); i++)
349     sgp.polylineAbs ((*i)->xOutline(), (*i)->yOutline(), (*i)->nOutlinePoints());
350 }
351 #endif
352
353
354 /* NAME
355  *   addStdSheppLogan   Make head phantom of Shepp-Logan
356  *
357  * REFERENCES
358  *   S. W. Rowland, "Computer Implementation of Image Reconstruction
359  *      Formulas", in "Image Reconstruction from Projections: Implementation
360  *      and Applications", edited by G. T. Herman, 1978.
361  */
362
363 void 
364 Phantom::addStdSheppLogan ()
365 {
366   addPElem ("ellipse",  0.0000,  0.0000, 0.6900,  0.9200,   0.0,  1.00);
367   addPElem ("ellipse",  0.0000, -0.0184, 0.6624,  0.8740,   0.0, -0.98);
368   addPElem ("ellipse",  0.2200,  0.0000, 0.1100,  0.3100, -18.0, -0.02);
369   addPElem ("ellipse", -0.2200,  0.0000, 0.1600,  0.4100,  18.0, -0.02);
370   addPElem ("ellipse",  0.0000,  0.3500, 0.2100,  0.2500,   0.0,  0.01);
371   addPElem ("ellipse",  0.0000,  0.1000, 0.0460,  0.0460,   0.0,  0.01);
372   addPElem ("ellipse",  0.0000, -0.1000, 0.0460,  0.0460,   0.0,  0.01);
373   addPElem ("ellipse", -0.0800, -0.6050, 0.0460,  0.0230,   0.0,  0.01);
374   addPElem ("ellipse",  0.0000, -0.6050, 0.0230,  0.0230,   0.0,  0.01);
375   addPElem ("ellipse",  0.0600, -0.6050, 0.0230,  0.0230,   0.0,  0.01);
376   addPElem ("ellipse",  0.5538, -0.3858, 0.0330,  0.2060, -18.0,  0.03);
377 }
378
379 void 
380 Phantom::addStdSheppLoganBordered ()
381 {
382   addStdSheppLogan ();
383   addPElem ("rectangle", 0.000, 0.0000, 0.8600, 1.150, 0.0, 0.00);
384 }
385
386 /* NAME
387  *   addStdHerman                       Standard head phantom of G. T. Herman
388  *
389  * REFERENCES
390  *   G. T. Herman, "Image Reconstructions from Projections:  The Fundementals
391  *      of Computed Tomography", 1979.
392  */
393
394 void 
395 Phantom::addStdHerman ()
396 {
397   addPElem ("ellipse",  0.000,  1.50,  0.375, 0.3000,  90.00, -0.003);
398   addPElem ("ellipse",  0.675, -0.75,  0.225, 0.1500, 140.00,  0.010);
399   addPElem ("ellipse",  0.750,  1.50,  0.375, 0.2250,  50.00,  0.003);
400   addPElem ("segment",  1.375, -7.50,  1.100, 0.6250,  19.20, -0.204);
401   addPElem ("segment",  1.375, -7.50,  1.100, 4.3200,  19.21,  0.204);
402   addPElem ("segment",  0.000, -2.25,  1.125, 0.3750,   0.00, -0.003);
403   addPElem ("segment",  0.000, -2.25,  1.125, 3.0000,   0.00,  0.003);
404   addPElem ("segment", -1.000,  3.75,  1.000, 0.5000, 135.00, -0.003);
405   addPElem ("segment", -1.000,  3.75,  1.000, 3.0000, 135.00,  0.003);
406   addPElem ("segment",  1.000,  3.75,  1.000, 0.5000, 225.00, -0.003);
407   addPElem ("segment",  1.000,  3.75,  1.000, 3.0000, 225.00,  0.003);
408   addPElem ("triangle", 5.025,  3.75,  1.125, 0.5000, 110.75,  0.206);
409   addPElem ("triangle",-5.025,  3.75,  1.125, 0.9000,-110.75,  0.206);
410   addPElem ("ellipse",  0.000,  0.00,  8.625, 6.4687,  90.00,  0.416);
411   addPElem ("ellipse",  0.000,  0.00,  7.875, 5.7187,  90.00, -0.206);
412 }
413
414 void
415 Phantom::addStdHermanBordered ()
416 {
417   addStdHerman();
418   addPElem ("rectangle",  0.000, 0.00, 10.780, 8.110,  90.00, 0.000);
419 }
420
421
422 /* NAME
423  *    convertToImagefile                Make image array from Phantom
424  *
425  * SYNOPSIS
426  *    pic_to_imagefile (pic, im, nsample)
427  *    Phantom& pic              Phantom definitions
428  *    ImageFile  *im            Computed pixel array
429  *    int nsample               Number of samples along each axis for each pixel
430  *                              (total samples per pixel = nsample * nsample)
431  */
432
433 void
434 Phantom::convertToImagefile (ImageFile& im, const int in_nsample, const int trace) const
435 {
436   convertToImagefile (im, in_nsample, trace, 0, im.nx(), true);
437 }
438
439 void 
440 Phantom::convertToImagefile (ImageFile& im, const int in_nsample, const int trace, const int colStart, const int colCount, bool bStoreAtColumnPos) const
441 {
442   int nx = im.nx();
443   int ny = im.ny();
444   if (nx < 2 || ny < 2)
445       return;
446
447   int nsample = in_nsample;
448   if (nsample < 1)  
449     nsample = 1;
450
451   double dx = m_xmax - m_xmin;
452   double dy = m_ymax - m_ymin;
453   double xcent = m_xmin + dx / 2;
454   double ycent = m_ymin + dy / 2;
455   double phmlen = (dx > dy ? dx : dy);
456
457   double phmradius = phmlen / 2;
458
459   double xmin = xcent - phmradius;
460   double xmax = xcent + phmradius;
461   double ymin = ycent - phmradius;
462   double ymax = ycent + phmradius;
463
464   // Each pixel holds the average of the intensity of the cell with (ix,iy) at the center of the pixel
465   // Set major increments so that the last cell v[nx-1][ny-1] will start at xmax - xinc, ymax - yinc).
466   // Set minor increments so that sample points are centered in cell
467
468   double xinc = (xmax - xmin) / nx;
469   double yinc = (ymax - ymin) / ny;
470
471   double kxinc = xinc / nsample;                /* interval between samples */
472   double kyinc = yinc / nsample;
473   double kxofs = kxinc / 2;             /* offset of 1st point */
474   double kyofs = kyinc / 2;
475
476   im.setAxisExtent (xmin, xmax, ymin, ymax);
477   im.setAxisIncrement (xinc, yinc);
478
479   ImageFileArray v = im.getArray();
480
481   for (int ix = 0; ix < colCount; ix++)
482     for (int iy = 0; iy < ny; iy++) {
483       int iColStore = ix;
484       if (bStoreAtColumnPos)
485                 iColStore += colStart;
486       v[iColStore][iy] = 0;
487     }
488
489   double x_start = xmin + (colStart * xinc);
490   for (PElemConstIterator pelem = m_listPElem.begin(); pelem != m_listPElem.end(); pelem++) {
491       const PhantomElement& rPElem = **pelem;
492       double x, y, xi, yi;
493       int ix, iy, kx, ky;
494       for (ix = 0, x = x_start; ix < colCount; ix++, x += xinc) {
495         int iColStore = ix;
496         if (bStoreAtColumnPos)
497           iColStore += colStart;
498         for (iy = 0, y = ymin; iy < ny; iy++, y += yinc) {
499           for (kx = 0, xi = x + kxofs; kx < nsample; kx++, xi += kxinc) {
500             for (ky = 0, yi = y + kyofs; ky < nsample; ky++, yi += kyinc)
501               if (rPElem.isPointInside (xi, yi, PHM_COORD) == TRUE)
502                         v[iColStore][iy] += rPElem.atten();
503               } // for kx
504           } /* for iy */
505       }  /* for ix */
506   }  /* for pelem */
507   
508
509   if (nsample > 1) {
510     double factor = 1.0 / static_cast<double>(nsample * nsample);
511
512 \r
513     for (int ix = 0; ix < colCount; ix++) {
514                 int iColStore = ix;\r
515                 if (bStoreAtColumnPos)\r
516                         iColStore += colStart;\r
517                 for (int iy = 0; iy < ny; iy++)
518                         v[iColStore][iy] *= factor;\r
519         }
520   }
521 }
522
523 ////////////////////////////////////////////////////////////////////////////////////////////////////////
524 // CLASS IDENTIFICATION
525 //
526 //      PhantomElement
527 //
528 // PURPOSE
529 //
530 ////////////////////////////////////////////////////////////////////////////////////////////////////////
531
532
533 PhantomElement::PhantomElement (const char *type, const double cx, const double cy, const double u, const double v, const double rot, const double atten)
534     : m_cx(cx), m_cy(cy), m_u(u), m_v(v), m_atten(atten), m_nPoints(0), m_xOutline(0), m_yOutline(0)
535 {
536   m_rot = convertDegreesToRadians (rot);   // convert angle to radians
537
538   m_type = convertNameToType (type);
539
540   makeTransformMatrices ();     // calc transform matrices between phantom and normalized phantomelement
541   makeVectorOutline ();         // calculate vector outline of pelem 
542
543   // Find maximum diameter of Object
544   double r2Max = 0;
545   for (int i = 0; i < m_nPoints; i++) {
546     double r2 = (m_xOutline[i] * m_xOutline[i]) + (m_yOutline[i] * m_yOutline[i]);
547     if (r2 > r2Max)
548       r2Max = r2;
549   }
550   m_diameter = 2 * sqrt( r2Max );
551
552   m_rectLimits[0] = m_xmin;   m_rectLimits[1] = m_ymin;
553   m_rectLimits[2] = m_xmax;   m_rectLimits[3] = m_ymax;
554 }
555
556
557 PhantomElement::~PhantomElement ()
558 {
559     delete m_xOutline;
560     delete m_yOutline;
561 }
562
563 PhmElemType
564 PhantomElement::convertNameToType (const char* const typeName)
565 {
566     PhmElemType type = PELEM_INVALID;
567
568     if (strcasecmp (typeName, "rectangle") == 0)
569         type = PELEM_RECTANGLE;
570     else if (strcasecmp (typeName, "triangle") == 0)
571         type = PELEM_TRIANGLE;
572     else if (strcasecmp (typeName, "ellipse") == 0)
573         type = PELEM_ELLIPSE;
574     else if (strcasecmp (typeName, "sector") == 0)
575         type = PELEM_SECTOR;
576     else if (strcasecmp (typeName, "segment") == 0)
577       type = PELEM_SEGMENT;
578     else
579         sys_error (ERR_WARNING, "Unknown PhantomElement type %s [PhantomElement::PhantomElement]", type);
580
581     return (type);
582 }
583
584 void 
585 PhantomElement::makeTransformMatrices ()
586 {
587   GRFMTX_2D temp;
588
589   // To map normalized Pelem coords to world Phantom 
590   //     scale by (u, v)                                       
591   //     rotate by rot                                  
592   //     translate by (cx, cy)                         
593
594   scale_mtx2 (m_xformObjToPhm, m_u, m_v);
595   rot_mtx2  (temp, m_rot);
596   mult_mtx2 (m_xformObjToPhm, temp, m_xformObjToPhm);
597   xlat_mtx2 (temp, m_cx, m_cy);
598   mult_mtx2 (m_xformObjToPhm, temp, m_xformObjToPhm);
599
600   // to map world Phantom coodinates to normalized PElem coords
601   //     translate by (-cx, -cy)
602   //     rotate by -rot
603   //     scale by (1/u, 1/v)
604
605   xlat_mtx2 (m_xformPhmToObj, -m_cx, -m_cy);
606   rot_mtx2  (temp, -m_rot);
607   mult_mtx2 (m_xformPhmToObj, temp, m_xformPhmToObj);
608   scale_mtx2 (temp, 1 / m_u, 1 / m_v);
609   mult_mtx2 (m_xformPhmToObj, temp, m_xformPhmToObj);
610 }
611
612
613 /* NAME
614  *   pelem_make_points          INTERNAL routine to calculate point array for an pelem
615  *
616  * SYNOPSIS
617  *   makepelempts (pelem)
618  *   PELEM *pelem       pelem whose points we are calculating
619  *
620  * NOTES
621  *   Called by phm_add_pelem()
622  */
623
624 void
625 PhantomElement::makeVectorOutline ()
626 {
627   double radius, theta, start, stop;
628   double xfact, yfact;
629   int cpts;
630
631   m_nPoints = 0;
632   switch (m_type) {
633   case PELEM_RECTANGLE:
634     m_nPoints = 5;
635     m_xOutline = new double [m_nPoints];
636     m_yOutline = new double [m_nPoints];
637     m_xOutline[0] =-m_u;        m_yOutline[0] =-m_v;
638     m_xOutline[1] = m_u;        m_yOutline[1] =-m_v;
639     m_xOutline[2] = m_u;        m_yOutline[2] = m_v;
640     m_xOutline[3] =-m_u;        m_yOutline[3] = m_v;
641     m_xOutline[4] =-m_u;        m_yOutline[4] =-m_v;
642     break;
643   case PELEM_TRIANGLE:
644     m_nPoints = 4;
645     m_xOutline = new double [m_nPoints];
646     m_yOutline = new double [m_nPoints];
647     m_xOutline[0] =-m_u;        m_yOutline[0] = 0.0;
648     m_xOutline[1] = m_u;        m_yOutline[1] = 0.0;
649     m_xOutline[2] = 0.0;        m_yOutline[2] = m_v;
650     m_xOutline[3] =-m_u;        m_yOutline[3] = 0.0;
651     break;
652   case PELEM_ELLIPSE:
653     cpts = numCirclePoints (TWOPI);
654     m_nPoints = cpts;
655     m_xOutline = new double [m_nPoints];
656     m_yOutline = new double [m_nPoints];
657     calcEllipsePoints (m_xOutline, m_yOutline, cpts, m_u, m_v);
658     break;
659   case PELEM_SECTOR:
660     radius = sqrt(m_u * m_u + m_v * m_v);
661     theta = atan(m_u / m_v);            // angle with y-axis 
662     start = 3.0 * HALFPI - theta;
663     stop  = 3.0 * HALFPI + theta;
664     cpts = numCirclePoints (stop - start);
665     m_nPoints = 3 + cpts;
666     m_xOutline = new double [m_nPoints];
667     m_yOutline = new double [m_nPoints];
668     
669     m_xOutline[0] = 0.0;                m_yOutline[0] = m_v;
670     m_xOutline[1] =-m_u;                m_yOutline[1] = 0.0;
671     calcArcPoints (&m_xOutline[2], &m_yOutline[2], cpts, 0.0, m_v, radius, start, stop);
672     m_xOutline[cpts + 2] = 0.0;
673     m_yOutline[cpts + 2] = m_v;
674     break;
675   case PELEM_SEGMENT:
676     radius = sqrt(m_u * m_u + m_v * m_v);
677     theta = atan (m_u / m_v);           // angle with y-axis 
678     start = 3.0 * HALFPI - theta;
679     stop  = 3.0 * HALFPI + theta;
680     
681     cpts = numCirclePoints (stop - start);
682     m_nPoints = cpts + 1;
683     m_xOutline = new double [m_nPoints];
684     m_yOutline = new double [m_nPoints];
685     
686     calcArcPoints (m_xOutline, m_yOutline, cpts, 0.0, m_v, radius, start, stop);
687     m_xOutline[cpts] = -m_u;
688     m_yOutline[cpts] = 0.0;
689     break;
690   default:
691     sys_error(ERR_WARNING, "illegal pelem type %d [makeVectorOutline]", m_type);
692     return;
693   }
694   
695   rotate2d (m_xOutline, m_yOutline, m_nPoints, m_rot);
696   xlat2d (m_xOutline, m_yOutline, m_nPoints, m_cx, m_cy);
697   
698   minmax_array (m_xOutline, m_nPoints, m_xmin, m_xmax);
699   minmax_array (m_yOutline, m_nPoints, m_ymin, m_ymax);
700   
701   // increase pelem extent by SCALE_PELEM_EXTENT to eliminate chance of
702   //   missing actual pelem maximum due to polygonal sampling 
703
704   xfact = (m_xmax - m_xmin) * SCALE_PELEM_EXTENT;
705   yfact = (m_ymax - m_ymin) * SCALE_PELEM_EXTENT;
706
707   m_xmin -= xfact;
708   m_ymin -= yfact;
709   m_xmax += xfact;
710   m_ymax += yfact;
711 }
712
713
714 /* NAME
715  *   calc_arc                   Calculate outline of a arc of a circle
716  *
717  * SYNOPSIS
718  *   calc_arc (x, y, xcent, ycent, pts, r, start, stop)
719  *   double x[], y[];           Array of points
720  *   int pts                    Number of points in array
721  *   double xcent, ycent        Center of cirlce
722  *   double r                   Radius of circle
723  *   double start, stop         Beginning & ending angles
724  */
725
726 void 
727 PhantomElement::calcArcPoints (double x[], double y[], const int pts, const double xcent, const double ycent, const double r, const double start, const double stop)
728 {
729     if (r <= 0.0)
730         sys_error (ERR_WARNING, "negative or zero radius in calc_arc()");
731
732     double theta = (stop - start) / (pts - 1);  // angle incr. between points 
733     double c = cos(theta);
734     double s = sin(theta);
735   
736     x[0] = r * cos (start) + xcent;
737     y[0] = r * sin (start) + ycent;
738
739     double xp = x[0] - xcent;
740     double yp = y[0] - ycent;
741     for (int i = 1; i < pts; i++) {
742         double xc = c * xp - s * yp;
743         double yc = s * xp + c * yp;
744         x[i] = xc + xcent;
745         y[i] = yc + ycent;
746         xp = xc;  yp = yc;
747     }
748 }
749
750
751 // NAME
752 //   PhantomElement::calcEllipsePoints    Calculate outline of a ellipse
753 //
754 // SYNOPSIS
755 //   calcEllipsePoints ()
756 //
757
758
759 void 
760 PhantomElement::calcEllipsePoints (double x[], double y[], const int pts, const double u, const double v)
761 {
762     calcArcPoints (x, y, m_nPoints, 0.0, 0.0, 1.0, 0.0, TWOPI);   // make a unit circle 
763     scale2d (x, y, m_nPoints, m_u, m_v);                             // scale to ellipse 
764 }
765
766
767 /* NAME
768  *   circle_pts         Calculate number of points to use for circle segment
769  *
770  * SYNOPSIS
771  *   n = circle_pts (theta)
772  *   int n              Number of points to use for arc
773  *   double theta       Length of arc in radians
774  */
775
776 int 
777 PhantomElement::numCirclePoints (double theta)
778 {
779     theta = clamp (theta, 0., TWOPI);
780
781     return static_cast<int> (POINTS_PER_CIRCLE * theta / TWOPI + 1.5);
782 }
783
784
785 bool
786 PhantomElement::clipLineWorldCoords (double& x1, double& y1, double& x2, double &y2) const
787 {
788   /* check if ray is outside of pelem extents */
789   double cx1 = x1, cy1 = y1, cx2 = x2, cy2 = y2;
790   if (! clip_rect (cx1, cy1, cx2, cy2, m_rectLimits))
791     return false;
792         
793   // convert phantom coordinates to pelem coordinates 
794   xform_mtx2 (m_xformPhmToObj, x1, y1);
795   xform_mtx2 (m_xformPhmToObj, x2, y2);
796         
797   if (! clipLineNormalizedCoords (x1, y1, x2, y2))
798     return false;
799
800   // convert standard pelem coordinates back to phantom coordinates 
801   xform_mtx2 (m_xformObjToPhm, x1, y1);
802   xform_mtx2 (m_xformObjToPhm, x2, y2);
803
804   return true;
805 }
806
807
808 /* NAME
809  *   pelem_clip_line                    Clip pelem against an arbitrary line
810  *
811  * SYNOPSIS
812  *   pelem_clip_line (pelem, x1, y1, x2, y2)
813  *   PhantomElement& pelem;             Pelem to be clipped
814  *   double *x1, *y1, *x2, *y2  Endpoints of line to be clipped
815  *
816  * RETURNS
817  *   true   if line passes through pelem
818  *              (x1, y1, x2, y2 hold coordinates of new line)
819  *   false  if line do not pass through pelem
820  *              (x1, y1, x2, y2 are undefined)
821  */
822
823 bool
824 PhantomElement::clipLineNormalizedCoords (double& x1, double& y1, double& x2, double& y2) const
825 {
826   bool accept = false;
827
828   switch (m_type) {
829   case PELEM_RECTANGLE:
830     double rect[4];
831     rect[0] = -1.0;  rect[1] = -1.0;
832     rect[2] = 1.0;  rect[3] = 1.0;
833     accept = clip_rect (x1, y1, x2, y2, rect);
834     break;
835   case PELEM_ELLIPSE:
836     accept = clip_circle (x1, y1, x2, y2, 0.0, 0.0, 1.0, 0.0, 0.0);
837     break;
838   case PELEM_TRIANGLE:
839     accept = clip_triangle (x1, y1, x2, y2, 1.0, 1.0, true);
840     break;
841   case PELEM_SEGMENT:
842     accept = clip_segment (x1, y1, x2, y2, m_u, m_v);
843     break;
844   case PELEM_SECTOR:
845     accept = clip_sector (x1, y1, x2, y2, m_u, m_v);
846     break;
847   default:
848     sys_error (ERR_WARNING, "Illegal pelem type %d [pelem_clip_line]", m_type);
849     break;
850   }
851
852   return(accept);
853 }
854
855
856 // METHOD IDENTIFICATION 
857 //    PhantomElement::isPointInside             Check if point is inside pelem
858 //
859 // SYNOPSIS
860 //    is_point_inside (pelem, x, y, coord_type)
861 //    double x, y               Point to see if lies in pelem
862 //    int coord_type            Coordinate type (PELEM_COORD or PHM_COORD)
863 //
864 // RETURNS
865 //    true if point lies within pelem
866 //    false if point lies outside of pelem
867
868 bool
869 PhantomElement::isPointInside (double x, double y, const CoordType coord_type) const
870 {
871   if (coord_type == PHM_COORD) {
872     xform_mtx2 (m_xformPhmToObj, x, y);
873   } else if (coord_type != PELEM_COORD) {
874     sys_error(ERR_WARNING, "Illegal coordinate type in pelem_is_point_inside");
875     return (false);
876   }
877
878   switch (m_type) {
879   case PELEM_RECTANGLE:
880     if (x > 1. || x < -1. || y > 1. || y < -1.)
881       return (false);
882     else
883       return (true);
884     break;
885   case PELEM_TRIANGLE:
886     if (y < 0. || y > 1. - x || y > 1. + x)
887       return (false);
888     else
889       return (true);
890     break;
891   case PELEM_ELLIPSE:
892     if (x > 1. || x < -1. || y > 1. || y < -1.)
893       return (false);
894     if (x * x + y * y > 1.)             // check if inside unit circle
895       return (false);
896     else
897       return (true);
898     break;
899
900     // for clipping segments & sectors, must NOT scale by (1/u, 1/v)
901     // because this destroys information about size of arc component 
902
903   case PELEM_SEGMENT:
904     if (x > 1. || x < -1. || y > 0.)
905         return (false);         // clip against y > 0 
906     x *= m_u;                   // put back u & v scale 
907     y *= m_v;
908     if (x * x + (y-m_v) * (y-m_v) > m_u * m_u + m_v * m_v)
909       return (false);           // clip against circle, r = sqrt(@)
910     else
911       return (true);
912     break;
913   case PELEM_SECTOR:
914       if (x > 1. || x < -1. || y > 1.)   // extent 
915       return (false);
916       if (y > 1. - x || y > 1. + x)      // triangle    
917           return (false);                      // clip against triangle 
918       x *= m_u;                // circle: put back u & v scale 
919     y *= m_v;
920     if (x * x + (y-m_v) * (y-m_v) > m_u * m_u + m_v * m_v)
921         return (false);                // clip against circle 
922     else
923       return (true);
924   break;
925   default:
926     sys_error (ERR_WARNING, "Illegal pelem type in pelem_is_point_inside()");
927     break;
928   }
929
930   return (false);
931 }
932
933