blob: 73eb65b6614af78eab2b14dfde2e50346908ae08 [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.orgdcfa9ff2014-01-28 01:55:24 +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 }
956
957 GrAutoScratchTexture mask;
958
959 if (create_mask_GPU(fContext, maskRect, *devPathPtr, stroke,
960 grPaint.isAntiAlias(), &mask)) {
961 GrTexture* filtered;
962
commit-bot@chromium.org41bf9302014-01-08 22:25:53 +0000963 if (paint.getMaskFilter()->filterMaskGPU(mask.texture(),
commit-bot@chromium.org439ff1b2014-01-13 16:39:39 +0000964 ctm, maskRect, &filtered, true)) {
skia.committer@gmail.com11a253b2013-11-12 07:02:05 +0000965 // filterMaskGPU gives us ownership of a ref to the result
966 SkAutoTUnref<GrTexture> atu(filtered);
967
968 // If the scratch texture that we used as the filter src also holds the filter
969 // result then we must detach so that this texture isn't recycled for a later
970 // draw.
971 if (filtered == mask.texture()) {
972 mask.detach();
973 filtered->unref(); // detach transfers GrAutoScratchTexture's ref to us.
974 }
975
976 if (draw_mask(fContext, maskRect, &grPaint, filtered)) {
977 // This path is completely drawn
978 return;
979 }
980 }
981 }
982 }
983
984 // draw the mask on the CPU - this is a fallthrough path in case the
985 // GPU path fails
986 SkPaint::Style style = stroke.isHairlineStyle() ? SkPaint::kStroke_Style :
987 SkPaint::kFill_Style;
988 draw_with_mask_filter(fContext, *devPathPtr, paint.getMaskFilter(),
989 *draw.fClip, draw.fBounder, &grPaint, style);
990 return;
991 }
992
993 fContext->drawPath(grPaint, *pathPtr, stroke);
994}
995
996static const int kBmpSmallTileSize = 1 << 10;
997
998static inline int get_tile_count(const SkIRect& srcRect, int tileSize) {
999 int tilesX = (srcRect.fRight / tileSize) - (srcRect.fLeft / tileSize) + 1;
1000 int tilesY = (srcRect.fBottom / tileSize) - (srcRect.fTop / tileSize) + 1;
1001 return tilesX * tilesY;
1002}
1003
1004static int determine_tile_size(const SkBitmap& bitmap, const SkIRect& src, int maxTileSize) {
1005 if (maxTileSize <= kBmpSmallTileSize) {
1006 return maxTileSize;
1007 }
1008
1009 size_t maxTileTotalTileSize = get_tile_count(src, maxTileSize);
1010 size_t smallTotalTileSize = get_tile_count(src, kBmpSmallTileSize);
1011
1012 maxTileTotalTileSize *= maxTileSize * maxTileSize;
1013 smallTotalTileSize *= kBmpSmallTileSize * kBmpSmallTileSize;
1014
1015 if (maxTileTotalTileSize > 2 * smallTotalTileSize) {
1016 return kBmpSmallTileSize;
1017 } else {
1018 return maxTileSize;
1019 }
1020}
1021
1022// Given a bitmap, an optional src rect, and a context with a clip and matrix determine what
1023// pixels from the bitmap are necessary.
1024static void determine_clipped_src_rect(const GrContext* context,
1025 const SkBitmap& bitmap,
1026 const SkRect* srcRectPtr,
1027 SkIRect* clippedSrcIRect) {
1028 const GrClipData* clip = context->getClip();
1029 clip->getConservativeBounds(context->getRenderTarget(), clippedSrcIRect, NULL);
1030 SkMatrix inv;
1031 if (!context->getMatrix().invert(&inv)) {
1032 clippedSrcIRect->setEmpty();
1033 return;
1034 }
1035 SkRect clippedSrcRect = SkRect::Make(*clippedSrcIRect);
1036 inv.mapRect(&clippedSrcRect);
1037 if (NULL != srcRectPtr) {
commit-bot@chromium.orga7d89c82014-01-13 14:47:00 +00001038 // we've setup src space 0,0 to map to the top left of the src rect.
1039 clippedSrcRect.offset(srcRectPtr->fLeft, srcRectPtr->fTop);
skia.committer@gmail.com11a253b2013-11-12 07:02:05 +00001040 if (!clippedSrcRect.intersect(*srcRectPtr)) {
1041 clippedSrcIRect->setEmpty();
1042 return;
1043 }
1044 }
1045 clippedSrcRect.roundOut(clippedSrcIRect);
1046 SkIRect bmpBounds = SkIRect::MakeWH(bitmap.width(), bitmap.height());
1047 if (!clippedSrcIRect->intersect(bmpBounds)) {
1048 clippedSrcIRect->setEmpty();
1049 }
1050}
1051
1052bool SkGpuDevice::shouldTileBitmap(const SkBitmap& bitmap,
1053 const GrTextureParams& params,
1054 const SkRect* srcRectPtr,
1055 int maxTileSize,
1056 int* tileSize,
1057 SkIRect* clippedSrcRect) const {
1058 // if bitmap is explictly texture backed then just use the texture
1059 if (NULL != bitmap.getTexture()) {
1060 return false;
1061 }
1062
1063 // if it's larger than the max tile size, then we have no choice but tiling.
1064 if (bitmap.width() > maxTileSize || bitmap.height() > maxTileSize) {
1065 determine_clipped_src_rect(fContext, bitmap, srcRectPtr, clippedSrcRect);
1066 *tileSize = determine_tile_size(bitmap, *clippedSrcRect, maxTileSize);
1067 return true;
1068 }
1069
1070 if (bitmap.width() * bitmap.height() < 4 * kBmpSmallTileSize * kBmpSmallTileSize) {
1071 return false;
1072 }
1073
1074 // if the entire texture is already in our cache then no reason to tile it
1075 if (GrIsBitmapInCache(fContext, bitmap, &params)) {
1076 return false;
1077 }
1078
1079 // At this point we know we could do the draw by uploading the entire bitmap
1080 // as a texture. However, if the texture would be large compared to the
1081 // cache size and we don't require most of it for this draw then tile to
1082 // reduce the amount of upload and cache spill.
1083
1084 // assumption here is that sw bitmap size is a good proxy for its size as
1085 // a texture
1086 size_t bmpSize = bitmap.getSize();
1087 size_t cacheSize;
1088 fContext->getTextureCacheLimits(NULL, &cacheSize);
1089 if (bmpSize < cacheSize / 2) {
1090 return false;
1091 }
1092
1093 // Figure out how much of the src we will need based on the src rect and clipping.
1094 determine_clipped_src_rect(fContext, bitmap, srcRectPtr, clippedSrcRect);
1095 *tileSize = kBmpSmallTileSize; // already know whole bitmap fits in one max sized tile.
1096 size_t usedTileBytes = get_tile_count(*clippedSrcRect, kBmpSmallTileSize) *
1097 kBmpSmallTileSize * kBmpSmallTileSize;
1098
1099 return usedTileBytes < 2 * bmpSize;
1100}
1101
commit-bot@chromium.orga7d89c82014-01-13 14:47:00 +00001102void SkGpuDevice::drawBitmap(const SkDraw& origDraw,
skia.committer@gmail.com11a253b2013-11-12 07:02:05 +00001103 const SkBitmap& bitmap,
1104 const SkMatrix& m,
1105 const SkPaint& paint) {
commit-bot@chromium.orga7d89c82014-01-13 14:47:00 +00001106 SkMatrix concat;
1107 SkTCopyOnFirstWrite<SkDraw> draw(origDraw);
1108 if (!m.isIdentity()) {
1109 concat.setConcat(*draw->fMatrix, m);
1110 draw.writable()->fMatrix = &concat;
1111 }
1112 this->drawBitmapCommon(*draw, bitmap, NULL, NULL, paint, SkCanvas::kNone_DrawBitmapRectFlag);
skia.committer@gmail.com11a253b2013-11-12 07:02:05 +00001113}
1114
commit-bot@chromium.orgdec61502013-12-02 22:22:35 +00001115// This method outsets 'iRect' by 'outset' all around and then clamps its extents to
skia.committer@gmail.com11a253b2013-11-12 07:02:05 +00001116// 'clamp'. 'offset' is adjusted to remain positioned over the top-left corner
1117// of 'iRect' for all possible outsets/clamps.
commit-bot@chromium.orgdec61502013-12-02 22:22:35 +00001118static inline void clamped_outset_with_offset(SkIRect* iRect,
1119 int outset,
1120 SkPoint* offset,
1121 const SkIRect& clamp) {
1122 iRect->outset(outset, outset);
skia.committer@gmail.com11a253b2013-11-12 07:02:05 +00001123
commit-bot@chromium.orgdec61502013-12-02 22:22:35 +00001124 int leftClampDelta = clamp.fLeft - iRect->fLeft;
1125 if (leftClampDelta > 0) {
1126 offset->fX -= outset - leftClampDelta;
skia.committer@gmail.com11a253b2013-11-12 07:02:05 +00001127 iRect->fLeft = clamp.fLeft;
1128 } else {
commit-bot@chromium.orgdec61502013-12-02 22:22:35 +00001129 offset->fX -= outset;
skia.committer@gmail.com11a253b2013-11-12 07:02:05 +00001130 }
commit-bot@chromium.orgdec61502013-12-02 22:22:35 +00001131
1132 int topClampDelta = clamp.fTop - iRect->fTop;
1133 if (topClampDelta > 0) {
1134 offset->fY -= outset - topClampDelta;
skia.committer@gmail.com11a253b2013-11-12 07:02:05 +00001135 iRect->fTop = clamp.fTop;
1136 } else {
commit-bot@chromium.orgdec61502013-12-02 22:22:35 +00001137 offset->fY -= outset;
skia.committer@gmail.com11a253b2013-11-12 07:02:05 +00001138 }
1139
1140 if (iRect->fRight > clamp.fRight) {
1141 iRect->fRight = clamp.fRight;
1142 }
1143 if (iRect->fBottom > clamp.fBottom) {
1144 iRect->fBottom = clamp.fBottom;
1145 }
1146}
1147
1148void SkGpuDevice::drawBitmapCommon(const SkDraw& draw,
1149 const SkBitmap& bitmap,
1150 const SkRect* srcRectPtr,
commit-bot@chromium.orga7d89c82014-01-13 14:47:00 +00001151 const SkSize* dstSizePtr,
skia.committer@gmail.com11a253b2013-11-12 07:02:05 +00001152 const SkPaint& paint,
1153 SkCanvas::DrawBitmapRectFlags flags) {
1154 CHECK_SHOULD_DRAW(draw, false);
1155
1156 SkRect srcRect;
commit-bot@chromium.orga7d89c82014-01-13 14:47:00 +00001157 SkSize dstSize;
commit-bot@chromium.orgdec61502013-12-02 22:22:35 +00001158 // If there is no src rect, or the src rect contains the entire bitmap then we're effectively
1159 // in the (easier) bleed case, so update flags.
skia.committer@gmail.com11a253b2013-11-12 07:02:05 +00001160 if (NULL == srcRectPtr) {
commit-bot@chromium.orga7d89c82014-01-13 14:47:00 +00001161 SkScalar w = SkIntToScalar(bitmap.width());
1162 SkScalar h = SkIntToScalar(bitmap.height());
1163 dstSize.fWidth = w;
1164 dstSize.fHeight = h;
1165 srcRect.set(0, 0, w, h);
commit-bot@chromium.orgdec61502013-12-02 22:22:35 +00001166 flags = (SkCanvas::DrawBitmapRectFlags) (flags | SkCanvas::kBleed_DrawBitmapRectFlag);
skia.committer@gmail.com11a253b2013-11-12 07:02:05 +00001167 } else {
commit-bot@chromium.orga7d89c82014-01-13 14:47:00 +00001168 SkASSERT(NULL != dstSizePtr);
skia.committer@gmail.com11a253b2013-11-12 07:02:05 +00001169 srcRect = *srcRectPtr;
commit-bot@chromium.orga7d89c82014-01-13 14:47:00 +00001170 dstSize = *dstSizePtr;
commit-bot@chromium.orgdec61502013-12-02 22:22:35 +00001171 if (srcRect.fLeft <= 0 && srcRect.fTop <= 0 &&
1172 srcRect.fRight >= bitmap.width() && srcRect.fBottom >= bitmap.height()) {
1173 flags = (SkCanvas::DrawBitmapRectFlags) (flags | SkCanvas::kBleed_DrawBitmapRectFlag);
1174 }
skia.committer@gmail.com11a253b2013-11-12 07:02:05 +00001175 }
1176
1177 if (paint.getMaskFilter()){
1178 // Convert the bitmap to a shader so that the rect can be drawn
1179 // through drawRect, which supports mask filters.
skia.committer@gmail.com11a253b2013-11-12 07:02:05 +00001180 SkBitmap tmp; // subset of bitmap, if necessary
1181 const SkBitmap* bitmapPtr = &bitmap;
commit-bot@chromium.orga7d89c82014-01-13 14:47:00 +00001182 SkMatrix localM;
skia.committer@gmail.com11a253b2013-11-12 07:02:05 +00001183 if (NULL != srcRectPtr) {
commit-bot@chromium.orga7d89c82014-01-13 14:47:00 +00001184 localM.setTranslate(-srcRectPtr->fLeft, -srcRectPtr->fTop);
1185 localM.postScale(dstSize.fWidth / srcRectPtr->width(),
1186 dstSize.fHeight / srcRectPtr->height());
commit-bot@chromium.orgd6ca4ac2013-11-22 20:34:59 +00001187 // In bleed mode we position and trim the bitmap based on the src rect which is
1188 // already accounted for in 'm' and 'srcRect'. In clamp mode we need to chop out
1189 // the desired portion of the bitmap and then update 'm' and 'srcRect' to
1190 // compensate.
1191 if (!(SkCanvas::kBleed_DrawBitmapRectFlag & flags)) {
1192 SkIRect iSrc;
1193 srcRect.roundOut(&iSrc);
skia.committer@gmail.com11a253b2013-11-12 07:02:05 +00001194
commit-bot@chromium.orgd6ca4ac2013-11-22 20:34:59 +00001195 SkPoint offset = SkPoint::Make(SkIntToScalar(iSrc.fLeft),
1196 SkIntToScalar(iSrc.fTop));
skia.committer@gmail.com11a253b2013-11-12 07:02:05 +00001197
commit-bot@chromium.orgd6ca4ac2013-11-22 20:34:59 +00001198 if (!bitmap.extractSubset(&tmp, iSrc)) {
1199 return; // extraction failed
1200 }
1201 bitmapPtr = &tmp;
1202 srcRect.offset(-offset.fX, -offset.fY);
commit-bot@chromium.orga7d89c82014-01-13 14:47:00 +00001203
commit-bot@chromium.orgd6ca4ac2013-11-22 20:34:59 +00001204 // The source rect has changed so update the matrix
commit-bot@chromium.orga7d89c82014-01-13 14:47:00 +00001205 localM.preTranslate(offset.fX, offset.fY);
skia.committer@gmail.com11a253b2013-11-12 07:02:05 +00001206 }
commit-bot@chromium.orga7d89c82014-01-13 14:47:00 +00001207 } else {
1208 localM.reset();
skia.committer@gmail.com11a253b2013-11-12 07:02:05 +00001209 }
1210
commit-bot@chromium.orga7d89c82014-01-13 14:47:00 +00001211 SkPaint paintWithShader(paint);
1212 paintWithShader.setShader(SkShader::CreateBitmapShader(*bitmapPtr,
skia.committer@gmail.com11a253b2013-11-12 07:02:05 +00001213 SkShader::kClamp_TileMode, SkShader::kClamp_TileMode))->unref();
commit-bot@chromium.orga7d89c82014-01-13 14:47:00 +00001214 paintWithShader.getShader()->setLocalMatrix(localM);
1215 SkRect dstRect = {0, 0, dstSize.fWidth, dstSize.fHeight};
1216 this->drawRect(draw, dstRect, paintWithShader);
skia.committer@gmail.com11a253b2013-11-12 07:02:05 +00001217
1218 return;
1219 }
1220
commit-bot@chromium.orga7d89c82014-01-13 14:47:00 +00001221 // If there is no mask filter than it is OK to handle the src rect -> dst rect scaling using
1222 // the view matrix rather than a local matrix.
1223 SkMatrix m;
1224 m.setScale(dstSize.fWidth / srcRect.width(),
1225 dstSize.fHeight / srcRect.height());
skia.committer@gmail.com11a253b2013-11-12 07:02:05 +00001226 fContext->concatMatrix(m);
1227
1228 GrTextureParams params;
1229 SkPaint::FilterLevel paintFilterLevel = paint.getFilterLevel();
1230 GrTextureParams::FilterMode textureFilterMode;
commit-bot@chromium.orgdec61502013-12-02 22:22:35 +00001231
1232 int tileFilterPad;
1233 bool doBicubic = false;
1234
skia.committer@gmail.com11a253b2013-11-12 07:02:05 +00001235 switch(paintFilterLevel) {
1236 case SkPaint::kNone_FilterLevel:
commit-bot@chromium.orgdec61502013-12-02 22:22:35 +00001237 tileFilterPad = 0;
skia.committer@gmail.com11a253b2013-11-12 07:02:05 +00001238 textureFilterMode = GrTextureParams::kNone_FilterMode;
1239 break;
1240 case SkPaint::kLow_FilterLevel:
commit-bot@chromium.orgdec61502013-12-02 22:22:35 +00001241 tileFilterPad = 1;
skia.committer@gmail.com11a253b2013-11-12 07:02:05 +00001242 textureFilterMode = GrTextureParams::kBilerp_FilterMode;
1243 break;
1244 case SkPaint::kMedium_FilterLevel:
commit-bot@chromium.orgdec61502013-12-02 22:22:35 +00001245 tileFilterPad = 1;
commit-bot@chromium.org79b7eee2013-12-16 21:02:29 +00001246 if (fContext->getMatrix().getMinStretch() < SK_Scalar1) {
1247 textureFilterMode = GrTextureParams::kMipMap_FilterMode;
1248 } else {
1249 // Don't trigger MIP level generation unnecessarily.
1250 textureFilterMode = GrTextureParams::kBilerp_FilterMode;
1251 }
skia.committer@gmail.com11a253b2013-11-12 07:02:05 +00001252 break;
commit-bot@chromium.org79b7eee2013-12-16 21:02:29 +00001253 case SkPaint::kHigh_FilterLevel:
commit-bot@chromium.orgcea9abb2013-12-09 19:15:37 +00001254 // Minification can look bad with the bicubic effect.
commit-bot@chromium.org7d7f3142013-12-16 15:18:11 +00001255 if (fContext->getMatrix().getMinStretch() >= SK_Scalar1) {
commit-bot@chromium.orgdec61502013-12-02 22:22:35 +00001256 // We will install an effect that does the filtering in the shader.
1257 textureFilterMode = GrTextureParams::kNone_FilterMode;
1258 tileFilterPad = GrBicubicEffect::kFilterTexelPad;
1259 doBicubic = true;
1260 } else {
commit-bot@chromium.orgdec61502013-12-02 22:22:35 +00001261 textureFilterMode = GrTextureParams::kMipMap_FilterMode;
1262 tileFilterPad = 1;
1263 }
skia.committer@gmail.com11a253b2013-11-12 07:02:05 +00001264 break;
1265 default:
1266 SkErrorInternals::SetError( kInvalidPaint_SkError,
1267 "Sorry, I don't understand the filtering "
1268 "mode you asked for. Falling back to "
1269 "MIPMaps.");
commit-bot@chromium.orgdec61502013-12-02 22:22:35 +00001270 tileFilterPad = 1;
skia.committer@gmail.com11a253b2013-11-12 07:02:05 +00001271 textureFilterMode = GrTextureParams::kMipMap_FilterMode;
1272 break;
skia.committer@gmail.com11a253b2013-11-12 07:02:05 +00001273 }
1274
1275 params.setFilterMode(textureFilterMode);
1276
commit-bot@chromium.orgdec61502013-12-02 22:22:35 +00001277 int maxTileSize = fContext->getMaxTextureSize() - 2 * tileFilterPad;
skia.committer@gmail.com11a253b2013-11-12 07:02:05 +00001278 int tileSize;
1279
1280 SkIRect clippedSrcRect;
1281 if (this->shouldTileBitmap(bitmap, params, srcRectPtr, maxTileSize, &tileSize,
1282 &clippedSrcRect)) {
commit-bot@chromium.orgdec61502013-12-02 22:22:35 +00001283 this->drawTiledBitmap(bitmap, srcRect, clippedSrcRect, params, paint, flags, tileSize,
1284 doBicubic);
skia.committer@gmail.com11a253b2013-11-12 07:02:05 +00001285 } else {
1286 // take the simple case
commit-bot@chromium.orgdec61502013-12-02 22:22:35 +00001287 this->internalDrawBitmap(bitmap, srcRect, params, paint, flags, doBicubic);
skia.committer@gmail.com11a253b2013-11-12 07:02:05 +00001288 }
1289}
1290
1291// Break 'bitmap' into several tiles to draw it since it has already
1292// been determined to be too large to fit in VRAM
1293void SkGpuDevice::drawTiledBitmap(const SkBitmap& bitmap,
1294 const SkRect& srcRect,
1295 const SkIRect& clippedSrcIRect,
1296 const GrTextureParams& params,
1297 const SkPaint& paint,
1298 SkCanvas::DrawBitmapRectFlags flags,
commit-bot@chromium.orgdec61502013-12-02 22:22:35 +00001299 int tileSize,
1300 bool bicubic) {
skia.committer@gmail.com11a253b2013-11-12 07:02:05 +00001301 SkRect clippedSrcRect = SkRect::Make(clippedSrcIRect);
1302
1303 int nx = bitmap.width() / tileSize;
1304 int ny = bitmap.height() / tileSize;
1305 for (int x = 0; x <= nx; x++) {
1306 for (int y = 0; y <= ny; y++) {
1307 SkRect tileR;
1308 tileR.set(SkIntToScalar(x * tileSize),
1309 SkIntToScalar(y * tileSize),
1310 SkIntToScalar((x + 1) * tileSize),
1311 SkIntToScalar((y + 1) * tileSize));
1312
1313 if (!SkRect::Intersects(tileR, clippedSrcRect)) {
1314 continue;
1315 }
1316
1317 if (!tileR.intersect(srcRect)) {
1318 continue;
1319 }
1320
1321 SkBitmap tmpB;
1322 SkIRect iTileR;
1323 tileR.roundOut(&iTileR);
1324 SkPoint offset = SkPoint::Make(SkIntToScalar(iTileR.fLeft),
1325 SkIntToScalar(iTileR.fTop));
1326
commit-bot@chromium.orga7d89c82014-01-13 14:47:00 +00001327 // Adjust the context matrix to draw at the right x,y in device space
1328 SkMatrix tmpM;
1329 GrContext::AutoMatrix am;
1330 tmpM.setTranslate(offset.fX - srcRect.fLeft, offset.fY - srcRect.fTop);
1331 am.setPreConcat(fContext, tmpM);
1332
commit-bot@chromium.orgdec61502013-12-02 22:22:35 +00001333 if (SkPaint::kNone_FilterLevel != paint.getFilterLevel() || bicubic) {
skia.committer@gmail.com11a253b2013-11-12 07:02:05 +00001334 SkIRect iClampRect;
1335
1336 if (SkCanvas::kBleed_DrawBitmapRectFlag & flags) {
1337 // In bleed mode we want to always expand the tile on all edges
1338 // but stay within the bitmap bounds
1339 iClampRect = SkIRect::MakeWH(bitmap.width(), bitmap.height());
1340 } else {
1341 // In texture-domain/clamp mode we only want to expand the
1342 // tile on edges interior to "srcRect" (i.e., we want to
1343 // not bleed across the original clamped edges)
1344 srcRect.roundOut(&iClampRect);
1345 }
commit-bot@chromium.orgdec61502013-12-02 22:22:35 +00001346 int outset = bicubic ? GrBicubicEffect::kFilterTexelPad : 1;
1347 clamped_outset_with_offset(&iTileR, outset, &offset, iClampRect);
skia.committer@gmail.com11a253b2013-11-12 07:02:05 +00001348 }
1349
1350 if (bitmap.extractSubset(&tmpB, iTileR)) {
1351 // now offset it to make it "local" to our tmp bitmap
1352 tileR.offset(-offset.fX, -offset.fY);
commit-bot@chromium.orga7d89c82014-01-13 14:47:00 +00001353
commit-bot@chromium.orgdec61502013-12-02 22:22:35 +00001354 this->internalDrawBitmap(tmpB, tileR, params, paint, flags, bicubic);
skia.committer@gmail.com11a253b2013-11-12 07:02:05 +00001355 }
1356 }
1357 }
1358}
1359
1360static bool has_aligned_samples(const SkRect& srcRect,
1361 const SkRect& transformedRect) {
1362 // detect pixel disalignment
1363 if (SkScalarAbs(SkScalarRoundToScalar(transformedRect.left()) -
1364 transformedRect.left()) < COLOR_BLEED_TOLERANCE &&
1365 SkScalarAbs(SkScalarRoundToScalar(transformedRect.top()) -
1366 transformedRect.top()) < COLOR_BLEED_TOLERANCE &&
1367 SkScalarAbs(transformedRect.width() - srcRect.width()) <
1368 COLOR_BLEED_TOLERANCE &&
1369 SkScalarAbs(transformedRect.height() - srcRect.height()) <
1370 COLOR_BLEED_TOLERANCE) {
1371 return true;
1372 }
1373 return false;
1374}
1375
1376static bool may_color_bleed(const SkRect& srcRect,
1377 const SkRect& transformedRect,
1378 const SkMatrix& m) {
1379 // Only gets called if has_aligned_samples returned false.
1380 // So we can assume that sampling is axis aligned but not texel aligned.
1381 SkASSERT(!has_aligned_samples(srcRect, transformedRect));
1382 SkRect innerSrcRect(srcRect), innerTransformedRect,
1383 outerTransformedRect(transformedRect);
1384 innerSrcRect.inset(SK_ScalarHalf, SK_ScalarHalf);
1385 m.mapRect(&innerTransformedRect, innerSrcRect);
1386
1387 // The gap between outerTransformedRect and innerTransformedRect
1388 // represents the projection of the source border area, which is
1389 // problematic for color bleeding. We must check whether any
1390 // destination pixels sample the border area.
1391 outerTransformedRect.inset(COLOR_BLEED_TOLERANCE, COLOR_BLEED_TOLERANCE);
1392 innerTransformedRect.outset(COLOR_BLEED_TOLERANCE, COLOR_BLEED_TOLERANCE);
1393 SkIRect outer, inner;
1394 outerTransformedRect.round(&outer);
1395 innerTransformedRect.round(&inner);
1396 // If the inner and outer rects round to the same result, it means the
1397 // border does not overlap any pixel centers. Yay!
1398 return inner != outer;
1399}
1400
1401
1402/*
1403 * This is called by drawBitmap(), which has to handle images that may be too
1404 * large to be represented by a single texture.
1405 *
1406 * internalDrawBitmap assumes that the specified bitmap will fit in a texture
1407 * and that non-texture portion of the GrPaint has already been setup.
1408 */
1409void SkGpuDevice::internalDrawBitmap(const SkBitmap& bitmap,
1410 const SkRect& srcRect,
1411 const GrTextureParams& params,
1412 const SkPaint& paint,
commit-bot@chromium.orgdec61502013-12-02 22:22:35 +00001413 SkCanvas::DrawBitmapRectFlags flags,
1414 bool bicubic) {
skia.committer@gmail.com11a253b2013-11-12 07:02:05 +00001415 SkASSERT(bitmap.width() <= fContext->getMaxTextureSize() &&
1416 bitmap.height() <= fContext->getMaxTextureSize());
1417
1418 GrTexture* texture;
1419 SkAutoCachedTexture act(this, bitmap, &params, &texture);
1420 if (NULL == texture) {
1421 return;
1422 }
1423
commit-bot@chromium.orga7d89c82014-01-13 14:47:00 +00001424 SkRect dstRect = {0, 0, srcRect.width(), srcRect.height() };
skia.committer@gmail.com11a253b2013-11-12 07:02:05 +00001425 SkRect paintRect;
1426 SkScalar wInv = SkScalarInvert(SkIntToScalar(texture->width()));
1427 SkScalar hInv = SkScalarInvert(SkIntToScalar(texture->height()));
1428 paintRect.setLTRB(SkScalarMul(srcRect.fLeft, wInv),
1429 SkScalarMul(srcRect.fTop, hInv),
1430 SkScalarMul(srcRect.fRight, wInv),
1431 SkScalarMul(srcRect.fBottom, hInv));
1432
1433 bool needsTextureDomain = false;
1434 if (!(flags & SkCanvas::kBleed_DrawBitmapRectFlag) &&
commit-bot@chromium.org7d7f3142013-12-16 15:18:11 +00001435 (bicubic || params.filterMode() != GrTextureParams::kNone_FilterMode)) {
1436 // Need texture domain if drawing a sub rect
skia.committer@gmail.com11a253b2013-11-12 07:02:05 +00001437 needsTextureDomain = srcRect.width() < bitmap.width() ||
1438 srcRect.height() < bitmap.height();
commit-bot@chromium.org7d7f3142013-12-16 15:18:11 +00001439 if (!bicubic && needsTextureDomain && fContext->getMatrix().rectStaysRect()) {
skia.committer@gmail.com11a253b2013-11-12 07:02:05 +00001440 const SkMatrix& matrix = fContext->getMatrix();
1441 // sampling is axis-aligned
1442 SkRect transformedRect;
1443 matrix.mapRect(&transformedRect, srcRect);
1444
1445 if (has_aligned_samples(srcRect, transformedRect)) {
1446 // We could also turn off filtering here (but we already did a cache lookup with
1447 // params).
1448 needsTextureDomain = false;
1449 } else {
1450 needsTextureDomain = may_color_bleed(srcRect, transformedRect, matrix);
1451 }
1452 }
1453 }
1454
1455 SkRect textureDomain = SkRect::MakeEmpty();
1456 SkAutoTUnref<GrEffectRef> effect;
1457 if (needsTextureDomain) {
1458 // Use a constrained texture domain to avoid color bleeding
1459 SkScalar left, top, right, bottom;
1460 if (srcRect.width() > SK_Scalar1) {
1461 SkScalar border = SK_ScalarHalf / texture->width();
1462 left = paintRect.left() + border;
1463 right = paintRect.right() - border;
1464 } else {
1465 left = right = SkScalarHalf(paintRect.left() + paintRect.right());
1466 }
1467 if (srcRect.height() > SK_Scalar1) {
1468 SkScalar border = SK_ScalarHalf / texture->height();
1469 top = paintRect.top() + border;
1470 bottom = paintRect.bottom() - border;
1471 } else {
1472 top = bottom = SkScalarHalf(paintRect.top() + paintRect.bottom());
1473 }
1474 textureDomain.setLTRB(left, top, right, bottom);
commit-bot@chromium.org7d7f3142013-12-16 15:18:11 +00001475 if (bicubic) {
1476 effect.reset(GrBicubicEffect::Create(texture, SkMatrix::I(), textureDomain));
1477 } else {
1478 effect.reset(GrTextureDomainEffect::Create(texture,
1479 SkMatrix::I(),
1480 textureDomain,
1481 GrTextureDomain::kClamp_Mode,
1482 params.filterMode()));
1483 }
commit-bot@chromium.orgdec61502013-12-02 22:22:35 +00001484 } else if (bicubic) {
commit-bot@chromium.orgbc91fd72013-12-10 12:53:39 +00001485 SkASSERT(GrTextureParams::kNone_FilterMode == params.filterMode());
1486 SkShader::TileMode tileModes[2] = { params.getTileModeX(), params.getTileModeY() };
1487 effect.reset(GrBicubicEffect::Create(texture, SkMatrix::I(), tileModes));
skia.committer@gmail.com11a253b2013-11-12 07:02:05 +00001488 } else {
1489 effect.reset(GrSimpleTextureEffect::Create(texture, SkMatrix::I(), params));
1490 }
1491
1492 // Construct a GrPaint by setting the bitmap texture as the first effect and then configuring
1493 // the rest from the SkPaint.
1494 GrPaint grPaint;
1495 grPaint.addColorEffect(effect);
1496 bool alphaOnly = !(SkBitmap::kA8_Config == bitmap.config());
1497 if (!skPaint2GrPaintNoShader(this, paint, alphaOnly, false, &grPaint)) {
1498 return;
1499 }
1500
1501 fContext->drawRectToRect(grPaint, dstRect, paintRect, NULL);
1502}
1503
1504static bool filter_texture(SkBaseDevice* device, GrContext* context,
1505 GrTexture* texture, SkImageFilter* filter,
1506 int w, int h, const SkMatrix& ctm, SkBitmap* result,
1507 SkIPoint* offset) {
1508 SkASSERT(filter);
1509 SkDeviceImageFilterProxy proxy(device);
1510
1511 if (filter->canFilterImageGPU()) {
1512 // Save the render target and set it to NULL, so we don't accidentally draw to it in the
1513 // filter. Also set the clip wide open and the matrix to identity.
1514 GrContext::AutoWideOpenIdentityDraw awo(context, NULL);
1515 return filter->filterImageGPU(&proxy, wrap_texture(texture), ctm, result, offset);
1516 } else {
1517 return false;
1518 }
1519}
1520
1521void SkGpuDevice::drawSprite(const SkDraw& draw, const SkBitmap& bitmap,
1522 int left, int top, const SkPaint& paint) {
1523 // drawSprite is defined to be in device coords.
1524 CHECK_SHOULD_DRAW(draw, true);
1525
1526 SkAutoLockPixels alp(bitmap, !bitmap.getTexture());
1527 if (!bitmap.getTexture() && !bitmap.readyToDraw()) {
1528 return;
1529 }
1530
1531 int w = bitmap.width();
1532 int h = bitmap.height();
1533
1534 GrTexture* texture;
1535 // draw sprite uses the default texture params
1536 SkAutoCachedTexture act(this, bitmap, NULL, &texture);
1537
1538 SkImageFilter* filter = paint.getImageFilter();
skia.committer@gmail.com11a253b2013-11-12 07:02:05 +00001539 // This bitmap will own the filtered result as a texture.
1540 SkBitmap filteredBitmap;
1541
1542 if (NULL != filter) {
senorblanco@chromium.org6776b822014-01-03 21:48:22 +00001543 SkIPoint offset = SkIPoint::Make(0, 0);
skia.committer@gmail.com11a253b2013-11-12 07:02:05 +00001544 SkMatrix matrix(*draw.fMatrix);
1545 matrix.postTranslate(SkIntToScalar(-left), SkIntToScalar(-top));
1546 if (filter_texture(this, fContext, texture, filter, w, h, matrix, &filteredBitmap,
1547 &offset)) {
1548 texture = (GrTexture*) filteredBitmap.getTexture();
1549 w = filteredBitmap.width();
1550 h = filteredBitmap.height();
senorblanco@chromium.org6776b822014-01-03 21:48:22 +00001551 left += offset.x();
1552 top += offset.y();
skia.committer@gmail.com11a253b2013-11-12 07:02:05 +00001553 } else {
1554 return;
1555 }
1556 }
1557
1558 GrPaint grPaint;
1559 grPaint.addColorTextureEffect(texture, SkMatrix::I());
1560
1561 if(!skPaint2GrPaintNoShader(this, paint, true, false, &grPaint)) {
1562 return;
1563 }
1564
1565 fContext->drawRectToRect(grPaint,
senorblanco@chromium.org6776b822014-01-03 21:48:22 +00001566 SkRect::MakeXYWH(SkIntToScalar(left),
1567 SkIntToScalar(top),
skia.committer@gmail.com11a253b2013-11-12 07:02:05 +00001568 SkIntToScalar(w),
1569 SkIntToScalar(h)),
1570 SkRect::MakeXYWH(0,
1571 0,
1572 SK_Scalar1 * w / texture->width(),
1573 SK_Scalar1 * h / texture->height()));
1574}
1575
commit-bot@chromium.orga7d89c82014-01-13 14:47:00 +00001576void SkGpuDevice::drawBitmapRect(const SkDraw& origDraw, const SkBitmap& bitmap,
skia.committer@gmail.com11a253b2013-11-12 07:02:05 +00001577 const SkRect* src, const SkRect& dst,
1578 const SkPaint& paint,
1579 SkCanvas::DrawBitmapRectFlags flags) {
1580 SkMatrix matrix;
1581 SkRect bitmapBounds, tmpSrc;
1582
1583 bitmapBounds.set(0, 0,
1584 SkIntToScalar(bitmap.width()),
1585 SkIntToScalar(bitmap.height()));
1586
1587 // Compute matrix from the two rectangles
1588 if (NULL != src) {
1589 tmpSrc = *src;
1590 } else {
1591 tmpSrc = bitmapBounds;
1592 }
commit-bot@chromium.orga7d89c82014-01-13 14:47:00 +00001593
skia.committer@gmail.com11a253b2013-11-12 07:02:05 +00001594 matrix.setRectToRect(tmpSrc, dst, SkMatrix::kFill_ScaleToFit);
1595
1596 // clip the tmpSrc to the bounds of the bitmap. No check needed if src==null.
1597 if (NULL != src) {
1598 if (!bitmapBounds.contains(tmpSrc)) {
1599 if (!tmpSrc.intersect(bitmapBounds)) {
1600 return; // nothing to draw
1601 }
1602 }
1603 }
1604
commit-bot@chromium.orga7d89c82014-01-13 14:47:00 +00001605 SkRect tmpDst;
1606 matrix.mapRect(&tmpDst, tmpSrc);
1607
1608 SkTCopyOnFirstWrite<SkDraw> draw(origDraw);
1609 if (0 != tmpDst.fLeft || 0 != tmpDst.fTop) {
1610 // Translate so that tempDst's top left is at the origin.
1611 matrix = *origDraw.fMatrix;
1612 matrix.preTranslate(tmpDst.fLeft, tmpDst.fTop);
1613 draw.writable()->fMatrix = &matrix;
1614 }
1615 SkSize dstSize;
1616 dstSize.fWidth = tmpDst.width();
1617 dstSize.fHeight = tmpDst.height();
1618
1619 this->drawBitmapCommon(*draw, bitmap, &tmpSrc, &dstSize, paint, flags);
skia.committer@gmail.com11a253b2013-11-12 07:02:05 +00001620}
1621
1622void SkGpuDevice::drawDevice(const SkDraw& draw, SkBaseDevice* device,
1623 int x, int y, const SkPaint& paint) {
1624 // clear of the source device must occur before CHECK_SHOULD_DRAW
1625 SkGpuDevice* dev = static_cast<SkGpuDevice*>(device);
1626 if (dev->fNeedClear) {
1627 // TODO: could check here whether we really need to draw at all
1628 dev->clear(0x0);
1629 }
1630
1631 // drawDevice is defined to be in device coords.
1632 CHECK_SHOULD_DRAW(draw, true);
1633
1634 GrRenderTarget* devRT = dev->accessRenderTarget();
1635 GrTexture* devTex;
1636 if (NULL == (devTex = devRT->asTexture())) {
1637 return;
1638 }
1639
1640 const SkBitmap& bm = dev->accessBitmap(false);
1641 int w = bm.width();
1642 int h = bm.height();
1643
1644 SkImageFilter* filter = paint.getImageFilter();
1645 // This bitmap will own the filtered result as a texture.
1646 SkBitmap filteredBitmap;
1647
1648 if (NULL != filter) {
1649 SkIPoint offset = SkIPoint::Make(0, 0);
1650 SkMatrix matrix(*draw.fMatrix);
1651 matrix.postTranslate(SkIntToScalar(-x), SkIntToScalar(-y));
1652 if (filter_texture(this, fContext, devTex, filter, w, h, matrix, &filteredBitmap,
1653 &offset)) {
1654 devTex = filteredBitmap.getTexture();
1655 w = filteredBitmap.width();
1656 h = filteredBitmap.height();
1657 x += offset.fX;
1658 y += offset.fY;
1659 } else {
1660 return;
1661 }
1662 }
1663
1664 GrPaint grPaint;
1665 grPaint.addColorTextureEffect(devTex, SkMatrix::I());
1666
1667 if (!skPaint2GrPaintNoShader(this, paint, true, false, &grPaint)) {
1668 return;
1669 }
1670
1671 SkRect dstRect = SkRect::MakeXYWH(SkIntToScalar(x),
1672 SkIntToScalar(y),
1673 SkIntToScalar(w),
1674 SkIntToScalar(h));
1675
1676 // The device being drawn may not fill up its texture (e.g. saveLayer uses approximate
1677 // scratch texture).
1678 SkRect srcRect = SkRect::MakeWH(SK_Scalar1 * w / devTex->width(),
1679 SK_Scalar1 * h / devTex->height());
1680
1681 fContext->drawRectToRect(grPaint, dstRect, srcRect);
1682}
1683
1684bool SkGpuDevice::canHandleImageFilter(SkImageFilter* filter) {
1685 return filter->canFilterImageGPU();
1686}
1687
1688bool SkGpuDevice::filterImage(SkImageFilter* filter, const SkBitmap& src,
1689 const SkMatrix& ctm,
1690 SkBitmap* result, SkIPoint* offset) {
1691 // want explicitly our impl, so guard against a subclass of us overriding it
1692 if (!this->SkGpuDevice::canHandleImageFilter(filter)) {
1693 return false;
1694 }
1695
1696 SkAutoLockPixels alp(src, !src.getTexture());
1697 if (!src.getTexture() && !src.readyToDraw()) {
1698 return false;
1699 }
1700
1701 GrTexture* texture;
1702 // We assume here that the filter will not attempt to tile the src. Otherwise, this cache lookup
1703 // must be pushed upstack.
1704 SkAutoCachedTexture act(this, src, NULL, &texture);
1705
1706 return filter_texture(this, fContext, texture, filter, src.width(), src.height(), ctm, result,
1707 offset);
1708}
1709
1710///////////////////////////////////////////////////////////////////////////////
1711
1712// must be in SkCanvas::VertexMode order
1713static const GrPrimitiveType gVertexMode2PrimitiveType[] = {
1714 kTriangles_GrPrimitiveType,
1715 kTriangleStrip_GrPrimitiveType,
1716 kTriangleFan_GrPrimitiveType,
1717};
1718
1719void SkGpuDevice::drawVertices(const SkDraw& draw, SkCanvas::VertexMode vmode,
1720 int vertexCount, const SkPoint vertices[],
1721 const SkPoint texs[], const SkColor colors[],
1722 SkXfermode* xmode,
1723 const uint16_t indices[], int indexCount,
1724 const SkPaint& paint) {
1725 CHECK_SHOULD_DRAW(draw, false);
1726
1727 GrPaint grPaint;
1728 // we ignore the shader if texs is null.
1729 if (NULL == texs) {
1730 if (!skPaint2GrPaintNoShader(this, paint, false, NULL == colors, &grPaint)) {
1731 return;
1732 }
1733 } else {
1734 if (!skPaint2GrPaintShader(this, paint, NULL == colors, &grPaint)) {
1735 return;
1736 }
1737 }
1738
1739 if (NULL != xmode && NULL != texs && NULL != colors) {
1740 if (!SkXfermode::IsMode(xmode, SkXfermode::kModulate_Mode)) {
1741 SkDebugf("Unsupported vertex-color/texture xfer mode.\n");
1742#if 0
1743 return
1744#endif
1745 }
1746 }
1747
1748 SkAutoSTMalloc<128, GrColor> convertedColors(0);
1749 if (NULL != colors) {
1750 // need to convert byte order and from non-PM to PM
1751 convertedColors.reset(vertexCount);
1752 for (int i = 0; i < vertexCount; ++i) {
1753 convertedColors[i] = SkColor2GrColor(colors[i]);
1754 }
1755 colors = convertedColors.get();
1756 }
1757 fContext->drawVertices(grPaint,
1758 gVertexMode2PrimitiveType[vmode],
1759 vertexCount,
1760 (GrPoint*) vertices,
1761 (GrPoint*) texs,
1762 colors,
1763 indices,
1764 indexCount);
1765}
1766
1767///////////////////////////////////////////////////////////////////////////////
1768
1769static void GlyphCacheAuxProc(void* data) {
1770 GrFontScaler* scaler = (GrFontScaler*)data;
1771 SkSafeUnref(scaler);
1772}
1773
1774static GrFontScaler* get_gr_font_scaler(SkGlyphCache* cache) {
1775 void* auxData;
1776 GrFontScaler* scaler = NULL;
1777 if (cache->getAuxProcData(GlyphCacheAuxProc, &auxData)) {
1778 scaler = (GrFontScaler*)auxData;
1779 }
1780 if (NULL == scaler) {
1781 scaler = SkNEW_ARGS(SkGrFontScaler, (cache));
1782 cache->setAuxProc(GlyphCacheAuxProc, scaler);
1783 }
1784 return scaler;
1785}
1786
1787static void SkGPU_Draw1Glyph(const SkDraw1Glyph& state,
1788 SkFixed fx, SkFixed fy,
1789 const SkGlyph& glyph) {
1790 SkASSERT(glyph.fWidth > 0 && glyph.fHeight > 0);
1791
1792 GrSkDrawProcs* procs = static_cast<GrSkDrawProcs*>(state.fDraw->fProcs);
1793
1794 if (NULL == procs->fFontScaler) {
1795 procs->fFontScaler = get_gr_font_scaler(state.fCache);
1796 }
1797
1798 procs->fTextContext->drawPackedGlyph(GrGlyph::Pack(glyph.getGlyphID(),
1799 glyph.getSubXFixed(),
1800 glyph.getSubYFixed()),
1801 SkFixedFloorToFixed(fx),
1802 SkFixedFloorToFixed(fy),
1803 procs->fFontScaler);
1804}
1805
1806SkDrawProcs* SkGpuDevice::initDrawForText(GrTextContext* context) {
1807
1808 // deferred allocation
1809 if (NULL == fDrawProcs) {
1810 fDrawProcs = SkNEW(GrSkDrawProcs);
1811 fDrawProcs->fD1GProc = SkGPU_Draw1Glyph;
1812 fDrawProcs->fContext = fContext;
skia.committer@gmail.com11a253b2013-11-12 07:02:05 +00001813 }
1814
1815 // init our (and GL's) state
1816 fDrawProcs->fTextContext = context;
1817 fDrawProcs->fFontScaler = NULL;
1818 return fDrawProcs;
1819}
1820
1821void SkGpuDevice::drawText(const SkDraw& draw, const void* text,
1822 size_t byteLength, SkScalar x, SkScalar y,
1823 const SkPaint& paint) {
1824 CHECK_SHOULD_DRAW(draw, false);
1825
commit-bot@chromium.org8128d8c2013-12-19 16:12:25 +00001826 if (SkDraw::ShouldDrawTextAsPaths(paint, fContext->getMatrix())) {
1827 draw.drawText_asPaths((const char*)text, byteLength, x, y, paint);
1828#if SK_DISTANCEFIELD_FONTS
1829 } else if (!paint.getRasterizer()) {
1830 GrPaint grPaint;
1831 if (!skPaint2GrPaintShader(this, paint, true, &grPaint)) {
1832 return;
1833 }
1834
1835 SkDEBUGCODE(this->validate();)
1836
commit-bot@chromium.orgcc40f062014-01-24 14:38:27 +00001837 SkAutoTDelete<GrTextContext> context(fTextContextManager->create(fContext, grPaint, paint));
1838 GrDistanceFieldTextContext* dfContext =
1839 static_cast<GrDistanceFieldTextContext*>(context.get());
commit-bot@chromium.org8128d8c2013-12-19 16:12:25 +00001840
commit-bot@chromium.orgcc40f062014-01-24 14:38:27 +00001841 SkAutoGlyphCache autoCache(dfContext->getSkPaint(), &this->fLeakyProperties, NULL);
commit-bot@chromium.org8128d8c2013-12-19 16:12:25 +00001842 SkGlyphCache* cache = autoCache.getCache();
1843 GrFontScaler* fontScaler = get_gr_font_scaler(cache);
1844
commit-bot@chromium.orgcc40f062014-01-24 14:38:27 +00001845 dfContext->drawText((const char *)text, byteLength, x, y, cache, fontScaler);
commit-bot@chromium.org8128d8c2013-12-19 16:12:25 +00001846#endif
skia.committer@gmail.com11a253b2013-11-12 07:02:05 +00001847 } else {
1848 SkDraw myDraw(draw);
1849
1850 GrPaint grPaint;
1851 if (!skPaint2GrPaintShader(this, paint, true, &grPaint)) {
1852 return;
1853 }
commit-bot@chromium.org8128d8c2013-12-19 16:12:25 +00001854
commit-bot@chromium.orgcc40f062014-01-24 14:38:27 +00001855 SkAutoTDelete<GrTextContext> context(fTextContextManager->create(fContext, grPaint, paint));
1856 myDraw.fProcs = this->initDrawForText(context.get());
commit-bot@chromium.org8128d8c2013-12-19 16:12:25 +00001857 this->INHERITED::drawText(myDraw, text, byteLength, x, y, paint);
skia.committer@gmail.com11a253b2013-11-12 07:02:05 +00001858 }
1859}
1860
1861void SkGpuDevice::drawPosText(const SkDraw& draw, const void* text,
1862 size_t byteLength, const SkScalar pos[],
1863 SkScalar constY, int scalarsPerPos,
1864 const SkPaint& paint) {
1865 CHECK_SHOULD_DRAW(draw, false);
1866
commit-bot@chromium.org8128d8c2013-12-19 16:12:25 +00001867 if (SkDraw::ShouldDrawTextAsPaths(paint, fContext->getMatrix())) {
skia.committer@gmail.com11a253b2013-11-12 07:02:05 +00001868 // this guy will just call our drawPath()
commit-bot@chromium.org8128d8c2013-12-19 16:12:25 +00001869 draw.drawPosText_asPaths((const char*)text, byteLength, pos, constY,
skia.committer@gmail.com11a253b2013-11-12 07:02:05 +00001870 scalarsPerPos, paint);
commit-bot@chromium.org8128d8c2013-12-19 16:12:25 +00001871#if SK_DISTANCEFIELD_FONTS
1872 } else if (!paint.getRasterizer()) {
1873 GrPaint grPaint;
1874 if (!skPaint2GrPaintShader(this, paint, true, &grPaint)) {
1875 return;
1876 }
1877
1878 SkDEBUGCODE(this->validate();)
1879
commit-bot@chromium.orgcc40f062014-01-24 14:38:27 +00001880 SkAutoTDelete<GrTextContext> context(fTextContextManager->create(fContext, grPaint, paint));
1881 GrDistanceFieldTextContext* dfContext =
1882 static_cast<GrDistanceFieldTextContext*>(context.get());
skia.committer@gmail.comd2ac07b2014-01-25 07:01:49 +00001883
commit-bot@chromium.orgcc40f062014-01-24 14:38:27 +00001884 SkAutoGlyphCache autoCache(dfContext->getSkPaint(), &this->fLeakyProperties, NULL);
commit-bot@chromium.org8128d8c2013-12-19 16:12:25 +00001885 SkGlyphCache* cache = autoCache.getCache();
1886 GrFontScaler* fontScaler = get_gr_font_scaler(cache);
skia.committer@gmail.comd2ac07b2014-01-25 07:01:49 +00001887
commit-bot@chromium.orgcc40f062014-01-24 14:38:27 +00001888 dfContext->drawPosText((const char *)text, byteLength, pos, constY, scalarsPerPos,
commit-bot@chromium.org8128d8c2013-12-19 16:12:25 +00001889 cache, fontScaler);
1890#endif
skia.committer@gmail.com11a253b2013-11-12 07:02:05 +00001891 } else {
1892 SkDraw myDraw(draw);
1893
1894 GrPaint grPaint;
1895 if (!skPaint2GrPaintShader(this, paint, true, &grPaint)) {
1896 return;
1897 }
commit-bot@chromium.orgcc40f062014-01-24 14:38:27 +00001898
1899 SkAutoTDelete<GrTextContext> context(fTextContextManager->create(fContext, grPaint, paint));
1900 myDraw.fProcs = this->initDrawForText(context.get());
commit-bot@chromium.org8128d8c2013-12-19 16:12:25 +00001901 this->INHERITED::drawPosText(myDraw, text, byteLength, pos, constY,
1902 scalarsPerPos, paint);
skia.committer@gmail.com11a253b2013-11-12 07:02:05 +00001903 }
1904}
1905
1906void SkGpuDevice::drawTextOnPath(const SkDraw& draw, const void* text,
1907 size_t len, const SkPath& path,
1908 const SkMatrix* m, const SkPaint& paint) {
1909 CHECK_SHOULD_DRAW(draw, false);
1910
1911 SkASSERT(draw.fDevice == this);
1912 draw.drawTextOnPath((const char*)text, len, path, m, paint);
1913}
1914
1915///////////////////////////////////////////////////////////////////////////////
1916
1917bool SkGpuDevice::filterTextFlags(const SkPaint& paint, TextFlags* flags) {
1918 if (!paint.isLCDRenderText()) {
1919 // we're cool with the paint as is
1920 return false;
1921 }
1922
1923 if (paint.getShader() ||
1924 paint.getXfermode() || // unless its srcover
1925 paint.getMaskFilter() ||
1926 paint.getRasterizer() ||
1927 paint.getColorFilter() ||
1928 paint.getPathEffect() ||
1929 paint.isFakeBoldText() ||
1930 paint.getStyle() != SkPaint::kFill_Style) {
1931 // turn off lcd
1932 flags->fFlags = paint.getFlags() & ~SkPaint::kLCDRenderText_Flag;
1933 flags->fHinting = paint.getHinting();
1934 return true;
1935 }
1936 // we're cool with the paint as is
1937 return false;
1938}
1939
1940void SkGpuDevice::flush() {
1941 DO_DEFERRED_CLEAR();
1942 fContext->resolveRenderTarget(fRenderTarget);
1943}
1944
1945///////////////////////////////////////////////////////////////////////////////
1946
1947SkBaseDevice* SkGpuDevice::onCreateCompatibleDevice(SkBitmap::Config config,
1948 int width, int height,
1949 bool isOpaque,
1950 Usage usage) {
1951 GrTextureDesc desc;
1952 desc.fConfig = fRenderTarget->config();
1953 desc.fFlags = kRenderTarget_GrTextureFlagBit;
1954 desc.fWidth = width;
1955 desc.fHeight = height;
1956 desc.fSampleCnt = fRenderTarget->numSamples();
1957
1958 SkAutoTUnref<GrTexture> texture;
1959 // Skia's convention is to only clear a device if it is non-opaque.
1960 bool needClear = !isOpaque;
1961
1962#if CACHE_COMPATIBLE_DEVICE_TEXTURES
1963 // layers are never draw in repeat modes, so we can request an approx
1964 // match and ignore any padding.
1965 const GrContext::ScratchTexMatch match = (kSaveLayer_Usage == usage) ?
1966 GrContext::kApprox_ScratchTexMatch :
1967 GrContext::kExact_ScratchTexMatch;
1968 texture.reset(fContext->lockAndRefScratchTexture(desc, match));
1969#else
1970 texture.reset(fContext->createUncachedTexture(desc, NULL, 0));
1971#endif
1972 if (NULL != texture.get()) {
1973 return SkNEW_ARGS(SkGpuDevice,(fContext, texture, needClear));
1974 } else {
1975 GrPrintf("---- failed to create compatible device texture [%d %d]\n", width, height);
1976 return NULL;
1977 }
1978}
1979
1980SkGpuDevice::SkGpuDevice(GrContext* context,
1981 GrTexture* texture,
1982 bool needClear)
1983 : SkBitmapDevice(make_bitmap(context, texture->asRenderTarget())) {
1984
1985 SkASSERT(texture && texture->asRenderTarget());
1986 // This constructor is called from onCreateCompatibleDevice. It has locked the RT in the texture
1987 // cache. We pass true for the third argument so that it will get unlocked.
1988 this->initFromRenderTarget(context, texture->asRenderTarget(), true);
1989 fNeedClear = needClear;
1990}