blob: 36e76e99409e2975d9581e44a2ce038dc68c0787 [file] [log] [blame]
skia.committer@gmail.com11a253b2013-11-12 07:02:05 +00001/*
2 * Copyright 2011 Google Inc.
3 *
4 * Use of this source code is governed by a BSD-style license that can be
5 * found in the LICENSE file.
6 */
7
8#include "SkGpuDevice.h"
9
commit-bot@chromium.orgdec61502013-12-02 22:22:35 +000010#include "effects/GrBicubicEffect.h"
commit-bot@chromium.org907fbd52013-12-09 17:03:02 +000011#include "effects/GrTextureDomain.h"
skia.committer@gmail.com11a253b2013-11-12 07:02:05 +000012#include "effects/GrSimpleTextureEffect.h"
13
14#include "GrContext.h"
15#include "GrBitmapTextContext.h"
16#if SK_DISTANCEFIELD_FONTS
17#include "GrDistanceFieldTextContext.h"
18#endif
19
20#include "SkGrTexturePixelRef.h"
21
22#include "SkColorFilter.h"
23#include "SkDeviceImageFilterProxy.h"
24#include "SkDrawProcs.h"
25#include "SkGlyphCache.h"
26#include "SkImageFilter.h"
27#include "SkPathEffect.h"
28#include "SkRRect.h"
29#include "SkStroke.h"
commit-bot@chromium.orga7d89c82014-01-13 14:47:00 +000030#include "SkTLazy.h"
skia.committer@gmail.com11a253b2013-11-12 07:02:05 +000031#include "SkUtils.h"
32#include "SkErrorInternals.h"
33
34#define CACHE_COMPATIBLE_DEVICE_TEXTURES 1
35
36#if 0
37 extern bool (*gShouldDrawProc)();
38 #define CHECK_SHOULD_DRAW(draw, forceI) \
39 do { \
40 if (gShouldDrawProc && !gShouldDrawProc()) return; \
41 this->prepareDraw(draw, forceI); \
42 } while (0)
43#else
44 #define CHECK_SHOULD_DRAW(draw, forceI) this->prepareDraw(draw, forceI)
45#endif
46
47// This constant represents the screen alignment criterion in texels for
48// requiring texture domain clamping to prevent color bleeding when drawing
49// a sub region of a larger source image.
commit-bot@chromium.org4b413c82013-11-25 19:44:07 +000050#define COLOR_BLEED_TOLERANCE 0.001f
skia.committer@gmail.com11a253b2013-11-12 07:02:05 +000051
52#define DO_DEFERRED_CLEAR() \
53 do { \
54 if (fNeedClear) { \
55 this->clear(SK_ColorTRANSPARENT); \
56 } \
57 } while (false) \
58
59///////////////////////////////////////////////////////////////////////////////
60
61#define CHECK_FOR_ANNOTATION(paint) \
62 do { if (paint.getAnnotation()) { return; } } while (0)
63
64///////////////////////////////////////////////////////////////////////////////
65
66
67class SkGpuDevice::SkAutoCachedTexture : public ::SkNoncopyable {
68public:
69 SkAutoCachedTexture()
70 : fDevice(NULL)
71 , fTexture(NULL) {
72 }
73
74 SkAutoCachedTexture(SkGpuDevice* device,
75 const SkBitmap& bitmap,
76 const GrTextureParams* params,
77 GrTexture** texture)
78 : fDevice(NULL)
79 , fTexture(NULL) {
80 SkASSERT(NULL != texture);
81 *texture = this->set(device, bitmap, params);
82 }
83
84 ~SkAutoCachedTexture() {
85 if (NULL != fTexture) {
86 GrUnlockAndUnrefCachedBitmapTexture(fTexture);
87 }
88 }
89
90 GrTexture* set(SkGpuDevice* device,
91 const SkBitmap& bitmap,
92 const GrTextureParams* params) {
93 if (NULL != fTexture) {
94 GrUnlockAndUnrefCachedBitmapTexture(fTexture);
95 fTexture = NULL;
96 }
97 fDevice = device;
98 GrTexture* result = (GrTexture*)bitmap.getTexture();
99 if (NULL == result) {
100 // Cannot return the native texture so look it up in our cache
101 fTexture = GrLockAndRefCachedBitmapTexture(device->context(), bitmap, params);
102 result = fTexture;
103 }
104 return result;
105 }
106
107private:
108 SkGpuDevice* fDevice;
109 GrTexture* fTexture;
110};
111
112///////////////////////////////////////////////////////////////////////////////
113
114struct GrSkDrawProcs : public SkDrawProcs {
115public:
116 GrContext* fContext;
117 GrTextContext* fTextContext;
118 GrFontScaler* fFontScaler; // cached in the skia glyphcache
119};
120
121///////////////////////////////////////////////////////////////////////////////
122
123static SkBitmap::Config grConfig2skConfig(GrPixelConfig config, bool* isOpaque) {
124 switch (config) {
125 case kAlpha_8_GrPixelConfig:
126 *isOpaque = false;
127 return SkBitmap::kA8_Config;
128 case kRGB_565_GrPixelConfig:
129 *isOpaque = true;
130 return SkBitmap::kRGB_565_Config;
131 case kRGBA_4444_GrPixelConfig:
132 *isOpaque = false;
133 return SkBitmap::kARGB_4444_Config;
134 case kSkia8888_GrPixelConfig:
135 // we don't currently have a way of knowing whether
136 // a 8888 is opaque based on the config.
137 *isOpaque = false;
138 return SkBitmap::kARGB_8888_Config;
139 default:
140 *isOpaque = false;
141 return SkBitmap::kNo_Config;
142 }
143}
144
145/*
146 * GrRenderTarget does not know its opaqueness, only its config, so we have
147 * to make conservative guesses when we return an "equivalent" bitmap.
148 */
149static SkBitmap make_bitmap(GrContext* context, GrRenderTarget* renderTarget) {
150 bool isOpaque;
151 SkBitmap::Config config = grConfig2skConfig(renderTarget->config(), &isOpaque);
152
153 SkBitmap bitmap;
154 bitmap.setConfig(config, renderTarget->width(), renderTarget->height(), 0,
155 isOpaque ? kOpaque_SkAlphaType : kPremul_SkAlphaType);
156 return bitmap;
157}
158
commit-bot@chromium.org3e7f3852013-12-06 22:59:02 +0000159/*
160 * Calling SkBitmapDevice with individual params asks it to allocate pixel memory.
161 * We never want that, so we always need to call it with a bitmap argument
162 * (which says take my allocate (or lack thereof)).
163 *
164 * This is a REALLY good reason to finish the clean-up of SkBaseDevice, and have
165 * SkGpuDevice inherit from that instead of SkBitmapDevice.
166 */
167static SkBitmap make_bitmap(SkBitmap::Config config, int width, int height, bool isOpaque) {
168 SkBitmap bm;
169 bm.setConfig(config, width, height, isOpaque);
170 return bm;
171}
172
skia.committer@gmail.com11a253b2013-11-12 07:02:05 +0000173SkGpuDevice* SkGpuDevice::Create(GrSurface* surface) {
174 SkASSERT(NULL != surface);
175 if (NULL == surface->asRenderTarget() || NULL == surface->getContext()) {
176 return NULL;
177 }
178 if (surface->asTexture()) {
179 return SkNEW_ARGS(SkGpuDevice, (surface->getContext(), surface->asTexture()));
180 } else {
181 return SkNEW_ARGS(SkGpuDevice, (surface->getContext(), surface->asRenderTarget()));
182 }
183}
184
185SkGpuDevice::SkGpuDevice(GrContext* context, GrTexture* texture)
186 : SkBitmapDevice(make_bitmap(context, texture->asRenderTarget())) {
187 this->initFromRenderTarget(context, texture->asRenderTarget(), false);
188}
189
190SkGpuDevice::SkGpuDevice(GrContext* context, GrRenderTarget* renderTarget)
191 : SkBitmapDevice(make_bitmap(context, renderTarget)) {
192 this->initFromRenderTarget(context, renderTarget, false);
193}
194
195void SkGpuDevice::initFromRenderTarget(GrContext* context,
196 GrRenderTarget* renderTarget,
197 bool cached) {
198 fDrawProcs = NULL;
199
200 fContext = context;
201 fContext->ref();
202
203 fRenderTarget = NULL;
204 fNeedClear = false;
205
206 SkASSERT(NULL != renderTarget);
207 fRenderTarget = renderTarget;
208 fRenderTarget->ref();
209
210 // Hold onto to the texture in the pixel ref (if there is one) because the texture holds a ref
211 // on the RT but not vice-versa.
212 // TODO: Remove this trickery once we figure out how to make SkGrPixelRef do this without
213 // busting chrome (for a currently unknown reason).
214 GrSurface* surface = fRenderTarget->asTexture();
215 if (NULL == surface) {
216 surface = fRenderTarget;
217 }
reed@google.combf790232013-12-13 19:45:58 +0000218
219 SkImageInfo info;
220 surface->asImageInfo(&info);
221 SkPixelRef* pr = SkNEW_ARGS(SkGrPixelRef, (info, surface, cached));
skia.committer@gmail.com11a253b2013-11-12 07:02:05 +0000222
reed@google.com672588b2014-01-08 15:42:01 +0000223 this->setPixelRef(pr)->unref();
skia.committer@gmail.com11a253b2013-11-12 07:02:05 +0000224}
225
226SkGpuDevice::SkGpuDevice(GrContext* context,
227 SkBitmap::Config config,
228 int width,
229 int height,
230 int sampleCount)
reed@google.combf790232013-12-13 19:45:58 +0000231 : SkBitmapDevice(make_bitmap(config, width, height, false /*isOpaque*/))
232{
skia.committer@gmail.com11a253b2013-11-12 07:02:05 +0000233 fDrawProcs = NULL;
234
235 fContext = context;
236 fContext->ref();
237
238 fRenderTarget = NULL;
239 fNeedClear = false;
240
241 if (config != SkBitmap::kRGB_565_Config) {
242 config = SkBitmap::kARGB_8888_Config;
243 }
244
245 GrTextureDesc desc;
246 desc.fFlags = kRenderTarget_GrTextureFlagBit;
247 desc.fWidth = width;
248 desc.fHeight = height;
249 desc.fConfig = SkBitmapConfig2GrPixelConfig(config);
250 desc.fSampleCnt = sampleCount;
251
reed@google.combf790232013-12-13 19:45:58 +0000252 SkImageInfo info;
253 if (!GrPixelConfig2ColorType(desc.fConfig, &info.fColorType)) {
254 sk_throw();
255 }
256 info.fWidth = width;
257 info.fHeight = height;
258 info.fAlphaType = kPremul_SkAlphaType;
skia.committer@gmail.com96f5fa02013-12-16 07:01:40 +0000259
skia.committer@gmail.com11a253b2013-11-12 07:02:05 +0000260 SkAutoTUnref<GrTexture> texture(fContext->createUncachedTexture(desc, NULL, 0));
261
262 if (NULL != texture) {
263 fRenderTarget = texture->asRenderTarget();
264 fRenderTarget->ref();
265
266 SkASSERT(NULL != fRenderTarget);
267
268 // wrap the bitmap with a pixelref to expose our texture
reed@google.combf790232013-12-13 19:45:58 +0000269 SkGrPixelRef* pr = SkNEW_ARGS(SkGrPixelRef, (info, texture));
reed@google.com672588b2014-01-08 15:42:01 +0000270 this->setPixelRef(pr)->unref();
skia.committer@gmail.com11a253b2013-11-12 07:02:05 +0000271 } else {
272 GrPrintf("--- failed to create gpu-offscreen [%d %d]\n",
273 width, height);
274 SkASSERT(false);
275 }
276}
277
278SkGpuDevice::~SkGpuDevice() {
279 if (fDrawProcs) {
280 delete fDrawProcs;
281 }
282
283 // The GrContext takes a ref on the target. We don't want to cause the render
284 // target to be unnecessarily kept alive.
285 if (fContext->getRenderTarget() == fRenderTarget) {
286 fContext->setRenderTarget(NULL);
287 }
288
289 if (fContext->getClip() == &fClipData) {
290 fContext->setClip(NULL);
291 }
292
293 SkSafeUnref(fRenderTarget);
294 fContext->unref();
295}
296
297///////////////////////////////////////////////////////////////////////////////
298
299void SkGpuDevice::makeRenderTargetCurrent() {
300 DO_DEFERRED_CLEAR();
301 fContext->setRenderTarget(fRenderTarget);
302}
303
304///////////////////////////////////////////////////////////////////////////////
305
306namespace {
307GrPixelConfig config8888_to_grconfig_and_flags(SkCanvas::Config8888 config8888, uint32_t* flags) {
308 switch (config8888) {
309 case SkCanvas::kNative_Premul_Config8888:
310 *flags = 0;
311 return kSkia8888_GrPixelConfig;
312 case SkCanvas::kNative_Unpremul_Config8888:
313 *flags = GrContext::kUnpremul_PixelOpsFlag;
314 return kSkia8888_GrPixelConfig;
315 case SkCanvas::kBGRA_Premul_Config8888:
316 *flags = 0;
317 return kBGRA_8888_GrPixelConfig;
318 case SkCanvas::kBGRA_Unpremul_Config8888:
319 *flags = GrContext::kUnpremul_PixelOpsFlag;
320 return kBGRA_8888_GrPixelConfig;
321 case SkCanvas::kRGBA_Premul_Config8888:
322 *flags = 0;
323 return kRGBA_8888_GrPixelConfig;
324 case SkCanvas::kRGBA_Unpremul_Config8888:
325 *flags = GrContext::kUnpremul_PixelOpsFlag;
326 return kRGBA_8888_GrPixelConfig;
327 default:
328 GrCrash("Unexpected Config8888.");
329 *flags = 0; // suppress warning
330 return kSkia8888_GrPixelConfig;
331 }
332}
333}
334
335bool SkGpuDevice::onReadPixels(const SkBitmap& bitmap,
336 int x, int y,
337 SkCanvas::Config8888 config8888) {
338 DO_DEFERRED_CLEAR();
339 SkASSERT(SkBitmap::kARGB_8888_Config == bitmap.config());
340 SkASSERT(!bitmap.isNull());
341 SkASSERT(SkIRect::MakeWH(this->width(), this->height()).contains(SkIRect::MakeXYWH(x, y, bitmap.width(), bitmap.height())));
342
343 SkAutoLockPixels alp(bitmap);
344 GrPixelConfig config;
345 uint32_t flags;
346 config = config8888_to_grconfig_and_flags(config8888, &flags);
347 return fContext->readRenderTargetPixels(fRenderTarget,
348 x, y,
349 bitmap.width(),
350 bitmap.height(),
351 config,
352 bitmap.getPixels(),
353 bitmap.rowBytes(),
354 flags);
355}
356
357void SkGpuDevice::writePixels(const SkBitmap& bitmap, int x, int y,
358 SkCanvas::Config8888 config8888) {
359 SkAutoLockPixels alp(bitmap);
360 if (!bitmap.readyToDraw()) {
361 return;
362 }
363
364 GrPixelConfig config;
365 uint32_t flags;
366 if (SkBitmap::kARGB_8888_Config == bitmap.config()) {
367 config = config8888_to_grconfig_and_flags(config8888, &flags);
368 } else {
369 flags = 0;
370 config= SkBitmapConfig2GrPixelConfig(bitmap.config());
371 }
372
373 fRenderTarget->writePixels(x, y, bitmap.width(), bitmap.height(),
374 config, bitmap.getPixels(), bitmap.rowBytes(), flags);
375}
376
377void SkGpuDevice::onAttachToCanvas(SkCanvas* canvas) {
378 INHERITED::onAttachToCanvas(canvas);
379
380 // Canvas promises that this ptr is valid until onDetachFromCanvas is called
381 fClipData.fClipStack = canvas->getClipStack();
382}
383
384void SkGpuDevice::onDetachFromCanvas() {
385 INHERITED::onDetachFromCanvas();
386 fClipData.fClipStack = NULL;
387}
388
389// call this every draw call, to ensure that the context reflects our state,
390// and not the state from some other canvas/device
391void SkGpuDevice::prepareDraw(const SkDraw& draw, bool forceIdentity) {
392 SkASSERT(NULL != fClipData.fClipStack);
393
394 fContext->setRenderTarget(fRenderTarget);
395
396 SkASSERT(draw.fClipStack && draw.fClipStack == fClipData.fClipStack);
397
398 if (forceIdentity) {
399 fContext->setIdentityMatrix();
400 } else {
401 fContext->setMatrix(*draw.fMatrix);
402 }
403 fClipData.fOrigin = this->getOrigin();
404
405 fContext->setClip(&fClipData);
406
407 DO_DEFERRED_CLEAR();
408}
409
410GrRenderTarget* SkGpuDevice::accessRenderTarget() {
411 DO_DEFERRED_CLEAR();
412 return fRenderTarget;
413}
414
415///////////////////////////////////////////////////////////////////////////////
416
417SK_COMPILE_ASSERT(SkShader::kNone_BitmapType == 0, shader_type_mismatch);
418SK_COMPILE_ASSERT(SkShader::kDefault_BitmapType == 1, shader_type_mismatch);
419SK_COMPILE_ASSERT(SkShader::kRadial_BitmapType == 2, shader_type_mismatch);
420SK_COMPILE_ASSERT(SkShader::kSweep_BitmapType == 3, shader_type_mismatch);
421SK_COMPILE_ASSERT(SkShader::kTwoPointRadial_BitmapType == 4,
422 shader_type_mismatch);
423SK_COMPILE_ASSERT(SkShader::kTwoPointConical_BitmapType == 5,
424 shader_type_mismatch);
425SK_COMPILE_ASSERT(SkShader::kLinear_BitmapType == 6, shader_type_mismatch);
426SK_COMPILE_ASSERT(SkShader::kLast_BitmapType == 6, shader_type_mismatch);
427
428namespace {
429
430// converts a SkPaint to a GrPaint, ignoring the skPaint's shader
431// justAlpha indicates that skPaint's alpha should be used rather than the color
432// Callers may subsequently modify the GrPaint. Setting constantColor indicates
433// that the final paint will draw the same color at every pixel. This allows
434// an optimization where the the color filter can be applied to the skPaint's
435// color once while converting to GrPaint and then ignored.
436inline bool skPaint2GrPaintNoShader(SkGpuDevice* dev,
437 const SkPaint& skPaint,
438 bool justAlpha,
439 bool constantColor,
440 GrPaint* grPaint) {
441
442 grPaint->setDither(skPaint.isDither());
443 grPaint->setAntiAlias(skPaint.isAntiAlias());
444
445 SkXfermode::Coeff sm;
446 SkXfermode::Coeff dm;
447
448 SkXfermode* mode = skPaint.getXfermode();
449 GrEffectRef* xferEffect = NULL;
450 if (SkXfermode::AsNewEffectOrCoeff(mode, &xferEffect, &sm, &dm)) {
451 if (NULL != xferEffect) {
452 grPaint->addColorEffect(xferEffect)->unref();
453 sm = SkXfermode::kOne_Coeff;
454 dm = SkXfermode::kZero_Coeff;
455 }
456 } else {
457 //SkDEBUGCODE(SkDebugf("Unsupported xfer mode.\n");)
458#if 0
459 return false;
460#else
461 // Fall back to src-over
462 sm = SkXfermode::kOne_Coeff;
463 dm = SkXfermode::kISA_Coeff;
464#endif
465 }
466 grPaint->setBlendFunc(sk_blend_to_grblend(sm), sk_blend_to_grblend(dm));
467
468 if (justAlpha) {
469 uint8_t alpha = skPaint.getAlpha();
470 grPaint->setColor(GrColorPackRGBA(alpha, alpha, alpha, alpha));
471 // justAlpha is currently set to true only if there is a texture,
472 // so constantColor should not also be true.
473 SkASSERT(!constantColor);
474 } else {
475 grPaint->setColor(SkColor2GrColor(skPaint.getColor()));
476 }
477
478 SkColorFilter* colorFilter = skPaint.getColorFilter();
479 if (NULL != colorFilter) {
480 // if the source color is a constant then apply the filter here once rather than per pixel
481 // in a shader.
482 if (constantColor) {
483 SkColor filtered = colorFilter->filterColor(skPaint.getColor());
484 grPaint->setColor(SkColor2GrColor(filtered));
485 } else {
486 SkAutoTUnref<GrEffectRef> effect(colorFilter->asNewEffect(dev->context()));
487 if (NULL != effect.get()) {
488 grPaint->addColorEffect(effect);
489 }
490 }
491 }
492
493 return true;
494}
495
496// This function is similar to skPaint2GrPaintNoShader but also converts
497// skPaint's shader to a GrTexture/GrEffectStage if possible. The texture to
498// be used is set on grPaint and returned in param act. constantColor has the
499// same meaning as in skPaint2GrPaintNoShader.
500inline bool skPaint2GrPaintShader(SkGpuDevice* dev,
501 const SkPaint& skPaint,
502 bool constantColor,
503 GrPaint* grPaint) {
504 SkShader* shader = skPaint.getShader();
505 if (NULL == shader) {
506 return skPaint2GrPaintNoShader(dev, skPaint, false, constantColor, grPaint);
507 }
508
commit-bot@chromium.org60770572014-01-13 15:57:05 +0000509 // SkShader::asNewEffect() may do offscreen rendering. Setup default drawing state and require
510 // the shader to set a render target .
skia.committer@gmail.com11a253b2013-11-12 07:02:05 +0000511 GrContext::AutoWideOpenIdentityDraw awo(dev->context(), NULL);
skia.committer@gmail.com11a253b2013-11-12 07:02:05 +0000512
513 // setup the shader as the first color effect on the paint
514 SkAutoTUnref<GrEffectRef> effect(shader->asNewEffect(dev->context(), skPaint));
515 if (NULL != effect.get()) {
516 grPaint->addColorEffect(effect);
517 // Now setup the rest of the paint.
518 return skPaint2GrPaintNoShader(dev, skPaint, true, false, grPaint);
519 } else {
520 // We still don't have SkColorShader::asNewEffect() implemented.
521 SkShader::GradientInfo info;
522 SkColor color;
523
524 info.fColors = &color;
525 info.fColorOffsets = NULL;
526 info.fColorCount = 1;
527 if (SkShader::kColor_GradientType == shader->asAGradient(&info)) {
528 SkPaint copy(skPaint);
529 copy.setShader(NULL);
530 // modulate the paint alpha by the shader's solid color alpha
531 U8CPU newA = SkMulDiv255Round(SkColorGetA(color), copy.getAlpha());
532 copy.setColor(SkColorSetA(color, newA));
533 return skPaint2GrPaintNoShader(dev, copy, false, constantColor, grPaint);
534 } else {
535 return false;
536 }
537 }
538}
539}
540
541///////////////////////////////////////////////////////////////////////////////
skia.committer@gmail.com11a253b2013-11-12 07:02:05 +0000542
543SkBitmap::Config SkGpuDevice::config() const {
544 if (NULL == fRenderTarget) {
545 return SkBitmap::kNo_Config;
546 }
547
548 bool isOpaque;
549 return grConfig2skConfig(fRenderTarget->config(), &isOpaque);
550}
551
552void SkGpuDevice::clear(SkColor color) {
553 SkIRect rect = SkIRect::MakeWH(this->width(), this->height());
554 fContext->clear(&rect, SkColor2GrColor(color), true, fRenderTarget);
555 fNeedClear = false;
556}
557
558void SkGpuDevice::drawPaint(const SkDraw& draw, const SkPaint& paint) {
559 CHECK_SHOULD_DRAW(draw, false);
560
561 GrPaint grPaint;
562 if (!skPaint2GrPaintShader(this, paint, true, &grPaint)) {
563 return;
564 }
565
566 fContext->drawPaint(grPaint);
567}
568
569// must be in SkCanvas::PointMode order
570static const GrPrimitiveType gPointMode2PrimtiveType[] = {
571 kPoints_GrPrimitiveType,
572 kLines_GrPrimitiveType,
573 kLineStrip_GrPrimitiveType
574};
575
576void SkGpuDevice::drawPoints(const SkDraw& draw, SkCanvas::PointMode mode,
577 size_t count, const SkPoint pts[], const SkPaint& paint) {
578 CHECK_FOR_ANNOTATION(paint);
579 CHECK_SHOULD_DRAW(draw, false);
580
581 SkScalar width = paint.getStrokeWidth();
582 if (width < 0) {
583 return;
584 }
585
586 // we only handle hairlines and paints without path effects or mask filters,
587 // else we let the SkDraw call our drawPath()
588 if (width > 0 || paint.getPathEffect() || paint.getMaskFilter()) {
589 draw.drawPoints(mode, count, pts, paint, true);
590 return;
591 }
592
593 GrPaint grPaint;
594 if (!skPaint2GrPaintShader(this, paint, true, &grPaint)) {
595 return;
596 }
597
598 fContext->drawVertices(grPaint,
599 gPointMode2PrimtiveType[mode],
robertphillips@google.coma4662862013-11-21 14:24:16 +0000600 SkToS32(count),
skia.committer@gmail.com11a253b2013-11-12 07:02:05 +0000601 (GrPoint*)pts,
602 NULL,
603 NULL,
604 NULL,
605 0);
606}
607
608///////////////////////////////////////////////////////////////////////////////
609
610void SkGpuDevice::drawRect(const SkDraw& draw, const SkRect& rect,
611 const SkPaint& paint) {
612 CHECK_FOR_ANNOTATION(paint);
613 CHECK_SHOULD_DRAW(draw, false);
614
615 bool doStroke = paint.getStyle() != SkPaint::kFill_Style;
616 SkScalar width = paint.getStrokeWidth();
617
618 /*
619 We have special code for hairline strokes, miter-strokes, bevel-stroke
620 and fills. Anything else we just call our path code.
621 */
622 bool usePath = doStroke && width > 0 &&
623 (paint.getStrokeJoin() == SkPaint::kRound_Join ||
624 (paint.getStrokeJoin() == SkPaint::kBevel_Join && rect.isEmpty()));
625 // another two reasons we might need to call drawPath...
626 if (paint.getMaskFilter() || paint.getPathEffect()) {
627 usePath = true;
628 }
629 if (!usePath && paint.isAntiAlias() && !fContext->getMatrix().rectStaysRect()) {
630#if defined(SHADER_AA_FILL_RECT) || !defined(IGNORE_ROT_AA_RECT_OPT)
631 if (doStroke) {
632#endif
633 usePath = true;
634#if defined(SHADER_AA_FILL_RECT) || !defined(IGNORE_ROT_AA_RECT_OPT)
635 } else {
636 usePath = !fContext->getMatrix().preservesRightAngles();
637 }
638#endif
639 }
640 // until we can both stroke and fill rectangles
641 if (paint.getStyle() == SkPaint::kStrokeAndFill_Style) {
642 usePath = true;
643 }
644
645 if (usePath) {
646 SkPath path;
647 path.addRect(rect);
648 this->drawPath(draw, path, paint, NULL, true);
649 return;
650 }
651
652 GrPaint grPaint;
653 if (!skPaint2GrPaintShader(this, paint, true, &grPaint)) {
654 return;
655 }
656
657 if (!doStroke) {
658 fContext->drawRect(grPaint, rect);
659 } else {
660 SkStrokeRec stroke(paint);
661 fContext->drawRect(grPaint, rect, &stroke);
662 }
663}
664
665///////////////////////////////////////////////////////////////////////////////
666
667void SkGpuDevice::drawRRect(const SkDraw& draw, const SkRRect& rect,
668 const SkPaint& paint) {
669 CHECK_FOR_ANNOTATION(paint);
670 CHECK_SHOULD_DRAW(draw, false);
671
672 bool usePath = !rect.isSimple();
673 // another two reasons we might need to call drawPath...
674 if (paint.getMaskFilter() || paint.getPathEffect()) {
675 usePath = true;
676 }
677 // until we can rotate rrects...
678 if (!usePath && !fContext->getMatrix().rectStaysRect()) {
679 usePath = true;
680 }
681
682 if (usePath) {
683 SkPath path;
684 path.addRRect(rect);
685 this->drawPath(draw, path, paint, NULL, true);
686 return;
687 }
688
689 GrPaint grPaint;
690 if (!skPaint2GrPaintShader(this, paint, true, &grPaint)) {
691 return;
692 }
693
694 SkStrokeRec stroke(paint);
695 fContext->drawRRect(grPaint, rect, stroke);
696}
697
698///////////////////////////////////////////////////////////////////////////////
699
700void SkGpuDevice::drawOval(const SkDraw& draw, const SkRect& oval,
701 const SkPaint& paint) {
702 CHECK_FOR_ANNOTATION(paint);
703 CHECK_SHOULD_DRAW(draw, false);
704
705 bool usePath = false;
706 // some basic reasons we might need to call drawPath...
707 if (paint.getMaskFilter() || paint.getPathEffect()) {
708 usePath = true;
709 }
710
711 if (usePath) {
712 SkPath path;
713 path.addOval(oval);
714 this->drawPath(draw, path, paint, NULL, true);
715 return;
716 }
717
718 GrPaint grPaint;
719 if (!skPaint2GrPaintShader(this, paint, true, &grPaint)) {
720 return;
721 }
722 SkStrokeRec stroke(paint);
723
724 fContext->drawOval(grPaint, oval, stroke);
725}
726
727#include "SkMaskFilter.h"
728#include "SkBounder.h"
729
730///////////////////////////////////////////////////////////////////////////////
731
732// helpers for applying mask filters
733namespace {
734
735// Draw a mask using the supplied paint. Since the coverage/geometry
736// is already burnt into the mask this boils down to a rect draw.
737// Return true if the mask was successfully drawn.
738bool draw_mask(GrContext* context, const SkRect& maskRect,
739 GrPaint* grp, GrTexture* mask) {
740 GrContext::AutoMatrix am;
741 if (!am.setIdentity(context, grp)) {
742 return false;
743 }
744
745 SkMatrix matrix;
746 matrix.setTranslate(-maskRect.fLeft, -maskRect.fTop);
747 matrix.postIDiv(mask->width(), mask->height());
748
749 grp->addCoverageEffect(GrSimpleTextureEffect::Create(mask, matrix))->unref();
750 context->drawRect(*grp, maskRect);
751 return true;
752}
753
754bool draw_with_mask_filter(GrContext* context, const SkPath& devPath,
755 SkMaskFilter* filter, const SkRegion& clip, SkBounder* bounder,
756 GrPaint* grp, SkPaint::Style style) {
757 SkMask srcM, dstM;
758
759 if (!SkDraw::DrawToMask(devPath, &clip.getBounds(), filter, &context->getMatrix(), &srcM,
760 SkMask::kComputeBoundsAndRenderImage_CreateMode, style)) {
761 return false;
762 }
763 SkAutoMaskFreeImage autoSrc(srcM.fImage);
764
765 if (!filter->filterMask(&dstM, srcM, context->getMatrix(), NULL)) {
766 return false;
767 }
768 // this will free-up dstM when we're done (allocated in filterMask())
769 SkAutoMaskFreeImage autoDst(dstM.fImage);
770
771 if (clip.quickReject(dstM.fBounds)) {
772 return false;
773 }
774 if (bounder && !bounder->doIRect(dstM.fBounds)) {
775 return false;
776 }
777
778 // we now have a device-aligned 8bit mask in dstM, ready to be drawn using
779 // the current clip (and identity matrix) and GrPaint settings
780 GrTextureDesc desc;
781 desc.fWidth = dstM.fBounds.width();
782 desc.fHeight = dstM.fBounds.height();
783 desc.fConfig = kAlpha_8_GrPixelConfig;
784
785 GrAutoScratchTexture ast(context, desc);
786 GrTexture* texture = ast.texture();
787
788 if (NULL == texture) {
789 return false;
790 }
791 texture->writePixels(0, 0, desc.fWidth, desc.fHeight, desc.fConfig,
792 dstM.fImage, dstM.fRowBytes);
793
794 SkRect maskRect = SkRect::Make(dstM.fBounds);
795
796 return draw_mask(context, maskRect, grp, texture);
797}
798
799// Create a mask of 'devPath' and place the result in 'mask'. Return true on
800// success; false otherwise.
801bool create_mask_GPU(GrContext* context,
802 const SkRect& maskRect,
803 const SkPath& devPath,
804 const SkStrokeRec& stroke,
805 bool doAA,
806 GrAutoScratchTexture* mask) {
807 GrTextureDesc desc;
808 desc.fFlags = kRenderTarget_GrTextureFlagBit;
809 desc.fWidth = SkScalarCeilToInt(maskRect.width());
810 desc.fHeight = SkScalarCeilToInt(maskRect.height());
811 // We actually only need A8, but it often isn't supported as a
812 // render target so default to RGBA_8888
813 desc.fConfig = kRGBA_8888_GrPixelConfig;
814 if (context->isConfigRenderable(kAlpha_8_GrPixelConfig, false)) {
815 desc.fConfig = kAlpha_8_GrPixelConfig;
816 }
817
818 mask->set(context, desc);
819 if (NULL == mask->texture()) {
820 return false;
821 }
822
823 GrTexture* maskTexture = mask->texture();
824 SkRect clipRect = SkRect::MakeWH(maskRect.width(), maskRect.height());
825
826 GrContext::AutoRenderTarget art(context, maskTexture->asRenderTarget());
827 GrContext::AutoClip ac(context, clipRect);
828
829 context->clear(NULL, 0x0, true);
830
831 GrPaint tempPaint;
832 if (doAA) {
833 tempPaint.setAntiAlias(true);
834 // AA uses the "coverage" stages on GrDrawTarget. Coverage with a dst
835 // blend coeff of zero requires dual source blending support in order
836 // to properly blend partially covered pixels. This means the AA
837 // code path may not be taken. So we use a dst blend coeff of ISA. We
838 // could special case AA draws to a dst surface with known alpha=0 to
839 // use a zero dst coeff when dual source blending isn't available.
840 tempPaint.setBlendFunc(kOne_GrBlendCoeff, kISC_GrBlendCoeff);
841 }
842
843 GrContext::AutoMatrix am;
844
845 // Draw the mask into maskTexture with the path's top-left at the origin using tempPaint.
846 SkMatrix translate;
847 translate.setTranslate(-maskRect.fLeft, -maskRect.fTop);
848 am.set(context, translate);
849 context->drawPath(tempPaint, devPath, stroke);
850 return true;
851}
852
853SkBitmap wrap_texture(GrTexture* texture) {
reed@google.combf790232013-12-13 19:45:58 +0000854 SkImageInfo info;
855 texture->asImageInfo(&info);
856
skia.committer@gmail.com11a253b2013-11-12 07:02:05 +0000857 SkBitmap result;
reed@google.combf790232013-12-13 19:45:58 +0000858 result.setConfig(info);
859 result.setPixelRef(SkNEW_ARGS(SkGrPixelRef, (info, texture)))->unref();
skia.committer@gmail.com11a253b2013-11-12 07:02:05 +0000860 return result;
861}
862
863};
864
865void SkGpuDevice::drawPath(const SkDraw& draw, const SkPath& origSrcPath,
866 const SkPaint& paint, const SkMatrix* prePathMatrix,
867 bool pathIsMutable) {
868 CHECK_FOR_ANNOTATION(paint);
869 CHECK_SHOULD_DRAW(draw, false);
870
871 GrPaint grPaint;
872 if (!skPaint2GrPaintShader(this, paint, true, &grPaint)) {
873 return;
874 }
875
skia.committer@gmail.com11a253b2013-11-12 07:02:05 +0000876 // If we have a prematrix, apply it to the path, optimizing for the case
877 // where the original path can in fact be modified in place (even though
878 // its parameter type is const).
879 SkPath* pathPtr = const_cast<SkPath*>(&origSrcPath);
880 SkPath tmpPath, effectPath;
881
882 if (prePathMatrix) {
883 SkPath* result = pathPtr;
884
885 if (!pathIsMutable) {
886 result = &tmpPath;
887 pathIsMutable = true;
888 }
889 // should I push prePathMatrix on our MV stack temporarily, instead
890 // of applying it here? See SkDraw.cpp
891 pathPtr->transform(*prePathMatrix, result);
892 pathPtr = result;
893 }
894 // at this point we're done with prePathMatrix
895 SkDEBUGCODE(prePathMatrix = (const SkMatrix*)0x50FF8001;)
896
897 SkStrokeRec stroke(paint);
898 SkPathEffect* pathEffect = paint.getPathEffect();
899 const SkRect* cullRect = NULL; // TODO: what is our bounds?
900 if (pathEffect && pathEffect->filterPath(&effectPath, *pathPtr, &stroke,
901 cullRect)) {
902 pathPtr = &effectPath;
903 }
904
skia.committer@gmail.com11a253b2013-11-12 07:02:05 +0000905 if (paint.getMaskFilter()) {
906 if (!stroke.isHairlineStyle()) {
907 if (stroke.applyToPath(&tmpPath, *pathPtr)) {
908 pathPtr = &tmpPath;
909 pathIsMutable = true;
910 stroke.setFillStyle();
911 }
912 }
913
914 // avoid possibly allocating a new path in transform if we can
915 SkPath* devPathPtr = pathIsMutable ? pathPtr : &tmpPath;
916
917 // transform the path into device space
918 pathPtr->transform(fContext->getMatrix(), devPathPtr);
919
920 SkRect maskRect;
921 if (paint.getMaskFilter()->canFilterMaskGPU(devPathPtr->getBounds(),
922 draw.fClip->getBounds(),
923 fContext->getMatrix(),
924 &maskRect)) {
commit-bot@chromium.org439ff1b2014-01-13 16:39:39 +0000925 // The context's matrix may change while creating the mask, so save the CTM here to
926 // pass to filterMaskGPU.
927 const SkMatrix ctm = fContext->getMatrix();
928
skia.committer@gmail.com11a253b2013-11-12 07:02:05 +0000929 SkIRect finalIRect;
930 maskRect.roundOut(&finalIRect);
931 if (draw.fClip->quickReject(finalIRect)) {
932 // clipped out
933 return;
934 }
935 if (NULL != draw.fBounder && !draw.fBounder->doIRect(finalIRect)) {
936 // nothing to draw
937 return;
938 }
939
940 GrAutoScratchTexture mask;
941
942 if (create_mask_GPU(fContext, maskRect, *devPathPtr, stroke,
943 grPaint.isAntiAlias(), &mask)) {
944 GrTexture* filtered;
945
commit-bot@chromium.org41bf9302014-01-08 22:25:53 +0000946 if (paint.getMaskFilter()->filterMaskGPU(mask.texture(),
commit-bot@chromium.org439ff1b2014-01-13 16:39:39 +0000947 ctm, maskRect, &filtered, true)) {
skia.committer@gmail.com11a253b2013-11-12 07:02:05 +0000948 // filterMaskGPU gives us ownership of a ref to the result
949 SkAutoTUnref<GrTexture> atu(filtered);
950
951 // If the scratch texture that we used as the filter src also holds the filter
952 // result then we must detach so that this texture isn't recycled for a later
953 // draw.
954 if (filtered == mask.texture()) {
955 mask.detach();
956 filtered->unref(); // detach transfers GrAutoScratchTexture's ref to us.
957 }
958
959 if (draw_mask(fContext, maskRect, &grPaint, filtered)) {
960 // This path is completely drawn
961 return;
962 }
963 }
964 }
965 }
966
967 // draw the mask on the CPU - this is a fallthrough path in case the
968 // GPU path fails
969 SkPaint::Style style = stroke.isHairlineStyle() ? SkPaint::kStroke_Style :
970 SkPaint::kFill_Style;
971 draw_with_mask_filter(fContext, *devPathPtr, paint.getMaskFilter(),
972 *draw.fClip, draw.fBounder, &grPaint, style);
973 return;
974 }
975
976 fContext->drawPath(grPaint, *pathPtr, stroke);
977}
978
979static const int kBmpSmallTileSize = 1 << 10;
980
981static inline int get_tile_count(const SkIRect& srcRect, int tileSize) {
982 int tilesX = (srcRect.fRight / tileSize) - (srcRect.fLeft / tileSize) + 1;
983 int tilesY = (srcRect.fBottom / tileSize) - (srcRect.fTop / tileSize) + 1;
984 return tilesX * tilesY;
985}
986
987static int determine_tile_size(const SkBitmap& bitmap, const SkIRect& src, int maxTileSize) {
988 if (maxTileSize <= kBmpSmallTileSize) {
989 return maxTileSize;
990 }
991
992 size_t maxTileTotalTileSize = get_tile_count(src, maxTileSize);
993 size_t smallTotalTileSize = get_tile_count(src, kBmpSmallTileSize);
994
995 maxTileTotalTileSize *= maxTileSize * maxTileSize;
996 smallTotalTileSize *= kBmpSmallTileSize * kBmpSmallTileSize;
997
998 if (maxTileTotalTileSize > 2 * smallTotalTileSize) {
999 return kBmpSmallTileSize;
1000 } else {
1001 return maxTileSize;
1002 }
1003}
1004
1005// Given a bitmap, an optional src rect, and a context with a clip and matrix determine what
1006// pixels from the bitmap are necessary.
1007static void determine_clipped_src_rect(const GrContext* context,
1008 const SkBitmap& bitmap,
1009 const SkRect* srcRectPtr,
1010 SkIRect* clippedSrcIRect) {
1011 const GrClipData* clip = context->getClip();
1012 clip->getConservativeBounds(context->getRenderTarget(), clippedSrcIRect, NULL);
1013 SkMatrix inv;
1014 if (!context->getMatrix().invert(&inv)) {
1015 clippedSrcIRect->setEmpty();
1016 return;
1017 }
1018 SkRect clippedSrcRect = SkRect::Make(*clippedSrcIRect);
1019 inv.mapRect(&clippedSrcRect);
1020 if (NULL != srcRectPtr) {
commit-bot@chromium.orga7d89c82014-01-13 14:47:00 +00001021 // we've setup src space 0,0 to map to the top left of the src rect.
1022 clippedSrcRect.offset(srcRectPtr->fLeft, srcRectPtr->fTop);
skia.committer@gmail.com11a253b2013-11-12 07:02:05 +00001023 if (!clippedSrcRect.intersect(*srcRectPtr)) {
1024 clippedSrcIRect->setEmpty();
1025 return;
1026 }
1027 }
1028 clippedSrcRect.roundOut(clippedSrcIRect);
1029 SkIRect bmpBounds = SkIRect::MakeWH(bitmap.width(), bitmap.height());
1030 if (!clippedSrcIRect->intersect(bmpBounds)) {
1031 clippedSrcIRect->setEmpty();
1032 }
1033}
1034
1035bool SkGpuDevice::shouldTileBitmap(const SkBitmap& bitmap,
1036 const GrTextureParams& params,
1037 const SkRect* srcRectPtr,
1038 int maxTileSize,
1039 int* tileSize,
1040 SkIRect* clippedSrcRect) const {
1041 // if bitmap is explictly texture backed then just use the texture
1042 if (NULL != bitmap.getTexture()) {
1043 return false;
1044 }
1045
1046 // if it's larger than the max tile size, then we have no choice but tiling.
1047 if (bitmap.width() > maxTileSize || bitmap.height() > maxTileSize) {
1048 determine_clipped_src_rect(fContext, bitmap, srcRectPtr, clippedSrcRect);
1049 *tileSize = determine_tile_size(bitmap, *clippedSrcRect, maxTileSize);
1050 return true;
1051 }
1052
1053 if (bitmap.width() * bitmap.height() < 4 * kBmpSmallTileSize * kBmpSmallTileSize) {
1054 return false;
1055 }
1056
1057 // if the entire texture is already in our cache then no reason to tile it
1058 if (GrIsBitmapInCache(fContext, bitmap, &params)) {
1059 return false;
1060 }
1061
1062 // At this point we know we could do the draw by uploading the entire bitmap
1063 // as a texture. However, if the texture would be large compared to the
1064 // cache size and we don't require most of it for this draw then tile to
1065 // reduce the amount of upload and cache spill.
1066
1067 // assumption here is that sw bitmap size is a good proxy for its size as
1068 // a texture
1069 size_t bmpSize = bitmap.getSize();
1070 size_t cacheSize;
1071 fContext->getTextureCacheLimits(NULL, &cacheSize);
1072 if (bmpSize < cacheSize / 2) {
1073 return false;
1074 }
1075
1076 // Figure out how much of the src we will need based on the src rect and clipping.
1077 determine_clipped_src_rect(fContext, bitmap, srcRectPtr, clippedSrcRect);
1078 *tileSize = kBmpSmallTileSize; // already know whole bitmap fits in one max sized tile.
1079 size_t usedTileBytes = get_tile_count(*clippedSrcRect, kBmpSmallTileSize) *
1080 kBmpSmallTileSize * kBmpSmallTileSize;
1081
1082 return usedTileBytes < 2 * bmpSize;
1083}
1084
commit-bot@chromium.orga7d89c82014-01-13 14:47:00 +00001085void SkGpuDevice::drawBitmap(const SkDraw& origDraw,
skia.committer@gmail.com11a253b2013-11-12 07:02:05 +00001086 const SkBitmap& bitmap,
1087 const SkMatrix& m,
1088 const SkPaint& paint) {
commit-bot@chromium.orga7d89c82014-01-13 14:47:00 +00001089 SkMatrix concat;
1090 SkTCopyOnFirstWrite<SkDraw> draw(origDraw);
1091 if (!m.isIdentity()) {
1092 concat.setConcat(*draw->fMatrix, m);
1093 draw.writable()->fMatrix = &concat;
1094 }
1095 this->drawBitmapCommon(*draw, bitmap, NULL, NULL, paint, SkCanvas::kNone_DrawBitmapRectFlag);
skia.committer@gmail.com11a253b2013-11-12 07:02:05 +00001096}
1097
commit-bot@chromium.orgdec61502013-12-02 22:22:35 +00001098// This method outsets 'iRect' by 'outset' all around and then clamps its extents to
skia.committer@gmail.com11a253b2013-11-12 07:02:05 +00001099// 'clamp'. 'offset' is adjusted to remain positioned over the top-left corner
1100// of 'iRect' for all possible outsets/clamps.
commit-bot@chromium.orgdec61502013-12-02 22:22:35 +00001101static inline void clamped_outset_with_offset(SkIRect* iRect,
1102 int outset,
1103 SkPoint* offset,
1104 const SkIRect& clamp) {
1105 iRect->outset(outset, outset);
skia.committer@gmail.com11a253b2013-11-12 07:02:05 +00001106
commit-bot@chromium.orgdec61502013-12-02 22:22:35 +00001107 int leftClampDelta = clamp.fLeft - iRect->fLeft;
1108 if (leftClampDelta > 0) {
1109 offset->fX -= outset - leftClampDelta;
skia.committer@gmail.com11a253b2013-11-12 07:02:05 +00001110 iRect->fLeft = clamp.fLeft;
1111 } else {
commit-bot@chromium.orgdec61502013-12-02 22:22:35 +00001112 offset->fX -= outset;
skia.committer@gmail.com11a253b2013-11-12 07:02:05 +00001113 }
commit-bot@chromium.orgdec61502013-12-02 22:22:35 +00001114
1115 int topClampDelta = clamp.fTop - iRect->fTop;
1116 if (topClampDelta > 0) {
1117 offset->fY -= outset - topClampDelta;
skia.committer@gmail.com11a253b2013-11-12 07:02:05 +00001118 iRect->fTop = clamp.fTop;
1119 } else {
commit-bot@chromium.orgdec61502013-12-02 22:22:35 +00001120 offset->fY -= outset;
skia.committer@gmail.com11a253b2013-11-12 07:02:05 +00001121 }
1122
1123 if (iRect->fRight > clamp.fRight) {
1124 iRect->fRight = clamp.fRight;
1125 }
1126 if (iRect->fBottom > clamp.fBottom) {
1127 iRect->fBottom = clamp.fBottom;
1128 }
1129}
1130
1131void SkGpuDevice::drawBitmapCommon(const SkDraw& draw,
1132 const SkBitmap& bitmap,
1133 const SkRect* srcRectPtr,
commit-bot@chromium.orga7d89c82014-01-13 14:47:00 +00001134 const SkSize* dstSizePtr,
skia.committer@gmail.com11a253b2013-11-12 07:02:05 +00001135 const SkPaint& paint,
1136 SkCanvas::DrawBitmapRectFlags flags) {
1137 CHECK_SHOULD_DRAW(draw, false);
1138
1139 SkRect srcRect;
commit-bot@chromium.orga7d89c82014-01-13 14:47:00 +00001140 SkSize dstSize;
commit-bot@chromium.orgdec61502013-12-02 22:22:35 +00001141 // If there is no src rect, or the src rect contains the entire bitmap then we're effectively
1142 // in the (easier) bleed case, so update flags.
skia.committer@gmail.com11a253b2013-11-12 07:02:05 +00001143 if (NULL == srcRectPtr) {
commit-bot@chromium.orga7d89c82014-01-13 14:47:00 +00001144 SkScalar w = SkIntToScalar(bitmap.width());
1145 SkScalar h = SkIntToScalar(bitmap.height());
1146 dstSize.fWidth = w;
1147 dstSize.fHeight = h;
1148 srcRect.set(0, 0, w, h);
commit-bot@chromium.orgdec61502013-12-02 22:22:35 +00001149 flags = (SkCanvas::DrawBitmapRectFlags) (flags | SkCanvas::kBleed_DrawBitmapRectFlag);
skia.committer@gmail.com11a253b2013-11-12 07:02:05 +00001150 } else {
commit-bot@chromium.orga7d89c82014-01-13 14:47:00 +00001151 SkASSERT(NULL != dstSizePtr);
skia.committer@gmail.com11a253b2013-11-12 07:02:05 +00001152 srcRect = *srcRectPtr;
commit-bot@chromium.orga7d89c82014-01-13 14:47:00 +00001153 dstSize = *dstSizePtr;
commit-bot@chromium.orgdec61502013-12-02 22:22:35 +00001154 if (srcRect.fLeft <= 0 && srcRect.fTop <= 0 &&
1155 srcRect.fRight >= bitmap.width() && srcRect.fBottom >= bitmap.height()) {
1156 flags = (SkCanvas::DrawBitmapRectFlags) (flags | SkCanvas::kBleed_DrawBitmapRectFlag);
1157 }
skia.committer@gmail.com11a253b2013-11-12 07:02:05 +00001158 }
1159
1160 if (paint.getMaskFilter()){
1161 // Convert the bitmap to a shader so that the rect can be drawn
1162 // through drawRect, which supports mask filters.
skia.committer@gmail.com11a253b2013-11-12 07:02:05 +00001163 SkBitmap tmp; // subset of bitmap, if necessary
1164 const SkBitmap* bitmapPtr = &bitmap;
commit-bot@chromium.orga7d89c82014-01-13 14:47:00 +00001165 SkMatrix localM;
skia.committer@gmail.com11a253b2013-11-12 07:02:05 +00001166 if (NULL != srcRectPtr) {
commit-bot@chromium.orga7d89c82014-01-13 14:47:00 +00001167 localM.setTranslate(-srcRectPtr->fLeft, -srcRectPtr->fTop);
1168 localM.postScale(dstSize.fWidth / srcRectPtr->width(),
1169 dstSize.fHeight / srcRectPtr->height());
commit-bot@chromium.orgd6ca4ac2013-11-22 20:34:59 +00001170 // In bleed mode we position and trim the bitmap based on the src rect which is
1171 // already accounted for in 'm' and 'srcRect'. In clamp mode we need to chop out
1172 // the desired portion of the bitmap and then update 'm' and 'srcRect' to
1173 // compensate.
1174 if (!(SkCanvas::kBleed_DrawBitmapRectFlag & flags)) {
1175 SkIRect iSrc;
1176 srcRect.roundOut(&iSrc);
skia.committer@gmail.com11a253b2013-11-12 07:02:05 +00001177
commit-bot@chromium.orgd6ca4ac2013-11-22 20:34:59 +00001178 SkPoint offset = SkPoint::Make(SkIntToScalar(iSrc.fLeft),
1179 SkIntToScalar(iSrc.fTop));
skia.committer@gmail.com11a253b2013-11-12 07:02:05 +00001180
commit-bot@chromium.orgd6ca4ac2013-11-22 20:34:59 +00001181 if (!bitmap.extractSubset(&tmp, iSrc)) {
1182 return; // extraction failed
1183 }
1184 bitmapPtr = &tmp;
1185 srcRect.offset(-offset.fX, -offset.fY);
commit-bot@chromium.orga7d89c82014-01-13 14:47:00 +00001186
commit-bot@chromium.orgd6ca4ac2013-11-22 20:34:59 +00001187 // The source rect has changed so update the matrix
commit-bot@chromium.orga7d89c82014-01-13 14:47:00 +00001188 localM.preTranslate(offset.fX, offset.fY);
skia.committer@gmail.com11a253b2013-11-12 07:02:05 +00001189 }
commit-bot@chromium.orga7d89c82014-01-13 14:47:00 +00001190 } else {
1191 localM.reset();
skia.committer@gmail.com11a253b2013-11-12 07:02:05 +00001192 }
1193
commit-bot@chromium.orga7d89c82014-01-13 14:47:00 +00001194 SkPaint paintWithShader(paint);
1195 paintWithShader.setShader(SkShader::CreateBitmapShader(*bitmapPtr,
skia.committer@gmail.com11a253b2013-11-12 07:02:05 +00001196 SkShader::kClamp_TileMode, SkShader::kClamp_TileMode))->unref();
commit-bot@chromium.orga7d89c82014-01-13 14:47:00 +00001197 paintWithShader.getShader()->setLocalMatrix(localM);
1198 SkRect dstRect = {0, 0, dstSize.fWidth, dstSize.fHeight};
1199 this->drawRect(draw, dstRect, paintWithShader);
skia.committer@gmail.com11a253b2013-11-12 07:02:05 +00001200
1201 return;
1202 }
1203
commit-bot@chromium.orga7d89c82014-01-13 14:47:00 +00001204 // If there is no mask filter than it is OK to handle the src rect -> dst rect scaling using
1205 // the view matrix rather than a local matrix.
1206 SkMatrix m;
1207 m.setScale(dstSize.fWidth / srcRect.width(),
1208 dstSize.fHeight / srcRect.height());
skia.committer@gmail.com11a253b2013-11-12 07:02:05 +00001209 fContext->concatMatrix(m);
1210
1211 GrTextureParams params;
1212 SkPaint::FilterLevel paintFilterLevel = paint.getFilterLevel();
1213 GrTextureParams::FilterMode textureFilterMode;
commit-bot@chromium.orgdec61502013-12-02 22:22:35 +00001214
1215 int tileFilterPad;
1216 bool doBicubic = false;
1217
skia.committer@gmail.com11a253b2013-11-12 07:02:05 +00001218 switch(paintFilterLevel) {
1219 case SkPaint::kNone_FilterLevel:
commit-bot@chromium.orgdec61502013-12-02 22:22:35 +00001220 tileFilterPad = 0;
skia.committer@gmail.com11a253b2013-11-12 07:02:05 +00001221 textureFilterMode = GrTextureParams::kNone_FilterMode;
1222 break;
1223 case SkPaint::kLow_FilterLevel:
commit-bot@chromium.orgdec61502013-12-02 22:22:35 +00001224 tileFilterPad = 1;
skia.committer@gmail.com11a253b2013-11-12 07:02:05 +00001225 textureFilterMode = GrTextureParams::kBilerp_FilterMode;
1226 break;
1227 case SkPaint::kMedium_FilterLevel:
commit-bot@chromium.orgdec61502013-12-02 22:22:35 +00001228 tileFilterPad = 1;
commit-bot@chromium.org79b7eee2013-12-16 21:02:29 +00001229 if (fContext->getMatrix().getMinStretch() < SK_Scalar1) {
1230 textureFilterMode = GrTextureParams::kMipMap_FilterMode;
1231 } else {
1232 // Don't trigger MIP level generation unnecessarily.
1233 textureFilterMode = GrTextureParams::kBilerp_FilterMode;
1234 }
skia.committer@gmail.com11a253b2013-11-12 07:02:05 +00001235 break;
commit-bot@chromium.org79b7eee2013-12-16 21:02:29 +00001236 case SkPaint::kHigh_FilterLevel:
commit-bot@chromium.orgcea9abb2013-12-09 19:15:37 +00001237 // Minification can look bad with the bicubic effect.
commit-bot@chromium.org7d7f3142013-12-16 15:18:11 +00001238 if (fContext->getMatrix().getMinStretch() >= SK_Scalar1) {
commit-bot@chromium.orgdec61502013-12-02 22:22:35 +00001239 // We will install an effect that does the filtering in the shader.
1240 textureFilterMode = GrTextureParams::kNone_FilterMode;
1241 tileFilterPad = GrBicubicEffect::kFilterTexelPad;
1242 doBicubic = true;
1243 } else {
commit-bot@chromium.orgdec61502013-12-02 22:22:35 +00001244 textureFilterMode = GrTextureParams::kMipMap_FilterMode;
1245 tileFilterPad = 1;
1246 }
skia.committer@gmail.com11a253b2013-11-12 07:02:05 +00001247 break;
1248 default:
1249 SkErrorInternals::SetError( kInvalidPaint_SkError,
1250 "Sorry, I don't understand the filtering "
1251 "mode you asked for. Falling back to "
1252 "MIPMaps.");
commit-bot@chromium.orgdec61502013-12-02 22:22:35 +00001253 tileFilterPad = 1;
skia.committer@gmail.com11a253b2013-11-12 07:02:05 +00001254 textureFilterMode = GrTextureParams::kMipMap_FilterMode;
1255 break;
skia.committer@gmail.com11a253b2013-11-12 07:02:05 +00001256 }
1257
1258 params.setFilterMode(textureFilterMode);
1259
commit-bot@chromium.orgdec61502013-12-02 22:22:35 +00001260 int maxTileSize = fContext->getMaxTextureSize() - 2 * tileFilterPad;
skia.committer@gmail.com11a253b2013-11-12 07:02:05 +00001261 int tileSize;
1262
1263 SkIRect clippedSrcRect;
1264 if (this->shouldTileBitmap(bitmap, params, srcRectPtr, maxTileSize, &tileSize,
1265 &clippedSrcRect)) {
commit-bot@chromium.orgdec61502013-12-02 22:22:35 +00001266 this->drawTiledBitmap(bitmap, srcRect, clippedSrcRect, params, paint, flags, tileSize,
1267 doBicubic);
skia.committer@gmail.com11a253b2013-11-12 07:02:05 +00001268 } else {
1269 // take the simple case
commit-bot@chromium.orgdec61502013-12-02 22:22:35 +00001270 this->internalDrawBitmap(bitmap, srcRect, params, paint, flags, doBicubic);
skia.committer@gmail.com11a253b2013-11-12 07:02:05 +00001271 }
1272}
1273
1274// Break 'bitmap' into several tiles to draw it since it has already
1275// been determined to be too large to fit in VRAM
1276void SkGpuDevice::drawTiledBitmap(const SkBitmap& bitmap,
1277 const SkRect& srcRect,
1278 const SkIRect& clippedSrcIRect,
1279 const GrTextureParams& params,
1280 const SkPaint& paint,
1281 SkCanvas::DrawBitmapRectFlags flags,
commit-bot@chromium.orgdec61502013-12-02 22:22:35 +00001282 int tileSize,
1283 bool bicubic) {
skia.committer@gmail.com11a253b2013-11-12 07:02:05 +00001284 SkRect clippedSrcRect = SkRect::Make(clippedSrcIRect);
1285
1286 int nx = bitmap.width() / tileSize;
1287 int ny = bitmap.height() / tileSize;
1288 for (int x = 0; x <= nx; x++) {
1289 for (int y = 0; y <= ny; y++) {
1290 SkRect tileR;
1291 tileR.set(SkIntToScalar(x * tileSize),
1292 SkIntToScalar(y * tileSize),
1293 SkIntToScalar((x + 1) * tileSize),
1294 SkIntToScalar((y + 1) * tileSize));
1295
1296 if (!SkRect::Intersects(tileR, clippedSrcRect)) {
1297 continue;
1298 }
1299
1300 if (!tileR.intersect(srcRect)) {
1301 continue;
1302 }
1303
1304 SkBitmap tmpB;
1305 SkIRect iTileR;
1306 tileR.roundOut(&iTileR);
1307 SkPoint offset = SkPoint::Make(SkIntToScalar(iTileR.fLeft),
1308 SkIntToScalar(iTileR.fTop));
1309
commit-bot@chromium.orga7d89c82014-01-13 14:47:00 +00001310 // Adjust the context matrix to draw at the right x,y in device space
1311 SkMatrix tmpM;
1312 GrContext::AutoMatrix am;
1313 tmpM.setTranslate(offset.fX - srcRect.fLeft, offset.fY - srcRect.fTop);
1314 am.setPreConcat(fContext, tmpM);
1315
commit-bot@chromium.orgdec61502013-12-02 22:22:35 +00001316 if (SkPaint::kNone_FilterLevel != paint.getFilterLevel() || bicubic) {
skia.committer@gmail.com11a253b2013-11-12 07:02:05 +00001317 SkIRect iClampRect;
1318
1319 if (SkCanvas::kBleed_DrawBitmapRectFlag & flags) {
1320 // In bleed mode we want to always expand the tile on all edges
1321 // but stay within the bitmap bounds
1322 iClampRect = SkIRect::MakeWH(bitmap.width(), bitmap.height());
1323 } else {
1324 // In texture-domain/clamp mode we only want to expand the
1325 // tile on edges interior to "srcRect" (i.e., we want to
1326 // not bleed across the original clamped edges)
1327 srcRect.roundOut(&iClampRect);
1328 }
commit-bot@chromium.orgdec61502013-12-02 22:22:35 +00001329 int outset = bicubic ? GrBicubicEffect::kFilterTexelPad : 1;
1330 clamped_outset_with_offset(&iTileR, outset, &offset, iClampRect);
skia.committer@gmail.com11a253b2013-11-12 07:02:05 +00001331 }
1332
1333 if (bitmap.extractSubset(&tmpB, iTileR)) {
1334 // now offset it to make it "local" to our tmp bitmap
1335 tileR.offset(-offset.fX, -offset.fY);
commit-bot@chromium.orga7d89c82014-01-13 14:47:00 +00001336
commit-bot@chromium.orgdec61502013-12-02 22:22:35 +00001337 this->internalDrawBitmap(tmpB, tileR, params, paint, flags, bicubic);
skia.committer@gmail.com11a253b2013-11-12 07:02:05 +00001338 }
1339 }
1340 }
1341}
1342
1343static bool has_aligned_samples(const SkRect& srcRect,
1344 const SkRect& transformedRect) {
1345 // detect pixel disalignment
1346 if (SkScalarAbs(SkScalarRoundToScalar(transformedRect.left()) -
1347 transformedRect.left()) < COLOR_BLEED_TOLERANCE &&
1348 SkScalarAbs(SkScalarRoundToScalar(transformedRect.top()) -
1349 transformedRect.top()) < COLOR_BLEED_TOLERANCE &&
1350 SkScalarAbs(transformedRect.width() - srcRect.width()) <
1351 COLOR_BLEED_TOLERANCE &&
1352 SkScalarAbs(transformedRect.height() - srcRect.height()) <
1353 COLOR_BLEED_TOLERANCE) {
1354 return true;
1355 }
1356 return false;
1357}
1358
1359static bool may_color_bleed(const SkRect& srcRect,
1360 const SkRect& transformedRect,
1361 const SkMatrix& m) {
1362 // Only gets called if has_aligned_samples returned false.
1363 // So we can assume that sampling is axis aligned but not texel aligned.
1364 SkASSERT(!has_aligned_samples(srcRect, transformedRect));
1365 SkRect innerSrcRect(srcRect), innerTransformedRect,
1366 outerTransformedRect(transformedRect);
1367 innerSrcRect.inset(SK_ScalarHalf, SK_ScalarHalf);
1368 m.mapRect(&innerTransformedRect, innerSrcRect);
1369
1370 // The gap between outerTransformedRect and innerTransformedRect
1371 // represents the projection of the source border area, which is
1372 // problematic for color bleeding. We must check whether any
1373 // destination pixels sample the border area.
1374 outerTransformedRect.inset(COLOR_BLEED_TOLERANCE, COLOR_BLEED_TOLERANCE);
1375 innerTransformedRect.outset(COLOR_BLEED_TOLERANCE, COLOR_BLEED_TOLERANCE);
1376 SkIRect outer, inner;
1377 outerTransformedRect.round(&outer);
1378 innerTransformedRect.round(&inner);
1379 // If the inner and outer rects round to the same result, it means the
1380 // border does not overlap any pixel centers. Yay!
1381 return inner != outer;
1382}
1383
1384
1385/*
1386 * This is called by drawBitmap(), which has to handle images that may be too
1387 * large to be represented by a single texture.
1388 *
1389 * internalDrawBitmap assumes that the specified bitmap will fit in a texture
1390 * and that non-texture portion of the GrPaint has already been setup.
1391 */
1392void SkGpuDevice::internalDrawBitmap(const SkBitmap& bitmap,
1393 const SkRect& srcRect,
1394 const GrTextureParams& params,
1395 const SkPaint& paint,
commit-bot@chromium.orgdec61502013-12-02 22:22:35 +00001396 SkCanvas::DrawBitmapRectFlags flags,
1397 bool bicubic) {
skia.committer@gmail.com11a253b2013-11-12 07:02:05 +00001398 SkASSERT(bitmap.width() <= fContext->getMaxTextureSize() &&
1399 bitmap.height() <= fContext->getMaxTextureSize());
1400
1401 GrTexture* texture;
1402 SkAutoCachedTexture act(this, bitmap, &params, &texture);
1403 if (NULL == texture) {
1404 return;
1405 }
1406
commit-bot@chromium.orga7d89c82014-01-13 14:47:00 +00001407 SkRect dstRect = {0, 0, srcRect.width(), srcRect.height() };
skia.committer@gmail.com11a253b2013-11-12 07:02:05 +00001408 SkRect paintRect;
1409 SkScalar wInv = SkScalarInvert(SkIntToScalar(texture->width()));
1410 SkScalar hInv = SkScalarInvert(SkIntToScalar(texture->height()));
1411 paintRect.setLTRB(SkScalarMul(srcRect.fLeft, wInv),
1412 SkScalarMul(srcRect.fTop, hInv),
1413 SkScalarMul(srcRect.fRight, wInv),
1414 SkScalarMul(srcRect.fBottom, hInv));
1415
1416 bool needsTextureDomain = false;
1417 if (!(flags & SkCanvas::kBleed_DrawBitmapRectFlag) &&
commit-bot@chromium.org7d7f3142013-12-16 15:18:11 +00001418 (bicubic || params.filterMode() != GrTextureParams::kNone_FilterMode)) {
1419 // Need texture domain if drawing a sub rect
skia.committer@gmail.com11a253b2013-11-12 07:02:05 +00001420 needsTextureDomain = srcRect.width() < bitmap.width() ||
1421 srcRect.height() < bitmap.height();
commit-bot@chromium.org7d7f3142013-12-16 15:18:11 +00001422 if (!bicubic && needsTextureDomain && fContext->getMatrix().rectStaysRect()) {
skia.committer@gmail.com11a253b2013-11-12 07:02:05 +00001423 const SkMatrix& matrix = fContext->getMatrix();
1424 // sampling is axis-aligned
1425 SkRect transformedRect;
1426 matrix.mapRect(&transformedRect, srcRect);
1427
1428 if (has_aligned_samples(srcRect, transformedRect)) {
1429 // We could also turn off filtering here (but we already did a cache lookup with
1430 // params).
1431 needsTextureDomain = false;
1432 } else {
1433 needsTextureDomain = may_color_bleed(srcRect, transformedRect, matrix);
1434 }
1435 }
1436 }
1437
1438 SkRect textureDomain = SkRect::MakeEmpty();
1439 SkAutoTUnref<GrEffectRef> effect;
1440 if (needsTextureDomain) {
1441 // Use a constrained texture domain to avoid color bleeding
1442 SkScalar left, top, right, bottom;
1443 if (srcRect.width() > SK_Scalar1) {
1444 SkScalar border = SK_ScalarHalf / texture->width();
1445 left = paintRect.left() + border;
1446 right = paintRect.right() - border;
1447 } else {
1448 left = right = SkScalarHalf(paintRect.left() + paintRect.right());
1449 }
1450 if (srcRect.height() > SK_Scalar1) {
1451 SkScalar border = SK_ScalarHalf / texture->height();
1452 top = paintRect.top() + border;
1453 bottom = paintRect.bottom() - border;
1454 } else {
1455 top = bottom = SkScalarHalf(paintRect.top() + paintRect.bottom());
1456 }
1457 textureDomain.setLTRB(left, top, right, bottom);
commit-bot@chromium.org7d7f3142013-12-16 15:18:11 +00001458 if (bicubic) {
1459 effect.reset(GrBicubicEffect::Create(texture, SkMatrix::I(), textureDomain));
1460 } else {
1461 effect.reset(GrTextureDomainEffect::Create(texture,
1462 SkMatrix::I(),
1463 textureDomain,
1464 GrTextureDomain::kClamp_Mode,
1465 params.filterMode()));
1466 }
commit-bot@chromium.orgdec61502013-12-02 22:22:35 +00001467 } else if (bicubic) {
commit-bot@chromium.orgbc91fd72013-12-10 12:53:39 +00001468 SkASSERT(GrTextureParams::kNone_FilterMode == params.filterMode());
1469 SkShader::TileMode tileModes[2] = { params.getTileModeX(), params.getTileModeY() };
1470 effect.reset(GrBicubicEffect::Create(texture, SkMatrix::I(), tileModes));
skia.committer@gmail.com11a253b2013-11-12 07:02:05 +00001471 } else {
1472 effect.reset(GrSimpleTextureEffect::Create(texture, SkMatrix::I(), params));
1473 }
1474
1475 // Construct a GrPaint by setting the bitmap texture as the first effect and then configuring
1476 // the rest from the SkPaint.
1477 GrPaint grPaint;
1478 grPaint.addColorEffect(effect);
1479 bool alphaOnly = !(SkBitmap::kA8_Config == bitmap.config());
1480 if (!skPaint2GrPaintNoShader(this, paint, alphaOnly, false, &grPaint)) {
1481 return;
1482 }
1483
1484 fContext->drawRectToRect(grPaint, dstRect, paintRect, NULL);
1485}
1486
1487static bool filter_texture(SkBaseDevice* device, GrContext* context,
1488 GrTexture* texture, SkImageFilter* filter,
1489 int w, int h, const SkMatrix& ctm, SkBitmap* result,
1490 SkIPoint* offset) {
1491 SkASSERT(filter);
1492 SkDeviceImageFilterProxy proxy(device);
1493
1494 if (filter->canFilterImageGPU()) {
1495 // Save the render target and set it to NULL, so we don't accidentally draw to it in the
1496 // filter. Also set the clip wide open and the matrix to identity.
1497 GrContext::AutoWideOpenIdentityDraw awo(context, NULL);
1498 return filter->filterImageGPU(&proxy, wrap_texture(texture), ctm, result, offset);
1499 } else {
1500 return false;
1501 }
1502}
1503
1504void SkGpuDevice::drawSprite(const SkDraw& draw, const SkBitmap& bitmap,
1505 int left, int top, const SkPaint& paint) {
1506 // drawSprite is defined to be in device coords.
1507 CHECK_SHOULD_DRAW(draw, true);
1508
1509 SkAutoLockPixels alp(bitmap, !bitmap.getTexture());
1510 if (!bitmap.getTexture() && !bitmap.readyToDraw()) {
1511 return;
1512 }
1513
1514 int w = bitmap.width();
1515 int h = bitmap.height();
1516
1517 GrTexture* texture;
1518 // draw sprite uses the default texture params
1519 SkAutoCachedTexture act(this, bitmap, NULL, &texture);
1520
1521 SkImageFilter* filter = paint.getImageFilter();
skia.committer@gmail.com11a253b2013-11-12 07:02:05 +00001522 // This bitmap will own the filtered result as a texture.
1523 SkBitmap filteredBitmap;
1524
1525 if (NULL != filter) {
senorblanco@chromium.org6776b822014-01-03 21:48:22 +00001526 SkIPoint offset = SkIPoint::Make(0, 0);
skia.committer@gmail.com11a253b2013-11-12 07:02:05 +00001527 SkMatrix matrix(*draw.fMatrix);
1528 matrix.postTranslate(SkIntToScalar(-left), SkIntToScalar(-top));
1529 if (filter_texture(this, fContext, texture, filter, w, h, matrix, &filteredBitmap,
1530 &offset)) {
1531 texture = (GrTexture*) filteredBitmap.getTexture();
1532 w = filteredBitmap.width();
1533 h = filteredBitmap.height();
senorblanco@chromium.org6776b822014-01-03 21:48:22 +00001534 left += offset.x();
1535 top += offset.y();
skia.committer@gmail.com11a253b2013-11-12 07:02:05 +00001536 } else {
1537 return;
1538 }
1539 }
1540
1541 GrPaint grPaint;
1542 grPaint.addColorTextureEffect(texture, SkMatrix::I());
1543
1544 if(!skPaint2GrPaintNoShader(this, paint, true, false, &grPaint)) {
1545 return;
1546 }
1547
1548 fContext->drawRectToRect(grPaint,
senorblanco@chromium.org6776b822014-01-03 21:48:22 +00001549 SkRect::MakeXYWH(SkIntToScalar(left),
1550 SkIntToScalar(top),
skia.committer@gmail.com11a253b2013-11-12 07:02:05 +00001551 SkIntToScalar(w),
1552 SkIntToScalar(h)),
1553 SkRect::MakeXYWH(0,
1554 0,
1555 SK_Scalar1 * w / texture->width(),
1556 SK_Scalar1 * h / texture->height()));
1557}
1558
commit-bot@chromium.orga7d89c82014-01-13 14:47:00 +00001559void SkGpuDevice::drawBitmapRect(const SkDraw& origDraw, const SkBitmap& bitmap,
skia.committer@gmail.com11a253b2013-11-12 07:02:05 +00001560 const SkRect* src, const SkRect& dst,
1561 const SkPaint& paint,
1562 SkCanvas::DrawBitmapRectFlags flags) {
1563 SkMatrix matrix;
1564 SkRect bitmapBounds, tmpSrc;
1565
1566 bitmapBounds.set(0, 0,
1567 SkIntToScalar(bitmap.width()),
1568 SkIntToScalar(bitmap.height()));
1569
1570 // Compute matrix from the two rectangles
1571 if (NULL != src) {
1572 tmpSrc = *src;
1573 } else {
1574 tmpSrc = bitmapBounds;
1575 }
commit-bot@chromium.orga7d89c82014-01-13 14:47:00 +00001576
skia.committer@gmail.com11a253b2013-11-12 07:02:05 +00001577 matrix.setRectToRect(tmpSrc, dst, SkMatrix::kFill_ScaleToFit);
1578
1579 // clip the tmpSrc to the bounds of the bitmap. No check needed if src==null.
1580 if (NULL != src) {
1581 if (!bitmapBounds.contains(tmpSrc)) {
1582 if (!tmpSrc.intersect(bitmapBounds)) {
1583 return; // nothing to draw
1584 }
1585 }
1586 }
1587
commit-bot@chromium.orga7d89c82014-01-13 14:47:00 +00001588 SkRect tmpDst;
1589 matrix.mapRect(&tmpDst, tmpSrc);
1590
1591 SkTCopyOnFirstWrite<SkDraw> draw(origDraw);
1592 if (0 != tmpDst.fLeft || 0 != tmpDst.fTop) {
1593 // Translate so that tempDst's top left is at the origin.
1594 matrix = *origDraw.fMatrix;
1595 matrix.preTranslate(tmpDst.fLeft, tmpDst.fTop);
1596 draw.writable()->fMatrix = &matrix;
1597 }
1598 SkSize dstSize;
1599 dstSize.fWidth = tmpDst.width();
1600 dstSize.fHeight = tmpDst.height();
1601
1602 this->drawBitmapCommon(*draw, bitmap, &tmpSrc, &dstSize, paint, flags);
skia.committer@gmail.com11a253b2013-11-12 07:02:05 +00001603}
1604
1605void SkGpuDevice::drawDevice(const SkDraw& draw, SkBaseDevice* device,
1606 int x, int y, const SkPaint& paint) {
1607 // clear of the source device must occur before CHECK_SHOULD_DRAW
1608 SkGpuDevice* dev = static_cast<SkGpuDevice*>(device);
1609 if (dev->fNeedClear) {
1610 // TODO: could check here whether we really need to draw at all
1611 dev->clear(0x0);
1612 }
1613
1614 // drawDevice is defined to be in device coords.
1615 CHECK_SHOULD_DRAW(draw, true);
1616
1617 GrRenderTarget* devRT = dev->accessRenderTarget();
1618 GrTexture* devTex;
1619 if (NULL == (devTex = devRT->asTexture())) {
1620 return;
1621 }
1622
1623 const SkBitmap& bm = dev->accessBitmap(false);
1624 int w = bm.width();
1625 int h = bm.height();
1626
1627 SkImageFilter* filter = paint.getImageFilter();
1628 // This bitmap will own the filtered result as a texture.
1629 SkBitmap filteredBitmap;
1630
1631 if (NULL != filter) {
1632 SkIPoint offset = SkIPoint::Make(0, 0);
1633 SkMatrix matrix(*draw.fMatrix);
1634 matrix.postTranslate(SkIntToScalar(-x), SkIntToScalar(-y));
1635 if (filter_texture(this, fContext, devTex, filter, w, h, matrix, &filteredBitmap,
1636 &offset)) {
1637 devTex = filteredBitmap.getTexture();
1638 w = filteredBitmap.width();
1639 h = filteredBitmap.height();
1640 x += offset.fX;
1641 y += offset.fY;
1642 } else {
1643 return;
1644 }
1645 }
1646
1647 GrPaint grPaint;
1648 grPaint.addColorTextureEffect(devTex, SkMatrix::I());
1649
1650 if (!skPaint2GrPaintNoShader(this, paint, true, false, &grPaint)) {
1651 return;
1652 }
1653
1654 SkRect dstRect = SkRect::MakeXYWH(SkIntToScalar(x),
1655 SkIntToScalar(y),
1656 SkIntToScalar(w),
1657 SkIntToScalar(h));
1658
1659 // The device being drawn may not fill up its texture (e.g. saveLayer uses approximate
1660 // scratch texture).
1661 SkRect srcRect = SkRect::MakeWH(SK_Scalar1 * w / devTex->width(),
1662 SK_Scalar1 * h / devTex->height());
1663
1664 fContext->drawRectToRect(grPaint, dstRect, srcRect);
1665}
1666
1667bool SkGpuDevice::canHandleImageFilter(SkImageFilter* filter) {
1668 return filter->canFilterImageGPU();
1669}
1670
1671bool SkGpuDevice::filterImage(SkImageFilter* filter, const SkBitmap& src,
1672 const SkMatrix& ctm,
1673 SkBitmap* result, SkIPoint* offset) {
1674 // want explicitly our impl, so guard against a subclass of us overriding it
1675 if (!this->SkGpuDevice::canHandleImageFilter(filter)) {
1676 return false;
1677 }
1678
1679 SkAutoLockPixels alp(src, !src.getTexture());
1680 if (!src.getTexture() && !src.readyToDraw()) {
1681 return false;
1682 }
1683
1684 GrTexture* texture;
1685 // We assume here that the filter will not attempt to tile the src. Otherwise, this cache lookup
1686 // must be pushed upstack.
1687 SkAutoCachedTexture act(this, src, NULL, &texture);
1688
1689 return filter_texture(this, fContext, texture, filter, src.width(), src.height(), ctm, result,
1690 offset);
1691}
1692
1693///////////////////////////////////////////////////////////////////////////////
1694
1695// must be in SkCanvas::VertexMode order
1696static const GrPrimitiveType gVertexMode2PrimitiveType[] = {
1697 kTriangles_GrPrimitiveType,
1698 kTriangleStrip_GrPrimitiveType,
1699 kTriangleFan_GrPrimitiveType,
1700};
1701
1702void SkGpuDevice::drawVertices(const SkDraw& draw, SkCanvas::VertexMode vmode,
1703 int vertexCount, const SkPoint vertices[],
1704 const SkPoint texs[], const SkColor colors[],
1705 SkXfermode* xmode,
1706 const uint16_t indices[], int indexCount,
1707 const SkPaint& paint) {
1708 CHECK_SHOULD_DRAW(draw, false);
1709
1710 GrPaint grPaint;
1711 // we ignore the shader if texs is null.
1712 if (NULL == texs) {
1713 if (!skPaint2GrPaintNoShader(this, paint, false, NULL == colors, &grPaint)) {
1714 return;
1715 }
1716 } else {
1717 if (!skPaint2GrPaintShader(this, paint, NULL == colors, &grPaint)) {
1718 return;
1719 }
1720 }
1721
1722 if (NULL != xmode && NULL != texs && NULL != colors) {
1723 if (!SkXfermode::IsMode(xmode, SkXfermode::kModulate_Mode)) {
1724 SkDebugf("Unsupported vertex-color/texture xfer mode.\n");
1725#if 0
1726 return
1727#endif
1728 }
1729 }
1730
1731 SkAutoSTMalloc<128, GrColor> convertedColors(0);
1732 if (NULL != colors) {
1733 // need to convert byte order and from non-PM to PM
1734 convertedColors.reset(vertexCount);
1735 for (int i = 0; i < vertexCount; ++i) {
1736 convertedColors[i] = SkColor2GrColor(colors[i]);
1737 }
1738 colors = convertedColors.get();
1739 }
1740 fContext->drawVertices(grPaint,
1741 gVertexMode2PrimitiveType[vmode],
1742 vertexCount,
1743 (GrPoint*) vertices,
1744 (GrPoint*) texs,
1745 colors,
1746 indices,
1747 indexCount);
1748}
1749
1750///////////////////////////////////////////////////////////////////////////////
1751
1752static void GlyphCacheAuxProc(void* data) {
1753 GrFontScaler* scaler = (GrFontScaler*)data;
1754 SkSafeUnref(scaler);
1755}
1756
1757static GrFontScaler* get_gr_font_scaler(SkGlyphCache* cache) {
1758 void* auxData;
1759 GrFontScaler* scaler = NULL;
1760 if (cache->getAuxProcData(GlyphCacheAuxProc, &auxData)) {
1761 scaler = (GrFontScaler*)auxData;
1762 }
1763 if (NULL == scaler) {
1764 scaler = SkNEW_ARGS(SkGrFontScaler, (cache));
1765 cache->setAuxProc(GlyphCacheAuxProc, scaler);
1766 }
1767 return scaler;
1768}
1769
1770static void SkGPU_Draw1Glyph(const SkDraw1Glyph& state,
1771 SkFixed fx, SkFixed fy,
1772 const SkGlyph& glyph) {
1773 SkASSERT(glyph.fWidth > 0 && glyph.fHeight > 0);
1774
1775 GrSkDrawProcs* procs = static_cast<GrSkDrawProcs*>(state.fDraw->fProcs);
1776
1777 if (NULL == procs->fFontScaler) {
1778 procs->fFontScaler = get_gr_font_scaler(state.fCache);
1779 }
1780
1781 procs->fTextContext->drawPackedGlyph(GrGlyph::Pack(glyph.getGlyphID(),
1782 glyph.getSubXFixed(),
1783 glyph.getSubYFixed()),
1784 SkFixedFloorToFixed(fx),
1785 SkFixedFloorToFixed(fy),
1786 procs->fFontScaler);
1787}
1788
1789SkDrawProcs* SkGpuDevice::initDrawForText(GrTextContext* context) {
1790
1791 // deferred allocation
1792 if (NULL == fDrawProcs) {
1793 fDrawProcs = SkNEW(GrSkDrawProcs);
1794 fDrawProcs->fD1GProc = SkGPU_Draw1Glyph;
1795 fDrawProcs->fContext = fContext;
skia.committer@gmail.com11a253b2013-11-12 07:02:05 +00001796 }
1797
1798 // init our (and GL's) state
1799 fDrawProcs->fTextContext = context;
1800 fDrawProcs->fFontScaler = NULL;
1801 return fDrawProcs;
1802}
1803
1804void SkGpuDevice::drawText(const SkDraw& draw, const void* text,
1805 size_t byteLength, SkScalar x, SkScalar y,
1806 const SkPaint& paint) {
1807 CHECK_SHOULD_DRAW(draw, false);
1808
commit-bot@chromium.org8128d8c2013-12-19 16:12:25 +00001809 if (SkDraw::ShouldDrawTextAsPaths(paint, fContext->getMatrix())) {
1810 draw.drawText_asPaths((const char*)text, byteLength, x, y, paint);
1811#if SK_DISTANCEFIELD_FONTS
1812 } else if (!paint.getRasterizer()) {
1813 GrPaint grPaint;
1814 if (!skPaint2GrPaintShader(this, paint, true, &grPaint)) {
1815 return;
1816 }
1817
1818 SkDEBUGCODE(this->validate();)
1819
1820 GrDistanceFieldTextContext context(fContext, grPaint, paint);
1821
1822 SkAutoGlyphCache autoCache(context.getSkPaint(), &this->fLeakyProperties, NULL);
1823 SkGlyphCache* cache = autoCache.getCache();
1824 GrFontScaler* fontScaler = get_gr_font_scaler(cache);
1825
1826 context.drawText((const char *)text, byteLength, x, y, cache, fontScaler);
1827#endif
skia.committer@gmail.com11a253b2013-11-12 07:02:05 +00001828 } else {
1829 SkDraw myDraw(draw);
1830
1831 GrPaint grPaint;
1832 if (!skPaint2GrPaintShader(this, paint, true, &grPaint)) {
1833 return;
1834 }
commit-bot@chromium.org8128d8c2013-12-19 16:12:25 +00001835
1836 GrBitmapTextContext context(fContext, grPaint, paint.getColor());
1837 myDraw.fProcs = this->initDrawForText(&context);
1838 this->INHERITED::drawText(myDraw, text, byteLength, x, y, paint);
skia.committer@gmail.com11a253b2013-11-12 07:02:05 +00001839 }
1840}
1841
1842void SkGpuDevice::drawPosText(const SkDraw& draw, const void* text,
1843 size_t byteLength, const SkScalar pos[],
1844 SkScalar constY, int scalarsPerPos,
1845 const SkPaint& paint) {
1846 CHECK_SHOULD_DRAW(draw, false);
1847
commit-bot@chromium.org8128d8c2013-12-19 16:12:25 +00001848 if (SkDraw::ShouldDrawTextAsPaths(paint, fContext->getMatrix())) {
skia.committer@gmail.com11a253b2013-11-12 07:02:05 +00001849 // this guy will just call our drawPath()
commit-bot@chromium.org8128d8c2013-12-19 16:12:25 +00001850 draw.drawPosText_asPaths((const char*)text, byteLength, pos, constY,
skia.committer@gmail.com11a253b2013-11-12 07:02:05 +00001851 scalarsPerPos, paint);
commit-bot@chromium.org8128d8c2013-12-19 16:12:25 +00001852#if SK_DISTANCEFIELD_FONTS
1853 } else if (!paint.getRasterizer()) {
1854 GrPaint grPaint;
1855 if (!skPaint2GrPaintShader(this, paint, true, &grPaint)) {
1856 return;
1857 }
1858
1859 SkDEBUGCODE(this->validate();)
1860
1861 GrDistanceFieldTextContext context(fContext, grPaint, paint);
1862
1863 SkAutoGlyphCache autoCache(context.getSkPaint(), &this->fLeakyProperties, NULL);
1864 SkGlyphCache* cache = autoCache.getCache();
1865 GrFontScaler* fontScaler = get_gr_font_scaler(cache);
skia.committer@gmail.com22e96722013-12-20 07:01:36 +00001866
commit-bot@chromium.org8128d8c2013-12-19 16:12:25 +00001867 context.drawPosText((const char *)text, byteLength, pos, constY, scalarsPerPos,
1868 cache, fontScaler);
1869#endif
skia.committer@gmail.com11a253b2013-11-12 07:02:05 +00001870 } else {
1871 SkDraw myDraw(draw);
1872
1873 GrPaint grPaint;
1874 if (!skPaint2GrPaintShader(this, paint, true, &grPaint)) {
1875 return;
1876 }
commit-bot@chromium.org8128d8c2013-12-19 16:12:25 +00001877 GrBitmapTextContext context(fContext, grPaint, paint.getColor());
1878 myDraw.fProcs = this->initDrawForText(&context);
1879 this->INHERITED::drawPosText(myDraw, text, byteLength, pos, constY,
1880 scalarsPerPos, paint);
skia.committer@gmail.com11a253b2013-11-12 07:02:05 +00001881 }
1882}
1883
1884void SkGpuDevice::drawTextOnPath(const SkDraw& draw, const void* text,
1885 size_t len, const SkPath& path,
1886 const SkMatrix* m, const SkPaint& paint) {
1887 CHECK_SHOULD_DRAW(draw, false);
1888
1889 SkASSERT(draw.fDevice == this);
1890 draw.drawTextOnPath((const char*)text, len, path, m, paint);
1891}
1892
1893///////////////////////////////////////////////////////////////////////////////
1894
1895bool SkGpuDevice::filterTextFlags(const SkPaint& paint, TextFlags* flags) {
1896 if (!paint.isLCDRenderText()) {
1897 // we're cool with the paint as is
1898 return false;
1899 }
1900
1901 if (paint.getShader() ||
1902 paint.getXfermode() || // unless its srcover
1903 paint.getMaskFilter() ||
1904 paint.getRasterizer() ||
1905 paint.getColorFilter() ||
1906 paint.getPathEffect() ||
1907 paint.isFakeBoldText() ||
1908 paint.getStyle() != SkPaint::kFill_Style) {
1909 // turn off lcd
1910 flags->fFlags = paint.getFlags() & ~SkPaint::kLCDRenderText_Flag;
1911 flags->fHinting = paint.getHinting();
1912 return true;
1913 }
1914 // we're cool with the paint as is
1915 return false;
1916}
1917
1918void SkGpuDevice::flush() {
1919 DO_DEFERRED_CLEAR();
1920 fContext->resolveRenderTarget(fRenderTarget);
1921}
1922
1923///////////////////////////////////////////////////////////////////////////////
1924
1925SkBaseDevice* SkGpuDevice::onCreateCompatibleDevice(SkBitmap::Config config,
1926 int width, int height,
1927 bool isOpaque,
1928 Usage usage) {
1929 GrTextureDesc desc;
1930 desc.fConfig = fRenderTarget->config();
1931 desc.fFlags = kRenderTarget_GrTextureFlagBit;
1932 desc.fWidth = width;
1933 desc.fHeight = height;
1934 desc.fSampleCnt = fRenderTarget->numSamples();
1935
1936 SkAutoTUnref<GrTexture> texture;
1937 // Skia's convention is to only clear a device if it is non-opaque.
1938 bool needClear = !isOpaque;
1939
1940#if CACHE_COMPATIBLE_DEVICE_TEXTURES
1941 // layers are never draw in repeat modes, so we can request an approx
1942 // match and ignore any padding.
1943 const GrContext::ScratchTexMatch match = (kSaveLayer_Usage == usage) ?
1944 GrContext::kApprox_ScratchTexMatch :
1945 GrContext::kExact_ScratchTexMatch;
1946 texture.reset(fContext->lockAndRefScratchTexture(desc, match));
1947#else
1948 texture.reset(fContext->createUncachedTexture(desc, NULL, 0));
1949#endif
1950 if (NULL != texture.get()) {
1951 return SkNEW_ARGS(SkGpuDevice,(fContext, texture, needClear));
1952 } else {
1953 GrPrintf("---- failed to create compatible device texture [%d %d]\n", width, height);
1954 return NULL;
1955 }
1956}
1957
1958SkGpuDevice::SkGpuDevice(GrContext* context,
1959 GrTexture* texture,
1960 bool needClear)
1961 : SkBitmapDevice(make_bitmap(context, texture->asRenderTarget())) {
1962
1963 SkASSERT(texture && texture->asRenderTarget());
1964 // This constructor is called from onCreateCompatibleDevice. It has locked the RT in the texture
1965 // cache. We pass true for the third argument so that it will get unlocked.
1966 this->initFromRenderTarget(context, texture->asRenderTarget(), true);
1967 fNeedClear = needClear;
1968}