blob: da56009c55b823927100dabebd0c1340bfd3beef [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
commit-bot@chromium.orgcc40f062014-01-24 14:38:27 +0000203#if SK_DISTANCEFIELD_FONTS
commit-bot@chromium.orgcbbc4812014-01-30 22:05:47 +0000204 fMainTextContext = SkNEW_ARGS(GrDistanceFieldTextContext, (fContext, fLeakyProperties));
205 fFallbackTextContext = SkNEW_ARGS(GrBitmapTextContext, (fContext, fLeakyProperties));
commit-bot@chromium.orgcc40f062014-01-24 14:38:27 +0000206#else
commit-bot@chromium.orgcbbc4812014-01-30 22:05:47 +0000207 fMainTextContext = SkNEW_ARGS(GrBitmapTextContext, (fContext, fLeakyProperties));
208 fFallbackTextContext = NULL;
commit-bot@chromium.orgcc40f062014-01-24 14:38:27 +0000209#endif
210
skia.committer@gmail.com11a253b2013-11-12 07:02:05 +0000211 fRenderTarget = NULL;
212 fNeedClear = false;
213
214 SkASSERT(NULL != renderTarget);
215 fRenderTarget = renderTarget;
216 fRenderTarget->ref();
217
218 // Hold onto to the texture in the pixel ref (if there is one) because the texture holds a ref
219 // on the RT but not vice-versa.
220 // TODO: Remove this trickery once we figure out how to make SkGrPixelRef do this without
221 // busting chrome (for a currently unknown reason).
222 GrSurface* surface = fRenderTarget->asTexture();
223 if (NULL == surface) {
224 surface = fRenderTarget;
225 }
reed@google.combf790232013-12-13 19:45:58 +0000226
227 SkImageInfo info;
228 surface->asImageInfo(&info);
229 SkPixelRef* pr = SkNEW_ARGS(SkGrPixelRef, (info, surface, cached));
skia.committer@gmail.com11a253b2013-11-12 07:02:05 +0000230
reed@google.com672588b2014-01-08 15:42:01 +0000231 this->setPixelRef(pr)->unref();
skia.committer@gmail.com11a253b2013-11-12 07:02:05 +0000232}
233
234SkGpuDevice::SkGpuDevice(GrContext* context,
235 SkBitmap::Config config,
236 int width,
237 int height,
238 int sampleCount)
reed@google.combf790232013-12-13 19:45:58 +0000239 : SkBitmapDevice(make_bitmap(config, width, height, false /*isOpaque*/))
240{
skia.committer@gmail.com11a253b2013-11-12 07:02:05 +0000241 fDrawProcs = NULL;
242
243 fContext = context;
244 fContext->ref();
245
commit-bot@chromium.orgcc40f062014-01-24 14:38:27 +0000246#if SK_DISTANCEFIELD_FONTS
commit-bot@chromium.orgcbbc4812014-01-30 22:05:47 +0000247 fMainTextContext = SkNEW_ARGS(GrDistanceFieldTextContext, (fContext, fLeakyProperties));
248 fFallbackTextContext = SkNEW_ARGS(GrBitmapTextContext, (fContext, fLeakyProperties));
commit-bot@chromium.orgcc40f062014-01-24 14:38:27 +0000249#else
commit-bot@chromium.orgcbbc4812014-01-30 22:05:47 +0000250 fMainTextContext = SkNEW_ARGS(GrBitmapTextContext, (fContext, fLeakyProperties));
251 fFallbackTextContext = NULL;
commit-bot@chromium.orgcc40f062014-01-24 14:38:27 +0000252#endif
253
skia.committer@gmail.com11a253b2013-11-12 07:02:05 +0000254 fRenderTarget = NULL;
255 fNeedClear = false;
256
257 if (config != SkBitmap::kRGB_565_Config) {
258 config = SkBitmap::kARGB_8888_Config;
259 }
260
261 GrTextureDesc desc;
262 desc.fFlags = kRenderTarget_GrTextureFlagBit;
263 desc.fWidth = width;
264 desc.fHeight = height;
265 desc.fConfig = SkBitmapConfig2GrPixelConfig(config);
266 desc.fSampleCnt = sampleCount;
267
reed@google.combf790232013-12-13 19:45:58 +0000268 SkImageInfo info;
269 if (!GrPixelConfig2ColorType(desc.fConfig, &info.fColorType)) {
270 sk_throw();
271 }
272 info.fWidth = width;
273 info.fHeight = height;
274 info.fAlphaType = kPremul_SkAlphaType;
skia.committer@gmail.com96f5fa02013-12-16 07:01:40 +0000275
skia.committer@gmail.com11a253b2013-11-12 07:02:05 +0000276 SkAutoTUnref<GrTexture> texture(fContext->createUncachedTexture(desc, NULL, 0));
277
278 if (NULL != texture) {
279 fRenderTarget = texture->asRenderTarget();
280 fRenderTarget->ref();
281
282 SkASSERT(NULL != fRenderTarget);
283
284 // wrap the bitmap with a pixelref to expose our texture
reed@google.combf790232013-12-13 19:45:58 +0000285 SkGrPixelRef* pr = SkNEW_ARGS(SkGrPixelRef, (info, texture));
reed@google.com672588b2014-01-08 15:42:01 +0000286 this->setPixelRef(pr)->unref();
skia.committer@gmail.com11a253b2013-11-12 07:02:05 +0000287 } else {
288 GrPrintf("--- failed to create gpu-offscreen [%d %d]\n",
289 width, height);
290 SkASSERT(false);
291 }
292}
293
294SkGpuDevice::~SkGpuDevice() {
295 if (fDrawProcs) {
296 delete fDrawProcs;
297 }
skia.committer@gmail.comd2ac07b2014-01-25 07:01:49 +0000298
commit-bot@chromium.orgcbbc4812014-01-30 22:05:47 +0000299 delete fMainTextContext;
300 delete fFallbackTextContext;
skia.committer@gmail.com11a253b2013-11-12 07:02:05 +0000301
302 // The GrContext takes a ref on the target. We don't want to cause the render
303 // target to be unnecessarily kept alive.
304 if (fContext->getRenderTarget() == fRenderTarget) {
305 fContext->setRenderTarget(NULL);
306 }
307
308 if (fContext->getClip() == &fClipData) {
309 fContext->setClip(NULL);
310 }
311
312 SkSafeUnref(fRenderTarget);
313 fContext->unref();
314}
315
316///////////////////////////////////////////////////////////////////////////////
317
318void SkGpuDevice::makeRenderTargetCurrent() {
319 DO_DEFERRED_CLEAR();
320 fContext->setRenderTarget(fRenderTarget);
321}
322
323///////////////////////////////////////////////////////////////////////////////
324
325namespace {
326GrPixelConfig config8888_to_grconfig_and_flags(SkCanvas::Config8888 config8888, uint32_t* flags) {
327 switch (config8888) {
328 case SkCanvas::kNative_Premul_Config8888:
329 *flags = 0;
330 return kSkia8888_GrPixelConfig;
331 case SkCanvas::kNative_Unpremul_Config8888:
332 *flags = GrContext::kUnpremul_PixelOpsFlag;
333 return kSkia8888_GrPixelConfig;
334 case SkCanvas::kBGRA_Premul_Config8888:
335 *flags = 0;
336 return kBGRA_8888_GrPixelConfig;
337 case SkCanvas::kBGRA_Unpremul_Config8888:
338 *flags = GrContext::kUnpremul_PixelOpsFlag;
339 return kBGRA_8888_GrPixelConfig;
340 case SkCanvas::kRGBA_Premul_Config8888:
341 *flags = 0;
342 return kRGBA_8888_GrPixelConfig;
343 case SkCanvas::kRGBA_Unpremul_Config8888:
344 *flags = GrContext::kUnpremul_PixelOpsFlag;
345 return kRGBA_8888_GrPixelConfig;
346 default:
347 GrCrash("Unexpected Config8888.");
348 *flags = 0; // suppress warning
349 return kSkia8888_GrPixelConfig;
350 }
351}
352}
353
354bool SkGpuDevice::onReadPixels(const SkBitmap& bitmap,
355 int x, int y,
356 SkCanvas::Config8888 config8888) {
357 DO_DEFERRED_CLEAR();
358 SkASSERT(SkBitmap::kARGB_8888_Config == bitmap.config());
359 SkASSERT(!bitmap.isNull());
360 SkASSERT(SkIRect::MakeWH(this->width(), this->height()).contains(SkIRect::MakeXYWH(x, y, bitmap.width(), bitmap.height())));
361
362 SkAutoLockPixels alp(bitmap);
363 GrPixelConfig config;
364 uint32_t flags;
365 config = config8888_to_grconfig_and_flags(config8888, &flags);
366 return fContext->readRenderTargetPixels(fRenderTarget,
367 x, y,
368 bitmap.width(),
369 bitmap.height(),
370 config,
371 bitmap.getPixels(),
372 bitmap.rowBytes(),
373 flags);
374}
375
376void SkGpuDevice::writePixels(const SkBitmap& bitmap, int x, int y,
377 SkCanvas::Config8888 config8888) {
378 SkAutoLockPixels alp(bitmap);
379 if (!bitmap.readyToDraw()) {
380 return;
381 }
382
383 GrPixelConfig config;
384 uint32_t flags;
385 if (SkBitmap::kARGB_8888_Config == bitmap.config()) {
386 config = config8888_to_grconfig_and_flags(config8888, &flags);
387 } else {
388 flags = 0;
389 config= SkBitmapConfig2GrPixelConfig(bitmap.config());
390 }
391
392 fRenderTarget->writePixels(x, y, bitmap.width(), bitmap.height(),
393 config, bitmap.getPixels(), bitmap.rowBytes(), flags);
394}
395
396void SkGpuDevice::onAttachToCanvas(SkCanvas* canvas) {
397 INHERITED::onAttachToCanvas(canvas);
398
399 // Canvas promises that this ptr is valid until onDetachFromCanvas is called
400 fClipData.fClipStack = canvas->getClipStack();
401}
402
403void SkGpuDevice::onDetachFromCanvas() {
404 INHERITED::onDetachFromCanvas();
405 fClipData.fClipStack = NULL;
406}
407
408// call this every draw call, to ensure that the context reflects our state,
409// and not the state from some other canvas/device
410void SkGpuDevice::prepareDraw(const SkDraw& draw, bool forceIdentity) {
411 SkASSERT(NULL != fClipData.fClipStack);
412
413 fContext->setRenderTarget(fRenderTarget);
414
415 SkASSERT(draw.fClipStack && draw.fClipStack == fClipData.fClipStack);
416
417 if (forceIdentity) {
418 fContext->setIdentityMatrix();
419 } else {
420 fContext->setMatrix(*draw.fMatrix);
421 }
422 fClipData.fOrigin = this->getOrigin();
423
424 fContext->setClip(&fClipData);
425
426 DO_DEFERRED_CLEAR();
427}
428
429GrRenderTarget* SkGpuDevice::accessRenderTarget() {
430 DO_DEFERRED_CLEAR();
431 return fRenderTarget;
432}
433
434///////////////////////////////////////////////////////////////////////////////
435
436SK_COMPILE_ASSERT(SkShader::kNone_BitmapType == 0, shader_type_mismatch);
437SK_COMPILE_ASSERT(SkShader::kDefault_BitmapType == 1, shader_type_mismatch);
438SK_COMPILE_ASSERT(SkShader::kRadial_BitmapType == 2, shader_type_mismatch);
439SK_COMPILE_ASSERT(SkShader::kSweep_BitmapType == 3, shader_type_mismatch);
440SK_COMPILE_ASSERT(SkShader::kTwoPointRadial_BitmapType == 4,
441 shader_type_mismatch);
442SK_COMPILE_ASSERT(SkShader::kTwoPointConical_BitmapType == 5,
443 shader_type_mismatch);
444SK_COMPILE_ASSERT(SkShader::kLinear_BitmapType == 6, shader_type_mismatch);
445SK_COMPILE_ASSERT(SkShader::kLast_BitmapType == 6, shader_type_mismatch);
446
447namespace {
448
449// converts a SkPaint to a GrPaint, ignoring the skPaint's shader
450// justAlpha indicates that skPaint's alpha should be used rather than the color
451// Callers may subsequently modify the GrPaint. Setting constantColor indicates
452// that the final paint will draw the same color at every pixel. This allows
453// an optimization where the the color filter can be applied to the skPaint's
454// color once while converting to GrPaint and then ignored.
455inline bool skPaint2GrPaintNoShader(SkGpuDevice* dev,
456 const SkPaint& skPaint,
457 bool justAlpha,
458 bool constantColor,
459 GrPaint* grPaint) {
460
461 grPaint->setDither(skPaint.isDither());
462 grPaint->setAntiAlias(skPaint.isAntiAlias());
463
464 SkXfermode::Coeff sm;
465 SkXfermode::Coeff dm;
466
467 SkXfermode* mode = skPaint.getXfermode();
468 GrEffectRef* xferEffect = NULL;
469 if (SkXfermode::AsNewEffectOrCoeff(mode, &xferEffect, &sm, &dm)) {
470 if (NULL != xferEffect) {
471 grPaint->addColorEffect(xferEffect)->unref();
472 sm = SkXfermode::kOne_Coeff;
473 dm = SkXfermode::kZero_Coeff;
474 }
475 } else {
476 //SkDEBUGCODE(SkDebugf("Unsupported xfer mode.\n");)
477#if 0
478 return false;
479#else
480 // Fall back to src-over
481 sm = SkXfermode::kOne_Coeff;
482 dm = SkXfermode::kISA_Coeff;
483#endif
484 }
485 grPaint->setBlendFunc(sk_blend_to_grblend(sm), sk_blend_to_grblend(dm));
486
487 if (justAlpha) {
488 uint8_t alpha = skPaint.getAlpha();
489 grPaint->setColor(GrColorPackRGBA(alpha, alpha, alpha, alpha));
490 // justAlpha is currently set to true only if there is a texture,
491 // so constantColor should not also be true.
492 SkASSERT(!constantColor);
493 } else {
494 grPaint->setColor(SkColor2GrColor(skPaint.getColor()));
495 }
496
497 SkColorFilter* colorFilter = skPaint.getColorFilter();
498 if (NULL != colorFilter) {
499 // if the source color is a constant then apply the filter here once rather than per pixel
500 // in a shader.
501 if (constantColor) {
502 SkColor filtered = colorFilter->filterColor(skPaint.getColor());
503 grPaint->setColor(SkColor2GrColor(filtered));
504 } else {
505 SkAutoTUnref<GrEffectRef> effect(colorFilter->asNewEffect(dev->context()));
506 if (NULL != effect.get()) {
507 grPaint->addColorEffect(effect);
508 }
509 }
510 }
511
512 return true;
513}
514
515// This function is similar to skPaint2GrPaintNoShader but also converts
516// skPaint's shader to a GrTexture/GrEffectStage if possible. The texture to
517// be used is set on grPaint and returned in param act. constantColor has the
518// same meaning as in skPaint2GrPaintNoShader.
519inline bool skPaint2GrPaintShader(SkGpuDevice* dev,
520 const SkPaint& skPaint,
521 bool constantColor,
522 GrPaint* grPaint) {
523 SkShader* shader = skPaint.getShader();
524 if (NULL == shader) {
525 return skPaint2GrPaintNoShader(dev, skPaint, false, constantColor, grPaint);
526 }
527
commit-bot@chromium.org60770572014-01-13 15:57:05 +0000528 // SkShader::asNewEffect() may do offscreen rendering. Setup default drawing state and require
529 // the shader to set a render target .
skia.committer@gmail.com11a253b2013-11-12 07:02:05 +0000530 GrContext::AutoWideOpenIdentityDraw awo(dev->context(), NULL);
skia.committer@gmail.com11a253b2013-11-12 07:02:05 +0000531
532 // setup the shader as the first color effect on the paint
533 SkAutoTUnref<GrEffectRef> effect(shader->asNewEffect(dev->context(), skPaint));
534 if (NULL != effect.get()) {
535 grPaint->addColorEffect(effect);
536 // Now setup the rest of the paint.
537 return skPaint2GrPaintNoShader(dev, skPaint, true, false, grPaint);
538 } else {
539 // We still don't have SkColorShader::asNewEffect() implemented.
540 SkShader::GradientInfo info;
541 SkColor color;
542
543 info.fColors = &color;
544 info.fColorOffsets = NULL;
545 info.fColorCount = 1;
546 if (SkShader::kColor_GradientType == shader->asAGradient(&info)) {
547 SkPaint copy(skPaint);
548 copy.setShader(NULL);
549 // modulate the paint alpha by the shader's solid color alpha
550 U8CPU newA = SkMulDiv255Round(SkColorGetA(color), copy.getAlpha());
551 copy.setColor(SkColorSetA(color, newA));
552 return skPaint2GrPaintNoShader(dev, copy, false, constantColor, grPaint);
553 } else {
554 return false;
555 }
556 }
557}
558}
559
560///////////////////////////////////////////////////////////////////////////////
skia.committer@gmail.com11a253b2013-11-12 07:02:05 +0000561
562SkBitmap::Config SkGpuDevice::config() const {
563 if (NULL == fRenderTarget) {
564 return SkBitmap::kNo_Config;
565 }
566
567 bool isOpaque;
568 return grConfig2skConfig(fRenderTarget->config(), &isOpaque);
569}
570
571void SkGpuDevice::clear(SkColor color) {
572 SkIRect rect = SkIRect::MakeWH(this->width(), this->height());
573 fContext->clear(&rect, SkColor2GrColor(color), true, fRenderTarget);
574 fNeedClear = false;
575}
576
577void SkGpuDevice::drawPaint(const SkDraw& draw, const SkPaint& paint) {
578 CHECK_SHOULD_DRAW(draw, false);
579
580 GrPaint grPaint;
581 if (!skPaint2GrPaintShader(this, paint, true, &grPaint)) {
582 return;
583 }
584
585 fContext->drawPaint(grPaint);
586}
587
588// must be in SkCanvas::PointMode order
589static const GrPrimitiveType gPointMode2PrimtiveType[] = {
590 kPoints_GrPrimitiveType,
591 kLines_GrPrimitiveType,
592 kLineStrip_GrPrimitiveType
593};
594
595void SkGpuDevice::drawPoints(const SkDraw& draw, SkCanvas::PointMode mode,
596 size_t count, const SkPoint pts[], const SkPaint& paint) {
597 CHECK_FOR_ANNOTATION(paint);
598 CHECK_SHOULD_DRAW(draw, false);
599
600 SkScalar width = paint.getStrokeWidth();
601 if (width < 0) {
602 return;
603 }
604
605 // we only handle hairlines and paints without path effects or mask filters,
606 // else we let the SkDraw call our drawPath()
607 if (width > 0 || paint.getPathEffect() || paint.getMaskFilter()) {
608 draw.drawPoints(mode, count, pts, paint, true);
609 return;
610 }
611
612 GrPaint grPaint;
613 if (!skPaint2GrPaintShader(this, paint, true, &grPaint)) {
614 return;
615 }
616
617 fContext->drawVertices(grPaint,
618 gPointMode2PrimtiveType[mode],
robertphillips@google.coma4662862013-11-21 14:24:16 +0000619 SkToS32(count),
skia.committer@gmail.com11a253b2013-11-12 07:02:05 +0000620 (GrPoint*)pts,
621 NULL,
622 NULL,
623 NULL,
624 0);
625}
626
627///////////////////////////////////////////////////////////////////////////////
628
629void SkGpuDevice::drawRect(const SkDraw& draw, const SkRect& rect,
630 const SkPaint& paint) {
631 CHECK_FOR_ANNOTATION(paint);
632 CHECK_SHOULD_DRAW(draw, false);
633
634 bool doStroke = paint.getStyle() != SkPaint::kFill_Style;
635 SkScalar width = paint.getStrokeWidth();
636
637 /*
638 We have special code for hairline strokes, miter-strokes, bevel-stroke
639 and fills. Anything else we just call our path code.
640 */
641 bool usePath = doStroke && width > 0 &&
642 (paint.getStrokeJoin() == SkPaint::kRound_Join ||
643 (paint.getStrokeJoin() == SkPaint::kBevel_Join && rect.isEmpty()));
644 // another two reasons we might need to call drawPath...
645 if (paint.getMaskFilter() || paint.getPathEffect()) {
646 usePath = true;
647 }
648 if (!usePath && paint.isAntiAlias() && !fContext->getMatrix().rectStaysRect()) {
649#if defined(SHADER_AA_FILL_RECT) || !defined(IGNORE_ROT_AA_RECT_OPT)
650 if (doStroke) {
651#endif
652 usePath = true;
653#if defined(SHADER_AA_FILL_RECT) || !defined(IGNORE_ROT_AA_RECT_OPT)
654 } else {
655 usePath = !fContext->getMatrix().preservesRightAngles();
656 }
657#endif
658 }
659 // until we can both stroke and fill rectangles
660 if (paint.getStyle() == SkPaint::kStrokeAndFill_Style) {
661 usePath = true;
662 }
663
664 if (usePath) {
665 SkPath path;
666 path.addRect(rect);
667 this->drawPath(draw, path, paint, NULL, true);
668 return;
669 }
670
671 GrPaint grPaint;
672 if (!skPaint2GrPaintShader(this, paint, true, &grPaint)) {
673 return;
674 }
675
676 if (!doStroke) {
677 fContext->drawRect(grPaint, rect);
678 } else {
679 SkStrokeRec stroke(paint);
680 fContext->drawRect(grPaint, rect, &stroke);
681 }
682}
683
684///////////////////////////////////////////////////////////////////////////////
685
686void SkGpuDevice::drawRRect(const SkDraw& draw, const SkRRect& rect,
687 const SkPaint& paint) {
688 CHECK_FOR_ANNOTATION(paint);
689 CHECK_SHOULD_DRAW(draw, false);
690
691 bool usePath = !rect.isSimple();
692 // another two reasons we might need to call drawPath...
693 if (paint.getMaskFilter() || paint.getPathEffect()) {
694 usePath = true;
695 }
696 // until we can rotate rrects...
697 if (!usePath && !fContext->getMatrix().rectStaysRect()) {
698 usePath = true;
699 }
700
701 if (usePath) {
702 SkPath path;
703 path.addRRect(rect);
704 this->drawPath(draw, path, paint, NULL, true);
705 return;
706 }
707
708 GrPaint grPaint;
709 if (!skPaint2GrPaintShader(this, paint, true, &grPaint)) {
710 return;
711 }
712
713 SkStrokeRec stroke(paint);
714 fContext->drawRRect(grPaint, rect, stroke);
715}
716
717///////////////////////////////////////////////////////////////////////////////
718
719void SkGpuDevice::drawOval(const SkDraw& draw, const SkRect& oval,
720 const SkPaint& paint) {
721 CHECK_FOR_ANNOTATION(paint);
722 CHECK_SHOULD_DRAW(draw, false);
723
724 bool usePath = false;
725 // some basic reasons we might need to call drawPath...
726 if (paint.getMaskFilter() || paint.getPathEffect()) {
727 usePath = true;
728 }
729
730 if (usePath) {
731 SkPath path;
732 path.addOval(oval);
733 this->drawPath(draw, path, paint, NULL, true);
734 return;
735 }
736
737 GrPaint grPaint;
738 if (!skPaint2GrPaintShader(this, paint, true, &grPaint)) {
739 return;
740 }
741 SkStrokeRec stroke(paint);
742
743 fContext->drawOval(grPaint, oval, stroke);
744}
745
746#include "SkMaskFilter.h"
747#include "SkBounder.h"
748
749///////////////////////////////////////////////////////////////////////////////
750
751// helpers for applying mask filters
752namespace {
753
754// Draw a mask using the supplied paint. Since the coverage/geometry
755// is already burnt into the mask this boils down to a rect draw.
756// Return true if the mask was successfully drawn.
757bool draw_mask(GrContext* context, const SkRect& maskRect,
758 GrPaint* grp, GrTexture* mask) {
759 GrContext::AutoMatrix am;
760 if (!am.setIdentity(context, grp)) {
761 return false;
762 }
763
764 SkMatrix matrix;
765 matrix.setTranslate(-maskRect.fLeft, -maskRect.fTop);
766 matrix.postIDiv(mask->width(), mask->height());
767
768 grp->addCoverageEffect(GrSimpleTextureEffect::Create(mask, matrix))->unref();
769 context->drawRect(*grp, maskRect);
770 return true;
771}
772
773bool draw_with_mask_filter(GrContext* context, const SkPath& devPath,
774 SkMaskFilter* filter, const SkRegion& clip, SkBounder* bounder,
775 GrPaint* grp, SkPaint::Style style) {
776 SkMask srcM, dstM;
777
778 if (!SkDraw::DrawToMask(devPath, &clip.getBounds(), filter, &context->getMatrix(), &srcM,
779 SkMask::kComputeBoundsAndRenderImage_CreateMode, style)) {
780 return false;
781 }
782 SkAutoMaskFreeImage autoSrc(srcM.fImage);
783
784 if (!filter->filterMask(&dstM, srcM, context->getMatrix(), NULL)) {
785 return false;
786 }
787 // this will free-up dstM when we're done (allocated in filterMask())
788 SkAutoMaskFreeImage autoDst(dstM.fImage);
789
790 if (clip.quickReject(dstM.fBounds)) {
791 return false;
792 }
793 if (bounder && !bounder->doIRect(dstM.fBounds)) {
794 return false;
795 }
796
797 // we now have a device-aligned 8bit mask in dstM, ready to be drawn using
798 // the current clip (and identity matrix) and GrPaint settings
799 GrTextureDesc desc;
800 desc.fWidth = dstM.fBounds.width();
801 desc.fHeight = dstM.fBounds.height();
802 desc.fConfig = kAlpha_8_GrPixelConfig;
803
804 GrAutoScratchTexture ast(context, desc);
805 GrTexture* texture = ast.texture();
806
807 if (NULL == texture) {
808 return false;
809 }
810 texture->writePixels(0, 0, desc.fWidth, desc.fHeight, desc.fConfig,
811 dstM.fImage, dstM.fRowBytes);
812
813 SkRect maskRect = SkRect::Make(dstM.fBounds);
814
815 return draw_mask(context, maskRect, grp, texture);
816}
817
818// Create a mask of 'devPath' and place the result in 'mask'. Return true on
819// success; false otherwise.
820bool create_mask_GPU(GrContext* context,
821 const SkRect& maskRect,
822 const SkPath& devPath,
823 const SkStrokeRec& stroke,
824 bool doAA,
825 GrAutoScratchTexture* mask) {
826 GrTextureDesc desc;
827 desc.fFlags = kRenderTarget_GrTextureFlagBit;
828 desc.fWidth = SkScalarCeilToInt(maskRect.width());
829 desc.fHeight = SkScalarCeilToInt(maskRect.height());
830 // We actually only need A8, but it often isn't supported as a
831 // render target so default to RGBA_8888
832 desc.fConfig = kRGBA_8888_GrPixelConfig;
833 if (context->isConfigRenderable(kAlpha_8_GrPixelConfig, false)) {
834 desc.fConfig = kAlpha_8_GrPixelConfig;
835 }
836
837 mask->set(context, desc);
838 if (NULL == mask->texture()) {
839 return false;
840 }
841
842 GrTexture* maskTexture = mask->texture();
843 SkRect clipRect = SkRect::MakeWH(maskRect.width(), maskRect.height());
844
845 GrContext::AutoRenderTarget art(context, maskTexture->asRenderTarget());
846 GrContext::AutoClip ac(context, clipRect);
847
848 context->clear(NULL, 0x0, true);
849
850 GrPaint tempPaint;
851 if (doAA) {
852 tempPaint.setAntiAlias(true);
853 // AA uses the "coverage" stages on GrDrawTarget. Coverage with a dst
854 // blend coeff of zero requires dual source blending support in order
855 // to properly blend partially covered pixels. This means the AA
856 // code path may not be taken. So we use a dst blend coeff of ISA. We
857 // could special case AA draws to a dst surface with known alpha=0 to
858 // use a zero dst coeff when dual source blending isn't available.
859 tempPaint.setBlendFunc(kOne_GrBlendCoeff, kISC_GrBlendCoeff);
860 }
861
862 GrContext::AutoMatrix am;
863
864 // Draw the mask into maskTexture with the path's top-left at the origin using tempPaint.
865 SkMatrix translate;
866 translate.setTranslate(-maskRect.fLeft, -maskRect.fTop);
867 am.set(context, translate);
868 context->drawPath(tempPaint, devPath, stroke);
869 return true;
870}
871
872SkBitmap wrap_texture(GrTexture* texture) {
reed@google.combf790232013-12-13 19:45:58 +0000873 SkImageInfo info;
874 texture->asImageInfo(&info);
875
skia.committer@gmail.com11a253b2013-11-12 07:02:05 +0000876 SkBitmap result;
reed@google.combf790232013-12-13 19:45:58 +0000877 result.setConfig(info);
878 result.setPixelRef(SkNEW_ARGS(SkGrPixelRef, (info, texture)))->unref();
skia.committer@gmail.com11a253b2013-11-12 07:02:05 +0000879 return result;
880}
881
882};
883
884void SkGpuDevice::drawPath(const SkDraw& draw, const SkPath& origSrcPath,
885 const SkPaint& paint, const SkMatrix* prePathMatrix,
886 bool pathIsMutable) {
887 CHECK_FOR_ANNOTATION(paint);
888 CHECK_SHOULD_DRAW(draw, false);
889
890 GrPaint grPaint;
891 if (!skPaint2GrPaintShader(this, paint, true, &grPaint)) {
892 return;
893 }
894
skia.committer@gmail.com11a253b2013-11-12 07:02:05 +0000895 // If we have a prematrix, apply it to the path, optimizing for the case
896 // where the original path can in fact be modified in place (even though
897 // its parameter type is const).
898 SkPath* pathPtr = const_cast<SkPath*>(&origSrcPath);
commit-bot@chromium.orgf0c41e22014-01-14 18:42:34 +0000899 SkTLazy<SkPath> tmpPath;
900 SkTLazy<SkPath> effectPath;
skia.committer@gmail.com11a253b2013-11-12 07:02:05 +0000901
902 if (prePathMatrix) {
903 SkPath* result = pathPtr;
904
905 if (!pathIsMutable) {
commit-bot@chromium.orgf0c41e22014-01-14 18:42:34 +0000906 result = tmpPath.init();
skia.committer@gmail.com11a253b2013-11-12 07:02:05 +0000907 pathIsMutable = true;
908 }
909 // should I push prePathMatrix on our MV stack temporarily, instead
910 // of applying it here? See SkDraw.cpp
911 pathPtr->transform(*prePathMatrix, result);
912 pathPtr = result;
913 }
914 // at this point we're done with prePathMatrix
915 SkDEBUGCODE(prePathMatrix = (const SkMatrix*)0x50FF8001;)
916
917 SkStrokeRec stroke(paint);
918 SkPathEffect* pathEffect = paint.getPathEffect();
919 const SkRect* cullRect = NULL; // TODO: what is our bounds?
commit-bot@chromium.orgf0c41e22014-01-14 18:42:34 +0000920 if (pathEffect && pathEffect->filterPath(effectPath.init(), *pathPtr, &stroke,
skia.committer@gmail.com11a253b2013-11-12 07:02:05 +0000921 cullRect)) {
commit-bot@chromium.orgf0c41e22014-01-14 18:42:34 +0000922 pathPtr = effectPath.get();
923 pathIsMutable = true;
skia.committer@gmail.com11a253b2013-11-12 07:02:05 +0000924 }
925
skia.committer@gmail.com11a253b2013-11-12 07:02:05 +0000926 if (paint.getMaskFilter()) {
927 if (!stroke.isHairlineStyle()) {
commit-bot@chromium.orgf0c41e22014-01-14 18:42:34 +0000928 SkPath* strokedPath = pathIsMutable ? pathPtr : tmpPath.init();
929 if (stroke.applyToPath(strokedPath, *pathPtr)) {
930 pathPtr = strokedPath;
skia.committer@gmail.com11a253b2013-11-12 07:02:05 +0000931 pathIsMutable = true;
932 stroke.setFillStyle();
933 }
934 }
935
936 // avoid possibly allocating a new path in transform if we can
commit-bot@chromium.orgf0c41e22014-01-14 18:42:34 +0000937 SkPath* devPathPtr = pathIsMutable ? pathPtr : tmpPath.init();
skia.committer@gmail.com11a253b2013-11-12 07:02:05 +0000938
939 // transform the path into device space
940 pathPtr->transform(fContext->getMatrix(), devPathPtr);
skia.committer@gmail.com4c18e9f2014-01-31 03:01:59 +0000941
skia.committer@gmail.com11a253b2013-11-12 07:02:05 +0000942 SkRect maskRect;
943 if (paint.getMaskFilter()->canFilterMaskGPU(devPathPtr->getBounds(),
944 draw.fClip->getBounds(),
945 fContext->getMatrix(),
946 &maskRect)) {
commit-bot@chromium.org439ff1b2014-01-13 16:39:39 +0000947 // The context's matrix may change while creating the mask, so save the CTM here to
948 // pass to filterMaskGPU.
949 const SkMatrix ctm = fContext->getMatrix();
950
skia.committer@gmail.com11a253b2013-11-12 07:02:05 +0000951 SkIRect finalIRect;
952 maskRect.roundOut(&finalIRect);
953 if (draw.fClip->quickReject(finalIRect)) {
954 // clipped out
955 return;
956 }
957 if (NULL != draw.fBounder && !draw.fBounder->doIRect(finalIRect)) {
958 // nothing to draw
959 return;
960 }
skia.committer@gmail.com4c18e9f2014-01-31 03:01:59 +0000961
commit-bot@chromium.orgcf34bc02014-01-30 15:34:43 +0000962 if (paint.getMaskFilter()->directFilterMaskGPU(fContext, &grPaint,
963 SkStrokeRec(paint), *devPathPtr)) {
964 // the mask filter was able to draw itself directly, so there's nothing
965 // left to do.
966 return;
967 }
skia.committer@gmail.com11a253b2013-11-12 07:02:05 +0000968
969 GrAutoScratchTexture mask;
970
971 if (create_mask_GPU(fContext, maskRect, *devPathPtr, stroke,
972 grPaint.isAntiAlias(), &mask)) {
973 GrTexture* filtered;
974
commit-bot@chromium.org41bf9302014-01-08 22:25:53 +0000975 if (paint.getMaskFilter()->filterMaskGPU(mask.texture(),
commit-bot@chromium.org439ff1b2014-01-13 16:39:39 +0000976 ctm, maskRect, &filtered, true)) {
skia.committer@gmail.com11a253b2013-11-12 07:02:05 +0000977 // filterMaskGPU gives us ownership of a ref to the result
978 SkAutoTUnref<GrTexture> atu(filtered);
979
980 // If the scratch texture that we used as the filter src also holds the filter
981 // result then we must detach so that this texture isn't recycled for a later
982 // draw.
983 if (filtered == mask.texture()) {
984 mask.detach();
985 filtered->unref(); // detach transfers GrAutoScratchTexture's ref to us.
986 }
987
988 if (draw_mask(fContext, maskRect, &grPaint, filtered)) {
989 // This path is completely drawn
990 return;
991 }
992 }
993 }
994 }
995
996 // draw the mask on the CPU - this is a fallthrough path in case the
997 // GPU path fails
998 SkPaint::Style style = stroke.isHairlineStyle() ? SkPaint::kStroke_Style :
999 SkPaint::kFill_Style;
1000 draw_with_mask_filter(fContext, *devPathPtr, paint.getMaskFilter(),
1001 *draw.fClip, draw.fBounder, &grPaint, style);
1002 return;
1003 }
1004
1005 fContext->drawPath(grPaint, *pathPtr, stroke);
1006}
1007
1008static const int kBmpSmallTileSize = 1 << 10;
1009
1010static inline int get_tile_count(const SkIRect& srcRect, int tileSize) {
1011 int tilesX = (srcRect.fRight / tileSize) - (srcRect.fLeft / tileSize) + 1;
1012 int tilesY = (srcRect.fBottom / tileSize) - (srcRect.fTop / tileSize) + 1;
1013 return tilesX * tilesY;
1014}
1015
1016static int determine_tile_size(const SkBitmap& bitmap, const SkIRect& src, int maxTileSize) {
1017 if (maxTileSize <= kBmpSmallTileSize) {
1018 return maxTileSize;
1019 }
1020
1021 size_t maxTileTotalTileSize = get_tile_count(src, maxTileSize);
1022 size_t smallTotalTileSize = get_tile_count(src, kBmpSmallTileSize);
1023
1024 maxTileTotalTileSize *= maxTileSize * maxTileSize;
1025 smallTotalTileSize *= kBmpSmallTileSize * kBmpSmallTileSize;
1026
1027 if (maxTileTotalTileSize > 2 * smallTotalTileSize) {
1028 return kBmpSmallTileSize;
1029 } else {
1030 return maxTileSize;
1031 }
1032}
1033
1034// Given a bitmap, an optional src rect, and a context with a clip and matrix determine what
1035// pixels from the bitmap are necessary.
1036static void determine_clipped_src_rect(const GrContext* context,
1037 const SkBitmap& bitmap,
1038 const SkRect* srcRectPtr,
1039 SkIRect* clippedSrcIRect) {
1040 const GrClipData* clip = context->getClip();
1041 clip->getConservativeBounds(context->getRenderTarget(), clippedSrcIRect, NULL);
1042 SkMatrix inv;
1043 if (!context->getMatrix().invert(&inv)) {
1044 clippedSrcIRect->setEmpty();
1045 return;
1046 }
1047 SkRect clippedSrcRect = SkRect::Make(*clippedSrcIRect);
1048 inv.mapRect(&clippedSrcRect);
1049 if (NULL != srcRectPtr) {
commit-bot@chromium.orga7d89c82014-01-13 14:47:00 +00001050 // we've setup src space 0,0 to map to the top left of the src rect.
1051 clippedSrcRect.offset(srcRectPtr->fLeft, srcRectPtr->fTop);
skia.committer@gmail.com11a253b2013-11-12 07:02:05 +00001052 if (!clippedSrcRect.intersect(*srcRectPtr)) {
1053 clippedSrcIRect->setEmpty();
1054 return;
1055 }
1056 }
1057 clippedSrcRect.roundOut(clippedSrcIRect);
1058 SkIRect bmpBounds = SkIRect::MakeWH(bitmap.width(), bitmap.height());
1059 if (!clippedSrcIRect->intersect(bmpBounds)) {
1060 clippedSrcIRect->setEmpty();
1061 }
1062}
1063
1064bool SkGpuDevice::shouldTileBitmap(const SkBitmap& bitmap,
1065 const GrTextureParams& params,
1066 const SkRect* srcRectPtr,
1067 int maxTileSize,
1068 int* tileSize,
1069 SkIRect* clippedSrcRect) const {
1070 // if bitmap is explictly texture backed then just use the texture
1071 if (NULL != bitmap.getTexture()) {
1072 return false;
1073 }
1074
1075 // if it's larger than the max tile size, then we have no choice but tiling.
1076 if (bitmap.width() > maxTileSize || bitmap.height() > maxTileSize) {
1077 determine_clipped_src_rect(fContext, bitmap, srcRectPtr, clippedSrcRect);
1078 *tileSize = determine_tile_size(bitmap, *clippedSrcRect, maxTileSize);
1079 return true;
1080 }
1081
1082 if (bitmap.width() * bitmap.height() < 4 * kBmpSmallTileSize * kBmpSmallTileSize) {
1083 return false;
1084 }
1085
1086 // if the entire texture is already in our cache then no reason to tile it
1087 if (GrIsBitmapInCache(fContext, bitmap, &params)) {
1088 return false;
1089 }
1090
1091 // At this point we know we could do the draw by uploading the entire bitmap
1092 // as a texture. However, if the texture would be large compared to the
1093 // cache size and we don't require most of it for this draw then tile to
1094 // reduce the amount of upload and cache spill.
1095
1096 // assumption here is that sw bitmap size is a good proxy for its size as
1097 // a texture
1098 size_t bmpSize = bitmap.getSize();
1099 size_t cacheSize;
1100 fContext->getTextureCacheLimits(NULL, &cacheSize);
1101 if (bmpSize < cacheSize / 2) {
1102 return false;
1103 }
1104
1105 // Figure out how much of the src we will need based on the src rect and clipping.
1106 determine_clipped_src_rect(fContext, bitmap, srcRectPtr, clippedSrcRect);
1107 *tileSize = kBmpSmallTileSize; // already know whole bitmap fits in one max sized tile.
1108 size_t usedTileBytes = get_tile_count(*clippedSrcRect, kBmpSmallTileSize) *
1109 kBmpSmallTileSize * kBmpSmallTileSize;
1110
1111 return usedTileBytes < 2 * bmpSize;
1112}
1113
commit-bot@chromium.orga7d89c82014-01-13 14:47:00 +00001114void SkGpuDevice::drawBitmap(const SkDraw& origDraw,
skia.committer@gmail.com11a253b2013-11-12 07:02:05 +00001115 const SkBitmap& bitmap,
1116 const SkMatrix& m,
1117 const SkPaint& paint) {
commit-bot@chromium.orga7d89c82014-01-13 14:47:00 +00001118 SkMatrix concat;
1119 SkTCopyOnFirstWrite<SkDraw> draw(origDraw);
1120 if (!m.isIdentity()) {
1121 concat.setConcat(*draw->fMatrix, m);
1122 draw.writable()->fMatrix = &concat;
1123 }
1124 this->drawBitmapCommon(*draw, bitmap, NULL, NULL, paint, SkCanvas::kNone_DrawBitmapRectFlag);
skia.committer@gmail.com11a253b2013-11-12 07:02:05 +00001125}
1126
commit-bot@chromium.orgdec61502013-12-02 22:22:35 +00001127// This method outsets 'iRect' by 'outset' all around and then clamps its extents to
skia.committer@gmail.com11a253b2013-11-12 07:02:05 +00001128// 'clamp'. 'offset' is adjusted to remain positioned over the top-left corner
1129// of 'iRect' for all possible outsets/clamps.
commit-bot@chromium.orgdec61502013-12-02 22:22:35 +00001130static inline void clamped_outset_with_offset(SkIRect* iRect,
1131 int outset,
1132 SkPoint* offset,
1133 const SkIRect& clamp) {
1134 iRect->outset(outset, outset);
skia.committer@gmail.com11a253b2013-11-12 07:02:05 +00001135
commit-bot@chromium.orgdec61502013-12-02 22:22:35 +00001136 int leftClampDelta = clamp.fLeft - iRect->fLeft;
1137 if (leftClampDelta > 0) {
1138 offset->fX -= outset - leftClampDelta;
skia.committer@gmail.com11a253b2013-11-12 07:02:05 +00001139 iRect->fLeft = clamp.fLeft;
1140 } else {
commit-bot@chromium.orgdec61502013-12-02 22:22:35 +00001141 offset->fX -= outset;
skia.committer@gmail.com11a253b2013-11-12 07:02:05 +00001142 }
commit-bot@chromium.orgdec61502013-12-02 22:22:35 +00001143
1144 int topClampDelta = clamp.fTop - iRect->fTop;
1145 if (topClampDelta > 0) {
1146 offset->fY -= outset - topClampDelta;
skia.committer@gmail.com11a253b2013-11-12 07:02:05 +00001147 iRect->fTop = clamp.fTop;
1148 } else {
commit-bot@chromium.orgdec61502013-12-02 22:22:35 +00001149 offset->fY -= outset;
skia.committer@gmail.com11a253b2013-11-12 07:02:05 +00001150 }
1151
1152 if (iRect->fRight > clamp.fRight) {
1153 iRect->fRight = clamp.fRight;
1154 }
1155 if (iRect->fBottom > clamp.fBottom) {
1156 iRect->fBottom = clamp.fBottom;
1157 }
1158}
1159
1160void SkGpuDevice::drawBitmapCommon(const SkDraw& draw,
1161 const SkBitmap& bitmap,
1162 const SkRect* srcRectPtr,
commit-bot@chromium.orga7d89c82014-01-13 14:47:00 +00001163 const SkSize* dstSizePtr,
skia.committer@gmail.com11a253b2013-11-12 07:02:05 +00001164 const SkPaint& paint,
1165 SkCanvas::DrawBitmapRectFlags flags) {
1166 CHECK_SHOULD_DRAW(draw, false);
1167
1168 SkRect srcRect;
commit-bot@chromium.orga7d89c82014-01-13 14:47:00 +00001169 SkSize dstSize;
commit-bot@chromium.orgdec61502013-12-02 22:22:35 +00001170 // If there is no src rect, or the src rect contains the entire bitmap then we're effectively
1171 // in the (easier) bleed case, so update flags.
skia.committer@gmail.com11a253b2013-11-12 07:02:05 +00001172 if (NULL == srcRectPtr) {
commit-bot@chromium.orga7d89c82014-01-13 14:47:00 +00001173 SkScalar w = SkIntToScalar(bitmap.width());
1174 SkScalar h = SkIntToScalar(bitmap.height());
1175 dstSize.fWidth = w;
1176 dstSize.fHeight = h;
1177 srcRect.set(0, 0, w, h);
commit-bot@chromium.orgdec61502013-12-02 22:22:35 +00001178 flags = (SkCanvas::DrawBitmapRectFlags) (flags | SkCanvas::kBleed_DrawBitmapRectFlag);
skia.committer@gmail.com11a253b2013-11-12 07:02:05 +00001179 } else {
commit-bot@chromium.orga7d89c82014-01-13 14:47:00 +00001180 SkASSERT(NULL != dstSizePtr);
skia.committer@gmail.com11a253b2013-11-12 07:02:05 +00001181 srcRect = *srcRectPtr;
commit-bot@chromium.orga7d89c82014-01-13 14:47:00 +00001182 dstSize = *dstSizePtr;
commit-bot@chromium.orgdec61502013-12-02 22:22:35 +00001183 if (srcRect.fLeft <= 0 && srcRect.fTop <= 0 &&
1184 srcRect.fRight >= bitmap.width() && srcRect.fBottom >= bitmap.height()) {
1185 flags = (SkCanvas::DrawBitmapRectFlags) (flags | SkCanvas::kBleed_DrawBitmapRectFlag);
1186 }
skia.committer@gmail.com11a253b2013-11-12 07:02:05 +00001187 }
1188
1189 if (paint.getMaskFilter()){
1190 // Convert the bitmap to a shader so that the rect can be drawn
1191 // through drawRect, which supports mask filters.
skia.committer@gmail.com11a253b2013-11-12 07:02:05 +00001192 SkBitmap tmp; // subset of bitmap, if necessary
1193 const SkBitmap* bitmapPtr = &bitmap;
commit-bot@chromium.orga7d89c82014-01-13 14:47:00 +00001194 SkMatrix localM;
skia.committer@gmail.com11a253b2013-11-12 07:02:05 +00001195 if (NULL != srcRectPtr) {
commit-bot@chromium.orga7d89c82014-01-13 14:47:00 +00001196 localM.setTranslate(-srcRectPtr->fLeft, -srcRectPtr->fTop);
1197 localM.postScale(dstSize.fWidth / srcRectPtr->width(),
1198 dstSize.fHeight / srcRectPtr->height());
commit-bot@chromium.orgd6ca4ac2013-11-22 20:34:59 +00001199 // In bleed mode we position and trim the bitmap based on the src rect which is
1200 // already accounted for in 'm' and 'srcRect'. In clamp mode we need to chop out
1201 // the desired portion of the bitmap and then update 'm' and 'srcRect' to
1202 // compensate.
1203 if (!(SkCanvas::kBleed_DrawBitmapRectFlag & flags)) {
1204 SkIRect iSrc;
1205 srcRect.roundOut(&iSrc);
skia.committer@gmail.com11a253b2013-11-12 07:02:05 +00001206
commit-bot@chromium.orgd6ca4ac2013-11-22 20:34:59 +00001207 SkPoint offset = SkPoint::Make(SkIntToScalar(iSrc.fLeft),
1208 SkIntToScalar(iSrc.fTop));
skia.committer@gmail.com11a253b2013-11-12 07:02:05 +00001209
commit-bot@chromium.orgd6ca4ac2013-11-22 20:34:59 +00001210 if (!bitmap.extractSubset(&tmp, iSrc)) {
1211 return; // extraction failed
1212 }
1213 bitmapPtr = &tmp;
1214 srcRect.offset(-offset.fX, -offset.fY);
commit-bot@chromium.orga7d89c82014-01-13 14:47:00 +00001215
commit-bot@chromium.orgd6ca4ac2013-11-22 20:34:59 +00001216 // The source rect has changed so update the matrix
commit-bot@chromium.orga7d89c82014-01-13 14:47:00 +00001217 localM.preTranslate(offset.fX, offset.fY);
skia.committer@gmail.com11a253b2013-11-12 07:02:05 +00001218 }
commit-bot@chromium.orga7d89c82014-01-13 14:47:00 +00001219 } else {
1220 localM.reset();
skia.committer@gmail.com11a253b2013-11-12 07:02:05 +00001221 }
1222
commit-bot@chromium.orga7d89c82014-01-13 14:47:00 +00001223 SkPaint paintWithShader(paint);
1224 paintWithShader.setShader(SkShader::CreateBitmapShader(*bitmapPtr,
skia.committer@gmail.com11a253b2013-11-12 07:02:05 +00001225 SkShader::kClamp_TileMode, SkShader::kClamp_TileMode))->unref();
commit-bot@chromium.orga7d89c82014-01-13 14:47:00 +00001226 paintWithShader.getShader()->setLocalMatrix(localM);
1227 SkRect dstRect = {0, 0, dstSize.fWidth, dstSize.fHeight};
1228 this->drawRect(draw, dstRect, paintWithShader);
skia.committer@gmail.com11a253b2013-11-12 07:02:05 +00001229
1230 return;
1231 }
1232
commit-bot@chromium.orga7d89c82014-01-13 14:47:00 +00001233 // If there is no mask filter than it is OK to handle the src rect -> dst rect scaling using
1234 // the view matrix rather than a local matrix.
1235 SkMatrix m;
1236 m.setScale(dstSize.fWidth / srcRect.width(),
1237 dstSize.fHeight / srcRect.height());
skia.committer@gmail.com11a253b2013-11-12 07:02:05 +00001238 fContext->concatMatrix(m);
1239
1240 GrTextureParams params;
1241 SkPaint::FilterLevel paintFilterLevel = paint.getFilterLevel();
1242 GrTextureParams::FilterMode textureFilterMode;
commit-bot@chromium.orgdec61502013-12-02 22:22:35 +00001243
1244 int tileFilterPad;
1245 bool doBicubic = false;
1246
skia.committer@gmail.com11a253b2013-11-12 07:02:05 +00001247 switch(paintFilterLevel) {
1248 case SkPaint::kNone_FilterLevel:
commit-bot@chromium.orgdec61502013-12-02 22:22:35 +00001249 tileFilterPad = 0;
skia.committer@gmail.com11a253b2013-11-12 07:02:05 +00001250 textureFilterMode = GrTextureParams::kNone_FilterMode;
1251 break;
1252 case SkPaint::kLow_FilterLevel:
commit-bot@chromium.orgdec61502013-12-02 22:22:35 +00001253 tileFilterPad = 1;
skia.committer@gmail.com11a253b2013-11-12 07:02:05 +00001254 textureFilterMode = GrTextureParams::kBilerp_FilterMode;
1255 break;
1256 case SkPaint::kMedium_FilterLevel:
commit-bot@chromium.orgdec61502013-12-02 22:22:35 +00001257 tileFilterPad = 1;
commit-bot@chromium.org79b7eee2013-12-16 21:02:29 +00001258 if (fContext->getMatrix().getMinStretch() < SK_Scalar1) {
1259 textureFilterMode = GrTextureParams::kMipMap_FilterMode;
1260 } else {
1261 // Don't trigger MIP level generation unnecessarily.
1262 textureFilterMode = GrTextureParams::kBilerp_FilterMode;
1263 }
skia.committer@gmail.com11a253b2013-11-12 07:02:05 +00001264 break;
commit-bot@chromium.org79b7eee2013-12-16 21:02:29 +00001265 case SkPaint::kHigh_FilterLevel:
commit-bot@chromium.orgcea9abb2013-12-09 19:15:37 +00001266 // Minification can look bad with the bicubic effect.
commit-bot@chromium.org7d7f3142013-12-16 15:18:11 +00001267 if (fContext->getMatrix().getMinStretch() >= SK_Scalar1) {
commit-bot@chromium.orgdec61502013-12-02 22:22:35 +00001268 // We will install an effect that does the filtering in the shader.
1269 textureFilterMode = GrTextureParams::kNone_FilterMode;
1270 tileFilterPad = GrBicubicEffect::kFilterTexelPad;
1271 doBicubic = true;
1272 } else {
commit-bot@chromium.orgdec61502013-12-02 22:22:35 +00001273 textureFilterMode = GrTextureParams::kMipMap_FilterMode;
1274 tileFilterPad = 1;
1275 }
skia.committer@gmail.com11a253b2013-11-12 07:02:05 +00001276 break;
1277 default:
1278 SkErrorInternals::SetError( kInvalidPaint_SkError,
1279 "Sorry, I don't understand the filtering "
1280 "mode you asked for. Falling back to "
1281 "MIPMaps.");
commit-bot@chromium.orgdec61502013-12-02 22:22:35 +00001282 tileFilterPad = 1;
skia.committer@gmail.com11a253b2013-11-12 07:02:05 +00001283 textureFilterMode = GrTextureParams::kMipMap_FilterMode;
1284 break;
skia.committer@gmail.com11a253b2013-11-12 07:02:05 +00001285 }
1286
1287 params.setFilterMode(textureFilterMode);
1288
commit-bot@chromium.orgdec61502013-12-02 22:22:35 +00001289 int maxTileSize = fContext->getMaxTextureSize() - 2 * tileFilterPad;
skia.committer@gmail.com11a253b2013-11-12 07:02:05 +00001290 int tileSize;
1291
1292 SkIRect clippedSrcRect;
1293 if (this->shouldTileBitmap(bitmap, params, srcRectPtr, maxTileSize, &tileSize,
1294 &clippedSrcRect)) {
commit-bot@chromium.orgdec61502013-12-02 22:22:35 +00001295 this->drawTiledBitmap(bitmap, srcRect, clippedSrcRect, params, paint, flags, tileSize,
1296 doBicubic);
skia.committer@gmail.com11a253b2013-11-12 07:02:05 +00001297 } else {
1298 // take the simple case
commit-bot@chromium.orgdec61502013-12-02 22:22:35 +00001299 this->internalDrawBitmap(bitmap, srcRect, params, paint, flags, doBicubic);
skia.committer@gmail.com11a253b2013-11-12 07:02:05 +00001300 }
1301}
1302
1303// Break 'bitmap' into several tiles to draw it since it has already
1304// been determined to be too large to fit in VRAM
1305void SkGpuDevice::drawTiledBitmap(const SkBitmap& bitmap,
1306 const SkRect& srcRect,
1307 const SkIRect& clippedSrcIRect,
1308 const GrTextureParams& params,
1309 const SkPaint& paint,
1310 SkCanvas::DrawBitmapRectFlags flags,
commit-bot@chromium.orgdec61502013-12-02 22:22:35 +00001311 int tileSize,
1312 bool bicubic) {
skia.committer@gmail.com11a253b2013-11-12 07:02:05 +00001313 SkRect clippedSrcRect = SkRect::Make(clippedSrcIRect);
1314
1315 int nx = bitmap.width() / tileSize;
1316 int ny = bitmap.height() / tileSize;
1317 for (int x = 0; x <= nx; x++) {
1318 for (int y = 0; y <= ny; y++) {
1319 SkRect tileR;
1320 tileR.set(SkIntToScalar(x * tileSize),
1321 SkIntToScalar(y * tileSize),
1322 SkIntToScalar((x + 1) * tileSize),
1323 SkIntToScalar((y + 1) * tileSize));
1324
1325 if (!SkRect::Intersects(tileR, clippedSrcRect)) {
1326 continue;
1327 }
1328
1329 if (!tileR.intersect(srcRect)) {
1330 continue;
1331 }
1332
1333 SkBitmap tmpB;
1334 SkIRect iTileR;
1335 tileR.roundOut(&iTileR);
1336 SkPoint offset = SkPoint::Make(SkIntToScalar(iTileR.fLeft),
1337 SkIntToScalar(iTileR.fTop));
1338
commit-bot@chromium.orga7d89c82014-01-13 14:47:00 +00001339 // Adjust the context matrix to draw at the right x,y in device space
1340 SkMatrix tmpM;
1341 GrContext::AutoMatrix am;
1342 tmpM.setTranslate(offset.fX - srcRect.fLeft, offset.fY - srcRect.fTop);
1343 am.setPreConcat(fContext, tmpM);
1344
commit-bot@chromium.orgdec61502013-12-02 22:22:35 +00001345 if (SkPaint::kNone_FilterLevel != paint.getFilterLevel() || bicubic) {
skia.committer@gmail.com11a253b2013-11-12 07:02:05 +00001346 SkIRect iClampRect;
1347
1348 if (SkCanvas::kBleed_DrawBitmapRectFlag & flags) {
1349 // In bleed mode we want to always expand the tile on all edges
1350 // but stay within the bitmap bounds
1351 iClampRect = SkIRect::MakeWH(bitmap.width(), bitmap.height());
1352 } else {
1353 // In texture-domain/clamp mode we only want to expand the
1354 // tile on edges interior to "srcRect" (i.e., we want to
1355 // not bleed across the original clamped edges)
1356 srcRect.roundOut(&iClampRect);
1357 }
commit-bot@chromium.orgdec61502013-12-02 22:22:35 +00001358 int outset = bicubic ? GrBicubicEffect::kFilterTexelPad : 1;
1359 clamped_outset_with_offset(&iTileR, outset, &offset, iClampRect);
skia.committer@gmail.com11a253b2013-11-12 07:02:05 +00001360 }
1361
1362 if (bitmap.extractSubset(&tmpB, iTileR)) {
1363 // now offset it to make it "local" to our tmp bitmap
1364 tileR.offset(-offset.fX, -offset.fY);
commit-bot@chromium.orga7d89c82014-01-13 14:47:00 +00001365
commit-bot@chromium.orgdec61502013-12-02 22:22:35 +00001366 this->internalDrawBitmap(tmpB, tileR, params, paint, flags, bicubic);
skia.committer@gmail.com11a253b2013-11-12 07:02:05 +00001367 }
1368 }
1369 }
1370}
1371
1372static bool has_aligned_samples(const SkRect& srcRect,
1373 const SkRect& transformedRect) {
1374 // detect pixel disalignment
1375 if (SkScalarAbs(SkScalarRoundToScalar(transformedRect.left()) -
1376 transformedRect.left()) < COLOR_BLEED_TOLERANCE &&
1377 SkScalarAbs(SkScalarRoundToScalar(transformedRect.top()) -
1378 transformedRect.top()) < COLOR_BLEED_TOLERANCE &&
1379 SkScalarAbs(transformedRect.width() - srcRect.width()) <
1380 COLOR_BLEED_TOLERANCE &&
1381 SkScalarAbs(transformedRect.height() - srcRect.height()) <
1382 COLOR_BLEED_TOLERANCE) {
1383 return true;
1384 }
1385 return false;
1386}
1387
1388static bool may_color_bleed(const SkRect& srcRect,
1389 const SkRect& transformedRect,
1390 const SkMatrix& m) {
1391 // Only gets called if has_aligned_samples returned false.
1392 // So we can assume that sampling is axis aligned but not texel aligned.
1393 SkASSERT(!has_aligned_samples(srcRect, transformedRect));
1394 SkRect innerSrcRect(srcRect), innerTransformedRect,
1395 outerTransformedRect(transformedRect);
1396 innerSrcRect.inset(SK_ScalarHalf, SK_ScalarHalf);
1397 m.mapRect(&innerTransformedRect, innerSrcRect);
1398
1399 // The gap between outerTransformedRect and innerTransformedRect
1400 // represents the projection of the source border area, which is
1401 // problematic for color bleeding. We must check whether any
1402 // destination pixels sample the border area.
1403 outerTransformedRect.inset(COLOR_BLEED_TOLERANCE, COLOR_BLEED_TOLERANCE);
1404 innerTransformedRect.outset(COLOR_BLEED_TOLERANCE, COLOR_BLEED_TOLERANCE);
1405 SkIRect outer, inner;
1406 outerTransformedRect.round(&outer);
1407 innerTransformedRect.round(&inner);
1408 // If the inner and outer rects round to the same result, it means the
1409 // border does not overlap any pixel centers. Yay!
1410 return inner != outer;
1411}
1412
1413
1414/*
1415 * This is called by drawBitmap(), which has to handle images that may be too
1416 * large to be represented by a single texture.
1417 *
1418 * internalDrawBitmap assumes that the specified bitmap will fit in a texture
1419 * and that non-texture portion of the GrPaint has already been setup.
1420 */
1421void SkGpuDevice::internalDrawBitmap(const SkBitmap& bitmap,
1422 const SkRect& srcRect,
1423 const GrTextureParams& params,
1424 const SkPaint& paint,
commit-bot@chromium.orgdec61502013-12-02 22:22:35 +00001425 SkCanvas::DrawBitmapRectFlags flags,
1426 bool bicubic) {
skia.committer@gmail.com11a253b2013-11-12 07:02:05 +00001427 SkASSERT(bitmap.width() <= fContext->getMaxTextureSize() &&
1428 bitmap.height() <= fContext->getMaxTextureSize());
1429
1430 GrTexture* texture;
1431 SkAutoCachedTexture act(this, bitmap, &params, &texture);
1432 if (NULL == texture) {
1433 return;
1434 }
1435
commit-bot@chromium.orga7d89c82014-01-13 14:47:00 +00001436 SkRect dstRect = {0, 0, srcRect.width(), srcRect.height() };
skia.committer@gmail.com11a253b2013-11-12 07:02:05 +00001437 SkRect paintRect;
1438 SkScalar wInv = SkScalarInvert(SkIntToScalar(texture->width()));
1439 SkScalar hInv = SkScalarInvert(SkIntToScalar(texture->height()));
1440 paintRect.setLTRB(SkScalarMul(srcRect.fLeft, wInv),
1441 SkScalarMul(srcRect.fTop, hInv),
1442 SkScalarMul(srcRect.fRight, wInv),
1443 SkScalarMul(srcRect.fBottom, hInv));
1444
1445 bool needsTextureDomain = false;
1446 if (!(flags & SkCanvas::kBleed_DrawBitmapRectFlag) &&
commit-bot@chromium.org7d7f3142013-12-16 15:18:11 +00001447 (bicubic || params.filterMode() != GrTextureParams::kNone_FilterMode)) {
1448 // Need texture domain if drawing a sub rect
skia.committer@gmail.com11a253b2013-11-12 07:02:05 +00001449 needsTextureDomain = srcRect.width() < bitmap.width() ||
1450 srcRect.height() < bitmap.height();
commit-bot@chromium.org7d7f3142013-12-16 15:18:11 +00001451 if (!bicubic && needsTextureDomain && fContext->getMatrix().rectStaysRect()) {
skia.committer@gmail.com11a253b2013-11-12 07:02:05 +00001452 const SkMatrix& matrix = fContext->getMatrix();
1453 // sampling is axis-aligned
1454 SkRect transformedRect;
1455 matrix.mapRect(&transformedRect, srcRect);
1456
1457 if (has_aligned_samples(srcRect, transformedRect)) {
1458 // We could also turn off filtering here (but we already did a cache lookup with
1459 // params).
1460 needsTextureDomain = false;
1461 } else {
1462 needsTextureDomain = may_color_bleed(srcRect, transformedRect, matrix);
1463 }
1464 }
1465 }
1466
1467 SkRect textureDomain = SkRect::MakeEmpty();
1468 SkAutoTUnref<GrEffectRef> effect;
1469 if (needsTextureDomain) {
1470 // Use a constrained texture domain to avoid color bleeding
1471 SkScalar left, top, right, bottom;
1472 if (srcRect.width() > SK_Scalar1) {
1473 SkScalar border = SK_ScalarHalf / texture->width();
1474 left = paintRect.left() + border;
1475 right = paintRect.right() - border;
1476 } else {
1477 left = right = SkScalarHalf(paintRect.left() + paintRect.right());
1478 }
1479 if (srcRect.height() > SK_Scalar1) {
1480 SkScalar border = SK_ScalarHalf / texture->height();
1481 top = paintRect.top() + border;
1482 bottom = paintRect.bottom() - border;
1483 } else {
1484 top = bottom = SkScalarHalf(paintRect.top() + paintRect.bottom());
1485 }
1486 textureDomain.setLTRB(left, top, right, bottom);
commit-bot@chromium.org7d7f3142013-12-16 15:18:11 +00001487 if (bicubic) {
1488 effect.reset(GrBicubicEffect::Create(texture, SkMatrix::I(), textureDomain));
1489 } else {
1490 effect.reset(GrTextureDomainEffect::Create(texture,
1491 SkMatrix::I(),
1492 textureDomain,
1493 GrTextureDomain::kClamp_Mode,
1494 params.filterMode()));
1495 }
commit-bot@chromium.orgdec61502013-12-02 22:22:35 +00001496 } else if (bicubic) {
commit-bot@chromium.orgbc91fd72013-12-10 12:53:39 +00001497 SkASSERT(GrTextureParams::kNone_FilterMode == params.filterMode());
1498 SkShader::TileMode tileModes[2] = { params.getTileModeX(), params.getTileModeY() };
1499 effect.reset(GrBicubicEffect::Create(texture, SkMatrix::I(), tileModes));
skia.committer@gmail.com11a253b2013-11-12 07:02:05 +00001500 } else {
1501 effect.reset(GrSimpleTextureEffect::Create(texture, SkMatrix::I(), params));
1502 }
1503
1504 // Construct a GrPaint by setting the bitmap texture as the first effect and then configuring
1505 // the rest from the SkPaint.
1506 GrPaint grPaint;
1507 grPaint.addColorEffect(effect);
1508 bool alphaOnly = !(SkBitmap::kA8_Config == bitmap.config());
1509 if (!skPaint2GrPaintNoShader(this, paint, alphaOnly, false, &grPaint)) {
1510 return;
1511 }
1512
1513 fContext->drawRectToRect(grPaint, dstRect, paintRect, NULL);
1514}
1515
1516static bool filter_texture(SkBaseDevice* device, GrContext* context,
1517 GrTexture* texture, SkImageFilter* filter,
1518 int w, int h, const SkMatrix& ctm, SkBitmap* result,
1519 SkIPoint* offset) {
1520 SkASSERT(filter);
1521 SkDeviceImageFilterProxy proxy(device);
1522
1523 if (filter->canFilterImageGPU()) {
1524 // Save the render target and set it to NULL, so we don't accidentally draw to it in the
1525 // filter. Also set the clip wide open and the matrix to identity.
1526 GrContext::AutoWideOpenIdentityDraw awo(context, NULL);
1527 return filter->filterImageGPU(&proxy, wrap_texture(texture), ctm, result, offset);
1528 } else {
1529 return false;
1530 }
1531}
1532
1533void SkGpuDevice::drawSprite(const SkDraw& draw, const SkBitmap& bitmap,
1534 int left, int top, const SkPaint& paint) {
1535 // drawSprite is defined to be in device coords.
1536 CHECK_SHOULD_DRAW(draw, true);
1537
1538 SkAutoLockPixels alp(bitmap, !bitmap.getTexture());
1539 if (!bitmap.getTexture() && !bitmap.readyToDraw()) {
1540 return;
1541 }
1542
1543 int w = bitmap.width();
1544 int h = bitmap.height();
1545
1546 GrTexture* texture;
1547 // draw sprite uses the default texture params
1548 SkAutoCachedTexture act(this, bitmap, NULL, &texture);
1549
1550 SkImageFilter* filter = paint.getImageFilter();
skia.committer@gmail.com11a253b2013-11-12 07:02:05 +00001551 // This bitmap will own the filtered result as a texture.
1552 SkBitmap filteredBitmap;
1553
1554 if (NULL != filter) {
senorblanco@chromium.org6776b822014-01-03 21:48:22 +00001555 SkIPoint offset = SkIPoint::Make(0, 0);
skia.committer@gmail.com11a253b2013-11-12 07:02:05 +00001556 SkMatrix matrix(*draw.fMatrix);
1557 matrix.postTranslate(SkIntToScalar(-left), SkIntToScalar(-top));
1558 if (filter_texture(this, fContext, texture, filter, w, h, matrix, &filteredBitmap,
1559 &offset)) {
1560 texture = (GrTexture*) filteredBitmap.getTexture();
1561 w = filteredBitmap.width();
1562 h = filteredBitmap.height();
senorblanco@chromium.org6776b822014-01-03 21:48:22 +00001563 left += offset.x();
1564 top += offset.y();
skia.committer@gmail.com11a253b2013-11-12 07:02:05 +00001565 } else {
1566 return;
1567 }
1568 }
1569
1570 GrPaint grPaint;
1571 grPaint.addColorTextureEffect(texture, SkMatrix::I());
1572
1573 if(!skPaint2GrPaintNoShader(this, paint, true, false, &grPaint)) {
1574 return;
1575 }
1576
1577 fContext->drawRectToRect(grPaint,
senorblanco@chromium.org6776b822014-01-03 21:48:22 +00001578 SkRect::MakeXYWH(SkIntToScalar(left),
1579 SkIntToScalar(top),
skia.committer@gmail.com11a253b2013-11-12 07:02:05 +00001580 SkIntToScalar(w),
1581 SkIntToScalar(h)),
1582 SkRect::MakeXYWH(0,
1583 0,
1584 SK_Scalar1 * w / texture->width(),
1585 SK_Scalar1 * h / texture->height()));
1586}
1587
commit-bot@chromium.orga7d89c82014-01-13 14:47:00 +00001588void SkGpuDevice::drawBitmapRect(const SkDraw& origDraw, const SkBitmap& bitmap,
skia.committer@gmail.com11a253b2013-11-12 07:02:05 +00001589 const SkRect* src, const SkRect& dst,
1590 const SkPaint& paint,
1591 SkCanvas::DrawBitmapRectFlags flags) {
1592 SkMatrix matrix;
1593 SkRect bitmapBounds, tmpSrc;
1594
1595 bitmapBounds.set(0, 0,
1596 SkIntToScalar(bitmap.width()),
1597 SkIntToScalar(bitmap.height()));
1598
1599 // Compute matrix from the two rectangles
1600 if (NULL != src) {
1601 tmpSrc = *src;
1602 } else {
1603 tmpSrc = bitmapBounds;
1604 }
commit-bot@chromium.orga7d89c82014-01-13 14:47:00 +00001605
skia.committer@gmail.com11a253b2013-11-12 07:02:05 +00001606 matrix.setRectToRect(tmpSrc, dst, SkMatrix::kFill_ScaleToFit);
1607
1608 // clip the tmpSrc to the bounds of the bitmap. No check needed if src==null.
1609 if (NULL != src) {
1610 if (!bitmapBounds.contains(tmpSrc)) {
1611 if (!tmpSrc.intersect(bitmapBounds)) {
1612 return; // nothing to draw
1613 }
1614 }
1615 }
1616
commit-bot@chromium.orga7d89c82014-01-13 14:47:00 +00001617 SkRect tmpDst;
1618 matrix.mapRect(&tmpDst, tmpSrc);
1619
1620 SkTCopyOnFirstWrite<SkDraw> draw(origDraw);
1621 if (0 != tmpDst.fLeft || 0 != tmpDst.fTop) {
1622 // Translate so that tempDst's top left is at the origin.
1623 matrix = *origDraw.fMatrix;
1624 matrix.preTranslate(tmpDst.fLeft, tmpDst.fTop);
1625 draw.writable()->fMatrix = &matrix;
1626 }
1627 SkSize dstSize;
1628 dstSize.fWidth = tmpDst.width();
1629 dstSize.fHeight = tmpDst.height();
1630
1631 this->drawBitmapCommon(*draw, bitmap, &tmpSrc, &dstSize, paint, flags);
skia.committer@gmail.com11a253b2013-11-12 07:02:05 +00001632}
1633
1634void SkGpuDevice::drawDevice(const SkDraw& draw, SkBaseDevice* device,
1635 int x, int y, const SkPaint& paint) {
1636 // clear of the source device must occur before CHECK_SHOULD_DRAW
1637 SkGpuDevice* dev = static_cast<SkGpuDevice*>(device);
1638 if (dev->fNeedClear) {
1639 // TODO: could check here whether we really need to draw at all
1640 dev->clear(0x0);
1641 }
1642
1643 // drawDevice is defined to be in device coords.
1644 CHECK_SHOULD_DRAW(draw, true);
1645
1646 GrRenderTarget* devRT = dev->accessRenderTarget();
1647 GrTexture* devTex;
1648 if (NULL == (devTex = devRT->asTexture())) {
1649 return;
1650 }
1651
1652 const SkBitmap& bm = dev->accessBitmap(false);
1653 int w = bm.width();
1654 int h = bm.height();
1655
1656 SkImageFilter* filter = paint.getImageFilter();
1657 // This bitmap will own the filtered result as a texture.
1658 SkBitmap filteredBitmap;
1659
1660 if (NULL != filter) {
1661 SkIPoint offset = SkIPoint::Make(0, 0);
1662 SkMatrix matrix(*draw.fMatrix);
1663 matrix.postTranslate(SkIntToScalar(-x), SkIntToScalar(-y));
1664 if (filter_texture(this, fContext, devTex, filter, w, h, matrix, &filteredBitmap,
1665 &offset)) {
1666 devTex = filteredBitmap.getTexture();
1667 w = filteredBitmap.width();
1668 h = filteredBitmap.height();
1669 x += offset.fX;
1670 y += offset.fY;
1671 } else {
1672 return;
1673 }
1674 }
1675
1676 GrPaint grPaint;
1677 grPaint.addColorTextureEffect(devTex, SkMatrix::I());
1678
1679 if (!skPaint2GrPaintNoShader(this, paint, true, false, &grPaint)) {
1680 return;
1681 }
1682
1683 SkRect dstRect = SkRect::MakeXYWH(SkIntToScalar(x),
1684 SkIntToScalar(y),
1685 SkIntToScalar(w),
1686 SkIntToScalar(h));
1687
1688 // The device being drawn may not fill up its texture (e.g. saveLayer uses approximate
1689 // scratch texture).
1690 SkRect srcRect = SkRect::MakeWH(SK_Scalar1 * w / devTex->width(),
1691 SK_Scalar1 * h / devTex->height());
1692
1693 fContext->drawRectToRect(grPaint, dstRect, srcRect);
1694}
1695
1696bool SkGpuDevice::canHandleImageFilter(SkImageFilter* filter) {
1697 return filter->canFilterImageGPU();
1698}
1699
1700bool SkGpuDevice::filterImage(SkImageFilter* filter, const SkBitmap& src,
1701 const SkMatrix& ctm,
1702 SkBitmap* result, SkIPoint* offset) {
1703 // want explicitly our impl, so guard against a subclass of us overriding it
1704 if (!this->SkGpuDevice::canHandleImageFilter(filter)) {
1705 return false;
1706 }
1707
1708 SkAutoLockPixels alp(src, !src.getTexture());
1709 if (!src.getTexture() && !src.readyToDraw()) {
1710 return false;
1711 }
1712
1713 GrTexture* texture;
1714 // We assume here that the filter will not attempt to tile the src. Otherwise, this cache lookup
1715 // must be pushed upstack.
1716 SkAutoCachedTexture act(this, src, NULL, &texture);
1717
1718 return filter_texture(this, fContext, texture, filter, src.width(), src.height(), ctm, result,
1719 offset);
1720}
1721
1722///////////////////////////////////////////////////////////////////////////////
1723
1724// must be in SkCanvas::VertexMode order
1725static const GrPrimitiveType gVertexMode2PrimitiveType[] = {
1726 kTriangles_GrPrimitiveType,
1727 kTriangleStrip_GrPrimitiveType,
1728 kTriangleFan_GrPrimitiveType,
1729};
1730
1731void SkGpuDevice::drawVertices(const SkDraw& draw, SkCanvas::VertexMode vmode,
1732 int vertexCount, const SkPoint vertices[],
1733 const SkPoint texs[], const SkColor colors[],
1734 SkXfermode* xmode,
1735 const uint16_t indices[], int indexCount,
1736 const SkPaint& paint) {
1737 CHECK_SHOULD_DRAW(draw, false);
1738
1739 GrPaint grPaint;
1740 // we ignore the shader if texs is null.
1741 if (NULL == texs) {
1742 if (!skPaint2GrPaintNoShader(this, paint, false, NULL == colors, &grPaint)) {
1743 return;
1744 }
1745 } else {
1746 if (!skPaint2GrPaintShader(this, paint, NULL == colors, &grPaint)) {
1747 return;
1748 }
1749 }
1750
1751 if (NULL != xmode && NULL != texs && NULL != colors) {
1752 if (!SkXfermode::IsMode(xmode, SkXfermode::kModulate_Mode)) {
1753 SkDebugf("Unsupported vertex-color/texture xfer mode.\n");
1754#if 0
1755 return
1756#endif
1757 }
1758 }
1759
1760 SkAutoSTMalloc<128, GrColor> convertedColors(0);
1761 if (NULL != colors) {
1762 // need to convert byte order and from non-PM to PM
1763 convertedColors.reset(vertexCount);
1764 for (int i = 0; i < vertexCount; ++i) {
1765 convertedColors[i] = SkColor2GrColor(colors[i]);
1766 }
1767 colors = convertedColors.get();
1768 }
1769 fContext->drawVertices(grPaint,
1770 gVertexMode2PrimitiveType[vmode],
1771 vertexCount,
1772 (GrPoint*) vertices,
1773 (GrPoint*) texs,
1774 colors,
1775 indices,
1776 indexCount);
1777}
1778
1779///////////////////////////////////////////////////////////////////////////////
1780
skia.committer@gmail.com11a253b2013-11-12 07:02:05 +00001781void SkGpuDevice::drawText(const SkDraw& draw, const void* text,
1782 size_t byteLength, SkScalar x, SkScalar y,
1783 const SkPaint& paint) {
1784 CHECK_SHOULD_DRAW(draw, false);
1785
commit-bot@chromium.orgcbbc4812014-01-30 22:05:47 +00001786 if (fMainTextContext->canDraw(paint)) {
commit-bot@chromium.org8128d8c2013-12-19 16:12:25 +00001787 GrPaint grPaint;
1788 if (!skPaint2GrPaintShader(this, paint, true, &grPaint)) {
1789 return;
1790 }
1791
1792 SkDEBUGCODE(this->validate();)
1793
commit-bot@chromium.orgcbbc4812014-01-30 22:05:47 +00001794 fMainTextContext->drawText(grPaint, paint, (const char *)text, byteLength, x, y);
1795 } else if (fFallbackTextContext && fFallbackTextContext->canDraw(paint)) {
commit-bot@chromium.org9f94b912014-01-30 15:22:54 +00001796 GrPaint grPaint;
1797 if (!skPaint2GrPaintShader(this, paint, true, &grPaint)) {
1798 return;
1799 }
1800
1801 SkDEBUGCODE(this->validate();)
1802
commit-bot@chromium.orgcbbc4812014-01-30 22:05:47 +00001803 fFallbackTextContext->drawText(grPaint, paint, (const char *)text, byteLength, x, y);
commit-bot@chromium.org9f94b912014-01-30 15:22:54 +00001804 } else {
1805 // this guy will just call our drawPath()
1806 draw.drawText_asPaths((const char*)text, byteLength, x, y, paint);
skia.committer@gmail.com11a253b2013-11-12 07:02:05 +00001807 }
1808}
1809
1810void SkGpuDevice::drawPosText(const SkDraw& draw, const void* text,
1811 size_t byteLength, const SkScalar pos[],
1812 SkScalar constY, int scalarsPerPos,
1813 const SkPaint& paint) {
1814 CHECK_SHOULD_DRAW(draw, false);
1815
commit-bot@chromium.orgcbbc4812014-01-30 22:05:47 +00001816 if (fMainTextContext->canDraw(paint)) {
commit-bot@chromium.org8128d8c2013-12-19 16:12:25 +00001817 GrPaint grPaint;
1818 if (!skPaint2GrPaintShader(this, paint, true, &grPaint)) {
1819 return;
1820 }
1821
1822 SkDEBUGCODE(this->validate();)
1823
skia.committer@gmail.com4c18e9f2014-01-31 03:01:59 +00001824 fMainTextContext->drawPosText(grPaint, paint, (const char *)text, byteLength, pos,
commit-bot@chromium.orgcbbc4812014-01-30 22:05:47 +00001825 constY, scalarsPerPos);
1826 } else if (fFallbackTextContext && fFallbackTextContext->canDraw(paint)) {
commit-bot@chromium.org9f94b912014-01-30 15:22:54 +00001827 GrPaint grPaint;
1828 if (!skPaint2GrPaintShader(this, paint, true, &grPaint)) {
1829 return;
1830 }
skia.committer@gmail.com4c18e9f2014-01-31 03:01:59 +00001831
commit-bot@chromium.org9f94b912014-01-30 15:22:54 +00001832 SkDEBUGCODE(this->validate();)
skia.committer@gmail.com4c18e9f2014-01-31 03:01:59 +00001833
1834 fFallbackTextContext->drawPosText(grPaint, paint, (const char *)text, byteLength, pos,
commit-bot@chromium.orgcbbc4812014-01-30 22:05:47 +00001835 constY, scalarsPerPos);
commit-bot@chromium.org9f94b912014-01-30 15:22:54 +00001836 } else {
1837 draw.drawPosText_asPaths((const char*)text, byteLength, pos, constY,
1838 scalarsPerPos, paint);
skia.committer@gmail.com11a253b2013-11-12 07:02:05 +00001839 }
1840}
1841
1842void SkGpuDevice::drawTextOnPath(const SkDraw& draw, const void* text,
1843 size_t len, const SkPath& path,
1844 const SkMatrix* m, const SkPaint& paint) {
1845 CHECK_SHOULD_DRAW(draw, false);
1846
1847 SkASSERT(draw.fDevice == this);
1848 draw.drawTextOnPath((const char*)text, len, path, m, paint);
1849}
1850
1851///////////////////////////////////////////////////////////////////////////////
1852
1853bool SkGpuDevice::filterTextFlags(const SkPaint& paint, TextFlags* flags) {
1854 if (!paint.isLCDRenderText()) {
1855 // we're cool with the paint as is
1856 return false;
1857 }
1858
1859 if (paint.getShader() ||
1860 paint.getXfermode() || // unless its srcover
1861 paint.getMaskFilter() ||
1862 paint.getRasterizer() ||
1863 paint.getColorFilter() ||
1864 paint.getPathEffect() ||
1865 paint.isFakeBoldText() ||
1866 paint.getStyle() != SkPaint::kFill_Style) {
1867 // turn off lcd
1868 flags->fFlags = paint.getFlags() & ~SkPaint::kLCDRenderText_Flag;
1869 flags->fHinting = paint.getHinting();
1870 return true;
1871 }
1872 // we're cool with the paint as is
1873 return false;
1874}
1875
1876void SkGpuDevice::flush() {
1877 DO_DEFERRED_CLEAR();
1878 fContext->resolveRenderTarget(fRenderTarget);
1879}
1880
1881///////////////////////////////////////////////////////////////////////////////
1882
1883SkBaseDevice* SkGpuDevice::onCreateCompatibleDevice(SkBitmap::Config config,
1884 int width, int height,
1885 bool isOpaque,
1886 Usage usage) {
1887 GrTextureDesc desc;
1888 desc.fConfig = fRenderTarget->config();
1889 desc.fFlags = kRenderTarget_GrTextureFlagBit;
1890 desc.fWidth = width;
1891 desc.fHeight = height;
1892 desc.fSampleCnt = fRenderTarget->numSamples();
1893
1894 SkAutoTUnref<GrTexture> texture;
1895 // Skia's convention is to only clear a device if it is non-opaque.
1896 bool needClear = !isOpaque;
1897
1898#if CACHE_COMPATIBLE_DEVICE_TEXTURES
1899 // layers are never draw in repeat modes, so we can request an approx
1900 // match and ignore any padding.
1901 const GrContext::ScratchTexMatch match = (kSaveLayer_Usage == usage) ?
1902 GrContext::kApprox_ScratchTexMatch :
1903 GrContext::kExact_ScratchTexMatch;
1904 texture.reset(fContext->lockAndRefScratchTexture(desc, match));
1905#else
1906 texture.reset(fContext->createUncachedTexture(desc, NULL, 0));
1907#endif
1908 if (NULL != texture.get()) {
1909 return SkNEW_ARGS(SkGpuDevice,(fContext, texture, needClear));
1910 } else {
1911 GrPrintf("---- failed to create compatible device texture [%d %d]\n", width, height);
1912 return NULL;
1913 }
1914}
1915
1916SkGpuDevice::SkGpuDevice(GrContext* context,
1917 GrTexture* texture,
1918 bool needClear)
1919 : SkBitmapDevice(make_bitmap(context, texture->asRenderTarget())) {
1920
1921 SkASSERT(texture && texture->asRenderTarget());
1922 // This constructor is called from onCreateCompatibleDevice. It has locked the RT in the texture
1923 // cache. We pass true for the third argument so that it will get unlocked.
1924 this->initFromRenderTarget(context, texture->asRenderTarget(), true);
1925 fNeedClear = needClear;
1926}