Debian Codegraph @

src/text/gpu/SubRunContainer.cpp

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