Debian Codegraph @

src/pdf/SkPDFGradientShader.cpp

raw
1 /*
2 * Copyright 2017 Google Inc.
3 *
4 * Use of this source code is governed by a BSD-style license that can be
5 * found in the LICENSE file.
6 */
7
8 #include "src/pdf/SkPDFGradientShader.h"
9
10 #include "include/core/SkAlphaType.h"
11 #include "include/core/SkPaint.h"
12 #include "include/core/SkPathTypes.h"
13 #include "include/core/SkSpan.h"
14 #include "include/core/SkStream.h"
15 #include "include/core/SkTileMode.h"
16 #include "include/effects/SkGradient.h"
17 #include "include/private/base/SkTemplates.h"
18 #include "include/private/base/SkTo.h"
19 #include "src/core/SkChecksum.h"
20 #include "src/core/SkTHash.h"
21 #include "src/pdf/SkPDFDocumentPriv.h"
22 #include "src/pdf/SkPDFFormXObject.h"
23 #include "src/pdf/SkPDFGraphicState.h"
24 #include "src/pdf/SkPDFResourceDict.h"
25 #include "src/pdf/SkPDFTypes.h"
26 #include "src/pdf/SkPDFUtils.h"
27
28 #include <cmath>
29 #include <cstddef>
30 #include <utility>
31 #include <vector>
32
33 using namespace skia_private;
34
35 static uint32_t hash(const SkShaderBase::GradientInfo& v) {
36 uint32_t buffer[] = {
37 (uint32_t)v.fColorCount,
38 SkChecksum::Hash32(v.fColors, v.fColorCount * sizeof(SkColor)),
39 SkChecksum::Hash32(v.fColorOffsets, v.fColorCount * sizeof(SkScalar)),
40 SkChecksum::Hash32(v.fPoint, 2 * sizeof(SkPoint)),
41 SkChecksum::Hash32(v.fRadius, 2 * sizeof(SkScalar)),
42 (uint32_t)v.fTileMode,
43 v.fPremulInterp,
44 };
45 return SkChecksum::Hash32(buffer, sizeof(buffer));
46 }
47
48 static uint32_t hash(const SkPDFGradientShader::Key& k) {
49 uint32_t buffer[] = {
50 (uint32_t)k.fType,
51 hash(k.fInfo),
52 SkChecksum::Hash32(&k.fCanvasTransform, sizeof(SkMatrix)),
53 SkChecksum::Hash32(&k.fShaderTransform, sizeof(SkMatrix)),
54 SkChecksum::Hash32(&k.fBBox, sizeof(SkIRect))
55 };
56 return SkChecksum::Hash32(buffer, sizeof(buffer));
57 }
58
59 static void unit_to_points_matrix(const SkPoint pts[2], SkMatrix* matrix) {
60 SkVector vec = pts[1] - pts[0];
61 SkScalar mag = vec.length();
62 SkScalar inv = mag ? SkScalarInvert(mag) : 0;
63
64 vec.scale(inv);
65 matrix->setSinCos(vec.fY, vec.fX);
66 matrix->preScale(mag, mag);
67 matrix->postTranslate(pts[0].fX, pts[0].fY);
68 }
69
70 enum NumComponents {
71 Three = 3,
72 Four = 4,
73 Max = Four,
74 };
75
76 /* Assumes t - startOffset is on the stack and does a linear interpolation on t
77 between startOffset and endOffset from prevColor to curColor (for each color
78 component), leaving the result in component order on the stack.
79 @param range endOffset - startOffset
80 @param beginColor The previous color.
81 @param endColor The current color.
82 @param numComponents The number of components (3 or 4 if alpha is needed).
83 @param result The result ps function.
84 */
85 static void interpolate_color_code(SkScalar range, NumComponents numComponents,
86 SkColor4f prevColor, SkColor4f curColor,
87 SkDynamicMemoryWStream* result) {
88 SkASSERT(range != SkIntToScalar(0));
89
90 /* Linearly interpolate from the previous color to the current.
91 Take the components 0..1 and determine the multipliers for interpolation.
92 C{r,g,b}(t, section) = t - offset_(section-1) + t * Multiplier{r,g,b}.
93 */
94
95 // Figure out how to scale each color component.
96 SkScalar multiplier[NumComponents::Max];
97 for (int i = 0; i < numComponents; i++) {
98 multiplier[i] = (curColor[i] - prevColor[i]) / range;
99 }
100
101 // Calculate when we no longer need to keep a copy of the input parameter t.
102 // If the last component to use t is i, then dupInput[0..i - 1] = true
103 // and dupInput[i .. components] = false.
104 bool dupInput[NumComponents::Max];
105 dupInput[numComponents - 1] = false;
106 for (int i = numComponents - 2; i >= 0; i--) {
107 dupInput[i] = dupInput[i + 1] || multiplier[i + 1] != 0;
108 }
109
110 if (!dupInput[0] && multiplier[0] == 0) {
111 result->writeText("pop ");
112 }
113
114 for (int i = 0; i < numComponents; i++) {
115 // If the next components needs t and this component will consume a
116 // copy, make another copy.
117 if (dupInput[i] && multiplier[i] != 0) {
118 result->writeText("dup ");
119 }
120
121 if (multiplier[i] == 0) {
122 SkPDFUtils::AppendColorComponentF(prevColor[i], result);
123 result->writeText(" ");
124 } else {
125 if (multiplier[i] != 1) {
126 SkPDFUtils::AppendScalar(multiplier[i], result);
127 result->writeText(" mul ");
128 }
129 if (prevColor[i] != 0) {
130 SkPDFUtils::AppendColorComponentF(prevColor[i], result);
131 result->writeText(" add ");
132 }
133 }
134
135 if (dupInput[i]) {
136 result->writeText("exch ");
137 }
138 }
139 }
140
141 // Convert { r, g, b, a } to a == 0 ? {0 0 0} : { r/a, g/a, b/a }
142 static void unpremul(const SkShaderBase::GradientInfo& info, SkDynamicMemoryWStream* function) {
143 // Preview Version 11.0 (1069.7.1) aborts the function if the predicate is like
144 // "dup 0 eq" or any other use of "eq" with "a".
145 function->writeText("dup abs 0.00001 lt"
146 "{ pop pop pop pop 0 0 0 }"
147 "{"
148 " dup" // r g b a a
149 " 3 1 roll" // r g a b a
150 " div" // r g a b/a
151 " 4 1 roll" // b/a r g a
152 " dup" // b/a r g a a
153 " 3 1 roll" // b/a r a g a
154 " div" // b/a r a g/a
155 " 4 1 roll" // g/a b/a r a
156 " div" // g/a b/a r/a
157 " 3 1 roll" // r/a g/a b/a
158 "} ifelse\n");
159 }
160
161 static void write_gradient_ranges(const SkShaderBase::GradientInfo& info, SkSpan<size_t> rangeEnds,
162 NumComponents numComponents,
163 bool top, bool first, SkDynamicMemoryWStream* result) {
164 SkASSERT(!rangeEnds.empty());
165
166 size_t rangeEndIndex = rangeEnds[rangeEnds.size() - 1];
167 SkScalar rangeEnd = info.fColorOffsets[rangeEndIndex];
168
169 // Each range check tests 0 < t <= end.
170 if (top) {
171 SkASSERT(first);
172 // t may have been set to 0 to signal that the answer has already been found.
173 result->writeText("dup dup 0 gt exch "); // In Preview 11.0 (1033.3) `0. 0 ne` is true.
174 SkPDFUtils::AppendScalar(rangeEnd, result);
175 result->writeText(" le and {\n");
176 } else if (first) {
177 // After the top level check, only t <= end needs to be tested on if (lo) side.
178 result->writeText("dup ");
179 SkPDFUtils::AppendScalar(rangeEnd, result);
180 result->writeText(" le {\n");
181 } else {
182 // The else (hi) side.
183 result->writeText("{\n");
184 }
185
186 if (rangeEnds.size() == 1) {
187 // Set the stack to [r g b].
188 size_t rangeBeginIndex = rangeEndIndex - 1;
189 SkScalar rangeBegin = info.fColorOffsets[rangeBeginIndex];
190 SkPDFUtils::AppendScalar(rangeBegin, result);
191 result->writeText(" sub "); // consume t, put t - startOffset on the stack.
192 interpolate_color_code(rangeEnd - rangeBegin, numComponents,
193 info.fColors[rangeBeginIndex], info.fColors[rangeEndIndex], result);
194 result->writeText("\n");
195 } else {
196 size_t loCount = rangeEnds.size() / 2;
197 SkSpan<size_t> loSpan = rangeEnds.subspan(0, loCount);
198 write_gradient_ranges(info, loSpan, numComponents, false, true, result);
199
200 SkSpan<size_t> hiSpan = rangeEnds.subspan(loCount, rangeEnds.size() - loCount);
201 write_gradient_ranges(info, hiSpan, numComponents, false, false, result);
202 }
203
204 if (top) {
205 // Put 0 on the stack for t once here instead of after every call to interpolate_color_code.
206 result->writeText("0} if\n");
207 } else if (first) {
208 result->writeText("}"); // The else (hi) side will come next.
209 } else {
210 result->writeText("} ifelse\n");
211 }
212 }
213
214 /* Generate Type 4 function code to map t to the passed gradient, clamping at the ends.
215 The types integer, real, and boolean are available.
216 There are no string, array, procedure, variable, or name types available.
217
218 The generated code will be of the following form with all values hard coded.
219
220 if (t <= 0) {
221 ret = color[0];
222 t = 0;
223 }
224 if (t > 0 && t <= stop[4]) {
225 if (t <= stop[2]) {
226 if (t <= stop[1]) {
227 ret = interp(t - stop[0], stop[1] - stop[0], color[0], color[1]);
228 } else {
229 ret = interp(t - stop[1], stop[2] - stop[1], color[1], color[2]);
230 }
231 } else {
232 if (t <= stop[3] {
233 ret = interp(t - stop[2], stop[3] - stop[2], color[2], color[3]);
234 } else {
235 ret = interp(t - stop[3], stop[4] - stop[3], color[3], color[4]);
236 }
237 }
238 t = 0;
239 }
240 if (t > 0) {
241 ret = color[4];
242 }
243
244 which in PDF will be represented like
245
246 dup 0 le {pop 0 0 0 0} if
247 dup dup 0 gt exch 1 le and {
248 dup .5 le {
249 dup .25 le {
250 0 sub 2 mul 0 0
251 }{
252 .25 sub .5 exch 2 mul 0
253 } ifelse
254 }{
255 dup .75 le {
256 .5 sub .5 exch .5 exch 2 mul
257 }{
258 .75 sub dup 2 mul .5 add exch dup 2 mul .5 add exch 2 mul .5 add
259 } ifelse
260 } ifelse
261 0} if
262 0 gt {1 1 1} if
263 */
264 static void gradient_function_code(const SkShaderBase::GradientInfo& info,
265 SkDynamicMemoryWStream* result) {
266 // While looking for a hit the stack is [t].
267 // After finding a hit the stack is [r g b 0].
268 // The 0 is consumed just before returning.
269
270 const bool premul = info.fPremulInterp;
271 NumComponents numComponents = premul ? NumComponents::Four : NumComponents::Three;
272
273 // The initial range has no previous and contains a solid color.
274 // Any t <= 0 will be handled by this initial range, so later t == 0 indicates a hit was found.
275 result->writeText("dup 0 le {pop ");
276 SkPDFUtils::AppendColorComponentF(info.fColors[0].fR, result);
277 result->writeText(" ");
278 SkPDFUtils::AppendColorComponentF(info.fColors[0].fG, result);
279 result->writeText(" ");
280 SkPDFUtils::AppendColorComponentF(info.fColors[0].fB, result);
281 if (numComponents == NumComponents::Four) {
282 result->writeText(" ");
283 SkPDFUtils::AppendColorComponentF(info.fColors[0].fA, result);
284 }
285 result->writeText(" 0} if\n");
286
287 // Optimize out ranges which don't make any visual difference.
288 AutoSTMalloc<4, size_t> rangeEnds(info.fColorCount);
289 size_t rangeEndsCount = 0;
290 for (int i = 1; i < info.fColorCount; ++i) {
291 // Ignoring the alpha, is this range the same solid color as the next range?
292 // This optimizes gradients where sometimes only the color or only the alpha is changing.
293 auto eqIgnoringAlpha = [&](SkColor4f a, SkColor4f b) {
294 if (premul) {
295 return a == b;
296 } else {
297 return a.makeOpaque() == b.makeOpaque();
298 }
299 };
300 bool constantColorBothSides =
301 eqIgnoringAlpha(info.fColors[i-1], info.fColors[i]) &&// This range is a solid color.
302 i != info.fColorCount-1 && // This is not the last range.
303 eqIgnoringAlpha(info.fColors[i], info.fColors[i+1]); // Next range is same solid color.
304
305 // Does this range have zero size?
306 bool degenerateRange = info.fColorOffsets[i-1] == info.fColorOffsets[i];
307
308 if (!degenerateRange && !constantColorBothSides) {
309 rangeEnds[rangeEndsCount] = i;
310 ++rangeEndsCount;
311 }
312 }
313
314 // If a cap on depth is needed, loop here.
315 write_gradient_ranges(info, SkSpan(rangeEnds.get(), rangeEndsCount),
316 numComponents, true, true, result);
317
318 // Clamp the final color.
319 result->writeText("0 gt {");
320 SkPDFUtils::AppendColorComponentF(info.fColors[info.fColorCount - 1].fR, result);
321 result->writeText(" ");
322 SkPDFUtils::AppendColorComponentF(info.fColors[info.fColorCount - 1].fG, result);
323 result->writeText(" ");
324 SkPDFUtils::AppendColorComponentF(info.fColors[info.fColorCount - 1].fB, result);
325 if (numComponents == NumComponents::Four) {
326 result->writeText(" ");
327 SkPDFUtils::AppendColorComponentF(info.fColors[info.fColorCount - 1].fA, result);
328 }
329 result->writeText("} if\n");
330
331 if (premul) {
332 unpremul(info, result);
333 }
334 }
335
336 static std::unique_ptr<SkPDFDict> createInterpolationFunction(const SkColor4f& color1,
337 const SkColor4f& color2) {
338 auto retval = SkPDFMakeDict();
339
340 auto c0 = SkPDFMakeArray();
341 c0->appendColorComponentF(color1.fR);
342 c0->appendColorComponentF(color1.fG);
343 c0->appendColorComponentF(color1.fB);
344 retval->insertObject("C0", std::move(c0));
345
346 auto c1 = SkPDFMakeArray();
347 c1->appendColorComponentF(color2.fR);
348 c1->appendColorComponentF(color2.fG);
349 c1->appendColorComponentF(color2.fB);
350 retval->insertObject("C1", std::move(c1));
351
352 retval->insertObject("Domain", SkPDFMakeArray(0, 1));
353
354 retval->insertInt("FunctionType", 2);
355 retval->insertScalar("N", 1.0f);
356
357 return retval;
358 }
359
360 static std::unique_ptr<SkPDFDict> gradientStitchCode(const SkShaderBase::GradientInfo& info) {
361 auto retval = SkPDFMakeDict();
362
363 // normalize color stops
364 int colorCount = info.fColorCount;
365 std::vector<SkColor4f> colors(info.fColors, info.fColors + colorCount);
366 std::vector<SkScalar> colorOffsets(info.fColorOffsets, info.fColorOffsets + colorCount);
367
368 int i = 1;
369 while (i < colorCount - 1) {
370 // ensure stops are in order
371 if (colorOffsets[i - 1] > colorOffsets[i]) {
372 colorOffsets[i] = colorOffsets[i - 1];
373 }
374
375 // remove points that are between 2 coincident points
376 if ((colorOffsets[i - 1] == colorOffsets[i]) && (colorOffsets[i] == colorOffsets[i + 1])) {
377 colorCount -= 1;
378 colors.erase(colors.begin() + i);
379 colorOffsets.erase(colorOffsets.begin() + i);
380 } else {
381 i++;
382 }
383 }
384 // find coincident points and slightly move them over
385 for (i = 1; i < colorCount - 1; i++) {
386 if (colorOffsets[i - 1] == colorOffsets[i]) {
387 colorOffsets[i] += 0.00001f;
388 }
389 }
390 // check if last 2 stops coincide
391 if (colorOffsets[i - 1] == colorOffsets[i]) {
392 colorOffsets[i - 1] -= 0.00001f;
393 }
394
395 // no need for a stitch function if there are only 2 stops.
396 if (colorCount == 2) {
397 return createInterpolationFunction(colors[0], colors[1]);
398 }
399
400 auto encode = SkPDFMakeArray();
401 auto bounds = SkPDFMakeArray();
402 auto functions = SkPDFMakeArray();
403
404 retval->insertObject("Domain", SkPDFMakeArray(0, 1));
405 retval->insertInt("FunctionType", 3);
406
407 for (int idx = 1; idx < colorCount; idx++) {
408 if (idx > 1) {
409 bounds->appendScalar(colorOffsets[idx-1]);
410 }
411
412 encode->appendScalar(0);
413 encode->appendScalar(1.0f);
414
415 functions->appendObject(createInterpolationFunction(colors[idx-1], colors[idx]));
416 }
417
418 retval->insertObject("Encode", std::move(encode));
419 retval->insertObject("Bounds", std::move(bounds));
420 retval->insertObject("Functions", std::move(functions));
421
422 return retval;
423 }
424
425 /* Map a value of t on the stack into [0, 1) for Repeat or Mirror tile mode. */
426 static void tileModeCode(SkTileMode mode, SkDynamicMemoryWStream* result) {
427 if (mode == SkTileMode::kRepeat) {
428 result->writeText("dup truncate sub\n"); // Get the fractional part.
429 result->writeText("dup 0 le {1 add} if\n"); // Map (-1,0) => (0,1)
430 return;
431 }
432
433 if (mode == SkTileMode::kMirror) {
434 // In Preview 11.0 (1033.3) `a n mod r eq` (with a and n both integers, r integer or real)
435 // early aborts the function when false would be put on the stack.
436 // Work around this by re-writing `t 2 mod 1 eq` as `t 2 mod 0 gt`.
437
438 // Map t mod 2 into [0, 1, 1, 0].
439 // Code Stack t
440 result->writeText("abs " // +t
441 "dup " // +t.s +t.s
442 "truncate " // +t.s +t
443 "dup " // +t.s +t +t
444 "cvi " // +t.s +t +T
445 "2 mod " // +t.s +t (+T mod 2)
446 /*"1 eq "*/ "0 gt " // +t.s +t true|false
447 "3 1 roll " // true|false +t.s +t
448 "sub " // true|false 0.s
449 "exch " // 0.s true|false
450 "{1 exch sub} if\n"); // 1 - 0.s|0.s
451 }
452 }
453
454 /**
455 * Returns PS function code that applies inverse perspective
456 * to a x, y point.
457 * The function assumes that the stack has at least two elements,
458 * and that the top 2 elements are numeric values.
459 * After executing this code on a PS stack, the last 2 elements are updated
460 * while the rest of the stack is preserved intact.
461 * inversePerspectiveMatrix is the inverse perspective matrix.
462 */
463 static void apply_perspective_to_coordinates(const SkMatrix& inversePerspectiveMatrix,
464 SkDynamicMemoryWStream* code) {
465 if (!inversePerspectiveMatrix.hasPerspective()) {
466 return;
467 }
468
469 // Perspective matrix should be:
470 // 1 0 0
471 // 0 1 0
472 // p0 p1 p2
473
474 const SkScalar p0 = inversePerspectiveMatrix[SkMatrix::kMPersp0];
475 const SkScalar p1 = inversePerspectiveMatrix[SkMatrix::kMPersp1];
476 const SkScalar p2 = inversePerspectiveMatrix[SkMatrix::kMPersp2];
477
478 // y = y / (p2 + p0 x + p1 y)
479 // x = x / (p2 + p0 x + p1 y)
480
481 // Input on stack: x y
482 code->writeText(" dup "); // x y y
483 SkPDFUtils::AppendScalar(p1, code); // x y y p1
484 code->writeText(" mul " // x y y*p1
485 " 2 index "); // x y y*p1 x
486 SkPDFUtils::AppendScalar(p0, code); // x y y p1 x p0
487 code->writeText(" mul "); // x y y*p1 x*p0
488 SkPDFUtils::AppendScalar(p2, code); // x y y p1 x*p0 p2
489 code->writeText(" add " // x y y*p1 x*p0+p2
490 "add " // x y y*p1+x*p0+p2
491 "3 1 roll " // y*p1+x*p0+p2 x y
492 "2 index " // z x y y*p1+x*p0+p2
493 "div " // y*p1+x*p0+p2 x y/(y*p1+x*p0+p2)
494 "3 1 roll " // y/(y*p1+x*p0+p2) y*p1+x*p0+p2 x
495 "exch " // y/(y*p1+x*p0+p2) x y*p1+x*p0+p2
496 "div " // y/(y*p1+x*p0+p2) x/(y*p1+x*p0+p2)
497 "exch\n"); // x/(y*p1+x*p0+p2) y/(y*p1+x*p0+p2)
498 }
499
500 static void linearCode(const SkShaderBase::GradientInfo& info,
501 const SkMatrix& perspectiveRemover,
502 SkDynamicMemoryWStream* function) {
503 function->writeText("{");
504
505 apply_perspective_to_coordinates(perspectiveRemover, function);
506
507 function->writeText("pop\n"); // Just ditch the y value.
508 tileModeCode((SkTileMode)info.fTileMode, function);
509 gradient_function_code(info, function);
510 function->writeText("}");
511 }
512
513 static void radialCode(const SkShaderBase::GradientInfo& info,
514 const SkMatrix& perspectiveRemover,
515 SkDynamicMemoryWStream* function) {
516 function->writeText("{");
517
518 apply_perspective_to_coordinates(perspectiveRemover, function);
519
520 // Find the distance from the origin.
521 function->writeText("dup " // x y y
522 "mul " // x y^2
523 "exch " // y^2 x
524 "dup " // y^2 x x
525 "mul " // y^2 x^2
526 "add " // y^2+x^2
527 "sqrt\n"); // sqrt(y^2+x^2)
528
529 tileModeCode((SkTileMode)info.fTileMode, function);
530 gradient_function_code(info, function);
531 function->writeText("}");
532 }
533
534 /* Conical gradient shader, based on the Canvas spec for radial gradients
535 See: http://www.w3.org/TR/2dcontext/#dom-context-2d-createradialgradient
536 */
537 static void twoPointConicalCode(const SkShaderBase::GradientInfo& info,
538 const SkMatrix& perspectiveRemover,
539 SkDynamicMemoryWStream* function) {
540 SkScalar dx = info.fPoint[1].fX - info.fPoint[0].fX;
541 SkScalar dy = info.fPoint[1].fY - info.fPoint[0].fY;
542 SkScalar r0 = info.fRadius[0];
543 SkScalar dr = info.fRadius[1] - info.fRadius[0];
544 SkScalar a = dx * dx + dy * dy - dr * dr;
545
546 // First compute t, if the pixel falls outside the cone, then we'll end
547 // with 'false' on the stack, otherwise we'll push 'true' with t below it
548
549 // We start with a stack of (x y), copy it and then consume one copy in
550 // order to calculate b and the other to calculate c.
551 function->writeText("{");
552
553 apply_perspective_to_coordinates(perspectiveRemover, function);
554
555 function->writeText("2 copy ");
556
557 // Calculate b and b^2; b = -2 * (y * dy + x * dx + r0 * dr).
558 SkPDFUtils::AppendScalar(dy, function);
559 function->writeText(" mul exch ");
560 SkPDFUtils::AppendScalar(dx, function);
561 function->writeText(" mul add ");
562 SkPDFUtils::AppendScalar(r0 * dr, function);
563 function->writeText(" add -2 mul dup dup mul\n");
564
565 // c = x^2 + y^2 + radius0^2
566 function->writeText("4 2 roll dup mul exch dup mul add ");
567 SkPDFUtils::AppendScalar(r0 * r0, function);
568 function->writeText(" sub dup 4 1 roll\n");
569
570 // Contents of the stack at this point: c, b, b^2, c
571
572 // if a = 0, then we collapse to a simpler linear case
573 if (a == 0) {
574
575 // t = -c/b
576 function->writeText("pop pop div neg dup ");
577
578 // compute radius(t)
579 SkPDFUtils::AppendScalar(dr, function);
580 function->writeText(" mul ");
581 SkPDFUtils::AppendScalar(r0, function);
582 function->writeText(" add\n");
583
584 // if r(t) < 0, then it's outside the cone
585 function->writeText("0 lt {pop false} {true} ifelse\n");
586
587 } else {
588
589 // quadratic case: the Canvas spec wants the largest
590 // root t for which radius(t) > 0
591
592 // compute the discriminant (b^2 - 4ac)
593 SkPDFUtils::AppendScalar(a * 4, function);
594 function->writeText(" mul sub dup\n");
595
596 // if d >= 0, proceed
597 function->writeText("0 ge {\n");
598
599 // an intermediate value we'll use to compute the roots:
600 // q = -0.5 * (b +/- sqrt(d))
601 function->writeText("sqrt exch dup 0 lt {exch -1 mul} if");
602 function->writeText(" add -0.5 mul dup\n");
603
604 // first root = q / a
605 SkPDFUtils::AppendScalar(a, function);
606 function->writeText(" div\n");
607
608 // second root = c / q
609 function->writeText("3 1 roll div\n");
610
611 // put the larger root on top of the stack
612 function->writeText("2 copy gt {exch} if\n");
613
614 // compute radius(t) for larger root
615 function->writeText("dup ");
616 SkPDFUtils::AppendScalar(dr, function);
617 function->writeText(" mul ");
618 SkPDFUtils::AppendScalar(r0, function);
619 function->writeText(" add\n");
620
621 // if r(t) > 0, we have our t, pop off the smaller root and we're done
622 function->writeText(" 0 gt {exch pop true}\n");
623
624 // otherwise, throw out the larger one and try the smaller root
625 function->writeText("{pop dup\n");
626 SkPDFUtils::AppendScalar(dr, function);
627 function->writeText(" mul ");
628 SkPDFUtils::AppendScalar(r0, function);
629 function->writeText(" add\n");
630
631 // if r(t) < 0, push false, otherwise the smaller root is our t
632 function->writeText("0 le {pop false} {true} ifelse\n");
633 function->writeText("} ifelse\n");
634
635 // d < 0, clear the stack and push false
636 function->writeText("} {pop pop pop false} ifelse\n");
637 }
638
639 // if the pixel is in the cone, proceed to compute a color
640 function->writeText("{");
641 tileModeCode((SkTileMode)info.fTileMode, function);
642 gradient_function_code(info, function);
643
644 // otherwise, just write black
645 // TODO: Correctly draw gradients_local_persepective, need to mask out this black
646 // The "gradients" gm works as falls into the 8.7.4.5.4 "Type 3 (Radial) Shadings" case.
647 function->writeText("} {0 0 0} ifelse }");
648 }
649
650 static void sweepCode(const SkShaderBase::GradientInfo& info,
651 const SkMatrix& perspectiveRemover,
652 SkDynamicMemoryWStream* function) {
653 function->writeText("{exch atan 360 div\n");
654 const SkScalar bias = info.fPoint[1].y();
655 if (bias != 0.0f) {
656 SkPDFUtils::AppendScalar(bias, function);
657 function->writeText(" add\n");
658 }
659 const SkScalar scale = info.fPoint[1].x();
660 if (scale != 1.0f) {
661 SkPDFUtils::AppendScalar(scale, function);
662 function->writeText(" mul\n");
663 }
664 tileModeCode((SkTileMode)info.fTileMode, function);
665 gradient_function_code(info, function);
666 function->writeText("}");
667 }
668
669
670 // catch cases where the inner just touches the outer circle
671 // and make the inner circle just inside the outer one to match raster
672 static void FixUpRadius(const SkPoint& p1, SkScalar& r1, const SkPoint& p2, SkScalar& r2) {
673 // detect touching circles
674 float distance = SkPoint::Distance(p1, p2);
675 float subtractRadii = fabsf(r1 - r2);
676 if (fabsf(distance - subtractRadii) < 0.002f) {
677 if (r1 > r2) {
678 r1 += 0.002f;
679 } else {
680 r2 += 0.002f;
681 }
682 }
683 }
684
685 // Finds affine and persp such that in = affine * persp.
686 // but it returns the inverse of perspective matrix.
687 static bool split_perspective(const SkMatrix in, SkMatrix* affine,
688 SkMatrix* perspectiveInverse) {
689 const SkScalar p2 = in[SkMatrix::kMPersp2];
690
691 if (SkScalarNearlyZero(p2)) {
692 return false;
693 }
694
695 const SkScalar zero = SkIntToScalar(0);
696 const SkScalar one = SkIntToScalar(1);
697
698 const SkScalar sx = in[SkMatrix::kMScaleX];
699 const SkScalar kx = in[SkMatrix::kMSkewX];
700 const SkScalar tx = in[SkMatrix::kMTransX];
701 const SkScalar ky = in[SkMatrix::kMSkewY];
702 const SkScalar sy = in[SkMatrix::kMScaleY];
703 const SkScalar ty = in[SkMatrix::kMTransY];
704 const SkScalar p0 = in[SkMatrix::kMPersp0];
705 const SkScalar p1 = in[SkMatrix::kMPersp1];
706
707 // Perspective matrix would be:
708 // 1 0 0
709 // 0 1 0
710 // p0 p1 p2
711 // But we need the inverse of persp.
712 perspectiveInverse->setAll(one, zero, zero,
713 zero, one, zero,
714 -p0/p2, -p1/p2, 1/p2);
715
716 affine->setAll(sx - p0 * tx / p2, kx - p1 * tx / p2, tx / p2,
717 ky - p0 * ty / p2, sy - p1 * ty / p2, ty / p2,
718 zero, zero, one);
719
720 return true;
721 }
722
723 static SkPDFIndirectReference make_ps_function(std::unique_ptr<SkStreamAsset> psCode,
724 std::unique_ptr<SkPDFArray> domain,
725 std::unique_ptr<SkPDFObject> range,
726 SkPDFDocument* doc) {
727 std::unique_ptr<SkPDFDict> dict = SkPDFMakeDict();
728 dict->insertInt("FunctionType", 4);
729 dict->insertObject("Domain", std::move(domain));
730 dict->insertObject("Range", std::move(range));
731 return SkPDFStreamOut(std::move(dict), std::move(psCode), doc);
732 }
733
734 static SkPDFIndirectReference make_function_shader(SkPDFDocument* doc,
735 const SkPDFGradientShader::Key& state) {
736 SkPoint transformPoints[2];
737 const SkShaderBase::GradientInfo& info = state.fInfo;
738 SkMatrix finalMatrix = state.fCanvasTransform;
739 finalMatrix.preConcat(state.fShaderTransform);
740
741 bool doStitchFunctions = (state.fType == SkShaderBase::GradientType::kLinear ||
742 state.fType == SkShaderBase::GradientType::kRadial ||
743 state.fType == SkShaderBase::GradientType::kConical) &&
744 (info.fTileMode == SkTileMode::kClamp ||
745 info.fTileMode == SkTileMode::kDecal) &&
746 !finalMatrix.hasPerspective() &&
747 !info.fPremulInterp;
748
749 enum class ShadingType : int32_t {
750 Function = 1,
751 Axial = 2,
752 Radial = 3,
753 FreeFormGouraudTriangleMesh = 4,
754 LatticeFormGouraudTriangleMesh = 5,
755 CoonsPatchMesh = 6,
756 TensorProductPatchMesh = 7,
757 } shadingType;
758
759 auto pdfShader = SkPDFMakeDict();
760 if (doStitchFunctions) {
761 pdfShader->insertObject("Function", gradientStitchCode(info));
762
763 if (info.fTileMode == SkTileMode::kClamp) {
764 auto extend = SkPDFMakeArray();
765 extend->reserve(2);
766 extend->appendBool(true);
767 extend->appendBool(true);
768 pdfShader->insertObject("Extend", std::move(extend));
769 }
770
771 std::unique_ptr<SkPDFArray> coords;
772 switch (state.fType) {
773 case SkShaderBase::GradientType::kLinear: {
774 shadingType = ShadingType::Axial;
775 const SkPoint& pt1 = info.fPoint[0];
776 const SkPoint& pt2 = info.fPoint[1];
777 coords = SkPDFMakeArray(pt1.x(), pt1.y(),
778 pt2.x(), pt2.y());
779 } break;
780 case SkShaderBase::GradientType::kRadial: {
781 shadingType = ShadingType::Radial;
782 const SkPoint& pt1 = info.fPoint[0];
783 coords = SkPDFMakeArray(pt1.x(), pt1.y(), 0,
784 pt1.x(), pt1.y(), info.fRadius[0]);
785 } break;
786 case SkShaderBase::GradientType::kConical: {
787 shadingType = ShadingType::Radial;
788 SkScalar r1 = info.fRadius[0];
789 SkScalar r2 = info.fRadius[1];
790 SkPoint pt1 = info.fPoint[0];
791 SkPoint pt2 = info.fPoint[1];
792 FixUpRadius(pt1, r1, pt2, r2);
793
794 coords = SkPDFMakeArray(pt1.x(), pt1.y(), r1,
795 pt2.x(), pt2.y(), r2);
796 break;
797 }
798 case SkShaderBase::GradientType::kSweep:
799 case SkShaderBase::GradientType::kNone:
800 default:
801 SkASSERT(false);
802 return SkPDFIndirectReference();
803 }
804 pdfShader->insertObject("Coords", std::move(coords));
805 } else {
806 shadingType = ShadingType::Function;
807
808 // Transform the coordinate space for the type of gradient.
809 transformPoints[0] = info.fPoint[0];
810 transformPoints[1] = info.fPoint[1];
811 switch (state.fType) {
812 case SkShaderBase::GradientType::kLinear:
813 break;
814 case SkShaderBase::GradientType::kRadial:
815 transformPoints[1] = transformPoints[0];
816 transformPoints[1].fX += info.fRadius[0];
817 break;
818 case SkShaderBase::GradientType::kConical: {
819 transformPoints[1] = transformPoints[0];
820 transformPoints[1].fX += SK_Scalar1;
821 break;
822 }
823 case SkShaderBase::GradientType::kSweep:
824 transformPoints[1] = transformPoints[0];
825 transformPoints[1].fX += SK_Scalar1;
826 break;
827 case SkShaderBase::GradientType::kNone:
828 default:
829 return SkPDFIndirectReference();
830 }
831
832 // Move any scaling (assuming a unit gradient) or translation
833 // (and rotation for linear gradient), of the final gradient from
834 // info.fPoints to the matrix (updating bbox appropriately). Now
835 // the gradient can be drawn on on the unit segment.
836 SkMatrix mapperMatrix;
837 unit_to_points_matrix(transformPoints, &mapperMatrix);
838
839 finalMatrix.preConcat(mapperMatrix);
840
841 // Preserves as much as possible in the final matrix, and only removes
842 // the perspective. The inverse of the perspective is stored in
843 // perspectiveInverseOnly matrix and has 3 useful numbers
844 // (p0, p1, p2), while everything else is either 0 or 1.
845 // In this way the shader will handle it eficiently, with minimal code.
846 SkMatrix perspectiveInverseOnly = SkMatrix::I();
847 if (finalMatrix.hasPerspective()) {
848 if (!split_perspective(finalMatrix,
849 &finalMatrix, &perspectiveInverseOnly)) {
850 return SkPDFIndirectReference();
851 }
852 }
853
854 SkRect bbox;
855 bbox.set(state.fBBox);
856 if (!SkPDFUtils::InverseTransformBBox(finalMatrix, &bbox)) {
857 return SkPDFIndirectReference();
858 }
859
860 SkDynamicMemoryWStream functionCode;
861 switch (state.fType) {
862 case SkShaderBase::GradientType::kLinear:
863 linearCode(info, perspectiveInverseOnly, &functionCode);
864 break;
865 case SkShaderBase::GradientType::kRadial:
866 radialCode(info, perspectiveInverseOnly, &functionCode);
867 break;
868 case SkShaderBase::GradientType::kConical: {
869 // The two point radial gradient further references state.fInfo
870 // in translating from x, y coordinates to the t parameter. So, we have
871 // to transform the points and radii according to the calculated matrix.
872 auto inverseMapperMatrix = mapperMatrix.invert();
873 if (!inverseMapperMatrix) {
874 return SkPDFIndirectReference();
875 }
876 SkShaderBase::GradientInfo infoCopy = info;
877 inverseMapperMatrix->mapPoints(infoCopy.fPoint);
878 infoCopy.fRadius[0] = inverseMapperMatrix->mapRadius(info.fRadius[0]);
879 infoCopy.fRadius[1] = inverseMapperMatrix->mapRadius(info.fRadius[1]);
880 twoPointConicalCode(infoCopy, perspectiveInverseOnly, &functionCode);
881 } break;
882 case SkShaderBase::GradientType::kSweep:
883 sweepCode(info, perspectiveInverseOnly, &functionCode);
884 break;
885 default:
886 SkASSERT(false);
887 }
888 pdfShader->insertObject(
889 "Domain", SkPDFMakeArray(bbox.left(), bbox.right(), bbox.top(), bbox.bottom()));
890
891 auto domain = SkPDFMakeArray(bbox.left(), bbox.right(), bbox.top(), bbox.bottom());
892 std::unique_ptr<SkPDFArray> rangeObject = SkPDFMakeArray(0, 1, 0, 1, 0, 1);
893 pdfShader->insertRef("Function",
894 make_ps_function(functionCode.detachAsStream(), std::move(domain),
895 std::move(rangeObject), doc));
896 }
897
898 pdfShader->insertInt("ShadingType", SkToS32(shadingType));
899 pdfShader->insertName("ColorSpace", "DeviceRGB");
900
901 SkPDFDict pdfFunctionShader("Pattern");
902 pdfFunctionShader.insertInt("PatternType", 2);
903 pdfFunctionShader.insertObject("Matrix", SkPDFUtils::MatrixToArray(finalMatrix));
904 pdfFunctionShader.insertObject("Shading", std::move(pdfShader));
905 return doc->emit(pdfFunctionShader);
906 }
907
908 static SkPDFIndirectReference find_pdf_shader(SkPDFDocument* doc,
909 SkPDFGradientShader::Key key,
910 bool makeAlphaShader);
911
912 static std::unique_ptr<SkPDFDict> get_gradient_resource_dict(SkPDFIndirectReference functionShader,
913 SkPDFIndirectReference gState) {
914 std::vector<SkPDFIndirectReference> patternShaders;
915 if (functionShader != SkPDFIndirectReference()) {
916 patternShaders.push_back(functionShader);
917 }
918 std::vector<SkPDFIndirectReference> graphicStates;
919 if (gState != SkPDFIndirectReference()) {
920 graphicStates.push_back(gState);
921 }
922 return SkPDFMakeResourceDict(std::move(graphicStates),
923 std::move(patternShaders),
924 std::vector<SkPDFIndirectReference>(),
925 std::vector<SkPDFIndirectReference>());
926 }
927
928 // Creates a content stream which fills the pattern P0 across bounds.
929 // @param gsIndex A graphics state resource index to apply, or <0 if no
930 // graphics state to apply.
931 static std::unique_ptr<SkStreamAsset> create_pattern_fill_content(int gsIndex,
932 int patternIndex,
933 SkRect& bounds) {
934 SkDynamicMemoryWStream content;
935 if (gsIndex >= 0) {
936 SkPDFUtils::ApplyGraphicState(gsIndex, &content);
937 }
938 SkPDFUtils::ApplyPattern(patternIndex, &content);
939 SkPDFUtils::AppendRectangle(bounds, &content);
940 SkPDFUtils::PaintPath(SkPaint::kFill_Style, SkPathFillType::kEvenOdd, &content);
941 return content.detachAsStream();
942 }
943
944 static bool gradient_has_alpha(const SkPDFGradientShader::Key& key) {
945 SkASSERT(key.fType != SkShaderBase::GradientType::kNone);
946 for (int i = 0; i < key.fInfo.fColorCount; i++) {
947 if (!key.fInfo.fColors[i].isOpaque()) {
948 return true;
949 }
950 }
951 return false;
952 }
953
954 // warning: does not set fHash on new key. (Both callers need to change fields.)
955 static SkPDFGradientShader::Key clone_key(const SkPDFGradientShader::Key& k) {
956 SkPDFGradientShader::Key clone = {
957 k.fType,
958 k.fInfo, // change pointers later.
959 std::unique_ptr<SkColor4f[]>(new SkColor4f[k.fInfo.fColorCount]),
960 std::unique_ptr<SkScalar[]>(new SkScalar[k.fInfo.fColorCount]),
961 k.fCanvasTransform,
962 k.fShaderTransform,
963 k.fBBox, 0};
964 clone.fInfo.fColors = clone.fColors.get();
965 clone.fInfo.fColorOffsets = clone.fStops.get();
966 for (int i = 0; i < clone.fInfo.fColorCount; i++) {
967 clone.fInfo.fColorOffsets[i] = k.fInfo.fColorOffsets[i];
968 clone.fInfo.fColors[i] = k.fInfo.fColors[i];
969 }
970 return clone;
971 }
972
973 static SkPDFIndirectReference create_smask_graphic_state(SkPDFDocument* doc,
974 const SkPDFGradientShader::Key& state) {
975 SkASSERT(state.fType != SkShaderBase::GradientType::kNone);
976 SkPDFGradientShader::Key luminosityState = clone_key(state);
977 for (int i = 0; i < luminosityState.fInfo.fColorCount; i++) {
978 float alpha = luminosityState.fInfo.fColors[i].fA;
979 luminosityState.fInfo.fColors[i] = SkColor4f{alpha, alpha, alpha, 1.0f};
980 }
981 luminosityState.fInfo.fPremulInterp = false;
982 luminosityState.fHash = hash(luminosityState);
983
984 SkASSERT(!gradient_has_alpha(luminosityState));
985 SkPDFIndirectReference luminosityShader = find_pdf_shader(doc, std::move(luminosityState), false);
986 std::unique_ptr<SkPDFDict> resources = get_gradient_resource_dict(luminosityShader,
987 SkPDFIndirectReference());
988 SkRect bbox = SkRect::Make(state.fBBox);
989 SkPDFIndirectReference alphaMask =
990 SkPDFMakeFormXObject(doc,
991 create_pattern_fill_content(-1, luminosityShader.fValue, bbox),
992 SkPDFUtils::RectToArray(bbox),
993 std::move(resources),
994 SkMatrix::I(),
995 "DeviceRGB");
996 return SkPDFGraphicState::GetSMaskGraphicState(
997 alphaMask, false, SkPDFGraphicState::kLuminosity_SMaskMode, doc);
998 }
999
1000 static SkPDFIndirectReference make_alpha_function_shader(SkPDFDocument* doc,
1001 const SkPDFGradientShader::Key& state) {
1002 SkASSERT(state.fType != SkShaderBase::GradientType::kNone);
1003 SkPDFGradientShader::Key opaqueState = clone_key(state);
1004 const bool keepAlpha = opaqueState.fInfo.fPremulInterp;
1005 if (!keepAlpha) {
1006 for (int i = 0; i < opaqueState.fInfo.fColorCount; i++) {
1007 opaqueState.fInfo.fColors[i].fA = 1.0f;
1008 }
1009 opaqueState.fHash = hash(opaqueState);
1010
1011 SkASSERT(!gradient_has_alpha(opaqueState));
1012 }
1013 SkRect bbox = SkRect::Make(state.fBBox);
1014 SkPDFIndirectReference colorShader = find_pdf_shader(doc, std::move(opaqueState), false);
1015 if (!colorShader) {
1016 return SkPDFIndirectReference();
1017 }
1018 // Create resource dict with alpha graphics state as G0 and
1019 // pattern shader as P0, then write content stream.
1020 SkPDFIndirectReference alphaGsRef = create_smask_graphic_state(doc, state);
1021
1022 std::unique_ptr<SkPDFDict> resourceDict = get_gradient_resource_dict(colorShader, alphaGsRef);
1023
1024 std::unique_ptr<SkStreamAsset> colorStream =
1025 create_pattern_fill_content(alphaGsRef.fValue, colorShader.fValue, bbox);
1026 std::unique_ptr<SkPDFDict> alphaFunctionShader = SkPDFMakeDict();
1027 SkPDFUtils::PopulateTilingPatternDict(alphaFunctionShader.get(), bbox, false, false,
1028 std::move(resourceDict), SkMatrix::I());
1029 return SkPDFStreamOut(std::move(alphaFunctionShader), std::move(colorStream), doc);
1030 }
1031
1032 static SkPDFGradientShader::Key make_key(const SkShader* shader,
1033 const SkMatrix& canvasTransform,
1034 const SkIRect& bbox) {
1035 SkPDFGradientShader::Key key = {
1036 SkShaderBase::GradientType::kNone,
1037 {0, nullptr, nullptr, {{0, 0}, {0, 0}}, {0, 0}, SkTileMode::kClamp, 0},
1038 nullptr,
1039 nullptr,
1040 canvasTransform,
1041 SkPDFUtils::GetShaderLocalMatrix(shader),
1042 bbox, 0};
1043 key.fType = as_SB(shader)->asGradient(&key.fInfo);
1044 SkASSERT(SkShaderBase::GradientType::kNone != key.fType);
1045 SkASSERT(key.fInfo.fColorCount > 0);
1046 key.fColors = std::make_unique<SkColor4f[]>(key.fInfo.fColorCount);
1047 key.fStops = std::make_unique<SkScalar[]>(key.fInfo.fColorCount);
1048 key.fInfo.fColors = key.fColors.get();
1049 key.fInfo.fColorOffsets = key.fStops.get();
1050 as_SB(shader)->asGradient(&key.fInfo);
1051 if (key.fInfo.fPremulInterp) {
1052 bool changedByPremul = false;
1053 for (auto&& c : SkSpan(key.fInfo.fColors, key.fInfo.fColorCount)) {
1054 if (c.fA != 1.0f) {
1055 changedByPremul = true;
1056 }
1057 SkRGBA4f<kPremul_SkAlphaType> pm = c.premul();
1058 c = SkColor4f{pm.fR, pm.fG, pm.fB, pm.fA};
1059 }
1060 if (!changedByPremul) {
1061 key.fInfo.fPremulInterp = false;
1062 }
1063 }
1064 key.fHash = hash(key);
1065 return key;
1066 }
1067
1068 static SkPDFIndirectReference find_pdf_shader(SkPDFDocument* doc,
1069 SkPDFGradientShader::Key key,
1070 bool makeAlphaShader) {
1071 auto& gradientPatternMap = doc->fGradientPatternMap;
1072 if (SkPDFIndirectReference* ptr = gradientPatternMap.find(key)) {
1073 return *ptr;
1074 }
1075 SkPDFIndirectReference pdfShader;
1076 if (makeAlphaShader) {
1077 pdfShader = make_alpha_function_shader(doc, key);
1078 } else {
1079 pdfShader = make_function_shader(doc, key);
1080 }
1081 gradientPatternMap.set(std::move(key), pdfShader);
1082 return pdfShader;
1083 }
1084
1085 SkPDFIndirectReference SkPDFGradientShader::Make(SkPDFDocument* doc,
1086 SkShader* shader,
1087 const SkMatrix& canvasTransform,
1088 const SkIRect& bbox) {
1089 SkASSERT(shader);
1090 SkASSERT(as_SB(shader)->asGradient() != SkShaderBase::GradientType::kNone);
1091 SkPDFGradientShader::Key key = make_key(shader, canvasTransform, bbox);
1092 const bool makeAlphaShader = gradient_has_alpha(key);
1093 return find_pdf_shader(doc, std::move(key), makeAlphaShader);
1094 }