diff options
author | Brian Salomon <bsalomon@google.com> | 2017-12-07 14:34:36 -0500 |
---|---|---|
committer | Skia Commit-Bot <skia-commit-bot@chromium.org> | 2017-12-08 13:41:10 +0000 |
commit | f06c3582677270c741a5e4fb366ec8b5d4ec4c21 (patch) | |
tree | be9fb470ef48933fdd5b6deb18ab3a01d373686b /src | |
parent | 852ca318a16f9c455d2bed3efb2063dff0e4d068 (diff) |
Remove instanced rendering
Change-Id: I4219b1d23a647b849ee41fe71b53e1c45edfc3f4
Reviewed-on: https://skia-review.googlesource.com/82241
Reviewed-by: Chris Dalton <csmartdalton@google.com>
Commit-Queue: Brian Salomon <bsalomon@google.com>
Diffstat (limited to 'src')
27 files changed, 0 insertions, 3831 deletions
diff --git a/src/gpu/GrCaps.cpp b/src/gpu/GrCaps.cpp index 67f67def70..198551ae9e 100644 --- a/src/gpu/GrCaps.cpp +++ b/src/gpu/GrCaps.cpp @@ -59,8 +59,6 @@ GrCaps::GrCaps(const GrContextOptions& options) { fFenceSyncSupport = false; fCrossContextTextureSupport = false; - fInstancedSupport = InstancedSupport::kNone; - fBlendEquationSupport = kBasic_BlendEquationSupport; fAdvBlendEqBlacklist = 0; @@ -89,7 +87,6 @@ GrCaps::GrCaps(const GrContextOptions& options) { fWireframeMode = false; #endif fBufferMapThreshold = options.fBufferMapThreshold; - fAvoidInstancedDrawsToFPTargets = false; fBlacklistCoverageCounting = false; fAvoidStencilBuffers = false; @@ -176,20 +173,6 @@ void GrCaps::dumpJSON(SkJSONWriter* writer) const { writer->appendS32("Max Window Rectangles", fMaxWindowRectangles); writer->appendS32("Max Clip Analytic Fragment Processors", fMaxClipAnalyticFPs); - static const char* kInstancedSupportNames[] = { - "None", - "Basic", - "Multisampled", - "Mixed Sampled", - }; - GR_STATIC_ASSERT(0 == (int)InstancedSupport::kNone); - GR_STATIC_ASSERT(1 == (int)InstancedSupport::kBasic); - GR_STATIC_ASSERT(2 == (int)InstancedSupport::kMultisampled); - GR_STATIC_ASSERT(3 == (int)InstancedSupport::kMixedSampled); - GR_STATIC_ASSERT(4 == SK_ARRAY_COUNT(kInstancedSupportNames)); - - writer->appendString("Instanced Support", kInstancedSupportNames[(int)fInstancedSupport]); - static const char* kBlendEquationSupportNames[] = { "Basic", "Advanced", diff --git a/src/gpu/GrDrawingManager.cpp b/src/gpu/GrDrawingManager.cpp index bf8d1abbcf..b75dd1c3c4 100644 --- a/src/gpu/GrDrawingManager.cpp +++ b/src/gpu/GrDrawingManager.cpp @@ -60,9 +60,6 @@ GrDrawingManager::~GrDrawingManager() { void GrDrawingManager::abandon() { fAbandoned = true; - for (int i = 0; i < fOpLists.count(); ++i) { - fOpLists[i]->abandonGpuResources(); - } this->cleanup(); } @@ -78,19 +75,6 @@ void GrDrawingManager::freeGpuResources() { delete fPathRendererChain; fPathRendererChain = nullptr; SkSafeSetNull(fSoftwarePathRenderer); - for (int i = 0; i < fOpLists.count(); ++i) { - fOpLists[i]->freeGpuResources(); - } - -} - -gr_instanced::OpAllocator* GrDrawingManager::instancingAllocator() { - if (fInstancingAllocator) { - return fInstancingAllocator.get(); - } - - fInstancingAllocator = fContext->getGpu()->createInstancedRenderingAllocator(); - return fInstancingAllocator.get(); } // MDB TODO: make use of the 'proxy' parameter. diff --git a/src/gpu/GrDrawingManager.h b/src/gpu/GrDrawingManager.h index fc17c69d3e..cbb28c494a 100644 --- a/src/gpu/GrDrawingManager.h +++ b/src/gpu/GrDrawingManager.h @@ -14,7 +14,6 @@ #include "GrRenderTargetOpList.h" #include "GrResourceCache.h" #include "SkTArray.h" -#include "instanced/InstancedRendering.h" #include "text/GrAtlasTextContext.h" class GrContext; @@ -39,8 +38,6 @@ public: bool wasAbandoned() const { return fAbandoned; } void freeGpuResources(); - gr_instanced::OpAllocator* instancingAllocator(); - sk_sp<GrRenderTargetContext> makeRenderTargetContext(sk_sp<GrSurfaceProxy>, sk_sp<SkColorSpace>, const SkSurfaceProps*, @@ -145,9 +142,6 @@ private: bool fFlushing; SkTArray<GrOnFlushCallbackObject*> fOnFlushCBObjects; - - // Lazily allocated - std::unique_ptr<gr_instanced::OpAllocator> fInstancingAllocator; }; #endif diff --git a/src/gpu/GrGpu.cpp b/src/gpu/GrGpu.cpp index 758d017027..5b338cdfa0 100644 --- a/src/gpu/GrGpu.cpp +++ b/src/gpu/GrGpu.cpp @@ -226,16 +226,6 @@ GrBuffer* GrGpu::createBuffer(size_t size, GrBufferType intendedType, return buffer; } -std::unique_ptr<gr_instanced::OpAllocator> GrGpu::createInstancedRenderingAllocator() { - SkASSERT(GrCaps::InstancedSupport::kNone != this->caps()->instancedSupport()); - return this->onCreateInstancedRenderingAllocator(); -} - -gr_instanced::InstancedRendering* GrGpu::createInstancedRendering() { - SkASSERT(GrCaps::InstancedSupport::kNone != this->caps()->instancedSupport()); - return this->onCreateInstancedRendering(); -} - bool GrGpu::copySurface(GrSurface* dst, GrSurfaceOrigin dstOrigin, GrSurface* src, GrSurfaceOrigin srcOrigin, const SkIRect& srcRect, const SkIPoint& dstPoint) { diff --git a/src/gpu/GrGpu.h b/src/gpu/GrGpu.h index 18ea772f23..cf91dbe53d 100644 --- a/src/gpu/GrGpu.h +++ b/src/gpu/GrGpu.h @@ -15,7 +15,6 @@ #include "GrTextureProducer.h" #include "GrTypes.h" #include "GrXferProcessor.h" -#include "instanced/InstancedRendering.h" #include "SkPath.h" #include "SkTArray.h" #include <map> @@ -42,12 +41,6 @@ class GrSurface; class GrTexture; class SkJSONWriter; -namespace gr_instanced { - class InstancedOp; - class InstancedRendering; - class OpAllocator; -} - class GrGpu : public SkRefCnt { public: /** @@ -153,12 +146,6 @@ public: const void* data = nullptr); /** - * Creates an instanced rendering object if it is supported on this platform. - */ - std::unique_ptr<gr_instanced::OpAllocator> createInstancedRenderingAllocator(); - gr_instanced::InstancedRendering* createInstancedRendering(); - - /** * Resolves MSAA. */ void resolveRenderTarget(GrRenderTarget*, GrSurfaceOrigin); @@ -567,11 +554,6 @@ private: virtual GrBuffer* onCreateBuffer(size_t size, GrBufferType intendedType, GrAccessPattern, const void* data) = 0; - virtual gr_instanced::InstancedRendering* onCreateInstancedRendering() = 0; - virtual std::unique_ptr<gr_instanced::OpAllocator> onCreateInstancedRenderingAllocator() { - return nullptr; - } - virtual bool onIsACopyNeededForTextureParams(GrTextureProxy* proxy, const GrSamplerState&, GrTextureProducer::CopyParams*, SkScalar scaleAdjust[2]) const { @@ -644,7 +626,6 @@ private: GrContext* fContext; friend class GrPathRendering; - friend class gr_instanced::InstancedOp; // for xferBarrier typedef SkRefCnt INHERITED; }; diff --git a/src/gpu/GrOpList.h b/src/gpu/GrOpList.h index 90629642f6..9cd72be0ad 100644 --- a/src/gpu/GrOpList.h +++ b/src/gpu/GrOpList.h @@ -67,11 +67,6 @@ public: // https://bugs.chromium.org/p/skia/issues/detail?id=7111 virtual void endFlush(); - // TODO: in an MDB world, where the OpLists don't allocate GPU resources, it seems like - // these could go away - virtual void abandonGpuResources() = 0; - virtual void freeGpuResources() = 0; - bool isClosed() const { return this->isSetFlag(kClosed_Flag); } /* diff --git a/src/gpu/GrRenderTargetContext.cpp b/src/gpu/GrRenderTargetContext.cpp index 1f7f6458ae..03d49bc2bb 100644 --- a/src/gpu/GrRenderTargetContext.cpp +++ b/src/gpu/GrRenderTargetContext.cpp @@ -31,7 +31,6 @@ #include "SkShadowUtils.h" #include "SkSurfacePriv.h" #include "effects/GrRRectEffect.h" -#include "instanced/InstancedRendering.h" #include "ops/GrAtlasTextOp.h" #include "ops/GrClearOp.h" #include "ops/GrClearStencilClipOp.h" @@ -155,7 +154,6 @@ GrRenderTargetContext::GrRenderTargetContext(GrContext* context, singleOwner) , fRenderTargetProxy(std::move(rtp)) , fOpList(sk_ref_sp(fRenderTargetProxy->getLastRenderTargetOpList())) - , fInstancedPipelineInfo(fRenderTargetProxy.get()) , fSurfaceProps(SkSurfacePropsCopyOrDefault(surfaceProps)) , fManagedOpList(managedOpList) { #ifdef SK_DISABLE_EXPLICIT_GPU_RESOURCE_ALLOCATION @@ -467,16 +465,6 @@ bool GrRenderTargetContext::drawFilledRect(const GrClip& clip, return true; } - if (GrCaps::InstancedSupport::kNone != fContext->caps()->instancedSupport() && - (!ss || ss->isDisabled(false))) { - gr_instanced::OpAllocator* oa = this->drawingManager()->instancingAllocator(); - std::unique_ptr<GrDrawOp> op = oa->recordRect(croppedRect, viewMatrix, std::move(paint), - aa, fInstancedPipelineInfo); - if (op) { - this->addDrawOp(clip, std::move(op)); - return true; - } - } GrAAType aaType = this->chooseAAType(aa, GrAllowMixedSamples::kNo); std::unique_ptr<GrDrawOp> op; if (GrAAType::kCoverage == aaType) { @@ -734,16 +722,6 @@ void GrRenderTargetContext::fillRectToRect(const GrClip& clip, AutoCheckFlush acf(this->drawingManager()); - if (GrCaps::InstancedSupport::kNone != fContext->caps()->instancedSupport()) { - gr_instanced::OpAllocator* oa = this->drawingManager()->instancingAllocator(); - std::unique_ptr<GrDrawOp> op(oa->recordRect(croppedRect, viewMatrix, std::move(paint), - croppedLocalRect, aa, fInstancedPipelineInfo)); - if (op) { - this->addDrawOp(clip, std::move(op)); - return; - } - } - GrAAType aaType = this->chooseAAType(aa, GrAllowMixedSamples::kNo); if (GrAAType::kCoverage != aaType) { std::unique_ptr<GrDrawOp> op = GrRectOpFactory::MakeNonAAFillWithLocalRect( @@ -833,16 +811,6 @@ void GrRenderTargetContext::fillRectWithLocalMatrix(const GrClip& clip, AutoCheckFlush acf(this->drawingManager()); - if (GrCaps::InstancedSupport::kNone != fContext->caps()->instancedSupport()) { - gr_instanced::OpAllocator* oa = this->drawingManager()->instancingAllocator(); - std::unique_ptr<GrDrawOp> op(oa->recordRect(croppedRect, viewMatrix, std::move(paint), - localMatrix, aa, fInstancedPipelineInfo)); - if (op) { - this->addDrawOp(clip, std::move(op)); - return; - } - } - GrAAType aaType = this->chooseAAType(aa, GrAllowMixedSamples::kNo); if (GrAAType::kCoverage != aaType) { std::unique_ptr<GrDrawOp> op = GrRectOpFactory::MakeNonAAFillWithLocalMatrix( @@ -949,17 +917,6 @@ void GrRenderTargetContext::drawRRect(const GrClip& origClip, AutoCheckFlush acf(this->drawingManager()); const SkStrokeRec stroke = style.strokeRec(); - if (GrCaps::InstancedSupport::kNone != fContext->caps()->instancedSupport() && - stroke.isFillStyle()) { - gr_instanced::OpAllocator* oa = this->drawingManager()->instancingAllocator(); - std::unique_ptr<GrDrawOp> op( - oa->recordRRect(rrect, viewMatrix, std::move(paint), aa, fInstancedPipelineInfo)); - if (op) { - this->addDrawOp(*clip, std::move(op)); - return; - } - } - GrAAType aaType = this->chooseAAType(aa, GrAllowMixedSamples::kNo); if (GrAAType::kCoverage == aaType) { const GrShaderCaps* shaderCaps = fContext->caps()->shaderCaps(); @@ -1214,16 +1171,6 @@ bool GrRenderTargetContext::drawFilledDRRect(const GrClip& clip, SkASSERT(!origInner.isEmpty()); SkASSERT(!origOuter.isEmpty()); - if (GrCaps::InstancedSupport::kNone != fContext->caps()->instancedSupport()) { - gr_instanced::OpAllocator* oa = this->drawingManager()->instancingAllocator(); - std::unique_ptr<GrDrawOp> op(oa->recordDRRect( - origOuter, origInner, viewMatrix, std::move(paint), aa, fInstancedPipelineInfo)); - if (op) { - this->addDrawOp(clip, std::move(op)); - return true; - } - } - SkTCopyOnFirstWrite<SkRRect> inner(origInner), outer(origOuter); GrAAType aaType = this->chooseAAType(aa, GrAllowMixedSamples::kNo); @@ -1386,17 +1333,6 @@ void GrRenderTargetContext::drawOval(const GrClip& clip, AutoCheckFlush acf(this->drawingManager()); const SkStrokeRec& stroke = style.strokeRec(); - if (GrCaps::InstancedSupport::kNone != fContext->caps()->instancedSupport() && - stroke.isFillStyle()) { - gr_instanced::OpAllocator* oa = this->drawingManager()->instancingAllocator(); - std::unique_ptr<GrDrawOp> op( - oa->recordOval(oval, viewMatrix, std::move(paint), aa, fInstancedPipelineInfo)); - if (op) { - this->addDrawOp(clip, std::move(op)); - return; - } - } - GrAAType aaType = this->chooseAAType(aa, GrAllowMixedSamples::kNo); if (GrAAType::kCoverage == aaType) { const GrShaderCaps* shaderCaps = fContext->caps()->shaderCaps(); diff --git a/src/gpu/GrRenderTargetContext.h b/src/gpu/GrRenderTargetContext.h index 82517b54f8..127063e097 100644 --- a/src/gpu/GrRenderTargetContext.h +++ b/src/gpu/GrRenderTargetContext.h @@ -8,7 +8,6 @@ #ifndef GrRenderTargetContext_DEFINED #define GrRenderTargetContext_DEFINED -#include "../private/GrInstancedPipelineInfo.h" #include "../private/GrRenderTargetProxy.h" #include "GrColor.h" #include "GrContext.h" @@ -453,7 +452,6 @@ private: // In MDB-mode the GrOpList can be closed by some other renderTargetContext that has picked // it up. For this reason, the GrOpList should only ever be accessed via 'getOpList'. sk_sp<GrRenderTargetOpList> fOpList; - GrInstancedPipelineInfo fInstancedPipelineInfo; SkSurfaceProps fSurfaceProps; bool fManagedOpList; diff --git a/src/gpu/GrRenderTargetContextPriv.h b/src/gpu/GrRenderTargetContextPriv.h index f74471b038..41fc725a21 100644 --- a/src/gpu/GrRenderTargetContextPriv.h +++ b/src/gpu/GrRenderTargetContextPriv.h @@ -23,10 +23,6 @@ struct GrUserStencilSettings; additional data members or virtual methods. */ class GrRenderTargetContextPriv { public: - gr_instanced::InstancedRendering* accessInstancedRendering() const { - return fRenderTargetContext->getRTOpList()->instancedRendering(); - } - // called to note the last clip drawn to the stencil buffer. // TODO: remove after clipping overhaul. void setLastClip(uint32_t clipStackGenID, const SkIRect& devClipBounds, diff --git a/src/gpu/GrRenderTargetOpList.cpp b/src/gpu/GrRenderTargetOpList.cpp index add5eb42d5..09ce76009a 100644 --- a/src/gpu/GrRenderTargetOpList.cpp +++ b/src/gpu/GrRenderTargetOpList.cpp @@ -13,12 +13,10 @@ #include "GrRect.h" #include "GrRenderTargetContext.h" #include "GrResourceAllocator.h" -#include "instanced/InstancedRendering.h" #include "ops/GrClearOp.h" #include "ops/GrCopySurfaceOp.h" #include "SkTraceEvent.h" -using gr_instanced::InstancedRendering; //////////////////////////////////////////////////////////////////////////////// @@ -31,9 +29,6 @@ GrRenderTargetOpList::GrRenderTargetOpList(GrRenderTargetProxy* proxy, GrGpu* gp : INHERITED(gpu->getContext()->resourceProvider(), proxy, auditTrail) , fLastClipStackGenID(SK_InvalidUniqueID) SkDEBUGCODE(, fNumClips(0)) { - if (GrCaps::InstancedSupport::kNone != gpu->caps()->instancedSupport()) { - fInstancedRendering.reset(gpu->createInstancedRendering()); - } } GrRenderTargetOpList::~GrRenderTargetOpList() { @@ -93,10 +88,6 @@ void GrRenderTargetOpList::onPrepare(GrOpFlushState* flushState) { flushState->setOpArgs(nullptr); } } - - if (fInstancedRendering) { - fInstancedRendering->beginFlush(flushState->resourceProvider()); - } } static std::unique_ptr<GrGpuRTCommandBuffer> create_command_buffer(GrGpu* gpu, @@ -192,26 +183,9 @@ void GrRenderTargetOpList::endFlush() { fLastClipStackGenID = SK_InvalidUniqueID; fRecordedOps.reset(); fClipAllocator.reset(); - if (fInstancedRendering) { - fInstancedRendering->endFlush(); - fInstancedRendering = nullptr; - } - INHERITED::endFlush(); } -void GrRenderTargetOpList::abandonGpuResources() { - if (fInstancedRendering) { - fInstancedRendering->resetGpuResources(InstancedRendering::ResetType::kAbandon); - } -} - -void GrRenderTargetOpList::freeGpuResources() { - if (fInstancedRendering) { - fInstancedRendering->resetGpuResources(InstancedRendering::ResetType::kDestroy); - } -} - void GrRenderTargetOpList::discard() { // Discard calls to in-progress opLists are ignored. Calls at the start update the // opLists' color & stencil load ops. diff --git a/src/gpu/GrRenderTargetOpList.h b/src/gpu/GrRenderTargetOpList.h index 93bab91051..5803d38f37 100644 --- a/src/gpu/GrRenderTargetOpList.h +++ b/src/gpu/GrRenderTargetOpList.h @@ -27,10 +27,6 @@ class GrClearOp; class GrCaps; class GrRenderTargetProxy; -namespace gr_instanced { - class InstancedRendering; -} - class GrRenderTargetOpList final : public GrOpList { private: using DstProxy = GrXferProcessor::DstProxy; @@ -57,9 +53,6 @@ public: */ void endFlush() override; - void abandonGpuResources() override; - void freeGpuResources() override; - /** * Together these two functions flush all queued up draws to GrCommandBuffer. The return value * of executeOps() indicates whether any commands were actually issued to the GPU. @@ -114,11 +107,6 @@ public: const SkIRect& srcRect, const SkIPoint& dstPoint) override; - gr_instanced::InstancedRendering* instancedRendering() const { - SkASSERT(fInstancedRendering); - return fInstancedRendering.get(); - } - GrRenderTargetOpList* asRenderTargetOpList() override { return this; } SkDEBUGCODE(void dump() const override;) @@ -166,8 +154,6 @@ private: bool combineIfPossible(const RecordedOp& a, GrOp* b, const GrAppliedClip* bClip, const DstProxy* bDstTexture, const GrCaps&); - std::unique_ptr<gr_instanced::InstancedRendering> fInstancedRendering; - uint32_t fLastClipStackGenID; SkIRect fLastDevClipBounds; int fLastClipNumAnalyticFPs; diff --git a/src/gpu/GrTextureOpList.h b/src/gpu/GrTextureOpList.h index 1b37ff27da..aa9cb2ea1f 100644 --- a/src/gpu/GrTextureOpList.h +++ b/src/gpu/GrTextureOpList.h @@ -31,9 +31,6 @@ public: */ void endFlush() override; - void abandonGpuResources() override {} - void freeGpuResources() override {} - /** * Together these two functions flush all queued ops to GrGpuCommandBuffer. The return value * of executeOps() indicates whether any commands were actually issued to the GPU. diff --git a/src/gpu/gl/GrGLCaps.cpp b/src/gpu/gl/GrGLCaps.cpp index 4daabda0c0..3a51eb0e0d 100644 --- a/src/gpu/gl/GrGLCaps.cpp +++ b/src/gpu/gl/GrGLCaps.cpp @@ -15,7 +15,6 @@ #include "SkJSONWriter.h" #include "SkTSearch.h" #include "SkTSort.h" -#include "instanced/GLInstancedRendering.h" GrGLCaps::GrGLCaps(const GrContextOptions& contextOptions, const GrGLContextInfo& ctxInfo, @@ -2336,14 +2335,6 @@ bool GrGLCaps::initDescForDstCopy(const GrRenderTargetProxy* src, GrSurfaceDesc* } void GrGLCaps::onApplyOptionsOverrides(const GrContextOptions& options) { - if (options.fEnableInstancedRendering) { - fInstancedSupport = gr_instanced::GLInstancedRendering::CheckSupport(*this); -#ifndef SK_BUILD_FOR_MAC - // OS X doesn't seem to write correctly to floating point textures when using - // glDraw*Indirect, regardless of the underlying GPU. - fAvoidInstancedDrawsToFPTargets = true; -#endif - } if (options.fUseDrawInsteadOfPartialRenderTargetWrite) { fUseDrawInsteadOfAllRenderTargetWrites = true; } diff --git a/src/gpu/gl/GrGLGpu.cpp b/src/gpu/gl/GrGLGpu.cpp index fe860c4610..c11f598b7a 100644 --- a/src/gpu/gl/GrGLGpu.cpp +++ b/src/gpu/gl/GrGLGpu.cpp @@ -37,7 +37,6 @@ #include "SkTraceEvent.h" #include "SkTypes.h" #include "builders/GrGLShaderStringBuilder.h" -#include "instanced/GLInstancedRendering.h" #define GL_CALL(X) GR_GL_CALL(this->glInterface(), X) #define GL_CALL_RET(RET, X) GR_GL_CALL_RET(this->glInterface(), RET, X) @@ -58,12 +57,6 @@ /////////////////////////////////////////////////////////////////////////////// -using gr_instanced::InstancedRendering; -using gr_instanced::GLInstancedRendering; - -using gr_instanced::OpAllocator; -using gr_instanced::GLOpAllocator; - static const GrGLenum gXfermodeEquation2Blend[] = { // Basic OpenGL blend equations. GR_GL_FUNC_ADD, @@ -1732,15 +1725,6 @@ GrBuffer* GrGLGpu::onCreateBuffer(size_t size, GrBufferType intendedType, return GrGLBuffer::Create(this, size, intendedType, accessPattern, data); } - -std::unique_ptr<OpAllocator> GrGLGpu::onCreateInstancedRenderingAllocator() { - return std::unique_ptr<OpAllocator>(new GLOpAllocator(this->caps())); -} - -InstancedRendering* GrGLGpu::onCreateInstancedRendering() { - return new GLInstancedRendering(this); -} - void GrGLGpu::flushScissor(const GrScissorState& scissorState, const GrGLIRect& rtViewport, GrSurfaceOrigin rtOrigin) { diff --git a/src/gpu/gl/GrGLGpu.h b/src/gpu/gl/GrGLGpu.h index cd78a6455c..3d9533d2bb 100644 --- a/src/gpu/gl/GrGLGpu.h +++ b/src/gpu/gl/GrGLGpu.h @@ -28,8 +28,6 @@ class GrGLBuffer; class GrPipeline; class GrSwizzle; -namespace gr_instanced { class GLInstancedRendering; } - #ifdef SK_DEBUG #define PROGRAM_CACHE_STATS #endif @@ -211,9 +209,6 @@ private: sk_sp<GrRenderTarget> onWrapBackendTextureAsRenderTarget(const GrBackendTexture&, int sampleCnt) override; - std::unique_ptr<gr_instanced::OpAllocator> onCreateInstancedRenderingAllocator() override; - gr_instanced::InstancedRendering* onCreateInstancedRendering() override; - // Given a GrPixelConfig return the index into the stencil format array on GrGLCaps to a // compatible stencil format, or negative if there is no compatible stencil format. int getCompatibleStencilIndex(GrPixelConfig config); @@ -650,7 +645,6 @@ private: typedef GrGpu INHERITED; friend class GrGLPathRendering; // For accessing setTextureUnit. - friend class gr_instanced::GLInstancedRendering; // For accessing flushGLState. }; #endif diff --git a/src/gpu/instanced/GLInstancedRendering.cpp b/src/gpu/instanced/GLInstancedRendering.cpp deleted file mode 100644 index bb733c2b81..0000000000 --- a/src/gpu/instanced/GLInstancedRendering.cpp +++ /dev/null @@ -1,330 +0,0 @@ -/* - * Copyright 2016 Google Inc. - * - * Use of this source code is governed by a BSD-style license that can be - * found in the LICENSE file. - */ - -#include "GLInstancedRendering.h" - -#include "GrResourceProvider.h" -#include "gl/GrGLGpu.h" -#include "instanced/InstanceProcessor.h" - -#define GL_CALL(X) GR_GL_CALL(this->glGpu()->glInterface(), X) - -namespace gr_instanced { - -class GLInstancedOp final : public InstancedOp { -public: - DEFINE_OP_CLASS_ID - - GLInstancedOp(GLOpAllocator* alloc, GrPaint&& paint) - : INHERITED(ClassID(), std::move(paint), alloc) { - } - int numGLCommands() const { return 1 + fNumChangesInGeometry; } - -private: - int fEmulatedBaseInstance; - int fGLDrawCmdsIdx; - - friend class GLInstancedRendering; - - typedef InstancedOp INHERITED; -}; - -GrCaps::InstancedSupport GLInstancedRendering::CheckSupport(const GrGLCaps& glCaps) { - // This method is only intended to be used for initializing fInstancedSupport in the caps. - SkASSERT(GrCaps::InstancedSupport::kNone == glCaps.instancedSupport()); - if (!glCaps.vertexArrayObjectSupport() || - (!glCaps.drawIndirectSupport() && !glCaps.drawInstancedSupport()) || - GrGLCaps::kNone_MapBufferType == glCaps.mapBufferType()) { - return GrCaps::InstancedSupport::kNone; - } - return InstanceProcessor::CheckSupport(*glCaps.shaderCaps(), glCaps); -} - -GLInstancedRendering::GLInstancedRendering(GrGLGpu* gpu) - : INHERITED(gpu) - , fVertexArrayID(0) - , fGLDrawCmdsInfo(0) - , fInstanceAttribsBufferUniqueId(SK_InvalidUniqueID) { - SkASSERT(GrCaps::InstancedSupport::kNone != this->gpu()->caps()->instancedSupport()); -} - -GLInstancedRendering::~GLInstancedRendering() { - if (fVertexArrayID) { - GL_CALL(DeleteVertexArrays(1, &fVertexArrayID)); - this->glGpu()->notifyVertexArrayDelete(fVertexArrayID); - } -} - -inline GrGLGpu* GLInstancedRendering::glGpu() const { - return static_cast<GrGLGpu*>(this->gpu()); -} - -std::unique_ptr<InstancedOp> GLOpAllocator::makeOp(GrPaint&& paint) { - return std::unique_ptr<InstancedOp>(new GLInstancedOp(this, std::move(paint))); -} - -void GLInstancedRendering::onBeginFlush(GrResourceProvider* rp) { - // Count what there is to draw. - OpList::Iter iter; - iter.init(this->trackedOps(), OpList::Iter::kHead_IterStart); - int numGLInstances = 0; - int numGLDrawCmds = 0; - while (InstancedOp* o = iter.get()) { - GLInstancedOp* op = (GLInstancedOp*) o; - iter.next(); - - numGLInstances += op->fNumDraws; - numGLDrawCmds += op->numGLCommands(); - } - if (!numGLDrawCmds) { - return; - } - SkASSERT(numGLInstances); - - // Lazily create a vertex array object. - if (!fVertexArrayID) { - GL_CALL(GenVertexArrays(1, &fVertexArrayID)); - if (!fVertexArrayID) { - return; - } - this->glGpu()->bindVertexArray(fVertexArrayID); - - // Attach our index buffer to the vertex array. - SkASSERT(!this->indexBuffer()->isCPUBacked()); - GL_CALL(BindBuffer(GR_GL_ELEMENT_ARRAY_BUFFER, - static_cast<const GrGLBuffer*>(this->indexBuffer())->bufferID())); - - // Set up the non-instanced attribs. - this->glGpu()->bindBuffer(kVertex_GrBufferType, this->vertexBuffer()); - GL_CALL(EnableVertexAttribArray((int)Attrib::kShapeCoords)); - GL_CALL(VertexAttribPointer((int)Attrib::kShapeCoords, 2, GR_GL_FLOAT, GR_GL_FALSE, - sizeof(ShapeVertex), (void*) offsetof(ShapeVertex, fX))); - GL_CALL(EnableVertexAttribArray((int)Attrib::kVertexAttrs)); - GL_CALL(VertexAttribIPointer((int)Attrib::kVertexAttrs, 1, GR_GL_INT, sizeof(ShapeVertex), - (void*) offsetof(ShapeVertex, fAttrs))); - - SkASSERT(fInstanceAttribsBufferUniqueId.isInvalid()); - } - - // Create and map instance and draw-indirect buffers. - SkASSERT(!fInstanceBuffer); - fInstanceBuffer.reset( - rp->createBuffer(sizeof(Instance) * numGLInstances, kVertex_GrBufferType, - kDynamic_GrAccessPattern, - GrResourceProvider::kNoPendingIO_Flag | - GrResourceProvider::kRequireGpuMemory_Flag)); - if (!fInstanceBuffer) { - return; - } - - SkASSERT(!fDrawIndirectBuffer); - if (this->glGpu()->glCaps().drawIndirectSupport()) { - fDrawIndirectBuffer.reset( - rp->createBuffer(sizeof(GrGLDrawElementsIndirectCommand) * numGLDrawCmds, - kDrawIndirect_GrBufferType, kDynamic_GrAccessPattern, - GrResourceProvider::kNoPendingIO_Flag | - GrResourceProvider::kRequireGpuMemory_Flag)); - if (!fDrawIndirectBuffer) { - return; - } - } - - Instance* glMappedInstances = static_cast<Instance*>(fInstanceBuffer->map()); - SkASSERT(glMappedInstances); - int glInstancesIdx = 0; - - GrGLDrawElementsIndirectCommand* glMappedCmds = nullptr; - int glDrawCmdsIdx = 0; - if (fDrawIndirectBuffer) { - glMappedCmds = static_cast<GrGLDrawElementsIndirectCommand*>(fDrawIndirectBuffer->map()); - SkASSERT(glMappedCmds); - } - - bool baseInstanceSupport = this->glGpu()->glCaps().baseInstanceSupport(); - SkASSERT(!baseInstanceSupport || fDrawIndirectBuffer); - - SkASSERT(!fGLDrawCmdsInfo); - if (GR_GL_LOG_INSTANCED_OPS || !baseInstanceSupport) { - fGLDrawCmdsInfo.reset(numGLDrawCmds); - } - - // Generate the instance and draw-indirect buffer contents based on the tracked ops. - iter.init(this->trackedOps(), OpList::Iter::kHead_IterStart); - while (InstancedOp* o = iter.get()) { - GLInstancedOp* op = static_cast<GLInstancedOp*>(o); - iter.next(); - - op->fEmulatedBaseInstance = baseInstanceSupport ? 0 : glInstancesIdx; - op->fGLDrawCmdsIdx = glDrawCmdsIdx; - - const InstancedOp::Draw* draw = op->fHeadDraw; - SkASSERT(draw); - do { - int instanceCount = 0; - IndexRange geometry = draw->fGeometry; - SkASSERT(!geometry.isEmpty()); - - do { - glMappedInstances[glInstancesIdx + instanceCount++] = draw->fInstance; - draw = draw->fNext; - } while (draw && draw->fGeometry == geometry); - - if (fDrawIndirectBuffer) { - GrGLDrawElementsIndirectCommand& glCmd = glMappedCmds[glDrawCmdsIdx]; - glCmd.fCount = geometry.fCount; - glCmd.fInstanceCount = instanceCount; - glCmd.fFirstIndex = geometry.fStart; - glCmd.fBaseVertex = 0; - glCmd.fBaseInstance = baseInstanceSupport ? glInstancesIdx : 0; - } - - if (GR_GL_LOG_INSTANCED_OPS || !baseInstanceSupport) { - GLDrawCmdInfo& cmdInfo = fGLDrawCmdsInfo[glDrawCmdsIdx]; - cmdInfo.fGeometry = geometry; - cmdInfo.fInstanceCount = instanceCount; - } - - glInstancesIdx += instanceCount; - ++glDrawCmdsIdx; - } while (draw); - } - - SkASSERT(glDrawCmdsIdx == numGLDrawCmds); - if (fDrawIndirectBuffer) { - fDrawIndirectBuffer->unmap(); - } - - SkASSERT(glInstancesIdx == numGLInstances); - fInstanceBuffer->unmap(); -} - -void GLInstancedRendering::onDraw(const GrPipeline& pipeline, const InstanceProcessor& instProc, - const InstancedOp* baseOp) { - if (!fDrawIndirectBuffer && !fGLDrawCmdsInfo) { - return; // beginFlush was not successful. - } - if (!this->glGpu()->flushGLState(pipeline, instProc, false)) { - return; - } - - if (fDrawIndirectBuffer) { - this->glGpu()->bindBuffer(kDrawIndirect_GrBufferType, fDrawIndirectBuffer.get()); - } - - const GrGLCaps& glCaps = this->glGpu()->glCaps(); - const GLInstancedOp* op = static_cast<const GLInstancedOp*>(baseOp); - int numCommands = op->numGLCommands(); - -#if GR_GL_LOG_INSTANCED_OPS - SkASSERT(fGLDrawCmdsInfo); - SkDebugf("Instanced op: ["); - for (int i = 0; i < numCommands; ++i) { - int glCmdIdx = op->fGLDrawCmdsIdx + i; - SkDebugf("%s%i * %s", (i ? ", " : ""), fGLDrawCmdsInfo[glCmdIdx].fInstanceCount, - InstanceProcessor::GetNameOfIndexRange(fGLDrawCmdsInfo[glCmdIdx].fGeometry)); - } - SkDebugf("]\n"); -#else - SkASSERT(SkToBool(fGLDrawCmdsInfo) == !glCaps.baseInstanceSupport()); -#endif - - if (numCommands > 1 && glCaps.multiDrawIndirectSupport() && glCaps.baseInstanceSupport()) { - SkASSERT(fDrawIndirectBuffer); - int glCmdsIdx = op->fGLDrawCmdsIdx; - this->flushInstanceAttribs(op->fEmulatedBaseInstance); - uintptr_t glCmdsOffset = glCmdsIdx * sizeof(GrGLDrawElementsIndirectCommand); - GL_CALL(MultiDrawElementsIndirect(GR_GL_TRIANGLES, GR_GL_UNSIGNED_BYTE, - reinterpret_cast<const void*>(glCmdsOffset), - numCommands, 0)); - return; - } - - int emulatedBaseInstance = op->fEmulatedBaseInstance; - for (int i = 0; i < numCommands; ++i) { - int glCmdIdx = op->fGLDrawCmdsIdx + i; - this->flushInstanceAttribs(emulatedBaseInstance); - if (fDrawIndirectBuffer) { - uintptr_t glCmdOffset = glCmdIdx * sizeof(GrGLDrawElementsIndirectCommand); - GL_CALL(DrawElementsIndirect(GR_GL_TRIANGLES, GR_GL_UNSIGNED_BYTE, - reinterpret_cast<const void*>(glCmdOffset))); - } else { - const GLDrawCmdInfo& cmdInfo = fGLDrawCmdsInfo[glCmdIdx]; - GL_CALL(DrawElementsInstanced(GR_GL_TRIANGLES, cmdInfo.fGeometry.fCount, - GR_GL_UNSIGNED_BYTE, - reinterpret_cast<const void*>(cmdInfo.fGeometry.fStart), - cmdInfo.fInstanceCount)); - } - if (!glCaps.baseInstanceSupport()) { - const GLDrawCmdInfo& cmdInfo = fGLDrawCmdsInfo[glCmdIdx]; - emulatedBaseInstance += cmdInfo.fInstanceCount; - } - } -} - -void GLInstancedRendering::flushInstanceAttribs(int baseInstance) { - SkASSERT(fVertexArrayID); - this->glGpu()->bindVertexArray(fVertexArrayID); - - SkASSERT(fInstanceBuffer); - if (fInstanceAttribsBufferUniqueId != fInstanceBuffer->uniqueID() || - fInstanceAttribsBaseInstance != baseInstance) { - uintptr_t offsetInBuffer = baseInstance * sizeof(Instance); - const Instance* offsetAsPtr = reinterpret_cast<const Instance*>(offsetInBuffer); - - this->glGpu()->bindBuffer(kVertex_GrBufferType, fInstanceBuffer.get()); - - // Info attrib. - GL_CALL(EnableVertexAttribArray((int)Attrib::kInstanceInfo)); - GL_CALL(VertexAttribIPointer((int)Attrib::kInstanceInfo, 1, GR_GL_UNSIGNED_INT, - sizeof(Instance), &offsetAsPtr->fInfo)); - GL_CALL(VertexAttribDivisor((int)Attrib::kInstanceInfo, 1)); - - // Shape matrix attrib. - GL_CALL(EnableVertexAttribArray((int)Attrib::kShapeMatrixX)); - GL_CALL(EnableVertexAttribArray((int)Attrib::kShapeMatrixY)); - GL_CALL(VertexAttribPointer((int)Attrib::kShapeMatrixX, 3, GR_GL_FLOAT, GR_GL_FALSE, - sizeof(Instance), &offsetAsPtr->fShapeMatrix2x3[0])); - GL_CALL(VertexAttribPointer((int)Attrib::kShapeMatrixY, 3, GR_GL_FLOAT, GR_GL_FALSE, - sizeof(Instance), &offsetAsPtr->fShapeMatrix2x3[3])); - GL_CALL(VertexAttribDivisor((int)Attrib::kShapeMatrixX, 1)); - GL_CALL(VertexAttribDivisor((int)Attrib::kShapeMatrixY, 1)); - - // Color attrib. - GL_CALL(EnableVertexAttribArray((int)Attrib::kColor)); - GL_CALL(VertexAttribPointer((int)Attrib::kColor, 4, GR_GL_UNSIGNED_BYTE, GR_GL_TRUE, - sizeof(Instance), &offsetAsPtr->fColor)); - GL_CALL(VertexAttribDivisor((int)Attrib::kColor, 1)); - - // Local rect attrib. - GL_CALL(EnableVertexAttribArray((int)Attrib::kLocalRect)); - GL_CALL(VertexAttribPointer((int)Attrib::kLocalRect, 4, GR_GL_FLOAT, GR_GL_FALSE, - sizeof(Instance), &offsetAsPtr->fLocalRect)); - GL_CALL(VertexAttribDivisor((int)Attrib::kLocalRect, 1)); - - fInstanceAttribsBufferUniqueId = fInstanceBuffer->uniqueID(); - fInstanceAttribsBaseInstance = baseInstance; - } -} - -void GLInstancedRendering::onEndFlush() { - fInstanceBuffer.reset(); - fDrawIndirectBuffer.reset(); - fGLDrawCmdsInfo.reset(0); -} - -void GLInstancedRendering::onResetGpuResources(ResetType resetType) { - if (fVertexArrayID && ResetType::kDestroy == resetType) { - GL_CALL(DeleteVertexArrays(1, &fVertexArrayID)); - this->glGpu()->notifyVertexArrayDelete(fVertexArrayID); - } - fVertexArrayID = 0; - fInstanceBuffer.reset(); - fDrawIndirectBuffer.reset(); - fInstanceAttribsBufferUniqueId.makeInvalid(); -} - -} diff --git a/src/gpu/instanced/GLInstancedRendering.h b/src/gpu/instanced/GLInstancedRendering.h deleted file mode 100644 index d68bc86cde..0000000000 --- a/src/gpu/instanced/GLInstancedRendering.h +++ /dev/null @@ -1,73 +0,0 @@ -/* - * Copyright 2016 Google Inc. - * - * Use of this source code is governed by a BSD-style license that can be - * found in the LICENSE file. - */ - -#ifndef gr_instanced_GLInstancedRendering_DEFINED -#define gr_instanced_GLInstancedRendering_DEFINED - -#include "GrCaps.h" -#include "gl/GrGLBuffer.h" -#include "instanced/InstancedOp.h" -#include "instanced/InstancedRendering.h" - -class GrGLCaps; -class GrGLGpu; - -#define GR_GL_LOG_INSTANCED_OPS 0 - -namespace gr_instanced { - -class GLOpAllocator final : public OpAllocator { -public: - GLOpAllocator(const GrCaps* caps) : INHERITED(caps) {} - -private: - std::unique_ptr<InstancedOp> makeOp(GrPaint&& paint) override; - - typedef OpAllocator INHERITED; -}; - -class GLInstancedRendering final : public InstancedRendering { -public: - GLInstancedRendering(GrGLGpu*); - ~GLInstancedRendering() override; - -private: - /** - * Called by GrGLCaps to determine the level of support this class can offer for instanced - * rendering on the current platform. - */ - static GrCaps::InstancedSupport CheckSupport(const GrGLCaps&); - - GrGLGpu* glGpu() const; - - void onBeginFlush(GrResourceProvider*) override; - void onDraw(const GrPipeline&, const InstanceProcessor&, const InstancedOp*) override; - void onEndFlush() override; - void onResetGpuResources(ResetType) override; - - void flushInstanceAttribs(int baseInstance); - - struct GLDrawCmdInfo { - IndexRange fGeometry; - int fInstanceCount; - }; - - GrGLuint fVertexArrayID; - sk_sp<GrBuffer> fInstanceBuffer; - sk_sp<GrBuffer> fDrawIndirectBuffer; - SkAutoSTMalloc<1024, GLDrawCmdInfo> fGLDrawCmdsInfo; - GrGpuResource::UniqueID fInstanceAttribsBufferUniqueId; - int fInstanceAttribsBaseInstance; - - friend class ::GrGLCaps; // For CheckSupport. - - typedef InstancedRendering INHERITED; -}; - -} - -#endif diff --git a/src/gpu/instanced/InstanceProcessor.cpp b/src/gpu/instanced/InstanceProcessor.cpp deleted file mode 100644 index f99a0dbc48..0000000000 --- a/src/gpu/instanced/InstanceProcessor.cpp +++ /dev/null @@ -1,2088 +0,0 @@ -/* - * Copyright 2016 Google Inc. - * - * Use of this source code is governed by a BSD-style license that can be - * found in the LICENSE file. - */ - -#include "InstanceProcessor.h" - -#include "GrContext.h" -#include "GrRenderTargetPriv.h" -#include "GrResourceCache.h" -#include "GrShaderCaps.h" -#include "glsl/GrGLSLGeometryProcessor.h" -#include "glsl/GrGLSLFragmentShaderBuilder.h" -#include "glsl/GrGLSLProgramBuilder.h" -#include "glsl/GrGLSLVarying.h" - -namespace gr_instanced { - -GrCaps::InstancedSupport InstanceProcessor::CheckSupport(const GrShaderCaps& shaderCaps, - const GrCaps& caps) { - if (!shaderCaps.canUseAnyFunctionInShader() || - !shaderCaps.flatInterpolationSupport() || - !shaderCaps.integerSupport() || - 0 == shaderCaps.maxVertexSamplers() || - !caps.shaderCaps()->texelBufferSupport() || - caps.maxVertexAttributes() < kNumAttribs) { - return GrCaps::InstancedSupport::kNone; - } - if (!caps.sampleLocationsSupport() || - !shaderCaps.sampleVariablesSupport() || - !shaderCaps.shaderDerivativeSupport()) { - return GrCaps::InstancedSupport::kBasic; - } - if (0 == caps.maxRasterSamples() || - !shaderCaps.sampleMaskOverrideCoverageSupport()) { - return GrCaps::InstancedSupport::kMultisampled; - } - return GrCaps::InstancedSupport::kMixedSampled; -} - -InstanceProcessor::InstanceProcessor(OpInfo opInfo, GrBuffer* paramsBuffer) -: INHERITED(kInstanceProcessor_ClassID) -, fOpInfo(opInfo) { - this->addVertexAttrib("shapeCoords", kFloat2_GrVertexAttribType); - this->addVertexAttrib("vertexAttrs", kInt_GrVertexAttribType); - this->addVertexAttrib("instanceInfo", kUint_GrVertexAttribType); - this->addVertexAttrib("shapeMatrixX", kFloat3_GrVertexAttribType); - this->addVertexAttrib("shapeMatrixY", kFloat3_GrVertexAttribType); - this->addVertexAttrib("color", kHalf4_GrVertexAttribType); - this->addVertexAttrib("localRect", kFloat4_GrVertexAttribType); - - GR_STATIC_ASSERT(0 == (int)Attrib::kShapeCoords); - GR_STATIC_ASSERT(1 == (int)Attrib::kVertexAttrs); - GR_STATIC_ASSERT(2 == (int)Attrib::kInstanceInfo); - GR_STATIC_ASSERT(3 == (int)Attrib::kShapeMatrixX); - GR_STATIC_ASSERT(4 == (int)Attrib::kShapeMatrixY); - GR_STATIC_ASSERT(5 == (int)Attrib::kColor); - GR_STATIC_ASSERT(6 == (int)Attrib::kLocalRect); - GR_STATIC_ASSERT(7 == kNumAttribs); - - if (fOpInfo.fHasParams) { - SkASSERT(paramsBuffer); - fParamsAccess.reset(kRGBA_float_GrPixelConfig, paramsBuffer, kVertex_GrShaderFlag); - this->addBufferAccess(&fParamsAccess); - } - - if (GrAATypeIsHW(fOpInfo.aaType())) { - if (!fOpInfo.isSimpleRects() || GrAAType::kMixedSamples == fOpInfo.aaType()) { - this->setWillUseSampleLocations(); - } - } -} - -class GLSLInstanceProcessor : public GrGLSLGeometryProcessor { -public: - void onEmitCode(EmitArgs& args, GrGPArgs* gpArgs) override; - -private: - void setData(const GrGLSLProgramDataManager& pdman, const GrPrimitiveProcessor&, - FPCoordTransformIter&& transformIter) override { - this->setTransformDataHelper(SkMatrix::I(), pdman, &transformIter); - } - - class VertexInputs; - class Backend; - class BackendNonAA; - class BackendCoverage; - class BackendMultisample; - - typedef GrGLSLGeometryProcessor INHERITED; -}; - -GrGLSLPrimitiveProcessor* InstanceProcessor::createGLSLInstance(const GrShaderCaps&) const { - return new GLSLInstanceProcessor(); -} - -class GLSLInstanceProcessor::VertexInputs { -public: - VertexInputs(const InstanceProcessor& instProc, GrGLSLVertexBuilder* vertexBuilder) - : fInstProc(instProc), - fVertexBuilder(vertexBuilder) { - } - - void initParams(const TexelBufferHandle paramsBuffer) { - fParamsBuffer = paramsBuffer; - fVertexBuilder->codeAppendf("int paramsIdx = int(%s & 0x%x);", - this->attr(Attrib::kInstanceInfo), - kParamsIdx_InfoMask); - } - - const char* attr(Attrib attr) const { return fInstProc.getAttrib((int)attr).fName; } - - void fetchNextParam(const GrShaderCaps* shaderCaps, GrSLType type = kHalf4_GrSLType) const { - SkASSERT(fParamsBuffer.isValid()); - switch (type) { - case kFloat2_GrSLType: // fall through - case kFloat3_GrSLType: // fall through - case kFloat4_GrSLType: // fall through - case kHalf2_GrSLType: // fall through - case kHalf3_GrSLType: // fall through - case kHalf4_GrSLType: - break; - default: - fVertexBuilder->codeAppendf("%s(", GrGLSLTypeString(shaderCaps, type)); - } - fVertexBuilder->appendTexelFetch(fParamsBuffer, "paramsIdx++"); - switch (type) { - case kFloat2_GrSLType: // fall through - case kHalf2_GrSLType: - fVertexBuilder->codeAppend(".xy"); - break; - case kFloat3_GrSLType: // fall through - case kHalf3_GrSLType: - fVertexBuilder->codeAppend(".xyz"); - break; - case kFloat4_GrSLType: // fall through - case kHalf4_GrSLType: - break; - default: - fVertexBuilder->codeAppend(")"); - } - } - - void skipParams(unsigned n) const { - SkASSERT(fParamsBuffer.isValid()); - fVertexBuilder->codeAppendf("paramsIdx += %u;", n); - } - -private: - const InstanceProcessor& fInstProc; - GrGLSLVertexBuilder* fVertexBuilder; - TexelBufferHandle fParamsBuffer; -}; - -class GLSLInstanceProcessor::Backend { -public: - static Backend* SK_WARN_UNUSED_RESULT Create(const GrPipeline&, OpInfo, const VertexInputs&); - virtual ~Backend() {} - - void init(GrGLSLVaryingHandler*, GrGLSLVertexBuilder*); - virtual void setupRect(GrGLSLVertexBuilder*) = 0; - virtual void setupOval(GrGLSLVertexBuilder*) = 0; - void setupRRect(const GrShaderCaps*, GrGLSLVertexBuilder*, int* usedShapeDefinitions); - - void initInnerShape(GrGLSLVaryingHandler*, GrGLSLVertexBuilder*); - virtual void setupInnerRect(GrGLSLVertexBuilder*) = 0; - virtual void setupInnerOval(GrGLSLVertexBuilder*) = 0; - void setupInnerSimpleRRect(const GrShaderCaps*, GrGLSLVertexBuilder*); - - const char* outShapeCoords() { - return fModifiedShapeCoords ? fModifiedShapeCoords : fInputs.attr(Attrib::kShapeCoords); - } - - void emitCode(GrGLSLVertexBuilder*, GrGLSLPPFragmentBuilder*, const char* outCoverage, - const char* outColor); - -protected: - Backend(OpInfo opInfo, const VertexInputs& inputs) - : fOpInfo(opInfo) - , fInputs(inputs) - , fModifiesCoverage(false) - , fModifiesColor(false) - , fNeedsNeighborRadii(false) - , fColor(kHalf4_GrSLType) - , fTriangleIsArc(kInt_GrSLType) - , fArcCoords(kHalf2_GrSLType) - , fInnerShapeCoords(kHalf2_GrSLType) - , fInnerRRect(kHalf4_GrSLType) - , fModifiedShapeCoords(nullptr) { - if (fOpInfo.fShapeTypes & kRRect_ShapesMask) { - fModifiedShapeCoords = "adjustedShapeCoords"; - } - } - - virtual void onInit(GrGLSLVaryingHandler*, GrGLSLVertexBuilder*) = 0; - virtual void adjustRRectVertices(GrGLSLVertexBuilder*); - virtual void onSetupRRect(GrGLSLVertexBuilder*) {} - - virtual void onInitInnerShape(GrGLSLVaryingHandler*, GrGLSLVertexBuilder*) = 0; - virtual void onSetupInnerSimpleRRect(GrGLSLVertexBuilder*) = 0; - - virtual void onEmitCode(GrGLSLVertexBuilder*, GrGLSLPPFragmentBuilder*, - const char* outCoverage, const char* outColor) = 0; - - void setupSimpleRadii(GrGLSLVertexBuilder*); - void setupNinePatchRadii(GrGLSLVertexBuilder*); - void setupComplexRadii(const GrShaderCaps*, GrGLSLVertexBuilder*); - - const OpInfo fOpInfo; - const VertexInputs& fInputs; - bool fModifiesCoverage; - bool fModifiesColor; - bool fNeedsNeighborRadii; - GrGLSLVertToFrag fColor; - GrGLSLVertToFrag fTriangleIsArc; - GrGLSLVertToFrag fArcCoords; - GrGLSLVertToFrag fInnerShapeCoords; - GrGLSLVertToFrag fInnerRRect; - const char* fModifiedShapeCoords; -}; - -void GLSLInstanceProcessor::onEmitCode(EmitArgs& args, GrGPArgs* gpArgs) { - const GrPipeline& pipeline = args.fVertBuilder->getProgramBuilder()->pipeline(); - const InstanceProcessor& ip = args.fGP.cast<InstanceProcessor>(); - GrGLSLUniformHandler* uniHandler = args.fUniformHandler; - GrGLSLVaryingHandler* varyingHandler = args.fVaryingHandler; - GrGLSLVertexBuilder* v = args.fVertBuilder; - GrGLSLPPFragmentBuilder* f = args.fFragBuilder; - - varyingHandler->emitAttributes(ip); - - VertexInputs inputs(ip, v); - if (ip.opInfo().fHasParams) { - SkASSERT(1 == ip.numBuffers()); - inputs.initParams(args.fTexelBuffers[0]); - } - - if (!ip.opInfo().fHasPerspective) { - v->codeAppendf("half2x3 shapeMatrix = half2x3(%s, %s);", - inputs.attr(Attrib::kShapeMatrixX), inputs.attr(Attrib::kShapeMatrixY)); - } else { - v->defineConstantf("int", "PERSPECTIVE_FLAG", "0x%x", kPerspective_InfoFlag); - v->codeAppendf("half3x3 shapeMatrix = half3x3(%s, %s, half3(0, 0, 1));", - inputs.attr(Attrib::kShapeMatrixX), inputs.attr(Attrib::kShapeMatrixY)); - v->codeAppendf("if (0 != (%s & uint(PERSPECTIVE_FLAG))) {", - inputs.attr(Attrib::kInstanceInfo)); - v->codeAppend ( "shapeMatrix[2] = "); - inputs.fetchNextParam(args.fShaderCaps, kHalf3_GrSLType); - v->codeAppend ( ";"); - v->codeAppend ("}"); - } - - bool hasSingleShapeType = SkIsPow2(ip.opInfo().fShapeTypes); - if (!hasSingleShapeType) { - v->defineConstant("SHAPE_TYPE_BIT", kShapeType_InfoBit); - v->codeAppendf("uint shapeType = %s >> uint(SHAPE_TYPE_BIT);", - inputs.attr(Attrib::kInstanceInfo)); - } - - std::unique_ptr<Backend> backend(Backend::Create(pipeline, ip.opInfo(), inputs)); - backend->init(varyingHandler, v); - - int usedShapeDefinitions = 0; - - if (hasSingleShapeType || !(ip.opInfo().fShapeTypes & ~kRRect_ShapesMask)) { - if (kRect_ShapeFlag == ip.opInfo().fShapeTypes) { - backend->setupRect(v); - } else if (kOval_ShapeFlag == ip.opInfo().fShapeTypes) { - backend->setupOval(v); - } else { - backend->setupRRect(args.fShaderCaps, v, &usedShapeDefinitions); - } - } else { - if (ip.opInfo().fShapeTypes & kRRect_ShapesMask) { - v->codeAppend ("if (shapeType >= uint(SIMPLE_R_RECT_SHAPE_TYPE)) {"); - backend->setupRRect(args.fShaderCaps, v, &usedShapeDefinitions); - v->codeAppend ("}"); - usedShapeDefinitions |= kSimpleRRect_ShapeFlag; - } - if (ip.opInfo().fShapeTypes & kOval_ShapeFlag) { - if (ip.opInfo().fShapeTypes & kRect_ShapeFlag) { - if (ip.opInfo().fShapeTypes & kRRect_ShapesMask) { - v->codeAppend ("else "); - } - v->codeAppend ("if (uint(OVAL_SHAPE_TYPE) == shapeType) {"); - usedShapeDefinitions |= kOval_ShapeFlag; - } else { - v->codeAppend ("else {"); - } - backend->setupOval(v); - v->codeAppend ("}"); - } - if (ip.opInfo().fShapeTypes & kRect_ShapeFlag) { - v->codeAppend ("else {"); - backend->setupRect(v); - v->codeAppend ("}"); - } - } - - if (ip.opInfo().fInnerShapeTypes) { - bool hasSingleInnerShapeType = SkIsPow2(ip.opInfo().fInnerShapeTypes); - if (!hasSingleInnerShapeType) { - v->defineConstantf("int", "INNER_SHAPE_TYPE_MASK", "0x%x", kInnerShapeType_InfoMask); - v->defineConstant("INNER_SHAPE_TYPE_BIT", kInnerShapeType_InfoBit); - v->codeAppendf("uint innerShapeType = ((%s & uint(INNER_SHAPE_TYPE_MASK)) >> " - "uint(INNER_SHAPE_TYPE_BIT));", - inputs.attr(Attrib::kInstanceInfo)); - } - // Here we take advantage of the fact that outerRect == localRect in recordDRRect. - v->codeAppendf("half4 outer = %s;", inputs.attr(Attrib::kLocalRect)); - v->codeAppend ("half4 inner = "); - inputs.fetchNextParam(args.fShaderCaps); - v->codeAppend (";"); - // outer2Inner is a transform from shape coords to inner shape coords: - // e.g. innerShapeCoords = shapeCoords * outer2Inner.xy + outer2Inner.zw - v->codeAppend ("half4 outer2Inner = half4(outer.zw - outer.xy, " - "outer.xy + outer.zw - inner.xy - inner.zw) / " - "(inner.zw - inner.xy).xyxy;"); - v->codeAppendf("half2 innerShapeCoords = %s * outer2Inner.xy + outer2Inner.zw;", - backend->outShapeCoords()); - - backend->initInnerShape(varyingHandler, v); - - SkASSERT(0 == (ip.opInfo().fInnerShapeTypes & kRRect_ShapesMask) || - kSimpleRRect_ShapeFlag == (ip.opInfo().fInnerShapeTypes & kRRect_ShapesMask)); - - if (hasSingleInnerShapeType) { - if (kRect_ShapeFlag == ip.opInfo().fInnerShapeTypes) { - backend->setupInnerRect(v); - } else if (kOval_ShapeFlag == ip.opInfo().fInnerShapeTypes) { - backend->setupInnerOval(v); - } else { - backend->setupInnerSimpleRRect(args.fShaderCaps, v); - } - } else { - if (ip.opInfo().fInnerShapeTypes & kSimpleRRect_ShapeFlag) { - v->codeAppend ("if (uint(SIMPLE_R_RECT_SHAPE_TYPE) == innerShapeType) {"); - backend->setupInnerSimpleRRect(args.fShaderCaps, v); - v->codeAppend("}"); - usedShapeDefinitions |= kSimpleRRect_ShapeFlag; - } - if (ip.opInfo().fInnerShapeTypes & kOval_ShapeFlag) { - if (ip.opInfo().fInnerShapeTypes & kRect_ShapeFlag) { - if (ip.opInfo().fInnerShapeTypes & kSimpleRRect_ShapeFlag) { - v->codeAppend ("else "); - } - v->codeAppend ("if (uint(OVAL_SHAPE_TYPE) == innerShapeType) {"); - usedShapeDefinitions |= kOval_ShapeFlag; - } else { - v->codeAppend ("else {"); - } - backend->setupInnerOval(v); - v->codeAppend("}"); - } - if (ip.opInfo().fInnerShapeTypes & kRect_ShapeFlag) { - v->codeAppend("else {"); - backend->setupInnerRect(v); - v->codeAppend("}"); - } - } - } - - if (usedShapeDefinitions & kOval_ShapeFlag) { - v->defineConstant("OVAL_SHAPE_TYPE", (int)ShapeType::kOval); - } - if (usedShapeDefinitions & kSimpleRRect_ShapeFlag) { - v->defineConstant("SIMPLE_R_RECT_SHAPE_TYPE", (int)ShapeType::kSimpleRRect); - } - if (usedShapeDefinitions & kNinePatch_ShapeFlag) { - v->defineConstant("NINE_PATCH_SHAPE_TYPE", (int)ShapeType::kNinePatch); - } - SkASSERT(!(usedShapeDefinitions & (kRect_ShapeFlag | kComplexRRect_ShapeFlag))); - - backend->emitCode(v, f, args.fOutputCoverage, args.fOutputColor); - - const char* localCoords = nullptr; - if (ip.opInfo().fUsesLocalCoords) { - localCoords = "localCoords"; - v->codeAppendf("half2 t = 0.5 * (%s + half2(1));", backend->outShapeCoords()); - v->codeAppendf("half2 localCoords = (1.0 - t) * %s.xy + t * %s.zw;", - inputs.attr(Attrib::kLocalRect), inputs.attr(Attrib::kLocalRect)); - } - if (ip.opInfo().fHasLocalMatrix && ip.opInfo().fHasParams) { - v->defineConstantf("int", "LOCAL_MATRIX_FLAG", "0x%x", kLocalMatrix_InfoFlag); - v->codeAppendf("if (0 != (%s & uint(LOCAL_MATRIX_FLAG))) {", - inputs.attr(Attrib::kInstanceInfo)); - if (!ip.opInfo().fUsesLocalCoords) { - inputs.skipParams(2); - } else { - v->codeAppendf( "half2x3 localMatrix;"); - v->codeAppend ( "localMatrix[0] = "); - inputs.fetchNextParam(args.fShaderCaps, kHalf3_GrSLType); - v->codeAppend ( ";"); - v->codeAppend ( "localMatrix[1] = "); - inputs.fetchNextParam(args.fShaderCaps, kHalf3_GrSLType); - v->codeAppend ( ";"); - v->codeAppend ( "localCoords = (half3(localCoords, 1) * localMatrix).xy;"); - } - v->codeAppend("}"); - } - - GrSLType positionType = ip.opInfo().fHasPerspective ? kFloat3_GrSLType : kFloat2_GrSLType; - v->codeAppendf("%s deviceCoords = float3(%s, 1) * shapeMatrix;", - GrGLSLTypeString(args.fShaderCaps, positionType), backend->outShapeCoords()); - gpArgs->fPositionVar.set(positionType, "deviceCoords"); - - this->emitTransforms(v, varyingHandler, uniHandler, GrShaderVar(localCoords, kHalf2_GrSLType), - args.fFPCoordTransformHandler); -} - -//////////////////////////////////////////////////////////////////////////////////////////////////// - -void GLSLInstanceProcessor::Backend::init(GrGLSLVaryingHandler* varyingHandler, - GrGLSLVertexBuilder* v) { - if (fModifiedShapeCoords) { - v->codeAppendf("half2 %s = %s;", fModifiedShapeCoords, fInputs.attr(Attrib::kShapeCoords)); - } - - this->onInit(varyingHandler, v); - - if (!fColor.vsOut()) { - varyingHandler->addFlatVarying("color", &fColor); - v->codeAppendf("%s = %s;", fColor.vsOut(), fInputs.attr(Attrib::kColor)); - } -} - -void GLSLInstanceProcessor::Backend::setupRRect(const GrShaderCaps* shaderCaps, - GrGLSLVertexBuilder* v, - int* usedShapeDefinitions) { - v->codeAppendf("uint2 corner = uint2(uint(%s) & 1, (uint(%s) >> 1) & 1);", - fInputs.attr(Attrib::kVertexAttrs), fInputs.attr(Attrib::kVertexAttrs)); - v->codeAppend ("half2 cornerSign = half2(corner) * 2.0 - 1.0;"); - v->codeAppendf("half2 radii%s;", fNeedsNeighborRadii ? ", neighborRadii" : ""); - v->codeAppend ("half2x2 p = "); - fInputs.fetchNextParam(shaderCaps, kHalf2x2_GrSLType); - v->codeAppend (";"); - uint8_t types = fOpInfo.fShapeTypes & kRRect_ShapesMask; - if (0 == (types & (types - 1))) { - if (kSimpleRRect_ShapeFlag == types) { - this->setupSimpleRadii(v); - } else if (kNinePatch_ShapeFlag == types) { - this->setupNinePatchRadii(v); - } else if (kComplexRRect_ShapeFlag == types) { - this->setupComplexRadii(shaderCaps, v); - } - } else { - if (types & kSimpleRRect_ShapeFlag) { - v->codeAppend ("if (uint(SIMPLE_R_RECT_SHAPE_TYPE) == shapeType) {"); - this->setupSimpleRadii(v); - v->codeAppend ("}"); - *usedShapeDefinitions |= kSimpleRRect_ShapeFlag; - } - if (types & kNinePatch_ShapeFlag) { - if (types & kComplexRRect_ShapeFlag) { - if (types & kSimpleRRect_ShapeFlag) { - v->codeAppend ("else "); - } - v->codeAppend ("if (uint(NINE_PATCH_SHAPE_TYPE) == shapeType) {"); - *usedShapeDefinitions |= kNinePatch_ShapeFlag; - } else { - v->codeAppend ("else {"); - } - this->setupNinePatchRadii(v); - v->codeAppend ("}"); - } - if (types & kComplexRRect_ShapeFlag) { - v->codeAppend ("else {"); - this->setupComplexRadii(shaderCaps, v); - v->codeAppend ("}"); - } - } - - this->adjustRRectVertices(v); - - if (fArcCoords.vsOut()) { - v->codeAppendf("%s = (cornerSign * %s + radii - half2(1)) / radii;", - fArcCoords.vsOut(), fModifiedShapeCoords); - } - if (fTriangleIsArc.vsOut()) { - v->codeAppendf("%s = int(all(equal(half2(1), abs(%s))));", - fTriangleIsArc.vsOut(), fInputs.attr(Attrib::kShapeCoords)); - } - - this->onSetupRRect(v); -} - -void GLSLInstanceProcessor::Backend::setupSimpleRadii(GrGLSLVertexBuilder* v) { - if (fNeedsNeighborRadii) { - v->codeAppend ("neighborRadii = "); - } - v->codeAppend("radii = p[0] * 2.0 / p[1];"); -} - -void GLSLInstanceProcessor::Backend::setupNinePatchRadii(GrGLSLVertexBuilder* v) { - v->codeAppend("radii = half2(p[0][corner.x], p[1][corner.y]);"); - if (fNeedsNeighborRadii) { - v->codeAppend("neighborRadii = half2(p[0][1 - corner.x], p[1][1 - corner.y]);"); - } -} - -void GLSLInstanceProcessor::Backend::setupComplexRadii(const GrShaderCaps* shaderCaps, - GrGLSLVertexBuilder* v) { - /** - * The x and y radii of each arc are stored in separate vectors, - * in the following order: - * - * __x1 _ _ _ x3__ - * - * y1 | | y2 - * - * | | - * - * y3 |__ _ _ _ __| y4 - * x2 x4 - * - */ - v->codeAppend("half2x2 p2 = "); - fInputs.fetchNextParam(shaderCaps, kHalf2x2_GrSLType); - v->codeAppend(";"); - v->codeAppend("radii = half2(p[corner.x][corner.y], p2[corner.y][corner.x]);"); - if (fNeedsNeighborRadii) { - v->codeAppend("neighborRadii = half2(p[1 - corner.x][corner.y], " - "p2[1 - corner.y][corner.x]);"); - } -} - -void GLSLInstanceProcessor::Backend::adjustRRectVertices(GrGLSLVertexBuilder* v) { - // Resize the 4 triangles that arcs are drawn into so they match their corresponding radii. - // 0.5 is a special value that indicates the edge of an arc triangle. - v->codeAppendf("if (abs(%s.x) == 0.5)" - "%s.x = cornerSign.x * (1.0 - radii.x);", - fInputs.attr(Attrib::kShapeCoords), fModifiedShapeCoords); - v->codeAppendf("if (abs(%s.y) == 0.5) " - "%s.y = cornerSign.y * (1.0 - radii.y);", - fInputs.attr(Attrib::kShapeCoords), fModifiedShapeCoords); -} - -void GLSLInstanceProcessor::Backend::initInnerShape(GrGLSLVaryingHandler* varyingHandler, - GrGLSLVertexBuilder* v) { - SkASSERT(!(fOpInfo.fInnerShapeTypes & (kNinePatch_ShapeFlag | kComplexRRect_ShapeFlag))); - - this->onInitInnerShape(varyingHandler, v); - - if (fInnerShapeCoords.vsOut()) { - v->codeAppendf("%s = innerShapeCoords;", fInnerShapeCoords.vsOut()); - } -} - -void GLSLInstanceProcessor::Backend::setupInnerSimpleRRect(const GrShaderCaps* shaderCaps, - GrGLSLVertexBuilder* v) { - v->codeAppend("half2x2 innerP = "); - fInputs.fetchNextParam(shaderCaps, kHalf2x2_GrSLType); - v->codeAppend(";"); - v->codeAppend("half2 innerRadii = innerP[0] * 2.0 / innerP[1];"); - this->onSetupInnerSimpleRRect(v); -} - -void GLSLInstanceProcessor::Backend::emitCode(GrGLSLVertexBuilder* v, GrGLSLPPFragmentBuilder* f, - const char* outCoverage, const char* outColor) { - SkASSERT(!fModifiesCoverage || outCoverage); - this->onEmitCode(v, f, fModifiesCoverage ? outCoverage : nullptr, - fModifiesColor ? outColor : nullptr); - if (outCoverage && !fModifiesCoverage) { - // Even though the subclass doesn't use coverage, we are expected to assign some value. - f->codeAppendf("%s = half4(1);", outCoverage); - } - if (!fModifiesColor) { - // The subclass didn't assign a value to the output color. - f->codeAppendf("%s = %s;", outColor, fColor.fsIn()); - } -} - -//////////////////////////////////////////////////////////////////////////////////////////////////// - -class GLSLInstanceProcessor::BackendNonAA : public Backend { -public: - BackendNonAA(OpInfo opInfo, const VertexInputs& inputs) : INHERITED(opInfo, inputs) { - if (fOpInfo.fCannotDiscard && !fOpInfo.isSimpleRects()) { - fModifiesColor = !fOpInfo.fCannotTweakAlphaForCoverage; - fModifiesCoverage = !fModifiesColor; - } - } - -private: - void onInit(GrGLSLVaryingHandler*, GrGLSLVertexBuilder*) override; - void setupRect(GrGLSLVertexBuilder*) override; - void setupOval(GrGLSLVertexBuilder*) override; - - void onInitInnerShape(GrGLSLVaryingHandler*, GrGLSLVertexBuilder*) override; - void setupInnerRect(GrGLSLVertexBuilder*) override; - void setupInnerOval(GrGLSLVertexBuilder*) override; - void onSetupInnerSimpleRRect(GrGLSLVertexBuilder*) override; - - void onEmitCode(GrGLSLVertexBuilder*, GrGLSLPPFragmentBuilder*, const char*, - const char*) override; - - typedef Backend INHERITED; -}; - -void GLSLInstanceProcessor::BackendNonAA::onInit(GrGLSLVaryingHandler* varyingHandler, - GrGLSLVertexBuilder*) { - if (kRect_ShapeFlag != fOpInfo.fShapeTypes) { - varyingHandler->addFlatVarying("triangleIsArc", &fTriangleIsArc); - varyingHandler->addVarying("arcCoords", &fArcCoords); - } -} - -void GLSLInstanceProcessor::BackendNonAA::setupRect(GrGLSLVertexBuilder* v) { - if (fTriangleIsArc.vsOut()) { - v->codeAppendf("%s = 0;", fTriangleIsArc.vsOut()); - } -} - -void GLSLInstanceProcessor::BackendNonAA::setupOval(GrGLSLVertexBuilder* v) { - SkASSERT(fArcCoords.vsOut()); - SkASSERT(fTriangleIsArc.vsOut()); - v->codeAppendf("%s = %s;", fArcCoords.vsOut(), this->outShapeCoords()); - v->codeAppendf("%s = %s & 1;", fTriangleIsArc.vsOut(), fInputs.attr(Attrib::kVertexAttrs)); -} - -void GLSLInstanceProcessor::BackendNonAA::onInitInnerShape(GrGLSLVaryingHandler* varyingHandler, - GrGLSLVertexBuilder*) { - varyingHandler->addVarying("innerShapeCoords", &fInnerShapeCoords); - if (kRect_ShapeFlag != fOpInfo.fInnerShapeTypes && - kOval_ShapeFlag != fOpInfo.fInnerShapeTypes) { - varyingHandler->addFlatVarying("innerRRect", &fInnerRRect); - } -} - -void GLSLInstanceProcessor::BackendNonAA::setupInnerRect(GrGLSLVertexBuilder* v) { - if (fInnerRRect.vsOut()) { - v->codeAppendf("%s = half4(1);", fInnerRRect.vsOut()); - } -} - -void GLSLInstanceProcessor::BackendNonAA::setupInnerOval(GrGLSLVertexBuilder* v) { - if (fInnerRRect.vsOut()) { - v->codeAppendf("%s = half4(0, 0, 1, 1);", fInnerRRect.vsOut()); - } -} - -void GLSLInstanceProcessor::BackendNonAA::onSetupInnerSimpleRRect(GrGLSLVertexBuilder* v) { - v->codeAppendf("%s = half4(1.0 - innerRadii, 1.0 / innerRadii);", fInnerRRect.vsOut()); -} - -void GLSLInstanceProcessor::BackendNonAA::onEmitCode(GrGLSLVertexBuilder*, - GrGLSLPPFragmentBuilder* f, - const char* outCoverage, - const char* outColor) { - const char* dropFragment = nullptr; - if (!fOpInfo.fCannotDiscard) { - dropFragment = "discard"; - } else if (fModifiesCoverage) { - f->codeAppend ("half covered = 1.0;"); - dropFragment = "covered = 0.0"; - } else if (fModifiesColor) { - f->codeAppendf("half4 color = %s;", fColor.fsIn()); - dropFragment = "color = half4(0)"; - } - if (fTriangleIsArc.fsIn()) { - SkASSERT(dropFragment); - f->codeAppendf("if (%s != 0 && dot(%s, %s) > 1.0) %s;", - fTriangleIsArc.fsIn(), fArcCoords.fsIn(), fArcCoords.fsIn(), dropFragment); - } - if (fOpInfo.fInnerShapeTypes) { - SkASSERT(dropFragment); - f->codeAppendf("// Inner shape.\n"); - if (kRect_ShapeFlag == fOpInfo.fInnerShapeTypes) { - f->codeAppendf("if (all(lessThanEqual(abs(%s), half2(1)))) %s;", - fInnerShapeCoords.fsIn(), dropFragment); - } else if (kOval_ShapeFlag == fOpInfo.fInnerShapeTypes) { - f->codeAppendf("if ((dot(%s, %s) <= 1.0)) %s;", - fInnerShapeCoords.fsIn(), fInnerShapeCoords.fsIn(), dropFragment); - } else { - f->codeAppendf("if (all(lessThan(abs(%s), half2(1)))) {", fInnerShapeCoords.fsIn()); - f->codeAppendf( "half2 distanceToArcEdge = abs(%s) - %s.xy;", - fInnerShapeCoords.fsIn(), fInnerRRect.fsIn()); - f->codeAppend ( "if (any(lessThan(distanceToArcEdge, half2(0)))) {"); - f->codeAppendf( "%s;", dropFragment); - f->codeAppend ( "} else {"); - f->codeAppendf( "half2 rrectCoords = distanceToArcEdge * %s.zw;", - fInnerRRect.fsIn()); - f->codeAppend ( "if (dot(rrectCoords, rrectCoords) <= 1.0) {"); - f->codeAppendf( "%s;", dropFragment); - f->codeAppend ( "}"); - f->codeAppend ( "}"); - f->codeAppend ("}"); - } - } - if (fModifiesCoverage) { - f->codeAppendf("%s = half4(covered);", outCoverage); - } else if (fModifiesColor) { - f->codeAppendf("%s = color;", outColor); - } -} - -//////////////////////////////////////////////////////////////////////////////////////////////////// - -class GLSLInstanceProcessor::BackendCoverage : public Backend { -public: - BackendCoverage(OpInfo opInfo, const VertexInputs& inputs) - : INHERITED(opInfo, inputs) - , fColorTimesRectCoverage(kHalf4_GrSLType) - , fRectCoverage(kHalf_GrSLType) - , fEllipseCoords(kHalf2_GrSLType) - , fEllipseName(kHalf2_GrSLType) - , fBloatedRadius(kHalf_GrSLType) - , fDistanceToInnerEdge(kHalf2_GrSLType) - , fInnerShapeBloatedHalfSize(kHalf2_GrSLType) - , fInnerEllipseCoords(kHalf2_GrSLType) - , fInnerEllipseName(kHalf2_GrSLType) { - fShapeIsCircle = !fOpInfo.fNonSquare && !(fOpInfo.fShapeTypes & kRRect_ShapesMask); - fTweakAlphaForCoverage = !fOpInfo.fCannotTweakAlphaForCoverage && !fOpInfo.fInnerShapeTypes; - fModifiesCoverage = !fTweakAlphaForCoverage; - fModifiesColor = fTweakAlphaForCoverage; - fModifiedShapeCoords = "bloatedShapeCoords"; - } - -private: - void onInit(GrGLSLVaryingHandler*, GrGLSLVertexBuilder*) override; - void setupRect(GrGLSLVertexBuilder*) override; - void setupOval(GrGLSLVertexBuilder*) override; - void adjustRRectVertices(GrGLSLVertexBuilder*) override; - void onSetupRRect(GrGLSLVertexBuilder*) override; - - void onInitInnerShape(GrGLSLVaryingHandler*, GrGLSLVertexBuilder*) override; - void setupInnerRect(GrGLSLVertexBuilder*) override; - void setupInnerOval(GrGLSLVertexBuilder*) override; - void onSetupInnerSimpleRRect(GrGLSLVertexBuilder*) override; - - void onEmitCode(GrGLSLVertexBuilder*, GrGLSLPPFragmentBuilder*, const char* outCoverage, - const char* outColor) override; - - void emitRect(GrGLSLPPFragmentBuilder*, const char* outCoverage, const char* outColor); - void emitCircle(GrGLSLPPFragmentBuilder*, const char* outCoverage); - void emitArc(GrGLSLPPFragmentBuilder* f, const char* ellipseCoords, const char* ellipseName, - bool ellipseCoordsNeedClamp, bool ellipseCoordsMayBeNegative, - const char* outCoverage); - void emitInnerRect(GrGLSLPPFragmentBuilder*, const char* outCoverage); - - GrGLSLVertToFrag fColorTimesRectCoverage; - GrGLSLVertToFrag fRectCoverage; - GrGLSLVertToFrag fEllipseCoords; - GrGLSLVertToFrag fEllipseName; - GrGLSLVertToFrag fBloatedRadius; - GrGLSLVertToFrag fDistanceToInnerEdge; - GrGLSLVertToFrag fInnerShapeBloatedHalfSize; - GrGLSLVertToFrag fInnerEllipseCoords; - GrGLSLVertToFrag fInnerEllipseName; - bool fShapeIsCircle; - bool fTweakAlphaForCoverage; - - typedef Backend INHERITED; -}; - -void GLSLInstanceProcessor::BackendCoverage::onInit(GrGLSLVaryingHandler* varyingHandler, - GrGLSLVertexBuilder* v) { - v->codeAppend ("half2x2 shapeTransposeMatrix = transpose(half2x2(shapeMatrix));"); - v->codeAppend ("half2 shapeHalfSize = half2(length(shapeTransposeMatrix[0]), " - "length(shapeTransposeMatrix[1]));"); - v->codeAppend ("half2 bloat = 0.5 / shapeHalfSize;"); - v->codeAppendf("bloatedShapeCoords = %s * (1.0 + bloat);", fInputs.attr(Attrib::kShapeCoords)); - - if (kOval_ShapeFlag != fOpInfo.fShapeTypes) { - if (fTweakAlphaForCoverage) { - varyingHandler->addVarying("colorTimesRectCoverage", &fColorTimesRectCoverage); - if (kRect_ShapeFlag == fOpInfo.fShapeTypes) { - fColor = fColorTimesRectCoverage; - } - } else { - varyingHandler->addVarying("rectCoverage", &fRectCoverage); - } - v->codeAppend("half rectCoverage = 0.0;"); - } - if (kRect_ShapeFlag != fOpInfo.fShapeTypes) { - varyingHandler->addFlatVarying("triangleIsArc", &fTriangleIsArc); - if (!fShapeIsCircle) { - varyingHandler->addVarying("ellipseCoords", &fEllipseCoords); - varyingHandler->addFlatVarying("ellipseName", &fEllipseName); - } else { - varyingHandler->addVarying("circleCoords", &fEllipseCoords); - varyingHandler->addFlatVarying("bloatedRadius", &fBloatedRadius); - } - } -} - -void GLSLInstanceProcessor::BackendCoverage::setupRect(GrGLSLVertexBuilder* v) { - // Make the border one pixel wide. Inner vs outer is indicated by coordAttrs. - v->codeAppendf("half2 rectBloat = (%s != 0) ? bloat : -bloat;", - fInputs.attr(Attrib::kVertexAttrs)); - // Here we use the absolute value, because when the rect is thinner than a pixel, this makes it - // mark the spot where pixel center is within half a pixel of the *opposite* edge. This, - // combined with the "maxCoverage" logic below gives us mathematically correct coverage even for - // subpixel rectangles. - v->codeAppendf("bloatedShapeCoords = %s * abs(half2(1.0 + rectBloat));", - fInputs.attr(Attrib::kShapeCoords)); - - // Determine coverage at the vertex. Coverage naturally ramps from 0 to 1 unless the rect is - // narrower than a pixel. - v->codeAppend ("half maxCoverage = 4.0 * min(0.5, shapeHalfSize.x) *" - "min(0.5, shapeHalfSize.y);"); - v->codeAppendf("rectCoverage = (%s != 0) ? 0.0 : maxCoverage;", - fInputs.attr(Attrib::kVertexAttrs)); - - if (fTriangleIsArc.vsOut()) { - v->codeAppendf("%s = 0;", fTriangleIsArc.vsOut()); - } -} - -void GLSLInstanceProcessor::BackendCoverage::setupOval(GrGLSLVertexBuilder* v) { - // Offset the inner and outer octagons by one pixel. Inner vs outer is indicated by coordAttrs. - v->codeAppendf("half2 ovalBloat = (%s != 0) ? bloat : -bloat;", - fInputs.attr(Attrib::kVertexAttrs)); - v->codeAppendf("bloatedShapeCoords = %s * max(half2(1.0 + ovalBloat), half2(0));", - fInputs.attr(Attrib::kShapeCoords)); - v->codeAppendf("%s = bloatedShapeCoords * shapeHalfSize;", fEllipseCoords.vsOut()); - if (fEllipseName.vsOut()) { - v->codeAppendf("%s = 1.0 / (shapeHalfSize * shapeHalfSize);", fEllipseName.vsOut()); - } - if (fBloatedRadius.vsOut()) { - SkASSERT(fShapeIsCircle); - v->codeAppendf("%s = shapeHalfSize.x + 0.5;", fBloatedRadius.vsOut()); - } - if (fTriangleIsArc.vsOut()) { - v->codeAppendf("%s = int(%s != 0);", - fTriangleIsArc.vsOut(), fInputs.attr(Attrib::kVertexAttrs)); - } - if (fColorTimesRectCoverage.vsOut() || fRectCoverage.vsOut()) { - v->codeAppendf("rectCoverage = 1.0;"); - } -} - -void GLSLInstanceProcessor::BackendCoverage::adjustRRectVertices(GrGLSLVertexBuilder* v) { - // We try to let the AA borders line up with the arc edges on their particular side, but we - // can't allow them to get closer than one half pixel to the edge or they might overlap with - // their neighboring border. - v->codeAppend("half2 innerEdge = max(1.0 - bloat, half2(0));"); - v->codeAppend ("half2 borderEdge = cornerSign * clamp(1.0 - radii, -innerEdge, innerEdge);"); - // 0.5 is a special value that indicates this vertex is an arc edge. - v->codeAppendf("if (abs(%s.x) == 0.5)" - "bloatedShapeCoords.x = borderEdge.x;", fInputs.attr(Attrib::kShapeCoords)); - v->codeAppendf("if (abs(%s.y) == 0.5)" - "bloatedShapeCoords.y = borderEdge.y;", fInputs.attr(Attrib::kShapeCoords)); - - // Adjust the interior border vertices to make the border one pixel wide. 0.75 is a special - // value to indicate these points. - v->codeAppendf("if (abs(%s.x) == 0.75) " - "bloatedShapeCoords.x = cornerSign.x * innerEdge.x;", - fInputs.attr(Attrib::kShapeCoords)); - v->codeAppendf("if (abs(%s.y) == 0.75) " - "bloatedShapeCoords.y = cornerSign.y * innerEdge.y;", - fInputs.attr(Attrib::kShapeCoords)); -} - -void GLSLInstanceProcessor::BackendCoverage::onSetupRRect(GrGLSLVertexBuilder* v) { - // The geometry is laid out in such a way that rectCoverage will be 0 and 1 on the vertices, but - // we still need to recompute this value because when the rrect gets thinner than one pixel, the - // interior edge of the border will necessarily clamp, and we need to match the AA behavior of - // the arc segments (i.e. distance from bloated edge only; ignoring the fact that the pixel - // actully has less coverage because it's not completely inside the opposite edge.) - v->codeAppend("half2 d = shapeHalfSize + 0.5 - abs(bloatedShapeCoords) * shapeHalfSize;"); - v->codeAppend("rectCoverage = min(d.x, d.y);"); - - SkASSERT(!fShapeIsCircle); - // The AA border does not get closer than one half pixel to the edge of the rect, so to get a - // smooth transition from flat edge to arc, we don't allow the radii to be smaller than one half - // pixel. (We don't worry about the transition on the opposite side when a radius is so large - // that the border clamped on that side.) - v->codeAppendf("half2 clampedRadii = max(radii, bloat);"); - v->codeAppendf("%s = (cornerSign * bloatedShapeCoords + clampedRadii - half2(1)) * " - "shapeHalfSize;", fEllipseCoords.vsOut()); - v->codeAppendf("%s = 1.0 / (clampedRadii * clampedRadii * shapeHalfSize * shapeHalfSize);", - fEllipseName.vsOut()); -} - -void GLSLInstanceProcessor::BackendCoverage::onInitInnerShape(GrGLSLVaryingHandler* varyingHandler, - GrGLSLVertexBuilder* v) { - v->codeAppend("half2 innerShapeHalfSize = shapeHalfSize / outer2Inner.xy;"); - - if (kOval_ShapeFlag == fOpInfo.fInnerShapeTypes) { - varyingHandler->addVarying("innerEllipseCoords", &fInnerEllipseCoords); - varyingHandler->addFlatVarying("innerEllipseName", &fInnerEllipseName); - } else { - varyingHandler->addVarying("distanceToInnerEdge", &fDistanceToInnerEdge); - varyingHandler->addFlatVarying("innerShapeBloatedHalfSize", &fInnerShapeBloatedHalfSize); - if (kRect_ShapeFlag != fOpInfo.fInnerShapeTypes) { - varyingHandler->addVarying("innerShapeCoords", &fInnerShapeCoords); - varyingHandler->addFlatVarying("innerEllipseName", &fInnerEllipseName); - varyingHandler->addFlatVarying("innerRRect", &fInnerRRect); - } - } -} - -void GLSLInstanceProcessor::BackendCoverage::setupInnerRect(GrGLSLVertexBuilder* v) { - if (fInnerRRect.vsOut()) { - // The fragment shader will generalize every inner shape as a round rect. Since this one - // is a rect, we simply emit bogus parameters for the round rect (effectively negative - // radii) that ensure the fragment shader always takes the "emitRect" codepath. - v->codeAppendf("%s.xy = abs(outer2Inner.xy) * (1.0 + bloat) + abs(outer2Inner.zw);", - fInnerRRect.vsOut()); - } -} - -void GLSLInstanceProcessor::BackendCoverage::setupInnerOval(GrGLSLVertexBuilder* v) { - v->codeAppendf("%s = 1.0 / (innerShapeHalfSize * innerShapeHalfSize);", - fInnerEllipseName.vsOut()); - if (fInnerEllipseCoords.vsOut()) { - v->codeAppendf("%s = innerShapeCoords * innerShapeHalfSize;", fInnerEllipseCoords.vsOut()); - } - if (fInnerRRect.vsOut()) { - v->codeAppendf("%s = half4(0, 0, innerShapeHalfSize);", fInnerRRect.vsOut()); - } -} - -void GLSLInstanceProcessor::BackendCoverage::onSetupInnerSimpleRRect(GrGLSLVertexBuilder* v) { - // The distance to ellipse formula doesn't work well when the radii are less than half a pixel. - v->codeAppend ("innerRadii = max(innerRadii, bloat);"); - v->codeAppendf("%s = 1.0 / (innerRadii * innerRadii * innerShapeHalfSize * " - "innerShapeHalfSize);", - fInnerEllipseName.vsOut()); - v->codeAppendf("%s = half4(1.0 - innerRadii, innerShapeHalfSize);", fInnerRRect.vsOut()); -} - -void GLSLInstanceProcessor::BackendCoverage::onEmitCode(GrGLSLVertexBuilder* v, - GrGLSLPPFragmentBuilder* f, - const char* outCoverage, - const char* outColor) { - if (fColorTimesRectCoverage.vsOut()) { - SkASSERT(!fRectCoverage.vsOut()); - v->codeAppendf("%s = %s * rectCoverage;", - fColorTimesRectCoverage.vsOut(), fInputs.attr(Attrib::kColor)); - } - if (fRectCoverage.vsOut()) { - SkASSERT(!fColorTimesRectCoverage.vsOut()); - v->codeAppendf("%s = rectCoverage;", fRectCoverage.vsOut()); - } - - SkString coverage("half coverage"); - if (fOpInfo.fInnerShapeTypes || (!fTweakAlphaForCoverage && fTriangleIsArc.fsIn())) { - f->codeAppendf("%s;", coverage.c_str()); - coverage = "coverage"; - } - if (fTriangleIsArc.fsIn()) { - f->codeAppendf("if (%s == 0) {", fTriangleIsArc.fsIn()); - this->emitRect(f, coverage.c_str(), outColor); - f->codeAppend ("} else {"); - if (fShapeIsCircle) { - this->emitCircle(f, coverage.c_str()); - } else { - bool ellipseCoordsMayBeNegative = SkToBool(fOpInfo.fShapeTypes & kOval_ShapeFlag); - this->emitArc(f, fEllipseCoords.fsIn(), fEllipseName.fsIn(), - true /*ellipseCoordsNeedClamp*/, ellipseCoordsMayBeNegative, - coverage.c_str()); - } - if (fTweakAlphaForCoverage) { - f->codeAppendf("%s = %s * coverage;", outColor, fColor.fsIn()); - } - f->codeAppend ("}"); - } else { - this->emitRect(f, coverage.c_str(), outColor); - } - - if (fOpInfo.fInnerShapeTypes) { - f->codeAppendf("// Inner shape.\n"); - SkString innerCoverageDecl("half innerCoverage"); - if (kOval_ShapeFlag == fOpInfo.fInnerShapeTypes) { - this->emitArc(f, fInnerEllipseCoords.fsIn(), fInnerEllipseName.fsIn(), - true /*ellipseCoordsNeedClamp*/, true /*ellipseCoordsMayBeNegative*/, - innerCoverageDecl.c_str()); - } else { - v->codeAppendf("%s = innerShapeCoords * innerShapeHalfSize;", - fDistanceToInnerEdge.vsOut()); - v->codeAppendf("%s = innerShapeHalfSize + 0.5;", fInnerShapeBloatedHalfSize.vsOut()); - - if (kRect_ShapeFlag == fOpInfo.fInnerShapeTypes) { - this->emitInnerRect(f, innerCoverageDecl.c_str()); - } else { - f->codeAppendf("%s = 0.0;", innerCoverageDecl.c_str()); - f->codeAppendf("half2 distanceToArcEdge = abs(%s) - %s.xy;", - fInnerShapeCoords.fsIn(), fInnerRRect.fsIn()); - f->codeAppend ("if (any(lessThan(distanceToArcEdge, half2(1e-5)))) {"); - this->emitInnerRect(f, "innerCoverage"); - f->codeAppend ("} else {"); - f->codeAppendf( "half2 ellipseCoords = distanceToArcEdge * %s.zw;", - fInnerRRect.fsIn()); - this->emitArc(f, "ellipseCoords", fInnerEllipseName.fsIn(), - false /*ellipseCoordsNeedClamp*/, - false /*ellipseCoordsMayBeNegative*/, "innerCoverage"); - f->codeAppend ("}"); - } - } - f->codeAppendf("%s = half4(max(coverage - innerCoverage, 0.0));", outCoverage); - } else if (!fTweakAlphaForCoverage) { - f->codeAppendf("%s = half4(coverage);", outCoverage); - } -} - -void GLSLInstanceProcessor::BackendCoverage::emitRect(GrGLSLPPFragmentBuilder* f, - const char* outCoverage, - const char* outColor) { - if (fColorTimesRectCoverage.fsIn()) { - f->codeAppendf("%s = %s;", outColor, fColorTimesRectCoverage.fsIn()); - } else if (fTweakAlphaForCoverage) { - // We are drawing just ovals. The interior rect always has 100% coverage. - f->codeAppendf("%s = %s;", outColor, fColor.fsIn()); - } else if (fRectCoverage.fsIn()) { - f->codeAppendf("%s = %s;", outCoverage, fRectCoverage.fsIn()); - } else { - f->codeAppendf("%s = 1.0;", outCoverage); - } -} - -void GLSLInstanceProcessor::BackendCoverage::emitCircle(GrGLSLPPFragmentBuilder* f, - const char* outCoverage) { - // TODO: circleCoords = max(circleCoords, 0) if we decide to do this optimization on rrects. - SkASSERT(!(kRRect_ShapesMask & fOpInfo.fShapeTypes)); - f->codeAppendf("half distanceToEdge = %s - length(%s);", - fBloatedRadius.fsIn(), fEllipseCoords.fsIn()); - f->codeAppendf("%s = clamp(distanceToEdge, 0.0, 1.0);", outCoverage); -} - -void GLSLInstanceProcessor::BackendCoverage::emitArc(GrGLSLPPFragmentBuilder* f, - const char* ellipseCoords, - const char* ellipseName, - bool ellipseCoordsNeedClamp, - bool ellipseCoordsMayBeNegative, - const char* outCoverage) { - SkASSERT(!ellipseCoordsMayBeNegative || ellipseCoordsNeedClamp); - if (ellipseCoordsNeedClamp) { - // This serves two purposes: - // - To restrict the arcs of rounded rects to their positive quadrants. - // - To avoid inversesqrt(0) in the ellipse formula. - if (ellipseCoordsMayBeNegative) { - f->codeAppendf("half2 ellipseClampedCoords = max(abs(%s), half2(1e-4));", - ellipseCoords); - } else { - f->codeAppendf("half2 ellipseClampedCoords = max(%s, half2(1e-4));", - ellipseCoords); - } - ellipseCoords = "ellipseClampedCoords"; - } - // ellipseCoords are in pixel space and ellipseName is 1 / rx^2, 1 / ry^2. - f->codeAppendf("float2 Z = %s * %s;", ellipseCoords, ellipseName); - // implicit is the evaluation of (x/rx)^2 + (y/ry)^2 - 1. - f->codeAppendf("float implicit = dot(Z, %s) - 1.0;", ellipseCoords); - // gradDot is the squared length of the gradient of the implicit. - f->codeAppendf("float gradDot = 4.0 * dot(Z, Z);"); - f->codeAppend ("half approxDist = implicit * inversesqrt(gradDot);"); - f->codeAppendf("%s = clamp(0.5 - approxDist, 0.0, 1.0);", outCoverage); -} - -void GLSLInstanceProcessor::BackendCoverage::emitInnerRect(GrGLSLPPFragmentBuilder* f, - const char* outCoverage) { - f->codeAppendf("half2 c = %s - abs(%s);", - fInnerShapeBloatedHalfSize.fsIn(), fDistanceToInnerEdge.fsIn()); - f->codeAppendf("%s = clamp(min(c.x, c.y), 0.0, 1.0);", outCoverage); -} - -//////////////////////////////////////////////////////////////////////////////////////////////////// - -class GLSLInstanceProcessor::BackendMultisample : public Backend { -public: - BackendMultisample(OpInfo opInfo, const VertexInputs& inputs, int effectiveSampleCnt) - : INHERITED(opInfo, inputs) - , fEffectiveSampleCnt(effectiveSampleCnt) - , fShapeCoords(kHalf2_GrSLType) - , fShapeInverseMatrix(kHalf2x2_GrSLType) - , fFragShapeHalfSpan(kHalf2_GrSLType) - , fArcTest(kHalf2_GrSLType) - , fArcInverseMatrix(kHalf2x2_GrSLType) - , fFragArcHalfSpan(kHalf2_GrSLType) - , fEarlyAccept(kInt_GrSLType) - , fInnerShapeInverseMatrix(kHalf2x2_GrSLType) - , fFragInnerShapeHalfSpan(kHalf2_GrSLType) { - fRectTrianglesMaySplit = fOpInfo.fHasPerspective; - fNeedsNeighborRadii = this->isMixedSampled() && !fOpInfo.fHasPerspective; - } - -private: - bool isMixedSampled() const { return GrAAType::kMixedSamples == fOpInfo.aaType(); } - - void onInit(GrGLSLVaryingHandler*, GrGLSLVertexBuilder*) override; - void setupRect(GrGLSLVertexBuilder*) override; - void setupOval(GrGLSLVertexBuilder*) override; - void adjustRRectVertices(GrGLSLVertexBuilder*) override; - void onSetupRRect(GrGLSLVertexBuilder*) override; - - void onInitInnerShape(GrGLSLVaryingHandler*, GrGLSLVertexBuilder*) override; - void setupInnerRect(GrGLSLVertexBuilder*) override; - void setupInnerOval(GrGLSLVertexBuilder*) override; - void onSetupInnerSimpleRRect(GrGLSLVertexBuilder*) override; - - void onEmitCode(GrGLSLVertexBuilder*, GrGLSLPPFragmentBuilder*, const char*, - const char*) override; - - struct EmitShapeCoords { - const GrGLSLVarying* fVarying; - const char* fInverseMatrix; - const char* fFragHalfSpan; - }; - - struct EmitShapeOpts { - bool fIsTightGeometry; - bool fResolveMixedSamples; - bool fInvertCoverage; - }; - - void emitRect(GrGLSLPPFragmentBuilder*, const EmitShapeCoords&, const EmitShapeOpts&); - void emitArc(GrGLSLPPFragmentBuilder*, const EmitShapeCoords&, bool coordsMayBeNegative, - bool clampCoords, const EmitShapeOpts&); - void emitSimpleRRect(GrGLSLPPFragmentBuilder*, const EmitShapeCoords&, const char* rrect, - const EmitShapeOpts&); - void interpolateAtSample(GrGLSLPPFragmentBuilder*, const GrGLSLVarying&, const char* sampleIdx, - const char* interpolationMatrix); - void acceptOrRejectWholeFragment(GrGLSLPPFragmentBuilder*, bool inside, const EmitShapeOpts&); - void acceptCoverageMask(GrGLSLPPFragmentBuilder*, const char* shapeMask, const EmitShapeOpts&, - bool maybeSharedEdge = true); - - int fEffectiveSampleCnt; - bool fRectTrianglesMaySplit; - GrGLSLVertToFrag fShapeCoords; - GrGLSLVertToFrag fShapeInverseMatrix; - GrGLSLVertToFrag fFragShapeHalfSpan; - GrGLSLVertToFrag fArcTest; - GrGLSLVertToFrag fArcInverseMatrix; - GrGLSLVertToFrag fFragArcHalfSpan; - GrGLSLVertToFrag fEarlyAccept; - GrGLSLVertToFrag fInnerShapeInverseMatrix; - GrGLSLVertToFrag fFragInnerShapeHalfSpan; - SkString fSquareFun; - - typedef Backend INHERITED; -}; - -void GLSLInstanceProcessor::BackendMultisample::onInit(GrGLSLVaryingHandler* varyingHandler, - GrGLSLVertexBuilder* v) { - if (!this->isMixedSampled()) { - if (kRect_ShapeFlag != fOpInfo.fShapeTypes) { - varyingHandler->addFlatVarying("triangleIsArc", &fTriangleIsArc); - varyingHandler->addVarying("arcCoords", &fArcCoords); - if (!fOpInfo.fHasPerspective) { - varyingHandler->addFlatVarying("arcInverseMatrix", &fArcInverseMatrix); - varyingHandler->addFlatVarying("fragArcHalfSpan", &fFragArcHalfSpan); - } - } else if (!fOpInfo.fInnerShapeTypes) { - return; - } - } else { - varyingHandler->addVarying("shapeCoords", &fShapeCoords); - if (!fOpInfo.fHasPerspective) { - varyingHandler->addFlatVarying("shapeInverseMatrix", &fShapeInverseMatrix); - varyingHandler->addFlatVarying("fragShapeHalfSpan", &fFragShapeHalfSpan); - } - if (fOpInfo.fShapeTypes & kRRect_ShapesMask) { - varyingHandler->addVarying("arcCoords", &fArcCoords); - varyingHandler->addVarying("arcTest", &fArcTest); - if (!fOpInfo.fHasPerspective) { - varyingHandler->addFlatVarying("arcInverseMatrix", &fArcInverseMatrix); - varyingHandler->addFlatVarying("fragArcHalfSpan", &fFragArcHalfSpan); - } - } else if (fOpInfo.fShapeTypes & kOval_ShapeFlag) { - fArcCoords = fShapeCoords; - fArcInverseMatrix = fShapeInverseMatrix; - fFragArcHalfSpan = fFragShapeHalfSpan; - if (fOpInfo.fShapeTypes & kRect_ShapeFlag) { - varyingHandler->addFlatVarying("triangleIsArc", &fTriangleIsArc); - } - } - if (kRect_ShapeFlag != fOpInfo.fShapeTypes) { - v->defineConstantf("int", "SAMPLE_MASK_ALL", "0x%x", (1 << fEffectiveSampleCnt) - 1); - varyingHandler->addFlatVarying("earlyAccept", &fEarlyAccept); - } - } - if (!fOpInfo.fHasPerspective) { - v->codeAppend("half2x2 shapeInverseMatrix = inverse(half2x2(shapeMatrix));"); - v->codeAppend("half2 fragShapeSpan = abs(half4(shapeInverseMatrix).xz) + " - "abs(half4(shapeInverseMatrix).yw);"); - } -} - -void GLSLInstanceProcessor::BackendMultisample::setupRect(GrGLSLVertexBuilder* v) { - if (fShapeCoords.vsOut()) { - v->codeAppendf("%s = %s;", fShapeCoords.vsOut(), this->outShapeCoords()); - } - if (fShapeInverseMatrix.vsOut()) { - v->codeAppendf("%s = shapeInverseMatrix;", fShapeInverseMatrix.vsOut()); - } - if (fFragShapeHalfSpan.vsOut()) { - v->codeAppendf("%s = 0.5 * fragShapeSpan;", fFragShapeHalfSpan.vsOut()); - } - if (fArcTest.vsOut()) { - // Pick a value that is not > 0. - v->codeAppendf("%s = float2(0);", fArcTest.vsOut()); - } - if (fTriangleIsArc.vsOut()) { - v->codeAppendf("%s = 0;", fTriangleIsArc.vsOut()); - } - if (fEarlyAccept.vsOut()) { - v->codeAppendf("%s = SAMPLE_MASK_ALL;", fEarlyAccept.vsOut()); - } -} - -void GLSLInstanceProcessor::BackendMultisample::setupOval(GrGLSLVertexBuilder* v) { - v->codeAppendf("%s = abs(%s);", fArcCoords.vsOut(), this->outShapeCoords()); - if (fArcInverseMatrix.vsOut()) { - v->codeAppendf("half2 s = sign(%s);", this->outShapeCoords()); - v->codeAppendf("%s = shapeInverseMatrix * half2x2(s.x, 0, 0 , s.y);", - fArcInverseMatrix.vsOut()); - } - if (fFragArcHalfSpan.vsOut()) { - v->codeAppendf("%s = 0.5 * fragShapeSpan;", fFragArcHalfSpan.vsOut()); - } - if (fArcTest.vsOut()) { - // Pick a value that is > 0. - v->codeAppendf("%s = half2(1);", fArcTest.vsOut()); - } - if (fTriangleIsArc.vsOut()) { - if (!this->isMixedSampled()) { - v->codeAppendf("%s = %s & 1;", - fTriangleIsArc.vsOut(), fInputs.attr(Attrib::kVertexAttrs)); - } else { - v->codeAppendf("%s = 1;", fTriangleIsArc.vsOut()); - } - } - if (fEarlyAccept.vsOut()) { - v->codeAppendf("%s = ~%s & SAMPLE_MASK_ALL;", - fEarlyAccept.vsOut(), fInputs.attr(Attrib::kVertexAttrs)); - } -} - -void GLSLInstanceProcessor::BackendMultisample::adjustRRectVertices(GrGLSLVertexBuilder* v) { - if (!this->isMixedSampled()) { - INHERITED::adjustRRectVertices(v); - return; - } - - if (!fOpInfo.fHasPerspective) { - // For the mixed samples algorithm it's best to bloat the corner triangles a bit so that - // more of the pixels that cross into the arc region are completely inside the shared edges. - // We also snap to a regular rect if the radii shrink smaller than a pixel. - v->codeAppend ("half2 midpt = 0.5 * (neighborRadii - radii);"); - v->codeAppend ("half2 cornerSize = any(lessThan(radii, fragShapeSpan)) ? " - "half2(0) : min(radii + 0.5 * fragShapeSpan, 1.0 - midpt);"); - } else { - // TODO: We could still bloat the corner triangle in the perspective case; we would just - // need to find the screen-space derivative of shape coords at this particular point. - v->codeAppend ("half2 cornerSize = any(lessThan(radii, half2(1e-3))) ? half2(0) : radii;"); - } - - v->codeAppendf("if (abs(%s.x) == 0.5)" - "%s.x = cornerSign.x * (1.0 - cornerSize.x);", - fInputs.attr(Attrib::kShapeCoords), fModifiedShapeCoords); - v->codeAppendf("if (abs(%s.y) == 0.5)" - "%s.y = cornerSign.y * (1.0 - cornerSize.y);", - fInputs.attr(Attrib::kShapeCoords), fModifiedShapeCoords); -} - -void GLSLInstanceProcessor::BackendMultisample::onSetupRRect(GrGLSLVertexBuilder* v) { - if (fShapeCoords.vsOut()) { - v->codeAppendf("%s = %s;", fShapeCoords.vsOut(), this->outShapeCoords()); - } - if (fShapeInverseMatrix.vsOut()) { - v->codeAppendf("%s = shapeInverseMatrix;", fShapeInverseMatrix.vsOut()); - } - if (fFragShapeHalfSpan.vsOut()) { - v->codeAppendf("%s = 0.5 * fragShapeSpan;", fFragShapeHalfSpan.vsOut()); - } - if (fArcInverseMatrix.vsOut()) { - v->codeAppend ("half2 s = cornerSign / radii;"); - v->codeAppendf("%s = shapeInverseMatrix * half2x2(s.x, 0, 0, s.y);", - fArcInverseMatrix.vsOut()); - } - if (fFragArcHalfSpan.vsOut()) { - v->codeAppendf("%s = 0.5 * (abs(half4(%s).xz) + abs(half4(%s).yw));", - fFragArcHalfSpan.vsOut(), fArcInverseMatrix.vsOut(), - fArcInverseMatrix.vsOut()); - } - if (fArcTest.vsOut()) { - // The interior triangles are laid out as a fan. fArcTest is both distances from shared - // edges of a fan triangle to a point within that triangle. fArcTest is used to check if a - // fragment is too close to either shared edge, in which case we point sample the shape as a - // rect at that point in order to guarantee the mixed samples discard logic works correctly. - v->codeAppendf("%s = (cornerSize == half2(0)) ? half2(0) : " - "cornerSign * %s * half2x2(1, cornerSize.x - 1.0, cornerSize.y - 1.0, 1);", - fArcTest.vsOut(), fModifiedShapeCoords); - if (!fOpInfo.fHasPerspective) { - // Shift the point at which distances to edges are measured from the center of the pixel - // to the corner. This way the sign of fArcTest will quickly tell us whether a pixel - // is completely inside the shared edge. Perspective mode will accomplish this same task - // by finding the derivatives in the fragment shader. - v->codeAppendf("%s -= 0.5 * (fragShapeSpan.yx * abs(radii - 1.0) + fragShapeSpan);", - fArcTest.vsOut()); - } - } - if (fEarlyAccept.vsOut()) { - SkASSERT(this->isMixedSampled()); - v->codeAppendf("%s = all(equal(half2(1), abs(%s))) ? 0 : SAMPLE_MASK_ALL;", - fEarlyAccept.vsOut(), fInputs.attr(Attrib::kShapeCoords)); - } -} - -void -GLSLInstanceProcessor::BackendMultisample::onInitInnerShape(GrGLSLVaryingHandler* varyingHandler, - GrGLSLVertexBuilder* v) { - varyingHandler->addVarying("innerShapeCoords", &fInnerShapeCoords); - if (kOval_ShapeFlag != fOpInfo.fInnerShapeTypes && - kRect_ShapeFlag != fOpInfo.fInnerShapeTypes) { - varyingHandler->addFlatVarying("innerRRect", &fInnerRRect); - } - if (!fOpInfo.fHasPerspective) { - varyingHandler->addFlatVarying("innerShapeInverseMatrix", &fInnerShapeInverseMatrix); - v->codeAppendf("%s = shapeInverseMatrix * float2x2(outer2Inner.x, 0, 0, outer2Inner.y);", - fInnerShapeInverseMatrix.vsOut()); - varyingHandler->addFlatVarying("fragInnerShapeHalfSpan", &fFragInnerShapeHalfSpan); - v->codeAppendf("%s = 0.5 * fragShapeSpan * outer2Inner.xy;", - fFragInnerShapeHalfSpan.vsOut()); - } -} - -void GLSLInstanceProcessor::BackendMultisample::setupInnerRect(GrGLSLVertexBuilder* v) { - if (fInnerRRect.vsOut()) { - // The fragment shader will generalize every inner shape as a round rect. Since this one - // is a rect, we simply emit bogus parameters for the round rect (negative radii) that - // ensure the fragment shader always takes the "sample as rect" codepath. - v->codeAppendf("%s = half4(2.0 * (inner.zw - inner.xy) / (outer.zw - outer.xy), half2(0));", - fInnerRRect.vsOut()); - } -} - -void GLSLInstanceProcessor::BackendMultisample::setupInnerOval(GrGLSLVertexBuilder* v) { - if (fInnerRRect.vsOut()) { - v->codeAppendf("%s = half4(0, 0, 1, 1);", fInnerRRect.vsOut()); - } -} - -void GLSLInstanceProcessor::BackendMultisample::onSetupInnerSimpleRRect(GrGLSLVertexBuilder* v) { - // Avoid numeric instability by not allowing the inner radii to get smaller than 1/10th pixel. - if (fFragInnerShapeHalfSpan.vsOut()) { - v->codeAppendf("innerRadii = max(innerRadii, 2e-1 * %s);", fFragInnerShapeHalfSpan.vsOut()); - } else { - v->codeAppend ("innerRadii = max(innerRadii, half2(1e-4));"); - } - v->codeAppendf("%s = half4(1.0 - innerRadii, 1.0 / innerRadii);", fInnerRRect.vsOut()); -} - -void GLSLInstanceProcessor::BackendMultisample::onEmitCode(GrGLSLVertexBuilder*, - GrGLSLPPFragmentBuilder* f, - const char*, const char*) { - f->defineConstant("SAMPLE_COUNT", fEffectiveSampleCnt); - if (this->isMixedSampled()) { - f->defineConstantf("int", "SAMPLE_MASK_ALL", "0x%x", (1 << fEffectiveSampleCnt) - 1); - f->defineConstantf("int", "SAMPLE_MASK_MSB", "0x%x", 1 << (fEffectiveSampleCnt - 1)); - } - - if (kRect_ShapeFlag != (fOpInfo.fShapeTypes | fOpInfo.fInnerShapeTypes)) { - GrShaderVar x("x", kFloat2_GrSLType, GrShaderVar::kNonArray); - f->emitFunction(kHalf_GrSLType, "square", 1, &x, "return dot(x, x);", &fSquareFun); - } - - EmitShapeCoords shapeCoords; - shapeCoords.fVarying = &fShapeCoords; - shapeCoords.fInverseMatrix = fShapeInverseMatrix.fsIn(); - shapeCoords.fFragHalfSpan = fFragShapeHalfSpan.fsIn(); - - EmitShapeCoords arcCoords; - arcCoords.fVarying = &fArcCoords; - arcCoords.fInverseMatrix = fArcInverseMatrix.fsIn(); - arcCoords.fFragHalfSpan = fFragArcHalfSpan.fsIn(); - bool clampArcCoords = this->isMixedSampled() && (fOpInfo.fShapeTypes & kRRect_ShapesMask); - - EmitShapeOpts opts; - opts.fIsTightGeometry = true; - opts.fResolveMixedSamples = this->isMixedSampled(); - opts.fInvertCoverage = false; - - if (fOpInfo.fHasPerspective && fOpInfo.fInnerShapeTypes) { - // This determines if the fragment should consider the inner shape in its sample mask. - // We take the derivative early in case discards may occur before we get to the inner shape. - f->codeAppendf("float2 fragInnerShapeApproxHalfSpan = 0.5 * fwidth(%s);", - fInnerShapeCoords.fsIn()); - } - - if (!this->isMixedSampled()) { - SkASSERT(!fArcTest.fsIn()); - if (fTriangleIsArc.fsIn()) { - f->codeAppendf("if (%s != 0) {", fTriangleIsArc.fsIn()); - this->emitArc(f, arcCoords, false, clampArcCoords, opts); - - f->codeAppend ("}"); - } - } else { - const char* arcTest = fArcTest.fsIn(); - if (arcTest && fOpInfo.fHasPerspective) { - // The non-perspective version accounts for fwidth() in the vertex shader. - // We make sure to take the derivative here, before a neighbor pixel may early accept. - f->codeAppendf("float2 arcTest = %s - 0.5 * fwidth(%s);", - fArcTest.fsIn(), fArcTest.fsIn()); - arcTest = "arcTest"; - } - const char* earlyAccept = fEarlyAccept.fsIn() ? fEarlyAccept.fsIn() : "SAMPLE_MASK_ALL"; - f->codeAppendf("if (gl_SampleMaskIn[0] == %s) {", earlyAccept); - f->overrideSampleCoverage(earlyAccept); - f->codeAppend ("} else {"); - if (arcTest) { - // At this point, if the sample mask is all set it means we are inside an arc triangle. - f->codeAppendf("if (gl_SampleMaskIn[0] == SAMPLE_MASK_ALL || " - "all(greaterThan(%s, float2(0)))) {", arcTest); - this->emitArc(f, arcCoords, false, clampArcCoords, opts); - f->codeAppend ("} else {"); - this->emitRect(f, shapeCoords, opts); - f->codeAppend ("}"); - } else if (fTriangleIsArc.fsIn()) { - f->codeAppendf("if (%s == 0) {", fTriangleIsArc.fsIn()); - this->emitRect(f, shapeCoords, opts); - f->codeAppend ("} else {"); - this->emitArc(f, arcCoords, false, clampArcCoords, opts); - f->codeAppend ("}"); - } else if (fOpInfo.fShapeTypes == kOval_ShapeFlag) { - this->emitArc(f, arcCoords, false, clampArcCoords, opts); - } else { - SkASSERT(fOpInfo.fShapeTypes == kRect_ShapeFlag); - this->emitRect(f, shapeCoords, opts); - } - f->codeAppend ("}"); - } - - if (fOpInfo.fInnerShapeTypes) { - f->codeAppendf("// Inner shape.\n"); - - EmitShapeCoords innerShapeCoords; - innerShapeCoords.fVarying = &fInnerShapeCoords; - if (!fOpInfo.fHasPerspective) { - innerShapeCoords.fInverseMatrix = fInnerShapeInverseMatrix.fsIn(); - innerShapeCoords.fFragHalfSpan = fFragInnerShapeHalfSpan.fsIn(); - } - - EmitShapeOpts innerOpts; - innerOpts.fIsTightGeometry = false; - innerOpts.fResolveMixedSamples = false; // Mixed samples are resolved in the outer shape. - innerOpts.fInvertCoverage = true; - - if (kOval_ShapeFlag == fOpInfo.fInnerShapeTypes) { - this->emitArc(f, innerShapeCoords, true, false, innerOpts); - } else { - f->codeAppendf("if (all(lessThan(abs(%s), 1.0 + %s))) {", fInnerShapeCoords.fsIn(), - !fOpInfo.fHasPerspective ? innerShapeCoords.fFragHalfSpan - : "fragInnerShapeApproxHalfSpan"); // Above. - if (kRect_ShapeFlag == fOpInfo.fInnerShapeTypes) { - this->emitRect(f, innerShapeCoords, innerOpts); - } else { - this->emitSimpleRRect(f, innerShapeCoords, fInnerRRect.fsIn(), innerOpts); - } - f->codeAppend ("}"); - } - } -} - -void GLSLInstanceProcessor::BackendMultisample::emitRect(GrGLSLPPFragmentBuilder* f, - const EmitShapeCoords& coords, - const EmitShapeOpts& opts) { - // Full MSAA doesn't need to do anything to draw a rect. - SkASSERT(!opts.fIsTightGeometry || opts.fResolveMixedSamples); - if (coords.fFragHalfSpan) { - f->codeAppendf("if (all(lessThanEqual(abs(%s), 1.0 - %s))) {", - coords.fVarying->fsIn(), coords.fFragHalfSpan); - // The entire pixel is inside the rect. - this->acceptOrRejectWholeFragment(f, true, opts); - f->codeAppend ("} else "); - if (opts.fIsTightGeometry && !fRectTrianglesMaySplit) { - f->codeAppendf("if (any(lessThan(abs(%s), 1.0 - %s))) {", - coords.fVarying->fsIn(), coords.fFragHalfSpan); - // The pixel falls on an edge of the rectangle and is known to not be on a shared edge. - this->acceptCoverageMask(f, "gl_SampleMaskIn[0]", opts, false); - f->codeAppend ("} else"); - } - f->codeAppend ("{"); - } - f->codeAppend ("int rectMask = 0;"); - f->codeAppend ("for (int i = 0; i < SAMPLE_COUNT; i++) {"); - f->codeAppend ( "float2 pt = "); - this->interpolateAtSample(f, *coords.fVarying, "i", coords.fInverseMatrix); - f->codeAppend ( ";"); - f->codeAppend ( "if (all(lessThan(abs(pt), float2(1)))) rectMask |= (1 << i);"); - f->codeAppend ("}"); - this->acceptCoverageMask(f, "rectMask", opts); - if (coords.fFragHalfSpan) { - f->codeAppend ("}"); - } -} - -void GLSLInstanceProcessor::BackendMultisample::emitArc(GrGLSLPPFragmentBuilder* f, - const EmitShapeCoords& coords, - bool coordsMayBeNegative, bool clampCoords, - const EmitShapeOpts& opts) { - if (coords.fFragHalfSpan) { - SkString absArcCoords; - absArcCoords.printf(coordsMayBeNegative ? "abs(%s)" : "%s", coords.fVarying->fsIn()); - if (clampCoords) { - f->codeAppendf("if (%s(max(%s + %s, half2(0))) < 1.0) {", - fSquareFun.c_str(), absArcCoords.c_str(), coords.fFragHalfSpan); - } else { - f->codeAppendf("if (%s(%s + %s) < 1.0) {", - fSquareFun.c_str(), absArcCoords.c_str(), coords.fFragHalfSpan); - } - // The entire pixel is inside the arc. - this->acceptOrRejectWholeFragment(f, true, opts); - f->codeAppendf("} else if (%s(max(%s - %s, half2(0))) >= 1.0) {", - fSquareFun.c_str(), absArcCoords.c_str(), coords.fFragHalfSpan); - // The entire pixel is outside the arc. - this->acceptOrRejectWholeFragment(f, false, opts); - f->codeAppend ("} else {"); - } - f->codeAppend ( "int arcMask = 0;"); - f->codeAppend ( "for (int i = 0; i < SAMPLE_COUNT; i++) {"); - f->codeAppend ( "float2 pt = "); - this->interpolateAtSample(f, *coords.fVarying, "i", coords.fInverseMatrix); - f->codeAppend ( ";"); - if (clampCoords) { - SkASSERT(!coordsMayBeNegative); - f->codeAppend ( "pt = max(pt, float2(0));"); - } - f->codeAppendf( "if (%s(pt) < 1.0) arcMask |= (1 << i);", fSquareFun.c_str()); - f->codeAppend ( "}"); - this->acceptCoverageMask(f, "arcMask", opts); - if (coords.fFragHalfSpan) { - f->codeAppend ("}"); - } -} - -void GLSLInstanceProcessor::BackendMultisample::emitSimpleRRect(GrGLSLPPFragmentBuilder* f, - const EmitShapeCoords& coords, - const char* rrect, - const EmitShapeOpts& opts) { - f->codeAppendf("float2 distanceToArcEdge = abs(%s) - %s.xy;", coords.fVarying->fsIn(), - rrect); - f->codeAppend ("if (any(lessThan(distanceToArcEdge, float2(0)))) {"); - this->emitRect(f, coords, opts); - f->codeAppend ("} else {"); - if (coords.fInverseMatrix && coords.fFragHalfSpan) { - f->codeAppendf("float2 rrectCoords = distanceToArcEdge * %s.zw;", rrect); - f->codeAppendf("float2 fragRRectHalfSpan = %s * %s.zw;", coords.fFragHalfSpan, rrect); - f->codeAppendf("if (%s(rrectCoords + fragRRectHalfSpan) <= 1.0) {", fSquareFun.c_str()); - // The entire pixel is inside the round rect. - this->acceptOrRejectWholeFragment(f, true, opts); - f->codeAppendf("} else if (%s(max(rrectCoords - fragRRectHalfSpan, float2(0))) >= 1.0) {", - fSquareFun.c_str()); - // The entire pixel is outside the round rect. - this->acceptOrRejectWholeFragment(f, false, opts); - f->codeAppend ("} else {"); - f->codeAppendf( "float2 s = %s.zw * sign(%s);", rrect, coords.fVarying->fsIn()); - f->codeAppendf( "float2x2 innerRRectInverseMatrix = %s * " - "float2x2(s.x, 0, 0, s.y);", coords.fInverseMatrix); - f->codeAppend ( "highp int rrectMask = 0;"); - f->codeAppend ( "for (int i = 0; i < SAMPLE_COUNT; i++) {"); - f->codeAppend ( "float2 pt = rrectCoords + "); - f->appendOffsetToSample("i", GrGLSLFPFragmentBuilder::kSkiaDevice_Coordinates); - f->codeAppend ( "* innerRRectInverseMatrix;"); - f->codeAppendf( "if (%s(max(pt, float2(0))) < 1.0) rrectMask |= (1 << i);", - fSquareFun.c_str()); - f->codeAppend ( "}"); - this->acceptCoverageMask(f, "rrectMask", opts); - f->codeAppend ("}"); - } else { - f->codeAppend ("int rrectMask = 0;"); - f->codeAppend ("for (int i = 0; i < SAMPLE_COUNT; i++) {"); - f->codeAppend ( "float2 shapePt = "); - this->interpolateAtSample(f, *coords.fVarying, "i", nullptr); - f->codeAppend ( ";"); - f->codeAppendf( "float2 rrectPt = max(abs(shapePt) - %s.xy, float2(0)) * %s.zw;", - rrect, rrect); - f->codeAppendf( "if (%s(rrectPt) < 1.0) rrectMask |= (1 << i);", fSquareFun.c_str()); - f->codeAppend ("}"); - this->acceptCoverageMask(f, "rrectMask", opts); - } - f->codeAppend ("}"); -} - -void GLSLInstanceProcessor::BackendMultisample::interpolateAtSample(GrGLSLPPFragmentBuilder* f, - const GrGLSLVarying& varying, - const char* sampleIdx, - const char* interpolationMatrix) { - if (interpolationMatrix) { - f->codeAppendf("(%s + ", varying.fsIn()); - f->appendOffsetToSample(sampleIdx, GrGLSLFPFragmentBuilder::kSkiaDevice_Coordinates); - f->codeAppendf(" * %s)", interpolationMatrix); - } else { - SkAssertResult( - f->enableFeature(GrGLSLFragmentBuilder::kMultisampleInterpolation_GLSLFeature)); - f->codeAppendf("interpolateAtOffset(%s, ", varying.fsIn()); - f->appendOffsetToSample(sampleIdx, GrGLSLFPFragmentBuilder::kGLSLWindow_Coordinates); - f->codeAppend(")"); - } -} - -void -GLSLInstanceProcessor::BackendMultisample::acceptOrRejectWholeFragment(GrGLSLPPFragmentBuilder* f, - bool inside, - const EmitShapeOpts& opts) { - if (inside != opts.fInvertCoverage) { // Accept the entire fragment. - if (opts.fResolveMixedSamples) { - // This is a mixed sampled fragment in the interior of the shape. Reassign 100% coverage - // to one fragment, and drop all other fragments that may fall on this same pixel. Since - // our geometry is water tight and non-overlapping, we can take advantage of the - // properties that (1) the incoming sample masks will be disjoint across fragments that - // fall on a common pixel, and (2) since the entire fragment is inside the shape, each - // sample's corresponding bit will be set in the incoming sample mask of exactly one - // fragment. - f->codeAppend("if ((gl_SampleMaskIn[0] & SAMPLE_MASK_MSB) == 0) {"); - // Drop this fragment. - if (!fOpInfo.fCannotDiscard) { - f->codeAppend("discard;"); - } else { - f->overrideSampleCoverage("0"); - } - f->codeAppend("} else {"); - // Override the lone surviving fragment to full coverage. - f->overrideSampleCoverage("-1"); - f->codeAppend("}"); - } - } else { // Reject the entire fragment. - if (!fOpInfo.fCannotDiscard) { - f->codeAppend("discard;"); - } else if (opts.fResolveMixedSamples) { - f->overrideSampleCoverage("0"); - } else { - f->maskSampleCoverage("0"); - } - } -} - -void GLSLInstanceProcessor::BackendMultisample::acceptCoverageMask(GrGLSLPPFragmentBuilder* f, - const char* shapeMask, - const EmitShapeOpts& opts, - bool maybeSharedEdge) { - if (opts.fResolveMixedSamples) { - if (maybeSharedEdge) { - // This is a mixed sampled fragment, potentially on the outer edge of the shape, with - // only partial shape coverage. Override the coverage of one fragment to "shapeMask", - // and drop all other fragments that may fall on this same pixel. Since our geometry is - // water tight, non-overlapping, and completely contains the shape, this means that each - // "on" bit from shapeMask is guaranteed to be set in the incoming sample mask of one, - // and only one, fragment that falls on this same pixel. - SkASSERT(!opts.fInvertCoverage); - f->codeAppendf("if ((gl_SampleMaskIn[0] & (1 << findMSB(%s))) == 0) {", shapeMask); - // Drop this fragment. - if (!fOpInfo.fCannotDiscard) { - f->codeAppend ("discard;"); - } else { - f->overrideSampleCoverage("0"); - } - f->codeAppend ("} else {"); - // Override the coverage of the lone surviving fragment to "shapeMask". - f->overrideSampleCoverage(shapeMask); - f->codeAppend ("}"); - } else { - f->overrideSampleCoverage(shapeMask); - } - } else { - f->maskSampleCoverage(shapeMask, opts.fInvertCoverage); - } -} - -//////////////////////////////////////////////////////////////////////////////////////////////////// - -GLSLInstanceProcessor::Backend* GLSLInstanceProcessor::Backend::Create(const GrPipeline& pipeline, - OpInfo opInfo, - const VertexInputs& inputs) { - switch (opInfo.aaType()) { - default: - SK_ABORT("Unexpected antialias mode."); - case GrAAType::kNone: - return new BackendNonAA(opInfo, inputs); - case GrAAType::kCoverage: - return new BackendCoverage(opInfo, inputs); - case GrAAType::kMSAA: - case GrAAType::kMixedSamples: { - const GrRenderTargetPriv& rtp = pipeline.renderTarget()->renderTargetPriv(); - const GrGpu::MultisampleSpecs& specs = rtp.getMultisampleSpecs(pipeline); - return new BackendMultisample(opInfo, inputs, specs.fEffectiveSampleCnt); - } - } -} - -//////////////////////////////////////////////////////////////////////////////////////////////////// - -const ShapeVertex kVertexData[] = { - // Rectangle. - {+1, +1, ~0}, /*0*/ - {-1, +1, ~0}, /*1*/ - {-1, -1, ~0}, /*2*/ - {+1, -1, ~0}, /*3*/ - // The next 4 are for the bordered version. - {+1, +1, 0}, /*4*/ - {-1, +1, 0}, /*5*/ - {-1, -1, 0}, /*6*/ - {+1, -1, 0}, /*7*/ - - // Octagon that inscribes the unit circle, cut by an interior unit octagon. - {+1.000000f, 0.000000f, 0}, /* 8*/ - {+1.000000f, +0.414214f, ~0}, /* 9*/ - {+0.707106f, +0.707106f, 0}, /*10*/ - {+0.414214f, +1.000000f, ~0}, /*11*/ - { 0.000000f, +1.000000f, 0}, /*12*/ - {-0.414214f, +1.000000f, ~0}, /*13*/ - {-0.707106f, +0.707106f, 0}, /*14*/ - {-1.000000f, +0.414214f, ~0}, /*15*/ - {-1.000000f, 0.000000f, 0}, /*16*/ - {-1.000000f, -0.414214f, ~0}, /*17*/ - {-0.707106f, -0.707106f, 0}, /*18*/ - {-0.414214f, -1.000000f, ~0}, /*19*/ - { 0.000000f, -1.000000f, 0}, /*20*/ - {+0.414214f, -1.000000f, ~0}, /*21*/ - {+0.707106f, -0.707106f, 0}, /*22*/ - {+1.000000f, -0.414214f, ~0}, /*23*/ - // This vertex is for the fanned versions. - { 0.000000f, 0.000000f, ~0}, /*24*/ - - // Rectangle with disjoint corner segments. - {+1.0, +0.5, 0x3}, /*25*/ - {+1.0, +1.0, 0x3}, /*26*/ - {+0.5, +1.0, 0x3}, /*27*/ - {-0.5, +1.0, 0x2}, /*28*/ - {-1.0, +1.0, 0x2}, /*29*/ - {-1.0, +0.5, 0x2}, /*30*/ - {-1.0, -0.5, 0x0}, /*31*/ - {-1.0, -1.0, 0x0}, /*32*/ - {-0.5, -1.0, 0x0}, /*33*/ - {+0.5, -1.0, 0x1}, /*34*/ - {+1.0, -1.0, 0x1}, /*35*/ - {+1.0, -0.5, 0x1}, /*36*/ - // The next 4 are for the fanned version. - { 0.0, 0.0, 0x3}, /*37*/ - { 0.0, 0.0, 0x2}, /*38*/ - { 0.0, 0.0, 0x0}, /*39*/ - { 0.0, 0.0, 0x1}, /*40*/ - // The next 8 are for the bordered version. - {+0.75, +0.50, 0x3}, /*41*/ - {+0.50, +0.75, 0x3}, /*42*/ - {-0.50, +0.75, 0x2}, /*43*/ - {-0.75, +0.50, 0x2}, /*44*/ - {-0.75, -0.50, 0x0}, /*45*/ - {-0.50, -0.75, 0x0}, /*46*/ - {+0.50, -0.75, 0x1}, /*47*/ - {+0.75, -0.50, 0x1}, /*48*/ - - // 16-gon that inscribes the unit circle, cut by an interior unit 16-gon. - {+1.000000f, +0.000000f, 0}, /*49*/ - {+1.000000f, +0.198913f, ~0}, /*50*/ - {+0.923879f, +0.382683f, 0}, /*51*/ - {+0.847760f, +0.566455f, ~0}, /*52*/ - {+0.707106f, +0.707106f, 0}, /*53*/ - {+0.566455f, +0.847760f, ~0}, /*54*/ - {+0.382683f, +0.923879f, 0}, /*55*/ - {+0.198913f, +1.000000f, ~0}, /*56*/ - {+0.000000f, +1.000000f, 0}, /*57*/ - {-0.198913f, +1.000000f, ~0}, /*58*/ - {-0.382683f, +0.923879f, 0}, /*59*/ - {-0.566455f, +0.847760f, ~0}, /*60*/ - {-0.707106f, +0.707106f, 0}, /*61*/ - {-0.847760f, +0.566455f, ~0}, /*62*/ - {-0.923879f, +0.382683f, 0}, /*63*/ - {-1.000000f, +0.198913f, ~0}, /*64*/ - {-1.000000f, +0.000000f, 0}, /*65*/ - {-1.000000f, -0.198913f, ~0}, /*66*/ - {-0.923879f, -0.382683f, 0}, /*67*/ - {-0.847760f, -0.566455f, ~0}, /*68*/ - {-0.707106f, -0.707106f, 0}, /*69*/ - {-0.566455f, -0.847760f, ~0}, /*70*/ - {-0.382683f, -0.923879f, 0}, /*71*/ - {-0.198913f, -1.000000f, ~0}, /*72*/ - {-0.000000f, -1.000000f, 0}, /*73*/ - {+0.198913f, -1.000000f, ~0}, /*74*/ - {+0.382683f, -0.923879f, 0}, /*75*/ - {+0.566455f, -0.847760f, ~0}, /*76*/ - {+0.707106f, -0.707106f, 0}, /*77*/ - {+0.847760f, -0.566455f, ~0}, /*78*/ - {+0.923879f, -0.382683f, 0}, /*79*/ - {+1.000000f, -0.198913f, ~0}, /*80*/ -}; - -const uint8_t kIndexData[] = { - // Rectangle. - 0, 1, 2, - 0, 2, 3, - - // Rectangle with a border. - 0, 1, 5, - 5, 4, 0, - 1, 2, 6, - 6, 5, 1, - 2, 3, 7, - 7, 6, 2, - 3, 0, 4, - 4, 7, 3, - 4, 5, 6, - 6, 7, 4, - - // Octagon that inscribes the unit circle, cut by an interior unit octagon. - 10, 8, 9, - 12, 10, 11, - 14, 12, 13, - 16, 14, 15, - 18, 16, 17, - 20, 18, 19, - 22, 20, 21, - 8, 22, 23, - 8, 10, 12, - 12, 14, 16, - 16, 18, 20, - 20, 22, 8, - 8, 12, 16, - 16, 20, 8, - - // Same octagons, but with the interior arranged as a fan. Used by mixed samples. - 10, 8, 9, - 12, 10, 11, - 14, 12, 13, - 16, 14, 15, - 18, 16, 17, - 20, 18, 19, - 22, 20, 21, - 8, 22, 23, - 24, 8, 10, - 12, 24, 10, - 24, 12, 14, - 16, 24, 14, - 24, 16, 18, - 20, 24, 18, - 24, 20, 22, - 8, 24, 22, - - // Same octagons, but with the inner and outer disjoint. Used by coverage AA. - 8, 22, 23, - 9, 8, 23, - 10, 8, 9, - 11, 10, 9, - 12, 10, 11, - 13, 12, 11, - 14, 12, 13, - 15, 14, 13, - 16, 14, 15, - 17, 16, 15, - 18, 16, 17, - 19, 18, 17, - 20, 18, 19, - 21, 20, 19, - 22, 20, 21, - 23, 22, 21, - 22, 8, 10, - 10, 12, 14, - 14, 16, 18, - 18, 20, 22, - 22, 10, 14, - 14, 18, 22, - - // Rectangle with disjoint corner segments. - 27, 25, 26, - 30, 28, 29, - 33, 31, 32, - 36, 34, 35, - 25, 27, 28, - 28, 30, 31, - 31, 33, 34, - 34, 36, 25, - 25, 28, 31, - 31, 34, 25, - - // Same rectangle with disjoint corners, but with the interior arranged as a fan. Used by - // mixed samples. - 27, 25, 26, - 30, 28, 29, - 33, 31, 32, - 36, 34, 35, - 27, 37, 25, - 28, 37, 27, - 30, 38, 28, - 31, 38, 30, - 33, 39, 31, - 34, 39, 33, - 36, 40, 34, - 25, 40, 36, - - // Same rectangle with disjoint corners, with a border as well. Used by coverage AA. - 41, 25, 26, - 42, 41, 26, - 27, 42, 26, - 43, 28, 29, - 44, 43, 29, - 30, 44, 29, - 45, 31, 32, - 46, 45, 32, - 33, 46, 32, - 47, 34, 35, - 48, 47, 35, - 36, 48, 35, - 27, 28, 42, - 42, 28, 43, - 30, 31, 44, - 44, 31, 45, - 33, 34, 46, - 46, 34, 47, - 36, 25, 48, - 48, 25, 41, - 41, 42, 43, - 43, 44, 45, - 45, 46, 47, - 47, 48, 41, - 41, 43, 45, - 45, 47, 41, - - // Same as the disjoint octagons, but with 16-gons instead. Used by coverage AA when the oval is - // sufficiently large. - 49, 79, 80, - 50, 49, 80, - 51, 49, 50, - 52, 51, 50, - 53, 51, 52, - 54, 53, 52, - 55, 53, 54, - 56, 55, 54, - 57, 55, 56, - 58, 57, 56, - 59, 57, 58, - 60, 59, 58, - 61, 59, 60, - 62, 61, 60, - 63, 61, 62, - 64, 63, 62, - 65, 63, 64, - 66, 65, 64, - 67, 65, 66, - 68, 67, 66, - 69, 67, 68, - 70, 69, 68, - 71, 69, 70, - 72, 71, 70, - 73, 71, 72, - 74, 73, 72, - 75, 73, 74, - 76, 75, 74, - 77, 75, 76, - 78, 77, 76, - 79, 77, 78, - 80, 79, 78, - 49, 51, 53, - 53, 55, 57, - 57, 59, 61, - 61, 63, 65, - 65, 67, 69, - 69, 71, 73, - 73, 75, 77, - 77, 79, 49, - 49, 53, 57, - 57, 61, 65, - 65, 69, 73, - 73, 77, 49, - 49, 57, 65, - 65, 73, 49, -}; - -enum { - kRect_FirstIndex = 0, - kRect_TriCount = 2, - - kFramedRect_FirstIndex = 6, - kFramedRect_TriCount = 10, - - kOctagons_FirstIndex = 36, - kOctagons_TriCount = 14, - - kOctagonsFanned_FirstIndex = 78, - kOctagonsFanned_TriCount = 16, - - kDisjointOctagons_FirstIndex = 126, - kDisjointOctagons_TriCount = 22, - - kCorneredRect_FirstIndex = 192, - kCorneredRect_TriCount = 10, - - kCorneredRectFanned_FirstIndex = 222, - kCorneredRectFanned_TriCount = 12, - - kCorneredFramedRect_FirstIndex = 258, - kCorneredFramedRect_TriCount = 26, - - kDisjoint16Gons_FirstIndex = 336, - kDisjoint16Gons_TriCount = 46, -}; - -GR_DECLARE_STATIC_UNIQUE_KEY(gShapeVertexBufferKey); - -const GrBuffer* InstanceProcessor::FindOrCreateVertexBuffer(GrGpu* gpu) { - GR_DEFINE_STATIC_UNIQUE_KEY(gShapeVertexBufferKey); - GrResourceCache* cache = gpu->getContext()->getResourceCache(); - if (GrGpuResource* cached = cache->findAndRefUniqueResource(gShapeVertexBufferKey)) { - return static_cast<GrBuffer*>(cached); - } - if (GrBuffer* buffer = gpu->createBuffer(sizeof(kVertexData), kVertex_GrBufferType, - kStatic_GrAccessPattern, kVertexData)) { - buffer->resourcePriv().setUniqueKey(gShapeVertexBufferKey); - return buffer; - } - return nullptr; -} - -GR_DECLARE_STATIC_UNIQUE_KEY(gShapeIndexBufferKey); - -const GrBuffer* InstanceProcessor::FindOrCreateIndex8Buffer(GrGpu* gpu) { - GR_DEFINE_STATIC_UNIQUE_KEY(gShapeIndexBufferKey); - GrResourceCache* cache = gpu->getContext()->getResourceCache(); - if (GrGpuResource* cached = cache->findAndRefUniqueResource(gShapeIndexBufferKey)) { - return static_cast<GrBuffer*>(cached); - } - if (GrBuffer* buffer = gpu->createBuffer(sizeof(kIndexData), kIndex_GrBufferType, - kStatic_GrAccessPattern, kIndexData)) { - buffer->resourcePriv().setUniqueKey(gShapeIndexBufferKey); - return buffer; - } - return nullptr; -} - -IndexRange InstanceProcessor::GetIndexRangeForRect(GrAAType aaType) { - switch (aaType) { - case GrAAType::kCoverage: - return {kFramedRect_FirstIndex, 3 * kFramedRect_TriCount}; - case GrAAType::kNone: - case GrAAType::kMSAA: - case GrAAType::kMixedSamples: - return {kRect_FirstIndex, 3 * kRect_TriCount}; - } - SK_ABORT("Unexpected aa type!"); - return {0, 0}; -} - -IndexRange InstanceProcessor::GetIndexRangeForOval(GrAAType aaType, const SkRect& devBounds) { - if (GrAAType::kCoverage == aaType && devBounds.height() * devBounds.width() >= 256 * 256) { - // This threshold was chosen quasi-scientifically on Tegra X1. - return {kDisjoint16Gons_FirstIndex, 3 * kDisjoint16Gons_TriCount}; - } - - switch (aaType) { - case GrAAType::kNone: - case GrAAType::kMSAA: - return {kOctagons_FirstIndex, 3 * kOctagons_TriCount}; - case GrAAType::kCoverage: - return {kDisjointOctagons_FirstIndex, 3 * kDisjointOctagons_TriCount}; - case GrAAType::kMixedSamples: - return {kOctagonsFanned_FirstIndex, 3 * kOctagonsFanned_TriCount}; - } - SK_ABORT("Unexpected aa type!"); - return {0, 0}; -} - -IndexRange InstanceProcessor::GetIndexRangeForRRect(GrAAType aaType) { - switch (aaType) { - case GrAAType::kNone: - case GrAAType::kMSAA: - return {kCorneredRect_FirstIndex, 3 * kCorneredRect_TriCount}; - case GrAAType::kCoverage: - return {kCorneredFramedRect_FirstIndex, 3 * kCorneredFramedRect_TriCount}; - case GrAAType::kMixedSamples: - return {kCorneredRectFanned_FirstIndex, 3 * kCorneredRectFanned_TriCount}; - } - SK_ABORT("Unexpected aa type!"); - return {0, 0}; -} - -const char* InstanceProcessor::GetNameOfIndexRange(IndexRange range) { - switch (range.fStart) { - case kRect_FirstIndex: return "basic_rect"; - case kFramedRect_FirstIndex: return "coverage_rect"; - - case kOctagons_FirstIndex: return "basic_oval"; - case kDisjointOctagons_FirstIndex: return "coverage_oval"; - case kDisjoint16Gons_FirstIndex: return "coverage_large_oval"; - case kOctagonsFanned_FirstIndex: return "mixed_samples_oval"; - - case kCorneredRect_FirstIndex: return "basic_round_rect"; - case kCorneredFramedRect_FirstIndex: return "coverage_round_rect"; - case kCorneredRectFanned_FirstIndex: return "mixed_samples_round_rect"; - - default: return "unknown"; - } -} - -} diff --git a/src/gpu/instanced/InstanceProcessor.h b/src/gpu/instanced/InstanceProcessor.h deleted file mode 100644 index 84d75a9f73..0000000000 --- a/src/gpu/instanced/InstanceProcessor.h +++ /dev/null @@ -1,69 +0,0 @@ -/* - * Copyright 2016 Google Inc. - * - * Use of this source code is governed by a BSD-style license that can be - * found in the LICENSE file. - */ - -#ifndef gr_instanced_InstanceProcessor_DEFINED -#define gr_instanced_InstanceProcessor_DEFINED - -#include "GrCaps.h" -#include "GrGeometryProcessor.h" -#include "instanced/InstancedRenderingTypes.h" - -namespace gr_instanced { - -/** - * This class provides a GP implementation that uses instanced rendering. Is sends geometry in as - * basic, pre-baked canonical shapes, and uses instanced vertex attribs to control how these shapes - * are transformed and drawn. MSAA is accomplished with the sample mask rather than finely - * tesselated geometry. - */ -class InstanceProcessor : public GrGeometryProcessor { -public: - InstanceProcessor(OpInfo, GrBuffer* paramsBuffer); - - const char* name() const override { return "Instance Processor"; } - OpInfo opInfo() const { return fOpInfo; } - - void getGLSLProcessorKey(const GrShaderCaps&, GrProcessorKeyBuilder* b) const override { - b->add32(fOpInfo.fData); - } - GrGLSLPrimitiveProcessor* createGLSLInstance(const GrShaderCaps&) const override; - - /** - * Returns a buffer of ShapeVertex that defines the canonical instanced geometry. - */ - static const GrBuffer* SK_WARN_UNUSED_RESULT FindOrCreateVertexBuffer(GrGpu*); - - /** - * Returns a buffer of 8-bit indices for the canonical instanced geometry. The client can call - * GetIndexRangeForXXX to know which indices to use for a specific shape. - */ - static const GrBuffer* SK_WARN_UNUSED_RESULT FindOrCreateIndex8Buffer(GrGpu*); - - static IndexRange GetIndexRangeForRect(GrAAType); - static IndexRange GetIndexRangeForOval(GrAAType, const SkRect& devBounds); - static IndexRange GetIndexRangeForRRect(GrAAType); - - static const char* GetNameOfIndexRange(IndexRange); - -private: - /** - * Called by the platform-specific instanced rendering implementation to determine the level of - * support this class can offer on the given GLSL platform. - */ - static GrCaps::InstancedSupport CheckSupport(const GrShaderCaps&, const GrCaps&); - - const OpInfo fOpInfo; - BufferAccess fParamsAccess; - - friend class GLInstancedRendering; // For CheckSupport. - - typedef GrGeometryProcessor INHERITED; -}; - -} - -#endif diff --git a/src/gpu/instanced/InstancedOp.cpp b/src/gpu/instanced/InstancedOp.cpp deleted file mode 100644 index ad76c18814..0000000000 --- a/src/gpu/instanced/InstancedOp.cpp +++ /dev/null @@ -1,468 +0,0 @@ -/* - * Copyright 2017 Google Inc. - * - * Use of this source code is governed by a BSD-style license that can be - * found in the LICENSE file. - */ - -#include "InstancedOp.h" -#include "InstanceProcessor.h" -#include "InstancedRendering.h" -#include "GrGpu.h" -#include "GrOpFlushState.h" -#include "GrRenderTargetOpList.h" - - -namespace gr_instanced { - -InstancedOp::InstancedOp(uint32_t classID, GrPaint&& paint, OpAllocator* alloc) - : INHERITED(classID) - , fIsTracked(false) - , fRequiresBarrierOnOverlap(false) - , fAllowsSRGBInputs(paint.getAllowSRGBInputs()) - , fDisableSRGBOutputConversion(paint.getDisableOutputConversionToSRGB()) - , fNumDraws(1) - , fNumChangesInGeometry(0) - , fAllocator(alloc) - , fInstancedRendering(nullptr) - , fProcessors(std::move(paint)) { - fHeadDraw = fTailDraw = alloc->allocateDraw(); -#ifdef SK_DEBUG - fHeadDraw->fGeometry = {-1, 0}; -#endif - fHeadDraw->fNext = nullptr; -} - -InstancedOp::~InstancedOp() { - if (fIsTracked) { - fInstancedRendering->removeOp(this); - } - - Draw* draw = fHeadDraw; - while (draw) { - Draw* next = draw->fNext; - fAllocator->releaseDraw(draw); - draw = next; - } -} - -void InstancedOp::appendRRectParams(const SkRRect& rrect) { - SkASSERT(!fIsTracked); - switch (rrect.getType()) { - case SkRRect::kSimple_Type: { - const SkVector& radii = rrect.getSimpleRadii(); - this->appendParamsTexel(radii.x(), radii.y(), rrect.width(), rrect.height()); - return; - } - case SkRRect::kNinePatch_Type: { - float twoOverW = 2 / rrect.width(); - float twoOverH = 2 / rrect.height(); - const SkVector& radiiTL = rrect.radii(SkRRect::kUpperLeft_Corner); - const SkVector& radiiBR = rrect.radii(SkRRect::kLowerRight_Corner); - this->appendParamsTexel(radiiTL.x() * twoOverW, radiiBR.x() * twoOverW, - radiiTL.y() * twoOverH, radiiBR.y() * twoOverH); - return; - } - case SkRRect::kComplex_Type: { - /** - * The x and y radii of each arc are stored in separate vectors, - * in the following order: - * - * __x1 _ _ _ x3__ - * y1 | | y2 - * - * | | - * - * y3 |__ _ _ _ __| y4 - * x2 x4 - * - */ - float twoOverW = 2 / rrect.width(); - float twoOverH = 2 / rrect.height(); - const SkVector& radiiTL = rrect.radii(SkRRect::kUpperLeft_Corner); - const SkVector& radiiTR = rrect.radii(SkRRect::kUpperRight_Corner); - const SkVector& radiiBR = rrect.radii(SkRRect::kLowerRight_Corner); - const SkVector& radiiBL = rrect.radii(SkRRect::kLowerLeft_Corner); - this->appendParamsTexel(radiiTL.x() * twoOverW, radiiBL.x() * twoOverW, - radiiTR.x() * twoOverW, radiiBR.x() * twoOverW); - this->appendParamsTexel(radiiTL.y() * twoOverH, radiiTR.y() * twoOverH, - radiiBL.y() * twoOverH, radiiBR.y() * twoOverH); - return; - } - default: return; - } -} - -void InstancedOp::appendParamsTexel(const SkScalar* vals, int count) { - SkASSERT(!fIsTracked); - SkASSERT(count <= 4 && count >= 0); - const float* valsAsFloats = vals; // Ensure SkScalar == float. - memcpy(&fParams.push_back(), valsAsFloats, count * sizeof(float)); - fInfo.fHasParams = true; -} - -void InstancedOp::appendParamsTexel(SkScalar x, SkScalar y, SkScalar z, SkScalar w) { - SkASSERT(!fIsTracked); - ParamsTexel& texel = fParams.push_back(); - texel.fX = SkScalarToFloat(x); - texel.fY = SkScalarToFloat(y); - texel.fZ = SkScalarToFloat(z); - texel.fW = SkScalarToFloat(w); - fInfo.fHasParams = true; -} - -void InstancedOp::appendParamsTexel(SkScalar x, SkScalar y, SkScalar z) { - SkASSERT(!fIsTracked); - ParamsTexel& texel = fParams.push_back(); - texel.fX = SkScalarToFloat(x); - texel.fY = SkScalarToFloat(y); - texel.fZ = SkScalarToFloat(z); - fInfo.fHasParams = true; -} - -GrDrawOp::RequiresDstTexture InstancedOp::finalize(const GrCaps& caps, const GrAppliedClip* clip, - GrPixelConfigIsClamped dstIsClamped) { - GrProcessorAnalysisCoverage coverageInput; - bool isMixedSamples = false; - if (GrAAType::kCoverage == fInfo.aaType() || - (GrAAType::kNone == fInfo.aaType() && !fInfo.isSimpleRects() && fInfo.fCannotDiscard)) { - coverageInput = GrProcessorAnalysisCoverage::kSingleChannel; - } else { - coverageInput = GrProcessorAnalysisCoverage::kNone; - isMixedSamples = GrAAType::kMixedSamples == fInfo.aaType(); - } - GrProcessorSet::Analysis analysis = - fProcessors.finalize(this->getSingleInstance().fColor, coverageInput, clip, - isMixedSamples, caps, dstIsClamped, - &this->getSingleDraw().fInstance.fColor); - - Draw& draw = this->getSingleDraw(); // This will assert if we have > 1 command. - SkASSERT(draw.fGeometry.isEmpty()); - SkASSERT(SkIsPow2(fInfo.fShapeTypes)); - SkASSERT(!fIsTracked); - - if (kRect_ShapeFlag == fInfo.fShapeTypes) { - draw.fGeometry = InstanceProcessor::GetIndexRangeForRect(fInfo.aaType()); - } else if (kOval_ShapeFlag == fInfo.fShapeTypes) { - draw.fGeometry = InstanceProcessor::GetIndexRangeForOval(fInfo.aaType(), this->bounds()); - } else { - draw.fGeometry = InstanceProcessor::GetIndexRangeForRRect(fInfo.aaType()); - } - - fInfo.fCannotTweakAlphaForCoverage = !analysis.isCompatibleWithCoverageAsAlpha(); - - fInfo.fUsesLocalCoords = analysis.usesLocalCoords(); - fRequiresBarrierOnOverlap = analysis.requiresBarrierBetweenOverlappingDraws(); - return analysis.requiresDstTexture() ? RequiresDstTexture::kYes : RequiresDstTexture::kNo; -} - -void InstancedOp::wasRecorded(GrRenderTargetOpList* opList) { - SkASSERT(!fInstancedRendering); - SkASSERT(!fIsTracked); - - fInstancedRendering = opList->instancedRendering(); - - this->getSingleInstance().fInfo |= fInstancedRendering->addOpParams(this); - fInstancedRendering->addOp(this); - fIsTracked = true; -} - -bool InstancedOp::onCombineIfPossible(GrOp* other, const GrCaps&) { - InstancedOp* that = static_cast<InstancedOp*>(other); - SkASSERT(!that->fInstancedRendering || (fInstancedRendering == that->fInstancedRendering)); - SkASSERT(fTailDraw); - SkASSERT(that->fTailDraw); - - if (!OpInfo::CanCombine(fInfo, that->fInfo) || fProcessors != that->fProcessors) { - return false; - } - - if (fAllowsSRGBInputs != that->fAllowsSRGBInputs || - fDisableSRGBOutputConversion != that->fDisableSRGBOutputConversion) { - return false; - } - SkASSERT(fRequiresBarrierOnOverlap == that->fRequiresBarrierOnOverlap); - if (fRequiresBarrierOnOverlap && this->bounds().intersects(that->bounds())) { - return false; - } - OpInfo combinedInfo = fInfo | that->fInfo; - if (!combinedInfo.isSimpleRects()) { - // This threshold was chosen with the "shapes_mixed" bench on a MacBook with Intel graphics. - // There seems to be a wide range where it doesn't matter if we combine or not. What matters - // is that the itty bitty rects combine with other shapes and the giant ones don't. - constexpr SkScalar kMaxPixelsToGeneralizeRects = 256 * 256; - if (fInfo.isSimpleRects() && fPixelLoad > kMaxPixelsToGeneralizeRects) { - return false; - } - if (that->fInfo.isSimpleRects() && that->fPixelLoad > kMaxPixelsToGeneralizeRects) { - return false; - } - } - - if (!that->fInstancedRendering) { - that->fInstancedRendering = fInstancedRendering; - that->getSingleInstance().fInfo |= fInstancedRendering->addOpParams(that); - } - - this->joinBounds(*that); - fInfo = combinedInfo; - fPixelLoad += that->fPixelLoad; - // Adopt the other op's draws. - fNumDraws += that->fNumDraws; - fNumChangesInGeometry += that->fNumChangesInGeometry; - if (fTailDraw->fGeometry != that->fHeadDraw->fGeometry) { - ++fNumChangesInGeometry; - } - fTailDraw->fNext = that->fHeadDraw; - fTailDraw = that->fTailDraw; - - that->fHeadDraw = that->fTailDraw = nullptr; - - return true; -} - -void InstancedOp::onExecute(GrOpFlushState* state) { - SkASSERT(fInstancedRendering->isFlushing()); - SkASSERT(state->gpu() == fInstancedRendering->gpu()); - - state->gpu()->handleDirtyContext(); - - GrPipeline::InitArgs args; - args.fCaps = &state->caps(); - args.fResourceProvider = state->resourceProvider(); - args.fFlags = GrAATypeIsHW(fInfo.aaType()) ? GrPipeline::kHWAntialias_Flag : 0; - if (fAllowsSRGBInputs) { - args.fFlags |= GrPipeline::kAllowSRGBInputs_Flag; - } - if (fDisableSRGBOutputConversion) { - args.fFlags |= GrPipeline::kDisableOutputConversionToSRGB_Flag; - } - args.fProxy = state->drawOpArgs().fProxy; - args.fDstProxy = state->drawOpArgs().fDstProxy; - GrPipeline pipeline(args, std::move(fProcessors), state->detachAppliedClip()); - - if (GrXferBarrierType barrierType = pipeline.xferBarrierType(*state->gpu()->caps())) { - state->gpu()->xferBarrier(pipeline.renderTarget(), barrierType); - } - fInstancedRendering->draw(pipeline, fInfo, this); -} - -//////////////////////////////////////////////////////////////////////////////////////////////////// - -OpAllocator::OpAllocator(const GrCaps* caps) - : fDrawPool(1024, 1024) - , fCaps(sk_ref_sp(caps)) { -} - -OpAllocator::~OpAllocator() {} - -std::unique_ptr<GrDrawOp> OpAllocator::recordRect(const SkRect& rect, - const SkMatrix& viewMatrix, - GrPaint&& paint, GrAA aa, - const GrInstancedPipelineInfo& info) { - return this->recordShape(ShapeType::kRect, rect, viewMatrix, std::move(paint), rect, aa, info); -} - -std::unique_ptr<GrDrawOp> OpAllocator::recordRect(const SkRect& rect, - const SkMatrix& viewMatrix, - GrPaint&& paint, const SkRect& localRect, - GrAA aa, - const GrInstancedPipelineInfo& info) { - return this->recordShape(ShapeType::kRect, rect, viewMatrix, std::move(paint), localRect, aa, - info); -} - -std::unique_ptr<GrDrawOp> OpAllocator::recordRect(const SkRect& rect, - const SkMatrix& viewMatrix, - GrPaint&& paint, - const SkMatrix& localMatrix, GrAA aa, - const GrInstancedPipelineInfo& info) { - if (localMatrix.hasPerspective()) { - return nullptr; // Perspective is not yet supported in the local matrix. - } - if (std::unique_ptr<InstancedOp> op = this->recordShape(ShapeType::kRect, rect, viewMatrix, - std::move(paint), rect, aa, info)) { - op->getSingleInstance().fInfo |= kLocalMatrix_InfoFlag; - op->appendParamsTexel(localMatrix.getScaleX(), localMatrix.getSkewX(), - localMatrix.getTranslateX()); - op->appendParamsTexel(localMatrix.getSkewY(), localMatrix.getScaleY(), - localMatrix.getTranslateY()); - op->fInfo.fHasLocalMatrix = true; - return std::move(op); - } - return nullptr; -} - -std::unique_ptr<GrDrawOp> OpAllocator::recordOval(const SkRect& oval, - const SkMatrix& viewMatrix, - GrPaint&& paint, GrAA aa, - const GrInstancedPipelineInfo& info) { - return this->recordShape(ShapeType::kOval, oval, viewMatrix, std::move(paint), oval, aa, info); -} - -std::unique_ptr<GrDrawOp> OpAllocator::recordRRect(const SkRRect& rrect, - const SkMatrix& viewMatrix, - GrPaint&& paint, GrAA aa, - const GrInstancedPipelineInfo& info) { - if (std::unique_ptr<InstancedOp> op = - this->recordShape(GetRRectShapeType(rrect), rrect.rect(), viewMatrix, - std::move(paint), rrect.rect(), aa, info)) { - op->appendRRectParams(rrect); - return std::move(op); - } - return nullptr; -} - -std::unique_ptr<GrDrawOp> OpAllocator::recordDRRect(const SkRRect& outer, - const SkRRect& inner, - const SkMatrix& viewMatrix, - GrPaint&& paint, GrAA aa, - const GrInstancedPipelineInfo& info) { - if (inner.getType() > SkRRect::kSimple_Type) { - return nullptr; // Complex inner round rects are not yet supported. - } - if (SkRRect::kEmpty_Type == inner.getType()) { - return this->recordRRect(outer, viewMatrix, std::move(paint), aa, info); - } - if (std::unique_ptr<InstancedOp> op = - this->recordShape(GetRRectShapeType(outer), outer.rect(), viewMatrix, - std::move(paint), outer.rect(), aa, info)) { - op->appendRRectParams(outer); - ShapeType innerShapeType = GetRRectShapeType(inner); - op->fInfo.fInnerShapeTypes |= GetShapeFlag(innerShapeType); - op->getSingleInstance().fInfo |= ((int)innerShapeType << kInnerShapeType_InfoBit); - op->appendParamsTexel(inner.rect().asScalars(), 4); - op->appendRRectParams(inner); - return std::move(op); - } - return nullptr; -} - -std::unique_ptr<InstancedOp> OpAllocator::recordShape( - ShapeType type, const SkRect& bounds, const SkMatrix& viewMatrix, GrPaint&& paint, - const SkRect& localRect, GrAA aa, const GrInstancedPipelineInfo& info) { - - if (info.fIsRenderingToFloat && fCaps->avoidInstancedDrawsToFPTargets()) { - return nullptr; - } - - GrAAType aaType; - if (!this->selectAntialiasMode(viewMatrix, aa, info, &aaType)) { - return nullptr; - } - - GrColor color = paint.getColor(); - std::unique_ptr<InstancedOp> op = this->makeOp(std::move(paint)); - op->fInfo.setAAType(aaType); - op->fInfo.fShapeTypes = GetShapeFlag(type); - op->fInfo.fCannotDiscard = true; - Instance& instance = op->getSingleInstance(); - instance.fInfo = (int)type << kShapeType_InfoBit; - - InstancedOp::HasAABloat aaBloat = - (aaType == GrAAType::kCoverage) ? InstancedOp::HasAABloat::kYes - : InstancedOp::HasAABloat::kNo; - InstancedOp::IsZeroArea zeroArea = bounds.isEmpty() ? InstancedOp::IsZeroArea::kYes - : InstancedOp::IsZeroArea::kNo; - - // The instanced shape renderer draws rectangles of [-1, -1, +1, +1], so we find the matrix that - // will map this rectangle to the same device coordinates as "viewMatrix * bounds". - float sx = 0.5f * bounds.width(); - float sy = 0.5f * bounds.height(); - float tx = sx + bounds.fLeft; - float ty = sy + bounds.fTop; - if (!viewMatrix.hasPerspective()) { - float* m = instance.fShapeMatrix2x3; - m[0] = viewMatrix.getScaleX() * sx; - m[1] = viewMatrix.getSkewX() * sy; - m[2] = viewMatrix.getTranslateX() + - viewMatrix.getScaleX() * tx + viewMatrix.getSkewX() * ty; - - m[3] = viewMatrix.getSkewY() * sx; - m[4] = viewMatrix.getScaleY() * sy; - m[5] = viewMatrix.getTranslateY() + - viewMatrix.getSkewY() * tx + viewMatrix.getScaleY() * ty; - - // Since 'm' is a 2x3 matrix that maps the rect [-1, +1] into the shape's device-space quad, - // it's quite simple to find the bounding rectangle: - float devBoundsHalfWidth = fabsf(m[0]) + fabsf(m[1]); - float devBoundsHalfHeight = fabsf(m[3]) + fabsf(m[4]); - SkRect opBounds; - opBounds.fLeft = m[2] - devBoundsHalfWidth; - opBounds.fRight = m[2] + devBoundsHalfWidth; - opBounds.fTop = m[5] - devBoundsHalfHeight; - opBounds.fBottom = m[5] + devBoundsHalfHeight; - op->setBounds(opBounds, aaBloat, zeroArea); - - // TODO: Is this worth the CPU overhead? - op->fInfo.fNonSquare = - fabsf(devBoundsHalfHeight - devBoundsHalfWidth) > 0.5f || // Early out. - fabs(m[0] * m[3] + m[1] * m[4]) > 1e-3f || // Skew? - fabs(m[0] * m[0] + m[1] * m[1] - m[3] * m[3] - m[4] * m[4]) > - 1e-2f; // Diff. lengths? - } else { - SkMatrix shapeMatrix(viewMatrix); - shapeMatrix.preTranslate(tx, ty); - shapeMatrix.preScale(sx, sy); - instance.fInfo |= kPerspective_InfoFlag; - - float* m = instance.fShapeMatrix2x3; - m[0] = SkScalarToFloat(shapeMatrix.getScaleX()); - m[1] = SkScalarToFloat(shapeMatrix.getSkewX()); - m[2] = SkScalarToFloat(shapeMatrix.getTranslateX()); - m[3] = SkScalarToFloat(shapeMatrix.getSkewY()); - m[4] = SkScalarToFloat(shapeMatrix.getScaleY()); - m[5] = SkScalarToFloat(shapeMatrix.getTranslateY()); - - // Send the perspective column as a param. - op->appendParamsTexel(shapeMatrix[SkMatrix::kMPersp0], shapeMatrix[SkMatrix::kMPersp1], - shapeMatrix[SkMatrix::kMPersp2]); - op->fInfo.fHasPerspective = true; - - op->setBounds(bounds, aaBloat, zeroArea); - op->fInfo.fNonSquare = true; - } - - instance.fColor = color; - - const float* rectAsFloats = localRect.asScalars(); // Ensure SkScalar == float. - memcpy(&instance.fLocalRect, rectAsFloats, 4 * sizeof(float)); - - op->fPixelLoad = op->bounds().height() * op->bounds().width(); - return op; -} - -inline bool OpAllocator::selectAntialiasMode(const SkMatrix& viewMatrix, GrAA aa, - const GrInstancedPipelineInfo& info, - GrAAType* aaType) { - SkASSERT(!info.fIsMixedSampled || info.fIsMultisampled); - SkASSERT(GrCaps::InstancedSupport::kNone != fCaps->instancedSupport()); - - if (!info.fIsMultisampled || fCaps->multisampleDisableSupport()) { - if (GrAA::kNo == aa) { - *aaType = GrAAType::kNone; - return true; - } - - if (info.canUseCoverageAA() && viewMatrix.preservesRightAngles()) { - *aaType = GrAAType::kCoverage; - return true; - } - } - - if (info.fIsMultisampled && - fCaps->instancedSupport() >= GrCaps::InstancedSupport::kMultisampled) { - if (!info.fIsMixedSampled) { - *aaType = GrAAType::kMSAA; - return true; - } - if (fCaps->instancedSupport() >= GrCaps::InstancedSupport::kMixedSampled) { - *aaType = GrAAType::kMixedSamples; - return true; - } - } - - return false; -} - -} diff --git a/src/gpu/instanced/InstancedOp.h b/src/gpu/instanced/InstancedOp.h deleted file mode 100644 index eb2a6fa437..0000000000 --- a/src/gpu/instanced/InstancedOp.h +++ /dev/null @@ -1,167 +0,0 @@ -/* - * Copyright 2017 Google Inc. - * - * Use of this source code is governed by a BSD-style license that can be - * found in the LICENSE file. - */ - -#ifndef gr_instanced_InstancedOp_DEFINED -#define gr_instanced_InstancedOp_DEFINED - - -#include "../private/GrInstancedPipelineInfo.h" -#include "GrMemoryPool.h" -#include "ops/GrDrawOp.h" -#include "instanced/InstancedRenderingTypes.h" - -#include "SkTInternalLList.h" - -namespace gr_instanced { - -class InstancedRendering; -class OpAllocator; - -class InstancedOp : public GrDrawOp { -public: - SK_DECLARE_INTERNAL_LLIST_INTERFACE(InstancedOp); - - ~InstancedOp() override; - const char* name() const override { return "InstancedOp"; } - - void visitProxies(const VisitProxyFunc& func) const override { - fProcessors.visitProxies(func); - } - - SkString dumpInfo() const override { - SkString string; - string.printf( - "AA: %d, ShapeTypes: 0x%02x, IShapeTypes: 0x%02x, Persp %d, " - "NonSquare: %d, PLoad: %0.2f, Tracked: %d, NumDraws: %d, " - "GeomChanges: %d\n", - (unsigned)fInfo.fAAType, - fInfo.fShapeTypes, - fInfo.fInnerShapeTypes, - fInfo.fHasPerspective, - fInfo.fNonSquare, - fPixelLoad, - fIsTracked, - fNumDraws, - fNumChangesInGeometry); - string.append(INHERITED::dumpInfo()); - return string; - } - - struct Draw { - Instance fInstance; - IndexRange fGeometry; - Draw* fNext; - }; - - Draw& getSingleDraw() const { SkASSERT(fHeadDraw && !fHeadDraw->fNext); return *fHeadDraw; } - Instance& getSingleInstance() const { return this->getSingleDraw().fInstance; } - - void appendRRectParams(const SkRRect&); - void appendParamsTexel(const SkScalar* vals, int count); - void appendParamsTexel(SkScalar x, SkScalar y, SkScalar z, SkScalar w); - void appendParamsTexel(SkScalar x, SkScalar y, SkScalar z); - FixedFunctionFlags fixedFunctionFlags() const override { - return GrAATypeIsHW(fInfo.aaType()) ? FixedFunctionFlags::kUsesHWAA - : FixedFunctionFlags::kNone; - } - RequiresDstTexture finalize(const GrCaps&, const GrAppliedClip*, - GrPixelConfigIsClamped) override; - - // Registers the op with the InstancedRendering list of tracked ops. - void wasRecorded(GrRenderTargetOpList*) override; - -protected: - InstancedOp(uint32_t classID, GrPaint&&, OpAllocator*); - - bool fIsTracked : 1; - bool fRequiresBarrierOnOverlap : 1; - bool fAllowsSRGBInputs : 1; - bool fDisableSRGBOutputConversion : 1; - int fNumDraws; - int fNumChangesInGeometry; - Draw* fHeadDraw; - Draw* fTailDraw; - OpAllocator* fAllocator; - InstancedRendering* fInstancedRendering; - OpInfo fInfo; - SkScalar fPixelLoad; - GrProcessorSet fProcessors; - SkSTArray<5, ParamsTexel, true> fParams; - -private: - bool onCombineIfPossible(GrOp* other, const GrCaps& caps) override; - void onPrepare(GrOpFlushState*) override {} - void onExecute(GrOpFlushState*) override; - - typedef GrDrawOp INHERITED; - - friend class InstancedRendering; - friend class OpAllocator; -}; - -class OpAllocator : public SkNoncopyable { -public: - virtual ~OpAllocator(); - - /** - * These methods make a new record internally for an instanced draw, and return an op that is - * effectively just an index to that record. The returned op is not self-contained, but - * rather relies on this class to handle the rendering. The client must call beginFlush() on - * this class before attempting to flush ops returned by it. It is invalid to record new - * draws between beginFlush() and endFlush(). - */ - std::unique_ptr<GrDrawOp> SK_WARN_UNUSED_RESULT recordRect(const SkRect&, const SkMatrix&, - GrPaint&&, GrAA, - const GrInstancedPipelineInfo&); - - std::unique_ptr<GrDrawOp> SK_WARN_UNUSED_RESULT recordRect(const SkRect&, const SkMatrix&, - GrPaint&&, const SkRect& localRect, - GrAA, - const GrInstancedPipelineInfo&); - - std::unique_ptr<GrDrawOp> SK_WARN_UNUSED_RESULT recordRect(const SkRect&, const SkMatrix&, - GrPaint&&, - const SkMatrix& localMatrix, GrAA, - const GrInstancedPipelineInfo&); - - std::unique_ptr<GrDrawOp> SK_WARN_UNUSED_RESULT recordOval(const SkRect&, const SkMatrix&, - GrPaint&&, GrAA, - const GrInstancedPipelineInfo&); - - std::unique_ptr<GrDrawOp> SK_WARN_UNUSED_RESULT recordRRect(const SkRRect&, const SkMatrix&, - GrPaint&&, GrAA, - const GrInstancedPipelineInfo&); - - std::unique_ptr<GrDrawOp> SK_WARN_UNUSED_RESULT recordDRRect(const SkRRect& outer, - const SkRRect& inner, - const SkMatrix&, GrPaint&&, GrAA, - const GrInstancedPipelineInfo&); - - InstancedOp::Draw* allocateDraw() { return fDrawPool.allocate(); } - void releaseDraw(InstancedOp::Draw* draw) { fDrawPool.release(draw); } - -protected: - OpAllocator(const GrCaps*); - -private: - bool selectAntialiasMode(const SkMatrix& viewMatrix, GrAA aa, const GrInstancedPipelineInfo&, - GrAAType*); - virtual std::unique_ptr<InstancedOp> makeOp(GrPaint&&) = 0; - - std::unique_ptr<InstancedOp> SK_WARN_UNUSED_RESULT recordShape( - ShapeType, const SkRect& bounds, - const SkMatrix& viewMatrix, GrPaint&&, - const SkRect& localRect, GrAA aa, - const GrInstancedPipelineInfo&); - - GrObjectMemoryPool<InstancedOp::Draw> fDrawPool; - sk_sp<const GrCaps> fCaps; -}; - -} - -#endif diff --git a/src/gpu/instanced/InstancedRendering.cpp b/src/gpu/instanced/InstancedRendering.cpp deleted file mode 100644 index 52daaec248..0000000000 --- a/src/gpu/instanced/InstancedRendering.cpp +++ /dev/null @@ -1,106 +0,0 @@ -/* - * Copyright 2016 Google Inc. - * - * Use of this source code is governed by a BSD-style license that can be - * found in the LICENSE file. - */ - -#include "InstancedRendering.h" - -#include "InstancedOp.h" -#include "GrAppliedClip.h" -#include "GrCaps.h" -#include "GrGpu.h" -#include "GrPipeline.h" -#include "GrResourceProvider.h" - -#include "instanced/InstanceProcessor.h" - -namespace gr_instanced { - - -InstancedRendering::InstancedRendering(GrGpu* gpu) - : fGpu(SkRef(gpu)) - SkDEBUGCODE(, fState(State::kRecordingDraws)) { -} - -InstancedRendering::~InstancedRendering() { - // Make sure there isn't anything with a dangling pointer to this instance. - SkASSERT(fTrackedOps.isEmpty()); -} - -void InstancedRendering::beginFlush(GrResourceProvider* rp) { -#ifdef SK_DEBUG - SkASSERT(State::kRecordingDraws == fState); - fState = State::kFlushing; -#endif - - if (fTrackedOps.isEmpty()) { - return; - } - - if (!fVertexBuffer) { - fVertexBuffer.reset(InstanceProcessor::FindOrCreateVertexBuffer(fGpu.get())); - if (!fVertexBuffer) { - return; - } - } - - if (!fIndexBuffer) { - fIndexBuffer.reset(InstanceProcessor::FindOrCreateIndex8Buffer(fGpu.get())); - if (!fIndexBuffer) { - return; - } - } - - if (!fParams.empty()) { - fParamsBuffer.reset(rp->createBuffer(fParams.count() * sizeof(ParamsTexel), - kTexel_GrBufferType, kDynamic_GrAccessPattern, - GrResourceProvider::kNoPendingIO_Flag | - GrResourceProvider::kRequireGpuMemory_Flag, - fParams.begin())); - if (!fParamsBuffer) { - return; - } - } - - this->onBeginFlush(rp); -} - -void InstancedRendering::draw(const GrPipeline& pipeline, - OpInfo info, - const InstancedOp* baseOp) { - InstanceProcessor instProc(info, fParamsBuffer.get()); - - this->onDraw(pipeline, instProc, baseOp); -} - -void InstancedRendering::endFlush() { - // The caller is expected to delete all tracked ops (i.e. ops whose applyPipelineOptimizations - // method has been called) before ending the flush. - SkASSERT(fTrackedOps.isEmpty()); - fParams.reset(); - fParamsBuffer.reset(); - this->onEndFlush(); - SkDEBUGCODE(fState = State::kRecordingDraws;) - // Hold on to the shape coords and index buffers. -} - -void InstancedRendering::resetGpuResources(ResetType resetType) { - fVertexBuffer.reset(); - fIndexBuffer.reset(); - fParamsBuffer.reset(); - this->onResetGpuResources(resetType); -} - -int InstancedRendering::addOpParams(InstancedOp* op) { - if (op->fParams.empty()) { - return 0; - } - - SkASSERT(fParams.count() < (int)kParamsIdx_InfoMask); // TODO: cleaner. - int count = fParams.count(); - fParams.push_back_n(op->fParams.count(), op->fParams.begin()); - return count; -} -} diff --git a/src/gpu/instanced/InstancedRendering.h b/src/gpu/instanced/InstancedRendering.h deleted file mode 100644 index 93e3d5884e..0000000000 --- a/src/gpu/instanced/InstancedRendering.h +++ /dev/null @@ -1,119 +0,0 @@ -/* - * Copyright 2016 Google Inc. - * - * Use of this source code is governed by a BSD-style license that can be - * found in the LICENSE file. - */ - -#ifndef gr_instanced_InstancedRendering_DEFINED -#define gr_instanced_InstancedRendering_DEFINED - -#include "instanced/InstancedOp.h" -#include "instanced/InstancedRenderingTypes.h" - -#include "SkTInternalLList.h" - -class GrGpu; -class GrResourceProvider; - -namespace gr_instanced { - -class InstancedOp; -class InstanceProcessor; - - -/** - * Instanced Rendering occurs through the interaction of four class: - * InstancedOp - * OpAllocator - * InstancedRendering - * InstanceProcessor - * - * The InstancedOp is a GrDrawOp but is more of a proxy than normal operations. It accumulates a - * LL of Draw objects that are allocated all together by the OpAllocator. - * - * There is only one OpAllocator which encapsulates the creation of InstancedOps and the pool - * of memory used for their Draw objects. - * - * The InstancedRendering class tracks a list of InstancedOps that will all be drawn during - * the same flush. There is currently one per opList. The nature of instanced - * rendering allows these ops to combine well and render efficiently. - * During a flush, it assembles the accumulated draw data into a single vertex and texel - * buffer per opList, and its subclasses draw the ops using backend-specific instanced - * rendering APIs. - * - * InstanceProcessors implement the shaders required for instance rendering. - */ -class InstancedRendering : public SkNoncopyable { -public: - virtual ~InstancedRendering(); - - GrGpu* gpu() const { return fGpu.get(); } - - /** - * Compiles all recorded draws into GPU buffers and allows the client to begin flushing the - * ops created by this class. - */ - void beginFlush(GrResourceProvider*); - - void draw(const GrPipeline& pipeline, OpInfo info, const InstancedOp* baseOp); - - /** - * Called once the ops created previously by this class have all been released. Allows the - * client to begin recording draws again. - */ - void endFlush(); - - enum class ResetType : bool { - kDestroy, - kAbandon - }; - - /** - * Resets all GPU resources, including those that are held long term. They will be lazily - * reinitialized if the class begins to be used again. - */ - void resetGpuResources(ResetType); - - void addOp(InstancedOp* op) { fTrackedOps.addToTail(op); } - void removeOp(InstancedOp* op) { fTrackedOps.remove(op); } - int addOpParams(InstancedOp* op); - -#ifdef SK_DEBUG - bool isFlushing() const { return InstancedRendering::State::kFlushing == fState; } -#endif - -protected: - typedef SkTInternalLList<InstancedOp> OpList; - - InstancedRendering(GrGpu* gpu); - - const OpList& trackedOps() const { return fTrackedOps; } - const GrBuffer* vertexBuffer() const { SkASSERT(fVertexBuffer); return fVertexBuffer.get(); } - const GrBuffer* indexBuffer() const { SkASSERT(fIndexBuffer); return fIndexBuffer.get(); } - - virtual void onBeginFlush(GrResourceProvider*) = 0; - virtual void onDraw(const GrPipeline&, const InstanceProcessor&, const InstancedOp*) = 0; - virtual void onEndFlush() = 0; - virtual void onResetGpuResources(ResetType) = 0; - -private: -#ifdef SK_DEBUG - enum class State : bool { - kRecordingDraws, - kFlushing - }; -#endif - - const sk_sp<GrGpu> fGpu; - SkDEBUGCODE(State fState;) - SkSTArray<1024, ParamsTexel, true> fParams; - OpList fTrackedOps; - sk_sp<const GrBuffer> fVertexBuffer; - sk_sp<const GrBuffer> fIndexBuffer; - sk_sp<GrBuffer> fParamsBuffer; -}; - -} - -#endif diff --git a/src/gpu/instanced/InstancedRenderingTypes.h b/src/gpu/instanced/InstancedRenderingTypes.h deleted file mode 100644 index 55102fce8e..0000000000 --- a/src/gpu/instanced/InstancedRenderingTypes.h +++ /dev/null @@ -1,188 +0,0 @@ -/* - * Copyright 2016 Google Inc. - * - * Use of this source code is governed by a BSD-style license that can be - * found in the LICENSE file. - */ - -#ifndef gr_instanced_InstancedRenderingTypes_DEFINED -#define gr_instanced_InstancedRenderingTypes_DEFINED - -#include "GrTypes.h" -#include "GrTypesPriv.h" -#include "SkRRect.h" - -namespace gr_instanced { - -/** - * Per-vertex data. These values get fed into normal vertex attribs. - */ -struct ShapeVertex { - float fX, fY; //!< Shape coordinates. - int32_t fAttrs; //!< Shape-specific vertex attributes, if needed. -}; - -/** - * Per-instance data. These values get fed into instanced vertex attribs. - */ -struct Instance { - uint32_t fInfo; //!< Packed info about the instance. See InfoBits. - float fShapeMatrix2x3[6]; //!< Maps canonical shape coords -> device space coords. - uint32_t fColor; //!< Color to be written out by the primitive processor. - float fLocalRect[4]; //!< Local coords rect that spans [-1, +1] in shape coords. -}; - -enum class Attrib : uint8_t { - kShapeCoords, - kVertexAttrs, - kInstanceInfo, - kShapeMatrixX, - kShapeMatrixY, - kColor, - kLocalRect -}; -constexpr int kNumAttribs = 1 + (int)Attrib::kLocalRect; - -enum class ShapeType : uint8_t { - kRect, - kOval, - kSimpleRRect, - kNinePatch, - kComplexRRect -}; -constexpr int kNumShapeTypes = 1 + (int)ShapeType::kComplexRRect; - -inline static ShapeType GetRRectShapeType(const SkRRect& rrect) { - SkASSERT(rrect.getType() >= SkRRect::kRect_Type && - rrect.getType() <= SkRRect::kComplex_Type); - return static_cast<ShapeType>(rrect.getType() - 1); - - GR_STATIC_ASSERT((int)ShapeType::kRect == SkRRect::kRect_Type - 1); - GR_STATIC_ASSERT((int)ShapeType::kOval == SkRRect::kOval_Type - 1); - GR_STATIC_ASSERT((int)ShapeType::kSimpleRRect == SkRRect::kSimple_Type - 1); - GR_STATIC_ASSERT((int)ShapeType::kNinePatch == SkRRect::kNinePatch_Type - 1); - GR_STATIC_ASSERT((int)ShapeType::kComplexRRect == SkRRect::kComplex_Type - 1); - GR_STATIC_ASSERT(kNumShapeTypes == SkRRect::kComplex_Type); -} - -enum ShapeFlag { - kRect_ShapeFlag = (1 << (int)ShapeType::kRect), - kOval_ShapeFlag = (1 << (int)ShapeType::kOval), - kSimpleRRect_ShapeFlag = (1 << (int)ShapeType::kSimpleRRect), - kNinePatch_ShapeFlag = (1 << (int)ShapeType::kNinePatch), - kComplexRRect_ShapeFlag = (1 << (int)ShapeType::kComplexRRect), - - kRRect_ShapesMask = kSimpleRRect_ShapeFlag | kNinePatch_ShapeFlag | kComplexRRect_ShapeFlag -}; - -constexpr uint8_t GetShapeFlag(ShapeType type) { return 1 << (int)type; } - -/** - * Defines what data is stored at which bits in the fInfo field of the instanced data. - */ -enum InfoBits { - kShapeType_InfoBit = 29, - kInnerShapeType_InfoBit = 27, - kPerspective_InfoBit = 26, - kLocalMatrix_InfoBit = 25, - kParamsIdx_InfoBit = 0 -}; - -enum InfoMasks { - kShapeType_InfoMask = 0u - (1 << kShapeType_InfoBit), - kInnerShapeType_InfoMask = (1 << kShapeType_InfoBit) - (1 << kInnerShapeType_InfoBit), - kPerspective_InfoFlag = (1 << kPerspective_InfoBit), - kLocalMatrix_InfoFlag = (1 << kLocalMatrix_InfoBit), - kParamsIdx_InfoMask = (1 << kLocalMatrix_InfoBit) - 1 -}; - -GR_STATIC_ASSERT((kNumShapeTypes - 1) <= (uint32_t)kShapeType_InfoMask >> kShapeType_InfoBit); -GR_STATIC_ASSERT((int)ShapeType::kSimpleRRect <= - kInnerShapeType_InfoMask >> kInnerShapeType_InfoBit); - -/** - * Additional parameters required by some instances (e.g. round rect radii, perspective column, - * local matrix). These are accessed via texel buffer. - */ -struct ParamsTexel { - float fX, fY, fZ, fW; -}; - -GR_STATIC_ASSERT(0 == offsetof(ParamsTexel, fX)); -GR_STATIC_ASSERT(4 * 4 == sizeof(ParamsTexel)); - -/** - * Tracks all information needed in order to draw a op of instances. This struct also serves - * as an all-in-one shader key for the op. - */ -struct OpInfo { - OpInfo() : fData(0) {} - explicit OpInfo(uint32_t data) : fData(data) {} - - static bool CanCombine(const OpInfo& a, const OpInfo& b); - - bool isSimpleRects() const { - return !((fShapeTypes & ~kRect_ShapeFlag) | fInnerShapeTypes); - } - - GrAAType aaType() const { return static_cast<GrAAType>(fAAType); } - void setAAType(GrAAType aaType) { fAAType = static_cast<uint8_t>(aaType); } - - union { - struct { - uint8_t fAAType; // GrAAType - uint8_t fShapeTypes; - uint8_t fInnerShapeTypes; - bool fHasPerspective : 1; - bool fHasLocalMatrix : 1; - bool fHasParams : 1; - bool fNonSquare : 1; - bool fUsesLocalCoords : 1; - bool fCannotTweakAlphaForCoverage : 1; - bool fCannotDiscard : 1; - }; - uint32_t fData; - }; -}; - -inline bool OpInfo::CanCombine(const OpInfo& a, const OpInfo& b) { - if (a.fAAType != b.fAAType) { - return false; - } - if (SkToBool(a.fInnerShapeTypes) != SkToBool(b.fInnerShapeTypes)) { - // GrInstanceProcessor can't currently combine draws with and without inner shapes. - return false; - } - if (a.fCannotDiscard != b.fCannotDiscard) { - // For stencil draws, the use of discard can be a requirement. - return false; - } - return true; -} - -inline OpInfo operator|(const OpInfo& a, const OpInfo& b) { - SkASSERT(OpInfo::CanCombine(a, b)); - return OpInfo(a.fData | b.fData); -} - -// This is required since all the data must fit into 32 bits of a shader key. -GR_STATIC_ASSERT(sizeof(uint32_t) == sizeof(OpInfo)); -GR_STATIC_ASSERT(kNumShapeTypes <= 8); - -struct IndexRange { - bool operator ==(const IndexRange& that) const { - SkASSERT(fStart != that.fStart || fCount == that.fCount); - return fStart == that.fStart; - } - bool operator !=(const IndexRange& that) const { return !(*this == that); } - - bool isEmpty() const { return fCount <= 0; } - int end() { return fStart + fCount; } - - int16_t fStart; - int16_t fCount; -}; - -} - -#endif diff --git a/src/gpu/mock/GrMockGpu.h b/src/gpu/mock/GrMockGpu.h index 49a52ff183..2a86a4ed87 100644 --- a/src/gpu/mock/GrMockGpu.h +++ b/src/gpu/mock/GrMockGpu.h @@ -98,8 +98,6 @@ private: GrBuffer* onCreateBuffer(size_t sizeInBytes, GrBufferType, GrAccessPattern, const void*) override; - gr_instanced::InstancedRendering* onCreateInstancedRendering() override { return nullptr; } - bool onReadPixels(GrSurface* surface, GrSurfaceOrigin, int left, int top, int width, int height, GrPixelConfig, diff --git a/src/gpu/mtl/GrMtlGpu.h b/src/gpu/mtl/GrMtlGpu.h index cb2744f0aa..4dde825dbc 100644 --- a/src/gpu/mtl/GrMtlGpu.h +++ b/src/gpu/mtl/GrMtlGpu.h @@ -107,8 +107,6 @@ private: return nullptr; } - gr_instanced::InstancedRendering* onCreateInstancedRendering() override { return nullptr; } - bool onReadPixels(GrSurface* surface, GrSurfaceOrigin, int left, int top, int width, int height, GrPixelConfig, diff --git a/src/gpu/vk/GrVkGpu.h b/src/gpu/vk/GrVkGpu.h index 8e6f39195a..75c7cb849f 100644 --- a/src/gpu/vk/GrVkGpu.h +++ b/src/gpu/vk/GrVkGpu.h @@ -195,8 +195,6 @@ private: GrBuffer* onCreateBuffer(size_t size, GrBufferType type, GrAccessPattern, const void* data) override; - gr_instanced::InstancedRendering* onCreateInstancedRendering() override { return nullptr; } - bool onReadPixels(GrSurface* surface, GrSurfaceOrigin, int left, int top, int width, int height, GrPixelConfig, |