xref: /aosp_15_r20/external/skia/src/gpu/graphite/ClipStack_graphite.h (revision c8dee2aa9b3f27cf6c858bd81872bdeb2c07ed17)
1 /*
2  * Copyright 2022 Google LLC
3  *
4  * Use of this source code is governed by a BSD-style license that can be
5  * found in the LICENSE file.
6  */
7 
8 #ifndef skgpu_graphite_ClipStack_DEFINED
9 #define skgpu_graphite_ClipStack_DEFINED
10 
11 #include "include/core/SkClipOp.h"
12 #include "include/private/base/SkTArray.h"
13 #include "src/base/SkTBlockList.h"
14 #include "src/gpu/graphite/DrawOrder.h"
15 #include "src/gpu/graphite/DrawParams.h"
16 #include "src/gpu/graphite/geom/Shape.h"
17 #include "src/gpu/graphite/geom/Transform_graphite.h"
18 
19 class SkShader;
20 class SkStrokeRec;
21 
22 namespace skgpu::graphite {
23 
24 class BoundsManager;
25 class Device;
26 class Geometry;
27 
28 // TODO: Port over many of the unit tests for skgpu/v1/ClipStack defined in GrClipStackTest since
29 // those tests do a thorough job of enumerating the different element combinations.
30 class ClipStack {
31 public:
32     // TODO: Some of these states reflect what SkDevice requires. Others are based on what Ganesh
33     // could handle analytically. They will likely change as graphite's clips are sorted out
34     enum class ClipState : uint8_t {
35         kEmpty, kWideOpen, kDeviceRect, kDeviceRRect, kComplex
36     };
37 
38     // All data describing a geometric modification to the clip
39     struct Element {
40         Shape     fShape;
41         Transform fLocalToDevice; // TODO: reference a cached Transform like DrawList?
42         SkClipOp  fOp;
43     };
44 
45     // 'owningDevice' must outlive the clip stack.
46     ClipStack(Device* owningDevice);
47 
48     ~ClipStack();
49 
50     ClipStack(const ClipStack&) = delete;
51     ClipStack& operator=(const ClipStack&) = delete;
52 
clipState()53     ClipState clipState() const { return this->currentSaveRecord().state(); }
maxDeferredClipDraws()54     int maxDeferredClipDraws() const { return fElements.count(); }
55     Rect conservativeBounds() const;
56 
57     class ElementIter;
58     // Provides for-range over active, valid clip elements from most recent to oldest.
59     // The iterator provides items as "const Element&".
60     inline ElementIter begin() const;
61     inline ElementIter end() const;
62 
63     // Clip stack manipulation
64     void save();
65     void restore();
66 
67     // The clip stack does not have a notion of AA vs. non-AA. However, if PixelSnapping::kYes is
68     // used and the right conditions are met, it can adjust the clip geometry to align with the
69     // pixel grid and emulate some aspects of non-AA behavior.
70     enum class PixelSnapping : bool {
71         kNo = false,
72         kYes = true
73     };
74     void clipShape(const Transform& localToDevice, const Shape& shape, SkClipOp op,
75                    PixelSnapping = PixelSnapping::kNo);
76     void clipShader(sk_sp<SkShader> shader);
77 
78     // Compute the bounds and the effective elements of the clip stack when applied to the draw
79     // described by the provided transform, shape, and stroke.
80     //
81     // Applying clips to a draw is a mostly lazy operation except for what is returned:
82     //  - The Clip's scissor is set to 'conservativeBounds()'.
83     //  - The Clip stores the draw's clipped bounds, taking into account its transform, styling, and
84     //    the above scissor.
85     //  - The Clip also stores the draw's fill-style invariant clipped bounds which is used in atlas
86     //    draws and may differ from the draw bounds.
87     //
88     // All clip elements that affect the draw will be returned in `outEffectiveElements` alongside
89     // the bounds. This method does not have any side-effects and the per-clip element state has to
90     // be explicitly updated by calling `updateClipStateForDraw()` which prepares the clip stack for
91     // later rendering.
92     //
93     // The returned clip element list will be empty if the shape is clipped out or if the draw is
94     // unaffected by any of the clip elements.
95     using ElementList = skia_private::STArray<4, const Element*>;
96     Clip visitClipStackForDraw(const Transform&,
97                                const Geometry&,
98                                const SkStrokeRec&,
99                                bool outsetBoundsForAA,
100                                ElementList* outEffectiveElements) const;
101 
102     // Update the per-clip element state for later rendering using pre-computed clip state data for
103     // a particular draw. The provided 'z' value is the depth value that the draw will use if it's
104     // not clipped out entirely.
105     //
106     // The returned CompressedPaintersOrder is the largest order that will be used by any of the
107     // clip elements that affect the draw.
108     //
109     // If the provided `clipState` indicates that the draw will be clipped out, then this method has
110     // no effect and returns DrawOrder::kNoIntersection.
111     CompressedPaintersOrder updateClipStateForDraw(const Clip& clip,
112                                                    const ElementList& effectiveElements,
113                                                    const BoundsManager*,
114                                                    PaintersDepth z);
115 
116     void recordDeferredClipDraws();
117 
118 private:
119     // SaveRecords and Elements are stored in two parallel stacks. The top-most SaveRecord is the
120     // active record, older records represent earlier save points and aren't modified until they
121     // become active again. Elements may be owned by the active SaveRecord, in which case they are
122     // fully mutable, or they may be owned by a prior SaveRecord. However, Elements from both the
123     // active SaveRecord and older records can be valid and affect draw operations. Elements are
124     // marked inactive when new elements are determined to supersede their effect completely.
125     // Inactive elements of the active SaveRecord can be deleted immediately; inactive elements of
126     // older SaveRecords may become active again as the save stack is popped back.
127     //
128     // See go/grclipstack-2.0 for additional details and visualization of the data structures.
129     class SaveRecord;
130 
131     // Internally, a lot of clip reasoning is based on an op, outer bounds, and whether a shape
132     // contains another (possibly just conservatively based on inner/outer device-space bounds).
133     // Element and SaveRecord store this information directly. A draw is equivalent to a clip
134     // element with the intersection op. TransformedShape is a lightweight wrapper that can convert
135     // these different types into a common type that Simplify() can reason about.
136     struct TransformedShape;
137     // This captures which of the two elements in (A op B) would be required when they are combined,
138     // where op is intersect or difference.
139     enum class SimplifyResult {
140         kEmpty,
141         kAOnly,
142         kBOnly,
143         kBoth
144     };
145     static SimplifyResult Simplify(const TransformedShape& a, const TransformedShape& b);
146 
147     // Wraps the geometric Element data with logic for containment and bounds testing.
148     class RawElement : public Element {
149     public:
150         using Stack = SkTBlockList<RawElement, 1>;
151 
152         RawElement(const Rect& deviceBounds,
153                    const Transform& localToDevice,
154                    const Shape& shape,
155                    SkClipOp op,
156                    PixelSnapping);
157 
~RawElement()158         ~RawElement() {
159             // A pending draw means the element affects something already recorded, so its own
160             // shape needs to be recorded as a draw. Since recording requires the Device (and
161             // DrawContext), it must happen before we destroy the element itself.
162             SkASSERT(!this->hasPendingDraw());
163         }
164 
165         // Silence warnings about implicit copy ctor/assignment because we're declaring a dtor
166         RawElement(const RawElement&) = default;
167         RawElement& operator=(const RawElement&) = default;
168 
169         operator TransformedShape() const;
170 
hasPendingDraw()171         bool             hasPendingDraw() const { return fOrder != DrawOrder::kNoIntersection; }
shape()172         const Shape&     shape()          const { return fShape;         }
localToDevice()173         const Transform& localToDevice()  const { return fLocalToDevice; }
outerBounds()174         const Rect&      outerBounds()    const { return fOuterBounds;   }
innerBounds()175         const Rect&      innerBounds()    const { return fInnerBounds;   }
op()176         SkClipOp         op()             const { return fOp;            }
177         ClipState        clipType()       const;
178 
179         // As new elements are pushed on to the stack, they may make older elements redundant.
180         // The old elements are marked invalid so they are skipped during clip application, but may
181         // become active again when a save record is restored.
isInvalid()182         bool isInvalid() const { return fInvalidatedByIndex >= 0; }
183         void markInvalid(const SaveRecord& current);
184         void restoreValid(const SaveRecord& current);
185 
186         // 'added' represents a new op added to the element stack. Its combination with this element
187         // can result in a number of possibilities:
188         //  1. The entire clip is empty (signaled by both this and 'added' being invalidated).
189         //  2. The 'added' op supercedes this element (this element is invalidated).
190         //  3. This op supercedes the 'added' element (the added element is marked invalidated).
191         //  4. Their combination can be represented by a single new op (in which case this
192         //     element should be invalidated, and the combined shape stored in 'added').
193         //  5. Or both elements remain needed to describe the clip (both are valid and unchanged).
194         //
195         // The calling element will only modify its invalidation index since it could belong
196         // to part of the inactive stack (that might be restored later). All merged state/geometry
197         // is handled by modifying 'added'.
198         void updateForElement(RawElement* added, const SaveRecord& current);
199 
200         // Returns how this element affects the draw after more detailed analysis.
201         enum class DrawInfluence {
202             kNone,       // The element does not affect the draw
203             kClipOut,    // The element causes the draw shape to be entirely clipped out
204             kIntersect,  // The element intersects the draw shape in a complex way
205         };
206         DrawInfluence testForDraw(const TransformedShape& draw) const;
207 
208         // Updates usage tracking to incorporate the bounds and Z value for the new draw call.
209         // If this element hasn't affected any prior draws, it will use the bounds manager to
210         // assign itself a compressed painters order for later rendering.
211         //
212         // This method assumes that this element affects the draw in a complex way, such that
213         // calling `testForDraw()` on the same draw would return `DrawInfluence::kIntersect`. It is
214         // assumed that `testForDraw()` was called beforehand to ensure that this is the case.
215         //
216         // Assuming that this element does not clip out the draw, returns the painters order the
217         // draw must sort after.
218         CompressedPaintersOrder updateForDraw(const BoundsManager* boundsManager,
219                                               const Rect& drawBounds,
220                                               PaintersDepth drawZ);
221 
222         // Record a depth-only draw to the given device, restricted to the portion of the clip that
223         // is actually required based on prior recorded draws. Resets usage tracking for subsequent
224         // passes.
225         void drawClip(Device*);
226 
227         void validate() const;
228 
229     private:
230         // TODO: Should only combine elements within the same save record, that don't have pending
231         // draws already. Otherwise, we're changing the geometry that will be rasterized and it
232         // could lead to gaps even if in a perfect the world the analytically intersected shape was
233         // equivalent. Can't combine with other save records, since they *might* become pending
234         // later on.
235         bool combine(const RawElement& other, const SaveRecord& current);
236 
237         // Device space bounds. These bounds are not snapped to pixels with the assumption that if
238         // a relation (intersects, contains, etc.) is true for the bounds it will be true for the
239         // rasterization of the coordinates that produced those bounds.
240         Rect fInnerBounds;
241         Rect fOuterBounds;
242         // TODO: Convert fOuterBounds to a ComplementRect to make intersection tests faster?
243         // Would need to store both original and complement, since the intersection test is
244         // Rect + ComplementRect and Element/SaveRecord could be on either side of operation.
245 
246         // State tracking how this clip element needs to be recorded into the draw context. As the
247         // clip stack is applied to additional draws, the clip's Z and usage bounds grow to account
248         // for it; its compressed painter's order is selected the first time a draw is affected.
249         Rect fUsageBounds;
250         CompressedPaintersOrder fOrder;
251         PaintersDepth fMaxZ;
252 
253         // Elements are invalidated by SaveRecords as the record is updated with new elements that
254         // override old geometry. An invalidated element stores the index of the first element of
255         // the save record that invalidated it. This makes it easy to undo when the save record is
256         // popped from the stack, and is stable as the current save record is modified.
257         int fInvalidatedByIndex;
258     };
259 
260     // Represents a saved point in the clip stack, and manages the life time of elements added to
261     // stack within the record's life time. Also provides the logic for determining active elements
262     // given a draw query.
263     class SaveRecord {
264     public:
265         using Stack = SkTBlockList<SaveRecord, 2>;
266 
267         explicit SaveRecord(const Rect& deviceBounds);
268 
269         SaveRecord(const SaveRecord& prior, int startingElementIndex);
270 
shader()271         const SkShader* shader()      const { return fShader.get(); }
outerBounds()272         const Rect&     outerBounds() const { return fOuterBounds;  }
innerBounds()273         const Rect&     innerBounds() const { return fInnerBounds;  }
op()274         SkClipOp        op()          const { return fStackOp;      }
275         ClipState       state()       const;
276 
firstActiveElementIndex()277         int  firstActiveElementIndex() const { return fStartingElementIndex;     }
oldestElementIndex()278         int  oldestElementIndex()      const { return fOldestValidIndex;         }
canBeUpdated()279         bool canBeUpdated()            const { return (fDeferredSaveCount == 0); }
280 
281         Rect scissor(const Rect& deviceBounds, const Rect& drawBounds) const;
282 
283         // Deferred save manipulation
pushSave()284         void pushSave() {
285             SkASSERT(fDeferredSaveCount >= 0);
286             fDeferredSaveCount++;
287         }
288         // Returns true if the record should stay alive. False means the ClipStack must delete it
popSave()289         bool popSave() {
290             fDeferredSaveCount--;
291             SkASSERT(fDeferredSaveCount >= -1);
292             return fDeferredSaveCount >= 0;
293         }
294 
295         // Return true if the element was added to 'elements', or otherwise affected the save record
296         // (e.g. turned it empty).
297         bool addElement(RawElement&& toAdd, RawElement::Stack* elements, Device*);
298 
299         void addShader(sk_sp<SkShader> shader);
300 
301         // Remove the elements owned by this save record, which must happen before the save record
302         // itself is removed from the clip stack. Records draws for any removed elements that have
303         // draw usages.
304         void removeElements(RawElement::Stack* elements, Device*);
305 
306         // Restore element validity now that this record is the new top of the stack.
307         void restoreElements(RawElement::Stack* elements);
308 
309     private:
310         // These functions modify 'elements' and element-dependent state of the record
311         // (such as valid index and fState). Records draws for any clips that have deferred usages
312         // that are inactivated and cannot be restored (i.e. part of the active save record).
313         bool appendElement(RawElement&& toAdd, RawElement::Stack* elements, Device*);
314         void replaceWithElement(RawElement&& toAdd, RawElement::Stack* elements, Device*);
315 
316         // Inner bounds is always contained in outer bounds, or it is empty. All bounds will be
317         // contained in the device bounds.
318         Rect fInnerBounds; // Inside is full coverage (stack op == intersect) or 0 cov (diff)
319         Rect fOuterBounds; // Outside is 0 coverage (op == intersect) or full cov (diff)
320 
321         // A save record can have up to one shader, multiple shaders are automatically blended
322         sk_sp<SkShader> fShader;
323 
324         const int fStartingElementIndex; // First element owned by this save record
325         int       fOldestValidIndex;     // Index of oldest element that's valid for this record
326         int       fDeferredSaveCount;    // Number of save() calls without modifications (yet)
327 
328         // Will be kIntersect unless every valid element is kDifference, which is significant
329         // because if kDifference then there is an implicit extra outer bounds at the device edges.
330         SkClipOp  fStackOp;
331         ClipState fState;
332     };
333 
334     Rect deviceBounds() const;
335 
currentSaveRecord()336     const SaveRecord& currentSaveRecord() const {
337         SkASSERT(!fSaves.empty());
338         return fSaves.back();
339     }
340 
341     // Will return the current save record, properly updating deferred saves
342     // and initializing a first record if it were empty.
343     SaveRecord& writableSaveRecord(bool* wasDeferred);
344 
345     RawElement::Stack fElements;
346     SaveRecord::Stack fSaves; // always has one wide open record at the top
347 
348     Device* fDevice; // the device this clip stack is coupled with
349 };
350 
351 // Clip element iteration
352 class ClipStack::ElementIter {
353 public:
354     bool operator!=(const ElementIter& o) const {
355         return o.fItem != fItem && o.fRemaining != fRemaining;
356     }
357 
358     const Element& operator*() const { return *fItem; }
359 
360     ElementIter& operator++() {
361         // Skip over invalidated elements
362         do {
363             fRemaining--;
364             ++fItem;
365         } while(fRemaining > 0 && (*fItem).isInvalid());
366 
367         return *this;
368     }
369 
ElementIter(RawElement::Stack::CRIter::Item item,int r)370     ElementIter(RawElement::Stack::CRIter::Item item, int r) : fItem(item), fRemaining(r) {}
371 
372     RawElement::Stack::CRIter::Item fItem;
373     int fRemaining;
374 
375     friend class ClipStack;
376 };
377 
begin()378 ClipStack::ElementIter ClipStack::begin() const {
379     if (this->currentSaveRecord().state() == ClipState::kEmpty ||
380         this->currentSaveRecord().state() == ClipState::kWideOpen) {
381         // No visible clip elements when empty or wide open
382         return this->end();
383     }
384     int count = fElements.count() - this->currentSaveRecord().oldestElementIndex();
385     return ElementIter(fElements.ritems().begin(), count);
386 }
387 
end()388 ClipStack::ElementIter ClipStack::end() const {
389     return ElementIter(fElements.ritems().end(), 0);
390 }
391 
392 } // namespace skgpu::graphite
393 
394 #endif // skgpu_graphite_ClipStack_DEFINED
395