home *** CD-ROM | disk | FTP | other *** search
/ Borland Programmer's Resource / Borland_Programmers_Resource_CD_1995.iso / code / graphics / rtnews / rtnv5n3 < prev   
Encoding:
Internet Message Format  |  1995-05-19  |  39.1 KB

  1. From nucsrl!news.acns.nwu.edu!zaphod.mps.ohio-state.edu!cis.ohio-state.edu!rutgers!psinntp!psinntp!eye!erich Mon Sep  7 19:44:41 CDT 1992
  2. Article: 13391 of comp.graphics
  3. Path: nucsrl!news.acns.nwu.edu!zaphod.mps.ohio-state.edu!cis.ohio-state.edu!rutgers!psinntp!psinntp!eye!erich
  4. From: erich@eye.com (Eric Haines)
  5. Newsgroups: comp.graphics
  6. Subject: Ray Tracing News, Volume 5, Number 3
  7. Summary: point in polygon revisited
  8. Message-ID: <1992Sep2.101609.9105@eye.com>
  9. Date: 2 Sep 92 14:16:09 GMT
  10. Sender: erich@eye.com (Eric Haines)
  11. Organization: 3D/EYE, Inc.  Ithaca, NY
  12. Lines: 1000
  13.  
  14.  
  15.  _ __                 ______                         _ __
  16. ' )  )                  /                           ' )  )
  17.  /--' __.  __  ,     --/ __  __.  _. o ____  _,      /  / _  , , , _
  18. /  \_(_/|_/ (_/_    (_/ / (_(_/|_(__<_/ / <_(_)_    /  (_</_(_(_/_/_)_
  19.              /                               /|
  20.             '                               |/
  21.  
  22.             "Light Makes Right"
  23.  
  24.              September 2, 1992
  25.             Volume 5, Number 3
  26.  
  27. Compiled by Eric Haines, 3D/Eye Inc, 2359 Triphammer Rd, Ithaca, NY 14850
  28.     erich@eye.com
  29. All contents are copyright (c) 1992 by the individual authors
  30. Archive locations: anonymous FTP at princeton.edu (128.112.128.1)
  31.     /pub/Graphics/RTNews, wuarchive.wustl.edu:/graphics/graphics/RTNews,
  32.     and many others.
  33. UUCP archive access: write Kory Hamzeh (quad.com!avatar!kory) for info.
  34.  
  35. Contents:
  36.     Introduction
  37.     Intersection Between a Line and a Polygon (UNDECIDABLE??), by Dave Baraff,
  38.     Tom Duff
  39.     Fastest Point in Polygon Test, by Aladdin Nassar, Philip Walden, Eric
  40.     Haines, Tom Dickens, Ron Capelli, Sundar Narasimhan, Christopher Jam,
  41.     and (last but not least) Stuart MacMartin
  42.     Polygon Intersection via Barycentric Coordinates, by Peter Shirley
  43.     Many-Sided Polygon Intersection, by Eric Haines, Benjamin Zhu
  44.     Code for Point in Polygon Intersectors, by Eric Haines
  45.  
  46. -------------------------------------------------------------------------------
  47.  
  48. Introduction
  49.  
  50. This special issue is dedicated to everyone's (well, at least my) favorite
  51. computer graphics FAQ:  how do you find if a given point is inside a polygon?
  52. John Griegg's FAQ posting points at _An Introduction to Ray Tracing_, edited
  53. by Andrew Glassner.  This issue speeds up that algorithm (count the crossings
  54. of a test ray), and hopefully lays to rest the idea of using the "sum the
  55. angles" algorithm.  Plus there's a little discussion of what to do for special
  56. cases such as triangles and complex polygons, and code for four different ways
  57. to do this test at the end of the issue.
  58.  
  59. -------------------------------------------------------------------------------
  60.  
  61. [To begin this issue, here is one of the better pieces of obfuscatory writing
  62. in the field of computer graphics.  Reprinted from RTNews8 - EAH]
  63.  
  64.  
  65. Intersection Between a Line and a Polygon (UNDECIDABLE??),
  66.     by Dave Baraff, Tom Duff
  67.  
  68.     From: deb@charisma.graphics.cornell.edu
  69.     Newsgroups: comp.graphics
  70.     Keywords: P, NP, Jordan curve separation, Ursyhon Metrization Theorem
  71.     Organization: Program of Computer Graphics
  72.  
  73. In article [...] ncsmith@ndsuvax.UUCP (Timothy Lyle Smith) writes:
  74. >
  75. >  I need to find a formula/algorithm to determine if a line intersects
  76. >  a polygon.  I would prefer a method that would do this in as little
  77. >  time as possible.  I need this for use in a forward raytracing
  78. >  program.
  79.  
  80. I think that this is a very difficult problem.  To start with, lines and
  81. polygons are semi-algebraic sets which both contain uncountable number of
  82. points.  Here are a few off-the-cuff ideas.
  83.  
  84. First, we need to check if the line and the polygon are separated.  Now, the
  85. Jordan curve separation theorem says that the polygon divides the plane into
  86. exactly two open (and thus non-compact) regions.  Thus, the line lies
  87. completely inside the polygon, the line lies completely outside the polygon,
  88. or possibly (but this will rarely happen) the line intersects the polyon.
  89.  
  90. Now, the phrasing of this question says "if a line intersects a polygon", so
  91. this is a decision problem.  One possibility (the decision model approach) is
  92. to reduce the question to some other (well known) problem Q, and then try to
  93. solve Q.  An answer to Q gives an answer to the original decision problem.
  94.  
  95. In recent years, many geometric problems have been successfully modeled in a
  96. new language called PostScript.  (See "PostScript Language", by Adobe Systems
  97. Incorporated, ISBN # 0-201-10179-3, co. 1985).
  98.  
  99. So, given a line L and a polygon P, we can write a PostScript program that
  100. draws the line L and the polygon P, and then "outputs" the answer.  By
  101. "output", we mean the program executes a command called "showpage", which
  102. actually prints a page of paper containing the line and the polygon.  A quick
  103. examination of the paper provides an answer to the reduced problem Q, and thus
  104. the original problem.
  105.  
  106. There are two small problems with this approach.
  107.  
  108.     (1) There is an infinite number of ways to encode L and P into the
  109.     reduced problem Q.  So, we will be forced to invoke the Axiom of
  110.     Choice (or equivalently, Zorn's Lemma).  But the use of the Axiom of
  111.     Choice is not regarded in a very serious light these days.
  112.  
  113.     (2) More importantly, the question arises as to whether or not the
  114.     PostScript program Q will actually output a piece of paper; or in
  115.     other words, will it halt?
  116.  
  117.     Now, PostScript is expressive enough to encode everything that a
  118.     Turing Machine might do; thus the halting problem (for PostScript) is
  119.     undecidable.  It is quite possible that the original problem will turn
  120.     out to be undecidable.
  121.  
  122.  
  123. I won't even begin to go into other difficulties, such as aliasing, finite
  124. precision and running out of ink, paper or both.
  125.  
  126. A couple of references might be:
  127.  
  128. 1. Principia Mathematica.  Newton, I.  Cambridge University Press, Cambridge,
  129.    England.  (Sorry, I don't have an ISBN# for this).
  130.  
  131. 2. An Introduction to Automata Theory, Languages, and Computation.  Hopcroft, J
  132.   and Ulman, J.
  133.  
  134. 3. The C Programming Language. Kernighan, B and Ritchie, D.
  135.  
  136. 4. A Tale of Two Cities. Dickens, C.
  137.  
  138. --------
  139.  
  140. From: td@alice.UUCP (Tom Duff)
  141. Summary: Overkill.
  142. Organization: AT&T Bell Laboratories, Murray Hill NJ
  143.  
  144. The situation is not nearly as bleak as Baraff suggests (he should know
  145. better, he's hung around The Labs for long enough).  By the well known
  146. Dobbin-Dullman reduction (see J. Dullman & D. Dobbin, J. Comp. Obfusc.
  147. 37,ii:  pp. 33-947, lemma 17(a)) line-polygon intersection can be reduced to
  148. Hamiltonian Circuit, without(!) the use of Grobner bases, so LPI (to coin an
  149. acronym) is probably only NP-complete.  Besides, Turing-completeness will no
  150. longer be a problem once our Cray-3 is delivered, since it will be able to
  151. complete an infinite loop in 4 milliseconds (with scatter-gather.)
  152.  
  153. --------
  154.  
  155. From: deb@svax.cs.cornell.edu (David Baraff)
  156.  
  157. Well, sure it's no worse than NP-complete, but that's ONLY if you restrict
  158. yourself to the case where the line satisfies a Lipschitz condition on its
  159. second derivative.  (I think there's an '89 SIGGRAPH paper from Caltech that
  160. deals with this).
  161.  
  162. -------------------------------------------------------------------------------
  163.  
  164. Fastest Point in Polygon Test, by Aladdin Nassar, Philip Walden, Eric Haines,
  165.     Tom Dickens, Ron Capelli, Sundar Narasimhan, Christopher Jam, and
  166.     (last but not least) Stuart MacMartin
  167.  
  168.  
  169. Aladdin Nassar asked a variant on the classic question:
  170.  
  171. What is the MOST EFFICIENT way to find if a point lies within a SIMPLE
  172. polygon given a set of vertices (in no particular order) and the point
  173. coordinate ?   Are there anonymous ftp sites with such canned functions
  174. instead of re-inventing the wheel.  Excuse me if that is a trivial question.
  175.  
  176. ----
  177.  
  178. Philip Walden (pwalden@hpcc01.corp.hp.com) replies:
  179.  
  180. Another alternative to using a test ray is to sum the arc angles from
  181. the vertices to the test point. If the sum is 2pi, the point is inside,
  182. if 0 it's outside. i.e.
  183.  
  184.     give a polygon with a set of vertices v[1:n] an test point p
  185.  
  186.     if (SUM i=1 to n (arcangle(v[i]->p->v[i+1])) > pi
  187.     then p is inside
  188.     else it's outside
  189.  
  190. ----
  191.  
  192. Eric Haines replies:
  193.  
  194. This method turns out to be exceedingly slow, about an order of magnitude
  195. slower than the "shoot a ray and count crossings" method.  The problem is that
  196. the "arcangle" routine takes awhile:  you need to normalize your vectors, you
  197. need to compute the dot product (for the angle) and cross product (for the
  198. sign of the angle), and you need the arccosine of the dot product for the
  199. angle itself.  This is done for every vertex of the polygon.  All of this adds
  200. up!
  201.  
  202. In fact, I wrote a program to test the two algorithms head-to-head when I was
  203. deciding which to use:  code attached (for a switch!).  The test program makes
  204. polygons from 3 to 7 (though you can change this) and random scatters the
  205. vertices from [0-1).  It then tests each of these polygons with a series of
  206. random points from [0-1).
  207.  
  208. I won't claim that either implementation of the angle summation or segment
  209. crossing routines below are optimal (though I do try to share intermediate
  210. results between vertices).  But I don't care how much you tune the angle
  211. summation algorithm:  it's still going to be slower than crossing counting.
  212. Please do tell me of any hacks you make to get either algorithm faster,
  213. anyway.
  214.  
  215. Code's at the end of this issue; you should mess with *_TEST_TIMES however you
  216. see fit.  I found you could set them pretty low, but I felt better when they
  217. were relatively high (i.e. the test times were greater than the granularity
  218. of the "time" command).  The crossing counting inside/outside test is the one
  219. I wrote up in _An Introduction to Ray Tracing_, edited by Andrew Glassner,
  220. Academic Press, plus a trick or two not in the book.
  221.  
  222. I should also mention that the tests below assuming that an even winding
  223. number means that the point is outside, as this is how the Jordan Curve test
  224. is used.  Think of the winding number as the number of loops around a point.
  225. As an example, think of a star shape:  the interior pentagon is considered
  226. "outside" since points in it cross two lines.  You can modify the tests as
  227. shown in the comments if you want to test for just a non-zero winding number
  228. (i.e. the star is fully filled).
  229.  
  230. Timings are shown after the next comment.
  231.  
  232. ----
  233.  
  234. Tom Dickens notes in a related article:
  235.  
  236. Additional logic [in the barycentric test] can be added to avoid checking
  237. triangles which are located in a region which has already been determined to
  238. be beyond of a side of a previous triangle which returned a negative check.
  239.  
  240. [I don't know if such an enhancement is possible (one triangle's outside is
  241. another's inside) if the polygon is not convex, but mention it here for
  242. interest's sake; it is certainly not incorporated in my code.  - EAH]
  243.  
  244. ----
  245.  
  246. comments from Ron Capelli (capelli@vnet.ibm.com):
  247.  
  248. >the "arcangle" routine takes awhile:  you need to normalize your vectors, you
  249. >need to compute the dot product (for the angle) and cross product (for the
  250. >sign of the angle), and you need the arccosine of the dot product for the
  251. >angle itself.  This is done for every vertex of the polygon.
  252.  
  253. See "Fast Approximation to the Arctangent" in Graphics Gems II (p.389).  The
  254. maximum error of this approximation allows polygons with up to about 40
  255. vertexes to be handled safely.
  256.  
  257. No need to normalize, take dot products, or cross products either.  From the
  258. vector components (dx, dy) from a test point to a polygon vertex, get an angle
  259. using arctan (or the fast approximation, in which case do not scale to radians
  260. or degrees; use the angle value in the range 0 to 8).  Calculate the signed
  261. angle between two successive vertexes by subtracting the angles for each
  262. vertex.  Add up all the signed angle differences, and compare to the mid-range
  263. value.
  264.  
  265. The case of a test point coincident with a polygon vertex must be explicitly
  266. checked, as the arctangent for a zero-length vector is undefined.  Another
  267. fine point is that angle differences must be wrapped in the range -180 to +180
  268. degrees.
  269.  
  270. As fond as I am :-) of this method, I still won't argue that the "count ray
  271. crossings" method is not better.  For a polygon with N edges, an optimized
  272. "count ray crossings" algorithm requires at most one multiply, one divide, and
  273. about a half-dozen add/subtract/compare operations per edge.  The "add angle
  274. differences" algorithm using the fast approximation to the arctangent requires
  275. only one divide but more than twice as many add/subtract/compare operations
  276. per edge...
  277.  
  278. ----
  279.  
  280. Sundar Narasimhan (sundar@fiber-one.ai.mit.edu) comments on Ron's post:
  281.  
  282. I think it is somewhat misleading to count worst case operations / edge and
  283. then multiply it blindly by N esp.  since the "count ray crossings" algorithm
  284. can be optimized to consider only the subset of N edges that actually have a
  285. chance of intersecting the fired ray, whereas I haven't seen any such
  286. pre-filtering done to the add angle difference algorithm.
  287.  
  288. ----
  289.  
  290. Christopher Jam (phillips@swanee.ee.uwa.oz.au) writes:
  291.  
  292. For the "count ray crossings" method, if your processor has no multiply or
  293. divide instructions, the multiply and divide may be replaced by a binary
  294. search for the point on the edge with the same y coordinate as the point being
  295. tested.  Alternatively, if you are going to draw the polygon at some stage,
  296. generate a list of points on the line for plotting, and keep these in a table
  297. to completely remove any requirements for multiplies, divides or searches.
  298. Just look up a point on the same line ;)
  299.  
  300. ----
  301.  
  302. Stuart MacMartin (sjm@bcrki65.bnr.ca) comments:
  303.  
  304. I know the purpose of your code was for a simple comparison of the two
  305. algorithms, but for production you might want to write optimal code.
  306.  
  307. The loop overhead is actually quite expensive, as I found out when I optimized
  308. someone else's implementation of this algorithm.  Most of the time is spent
  309. looking for the next y that is on/below the ray or the next y that is above
  310. the ray.  You should be able to get at lease a factor of 2 improvement by
  311. optimizing those two loops.  Call a subroutine if necessary for the deleted
  312. stuff.  (Note that subroutines can be MORE efficient because the compiler may
  313. make a better use of registers for the time-consuming part of the loop.)  Use
  314. pointers to the y rather than to the x to avoid the extra adding, and don't
  315. keep track of so many variables in the loop.
  316.  
  317. Finally, is it necessary to use doubles?  With appropriate units, will long
  318. suffice?  Just be careful if you make this switch:  if you have to have
  319. doubles in some places in your code, watch out for conversions from long to
  320. double and back.  On some platforms (definitely Apollo; I don't know about
  321. others) such casts take so long that they totally swamp anything else that is
  322. inefficient in a loop.
  323.  
  324. My code for the loop:
  325.  
  326.     stop = vertices + (numVertices << 1);
  327.  
  328.     for(y = vertices[1], p = vertices+3;  p < stop;  y = *p,p+=2) {
  329.     /* Skip all lines above */
  330.     if      (y > ay) while ((p < stop) && (*p > ay)) p += 2;
  331.     /* Skip all lines below */
  332.     else if (y < ay) while ((p < stop) && (*p < ay)) p += 2;
  333.         /* NOTE! Don't skip horizontal edges at ay! */
  334.     if (p >= stop) break;
  335.  
  336. The routine requires that the first point is duplicated as the last.
  337.  
  338. ----
  339.  
  340. Final (for now) comments, by Eric Haines:
  341.  
  342. Other people noted the barycentric test as being a way to do inside/outside
  343. testing.  The barycentric test is included below in Peter Shirley's article,
  344. and is also written up on page 390-393 of Graphics Gems, Didier Badouel's
  345. article.  You can do better than figuring out all the intermediate differences
  346. (as shown in Badouel's article), instead computing them as needed.  Also, my
  347. code worries about zero area triangles just to be safe, so it could be a bit
  348. faster without these sanity checks.
  349.  
  350. Badouel points out that triangle testing works for convex polygons:  you
  351. simply test all of the triangles, and any intersection ends the test.  Most
  352. people assume that concave triangles must be intersected using a different
  353. test.  Not so!  As Berlin pointed out (Vol 11, SIGGRAPH '85 course notes -
  354. sorry for the obscure reference!), you can test a concave polygon by checking
  355. all its triangles generated from one vertex.  If the number of triangles hit
  356. is odd, the point is inside the (potentially concave) polygon - try it out, it
  357. actually works!  You do have to test all triangles, however; if you knew the
  358. polygon was convex you can stop on the first intersection.  Also, the
  359. barycentric coordinates become somewhat meaningless, since more than one
  360. triangle can be found to overlap your test point.
  361.  
  362.  
  363. So, included in the new code (which is at the end of this issue) are two
  364. flavors of the crossings (segment) test, one which is fairly fast and
  365. readable, the other is "macmartinized" by me and runs a bit faster still.
  366. The barycentric polygon intersector is also included, and it works for all
  367. polygons (concave, self-intersecting, etc).
  368.  
  369. Random polygon testing:
  370.  
  371.              number (or range) of vertices
  372.             3        4        5        3-7        20        100
  373.  
  374. angle           57.21   69.81   86.44   82.98  303.33 1435.78
  375. barycentric        1.80    3.44    5.29    4.90   30.78  164.38
  376. crossings        2.17    2.76    3.32    3.24   12.51   60.13
  377. macmartin        1.86    2.35    2.87    2.64   11.04   52.27
  378.  
  379. inside %        6.00   12.00   13.78    9.33   26.89   41.22
  380.  
  381. Times are in microseconds per intersection test, on an HP 720 workstation.
  382. The "for" loop for repeating each test is counted into these test times
  383. (basically, I repeat each polygon/point test a number of times so that there's
  384. some reasonable amount of time to count) - not counting it just means the
  385. "crossings" tests is all that much faster.  Basically, the macmartinized
  386. crossing test wins on my machine; your mileage may vary.
  387.  
  388. Note that the barycentric intersector could be faster if the polygons are
  389. known to be convex, since then a quick out could be taken (i.e. the first hit
  390. ends testing).  I won't swear at all for the completeness of the barycentric
  391. code:  I suspect you can get into roundoff error problems for intersection
  392. points which lay exactly on some internal, invisible triangle testing edge
  393. (rare, but possible).
  394.  
  395. There are also a few hacks I haven't done on the barycentric intersector:  you
  396. could make the set of if statements into two big if statements, the variable
  397. "v0" is not all that useful, etc.  Also, if the polygon is a triangle the test
  398. could be made a special case and the "for" loop and other baggage could be
  399. eliminated (this I tried, and it resulted in about a 20% reduction in run
  400. time).  However, the code presented is at least readable, and the general
  401. behavior is the same:  this intersector gets more expensive than the crossing
  402. methods as the number of polygon vertices rises.
  403.  
  404. Looking over the branch flow analysis, I find that my test case polygons
  405. (randomly generated points) cause a lot of algebraic tests to occur when using
  406. the crossing algorithms (i.e.  the exact x intersection point has to be
  407. computed when a polygon edge goes from one quadrant to its diagonal opposite).
  408. For real polygons, this case is much less prevalent since vertices tend to be
  409. close to each other, so the polygons I've generated are more pathological than
  410. normally encountered.  For example, if the polygons generated are regular
  411. polygons inscribed in a circle of radius 1.0 and given a random rotation about
  412. the origin, the timings are
  413.  
  414. Regular polygon testing:
  415.  
  416.              number (or range) of vertices
  417.             3        4        5        3-7        20        100
  418.  
  419. angle           54.20   70.80   85.14   87.83  314.53 1522.00
  420. barycentric        2.11    3.98    5.48    5.64   27.63  144.27
  421. crossings        2.50    3.09    3.30    3.42    9.46   42.71
  422. macmartin        2.32    2.81    2.91    2.92    6.29   23.91
  423.  
  424. inside %       33.22   51.00   60.22   55.22   77.44   80.22
  425.  
  426. I'm not sure why there's any noticeable difference in the "angle summation"
  427. tests, since this test should be the same for any test point (I suspect it's
  428. just the "times()" routine's granularity).  The barycentric times change a
  429. little for better and worse, probably due to times() and to different polygon
  430. vs. point tests.  The two crossings test noticeably improve for large polygons
  431. (29% and 54% savings, respectively) - this is due to less "difficult" edges,
  432. and for the macmartin test there are now longer series of edges fully above or
  433. fully below the test point.  These tests show off the real improvement of the
  434. macmartin algorithm when testing many sided polygons.
  435.  
  436. The near-final word is that the crossings tests seems to be the most efficient
  437. overall, the angle test should generally be avoided like the plague, and the
  438. barycentric test is good for the special case of triangles (and you also
  439. get the vertex interpolant weights).  Just to add to the confusion, I talk
  440. about intersecting complex polygons in an article below; if you're using a lot
  441. of these then another intersection algorithm might be a better route to go.
  442.  
  443. -------------------------------------------------------------------------------
  444.  
  445. Polygon Intersection via Barycentric Coordinates, by Peter Shirley
  446.     (shirley@iuvax.cs.indiana.edu)
  447.  
  448. One good way to do ray triangle intersection is to use barycentric
  449. coordinates.  If the triangle has vertices p0, p1, p2, then any point in the
  450. plane containing the triangle can be represented as
  451.  
  452.     p = a*p0 + b*p2 + g*p3
  453.  
  454. and the constraint a + b + g = 1 will also hold.  If you want to interpolate
  455. colors or normals across the triangle, you can use a similar formula.  A
  456. little messing around will convince you that for points inside the triangle,
  457. a, b, and g are all positive, and outside the triangle, at least one is
  458. negative.  We can take this info, and get rid of a:
  459.  
  460.     p = p0 + b*(p1 - p0) + g*(p2-p0)
  461.  
  462. The point p is inside if b and g are positive, and (b+g) < 1.
  463.  
  464. A point on our ray can be represented as p' = o + t*v, where o is the point of
  465. origin on the ray, and v is the direction of propagation.  Plugging this into
  466. the triangle formula, we can find whether any point on the ray is also a point
  467. on the plane:
  468.  
  469.     o + t*v = p0 + b*(p1 - p0) + g*(p2-p0)
  470.  
  471. Note that this is really 3 linear equations (one for x, y and z).  You can
  472. rewrite this as a 3 by 3 linear system and solve for (t, b, g) and there is a
  473. hit if and only if:
  474.  
  475.     t > 0
  476.     b > 0
  477.     g > 0
  478.     b+g < 1
  479.  
  480. Alternatively, you can first find the equation of the plane containing the
  481. triangle and find t.  This will give you an explicit point h on the plane.
  482. You now have:
  483.  
  484.     h = p0 + b*(p1 - p0) + g*(p2-p0)
  485.  
  486. Now you have 3 equations and 2 unknowns.  Choosing any two of the equations is
  487. equivalent to projecting the problem onto one of the cartesian planes.  Watch
  488. out if the triangle is in one of the planes, because the projection might be a
  489. line segment.  You can check the surface normal to see if it is one of those
  490. cases (I just use the dimensions associated with the smallest magnitude
  491. components of the normal).
  492.  
  493. Note-- none of this is new.  GG II and the ray tracing book have other ways to
  494. do it.  Also, if your scenes are large, you are probably better off optimizing
  495. your spatial partitioning code (the part which takes longer for bigger
  496. scenes).
  497.  
  498. [For more info, see Didier Badouel's article in "Graphics Gems", p. 390-393]
  499.  
  500. -------------------------------------------------------------------------------
  501.  
  502. Many-Sided Polygon Intersection, by Eric Haines, Benjamin Zhu
  503.  
  504.  
  505. Jon Bennett (jb7m+@andrew.cmu.edu) writes:
  506.  
  507. >For a project i was working on i needed a very fast 2-D point-in-polygon
  508. >routine for a monte-carlo simulation, and came up with a variation of the
  509. >standard jordan curve theorem algorithm which ran approximately on the
  510. >order of O(n/20) when n > ~100 (for "mostly" round-ish polygons), instead
  511. >of O(n).  What I can't find, and no one here seems to know, is for large
  512. >polygons what is the best 2-D algorithm.  Everything they've heard of runs
  513. >in O(n) (I know that n and n/20 are the same "order" but the you know what
  514. >I mean). I'd like to know if there is something faster.
  515.  
  516.  
  517. You might check Preparata & Shamos's _Computational Geometry_ book, I believe
  518. they talk about faster algorithms.  Unfortunately, much of the stuff in CG
  519. tends to be things like O(K * log n), where K is something pretty large.
  520.  
  521. A simple way to test polygons with a large number of edges in O(n/K) time is
  522. to sort the edges into buckets, then find out which bucket the test point
  523. falls into.  Then you do the usual ray test, but only against those edges in
  524. the bucket.
  525.  
  526. For example, you could take a hundred edge polygon and find the Y extent in the
  527. polygon's plane.  Split this extent into, say, 20 buckets (or whatever number
  528. you like, more ==> more efficient, but also more memory and preprocessing).
  529. Now take each edge and note which buckets it's in.  As an added speed-up, sort
  530. the edges by their leftmost X values in that bucket.
  531.  
  532. Now testing can begin.  When you test a point, use the Y coordinate to find
  533. which bucket to check.  Now test each edge by the normal Jordan test against
  534. the point.  You only need to test edges to the left of the point (i.e. you are
  535. using a test ray in the -X direction), so as soon as you reach an edge whose
  536. leftmost X is greater than the point's X, you can stop testing.
  537.  
  538. The bucket sort immediately gets rid of a lot of edges, and the X test means
  539. often not having to test all edges in the bucket (it's optional icing).
  540.  
  541. If you're really into using memory and like preprocessing, you could use a
  542. grid structure to place buckets on the polygon.  Each grid cell is inside,
  543. outside, or indeterminate.  There are some tricks, but I leave these as an
  544. exercise for the reader...  Anyway, this method can be very fast, since much
  545. of the polygon's area is classified as in or out and much of the time no edges
  546. have to be tested at all.  The only limit is the grid cell resolution.  As the
  547. resolution rises the actual testing approaches constant time ( O(1)!).
  548. There's more preprocessing involved, but if you're making a lot of tests then
  549. this is worth doing.
  550.  
  551. ----
  552.  
  553. Benjamin Zhu (zhu@graphack.asd.sgi.com) comments on a similar question:
  554.  
  555. If your polygon is convex, (more generally, your polygon is star-shaped,) you
  556. can pre-process the polygon into triangle strips by connecting any point in
  557. the kernel of the polygon with each vertex of the polygon.  This takes you
  558. O(n) pre-processing time.  After that, for each point, you do a binary search
  559. in polar coordinates to locate the potential triangle where the point might
  560. lie.  Then you can determine if the point lies within this triangle, which is
  561. trivial.  See Preparata and Shamos' "Computational Geometry" for more details.
  562. Obviously, this algorithm will give you O(log(n)) time per point.  So you
  563. might consider this one if you need to solve the point-inclusion problem many
  564. times.
  565.  
  566. -------------------------------------------------------------------------------
  567.  
  568. Code for Point in Polygon Intersectors, by Eric Haines
  569.  
  570. Here it is, code for the angle test, the barycentric test, and the two
  571. crossings tests, with a main program to test their speeds.  You may need to
  572. use something other than srand()/drand48() for your random number generator,
  573. and the times() command for timing.  You'll also want to change the
  574. *_TEST_TIMES constants if you're using something slower than an HP 720
  575. workstation.  Feel free to complain about the slowness of any of the code -
  576. I'm always interested in new hacks.
  577.  
  578.  
  579. /* Point in polygon inside/outside tester.  Angle summation, barycentric
  580.  * coordinates, and ray along x-axis (crossings testing) compared.
  581.  *
  582.  * copyright 1992 by Eric Haines, 3D/Eye Inc, erich@eye.com
  583.  */
  584.  
  585. #include <math.h>
  586. #include <sys/types.h>
  587. #include <sys/param.h>
  588. #include <sys/times.h>
  589.  
  590. #define    X    0
  591. #define    Y    1
  592.  
  593. double    drand48() ;
  594.  
  595. double    AngleTimeTotal ;
  596. double    BarycentricTimeTotal ;
  597. double    CrossingsTimeTotal ;
  598. double    MacmartinTimeTotal ;
  599.  
  600. /* minimum & maximum number of polygon vertices to generate */
  601. #define    MIN_VERTS    3
  602. #define    MAX_VERTS    7
  603.  
  604. /* number of different polygons to try */
  605. #define    TEST_POLYGONS    30
  606.  
  607. /* number of different intersection points to try */
  608. #define    TEST_POINTS    30
  609.  
  610. /* number of times to try a single point vs. a polygon */
  611. /* this should be > 1 / ( HZ * approx. single test time in seconds ) */
  612. #define    ANGLE_TEST_TIMES    1000
  613. #define    BARYCENTRIC_TEST_TIMES    10000
  614. #define    CROSSINGS_TEST_TIMES    10000
  615. #define    MACMARTIN_TEST_TIMES    10000
  616.  
  617. main(argc,argv)
  618. int argc;  char *argv[];
  619. {
  620. int    i, j, numverts, inside_tot ;
  621. int    angle_flag, barycentric_flag, crossings_flag, macmartin_flag ;
  622. double    pgon[MAX_VERTS][2] ;
  623. double    point[2] ;
  624.  
  625.     srand( 12345 ) ;
  626.  
  627.     AngleTimeTotal = 0.0 ;
  628.     BarycentricTimeTotal = 0.0 ;
  629.     CrossingsTimeTotal = 0.0 ;
  630.     MacmartinTimeTotal = 0.0 ;
  631.     inside_tot = 0 ;
  632.  
  633.     for ( i = 0 ; i < TEST_POLYGONS ; i++ ) {
  634.  
  635. #ifdef CENTERED_SQUARE
  636.     /* for debugging purposes, test against a square */
  637.     numverts = 4 ;
  638.     pgon[0][X] = 0.2 ;
  639.     pgon[0][Y] = 0.2 ;
  640.     pgon[1][X] = 0.8 ;
  641.     pgon[1][Y] = 0.2 ;
  642.     pgon[2][X] = 0.8 ;
  643.     pgon[2][Y] = 0.8 ;
  644.     pgon[3][X] = 0.2 ;
  645.     pgon[3][Y] = 0.8 ;
  646. #else
  647.     /* make an arbitrary polygon fitting 0-1 range in x and y */
  648.     numverts = MIN_VERTS +
  649.         (int)(drand48() * (double)(MAX_VERTS-MIN_VERTS+1)) ;
  650.     for ( j = 0 ; j < numverts ; j++ ) {
  651.         pgon[j][X] = drand48() ;
  652.         pgon[j][Y] = drand48() ;
  653.     }
  654. #endif
  655.  
  656.     /* now try # of points against it */
  657.     for ( j = 0 ; j < TEST_POINTS ; j++ ) {
  658.         point[X] = drand48() ;
  659.         point[Y] = drand48() ;
  660.         angle_flag = angletest( pgon, numverts, point ) ;
  661.         barycentric_flag = barycentrictest( pgon, numverts, point ) ;
  662.         crossings_flag = crossingstest( pgon, numverts, point ) ;
  663.         macmartin_flag = macmartintest( pgon, numverts, point ) ;
  664.  
  665.         /* reality check */
  666.         if ( angle_flag != crossings_flag ) {
  667.         printf( "angle test says %s, crossings test says %s\n",
  668.             angle_flag ? "INSIDE" : "OUTSIDE",
  669.             crossings_flag ? "INSIDE" : "OUTSIDE" ) ;
  670.         printf( "point %g %g\n", (float)point[X], (float)point[Y] ) ;
  671.         printf( "polygon:\n" ) ;
  672.         for ( j = 0 ; j < numverts ; j++ ) {
  673.             printf( "  %g %g\n", (float)pgon[j][X], (float)pgon[j][Y]);
  674.         }
  675.         }
  676.         if ( barycentric_flag != macmartin_flag ) {
  677.         printf( "barycentric test says %s, macmartin test says %s\n",
  678.             barycentric_flag ? "INSIDE" : "OUTSIDE",
  679.             macmartin_flag ? "INSIDE" : "OUTSIDE" ) ;
  680.         printf( "point %g %g\n", (float)point[X], (float)point[Y] ) ;
  681.         printf( "polygon:\n" ) ;
  682.         for ( j = 0 ; j < numverts ; j++ ) {
  683.             printf( "  %g %g\n", (float)pgon[j][X], (float)pgon[j][Y]);
  684.         }
  685.         }
  686.  
  687.         inside_tot += crossings_flag ;
  688.     }
  689.     }
  690.     printf( "angle test time: %g microseconds per test\n",
  691.     (float)( AngleTimeTotal/(double)(TEST_POINTS*TEST_POLYGONS) ) ) ;
  692.     printf( "barycentric test time: %g microseconds per test\n",
  693.     (float)( BarycentricTimeTotal/(double)(TEST_POINTS*TEST_POLYGONS) ) ) ;
  694.     printf( "crossings test time: %g microseconds per test\n",
  695.     (float)( CrossingsTimeTotal/(double)(TEST_POINTS*TEST_POLYGONS) ) ) ;
  696.     printf( "macmartin crossings test time: %g microseconds per test\n",
  697.     (float)( MacmartinTimeTotal/(double)(TEST_POINTS*TEST_POLYGONS) ) ) ;
  698.  
  699.     printf( "%g %% of all points were inside polygons\n",
  700.     (float)inside_tot * 100.0 / (float)(TEST_POINTS*TEST_POLYGONS) ) ;
  701. }
  702.  
  703. /* sum angles of vtxN - point - vtxN+1, check if in PI to 3*PI range */
  704. int
  705. angletest( pgon, numverts, point )
  706. double    pgon[MAX_VERTS][2] ;
  707. int    numverts ;
  708. double    point[2] ;
  709. {
  710. int    i, j, inside_flag ;
  711. struct  tms     timebuf ;
  712. long    timestart ;
  713. long    timestop ;
  714. double    *vtx0, *vtx1, angle, len, vec0[2], vec1[2] ;
  715.  
  716.     /* do the test a bunch of times to get a useful time reading */
  717.     timestart = times( &timebuf ) ;
  718.     for ( i = 0 ; i < ANGLE_TEST_TIMES ; i++ ) {
  719.     /* sum the angles and see if answer mod 2*PI > PI */
  720.     vtx0 = pgon[numverts-1] ;
  721.     vec0[X] = vtx0[X] - point[X] ;
  722.     vec0[Y] = vtx0[Y] - point[Y] ;
  723.     if ( (len = hypot( vec0[X], vec0[Y] )) <= 0.0 ) {
  724.         /* point and vertex coincide */
  725.         return( 1 ) ;
  726.     }
  727.     vec0[X] /= len ;
  728.     vec0[Y] /= len ;
  729.  
  730.     angle = 0.0 ;
  731.     for ( j = 0 ; j < numverts ; j++ ) {
  732.         vtx1 = pgon[j] ;
  733.         vec1[X] = vtx1[X] - point[X] ;
  734.         vec1[Y] = vtx1[Y] - point[Y] ;
  735.         if ( (len = hypot( vec1[X], vec1[Y] )) <= 0.0 ) {
  736.         /* point and vertex coincide */
  737.         return( 1 ) ;
  738.         }
  739.         vec1[X] /= len ;
  740.         vec1[Y] /= len ;
  741.  
  742.         /* check if vec1 is to "left" or "right" of vec0 */
  743.         if ( vec0[X] * vec1[Y] - vec1[X] * vec0[Y] >= 0.0 ) {
  744.         /* add angle due to dot product of vectors */
  745.         angle += acos( vec0[X] * vec1[X] + vec0[Y] * vec1[Y] ) ;
  746.         } else {
  747.         /* subtract angle due to dot product of vectors */
  748.         angle -= acos( vec0[X] * vec1[X] + vec0[Y] * vec1[Y] ) ;
  749.         }
  750.  
  751.         /* get to next point */
  752.         vtx0 = vtx1 ;
  753.         vec0[X] = vec1[X] ;
  754.         vec0[Y] = vec1[Y] ;
  755.     }
  756.     /* test if between PI and 3*PI, 5*PI and 7*PI, etc */
  757.     /* if we care about is winding number > 0, then just:
  758.            inside_flag = fabs(angle) > M_PI ;
  759.      */
  760.     inside_flag = fmod( fabs(angle) + M_PI, 4.0*M_PI ) > 2.0*M_PI ;
  761.     }
  762.     timestop = times( &timebuf ) ;
  763.     /* time in microseconds */
  764.     AngleTimeTotal += 1000000.0 * (double)(timestop - timestart) /
  765.     (double)(HZ * ANGLE_TEST_TIMES) ;
  766.  
  767.     return (inside_flag) ;
  768. }
  769.  
  770. /* barycentric, a la Gems I, with a little efficiency tuning */
  771. int
  772. barycentrictest( pgon, numverts, point )
  773. double    pgon[MAX_VERTS][2] ;
  774. int    numverts ;
  775. double    point[2] ;
  776. {
  777. int    i, tris_hit, inside_flag, p1, p2 ;
  778. struct  tms     timebuf ;
  779. long    timestart ;
  780. long    timestop ;
  781. double    tx, ty, u0, u1, u2, v0, v1, alpha, beta, denom ;
  782.  
  783.     /* do the test a bunch of times to get a useful time reading */
  784.     timestart = times( &timebuf ) ;
  785.     for ( i = 0 ; i < BARYCENTRIC_TEST_TIMES ; i++ ) {
  786.  
  787.     tx = point[X] ;
  788.     ty = point[Y] ;
  789.  
  790.     tris_hit = 0 ;
  791.  
  792.     for ( p1 = 1, p2 = 2 ; p2 < numverts ; p1++, p2++ ) {
  793.  
  794.         if ( ( u1 = pgon[0][X] - pgon[p2][X] ) == 0.0 ) {
  795.  
  796.         /* zero area test - optional */
  797.         if ( ( u2 = pgon[p1][X] - pgon[p2][X] ) == 0.0 ) {
  798.             goto NextTri;
  799.         }
  800.  
  801.         /* Compute intersection point */
  802.         if ( ( ( beta = ( tx - pgon[p2][X] ) / u2 ) < 0.0 ) ||
  803.                ( beta > 1.0 ) ) {
  804.  
  805.             goto NextTri;
  806.         }
  807.  
  808.         if ( ( v1 = pgon[0][Y] - pgon[p2][Y] ) == 0.0 ) {
  809.             goto NextTri;
  810.         }
  811.  
  812.         if ( ( alpha = ( ty - pgon[p2][Y] - beta *
  813.             ( pgon[p1][Y] - pgon[p2][Y] ) ) / v1 ) < 0.0 ) {
  814.             goto NextTri;
  815.         }
  816.  
  817.         } else {
  818.         if ( ( denom = ( pgon[p1][Y] - pgon[p2][Y] ) * u1 -
  819.             ( u2 = pgon[p1][X] - pgon[p2][X] ) *
  820.             ( v1 = pgon[0][Y] - pgon[p2][Y] ) ) == 0.0 ) {
  821.  
  822.             goto NextTri;
  823.         }
  824.  
  825.         /* Compute intersection point & subtract 0 vertex */
  826.         u0 = tx - pgon[p2][X] ;
  827.         v0 = ty - pgon[p2][Y] ;
  828.  
  829.         if ( ( ( ( beta = ( v0 * u1 - u0 * v1 ) / denom ) ) < 0.0 ) ||
  830.                ( beta > 1.0 ) ) {
  831.  
  832.             goto NextTri;
  833.         }
  834.         if ( ( alpha = ( u0 - beta * u2 ) / u1 ) < 0.0 ) {
  835.             goto NextTri;
  836.         }
  837.         }
  838.  
  839.         /* check gamma */
  840.         if ( alpha + beta <= 1.0 ) {
  841.         /* survived */
  842.         tris_hit++ ;
  843.         }
  844.  
  845.         NextTri: ;
  846.     }
  847.     inside_flag = tris_hit & 0x1 ;
  848.     }
  849.     timestop = times( &timebuf ) ;
  850.     /* time in microseconds */
  851.     BarycentricTimeTotal += 1000000.0 * (double)(timestop - timestart) /
  852.     (double)(HZ * BARYCENTRIC_TEST_TIMES) ;
  853.  
  854.     return (inside_flag) ;
  855. }
  856.  
  857. /* shoot a test ray along +X axis - slower version, less messy */
  858. int
  859. crossingstest( pgon, numverts, point )
  860. double    pgon[MAX_VERTS][2] ;
  861. int    numverts ;
  862. double    point[2] ;
  863. {
  864. int    i, j, inside_flag, xflag0 ;
  865. struct  tms     timebuf ;
  866. long    timestart ;
  867. long    timestop ;
  868. double    *vtx0, *vtx1, dv0 ;
  869. int    crossings, yflag0, yflag1 ;
  870.  
  871.     /* do the test a bunch of times to get a useful time reading */
  872.     timestart = times( &timebuf ) ;
  873.     for ( i = 0 ; i < CROSSINGS_TEST_TIMES ; i++ ) {
  874.  
  875.     vtx0 = pgon[numverts-1] ;
  876.     /* get test bit for above/below Y axis */
  877.     yflag0 = ( dv0 = vtx0[Y] - point[Y] ) >= 0.0 ;
  878.  
  879.     crossings = 0 ;
  880.     for ( j = 0 ; j < numverts ; j++ ) {
  881.         /* cleverness:  bobble between filling endpoints of edges, so
  882.          * that the previous edge's shared endpoint is maintained.
  883.          */
  884.         if ( j & 0x1 ) {
  885.         vtx0 = pgon[j] ;
  886.         yflag0 = ( dv0 = vtx0[Y] - point[Y] ) >= 0.0 ;
  887.         } else {
  888.         vtx1 = pgon[j] ;
  889.         yflag1 = ( vtx1[Y] >= point[Y] ) ;
  890.         }
  891.  
  892.         /* check if points not both above/below X axis - can't hit ray */
  893.         if ( yflag0 != yflag1 ) {
  894.         /* check if points on same side of Y axis */
  895.         if ( ( xflag0 = ( vtx0[X] >= point[X] ) ) ==
  896.              ( vtx1[X] >= point[X] ) ) {
  897.  
  898.             if ( xflag0 ) crossings++ ;
  899.         } else {
  900.             /* compute intersection of pgon segment with X ray, note
  901.              * if > point's X.
  902.              */
  903.             crossings += (vtx0[X] -
  904.             dv0*( vtx1[X]-vtx0[X])/(vtx1[Y]-vtx0[Y])) >= point[X] ;
  905.         }
  906.         }
  907.     }
  908.     /* test if crossings is odd */
  909.     /* if we care about is winding number > 0, then just:
  910.            inside_flag = crossings > 0 ;
  911.      */
  912.     inside_flag = crossings & 0x01 ;
  913.     }
  914.     timestop = times( &timebuf ) ;
  915.     /* time in microseconds */
  916.     CrossingsTimeTotal += 1000000.0 * (double)(timestop - timestart) /
  917.     (double)(HZ * CROSSINGS_TEST_TIMES) ;
  918.  
  919.     return (inside_flag) ;
  920. }
  921.  
  922. /* shoot a test ray along +X axis - macmartinized by me, a bit messier */
  923. int
  924. macmartintest( pgon, numverts, point )
  925. double    pgon[MAX_VERTS][2] ;
  926. int    numverts ;
  927. double    point[2] ;
  928. {
  929. int    i, inside_flag, xflag0 ;
  930. struct  tms     timebuf ;
  931. long    timestart ;
  932. long    timestop ;
  933. double    *p, *stop ;
  934. int    crossings ;
  935. double    tx, ty, y ;
  936.  
  937.     /* do the test a bunch of times to get a useful time reading */
  938.     timestart = times( &timebuf ) ;
  939.     for ( i = 0 ; i < MACMARTIN_TEST_TIMES ; i++ ) {
  940.  
  941.     crossings = 0 ;
  942.  
  943.     tx = point[X] ;
  944.     ty = point[Y] ;
  945.     y = pgon[numverts-1][Y] ;
  946.  
  947.     p = (double *)pgon + 1 ;
  948.     if ( ( y >= ty ) != ( *p >= ty ) ) {
  949.         /* x crossing */
  950.         if ( ( xflag0 = ( pgon[numverts-1][X] >= tx ) ) ==
  951.          ( *(double *)pgon >= tx ) ) {
  952.  
  953.         if ( xflag0 ) crossings++ ;
  954.         } else {
  955.         /* compute intersection of pgon segment with X ray, note
  956.          * if > point's X.
  957.          */
  958.         crossings += ( pgon[numverts-1][X] -
  959.         (y-ty)*( *(double *)pgon - pgon[numverts-1][X])/(*p-y)) >= tx ;
  960.         }
  961.     }
  962.  
  963.     stop = pgon[numverts] ;
  964.  
  965.     for ( y=*p,p += 2 ; p < stop ; y=*p,p+=2) {
  966.  
  967.         if ( y >= ty ) {
  968.         while ( (p < stop) && (*p >= ty) ) p+=2 ;
  969.         if ( p >= stop ) goto Exit ;
  970.         /* y crosses */
  971.         if ( ( xflag0 = ( *(p-3) >= tx ) ) ==
  972.              ( *(p-1) >= tx ) ) {
  973.  
  974.             if ( xflag0 ) crossings++ ;
  975.         } else {
  976.             /* compute intersection of pgon segment with X ray, note
  977.              * if > point's X.
  978.              */
  979.             crossings += ( *(p-3) -
  980.             (*(p-2)-ty)*( *(p-1)-*(p-3))/(*p-*(p-2))) >= tx ;
  981.         }
  982.         } else {
  983.         while ( (p < stop) && (*p < ty)) p+=2 ;
  984.         if ( p >= stop ) goto Exit ;
  985.         /* y crosses */
  986.         if ( ( xflag0 = ( *(p-3) >= tx ) ) ==
  987.              ( *(p-1) >= tx ) ) {
  988.  
  989.             if ( xflag0 ) crossings++ ;
  990.         } else {
  991.             /* compute intersection of pgon segment with X ray, note
  992.              * if > point's X.
  993.              */
  994.             crossings += ( *(p-3) -
  995.             (*(p-2)-ty)*( *(p-1)-*(p-3))/(*p-*(p-2))) >= tx ;
  996.         }
  997.         }
  998.     }
  999.  
  1000.     Exit:
  1001.     /* test if crossings is odd */
  1002.     /* if we care about is winding number > 0, then just:
  1003.            inside_flag = crossings > 0 ;
  1004.      */
  1005.     inside_flag = crossings & 0x01 ;
  1006.     }
  1007.     timestop = times( &timebuf ) ;
  1008.     /* time in microseconds */
  1009.     MacmartinTimeTotal += 1000000.0 * (double)(timestop - timestart) /
  1010.     (double)(HZ * MACMARTIN_TEST_TIMES) ;
  1011.  
  1012.     return (inside_flag) ;
  1013. }
  1014.  
  1015.  
  1016.