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