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