| 1 |
/* |
| 2 |
* Copyright 2021 Google LLC |
| 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/graphite/Device.h" |
| 8 |
|
| 9 |
#include "include/core/SkAlphaType.h" |
| 10 |
#include "include/core/SkArc.h" |
| 11 |
#include "include/core/SkBlendMode.h" |
| 12 |
#include "include/core/SkClipOp.h" |
| 13 |
#include "include/core/SkColorFilter.h" |
| 14 |
#include "include/core/SkColorSpace.h" |
| 15 |
#include "include/core/SkColorType.h" |
| 16 |
#include "include/core/SkImage.h" |
| 17 |
#include "include/core/SkImageInfo.h" |
| 18 |
#include "include/core/SkM44.h" |
| 19 |
#include "include/core/SkMatrix.h" |
| 20 |
#include "include/core/SkPaint.h" |
| 21 |
#include "include/core/SkPath.h" |
| 22 |
#include "include/core/SkPathBuilder.h" |
| 23 |
#include "include/core/SkPathEffect.h" |
| 24 |
#include "include/core/SkPixmap.h" |
| 25 |
#include "include/core/SkPoint.h" |
| 26 |
#include "include/core/SkRRect.h" |
| 27 |
#include "include/core/SkRegion.h" |
| 28 |
#include "include/core/SkScalar.h" |
| 29 |
#include "include/core/SkShader.h" |
| 30 |
#include "include/core/SkSize.h" |
| 31 |
#include "include/core/SkStrokeRec.h" |
| 32 |
#include "include/core/SkSurfaceProps.h" |
| 33 |
#include "include/core/SkVertices.h" |
| 34 |
#include "include/gpu/GpuTypes.h" |
| 35 |
#include "include/gpu/graphite/Context.h" |
| 36 |
#include "include/gpu/graphite/GraphiteTypes.h" |
| 37 |
#include "include/gpu/graphite/Image.h" |
| 38 |
#include "include/gpu/graphite/Recorder.h" |
| 39 |
#include "include/gpu/graphite/Surface.h" |
| 40 |
#include "include/gpu/graphite/TextureInfo.h" |
| 41 |
#include "include/private/base/SingleOwner.h" |
| 42 |
#include "include/private/base/SkAssert.h" |
| 43 |
#include "include/private/base/SkFloatingPoint.h" |
| 44 |
#include "include/private/base/SkTo.h" |
| 45 |
#include "src/base/SkArenaAlloc.h" |
| 46 |
#include "src/base/SkVx.h" |
| 47 |
#include "src/core/SkBlendModePriv.h" |
| 48 |
#include "src/core/SkBlenderBase.h" |
| 49 |
#include "src/core/SkImageFilterTypes.h" // IWYU pragma: keep |
| 50 |
#include "src/core/SkPaintPriv.h" |
| 51 |
#include "src/core/SkPathPriv.h" |
| 52 |
#include "src/core/SkRRectPriv.h" |
| 53 |
#include "src/core/SkRectPriv.h" |
| 54 |
#include "src/core/SkSpecialImage.h" |
| 55 |
#include "src/core/SkStrikeCache.h" |
| 56 |
#include "src/core/SkTraceEvent.h" |
| 57 |
#include "src/core/SkVerticesPriv.h" |
| 58 |
#include "src/gpu/AtlasTypes.h" |
| 59 |
#include "src/gpu/BlurUtils.h" |
| 60 |
#include "src/gpu/SkBackingFit.h" |
| 61 |
#include "src/gpu/Swizzle.h" |
| 62 |
#include "src/gpu/TiledTextureUtils.h" |
| 63 |
#include "src/gpu/graphite/AtlasProvider.h" |
| 64 |
#include "src/gpu/graphite/Caps.h" |
| 65 |
#include "src/gpu/graphite/ContextOptionsPriv.h" |
| 66 |
#include "src/gpu/graphite/ContextPriv.h" |
| 67 |
#include "src/gpu/graphite/ContextUtils.h" |
| 68 |
#include "src/gpu/graphite/DrawContext.h" |
| 69 |
#include "src/gpu/graphite/DrawList.h" |
| 70 |
#include "src/gpu/graphite/DrawParams.h" |
| 71 |
#include "src/gpu/graphite/DrawTypes.h" |
| 72 |
#include "src/gpu/graphite/Image_Base_Graphite.h" |
| 73 |
#include "src/gpu/graphite/Image_Graphite.h" |
| 74 |
#include "src/gpu/graphite/KeyContext.h" |
| 75 |
#include "src/gpu/graphite/Log.h" |
| 76 |
#include "src/gpu/graphite/PaintParams.h" |
| 77 |
#include "src/gpu/graphite/PathAtlas.h" |
| 78 |
#include "src/gpu/graphite/RasterPathAtlas.h" |
| 79 |
#include "src/gpu/graphite/RecorderPriv.h" |
| 80 |
#include "src/gpu/graphite/Renderer.h" |
| 81 |
#include "src/gpu/graphite/RendererProvider.h" |
| 82 |
#include "src/gpu/graphite/SpecialImage_Graphite.h" |
| 83 |
#include "src/gpu/graphite/TextureFormat.h" |
| 84 |
#include "src/gpu/graphite/TextureInfoPriv.h" |
| 85 |
#include "src/gpu/graphite/TextureProxy.h" |
| 86 |
#include "src/gpu/graphite/TextureProxyView.h" |
| 87 |
#include "src/gpu/graphite/TextureUtils.h" |
| 88 |
#include "src/gpu/graphite/geom/AnalyticBlurMask.h" |
| 89 |
#include "src/gpu/graphite/geom/BoundsManager.h" |
| 90 |
#include "src/gpu/graphite/geom/CoverageMaskShape.h" |
| 91 |
#include "src/gpu/graphite/geom/EdgeAAQuad.h" |
| 92 |
#include "src/gpu/graphite/geom/Geometry.h" |
| 93 |
#include "src/gpu/graphite/geom/IntersectionTree.h" |
| 94 |
#include "src/gpu/graphite/geom/NonMSAAClip.h" |
| 95 |
#include "src/gpu/graphite/geom/Shape.h" |
| 96 |
#include "src/gpu/graphite/geom/SubRunData.h" |
| 97 |
#include "src/gpu/graphite/geom/Transform.h" |
| 98 |
#include "src/gpu/graphite/task/Task.h" |
| 99 |
#include "src/gpu/graphite/task/UploadTask.h" |
| 100 |
#include "src/image/SkImage_Base.h" |
| 101 |
#include "src/text/gpu/GlyphVector.h" |
| 102 |
#include "src/text/gpu/SlugImpl.h" |
| 103 |
#include "src/text/gpu/SubRunContainer.h" |
| 104 |
#include "src/text/gpu/TextBlobRedrawCoordinator.h" |
| 105 |
#include "src/text/gpu/VertexFiller.h" |
| 106 |
|
| 107 |
#include <algorithm> |
| 108 |
#include <atomic> |
| 109 |
#include <cstddef> |
| 110 |
#include <functional> |
| 111 |
#include <optional> |
| 112 |
#include <string> |
| 113 |
#include <tuple> |
| 114 |
#include <unordered_map> |
| 115 |
#include <vector> |
| 116 |
|
| 117 |
using RescaleGamma = SkImage::RescaleGamma; |
| 118 |
using RescaleMode = SkImage::RescaleMode; |
| 119 |
using ReadPixelsCallback = SkImage::ReadPixelsCallback; |
| 120 |
using ReadPixelsContext = SkImage::ReadPixelsContext; |
| 121 |
|
| 122 |
#if defined(GPU_TEST_UTILS) |
| 123 |
int gOverrideMaxTextureSizeGraphite = 0; |
| 124 |
// Allows tests to check how many tiles were drawn on the most recent call to |
| 125 |
// Device::drawAsTiledImageRect. This is an atomic because we can write to it from |
| 126 |
// multiple threads during "normal" operations. However, the tests that actually |
| 127 |
// read from it are done single-threaded. |
| 128 |
std::atomic<int> gNumTilesDrawnGraphite{0}; |
| 129 |
#endif |
| 130 |
|
| 131 |
namespace skgpu::graphite { |
| 132 |
|
| 133 |
class Recording; |
| 134 |
enum class TextureFormat : uint8_t; |
| 135 |
|
| 136 |
#define ASSERT_SINGLE_OWNER SkASSERT(fRecorder); SKGPU_ASSERT_SINGLE_OWNER(fRecorder->singleOwner()) |
| 137 |
|
| 138 |
namespace { |
| 139 |
|
| 140 |
const SkStrokeRec& DefaultFillStyle() { |
| 141 |
static const SkStrokeRec kFillStyle(SkStrokeRec::kFill_InitStyle); |
| 142 |
return kFillStyle; |
| 143 |
} |
| 144 |
|
| 145 |
/** If the paint can be reduced to a solid flood-fill, determine the correct color to fill with. */ |
| 146 |
std::optional<SkColor4f> extract_paint_color(const PaintParams& paint, |
| 147 |
const SkColorInfo& dstColorInfo) { |
| 148 |
SkBlendMode bm = paint.finalBlendMode(); |
| 149 |
// Since we don't depend on the dst, a dst-out blend mode implies source is |
| 150 |
// opaque, which causes dst-out to behave like clear. |
| 151 |
if (bm == SkBlendMode::kClear || bm == SkBlendMode::kDstOut) { |
| 152 |
return SkColors::kTransparent; |
| 153 |
} |
| 154 |
|
| 155 |
// PaintParams has already consolidated constant shaders or images and applied color filters to |
| 156 |
// constant input colors. If the paint still has any of those fields, then we can't extract it. |
| 157 |
if (paint.shader() || paint.imageShader() || paint.colorFilter()) { |
| 158 |
return std::nullopt; |
| 159 |
} |
| 160 |
|
| 161 |
// However, PaintParams converted the color in sRGB and we need to return this in the |
| 162 |
// destination color space. |
| 163 |
return PaintParams::Color4fPrepForDst(paint.color(), dstColorInfo); |
| 164 |
} |
| 165 |
|
| 166 |
// Returns a local rect that has been adjusted such that when it's rasterized with `localToDevice` |
| 167 |
// it will be pixel aligned. If this adjustment is not possible (due to transform type or precision) |
| 168 |
// then this returns the original local rect unmodified. |
| 169 |
// |
| 170 |
// If `strokeWidth` is null, it's assumed to be a filled rectangle. If it's not null, on input it |
| 171 |
// should hold the stroke width (or 0 for a hairline). After this returns, the stroke width may |
| 172 |
// have been adjusted so that outer and inner stroked edges are pixel aligned (in which case the |
| 173 |
// underlying rectangle geometry probably won't be pixel aligned). |
| 174 |
// |
| 175 |
// A best effort is made to align the stroke edges when there's a non-uniform scale factor that |
| 176 |
// prevents exactly aligning both X and Y axes. |
| 177 |
Rect snap_rect_to_pixels(const Transform& localToDevice, |
| 178 |
const Rect& rect, |
| 179 |
float* strokeWidth=nullptr) { |
| 180 |
if (localToDevice.type() > Transform::Type::kRectStaysRect) { |
| 181 |
return rect; |
| 182 |
} |
| 183 |
|
| 184 |
Rect snappedDeviceRect; |
| 185 |
if (!strokeWidth) { |
| 186 |
// Just a fill, use round() to emulate non-AA rasterization (vs. roundOut() to get the |
| 187 |
// covering bounds). This matches how ClipStack treats clipRects with PixelSnapping::kYes. |
| 188 |
snappedDeviceRect = localToDevice.mapRect(rect).round(); |
| 189 |
} else if (strokeWidth) { |
| 190 |
if (*strokeWidth == 0.f) { |
| 191 |
// Hairline case needs to be outset by 1/2 device pixels *before* rounding, and then |
| 192 |
// inset by 1/2px to get the base shape while leaving the stroke width as 0. |
| 193 |
snappedDeviceRect = localToDevice.mapRect(rect); |
| 194 |
snappedDeviceRect.outset(0.5f).round().inset(0.5f); |
| 195 |
} else { |
| 196 |
// For regular strokes, outset by the stroke radius *before* mapping to device space, |
| 197 |
// and then round. |
| 198 |
snappedDeviceRect = localToDevice.mapRect(rect.makeOutset(0.5f*(*strokeWidth))).round(); |
| 199 |
|
| 200 |
// devScales.x() holds scale factor affecting device-space X axis (so max of |m00| or |
| 201 |
// |m01|) and y() holds the device Y axis scale (max of |m10| or |m11|). |
| 202 |
skvx::float2 devScales = max(abs(skvx::float2(localToDevice.matrix().rc(0,0), |
| 203 |
localToDevice.matrix().rc(1,0))), |
| 204 |
abs(skvx::float2(localToDevice.matrix().rc(0,1), |
| 205 |
localToDevice.matrix().rc(1,1)))); |
| 206 |
skvx::float2 devStrokeWidth = max(round(*strokeWidth * devScales), 1.f); |
| 207 |
|
| 208 |
// Prioritize the axis that has the largest device-space radius (any error from a |
| 209 |
// non-uniform scale factor will go into the inner edge of the opposite axis). |
| 210 |
// During animating scale factors, preserving the large axis leads to better behavior. |
| 211 |
if (devStrokeWidth.x() > devStrokeWidth.y()) { |
| 212 |
*strokeWidth = devStrokeWidth.x() / devScales.x(); |
| 213 |
} else { |
| 214 |
*strokeWidth = devStrokeWidth.y() / devScales.y(); |
| 215 |
} |
| 216 |
|
| 217 |
snappedDeviceRect.inset(0.5f * devScales * (*strokeWidth)); |
| 218 |
} |
| 219 |
} |
| 220 |
|
| 221 |
// Map back to local space so that it can be drawn with appropriate coord interpolation. |
| 222 |
Rect snappedLocalRect = localToDevice.inverseMapRect(snappedDeviceRect); |
| 223 |
// If the transform has an extreme scale factor or large translation, it's possible for floating |
| 224 |
// point precision to round `snappedLocalRect` in such a way that re-transforming it by the |
| 225 |
// local-to-device matrix no longer matches the expected device bounds. |
| 226 |
if (snappedDeviceRect.nearlyEquals(localToDevice.mapRect(snappedLocalRect))) { |
| 227 |
return snappedLocalRect; |
| 228 |
} else { |
| 229 |
// In this case we will just return the original geometry and the pixels will show |
| 230 |
// fractional coverage. |
| 231 |
return rect; |
| 232 |
} |
| 233 |
} |
| 234 |
|
| 235 |
// If possible, snaps `dstRect` such that its device-space transformation lands on pixel bounds, |
| 236 |
// and then updates `srcRect` to match the original src-to-dst coordinate mapping. |
| 237 |
void snap_src_and_dst_rect_to_pixels(const Transform& localToDevice, |
| 238 |
SkRect* srcRect, |
| 239 |
SkRect* dstRect) { |
| 240 |
if (localToDevice.type() > Transform::Type::kRectStaysRect) { |
| 241 |
return; |
| 242 |
} |
| 243 |
|
| 244 |
// Assume snapping will succeed and always update 'src' to match; in the event snapping |
| 245 |
// returns the original dst rect, then the recalculated src rect is a no-op. |
| 246 |
SkMatrix dstToSrc = SkMatrix::RectToRectOrIdentity(*dstRect, *srcRect); |
| 247 |
*dstRect = snap_rect_to_pixels(localToDevice, *dstRect).asSkRect(); |
| 248 |
*srcRect = dstToSrc.mapRect(*dstRect); |
| 249 |
} |
| 250 |
|
| 251 |
// Returns the inner bounds of `geometry` that is known to have full coverage. This does not worry |
| 252 |
// about identifying draws that are equivalent pixel aligned and thus entirely full coverage, as |
| 253 |
// that should have been caught earlier and used a coverage-less renderer from the beginning. |
| 254 |
// |
| 255 |
// An empty Rect is returned if there is no available inner bounds, or if it's not worth performing. |
| 256 |
Rect get_inner_bounds(const Geometry& geometry, const Transform& localToDevice) { |
| 257 |
auto applyAAInset = [&](Rect rect) { |
| 258 |
// If the aa inset is too large, rect becomes empty and the inner bounds draw is |
| 259 |
// automatically skipped |
| 260 |
float aaInset = localToDevice.localAARadius(rect); |
| 261 |
rect.inset(aaInset); |
| 262 |
// Only add a second draw if it will have a reasonable number of covered pixels; otherwise |
| 263 |
// we are just adding draws to sort and pipelines to switch around. |
| 264 |
static constexpr float kInnerFillArea = 64*64; |
| 265 |
// Approximate the device-space area based on the minimum scale factor of the transform. |
| 266 |
float scaleFactor = sk_ieee_float_divide(1.f, aaInset); |
| 267 |
return scaleFactor*rect.area() >= kInnerFillArea ? rect : Rect::InfiniteInverted(); |
| 268 |
}; |
| 269 |
|
| 270 |
if (geometry.isEdgeAAQuad()) { |
| 271 |
const EdgeAAQuad& quad = geometry.edgeAAQuad(); |
| 272 |
if (quad.isRect()) { |
| 273 |
return applyAAInset(quad.bounds()); |
| 274 |
} |
| 275 |
// else currently we don't have a function to calculate the largest interior axis aligned |
| 276 |
// bounding box of a quadrilateral so skip the inner fill draw. |
| 277 |
} else if (geometry.isShape()) { |
| 278 |
const Shape& shape = geometry.shape(); |
| 279 |
if (shape.isRect()) { |
| 280 |
return applyAAInset(shape.rect()); |
| 281 |
} else if (shape.isRRect()) { |
| 282 |
return applyAAInset(SkRRectPriv::InnerBounds(shape.rrect())); |
| 283 |
} |
| 284 |
} |
| 285 |
|
| 286 |
return Rect::InfiniteInverted(); |
| 287 |
} |
| 288 |
|
| 289 |
SkIRect rect_to_pixelbounds(const Rect& r) { |
| 290 |
return r.makeRoundOut().asSkIRect(); |
| 291 |
} |
| 292 |
|
| 293 |
bool is_pixel_aligned(const Rect& r, const Transform& t) { |
| 294 |
if (t.type() <= Transform::Type::kRectStaysRect) { |
| 295 |
Rect devRect = t.mapRect(r); |
| 296 |
return devRect.nearlyEquals(devRect.makeRound(), Shape::kDefaultPixelTolerance); |
| 297 |
} |
| 298 |
|
| 299 |
return false; |
| 300 |
} |
| 301 |
|
| 302 |
bool is_simple_shape(const Shape& shape, const Transform& localToDevice, SkStrokeRec::Style type) { |
| 303 |
if (shape.isFloodFill()) { |
| 304 |
return true; // Always supported |
| 305 |
} else if (!shape.inverted() && type != SkStrokeRec::kStrokeAndFill_Style) { |
| 306 |
// A filled line renders nothing but that should be caught earlier, so the actual branches |
| 307 |
// in this function can be simplified. |
| 308 |
SkASSERT(!shape.isLine() || type != SkStrokeRec::kFill_Style); |
| 309 |
|
| 310 |
if (shape.isRRect() && type == SkStrokeRec::kStroke_Style) { |
| 311 |
// Non-hairline stroked round rects require the corner radii to be circular to be |
| 312 |
// compatible with the shared Renderer. |
| 313 |
const float tol = |
| 314 |
localToDevice.localAARadius(shape.bounds()) * Shape::kDefaultPixelTolerance; |
| 315 |
return SkRRectPriv::AllCornersRelativelyCircular(shape.rrect(), tol); |
| 316 |
} else if (shape.isRRect() || shape.isRect() || shape.isLine()) { |
| 317 |
// There are no restrictions on filled or hairline [r]rects and lines. |
| 318 |
return true; |
| 319 |
} // Fallthrough |
| 320 |
} |
| 321 |
|
| 322 |
// Requires path rendering |
| 323 |
return false; |
| 324 |
} |
| 325 |
|
| 326 |
class ScopedDrawBuilder { |
| 327 |
public: |
| 328 |
explicit ScopedDrawBuilder(Recorder* recorder) |
| 329 |
: fRecorder(recorder), |
| 330 |
fKeyAndDataBuilder(fRecorder->priv().popOrCreateKeyAndDataBuilder()) { |
| 331 |
SkASSERT(fKeyAndDataBuilder); |
| 332 |
SkDEBUGCODE(this->gatherer()->checkReset()); |
| 333 |
SkDEBUGCODE(this->builder()->checkReset()); |
| 334 |
} |
| 335 |
|
| 336 |
~ScopedDrawBuilder() { |
| 337 |
SkASSERT(fKeyAndDataBuilder && fRecorder); |
| 338 |
// The PipelineDataGatherer must be reset before being returned to the pool for reuse. |
| 339 |
this->gatherer()->resetForDraw(); |
| 340 |
fRecorder->priv().pushKeyAndDataBuilder(std::move(fKeyAndDataBuilder)); |
| 341 |
} |
| 342 |
|
| 343 |
PipelineDataGatherer* gatherer() { return &fKeyAndDataBuilder->first; } |
| 344 |
PaintParamsKeyBuilder* builder() { return &fKeyAndDataBuilder->second; } |
| 345 |
|
| 346 |
ScopedDrawBuilder(const ScopedDrawBuilder&) = delete; |
| 347 |
ScopedDrawBuilder& operator=(const ScopedDrawBuilder&) = delete; |
| 348 |
|
| 349 |
private: |
| 350 |
Recorder* fRecorder; |
| 351 |
std::unique_ptr<KeyAndDataBuilder> fKeyAndDataBuilder; |
| 352 |
}; |
| 353 |
|
| 354 |
} // anonymous namespace |
| 355 |
|
| 356 |
/** |
| 357 |
* IntersectionTreeSet controls multiple IntersectionTrees to organize all add rectangles into |
| 358 |
* disjoint sets. For a given CompressedPaintersOrder and bounds, it returns the smallest |
| 359 |
* DisjointStencilIndex that guarantees the bounds are disjoint from all other draws that use the |
| 360 |
* same painters order and stencil index. |
| 361 |
*/ |
| 362 |
class Device::IntersectionTreeSet { |
| 363 |
public: |
| 364 |
IntersectionTreeSet() = default; |
| 365 |
|
| 366 |
DisjointStencilIndex add(CompressedPaintersOrder drawOrder, Rect rect) { |
| 367 |
auto& trees = fTrees[drawOrder]; |
| 368 |
DisjointStencilIndex stencil = DisjointStencilIndex::First(); |
| 369 |
for (auto&& tree : trees) { |
| 370 |
if (tree->add(rect)) { |
| 371 |
return stencil; |
| 372 |
} |
| 373 |
stencil = stencil.next(); // advance to the next tree's index |
| 374 |
} |
| 375 |
|
| 376 |
// If here, no existing intersection tree can hold the rect so add a new one |
| 377 |
SkASSERT(stencil != DrawOrder::kUnassigned); |
| 378 |
IntersectionTree* newTree = this->makeTree(); |
| 379 |
SkAssertResult(newTree->add(rect)); |
| 380 |
trees.push_back(newTree); |
| 381 |
return stencil; |
| 382 |
} |
| 383 |
|
| 384 |
void reset() { |
| 385 |
fTrees.clear(); |
| 386 |
fTreeStore.reset(); |
| 387 |
} |
| 388 |
|
| 389 |
private: |
| 390 |
struct Hash { |
| 391 |
size_t operator()(const CompressedPaintersOrder& o) const noexcept { return o.bits(); } |
| 392 |
}; |
| 393 |
|
| 394 |
IntersectionTree* makeTree() { |
| 395 |
return fTreeStore.make<IntersectionTree>(); |
| 396 |
} |
| 397 |
|
| 398 |
// Each compressed painters order defines a barrier around draws so each order's set of draws |
| 399 |
// are independent, even if they may intersect. Within each order, the list of trees holds the |
| 400 |
// IntersectionTrees representing each disjoint set. |
| 401 |
// TODO: This organization of trees is logically convenient but may need to be optimized based |
| 402 |
// on real world data (e.g. how sparse is the map, how long is each vector of trees,...) |
| 403 |
std::unordered_map<CompressedPaintersOrder, std::vector<IntersectionTree*>, Hash> fTrees; |
| 404 |
SkSTArenaAllocWithReset<4 * sizeof(IntersectionTree)> fTreeStore; |
| 405 |
}; |
| 406 |
|
| 407 |
sk_sp<Device> Device::Make(Recorder* recorder, |
| 408 |
const SkImageInfo& ii, |
| 409 |
skgpu::Budgeted budgeted, |
| 410 |
Mipmapped mipmapped, |
| 411 |
SkBackingFit backingFit, |
| 412 |
const SkSurfaceProps& props, |
| 413 |
LoadOp initialLoadOp, |
| 414 |
std::string_view label, |
| 415 |
bool registerWithRecorder) { |
| 416 |
SkASSERT(!(mipmapped == Mipmapped::kYes && backingFit == SkBackingFit::kApprox)); |
| 417 |
if (!recorder) { |
| 418 |
return nullptr; |
| 419 |
} |
| 420 |
|
| 421 |
const Caps* caps = recorder->priv().caps(); |
| 422 |
SkISize backingDimensions = backingFit == SkBackingFit::kApprox ? GetApproxSize(ii.dimensions()) |
| 423 |
: ii.dimensions(); |
| 424 |
auto textureInfo = caps->getDefaultSampledTextureInfo(ii.colorType(), |
| 425 |
mipmapped, |
| 426 |
recorder->priv().isProtected(), |
| 427 |
Renderable::kYes); |
| 428 |
|
| 429 |
return Make(recorder, |
| 430 |
TextureProxy::Make(caps, recorder->priv().resourceProvider(), |
| 431 |
backingDimensions, textureInfo, label, budgeted), |
| 432 |
ii.dimensions(), |
| 433 |
ii.colorInfo(), |
| 434 |
props, |
| 435 |
initialLoadOp, |
| 436 |
registerWithRecorder); |
| 437 |
} |
| 438 |
|
| 439 |
sk_sp<Device> Device::Make(Recorder* recorder, |
| 440 |
sk_sp<TextureProxy> target, |
| 441 |
SkISize deviceSize, |
| 442 |
const SkColorInfo& colorInfo, |
| 443 |
const SkSurfaceProps& props, |
| 444 |
LoadOp initialLoadOp, |
| 445 |
bool registerWithRecorder) { |
| 446 |
if (!recorder || !target) { |
| 447 |
return nullptr; |
| 448 |
} |
| 449 |
|
| 450 |
// DrawContext::Make ensures `target` can be rendered into, but if the path strategy might |
| 451 |
// require MSAA, then we need to make sure a multisampled attachment can also be created later. |
| 452 |
// - This would also apply for compute renderers that have to write directly to `target`, but |
| 453 |
// the current versions of compute render into separate compute-compatible textures instead. |
| 454 |
const Caps* caps = recorder->priv().caps(); |
| 455 |
switch (recorder->priv().rendererProvider()->pathRendererStrategy()) { |
| 456 |
case PathRendererStrategy::kTessellationAndSmallAtlas: |
| 457 |
[[fallthrough]]; |
| 458 |
case PathRendererStrategy::kTessellation: |
| 459 |
if (caps->getCompatibleMSAASampleCount(target->textureInfo()) <= SampleCount::k1) { |
| 460 |
return nullptr; |
| 461 |
} |
| 462 |
break; |
| 463 |
|
| 464 |
case PathRendererStrategy::kRasterAtlas: |
| 465 |
case PathRendererStrategy::kComputeAnalyticAA: |
| 466 |
case PathRendererStrategy::kComputeMSAA16: |
| 467 |
case PathRendererStrategy::kComputeMSAA8: |
| 468 |
// No additional support required |
| 469 |
break; |
| 470 |
} |
| 471 |
|
| 472 |
sk_sp<DrawContext> dc = DrawContext::Make(recorder->priv().caps(), |
| 473 |
std::move(target), |
| 474 |
deviceSize, |
| 475 |
colorInfo, |
| 476 |
props); |
| 477 |
if (!dc) { |
| 478 |
return nullptr; |
| 479 |
} else if (initialLoadOp == LoadOp::kClear) { |
| 480 |
dc->clear(SkColors::kTransparent); |
| 481 |
} else if (initialLoadOp == LoadOp::kDiscard) { |
| 482 |
dc->discard(); |
| 483 |
} // else kLoad is the default initial op for a DrawContext |
| 484 |
|
| 485 |
sk_sp<Device> device{new Device(recorder, std::move(dc))}; |
| 486 |
if (registerWithRecorder) { |
| 487 |
// We don't register the device with the recorder until after the constructor has returned. |
| 488 |
recorder->registerDevice(device); |
| 489 |
} else { |
| 490 |
// Since it's not registered, it should go out of scope before nextRecordingID() changes |
| 491 |
// from what is saved to fScopedRecordingID. |
| 492 |
SkDEBUGCODE(device->fScopedRecordingID = recorder->priv().nextRecordingID();) |
| 493 |
} |
| 494 |
return device; |
| 495 |
} |
| 496 |
|
| 497 |
// These default tuning numbers for the HybridBoundsManager were chosen from looking at performance |
| 498 |
// and accuracy curves produced by the BoundsManagerBench for random draw bounding boxes. This |
| 499 |
// config will use brute force for the first 64 draw calls to the Device and then switch to a grid |
| 500 |
// that is dynamically sized to produce cells that are 16x16, up to a grid that's 32x32 cells. |
| 501 |
// This seemed like a sweet spot balancing accuracy for low-draw count surfaces and overhead for |
| 502 |
// high-draw count and high-resolution surfaces. With the 32x32 grid limit, cell size will increase |
| 503 |
// above 16px when the surface dimension goes above 512px. |
| 504 |
// TODO: These could be exposed as context options or surface options, and we may want to have |
| 505 |
// different strategies in place for a base device vs. a layer's device. |
| 506 |
static constexpr int kGridCellSize = 16; |
| 507 |
static constexpr int kMaxBruteForceN = 64; |
| 508 |
static constexpr int kMaxGridSize = 32; |
| 509 |
|
| 510 |
Device::Device(Recorder* recorder, sk_sp<DrawContext> dc) |
| 511 |
: SkDevice(dc->imageInfo(), dc->surfaceProps()) |
| 512 |
, fRecorder(recorder) |
| 513 |
, fDC(std::move(dc)) |
| 514 |
, fClip(this) |
| 515 |
, fColorDepthBoundsManager(std::make_unique<HybridBoundsManager>( |
| 516 |
fDC->imageInfo().dimensions(), kGridCellSize, kMaxBruteForceN, kMaxGridSize)) |
| 517 |
, fDisjointStencilSet(std::make_unique<IntersectionTreeSet>()) |
| 518 |
, fCachedLocalToDevice(SkM44()) |
| 519 |
, fCurrentDepth(DrawOrder::kClearDepth) |
| 520 |
, fSubRunControl(recorder->priv().caps()->getSubRunControl( |
| 521 |
fDC->surfaceProps().isUseDeviceIndependentFonts())) { |
| 522 |
SkASSERT(SkToBool(fDC) && SkToBool(fRecorder)); |
| 523 |
} |
| 524 |
|
| 525 |
Device::~Device() { |
| 526 |
// The Device should have been marked immutable before it's destroyed, or the Recorder was the |
| 527 |
// last holder of a reference to it and de-registered the device as part of its cleanup. |
| 528 |
// However, if the Device was not registered with the recorder (i.e. a scratch device) we don't |
| 529 |
// require that its recorder be adandoned. Scratch devices must either have been marked |
| 530 |
// immutable or be destroyed before the recorder has been snapped. |
| 531 |
SkASSERT(!fRecorder || fScopedRecordingID != 0); |
| 532 |
#if defined(SK_DEBUG) |
| 533 |
if (fScopedRecordingID != 0 && fRecorder) { |
| 534 |
SkASSERT(fScopedRecordingID == fRecorder->priv().nextRecordingID()); |
| 535 |
} |
| 536 |
// else it wasn't a scratch device, or it was a scratch device that was marked immutable so its |
| 537 |
// lifetime was validated when setImmutable() was called. |
| 538 |
#endif |
| 539 |
} |
| 540 |
|
| 541 |
#if defined(GPU_TEST_UTILS) |
| 542 |
|
| 543 |
int Device::testingOnly_pendingRenderSteps() const { |
| 544 |
return fDC->pendingRenderSteps(); |
| 545 |
} |
| 546 |
|
| 547 |
#endif |
| 548 |
|
| 549 |
void Device::setImmutable() { |
| 550 |
if (fRecorder) { |
| 551 |
// Push any pending work to the Recorder now. setImmutable() is only called by the |
| 552 |
// destructor of a client-owned Surface, or explicitly in layer/filtering workflows. In |
| 553 |
// both cases this is restricted to the Recorder's thread. This is in contrast to ~Device(), |
| 554 |
// which might be called from another thread if it was linked to an Image used in multiple |
| 555 |
// recorders. |
| 556 |
this->flushPendingWork(/*drawContext=*/nullptr); |
| 557 |
fRecorder->deregisterDevice(this); |
| 558 |
// Abandoning the recorder ensures that there are no further operations that can be recorded |
| 559 |
// and is relied on by Image::notifyInUse() to detect when it can unlink from a Device. |
| 560 |
this->abandonRecorder(); |
| 561 |
} |
| 562 |
} |
| 563 |
|
| 564 |
bool Device::notifyInUse(Recorder* recorder, DrawContext* drawContext) { |
| 565 |
if (this->isScratchDevice()) { |
| 566 |
if (fLastTask) { |
| 567 |
// Increment the pending read count for the device's target |
| 568 |
recorder->priv().addPendingRead(this->target()); |
| 569 |
if (drawContext) { |
| 570 |
// Add a reference to the device's drawTask to `drawContext` if that's provided. |
| 571 |
drawContext->recordDependency(fLastTask); |
| 572 |
} else { |
| 573 |
// If there's no `drawContext` this notify represents a copy, so for now append the |
| 574 |
// task to the root task list since that is where the subsequent copy task will go |
| 575 |
// as well. |
| 576 |
recorder->priv().add(fLastTask); |
| 577 |
} |
| 578 |
} else { |
| 579 |
// If there's no draw task yet, there are two possible scenarios: |
| 580 |
// |
| 581 |
// 1) the device is being drawn into a child scratch device (backdrop filter or |
| 582 |
// init-from-prev layer), and the child will later on be drawn back into the device's |
| 583 |
// `drawContext`. In this case `device` should already have performed an internal |
| 584 |
// flush and have no pending work, and not yet be marked immutable. The correct |
| 585 |
// action at this point in time is to do nothing: the final task order in the |
| 586 |
// device's DrawTask will be pre-notified tasks into the device's target, then the |
| 587 |
// child's DrawTask when it's drawn back into `device`, and then any post tasks that |
| 588 |
// further modify the `device`'s target. |
| 589 |
// 2) the scratch device was flushed to a drawContext's local task list, resulting in no |
| 590 |
// pending work but also no lastTask. The correct action is again to do nothing. In |
| 591 |
// this case, it is also possible that the device was not registered with the |
| 592 |
// recorder. |
| 593 |
SkASSERT(!fRecorder || fRecorder == recorder); |
| 594 |
} |
| 595 |
|
| 596 |
// Scratch devices are often already marked immutable, but they are also the way in which |
| 597 |
// Image finds the last snapped DrawTask so we don't unlink scratch devices. The scratch |
| 598 |
// image view will be short-lived as well, or the device will transition to a non-scratch |
| 599 |
// device in a future Recording and then it will be unlinked then. Thus, we always return |
| 600 |
// false for scratch devices so they are not unlinked from their images. |
| 601 |
return false; |
| 602 |
} else { |
| 603 |
// Automatic flushing of image views only happens when mixing reads and writes on the |
| 604 |
// originating Recorder. Draws of the view on another Recorder will always see the texture |
| 605 |
// content dependent on how Recordings are inserted. |
| 606 |
if (fRecorder == recorder) { |
| 607 |
// Non-scratch devices push their tasks to the root task list to maintain an order |
| 608 |
// consistent with the client-triggering actions. Because of this, there's no need to |
| 609 |
// add references to the `drawContext` that the device is being drawn into. |
| 610 |
this->flushPendingWork(/*drawContext=*/nullptr); |
| 611 |
|
| 612 |
if (drawContext) { |
| 613 |
// But if we are being drawn into another context, remember that there is an |
| 614 |
// outstanding dependency on the current state of this device, in which case it's |
| 615 |
// next flush must also flush those other devices before its new tasks are added. |
| 616 |
fMustFlushDependencies = true; |
| 617 |
} |
| 618 |
} |
| 619 |
// Return true (to unlink with the image) if the non-scratch surface is immutable since this |
| 620 |
// Device cannot record any more commands that will modify its texture. |
| 621 |
return !SkToBool(fRecorder) || this->unique(); |
| 622 |
} |
| 623 |
} |
| 624 |
|
| 625 |
bool Device::hasPendingReads(const TextureProxy* texture) const { |
| 626 |
return fRecorder && fDC->readsTexture(texture); |
| 627 |
} |
| 628 |
|
| 629 |
const Transform& Device::localToDeviceTransform() { |
| 630 |
if (this->checkLocalToDeviceDirty()) { |
| 631 |
fCachedLocalToDevice = Transform{this->localToDevice44()}; |
| 632 |
} |
| 633 |
return fCachedLocalToDevice; |
| 634 |
} |
| 635 |
|
| 636 |
SkStrikeDeviceInfo Device::strikeDeviceInfo() const { |
| 637 |
return {this->surfaceProps(), this->scalerContextFlags(), &fSubRunControl}; |
| 638 |
} |
| 639 |
|
| 640 |
sk_sp<SkDevice> Device::createDevice(const CreateInfo& info, const SkPaint*) { |
| 641 |
// TODO: Inspect the paint and create info to determine if there's anything that has to be |
| 642 |
// modified to support inline subpasses. |
| 643 |
SkSurfaceProps props = |
| 644 |
this->surfaceProps().cloneWithPixelGeometry(info.fPixelGeometry); |
| 645 |
|
| 646 |
// Skia's convention is to only clear a device if it is non-opaque. |
| 647 |
LoadOp initialLoadOp = info.fInfo.isOpaque() ? LoadOp::kDiscard : LoadOp::kClear; |
| 648 |
|
| 649 |
std::string label = this->target()->label(); |
| 650 |
if (label.empty()) { |
| 651 |
label = "ChildDevice"; |
| 652 |
} else { |
| 653 |
label += "_ChildDevice"; |
| 654 |
} |
| 655 |
|
| 656 |
return Make(fRecorder, |
| 657 |
info.fInfo, |
| 658 |
skgpu::Budgeted::kYes, |
| 659 |
Mipmapped::kNo, |
| 660 |
SkBackingFit::kApprox, |
| 661 |
props, |
| 662 |
initialLoadOp, |
| 663 |
label); |
| 664 |
} |
| 665 |
|
| 666 |
sk_sp<SkSurface> Device::makeSurface(const SkImageInfo& ii, const SkSurfaceProps& props) { |
| 667 |
return SkSurfaces::RenderTarget(fRecorder, ii, Mipmapped::kNo, &props); |
| 668 |
} |
| 669 |
|
| 670 |
// Although we have a drawContext here, we pass a nullptr to both flushPendingWork and Image::Copy |
| 671 |
// so that tasks end up on the root task list. |
| 672 |
sk_sp<Image> Device::makeImageCopy(const SkIRect& subset, |
| 673 |
Budgeted budgeted, |
| 674 |
Mipmapped mipmapped, |
| 675 |
SkBackingFit backingFit) { |
| 676 |
ASSERT_SINGLE_OWNER |
| 677 |
this->flushPendingWork(/*drawContext=*/nullptr); |
| 678 |
|
| 679 |
const SkColorInfo& colorInfo = this->imageInfo().colorInfo(); |
| 680 |
TextureProxyView srcView = this->readSurfaceView(); |
| 681 |
if (!srcView) { |
| 682 |
// readSurfaceView() returns an empty view when the target is not texturable. Create an |
| 683 |
// equivalent view for the blitting operation. |
| 684 |
Swizzle readSwizzle = fRecorder->priv().caps()->getReadSwizzle( |
| 685 |
colorInfo.colorType(), this->target()->textureInfo()); |
| 686 |
srcView = {sk_ref_sp(this->target()), readSwizzle}; |
| 687 |
} |
| 688 |
std::string label = this->target()->label(); |
| 689 |
if (label.empty()) { |
| 690 |
label = "CopyDeviceTexture"; |
| 691 |
} else { |
| 692 |
label += "_DeviceCopy"; |
| 693 |
} |
| 694 |
|
| 695 |
return Image::Copy(fRecorder, /*drawContext=*/nullptr, srcView, colorInfo, subset, budgeted, |
| 696 |
mipmapped, backingFit, label); |
| 697 |
} |
| 698 |
|
| 699 |
bool Device::onReadPixels(const SkPixmap& pm, int srcX, int srcY) { |
| 700 |
#if defined(GPU_TEST_UTILS) |
| 701 |
// This testing-only function should only be called before the Device has detached from its |
| 702 |
// Recorder, since it's accessed via the test-held Surface. |
| 703 |
ASSERT_SINGLE_OWNER |
| 704 |
if (Context* context = fRecorder->priv().context()) { |
| 705 |
// Add all previous commands generated to the command buffer. |
| 706 |
// If the client snaps later they'll only get post-read commands in their Recording, |
| 707 |
// but since they're doing a readPixels in the middle that shouldn't be unexpected. |
| 708 |
std::unique_ptr<Recording> recording = fRecorder->snap(); |
| 709 |
if (!recording) { |
| 710 |
return false; |
| 711 |
} |
| 712 |
InsertRecordingInfo info; |
| 713 |
info.fRecording = recording.get(); |
| 714 |
if (!context->insertRecording(info)) { |
| 715 |
return false; |
| 716 |
} |
| 717 |
return context->priv().readPixels(pm, fDC->target(), this->imageInfo(), srcX, srcY); |
| 718 |
} |
| 719 |
#endif |
| 720 |
// We have no access to a context to do a read pixels here. |
| 721 |
return false; |
| 722 |
} |
| 723 |
|
| 724 |
bool Device::onWritePixels(const SkPixmap& src, int x, int y) { |
| 725 |
ASSERT_SINGLE_OWNER |
| 726 |
// TODO: we may need to share this in a more central place to handle uploads |
| 727 |
// to backend textures |
| 728 |
|
| 729 |
const TextureProxy* target = fDC->target(); |
| 730 |
|
| 731 |
// TODO: add mipmap support for createBackendTexture |
| 732 |
|
| 733 |
if (src.colorType() == kUnknown_SkColorType) { |
| 734 |
return false; |
| 735 |
} |
| 736 |
|
| 737 |
// If one alpha type is unknown and the other isn't, it's too underspecified. |
| 738 |
if ((src.alphaType() == kUnknown_SkAlphaType) != |
| 739 |
(this->imageInfo().alphaType() == kUnknown_SkAlphaType)) { |
| 740 |
return false; |
| 741 |
} |
| 742 |
|
| 743 |
// TODO: canvas2DFastPath? |
| 744 |
|
| 745 |
if (!fRecorder->priv().caps()->supportsWritePixels(target->textureInfo())) { |
| 746 |
auto image = SkImages::RasterFromPixmap(src, nullptr, nullptr); |
| 747 |
image = SkImages::TextureFromImage(fRecorder, image.get()); |
| 748 |
if (!image) { |
| 749 |
return false; |
| 750 |
} |
| 751 |
|
| 752 |
SkPaint paint; |
| 753 |
paint.setBlendMode(SkBlendMode::kSrc); |
| 754 |
this->drawImageRect(image.get(), |
| 755 |
/*src=*/nullptr, |
| 756 |
SkRect::MakeXYWH(x, y, src.width(), src.height()), |
| 757 |
SkFilterMode::kNearest, |
| 758 |
paint, |
| 759 |
SkCanvas::kFast_SrcRectConstraint); |
| 760 |
return true; |
| 761 |
} |
| 762 |
|
| 763 |
// TODO: check for flips and either handle here or pass info to UploadTask |
| 764 |
|
| 765 |
// Determine rect to copy |
| 766 |
SkIRect dstRect = SkIRect::MakePtSize({x, y}, src.dimensions()); |
| 767 |
if (!target->isFullyLazy() && !dstRect.intersect(SkIRect::MakeSize(target->dimensions()))) { |
| 768 |
return false; |
| 769 |
} |
| 770 |
|
| 771 |
// Set up copy location |
| 772 |
const void* addr = src.addr(dstRect.fLeft - x, dstRect.fTop - y); |
| 773 |
std::vector<MipLevel> levels; |
| 774 |
levels.push_back({addr, src.rowBytes()}); |
| 775 |
|
| 776 |
// The writePixels() still respects painter's order, so flush everything to tasks before this |
| 777 |
// recording the upload for the pixel data. |
| 778 |
this->internalFlush(); |
| 779 |
// The new upload will be executed before any new draws are recorded and also ensures that |
| 780 |
// the next call to flushDeviceToRecorder() will produce a non-null DrawTask. If this Device's |
| 781 |
// target is mipmapped, mipmap generation tasks will be added automatically at that point. |
| 782 |
const UploadSource uploadSource = UploadSource::Make(fRecorder->priv().caps(), |
| 783 |
*fDC->refTarget(), |
| 784 |
src.info().colorInfo(), |
| 785 |
this->imageInfo().colorInfo(), |
| 786 |
levels, |
| 787 |
dstRect); |
| 788 |
if (!uploadSource.isValid()) { |
| 789 |
return false; |
| 790 |
} |
| 791 |
return fDC->recordUpload(fRecorder, |
| 792 |
fDC->refTarget(), |
| 793 |
src.info().colorInfo(), |
| 794 |
this->imageInfo().colorInfo(), |
| 795 |
uploadSource, |
| 796 |
dstRect, |
| 797 |
nullptr); |
| 798 |
} |
| 799 |
|
| 800 |
|
| 801 |
/////////////////////////////////////////////////////////////////////////////// |
| 802 |
|
| 803 |
bool Device::isClipAntiAliased() const { |
| 804 |
// All clips are AA'ed unless it's wide-open, empty, or a device-rect with integer coordinates |
| 805 |
ClipStack::ClipState type = fClip.clipState(); |
| 806 |
if (type == ClipStack::ClipState::kWideOpen || type == ClipStack::ClipState::kEmpty) { |
| 807 |
return false; |
| 808 |
} else if (type == ClipStack::ClipState::kDeviceRect) { |
| 809 |
const ClipStack::Element rect = *fClip.begin(); |
| 810 |
SkASSERT(rect.fShape.isRect() && rect.fLocalToDevice.type() == Transform::Type::kIdentity); |
| 811 |
return rect.fShape.rect() != rect.fShape.rect().makeRoundOut(); |
| 812 |
} else { |
| 813 |
return true; |
| 814 |
} |
| 815 |
} |
| 816 |
|
| 817 |
SkIRect Device::devClipBounds() const { |
| 818 |
return rect_to_pixelbounds(fClip.conservativeBounds()); |
| 819 |
} |
| 820 |
|
| 821 |
// TODO: This is easy enough to support, but do we still need this API in Skia at all? |
| 822 |
void Device::android_utils_clipAsRgn(SkRegion* region) const { |
| 823 |
SkIRect bounds = this->devClipBounds(); |
| 824 |
// Assume wide open and then perform intersect/difference operations reducing the region |
| 825 |
region->setRect(bounds); |
| 826 |
const SkRegion deviceBounds(bounds); |
| 827 |
for (const ClipStack::Element& e : fClip) { |
| 828 |
SkRegion tmp; |
| 829 |
if (e.fShape.isRect() && e.fLocalToDevice.type() == Transform::Type::kIdentity) { |
| 830 |
tmp.setRect(rect_to_pixelbounds(e.fShape.rect())); |
| 831 |
} else { |
| 832 |
SkPath tmpPath = e.fShape.asPath().makeTransform(e.fLocalToDevice); |
| 833 |
tmp.setPath(tmpPath, deviceBounds); |
| 834 |
} |
| 835 |
|
| 836 |
region->op(tmp, (SkRegion::Op) e.fOp); |
| 837 |
} |
| 838 |
} |
| 839 |
|
| 840 |
void Device::clipRect(const SkRect& rect, SkClipOp op, bool aa) { |
| 841 |
SkASSERT(op == SkClipOp::kIntersect || op == SkClipOp::kDifference); |
| 842 |
auto snapping = aa ? ClipStack::PixelSnapping::kNo : ClipStack::PixelSnapping::kYes; |
| 843 |
fClip.clipShape(this->localToDeviceTransform(), Shape{rect}, op, snapping); |
| 844 |
} |
| 845 |
|
| 846 |
void Device::clipRRect(const SkRRect& rrect, SkClipOp op, bool aa) { |
| 847 |
SkASSERT(op == SkClipOp::kIntersect || op == SkClipOp::kDifference); |
| 848 |
auto snapping = aa ? ClipStack::PixelSnapping::kNo : ClipStack::PixelSnapping::kYes; |
| 849 |
fClip.clipShape(this->localToDeviceTransform(), Shape{rrect}, op, snapping); |
| 850 |
} |
| 851 |
|
| 852 |
void Device::clipPath(const SkPath& path, SkClipOp op, bool aa) { |
| 853 |
SkASSERT(op == SkClipOp::kIntersect || op == SkClipOp::kDifference); |
| 854 |
// TODO: Ensure all path inspection is handled here or in SkCanvas, and that non-AA rects as |
| 855 |
// paths are routed appropriately. |
| 856 |
// TODO: Must also detect paths that are lines so the clip stack can be set to empty |
| 857 |
fClip.clipShape(this->localToDeviceTransform(), Shape{path}, op); |
| 858 |
} |
| 859 |
|
| 860 |
void Device::onClipShader(sk_sp<SkShader> shader) { |
| 861 |
fClip.clipShader(std::move(shader)); |
| 862 |
} |
| 863 |
|
| 864 |
// TODO: Is clipRegion() on the deprecation chopping block. If not it should be... |
| 865 |
void Device::clipRegion(const SkRegion& globalRgn, SkClipOp op) { |
| 866 |
SkASSERT(op == SkClipOp::kIntersect || op == SkClipOp::kDifference); |
| 867 |
|
| 868 |
Transform globalToDevice{this->globalToDevice()}; |
| 869 |
|
| 870 |
if (globalRgn.isEmpty()) { |
| 871 |
fClip.clipShape(globalToDevice, Shape{}, op); |
| 872 |
} else if (globalRgn.isRect()) { |
| 873 |
fClip.clipShape(globalToDevice, Shape{SkRect::Make(globalRgn.getBounds())}, op, |
| 874 |
ClipStack::PixelSnapping::kYes); |
| 875 |
} else { |
| 876 |
// TODO: Can we just iterate the region and do non-AA rects for each chunk? |
| 877 |
SkPath path = globalRgn.getBoundaryPath(); |
| 878 |
fClip.clipShape(globalToDevice, Shape{path}, op); |
| 879 |
} |
| 880 |
} |
| 881 |
|
| 882 |
void Device::replaceClip(const SkIRect& rect) { |
| 883 |
// ReplaceClip() is currently not intended to be supported in Graphite since it's only used |
| 884 |
// for emulating legacy clip ops in Android Framework, and apps/devices that require that |
| 885 |
// should not use Graphite. However, if it needs to be supported, we could probably implement |
| 886 |
// it by: |
| 887 |
// 1. Flush all pending clip element depth draws. |
| 888 |
// 2. Draw a fullscreen rect to the depth attachment using a Z value greater than what's |
| 889 |
// been used so far. |
| 890 |
// 3. Make sure all future "unclipped" draws use this Z value instead of 0 so they aren't |
| 891 |
// sorted before the depth reset. |
| 892 |
// 4. Make sure all prior elements are inactive so they can't affect subsequent draws. |
| 893 |
// |
| 894 |
// For now, just ignore it. |
| 895 |
} |
| 896 |
|
| 897 |
/////////////////////////////////////////////////////////////////////////////// |
| 898 |
|
| 899 |
void Device::drawPaint(const SkPaint& paint) { |
| 900 |
ASSERT_SINGLE_OWNER |
| 901 |
|
| 902 |
Shape inverseFill; // defaults to empty |
| 903 |
inverseFill.setInverted(true); |
| 904 |
// An empty shape with an inverse fill completely floods the clip |
| 905 |
SkASSERT(inverseFill.isFloodFill()); |
| 906 |
|
| 907 |
this->drawGeometry(this->localToDeviceTransform(), |
| 908 |
Geometry(inverseFill), |
| 909 |
PaintParams(paint), |
| 910 |
DefaultFillStyle()); |
| 911 |
} |
| 912 |
|
| 913 |
void Device::drawRect(const SkRect& r, const SkPaint& paint) { |
| 914 |
Rect rectToDraw(r); |
| 915 |
SkStrokeRec style(paint); |
| 916 |
if (!paint.isAntiAlias()) { |
| 917 |
// Graphite assumes everything is anti-aliased. In the case of axis-aligned non-aa requested |
| 918 |
// rectangles, we snap the local geometry to land on pixel boundaries to emulate non-aa. |
| 919 |
if (style.isFillStyle()) { |
| 920 |
rectToDraw = snap_rect_to_pixels(this->localToDeviceTransform(), rectToDraw); |
| 921 |
} else { |
| 922 |
const bool strokeAndFill = style.getStyle() == SkStrokeRec::kStrokeAndFill_Style; |
| 923 |
float strokeWidth = style.getWidth(); |
| 924 |
rectToDraw = snap_rect_to_pixels(this->localToDeviceTransform(), |
| 925 |
rectToDraw, &strokeWidth); |
| 926 |
style.setStrokeStyle(strokeWidth, strokeAndFill); |
| 927 |
} |
| 928 |
} |
| 929 |
this->drawGeometryWithPathEffect(this->localToDeviceTransform(), |
| 930 |
Geometry(Shape(rectToDraw)), |
| 931 |
PaintParams(paint), |
| 932 |
style, |
| 933 |
paint.getPathEffect()); |
| 934 |
} |
| 935 |
|
| 936 |
void Device::drawVertices(const SkVertices* vertices, sk_sp<SkBlender> blender, |
| 937 |
const SkPaint& paint, bool skipColorXform) { |
| 938 |
// A null blender is normally equivalent to SrcOver; coerce it to non-null so that nullity |
| 939 |
// can be used by PaintParamsKeyBuilder to know when to add primitive blending blocks. |
| 940 |
// Use null for the primitive blender if `vertices` does not have per-vertex colors. |
| 941 |
const SkBlender* primitiveBlender = |
| 942 |
!vertices->priv().hasColors() ? nullptr : |
| 943 |
blender ? blender.get() |
| 944 |
: GetBlendModeSingleton(SkBlendMode::kSrcOver); |
| 945 |
this->drawGeometry(this->localToDeviceTransform(), |
| 946 |
Geometry(sk_ref_sp(vertices)), |
| 947 |
PaintParams(paint, primitiveBlender, skipColorXform), |
| 948 |
DefaultFillStyle()); |
| 949 |
} |
| 950 |
|
| 951 |
bool Device::drawAsTiledImageRect(SkCanvas* canvas, |
| 952 |
const SkImage* image, |
| 953 |
const SkRect* src, |
| 954 |
const SkRect& dst, |
| 955 |
const SkSamplingOptions& sampling, |
| 956 |
const SkPaint& paint, |
| 957 |
SkCanvas::SrcRectConstraint constraint) { |
| 958 |
auto recorder = canvas->recorder(); |
| 959 |
if (!recorder) { |
| 960 |
return false; |
| 961 |
} |
| 962 |
SkASSERT(src); |
| 963 |
|
| 964 |
// For Graphite this is a pretty loose heuristic. The Recorder-local cache size (relative |
| 965 |
// to the large image's size) is used as a proxy for how conservative we should be when |
| 966 |
// allocating tiles. Since the tiles will actually be owned by the client (via an |
| 967 |
// ImageProvider) they won't actually add any memory pressure directly to Graphite. |
| 968 |
size_t cacheSize = recorder->priv().getResourceCacheLimit(); |
| 969 |
size_t maxTextureSize = recorder->priv().caps()->maxTextureSize(); |
| 970 |
|
| 971 |
#if defined(GPU_TEST_UTILS) |
| 972 |
if (gOverrideMaxTextureSizeGraphite) { |
| 973 |
maxTextureSize = gOverrideMaxTextureSizeGraphite; |
| 974 |
} |
| 975 |
gNumTilesDrawnGraphite.store(0, std::memory_order_relaxed); |
| 976 |
#endif |
| 977 |
|
| 978 |
// DrawAsTiledImageRect produces per-edge AA quads, which do not participate in non-AA pixel |
| 979 |
// snapping emulation. To match an un-tiled drawImageRect, round the src and dst geometry |
| 980 |
// before any tiling occurs. |
| 981 |
SkRect finalSrc = *src; |
| 982 |
SkRect finalDst = dst; |
| 983 |
if (!paint.isAntiAlias()) { |
| 984 |
snap_src_and_dst_rect_to_pixels(this->localToDeviceTransform(), |
| 985 |
&finalSrc, &finalDst); |
| 986 |
} |
| 987 |
|
| 988 |
[[maybe_unused]] auto [wasTiled, numTiles] = |
| 989 |
skgpu::TiledTextureUtils::DrawAsTiledImageRect(canvas, |
| 990 |
image, |
| 991 |
finalSrc, |
| 992 |
finalDst, |
| 993 |
SkCanvas::kAll_QuadAAFlags, |
| 994 |
sampling, |
| 995 |
&paint, |
| 996 |
constraint, |
| 997 |
/* sharpenMM= */ true, |
| 998 |
cacheSize, |
| 999 |
maxTextureSize); |
| 1000 |
#if defined(GPU_TEST_UTILS) |
| 1001 |
gNumTilesDrawnGraphite.store(numTiles, std::memory_order_relaxed); |
| 1002 |
#endif |
| 1003 |
return wasTiled; |
| 1004 |
} |
| 1005 |
|
| 1006 |
void Device::drawOval(const SkRect& oval, const SkPaint& paint) { |
| 1007 |
if (paint.getPathEffect()) { |
| 1008 |
// Dashing requires that the oval path starts on the right side and travels clockwise. This |
| 1009 |
// is the default for the SkPath::Oval constructor, as used by SkBitmapDevice. |
| 1010 |
this->drawGeometryWithPathEffect(this->localToDeviceTransform(), |
| 1011 |
Geometry(Shape(SkPath::Oval(oval))), |
| 1012 |
PaintParams(paint), |
| 1013 |
SkStrokeRec(paint), |
| 1014 |
paint.getPathEffect()); |
| 1015 |
} else { |
| 1016 |
// TODO: This has wasted effort from the SkCanvas level since it instead converts rrects |
| 1017 |
// that happen to be ovals into this, only for us to go right back to rrect. |
| 1018 |
this->drawRRect(SkRRect::MakeOval(oval), paint); |
| 1019 |
} |
| 1020 |
} |
| 1021 |
|
| 1022 |
void Device::drawArc(const SkArc& arc, const SkPaint& paint) { |
| 1023 |
// For sweeps >= 360°, simple fills and simple strokes without the center point or square caps |
| 1024 |
// are ovals. Culling these here simplifies the path processing in Shape. |
| 1025 |
if (!paint.getPathEffect() && |
| 1026 |
SkScalarAbs(arc.sweepAngle()) >= 360.f && |
| 1027 |
(paint.getStyle() == SkPaint::kFill_Style || |
| 1028 |
(paint.getStyle() == SkPaint::kStroke_Style && |
| 1029 |
// square caps can stick out from the shape so we can't do this with an rrect draw |
| 1030 |
paint.getStrokeCap() != SkPaint::kSquare_Cap && |
| 1031 |
// wedge cases with strokes will draw lines to the center |
| 1032 |
!arc.isWedge()))) { |
| 1033 |
this->drawRRect(SkRRect::MakeOval(arc.oval()), paint); |
| 1034 |
} else { |
| 1035 |
this->drawGeometryWithPathEffect(this->localToDeviceTransform(), |
| 1036 |
Geometry(Shape(arc)), |
| 1037 |
PaintParams(paint), |
| 1038 |
SkStrokeRec(paint), |
| 1039 |
paint.getPathEffect()); |
| 1040 |
} |
| 1041 |
} |
| 1042 |
|
| 1043 |
void Device::drawRRect(const SkRRect& rr, const SkPaint& paint) { |
| 1044 |
Shape rrectToDraw; |
| 1045 |
SkStrokeRec style(paint); |
| 1046 |
|
| 1047 |
if (paint.isAntiAlias()) { |
| 1048 |
rrectToDraw.setRRect(rr); |
| 1049 |
} else { |
| 1050 |
// Snap the horizontal and vertical edges of the rounded rectangle to pixel edges to match |
| 1051 |
// the behavior of drawRect(rr.bounds()), to partially emulate non-AA rendering while |
| 1052 |
// preserving the anti-aliasing of the curved corners. |
| 1053 |
Rect snappedBounds; |
| 1054 |
if (style.isFillStyle()) { |
| 1055 |
snappedBounds = snap_rect_to_pixels(this->localToDeviceTransform(), rr.rect()); |
| 1056 |
} else { |
| 1057 |
const bool strokeAndFill = style.getStyle() == SkStrokeRec::kStrokeAndFill_Style; |
| 1058 |
float strokeWidth = style.getWidth(); |
| 1059 |
snappedBounds = snap_rect_to_pixels(this->localToDeviceTransform(), |
| 1060 |
rr.rect(), &strokeWidth); |
| 1061 |
style.setStrokeStyle(strokeWidth, strokeAndFill); |
| 1062 |
} |
| 1063 |
|
| 1064 |
SkRRect snappedRRect; |
| 1065 |
snappedRRect.setRectRadii(snappedBounds.asSkRect(), rr.radii().data()); |
| 1066 |
rrectToDraw.setRRect(snappedRRect); |
| 1067 |
} |
| 1068 |
|
| 1069 |
this->drawGeometryWithPathEffect(this->localToDeviceTransform(), |
| 1070 |
Geometry(rrectToDraw), |
| 1071 |
PaintParams(paint), |
| 1072 |
style, |
| 1073 |
paint.getPathEffect()); |
| 1074 |
} |
| 1075 |
|
| 1076 |
void Device::drawDRRect(const SkRRect& outer, const SkRRect& inner, const SkPaint& paint) { |
| 1077 |
// If there's a path effect or inverse fill, fall back to path rendering |
| 1078 |
if (paint.getPathEffect() || paint.getStyle() != SkPaint::kFill_Style) { |
| 1079 |
this->SkDevice::drawDRRect(outer, inner, paint); |
| 1080 |
return; |
| 1081 |
} |
| 1082 |
|
| 1083 |
// This holds the positive insets from `outer` to `inner` |
| 1084 |
Rect strokeRect{outer.rect()}; |
| 1085 |
skvx::float4 gap = Rect(inner.rect()).vals() - strokeRect.vals(); |
| 1086 |
const float tolerance = Shape::kDefaultPixelTolerance * |
| 1087 |
this->localToDeviceTransform().localAARadius(strokeRect); |
| 1088 |
const float strokeWidth = gap[0]; |
| 1089 |
if (!all((gap > tolerance) & (abs(gap - strokeWidth) <= tolerance))) { |
| 1090 |
// Either not approximately equal insets on all sides, or it would create a hairline stroke |
| 1091 |
// which is something that should be requested via paint style. |
| 1092 |
// |
| 1093 |
// But we can try subtracting inner from outer if they are both rectangular to see if it |
| 1094 |
// leaves a valid filled rect. |
| 1095 |
SkRect diff; |
| 1096 |
if (outer.isRect() && inner.isRect() && |
| 1097 |
SkRectPriv::Subtract(outer.rect(), inner.rect(), &diff)) { |
| 1098 |
this->drawRect(diff, paint); |
| 1099 |
return; |
| 1100 |
} |
| 1101 |
|
| 1102 |
// Fall through to the draw+clip handling |
| 1103 |
} else { |
| 1104 |
// The shape is possibly expressible as a stroked [r]rect. |
| 1105 |
const float strokeRadius = 0.5f * strokeWidth; |
| 1106 |
strokeRect.inset(strokeRadius); |
| 1107 |
|
| 1108 |
SkPaint strokePaint = paint; |
| 1109 |
strokePaint.setStroke(true); |
| 1110 |
strokePaint.setStrokeWidth(strokeWidth); |
| 1111 |
strokePaint.setStrokeCap(SkPaint::kButt_Cap); |
| 1112 |
strokePaint.setStrokeMiter(4.f); // large enough to not trigger bevels for 90 degree corners |
| 1113 |
|
| 1114 |
// Check the corners to see if they are equivalent to a stroked round rect. If `outer` has |
| 1115 |
// rounded corners, they must be circular and be at least `strokeRadius`. An outer corner |
| 1116 |
// can have a 0 radius if we assume a miter join style, but if an outer corner is exactly |
| 1117 |
// the stroke radius then we have to use a round join style. The matching corners of `inner` |
| 1118 |
// must also be rounded, and be exactly strokeWidth less, or they must be 0 if the |
| 1119 |
// difference would be negative. |
| 1120 |
int validCorners = 0; |
| 1121 |
int rectCorners = 0; |
| 1122 |
SkVector strokeCorners[4]; |
| 1123 |
std::optional<SkPaint::Join> requiredJoin; |
| 1124 |
for (int i = 0; i < 4; ++i) { |
| 1125 |
SkVector outerCornerRadii = outer.radii((SkRRect::Corner) i); |
| 1126 |
SkVector innerCornerRadii = inner.radii((SkRRect::Corner) i); |
| 1127 |
|
| 1128 |
float strokeCorner; |
| 1129 |
if (!SkRRectPriv::IsRelativelyCircular(outerCornerRadii.fX, |
| 1130 |
outerCornerRadii.fY, |
| 1131 |
tolerance)) { |
| 1132 |
// Not circular; a stroked ellipse is not just a larger ellipse |
| 1133 |
break; |
| 1134 |
} else if (SkScalarNearlyZero(outerCornerRadii.fX, tolerance)) { |
| 1135 |
// A rectangular outer corner requires miter joins |
| 1136 |
if (requiredJoin.has_value() && *requiredJoin != SkPaint::kMiter_Join) { |
| 1137 |
break; |
| 1138 |
} |
| 1139 |
requiredJoin = SkPaint::kMiter_Join; |
| 1140 |
strokeCorner = 0.f; |
| 1141 |
rectCorners++; |
| 1142 |
} else { |
| 1143 |
strokeCorner = outerCornerRadii.fX - strokeRadius; |
| 1144 |
if (strokeCorner < -tolerance) { |
| 1145 |
// Corner is rounded but less than the stroke radius, which isn't representable |
| 1146 |
break; |
| 1147 |
} else if (strokeCorner <= tolerance) { |
| 1148 |
// Corner is rounded to the stroke radius, which can only be represented as an |
| 1149 |
// underlying rect corner and round join |
| 1150 |
if (requiredJoin.has_value() && *requiredJoin != SkPaint::kRound_Join) { |
| 1151 |
break; |
| 1152 |
} |
| 1153 |
requiredJoin = SkPaint::kRound_Join; |
| 1154 |
strokeCorner = 0.f; |
| 1155 |
rectCorners++; |
| 1156 |
} |
| 1157 |
} |
| 1158 |
|
| 1159 |
float expectedInnerRadius = std::max(0.f, strokeCorner - strokeRadius); |
| 1160 |
if (!SkRRectPriv::IsRelativelyCircular(innerCornerRadii.fX, |
| 1161 |
expectedInnerRadius, |
| 1162 |
tolerance) || |
| 1163 |
!SkRRectPriv::IsRelativelyCircular(innerCornerRadii.fY, |
| 1164 |
expectedInnerRadius, |
| 1165 |
tolerance)) { |
| 1166 |
// Inner corner doesn't match expectation |
| 1167 |
break; |
| 1168 |
} |
| 1169 |
|
| 1170 |
strokeCorners[i] = {strokeCorner, strokeCorner}; |
| 1171 |
validCorners++; |
| 1172 |
} |
| 1173 |
|
| 1174 |
if (validCorners == 4) { |
| 1175 |
strokePaint.setStrokeJoin(requiredJoin.value_or(SkPaint::kRound_Join)); |
| 1176 |
if (rectCorners == 4) { |
| 1177 |
this->drawRect(strokeRect.asSkRect(), strokePaint); |
| 1178 |
} else { |
| 1179 |
SkRRect strokeRRect; |
| 1180 |
strokeRRect.setRectRadii(strokeRect.asSkRect(), strokeCorners); |
| 1181 |
this->drawRRect(strokeRRect, strokePaint); |
| 1182 |
} |
| 1183 |
return; |
| 1184 |
} |
| 1185 |
// Otherwise fall through to draw+clip handling |
| 1186 |
} |
| 1187 |
|
| 1188 |
// To avoid path rendering, treat DRRects as a drawRRect(outer) with a clipRRect(inner, kDiff) |
| 1189 |
fClip.save(); |
| 1190 |
fClip.clipShape(this->localToDeviceTransform(), |
| 1191 |
inner.isRect() ? Shape{inner.rect()} : Shape{inner}, |
| 1192 |
SkClipOp::kDifference, |
| 1193 |
paint.isAntiAlias() ? ClipStack::PixelSnapping::kNo |
| 1194 |
: ClipStack::PixelSnapping::kYes); |
| 1195 |
if (outer.isRect()) { |
| 1196 |
this->drawRect(outer.rect(), paint); |
| 1197 |
} else { |
| 1198 |
this->drawRRect(outer, paint); |
| 1199 |
} |
| 1200 |
fClip.restore(); |
| 1201 |
} |
| 1202 |
|
| 1203 |
void Device::drawPath(const SkPath& path, const SkPaint& paint) { |
| 1204 |
// Alternatively, we could move this analysis to SkCanvas. Also, we could consider applying the |
| 1205 |
// path effect, being careful about starting point and direction. |
| 1206 |
if (!paint.getPathEffect() && !path.isInverseFillType()) { |
| 1207 |
SkPoint linePts[2]; |
| 1208 |
if (path.isLine(linePts)) { |
| 1209 |
// A line has zero area, so stroke and stroke-and-fill are equivalent |
| 1210 |
if (paint.getStyle() != SkPaint::kFill_Style) { |
| 1211 |
this->drawPoints(SkCanvas::kLines_PointMode, linePts, paint); |
| 1212 |
} // and if it's fill, nothing is drawn |
| 1213 |
return; |
| 1214 |
} |
| 1215 |
if (SkRect oval; path.isOval(&oval)) { |
| 1216 |
this->drawOval(oval, paint); |
| 1217 |
return; |
| 1218 |
} |
| 1219 |
if (SkRRect rrect; path.isRRect(&rrect)) { |
| 1220 |
this->drawRRect(rrect, paint); |
| 1221 |
return; |
| 1222 |
} |
| 1223 |
// For rects, if the path is not explicitly closed and the paint style is stroked then it |
| 1224 |
// represents a rectangle with only 3 sides rasterized (and with any caps). If it's filled |
| 1225 |
// or is closed+stroked, then the path renders identically to the rectangle. |
| 1226 |
bool isClosed = false; |
| 1227 |
if (SkRect rect; path.isRect(&rect, &isClosed) && |
| 1228 |
(paint.getStyle() == SkPaint::kFill_Style || isClosed)) { |
| 1229 |
this->drawRect(rect, paint); |
| 1230 |
return; |
| 1231 |
} |
| 1232 |
// Detect filled nested rect contours |
| 1233 |
SkRect rects[2]; |
| 1234 |
SkPathDirection dirs[2]; |
| 1235 |
if (paint.getStyle() == SkPaint::kFill_Style && |
| 1236 |
SkPathPriv::IsNestedFillRects(path, rects, dirs)) { |
| 1237 |
// For winding fills with contours going the same direction, there isn't any cutout |
| 1238 |
if (path.getFillType() == SkPathFillType::kWinding && dirs[0] == dirs[1]) { |
| 1239 |
this->drawRect(rects[0], paint); |
| 1240 |
return; |
| 1241 |
} else { |
| 1242 |
// The inner is cut out from the outer rect. Delegate to drawDRRect. |
| 1243 |
this->drawDRRect(SkRRect::MakeRect(rects[0]), SkRRect::MakeRect(rects[1]), paint); |
| 1244 |
return; |
| 1245 |
} |
| 1246 |
} |
| 1247 |
} |
| 1248 |
|
| 1249 |
// Full path rendering required |
| 1250 |
this->drawGeometryWithPathEffect(this->localToDeviceTransform(), |
| 1251 |
Geometry(Shape(path)), |
| 1252 |
PaintParams(paint), |
| 1253 |
SkStrokeRec(paint), |
| 1254 |
paint.getPathEffect()); |
| 1255 |
} |
| 1256 |
|
| 1257 |
void Device::drawPoints(SkCanvas::PointMode mode, SkSpan<const SkPoint> points, |
| 1258 |
const SkPaint& paint) { |
| 1259 |
if (points.empty()) { |
| 1260 |
return; |
| 1261 |
} |
| 1262 |
size_t count = points.size(); |
| 1263 |
|
| 1264 |
SkStrokeRec stroke(paint, SkPaint::kStroke_Style); |
| 1265 |
size_t next = 0; |
| 1266 |
if (mode == SkCanvas::kPoints_PointMode) { |
| 1267 |
// Treat kPoints mode as stroking zero-length path segments, which produce caps so that |
| 1268 |
// both hairlines and round vs. square geometry are handled entirely on the GPU. |
| 1269 |
// TODO: SkCanvas should probably do the butt to square cap correction. |
| 1270 |
if (paint.getStrokeCap() == SkPaint::kButt_Cap) { |
| 1271 |
stroke.setStrokeParams(SkPaint::kSquare_Cap, |
| 1272 |
paint.getStrokeJoin(), |
| 1273 |
paint.getStrokeMiter()); |
| 1274 |
} |
| 1275 |
} else { |
| 1276 |
next = 1; |
| 1277 |
count--; |
| 1278 |
} |
| 1279 |
|
| 1280 |
const PaintParams paintParams(paint); |
| 1281 |
size_t inc = mode == SkCanvas::kLines_PointMode ? 2 : 1; |
| 1282 |
for (size_t i = 0; i < count; i += inc) { |
| 1283 |
this->drawGeometryWithPathEffect(this->localToDeviceTransform(), |
| 1284 |
Geometry(Shape(points[i], points[i + next])), |
| 1285 |
paintParams, |
| 1286 |
stroke, |
| 1287 |
paint.getPathEffect()); |
| 1288 |
} |
| 1289 |
} |
| 1290 |
|
| 1291 |
void Device::drawEdgeAAQuad(const SkRect& rect, |
| 1292 |
const SkPoint clip[4], |
| 1293 |
SkCanvas::QuadAAFlags aaFlags, |
| 1294 |
const SkColor4f& color, |
| 1295 |
SkBlendMode mode) { |
| 1296 |
// NOTE: We do not snap edge AA quads that are fully non-AA because we need their edges to seam |
| 1297 |
// with quads that have mixed edge flags (so both need to match the GPU rasterization, not our |
| 1298 |
// CPU rounding). |
| 1299 |
SkEnumBitMask<EdgeAAQuad::Flags> flags = static_cast<EdgeAAQuad::Flags>(aaFlags); |
| 1300 |
EdgeAAQuad quad = clip ? EdgeAAQuad(clip, flags) : EdgeAAQuad(rect, flags); |
| 1301 |
this->drawGeometry(this->localToDeviceTransform(), |
| 1302 |
Geometry(quad), |
| 1303 |
PaintParams(color, mode), |
| 1304 |
DefaultFillStyle()); |
| 1305 |
} |
| 1306 |
|
| 1307 |
void Device::drawEdgeAAImageSet(const SkCanvas::ImageSetEntry set[], int count, |
| 1308 |
const SkPoint dstClips[], const SkMatrix preViewMatrices[], |
| 1309 |
const SkSamplingOptions& sampling, const SkPaint& paint, |
| 1310 |
SkCanvas::SrcRectConstraint constraint) { |
| 1311 |
SkASSERT(count > 0); |
| 1312 |
|
| 1313 |
const Transform& localToDevice = this->localToDeviceTransform(); |
| 1314 |
// SkPaint paintWithShader(paint); |
| 1315 |
int dstClipIndex = 0; |
| 1316 |
for (int i = 0; i < count; ++i) { |
| 1317 |
// If the entry is clipped by 'dstClips', that must be provided |
| 1318 |
SkASSERT(!set[i].fHasClip || dstClips); |
| 1319 |
// Similarly, if it has an extra transform, those must be provided |
| 1320 |
SkASSERT(set[i].fMatrixIndex < 0 || preViewMatrices); |
| 1321 |
|
| 1322 |
// See SkImageShader::MakeForDrawRect, as this behavior is consistent but avoids |
| 1323 |
// allocating SkShader objects or having to modify the SkPaint. |
| 1324 |
// Adjust `dst` such that it only samples from the portion of fSrcRect that overlaps with |
| 1325 |
// the image bounds. This "decal" effect is applied geometrically to what is drawn so that |
| 1326 |
// actual texture tiling can be clamped to the src rect. |
| 1327 |
const SkRect imageBounds = SkRect::Make(set[i].fImage->bounds()); |
| 1328 |
SkRect dstToDraw = set[i].fDstRect; |
| 1329 |
SkRect subset = set[i].fSrcRect; |
| 1330 |
SkMatrix localMatrix = SkMatrix::RectToRectOrIdentity(subset, dstToDraw); |
| 1331 |
if (!imageBounds.contains(subset)) { |
| 1332 |
if (subset.intersect(imageBounds)) { |
| 1333 |
// Update dst to match the smaller src |
| 1334 |
dstToDraw = localMatrix.mapRect(subset); |
| 1335 |
} else { |
| 1336 |
dstToDraw.setEmpty(); |
| 1337 |
} |
| 1338 |
} |
| 1339 |
if (!dstToDraw.isEmpty()) { |
| 1340 |
PaintParams::SimpleImage imageShader{ |
| 1341 |
set[i].fImage.get(), |
| 1342 |
&localMatrix, |
| 1343 |
constraint == SkCanvas::kStrict_SrcRectConstraint ? subset : imageBounds, |
| 1344 |
sampling}; |
| 1345 |
|
| 1346 |
// NOTE: See drawEdgeAAQuad for details, we do not snap non-AA quads. |
| 1347 |
SkEnumBitMask<EdgeAAQuad::Flags> flags = |
| 1348 |
static_cast<EdgeAAQuad::Flags>(set[i].fAAFlags); |
| 1349 |
EdgeAAQuad quad = set[i].fHasClip ? EdgeAAQuad(dstClips + dstClipIndex, flags) |
| 1350 |
: EdgeAAQuad(dstToDraw, flags); |
| 1351 |
|
| 1352 |
// TODO: Calling drawGeometry() for each entry re-evaluates the clip stack every time, |
| 1353 |
// which is consistent with Ganesh's behavior. It also matches the behavior if edge-AA |
| 1354 |
// images were submitted one at a time by SkiaRenderer (a nice client simplification). |
| 1355 |
// However, we should explore the performance trade off with doing one bulk evaluation |
| 1356 |
// for the whole set |
| 1357 |
const SkMatrix* xtraXform = |
| 1358 |
set[i].fMatrixIndex < 0 ? nullptr : &preViewMatrices[set[i].fMatrixIndex]; |
| 1359 |
this->drawGeometry(xtraXform ? localToDevice.concat(SkM44(*xtraXform)) : localToDevice, |
| 1360 |
Geometry(quad), |
| 1361 |
PaintParams(paint, imageShader, set[i].fAlpha), |
| 1362 |
DefaultFillStyle()); |
| 1363 |
} |
| 1364 |
dstClipIndex += 4 * set[i].fHasClip; |
| 1365 |
} |
| 1366 |
} |
| 1367 |
|
| 1368 |
void Device::drawImageRect(const SkImage* image, const SkRect* src, const SkRect& dst, |
| 1369 |
const SkSamplingOptions& sampling, const SkPaint& paint, |
| 1370 |
SkCanvas::SrcRectConstraint constraint) { |
| 1371 |
SkCanvas::ImageSetEntry single{sk_ref_sp(image), |
| 1372 |
src ? *src : SkRect::Make(image->bounds()), |
| 1373 |
dst, |
| 1374 |
/*alpha=*/1.f, |
| 1375 |
SkCanvas::kAll_QuadAAFlags}; |
| 1376 |
// While this delegates to drawEdgeAAImageSet() for the image shading logic, semantically a |
| 1377 |
// drawImageRect()'s non-AA behavior should match that of drawRect() so we snap dst (and update |
| 1378 |
// src to match) if needed before hand. |
| 1379 |
if (!paint.isAntiAlias()) { |
| 1380 |
snap_src_and_dst_rect_to_pixels(this->localToDeviceTransform(), |
| 1381 |
&single.fSrcRect, &single.fDstRect); |
| 1382 |
} |
| 1383 |
this->drawEdgeAAImageSet(&single, 1, nullptr, nullptr, sampling, paint, constraint); |
| 1384 |
} |
| 1385 |
|
| 1386 |
sktext::gpu::AtlasDrawDelegate Device::atlasDelegate() { |
| 1387 |
return [&](const sktext::gpu::AtlasSubRun* subRun, |
| 1388 |
SkPoint drawOrigin, |
| 1389 |
const SkPaint& paint, |
| 1390 |
sk_sp<SkRefCnt> subRunStorage, |
| 1391 |
sktext::gpu::RendererData rendererData) { |
| 1392 |
this->drawAtlasSubRun(subRun, drawOrigin, paint, std::move(subRunStorage), rendererData); |
| 1393 |
}; |
| 1394 |
} |
| 1395 |
|
| 1396 |
void Device::onDrawGlyphRunList(SkCanvas* canvas, |
| 1397 |
const sktext::GlyphRunList& glyphRunList, |
| 1398 |
const SkPaint& paint) { |
| 1399 |
ASSERT_SINGLE_OWNER |
| 1400 |
fRecorder->priv().textBlobCache()->drawGlyphRunList(canvas, |
| 1401 |
this->localToDevice(), |
| 1402 |
glyphRunList, |
| 1403 |
paint, |
| 1404 |
this->strikeDeviceInfo(), |
| 1405 |
this->atlasDelegate()); |
| 1406 |
} |
| 1407 |
|
| 1408 |
void Device::drawAtlasSubRun(const sktext::gpu::AtlasSubRun* subRun, |
| 1409 |
SkPoint drawOrigin, |
| 1410 |
const SkPaint& paint, |
| 1411 |
sk_sp<SkRefCnt> subRunStorage, |
| 1412 |
sktext::gpu::RendererData rendererData) { |
| 1413 |
ASSERT_SINGLE_OWNER |
| 1414 |
|
| 1415 |
// For color emoji, the shading behaves similarly to how drawImageRects override the shader |
| 1416 |
// via a SimpleImage. However, for text, the "image" is coming from the atlas and RenderStep as |
| 1417 |
// a primitive color and is combined with the paint color using the primitive blender, so we |
| 1418 |
// construct the PaintParams to explicitly ignore the paint's set shader. For regular and LCD |
| 1419 |
// text, the mask image provides coverage so there is no primitive blender. |
| 1420 |
const SkBlender* primitiveBlender = subRun->maskFormat() == MaskFormat::kARGB ? |
| 1421 |
GetBlendModeSingleton(SkBlendMode::kDstIn) : nullptr; |
| 1422 |
const PaintParams paintParams(paint, |
| 1423 |
primitiveBlender, |
| 1424 |
/*skipColorXform=*/false, |
| 1425 |
/*ignoreShader=*/SkToBool(primitiveBlender)); |
| 1426 |
const bool useGammaCorrectDistanceTable = this->imageInfo().colorSpace() && |
| 1427 |
this->imageInfo().colorSpace()->gammaIsLinear(); |
| 1428 |
const Transform& localToDevice = this->localToDeviceTransform(); |
| 1429 |
|
| 1430 |
const int subRunEnd = subRun->glyphCount(); |
| 1431 |
auto regenerateDelegate = [&](sktext::gpu::GlyphVector* glyphs, |
| 1432 |
int begin, |
| 1433 |
int end, |
| 1434 |
skgpu::MaskFormat maskFormat, |
| 1435 |
int padding) { |
| 1436 |
return glyphs->regenerateAtlasForGraphite(begin, end, maskFormat, padding, fRecorder); |
| 1437 |
}; |
| 1438 |
|
| 1439 |
for (int subRunCursor = 0; subRunCursor < subRunEnd;) { |
| 1440 |
// For the remainder of the run, add any atlas uploads to the Recorder's TextAtlasManager |
| 1441 |
auto[ok, glyphsRegenerated] = subRun->regenerateAtlas(subRunCursor, subRunEnd, |
| 1442 |
regenerateDelegate); |
| 1443 |
// There was a problem allocating the glyph in the atlas. Bail. |
| 1444 |
if (!ok) { |
| 1445 |
return; |
| 1446 |
} |
| 1447 |
if (glyphsRegenerated) { |
| 1448 |
auto [bounds, maskToDevice] = |
| 1449 |
subRun->vertexFiller().boundsAndDeviceMatrix(localToDevice, drawOrigin); |
| 1450 |
|
| 1451 |
|
| 1452 |
this->drawGeometry(maskToDevice, |
| 1453 |
Geometry(SubRunData(subRun, |
| 1454 |
subRunStorage, |
| 1455 |
bounds, |
| 1456 |
localToDevice.inverse(), |
| 1457 |
subRunCursor, |
| 1458 |
glyphsRegenerated, |
| 1459 |
SkPaintPriv::ComputeLuminanceColor(paint), |
| 1460 |
useGammaCorrectDistanceTable, |
| 1461 |
this->surfaceProps().pixelGeometry(), |
| 1462 |
fRecorder, |
| 1463 |
rendererData)), |
| 1464 |
paintParams, |
| 1465 |
DefaultFillStyle()); |
| 1466 |
} |
| 1467 |
subRunCursor += glyphsRegenerated; |
| 1468 |
|
| 1469 |
if (subRunCursor < subRunEnd) { |
| 1470 |
// Flush if not all the glyphs are handled because the atlas is out of space. |
| 1471 |
// We flush every Device because the glyphs that are being flushed/referenced are not |
| 1472 |
// necessarily specific to this Device. This addresses both multiple SkSurfaces within |
| 1473 |
// a Recorder, and nested layers. |
| 1474 |
TRACE_EVENT_INSTANT0("skia.gpu", "Glyph atlas full", TRACE_EVENT_SCOPE_NAME_THREAD); |
| 1475 |
fRecorder->priv().flushTrackedDevices(SK_DUMP_TASKS_CODE("Device::drawAtlasSubRun")); |
| 1476 |
} |
| 1477 |
} |
| 1478 |
} |
| 1479 |
|
| 1480 |
void Device::drawGeometryWithPathEffect(const Transform& localToDevice, |
| 1481 |
Geometry&& geometry, |
| 1482 |
const PaintParams& paint, |
| 1483 |
SkStrokeRec style, |
| 1484 |
const SkPathEffect* pathEffect) { |
| 1485 |
// Path effects are applied on the CPU, which may modify the geometry to draw. |
| 1486 |
// TODO(b/238757903): Handle dashing on the GPU when possible (e.g. straight lines) |
| 1487 |
if (pathEffect && localToDevice.valid()) { |
| 1488 |
// Apply the path effect before anything else, which if we are applying here, means that we |
| 1489 |
// are dealing with a Shape. drawVertices (and a SkVertices geometry) should pass in |
| 1490 |
// kIgnorePathEffect per SkCanvas spec. Text geometry also should pass in kIgnorePathEffect |
| 1491 |
// because the path effect is applied per glyph by the SkStrikeSpec already. |
| 1492 |
SkASSERT(geometry.isShape()); |
| 1493 |
|
| 1494 |
// TODO: If asADash() returns true and the base path matches the dashing fast path, then |
| 1495 |
// that should be detected now as well. Maybe add dashPath to Device so canvas can handle it |
| 1496 |
float maxScaleFactor = localToDevice.maxScaleFactor(); |
| 1497 |
if (localToDevice.type() == Transform::Type::kPerspective) { |
| 1498 |
auto bounds = geometry.bounds(); |
| 1499 |
float tl = std::get<1>(localToDevice.scaleFactors({bounds.left(), bounds.top()})); |
| 1500 |
float tr = std::get<1>(localToDevice.scaleFactors({bounds.right(), bounds.top()})); |
| 1501 |
float br = std::get<1>(localToDevice.scaleFactors({bounds.right(), bounds.bot()})); |
| 1502 |
float bl = std::get<1>(localToDevice.scaleFactors({bounds.left(), bounds.bot()})); |
| 1503 |
maxScaleFactor = std::max(std::max(tl, tr), std::max(bl, br)); |
| 1504 |
} |
| 1505 |
|
| 1506 |
style.setResScale(maxScaleFactor); |
| 1507 |
SkPathBuilder builder; |
| 1508 |
if (pathEffect->filterPath(&builder, geometry.shape().asPath(), |
| 1509 |
&style, nullptr, localToDevice)) { |
| 1510 |
SkPath dst = builder.detach(); |
| 1511 |
dst.setIsVolatile(true); |
| 1512 |
geometry.setShape(Shape(dst)); |
| 1513 |
} else { |
| 1514 |
SKGPU_LOG_W("Path effect failed to apply, drawing original path."); |
| 1515 |
} |
| 1516 |
|
| 1517 |
// Fallthrough, remaining code assumes the effect has been applied to `geometry` and `style` |
| 1518 |
} |
| 1519 |
|
| 1520 |
this->drawGeometry(localToDevice, std::move(geometry), paint, style); |
| 1521 |
} |
| 1522 |
|
| 1523 |
void Device::drawGeometry(const Transform& localToDevice, |
| 1524 |
Geometry&& geometry, |
| 1525 |
const PaintParams& paint, |
| 1526 |
SkStrokeRec style) { |
| 1527 |
ASSERT_SINGLE_OWNER |
| 1528 |
|
| 1529 |
if (!localToDevice.valid()) { |
| 1530 |
// If the transform is not invertible or not finite then drawing isn't well defined. |
| 1531 |
SKGPU_LOG_W("Skipping draw with non-invertible/non-finite transform."); |
| 1532 |
return; |
| 1533 |
} |
| 1534 |
|
| 1535 |
// TODO: The tessellating and atlas path renderers haven't implemented perspective yet, so |
| 1536 |
// transform to device space so we draw something approximately correct (barring local coord |
| 1537 |
// issues). |
| 1538 |
if (geometry.isShape() && localToDevice.type() == Transform::Type::kPerspective && |
| 1539 |
!is_simple_shape(geometry.shape(), localToDevice, style.getStyle())) { |
| 1540 |
SkPath devicePath = geometry.shape().asPath().makeTransform(localToDevice.matrix().asM33()); |
| 1541 |
devicePath.setIsVolatile(true); |
| 1542 |
// TODO(b/452415460): This fallback breaks perspective interpolation for local coords and |
| 1543 |
// it causes strokes to render in device space. |
| 1544 |
this->drawGeometry(Transform::Identity(), Geometry(Shape(devicePath)), paint, style); |
| 1545 |
return; |
| 1546 |
} |
| 1547 |
|
| 1548 |
ScopedDrawBuilder scopedDrawBuilder(fRecorder); |
| 1549 |
|
| 1550 |
// Calculate the clipped bounds of the draw and determine the clip elements that affect the |
| 1551 |
// draw without updating the clip stack. |
| 1552 |
ClipStack::ElementList clipElements; |
| 1553 |
Clip clip = fClip.visitClipStackForDraw(localToDevice, |
| 1554 |
&geometry, |
| 1555 |
style, |
| 1556 |
&clipElements); |
| 1557 |
if (clip.isClippedOut()) { |
| 1558 |
// Clipped out, so don't record anything. |
| 1559 |
return; |
| 1560 |
} |
| 1561 |
|
| 1562 |
// We assume that we will receive a renderer, or a PathAtlas. If it's a PathAtlas, then we |
| 1563 |
// assume that the renderer chosen in PathAtlas::addShape() will have single-channel coverage, |
| 1564 |
// require AA bounds outsetting, and have a single renderStep. The clip's draw bounds are passed |
| 1565 |
// in for heuristics, so it's fine if it doesn't include the AA outsetting we add for some |
| 1566 |
// analytic coverage renderers. |
| 1567 |
auto [renderer, pathAtlas] = this->chooseRenderer(localToDevice, |
| 1568 |
geometry, |
| 1569 |
style, |
| 1570 |
clip.transformedShapeBounds()); |
| 1571 |
if (!renderer && !pathAtlas) { |
| 1572 |
SKGPU_LOG_W("Skipping draw with no supported renderer or PathAtlas."); |
| 1573 |
return; |
| 1574 |
} |
| 1575 |
|
| 1576 |
// Update the pixel bounds of the draw to include any outsets done by the renderer (or that |
| 1577 |
// must be included in the pixels required when using an atlas). This is important so that |
| 1578 |
// all bounds overlap checks take into account pixels touched by rasterization, even if the |
| 1579 |
// calculated coverage for a pixel is 0. |
| 1580 |
if (!renderer || renderer->outsetBoundsForAA()) { |
| 1581 |
clip.outsetBoundsForAA(); |
| 1582 |
} |
| 1583 |
|
| 1584 |
// A renderer that emits a primitive color should only be used by a drawX() call that sets a |
| 1585 |
// non-null primitive blender. |
| 1586 |
SkASSERT(SkToBool(paint.primitiveBlender()) == (renderer && renderer->emitsPrimitiveColor())); |
| 1587 |
|
| 1588 |
ShadingParams shading{fRecorder->priv().caps(), |
| 1589 |
paint, |
| 1590 |
clip.nonMSAAClip(), |
| 1591 |
clip.shader(), |
| 1592 |
renderer ? renderer->coverage() : Coverage::kSingleChannel, |
| 1593 |
TextureInfoPriv::ViewFormat(fDC->target()->textureInfo())}; |
| 1594 |
|
| 1595 |
// Some shapes and styles combine multiple draws so the total render step count is split between |
| 1596 |
// the main renderer and possibly a secondaryRenderer. As we can't be sure whether a secondary |
| 1597 |
// renderer is required prior to getting the dstUsage from shading.toKey(), we pessimistically |
| 1598 |
// assume it's required for needsFlushBeforeDraw(). |
| 1599 |
int numNewRenderSteps = 1; |
| 1600 |
SkStrokeRec::Style styleType = style.getStyle(); |
| 1601 |
if (renderer) { |
| 1602 |
numNewRenderSteps = renderer->numRenderSteps(); |
| 1603 |
if (styleType == SkStrokeRec::kStrokeAndFill_Style) { |
| 1604 |
numNewRenderSteps += |
| 1605 |
fRecorder->priv().rendererProvider()->tessellatedStrokes()->numRenderSteps(); |
| 1606 |
} else if (style.isFillStyle() && renderer->useNonAAInnerFill()) { |
| 1607 |
numNewRenderSteps += |
| 1608 |
fRecorder->priv().rendererProvider()->nonAABounds()->numRenderSteps(); |
| 1609 |
} |
| 1610 |
} |
| 1611 |
|
| 1612 |
// Decide if we have any reason to flush pending work. A flush may be necessary for two reasons: |
| 1613 |
// 1) A flush is required before updating the clip state or making any permanent changes to |
| 1614 |
// a path atlas, since otherwise clip operations and/or atlas entries for the current |
| 1615 |
// draw will be flushed. |
| 1616 |
// 2) A flush is required before shading.toKey() is called so that child tasks required by |
| 1617 |
// this draw are associated with the DrawContext after any instead of being added as a |
| 1618 |
// child of the current draw. See "Layer" tests in NotifyInUseTest.cpp. |
| 1619 |
DstReadStrategy dstReadStrategy = shading.dstReadRequired() ? |
| 1620 |
fDC->dstReadStrategy() : DstReadStrategy::kNoneRequired; |
| 1621 |
const bool needsFlush = this->needsFlushBeforeDraw(numNewRenderSteps, dstReadStrategy); |
| 1622 |
if (needsFlush) { |
| 1623 |
if (pathAtlas != nullptr) { |
| 1624 |
// We need to flush work for all devices associated with the current Recorder. |
| 1625 |
// Otherwise we may end up with outstanding draws that depend on past atlas state. |
| 1626 |
fRecorder->priv().flushTrackedDevices( |
| 1627 |
SK_DUMP_TASKS_CODE("Device::drawGeometry Flush Before Draw")); |
| 1628 |
} else { |
| 1629 |
this->flushPendingWork(/*drawContext=*/nullptr); |
| 1630 |
} |
| 1631 |
} |
| 1632 |
|
| 1633 |
// Determine the paint ID and collect the paint uniforms now before anything has been recorded. |
| 1634 |
// The paint may reference an SkPicture or a Graphite-backed dynamic SkImage that can trigger |
| 1635 |
// a flush of the Recorder. |
| 1636 |
KeyContext keyContext{fRecorder, |
| 1637 |
fDC.get(), |
| 1638 |
fRecorder->priv().floatStorageManager(), |
| 1639 |
scopedDrawBuilder.builder(), |
| 1640 |
scopedDrawBuilder.gatherer(), |
| 1641 |
localToDevice.matrix(), |
| 1642 |
fDC->colorInfo(), |
| 1643 |
geometry.isShape() || geometry.isEdgeAAQuad() |
| 1644 |
? KeyGenFlags::kDefault |
| 1645 |
: KeyGenFlags::kDisableSamplingOptimization, |
| 1646 |
paint.color()}; |
| 1647 |
auto keyResult = shading.toKey(keyContext); |
| 1648 |
if (!keyResult) { |
| 1649 |
// Converting the SkPaint to a pipeline and set of uniform values + sampled textures failed. |
| 1650 |
SKGPU_LOG_W("Key context creation failed in Device::drawGeometry, draw dropped!"); |
| 1651 |
return; |
| 1652 |
} |
| 1653 |
auto [paintID, dstUsage] = *keyResult; |
| 1654 |
|
| 1655 |
// If we are unclipped, do not depend on the dst, and cover the target, then we can adjust |
| 1656 |
// load ops of the renderpass to more optimally handle the draw (and avoid redundant clears). |
| 1657 |
// NOTE: We skip this for fully-lazy render targets because the load ops may impact a larger |
| 1658 |
// area than the Device's theoretical bounds. |
| 1659 |
const bool overwritesAllPixels = dstUsage == DstUsage::kNone && |
| 1660 |
geometry.isShape() && |
| 1661 |
geometry.shape().isFloodFill() && |
| 1662 |
!fDC->target()->isFullyLazy() && |
| 1663 |
clipElements.empty() && |
| 1664 |
clip.scissor().contains(this->bounds()); |
| 1665 |
if (overwritesAllPixels) { |
| 1666 |
if (std::optional<SkColor4f> color = extract_paint_color(paint, fDC->colorInfo())) { |
| 1667 |
// Fullscreen clear, so nothing has to be rendered at all |
| 1668 |
fDC->clear(*color); |
| 1669 |
return; |
| 1670 |
} else { |
| 1671 |
// This paint does not depend on the destination and covers the entire surface, so |
| 1672 |
// discard everything previously recorded and proceed with the draw. However, if we are |
| 1673 |
// here because of a paint with src-over blending that just happens to be opaque, the |
| 1674 |
// discarded dst can still be accessed. For non-floating point formats, that is fine, |
| 1675 |
// but float formats can have NaNs after a discard that cause blending to fail. To |
| 1676 |
// avoid that scenario, we clear to a known value instead. |
| 1677 |
if (paint.finalBlendMode() == SkBlendMode::kSrcOver && |
| 1678 |
TextureFormatIsFloatingPoint( |
| 1679 |
TextureInfoPriv::ViewFormat(fDC->target()->textureInfo()))) { |
| 1680 |
fDC->clear(SkColors::kMagenta); // This color doesn't matter |
| 1681 |
} else { |
| 1682 |
fDC->discard(); |
| 1683 |
} |
| 1684 |
// But then continue to render the flood fill with shading |
| 1685 |
} |
| 1686 |
} |
| 1687 |
|
| 1688 |
// If an atlas path renderer was chosen we need to insert the shape into the atlas and schedule |
| 1689 |
// it to be drawn. |
| 1690 |
std::optional<PathAtlas::MaskAndOrigin> atlasMask; // only used if `pathAtlas != nullptr` |
| 1691 |
if (pathAtlas != nullptr) { |
| 1692 |
Rect clippedShapeBounds = clip.transformedShapeBounds().makeIntersect(clip.scissor()); |
| 1693 |
if (clippedShapeBounds.area() >= 0.8f * clip.transformedShapeBounds().area()) { |
| 1694 |
// The clip isn't excluding very much of the original shape, so store the entire path |
| 1695 |
// in the atlas to avoid redundant entries with slightly different clips. |
| 1696 |
clippedShapeBounds = clip.transformedShapeBounds(); |
| 1697 |
} |
| 1698 |
std::tie(renderer, atlasMask) = pathAtlas->addShape(clippedShapeBounds, |
| 1699 |
geometry.shape(), |
| 1700 |
localToDevice, |
| 1701 |
style); |
| 1702 |
|
| 1703 |
// If there was no space in the atlas and we haven't flushed already, then flush pending |
| 1704 |
// work to clear up space in the atlas. If we had already flushed once (which would have |
| 1705 |
// cleared the atlas) then the atlas is too small for this shape. |
| 1706 |
if (!atlasMask && !needsFlush) { |
| 1707 |
// We need to flush work for all devices associated with the current Recorder. |
| 1708 |
// Otherwise we may end up with outstanding draws that depend on past atlas state. |
| 1709 |
fRecorder->priv().flushTrackedDevices( |
| 1710 |
SK_DUMP_TASKS_CODE("Device::drawGeometry Atlas Flush")); |
| 1711 |
|
| 1712 |
// Try inserting the shape again. |
| 1713 |
std::tie(renderer, atlasMask) = pathAtlas->addShape(clippedShapeBounds, |
| 1714 |
geometry.shape(), |
| 1715 |
localToDevice, |
| 1716 |
style); |
| 1717 |
} |
| 1718 |
|
| 1719 |
if (!atlasMask) { |
| 1720 |
SKGPU_LOG_E("Failed to add shape to atlas!"); |
| 1721 |
// TODO(b/285195175): This can happen if the atlas is not large enough or a compatible |
| 1722 |
// atlas texture cannot be created. Handle the first case in `chooseRenderer` and make |
| 1723 |
// sure that the atlas path renderer is not chosen if the path is larger than the atlas |
| 1724 |
// texture. |
| 1725 |
return; |
| 1726 |
} |
| 1727 |
// Since addShape() was successful we should have a valid Renderer now. |
| 1728 |
SkASSERT(renderer && renderer->numRenderSteps() == 1 && !renderer->emitsPrimitiveColor()); |
| 1729 |
fAtlasedPathCount++; |
| 1730 |
} |
| 1731 |
|
| 1732 |
#if defined(SK_DEBUG) |
| 1733 |
// Renderers and their component RenderSteps have flexibility in defining their |
| 1734 |
// DepthStencilSettings. However, the clipping and ordering managed between Device and ClipStack |
| 1735 |
// requires that only LESS or LEQUAL depth tests are used for draws recorded through the |
| 1736 |
// client-facing, painters-order-oriented API. We assert here vs. in Renderer's constructor to |
| 1737 |
// allow internal-oriented Renderers that are never selected for a "regular" draw call to have |
| 1738 |
// more flexibility in their settings. |
| 1739 |
SkASSERT(renderer); |
| 1740 |
for (const RenderStep* step : renderer->steps()) { |
| 1741 |
auto dss = step->depthStencilSettings(); |
| 1742 |
SkASSERT((!step->performsShading() || dss.fDepthTestEnabled) && |
| 1743 |
(!dss.fDepthTestEnabled || |
| 1744 |
dss.fDepthCompareOp == CompareOp::kLess || |
| 1745 |
dss.fDepthCompareOp == CompareOp::kLEqual)); |
| 1746 |
} |
| 1747 |
#endif |
| 1748 |
|
| 1749 |
// Update the clip stack after issuing a flush (if it was needed). A draw will be recorded after |
| 1750 |
// this point. |
| 1751 |
DrawOrder order(fCurrentDepth.next()); |
| 1752 |
CompressedPaintersOrder clipOrder = fClip.updateClipStateForDraw( |
| 1753 |
clip, clipElements, fColorDepthBoundsManager.get(), order.depth()); |
| 1754 |
|
| 1755 |
// A draw's order always depends on the clips that must be drawn before it |
| 1756 |
order.dependsOnPaintersOrder(clipOrder); |
| 1757 |
// If a draw is not opaque, it must be drawn after the most recent draw it intersects with in |
| 1758 |
// order to blend correctly. |
| 1759 |
if (dstUsage & DstUsage::kDependsOnDst) { |
| 1760 |
CompressedPaintersOrder prevDraw = |
| 1761 |
fColorDepthBoundsManager->getMostRecentDraw(clip.drawBounds()); |
| 1762 |
order.dependsOnPaintersOrder(prevDraw); |
| 1763 |
} |
| 1764 |
|
| 1765 |
// Now that the base paint order and draw bounds are finalized, if the Renderer relies on the |
| 1766 |
// stencil attachment, we compute a secondary sorting field to allow disjoint draws to reorder |
| 1767 |
// the RenderSteps across draws instead of in sequence for each draw. |
| 1768 |
if (renderer->depthStencilFlags() & DepthStencilFlags::kStencil) { |
| 1769 |
DisjointStencilIndex setIndex = fDisjointStencilSet->add(order.paintOrder(), |
| 1770 |
clip.drawBounds()); |
| 1771 |
order.dependsOnStencil(setIndex); |
| 1772 |
} else if (!(dstUsage & DstUsage::kDependsOnDst) && |
| 1773 |
style.isFillStyle() && |
| 1774 |
((geometry.isEdgeAAQuad() && geometry.edgeAAQuad().isRect()) || |
| 1775 |
(geometry.isShape() && geometry.shape().isRect()))) { |
| 1776 |
// Sort this draw front to back since it will not blend against what came before it. |
| 1777 |
// We could do this for all opaque/non-blending draws but that can hurt the performance of |
| 1778 |
// the std::sort in DrawPass::Make if it has to effectively reverse a large list. For now, |
| 1779 |
// limit it to filled rectangles (here and for the later non-AA inner fill). |
| 1780 |
order.reverseDepthAsStencil(); |
| 1781 |
} |
| 1782 |
|
| 1783 |
// If an atlas path renderer was chosen, then record a single CoverageMaskShape draw. |
| 1784 |
// The shape will be scheduled to be rendered or uploaded into the atlas during the |
| 1785 |
// next invocation of flushPendingWork(). |
| 1786 |
if (pathAtlas != nullptr) { |
| 1787 |
// Record the draw as a fill since stroking is handled by the atlas render/upload. |
| 1788 |
SkASSERT(atlasMask.has_value()); |
| 1789 |
auto [mask, origin] = *atlasMask; |
| 1790 |
fDC->recordDraw(renderer, Transform::Translate(origin.fX, origin.fY), Geometry(mask), clip, |
| 1791 |
order, paintID, dstUsage, scopedDrawBuilder.gatherer(), nullptr); |
| 1792 |
} else { |
| 1793 |
if (styleType != SkStrokeRec::kFill_Style) { |
| 1794 |
// For stroke-and-fill, 'renderer' is used for the fill and we always use the |
| 1795 |
// TessellatedStrokes renderer; for stroke and hairline, 'renderer' is used. |
| 1796 |
StrokeStyle stroke(style.getWidth(), style.getMiter(), style.getJoin(), style.getCap()); |
| 1797 |
fDC->recordDraw(styleType == SkStrokeRec::kStrokeAndFill_Style |
| 1798 |
? fRecorder->priv().rendererProvider()->tessellatedStrokes() |
| 1799 |
: renderer, |
| 1800 |
localToDevice, geometry, clip, order, paintID, dstUsage, |
| 1801 |
scopedDrawBuilder.gatherer(), &stroke); |
| 1802 |
} else if ((dstUsage & DstUsage::kDstOnlyUsedByRenderer) && renderer->useNonAAInnerFill()) { |
| 1803 |
// Possibly record an additional draw using the non-AA bounds renderer to fill the |
| 1804 |
// interior with a renderer that can disable blending entirely. |
| 1805 |
Rect innerFillBounds = get_inner_bounds(geometry, localToDevice); |
| 1806 |
if (!innerFillBounds.isEmptyNegativeOrNaN()) { |
| 1807 |
DrawOrder orderWithoutCoverage{order.depth()}; |
| 1808 |
orderWithoutCoverage.dependsOnPaintersOrder(clipOrder); |
| 1809 |
// The regular draw has analytic coverage, so isn't being sorted front to back, but |
| 1810 |
// we do want to sort the inner fill to maximize overdraw reduction |
| 1811 |
orderWithoutCoverage.reverseDepthAsStencil(); |
| 1812 |
fDC->recordDraw(fRecorder->priv().rendererProvider()->nonAABounds(), localToDevice, |
| 1813 |
Geometry(Shape(innerFillBounds)), clip, orderWithoutCoverage, |
| 1814 |
paintID, DstUsage::kNone, scopedDrawBuilder.gatherer(), nullptr); |
| 1815 |
// Force the coverage draw to come after the non-AA draw in order to benefit from |
| 1816 |
// early depth testing. |
| 1817 |
order.dependsOnPaintersOrder(orderWithoutCoverage.paintOrder()); |
| 1818 |
} |
| 1819 |
} |
| 1820 |
|
| 1821 |
if (styleType == SkStrokeRec::kFill_Style || |
| 1822 |
styleType == SkStrokeRec::kStrokeAndFill_Style) { |
| 1823 |
fDC->recordDraw(renderer, localToDevice, geometry, clip, order, paintID, dstUsage, |
| 1824 |
scopedDrawBuilder.gatherer(), nullptr); |
| 1825 |
} |
| 1826 |
} |
| 1827 |
|
| 1828 |
// Post-draw book keeping (bounds manager, depth tracking, etc.) |
| 1829 |
fColorDepthBoundsManager->recordDraw(clip.drawBounds(), order.paintOrder()); |
| 1830 |
fCurrentDepth = order.depth(); |
| 1831 |
|
| 1832 |
// TODO(b/238758897): When we enable layer elision that depends on draws not overlapping, we |
| 1833 |
// can use the `getMostRecentDraw()` query to determine that, although that will mean querying |
| 1834 |
// even if the draw does not depend on dst (so should be only be used when the Device is an |
| 1835 |
// elision candidate). |
| 1836 |
} |
| 1837 |
|
| 1838 |
void Device::drawClipShape(const Transform& localToDevice, |
| 1839 |
const Shape& shape, |
| 1840 |
const Clip& clip, |
| 1841 |
DrawOrder order) { |
| 1842 |
ScopedDrawBuilder scopedDrawBuilder(fRecorder); |
| 1843 |
|
| 1844 |
// A clip draw's state is almost fully defined by the ClipStack. The only thing we need to |
| 1845 |
// account for is selecting a Renderer and tracking the stencil buffer usage. |
| 1846 |
// |
| 1847 |
// While kRasterAtlas attempts to route clip elements to an atlas, this can fail, in which case |
| 1848 |
// the element may still be rendered into the depth buffer with tessellation (likely w/o AA). |
| 1849 |
auto renderer = this->chooseMSAARenderer(shape, |
| 1850 |
DefaultFillStyle(), |
| 1851 |
clip.transformedShapeBounds()); |
| 1852 |
if (!renderer) { |
| 1853 |
SKGPU_LOG_W("Skipping clip with no supported path renderer."); |
| 1854 |
return; |
| 1855 |
} else if (renderer->depthStencilFlags() & DepthStencilFlags::kStencil) { |
| 1856 |
DisjointStencilIndex setIndex = fDisjointStencilSet->add(order.paintOrder(), |
| 1857 |
clip.drawBounds()); |
| 1858 |
order.dependsOnStencil(setIndex); |
| 1859 |
} |
| 1860 |
|
| 1861 |
// This call represents one of the deferred clip shapes that's already pessimistically counted |
| 1862 |
// in needsFlushBeforeDraw(), so the DrawContext should have room to add it. |
| 1863 |
SkASSERT(fDC->pendingRenderSteps() + renderer->numRenderSteps() < DrawList::kMaxRenderSteps); |
| 1864 |
|
| 1865 |
// Anti-aliased clipping requires the renderer to use MSAA to modify the depth per sample, so |
| 1866 |
// analytic coverage renderers cannot be used. |
| 1867 |
SkASSERT(renderer->coverage() == Coverage::kNone && renderer->requiresMSAA()); |
| 1868 |
|
| 1869 |
// Clips draws are depth-only (invalid UniquePaintParamsID), and filled (null StrokeStyle). |
| 1870 |
// The data gatherer must be reset so that the DrawList can use it for any RenderStep data. |
| 1871 |
if (localToDevice.type() == Transform::Type::kPerspective) { |
| 1872 |
SkPath devicePath = shape.asPath().makeTransform(localToDevice.matrix().asM33()); |
| 1873 |
fDC->recordDraw(renderer, Transform::Identity(), Geometry(Shape(devicePath)), clip, order, |
| 1874 |
UniquePaintParamsID::Invalid(), DstUsage::kNone, |
| 1875 |
scopedDrawBuilder.gatherer(), /*stroke=*/nullptr); |
| 1876 |
} else { |
| 1877 |
fDC->recordDraw(renderer, localToDevice, Geometry(shape), clip, order, |
| 1878 |
UniquePaintParamsID::Invalid(), DstUsage::kNone, |
| 1879 |
scopedDrawBuilder.gatherer(), /*stroke=*/nullptr); |
| 1880 |
} |
| 1881 |
// This ensures that draws recorded after this clip shape has been popped off the stack will |
| 1882 |
// be unaffected by the Z value the clip shape wrote to the depth attachment. |
| 1883 |
if (order.depth() > fCurrentDepth) { |
| 1884 |
fCurrentDepth = order.depth(); |
| 1885 |
} |
| 1886 |
} |
| 1887 |
|
| 1888 |
// TODO: Currently all Renderers are always defined, but with config options and caps that may not |
| 1889 |
// be the case, in which case chooseRenderer() will have to go through compatible choices. |
| 1890 |
std::pair<const Renderer*, PathAtlas*> Device::chooseRenderer(const Transform& localToDevice, |
| 1891 |
const Geometry& geometry, |
| 1892 |
const SkStrokeRec& style, |
| 1893 |
const Rect& drawBounds) const { |
| 1894 |
const RendererProvider* renderers = fRecorder->priv().rendererProvider(); |
| 1895 |
SkASSERT(renderers); |
| 1896 |
SkStrokeRec::Style type = style.getStyle(); |
| 1897 |
|
| 1898 |
if (geometry.isSubRun()) { |
| 1899 |
sktext::gpu::RendererData rendererData = geometry.subRunData().rendererData(); |
| 1900 |
if (!rendererData.isSDF) { |
| 1901 |
return {renderers->bitmapText(rendererData.isLCD, rendererData.maskFormat), nullptr}; |
| 1902 |
} |
| 1903 |
// Even though the SkPaint can request subpixel rendering, we still need to match |
| 1904 |
// this with the pixel geometry. |
| 1905 |
bool useLCD = rendererData.isLCD && |
| 1906 |
geometry.subRunData().pixelGeometry() != kUnknown_SkPixelGeometry; |
| 1907 |
return {renderers->sdfText(useLCD), nullptr}; |
| 1908 |
} else if (geometry.isVertices()) { |
| 1909 |
SkVerticesPriv info(geometry.vertices()->priv()); |
| 1910 |
return {renderers->vertices(info.mode(), info.hasColors(), info.hasTexCoords()), nullptr}; |
| 1911 |
} else if (geometry.isCoverageMaskShape()) { |
| 1912 |
// drawCoverageMask() passes in CoverageMaskShapes that reference a provided texture. |
| 1913 |
// The CoverageMask renderer can also be chosen later on if the shape is assigned to |
| 1914 |
// to be rendered into the PathAtlas, in which case the 2nd return value is non-null. |
| 1915 |
return {renderers->coverageMask(), nullptr}; |
| 1916 |
} else if (geometry.isEdgeAAQuad()) { |
| 1917 |
SkASSERT(style.isFillStyle()); |
| 1918 |
// handled by specialized system, simplified from rects and round rects |
| 1919 |
const EdgeAAQuad& quad = geometry.edgeAAQuad(); |
| 1920 |
if (quad.isRect() && (quad.edgeFlags() == EdgeAAQuad::Flags::kNone |
| 1921 |
#if !defined(SK_SKIP_PIXELALIGNED_QUAD_CHECK_GRAPHITE) |
| 1922 |
|| is_pixel_aligned(quad.bounds(), localToDevice) |
| 1923 |
#endif |
| 1924 |
)) { |
| 1925 |
// For non-AA rectangular quads, it can always use a coverage-less renderer; there's no |
| 1926 |
// need to check for pixel alignment to avoid popping if MSAA is turned on because quad |
| 1927 |
// tile edges will seam with each in either mode. We also switch to use the cover bounds |
| 1928 |
// when the quad is pixel aligned to be consistent with drawRect Renderer handling. |
| 1929 |
return {renderers->nonAABounds(), nullptr}; |
| 1930 |
} else { |
| 1931 |
return {renderers->perEdgeAAQuad(), nullptr}; |
| 1932 |
} |
| 1933 |
} else if (geometry.isAnalyticBlur()) { |
| 1934 |
return {renderers->analyticBlur(), nullptr}; |
| 1935 |
} else if (!geometry.isShape()) { |
| 1936 |
// We must account for new Geometry types with specific Renderers |
| 1937 |
return {nullptr, nullptr}; |
| 1938 |
} |
| 1939 |
|
| 1940 |
const Shape& shape = geometry.shape(); |
| 1941 |
if (is_simple_shape(shape, localToDevice, type)) { |
| 1942 |
SkASSERT(type != SkStrokeRec::kStrokeAndFill_Style); // stroke+fill is *not* simple |
| 1943 |
// For pixel-aligned rects, use the the non-AA bounds renderer to avoid triggering any |
| 1944 |
// dst-read requirement due to src blending. |
| 1945 |
bool pixelAlignedRect = false; |
| 1946 |
if (shape.isRect() && style.isFillStyle()) { |
| 1947 |
pixelAlignedRect = is_pixel_aligned(shape.rect(), localToDevice); |
| 1948 |
} |
| 1949 |
|
| 1950 |
if (shape.isEmpty() || pixelAlignedRect) { |
| 1951 |
SkASSERT(!shape.isEmpty() || shape.inverted()); |
| 1952 |
return {renderers->nonAABounds(), nullptr}; |
| 1953 |
} else { |
| 1954 |
return {renderers->analyticRRect(), nullptr}; |
| 1955 |
} |
| 1956 |
} |
| 1957 |
|
| 1958 |
if (shape.isArc() && |
| 1959 |
std::abs(shape.arc().sweepAngle()) < 360.f && |
| 1960 |
localToDevice.type() <= Transform::Type::kAffine && |
| 1961 |
SkRRectPriv::IsRelativelyCircular(shape.arc().oval().width(), shape.arc().oval().height(), |
| 1962 |
Shape::kDefaultPixelTolerance * |
| 1963 |
localToDevice.localAARadius(drawBounds))) { |
| 1964 |
// We aren't perspective, so the point passed to scaleFactors() doesn't matter |
| 1965 |
auto [minScale, maxScale] = localToDevice.scaleFactors({0, 0}); |
| 1966 |
if (SkScalarNearlyEqual(maxScale, minScale)) { |
| 1967 |
// Arc support depends on the style. |
| 1968 |
SkStrokeRec::Style recStyle = style.getStyle(); |
| 1969 |
switch (recStyle) { |
| 1970 |
case SkStrokeRec::kStrokeAndFill_Style: |
| 1971 |
// This produces a strange result that this op doesn't implement. |
| 1972 |
break; |
| 1973 |
case SkStrokeRec::kFill_Style: |
| 1974 |
return {renderers->circularArc(), nullptr}; |
| 1975 |
case SkStrokeRec::kStroke_Style: |
| 1976 |
case SkStrokeRec::kHairline_Style: |
| 1977 |
// Strokes that don't use the center point are supported with butt & round caps. |
| 1978 |
bool isWedge = shape.arc().isWedge(); |
| 1979 |
bool isSquareCap = style.getCap() == SkPaint::kSquare_Cap; |
| 1980 |
if (!isWedge && !isSquareCap) { |
| 1981 |
return {renderers->circularArc(), nullptr}; |
| 1982 |
} |
| 1983 |
break; |
| 1984 |
} |
| 1985 |
} |
| 1986 |
} |
| 1987 |
|
| 1988 |
AtlasProvider* atlasProvider = fRecorder->priv().atlasProvider(); |
| 1989 |
switch (renderers->pathRendererStrategy()) { |
| 1990 |
case PathRendererStrategy::kComputeAnalyticAA: |
| 1991 |
case PathRendererStrategy::kComputeMSAA16: |
| 1992 |
case PathRendererStrategy::kComputeMSAA8: { |
| 1993 |
PathAtlas* atlas = fDC->getComputePathAtlas(fRecorder); |
| 1994 |
SkASSERT(atlas); |
| 1995 |
|
| 1996 |
// Don't use the compute renderer if it can't handle the shape efficiently. |
| 1997 |
if (atlas->isSuitableForAtlasing(drawBounds, fClip.conservativeBounds())) { |
| 1998 |
return {nullptr, atlas}; |
| 1999 |
} // else falls back to tessellation |
| 2000 |
} break; |
| 2001 |
|
| 2002 |
case PathRendererStrategy::kTessellationAndSmallAtlas: { |
| 2003 |
static constexpr int kMaxSmallPathAtlasCount = 256; |
| 2004 |
const float minPathSizeForMSAA = fRecorder->priv().caps()->minPathSizeForMSAA(); |
| 2005 |
if (fAtlasedPathCount < kMaxSmallPathAtlasCount && |
| 2006 |
all(drawBounds.size() <= minPathSizeForMSAA)) { |
| 2007 |
// Small paths are rasterized on the CPU for higher quality |
| 2008 |
return {nullptr, atlasProvider->getRasterPathAtlas()}; |
| 2009 |
} // else falls back to tessellation |
| 2010 |
} break; |
| 2011 |
|
| 2012 |
case PathRendererStrategy::kRasterAtlas: |
| 2013 |
// Everything is rasterized on the CPU and packed into the atlas |
| 2014 |
return {nullptr, atlasProvider->getRasterPathAtlas()}; |
| 2015 |
|
| 2016 |
case PathRendererStrategy::kTessellation: |
| 2017 |
// Never uses an atlas for rendering, leave it null |
| 2018 |
break; |
| 2019 |
} |
| 2020 |
|
| 2021 |
// If we got here, it requires tessellated path rendering or an MSAA technique applied to a |
| 2022 |
// simple shape (so we interpret them as paths to reduce the number of pipelines we need). |
| 2023 |
return {this->chooseMSAARenderer(geometry.shape(), style, drawBounds), nullptr}; |
| 2024 |
} |
| 2025 |
|
| 2026 |
const Renderer* Device::chooseMSAARenderer(const Shape& shape, |
| 2027 |
const SkStrokeRec& style, |
| 2028 |
const Rect& drawBounds) const { |
| 2029 |
// TODO: All shapes that select a tessellating path renderer need to be "pre-chopped" if they |
| 2030 |
// are large enough to exceed the fixed count tessellation limits. Fills are pre-chopped to the |
| 2031 |
// viewport bounds, strokes and stroke-and-fills are pre-chopped to the viewport bounds outset |
| 2032 |
// by the stroke radius (hence taking the whole style and not just its type). |
| 2033 |
const RendererProvider* renderers = fRecorder->priv().rendererProvider(); |
| 2034 |
SkStrokeRec::Style type = style.getStyle(); |
| 2035 |
|
| 2036 |
if (type == SkStrokeRec::kStroke_Style || |
| 2037 |
type == SkStrokeRec::kHairline_Style) { |
| 2038 |
// Unlike in Ganesh, the HW stroke tessellator can work with arbitrary paints since the |
| 2039 |
// depth test prevents double-blending when there is transparency, thus we can HW stroke |
| 2040 |
// any path regardless of its paint. |
| 2041 |
// TODO: We treat inverse-filled strokes as regular strokes. We could handle them by |
| 2042 |
// stenciling first with the HW stroke tessellator and then covering their bounds, but |
| 2043 |
// inverse-filled strokes are not well-specified in our public canvas behavior so we may be |
| 2044 |
// able to remove it. |
| 2045 |
return renderers->tessellatedStrokes(); |
| 2046 |
} |
| 2047 |
|
| 2048 |
// 'type' could be kStrokeAndFill, but in that case chooseRenderer() is meant to return the |
| 2049 |
// fill renderer since tessellatedStrokes() will always be used for the stroke pass. |
| 2050 |
if (shape.convex() && !shape.inverted()) { |
| 2051 |
// TODO: Ganesh doesn't have a curve+middle-out triangles option for convex paths, but it |
| 2052 |
// would be pretty trivial to spin up. |
| 2053 |
return renderers->convexTessellatedWedges(); |
| 2054 |
} else { |
| 2055 |
const bool preferWedges = |
| 2056 |
// TODO: Combine this heuristic with what is used in PathStencilCoverOp to choose |
| 2057 |
// between wedges curves consistently in Graphite and Ganesh. |
| 2058 |
(shape.isPath() && shape.path().countVerbs() < 50) || |
| 2059 |
drawBounds.area() <= (256 * 256); |
| 2060 |
|
| 2061 |
if (preferWedges) { |
| 2062 |
return renderers->stencilTessellatedWedges(shape.fillType()); |
| 2063 |
} else { |
| 2064 |
return renderers->stencilTessellatedCurvesAndTris(shape.fillType()); |
| 2065 |
} |
| 2066 |
} |
| 2067 |
} |
| 2068 |
|
| 2069 |
sk_sp<Task> Device::lastDrawTask() const { |
| 2070 |
SkASSERT(this->isScratchDevice()); |
| 2071 |
return fLastTask; |
| 2072 |
} |
| 2073 |
|
| 2074 |
void Device::flushPendingWork(DrawContext* drawContext) { |
| 2075 |
TRACE_EVENT0("skia.gpu", TRACE_FUNC); |
| 2076 |
|
| 2077 |
// If this is a scratch device being flushed, it should only be flushing into the expected |
| 2078 |
// next recording from when the Device was first created. |
| 2079 |
SkASSERT(fRecorder); |
| 2080 |
SkASSERT(fScopedRecordingID == 0 || fScopedRecordingID == fRecorder->priv().nextRecordingID()); |
| 2081 |
|
| 2082 |
// Ideally we would just check if `drawTask` was non-null and then call flushTrackedDevices() |
| 2083 |
// before we appended `drawTask` afterwards. Unfortunately, internalFlush() is not 100% internal |
| 2084 |
// because it can record atlas uploads to the DrawContext. If those uploads were moved to |
| 2085 |
// `drawTask` before flushTrackedDevices() is called, any other Devices would incorrectly assume |
| 2086 |
// that the uploads would be executed before their tasks, even though that's not the case here. |
| 2087 |
if (fDC->modifiesTarget() && fMustFlushDependencies) { |
| 2088 |
// If this is a client-owned Device that has also been used as an image in the same Recorder |
| 2089 |
// we need flush all tracked devices that have pending reads from this Device, because those |
| 2090 |
// need to be resolved *before* `drawTask` would be executed and modify its texture state. |
| 2091 |
fMustFlushDependencies = false; |
| 2092 |
fRecorder->priv().flushTrackedDevices(this->target()); |
| 2093 |
} |
| 2094 |
|
| 2095 |
// While unbounded recursion is gone, bounded re-entrant flushing is still possible during |
| 2096 |
// dependency resolution. We assert *after* the dependency flush to permit this valid re-entry. |
| 2097 |
SkASSERT(!fIsFlushing); |
| 2098 |
SkDEBUGCODE(fIsFlushing = true;) |
| 2099 |
|
| 2100 |
this->internalFlush(); |
| 2101 |
sk_sp<Task> drawTask = fDC->snapDrawTask(); |
| 2102 |
if (drawContext) { |
| 2103 |
drawContext->recordDependency(std::move(drawTask)); |
| 2104 |
} else { |
| 2105 |
if (this->isScratchDevice()) { |
| 2106 |
// TODO(b/323887221): Once shared atlas resources are less brittle, scratch devices |
| 2107 |
// won't flush to the recorder at all and will only store the snapped task here. |
| 2108 |
fLastTask = drawTask; |
| 2109 |
} else { |
| 2110 |
// Non-scratch devices do not need to point back to the last snapped task since they are |
| 2111 |
// always added to the root task list. |
| 2112 |
// TODO: It is currently possible for scratch devices to be flushed and instantiated |
| 2113 |
// before their work is finished, meaning they will produce additional tasks to be |
| 2114 |
// included in a follow-up Recording: |
| 2115 |
// https://chat.google.com/room/AAAA2HlH94I/YU0XdFqX2Uw. However, in this case they no |
| 2116 |
// longer appear scratch because the first Recording instantiated the targets. When |
| 2117 |
// scratch devices are not actually registered with the Recorder and are only included |
| 2118 |
// when they are drawn (e.g. restored), we should be able to assert that `fLastTask` is |
| 2119 |
// null. |
| 2120 |
fLastTask = nullptr; |
| 2121 |
} |
| 2122 |
|
| 2123 |
if (drawTask) { |
| 2124 |
fRecorder->priv().add(std::move(drawTask)); |
| 2125 |
} |
| 2126 |
} |
| 2127 |
|
| 2128 |
SkDEBUGCODE(fIsFlushing = false;) |
| 2129 |
} |
| 2130 |
|
| 2131 |
void Device::internalFlush() { |
| 2132 |
TRACE_EVENT0("skia.gpu", TRACE_FUNC); |
| 2133 |
ASSERT_SINGLE_OWNER |
| 2134 |
|
| 2135 |
// Push any pending uploads from the atlas provider that pending draws reference. |
| 2136 |
fRecorder->priv().atlasProvider()->recordUploads(fDC.get()); |
| 2137 |
|
| 2138 |
// Clip shapes are depth-only draws, but aren't recorded in the DrawContext until a flush in |
| 2139 |
// order to determine the Z values for each element. |
| 2140 |
fClip.recordDeferredClipDraws(); |
| 2141 |
|
| 2142 |
// Flush all pending items to the internal task list and reset Device tracking state |
| 2143 |
fDC->flush(fRecorder); |
| 2144 |
|
| 2145 |
fColorDepthBoundsManager->reset(); |
| 2146 |
fDisjointStencilSet->reset(); |
| 2147 |
fCurrentDepth = DrawOrder::kClearDepth; |
| 2148 |
fAtlasedPathCount = 0; |
| 2149 |
|
| 2150 |
// Any cleanup in the AtlasProvider |
| 2151 |
fRecorder->priv().atlasProvider()->compact(); |
| 2152 |
} |
| 2153 |
|
| 2154 |
bool Device::needsFlushBeforeDraw(int numNewRenderSteps, DstReadStrategy dstReadStrategy) { |
| 2155 |
// Must also account for the elements in the clip stack that might need to be recorded. |
| 2156 |
numNewRenderSteps += fClip.maxDeferredClipDraws() * Renderer::kMaxRenderSteps; |
| 2157 |
bool needsFlush = |
| 2158 |
// Need flush if we don't have room to record into the current list. |
| 2159 |
(DrawList::kMaxRenderSteps - fDC->pendingRenderSteps()) < numNewRenderSteps || |
| 2160 |
// Need flush if this draw needs to copy the dst surface for reading. |
| 2161 |
dstReadStrategy == DstReadStrategy::kTextureCopy; |
| 2162 |
|
| 2163 |
return needsFlush; |
| 2164 |
} |
| 2165 |
|
| 2166 |
void Device::drawSpecial(SkSpecialImage* special, |
| 2167 |
const SkMatrix& localToDevice, |
| 2168 |
const SkSamplingOptions& sampling, |
| 2169 |
const SkPaint& paint, |
| 2170 |
SkCanvas::SrcRectConstraint constraint) { |
| 2171 |
SkASSERT(!paint.getMaskFilter() && !paint.getImageFilter()); |
| 2172 |
|
| 2173 |
sk_sp<SkImage> img = special->asImage(); |
| 2174 |
if (!img || !as_IB(img)->isGraphiteBacked()) { |
| 2175 |
SKGPU_LOG_W("Couldn't get Graphite-backed special image as image"); |
| 2176 |
return; |
| 2177 |
} |
| 2178 |
|
| 2179 |
// drawSpecial could be the same as drawEdgeAAImageSet or drawImageRect except that it |
| 2180 |
// ignores the currently assigned local-to-device transform and uses the one provided. |
| 2181 |
// But because SkSpecialImage guarantees the subset is already contained in the image and it's |
| 2182 |
// not empty, we can skip the src/dst correction. |
| 2183 |
SkRect src = SkRect::Make(special->subset()); |
| 2184 |
SkRect dst = SkRect::MakeIWH(special->width(), special->height()); |
| 2185 |
SkASSERT(img->bounds().contains(src) && !dst.isEmpty()); |
| 2186 |
|
| 2187 |
SkMatrix localMatrix = *SkMatrix::Rect2Rect(src, dst); |
| 2188 |
SkRect subset = constraint == SkCanvas::kStrict_SrcRectConstraint ? |
| 2189 |
src : SkRect::Make(img->bounds()); |
| 2190 |
PaintParams::SimpleImage imageShader{img.get(), &localMatrix, subset, sampling}; |
| 2191 |
|
| 2192 |
// The image filtering and layer code paths often rely on the paint being non-AA to avoid |
| 2193 |
// coverage operations. To stay consistent with the other backends, we use an edge AA "quad" |
| 2194 |
// whose flags match the paint's AA request. |
| 2195 |
EdgeAAQuad::Flags aaFlags = paint.isAntiAlias() ? EdgeAAQuad::Flags::kAll |
| 2196 |
: EdgeAAQuad::Flags::kNone; |
| 2197 |
this->drawGeometry(Transform(SkM44(localToDevice)), |
| 2198 |
Geometry(EdgeAAQuad(dst, aaFlags)), |
| 2199 |
PaintParams(paint, imageShader), |
| 2200 |
DefaultFillStyle()); |
| 2201 |
} |
| 2202 |
|
| 2203 |
void Device::drawCoverageMask(const SkSpecialImage* mask, |
| 2204 |
const SkMatrix& localToDevice, |
| 2205 |
const SkSamplingOptions& sampling, |
| 2206 |
const SkPaint& paint) { |
| 2207 |
CoverageMaskShape::MaskInfo maskInfo{/*fTextureOrigin=*/{SkTo<uint16_t>(mask->subset().fLeft), |
| 2208 |
SkTo<uint16_t>(mask->subset().fTop)}, |
| 2209 |
/*fMaskSize=*/{SkTo<uint16_t>(mask->width()), |
| 2210 |
SkTo<uint16_t>(mask->height())}}; |
| 2211 |
|
| 2212 |
auto maskProxyView = AsView(mask->asImage()); |
| 2213 |
if (!maskProxyView) { |
| 2214 |
SKGPU_LOG_W("Couldn't get Graphite-backed special image as texture proxy view"); |
| 2215 |
return; |
| 2216 |
} |
| 2217 |
|
| 2218 |
// Every other "Image" draw reaches the underlying texture via AddToKey/NotifyInUse, which |
| 2219 |
// handles notifying the image and either flushing the linked surface or attaching draw tasks |
| 2220 |
// from a scratch device to the current draw context. In this case, 'mask' is very likely to |
| 2221 |
// be linked to a scratch device, but we must perform the same notifyInUse manually here because |
| 2222 |
// the texture is consumed by the RenderStep and not part of the PaintParams. |
| 2223 |
static_cast<Image_Base*>(mask->asImage().get())->notifyInUse(fRecorder, fDC.get()); |
| 2224 |
|
| 2225 |
// CoverageMaskShape() wraps a Shape when it's used as a PathAtlas, but in this case the |
| 2226 |
// original shape has been long lost, so just use a Rect that bounds the image. |
| 2227 |
CoverageMaskShape maskShape{Shape{Rect::WH((float)mask->width(), (float)mask->height())}, |
| 2228 |
// We store a ref to the textureProxy to keep it alive. |
| 2229 |
maskProxyView.refProxy(), |
| 2230 |
// Use the active local-to-device transform for this since it |
| 2231 |
// determines the local coords for evaluating the skpaint, whereas |
| 2232 |
// the provided 'localToDevice' just places the coverage mask. |
| 2233 |
this->localToDeviceTransform().inverse(), |
| 2234 |
maskInfo}; |
| 2235 |
|
| 2236 |
this->drawGeometry(Transform(SkM44(localToDevice)), |
| 2237 |
Geometry(maskShape), |
| 2238 |
PaintParams(paint), |
| 2239 |
DefaultFillStyle()); |
| 2240 |
} |
| 2241 |
|
| 2242 |
sk_sp<SkSpecialImage> Device::snapSpecial(const SkIRect& subset, bool forceCopy) { |
| 2243 |
// NOTE: snapSpecial() can be called even after the device has been marked immutable (null |
| 2244 |
// recorder), but in those cases it should not be a copy and just returns the image view. |
| 2245 |
sk_sp<Image> deviceImage; |
| 2246 |
SkIRect finalSubset; |
| 2247 |
if (forceCopy || !this->readSurfaceView() || this->readSurfaceView().proxy()->isFullyLazy()) { |
| 2248 |
deviceImage = this->makeImageCopy( |
| 2249 |
subset, Budgeted::kYes, Mipmapped::kNo, SkBackingFit::kApprox); |
| 2250 |
finalSubset = SkIRect::MakeSize(subset.size()); |
| 2251 |
} else { |
| 2252 |
// TODO(b/323886870): For now snapSpecial() force adds the pending work to the recorder's |
| 2253 |
// root task list. Once shared atlas management is solved and DrawTasks can be nested in a |
| 2254 |
// graph then this can go away in favor of auto-flushing through the image's linked device. |
| 2255 |
if (fRecorder) { |
| 2256 |
this->flushPendingWork(/*drawContext=*/nullptr); |
| 2257 |
} |
| 2258 |
deviceImage = Image::WrapDevice(sk_ref_sp(this)); |
| 2259 |
finalSubset = subset; |
| 2260 |
} |
| 2261 |
|
| 2262 |
if (!deviceImage) { |
| 2263 |
return nullptr; |
| 2264 |
} |
| 2265 |
|
| 2266 |
// For non-copying "snapSpecial", the semantics are returning an image view of the surface data, |
| 2267 |
// and relying on higher-level draw and restore logic for the contents to make sense. |
| 2268 |
return SkSpecialImages::MakeGraphite( |
| 2269 |
fRecorder, finalSubset, std::move(deviceImage), this->surfaceProps()); |
| 2270 |
} |
| 2271 |
|
| 2272 |
sk_sp<skif::Backend> Device::createImageFilteringBackend(const SkSurfaceProps& surfaceProps, |
| 2273 |
SkColorType colorType) const { |
| 2274 |
return skif::MakeGraphiteBackend(fRecorder, surfaceProps, colorType); |
| 2275 |
} |
| 2276 |
|
| 2277 |
TextureProxy* Device::target() { return fDC->target(); } |
| 2278 |
|
| 2279 |
TextureProxyView Device::readSurfaceView() const { return fDC->readSurfaceView(); } |
| 2280 |
|
| 2281 |
bool Device::isScratchDevice() const { |
| 2282 |
// Scratch device status is inferred from whether or not the Device's target is instantiated. |
| 2283 |
// By default devices start out un-instantiated unless they are wrapping an existing backend |
| 2284 |
// texture (definitely not a scratch scenario), or Surface explicitly instantiates the target |
| 2285 |
// before returning to the client (not a scratch scenario). |
| 2286 |
// |
| 2287 |
// Scratch device targets are instantiated during the prepareResources() phase of |
| 2288 |
// Recorder::snap(). Truly scratch devices that have gone out of scope as intended will have |
| 2289 |
// already been destroyed at this point. Scratch devices that become longer-lived (linked to |
| 2290 |
// a client-owned object) automatically transition to non-scratch usage. |
| 2291 |
return !fDC->target()->isInstantiated() && !fDC->target()->isLazy(); |
| 2292 |
} |
| 2293 |
|
| 2294 |
sk_sp<sktext::gpu::Slug> Device::convertGlyphRunListToSlug(const sktext::GlyphRunList& glyphRunList, |
| 2295 |
const SkPaint& paint) { |
| 2296 |
return sktext::gpu::SlugImpl::Make(this->localToDevice(), |
| 2297 |
glyphRunList, |
| 2298 |
paint, |
| 2299 |
this->strikeDeviceInfo(), |
| 2300 |
SkStrikeCache::GlobalStrikeCache()); |
| 2301 |
} |
| 2302 |
|
| 2303 |
void Device::drawSlug(SkCanvas* canvas, const sktext::gpu::Slug* slug, const SkPaint& paint) { |
| 2304 |
auto slugImpl = static_cast<const sktext::gpu::SlugImpl*>(slug); |
| 2305 |
slugImpl->subRuns()->draw(canvas, slugImpl->origin(), paint, slugImpl, this->atlasDelegate()); |
| 2306 |
} |
| 2307 |
|
| 2308 |
bool Device::drawBlurredRRect(const SkRRect& rrect, const SkPaint& paint, float deviceSigma) { |
| 2309 |
if (skgpu::BlurIsEffectivelyIdentity(deviceSigma)) { |
| 2310 |
this->drawRRect(rrect, paint); |
| 2311 |
return true; |
| 2312 |
} |
| 2313 |
|
| 2314 |
std::optional<AnalyticBlurMask> analyticBlur = AnalyticBlurMask::Make( |
| 2315 |
this->recorder(), this->localToDeviceTransform(), deviceSigma, rrect); |
| 2316 |
if (!analyticBlur) { |
| 2317 |
return false; |
| 2318 |
} |
| 2319 |
|
| 2320 |
this->drawGeometry(this->localToDeviceTransform(), |
| 2321 |
Geometry(*analyticBlur), |
| 2322 |
PaintParams(paint), |
| 2323 |
SkStrokeRec(paint)); |
| 2324 |
return true; |
| 2325 |
} |
| 2326 |
|
| 2327 |
} // namespace skgpu::graphite |