3 * Copyright 2012 Google Inc.
5 * Use of this source code is governed by a BSD-style license that can be
6 * found in the LICENSE file.
9 #include "GrClipMaskManager.h"
10 #include "GrAAConvexPathRenderer.h"
11 #include "GrAAHairLinePathRenderer.h"
12 #include "GrAARectRenderer.h"
13 #include "GrDrawTargetCaps.h"
16 #include "GrPathRenderer.h"
17 #include "GrRenderTarget.h"
18 #include "GrStencilBuffer.h"
19 #include "GrSWMaskHelper.h"
20 #include "effects/GrTextureDomain.h"
21 #include "SkRasterClip.h"
22 #include "SkStrokeRec.h"
27 typedef SkClipStack::Element Element;
29 using namespace GrReducedClip;
31 ////////////////////////////////////////////////////////////////////////////////
33 // set up the draw state to enable the aa clipping mask. Besides setting up the
34 // stage matrix this also alters the vertex layout
35 void setup_drawstate_aaclip(GrGpu* gpu,
37 const SkIRect &devBound) {
38 GrDrawState* drawState = gpu->drawState();
42 // We want to use device coords to compute the texture coordinates. We set our matrix to be
43 // equal to the view matrix followed by an offset to the devBound, and then a scaling matrix to
44 // normalized coords. We apply this matrix to the vertex positions rather than local coords.
45 mat.setIDiv(result->width(), result->height());
46 mat.preTranslate(SkIntToScalar(-devBound.fLeft),
47 SkIntToScalar(-devBound.fTop));
48 mat.preConcat(drawState->getViewMatrix());
50 SkIRect domainTexels = SkIRect::MakeWH(devBound.width(), devBound.height());
51 // This could be a long-lived effect that is cached with the alpha-mask.
52 drawState->addCoverageEffect(
53 GrTextureDomainEffect::Create(result,
55 GrTextureDomain::MakeTexelDomain(result, domainTexels),
56 GrTextureDomain::kDecal_Mode,
57 GrTextureParams::kNone_FilterMode,
58 kPosition_GrCoordSet))->unref();
61 bool path_needs_SW_renderer(GrContext* context,
63 const SkPath& origPath,
64 const SkStrokeRec& stroke,
66 // the gpu alpha mask will draw the inverse paths as non-inverse to a temp buffer
67 SkTCopyOnFirstWrite<SkPath> path(origPath);
68 if (path->isInverseFillType()) {
69 path.writable()->toggleInverseFillType();
71 // last (false) parameter disallows use of the SW path renderer
72 GrPathRendererChain::DrawType type = doAA ?
73 GrPathRendererChain::kColorAntiAlias_DrawType :
74 GrPathRendererChain::kColor_DrawType;
76 return NULL == context->getPathRenderer(*path, stroke, gpu, false, type);
82 * This method traverses the clip stack to see if the GrSoftwarePathRenderer
83 * will be used on any element. If so, it returns true to indicate that the
84 * entire clip should be rendered in SW and then uploaded en masse to the gpu.
86 bool GrClipMaskManager::useSWOnlyPath(const ElementList& elements) {
88 // TODO: generalize this function so that when
89 // a clip gets complex enough it can just be done in SW regardless
90 // of whether it would invoke the GrSoftwarePathRenderer.
91 SkStrokeRec stroke(SkStrokeRec::kFill_InitStyle);
93 for (ElementList::Iter iter(elements.headIter()); iter.get(); iter.next()) {
94 const Element* element = iter.get();
95 // rects can always be drawn directly w/o using the software path
96 // so only paths need to be checked
97 if (Element::kPath_Type == element->getType() &&
98 path_needs_SW_renderer(this->getContext(), fGpu,
108 ////////////////////////////////////////////////////////////////////////////////
109 // sort out what kind of clip mask needs to be created: alpha, stencil,
110 // scissor, or entirely software
111 bool GrClipMaskManager::setupClipping(const GrClipData* clipDataIn,
112 GrDrawState::AutoRestoreEffects* are) {
113 fCurrClipMaskType = kNone_ClipMaskType;
115 ElementList elements(16);
117 InitialState initialState;
118 SkIRect clipSpaceIBounds;
122 GrDrawState* drawState = fGpu->drawState();
124 const GrRenderTarget* rt = drawState->getRenderTarget();
125 // GrDrawTarget should have filtered this for us
126 SkASSERT(NULL != rt);
128 bool ignoreClip = !drawState->isClipState() || clipDataIn->fClipStack->isWideOpen();
131 SkIRect clipSpaceRTIBounds = SkIRect::MakeWH(rt->width(), rt->height());
132 clipSpaceRTIBounds.offset(clipDataIn->fOrigin);
133 ReduceClipStack(*clipDataIn->fClipStack,
140 if (elements.isEmpty()) {
141 if (kAllIn_InitialState == initialState) {
142 ignoreClip = clipSpaceIBounds == clipSpaceRTIBounds;
151 fGpu->disableScissor();
152 this->setGpuStencil();
157 // TODO: catch isRect && requiresAA and use clip planes if available rather than a mask.
159 // If MSAA is enabled we can do everything in the stencil buffer.
160 if (0 == rt->numSamples() && requiresAA) {
161 GrTexture* result = NULL;
163 if (this->useSWOnlyPath(elements)) {
164 // The clip geometry is complex enough that it will be more efficient to create it
165 // entirely in software
166 result = this->createSoftwareClipMask(genID,
171 result = this->createAlphaClipMask(genID,
177 if (NULL != result) {
178 // The mask's top left coord should be pinned to the rounded-out top left corner of
179 // clipSpace bounds. We determine the mask's position WRT to the render target here.
180 SkIRect rtSpaceMaskBounds = clipSpaceIBounds;
181 rtSpaceMaskBounds.offset(-clipDataIn->fOrigin);
182 are->set(fGpu->drawState());
183 setup_drawstate_aaclip(fGpu, result, rtSpaceMaskBounds);
184 fGpu->disableScissor();
185 this->setGpuStencil();
188 // if alpha clip mask creation fails fall through to the non-AA code paths
192 // Either a hard (stencil buffer) clip was explicitly requested or an anti-aliased clip couldn't
193 // be created. In either case, free up the texture in the anti-aliased mask cache.
194 // TODO: this may require more investigation. Ganesh performs a lot of utility draws (e.g.,
195 // clears, InOrderDrawBuffer playbacks) that hit the stencil buffer path. These may be
196 // "incorrectly" clearing the AA cache.
199 // If the clip is a rectangle then just set the scissor. Otherwise, create
202 SkIRect clipRect = clipSpaceIBounds;
203 clipRect.offset(-clipDataIn->fOrigin);
204 fGpu->enableScissor(clipRect);
205 this->setGpuStencil();
209 // use the stencil clip if we can't represent the clip as a rectangle.
210 SkIPoint clipSpaceToStencilSpaceOffset = -clipDataIn->fOrigin;
211 this->createStencilClipMask(genID,
215 clipSpaceToStencilSpaceOffset);
217 // This must occur after createStencilClipMask. That function may change the scissor. Also, it
218 // only guarantees that the stencil mask is correct within the bounds it was passed, so we must
219 // use both stencil and scissor test to the bounds for the final draw.
220 SkIRect scissorSpaceIBounds(clipSpaceIBounds);
221 scissorSpaceIBounds.offset(clipSpaceToStencilSpaceOffset);
222 fGpu->enableScissor(scissorSpaceIBounds);
223 this->setGpuStencil();
227 #define VISUALIZE_COMPLEX_CLIP 0
229 #if VISUALIZE_COMPLEX_CLIP
230 #include "SkRandom.h"
232 #define SET_RANDOM_COLOR drawState->setColor(0xff000000 | gRandom.nextU());
234 #define SET_RANDOM_COLOR
239 ////////////////////////////////////////////////////////////////////////////////
240 // set up the OpenGL blend function to perform the specified
241 // boolean operation for alpha clip mask creation
242 void setup_boolean_blendcoeffs(GrDrawState* drawState, SkRegion::Op op) {
245 case SkRegion::kReplace_Op:
246 drawState->setBlendFunc(kOne_GrBlendCoeff, kZero_GrBlendCoeff);
248 case SkRegion::kIntersect_Op:
249 drawState->setBlendFunc(kDC_GrBlendCoeff, kZero_GrBlendCoeff);
251 case SkRegion::kUnion_Op:
252 drawState->setBlendFunc(kOne_GrBlendCoeff, kISC_GrBlendCoeff);
254 case SkRegion::kXOR_Op:
255 drawState->setBlendFunc(kIDC_GrBlendCoeff, kISC_GrBlendCoeff);
257 case SkRegion::kDifference_Op:
258 drawState->setBlendFunc(kZero_GrBlendCoeff, kISC_GrBlendCoeff);
260 case SkRegion::kReverseDifference_Op:
261 drawState->setBlendFunc(kIDC_GrBlendCoeff, kZero_GrBlendCoeff);
271 ////////////////////////////////////////////////////////////////////////////////
272 bool GrClipMaskManager::drawElement(GrTexture* target,
273 const SkClipStack::Element* element,
274 GrPathRenderer* pr) {
275 GrDrawState* drawState = fGpu->drawState();
277 drawState->setRenderTarget(target->asRenderTarget());
279 switch (element->getType()) {
280 case Element::kRect_Type:
281 // TODO: Do rects directly to the accumulator using a aa-rect GrEffect that covers the
282 // entire mask bounds and writes 0 outside the rect.
283 if (element->isAA()) {
284 getContext()->getAARectRenderer()->fillAARect(fGpu,
291 fGpu->drawSimpleRect(element->getRect(), NULL);
294 case Element::kPath_Type: {
295 SkTCopyOnFirstWrite<SkPath> path(element->getPath());
296 if (path->isInverseFillType()) {
297 path.writable()->toggleInverseFillType();
299 SkStrokeRec stroke(SkStrokeRec::kFill_InitStyle);
301 GrPathRendererChain::DrawType type;
302 type = element->isAA() ? GrPathRendererChain::kColorAntiAlias_DrawType :
303 GrPathRendererChain::kColor_DrawType;
304 pr = this->getContext()->getPathRenderer(*path, stroke, fGpu, false, type);
309 pr->drawPath(element->getPath(), stroke, fGpu, element->isAA());
313 // something is wrong if we're trying to draw an empty element.
314 GrCrash("Unexpected element type");
320 bool GrClipMaskManager::canStencilAndDrawElement(GrTexture* target,
321 const SkClipStack::Element* element,
322 GrPathRenderer** pr) {
323 GrDrawState* drawState = fGpu->drawState();
324 drawState->setRenderTarget(target->asRenderTarget());
326 switch (element->getType()) {
327 case Element::kRect_Type:
329 case Element::kPath_Type: {
330 SkTCopyOnFirstWrite<SkPath> path(element->getPath());
331 if (path->isInverseFillType()) {
332 path.writable()->toggleInverseFillType();
334 SkStrokeRec stroke(SkStrokeRec::kFill_InitStyle);
335 GrPathRendererChain::DrawType type = element->isAA() ?
336 GrPathRendererChain::kStencilAndColorAntiAlias_DrawType :
337 GrPathRendererChain::kStencilAndColor_DrawType;
338 *pr = this->getContext()->getPathRenderer(*path, stroke, fGpu, false, type);
342 // something is wrong if we're trying to draw an empty element.
343 GrCrash("Unexpected element type");
348 void GrClipMaskManager::mergeMask(GrTexture* dstMask,
351 const SkIRect& dstBound,
352 const SkIRect& srcBound) {
353 GrDrawState::AutoViewMatrixRestore avmr;
354 GrDrawState* drawState = fGpu->drawState();
355 SkAssertResult(avmr.setIdentity(drawState));
356 GrDrawState::AutoRestoreEffects are(drawState);
358 drawState->setRenderTarget(dstMask->asRenderTarget());
360 setup_boolean_blendcoeffs(drawState, op);
363 sampleM.setIDiv(srcMask->width(), srcMask->height());
365 drawState->addColorEffect(
366 GrTextureDomainEffect::Create(srcMask,
368 GrTextureDomain::MakeTexelDomain(srcMask, srcBound),
369 GrTextureDomain::kDecal_Mode,
370 GrTextureParams::kNone_FilterMode))->unref();
371 fGpu->drawSimpleRect(SkRect::Make(dstBound), NULL);
374 // get a texture to act as a temporary buffer for AA clip boolean operations
375 // TODO: given the expense of createTexture we may want to just cache this too
376 void GrClipMaskManager::getTemp(int width, int height, GrAutoScratchTexture* temp) {
377 if (NULL != temp->texture()) {
378 // we've already allocated the temp texture
383 desc.fFlags = kRenderTarget_GrTextureFlagBit|kNoStencil_GrTextureFlagBit;
385 desc.fHeight = height;
386 desc.fConfig = kAlpha_8_GrPixelConfig;
388 temp->set(this->getContext(), desc);
391 ////////////////////////////////////////////////////////////////////////////////
392 // Handles caching & allocation (if needed) of a clip alpha-mask texture for both the sw-upload
393 // or gpu-rendered cases. Returns true if there is no more work to be done (i.e., we got a cache
395 bool GrClipMaskManager::getMaskTexture(int32_t elementsGenID,
396 const SkIRect& clipSpaceIBounds,
399 bool cached = fAACache.canReuse(elementsGenID, clipSpaceIBounds);
402 // There isn't a suitable entry in the cache so we create a new texture to store the mask.
403 // Since we are setting up the cache we know the last lookup was a miss. Free up the
404 // currently cached mask so it can be reused.
408 desc.fFlags = willUpload ? kNone_GrTextureFlags : kRenderTarget_GrTextureFlagBit;
409 desc.fWidth = clipSpaceIBounds.width();
410 desc.fHeight = clipSpaceIBounds.height();
411 desc.fConfig = kRGBA_8888_GrPixelConfig;
412 if (willUpload || this->getContext()->isConfigRenderable(kAlpha_8_GrPixelConfig, false)) {
413 // We would always like A8 but it isn't supported on all platforms
414 desc.fConfig = kAlpha_8_GrPixelConfig;
417 fAACache.acquireMask(elementsGenID, desc, clipSpaceIBounds);
420 *result = fAACache.getLastMask();
424 ////////////////////////////////////////////////////////////////////////////////
425 // Create a 8-bit clip mask in alpha
426 GrTexture* GrClipMaskManager::createAlphaClipMask(int32_t elementsGenID,
427 InitialState initialState,
428 const ElementList& elements,
429 const SkIRect& clipSpaceIBounds) {
430 SkASSERT(kNone_ClipMaskType == fCurrClipMaskType);
433 if (this->getMaskTexture(elementsGenID, clipSpaceIBounds, &result, false)) {
434 fCurrClipMaskType = kAlpha_ClipMaskType;
438 if (NULL == result) {
443 // The top-left of the mask corresponds to the top-left corner of the bounds.
444 SkVector clipToMaskOffset = {
445 SkIntToScalar(-clipSpaceIBounds.fLeft),
446 SkIntToScalar(-clipSpaceIBounds.fTop)
448 // The texture may be larger than necessary, this rect represents the part of the texture
449 // we populate with a rasterization of the clip.
450 SkIRect maskSpaceIBounds = SkIRect::MakeWH(clipSpaceIBounds.width(), clipSpaceIBounds.height());
452 // Set the matrix so that rendered clip elements are transformed to mask space from clip space.
454 translate.setTranslate(clipToMaskOffset);
455 GrDrawTarget::AutoGeometryAndStatePush agasp(fGpu, GrDrawTarget::kReset_ASRInit, &translate);
457 GrDrawState* drawState = fGpu->drawState();
459 // We're drawing a coverage mask and want coverage to be run through the blend function.
460 drawState->enableState(GrDrawState::kCoverageDrawing_StateBit);
462 // The scratch texture that we are drawing into can be substantially larger than the mask. Only
463 // clear the part that we care about.
464 fGpu->clear(&maskSpaceIBounds,
465 kAllIn_InitialState == initialState ? 0xffffffff : 0x00000000,
467 result->asRenderTarget());
469 // When we use the stencil in the below loop it is important to have this clip installed.
470 // The second pass that zeros the stencil buffer renders the rect maskSpaceIBounds so the first
471 // pass must not set values outside of this bounds or stencil values outside the rect won't be
473 GrDrawTarget::AutoClipRestore acr(fGpu, maskSpaceIBounds);
474 drawState->enableState(GrDrawState::kClip_StateBit);
476 GrAutoScratchTexture temp;
477 // walk through each clip element and perform its set op
478 for (ElementList::Iter iter = elements.headIter(); iter.get(); iter.next()) {
479 const Element* element = iter.get();
480 SkRegion::Op op = element->getOp();
481 bool invert = element->isInverseFilled();
483 if (invert || SkRegion::kIntersect_Op == op || SkRegion::kReverseDifference_Op == op) {
484 GrPathRenderer* pr = NULL;
485 bool useTemp = !this->canStencilAndDrawElement(result, element, &pr);
487 // This is the bounds of the clip element in the space of the alpha-mask. The temporary
488 // mask buffer can be substantially larger than the actually clip stack element. We
489 // touch the minimum number of pixels necessary and use decal mode to combine it with
491 SkIRect maskSpaceElementIBounds;
495 maskSpaceElementIBounds = maskSpaceIBounds;
497 SkRect elementBounds = element->getBounds();
498 elementBounds.offset(clipToMaskOffset);
499 elementBounds.roundOut(&maskSpaceElementIBounds);
502 this->getTemp(maskSpaceIBounds.fRight, maskSpaceIBounds.fBottom, &temp);
503 if (NULL == temp.texture()) {
507 dst = temp.texture();
508 // clear the temp target and set blend to replace
509 fGpu->clear(&maskSpaceElementIBounds,
510 invert ? 0xffffffff : 0x00000000,
512 dst->asRenderTarget());
513 setup_boolean_blendcoeffs(drawState, SkRegion::kReplace_Op);
516 // draw directly into the result with the stencil set to make the pixels affected
517 // by the clip shape be non-zero.
519 GR_STATIC_CONST_SAME_STENCIL(kStencilInElement,
526 drawState->setStencil(kStencilInElement);
527 setup_boolean_blendcoeffs(drawState, op);
530 drawState->setAlpha(invert ? 0x00 : 0xff);
532 if (!this->drawElement(dst, element, pr)) {
538 // Now draw into the accumulator using the real operation and the temp buffer as a
540 this->mergeMask(result,
544 maskSpaceElementIBounds);
546 // Draw to the exterior pixels (those with a zero stencil value).
547 drawState->setAlpha(invert ? 0xff : 0x00);
548 GR_STATIC_CONST_SAME_STENCIL(kDrawOutsideElement,
555 drawState->setStencil(kDrawOutsideElement);
556 fGpu->drawSimpleRect(clipSpaceIBounds);
557 drawState->disableStencil();
560 // all the remaining ops can just be directly draw into the accumulation buffer
561 drawState->setAlpha(0xff);
562 setup_boolean_blendcoeffs(drawState, op);
563 this->drawElement(result, element);
567 fCurrClipMaskType = kAlpha_ClipMaskType;
571 ////////////////////////////////////////////////////////////////////////////////
572 // Create a 1-bit clip mask in the stencil buffer. 'devClipBounds' are in device
573 // (as opposed to canvas) coordinates
574 bool GrClipMaskManager::createStencilClipMask(int32_t elementsGenID,
575 InitialState initialState,
576 const ElementList& elements,
577 const SkIRect& clipSpaceIBounds,
578 const SkIPoint& clipSpaceToStencilOffset) {
580 SkASSERT(kNone_ClipMaskType == fCurrClipMaskType);
582 GrDrawState* drawState = fGpu->drawState();
583 SkASSERT(drawState->isClipState());
585 GrRenderTarget* rt = drawState->getRenderTarget();
586 SkASSERT(NULL != rt);
588 // TODO: dynamically attach a SB when needed.
589 GrStencilBuffer* stencilBuffer = rt->getStencilBuffer();
590 if (NULL == stencilBuffer) {
594 if (stencilBuffer->mustRenderClip(elementsGenID, clipSpaceIBounds, clipSpaceToStencilOffset)) {
596 stencilBuffer->setLastClip(elementsGenID, clipSpaceIBounds, clipSpaceToStencilOffset);
598 // Set the matrix so that rendered clip elements are transformed from clip to stencil space.
599 SkVector translate = {
600 SkIntToScalar(clipSpaceToStencilOffset.fX),
601 SkIntToScalar(clipSpaceToStencilOffset.fY)
604 matrix.setTranslate(translate);
605 GrDrawTarget::AutoGeometryAndStatePush agasp(fGpu, GrDrawTarget::kReset_ASRInit, &matrix);
606 drawState = fGpu->drawState();
608 drawState->setRenderTarget(rt);
610 // We set the current clip to the bounds so that our recursive draws are scissored to them.
611 SkIRect stencilSpaceIBounds(clipSpaceIBounds);
612 stencilSpaceIBounds.offset(clipSpaceToStencilOffset);
613 GrDrawTarget::AutoClipRestore acr(fGpu, stencilSpaceIBounds);
614 drawState->enableState(GrDrawState::kClip_StateBit);
616 #if !VISUALIZE_COMPLEX_CLIP
617 drawState->enableState(GrDrawState::kNoColorWrites_StateBit);
620 int clipBit = stencilBuffer->bits();
621 SkASSERT((clipBit <= 16) && "Ganesh only handles 16b or smaller stencil buffers");
622 clipBit = (1 << (clipBit-1));
624 fGpu->clearStencilClip(stencilSpaceIBounds, kAllIn_InitialState == initialState);
626 // walk through each clip element and perform its set op
627 // with the existing clip.
628 for (ElementList::Iter iter(elements.headIter()); NULL != iter.get(); iter.next()) {
629 const Element* element = iter.get();
630 bool fillInverted = false;
631 // enabled at bottom of loop
632 drawState->disableState(GrGpu::kModifyStencilClip_StateBit);
633 // if the target is MSAA then we want MSAA enabled when the clip is soft
634 if (rt->isMultisampled()) {
635 drawState->setState(GrDrawState::kHWAntialias_StateBit, element->isAA());
638 // This will be used to determine whether the clip shape can be rendered into the
639 // stencil with arbitrary stencil settings.
640 GrPathRenderer::StencilSupport stencilSupport;
642 SkStrokeRec stroke(SkStrokeRec::kFill_InitStyle);
644 SkRegion::Op op = element->getOp();
646 GrPathRenderer* pr = NULL;
647 SkTCopyOnFirstWrite<SkPath> clipPath;
648 if (Element::kRect_Type == element->getType()) {
649 stencilSupport = GrPathRenderer::kNoRestriction_StencilSupport;
650 fillInverted = false;
652 SkASSERT(Element::kPath_Type == element->getType());
653 clipPath.init(element->getPath());
654 fillInverted = clipPath->isInverseFillType();
656 clipPath.writable()->toggleInverseFillType();
658 pr = this->getContext()->getPathRenderer(*clipPath,
662 GrPathRendererChain::kStencilOnly_DrawType,
670 GrStencilSettings stencilSettings[GrStencilSettings::kMaxStencilClipPasses];
672 bool canRenderDirectToStencil =
673 GrPathRenderer::kNoRestriction_StencilSupport == stencilSupport;
674 bool canDrawDirectToClip; // Given the renderer, the element,
675 // fill rule, and set operation can
676 // we render the element directly to
677 // stencil bit used for clipping.
678 canDrawDirectToClip = GrStencilSettings::GetClipPasses(op,
679 canRenderDirectToStencil,
685 // draw the element to the client stencil bits if necessary
686 if (!canDrawDirectToClip) {
687 GR_STATIC_CONST_SAME_STENCIL(gDrawToStencil,
695 if (Element::kRect_Type == element->getType()) {
696 *drawState->stencil() = gDrawToStencil;
697 fGpu->drawSimpleRect(element->getRect(), NULL);
699 SkASSERT(Element::kPath_Type == element->getType());
700 if (!clipPath->isEmpty()) {
701 if (canRenderDirectToStencil) {
702 *drawState->stencil() = gDrawToStencil;
703 pr->drawPath(*clipPath, stroke, fGpu, false);
705 pr->stencilPath(*clipPath, stroke, fGpu);
711 // now we modify the clip bit by rendering either the clip
712 // element directly or a bounding rect of the entire clip.
713 drawState->enableState(GrGpu::kModifyStencilClip_StateBit);
714 for (int p = 0; p < passes; ++p) {
715 *drawState->stencil() = stencilSettings[p];
716 if (canDrawDirectToClip) {
717 if (Element::kRect_Type == element->getType()) {
719 fGpu->drawSimpleRect(element->getRect(), NULL);
721 SkASSERT(Element::kPath_Type == element->getType());
723 pr->drawPath(*clipPath, stroke, fGpu, false);
727 // The view matrix is setup to do clip space -> stencil space translation, so
728 // draw rect in clip space.
729 fGpu->drawSimpleRect(SkRect::Make(clipSpaceIBounds), NULL);
734 // set this last because recursive draws may overwrite it back to kNone.
735 SkASSERT(kNone_ClipMaskType == fCurrClipMaskType);
736 fCurrClipMaskType = kStencil_ClipMaskType;
741 // mapping of clip-respecting stencil funcs to normal stencil funcs
742 // mapping depends on whether stencil-clipping is in effect.
743 static const GrStencilFunc
744 gSpecialToBasicStencilFunc[2][kClipStencilFuncCount] = {
745 {// Stencil-Clipping is DISABLED, we are effectively always inside the clip
747 kAlways_StencilFunc, // kAlwaysIfInClip_StencilFunc
748 kEqual_StencilFunc, // kEqualIfInClip_StencilFunc
749 kLess_StencilFunc, // kLessIfInClip_StencilFunc
750 kLEqual_StencilFunc, // kLEqualIfInClip_StencilFunc
751 // Special in the clip func that forces user's ref to be 0.
752 kNotEqual_StencilFunc, // kNonZeroIfInClip_StencilFunc
753 // make ref 0 and do normal nequal.
755 {// Stencil-Clipping is ENABLED
757 kEqual_StencilFunc, // kAlwaysIfInClip_StencilFunc
758 // eq stencil clip bit, mask
761 kEqual_StencilFunc, // kEqualIfInClip_StencilFunc
762 // add stencil bit to mask and ref
764 kLess_StencilFunc, // kLessIfInClip_StencilFunc
765 kLEqual_StencilFunc, // kLEqualIfInClip_StencilFunc
766 // for both of these we can add
767 // the clip bit to the mask and
768 // ref and compare as normal
769 // Special in the clip func that forces user's ref to be 0.
770 kLess_StencilFunc, // kNonZeroIfInClip_StencilFunc
771 // make ref have only the clip bit set
772 // and make comparison be less
773 // 10..0 < 1..user_bits..
778 // Sets the settings to clip against the stencil buffer clip while ignoring the
780 const GrStencilSettings& basic_apply_stencil_clip_settings() {
781 // stencil settings to use when clip is in stencil
782 GR_STATIC_CONST_SAME_STENCIL_STRUCT(gSettings,
785 kAlwaysIfInClip_StencilFunc,
789 return *GR_CONST_STENCIL_SETTINGS_PTR_FROM_STRUCT_PTR(&gSettings);
793 void GrClipMaskManager::setGpuStencil() {
794 // We make two copies of the StencilSettings here (except in the early
795 // exit scenario. One copy from draw state to the stack var. Then another
796 // from the stack var to the gpu. We could make this class hold a ptr to
797 // GrGpu's fStencilSettings and eliminate the stack copy here.
799 const GrDrawState& drawState = fGpu->getDrawState();
801 // use stencil for clipping if clipping is enabled and the clip
802 // has been written into the stencil.
803 GrClipMaskManager::StencilClipMode clipMode;
804 if (this->isClipInStencil() && drawState.isClipState()) {
805 clipMode = GrClipMaskManager::kRespectClip_StencilClipMode;
806 // We can't be modifying the clip and respecting it at the same time.
807 SkASSERT(!drawState.isStateFlagEnabled(
808 GrGpu::kModifyStencilClip_StateBit));
809 } else if (drawState.isStateFlagEnabled(
810 GrGpu::kModifyStencilClip_StateBit)) {
811 clipMode = GrClipMaskManager::kModifyClip_StencilClipMode;
813 clipMode = GrClipMaskManager::kIgnoreClip_StencilClipMode;
816 GrStencilSettings settings;
817 // The GrGpu client may not be using the stencil buffer but we may need to
818 // enable it in order to respect a stencil clip.
819 if (drawState.getStencil().isDisabled()) {
820 if (GrClipMaskManager::kRespectClip_StencilClipMode == clipMode) {
821 settings = basic_apply_stencil_clip_settings();
823 fGpu->disableStencil();
827 settings = drawState.getStencil();
830 // TODO: dynamically attach a stencil buffer
832 GrStencilBuffer* stencilBuffer =
833 drawState.getRenderTarget()->getStencilBuffer();
834 if (NULL != stencilBuffer) {
835 stencilBits = stencilBuffer->bits();
838 SkASSERT(fGpu->caps()->stencilWrapOpsSupport() || !settings.usesWrapOp());
839 SkASSERT(fGpu->caps()->twoSidedStencilSupport() || !settings.isTwoSided());
840 this->adjustStencilParams(&settings, clipMode, stencilBits);
841 fGpu->setStencilSettings(settings);
844 void GrClipMaskManager::adjustStencilParams(GrStencilSettings* settings,
845 StencilClipMode mode,
847 SkASSERT(stencilBitCnt > 0);
849 if (kModifyClip_StencilClipMode == mode) {
850 // We assume that this clip manager itself is drawing to the GrGpu and
851 // has already setup the correct values.
855 unsigned int clipBit = (1 << (stencilBitCnt - 1));
856 unsigned int userBits = clipBit - 1;
858 GrStencilSettings::Face face = GrStencilSettings::kFront_Face;
859 bool twoSided = fGpu->caps()->twoSidedStencilSupport();
861 bool finished = false;
863 GrStencilFunc func = settings->func(face);
864 uint16_t writeMask = settings->writeMask(face);
865 uint16_t funcMask = settings->funcMask(face);
866 uint16_t funcRef = settings->funcRef(face);
868 SkASSERT((unsigned) func < kStencilFuncCount);
870 writeMask &= userBits;
872 if (func >= kBasicStencilFuncCount) {
873 int respectClip = kRespectClip_StencilClipMode == mode;
875 // The GrGpu class should have checked this
876 SkASSERT(this->isClipInStencil());
878 case kAlwaysIfInClip_StencilFunc:
882 case kEqualIfInClip_StencilFunc:
883 case kLessIfInClip_StencilFunc:
884 case kLEqualIfInClip_StencilFunc:
885 funcMask = (funcMask & userBits) | clipBit;
886 funcRef = (funcRef & userBits) | clipBit;
888 case kNonZeroIfInClip_StencilFunc:
889 funcMask = (funcMask & userBits) | clipBit;
893 GrCrash("Unknown stencil func");
896 funcMask &= userBits;
899 const GrStencilFunc* table =
900 gSpecialToBasicStencilFunc[respectClip];
901 func = table[func - kBasicStencilFuncCount];
902 SkASSERT(func >= 0 && func < kBasicStencilFuncCount);
904 funcMask &= userBits;
908 settings->setFunc(face, func);
909 settings->setWriteMask(face, writeMask);
910 settings->setFuncMask(face, funcMask);
911 settings->setFuncRef(face, funcRef);
913 if (GrStencilSettings::kFront_Face == face) {
914 face = GrStencilSettings::kBack_Face;
915 finished = !twoSided;
921 settings->copyFrontSettingsToBack();
925 ////////////////////////////////////////////////////////////////////////////////
926 GrTexture* GrClipMaskManager::createSoftwareClipMask(int32_t elementsGenID,
927 GrReducedClip::InitialState initialState,
928 const GrReducedClip::ElementList& elements,
929 const SkIRect& clipSpaceIBounds) {
930 SkASSERT(kNone_ClipMaskType == fCurrClipMaskType);
933 if (this->getMaskTexture(elementsGenID, clipSpaceIBounds, &result, true)) {
937 if (NULL == result) {
942 // The mask texture may be larger than necessary. We round out the clip space bounds and pin
943 // the top left corner of the resulting rect to the top left of the texture.
944 SkIRect maskSpaceIBounds = SkIRect::MakeWH(clipSpaceIBounds.width(), clipSpaceIBounds.height());
946 GrSWMaskHelper helper(this->getContext());
949 matrix.setTranslate(SkIntToScalar(-clipSpaceIBounds.fLeft),
950 SkIntToScalar(-clipSpaceIBounds.fTop));
951 helper.init(maskSpaceIBounds, &matrix);
953 helper.clear(kAllIn_InitialState == initialState ? 0xFF : 0x00);
955 SkStrokeRec stroke(SkStrokeRec::kFill_InitStyle);
957 for (ElementList::Iter iter(elements.headIter()) ; NULL != iter.get(); iter.next()) {
959 const Element* element = iter.get();
960 SkRegion::Op op = element->getOp();
962 if (SkRegion::kIntersect_Op == op || SkRegion::kReverseDifference_Op == op) {
963 // Intersect and reverse difference require modifying pixels outside of the geometry
964 // that is being "drawn". In both cases we erase all the pixels outside of the geometry
965 // but leave the pixels inside the geometry alone. For reverse difference we invert all
966 // the pixels before clearing the ones outside the geometry.
967 if (SkRegion::kReverseDifference_Op == op) {
968 SkRect temp = SkRect::Make(clipSpaceIBounds);
969 // invert the entire scene
970 helper.draw(temp, SkRegion::kXOR_Op, false, 0xFF);
973 if (Element::kRect_Type == element->getType()) {
974 // convert the rect to a path so we can invert the fill
976 temp.addRect(element->getRect());
977 temp.setFillType(SkPath::kInverseEvenOdd_FillType);
979 helper.draw(temp, stroke, SkRegion::kReplace_Op,
983 SkASSERT(Element::kPath_Type == element->getType());
984 SkPath clipPath = element->getPath();
985 clipPath.toggleInverseFillType();
986 helper.draw(clipPath, stroke,
987 SkRegion::kReplace_Op,
995 // The other ops (union, xor, diff) only affect pixels inside
996 // the geometry so they can just be drawn normally
997 if (Element::kRect_Type == element->getType()) {
998 helper.draw(element->getRect(), op, element->isAA(), 0xFF);
1000 SkASSERT(Element::kPath_Type == element->getType());
1001 helper.draw(element->getPath(), stroke, op, element->isAA(), 0xFF);
1005 helper.toTexture(result);
1007 fCurrClipMaskType = kAlpha_ClipMaskType;
1011 ////////////////////////////////////////////////////////////////////////////////
1012 void GrClipMaskManager::releaseResources() {
1013 fAACache.releaseResources();
1016 void GrClipMaskManager::setGpu(GrGpu* gpu) {
1018 fAACache.setContext(gpu->getContext());
1021 void GrClipMaskManager::adjustPathStencilParams(GrStencilSettings* settings) {
1022 const GrDrawState& drawState = fGpu->getDrawState();
1023 GrClipMaskManager::StencilClipMode clipMode;
1024 if (this->isClipInStencil() && drawState.isClipState()) {
1025 clipMode = GrClipMaskManager::kRespectClip_StencilClipMode;
1026 // We can't be modifying the clip and respecting it at the same time.
1027 SkASSERT(!drawState.isStateFlagEnabled(
1028 GrGpu::kModifyStencilClip_StateBit));
1029 } else if (drawState.isStateFlagEnabled(
1030 GrGpu::kModifyStencilClip_StateBit)) {
1031 clipMode = GrClipMaskManager::kModifyClip_StencilClipMode;
1033 clipMode = GrClipMaskManager::kIgnoreClip_StencilClipMode;
1036 // TODO: dynamically attach a stencil buffer
1037 int stencilBits = 0;
1038 GrStencilBuffer* stencilBuffer =
1039 drawState.getRenderTarget()->getStencilBuffer();
1040 if (NULL != stencilBuffer) {
1041 stencilBits = stencilBuffer->bits();
1042 this->adjustStencilParams(settings, clipMode, stencilBits);