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
8 #include "include/core/SkAlphaType.h"
9 #include "include/core/SkBlendMode.h"
10 #include "include/core/SkBlender.h"
11 #include "include/core/SkColor.h"
12 #include "include/core/SkColorSpace.h"
13 #include "include/core/SkColorType.h"
14 #include "include/core/SkImageInfo.h"
15 #include "include/core/SkMatrix.h"
16 #include "include/core/SkPaint.h"
17 #include "include/core/SkPixmap.h"
18 #include "include/core/SkPoint.h"
19 #include "include/core/SkPoint3.h"
20 #include "include/core/SkRect.h"
21 #include "include/core/SkRefCnt.h"
22 #include "include/core/SkScalar.h"
23 #include "include/core/SkShader.h"
24 #include "include/core/SkSurfaceProps.h"
25 #include "include/core/SkTypes.h"
26 #include "include/core/SkVertices.h"
27 #include "include/private/SkColorData.h"
28 #include "include/private/base/SkFloatingPoint.h"
29 #include "include/private/base/SkTo.h"
30 #include "src/base/SkArenaAlloc.h"
31 #include "src/core/SkBlenderBase.h"
32 #include "src/core/SkConvertPixels.h"
33 #include "src/core/SkCoreBlitters.h"
34 #include "src/core/SkDraw.h"
35 #include "src/core/SkRasterClip.h"
36 #include "src/core/SkScan.h"
37 #include "src/core/SkSurfacePriv.h"
38 #include "src/core/SkVertState.h"
39 #include "src/core/SkVerticesPriv.h"
40 #include "src/shaders/SkShaderBase.h"
41 #include "src/shaders/SkTransformShader.h"
42 #include "src/shaders/SkTriColorShader.h"
43
44 #include <cstddef>
45 #include <cstdint>
46 #include <optional>
47 #include <utility>
48
49 class SkBlitter;
50
texture_to_matrix(const VertState & state,const SkPoint verts[],const SkPoint texs[],SkMatrix * matrix)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 //
convert_colors(const SkColor src[],int count,SkColorSpace * deviceCS,SkArenaAlloc * alloc,bool skipColorXform)73 static SkPMColor4f* convert_colors(const SkColor src[],
74 int count,
75 SkColorSpace* deviceCS,
76 SkArenaAlloc* alloc,
77 bool skipColorXform) {
78 SkPMColor4f* dst = alloc->makeArray<SkPMColor4f>(count);
79
80 // Passing `nullptr` for the destination CS effectively disables color conversion.
81 auto dstCS = skipColorXform ? nullptr : sk_ref_sp(deviceCS);
82 SkImageInfo srcInfo = SkImageInfo::Make(
83 count, 1, kBGRA_8888_SkColorType, kUnpremul_SkAlphaType, SkColorSpace::MakeSRGB());
84 SkImageInfo dstInfo =
85 SkImageInfo::Make(count, 1, kRGBA_F32_SkColorType, kPremul_SkAlphaType, dstCS);
86 SkAssertResult(SkConvertPixels(dstInfo, dst, 0, srcInfo, src, 0));
87 return dst;
88 }
89
compute_is_opaque(const SkColor colors[],int count)90 static 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
fill_triangle_2(const VertState & state,SkBlitter * blitter,const SkRasterClip & rc,const SkPoint dev2[])98 static 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
106 static constexpr int kMaxClippedTrianglePointCount = 4;
fill_triangle_3(const VertState & state,SkBlitter * blitter,const SkRasterClip & rc,const SkPoint3 dev3[])107 static 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 {
137 SkPoint3 outPoints[kMaxClippedTrianglePointCount];
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
164 SkPoint tmp[kMaxClippedTrianglePointCount];
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
fill_triangle(const VertState & state,SkBlitter * blitter,const SkRasterClip & rc,const SkPoint dev2[],const SkPoint3 dev3[])178 static 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
drawFixedVertices(const SkVertices * vertices,sk_sp<SkBlender> blender,const SkPaint & paint,const SkMatrix & ctmInverse,const SkPoint * dev2,const SkPoint3 * dev3,SkArenaAlloc * outerAlloc,bool skipColorXform) const187 void 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) {
219 case SkBlendMode::kSrc:
220 colors = nullptr;
221 break;
222 case SkBlendMode::kDst:
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());
284 SkSurfaceProps props = SkSurfacePropsCopyOrDefault(fProps);
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
drawVertices(const SkVertices * vertices,sk_sp<SkBlender> blender,const SkPaint & paint,bool skipColorXform) const309 void 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;
329 SkSTArenaAlloc<kOuterSize> outerAlloc;
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
345 SkRect bounds;
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 }
356