| 1 |
/* |
| 2 |
* Copyright 2022 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/ClipStack.h" |
| 8 |
|
| 9 |
#include "include/core/SkBlendMode.h" |
| 10 |
#include "include/core/SkClipOp.h" |
| 11 |
#include "include/core/SkM44.h" |
| 12 |
#include "include/core/SkPaint.h" |
| 13 |
#include "include/core/SkPath.h" |
| 14 |
#include "include/core/SkPoint.h" |
| 15 |
#include "include/core/SkRRect.h" |
| 16 |
#include "include/core/SkRect.h" |
| 17 |
#include "include/core/SkScalar.h" |
| 18 |
#include "include/core/SkShader.h" |
| 19 |
#include "include/core/SkSpan.h" |
| 20 |
#include "include/core/SkStrokeRec.h" |
| 21 |
#include "include/gpu/graphite/Recorder.h" |
| 22 |
#include "include/private/base/SkDebug.h" |
| 23 |
#include "include/private/base/SkFloatingPoint.h" |
| 24 |
#include "src/base/SkEnumBitMask.h" |
| 25 |
#include "src/base/SkVx.h" |
| 26 |
#include "src/core/SkPathPriv.h" |
| 27 |
#include "src/core/SkRRectPriv.h" |
| 28 |
#include "src/core/SkRectPriv.h" |
| 29 |
#include "src/gpu/graphite/AtlasProvider.h" |
| 30 |
#include "src/gpu/graphite/ClipAtlasManager.h" |
| 31 |
#include "src/gpu/graphite/Device.h" |
| 32 |
#include "src/gpu/graphite/DrawParams.h" |
| 33 |
#include "src/gpu/graphite/RecorderPriv.h" |
| 34 |
#include "src/gpu/graphite/RendererProvider.h" |
| 35 |
#include "src/gpu/graphite/TextureProxy.h" |
| 36 |
#include "src/gpu/graphite/geom/BoundsManager.h" |
| 37 |
#include "src/gpu/graphite/geom/EdgeAAQuad.h" |
| 38 |
#include "src/gpu/graphite/geom/Geometry.h" |
| 39 |
#include "src/gpu/graphite/geom/NonMSAAClip.h" |
| 40 |
|
| 41 |
#include <algorithm> |
| 42 |
#include <atomic> |
| 43 |
#include <utility> |
| 44 |
|
| 45 |
namespace skgpu::graphite { |
| 46 |
|
| 47 |
namespace { |
| 48 |
|
| 49 |
Rect subtract(const Rect& a, const Rect& b, bool exact) { |
| 50 |
SkRect diff; |
| 51 |
if (SkRectPriv::Subtract(a.asSkRect(), b.asSkRect(), &diff) || !exact) { |
| 52 |
// Either A-B is exactly the rectangle stored in diff, or we don't need an exact answer |
| 53 |
// and can settle for the subrect of A excluded from B (which is also 'diff') |
| 54 |
return Rect{diff}; |
| 55 |
} else { |
| 56 |
// For our purposes, we want the original A when A-B cannot be exactly represented |
| 57 |
return a; |
| 58 |
} |
| 59 |
} |
| 60 |
|
| 61 |
static constexpr uint32_t kInvalidGenID = 0; |
| 62 |
static constexpr uint32_t kEmptyGenID = 1; |
| 63 |
static constexpr uint32_t kWideOpenGenID = 2; |
| 64 |
|
| 65 |
uint32_t next_gen_id() { |
| 66 |
// 0-2 are reserved for invalid, empty & wide-open |
| 67 |
static const uint32_t kFirstUnreservedGenID = 3; |
| 68 |
static std::atomic<uint32_t> nextID{kFirstUnreservedGenID}; |
| 69 |
|
| 70 |
uint32_t id; |
| 71 |
do { |
| 72 |
id = nextID.fetch_add(1, std::memory_order_relaxed); |
| 73 |
} while (id < kFirstUnreservedGenID); |
| 74 |
return id; |
| 75 |
} |
| 76 |
|
| 77 |
bool oriented_bbox_intersection(const Rect& a, const Transform& aXform, |
| 78 |
const Rect& b, const Transform& bXform) { |
| 79 |
// NOTE: We intentionally exclude projected bounds for two reasons: |
| 80 |
// 1. We can skip the division by w and worring about clipping to w = 0. |
| 81 |
// 2. W/o the projective case, the separating axes are simpler to compute (see below). |
| 82 |
SkASSERT(aXform.type() != Transform::Type::kPerspective && |
| 83 |
bXform.type() != Transform::Type::kPerspective); |
| 84 |
SkV4 quadA[4], quadB[4]; |
| 85 |
|
| 86 |
aXform.mapPoints(a, quadA); |
| 87 |
bXform.mapPoints(b, quadB); |
| 88 |
|
| 89 |
// There are 4 separating axes, defined by the two normals from quadA and from quadB, but |
| 90 |
// since they were produced by transforming a rectangle by an affine transform, we know the |
| 91 |
// normals are orthoganal to the basis vectors of upper 2x2 of their two transforms. |
| 92 |
auto axesX = skvx::float4(-aXform.matrix().rc(1,0), -aXform.matrix().rc(1,1), |
| 93 |
-bXform.matrix().rc(1,0), -bXform.matrix().rc(1,1)); |
| 94 |
auto axesY = skvx::float4(aXform.matrix().rc(0,0), aXform.matrix().rc(0,1), |
| 95 |
bXform.matrix().rc(0,0), bXform.matrix().rc(0,1)); |
| 96 |
|
| 97 |
// Projections of the 4 corners of each quadrilateral vs. the 4 axes. For orthonormal |
| 98 |
// transforms, the projections of a quad's corners to its own normal axes should work out |
| 99 |
// to the original dimensions of the rectangle, but this code handles skew and scale factors |
| 100 |
// without branching. |
| 101 |
auto aProj0 = quadA[0].x * axesX + quadA[0].y * axesY; |
| 102 |
auto aProj1 = quadA[1].x * axesX + quadA[1].y * axesY; |
| 103 |
auto aProj2 = quadA[2].x * axesX + quadA[2].y * axesY; |
| 104 |
auto aProj3 = quadA[3].x * axesX + quadA[3].y * axesY; |
| 105 |
|
| 106 |
auto bProj0 = quadB[0].x * axesX + quadB[0].y * axesY; |
| 107 |
auto bProj1 = quadB[1].x * axesX + quadB[1].y * axesY; |
| 108 |
auto bProj2 = quadB[2].x * axesX + quadB[2].y * axesY; |
| 109 |
auto bProj3 = quadB[3].x * axesX + quadB[3].y * axesY; |
| 110 |
|
| 111 |
// Minimum and maximum projected values against the 4 axes, for both quadA and quadB, which |
| 112 |
// gives us four pairs of intervals to test for separation. |
| 113 |
auto minA = min(min(aProj0, aProj1), min(aProj2, aProj3)); |
| 114 |
auto maxA = max(max(aProj0, aProj1), max(aProj2, aProj3)); |
| 115 |
auto minB = min(min(bProj0, bProj1), min(bProj2, bProj3)); |
| 116 |
auto maxB = max(max(bProj0, bProj1), max(bProj2, bProj3)); |
| 117 |
|
| 118 |
auto overlaps = (minB <= maxA) & (minA <= maxB); |
| 119 |
return all(overlaps); // any non-overlapping interval would imply no intersection |
| 120 |
} |
| 121 |
|
| 122 |
// LTRB are set in returned bitmask if other's LTRB edge is coincident or inside `shape`'s edge. |
| 123 |
SkEnumBitMask<EdgeAAQuad::Flags> clipped_edges(const Rect& shape, const Rect& other) { |
| 124 |
// Since RB are stored negated in vals(), this works out to |
| 125 |
// [other.LT >= shape.LT, other.RB <= shape.RB] |
| 126 |
auto insideMask = other.vals() >= shape.vals(); |
| 127 |
return (insideMask[0] ? EdgeAAQuad::Flags::kLeft : EdgeAAQuad::Flags::kNone) | |
| 128 |
(insideMask[1] ? EdgeAAQuad::Flags::kTop : EdgeAAQuad::Flags::kNone) | |
| 129 |
(insideMask[2] ? EdgeAAQuad::Flags::kRight : EdgeAAQuad::Flags::kNone) | |
| 130 |
(insideMask[3] ? EdgeAAQuad::Flags::kBottom : EdgeAAQuad::Flags::kNone); |
| 131 |
} |
| 132 |
|
| 133 |
// Tries to intersect `otherShape` transformed by `otherToDevice` directly into `shape` assuming |
| 134 |
// that `shape` is transformed by localToDevice. If possible (true), `shape` represents the exact |
| 135 |
// intersection of the two original shapes. Returns true if `shape` is modified, false otherwise. |
| 136 |
bool intersect_shape(const Transform& otherToDevice, const Shape& otherShape, |
| 137 |
const Transform& localToDevice, Shape* shape, |
| 138 |
SkEnumBitMask<EdgeAAQuad::Flags>* edgeFlags) { |
| 139 |
// There are only a subset of shape types that we can analytically intersect with each other, |
| 140 |
// assuming a simple fill style (always the case for clip shapes): |
| 141 |
// |
| 142 |
// rects, rrects, flood-fills (empty+inverse-fill) |
| 143 |
// |
| 144 |
// Flood-fills only appear as part of a draw, so it's only checked for `shape` and not |
| 145 |
// `otherShape`. In theory, per-edge AA quads could also be included but they do not appear as |
| 146 |
// clip shapes. |
| 147 |
// |
| 148 |
// Paths and arcs have complex intersection logic, so are skipped under the assumption that |
| 149 |
// simple cases have already been mapped to a rect or rrect. Lines are only ever stroked, so |
| 150 |
// are incompatible with this function. |
| 151 |
// |
| 152 |
// EdgeAAQuads that are rectangular can be intersected by being treated as a rect shape and |
| 153 |
// adjusting edge flags as non-AA edges are clipped out. |
| 154 |
bool shapeIntersectable = shape->isRect() || |
| 155 |
shape->isRRect() || |
| 156 |
shape->isFloodFill(); |
| 157 |
bool otherIntersectable = otherShape.isRect() || otherShape.isRRect(); |
| 158 |
// Only clip shapes are used for `otherShape`, so we shouldn't see any flood fills here |
| 159 |
SkASSERT(!otherShape.isFloodFill()); |
| 160 |
// Only rects should have edge flags other than kAll |
| 161 |
SkASSERT(*edgeFlags == EdgeAAQuad::Flags::kAll || shape->isRect()); |
| 162 |
|
| 163 |
if (!shapeIntersectable || !otherIntersectable) { |
| 164 |
// Technically if shapeIntersectable was true for empty+inverse, we could turn the flood |
| 165 |
// fill into `otherShape` regardless of its type, but those other types are more expensive |
| 166 |
// to render and in the situation where many draws fill against a clip path, we'd want to |
| 167 |
// draw the clip a single time vs. drawing the path multiple times. |
| 168 |
return false; |
| 169 |
} |
| 170 |
|
| 171 |
// In order to combine, otherShape must be able to map into `localToDevice` without changing |
| 172 |
// shape class (e.g. to a path when rotated) in order for shading to apply in the same |
| 173 |
// coordinate space. This is possible if the relative transform between otherToDevice and |
| 174 |
// localToDevice is rectStaysRect. |
| 175 |
Transform storage{SkM44::kUninitialized_Constructor}; |
| 176 |
|
| 177 |
// We track `local` to `other` and use the `inverseMapRect` functions to map the `otherShape` |
| 178 |
// into local space when possible. Using `localToOther` instead of `otherToLocal` allows the |
| 179 |
// common case of a device-space clip (otherToDevice == I) and an axis-aligned draw to |
| 180 |
// simply use `localToDevice` as `localToOther`. |
| 181 |
const Transform* localToOther; |
| 182 |
|
| 183 |
if (otherToDevice == localToDevice) { |
| 184 |
// No coordinate space conversion, so set to null to signal identity mapping is skippable. |
| 185 |
// NOTE: This case arises in clip-clip combinations when both were axis-aligned and pre- |
| 186 |
// transformed to device space. |
| 187 |
localToOther = nullptr; |
| 188 |
} else if (otherToDevice.type() == Transform::Type::kIdentity && |
| 189 |
localToDevice.type() <= Transform::Type::kRectStaysRect) { |
| 190 |
// Relative transform is (otherToDevice)^-1*localToDevice = localToDevice |
| 191 |
localToOther = &localToDevice; |
| 192 |
} else if (otherToDevice.type() <= Transform::Type::kRectStaysRect && |
| 193 |
localToDevice.type() == Transform::Type::kIdentity) { |
| 194 |
// Relative transform is otherToDevice^-1*localToDevice = otherToDevice^-1 |
| 195 |
// (which may not occur in a common scenario but is harmless). Inverse() is mostly |
| 196 |
// shuffling bytes around, not recomputing the inverse. |
| 197 |
storage = Transform::Inverse(otherToDevice); |
| 198 |
localToOther = &storage; |
| 199 |
} else { |
| 200 |
// Calculate (otherToDevice)^-1*localToDevice and see if the relative transform is |
| 201 |
// of the right type. |
| 202 |
storage = Transform(otherToDevice.inverse() * localToDevice); |
| 203 |
if (storage.type() <= Transform::Type::kRectStaysRect) { |
| 204 |
localToOther = &storage; |
| 205 |
} else { |
| 206 |
// `otherShape` can't be trivially mapped to the local coordinate space |
| 207 |
return false; |
| 208 |
} |
| 209 |
} |
| 210 |
|
| 211 |
// Since `otherShape` is either a rect or a round rect, bounds() is tight to the linear edges. |
| 212 |
Rect localOtherRect = otherShape.bounds(); |
| 213 |
if (localToOther) { |
| 214 |
// In this block, `localOtherRect` is defined in the other coord space and `mapped` is in |
| 215 |
// the local coord space. At the end of the block, `localOtherRect` is set to `mapped` so |
| 216 |
// that afterwards it is always defined in local space. |
| 217 |
Rect mapped = localToOther->inverseMapRect(localOtherRect); |
| 218 |
// If we don't have enough precision, the other shape might not map back to the geometry. |
| 219 |
// Allow up to 1/1000th of a pixel in tolerance when mapping between coordinate spaces, |
| 220 |
// otherwise we'll have to clip the shapes independently. |
| 221 |
const float otherTol = |
| 222 |
Shape::kDefaultPixelTolerance * otherToDevice.localAARadius(localOtherRect); |
| 223 |
if (localOtherRect.isEmptyNegativeOrNaN() || |
| 224 |
!localToOther->mapRect(mapped).nearlyEquals(localOtherRect, otherTol)) { |
| 225 |
return false; |
| 226 |
} |
| 227 |
localOtherRect = mapped; |
| 228 |
} |
| 229 |
// Remember the edges that get clipped by the intersection |
| 230 |
SkEnumBitMask<EdgeAAQuad::Flags> clippedEdges = clipped_edges(shape->bounds(), localOtherRect); |
| 231 |
if (!shape->isFloodFill()) { |
| 232 |
// And now it's tight to the intersection with `shape`, sans any corner rounding |
| 233 |
localOtherRect.intersect(shape->bounds()); |
| 234 |
} |
| 235 |
// Make sure that the intersected shape does not become subpixel in size, since drawing a |
| 236 |
// subpixel/hairline shape produces a different result than something that's clipped. |
| 237 |
float localAARadius = localToDevice.localAARadius(localOtherRect); |
| 238 |
if (!std::isfinite(localAARadius) || any(localOtherRect.size() <= localAARadius)) { |
| 239 |
return false; |
| 240 |
} |
| 241 |
|
| 242 |
SkRRect localOtherRRect; |
| 243 |
if (otherShape.isRect()) { |
| 244 |
if (shape->isRect() || shape->isFloodFill()) { |
| 245 |
SkASSERT(*edgeFlags == EdgeAAQuad::Flags::kAll || !shape->isFloodFill()); |
| 246 |
// Assuming that non-AA edges seam with non-AA edges other quads to create a uniform |
| 247 |
// coverage field, we turn on the AA edge flag when coincident or clipped. This will |
| 248 |
// create a nice AA edge from this draw while the other non-AA quad is discarded. |
| 249 |
*edgeFlags |= clippedEdges; // This is a no-op if shape was a flood fill |
| 250 |
shape->setRect(localOtherRect); |
| 251 |
return true; |
| 252 |
} else { |
| 253 |
// Fall back to rrect+rrect intersection |
| 254 |
localOtherRRect = SkRRect::MakeRect(localOtherRect.asSkRect()); |
| 255 |
} |
| 256 |
} else { |
| 257 |
SkASSERT(otherShape.isRRect()); |
| 258 |
if (localToOther) { |
| 259 |
if (auto rr = otherShape.rrect().transform(localToOther->inverse().asM33())) { |
| 260 |
localOtherRRect = *rr; |
| 261 |
} else { |
| 262 |
// Transformation produced invalid geometry |
| 263 |
return false; |
| 264 |
} |
| 265 |
} else { |
| 266 |
localOtherRRect = otherShape.rrect(); |
| 267 |
} |
| 268 |
|
| 269 |
if (shape->isRect() && *edgeFlags != EdgeAAQuad::Flags::kAll) { |
| 270 |
// When combining a mixed edge AA quad with a rounded rectangle, we require that all |
| 271 |
// non-AA edges be clipped out entirely. |
| 272 |
if ((clippedEdges | *edgeFlags) != EdgeAAQuad::Flags::kAll) { |
| 273 |
// The intersection shows AA'ed round corners and non-AA'ed edges, which can't be |
| 274 |
// represented by just Geometry or Shape. |
| 275 |
return false; |
| 276 |
} |
| 277 |
} else if (shape->isFloodFill()) { |
| 278 |
SkASSERT(*edgeFlags == EdgeAAQuad::Flags::kAll); |
| 279 |
shape->setRRect(localOtherRRect); |
| 280 |
return true; |
| 281 |
} // Else continue with rrect+rrect intersection |
| 282 |
} |
| 283 |
|
| 284 |
// `shape` can only be rect or rrect at this point, flood fill should already have returned. |
| 285 |
// If we've made it this far, we've also determined that the edge flags should be set to kAll |
| 286 |
// on a successful rrect+rrect intersection. |
| 287 |
SkASSERT(shape->isRect() || shape->isRRect()); |
| 288 |
|
| 289 |
SkRRect localRRect = SkRRectPriv::ConservativeIntersect( |
| 290 |
localOtherRRect, |
| 291 |
shape->isRect() ? SkRRect::MakeRect(shape->rect().asSkRect()) : shape->rrect()); |
| 292 |
if (localRRect.isRect()) { |
| 293 |
// Valid shape that can be simplified to rect |
| 294 |
shape->setRect(localRRect.rect()); |
| 295 |
*edgeFlags = EdgeAAQuad::Flags::kAll; |
| 296 |
return true; |
| 297 |
} else if (!localRRect.isEmpty()) { |
| 298 |
// Intersection is representable as a rrect still |
| 299 |
shape->setRRect(localRRect); |
| 300 |
*edgeFlags = EdgeAAQuad::Flags::kAll; |
| 301 |
return true; |
| 302 |
} else { |
| 303 |
// Intersection is complex, leave edge flags unmodified |
| 304 |
return false; |
| 305 |
} |
| 306 |
} |
| 307 |
|
| 308 |
Rect snap_scissor(const Rect& a, const Rect& deviceBounds) { |
| 309 |
// Snapping to 4 pixel boundaries seems to give a good tradeoff between rasterizing slightly |
| 310 |
// more (but being clipped by the depth test), vs. setting a tight scissor that forces a state |
| 311 |
// change. |
| 312 |
// NOTE: This rounds out to the *next* multiple of 4, so that if the input rectangle happens to |
| 313 |
// land on a multiple of 4 we still create some padding to avoid scissoring just AA outsets. |
| 314 |
static constexpr int kRes = 4; |
| 315 |
Rect snapped = a.makeOutset(kRes - 1.f); |
| 316 |
snapped = Rect::FromVals(snapped.vals() * (1.f / kRes)).makeRoundOut(); |
| 317 |
return Rect::FromVals(snapped.vals() * kRes).makeIntersect(deviceBounds); |
| 318 |
} |
| 319 |
|
| 320 |
} // anonymous namespace |
| 321 |
|
| 322 |
/////////////////////////////////////////////////////////////////////////////// |
| 323 |
// ClipStack::TransformedShape |
| 324 |
|
| 325 |
// A flyweight object describing geometry, subject to a local-to-device transform. |
| 326 |
// This can be used by SaveRecords, Elements, and draws to determine how two shape operations |
| 327 |
// interact with each other, without needing to share a base class, friend each other, or have a |
| 328 |
// template for each combination of two types. |
| 329 |
struct ClipStack::TransformedShape { |
| 330 |
const Transform& fLocalToDevice; |
| 331 |
const Shape& fShape; |
| 332 |
const Rect& fOuterBounds; |
| 333 |
const Rect& fInnerBounds; |
| 334 |
|
| 335 |
SkClipOp fOp; |
| 336 |
|
| 337 |
// contains() performs a fair amount of work to be as accurate as possible since it can mean |
| 338 |
// greatly simplifying the clip stack. However, in some contexts this isn't worth doing because |
| 339 |
// the actual shape is only an approximation (save records), or there's no current way to take |
| 340 |
// advantage of knowing this shape contains another (draws containing a clip hypothetically |
| 341 |
// could replace their geometry to draw the clip directly, but that isn't implemented now). |
| 342 |
bool fContainsChecksOnlyBounds = false; |
| 343 |
|
| 344 |
bool intersects(const TransformedShape&) const; |
| 345 |
bool contains(const TransformedShape&) const; |
| 346 |
}; |
| 347 |
|
| 348 |
bool ClipStack::TransformedShape::intersects(const TransformedShape& o) const { |
| 349 |
if (!fOuterBounds.intersects(o.fOuterBounds)) { |
| 350 |
return false; |
| 351 |
} |
| 352 |
|
| 353 |
if (fLocalToDevice.type() <= Transform::Type::kRectStaysRect && |
| 354 |
o.fLocalToDevice.type() <= Transform::Type::kRectStaysRect) { |
| 355 |
// The two shape's coordinate spaces are different but both rect-stays-rect or simpler. |
| 356 |
// This means, though, that their outer bounds approximations are tight to their transormed |
| 357 |
// shape bounds. There's no point to do further tests given that and that we already found |
| 358 |
// that these outer bounds *do* intersect. |
| 359 |
return true; |
| 360 |
} else if (fLocalToDevice == o.fLocalToDevice) { |
| 361 |
// Since the two shape's local coordinate spaces are the same, we can compare shape |
| 362 |
// bounds directly for a more accurate intersection test. We intentionally do not go |
| 363 |
// further and do shape-specific intersection tests since these could have unknown |
| 364 |
// complexity (for paths) and limited utility (e.g. two round rects that are disjoint |
| 365 |
// solely from their corner curves). |
| 366 |
return fShape.bounds().intersects(o.fShape.bounds()); |
| 367 |
} else if (fLocalToDevice.type() != Transform::Type::kPerspective && |
| 368 |
o.fLocalToDevice.type() != Transform::Type::kPerspective) { |
| 369 |
// The shapes don't share the same coordinate system, and their approximate 'outer' |
| 370 |
// bounds in device space could have substantial outsetting to contain the transformed |
| 371 |
// shape (e.g. 45 degree rotation). Perform a more detailed check on their oriented |
| 372 |
// bounding boxes. |
| 373 |
return oriented_bbox_intersection(fShape.bounds(), fLocalToDevice, |
| 374 |
o.fShape.bounds(), o.fLocalToDevice); |
| 375 |
} |
| 376 |
// Else multiple perspective transforms are involved, so assume intersection and allow the |
| 377 |
// rasterizer to handle perspective clipping. |
| 378 |
return true; |
| 379 |
} |
| 380 |
|
| 381 |
bool ClipStack::TransformedShape::contains(const TransformedShape& o) const { |
| 382 |
if (fInnerBounds.contains(o.fOuterBounds)) { |
| 383 |
return true; |
| 384 |
} |
| 385 |
// Skip more expensive contains() checks if configured not to, or if the extent of 'o' exceeds |
| 386 |
// this shape's outer bounds. When that happens there must be some part of 'o' that cannot be |
| 387 |
// contained in this shape. |
| 388 |
if (fContainsChecksOnlyBounds || !fOuterBounds.contains(o.fOuterBounds)) { |
| 389 |
return false; |
| 390 |
} |
| 391 |
|
| 392 |
if (fContainsChecksOnlyBounds) { |
| 393 |
return false; // don't do any more work |
| 394 |
} |
| 395 |
|
| 396 |
if (fLocalToDevice == o.fLocalToDevice) { |
| 397 |
// Test the shapes directly against each other, with a special check for a rrect+rrect |
| 398 |
// containment (a intersect b == a implies b contains a) and paths (same gen ID, or same |
| 399 |
// path for small paths means they contain each other). |
| 400 |
static constexpr int kMaxPathComparePoints = 16; |
| 401 |
if (fShape.isRRect() && o.fShape.isRRect()) { |
| 402 |
return SkRRectPriv::ConservativeIntersect(fShape.rrect(), o.fShape.rrect()) |
| 403 |
== o.fShape.rrect(); |
| 404 |
} else if (fShape.isPath() && o.fShape.isPath()) { |
| 405 |
// TODO: Is this worth doing still if clips only cost as much as a single draw? |
| 406 |
return (fShape.path().getGenerationID() == o.fShape.path().getGenerationID()) || |
| 407 |
(fShape.path().countPoints() <= kMaxPathComparePoints && |
| 408 |
fShape.path() == o.fShape.path()); |
| 409 |
} else { |
| 410 |
return fShape.conservativeContains(o.fShape.bounds()); |
| 411 |
} |
| 412 |
} else if (fLocalToDevice.type() <= Transform::Type::kRectStaysRect && |
| 413 |
o.fLocalToDevice.type() <= Transform::Type::kRectStaysRect) { |
| 414 |
// Optimize the common case where o's bounds can be mapped tightly into this coordinate |
| 415 |
// space and then tested against our shape. |
| 416 |
Rect localBounds = fLocalToDevice.inverseMapRect( |
| 417 |
o.fLocalToDevice.mapRect(o.fShape.bounds())); |
| 418 |
return fShape.conservativeContains(localBounds); |
| 419 |
} else if (fShape.convex()) { |
| 420 |
// Since this shape is convex, if all four corners of o's bounding box are inside it |
| 421 |
// then the entirety of o is also guaranteed to be inside it. |
| 422 |
SkV4 deviceQuad[4]; |
| 423 |
o.fLocalToDevice.mapPoints(o.fShape.bounds(), deviceQuad); |
| 424 |
SkV4 localQuad[4]; |
| 425 |
fLocalToDevice.inverseMapPoints(deviceQuad, localQuad, 4); |
| 426 |
for (int i = 0; i < 4; ++i) { |
| 427 |
// TODO: Would be nice to make this consistent with how the GPU clips NDC w. |
| 428 |
if (deviceQuad[i].w < SkPathPriv::kW0PlaneDistance || |
| 429 |
localQuad[i].w < SkPathPriv::kW0PlaneDistance) { |
| 430 |
// Something in O actually projects behind the W = 0 plane and would be clipped |
| 431 |
// to infinity, so it's extremely unlikely that this contains O. |
| 432 |
return false; |
| 433 |
} |
| 434 |
if (!fShape.conservativeContains(skvx::float2::Load(localQuad + i) / localQuad[i].w)) { |
| 435 |
return false; |
| 436 |
} |
| 437 |
} |
| 438 |
return true; |
| 439 |
} |
| 440 |
|
| 441 |
// Else not an easily comparable pair of shapes so assume this doesn't contain O |
| 442 |
return false; |
| 443 |
} |
| 444 |
|
| 445 |
ClipStack::SimplifyResult ClipStack::Simplify(const TransformedShape& a, |
| 446 |
const TransformedShape& b) { |
| 447 |
enum class ClipCombo { |
| 448 |
kDD = 0b00, |
| 449 |
kDI = 0b01, |
| 450 |
kID = 0b10, |
| 451 |
kII = 0b11 |
| 452 |
}; |
| 453 |
|
| 454 |
switch(static_cast<ClipCombo>(((int) a.fOp << 1) | (int) b.fOp)) { |
| 455 |
case ClipCombo::kII: |
| 456 |
// Intersect (A) + Intersect (B) |
| 457 |
if (!a.intersects(b)) { |
| 458 |
// Regions with non-zero coverage are disjoint, so intersection = empty |
| 459 |
return SimplifyResult::kEmpty; |
| 460 |
} else if (b.contains(a)) { |
| 461 |
// B's full coverage region contains entirety of A, so intersection = A |
| 462 |
return SimplifyResult::kAOnly; |
| 463 |
} else if (a.contains(b)) { |
| 464 |
// A's full coverage region contains entirety of B, so intersection = B |
| 465 |
return SimplifyResult::kBOnly; |
| 466 |
} else { |
| 467 |
// The shapes intersect in some non-trivial manner |
| 468 |
return SimplifyResult::kBoth; |
| 469 |
} |
| 470 |
case ClipCombo::kID: |
| 471 |
// Intersect (A) + Difference (B) |
| 472 |
if (!a.intersects(b)) { |
| 473 |
// A only intersects B's full coverage region, so intersection = A |
| 474 |
return SimplifyResult::kAOnly; |
| 475 |
} else if (b.contains(a)) { |
| 476 |
// B's zero coverage region completely contains A, so intersection = empty |
| 477 |
return SimplifyResult::kEmpty; |
| 478 |
} else { |
| 479 |
// Intersection cannot be simplified. Note that the combination of a intersect |
| 480 |
// and difference op in this order cannot produce kBOnly |
| 481 |
return SimplifyResult::kBoth; |
| 482 |
} |
| 483 |
case ClipCombo::kDI: |
| 484 |
// Difference (A) + Intersect (B) - the mirror of Intersect(A) + Difference(B), |
| 485 |
// but combining is commutative so this is equivalent barring naming. |
| 486 |
if (!b.intersects(a)) { |
| 487 |
// B only intersects A's full coverage region, so intersection = B |
| 488 |
return SimplifyResult::kBOnly; |
| 489 |
} else if (a.contains(b)) { |
| 490 |
// A's zero coverage region completely contains B, so intersection = empty |
| 491 |
return SimplifyResult::kEmpty; |
| 492 |
} else { |
| 493 |
// Cannot be simplified |
| 494 |
return SimplifyResult::kBoth; |
| 495 |
} |
| 496 |
case ClipCombo::kDD: |
| 497 |
// Difference (A) + Difference (B) |
| 498 |
if (a.contains(b)) { |
| 499 |
// A's zero coverage region contains B, so B doesn't remove any extra |
| 500 |
// coverage from their intersection. |
| 501 |
return SimplifyResult::kAOnly; |
| 502 |
} else if (b.contains(a)) { |
| 503 |
// Mirror of the above case, intersection = B instead |
| 504 |
return SimplifyResult::kBOnly; |
| 505 |
} else { |
| 506 |
// Intersection of the two differences cannot be simplified. Note that for |
| 507 |
// this op combination it is not possible to produce kEmpty. |
| 508 |
return SimplifyResult::kBoth; |
| 509 |
} |
| 510 |
} |
| 511 |
SkUNREACHABLE; |
| 512 |
} |
| 513 |
|
| 514 |
ClipStack::DrawInfluence ClipStack::SimplifyForDraw(const TransformedShape& clip, |
| 515 |
const TransformedShape& draw) { |
| 516 |
// Given the asserts below, we can just recast the SimplifyResult returned from |
| 517 |
// Simplify(A=clip, B=draw): |
| 518 |
// |
| 519 |
// If the result is kEmpty, the draw is clipped out. |
| 520 |
static_assert((int) SimplifyResult::kEmpty == (int) DrawInfluence::kClipsOutDraw); |
| 521 |
// If the result is kAOnly, only the clip's shape provides coverage and the draw could be |
| 522 |
// replaced with something that just covers the clip bounds. |
| 523 |
static_assert((int) SimplifyResult::kAOnly == (int) DrawInfluence::kReplacesDraw); |
| 524 |
// If the result is kBOnly, the clip's shape doesn't impact the draw's coverage at all. |
| 525 |
static_assert((int) SimplifyResult::kBOnly == (int) DrawInfluence::kNone); |
| 526 |
// If the result is kBoth, the clip and the draw combine in a complex manner |
| 527 |
static_assert((int) SimplifyResult::kBoth == (int) DrawInfluence::kComplexInteraction); |
| 528 |
|
| 529 |
SimplifyResult result = Simplify(clip, draw); |
| 530 |
return static_cast<DrawInfluence>(result); |
| 531 |
} |
| 532 |
|
| 533 |
/////////////////////////////////////////////////////////////////////////////// |
| 534 |
// ClipStack::Element |
| 535 |
|
| 536 |
ClipStack::RawElement::RawElement(const Rect& deviceBounds, |
| 537 |
const Transform& localToDevice, |
| 538 |
const Shape& shape, |
| 539 |
SkClipOp op, |
| 540 |
PixelSnapping snapping) |
| 541 |
: Element{shape, localToDevice, op} |
| 542 |
, fUsageBounds{Rect::InfiniteInverted()} |
| 543 |
, fOrder(DrawOrder::kNoIntersection) |
| 544 |
, fMaxZ(DrawOrder::kClearDepth) |
| 545 |
, fInvalidatedByIndex(-1) { |
| 546 |
// Discard shapes that don't have any area (including when a transform can't be inverted, since |
| 547 |
// it means the two dimensions are collapsed to 0 or 1 dimension in device space). |
| 548 |
if (fShape.isLine() || !localToDevice.valid()) { |
| 549 |
fShape.reset(); |
| 550 |
} |
| 551 |
// Make sure the shape is not inverted. An inverted shape is equivalent to a non-inverted shape |
| 552 |
// with the clip op toggled. |
| 553 |
if (fShape.inverted()) { |
| 554 |
fOp = (fOp == SkClipOp::kIntersect) ? SkClipOp::kDifference : SkClipOp::kIntersect; |
| 555 |
} |
| 556 |
|
| 557 |
fOuterBounds = fLocalToDevice.mapRect(fShape.bounds()).makeIntersect(deviceBounds); |
| 558 |
fInnerBounds = Rect::InfiniteInverted(); |
| 559 |
|
| 560 |
// Apply rect-stays-rect transforms to rects and round rects to reduce the number of unique |
| 561 |
// local coordinate systems that are in play. |
| 562 |
if (!fOuterBounds.isEmptyNegativeOrNaN() && |
| 563 |
fLocalToDevice.type() <= Transform::Type::kRectStaysRect) { |
| 564 |
if (fShape.isRect()) { |
| 565 |
// The actual geometry can be updated to the device-intersected bounds and we know the |
| 566 |
// inner bounds are equal to the outer. |
| 567 |
if (snapping == PixelSnapping::kYes) { |
| 568 |
fOuterBounds.round(); |
| 569 |
} |
| 570 |
fShape.setRect(fOuterBounds); |
| 571 |
fLocalToDevice = Transform::Identity(); |
| 572 |
fInnerBounds = fOuterBounds; |
| 573 |
} else if (fShape.isRRect()) { |
| 574 |
// Can't transform in place and must still check transform result since some very |
| 575 |
// ill-formed scale+translate matrices can cause invalid rrect radii. |
| 576 |
if (auto xformed = fShape.rrect().transform(fLocalToDevice)) { |
| 577 |
if (snapping == PixelSnapping::kYes) { |
| 578 |
// The rounded corners will still be anti-aliased, but snap the horizontal and |
| 579 |
// vertical edges to pixel values. |
| 580 |
xformed->setRectRadii(SkRect::Make(xformed->rect().round()), |
| 581 |
xformed->radii().data()); |
| 582 |
} |
| 583 |
fShape.setRRect(*xformed); |
| 584 |
fLocalToDevice = Transform::Identity(); |
| 585 |
// Refresh outer bounds to match the transformed round rect in case |
| 586 |
// SkRRect::transform produces slightly different results from Transform::mapRect. |
| 587 |
fOuterBounds = fShape.bounds().makeIntersect(deviceBounds); |
| 588 |
fInnerBounds = Rect{SkRRectPriv::InnerBounds(*xformed)}.makeIntersect(fOuterBounds); |
| 589 |
} |
| 590 |
} |
| 591 |
} |
| 592 |
|
| 593 |
if (fOuterBounds.isEmptyNegativeOrNaN()) { |
| 594 |
// Either was already an empty shape or a non-empty shape is offscreen, so treat it as such. |
| 595 |
fShape.reset(); |
| 596 |
fInnerBounds = Rect::InfiniteInverted(); |
| 597 |
} |
| 598 |
|
| 599 |
// Now that fOp and fShape are canonical, set the shape's fill type to match how it needs to be |
| 600 |
// drawn as a depth-only shape everywhere that is clipped out (intersect is thus inverse-filled) |
| 601 |
fShape.setInverted(fOp == SkClipOp::kIntersect); |
| 602 |
|
| 603 |
// Post-conditions on inner and outer bounds |
| 604 |
SkASSERT(fShape.isEmpty() || deviceBounds.contains(fOuterBounds)); |
| 605 |
this->validate(); |
| 606 |
} |
| 607 |
|
| 608 |
ClipStack::RawElement::operator ClipStack::TransformedShape() const { |
| 609 |
return {fLocalToDevice, fShape, fOuterBounds, fInnerBounds, fOp}; |
| 610 |
} |
| 611 |
|
| 612 |
void ClipStack::RawElement::drawClip(Device* device) { |
| 613 |
this->validate(); |
| 614 |
|
| 615 |
// Skip elements that have not affected any draws |
| 616 |
if (!this->hasPendingDraw()) { |
| 617 |
SkASSERT(fUsageBounds.isEmptyNegativeOrNaN()); |
| 618 |
return; |
| 619 |
} |
| 620 |
|
| 621 |
SkASSERT(!fUsageBounds.isEmptyNegativeOrNaN()); |
| 622 |
// For clip draws, the usage bounds is the scissor. |
| 623 |
const Rect deviceBounds = Rect::WH(device->width(), device->height()); |
| 624 |
Rect scissor = fUsageBounds; // all joined usage bounds are pre-snapped |
| 625 |
|
| 626 |
// snappedOuterBounds was the rectangle used in updateForDraw() to query the Z order the clip's |
| 627 |
// draw will be inserted at. The scissor must enforce that rendering doesn't happen outside of |
| 628 |
// those bounds. |
| 629 |
Rect snappedOuterBounds = snap_scissor(fOuterBounds, deviceBounds); |
| 630 |
scissor.intersect(snappedOuterBounds); |
| 631 |
// But if the overlap is sufficiently large, just rasterize out to the snapped bounds instead of |
| 632 |
// adding a tight scissor. A factor of 1/2 is used because that corresponds to the area |
| 633 |
// change caused by a 45-degree rotation. |
| 634 |
if (0.5f * snappedOuterBounds.area() < scissor.area()) { |
| 635 |
scissor = snappedOuterBounds; |
| 636 |
} |
| 637 |
|
| 638 |
Rect drawBounds = fOp == SkClipOp::kIntersect ? scissor : fOuterBounds.makeIntersect(scissor); |
| 639 |
if (!drawBounds.isEmptyNegativeOrNaN()) { |
| 640 |
// Although we are recording this clip draw after all the draws it affects, 'fOrder' was |
| 641 |
// determined at the first usage, so after sorting by DrawOrder the clip draw will be in the |
| 642 |
// right place. Unlike regular draws that use their own "Z", by writing (1 + max Z this clip |
| 643 |
// affects), it will cause those draws to fail either GREATER and GEQUAL depth tests where |
| 644 |
// they need to be clipped. |
| 645 |
DrawOrder order{fMaxZ.next(), fOrder}; |
| 646 |
// An element's clip op is encoded in the shape's fill type. Inverse fills are intersect ops |
| 647 |
// and regular fills are difference ops. This means fShape is already in the right state to |
| 648 |
// draw directly. |
| 649 |
SkASSERT((fOp == SkClipOp::kDifference && !fShape.inverted()) || |
| 650 |
(fOp == SkClipOp::kIntersect && fShape.inverted())); |
| 651 |
|
| 652 |
// NOTE: We use fOuterBounds as the transformed shape bounds as that hasn't been clipped by |
| 653 |
// the scissor. It has been clipped by the device bounds, but that shouldn't impact any |
| 654 |
// decisions at this point. If that becomes not the case, we can either recompute the |
| 655 |
// shape's device-space bounds (fLocalToDevice.mapRect(fShape.bounds())) or store a fully |
| 656 |
// unclipped shape bounds on the RawElement. |
| 657 |
device->drawClipShape(fLocalToDevice, |
| 658 |
fShape, |
| 659 |
Clip{drawBounds, fOuterBounds, scissor.asSkIRect(), |
| 660 |
/* nonMSAAClip= */ {}, /* shader= */ nullptr}, |
| 661 |
order); |
| 662 |
} |
| 663 |
|
| 664 |
// After the clip shape is drawn, reset its state. If the clip element is being popped off the |
| 665 |
// stack or overwritten because a new clip invalidated it, this won't matter. But if the clips |
| 666 |
// were drawn because the Device had to flush pending work while the clip stack was not empty, |
| 667 |
// subsequent draws will still need to be clipped to the elements. In this case, the usage |
| 668 |
// accumulation process will begin again and automatically use the Device's post-flush Z values |
| 669 |
// and BoundsManager state. |
| 670 |
fUsageBounds = Rect::InfiniteInverted(); |
| 671 |
fOrder = DrawOrder::kNoIntersection; |
| 672 |
fMaxZ = DrawOrder::kClearDepth; |
| 673 |
} |
| 674 |
|
| 675 |
void ClipStack::RawElement::validate() const { |
| 676 |
// If the shape type isn't empty, the outer bounds shouldn't be empty; if the inner bounds are |
| 677 |
// not empty, they must be contained in outer. |
| 678 |
SkASSERT((fShape.isEmpty() || !fOuterBounds.isEmptyNegativeOrNaN()) && |
| 679 |
(fInnerBounds.isEmptyNegativeOrNaN() || fOuterBounds.contains(fInnerBounds))); |
| 680 |
SkASSERT((fOp == SkClipOp::kDifference && !fShape.inverted()) || |
| 681 |
(fOp == SkClipOp::kIntersect && fShape.inverted())); |
| 682 |
SkASSERT(!this->hasPendingDraw() || !fUsageBounds.isEmptyNegativeOrNaN()); |
| 683 |
} |
| 684 |
|
| 685 |
void ClipStack::RawElement::markInvalid(const SaveRecord& current) { |
| 686 |
SkASSERT(!this->isInvalid()); |
| 687 |
fInvalidatedByIndex = current.firstActiveElementIndex(); |
| 688 |
// NOTE: We don't draw the accumulated clip usage when the element is marked invalid. Some |
| 689 |
// invalidated elements are part of earlier save records so can become re-active after a restore |
| 690 |
// in which case they should continue to accumulate. Invalidated elements that are part of the |
| 691 |
// active save record are removed at the end of the stack modification, which is when they are |
| 692 |
// explicitly drawn. |
| 693 |
} |
| 694 |
|
| 695 |
void ClipStack::RawElement::restoreValid(const SaveRecord& current) { |
| 696 |
if (current.firstActiveElementIndex() < fInvalidatedByIndex) { |
| 697 |
fInvalidatedByIndex = -1; |
| 698 |
} |
| 699 |
} |
| 700 |
|
| 701 |
bool ClipStack::RawElement::combine(const RawElement& other, const SaveRecord& current) { |
| 702 |
// Don't combine elements that have collected draw usage, since that changes their geometry. |
| 703 |
if (this->hasPendingDraw() || other.hasPendingDraw()) { |
| 704 |
return false; |
| 705 |
} |
| 706 |
// To reduce the number of possibilities, only consider intersect+intersect. Difference and |
| 707 |
// mixed op cases could be analyzed to simplify one of the shapes, but that is a rare |
| 708 |
// occurrence and the math is much more complicated. |
| 709 |
if (other.fOp != SkClipOp::kIntersect || fOp != SkClipOp::kIntersect) { |
| 710 |
return false; |
| 711 |
} |
| 712 |
|
| 713 |
// NOTE: intersect_shape operates on the underlying geometry and ignores the fill rule, which |
| 714 |
// because these are intersect clip ops, is the inverse fill. If the shape is updated, the |
| 715 |
// resulting geometry is set to a regular fill so it must be re-inverted to represent the |
| 716 |
// pixels rasterized for a depth-only clip draw. |
| 717 |
SkEnumBitMask<EdgeAAQuad::Flags> edgeFlags = EdgeAAQuad::Flags::kAll; |
| 718 |
const bool shapeUpdated = intersect_shape(other.fLocalToDevice, other.fShape, |
| 719 |
fLocalToDevice, &fShape, &edgeFlags); |
| 720 |
SkASSERT(edgeFlags == EdgeAAQuad::Flags::kAll); |
| 721 |
|
| 722 |
if (shapeUpdated) { |
| 723 |
// This logic works under the assumption that both combined elements were intersect. |
| 724 |
SkASSERT(fOp == SkClipOp::kIntersect && other.fOp == SkClipOp::kIntersect); |
| 725 |
fOuterBounds.intersect(other.fOuterBounds); |
| 726 |
fInnerBounds.intersect(other.fInnerBounds); |
| 727 |
// Inner bounds can become empty, but outer bounds should not be able to. |
| 728 |
SkASSERT(!fOuterBounds.isEmptyNegativeOrNaN()); |
| 729 |
fShape.setInverted(true); // Undo intersect_shape setting it to non-inverse |
| 730 |
this->validate(); |
| 731 |
return true; |
| 732 |
} else { |
| 733 |
return false; |
| 734 |
} |
| 735 |
} |
| 736 |
|
| 737 |
void ClipStack::RawElement::updateForElement(RawElement* added, const SaveRecord& current) { |
| 738 |
if (this->isInvalid()) { |
| 739 |
// Already doesn't do anything, so skip this element |
| 740 |
return; |
| 741 |
} |
| 742 |
|
| 743 |
// 'A' refers to this element, 'B' refers to 'added'. |
| 744 |
switch (Simplify(*this, *added)) { |
| 745 |
case SimplifyResult::kEmpty: |
| 746 |
// Mark both elements as invalid to signal that the clip is fully empty |
| 747 |
this->markInvalid(current); |
| 748 |
added->markInvalid(current); |
| 749 |
break; |
| 750 |
|
| 751 |
case SimplifyResult::kAOnly: |
| 752 |
// This element already clips more than 'added', so mark 'added' is invalid to skip it |
| 753 |
added->markInvalid(current); |
| 754 |
break; |
| 755 |
|
| 756 |
case SimplifyResult::kBOnly: |
| 757 |
// 'added' clips more than this element, so mark this as invalid |
| 758 |
this->markInvalid(current); |
| 759 |
break; |
| 760 |
|
| 761 |
case SimplifyResult::kBoth: |
| 762 |
// Else the bounds checks think we need to keep both, but depending on the combination |
| 763 |
// of the ops and shape kinds, we may be able to do better. |
| 764 |
if (added->combine(*this, current)) { |
| 765 |
// 'added' now fully represents the combination of the two elements |
| 766 |
this->markInvalid(current); |
| 767 |
} |
| 768 |
break; |
| 769 |
} |
| 770 |
} |
| 771 |
|
| 772 |
ClipStack::DrawInfluence ClipStack::RawElement::testForDraw(const TransformedShape& draw) const { |
| 773 |
if (this->isInvalid()) { |
| 774 |
// Cannot affect the draw |
| 775 |
return DrawInfluence::kNone; |
| 776 |
} |
| 777 |
|
| 778 |
return SimplifyForDraw(*this, draw); |
| 779 |
} |
| 780 |
|
| 781 |
CompressedPaintersOrder ClipStack::RawElement::updateForDraw(const BoundsManager* boundsManager, |
| 782 |
const Rect& deviceBounds, |
| 783 |
const Rect& drawBounds, |
| 784 |
PaintersDepth drawZ) { |
| 785 |
SkASSERT(!this->isInvalid()); |
| 786 |
SkASSERT(!drawBounds.isEmptyNegativeOrNaN()); |
| 787 |
|
| 788 |
// Always record snapped draw bounds to avoid scissor thrashing since these bounds will be used |
| 789 |
// to determine the scissor applied to the depth-only draw for the clip element. |
| 790 |
Rect snappedDrawBounds = snap_scissor(drawBounds, deviceBounds); |
| 791 |
|
| 792 |
if (!this->hasPendingDraw()) { |
| 793 |
// No usage yet so we need an order that we will use when drawing to just the depth |
| 794 |
// attachment. It is sufficient to use the next CompressedPaintersOrder after the |
| 795 |
// most recent draw under this clip's outer bounds. It is necessary to use the |
| 796 |
// entire clip's outer bounds because the order has to be determined before the |
| 797 |
// final usage bounds are known and a subsequent draw could require a completely |
| 798 |
// different portion of the clip than this triggering draw. |
| 799 |
// |
| 800 |
// Lazily determining the order has several benefits to computing it when the clip |
| 801 |
// element was first created: |
| 802 |
// - Elements that are invalidated by nested clips before draws are made do not |
| 803 |
// waste time in the BoundsManager. |
| 804 |
// - Elements that never actually modify a draw (e.g. a defensive clip) do not |
| 805 |
// waste time in the BoundsManager. |
| 806 |
// - A draw that triggers clip usage on multiple elements will more likely assign |
| 807 |
// the same order to those elements, meaning their depth-only draws are more |
| 808 |
// likely to batch in the final DrawPass. |
| 809 |
// |
| 810 |
// However, it does mean that clip elements can have the same order as each other, |
| 811 |
// or as later draws (e.g. after the clip has been popped off the stack). Any |
| 812 |
// overlap between clips or draws is addressed when the clip is drawn by selecting |
| 813 |
// an appropriate DisjointStencilIndex value. Stencil-aside, this order assignment |
| 814 |
// logic, max Z tracking, and the depth test during rasterization are able to |
| 815 |
// resolve everything correctly even if clips have the same order value. |
| 816 |
// See go/clip-stack-order for a detailed analysis of why this works. |
| 817 |
Rect snappedOuterBounds = snap_scissor(fOuterBounds, deviceBounds); |
| 818 |
fOrder = boundsManager->getMostRecentDraw(snappedOuterBounds).next(); |
| 819 |
fUsageBounds = snappedDrawBounds; |
| 820 |
fMaxZ = drawZ; |
| 821 |
} else { |
| 822 |
// Earlier draws have already used this element so we cannot change where the |
| 823 |
// depth-only draw will be sorted to, but we need to ensure we cover the new draw's |
| 824 |
// bounds and use a Z value that will clip out its pixels as appropriate. |
| 825 |
fUsageBounds.join(snappedDrawBounds); |
| 826 |
if (drawZ > fMaxZ) { |
| 827 |
fMaxZ = drawZ; |
| 828 |
} |
| 829 |
} |
| 830 |
|
| 831 |
return fOrder; |
| 832 |
} |
| 833 |
|
| 834 |
ClipStack::ClipState ClipStack::RawElement::clipType() const { |
| 835 |
// Map from the internal shape kind to the clip state enum |
| 836 |
switch (fShape.type()) { |
| 837 |
case Shape::Type::kEmpty: |
| 838 |
return ClipState::kEmpty; |
| 839 |
|
| 840 |
case Shape::Type::kRect: |
| 841 |
return fOp == SkClipOp::kIntersect && |
| 842 |
fLocalToDevice.type() == Transform::Type::kIdentity |
| 843 |
? ClipState::kDeviceRect : ClipState::kComplex; |
| 844 |
|
| 845 |
case Shape::Type::kRRect: |
| 846 |
return fOp == SkClipOp::kIntersect && |
| 847 |
fLocalToDevice.type() == Transform::Type::kIdentity |
| 848 |
? ClipState::kDeviceRRect : ClipState::kComplex; |
| 849 |
|
| 850 |
case Shape::Type::kArc: |
| 851 |
case Shape::Type::kLine: |
| 852 |
// These types should never become RawElements, but call them kComplex in release builds |
| 853 |
SkASSERT(false); |
| 854 |
[[fallthrough]]; |
| 855 |
|
| 856 |
case Shape::Type::kPath: |
| 857 |
return ClipState::kComplex; |
| 858 |
} |
| 859 |
SkUNREACHABLE; |
| 860 |
} |
| 861 |
|
| 862 |
/////////////////////////////////////////////////////////////////////////////// |
| 863 |
// ClipStack::SaveRecord |
| 864 |
|
| 865 |
ClipStack::SaveRecord::SaveRecord(const Rect& deviceBounds) |
| 866 |
: fInnerBounds(deviceBounds) |
| 867 |
, fOuterBounds(deviceBounds) |
| 868 |
, fShader(nullptr) |
| 869 |
, fStartingElementIndex(0) |
| 870 |
, fOldestValidIndex(0) |
| 871 |
, fDeferredSaveCount(0) |
| 872 |
, fStackOp(SkClipOp::kIntersect) |
| 873 |
, fState(ClipState::kWideOpen) |
| 874 |
, fGenID(kInvalidGenID) {} |
| 875 |
|
| 876 |
ClipStack::SaveRecord::SaveRecord(const SaveRecord& prior, |
| 877 |
int startingElementIndex) |
| 878 |
: fInnerBounds(prior.fInnerBounds) |
| 879 |
, fOuterBounds(prior.fOuterBounds) |
| 880 |
, fShader(prior.fShader) |
| 881 |
, fStartingElementIndex(startingElementIndex) |
| 882 |
, fOldestValidIndex(prior.fOldestValidIndex) |
| 883 |
, fDeferredSaveCount(0) |
| 884 |
, fStackOp(prior.fStackOp) |
| 885 |
, fState(prior.fState) |
| 886 |
, fGenID(kInvalidGenID) { |
| 887 |
// If the prior record added an element, this one will insert into the same index |
| 888 |
// (that's okay since we'll remove it when this record is popped off the stack). |
| 889 |
SkASSERT(startingElementIndex >= prior.fStartingElementIndex); |
| 890 |
} |
| 891 |
|
| 892 |
uint32_t ClipStack::SaveRecord::genID() const { |
| 893 |
if (fState == ClipState::kEmpty) { |
| 894 |
return kEmptyGenID; |
| 895 |
} else if (fState == ClipState::kWideOpen) { |
| 896 |
return kWideOpenGenID; |
| 897 |
} else { |
| 898 |
// The gen ID shouldn't be empty or wide open, since they are reserved for the above |
| 899 |
// if-cases. It may be kInvalid if the record hasn't had any elements added to it yet. |
| 900 |
SkASSERT(fGenID != kEmptyGenID && fGenID != kWideOpenGenID); |
| 901 |
return fGenID; |
| 902 |
} |
| 903 |
} |
| 904 |
|
| 905 |
ClipStack::ClipState ClipStack::SaveRecord::state() const { |
| 906 |
if (fShader && fState != ClipState::kEmpty) { |
| 907 |
return ClipState::kComplex; |
| 908 |
} else { |
| 909 |
return fState; |
| 910 |
} |
| 911 |
} |
| 912 |
|
| 913 |
ClipStack::DrawInfluence ClipStack::SaveRecord::testForDraw(const TransformedShape& draw) const { |
| 914 |
Transform identity = Transform::Identity(); |
| 915 |
Shape outerSaveBounds{fOuterBounds}; |
| 916 |
TransformedShape save{identity, outerSaveBounds, fOuterBounds, fInnerBounds, fStackOp, |
| 917 |
/*containsChecksOnlyBounds=*/true}; |
| 918 |
|
| 919 |
return SimplifyForDraw(save, draw); |
| 920 |
} |
| 921 |
|
| 922 |
void ClipStack::SaveRecord::removeElements(RawElement::Stack* elements, Device* device) { |
| 923 |
while (elements->count() > fStartingElementIndex) { |
| 924 |
// Since the element is being deleted now, it won't be in the ClipStack when the Device |
| 925 |
// calls recordDeferredClipDraws(). Record the clip's draw now (if it needs it). |
| 926 |
elements->back().drawClip(device); |
| 927 |
elements->pop_back(); |
| 928 |
} |
| 929 |
} |
| 930 |
|
| 931 |
void ClipStack::SaveRecord::restoreElements(RawElement::Stack* elements) { |
| 932 |
// Presumably this SaveRecord is the new top of the stack, and so it owns the elements |
| 933 |
// from its starting index to restoreCount - 1. Elements from the old save record have |
| 934 |
// been destroyed already, so their indices would have been >= restoreCount, and any |
| 935 |
// still-present element can be un-invalidated based on that. |
| 936 |
int i = elements->count() - 1; |
| 937 |
for (RawElement& e : elements->ritems()) { |
| 938 |
if (i < fOldestValidIndex) { |
| 939 |
break; |
| 940 |
} |
| 941 |
e.restoreValid(*this); |
| 942 |
--i; |
| 943 |
} |
| 944 |
} |
| 945 |
|
| 946 |
void ClipStack::SaveRecord::addShader(sk_sp<SkShader> shader) { |
| 947 |
SkASSERT(shader); |
| 948 |
SkASSERT(this->canBeUpdated()); |
| 949 |
if (!fShader) { |
| 950 |
fShader = std::move(shader); |
| 951 |
} else { |
| 952 |
// The total coverage is computed by multiplying the coverage from each element (shape or |
| 953 |
// shader), but since multiplication is associative, we can use kSrcIn blending to make |
| 954 |
// a new shader that represents 'shader' * 'fShader' |
| 955 |
fShader = SkShaders::Blend(SkBlendMode::kSrcIn, std::move(shader), fShader); |
| 956 |
} |
| 957 |
} |
| 958 |
|
| 959 |
bool ClipStack::SaveRecord::addElement(RawElement&& toAdd, |
| 960 |
RawElement::Stack* elements, |
| 961 |
Device* device) { |
| 962 |
// Validity check the element's state first |
| 963 |
toAdd.validate(); |
| 964 |
|
| 965 |
// And we shouldn't be adding an element if we have a deferred save |
| 966 |
SkASSERT(this->canBeUpdated()); |
| 967 |
|
| 968 |
if (fState == ClipState::kEmpty) { |
| 969 |
// The clip is already empty, and we only shrink, so there's no need to record this element. |
| 970 |
return false; |
| 971 |
} else if (toAdd.shape().isEmpty()) { |
| 972 |
// An empty difference op should have been detected earlier, since it's a no-op |
| 973 |
SkASSERT(toAdd.op() == SkClipOp::kIntersect); |
| 974 |
fState = ClipState::kEmpty; |
| 975 |
this->removeElements(elements, device); |
| 976 |
return true; |
| 977 |
} |
| 978 |
|
| 979 |
// Here we treat the SaveRecord as a "TransformedShape" with the identity transform, and a shape |
| 980 |
// equal to its outer bounds. This lets us get accurate intersection tests against the new |
| 981 |
// element, but we pass true to skip more detailed contains checks because the SaveRecord's |
| 982 |
// shape is potentially very different from its aggregate outer bounds. |
| 983 |
Shape outerSaveBounds{fOuterBounds}; |
| 984 |
Transform identity = Transform::Identity(); |
| 985 |
TransformedShape save{identity, outerSaveBounds, fOuterBounds, fInnerBounds, fStackOp, |
| 986 |
/*containsChecksOnlyBounds=*/true}; |
| 987 |
|
| 988 |
// In this invocation, 'A' refers to the existing stack's bounds and 'B' refers to the new |
| 989 |
// element. |
| 990 |
switch (Simplify(save, toAdd)) { |
| 991 |
case SimplifyResult::kEmpty: |
| 992 |
// The combination results in an empty clip |
| 993 |
fState = ClipState::kEmpty; |
| 994 |
this->removeElements(elements, device); |
| 995 |
return true; |
| 996 |
|
| 997 |
case SimplifyResult::kAOnly: |
| 998 |
// The combination would not be any different than the existing clip |
| 999 |
return false; |
| 1000 |
|
| 1001 |
case SimplifyResult::kBOnly: |
| 1002 |
// The combination would invalidate the entire existing stack and can be replaced with |
| 1003 |
// just the new element. |
| 1004 |
this->replaceWithElement(std::move(toAdd), elements, device); |
| 1005 |
return true; |
| 1006 |
|
| 1007 |
case SimplifyResult::kBoth: |
| 1008 |
// The new element combines in a complex manner, so update the stack's bounds based on |
| 1009 |
// the combination of its and the new element's ops (handled below) |
| 1010 |
break; |
| 1011 |
} |
| 1012 |
|
| 1013 |
if (fState == ClipState::kWideOpen) { |
| 1014 |
// When the stack was wide open and the clip effect was kBoth, the "complex" manner is |
| 1015 |
// simply to keep the element and update the stack bounds to be the element's intersected |
| 1016 |
// with the device. |
| 1017 |
this->replaceWithElement(std::move(toAdd), elements, device); |
| 1018 |
return true; |
| 1019 |
} |
| 1020 |
|
| 1021 |
// Some form of actual clip element(s) to combine with. |
| 1022 |
if (fStackOp == SkClipOp::kIntersect) { |
| 1023 |
if (toAdd.op() == SkClipOp::kIntersect) { |
| 1024 |
// Intersect (stack) + Intersect (toAdd) |
| 1025 |
// - Bounds updates is simply the paired intersections of outer and inner. |
| 1026 |
fOuterBounds.intersect(toAdd.outerBounds()); |
| 1027 |
fInnerBounds.intersect(toAdd.innerBounds()); |
| 1028 |
// Outer should not have become empty, but is allowed to if there's no intersection. |
| 1029 |
SkASSERT(!fOuterBounds.isEmptyNegativeOrNaN()); |
| 1030 |
} else { |
| 1031 |
// Intersect (stack) + Difference (toAdd) |
| 1032 |
// - Shrink the stack's outer bounds if the difference op's inner bounds completely |
| 1033 |
// cuts off an edge. |
| 1034 |
// - Shrink the stack's inner bounds to completely exclude the op's outer bounds. |
| 1035 |
fOuterBounds = subtract(fOuterBounds, toAdd.innerBounds(), /* exact */ true); |
| 1036 |
fInnerBounds = subtract(fInnerBounds, toAdd.outerBounds(), /* exact */ false); |
| 1037 |
} |
| 1038 |
} else { |
| 1039 |
if (toAdd.op() == SkClipOp::kIntersect) { |
| 1040 |
// Difference (stack) + Intersect (toAdd) |
| 1041 |
// - Bounds updates are just the mirror of Intersect(stack) + Difference(toAdd) |
| 1042 |
Rect oldOuter = fOuterBounds; |
| 1043 |
fOuterBounds = subtract(toAdd.outerBounds(), fInnerBounds, /* exact */ true); |
| 1044 |
fInnerBounds = subtract(toAdd.innerBounds(), oldOuter, /* exact */ false); |
| 1045 |
} else { |
| 1046 |
// Difference (stack) + Difference (toAdd) |
| 1047 |
// - The updated outer bounds is the union of outer bounds and the inner becomes the |
| 1048 |
// largest of the two possible inner bounds |
| 1049 |
fOuterBounds.join(toAdd.outerBounds()); |
| 1050 |
if (toAdd.innerBounds().area() > fInnerBounds.area()) { |
| 1051 |
fInnerBounds = toAdd.innerBounds(); |
| 1052 |
} |
| 1053 |
} |
| 1054 |
} |
| 1055 |
|
| 1056 |
// If we get here, we're keeping the new element and the stack's bounds have been updated. |
| 1057 |
// We ought to have caught the cases where the stack bounds resemble an empty or wide open |
| 1058 |
// clip, so assert that's the case. |
| 1059 |
SkASSERT(!fOuterBounds.isEmptyNegativeOrNaN() && |
| 1060 |
(fInnerBounds.isEmptyNegativeOrNaN() || fOuterBounds.contains(fInnerBounds))); |
| 1061 |
|
| 1062 |
return this->appendElement(std::move(toAdd), elements, device); |
| 1063 |
} |
| 1064 |
|
| 1065 |
bool ClipStack::SaveRecord::appendElement(RawElement&& toAdd, |
| 1066 |
RawElement::Stack* elements, |
| 1067 |
Device* device) { |
| 1068 |
// Update past elements to account for the new element |
| 1069 |
int i = elements->count() - 1; |
| 1070 |
|
| 1071 |
// After the loop, elements between [max(youngestValid, startingIndex)+1, count-1] can be |
| 1072 |
// removed from the stack (these are the active elements that have been invalidated by the |
| 1073 |
// newest element; since it's the active part of the stack, no restore() can bring them back). |
| 1074 |
int youngestValid = fStartingElementIndex - 1; |
| 1075 |
// After the loop, elements between [0, oldestValid-1] are all invalid. The value of oldestValid |
| 1076 |
// becomes the save record's new fLastValidIndex value. |
| 1077 |
int oldestValid = elements->count(); |
| 1078 |
// After the loop, this is the earliest active element that was invalidated. It may be |
| 1079 |
// older in the stack than earliestValid, so cannot be popped off, but can be used to store |
| 1080 |
// the new element instead of allocating more. |
| 1081 |
RawElement* oldestActiveInvalid = nullptr; |
| 1082 |
int oldestActiveInvalidIndex = elements->count(); |
| 1083 |
|
| 1084 |
for (RawElement& existing : elements->ritems()) { |
| 1085 |
if (i < fOldestValidIndex) { |
| 1086 |
break; |
| 1087 |
} |
| 1088 |
// We don't need to pass the actual index that toAdd will be saved to; just the minimum |
| 1089 |
// index of this save record, since that will result in the same restoration behavior later. |
| 1090 |
existing.updateForElement(&toAdd, *this); |
| 1091 |
|
| 1092 |
if (toAdd.isInvalid()) { |
| 1093 |
if (existing.isInvalid()) { |
| 1094 |
// Both new and old invalid implies the entire clip becomes empty |
| 1095 |
fState = ClipState::kEmpty; |
| 1096 |
return true; |
| 1097 |
} else { |
| 1098 |
// The new element doesn't change the clip beyond what the old element already does |
| 1099 |
return false; |
| 1100 |
} |
| 1101 |
} else if (existing.isInvalid()) { |
| 1102 |
// The new element cancels out the old element. The new element may have been modified |
| 1103 |
// to account for the old element's geometry. |
| 1104 |
if (i >= fStartingElementIndex) { |
| 1105 |
// Still active, so the invalidated index could be used to store the new element |
| 1106 |
oldestActiveInvalid = &existing; |
| 1107 |
oldestActiveInvalidIndex = i; |
| 1108 |
} |
| 1109 |
} else { |
| 1110 |
// Keep both new and old elements |
| 1111 |
oldestValid = i; |
| 1112 |
if (i > youngestValid) { |
| 1113 |
youngestValid = i; |
| 1114 |
} |
| 1115 |
} |
| 1116 |
|
| 1117 |
--i; |
| 1118 |
} |
| 1119 |
|
| 1120 |
// Post-iteration validity check |
| 1121 |
SkASSERT(oldestValid == elements->count() || |
| 1122 |
(oldestValid >= fOldestValidIndex && oldestValid < elements->count())); |
| 1123 |
SkASSERT(youngestValid == fStartingElementIndex - 1 || |
| 1124 |
(youngestValid >= fStartingElementIndex && youngestValid < elements->count())); |
| 1125 |
SkASSERT((oldestActiveInvalid && oldestActiveInvalidIndex >= fStartingElementIndex && |
| 1126 |
oldestActiveInvalidIndex < elements->count()) || !oldestActiveInvalid); |
| 1127 |
|
| 1128 |
// Update final state |
| 1129 |
SkASSERT(oldestValid >= fOldestValidIndex); |
| 1130 |
fOldestValidIndex = std::min(oldestValid, oldestActiveInvalidIndex); |
| 1131 |
fState = oldestValid == elements->count() ? toAdd.clipType() : ClipState::kComplex; |
| 1132 |
if (fStackOp == SkClipOp::kDifference && toAdd.op() == SkClipOp::kIntersect) { |
| 1133 |
// The stack remains in difference mode only as long as all elements are difference |
| 1134 |
fStackOp = SkClipOp::kIntersect; |
| 1135 |
} |
| 1136 |
|
| 1137 |
int targetCount = youngestValid + 1; |
| 1138 |
if (!oldestActiveInvalid || oldestActiveInvalidIndex >= targetCount) { |
| 1139 |
// toAdd will be stored right after youngestValid |
| 1140 |
targetCount++; |
| 1141 |
oldestActiveInvalid = nullptr; |
| 1142 |
} |
| 1143 |
while (elements->count() > targetCount) { |
| 1144 |
SkASSERT(oldestActiveInvalid != &elements->back()); // shouldn't delete what we'll reuse |
| 1145 |
elements->back().drawClip(device); |
| 1146 |
elements->pop_back(); |
| 1147 |
} |
| 1148 |
if (oldestActiveInvalid) { |
| 1149 |
oldestActiveInvalid->drawClip(device); |
| 1150 |
*oldestActiveInvalid = std::move(toAdd); |
| 1151 |
} else if (elements->count() < targetCount) { |
| 1152 |
elements->push_back(std::move(toAdd)); |
| 1153 |
} else { |
| 1154 |
elements->back().drawClip(device); |
| 1155 |
elements->back() = std::move(toAdd); |
| 1156 |
} |
| 1157 |
|
| 1158 |
// Changing this will prompt ClipStack to invalidate any masks associated with this record. |
| 1159 |
fGenID = next_gen_id(); |
| 1160 |
return true; |
| 1161 |
} |
| 1162 |
|
| 1163 |
void ClipStack::SaveRecord::replaceWithElement(RawElement&& toAdd, |
| 1164 |
RawElement::Stack* elements, |
| 1165 |
Device* device) { |
| 1166 |
// The aggregate state of the save record mirrors the element |
| 1167 |
fInnerBounds = toAdd.innerBounds(); |
| 1168 |
fOuterBounds = toAdd.outerBounds(); |
| 1169 |
fStackOp = toAdd.op(); |
| 1170 |
fState = toAdd.clipType(); |
| 1171 |
|
| 1172 |
// All prior active element can be removed from the stack: [startingIndex, count - 1] |
| 1173 |
int targetCount = fStartingElementIndex + 1; |
| 1174 |
while (elements->count() > targetCount) { |
| 1175 |
elements->back().drawClip(device); |
| 1176 |
elements->pop_back(); |
| 1177 |
} |
| 1178 |
if (elements->count() < targetCount) { |
| 1179 |
elements->push_back(std::move(toAdd)); |
| 1180 |
} else { |
| 1181 |
elements->back().drawClip(device); |
| 1182 |
elements->back() = std::move(toAdd); |
| 1183 |
} |
| 1184 |
|
| 1185 |
SkASSERT(elements->count() == fStartingElementIndex + 1); |
| 1186 |
|
| 1187 |
// This invalidates all older elements that are owned by save records lower in the clip stack. |
| 1188 |
fOldestValidIndex = fStartingElementIndex; |
| 1189 |
fGenID = next_gen_id(); |
| 1190 |
} |
| 1191 |
|
| 1192 |
/////////////////////////////////////////////////////////////////////////////// |
| 1193 |
// ClipStack::DrawShape |
| 1194 |
|
| 1195 |
/** |
| 1196 |
* DrawShape represents the approximate shape that is being drawn in order to compare it against |
| 1197 |
* the clip stack's RawElements. It is able to map to a `TransformedShape` to be simplified with |
| 1198 |
* either the SaveRecord or each element. For non-Shape geometries and stroked shapes, it |
| 1199 |
* represents the oriented bounding box. For filled Shapes, it preserves the original shape for |
| 1200 |
* more accurate contains/intersect checks and geometrically combining RawElements into the |
| 1201 |
* shape. |
| 1202 |
*/ |
| 1203 |
class ClipStack::DrawShape { |
| 1204 |
public: |
| 1205 |
DrawShape(const Transform& localToDevice, const Geometry& geometry) |
| 1206 |
: fLocalToDevice(&localToDevice) |
| 1207 |
, fEdgeFlags(EdgeAAQuad::Flags::kAll) |
| 1208 |
, fScissor(Rect::Infinite()) |
| 1209 |
, fShapeWasModified(false) { |
| 1210 |
if (geometry.isShape()) { |
| 1211 |
fShape = geometry.shape(); |
| 1212 |
fShapeMatchesGeometry = true; |
| 1213 |
} else { |
| 1214 |
// The geometry is something special like text or vertices, in which case it's |
| 1215 |
// definitely not a shape that could simplify cleanly with the clip stack, so just track |
| 1216 |
// its bounds. The exception is EdgeAA quads that are rectangular, in which case we can |
| 1217 |
// clip its edges and adjust edge flags. |
| 1218 |
fShape.setRect(geometry.bounds()); |
| 1219 |
if (geometry.isEdgeAAQuad()) { |
| 1220 |
fEdgeFlags = geometry.edgeAAQuad().edgeFlags(); |
| 1221 |
fShapeMatchesGeometry = geometry.edgeAAQuad().isRect(); |
| 1222 |
} else { |
| 1223 |
fShapeMatchesGeometry = false; |
| 1224 |
} |
| 1225 |
// If geometry is not a shape, it is not inverted. |
| 1226 |
SkASSERT(!fShape.inverted()); |
| 1227 |
} |
| 1228 |
|
| 1229 |
fShapeCompatibleWithIntersectShape = fShape.isFloodFill() || |
| 1230 |
(!fShape.inverted() && (fShape.isRect() || |
| 1231 |
fShape.isRRect())); |
| 1232 |
} |
| 1233 |
|
| 1234 |
operator TransformedShape() const { |
| 1235 |
// A regular draw is a transformed shape that "intersects" the clip. An inverse-filled draw |
| 1236 |
// is equivalent to "difference". For simple convex shapes we provide an inner bounds |
| 1237 |
// because we can geometrically intersect clip elements with the draw geometry and not |
| 1238 |
// really impact the choice of Renderer (given the family of renderers used for simple |
| 1239 |
// shapes). In theory any convex shape could provide an inner bounds and/or use the detailed |
| 1240 |
// contains check, but that would cause path rendering draws to potentially change in hard |
| 1241 |
// to predict ways. |
| 1242 |
SkClipOp op = fShape.inverted() ? SkClipOp::kDifference : SkClipOp::kIntersect; |
| 1243 |
return TransformedShape{*fLocalToDevice, fShape, fOuterBounds, fInnerBounds, op, |
| 1244 |
/*containsChecksOnlyBounds=*/!this->shapeCanBeModified()}; |
| 1245 |
} |
| 1246 |
|
| 1247 |
bool shapeCanBeModified() const { |
| 1248 |
return fShapeCompatibleWithIntersectShape && fShapeMatchesGeometry; |
| 1249 |
} |
| 1250 |
|
| 1251 |
bool applyStyle(const SkStrokeRec& style, const Rect& deviceBounds); |
| 1252 |
void applyScissor(const Rect& scissor); |
| 1253 |
|
| 1254 |
void resetToFloodFill(); |
| 1255 |
bool intersectClipElement(const RawElement& clip); |
| 1256 |
|
| 1257 |
// Sync any modifications back to `geometry` and return a Clip object encapsulating the |
| 1258 |
// tracked bounds of the now-clipped draw. |
| 1259 |
Clip toClip(Geometry* geometry, const NonMSAAClip& analyticClip, const SkShader* clipShader); |
| 1260 |
|
| 1261 |
private: |
| 1262 |
const Transform* fLocalToDevice; |
| 1263 |
|
| 1264 |
// When 'style' isn't fill, the original geometry describes the pre-stroked shape, so 'fShape' |
| 1265 |
// is updated to include the bounds post-stroking. `fShape` may also include local AA outsets |
| 1266 |
// under certain circumstances: |
| 1267 |
// 1. If it's a hairline, the AA outset can be added in local space to preserve a tighter |
| 1268 |
// oriented bbox compared to device bounds outset by 1px. |
| 1269 |
// 2. If it's subpixel, the rendered geometry is often treated as a hairline with an adjusted |
| 1270 |
// coverage ramp. |
| 1271 |
// Notably, the local AA outset is not included in `styledShape` for other cases to maximize the |
| 1272 |
// cases where a draw is contained in a clip, or can be clipped geometrically. This assumes that |
| 1273 |
// rendering an AA'ed non-hairline/subpixel edge produces a 1px feathered edge that's not |
| 1274 |
// qualitatively different from the 1px feathered edge a clip would enforce. |
| 1275 |
Shape fShape; |
| 1276 |
SkEnumBitMask<EdgeAAQuad::Flags> fEdgeFlags; |
| 1277 |
|
| 1278 |
// Not valid until after applyStyle() is called, although applyScissor() can shrink the inner |
| 1279 |
// and outer bounds. |
| 1280 |
Rect fTransformedShapeBounds; |
| 1281 |
Rect fOuterBounds; |
| 1282 |
Rect fInnerBounds; |
| 1283 |
|
| 1284 |
Rect fScissor; |
| 1285 |
|
| 1286 |
// Whether or not the shape matches the original geometry to draw (with style) |
| 1287 |
bool fShapeMatchesGeometry; |
| 1288 |
// Whether or not the clip stack can modify this shape in place (and if it has already done so). |
| 1289 |
bool fShapeCompatibleWithIntersectShape; |
| 1290 |
bool fShapeWasModified; |
| 1291 |
}; |
| 1292 |
|
| 1293 |
bool ClipStack::DrawShape::applyStyle(const SkStrokeRec& style, const Rect& deviceBounds) { |
| 1294 |
// For overriding fLocalToDevice when the shape is only tracking device-space bounds |
| 1295 |
static const Transform kIdentity = Transform::Identity(); |
| 1296 |
|
| 1297 |
fTransformedShapeBounds = fShape.bounds(); // not scissor'ed, regular fill rule bounds |
| 1298 |
auto origSize = fTransformedShapeBounds.size(); |
| 1299 |
if (!SkIsFinite(origSize.x(), origSize.y())) { |
| 1300 |
// Discard all non-finite geometry as if it were clipped out |
| 1301 |
return false; |
| 1302 |
} |
| 1303 |
|
| 1304 |
// Discard fills and strokes that cannot produce any coverage: an empty fill, or a |
| 1305 |
// zero-length stroke that has butt caps. Otherwise the stroke style applies to a vertical |
| 1306 |
// or horizontal line (making it non-empty), or it's a zero-length path segment that |
| 1307 |
// must produce round or square caps (making it non-empty): |
| 1308 |
// https://www.w3.org/TR/SVG11/implnote.html#PathElementImplementationNotes |
| 1309 |
if (!fShape.inverted() && (fShape.isLine() || any(origSize == 0.f))) { |
| 1310 |
if (style.isFillStyle() || (style.getCap() == SkPaint::kButt_Cap && all(origSize == 0.f))) { |
| 1311 |
return false; |
| 1312 |
} |
| 1313 |
} |
| 1314 |
|
| 1315 |
// Anti-aliasing makes shapes larger than their original coordinates, but we only care about |
| 1316 |
// that for local clip checks in certain cases (see above). |
| 1317 |
// NOTE: After this if-else block, `transformedShapeBounds` will be in device space. |
| 1318 |
float localAAOutset = fLocalToDevice->localAARadius(fTransformedShapeBounds); |
| 1319 |
if (!SkIsFinite(localAAOutset)) SK_UNLIKELY { |
| 1320 |
// We cannot calculate an accurate local shape bounds, and transformedShapeBounds is meant |
| 1321 |
// to be unclipped. This is to maximize atlas reuse for mostly unclipped draws and to detect |
| 1322 |
// when a scissor state change is required. Setting transformedShapeBounds to deviceBounds |
| 1323 |
// is harmless in this case as these benefits are unlikely to apply for this transform. |
| 1324 |
fTransformedShapeBounds = deviceBounds; |
| 1325 |
fShape.setRect(deviceBounds); |
| 1326 |
fLocalToDevice = &kIdentity; |
| 1327 |
fShapeMatchesGeometry = false; |
| 1328 |
} else { |
| 1329 |
// SkStrokeRec::GetInflationRadius() returns a device-space inflation for hairlines. |
| 1330 |
float localOutset = 0.f; |
| 1331 |
if (!style.isFillStyle() && !style.isHairlineStyle()) { |
| 1332 |
// Rectangles, rounded rectangles, and lines do not produce miters so don't count the |
| 1333 |
// pessimistic limit against their draw bounds. |
| 1334 |
const float effectiveMiterLimit = fShape.isPath() ? style.getMiter() : 1.f; |
| 1335 |
// Rectangles and rounded rectangles don't have caps, so don't count that against their |
| 1336 |
// draw bounds (if we could efficiently know a path was a closed contour, it could |
| 1337 |
// be included here too). |
| 1338 |
const SkPaint::Cap effectiveCap = fShape.isRect() || fShape.isRRect() |
| 1339 |
? SkPaint::kButt_Cap : style.getCap(); |
| 1340 |
localOutset = SkStrokeRec::GetInflationRadius(style.getJoin(), |
| 1341 |
effectiveMiterLimit, |
| 1342 |
effectiveCap, |
| 1343 |
style.getWidth()); |
| 1344 |
} |
| 1345 |
|
| 1346 |
if (style.isHairlineStyle() || |
| 1347 |
(!style.isFillStyle() && style.getWidth() < localAAOutset) || |
| 1348 |
(style.isFillStyle() && !fShape.inverted() && any(origSize < localAAOutset))) { |
| 1349 |
// The geometry is a hairline or projects to a subpixel shape, so rendering will not |
| 1350 |
// follow the typical 1/2px outset anti-aliasing that is compatible with clipping. |
| 1351 |
// In this case, apply the local AA radius to the shape to have a conservative clip |
| 1352 |
// query while preserving the oriented bounding box. |
| 1353 |
localOutset += localAAOutset; |
| 1354 |
} |
| 1355 |
|
| 1356 |
if (localOutset > 0.f) { |
| 1357 |
// Propagate style and AA outset into styledShape so clip queries reflect style. |
| 1358 |
fTransformedShapeBounds.outset(localOutset); |
| 1359 |
|
| 1360 |
bool inverted = fShape.inverted(); |
| 1361 |
if (fShape.isRRect()) { |
| 1362 |
// Try to preserve the rounded corners, which can reduce the chance of clipping |
| 1363 |
// stroked rounded rects that are clipped to a round rect matching their outer edge. |
| 1364 |
fShape.rrect().outset(localOutset, localOutset, &fShape.rrect()); |
| 1365 |
} else |
| 1366 |
{ |
| 1367 |
fShape.setRect(fTransformedShapeBounds); // it's still local at this point |
| 1368 |
} |
| 1369 |
fShape.setInverted(inverted); // preserve original inversion state |
| 1370 |
fShapeMatchesGeometry = false; |
| 1371 |
} |
| 1372 |
|
| 1373 |
fTransformedShapeBounds = fLocalToDevice->mapRect(fTransformedShapeBounds); |
| 1374 |
} |
| 1375 |
|
| 1376 |
fOuterBounds = fTransformedShapeBounds; |
| 1377 |
fInnerBounds = Rect::InfiniteInverted(); |
| 1378 |
|
| 1379 |
if (this->shapeCanBeModified() && fLocalToDevice->type() <= Transform::Type::kRectStaysRect) { |
| 1380 |
if (fShape.isRect()) { |
| 1381 |
fInnerBounds = fOuterBounds; |
| 1382 |
} else if (fShape.isRRect()) { |
| 1383 |
SkRect rrectInnerBounds = SkRRectPriv::InnerBounds(fShape.rrect()); |
| 1384 |
if (!rrectInnerBounds.isEmpty()) { |
| 1385 |
fInnerBounds = fLocalToDevice->mapRect(rrectInnerBounds); |
| 1386 |
} |
| 1387 |
} |
| 1388 |
// Otherwise it's a flood fill, but should have empty bounds anyways |
| 1389 |
} |
| 1390 |
// Otherwise we either don't need the inner bounds, or the inner bounds can't be computed |
| 1391 |
// for a non-axis-aligned transform |
| 1392 |
|
| 1393 |
return true; // Something can be drawn based on style (might still be clipped out) |
| 1394 |
} |
| 1395 |
|
| 1396 |
void ClipStack::DrawShape::applyScissor(const Rect& scissor) { |
| 1397 |
// Apply the scissor to the outer bounds because it restricts rasterization and will allow |
| 1398 |
// the SaveRecord::testForDraw() case to detect no clip influence if only the scissor is |
| 1399 |
// needed. |
| 1400 |
SkASSERT(scissor == Rect(scissor.asSkIRect())); // `scissor` must be integer valued |
| 1401 |
fScissor.intersect(scissor); // For first call, fScissor is infinite so this is assignment |
| 1402 |
fOuterBounds.intersect(scissor); |
| 1403 |
fInnerBounds.intersect(scissor); |
| 1404 |
} |
| 1405 |
|
| 1406 |
Clip ClipStack::DrawShape::toClip(Geometry* geometry, |
| 1407 |
const NonMSAAClip& analyticClip, |
| 1408 |
const SkShader* clipShader) { |
| 1409 |
if (fShapeWasModified) { |
| 1410 |
// Sync back to the geometry that will be drawn |
| 1411 |
SkASSERT(this->shapeCanBeModified()); |
| 1412 |
if (geometry->isEdgeAAQuad() && fShape.isRect()) { |
| 1413 |
// Preserve the EdgeAAQuad geometry type and sync updated edge flags |
| 1414 |
SkASSERT(geometry->edgeAAQuad().isRect()); |
| 1415 |
geometry->setEdgeAAQuad(EdgeAAQuad(fShape.rect(), fEdgeFlags)); |
| 1416 |
} else { |
| 1417 |
SkASSERT(fEdgeFlags == EdgeAAQuad::Flags::kAll); |
| 1418 |
geometry->setShape(fShape); |
| 1419 |
} |
| 1420 |
// Reconstruct new transformedShapeBounds and outer bounds |
| 1421 |
fTransformedShapeBounds = fLocalToDevice->mapRect(fShape.bounds()); |
| 1422 |
fOuterBounds = fTransformedShapeBounds.makeIntersect(fScissor); |
| 1423 |
} |
| 1424 |
|
| 1425 |
Rect drawBounds = fShape.inverted() ? fScissor : fOuterBounds; |
| 1426 |
// If the draw isn't clipped out (empty drawBounds), it should be in the scissor rect |
| 1427 |
SkASSERT(drawBounds.isEmptyNegativeOrNaN() || fScissor.contains(drawBounds)); |
| 1428 |
// If the scissor is empty, the draw bounds must also be empty |
| 1429 |
SkASSERT(!fScissor.isEmptyNegativeOrNaN() || drawBounds.isEmptyNegativeOrNaN()); |
| 1430 |
// fScissor.asSkIRect() must be equivalent |
| 1431 |
SkASSERT(fScissor == Rect(fScissor.asSkIRect())); |
| 1432 |
return Clip(drawBounds, fTransformedShapeBounds, |
| 1433 |
fScissor.asSkIRect(), analyticClip, clipShader); |
| 1434 |
} |
| 1435 |
|
| 1436 |
void ClipStack::DrawShape::resetToFloodFill() { |
| 1437 |
if (this->shapeCanBeModified() && !fShape.isFloodFill()) { |
| 1438 |
fShape.reset(); |
| 1439 |
fShape.setInverted(true); |
| 1440 |
fEdgeFlags = EdgeAAQuad::Flags::kAll; |
| 1441 |
fOuterBounds = fInnerBounds = Rect::InfiniteInverted(); |
| 1442 |
fShapeWasModified = true; |
| 1443 |
} |
| 1444 |
} |
| 1445 |
|
| 1446 |
bool ClipStack::DrawShape::intersectClipElement(const RawElement& clip) { |
| 1447 |
SkASSERT(clip.op() == SkClipOp::kIntersect); |
| 1448 |
if (this->shapeCanBeModified() && |
| 1449 |
intersect_shape(clip.localToDevice(), clip.shape(), |
| 1450 |
*fLocalToDevice, &fShape, &fEdgeFlags)) { |
| 1451 |
SkASSERT(!fShape.inverted()); |
| 1452 |
if (fOuterBounds.isEmptyNegativeOrNaN()) { |
| 1453 |
// Changing from a flood fill to the clip's shape |
| 1454 |
fOuterBounds = clip.outerBounds(); |
| 1455 |
fInnerBounds = clip.innerBounds(); |
| 1456 |
} else { |
| 1457 |
// Restricting the shape's geometry by the clip |
| 1458 |
fOuterBounds.intersect(clip.outerBounds()); |
| 1459 |
fInnerBounds.intersect(clip.innerBounds()); |
| 1460 |
SkASSERT(!fOuterBounds.isEmptyNegativeOrNaN()); // Should have been caught earlier |
| 1461 |
} |
| 1462 |
|
| 1463 |
fShapeWasModified = true; |
| 1464 |
return true; |
| 1465 |
} |
| 1466 |
|
| 1467 |
return false; |
| 1468 |
} |
| 1469 |
|
| 1470 |
/////////////////////////////////////////////////////////////////////////////// |
| 1471 |
// ClipStack |
| 1472 |
|
| 1473 |
// NOTE: Based on draw calls in all GMs, SKPs, and SVGs as of 08/20, 98% use a clip stack with |
| 1474 |
// one Element and up to two SaveRecords, thus the inline size for RawElement::Stack and |
| 1475 |
// SaveRecord::Stack (this conveniently keeps the size of ClipStack manageable). The max |
| 1476 |
// encountered element stack depth was 5 and the max save depth was 6. Using an increment of 8 for |
| 1477 |
// these stacks means that clip management will incur a single allocation for the remaining 2% |
| 1478 |
// of the draws, with extra head room for more complex clips encountered in the wild. |
| 1479 |
static constexpr int kElementStackIncrement = 8; |
| 1480 |
static constexpr int kSaveStackIncrement = 8; |
| 1481 |
|
| 1482 |
ClipStack::ClipStack(Device* owningDevice) |
| 1483 |
: fElements(kElementStackIncrement) |
| 1484 |
, fSaves(kSaveStackIncrement) |
| 1485 |
, fDevice(owningDevice) { |
| 1486 |
// Start with a save record that is wide open |
| 1487 |
fSaves.emplace_back(this->deviceBounds()); |
| 1488 |
} |
| 1489 |
|
| 1490 |
ClipStack::~ClipStack() = default; |
| 1491 |
|
| 1492 |
void ClipStack::save() { |
| 1493 |
SkASSERT(!fSaves.empty()); |
| 1494 |
fSaves.back().pushSave(); |
| 1495 |
} |
| 1496 |
|
| 1497 |
void ClipStack::restore() { |
| 1498 |
SkASSERT(!fSaves.empty()); |
| 1499 |
SaveRecord& current = fSaves.back(); |
| 1500 |
if (current.popSave()) { |
| 1501 |
// This was just a deferred save being undone, so the record doesn't need to be removed yet |
| 1502 |
return; |
| 1503 |
} |
| 1504 |
|
| 1505 |
// When we remove a save record, we delete all elements >= its starting index and any masks |
| 1506 |
// that were rasterized for it. |
| 1507 |
current.removeElements(&fElements, fDevice); |
| 1508 |
|
| 1509 |
fSaves.pop_back(); |
| 1510 |
// Restore any remaining elements that were only invalidated by the now-removed save record. |
| 1511 |
fSaves.back().restoreElements(&fElements); |
| 1512 |
} |
| 1513 |
|
| 1514 |
Rect ClipStack::deviceBounds() const { |
| 1515 |
return Rect::WH(fDevice->width(), fDevice->height()); |
| 1516 |
} |
| 1517 |
|
| 1518 |
Rect ClipStack::conservativeBounds() const { |
| 1519 |
const SaveRecord& current = this->currentSaveRecord(); |
| 1520 |
if (current.state() == ClipState::kEmpty) { |
| 1521 |
return Rect::InfiniteInverted(); |
| 1522 |
} else if (current.state() == ClipState::kWideOpen) { |
| 1523 |
return this->deviceBounds(); |
| 1524 |
} else { |
| 1525 |
if (current.op() == SkClipOp::kDifference) { |
| 1526 |
// The outer/inner bounds represent what's cut out, so full bounds remains the device |
| 1527 |
// bounds, minus any fully clipped content that spans the device edge. |
| 1528 |
return subtract(this->deviceBounds(), current.innerBounds(), /* exact */ true); |
| 1529 |
} else { |
| 1530 |
SkASSERT(this->deviceBounds().contains(current.outerBounds())); |
| 1531 |
return current.outerBounds(); |
| 1532 |
} |
| 1533 |
} |
| 1534 |
} |
| 1535 |
|
| 1536 |
ClipStack::SaveRecord& ClipStack::writableSaveRecord(bool* wasDeferred) { |
| 1537 |
SaveRecord& current = fSaves.back(); |
| 1538 |
if (current.canBeUpdated()) { |
| 1539 |
// Current record is still open, so it can be modified directly |
| 1540 |
*wasDeferred = false; |
| 1541 |
return current; |
| 1542 |
} else { |
| 1543 |
// Must undefer the save to get a new record. |
| 1544 |
SkAssertResult(current.popSave()); |
| 1545 |
*wasDeferred = true; |
| 1546 |
return fSaves.emplace_back(current, fElements.count()); |
| 1547 |
} |
| 1548 |
} |
| 1549 |
|
| 1550 |
void ClipStack::clipShader(sk_sp<SkShader> shader) { |
| 1551 |
// Shaders can't bring additional coverage |
| 1552 |
if (this->currentSaveRecord().state() == ClipState::kEmpty) { |
| 1553 |
return; |
| 1554 |
} |
| 1555 |
|
| 1556 |
bool wasDeferred; |
| 1557 |
this->writableSaveRecord(&wasDeferred).addShader(std::move(shader)); |
| 1558 |
// Geometry elements are not invalidated by updating the clip shader |
| 1559 |
// TODO(b/238763003): Integrating clipShader into graphite needs more thought, particularly how |
| 1560 |
// to handle the shader explosion and where to put the effects in the GraphicsPipelineDesc. |
| 1561 |
// One idea is to use sample locations and draw the clipShader into the depth buffer. |
| 1562 |
// Another is resolve the clip shader into an alpha mask image that is sampled by the draw. |
| 1563 |
} |
| 1564 |
|
| 1565 |
void ClipStack::clipShape(const Transform& localToDevice, |
| 1566 |
const Shape& shape, |
| 1567 |
SkClipOp op, |
| 1568 |
PixelSnapping snapping) { |
| 1569 |
if (this->currentSaveRecord().state() == ClipState::kEmpty) { |
| 1570 |
return; |
| 1571 |
} |
| 1572 |
|
| 1573 |
// This will apply the transform if it's shape-type preserving, and clip the element's bounds |
| 1574 |
// to the device bounds (NOT the conservative clip bounds, since those are based on the net |
| 1575 |
// effect of all elements while device bounds clipping happens implicitly. During addElement, |
| 1576 |
// we may still be able to invalidate some older elements). |
| 1577 |
// NOTE: Does not try to simplify the shape type by inspecting the SkPath. |
| 1578 |
RawElement element{this->deviceBounds(), localToDevice, shape, op, snapping}; |
| 1579 |
|
| 1580 |
// An empty op means do nothing (for difference), or close the save record, so we try and detect |
| 1581 |
// that early before doing additional unnecessary save record allocation. |
| 1582 |
if (element.shape().isEmpty()) { |
| 1583 |
if (element.op() == SkClipOp::kDifference) { |
| 1584 |
// If the shape is empty and we're subtracting, this has no effect on the clip |
| 1585 |
return; |
| 1586 |
} |
| 1587 |
// else we will make the clip empty, but we need a new save record to record that change |
| 1588 |
// in the clip state; fall through to below and updateForElement() will handle it. |
| 1589 |
} |
| 1590 |
|
| 1591 |
bool wasDeferred; |
| 1592 |
SaveRecord& save = this->writableSaveRecord(&wasDeferred); |
| 1593 |
SkDEBUGCODE(int elementCount = fElements.count();) |
| 1594 |
if (!save.addElement(std::move(element), &fElements, fDevice)) { |
| 1595 |
if (wasDeferred) { |
| 1596 |
// We made a new save record, but ended up not adding an element to the stack. |
| 1597 |
// So instead of keeping an empty save record around, pop it off and restore the counter |
| 1598 |
SkASSERT(elementCount == fElements.count()); |
| 1599 |
fSaves.pop_back(); |
| 1600 |
fSaves.back().pushSave(); |
| 1601 |
} |
| 1602 |
} |
| 1603 |
} |
| 1604 |
|
| 1605 |
// Decide whether we can use this shape to do analytic clipping. Only rects and certain |
| 1606 |
// rrects are supported. We assume these have been pre-transformed by the RawElement |
| 1607 |
// constructor, so only identity transforms are allowed. |
| 1608 |
namespace { |
| 1609 |
|
| 1610 |
AnalyticClip can_apply_analytic_clip(const Shape& shape, const Transform& localToDevice) { |
| 1611 |
if (localToDevice.type() != Transform::Type::kIdentity) { |
| 1612 |
return {}; |
| 1613 |
} |
| 1614 |
|
| 1615 |
// The circular rrect clip only handles rrect radii >= kRadiusMin, circular radii less than |
| 1616 |
// this are coerced to be rectangular. |
| 1617 |
static constexpr float kRadiusMin = SK_ScalarHalf; |
| 1618 |
|
| 1619 |
// Can handle Rect directly. |
| 1620 |
if (shape.isRect()) { |
| 1621 |
return {shape.rect(), kRadiusMin, AnalyticClip::kNone_EdgeFlag, shape.inverted()}; |
| 1622 |
} |
| 1623 |
|
| 1624 |
// Otherwise we only handle certain kinds of RRects, specifically only approximately simple |
| 1625 |
// circular rrects (e.g. all 4 corners can be described by a single radius value). |
| 1626 |
if (!shape.isRRect()) { |
| 1627 |
return {}; |
| 1628 |
} |
| 1629 |
|
| 1630 |
const SkRRect& rrect = shape.rrect(); |
| 1631 |
if (rrect.isOval() || rrect.isSimple()) { |
| 1632 |
SkVector radii = SkRRectPriv::GetSimpleRadii(rrect); |
| 1633 |
if (radii.fX < kRadiusMin || radii.fY < kRadiusMin) { |
| 1634 |
// In this case the corners are extremely close to rectangular and we collapse the |
| 1635 |
// clip to a rectangular clip. |
| 1636 |
return {rrect.rect(), kRadiusMin, AnalyticClip::kNone_EdgeFlag, shape.inverted()}; |
| 1637 |
} |
| 1638 |
if (SkRRectPriv::IsRelativelyCircular(radii.fX, radii.fY, Shape::kDefaultPixelTolerance)) { |
| 1639 |
return {rrect.rect(), radii.fX, AnalyticClip::kAll_EdgeFlag, shape.inverted()}; |
| 1640 |
} else { |
| 1641 |
return {}; |
| 1642 |
} |
| 1643 |
} |
| 1644 |
|
| 1645 |
// If rrect is not an oval or simple, it's either empty, rect, 9-patch, or complex. However, |
| 1646 |
// empty should have been handled by the clip stack, and rect ought to have been simplified |
| 1647 |
// into an explicit Rect shape (already handled above). That leaves 9-patch and complex, |
| 1648 |
// so we check for the "tab" cases - two adjacent circular corners and two square corners. |
| 1649 |
// It just so happens that if a rect RRect slipped through the cracks, we detect it here too. |
| 1650 |
constexpr uint32_t kCornerFlags[4] = { |
| 1651 |
AnalyticClip::kTop_EdgeFlag | AnalyticClip::kLeft_EdgeFlag, |
| 1652 |
AnalyticClip::kTop_EdgeFlag | AnalyticClip::kRight_EdgeFlag, |
| 1653 |
AnalyticClip::kBottom_EdgeFlag | AnalyticClip::kRight_EdgeFlag, |
| 1654 |
AnalyticClip::kBottom_EdgeFlag | AnalyticClip::kLeft_EdgeFlag, |
| 1655 |
}; |
| 1656 |
SkScalar circularRadius = 0; |
| 1657 |
uint32_t edgeFlags = 0; |
| 1658 |
int squareCount = 0; |
| 1659 |
for (int corner = 0; corner < 4; ++corner) { |
| 1660 |
SkVector radii = rrect.radii((SkRRect::Corner)corner); |
| 1661 |
// Can only handle circular radii. |
| 1662 |
// Also applies to corners with both zero and non-zero radii. |
| 1663 |
if (!SkRRectPriv::IsRelativelyCircular(radii.fX, radii.fY, Shape::kDefaultPixelTolerance)) { |
| 1664 |
return {}; |
| 1665 |
} |
| 1666 |
if (radii.fX < kRadiusMin || radii.fY < kRadiusMin) { |
| 1667 |
// The corner is square, so no need to flag as circular. |
| 1668 |
squareCount++; |
| 1669 |
continue; |
| 1670 |
} |
| 1671 |
// First circular corner seen |
| 1672 |
if (!edgeFlags) { |
| 1673 |
circularRadius = radii.fX; |
| 1674 |
} else if (!SkRRectPriv::IsRelativelyCircular(radii.fX, |
| 1675 |
circularRadius, |
| 1676 |
Shape::kDefaultPixelTolerance)) { |
| 1677 |
// Radius doesn't match previously seen circular radius |
| 1678 |
return {}; |
| 1679 |
} |
| 1680 |
edgeFlags |= kCornerFlags[corner]; |
| 1681 |
} |
| 1682 |
|
| 1683 |
if (edgeFlags == AnalyticClip::kNone_EdgeFlag) { |
| 1684 |
// It's a rect (or coerced to a rect) |
| 1685 |
return {rrect.rect(), kRadiusMin, edgeFlags, shape.inverted()}; |
| 1686 |
} else if (edgeFlags == AnalyticClip::kAll_EdgeFlag && squareCount != 0) { |
| 1687 |
// If any rounded corner pairs are non-adjacent or if there are three rounded corners all |
| 1688 |
// edge flags will be set, which is not valid. |
| 1689 |
return {}; |
| 1690 |
} else { |
| 1691 |
// At least one corner is rounded, or two adjacent corners are rounded, or all corners |
| 1692 |
// are approximately the same (but not classified as simple due to inexactness). |
| 1693 |
return {rrect.rect(), circularRadius, edgeFlags, shape.inverted()}; |
| 1694 |
} |
| 1695 |
} |
| 1696 |
|
| 1697 |
} // anonymous namespace |
| 1698 |
|
| 1699 |
Clip ClipStack::visitClipStackForDraw(const Transform& localToDevice, |
| 1700 |
Geometry* geometry, |
| 1701 |
const SkStrokeRec& style, |
| 1702 |
ClipStack::ElementList* outEffectiveElements) const { |
| 1703 |
static const Clip kClippedOut = { |
| 1704 |
Rect::InfiniteInverted(), Rect::InfiniteInverted(), SkIRect::MakeEmpty(), |
| 1705 |
/* nonMSAAClip= */ {}, /* shader= */ nullptr}; |
| 1706 |
|
| 1707 |
const SaveRecord& cs = this->currentSaveRecord(); |
| 1708 |
if (cs.state() == ClipState::kEmpty) { |
| 1709 |
// We know the draw is clipped out so don't bother computing the base draw bounds. |
| 1710 |
return kClippedOut; |
| 1711 |
} |
| 1712 |
// Compute draw bounds, clipped only to our device bounds since we need to return that even if |
| 1713 |
// the clip stack is known to be wide-open. |
| 1714 |
const Rect deviceBounds = this->deviceBounds(); |
| 1715 |
|
| 1716 |
DrawShape draw{localToDevice, *geometry}; |
| 1717 |
if (!draw.applyStyle(style, deviceBounds)) { |
| 1718 |
return kClippedOut; |
| 1719 |
} |
| 1720 |
|
| 1721 |
// For intersect clips, the scissor rectangle is snapped outer bounds (to loosely restrict |
| 1722 |
// rasterization if absolutely necessary). Cases where the draw is fully inside the scissor are |
| 1723 |
// automatically handled during GPU command generation. |
| 1724 |
// |
| 1725 |
// For difference clips, a tight scissor could be `subtract(drawBounds, cs.innerBounds())` |
| 1726 |
// but this is only useful when the clip spans across an axis of the draw and can otherwise |
| 1727 |
// lead to scissor state thrashing since it's connected to the draw's bounds as well. So just |
| 1728 |
// use the device bounds for simplicity. |
| 1729 |
draw.applyScissor(cs.op() == SkClipOp::kIntersect ? snap_scissor(cs.outerBounds(), deviceBounds) |
| 1730 |
: deviceBounds); |
| 1731 |
|
| 1732 |
switch (cs.testForDraw(draw)) { |
| 1733 |
case DrawInfluence::kClipsOutDraw: |
| 1734 |
// The draw is offscreen or clipped out, so there is no need to visit the clip elements. |
| 1735 |
return kClippedOut; |
| 1736 |
|
| 1737 |
case DrawInfluence::kNone: |
| 1738 |
// The draw is unaffected by the clip stack (except possibly `scissor`), and there's no |
| 1739 |
// need to visit each clip element. |
| 1740 |
return draw.toClip(geometry, {}, cs.shader()); |
| 1741 |
|
| 1742 |
case DrawInfluence::kReplacesDraw: |
| 1743 |
// The draw covers the clip entirely. Replace the shape with a flood fill, which can |
| 1744 |
// intersect with shapes efficiently. |
| 1745 |
draw.resetToFloodFill(); |
| 1746 |
[[fallthrough]]; |
| 1747 |
|
| 1748 |
case DrawInfluence::kComplexInteraction: |
| 1749 |
// Check each element's influence on the draw below |
| 1750 |
break; |
| 1751 |
} |
| 1752 |
|
| 1753 |
SkASSERT(outEffectiveElements); |
| 1754 |
SkASSERT(outEffectiveElements->empty()); |
| 1755 |
int i = fElements.count(); |
| 1756 |
NonMSAAClip nonMSAAClip; |
| 1757 |
for (const RawElement& e : fElements.ritems()) { |
| 1758 |
--i; |
| 1759 |
if (i < cs.oldestElementIndex()) { |
| 1760 |
// All earlier elements have been invalidated by elements already processed so the draw |
| 1761 |
// can't be affected by them and cannot contribute to their usage bounds. |
| 1762 |
break; |
| 1763 |
} |
| 1764 |
|
| 1765 |
switch (e.testForDraw(draw)) { |
| 1766 |
case DrawInfluence::kClipsOutDraw: |
| 1767 |
// Per-element check was able to completely reject the draw. |
| 1768 |
outEffectiveElements->clear(); |
| 1769 |
return kClippedOut; |
| 1770 |
|
| 1771 |
case DrawInfluence::kNone: |
| 1772 |
// This element does not interact, so continue to the next |
| 1773 |
continue; |
| 1774 |
|
| 1775 |
case DrawInfluence::kReplacesDraw: |
| 1776 |
// This element is covered entirely by the draw, so the draw's geometry can be |
| 1777 |
// replaced assuming the coordinate spaces are compatible. To facilitate this, we |
| 1778 |
// switch the drawn geometry to a flood fill and then fall through to intersection. |
| 1779 |
// Even if the coordinate spaces aren't in alignment, this eliminates the draw's |
| 1780 |
// source of analytic coverage. |
| 1781 |
draw.resetToFloodFill(); |
| 1782 |
|
| 1783 |
[[fallthrough]]; |
| 1784 |
|
| 1785 |
case DrawInfluence::kComplexInteraction: |
| 1786 |
// First try to handle the clip geometrically |
| 1787 |
if (e.op() == SkClipOp::kIntersect && draw.intersectClipElement(e)) { |
| 1788 |
continue; |
| 1789 |
} |
| 1790 |
// Second try to tighten the scissor, which is lighter weight than adding an |
| 1791 |
// analytic clip pipeline variation or triggering MSAA. |
| 1792 |
if (e.clipType() == ClipState::kDeviceRect) { |
| 1793 |
Rect scissor = e.shape().rect().makeRound(); |
| 1794 |
if (e.shape().rect().nearlyEquals(scissor, Shape::kDefaultPixelTolerance)) { |
| 1795 |
// Pass in `scissor` since these need to be integral values while |
| 1796 |
// nearlyEquals allows the original rect coordinates to be slightly |
| 1797 |
// different (causing problems later with asSkIRect()). |
| 1798 |
draw.applyScissor(scissor); |
| 1799 |
continue; |
| 1800 |
} |
| 1801 |
} |
| 1802 |
// // Third try to handle the clip analytically in the shader |
| 1803 |
if (nonMSAAClip.fAnalyticClip.isEmpty()) { |
| 1804 |
nonMSAAClip.fAnalyticClip = can_apply_analytic_clip(e.shape(), |
| 1805 |
e.localToDevice()); |
| 1806 |
if (!nonMSAAClip.fAnalyticClip.isEmpty()) { |
| 1807 |
continue; |
| 1808 |
} |
| 1809 |
} |
| 1810 |
// Fourth, remember the element for later, either to be a depth-only draw or to be |
| 1811 |
// flattened into a clip mask. |
| 1812 |
// Otherwise, accumulate it for later. Depending on how many elements are collected |
| 1813 |
// we may use the scissor, analytic clip, or MSAA/atlas. |
| 1814 |
outEffectiveElements->push_back(&e); |
| 1815 |
break; |
| 1816 |
} |
| 1817 |
} |
| 1818 |
|
| 1819 |
// If there is no MSAA supported, rasterize any remaining elements by flattening them |
| 1820 |
// into a single mask and storing in an atlas. Otherwise these will be handled by |
| 1821 |
// Device::drawClip(). |
| 1822 |
ClipAtlasManager* clipAtlas = |
| 1823 |
fDevice->recorder()->priv().atlasProvider()->getClipAtlasManager(); |
| 1824 |
if (clipAtlas && !outEffectiveElements->empty()) { |
| 1825 |
AtlasClip* atlasClip = &nonMSAAClip.fAtlasClip; |
| 1826 |
|
| 1827 |
SkIRect iMaskBounds = cs.outerBounds().makeRoundOut().asSkIRect(); |
| 1828 |
sk_sp<TextureProxy> proxy = clipAtlas->findOrCreateEntry(cs.genID(), |
| 1829 |
outEffectiveElements, |
| 1830 |
iMaskBounds, |
| 1831 |
&atlasClip->fOutPos); |
| 1832 |
if (proxy) { |
| 1833 |
// Add to Clip |
| 1834 |
atlasClip->fMaskBounds = iMaskBounds; |
| 1835 |
atlasClip->fAtlasTexture = std::move(proxy); |
| 1836 |
|
| 1837 |
// Elements are represented in the clip atlas, discard. |
| 1838 |
outEffectiveElements->clear(); |
| 1839 |
} |
| 1840 |
} |
| 1841 |
|
| 1842 |
return draw.toClip(geometry, nonMSAAClip, cs.shader()); |
| 1843 |
} |
| 1844 |
|
| 1845 |
CompressedPaintersOrder ClipStack::updateClipStateForDraw(const Clip& clip, |
| 1846 |
const ElementList& effectiveElements, |
| 1847 |
const BoundsManager* boundsManager, |
| 1848 |
PaintersDepth z) { |
| 1849 |
if (clip.isClippedOut()) { |
| 1850 |
return DrawOrder::kNoIntersection; |
| 1851 |
} |
| 1852 |
|
| 1853 |
SkDEBUGCODE(const SaveRecord& cs = this->currentSaveRecord();) |
| 1854 |
SkASSERT(cs.state() != ClipState::kEmpty); |
| 1855 |
|
| 1856 |
Rect deviceBounds = this->deviceBounds(); |
| 1857 |
CompressedPaintersOrder maxClipOrder = DrawOrder::kNoIntersection; |
| 1858 |
for (int i = 0; i < effectiveElements.size(); ++i) { |
| 1859 |
// ClipStack owns the elements in the `clipState` so it's OK to downcast and cast away |
| 1860 |
// const. |
| 1861 |
// TODO: Enforce the ownership? In debug builds we could invalidate a `ClipStateForDraw` if |
| 1862 |
// its element pointers become dangling and assert validity here. |
| 1863 |
const RawElement* e = static_cast<const RawElement*>(effectiveElements[i]); |
| 1864 |
CompressedPaintersOrder order = const_cast<RawElement*>(e)->updateForDraw( |
| 1865 |
boundsManager, deviceBounds, clip.drawBounds(), z); |
| 1866 |
maxClipOrder = std::max(order, maxClipOrder); |
| 1867 |
} |
| 1868 |
|
| 1869 |
return maxClipOrder; |
| 1870 |
} |
| 1871 |
|
| 1872 |
void ClipStack::recordDeferredClipDraws() { |
| 1873 |
for (auto& e : fElements.items()) { |
| 1874 |
// When a Device requires all clip elements to be recorded, we have to iterate all elements, |
| 1875 |
// and will draw clip shapes for elements that are still marked as invalid from the clip |
| 1876 |
// stack, including those that are older than the current save record's oldest valid index, |
| 1877 |
// because they could have accumulated draw usage prior to being invalidated, but weren't |
| 1878 |
// flushed when they were invalidated because of an intervening save. |
| 1879 |
e.drawClip(fDevice); |
| 1880 |
} |
| 1881 |
} |
| 1882 |
|
| 1883 |
} // namespace skgpu::graphite |