1 /*
2 * Copyright 2014 Google Inc.
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 GrResourceKey_DEFINED
9 #define GrResourceKey_DEFINED
10
11 #include "../private/SkOnce.h"
12 #include "../private/SkTemplates.h"
13 #include "../private/SkTo.h"
14 #include "GrTypes.h"
15 #include "SkData.h"
16 #include "SkString.h"
17
18 #include <new>
19
20 uint32_t GrResourceKeyHash(const uint32_t* data, size_t size);
21
22 /**
23 * Base class for all GrGpuResource cache keys. There are two types of cache keys. Refer to the
24 * comments for each key type below.
25 */
26 class GrResourceKey {
27 public:
hash()28 uint32_t hash() const {
29 this->validate();
30 return fKey[kHash_MetaDataIdx];
31 }
32
size()33 size_t size() const {
34 this->validate();
35 SkASSERT(this->isValid());
36 return this->internalSize();
37 }
38
39 protected:
40 static const uint32_t kInvalidDomain = 0;
41
GrResourceKey()42 GrResourceKey() { this->reset(); }
43
44 /** Reset to an invalid key. */
reset()45 void reset() {
46 GR_STATIC_ASSERT((uint16_t)kInvalidDomain == kInvalidDomain);
47 fKey.reset(kMetaDataCnt);
48 fKey[kHash_MetaDataIdx] = 0;
49 fKey[kDomainAndSize_MetaDataIdx] = kInvalidDomain;
50 }
51
52 bool operator==(const GrResourceKey& that) const {
53 return this->hash() == that.hash() && 0 == memcmp(&fKey[kHash_MetaDataIdx + 1],
54 &that.fKey[kHash_MetaDataIdx + 1],
55 this->internalSize() - sizeof(uint32_t));
56 }
57
58 GrResourceKey& operator=(const GrResourceKey& that) {
59 if (this != &that) {
60 if (!that.isValid()) {
61 this->reset();
62 } else {
63 size_t bytes = that.size();
64 SkASSERT(SkIsAlign4(bytes));
65 fKey.reset(SkToInt(bytes / sizeof(uint32_t)));
66 memcpy(fKey.get(), that.fKey.get(), bytes);
67 this->validate();
68 }
69 }
70 return *this;
71 }
72
isValid()73 bool isValid() const { return kInvalidDomain != this->domain(); }
74
domain()75 uint32_t domain() const { return fKey[kDomainAndSize_MetaDataIdx] & 0xffff; }
76
77 /** size of the key data, excluding meta-data (hash, domain, etc). */
dataSize()78 size_t dataSize() const { return this->size() - 4 * kMetaDataCnt; }
79
80 /** ptr to the key data, excluding meta-data (hash, domain, etc). */
data()81 const uint32_t* data() const {
82 this->validate();
83 return &fKey[kMetaDataCnt];
84 }
85
86 #ifdef SK_DEBUG
dump()87 void dump() const {
88 if (!this->isValid()) {
89 SkDebugf("Invalid Key\n");
90 } else {
91 SkDebugf("hash: %d ", this->hash());
92 SkDebugf("domain: %d ", this->domain());
93 SkDebugf("size: %dB ", this->internalSize());
94 for (size_t i = 0; i < this->internalSize(); ++i) {
95 SkDebugf("%d ", fKey[SkTo<int>(i)]);
96 }
97 SkDebugf("\n");
98 }
99 }
100 #endif
101
102 /** Used to initialize a key. */
103 class Builder {
104 public:
Builder(GrResourceKey * key,uint32_t domain,int data32Count)105 Builder(GrResourceKey* key, uint32_t domain, int data32Count) : fKey(key) {
106 SkASSERT(data32Count >= 0);
107 SkASSERT(domain != kInvalidDomain);
108 key->fKey.reset(kMetaDataCnt + data32Count);
109 int size = (data32Count + kMetaDataCnt) * sizeof(uint32_t);
110 SkASSERT(SkToU16(size) == size);
111 SkASSERT(SkToU16(domain) == domain);
112 key->fKey[kDomainAndSize_MetaDataIdx] = domain | (size << 16);
113 }
114
~Builder()115 ~Builder() { this->finish(); }
116
finish()117 void finish() {
118 if (nullptr == fKey) {
119 return;
120 }
121 GR_STATIC_ASSERT(0 == kHash_MetaDataIdx);
122 uint32_t* hash = &fKey->fKey[kHash_MetaDataIdx];
123 *hash = GrResourceKeyHash(hash + 1, fKey->internalSize() - sizeof(uint32_t));
124 fKey->validate();
125 fKey = nullptr;
126 }
127
128 uint32_t& operator[](int dataIdx) {
129 SkASSERT(fKey);
130 SkDEBUGCODE(size_t dataCount = fKey->internalSize() / sizeof(uint32_t) - kMetaDataCnt;)
131 SkASSERT(SkToU32(dataIdx) < dataCount);
132 return fKey->fKey[kMetaDataCnt + dataIdx];
133 }
134
135 private:
136 GrResourceKey* fKey;
137 };
138
139 private:
140 enum MetaDataIdx {
141 kHash_MetaDataIdx,
142 // The key domain and size are packed into a single uint32_t.
143 kDomainAndSize_MetaDataIdx,
144
145 kLastMetaDataIdx = kDomainAndSize_MetaDataIdx
146 };
147 static const uint32_t kMetaDataCnt = kLastMetaDataIdx + 1;
148
internalSize()149 size_t internalSize() const { return fKey[kDomainAndSize_MetaDataIdx] >> 16; }
150
validate()151 void validate() const {
152 SkASSERT(this->isValid());
153 SkASSERT(fKey[kHash_MetaDataIdx] ==
154 GrResourceKeyHash(&fKey[kHash_MetaDataIdx] + 1,
155 this->internalSize() - sizeof(uint32_t)));
156 SkASSERT(SkIsAlign4(this->internalSize()));
157 }
158
159 friend class TestResource; // For unit test to access kMetaDataCnt.
160
161 // bmp textures require 5 uint32_t values.
162 SkAutoSTMalloc<kMetaDataCnt + 5, uint32_t> fKey;
163 };
164
165 /**
166 * A key used for scratch resources. There are three important rules about scratch keys:
167 * * Multiple resources can share the same scratch key. Therefore resources assigned the same
168 * scratch key should be interchangeable with respect to the code that uses them.
169 * * A resource can have at most one scratch key and it is set at resource creation by the
170 * resource itself.
171 * * When a scratch resource is ref'ed it will not be returned from the
172 * cache for a subsequent cache request until all refs are released. This facilitates using
173 * a scratch key for multiple render-to-texture scenarios. An example is a separable blur:
174 *
175 * GrTexture* texture[2];
176 * texture[0] = get_scratch_texture(scratchKey);
177 * texture[1] = get_scratch_texture(scratchKey); // texture[0] is already owned so we will get a
178 * // different one for texture[1]
179 * draw_mask(texture[0], path); // draws path mask to texture[0]
180 * blur_x(texture[0], texture[1]); // blurs texture[0] in y and stores result in texture[1]
181 * blur_y(texture[1], texture[0]); // blurs texture[1] in y and stores result in texture[0]
182 * texture[1]->unref(); // texture 1 can now be recycled for the next request with scratchKey
183 * consume_blur(texture[0]);
184 * texture[0]->unref(); // texture 0 can now be recycled for the next request with scratchKey
185 */
186 class GrScratchKey : public GrResourceKey {
187 private:
188 typedef GrResourceKey INHERITED;
189
190 public:
191 /** Uniquely identifies the type of resource that is cached as scratch. */
192 typedef uint32_t ResourceType;
193
194 /** Generate a unique ResourceType. */
195 static ResourceType GenerateResourceType();
196
197 /** Creates an invalid scratch key. It must be initialized using a Builder object before use. */
GrScratchKey()198 GrScratchKey() {}
199
GrScratchKey(const GrScratchKey & that)200 GrScratchKey(const GrScratchKey& that) { *this = that; }
201
202 /** reset() returns the key to the invalid state. */
203 using INHERITED::reset;
204
205 using INHERITED::isValid;
206
resourceType()207 ResourceType resourceType() const { return this->domain(); }
208
209 GrScratchKey& operator=(const GrScratchKey& that) {
210 this->INHERITED::operator=(that);
211 return *this;
212 }
213
214 bool operator==(const GrScratchKey& that) const { return this->INHERITED::operator==(that); }
215 bool operator!=(const GrScratchKey& that) const { return !(*this == that); }
216
217 class Builder : public INHERITED::Builder {
218 public:
Builder(GrScratchKey * key,ResourceType type,int data32Count)219 Builder(GrScratchKey* key, ResourceType type, int data32Count)
220 : INHERITED::Builder(key, type, data32Count) {}
221 };
222 };
223
224 /**
225 * A key that allows for exclusive use of a resource for a use case (AKA "domain"). There are three
226 * rules governing the use of unique keys:
227 * * Only one resource can have a given unique key at a time. Hence, "unique".
228 * * A resource can have at most one unique key at a time.
229 * * Unlike scratch keys, multiple requests for a unique key will return the same
230 * resource even if the resource already has refs.
231 * This key type allows a code path to create cached resources for which it is the exclusive user.
232 * The code path creates a domain which it sets on its keys. This guarantees that there are no
233 * cross-domain collisions.
234 *
235 * Unique keys preempt scratch keys. While a resource has a unique key it is inaccessible via its
236 * scratch key. It can become scratch again if the unique key is removed.
237 */
238 class GrUniqueKey : public GrResourceKey {
239 private:
240 typedef GrResourceKey INHERITED;
241
242 public:
243 typedef uint32_t Domain;
244 /** Generate a Domain for unique keys. */
245 static Domain GenerateDomain();
246
247 /** Creates an invalid unique key. It must be initialized using a Builder object before use. */
GrUniqueKey()248 GrUniqueKey() : fTag(nullptr) {}
249
GrUniqueKey(const GrUniqueKey & that)250 GrUniqueKey(const GrUniqueKey& that) { *this = that; }
251
252 /** reset() returns the key to the invalid state. */
253 using INHERITED::reset;
254
255 using INHERITED::isValid;
256
257 GrUniqueKey& operator=(const GrUniqueKey& that) {
258 this->INHERITED::operator=(that);
259 this->setCustomData(sk_ref_sp(that.getCustomData()));
260 fTag = that.fTag;
261 return *this;
262 }
263
264 bool operator==(const GrUniqueKey& that) const { return this->INHERITED::operator==(that); }
265 bool operator!=(const GrUniqueKey& that) const { return !(*this == that); }
266
setCustomData(sk_sp<SkData> data)267 void setCustomData(sk_sp<SkData> data) { fData = std::move(data); }
getCustomData()268 SkData* getCustomData() const { return fData.get(); }
269
tag()270 const char* tag() const { return fTag; }
271
272 #ifdef SK_DEBUG
dump(const char * label)273 void dump(const char* label) const {
274 SkDebugf("%s tag: %s\n", label, fTag ? fTag : "None");
275 this->INHERITED::dump();
276 }
277 #endif
278
279 class Builder : public INHERITED::Builder {
280 public:
281 Builder(GrUniqueKey* key, Domain type, int data32Count, const char* tag = nullptr)
Builder(key,type,data32Count)282 : INHERITED::Builder(key, type, data32Count) {
283 key->fTag = tag;
284 }
285
286 /** Used to build a key that wraps another key and adds additional data. */
287 Builder(GrUniqueKey* key, const GrUniqueKey& innerKey, Domain domain, int extraData32Cnt,
288 const char* tag = nullptr)
289 : INHERITED::Builder(key, domain, Data32CntForInnerKey(innerKey) + extraData32Cnt) {
290 SkASSERT(&innerKey != key);
291 // add the inner key to the end of the key so that op[] can be indexed normally.
292 uint32_t* innerKeyData = &this->operator[](extraData32Cnt);
293 const uint32_t* srcData = innerKey.data();
294 (*innerKeyData++) = innerKey.domain();
295 memcpy(innerKeyData, srcData, innerKey.dataSize());
296 key->fTag = tag;
297 }
298
299 private:
Data32CntForInnerKey(const GrUniqueKey & innerKey)300 static int Data32CntForInnerKey(const GrUniqueKey& innerKey) {
301 // key data + domain
302 return SkToInt((innerKey.dataSize() >> 2) + 1);
303 }
304 };
305
306 private:
307 sk_sp<SkData> fData;
308 const char* fTag;
309 };
310
311 /**
312 * It is common to need a frequently reused GrUniqueKey where the only requirement is that the key
313 * is unique. These macros create such a key in a thread safe manner so the key can be truly global
314 * and only constructed once.
315 */
316
317 /** Place outside of function/class definitions. */
318 #define GR_DECLARE_STATIC_UNIQUE_KEY(name) static SkOnce name##_once
319
320 /** Place inside function where the key is used. */
321 #define GR_DEFINE_STATIC_UNIQUE_KEY(name) \
322 static SkAlignedSTStorage<1, GrUniqueKey> name##_storage; \
323 name##_once(gr_init_static_unique_key_once, &name##_storage); \
324 static const GrUniqueKey& name = *reinterpret_cast<GrUniqueKey*>(name##_storage.get())
325
gr_init_static_unique_key_once(SkAlignedSTStorage<1,GrUniqueKey> * keyStorage)326 static inline void gr_init_static_unique_key_once(SkAlignedSTStorage<1, GrUniqueKey>* keyStorage) {
327 GrUniqueKey* key = new (keyStorage->get()) GrUniqueKey;
328 GrUniqueKey::Builder builder(key, GrUniqueKey::GenerateDomain(), 0);
329 }
330
331 // The cache listens for these messages to purge junk resources proactively.
332 class GrUniqueKeyInvalidatedMessage {
333 public:
334 GrUniqueKeyInvalidatedMessage() = default;
GrUniqueKeyInvalidatedMessage(const GrUniqueKey & key,uint32_t contextUniqueID)335 GrUniqueKeyInvalidatedMessage(const GrUniqueKey& key, uint32_t contextUniqueID)
336 : fKey(key), fContextID(contextUniqueID) {
337 SkASSERT(SK_InvalidUniqueID != contextUniqueID);
338 }
339
340 GrUniqueKeyInvalidatedMessage(const GrUniqueKeyInvalidatedMessage&) = default;
341
342 GrUniqueKeyInvalidatedMessage& operator=(const GrUniqueKeyInvalidatedMessage&) = default;
343
key()344 const GrUniqueKey& key() const { return fKey; }
contextID()345 uint32_t contextID() const { return fContextID; }
346
347 private:
348 GrUniqueKey fKey;
349 uint32_t fContextID = SK_InvalidUniqueID;
350 };
351
SkShouldPostMessageToBus(const GrUniqueKeyInvalidatedMessage & msg,uint32_t msgBusUniqueID)352 static inline bool SkShouldPostMessageToBus(const GrUniqueKeyInvalidatedMessage& msg,
353 uint32_t msgBusUniqueID) {
354 return msg.contextID() == msgBusUniqueID;
355 }
356
357 #endif
358