blob: 6160876dd18d59e1af06fdebb167b3440f3cbd8a [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
204 fTextContextManager = SkNEW(GrTTextContextManager<GrDistanceFieldTextContext>);
205#else
206 fTextContextManager = SkNEW(GrTTextContextManager<GrBitmapTextContext>);
207#endif
208
skia.committer@gmail.com11a253b2013-11-12 07:02:05 +0000209 fRenderTarget = NULL;
210 fNeedClear = false;
211
212 SkASSERT(NULL != renderTarget);
213 fRenderTarget = renderTarget;
214 fRenderTarget->ref();
215
216 // Hold onto to the texture in the pixel ref (if there is one) because the texture holds a ref
217 // on the RT but not vice-versa.
218 // TODO: Remove this trickery once we figure out how to make SkGrPixelRef do this without
219 // busting chrome (for a currently unknown reason).
220 GrSurface* surface = fRenderTarget->asTexture();
221 if (NULL == surface) {
222 surface = fRenderTarget;
223 }
reed@google.combf790232013-12-13 19:45:58 +0000224
225 SkImageInfo info;
226 surface->asImageInfo(&info);
227 SkPixelRef* pr = SkNEW_ARGS(SkGrPixelRef, (info, surface, cached));
skia.committer@gmail.com11a253b2013-11-12 07:02:05 +0000228
reed@google.com672588b2014-01-08 15:42:01 +0000229 this->setPixelRef(pr)->unref();
skia.committer@gmail.com11a253b2013-11-12 07:02:05 +0000230}
231
232SkGpuDevice::SkGpuDevice(GrContext* context,
233 SkBitmap::Config config,
234 int width,
235 int height,
236 int sampleCount)
reed@google.combf790232013-12-13 19:45:58 +0000237 : SkBitmapDevice(make_bitmap(config, width, height, false /*isOpaque*/))
238{
skia.committer@gmail.com11a253b2013-11-12 07:02:05 +0000239 fDrawProcs = NULL;
240
241 fContext = context;
242 fContext->ref();
243
commit-bot@chromium.orgcc40f062014-01-24 14:38:27 +0000244#if SK_DISTANCEFIELD_FONTS
245 fTextContextManager = SkNEW(GrTTextContextManager<GrDistanceFieldTextContext>);
246#else
247 fTextContextManager = SkNEW(GrTTextContextManager<GrBitmapTextContext>);
248#endif
249
skia.committer@gmail.com11a253b2013-11-12 07:02:05 +0000250 fRenderTarget = NULL;
251 fNeedClear = false;
252
253 if (config != SkBitmap::kRGB_565_Config) {
254 config = SkBitmap::kARGB_8888_Config;
255 }
256
257 GrTextureDesc desc;
258 desc.fFlags = kRenderTarget_GrTextureFlagBit;
259 desc.fWidth = width;
260 desc.fHeight = height;
261 desc.fConfig = SkBitmapConfig2GrPixelConfig(config);
262 desc.fSampleCnt = sampleCount;
263
reed@google.combf790232013-12-13 19:45:58 +0000264 SkImageInfo info;
265 if (!GrPixelConfig2ColorType(desc.fConfig, &info.fColorType)) {
266 sk_throw();
267 }
268 info.fWidth = width;
269 info.fHeight = height;
270 info.fAlphaType = kPremul_SkAlphaType;
skia.committer@gmail.com96f5fa02013-12-16 07:01:40 +0000271
skia.committer@gmail.com11a253b2013-11-12 07:02:05 +0000272 SkAutoTUnref<GrTexture> texture(fContext->createUncachedTexture(desc, NULL, 0));
273
274 if (NULL != texture) {
275 fRenderTarget = texture->asRenderTarget();
276 fRenderTarget->ref();
277
278 SkASSERT(NULL != fRenderTarget);
279
280 // wrap the bitmap with a pixelref to expose our texture
reed@google.combf790232013-12-13 19:45:58 +0000281 SkGrPixelRef* pr = SkNEW_ARGS(SkGrPixelRef, (info, texture));
reed@google.com672588b2014-01-08 15:42:01 +0000282 this->setPixelRef(pr)->unref();
skia.committer@gmail.com11a253b2013-11-12 07:02:05 +0000283 } else {
284 GrPrintf("--- failed to create gpu-offscreen [%d %d]\n",
285 width, height);
286 SkASSERT(false);
287 }
288}
289
290SkGpuDevice::~SkGpuDevice() {
291 if (fDrawProcs) {
292 delete fDrawProcs;
293 }
skia.committer@gmail.comd2ac07b2014-01-25 07:01:49 +0000294
commit-bot@chromium.orgcc40f062014-01-24 14:38:27 +0000295 delete fTextContextManager;
skia.committer@gmail.com11a253b2013-11-12 07:02:05 +0000296
297 // The GrContext takes a ref on the target. We don't want to cause the render
298 // target to be unnecessarily kept alive.
299 if (fContext->getRenderTarget() == fRenderTarget) {
300 fContext->setRenderTarget(NULL);
301 }
302
303 if (fContext->getClip() == &fClipData) {
304 fContext->setClip(NULL);
305 }
306
307 SkSafeUnref(fRenderTarget);
308 fContext->unref();
309}
310
311///////////////////////////////////////////////////////////////////////////////
312
313void SkGpuDevice::makeRenderTargetCurrent() {
314 DO_DEFERRED_CLEAR();
315 fContext->setRenderTarget(fRenderTarget);
316}
317
318///////////////////////////////////////////////////////////////////////////////
319
320namespace {
321GrPixelConfig config8888_to_grconfig_and_flags(SkCanvas::Config8888 config8888, uint32_t* flags) {
322 switch (config8888) {
323 case SkCanvas::kNative_Premul_Config8888:
324 *flags = 0;
325 return kSkia8888_GrPixelConfig;
326 case SkCanvas::kNative_Unpremul_Config8888:
327 *flags = GrContext::kUnpremul_PixelOpsFlag;
328 return kSkia8888_GrPixelConfig;
329 case SkCanvas::kBGRA_Premul_Config8888:
330 *flags = 0;
331 return kBGRA_8888_GrPixelConfig;
332 case SkCanvas::kBGRA_Unpremul_Config8888:
333 *flags = GrContext::kUnpremul_PixelOpsFlag;
334 return kBGRA_8888_GrPixelConfig;
335 case SkCanvas::kRGBA_Premul_Config8888:
336 *flags = 0;
337 return kRGBA_8888_GrPixelConfig;
338 case SkCanvas::kRGBA_Unpremul_Config8888:
339 *flags = GrContext::kUnpremul_PixelOpsFlag;
340 return kRGBA_8888_GrPixelConfig;
341 default:
342 GrCrash("Unexpected Config8888.");
343 *flags = 0; // suppress warning
344 return kSkia8888_GrPixelConfig;
345 }
346}
347}
348
349bool SkGpuDevice::onReadPixels(const SkBitmap& bitmap,
350 int x, int y,
351 SkCanvas::Config8888 config8888) {
352 DO_DEFERRED_CLEAR();
353 SkASSERT(SkBitmap::kARGB_8888_Config == bitmap.config());
354 SkASSERT(!bitmap.isNull());
355 SkASSERT(SkIRect::MakeWH(this->width(), this->height()).contains(SkIRect::MakeXYWH(x, y, bitmap.width(), bitmap.height())));
356
357 SkAutoLockPixels alp(bitmap);
358 GrPixelConfig config;
359 uint32_t flags;
360 config = config8888_to_grconfig_and_flags(config8888, &flags);
361 return fContext->readRenderTargetPixels(fRenderTarget,
362 x, y,
363 bitmap.width(),
364 bitmap.height(),
365 config,
366 bitmap.getPixels(),
367 bitmap.rowBytes(),
368 flags);
369}
370
371void SkGpuDevice::writePixels(const SkBitmap& bitmap, int x, int y,
372 SkCanvas::Config8888 config8888) {
373 SkAutoLockPixels alp(bitmap);
374 if (!bitmap.readyToDraw()) {
375 return;
376 }
377
378 GrPixelConfig config;
379 uint32_t flags;
380 if (SkBitmap::kARGB_8888_Config == bitmap.config()) {
381 config = config8888_to_grconfig_and_flags(config8888, &flags);
382 } else {
383 flags = 0;
384 config= SkBitmapConfig2GrPixelConfig(bitmap.config());
385 }
386
387 fRenderTarget->writePixels(x, y, bitmap.width(), bitmap.height(),
388 config, bitmap.getPixels(), bitmap.rowBytes(), flags);
389}
390
391void SkGpuDevice::onAttachToCanvas(SkCanvas* canvas) {
392 INHERITED::onAttachToCanvas(canvas);
393
394 // Canvas promises that this ptr is valid until onDetachFromCanvas is called
395 fClipData.fClipStack = canvas->getClipStack();
396}
397
398void SkGpuDevice::onDetachFromCanvas() {
399 INHERITED::onDetachFromCanvas();
400 fClipData.fClipStack = NULL;
401}
402
403// call this every draw call, to ensure that the context reflects our state,
404// and not the state from some other canvas/device
405void SkGpuDevice::prepareDraw(const SkDraw& draw, bool forceIdentity) {
406 SkASSERT(NULL != fClipData.fClipStack);
407
408 fContext->setRenderTarget(fRenderTarget);
409
410 SkASSERT(draw.fClipStack && draw.fClipStack == fClipData.fClipStack);
411
412 if (forceIdentity) {
413 fContext->setIdentityMatrix();
414 } else {
415 fContext->setMatrix(*draw.fMatrix);
416 }
417 fClipData.fOrigin = this->getOrigin();
418
419 fContext->setClip(&fClipData);
420
421 DO_DEFERRED_CLEAR();
422}
423
424GrRenderTarget* SkGpuDevice::accessRenderTarget() {
425 DO_DEFERRED_CLEAR();
426 return fRenderTarget;
427}
428
429///////////////////////////////////////////////////////////////////////////////
430
431SK_COMPILE_ASSERT(SkShader::kNone_BitmapType == 0, shader_type_mismatch);
432SK_COMPILE_ASSERT(SkShader::kDefault_BitmapType == 1, shader_type_mismatch);
433SK_COMPILE_ASSERT(SkShader::kRadial_BitmapType == 2, shader_type_mismatch);
434SK_COMPILE_ASSERT(SkShader::kSweep_BitmapType == 3, shader_type_mismatch);
435SK_COMPILE_ASSERT(SkShader::kTwoPointRadial_BitmapType == 4,
436 shader_type_mismatch);
437SK_COMPILE_ASSERT(SkShader::kTwoPointConical_BitmapType == 5,
438 shader_type_mismatch);
439SK_COMPILE_ASSERT(SkShader::kLinear_BitmapType == 6, shader_type_mismatch);
440SK_COMPILE_ASSERT(SkShader::kLast_BitmapType == 6, shader_type_mismatch);
441
442namespace {
443
444// converts a SkPaint to a GrPaint, ignoring the skPaint's shader
445// justAlpha indicates that skPaint's alpha should be used rather than the color
446// Callers may subsequently modify the GrPaint. Setting constantColor indicates
447// that the final paint will draw the same color at every pixel. This allows
448// an optimization where the the color filter can be applied to the skPaint's
449// color once while converting to GrPaint and then ignored.
450inline bool skPaint2GrPaintNoShader(SkGpuDevice* dev,
451 const SkPaint& skPaint,
452 bool justAlpha,
453 bool constantColor,
454 GrPaint* grPaint) {
455
456 grPaint->setDither(skPaint.isDither());
457 grPaint->setAntiAlias(skPaint.isAntiAlias());
458
459 SkXfermode::Coeff sm;
460 SkXfermode::Coeff dm;
461
462 SkXfermode* mode = skPaint.getXfermode();
463 GrEffectRef* xferEffect = NULL;
464 if (SkXfermode::AsNewEffectOrCoeff(mode, &xferEffect, &sm, &dm)) {
465 if (NULL != xferEffect) {
466 grPaint->addColorEffect(xferEffect)->unref();
467 sm = SkXfermode::kOne_Coeff;
468 dm = SkXfermode::kZero_Coeff;
469 }
470 } else {
471 //SkDEBUGCODE(SkDebugf("Unsupported xfer mode.\n");)
472#if 0
473 return false;
474#else
475 // Fall back to src-over
476 sm = SkXfermode::kOne_Coeff;
477 dm = SkXfermode::kISA_Coeff;
478#endif
479 }
480 grPaint->setBlendFunc(sk_blend_to_grblend(sm), sk_blend_to_grblend(dm));
481
482 if (justAlpha) {
483 uint8_t alpha = skPaint.getAlpha();
484 grPaint->setColor(GrColorPackRGBA(alpha, alpha, alpha, alpha));
485 // justAlpha is currently set to true only if there is a texture,
486 // so constantColor should not also be true.
487 SkASSERT(!constantColor);
488 } else {
489 grPaint->setColor(SkColor2GrColor(skPaint.getColor()));
490 }
491
492 SkColorFilter* colorFilter = skPaint.getColorFilter();
493 if (NULL != colorFilter) {
494 // if the source color is a constant then apply the filter here once rather than per pixel
495 // in a shader.
496 if (constantColor) {
497 SkColor filtered = colorFilter->filterColor(skPaint.getColor());
498 grPaint->setColor(SkColor2GrColor(filtered));
499 } else {
500 SkAutoTUnref<GrEffectRef> effect(colorFilter->asNewEffect(dev->context()));
501 if (NULL != effect.get()) {
502 grPaint->addColorEffect(effect);
503 }
504 }
505 }
506
507 return true;
508}
509
510// This function is similar to skPaint2GrPaintNoShader but also converts
511// skPaint's shader to a GrTexture/GrEffectStage if possible. The texture to
512// be used is set on grPaint and returned in param act. constantColor has the
513// same meaning as in skPaint2GrPaintNoShader.
514inline bool skPaint2GrPaintShader(SkGpuDevice* dev,
515 const SkPaint& skPaint,
516 bool constantColor,
517 GrPaint* grPaint) {
518 SkShader* shader = skPaint.getShader();
519 if (NULL == shader) {
520 return skPaint2GrPaintNoShader(dev, skPaint, false, constantColor, grPaint);
521 }
522
commit-bot@chromium.org60770572014-01-13 15:57:05 +0000523 // SkShader::asNewEffect() may do offscreen rendering. Setup default drawing state and require
524 // the shader to set a render target .
skia.committer@gmail.com11a253b2013-11-12 07:02:05 +0000525 GrContext::AutoWideOpenIdentityDraw awo(dev->context(), NULL);
skia.committer@gmail.com11a253b2013-11-12 07:02:05 +0000526
527 // setup the shader as the first color effect on the paint
528 SkAutoTUnref<GrEffectRef> effect(shader->asNewEffect(dev->context(), skPaint));
529 if (NULL != effect.get()) {
530 grPaint->addColorEffect(effect);
531 // Now setup the rest of the paint.
532 return skPaint2GrPaintNoShader(dev, skPaint, true, false, grPaint);
533 } else {
534 // We still don't have SkColorShader::asNewEffect() implemented.
535 SkShader::GradientInfo info;
536 SkColor color;
537
538 info.fColors = &color;
539 info.fColorOffsets = NULL;
540 info.fColorCount = 1;
541 if (SkShader::kColor_GradientType == shader->asAGradient(&info)) {
542 SkPaint copy(skPaint);
543 copy.setShader(NULL);
544 // modulate the paint alpha by the shader's solid color alpha
545 U8CPU newA = SkMulDiv255Round(SkColorGetA(color), copy.getAlpha());
546 copy.setColor(SkColorSetA(color, newA));
547 return skPaint2GrPaintNoShader(dev, copy, false, constantColor, grPaint);
548 } else {
549 return false;
550 }
551 }
552}
553}
554
555///////////////////////////////////////////////////////////////////////////////
skia.committer@gmail.com11a253b2013-11-12 07:02:05 +0000556
557SkBitmap::Config SkGpuDevice::config() const {
558 if (NULL == fRenderTarget) {
559 return SkBitmap::kNo_Config;
560 }
561
562 bool isOpaque;
563 return grConfig2skConfig(fRenderTarget->config(), &isOpaque);
564}
565
566void SkGpuDevice::clear(SkColor color) {
567 SkIRect rect = SkIRect::MakeWH(this->width(), this->height());
568 fContext->clear(&rect, SkColor2GrColor(color), true, fRenderTarget);
569 fNeedClear = false;
570}
571
572void SkGpuDevice::drawPaint(const SkDraw& draw, const SkPaint& paint) {
573 CHECK_SHOULD_DRAW(draw, false);
574
575 GrPaint grPaint;
576 if (!skPaint2GrPaintShader(this, paint, true, &grPaint)) {
577 return;
578 }
579
580 fContext->drawPaint(grPaint);
581}
582
583// must be in SkCanvas::PointMode order
584static const GrPrimitiveType gPointMode2PrimtiveType[] = {
585 kPoints_GrPrimitiveType,
586 kLines_GrPrimitiveType,
587 kLineStrip_GrPrimitiveType
588};
589
590void SkGpuDevice::drawPoints(const SkDraw& draw, SkCanvas::PointMode mode,
591 size_t count, const SkPoint pts[], const SkPaint& paint) {
592 CHECK_FOR_ANNOTATION(paint);
593 CHECK_SHOULD_DRAW(draw, false);
594
595 SkScalar width = paint.getStrokeWidth();
596 if (width < 0) {
597 return;
598 }
599
600 // we only handle hairlines and paints without path effects or mask filters,
601 // else we let the SkDraw call our drawPath()
602 if (width > 0 || paint.getPathEffect() || paint.getMaskFilter()) {
603 draw.drawPoints(mode, count, pts, paint, true);
604 return;
605 }
606
607 GrPaint grPaint;
608 if (!skPaint2GrPaintShader(this, paint, true, &grPaint)) {
609 return;
610 }
611
612 fContext->drawVertices(grPaint,
613 gPointMode2PrimtiveType[mode],
robertphillips@google.coma4662862013-11-21 14:24:16 +0000614 SkToS32(count),
skia.committer@gmail.com11a253b2013-11-12 07:02:05 +0000615 (GrPoint*)pts,
616 NULL,
617 NULL,
618 NULL,
619 0);
620}
621
622///////////////////////////////////////////////////////////////////////////////
623
624void SkGpuDevice::drawRect(const SkDraw& draw, const SkRect& rect,
625 const SkPaint& paint) {
626 CHECK_FOR_ANNOTATION(paint);
627 CHECK_SHOULD_DRAW(draw, false);
628
629 bool doStroke = paint.getStyle() != SkPaint::kFill_Style;
630 SkScalar width = paint.getStrokeWidth();
631
632 /*
633 We have special code for hairline strokes, miter-strokes, bevel-stroke
634 and fills. Anything else we just call our path code.
635 */
636 bool usePath = doStroke && width > 0 &&
637 (paint.getStrokeJoin() == SkPaint::kRound_Join ||
638 (paint.getStrokeJoin() == SkPaint::kBevel_Join && rect.isEmpty()));
639 // another two reasons we might need to call drawPath...
640 if (paint.getMaskFilter() || paint.getPathEffect()) {
641 usePath = true;
642 }
643 if (!usePath && paint.isAntiAlias() && !fContext->getMatrix().rectStaysRect()) {
644#if defined(SHADER_AA_FILL_RECT) || !defined(IGNORE_ROT_AA_RECT_OPT)
645 if (doStroke) {
646#endif
647 usePath = true;
648#if defined(SHADER_AA_FILL_RECT) || !defined(IGNORE_ROT_AA_RECT_OPT)
649 } else {
650 usePath = !fContext->getMatrix().preservesRightAngles();
651 }
652#endif
653 }
654 // until we can both stroke and fill rectangles
655 if (paint.getStyle() == SkPaint::kStrokeAndFill_Style) {
656 usePath = true;
657 }
658
659 if (usePath) {
660 SkPath path;
661 path.addRect(rect);
662 this->drawPath(draw, path, paint, NULL, true);
663 return;
664 }
665
666 GrPaint grPaint;
667 if (!skPaint2GrPaintShader(this, paint, true, &grPaint)) {
668 return;
669 }
670
671 if (!doStroke) {
672 fContext->drawRect(grPaint, rect);
673 } else {
674 SkStrokeRec stroke(paint);
675 fContext->drawRect(grPaint, rect, &stroke);
676 }
677}
678
679///////////////////////////////////////////////////////////////////////////////
680
681void SkGpuDevice::drawRRect(const SkDraw& draw, const SkRRect& rect,
682 const SkPaint& paint) {
683 CHECK_FOR_ANNOTATION(paint);
684 CHECK_SHOULD_DRAW(draw, false);
685
686 bool usePath = !rect.isSimple();
687 // another two reasons we might need to call drawPath...
688 if (paint.getMaskFilter() || paint.getPathEffect()) {
689 usePath = true;
690 }
691 // until we can rotate rrects...
692 if (!usePath && !fContext->getMatrix().rectStaysRect()) {
693 usePath = true;
694 }
695
696 if (usePath) {
697 SkPath path;
698 path.addRRect(rect);
699 this->drawPath(draw, path, paint, NULL, true);
700 return;
701 }
702
703 GrPaint grPaint;
704 if (!skPaint2GrPaintShader(this, paint, true, &grPaint)) {
705 return;
706 }
707
708 SkStrokeRec stroke(paint);
709 fContext->drawRRect(grPaint, rect, stroke);
710}
711
712///////////////////////////////////////////////////////////////////////////////
713
714void SkGpuDevice::drawOval(const SkDraw& draw, const SkRect& oval,
715 const SkPaint& paint) {
716 CHECK_FOR_ANNOTATION(paint);
717 CHECK_SHOULD_DRAW(draw, false);
718
719 bool usePath = false;
720 // some basic reasons we might need to call drawPath...
721 if (paint.getMaskFilter() || paint.getPathEffect()) {
722 usePath = true;
723 }
724
725 if (usePath) {
726 SkPath path;
727 path.addOval(oval);
728 this->drawPath(draw, path, paint, NULL, true);
729 return;
730 }
731
732 GrPaint grPaint;
733 if (!skPaint2GrPaintShader(this, paint, true, &grPaint)) {
734 return;
735 }
736 SkStrokeRec stroke(paint);
737
738 fContext->drawOval(grPaint, oval, stroke);
739}
740
741#include "SkMaskFilter.h"
742#include "SkBounder.h"
743
744///////////////////////////////////////////////////////////////////////////////
745
746// helpers for applying mask filters
747namespace {
748
749// Draw a mask using the supplied paint. Since the coverage/geometry
750// is already burnt into the mask this boils down to a rect draw.
751// Return true if the mask was successfully drawn.
752bool draw_mask(GrContext* context, const SkRect& maskRect,
753 GrPaint* grp, GrTexture* mask) {
754 GrContext::AutoMatrix am;
755 if (!am.setIdentity(context, grp)) {
756 return false;
757 }
758
759 SkMatrix matrix;
760 matrix.setTranslate(-maskRect.fLeft, -maskRect.fTop);
761 matrix.postIDiv(mask->width(), mask->height());
762
763 grp->addCoverageEffect(GrSimpleTextureEffect::Create(mask, matrix))->unref();
764 context->drawRect(*grp, maskRect);
765 return true;
766}
767
768bool draw_with_mask_filter(GrContext* context, const SkPath& devPath,
769 SkMaskFilter* filter, const SkRegion& clip, SkBounder* bounder,
770 GrPaint* grp, SkPaint::Style style) {
771 SkMask srcM, dstM;
772
773 if (!SkDraw::DrawToMask(devPath, &clip.getBounds(), filter, &context->getMatrix(), &srcM,
774 SkMask::kComputeBoundsAndRenderImage_CreateMode, style)) {
775 return false;
776 }
777 SkAutoMaskFreeImage autoSrc(srcM.fImage);
778
779 if (!filter->filterMask(&dstM, srcM, context->getMatrix(), NULL)) {
780 return false;
781 }
782 // this will free-up dstM when we're done (allocated in filterMask())
783 SkAutoMaskFreeImage autoDst(dstM.fImage);
784
785 if (clip.quickReject(dstM.fBounds)) {
786 return false;
787 }
788 if (bounder && !bounder->doIRect(dstM.fBounds)) {
789 return false;
790 }
791
792 // we now have a device-aligned 8bit mask in dstM, ready to be drawn using
793 // the current clip (and identity matrix) and GrPaint settings
794 GrTextureDesc desc;
795 desc.fWidth = dstM.fBounds.width();
796 desc.fHeight = dstM.fBounds.height();
797 desc.fConfig = kAlpha_8_GrPixelConfig;
798
799 GrAutoScratchTexture ast(context, desc);
800 GrTexture* texture = ast.texture();
801
802 if (NULL == texture) {
803 return false;
804 }
805 texture->writePixels(0, 0, desc.fWidth, desc.fHeight, desc.fConfig,
806 dstM.fImage, dstM.fRowBytes);
807
808 SkRect maskRect = SkRect::Make(dstM.fBounds);
809
810 return draw_mask(context, maskRect, grp, texture);
811}
812
813// Create a mask of 'devPath' and place the result in 'mask'. Return true on
814// success; false otherwise.
815bool create_mask_GPU(GrContext* context,
816 const SkRect& maskRect,
817 const SkPath& devPath,
818 const SkStrokeRec& stroke,
819 bool doAA,
820 GrAutoScratchTexture* mask) {
821 GrTextureDesc desc;
822 desc.fFlags = kRenderTarget_GrTextureFlagBit;
823 desc.fWidth = SkScalarCeilToInt(maskRect.width());
824 desc.fHeight = SkScalarCeilToInt(maskRect.height());
825 // We actually only need A8, but it often isn't supported as a
826 // render target so default to RGBA_8888
827 desc.fConfig = kRGBA_8888_GrPixelConfig;
828 if (context->isConfigRenderable(kAlpha_8_GrPixelConfig, false)) {
829 desc.fConfig = kAlpha_8_GrPixelConfig;
830 }
831
832 mask->set(context, desc);
833 if (NULL == mask->texture()) {
834 return false;
835 }
836
837 GrTexture* maskTexture = mask->texture();
838 SkRect clipRect = SkRect::MakeWH(maskRect.width(), maskRect.height());
839
840 GrContext::AutoRenderTarget art(context, maskTexture->asRenderTarget());
841 GrContext::AutoClip ac(context, clipRect);
842
843 context->clear(NULL, 0x0, true);
844
845 GrPaint tempPaint;
846 if (doAA) {
847 tempPaint.setAntiAlias(true);
848 // AA uses the "coverage" stages on GrDrawTarget. Coverage with a dst
849 // blend coeff of zero requires dual source blending support in order
850 // to properly blend partially covered pixels. This means the AA
851 // code path may not be taken. So we use a dst blend coeff of ISA. We
852 // could special case AA draws to a dst surface with known alpha=0 to
853 // use a zero dst coeff when dual source blending isn't available.
854 tempPaint.setBlendFunc(kOne_GrBlendCoeff, kISC_GrBlendCoeff);
855 }
856
857 GrContext::AutoMatrix am;
858
859 // Draw the mask into maskTexture with the path's top-left at the origin using tempPaint.
860 SkMatrix translate;
861 translate.setTranslate(-maskRect.fLeft, -maskRect.fTop);
862 am.set(context, translate);
863 context->drawPath(tempPaint, devPath, stroke);
864 return true;
865}
866
867SkBitmap wrap_texture(GrTexture* texture) {
reed@google.combf790232013-12-13 19:45:58 +0000868 SkImageInfo info;
869 texture->asImageInfo(&info);
870
skia.committer@gmail.com11a253b2013-11-12 07:02:05 +0000871 SkBitmap result;
reed@google.combf790232013-12-13 19:45:58 +0000872 result.setConfig(info);
873 result.setPixelRef(SkNEW_ARGS(SkGrPixelRef, (info, texture)))->unref();
skia.committer@gmail.com11a253b2013-11-12 07:02:05 +0000874 return result;
875}
876
877};
878
879void SkGpuDevice::drawPath(const SkDraw& draw, const SkPath& origSrcPath,
880 const SkPaint& paint, const SkMatrix* prePathMatrix,
881 bool pathIsMutable) {
882 CHECK_FOR_ANNOTATION(paint);
883 CHECK_SHOULD_DRAW(draw, false);
884
885 GrPaint grPaint;
886 if (!skPaint2GrPaintShader(this, paint, true, &grPaint)) {
887 return;
888 }
889
skia.committer@gmail.com11a253b2013-11-12 07:02:05 +0000890 // If we have a prematrix, apply it to the path, optimizing for the case
891 // where the original path can in fact be modified in place (even though
892 // its parameter type is const).
893 SkPath* pathPtr = const_cast<SkPath*>(&origSrcPath);
commit-bot@chromium.orgf0c41e22014-01-14 18:42:34 +0000894 SkTLazy<SkPath> tmpPath;
895 SkTLazy<SkPath> effectPath;
skia.committer@gmail.com11a253b2013-11-12 07:02:05 +0000896
897 if (prePathMatrix) {
898 SkPath* result = pathPtr;
899
900 if (!pathIsMutable) {
commit-bot@chromium.orgf0c41e22014-01-14 18:42:34 +0000901 result = tmpPath.init();
skia.committer@gmail.com11a253b2013-11-12 07:02:05 +0000902 pathIsMutable = true;
903 }
904 // should I push prePathMatrix on our MV stack temporarily, instead
905 // of applying it here? See SkDraw.cpp
906 pathPtr->transform(*prePathMatrix, result);
907 pathPtr = result;
908 }
909 // at this point we're done with prePathMatrix
910 SkDEBUGCODE(prePathMatrix = (const SkMatrix*)0x50FF8001;)
911
912 SkStrokeRec stroke(paint);
913 SkPathEffect* pathEffect = paint.getPathEffect();
914 const SkRect* cullRect = NULL; // TODO: what is our bounds?
commit-bot@chromium.orgf0c41e22014-01-14 18:42:34 +0000915 if (pathEffect && pathEffect->filterPath(effectPath.init(), *pathPtr, &stroke,
skia.committer@gmail.com11a253b2013-11-12 07:02:05 +0000916 cullRect)) {
commit-bot@chromium.orgf0c41e22014-01-14 18:42:34 +0000917 pathPtr = effectPath.get();
918 pathIsMutable = true;
skia.committer@gmail.com11a253b2013-11-12 07:02:05 +0000919 }
920
skia.committer@gmail.com11a253b2013-11-12 07:02:05 +0000921 if (paint.getMaskFilter()) {
922 if (!stroke.isHairlineStyle()) {
commit-bot@chromium.orgf0c41e22014-01-14 18:42:34 +0000923 SkPath* strokedPath = pathIsMutable ? pathPtr : tmpPath.init();
924 if (stroke.applyToPath(strokedPath, *pathPtr)) {
925 pathPtr = strokedPath;
skia.committer@gmail.com11a253b2013-11-12 07:02:05 +0000926 pathIsMutable = true;
927 stroke.setFillStyle();
928 }
929 }
930
931 // avoid possibly allocating a new path in transform if we can
commit-bot@chromium.orgf0c41e22014-01-14 18:42:34 +0000932 SkPath* devPathPtr = pathIsMutable ? pathPtr : tmpPath.init();
skia.committer@gmail.com11a253b2013-11-12 07:02:05 +0000933
934 // transform the path into device space
935 pathPtr->transform(fContext->getMatrix(), devPathPtr);
commit-bot@chromium.orgd1829152014-01-27 22:41:45 +0000936
skia.committer@gmail.com11a253b2013-11-12 07:02:05 +0000937 SkRect maskRect;
938 if (paint.getMaskFilter()->canFilterMaskGPU(devPathPtr->getBounds(),
939 draw.fClip->getBounds(),
940 fContext->getMatrix(),
941 &maskRect)) {
commit-bot@chromium.org439ff1b2014-01-13 16:39:39 +0000942 // The context's matrix may change while creating the mask, so save the CTM here to
943 // pass to filterMaskGPU.
944 const SkMatrix ctm = fContext->getMatrix();
945
skia.committer@gmail.com11a253b2013-11-12 07:02:05 +0000946 SkIRect finalIRect;
947 maskRect.roundOut(&finalIRect);
948 if (draw.fClip->quickReject(finalIRect)) {
949 // clipped out
950 return;
951 }
952 if (NULL != draw.fBounder && !draw.fBounder->doIRect(finalIRect)) {
953 // nothing to draw
954 return;
955 }
commit-bot@chromium.orgd1829152014-01-27 22:41:45 +0000956
957 if (paint.getMaskFilter()->directFilterMaskGPU(fContext, &grPaint,
958 SkStrokeRec(paint), *devPathPtr)) {
959 // the mask filter was able to draw itself directly, so there's nothing
960 // left to do.
961 return;
962 }
skia.committer@gmail.com11a253b2013-11-12 07:02:05 +0000963
964 GrAutoScratchTexture mask;
965
966 if (create_mask_GPU(fContext, maskRect, *devPathPtr, stroke,
967 grPaint.isAntiAlias(), &mask)) {
968 GrTexture* filtered;
969
commit-bot@chromium.org41bf9302014-01-08 22:25:53 +0000970 if (paint.getMaskFilter()->filterMaskGPU(mask.texture(),
commit-bot@chromium.org439ff1b2014-01-13 16:39:39 +0000971 ctm, maskRect, &filtered, true)) {
skia.committer@gmail.com11a253b2013-11-12 07:02:05 +0000972 // filterMaskGPU gives us ownership of a ref to the result
973 SkAutoTUnref<GrTexture> atu(filtered);
974
975 // If the scratch texture that we used as the filter src also holds the filter
976 // result then we must detach so that this texture isn't recycled for a later
977 // draw.
978 if (filtered == mask.texture()) {
979 mask.detach();
980 filtered->unref(); // detach transfers GrAutoScratchTexture's ref to us.
981 }
982
983 if (draw_mask(fContext, maskRect, &grPaint, filtered)) {
984 // This path is completely drawn
985 return;
986 }
987 }
988 }
989 }
990
991 // draw the mask on the CPU - this is a fallthrough path in case the
992 // GPU path fails
993 SkPaint::Style style = stroke.isHairlineStyle() ? SkPaint::kStroke_Style :
994 SkPaint::kFill_Style;
995 draw_with_mask_filter(fContext, *devPathPtr, paint.getMaskFilter(),
996 *draw.fClip, draw.fBounder, &grPaint, style);
997 return;
998 }
999
1000 fContext->drawPath(grPaint, *pathPtr, stroke);
1001}
1002
1003static const int kBmpSmallTileSize = 1 << 10;
1004
1005static inline int get_tile_count(const SkIRect& srcRect, int tileSize) {
1006 int tilesX = (srcRect.fRight / tileSize) - (srcRect.fLeft / tileSize) + 1;
1007 int tilesY = (srcRect.fBottom / tileSize) - (srcRect.fTop / tileSize) + 1;
1008 return tilesX * tilesY;
1009}
1010
1011static int determine_tile_size(const SkBitmap& bitmap, const SkIRect& src, int maxTileSize) {
1012 if (maxTileSize <= kBmpSmallTileSize) {
1013 return maxTileSize;
1014 }
1015
1016 size_t maxTileTotalTileSize = get_tile_count(src, maxTileSize);
1017 size_t smallTotalTileSize = get_tile_count(src, kBmpSmallTileSize);
1018
1019 maxTileTotalTileSize *= maxTileSize * maxTileSize;
1020 smallTotalTileSize *= kBmpSmallTileSize * kBmpSmallTileSize;
1021
1022 if (maxTileTotalTileSize > 2 * smallTotalTileSize) {
1023 return kBmpSmallTileSize;
1024 } else {
1025 return maxTileSize;
1026 }
1027}
1028
1029// Given a bitmap, an optional src rect, and a context with a clip and matrix determine what
1030// pixels from the bitmap are necessary.
1031static void determine_clipped_src_rect(const GrContext* context,
1032 const SkBitmap& bitmap,
1033 const SkRect* srcRectPtr,
1034 SkIRect* clippedSrcIRect) {
1035 const GrClipData* clip = context->getClip();
1036 clip->getConservativeBounds(context->getRenderTarget(), clippedSrcIRect, NULL);
1037 SkMatrix inv;
1038 if (!context->getMatrix().invert(&inv)) {
1039 clippedSrcIRect->setEmpty();
1040 return;
1041 }
1042 SkRect clippedSrcRect = SkRect::Make(*clippedSrcIRect);
1043 inv.mapRect(&clippedSrcRect);
1044 if (NULL != srcRectPtr) {
commit-bot@chromium.orga7d89c82014-01-13 14:47:00 +00001045 // we've setup src space 0,0 to map to the top left of the src rect.
1046 clippedSrcRect.offset(srcRectPtr->fLeft, srcRectPtr->fTop);
skia.committer@gmail.com11a253b2013-11-12 07:02:05 +00001047 if (!clippedSrcRect.intersect(*srcRectPtr)) {
1048 clippedSrcIRect->setEmpty();
1049 return;
1050 }
1051 }
1052 clippedSrcRect.roundOut(clippedSrcIRect);
1053 SkIRect bmpBounds = SkIRect::MakeWH(bitmap.width(), bitmap.height());
1054 if (!clippedSrcIRect->intersect(bmpBounds)) {
1055 clippedSrcIRect->setEmpty();
1056 }
1057}
1058
1059bool SkGpuDevice::shouldTileBitmap(const SkBitmap& bitmap,
1060 const GrTextureParams& params,
1061 const SkRect* srcRectPtr,
1062 int maxTileSize,
1063 int* tileSize,
1064 SkIRect* clippedSrcRect) const {
1065 // if bitmap is explictly texture backed then just use the texture
1066 if (NULL != bitmap.getTexture()) {
1067 return false;
1068 }
1069
1070 // if it's larger than the max tile size, then we have no choice but tiling.
1071 if (bitmap.width() > maxTileSize || bitmap.height() > maxTileSize) {
1072 determine_clipped_src_rect(fContext, bitmap, srcRectPtr, clippedSrcRect);
1073 *tileSize = determine_tile_size(bitmap, *clippedSrcRect, maxTileSize);
1074 return true;
1075 }
1076
1077 if (bitmap.width() * bitmap.height() < 4 * kBmpSmallTileSize * kBmpSmallTileSize) {
1078 return false;
1079 }
1080
1081 // if the entire texture is already in our cache then no reason to tile it
1082 if (GrIsBitmapInCache(fContext, bitmap, &params)) {
1083 return false;
1084 }
1085
1086 // At this point we know we could do the draw by uploading the entire bitmap
1087 // as a texture. However, if the texture would be large compared to the
1088 // cache size and we don't require most of it for this draw then tile to
1089 // reduce the amount of upload and cache spill.
1090
1091 // assumption here is that sw bitmap size is a good proxy for its size as
1092 // a texture
1093 size_t bmpSize = bitmap.getSize();
1094 size_t cacheSize;
1095 fContext->getTextureCacheLimits(NULL, &cacheSize);
1096 if (bmpSize < cacheSize / 2) {
1097 return false;
1098 }
1099
1100 // Figure out how much of the src we will need based on the src rect and clipping.
1101 determine_clipped_src_rect(fContext, bitmap, srcRectPtr, clippedSrcRect);
1102 *tileSize = kBmpSmallTileSize; // already know whole bitmap fits in one max sized tile.
1103 size_t usedTileBytes = get_tile_count(*clippedSrcRect, kBmpSmallTileSize) *
1104 kBmpSmallTileSize * kBmpSmallTileSize;
1105
1106 return usedTileBytes < 2 * bmpSize;
1107}
1108
commit-bot@chromium.orga7d89c82014-01-13 14:47:00 +00001109void SkGpuDevice::drawBitmap(const SkDraw& origDraw,
skia.committer@gmail.com11a253b2013-11-12 07:02:05 +00001110 const SkBitmap& bitmap,
1111 const SkMatrix& m,
1112 const SkPaint& paint) {
commit-bot@chromium.orga7d89c82014-01-13 14:47:00 +00001113 SkMatrix concat;
1114 SkTCopyOnFirstWrite<SkDraw> draw(origDraw);
1115 if (!m.isIdentity()) {
1116 concat.setConcat(*draw->fMatrix, m);
1117 draw.writable()->fMatrix = &concat;
1118 }
1119 this->drawBitmapCommon(*draw, bitmap, NULL, NULL, paint, SkCanvas::kNone_DrawBitmapRectFlag);
skia.committer@gmail.com11a253b2013-11-12 07:02:05 +00001120}
1121
commit-bot@chromium.orgdec61502013-12-02 22:22:35 +00001122// This method outsets 'iRect' by 'outset' all around and then clamps its extents to
skia.committer@gmail.com11a253b2013-11-12 07:02:05 +00001123// 'clamp'. 'offset' is adjusted to remain positioned over the top-left corner
1124// of 'iRect' for all possible outsets/clamps.
commit-bot@chromium.orgdec61502013-12-02 22:22:35 +00001125static inline void clamped_outset_with_offset(SkIRect* iRect,
1126 int outset,
1127 SkPoint* offset,
1128 const SkIRect& clamp) {
1129 iRect->outset(outset, outset);
skia.committer@gmail.com11a253b2013-11-12 07:02:05 +00001130
commit-bot@chromium.orgdec61502013-12-02 22:22:35 +00001131 int leftClampDelta = clamp.fLeft - iRect->fLeft;
1132 if (leftClampDelta > 0) {
1133 offset->fX -= outset - leftClampDelta;
skia.committer@gmail.com11a253b2013-11-12 07:02:05 +00001134 iRect->fLeft = clamp.fLeft;
1135 } else {
commit-bot@chromium.orgdec61502013-12-02 22:22:35 +00001136 offset->fX -= outset;
skia.committer@gmail.com11a253b2013-11-12 07:02:05 +00001137 }
commit-bot@chromium.orgdec61502013-12-02 22:22:35 +00001138
1139 int topClampDelta = clamp.fTop - iRect->fTop;
1140 if (topClampDelta > 0) {
1141 offset->fY -= outset - topClampDelta;
skia.committer@gmail.com11a253b2013-11-12 07:02:05 +00001142 iRect->fTop = clamp.fTop;
1143 } else {
commit-bot@chromium.orgdec61502013-12-02 22:22:35 +00001144 offset->fY -= outset;
skia.committer@gmail.com11a253b2013-11-12 07:02:05 +00001145 }
1146
1147 if (iRect->fRight > clamp.fRight) {
1148 iRect->fRight = clamp.fRight;
1149 }
1150 if (iRect->fBottom > clamp.fBottom) {
1151 iRect->fBottom = clamp.fBottom;
1152 }
1153}
1154
1155void SkGpuDevice::drawBitmapCommon(const SkDraw& draw,
1156 const SkBitmap& bitmap,
1157 const SkRect* srcRectPtr,
commit-bot@chromium.orga7d89c82014-01-13 14:47:00 +00001158 const SkSize* dstSizePtr,
skia.committer@gmail.com11a253b2013-11-12 07:02:05 +00001159 const SkPaint& paint,
1160 SkCanvas::DrawBitmapRectFlags flags) {
1161 CHECK_SHOULD_DRAW(draw, false);
1162
1163 SkRect srcRect;
commit-bot@chromium.orga7d89c82014-01-13 14:47:00 +00001164 SkSize dstSize;
commit-bot@chromium.orgdec61502013-12-02 22:22:35 +00001165 // If there is no src rect, or the src rect contains the entire bitmap then we're effectively
1166 // in the (easier) bleed case, so update flags.
skia.committer@gmail.com11a253b2013-11-12 07:02:05 +00001167 if (NULL == srcRectPtr) {
commit-bot@chromium.orga7d89c82014-01-13 14:47:00 +00001168 SkScalar w = SkIntToScalar(bitmap.width());
1169 SkScalar h = SkIntToScalar(bitmap.height());
1170 dstSize.fWidth = w;
1171 dstSize.fHeight = h;
1172 srcRect.set(0, 0, w, h);
commit-bot@chromium.orgdec61502013-12-02 22:22:35 +00001173 flags = (SkCanvas::DrawBitmapRectFlags) (flags | SkCanvas::kBleed_DrawBitmapRectFlag);
skia.committer@gmail.com11a253b2013-11-12 07:02:05 +00001174 } else {
commit-bot@chromium.orga7d89c82014-01-13 14:47:00 +00001175 SkASSERT(NULL != dstSizePtr);
skia.committer@gmail.com11a253b2013-11-12 07:02:05 +00001176 srcRect = *srcRectPtr;
commit-bot@chromium.orga7d89c82014-01-13 14:47:00 +00001177 dstSize = *dstSizePtr;
commit-bot@chromium.orgdec61502013-12-02 22:22:35 +00001178 if (srcRect.fLeft <= 0 && srcRect.fTop <= 0 &&
1179 srcRect.fRight >= bitmap.width() && srcRect.fBottom >= bitmap.height()) {
1180 flags = (SkCanvas::DrawBitmapRectFlags) (flags | SkCanvas::kBleed_DrawBitmapRectFlag);
1181 }
skia.committer@gmail.com11a253b2013-11-12 07:02:05 +00001182 }
1183
1184 if (paint.getMaskFilter()){
1185 // Convert the bitmap to a shader so that the rect can be drawn
1186 // through drawRect, which supports mask filters.
skia.committer@gmail.com11a253b2013-11-12 07:02:05 +00001187 SkBitmap tmp; // subset of bitmap, if necessary
1188 const SkBitmap* bitmapPtr = &bitmap;
commit-bot@chromium.orga7d89c82014-01-13 14:47:00 +00001189 SkMatrix localM;
skia.committer@gmail.com11a253b2013-11-12 07:02:05 +00001190 if (NULL != srcRectPtr) {
commit-bot@chromium.orga7d89c82014-01-13 14:47:00 +00001191 localM.setTranslate(-srcRectPtr->fLeft, -srcRectPtr->fTop);
1192 localM.postScale(dstSize.fWidth / srcRectPtr->width(),
1193 dstSize.fHeight / srcRectPtr->height());
commit-bot@chromium.orgd6ca4ac2013-11-22 20:34:59 +00001194 // In bleed mode we position and trim the bitmap based on the src rect which is
1195 // already accounted for in 'm' and 'srcRect'. In clamp mode we need to chop out
1196 // the desired portion of the bitmap and then update 'm' and 'srcRect' to
1197 // compensate.
1198 if (!(SkCanvas::kBleed_DrawBitmapRectFlag & flags)) {
1199 SkIRect iSrc;
1200 srcRect.roundOut(&iSrc);
skia.committer@gmail.com11a253b2013-11-12 07:02:05 +00001201
commit-bot@chromium.orgd6ca4ac2013-11-22 20:34:59 +00001202 SkPoint offset = SkPoint::Make(SkIntToScalar(iSrc.fLeft),
1203 SkIntToScalar(iSrc.fTop));
skia.committer@gmail.com11a253b2013-11-12 07:02:05 +00001204
commit-bot@chromium.orgd6ca4ac2013-11-22 20:34:59 +00001205 if (!bitmap.extractSubset(&tmp, iSrc)) {
1206 return; // extraction failed
1207 }
1208 bitmapPtr = &tmp;
1209 srcRect.offset(-offset.fX, -offset.fY);
commit-bot@chromium.orga7d89c82014-01-13 14:47:00 +00001210
commit-bot@chromium.orgd6ca4ac2013-11-22 20:34:59 +00001211 // The source rect has changed so update the matrix
commit-bot@chromium.orga7d89c82014-01-13 14:47:00 +00001212 localM.preTranslate(offset.fX, offset.fY);
skia.committer@gmail.com11a253b2013-11-12 07:02:05 +00001213 }
commit-bot@chromium.orga7d89c82014-01-13 14:47:00 +00001214 } else {
1215 localM.reset();
skia.committer@gmail.com11a253b2013-11-12 07:02:05 +00001216 }
1217
commit-bot@chromium.orga7d89c82014-01-13 14:47:00 +00001218 SkPaint paintWithShader(paint);
1219 paintWithShader.setShader(SkShader::CreateBitmapShader(*bitmapPtr,
skia.committer@gmail.com11a253b2013-11-12 07:02:05 +00001220 SkShader::kClamp_TileMode, SkShader::kClamp_TileMode))->unref();
commit-bot@chromium.orga7d89c82014-01-13 14:47:00 +00001221 paintWithShader.getShader()->setLocalMatrix(localM);
1222 SkRect dstRect = {0, 0, dstSize.fWidth, dstSize.fHeight};
1223 this->drawRect(draw, dstRect, paintWithShader);
skia.committer@gmail.com11a253b2013-11-12 07:02:05 +00001224
1225 return;
1226 }
1227
commit-bot@chromium.orga7d89c82014-01-13 14:47:00 +00001228 // If there is no mask filter than it is OK to handle the src rect -> dst rect scaling using
1229 // the view matrix rather than a local matrix.
1230 SkMatrix m;
1231 m.setScale(dstSize.fWidth / srcRect.width(),
1232 dstSize.fHeight / srcRect.height());
skia.committer@gmail.com11a253b2013-11-12 07:02:05 +00001233 fContext->concatMatrix(m);
1234
1235 GrTextureParams params;
1236 SkPaint::FilterLevel paintFilterLevel = paint.getFilterLevel();
1237 GrTextureParams::FilterMode textureFilterMode;
commit-bot@chromium.orgdec61502013-12-02 22:22:35 +00001238
1239 int tileFilterPad;
1240 bool doBicubic = false;
1241
skia.committer@gmail.com11a253b2013-11-12 07:02:05 +00001242 switch(paintFilterLevel) {
1243 case SkPaint::kNone_FilterLevel:
commit-bot@chromium.orgdec61502013-12-02 22:22:35 +00001244 tileFilterPad = 0;
skia.committer@gmail.com11a253b2013-11-12 07:02:05 +00001245 textureFilterMode = GrTextureParams::kNone_FilterMode;
1246 break;
1247 case SkPaint::kLow_FilterLevel:
commit-bot@chromium.orgdec61502013-12-02 22:22:35 +00001248 tileFilterPad = 1;
skia.committer@gmail.com11a253b2013-11-12 07:02:05 +00001249 textureFilterMode = GrTextureParams::kBilerp_FilterMode;
1250 break;
1251 case SkPaint::kMedium_FilterLevel:
commit-bot@chromium.orgdec61502013-12-02 22:22:35 +00001252 tileFilterPad = 1;
commit-bot@chromium.org79b7eee2013-12-16 21:02:29 +00001253 if (fContext->getMatrix().getMinStretch() < SK_Scalar1) {
1254 textureFilterMode = GrTextureParams::kMipMap_FilterMode;
1255 } else {
1256 // Don't trigger MIP level generation unnecessarily.
1257 textureFilterMode = GrTextureParams::kBilerp_FilterMode;
1258 }
skia.committer@gmail.com11a253b2013-11-12 07:02:05 +00001259 break;
commit-bot@chromium.org79b7eee2013-12-16 21:02:29 +00001260 case SkPaint::kHigh_FilterLevel:
commit-bot@chromium.orgcea9abb2013-12-09 19:15:37 +00001261 // Minification can look bad with the bicubic effect.
commit-bot@chromium.org7d7f3142013-12-16 15:18:11 +00001262 if (fContext->getMatrix().getMinStretch() >= SK_Scalar1) {
commit-bot@chromium.orgdec61502013-12-02 22:22:35 +00001263 // We will install an effect that does the filtering in the shader.
1264 textureFilterMode = GrTextureParams::kNone_FilterMode;
1265 tileFilterPad = GrBicubicEffect::kFilterTexelPad;
1266 doBicubic = true;
1267 } else {
commit-bot@chromium.orgdec61502013-12-02 22:22:35 +00001268 textureFilterMode = GrTextureParams::kMipMap_FilterMode;
1269 tileFilterPad = 1;
1270 }
skia.committer@gmail.com11a253b2013-11-12 07:02:05 +00001271 break;
1272 default:
1273 SkErrorInternals::SetError( kInvalidPaint_SkError,
1274 "Sorry, I don't understand the filtering "
1275 "mode you asked for. Falling back to "
1276 "MIPMaps.");
commit-bot@chromium.orgdec61502013-12-02 22:22:35 +00001277 tileFilterPad = 1;
skia.committer@gmail.com11a253b2013-11-12 07:02:05 +00001278 textureFilterMode = GrTextureParams::kMipMap_FilterMode;
1279 break;
skia.committer@gmail.com11a253b2013-11-12 07:02:05 +00001280 }
1281
1282 params.setFilterMode(textureFilterMode);
1283
commit-bot@chromium.orgdec61502013-12-02 22:22:35 +00001284 int maxTileSize = fContext->getMaxTextureSize() - 2 * tileFilterPad;
skia.committer@gmail.com11a253b2013-11-12 07:02:05 +00001285 int tileSize;
1286
1287 SkIRect clippedSrcRect;
1288 if (this->shouldTileBitmap(bitmap, params, srcRectPtr, maxTileSize, &tileSize,
1289 &clippedSrcRect)) {
commit-bot@chromium.orgdec61502013-12-02 22:22:35 +00001290 this->drawTiledBitmap(bitmap, srcRect, clippedSrcRect, params, paint, flags, tileSize,
1291 doBicubic);
skia.committer@gmail.com11a253b2013-11-12 07:02:05 +00001292 } else {
1293 // take the simple case
commit-bot@chromium.orgdec61502013-12-02 22:22:35 +00001294 this->internalDrawBitmap(bitmap, srcRect, params, paint, flags, doBicubic);
skia.committer@gmail.com11a253b2013-11-12 07:02:05 +00001295 }
1296}
1297
1298// Break 'bitmap' into several tiles to draw it since it has already
1299// been determined to be too large to fit in VRAM
1300void SkGpuDevice::drawTiledBitmap(const SkBitmap& bitmap,
1301 const SkRect& srcRect,
1302 const SkIRect& clippedSrcIRect,
1303 const GrTextureParams& params,
1304 const SkPaint& paint,
1305 SkCanvas::DrawBitmapRectFlags flags,
commit-bot@chromium.orgdec61502013-12-02 22:22:35 +00001306 int tileSize,
1307 bool bicubic) {
skia.committer@gmail.com11a253b2013-11-12 07:02:05 +00001308 SkRect clippedSrcRect = SkRect::Make(clippedSrcIRect);
1309
1310 int nx = bitmap.width() / tileSize;
1311 int ny = bitmap.height() / tileSize;
1312 for (int x = 0; x <= nx; x++) {
1313 for (int y = 0; y <= ny; y++) {
1314 SkRect tileR;
1315 tileR.set(SkIntToScalar(x * tileSize),
1316 SkIntToScalar(y * tileSize),
1317 SkIntToScalar((x + 1) * tileSize),
1318 SkIntToScalar((y + 1) * tileSize));
1319
1320 if (!SkRect::Intersects(tileR, clippedSrcRect)) {
1321 continue;
1322 }
1323
1324 if (!tileR.intersect(srcRect)) {
1325 continue;
1326 }
1327
1328 SkBitmap tmpB;
1329 SkIRect iTileR;
1330 tileR.roundOut(&iTileR);
1331 SkPoint offset = SkPoint::Make(SkIntToScalar(iTileR.fLeft),
1332 SkIntToScalar(iTileR.fTop));
1333
commit-bot@chromium.orga7d89c82014-01-13 14:47:00 +00001334 // Adjust the context matrix to draw at the right x,y in device space
1335 SkMatrix tmpM;
1336 GrContext::AutoMatrix am;
1337 tmpM.setTranslate(offset.fX - srcRect.fLeft, offset.fY - srcRect.fTop);
1338 am.setPreConcat(fContext, tmpM);
1339
commit-bot@chromium.orgdec61502013-12-02 22:22:35 +00001340 if (SkPaint::kNone_FilterLevel != paint.getFilterLevel() || bicubic) {
skia.committer@gmail.com11a253b2013-11-12 07:02:05 +00001341 SkIRect iClampRect;
1342
1343 if (SkCanvas::kBleed_DrawBitmapRectFlag & flags) {
1344 // In bleed mode we want to always expand the tile on all edges
1345 // but stay within the bitmap bounds
1346 iClampRect = SkIRect::MakeWH(bitmap.width(), bitmap.height());
1347 } else {
1348 // In texture-domain/clamp mode we only want to expand the
1349 // tile on edges interior to "srcRect" (i.e., we want to
1350 // not bleed across the original clamped edges)
1351 srcRect.roundOut(&iClampRect);
1352 }
commit-bot@chromium.orgdec61502013-12-02 22:22:35 +00001353 int outset = bicubic ? GrBicubicEffect::kFilterTexelPad : 1;
1354 clamped_outset_with_offset(&iTileR, outset, &offset, iClampRect);
skia.committer@gmail.com11a253b2013-11-12 07:02:05 +00001355 }
1356
1357 if (bitmap.extractSubset(&tmpB, iTileR)) {
1358 // now offset it to make it "local" to our tmp bitmap
1359 tileR.offset(-offset.fX, -offset.fY);
commit-bot@chromium.orga7d89c82014-01-13 14:47:00 +00001360
commit-bot@chromium.orgdec61502013-12-02 22:22:35 +00001361 this->internalDrawBitmap(tmpB, tileR, params, paint, flags, bicubic);
skia.committer@gmail.com11a253b2013-11-12 07:02:05 +00001362 }
1363 }
1364 }
1365}
1366
1367static bool has_aligned_samples(const SkRect& srcRect,
1368 const SkRect& transformedRect) {
1369 // detect pixel disalignment
1370 if (SkScalarAbs(SkScalarRoundToScalar(transformedRect.left()) -
1371 transformedRect.left()) < COLOR_BLEED_TOLERANCE &&
1372 SkScalarAbs(SkScalarRoundToScalar(transformedRect.top()) -
1373 transformedRect.top()) < COLOR_BLEED_TOLERANCE &&
1374 SkScalarAbs(transformedRect.width() - srcRect.width()) <
1375 COLOR_BLEED_TOLERANCE &&
1376 SkScalarAbs(transformedRect.height() - srcRect.height()) <
1377 COLOR_BLEED_TOLERANCE) {
1378 return true;
1379 }
1380 return false;
1381}
1382
1383static bool may_color_bleed(const SkRect& srcRect,
1384 const SkRect& transformedRect,
1385 const SkMatrix& m) {
1386 // Only gets called if has_aligned_samples returned false.
1387 // So we can assume that sampling is axis aligned but not texel aligned.
1388 SkASSERT(!has_aligned_samples(srcRect, transformedRect));
1389 SkRect innerSrcRect(srcRect), innerTransformedRect,
1390 outerTransformedRect(transformedRect);
1391 innerSrcRect.inset(SK_ScalarHalf, SK_ScalarHalf);
1392 m.mapRect(&innerTransformedRect, innerSrcRect);
1393
1394 // The gap between outerTransformedRect and innerTransformedRect
1395 // represents the projection of the source border area, which is
1396 // problematic for color bleeding. We must check whether any
1397 // destination pixels sample the border area.
1398 outerTransformedRect.inset(COLOR_BLEED_TOLERANCE, COLOR_BLEED_TOLERANCE);
1399 innerTransformedRect.outset(COLOR_BLEED_TOLERANCE, COLOR_BLEED_TOLERANCE);
1400 SkIRect outer, inner;
1401 outerTransformedRect.round(&outer);
1402 innerTransformedRect.round(&inner);
1403 // If the inner and outer rects round to the same result, it means the
1404 // border does not overlap any pixel centers. Yay!
1405 return inner != outer;
1406}
1407
1408
1409/*
1410 * This is called by drawBitmap(), which has to handle images that may be too
1411 * large to be represented by a single texture.
1412 *
1413 * internalDrawBitmap assumes that the specified bitmap will fit in a texture
1414 * and that non-texture portion of the GrPaint has already been setup.
1415 */
1416void SkGpuDevice::internalDrawBitmap(const SkBitmap& bitmap,
1417 const SkRect& srcRect,
1418 const GrTextureParams& params,
1419 const SkPaint& paint,
commit-bot@chromium.orgdec61502013-12-02 22:22:35 +00001420 SkCanvas::DrawBitmapRectFlags flags,
1421 bool bicubic) {
skia.committer@gmail.com11a253b2013-11-12 07:02:05 +00001422 SkASSERT(bitmap.width() <= fContext->getMaxTextureSize() &&
1423 bitmap.height() <= fContext->getMaxTextureSize());
1424
1425 GrTexture* texture;
1426 SkAutoCachedTexture act(this, bitmap, &params, &texture);
1427 if (NULL == texture) {
1428 return;
1429 }
1430
commit-bot@chromium.orga7d89c82014-01-13 14:47:00 +00001431 SkRect dstRect = {0, 0, srcRect.width(), srcRect.height() };
skia.committer@gmail.com11a253b2013-11-12 07:02:05 +00001432 SkRect paintRect;
1433 SkScalar wInv = SkScalarInvert(SkIntToScalar(texture->width()));
1434 SkScalar hInv = SkScalarInvert(SkIntToScalar(texture->height()));
1435 paintRect.setLTRB(SkScalarMul(srcRect.fLeft, wInv),
1436 SkScalarMul(srcRect.fTop, hInv),
1437 SkScalarMul(srcRect.fRight, wInv),
1438 SkScalarMul(srcRect.fBottom, hInv));
1439
1440 bool needsTextureDomain = false;
1441 if (!(flags & SkCanvas::kBleed_DrawBitmapRectFlag) &&
commit-bot@chromium.org7d7f3142013-12-16 15:18:11 +00001442 (bicubic || params.filterMode() != GrTextureParams::kNone_FilterMode)) {
1443 // Need texture domain if drawing a sub rect
skia.committer@gmail.com11a253b2013-11-12 07:02:05 +00001444 needsTextureDomain = srcRect.width() < bitmap.width() ||
1445 srcRect.height() < bitmap.height();
commit-bot@chromium.org7d7f3142013-12-16 15:18:11 +00001446 if (!bicubic && needsTextureDomain && fContext->getMatrix().rectStaysRect()) {
skia.committer@gmail.com11a253b2013-11-12 07:02:05 +00001447 const SkMatrix& matrix = fContext->getMatrix();
1448 // sampling is axis-aligned
1449 SkRect transformedRect;
1450 matrix.mapRect(&transformedRect, srcRect);
1451
1452 if (has_aligned_samples(srcRect, transformedRect)) {
1453 // We could also turn off filtering here (but we already did a cache lookup with
1454 // params).
1455 needsTextureDomain = false;
1456 } else {
1457 needsTextureDomain = may_color_bleed(srcRect, transformedRect, matrix);
1458 }
1459 }
1460 }
1461
1462 SkRect textureDomain = SkRect::MakeEmpty();
1463 SkAutoTUnref<GrEffectRef> effect;
1464 if (needsTextureDomain) {
1465 // Use a constrained texture domain to avoid color bleeding
1466 SkScalar left, top, right, bottom;
1467 if (srcRect.width() > SK_Scalar1) {
1468 SkScalar border = SK_ScalarHalf / texture->width();
1469 left = paintRect.left() + border;
1470 right = paintRect.right() - border;
1471 } else {
1472 left = right = SkScalarHalf(paintRect.left() + paintRect.right());
1473 }
1474 if (srcRect.height() > SK_Scalar1) {
1475 SkScalar border = SK_ScalarHalf / texture->height();
1476 top = paintRect.top() + border;
1477 bottom = paintRect.bottom() - border;
1478 } else {
1479 top = bottom = SkScalarHalf(paintRect.top() + paintRect.bottom());
1480 }
1481 textureDomain.setLTRB(left, top, right, bottom);
commit-bot@chromium.org7d7f3142013-12-16 15:18:11 +00001482 if (bicubic) {
1483 effect.reset(GrBicubicEffect::Create(texture, SkMatrix::I(), textureDomain));
1484 } else {
1485 effect.reset(GrTextureDomainEffect::Create(texture,
1486 SkMatrix::I(),
1487 textureDomain,
1488 GrTextureDomain::kClamp_Mode,
1489 params.filterMode()));
1490 }
commit-bot@chromium.orgdec61502013-12-02 22:22:35 +00001491 } else if (bicubic) {
commit-bot@chromium.orgbc91fd72013-12-10 12:53:39 +00001492 SkASSERT(GrTextureParams::kNone_FilterMode == params.filterMode());
1493 SkShader::TileMode tileModes[2] = { params.getTileModeX(), params.getTileModeY() };
1494 effect.reset(GrBicubicEffect::Create(texture, SkMatrix::I(), tileModes));
skia.committer@gmail.com11a253b2013-11-12 07:02:05 +00001495 } else {
1496 effect.reset(GrSimpleTextureEffect::Create(texture, SkMatrix::I(), params));
1497 }
1498
1499 // Construct a GrPaint by setting the bitmap texture as the first effect and then configuring
1500 // the rest from the SkPaint.
1501 GrPaint grPaint;
1502 grPaint.addColorEffect(effect);
1503 bool alphaOnly = !(SkBitmap::kA8_Config == bitmap.config());
1504 if (!skPaint2GrPaintNoShader(this, paint, alphaOnly, false, &grPaint)) {
1505 return;
1506 }
1507
1508 fContext->drawRectToRect(grPaint, dstRect, paintRect, NULL);
1509}
1510
1511static bool filter_texture(SkBaseDevice* device, GrContext* context,
1512 GrTexture* texture, SkImageFilter* filter,
1513 int w, int h, const SkMatrix& ctm, SkBitmap* result,
1514 SkIPoint* offset) {
1515 SkASSERT(filter);
1516 SkDeviceImageFilterProxy proxy(device);
1517
1518 if (filter->canFilterImageGPU()) {
1519 // Save the render target and set it to NULL, so we don't accidentally draw to it in the
1520 // filter. Also set the clip wide open and the matrix to identity.
1521 GrContext::AutoWideOpenIdentityDraw awo(context, NULL);
1522 return filter->filterImageGPU(&proxy, wrap_texture(texture), ctm, result, offset);
1523 } else {
1524 return false;
1525 }
1526}
1527
1528void SkGpuDevice::drawSprite(const SkDraw& draw, const SkBitmap& bitmap,
1529 int left, int top, const SkPaint& paint) {
1530 // drawSprite is defined to be in device coords.
1531 CHECK_SHOULD_DRAW(draw, true);
1532
1533 SkAutoLockPixels alp(bitmap, !bitmap.getTexture());
1534 if (!bitmap.getTexture() && !bitmap.readyToDraw()) {
1535 return;
1536 }
1537
1538 int w = bitmap.width();
1539 int h = bitmap.height();
1540
1541 GrTexture* texture;
1542 // draw sprite uses the default texture params
1543 SkAutoCachedTexture act(this, bitmap, NULL, &texture);
1544
1545 SkImageFilter* filter = paint.getImageFilter();
skia.committer@gmail.com11a253b2013-11-12 07:02:05 +00001546 // This bitmap will own the filtered result as a texture.
1547 SkBitmap filteredBitmap;
1548
1549 if (NULL != filter) {
senorblanco@chromium.org6776b822014-01-03 21:48:22 +00001550 SkIPoint offset = SkIPoint::Make(0, 0);
skia.committer@gmail.com11a253b2013-11-12 07:02:05 +00001551 SkMatrix matrix(*draw.fMatrix);
1552 matrix.postTranslate(SkIntToScalar(-left), SkIntToScalar(-top));
1553 if (filter_texture(this, fContext, texture, filter, w, h, matrix, &filteredBitmap,
1554 &offset)) {
1555 texture = (GrTexture*) filteredBitmap.getTexture();
1556 w = filteredBitmap.width();
1557 h = filteredBitmap.height();
senorblanco@chromium.org6776b822014-01-03 21:48:22 +00001558 left += offset.x();
1559 top += offset.y();
skia.committer@gmail.com11a253b2013-11-12 07:02:05 +00001560 } else {
1561 return;
1562 }
1563 }
1564
1565 GrPaint grPaint;
1566 grPaint.addColorTextureEffect(texture, SkMatrix::I());
1567
1568 if(!skPaint2GrPaintNoShader(this, paint, true, false, &grPaint)) {
1569 return;
1570 }
1571
1572 fContext->drawRectToRect(grPaint,
senorblanco@chromium.org6776b822014-01-03 21:48:22 +00001573 SkRect::MakeXYWH(SkIntToScalar(left),
1574 SkIntToScalar(top),
skia.committer@gmail.com11a253b2013-11-12 07:02:05 +00001575 SkIntToScalar(w),
1576 SkIntToScalar(h)),
1577 SkRect::MakeXYWH(0,
1578 0,
1579 SK_Scalar1 * w / texture->width(),
1580 SK_Scalar1 * h / texture->height()));
1581}
1582
commit-bot@chromium.orga7d89c82014-01-13 14:47:00 +00001583void SkGpuDevice::drawBitmapRect(const SkDraw& origDraw, const SkBitmap& bitmap,
skia.committer@gmail.com11a253b2013-11-12 07:02:05 +00001584 const SkRect* src, const SkRect& dst,
1585 const SkPaint& paint,
1586 SkCanvas::DrawBitmapRectFlags flags) {
1587 SkMatrix matrix;
1588 SkRect bitmapBounds, tmpSrc;
1589
1590 bitmapBounds.set(0, 0,
1591 SkIntToScalar(bitmap.width()),
1592 SkIntToScalar(bitmap.height()));
1593
1594 // Compute matrix from the two rectangles
1595 if (NULL != src) {
1596 tmpSrc = *src;
1597 } else {
1598 tmpSrc = bitmapBounds;
1599 }
commit-bot@chromium.orga7d89c82014-01-13 14:47:00 +00001600
skia.committer@gmail.com11a253b2013-11-12 07:02:05 +00001601 matrix.setRectToRect(tmpSrc, dst, SkMatrix::kFill_ScaleToFit);
1602
1603 // clip the tmpSrc to the bounds of the bitmap. No check needed if src==null.
1604 if (NULL != src) {
1605 if (!bitmapBounds.contains(tmpSrc)) {
1606 if (!tmpSrc.intersect(bitmapBounds)) {
1607 return; // nothing to draw
1608 }
1609 }
1610 }
1611
commit-bot@chromium.orga7d89c82014-01-13 14:47:00 +00001612 SkRect tmpDst;
1613 matrix.mapRect(&tmpDst, tmpSrc);
1614
1615 SkTCopyOnFirstWrite<SkDraw> draw(origDraw);
1616 if (0 != tmpDst.fLeft || 0 != tmpDst.fTop) {
1617 // Translate so that tempDst's top left is at the origin.
1618 matrix = *origDraw.fMatrix;
1619 matrix.preTranslate(tmpDst.fLeft, tmpDst.fTop);
1620 draw.writable()->fMatrix = &matrix;
1621 }
1622 SkSize dstSize;
1623 dstSize.fWidth = tmpDst.width();
1624 dstSize.fHeight = tmpDst.height();
1625
1626 this->drawBitmapCommon(*draw, bitmap, &tmpSrc, &dstSize, paint, flags);
skia.committer@gmail.com11a253b2013-11-12 07:02:05 +00001627}
1628
1629void SkGpuDevice::drawDevice(const SkDraw& draw, SkBaseDevice* device,
1630 int x, int y, const SkPaint& paint) {
1631 // clear of the source device must occur before CHECK_SHOULD_DRAW
1632 SkGpuDevice* dev = static_cast<SkGpuDevice*>(device);
1633 if (dev->fNeedClear) {
1634 // TODO: could check here whether we really need to draw at all
1635 dev->clear(0x0);
1636 }
1637
1638 // drawDevice is defined to be in device coords.
1639 CHECK_SHOULD_DRAW(draw, true);
1640
1641 GrRenderTarget* devRT = dev->accessRenderTarget();
1642 GrTexture* devTex;
1643 if (NULL == (devTex = devRT->asTexture())) {
1644 return;
1645 }
1646
1647 const SkBitmap& bm = dev->accessBitmap(false);
1648 int w = bm.width();
1649 int h = bm.height();
1650
1651 SkImageFilter* filter = paint.getImageFilter();
1652 // This bitmap will own the filtered result as a texture.
1653 SkBitmap filteredBitmap;
1654
1655 if (NULL != filter) {
1656 SkIPoint offset = SkIPoint::Make(0, 0);
1657 SkMatrix matrix(*draw.fMatrix);
1658 matrix.postTranslate(SkIntToScalar(-x), SkIntToScalar(-y));
1659 if (filter_texture(this, fContext, devTex, filter, w, h, matrix, &filteredBitmap,
1660 &offset)) {
1661 devTex = filteredBitmap.getTexture();
1662 w = filteredBitmap.width();
1663 h = filteredBitmap.height();
1664 x += offset.fX;
1665 y += offset.fY;
1666 } else {
1667 return;
1668 }
1669 }
1670
1671 GrPaint grPaint;
1672 grPaint.addColorTextureEffect(devTex, SkMatrix::I());
1673
1674 if (!skPaint2GrPaintNoShader(this, paint, true, false, &grPaint)) {
1675 return;
1676 }
1677
1678 SkRect dstRect = SkRect::MakeXYWH(SkIntToScalar(x),
1679 SkIntToScalar(y),
1680 SkIntToScalar(w),
1681 SkIntToScalar(h));
1682
1683 // The device being drawn may not fill up its texture (e.g. saveLayer uses approximate
1684 // scratch texture).
1685 SkRect srcRect = SkRect::MakeWH(SK_Scalar1 * w / devTex->width(),
1686 SK_Scalar1 * h / devTex->height());
1687
1688 fContext->drawRectToRect(grPaint, dstRect, srcRect);
1689}
1690
1691bool SkGpuDevice::canHandleImageFilter(SkImageFilter* filter) {
1692 return filter->canFilterImageGPU();
1693}
1694
1695bool SkGpuDevice::filterImage(SkImageFilter* filter, const SkBitmap& src,
1696 const SkMatrix& ctm,
1697 SkBitmap* result, SkIPoint* offset) {
1698 // want explicitly our impl, so guard against a subclass of us overriding it
1699 if (!this->SkGpuDevice::canHandleImageFilter(filter)) {
1700 return false;
1701 }
1702
1703 SkAutoLockPixels alp(src, !src.getTexture());
1704 if (!src.getTexture() && !src.readyToDraw()) {
1705 return false;
1706 }
1707
1708 GrTexture* texture;
1709 // We assume here that the filter will not attempt to tile the src. Otherwise, this cache lookup
1710 // must be pushed upstack.
1711 SkAutoCachedTexture act(this, src, NULL, &texture);
1712
1713 return filter_texture(this, fContext, texture, filter, src.width(), src.height(), ctm, result,
1714 offset);
1715}
1716
1717///////////////////////////////////////////////////////////////////////////////
1718
1719// must be in SkCanvas::VertexMode order
1720static const GrPrimitiveType gVertexMode2PrimitiveType[] = {
1721 kTriangles_GrPrimitiveType,
1722 kTriangleStrip_GrPrimitiveType,
1723 kTriangleFan_GrPrimitiveType,
1724};
1725
1726void SkGpuDevice::drawVertices(const SkDraw& draw, SkCanvas::VertexMode vmode,
1727 int vertexCount, const SkPoint vertices[],
1728 const SkPoint texs[], const SkColor colors[],
1729 SkXfermode* xmode,
1730 const uint16_t indices[], int indexCount,
1731 const SkPaint& paint) {
1732 CHECK_SHOULD_DRAW(draw, false);
1733
1734 GrPaint grPaint;
1735 // we ignore the shader if texs is null.
1736 if (NULL == texs) {
1737 if (!skPaint2GrPaintNoShader(this, paint, false, NULL == colors, &grPaint)) {
1738 return;
1739 }
1740 } else {
1741 if (!skPaint2GrPaintShader(this, paint, NULL == colors, &grPaint)) {
1742 return;
1743 }
1744 }
1745
1746 if (NULL != xmode && NULL != texs && NULL != colors) {
1747 if (!SkXfermode::IsMode(xmode, SkXfermode::kModulate_Mode)) {
1748 SkDebugf("Unsupported vertex-color/texture xfer mode.\n");
1749#if 0
1750 return
1751#endif
1752 }
1753 }
1754
1755 SkAutoSTMalloc<128, GrColor> convertedColors(0);
1756 if (NULL != colors) {
1757 // need to convert byte order and from non-PM to PM
1758 convertedColors.reset(vertexCount);
1759 for (int i = 0; i < vertexCount; ++i) {
1760 convertedColors[i] = SkColor2GrColor(colors[i]);
1761 }
1762 colors = convertedColors.get();
1763 }
1764 fContext->drawVertices(grPaint,
1765 gVertexMode2PrimitiveType[vmode],
1766 vertexCount,
1767 (GrPoint*) vertices,
1768 (GrPoint*) texs,
1769 colors,
1770 indices,
1771 indexCount);
1772}
1773
1774///////////////////////////////////////////////////////////////////////////////
1775
1776static void GlyphCacheAuxProc(void* data) {
1777 GrFontScaler* scaler = (GrFontScaler*)data;
1778 SkSafeUnref(scaler);
1779}
1780
1781static GrFontScaler* get_gr_font_scaler(SkGlyphCache* cache) {
1782 void* auxData;
1783 GrFontScaler* scaler = NULL;
1784 if (cache->getAuxProcData(GlyphCacheAuxProc, &auxData)) {
1785 scaler = (GrFontScaler*)auxData;
1786 }
1787 if (NULL == scaler) {
1788 scaler = SkNEW_ARGS(SkGrFontScaler, (cache));
1789 cache->setAuxProc(GlyphCacheAuxProc, scaler);
1790 }
1791 return scaler;
1792}
1793
1794static void SkGPU_Draw1Glyph(const SkDraw1Glyph& state,
1795 SkFixed fx, SkFixed fy,
1796 const SkGlyph& glyph) {
1797 SkASSERT(glyph.fWidth > 0 && glyph.fHeight > 0);
1798
1799 GrSkDrawProcs* procs = static_cast<GrSkDrawProcs*>(state.fDraw->fProcs);
1800
1801 if (NULL == procs->fFontScaler) {
1802 procs->fFontScaler = get_gr_font_scaler(state.fCache);
1803 }
1804
1805 procs->fTextContext->drawPackedGlyph(GrGlyph::Pack(glyph.getGlyphID(),
1806 glyph.getSubXFixed(),
1807 glyph.getSubYFixed()),
1808 SkFixedFloorToFixed(fx),
1809 SkFixedFloorToFixed(fy),
1810 procs->fFontScaler);
1811}
1812
1813SkDrawProcs* SkGpuDevice::initDrawForText(GrTextContext* context) {
1814
1815 // deferred allocation
1816 if (NULL == fDrawProcs) {
1817 fDrawProcs = SkNEW(GrSkDrawProcs);
1818 fDrawProcs->fD1GProc = SkGPU_Draw1Glyph;
1819 fDrawProcs->fContext = fContext;
skia.committer@gmail.com11a253b2013-11-12 07:02:05 +00001820 }
1821
1822 // init our (and GL's) state
1823 fDrawProcs->fTextContext = context;
1824 fDrawProcs->fFontScaler = NULL;
1825 return fDrawProcs;
1826}
1827
1828void SkGpuDevice::drawText(const SkDraw& draw, const void* text,
1829 size_t byteLength, SkScalar x, SkScalar y,
1830 const SkPaint& paint) {
1831 CHECK_SHOULD_DRAW(draw, false);
1832
commit-bot@chromium.org8128d8c2013-12-19 16:12:25 +00001833 if (SkDraw::ShouldDrawTextAsPaths(paint, fContext->getMatrix())) {
1834 draw.drawText_asPaths((const char*)text, byteLength, x, y, paint);
1835#if SK_DISTANCEFIELD_FONTS
1836 } else if (!paint.getRasterizer()) {
1837 GrPaint grPaint;
1838 if (!skPaint2GrPaintShader(this, paint, true, &grPaint)) {
1839 return;
1840 }
1841
1842 SkDEBUGCODE(this->validate();)
1843
commit-bot@chromium.orgcc40f062014-01-24 14:38:27 +00001844 SkAutoTDelete<GrTextContext> context(fTextContextManager->create(fContext, grPaint, paint));
1845 GrDistanceFieldTextContext* dfContext =
1846 static_cast<GrDistanceFieldTextContext*>(context.get());
commit-bot@chromium.org8128d8c2013-12-19 16:12:25 +00001847
commit-bot@chromium.orgcc40f062014-01-24 14:38:27 +00001848 SkAutoGlyphCache autoCache(dfContext->getSkPaint(), &this->fLeakyProperties, NULL);
commit-bot@chromium.org8128d8c2013-12-19 16:12:25 +00001849 SkGlyphCache* cache = autoCache.getCache();
1850 GrFontScaler* fontScaler = get_gr_font_scaler(cache);
1851
commit-bot@chromium.orgcc40f062014-01-24 14:38:27 +00001852 dfContext->drawText((const char *)text, byteLength, x, y, cache, fontScaler);
commit-bot@chromium.org8128d8c2013-12-19 16:12:25 +00001853#endif
skia.committer@gmail.com11a253b2013-11-12 07:02:05 +00001854 } else {
1855 SkDraw myDraw(draw);
1856
1857 GrPaint grPaint;
1858 if (!skPaint2GrPaintShader(this, paint, true, &grPaint)) {
1859 return;
1860 }
commit-bot@chromium.org8128d8c2013-12-19 16:12:25 +00001861
commit-bot@chromium.orgcc40f062014-01-24 14:38:27 +00001862 SkAutoTDelete<GrTextContext> context(fTextContextManager->create(fContext, grPaint, paint));
1863 myDraw.fProcs = this->initDrawForText(context.get());
commit-bot@chromium.org8128d8c2013-12-19 16:12:25 +00001864 this->INHERITED::drawText(myDraw, text, byteLength, x, y, paint);
skia.committer@gmail.com11a253b2013-11-12 07:02:05 +00001865 }
1866}
1867
1868void SkGpuDevice::drawPosText(const SkDraw& draw, const void* text,
1869 size_t byteLength, const SkScalar pos[],
1870 SkScalar constY, int scalarsPerPos,
1871 const SkPaint& paint) {
1872 CHECK_SHOULD_DRAW(draw, false);
1873
commit-bot@chromium.org8128d8c2013-12-19 16:12:25 +00001874 if (SkDraw::ShouldDrawTextAsPaths(paint, fContext->getMatrix())) {
skia.committer@gmail.com11a253b2013-11-12 07:02:05 +00001875 // this guy will just call our drawPath()
commit-bot@chromium.org8128d8c2013-12-19 16:12:25 +00001876 draw.drawPosText_asPaths((const char*)text, byteLength, pos, constY,
skia.committer@gmail.com11a253b2013-11-12 07:02:05 +00001877 scalarsPerPos, paint);
commit-bot@chromium.org8128d8c2013-12-19 16:12:25 +00001878#if SK_DISTANCEFIELD_FONTS
1879 } else if (!paint.getRasterizer()) {
1880 GrPaint grPaint;
1881 if (!skPaint2GrPaintShader(this, paint, true, &grPaint)) {
1882 return;
1883 }
1884
1885 SkDEBUGCODE(this->validate();)
1886
commit-bot@chromium.orgcc40f062014-01-24 14:38:27 +00001887 SkAutoTDelete<GrTextContext> context(fTextContextManager->create(fContext, grPaint, paint));
1888 GrDistanceFieldTextContext* dfContext =
1889 static_cast<GrDistanceFieldTextContext*>(context.get());
skia.committer@gmail.comd2ac07b2014-01-25 07:01:49 +00001890
commit-bot@chromium.orgcc40f062014-01-24 14:38:27 +00001891 SkAutoGlyphCache autoCache(dfContext->getSkPaint(), &this->fLeakyProperties, NULL);
commit-bot@chromium.org8128d8c2013-12-19 16:12:25 +00001892 SkGlyphCache* cache = autoCache.getCache();
1893 GrFontScaler* fontScaler = get_gr_font_scaler(cache);
skia.committer@gmail.comd2ac07b2014-01-25 07:01:49 +00001894
commit-bot@chromium.orgcc40f062014-01-24 14:38:27 +00001895 dfContext->drawPosText((const char *)text, byteLength, pos, constY, scalarsPerPos,
commit-bot@chromium.org8128d8c2013-12-19 16:12:25 +00001896 cache, fontScaler);
1897#endif
skia.committer@gmail.com11a253b2013-11-12 07:02:05 +00001898 } else {
1899 SkDraw myDraw(draw);
1900
1901 GrPaint grPaint;
1902 if (!skPaint2GrPaintShader(this, paint, true, &grPaint)) {
1903 return;
1904 }
commit-bot@chromium.orgcc40f062014-01-24 14:38:27 +00001905
1906 SkAutoTDelete<GrTextContext> context(fTextContextManager->create(fContext, grPaint, paint));
1907 myDraw.fProcs = this->initDrawForText(context.get());
commit-bot@chromium.org8128d8c2013-12-19 16:12:25 +00001908 this->INHERITED::drawPosText(myDraw, text, byteLength, pos, constY,
1909 scalarsPerPos, paint);
skia.committer@gmail.com11a253b2013-11-12 07:02:05 +00001910 }
1911}
1912
1913void SkGpuDevice::drawTextOnPath(const SkDraw& draw, const void* text,
1914 size_t len, const SkPath& path,
1915 const SkMatrix* m, const SkPaint& paint) {
1916 CHECK_SHOULD_DRAW(draw, false);
1917
1918 SkASSERT(draw.fDevice == this);
1919 draw.drawTextOnPath((const char*)text, len, path, m, paint);
1920}
1921
1922///////////////////////////////////////////////////////////////////////////////
1923
1924bool SkGpuDevice::filterTextFlags(const SkPaint& paint, TextFlags* flags) {
1925 if (!paint.isLCDRenderText()) {
1926 // we're cool with the paint as is
1927 return false;
1928 }
1929
1930 if (paint.getShader() ||
1931 paint.getXfermode() || // unless its srcover
1932 paint.getMaskFilter() ||
1933 paint.getRasterizer() ||
1934 paint.getColorFilter() ||
1935 paint.getPathEffect() ||
1936 paint.isFakeBoldText() ||
1937 paint.getStyle() != SkPaint::kFill_Style) {
1938 // turn off lcd
1939 flags->fFlags = paint.getFlags() & ~SkPaint::kLCDRenderText_Flag;
1940 flags->fHinting = paint.getHinting();
1941 return true;
1942 }
1943 // we're cool with the paint as is
1944 return false;
1945}
1946
1947void SkGpuDevice::flush() {
1948 DO_DEFERRED_CLEAR();
1949 fContext->resolveRenderTarget(fRenderTarget);
1950}
1951
1952///////////////////////////////////////////////////////////////////////////////
1953
1954SkBaseDevice* SkGpuDevice::onCreateCompatibleDevice(SkBitmap::Config config,
1955 int width, int height,
1956 bool isOpaque,
1957 Usage usage) {
1958 GrTextureDesc desc;
1959 desc.fConfig = fRenderTarget->config();
1960 desc.fFlags = kRenderTarget_GrTextureFlagBit;
1961 desc.fWidth = width;
1962 desc.fHeight = height;
1963 desc.fSampleCnt = fRenderTarget->numSamples();
1964
1965 SkAutoTUnref<GrTexture> texture;
1966 // Skia's convention is to only clear a device if it is non-opaque.
1967 bool needClear = !isOpaque;
1968
1969#if CACHE_COMPATIBLE_DEVICE_TEXTURES
1970 // layers are never draw in repeat modes, so we can request an approx
1971 // match and ignore any padding.
1972 const GrContext::ScratchTexMatch match = (kSaveLayer_Usage == usage) ?
1973 GrContext::kApprox_ScratchTexMatch :
1974 GrContext::kExact_ScratchTexMatch;
1975 texture.reset(fContext->lockAndRefScratchTexture(desc, match));
1976#else
1977 texture.reset(fContext->createUncachedTexture(desc, NULL, 0));
1978#endif
1979 if (NULL != texture.get()) {
1980 return SkNEW_ARGS(SkGpuDevice,(fContext, texture, needClear));
1981 } else {
1982 GrPrintf("---- failed to create compatible device texture [%d %d]\n", width, height);
1983 return NULL;
1984 }
1985}
1986
1987SkGpuDevice::SkGpuDevice(GrContext* context,
1988 GrTexture* texture,
1989 bool needClear)
1990 : SkBitmapDevice(make_bitmap(context, texture->asRenderTarget())) {
1991
1992 SkASSERT(texture && texture->asRenderTarget());
1993 // This constructor is called from onCreateCompatibleDevice. It has locked the RT in the texture
1994 // cache. We pass true for the third argument so that it will get unlocked.
1995 this->initFromRenderTarget(context, texture->asRenderTarget(), true);
1996 fNeedClear = needClear;
1997}