1 /*
2  * Copyright 2010 Google Inc.
3  *
4  * Use of this source code is governed by a BSD-style license that can be
5  * found in the LICENSE file.
6  */
7 
8 #include "src/gpu/SkGr.h"
9 
10 #include "include/core/SkCanvas.h"
11 #include "include/core/SkColorFilter.h"
12 #include "include/core/SkData.h"
13 #include "include/core/SkPixelRef.h"
14 #include "include/gpu/GrContext.h"
15 #include "include/gpu/GrTypes.h"
16 #include "include/private/GrRecordingContext.h"
17 #include "include/private/SkImageInfoPriv.h"
18 #include "include/private/SkTemplates.h"
19 #include "src/core/SkAutoMalloc.h"
20 #include "src/core/SkBlendModePriv.h"
21 #include "src/core/SkColorSpacePriv.h"
22 #include "src/core/SkImagePriv.h"
23 #include "src/core/SkMaskFilterBase.h"
24 #include "src/core/SkMessageBus.h"
25 #include "src/core/SkMipMap.h"
26 #include "src/core/SkPaintPriv.h"
27 #include "src/core/SkResourceCache.h"
28 #include "src/core/SkTraceEvent.h"
29 #include "src/gpu/GrBitmapTextureMaker.h"
30 #include "src/gpu/GrCaps.h"
31 #include "src/gpu/GrColorSpaceXform.h"
32 #include "src/gpu/GrContextPriv.h"
33 #include "src/gpu/GrGpuResourcePriv.h"
34 #include "src/gpu/GrPaint.h"
35 #include "src/gpu/GrProxyProvider.h"
36 #include "src/gpu/GrRecordingContextPriv.h"
37 #include "src/gpu/GrTextureProxy.h"
38 #include "src/gpu/GrXferProcessor.h"
39 #include "src/gpu/effects/GrBicubicEffect.h"
40 #include "src/gpu/effects/GrPorterDuffXferProcessor.h"
41 #include "src/gpu/effects/GrSkSLFP.h"
42 #include "src/gpu/effects/GrXfermodeFragmentProcessor.h"
43 #include "src/gpu/effects/generated/GrConstColorProcessor.h"
44 #include "src/gpu/effects/generated/GrSaturateProcessor.h"
45 #include "src/image/SkImage_Base.h"
46 #include "src/shaders/SkShaderBase.h"
47 
48 GR_FP_SRC_STRING SKSL_DITHER_SRC = R"(
49 // This controls the range of values added to color channels
50 in int rangeType;
51 
52 void main(float x, float y, inout half4 color) {
53     half value;
54     half range;
55     @switch (rangeType) {
56         case 0:
57             range = 1.0 / 255.0;
58             break;
59         case 1:
60             range = 1.0 / 63.0;
61             break;
62         default:
63             // Experimentally this looks better than the expected value of 1/15.
64             range = 1.0 / 15.0;
65             break;
66     }
67     @if (sk_Caps.integerSupport) {
68         // This ordered-dither code is lifted from the cpu backend.
69         uint x = uint(x);
70         uint y = uint(y);
71         uint m = (y & 1) << 5 | (x & 1) << 4 |
72                  (y & 2) << 2 | (x & 2) << 1 |
73                  (y & 4) >> 1 | (x & 4) >> 2;
74         value = half(m) * 1.0 / 64.0 - 63.0 / 128.0;
75     } else {
76         // Simulate the integer effect used above using step/mod. For speed, simulates a 4x4
77         // dither pattern rather than an 8x8 one.
78         half4 modValues = mod(half4(half(x), half(y), half(x), half(y)), half4(2.0, 2.0, 4.0, 4.0));
79         half4 stepValues = step(modValues, half4(1.0, 1.0, 2.0, 2.0));
80         value = dot(stepValues, half4(8.0 / 16.0, 4.0 / 16.0, 2.0 / 16.0, 1.0 / 16.0)) - 15.0 / 32.0;
81     }
82     // For each color channel, add the random offset to the channel value and then clamp
83     // between 0 and alpha to keep the color premultiplied.
84     color = half4(clamp(color.rgb + value * range, 0.0, color.a), color.a);
85 }
86 )";
87 
GrImageInfoToSurfaceDesc(const SkImageInfo & info)88 GrSurfaceDesc GrImageInfoToSurfaceDesc(const SkImageInfo& info) {
89     GrSurfaceDesc desc;
90     desc.fWidth = info.width();
91     desc.fHeight = info.height();
92     desc.fConfig = SkImageInfo2GrPixelConfig(info);
93     return desc;
94 }
95 
GrMakeKeyFromImageID(GrUniqueKey * key,uint32_t imageID,const SkIRect & imageBounds)96 void GrMakeKeyFromImageID(GrUniqueKey* key, uint32_t imageID, const SkIRect& imageBounds) {
97     SkASSERT(key);
98     SkASSERT(imageID);
99     SkASSERT(!imageBounds.isEmpty());
100     static const GrUniqueKey::Domain kImageIDDomain = GrUniqueKey::GenerateDomain();
101     GrUniqueKey::Builder builder(key, kImageIDDomain, 5, "Image");
102     builder[0] = imageID;
103     builder[1] = imageBounds.fLeft;
104     builder[2] = imageBounds.fTop;
105     builder[3] = imageBounds.fRight;
106     builder[4] = imageBounds.fBottom;
107 }
108 
109 ////////////////////////////////////////////////////////////////////////////////
110 
GrInstallBitmapUniqueKeyInvalidator(const GrUniqueKey & key,uint32_t contextUniqueID,SkPixelRef * pixelRef)111 void GrInstallBitmapUniqueKeyInvalidator(const GrUniqueKey& key, uint32_t contextUniqueID,
112                                          SkPixelRef* pixelRef) {
113     class Invalidator : public SkPixelRef::GenIDChangeListener {
114     public:
115         explicit Invalidator(const GrUniqueKey& key, uint32_t contextUniqueID)
116                 : fMsg(key, contextUniqueID) {}
117 
118     private:
119         GrUniqueKeyInvalidatedMessage fMsg;
120 
121         void onChange() override { SkMessageBus<GrUniqueKeyInvalidatedMessage>::Post(fMsg); }
122     };
123 
124     pixelRef->addGenIDChangeListener(new Invalidator(key, contextUniqueID));
125 }
126 
GrCopyBaseMipMapToTextureProxy(GrRecordingContext * ctx,GrTextureProxy * baseProxy,GrColorType srcColorType)127 sk_sp<GrTextureProxy> GrCopyBaseMipMapToTextureProxy(GrRecordingContext* ctx,
128                                                      GrTextureProxy* baseProxy,
129                                                      GrColorType srcColorType) {
130     SkASSERT(baseProxy);
131 
132     if (!ctx->priv().caps()->isFormatCopyable(baseProxy->backendFormat())) {
133         return nullptr;
134     }
135     return GrSurfaceProxy::Copy(ctx, baseProxy, srcColorType, GrMipMapped::kYes,
136                                 SkBackingFit::kExact, SkBudgeted::kYes);
137 }
138 
GrRefCachedBitmapTextureProxy(GrRecordingContext * ctx,const SkBitmap & bitmap,const GrSamplerState & params,SkScalar scaleAdjust[2])139 sk_sp<GrTextureProxy> GrRefCachedBitmapTextureProxy(GrRecordingContext* ctx,
140                                                     const SkBitmap& bitmap,
141                                                     const GrSamplerState& params,
142                                                     SkScalar scaleAdjust[2]) {
143     return GrBitmapTextureMaker(ctx, bitmap).refTextureProxyForParams(params, scaleAdjust);
144 }
145 
GrMakeCachedBitmapProxy(GrProxyProvider * proxyProvider,const SkBitmap & bitmap,SkBackingFit fit)146 sk_sp<GrTextureProxy> GrMakeCachedBitmapProxy(GrProxyProvider* proxyProvider,
147                                               const SkBitmap& bitmap,
148                                               SkBackingFit fit) {
149     if (!bitmap.peekPixels(nullptr)) {
150         return nullptr;
151     }
152 
153     // In non-ddl we will always instantiate right away. Thus we never want to copy the SkBitmap
154     // even if its mutable. In ddl, if the bitmap is mutable then we must make a copy since the
155     // upload of the data to the gpu can happen at anytime and the bitmap may change by then.
156     SkCopyPixelsMode cpyMode = proxyProvider->renderingDirectly() ? kNever_SkCopyPixelsMode
157                                                                   : kIfMutable_SkCopyPixelsMode;
158     sk_sp<SkImage> image = SkMakeImageFromRasterBitmap(bitmap, cpyMode);
159 
160     if (!image) {
161         return nullptr;
162     }
163 
164     return GrMakeCachedImageProxy(proxyProvider, std::move(image), fit);
165 }
166 
create_unique_key_for_image(const SkImage * image,GrUniqueKey * result)167 static void create_unique_key_for_image(const SkImage* image, GrUniqueKey* result) {
168     if (!image) {
169         result->reset(); // will be invalid
170         return;
171     }
172 
173     if (const SkBitmap* bm = as_IB(image)->onPeekBitmap()) {
174         if (!bm->isVolatile()) {
175             SkIPoint origin = bm->pixelRefOrigin();
176             SkIRect subset = SkIRect::MakeXYWH(origin.fX, origin.fY, bm->width(), bm->height());
177             GrMakeKeyFromImageID(result, bm->getGenerationID(), subset);
178         }
179         return;
180     }
181 
182     GrMakeKeyFromImageID(result, image->uniqueID(), image->bounds());
183 }
184 
GrMakeCachedImageProxy(GrProxyProvider * proxyProvider,sk_sp<SkImage> srcImage,SkBackingFit fit)185 sk_sp<GrTextureProxy> GrMakeCachedImageProxy(GrProxyProvider* proxyProvider,
186                                              sk_sp<SkImage> srcImage,
187                                              SkBackingFit fit) {
188     sk_sp<GrTextureProxy> proxy;
189     GrUniqueKey originalKey;
190 
191     create_unique_key_for_image(srcImage.get(), &originalKey);
192 
193     if (originalKey.isValid()) {
194         proxy = proxyProvider->findOrCreateProxyByUniqueKey(
195                 originalKey, SkColorTypeToGrColorType(srcImage->colorType()),
196                 kTopLeft_GrSurfaceOrigin);
197     }
198     if (!proxy) {
199         proxy = proxyProvider->createTextureProxy(srcImage, 1, SkBudgeted::kYes, fit);
200         if (proxy && originalKey.isValid()) {
201             proxyProvider->assignUniqueKeyToProxy(originalKey, proxy.get());
202             const SkBitmap* bm = as_IB(srcImage.get())->onPeekBitmap();
203             // When recording DDLs we do not want to install change listeners because doing
204             // so isn't threadsafe.
205             if (bm && proxyProvider->renderingDirectly()) {
206                 GrInstallBitmapUniqueKeyInvalidator(originalKey, proxyProvider->contextID(),
207                                                     bm->pixelRef());
208             }
209         }
210     }
211 
212     return proxy;
213 }
214 
215 ///////////////////////////////////////////////////////////////////////////////
216 
SkColorToPMColor4f(SkColor c,const GrColorInfo & colorInfo)217 SkPMColor4f SkColorToPMColor4f(SkColor c, const GrColorInfo& colorInfo) {
218     SkColor4f color = SkColor4f::FromColor(c);
219     if (auto* xform = colorInfo.colorSpaceXformFromSRGB()) {
220         color = xform->apply(color);
221     }
222     return color.premul();
223 }
224 
SkColor4fPrepForDst(SkColor4f color,const GrColorInfo & colorInfo)225 SkColor4f SkColor4fPrepForDst(SkColor4f color, const GrColorInfo& colorInfo) {
226     if (auto* xform = colorInfo.colorSpaceXformFromSRGB()) {
227         color = xform->apply(color);
228     }
229     return color;
230 }
231 
232 ///////////////////////////////////////////////////////////////////////////////
233 
SkColorType2GrPixelConfig(const SkColorType type)234 GrPixelConfig SkColorType2GrPixelConfig(const SkColorType type) {
235     switch (type) {
236         case kUnknown_SkColorType:
237             return kUnknown_GrPixelConfig;
238         case kAlpha_8_SkColorType:
239             return kAlpha_8_GrPixelConfig;
240         case kRGB_565_SkColorType:
241             return kRGB_565_GrPixelConfig;
242         case kARGB_4444_SkColorType:
243             return kRGBA_4444_GrPixelConfig;
244         case kRGBA_8888_SkColorType:
245             return kRGBA_8888_GrPixelConfig;
246         case kRGB_888x_SkColorType:
247             return kRGB_888_GrPixelConfig;
248         case kBGRA_8888_SkColorType:
249             return kBGRA_8888_GrPixelConfig;
250         case kRGBA_1010102_SkColorType:
251             return kRGBA_1010102_GrPixelConfig;
252         case kRGB_101010x_SkColorType:
253             return kUnknown_GrPixelConfig;
254         case kGray_8_SkColorType:
255             return kGray_8_GrPixelConfig;
256         case kRGBA_F16Norm_SkColorType:
257             return kRGBA_half_Clamped_GrPixelConfig;
258         case kRGBA_F16_SkColorType:
259             return kRGBA_half_GrPixelConfig;
260         case kRGBA_F32_SkColorType:
261             return kUnknown_GrPixelConfig;
262         case kR8G8_unorm_SkColorType:
263             return kRG_88_GrPixelConfig;
264         case kR16G16_unorm_SkColorType:
265             return kRG_1616_GrPixelConfig;
266         case kA16_unorm_SkColorType:
267             return kAlpha_16_GrPixelConfig;
268         case kA16_float_SkColorType:
269             return kAlpha_half_GrPixelConfig;
270         case kR16G16_float_SkColorType:
271             return kRG_half_GrPixelConfig;
272         case kR16G16B16A16_unorm_SkColorType:
273             return kRGBA_16161616_GrPixelConfig;
274     }
275     SkUNREACHABLE;
276 }
277 
SkImageInfo2GrPixelConfig(const SkImageInfo & info)278 GrPixelConfig SkImageInfo2GrPixelConfig(const SkImageInfo& info) {
279     return SkColorType2GrPixelConfig(info.colorType());
280 }
281 
GrPixelConfigToColorType(GrPixelConfig config,SkColorType * ctOut)282 bool GrPixelConfigToColorType(GrPixelConfig config, SkColorType* ctOut) {
283     SkColorType ct = GrColorTypeToSkColorType(GrPixelConfigToColorType(config));
284     if (kUnknown_SkColorType != ct) {
285         if (ctOut) {
286             *ctOut = ct;
287         }
288         return true;
289     }
290     return false;
291 }
292 
293 ////////////////////////////////////////////////////////////////////////////////////////////////
294 
blend_requires_shader(const SkBlendMode mode)295 static inline bool blend_requires_shader(const SkBlendMode mode) {
296     return SkBlendMode::kDst != mode;
297 }
298 
299 #ifndef SK_IGNORE_GPU_DITHER
dither_range_type_for_config(GrColorType dstColorType)300 static inline int32_t dither_range_type_for_config(GrColorType dstColorType) {
301     switch (dstColorType) {
302         case GrColorType::kGray_8:
303         case GrColorType::kRGBA_8888:
304         case GrColorType::kRGB_888x:
305         case GrColorType::kRG_88:
306         case GrColorType::kBGRA_8888:
307         case GrColorType::kRG_1616:
308         case GrColorType::kRGBA_16161616:
309         case GrColorType::kRG_F16:
310             return 0;
311         case GrColorType::kBGR_565:
312             return 1;
313         case GrColorType::kABGR_4444:
314             return 2;
315         case GrColorType::kUnknown:
316         case GrColorType::kRGBA_8888_SRGB:
317         case GrColorType::kRGBA_1010102:
318         case GrColorType::kAlpha_F16:
319         case GrColorType::kRGBA_F32:
320         case GrColorType::kRGBA_F16:
321         case GrColorType::kRGBA_F16_Clamped:
322         case GrColorType::kAlpha_8:
323         case GrColorType::kAlpha_8xxx:
324         case GrColorType::kAlpha_16:
325         case GrColorType::kAlpha_F32xxx:
326         case GrColorType::kGray_8xxx:
327             return -1;
328     }
329     SkUNREACHABLE;
330 }
331 #endif
332 
skpaint_to_grpaint_impl(GrRecordingContext * context,const GrColorInfo & dstColorInfo,const SkPaint & skPaint,const SkMatrix & viewM,std::unique_ptr<GrFragmentProcessor> * shaderProcessor,SkBlendMode * primColorMode,GrPaint * grPaint)333 static inline bool skpaint_to_grpaint_impl(GrRecordingContext* context,
334                                            const GrColorInfo& dstColorInfo,
335                                            const SkPaint& skPaint,
336                                            const SkMatrix& viewM,
337                                            std::unique_ptr<GrFragmentProcessor>* shaderProcessor,
338                                            SkBlendMode* primColorMode,
339                                            GrPaint* grPaint) {
340     // Convert SkPaint color to 4f format in the destination color space
341     SkColor4f origColor = SkColor4fPrepForDst(skPaint.getColor4f(), dstColorInfo);
342 
343     GrFPArgs fpArgs(context, &viewM, skPaint.getFilterQuality(), &dstColorInfo);
344 
345     // Setup the initial color considering the shader, the SkPaint color, and the presence or not
346     // of per-vertex colors.
347     std::unique_ptr<GrFragmentProcessor> shaderFP;
348     if (!primColorMode || blend_requires_shader(*primColorMode)) {
349         fpArgs.fInputColorIsOpaque = origColor.isOpaque();
350         if (shaderProcessor) {
351             shaderFP = std::move(*shaderProcessor);
352         } else if (const auto* shader = as_SB(skPaint.getShader())) {
353             shaderFP = shader->asFragmentProcessor(fpArgs);
354             if (!shaderFP) {
355                 return false;
356             }
357         }
358     }
359 
360     // Set this in below cases if the output of the shader/paint-color/paint-alpha/primXfermode is
361     // a known constant value. In that case we can simply apply a color filter during this
362     // conversion without converting the color filter to a GrFragmentProcessor.
363     bool applyColorFilterToPaintColor = false;
364     if (shaderFP) {
365         if (primColorMode) {
366             // There is a blend between the primitive color and the shader color. The shader sees
367             // the opaque paint color. The shader's output is blended using the provided mode by
368             // the primitive color. The blended color is then modulated by the paint's alpha.
369 
370             // The geometry processor will insert the primitive color to start the color chain, so
371             // the GrPaint color will be ignored.
372 
373             SkPMColor4f shaderInput = origColor.makeOpaque().premul();
374             shaderFP = GrFragmentProcessor::OverrideInput(std::move(shaderFP), shaderInput);
375             shaderFP = GrXfermodeFragmentProcessor::MakeFromSrcProcessor(std::move(shaderFP),
376                                                                          *primColorMode);
377 
378             // The above may return null if compose results in a pass through of the prim color.
379             if (shaderFP) {
380                 grPaint->addColorFragmentProcessor(std::move(shaderFP));
381             }
382 
383             // We can ignore origColor here - alpha is unchanged by gamma
384             float paintAlpha = skPaint.getColor4f().fA;
385             if (1.0f != paintAlpha) {
386                 // No gamut conversion - paintAlpha is a (linear) alpha value, splatted to all
387                 // color channels. It's value should be treated as the same in ANY color space.
388                 grPaint->addColorFragmentProcessor(GrConstColorProcessor::Make(
389                     { paintAlpha, paintAlpha, paintAlpha, paintAlpha },
390                     GrConstColorProcessor::InputMode::kModulateRGBA));
391             }
392         } else {
393             // The shader's FP sees the paint *unpremul* color
394             SkPMColor4f origColorAsPM = { origColor.fR, origColor.fG, origColor.fB, origColor.fA };
395             grPaint->setColor4f(origColorAsPM);
396             grPaint->addColorFragmentProcessor(std::move(shaderFP));
397         }
398     } else {
399         if (primColorMode) {
400             // There is a blend between the primitive color and the paint color. The blend considers
401             // the opaque paint color. The paint's alpha is applied to the post-blended color.
402             SkPMColor4f opaqueColor = origColor.makeOpaque().premul();
403             auto processor = GrConstColorProcessor::Make(opaqueColor,
404                                                          GrConstColorProcessor::InputMode::kIgnore);
405             processor = GrXfermodeFragmentProcessor::MakeFromSrcProcessor(std::move(processor),
406                                                                           *primColorMode);
407             if (processor) {
408                 grPaint->addColorFragmentProcessor(std::move(processor));
409             }
410 
411             grPaint->setColor4f(opaqueColor);
412 
413             // We can ignore origColor here - alpha is unchanged by gamma
414             float paintAlpha = skPaint.getColor4f().fA;
415             if (1.0f != paintAlpha) {
416                 // No gamut conversion - paintAlpha is a (linear) alpha value, splatted to all
417                 // color channels. It's value should be treated as the same in ANY color space.
418                 grPaint->addColorFragmentProcessor(GrConstColorProcessor::Make(
419                     { paintAlpha, paintAlpha, paintAlpha, paintAlpha },
420                     GrConstColorProcessor::InputMode::kModulateRGBA));
421             }
422         } else {
423             // No shader, no primitive color.
424             grPaint->setColor4f(origColor.premul());
425             applyColorFilterToPaintColor = true;
426         }
427     }
428 
429     SkColorFilter* colorFilter = skPaint.getColorFilter();
430     if (colorFilter) {
431         if (applyColorFilterToPaintColor) {
432             SkColorSpace* dstCS = dstColorInfo.colorSpace();
433             grPaint->setColor4f(colorFilter->filterColor4f(origColor, dstCS, dstCS).premul());
434         } else {
435             auto cfFP = colorFilter->asFragmentProcessor(context, dstColorInfo);
436             if (cfFP) {
437                 grPaint->addColorFragmentProcessor(std::move(cfFP));
438             } else {
439                 return false;
440             }
441         }
442     }
443 
444     SkMaskFilterBase* maskFilter = as_MFB(skPaint.getMaskFilter());
445     if (maskFilter) {
446         // We may have set this before passing to the SkShader.
447         fpArgs.fInputColorIsOpaque = false;
448         if (auto mfFP = maskFilter->asFragmentProcessor(fpArgs)) {
449             grPaint->addCoverageFragmentProcessor(std::move(mfFP));
450         }
451     }
452 
453     // When the xfermode is null on the SkPaint (meaning kSrcOver) we need the XPFactory field on
454     // the GrPaint to also be null (also kSrcOver).
455     SkASSERT(!grPaint->getXPFactory());
456     if (!skPaint.isSrcOver()) {
457         grPaint->setXPFactory(SkBlendMode_AsXPFactory(skPaint.getBlendMode()));
458     }
459 
460 #ifndef SK_IGNORE_GPU_DITHER
461     // Conservative default, in case GrPixelConfigToColorType() fails.
462     GrColorType ct = dstColorInfo.colorType();
463     if (SkPaintPriv::ShouldDither(skPaint, GrColorTypeToSkColorType(ct)) &&
464         grPaint->numColorFragmentProcessors() > 0) {
465         int32_t ditherRange = dither_range_type_for_config(ct);
466         if (ditherRange >= 0) {
467             static int ditherIndex = GrSkSLFP::NewIndex();
468             auto ditherFP = GrSkSLFP::Make(context, ditherIndex, "Dither", SKSL_DITHER_SRC,
469                                            &ditherRange, sizeof(ditherRange));
470             if (ditherFP) {
471                 grPaint->addColorFragmentProcessor(std::move(ditherFP));
472             }
473         }
474     }
475 #endif
476     if (GrColorTypeClampType(dstColorInfo.colorType()) == GrClampType::kManual) {
477         if (grPaint->numColorFragmentProcessors()) {
478             grPaint->addColorFragmentProcessor(GrSaturateProcessor::Make());
479         } else {
480             auto color = grPaint->getColor4f();
481             grPaint->setColor4f({SkTPin(color.fR, 0.f, 1.f),
482                                  SkTPin(color.fG, 0.f, 1.f),
483                                  SkTPin(color.fB, 0.f, 1.f),
484                                  SkTPin(color.fA, 0.f, 1.f)});
485         }
486     }
487     return true;
488 }
489 
SkPaintToGrPaint(GrRecordingContext * context,const GrColorInfo & dstColorInfo,const SkPaint & skPaint,const SkMatrix & viewM,GrPaint * grPaint)490 bool SkPaintToGrPaint(GrRecordingContext* context, const GrColorInfo& dstColorInfo,
491                       const SkPaint& skPaint, const SkMatrix& viewM, GrPaint* grPaint) {
492     return skpaint_to_grpaint_impl(context, dstColorInfo, skPaint, viewM, nullptr, nullptr,
493                                    grPaint);
494 }
495 
496 /** Replaces the SkShader (if any) on skPaint with the passed in GrFragmentProcessor. */
SkPaintToGrPaintReplaceShader(GrRecordingContext * context,const GrColorInfo & dstColorInfo,const SkPaint & skPaint,std::unique_ptr<GrFragmentProcessor> shaderFP,GrPaint * grPaint)497 bool SkPaintToGrPaintReplaceShader(GrRecordingContext* context,
498                                    const GrColorInfo& dstColorInfo,
499                                    const SkPaint& skPaint,
500                                    std::unique_ptr<GrFragmentProcessor> shaderFP,
501                                    GrPaint* grPaint) {
502     if (!shaderFP) {
503         return false;
504     }
505     return skpaint_to_grpaint_impl(context, dstColorInfo, skPaint, SkMatrix::I(), &shaderFP,
506                                    nullptr, grPaint);
507 }
508 
509 /** Ignores the SkShader (if any) on skPaint. */
SkPaintToGrPaintNoShader(GrRecordingContext * context,const GrColorInfo & dstColorInfo,const SkPaint & skPaint,GrPaint * grPaint)510 bool SkPaintToGrPaintNoShader(GrRecordingContext* context,
511                               const GrColorInfo& dstColorInfo,
512                               const SkPaint& skPaint,
513                               GrPaint* grPaint) {
514     // Use a ptr to a nullptr to to indicate that the SkShader is ignored and not replaced.
515     std::unique_ptr<GrFragmentProcessor> nullShaderFP(nullptr);
516     return skpaint_to_grpaint_impl(context, dstColorInfo, skPaint, SkMatrix::I(), &nullShaderFP,
517                                    nullptr, grPaint);
518 }
519 
520 /** Blends the SkPaint's shader (or color if no shader) with a per-primitive color which must
521 be setup as a vertex attribute using the specified SkBlendMode. */
SkPaintToGrPaintWithXfermode(GrRecordingContext * context,const GrColorInfo & dstColorInfo,const SkPaint & skPaint,const SkMatrix & viewM,SkBlendMode primColorMode,GrPaint * grPaint)522 bool SkPaintToGrPaintWithXfermode(GrRecordingContext* context,
523                                   const GrColorInfo& dstColorInfo,
524                                   const SkPaint& skPaint,
525                                   const SkMatrix& viewM,
526                                   SkBlendMode primColorMode,
527                                   GrPaint* grPaint) {
528     return skpaint_to_grpaint_impl(context, dstColorInfo, skPaint, viewM, nullptr, &primColorMode,
529                                    grPaint);
530 }
531 
SkPaintToGrPaintWithTexture(GrRecordingContext * context,const GrColorInfo & dstColorInfo,const SkPaint & paint,const SkMatrix & viewM,std::unique_ptr<GrFragmentProcessor> fp,bool textureIsAlphaOnly,GrPaint * grPaint)532 bool SkPaintToGrPaintWithTexture(GrRecordingContext* context,
533                                  const GrColorInfo& dstColorInfo,
534                                  const SkPaint& paint,
535                                  const SkMatrix& viewM,
536                                  std::unique_ptr<GrFragmentProcessor> fp,
537                                  bool textureIsAlphaOnly,
538                                  GrPaint* grPaint) {
539     std::unique_ptr<GrFragmentProcessor> shaderFP;
540     if (textureIsAlphaOnly) {
541         if (const auto* shader = as_SB(paint.getShader())) {
542             shaderFP = shader->asFragmentProcessor(
543                     GrFPArgs(context, &viewM, paint.getFilterQuality(), &dstColorInfo));
544             if (!shaderFP) {
545                 return false;
546             }
547             std::unique_ptr<GrFragmentProcessor> fpSeries[] = { std::move(shaderFP), std::move(fp) };
548             shaderFP = GrFragmentProcessor::RunInSeries(fpSeries, 2);
549         } else {
550             shaderFP = GrFragmentProcessor::MakeInputPremulAndMulByOutput(std::move(fp));
551         }
552     } else {
553         if (paint.getColor4f().isOpaque()) {
554             shaderFP = GrFragmentProcessor::OverrideInput(std::move(fp), SK_PMColor4fWHITE, false);
555         } else {
556             shaderFP = GrFragmentProcessor::MulChildByInputAlpha(std::move(fp));
557         }
558     }
559 
560     return SkPaintToGrPaintReplaceShader(context, dstColorInfo, paint, std::move(shaderFP),
561                                          grPaint);
562 }
563 
564 ////////////////////////////////////////////////////////////////////////////////////////////////
565 
GrSkFilterQualityToGrFilterMode(int imageWidth,int imageHeight,SkFilterQuality paintFilterQuality,const SkMatrix & viewM,const SkMatrix & localM,bool sharpenMipmappedTextures,bool * doBicubic)566 GrSamplerState::Filter GrSkFilterQualityToGrFilterMode(int imageWidth, int imageHeight,
567                                                        SkFilterQuality paintFilterQuality,
568                                                        const SkMatrix& viewM,
569                                                        const SkMatrix& localM,
570                                                        bool sharpenMipmappedTextures,
571                                                        bool* doBicubic) {
572     *doBicubic = false;
573     if (imageWidth <= 1 && imageHeight <= 1) {
574         return GrSamplerState::Filter::kNearest;
575     }
576     switch (paintFilterQuality) {
577         case kNone_SkFilterQuality:
578             return GrSamplerState::Filter::kNearest;
579         case kLow_SkFilterQuality:
580             return GrSamplerState::Filter::kBilerp;
581         case kMedium_SkFilterQuality: {
582             SkMatrix matrix;
583             matrix.setConcat(viewM, localM);
584             // With sharp mips, we bias lookups by -0.5. That means our final LOD is >= 0 until the
585             // computed LOD is >= 0.5. At what scale factor does a texture get an LOD of 0.5?
586             //
587             // Want:  0       = log2(1/s) - 0.5
588             //        0.5     = log2(1/s)
589             //        2^0.5   = 1/s
590             //        1/2^0.5 = s
591             //        2^0.5/2 = s
592             SkScalar mipScale = sharpenMipmappedTextures ? SK_ScalarRoot2Over2 : SK_Scalar1;
593             if (matrix.getMinScale() < mipScale) {
594                 return GrSamplerState::Filter::kMipMap;
595             } else {
596                 // Don't trigger MIP level generation unnecessarily.
597                 return GrSamplerState::Filter::kBilerp;
598             }
599         }
600         case kHigh_SkFilterQuality: {
601             SkMatrix matrix;
602             matrix.setConcat(viewM, localM);
603             GrSamplerState::Filter textureFilterMode;
604             *doBicubic = GrBicubicEffect::ShouldUseBicubic(matrix, &textureFilterMode);
605             return textureFilterMode;
606         }
607     }
608     SkUNREACHABLE;
609 }
610