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 "SkPDFGradientShader.h"
9 
10 #include "SkOpts.h"
11 #include "SkPDFDocument.h"
12 #include "SkPDFDocumentPriv.h"
13 #include "SkPDFFormXObject.h"
14 #include "SkPDFGraphicState.h"
15 #include "SkPDFResourceDict.h"
16 #include "SkPDFTypes.h"
17 #include "SkPDFUtils.h"
18 
hash(const SkShader::GradientInfo & v)19 static uint32_t hash(const SkShader::GradientInfo& v) {
20     uint32_t buffer[] = {
21         (uint32_t)v.fColorCount,
22         SkOpts::hash(v.fColors, v.fColorCount * sizeof(SkColor)),
23         SkOpts::hash(v.fColorOffsets, v.fColorCount * sizeof(SkScalar)),
24         SkOpts::hash(v.fPoint, 2 * sizeof(SkPoint)),
25         SkOpts::hash(v.fRadius, 2 * sizeof(SkScalar)),
26         (uint32_t)v.fTileMode,
27         v.fGradientFlags,
28     };
29     return SkOpts::hash(buffer, sizeof(buffer));
30 }
31 
hash(const SkPDFGradientShader::Key & k)32 static uint32_t hash(const SkPDFGradientShader::Key& k) {
33     uint32_t buffer[] = {
34         (uint32_t)k.fType,
35         hash(k.fInfo),
36         SkOpts::hash(&k.fCanvasTransform, sizeof(SkMatrix)),
37         SkOpts::hash(&k.fShaderTransform, sizeof(SkMatrix)),
38         SkOpts::hash(&k.fBBox, sizeof(SkIRect))
39     };
40     return SkOpts::hash(buffer, sizeof(buffer));
41 }
42 
unit_to_points_matrix(const SkPoint pts[2],SkMatrix * matrix)43 static void unit_to_points_matrix(const SkPoint pts[2], SkMatrix* matrix) {
44     SkVector    vec = pts[1] - pts[0];
45     SkScalar    mag = vec.length();
46     SkScalar    inv = mag ? SkScalarInvert(mag) : 0;
47 
48     vec.scale(inv);
49     matrix->setSinCos(vec.fY, vec.fX);
50     matrix->preScale(mag, mag);
51     matrix->postTranslate(pts[0].fX, pts[0].fY);
52 }
53 
54 static const int kColorComponents = 3;
55 typedef uint8_t ColorTuple[kColorComponents];
56 
57 /* Assumes t + startOffset is on the stack and does a linear interpolation on t
58    between startOffset and endOffset from prevColor to curColor (for each color
59    component), leaving the result in component order on the stack. It assumes
60    there are always 3 components per color.
61    @param range                  endOffset - startOffset
62    @param curColor[components]   The current color components.
63    @param prevColor[components]  The previous color components.
64    @param result                 The result ps function.
65  */
interpolate_color_code(SkScalar range,const ColorTuple & curColor,const ColorTuple & prevColor,SkDynamicMemoryWStream * result)66 static void interpolate_color_code(SkScalar range, const ColorTuple& curColor,
67                                    const ColorTuple& prevColor,
68                                    SkDynamicMemoryWStream* result) {
69     SkASSERT(range != SkIntToScalar(0));
70 
71     // Figure out how to scale each color component.
72     SkScalar multiplier[kColorComponents];
73     for (int i = 0; i < kColorComponents; i++) {
74         static const SkScalar kColorScale = SkScalarInvert(255);
75         multiplier[i] = kColorScale * (curColor[i] - prevColor[i]) / range;
76     }
77 
78     // Calculate when we no longer need to keep a copy of the input parameter t.
79     // If the last component to use t is i, then dupInput[0..i - 1] = true
80     // and dupInput[i .. components] = false.
81     bool dupInput[kColorComponents];
82     dupInput[kColorComponents - 1] = false;
83     for (int i = kColorComponents - 2; i >= 0; i--) {
84         dupInput[i] = dupInput[i + 1] || multiplier[i + 1] != 0;
85     }
86 
87     if (!dupInput[0] && multiplier[0] == 0) {
88         result->writeText("pop ");
89     }
90 
91     for (int i = 0; i < kColorComponents; i++) {
92         // If the next components needs t and this component will consume a
93         // copy, make another copy.
94         if (dupInput[i] && multiplier[i] != 0) {
95             result->writeText("dup ");
96         }
97 
98         if (multiplier[i] == 0) {
99             SkPDFUtils::AppendColorComponent(prevColor[i], result);
100             result->writeText(" ");
101         } else {
102             if (multiplier[i] != 1) {
103                 SkPDFUtils::AppendScalar(multiplier[i], result);
104                 result->writeText(" mul ");
105             }
106             if (prevColor[i] != 0) {
107                 SkPDFUtils::AppendColorComponent(prevColor[i], result);
108                 result->writeText(" add ");
109             }
110         }
111 
112         if (dupInput[i]) {
113             result->writeText("exch\n");
114         }
115     }
116 }
117 
118 /* Generate Type 4 function code to map t=[0,1) to the passed gradient,
119    clamping at the edges of the range.  The generated code will be of the form:
120        if (t < 0) {
121            return colorData[0][r,g,b];
122        } else {
123            if (t < info.fColorOffsets[1]) {
124                return linearinterpolation(colorData[0][r,g,b],
125                                           colorData[1][r,g,b]);
126            } else {
127                if (t < info.fColorOffsets[2]) {
128                    return linearinterpolation(colorData[1][r,g,b],
129                                               colorData[2][r,g,b]);
130                } else {
131 
132                 ...    } else {
133                            return colorData[info.fColorCount - 1][r,g,b];
134                        }
135                 ...
136            }
137        }
138  */
gradient_function_code(const SkShader::GradientInfo & info,SkDynamicMemoryWStream * result)139 static void gradient_function_code(const SkShader::GradientInfo& info,
140                                  SkDynamicMemoryWStream* result) {
141     /* We want to linearly interpolate from the previous color to the next.
142        Scale the colors from 0..255 to 0..1 and determine the multipliers
143        for interpolation.
144        C{r,g,b}(t, section) = t - offset_(section-1) + t * Multiplier{r,g,b}.
145      */
146 
147     SkAutoSTMalloc<4, ColorTuple> colorDataAlloc(info.fColorCount);
148     ColorTuple *colorData = colorDataAlloc.get();
149     for (int i = 0; i < info.fColorCount; i++) {
150         colorData[i][0] = SkColorGetR(info.fColors[i]);
151         colorData[i][1] = SkColorGetG(info.fColors[i]);
152         colorData[i][2] = SkColorGetB(info.fColors[i]);
153     }
154 
155     // Clamp the initial color.
156     result->writeText("dup 0 le {pop ");
157     SkPDFUtils::AppendColorComponent(colorData[0][0], result);
158     result->writeText(" ");
159     SkPDFUtils::AppendColorComponent(colorData[0][1], result);
160     result->writeText(" ");
161     SkPDFUtils::AppendColorComponent(colorData[0][2], result);
162     result->writeText(" }\n");
163 
164     // The gradient colors.
165     int gradients = 0;
166     for (int i = 1 ; i < info.fColorCount; i++) {
167         if (info.fColorOffsets[i] == info.fColorOffsets[i - 1]) {
168             continue;
169         }
170         gradients++;
171 
172         result->writeText("{dup ");
173         SkPDFUtils::AppendScalar(info.fColorOffsets[i], result);
174         result->writeText(" le {");
175         if (info.fColorOffsets[i - 1] != 0) {
176             SkPDFUtils::AppendScalar(info.fColorOffsets[i - 1], result);
177             result->writeText(" sub\n");
178         }
179 
180         interpolate_color_code(info.fColorOffsets[i] - info.fColorOffsets[i - 1],
181                              colorData[i], colorData[i - 1], result);
182         result->writeText("}\n");
183     }
184 
185     // Clamp the final color.
186     result->writeText("{pop ");
187     SkPDFUtils::AppendColorComponent(colorData[info.fColorCount - 1][0], result);
188     result->writeText(" ");
189     SkPDFUtils::AppendColorComponent(colorData[info.fColorCount - 1][1], result);
190     result->writeText(" ");
191     SkPDFUtils::AppendColorComponent(colorData[info.fColorCount - 1][2], result);
192 
193     for (int i = 0 ; i < gradients + 1; i++) {
194         result->writeText("} ifelse\n");
195     }
196 }
197 
createInterpolationFunction(const ColorTuple & color1,const ColorTuple & color2)198 static std::unique_ptr<SkPDFDict> createInterpolationFunction(const ColorTuple& color1,
199                                                     const ColorTuple& color2) {
200     auto retval = SkPDFMakeDict();
201 
202     auto c0 = SkPDFMakeArray();
203     c0->appendColorComponent(color1[0]);
204     c0->appendColorComponent(color1[1]);
205     c0->appendColorComponent(color1[2]);
206     retval->insertObject("C0", std::move(c0));
207 
208     auto c1 = SkPDFMakeArray();
209     c1->appendColorComponent(color2[0]);
210     c1->appendColorComponent(color2[1]);
211     c1->appendColorComponent(color2[2]);
212     retval->insertObject("C1", std::move(c1));
213 
214     retval->insertObject("Domain", SkPDFMakeArray(0, 1));
215 
216     retval->insertInt("FunctionType", 2);
217     retval->insertScalar("N", 1.0f);
218 
219     return retval;
220 }
221 
gradientStitchCode(const SkShader::GradientInfo & info)222 static std::unique_ptr<SkPDFDict> gradientStitchCode(const SkShader::GradientInfo& info) {
223     auto retval = SkPDFMakeDict();
224 
225     // normalize color stops
226     int colorCount = info.fColorCount;
227     std::vector<SkColor>  colors(info.fColors, info.fColors + colorCount);
228     std::vector<SkScalar> colorOffsets(info.fColorOffsets, info.fColorOffsets + colorCount);
229 
230     int i = 1;
231     while (i < colorCount - 1) {
232         // ensure stops are in order
233         if (colorOffsets[i - 1] > colorOffsets[i]) {
234             colorOffsets[i] = colorOffsets[i - 1];
235         }
236 
237         // remove points that are between 2 coincident points
238         if ((colorOffsets[i - 1] == colorOffsets[i]) && (colorOffsets[i] == colorOffsets[i + 1])) {
239             colorCount -= 1;
240             colors.erase(colors.begin() + i);
241             colorOffsets.erase(colorOffsets.begin() + i);
242         } else {
243             i++;
244         }
245     }
246     // find coincident points and slightly move them over
247     for (i = 1; i < colorCount - 1; i++) {
248         if (colorOffsets[i - 1] == colorOffsets[i]) {
249             colorOffsets[i] += 0.00001f;
250         }
251     }
252     // check if last 2 stops coincide
253     if (colorOffsets[i - 1] == colorOffsets[i]) {
254         colorOffsets[i - 1] -= 0.00001f;
255     }
256 
257     SkAutoSTMalloc<4, ColorTuple> colorDataAlloc(colorCount);
258     ColorTuple *colorData = colorDataAlloc.get();
259     for (int i = 0; i < colorCount; i++) {
260         colorData[i][0] = SkColorGetR(colors[i]);
261         colorData[i][1] = SkColorGetG(colors[i]);
262         colorData[i][2] = SkColorGetB(colors[i]);
263     }
264 
265     // no need for a stitch function if there are only 2 stops.
266     if (colorCount == 2)
267         return createInterpolationFunction(colorData[0], colorData[1]);
268 
269     auto encode = SkPDFMakeArray();
270     auto bounds = SkPDFMakeArray();
271     auto functions = SkPDFMakeArray();
272 
273     retval->insertObject("Domain", SkPDFMakeArray(0, 1));
274     retval->insertInt("FunctionType", 3);
275 
276     for (int i = 1; i < colorCount; i++) {
277         if (i > 1) {
278             bounds->appendScalar(colorOffsets[i-1]);
279         }
280 
281         encode->appendScalar(0);
282         encode->appendScalar(1.0f);
283 
284         functions->appendObject(createInterpolationFunction(colorData[i-1], colorData[i]));
285     }
286 
287     retval->insertObject("Encode", std::move(encode));
288     retval->insertObject("Bounds", std::move(bounds));
289     retval->insertObject("Functions", std::move(functions));
290 
291     return retval;
292 }
293 
294 /* Map a value of t on the stack into [0, 1) for Repeat or Mirror tile mode. */
tileModeCode(SkShader::TileMode mode,SkDynamicMemoryWStream * result)295 static void tileModeCode(SkShader::TileMode mode,
296                          SkDynamicMemoryWStream* result) {
297     if (mode == SkShader::kRepeat_TileMode) {
298         result->writeText("dup truncate sub\n");  // Get the fractional part.
299         result->writeText("dup 0 le {1 add} if\n");  // Map (-1,0) => (0,1)
300         return;
301     }
302 
303     if (mode == SkShader::kMirror_TileMode) {
304         // Map t mod 2 into [0, 1, 1, 0].
305         //               Code                     Stack
306         result->writeText("abs "                 // Map negative to positive.
307                           "dup "                 // t.s t.s
308                           "truncate "            // t.s t
309                           "dup "                 // t.s t t
310                           "cvi "                 // t.s t T
311                           "2 mod "               // t.s t (i mod 2)
312                           "1 eq "                // t.s t true|false
313                           "3 1 roll "            // true|false t.s t
314                           "sub "                 // true|false 0.s
315                           "exch "                // 0.s true|false
316                           "{1 exch sub} if\n");  // 1 - 0.s|0.s
317     }
318 }
319 
320 /**
321  *  Returns PS function code that applies inverse perspective
322  *  to a x, y point.
323  *  The function assumes that the stack has at least two elements,
324  *  and that the top 2 elements are numeric values.
325  *  After executing this code on a PS stack, the last 2 elements are updated
326  *  while the rest of the stack is preserved intact.
327  *  inversePerspectiveMatrix is the inverse perspective matrix.
328  */
apply_perspective_to_coordinates(const SkMatrix & inversePerspectiveMatrix,SkDynamicMemoryWStream * code)329 static void apply_perspective_to_coordinates(const SkMatrix& inversePerspectiveMatrix,
330                                              SkDynamicMemoryWStream* code) {
331     if (!inversePerspectiveMatrix.hasPerspective()) {
332         return;
333     }
334 
335     // Perspective matrix should be:
336     // 1   0  0
337     // 0   1  0
338     // p0 p1 p2
339 
340     const SkScalar p0 = inversePerspectiveMatrix[SkMatrix::kMPersp0];
341     const SkScalar p1 = inversePerspectiveMatrix[SkMatrix::kMPersp1];
342     const SkScalar p2 = inversePerspectiveMatrix[SkMatrix::kMPersp2];
343 
344     // y = y / (p2 + p0 x + p1 y)
345     // x = x / (p2 + p0 x + p1 y)
346 
347     // Input on stack: x y
348     code->writeText(" dup ");             // x y y
349     SkPDFUtils::AppendScalar(p1, code);   // x y y p1
350     code->writeText(" mul "               // x y y*p1
351                     " 2 index ");         // x y y*p1 x
352     SkPDFUtils::AppendScalar(p0, code);   // x y y p1 x p0
353     code->writeText(" mul ");             // x y y*p1 x*p0
354     SkPDFUtils::AppendScalar(p2, code);   // x y y p1 x*p0 p2
355     code->writeText(" add "               // x y y*p1 x*p0+p2
356                     "add "                // x y y*p1+x*p0+p2
357                     "3 1 roll "           // y*p1+x*p0+p2 x y
358                     "2 index "            // z x y y*p1+x*p0+p2
359                     "div "                // y*p1+x*p0+p2 x y/(y*p1+x*p0+p2)
360                     "3 1 roll "           // y/(y*p1+x*p0+p2) y*p1+x*p0+p2 x
361                     "exch "               // y/(y*p1+x*p0+p2) x y*p1+x*p0+p2
362                     "div "                // y/(y*p1+x*p0+p2) x/(y*p1+x*p0+p2)
363                     "exch\n");            // x/(y*p1+x*p0+p2) y/(y*p1+x*p0+p2)
364 }
365 
linearCode(const SkShader::GradientInfo & info,const SkMatrix & perspectiveRemover,SkDynamicMemoryWStream * function)366 static void linearCode(const SkShader::GradientInfo& info,
367                        const SkMatrix& perspectiveRemover,
368                        SkDynamicMemoryWStream* function) {
369     function->writeText("{");
370 
371     apply_perspective_to_coordinates(perspectiveRemover, function);
372 
373     function->writeText("pop\n");  // Just ditch the y value.
374     tileModeCode(info.fTileMode, function);
375     gradient_function_code(info, function);
376     function->writeText("}");
377 }
378 
radialCode(const SkShader::GradientInfo & info,const SkMatrix & perspectiveRemover,SkDynamicMemoryWStream * function)379 static void radialCode(const SkShader::GradientInfo& info,
380                        const SkMatrix& perspectiveRemover,
381                        SkDynamicMemoryWStream* function) {
382     function->writeText("{");
383 
384     apply_perspective_to_coordinates(perspectiveRemover, function);
385 
386     // Find the distance from the origin.
387     function->writeText("dup "      // x y y
388                     "mul "      // x y^2
389                     "exch "     // y^2 x
390                     "dup "      // y^2 x x
391                     "mul "      // y^2 x^2
392                     "add "      // y^2+x^2
393                     "sqrt\n");  // sqrt(y^2+x^2)
394 
395     tileModeCode(info.fTileMode, function);
396     gradient_function_code(info, function);
397     function->writeText("}");
398 }
399 
400 /* Conical gradient shader, based on the Canvas spec for radial gradients
401    See: http://www.w3.org/TR/2dcontext/#dom-context-2d-createradialgradient
402  */
twoPointConicalCode(const SkShader::GradientInfo & info,const SkMatrix & perspectiveRemover,SkDynamicMemoryWStream * function)403 static void twoPointConicalCode(const SkShader::GradientInfo& info,
404                                 const SkMatrix& perspectiveRemover,
405                                 SkDynamicMemoryWStream* function) {
406     SkScalar dx = info.fPoint[1].fX - info.fPoint[0].fX;
407     SkScalar dy = info.fPoint[1].fY - info.fPoint[0].fY;
408     SkScalar r0 = info.fRadius[0];
409     SkScalar dr = info.fRadius[1] - info.fRadius[0];
410     SkScalar a = dx * dx + dy * dy - dr * dr;
411 
412     // First compute t, if the pixel falls outside the cone, then we'll end
413     // with 'false' on the stack, otherwise we'll push 'true' with t below it
414 
415     // We start with a stack of (x y), copy it and then consume one copy in
416     // order to calculate b and the other to calculate c.
417     function->writeText("{");
418 
419     apply_perspective_to_coordinates(perspectiveRemover, function);
420 
421     function->writeText("2 copy ");
422 
423     // Calculate b and b^2; b = -2 * (y * dy + x * dx + r0 * dr).
424     SkPDFUtils::AppendScalar(dy, function);
425     function->writeText(" mul exch ");
426     SkPDFUtils::AppendScalar(dx, function);
427     function->writeText(" mul add ");
428     SkPDFUtils::AppendScalar(r0 * dr, function);
429     function->writeText(" add -2 mul dup dup mul\n");
430 
431     // c = x^2 + y^2 + radius0^2
432     function->writeText("4 2 roll dup mul exch dup mul add ");
433     SkPDFUtils::AppendScalar(r0 * r0, function);
434     function->writeText(" sub dup 4 1 roll\n");
435 
436     // Contents of the stack at this point: c, b, b^2, c
437 
438     // if a = 0, then we collapse to a simpler linear case
439     if (a == 0) {
440 
441         // t = -c/b
442         function->writeText("pop pop div neg dup ");
443 
444         // compute radius(t)
445         SkPDFUtils::AppendScalar(dr, function);
446         function->writeText(" mul ");
447         SkPDFUtils::AppendScalar(r0, function);
448         function->writeText(" add\n");
449 
450         // if r(t) < 0, then it's outside the cone
451         function->writeText("0 lt {pop false} {true} ifelse\n");
452 
453     } else {
454 
455         // quadratic case: the Canvas spec wants the largest
456         // root t for which radius(t) > 0
457 
458         // compute the discriminant (b^2 - 4ac)
459         SkPDFUtils::AppendScalar(a * 4, function);
460         function->writeText(" mul sub dup\n");
461 
462         // if d >= 0, proceed
463         function->writeText("0 ge {\n");
464 
465         // an intermediate value we'll use to compute the roots:
466         // q = -0.5 * (b +/- sqrt(d))
467         function->writeText("sqrt exch dup 0 lt {exch -1 mul} if");
468         function->writeText(" add -0.5 mul dup\n");
469 
470         // first root = q / a
471         SkPDFUtils::AppendScalar(a, function);
472         function->writeText(" div\n");
473 
474         // second root = c / q
475         function->writeText("3 1 roll div\n");
476 
477         // put the larger root on top of the stack
478         function->writeText("2 copy gt {exch} if\n");
479 
480         // compute radius(t) for larger root
481         function->writeText("dup ");
482         SkPDFUtils::AppendScalar(dr, function);
483         function->writeText(" mul ");
484         SkPDFUtils::AppendScalar(r0, function);
485         function->writeText(" add\n");
486 
487         // if r(t) > 0, we have our t, pop off the smaller root and we're done
488         function->writeText(" 0 gt {exch pop true}\n");
489 
490         // otherwise, throw out the larger one and try the smaller root
491         function->writeText("{pop dup\n");
492         SkPDFUtils::AppendScalar(dr, function);
493         function->writeText(" mul ");
494         SkPDFUtils::AppendScalar(r0, function);
495         function->writeText(" add\n");
496 
497         // if r(t) < 0, push false, otherwise the smaller root is our t
498         function->writeText("0 le {pop false} {true} ifelse\n");
499         function->writeText("} ifelse\n");
500 
501         // d < 0, clear the stack and push false
502         function->writeText("} {pop pop pop false} ifelse\n");
503     }
504 
505     // if the pixel is in the cone, proceed to compute a color
506     function->writeText("{");
507     tileModeCode(info.fTileMode, function);
508     gradient_function_code(info, function);
509 
510     // otherwise, just write black
511     function->writeText("} {0 0 0} ifelse }");
512 }
513 
sweepCode(const SkShader::GradientInfo & info,const SkMatrix & perspectiveRemover,SkDynamicMemoryWStream * function)514 static void sweepCode(const SkShader::GradientInfo& info,
515                           const SkMatrix& perspectiveRemover,
516                           SkDynamicMemoryWStream* function) {
517     function->writeText("{exch atan 360 div\n");
518     tileModeCode(info.fTileMode, function);
519     gradient_function_code(info, function);
520     function->writeText("}");
521 }
522 
523 
524 // catch cases where the inner just touches the outer circle
525 // and make the inner circle just inside the outer one to match raster
FixUpRadius(const SkPoint & p1,SkScalar & r1,const SkPoint & p2,SkScalar & r2)526 static void FixUpRadius(const SkPoint& p1, SkScalar& r1, const SkPoint& p2, SkScalar& r2) {
527     // detect touching circles
528     SkScalar distance = SkPoint::Distance(p1, p2);
529     SkScalar subtractRadii = fabs(r1 - r2);
530     if (fabs(distance - subtractRadii) < 0.002f) {
531         if (r1 > r2) {
532             r1 += 0.002f;
533         } else {
534             r2 += 0.002f;
535         }
536     }
537 }
538 
539 // Finds affine and persp such that in = affine * persp.
540 // but it returns the inverse of perspective matrix.
split_perspective(const SkMatrix in,SkMatrix * affine,SkMatrix * perspectiveInverse)541 static bool split_perspective(const SkMatrix in, SkMatrix* affine,
542                               SkMatrix* perspectiveInverse) {
543     const SkScalar p2 = in[SkMatrix::kMPersp2];
544 
545     if (SkScalarNearlyZero(p2)) {
546         return false;
547     }
548 
549     const SkScalar zero = SkIntToScalar(0);
550     const SkScalar one = SkIntToScalar(1);
551 
552     const SkScalar sx = in[SkMatrix::kMScaleX];
553     const SkScalar kx = in[SkMatrix::kMSkewX];
554     const SkScalar tx = in[SkMatrix::kMTransX];
555     const SkScalar ky = in[SkMatrix::kMSkewY];
556     const SkScalar sy = in[SkMatrix::kMScaleY];
557     const SkScalar ty = in[SkMatrix::kMTransY];
558     const SkScalar p0 = in[SkMatrix::kMPersp0];
559     const SkScalar p1 = in[SkMatrix::kMPersp1];
560 
561     // Perspective matrix would be:
562     // 1  0  0
563     // 0  1  0
564     // p0 p1 p2
565     // But we need the inverse of persp.
566     perspectiveInverse->setAll(one,          zero,       zero,
567                                zero,         one,        zero,
568                                -p0/p2,     -p1/p2,     1/p2);
569 
570     affine->setAll(sx - p0 * tx / p2,       kx - p1 * tx / p2,      tx / p2,
571                    ky - p0 * ty / p2,       sy - p1 * ty / p2,      ty / p2,
572                    zero,                    zero,                   one);
573 
574     return true;
575 }
576 
make_ps_function(std::unique_ptr<SkStreamAsset> psCode,std::unique_ptr<SkPDFArray> domain,std::unique_ptr<SkPDFObject> range,SkPDFDocument * doc)577 static SkPDFIndirectReference make_ps_function(std::unique_ptr<SkStreamAsset> psCode,
578                                                std::unique_ptr<SkPDFArray> domain,
579                                                std::unique_ptr<SkPDFObject> range,
580                                                SkPDFDocument* doc) {
581     std::unique_ptr<SkPDFDict> dict = SkPDFMakeDict();
582     dict->insertInt("FunctionType", 4);
583     dict->insertObject("Domain", std::move(domain));
584     dict->insertObject("Range", std::move(range));
585     return SkPDFStreamOut(std::move(dict), std::move(psCode), doc);
586 }
587 
make_function_shader(SkPDFDocument * doc,const SkPDFGradientShader::Key & state)588 static SkPDFIndirectReference make_function_shader(SkPDFDocument* doc,
589                                                    const SkPDFGradientShader::Key& state) {
590     SkPoint transformPoints[2];
591     const SkShader::GradientInfo& info = state.fInfo;
592     SkMatrix finalMatrix = state.fCanvasTransform;
593     finalMatrix.preConcat(state.fShaderTransform);
594 
595     bool doStitchFunctions = (state.fType == SkShader::kLinear_GradientType ||
596                               state.fType == SkShader::kRadial_GradientType ||
597                               state.fType == SkShader::kConical_GradientType) &&
598                              info.fTileMode == SkShader::kClamp_TileMode &&
599                              !finalMatrix.hasPerspective();
600 
601     int32_t shadingType = 1;
602     auto pdfShader = SkPDFMakeDict();
603     // The two point radial gradient further references
604     // state.fInfo
605     // in translating from x, y coordinates to the t parameter. So, we have
606     // to transform the points and radii according to the calculated matrix.
607     if (doStitchFunctions) {
608         pdfShader->insertObject("Function", gradientStitchCode(info));
609         shadingType = (state.fType == SkShader::kLinear_GradientType) ? 2 : 3;
610 
611         auto extend = SkPDFMakeArray();
612         extend->reserve(2);
613         extend->appendBool(true);
614         extend->appendBool(true);
615         pdfShader->insertObject("Extend", std::move(extend));
616 
617         std::unique_ptr<SkPDFArray> coords;
618         if (state.fType == SkShader::kConical_GradientType) {
619             SkScalar r1 = info.fRadius[0];
620             SkScalar r2 = info.fRadius[1];
621             SkPoint pt1 = info.fPoint[0];
622             SkPoint pt2 = info.fPoint[1];
623             FixUpRadius(pt1, r1, pt2, r2);
624 
625             coords = SkPDFMakeArray(pt1.x(),
626                                     pt1.y(),
627                                     r1,
628                                     pt2.x(),
629                                     pt2.y(),
630                                     r2);
631         } else if (state.fType == SkShader::kRadial_GradientType) {
632             const SkPoint& pt1 = info.fPoint[0];
633             coords = SkPDFMakeArray(pt1.x(),
634                                     pt1.y(),
635                                     0,
636                                     pt1.x(),
637                                     pt1.y(),
638                                     info.fRadius[0]);
639         } else {
640             const SkPoint& pt1 = info.fPoint[0];
641             const SkPoint& pt2 = info.fPoint[1];
642             coords = SkPDFMakeArray(pt1.x(),
643                                     pt1.y(),
644                                     pt2.x(),
645                                     pt2.y());
646         }
647 
648         pdfShader->insertObject("Coords", std::move(coords));
649     } else {
650         // Depending on the type of the gradient, we want to transform the
651         // coordinate space in different ways.
652         transformPoints[0] = info.fPoint[0];
653         transformPoints[1] = info.fPoint[1];
654         switch (state.fType) {
655             case SkShader::kLinear_GradientType:
656                 break;
657             case SkShader::kRadial_GradientType:
658                 transformPoints[1] = transformPoints[0];
659                 transformPoints[1].fX += info.fRadius[0];
660                 break;
661             case SkShader::kConical_GradientType: {
662                 transformPoints[1] = transformPoints[0];
663                 transformPoints[1].fX += SK_Scalar1;
664                 break;
665             }
666             case SkShader::kSweep_GradientType:
667                 transformPoints[1] = transformPoints[0];
668                 transformPoints[1].fX += SK_Scalar1;
669                 break;
670             case SkShader::kColor_GradientType:
671             case SkShader::kNone_GradientType:
672             default:
673                 return SkPDFIndirectReference();
674         }
675 
676         // Move any scaling (assuming a unit gradient) or translation
677         // (and rotation for linear gradient), of the final gradient from
678         // info.fPoints to the matrix (updating bbox appropriately).  Now
679         // the gradient can be drawn on on the unit segment.
680         SkMatrix mapperMatrix;
681         unit_to_points_matrix(transformPoints, &mapperMatrix);
682 
683         finalMatrix.preConcat(mapperMatrix);
684 
685         // Preserves as much as possible in the final matrix, and only removes
686         // the perspective. The inverse of the perspective is stored in
687         // perspectiveInverseOnly matrix and has 3 useful numbers
688         // (p0, p1, p2), while everything else is either 0 or 1.
689         // In this way the shader will handle it eficiently, with minimal code.
690         SkMatrix perspectiveInverseOnly = SkMatrix::I();
691         if (finalMatrix.hasPerspective()) {
692             if (!split_perspective(finalMatrix,
693                                    &finalMatrix, &perspectiveInverseOnly)) {
694                 return SkPDFIndirectReference();
695             }
696         }
697 
698         SkRect bbox;
699         bbox.set(state.fBBox);
700         if (!SkPDFUtils::InverseTransformBBox(finalMatrix, &bbox)) {
701             return SkPDFIndirectReference();
702         }
703         SkDynamicMemoryWStream functionCode;
704 
705         SkShader::GradientInfo infoCopy = info;
706 
707         if (state.fType == SkShader::kConical_GradientType) {
708             SkMatrix inverseMapperMatrix;
709             if (!mapperMatrix.invert(&inverseMapperMatrix)) {
710                 return SkPDFIndirectReference();
711             }
712             inverseMapperMatrix.mapPoints(infoCopy.fPoint, 2);
713             infoCopy.fRadius[0] = inverseMapperMatrix.mapRadius(info.fRadius[0]);
714             infoCopy.fRadius[1] = inverseMapperMatrix.mapRadius(info.fRadius[1]);
715         }
716         switch (state.fType) {
717             case SkShader::kLinear_GradientType:
718                 linearCode(infoCopy, perspectiveInverseOnly, &functionCode);
719                 break;
720             case SkShader::kRadial_GradientType:
721                 radialCode(infoCopy, perspectiveInverseOnly, &functionCode);
722                 break;
723             case SkShader::kConical_GradientType:
724                 twoPointConicalCode(infoCopy, perspectiveInverseOnly, &functionCode);
725                 break;
726             case SkShader::kSweep_GradientType:
727                 sweepCode(infoCopy, perspectiveInverseOnly, &functionCode);
728                 break;
729             default:
730                 SkASSERT(false);
731         }
732         pdfShader->insertObject(
733                 "Domain", SkPDFMakeArray(bbox.left(), bbox.right(), bbox.top(), bbox.bottom()));
734 
735         auto domain = SkPDFMakeArray(bbox.left(), bbox.right(), bbox.top(), bbox.bottom());
736         std::unique_ptr<SkPDFArray> rangeObject = SkPDFMakeArray(0, 1, 0, 1, 0, 1);
737         pdfShader->insertRef("Function",
738                              make_ps_function(functionCode.detachAsStream(), std::move(domain),
739                                               std::move(rangeObject), doc));
740     }
741 
742     pdfShader->insertInt("ShadingType", shadingType);
743     pdfShader->insertName("ColorSpace", "DeviceRGB");
744 
745     SkPDFDict pdfFunctionShader("Pattern");
746     pdfFunctionShader.insertInt("PatternType", 2);
747     pdfFunctionShader.insertObject("Matrix", SkPDFUtils::MatrixToArray(finalMatrix));
748     pdfFunctionShader.insertObject("Shading", std::move(pdfShader));
749     return doc->emit(pdfFunctionShader);
750 }
751 
752 static SkPDFIndirectReference find_pdf_shader(SkPDFDocument* doc,
753                                               SkPDFGradientShader::Key key,
754                                               bool keyHasAlpha);
755 
get_gradient_resource_dict(SkPDFIndirectReference functionShader,SkPDFIndirectReference gState)756 static std::unique_ptr<SkPDFDict> get_gradient_resource_dict(SkPDFIndirectReference functionShader,
757                                                    SkPDFIndirectReference gState) {
758     std::vector<SkPDFIndirectReference> patternShaders;
759     if (functionShader != SkPDFIndirectReference()) {
760         patternShaders.push_back(functionShader);
761     }
762     std::vector<SkPDFIndirectReference> graphicStates;
763     if (gState != SkPDFIndirectReference()) {
764         graphicStates.push_back(gState);
765     }
766     return SkPDFMakeResourceDict(std::move(graphicStates),
767                                  std::move(patternShaders),
768                                  std::vector<SkPDFIndirectReference>(),
769                                  std::vector<SkPDFIndirectReference>());
770 }
771 
772 // Creates a content stream which fills the pattern P0 across bounds.
773 // @param gsIndex A graphics state resource index to apply, or <0 if no
774 // graphics state to apply.
create_pattern_fill_content(int gsIndex,int patternIndex,SkRect & bounds)775 static std::unique_ptr<SkStreamAsset> create_pattern_fill_content(int gsIndex,
776                                                                   int patternIndex,
777                                                                   SkRect& bounds) {
778     SkDynamicMemoryWStream content;
779     if (gsIndex >= 0) {
780         SkPDFUtils::ApplyGraphicState(gsIndex, &content);
781     }
782     SkPDFUtils::ApplyPattern(patternIndex, &content);
783     SkPDFUtils::AppendRectangle(bounds, &content);
784     SkPDFUtils::PaintPath(SkPaint::kFill_Style, SkPath::kEvenOdd_FillType, &content);
785     return content.detachAsStream();
786 }
787 
gradient_has_alpha(const SkPDFGradientShader::Key & key)788 static bool gradient_has_alpha(const SkPDFGradientShader::Key& key) {
789     SkASSERT(key.fType != SkShader::kNone_GradientType);
790     for (int i = 0; i < key.fInfo.fColorCount; i++) {
791         if ((SkAlpha)SkColorGetA(key.fInfo.fColors[i]) != SK_AlphaOPAQUE) {
792             return true;
793         }
794     }
795     return false;
796 }
797 
798 // warning: does not set fHash on new key.  (Both callers need to change fields.)
clone_key(const SkPDFGradientShader::Key & k)799 static SkPDFGradientShader::Key clone_key(const SkPDFGradientShader::Key& k) {
800     SkPDFGradientShader::Key clone = {
801         k.fType,
802         k.fInfo,  // change pointers later.
803         std::unique_ptr<SkColor[]>(new SkColor[k.fInfo.fColorCount]),
804         std::unique_ptr<SkScalar[]>(new SkScalar[k.fInfo.fColorCount]),
805         k.fCanvasTransform,
806         k.fShaderTransform,
807         k.fBBox, 0};
808     clone.fInfo.fColors = clone.fColors.get();
809     clone.fInfo.fColorOffsets = clone.fStops.get();
810     for (int i = 0; i < clone.fInfo.fColorCount; i++) {
811         clone.fInfo.fColorOffsets[i] = k.fInfo.fColorOffsets[i];
812         clone.fInfo.fColors[i] = k.fInfo.fColors[i];
813     }
814     return clone;
815 }
816 
create_smask_graphic_state(SkPDFDocument * doc,const SkPDFGradientShader::Key & state)817 static SkPDFIndirectReference create_smask_graphic_state(SkPDFDocument* doc,
818                                                      const SkPDFGradientShader::Key& state) {
819     SkASSERT(state.fType != SkShader::kNone_GradientType);
820     SkPDFGradientShader::Key luminosityState = clone_key(state);
821     for (int i = 0; i < luminosityState.fInfo.fColorCount; i++) {
822         SkAlpha alpha = SkColorGetA(luminosityState.fInfo.fColors[i]);
823         luminosityState.fInfo.fColors[i] = SkColorSetARGB(255, alpha, alpha, alpha);
824     }
825     luminosityState.fHash = hash(luminosityState);
826 
827     SkASSERT(!gradient_has_alpha(luminosityState));
828     SkPDFIndirectReference luminosityShader = find_pdf_shader(doc, std::move(luminosityState), false);
829     std::unique_ptr<SkPDFDict> resources = get_gradient_resource_dict(luminosityShader,
830                                                             SkPDFIndirectReference());
831     SkRect bbox = SkRect::Make(state.fBBox);
832     SkPDFIndirectReference alphaMask =
833             SkPDFMakeFormXObject(doc,
834                                  create_pattern_fill_content(-1, luminosityShader.fValue, bbox),
835                                  SkPDFUtils::RectToArray(bbox),
836                                  std::move(resources),
837                                  SkMatrix::I(),
838                                  "DeviceRGB");
839     return SkPDFGraphicState::GetSMaskGraphicState(
840             alphaMask, false, SkPDFGraphicState::kLuminosity_SMaskMode, doc);
841 }
842 
make_alpha_function_shader(SkPDFDocument * doc,const SkPDFGradientShader::Key & state)843 static SkPDFIndirectReference make_alpha_function_shader(SkPDFDocument* doc,
844                                                          const SkPDFGradientShader::Key& state) {
845     SkASSERT(state.fType != SkShader::kNone_GradientType);
846     SkPDFGradientShader::Key opaqueState = clone_key(state);
847     for (int i = 0; i < opaqueState.fInfo.fColorCount; i++) {
848         opaqueState.fInfo.fColors[i] = SkColorSetA(opaqueState.fInfo.fColors[i], SK_AlphaOPAQUE);
849     }
850     opaqueState.fHash = hash(opaqueState);
851 
852     SkASSERT(!gradient_has_alpha(opaqueState));
853     SkRect bbox = SkRect::Make(state.fBBox);
854     SkPDFIndirectReference colorShader = find_pdf_shader(doc, std::move(opaqueState), false);
855     if (!colorShader) {
856         return SkPDFIndirectReference();
857     }
858     // Create resource dict with alpha graphics state as G0 and
859     // pattern shader as P0, then write content stream.
860     SkPDFIndirectReference alphaGsRef = create_smask_graphic_state(doc, state);
861 
862     std::unique_ptr<SkPDFDict> resourceDict = get_gradient_resource_dict(colorShader, alphaGsRef);
863 
864     std::unique_ptr<SkStreamAsset> colorStream =
865             create_pattern_fill_content(alphaGsRef.fValue, colorShader.fValue, bbox);
866     std::unique_ptr<SkPDFDict> alphaFunctionShader = SkPDFMakeDict();
867     SkPDFUtils::PopulateTilingPatternDict(alphaFunctionShader.get(), bbox,
868                                  std::move(resourceDict), SkMatrix::I());
869     return SkPDFStreamOut(std::move(alphaFunctionShader), std::move(colorStream), doc);
870 }
871 
make_key(const SkShader * shader,const SkMatrix & canvasTransform,const SkIRect & bbox)872 static SkPDFGradientShader::Key make_key(const SkShader* shader,
873                                          const SkMatrix& canvasTransform,
874                                          const SkIRect& bbox) {
875     SkPDFGradientShader::Key key = {
876          SkShader::kNone_GradientType,
877          {0, nullptr, nullptr, {{0, 0}, {0, 0}}, {0, 0}, SkShader::kClamp_TileMode, 0},
878          nullptr,
879          nullptr,
880          canvasTransform,
881          SkPDFUtils::GetShaderLocalMatrix(shader),
882          bbox, 0};
883     key.fType = shader->asAGradient(&key.fInfo);
884     SkASSERT(SkShader::kNone_GradientType != key.fType);
885     SkASSERT(key.fInfo.fColorCount > 0);
886     key.fColors.reset(new SkColor[key.fInfo.fColorCount]);
887     key.fStops.reset(new SkScalar[key.fInfo.fColorCount]);
888     key.fInfo.fColors = key.fColors.get();
889     key.fInfo.fColorOffsets = key.fStops.get();
890     (void)shader->asAGradient(&key.fInfo);
891     key.fHash = hash(key);
892     return key;
893 }
894 
find_pdf_shader(SkPDFDocument * doc,SkPDFGradientShader::Key key,bool keyHasAlpha)895 static SkPDFIndirectReference find_pdf_shader(SkPDFDocument* doc,
896                                               SkPDFGradientShader::Key key,
897                                               bool keyHasAlpha) {
898     SkASSERT(gradient_has_alpha(key) == keyHasAlpha);
899     auto& gradientPatternMap = doc->fGradientPatternMap;
900     if (SkPDFIndirectReference* ptr = gradientPatternMap.find(key)) {
901         return *ptr;
902     }
903     SkPDFIndirectReference pdfShader;
904     if (keyHasAlpha) {
905         pdfShader = make_alpha_function_shader(doc, key);
906     } else {
907         pdfShader = make_function_shader(doc, key);
908     }
909     gradientPatternMap.set(std::move(key), pdfShader);
910     return pdfShader;
911 }
912 
Make(SkPDFDocument * doc,SkShader * shader,const SkMatrix & canvasTransform,const SkIRect & bbox)913 SkPDFIndirectReference SkPDFGradientShader::Make(SkPDFDocument* doc,
914                                              SkShader* shader,
915                                              const SkMatrix& canvasTransform,
916                                              const SkIRect& bbox) {
917     SkASSERT(shader);
918     SkASSERT(SkShader::kNone_GradientType != shader->asAGradient(nullptr));
919     SkPDFGradientShader::Key key = make_key(shader, canvasTransform, bbox);
920     bool alpha = gradient_has_alpha(key);
921     return find_pdf_shader(doc, std::move(key), alpha);
922 }
923