• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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/ganesh/SkGr.h"
9 
10 #include "include/core/SkAlphaType.h"
11 #include "include/core/SkBitmap.h"
12 #include "include/core/SkColorFilter.h"
13 #include "include/core/SkData.h"
14 #include "include/core/SkImageInfo.h"
15 #include "include/core/SkMatrix.h"
16 #include "include/core/SkPaint.h"
17 #include "include/core/SkPixelRef.h"
18 #include "include/core/SkPoint.h"
19 #include "include/core/SkRect.h"
20 #include "include/core/SkSize.h"
21 #include "include/core/SkSurfaceProps.h"
22 #include "include/effects/SkRuntimeEffect.h"
23 #include "include/gpu/ganesh/GrBackendSurface.h"
24 #include "include/gpu/ganesh/GrRecordingContext.h"
25 #include "include/gpu/ganesh/GrTypes.h"
26 #include "include/private/SkIDChangeListener.h"
27 #include "include/private/base/SkTPin.h"
28 #include "include/private/gpu/ganesh/GrTypesPriv.h"
29 #include "src/core/SkBlenderBase.h"
30 #include "src/core/SkMessageBus.h"
31 #include "src/core/SkPaintPriv.h"
32 #include "src/core/SkRuntimeEffectPriv.h"
33 #include "src/gpu/DitherUtils.h"
34 #include "src/gpu/ResourceKey.h"
35 #include "src/gpu/Swizzle.h"
36 #include "src/gpu/ganesh/GrCaps.h"
37 #include "src/gpu/ganesh/GrColorInfo.h"
38 #include "src/gpu/ganesh/GrColorSpaceXform.h"
39 #include "src/gpu/ganesh/GrFPArgs.h"
40 #include "src/gpu/ganesh/GrFragmentProcessor.h"
41 #include "src/gpu/ganesh/GrFragmentProcessors.h"
42 #include "src/gpu/ganesh/GrPaint.h"
43 #include "src/gpu/ganesh/GrProxyProvider.h"
44 #include "src/gpu/ganesh/GrRecordingContextPriv.h"
45 #include "src/gpu/ganesh/GrSurfaceProxy.h"
46 #include "src/gpu/ganesh/GrSurfaceProxyView.h"
47 #include "src/gpu/ganesh/GrTextureProxy.h"
48 #include "src/gpu/ganesh/GrXferProcessor.h"
49 #include "src/gpu/ganesh/effects/GrSkSLFP.h"
50 #include "src/gpu/ganesh/effects/GrTextureEffect.h"
51 #include "src/shaders/SkShaderBase.h"
52 
53 #include <optional>
54 #include <utility>
55 
56 class SkBlender;
57 class SkColorSpace;
58 enum SkColorType : int;
59 
GrMakeKeyFromImageID(skgpu::UniqueKey * key,uint32_t imageID,const SkIRect & imageBounds)60 void GrMakeKeyFromImageID(skgpu::UniqueKey* key, uint32_t imageID, const SkIRect& imageBounds) {
61     SkASSERT(key);
62     SkASSERT(imageID);
63     SkASSERT(!imageBounds.isEmpty());
64     static const skgpu::UniqueKey::Domain kImageIDDomain = skgpu::UniqueKey::GenerateDomain();
65     skgpu::UniqueKey::Builder builder(key, kImageIDDomain, 5, "Image");
66     builder[0] = imageID;
67     builder[1] = imageBounds.fLeft;
68     builder[2] = imageBounds.fTop;
69     builder[3] = imageBounds.fRight;
70     builder[4] = imageBounds.fBottom;
71 }
72 
73 ////////////////////////////////////////////////////////////////////////////////
74 
GrMakeUniqueKeyInvalidationListener(skgpu::UniqueKey * key,uint32_t contextID)75 sk_sp<SkIDChangeListener> GrMakeUniqueKeyInvalidationListener(skgpu::UniqueKey* key,
76                                                               uint32_t contextID) {
77     class Listener : public SkIDChangeListener {
78     public:
79         Listener(const skgpu::UniqueKey& key, uint32_t contextUniqueID)
80                 : fMsg(key, contextUniqueID) {}
81 
82         void changed() override {
83             SkMessageBus<skgpu::UniqueKeyInvalidatedMessage, uint32_t>::Post(fMsg);
84         }
85 
86     private:
87         skgpu::UniqueKeyInvalidatedMessage fMsg;
88     };
89 
90     auto listener = sk_make_sp<Listener>(*key, contextID);
91 
92     // We stick a SkData on the key that calls invalidateListener in its destructor.
93     auto invalidateListener = [](const void* ptr, void* /*context*/) {
94         auto listener = reinterpret_cast<const sk_sp<Listener>*>(ptr);
95         (*listener)->markShouldDeregister();
96         delete listener;
97     };
98     auto data = SkData::MakeWithProc(new sk_sp<Listener>(listener),
99                                      sizeof(sk_sp<Listener>),
100                                      invalidateListener,
101                                      nullptr);
102     SkASSERT(!key->getCustomData());
103     key->setCustomData(std::move(data));
104     return listener;
105 }
106 
GrCopyBaseMipMapToTextureProxy(GrRecordingContext * ctx,sk_sp<GrSurfaceProxy> baseProxy,GrSurfaceOrigin origin,std::string_view label,skgpu::Budgeted budgeted)107 sk_sp<GrSurfaceProxy> GrCopyBaseMipMapToTextureProxy(GrRecordingContext* ctx,
108                                                      sk_sp<GrSurfaceProxy> baseProxy,
109                                                      GrSurfaceOrigin origin,
110                                                      std::string_view label,
111                                                      skgpu::Budgeted budgeted) {
112     SkASSERT(baseProxy);
113 
114     // We don't allow this for promise proxies i.e. if they need mips they need to give them
115     // to us upfront.
116     if (baseProxy->isPromiseProxy()) {
117         return nullptr;
118     }
119     if (!ctx->priv().caps()->isFormatCopyable(baseProxy->backendFormat())) {
120         return nullptr;
121     }
122     auto copy = GrSurfaceProxy::Copy(ctx,
123                                      std::move(baseProxy),
124                                      origin,
125                                      skgpu::Mipmapped::kYes,
126                                      SkBackingFit::kExact,
127                                      budgeted,
128                                      label);
129     if (!copy) {
130         return nullptr;
131     }
132     SkASSERT(copy->asTextureProxy());
133     return copy;
134 }
135 
GrCopyBaseMipMapToView(GrRecordingContext * context,GrSurfaceProxyView src,skgpu::Budgeted budgeted)136 GrSurfaceProxyView GrCopyBaseMipMapToView(GrRecordingContext* context,
137                                           GrSurfaceProxyView src,
138                                           skgpu::Budgeted budgeted) {
139     auto origin = src.origin();
140     auto swizzle = src.swizzle();
141     auto proxy = src.refProxy();
142     return {GrCopyBaseMipMapToTextureProxy(
143                     context, proxy, origin, /*label=*/"CopyBaseMipMapToView", budgeted),
144             origin,
145             swizzle};
146 }
147 
adjust_mipmapped(skgpu::Mipmapped mipmapped,const SkBitmap & bitmap,const GrCaps * caps)148 static skgpu::Mipmapped adjust_mipmapped(skgpu::Mipmapped mipmapped,
149                                          const SkBitmap& bitmap,
150                                          const GrCaps* caps) {
151     if (!caps->mipmapSupport() || bitmap.dimensions().area() <= 1) {
152         return skgpu::Mipmapped::kNo;
153     }
154     return mipmapped;
155 }
156 
choose_bmp_texture_colortype(const GrCaps * caps,const SkBitmap & bitmap)157 static GrColorType choose_bmp_texture_colortype(const GrCaps* caps, const SkBitmap& bitmap) {
158     GrColorType ct = SkColorTypeToGrColorType(bitmap.info().colorType());
159     if (caps->getDefaultBackendFormat(ct, GrRenderable::kNo).isValid()) {
160         return ct;
161     }
162     return GrColorType::kRGBA_8888;
163 }
164 
make_bmp_proxy(GrProxyProvider * proxyProvider,const SkBitmap & bitmap,GrColorType ct,skgpu::Mipmapped mipmapped,SkBackingFit fit,skgpu::Budgeted budgeted)165 static sk_sp<GrTextureProxy> make_bmp_proxy(GrProxyProvider* proxyProvider,
166                                             const SkBitmap& bitmap,
167                                             GrColorType ct,
168                                             skgpu::Mipmapped mipmapped,
169                                             SkBackingFit fit,
170                                             skgpu::Budgeted budgeted) {
171     SkBitmap bmpToUpload;
172     if (ct != SkColorTypeToGrColorType(bitmap.info().colorType())) {
173         SkColorType skCT = GrColorTypeToSkColorType(ct);
174         if (!bmpToUpload.tryAllocPixels(bitmap.info().makeColorType(skCT)) ||
175             !bitmap.readPixels(bmpToUpload.pixmap())) {
176             return {};
177         }
178         bmpToUpload.setImmutable();
179     } else {
180         bmpToUpload = bitmap;
181     }
182     auto proxy = proxyProvider->createProxyFromBitmap(bmpToUpload, mipmapped, fit, budgeted);
183     SkASSERT(!proxy || mipmapped == skgpu::Mipmapped::kNo ||
184              proxy->mipmapped() == skgpu::Mipmapped::kYes);
185     return proxy;
186 }
187 
GrMakeCachedBitmapProxyView(GrRecordingContext * rContext,const SkBitmap & bitmap,std::string_view label,skgpu::Mipmapped mipmapped)188 std::tuple<GrSurfaceProxyView, GrColorType> GrMakeCachedBitmapProxyView(
189         GrRecordingContext* rContext,
190         const SkBitmap& bitmap,
191         std::string_view label,
192         skgpu::Mipmapped mipmapped) {
193     if (!bitmap.peekPixels(nullptr)) {
194         return {};
195     }
196 
197     GrProxyProvider* proxyProvider = rContext->priv().proxyProvider();
198     const GrCaps* caps = rContext->priv().caps();
199 
200     skgpu::UniqueKey key;
201     SkIPoint origin = bitmap.pixelRefOrigin();
202     SkIRect subset = SkIRect::MakePtSize(origin, bitmap.dimensions());
203     GrMakeKeyFromImageID(&key, bitmap.pixelRef()->getGenerationID(), subset);
204 
205     mipmapped = adjust_mipmapped(mipmapped, bitmap, caps);
206     GrColorType ct = choose_bmp_texture_colortype(caps, bitmap);
207 
208     auto installKey = [&](GrTextureProxy* proxy) {
209         auto listener = GrMakeUniqueKeyInvalidationListener(&key, proxyProvider->contextID());
210         bitmap.pixelRef()->addGenIDChangeListener(std::move(listener));
211         proxyProvider->assignUniqueKeyToProxy(key, proxy);
212     };
213 
214     sk_sp<GrTextureProxy> proxy = proxyProvider->findOrCreateProxyByUniqueKey(key);
215     if (!proxy) {
216         proxy = make_bmp_proxy(
217                 proxyProvider, bitmap, ct, mipmapped, SkBackingFit::kExact, skgpu::Budgeted::kYes);
218         if (!proxy) {
219             return {};
220         }
221         SkASSERT(mipmapped == skgpu::Mipmapped::kNo ||
222                  proxy->mipmapped() == skgpu::Mipmapped::kYes);
223         installKey(proxy.get());
224     }
225 
226     skgpu::Swizzle swizzle = caps->getReadSwizzle(proxy->backendFormat(), ct);
227     if (mipmapped == skgpu::Mipmapped::kNo || proxy->mipmapped() == skgpu::Mipmapped::kYes) {
228         return {{std::move(proxy), kTopLeft_GrSurfaceOrigin, swizzle}, ct};
229     }
230 
231     // We need a mipped proxy, but we found a proxy earlier that wasn't mipped. Thus we generate
232     // a new mipped surface and copy the original proxy into the base layer. We will then let
233     // the gpu generate the rest of the mips.
234     auto mippedProxy = GrCopyBaseMipMapToTextureProxy(
235             rContext, proxy, kTopLeft_GrSurfaceOrigin, /*label=*/"MakeCachedBitmapProxyView");
236     if (!mippedProxy) {
237         // We failed to make a mipped proxy with the base copied into it. This could have
238         // been from failure to make the proxy or failure to do the copy. Thus we will fall
239         // back to just using the non mipped proxy; See skbug.com/7094.
240         return {{std::move(proxy), kTopLeft_GrSurfaceOrigin, swizzle}, ct};
241     }
242     // In this case we are stealing the key from the original proxy which should only happen
243     // when we have just generated mipmaps for an originally unmipped proxy/texture. This
244     // means that all future uses of the key will access the mipmapped version. The texture
245     // backing the unmipped version will remain in the resource cache until the last texture
246     // proxy referencing it is deleted at which time it too will be deleted or recycled.
247     SkASSERT(proxy->getUniqueKey() == key);
248     proxyProvider->removeUniqueKeyFromProxy(proxy.get());
249     installKey(mippedProxy->asTextureProxy());
250     return {{std::move(mippedProxy), kTopLeft_GrSurfaceOrigin, swizzle}, ct};
251 }
252 
GrMakeUncachedBitmapProxyView(GrRecordingContext * rContext,const SkBitmap & bitmap,skgpu::Mipmapped mipmapped,SkBackingFit fit,skgpu::Budgeted budgeted)253 std::tuple<GrSurfaceProxyView, GrColorType> GrMakeUncachedBitmapProxyView(
254         GrRecordingContext* rContext,
255         const SkBitmap& bitmap,
256         skgpu::Mipmapped mipmapped,
257         SkBackingFit fit,
258         skgpu::Budgeted budgeted) {
259     GrProxyProvider* proxyProvider = rContext->priv().proxyProvider();
260     const GrCaps* caps = rContext->priv().caps();
261 
262     mipmapped = adjust_mipmapped(mipmapped, bitmap, caps);
263     GrColorType ct = choose_bmp_texture_colortype(caps, bitmap);
264 
265     if (auto proxy = make_bmp_proxy(proxyProvider, bitmap, ct, mipmapped, fit, budgeted)) {
266         skgpu::Swizzle swizzle = caps->getReadSwizzle(proxy->backendFormat(), ct);
267         SkASSERT(mipmapped == skgpu::Mipmapped::kNo ||
268                  proxy->mipmapped() == skgpu::Mipmapped::kYes);
269         return {{std::move(proxy), kTopLeft_GrSurfaceOrigin, swizzle}, ct};
270     }
271     return {};
272 }
273 ///////////////////////////////////////////////////////////////////////////////
274 
SkColorToPMColor4f(SkColor c,const GrColorInfo & colorInfo)275 SkPMColor4f SkColorToPMColor4f(SkColor c, const GrColorInfo& colorInfo) {
276     SkColor4f color = SkColor4f::FromColor(c);
277     if (auto* xform = colorInfo.colorSpaceXformFromSRGB()) {
278         color = xform->apply(color);
279     }
280     return color.premul();
281 }
282 
SkColor4fPrepForDst(SkColor4f color,const GrColorInfo & colorInfo)283 SkColor4f SkColor4fPrepForDst(SkColor4f color, const GrColorInfo& colorInfo) {
284     if (auto* xform = colorInfo.colorSpaceXformFromSRGB()) {
285         color = xform->apply(color);
286     }
287     return color;
288 }
289 
290 ///////////////////////////////////////////////////////////////////////////////
291 
blender_requires_shader(const SkBlender * blender)292 static inline bool blender_requires_shader(const SkBlender* blender) {
293     SkASSERT(blender);
294     std::optional<SkBlendMode> mode = as_BB(blender)->asBlendMode();
295     return !mode.has_value() || *mode != SkBlendMode::kDst;
296 }
297 
298 
299 #ifndef SK_IGNORE_GPU_DITHER
300 #ifdef SKIA_OHOS
make_dither_effect(GrRecordingContext * rContext,std::unique_ptr<GrFragmentProcessor> inputFP,float range,const GrCaps * caps)301  std::unique_ptr<GrFragmentProcessor> make_dither_effect(
302      GrRecordingContext* rContext,
303      std::unique_ptr<GrFragmentProcessor> inputFP,
304      float range,
305      const GrCaps* caps) {
306 #else
307 static std::unique_ptr<GrFragmentProcessor> make_dither_effect(
308         GrRecordingContext* rContext,
309         std::unique_ptr<GrFragmentProcessor> inputFP,
310         float range,
311         const GrCaps* caps) {
312 #endif // SKIA_OHOS
313     if (range == 0 || inputFP == nullptr) {
314         return inputFP;
315     }
316 
317     if (caps->avoidDithering()) {
318         return inputFP;
319     }
320 
321     // We used to use integer math on sk_FragCoord, when supported, and a fallback using floating
322     // point (on a 4x4 rather than 8x8 grid). Now we precompute a 8x8 table in a texture because
323     // it was shown to be significantly faster on several devices. Test was done with the following
324     // running in viewer with the stats layer enabled and looking at total frame time:
325     //      SkRandom r;
326     //      for (int i = 0; i < N; ++i) {
327     //          SkColor c[2] = {r.nextU(), r.nextU()};
328     //          SkPoint pts[2] = {{r.nextRangeScalar(0, 500), r.nextRangeScalar(0, 500)},
329     //                            {r.nextRangeScalar(0, 500), r.nextRangeScalar(0, 500)}};
330     //          SkPaint p;
331     //          p.setDither(true);
332     //          p.setShader(SkGradientShader::MakeLinear(pts, c, nullptr, 2, SkTileMode::kRepeat));
333     //          canvas->drawPaint(p);
334     //      }
335     // Device            GPU             N      no dither    int math dither   table dither
336     // Linux desktop     QuadroP1000     5000   304ms        400ms (1.31x)     383ms (1.26x)
337     // TecnoSpark3Pro    PowerVRGE8320   200    299ms        820ms (2.74x)     592ms (1.98x)
338     // Pixel 4           Adreno640       500    110ms        221ms (2.01x)     214ms (1.95x)
339     // Galaxy S20 FE     Mali-G77 MP11   600    165ms        360ms (2.18x)     260ms (1.58x)
340     static const SkBitmap gLUT = skgpu::MakeDitherLUT();
341     auto [tex, ct] = GrMakeCachedBitmapProxyView(
342             rContext, gLUT, /*label=*/"MakeDitherEffect", skgpu::Mipmapped::kNo);
343     if (!tex) {
344         return inputFP;
345     }
346     SkASSERT(ct == GrColorType::kAlpha_8);
347     GrSamplerState sampler(GrSamplerState::WrapMode::kRepeat, SkFilterMode::kNearest);
348     auto te = GrTextureEffect::Make(
349             std::move(tex), kPremul_SkAlphaType, SkMatrix::I(), sampler, *caps);
350     static const SkRuntimeEffect* effect = SkMakeRuntimeEffect(SkRuntimeEffect::MakeForShader,
351         "uniform half range;"
352         "uniform shader inputFP;"
353         "uniform shader table;"
354         "half4 main(float2 xy) {"
355             "half4 color = inputFP.eval(xy);"
356             "half value = table.eval(sk_FragCoord.xy).a - 0.5;" // undo the bias in the table
357             // For each color channel, add the random offset to the channel value and then clamp
358             // between 0 and alpha to keep the color premultiplied.
359             "return half4(clamp(color.rgb + value * range, 0.0, color.a), color.a);"
360         "}"
361     );
362     return GrSkSLFP::Make(effect, "Dither", /*inputFP=*/nullptr,
363                           GrSkSLFP::OptFlags::kPreservesOpaqueInput,
364                           "range", range,
365                           "inputFP", std::move(inputFP),
366                           "table", GrSkSLFP::IgnoreOptFlags(std::move(te)));
367 }
368 #endif
369 
370 static inline bool skpaint_to_grpaint_impl(
371         GrRecordingContext* context,
372         const GrColorInfo& dstColorInfo,
373         const SkPaint& skPaint,
374         const SkMatrix& ctm,
375         std::optional<std::unique_ptr<GrFragmentProcessor>> shaderFP,
376         SkBlender* primColorBlender,
377         const SkSurfaceProps& surfaceProps,
378         GrPaint* grPaint) {
379     // Convert SkPaint color to 4f format in the destination color space
380     SkColor4f origColor = SkColor4fPrepForDst(skPaint.getColor4f(), dstColorInfo);
381 
382     GrFPArgs fpArgs(context, &dstColorInfo, surfaceProps, GrFPArgs::Scope::kDefault);
383 
384     // Setup the initial color considering the shader, the SkPaint color, and the presence or not
385     // of per-vertex colors.
386     std::unique_ptr<GrFragmentProcessor> paintFP;
387     const bool gpProvidesShader = shaderFP.has_value() && !*shaderFP;
388     if (!primColorBlender || blender_requires_shader(primColorBlender)) {
389         if (shaderFP.has_value()) {
390             paintFP = std::move(*shaderFP);
391         } else {
392             if (const SkShaderBase* shader = as_SB(skPaint.getShader())) {
393                 paintFP = GrFragmentProcessors::Make(shader, fpArgs, ctm);
394                 if (paintFP == nullptr) {
395                     return false;
396                 }
397             }
398         }
399     }
400 
401     // Set this in below cases if the output of the shader/paint-color/paint-alpha/primXfermode is
402     // a known constant value. In that case we can simply apply a color filter during this
403     // conversion without converting the color filter to a GrFragmentProcessor.
404     bool applyColorFilterToPaintColor = false;
405     if (paintFP) {
406         if (primColorBlender) {
407             // There is a blend between the primitive color and the shader color. The shader sees
408             // the opaque paint color. The shader's output is blended using the provided mode by
409             // the primitive color. The blended color is then modulated by the paint's alpha.
410 
411             // The geometry processor will insert the primitive color to start the color chain, so
412             // the GrPaint color will be ignored.
413 
414             SkPMColor4f shaderInput = origColor.makeOpaque().premul();
415             paintFP = GrFragmentProcessor::OverrideInput(std::move(paintFP), shaderInput);
416             paintFP = GrFragmentProcessors::Make(as_BB(primColorBlender),
417                                                  /*srcFP=*/std::move(paintFP),
418                                                  /*dstFP=*/nullptr,
419                                                  fpArgs);
420             if (!paintFP) {
421                 return false;
422             }
423 
424             // We can ignore origColor here - alpha is unchanged by gamma
425             float paintAlpha = skPaint.getColor4f().fA;
426             if (1.0f != paintAlpha) {
427                 // No gamut conversion - paintAlpha is a (linear) alpha value, splatted to all
428                 // color channels. It's value should be treated as the same in ANY color space.
429                 paintFP = GrFragmentProcessor::ModulateRGBA(
430                         std::move(paintFP), {paintAlpha, paintAlpha, paintAlpha, paintAlpha});
431             }
432         } else {
433             float paintAlpha = skPaint.getColor4f().fA;
434             if (paintAlpha != 1.0f) {
435                 // This invokes the shader's FP tree with an opaque version of the paint color,
436                 // then multiplies the final result by the incoming (paint) alpha.
437                 // We're actually putting the *unpremul* paint color on the GrPaint. This is okay,
438                 // because the shader is supposed to see the original (opaque) RGB from the paint.
439                 // ApplyPaintAlpha then creates a valid premul color by applying the paint alpha.
440                 // Think of this as equivalent to (but faster than) putting origColor.premul() on
441                 // the GrPaint, and ApplyPaintAlpha unpremuling it before passing it to the child.
442                 paintFP = GrFragmentProcessor::ApplyPaintAlpha(std::move(paintFP));
443                 grPaint->setColor4f({origColor.fR, origColor.fG, origColor.fB, origColor.fA});
444             } else {
445                 // paintFP will ignore its input color, so we must disable coverage-as-alpha.
446                 // TODO(skbug:11942): The alternative would be to always use ApplyPaintAlpha, but
447                 // we'd need to measure the cost of that shader math against the CAA benefit.
448                 paintFP = GrFragmentProcessor::DisableCoverageAsAlpha(std::move(paintFP));
449                 grPaint->setColor4f(origColor.premul());
450             }
451         }
452     } else {
453         if (primColorBlender) {
454             // The primitive itself has color (e.g. interpolated vertex color) and this is what
455             // the GP will output. Thus, we must get the paint color in separately below as a color
456             // FP. This could be made more efficient if the relevant GPs used GrPaint color and
457             // took the SkBlender to apply with primitive color. As it stands changing the SkPaint
458             // color will break batches.
459             grPaint->setColor4f(SK_PMColor4fWHITE);  // won't be used.
460             if (blender_requires_shader(primColorBlender)) {
461                 paintFP = GrFragmentProcessor::MakeColor(origColor.makeOpaque().premul());
462                 paintFP = GrFragmentProcessors::Make(as_BB(primColorBlender),
463                                                      /*srcFP=*/std::move(paintFP),
464                                                      /*dstFP=*/nullptr,
465                                                      fpArgs);
466                 if (!paintFP) {
467                     return false;
468                 }
469             }
470 
471             // The paint's *alpha* is applied after the paint/primitive color blend:
472             // We can ignore origColor here - alpha is unchanged by gamma
473             float paintAlpha = skPaint.getColor4f().fA;
474             if (paintAlpha != 1.0f) {
475                 // No gamut conversion - paintAlpha is a (linear) alpha value, splatted to all
476                 // color channels. It's value should be treated as the same in ANY color space.
477                 paintFP = GrFragmentProcessor::ModulateRGBA(
478                         std::move(paintFP), {paintAlpha, paintAlpha, paintAlpha, paintAlpha});
479             }
480         } else {
481             // No shader, no primitive color.
482             grPaint->setColor4f(origColor.premul());
483             // We can do this if there isn't a GP that is acting as the shader.
484             applyColorFilterToPaintColor = !gpProvidesShader;
485         }
486     }
487 
488     SkColorFilter* colorFilter = skPaint.getColorFilter();
489     if (colorFilter) {
490         if (applyColorFilterToPaintColor) {
491             SkColorSpace* dstCS = dstColorInfo.colorSpace();
492             grPaint->setColor4f(colorFilter->filterColor4f(origColor, dstCS, dstCS).premul());
493         } else {
494             auto [success, fp] = GrFragmentProcessors::Make(
495                     context, colorFilter, std::move(paintFP), dstColorInfo, surfaceProps);
496             if (!success) {
497                 return false;
498             }
499             paintFP = std::move(fp);
500         }
501     }
502 
503     if (auto maskFilter = skPaint.getMaskFilter()) {
504         if (auto mfFP = GrFragmentProcessors::Make(maskFilter, fpArgs, ctm)) {
505             grPaint->setCoverageFragmentProcessor(std::move(mfFP));
506         }
507     }
508 
509 #ifndef SK_IGNORE_GPU_DITHER
510     SkColorType ct = GrColorTypeToSkColorType(dstColorInfo.colorType());
511     if (paintFP != nullptr && (
512             surfaceProps.isAlwaysDither() || SkPaintPriv::ShouldDither(skPaint, ct))) {
513         float ditherRange = skgpu::DitherRangeForConfig(ct);
514         paintFP = make_dither_effect(
515                 context, std::move(paintFP), ditherRange, context->priv().caps());
516     }
517 #endif
518 
519     // Note that for the final blend onto the canvas, we should prefer to use the GrXferProcessor
520     // instead of a SkBlendModeBlender to perform the blend. The Xfer processor is able to perform
521     // coefficient-based blends directly, without readback. This will be much more efficient.
522     if (auto bm = skPaint.asBlendMode()) {
523         // When the xfermode is null on the SkPaint (meaning kSrcOver) we need the XPFactory field
524         // on the GrPaint to also be null (also kSrcOver).
525         SkASSERT(!grPaint->getXPFactory());
526         if (bm.value() != SkBlendMode::kSrcOver) {
527             grPaint->setXPFactory(GrXPFactory::FromBlendMode(bm.value()));
528         }
529     } else {
530         // Apply a custom blend against the surface color, and force the XP to kSrc so that the
531         // computed result is applied directly to the canvas while still honoring the alpha.
532         paintFP = GrFragmentProcessors::Make(as_BB(skPaint.getBlender()),
533                                              std::move(paintFP),
534                                              GrFragmentProcessor::SurfaceColor(),
535                                              fpArgs);
536         if (!paintFP) {
537             return false;
538         }
539         grPaint->setXPFactory(GrXPFactory::FromBlendMode(SkBlendMode::kSrc));
540     }
541 
542     if (GrColorTypeClampType(dstColorInfo.colorType()) == GrClampType::kManual) {
543         if (paintFP != nullptr) {
544             paintFP = GrFragmentProcessor::ClampOutput(std::move(paintFP));
545         } else {
546             auto color = grPaint->getColor4f();
547             grPaint->setColor4f({SkTPin(color.fR, 0.f, 1.f),
548                                  SkTPin(color.fG, 0.f, 1.f),
549                                  SkTPin(color.fB, 0.f, 1.f),
550                                  SkTPin(color.fA, 0.f, 1.f)});
551         }
552     }
553 
554     if (paintFP) {
555         grPaint->setColorFragmentProcessor(std::move(paintFP));
556     }
557 
558     return true;
559 }
560 
561 bool SkPaintToGrPaint(GrRecordingContext* context,
562                       const GrColorInfo& dstColorInfo,
563                       const SkPaint& skPaint,
564                       const SkMatrix& ctm,
565                       const SkSurfaceProps& surfaceProps,
566                       GrPaint* grPaint) {
567     return skpaint_to_grpaint_impl(context,
568                                    dstColorInfo,
569                                    skPaint,
570                                    ctm,
571                                    /*shaderFP=*/std::nullopt,
572                                    /*primColorBlender=*/nullptr,
573                                    surfaceProps,
574                                    grPaint);
575 }
576 
577 /** Replaces the SkShader (if any) on skPaint with the passed in GrFragmentProcessor. */
578 bool SkPaintToGrPaintReplaceShader(GrRecordingContext* context,
579                                    const GrColorInfo& dstColorInfo,
580                                    const SkPaint& skPaint,
581                                    const SkMatrix& ctm,
582                                    std::unique_ptr<GrFragmentProcessor> shaderFP,
583                                    const SkSurfaceProps& surfaceProps,
584                                    GrPaint* grPaint) {
585     return skpaint_to_grpaint_impl(context,
586                                    dstColorInfo,
587                                    skPaint,
588                                    ctm,
589                                    std::move(shaderFP),
590                                    /*primColorBlender=*/nullptr,
591                                    surfaceProps,
592                                    grPaint);
593 }
594 
595 /** Blends the SkPaint's shader (or color if no shader) with a per-primitive color which must
596     be setup as a vertex attribute using the specified SkBlender. */
597 bool SkPaintToGrPaintWithBlend(GrRecordingContext* context,
598                                const GrColorInfo& dstColorInfo,
599                                const SkPaint& skPaint,
600                                const SkMatrix& ctm,
601                                SkBlender* primColorBlender,
602                                const SkSurfaceProps& surfaceProps,
603                                GrPaint* grPaint) {
604     return skpaint_to_grpaint_impl(context,
605                                    dstColorInfo,
606                                    skPaint,
607                                    ctm,
608                                    /*shaderFP=*/std::nullopt,
609                                    primColorBlender,
610                                    surfaceProps,
611                                    grPaint);
612 }
613