summaryrefslogtreecommitdiff
path: root/drawinglayer/source/primitive2d/sceneprimitive2d.cxx
blob: 2ad2a401aae7547c77b0e2173baa20e313c1af7f (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
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
 * This file is part of the LibreOffice project.
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 *
 * This file incorporates work covered by the following license notice:
 *
 *   Licensed to the Apache Software Foundation (ASF) under one or more
 *   contributor license agreements. See the NOTICE file distributed
 *   with this work for additional information regarding copyright
 *   ownership. The ASF licenses this file to you under the Apache
 *   License, Version 2.0 (the "License"); you may not use this file
 *   except in compliance with the License. You may obtain a copy of
 *   the License at http://www.apache.org/licenses/LICENSE-2.0 .
 */

#include <drawinglayer/primitive2d/sceneprimitive2d.hxx>
#include <basegfx/polygon/b2dpolygontools.hxx>
#include <basegfx/polygon/b2dpolygon.hxx>
#include <basegfx/matrix/b2dhommatrix.hxx>
#include <drawinglayer/attribute/sdrlightattribute3d.hxx>
#include <drawinglayer/primitive2d/bitmapprimitive2d.hxx>
#include <drawinglayer/primitive2d/PolygonHairlinePrimitive2D.hxx>
#include <processor3d/zbufferprocessor3d.hxx>
#include <processor3d/shadow3dextractor.hxx>
#include <drawinglayer/geometry/viewinformation2d.hxx>
#include <drawinglayer/primitive2d/drawinglayer_primitivetypes2d.hxx>
#include <svtools/optionsdrawinglayer.hxx>
#include <processor3d/geometry2dextractor.hxx>
#include <basegfx/raster/bzpixelraster.hxx>
#include <utility>
#include <vcl/BitmapTools.hxx>
#include <comphelper/threadpool.hxx>
#include <toolkit/helper/vclunohelper.hxx>

using namespace com::sun::star;

namespace
{
    BitmapEx BPixelRasterToBitmapEx(const basegfx::BZPixelRaster& rRaster, sal_uInt16 mnAntiAlialize)
    {
        BitmapEx aRetval;
        const sal_uInt32 nWidth(mnAntiAlialize ? rRaster.getWidth()/mnAntiAlialize : rRaster.getWidth());
        const sal_uInt32 nHeight(mnAntiAlialize ? rRaster.getHeight()/mnAntiAlialize : rRaster.getHeight());

        if(nWidth && nHeight)
        {
            const Size aDestSize(nWidth, nHeight);
            vcl::bitmap::RawBitmap aContent(aDestSize, 32);

            if(mnAntiAlialize)
            {
                const sal_uInt16 nDivisor(mnAntiAlialize * mnAntiAlialize);

                for(sal_uInt32 y(0); y < nHeight; y++)
                {
                    for(sal_uInt32 x(0); x < nWidth; x++)
                    {
                        sal_uInt16 nRed(0);
                        sal_uInt16 nGreen(0);
                        sal_uInt16 nBlue(0);
                        sal_uInt16 nAlpha(0);
                        sal_uInt32 nIndex(rRaster.getIndexFromXY(x * mnAntiAlialize, y * mnAntiAlialize));

                        for(sal_uInt32 c(0); c < mnAntiAlialize; c++)
                        {
                            for(sal_uInt32 d(0); d < mnAntiAlialize; d++)
                            {
                                const basegfx::BPixel& rPixel(rRaster.getBPixel(nIndex++));
                                nRed += rPixel.getRed();
                                nGreen += rPixel.getGreen();
                                nBlue += rPixel.getBlue();
                                nAlpha += rPixel.getAlpha();
                            }

                            nIndex += rRaster.getWidth() - mnAntiAlialize;
                        }

                        nAlpha /= nDivisor;

                        if(nAlpha)
                        {
                            aContent.SetPixel(y, x, Color(ColorAlpha,
                                static_cast<sal_uInt8>(nAlpha),
                                static_cast<sal_uInt8>(nRed / nDivisor),
                                static_cast<sal_uInt8>(nGreen / nDivisor),
                                static_cast<sal_uInt8>(nBlue / nDivisor) ));
                        }
                        else
                            aContent.SetPixel(y, x, Color(ColorAlpha, 0, 0, 0, 0));
                    }
                }
            }
            else
            {
                sal_uInt32 nIndex(0);

                for(sal_uInt32 y(0); y < nHeight; y++)
                {
                    for(sal_uInt32 x(0); x < nWidth; x++)
                    {
                        const basegfx::BPixel& rPixel(rRaster.getBPixel(nIndex++));

                        if(rPixel.getAlpha())
                        {
                            aContent.SetPixel(y, x, Color(ColorAlpha, rPixel.getAlpha(), rPixel.getRed(), rPixel.getGreen(), rPixel.getBlue()));
                        }
                        else
                            aContent.SetPixel(y, x, Color(ColorAlpha, 0, 0, 0, 0));
                    }
                }
            }

            aRetval = vcl::bitmap::CreateFromData(std::move(aContent));

            // #i101811# set PrefMapMode and PrefSize at newly created Bitmap
            aRetval.SetPrefMapMode(MapMode(MapUnit::MapPixel));
            aRetval.SetPrefSize(Size(nWidth, nHeight));
        }

        return aRetval;
    }
} // end of anonymous namespace

namespace drawinglayer::primitive2d
{
        bool ScenePrimitive2D::impGetShadow3D() const
        {
            // create on demand
            if(!mbShadow3DChecked && !getChildren3D().empty())
            {
                basegfx::B3DVector aLightNormal;
                const double fShadowSlant(getSdrSceneAttribute().getShadowSlant());
                const basegfx::B3DRange aScene3DRange(getChildren3D().getB3DRange(getViewInformation3D()));

                if(!maSdrLightingAttribute.getLightVector().empty())
                {
                    // get light normal from first light and normalize
                    aLightNormal = maSdrLightingAttribute.getLightVector()[0].getDirection();
                    aLightNormal.normalize();
                }

                // create shadow extraction processor
                processor3d::Shadow3DExtractingProcessor aShadowProcessor(
                    getViewInformation3D(),
                    getObjectTransformation(),
                    aLightNormal,
                    fShadowSlant,
                    aScene3DRange);

                // process local primitives
                aShadowProcessor.process(getChildren3D());

                // fetch result and set checked flag
                const_cast< ScenePrimitive2D* >(this)->maShadowPrimitives = aShadowProcessor.getPrimitive2DSequence();
                const_cast< ScenePrimitive2D* >(this)->mbShadow3DChecked = true;
            }

            // return if there are shadow primitives
            return !maShadowPrimitives.empty();
        }

        void ScenePrimitive2D::calculateDiscreteSizes(
            const geometry::ViewInformation2D& rViewInformation,
            basegfx::B2DRange& rDiscreteRange,
            basegfx::B2DRange& rVisibleDiscreteRange,
            basegfx::B2DRange& rUnitVisibleRange) const
        {
            // use unit range and transform to discrete coordinates
            rDiscreteRange = basegfx::B2DRange(0.0, 0.0, 1.0, 1.0);
            rDiscreteRange.transform(rViewInformation.getObjectToViewTransformation() * getObjectTransformation());

            // clip it against discrete Viewport (if set)
            rVisibleDiscreteRange = rDiscreteRange;

            if(!rViewInformation.getViewport().isEmpty())
            {
                rVisibleDiscreteRange.intersect(rViewInformation.getDiscreteViewport());
            }

            if(rVisibleDiscreteRange.isEmpty())
            {
                rUnitVisibleRange = rVisibleDiscreteRange;
            }
            else
            {
                // create UnitVisibleRange containing unit range values [0.0 .. 1.0] describing
                // the relative position of rVisibleDiscreteRange inside rDiscreteRange
                const double fDiscreteScaleFactorX(basegfx::fTools::equalZero(rDiscreteRange.getWidth()) ? 1.0 : 1.0 / rDiscreteRange.getWidth());
                const double fDiscreteScaleFactorY(basegfx::fTools::equalZero(rDiscreteRange.getHeight()) ? 1.0 : 1.0 / rDiscreteRange.getHeight());

                const double fMinX(basegfx::fTools::equal(rVisibleDiscreteRange.getMinX(), rDiscreteRange.getMinX())
                    ? 0.0
                    : (rVisibleDiscreteRange.getMinX() - rDiscreteRange.getMinX()) * fDiscreteScaleFactorX);
                const double fMinY(basegfx::fTools::equal(rVisibleDiscreteRange.getMinY(), rDiscreteRange.getMinY())
                    ? 0.0
                    : (rVisibleDiscreteRange.getMinY() - rDiscreteRange.getMinY()) * fDiscreteScaleFactorY);

                const double fMaxX(basegfx::fTools::equal(rVisibleDiscreteRange.getMaxX(), rDiscreteRange.getMaxX())
                    ? 1.0
                    : (rVisibleDiscreteRange.getMaxX() - rDiscreteRange.getMinX()) * fDiscreteScaleFactorX);
                const double fMaxY(basegfx::fTools::equal(rVisibleDiscreteRange.getMaxY(), rDiscreteRange.getMaxY())
                    ? 1.0
                    : (rVisibleDiscreteRange.getMaxY() - rDiscreteRange.getMinY()) * fDiscreteScaleFactorY);

                rUnitVisibleRange = basegfx::B2DRange(fMinX, fMinY, fMaxX, fMaxY);
            }
        }

        void ScenePrimitive2D::create2DDecomposition(Primitive2DContainer& rContainer, const geometry::ViewInformation2D& rViewInformation) const
        {
            // create 2D shadows from contained 3D primitives. This creates the shadow primitives on demand and tells if
            // there are some or not. Do this at start, the shadow might still be visible even when the scene is not
            if(impGetShadow3D())
            {
                // test visibility
                const basegfx::B2DRange aShadow2DRange(maShadowPrimitives.getB2DRange(rViewInformation));
                const basegfx::B2DRange aViewRange(
                    rViewInformation.getViewport());

                if(aViewRange.isEmpty() || aShadow2DRange.overlaps(aViewRange))
                {
                    // add extracted 2d shadows (before 3d scene creations itself)
                    rContainer.append(maShadowPrimitives);
                }
            }

            // get the involved ranges (see helper method calculateDiscreteSizes for details)
            basegfx::B2DRange aDiscreteRange;
            basegfx::B2DRange aVisibleDiscreteRange;
            basegfx::B2DRange aUnitVisibleRange;

            calculateDiscreteSizes(rViewInformation, aDiscreteRange, aVisibleDiscreteRange, aUnitVisibleRange);

            if(aVisibleDiscreteRange.isEmpty())
                return;

            // test if discrete view size (pixel) maybe too big and limit it
            double fViewSizeX(aVisibleDiscreteRange.getWidth());
            double fViewSizeY(aVisibleDiscreteRange.getHeight());
            const double fViewVisibleArea(fViewSizeX * fViewSizeY);
            const double fMaximumVisibleArea(SvtOptionsDrawinglayer::GetQuadratic3DRenderLimit());
            double fReduceFactor(1.0);

            if(fViewVisibleArea > fMaximumVisibleArea)
            {
                fReduceFactor = sqrt(fMaximumVisibleArea / fViewVisibleArea);
                fViewSizeX *= fReduceFactor;
                fViewSizeY *= fReduceFactor;
            }

            if(rViewInformation.getReducedDisplayQuality())
            {
                // when reducing the visualisation is allowed (e.g. an OverlayObject
                // only needed for dragging), reduce resolution extra
                // to speed up dragging interactions
                const double fArea(fViewSizeX * fViewSizeY);
                if (fArea != 0.0)
                {
                    double fReducedVisualisationFactor(1.0 / (sqrt(fArea) * (1.0 / 170.0)));

                    if(fReducedVisualisationFactor > 1.0)
                    {
                        fReducedVisualisationFactor = 1.0;
                    }
                    else if(fReducedVisualisationFactor < 0.20)
                    {
                        fReducedVisualisationFactor = 0.20;
                    }

                    if(fReducedVisualisationFactor != 1.0)
                    {
                        fReduceFactor *= fReducedVisualisationFactor;
                    }
                }
            }

            // determine the oversample value
            static const sal_uInt16 nDefaultOversampleValue(3);
            const sal_uInt16 nOversampleValue(SvtOptionsDrawinglayer::IsAntiAliasing() ? nDefaultOversampleValue : 0);

            geometry::ViewInformation3D aViewInformation3D(getViewInformation3D());
            {
                // calculate a transformation from DiscreteRange to evtl. rotated/sheared content.
                // Start with full transformation from object to discrete units
                basegfx::B2DHomMatrix aObjToUnit(rViewInformation.getObjectToViewTransformation() * getObjectTransformation());

                // bring to unit coordinates by applying inverse DiscreteRange
                aObjToUnit.translate(-aDiscreteRange.getMinX(), -aDiscreteRange.getMinY());
                if (aDiscreteRange.getWidth() != 0.0 && aDiscreteRange.getHeight() != 0.0)
                {
                    aObjToUnit.scale(1.0 / aDiscreteRange.getWidth(), 1.0 / aDiscreteRange.getHeight());
                }

                // calculate transformed user coordinate system
                const basegfx::B2DPoint aStandardNull(0.0, 0.0);
                const basegfx::B2DPoint aUnitRangeTopLeft(aObjToUnit * aStandardNull);
                const basegfx::B2DVector aStandardXAxis(1.0, 0.0);
                const basegfx::B2DVector aUnitRangeXAxis(aObjToUnit * aStandardXAxis);
                const basegfx::B2DVector aStandardYAxis(0.0, 1.0);
                const basegfx::B2DVector aUnitRangeYAxis(aObjToUnit * aStandardYAxis);

                if(!aUnitRangeTopLeft.equal(aStandardNull) || !aUnitRangeXAxis.equal(aStandardXAxis) || !aUnitRangeYAxis.equal(aStandardYAxis))
                {
                    // build transformation from unit range to user coordinate system; the unit range
                    // X and Y axes are the column vectors, the null point is the offset
                    basegfx::B2DHomMatrix aUnitRangeToUser;

                    aUnitRangeToUser.set3x2(
                        aUnitRangeXAxis.getX(), aUnitRangeYAxis.getX(), aUnitRangeTopLeft.getX(),
                        aUnitRangeXAxis.getY(), aUnitRangeYAxis.getY(), aUnitRangeTopLeft.getY());

                    // decompose to allow to apply this to the 3D transformation
                    basegfx::B2DVector aScale, aTranslate;
                    double fRotate, fShearX;
                    aUnitRangeToUser.decompose(aScale, aTranslate, fRotate, fShearX);

                    // apply before DeviceToView and after Projection, 3D is in range [-1.0 .. 1.0] in X,Y and Z
                    // and not yet flipped in Y
                    basegfx::B3DHomMatrix aExtendedProjection(aViewInformation3D.getProjection());

                    // bring to unit coordinates, flip Y, leave Z unchanged
                    aExtendedProjection.scale(0.5, -0.5, 1.0);
                    aExtendedProjection.translate(0.5, 0.5, 0.0);

                    // apply extra; Y is flipped now, go with positive shear and rotate values
                    aExtendedProjection.scale(aScale.getX(), aScale.getY(), 1.0);
                    aExtendedProjection.shearXZ(fShearX, 0.0);
                    aExtendedProjection.rotate(0.0, 0.0, fRotate);
                    aExtendedProjection.translate(aTranslate.getX(), aTranslate.getY(), 0.0);

                    // back to state after projection
                    aExtendedProjection.translate(-0.5, -0.5, 0.0);
                    aExtendedProjection.scale(2.0, -2.0, 1.0);

                    aViewInformation3D = geometry::ViewInformation3D(
                        aViewInformation3D.getObjectTransformation(),
                        aViewInformation3D.getOrientation(),
                        aExtendedProjection,
                        aViewInformation3D.getDeviceToView(),
                        aViewInformation3D.getViewTime(),
                        aViewInformation3D.getExtendedInformationSequence());
                }
            }

            // calculate logic render size in world coordinates for usage in renderer
            const basegfx::B2DHomMatrix& aInverseOToV(rViewInformation.getInverseObjectToViewTransformation());
            const double fLogicX((aInverseOToV * basegfx::B2DVector(aDiscreteRange.getWidth() * fReduceFactor, 0.0)).getLength());
            const double fLogicY((aInverseOToV * basegfx::B2DVector(0.0, aDiscreteRange.getHeight() * fReduceFactor)).getLength());

            // generate ViewSizes
            const double fFullViewSizeX((rViewInformation.getObjectToViewTransformation() * basegfx::B2DVector(fLogicX, 0.0)).getLength());
            const double fFullViewSizeY((rViewInformation.getObjectToViewTransformation() * basegfx::B2DVector(0.0, fLogicY)).getLength());

            // generate RasterWidth and RasterHeight for visible part
            const sal_Int32 nRasterWidth(basegfx::fround(fFullViewSizeX * aUnitVisibleRange.getWidth()) + 1);
            const sal_Int32 nRasterHeight(basegfx::fround(fFullViewSizeY * aUnitVisibleRange.getHeight()) + 1);

            if(!(nRasterWidth && nRasterHeight))
                return;

            // create view unit buffer
            basegfx::BZPixelRaster aBZPixelRaster(
                nOversampleValue ? nRasterWidth * nOversampleValue : nRasterWidth,
                nOversampleValue ? nRasterHeight * nOversampleValue : nRasterHeight);

            // check for parallel execution possibilities
            static bool bMultithreadAllowed = false; // loplugin:constvars:ignore
            sal_Int32 nThreadCount(0);
            comphelper::ThreadPool& rThreadPool(comphelper::ThreadPool::getSharedOptimalPool());

            if(bMultithreadAllowed)
            {
                nThreadCount = rThreadPool.getWorkerCount();

                if(nThreadCount > 1)
                {
                    // at least use 10px per processor, so limit number of processors to
                    // target pixel size divided by 10 (which might be zero what is okay)
                    nThreadCount = std::min(nThreadCount, nRasterHeight / 10);
                }
            }

            if(nThreadCount > 1)
            {
                class Executor : public comphelper::ThreadTask
                {
                private:
                    std::unique_ptr<processor3d::ZBufferProcessor3D> mpZBufferProcessor3D;
                    const primitive3d::Primitive3DContainer&    mrChildren3D;

                public:
                    explicit Executor(
                        std::shared_ptr<comphelper::ThreadTaskTag> const & rTag,
                        std::unique_ptr<processor3d::ZBufferProcessor3D> pZBufferProcessor3D,
                        const primitive3d::Primitive3DContainer& rChildren3D)
                    :   comphelper::ThreadTask(rTag),
                        mpZBufferProcessor3D(std::move(pZBufferProcessor3D)),
                        mrChildren3D(rChildren3D)
                    {
                    }

                    virtual void doWork() override
                    {
                        mpZBufferProcessor3D->process(mrChildren3D);
                        mpZBufferProcessor3D->finish();
                        mpZBufferProcessor3D.reset();
                    }
                };

                const sal_uInt32 nLinesPerThread(aBZPixelRaster.getHeight() / nThreadCount);
                std::shared_ptr<comphelper::ThreadTaskTag> aTag = comphelper::ThreadPool::createThreadTaskTag();

                for(sal_Int32 a(0); a < nThreadCount; a++)
                {
                    std::unique_ptr<processor3d::ZBufferProcessor3D> pNewZBufferProcessor3D(new processor3d::ZBufferProcessor3D(
                        aViewInformation3D,
                        getSdrSceneAttribute(),
                        getSdrLightingAttribute(),
                        aUnitVisibleRange,
                        nOversampleValue,
                        fFullViewSizeX,
                        fFullViewSizeY,
                        aBZPixelRaster,
                        nLinesPerThread * a,
                        a + 1 == nThreadCount ? aBZPixelRaster.getHeight() : nLinesPerThread * (a + 1)));
                    std::unique_ptr<Executor> pExecutor(new Executor(aTag, std::move(pNewZBufferProcessor3D), getChildren3D()));
                    rThreadPool.pushTask(std::move(pExecutor));
                }

                rThreadPool.waitUntilDone(aTag);
            }
            else
            {
                // use default 3D primitive processor to create BitmapEx for aUnitVisiblePart and process
                processor3d::ZBufferProcessor3D aZBufferProcessor3D(
                    aViewInformation3D,
                    getSdrSceneAttribute(),
                    getSdrLightingAttribute(),
                    aUnitVisibleRange,
                    nOversampleValue,
                    fFullViewSizeX,
                    fFullViewSizeY,
                    aBZPixelRaster,
                    0,
                    aBZPixelRaster.getHeight());

                aZBufferProcessor3D.process(getChildren3D());
                aZBufferProcessor3D.finish();
            }

            const_cast< ScenePrimitive2D* >(this)->maOldRenderedBitmap = BPixelRasterToBitmapEx(aBZPixelRaster, nOversampleValue);
            const Size aBitmapSizePixel(maOldRenderedBitmap.GetSizePixel());

            if(!(aBitmapSizePixel.getWidth() && aBitmapSizePixel.getHeight()))
                return;

            // create transform for the created bitmap in discrete coordinates first.
            basegfx::B2DHomMatrix aNew2DTransform;

            aNew2DTransform.set(0, 0, aVisibleDiscreteRange.getWidth());
            aNew2DTransform.set(1, 1, aVisibleDiscreteRange.getHeight());
            aNew2DTransform.set(0, 2, aVisibleDiscreteRange.getMinX());
            aNew2DTransform.set(1, 2, aVisibleDiscreteRange.getMinY());

            // transform back to world coordinates for usage in primitive creation
            aNew2DTransform *= aInverseOToV;

            // create bitmap primitive and add
            rContainer.push_back(
                new BitmapPrimitive2D(
                    VCLUnoHelper::CreateVCLXBitmap(maOldRenderedBitmap),
                    aNew2DTransform));

            // test: Allow to add an outline in the debugger when tests are needed
            static bool bAddOutlineToCreated3DSceneRepresentation(false); // loplugin:constvars:ignore

            if(bAddOutlineToCreated3DSceneRepresentation)
            {
                basegfx::B2DPolygon aOutline(basegfx::utils::createUnitPolygon());
                aOutline.transform(aNew2DTransform);
                rContainer.push_back(new PolygonHairlinePrimitive2D(aOutline, basegfx::BColor(1.0, 0.0, 0.0)));
            }
        }

        Primitive2DContainer ScenePrimitive2D::getGeometry2D() const
        {
            Primitive2DContainer aRetval;

            // create 2D projected geometry from 3D geometry
            if(!getChildren3D().empty())
            {
                // create 2D geometry extraction processor
                processor3d::Geometry2DExtractingProcessor aGeometryProcessor(
                    getViewInformation3D(),
                    getObjectTransformation());

                // process local primitives
                aGeometryProcessor.process(getChildren3D());

                // fetch result
                aRetval = aGeometryProcessor.getPrimitive2DSequence();
            }

            return aRetval;
        }

        Primitive2DContainer ScenePrimitive2D::getShadow2D() const
        {
            Primitive2DContainer aRetval;

            // create 2D shadows from contained 3D primitives
            if(impGetShadow3D())
            {
                // add extracted 2d shadows (before 3d scene creations itself)
                aRetval = maShadowPrimitives;
            }

            return aRetval;
        }

        bool ScenePrimitive2D::tryToCheckLastVisualisationDirectHit(const basegfx::B2DPoint& rLogicHitPoint, bool& o_rResult) const
        {
            if(maOldRenderedBitmap.IsEmpty() || maOldUnitVisiblePart.isEmpty())
                return false;

            basegfx::B2DHomMatrix aInverseSceneTransform(getObjectTransformation());
            aInverseSceneTransform.invert();
            const basegfx::B2DPoint aRelativePoint(aInverseSceneTransform * rLogicHitPoint);

            if(!maOldUnitVisiblePart.isInside(aRelativePoint))
                return false;

            // calculate coordinates relative to visualized part
            double fDivisorX(maOldUnitVisiblePart.getWidth());
            double fDivisorY(maOldUnitVisiblePart.getHeight());

            if(basegfx::fTools::equalZero(fDivisorX))
            {
                fDivisorX = 1.0;
            }

            if(basegfx::fTools::equalZero(fDivisorY))
            {
                fDivisorY = 1.0;
            }

            const double fRelativeX((aRelativePoint.getX() - maOldUnitVisiblePart.getMinX()) / fDivisorX);
            const double fRelativeY((aRelativePoint.getY() - maOldUnitVisiblePart.getMinY()) / fDivisorY);

            // combine with real BitmapSizePixel to get bitmap coordinates
            const Size aBitmapSizePixel(maOldRenderedBitmap.GetSizePixel());
            const sal_Int32 nX(basegfx::fround(fRelativeX * aBitmapSizePixel.Width()));
            const sal_Int32 nY(basegfx::fround(fRelativeY * aBitmapSizePixel.Height()));

            // try to get a statement about transparency in that pixel
            o_rResult = (0 != maOldRenderedBitmap.GetAlpha(nX, nY));
            return true;
        }

        ScenePrimitive2D::ScenePrimitive2D(
            primitive3d::Primitive3DContainer aChildren3D,
            attribute::SdrSceneAttribute  aSdrSceneAttribute,
            attribute::SdrLightingAttribute aSdrLightingAttribute,
            basegfx::B2DHomMatrix aObjectTransformation,
            geometry::ViewInformation3D aViewInformation3D)
        :   mxChildren3D(std::move(aChildren3D)),
            maSdrSceneAttribute(std::move(aSdrSceneAttribute)),
            maSdrLightingAttribute(std::move(aSdrLightingAttribute)),
            maObjectTransformation(std::move(aObjectTransformation)),
            maViewInformation3D(std::move(aViewInformation3D)),
            mbShadow3DChecked(false),
            mfOldDiscreteSizeX(0.0),
            mfOldDiscreteSizeY(0.0)
        {
        }

        bool ScenePrimitive2D::operator==(const BasePrimitive2D& rPrimitive) const
        {
            if(BufferedDecompositionPrimitive2D::operator==(rPrimitive))
            {
                const ScenePrimitive2D& rCompare = static_cast<const ScenePrimitive2D&>(rPrimitive);

                return (getChildren3D() == rCompare.getChildren3D()
                    && getSdrSceneAttribute() == rCompare.getSdrSceneAttribute()
                    && getSdrLightingAttribute() == rCompare.getSdrLightingAttribute()
                    && getObjectTransformation() == rCompare.getObjectTransformation()
                    && getViewInformation3D() == rCompare.getViewInformation3D());
            }

            return false;
        }

        basegfx::B2DRange ScenePrimitive2D::getB2DRange(const geometry::ViewInformation2D& rViewInformation) const
        {
            // transform unit range to discrete coordinate range
            basegfx::B2DRange aRetval(0.0, 0.0, 1.0, 1.0);
            aRetval.transform(rViewInformation.getObjectToViewTransformation() * getObjectTransformation());

            // force to discrete expanded bounds (it grows, so expanding works perfectly well)
            aRetval.expand(basegfx::B2DTuple(floor(aRetval.getMinX()), floor(aRetval.getMinY())));
            aRetval.expand(basegfx::B2DTuple(ceil(aRetval.getMaxX()), ceil(aRetval.getMaxY())));

            // transform back from discrete (view) to world coordinates
            aRetval.transform(rViewInformation.getInverseObjectToViewTransformation());

            // expand by evtl. existing shadow primitives
            if(impGetShadow3D())
            {
                const basegfx::B2DRange aShadow2DRange(maShadowPrimitives.getB2DRange(rViewInformation));

                if(!aShadow2DRange.isEmpty())
                {
                    aRetval.expand(aShadow2DRange);
                }
            }

            return aRetval;
        }

        void ScenePrimitive2D::get2DDecomposition(Primitive2DDecompositionVisitor& rVisitor, const geometry::ViewInformation2D& rViewInformation) const
        {
            // get the involved ranges (see helper method calculateDiscreteSizes for details)
            basegfx::B2DRange aDiscreteRange;
            basegfx::B2DRange aUnitVisibleRange;
            bool bNeedNewDecomposition(false);
            bool bDiscreteSizesAreCalculated(false);

            if(!getBuffered2DDecomposition().empty())
            {
                basegfx::B2DRange aVisibleDiscreteRange;
                calculateDiscreteSizes(rViewInformation, aDiscreteRange, aVisibleDiscreteRange, aUnitVisibleRange);
                bDiscreteSizesAreCalculated = true;

                // needs to be painted when the new part is not part of the last
                // decomposition
                if(!maOldUnitVisiblePart.isInside(aUnitVisibleRange))
                {
                    bNeedNewDecomposition = true;
                }

                // display has changed and cannot be reused when resolution got bigger. It
                // can be reused when resolution got smaller, though.
                if(!bNeedNewDecomposition)
                {
                    if(basegfx::fTools::more(aDiscreteRange.getWidth(), mfOldDiscreteSizeX) ||
                        basegfx::fTools::more(aDiscreteRange.getHeight(), mfOldDiscreteSizeY))
                    {
                        bNeedNewDecomposition = true;
                    }
                }
            }

            if(bNeedNewDecomposition)
            {
                // conditions of last local decomposition have changed, delete
                const_cast< ScenePrimitive2D* >(this)->setBuffered2DDecomposition(Primitive2DContainer());
            }

            if(getBuffered2DDecomposition().empty())
            {
                if(!bDiscreteSizesAreCalculated)
                {
                    basegfx::B2DRange aVisibleDiscreteRange;
                    calculateDiscreteSizes(rViewInformation, aDiscreteRange, aVisibleDiscreteRange, aUnitVisibleRange);
                }

                // remember last used NewDiscreteSize and NewUnitVisiblePart
                ScenePrimitive2D* pThat = const_cast< ScenePrimitive2D* >(this);
                pThat->mfOldDiscreteSizeX = aDiscreteRange.getWidth();
                pThat->mfOldDiscreteSizeY = aDiscreteRange.getHeight();
                pThat->maOldUnitVisiblePart = aUnitVisibleRange;
            }

            // use parent implementation
            BufferedDecompositionPrimitive2D::get2DDecomposition(rVisitor, rViewInformation);
        }

        // provide unique ID
        sal_uInt32 ScenePrimitive2D::getPrimitive2DID() const
        {
            return PRIMITIVE2D_ID_SCENEPRIMITIVE2D;
        }

} // end of namespace

/* vim:set shiftwidth=4 softtabstop=4 expandtab: */