1
2/*
3 * Copyright 2010 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
10#include "GrGpu.h"
11
12#include "GrBufferAllocPool.h"
13#include "GrContext.h"
14#include "GrDrawTargetCaps.h"
15#include "GrIndexBuffer.h"
16#include "GrStencilBuffer.h"
17#include "GrVertexBuffer.h"
18
19// probably makes no sense for this to be less than a page
20static const size_t VERTEX_POOL_VB_SIZE = 1 << 18;
21static const int VERTEX_POOL_VB_COUNT = 4;
22static const size_t INDEX_POOL_IB_SIZE = 1 << 16;
23static const int INDEX_POOL_IB_COUNT = 4;
24
25////////////////////////////////////////////////////////////////////////////////
26
27#define DEBUG_INVAL_BUFFER    0xdeadcafe
28#define DEBUG_INVAL_START_IDX -1
29
30GrGpu::GrGpu(GrContext* context)
31    : GrDrawTarget(context)
32    , fResetTimestamp(kExpiredTimestamp+1)
33    , fResetBits(kAll_GrBackendState)
34    , fVertexPool(NULL)
35    , fIndexPool(NULL)
36    , fVertexPoolUseCnt(0)
37    , fIndexPoolUseCnt(0)
38    , fQuadIndexBuffer(NULL) {
39
40    fClipMaskManager.setGpu(this);
41
42    fGeomPoolStateStack.push_back();
43#if GR_DEBUG
44    GeometryPoolState& poolState = fGeomPoolStateStack.back();
45    poolState.fPoolVertexBuffer = (GrVertexBuffer*)DEBUG_INVAL_BUFFER;
46    poolState.fPoolStartVertex = DEBUG_INVAL_START_IDX;
47    poolState.fPoolIndexBuffer = (GrIndexBuffer*)DEBUG_INVAL_BUFFER;
48    poolState.fPoolStartIndex = DEBUG_INVAL_START_IDX;
49#endif
50
51    for (int i = 0; i < kGrPixelConfigCnt; ++i) {
52        fConfigRenderSupport[i] = false;
53    };
54}
55
56GrGpu::~GrGpu() {
57    this->releaseResources();
58}
59
60void GrGpu::abandonResources() {
61
62    fClipMaskManager.releaseResources();
63
64    while (NULL != fResourceList.head()) {
65        fResourceList.head()->abandon();
66    }
67
68    GrAssert(NULL == fQuadIndexBuffer || !fQuadIndexBuffer->isValid());
69    GrSafeSetNull(fQuadIndexBuffer);
70    delete fVertexPool;
71    fVertexPool = NULL;
72    delete fIndexPool;
73    fIndexPool = NULL;
74}
75
76void GrGpu::releaseResources() {
77
78    fClipMaskManager.releaseResources();
79
80    while (NULL != fResourceList.head()) {
81        fResourceList.head()->release();
82    }
83
84    GrAssert(NULL == fQuadIndexBuffer || !fQuadIndexBuffer->isValid());
85    GrSafeSetNull(fQuadIndexBuffer);
86    delete fVertexPool;
87    fVertexPool = NULL;
88    delete fIndexPool;
89    fIndexPool = NULL;
90}
91
92void GrGpu::insertResource(GrResource* resource) {
93    GrAssert(NULL != resource);
94    GrAssert(this == resource->getGpu());
95
96    fResourceList.addToHead(resource);
97}
98
99void GrGpu::removeResource(GrResource* resource) {
100    GrAssert(NULL != resource);
101    GrAssert(this == resource->getGpu());
102
103    fResourceList.remove(resource);
104}
105
106
107void GrGpu::unimpl(const char msg[]) {
108#if GR_DEBUG
109    GrPrintf("--- GrGpu unimplemented(\"%s\")\n", msg);
110#endif
111}
112
113////////////////////////////////////////////////////////////////////////////////
114
115GrTexture* GrGpu::createTexture(const GrTextureDesc& desc,
116                                const void* srcData, size_t rowBytes) {
117    if (kUnknown_GrPixelConfig == desc.fConfig) {
118        return NULL;
119    }
120
121    this->handleDirtyContext();
122    GrTexture* tex = this->onCreateTexture(desc, srcData, rowBytes);
123    if (NULL != tex &&
124        (kRenderTarget_GrTextureFlagBit & desc.fFlags) &&
125        !(kNoStencil_GrTextureFlagBit & desc.fFlags)) {
126        GrAssert(NULL != tex->asRenderTarget());
127        // TODO: defer this and attach dynamically
128        if (!this->attachStencilBufferToRenderTarget(tex->asRenderTarget())) {
129            tex->unref();
130            return NULL;
131        }
132    }
133    return tex;
134}
135
136bool GrGpu::attachStencilBufferToRenderTarget(GrRenderTarget* rt) {
137    GrAssert(NULL == rt->getStencilBuffer());
138    GrStencilBuffer* sb =
139        this->getContext()->findStencilBuffer(rt->width(),
140                                              rt->height(),
141                                              rt->numSamples());
142    if (NULL != sb) {
143        rt->setStencilBuffer(sb);
144        bool attached = this->attachStencilBufferToRenderTarget(sb, rt);
145        if (!attached) {
146            rt->setStencilBuffer(NULL);
147        }
148        return attached;
149    }
150    if (this->createStencilBufferForRenderTarget(rt,
151                                                 rt->width(), rt->height())) {
152        // Right now we're clearing the stencil buffer here after it is
153        // attached to an RT for the first time. When we start matching
154        // stencil buffers with smaller color targets this will no longer
155        // be correct because it won't be guaranteed to clear the entire
156        // sb.
157        // We used to clear down in the GL subclass using a special purpose
158        // FBO. But iOS doesn't allow a stencil-only FBO. It reports unsupported
159        // FBO status.
160        GrDrawState::AutoRenderTargetRestore artr(this->drawState(), rt);
161        this->clearStencil();
162        return true;
163    } else {
164        return false;
165    }
166}
167
168GrTexture* GrGpu::wrapBackendTexture(const GrBackendTextureDesc& desc) {
169    this->handleDirtyContext();
170    GrTexture* tex = this->onWrapBackendTexture(desc);
171    if (NULL == tex) {
172        return NULL;
173    }
174    // TODO: defer this and attach dynamically
175    GrRenderTarget* tgt = tex->asRenderTarget();
176    if (NULL != tgt &&
177        !this->attachStencilBufferToRenderTarget(tgt)) {
178        tex->unref();
179        return NULL;
180    } else {
181        return tex;
182    }
183}
184
185GrRenderTarget* GrGpu::wrapBackendRenderTarget(const GrBackendRenderTargetDesc& desc) {
186    this->handleDirtyContext();
187    return this->onWrapBackendRenderTarget(desc);
188}
189
190GrVertexBuffer* GrGpu::createVertexBuffer(uint32_t size, bool dynamic) {
191    this->handleDirtyContext();
192    return this->onCreateVertexBuffer(size, dynamic);
193}
194
195GrIndexBuffer* GrGpu::createIndexBuffer(uint32_t size, bool dynamic) {
196    this->handleDirtyContext();
197    return this->onCreateIndexBuffer(size, dynamic);
198}
199
200GrPath* GrGpu::createPath(const SkPath& path) {
201    GrAssert(this->caps()->pathStencilingSupport());
202    this->handleDirtyContext();
203    return this->onCreatePath(path);
204}
205
206void GrGpu::clear(const SkIRect* rect,
207                  GrColor color,
208                  GrRenderTarget* renderTarget) {
209    GrDrawState::AutoRenderTargetRestore art;
210    if (NULL != renderTarget) {
211        art.set(this->drawState(), renderTarget);
212    }
213    if (NULL == this->getDrawState().getRenderTarget()) {
214        GrAssert(0);
215        return;
216    }
217    this->handleDirtyContext();
218    this->onClear(rect, color);
219}
220
221void GrGpu::forceRenderTargetFlush() {
222    this->handleDirtyContext();
223    this->onForceRenderTargetFlush();
224}
225
226bool GrGpu::readPixels(GrRenderTarget* target,
227                       int left, int top, int width, int height,
228                       GrPixelConfig config, void* buffer,
229                       size_t rowBytes) {
230    this->handleDirtyContext();
231    return this->onReadPixels(target, left, top, width, height,
232                              config, buffer, rowBytes);
233}
234
235bool GrGpu::writeTexturePixels(GrTexture* texture,
236                               int left, int top, int width, int height,
237                               GrPixelConfig config, const void* buffer,
238                               size_t rowBytes) {
239    this->handleDirtyContext();
240    return this->onWriteTexturePixels(texture, left, top, width, height,
241                                      config, buffer, rowBytes);
242}
243
244void GrGpu::resolveRenderTarget(GrRenderTarget* target) {
245    GrAssert(target);
246    this->handleDirtyContext();
247    this->onResolveRenderTarget(target);
248}
249
250
251////////////////////////////////////////////////////////////////////////////////
252
253static const int MAX_QUADS = 1 << 12; // max possible: (1 << 14) - 1;
254
255GR_STATIC_ASSERT(4 * MAX_QUADS <= 65535);
256
257static inline void fill_indices(uint16_t* indices, int quadCount) {
258    for (int i = 0; i < quadCount; ++i) {
259        indices[6 * i + 0] = 4 * i + 0;
260        indices[6 * i + 1] = 4 * i + 1;
261        indices[6 * i + 2] = 4 * i + 2;
262        indices[6 * i + 3] = 4 * i + 0;
263        indices[6 * i + 4] = 4 * i + 2;
264        indices[6 * i + 5] = 4 * i + 3;
265    }
266}
267
268const GrIndexBuffer* GrGpu::getQuadIndexBuffer() const {
269    if (NULL == fQuadIndexBuffer) {
270        static const int SIZE = sizeof(uint16_t) * 6 * MAX_QUADS;
271        GrGpu* me = const_cast<GrGpu*>(this);
272        fQuadIndexBuffer = me->createIndexBuffer(SIZE, false);
273        if (NULL != fQuadIndexBuffer) {
274            uint16_t* indices = (uint16_t*)fQuadIndexBuffer->lock();
275            if (NULL != indices) {
276                fill_indices(indices, MAX_QUADS);
277                fQuadIndexBuffer->unlock();
278            } else {
279                indices = (uint16_t*)GrMalloc(SIZE);
280                fill_indices(indices, MAX_QUADS);
281                if (!fQuadIndexBuffer->updateData(indices, SIZE)) {
282                    fQuadIndexBuffer->unref();
283                    fQuadIndexBuffer = NULL;
284                    GrCrash("Can't get indices into buffer!");
285                }
286                GrFree(indices);
287            }
288        }
289    }
290
291    return fQuadIndexBuffer;
292}
293
294////////////////////////////////////////////////////////////////////////////////
295
296bool GrGpu::setupClipAndFlushState(DrawType type, const GrDeviceCoordTexture* dstCopy,
297                                   GrDrawState::AutoRestoreEffects* are) {
298    if (!fClipMaskManager.setupClipping(this->getClip(), are)) {
299        return false;
300    }
301
302    if (!this->flushGraphicsState(type, dstCopy)) {
303        return false;
304    }
305
306    return true;
307}
308
309////////////////////////////////////////////////////////////////////////////////
310
311void GrGpu::geometrySourceWillPush() {
312    const GeometrySrcState& geoSrc = this->getGeomSrc();
313    if (kArray_GeometrySrcType == geoSrc.fVertexSrc ||
314        kReserved_GeometrySrcType == geoSrc.fVertexSrc) {
315        this->finalizeReservedVertices();
316    }
317    if (kArray_GeometrySrcType == geoSrc.fIndexSrc ||
318        kReserved_GeometrySrcType == geoSrc.fIndexSrc) {
319        this->finalizeReservedIndices();
320    }
321    GeometryPoolState& newState = fGeomPoolStateStack.push_back();
322#if GR_DEBUG
323    newState.fPoolVertexBuffer = (GrVertexBuffer*)DEBUG_INVAL_BUFFER;
324    newState.fPoolStartVertex = DEBUG_INVAL_START_IDX;
325    newState.fPoolIndexBuffer = (GrIndexBuffer*)DEBUG_INVAL_BUFFER;
326    newState.fPoolStartIndex = DEBUG_INVAL_START_IDX;
327#else
328    (void) newState; // silence compiler warning
329#endif
330}
331
332void GrGpu::geometrySourceWillPop(const GeometrySrcState& restoredState) {
333    // if popping last entry then pops are unbalanced with pushes
334    GrAssert(fGeomPoolStateStack.count() > 1);
335    fGeomPoolStateStack.pop_back();
336}
337
338void GrGpu::onDraw(const DrawInfo& info) {
339    this->handleDirtyContext();
340    GrDrawState::AutoRestoreEffects are;
341    if (!this->setupClipAndFlushState(PrimTypeToDrawType(info.primitiveType()),
342                                      info.getDstCopy(),
343                                      &are)) {
344        return;
345    }
346    this->onGpuDraw(info);
347}
348
349void GrGpu::onStencilPath(const GrPath* path, const SkStrokeRec&, SkPath::FillType fill) {
350    this->handleDirtyContext();
351
352    // TODO: make this more efficient (don't copy and copy back)
353    GrAutoTRestore<GrStencilSettings> asr(this->drawState()->stencil());
354
355    this->setStencilPathSettings(*path, fill, this->drawState()->stencil());
356    GrDrawState::AutoRestoreEffects are;
357    if (!this->setupClipAndFlushState(kStencilPath_DrawType, NULL, &are)) {
358        return;
359    }
360
361    this->onGpuStencilPath(path, fill);
362}
363
364void GrGpu::finalizeReservedVertices() {
365    GrAssert(NULL != fVertexPool);
366    fVertexPool->unlock();
367}
368
369void GrGpu::finalizeReservedIndices() {
370    GrAssert(NULL != fIndexPool);
371    fIndexPool->unlock();
372}
373
374void GrGpu::prepareVertexPool() {
375    if (NULL == fVertexPool) {
376        GrAssert(0 == fVertexPoolUseCnt);
377        fVertexPool = SkNEW_ARGS(GrVertexBufferAllocPool, (this, true,
378                                                  VERTEX_POOL_VB_SIZE,
379                                                  VERTEX_POOL_VB_COUNT));
380        fVertexPool->releaseGpuRef();
381    } else if (!fVertexPoolUseCnt) {
382        // the client doesn't have valid data in the pool
383        fVertexPool->reset();
384    }
385}
386
387void GrGpu::prepareIndexPool() {
388    if (NULL == fIndexPool) {
389        GrAssert(0 == fIndexPoolUseCnt);
390        fIndexPool = SkNEW_ARGS(GrIndexBufferAllocPool, (this, true,
391                                                INDEX_POOL_IB_SIZE,
392                                                INDEX_POOL_IB_COUNT));
393        fIndexPool->releaseGpuRef();
394    } else if (!fIndexPoolUseCnt) {
395        // the client doesn't have valid data in the pool
396        fIndexPool->reset();
397    }
398}
399
400bool GrGpu::onReserveVertexSpace(size_t vertexSize,
401                                 int vertexCount,
402                                 void** vertices) {
403    GeometryPoolState& geomPoolState = fGeomPoolStateStack.back();
404
405    GrAssert(vertexCount > 0);
406    GrAssert(NULL != vertices);
407
408    this->prepareVertexPool();
409
410    *vertices = fVertexPool->makeSpace(vertexSize,
411                                       vertexCount,
412                                       &geomPoolState.fPoolVertexBuffer,
413                                       &geomPoolState.fPoolStartVertex);
414    if (NULL == *vertices) {
415        return false;
416    }
417    ++fVertexPoolUseCnt;
418    return true;
419}
420
421bool GrGpu::onReserveIndexSpace(int indexCount, void** indices) {
422    GeometryPoolState& geomPoolState = fGeomPoolStateStack.back();
423
424    GrAssert(indexCount > 0);
425    GrAssert(NULL != indices);
426
427    this->prepareIndexPool();
428
429    *indices = fIndexPool->makeSpace(indexCount,
430                                     &geomPoolState.fPoolIndexBuffer,
431                                     &geomPoolState.fPoolStartIndex);
432    if (NULL == *indices) {
433        return false;
434    }
435    ++fIndexPoolUseCnt;
436    return true;
437}
438
439void GrGpu::releaseReservedVertexSpace() {
440    const GeometrySrcState& geoSrc = this->getGeomSrc();
441    GrAssert(kReserved_GeometrySrcType == geoSrc.fVertexSrc);
442    size_t bytes = geoSrc.fVertexCount * geoSrc.fVertexSize;
443    fVertexPool->putBack(bytes);
444    --fVertexPoolUseCnt;
445}
446
447void GrGpu::releaseReservedIndexSpace() {
448    const GeometrySrcState& geoSrc = this->getGeomSrc();
449    GrAssert(kReserved_GeometrySrcType == geoSrc.fIndexSrc);
450    size_t bytes = geoSrc.fIndexCount * sizeof(uint16_t);
451    fIndexPool->putBack(bytes);
452    --fIndexPoolUseCnt;
453}
454
455void GrGpu::onSetVertexSourceToArray(const void* vertexArray, int vertexCount) {
456    this->prepareVertexPool();
457    GeometryPoolState& geomPoolState = fGeomPoolStateStack.back();
458#if GR_DEBUG
459    bool success =
460#endif
461    fVertexPool->appendVertices(this->getVertexSize(),
462                                vertexCount,
463                                vertexArray,
464                                &geomPoolState.fPoolVertexBuffer,
465                                &geomPoolState.fPoolStartVertex);
466    ++fVertexPoolUseCnt;
467    GR_DEBUGASSERT(success);
468}
469
470void GrGpu::onSetIndexSourceToArray(const void* indexArray, int indexCount) {
471    this->prepareIndexPool();
472    GeometryPoolState& geomPoolState = fGeomPoolStateStack.back();
473#if GR_DEBUG
474    bool success =
475#endif
476    fIndexPool->appendIndices(indexCount,
477                              indexArray,
478                              &geomPoolState.fPoolIndexBuffer,
479                              &geomPoolState.fPoolStartIndex);
480    ++fIndexPoolUseCnt;
481    GR_DEBUGASSERT(success);
482}
483
484void GrGpu::releaseVertexArray() {
485    // if vertex source was array, we stowed data in the pool
486    const GeometrySrcState& geoSrc = this->getGeomSrc();
487    GrAssert(kArray_GeometrySrcType == geoSrc.fVertexSrc);
488    size_t bytes = geoSrc.fVertexCount * geoSrc.fVertexSize;
489    fVertexPool->putBack(bytes);
490    --fVertexPoolUseCnt;
491}
492
493void GrGpu::releaseIndexArray() {
494    // if index source was array, we stowed data in the pool
495    const GeometrySrcState& geoSrc = this->getGeomSrc();
496    GrAssert(kArray_GeometrySrcType == geoSrc.fIndexSrc);
497    size_t bytes = geoSrc.fIndexCount * sizeof(uint16_t);
498    fIndexPool->putBack(bytes);
499    --fIndexPoolUseCnt;
500}
501