Debian Codegraph @

src/text/gpu/SubRunContainer.cpp

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