SkGpuDevice.cpp 70 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704
  1. /*
  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. #include "src/gpu/SkGpuDevice.h"
  8. #include "include/core/SkImageFilter.h"
  9. #include "include/core/SkPathEffect.h"
  10. #include "include/core/SkPicture.h"
  11. #include "include/core/SkSurface.h"
  12. #include "include/core/SkVertices.h"
  13. #include "include/gpu/GrContext.h"
  14. #include "include/private/SkImageInfoPriv.h"
  15. #include "include/private/SkShadowFlags.h"
  16. #include "include/private/SkTo.h"
  17. #include "src/core/SkCanvasPriv.h"
  18. #include "src/core/SkClipStack.h"
  19. #include "src/core/SkDraw.h"
  20. #include "src/core/SkImageFilterCache.h"
  21. #include "src/core/SkLatticeIter.h"
  22. #include "src/core/SkMakeUnique.h"
  23. #include "src/core/SkPictureData.h"
  24. #include "src/core/SkRRectPriv.h"
  25. #include "src/core/SkRasterClip.h"
  26. #include "src/core/SkRecord.h"
  27. #include "src/core/SkSpecialImage.h"
  28. #include "src/core/SkStroke.h"
  29. #include "src/core/SkTLazy.h"
  30. #include "src/core/SkVertState.h"
  31. #include "src/core/SkWritePixelsRec.h"
  32. #include "src/gpu/GrBitmapTextureMaker.h"
  33. #include "src/gpu/GrBlurUtils.h"
  34. #include "src/gpu/GrContextPriv.h"
  35. #include "src/gpu/GrGpu.h"
  36. #include "src/gpu/GrImageTextureMaker.h"
  37. #include "src/gpu/GrRenderTargetContextPriv.h"
  38. #include "src/gpu/GrStyle.h"
  39. #include "src/gpu/GrSurfaceProxyPriv.h"
  40. #include "src/gpu/GrTextureAdjuster.h"
  41. #include "src/gpu/GrTracing.h"
  42. #include "src/gpu/SkGr.h"
  43. #include "src/gpu/effects/GrBicubicEffect.h"
  44. #include "src/gpu/effects/GrTextureDomain.h"
  45. #include "src/gpu/geometry/GrShape.h"
  46. #include "src/gpu/text/GrTextTarget.h"
  47. #include "src/image/SkImage_Base.h"
  48. #include "src/image/SkReadPixelsRec.h"
  49. #include "src/image/SkSurface_Gpu.h"
  50. #include "src/utils/SkUTF.h"
  51. #define ASSERT_SINGLE_OWNER \
  52. SkDEBUGCODE(GrSingleOwner::AutoEnforce debug_SingleOwner(fContext->priv().singleOwner());)
  53. ///////////////////////////////////////////////////////////////////////////////
  54. /** Checks that the alpha type is legal and gets constructor flags. Returns false if device creation
  55. should fail. */
  56. bool SkGpuDevice::CheckAlphaTypeAndGetFlags(
  57. const SkImageInfo* info, SkGpuDevice::InitContents init, unsigned* flags) {
  58. *flags = 0;
  59. if (info) {
  60. switch (info->alphaType()) {
  61. case kPremul_SkAlphaType:
  62. break;
  63. case kOpaque_SkAlphaType:
  64. *flags |= SkGpuDevice::kIsOpaque_Flag;
  65. break;
  66. default: // If it is unpremul or unknown don't try to render
  67. return false;
  68. }
  69. }
  70. if (kClear_InitContents == init) {
  71. *flags |= kNeedClear_Flag;
  72. }
  73. return true;
  74. }
  75. sk_sp<SkGpuDevice> SkGpuDevice::Make(GrContext* context,
  76. sk_sp<GrRenderTargetContext> renderTargetContext,
  77. int width, int height,
  78. InitContents init) {
  79. if (!renderTargetContext || context->priv().abandoned()) {
  80. return nullptr;
  81. }
  82. unsigned flags;
  83. if (!CheckAlphaTypeAndGetFlags(nullptr, init, &flags)) {
  84. return nullptr;
  85. }
  86. return sk_sp<SkGpuDevice>(new SkGpuDevice(context, std::move(renderTargetContext),
  87. width, height, flags));
  88. }
  89. sk_sp<SkGpuDevice> SkGpuDevice::Make(GrContext* context, SkBudgeted budgeted,
  90. const SkImageInfo& info, int sampleCount,
  91. GrSurfaceOrigin origin, const SkSurfaceProps* props,
  92. GrMipMapped mipMapped, InitContents init) {
  93. unsigned flags;
  94. if (!CheckAlphaTypeAndGetFlags(&info, init, &flags)) {
  95. return nullptr;
  96. }
  97. sk_sp<GrRenderTargetContext> renderTargetContext(MakeRenderTargetContext(context, budgeted,
  98. info, sampleCount,
  99. origin, props,
  100. mipMapped));
  101. if (!renderTargetContext) {
  102. return nullptr;
  103. }
  104. return sk_sp<SkGpuDevice>(new SkGpuDevice(context, std::move(renderTargetContext),
  105. info.width(), info.height(), flags));
  106. }
  107. static SkImageInfo make_info(GrRenderTargetContext* context, int w, int h, bool opaque) {
  108. SkColorType colorType = GrColorTypeToSkColorType(context->colorSpaceInfo().colorType());
  109. return SkImageInfo::Make(w, h, colorType, opaque ? kOpaque_SkAlphaType : kPremul_SkAlphaType,
  110. context->colorSpaceInfo().refColorSpace());
  111. }
  112. SkGpuDevice::SkGpuDevice(GrContext* context, sk_sp<GrRenderTargetContext> renderTargetContext,
  113. int width, int height, unsigned flags)
  114. : INHERITED(make_info(renderTargetContext.get(), width, height,
  115. SkToBool(flags & kIsOpaque_Flag)), renderTargetContext->surfaceProps())
  116. , fContext(SkRef(context))
  117. , fRenderTargetContext(std::move(renderTargetContext))
  118. {
  119. fSize.set(width, height);
  120. if (flags & kNeedClear_Flag) {
  121. this->clearAll();
  122. }
  123. }
  124. sk_sp<GrRenderTargetContext> SkGpuDevice::MakeRenderTargetContext(
  125. GrContext* context,
  126. SkBudgeted budgeted,
  127. const SkImageInfo& origInfo,
  128. int sampleCount,
  129. GrSurfaceOrigin origin,
  130. const SkSurfaceProps* surfaceProps,
  131. GrMipMapped mipMapped) {
  132. if (kUnknown_SkColorType == origInfo.colorType() ||
  133. origInfo.width() < 0 || origInfo.height() < 0) {
  134. return nullptr;
  135. }
  136. if (!context) {
  137. return nullptr;
  138. }
  139. // This method is used to create SkGpuDevice's for SkSurface_Gpus. In this case
  140. // they need to be exact.
  141. return context->priv().makeDeferredRenderTargetContext(
  142. SkBackingFit::kExact, origInfo.width(), origInfo.height(),
  143. SkColorTypeToGrColorType(origInfo.colorType()), origInfo.refColorSpace(), sampleCount,
  144. mipMapped, origin, surfaceProps, budgeted);
  145. }
  146. sk_sp<SkSpecialImage> SkGpuDevice::filterTexture(SkSpecialImage* srcImg,
  147. int left, int top,
  148. SkIPoint* offset,
  149. const SkImageFilter* filter) {
  150. SkASSERT(srcImg->isTextureBacked());
  151. SkASSERT(filter);
  152. SkMatrix matrix = this->ctm();
  153. matrix.postTranslate(SkIntToScalar(-left), SkIntToScalar(-top));
  154. const SkIRect clipBounds = this->devClipBounds().makeOffset(-left, -top);
  155. sk_sp<SkImageFilterCache> cache(this->getImageFilterCache());
  156. SkColorType colorType =
  157. GrColorTypeToSkColorType(fRenderTargetContext->colorSpaceInfo().colorType());
  158. if (colorType == kUnknown_SkColorType) {
  159. colorType = kRGBA_8888_SkColorType;
  160. }
  161. SkImageFilter::OutputProperties outputProperties(
  162. colorType, fRenderTargetContext->colorSpaceInfo().colorSpace());
  163. SkImageFilter::Context ctx(matrix, clipBounds, cache.get(), outputProperties);
  164. return filter->filterImage(srcImg, ctx, offset);
  165. }
  166. ///////////////////////////////////////////////////////////////////////////////
  167. bool SkGpuDevice::onReadPixels(const SkPixmap& pm, int x, int y) {
  168. ASSERT_SINGLE_OWNER
  169. if (!SkImageInfoValidConversion(pm.info(), this->imageInfo())) {
  170. return false;
  171. }
  172. return fRenderTargetContext->readPixels(pm.info(), pm.writable_addr(), pm.rowBytes(), {x, y});
  173. }
  174. bool SkGpuDevice::onWritePixels(const SkPixmap& pm, int x, int y) {
  175. ASSERT_SINGLE_OWNER
  176. if (!SkImageInfoValidConversion(this->imageInfo(), pm.info())) {
  177. return false;
  178. }
  179. return fRenderTargetContext->writePixels(pm.info(), pm.addr(), pm.rowBytes(), {x, y});
  180. }
  181. bool SkGpuDevice::onAccessPixels(SkPixmap* pmap) {
  182. ASSERT_SINGLE_OWNER
  183. return false;
  184. }
  185. GrRenderTargetContext* SkGpuDevice::accessRenderTargetContext() {
  186. ASSERT_SINGLE_OWNER
  187. return fRenderTargetContext.get();
  188. }
  189. void SkGpuDevice::clearAll() {
  190. ASSERT_SINGLE_OWNER
  191. GR_CREATE_TRACE_MARKER_CONTEXT("SkGpuDevice", "clearAll", fContext.get());
  192. SkIRect rect = SkIRect::MakeWH(this->width(), this->height());
  193. fRenderTargetContext->clear(&rect, SK_PMColor4fTRANSPARENT,
  194. GrRenderTargetContext::CanClearFullscreen::kYes);
  195. }
  196. void SkGpuDevice::replaceRenderTargetContext(sk_sp<GrRenderTargetContext> rtc,
  197. bool shouldRetainContent) {
  198. SkASSERT(rtc->width() == this->width());
  199. SkASSERT(rtc->height() == this->height());
  200. SkASSERT(rtc->numSamples() == fRenderTargetContext->numSamples());
  201. SkASSERT(rtc->asSurfaceProxy()->priv().isExact());
  202. if (shouldRetainContent) {
  203. if (this->context()->abandoned()) {
  204. return;
  205. }
  206. SkASSERT(fRenderTargetContext->asTextureProxy());
  207. SkAssertResult(rtc->blitTexture(fRenderTargetContext->asTextureProxy(),
  208. SkIRect::MakeWH(this->width(), this->height()),
  209. SkIPoint::Make(0,0)));
  210. }
  211. fRenderTargetContext = std::move(rtc);
  212. }
  213. void SkGpuDevice::replaceRenderTargetContext(bool shouldRetainContent) {
  214. ASSERT_SINGLE_OWNER
  215. SkBudgeted budgeted = fRenderTargetContext->priv().isBudgeted();
  216. // This entry point is used by SkSurface_Gpu::onCopyOnWrite so it must create a
  217. // kExact-backed render target context.
  218. sk_sp<GrRenderTargetContext> newRTC(MakeRenderTargetContext(
  219. this->context(),
  220. budgeted,
  221. this->imageInfo(),
  222. fRenderTargetContext->numSamples(),
  223. fRenderTargetContext->origin(),
  224. &this->surfaceProps(),
  225. fRenderTargetContext->mipMapped()));
  226. if (!newRTC) {
  227. return;
  228. }
  229. this->replaceRenderTargetContext(std::move(newRTC), shouldRetainContent);
  230. }
  231. ///////////////////////////////////////////////////////////////////////////////
  232. void SkGpuDevice::drawPaint(const SkPaint& paint) {
  233. ASSERT_SINGLE_OWNER
  234. GR_CREATE_TRACE_MARKER_CONTEXT("SkGpuDevice", "drawPaint", fContext.get());
  235. GrPaint grPaint;
  236. if (!SkPaintToGrPaint(this->context(), fRenderTargetContext->colorSpaceInfo(), paint,
  237. this->ctm(), &grPaint)) {
  238. return;
  239. }
  240. fRenderTargetContext->drawPaint(this->clip(), std::move(grPaint), this->ctm());
  241. }
  242. static inline GrPrimitiveType point_mode_to_primitive_type(SkCanvas::PointMode mode) {
  243. switch (mode) {
  244. case SkCanvas::kPoints_PointMode:
  245. return GrPrimitiveType::kPoints;
  246. case SkCanvas::kLines_PointMode:
  247. return GrPrimitiveType::kLines;
  248. case SkCanvas::kPolygon_PointMode:
  249. return GrPrimitiveType::kLineStrip;
  250. }
  251. SK_ABORT("Unexpected mode");
  252. return GrPrimitiveType::kPoints;
  253. }
  254. void SkGpuDevice::drawPoints(SkCanvas::PointMode mode,
  255. size_t count, const SkPoint pts[], const SkPaint& paint) {
  256. ASSERT_SINGLE_OWNER
  257. GR_CREATE_TRACE_MARKER_CONTEXT("SkGpuDevice", "drawPoints", fContext.get());
  258. SkScalar width = paint.getStrokeWidth();
  259. if (width < 0) {
  260. return;
  261. }
  262. if (paint.getPathEffect() && 2 == count && SkCanvas::kLines_PointMode == mode) {
  263. GrStyle style(paint, SkPaint::kStroke_Style);
  264. GrPaint grPaint;
  265. if (!SkPaintToGrPaint(this->context(), fRenderTargetContext->colorSpaceInfo(), paint,
  266. this->ctm(), &grPaint)) {
  267. return;
  268. }
  269. SkPath path;
  270. path.setIsVolatile(true);
  271. path.moveTo(pts[0]);
  272. path.lineTo(pts[1]);
  273. fRenderTargetContext->drawPath(this->clip(), std::move(grPaint), GrAA(paint.isAntiAlias()),
  274. this->ctm(), path, style);
  275. return;
  276. }
  277. SkScalar scales[2];
  278. bool isHairline = (0 == width) || (1 == width && this->ctm().getMinMaxScales(scales) &&
  279. SkScalarNearlyEqual(scales[0], 1.f) &&
  280. SkScalarNearlyEqual(scales[1], 1.f));
  281. // we only handle non-antialiased hairlines and paints without path effects or mask filters,
  282. // else we let the SkDraw call our drawPath()
  283. if (!isHairline || paint.getPathEffect() || paint.getMaskFilter() || paint.isAntiAlias()) {
  284. SkRasterClip rc(this->devClipBounds());
  285. SkDraw draw;
  286. draw.fDst = SkPixmap(SkImageInfo::MakeUnknown(this->width(), this->height()), nullptr, 0);
  287. draw.fMatrix = &this->ctm();
  288. draw.fRC = &rc;
  289. draw.drawPoints(mode, count, pts, paint, this);
  290. return;
  291. }
  292. GrPrimitiveType primitiveType = point_mode_to_primitive_type(mode);
  293. const SkMatrix* viewMatrix = &this->ctm();
  294. #ifdef SK_BUILD_FOR_ANDROID_FRAMEWORK
  295. // This offsetting in device space matches the expectations of the Android framework for non-AA
  296. // points and lines.
  297. SkMatrix tempMatrix;
  298. if (GrIsPrimTypeLines(primitiveType) || GrPrimitiveType::kPoints == primitiveType) {
  299. tempMatrix = *viewMatrix;
  300. static const SkScalar kOffset = 0.063f; // Just greater than 1/16.
  301. tempMatrix.postTranslate(kOffset, kOffset);
  302. viewMatrix = &tempMatrix;
  303. }
  304. #endif
  305. GrPaint grPaint;
  306. if (!SkPaintToGrPaint(this->context(), fRenderTargetContext->colorSpaceInfo(), paint,
  307. *viewMatrix, &grPaint)) {
  308. return;
  309. }
  310. static constexpr SkVertices::VertexMode kIgnoredMode = SkVertices::kTriangles_VertexMode;
  311. sk_sp<SkVertices> vertices = SkVertices::MakeCopy(kIgnoredMode, SkToS32(count), pts, nullptr,
  312. nullptr);
  313. fRenderTargetContext->drawVertices(this->clip(), std::move(grPaint), *viewMatrix,
  314. std::move(vertices), nullptr, 0, &primitiveType);
  315. }
  316. ///////////////////////////////////////////////////////////////////////////////
  317. void SkGpuDevice::drawRect(const SkRect& rect, const SkPaint& paint) {
  318. ASSERT_SINGLE_OWNER
  319. GR_CREATE_TRACE_MARKER_CONTEXT("SkGpuDevice", "drawRect", fContext.get());
  320. GrStyle style(paint);
  321. // A couple reasons we might need to call drawPath.
  322. if (paint.getMaskFilter() || paint.getPathEffect()) {
  323. GrShape shape(rect, style);
  324. GrBlurUtils::drawShapeWithMaskFilter(fContext.get(), fRenderTargetContext.get(),
  325. this->clip(), paint, this->ctm(), shape);
  326. return;
  327. }
  328. GrPaint grPaint;
  329. if (!SkPaintToGrPaint(this->context(), fRenderTargetContext->colorSpaceInfo(), paint,
  330. this->ctm(), &grPaint)) {
  331. return;
  332. }
  333. fRenderTargetContext->drawRect(this->clip(), std::move(grPaint), GrAA(paint.isAntiAlias()),
  334. this->ctm(), rect, &style);
  335. }
  336. void SkGpuDevice::drawEdgeAAQuad(const SkRect& rect, const SkPoint clip[4],
  337. SkCanvas::QuadAAFlags aaFlags, SkColor color, SkBlendMode mode) {
  338. ASSERT_SINGLE_OWNER
  339. GR_CREATE_TRACE_MARKER_CONTEXT("SkGpuDevice", "drawEdgeAAQuad", fContext.get());
  340. SkPMColor4f dstColor = SkColor4fPrepForDst(SkColor4f::FromColor(color),
  341. fRenderTargetContext->colorSpaceInfo())
  342. .premul();
  343. GrPaint grPaint;
  344. grPaint.setColor4f(dstColor);
  345. if (mode != SkBlendMode::kSrcOver) {
  346. grPaint.setXPFactory(SkBlendMode_AsXPFactory(mode));
  347. }
  348. // This is exclusively meant for tiling operations, so keep AA enabled to handle MSAA seaming
  349. GrQuadAAFlags grAA = SkToGrQuadAAFlags(aaFlags);
  350. if (clip) {
  351. // Use fillQuadWithEdgeAA
  352. fRenderTargetContext->fillQuadWithEdgeAA(this->clip(), std::move(grPaint), GrAA::kYes, grAA,
  353. this->ctm(), clip, nullptr);
  354. } else {
  355. // Use fillRectWithEdgeAA to preserve mathematical properties of dst being rectangular
  356. fRenderTargetContext->fillRectWithEdgeAA(this->clip(), std::move(grPaint), GrAA::kYes, grAA,
  357. this->ctm(), rect);
  358. }
  359. }
  360. ///////////////////////////////////////////////////////////////////////////////
  361. void SkGpuDevice::drawRRect(const SkRRect& rrect, const SkPaint& paint) {
  362. ASSERT_SINGLE_OWNER
  363. GR_CREATE_TRACE_MARKER_CONTEXT("SkGpuDevice", "drawRRect", fContext.get());
  364. SkMaskFilterBase* mf = as_MFB(paint.getMaskFilter());
  365. if (mf) {
  366. if (mf->hasFragmentProcessor()) {
  367. mf = nullptr; // already handled in SkPaintToGrPaint
  368. }
  369. }
  370. GrStyle style(paint);
  371. if (mf || style.pathEffect()) {
  372. // A path effect will presumably transform this rrect into something else.
  373. GrShape shape(rrect, style);
  374. GrBlurUtils::drawShapeWithMaskFilter(fContext.get(), fRenderTargetContext.get(),
  375. this->clip(), paint, this->ctm(), shape);
  376. return;
  377. }
  378. SkASSERT(!style.pathEffect());
  379. GrPaint grPaint;
  380. if (!SkPaintToGrPaint(this->context(), fRenderTargetContext->colorSpaceInfo(), paint,
  381. this->ctm(), &grPaint)) {
  382. return;
  383. }
  384. fRenderTargetContext->drawRRect(this->clip(), std::move(grPaint), GrAA(paint.isAntiAlias()),
  385. this->ctm(), rrect, style);
  386. }
  387. void SkGpuDevice::drawDRRect(const SkRRect& outer, const SkRRect& inner, const SkPaint& paint) {
  388. ASSERT_SINGLE_OWNER
  389. GR_CREATE_TRACE_MARKER_CONTEXT("SkGpuDevice", "drawDRRect", fContext.get());
  390. if (outer.isEmpty()) {
  391. return;
  392. }
  393. if (inner.isEmpty()) {
  394. return this->drawRRect(outer, paint);
  395. }
  396. SkStrokeRec stroke(paint);
  397. if (stroke.isFillStyle() && !paint.getMaskFilter() && !paint.getPathEffect()) {
  398. GrPaint grPaint;
  399. if (!SkPaintToGrPaint(this->context(), fRenderTargetContext->colorSpaceInfo(), paint,
  400. this->ctm(), &grPaint)) {
  401. return;
  402. }
  403. fRenderTargetContext->drawDRRect(this->clip(), std::move(grPaint),
  404. GrAA(paint.isAntiAlias()), this->ctm(), outer, inner);
  405. return;
  406. }
  407. SkPath path;
  408. path.setIsVolatile(true);
  409. path.addRRect(outer);
  410. path.addRRect(inner);
  411. path.setFillType(SkPath::kEvenOdd_FillType);
  412. // TODO: We are losing the possible mutability of the path here but this should probably be
  413. // fixed by upgrading GrShape to handle DRRects.
  414. GrShape shape(path, paint);
  415. GrBlurUtils::drawShapeWithMaskFilter(fContext.get(), fRenderTargetContext.get(), this->clip(),
  416. paint, this->ctm(), shape);
  417. }
  418. /////////////////////////////////////////////////////////////////////////////
  419. void SkGpuDevice::drawRegion(const SkRegion& region, const SkPaint& paint) {
  420. if (paint.getMaskFilter()) {
  421. SkPath path;
  422. region.getBoundaryPath(&path);
  423. path.setIsVolatile(true);
  424. return this->drawPath(path, paint, true);
  425. }
  426. GrPaint grPaint;
  427. if (!SkPaintToGrPaint(this->context(), fRenderTargetContext->colorSpaceInfo(), paint,
  428. this->ctm(), &grPaint)) {
  429. return;
  430. }
  431. fRenderTargetContext->drawRegion(this->clip(), std::move(grPaint), GrAA(paint.isAntiAlias()),
  432. this->ctm(), region, GrStyle(paint));
  433. }
  434. void SkGpuDevice::drawOval(const SkRect& oval, const SkPaint& paint) {
  435. ASSERT_SINGLE_OWNER
  436. GR_CREATE_TRACE_MARKER_CONTEXT("SkGpuDevice", "drawOval", fContext.get());
  437. if (paint.getMaskFilter()) {
  438. // The RRect path can handle special case blurring
  439. SkRRect rr = SkRRect::MakeOval(oval);
  440. return this->drawRRect(rr, paint);
  441. }
  442. GrPaint grPaint;
  443. if (!SkPaintToGrPaint(this->context(), fRenderTargetContext->colorSpaceInfo(), paint,
  444. this->ctm(), &grPaint)) {
  445. return;
  446. }
  447. fRenderTargetContext->drawOval(this->clip(), std::move(grPaint), GrAA(paint.isAntiAlias()),
  448. this->ctm(), oval, GrStyle(paint));
  449. }
  450. void SkGpuDevice::drawArc(const SkRect& oval, SkScalar startAngle,
  451. SkScalar sweepAngle, bool useCenter, const SkPaint& paint) {
  452. ASSERT_SINGLE_OWNER
  453. GR_CREATE_TRACE_MARKER_CONTEXT("SkGpuDevice", "drawArc", fContext.get());
  454. if (paint.getMaskFilter()) {
  455. this->INHERITED::drawArc(oval, startAngle, sweepAngle, useCenter, paint);
  456. return;
  457. }
  458. GrPaint grPaint;
  459. if (!SkPaintToGrPaint(this->context(), fRenderTargetContext->colorSpaceInfo(), paint,
  460. this->ctm(), &grPaint)) {
  461. return;
  462. }
  463. fRenderTargetContext->drawArc(this->clip(), std::move(grPaint), GrAA(paint.isAntiAlias()),
  464. this->ctm(), oval, startAngle, sweepAngle, useCenter,
  465. GrStyle(paint));
  466. }
  467. #include "include/core/SkMaskFilter.h"
  468. ///////////////////////////////////////////////////////////////////////////////
  469. void SkGpuDevice::drawStrokedLine(const SkPoint points[2],
  470. const SkPaint& origPaint) {
  471. ASSERT_SINGLE_OWNER
  472. GR_CREATE_TRACE_MARKER_CONTEXT("SkGpuDevice", "drawStrokedLine", fContext.get());
  473. // Adding support for round capping would require a
  474. // GrRenderTargetContext::fillRRectWithLocalMatrix entry point
  475. SkASSERT(SkPaint::kRound_Cap != origPaint.getStrokeCap());
  476. SkASSERT(SkPaint::kStroke_Style == origPaint.getStyle());
  477. SkASSERT(!origPaint.getPathEffect());
  478. SkASSERT(!origPaint.getMaskFilter());
  479. const SkScalar halfWidth = 0.5f * origPaint.getStrokeWidth();
  480. SkASSERT(halfWidth > 0);
  481. SkVector v = points[1] - points[0];
  482. SkScalar length = SkPoint::Normalize(&v);
  483. if (!length) {
  484. v.fX = 1.0f;
  485. v.fY = 0.0f;
  486. }
  487. SkPaint newPaint(origPaint);
  488. newPaint.setStyle(SkPaint::kFill_Style);
  489. SkScalar xtraLength = 0.0f;
  490. if (SkPaint::kButt_Cap != origPaint.getStrokeCap()) {
  491. xtraLength = halfWidth;
  492. }
  493. SkPoint mid = points[0] + points[1];
  494. mid.scale(0.5f);
  495. SkRect rect = SkRect::MakeLTRB(mid.fX-halfWidth, mid.fY - 0.5f*length - xtraLength,
  496. mid.fX+halfWidth, mid.fY + 0.5f*length + xtraLength);
  497. SkMatrix m;
  498. m.setSinCos(v.fX, -v.fY, mid.fX, mid.fY);
  499. SkMatrix local = m;
  500. m.postConcat(this->ctm());
  501. GrPaint grPaint;
  502. if (!SkPaintToGrPaint(this->context(), fRenderTargetContext->colorSpaceInfo(), newPaint, m,
  503. &grPaint)) {
  504. return;
  505. }
  506. fRenderTargetContext->fillRectWithLocalMatrix(
  507. this->clip(), std::move(grPaint), GrAA(newPaint.isAntiAlias()), m, rect, local);
  508. }
  509. void SkGpuDevice::drawPath(const SkPath& origSrcPath, const SkPaint& paint, bool pathIsMutable) {
  510. ASSERT_SINGLE_OWNER
  511. if (!origSrcPath.isInverseFillType() && !paint.getPathEffect()) {
  512. SkPoint points[2];
  513. if (SkPaint::kStroke_Style == paint.getStyle() && paint.getStrokeWidth() > 0 &&
  514. !paint.getMaskFilter() && SkPaint::kRound_Cap != paint.getStrokeCap() &&
  515. this->ctm().preservesRightAngles() && origSrcPath.isLine(points)) {
  516. // Path-based stroking looks better for thin rects
  517. SkScalar strokeWidth = this->ctm().getMaxScale() * paint.getStrokeWidth();
  518. if (strokeWidth >= 1.0f) {
  519. // Round capping support is currently disabled b.c. it would require a RRect
  520. // GrDrawOp that takes a localMatrix.
  521. this->drawStrokedLine(points, paint);
  522. return;
  523. }
  524. }
  525. }
  526. GR_CREATE_TRACE_MARKER_CONTEXT("SkGpuDevice", "drawPath", fContext.get());
  527. if (!paint.getMaskFilter()) {
  528. GrPaint grPaint;
  529. if (!SkPaintToGrPaint(this->context(), fRenderTargetContext->colorSpaceInfo(), paint,
  530. this->ctm(), &grPaint)) {
  531. return;
  532. }
  533. fRenderTargetContext->drawPath(this->clip(), std::move(grPaint), GrAA(paint.isAntiAlias()),
  534. this->ctm(), origSrcPath, GrStyle(paint));
  535. return;
  536. }
  537. // TODO: losing possible mutability of 'origSrcPath' here
  538. GrShape shape(origSrcPath, paint);
  539. GrBlurUtils::drawShapeWithMaskFilter(fContext.get(), fRenderTargetContext.get(), this->clip(),
  540. paint, this->ctm(), shape);
  541. }
  542. static const int kBmpSmallTileSize = 1 << 10;
  543. static inline int get_tile_count(const SkIRect& srcRect, int tileSize) {
  544. int tilesX = (srcRect.fRight / tileSize) - (srcRect.fLeft / tileSize) + 1;
  545. int tilesY = (srcRect.fBottom / tileSize) - (srcRect.fTop / tileSize) + 1;
  546. return tilesX * tilesY;
  547. }
  548. static int determine_tile_size(const SkIRect& src, int maxTileSize) {
  549. if (maxTileSize <= kBmpSmallTileSize) {
  550. return maxTileSize;
  551. }
  552. size_t maxTileTotalTileSize = get_tile_count(src, maxTileSize);
  553. size_t smallTotalTileSize = get_tile_count(src, kBmpSmallTileSize);
  554. maxTileTotalTileSize *= maxTileSize * maxTileSize;
  555. smallTotalTileSize *= kBmpSmallTileSize * kBmpSmallTileSize;
  556. if (maxTileTotalTileSize > 2 * smallTotalTileSize) {
  557. return kBmpSmallTileSize;
  558. } else {
  559. return maxTileSize;
  560. }
  561. }
  562. // Given a bitmap, an optional src rect, and a context with a clip and matrix determine what
  563. // pixels from the bitmap are necessary.
  564. static void determine_clipped_src_rect(int width, int height,
  565. const GrClip& clip,
  566. const SkMatrix& viewMatrix,
  567. const SkMatrix& srcToDstRect,
  568. const SkISize& imageSize,
  569. const SkRect* srcRectPtr,
  570. SkIRect* clippedSrcIRect) {
  571. clip.getConservativeBounds(width, height, clippedSrcIRect, nullptr);
  572. SkMatrix inv = SkMatrix::Concat(viewMatrix, srcToDstRect);
  573. if (!inv.invert(&inv)) {
  574. clippedSrcIRect->setEmpty();
  575. return;
  576. }
  577. SkRect clippedSrcRect = SkRect::Make(*clippedSrcIRect);
  578. inv.mapRect(&clippedSrcRect);
  579. if (srcRectPtr) {
  580. if (!clippedSrcRect.intersect(*srcRectPtr)) {
  581. clippedSrcIRect->setEmpty();
  582. return;
  583. }
  584. }
  585. clippedSrcRect.roundOut(clippedSrcIRect);
  586. SkIRect bmpBounds = SkIRect::MakeSize(imageSize);
  587. if (!clippedSrcIRect->intersect(bmpBounds)) {
  588. clippedSrcIRect->setEmpty();
  589. }
  590. }
  591. const GrCaps* SkGpuDevice::caps() const {
  592. return fContext->priv().caps();
  593. }
  594. bool SkGpuDevice::shouldTileImageID(uint32_t imageID,
  595. const SkIRect& imageRect,
  596. const SkMatrix& viewMatrix,
  597. const SkMatrix& srcToDstRect,
  598. const GrSamplerState& params,
  599. const SkRect* srcRectPtr,
  600. int maxTileSize,
  601. int* tileSize,
  602. SkIRect* clippedSubset) const {
  603. ASSERT_SINGLE_OWNER
  604. // if it's larger than the max tile size, then we have no choice but tiling.
  605. if (imageRect.width() > maxTileSize || imageRect.height() > maxTileSize) {
  606. determine_clipped_src_rect(fRenderTargetContext->width(), fRenderTargetContext->height(),
  607. this->clip(), viewMatrix, srcToDstRect, imageRect.size(),
  608. srcRectPtr, clippedSubset);
  609. *tileSize = determine_tile_size(*clippedSubset, maxTileSize);
  610. return true;
  611. }
  612. // If the image would only produce 4 tiles of the smaller size, don't bother tiling it.
  613. const size_t area = imageRect.width() * imageRect.height();
  614. if (area < 4 * kBmpSmallTileSize * kBmpSmallTileSize) {
  615. return false;
  616. }
  617. // At this point we know we could do the draw by uploading the entire bitmap
  618. // as a texture. However, if the texture would be large compared to the
  619. // cache size and we don't require most of it for this draw then tile to
  620. // reduce the amount of upload and cache spill.
  621. // assumption here is that sw bitmap size is a good proxy for its size as
  622. // a texture
  623. size_t bmpSize = area * sizeof(SkPMColor); // assume 32bit pixels
  624. size_t cacheSize;
  625. fContext->getResourceCacheLimits(nullptr, &cacheSize);
  626. if (bmpSize < cacheSize / 2) {
  627. return false;
  628. }
  629. // Figure out how much of the src we will need based on the src rect and clipping. Reject if
  630. // tiling memory savings would be < 50%.
  631. determine_clipped_src_rect(fRenderTargetContext->width(), fRenderTargetContext->height(),
  632. this->clip(), viewMatrix, srcToDstRect, imageRect.size(), srcRectPtr,
  633. clippedSubset);
  634. *tileSize = kBmpSmallTileSize; // already know whole bitmap fits in one max sized tile.
  635. size_t usedTileBytes = get_tile_count(*clippedSubset, kBmpSmallTileSize) *
  636. kBmpSmallTileSize * kBmpSmallTileSize *
  637. sizeof(SkPMColor); // assume 32bit pixels;
  638. return usedTileBytes * 2 < bmpSize;
  639. }
  640. bool SkGpuDevice::shouldTileImage(const SkImage* image, const SkRect* srcRectPtr,
  641. SkCanvas::SrcRectConstraint constraint, SkFilterQuality quality,
  642. const SkMatrix& viewMatrix,
  643. const SkMatrix& srcToDstRect) const {
  644. ASSERT_SINGLE_OWNER
  645. // If image is explicitly texture backed then we shouldn't get here.
  646. SkASSERT(!image->isTextureBacked());
  647. GrSamplerState samplerState;
  648. bool doBicubic;
  649. GrSamplerState::Filter textureFilterMode = GrSkFilterQualityToGrFilterMode(
  650. quality, viewMatrix, srcToDstRect,
  651. fContext->priv().options().fSharpenMipmappedTextures, &doBicubic);
  652. int tileFilterPad;
  653. if (doBicubic) {
  654. tileFilterPad = GrBicubicEffect::kFilterTexelPad;
  655. } else if (GrSamplerState::Filter::kNearest == textureFilterMode) {
  656. tileFilterPad = 0;
  657. } else {
  658. tileFilterPad = 1;
  659. }
  660. samplerState.setFilterMode(textureFilterMode);
  661. int maxTileSize = this->caps()->maxTileSize() - 2 * tileFilterPad;
  662. // these are output, which we safely ignore, as we just want to know the predicate
  663. int outTileSize;
  664. SkIRect outClippedSrcRect;
  665. return this->shouldTileImageID(image->unique(), image->bounds(), viewMatrix, srcToDstRect,
  666. samplerState, srcRectPtr, maxTileSize, &outTileSize,
  667. &outClippedSrcRect);
  668. }
  669. // This method outsets 'iRect' by 'outset' all around and then clamps its extents to
  670. // 'clamp'. 'offset' is adjusted to remain positioned over the top-left corner
  671. // of 'iRect' for all possible outsets/clamps.
  672. static inline void clamped_outset_with_offset(SkIRect* iRect,
  673. int outset,
  674. SkPoint* offset,
  675. const SkIRect& clamp) {
  676. iRect->outset(outset, outset);
  677. int leftClampDelta = clamp.fLeft - iRect->fLeft;
  678. if (leftClampDelta > 0) {
  679. offset->fX -= outset - leftClampDelta;
  680. iRect->fLeft = clamp.fLeft;
  681. } else {
  682. offset->fX -= outset;
  683. }
  684. int topClampDelta = clamp.fTop - iRect->fTop;
  685. if (topClampDelta > 0) {
  686. offset->fY -= outset - topClampDelta;
  687. iRect->fTop = clamp.fTop;
  688. } else {
  689. offset->fY -= outset;
  690. }
  691. if (iRect->fRight > clamp.fRight) {
  692. iRect->fRight = clamp.fRight;
  693. }
  694. if (iRect->fBottom > clamp.fBottom) {
  695. iRect->fBottom = clamp.fBottom;
  696. }
  697. }
  698. // Break 'bitmap' into several tiles to draw it since it has already
  699. // been determined to be too large to fit in VRAM
  700. void SkGpuDevice::drawTiledBitmap(const SkBitmap& bitmap,
  701. const SkMatrix& viewMatrix,
  702. const SkMatrix& dstMatrix,
  703. const SkRect& srcRect,
  704. const SkIRect& clippedSrcIRect,
  705. const GrSamplerState& params,
  706. const SkPaint& origPaint,
  707. SkCanvas::SrcRectConstraint constraint,
  708. int tileSize,
  709. bool bicubic) {
  710. ASSERT_SINGLE_OWNER
  711. // This is the funnel for all paths that draw tiled bitmaps/images. Log histogram entries.
  712. SK_HISTOGRAM_BOOLEAN("DrawTiled", true);
  713. LogDrawScaleFactor(viewMatrix, SkMatrix::I(), origPaint.getFilterQuality());
  714. const SkPaint* paint = &origPaint;
  715. SkPaint tempPaint;
  716. if (origPaint.isAntiAlias() && fRenderTargetContext->numSamples() <= 1) {
  717. // Drop antialiasing to avoid seams at tile boundaries.
  718. tempPaint = origPaint;
  719. tempPaint.setAntiAlias(false);
  720. paint = &tempPaint;
  721. }
  722. SkRect clippedSrcRect = SkRect::Make(clippedSrcIRect);
  723. int nx = bitmap.width() / tileSize;
  724. int ny = bitmap.height() / tileSize;
  725. for (int x = 0; x <= nx; x++) {
  726. for (int y = 0; y <= ny; y++) {
  727. SkRect tileR;
  728. tileR.set(SkIntToScalar(x * tileSize),
  729. SkIntToScalar(y * tileSize),
  730. SkIntToScalar((x + 1) * tileSize),
  731. SkIntToScalar((y + 1) * tileSize));
  732. if (!SkRect::Intersects(tileR, clippedSrcRect)) {
  733. continue;
  734. }
  735. if (!tileR.intersect(srcRect)) {
  736. continue;
  737. }
  738. SkIRect iTileR;
  739. tileR.roundOut(&iTileR);
  740. SkVector offset = SkPoint::Make(SkIntToScalar(iTileR.fLeft),
  741. SkIntToScalar(iTileR.fTop));
  742. SkRect rectToDraw = tileR;
  743. dstMatrix.mapRect(&rectToDraw);
  744. if (GrSamplerState::Filter::kNearest != params.filter() || bicubic) {
  745. SkIRect iClampRect;
  746. if (SkCanvas::kFast_SrcRectConstraint == constraint) {
  747. // In bleed mode we want to always expand the tile on all edges
  748. // but stay within the bitmap bounds
  749. iClampRect = SkIRect::MakeWH(bitmap.width(), bitmap.height());
  750. } else {
  751. // In texture-domain/clamp mode we only want to expand the
  752. // tile on edges interior to "srcRect" (i.e., we want to
  753. // not bleed across the original clamped edges)
  754. srcRect.roundOut(&iClampRect);
  755. }
  756. int outset = bicubic ? GrBicubicEffect::kFilterTexelPad : 1;
  757. clamped_outset_with_offset(&iTileR, outset, &offset, iClampRect);
  758. }
  759. SkBitmap tmpB;
  760. if (bitmap.extractSubset(&tmpB, iTileR)) {
  761. // now offset it to make it "local" to our tmp bitmap
  762. tileR.offset(-offset.fX, -offset.fY);
  763. // de-optimized this determination
  764. bool needsTextureDomain = true;
  765. this->drawBitmapTile(tmpB,
  766. viewMatrix,
  767. rectToDraw,
  768. tileR,
  769. params,
  770. *paint,
  771. constraint,
  772. bicubic,
  773. needsTextureDomain);
  774. }
  775. }
  776. }
  777. }
  778. void SkGpuDevice::drawBitmapTile(const SkBitmap& bitmap,
  779. const SkMatrix& viewMatrix,
  780. const SkRect& dstRect,
  781. const SkRect& srcRect,
  782. const GrSamplerState& samplerState,
  783. const SkPaint& paint,
  784. SkCanvas::SrcRectConstraint constraint,
  785. bool bicubic,
  786. bool needsTextureDomain) {
  787. // We should have already handled bitmaps larger than the max texture size.
  788. SkASSERT(bitmap.width() <= this->caps()->maxTextureSize() &&
  789. bitmap.height() <= this->caps()->maxTextureSize());
  790. // We should be respecting the max tile size by the time we get here.
  791. SkASSERT(bitmap.width() <= this->caps()->maxTileSize() &&
  792. bitmap.height() <= this->caps()->maxTileSize());
  793. SkASSERT(!samplerState.isRepeated());
  794. SkScalar scales[2] = {1.f, 1.f};
  795. sk_sp<GrTextureProxy> proxy =
  796. GrRefCachedBitmapTextureProxy(fContext.get(), bitmap, samplerState, scales);
  797. if (!proxy) {
  798. return;
  799. }
  800. // Compute a matrix that maps the rect we will draw to the src rect.
  801. SkMatrix texMatrix = SkMatrix::MakeRectToRect(dstRect, srcRect, SkMatrix::kFill_ScaleToFit);
  802. texMatrix.postScale(scales[0], scales[1]);
  803. // Construct a GrPaint by setting the bitmap texture as the first effect and then configuring
  804. // the rest from the SkPaint.
  805. std::unique_ptr<GrFragmentProcessor> fp;
  806. if (needsTextureDomain && (SkCanvas::kStrict_SrcRectConstraint == constraint)) {
  807. // Use a constrained texture domain to avoid color bleeding
  808. SkRect domain;
  809. if (srcRect.width() > SK_Scalar1) {
  810. domain.fLeft = srcRect.fLeft + 0.5f;
  811. domain.fRight = srcRect.fRight - 0.5f;
  812. } else {
  813. domain.fLeft = domain.fRight = srcRect.centerX();
  814. }
  815. if (srcRect.height() > SK_Scalar1) {
  816. domain.fTop = srcRect.fTop + 0.5f;
  817. domain.fBottom = srcRect.fBottom - 0.5f;
  818. } else {
  819. domain.fTop = domain.fBottom = srcRect.centerY();
  820. }
  821. if (bicubic) {
  822. static constexpr auto kDir = GrBicubicEffect::Direction::kXY;
  823. fp = GrBicubicEffect::Make(std::move(proxy), texMatrix, domain, kDir,
  824. bitmap.alphaType());
  825. } else {
  826. fp = GrTextureDomainEffect::Make(std::move(proxy), texMatrix, domain,
  827. GrTextureDomain::kClamp_Mode, samplerState.filter());
  828. }
  829. } else if (bicubic) {
  830. SkASSERT(GrSamplerState::Filter::kNearest == samplerState.filter());
  831. GrSamplerState::WrapMode wrapMode[2] = {samplerState.wrapModeX(), samplerState.wrapModeY()};
  832. static constexpr auto kDir = GrBicubicEffect::Direction::kXY;
  833. fp = GrBicubicEffect::Make(std::move(proxy), texMatrix, wrapMode, kDir, bitmap.alphaType());
  834. } else {
  835. fp = GrSimpleTextureEffect::Make(std::move(proxy), texMatrix, samplerState);
  836. }
  837. fp = GrColorSpaceXformEffect::Make(std::move(fp), bitmap.colorSpace(), bitmap.alphaType(),
  838. fRenderTargetContext->colorSpaceInfo().colorSpace());
  839. GrPaint grPaint;
  840. if (!SkPaintToGrPaintWithTexture(this->context(), fRenderTargetContext->colorSpaceInfo(), paint,
  841. viewMatrix, std::move(fp),
  842. kAlpha_8_SkColorType == bitmap.colorType(), &grPaint)) {
  843. return;
  844. }
  845. // Coverage-based AA would cause seams between tiles.
  846. GrAA aa = GrAA(paint.isAntiAlias() && fRenderTargetContext->numSamples() > 1);
  847. fRenderTargetContext->drawRect(this->clip(), std::move(grPaint), aa, viewMatrix, dstRect);
  848. }
  849. void SkGpuDevice::drawSprite(const SkBitmap& bitmap,
  850. int left, int top, const SkPaint& paint) {
  851. ASSERT_SINGLE_OWNER
  852. GR_CREATE_TRACE_MARKER_CONTEXT("SkGpuDevice", "drawSprite", fContext.get());
  853. if (fContext->priv().abandoned()) {
  854. return;
  855. }
  856. sk_sp<SkSpecialImage> srcImg = this->makeSpecial(bitmap);
  857. if (!srcImg) {
  858. return;
  859. }
  860. this->drawSpecial(srcImg.get(), left, top, paint, nullptr, SkMatrix::I());
  861. }
  862. void SkGpuDevice::drawSpecial(SkSpecialImage* special, int left, int top, const SkPaint& paint,
  863. SkImage* clipImage, const SkMatrix& clipMatrix) {
  864. ASSERT_SINGLE_OWNER
  865. GR_CREATE_TRACE_MARKER_CONTEXT("SkGpuDevice", "drawSpecial", fContext.get());
  866. sk_sp<SkSpecialImage> result;
  867. if (paint.getImageFilter()) {
  868. SkIPoint offset = { 0, 0 };
  869. result = this->filterTexture(special, left, top, &offset, paint.getImageFilter());
  870. if (!result) {
  871. return;
  872. }
  873. left += offset.fX;
  874. top += offset.fY;
  875. } else {
  876. result = sk_ref_sp(special);
  877. }
  878. SkASSERT(result->isTextureBacked());
  879. sk_sp<GrTextureProxy> proxy = result->asTextureProxyRef(this->context());
  880. if (!proxy) {
  881. return;
  882. }
  883. const GrPixelConfig config = proxy->config();
  884. SkMatrix ctm = this->ctm();
  885. ctm.postTranslate(-SkIntToScalar(left), -SkIntToScalar(top));
  886. SkPaint tmpUnfiltered(paint);
  887. if (tmpUnfiltered.getMaskFilter()) {
  888. tmpUnfiltered.setMaskFilter(tmpUnfiltered.getMaskFilter()->makeWithMatrix(ctm));
  889. }
  890. tmpUnfiltered.setImageFilter(nullptr);
  891. auto fp = GrSimpleTextureEffect::Make(std::move(proxy), SkMatrix::I());
  892. fp = GrColorSpaceXformEffect::Make(std::move(fp), result->getColorSpace(), result->alphaType(),
  893. fRenderTargetContext->colorSpaceInfo().colorSpace());
  894. if (GrPixelConfigIsAlphaOnly(config)) {
  895. fp = GrFragmentProcessor::MakeInputPremulAndMulByOutput(std::move(fp));
  896. } else {
  897. if (paint.getColor4f().isOpaque()) {
  898. fp = GrFragmentProcessor::OverrideInput(std::move(fp), SK_PMColor4fWHITE, false);
  899. } else {
  900. fp = GrFragmentProcessor::MulChildByInputAlpha(std::move(fp));
  901. }
  902. }
  903. GrPaint grPaint;
  904. if (!SkPaintToGrPaintReplaceShader(this->context(), fRenderTargetContext->colorSpaceInfo(),
  905. tmpUnfiltered, std::move(fp), &grPaint)) {
  906. return;
  907. }
  908. const SkIRect& subset = result->subset();
  909. SkRect dstRect = SkRect::Make(SkIRect::MakeXYWH(left, top, subset.width(), subset.height()));
  910. SkRect srcRect = SkRect::Make(subset);
  911. if (clipImage) {
  912. // Add the image as a simple texture effect applied to coverage. Accessing content outside
  913. // of the clip image should behave as if it were a decal (i.e. zero coverage). However, to
  914. // limit pixels touched and hardware checks, we draw the clip image geometry to get the
  915. // decal effect.
  916. GrSamplerState sampler = paint.getFilterQuality() > kNone_SkFilterQuality ?
  917. GrSamplerState::ClampBilerp() : GrSamplerState::ClampNearest();
  918. sk_sp<GrTextureProxy> clipProxy = as_IB(clipImage)->asTextureProxyRef(this->context(),
  919. sampler, nullptr);
  920. // Fold clip matrix into ctm
  921. ctm.preConcat(clipMatrix);
  922. SkMatrix inverseClipMatrix;
  923. std::unique_ptr<GrFragmentProcessor> cfp;
  924. if (clipProxy && ctm.invert(&inverseClipMatrix)) {
  925. cfp = GrSimpleTextureEffect::Make(std::move(clipProxy), inverseClipMatrix, sampler);
  926. if (clipImage->colorType() != kAlpha_8_SkColorType) {
  927. cfp = GrFragmentProcessor::SwizzleOutput(std::move(cfp), GrSwizzle::AAAA());
  928. }
  929. }
  930. if (cfp) {
  931. // If the grPaint already has coverage, this adds an additional stage that multiples
  932. // the image's alpha channel with the prior coverage.
  933. grPaint.addCoverageFragmentProcessor(std::move(cfp));
  934. // Undo the offset that was needed for shader coord transforms to get the transform for
  935. // the actual drawn geometry.
  936. ctm.postTranslate(SkIntToScalar(left), SkIntToScalar(top));
  937. inverseClipMatrix.preTranslate(-SkIntToScalar(left), -SkIntToScalar(top));
  938. SkRect clipGeometry = SkRect::MakeWH(clipImage->width(), clipImage->height());
  939. if (!clipGeometry.contains(inverseClipMatrix.mapRect(dstRect))) {
  940. // Draw the clip geometry since it is smaller, using dstRect as an extra scissor
  941. SkClipStack clip(this->cs());
  942. clip.clipDevRect(SkIRect::MakeXYWH(left, top, subset.width(), subset.height()),
  943. SkClipOp::kIntersect);
  944. SkMatrix local = SkMatrix::Concat(SkMatrix::MakeRectToRect(
  945. dstRect, srcRect, SkMatrix::kFill_ScaleToFit), ctm);
  946. fRenderTargetContext->fillRectWithLocalMatrix(GrClipStackClip(&clip),
  947. std::move(grPaint), GrAA(paint.isAntiAlias()), ctm, clipGeometry, local);
  948. return;
  949. }
  950. // Else fall through and draw the subset since that is contained in the clip geometry
  951. }
  952. // Else some issue configuring the coverage FP, so just draw without the clip mask image
  953. }
  954. // Draw directly in screen space, possibly with an extra coverage processor
  955. fRenderTargetContext->fillRectToRect(this->clip(), std::move(grPaint),
  956. GrAA(paint.isAntiAlias()), SkMatrix::I(), dstRect, srcRect);
  957. }
  958. void SkGpuDevice::drawBitmapRect(const SkBitmap& bitmap,
  959. const SkRect* src, const SkRect& origDst,
  960. const SkPaint& paint, SkCanvas::SrcRectConstraint constraint) {
  961. ASSERT_SINGLE_OWNER
  962. // The src rect is inferred to be the bmp bounds if not provided. Otherwise, the src rect must
  963. // be clipped to the bmp bounds. To determine tiling parameters we need the filter mode which
  964. // in turn requires knowing the src-to-dst mapping. If the src was clipped to the bmp bounds
  965. // then we use the src-to-dst mapping to compute a new clipped dst rect.
  966. const SkRect* dst = &origDst;
  967. const SkRect bmpBounds = SkRect::MakeIWH(bitmap.width(), bitmap.height());
  968. // Compute matrix from the two rectangles
  969. if (!src) {
  970. src = &bmpBounds;
  971. }
  972. SkMatrix srcToDstMatrix;
  973. if (!srcToDstMatrix.setRectToRect(*src, *dst, SkMatrix::kFill_ScaleToFit)) {
  974. return;
  975. }
  976. SkRect tmpSrc, tmpDst;
  977. if (src != &bmpBounds) {
  978. if (!bmpBounds.contains(*src)) {
  979. tmpSrc = *src;
  980. if (!tmpSrc.intersect(bmpBounds)) {
  981. return; // nothing to draw
  982. }
  983. src = &tmpSrc;
  984. srcToDstMatrix.mapRect(&tmpDst, *src);
  985. dst = &tmpDst;
  986. }
  987. }
  988. int maxTileSize = this->caps()->maxTileSize();
  989. // The tile code path doesn't currently support AA, so if the paint asked for aa and we could
  990. // draw untiled, then we bypass checking for tiling purely for optimization reasons.
  991. bool useCoverageAA = fRenderTargetContext->numSamples() <= 1 &&
  992. paint.isAntiAlias() && bitmap.width() <= maxTileSize &&
  993. bitmap.height() <= maxTileSize;
  994. bool skipTileCheck = useCoverageAA || paint.getMaskFilter();
  995. if (!skipTileCheck) {
  996. int tileSize;
  997. SkIRect clippedSrcRect;
  998. GrSamplerState sampleState;
  999. bool doBicubic;
  1000. GrSamplerState::Filter textureFilterMode = GrSkFilterQualityToGrFilterMode(
  1001. paint.getFilterQuality(), this->ctm(), srcToDstMatrix,
  1002. fContext->priv().options().fSharpenMipmappedTextures, &doBicubic);
  1003. int tileFilterPad;
  1004. if (doBicubic) {
  1005. tileFilterPad = GrBicubicEffect::kFilterTexelPad;
  1006. } else if (GrSamplerState::Filter::kNearest == textureFilterMode) {
  1007. tileFilterPad = 0;
  1008. } else {
  1009. tileFilterPad = 1;
  1010. }
  1011. sampleState.setFilterMode(textureFilterMode);
  1012. int maxTileSizeForFilter = this->caps()->maxTileSize() - 2 * tileFilterPad;
  1013. if (this->shouldTileImageID(bitmap.getGenerationID(), bitmap.getSubset(), this->ctm(),
  1014. srcToDstMatrix, sampleState, src, maxTileSizeForFilter,
  1015. &tileSize, &clippedSrcRect)) {
  1016. this->drawTiledBitmap(bitmap, this->ctm(), srcToDstMatrix, *src, clippedSrcRect,
  1017. sampleState, paint, constraint, tileSize, doBicubic);
  1018. return;
  1019. }
  1020. }
  1021. GrBitmapTextureMaker maker(fContext.get(), bitmap);
  1022. this->drawTextureProducer(&maker, src, dst, constraint, this->ctm(), paint, true);
  1023. }
  1024. sk_sp<SkSpecialImage> SkGpuDevice::makeSpecial(const SkBitmap& bitmap) {
  1025. // TODO: this makes a tight copy of 'bitmap' but it doesn't have to be (given SkSpecialImage's
  1026. // semantics). Since this is cached we would have to bake the fit into the cache key though.
  1027. sk_sp<GrTextureProxy> proxy = GrMakeCachedBitmapProxy(fContext->priv().proxyProvider(),
  1028. bitmap);
  1029. if (!proxy) {
  1030. return nullptr;
  1031. }
  1032. const SkIRect rect = SkIRect::MakeWH(proxy->width(), proxy->height());
  1033. // GrMakeCachedBitmapProxy creates a tight copy of 'bitmap' so we don't have to subset
  1034. // the special image
  1035. return SkSpecialImage::MakeDeferredFromGpu(fContext.get(),
  1036. rect,
  1037. bitmap.getGenerationID(),
  1038. std::move(proxy),
  1039. bitmap.refColorSpace(),
  1040. &this->surfaceProps());
  1041. }
  1042. sk_sp<SkSpecialImage> SkGpuDevice::makeSpecial(const SkImage* image) {
  1043. SkPixmap pm;
  1044. if (image->isTextureBacked()) {
  1045. sk_sp<GrTextureProxy> proxy = as_IB(image)->asTextureProxyRef(this->context());
  1046. return SkSpecialImage::MakeDeferredFromGpu(fContext.get(),
  1047. SkIRect::MakeWH(image->width(), image->height()),
  1048. image->uniqueID(),
  1049. std::move(proxy),
  1050. image->refColorSpace(),
  1051. &this->surfaceProps());
  1052. } else if (image->peekPixels(&pm)) {
  1053. SkBitmap bm;
  1054. bm.installPixels(pm);
  1055. return this->makeSpecial(bm);
  1056. } else {
  1057. return nullptr;
  1058. }
  1059. }
  1060. sk_sp<SkSpecialImage> SkGpuDevice::snapSpecial() {
  1061. // If we are wrapping a vulkan secondary command buffer, then we can't snap off a special image
  1062. // since it would require us to make a copy of the underlying VkImage which we don't have access
  1063. // to. Additionaly we can't stop and start the render pass that is used with the secondary
  1064. // command buffer.
  1065. if (this->accessRenderTargetContext()->wrapsVkSecondaryCB()) {
  1066. return nullptr;
  1067. }
  1068. sk_sp<GrTextureProxy> proxy(this->accessRenderTargetContext()->asTextureProxyRef());
  1069. if (!proxy) {
  1070. // When the device doesn't have a texture, we create a temporary texture.
  1071. // TODO: we should actually only copy the portion of the source needed to apply the image
  1072. // filter
  1073. proxy = GrSurfaceProxy::Copy(fContext.get(),
  1074. this->accessRenderTargetContext()->asSurfaceProxy(),
  1075. GrMipMapped::kNo,
  1076. SkBackingFit::kApprox,
  1077. SkBudgeted::kYes);
  1078. if (!proxy) {
  1079. return nullptr;
  1080. }
  1081. }
  1082. const SkImageInfo ii = this->imageInfo();
  1083. const SkIRect srcRect = SkIRect::MakeWH(ii.width(), ii.height());
  1084. return SkSpecialImage::MakeDeferredFromGpu(fContext.get(),
  1085. srcRect,
  1086. kNeedNewImageUniqueID_SpecialImage,
  1087. std::move(proxy),
  1088. ii.refColorSpace(),
  1089. &this->surfaceProps());
  1090. }
  1091. sk_sp<SkSpecialImage> SkGpuDevice::snapBackImage(const SkIRect& subset) {
  1092. GrRenderTargetContext* rtc = this->accessRenderTargetContext();
  1093. // If we are wrapping a vulkan secondary command buffer, then we can't snap off a special image
  1094. // since it would require us to make a copy of the underlying VkImage which we don't have access
  1095. // to. Additionaly we can't stop and start the render pass that is used with the secondary
  1096. // command buffer.
  1097. if (rtc->wrapsVkSecondaryCB()) {
  1098. return nullptr;
  1099. }
  1100. GrContext* ctx = this->context();
  1101. SkASSERT(rtc->asSurfaceProxy());
  1102. auto srcProxy =
  1103. GrSurfaceProxy::Copy(ctx, rtc->asSurfaceProxy(), rtc->mipMapped(), subset,
  1104. SkBackingFit::kApprox, rtc->asSurfaceProxy()->isBudgeted());
  1105. if (!srcProxy) {
  1106. return nullptr;
  1107. }
  1108. // Note, can't move srcProxy since we also refer to this in the 2nd parameter
  1109. return SkSpecialImage::MakeDeferredFromGpu(fContext.get(),
  1110. SkIRect::MakeSize(srcProxy->isize()),
  1111. kNeedNewImageUniqueID_SpecialImage,
  1112. srcProxy,
  1113. this->imageInfo().refColorSpace(),
  1114. &this->surfaceProps());
  1115. }
  1116. void SkGpuDevice::drawDevice(SkBaseDevice* device,
  1117. int left, int top, const SkPaint& paint) {
  1118. SkASSERT(!paint.getImageFilter());
  1119. ASSERT_SINGLE_OWNER
  1120. // clear of the source device must occur before CHECK_SHOULD_DRAW
  1121. GR_CREATE_TRACE_MARKER_CONTEXT("SkGpuDevice", "drawDevice", fContext.get());
  1122. // drawDevice is defined to be in device coords.
  1123. SkGpuDevice* dev = static_cast<SkGpuDevice*>(device);
  1124. sk_sp<SkSpecialImage> srcImg(dev->snapSpecial());
  1125. if (!srcImg) {
  1126. return;
  1127. }
  1128. this->drawSpecial(srcImg.get(), left, top, paint, nullptr, SkMatrix::I());
  1129. }
  1130. void SkGpuDevice::drawImageRect(const SkImage* image, const SkRect* src, const SkRect& dst,
  1131. const SkPaint& paint, SkCanvas::SrcRectConstraint constraint) {
  1132. ASSERT_SINGLE_OWNER
  1133. GrQuadAAFlags aaFlags = paint.isAntiAlias() ? GrQuadAAFlags::kAll : GrQuadAAFlags::kNone;
  1134. this->drawImageQuad(image, src, &dst, nullptr, GrAA(paint.isAntiAlias()), aaFlags, nullptr,
  1135. paint, constraint);
  1136. }
  1137. // When drawing nine-patches or n-patches, cap the filter quality at kBilerp.
  1138. static GrSamplerState::Filter compute_lattice_filter_mode(const SkPaint& paint) {
  1139. if (paint.getFilterQuality() == kNone_SkFilterQuality) {
  1140. return GrSamplerState::Filter::kNearest;
  1141. }
  1142. return GrSamplerState::Filter::kBilerp;
  1143. }
  1144. void SkGpuDevice::drawImageNine(const SkImage* image,
  1145. const SkIRect& center, const SkRect& dst, const SkPaint& paint) {
  1146. ASSERT_SINGLE_OWNER
  1147. uint32_t pinnedUniqueID;
  1148. auto iter = skstd::make_unique<SkLatticeIter>(image->width(), image->height(), center, dst);
  1149. if (sk_sp<GrTextureProxy> proxy = as_IB(image)->refPinnedTextureProxy(this->context(),
  1150. &pinnedUniqueID)) {
  1151. GrTextureAdjuster adjuster(this->context(), std::move(proxy),
  1152. SkColorTypeToGrColorType(image->colorType()), image->alphaType(),
  1153. pinnedUniqueID, image->colorSpace());
  1154. this->drawProducerLattice(&adjuster, std::move(iter), dst, paint);
  1155. } else {
  1156. SkBitmap bm;
  1157. if (image->isLazyGenerated()) {
  1158. GrImageTextureMaker maker(fContext.get(), image, SkImage::kAllow_CachingHint);
  1159. this->drawProducerLattice(&maker, std::move(iter), dst, paint);
  1160. } else if (as_IB(image)->getROPixels(&bm)) {
  1161. GrBitmapTextureMaker maker(fContext.get(), bm);
  1162. this->drawProducerLattice(&maker, std::move(iter), dst, paint);
  1163. }
  1164. }
  1165. }
  1166. void SkGpuDevice::drawBitmapNine(const SkBitmap& bitmap, const SkIRect& center,
  1167. const SkRect& dst, const SkPaint& paint) {
  1168. ASSERT_SINGLE_OWNER
  1169. auto iter = skstd::make_unique<SkLatticeIter>(bitmap.width(), bitmap.height(), center, dst);
  1170. GrBitmapTextureMaker maker(fContext.get(), bitmap);
  1171. this->drawProducerLattice(&maker, std::move(iter), dst, paint);
  1172. }
  1173. void SkGpuDevice::drawProducerLattice(GrTextureProducer* producer,
  1174. std::unique_ptr<SkLatticeIter> iter, const SkRect& dst,
  1175. const SkPaint& origPaint) {
  1176. GR_CREATE_TRACE_MARKER_CONTEXT("SkGpuDevice", "drawProducerLattice", fContext.get());
  1177. SkTCopyOnFirstWrite<SkPaint> paint(&origPaint);
  1178. if (!producer->isAlphaOnly() && (paint->getColor() & 0x00FFFFFF) != 0x00FFFFFF) {
  1179. paint.writable()->setColor(SkColorSetARGB(origPaint.getAlpha(), 0xFF, 0xFF, 0xFF));
  1180. }
  1181. GrPaint grPaint;
  1182. if (!SkPaintToGrPaintWithPrimitiveColor(this->context(), fRenderTargetContext->colorSpaceInfo(),
  1183. *paint, &grPaint)) {
  1184. return;
  1185. }
  1186. auto dstColorSpace = fRenderTargetContext->colorSpaceInfo().colorSpace();
  1187. const GrSamplerState::Filter filter = compute_lattice_filter_mode(*paint);
  1188. auto proxy = producer->refTextureProxyForParams(&filter, nullptr);
  1189. if (!proxy) {
  1190. return;
  1191. }
  1192. auto csxf = GrColorSpaceXform::Make(producer->colorSpace(), producer->alphaType(),
  1193. dstColorSpace, kPremul_SkAlphaType);
  1194. fRenderTargetContext->drawImageLattice(this->clip(), std::move(grPaint), this->ctm(),
  1195. std::move(proxy), std::move(csxf), filter,
  1196. std::move(iter), dst);
  1197. }
  1198. void SkGpuDevice::drawImageLattice(const SkImage* image,
  1199. const SkCanvas::Lattice& lattice, const SkRect& dst,
  1200. const SkPaint& paint) {
  1201. ASSERT_SINGLE_OWNER
  1202. uint32_t pinnedUniqueID;
  1203. auto iter = skstd::make_unique<SkLatticeIter>(lattice, dst);
  1204. if (sk_sp<GrTextureProxy> proxy = as_IB(image)->refPinnedTextureProxy(this->context(),
  1205. &pinnedUniqueID)) {
  1206. GrTextureAdjuster adjuster(this->context(), std::move(proxy),
  1207. SkColorTypeToGrColorType(image->colorType()), image->alphaType(),
  1208. pinnedUniqueID, image->colorSpace());
  1209. this->drawProducerLattice(&adjuster, std::move(iter), dst, paint);
  1210. } else {
  1211. SkBitmap bm;
  1212. if (image->isLazyGenerated()) {
  1213. GrImageTextureMaker maker(fContext.get(), image, SkImage::kAllow_CachingHint);
  1214. this->drawProducerLattice(&maker, std::move(iter), dst, paint);
  1215. } else if (as_IB(image)->getROPixels(&bm)) {
  1216. GrBitmapTextureMaker maker(fContext.get(), bm);
  1217. this->drawProducerLattice(&maker, std::move(iter), dst, paint);
  1218. }
  1219. }
  1220. }
  1221. void SkGpuDevice::drawBitmapLattice(const SkBitmap& bitmap,
  1222. const SkCanvas::Lattice& lattice, const SkRect& dst,
  1223. const SkPaint& paint) {
  1224. ASSERT_SINGLE_OWNER
  1225. auto iter = skstd::make_unique<SkLatticeIter>(lattice, dst);
  1226. GrBitmapTextureMaker maker(fContext.get(), bitmap);
  1227. this->drawProducerLattice(&maker, std::move(iter), dst, paint);
  1228. }
  1229. static bool init_vertices_paint(GrContext* context, const GrColorSpaceInfo& colorSpaceInfo,
  1230. const SkPaint& skPaint, const SkMatrix& matrix, SkBlendMode bmode,
  1231. bool hasTexs, bool hasColors, GrPaint* grPaint) {
  1232. if (hasTexs && skPaint.getShader()) {
  1233. if (hasColors) {
  1234. // When there are texs and colors the shader and colors are combined using bmode.
  1235. return SkPaintToGrPaintWithXfermode(context, colorSpaceInfo, skPaint, matrix, bmode,
  1236. grPaint);
  1237. } else {
  1238. // We have a shader, but no colors to blend it against.
  1239. return SkPaintToGrPaint(context, colorSpaceInfo, skPaint, matrix, grPaint);
  1240. }
  1241. } else {
  1242. if (hasColors) {
  1243. // We have colors, but either have no shader or no texture coords (which implies that
  1244. // we should ignore the shader).
  1245. return SkPaintToGrPaintWithPrimitiveColor(context, colorSpaceInfo, skPaint, grPaint);
  1246. } else {
  1247. // No colors and no shaders. Just draw with the paint color.
  1248. return SkPaintToGrPaintNoShader(context, colorSpaceInfo, skPaint, grPaint);
  1249. }
  1250. }
  1251. }
  1252. void SkGpuDevice::wireframeVertices(SkVertices::VertexMode vmode, int vertexCount,
  1253. const SkPoint vertices[],
  1254. const SkVertices::Bone bones[], int boneCount,
  1255. SkBlendMode bmode,
  1256. const uint16_t indices[], int indexCount,
  1257. const SkPaint& paint) {
  1258. ASSERT_SINGLE_OWNER
  1259. GR_CREATE_TRACE_MARKER_CONTEXT("SkGpuDevice", "wireframeVertices", fContext.get());
  1260. SkPaint copy(paint);
  1261. copy.setStyle(SkPaint::kStroke_Style);
  1262. copy.setStrokeWidth(0);
  1263. GrPaint grPaint;
  1264. // we ignore the shader since we have no texture coordinates.
  1265. if (!SkPaintToGrPaintNoShader(this->context(), fRenderTargetContext->colorSpaceInfo(), copy,
  1266. &grPaint)) {
  1267. return;
  1268. }
  1269. int triangleCount = 0;
  1270. int n = (nullptr == indices) ? vertexCount : indexCount;
  1271. switch (vmode) {
  1272. case SkVertices::kTriangles_VertexMode:
  1273. triangleCount = n / 3;
  1274. break;
  1275. case SkVertices::kTriangleStrip_VertexMode:
  1276. triangleCount = n - 2;
  1277. break;
  1278. case SkVertices::kTriangleFan_VertexMode:
  1279. SK_ABORT("Unexpected triangle fan.");
  1280. break;
  1281. }
  1282. VertState state(vertexCount, indices, indexCount);
  1283. VertState::Proc vertProc = state.chooseProc(vmode);
  1284. //number of indices for lines per triangle with kLines
  1285. indexCount = triangleCount * 6;
  1286. static constexpr SkVertices::VertexMode kIgnoredMode = SkVertices::kTriangles_VertexMode;
  1287. SkVertices::Builder builder(kIgnoredMode, vertexCount, indexCount, 0);
  1288. memcpy(builder.positions(), vertices, vertexCount * sizeof(SkPoint));
  1289. uint16_t* lineIndices = builder.indices();
  1290. int i = 0;
  1291. while (vertProc(&state)) {
  1292. lineIndices[i] = state.f0;
  1293. lineIndices[i + 1] = state.f1;
  1294. lineIndices[i + 2] = state.f1;
  1295. lineIndices[i + 3] = state.f2;
  1296. lineIndices[i + 4] = state.f2;
  1297. lineIndices[i + 5] = state.f0;
  1298. i += 6;
  1299. }
  1300. GrPrimitiveType primitiveType = GrPrimitiveType::kLines;
  1301. fRenderTargetContext->drawVertices(this->clip(),
  1302. std::move(grPaint),
  1303. this->ctm(),
  1304. builder.detach(),
  1305. bones,
  1306. boneCount,
  1307. &primitiveType);
  1308. }
  1309. void SkGpuDevice::drawVertices(const SkVertices* vertices, const SkVertices::Bone bones[],
  1310. int boneCount, SkBlendMode mode, const SkPaint& paint) {
  1311. ASSERT_SINGLE_OWNER
  1312. GR_CREATE_TRACE_MARKER_CONTEXT("SkGpuDevice", "drawVertices", fContext.get());
  1313. SkASSERT(vertices);
  1314. GrPaint grPaint;
  1315. bool hasColors = vertices->hasColors();
  1316. bool hasTexs = vertices->hasTexCoords();
  1317. if ((!hasTexs || !paint.getShader()) && !hasColors) {
  1318. // The dreaded wireframe mode. Fallback to drawVertices and go so slooooooow.
  1319. this->wireframeVertices(vertices->mode(), vertices->vertexCount(), vertices->positions(),
  1320. bones, boneCount, mode, vertices->indices(), vertices->indexCount(),
  1321. paint);
  1322. return;
  1323. }
  1324. if (!init_vertices_paint(fContext.get(), fRenderTargetContext->colorSpaceInfo(), paint,
  1325. this->ctm(), mode, hasTexs, hasColors, &grPaint)) {
  1326. return;
  1327. }
  1328. fRenderTargetContext->drawVertices(this->clip(), std::move(grPaint), this->ctm(),
  1329. sk_ref_sp(const_cast<SkVertices*>(vertices)),
  1330. bones, boneCount);
  1331. }
  1332. ///////////////////////////////////////////////////////////////////////////////
  1333. void SkGpuDevice::drawShadow(const SkPath& path, const SkDrawShadowRec& rec) {
  1334. ASSERT_SINGLE_OWNER
  1335. GR_CREATE_TRACE_MARKER_CONTEXT("SkGpuDevice", "drawShadow", fContext.get());
  1336. if (!fRenderTargetContext->drawFastShadow(this->clip(), this->ctm(), path, rec)) {
  1337. // failed to find an accelerated case
  1338. this->INHERITED::drawShadow(path, rec);
  1339. }
  1340. }
  1341. ///////////////////////////////////////////////////////////////////////////////
  1342. void SkGpuDevice::drawAtlas(const SkImage* atlas, const SkRSXform xform[],
  1343. const SkRect texRect[], const SkColor colors[], int count,
  1344. SkBlendMode mode, const SkPaint& paint) {
  1345. ASSERT_SINGLE_OWNER
  1346. GR_CREATE_TRACE_MARKER_CONTEXT("SkGpuDevice", "drawAtlas", fContext.get());
  1347. SkPaint p(paint);
  1348. p.setShader(atlas->makeShader());
  1349. GrPaint grPaint;
  1350. if (colors) {
  1351. if (!SkPaintToGrPaintWithXfermode(this->context(), fRenderTargetContext->colorSpaceInfo(),
  1352. p, this->ctm(), (SkBlendMode)mode, &grPaint)) {
  1353. return;
  1354. }
  1355. } else {
  1356. if (!SkPaintToGrPaint(this->context(), fRenderTargetContext->colorSpaceInfo(), p,
  1357. this->ctm(), &grPaint)) {
  1358. return;
  1359. }
  1360. }
  1361. fRenderTargetContext->drawAtlas(
  1362. this->clip(), std::move(grPaint), this->ctm(), count, xform, texRect, colors);
  1363. }
  1364. ///////////////////////////////////////////////////////////////////////////////
  1365. void SkGpuDevice::drawGlyphRunList(const SkGlyphRunList& glyphRunList) {
  1366. ASSERT_SINGLE_OWNER
  1367. GR_CREATE_TRACE_MARKER_CONTEXT("SkGpuDevice", "drawGlyphRunList", fContext.get());
  1368. // Check for valid input
  1369. const SkMatrix& ctm = this->ctm();
  1370. if (!ctm.isFinite() || !glyphRunList.allFontsFinite()) {
  1371. return;
  1372. }
  1373. fRenderTargetContext->drawGlyphRunList(this->clip(), ctm, glyphRunList);
  1374. }
  1375. ///////////////////////////////////////////////////////////////////////////////
  1376. void SkGpuDevice::drawDrawable(SkDrawable* drawable, const SkMatrix* matrix, SkCanvas* canvas) {
  1377. GrBackendApi api = this->context()->backend();
  1378. if (GrBackendApi::kVulkan == api) {
  1379. const SkMatrix& ctm = canvas->getTotalMatrix();
  1380. const SkMatrix& combinedMatrix = matrix ? SkMatrix::Concat(ctm, *matrix) : ctm;
  1381. std::unique_ptr<SkDrawable::GpuDrawHandler> gpuDraw =
  1382. drawable->snapGpuDrawHandler(api, combinedMatrix, canvas->getDeviceClipBounds(),
  1383. this->imageInfo());
  1384. if (gpuDraw) {
  1385. fRenderTargetContext->drawDrawable(std::move(gpuDraw), drawable->getBounds());
  1386. return;
  1387. }
  1388. }
  1389. this->INHERITED::drawDrawable(drawable, matrix, canvas);
  1390. }
  1391. ///////////////////////////////////////////////////////////////////////////////
  1392. void SkGpuDevice::flush() {
  1393. this->flush(SkSurface::BackendSurfaceAccess::kNoAccess, GrFlushInfo());
  1394. }
  1395. GrSemaphoresSubmitted SkGpuDevice::flush(SkSurface::BackendSurfaceAccess access,
  1396. const GrFlushInfo& info) {
  1397. ASSERT_SINGLE_OWNER
  1398. return fRenderTargetContext->flush(access, info);
  1399. }
  1400. bool SkGpuDevice::wait(int numSemaphores, const GrBackendSemaphore* waitSemaphores) {
  1401. ASSERT_SINGLE_OWNER
  1402. return fRenderTargetContext->waitOnSemaphores(numSemaphores, waitSemaphores);
  1403. }
  1404. ///////////////////////////////////////////////////////////////////////////////
  1405. SkBaseDevice* SkGpuDevice::onCreateDevice(const CreateInfo& cinfo, const SkPaint*) {
  1406. ASSERT_SINGLE_OWNER
  1407. SkSurfaceProps props(this->surfaceProps().flags(), cinfo.fPixelGeometry);
  1408. // layers are never drawn in repeat modes, so we can request an approx
  1409. // match and ignore any padding.
  1410. SkBackingFit fit = kNever_TileUsage == cinfo.fTileUsage ? SkBackingFit::kApprox
  1411. : SkBackingFit::kExact;
  1412. GrColorType colorType = fRenderTargetContext->colorSpaceInfo().colorType();
  1413. if (colorType == GrColorType::kRGBA_1010102) {
  1414. // If the original device is 1010102, fall back to 8888 so that we have a usable alpha
  1415. // channel in the layer.
  1416. colorType = GrColorType::kRGBA_8888;
  1417. }
  1418. sk_sp<GrRenderTargetContext> rtc(fContext->priv().makeDeferredRenderTargetContext(
  1419. fit,
  1420. cinfo.fInfo.width(),
  1421. cinfo.fInfo.height(),
  1422. colorType,
  1423. fRenderTargetContext->colorSpaceInfo().refColorSpace(),
  1424. fRenderTargetContext->numSamples(),
  1425. GrMipMapped::kNo,
  1426. kBottomLeft_GrSurfaceOrigin,
  1427. &props,
  1428. SkBudgeted::kYes,
  1429. fRenderTargetContext->asSurfaceProxy()->isProtected() ? GrProtected::kYes
  1430. : GrProtected::kNo));
  1431. if (!rtc) {
  1432. return nullptr;
  1433. }
  1434. // Skia's convention is to only clear a device if it is non-opaque.
  1435. InitContents init = cinfo.fInfo.isOpaque() ? kUninit_InitContents : kClear_InitContents;
  1436. return SkGpuDevice::Make(fContext.get(), std::move(rtc),
  1437. cinfo.fInfo.width(), cinfo.fInfo.height(), init).release();
  1438. }
  1439. sk_sp<SkSurface> SkGpuDevice::makeSurface(const SkImageInfo& info, const SkSurfaceProps& props) {
  1440. ASSERT_SINGLE_OWNER
  1441. // TODO: Change the signature of newSurface to take a budgeted parameter.
  1442. static const SkBudgeted kBudgeted = SkBudgeted::kNo;
  1443. return SkSurface::MakeRenderTarget(fContext.get(), kBudgeted, info,
  1444. fRenderTargetContext->numSamples(),
  1445. fRenderTargetContext->origin(), &props);
  1446. }
  1447. SkImageFilterCache* SkGpuDevice::getImageFilterCache() {
  1448. ASSERT_SINGLE_OWNER
  1449. // We always return a transient cache, so it is freed after each
  1450. // filter traversal.
  1451. return SkImageFilterCache::Create(SkImageFilterCache::kDefaultTransientSize);
  1452. }