blob: c833c5d77dd17636620da01a5960e681e14c1c12 [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
498 SkPDFDevice pattern(surfaceBBox.fRight, surfaceBBox.fBottom,
499 SkPDFDevice::kNoFlip_OriginTransform);
500 SkCanvas canvas(&pattern);
501 canvas.clipRect(surfaceBBox, SkRegion::kReplace_Op);
502
503 const SkBitmap* image = &fState.get()->fImage;
504 int width = image->width();
505 int height = image->height();
506 SkShader::TileMode tileModes[2];
507 tileModes[0] = fState.get()->fImageTileModes[0];
508 tileModes[1] = fState.get()->fImageTileModes[1];
509
510 canvas.drawBitmap(*image, 0, 0);
511 SkRect patternBBox = SkRect::MakeWH(width, height);
512
513 // Tiling is implied. First we handle mirroring.
514 if (tileModes[0] == SkShader::kMirror_TileMode) {
515 SkMatrix xMirror;
516 xMirror.setScale(-1, 1);
517 xMirror.postTranslate(2 * width, 0);
518 canvas.drawBitmapMatrix(*image, xMirror);
519 patternBBox.fRight += width;
520 }
521 if (tileModes[1] == SkShader::kMirror_TileMode) {
522 SkMatrix yMirror;
523 yMirror.setScale(1, -1);
524 yMirror.postTranslate(0, 2 * height);
525 canvas.drawBitmapMatrix(*image, yMirror);
526 patternBBox.fBottom += height;
527 }
528 if (tileModes[0] == SkShader::kMirror_TileMode &&
529 tileModes[1] == SkShader::kMirror_TileMode) {
530 SkMatrix mirror;
531 mirror.setScale(-1, -1);
532 mirror.postTranslate(2 * width, 2 * height);
533 canvas.drawBitmapMatrix(*image, mirror);
534 }
535
536 // Then handle Clamping, which requires expanding the pattern canvas to
537 // cover the entire surfaceBBox.
538
539 // If both x and y are in clamp mode, we start by filling in the corners.
540 // (Which are just a rectangles of the corner colors.)
541 if (tileModes[0] == SkShader::kClamp_TileMode &&
542 tileModes[1] == SkShader::kClamp_TileMode) {
543 SkPaint paint;
544 SkRect rect;
545 rect = SkRect::MakeLTRB(surfaceBBox.fLeft, surfaceBBox.fTop, 0, 0);
546 if (!rect.isEmpty()) {
547 paint.setColor(image->getColor(0, 0));
548 canvas.drawRect(rect, paint);
549 }
550
551 rect = SkRect::MakeLTRB(width, surfaceBBox.fTop, surfaceBBox.fRight, 0);
552 if (!rect.isEmpty()) {
553 paint.setColor(image->getColor(width - 1, 0));
554 canvas.drawRect(rect, paint);
555 }
556
557 rect = SkRect::MakeLTRB(width, height, surfaceBBox.fRight,
558 surfaceBBox.fBottom);
559 if (!rect.isEmpty()) {
560 paint.setColor(image->getColor(width - 1, height - 1));
561 canvas.drawRect(rect, paint);
562 }
563
564 rect = SkRect::MakeLTRB(surfaceBBox.fLeft, height, 0,
565 surfaceBBox.fBottom);
566 if (!rect.isEmpty()) {
567 paint.setColor(image->getColor(0, height - 1));
568 canvas.drawRect(rect, paint);
569 }
570 }
571
572 // Then expand the left, right, top, then bottom.
573 if (tileModes[0] == SkShader::kClamp_TileMode) {
574 SkIRect subset = SkIRect::MakeXYWH(0, 0, 1, height);
575 if (surfaceBBox.fLeft < 0) {
576 SkBitmap left;
577 SkAssertResult(image->extractSubset(&left, subset));
578
579 SkMatrix leftMatrix;
580 leftMatrix.setScale(-surfaceBBox.fLeft, 1);
581 leftMatrix.postTranslate(surfaceBBox.fLeft, 0);
582 canvas.drawBitmapMatrix(left, leftMatrix);
583
584 if (tileModes[1] == SkShader::kMirror_TileMode) {
585 leftMatrix.postScale(1, -1);
586 leftMatrix.postTranslate(0, 2 * height);
587 canvas.drawBitmapMatrix(left, leftMatrix);
588 }
589 patternBBox.fLeft = surfaceBBox.fLeft;
590 }
591
592 if (surfaceBBox.fRight > width) {
593 SkBitmap right;
594 subset.offset(width - 1, 0);
595 SkAssertResult(image->extractSubset(&right, subset));
596
597 SkMatrix rightMatrix;
598 rightMatrix.setScale(surfaceBBox.fRight - width, 1);
599 rightMatrix.postTranslate(width, 0);
600 canvas.drawBitmapMatrix(right, rightMatrix);
601
602 if (tileModes[1] == SkShader::kMirror_TileMode) {
603 rightMatrix.postScale(1, -1);
604 rightMatrix.postTranslate(0, 2 * height);
605 canvas.drawBitmapMatrix(right, rightMatrix);
606 }
607 patternBBox.fRight = surfaceBBox.fRight;
608 }
609 }
610
611 if (tileModes[1] == SkShader::kClamp_TileMode) {
612 SkIRect subset = SkIRect::MakeXYWH(0, 0, width, 1);
613 if (surfaceBBox.fTop < 0) {
614 SkBitmap top;
615 SkAssertResult(image->extractSubset(&top, subset));
616
617 SkMatrix topMatrix;
618 topMatrix.setScale(1, -surfaceBBox.fTop);
619 topMatrix.postTranslate(0, surfaceBBox.fTop);
620 canvas.drawBitmapMatrix(top, topMatrix);
621
622 if (tileModes[0] == SkShader::kMirror_TileMode) {
623 topMatrix.postScale(-1, 1);
624 topMatrix.postTranslate(2 * width, 0);
625 canvas.drawBitmapMatrix(top, topMatrix);
626 }
627 patternBBox.fTop = surfaceBBox.fTop;
628 }
629
630 if (surfaceBBox.fBottom > height) {
631 SkBitmap bottom;
632 subset.offset(0, height - 1);
633 SkAssertResult(image->extractSubset(&bottom, subset));
634
635 SkMatrix bottomMatrix;
636 bottomMatrix.setScale(1, surfaceBBox.fBottom - height);
637 bottomMatrix.postTranslate(0, height);
638 canvas.drawBitmapMatrix(bottom, bottomMatrix);
639
640 if (tileModes[0] == SkShader::kMirror_TileMode) {
641 bottomMatrix.postScale(-1, 1);
642 bottomMatrix.postTranslate(2 * width, 0);
643 canvas.drawBitmapMatrix(bottom, bottomMatrix);
644 }
645 patternBBox.fBottom = surfaceBBox.fBottom;
646 }
647 }
648
649 SkRefPtr<SkPDFArray> patternBBoxArray = new SkPDFArray;
650 patternBBoxArray->unref(); // SkRefPtr and new both took a reference.
651 patternBBoxArray->reserve(4);
652 patternBBoxArray->append(new SkPDFInt(patternBBox.fLeft))->unref();
653 patternBBoxArray->append(new SkPDFInt(patternBBox.fTop))->unref();
654 patternBBoxArray->append(new SkPDFInt(patternBBox.fRight))->unref();
655 patternBBoxArray->append(new SkPDFInt(patternBBox.fBottom))->unref();
656
657 // Put the canvas into the pattern stream (fContent).
658 SkRefPtr<SkStream> content = pattern.content();
659 content->unref(); // SkRefPtr and content() both took a reference.
660 pattern.getResources(&fResources);
661
662 fContent = new SkPDFStream(content.get());
663 fContent->unref(); // SkRefPtr and new both took a reference.
664 fContent->insert("Type", new SkPDFName("Pattern"))->unref();
665 fContent->insert("PatternType", new SkPDFInt(1))->unref();
666 fContent->insert("PaintType", new SkPDFInt(1))->unref();
667 fContent->insert("TilingType", new SkPDFInt(1))->unref();
668 fContent->insert("BBox", patternBBoxArray.get());
669 fContent->insert("XStep", new SkPDFInt(patternBBox.width()))->unref();
670 fContent->insert("YStep", new SkPDFInt(patternBBox.height()))->unref();
671 fContent->insert("Resources", pattern.getResourceDict().get());
672 fContent->insert("Matrix", SkPDFUtils::MatrixToArray(finalMatrix))->unref();
673
674 fState.get()->fImage.unlockPixels();
675}
676
677SkPDFStream* SkPDFShader::makePSFunction(const SkString& psCode,
678 SkPDFArray* domain) {
679 SkRefPtr<SkMemoryStream> funcStream =
680 new SkMemoryStream(psCode.c_str(), psCode.size(), true);
681 funcStream->unref(); // SkRefPtr and new both took a reference.
682
683 SkPDFStream* result = new SkPDFStream(funcStream.get());
684 result->insert("FunctionType", new SkPDFInt(4))->unref();
685 result->insert("Domain", domain);
686 result->insert("Range", rangeObject());
687 return result;
688}
689
690bool SkPDFShader::State::operator==(const SkPDFShader::State& b) const {
691 if (fType != b.fType ||
692 fCanvasTransform != b.fCanvasTransform ||
693 fShaderTransform != b.fShaderTransform ||
694 fBBox != b.fBBox) {
695 return false;
696 }
697
698 if (fType == SkShader::kNone_GradientType) {
699 if (fPixelGeneration != b.fPixelGeneration ||
700 fPixelGeneration == 0 ||
701 fImageTileModes[0] != b.fImageTileModes[0] ||
702 fImageTileModes[1] != b.fImageTileModes[1]) {
703 return false;
704 }
705 } else {
706 if (fInfo.fColorCount != b.fInfo.fColorCount ||
707 memcmp(fInfo.fColors, b.fInfo.fColors,
708 sizeof(SkColor) * fInfo.fColorCount) != 0 ||
709 memcmp(fInfo.fColorOffsets, b.fInfo.fColorOffsets,
710 sizeof(SkScalar) * fInfo.fColorCount) != 0 ||
711 fInfo.fPoint[0] != b.fInfo.fPoint[0] ||
712 fInfo.fTileMode != b.fInfo.fTileMode) {
713 return false;
714 }
715
716 switch (fType) {
717 case SkShader::kLinear_GradientType:
718 if (fInfo.fPoint[1] != b.fInfo.fPoint[1]) {
719 return false;
720 }
721 break;
722 case SkShader::kRadial_GradientType:
723 if (fInfo.fRadius[0] != b.fInfo.fRadius[0]) {
724 return false;
725 }
726 break;
727 case SkShader::kRadial2_GradientType:
728 if (fInfo.fPoint[1] != b.fInfo.fPoint[1] ||
729 fInfo.fRadius[0] != b.fInfo.fRadius[0] ||
730 fInfo.fRadius[1] != b.fInfo.fRadius[1]) {
731 return false;
732 }
733 break;
734 case SkShader::kSweep_GradientType:
735 case SkShader::kNone_GradientType:
736 case SkShader::kColor_GradientType:
737 break;
738 }
739 }
740 return true;
741}
742
743SkPDFShader::State::State(const SkShader& shader,
744 const SkMatrix& canvasTransform, const SkIRect& bbox)
745 : fCanvasTransform(canvasTransform),
746 fBBox(bbox) {
747
748 fInfo.fColorCount = 0;
749 fInfo.fColors = NULL;
750 fInfo.fColorOffsets = NULL;
751 shader.getLocalMatrix(&fShaderTransform);
752
753 fType = shader.asAGradient(&fInfo);
754
755 if (fType == SkShader::kNone_GradientType) {
756 SkShader::BitmapType bitmapType;
757 SkMatrix matrix;
758 bitmapType = shader.asABitmap(&fImage, &matrix, fImageTileModes, NULL);
759 if (bitmapType != SkShader::kDefault_BitmapType) {
760 fImage.reset();
761 return;
762 }
763 SkASSERT(matrix.isIdentity());
764 fPixelGeneration = fImage.getGenerationID();
765 } else {
766 fColorData.set(sk_malloc_throw(
767 fInfo.fColorCount * (sizeof(SkColor) + sizeof(SkScalar))));
768 fInfo.fColors = (SkColor*)fColorData.get();
769 fInfo.fColorOffsets = (SkScalar*)(fInfo.fColors + fInfo.fColorCount);
770 shader.asAGradient(&fInfo);
771 }
772}