Debian Codegraph @

src/text/gpu/SubRunContainer.cpp

raw ◀ ▶
Source reconstructed at patch state 2 of 3 — not the installed (fully patched) source.
3 Debian patches touch this file
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
8 #include "src/text/gpu/SubRunContainer.h"
9
10 #include "include/core/SkCanvas.h"
11 #include "include/core/SkDrawable.h"
12 #include "include/core/SkFont.h"
13 #include "include/core/SkMaskFilter.h"
14 #include "include/core/SkMatrix.h"
15 #include "include/core/SkPaint.h"
16 #include "include/core/SkPath.h"
17 #include "include/core/SkPathEffect.h"
18 #include "include/core/SkRect.h"
19 #include "include/core/SkScalar.h"
20 #include "include/core/SkStrokeRec.h"
21 #include "include/core/SkSurfaceProps.h"
22 #include "include/core/SkTypes.h"
23 #include "include/effects/SkDashPathEffect.h"
24 #include "include/private/base/SkFloatingPoint.h"
25 #include "include/private/base/SkOnce.h"
26 #include "include/private/base/SkTArray.h"
27 #include "include/private/base/SkTLogic.h"
28 #include "include/private/base/SkTo.h"
29 #include "src/base/SkZip.h"
30 #include "src/core/SkDevice.h"
31 #include "src/core/SkDistanceFieldGen.h"
32 #include "src/core/SkEnumerate.h"
33 #include "src/core/SkFontPriv.h"
34 #include "src/core/SkGlyph.h"
35 #include "src/core/SkMask.h"
36 #include "src/core/SkMaskFilterBase.h"
37 #include "src/core/SkMatrixPriv.h"
38 #include "src/core/SkPathEffectBase.h"
39 #include "src/core/SkReadBuffer.h"
40 #include "src/core/SkScalerContext.h"
41 #include "src/core/SkStrike.h"
42 #include "src/core/SkStrikeCache.h"
43 #include "src/core/SkStrikeSpec.h"
44 #include "src/core/SkWriteBuffer.h"
45 #include "src/gpu/AtlasTypes.h"
46 #include "src/text/GlyphRun.h"
47 #include "src/text/StrikeForGPU.h"
48 #include "src/text/gpu/Glyph.h"
49 #include "src/text/gpu/SDFMaskFilter.h"
50 #include "src/text/gpu/StrikeCache.h"
51 #include "src/text/gpu/SubRunControl.h"
52
53 #include <algorithm>
54 #include <climits>
55 #include <cstdint>
56 #include <new>
57 #include <optional>
58 #include <vector>
59
60 using namespace skia_private;
61 using namespace skglyph;
62
63 // -- GPU Text -------------------------------------------------------------------------------------
64 // Naming conventions
65 // * drawMatrix - the CTM from the canvas.
66 // * drawOrigin - the x, y location of the drawTextBlob call.
67 // * positionMatrix - this is the combination of the drawMatrix and the drawOrigin:
68 // positionMatrix = drawMatrix * TranslationMatrix(drawOrigin.x, drawOrigin.y);
69 //
70 // Note:
71 // In order to transform Slugs, you need to set the fSupportBilerpFromGlyphAtlas on
72 // GrContextOptions.
73
74 namespace sktext::gpu {
75 // -- SubRunStreamTag ------------------------------------------------------------------------------
76 enum SubRun::SubRunStreamTag : int {
77 kBad = 0, // Make this 0 to line up with errors from readInt.
78 kDirectMaskStreamTag,
79 #if !defined(SK_DISABLE_SDF_TEXT)
80 kSDFTStreamTag,
81 #endif
82 kTransformMaskStreamTag,
83 kPathStreamTag,
84 kDrawableStreamTag,
85 kSubRunStreamTagCount,
86 };
87
88 } // namespace sktext::gpu
89
90 using MaskFormat = skgpu::MaskFormat;
91
92 using namespace sktext;
93 using namespace sktext::gpu;
94
95 namespace {
96 SkSpan<const SkPackedGlyphID> get_packedIDs(SkZip<const SkPackedGlyphID, const SkPoint> accepted) {
97 return accepted.get<0>();
98 }
99
100 SkSpan<const SkGlyphID> get_glyphIDs(SkZip<const SkGlyphID, const SkPoint> accepted) {
101 return accepted.get<0>();
102 }
103
104 template <typename U> SkSpan<const SkPoint> get_positions(SkZip<U, const SkPoint> accepted) {
105 return accepted.template get<1>();
106 }
107
108 SkGlyphRect glyph_bounds(SkGlyphDigest digest, int inset, SkPoint origin) {
109 return digest.bounds().inset(inset, inset).offset(origin);
110 }
111
112 SkGlyphRect glyph_bounds_from_left_top(SkGlyphDigest digest, int inset, SkPoint leftTop) {
113 SkGlyphRect bounds = digest.bounds();
114 SkPoint offset = leftTop - bounds.leftTop() - SkPoint{SkIntToScalar(inset),
115 SkIntToScalar(inset)};
116 return glyph_bounds(digest, inset, offset);
117 }
118
119 // Returns the empty span if there is a problem reading the positions.
120 SkSpan<SkPoint> make_points_from_buffer(SkReadBuffer& buffer, SubRunAllocator* alloc) {
121 uint32_t glyphCount = buffer.getArrayCount();
122
123 // Zero indicates a problem with serialization.
124 if (!buffer.validate(glyphCount != 0)) { return {}; }
125
126 // Check that the count will not overflow the arena.
127 if (!buffer.validate(glyphCount <= INT_MAX &&
128 BagOfBytes::WillCountFit<SkPoint>(glyphCount))) { return {}; }
129
130 SkPoint* positionsData = alloc->makePODArray<SkPoint>(glyphCount);
131 if (!buffer.readPointArray({positionsData, glyphCount})) { return {}; }
132 return {positionsData, glyphCount};
133 }
134
135 SkRect reconstruct_safe_bounds(SkSpan<const SkPoint> leftTop,
136 GlyphVector* glyphVector,
137 skglyph::ActionType actionType,
138 int inset) {
139 int count = leftTop.size();
140
141 StrikeForGPU* strike = glyphVector->strikePromise().strike();
142 StrikeMutationMonitor m{strike};
143
144 SkGlyphRect boundingRect = skglyph::empty_rect();
145 for (int i = 0; i < count; ++i) {
146 SkPackedGlyphID packedID = glyphVector->getPackedGlyphID(i);
147 SkGlyphDigest digest = strike->digestFor(actionType, packedID);
148 boundingRect = skglyph::rect_union(
149 boundingRect, glyph_bounds_from_left_top(digest, inset, leftTop[i]));
150 }
151 return boundingRect.empty() ? SkRect::MakeEmpty() : boundingRect.rect();
152 }
153
154 void flatten_vertex_filler(SkWriteBuffer &buffer, const VertexFiller& vf) {
155 buffer.writeInt(static_cast<int>(vf.maskFormat()));
156 buffer.writeBool(vf.canDrawDirect());
157 buffer.writeMatrix(vf.creationMatrix());
158 buffer.writePointArray(vf.topLefts());
159 }
160
161 std::optional<VertexFiller> make_vertex_filler_from_buffer(SkReadBuffer& buffer,
162 SubRunAllocator* alloc,
163 GlyphVector* glyphVector,
164 skglyph::ActionType actionType,
165 int inset) {
166 MaskFormat maskFormat = buffer.read32LE(MaskFormat::kLast);
167
168 const bool canDrawDirect = buffer.readBool();
169
170 SkMatrix creationMatrix;
171 buffer.readMatrix(&creationMatrix);
172 // The only valid creationMatrices do not have perspective and many rendering parts assume
173 // they are non-affine, so reject any malformed matrices here.
174 if (!buffer.validate(!creationMatrix.hasPerspective())) {
175 return std::nullopt;
176 }
177
178 SkSpan<SkPoint> leftTop = make_points_from_buffer(buffer, alloc);
179 if (leftTop.empty()) {
180 return std::nullopt;
181 }
182
183 if (!buffer.validate(glyphVector->glyphCount() == (int)leftTop.size())) {
184 return std::nullopt;
185 }
186
187 SkRect safeBounds = reconstruct_safe_bounds(leftTop, glyphVector, actionType, inset);
188
189 return VertexFiller{maskFormat, creationMatrix, safeBounds, leftTop, canDrawDirect};
190 }
191
192 // -- PathOpSubmitter ------------------------------------------------------------------------------
193 // PathOpSubmitter holds glyph ids until ready to draw. During drawing, the glyph ids are
194 // converted to SkPaths. PathOpSubmitter can only be serialized when it is holding glyph ids;
195 // it can only be serialized before submitDraws has been called.
196 class PathOpSubmitter {
197 public:
198 PathOpSubmitter() = delete;
199 PathOpSubmitter(const PathOpSubmitter&) = delete;
200 const PathOpSubmitter& operator=(const PathOpSubmitter&) = delete;
201 PathOpSubmitter(PathOpSubmitter&& that)
202 // Transfer ownership of fIDsOrPaths from that to this.
203 : fIDsOrPaths{std::exchange(
204 const_cast<SkSpan<IDOrPath>&>(that.fIDsOrPaths), SkSpan<IDOrPath>{})}
205 , fPositions{that.fPositions}
206 , fStrikeToSourceScale{that.fStrikeToSourceScale}
207 , fIsAntiAliased{that.fIsAntiAliased}
208 , fStrikePromise{std::move(that.fStrikePromise)} {}
209 PathOpSubmitter& operator=(PathOpSubmitter&& that) {
210 this->~PathOpSubmitter();
211 new (this) PathOpSubmitter{std::move(that)};
212 return *this;
213 }
214 PathOpSubmitter(bool isAntiAliased,
215 SkScalar strikeToSourceScale,
216 SkSpan<SkPoint> positions,
217 SkSpan<IDOrPath> idsOrPaths,
218 SkStrikePromise&& strikePromise);
219
220 ~PathOpSubmitter();
221
222 static PathOpSubmitter Make(SkZip<const SkGlyphID, const SkPoint> accepted,
223 bool isAntiAliased,
224 SkScalar strikeToSourceScale,
225 SkStrikePromise&& strikePromise,
226 SubRunAllocator* alloc);
227
228 int unflattenSize() const;
229 void flatten(SkWriteBuffer& buffer) const;
230 static std::optional<PathOpSubmitter> MakeFromBuffer(SkReadBuffer& buffer,
231 SubRunAllocator* alloc,
232 const SkStrikeClient* client);
233
234 // submitDraws is not thread safe. It only occurs the single thread drawing portion of the GPU
235 // rendering.
236 void submitDraws(SkCanvas*,
237 SkPoint drawOrigin,
238 const SkPaint& paint) const;
239
240 private:
241 // When PathOpSubmitter is created only the glyphIDs are needed, during the submitDraws call,
242 // the glyphIDs are converted to SkPaths.
243 const SkSpan<IDOrPath> fIDsOrPaths;
244 const SkSpan<const SkPoint> fPositions;
245 const SkScalar fStrikeToSourceScale;
246 const bool fIsAntiAliased;
247
248 mutable SkStrikePromise fStrikePromise;
249 mutable SkOnce fConvertIDsToPaths;
250 mutable bool fPathsAreCreated{false};
251 };
252
253 int PathOpSubmitter::unflattenSize() const {
254 return fPositions.size_bytes() + fIDsOrPaths.size_bytes();
255 }
256
257 void PathOpSubmitter::flatten(SkWriteBuffer& buffer) const {
258 fStrikePromise.flatten(buffer);
259
260 buffer.writeInt(fIsAntiAliased);
261 buffer.writeScalar(fStrikeToSourceScale);
262 buffer.writePointArray(fPositions);
263 for (IDOrPath& idOrPath : fIDsOrPaths) {
264 buffer.writeInt(idOrPath.fGlyphID);
265 }
266 }
267
268 std::optional<PathOpSubmitter> PathOpSubmitter::MakeFromBuffer(SkReadBuffer& buffer,
269 SubRunAllocator* alloc,
270 const SkStrikeClient* client) {
271 std::optional<SkStrikePromise> strikePromise =
272 SkStrikePromise::MakeFromBuffer(buffer, client, SkStrikeCache::GlobalStrikeCache());
273 if (!buffer.validate(strikePromise.has_value())) {
274 return std::nullopt;
275 }
276
277 bool isAntiAlias = buffer.readInt();
278
279 SkScalar strikeToSourceScale = buffer.readScalar();
280 if (!buffer.validate(0 < strikeToSourceScale)) { return std::nullopt; }
281
282 SkSpan<SkPoint> positions = make_points_from_buffer(buffer, alloc);
283 if (positions.empty()) { return std::nullopt; }
284 const int glyphCount = SkCount(positions);
285
286 // Remember, we stored an int for glyph id.
287 if (!buffer.validateCanReadN<int>(glyphCount)) { return std::nullopt; }
288 auto idsOrPaths = SkSpan(alloc->makeUniqueArray<IDOrPath>(glyphCount).release(), glyphCount);
289 for (auto& idOrPath : idsOrPaths) {
290 idOrPath.fGlyphID = SkTo<SkGlyphID>(buffer.readInt());
291 }
292
293 if (!buffer.isValid()) { return std::nullopt; }
294
295 return PathOpSubmitter{isAntiAlias,
296 strikeToSourceScale,
297 positions,
298 idsOrPaths,
299 std::move(strikePromise.value())};
300 }
301
302 PathOpSubmitter::PathOpSubmitter(
303 bool isAntiAliased,
304 SkScalar strikeToSourceScale,
305 SkSpan<SkPoint> positions,
306 SkSpan<IDOrPath> idsOrPaths,
307 SkStrikePromise&& strikePromise)
308 : fIDsOrPaths{idsOrPaths}
309 , fPositions{positions}
310 , fStrikeToSourceScale{strikeToSourceScale}
311 , fIsAntiAliased{isAntiAliased}
312 , fStrikePromise{std::move(strikePromise)} {
313 SkASSERT(!fPositions.empty());
314 }
315
316 PathOpSubmitter::~PathOpSubmitter() {
317 // If we have converted glyph IDs to paths, then clean up the SkPaths.
318 if (fPathsAreCreated) {
319 for (auto& idOrPath : fIDsOrPaths) {
320 idOrPath.fPath.~SkPath();
321 }
322 }
323 }
324
325 PathOpSubmitter PathOpSubmitter::Make(SkZip<const SkGlyphID, const SkPoint> accepted,
326 bool isAntiAliased,
327 SkScalar strikeToSourceScale,
328 SkStrikePromise&& strikePromise,
329 SubRunAllocator* alloc) {
330 auto mapToIDOrPath = [](SkGlyphID glyphID) { return IDOrPath{glyphID}; };
331
332 IDOrPath* const rawIDsOrPaths =
333 alloc->makeUniqueArray<IDOrPath>(get_glyphIDs(accepted), mapToIDOrPath).release();
334
335 return PathOpSubmitter{isAntiAliased,
336 strikeToSourceScale,
337 alloc->makePODSpan(get_positions(accepted)),
338 SkSpan(rawIDsOrPaths, accepted.size()),
339 std::move(strikePromise)};
340 }
341
342 void
343 PathOpSubmitter::submitDraws(SkCanvas* canvas, SkPoint drawOrigin, const SkPaint& paint) const {
344 // Convert the glyph IDs to paths if it hasn't been done yet. This is thread safe.
345 fConvertIDsToPaths([&]() {
346 if (SkStrike* strike = fStrikePromise.strike()) {
347 strike->glyphIDsToPaths(fIDsOrPaths);
348
349 // Drop ref to strike so that it can be purged from the cache if needed.
350 fStrikePromise.resetStrike();
351 fPathsAreCreated = true;
352 }
353 });
354
355 SkPaint runPaint{paint};
356 runPaint.setAntiAlias(fIsAntiAliased);
357
358 SkMaskFilterBase* maskFilter = as_MFB(runPaint.getMaskFilter());
359
360 // Calculate the matrix that maps the path glyphs from their size in the strike to
361 // the graphics source space.
362 SkMatrix strikeToSource = SkMatrix::Scale(fStrikeToSourceScale, fStrikeToSourceScale);
363 strikeToSource.postTranslate(drawOrigin.x(), drawOrigin.y());
364
365 // If there are shaders, non-blur mask filters or styles, the path must be scaled into source
366 // space independently of the CTM. This allows the CTM to be correct for the different effects.
367 SkStrokeRec style(runPaint);
368 bool needsExactCTM = runPaint.getShader()
369 || runPaint.getPathEffect()
370 || (!style.isFillStyle() && !style.isHairlineStyle())
371 || (maskFilter != nullptr && !maskFilter->asABlur(nullptr));
372 if (!needsExactCTM) {
373 SkMaskFilterBase::BlurRec blurRec;
374
375 // If there is a blur mask filter, then sigma needs to be adjusted to account for the
376 // scaling of fStrikeToSourceScale.
377 if (maskFilter != nullptr && maskFilter->asABlur(&blurRec)) {
378 runPaint.setMaskFilter(
379 SkMaskFilter::MakeBlur(blurRec.fStyle, blurRec.fSigma / fStrikeToSourceScale));
380 }
381 for (auto [idOrPath, pos] : SkMakeZip(fIDsOrPaths, fPositions)) {
382 // Transform the glyph to source space.
383 SkMatrix pathMatrix = strikeToSource;
384 pathMatrix.postTranslate(pos.x(), pos.y());
385
386 SkAutoCanvasRestore acr(canvas, true);
387 canvas->concat(pathMatrix);
388 canvas->drawPath(idOrPath.fPath, runPaint);
389 }
390 } else {
391 // Transform the path to device because the deviceMatrix must be unchanged to
392 // draw effect, filter or shader paths.
393 for (auto [idOrPath, pos] : SkMakeZip(fIDsOrPaths, fPositions)) {
394 // Transform the glyph to source space.
395 SkMatrix pathMatrix = strikeToSource;
396 pathMatrix.postTranslate(pos.x(), pos.y());
397
398 SkPath deviceOutline = idOrPath.fPath.makeTransform(pathMatrix);
399 deviceOutline.setIsVolatile(true);
400 canvas->drawPath(deviceOutline, runPaint);
401 }
402 }
403 }
404
405 // -- PathSubRun -----------------------------------------------------------------------------------
406 class PathSubRun final : public SubRun {
407 public:
408 PathSubRun(PathOpSubmitter&& pathDrawing) : fPathDrawing(std::move(pathDrawing)) {}
409
410 static SubRunOwner Make(SkZip<const SkGlyphID, const SkPoint> accepted,
411 bool isAntiAliased,
412 SkScalar strikeToSourceScale,
413 SkStrikePromise&& strikePromise,
414 SubRunAllocator* alloc) {
415 return alloc->makeUnique<PathSubRun>(
416 PathOpSubmitter::Make(
417 accepted, isAntiAliased, strikeToSourceScale, std::move(strikePromise), alloc));
418 }
419
420 void draw(SkCanvas* canvas,
421 SkPoint drawOrigin,
422 const SkPaint& paint,
423 sk_sp<SkRefCnt>,
424 const AtlasDrawDelegate&) const override {
425 fPathDrawing.submitDraws(canvas, drawOrigin, paint);
426 }
427
428 int unflattenSize() const override;
429
430 bool canReuse(const SkPaint& paint, const SkMatrix& positionMatrix) const override {
431 return true;
432 }
433 const AtlasSubRun* testingOnly_atlasSubRun() const override { return nullptr; }
434 static SubRunOwner MakeFromBuffer(SkReadBuffer& buffer,
435 SubRunAllocator* alloc,
436 const SkStrikeClient* client);
437
438 protected:
439 SubRunStreamTag subRunStreamTag() const override { return SubRunStreamTag::kPathStreamTag; }
440 void doFlatten(SkWriteBuffer& buffer) const override;
441
442 private:
443 PathOpSubmitter fPathDrawing;
444 };
445
446 int PathSubRun::unflattenSize() const {
447 return sizeof(PathSubRun) + fPathDrawing.unflattenSize();
448 }
449
450 void PathSubRun::doFlatten(SkWriteBuffer& buffer) const {
451 fPathDrawing.flatten(buffer);
452 }
453
454 SubRunOwner PathSubRun::MakeFromBuffer(SkReadBuffer& buffer,
455 SubRunAllocator* alloc,
456 const SkStrikeClient* client) {
457 auto pathOpSubmitter = PathOpSubmitter::MakeFromBuffer(buffer, alloc, client);
458 if (!buffer.validate(pathOpSubmitter.has_value())) { return nullptr; }
459 return alloc->makeUnique<PathSubRun>(std::move(*pathOpSubmitter));
460 }
461
462 // -- DrawableOpSubmitter --------------------------------------------------------------------------
463 // Shared code for submitting GPU ops for drawing glyphs as drawables.
464 class DrawableOpSubmitter {
465 public:
466 DrawableOpSubmitter() = delete;
467 DrawableOpSubmitter(const DrawableOpSubmitter&) = delete;
468 const DrawableOpSubmitter& operator=(const DrawableOpSubmitter&) = delete;
469 DrawableOpSubmitter(DrawableOpSubmitter&& that)
470 : fStrikeToSourceScale{that.fStrikeToSourceScale}
471 , fPositions{that.fPositions}
472 , fIDsOrDrawables{that.fIDsOrDrawables}
473 , fStrikePromise{std::move(that.fStrikePromise)} {}
474 DrawableOpSubmitter& operator=(DrawableOpSubmitter&& that) {
475 this->~DrawableOpSubmitter();
476 new (this) DrawableOpSubmitter{std::move(that)};
477 return *this;
478 }
479 DrawableOpSubmitter(SkScalar strikeToSourceScale,
480 SkSpan<SkPoint> positions,
481 SkSpan<IDOrDrawable> idsOrDrawables,
482 SkStrikePromise&& strikePromise);
483
484 static DrawableOpSubmitter Make(SkZip<const SkGlyphID, const SkPoint> accepted,
485 SkScalar strikeToSourceScale,
486 SkStrikePromise&& strikePromise,
487 SubRunAllocator* alloc) {
488 auto mapToIDOrDrawable = [](const SkGlyphID glyphID) { return IDOrDrawable{glyphID}; };
489
490 return DrawableOpSubmitter{
491 strikeToSourceScale,
492 alloc->makePODSpan(get_positions(accepted)),
493 alloc->makePODArray<IDOrDrawable>(get_glyphIDs(accepted), mapToIDOrDrawable),
494 std::move(strikePromise)};
495 }
496
497 int unflattenSize() const;
498 void flatten(SkWriteBuffer& buffer) const;
499 static std::optional<DrawableOpSubmitter> MakeFromBuffer(SkReadBuffer& buffer,
500 SubRunAllocator* alloc,
501 const SkStrikeClient* client);
502 void submitDraws(SkCanvas* canvas, SkPoint drawOrigin, const SkPaint& paint) const;
503
504 private:
505 const SkScalar fStrikeToSourceScale;
506 const SkSpan<SkPoint> fPositions;
507 const SkSpan<IDOrDrawable> fIDsOrDrawables;
508 // When the promise is converted to a strike it acts as the ref on the strike to keep the
509 // SkDrawable data alive.
510 mutable SkStrikePromise fStrikePromise;
511 mutable SkOnce fConvertIDsToDrawables;
512 };
513
514 int DrawableOpSubmitter::unflattenSize() const {
515 return fPositions.size_bytes() + fIDsOrDrawables.size_bytes();
516 }
517
518 void DrawableOpSubmitter::flatten(SkWriteBuffer& buffer) const {
519 fStrikePromise.flatten(buffer);
520
521 buffer.writeScalar(fStrikeToSourceScale);
522 buffer.writePointArray(fPositions);
523 for (IDOrDrawable idOrDrawable : fIDsOrDrawables) {
524 buffer.writeInt(idOrDrawable.fGlyphID);
525 }
526 }
527
528 std::optional<DrawableOpSubmitter> DrawableOpSubmitter::MakeFromBuffer(
529 SkReadBuffer& buffer, SubRunAllocator* alloc, const SkStrikeClient* client) {
530 std::optional<SkStrikePromise> strikePromise =
531 SkStrikePromise::MakeFromBuffer(buffer, client, SkStrikeCache::GlobalStrikeCache());
532 if (!buffer.validate(strikePromise.has_value())) {
533 return std::nullopt;
534 }
535
536 SkScalar strikeToSourceScale = buffer.readScalar();
537 if (!buffer.validate(0 < strikeToSourceScale)) { return std::nullopt; }
538
539 SkSpan<SkPoint> positions = make_points_from_buffer(buffer, alloc);
540 if (positions.empty()) { return std::nullopt; }
541 const int glyphCount = SkCount(positions);
542
543 if (!buffer.validateCanReadN<int>(glyphCount)) { return std::nullopt; }
544 auto idsOrDrawables = alloc->makePODArray<IDOrDrawable>(glyphCount);
545 for (int i = 0; i < SkToInt(glyphCount); ++i) {
546 // Remember, we stored an int for glyph id.
547 idsOrDrawables[i].fGlyphID = SkTo<SkGlyphID>(buffer.readInt());
548 }
549
550 if (!buffer.isValid()) {
551 return std::nullopt;
552 }
553
554 return DrawableOpSubmitter{strikeToSourceScale,
555 positions,
556 SkSpan(idsOrDrawables, glyphCount),
557 std::move(strikePromise.value())};
558 }
559
560 DrawableOpSubmitter::DrawableOpSubmitter(
561 SkScalar strikeToSourceScale,
562 SkSpan<SkPoint> positions,
563 SkSpan<IDOrDrawable> idsOrDrawables,
564 SkStrikePromise&& strikePromise)
565 : fStrikeToSourceScale{strikeToSourceScale}
566 , fPositions{positions}
567 , fIDsOrDrawables{idsOrDrawables}
568 , fStrikePromise(std::move(strikePromise)) {
569 SkASSERT(!fPositions.empty());
570 }
571
572 void
573 DrawableOpSubmitter::submitDraws(SkCanvas* canvas, SkPoint drawOrigin,const SkPaint& paint) const {
574 // Convert glyph IDs to Drawables if it hasn't been done yet.
575 fConvertIDsToDrawables([&]() {
576 fStrikePromise.strike()->glyphIDsToDrawables(fIDsOrDrawables);
577 // Do not call resetStrike() because the strike must remain owned to ensure the Drawable
578 // data is not freed.
579 });
580
581 // Calculate the matrix that maps the path glyphs from their size in the strike to
582 // the graphics source space.
583 SkMatrix strikeToSource = SkMatrix::Scale(fStrikeToSourceScale, fStrikeToSourceScale);
584 strikeToSource.postTranslate(drawOrigin.x(), drawOrigin.y());
585
586 // Transform the path to device because the deviceMatrix must be unchanged to
587 // draw effect, filter or shader paths.
588 for (auto [i, position] : SkMakeEnumerate(fPositions)) {
589 SkDrawable* drawable = fIDsOrDrawables[i].fDrawable;
590
591 if (drawable == nullptr) {
592 // This better be pinned to keep the drawable data alive.
593 fStrikePromise.strike()->verifyPinnedStrike();
594 SkDEBUGFAIL("Drawable should not be nullptr.");
595 continue;
596 }
597
598 // Transform the glyph to source space.
599 SkMatrix pathMatrix = strikeToSource;
600 pathMatrix.postTranslate(position.x(), position.y());
601
602 SkAutoCanvasRestore acr(canvas, false);
603 SkRect drawableBounds = drawable->getBounds();
604 pathMatrix.mapRect(&drawableBounds);
605 canvas->saveLayer(&drawableBounds, &paint);
606 drawable->draw(canvas, &pathMatrix);
607 }
608 }
609
610 // -- DrawableSubRun -------------------------------------------------------------------------------
611 class DrawableSubRun : public SubRun {
612 public:
613 DrawableSubRun(DrawableOpSubmitter&& drawingDrawing)
614 : fDrawingDrawing(std::move(drawingDrawing)) {}
615
616 static SubRunOwner Make(SkZip<const SkGlyphID, const SkPoint> drawables,
617 SkScalar strikeToSourceScale,
618 SkStrikePromise&& strikePromise,
619 SubRunAllocator* alloc) {
620 return alloc->makeUnique<DrawableSubRun>(
621 DrawableOpSubmitter::Make(drawables,
622 strikeToSourceScale,
623 std::move(strikePromise),
624 alloc));
625 }
626
627 static SubRunOwner MakeFromBuffer(SkReadBuffer& buffer,
628 SubRunAllocator* alloc,
629 const SkStrikeClient* client);
630
631 void draw(SkCanvas* canvas,
632 SkPoint drawOrigin,
633 const SkPaint& paint,
634 sk_sp<SkRefCnt>,
635 const AtlasDrawDelegate&) const override {
636 fDrawingDrawing.submitDraws(canvas, drawOrigin, paint);
637 }
638
639 int unflattenSize() const override;
640
641 bool canReuse(const SkPaint& paint, const SkMatrix& positionMatrix) const override;
642
643 const AtlasSubRun* testingOnly_atlasSubRun() const override;
644
645 protected:
646 SubRunStreamTag subRunStreamTag() const override { return SubRunStreamTag::kDrawableStreamTag; }
647 void doFlatten(SkWriteBuffer& buffer) const override;
648
649 private:
650 DrawableOpSubmitter fDrawingDrawing;
651 };
652
653 int DrawableSubRun::unflattenSize() const {
654 return sizeof(DrawableSubRun) + fDrawingDrawing.unflattenSize();
655 }
656
657 void DrawableSubRun::doFlatten(SkWriteBuffer& buffer) const {
658 fDrawingDrawing.flatten(buffer);
659 }
660
661 SubRunOwner DrawableSubRun::MakeFromBuffer(SkReadBuffer& buffer,
662 SubRunAllocator* alloc,
663 const SkStrikeClient* client) {
664 auto drawableOpSubmitter = DrawableOpSubmitter::MakeFromBuffer(buffer, alloc, client);
665 if (!buffer.validate(drawableOpSubmitter.has_value())) { return nullptr; }
666 return alloc->makeUnique<DrawableSubRun>(std::move(*drawableOpSubmitter));
667 }
668
669 bool DrawableSubRun::canReuse(const SkPaint& paint, const SkMatrix& positionMatrix) const {
670 return true;
671 }
672
673 const AtlasSubRun* DrawableSubRun::testingOnly_atlasSubRun() const {
674 return nullptr;
675 }
676
677 // -- DirectMaskSubRun -----------------------------------------------------------------------------
678 class DirectMaskSubRun final : public AtlasSubRun {
679 public:
680 static constexpr int kGlyphInsetting = 0;
681
682 DirectMaskSubRun(VertexFiller&& vertexFiller,
683 GlyphVector&& glyphs)
684 : AtlasSubRun(std::move(vertexFiller), std::move(glyphs)) {}
685
686 static SubRunOwner Make(SkRect creationBounds,
687 SkZip<const SkPackedGlyphID, const SkPoint> accepted,
688 const SkMatrix& creationMatrix,
689 SkStrikePromise&& strikePromise,
690 MaskFormat maskType,
691 SubRunAllocator* alloc) {
692 auto vertexFiller = VertexFiller::Make(maskType,
693 creationMatrix,
694 creationBounds,
695 get_positions(accepted),
696 alloc,
697 kIsDirect);
698
699 auto glyphVector =
700 GlyphVector::Make(std::move(strikePromise), get_packedIDs(accepted), alloc);
701
702 return alloc->makeUnique<DirectMaskSubRun>(std::move(vertexFiller), std::move(glyphVector));
703 }
704
705 static SubRunOwner MakeFromBuffer(SkReadBuffer& buffer,
706 SubRunAllocator* alloc,
707 const SkStrikeClient* client) {
708 auto glyphVector = GlyphVector::MakeFromBuffer(buffer, client, alloc);
709 if (!buffer.validate(glyphVector.has_value())) { return nullptr; }
710 auto vertexFiller = make_vertex_filler_from_buffer(buffer, alloc, &glyphVector.value(),
711 skglyph::kDirectMask, kGlyphInsetting);
712 if (!buffer.validate(vertexFiller.has_value())) { return nullptr; }
713
714 SkASSERT(buffer.isValid());
715 return alloc->makeUnique<DirectMaskSubRun>(
716 std::move(*vertexFiller), std::move(*glyphVector));
717 }
718
719 void draw(SkCanvas*,
720 SkPoint drawOrigin,
721 const SkPaint& paint,
722 sk_sp<SkRefCnt> subRunStorage,
723 const AtlasDrawDelegate& drawAtlas) const override {
724 drawAtlas(this, drawOrigin, paint, std::move(subRunStorage),
725 {/* isSDF = */false, fVertexFiller.isLCD(), fVertexFiller.grMaskType()});
726 }
727
728 int unflattenSize() const override {
729 return sizeof(DirectMaskSubRun) +
730 fGlyphs.unflattenSize() +
731 fVertexFiller.unflattenSize();
732 }
733
734 int glyphSrcPadding() const override { return kGlyphInsetting; }
735
736 void testingOnly_packedGlyphIDToGlyph(StrikeCache* cache,
737 skgpu::MaskFormat maskFormat) const override {
738 fGlyphs.packedGlyphIDToGlyph(cache, maskFormat);
739 }
740
741 std::tuple<bool, SkRect> deviceRectAndNeedsTransform(
742 const SkMatrix &positionMatrix) const override {
743 auto [integerTranslate, deviceRect] =
744 fVertexFiller.deviceRectAndCheckTransform(positionMatrix);
745 return {!integerTranslate, deviceRect};
746 }
747
748 GlyphParams glyphParams() const override {
749 // Since this is non-SDF, isAA will be ignored so we just pass true
750 return { /*isSDF=*/false, fVertexFiller.isLCD(), /*isAA=*/true };
751 }
752
753 std::tuple<bool, int> regenerateAtlas(int begin, int end,
754 RegenerateAtlasDelegate regenerateAtlas) const override {
755 return regenerateAtlas(
756 &fGlyphs, begin, end, fVertexFiller.grMaskType(), this->glyphSrcPadding());
757 }
758
759 bool canReuse(const SkPaint& paint, const SkMatrix& positionMatrix) const override {
760 auto [reuse, _] = fVertexFiller.deviceRectAndCheckTransform(positionMatrix);
761 return reuse;
762 }
763
764 const AtlasSubRun* testingOnly_atlasSubRun() const override {
765 return this;
766 }
767
768 protected:
769 SubRunStreamTag subRunStreamTag() const override {
770 return SubRunStreamTag::kDirectMaskStreamTag;
771 }
772
773 void doFlatten(SkWriteBuffer& buffer) const override {
774 fGlyphs.flatten(buffer);
775 flatten_vertex_filler(buffer, fVertexFiller);
776 }
777 };
778
779 // -- TransformedMaskSubRun ------------------------------------------------------------------------
780 class TransformedMaskSubRun final : public AtlasSubRun {
781 public:
782 static constexpr int kGlyphInsetting = 0;
783
784 TransformedMaskSubRun(bool isBigEnough,
785 VertexFiller&& vertexFiller,
786 GlyphVector&& glyphs)
787 : AtlasSubRun(std::move(vertexFiller), std::move(glyphs))
788 , fIsBigEnough{isBigEnough} {}
789
790 static SubRunOwner Make(SkZip<const SkPackedGlyphID, const SkPoint> accepted,
791 const SkMatrix& initialPositionMatrix,
792 SkStrikePromise&& strikePromise,
793 SkMatrix creationMatrix,
794 SkRect creationBounds,
795 MaskFormat maskType,
796 SubRunAllocator* alloc) {
797 auto vertexFiller = VertexFiller::Make(maskType,
798 creationMatrix,
799 creationBounds,
800 get_positions(accepted),
801 alloc,
802 kIsTransformed);
803
804 auto glyphVector = GlyphVector::Make(
805 std::move(strikePromise), get_packedIDs(accepted), alloc);
806
807 return alloc->makeUnique<TransformedMaskSubRun>(
808 AtlasSubRun::IsBigEnough(initialPositionMatrix),
809 std::move(vertexFiller),
810 std::move(glyphVector));
811 }
812
813 static SubRunOwner MakeFromBuffer(SkReadBuffer& buffer,
814 SubRunAllocator* alloc,
815 const SkStrikeClient* client) {
816 auto glyphVector = GlyphVector::MakeFromBuffer(buffer, client, alloc);
817 if (!buffer.validate(glyphVector.has_value())) { return nullptr; }
818 auto vertexFiller = make_vertex_filler_from_buffer(buffer, alloc, &glyphVector.value(),
819 skglyph::kMask, kGlyphInsetting);
820 if (!buffer.validate(vertexFiller.has_value())) { return nullptr; }
821
822 const bool isBigEnough = buffer.readBool();
823 return alloc->makeUnique<TransformedMaskSubRun>(
824 AtlasSubRun::IsBigEnough(vertexFiller->creationMatrix()),
825 std::move(*vertexFiller), std::move(*glyphVector));
826 }
827
828 int unflattenSize() const override {
829 return sizeof(TransformedMaskSubRun) +
830 fGlyphs.unflattenSize() +
831 fVertexFiller.unflattenSize();
832 }
833
834 bool canReuse(const SkPaint& paint, const SkMatrix& positionMatrix) const override {
835 // If we are not scaling the cache entry to be larger, than a cache with smaller glyphs may
836 // be better.
837 return fIsBigEnough;
838 }
839
840 const AtlasSubRun* testingOnly_atlasSubRun() const override { return this; }
841
842 void testingOnly_packedGlyphIDToGlyph(StrikeCache *cache,
843 skgpu::MaskFormat maskFormat) const override {
844 fGlyphs.packedGlyphIDToGlyph(cache, maskFormat);
845 }
846
847 int glyphSrcPadding() const override { return 1; } // Padding NOT equal to insetting
848
849 void draw(SkCanvas*,
850 SkPoint drawOrigin,
851 const SkPaint& paint,
852 sk_sp<SkRefCnt> subRunStorage,
853 const AtlasDrawDelegate& drawAtlas) const override {
854 drawAtlas(this, drawOrigin, paint, std::move(subRunStorage),
855 {/* isSDF = */false, fVertexFiller.isLCD(), fVertexFiller.grMaskType()});
856 }
857
858 std::tuple<bool, SkRect> deviceRectAndNeedsTransform(
859 const SkMatrix &positionMatrix) const override {
860 auto [_, deviceRect] = fVertexFiller.deviceRectAndCheckTransform(positionMatrix);
861 return {true, deviceRect};
862 }
863
864 GlyphParams glyphParams() const override {
865 // Since this is non-SDF, isAA will be ignored so we just pass true
866 return { /*isSDF=*/false, fVertexFiller.isLCD(), /*isAA=*/true };
867 }
868
869 std::tuple<bool, int> regenerateAtlas(int begin, int end,
870 RegenerateAtlasDelegate regenerateAtlas) const override {
871 return regenerateAtlas(
872 &fGlyphs, begin, end, fVertexFiller.grMaskType(), this->glyphSrcPadding());
873 }
874
875 protected:
876 SubRunStreamTag subRunStreamTag() const override {
877 return SubRunStreamTag::kTransformMaskStreamTag;
878 }
879
880 void doFlatten(SkWriteBuffer& buffer) const override {
881 fGlyphs.flatten(buffer);
882 flatten_vertex_filler(buffer, fVertexFiller);
883 }
884
885 private:
886 const bool fIsBigEnough;
887 }; // class TransformedMaskSubRun
888
889 // -- SDFTSubRun -----------------------------------------------------------------------------------
890
891 bool has_some_antialiasing(const SkFont& font ) {
892 SkFont::Edging edging = font.getEdging();
893 return edging == SkFont::Edging::kAntiAlias
894 || edging == SkFont::Edging::kSubpixelAntiAlias;
895 }
896
897 #if !defined(SK_DISABLE_SDF_TEXT)
898
899 class SDFTSubRun final : public AtlasSubRun {
900 public:
901 static constexpr int kGlyphInsetting = SK_DistanceFieldInset;
902
903 SDFTSubRun(bool useLCDText,
904 bool antiAliased,
905 const SDFTMatrixRange& matrixRange,
906 VertexFiller&& vertexFiller,
907 GlyphVector&& glyphs)
908 : AtlasSubRun(std::move(vertexFiller), std::move(glyphs))
909 , fUseLCDText{useLCDText}
910 , fAntiAliased{antiAliased}
911 , fMatrixRange{matrixRange} {
912 SkASSERT(fVertexFiller.grMaskType() == MaskFormat::kA8);
913 }
914
915 static SubRunOwner Make(SkZip<const SkPackedGlyphID, const SkPoint> accepted,
916 const SkFont& runFont,
917 SkStrikePromise&& strikePromise,
918 const SkMatrix& creationMatrix,
919 SkRect creationBounds,
920 const SDFTMatrixRange& matrixRange,
921 SubRunAllocator* alloc) {
922 // NOTE: The MaskFormat is hard coded to kA8 here. This means that when isLCD() is called
923 // from VertexFiller, it always returns false. However, VertexFiller has no other behavior
924 // that depends on this function, and drawAtlasSubrun instead determines LCD based on the
925 // fUseLCDText member variable. If this ever changes, VertexFiller will need to take an
926 // additional isLCD argument on the constructor.
927 auto vertexFiller = VertexFiller::Make(MaskFormat::kA8,
928 creationMatrix,
929 creationBounds,
930 get_positions(accepted),
931 alloc,
932 kIsTransformed);
933
934 auto glyphVector = GlyphVector::Make(
935 std::move(strikePromise), get_packedIDs(accepted), alloc);
936
937 // NOTE: When creating the SubRun, only the runFont edging determines LCD usage. This is
938 // because the upstream preparation in SubRunContainer::MakeInAlloc is identical between
939 // LCD and non-LCD. Instead LCD is set here, so that when the subRun is consumed in
940 // drawAtlasSubRun, the SDFLCD renderer is chosen.
941 return alloc->makeUnique<SDFTSubRun>(
942 runFont.getEdging() == SkFont::Edging::kSubpixelAntiAlias,
943 has_some_antialiasing(runFont),
944 matrixRange,
945 std::move(vertexFiller),
946 std::move(glyphVector));
947 }
948
949 static SubRunOwner MakeFromBuffer(SkReadBuffer& buffer,
950 SubRunAllocator* alloc,
951 const SkStrikeClient* client) {
952 int useLCD = buffer.readInt();
953 int isAntiAliased = buffer.readInt();
954 SDFTMatrixRange matrixRange = SDFTMatrixRange::MakeFromBuffer(buffer);
955
956 auto glyphVector = GlyphVector::MakeFromBuffer(buffer, client, alloc);
957 if (!buffer.validate(glyphVector.has_value())) { return nullptr; }
958 auto vertexFiller = make_vertex_filler_from_buffer(buffer, alloc, &glyphVector.value(),
959 skglyph::kSDFT, kGlyphInsetting);
960 if (!buffer.validate(vertexFiller.has_value())) { return nullptr; }
961
962 return alloc->makeUnique<SDFTSubRun>(useLCD,
963 isAntiAliased,
964 matrixRange,
965 std::move(*vertexFiller),
966 std::move(*glyphVector));
967 }
968
969 int unflattenSize() const override {
970 return sizeof(SDFTSubRun) + fGlyphs.unflattenSize() + fVertexFiller.unflattenSize();
971 }
972
973 bool canReuse(const SkPaint& paint, const SkMatrix& positionMatrix) const override {
974 return fMatrixRange.matrixInRange(positionMatrix);
975 }
976
977 const AtlasSubRun* testingOnly_atlasSubRun() const override { return this; }
978
979 void testingOnly_packedGlyphIDToGlyph(StrikeCache *cache,
980 skgpu::MaskFormat maskFormat) const override {
981 fGlyphs.packedGlyphIDToGlyph(cache, maskFormat);
982 }
983
984 int glyphSrcPadding() const override { return kGlyphInsetting; }
985
986 void draw(SkCanvas*,
987 SkPoint drawOrigin,
988 const SkPaint& paint,
989 sk_sp<SkRefCnt> subRunStorage,
990 const AtlasDrawDelegate& drawAtlas) const override {
991 drawAtlas(this, drawOrigin, paint, std::move(subRunStorage),
992 {/* isSDF = */true, /* isLCD = */fUseLCDText, skgpu::MaskFormat::kA8});
993 }
994
995 std::tuple<bool, SkRect> deviceRectAndNeedsTransform(
996 const SkMatrix &positionMatrix) const override {
997 auto [_, deviceRect] = fVertexFiller.deviceRectAndCheckTransform(positionMatrix);
998 return {true, deviceRect};
999 }
1000
1001 GlyphParams glyphParams() const override {
1002 return { /*isSDF=*/true, fUseLCDText, /*isAA=*/fAntiAliased };
1003 }
1004
1005 std::tuple<bool, int> regenerateAtlas(int begin, int end,
1006 RegenerateAtlasDelegate regenerateAtlas) const override {
1007 return regenerateAtlas(&fGlyphs, begin, end, MaskFormat::kA8, this->glyphSrcPadding());
1008 }
1009
1010 protected:
1011 SubRunStreamTag subRunStreamTag() const override { return SubRunStreamTag::kSDFTStreamTag; }
1012 void doFlatten(SkWriteBuffer& buffer) const override {
1013 buffer.writeInt(fUseLCDText);
1014 buffer.writeInt(fAntiAliased);
1015 fMatrixRange.flatten(buffer);
1016 fGlyphs.flatten(buffer);
1017 flatten_vertex_filler(buffer, fVertexFiller);
1018 }
1019
1020 private:
1021 const bool fUseLCDText;
1022 const bool fAntiAliased;
1023 const SDFTMatrixRange fMatrixRange;
1024 }; // class SDFTSubRun
1025
1026 #endif // !defined(SK_DISABLE_SDF_TEXT)
1027
1028 // -- SubRun ---------------------------------------------------------------------------------------
1029
1030 template<typename AddSingleMaskFormat>
1031 void add_multi_mask_format(
1032 AddSingleMaskFormat addSingleMaskFormat,
1033 SkZip<const SkPackedGlyphID, const SkPoint, const SkMask::Format> accepted) {
1034 if (accepted.empty()) { return; }
1035
1036 auto maskSpan = accepted.get<2>();
1037 MaskFormat format = Glyph::FormatFromSkGlyph(maskSpan[0]);
1038 size_t startIndex = 0;
1039 for (size_t i = 1; i < accepted.size(); i++) {
1040 MaskFormat nextFormat = Glyph::FormatFromSkGlyph(maskSpan[i]);
1041 if (format != nextFormat) {
1042 auto interval = accepted.subspan(startIndex, i - startIndex);
1043 // Only pass the packed glyph ids and positions.
1044 auto glyphsWithSameFormat = SkMakeZip(interval.get<0>(), interval.get<1>());
1045 // Take a ref on the strike. This should rarely happen.
1046 addSingleMaskFormat(glyphsWithSameFormat, format);
1047 format = nextFormat;
1048 startIndex = i;
1049 }
1050 }
1051 auto interval = accepted.last(accepted.size() - startIndex);
1052 auto glyphsWithSameFormat = SkMakeZip(interval.get<0>(), interval.get<1>());
1053 addSingleMaskFormat(glyphsWithSameFormat, format);
1054 }
1055 } // anonymous namespace
1056
1057 namespace sktext::gpu {
1058 SubRun::~SubRun() = default;
1059
1060 void SubRun::flatten(SkWriteBuffer& buffer) const {
1061 buffer.writeInt(this->subRunStreamTag());
1062 this->doFlatten(buffer);
1063 }
1064
1065 SubRunOwner SubRun::MakeFromBuffer(SkReadBuffer& buffer,
1066 SubRunAllocator* alloc,
1067 const SkStrikeClient* client) {
1068 using Maker = SubRunOwner (*)(SkReadBuffer&,
1069 SubRunAllocator*,
1070 const SkStrikeClient*);
1071
1072 static Maker makers[kSubRunStreamTagCount] = {
1073 nullptr, // 0 index is bad.
1074 DirectMaskSubRun::MakeFromBuffer,
1075 #if !defined(SK_DISABLE_SDF_TEXT)
1076 SDFTSubRun::MakeFromBuffer,
1077 #endif
1078 TransformedMaskSubRun::MakeFromBuffer,
1079 PathSubRun::MakeFromBuffer,
1080 DrawableSubRun::MakeFromBuffer,
1081 };
1082 int subRunTypeInt = buffer.readInt();
1083 if (!buffer.validate(kBad < subRunTypeInt && subRunTypeInt < kSubRunStreamTagCount)) {
1084 return nullptr;
1085 }
1086 auto maker = makers[subRunTypeInt];
1087 if (!buffer.validate(maker != nullptr)) { return nullptr; }
1088 return maker(buffer, alloc, client);
1089 }
1090
1091 // -- SubRunContainer ------------------------------------------------------------------------------
1092 SubRunContainer::SubRunContainer(const SkMatrix& initialPositionMatrix)
1093 : fInitialPositionMatrix{initialPositionMatrix} {}
1094
1095 void SubRunContainer::flattenAllocSizeHint(SkWriteBuffer& buffer) const {
1096 int unflattenSizeHint = 0;
1097 for (auto& subrun : fSubRuns) {
1098 unflattenSizeHint += subrun.unflattenSize();
1099 }
1100 buffer.writeInt(unflattenSizeHint);
1101 }
1102
1103 int SubRunContainer::AllocSizeHintFromBuffer(SkReadBuffer& buffer) {
1104 int subRunsSizeHint = buffer.readInt();
1105
1106 // Since the hint doesn't affect correctness, if it looks fishy just pick a reasonable
1107 // value.
1108 if (subRunsSizeHint < 0 || (1 << 16) < subRunsSizeHint) {
1109 subRunsSizeHint = 128;
1110 }
1111 return subRunsSizeHint;
1112 }
1113
1114 void SubRunContainer::flattenRuns(SkWriteBuffer& buffer) const {
1115 buffer.writeMatrix(fInitialPositionMatrix);
1116 int subRunCount = 0;
1117 for ([[maybe_unused]] auto& subRun : fSubRuns) {
1118 subRunCount += 1;
1119 }
1120 buffer.writeInt(subRunCount);
1121 for (auto& subRun : fSubRuns) {
1122 subRun.flatten(buffer);
1123 }
1124 }
1125
1126 SubRunContainerOwner SubRunContainer::MakeFromBufferInAlloc(SkReadBuffer& buffer,
1127 const SkStrikeClient* client,
1128 SubRunAllocator* alloc) {
1129 SkMatrix positionMatrix;
1130 buffer.readMatrix(&positionMatrix);
1131 if (!buffer.isValid()) { return nullptr; }
1132 SubRunContainerOwner container = alloc->makeUnique<SubRunContainer>(positionMatrix);
1133
1134 int subRunCount = buffer.readInt();
1135 if (!buffer.validate(subRunCount > 0)) { return nullptr; }
1136 for (int i = 0; i < subRunCount; ++i) {
1137 auto subRunOwner = SubRun::MakeFromBuffer(buffer, alloc, client);
1138 if (!buffer.validate(subRunOwner != nullptr)) { return nullptr; }
1139 if (subRunOwner != nullptr) {
1140 container->fSubRuns.append(std::move(subRunOwner));
1141 }
1142 }
1143 return container;
1144 }
1145
1146 size_t SubRunContainer::EstimateAllocSize(const GlyphRunList& glyphRunList) {
1147 // The difference in alignment from the per-glyph data to the SubRun;
1148 constexpr size_t alignDiff = alignof(DirectMaskSubRun) - alignof(SkPoint);
1149 constexpr size_t vertexDataToSubRunPadding = alignDiff > 0 ? alignDiff : 0;
1150 size_t totalGlyphCount = glyphRunList.totalGlyphCount();
1151 // This is optimized for DirectMaskSubRun which is by far the most common case.
1152 return totalGlyphCount * sizeof(SkPoint)
1153 + GlyphVector::GlyphVectorSize(totalGlyphCount)
1154 + glyphRunList.runCount() * (sizeof(DirectMaskSubRun) + vertexDataToSubRunPadding)
1155 + sizeof(SubRunContainer);
1156 }
1157
1158 SkScalar find_maximum_glyph_dimension(StrikeForGPU* strike, SkSpan<const SkGlyphID> glyphs) {
1159 StrikeMutationMonitor m{strike};
1160 SkScalar maxDimension = 0;
1161 for (SkGlyphID glyphID : glyphs) {
1162 SkGlyphDigest digest = strike->digestFor(kMask, SkPackedGlyphID{glyphID});
1163 maxDimension = std::max(static_cast<SkScalar>(digest.maxDimension()), maxDimension);
1164 }
1165
1166 return maxDimension;
1167 }
1168
1169 #if !defined(SK_DISABLE_SDF_TEXT)
1170 std::tuple<SkZip<const SkPackedGlyphID, const SkPoint>, SkZip<SkGlyphID, SkPoint>, SkRect>
1171 prepare_for_SDFT_drawing(StrikeForGPU* strike,
1172 const SkMatrix& creationMatrix,
1173 SkZip<const SkGlyphID, const SkPoint> source,
1174 SkZip<SkPackedGlyphID, SkPoint> acceptedBuffer,
1175 SkZip<SkGlyphID, SkPoint> rejectedBuffer) {
1176 int acceptedSize = 0,
1177 rejectedSize = 0;
1178 SkGlyphRect boundingRect = skglyph::empty_rect();
1179 StrikeMutationMonitor m{strike};
1180 for (const auto [glyphID, pos] : source) {
1181 if (!SkIsFinite(pos.x(), pos.y())) {
1182 continue;
1183 }
1184
1185 const SkPackedGlyphID packedID{glyphID};
1186 switch (const SkGlyphDigest digest = strike->digestFor(skglyph::kSDFT, packedID);
1187 digest.actionFor(skglyph::kSDFT)) {
1188 case GlyphAction::kAccept: {
1189 SkPoint mappedPos = creationMatrix.mapPoint(pos);
1190 const SkGlyphRect glyphBounds =
1191 glyph_bounds(digest, SDFTSubRun::kGlyphInsetting, mappedPos);
1192 boundingRect = skglyph::rect_union(boundingRect, glyphBounds);
1193 acceptedBuffer[acceptedSize++] = std::make_tuple(packedID, glyphBounds.leftTop());
1194 break;
1195 }
1196 case GlyphAction::kReject:
1197 rejectedBuffer[rejectedSize++] = std::make_tuple(glyphID, pos);
1198 break;
1199 default:
1200 break;
1201 }
1202 }
1203
1204 return {acceptedBuffer.first(acceptedSize),
1205 rejectedBuffer.first(rejectedSize),
1206 boundingRect.rect()};
1207 }
1208 #endif
1209
1210 std::tuple<SkZip<const SkPackedGlyphID, const SkPoint, const SkMask::Format>,
1211 SkZip<SkGlyphID, SkPoint>,
1212 SkRect>
1213 prepare_for_direct_mask_drawing(StrikeForGPU* strike,
1214 const SkMatrix& positionMatrix,
1215 SkZip<const SkGlyphID, const SkPoint> source,
1216 SkZip<SkPackedGlyphID, SkPoint, SkMask::Format> acceptedBuffer,
1217 SkZip<SkGlyphID, SkPoint> rejectedBuffer) {
1218 const SkIPoint mask = strike->roundingSpec().ignorePositionFieldMask;
1219 const SkPoint halfSampleFreq = strike->roundingSpec().halfAxisSampleFreq;
1220
1221 // Build up the mapping from source space to device space. Add the rounding constant
1222 // halfSampleFreq, so we just need to floor to get the device result.
1223 SkMatrix positionMatrixWithRounding = positionMatrix;
1224 positionMatrixWithRounding.postTranslate(halfSampleFreq.x(), halfSampleFreq.y());
1225
1226 int acceptedSize = 0,
1227 rejectedSize = 0;
1228 SkGlyphRect boundingRect = skglyph::empty_rect();
1229 StrikeMutationMonitor m{strike};
1230 for (auto [glyphID, pos] : source) {
1231 if (!SkIsFinite(pos.x(), pos.y())) {
1232 continue;
1233 }
1234
1235 const SkPoint mappedPos = positionMatrixWithRounding.mapPoint(pos);
1236 const SkPackedGlyphID packedID{glyphID, mappedPos, mask};
1237 switch (const SkGlyphDigest digest = strike->digestFor(skglyph::kDirectMask, packedID);
1238 digest.actionFor(skglyph::kDirectMask)) {
1239 case GlyphAction::kAccept: {
1240 const SkPoint roundedPos{SkScalarFloorToScalar(mappedPos.x()),
1241 SkScalarFloorToScalar(mappedPos.y())};
1242 const SkGlyphRect glyphBounds = glyph_bounds(digest,
1243 DirectMaskSubRun::kGlyphInsetting,
1244 roundedPos);
1245 boundingRect = skglyph::rect_union(boundingRect, glyphBounds);
1246 acceptedBuffer[acceptedSize++] =
1247 std::make_tuple(packedID, glyphBounds.leftTop(), digest.maskFormat());
1248 break;
1249 }
1250 case GlyphAction::kReject:
1251 rejectedBuffer[rejectedSize++] = std::make_tuple(glyphID, pos);
1252 break;
1253 default:
1254 break;
1255 }
1256 }
1257
1258 return {acceptedBuffer.first(acceptedSize),
1259 rejectedBuffer.first(rejectedSize),
1260 boundingRect.rect()};
1261 }
1262
1263 std::tuple<SkZip<const SkPackedGlyphID, const SkPoint, const SkMask::Format>,
1264 SkZip<SkGlyphID, SkPoint>,
1265 SkRect>
1266 prepare_for_mask_drawing(StrikeForGPU* strike,
1267 const SkMatrix& creationMatrix,
1268 SkZip<const SkGlyphID, const SkPoint> source,
1269 SkZip<SkPackedGlyphID, SkPoint, SkMask::Format> acceptedBuffer,
1270 SkZip<SkGlyphID, SkPoint> rejectedBuffer) {
1271 int acceptedSize = 0,
1272 rejectedSize = 0;
1273 SkGlyphRect boundingRect = skglyph::empty_rect();
1274 StrikeMutationMonitor m{strike};
1275 for (auto [glyphID, pos] : source) {
1276 if (!SkIsFinite(pos.x(), pos.y())) {
1277 continue;
1278 }
1279
1280 const SkPackedGlyphID packedID{glyphID};
1281 switch (const SkGlyphDigest digest = strike->digestFor(kMask, packedID);
1282 digest.actionFor(kMask)) {
1283 case GlyphAction::kAccept: {
1284 const SkPoint mappedPos = creationMatrix.mapPoint(pos);
1285 const SkGlyphRect glyphBounds =
1286 glyph_bounds(digest, TransformedMaskSubRun::kGlyphInsetting, mappedPos);
1287 boundingRect = skglyph::rect_union(boundingRect, glyphBounds);
1288 acceptedBuffer[acceptedSize++] =
1289 std::make_tuple(packedID, glyphBounds.leftTop(), digest.maskFormat());
1290 break;
1291 }
1292 case GlyphAction::kReject:
1293 rejectedBuffer[rejectedSize++] = std::make_tuple(glyphID, pos);
1294 break;
1295 default:
1296 break;
1297 }
1298 }
1299
1300 return {acceptedBuffer.first(acceptedSize),
1301 rejectedBuffer.first(rejectedSize),
1302 boundingRect.rect()};
1303 }
1304
1305 std::tuple<SkZip<const SkGlyphID, const SkPoint>, SkZip<SkGlyphID, SkPoint>>
1306 prepare_for_path_drawing(StrikeForGPU* strike,
1307 SkZip<const SkGlyphID, const SkPoint> source,
1308 SkZip<SkGlyphID, SkPoint> acceptedBuffer,
1309 SkZip<SkGlyphID, SkPoint> rejectedBuffer) {
1310 int acceptedSize = 0;
1311 int rejectedSize = 0;
1312 StrikeMutationMonitor m{strike};
1313 for (const auto [glyphID, pos] : source) {
1314 if (!SkIsFinite(pos.x(), pos.y())) {
1315 continue;
1316 }
1317
1318 switch (strike->digestFor(skglyph::kPath, SkPackedGlyphID{glyphID})
1319 .actionFor(skglyph::kPath)) {
1320 case GlyphAction::kAccept:
1321 acceptedBuffer[acceptedSize++] = std::make_tuple(glyphID, pos);
1322 break;
1323 case GlyphAction::kReject:
1324 rejectedBuffer[rejectedSize++] = std::make_tuple(glyphID, pos);
1325 break;
1326 default:
1327 break;
1328 }
1329 }
1330 return {acceptedBuffer.first(acceptedSize), rejectedBuffer.first(rejectedSize)};
1331 }
1332
1333 std::tuple<SkZip<const SkGlyphID, const SkPoint>, SkZip<SkGlyphID, SkPoint>>
1334 prepare_for_drawable_drawing(StrikeForGPU* strike,
1335 SkZip<const SkGlyphID, const SkPoint> source,
1336 SkZip<SkGlyphID, SkPoint> acceptedBuffer,
1337 SkZip<SkGlyphID, SkPoint> rejectedBuffer) {
1338 int acceptedSize = 0;
1339 int rejectedSize = 0;
1340 StrikeMutationMonitor m{strike};
1341 for (const auto [glyphID, pos] : source) {
1342 if (!SkIsFinite(pos.x(), pos.y())) {
1343 continue;
1344 }
1345
1346 switch (strike->digestFor(skglyph::kDrawable, SkPackedGlyphID{glyphID})
1347 .actionFor(skglyph::kDrawable)) {
1348 case GlyphAction::kAccept:
1349 acceptedBuffer[acceptedSize++] = std::make_tuple(glyphID, pos);
1350 break;
1351 case GlyphAction::kReject:
1352 rejectedBuffer[rejectedSize++] = std::make_tuple(glyphID, pos);
1353 break;
1354 default:
1355 break;
1356 }
1357 }
1358 return {acceptedBuffer.first(acceptedSize), rejectedBuffer.first(rejectedSize)};
1359 }
1360
1361 #if !defined(SK_DISABLE_SDF_TEXT)
1362 static std::tuple<SkStrikeSpec, SkScalar, sktext::gpu::SDFTMatrixRange>
1363 make_sdft_strike_spec(const SkFont& font, const SkPaint& paint,
1364 const SkSurfaceProps& surfaceProps, const SkMatrix& deviceMatrix,
1365 const SkPoint& textLocation, const sktext::gpu::SubRunControl& control) {
1366 // Add filter to the paint which creates the SDFT data for A8 masks.
1367 SkPaint dfPaint{paint};
1368 dfPaint.setMaskFilter(sktext::gpu::SDFMaskFilter::Make());
1369
1370 auto [dfFont, strikeToSourceScale, matrixRange] = control.getSDFFont(font, deviceMatrix,
1371 textLocation);
1372
1373 // Adjust the stroke width by the scale factor for drawing the SDFT.
1374 dfPaint.setStrokeWidth(paint.getStrokeWidth() / strikeToSourceScale);
1375
1376 // Check for dashing and adjust the intervals.
1377 if (SkPathEffect* pathEffect = paint.getPathEffect(); pathEffect != nullptr) {
1378 if (auto info = as_PEB(pathEffect)->asADash()) {
1379 SkSpan<const SkScalar> src = info->fIntervals;
1380 SkASSERT(src.size() > 1);
1381 // Allocate the intervals.
1382 std::vector<SkScalar> scaledIntervals(src.size());
1383 for (size_t i = 0; i < src.size(); ++i) {
1384 scaledIntervals[i] = src[i] / strikeToSourceScale;
1385 }
1386 auto scaledDashes = SkDashPathEffect::Make(scaledIntervals,
1387 info->fPhase / strikeToSourceScale);
1388 dfPaint.setPathEffect(scaledDashes);
1389 }
1390 }
1391
1392 // Fake-gamma and subpixel antialiasing are applied in the shader, so we ignore the
1393 // passed-in scaler context flags. (It's only used when we fall-back to bitmap text).
1394 SkScalerContextFlags flags = SkScalerContextFlags::kNone;
1395 SkStrikeSpec strikeSpec = SkStrikeSpec::MakeMask(dfFont, dfPaint, surfaceProps, flags,
1396 SkMatrix::I());
1397
1398 return std::make_tuple(std::move(strikeSpec), strikeToSourceScale, matrixRange);
1399 }
1400 #endif
1401
1402 SubRunContainerOwner SubRunContainer::MakeInAlloc(
1403 const GlyphRunList& glyphRunList,
1404 const SkMatrix& positionMatrix,
1405 const SkPaint& runPaint,
1406 SkStrikeDeviceInfo strikeDeviceInfo,
1407 StrikeForGPUCacheInterface* strikeCache,
1408 SubRunAllocator* alloc,
1409 SubRunCreationBehavior creationBehavior,
1410 const char* tag) {
1411 SkASSERT(alloc != nullptr);
1412 SkASSERT(strikeDeviceInfo.fSubRunControl != nullptr);
1413
1414 SubRunContainerOwner container = alloc->makeUnique<SubRunContainer>(positionMatrix);
1415 // If there is no SubRunControl description ignore all SubRuns.
1416 if (strikeDeviceInfo.fSubRunControl == nullptr) {
1417 return container;
1418 }
1419
1420 const SkSurfaceProps deviceProps = strikeDeviceInfo.fSurfaceProps;
1421 const SkScalerContextFlags scalerContextFlags = strikeDeviceInfo.fScalerContextFlags;
1422 const SubRunControl* subRunControl = strikeDeviceInfo.fSubRunControl;
1423 #if !defined(SK_DISABLE_SDF_TEXT)
1424 const SkScalar maxMaskSize = subRunControl->maxSize();
1425 #else
1426 const SkScalar maxMaskSize = 256;
1427 #endif
1428
1429 // TODO: hoist the buffer structure to the GlyphRunBuilder. The buffer structure here is
1430 // still begin tuned, and this is expected to be slower until tuned.
1431 const int maxGlyphRunSize = glyphRunList.maxGlyphRunSize();
1432
1433 // Accepted buffers.
1434 STArray<64, SkPackedGlyphID> acceptedPackedGlyphIDs;
1435 STArray<64, SkGlyphID> acceptedGlyphIDs;
1436 STArray<64, SkPoint> acceptedPositions;
1437 STArray<64, SkMask::Format> acceptedFormats;
1438 acceptedPackedGlyphIDs.resize(maxGlyphRunSize);
1439 acceptedGlyphIDs.resize(maxGlyphRunSize);
1440 acceptedPositions.resize(maxGlyphRunSize);
1441 acceptedFormats.resize(maxGlyphRunSize);
1442
1443 // Rejected buffers.
1444 STArray<64, SkGlyphID> rejectedGlyphIDs;
1445 STArray<64, SkPoint> rejectedPositions;
1446 rejectedGlyphIDs.resize(maxGlyphRunSize);
1447 rejectedPositions.resize(maxGlyphRunSize);
1448 const auto rejectedBuffer = SkMakeZip(rejectedGlyphIDs, rejectedPositions);
1449
1450 const SkPoint glyphRunListLocation = glyphRunList.sourceBounds().center();
1451
1452 // Handle all the runs in the glyphRunList
1453 for (auto& glyphRun : glyphRunList) {
1454 SkZip<const SkGlyphID, const SkPoint> source = glyphRun.source();
1455 const SkFont& runFont = glyphRun.font();
1456
1457 const SkScalar approximateDeviceTextSize =
1458 // Since the positionMatrix has the origin prepended, use the plain
1459 // sourceBounds from above.
1460 SkFontPriv::ApproximateTransformedTextSize(runFont, positionMatrix,
1461 glyphRunListLocation);
1462
1463 // Atlas mask cases - SDFT and direct mask
1464 // Only consider using direct or SDFT drawing if not drawing hairlines and not too big.
1465 if ((runPaint.getStyle() != SkPaint::kStroke_Style || runPaint.getStrokeWidth() != 0) &&
1466 approximateDeviceTextSize < maxMaskSize) {
1467
1468 #if !defined(SK_DISABLE_SDF_TEXT)
1469 // SDFT case
1470 if (subRunControl->isSDFT(approximateDeviceTextSize, runPaint, positionMatrix)) {
1471 // Process SDFT - This should be the .009% case.
1472 const auto& [strikeSpec, strikeToSourceScale, matrixRange] =
1473 make_sdft_strike_spec(
1474 runFont, runPaint, deviceProps, positionMatrix,
1475 glyphRunListLocation, *subRunControl);
1476
1477 if (!SkScalarNearlyZero(strikeToSourceScale)) {
1478 sk_sp<StrikeForGPU> strike = strikeSpec.findOrCreateScopedStrike(strikeCache);
1479
1480 // The creationMatrix needs to scale the strike data when inverted and
1481 // multiplied by the positionMatrix. The final CTM should be:
1482 // [positionMatrix][scale by strikeToSourceScale],
1483 // which should equal the following because of the transform during the vertex
1484 // calculation,
1485 // [positionMatrix][creationMatrix]^-1.
1486 // So, the creation matrix needs to be
1487 // [scale by 1/strikeToSourceScale].
1488 SkMatrix creationMatrix =
1489 SkMatrix::Scale(1.f/strikeToSourceScale, 1.f/strikeToSourceScale);
1490
1491 auto acceptedBuffer = SkMakeZip(acceptedPackedGlyphIDs, acceptedPositions);
1492 auto [accepted, rejected, creationBounds] = prepare_for_SDFT_drawing(
1493 strike.get(), creationMatrix, source, acceptedBuffer, rejectedBuffer);
1494 source = rejected;
1495
1496 if (creationBehavior == kAddSubRuns && !accepted.empty()) {
1497 container->fSubRuns.append(SDFTSubRun::Make(
1498 accepted,
1499 runFont,
1500 strike->strikePromise(),
1501 creationMatrix,
1502 creationBounds,
1503 matrixRange,
1504 alloc));
1505 }
1506 }
1507 }
1508 #endif // !defined(SK_DISABLE_SDF_TEXT)
1509 // Mask filters with 3D format (e.g. EmbossMaskFilter) need to be drawn as a path
1510 // in order to apply the filter through the Canvas AutoLayer system.
1511 const bool needsAutoLayer = runPaint.getMaskFilter() &&
1512 as_MFB(runPaint.getMaskFilter())->getFormat() == SkMask::k3D_Format;
1513 // Direct Mask case
1514 // Handle all the directly mapped mask subruns.
1515 if (!source.empty() && !positionMatrix.hasPerspective() && !needsAutoLayer) {
1516 // Process masks including ARGB - this should be the 99.99% case.
1517 // This will handle medium size emoji that are sharing the run with SDFT drawn text.
1518 // If things are too big they will be passed along to the drawing of last resort
1519 // below.
1520 SkStrikeSpec strikeSpec = SkStrikeSpec::MakeMask(
1521 runFont, runPaint, deviceProps, scalerContextFlags, positionMatrix);
1522
1523 sk_sp<StrikeForGPU> strike = strikeSpec.findOrCreateScopedStrike(strikeCache);
1524
1525 auto acceptedBuffer = SkMakeZip(acceptedPackedGlyphIDs,
1526 acceptedPositions,
1527 acceptedFormats);
1528 auto [accepted, rejected, creationBounds] = prepare_for_direct_mask_drawing(
1529 strike.get(), positionMatrix, source, acceptedBuffer, rejectedBuffer);
1530 source = rejected;
1531
1532 if (creationBehavior == kAddSubRuns && !accepted.empty()) {
1533 auto addGlyphsWithSameFormat =
1534 [&, bounds = creationBounds](
1535 SkZip<const SkPackedGlyphID, const SkPoint> subrun,
1536 MaskFormat format) {
1537 container->fSubRuns.append(
1538 DirectMaskSubRun::Make(bounds,
1539 subrun,
1540 container->initialPosition(),
1541 strike->strikePromise(),
1542 format,
1543 alloc));
1544 };
1545 add_multi_mask_format(addGlyphsWithSameFormat, accepted);
1546 }
1547 }
1548 }
1549
1550 // Drawable case
1551 // Handle all the drawable glyphs - usually large or perspective color glyphs.
1552 if (!source.empty()) {
1553 auto [strikeSpec, strikeToSourceScale] =
1554 SkStrikeSpec::MakePath(runFont, runPaint, deviceProps, scalerContextFlags);
1555
1556 if (!SkScalarNearlyZero(strikeToSourceScale)) {
1557 sk_sp<StrikeForGPU> strike = strikeSpec.findOrCreateScopedStrike(strikeCache);
1558
1559 auto acceptedBuffer = SkMakeZip(acceptedGlyphIDs, acceptedPositions);
1560 auto [accepted, rejected] =
1561 prepare_for_drawable_drawing(strike.get(), source, acceptedBuffer, rejectedBuffer);
1562 source = rejected;
1563
1564 if (creationBehavior == kAddSubRuns && !accepted.empty()) {
1565 container->fSubRuns.append(
1566 DrawableSubRun::Make(
1567 accepted,
1568 strikeToSourceScale,
1569 strike->strikePromise(),
1570 alloc));
1571 }
1572 }
1573 }
1574
1575 // Path case
1576 // Handle path subruns. Mainly, large or large perspective glyphs with no color.
1577 if (!source.empty()) {
1578 auto [strikeSpec, strikeToSourceScale] =
1579 SkStrikeSpec::MakePath(runFont, runPaint, deviceProps, scalerContextFlags);
1580
1581 if (!SkScalarNearlyZero(strikeToSourceScale)) {
1582 sk_sp<StrikeForGPU> strike = strikeSpec.findOrCreateScopedStrike(strikeCache);
1583
1584 auto acceptedBuffer = SkMakeZip(acceptedGlyphIDs, acceptedPositions);
1585 auto [accepted, rejected] =
1586 prepare_for_path_drawing(strike.get(), source, acceptedBuffer, rejectedBuffer);
1587 source = rejected;
1588
1589 if (creationBehavior == kAddSubRuns && !accepted.empty()) {
1590 const bool isAntiAliased =
1591 subRunControl->forcePathAA() || has_some_antialiasing(runFont);
1592 container->fSubRuns.append(
1593 PathSubRun::Make(accepted,
1594 isAntiAliased,
1595 strikeToSourceScale,
1596 strike->strikePromise(),
1597 alloc));
1598 }
1599 }
1600 }
1601
1602 // Drawing of last resort case
1603 // Draw all the rest of the rejected glyphs from above. This scales out of the atlas to
1604 // the screen, so quality will suffer. This mainly handles large color or perspective
1605 // color not handled by Drawables.
1606 if (!source.empty() && !SkScalarNearlyZero(approximateDeviceTextSize)) {
1607 // Creation matrix will be changed below to meet the following criteria:
1608 // * No perspective - the font scaler and the strikes can't handle perspective masks.
1609 // * Fits atlas - creationMatrix will be conditioned so that the maximum glyph
1610 // dimension for this run will be < kMaxBilerpAtlasDimension.
1611 SkMatrix creationMatrix = positionMatrix;
1612
1613 // Condition creationMatrix for perspective.
1614 if (creationMatrix.hasPerspective()) {
1615 // Find a scale factor that reduces pixelation caused by keystoning.
1616 SkPoint center = glyphRunList.sourceBounds().center();
1617 SkScalar maxAreaScale = SkMatrixPriv::DifferentialAreaScale(creationMatrix, center);
1618 SkScalar perspectiveFactor = 1;
1619 if (SkIsFinite(maxAreaScale) && !SkScalarNearlyZero(maxAreaScale)) {
1620 perspectiveFactor = SkScalarSqrt(maxAreaScale);
1621 }
1622
1623 // Masks can not be created in perspective. Create a non-perspective font with a
1624 // scale that will support the perspective keystoning.
1625 creationMatrix = SkMatrix::Scale(perspectiveFactor, perspectiveFactor);
1626 }
1627
1628 // Reduce to make a one pixel border for the bilerp padding.
1629 static const constexpr SkScalar kMaxBilerpAtlasDimension =
1630 SkGlyphDigest::kSkSideTooBigForAtlas - 2;
1631
1632 // Get the raw glyph IDs to simulate device drawing to figure the maximum device
1633 // dimension.
1634 const SkSpan<const SkGlyphID> glyphs = get_glyphIDs(source);
1635
1636 // maxGlyphDimension always returns an integer even though the return type is SkScalar.
1637 auto maxGlyphDimension = [&](const SkMatrix& m) {
1638 const SkStrikeSpec strikeSpec = SkStrikeSpec::MakeTransformMask(
1639 runFont, runPaint, deviceProps, scalerContextFlags, m);
1640 const sk_sp<StrikeForGPU> gaugingStrike =
1641 strikeSpec.findOrCreateScopedStrike(strikeCache);
1642 const SkScalar maxDimension =
1643 find_maximum_glyph_dimension(gaugingStrike.get(), glyphs);
1644 // TODO: There is a problem where a small character (say .) and a large
1645 // character (say M) are in the same run. If the run is scaled to be very
1646 // large, then the M may return 0 because its dimensions are > 65535, but
1647 // the small character produces regular result because its largest dimension
1648 // is < 65535. This will create an improper scale factor causing the M to be
1649 // too large to fit in the atlas. Tracked by skbug.com/40044801.
1650 return maxDimension;
1651 };
1652
1653 // Condition the creationMatrix so that glyphs fit in the atlas.
1654 for (SkScalar maxDimension = maxGlyphDimension(creationMatrix);
1655 kMaxBilerpAtlasDimension < maxDimension;
1656 maxDimension = maxGlyphDimension(creationMatrix))
1657 {
1658 // The SkScalerContext has a limit of 65536 maximum dimension.
1659 // reductionFactor will always be < 1 because
1660 // maxDimension > kMaxBilerpAtlasDimension, and because maxDimension will always
1661 // be an integer the reduction factor will always be at most 254 / 255.
1662 SkScalar reductionFactor = kMaxBilerpAtlasDimension / maxDimension;
1663 creationMatrix.postScale(reductionFactor, reductionFactor);
1664 }
1665
1666 // Draw using the creationMatrix.
1667 SkStrikeSpec strikeSpec = SkStrikeSpec::MakeTransformMask(
1668 runFont, runPaint, deviceProps, scalerContextFlags, creationMatrix);
1669
1670 sk_sp<StrikeForGPU> strike = strikeSpec.findOrCreateScopedStrike(strikeCache);
1671
1672 auto acceptedBuffer =
1673 SkMakeZip(acceptedPackedGlyphIDs, acceptedPositions, acceptedFormats);
1674 auto [accepted, rejected, creationBounds] =
1675 prepare_for_mask_drawing(
1676 strike.get(), creationMatrix, source, acceptedBuffer, rejectedBuffer);
1677 source = rejected;
1678
1679 if (creationBehavior == kAddSubRuns && !accepted.empty()) {
1680
1681 auto addGlyphsWithSameFormat =
1682 [&, bounds = creationBounds](
1683 SkZip<const SkPackedGlyphID, const SkPoint> subrun,
1684 MaskFormat format) {
1685 container->fSubRuns.append(
1686 TransformedMaskSubRun::Make(subrun,
1687 container->initialPosition(),
1688 strike->strikePromise(),
1689 creationMatrix,
1690 bounds,
1691 format,
1692 alloc));
1693 };
1694 add_multi_mask_format(addGlyphsWithSameFormat, accepted);
1695 }
1696 }
1697 }
1698
1699 return container;
1700 }
1701
1702 void SubRunContainer::draw(SkCanvas* canvas,
1703 SkPoint drawOrigin,
1704 const SkPaint& paint,
1705 const SkRefCnt* subRunStorage,
1706 const AtlasDrawDelegate& atlasDelegate) const {
1707 for (auto& subRun : fSubRuns) {
1708 subRun.draw(canvas, drawOrigin, paint, sk_ref_sp(subRunStorage), atlasDelegate);
1709 }
1710 }
1711
1712 bool SubRunContainer::canReuse(const SkPaint& paint, const SkMatrix& positionMatrix) const {
1713 for (const SubRun& subRun : fSubRuns) {
1714 if (!subRun.canReuse(paint, positionMatrix)) {
1715 return false;
1716 }
1717 }
1718 return true;
1719 }
1720
1721 } // namespace sktext::gpu