1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
|
/*
* Copyright 2012 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "GrClipMaskManager.h"
#include "GrCaps.h"
#include "GrDrawingManager.h"
#include "GrDrawContextPriv.h"
#include "GrDrawTarget.h"
#include "GrGpuResourcePriv.h"
#include "GrPaint.h"
#include "GrPathRenderer.h"
#include "GrRenderTarget.h"
#include "GrRenderTargetPriv.h"
#include "GrResourceProvider.h"
#include "GrStencilAttachment.h"
#include "GrSWMaskHelper.h"
#include "SkRasterClip.h"
#include "SkTLazy.h"
#include "batches/GrRectBatchFactory.h"
#include "effects/GrConvexPolyEffect.h"
#include "effects/GrPorterDuffXferProcessor.h"
#include "effects/GrRRectEffect.h"
#include "effects/GrTextureDomain.h"
typedef SkClipStack::Element Element;
////////////////////////////////////////////////////////////////////////////////
// set up the draw state to enable the aa clipping mask. Besides setting up the
// stage matrix this also alters the vertex layout
static const GrFragmentProcessor* create_fp_for_mask(GrTexture* result, const SkIRect &devBound) {
SkMatrix mat;
// We use device coords to compute the texture coordinates. We set our matrix to be a
// translation to the devBound, and then a scaling matrix to normalized coords.
mat.setIDiv(result->width(), result->height());
mat.preTranslate(SkIntToScalar(-devBound.fLeft),
SkIntToScalar(-devBound.fTop));
SkIRect domainTexels = SkIRect::MakeWH(devBound.width(), devBound.height());
return GrTextureDomainEffect::Create(result,
mat,
GrTextureDomain::MakeTexelDomain(result, domainTexels),
GrTextureDomain::kDecal_Mode,
GrTextureParams::kNone_FilterMode,
kDevice_GrCoordSet);
}
static void draw_non_aa_rect(GrDrawTarget* drawTarget,
const GrPipelineBuilder& pipelineBuilder,
GrColor color,
const SkMatrix& viewMatrix,
const SkRect& rect) {
SkAutoTUnref<GrDrawBatch> batch(GrRectBatchFactory::CreateNonAAFill(color, viewMatrix, rect,
nullptr, nullptr));
drawTarget->drawBatch(pipelineBuilder, batch);
}
// Does the path in 'element' require SW rendering? If so, return true (and,
// optionally, set 'prOut' to NULL. If not, return false (and, optionally, set
// 'prOut' to the non-SW path renderer that will do the job).
bool GrClipMaskManager::PathNeedsSWRenderer(GrContext* context,
bool isStencilDisabled,
const GrRenderTarget* rt,
const SkMatrix& viewMatrix,
const Element* element,
GrPathRenderer** prOut,
bool needsStencil) {
if (Element::kRect_Type == element->getType()) {
// rects can always be drawn directly w/o using the software path
// TODO: skip rrects once we're drawing them directly.
if (prOut) {
*prOut = nullptr;
}
return false;
} else {
// We shouldn't get here with an empty clip element.
SkASSERT(Element::kEmpty_Type != element->getType());
// the gpu alpha mask will draw the inverse paths as non-inverse to a temp buffer
SkPath path;
element->asPath(&path);
if (path.isInverseFillType()) {
path.toggleInverseFillType();
}
GrStrokeInfo stroke(SkStrokeRec::kFill_InitStyle);
GrPathRendererChain::DrawType type;
if (needsStencil) {
type = element->isAA()
? GrPathRendererChain::kStencilAndColorAntiAlias_DrawType
: GrPathRendererChain::kStencilAndColor_DrawType;
} else {
type = element->isAA()
? GrPathRendererChain::kColorAntiAlias_DrawType
: GrPathRendererChain::kColor_DrawType;
}
GrPathRenderer::CanDrawPathArgs canDrawArgs;
canDrawArgs.fShaderCaps = context->caps()->shaderCaps();
canDrawArgs.fViewMatrix = &viewMatrix;
canDrawArgs.fPath = &path;
canDrawArgs.fStroke = &stroke;
canDrawArgs.fAntiAlias = element->isAA();
canDrawArgs.fIsStencilDisabled = isStencilDisabled;
canDrawArgs.fIsStencilBufferMSAA = rt->isStencilBufferMultisampled();
// the 'false' parameter disallows use of the SW path renderer
GrPathRenderer* pr = context->drawingManager()->getPathRenderer(canDrawArgs, false, type);
if (prOut) {
*prOut = pr;
}
return SkToBool(!pr);
}
}
// Determines whether it is possible to draw the element to both the stencil buffer and the
// alpha mask simultaneously. If so and the element is a path a compatible path renderer is
// also returned.
GrPathRenderer* GrClipMaskManager::GetPathRenderer(GrContext* context,
GrTexture* texture,
const SkMatrix& viewMatrix,
const SkClipStack::Element* element) {
GrPathRenderer* pr;
static const bool kNeedsStencil = true;
static const bool kStencilIsDisabled = true;
PathNeedsSWRenderer(context,
kStencilIsDisabled,
texture->asRenderTarget(),
viewMatrix,
element,
&pr,
kNeedsStencil);
return pr;
}
GrClipMaskManager::GrClipMaskManager(GrDrawTarget* drawTarget, bool debugClipBatchToBounds)
: fDrawTarget(drawTarget)
, fClipMode(kIgnoreClip_StencilClipMode)
, fDebugClipBatchToBounds(debugClipBatchToBounds) {
}
GrContext* GrClipMaskManager::getContext() {
return fDrawTarget->cmmAccess().context();
}
const GrCaps* GrClipMaskManager::caps() const {
return fDrawTarget->caps();
}
GrResourceProvider* GrClipMaskManager::resourceProvider() {
return fDrawTarget->cmmAccess().resourceProvider();
}
/*
* This method traverses the clip stack to see if the GrSoftwarePathRenderer
* will be used on any element. If so, it returns true to indicate that the
* entire clip should be rendered in SW and then uploaded en masse to the gpu.
*/
bool GrClipMaskManager::UseSWOnlyPath(GrContext* context,
const GrPipelineBuilder& pipelineBuilder,
const GrRenderTarget* rt,
const SkVector& clipToMaskOffset,
const GrReducedClip::ElementList& elements) {
// TODO: generalize this function so that when
// a clip gets complex enough it can just be done in SW regardless
// of whether it would invoke the GrSoftwarePathRenderer.
// Set the matrix so that rendered clip elements are transformed to mask space from clip
// space.
const SkMatrix translate = SkMatrix::MakeTrans(clipToMaskOffset.fX, clipToMaskOffset.fY);
for (GrReducedClip::ElementList::Iter iter(elements.headIter()); iter.get(); iter.next()) {
const Element* element = iter.get();
SkRegion::Op op = element->getOp();
bool invert = element->isInverseFilled();
bool needsStencil = invert ||
SkRegion::kIntersect_Op == op || SkRegion::kReverseDifference_Op == op;
if (PathNeedsSWRenderer(context, pipelineBuilder.getStencil().isDisabled(),
rt, translate, element, nullptr, needsStencil)) {
return true;
}
}
return false;
}
bool GrClipMaskManager::getAnalyticClipProcessor(const GrReducedClip::ElementList& elements,
bool abortIfAA,
SkVector& clipToRTOffset,
const SkRect* drawBounds,
const GrFragmentProcessor** resultFP) {
SkRect boundsInClipSpace;
if (drawBounds) {
boundsInClipSpace = *drawBounds;
boundsInClipSpace.offset(-clipToRTOffset.fX, -clipToRTOffset.fY);
}
SkASSERT(elements.count() <= kMaxAnalyticElements);
const GrFragmentProcessor* fps[kMaxAnalyticElements];
for (int i = 0; i < kMaxAnalyticElements; ++i) {
fps[i] = nullptr;
}
int fpCnt = 0;
GrReducedClip::ElementList::Iter iter(elements);
bool failed = false;
while (iter.get()) {
SkRegion::Op op = iter.get()->getOp();
bool invert;
bool skip = false;
switch (op) {
case SkRegion::kReplace_Op:
SkASSERT(iter.get() == elements.head());
// Fallthrough, handled same as intersect.
case SkRegion::kIntersect_Op:
invert = false;
if (drawBounds && iter.get()->contains(boundsInClipSpace)) {
skip = true;
}
break;
case SkRegion::kDifference_Op:
invert = true;
// We don't currently have a cheap test for whether a rect is fully outside an
// element's primitive, so don't attempt to set skip.
break;
default:
failed = true;
break;
}
if (failed) {
break;
}
if (!skip) {
GrPrimitiveEdgeType edgeType;
if (iter.get()->isAA()) {
if (abortIfAA) {
failed = true;
break;
}
edgeType =
invert ? kInverseFillAA_GrProcessorEdgeType : kFillAA_GrProcessorEdgeType;
} else {
edgeType =
invert ? kInverseFillBW_GrProcessorEdgeType : kFillBW_GrProcessorEdgeType;
}
switch (iter.get()->getType()) {
case SkClipStack::Element::kPath_Type:
fps[fpCnt] = GrConvexPolyEffect::Create(edgeType, iter.get()->getPath(),
&clipToRTOffset);
break;
case SkClipStack::Element::kRRect_Type: {
SkRRect rrect = iter.get()->getRRect();
rrect.offset(clipToRTOffset.fX, clipToRTOffset.fY);
fps[fpCnt] = GrRRectEffect::Create(edgeType, rrect);
break;
}
case SkClipStack::Element::kRect_Type: {
SkRect rect = iter.get()->getRect();
rect.offset(clipToRTOffset.fX, clipToRTOffset.fY);
fps[fpCnt] = GrConvexPolyEffect::Create(edgeType, rect);
break;
}
default:
break;
}
if (!fps[fpCnt]) {
failed = true;
break;
}
fpCnt++;
}
iter.next();
}
*resultFP = nullptr;
if (!failed && fpCnt) {
*resultFP = GrFragmentProcessor::RunInSeries(fps, fpCnt);
}
for (int i = 0; i < fpCnt; ++i) {
fps[i]->unref();
}
return !failed;
}
static void add_rect_to_clip(const GrClip& clip, const SkRect& devRect, GrClip* out) {
switch (clip.clipType()) {
case GrClip::kClipStack_ClipType: {
SkClipStack* stack = new SkClipStack;
*stack = *clip.clipStack();
// The stack is actually in clip space not device space.
SkRect clipRect = devRect;
SkPoint origin = { SkIntToScalar(clip.origin().fX), SkIntToScalar(clip.origin().fY) };
clipRect.offset(origin);
SkIRect iclipRect;
clipRect.roundOut(&iclipRect);
clipRect = SkRect::Make(iclipRect);
stack->clipDevRect(clipRect, SkRegion::kIntersect_Op, false);
out->setClipStack(stack, &clip.origin());
break;
}
case GrClip::kWideOpen_ClipType:
*out = GrClip(devRect);
break;
case GrClip::kIRect_ClipType: {
SkIRect intersect;
devRect.roundOut(&intersect);
if (intersect.intersect(clip.irect())) {
*out = GrClip(intersect);
} else {
*out = clip;
}
break;
}
}
}
bool GrClipMaskManager::setupScissorClip(const GrPipelineBuilder& pipelineBuilder,
GrPipelineBuilder::AutoRestoreStencil* ars,
const SkIRect& clipScissor,
const SkRect* devBounds,
GrAppliedClip* out) {
if (kRespectClip_StencilClipMode == fClipMode) {
fClipMode = kIgnoreClip_StencilClipMode;
}
GrRenderTarget* rt = pipelineBuilder.getRenderTarget();
SkIRect clipSpaceRTIBounds = SkIRect::MakeWH(rt->width(), rt->height());
SkIRect devBoundsScissor;
const SkIRect* scissor = &clipScissor;
bool doDevBoundsClip = fDebugClipBatchToBounds && devBounds;
if (doDevBoundsClip) {
devBounds->roundOut(&devBoundsScissor);
if (devBoundsScissor.intersect(clipScissor)) {
scissor = &devBoundsScissor;
}
}
if (scissor->contains(clipSpaceRTIBounds)) {
// This counts as wide open
this->setPipelineBuilderStencil(pipelineBuilder, ars);
return true;
}
if (clipSpaceRTIBounds.intersect(*scissor)) {
out->fScissorState.set(clipSpaceRTIBounds);
this->setPipelineBuilderStencil(pipelineBuilder, ars);
return true;
}
return false;
}
////////////////////////////////////////////////////////////////////////////////
// sort out what kind of clip mask needs to be created: alpha, stencil,
// scissor, or entirely software
bool GrClipMaskManager::setupClipping(const GrPipelineBuilder& pipelineBuilder,
GrPipelineBuilder::AutoRestoreStencil* ars,
const SkRect* devBounds,
GrAppliedClip* out) {
if (kRespectClip_StencilClipMode == fClipMode) {
fClipMode = kIgnoreClip_StencilClipMode;
}
GrReducedClip::ElementList elements;
int32_t genID = 0;
GrReducedClip::InitialState initialState = GrReducedClip::kAllIn_InitialState;
SkIRect clipSpaceIBounds;
bool requiresAA = false;
GrRenderTarget* rt = pipelineBuilder.getRenderTarget();
// GrDrawTarget should have filtered this for us
SkASSERT(rt);
SkIRect clipSpaceRTIBounds = SkIRect::MakeWH(rt->width(), rt->height());
GrClip devBoundsClip;
bool doDevBoundsClip = fDebugClipBatchToBounds && devBounds;
if (doDevBoundsClip) {
add_rect_to_clip(pipelineBuilder.clip(), *devBounds, &devBoundsClip);
}
const GrClip& clip = doDevBoundsClip ? devBoundsClip : pipelineBuilder.clip();
if (clip.isWideOpen(clipSpaceRTIBounds)) {
this->setPipelineBuilderStencil(pipelineBuilder, ars);
return true;
}
// The clip mask manager always draws with a single IRect so we special case that logic here
// Image filters just use a rect, so we also special case that logic
switch (clip.clipType()) {
case GrClip::kWideOpen_ClipType:
SkFAIL("Should have caught this with clip.isWideOpen()");
return true;
case GrClip::kIRect_ClipType: {
SkIRect scissor = clip.irect();
if (scissor.intersect(clipSpaceRTIBounds)) {
out->fScissorState.set(scissor);
this->setPipelineBuilderStencil(pipelineBuilder, ars);
return true;
}
return false;
}
case GrClip::kClipStack_ClipType: {
clipSpaceRTIBounds.offset(clip.origin());
SkIRect clipSpaceReduceQueryBounds;
#define DISABLE_DEV_BOUNDS_FOR_CLIP_REDUCTION 0
if (devBounds && !DISABLE_DEV_BOUNDS_FOR_CLIP_REDUCTION) {
SkIRect devIBounds = devBounds->roundOut();
devIBounds.offset(clip.origin());
if (!clipSpaceReduceQueryBounds.intersect(clipSpaceRTIBounds, devIBounds)) {
return false;
}
} else {
clipSpaceReduceQueryBounds = clipSpaceRTIBounds;
}
GrReducedClip::ReduceClipStack(*clip.clipStack(),
clipSpaceReduceQueryBounds,
&elements,
&genID,
&initialState,
&clipSpaceIBounds,
&requiresAA);
if (elements.isEmpty()) {
if (GrReducedClip::kAllIn_InitialState == initialState) {
if (clipSpaceIBounds == clipSpaceRTIBounds) {
this->setPipelineBuilderStencil(pipelineBuilder, ars);
return true;
}
} else {
return false;
}
}
} break;
}
// An element count of 4 was chosen because of the common pattern in Blink of:
// isect RR
// diff RR
// isect convex_poly
// isect convex_poly
// when drawing rounded div borders. This could probably be tuned based on a
// configuration's relative costs of switching RTs to generate a mask vs
// longer shaders.
if (elements.count() <= kMaxAnalyticElements) {
SkVector clipToRTOffset = { SkIntToScalar(-clip.origin().fX),
SkIntToScalar(-clip.origin().fY) };
// When there are multiple samples we want to do per-sample clipping, not compute a
// fractional pixel coverage.
bool disallowAnalyticAA = rt->isUnifiedMultisampled() || pipelineBuilder.hasMixedSamples();
const GrFragmentProcessor* clipFP = nullptr;
if (elements.isEmpty() ||
(requiresAA &&
this->getAnalyticClipProcessor(elements, disallowAnalyticAA, clipToRTOffset, devBounds,
&clipFP))) {
SkIRect scissorSpaceIBounds(clipSpaceIBounds);
scissorSpaceIBounds.offset(-clip.origin());
if (nullptr == devBounds ||
!SkRect::Make(scissorSpaceIBounds).contains(*devBounds)) {
out->fScissorState.set(scissorSpaceIBounds);
}
this->setPipelineBuilderStencil(pipelineBuilder, ars);
out->fClipCoverageFP.reset(clipFP);
return true;
}
}
// If the stencil buffer is multisampled we can use it to do everything.
if (!rt->isStencilBufferMultisampled() && requiresAA) {
SkAutoTUnref<GrTexture> result;
// The top-left of the mask corresponds to the top-left corner of the bounds.
SkVector clipToMaskOffset = {
SkIntToScalar(-clipSpaceIBounds.fLeft),
SkIntToScalar(-clipSpaceIBounds.fTop)
};
if (UseSWOnlyPath(this->getContext(), pipelineBuilder, rt, clipToMaskOffset, elements)) {
// The clip geometry is complex enough that it will be more efficient to create it
// entirely in software
result.reset(CreateSoftwareClipMask(this->getContext(),
genID,
initialState,
elements,
clipToMaskOffset,
clipSpaceIBounds));
} else {
result.reset(CreateAlphaClipMask(this->getContext(),
genID,
initialState,
elements,
clipToMaskOffset,
clipSpaceIBounds));
// If createAlphaClipMask fails it means UseSWOnlyPath has a bug
SkASSERT(result);
}
if (result) {
// The mask's top left coord should be pinned to the rounded-out top left corner of
// clipSpace bounds. We determine the mask's position WRT to the render target here.
SkIRect rtSpaceMaskBounds = clipSpaceIBounds;
rtSpaceMaskBounds.offset(-clip.origin());
out->fClipCoverageFP.reset(create_fp_for_mask(result, rtSpaceMaskBounds));
this->setPipelineBuilderStencil(pipelineBuilder, ars);
return true;
}
// if alpha clip mask creation fails fall through to the non-AA code paths
}
// use the stencil clip if we can't represent the clip as a rectangle.
SkIPoint clipSpaceToStencilSpaceOffset = -clip.origin();
this->createStencilClipMask(rt,
genID,
initialState,
elements,
clipSpaceIBounds,
clipSpaceToStencilSpaceOffset);
// This must occur after createStencilClipMask. That function may change the scissor. Also, it
// only guarantees that the stencil mask is correct within the bounds it was passed, so we must
// use both stencil and scissor test to the bounds for the final draw.
SkIRect scissorSpaceIBounds(clipSpaceIBounds);
scissorSpaceIBounds.offset(clipSpaceToStencilSpaceOffset);
out->fScissorState.set(scissorSpaceIBounds);
this->setPipelineBuilderStencil(pipelineBuilder, ars);
return true;
}
static bool stencil_element(GrDrawContext* dc,
const SkIRect* scissorRect,
const GrStencilSettings& ss,
const SkMatrix& viewMatrix,
const SkClipStack::Element* element) {
// TODO: Draw rrects directly here.
switch (element->getType()) {
case Element::kEmpty_Type:
SkDEBUGFAIL("Should never get here with an empty element.");
break;
case Element::kRect_Type:
return dc->drawContextPriv().drawAndStencilRect(scissorRect, ss,
element->getOp(),
element->isInverseFilled(),
element->isAA(),
viewMatrix, element->getRect());
break;
default: {
SkPath path;
element->asPath(&path);
if (path.isInverseFillType()) {
path.toggleInverseFillType();
}
return dc->drawContextPriv().drawAndStencilPath(scissorRect, ss,
element->getOp(),
element->isInverseFilled(),
element->isAA(), viewMatrix, path);
break;
}
}
return false;
}
static void draw_element(GrDrawContext* dc,
const GrClip& clip, // TODO: can this just always be WideOpen?
const GrPaint &paint,
const SkMatrix& viewMatrix,
const SkClipStack::Element* element) {
// TODO: Draw rrects directly here.
switch (element->getType()) {
case Element::kEmpty_Type:
SkDEBUGFAIL("Should never get here with an empty element.");
break;
case Element::kRect_Type:
dc->drawRect(clip, paint, viewMatrix, element->getRect());
break;
default: {
SkPath path;
element->asPath(&path);
if (path.isInverseFillType()) {
path.toggleInverseFillType();
}
dc->drawPath(clip, paint, viewMatrix, path, GrStrokeInfo::FillInfo());
break;
}
}
}
////////////////////////////////////////////////////////////////////////////////
// Create a 8-bit clip mask in alpha
static void GetClipMaskKey(int32_t clipGenID, const SkIRect& bounds, GrUniqueKey* key) {
static const GrUniqueKey::Domain kDomain = GrUniqueKey::GenerateDomain();
GrUniqueKey::Builder builder(key, kDomain, 3);
builder[0] = clipGenID;
builder[1] = SkToU16(bounds.fLeft) | (SkToU16(bounds.fRight) << 16);
builder[2] = SkToU16(bounds.fTop) | (SkToU16(bounds.fBottom) << 16);
}
GrTexture* GrClipMaskManager::CreateAlphaClipMask(GrContext* context,
int32_t elementsGenID,
GrReducedClip::InitialState initialState,
const GrReducedClip::ElementList& elements,
const SkVector& clipToMaskOffset,
const SkIRect& clipSpaceIBounds) {
GrResourceProvider* resourceProvider = context->resourceProvider();
GrUniqueKey key;
GetClipMaskKey(elementsGenID, clipSpaceIBounds, &key);
if (GrTexture* texture = resourceProvider->findAndRefTextureByUniqueKey(key)) {
return texture;
}
// There's no texture in the cache. Let's try to allocate it then.
GrSurfaceDesc desc;
desc.fWidth = clipSpaceIBounds.width();
desc.fHeight = clipSpaceIBounds.height();
desc.fFlags = kRenderTarget_GrSurfaceFlag;
if (context->caps()->isConfigRenderable(kAlpha_8_GrPixelConfig, false)) {
desc.fConfig = kAlpha_8_GrPixelConfig;
} else {
desc.fConfig = kRGBA_8888_GrPixelConfig;
}
SkAutoTUnref<GrTexture> texture(resourceProvider->createApproxTexture(desc, 0));
if (!texture) {
return nullptr;
}
texture->resourcePriv().setUniqueKey(key);
sk_sp<GrDrawContext> dc(context->drawContext(sk_ref_sp(texture->asRenderTarget())));
if (!dc) {
return nullptr;
}
// The texture may be larger than necessary, this rect represents the part of the texture
// we populate with a rasterization of the clip.
SkIRect maskSpaceIBounds = SkIRect::MakeWH(clipSpaceIBounds.width(), clipSpaceIBounds.height());
// The scratch texture that we are drawing into can be substantially larger than the mask. Only
// clear the part that we care about.
dc->clear(&maskSpaceIBounds,
GrReducedClip::kAllIn_InitialState == initialState ? 0xffffffff : 0x00000000,
true);
// Set the matrix so that rendered clip elements are transformed to mask space from clip
// space.
const SkMatrix translate = SkMatrix::MakeTrans(clipToMaskOffset.fX, clipToMaskOffset.fY);
// It is important that we use maskSpaceIBounds as the stencil rect in the below loop.
// The second pass that zeros the stencil buffer renders the rect maskSpaceIBounds so the first
// pass must not set values outside of this bounds or stencil values outside the rect won't be
// cleared.
// walk through each clip element and perform its set op
for (GrReducedClip::ElementList::Iter iter = elements.headIter(); iter.get(); iter.next()) {
const Element* element = iter.get();
SkRegion::Op op = element->getOp();
bool invert = element->isInverseFilled();
if (invert || SkRegion::kIntersect_Op == op || SkRegion::kReverseDifference_Op == op) {
#ifdef SK_DEBUG
GrPathRenderer* pr = GetPathRenderer(context,
texture, translate, element);
if (Element::kRect_Type != element->getType() && !pr) {
// UseSWOnlyPath should now filter out all cases where gpu-side mask merging would
// be performed (i.e., pr would be NULL for a non-rect path).
// See https://bug.skia.org/4519 for rationale and details.
SkASSERT(0);
}
#endif
// draw directly into the result with the stencil set to make the pixels affected
// by the clip shape be non-zero.
GR_STATIC_CONST_SAME_STENCIL(kStencilInElement,
kReplace_StencilOp,
kReplace_StencilOp,
kAlways_StencilFunc,
0xffff,
0xffff,
0xffff)
if (!stencil_element(dc.get(), &maskSpaceIBounds, kStencilInElement,
translate, element)) {
texture->resourcePriv().removeUniqueKey();
return nullptr;
}
// Draw to the exterior pixels (those with a zero stencil value).
GR_STATIC_CONST_SAME_STENCIL(kDrawOutsideElement,
kZero_StencilOp,
kZero_StencilOp,
kEqual_StencilFunc,
0xffff,
0x0000,
0xffff);
if (!dc->drawContextPriv().drawAndStencilRect(&maskSpaceIBounds, kDrawOutsideElement,
op, !invert, false,
translate,
SkRect::Make(clipSpaceIBounds))) {
texture->resourcePriv().removeUniqueKey();
return nullptr;
}
} else {
// all the remaining ops can just be directly draw into the accumulation buffer
GrPaint paint;
paint.setAntiAlias(element->isAA());
paint.setCoverageSetOpXPFactory(op, false);
draw_element(dc.get(), GrClip::WideOpen(), paint, translate, element);
}
}
return texture.release();
}
////////////////////////////////////////////////////////////////////////////////
// Create a 1-bit clip mask in the stencil buffer. 'devClipBounds' are in device
// (as opposed to canvas) coordinates
bool GrClipMaskManager::createStencilClipMask(GrRenderTarget* rt,
int32_t elementsGenID,
GrReducedClip::InitialState initialState,
const GrReducedClip::ElementList& elements,
const SkIRect& clipSpaceIBounds,
const SkIPoint& clipSpaceToStencilOffset) {
SkASSERT(rt);
GrStencilAttachment* stencilAttachment = this->resourceProvider()->attachStencilAttachment(rt);
if (nullptr == stencilAttachment) {
return false;
}
if (stencilAttachment->mustRenderClip(elementsGenID, clipSpaceIBounds, clipSpaceToStencilOffset)) {
stencilAttachment->setLastClip(elementsGenID, clipSpaceIBounds, clipSpaceToStencilOffset);
// Set the matrix so that rendered clip elements are transformed from clip to stencil space.
SkVector translate = {
SkIntToScalar(clipSpaceToStencilOffset.fX),
SkIntToScalar(clipSpaceToStencilOffset.fY)
};
SkMatrix viewMatrix;
viewMatrix.setTranslate(translate);
// We set the current clip to the bounds so that our recursive draws are scissored to them.
SkIRect stencilSpaceIBounds(clipSpaceIBounds);
stencilSpaceIBounds.offset(clipSpaceToStencilOffset);
GrClip clip(stencilSpaceIBounds);
int clipBit = stencilAttachment->bits();
SkASSERT((clipBit <= 16) && "Ganesh only handles 16b or smaller stencil buffers");
clipBit = (1 << (clipBit-1));
fDrawTarget->cmmAccess().clearStencilClip(stencilSpaceIBounds,
GrReducedClip::kAllIn_InitialState == initialState, rt);
// walk through each clip element and perform its set op
// with the existing clip.
for (GrReducedClip::ElementList::Iter iter(elements.headIter()); iter.get(); iter.next()) {
const Element* element = iter.get();
GrPipelineBuilder pipelineBuilder;
pipelineBuilder.setClip(clip);
pipelineBuilder.setRenderTarget(rt);
pipelineBuilder.setDisableColorXPFactory();
// if the target is MSAA then we want MSAA enabled when the clip is soft
if (rt->isStencilBufferMultisampled()) {
pipelineBuilder.setState(GrPipelineBuilder::kHWAntialias_Flag, element->isAA());
}
bool fillInverted = false;
// enabled at bottom of loop
fClipMode = kIgnoreClip_StencilClipMode;
// This will be used to determine whether the clip shape can be rendered into the
// stencil with arbitrary stencil settings.
GrPathRenderer::StencilSupport stencilSupport;
GrStrokeInfo stroke(SkStrokeRec::kFill_InitStyle);
SkRegion::Op op = element->getOp();
GrPathRenderer* pr = nullptr;
SkPath clipPath;
if (Element::kRect_Type == element->getType()) {
stencilSupport = GrPathRenderer::kNoRestriction_StencilSupport;
fillInverted = false;
} else {
element->asPath(&clipPath);
fillInverted = clipPath.isInverseFillType();
if (fillInverted) {
clipPath.toggleInverseFillType();
}
SkASSERT(pipelineBuilder.getStencil().isDisabled());
GrPathRenderer::CanDrawPathArgs canDrawArgs;
canDrawArgs.fShaderCaps = this->getContext()->caps()->shaderCaps();
canDrawArgs.fViewMatrix = &viewMatrix;
canDrawArgs.fPath = &clipPath;
canDrawArgs.fStroke = &stroke;
canDrawArgs.fAntiAlias = false;
canDrawArgs.fIsStencilDisabled = pipelineBuilder.getStencil().isDisabled();
canDrawArgs.fIsStencilBufferMSAA = rt->isStencilBufferMultisampled();
pr = this->getContext()->drawingManager()->getPathRenderer(canDrawArgs, false,
GrPathRendererChain::kStencilOnly_DrawType,
&stencilSupport);
if (nullptr == pr) {
return false;
}
}
int passes;
GrStencilSettings stencilSettings[GrStencilSettings::kMaxStencilClipPasses];
bool canRenderDirectToStencil =
GrPathRenderer::kNoRestriction_StencilSupport == stencilSupport;
bool canDrawDirectToClip; // Given the renderer, the element,
// fill rule, and set operation can
// we render the element directly to
// stencil bit used for clipping.
canDrawDirectToClip = GrStencilSettings::GetClipPasses(op,
canRenderDirectToStencil,
clipBit,
fillInverted,
&passes,
stencilSettings);
// draw the element to the client stencil bits if necessary
if (!canDrawDirectToClip) {
GR_STATIC_CONST_SAME_STENCIL(gDrawToStencil,
kIncClamp_StencilOp,
kIncClamp_StencilOp,
kAlways_StencilFunc,
0xffff,
0x0000,
0xffff);
if (Element::kRect_Type == element->getType()) {
*pipelineBuilder.stencil() = gDrawToStencil;
draw_non_aa_rect(fDrawTarget, pipelineBuilder, GrColor_WHITE, viewMatrix,
element->getRect());
} else {
if (!clipPath.isEmpty()) {
if (canRenderDirectToStencil) {
*pipelineBuilder.stencil() = gDrawToStencil;
GrPathRenderer::DrawPathArgs args;
args.fTarget = fDrawTarget;
args.fResourceProvider = this->getContext()->resourceProvider();
args.fPipelineBuilder = &pipelineBuilder;
args.fColor = GrColor_WHITE;
args.fViewMatrix = &viewMatrix;
args.fPath = &clipPath;
args.fStroke = &stroke;
args.fAntiAlias = false;
args.fGammaCorrect = false;
pr->drawPath(args);
} else {
GrPathRenderer::StencilPathArgs args;
args.fTarget = fDrawTarget;
args.fResourceProvider = this->getContext()->resourceProvider();
args.fPipelineBuilder = &pipelineBuilder;
args.fViewMatrix = &viewMatrix;
args.fPath = &clipPath;
args.fStroke = &stroke;
pr->stencilPath(args);
}
}
}
}
// now we modify the clip bit by rendering either the clip
// element directly or a bounding rect of the entire clip.
fClipMode = kModifyClip_StencilClipMode;
for (int p = 0; p < passes; ++p) {
*pipelineBuilder.stencil() = stencilSettings[p];
if (canDrawDirectToClip) {
if (Element::kRect_Type == element->getType()) {
draw_non_aa_rect(fDrawTarget, pipelineBuilder, GrColor_WHITE, viewMatrix,
element->getRect());
} else {
GrPathRenderer::DrawPathArgs args;
args.fTarget = fDrawTarget;
args.fResourceProvider = this->getContext()->resourceProvider();
args.fPipelineBuilder = &pipelineBuilder;
args.fColor = GrColor_WHITE;
args.fViewMatrix = &viewMatrix;
args.fPath = &clipPath;
args.fStroke = &stroke;
args.fAntiAlias = false;
args.fGammaCorrect = false;
pr->drawPath(args);
}
} else {
// The view matrix is setup to do clip space -> stencil space translation, so
// draw rect in clip space.
draw_non_aa_rect(fDrawTarget, pipelineBuilder, GrColor_WHITE, viewMatrix,
SkRect::Make(clipSpaceIBounds));
}
}
}
}
fClipMode = kRespectClip_StencilClipMode;
return true;
}
// mapping of clip-respecting stencil funcs to normal stencil funcs
// mapping depends on whether stencil-clipping is in effect.
static const GrStencilFunc
gSpecialToBasicStencilFunc[2][kClipStencilFuncCount] = {
{// Stencil-Clipping is DISABLED, we are effectively always inside the clip
// In the Clip Funcs
kAlways_StencilFunc, // kAlwaysIfInClip_StencilFunc
kEqual_StencilFunc, // kEqualIfInClip_StencilFunc
kLess_StencilFunc, // kLessIfInClip_StencilFunc
kLEqual_StencilFunc, // kLEqualIfInClip_StencilFunc
// Special in the clip func that forces user's ref to be 0.
kNotEqual_StencilFunc, // kNonZeroIfInClip_StencilFunc
// make ref 0 and do normal nequal.
},
{// Stencil-Clipping is ENABLED
// In the Clip Funcs
kEqual_StencilFunc, // kAlwaysIfInClip_StencilFunc
// eq stencil clip bit, mask
// out user bits.
kEqual_StencilFunc, // kEqualIfInClip_StencilFunc
// add stencil bit to mask and ref
kLess_StencilFunc, // kLessIfInClip_StencilFunc
kLEqual_StencilFunc, // kLEqualIfInClip_StencilFunc
// for both of these we can add
// the clip bit to the mask and
// ref and compare as normal
// Special in the clip func that forces user's ref to be 0.
kLess_StencilFunc, // kNonZeroIfInClip_StencilFunc
// make ref have only the clip bit set
// and make comparison be less
// 10..0 < 1..user_bits..
}
};
namespace {
// Sets the settings to clip against the stencil buffer clip while ignoring the
// client bits.
const GrStencilSettings& basic_apply_stencil_clip_settings() {
// stencil settings to use when clip is in stencil
GR_STATIC_CONST_SAME_STENCIL_STRUCT(gSettings,
kKeep_StencilOp,
kKeep_StencilOp,
kAlwaysIfInClip_StencilFunc,
0x0000,
0x0000,
0x0000);
return *GR_CONST_STENCIL_SETTINGS_PTR_FROM_STRUCT_PTR(&gSettings);
}
}
void GrClipMaskManager::setPipelineBuilderStencil(const GrPipelineBuilder& pipelineBuilder,
GrPipelineBuilder::AutoRestoreStencil* ars) {
// We make two copies of the StencilSettings here (except in the early
// exit scenario. One copy from draw state to the stack var. Then another
// from the stack var to the gpu. We could make this class hold a ptr to
// GrGpu's fStencilSettings and eliminate the stack copy here.
// use stencil for clipping if clipping is enabled and the clip
// has been written into the stencil.
GrStencilSettings settings;
// The GrGpu client may not be using the stencil buffer but we may need to
// enable it in order to respect a stencil clip.
if (pipelineBuilder.getStencil().isDisabled()) {
if (GrClipMaskManager::kRespectClip_StencilClipMode == fClipMode) {
settings = basic_apply_stencil_clip_settings();
} else {
return;
}
} else {
settings = pipelineBuilder.getStencil();
}
int stencilBits = 0;
GrRenderTarget* rt = pipelineBuilder.getRenderTarget();
GrStencilAttachment* stencilAttachment = this->resourceProvider()->attachStencilAttachment(rt);
if (stencilAttachment) {
stencilBits = stencilAttachment->bits();
}
SkASSERT(this->caps()->stencilWrapOpsSupport() || !settings.usesWrapOp());
SkASSERT(this->caps()->twoSidedStencilSupport() || !settings.isTwoSided());
this->adjustStencilParams(&settings, fClipMode, stencilBits);
ars->set(&pipelineBuilder);
ars->setStencil(settings);
}
void GrClipMaskManager::adjustStencilParams(GrStencilSettings* settings,
StencilClipMode mode,
int stencilBitCnt) {
SkASSERT(stencilBitCnt > 0);
if (kModifyClip_StencilClipMode == mode) {
// We assume that this clip manager itself is drawing to the GrGpu and
// has already setup the correct values.
return;
}
unsigned int clipBit = (1 << (stencilBitCnt - 1));
unsigned int userBits = clipBit - 1;
GrStencilSettings::Face face = GrStencilSettings::kFront_Face;
bool twoSided = this->caps()->twoSidedStencilSupport();
bool finished = false;
while (!finished) {
GrStencilFunc func = settings->func(face);
uint16_t writeMask = settings->writeMask(face);
uint16_t funcMask = settings->funcMask(face);
uint16_t funcRef = settings->funcRef(face);
SkASSERT((unsigned) func < kStencilFuncCount);
writeMask &= userBits;
if (func >= kBasicStencilFuncCount) {
int respectClip = kRespectClip_StencilClipMode == mode;
if (respectClip) {
switch (func) {
case kAlwaysIfInClip_StencilFunc:
funcMask = clipBit;
funcRef = clipBit;
break;
case kEqualIfInClip_StencilFunc:
case kLessIfInClip_StencilFunc:
case kLEqualIfInClip_StencilFunc:
funcMask = (funcMask & userBits) | clipBit;
funcRef = (funcRef & userBits) | clipBit;
break;
case kNonZeroIfInClip_StencilFunc:
funcMask = (funcMask & userBits) | clipBit;
funcRef = clipBit;
break;
default:
SkFAIL("Unknown stencil func");
}
} else {
funcMask &= userBits;
funcRef &= userBits;
}
const GrStencilFunc* table =
gSpecialToBasicStencilFunc[respectClip];
func = table[func - kBasicStencilFuncCount];
SkASSERT(func >= 0 && func < kBasicStencilFuncCount);
} else {
funcMask &= userBits;
funcRef &= userBits;
}
settings->setFunc(face, func);
settings->setWriteMask(face, writeMask);
settings->setFuncMask(face, funcMask);
settings->setFuncRef(face, funcRef);
if (GrStencilSettings::kFront_Face == face) {
face = GrStencilSettings::kBack_Face;
finished = !twoSided;
} else {
finished = true;
}
}
if (!twoSided) {
settings->copyFrontSettingsToBack();
}
}
////////////////////////////////////////////////////////////////////////////////
GrTexture* GrClipMaskManager::CreateSoftwareClipMask(GrContext* context,
int32_t elementsGenID,
GrReducedClip::InitialState initialState,
const GrReducedClip::ElementList& elements,
const SkVector& clipToMaskOffset,
const SkIRect& clipSpaceIBounds) {
GrUniqueKey key;
GetClipMaskKey(elementsGenID, clipSpaceIBounds, &key);
GrResourceProvider* resourceProvider = context->resourceProvider();
if (GrTexture* texture = resourceProvider->findAndRefTextureByUniqueKey(key)) {
return texture;
}
// The mask texture may be larger than necessary. We round out the clip space bounds and pin
// the top left corner of the resulting rect to the top left of the texture.
SkIRect maskSpaceIBounds = SkIRect::MakeWH(clipSpaceIBounds.width(), clipSpaceIBounds.height());
GrSWMaskHelper helper(context);
// Set the matrix so that rendered clip elements are transformed to mask space from clip
// space.
SkMatrix translate;
translate.setTranslate(clipToMaskOffset);
helper.init(maskSpaceIBounds, &translate, false);
helper.clear(GrReducedClip::kAllIn_InitialState == initialState ? 0xFF : 0x00);
SkStrokeRec stroke(SkStrokeRec::kFill_InitStyle);
for (GrReducedClip::ElementList::Iter iter(elements.headIter()) ; iter.get(); iter.next()) {
const Element* element = iter.get();
SkRegion::Op op = element->getOp();
if (SkRegion::kIntersect_Op == op || SkRegion::kReverseDifference_Op == op) {
// Intersect and reverse difference require modifying pixels outside of the geometry
// that is being "drawn". In both cases we erase all the pixels outside of the geometry
// but leave the pixels inside the geometry alone. For reverse difference we invert all
// the pixels before clearing the ones outside the geometry.
if (SkRegion::kReverseDifference_Op == op) {
SkRect temp = SkRect::Make(clipSpaceIBounds);
// invert the entire scene
helper.draw(temp, SkRegion::kXOR_Op, false, 0xFF);
}
SkPath clipPath;
element->asPath(&clipPath);
clipPath.toggleInverseFillType();
helper.draw(clipPath, stroke, SkRegion::kReplace_Op, element->isAA(), 0x00);
continue;
}
// The other ops (union, xor, diff) only affect pixels inside
// the geometry so they can just be drawn normally
if (Element::kRect_Type == element->getType()) {
helper.draw(element->getRect(), op, element->isAA(), 0xFF);
} else {
SkPath path;
element->asPath(&path);
helper.draw(path, stroke, op, element->isAA(), 0xFF);
}
}
// Allocate clip mask texture
GrSurfaceDesc desc;
desc.fWidth = clipSpaceIBounds.width();
desc.fHeight = clipSpaceIBounds.height();
desc.fConfig = kAlpha_8_GrPixelConfig;
GrTexture* result = context->resourceProvider()->createApproxTexture(desc, 0);
if (!result) {
return nullptr;
}
result->resourcePriv().setUniqueKey(key);
helper.toTexture(result);
return result;
}
////////////////////////////////////////////////////////////////////////////////
void GrClipMaskManager::adjustPathStencilParams(const GrStencilAttachment* stencilAttachment,
GrStencilSettings* settings) {
if (stencilAttachment) {
int stencilBits = stencilAttachment->bits();
this->adjustStencilParams(settings, fClipMode, stencilBits);
}
}
|