Coverage Report

Created: 2025-12-08 09:28

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/libreoffice/drawinglayer/source/primitive2d/glowprimitive2d.cxx
Line
Count
Source
1
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
2
/*
3
 * This file is part of the LibreOffice project.
4
 *
5
 * This Source Code Form is subject to the terms of the Mozilla Public
6
 * License, v. 2.0. If a copy of the MPL was not distributed with this
7
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
8
 *
9
 * This file incorporates work covered by the following license notice:
10
 *
11
 *   Licensed to the Apache Software Foundation (ASF) under one or more
12
 *   contributor license agreements. See the NOTICE file distributed
13
 *   with this work for additional information regarding copyright
14
 *   ownership. The ASF licenses this file to you under the Apache
15
 *   License, Version 2.0 (the "License"); you may not use this file
16
 *   except in compliance with the License. You may obtain a copy of
17
 *   the License at http://www.apache.org/licenses/LICENSE-2.0 .
18
 */
19
20
#include <drawinglayer/primitive2d/glowprimitive2d.hxx>
21
#include <drawinglayer/primitive2d/transformprimitive2d.hxx>
22
#include <drawinglayer/primitive2d/drawinglayer_primitivetypes2d.hxx>
23
#include <drawinglayer/primitive2d/bitmapprimitive2d.hxx>
24
#include <basegfx/matrix/b2dhommatrixtools.hxx>
25
#include <drawinglayer/converters.hxx>
26
#include "GlowSoftEgdeShadowTools.hxx"
27
28
#ifdef DBG_UTIL
29
#include <o3tl/environment.hxx>
30
#include <tools/stream.hxx>
31
#include <vcl/filter/PngImageWriter.hxx>
32
#endif
33
34
using namespace com::sun::star;
35
36
namespace drawinglayer::primitive2d
37
{
38
GlowPrimitive2D::GlowPrimitive2D(const Color& rGlowColor, double fRadius,
39
                                 Primitive2DContainer&& rChildren)
40
0
    : BufferedDecompositionGroupPrimitive2D(std::move(rChildren))
41
0
    , maGlowColor(rGlowColor)
42
0
    , mfGlowRadius(fRadius)
43
0
    , mfLastDiscreteGlowRadius(0.0)
44
0
    , maLastClippedRange()
45
0
{
46
    // activate callback to flush buffered decomposition content
47
0
    activateFlushOnTimer();
48
0
}
49
50
bool GlowPrimitive2D::operator==(const BasePrimitive2D& rPrimitive) const
51
0
{
52
0
    if (BufferedDecompositionGroupPrimitive2D::operator==(rPrimitive))
53
0
    {
54
0
        const GlowPrimitive2D& rCompare = static_cast<const GlowPrimitive2D&>(rPrimitive);
55
56
0
        return (getGlowRadius() == rCompare.getGlowRadius()
57
0
                && getGlowColor() == rCompare.getGlowColor());
58
0
    }
59
60
0
    return false;
61
0
}
62
63
bool GlowPrimitive2D::prepareValuesAndcheckValidity(
64
    basegfx::B2DRange& rGlowRange, basegfx::B2DRange& rClippedRange,
65
    basegfx::B2DVector& rDiscreteGlowSize, double& rfDiscreteGlowRadius,
66
    const geometry::ViewInformation2D& rViewInformation) const
67
0
{
68
    // no GlowRadius defined, done
69
0
    if (getGlowRadius() <= 0.0)
70
0
        return false;
71
72
    // no geometry, done
73
0
    if (getChildren().empty())
74
0
        return false;
75
76
    // no pixel target, done
77
0
    if (rViewInformation.getObjectToViewTransformation().isIdentity())
78
0
        return false;
79
80
    // get geometry range that defines area that needs to be pixelated
81
0
    rGlowRange = getChildren().getB2DRange(rViewInformation);
82
83
    // no range of geometry, done
84
0
    if (rGlowRange.isEmpty())
85
0
        return false;
86
87
    // extend range by GlowRadius in all directions
88
0
    rGlowRange.grow(getGlowRadius());
89
90
    // initialize ClippedRange to full GlowRange -> all is visible
91
0
    rClippedRange = rGlowRange;
92
93
    // get Viewport and check if used. If empty, all is visible (see
94
    // ViewInformation2D definition in viewinformation2d.hxx)
95
0
    if (!rViewInformation.getViewport().isEmpty())
96
0
    {
97
        // if used, extend by GlowRadius to ensure needed parts are included
98
0
        basegfx::B2DRange aVisibleArea(rViewInformation.getViewport());
99
0
        aVisibleArea.grow(getGlowRadius());
100
101
        // To do this correctly, it needs to be done in discrete coordinates.
102
        // The object may be transformed relative to the original#
103
        // ObjectTransformation, e.g. when re-used in shadow
104
0
        aVisibleArea.transform(rViewInformation.getViewTransformation());
105
0
        rClippedRange.transform(rViewInformation.getObjectToViewTransformation());
106
107
        // calculate ClippedRange
108
0
        rClippedRange.intersect(aVisibleArea);
109
110
        // if GlowRange is completely outside of VisibleArea, ClippedRange
111
        // will be empty and we are done
112
0
        if (rClippedRange.isEmpty())
113
0
            return false;
114
115
        // convert result back to object coordinates
116
0
        rClippedRange.transform(rViewInformation.getInverseObjectToViewTransformation());
117
0
    }
118
119
    // calculate discrete pixel size of GlowRange. If it's too small to visualize, we are done
120
0
    rDiscreteGlowSize = rViewInformation.getObjectToViewTransformation() * rGlowRange.getRange();
121
0
    if (ceil(rDiscreteGlowSize.getX()) < 2.0 || ceil(rDiscreteGlowSize.getY()) < 2.0)
122
0
        return false;
123
124
    // calculate discrete pixel size of GlowRadius. If it's too small to visualize, we are done
125
0
    rfDiscreteGlowRadius = ceil(
126
0
        (rViewInformation.getObjectToViewTransformation() * basegfx::B2DVector(getGlowRadius(), 0))
127
0
            .getLength());
128
0
    if (rfDiscreteGlowRadius < 1.0)
129
0
        return false;
130
131
0
    return true;
132
0
}
133
134
void GlowPrimitive2D::create2DDecomposition(
135
    Primitive2DContainer& rContainer, const geometry::ViewInformation2D& rViewInformation) const
136
0
{
137
0
    basegfx::B2DRange aGlowRange;
138
0
    basegfx::B2DRange aClippedRange;
139
0
    basegfx::B2DVector aDiscreteGlowSize;
140
0
    double fDiscreteGlowRadius(0.0);
141
142
    // Check various validity details and calculate/prepare values. If false, we are done
143
0
    if (!prepareValuesAndcheckValidity(aGlowRange, aClippedRange, aDiscreteGlowSize,
144
0
                                       fDiscreteGlowRadius, rViewInformation))
145
0
        return;
146
147
    // Create embedding transformation from object to top-left zero-aligned
148
    // target pixel geometry (discrete form of ClippedRange)
149
    // First, move to top-left of GlowRange
150
0
    const sal_uInt32 nDiscreteGlowWidth(ceil(aDiscreteGlowSize.getX()));
151
0
    const sal_uInt32 nDiscreteGlowHeight(ceil(aDiscreteGlowSize.getY()));
152
0
    basegfx::B2DHomMatrix aEmbedding(basegfx::utils::createTranslateB2DHomMatrix(
153
0
        -aClippedRange.getMinX(), -aClippedRange.getMinY()));
154
    // Second, scale to discrete bitmap size
155
    // Even when using the offset from ClippedRange, we need to use the
156
    // scaling from the full representation, thus from GlowRange
157
0
    aEmbedding.scale(nDiscreteGlowWidth / aGlowRange.getWidth(),
158
0
                     nDiscreteGlowHeight / aGlowRange.getHeight());
159
160
    // Embed content graphics to TransformPrimitive2D
161
0
    const primitive2d::Primitive2DReference xEmbedRef(
162
0
        new primitive2d::TransformPrimitive2D(aEmbedding, Primitive2DContainer(getChildren())));
163
0
    primitive2d::Primitive2DContainer xEmbedSeq{ xEmbedRef };
164
165
    // Create Bitmap using drawinglayer tooling, including a MaximumQuadraticPixel
166
    // limitation to be safe and not go runtime/memory havoc. Use a pretty small
167
    // limit due to this is glow functionality and will look good with bitmap scaling
168
    // anyways. The value of 250.000 square pixels below maybe adapted as needed.
169
0
    const basegfx::B2DVector aDiscreteClippedSize(rViewInformation.getObjectToViewTransformation()
170
0
                                                  * aClippedRange.getRange());
171
0
    const sal_uInt32 nDiscreteClippedWidth(ceil(aDiscreteClippedSize.getX()));
172
0
    const sal_uInt32 nDiscreteClippedHeight(ceil(aDiscreteClippedSize.getY()));
173
0
    const geometry::ViewInformation2D aViewInformation2D;
174
0
    const sal_uInt32 nMaximumQuadraticPixels(250000);
175
176
    // I have now added a helper that just creates the mask without having
177
    // to render the content, use it, it's faster
178
0
    const AlphaMask aAlpha(::drawinglayer::createAlphaMask(
179
0
        std::move(xEmbedSeq), aViewInformation2D, nDiscreteClippedWidth, nDiscreteClippedHeight,
180
0
        nMaximumQuadraticPixels));
181
182
0
    if (aAlpha.IsEmpty())
183
0
        return;
184
185
0
    const Size aBitmapExSizePixel(aAlpha.GetSizePixel());
186
187
0
    if (aBitmapExSizePixel.Width() <= 0 || aBitmapExSizePixel.Height() <= 0)
188
0
        return;
189
190
    // We may have to take a corrective scaling into account when the
191
    // MaximumQuadraticPixel limit was used/triggered
192
0
    double fScale(1.0);
193
194
0
    if (static_cast<sal_uInt32>(aBitmapExSizePixel.Width()) != nDiscreteClippedWidth
195
0
        || static_cast<sal_uInt32>(aBitmapExSizePixel.Height()) != nDiscreteClippedHeight)
196
0
    {
197
        // scale in X and Y should be the same (see fReduceFactor in createAlphaMask),
198
        // so adapt numerically to a single scale value, they are integer rounded values
199
0
        const double fScaleX(static_cast<double>(aBitmapExSizePixel.Width())
200
0
                             / static_cast<double>(nDiscreteClippedWidth));
201
0
        const double fScaleY(static_cast<double>(aBitmapExSizePixel.Height())
202
0
                             / static_cast<double>(nDiscreteClippedHeight));
203
204
0
        fScale = (fScaleX + fScaleY) * 0.5;
205
0
    }
206
207
    // fDiscreteGlowRadius is the size of the halo from each side of the object. The halo is the
208
    // border of glow color that fades from glow transparency level to fully transparent
209
    // When blurring a sharp boundary (our case), it gets 50% of original intensity, and
210
    // fades to both sides by the blur radius; thus blur radius is half of glow radius.
211
    // Consider glow transparency (initial transparency near the object edge)
212
0
    AlphaMask mask(ProcessAndBlurAlphaMask(aAlpha, fDiscreteGlowRadius * fScale / 2.0,
213
0
                                           fDiscreteGlowRadius * fScale / 2.0,
214
0
                                           255 - getGlowColor().GetAlpha()));
215
216
    // The end result is the bitmap filled with glow color and blurred 8-bit alpha mask
217
0
    Bitmap bmp(aAlpha.GetSizePixel(), vcl::PixelFormat::N24_BPP);
218
0
    bmp.Erase(getGlowColor());
219
0
    Bitmap result(bmp, mask);
220
221
#ifdef DBG_UTIL
222
    static bool bDoSaveForVisualControl(false); // loplugin:constvars:ignore
223
    if (bDoSaveForVisualControl)
224
    {
225
        // VCL_DUMP_BMP_PATH should be like C:/path/ or ~/path/
226
        static const OUString sDumpPath(o3tl::getEnvironment(u"VCL_DUMP_BMP_PATH"_ustr));
227
        if (!sDumpPath.isEmpty())
228
        {
229
            SvFileStream aNew(sDumpPath + "test_glow.png", StreamMode::WRITE | StreamMode::TRUNC);
230
            vcl::PngImageWriter aPNGWriter(aNew);
231
            aPNGWriter.write(result);
232
        }
233
    }
234
#endif
235
236
    // Independent from discrete sizes of glow alpha creation, always
237
    // map and project glow result to geometry range extended by glow
238
    // radius, but to the eventually clipped instance (ClippedRange)
239
0
    const primitive2d::Primitive2DReference xEmbedRefBitmap(
240
0
        new BitmapPrimitive2D(result, basegfx::utils::createScaleTranslateB2DHomMatrix(
241
0
                                          aClippedRange.getWidth(), aClippedRange.getHeight(),
242
0
                                          aClippedRange.getMinX(), aClippedRange.getMinY())));
243
244
0
    rContainer = primitive2d::Primitive2DContainer{ xEmbedRefBitmap };
245
0
}
246
247
// Using tooling class BufferedDecompositionGroupPrimitive2D now, so
248
// no more need to locally do the buffered get2DDecomposition here,
249
// see BufferedDecompositionGroupPrimitive2D::get2DDecomposition
250
void GlowPrimitive2D::get2DDecomposition(Primitive2DDecompositionVisitor& rVisitor,
251
                                         const geometry::ViewInformation2D& rViewInformation) const
252
0
{
253
0
    basegfx::B2DRange aGlowRange;
254
0
    basegfx::B2DRange aClippedRange;
255
0
    basegfx::B2DVector aDiscreteGlowSize;
256
0
    double fDiscreteGlowRadius(0.0);
257
258
    // Check various validity details and calculate/prepare values. If false, we are done
259
0
    if (!prepareValuesAndcheckValidity(aGlowRange, aClippedRange, aDiscreteGlowSize,
260
0
                                       fDiscreteGlowRadius, rViewInformation))
261
0
        return;
262
263
0
    if (hasBuffered2DDecomposition())
264
0
    {
265
        // First check is to detect if the last created decompose is capable
266
        // to represent the now requested visualization.
267
        // ClippedRange is the needed visualizationArea for the current glow
268
        // effect, LastClippedRange is the one from the existing/last rendering.
269
        // Check if last created area is sufficient and can be re-used
270
0
        if (!maLastClippedRange.isEmpty() && !maLastClippedRange.isInside(aClippedRange))
271
0
        {
272
            // To avoid unnecessary invalidations due to being *very* correct
273
            // with HairLines (which are view-dependent and thus change the
274
            // result(s) here slightly when changing zoom), add a slight unsharp
275
            // component if we have a ViewTransform. The derivation is inside
276
            // the range of half a pixel (due to one pixel hairline)
277
0
            basegfx::B2DRange aLastClippedRangeAndHairline(maLastClippedRange);
278
279
0
            if (!rViewInformation.getObjectToViewTransformation().isIdentity())
280
0
            {
281
                // Grow by view-dependent size of 1/2 pixel
282
0
                const double fHalfPixel((rViewInformation.getInverseObjectToViewTransformation()
283
0
                                         * basegfx::B2DVector(0.5, 0))
284
0
                                            .getLength());
285
0
                aLastClippedRangeAndHairline.grow(fHalfPixel);
286
0
            }
287
288
0
            if (!aLastClippedRangeAndHairline.isInside(aClippedRange))
289
0
            {
290
                // Conditions of last local decomposition have changed, delete
291
0
                const_cast<GlowPrimitive2D*>(this)->setBuffered2DDecomposition(
292
0
                    Primitive2DContainer());
293
0
            }
294
0
        }
295
0
    }
296
297
0
    if (hasBuffered2DDecomposition())
298
0
    {
299
        // Second check is to react on changes of the DiscreteGlowRadius when
300
        // zooming in/out.
301
        // Use the known last and current DiscreteGlowRadius to decide
302
        // if the visualization can be re-used. Be a little 'creative' here
303
        // and make it dependent on a *relative* change - it is not necessary
304
        // to re-create everytime if the exact value is missed since zooming
305
        // pixel-based glow effect is pretty good due to it's smooth nature
306
0
        bool bFree(mfLastDiscreteGlowRadius <= 0.0 || fDiscreteGlowRadius <= 0.0);
307
308
0
        if (!bFree)
309
0
        {
310
0
            const double fDiff(fabs(mfLastDiscreteGlowRadius - fDiscreteGlowRadius));
311
0
            const double fLen(fabs(mfLastDiscreteGlowRadius) + fabs(fDiscreteGlowRadius));
312
0
            const double fRelativeChange(fDiff / fLen);
313
314
            // Use lower fixed values here to change more often, higher to change less often.
315
            // Value is in the range of ]0.0 .. 1.0]
316
0
            bFree = fRelativeChange >= 0.15;
317
0
        }
318
319
0
        if (bFree)
320
0
        {
321
            // Conditions of last local decomposition have changed, delete
322
0
            const_cast<GlowPrimitive2D*>(this)->setBuffered2DDecomposition(Primitive2DContainer());
323
0
        }
324
0
    }
325
326
0
    if (!hasBuffered2DDecomposition())
327
0
    {
328
        // refresh last used DiscreteGlowRadius and ClippedRange to new remembered values
329
0
        const_cast<GlowPrimitive2D*>(this)->mfLastDiscreteGlowRadius = fDiscreteGlowRadius;
330
0
        const_cast<GlowPrimitive2D*>(this)->maLastClippedRange = aClippedRange;
331
0
    }
332
333
    // call parent, that will check for empty, call create2DDecomposition and
334
    // set as decomposition
335
0
    BufferedDecompositionGroupPrimitive2D::get2DDecomposition(rVisitor, rViewInformation);
336
0
}
337
338
basegfx::B2DRange
339
GlowPrimitive2D::getB2DRange(const geometry::ViewInformation2D& rViewInformation) const
340
0
{
341
    // Hint: Do *not* use GroupPrimitive2D::getB2DRange, that will (unnecessarily)
342
    // use the decompose - what works, but is not needed here.
343
    // We know the to-be-visualized geometry and the radius it needs to be extended,
344
    // so simply calculate the exact needed range.
345
0
    basegfx::B2DRange aRetval(getChildren().getB2DRange(rViewInformation));
346
347
    // We need additional space for the glow from all sides
348
0
    aRetval.grow(getGlowRadius());
349
350
0
    return aRetval;
351
0
}
352
353
// provide unique ID
354
0
sal_uInt32 GlowPrimitive2D::getPrimitive2DID() const { return PRIMITIVE2D_ID_GLOWPRIMITIVE2D; }
355
356
} // end of namespace
357
358
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */