• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright 2019 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 #ifndef GrQuadBuffer_DEFINED
8 #define GrQuadBuffer_DEFINED
9 
10 #include "include/private/SkTDArray.h"
11 #include "src/gpu/geometry/GrQuad.h"
12 
13 template<typename T>
14 class GrQuadBuffer {
15 public:
GrQuadBuffer()16     GrQuadBuffer()
17             : fCount(0)
18             , fDeviceType(GrQuad::Type::kAxisAligned)
19             , fLocalType(GrQuad::Type::kAxisAligned) {
20         // Pre-allocate space for 1 2D device-space quad, metadata, and header
21         fData.reserve(this->entrySize(fDeviceType, nullptr));
22     }
23 
24     // Reserves space for the given number of entries; if 'needsLocals' is true, space will be
25     // reserved for each entry to also have a 2D local quad. The reserved space assumes 2D device
26     // quad for simplicity. Since this buffer has a variable bitrate encoding for quads, this may
27     // over or under reserve, but pre-allocating still helps when possible.
28     GrQuadBuffer(int count, bool needsLocals = false)
29             : fCount(0)
30             , fDeviceType(GrQuad::Type::kAxisAligned)
31             , fLocalType(GrQuad::Type::kAxisAligned) {
32         int entrySize = this->entrySize(fDeviceType, needsLocals ? &fLocalType : nullptr);
33         fData.reserve(count * entrySize);
34     }
35 
36     // The number of device-space quads (and metadata, and optional local quads) that are in the
37     // the buffer.
count()38     int count() const { return fCount; }
39 
40     // The most general type for the device-space quads in this buffer
deviceQuadType()41     GrQuad::Type deviceQuadType() const { return fDeviceType; }
42 
43     // The most general type for the local quads; if no local quads are ever added, this will
44     // return kAxisAligned.
localQuadType()45     GrQuad::Type localQuadType() const { return fLocalType; }
46 
47     // Append the given 'deviceQuad' to this buffer, with its associated 'metadata'. If 'localQuad'
48     // is not null, the local coordinates will also be attached to the entry. When an entry
49     // has local coordinates, during iteration, the Iter::hasLocals() will return true and its
50     // Iter::localQuad() will be equivalent to the provided local coordinates. If 'localQuad' is
51     // null then Iter::hasLocals() will report false for the added entry.
52     void append(const GrQuad& deviceQuad, T&& metadata, const GrQuad* localQuad = nullptr);
53 
54     // Copies all entries from 'that' to this buffer
55     void concat(const GrQuadBuffer<T>& that);
56 
57     // Provides a read-only iterator over a quad buffer, giving access to the device quad, metadata
58     // and optional local quad.
59     class Iter {
60     public:
Iter(const GrQuadBuffer<T> * buffer)61         Iter(const GrQuadBuffer<T>* buffer)
62                 : fDeviceQuad(SkRect::MakeEmpty())
63                 , fLocalQuad(SkRect::MakeEmpty())
64                 , fBuffer(buffer)
65                 , fCurrentEntry(nullptr)
66                 , fNextEntry(buffer->fData.begin()) {
67             SkDEBUGCODE(fExpectedCount = buffer->count();)
68         }
69 
70         bool next();
71 
metadata()72         const T& metadata() const { this->validate(); return *(fBuffer->metadata(fCurrentEntry)); }
73 
deviceQuad()74         const GrQuad& deviceQuad() const { this->validate(); return fDeviceQuad; }
75 
76         // If isLocalValid() returns false, this returns an empty quad (all 0s) so that localQuad()
77         // can be called without triggering any sanitizers, for convenience when some other state
78         // ensures that the quad will eventually not be used.
localQuad()79         const GrQuad& localQuad() const {
80             this->validate();
81             return fLocalQuad;
82         }
83 
isLocalValid()84         bool isLocalValid() const {
85             this->validate();
86             return fBuffer->header(fCurrentEntry)->fHasLocals;
87         }
88 
89     private:
90         // Quads are stored locally so that calling code doesn't need to re-declare their own quads
91         GrQuad fDeviceQuad;
92         GrQuad fLocalQuad;
93 
94         const GrQuadBuffer<T>* fBuffer;
95         // The pointer to the current entry to read metadata/header details from
96         const char* fCurrentEntry;
97         // The pointer to replace fCurrentEntry when next() is called, cached since it is calculated
98         // automatically while unpacking the quad data.
99         const char* fNextEntry;
100 
SkDEBUGCODE(int fExpectedCount;)101         SkDEBUGCODE(int fExpectedCount;)
102 
103         void validate() const {
104             SkDEBUGCODE(fBuffer->validate(fCurrentEntry, fExpectedCount);)
105         }
106     };
107 
iterator()108     Iter iterator() const { return Iter(this); }
109 
110     // Provides a *mutable* iterator over just the metadata stored in the quad buffer. This skips
111     // unpacking the device and local quads into GrQuads and is intended for use during op
112     // finalization, which may require rewriting state such as color.
113     class MetadataIter {
114     public:
MetadataIter(GrQuadBuffer<T> * list)115         MetadataIter(GrQuadBuffer<T>* list)
116                 : fBuffer(list)
117                 , fCurrentEntry(nullptr) {
118             SkDEBUGCODE(fExpectedCount = list->count();)
119         }
120 
121         bool next();
122 
123         T& operator*() { this->validate(); return *(fBuffer->metadata(fCurrentEntry)); }
124 
125         T* operator->() { this->validate(); return fBuffer->metadata(fCurrentEntry); }
126 
127     private:
128         GrQuadBuffer<T>* fBuffer;
129         char* fCurrentEntry;
130 
SkDEBUGCODE(int fExpectedCount;)131         SkDEBUGCODE(int fExpectedCount;)
132 
133         void validate() const {
134             SkDEBUGCODE(fBuffer->validate(fCurrentEntry, fExpectedCount);)
135         }
136     };
137 
metadata()138     MetadataIter metadata() { return MetadataIter(this); }
139 
140 private:
141     struct alignas(int32_t) Header {
142         unsigned fDeviceType : 2;
143         unsigned fLocalType  : 2; // Ignore if fHasLocals is false
144         unsigned fHasLocals  : 1;
145         // Known value to detect if iteration doesn't properly advance through the buffer
146         SkDEBUGCODE(unsigned fSentinel : 27;)
147     };
148     static_assert(sizeof(Header) == sizeof(int32_t), "Header should be 4 bytes");
149 
150     static constexpr unsigned kSentinel = 0xbaffe;
151     static constexpr int kMetaSize = sizeof(Header) + sizeof(T);
152     static constexpr int k2DQuadFloats = 8;
153     static constexpr int k3DQuadFloats = 12;
154 
155     // Each logical entry in the buffer is a variable length tuple storing device coordinates,
156     // optional local coordinates, and metadata. An entry always has a header that defines the
157     // quad types of device and local coordinates, and always has metadata of type T. The device
158     // and local quads' data follows as a variable length array of floats:
159     //  [ header    ] = 4 bytes
160     //  [ metadata  ] = sizeof(T), assert alignof(T) == 4 so that pointer casts are valid
161     //  [ device xs ] = 4 floats = 16 bytes
162     //  [ device ys ] = 4 floats
163     //  [ device ws ] = 4 floats or 0 floats depending on fDeviceType in header
164     //  [ local xs  ] = 4 floats or 0 floats depending on fHasLocals in header
165     //  [ local ys  ] = 4 floats or 0 floats depending on fHasLocals in header
166     //  [ local ws  ] = 4 floats or 0 floats depending on fHasLocals and fLocalType in header
167     // FIXME (michaelludwig) - Since this is intended only for ops, can we use the arena to
168     //      allocate storage for the quad buffer? Since this is forward-iteration only, could also
169     //      explore a linked-list structure for concatenating quads when batching ops
170     SkTDArray<char> fData;
171 
172     int fCount; // Number of (device, local, metadata) entries
173     GrQuad::Type fDeviceType; // Most general type of all entries
174     GrQuad::Type fLocalType;
175 
entrySize(GrQuad::Type deviceType,const GrQuad::Type * localType)176     inline int entrySize(GrQuad::Type deviceType, const GrQuad::Type* localType) const {
177         int size = kMetaSize;
178         size += (deviceType == GrQuad::Type::kPerspective ? k3DQuadFloats
179                                                           : k2DQuadFloats) * sizeof(float);
180         if (localType) {
181             size += (*localType == GrQuad::Type::kPerspective ? k3DQuadFloats
182                                                               : k2DQuadFloats) * sizeof(float);
183         }
184         return size;
185     }
entrySize(const Header * header)186     inline int entrySize(const Header* header) const {
187         if (header->fHasLocals) {
188             GrQuad::Type localType = static_cast<GrQuad::Type>(header->fLocalType);
189             return this->entrySize(static_cast<GrQuad::Type>(header->fDeviceType), &localType);
190         } else {
191             return this->entrySize(static_cast<GrQuad::Type>(header->fDeviceType), nullptr);
192         }
193     }
194 
195     // Helpers to access typed sections of the buffer, given the start of an entry
header(char * entry)196     inline Header* header(char* entry) {
197         return static_cast<Header*>(static_cast<void*>(entry));
198     }
header(const char * entry)199     inline const Header* header(const char* entry) const {
200         return static_cast<const Header*>(static_cast<const void*>(entry));
201     }
202 
metadata(char * entry)203     inline T* metadata(char* entry) {
204         return static_cast<T*>(static_cast<void*>(entry + sizeof(Header)));
205     }
metadata(const char * entry)206     inline const T* metadata(const char* entry) const {
207         return static_cast<const T*>(static_cast<const void*>(entry + sizeof(Header)));
208     }
209 
coords(char * entry)210     inline float* coords(char* entry) {
211         return static_cast<float*>(static_cast<void*>(entry + kMetaSize));
212     }
coords(const char * entry)213     inline const float* coords(const char* entry) const {
214         return static_cast<const float*>(static_cast<const void*>(entry + kMetaSize));
215     }
216 
217     // Helpers to convert from coordinates to GrQuad and vice versa, returning pointer to the
218     // next packed quad coordinates.
219     float* packQuad(const GrQuad& quad, float* coords);
220     const float* unpackQuad(GrQuad::Type type, const float* coords, GrQuad* quad) const;
221 
222 #ifdef SK_DEBUG
223     void validate(const char* entry, int expectedCount) const;
224 #endif
225 };
226 
227 ///////////////////////////////////////////////////////////////////////////////////////////////////
228 // Buffer implementation
229 ///////////////////////////////////////////////////////////////////////////////////////////////////
230 
231 template<typename T>
packQuad(const GrQuad & quad,float * coords)232 float* GrQuadBuffer<T>::packQuad(const GrQuad& quad, float* coords) {
233     // Copies all 12 (or 8) floats at once, so requires the 3 arrays to be contiguous
234     // FIXME(michaelludwig) - If this turns out not to be the case, just do 4 copies
235     SkASSERT(quad.xs() + 4 == quad.ys() && quad.xs() + 8 == quad.ws());
236     if (quad.hasPerspective()) {
237         memcpy(coords, quad.xs(), k3DQuadFloats * sizeof(float));
238         return coords + k3DQuadFloats;
239     } else {
240         memcpy(coords, quad.xs(), k2DQuadFloats * sizeof(float));
241         return coords + k2DQuadFloats;
242     }
243 }
244 
245 template<typename T>
unpackQuad(GrQuad::Type type,const float * coords,GrQuad * quad)246 const float* GrQuadBuffer<T>::unpackQuad(GrQuad::Type type, const float* coords, GrQuad* quad) const {
247     SkASSERT(quad->xs() + 4 == quad->ys() && quad->xs() + 8 == quad->ws());
248     if (type == GrQuad::Type::kPerspective) {
249         // Fill in X, Y, and W in one go
250         memcpy(quad->xs(), coords, k3DQuadFloats * sizeof(float));
251         coords = coords + k3DQuadFloats;
252     } else {
253         // Fill in X and Y of the quad, and set W to 1s if needed
254         memcpy(quad->xs(), coords, k2DQuadFloats * sizeof(float));
255         coords = coords + k2DQuadFloats;
256 
257         if (quad->quadType() == GrQuad::Type::kPerspective) {
258             // The output quad was previously perspective, so its ws are not 1s
259             static constexpr float kNoPerspectiveWs[4] = {1.f, 1.f, 1.f, 1.f};
260             memcpy(quad->ws(), kNoPerspectiveWs, 4 * sizeof(float));
261         }
262         // Else the quad should already have 1s in w
263         SkASSERT(quad->w(0) == 1.f && quad->w(1) == 1.f &&
264                  quad->w(2) == 1.f && quad->w(3) == 1.f);
265     }
266 
267     quad->setQuadType(type);
268     return coords;
269 }
270 
271 template<typename T>
append(const GrQuad & deviceQuad,T && metadata,const GrQuad * localQuad)272 void GrQuadBuffer<T>::append(const GrQuad& deviceQuad, T&& metadata, const GrQuad* localQuad) {
273     GrQuad::Type localType = localQuad ? localQuad->quadType() : GrQuad::Type::kAxisAligned;
274     int entrySize = this->entrySize(deviceQuad.quadType(), localQuad ? &localType : nullptr);
275 
276     // Fill in the entry, as described in fData's declaration
277     char* entry = fData.append(entrySize);
278     // First the header
279     Header* h = this->header(entry);
280     h->fDeviceType = static_cast<unsigned>(deviceQuad.quadType());
281     h->fHasLocals = static_cast<unsigned>(localQuad != nullptr);
282     h->fLocalType = static_cast<unsigned>(localQuad ? localQuad->quadType()
283                                                     : GrQuad::Type::kAxisAligned);
284     SkDEBUGCODE(h->fSentinel = static_cast<unsigned>(kSentinel);)
285 
286     // Second, the fixed-size metadata
287     static_assert(alignof(T) == 4, "Metadata must be 4 byte aligned");
288     *(this->metadata(entry)) = std::move(metadata);
289 
290     // Then the variable blocks of x, y, and w float coordinates
291     float* coords = this->coords(entry);
292     coords = this->packQuad(deviceQuad, coords);
293     if (localQuad) {
294         coords = this->packQuad(*localQuad, coords);
295     }
296     SkASSERT((char*)coords - entry == entrySize);
297 
298     // Entry complete, update buffer-level state
299     fCount++;
300     if (deviceQuad.quadType() > fDeviceType) {
301         fDeviceType = deviceQuad.quadType();
302     }
303     if (localQuad && localQuad->quadType() > fLocalType) {
304         fLocalType = localQuad->quadType();
305     }
306 }
307 
308 template<typename T>
concat(const GrQuadBuffer<T> & that)309 void GrQuadBuffer<T>::concat(const GrQuadBuffer<T>& that) {
310     fData.append(that.fData.count(), that.fData.begin());
311     fCount += that.fCount;
312     if (that.fDeviceType > fDeviceType) {
313         fDeviceType = that.fDeviceType;
314     }
315     if (that.fLocalType > fLocalType) {
316         fLocalType = that.fLocalType;
317     }
318 }
319 
320 #ifdef SK_DEBUG
321 template<typename T>
validate(const char * entry,int expectedCount)322 void GrQuadBuffer<T>::validate(const char* entry, int expectedCount) const {
323     // Triggers if accessing before next() is called on an iterator
324     SkASSERT(entry);
325     // Triggers if accessing after next() returns false
326     SkASSERT(entry < fData.end());
327     // Triggers if elements have been added to the buffer while iterating entries
328     SkASSERT(expectedCount == fCount);
329     // Make sure the start of the entry looks like a header
330     SkASSERT(this->header(entry)->fSentinel == kSentinel);
331 }
332 #endif
333 
334 ///////////////////////////////////////////////////////////////////////////////////////////////////
335 // Iterator implementations
336 ///////////////////////////////////////////////////////////////////////////////////////////////////
337 
338 template<typename T>
next()339 bool GrQuadBuffer<T>::Iter::next() {
340     SkASSERT(fNextEntry);
341     if (fNextEntry >= fBuffer->fData.end()) {
342         return false;
343     }
344     // There is at least one more entry, so store the current start for metadata access
345     fCurrentEntry = fNextEntry;
346 
347     // And then unpack the device and optional local coordinates into fDeviceQuad and fLocalQuad
348     const Header* h = fBuffer->header(fCurrentEntry);
349     const float* coords = fBuffer->coords(fCurrentEntry);
350     coords = fBuffer->unpackQuad(static_cast<GrQuad::Type>(h->fDeviceType), coords, &fDeviceQuad);
351     if (h->fHasLocals) {
352         coords = fBuffer->unpackQuad(static_cast<GrQuad::Type>(h->fLocalType), coords, &fLocalQuad);
353     } else {
354         static const GrQuad kEmptyLocal(SkRect::MakeEmpty());
355         fLocalQuad = kEmptyLocal;
356     }
357     // At this point, coords points to the start of the next entry
358     fNextEntry = static_cast<const char*>(static_cast<const void*>(coords));
359     SkASSERT((fNextEntry - fCurrentEntry) == fBuffer->entrySize(h));
360     return true;
361 }
362 
363 template<typename T>
next()364 bool GrQuadBuffer<T>::MetadataIter::next() {
365     if (fCurrentEntry) {
366         // Advance pointer by entry size
367         if (fCurrentEntry < fBuffer->fData.end()) {
368             const Header* h = fBuffer->header(fCurrentEntry);
369             fCurrentEntry += fBuffer->entrySize(h);
370         }
371     } else {
372         // First call to next
373         fCurrentEntry = fBuffer->fData.begin();
374     }
375     // Nothing else is needed to do but report whether or not the updated pointer is valid
376     return fCurrentEntry < fBuffer->fData.end();
377 }
378 #endif  // GrQuadBuffer_DEFINED
379