Flutter Engine
The Flutter Engine
SkDraw_vertices.cpp
Go to the documentation of this file.
1/*
2 * Copyright 2017 Google Inc.
3 *
4 * Use of this source code is governed by a BSD-style license that can be
5 * found in the LICENSE file.
6 */
7
20#include "include/core/SkRect.h"
34#include "src/core/SkDraw.h"
36#include "src/core/SkScan.h"
43
44#include <cstddef>
45#include <cstdint>
46#include <optional>
47#include <utility>
48
49class SkBlitter;
50
51[[nodiscard]] static bool texture_to_matrix(const VertState& state, const SkPoint verts[],
52 const SkPoint texs[], SkMatrix* matrix) {
53 SkPoint src[3], dst[3];
54
55 src[0] = verts[state.f0];
56 src[1] = verts[state.f1];
57 src[2] = verts[state.f2];
58 dst[0] = texs[state.f0];
59 dst[1] = texs[state.f1];
60 dst[2] = texs[state.f2];
61 return matrix->setPolyToPoly(src, dst, 3);
62}
63
64// Convert the SkColors into float colors. The conversion depends on some conditions:
65// - If the pixmap has a dst colorspace, we have to be "color-correct".
66// Do we map into dst-colorspace before or after we interpolate?
67// - We have to decide when to apply per-color alpha (before or after we interpolate)
68//
69// For now, we will take a simple approach, but recognize this is just a start:
70// - convert colors into dst colorspace before interpolation (matches gradients)
71// - apply per-color alpha before interpolation (matches old version of vertices)
72//
74 int count,
75 SkColorSpace* deviceCS,
76 SkArenaAlloc* alloc,
77 bool skipColorXform) {
79
80 // Passing `nullptr` for the destination CS effectively disables color conversion.
81 auto dstCS = skipColorXform ? nullptr : sk_ref_sp(deviceCS);
84 SkImageInfo dstInfo =
86 SkAssertResult(SkConvertPixels(dstInfo, dst, 0, srcInfo, src, 0));
87 return dst;
88}
89
90static bool compute_is_opaque(const SkColor colors[], int count) {
91 uint32_t c = ~0;
92 for (int i = 0; i < count; ++i) {
93 c &= colors[i];
94 }
95 return SkColorGetA(c) == 0xFF;
96}
97
98static void fill_triangle_2(const VertState& state, SkBlitter* blitter, const SkRasterClip& rc,
99 const SkPoint dev2[]) {
100 SkPoint tmp[] = {
101 dev2[state.f0], dev2[state.f1], dev2[state.f2]
102 };
103 SkScan::FillTriangle(tmp, rc, blitter);
104}
105
106static constexpr int kMaxClippedTrianglePointCount = 4;
107static void fill_triangle_3(const VertState& state, SkBlitter* blitter, const SkRasterClip& rc,
108 const SkPoint3 dev3[]) {
109 // Compute the crossing point (across zero) for the two values, expressed as a
110 // normalized 0...1 value. If curr is 0, returns 0. If next is 0, returns 1.
111 auto computeT = [](float curr, float next) {
112 // Check that 0 is between next and curr.
113 SkASSERT((next <= 0 && 0 < curr) || (curr <= 0 && 0 < next));
114 float t = curr / (curr - next);
115 SkASSERT(0 <= t && t <= 1);
116 return t;
117 };
118
119 auto lerp = [](SkPoint3 curr, SkPoint3 next, float t) {
120 return curr + t * (next - curr);
121 };
122
123 constexpr float tol = 0.05f;
124 // tol is the nudge away from zero, to keep the numerics nice.
125 // Think of it as our near-clipping-plane (or w-plane).
126 auto clip = [&](SkPoint3 curr, SkPoint3 next) {
127 // Return the point between curr and next where the fZ value crosses tol.
128 // To be (really) perspective correct, we should be computing based on 1/Z, not Z.
129 // For now, this is close enough (and faster).
130 return lerp(curr, next, computeT(curr.fZ - tol, next.fZ - tol));
131 };
132
133 // Clip a triangle (based on its homogeneous W values), and return the projected polygon.
134 // Since we only clip against one "edge"/plane, the max number of points in the clipped
135 // polygon is 4.
136 auto clipTriangle = [&](SkPoint dst[], const int idx[3], const SkPoint3 pts[]) -> int {
138 SkPoint3* outP = outPoints;
139
140 for (int i = 0; i < 3; ++i) {
141 int curr = idx[i];
142 int next = idx[(i + 1) % 3];
143 if (pts[curr].fZ > tol) {
144 *outP++ = pts[curr];
145 if (pts[next].fZ <= tol) { // curr is IN, next is OUT
146 *outP++ = clip(pts[curr], pts[next]);
147 }
148 } else {
149 if (pts[next].fZ > tol) { // curr is OUT, next is IN
150 *outP++ = clip(pts[curr], pts[next]);
151 }
152 }
153 }
154
155 const int count = SkTo<int>(outP - outPoints);
156 SkASSERT(count == 0 || count == 3 || count == 4);
157 for (int i = 0; i < count; ++i) {
158 float scale = sk_ieee_float_divide(1.0f, outPoints[i].fZ);
159 dst[i].set(outPoints[i].fX * scale, outPoints[i].fY * scale);
160 }
161 return count;
162 };
163
165 int idx[] = { state.f0, state.f1, state.f2 };
166 if (int n = clipTriangle(tmp, idx, dev3)) {
167 // TODO: SkScan::FillConvexPoly(tmp, n, ...);
168 SkASSERT(n == 3 || n == 4);
169 SkScan::FillTriangle(tmp, rc, blitter);
170 if (n == 4) {
171 tmp[1] = tmp[2];
172 tmp[2] = tmp[3];
173 SkScan::FillTriangle(tmp, rc, blitter);
174 }
175 }
176}
177
178static void fill_triangle(const VertState& state, SkBlitter* blitter, const SkRasterClip& rc,
179 const SkPoint dev2[], const SkPoint3 dev3[]) {
180 if (dev3) {
181 fill_triangle_3(state, blitter, rc, dev3);
182 } else {
183 fill_triangle_2(state, blitter, rc, dev2);
184 }
185}
186
187void SkDraw::drawFixedVertices(const SkVertices* vertices,
188 sk_sp<SkBlender> blender,
189 const SkPaint& paint,
190 const SkMatrix& ctmInverse,
191 const SkPoint* dev2,
192 const SkPoint3* dev3,
193 SkArenaAlloc* outerAlloc,
194 bool skipColorXform) const {
195 SkVerticesPriv info(vertices->priv());
196
197 const int vertexCount = info.vertexCount();
198 const int indexCount = info.indexCount();
199 const SkPoint* positions = info.positions();
200 const SkPoint* texCoords = info.texCoords();
201 const uint16_t* indices = info.indices();
202 const SkColor* colors = info.colors();
203
204 SkShader* paintShader = paint.getShader();
205
206 if (paintShader) {
207 if (!texCoords) {
208 texCoords = positions;
209 }
210 } else {
211 texCoords = nullptr;
212 }
213
214 bool blenderIsDst = false;
215 // We can simplify things for certain blend modes. This is for speed, and SkShader_Blend
216 // itself insists we don't pass kSrc or kDst to it.
217 if (std::optional<SkBlendMode> bm = as_BB(blender)->asBlendMode(); bm.has_value() && colors) {
218 switch (*bm) {
220 colors = nullptr;
221 break;
223 blenderIsDst = true;
224 texCoords = nullptr;
225 paintShader = nullptr;
226 break;
227 default: break;
228 }
229 }
230
231 // There is a paintShader iff there is texCoords.
232 SkASSERT((texCoords != nullptr) == (paintShader != nullptr));
233
234 // Explicit texture coords can't contain perspective - only the CTM can.
235 const bool usePerspective = fCTM->hasPerspective();
236
237 SkTriColorShader* triColorShader = nullptr;
238 SkPMColor4f* dstColors = nullptr;
239 if (colors) {
240 dstColors =
241 convert_colors(colors, vertexCount, fDst.colorSpace(), outerAlloc, skipColorXform);
242 triColorShader = outerAlloc->make<SkTriColorShader>(compute_is_opaque(colors, vertexCount),
243 usePerspective);
244 }
245
246 // Combines per-vertex colors with 'shader' using 'blender'.
247 auto applyShaderColorBlend = [&](SkShader* shader) -> sk_sp<SkShader> {
248 if (!colors) {
249 return sk_ref_sp(shader);
250 }
251 if (blenderIsDst) {
252 return sk_ref_sp(triColorShader);
253 }
254 sk_sp<SkShader> shaderWithWhichToBlend;
255 if (!shader) {
256 // When there is no shader then the blender applies to the vertex colors and opaque
257 // paint color.
258 shaderWithWhichToBlend = SkShaders::Color(paint.getColor4f().makeOpaque(), nullptr);
259 } else {
260 shaderWithWhichToBlend = sk_ref_sp(shader);
261 }
262 return SkShaders::Blend(blender,
263 sk_ref_sp(triColorShader),
264 std::move(shaderWithWhichToBlend));
265 };
266
267 // If there are separate texture coords then we need to insert a transform shader to update
268 // a matrix derived from each triangle's coords. In that case we will fold the CTM into
269 // each update and use an identity matrix.
270 SkTransformShader* transformShader = nullptr;
271 const SkMatrix* ctm = fCTM;
272 if (texCoords && texCoords != positions) {
273 paintShader = transformShader = outerAlloc->make<SkTransformShader>(*as_SB(paintShader),
274 usePerspective);
275 ctm = &SkMatrix::I();
276 }
277 sk_sp<SkShader> blenderShader = applyShaderColorBlend(paintShader);
278
279 SkPaint finalPaint{paint};
280 finalPaint.setShader(std::move(blenderShader));
281
282 VertState state(vertexCount, indices, indexCount);
283 VertState::Proc vertProc = state.chooseProc(info.mode());
285
286 auto blitter = SkCreateRasterPipelineBlitter(fDst,
287 finalPaint,
288 *ctm,
289 outerAlloc,
290 fRC->clipShader(),
291 props);
292 if (!blitter) {
293 return;
294 }
295 while (vertProc(&state)) {
296 if (triColorShader && !triColorShader->update(ctmInverse, positions, dstColors,
297 state.f0, state.f1, state.f2)) {
298 continue;
299 }
300
301 SkMatrix localM;
302 if (!transformShader || (texture_to_matrix(state, positions, texCoords, &localM) &&
303 transformShader->update(SkMatrix::Concat(localM, ctmInverse)))) {
304 fill_triangle(state, blitter, *fRC, dev2, dev3);
305 }
306 }
307}
308
309void SkDraw::drawVertices(const SkVertices* vertices,
310 sk_sp<SkBlender> blender,
311 const SkPaint& paint,
312 bool skipColorXform) const {
313 SkVerticesPriv info(vertices->priv());
314 const int vertexCount = info.vertexCount();
315 const int indexCount = info.indexCount();
316
317 // abort early if there is nothing to draw
318 if (vertexCount < 3 || (indexCount > 0 && indexCount < 3) || fRC->isEmpty()) {
319 return;
320 }
321 SkMatrix ctmInv;
322 if (!fCTM->invert(&ctmInv)) {
323 return;
324 }
325
326 constexpr size_t kDefVertexCount = 16;
327 constexpr size_t kOuterSize = sizeof(SkTriColorShader) +
328 (2 * sizeof(SkPoint) + sizeof(SkColor4f)) * kDefVertexCount;
330
331 SkPoint* dev2 = nullptr;
332 SkPoint3* dev3 = nullptr;
333
334 if (fCTM->hasPerspective()) {
335 dev3 = outerAlloc.makeArray<SkPoint3>(vertexCount);
336 fCTM->mapHomogeneousPoints(dev3, info.positions(), vertexCount);
337 // similar to the bounds check for 2d points (below)
338 if (!SkIsFinite((const SkScalar*)dev3, vertexCount * 3)) {
339 return;
340 }
341 } else {
342 dev2 = outerAlloc.makeArray<SkPoint>(vertexCount);
343 fCTM->mapPoints(dev2, info.positions(), vertexCount);
344
346 // this also sets bounds to empty if we see a non-finite value
347 bounds.setBounds(dev2, vertexCount);
348 if (bounds.isEmpty()) {
349 return;
350 }
351 }
352
353 this->drawFixedVertices(
354 vertices, std::move(blender), paint, ctmInv, dev2, dev3, &outerAlloc, skipColorXform);
355}
static void info(const char *fmt,...) SK_PRINTF_LIKE(1
Definition: DM.cpp:213
SkAssertResult(font.textToGlyphs("Hello", 5, SkTextEncoding::kUTF8, glyphs, std::size(glyphs))==count)
int count
Definition: FontMgrTest.cpp:50
SkPoint lerp(const SkPoint &a, const SkPoint &b, float t)
static float next(float f)
kUnpremul_SkAlphaType
@ kPremul_SkAlphaType
pixel components are premultiplied by alpha
Definition: SkAlphaType.h:29
#define SkASSERT(cond)
Definition: SkAssert.h:116
SkBlenderBase * as_BB(SkBlender *blend)
Definition: SkBlenderBase.h:69
@ kBGRA_8888_SkColorType
pixel with 8 bits for blue, green, red, alpha; in 32-bit word
Definition: SkColorType.h:26
@ kRGBA_F32_SkColorType
pixel using C float for red, green, blue, alpha; in 128-bit word
Definition: SkColorType.h:40
SkRGBA4f< kUnpremul_SkAlphaType > SkColor4f
Definition: SkColor.h:426
uint32_t SkColor
Definition: SkColor.h:37
#define SkColorGetA(color)
Definition: SkColor.h:61
bool SkConvertPixels(const SkImageInfo &dstInfo, void *dstPixels, size_t dstRB, const SkImageInfo &srcInfo, const void *srcPixels, size_t srcRB)
SkBlitter * SkCreateRasterPipelineBlitter(const SkPixmap &, const SkPaint &, const SkMatrix &ctm, SkArenaAlloc *, sk_sp< SkShader > clipShader, const SkSurfaceProps &props)
static SkPMColor4f * convert_colors(const SkColor src[], int count, SkColorSpace *deviceCS, SkArenaAlloc *alloc, bool skipColorXform)
static void fill_triangle_3(const VertState &state, SkBlitter *blitter, const SkRasterClip &rc, const SkPoint3 dev3[])
static bool texture_to_matrix(const VertState &state, const SkPoint verts[], const SkPoint texs[], SkMatrix *matrix)
static void fill_triangle_2(const VertState &state, SkBlitter *blitter, const SkRasterClip &rc, const SkPoint dev2[])
static void fill_triangle(const VertState &state, SkBlitter *blitter, const SkRasterClip &rc, const SkPoint dev2[], const SkPoint3 dev3[])
static constexpr int kMaxClippedTrianglePointCount
static bool compute_is_opaque(const SkColor colors[], int count)
static bool SkIsFinite(T x, Pack... values)
static constexpr float sk_ieee_float_divide(float numer, float denom)
static SkPath clip(const SkPath &path, const SkHalfPlane &plane)
Definition: SkPath.cpp:3892
sk_sp< T > sk_ref_sp(T *obj)
Definition: SkRefCnt.h:381
SkShaderBase * as_SB(SkShader *shader)
Definition: SkShaderBase.h:412
static SkSurfaceProps SkSurfacePropsCopyOrDefault(const SkSurfaceProps *props)
Definition: SkSurfacePriv.h:15
T * makeArray(size_t count)
Definition: SkArenaAlloc.h:181
auto make(Ctor &&ctor) -> decltype(ctor(nullptr))
Definition: SkArenaAlloc.h:120
static sk_sp< SkColorSpace > MakeSRGB()
const SkSurfaceProps * fProps
Definition: SkDrawBase.h:157
const SkRasterClip * fRC
Definition: SkDrawBase.h:156
SkPixmap fDst
Definition: SkDrawBase.h:153
const SkMatrix * fCTM
Definition: SkDrawBase.h:155
void drawVertices(const SkVertices *, sk_sp< SkBlender >, const SkPaint &, bool skipColorXform) const
void mapHomogeneousPoints(SkPoint3 dst[], const SkPoint3 src[], int count) const
Definition: SkMatrix.cpp:1066
void mapPoints(SkPoint dst[], const SkPoint src[], int count) const
Definition: SkMatrix.cpp:770
static SkMatrix Concat(const SkMatrix &a, const SkMatrix &b)
Definition: SkMatrix.h:1775
bool invert(SkMatrix *inverse) const
Definition: SkMatrix.h:1206
static const SkMatrix & I()
Definition: SkMatrix.cpp:1544
bool hasPerspective() const
Definition: SkMatrix.h:312
SkColorSpace * colorSpace() const
Definition: SkPixmap.cpp:61
sk_sp< SkShader > clipShader() const
Definition: SkRasterClip.h:95
bool isEmpty() const
Definition: SkRasterClip.h:47
static void FillTriangle(const SkPoint pts[], const SkRasterClip &, SkBlitter *)
bool update(const SkMatrix &matrix)
bool update(const SkMatrix &ctmInv, const SkPoint pts[], const SkPMColor4f colors[], int index0, int index1, int index2)
SkVerticesPriv priv()
const Paint & paint
Definition: color_source.cc:38
float SkScalar
Definition: extension.cpp:12
AtkStateType state
unsigned useCenter Optional< SkMatrix > matrix
Definition: SkRecords.h:258
Optional< SkRect > bounds
Definition: SkRecords.h:189
PODArray< SkRect > texs
Definition: SkRecords.h:333
PODArray< SkColor > colors
Definition: SkRecords.h:276
SK_API sk_sp< SkShader > Blend(SkBlendMode mode, sk_sp< SkShader > dst, sk_sp< SkShader > src)
SK_API sk_sp< SkShader > Color(SkColor)
dst
Definition: cp.py:12
const Scalar scale
static SkImageInfo Make(int width, int height, SkColorType ct, SkAlphaType at)
bool(* Proc)(VertState *)
Definition: SkVertState.h:39