1 2 /* 3 * Copyright 2011 Google Inc. 4 * 5 * Use of this source code is governed by a BSD-style license that can be 6 * found in the LICENSE file. 7 */ 8 9 10 #include "SkPDFShader.h" 11 12 #include "SkData.h" 13 #include "SkPDFCatalog.h" 14 #include "SkPDFDevice.h" 15 #include "SkPDFFormXObject.h" 16 #include "SkPDFGraphicState.h" 17 #include "SkPDFResourceDict.h" 18 #include "SkPDFUtils.h" 19 #include "SkScalar.h" 20 #include "SkStream.h" 21 #include "SkTemplates.h" 22 #include "SkThread.h" 23 #include "SkTSet.h" 24 #include "SkTypes.h" 25 26 static bool transformBBox(const SkMatrix& matrix, SkRect* bbox) { 27 SkMatrix inverse; 28 if (!matrix.invert(&inverse)) { 29 return false; 30 } 31 inverse.mapRect(bbox); 32 return true; 33 } 34 35 static void unitToPointsMatrix(const SkPoint pts[2], SkMatrix* matrix) { 36 SkVector vec = pts[1] - pts[0]; 37 SkScalar mag = vec.length(); 38 SkScalar inv = mag ? SkScalarInvert(mag) : 0; 39 40 vec.scale(inv); 41 matrix->setSinCos(vec.fY, vec.fX); 42 matrix->preScale(mag, mag); 43 matrix->postTranslate(pts[0].fX, pts[0].fY); 44 } 45 46 /* Assumes t + startOffset is on the stack and does a linear interpolation on t 47 between startOffset and endOffset from prevColor to curColor (for each color 48 component), leaving the result in component order on the stack. It assumes 49 there are always 3 components per color. 50 @param range endOffset - startOffset 51 @param curColor[components] The current color components. 52 @param prevColor[components] The previous color components. 53 @param result The result ps function. 54 */ 55 static void interpolateColorCode(SkScalar range, SkScalar* curColor, 56 SkScalar* prevColor, SkString* result) { 57 static const int kColorComponents = 3; 58 59 // Figure out how to scale each color component. 60 SkScalar multiplier[kColorComponents]; 61 for (int i = 0; i < kColorComponents; i++) { 62 multiplier[i] = SkScalarDiv(curColor[i] - prevColor[i], range); 63 } 64 65 // Calculate when we no longer need to keep a copy of the input parameter t. 66 // If the last component to use t is i, then dupInput[0..i - 1] = true 67 // and dupInput[i .. components] = false. 68 bool dupInput[kColorComponents]; 69 dupInput[kColorComponents - 1] = false; 70 for (int i = kColorComponents - 2; i >= 0; i--) { 71 dupInput[i] = dupInput[i + 1] || multiplier[i + 1] != 0; 72 } 73 74 if (!dupInput[0] && multiplier[0] == 0) { 75 result->append("pop "); 76 } 77 78 for (int i = 0; i < kColorComponents; i++) { 79 // If the next components needs t and this component will consume a 80 // copy, make another copy. 81 if (dupInput[i] && multiplier[i] != 0) { 82 result->append("dup "); 83 } 84 85 if (multiplier[i] == 0) { 86 result->appendScalar(prevColor[i]); 87 result->append(" "); 88 } else { 89 if (multiplier[i] != 1) { 90 result->appendScalar(multiplier[i]); 91 result->append(" mul "); 92 } 93 if (prevColor[i] != 0) { 94 result->appendScalar(prevColor[i]); 95 result->append(" add "); 96 } 97 } 98 99 if (dupInput[i]) { 100 result->append("exch\n"); 101 } 102 } 103 } 104 105 /* Generate Type 4 function code to map t=[0,1) to the passed gradient, 106 clamping at the edges of the range. The generated code will be of the form: 107 if (t < 0) { 108 return colorData[0][r,g,b]; 109 } else { 110 if (t < info.fColorOffsets[1]) { 111 return linearinterpolation(colorData[0][r,g,b], 112 colorData[1][r,g,b]); 113 } else { 114 if (t < info.fColorOffsets[2]) { 115 return linearinterpolation(colorData[1][r,g,b], 116 colorData[2][r,g,b]); 117 } else { 118 119 ... } else { 120 return colorData[info.fColorCount - 1][r,g,b]; 121 } 122 ... 123 } 124 } 125 */ 126 static void gradientFunctionCode(const SkShader::GradientInfo& info, 127 SkString* result) { 128 /* We want to linearly interpolate from the previous color to the next. 129 Scale the colors from 0..255 to 0..1 and determine the multipliers 130 for interpolation. 131 C{r,g,b}(t, section) = t - offset_(section-1) + t * Multiplier{r,g,b}. 132 */ 133 static const int kColorComponents = 3; 134 typedef SkScalar ColorTuple[kColorComponents]; 135 SkAutoSTMalloc<4, ColorTuple> colorDataAlloc(info.fColorCount); 136 ColorTuple *colorData = colorDataAlloc.get(); 137 const SkScalar scale = SkScalarInvert(SkIntToScalar(255)); 138 for (int i = 0; i < info.fColorCount; i++) { 139 colorData[i][0] = SkScalarMul(SkColorGetR(info.fColors[i]), scale); 140 colorData[i][1] = SkScalarMul(SkColorGetG(info.fColors[i]), scale); 141 colorData[i][2] = SkScalarMul(SkColorGetB(info.fColors[i]), scale); 142 } 143 144 // Clamp the initial color. 145 result->append("dup 0 le {pop "); 146 result->appendScalar(colorData[0][0]); 147 result->append(" "); 148 result->appendScalar(colorData[0][1]); 149 result->append(" "); 150 result->appendScalar(colorData[0][2]); 151 result->append(" }\n"); 152 153 // The gradient colors. 154 for (int i = 1 ; i < info.fColorCount; i++) { 155 result->append("{dup "); 156 result->appendScalar(info.fColorOffsets[i]); 157 result->append(" le {"); 158 if (info.fColorOffsets[i - 1] != 0) { 159 result->appendScalar(info.fColorOffsets[i - 1]); 160 result->append(" sub\n"); 161 } 162 163 interpolateColorCode(info.fColorOffsets[i] - info.fColorOffsets[i - 1], 164 colorData[i], colorData[i - 1], result); 165 result->append("}\n"); 166 } 167 168 // Clamp the final color. 169 result->append("{pop "); 170 result->appendScalar(colorData[info.fColorCount - 1][0]); 171 result->append(" "); 172 result->appendScalar(colorData[info.fColorCount - 1][1]); 173 result->append(" "); 174 result->appendScalar(colorData[info.fColorCount - 1][2]); 175 176 for (int i = 0 ; i < info.fColorCount; i++) { 177 result->append("} ifelse\n"); 178 } 179 } 180 181 /* Map a value of t on the stack into [0, 1) for Repeat or Mirror tile mode. */ 182 static void tileModeCode(SkShader::TileMode mode, SkString* result) { 183 if (mode == SkShader::kRepeat_TileMode) { 184 result->append("dup truncate sub\n"); // Get the fractional part. 185 result->append("dup 0 le {1 add} if\n"); // Map (-1,0) => (0,1) 186 return; 187 } 188 189 if (mode == SkShader::kMirror_TileMode) { 190 // Map t mod 2 into [0, 1, 1, 0]. 191 // Code Stack 192 result->append("abs " // Map negative to positive. 193 "dup " // t.s t.s 194 "truncate " // t.s t 195 "dup " // t.s t t 196 "cvi " // t.s t T 197 "2 mod " // t.s t (i mod 2) 198 "1 eq " // t.s t true|false 199 "3 1 roll " // true|false t.s t 200 "sub " // true|false 0.s 201 "exch " // 0.s true|false 202 "{1 exch sub} if\n"); // 1 - 0.s|0.s 203 } 204 } 205 206 /** 207 * Returns PS function code that applies inverse perspective 208 * to a x, y point. 209 * The function assumes that the stack has at least two elements, 210 * and that the top 2 elements are numeric values. 211 * After executing this code on a PS stack, the last 2 elements are updated 212 * while the rest of the stack is preserved intact. 213 * inversePerspectiveMatrix is the inverse perspective matrix. 214 */ 215 static SkString apply_perspective_to_coordinates( 216 const SkMatrix& inversePerspectiveMatrix) { 217 SkString code; 218 if (!inversePerspectiveMatrix.hasPerspective()) { 219 return code; 220 } 221 222 // Perspective matrix should be: 223 // 1 0 0 224 // 0 1 0 225 // p0 p1 p2 226 227 const SkScalar p0 = inversePerspectiveMatrix[SkMatrix::kMPersp0]; 228 const SkScalar p1 = inversePerspectiveMatrix[SkMatrix::kMPersp1]; 229 const SkScalar p2 = inversePerspectiveMatrix[SkMatrix::kMPersp2]; 230 231 // y = y / (p2 + p0 x + p1 y) 232 // x = x / (p2 + p0 x + p1 y) 233 234 // Input on stack: x y 235 code.append(" dup "); // x y y 236 code.appendScalar(p1); // x y y p1 237 code.append(" mul " // x y y*p1 238 " 2 index "); // x y y*p1 x 239 code.appendScalar(p0); // x y y p1 x p0 240 code.append(" mul "); // x y y*p1 x*p0 241 code.appendScalar(p2); // x y y p1 x*p0 p2 242 code.append(" add " // x y y*p1 x*p0+p2 243 "add " // x y y*p1+x*p0+p2 244 "3 1 roll " // y*p1+x*p0+p2 x y 245 "2 index " // z x y y*p1+x*p0+p2 246 "div " // y*p1+x*p0+p2 x y/(y*p1+x*p0+p2) 247 "3 1 roll " // y/(y*p1+x*p0+p2) y*p1+x*p0+p2 x 248 "exch " // y/(y*p1+x*p0+p2) x y*p1+x*p0+p2 249 "div " // y/(y*p1+x*p0+p2) x/(y*p1+x*p0+p2) 250 "exch\n"); // x/(y*p1+x*p0+p2) y/(y*p1+x*p0+p2) 251 return code; 252 } 253 254 static SkString linearCode(const SkShader::GradientInfo& info, 255 const SkMatrix& perspectiveRemover) { 256 SkString function("{"); 257 258 function.append(apply_perspective_to_coordinates(perspectiveRemover)); 259 260 function.append("pop\n"); // Just ditch the y value. 261 tileModeCode(info.fTileMode, &function); 262 gradientFunctionCode(info, &function); 263 function.append("}"); 264 return function; 265 } 266 267 static SkString radialCode(const SkShader::GradientInfo& info, 268 const SkMatrix& perspectiveRemover) { 269 SkString function("{"); 270 271 function.append(apply_perspective_to_coordinates(perspectiveRemover)); 272 273 // Find the distance from the origin. 274 function.append("dup " // x y y 275 "mul " // x y^2 276 "exch " // y^2 x 277 "dup " // y^2 x x 278 "mul " // y^2 x^2 279 "add " // y^2+x^2 280 "sqrt\n"); // sqrt(y^2+x^2) 281 282 tileModeCode(info.fTileMode, &function); 283 gradientFunctionCode(info, &function); 284 function.append("}"); 285 return function; 286 } 287 288 /* The math here is all based on the description in Two_Point_Radial_Gradient, 289 with one simplification, the coordinate space has been scaled so that 290 Dr = 1. This means we don't need to scale the entire equation by 1/Dr^2. 291 */ 292 static SkString twoPointRadialCode(const SkShader::GradientInfo& info, 293 const SkMatrix& perspectiveRemover) { 294 SkScalar dx = info.fPoint[0].fX - info.fPoint[1].fX; 295 SkScalar dy = info.fPoint[0].fY - info.fPoint[1].fY; 296 SkScalar sr = info.fRadius[0]; 297 SkScalar a = SkScalarMul(dx, dx) + SkScalarMul(dy, dy) - SK_Scalar1; 298 bool posRoot = info.fRadius[1] > info.fRadius[0]; 299 300 // We start with a stack of (x y), copy it and then consume one copy in 301 // order to calculate b and the other to calculate c. 302 SkString function("{"); 303 304 function.append(apply_perspective_to_coordinates(perspectiveRemover)); 305 306 function.append("2 copy "); 307 308 // Calculate -b and b^2. 309 function.appendScalar(dy); 310 function.append(" mul exch "); 311 function.appendScalar(dx); 312 function.append(" mul add "); 313 function.appendScalar(sr); 314 function.append(" sub 2 mul neg dup dup mul\n"); 315 316 // Calculate c 317 function.append("4 2 roll dup mul exch dup mul add "); 318 function.appendScalar(SkScalarMul(sr, sr)); 319 function.append(" sub\n"); 320 321 // Calculate the determinate 322 function.appendScalar(SkScalarMul(SkIntToScalar(4), a)); 323 function.append(" mul sub abs sqrt\n"); 324 325 // And then the final value of t. 326 if (posRoot) { 327 function.append("sub "); 328 } else { 329 function.append("add "); 330 } 331 function.appendScalar(SkScalarMul(SkIntToScalar(2), a)); 332 function.append(" div\n"); 333 334 tileModeCode(info.fTileMode, &function); 335 gradientFunctionCode(info, &function); 336 function.append("}"); 337 return function; 338 } 339 340 /* Conical gradient shader, based on the Canvas spec for radial gradients 341 See: http://www.w3.org/TR/2dcontext/#dom-context-2d-createradialgradient 342 */ 343 static SkString twoPointConicalCode(const SkShader::GradientInfo& info, 344 const SkMatrix& perspectiveRemover) { 345 SkScalar dx = info.fPoint[1].fX - info.fPoint[0].fX; 346 SkScalar dy = info.fPoint[1].fY - info.fPoint[0].fY; 347 SkScalar r0 = info.fRadius[0]; 348 SkScalar dr = info.fRadius[1] - info.fRadius[0]; 349 SkScalar a = SkScalarMul(dx, dx) + SkScalarMul(dy, dy) - 350 SkScalarMul(dr, dr); 351 352 // First compute t, if the pixel falls outside the cone, then we'll end 353 // with 'false' on the stack, otherwise we'll push 'true' with t below it 354 355 // We start with a stack of (x y), copy it and then consume one copy in 356 // order to calculate b and the other to calculate c. 357 SkString function("{"); 358 359 function.append(apply_perspective_to_coordinates(perspectiveRemover)); 360 361 function.append("2 copy "); 362 363 // Calculate b and b^2; b = -2 * (y * dy + x * dx + r0 * dr). 364 function.appendScalar(dy); 365 function.append(" mul exch "); 366 function.appendScalar(dx); 367 function.append(" mul add "); 368 function.appendScalar(SkScalarMul(r0, dr)); 369 function.append(" add -2 mul dup dup mul\n"); 370 371 // c = x^2 + y^2 + radius0^2 372 function.append("4 2 roll dup mul exch dup mul add "); 373 function.appendScalar(SkScalarMul(r0, r0)); 374 function.append(" sub dup 4 1 roll\n"); 375 376 // Contents of the stack at this point: c, b, b^2, c 377 378 // if a = 0, then we collapse to a simpler linear case 379 if (a == 0) { 380 381 // t = -c/b 382 function.append("pop pop div neg dup "); 383 384 // compute radius(t) 385 function.appendScalar(dr); 386 function.append(" mul "); 387 function.appendScalar(r0); 388 function.append(" add\n"); 389 390 // if r(t) < 0, then it's outside the cone 391 function.append("0 lt {pop false} {true} ifelse\n"); 392 393 } else { 394 395 // quadratic case: the Canvas spec wants the largest 396 // root t for which radius(t) > 0 397 398 // compute the discriminant (b^2 - 4ac) 399 function.appendScalar(SkScalarMul(SkIntToScalar(4), a)); 400 function.append(" mul sub dup\n"); 401 402 // if d >= 0, proceed 403 function.append("0 ge {\n"); 404 405 // an intermediate value we'll use to compute the roots: 406 // q = -0.5 * (b +/- sqrt(d)) 407 function.append("sqrt exch dup 0 lt {exch -1 mul} if"); 408 function.append(" add -0.5 mul dup\n"); 409 410 // first root = q / a 411 function.appendScalar(a); 412 function.append(" div\n"); 413 414 // second root = c / q 415 function.append("3 1 roll div\n"); 416 417 // put the larger root on top of the stack 418 function.append("2 copy gt {exch} if\n"); 419 420 // compute radius(t) for larger root 421 function.append("dup "); 422 function.appendScalar(dr); 423 function.append(" mul "); 424 function.appendScalar(r0); 425 function.append(" add\n"); 426 427 // if r(t) > 0, we have our t, pop off the smaller root and we're done 428 function.append(" 0 gt {exch pop true}\n"); 429 430 // otherwise, throw out the larger one and try the smaller root 431 function.append("{pop dup\n"); 432 function.appendScalar(dr); 433 function.append(" mul "); 434 function.appendScalar(r0); 435 function.append(" add\n"); 436 437 // if r(t) < 0, push false, otherwise the smaller root is our t 438 function.append("0 le {pop false} {true} ifelse\n"); 439 function.append("} ifelse\n"); 440 441 // d < 0, clear the stack and push false 442 function.append("} {pop pop pop false} ifelse\n"); 443 } 444 445 // if the pixel is in the cone, proceed to compute a color 446 function.append("{"); 447 tileModeCode(info.fTileMode, &function); 448 gradientFunctionCode(info, &function); 449 450 // otherwise, just write black 451 function.append("} {0 0 0} ifelse }"); 452 453 return function; 454 } 455 456 static SkString sweepCode(const SkShader::GradientInfo& info, 457 const SkMatrix& perspectiveRemover) { 458 SkString function("{exch atan 360 div\n"); 459 tileModeCode(info.fTileMode, &function); 460 gradientFunctionCode(info, &function); 461 function.append("}"); 462 return function; 463 } 464 465 class SkPDFShader::State { 466 public: 467 SkShader::GradientType fType; 468 SkShader::GradientInfo fInfo; 469 SkAutoFree fColorData; // This provides storage for arrays in fInfo. 470 SkMatrix fCanvasTransform; 471 SkMatrix fShaderTransform; 472 SkIRect fBBox; 473 474 SkBitmap fImage; 475 uint32_t fPixelGeneration; 476 SkShader::TileMode fImageTileModes[2]; 477 478 State(const SkShader& shader, const SkMatrix& canvasTransform, 479 const SkIRect& bbox); 480 481 bool operator==(const State& b) const; 482 483 SkPDFShader::State* CreateAlphaToLuminosityState() const; 484 SkPDFShader::State* CreateOpaqueState() const; 485 486 bool GradientHasAlpha() const; 487 488 private: 489 State(const State& other); 490 State operator=(const State& rhs); 491 void AllocateGradientInfoStorage(); 492 }; 493 494 class SkPDFFunctionShader : public SkPDFDict, public SkPDFShader { 495 public: 496 explicit SkPDFFunctionShader(SkPDFShader::State* state); 497 virtual ~SkPDFFunctionShader() { 498 if (isValid()) { 499 RemoveShader(this); 500 } 501 fResources.unrefAll(); 502 } 503 504 virtual bool isValid() { return fResources.count() > 0; } 505 506 void getResources(const SkTSet<SkPDFObject*>& knownResourceObjects, 507 SkTSet<SkPDFObject*>* newResourceObjects) { 508 GetResourcesHelper(&fResources, 509 knownResourceObjects, 510 newResourceObjects); 511 } 512 513 private: 514 static SkPDFObject* RangeObject(); 515 516 SkTDArray<SkPDFObject*> fResources; 517 SkAutoTDelete<const SkPDFShader::State> fState; 518 519 SkPDFStream* makePSFunction(const SkString& psCode, SkPDFArray* domain); 520 }; 521 522 /** 523 * A shader for PDF gradients. This encapsulates the function shader 524 * inside a tiling pattern while providing a common pattern interface. 525 * The encapsulation allows the use of a SMask for transparency gradients. 526 */ 527 class SkPDFAlphaFunctionShader : public SkPDFStream, public SkPDFShader { 528 public: 529 explicit SkPDFAlphaFunctionShader(SkPDFShader::State* state); 530 virtual ~SkPDFAlphaFunctionShader() { 531 if (isValid()) { 532 RemoveShader(this); 533 } 534 } 535 536 virtual bool isValid() { 537 return fColorShader.get() != NULL; 538 } 539 540 private: 541 SkAutoTDelete<const SkPDFShader::State> fState; 542 543 SkPDFGraphicState* CreateSMaskGraphicState(); 544 545 void getResources(const SkTSet<SkPDFObject*>& knownResourceObjects, 546 SkTSet<SkPDFObject*>* newResourceObjects) { 547 fResourceDict->getReferencedResources(knownResourceObjects, 548 newResourceObjects, 549 true); 550 } 551 552 SkAutoTUnref<SkPDFObject> fColorShader; 553 SkAutoTUnref<SkPDFResourceDict> fResourceDict; 554 }; 555 556 class SkPDFImageShader : public SkPDFStream, public SkPDFShader { 557 public: 558 explicit SkPDFImageShader(SkPDFShader::State* state); 559 virtual ~SkPDFImageShader() { 560 if (isValid()) { 561 RemoveShader(this); 562 } 563 fResources.unrefAll(); 564 } 565 566 virtual bool isValid() { return size() > 0; } 567 568 void getResources(const SkTSet<SkPDFObject*>& knownResourceObjects, 569 SkTSet<SkPDFObject*>* newResourceObjects) { 570 GetResourcesHelper(&fResources.toArray(), 571 knownResourceObjects, 572 newResourceObjects); 573 } 574 575 private: 576 SkTSet<SkPDFObject*> fResources; 577 SkAutoTDelete<const SkPDFShader::State> fState; 578 }; 579 580 SkPDFShader::SkPDFShader() {} 581 582 // static 583 SkPDFObject* SkPDFShader::GetPDFShaderByState(State* inState) { 584 SkPDFObject* result; 585 586 SkAutoTDelete<State> shaderState(inState); 587 if (shaderState.get()->fType == SkShader::kNone_GradientType && 588 shaderState.get()->fImage.isNull()) { 589 // TODO(vandebo) This drops SKComposeShader on the floor. We could 590 // handle compose shader by pulling things up to a layer, drawing with 591 // the first shader, applying the xfer mode and drawing again with the 592 // second shader, then applying the layer to the original drawing. 593 return NULL; 594 } 595 596 ShaderCanonicalEntry entry(NULL, shaderState.get()); 597 int index = CanonicalShaders().find(entry); 598 if (index >= 0) { 599 result = CanonicalShaders()[index].fPDFShader; 600 result->ref(); 601 return result; 602 } 603 604 bool valid = false; 605 // The PDFShader takes ownership of the shaderSate. 606 if (shaderState.get()->fType == SkShader::kNone_GradientType) { 607 SkPDFImageShader* imageShader = 608 new SkPDFImageShader(shaderState.detach()); 609 valid = imageShader->isValid(); 610 result = imageShader; 611 } else { 612 if (shaderState.get()->GradientHasAlpha()) { 613 SkPDFAlphaFunctionShader* gradientShader = 614 SkNEW_ARGS(SkPDFAlphaFunctionShader, (shaderState.detach())); 615 valid = gradientShader->isValid(); 616 result = gradientShader; 617 } else { 618 SkPDFFunctionShader* functionShader = 619 SkNEW_ARGS(SkPDFFunctionShader, (shaderState.detach())); 620 valid = functionShader->isValid(); 621 result = functionShader; 622 } 623 } 624 if (!valid) { 625 delete result; 626 return NULL; 627 } 628 entry.fPDFShader = result; 629 CanonicalShaders().push(entry); 630 return result; // return the reference that came from new. 631 } 632 633 // static 634 void SkPDFShader::RemoveShader(SkPDFObject* shader) { 635 SkAutoMutexAcquire lock(CanonicalShadersMutex()); 636 ShaderCanonicalEntry entry(shader, NULL); 637 int index = CanonicalShaders().find(entry); 638 SkASSERT(index >= 0); 639 CanonicalShaders().removeShuffle(index); 640 } 641 642 // static 643 SkPDFObject* SkPDFShader::GetPDFShader(const SkShader& shader, 644 const SkMatrix& matrix, 645 const SkIRect& surfaceBBox) { 646 SkAutoMutexAcquire lock(CanonicalShadersMutex()); 647 return GetPDFShaderByState( 648 SkNEW_ARGS(State, (shader, matrix, surfaceBBox))); 649 } 650 651 // static 652 SkTDArray<SkPDFShader::ShaderCanonicalEntry>& SkPDFShader::CanonicalShaders() { 653 // This initialization is only thread safe with gcc. 654 static SkTDArray<ShaderCanonicalEntry> gCanonicalShaders; 655 return gCanonicalShaders; 656 } 657 658 // static 659 SkBaseMutex& SkPDFShader::CanonicalShadersMutex() { 660 // This initialization is only thread safe with gcc or when 661 // POD-style mutex initialization is used. 662 SK_DECLARE_STATIC_MUTEX(gCanonicalShadersMutex); 663 return gCanonicalShadersMutex; 664 } 665 666 // static 667 SkPDFObject* SkPDFFunctionShader::RangeObject() { 668 // This initialization is only thread safe with gcc. 669 static SkPDFArray* range = NULL; 670 // This method is only used with CanonicalShadersMutex, so it's safe to 671 // populate domain. 672 if (range == NULL) { 673 range = new SkPDFArray; 674 range->reserve(6); 675 range->appendInt(0); 676 range->appendInt(1); 677 range->appendInt(0); 678 range->appendInt(1); 679 range->appendInt(0); 680 range->appendInt(1); 681 } 682 return range; 683 } 684 685 static SkPDFResourceDict* get_gradient_resource_dict( 686 SkPDFObject* functionShader, 687 SkPDFObject* gState) { 688 SkPDFResourceDict* dict = new SkPDFResourceDict(); 689 690 if (functionShader != NULL) { 691 dict->insertResourceAsReference( 692 SkPDFResourceDict::kPattern_ResourceType, 0, functionShader); 693 } 694 if (gState != NULL) { 695 dict->insertResourceAsReference( 696 SkPDFResourceDict::kExtGState_ResourceType, 0, gState); 697 } 698 699 return dict; 700 } 701 702 static void populate_tiling_pattern_dict(SkPDFDict* pattern, 703 SkRect& bbox, SkPDFDict* resources, 704 const SkMatrix& matrix) { 705 const int kTiling_PatternType = 1; 706 const int kColoredTilingPattern_PaintType = 1; 707 const int kConstantSpacing_TilingType = 1; 708 709 pattern->insertName("Type", "Pattern"); 710 pattern->insertInt("PatternType", kTiling_PatternType); 711 pattern->insertInt("PaintType", kColoredTilingPattern_PaintType); 712 pattern->insertInt("TilingType", kConstantSpacing_TilingType); 713 pattern->insert("BBox", SkPDFUtils::RectToArray(bbox))->unref(); 714 pattern->insertScalar("XStep", bbox.width()); 715 pattern->insertScalar("YStep", bbox.height()); 716 pattern->insert("Resources", resources); 717 if (!matrix.isIdentity()) { 718 pattern->insert("Matrix", SkPDFUtils::MatrixToArray(matrix))->unref(); 719 } 720 } 721 722 /** 723 * Creates a content stream which fills the pattern P0 across bounds. 724 * @param gsIndex A graphics state resource index to apply, or <0 if no 725 * graphics state to apply. 726 */ 727 static SkStream* create_pattern_fill_content(int gsIndex, SkRect& bounds) { 728 SkDynamicMemoryWStream content; 729 if (gsIndex >= 0) { 730 SkPDFUtils::ApplyGraphicState(gsIndex, &content); 731 } 732 SkPDFUtils::ApplyPattern(0, &content); 733 SkPDFUtils::AppendRectangle(bounds, &content); 734 SkPDFUtils::PaintPath(SkPaint::kFill_Style, SkPath::kEvenOdd_FillType, 735 &content); 736 737 return content.detachAsStream(); 738 } 739 740 /** 741 * Creates a ExtGState with the SMask set to the luminosityShader in 742 * luminosity mode. The shader pattern extends to the bbox. 743 */ 744 SkPDFGraphicState* SkPDFAlphaFunctionShader::CreateSMaskGraphicState() { 745 SkRect bbox; 746 bbox.set(fState.get()->fBBox); 747 748 SkAutoTUnref<SkPDFObject> luminosityShader( 749 SkPDFShader::GetPDFShaderByState( 750 fState->CreateAlphaToLuminosityState())); 751 752 SkAutoTUnref<SkStream> alphaStream(create_pattern_fill_content(-1, bbox)); 753 754 SkAutoTUnref<SkPDFResourceDict> 755 resources(get_gradient_resource_dict(luminosityShader, NULL)); 756 757 SkAutoTUnref<SkPDFFormXObject> alphaMask( 758 new SkPDFFormXObject(alphaStream.get(), bbox, resources.get())); 759 760 return SkPDFGraphicState::GetSMaskGraphicState( 761 alphaMask.get(), false, 762 SkPDFGraphicState::kLuminosity_SMaskMode); 763 } 764 765 SkPDFAlphaFunctionShader::SkPDFAlphaFunctionShader(SkPDFShader::State* state) 766 : fState(state) { 767 SkRect bbox; 768 bbox.set(fState.get()->fBBox); 769 770 fColorShader.reset( 771 SkPDFShader::GetPDFShaderByState(state->CreateOpaqueState())); 772 773 // Create resource dict with alpha graphics state as G0 and 774 // pattern shader as P0, then write content stream. 775 SkAutoTUnref<SkPDFGraphicState> alphaGs(CreateSMaskGraphicState()); 776 fResourceDict.reset( 777 get_gradient_resource_dict(fColorShader.get(), alphaGs.get())); 778 779 SkAutoTUnref<SkStream> colorStream( 780 create_pattern_fill_content(0, bbox)); 781 setData(colorStream.get()); 782 783 populate_tiling_pattern_dict(this, bbox, fResourceDict.get(), 784 SkMatrix::I()); 785 } 786 787 // Finds affine and persp such that in = affine * persp. 788 // but it returns the inverse of perspective matrix. 789 static bool split_perspective(const SkMatrix in, SkMatrix* affine, 790 SkMatrix* perspectiveInverse) { 791 const SkScalar p2 = in[SkMatrix::kMPersp2]; 792 793 if (SkScalarNearlyZero(p2)) { 794 return false; 795 } 796 797 const SkScalar zero = SkIntToScalar(0); 798 const SkScalar one = SkIntToScalar(1); 799 800 const SkScalar sx = in[SkMatrix::kMScaleX]; 801 const SkScalar kx = in[SkMatrix::kMSkewX]; 802 const SkScalar tx = in[SkMatrix::kMTransX]; 803 const SkScalar ky = in[SkMatrix::kMSkewY]; 804 const SkScalar sy = in[SkMatrix::kMScaleY]; 805 const SkScalar ty = in[SkMatrix::kMTransY]; 806 const SkScalar p0 = in[SkMatrix::kMPersp0]; 807 const SkScalar p1 = in[SkMatrix::kMPersp1]; 808 809 // Perspective matrix would be: 810 // 1 0 0 811 // 0 1 0 812 // p0 p1 p2 813 // But we need the inverse of persp. 814 perspectiveInverse->setAll(one, zero, zero, 815 zero, one, zero, 816 -p0/p2, -p1/p2, 1/p2); 817 818 affine->setAll(sx - p0 * tx / p2, kx - p1 * tx / p2, tx / p2, 819 ky - p0 * ty / p2, sy - p1 * ty / p2, ty / p2, 820 zero, zero, one); 821 822 return true; 823 } 824 825 SkPDFFunctionShader::SkPDFFunctionShader(SkPDFShader::State* state) 826 : SkPDFDict("Pattern"), 827 fState(state) { 828 SkString (*codeFunction)(const SkShader::GradientInfo& info, 829 const SkMatrix& perspectiveRemover) = NULL; 830 SkPoint transformPoints[2]; 831 832 // Depending on the type of the gradient, we want to transform the 833 // coordinate space in different ways. 834 const SkShader::GradientInfo* info = &fState.get()->fInfo; 835 transformPoints[0] = info->fPoint[0]; 836 transformPoints[1] = info->fPoint[1]; 837 switch (fState.get()->fType) { 838 case SkShader::kLinear_GradientType: 839 codeFunction = &linearCode; 840 break; 841 case SkShader::kRadial_GradientType: 842 transformPoints[1] = transformPoints[0]; 843 transformPoints[1].fX += info->fRadius[0]; 844 codeFunction = &radialCode; 845 break; 846 case SkShader::kRadial2_GradientType: { 847 // Bail out if the radii are the same. Empty fResources signals 848 // an error and isValid will return false. 849 if (info->fRadius[0] == info->fRadius[1]) { 850 return; 851 } 852 transformPoints[1] = transformPoints[0]; 853 SkScalar dr = info->fRadius[1] - info->fRadius[0]; 854 transformPoints[1].fX += dr; 855 codeFunction = &twoPointRadialCode; 856 break; 857 } 858 case SkShader::kConical_GradientType: { 859 transformPoints[1] = transformPoints[0]; 860 transformPoints[1].fX += SK_Scalar1; 861 codeFunction = &twoPointConicalCode; 862 break; 863 } 864 case SkShader::kSweep_GradientType: 865 transformPoints[1] = transformPoints[0]; 866 transformPoints[1].fX += SK_Scalar1; 867 codeFunction = &sweepCode; 868 break; 869 case SkShader::kColor_GradientType: 870 case SkShader::kNone_GradientType: 871 default: 872 return; 873 } 874 875 // Move any scaling (assuming a unit gradient) or translation 876 // (and rotation for linear gradient), of the final gradient from 877 // info->fPoints to the matrix (updating bbox appropriately). Now 878 // the gradient can be drawn on on the unit segment. 879 SkMatrix mapperMatrix; 880 unitToPointsMatrix(transformPoints, &mapperMatrix); 881 882 SkMatrix finalMatrix = fState.get()->fCanvasTransform; 883 finalMatrix.preConcat(fState.get()->fShaderTransform); 884 finalMatrix.preConcat(mapperMatrix); 885 886 // Preserves as much as posible in the final matrix, and only removes 887 // the perspective. The inverse of the perspective is stored in 888 // perspectiveInverseOnly matrix and has 3 useful numbers 889 // (p0, p1, p2), while everything else is either 0 or 1. 890 // In this way the shader will handle it eficiently, with minimal code. 891 SkMatrix perspectiveInverseOnly = SkMatrix::I(); 892 if (finalMatrix.hasPerspective()) { 893 if (!split_perspective(finalMatrix, 894 &finalMatrix, &perspectiveInverseOnly)) { 895 return; 896 } 897 } 898 899 SkRect bbox; 900 bbox.set(fState.get()->fBBox); 901 if (!transformBBox(finalMatrix, &bbox)) { 902 return; 903 } 904 905 SkAutoTUnref<SkPDFArray> domain(new SkPDFArray); 906 domain->reserve(4); 907 domain->appendScalar(bbox.fLeft); 908 domain->appendScalar(bbox.fRight); 909 domain->appendScalar(bbox.fTop); 910 domain->appendScalar(bbox.fBottom); 911 912 SkString functionCode; 913 // The two point radial gradient further references fState.get()->fInfo 914 // in translating from x, y coordinates to the t parameter. So, we have 915 // to transform the points and radii according to the calculated matrix. 916 if (fState.get()->fType == SkShader::kRadial2_GradientType) { 917 SkShader::GradientInfo twoPointRadialInfo = *info; 918 SkMatrix inverseMapperMatrix; 919 if (!mapperMatrix.invert(&inverseMapperMatrix)) { 920 return; 921 } 922 inverseMapperMatrix.mapPoints(twoPointRadialInfo.fPoint, 2); 923 twoPointRadialInfo.fRadius[0] = 924 inverseMapperMatrix.mapRadius(info->fRadius[0]); 925 twoPointRadialInfo.fRadius[1] = 926 inverseMapperMatrix.mapRadius(info->fRadius[1]); 927 functionCode = codeFunction(twoPointRadialInfo, perspectiveInverseOnly); 928 } else { 929 functionCode = codeFunction(*info, perspectiveInverseOnly); 930 } 931 932 SkAutoTUnref<SkPDFDict> pdfShader(new SkPDFDict); 933 pdfShader->insertInt("ShadingType", 1); 934 pdfShader->insertName("ColorSpace", "DeviceRGB"); 935 pdfShader->insert("Domain", domain.get()); 936 937 SkPDFStream* function = makePSFunction(functionCode, domain.get()); 938 pdfShader->insert("Function", new SkPDFObjRef(function))->unref(); 939 fResources.push(function); // Pass ownership to resource list. 940 941 insertInt("PatternType", 2); 942 insert("Matrix", SkPDFUtils::MatrixToArray(finalMatrix))->unref(); 943 insert("Shading", pdfShader.get()); 944 } 945 946 SkPDFImageShader::SkPDFImageShader(SkPDFShader::State* state) : fState(state) { 947 fState.get()->fImage.lockPixels(); 948 949 SkMatrix finalMatrix = fState.get()->fCanvasTransform; 950 finalMatrix.preConcat(fState.get()->fShaderTransform); 951 SkRect surfaceBBox; 952 surfaceBBox.set(fState.get()->fBBox); 953 if (!transformBBox(finalMatrix, &surfaceBBox)) { 954 return; 955 } 956 957 SkMatrix unflip; 958 unflip.setTranslate(0, SkScalarRoundToScalar(surfaceBBox.height())); 959 unflip.preScale(SK_Scalar1, -SK_Scalar1); 960 SkISize size = SkISize::Make(SkScalarRound(surfaceBBox.width()), 961 SkScalarRound(surfaceBBox.height())); 962 SkPDFDevice pattern(size, size, unflip); 963 SkCanvas canvas(&pattern); 964 canvas.translate(-surfaceBBox.fLeft, -surfaceBBox.fTop); 965 finalMatrix.preTranslate(surfaceBBox.fLeft, surfaceBBox.fTop); 966 967 const SkBitmap* image = &fState.get()->fImage; 968 SkScalar width = SkIntToScalar(image->width()); 969 SkScalar height = SkIntToScalar(image->height()); 970 SkShader::TileMode tileModes[2]; 971 tileModes[0] = fState.get()->fImageTileModes[0]; 972 tileModes[1] = fState.get()->fImageTileModes[1]; 973 974 canvas.drawBitmap(*image, 0, 0); 975 SkRect patternBBox = SkRect::MakeXYWH(-surfaceBBox.fLeft, -surfaceBBox.fTop, 976 width, height); 977 978 // Tiling is implied. First we handle mirroring. 979 if (tileModes[0] == SkShader::kMirror_TileMode) { 980 SkMatrix xMirror; 981 xMirror.setScale(-1, 1); 982 xMirror.postTranslate(2 * width, 0); 983 canvas.drawBitmapMatrix(*image, xMirror); 984 patternBBox.fRight += width; 985 } 986 if (tileModes[1] == SkShader::kMirror_TileMode) { 987 SkMatrix yMirror; 988 yMirror.setScale(SK_Scalar1, -SK_Scalar1); 989 yMirror.postTranslate(0, 2 * height); 990 canvas.drawBitmapMatrix(*image, yMirror); 991 patternBBox.fBottom += height; 992 } 993 if (tileModes[0] == SkShader::kMirror_TileMode && 994 tileModes[1] == SkShader::kMirror_TileMode) { 995 SkMatrix mirror; 996 mirror.setScale(-1, -1); 997 mirror.postTranslate(2 * width, 2 * height); 998 canvas.drawBitmapMatrix(*image, mirror); 999 } 1000 1001 // Then handle Clamping, which requires expanding the pattern canvas to 1002 // cover the entire surfaceBBox. 1003 1004 // If both x and y are in clamp mode, we start by filling in the corners. 1005 // (Which are just a rectangles of the corner colors.) 1006 if (tileModes[0] == SkShader::kClamp_TileMode && 1007 tileModes[1] == SkShader::kClamp_TileMode) { 1008 SkPaint paint; 1009 SkRect rect; 1010 rect = SkRect::MakeLTRB(surfaceBBox.fLeft, surfaceBBox.fTop, 0, 0); 1011 if (!rect.isEmpty()) { 1012 paint.setColor(image->getColor(0, 0)); 1013 canvas.drawRect(rect, paint); 1014 } 1015 1016 rect = SkRect::MakeLTRB(width, surfaceBBox.fTop, surfaceBBox.fRight, 0); 1017 if (!rect.isEmpty()) { 1018 paint.setColor(image->getColor(image->width() - 1, 0)); 1019 canvas.drawRect(rect, paint); 1020 } 1021 1022 rect = SkRect::MakeLTRB(width, height, surfaceBBox.fRight, 1023 surfaceBBox.fBottom); 1024 if (!rect.isEmpty()) { 1025 paint.setColor(image->getColor(image->width() - 1, 1026 image->height() - 1)); 1027 canvas.drawRect(rect, paint); 1028 } 1029 1030 rect = SkRect::MakeLTRB(surfaceBBox.fLeft, height, 0, 1031 surfaceBBox.fBottom); 1032 if (!rect.isEmpty()) { 1033 paint.setColor(image->getColor(0, image->height() - 1)); 1034 canvas.drawRect(rect, paint); 1035 } 1036 } 1037 1038 // Then expand the left, right, top, then bottom. 1039 if (tileModes[0] == SkShader::kClamp_TileMode) { 1040 SkIRect subset = SkIRect::MakeXYWH(0, 0, 1, image->height()); 1041 if (surfaceBBox.fLeft < 0) { 1042 SkBitmap left; 1043 SkAssertResult(image->extractSubset(&left, subset)); 1044 1045 SkMatrix leftMatrix; 1046 leftMatrix.setScale(-surfaceBBox.fLeft, 1); 1047 leftMatrix.postTranslate(surfaceBBox.fLeft, 0); 1048 canvas.drawBitmapMatrix(left, leftMatrix); 1049 1050 if (tileModes[1] == SkShader::kMirror_TileMode) { 1051 leftMatrix.postScale(SK_Scalar1, -SK_Scalar1); 1052 leftMatrix.postTranslate(0, 2 * height); 1053 canvas.drawBitmapMatrix(left, leftMatrix); 1054 } 1055 patternBBox.fLeft = 0; 1056 } 1057 1058 if (surfaceBBox.fRight > width) { 1059 SkBitmap right; 1060 subset.offset(image->width() - 1, 0); 1061 SkAssertResult(image->extractSubset(&right, subset)); 1062 1063 SkMatrix rightMatrix; 1064 rightMatrix.setScale(surfaceBBox.fRight - width, 1); 1065 rightMatrix.postTranslate(width, 0); 1066 canvas.drawBitmapMatrix(right, rightMatrix); 1067 1068 if (tileModes[1] == SkShader::kMirror_TileMode) { 1069 rightMatrix.postScale(SK_Scalar1, -SK_Scalar1); 1070 rightMatrix.postTranslate(0, 2 * height); 1071 canvas.drawBitmapMatrix(right, rightMatrix); 1072 } 1073 patternBBox.fRight = surfaceBBox.width(); 1074 } 1075 } 1076 1077 if (tileModes[1] == SkShader::kClamp_TileMode) { 1078 SkIRect subset = SkIRect::MakeXYWH(0, 0, image->width(), 1); 1079 if (surfaceBBox.fTop < 0) { 1080 SkBitmap top; 1081 SkAssertResult(image->extractSubset(&top, subset)); 1082 1083 SkMatrix topMatrix; 1084 topMatrix.setScale(SK_Scalar1, -surfaceBBox.fTop); 1085 topMatrix.postTranslate(0, surfaceBBox.fTop); 1086 canvas.drawBitmapMatrix(top, topMatrix); 1087 1088 if (tileModes[0] == SkShader::kMirror_TileMode) { 1089 topMatrix.postScale(-1, 1); 1090 topMatrix.postTranslate(2 * width, 0); 1091 canvas.drawBitmapMatrix(top, topMatrix); 1092 } 1093 patternBBox.fTop = 0; 1094 } 1095 1096 if (surfaceBBox.fBottom > height) { 1097 SkBitmap bottom; 1098 subset.offset(0, image->height() - 1); 1099 SkAssertResult(image->extractSubset(&bottom, subset)); 1100 1101 SkMatrix bottomMatrix; 1102 bottomMatrix.setScale(SK_Scalar1, surfaceBBox.fBottom - height); 1103 bottomMatrix.postTranslate(0, height); 1104 canvas.drawBitmapMatrix(bottom, bottomMatrix); 1105 1106 if (tileModes[0] == SkShader::kMirror_TileMode) { 1107 bottomMatrix.postScale(-1, 1); 1108 bottomMatrix.postTranslate(2 * width, 0); 1109 canvas.drawBitmapMatrix(bottom, bottomMatrix); 1110 } 1111 patternBBox.fBottom = surfaceBBox.height(); 1112 } 1113 } 1114 1115 // Put the canvas into the pattern stream (fContent). 1116 SkAutoTUnref<SkStream> content(pattern.content()); 1117 setData(content.get()); 1118 SkPDFResourceDict* resourceDict = pattern.getResourceDict(); 1119 resourceDict->getReferencedResources(fResources, &fResources, false); 1120 1121 populate_tiling_pattern_dict(this, patternBBox, 1122 pattern.getResourceDict(), finalMatrix); 1123 1124 fState.get()->fImage.unlockPixels(); 1125 } 1126 1127 SkPDFStream* SkPDFFunctionShader::makePSFunction(const SkString& psCode, 1128 SkPDFArray* domain) { 1129 SkAutoDataUnref funcData(SkData::NewWithCopy(psCode.c_str(), 1130 psCode.size())); 1131 SkPDFStream* result = new SkPDFStream(funcData.get()); 1132 result->insertInt("FunctionType", 4); 1133 result->insert("Domain", domain); 1134 result->insert("Range", RangeObject()); 1135 return result; 1136 } 1137 1138 SkPDFShader::ShaderCanonicalEntry::ShaderCanonicalEntry(SkPDFObject* pdfShader, 1139 const State* state) 1140 : fPDFShader(pdfShader), 1141 fState(state) { 1142 } 1143 1144 bool SkPDFShader::ShaderCanonicalEntry::operator==( 1145 const ShaderCanonicalEntry& b) const { 1146 return fPDFShader == b.fPDFShader || 1147 (fState != NULL && b.fState != NULL && *fState == *b.fState); 1148 } 1149 1150 bool SkPDFShader::State::operator==(const SkPDFShader::State& b) const { 1151 if (fType != b.fType || 1152 fCanvasTransform != b.fCanvasTransform || 1153 fShaderTransform != b.fShaderTransform || 1154 fBBox != b.fBBox) { 1155 return false; 1156 } 1157 1158 if (fType == SkShader::kNone_GradientType) { 1159 if (fPixelGeneration != b.fPixelGeneration || 1160 fPixelGeneration == 0 || 1161 fImageTileModes[0] != b.fImageTileModes[0] || 1162 fImageTileModes[1] != b.fImageTileModes[1]) { 1163 return false; 1164 } 1165 } else { 1166 if (fInfo.fColorCount != b.fInfo.fColorCount || 1167 memcmp(fInfo.fColors, b.fInfo.fColors, 1168 sizeof(SkColor) * fInfo.fColorCount) != 0 || 1169 memcmp(fInfo.fColorOffsets, b.fInfo.fColorOffsets, 1170 sizeof(SkScalar) * fInfo.fColorCount) != 0 || 1171 fInfo.fPoint[0] != b.fInfo.fPoint[0] || 1172 fInfo.fTileMode != b.fInfo.fTileMode) { 1173 return false; 1174 } 1175 1176 switch (fType) { 1177 case SkShader::kLinear_GradientType: 1178 if (fInfo.fPoint[1] != b.fInfo.fPoint[1]) { 1179 return false; 1180 } 1181 break; 1182 case SkShader::kRadial_GradientType: 1183 if (fInfo.fRadius[0] != b.fInfo.fRadius[0]) { 1184 return false; 1185 } 1186 break; 1187 case SkShader::kRadial2_GradientType: 1188 case SkShader::kConical_GradientType: 1189 if (fInfo.fPoint[1] != b.fInfo.fPoint[1] || 1190 fInfo.fRadius[0] != b.fInfo.fRadius[0] || 1191 fInfo.fRadius[1] != b.fInfo.fRadius[1]) { 1192 return false; 1193 } 1194 break; 1195 case SkShader::kSweep_GradientType: 1196 case SkShader::kNone_GradientType: 1197 case SkShader::kColor_GradientType: 1198 break; 1199 } 1200 } 1201 return true; 1202 } 1203 1204 SkPDFShader::State::State(const SkShader& shader, 1205 const SkMatrix& canvasTransform, const SkIRect& bbox) 1206 : fCanvasTransform(canvasTransform), 1207 fBBox(bbox), 1208 fPixelGeneration(0) { 1209 fInfo.fColorCount = 0; 1210 fInfo.fColors = NULL; 1211 fInfo.fColorOffsets = NULL; 1212 fShaderTransform = shader.getLocalMatrix(); 1213 fImageTileModes[0] = fImageTileModes[1] = SkShader::kClamp_TileMode; 1214 1215 fType = shader.asAGradient(&fInfo); 1216 1217 if (fType == SkShader::kNone_GradientType) { 1218 SkShader::BitmapType bitmapType; 1219 SkMatrix matrix; 1220 bitmapType = shader.asABitmap(&fImage, &matrix, fImageTileModes); 1221 if (bitmapType != SkShader::kDefault_BitmapType) { 1222 fImage.reset(); 1223 return; 1224 } 1225 SkASSERT(matrix.isIdentity()); 1226 fPixelGeneration = fImage.getGenerationID(); 1227 } else { 1228 AllocateGradientInfoStorage(); 1229 shader.asAGradient(&fInfo); 1230 } 1231 } 1232 1233 SkPDFShader::State::State(const SkPDFShader::State& other) 1234 : fType(other.fType), 1235 fCanvasTransform(other.fCanvasTransform), 1236 fShaderTransform(other.fShaderTransform), 1237 fBBox(other.fBBox) 1238 { 1239 // Only gradients supported for now, since that is all that is used. 1240 // If needed, image state copy constructor can be added here later. 1241 SkASSERT(fType != SkShader::kNone_GradientType); 1242 1243 if (fType != SkShader::kNone_GradientType) { 1244 fInfo = other.fInfo; 1245 1246 AllocateGradientInfoStorage(); 1247 for (int i = 0; i < fInfo.fColorCount; i++) { 1248 fInfo.fColors[i] = other.fInfo.fColors[i]; 1249 fInfo.fColorOffsets[i] = other.fInfo.fColorOffsets[i]; 1250 } 1251 } 1252 } 1253 1254 /** 1255 * Create a copy of this gradient state with alpha assigned to RGB luminousity. 1256 * Only valid for gradient states. 1257 */ 1258 SkPDFShader::State* SkPDFShader::State::CreateAlphaToLuminosityState() const { 1259 SkASSERT(fType != SkShader::kNone_GradientType); 1260 1261 SkPDFShader::State* newState = new SkPDFShader::State(*this); 1262 1263 for (int i = 0; i < fInfo.fColorCount; i++) { 1264 SkAlpha alpha = SkColorGetA(fInfo.fColors[i]); 1265 newState->fInfo.fColors[i] = SkColorSetARGB(255, alpha, alpha, alpha); 1266 } 1267 1268 return newState; 1269 } 1270 1271 /** 1272 * Create a copy of this gradient state with alpha set to fully opaque 1273 * Only valid for gradient states. 1274 */ 1275 SkPDFShader::State* SkPDFShader::State::CreateOpaqueState() const { 1276 SkASSERT(fType != SkShader::kNone_GradientType); 1277 1278 SkPDFShader::State* newState = new SkPDFShader::State(*this); 1279 for (int i = 0; i < fInfo.fColorCount; i++) { 1280 newState->fInfo.fColors[i] = SkColorSetA(fInfo.fColors[i], 1281 SK_AlphaOPAQUE); 1282 } 1283 1284 return newState; 1285 } 1286 1287 /** 1288 * Returns true if state is a gradient and the gradient has alpha. 1289 */ 1290 bool SkPDFShader::State::GradientHasAlpha() const { 1291 if (fType == SkShader::kNone_GradientType) { 1292 return false; 1293 } 1294 1295 for (int i = 0; i < fInfo.fColorCount; i++) { 1296 SkAlpha alpha = SkColorGetA(fInfo.fColors[i]); 1297 if (alpha != SK_AlphaOPAQUE) { 1298 return true; 1299 } 1300 } 1301 return false; 1302 } 1303 1304 void SkPDFShader::State::AllocateGradientInfoStorage() { 1305 fColorData.set(sk_malloc_throw( 1306 fInfo.fColorCount * (sizeof(SkColor) + sizeof(SkScalar)))); 1307 fInfo.fColors = reinterpret_cast<SkColor*>(fColorData.get()); 1308 fInfo.fColorOffsets = 1309 reinterpret_cast<SkScalar*>(fInfo.fColors + fInfo.fColorCount); 1310 } 1311