source: GTP/trunk/Lib/Vis/Preprocessing/src/Polygon3.cpp @ 863

Revision 863, 11.5 KB checked in by mattausch, 18 years ago (diff)

working on preprocessor integration
added iv stuff

Line 
1#include "Polygon3.h"
2#include "Mesh.h"
3#include "AxisAlignedBox3.h"
4#include "Ray.h"
5#include "Triangle3.h"
6
7
8namespace GtpVisibilityPreprocessor {
9
10
11Polygon3::Polygon3():
12mMaterial(NULL), mParent(NULL), mPiercingRays(0)
13{
14        // mostly there will be triangles
15        //mVertices.reserve(3);
16}
17
18Polygon3::Polygon3(const VertexContainer &vertices):
19mMaterial(NULL), mParent(NULL), mPiercingRays(0)
20{
21        mVertices.reserve(vertices.size());
22        mVertices = vertices;
23}
24
25
26Polygon3::Polygon3(MeshInstance *parent):
27mMaterial(NULL), mParent(parent), mPiercingRays(0)
28{}
29
30
31Polygon3::Polygon3(Face *face, Mesh *parentMesh):
32mMaterial(NULL), mParent(NULL), mPiercingRays(0)
33{       
34        mVertices.reserve(face->mVertexIndices.size());
35       
36        VertexIndexContainer::iterator it = face->mVertexIndices.begin();
37        for (; it != face->mVertexIndices.end();  ++it)
38        {
39                mVertices.push_back(parentMesh->mVertices[*it]);
40        }
41
42        mMaterial = parentMesh->mMaterial;
43}
44
45
46Plane3 Polygon3::GetSupportingPlane() const
47{
48        return Plane3(mVertices[0], mVertices[1], mVertices[2]);
49}
50
51
52Vector3 Polygon3::GetNormal() const
53{
54    return Normalize(CrossProd(mVertices[2] - mVertices[1],
55                                                           mVertices[0] - mVertices[1]));
56}
57
58void Polygon3::Split(const Plane3 &partition,
59                                         Polygon3 &front,
60                                         Polygon3 &back,
61                                         const float epsilon)
62{
63        Vector3 ptA = mVertices.back();
64       
65        int sideA = partition.Side(ptA, epsilon);
66       
67        VertexContainer::const_iterator it;
68       
69        Vector3 lastSplit;
70
71        bool foundSplit = false;
72
73        //-- find line - plane intersections
74        for (it = mVertices.begin(); it != mVertices.end(); ++ it)
75        {
76                Vector3 ptB = *it;
77                int sideB = partition.Side(ptB, epsilon);
78       
79                // vertices on different sides => split
80            if (sideB > 0)
81                {
82                        if (sideA < 0)
83                        {
84                                //-- plane - line intersection
85                                Vector3 splitPt = partition.FindIntersection(ptA, ptB);
86                       
87                                // test if split point not too close to previous split point
88                                if (!foundSplit || (!EpsilonEqualV3(splitPt, lastSplit, epsilon)))
89                                {
90                                        // add vertex to both polygons
91                                        front.mVertices.push_back(splitPt);
92                                        back.mVertices.push_back(splitPt);
93                                       
94                                        lastSplit = splitPt;
95                                        foundSplit = true;
96                                }
97                        }
98                        front.mVertices.push_back(ptB);
99                }
100                else if (sideB < 0)
101                {
102                        if (sideA > 0)
103                        {
104                                //-- plane - line intersection
105                                Vector3 splitPt = partition.FindIntersection(ptA, ptB);
106                                // test if split point not too close to other split point
107                                        // test if split point not too close to previous split point
108                                if (!foundSplit || (!EpsilonEqualV3(splitPt, lastSplit, epsilon)))
109                                {
110                                        // add vertex to both polygons
111                                        front.mVertices.push_back(splitPt);
112                                        back.mVertices.push_back(splitPt);
113
114                                        lastSplit = splitPt;
115                                        foundSplit = true;
116                                }       
117                        }
118                        back.mVertices.push_back(ptB);
119                }
120                else
121                {
122                        // vertex on plane => add vertex to both polygons
123                        front.mVertices.push_back(ptB);
124                        back.mVertices.push_back(ptB);
125                }
126       
127                ptA = ptB;
128                sideA = sideB;
129        }
130}
131
132
133float Polygon3::GetArea() const
134{
135        Vector3 v = CrossProd(mVertices.back(), mVertices.front());
136   
137    for (int i=0; i < mVertices.size() - 1; ++i)
138                v += CrossProd(mVertices[i], mVertices[i+1]);
139   
140    return 0.5f * fabs(DotProd(GetNormal(), v));
141}
142
143
144int Polygon3::Side(const Plane3 &plane,
145                                   const float epsilon) const
146{
147        int classification = ClassifyPlane(plane, epsilon);
148       
149        if (classification == BACK_SIDE)
150                return -1;
151        else if (classification == FRONT_SIDE)
152                return 1;
153        // plane splits polygon
154        return 0;
155}
156
157
158int Polygon3::ClassifyPlane(const Plane3 &plane,
159                                                        const float epsilon) const
160{
161        VertexContainer::const_iterator it, it_end = mVertices.end();
162
163        bool onFrontSide = false;
164        bool onBackSide = false;
165       
166        int count = 0;
167        // find possible line-plane intersections
168        for (it = mVertices.begin(); it != it_end; ++ it)
169        {
170                const int side = plane.Side(*it, epsilon);
171               
172                if (side > 0)
173                {
174                        onFrontSide = true;
175                }
176                else if (side < 0)
177                {
178                        onBackSide = true;
179                }
180
181                //TODO: check if split goes through vertex
182                if (onFrontSide && onBackSide) // split
183                {
184                        return SPLIT;
185                }
186                // 3 vertices enough to decide coincident
187                else if (((++ count) >= 3) && !onFrontSide && !onBackSide)
188                {   
189                        return COINCIDENT;
190                }
191        }
192
193        if (onBackSide)
194        {
195                return BACK_SIDE;
196        }
197        else if (onFrontSide)
198        {
199                return FRONT_SIDE;
200        }
201       
202        return COINCIDENT; // plane and polygon are coincident
203}
204
205
206Vector3
207Polygon3::Center() const
208{
209        int i;
210        Vector3 sum = mVertices[0];
211        for (i=1; i < mVertices.size(); i++)
212                sum += mVertices[i];
213       
214        return sum/(float)i;
215}
216
217
218void
219Polygon3::Scale(const float scale)
220{
221        int i;
222        Vector3 center = Center();
223        for (i=0; i < mVertices.size(); i++) {
224                mVertices[i] = center + scale*(mVertices[i] - center);
225        }
226}
227
228bool Polygon3::Valid(const float epsilon) const
229{
230        if (mVertices.size() < 3)
231                return false;
232
233        //TODO: remove for performance
234#if 0
235        if (1)
236        {
237                // check if area exceeds certain size
238                if (GetArea() < AREA_LIMIT)
239                {
240                        Debug << "area too small: " << GetArea() << endl;
241                        return false;
242                }
243        }
244       
245        if (1)
246        {
247                Vector3 vtx = mVertices.back();
248                VertexContainer::const_iterator it, it_end = mVertices.end();
249
250                for (it = mVertices.begin(); it != it_end; ++it)
251                {
252                        if (EpsilonEqualV3(vtx, *it, 0.0001))
253                        {
254                                //Debug << "Malformed vertices:\n" << *this << endl;
255                                return false;
256                        }
257                        vtx = *it;
258                }
259        }
260#endif
261
262        return true;
263}
264
265
266// int_lineseg returns 1 if the given line segment intersects a 2D
267// ray travelling in the positive X direction.  This is used in the
268// Jordan curve computation for polygon intersection.
269inline int
270int_lineseg(float px,
271            float py,
272            float u1,
273            float v1,
274            float u2,
275            float v2)
276{
277        float t;
278        float ydiff;
279
280        u1 -= px; u2 -= px;       // translate line
281        v1 -= py; v2 -= py;
282
283        if ((v1 > 0 && v2 > 0) ||
284                (v1 < 0 && v2 < 0) ||
285                (u1 < 0 && u2 < 0))
286        return 0;
287
288        if (u1 > 0 && u2 > 0)
289        return 1;
290
291        ydiff = v2 - v1;
292
293        if (fabs(ydiff) < Limits::Small)
294        {         // denominator near 0
295                if (((fabs(v1) > Limits::Small) || (u1 > 0) || (u2 > 0)))
296                        return 0;
297                return 1;
298        }
299
300        t = -v1 / ydiff;                  // Compute parameter
301
302        return (u1 + t * (u2 - u1)) > 0;
303}
304
305
306int Polygon3::CastRay(const Ray &ray, float &t, const float nearestT)
307{
308        Plane3 plane = GetSupportingPlane();
309        float dot = DotProd(plane.mNormal, ray.GetDir());
310
311        // Watch for near-zero denominator
312        // ONLY single sided polygons!!!!!
313        if (dot > -Limits::Small)
314        //  if (fabs(dot) < Limits::Small)
315        return Ray::NO_INTERSECTION;
316
317        t = (-plane.mD - DotProd(plane.mNormal, ray.GetLoc())) / dot;
318
319        if (t <= Limits::Small)
320        return Ray::INTERSECTION_OUT_OF_LIMITS;
321
322        if (t >= nearestT) {
323        return Ray::INTERSECTION_OUT_OF_LIMITS; // no intersection was found
324        }
325
326        int count = 0;
327        float u, v, u1, v1, u2, v2;
328        int i;
329
330        int paxis = plane.mNormal.DrivingAxis();
331
332        // Project the intersection point onto the coordinate plane
333        // specified by which.
334        ray.Extrap(t).ExtractVerts(&u, &v, paxis);
335
336        int size = (int)mVertices.size();
337
338        mVertices.back().ExtractVerts(&u1, &v1, paxis );
339
340        if (0 && size <= 4)
341        {
342                // assume a convex face
343                for (i = 0; i < size; i++)
344                {
345                mVertices[i].ExtractVerts(&u2, &v2, paxis);
346           
347                        // line u1, v1, u2, v2
348           
349                        if ((v2 - v1)*(u1 - u) > (u2 - u1)*(v1 - v))
350                                return Ray::NO_INTERSECTION;
351
352                        u1 = u2;
353                        v1 = v2;
354        }
355
356        return Ray::INTERSECTION;
357        }
358
359        // We're stuck with the Jordan curve computation.  Count number
360        // of intersections between the line segments the polygon comprises
361        // with a ray originating at the point of intersection and
362        // travelling in the positive X direction.
363        for (i = 0; i < size; i++)
364        {
365                mVertices[i].ExtractVerts(&u2, &v2, paxis);
366
367                count += (int_lineseg(u, v, u1, v1, u2, v2) != 0);
368
369                u1 = u2;
370                v1 = v2;
371        }
372
373        // We hit polygon if number of intersections is odd.
374        return (count & 1) ? Ray::INTERSECTION : Ray::NO_INTERSECTION;
375}
376
377
378void Polygon3::InheritRays(Polygon3 &front_piece,
379                                               Polygon3 &back_piece) const
380{
381        if (mPiercingRays.empty())
382                return;
383
384        RayContainer::const_iterator it,
385                it_end = mPiercingRays.end();
386
387        for (it = mPiercingRays.begin(); it != it_end; ++ it)
388        {
389                switch((*it)->GetId())
390                {
391                case Ray::BACK:
392                        back_piece.mPiercingRays.push_back(*it);
393                        break;
394                case Ray::FRONT:
395                        front_piece.mPiercingRays.push_back(*it);
396                        break;
397                case Ray::FRONT_BACK:
398                        back_piece.mPiercingRays.push_back(*it);
399                        break;
400                case Ray::BACK_FRONT:
401                        front_piece.mPiercingRays.push_back(*it);
402                        break;
403                default:
404                        break;
405                }
406        }
407}
408
409
410int Polygon3::ClassifyPlane(const PolygonContainer &polys,
411                                                        const Plane3 &plane,
412                                                        const float epsilon)
413{
414        bool onFrontSide = false;
415        bool onBackSide = false;
416        PolygonContainer::const_iterator it;
417
418        // find intersections
419        for (it = polys.begin(); it != polys.end(); ++ it)
420        {
421        const int cf = (*it)->ClassifyPlane(plane, epsilon);
422               
423        if (cf == FRONT_SIDE)
424                        onFrontSide = true;
425                else if (cf == BACK_SIDE)
426                        onBackSide = true;
427               
428                if ((cf == SPLIT) || (cf == COINCIDENT) || (onFrontSide && onBackSide))
429                {
430                        return SPLIT;
431                }
432        }
433
434        if (onBackSide)
435        {
436                return BACK_SIDE;
437        }
438        else if (onFrontSide)
439        {
440                return FRONT_SIDE;
441        }
442       
443        return SPLIT;
444}
445
446
447int Polygon3::ParentObjectsSize(const PolygonContainer &polys)
448{
449        int count = 0;
450
451        PolygonContainer::const_iterator it, it_end = polys.end();
452
453        MeshInstance::NewMail();
454
455        for (it = polys.begin(); it != it_end; ++ it)
456        {
457                if ((*it)->mParent && !(*it)->mParent->Mailed())
458                {
459                        ++ count;
460                        (*it)->mParent->Mail();
461                }
462        }
463        return count;
464}
465
466
467float Polygon3::GetArea(const PolygonContainer &cell)
468{
469        float area = 0;
470        PolygonContainer::const_iterator pit;
471
472        for (pit = cell.begin(); pit != cell.end(); ++ pit)
473        {
474                area += (*pit)->GetArea();
475        }
476
477        return area;
478}
479
480
481Polygon3 *Polygon3::CreateReversePolygon() const
482{
483        Polygon3 *revPoly = new Polygon3();
484
485        VertexContainer::const_reverse_iterator rit,
486                        rit_end = mVertices.rend();
487
488        for(rit = mVertices.rbegin(); rit != rit_end; ++ rit)
489                revPoly->mVertices.push_back(*rit);
490
491        return revPoly;
492}
493
494
495void Polygon3::Triangulate(vector<Triangle3> &triangles) const
496{
497        int i = 1;
498        int j = 0;
499        int k = (int)mVertices.size() - 1;
500        int count = 0;
501
502        while (i < k)
503        {
504                triangles.push_back(Triangle3(mVertices[i], mVertices[j], mVertices[k]));
505
506                if ((count ++) % 2)
507                        j = i ++;
508                else
509                        j = k --;
510        }
511}
512
513
514void Polygon3::Triangulate(VertexIndexContainer &indices) const
515{
516        int i = 1;
517        int j = 0;
518        int k = (int)mVertices.size() - 1;
519
520        int count = 0;
521
522        while (i < k)
523        {
524                indices.push_back(k);
525                indices.push_back(j);
526                indices.push_back(i);
527
528                if ((count ++) % 2)
529                        j = i ++;
530                else
531                        j = k --;
532        }
533}
534
535
536void IncludePolyInMesh(const Polygon3 &poly, Mesh &mesh)
537{
538        const int n = (int)mesh.mVertices.size();
539
540    //-- add the vertices
541    VertexContainer::const_iterator vit, vit_end = poly.mVertices.end();
542        for (vit = poly.mVertices.begin(); vit != vit_end; ++ vit)
543        {
544                mesh.mVertices.push_back(*vit);
545        }
546
547        // one quad => no triangulation necessary
548        if (poly.mVertices.size() == 4)
549        {
550                mesh.AddFace(new Face(n, n + 1, n + 2, n + 3));
551                return;
552        }
553       
554        VertexIndexContainer indices;
555        poly.Triangulate(indices);
556
557        // add indices of triangle strip
558        for (int i = 0; i < (int)indices.size(); i += 3)
559        {
560                Face *face = new Face(n + indices[i],
561                                                          n + indices[i + 1],
562                                                          n + indices[i + 2]);
563                mesh.AddFace(face);
564        }
565}
566
567}
Note: See TracBrowser for help on using the repository browser.