blob: 3f383e5de18c456b30cd97bd8ec53dedb47c0f4a [file] [log] [blame]
vandebo@chromium.orgda912d62011-03-08 18:31:02 +00001/*
2 * Copyright (C) 2011 Google Inc.
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#include "SkPDFShader.h"
18
19#include "SkCanvas.h"
20#include "SkPDFCatalog.h"
21#include "SkPDFDevice.h"
22#include "SkPDFTypes.h"
23#include "SkPDFUtils.h"
24#include "SkScalar.h"
25#include "SkStream.h"
twiz@google.com316338a2011-03-09 23:14:04 +000026#include "SkTemplates.h"
vandebo@chromium.orgda912d62011-03-08 18:31:02 +000027#include "SkThread.h"
28#include "SkTypes.h"
29
30static void transformBBox(const SkMatrix& matrix, SkRect* bbox) {
31 SkMatrix inverse;
32 inverse.reset();
33 matrix.invert(&inverse);
34 inverse.mapRect(bbox);
35}
36
37static void unitToPointsMatrix(const SkPoint pts[2], SkMatrix* matrix) {
38 SkVector vec = pts[1] - pts[0];
39 SkScalar mag = vec.length();
40 SkScalar inv = mag ? SkScalarInvert(mag) : 0;
41
42 vec.scale(inv);
43 matrix->setSinCos(vec.fY, vec.fX);
44 matrix->preTranslate(pts[0].fX, pts[0].fY);
45 matrix->preScale(mag, mag);
46}
47
48/* Assumes t + startOffset is on the stack and does a linear interpolation on t
49 between startOffset and endOffset from prevColor to curColor (for each color
50 component), leaving the result in component order on the stack.
51 @param range endOffset - startOffset
52 @param curColor[components] The current color components.
53 @param prevColor[components] The previous color components.
54 @param result The result ps function.
55 */
56static void interpolateColorCode(SkScalar range, SkScalar* curColor,
57 SkScalar* prevColor, int components,
58 SkString* result) {
59 // Figure out how to scale each color component.
twiz@google.com316338a2011-03-09 23:14:04 +000060 SkAutoSTMalloc<4, SkScalar> multiplierAlloc(components);
61 SkScalar *multiplier = multiplierAlloc.get();
vandebo@chromium.orgda912d62011-03-08 18:31:02 +000062 for (int i = 0; i < components; i++) {
63 multiplier[i] = SkScalarDiv(curColor[i] - prevColor[i], range);
64 }
65
66 // Calculate when we no longer need to keep a copy of the input parameter t.
67 // If the last component to use t is i, then dupInput[0..i - 1] = true
68 // and dupInput[i .. components] = false.
twiz@google.com316338a2011-03-09 23:14:04 +000069 SkAutoSTMalloc<4, bool> dupInputAlloc(components);
70 bool *dupInput = dupInputAlloc.get();
vandebo@chromium.orgda912d62011-03-08 18:31:02 +000071 dupInput[components - 1] = false;
72 for (int i = components - 2; i >= 0; i--) {
73 dupInput[i] = dupInput[i + 1] || multiplier[i + 1] != 0;
74 }
75
76 if (!dupInput[0] && multiplier[0] == 0) {
77 result->append("pop ");
78 }
79
80 for (int i = 0; i < components; i++) {
81 // If the next components needs t, make a copy.
82 if (dupInput[i]) {
83 result->append("dup ");
84 }
85
86 if (multiplier[i] == 0) {
87 result->appendScalar(prevColor[i]);
88 result->append(" ");
89 } else {
90 if (multiplier[i] != 1) {
91 result->appendScalar(multiplier[i]);
92 result->append(" mul ");
93 }
94 if (prevColor[i] != 0) {
95 result->appendScalar(prevColor[i]);
96 result->append(" add ");
97 }
98 }
99
100 if (dupInput[i]) {
101 result->append("exch\n");
102 }
103 }
104}
105
106/* Generate Type 4 function code to map t=[0,1) to the passed gradient,
107 clamping at the edges of the range. The generated code will be of the form:
108 if (t < 0) {
109 return colorData[0][r,g,b];
110 } else {
111 if (t < info.fColorOffsets[1]) {
112 return linearinterpolation(colorData[0][r,g,b],
113 colorData[1][r,g,b]);
114 } else {
115 if (t < info.fColorOffsets[2]) {
116 return linearinterpolation(colorData[1][r,g,b],
117 colorData[2][r,g,b]);
118 } else {
119
120 ... } else {
121 return colorData[info.fColorCount - 1][r,g,b];
122 }
123 ...
124 }
125 }
126 */
127static void gradientFunctionCode(const SkShader::GradientInfo& info,
128 SkString* result) {
129 /* We want to linearly interpolate from the previous color to the next.
130 Scale the colors from 0..255 to 0..1 and determine the multipliers
131 for interpolation.
132 C{r,g,b}(t, section) = t - offset_(section-1) + t * Multiplier{r,g,b}.
133 */
134 static const int kColorComponents = 3;
twiz@google.com316338a2011-03-09 23:14:04 +0000135 typedef SkScalar ColorTuple[kColorComponents];
136 SkAutoSTMalloc<4, ColorTuple> colorDataAlloc(info.fColorCount);
137 ColorTuple *colorData = colorDataAlloc.get();
vandebo@chromium.orgda912d62011-03-08 18:31:02 +0000138 const SkScalar scale = SkScalarInvert(SkIntToScalar(255));
139 for (int i = 0; i < info.fColorCount; i++) {
140 colorData[i][0] = SkScalarMul(SkColorGetR(info.fColors[i]), scale);
141 colorData[i][1] = SkScalarMul(SkColorGetG(info.fColors[i]), scale);
142 colorData[i][2] = SkScalarMul(SkColorGetB(info.fColors[i]), scale);
143 }
144
145 // Clamp the initial color.
146 result->append("dup 0 le {pop ");
147 result->appendScalar(colorData[0][0]);
148 result->append(" ");
149 result->appendScalar(colorData[0][1]);
150 result->append(" ");
151 result->appendScalar(colorData[0][2]);
152 result->append(" }\n");
153
154 // The gradient colors.
155 for (int i = 1 ; i < info.fColorCount; i++) {
156 result->append("{dup ");
157 result->appendScalar(info.fColorOffsets[i]);
158 result->append(" le {");
159 if (info.fColorOffsets[i - 1] != 0) {
160 result->appendScalar(info.fColorOffsets[i - 1]);
161 result->append(" sub\n");
162 }
163
164 interpolateColorCode(info.fColorOffsets[i] - info.fColorOffsets[i - 1],
165 colorData[i], colorData[i - 1], kColorComponents,
166 result);
167 result->append("}\n");
168 }
169
170 // Clamp the final color.
171 result->append("{pop ");
172 result->appendScalar(colorData[info.fColorCount - 1][0]);
173 result->append(" ");
174 result->appendScalar(colorData[info.fColorCount - 1][1]);
175 result->append(" ");
176 result->appendScalar(colorData[info.fColorCount - 1][2]);
177
178 for (int i = 0 ; i < info.fColorCount; i++) {
179 result->append("} ifelse\n");
180 }
181}
182
183/* Map a value of t on the stack into [0, 1) for Repeat or Mirror tile mode. */
184static void tileModeCode(SkShader::TileMode mode, SkString* result) {
185 if (mode == SkShader::kRepeat_TileMode) {
186 result->append("dup truncate sub\n"); // Get the fractional part.
187 result->append("dup 0 le {1 add} if\n"); // Map (-1,0) => (0,1)
188 return;
189 }
190
191 if (mode == SkShader::kMirror_TileMode) {
192 // Map t mod 2 into [0, 1, 1, 0].
193 // Code Stack
194 result->append("abs " // Map negative to positive.
195 "dup " // t.s t.s
196 "truncate " // t.s t
197 "dup " // t.s t t
198 "cvi " // t.s t T
199 "2 mod " // t.s t (i mod 2)
200 "1 eq " // t.s t true|false
201 "3 1 roll " // true|false t.s t
202 "sub " // true|false 0.s
203 "exch " // 0.s true|false
204 "{1 exch sub} if\n"); // 1 - 0.s|0.s
205 }
206}
207
208static SkString linearCode(const SkShader::GradientInfo& info) {
209 SkString function("{pop\n"); // Just ditch the y value.
210 tileModeCode(info.fTileMode, &function);
211 gradientFunctionCode(info, &function);
212 function.append("}");
213 return function;
214}
215
216static SkString radialCode(const SkShader::GradientInfo& info) {
217 SkString function("{");
218 // Find the distance from the origin.
219 function.append("dup " // x y y
220 "mul " // x y^2
221 "exch " // y^2 x
222 "dup " // y^2 x x
223 "mul " // y^2 x^2
224 "add " // y^2+x^2
225 "sqrt\n"); // sqrt(y^2+x^2)
226
227 tileModeCode(info.fTileMode, &function);
228 gradientFunctionCode(info, &function);
229 function.append("}");
230 return function;
231}
232
233/* The math here is all based on the description in Two_Point_Radial_Gradient,
234 with one simplification, the coordinate space has been scaled so that
235 Dr = 1. This means we don't need to scale the entire equation by 1/Dr^2.
236 */
237static SkString twoPointRadialCode(const SkShader::GradientInfo& info) {
238 SkScalar dx = info.fPoint[0].fX - info.fPoint[1].fX;
239 SkScalar dy = info.fPoint[0].fY - info.fPoint[1].fY;
240 SkScalar sr = info.fRadius[0];
241 SkScalar a = SkScalarMul(dx, dx) + SkScalarMul(dy, dy) - SK_Scalar1;
242 bool posRoot = info.fRadius[1] > info.fRadius[0];
243
244 // We start with a stack of (x y), copy it and then consume one copy in
245 // order to calculate b and the other to calculate c.
246 SkString function("{");
247 function.append("2 copy ");
248
249 // Calculate -b and b^2.
250 function.appendScalar(dy);
251 function.append(" mul exch ");
252 function.appendScalar(dx);
253 function.append(" mul add ");
254 function.appendScalar(sr);
255 function.append(" sub 2 mul neg dup dup mul\n");
256
257 // Calculate c
258 function.append("4 2 roll dup mul exch dup mul add ");
259 function.appendScalar(SkScalarMul(sr, sr));
260 function.append(" sub\n");
261
262 // Calculate the determinate
263 function.appendScalar(SkScalarMul(SkIntToScalar(4), a));
264 function.append(" mul sub abs sqrt\n");
265
266 // And then the final value of t.
267 if (posRoot) {
268 function.append("sub ");
269 } else {
270 function.append("add ");
271 }
272 function.appendScalar(SkScalarMul(SkIntToScalar(2), a));
273 function.append(" div\n");
274
275 tileModeCode(info.fTileMode, &function);
276 gradientFunctionCode(info, &function);
277 function.append("}");
278 return function;
279}
280
281static SkString sweepCode(const SkShader::GradientInfo& info) {
282 SkString function("{exch atan 360 div\n");
283 tileModeCode(info.fTileMode, &function);
284 gradientFunctionCode(info, &function);
285 function.append("}");
286 return function;
287}
288
289SkPDFShader::~SkPDFShader() {
290 SkAutoMutexAcquire lock(canonicalShadersMutex());
291 ShaderCanonicalEntry entry(this, fState.get());
292 int index = canonicalShaders().find(entry);
293 SkASSERT(index >= 0);
294 canonicalShaders().removeShuffle(index);
295 fResources.unrefAll();
296}
297
298void SkPDFShader::emitObject(SkWStream* stream, SkPDFCatalog* catalog,
299 bool indirect) {
300 if (indirect)
301 return emitIndirectObject(stream, catalog);
302
303 fContent->emitObject(stream, catalog, indirect);
304}
305
306size_t SkPDFShader::getOutputSize(SkPDFCatalog* catalog, bool indirect) {
307 if (indirect)
308 return getIndirectOutputSize(catalog);
309
310 return fContent->getOutputSize(catalog, indirect);
311}
312
313void SkPDFShader::getResources(SkTDArray<SkPDFObject*>* resourceList) {
314 resourceList->setReserve(resourceList->count() + fResources.count());
315 for (int i = 0; i < fResources.count(); i++) {
316 resourceList->push(fResources[i]);
317 fResources[i]->ref();
318 }
319}
320
321// static
322SkPDFShader* SkPDFShader::getPDFShader(const SkShader& shader,
323 const SkMatrix& matrix,
324 const SkIRect& surfaceBBox) {
325 SkRefPtr<SkPDFShader> pdfShader;
326 SkAutoMutexAcquire lock(canonicalShadersMutex());
327 SkAutoTDelete<State> shaderState(new State(shader, matrix, surfaceBBox));
328
329 ShaderCanonicalEntry entry(NULL, shaderState.get());
330 int index = canonicalShaders().find(entry);
331 if (index >= 0) {
332 SkPDFShader* result = canonicalShaders()[index].fPDFShader;
333 result->ref();
334 return result;
335 }
336 // The PDFShader takes ownership of the shaderSate.
337 pdfShader = new SkPDFShader(shaderState.detach());
338 // Check for a valid shader.
339 if (pdfShader->fContent.get() == NULL) {
340 pdfShader->unref();
341 return NULL;
342 }
343 entry.fPDFShader = pdfShader.get();
344 canonicalShaders().push(entry);
345 return pdfShader.get(); // return the reference that came from new.
346}
347
348// static
349SkTDArray<SkPDFShader::ShaderCanonicalEntry>& SkPDFShader::canonicalShaders() {
350 // This initialization is only thread safe with gcc.
351 static SkTDArray<ShaderCanonicalEntry> gCanonicalShaders;
352 return gCanonicalShaders;
353}
354
355// static
356SkMutex& SkPDFShader::canonicalShadersMutex() {
357 // This initialization is only thread safe with gcc.
358 static SkMutex gCanonicalShadersMutex;
359 return gCanonicalShadersMutex;
360}
361
362// static
363SkPDFObject* SkPDFShader::rangeObject() {
364 // This initialization is only thread safe with gcc.
365 static SkPDFArray* range = NULL;
366 // This method is only used with canonicalShadersMutex, so it's safe to
367 // populate domain.
368 if (range == NULL) {
369 range = new SkPDFArray;
370 range->reserve(6);
371 range->append(new SkPDFInt(0))->unref();
372 range->append(new SkPDFInt(1))->unref();
373 range->append(new SkPDFInt(0))->unref();
374 range->append(new SkPDFInt(1))->unref();
375 range->append(new SkPDFInt(0))->unref();
376 range->append(new SkPDFInt(1))->unref();
377 }
378 return range;
379}
380
381SkPDFShader::SkPDFShader(State* state) : fState(state) {
382 if (fState.get()->fType == SkShader::kNone_GradientType) {
383 doImageShader();
384 } else {
385 doFunctionShader();
386 }
387}
388
389void SkPDFShader::doFunctionShader() {
390 SkString (*codeFunction)(const SkShader::GradientInfo& info) = NULL;
391 SkPoint transformPoints[2];
392
393 // Depending on the type of the gradient, we want to transform the
394 // coordinate space in different ways.
395 const SkShader::GradientInfo* info = &fState.get()->fInfo;
396 transformPoints[0] = info->fPoint[0];
397 transformPoints[1] = info->fPoint[1];
398 switch (fState.get()->fType) {
399 case SkShader::kLinear_GradientType:
400 codeFunction = &linearCode;
401 break;
402 case SkShader::kRadial_GradientType:
403 transformPoints[1] = transformPoints[0];
404 transformPoints[1].fX += info->fRadius[0];
405 codeFunction = &radialCode;
406 break;
407 case SkShader::kRadial2_GradientType: {
408 // Bail out if the radii are the same. Not setting fContent will
409 // cause the higher level code to detect the resulting object
410 // as invalid.
411 if (info->fRadius[0] == info->fRadius[1]) {
412 return;
413 }
414 transformPoints[1] = transformPoints[0];
415 SkScalar dr = info->fRadius[1] - info->fRadius[0];
416 transformPoints[1].fX += dr;
417 codeFunction = &twoPointRadialCode;
418 break;
419 }
420 case SkShader::kSweep_GradientType:
421 transformPoints[1] = transformPoints[0];
422 transformPoints[1].fX += 1;
423 codeFunction = &sweepCode;
424 break;
425 case SkShader::kColor_GradientType:
426 case SkShader::kNone_GradientType:
427 SkASSERT(false);
428 return;
429 }
430
431 // Move any scaling (assuming a unit gradient) or translation
432 // (and rotation for linear gradient), of the final gradient from
433 // info->fPoints to the matrix (updating bbox appropriately). Now
434 // the gradient can be drawn on on the unit segment.
435 SkMatrix mapperMatrix;
436 unitToPointsMatrix(transformPoints, &mapperMatrix);
437 SkMatrix finalMatrix = fState.get()->fCanvasTransform;
438 finalMatrix.preConcat(mapperMatrix);
439 finalMatrix.preConcat(fState.get()->fShaderTransform);
440 SkRect bbox;
441 bbox.set(fState.get()->fBBox);
442 transformBBox(finalMatrix, &bbox);
443
444 SkRefPtr<SkPDFArray> domain = new SkPDFArray;
445 domain->unref(); // SkRefPtr and new both took a reference.
446 domain->reserve(4);
447 domain->append(new SkPDFScalar(bbox.fLeft))->unref();
448 domain->append(new SkPDFScalar(bbox.fRight))->unref();
449 domain->append(new SkPDFScalar(bbox.fTop))->unref();
450 domain->append(new SkPDFScalar(bbox.fBottom))->unref();
451
452 SkString functionCode;
453 // The two point radial gradient further references fState.get()->fInfo
454 // in translating from x, y coordinates to the t parameter. So, we have
455 // to transform the points and radii according to the calculated matrix.
456 if (fState.get()->fType == SkShader::kRadial2_GradientType) {
457 SkShader::GradientInfo twoPointRadialInfo = *info;
458 SkMatrix inverseMapperMatrix;
459 mapperMatrix.invert(&inverseMapperMatrix);
460 inverseMapperMatrix.mapPoints(twoPointRadialInfo.fPoint, 2);
461 twoPointRadialInfo.fRadius[0] =
462 inverseMapperMatrix.mapRadius(info->fRadius[0]);
463 twoPointRadialInfo.fRadius[1] =
464 inverseMapperMatrix.mapRadius(info->fRadius[1]);
465 functionCode = codeFunction(twoPointRadialInfo);
466 } else {
467 functionCode = codeFunction(*info);
468 }
469
470 SkRefPtr<SkPDFStream> function = makePSFunction(functionCode, domain.get());
471 // Pass one reference to fResources, SkRefPtr and new both took a reference.
472 fResources.push(function.get());
473
474 SkRefPtr<SkPDFDict> pdfShader = new SkPDFDict;
475 pdfShader->unref(); // SkRefPtr and new both took a reference.
476 pdfShader->insert("ShadingType", new SkPDFInt(1))->unref();
477 pdfShader->insert("ColorSpace", new SkPDFName("DeviceRGB"))->unref();
478 pdfShader->insert("Domain", domain.get());
479 pdfShader->insert("Function", new SkPDFObjRef(function.get()))->unref();
480
481 fContent = new SkPDFDict("Pattern");
482 fContent->unref(); // SkRefPtr and new both took a reference.
483 fContent->insert("PatternType", new SkPDFInt(2))->unref();
484 fContent->insert("Matrix", SkPDFUtils::MatrixToArray(finalMatrix))->unref();
485 fContent->insert("Shading", pdfShader.get());
486}
487
488// SkShader* shader, SkMatrix matrix, const SkRect& surfaceBBox
489void SkPDFShader::doImageShader() {
490 fState.get()->fImage.lockPixels();
491
492 SkMatrix finalMatrix = fState.get()->fCanvasTransform;
493 finalMatrix.preConcat(fState.get()->fShaderTransform);
494 SkRect surfaceBBox;
495 surfaceBBox.set(fState.get()->fBBox);
496 transformBBox(finalMatrix, &surfaceBBox);
497
vandebo@chromium.org75f97e42011-04-11 23:24:18 +0000498 SkMatrix unflip;
499 unflip.setTranslate(0, surfaceBBox.fBottom);
500 unflip.preScale(1, -1);
501 SkPDFDevice pattern(surfaceBBox.fRight, surfaceBBox.fBottom, unflip);
vandebo@chromium.orgda912d62011-03-08 18:31:02 +0000502 SkCanvas canvas(&pattern);
503 canvas.clipRect(surfaceBBox, SkRegion::kReplace_Op);
504
505 const SkBitmap* image = &fState.get()->fImage;
506 int width = image->width();
507 int height = image->height();
508 SkShader::TileMode tileModes[2];
509 tileModes[0] = fState.get()->fImageTileModes[0];
510 tileModes[1] = fState.get()->fImageTileModes[1];
511
512 canvas.drawBitmap(*image, 0, 0);
513 SkRect patternBBox = SkRect::MakeWH(width, height);
514
515 // Tiling is implied. First we handle mirroring.
516 if (tileModes[0] == SkShader::kMirror_TileMode) {
517 SkMatrix xMirror;
518 xMirror.setScale(-1, 1);
519 xMirror.postTranslate(2 * width, 0);
520 canvas.drawBitmapMatrix(*image, xMirror);
521 patternBBox.fRight += width;
522 }
523 if (tileModes[1] == SkShader::kMirror_TileMode) {
524 SkMatrix yMirror;
525 yMirror.setScale(1, -1);
526 yMirror.postTranslate(0, 2 * height);
527 canvas.drawBitmapMatrix(*image, yMirror);
528 patternBBox.fBottom += height;
529 }
530 if (tileModes[0] == SkShader::kMirror_TileMode &&
531 tileModes[1] == SkShader::kMirror_TileMode) {
532 SkMatrix mirror;
533 mirror.setScale(-1, -1);
534 mirror.postTranslate(2 * width, 2 * height);
535 canvas.drawBitmapMatrix(*image, mirror);
536 }
537
538 // Then handle Clamping, which requires expanding the pattern canvas to
539 // cover the entire surfaceBBox.
540
541 // If both x and y are in clamp mode, we start by filling in the corners.
542 // (Which are just a rectangles of the corner colors.)
543 if (tileModes[0] == SkShader::kClamp_TileMode &&
544 tileModes[1] == SkShader::kClamp_TileMode) {
545 SkPaint paint;
546 SkRect rect;
547 rect = SkRect::MakeLTRB(surfaceBBox.fLeft, surfaceBBox.fTop, 0, 0);
548 if (!rect.isEmpty()) {
549 paint.setColor(image->getColor(0, 0));
550 canvas.drawRect(rect, paint);
551 }
552
553 rect = SkRect::MakeLTRB(width, surfaceBBox.fTop, surfaceBBox.fRight, 0);
554 if (!rect.isEmpty()) {
555 paint.setColor(image->getColor(width - 1, 0));
556 canvas.drawRect(rect, paint);
557 }
558
559 rect = SkRect::MakeLTRB(width, height, surfaceBBox.fRight,
560 surfaceBBox.fBottom);
561 if (!rect.isEmpty()) {
562 paint.setColor(image->getColor(width - 1, height - 1));
563 canvas.drawRect(rect, paint);
564 }
565
566 rect = SkRect::MakeLTRB(surfaceBBox.fLeft, height, 0,
567 surfaceBBox.fBottom);
568 if (!rect.isEmpty()) {
569 paint.setColor(image->getColor(0, height - 1));
570 canvas.drawRect(rect, paint);
571 }
572 }
573
574 // Then expand the left, right, top, then bottom.
575 if (tileModes[0] == SkShader::kClamp_TileMode) {
576 SkIRect subset = SkIRect::MakeXYWH(0, 0, 1, height);
577 if (surfaceBBox.fLeft < 0) {
578 SkBitmap left;
579 SkAssertResult(image->extractSubset(&left, subset));
580
581 SkMatrix leftMatrix;
582 leftMatrix.setScale(-surfaceBBox.fLeft, 1);
583 leftMatrix.postTranslate(surfaceBBox.fLeft, 0);
584 canvas.drawBitmapMatrix(left, leftMatrix);
585
586 if (tileModes[1] == SkShader::kMirror_TileMode) {
587 leftMatrix.postScale(1, -1);
588 leftMatrix.postTranslate(0, 2 * height);
589 canvas.drawBitmapMatrix(left, leftMatrix);
590 }
591 patternBBox.fLeft = surfaceBBox.fLeft;
592 }
593
594 if (surfaceBBox.fRight > width) {
595 SkBitmap right;
596 subset.offset(width - 1, 0);
597 SkAssertResult(image->extractSubset(&right, subset));
598
599 SkMatrix rightMatrix;
600 rightMatrix.setScale(surfaceBBox.fRight - width, 1);
601 rightMatrix.postTranslate(width, 0);
602 canvas.drawBitmapMatrix(right, rightMatrix);
603
604 if (tileModes[1] == SkShader::kMirror_TileMode) {
605 rightMatrix.postScale(1, -1);
606 rightMatrix.postTranslate(0, 2 * height);
607 canvas.drawBitmapMatrix(right, rightMatrix);
608 }
609 patternBBox.fRight = surfaceBBox.fRight;
610 }
611 }
612
613 if (tileModes[1] == SkShader::kClamp_TileMode) {
614 SkIRect subset = SkIRect::MakeXYWH(0, 0, width, 1);
615 if (surfaceBBox.fTop < 0) {
616 SkBitmap top;
617 SkAssertResult(image->extractSubset(&top, subset));
618
619 SkMatrix topMatrix;
620 topMatrix.setScale(1, -surfaceBBox.fTop);
621 topMatrix.postTranslate(0, surfaceBBox.fTop);
622 canvas.drawBitmapMatrix(top, topMatrix);
623
624 if (tileModes[0] == SkShader::kMirror_TileMode) {
625 topMatrix.postScale(-1, 1);
626 topMatrix.postTranslate(2 * width, 0);
627 canvas.drawBitmapMatrix(top, topMatrix);
628 }
629 patternBBox.fTop = surfaceBBox.fTop;
630 }
631
632 if (surfaceBBox.fBottom > height) {
633 SkBitmap bottom;
634 subset.offset(0, height - 1);
635 SkAssertResult(image->extractSubset(&bottom, subset));
636
637 SkMatrix bottomMatrix;
638 bottomMatrix.setScale(1, surfaceBBox.fBottom - height);
639 bottomMatrix.postTranslate(0, height);
640 canvas.drawBitmapMatrix(bottom, bottomMatrix);
641
642 if (tileModes[0] == SkShader::kMirror_TileMode) {
643 bottomMatrix.postScale(-1, 1);
644 bottomMatrix.postTranslate(2 * width, 0);
645 canvas.drawBitmapMatrix(bottom, bottomMatrix);
646 }
647 patternBBox.fBottom = surfaceBBox.fBottom;
648 }
649 }
650
651 SkRefPtr<SkPDFArray> patternBBoxArray = new SkPDFArray;
652 patternBBoxArray->unref(); // SkRefPtr and new both took a reference.
653 patternBBoxArray->reserve(4);
654 patternBBoxArray->append(new SkPDFInt(patternBBox.fLeft))->unref();
655 patternBBoxArray->append(new SkPDFInt(patternBBox.fTop))->unref();
656 patternBBoxArray->append(new SkPDFInt(patternBBox.fRight))->unref();
657 patternBBoxArray->append(new SkPDFInt(patternBBox.fBottom))->unref();
658
659 // Put the canvas into the pattern stream (fContent).
660 SkRefPtr<SkStream> content = pattern.content();
661 content->unref(); // SkRefPtr and content() both took a reference.
662 pattern.getResources(&fResources);
663
664 fContent = new SkPDFStream(content.get());
665 fContent->unref(); // SkRefPtr and new both took a reference.
666 fContent->insert("Type", new SkPDFName("Pattern"))->unref();
667 fContent->insert("PatternType", new SkPDFInt(1))->unref();
668 fContent->insert("PaintType", new SkPDFInt(1))->unref();
669 fContent->insert("TilingType", new SkPDFInt(1))->unref();
670 fContent->insert("BBox", patternBBoxArray.get());
671 fContent->insert("XStep", new SkPDFInt(patternBBox.width()))->unref();
672 fContent->insert("YStep", new SkPDFInt(patternBBox.height()))->unref();
673 fContent->insert("Resources", pattern.getResourceDict().get());
674 fContent->insert("Matrix", SkPDFUtils::MatrixToArray(finalMatrix))->unref();
675
676 fState.get()->fImage.unlockPixels();
677}
678
679SkPDFStream* SkPDFShader::makePSFunction(const SkString& psCode,
680 SkPDFArray* domain) {
681 SkRefPtr<SkMemoryStream> funcStream =
682 new SkMemoryStream(psCode.c_str(), psCode.size(), true);
683 funcStream->unref(); // SkRefPtr and new both took a reference.
684
685 SkPDFStream* result = new SkPDFStream(funcStream.get());
686 result->insert("FunctionType", new SkPDFInt(4))->unref();
687 result->insert("Domain", domain);
688 result->insert("Range", rangeObject());
689 return result;
690}
691
692bool SkPDFShader::State::operator==(const SkPDFShader::State& b) const {
693 if (fType != b.fType ||
694 fCanvasTransform != b.fCanvasTransform ||
695 fShaderTransform != b.fShaderTransform ||
696 fBBox != b.fBBox) {
697 return false;
698 }
699
700 if (fType == SkShader::kNone_GradientType) {
701 if (fPixelGeneration != b.fPixelGeneration ||
702 fPixelGeneration == 0 ||
703 fImageTileModes[0] != b.fImageTileModes[0] ||
704 fImageTileModes[1] != b.fImageTileModes[1]) {
705 return false;
706 }
707 } else {
708 if (fInfo.fColorCount != b.fInfo.fColorCount ||
709 memcmp(fInfo.fColors, b.fInfo.fColors,
710 sizeof(SkColor) * fInfo.fColorCount) != 0 ||
711 memcmp(fInfo.fColorOffsets, b.fInfo.fColorOffsets,
712 sizeof(SkScalar) * fInfo.fColorCount) != 0 ||
713 fInfo.fPoint[0] != b.fInfo.fPoint[0] ||
714 fInfo.fTileMode != b.fInfo.fTileMode) {
715 return false;
716 }
717
718 switch (fType) {
719 case SkShader::kLinear_GradientType:
720 if (fInfo.fPoint[1] != b.fInfo.fPoint[1]) {
721 return false;
722 }
723 break;
724 case SkShader::kRadial_GradientType:
725 if (fInfo.fRadius[0] != b.fInfo.fRadius[0]) {
726 return false;
727 }
728 break;
729 case SkShader::kRadial2_GradientType:
730 if (fInfo.fPoint[1] != b.fInfo.fPoint[1] ||
731 fInfo.fRadius[0] != b.fInfo.fRadius[0] ||
732 fInfo.fRadius[1] != b.fInfo.fRadius[1]) {
733 return false;
734 }
735 break;
736 case SkShader::kSweep_GradientType:
737 case SkShader::kNone_GradientType:
738 case SkShader::kColor_GradientType:
739 break;
740 }
741 }
742 return true;
743}
744
745SkPDFShader::State::State(const SkShader& shader,
746 const SkMatrix& canvasTransform, const SkIRect& bbox)
747 : fCanvasTransform(canvasTransform),
748 fBBox(bbox) {
749
750 fInfo.fColorCount = 0;
751 fInfo.fColors = NULL;
752 fInfo.fColorOffsets = NULL;
753 shader.getLocalMatrix(&fShaderTransform);
754
755 fType = shader.asAGradient(&fInfo);
756
757 if (fType == SkShader::kNone_GradientType) {
758 SkShader::BitmapType bitmapType;
759 SkMatrix matrix;
760 bitmapType = shader.asABitmap(&fImage, &matrix, fImageTileModes, NULL);
761 if (bitmapType != SkShader::kDefault_BitmapType) {
762 fImage.reset();
763 return;
764 }
765 SkASSERT(matrix.isIdentity());
766 fPixelGeneration = fImage.getGenerationID();
767 } else {
768 fColorData.set(sk_malloc_throw(
769 fInfo.fColorCount * (sizeof(SkColor) + sizeof(SkScalar))));
770 fInfo.fColors = (SkColor*)fColorData.get();
771 fInfo.fColorOffsets = (SkScalar*)(fInfo.fColors + fInfo.fColorCount);
772 shader.asAGradient(&fInfo);
773 }
774}