GrResourceKey.h 13 KB

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