summaryrefslogtreecommitdiff
path: root/basegfx/source/polygon/b2dpolygonclipper.cxx
blob: 8f25c82ddef2c611453a9344235d02ba0b7c5cc8 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2008 by Sun Microsystems, Inc.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * $RCSfile: b2dpolygonclipper.cxx,v $
 * $Revision: 1.6 $
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_basegfx.hxx"
#include <basegfx/polygon/b2dpolygonclipper.hxx>
#include <osl/diagnose.h>
#include <basegfx/polygon/b2dpolygontools.hxx>
#include <basegfx/numeric/ftools.hxx>
#include <basegfx/matrix/b2dhommatrix.hxx>
#include <basegfx/polygon/b2dpolypolygoncutter.hxx>
#include <basegfx/polygon/b2dpolygoncutandtouch.hxx>
#include <basegfx/polygon/b2dpolypolygontools.hxx>
#include <basegfx/curve/b2dcubicbezier.hxx>
#include <basegfx/tools/rectcliptools.hxx>

//////////////////////////////////////////////////////////////////////////////

namespace basegfx
{
    namespace tools
    {
        B2DPolyPolygon clipPolygonOnParallelAxis(const B2DPolygon& rCandidate, bool bParallelToXAxis, bool bAboveAxis, double fValueOnOtherAxis, bool bStroke)
        {
            B2DPolyPolygon aRetval;

            if(rCandidate.count())
            {
                const B2DRange aCandidateRange(getRange(rCandidate));

                if(bParallelToXAxis && fTools::moreOrEqual(aCandidateRange.getMinY(), fValueOnOtherAxis))
                {
                    // completely above and on the clip line. also true for curves.
                    if(bAboveAxis)
                    {
                        // add completely
                        aRetval.append(rCandidate);
                    }
                }
                else if(bParallelToXAxis && fTools::lessOrEqual(aCandidateRange.getMaxY(), fValueOnOtherAxis))
                {
                    // completely below and on the clip line. also true for curves.
                    if(!bAboveAxis)
                    {
                        // add completely
                        aRetval.append(rCandidate);
                    }
                }
                else if(!bParallelToXAxis && fTools::moreOrEqual(aCandidateRange.getMinX(), fValueOnOtherAxis))
                {
                    // completely right of and on the clip line. also true for curves.
                    if(bAboveAxis)
                    {
                        // add completely
                        aRetval.append(rCandidate);
                    }
                }
                else if(!bParallelToXAxis && fTools::lessOrEqual(aCandidateRange.getMaxX(), fValueOnOtherAxis))
                {
                    // completely left of and on the clip line. also true for curves.
                    if(!bAboveAxis)
                    {
                        // add completely
                        aRetval.append(rCandidate);
                    }
                }
                else
                {
                    // prepare loop(s)
                    OSL_ENSURE(!rCandidate.areControlPointsUsed(), "clipPolygonOnParallelAxis: ATM works not for curves (!)");
                    B2DPolygon aNewPolygon;
                    B2DPoint aCurrent(rCandidate.getB2DPoint(0L));
                    bool bCurrentInside(bParallelToXAxis ?
                        fTools::moreOrEqual(aCurrent.getY(), fValueOnOtherAxis) == bAboveAxis :
                        fTools::moreOrEqual(aCurrent.getX(), fValueOnOtherAxis) == bAboveAxis);
                    const sal_uInt32 nPointCount(rCandidate.count());
                    const sal_uInt32 nEdgeCount(rCandidate.isClosed() ? nPointCount : nPointCount - 1L);

                    if(bCurrentInside)
                    {
                        aNewPolygon.append(aCurrent);
                    }

                    if(bStroke)
                    {
                        // open polygon, create clipped line snippets.
                        for(sal_uInt32 a(0L); a < nEdgeCount; a++)
                        {
                            // get next point data
                            const sal_uInt32 nNextIndex((a + 1L == nPointCount) ? 0L : a + 1L);
                            const B2DPoint aNext(rCandidate.getB2DPoint(nNextIndex));
                            const bool bNextInside(bParallelToXAxis ?
                                fTools::moreOrEqual(aNext.getY(), fValueOnOtherAxis) == bAboveAxis :
                                fTools::moreOrEqual(aNext.getX(), fValueOnOtherAxis) == bAboveAxis);

                            if(bCurrentInside != bNextInside)
                            {
                                // change inside/outside
                                if(bNextInside)
                                {
                                    // entering, finish existing and start new line polygon
                                    if(aNewPolygon.count() > 1L)
                                    {
                                        aRetval.append(aNewPolygon);
                                    }

                                    aNewPolygon.clear();
                                }

                                // calculate and add cut point
                                if(bParallelToXAxis)
                                {
                                    const double fNewX(aCurrent.getX() - (((aCurrent.getY() - fValueOnOtherAxis) * (aNext.getX() - aCurrent.getX()) / (aNext.getY() - aCurrent.getY()))));
                                    aNewPolygon.append(B2DPoint(fNewX, fValueOnOtherAxis));
                                }
                                else
                                {
                                    const double fNewY(aCurrent.getY() - (((aCurrent.getX() - fValueOnOtherAxis) * (aNext.getY() - aCurrent.getY()) / (aNext.getX() - aCurrent.getX()))));
                                    aNewPolygon.append(B2DPoint(fValueOnOtherAxis, fNewY));
                                }

                                // pepare next step
                                bCurrentInside = bNextInside;
                            }

                            if(bNextInside)
                            {
                                aNewPolygon.append(aNext);
                            }

                            // pepare next step
                            aCurrent = aNext;
                        }

                        if(aNewPolygon.count() > 1L)
                        {
                            aRetval.append(aNewPolygon);
                        }
                    }
                    else
                    {
                        // closed polygon, create single clipped closed polygon
                        for(sal_uInt32 a(0L); a < nEdgeCount; a++)
                        {
                            // get next point data, use offset
                            const sal_uInt32 nNextIndex((a + 1L == nPointCount) ? 0L : a + 1L);
                            const B2DPoint aNext(rCandidate.getB2DPoint(nNextIndex));
                            const bool bNextInside(bParallelToXAxis ?
                                fTools::moreOrEqual(aNext.getY(), fValueOnOtherAxis) == bAboveAxis :
                                fTools::moreOrEqual(aNext.getX(), fValueOnOtherAxis) == bAboveAxis);

                            if(bCurrentInside != bNextInside)
                            {
                                // change inside/outside, calculate and add cut point
                                if(bParallelToXAxis)
                                {
                                    const double fNewX(aCurrent.getX() - (((aCurrent.getY() - fValueOnOtherAxis) * (aNext.getX() - aCurrent.getX()) / (aNext.getY() - aCurrent.getY()))));
                                    aNewPolygon.append(B2DPoint(fNewX, fValueOnOtherAxis));
                                }
                                else
                                {
                                    const double fNewY(aCurrent.getY() - (((aCurrent.getX() - fValueOnOtherAxis) * (aNext.getY() - aCurrent.getY()) / (aNext.getX() - aCurrent.getX()))));
                                    aNewPolygon.append(B2DPoint(fValueOnOtherAxis, fNewY));
                                }

                                // pepare next step
                                bCurrentInside = bNextInside;
                            }

                            if(bNextInside && nNextIndex)
                            {
                                aNewPolygon.append(aNext);
                            }

                            // pepare next step
                            aCurrent = aNext;
                        }

                        if(aNewPolygon.count() > 2L)
                        {
                            aNewPolygon.setClosed(true);
                            aRetval.append(aNewPolygon);
                        }
                    }
                }
            }

            return aRetval;
        }

        B2DPolyPolygon clipPolyPolygonOnParallelAxis(const B2DPolyPolygon& rCandidate, bool bParallelToXAxis, bool bAboveAxis, double fValueOnOtherAxis, bool bStroke)
        {
            const sal_uInt32 nPolygonCount(rCandidate.count());
            B2DPolyPolygon aRetval;

            for(sal_uInt32 a(0L); a < nPolygonCount; a++)
            {
                B2DPolygon aCandidate(rCandidate.getB2DPolygon(a));

                aRetval.append(clipPolygonOnParallelAxis(aCandidate, bParallelToXAxis, bAboveAxis, fValueOnOtherAxis, bStroke));
            }

            return aRetval;
        }

        B2DPolyPolygon clipPolygonOnRange(const B2DPolygon& rCandidate, const B2DRange& rRange, bool bInside, bool bStroke)
        {
            B2DPolyPolygon aRetval;

            if(rRange.isEmpty())
            {
                // clipping against an empty range. Nothing is inside an empty range, so the polygon
                // is outside the range. So only return if not inside is wanted
                if(!bInside && rCandidate.count())
                {
                    aRetval.append(rCandidate);
                }
            }
            if(rCandidate.count())
            {
                const B2DRange aCandidateRange(getRange(rCandidate));

                if(rRange.isInside(aCandidateRange))
                {
                    // candidate is completely inside given range, nothing to do. Is also true with curves.
                    if(bInside)
                    {
                        aRetval.append(rCandidate);
                    }
                }
                else
                {
                    // clip against the four axes of the range
                    // against X-Axis, lower value
                    aRetval = clipPolygonOnParallelAxis(rCandidate, true, bInside, rRange.getMinY(), bStroke);

                    if(aRetval.count())
                    {
                        // against Y-Axis, lower value
                        if(1L == aRetval.count())
                        {
                            aRetval = clipPolygonOnParallelAxis(aRetval.getB2DPolygon(0L), false, bInside, rRange.getMinX(), bStroke);
                        }
                        else
                        {
                            aRetval = clipPolyPolygonOnParallelAxis(aRetval, false, bInside, rRange.getMinX(), bStroke);
                        }

                        if(aRetval.count())
                        {
                            // against X-Axis, higher value
                            if(1L == aRetval.count())
                            {
                                aRetval = clipPolygonOnParallelAxis(aRetval.getB2DPolygon(0L), true, !bInside, rRange.getMaxY(), bStroke);
                            }
                            else
                            {
                                aRetval = clipPolyPolygonOnParallelAxis(aRetval, true, !bInside, rRange.getMaxY(), bStroke);
                            }

                            if(aRetval.count())
                            {
                                // against Y-Axis, higher value
                                if(1L == aRetval.count())
                                {
                                    aRetval = clipPolygonOnParallelAxis(aRetval.getB2DPolygon(0L), false, !bInside, rRange.getMaxX(), bStroke);
                                }
                                else
                                {
                                    aRetval = clipPolyPolygonOnParallelAxis(aRetval, false, !bInside, rRange.getMaxX(), bStroke);
                                }
                            }
                        }
                    }
                }
            }

            return aRetval;
        }

        B2DPolyPolygon clipPolyPolygonOnRange(const B2DPolyPolygon& rCandidate, const B2DRange& rRange, bool bInside, bool bStroke)
        {
            const sal_uInt32 nPolygonCount(rCandidate.count());
            B2DPolyPolygon aRetval;

            for(sal_uInt32 a(0L); a < nPolygonCount; a++)
            {
                B2DPolygon aCandidate(rCandidate.getB2DPolygon(a));

                aRetval.append(clipPolygonOnRange(aCandidate, rRange, bInside, bStroke));
            }

            return aRetval;
        }

        B2DPolyPolygon clipPolygonOnEdge(const B2DPolygon& rCandidate, const B2DPoint& rPointA, const B2DPoint& rPointB, bool bAbove, bool bStroke)
        {
            B2DPolyPolygon aRetval;

            if(rPointA.equal(rPointB))
            {
                // edge has no length, return polygon
                aRetval.append(rCandidate);
            }
            else if(rCandidate.count())
            {
                const B2DVector aEdge(rPointB - rPointA);
                B2DHomMatrix aMatrixTransform;
                B2DPolygon aCandidate(rCandidate);

                // translate and rotate polygon so that given edge is on x axis
                aMatrixTransform.translate(-rPointA.getX(), -rPointA.getY());
                aMatrixTransform.rotate(-atan2(aEdge.getY(), aEdge.getX()));
                aCandidate.transform(aMatrixTransform);

                // call clip method on X-Axis
                aRetval = clipPolygonOnParallelAxis(aCandidate, true, bAbove, 0.0, bStroke);

                if(aRetval.count())
                {
                    // if there is a result, it needs to be transformed back
                    aMatrixTransform.invert();
                    aRetval.transform(aMatrixTransform);
                }
            }

            return aRetval;
        }

        B2DPolyPolygon clipPolyPolygonOnEdge(const B2DPolyPolygon& rCandidate, const B2DPoint& rPointA, const B2DPoint& rPointB, bool bAbove, bool bStroke)
        {
            B2DPolyPolygon aRetval;

            if(rPointA.equal(rPointB))
            {
                // edge has no length, return polygon
                aRetval = rCandidate;
            }
            else if(rCandidate.count())
            {
                const B2DVector aEdge(rPointB - rPointA);
                B2DHomMatrix aMatrixTransform;
                B2DPolyPolygon aCandidate(rCandidate);

                // translate and rotate polygon so that given edge is on x axis
                aMatrixTransform.translate(-rPointA.getX(), -rPointA.getY());
                aMatrixTransform.rotate(-atan2(aEdge.getY(), aEdge.getX()));
                aCandidate.transform(aMatrixTransform);

                // call clip method on X-Axis
                aRetval = clipPolyPolygonOnParallelAxis(aCandidate, true, bAbove, 0.0, bStroke);

                if(aRetval.count())
                {
                    // if there is a result, it needs to be transformed back
                    aMatrixTransform.invert();
                    aRetval.transform(aMatrixTransform);
                }
            }

            return aRetval;
        }

        //////////////////////////////////////////////////////////////////////////////

        B2DPolyPolygon clipPolyPolygonOnPolyPolygon(const B2DPolyPolygon& rCandidate, const B2DPolyPolygon& rClip, bool bStroke, bool bInvert)
        {
            B2DPolyPolygon aRetval;

            if(rCandidate.count() && rClip.count())
            {
                if(bStroke)
                {
                    // line clipping, create line snippets
                    for(sal_uInt32 a(0L); a < rCandidate.count(); a++)
                    {
                        // get candidate and add cuts and touches with rClip to aCandidate
                        const B2DPolygon aCandidate(addPointsAtCutsAndTouches(rClip, rCandidate.getB2DPolygon(a)));
                        const sal_uInt32 nPointCount(aCandidate.count());

                        if(nPointCount)
                        {
                            const sal_uInt32 nEdgeCount(aCandidate.isClosed() ? nPointCount : nPointCount - 1L);

                            if(nEdgeCount)
                            {
                                // prepare partial polygon
                                B2DPolygon aRun;
                                B2DPoint aCurrent(aCandidate.getB2DPoint(0L));
                                B2DPoint aControlPointPrev;
                                B2DPoint aControlPointNext;
                                bool bInside(false);

                                for(sal_uInt32 b(0L); b < nEdgeCount; b++)
                                {
                                    const sal_uInt32 nNextIndex((b + 1L) % nPointCount);
                                    const B2DPoint aNext(aCandidate.getB2DPoint(nNextIndex));
                                    bool bCurveEdge(false);

                                    if(aCandidate.areControlPointsUsed())
                                    {
                                        aControlPointNext = aCandidate.getNextControlPoint(b);
                                        aControlPointPrev = aCandidate.getPrevControlPoint(nNextIndex);
                                        bCurveEdge = !aControlPointNext.equal(aCurrent) || !aControlPointPrev.equal(aNext);
                                    }

                                    if(bCurveEdge)
                                    {
                                        const B2DCubicBezier aCubicBezier(aCurrent, aControlPointNext, aControlPointPrev, aNext);
                                        const B2DPoint aComparePoint(aCubicBezier.interpolatePoint(0.5));
                                        bInside = (isInside(rClip, aComparePoint) != bInvert);
                                    }
                                    else
                                    {
                                        const B2DPoint aComparePoint(average(aCurrent, aNext));
                                        bInside = (isInside(rClip, aComparePoint) != bInvert);
                                    }

                                    if(bInside)
                                    {
                                        if(!aRun.count())
                                        {
                                            aRun.append(aCurrent);
                                        }

                                        if(bCurveEdge)
                                        {
                                            aRun.appendBezierSegment(aControlPointNext, aControlPointPrev, aNext);
                                        }
                                        else
                                        {
                                            aRun.append(aNext);
                                        }
                                    }
                                    else
                                    {
                                        if(aRun.count())
                                        {
                                            aRetval.append(aRun);
                                            aRun.clear();
                                        }
                                    }

                                    // prepare next step
                                    aCurrent = aNext;
                                }

                                if(aRun.count())
                                {
                                    aRetval.append(aRun);
                                }
                            }
                        }
                    }
                }
                else
                {
                    // area clipping
                    B2DPolyPolygon aMergePolyPolygonA(rClip);
                    aMergePolyPolygonA = SolveCrossovers(aMergePolyPolygonA);
                    aMergePolyPolygonA = StripNeutralPolygons(aMergePolyPolygonA);
                    aMergePolyPolygonA = StripDispensablePolygons(aMergePolyPolygonA);

                    if(bInvert)
                    {
                        aMergePolyPolygonA.flip();
                    }

                    B2DPolyPolygon aMergePolyPolygonB(rCandidate);
                    aMergePolyPolygonB = SolveCrossovers(aMergePolyPolygonB);
                    aMergePolyPolygonB = StripNeutralPolygons(aMergePolyPolygonB);
                    aMergePolyPolygonB = StripDispensablePolygons(aMergePolyPolygonB);

                    aRetval.append(aMergePolyPolygonA);
                    aRetval.append(aMergePolyPolygonB);
                    aRetval = SolveCrossovers(aRetval, false);
                    aRetval = StripNeutralPolygons(aRetval);
                    aRetval = StripDispensablePolygons(aRetval, !bInvert);
                }
            }

            return aRetval;
        }

        //////////////////////////////////////////////////////////////////////////////

        B2DPolyPolygon clipPolygonOnPolyPolygon(const B2DPolygon& rCandidate, const B2DPolyPolygon& rClip, bool bStroke, bool bInvert)
        {
            B2DPolyPolygon aRetval;

            if(rCandidate.count() && rClip.count())
            {
                aRetval = clipPolyPolygonOnPolyPolygon(B2DPolyPolygon(rCandidate), rClip, bStroke, bInvert);
            }

            return aRetval;
        }

        //////////////////////////////////////////////////////////////////////////////

        /*
        * let a plane be defined as
        *
        *     v.n+d=0
        *
        * and a ray be defined as
        *
        *     a+(b-a)*t=0
        *
        * substitute and rearranging yields
        *
        *     t = -(a.n+d)/(n.(b-a))
        *
        * if the denominator is zero, the line is either
        * contained in the plane or parallel to the plane.
        * in either case, there is no intersection.
        * if numerator and denominator are both zero, the
        * ray is contained in the plane.
        *
        */
        struct scissor_plane {
            double nx,ny;           // plane normal
            double d;               // [-] minimum distance from origin
            sal_uInt32 clipmask;    // clipping mask, e.g. 1000 1000
        };

        /*
        *
        * polygon clipping rules  (straight out of Foley and Van Dam)
        * ===========================================================
        * current   |next       |emit
        * ____________________________________
        * inside    |inside     |next
        * inside    |outside    |intersect with clip plane
        * outside   |outside    |nothing
        * outside   |inside     |intersect with clip plane follwed by next
        *
        */
        sal_uInt32 scissorLineSegment( ::basegfx::B2DPoint           *in_vertex,    // input buffer
                                       sal_uInt32                     in_count,     // number of verts in input buffer
                                       ::basegfx::B2DPoint           *out_vertex,   // output buffer
                                       scissor_plane                 *pPlane,       // scissoring plane
                                       const ::basegfx::B2DRectangle &rR )          // clipping rectangle
        {
            ::basegfx::B2DPoint *curr;
            ::basegfx::B2DPoint *next;

            sal_uInt32 out_count=0;

            // process all the verts
            for(sal_uInt32 i=0; i<in_count; i++) {

                // vertices are relative to the coordinate
                // system defined by the rectangle.
                curr = &in_vertex[i];
                next = &in_vertex[(i+1)%in_count];

                // perform clipping judgement & mask against current plane.
                sal_uInt32 clip = pPlane->clipmask & ((getCohenSutherlandClipFlags(*curr,rR)<<4)|getCohenSutherlandClipFlags(*next,rR));

                if(clip==0) { // both verts are inside
                    out_vertex[out_count++] = *next;
                }
                else if((clip&0x0f) && (clip&0xf0)) { // both verts are outside
                }
                else if((clip&0x0f) && (clip&0xf0)==0) { // curr is inside, next is outside

                    // direction vector from 'current' to 'next', *not* normalized
                    // to bring 't' into the [0<=x<=1] intervall.
                    ::basegfx::B2DPoint dir((*next)-(*curr));

                    double denominator = ( pPlane->nx*dir.getX() +
                                        pPlane->ny*dir.getY() );
                    double numerator = ( pPlane->nx*curr->getX() +
                                        pPlane->ny*curr->getY() +
                                        pPlane->d );
                    double t = -numerator/denominator;

                    // calculate the actual point of intersection
                    ::basegfx::B2DPoint intersection( curr->getX()+t*dir.getX(),
                                                    curr->getY()+t*dir.getY() );

                    out_vertex[out_count++] = intersection;
                }
                else if((clip&0x0f)==0 && (clip&0xf0)) { // curr is outside, next is inside

                    // direction vector from 'current' to 'next', *not* normalized
                    // to bring 't' into the [0<=x<=1] intervall.
                    ::basegfx::B2DPoint dir((*next)-(*curr));

                    double denominator = ( pPlane->nx*dir.getX() +
                                        pPlane->ny*dir.getY() );
                    double numerator = ( pPlane->nx*curr->getX() +
                                        pPlane->ny*curr->getY() +
                                        pPlane->d );
                    double t = -numerator/denominator;

                    // calculate the actual point of intersection
                    ::basegfx::B2DPoint intersection( curr->getX()+t*dir.getX(),
                                                    curr->getY()+t*dir.getY() );

                    out_vertex[out_count++] = intersection;
                    out_vertex[out_count++] = *next;
                }
            }

            return out_count;
        }

        B2DPolygon clipTriangleListOnRange( const B2DPolygon& rCandidate,
                                            const B2DRange&   rRange )
        {
            B2DPolygon aResult;

            if( !(rCandidate.count()%3) )
            {
                const int scissor_plane_count = 4;

                scissor_plane sp[scissor_plane_count];

                sp[0].nx = +1.0;
                sp[0].ny = +0.0;
                sp[0].d = -(rRange.getMinX());
                sp[0].clipmask = (RectClipFlags::LEFT << 4) | RectClipFlags::LEFT; // 0001 0001
                sp[1].nx = -1.0;
                sp[1].ny = +0.0;
                sp[1].d = +(rRange.getMaxX());
                sp[1].clipmask = (RectClipFlags::RIGHT << 4) | RectClipFlags::RIGHT; // 0010 0010
                sp[2].nx = +0.0;
                sp[2].ny = +1.0;
                sp[2].d = -(rRange.getMinY());
                sp[2].clipmask = (RectClipFlags::TOP << 4) | RectClipFlags::TOP; // 0100 0100
                sp[3].nx = +0.0;
                sp[3].ny = -1.0;
                sp[3].d = +(rRange.getMaxY());
                sp[3].clipmask = (RectClipFlags::BOTTOM << 4) | RectClipFlags::BOTTOM; // 1000 1000

                // retrieve the number of vertices of the triangulated polygon
                const sal_uInt32 nVertexCount = rCandidate.count();

                if(nVertexCount)
                {
                    ////////////////////////////////////////////////////////////////////////
                    ////////////////////////////////////////////////////////////////////////
                    ////////////////////////////////////////////////////////////////////////
                    //
                    // Upper bound for the maximal number of vertices when intersecting an
                    // axis-aligned rectangle with a triangle in E2
                    //
                    // The rectangle and the triangle are in general position, and have 4 and 3
                    // vertices, respectively.
                    //
                    //   Lemma: Since the rectangle is a convex polygon ( see
                    //   http://mathworld.wolfram.com/ConvexPolygon.html for a definition), and
                    //   has no holes, it follows that any straight line will intersect the
                    //   rectangle's border line at utmost two times (with the usual
                    //   tie-breaking rule, if the intersection exactly hits an already existing
                    //   rectangle vertex, that this intersection is only attributed to one of
                    //   the adjoining edges). Thus, having a rectangle intersected with
                    //   a half-plane (one side of a straight line denotes 'inside', the
                    //   other 'outside') will at utmost add _one_  vertex to the resulting
                    //   intersection polygon (adding two intersection vertices, and removing at
                    //   least one rectangle vertex):
                    //
                    //         *
                    //     +--+-----------------+
                    //     | *                  |
                    //     |*                   |
                    //     +                    |
                    //    *|                    |
                    //   * |                    |
                    //     +--------------------+
                    //
                    //   Proof: If the straight line intersects the rectangle two
                    //   times, it does so for distinct edges, i.e. the intersection has
                    //   minimally one of the rectangle's vertices on either side of the straight
                    //   line (but maybe more). Thus, the intersection with a half-plane has
                    //   minimally _one_ rectangle vertex removed from the resulting clip
                    //   polygon, and therefore, a clip against a half-plane has the net effect
                    //   of adding at utmost _one_ vertex to the resulting clip polygon.
                    //
                    // Theorem: The intersection of a rectangle and a triangle results in a
                    // polygon with at utmost 7 vertices.
                    //
                    // Proof: The inside of the triangle can be described as the consecutive
                    // intersection with three half-planes. Together with the lemma above, this
                    // results in at utmost 3 additional vertices added to the already existing 4
                    // rectangle vertices.
                    //
                    // This upper bound is attained with the following example configuration:
                    //
                    //                               *
                    //                             ***
                    //                           ** *
                    //                         **  *
                    //                       **   *
                    //                     **    *
                    //                   **     *
                    //                 **      *
                    //               **       *
                    //             **        *
                    //           **         *
                    //     ----*2--------3 *
                    //     | **          |*
                    //     1*            4
                    //   **|            *|
                    // **  |           * |
                    //   **|          *  |
                    //     7*        *   |
                    //     --*6-----5-----
                    //         **  *
                    //           **
                    //
                    // As we need to scissor all triangles against the
                    // output rectangle we employ an output buffer for the
                    // resulting vertices.  the question is how large this
                    // buffer needs to be compared to the number of
                    // incoming vertices.  this buffer needs to hold at
                    // most the number of original vertices times '7'. see
                    // figure above for an example.  scissoring triangles
                    // with the cohen-sutherland line clipping algorithm
                    // as implemented here will result in a triangle fan
                    // which will be rendered as separate triangles to
                    // avoid pipeline stalls for each scissored
                    // triangle. creating separate triangles from a
                    // triangle fan produces (n-2)*3 vertices where n is
                    // the number of vertices of the original triangle
                    // fan.  for the maximum number of 7 vertices of
                    // resulting triangle fans we therefore need 15 times
                    // the number of original vertices.
                    //
                    ////////////////////////////////////////////////////////////////////////
                    ////////////////////////////////////////////////////////////////////////
                    ////////////////////////////////////////////////////////////////////////

                    //const size_t nBufferSize = sizeof(vertex)*(nVertexCount*16);
                    //vertex *pVertices = (vertex*)alloca(nBufferSize);
                    //sal_uInt32 nNumOutput = 0;

                    // we need to clip this triangle against the output rectangle
                    // to ensure that the resulting texture coordinates are in
                    // the valid range from [0<=st<=1]. under normal circustances
                    // we could use the BORDERCOLOR renderstate but some cards
                    // seem to ignore this feature.
                    ::basegfx::B2DPoint stack[3];
                    unsigned int clipflag = 0;

                    for(sal_uInt32 nIndex=0; nIndex<nVertexCount; ++nIndex)
                    {
                        // rotate stack
                        stack[0] = stack[1];
                        stack[1] = stack[2];
                        stack[2] = rCandidate.getB2DPoint(nIndex);

                        // clipping judgement
                        clipflag |= !(rRange.isInside(stack[2]));

                        if(nIndex > 1)
                        {
                            // consume vertices until a single seperate triangle has been visited.
                            if(!((nIndex+1)%3))
                            {
                                // if any of the last three vertices was outside
                                // we need to scissor against the destination rectangle
                                if(clipflag & 7)
                                {
                                    ::basegfx::B2DPoint buf0[16];
                                    ::basegfx::B2DPoint buf1[16];

                                    sal_uInt32 vertex_count = 3;

                                    // clip against all 4 planes passing the result of
                                    // each plane as the input to the next using a double buffer
                                    vertex_count = scissorLineSegment(stack,vertex_count,buf1,&sp[0],rRange);
                                    vertex_count = scissorLineSegment(buf1,vertex_count,buf0,&sp[1],rRange);
                                    vertex_count = scissorLineSegment(buf0,vertex_count,buf1,&sp[2],rRange);
                                    vertex_count = scissorLineSegment(buf1,vertex_count,buf0,&sp[3],rRange);

                                    if(vertex_count >= 3)
                                    {
                                        // convert triangle fan back to triangle list.
                                        ::basegfx::B2DPoint v0(buf0[0]);
                                        ::basegfx::B2DPoint v1(buf0[1]);
                                        for(sal_uInt32 i=2; i<vertex_count; ++i)
                                        {
                                            ::basegfx::B2DPoint v2(buf0[i]);
                                            aResult.append(v0);
                                            aResult.append(v1);
                                            aResult.append(v2);
                                            v1 = v2;
                                        }
                                    }
                                }
                                else
                                {
                                    // the last triangle has not been altered, simply copy to result
                                    for(sal_uInt32 i=0; i<3; ++i)
                                        aResult.append(stack[i]);
                                }
                            }
                        }

                        clipflag <<= 1;
                    }
                }
            }

            return aResult;
        }

        //////////////////////////////////////////////////////////////////////////////

    } // end of namespace tools
} // end of namespace basegfx

//////////////////////////////////////////////////////////////////////////////

// eof