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