Debian Codegraph @

src/gpu/graphite/KeyHelpers.cpp

raw ◀ ▶
1 Debian patch touch this file
1 /*
2 * Copyright 2022 Google LLC
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/graphite/KeyHelpers.h"
9
10 #include "include/core/SkColorFilter.h"
11 #include "include/core/SkColorSpace.h"
12 #include "include/core/SkData.h"
13 #include "include/core/SkImageInfo.h"
14 #include "include/core/SkM44.h"
15 #include "include/core/SkScalar.h"
16 #include "include/effects/SkRuntimeEffect.h"
17 #include "include/gpu/graphite/Surface.h"
18 #include "src/base/SkHalf.h"
19 #include "src/core/SkBlendModeBlender.h"
20 #include "src/core/SkBlenderBase.h"
21 #include "src/core/SkColorSpacePriv.h"
22 #include "src/core/SkDebugUtils.h"
23 #include "src/core/SkRuntimeBlender.h"
24 #include "src/core/SkRuntimeEffectPriv.h"
25 #include "src/core/SkYUVMath.h"
26 #include "src/effects/colorfilters/SkBlendModeColorFilter.h"
27 #include "src/effects/colorfilters/SkColorFilterBase.h"
28 #include "src/effects/colorfilters/SkColorSpaceXformColorFilter.h"
29 #include "src/effects/colorfilters/SkComposeColorFilter.h"
30 #include "src/effects/colorfilters/SkGaussianColorFilter.h"
31 #include "src/effects/colorfilters/SkMatrixColorFilter.h"
32 #include "src/effects/colorfilters/SkRuntimeColorFilter.h"
33 #include "src/effects/colorfilters/SkTableColorFilter.h"
34 #include "src/effects/colorfilters/SkWorkingFormatColorFilter.h"
35 #include "src/gpu/Blend.h"
36 #include "src/gpu/DitherUtils.h"
37 #include "src/gpu/Swizzle.h"
38 #include "src/gpu/graphite/Caps.h"
39 #include "src/gpu/graphite/DrawContext.h"
40 #include "src/gpu/graphite/Image_Base_Graphite.h"
41 #include "src/gpu/graphite/Image_Graphite.h"
42 #include "src/gpu/graphite/Image_YUVA_Graphite.h"
43 #include "src/gpu/graphite/KeyContext.h"
44 #include "src/gpu/graphite/KeyHelpers.h"
45 #include "src/gpu/graphite/Log.h"
46 #include "src/gpu/graphite/PaintParams.h"
47 #include "src/gpu/graphite/PaintParamsKey.h"
48 #include "src/gpu/graphite/PipelineData.h"
49 #include "src/gpu/graphite/ReadSwizzle.h"
50 #include "src/gpu/graphite/RecorderPriv.h"
51 #include "src/gpu/graphite/ResourceProvider.h"
52 #include "src/gpu/graphite/RuntimeEffectDictionary.h"
53 #include "src/gpu/graphite/ShaderCodeDictionary.h"
54 #include "src/gpu/graphite/Surface_Graphite.h"
55 #include "src/gpu/graphite/Texture.h"
56 #include "src/gpu/graphite/TextureProxy.h"
57 #include "src/gpu/graphite/TextureProxyView.h"
58 #include "src/gpu/graphite/TextureUtils.h"
59 #include "src/gpu/graphite/Uniform.h"
60 #include "src/gpu/graphite/UniformManager.h"
61 #include "src/image/SkImage_Base.h"
62 #include "src/shaders/SkBlendShader.h"
63 #include "src/shaders/SkColorFilterShader.h"
64 #include "src/shaders/SkColorShader.h"
65 #include "src/shaders/SkCoordClampShader.h"
66 #include "src/shaders/SkEmptyShader.h"
67 #include "src/shaders/SkImageShader.h"
68 #include "src/shaders/SkLocalMatrixShader.h"
69 #include "src/shaders/SkPerlinNoiseShaderImpl.h"
70 #include "src/shaders/SkPerlinNoiseShaderType.h"
71 #include "src/shaders/SkPictureShader.h"
72 #include "src/shaders/SkRuntimeShader.h"
73 #include "src/shaders/SkShaderBase.h"
74 #include "src/shaders/SkTransformShader.h"
75 #include "src/shaders/SkTriColorShader.h"
76 #include "src/shaders/SkWorkingColorSpaceShader.h"
77 #include "src/shaders/gradients/SkConicalGradient.h"
78 #include "src/shaders/gradients/SkLinearGradient.h"
79 #include "src/shaders/gradients/SkRadialGradient.h"
80 #include "src/shaders/gradients/SkSweepGradient.h"
81
82 using namespace skia_private;
83
84 namespace skgpu::graphite {
85
86 //--------------------------------------------------------------------------------------------------
87
88 namespace {
89
90 // Automatically calls beginStruct() with the required alignment and endStruct() when it is deleted.
91 // Automatically registers uniform expectations in debug builds.
92 class ScopedUniformWriter {
93 public:
94 ScopedUniformWriter(const KeyContext& keyContext, BuiltInCodeSnippetID codeSnippetID)
95 : ScopedUniformWriter(keyContext.pipelineDataGatherer(),
96 keyContext.dict()->getEntry(codeSnippetID)) {}
97
98 ~ScopedUniformWriter() {
99 if (fGatherer) {
100 fGatherer->endStruct();
101 }
102 }
103
104 private:
105 ScopedUniformWriter(PipelineDataGatherer* gatherer, const ShaderSnippet* snippet)
106 #if defined(SK_DEBUG)
107 : fValidator(gatherer, snippet->fUniforms, SkToBool(snippet->fUniformStructName))
108 #endif
109 {
110 if (snippet->fUniformStructName) {
111 gatherer->beginStruct(snippet->fRequiredAlignment);
112 fGatherer = gatherer;
113 } else {
114 fGatherer = nullptr;
115 }
116 }
117
118 PipelineDataGatherer* fGatherer;
119 SkDEBUGCODE(UniformExpectationsValidator fValidator;)
120 };
121
122 #define BEGIN_WRITE_UNIFORMS(keyContext, codeSnippetID) \
123 ScopedUniformWriter scope{keyContext, codeSnippetID};
124
125 void add_solid_uniform_data(const KeyContext& keyContext, const SkPMColor4f& premulColor) {
126 BEGIN_WRITE_UNIFORMS(keyContext, BuiltInCodeSnippetID::kSolidColorShader)
127 keyContext.pipelineDataGatherer()->write(premulColor);
128 }
129
130 } // anonymous namespace
131
132 void SolidColorShaderBlock::AddBlock(const KeyContext& keyContext, const SkPMColor4f& premulColor) {
133 add_solid_uniform_data(keyContext, premulColor);
134 keyContext.paintParamsKeyBuilder()->addBlock(BuiltInCodeSnippetID::kSolidColorShader);
135 }
136
137 //--------------------------------------------------------------------------------------------------
138
139 namespace {
140
141 void add_rgb_paint_color_uniform_data(const KeyContext& keyContext) {
142 BEGIN_WRITE_UNIFORMS(keyContext, BuiltInCodeSnippetID::kRGBPaintColor)
143 keyContext.pipelineDataGatherer()->writePaintColor(keyContext.paintColor());
144 }
145
146 void add_alpha_only_paint_color_uniform_data(const KeyContext& keyContext) {
147 BEGIN_WRITE_UNIFORMS(keyContext, BuiltInCodeSnippetID::kAlphaOnlyPaintColor)
148 keyContext.pipelineDataGatherer()->writePaintColor(keyContext.paintColor());
149 }
150
151 } // anonymous namespace
152
153 void RGBPaintColorBlock::AddBlock(const KeyContext& keyContext) {
154 add_rgb_paint_color_uniform_data(keyContext);
155 keyContext.paintParamsKeyBuilder()->addBlock(BuiltInCodeSnippetID::kRGBPaintColor);
156 }
157
158 void AlphaOnlyPaintColorBlock::AddBlock(const KeyContext& keyContext) {
159 add_alpha_only_paint_color_uniform_data(keyContext);
160 keyContext.paintParamsKeyBuilder()->addBlock(BuiltInCodeSnippetID::kAlphaOnlyPaintColor);
161 }
162
163 //--------------------------------------------------------------------------------------------------
164
165 namespace {
166
167 void add_gradient_preamble(const GradientShaderBlocks::GradientData& gradData,
168 PipelineDataGatherer* gatherer) {
169 constexpr int kInternalStopLimit = GradientShaderBlocks::GradientData::kNumInternalStorageStops;
170
171 if (gradData.fNumStops <= kInternalStopLimit) {
172 if (gradData.fNumStops <= 4) {
173 // Round up to 4 stops.
174 gatherer->writeArray(SkSpan{gradData.fColors, 4});
175 gatherer->write(gradData.fOffsets[0]);
176 } else if (gradData.fNumStops <= 8) {
177 // Round up to 8 stops.
178 gatherer->writeArray(SkSpan{gradData.fColors, 8});
179 gatherer->writeArray(SkSpan{gradData.fOffsets, 2});
180 } else {
181 // Did kNumInternalStorageStops change?
182 SkUNREACHABLE;
183 }
184 }
185 }
186
187 // All the gradients share a common postamble of:
188 // numStops - for texture-based gradients
189 // tilemode
190 // colorSpace
191 // doUnPremul
192 void add_gradient_postamble(const GradientShaderBlocks::GradientData& gradData,
193 int bufferOffset,
194 PipelineDataGatherer* gatherer) {
195 using ColorSpace = SkGradient::Interpolation::ColorSpace;
196
197 constexpr int kInternalStopLimit = GradientShaderBlocks::GradientData::kNumInternalStorageStops;
198
199 static_assert(static_cast<int>(ColorSpace::kLab) == 2);
200 static_assert(static_cast<int>(ColorSpace::kOKLab) == 3);
201 static_assert(static_cast<int>(ColorSpace::kOKLabGamutMap) == 4);
202 static_assert(static_cast<int>(ColorSpace::kLCH) == 5);
203 static_assert(static_cast<int>(ColorSpace::kOKLCH) == 6);
204 static_assert(static_cast<int>(ColorSpace::kOKLCHGamutMap) == 7);
205 static_assert(static_cast<int>(ColorSpace::kHSL) == 9);
206 static_assert(static_cast<int>(ColorSpace::kHWB) == 10);
207
208 bool inputPremul = static_cast<bool>(gradData.fInterpolation.fInPremul);
209
210 if (gradData.fNumStops > kInternalStopLimit) {
211 gatherer->write(gradData.fNumStops);
212 if (gradData.fUseStorageBuffer) {
213 gatherer->write(bufferOffset);
214 }
215 }
216
217 gatherer->write(static_cast<int>(gradData.fTM));
218 gatherer->write(static_cast<int>(gradData.fInterpolation.fColorSpace));
219 gatherer->write(static_cast<int>(inputPremul));
220 }
221
222 void add_linear_gradient_uniform_data(const KeyContext& keyContext,
223 BuiltInCodeSnippetID codeSnippetID,
224 const GradientShaderBlocks::GradientData& gradData,
225 int bufferOffset) {
226 BEGIN_WRITE_UNIFORMS(keyContext, codeSnippetID)
227
228 add_gradient_preamble(gradData, keyContext.pipelineDataGatherer());
229 add_gradient_postamble(gradData, bufferOffset, keyContext.pipelineDataGatherer());
230 }
231
232 void add_radial_gradient_uniform_data(const KeyContext& keyContext,
233 BuiltInCodeSnippetID codeSnippetID,
234 const GradientShaderBlocks::GradientData& gradData,
235 int bufferOffset) {
236 BEGIN_WRITE_UNIFORMS(keyContext, codeSnippetID)
237
238 add_gradient_preamble(gradData, keyContext.pipelineDataGatherer());
239 add_gradient_postamble(gradData, bufferOffset, keyContext.pipelineDataGatherer());
240 }
241
242 void add_sweep_gradient_uniform_data(const KeyContext& keyContext,
243 BuiltInCodeSnippetID codeSnippetID,
244 const GradientShaderBlocks::GradientData& gradData,
245 int bufferOffset) {
246 BEGIN_WRITE_UNIFORMS(keyContext, codeSnippetID)
247
248 add_gradient_preamble(gradData, keyContext.pipelineDataGatherer());
249 keyContext.pipelineDataGatherer()->write(gradData.fBias);
250 keyContext.pipelineDataGatherer()->write(gradData.fScale);
251 add_gradient_postamble(gradData, bufferOffset, keyContext.pipelineDataGatherer());
252 }
253
254 void add_conical_gradient_uniform_data(const KeyContext& keyContext,
255 BuiltInCodeSnippetID codeSnippetID,
256 const GradientShaderBlocks::GradientData& gradData,
257 int bufferOffset) {
258 BEGIN_WRITE_UNIFORMS(keyContext, codeSnippetID)
259
260 float dRadius = gradData.fRadii[1] - gradData.fRadii[0];
261 bool isRadial = SkPoint::Distance(gradData.fPoints[1], gradData.fPoints[0])
262 < SK_ScalarNearlyZero;
263
264 // When a == 0, encode invA == 1 for radial case, and invA == 0 for linear edge case.
265 float a = 0;
266 float invA = 1;
267 if (!isRadial) {
268 a = 1 - dRadius * dRadius;
269 if (std::abs(a) > SK_ScalarNearlyZero) {
270 invA = 1.0 / (2.0 * a);
271 } else {
272 a = 0;
273 invA = 0;
274 }
275 } else {
276 // Since radius0 is being scaled by 1 / dRadius, and the original radius
277 // is always positive, this gives us the original sign of dRadius.
278 dRadius = gradData.fRadii[0] > 0 ? 1 : -1;
279 }
280
281 add_gradient_preamble(gradData, keyContext.pipelineDataGatherer());
282 keyContext.pipelineDataGatherer()->write(gradData.fRadii[0]);
283 keyContext.pipelineDataGatherer()->write(dRadius);
284 keyContext.pipelineDataGatherer()->write(a);
285 keyContext.pipelineDataGatherer()->write(invA);
286 add_gradient_postamble(gradData, bufferOffset, keyContext.pipelineDataGatherer());
287 }
288
289 } // anonymous namespace
290
291 // Writes the color and offset data directly in the gatherer gradient buffer and returns the
•292 // offset the data begins at in the buffer.
293 //
294 // Returns a negative offset to signal failure, in which case the paint key must be poisoned
295 // to drop the draw.
296 static int write_color_and_offset_bufdata(int numStops,
297 const SkPMColor4f* colors,
298 const float* offsets,
299 const SkGradientBaseShader* shader,
300 FloatStorageManager* floatStorageManager) {
301 auto [dstData, bufferOffset] = floatStorageManager->allocateGradientData(numStops, shader);
•302 if (dstData) {
303 SkASSERT(bufferOffset >= 0);
304 // Data doesn't already exist so we need to write it.
305 // Writes all offset data, then color data. This way when binary searching through the
306 // offsets, there is better cache locality.
307 for (int i = 0, colorIdx = numStops; i < numStops; i++, colorIdx+=4) {
308 float offset = offsets ? offsets[i] : SkIntToFloat(i) / (numStops - 1);
309 SkASSERT(offset >= 0.0f && offset <= 1.0f);
310
311 dstData[i] = offset;
312 dstData[colorIdx + 0] = colors[i].fR;
313 dstData[colorIdx + 1] = colors[i].fG;
314 dstData[colorIdx + 2] = colors[i].fB;
315 dstData[colorIdx + 3] = colors[i].fA;
316 }
317 }
318
319 return bufferOffset;
320 }
321
322 GradientShaderBlocks::GradientData::GradientData(SkShaderBase::GradientType type,
323 int numStops,
324 bool useStorageBuffer)
325 : fType(type)
326 , fPoints{{0.0f, 0.0f}, {0.0f, 0.0f}}
327 , fRadii{0.0f, 0.0f}
328 , fBias(0.0f)
329 , fScale(0.0f)
330 , fTM(SkTileMode::kClamp)
331 , fNumStops(numStops)
332 , fUseStorageBuffer(useStorageBuffer)
333 , fSrcColors(nullptr)
334 , fSrcOffsets(nullptr) {
335 sk_bzero(fColors, sizeof(fColors));
336 sk_bzero(fOffsets, sizeof(fOffsets));
337 }
338
339 GradientShaderBlocks::GradientData::GradientData(SkShaderBase::GradientType type,
340 SkPoint point0, SkPoint point1,
341 float radius0, float radius1,
342 float bias, float scale,
343 SkTileMode tm,
344 int numStops,
345 const SkPMColor4f* colors,
346 const float* offsets,
347 const SkGradientBaseShader* shader,
348 sk_sp<TextureProxy> colorsAndOffsetsProxy,
349 bool useStorageBuffer,
350 const SkGradient::Interpolation& interp)
351 : fType(type)
352 , fBias(bias)
353 , fScale(scale)
354 , fTM(tm)
355 , fNumStops(numStops)
356 , fUseStorageBuffer(useStorageBuffer)
357 , fSrcColors(colors)
358 , fSrcOffsets(offsets)
359 , fSrcShader(shader)
360 , fInterpolation(interp) {
361 SkASSERT(fNumStops >= 1);
362
363 fPoints[0] = point0;
364 fPoints[1] = point1;
365 fRadii[0] = radius0;
366 fRadii[1] = radius1;
367
368 if (fNumStops <= kNumInternalStorageStops) {
369 memcpy(fColors, colors, fNumStops * sizeof(SkColor4f));
370 float* rawOffsets = fOffsets[0].ptr();
371 if (offsets) {
372 memcpy(rawOffsets, offsets, fNumStops * sizeof(float));
373 } else {
374 for (int i = 0; i < fNumStops; ++i) {
375 rawOffsets[i] = SkIntToFloat(i) / (fNumStops-1);
376 }
377 }
378
379 // Extend the colors and offset, if necessary, to fill out the arrays.
380 // The unrolled binary search implementation assumes excess stops match the last real value.
381 for (int i = fNumStops; i < kNumInternalStorageStops; ++i) {
382 fColors[i] = fColors[fNumStops-1];
383 rawOffsets[i] = rawOffsets[fNumStops-1];
384 }
385 } else {
386 if (!fUseStorageBuffer) {
387 fColorsAndOffsetsProxy = std::move(colorsAndOffsetsProxy);
388 SkASSERT(fColorsAndOffsetsProxy);
389 }
390 }
391 }
392
393 void GradientShaderBlocks::AddBlock(const KeyContext& keyContext, const GradientData& gradData) {
394 int bufferOffset = 0;
•395 if (gradData.fNumStops > GradientData::kNumInternalStorageStops && keyContext.recorder()) {
396 bool hasStorage;
397 if (gradData.fUseStorageBuffer) {
398 bufferOffset = write_color_and_offset_bufdata(gradData.fNumStops,
399 gradData.fSrcColors,
400 gradData.fSrcOffsets,
401 gradData.fSrcShader,
•402 keyContext.floatStorageManager());
403 hasStorage = bufferOffset >= 0;
404 } else {
405 keyContext.pipelineDataGatherer()->add(gradData.fColorsAndOffsetsProxy,
•406 {SkFilterMode::kNearest, SkTileMode::kClamp});
407 hasStorage = SkToBool(gradData.fColorsAndOffsetsProxy);
408 }
409
410 if (!hasStorage) {
411 keyContext.paintParamsKeyBuilder()->addErrorBlock();
412 SKGPU_LOG_W("Couldn't upload large gradient color stop data");
413 return;
414 }
415 }
416
417 BuiltInCodeSnippetID codeSnippetID = BuiltInCodeSnippetID::kSolidColorShader;
418 switch (gradData.fType) {
419 case SkShaderBase::GradientType::kLinear:
420 codeSnippetID =
421 gradData.fNumStops <= 4 ? BuiltInCodeSnippetID::kLinearGradientShader4
422 : gradData.fNumStops <= 8 ? BuiltInCodeSnippetID::kLinearGradientShader8
423 : gradData.fUseStorageBuffer
424 ? BuiltInCodeSnippetID::kLinearGradientShaderBuffer
425 : BuiltInCodeSnippetID::kLinearGradientShaderTexture;
426 add_linear_gradient_uniform_data(keyContext, codeSnippetID, gradData, bufferOffset);
427 break;
428 case SkShaderBase::GradientType::kRadial:
429 codeSnippetID =
430 gradData.fNumStops <= 4 ? BuiltInCodeSnippetID::kRadialGradientShader4
431 : gradData.fNumStops <= 8 ? BuiltInCodeSnippetID::kRadialGradientShader8
432 : gradData.fUseStorageBuffer
433 ? BuiltInCodeSnippetID::kRadialGradientShaderBuffer
434 : BuiltInCodeSnippetID::kRadialGradientShaderTexture;
435 add_radial_gradient_uniform_data(keyContext, codeSnippetID, gradData, bufferOffset);
436 break;
437 case SkShaderBase::GradientType::kSweep:
438 codeSnippetID =
439 gradData.fNumStops <= 4 ? BuiltInCodeSnippetID::kSweepGradientShader4
440 : gradData.fNumStops <= 8 ? BuiltInCodeSnippetID::kSweepGradientShader8
441 : gradData.fUseStorageBuffer
442 ? BuiltInCodeSnippetID::kSweepGradientShaderBuffer
443 : BuiltInCodeSnippetID::kSweepGradientShaderTexture;
444 add_sweep_gradient_uniform_data(keyContext, codeSnippetID, gradData, bufferOffset);
445 break;
446 case SkShaderBase::GradientType::kConical:
447 codeSnippetID =
448 gradData.fNumStops <= 4 ? BuiltInCodeSnippetID::kConicalGradientShader4
449 : gradData.fNumStops <= 8 ? BuiltInCodeSnippetID::kConicalGradientShader8
450 : gradData.fUseStorageBuffer
451 ? BuiltInCodeSnippetID::kConicalGradientShaderBuffer
452 : BuiltInCodeSnippetID::kConicalGradientShaderTexture;
453 add_conical_gradient_uniform_data(keyContext, codeSnippetID, gradData, bufferOffset);
454 break;
455 case SkShaderBase::GradientType::kNone:
456 default:
457 SkDEBUGFAIL("Expected a gradient shader, but it wasn't one.");
458 break;
459 }
460
461 keyContext.paintParamsKeyBuilder()->addBlock(codeSnippetID);
462 }
463
464 //--------------------------------------------------------------------------------------------------
465
466 void LocalMatrixShaderBlock::BeginBlock(const KeyContext& keyContext,
467 const LMShaderData& lmShaderData) {
468 const SkMatrix& m = lmShaderData.fLocalMatrix;
469
470 if (lmShaderData.fLocalMatrix.hasPerspective()) {
471 // Perspective local matrices are rare enough and add enough extra instructions that it's
472 // worth specializing since it has to perform a per-pixel division.
473 keyContext.paintParamsKeyBuilder()->beginBlock(
474 BuiltInCodeSnippetID::kLocalMatrixShaderPersp);
475 BEGIN_WRITE_UNIFORMS(keyContext, BuiltInCodeSnippetID::kLocalMatrixShaderPersp)
476 keyContext.pipelineDataGatherer()->write(m);
477 } else {
478 // For an affine 2D transform, we only need to upload the upper 2x2 and XY translation.
479 keyContext.paintParamsKeyBuilder()->beginBlock(BuiltInCodeSnippetID::kLocalMatrixShader);
480
481 BEGIN_WRITE_UNIFORMS(keyContext, BuiltInCodeSnippetID::kLocalMatrixShader)
482 // The upper 2x2 is expected to be in column major order, but SkMatrix is 3x3 row major.
483 keyContext.pipelineDataGatherer()->write(SkV4{m.getScaleX(), m.getSkewY(),
484 m.getSkewX(), m.getScaleY()});
485 keyContext.pipelineDataGatherer()->write(SkV2{m.getTranslateX(), m.getTranslateY()});
486 }
487 }
488
489 //--------------------------------------------------------------------------------------------------
490
491 namespace {
492
493 void add_image_uniform_data(const KeyContext& keyContext,
494 const ImageShaderBlock::ImageData& imgData) {
495 SkASSERT(!imgData.fSampling.useCubic);
496 BEGIN_WRITE_UNIFORMS(keyContext, BuiltInCodeSnippetID::kImageShader)
497
498 keyContext.pipelineDataGatherer()->write(SkSize::Make(1.f/imgData.fImgSize.width(),
499 1.f/imgData.fImgSize.height()));
500 keyContext.pipelineDataGatherer()->write(imgData.fSubset);
501 keyContext.pipelineDataGatherer()->write(SkTo<int>(imgData.fTileModes.first));
502 keyContext.pipelineDataGatherer()->write(SkTo<int>(imgData.fTileModes.second));
503 keyContext.pipelineDataGatherer()->write(SkTo<int>(imgData.fSampling.filter));
504 }
505
506 void add_clamp_image_uniform_data(const KeyContext& keyContext,
507 const ImageShaderBlock::ImageData& imgData) {
508 SkASSERT(!imgData.fSampling.useCubic);
509 BEGIN_WRITE_UNIFORMS(keyContext, BuiltInCodeSnippetID::kImageShaderClamp)
510
511 keyContext.pipelineDataGatherer()->write(SkSize::Make(1.f/imgData.fImgSize.width(),
512 1.f/imgData.fImgSize.height()));
513
514 // Matches GrTextureEffect::kLinearInset, to make sure we don't touch an outer row or column
515 // with a weight of 0 when linear filtering.
516 const float kLinearInset = 0.5f + 0.00001f;
517
518 // The subset should clamp texel coordinates to an inset subset to prevent sampling neighboring
519 // texels when coords fall exactly at texel boundaries.
520 SkRect subsetInsetClamp = imgData.fSubset;
521 if (imgData.fSampling.filter == SkFilterMode::kNearest) {
522 subsetInsetClamp.roundOut(&subsetInsetClamp);
523 }
524 subsetInsetClamp.inset(kLinearInset, kLinearInset);
525 keyContext.pipelineDataGatherer()->write(subsetInsetClamp);
526 }
527
528 void add_cubic_image_uniform_data(const KeyContext& keyContext,
529 const ImageShaderBlock::ImageData& imgData) {
530 SkASSERT(imgData.fSampling.useCubic);
531 BEGIN_WRITE_UNIFORMS(keyContext, BuiltInCodeSnippetID::kCubicImageShader)
532
533 keyContext.pipelineDataGatherer()->write(SkSize::Make(1.f/imgData.fImgSize.width(),
534 1.f/imgData.fImgSize.height()));
535 keyContext.pipelineDataGatherer()->write(imgData.fSubset);
536 keyContext.pipelineDataGatherer()->write(SkTo<int>(imgData.fTileModes.first));
537 keyContext.pipelineDataGatherer()->write(SkTo<int>(imgData.fTileModes.second));
538 const SkCubicResampler& cubic = imgData.fSampling.cubic;
539 keyContext.pipelineDataGatherer()->writeHalf(
540 SkImageShader::CubicResamplerMatrix(cubic.B, cubic.C));
541 }
542
543 // If clampToBorderSupport is unavailable, kDecal will be substituted to clamp in most cases.
544 bool should_substitute_decal(const std::pair<SkTileMode, SkTileMode>& tileMode, const Caps* caps) {
545 return !caps->clampToBorderSupport() && (tileMode.first == SkTileMode::kDecal ||
546 tileMode.second == SkTileMode::kDecal);
547 }
548
549 bool can_do_tiling_in_hw(const ImageShaderBlock::ImageData& imgData, const Caps* caps) {
550 return !should_substitute_decal(imgData.fTileModes, caps) &&
551 imgData.fSubset.contains(SkRect::Make(imgData.fImgSize));
552 }
553
554 void add_sampler_data_to_key(const KeyContext& keyContext, const SamplerDesc& samplerDesc) {
555 if (samplerDesc.isImmutable()) {
556 keyContext.paintParamsKeyBuilder()->addData(samplerDesc.asSpan());
557 } else {
558 // Means we have a regular dynamic sampler. Append a default SamplerDesc to convey this,
559 // allowing the key to maintain and convey sampler binding order.
560 keyContext.paintParamsKeyBuilder()->addData({});
561 }
562 }
563
564 } // anonymous namespace
565
566 ImageShaderBlock::ImageData::ImageData(const SkSamplingOptions& sampling,
567 SkTileMode tileModeX,
568 SkTileMode tileModeY,
569 SkISize imgSize,
570 SkRect subset,
571 ImmutableSamplerInfo immutableSamplerInfo)
572 : fSampling(sampling)
573 , fTileModes{tileModeX, tileModeY}
574 , fImgSize(imgSize)
575 , fSubset(subset)
576 , fImmutableSamplerInfo(immutableSamplerInfo) {
577 }
578
579
580 void ImageShaderBlock::AddBlock(const KeyContext& keyContext, const ImageData& imgData) {
581 if (keyContext.recorder() && !imgData.fTextureProxy) {
582 keyContext.paintParamsKeyBuilder()->addErrorBlock();
583 return;
584 }
585
586 const Caps* caps = keyContext.caps();
587 const bool doTilingInHw = !imgData.fSampling.useCubic && can_do_tiling_in_hw(imgData, caps);
588
589 if (doTilingInHw) {
590 CoordNormalizeShaderBlock::CoordNormalizeData data(SkSize::Make(imgData.fImgSize));
591 CoordNormalizeShaderBlock::BeginBlock(keyContext, data);
592 keyContext.paintParamsKeyBuilder()->beginBlock(BuiltInCodeSnippetID::kHWImageShader);
593 } else if (imgData.fSampling.useCubic) {
594 add_cubic_image_uniform_data(keyContext, imgData);
595 keyContext.paintParamsKeyBuilder()->beginBlock(BuiltInCodeSnippetID::kCubicImageShader);
596 } else if (imgData.fTileModes.first == SkTileMode::kClamp &&
597 imgData.fTileModes.second == SkTileMode::kClamp) {
598 add_clamp_image_uniform_data(keyContext, imgData);
599 keyContext.paintParamsKeyBuilder()->beginBlock(BuiltInCodeSnippetID::kImageShaderClamp);
600 } else {
601 add_image_uniform_data(keyContext, imgData);
602 keyContext.paintParamsKeyBuilder()->beginBlock(BuiltInCodeSnippetID::kImageShader);
603 }
604
605 // Image shaders must append immutable sampler data (or '0' in the more common case where
606 // regular samplers are used).
607 // TODO(b/392623124): In precompile mode (fTextureProxy == null), we still have a need for
608 // immutable samplers, which must be passed in somehow.
609 ImmutableSamplerInfo info = imgData.fTextureProxy
610 ? caps->getImmutableSamplerInfo(imgData.fTextureProxy->textureInfo())
611 : imgData.fImmutableSamplerInfo;
612 auto tileModeWithSubstitution = doTilingInHw ? imgData.fTileModes :
613 std::make_pair(SkTileMode::kClamp, SkTileMode::kClamp);
614 SamplerDesc samplerDesc{imgData.fSampling, tileModeWithSubstitution, info};
615 keyContext.pipelineDataGatherer()->add(imgData.fTextureProxy, samplerDesc);
616 add_sampler_data_to_key(keyContext, samplerDesc);
617
618 keyContext.paintParamsKeyBuilder()->endBlock();
619
620 if (doTilingInHw) {
621 // Additional block for coord normalization.
622 keyContext.paintParamsKeyBuilder()->endBlock();
623 }
624 }
625
626
627 //--------------------------------------------------------------------------------------------------
628
629 // makes use of ImageShader functions, above
630 namespace {
631
632 void add_yuv_image_uniform_data(const KeyContext& keyContext,
633 const YUVImageShaderBlock::ImageData& imgData) {
634 BEGIN_WRITE_UNIFORMS(keyContext, BuiltInCodeSnippetID::kYUVImageShader)
635
636 keyContext.pipelineDataGatherer()->write(SkSize::Make(1.f/imgData.fImgSize.width(),
637 1.f/imgData.fImgSize.height()));
638 keyContext.pipelineDataGatherer()->write(SkSize::Make(1.f/imgData.fImgSizeUV.width(),
639 1.f/imgData.fImgSizeUV.height()));
640 keyContext.pipelineDataGatherer()->write(imgData.fSubset);
641 keyContext.pipelineDataGatherer()->write(imgData.fLinearFilterUVInset);
642 keyContext.pipelineDataGatherer()->write(SkTo<int>(imgData.fTileModes.first));
643 keyContext.pipelineDataGatherer()->write(SkTo<int>(imgData.fTileModes.second));
644 keyContext.pipelineDataGatherer()->write(SkTo<int>(imgData.fSampling.filter));
645 keyContext.pipelineDataGatherer()->write(SkTo<int>(imgData.fSamplingUV.filter));
646
647 for (int i = 0; i < 4; ++i) {
648 keyContext.pipelineDataGatherer()->writeHalf(imgData.fChannelSelect[i]);
649 }
650 keyContext.pipelineDataGatherer()->writeHalf(imgData.fYUVtoRGBMatrix);
651 keyContext.pipelineDataGatherer()->writeHalf(imgData.fYUVtoRGBTranslate);
652 }
653
654 void add_cubic_yuv_image_uniform_data(const KeyContext& keyContext,
655 const YUVImageShaderBlock::ImageData& imgData) {
656 BEGIN_WRITE_UNIFORMS(keyContext, BuiltInCodeSnippetID::kCubicYUVImageShader)
657
658 keyContext.pipelineDataGatherer()->write(SkSize::Make(1.f/imgData.fImgSize.width(),
659 1.f/imgData.fImgSize.height()));
660 keyContext.pipelineDataGatherer()->write(SkSize::Make(1.f/imgData.fImgSizeUV.width(),
661 1.f/imgData.fImgSizeUV.height()));
662 keyContext.pipelineDataGatherer()->write(imgData.fSubset);
663 keyContext.pipelineDataGatherer()->write(SkTo<int>(imgData.fTileModes.first));
664 keyContext.pipelineDataGatherer()->write(SkTo<int>(imgData.fTileModes.second));
665 const SkCubicResampler& cubic = imgData.fSampling.cubic;
666 keyContext.pipelineDataGatherer()->writeHalf(SkImageShader::CubicResamplerMatrix(cubic.B, cubic.C));
667
668 for (int i = 0; i < 4; ++i) {
669 keyContext.pipelineDataGatherer()->writeHalf(imgData.fChannelSelect[i]);
670 }
671 keyContext.pipelineDataGatherer()->writeHalf(imgData.fYUVtoRGBMatrix);
672 keyContext.pipelineDataGatherer()->writeHalf(imgData.fYUVtoRGBTranslate);
673 }
674
675 void add_hw_yuv_image_uniform_data(const KeyContext& keyContext,
676 const YUVImageShaderBlock::ImageData& imgData) {
677 BEGIN_WRITE_UNIFORMS(keyContext, BuiltInCodeSnippetID::kHWYUVImageShader)
678
679 keyContext.pipelineDataGatherer()->write(SkSize::Make(1.f/imgData.fImgSize.width(),
680 1.f/imgData.fImgSize.height()));
681 keyContext.pipelineDataGatherer()->write(SkSize::Make(1.f/imgData.fImgSizeUV.width(),
682 1.f/imgData.fImgSizeUV.height()));
683 keyContext.pipelineDataGatherer()->write(imgData.fSubset);
684
685 SkPoint linearFilterUVInset = imgData.fLinearFilterUVInset;
686 // We sign-encode whether we need to adjust the UV coords by applying `fLinearFilterUVInset` for
687 // nearest neighbor filtering in `linearFilterUVInset.fX`.
688 if (imgData.fSampling.filter == SkFilterMode::kNearest) {
689 linearFilterUVInset.fX = -linearFilterUVInset.fX;
690 }
691 // We sign-encode whether we need clamping for subset or mismatched Y/UV plane size draws in
692 // `linearFilterUVInset.fY` - only clamp tiling modes are supported though.
693 if (!imgData.fSubset.contains(SkRect::Make(imgData.fImgSize)) ||
694 imgData.fImgSize != imgData.fImgSizeUV) {
695 SkASSERT(imgData.fTileModes.first == SkTileMode::kClamp &&
696 imgData.fTileModes.second == SkTileMode::kClamp);
697 linearFilterUVInset.fY = -linearFilterUVInset.fY;
698 }
699 keyContext.pipelineDataGatherer()->write(linearFilterUVInset);
700
701 for (int i = 0; i < 4; ++i) {
702 keyContext.pipelineDataGatherer()->writeHalf(imgData.fChannelSelect[i]);
703 }
704 keyContext.pipelineDataGatherer()->writeHalf(imgData.fYUVtoRGBMatrix);
705 keyContext.pipelineDataGatherer()->writeHalf(imgData.fYUVtoRGBTranslate);
706 }
707
708 void add_hw_yuv_no_swizzle_image_uniform_data(const KeyContext& keyContext,
709 const YUVImageShaderBlock::ImageData& imgData) {
710 BEGIN_WRITE_UNIFORMS(keyContext, BuiltInCodeSnippetID::kHWYUVNoSwizzleImageShader)
711
712 keyContext.pipelineDataGatherer()->write(SkSize::Make(1.f/imgData.fImgSize.width(),
713 1.f/imgData.fImgSize.height()));
714 keyContext.pipelineDataGatherer()->write(SkSize::Make(1.f/imgData.fImgSizeUV.width(),
715 1.f/imgData.fImgSizeUV.height()));
716 keyContext.pipelineDataGatherer()->write(imgData.fSubset);
717
718 SkPoint linearFilterUVInset = imgData.fLinearFilterUVInset;
719 // We sign-encode whether we need to adjust the UV coords by applying `fLinearFilterUVInset` for
720 // nearest neighbor filtering in `linearFilterUVInset.fX`.
721 if (imgData.fSampling.filter == SkFilterMode::kNearest) {
722 linearFilterUVInset.fX = -linearFilterUVInset.fX;
723 }
724 // We sign-encode whether we need clamping for subset or mismatched Y/UV plane size draws in
725 // `linearFilterUVInset.fY` - only clamp tiling modes are supported though.
726 if (!imgData.fSubset.contains(SkRect::Make(imgData.fImgSize)) ||
727 imgData.fImgSize != imgData.fImgSizeUV) {
728 SkASSERT(imgData.fTileModes.first == SkTileMode::kClamp &&
729 imgData.fTileModes.second == SkTileMode::kClamp);
730 linearFilterUVInset.fY = -linearFilterUVInset.fY;
731 }
732 keyContext.pipelineDataGatherer()->write(linearFilterUVInset);
733
734 keyContext.pipelineDataGatherer()->writeHalf(imgData.fYUVtoRGBMatrix);
735 SkV4 yuvToRGBXlateAlphaParam = {
736 imgData.fYUVtoRGBTranslate.fX,
737 imgData.fYUVtoRGBTranslate.fY,
738 imgData.fYUVtoRGBTranslate.fZ,
739 imgData.fAlphaParam
740 };
741 keyContext.pipelineDataGatherer()->writeHalf(yuvToRGBXlateAlphaParam);
742 }
743
744 } // anonymous namespace
745
746 YUVImageShaderBlock::ImageData::ImageData(const SkSamplingOptions& sampling,
747 SkTileMode tileModeX,
748 SkTileMode tileModeY,
749 SkISize imgSize,
750 SkRect subset)
751 : fSampling(sampling)
752 , fSamplingUV(sampling)
753 , fTileModes{tileModeX, tileModeY}
754 , fImgSize(imgSize)
755 , fImgSizeUV(imgSize)
756 , fSubset(subset) {
757 }
758
759 static bool can_do_yuv_tiling_in_hw(const YUVImageShaderBlock::ImageData& imgData,
760 const Caps* caps) {
761 if (should_substitute_decal(imgData.fTileModes, caps)) {
762 return false;
763 }
764 // Use the HW tiling shader variant if we're drawing the full rect with matched Y and UV plane
765 // sizes and any tiling mode, or if we're drawing a subset with clamp tiling mode.
766 return (imgData.fSubset.contains(SkRect::Make(imgData.fImgSize)) &&
767 imgData.fImgSize == imgData.fImgSizeUV) ||
768 (imgData.fTileModes.first == SkTileMode::kClamp &&
769 imgData.fTileModes.second == SkTileMode::kClamp);
770 }
771
772 static bool no_yuv_swizzle(const YUVImageShaderBlock::ImageData& imgData) {
773 // Y_U_V or U_Y_V format, reading from R channel for each texture
774 if (imgData.fChannelSelect[0].x == 1 &&
775 imgData.fChannelSelect[1].x == 1 &&
776 imgData.fChannelSelect[2].x == 1 &&
777 imgData.fChannelSelect[3].x == 1) {
778 return true;
779 }
780
781 return false;
782 }
783
784 void YUVImageShaderBlock::AddBlock(const KeyContext& keyContext, const ImageData& imgData) {
785 if (keyContext.recorder() &&
786 (!imgData.fTextureProxies[0] || !imgData.fTextureProxies[1] ||
787 !imgData.fTextureProxies[2] || !imgData.fTextureProxies[3])) {
788 keyContext.paintParamsKeyBuilder()->addErrorBlock();
789 return;
790 }
791
792 const Caps* caps = keyContext.caps();
793 const bool doTilingInHw = !imgData.fSampling.useCubic && can_do_yuv_tiling_in_hw(imgData, caps);
794 const bool noYUVSwizzle = no_yuv_swizzle(imgData);
795
796 // uvs are never SkTileMode::kDecal
797 auto uvTileModes = std::make_pair(imgData.fTileModes.first == SkTileMode::kDecal
798 ? SkTileMode::kClamp : imgData.fTileModes.first,
799 imgData.fTileModes.second == SkTileMode::kDecal
800 ? SkTileMode::kClamp : imgData.fTileModes.second);
801 auto yAlphaTileModes = doTilingInHw ? imgData.fTileModes :
802 std::make_pair(SkTileMode::kClamp, SkTileMode::kClamp);
803 keyContext.pipelineDataGatherer()->add(imgData.fTextureProxies[0],
804 {imgData.fSampling, yAlphaTileModes});
805 keyContext.pipelineDataGatherer()->add(imgData.fTextureProxies[1],
806 {imgData.fSamplingUV, uvTileModes});
807 keyContext.pipelineDataGatherer()->add(imgData.fTextureProxies[2],
808 {imgData.fSamplingUV, uvTileModes});
809 keyContext.pipelineDataGatherer()->add(imgData.fTextureProxies[3],
810 {imgData.fSampling, yAlphaTileModes});
811
812 if (doTilingInHw && noYUVSwizzle) {
813 add_hw_yuv_no_swizzle_image_uniform_data(keyContext, imgData);
814 keyContext.paintParamsKeyBuilder()->addBlock(
815 BuiltInCodeSnippetID::kHWYUVNoSwizzleImageShader);
816 } else if (doTilingInHw) {
817 add_hw_yuv_image_uniform_data(keyContext, imgData);
818 keyContext.paintParamsKeyBuilder()->addBlock(
819 BuiltInCodeSnippetID::kHWYUVImageShader);
820 } else if (imgData.fSampling.useCubic) {
821 add_cubic_yuv_image_uniform_data(keyContext, imgData);
822 keyContext.paintParamsKeyBuilder()->addBlock(
823 BuiltInCodeSnippetID::kCubicYUVImageShader);
824 } else {
825 add_yuv_image_uniform_data(keyContext, imgData);
826 keyContext.paintParamsKeyBuilder()->addBlock(
827 BuiltInCodeSnippetID::kYUVImageShader);
828 }
829 }
830
831 //--------------------------------------------------------------------------------------------------
832
833 namespace {
834
835 void add_coord_normalize_uniform_data(const KeyContext& keyContext,
836 const CoordNormalizeShaderBlock::CoordNormalizeData& data) {
837 BEGIN_WRITE_UNIFORMS(keyContext, BuiltInCodeSnippetID::kCoordNormalizeShader)
838 keyContext.pipelineDataGatherer()->write(data.fInvDimensions);
839 }
840
841 } // anonymous namespace
842
843 void CoordNormalizeShaderBlock::BeginBlock(const KeyContext& keyContext,
844 const CoordNormalizeData& data) {
845 add_coord_normalize_uniform_data(keyContext, data);
846 keyContext.paintParamsKeyBuilder()->beginBlock(BuiltInCodeSnippetID::kCoordNormalizeShader);
847 }
848
849 //--------------------------------------------------------------------------------------------------
850
851 namespace {
852
853 void add_coordclamp_uniform_data(const KeyContext& keyContext,
854 const CoordClampShaderBlock::CoordClampData& clampData) {
855 BEGIN_WRITE_UNIFORMS(keyContext, BuiltInCodeSnippetID::kCoordClampShader)
856 keyContext.pipelineDataGatherer()->write(clampData.fSubset);
857 }
858
859 } // anonymous namespace
860
861 void CoordClampShaderBlock::BeginBlock(const KeyContext& keyContext,
862 const CoordClampData& clampData) {
863 add_coordclamp_uniform_data(keyContext, clampData);
864 keyContext.paintParamsKeyBuilder()->beginBlock(BuiltInCodeSnippetID::kCoordClampShader);
865 }
866
867 //--------------------------------------------------------------------------------------------------
868
869 namespace {
870
871 void add_dither_uniform_data(const KeyContext& keyContext,
872 const DitherShaderBlock::DitherData& ditherData) {
873 BEGIN_WRITE_UNIFORMS(keyContext, BuiltInCodeSnippetID::kDitherShader)
874
875 keyContext.pipelineDataGatherer()->writeHalf(ditherData.fRange);
876 }
877
878 } // anonymous namespace
879
880 void DitherShaderBlock::AddBlock(const KeyContext& keyContext, const DitherData& data) {
881 auto gatherer = keyContext.pipelineDataGatherer();
882 add_dither_uniform_data(keyContext, data);
883
884 SkASSERT(data.fLUTProxy || !keyContext.recorder());
885 gatherer->add(data.fLUTProxy, {SkFilterMode::kNearest, SkTileMode::kRepeat});
886
887 keyContext.paintParamsKeyBuilder()->addBlock(BuiltInCodeSnippetID::kDitherShader);
888 }
889
890 //--------------------------------------------------------------------------------------------------
891
892 namespace {
893
894 void add_perlin_noise_uniform_data(const KeyContext& keyContext,
895 const PerlinNoiseShaderBlock::PerlinNoiseData& noiseData) {
896 BEGIN_WRITE_UNIFORMS(keyContext, BuiltInCodeSnippetID::kPerlinNoiseShader)
897
898 auto gatherer = keyContext.pipelineDataGatherer();
899 gatherer->write(noiseData.fBaseFrequency);
900 gatherer->write(noiseData.fStitchData);
901 gatherer->write(static_cast<int>(noiseData.fType));
902 gatherer->write(noiseData.fNumOctaves);
903 gatherer->write(static_cast<int>(noiseData.stitching()));
904
905 static const std::pair<SkTileMode, SkTileMode> kRepeatXTileModes =
906 { SkTileMode::kRepeat, SkTileMode::kClamp };
907 gatherer->add(noiseData.fPermutationsProxy, {SkFilterMode::kNearest, kRepeatXTileModes});
908 gatherer->add(noiseData.fNoiseProxy, {SkFilterMode::kNearest, kRepeatXTileModes});
909 }
910
911 } // anonymous namespace
912
913 void PerlinNoiseShaderBlock::AddBlock(const KeyContext& keyContext,
914 const PerlinNoiseData& noiseData) {
915 add_perlin_noise_uniform_data(keyContext, noiseData);
916
917 keyContext.paintParamsKeyBuilder()->addBlock(BuiltInCodeSnippetID::kPerlinNoiseShader);
918 }
919
920 //--------------------------------------------------------------------------------------------------
921
922 void BlendComposeBlock::BeginBlock(const KeyContext& keyContext) {
923 BEGIN_WRITE_UNIFORMS(keyContext, BuiltInCodeSnippetID::kBlendCompose)
924
925 keyContext.paintParamsKeyBuilder()->beginBlock(BuiltInCodeSnippetID::kBlendCompose);
926 }
927
928 //--------------------------------------------------------------------------------------------------
929
930 void PorterDuffBlenderBlock::AddBlock(const KeyContext& keyContext, SkSpan<const float> coeffs) {
931 BEGIN_WRITE_UNIFORMS(keyContext, BuiltInCodeSnippetID::kPorterDuffBlender)
932 SkASSERT(coeffs.size() == 4);
933 keyContext.pipelineDataGatherer()->writeHalf(SkV4{coeffs[0], coeffs[1], coeffs[2], coeffs[3]});
934
935 keyContext.paintParamsKeyBuilder()->addBlock(BuiltInCodeSnippetID::kPorterDuffBlender);
936 }
937
938 //--------------------------------------------------------------------------------------------------
939
940 void HSLCBlenderBlock::AddBlock(const KeyContext& keyContext, SkSpan<const float> coeffs) {
941 BEGIN_WRITE_UNIFORMS(keyContext, BuiltInCodeSnippetID::kHSLCBlender)
942 SkASSERT(coeffs.size() == 2);
943 keyContext.pipelineDataGatherer()->writeHalf(SkV2{coeffs[0], coeffs[1]});
944
945 keyContext.paintParamsKeyBuilder()->addBlock(BuiltInCodeSnippetID::kHSLCBlender);
946 }
947
948 //--------------------------------------------------------------------------------------------------
949
950 void ComposeBlock::BeginBlock(const KeyContext& keyContext) {
951 keyContext.paintParamsKeyBuilder()->beginBlock(BuiltInCodeSnippetID::kCompose);
952 }
953
954 //--------------------------------------------------------------------------------------------------
955
956 namespace {
957
958 void add_matrix_colorfilter_uniform_data(const KeyContext& keyContext,
959 const MatrixColorFilterBlock::MatrixColorFilterData& data) {
960 BEGIN_WRITE_UNIFORMS(keyContext, BuiltInCodeSnippetID::kMatrixColorFilter)
961 auto gatherer = keyContext.pipelineDataGatherer();
962 gatherer->writeHalf(data.fMatrix);
963 gatherer->writeHalf(data.fTranslate);
964 if (data.fClamp) {
965 gatherer->writeHalf(SkV2{0.f, 1.f});
966 } else {
967 // Alpha is always clamped to 1. RGB clamp to the max finite half value.
968 static constexpr float kUnclamped = 65504.f; // SK_HalfMax converted back to float
969 SkASSERT(SkHalfToFloat(SkFloatToHalf(kUnclamped)) == kUnclamped);
970 SkASSERT(SkHalfToFloat(SkFloatToHalf(-kUnclamped)) == -kUnclamped);
971 gatherer->writeHalf(SkV2{-kUnclamped, kUnclamped});
972 }
973 }
974
975 void add_hsl_matrix_colorfilter_uniform_data(
976 const KeyContext& keyContext,
977 const MatrixColorFilterBlock::MatrixColorFilterData& data) {
978 BEGIN_WRITE_UNIFORMS(keyContext, BuiltInCodeSnippetID::kHSLMatrixColorFilter)
979 auto gatherer = keyContext.pipelineDataGatherer();
980 gatherer->writeHalf(data.fMatrix);
981 gatherer->writeHalf(data.fTranslate);
982 }
983
984 } // anonymous namespace
985
986 void MatrixColorFilterBlock::AddBlock(const KeyContext& keyContext,
987 const MatrixColorFilterData& matrixCFData) {
988 if (matrixCFData.fInHSLA) {
989 add_hsl_matrix_colorfilter_uniform_data(keyContext, matrixCFData);
990
991 keyContext.paintParamsKeyBuilder()->addBlock(BuiltInCodeSnippetID::kHSLMatrixColorFilter);
992 } else {
993 add_matrix_colorfilter_uniform_data(keyContext, matrixCFData);
994
995 keyContext.paintParamsKeyBuilder()->addBlock(BuiltInCodeSnippetID::kMatrixColorFilter);
996 }
997 }
998
999 //--------------------------------------------------------------------------------------------------
1000
1001 namespace {
1002
1003 void add_table_colorfilter_uniform_data(const KeyContext& keyContext,
1004 const TableColorFilterBlock::TableColorFilterData& data) {
1005 BEGIN_WRITE_UNIFORMS(keyContext, BuiltInCodeSnippetID::kTableColorFilter)
1006
1007 keyContext.pipelineDataGatherer()->add(data.fTextureProxy, {SkFilterMode::kNearest, SkTileMode::kClamp});
1008 }
1009
1010 } // anonymous namespace
1011
1012 void TableColorFilterBlock::AddBlock(const KeyContext& keyContext,
1013 const TableColorFilterData& data) {
1014 SkASSERT(data.fTextureProxy || !keyContext.recorder());
1015
1016 add_table_colorfilter_uniform_data(keyContext, data);
1017
1018 keyContext.paintParamsKeyBuilder()->addBlock(BuiltInCodeSnippetID::kTableColorFilter);
1019 }
1020
1021 //--------------------------------------------------------------------------------------------------
1022 namespace {
1023
1024 // There are three variations of color space transforms with increasing complexity, but they are
1025 // built on the same techniques for managing variations w/o adding branches in the shader.
1026 void add_color_space_uniforms(const KeyContext& keyContext,
1027 BuiltInCodeSnippetID id,
1028 const SkColorSpaceXformSteps& steps,
1029 ReadSwizzle readSwizzle) {
1030 SkASSERT(id == BuiltInCodeSnippetID::kColorSpaceXformPremul || // premul/unpremul/opaque
1031 id == BuiltInCodeSnippetID::kColorSpaceXformSRGB || // + sRGB [d]encode/gamut
1032 id == BuiltInCodeSnippetID::kColorSpaceXformColorFilter); // + everything else
1033
1034 BEGIN_WRITE_UNIFORMS(keyContext, id)
1035
1036 // To encode whether to do premul/unpremul or make the output opaque, we use
1037 // srcDEF_args.w and dstDEF_args.w:
1038 // - identity: {0, 1}
1039 // - do unpremul: {-1, 1}
1040 // - do premul: {0, 0}
1041 // - do both: {-1, 0}
1042 // - alpha swizzle 1: {1, 1}
1043 // - alpha swizzle r: {1, 0}
1044 const bool alphaSwizzleR = readSwizzle == ReadSwizzle::k000R;
1045 const bool alphaSwizzle1 = readSwizzle == ReadSwizzle::kRGB1 ||
1046 readSwizzle == ReadSwizzle::kRRR1;
1047
1048 // It doesn't make sense to unpremul/premul in opaque cases, but we might get a request to
1049 // anyways, which we can just ignore.
1050 const bool unpremul = alphaSwizzle1 ? false : steps.fFlags.unpremul;
1051 const bool premul = alphaSwizzle1 ? false : steps.fFlags.premul;
1052
1053 const float srcW = unpremul ? -1.f :
1054 (alphaSwizzleR || alphaSwizzle1) ? 1.f :
1055 0.f;
1056 const float dstW = (premul || alphaSwizzleR) ? 0.f : 1.f;
1057
1058 if (id == BuiltInCodeSnippetID::kColorSpaceXformPremul) {
1059 // If either of these asserts would fail, we can't correctly use this specialized shader for
1060 // the given transform.
1061 SkASSERT(readSwizzle == ReadSwizzle::kRGBA || readSwizzle == ReadSwizzle::kRGB1);
1062 // If these are both true, that implies there's a color space transfer or gamut transform.
1063 SkASSERT(!(steps.fFlags.unpremul && steps.fFlags.premul));
1064 // And given these assertions, the 6 cases encoded in srcW and dstW are reduced to:
1065 // identity, do unpremul, do premul, and make opaque (alpha swizzle 1)
1066 keyContext.pipelineDataGatherer()->writeHalf(SkV2{srcW, dstW});
1067 return;
1068 }
1069
1070 // srcW and dstW will be used later with the other transfer function values, but for the
1071 // more complex shaders, we put the gamut matrix first for alignment.
1072
1073 SkMatrix gamutTransform;
1074 const float identity[] = { 1, 0, 0, 0, 1, 0, 0, 0, 1 };
1075 // TODO: it seems odd to copy this into an SkMatrix just to write it to the gatherer
1076 // fSrcToDstMatrix is column-major, SkMatrix is row-major.
1077 const float* m = steps.fFlags.gamut_transform ? steps.fSrcToDstMatrix : identity;
1078 if (readSwizzle == ReadSwizzle::kRRR1) {
1079 gamutTransform.setAll(m[0] + m[3] + m[6], 0, 0,
1080 m[1] + m[4] + m[7], 0, 0,
1081 m[2] + m[5] + m[8], 0, 0);
1082 } else if (readSwizzle == ReadSwizzle::kBGRA) {
1083 gamutTransform.setAll(m[6], m[3], m[0],
1084 m[7], m[4], m[1],
1085 m[8], m[5], m[2]);
1086 } else if (readSwizzle == ReadSwizzle::k000R) {
1087 gamutTransform.setAll(0, 0, 0,
1088 0, 0, 0,
1089 0, 0, 0);
1090 } else if (steps.fFlags.gamut_transform) {
1091 gamutTransform.setAll(m[0], m[3], m[6],
1092 m[1], m[4], m[7],
1093 m[2], m[5], m[8]);
1094 }
1095 keyContext.pipelineDataGatherer()->writeHalf(gamutTransform);
1096
1097 // To encode which transfer function to apply, we use the src and dst gamma values:
1098 // - identity: 0
1099 // - sRGB: g > 0
1100 // - PQ: -2
1101 // - HLG: -1
1102 // For the sRGB shader, we allow linear sRGB but that shader has no branches on TF type, so
1103 // we have to replace the values with an actual identity sRGB-ish function.
1104 const bool treatLinearAsSRGB = id == BuiltInCodeSnippetID::kColorSpaceXformSRGB;
1105 if (steps.fFlags.linearize) {
1106 const skcms_TFType type = skcms_TransferFunction_getType(&steps.fSrcTF);
1107 const float srcG = type == skcms_TFType_sRGBish ? steps.fSrcTF.g :
1108 type == skcms_TFType_PQish ? -2.f :
1109 type == skcms_TFType_HLGish ? -1.f :
1110 0.f;
1111 keyContext.pipelineDataGatherer()->write(SkV4{srcG, steps.fSrcTF.a,
1112 steps.fSrcTF.b, steps.fSrcTF.c});
1113 keyContext.pipelineDataGatherer()->write(SkV4{steps.fSrcTF.d, steps.fSrcTF.e,
1114 steps.fSrcTF.f, srcW});
1115 } else if (treatLinearAsSRGB) {
1116 // Branchless identity function with g=1 (sRGB-ish)
1117 static constexpr skcms_TransferFunction kI = SkNamedTransferFn::kLinear;
1118 keyContext.pipelineDataGatherer()->write(SkV4{kI.g, kI.a, kI.b, kI.c});
1119 keyContext.pipelineDataGatherer()->write(SkV4{kI.d, kI.e, kI.f, srcW});
1120 } else {
1121 // Branched identity that actually skips all operations
1122 keyContext.pipelineDataGatherer()->write(SkV4{0.f, 0.f, 0.f, 0.f});
1123 keyContext.pipelineDataGatherer()->write(SkV4{0.f, 0.f, 0.f, srcW});
1124 }
1125
1126 if (steps.fFlags.encode) {
1127 const skcms_TFType type = skcms_TransferFunction_getType(&steps.fDstTFInv);
1128 const float dstG = type == skcms_TFType_sRGBish ? steps.fDstTFInv.g :
1129 type == skcms_TFType_PQish ? -2.f :
1130 type == skcms_TFType_HLGinvish ? -1.f :
1131 0.f;
1132 keyContext.pipelineDataGatherer()->write(SkV4{dstG, steps.fDstTFInv.a,
1133 steps.fDstTFInv.b, steps.fDstTFInv.c});
1134 keyContext.pipelineDataGatherer()->write(SkV4{steps.fDstTFInv.d, steps.fDstTFInv.e,
1135 steps.fDstTFInv.f, dstW});
1136 } else if (treatLinearAsSRGB) {
1137 static constexpr skcms_TransferFunction kI = SkNamedTransferFn::kLinear;
1138 keyContext.pipelineDataGatherer()->write(SkV4{kI.g, kI.a, kI.b, kI.c});
1139 keyContext.pipelineDataGatherer()->write(SkV4{kI.d, kI.e, kI.f, dstW});
1140 } else {
1141 keyContext.pipelineDataGatherer()->write(SkV4{0.f, 0.f, 0.f, 0.f});
1142 keyContext.pipelineDataGatherer()->write(SkV4{0.f, 0.f, 0.f, dstW});
1143 }
1144
1145 const bool hasOOTFUniforms = id == BuiltInCodeSnippetID::kColorSpaceXformColorFilter;
1146 if (hasOOTFUniforms) {
1147 SkV4 src_ootf = {0.f, 0.f, 0.f, 0.f};
1148 SkV4 dst_ootf = {0.f, 0.f, 0.f, 0.f};
1149
1150 if (steps.fFlags.src_ootf) {
1151 if (readSwizzle == ReadSwizzle::kBGRA) {
1152 src_ootf = SkV4{
1153 steps.fSrcOotf[2], steps.fSrcOotf[1], steps.fSrcOotf[0], steps.fSrcOotf[3]};
1154 } else {
1155 src_ootf = SkV4{
1156 steps.fSrcOotf[0], steps.fSrcOotf[1], steps.fSrcOotf[2], steps.fSrcOotf[3]};
1157 }
1158 }
1159
1160 if (steps.fFlags.dst_ootf) {
1161 if (readSwizzle == ReadSwizzle::kBGRA) {
1162 dst_ootf = SkV4{
1163 steps.fDstOotf[2], steps.fDstOotf[1], steps.fDstOotf[0], steps.fDstOotf[3]};
1164 } else {
1165 dst_ootf = SkV4{
1166 steps.fDstOotf[0], steps.fDstOotf[1], steps.fDstOotf[2], steps.fDstOotf[3]};
1167 }
1168 }
1169
1170 keyContext.pipelineDataGatherer()->write(src_ootf);
1171 keyContext.pipelineDataGatherer()->write(dst_ootf);
1172 } else {
1173 SkASSERT(!steps.fFlags.src_ootf);
1174 SkASSERT(!steps.fFlags.dst_ootf);
1175 }
1176 }
1177
1178 } // anonymous namespace
1179
1180 ColorSpaceTransformBlock::ColorSpaceTransformData::ColorSpaceTransformData(const SkColorSpace* src,
1181 SkAlphaType srcAT,
1182 const SkColorSpace* dst,
1183 SkAlphaType dstAT)
1184 : fSteps(src, srcAT, dst, dstAT) {}
1185
1186 void ColorSpaceTransformBlock::AddBlock(const KeyContext& keyContext,
1187 const ColorSpaceTransformData& data) {
1188 const bool xformNeedsGamutOrXferFn = data.fSteps.fFlags.linearize ||
1189 data.fSteps.fFlags.encode ||
1190 data.fSteps.fFlags.src_ootf ||
1191 data.fSteps.fFlags.dst_ootf ||
1192 data.fSteps.fFlags.gamut_transform;
1193 const bool swizzleNeedsGamutTransform = !(data.fReadSwizzle == ReadSwizzle::kRGBA ||
1194 data.fReadSwizzle == ReadSwizzle::kRGB1);
1195
1196 // Use a specialized shader if we don't need transfer function or gamut transforms.
1197 if (!(xformNeedsGamutOrXferFn || swizzleNeedsGamutTransform)) {
1198 // When enabled, the most specialized is to do nothing at all. To simplify calling code,
1199 // this adds a passthrough block vs. having callers know how to reconfigure their blocks.
1200 if (SkToBool(keyContext.flags() & KeyGenFlags::kEnableIdentityColorSpaceXform) &&
1201 data.fReadSwizzle == ReadSwizzle::kRGBA &&
1202 !data.fSteps.fFlags.premul && !data.fSteps.fFlags.unpremul) {
1203 keyContext.paintParamsKeyBuilder()->addBlock(BuiltInCodeSnippetID::kPriorOutput);
1204 return;
1205 }
1206
1207 add_color_space_uniforms(keyContext, BuiltInCodeSnippetID::kColorSpaceXformPremul,
1208 data.fSteps, data.fReadSwizzle);
1209 keyContext.paintParamsKeyBuilder()->addBlock(BuiltInCodeSnippetID::kColorSpaceXformPremul);
1210 return;
1211 }
1212
1213 // Use a specialized shader if we're transferring to and from sRGB-ish color spaces.
1214 // We take this path even if linearize/encode are false since we can set coefficients
1215 // in the sRGB transfer functions to represent identity, and that is better than using the
1216 // most general colorspace option.
1217 if ((!data.fSteps.fFlags.linearize || skcms_TransferFunction_isSRGBish(&data.fSteps.fSrcTF)) &&
1218 (!data.fSteps.fFlags.encode || skcms_TransferFunction_isSRGBish(&data.fSteps.fDstTFInv))) {
1219 add_color_space_uniforms(keyContext, BuiltInCodeSnippetID::kColorSpaceXformSRGB,
1220 data.fSteps, data.fReadSwizzle);
1221 keyContext.paintParamsKeyBuilder()->addBlock(BuiltInCodeSnippetID::kColorSpaceXformSRGB);
1222 return;
1223 }
1224
1225 // Use the most general color space transform shader if no specializations can be used.
1226 add_color_space_uniforms(keyContext, BuiltInCodeSnippetID::kColorSpaceXformColorFilter,
1227 data.fSteps, data.fReadSwizzle);
1228 keyContext.paintParamsKeyBuilder()->addBlock(BuiltInCodeSnippetID::kColorSpaceXformColorFilter);
1229 }
1230
1231 //--------------------------------------------------------------------------------------------------
1232 namespace {
1233
1234 void add_analytic_clip_data(const KeyContext& keyContext,
1235 const NonMSAAClipBlock::NonMSAAClipData& data) {
1236 BEGIN_WRITE_UNIFORMS(keyContext, BuiltInCodeSnippetID::kAnalyticClip)
1237 keyContext.pipelineDataGatherer()->write(data.fRect);
1238 keyContext.pipelineDataGatherer()->write(data.fRadiusPlusHalf);
1239 keyContext.pipelineDataGatherer()->writeHalf(data.fEdgeSelect);
1240 }
1241
1242 void add_analytic_and_atlas_clip_data(const KeyContext& keyContext,
1243 const NonMSAAClipBlock::NonMSAAClipData& data) {
1244 BEGIN_WRITE_UNIFORMS(keyContext, BuiltInCodeSnippetID::kAnalyticAndAtlasClip)
1245 keyContext.pipelineDataGatherer()->write(data.fRect);
1246 keyContext.pipelineDataGatherer()->write(data.fRadiusPlusHalf);
1247 keyContext.pipelineDataGatherer()->writeHalf(data.fEdgeSelect);
1248 keyContext.pipelineDataGatherer()->write(data.fTexCoordOffset);
1249 keyContext.pipelineDataGatherer()->write(data.fMaskBounds);
1250 if (data.fAtlasTexture) {
1251 keyContext.pipelineDataGatherer()->write(
1252 SkSize::Make(1.f/data.fAtlasTexture->dimensions().width(),
1253 1.f/data.fAtlasTexture->dimensions().height()));
1254 } else {
1255 keyContext.pipelineDataGatherer()->write(SkSize::Make(0, 0));
1256 }
1257 }
1258
1259 } // anonymous namespace
1260
1261 void NonMSAAClipBlock::AddBlock(const KeyContext& keyContext, const NonMSAAClipData& data) {
1262 if (data.fAtlasTexture) {
1263 add_analytic_and_atlas_clip_data(keyContext, data);
1264 keyContext.paintParamsKeyBuilder()->beginBlock(BuiltInCodeSnippetID::kAnalyticAndAtlasClip);
1265
1266 const Caps* caps = keyContext.caps();
1267 ImmutableSamplerInfo info =
1268 caps->getImmutableSamplerInfo(data.fAtlasTexture->textureInfo());
1269 SamplerDesc samplerDesc {SkSamplingOptions(SkFilterMode::kNearest, SkMipmapMode::kNone),
1270 {SkTileMode::kClamp, SkTileMode::kClamp},
1271 info};
1272 keyContext.pipelineDataGatherer()->add(data.fAtlasTexture, samplerDesc);
1273
1274 keyContext.paintParamsKeyBuilder()->endBlock();
1275 } else {
1276 add_analytic_clip_data(keyContext, data);
1277 keyContext.paintParamsKeyBuilder()->addBlock(BuiltInCodeSnippetID::kAnalyticClip);
1278 }
1279 }
1280
1281 //--------------------------------------------------------------------------------------------------
1282
1283 void AddPrimitiveColor(const KeyContext& keyContext, bool skipColorXform) {
1284 /**
1285 * When skipColorXform is true, we assume the primitive color is already in the dst color space.
1286 */
1287 if (skipColorXform) {
1288 keyContext.paintParamsKeyBuilder()->addBlock(BuiltInCodeSnippetID::kPrimitiveColor);
1289 return;
1290 }
1291
1292 /**
1293 * If skipColorXform is false (most cases), the primitive color is assumed to be in sRGB.
1294 */
1295 ColorSpaceTransformBlock::ColorSpaceTransformData toDst(sk_srgb_singleton(),
1296 kPremul_SkAlphaType,
1297 keyContext.dstColorInfo().colorSpace(),
1298 keyContext.dstColorInfo().alphaType());
1299
1300 Compose(keyContext,
1301 /* addInnerToKey= */ [&]() -> void {
1302 keyContext.paintParamsKeyBuilder()->addBlock(BuiltInCodeSnippetID::kPrimitiveColor);
1303 },
1304 /* addOuterToKey= */ [&]() -> void {
1305 ColorSpaceTransformBlock::AddBlock(keyContext, toDst);
1306 });
1307 }
1308
1309 //--------------------------------------------------------------------------------------------------
1310
1311 void AddBlendModeColorFilter(const KeyContext& keyContext, SkBlendMode bm,
1312 const SkPMColor4f& srcColor) {
1313 Blend(keyContext,
1314 /* addBlendToKey= */ [&] () -> void {
1315 AddBlendMode(keyContext, bm);
1316 },
1317 /* addSrcToKey= */ [&]() -> void {
1318 SolidColorShaderBlock::AddBlock(keyContext, srcColor);
1319 },
1320 /* addDstToKey= */ [&]() -> void {
1321 keyContext.paintParamsKeyBuilder()->addBlock(BuiltInCodeSnippetID::kPriorOutput);
1322 });
1323 }
1324
1325 RuntimeEffectBlock::ShaderData::ShaderData(sk_sp<const SkRuntimeEffect> effect)
1326 : fEffect(std::move(effect)) {}
1327
1328 RuntimeEffectBlock::ShaderData::ShaderData(sk_sp<const SkRuntimeEffect> effect,
1329 sk_sp<const SkData> uniforms)
1330 : fEffect(std::move(effect))
1331 , fUniforms(std::move(uniforms)) {}
1332
1333 static bool skdata_matches(const SkData* a, const SkData* b) {
1334 // Returns true if both SkData objects hold the same contents, or if they are both null.
1335 // (SkData::equals supports passing null, and returns false.)
1336 return a ? a->equals(b) : (a == b);
1337 }
1338
1339 bool RuntimeEffectBlock::ShaderData::operator==(const ShaderData& rhs) const {
1340 return fEffect == rhs.fEffect && skdata_matches(fUniforms.get(), rhs.fUniforms.get());
1341 }
1342
1343 static void gather_runtime_effect_uniforms(const KeyContext& keyContext,
1344 const SkRuntimeEffect* effect,
1345 SkSpan<const Uniform> graphiteUniforms,
1346 const SkData* uniformData,
1347 PipelineDataGatherer* gatherer) {
1348 if (!uniformData) {
1349 return; // precompiling
1350 }
1351
1352 SkDEBUGCODE(UniformExpectationsValidator uev(gatherer, graphiteUniforms);)
1353
1354 SkSpan<const SkRuntimeEffect::Uniform> rtsUniforms = effect->uniforms();
1355
1356 if (!rtsUniforms.empty() && uniformData) {
1357 // Collect all the other uniforms from the provided SkData.
1358 const uint8_t* uniformBase = uniformData->bytes();
1359 for (size_t index = 0; index < rtsUniforms.size(); ++index) {
1360 const Uniform& uniform = graphiteUniforms[index];
1361 // Get a pointer to the offset in our data for this uniform.
1362 const uint8_t* uniformPtr = uniformBase + rtsUniforms[index].offset;
1363 // Pass the uniform data to the gatherer.
1364 gatherer->write(uniform, uniformPtr);
1365 }
1366 }
1367 }
1368
1369 // TODO(robertphillips): when BeginBlock fails we should mark the 'builder' as having failed
1370 // and explicitly handle the failure in ShaderCodeDictionary::findOrCreate.
1371 bool RuntimeEffectBlock::BeginBlock(const KeyContext& keyContext, const ShaderData& shaderData) {
1372 ShaderCodeDictionary* dict = keyContext.dict();
1373 int codeSnippetID = dict->findOrCreateRuntimeEffectSnippet(shaderData.fEffect.get());
1374
1375 if (codeSnippetID < 0) {
1376 return false;
1377 }
1378
1379 if (SkKnownRuntimeEffects::IsUserDefinedRuntimeEffect(codeSnippetID)) {
1380 keyContext.rtEffectDict()->set(codeSnippetID, shaderData.fEffect);
1381 }
1382
1383 const ShaderSnippet* entry = dict->getEntry(codeSnippetID);
1384 if (!entry) {
1385 return false;
1386 }
1387
1388 gather_runtime_effect_uniforms(keyContext,
1389 shaderData.fEffect.get(),
1390 entry->fUniforms,
1391 shaderData.fUniforms.get(),
1392 keyContext.pipelineDataGatherer());
1393
1394 keyContext.paintParamsKeyBuilder()->beginBlock(codeSnippetID);
1395 return true;
1396 }
1397
1398 // TODO(robertphillips): fuse this with the similar code in add_children_to_key and
1399 // PrecompileRTEffect::addToKey.
1400 void RuntimeEffectBlock::AddNoOpEffect(const KeyContext& keyContext, SkRuntimeEffect* effect) {
1401 if (effect->allowShader()) {
1402 // A missing shader returns transparent black
1403 SolidColorShaderBlock::AddBlock(keyContext, SK_PMColor4fTRANSPARENT);
1404 } else if (effect->allowColorFilter()) {
1405 // A "passthrough" color filter returns the input color as-is.
1406 keyContext.paintParamsKeyBuilder()->addBlock(BuiltInCodeSnippetID::kPriorOutput);
1407 } else {
1408 SkASSERT(effect->allowBlender());
1409 // A "passthrough" blender performs `blend_src_over(src, dest)`.
1410 AddFixedBlendMode(keyContext, SkBlendMode::kSrcOver);
1411 }
1412 }
1413
1414 void RuntimeEffectBlock::HandleIntrinsics(const KeyContext& keyContext, const SkRuntimeEffect* effect) {
1415 // Runtime effects that reference color transform intrinsics have two extra children that
1416 // are bound to the colorspace xform snippet with values to go to and from the linear srgb
1417 // to the current working/dst color space.
1418 if (SkRuntimeEffectPriv::UsesColorTransform(effect)) {
1419 SkColorSpace* dstCS = keyContext.dstColorInfo().colorSpace();
1420 if (!dstCS) {
1421 dstCS = sk_srgb_linear_singleton(); // turn colorspace conversion into a noop
1422 }
1423
1424 // TODO(b/332565302): If the runtime shader only uses one of these transforms, we could
1425 // upload only one set of uniforms.
1426
1427 // NOTE: This must be kept in sync with the logic used to generate the toLinearSrgb() and
1428 // fromLinearSrgb() expressions for each runtime effect. toLinearSrgb() is assumed to be
1429 // the second to last child, and fromLinearSrgb() is assumed to be the last.
1430 ColorSpaceTransformBlock::ColorSpaceTransformData dstToLinear(dstCS,
1431 kUnpremul_SkAlphaType,
1432 sk_srgb_linear_singleton(),
1433 kUnpremul_SkAlphaType);
1434 ColorSpaceTransformBlock::ColorSpaceTransformData linearToDst(sk_srgb_linear_singleton(),
1435 kUnpremul_SkAlphaType,
1436 dstCS,
1437 kUnpremul_SkAlphaType);
1438
1439 ColorSpaceTransformBlock::AddBlock(keyContext, dstToLinear);
1440 ColorSpaceTransformBlock::AddBlock(keyContext, linearToDst);
1441 }
1442 }
1443
1444 // ==================================================================
1445
1446 namespace {
1447
1448 void add_to_key(const KeyContext& keyContext, const SkBlendModeBlender* blender) {
1449 SkASSERT(blender);
1450 AddBlendMode(keyContext, blender->mode());
1451 }
1452
1453 // Be sure to keep this function in sync w/ the code in PrecompileRTEffect::addToKey
1454 void add_children_to_key(const KeyContext& keyContext,
1455 SkSpan<const SkRuntimeEffect::ChildPtr> children,
1456 const SkRuntimeEffect* effect) {
1457 SkSpan<const SkRuntimeEffect::Child> childInfo = effect->children();
1458 SkASSERT(children.size() == childInfo.size());
1459
1460 using ChildType = SkRuntimeEffect::ChildType;
1461
1462 for (size_t index = 0; index < children.size(); ++index) {
1463 const SkRuntimeEffect::ChildPtr& child = children[index];
1464 KeyContext childContext = keyContext.forRuntimeEffect(effect, index);
1465
1466 std::optional<ChildType> type = child.type();
1467 if (type == ChildType::kShader) {
1468 AddToKey(childContext, child.shader());
1469 } else if (type == ChildType::kColorFilter) {
1470 AddToKey(childContext, child.colorFilter());
1471 } else if (type == ChildType::kBlender) {
1472 AddToKey(childContext, child.blender());
1473 } else {
1474 // We don't have a child effect. Substitute in a no-op effect.
1475 switch (childInfo[index].type) {
1476 case ChildType::kShader:
1477 // A missing shader returns transparent black
1478 SolidColorShaderBlock::AddBlock(childContext,
1479 SK_PMColor4fTRANSPARENT);
1480 break;
1481
1482 case ChildType::kColorFilter:
1483 // A "passthrough" color filter returns the input color as-is.
1484 keyContext.paintParamsKeyBuilder()->addBlock(BuiltInCodeSnippetID::kPriorOutput);
1485 break;
1486
1487 case ChildType::kBlender:
1488 // A "passthrough" blender performs `blend_src_over(src, dest)`.
1489 AddFixedBlendMode(childContext, SkBlendMode::kSrcOver);
1490 break;
1491 }
1492 }
1493 }
1494
1495 RuntimeEffectBlock::HandleIntrinsics(keyContext, effect);
1496 }
1497
1498 void add_to_key(const KeyContext& keyContext, const SkRuntimeBlender* blender) {
1499 SkASSERT(blender);
1500 sk_sp<SkRuntimeEffect> effect = blender->effect();
1501 SkASSERT(effect);
1502 sk_sp<const SkData> uniforms = SkRuntimeEffectPriv::TransformUniforms(
1503 effect->uniforms(),
1504 blender->uniforms(),
1505 keyContext.dstColorInfo().colorSpace());
1506 SkASSERT(uniforms);
1507
1508 if (!RuntimeEffectBlock::BeginBlock(keyContext, { effect, std::move(uniforms) })) {
1509 RuntimeEffectBlock::AddNoOpEffect(keyContext, effect.get());
1510 return;
1511 }
1512
1513 add_children_to_key(keyContext, blender->children(), effect.get());
1514
1515 keyContext.paintParamsKeyBuilder()->endBlock();
1516 }
1517
1518 } // anonymous namespace
1519
1520 void AddToKey(const KeyContext& keyContext, const SkBlender* blender) {
1521 if (!blender) {
1522 // Calling code assumes a block will be appended. Add a fixed block to preserve shader
1523 // and PaintParamsKey structure in release builds but assert since this should either not
1524 // happen or should be changing high-level logic within PaintParams::toKey().
1525 SkASSERT(false);
1526 AddFixedBlendMode(keyContext, SkBlendMode::kSrcOver);
1527 return;
1528 }
1529 switch (as_BB(blender)->type()) {
1530 #define M(type) \
1531 case SkBlenderBase::BlenderType::k##type: \
1532 add_to_key(keyContext, \
1533 static_cast<const Sk##type##Blender*>(blender)); \
1534 return;
1535 SK_ALL_BLENDERS(M)
1536 #undef M
1537 }
1538 SkUNREACHABLE;
1539 }
1540
1541 //--------------------------------------------------------------------------------------------------
1542 //--------------------------------------------------------------------------------------------------
1543 static SkPMColor4f map_color(const SkColor4f& c,
1544 SkColorSpace* src,
1545 SkColorSpace* dst,
1546 SkAlphaType dstAlphaType) {
1547 SkPMColor4f color = {c.fR, c.fG, c.fB, c.fA};
1548 SkColorSpaceXformSteps(src, kUnpremul_SkAlphaType, dst, dstAlphaType).apply(color.vec());
1549 return color;
1550 }
1551 static void add_to_key(const KeyContext& keyContext, const SkBlendModeColorFilter* filter) {
1552 SkASSERT(filter);
1553
1554 SkPMColor4f color = map_color(filter->color(), sk_srgb_singleton(),
1555 keyContext.dstColorInfo().colorSpace(),
1556 keyContext.dstColorInfo().alphaType());
1557
1558 AddBlendModeColorFilter(keyContext, filter->mode(), color);
1559 }
1560
1561 static void add_to_key(const KeyContext& keyContext, const SkColorSpaceXformColorFilter* filter) {
1562 SkASSERT(filter);
1563
1564 constexpr SkAlphaType kAlphaType = kPremul_SkAlphaType;
1565 ColorSpaceTransformBlock::ColorSpaceTransformData csData(filter->src().get(), kAlphaType,
1566 filter->dst().get(), kAlphaType);
1567 ColorSpaceTransformBlock::AddBlock(keyContext, csData);
1568 }
1569
1570 static void add_to_key(const KeyContext& keyContext, const SkComposeColorFilter* filter) {
1571 SkASSERT(filter);
1572
1573 Compose(keyContext,
1574 /* addInnerToKey= */ [&]() -> void {
1575 AddToKey(keyContext, filter->inner().get());
1576 },
1577 /* addOuterToKey= */ [&]() -> void {
1578 AddToKey(keyContext, filter->outer().get());
1579 });
1580 }
1581
1582 static void add_to_key(const KeyContext& keyContext, const SkGaussianColorFilter*) {
1583 keyContext.paintParamsKeyBuilder()->addBlock(BuiltInCodeSnippetID::kGaussianColorFilter);
1584 }
1585
1586 static void add_to_key(const KeyContext& keyContext, const SkMatrixColorFilter* filter) {
1587 SkASSERT(filter);
1588
1589 bool inHSLA = filter->domain() == SkMatrixColorFilter::Domain::kHSLA;
1590 bool clamp = filter->clamp() == SkMatrixColorFilter::Clamp::kYes;
1591 MatrixColorFilterBlock::MatrixColorFilterData matrixCFData(filter->matrix(), inHSLA, clamp);
1592
1593 MatrixColorFilterBlock::AddBlock(keyContext, matrixCFData);
1594 }
1595
1596 static void add_to_key(const KeyContext& keyContext, const SkRuntimeColorFilter* filter) {
1597 SkASSERT(filter);
1598
1599 sk_sp<SkRuntimeEffect> effect = filter->effect();
1600 sk_sp<const SkData> uniforms = SkRuntimeEffectPriv::TransformUniforms(
1601 effect->uniforms(), filter->uniforms(), keyContext.dstColorInfo().colorSpace());
1602 SkASSERT(uniforms);
1603
1604 if (!RuntimeEffectBlock::BeginBlock(keyContext, { effect, std::move(uniforms) })) {
1605 RuntimeEffectBlock::AddNoOpEffect(keyContext, effect.get());
1606 return;
1607 }
1608
1609 add_children_to_key(keyContext, filter->children(), effect.get());
1610
1611 keyContext.paintParamsKeyBuilder()->endBlock();
1612 }
1613
1614 static void add_to_key(const KeyContext& keyContext, const SkTableColorFilter* filter) {
1615 SkASSERT(filter);
1616
1617 sk_sp<TextureProxy> proxy = RecorderPriv::CreateCachedProxy(keyContext.recorder(),
1618 filter->bitmap(),
1619 "TableColorFilterTexture");
1620 if (!proxy) {
1621 SKGPU_LOG_W("Couldn't create TableColorFilter's table");
1622
1623 // Return the input color as-is.
1624 keyContext.paintParamsKeyBuilder()->addBlock(BuiltInCodeSnippetID::kPriorOutput);
1625 return;
1626 }
1627
1628 TableColorFilterBlock::TableColorFilterData data(std::move(proxy));
1629
1630 TableColorFilterBlock::AddBlock(keyContext, data);
1631 }
1632
1633 static void add_to_key(const KeyContext& keyContext, const SkWorkingFormatColorFilter* filter) {
1634 SkASSERT(filter);
1635
1636 const SkColorInfo& dstInfo = keyContext.dstColorInfo();
1637 const SkAlphaType dstAT = dstInfo.alphaType();
1638 sk_sp<SkColorSpace> dstCS = dstInfo.refColorSpace();
1639 if (!dstCS) {
1640 dstCS = SkColorSpace::MakeSRGB();
1641 }
1642
1643 SkAlphaType workingAT;
1644 sk_sp<SkColorSpace> workingCS = filter->workingFormat(dstCS, &workingAT);
1645 KeyContext workingContext =
1646 keyContext.withColorInfo({dstInfo.colorType(), workingAT, workingCS});
1647
1648 // Use two nested compose blocks to chain (dst->working), child, and (working->dst) together
1649 // while appearing as one block to the parent node.
1650 Compose(keyContext,
1651 /* addInnerToKey= */ [&]() -> void {
1652 // Inner compose
1653 Compose(keyContext,
1654 /* addInnerToKey= */ [&]() -> void {
1655 // Innermost (inner of inner compose)
1656 ColorSpaceTransformBlock::ColorSpaceTransformData data1(
1657 dstCS.get(), dstAT, workingCS.get(), workingAT);
1658 ColorSpaceTransformBlock::AddBlock(keyContext, data1);
1659 },
1660 /* addOuterToKey= */ [&]() -> void {
1661 // Middle (outer of inner compose)
1662 AddToKey(workingContext, filter->child().get());
1663 });
1664 },
1665 /* addOuterToKey= */ [&]() -> void {
1666 // Outermost (outer of outer compose)
1667 ColorSpaceTransformBlock::ColorSpaceTransformData data2(
1668 workingCS.get(), workingAT, dstCS.get(), dstAT);
1669 ColorSpaceTransformBlock::AddBlock(keyContext, data2);
1670 });
1671 }
1672
1673 void AddToKey(const KeyContext& keyContext, const SkColorFilter* filter) {
1674 if (!filter) {
1675 // Calling code assumes a block will be appended. Add a fixed block to preserve shader
1676 // and PaintParamsKey structure in release builds but assert since this should either not
1677 // happen or should be changing high-level logic within PaintParams::toKey().
1678 SkASSERT(false);
1679 keyContext.paintParamsKeyBuilder()->addBlock(BuiltInCodeSnippetID::kPriorOutput);
1680 return;
1681 }
1682 switch (as_CFB(filter)->type()) {
1683 case SkColorFilterBase::Type::kNoop:
1684 // Return the input color as-is.
1685 keyContext.paintParamsKeyBuilder()->addBlock(BuiltInCodeSnippetID::kPriorOutput);
1686 return;
1687 #define M(type) \
1688 case SkColorFilterBase::Type::k##type: \
1689 add_to_key(keyContext, \
1690 static_cast<const Sk##type##ColorFilter*>(filter)); \
1691 return;
1692 SK_ALL_COLOR_FILTERS(M)
1693 #undef M
1694 }
1695 SkUNREACHABLE;
1696 }
1697
1698 // ==================================================================
1699
1700 static void add_to_key(const KeyContext& keyContext, const SkBlendShader* shader) {
1701 SkASSERT(shader);
1702
1703 Blend(keyContext,
1704 /* addBlendToKey= */ [&] () -> void {
1705 AddBlendMode(keyContext, shader->mode());
1706 },
1707 /* addSrcToKey= */ [&]() -> void {
1708 AddToKey(keyContext, shader->src().get());
1709 },
1710 /* addDstToKey= */ [&]() -> void {
1711 AddToKey(keyContext, shader->dst().get());
1712 });
1713 }
1714
1715 template <typename AddInnerToKeyT>
1716 static void add_local_matrix_to_key(const KeyContext& keyContext,
1717 const SkMatrix& localMatrix,
1718 const SkMatrix& postInverseMatrix,
1719 AddInnerToKeyT addInnerToKey) {
1720 auto lmInverse = localMatrix.invert();
1721 if (!lmInverse) {
1722 keyContext.paintParamsKeyBuilder()->addErrorBlock();
1723 return;
1724 }
1725
1726 lmInverse->postConcat(postInverseMatrix);
1727
1728 LocalMatrixShaderBlock::BeginBlock(keyContext,
1729 LocalMatrixShaderBlock::LMShaderData(*lmInverse));
1730 KeyContextWithLocalMatrix lmContext(keyContext, localMatrix);
1731 addInnerToKey(lmContext);
1732 keyContext.paintParamsKeyBuilder()->endBlock();
1733 }
1734
1735 static void add_to_key(const KeyContext& keyContext, const SkCTMShader* shader) {
1736 // CTM shaders are always given device coordinates, so we don't have to modify the CTM itself
1737 // with keyContext's local transform.
1738 add_local_matrix_to_key(keyContext,
1739 /*localMatrix=*/shader->ctm(),
1740 /*postInverseMatrix=*/SkMatrix::I(),
1741 [&](const KeyContext& childCtx) {
1742 AddToKey(childCtx, shader->proxyShader().get());
1743 });
1744 }
1745
1746 static void add_to_key(const KeyContext& keyContext, const SkColorShader* shader) {
1747 SkASSERT(shader);
1748
1749 SkPMColor4f color = map_color(shader->color(), sk_srgb_singleton(),
1750 keyContext.dstColorInfo().colorSpace(),
1751 keyContext.dstColorInfo().alphaType());
1752
1753 SolidColorShaderBlock::AddBlock(keyContext, color);
1754 }
1755
1756 static void add_to_key(const KeyContext& keyContext, const SkColorFilterShader* shader) {
1757 SkASSERT(shader);
1758
1759 Compose(keyContext,
1760 /* addInnerToKey= */ [&]() -> void {
1761 AddToKey(keyContext, shader->shader().get());
1762 },
1763 /* addOuterToKey= */ [&]() -> void {
1764 AddToKey(keyContext, shader->filter().get());
1765 });
1766 }
1767
1768 static void add_to_key(const KeyContext& keyContext, const SkCoordClampShader* shader) {
1769 SkASSERT(shader);
1770
1771 CoordClampShaderBlock::CoordClampData data(shader->subset());
1772
1773 CoordClampShaderBlock::BeginBlock(keyContext, data);
1774
1775 // Subtleties in clamping implementation can lead to texture samples at non pixel aligned
1776 // coordinates, particularly if clamped to non-texel centers.
1777 AddToKey(keyContext.withExtraFlags(KeyGenFlags::kDisableSamplingOptimization),
1778 shader->shader().get());
1779
1780 keyContext.paintParamsKeyBuilder()->endBlock();
1781 }
1782
1783 static void add_to_key(const KeyContext& keyContext, const SkEmptyShader*) {
1784 keyContext.paintParamsKeyBuilder()->addBlock(BuiltInCodeSnippetID::kPriorOutput);
1785 }
1786
1787 static void add_yuv_image_to_key(const KeyContext& keyContext,
1788 const SkImage* imageToDraw,
1789 SkRect subset,
1790 SkSamplingOptions sampling,
1791 SkTileMode tileModeX,
1792 SkTileMode tileModeY,
1793 bool isRaw) {
1794 SkASSERT(!imageToDraw->isAlphaOnly());
1795
1796 const Image_YUVA* yuvaImage = static_cast<const Image_YUVA*>(imageToDraw);
1797 const SkYUVAInfo& yuvaInfo = yuvaImage->yuvaInfo();
1798 // We would want to add a translation to the local matrix to handle other sitings.
1799 SkASSERT(yuvaInfo.sitingX() == SkYUVAInfo::Siting::kCentered);
1800 SkASSERT(yuvaInfo.sitingY() == SkYUVAInfo::Siting::kCentered);
1801
1802 YUVImageShaderBlock::ImageData imgData(sampling,
1803 tileModeX,
1804 tileModeY,
1805 imageToDraw->dimensions(),
1806 subset);
1807 for (int locIndex = 0; locIndex < SkYUVAInfo::kYUVAChannelCount; ++locIndex) {
1808 const TextureProxyView& view = yuvaImage->proxyView(locIndex);
1809 if (view) {
1810 imgData.fTextureProxies[locIndex] = view.refProxy();
1811 // The view's swizzle has the data channel for the YUVA location in all slots, so read
1812 // the 0th slot to determine fChannelSelect
1813 switch(view.swizzle()[0]) {
1814 case 'r': imgData.fChannelSelect[locIndex] = {1.f, 0.f, 0.f, 0.f}; break;
1815 case 'g': imgData.fChannelSelect[locIndex] = {0.f, 1.f, 0.f, 0.f}; break;
1816 case 'b': imgData.fChannelSelect[locIndex] = {0.f, 0.f, 1.f, 0.f}; break;
1817 case 'a': imgData.fChannelSelect[locIndex] = {0.f, 0.f, 0.f, 1.f}; break;
1818 default:
1819 imgData.fChannelSelect[locIndex] = {0.f, 0.f, 0.f, 0.f};
1820 SkDEBUGFAILF("Unexpected swizzle for YUVA data: %c", view.swizzle()[0]);
1821 break;
1822 }
1823 } else {
1824 // Only the A proxy view should be null, in which case we bind the Y proxy view to
1825 // pass validation and send all 1s for the channel selection to signal opaque alpha.
1826 SkASSERT(locIndex == 3);
1827 imgData.fTextureProxies[locIndex] = yuvaImage->proxyView(SkYUVAInfo::kY).refProxy();
1828 imgData.fChannelSelect[locIndex] = {1.f, 1.f, 1.f, 1.f};
1829 // For the hardcoded sampling no-swizzle case, we use this to set constant alpha
1830 imgData.fAlphaParam = 1;
1831 }
1832 }
1833
1834 auto [ssx, ssy] = yuvaImage->uvSubsampleFactors();
1835 if (ssx > 1 || ssy > 1) {
1836 // We need to adjust the image size we use for sampling to reflect the actual image size of
1837 // the UV planes. However, since our coordinates are in Y's texel space we need to scale
1838 // accordingly.
1839 const TextureProxyView& view = yuvaImage->proxyView(SkYUVAInfo::kU);
1840 imgData.fImgSizeUV = {view.dimensions().width()*ssx, view.dimensions().height()*ssy};
1841 // This promotion of nearest to linear filtering for UV planes exists to mimic
1842 // libjpeg[-turbo]'s do_fancy_upsampling option. We will filter the subsampled plane,
1843 // however we want to filter at a fixed point for each logical image pixel to simulate
1844 // nearest neighbor. In the shader we detect that the UV filtermode doesn't match the Y
1845 // filtermode, and snap to Y pixel centers.
1846 if (imgData.fSampling.filter == SkFilterMode::kNearest) {
1847 imgData.fSamplingUV = SkSamplingOptions(SkFilterMode::kLinear,
1848 imgData.fSampling.mipmap);
1849 // Consider a logical image pixel at the edge of the subset. When computing the logical
1850 // pixel color value we should use a blend of two values from the subsampled plane.
1851 // Depending on where the subset edge falls in actual subsampled plane, one of those
1852 // values may come from outside the subset. Hence, we will use the default inset
1853 // in Y texel space of 1/2. This applies the wrap mode to the subset but allows
1854 // linear filtering to read pixels that are just outside the subset.
1855 imgData.fLinearFilterUVInset.fX = 0.5f;
1856 imgData.fLinearFilterUVInset.fY = 0.5f;
1857 } else if (imgData.fSampling.filter == SkFilterMode::kLinear) {
1858 // We need to inset so that we aren't sampling outside the subset, but no farther.
1859 // Start by mapping the subset to UV texel space
1860 float scaleX = 1.f/ssx;
1861 float scaleY = 1.f/ssy;
1862 SkRect subsetUV = {imgData.fSubset.fLeft *scaleX,
1863 imgData.fSubset.fTop *scaleY,
1864 imgData.fSubset.fRight *scaleX,
1865 imgData.fSubset.fBottom*scaleY};
1866 // Round to UV texel borders
1867 SkIRect iSubsetUV = subsetUV.roundOut();
1868 // Inset in UV and map back to Y texel space. This gives us the largest possible
1869 // inset rectangle that will not sample outside of the subset texels in UV space.
1870 SkRect insetRectUV = {(iSubsetUV.fLeft +0.5f)*ssx,
1871 (iSubsetUV.fTop +0.5f)*ssy,
1872 (iSubsetUV.fRight -0.5f)*ssx,
1873 (iSubsetUV.fBottom-0.5f)*ssy};
1874 // Compute intersection with original inset
1875 SkRect insetRect = imgData.fSubset.makeOutset(-0.5f, -0.5f);
1876 (void) insetRect.intersect(insetRectUV);
1877 // Compute max inset values to ensure we always remain within the subset.
1878 imgData.fLinearFilterUVInset = {std::max(insetRect.fLeft - imgData.fSubset.fLeft,
1879 imgData.fSubset.fRight - insetRect.fRight),
1880 std::max(insetRect.fTop - imgData.fSubset.fTop,
1881 imgData.fSubset.fBottom - insetRect.fBottom)};
1882 }
1883 }
1884
1885 float yuvM[20];
1886 SkColorMatrix_YUV2RGB(yuvaInfo.yuvColorSpace(), yuvM);
1887 // We drop the fourth column entirely since the transformation
1888 // should not depend on alpha. The fifth column is sent as a separate
1889 // vector. The fourth row is also dropped entirely because alpha should
1890 // never be modified.
1891 SkASSERT(yuvM[3] == 0 && yuvM[8] == 0 && yuvM[13] == 0 && yuvM[18] == 1);
1892 SkASSERT(yuvM[15] == 0 && yuvM[16] == 0 && yuvM[17] == 0 && yuvM[19] == 0);
1893 imgData.fYUVtoRGBMatrix.setAll(
1894 yuvM[ 0], yuvM[ 1], yuvM[ 2],
1895 yuvM[ 5], yuvM[ 6], yuvM[ 7],
1896 yuvM[10], yuvM[11], yuvM[12]
1897 );
1898 imgData.fYUVtoRGBTranslate = {yuvM[4], yuvM[9], yuvM[14]};
1899
1900 SkColorSpaceXformSteps steps;
1901 SkASSERT(steps.fFlags.mask() == 0); // By default, the colorspace should have no effect
1902
1903 // The actual output from the YUV image shader for non-opaque images is unpremul so
1904 // we need to correct for the fact that the Image_YUVA_Graphite's alpha type is premul.
1905 SkAlphaType srcAT = imageToDraw->alphaType() == kPremul_SkAlphaType
1906 ? kUnpremul_SkAlphaType
1907 : imageToDraw->alphaType();
1908 if (isRaw) {
1909 // Because we've avoided the premul alpha step in the YUV shader, we need to make sure
1910 // it happens when drawing unpremul (i.e., non-opaque) images.
1911 steps = SkColorSpaceXformSteps(imageToDraw->colorSpace(),
1912 srcAT,
1913 imageToDraw->colorSpace(),
1914 imageToDraw->alphaType());
1915 } else {
1916 SkAlphaType dstAT = keyContext.dstColorInfo().alphaType();
1917 // Setting the dst alphaType up this way is necessary because otherwise the constructor
1918 // for SkColorSpaceXformSteps will set dstAT = srcAT when dstAT == kOpaque, and the
1919 // premul step needed for non-opaque images won't occur.
1920 if (dstAT == kOpaque_SkAlphaType && srcAT == kUnpremul_SkAlphaType) {
1921 dstAT = kPremul_SkAlphaType;
1922 }
1923 steps = SkColorSpaceXformSteps(imageToDraw->colorSpace(),
1924 srcAT,
1925 keyContext.dstColorInfo().colorSpace(),
1926 dstAT);
1927 }
1928 ColorSpaceTransformBlock::ColorSpaceTransformData data(steps);
1929
1930 Compose(keyContext,
1931 /* addInnerToKey= */ [&]() -> void {
1932 YUVImageShaderBlock::AddBlock(keyContext, imgData);
1933 },
1934 /* addOuterToKey= */ [&]() -> void {
1935 ColorSpaceTransformBlock::AddBlock(keyContext, data);
1936 });
1937 }
1938
1939 static void add_image_to_key(const KeyContext& keyContext,
1940 const SkImage* image,
1941 SkRect subset,
1942 SkSamplingOptions sampling,
1943 SkTileMode tileModeX,
1944 SkTileMode tileModeY,
1945 bool isRaw) {
1946 auto [ imageToDraw, newSampling ] = GetGraphiteBacked(keyContext.recorder(),
1947 image,
1948 sampling);
1949 if (!imageToDraw) {
1950 SKGPU_LOG_W("Couldn't convert SkImage to a Graphite-backed representation");
1951 keyContext.paintParamsKeyBuilder()->addErrorBlock();
1952 return;
1953 }
1954
1955 // We must call notifyInUse() here to link the final, Graphite-backed 'imageToDraw'
1956 // to the DrawContext that will sample it.
1957 //
1958 // This is necessary for two primary cases:
1959 // 1. The original image was not Graphite-backed.
1960 // 2. The original image was already Graphite-backed, but produced through Image::Copy, possibly
1961 // from a different DrawContext.
1962 //
1963 // Failing to call this can lead to leaked Device and DrawContext memory (b/338453542).
1964 SkASSERT(as_IB(imageToDraw)->isGraphiteBacked());
1965 SkASSERT(keyContext.drawContext());
1966 static_cast<Image_Base*>(imageToDraw.get())->notifyInUse(keyContext.recorder(),
1967 keyContext.drawContext());
1968 if (as_IB(imageToDraw)->isYUVA()) {
1969 return add_yuv_image_to_key(keyContext,
1970 imageToDraw.get(),
1971 subset,
1972 newSampling,
1973 tileModeX,
1974 tileModeY,
1975 isRaw);
1976 }
1977
1978 auto view = AsView(imageToDraw.get());
1979 SkASSERT(newSampling.mipmap == SkMipmapMode::kNone || view.mipmapped() == Mipmapped::kYes);
1980
1981 ImageShaderBlock::ImageData imgData(newSampling,
1982 tileModeX,
1983 tileModeY,
1984 view.proxy()->dimensions(),
1985 subset);
1986
1987 // Here we detect pixel aligned blit-like image draws. Some devices have low precision filtering
1988 // and will produce degraded (blurry) images unexpectedly for sequential exact pixel blits when
1989 // not using nearest filtering. This is common for canvas scrolling implementations. Forcing
1990 // nearest filtering when possible can also be a minor perf/power optimization depending on the
1991 // hardware.
1992 bool samplingHasNoEffect = false;
1993 // Cubic sampling is will not filter the same as nearest even when pixel aligned.
1994 if (!(keyContext.flags() & KeyGenFlags::kDisableSamplingOptimization || newSampling.useCubic)) {
1995 SkMatrix totalM = keyContext.local2Dev().asM33();
1996 if (keyContext.localMatrix()) {
1997 totalM.preConcat(*keyContext.localMatrix());
1998 }
1999 totalM.normalizePerspective();
2000 // The matrix should be translation with only pixel aligned 2d translation.
2001 samplingHasNoEffect = totalM.isTranslate() && SkScalarIsInt(totalM.getTranslateX()) &&
2002 SkScalarIsInt(totalM.getTranslateY());
2003 }
2004
2005 imgData.fSampling = samplingHasNoEffect ? SkFilterMode::kNearest : newSampling;
2006 imgData.fTextureProxy = view.refProxy();
2007 skgpu::Swizzle readSwizzle = view.swizzle();
2008 // If the color type is alpha-only, propagate the alpha value to the other channels.
2009 if (imageToDraw->isAlphaOnly()) {
2010 readSwizzle = skgpu::Swizzle::Concat(readSwizzle, skgpu::Swizzle("000a"));
2011 }
2012 ColorSpaceTransformBlock::ColorSpaceTransformData colorXformData(
2013 SwizzleClassToReadEnum(readSwizzle));
2014
2015 if (!isRaw) {
2016 colorXformData.fSteps = SkColorSpaceXformSteps(imageToDraw->colorSpace(),
2017 imageToDraw->alphaType(),
2018 keyContext.dstColorInfo().colorSpace(),
2019 keyContext.dstColorInfo().alphaType());
2020
2021 if (imageToDraw->isAlphaOnly() &&
2022 !(keyContext.flags() & KeyGenFlags::kDisableAlphaOnlyImageColorization)) {
2023 // NOTE: Alpha is not affected by colorspace conversion to the dst, and the paint color
2024 // is already xformed to the dst, but the ColorSpaceTransformBlock is necessary to apply
2025 // any read swizzle, which is often necessary for alpha-only color types.
2026 Blend(keyContext,
2027 /* addBlendToKey= */ [&] () -> void {
2028 AddFixedBlendMode(keyContext, SkBlendMode::kDstIn);
2029 },
2030 /* addSrcToKey= */ [&] () -> void {
2031 Compose(keyContext,
2032 /* addInnerToKey= */ [&]() -> void {
2033 ImageShaderBlock::AddBlock(keyContext,
2034 imgData);
2035 },
2036 /* addOuterToKey= */ [&]() -> void {
2037 ColorSpaceTransformBlock::AddBlock(keyContext,
2038 colorXformData);
2039 });
2040 },
2041 /* addDstToKey= */ [&]() -> void {
2042 RGBPaintColorBlock::AddBlock(keyContext);
2043 });
2044 return;
2045 }
2046 }
2047
2048 Compose(keyContext,
2049 /* addInnerToKey= */ [&]() -> void {
2050 ImageShaderBlock::AddBlock(keyContext, imgData);
2051 },
2052 /* addOuterToKey= */ [&]() -> void {
2053 ColorSpaceTransformBlock::AddBlock(keyContext, colorXformData);
2054 });
2055 }
2056
2057 static void add_to_key(const KeyContext& keyContext, const SkImageShader* shader) {
2058 SkASSERT(shader);
2059 add_image_to_key(keyContext, shader->image().get(), shader->subset(), shader->sampling(),
2060 shader->tileModeX(), shader->tileModeY(), shader->isRaw());
2061 }
2062
2063 static SkMatrix get_image_origin_matrix(const SkImage* image) {
2064 // If the image is not graphite backed then we can assume the origin will be TopLeft as we
2065 // require that in the ImageProvider utility. Also Graphite YUV images are assumed to be TopLeft
2066 // origin.
2067 SkASSERT(image);
2068 const auto* imgBase = as_IB(image);
2069 if (imgBase->isGraphiteBacked()) {
2070 // The YUV formats can encode their own origin including reflection and rotation,
2071 // so we need to concat that to the local matrix transform.
2072 if (imgBase->isYUVA()) {
2073 auto imgYUVA = static_cast<const Image_YUVA*>(imgBase);
2074 return imgYUVA->yuvaInfo().inverseOriginMatrix();
2075 } else {
2076 const auto& view = static_cast<const Image*>(imgBase)->textureProxyView();
2077 if (view.origin() == Origin::kBottomLeft) {
2078 return SkMatrix::ScaleTranslate(1.f, -1.f, 0.f, view.height());
2079 }
2080 }
2081 }
2082 // Otherwise no modification required
2083 return SkMatrix::I();
2084 }
2085
2086 static SkMatrix get_gradient_matrix(const SkGradientBaseShader* gradShader) {
2087 // Override the conical gradient matrix since graphite uses a different algorithm
2088 // than the ganesh and raster backends.
2089 if (gradShader->asGradient() == SkShaderBase::GradientType::kConical) {
2090 auto conicalShader = static_cast<const SkConicalGradient*>(gradShader);
2091
2092 if (conicalShader->getType() == SkConicalGradient::Type::kRadial) {
2093 SkMatrix conicalMatrix = SkMatrix::Translate(-conicalShader->getStartCenter());
2094 float scale = sk_ieee_float_divide(1, conicalShader->getDiffRadius());
2095 conicalMatrix.postScale(scale, scale);
2096 return conicalMatrix;
2097 } else {
2098 auto mx = (SkConicalGradient::MapToUnitX(conicalShader->getStartCenter(),
2099 conicalShader->getEndCenter()));
2100 return *mx;
2101 }
2102 } else {
2103 // Use the standard gradient matrix for other types
2104 return gradShader->getGradientMatrix();
2105 }
2106 }
2107
2108 static void add_to_key(const KeyContext& keyContext, const SkLocalMatrixShader* shader) {
2109 SkASSERT(shader);
2110 // Fold the texture's origin flip into the local matrix so that the image shader doesn't need
2111 // additional state; the same goes for gradient shader's gradient matrix coord conversion.
2112 SkShaderBase* wrappedShaderBase = as_SB(shader->wrappedShader().get());
2113 SkMatrix xtraMatrix = SkMatrix::I();
2114 if (wrappedShaderBase->type() == SkShaderBase::ShaderType::kImage) {
2115 auto imgShader = static_cast<const SkImageShader*>(wrappedShaderBase);
2116 xtraMatrix = get_image_origin_matrix(imgShader->image().get());
2117 } else if (wrappedShaderBase->type() == SkShaderBase::ShaderType::kGradientBase) {
2118 auto gradShader = static_cast<const SkGradientBaseShader*>(wrappedShaderBase);
2119 xtraMatrix = get_gradient_matrix(gradShader);
2120 }
2121
2122 add_local_matrix_to_key(keyContext,
2123 shader->localMatrix(),
2124 /*postInverseMatrix=*/xtraMatrix,
2125 [&](const KeyContext& childCtx) {
2126 AddToKey(childCtx, wrappedShaderBase);
2127 });
2128 }
2129
2130 // If either of these change then the corresponding change must also be made in the SkSL
2131 // perlin_noise_shader function.
2132 static_assert((int)SkPerlinNoiseShaderType::kFractalNoise ==
2133 (int)PerlinNoiseShaderBlock::Type::kFractalNoise);
2134 static_assert((int)SkPerlinNoiseShaderType::kTurbulence ==
2135 (int)PerlinNoiseShaderBlock::Type::kTurbulence);
2136
2137 static void add_to_key(const KeyContext& keyContext, const SkPerlinNoiseShader* shader) {
2138 SkASSERT(shader);
2139 SkASSERT(shader->numOctaves());
2140
2141 std::unique_ptr<SkPerlinNoiseShader::PaintingData> paintingData = shader->getPaintingData();
2142 paintingData->generateBitmaps();
2143
2144 sk_sp<TextureProxy> perm =
2145 RecorderPriv::CreateCachedProxy(keyContext.recorder(),
2146 paintingData->getPermutationsBitmap(),
2147 "PerlinNoisePermTable");
2148
2149 sk_sp<TextureProxy> noise =
2150 RecorderPriv::CreateCachedProxy(keyContext.recorder(), paintingData->getNoiseBitmap(),
2151 "PerlinNoiseNoiseTable");
2152
2153 if (!perm || !noise) {
2154 SKGPU_LOG_W("Couldn't create tables for PerlinNoiseShader");
2155 keyContext.paintParamsKeyBuilder()->addErrorBlock();
2156 return;
2157 }
2158
2159 PerlinNoiseShaderBlock::PerlinNoiseData perlinData(
2160 static_cast<PerlinNoiseShaderBlock::Type>(shader->noiseType()),
2161 paintingData->fBaseFrequency,
2162 shader->numOctaves(),
2163 {paintingData->fStitchDataInit.fWidth, paintingData->fStitchDataInit.fHeight});
2164
2165 perlinData.fPermutationsProxy = std::move(perm);
2166 perlinData.fNoiseProxy = std::move(noise);
2167
2168 PerlinNoiseShaderBlock::AddBlock(keyContext, perlinData);
2169 }
2170
2171 static void add_to_key(const KeyContext& keyContext,
2172 const SkPictureShader* shader) {
2173 SkASSERT(shader);
2174
2175 Recorder* recorder = keyContext.recorder();
2176 const Caps* caps = recorder->priv().caps();
2177
2178 // TODO: We'll need additional plumbing to get the correct props from our callers. In
2179 // particular we'll need to expand the keyContext to have the surfaceProps.
2180 SkSurfaceProps props{};
2181
2182 SkMatrix totalM = keyContext.local2Dev().asM33();
2183 if (keyContext.localMatrix()) {
2184 totalM.preConcat(*keyContext.localMatrix());
2185 }
2186 auto info = SkPictureShader::CachedImageInfo::Make(shader->tile(),
2187 totalM,
2188 keyContext.dstColorInfo().colorType(),
2189 keyContext.dstColorInfo().colorSpace(),
2190 caps->maxTextureSize(),
2191 props);
2192 if (!info.success) {
2193 SKGPU_LOG_W("Couldn't access PictureShaders' Image info");
2194 keyContext.paintParamsKeyBuilder()->addErrorBlock();
2195 return;
2196 }
2197
2198 // NOTE: While this is intended to be a "scratch" surface, we don't use MakeScratch() because
2199 // the SkPicture could contain arbitrary operations that rely on the Recorder's atlases, which
2200 // means the Surface's device has to participate in flushing when the atlas fills up.
2201 // TODO: Can this be an approx-fit image that's generated?
2202 // TODO: right now we're explicitly not caching here. We could expand the ImageProvider
2203 // API to include already Graphite-backed images, add a Recorder-local cache or add
2204 // rendered-picture images to the global cache.
2205 sk_sp<Surface> surface = Surface::Make(recorder,
2206 info.imageInfo,
2207 "PictureShaderTexture",
2208 Budgeted::kYes,
2209 Mipmapped::kNo,
2210 SkBackingFit::kExact,
2211 &info.props);
2212 if (!surface) {
2213 SKGPU_LOG_W("Could not create surface to render PictureShader");
2214 keyContext.paintParamsKeyBuilder()->addErrorBlock();
2215 return;
2216 }
2217
2218 sk_sp<SkImage> img = info.makeImage(std::move(surface), shader->picture().get());
2219 // TODO: 'img' did not exist when notify_in_use() was called, but ideally the DrawTask to render
2220 // into 'surface' would be a child of the current device. While we push all tasks to the root
2221 // list this works out okay, but will need to be addressed before we move off that system.
2222 if (!img) {
2223 SKGPU_LOG_W("Couldn't create SkImage for PictureShader");
2224 keyContext.paintParamsKeyBuilder()->addErrorBlock();
2225 return;
2226 }
2227
2228 const auto shaderLM = SkMatrix::Scale(1.f/info.tileScale.width(), 1.f/info.tileScale.height());
2229 sk_sp<SkShader> imgShader = img->makeShader(shader->tileModeX(), shader->tileModeY(),
2230 SkSamplingOptions(shader->filter()), &shaderLM);
2231 if (!imgShader) {
2232 SKGPU_LOG_W("Couldn't create SkImageShader for PictureShader");
2233 keyContext.paintParamsKeyBuilder()->addErrorBlock();
2234 return;
2235 }
2236
2237 AddToKey(keyContext, imgShader.get());
2238 }
2239
2240 static void add_to_key(const KeyContext& keyContext,
2241 const SkRuntimeShader* shader) {
2242 SkASSERT(shader);
2243 sk_sp<SkRuntimeEffect> effect = shader->effect();
2244 sk_sp<const SkData> uniforms = SkRuntimeEffectPriv::TransformUniforms(
2245 effect->uniforms(),
2246 shader->uniformData(keyContext.dstColorInfo().colorSpace()),
2247 keyContext.dstColorInfo().colorSpace());
2248 SkASSERT(uniforms);
2249
2250 if (!RuntimeEffectBlock::BeginBlock(keyContext, { effect, std::move(uniforms) })) {
2251 RuntimeEffectBlock::AddNoOpEffect(keyContext, effect.get());
2252 return;
2253 }
2254
2255 add_children_to_key(keyContext, shader->children(), effect.get());
2256
2257 keyContext.paintParamsKeyBuilder()->endBlock();
2258 }
2259
2260 static void add_to_key(const KeyContext& keyContext,
2261 const SkTransformShader* shader) {
2262 SKGPU_LOG_W("Raster-only SkShader (SkTransformShader) encountered");
2263 keyContext.paintParamsKeyBuilder()->addErrorBlock();
2264 }
2265
2266 static void add_to_key(const KeyContext& keyContext,
2267 const SkTriColorShader* shader) {
2268 SKGPU_LOG_W("Raster-only SkShader (SkTriColorShader) encountered");
2269 keyContext.paintParamsKeyBuilder()->addErrorBlock();
2270 }
2271
2272 static void add_to_key(const KeyContext& keyContext,
2273 const SkWorkingColorSpaceShader* shader) {
2274 SkASSERT(shader);
2275
2276 const SkColorInfo& dstInfo = keyContext.dstColorInfo();
2277 const SkAlphaType dstAT = dstInfo.alphaType();
2278 sk_sp<SkColorSpace> dstCS = dstInfo.refColorSpace();
2279 if (!dstCS) {
2280 dstCS = SkColorSpace::MakeSRGB();
2281 }
2282
2283 // It requires C++20 to use an auto structured binding and then reference them in the lambda.
2284 sk_sp<SkColorSpace> inputCS, outputCS;
2285 SkAlphaType workingAT;
2286 std::tie(inputCS, outputCS, workingAT) = shader->workingSpace(dstCS, dstAT);
2287 KeyContext workingContext = keyContext.withColorInfo({dstInfo.colorType(), workingAT, inputCS});
2288
2289 // Compose the inner shader (in the input space) with a (output->dst) transform, under the
2290 // assumption that the child shader handles conversion between input and output CS/alpha types.
2291 Compose(keyContext,
2292 /* addInnerToKey= */ [&]() -> void {
2293 AddToKey(workingContext, shader->shader().get());
2294 },
2295 /* addOuterToKey= */ [&]() -> void {
2296 ColorSpaceTransformBlock::ColorSpaceTransformData data(
2297 outputCS.get(), workingAT, dstCS.get(), dstAT);
2298 ColorSpaceTransformBlock::AddBlock(keyContext, data);
2299 });
2300 }
2301
2302 static SkBitmap create_color_and_offset_bitmap(int numStops,
2303 const SkPMColor4f* colors,
2304 const float* offsets) {
2305 SkBitmap colorsAndOffsetsBitmap;
2306
2307 colorsAndOffsetsBitmap.allocPixels(
2308 SkImageInfo::Make(numStops, 2, kRGBA_F16_SkColorType, kPremul_SkAlphaType));
2309
2310 for (int i = 0; i < numStops; i++) {
2311 // TODO: there should be a way to directly set a premul pixel in a bitmap with
2312 // a premul color.
2313 SkColor4f unpremulColor = colors[i].unpremul();
2314 colorsAndOffsetsBitmap.erase(unpremulColor, SkIRect::MakeXYWH(i, 0, 1, 1));
2315
2316 float offset = offsets ? offsets[i] : SkIntToFloat(i) / (numStops - 1);
2317 SkASSERT(offset >= 0.0f && offset <= 1.0f);
2318
2319 int exponent;
2320 float mantissa = frexp(offset, &exponent);
2321
2322 SkHalf halfE = SkFloatToHalf(exponent);
2323 if ((int)SkHalfToFloat(halfE) != exponent) {
2324 SKGPU_LOG_W("Encoding gradient to f16 failed");
2325 return {};
2326 }
2327
2328 #if defined(SK_DEBUG)
2329 SkHalf halfM = SkFloatToHalf(mantissa);
2330
2331 float restored = ldexp(SkHalfToFloat(halfM), (int)SkHalfToFloat(halfE));
2332 float error = abs(restored - offset);
2333 SkASSERT(error < 0.001f);
2334 #endif
2335
2336 // TODO: we're only using 2 of the f16s here. The encoding could be altered to better
2337 // preserve precision. This encoding yields < 0.001f error for 2^20 evenly spaced stops.
2338 colorsAndOffsetsBitmap.erase(SkColor4f{mantissa, (float)exponent, 0, 1},
2339 SkIRect::MakeXYWH(i, 1, 1, 1));
2340 }
2341
2342 return colorsAndOffsetsBitmap;
2343 }
2344
2345 // Please see GrGradientShader.cpp::make_interpolated_to_dst for substantial comments
2346 // as to why this code is structured this way.
2347 static void make_interpolated_to_dst(const KeyContext& keyContext,
2348 const GradientShaderBlocks::GradientData& gradData,
2349 const SkGradient::Interpolation& interp,
2350 SkColorSpace* intermediateCS) {
2351 using ColorSpace = SkGradient::Interpolation::ColorSpace;
2352
2353 bool inputPremul = static_cast<bool>(interp.fInPremul);
2354
2355 switch (interp.fColorSpace) {
2356 case ColorSpace::kLab:
2357 case ColorSpace::kOKLab:
2358 case ColorSpace::kOKLabGamutMap:
2359 case ColorSpace::kLCH:
2360 case ColorSpace::kOKLCH:
2361 case ColorSpace::kOKLCHGamutMap:
2362 case ColorSpace::kHSL:
2363 case ColorSpace::kHWB:
2364 inputPremul = false;
2365 break;
2366 default:
2367 break;
2368 }
2369
2370 const SkColorInfo& dstColorInfo = keyContext.dstColorInfo();
2371
2372 SkColorSpace* dstColorSpace =
2373 dstColorInfo.colorSpace() ? dstColorInfo.colorSpace() : sk_srgb_singleton();
2374
2375 SkAlphaType intermediateAlphaType = inputPremul ? kPremul_SkAlphaType : kUnpremul_SkAlphaType;
2376
2377 ColorSpaceTransformBlock::ColorSpaceTransformData data(
2378 intermediateCS, intermediateAlphaType, dstColorSpace, dstColorInfo.alphaType());
2379
2380 // The gradient block and colorSpace conversion block need to be combined
2381 // (via the Compose block) so that the localMatrix block can treat them as
2382 // one child.
2383 Compose(keyContext,
2384 /* addInnerToKey= */ [&]() -> void {
2385 GradientShaderBlocks::AddBlock(keyContext, gradData);
2386 },
2387 /* addOuterToKey= */ [&]() -> void {
2388 ColorSpaceTransformBlock::AddBlock(keyContext, data);
2389 });
2390 }
2391
2392 static void add_gradient_to_key(const KeyContext& keyContext,
2393 const SkGradientBaseShader* shader,
2394 SkPoint point0,
2395 SkPoint point1,
2396 float radius0,
2397 float radius1,
2398 float bias,
2399 float scale) {
2400 SkColor4fXformer xformedColors(shader, keyContext.dstColorInfo().colorSpace());
2401 const SkPMColor4f* colors = xformedColors.fColors.begin();
2402 const float* positions = xformedColors.fPositions;
2403 const int colorCount = xformedColors.fColors.size();
2404
2405 sk_sp<TextureProxy> proxy;
2406
2407 bool useStorageBuffer = keyContext.caps()->gradientBufferSupport();
2408 if (colorCount > GradientShaderBlocks::GradientData::kNumInternalStorageStops
2409 && !useStorageBuffer) {
2410 if (shader->cachedBitmap().empty()) {
2411 SkBitmap colorsAndOffsetsBitmap =
2412 create_color_and_offset_bitmap(colorCount, colors, positions);
2413 if (colorsAndOffsetsBitmap.empty()) {
2414 SKGPU_LOG_W("Couldn't create GradientShader's color and offset bitmap");
2415 keyContext.paintParamsKeyBuilder()->addErrorBlock();
2416 return;
2417 }
2418 shader->setCachedBitmap(colorsAndOffsetsBitmap);
2419 }
2420
2421 proxy = RecorderPriv::CreateCachedProxy(keyContext.recorder(), shader->cachedBitmap(),
2422 "GradientTexture");
2423 if (!proxy) {
2424 SKGPU_LOG_W("Couldn't create GradientShader's color and offset bitmap proxy");
2425 keyContext.paintParamsKeyBuilder()->addErrorBlock();
2426 return;
2427 }
2428 }
2429
2430 GradientShaderBlocks::GradientData data(shader->asGradient(),
2431 point0,
2432 point1,
2433 radius0,
2434 radius1,
2435 bias,
2436 scale,
2437 shader->getTileMode(),
2438 colorCount,
2439 colors,
2440 positions,
2441 shader,
2442 std::move(proxy),
2443 useStorageBuffer,
2444 shader->getInterpolation());
2445
2446 make_interpolated_to_dst(keyContext,
2447 data,
2448 shader->getInterpolation(),
2449 xformedColors.fIntermediateColorSpace.get());
2450 }
2451
2452 static void add_gradient_to_key(const KeyContext& keyContext,
2453 const SkConicalGradient* shader) {
2454 SkScalar r0 = shader->getStartRadius();
2455 SkScalar r1 = shader->getEndRadius();
2456
2457 if (shader->getType() != SkConicalGradient::Type::kRadial) {
2458 // Since we map the centers to be (0,0) and (1,0) in the gradient matrix,
2459 // there is a scale of 1/distance-between-centers that has to be applied to the radii.
2460 r0 /= shader->getCenterX1();
2461 r1 /= shader->getCenterX1();
2462 } else {
2463 r0 /= shader->getDiffRadius();
2464 r1 /= shader->getDiffRadius();
2465 }
2466
2467 add_gradient_to_key(keyContext,
2468 shader,
2469 shader->getStartCenter(),
2470 shader->getEndCenter(),
2471 r0,
2472 r1,
2473 0.0f,
2474 0.0f);
2475 }
2476
2477 static void add_gradient_to_key(const KeyContext& keyContext,
2478 const SkLinearGradient* shader) {
2479 add_gradient_to_key(keyContext,
2480 shader,
2481 shader->start(),
2482 shader->end(),
2483 0.0f,
2484 0.0f,
2485 0.0f,
2486 0.0f);
2487 }
2488
2489 static void add_gradient_to_key(const KeyContext& keyContext,
2490 const SkRadialGradient* shader) {
2491 add_gradient_to_key(keyContext,
2492 shader,
2493 shader->center(),
2494 { 0.0f, 0.0f },
2495 shader->radius(),
2496 0.0f,
2497 0.0f,
2498 0.0f);
2499 }
2500
2501 static void add_gradient_to_key(const KeyContext& keyContext,
2502 const SkSweepGradient* shader) {
2503 add_gradient_to_key(keyContext,
2504 shader,
2505 shader->center(),
2506 { 0.0f, 0.0f },
2507 0.0f,
2508 0.0f,
2509 shader->tBias(),
2510 shader->tScale());
2511 }
2512
2513 static void add_to_key(const KeyContext& keyContext,
2514 const SkGradientBaseShader* shader) {
2515 SkASSERT(shader);
2516 switch (shader->asGradient()) {
2517 #define M(type) \
2518 case SkShaderBase::GradientType::k##type: \
2519 add_gradient_to_key(keyContext, \
2520 static_cast<const Sk##type##Gradient*>(shader)); \
2521 return;
2522 SK_ALL_GRADIENTS(M)
2523 #undef M
2524 case SkShaderBase::GradientType::kNone:
2525 SkDEBUGFAIL("Gradient shader says its type is none");
2526 return;
2527 }
2528 SkUNREACHABLE;
2529 }
2530
2531 void AddToKey(const KeyContext& keyContext, const SkShader* shader) {
2532 if (!shader) {
2533 // Calling code assumes a block will be appended. Add a fixed block to preserve shader
2534 // and PaintParamsKey structure in release builds but assert since this should either not
2535 // happen or should be changing high-level logic within PaintParams::toKey().
2536 SkASSERT(false);
2537 SolidColorShaderBlock::AddBlock(keyContext, SK_PMColor4fTRANSPARENT);
2538 return;
2539 }
2540 switch (as_SB(shader)->type()) {
2541 #define M(type) \
2542 case SkShaderBase::ShaderType::k##type: \
2543 add_to_key(keyContext, \
2544 static_cast<const Sk##type##Shader*>(shader)); \
2545 return;
2546 SK_ALL_SHADERS(M)
2547 #undef M
2548 }
2549 SkUNREACHABLE;
2550 }
2551
2552 // An SkImageShader object on a paint is actually always an SkLocalMatrixShader composed with an
2553 // SkImageShader. This creates the same call sequence with the decomposed objects.
2554 void AddToKey(const KeyContext& keyContext, const PaintParams::SimpleImage& simpleImage) {
2555 add_local_matrix_to_key(keyContext,
2556 simpleImage.fLocalMatrix ? *simpleImage.fLocalMatrix : SkMatrix::I(),
2557 get_image_origin_matrix(simpleImage.fImage),
2558 [&](const KeyContext& childCtx) {
2559 add_image_to_key(childCtx,
2560 simpleImage.fImage,
2561 simpleImage.fSubset,
2562 simpleImage.fSamplingOptions,
2563 SkTileMode::kClamp,
2564 SkTileMode::kClamp,
2565 /*isRaw=*/false);
2566 });
2567 }
2568
2569 void AddFixedBlendMode(const KeyContext& keyContext, SkBlendMode bm) {
2570 SkASSERT(bm <= SkBlendMode::kLastMode);
2571 BuiltInCodeSnippetID id = static_cast<BuiltInCodeSnippetID>(kFixedBlendIDOffset +
2572 static_cast<int>(bm));
2573 keyContext.paintParamsKeyBuilder()->addBlock(id);
2574 }
2575
2576 void AddBlendMode(const KeyContext& keyContext, SkBlendMode bm) {
2577 // For non-fixed blends, coefficient blend modes are combined into the same shader snippet.
2578 // The same goes for the HSLC advanced blends. The remaining advanced blends are fairly unique
2579 // in their implementations. To avoid having to compile all of their SkSL, they are treated as
2580 // fixed blend modes.
2581 SkSpan<const float> coeffs = skgpu::GetPorterDuffBlendConstants(bm);
2582 if (!coeffs.empty()) {
2583 PorterDuffBlenderBlock::AddBlock(keyContext, coeffs);
2584 } else if (bm >= SkBlendMode::kHue) {
2585 ReducedBlendModeInfo blendInfo = GetReducedBlendModeInfo(bm);
2586 HSLCBlenderBlock::AddBlock(keyContext, blendInfo.fUniformData);
2587 } else {
2588 AddFixedBlendMode(keyContext, bm);
2589 }
2590 }
2591
2592 void AddDitherBlock(const KeyContext& keyContext, SkColorType ct) {
2593 static const SkBitmap gLUT = skgpu::MakeDitherLUT();
2594
2595 sk_sp<TextureProxy> proxy = RecorderPriv::CreateCachedProxy(keyContext.recorder(), gLUT,
2596 "DitherLUT");
2597 if (keyContext.recorder() && !proxy) {
2598 SKGPU_LOG_W("Couldn't create dither shader's LUT");
2599 keyContext.paintParamsKeyBuilder()->addBlock(BuiltInCodeSnippetID::kPriorOutput);
2600 return;
2601 }
2602
2603 DitherShaderBlock::DitherData data(skgpu::DitherRangeForConfig(ct), std::move(proxy));
2604
2605 DitherShaderBlock::AddBlock(keyContext, data);
2606 }
2607
2608
2609 } // namespace skgpu::graphite