-
Notifications
You must be signed in to change notification settings - Fork 102
Expand file tree
/
Copy pathrender_context.cpp
More file actions
3290 lines (3000 loc) · 132 KB
/
render_context.cpp
File metadata and controls
3290 lines (3000 loc) · 132 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright 2022 Rive
*/
#include "rive/renderer/render_context.hpp"
#include "gr_inner_fan_triangulator.hpp"
#include "intersection_board.hpp"
#include "gradient.hpp"
#include "rive_render_paint.hpp"
#include "rive/renderer/draw.hpp"
#include "rive/renderer/rive_render_image.hpp"
#include "rive/renderer/render_context_impl.hpp"
#include "rive/profiler/profiler_macros.h"
#include "shaders/constants.glsl"
#include <string_view>
#ifdef RIVE_DECODERS
#include "rive/decoders/bitmap_decoder.hpp"
#endif
namespace rive::gpu
{
constexpr size_t kDefaultSimpleGradientCapacity = 512;
constexpr size_t kDefaultComplexGradientCapacity = 1024;
constexpr size_t kDefaultDrawCapacity = 2048;
// TODO: Move this variable to PlatformFeatures.
constexpr uint32_t kMaxTextureHeight = 2048;
constexpr size_t kMaxTessellationVertexCount =
kMaxTextureHeight * kTessTextureWidth;
constexpr size_t kMaxTessellationPaddingVertexCount =
gpu::kMidpointFanPatchSegmentSpan + // Padding at the beginning of the tess
// texture
(gpu::kOuterCurvePatchSegmentSpan -
1) + // Max padding between patch types in the tess texture
1; // Padding at the end of the tessellation texture
constexpr size_t kMaxTessellationVertexCountBeforePadding =
kMaxTessellationVertexCount - kMaxTessellationPaddingVertexCount;
// Metal requires vertex buffers to be 256-byte aligned.
constexpr size_t kMaxTessellationAlignmentVertices =
gpu::kTessVertexBufferAlignmentInElements - 1;
// We can only reorder 32767 draws at a time since the one-based groupIndex
// returned by IntersectionBoard is a signed 16-bit integer.
constexpr size_t kMaxReorderedDrawPassCount =
std::numeric_limits<int16_t>::max();
// How tall to make a resource texture in order to support the given number of
// items.
template <size_t WidthInItems>
constexpr static size_t resource_texture_height(size_t itemCount)
{
return (itemCount + WidthInItems - 1) / WidthInItems;
}
constexpr static size_t gradient_data_height(size_t simpleRampCount,
size_t complexRampCount)
{
return resource_texture_height<gpu::kGradTextureWidthInSimpleRamps>(
simpleRampCount) +
complexRampCount;
}
inline GradientContentKey::GradientContentKey(rcp<const Gradient> gradient) :
m_gradient(std::move(gradient))
{}
inline GradientContentKey::GradientContentKey(GradientContentKey&& other) :
m_gradient(std::move(other.m_gradient))
{}
bool GradientContentKey::operator==(const GradientContentKey& other) const
{
if (m_gradient.get() == other.m_gradient.get())
{
return true;
}
else
{
return m_gradient->count() == other.m_gradient->count() &&
!memcmp(m_gradient->stops(),
other.m_gradient->stops(),
m_gradient->count() * sizeof(float)) &&
!memcmp(m_gradient->colors(),
other.m_gradient->colors(),
m_gradient->count() * sizeof(ColorInt));
}
}
size_t DeepHashGradient::operator()(const GradientContentKey& key) const
{
const Gradient* grad = key.gradient();
std::hash<std::string_view> hash;
size_t x =
hash(std::string_view(reinterpret_cast<const char*>(grad->stops()),
grad->count() * sizeof(float)));
size_t y =
hash(std::string_view(reinterpret_cast<const char*>(grad->colors()),
grad->count() * sizeof(ColorInt)));
return x ^ y;
}
RenderContext::RenderContext(std::unique_ptr<RenderContextImpl> impl) :
m_impl(std::move(impl)),
// -1 from m_maxPathID so we reserve a path record for the clearColor paint
// (for atomic mode). This also allows us to index the storage buffers
// directly by pathID.
m_maxPathID(MaxPathID(m_impl->platformFeatures().pathIDGranularity) - 1)
{
setResourceSizes(ResourceAllocationCounts(), /*forceRealloc =*/true);
releaseResources();
}
RenderContext::~RenderContext()
{
// Always call flush() to avoid deadlock.
assert(!m_didBeginFrame);
// Delete the logical flushes before the block allocators let go of their
// allocations.
m_logicalFlushes.clear();
}
const gpu::PlatformFeatures& RenderContext::platformFeatures() const
{
return m_impl->platformFeatures();
}
rcp<RenderBuffer> RenderContext::makeRenderBuffer(RenderBufferType type,
RenderBufferFlags flags,
size_t sizeInBytes)
{
return m_impl->makeRenderBuffer(type, flags, sizeInBytes);
}
rcp<RenderImage> RenderContext::decodeImage(Span<const uint8_t> encodedBytes)
{
RIVE_PROF_SCOPE()
rcp<Texture> texture = m_impl->platformDecodeImageTexture(encodedBytes);
#ifdef RIVE_DECODERS
if (texture == nullptr)
{
auto bitmap = Bitmap::decode(encodedBytes.data(), encodedBytes.size());
if (bitmap)
{
// For now, RenderContextImpl::makeImageTexture() only accepts RGBA.
if (bitmap->pixelFormat() != Bitmap::PixelFormat::RGBAPremul)
{
bitmap->pixelFormat(Bitmap::PixelFormat::RGBAPremul);
}
uint32_t width = bitmap->width();
uint32_t height = bitmap->height();
uint32_t mipLevelCount = math::msb(height | width);
texture = m_impl->makeImageTexture(width,
height,
mipLevelCount,
bitmap->bytes());
}
}
#endif
return texture != nullptr ? make_rcp<RiveRenderImage>(std::move(texture))
: nullptr;
}
void RenderContext::releaseResources()
{
assert(!m_didBeginFrame);
resetContainers();
setResourceSizes(ResourceAllocationCounts());
m_maxRecentResourceRequirements = ResourceAllocationCounts();
m_lastResourceTrimTimeInSeconds = m_impl->secondsNow();
}
void RenderContext::resetContainers()
{
assert(!m_didBeginFrame);
if (!m_logicalFlushes.empty())
{
// Should get reset to 1 after flush().
assert(m_logicalFlushes.size() == 1);
m_logicalFlushes.resize(1);
m_logicalFlushes.front()->resetContainers();
}
m_indirectDrawList.clear();
m_indirectDrawList.shrink_to_fit();
m_intersectionBoard = nullptr;
}
RenderContext::LogicalFlush::LogicalFlush(RenderContext* parent) : m_ctx(parent)
{
rewind();
}
void RenderContext::LogicalFlush::rewind()
{
RIVE_PROF_SCOPE()
m_resourceCounts = Draw::ResourceCounters();
m_drawPassCount = 0;
m_simpleGradients.clear();
m_pendingSimpleGradDraws.clear();
m_complexGradients.clear();
m_pendingComplexGradDraws.clear();
m_pendingGradSpanCount = 0;
m_clips.clear();
m_draws.clear();
m_combinedDrawBounds = {std::numeric_limits<int32_t>::max(),
std::numeric_limits<int32_t>::max(),
std::numeric_limits<int32_t>::min(),
std::numeric_limits<int32_t>::min()};
m_combinedDrawContents = gpu::DrawContents::none;
m_pathPaddingCount = 0;
m_paintPaddingCount = 0;
m_paintAuxPaddingCount = 0;
m_contourPaddingCount = 0;
m_gradSpanPaddingCount = 0;
m_midpointFanTessEndLocation = 0;
m_outerCubicTessEndLocation = 0;
m_outerCubicTessVertexIdx = 0;
m_midpointFanTessVertexIdx = 0;
m_baselineShaderMiscFlags = gpu::ShaderMiscFlags::none;
m_flushDesc = FlushDescriptor();
m_drawList.reset();
m_firstDstBlendBarrier = nullptr;
m_dstBlendBarrierListTail = &m_firstDstBlendBarrier;
m_combinedShaderFeatures = gpu::ShaderFeatures::NONE;
m_currentPathID = 0;
m_currentContourID = 0;
if (m_atlasRectanizer != nullptr)
{
m_atlasRectanizer->reset();
}
m_atlasMaxX = 0;
m_atlasMaxY = 0;
m_pendingAtlasDraws.clear();
m_coverageBufferLength = 0;
m_pendingBarriers = BarrierFlags::none;
m_currentZIndex = 0;
RIVE_DEBUG_CODE(m_hasDoneLayout = false;)
}
void RenderContext::LogicalFlush::resetContainers()
{
m_clips.clear();
m_clips.shrink_to_fit();
m_draws.clear();
m_draws.shrink_to_fit();
m_draws.reserve(kDefaultDrawCapacity);
m_simpleGradients.rehash(0);
m_simpleGradients.reserve(kDefaultSimpleGradientCapacity);
m_pendingSimpleGradDraws.clear();
m_pendingSimpleGradDraws.shrink_to_fit();
m_pendingSimpleGradDraws.reserve(kDefaultSimpleGradientCapacity);
m_complexGradients.rehash(0);
m_complexGradients.reserve(kDefaultComplexGradientCapacity);
m_pendingComplexGradDraws.clear();
m_pendingComplexGradDraws.shrink_to_fit();
m_pendingComplexGradDraws.reserve(kDefaultComplexGradientCapacity);
m_pendingAtlasDraws.clear();
m_pendingAtlasDraws.shrink_to_fit();
// Don't reserve any space in m_pendingAtlasDraws since there are many
// usecases where it isn't used at all.
}
static gpu::InterlockMode select_interlock_mode(
const RenderContext::FrameDescriptor& frameDescriptor,
const gpu::PlatformFeatures& platformFeatures)
{
if (frameDescriptor.msaaSampleCount != 0)
{
return gpu::InterlockMode::msaa;
}
if (frameDescriptor.clockwiseFillOverride)
{
if (platformFeatures.supportsClockwiseMode &&
!frameDescriptor.disableRasterOrdering)
{
return gpu::InterlockMode::clockwise;
}
if (platformFeatures.supportsClockwiseAtomicMode)
{
return gpu::InterlockMode::clockwiseAtomic;
}
}
if (platformFeatures.supportsRasterOrderingMode &&
(!frameDescriptor.disableRasterOrdering ||
// Only respect "disableRasterOrdering" if we have atomic mode to fall
// back on.
// FIXME: This API can be improved.
!platformFeatures.supportsAtomicMode))
{
return gpu::InterlockMode::rasterOrdering;
}
if (platformFeatures.supportsAtomicMode)
{
return gpu::InterlockMode::atomics;
}
return gpu::InterlockMode::msaa;
}
void RenderContext::beginFrame(const FrameDescriptor& frameDescriptor)
{
RIVE_PROF_SCOPE()
m_impl->preBeginFrame(this);
assert(!m_didBeginFrame);
assert(frameDescriptor.renderTargetWidth > 0);
assert(frameDescriptor.renderTargetHeight > 0);
m_frameDescriptor = frameDescriptor;
m_frameInterlockMode =
select_interlock_mode(m_frameDescriptor, platformFeatures());
if (m_frameInterlockMode == gpu::InterlockMode::msaa &&
m_frameDescriptor.msaaSampleCount == 0)
{
// Use 4x MSAA if msaaSampleCount wasn't already specified.
m_frameDescriptor.msaaSampleCount = 4;
}
m_frameShaderFeaturesMask =
gpu::ShaderFeaturesMaskFor(m_frameInterlockMode);
if (m_logicalFlushes.empty())
{
m_logicalFlushes.emplace_back(new LogicalFlush(this));
}
RIVE_DEBUG_CODE(m_didBeginFrame = true);
}
bool RenderContext::isOutsideCurrentFrame(const IAABB& pixelBounds)
{
assert(m_didBeginFrame);
int4 bounds = simd::load4i(&pixelBounds);
auto renderTargetSize =
simd::cast<int32_t>(uint2{m_frameDescriptor.renderTargetWidth,
m_frameDescriptor.renderTargetHeight});
return simd::any(bounds.xy >= renderTargetSize || bounds.zw <= 0 ||
bounds.xy >= bounds.zw);
}
bool RenderContext::frameSupportsClipRects() const
{
assert(m_didBeginFrame);
return m_frameInterlockMode != gpu::InterlockMode::msaa ||
platformFeatures().supportsClipPlanes;
}
bool RenderContext::frameSupportsImagePaintForPaths() const
{
assert(m_didBeginFrame);
return m_frameInterlockMode != gpu::InterlockMode::atomics;
}
uint32_t RenderContext::generateClipID(const IAABB& contentBounds)
{
assert(m_didBeginFrame);
assert(!m_logicalFlushes.empty());
return m_logicalFlushes.back()->generateClipID(contentBounds);
}
uint32_t RenderContext::LogicalFlush::generateClipID(const IAABB& contentBounds)
{
if (m_clips.size() < m_ctx->m_maxPathID) // maxClipID == maxPathID.
{
m_clips.emplace_back(contentBounds);
assert(m_ctx->m_clipContentID != m_clips.size());
return math::lossless_numeric_cast<uint32_t>(m_clips.size());
}
return 0; // There are no available clip IDs. The caller should flush and
// try again.
}
RenderContext::LogicalFlush::ClipInfo& RenderContext::LogicalFlush::
getWritableClipInfo(uint32_t clipID)
{
assert(clipID > 0);
assert(clipID <= m_clips.size());
return m_clips[clipID - 1];
}
void RenderContext::LogicalFlush::addClipReadBounds(uint32_t clipID,
const IAABB& bounds)
{
assert(clipID > 0);
assert(clipID <= m_clips.size());
ClipInfo& clipInfo = getWritableClipInfo(clipID);
clipInfo.readBounds = clipInfo.readBounds.join(bounds);
}
bool RenderContext::pushDraws(DrawUniquePtr draws[], size_t drawCount)
{
assert(m_didBeginFrame);
assert(!m_logicalFlushes.empty());
return m_logicalFlushes.back()->pushDraws(draws, drawCount);
}
bool RenderContext::LogicalFlush::pushDraws(DrawUniquePtr draws[],
size_t drawCount)
{
RIVE_PROF_SCOPE()
assert(!m_hasDoneLayout);
PUSH_DISABLE_CLANG_SIMD_ABI_WARNING()
auto countsVector = m_resourceCounts.toVec();
for (size_t i = 0; i < drawCount; ++i)
{
assert(!draws[i]->pixelBounds().empty());
assert(m_ctx->frameSupportsClipRects() ||
draws[i]->clipRectInverseMatrix() == nullptr);
countsVector += draws[i]->resourceCounts().toVec();
}
POP_DISABLE_CLANG_SIMD_ABI_WARNING()
Draw::ResourceCounters countsWithNewBatch = countsVector;
// Textures and buffers have hard size limits. If the new batch doesn't fit
// within our constraints, the caller needs to flush and try again.
if (countsWithNewBatch.pathCount > m_ctx->m_maxPathID ||
countsWithNewBatch.contourCount > kMaxContourID ||
countsWithNewBatch.midpointFanTessVertexCount +
countsWithNewBatch.outerCubicTessVertexCount >
kMaxTessellationVertexCountBeforePadding)
{
return false;
}
// Allocate subpasses.
int passCountInBatch = 0;
for (size_t i = 0; i < drawCount; ++i)
{
draws[i]->countSubpasses();
assert(draws[i]->prepassCount() >= 0);
assert(draws[i]->subpassCount() >= 0);
assert(draws[i]->prepassCount() + draws[i]->subpassCount() >= 1);
passCountInBatch += draws[i]->prepassCount() + draws[i]->subpassCount();
}
// We can only reorder 32k draws at a time in atomic and msaa modes since
// the sort key addresses them with a signed 16-bit index. Make sure we
// don't exceed that limit.
if (m_ctx->frameInterlockMode() != gpu::InterlockMode::rasterOrdering &&
m_drawPassCount + passCountInBatch > kMaxReorderedDrawPassCount)
{
return false;
}
// Allocate final resources.
for (size_t i = 0; i < drawCount; ++i)
{
if (!draws[i]->allocateResources(this))
{
// The draw failed to allocate resources. Give up and let the caller
// flush and try again.
//
// FIXME: This works today, but the surrounding code could be
// modified to inadvertently leave a stale dangling reference to one
// of these draws in m_pendingAtlasDraws. This needs to be
// revisited.
return false;
}
}
for (size_t i = 0; i < drawCount; ++i)
{
m_draws.push_back(std::move(draws[i]));
m_combinedDrawBounds =
m_combinedDrawBounds.join(m_draws.back()->pixelBounds());
m_combinedDrawContents |= m_draws.back()->drawContents();
}
m_resourceCounts = countsWithNewBatch;
m_drawPassCount += passCountInBatch;
return true;
}
bool RenderContext::LogicalFlush::allocateGradient(
const Gradient* gradient,
gpu::ColorRampLocation* colorRampLocation)
{
RIVE_PROF_SCOPE()
assert(!m_hasDoneLayout);
const float* stops = gradient->stops();
size_t stopCount = gradient->count();
assert(stopCount > 0); // RiveRenderFactory guarantees this.
if (stopCount == 1 || (stopCount == 2 && stops[0] == 0 && stops[1] == 1))
{
// This is a simple gradient that can be implemented by a two-texel
// color ramp.
const ColorInt* colors = gradient->colors();
TwoTexelRamp colorRamp = {colors[0],
// Handle ramps with a single stop.
colors[std::min<size_t>(1, stopCount - 1)]};
uint64_t simpleKey;
static_assert(sizeof(simpleKey) == sizeof(ColorInt) * 2);
RIVE_INLINE_MEMCPY(&simpleKey, &colorRamp, sizeof(ColorInt) * 2);
uint32_t rampTexelsIdx;
auto iter = m_simpleGradients.find(simpleKey);
if (iter != m_simpleGradients.end())
{
// This gradient is already in the texture.
rampTexelsIdx = iter->second;
}
else
{
if (gradient_data_height(m_simpleGradients.size() + 1,
m_complexGradients.size()) >
kMaxTextureHeight)
{
// We ran out of rows in the gradient texture. Caller has to
// flush and try again.
return false;
}
rampTexelsIdx = math::lossless_numeric_cast<uint32_t>(
m_simpleGradients.size() * 2);
m_simpleGradients.insert({simpleKey, rampTexelsIdx});
m_pendingSimpleGradDraws.push_back(colorRamp);
// Simple gradients get uploaded to the GPU as a single GradientSpan
// instance.
++m_pendingGradSpanCount;
}
colorRampLocation->row = rampTexelsIdx / kGradTextureWidth;
colorRampLocation->col = rampTexelsIdx % kGradTextureWidth;
}
else
{
// This is a complex gradient. Render it to an entire row of the
// gradient texture.
GradientContentKey key(ref_rcp(gradient));
auto iter = m_complexGradients.find(key);
uint16_t row;
if (iter != m_complexGradients.end())
{
row = iter->second; // This gradient is already in the texture.
}
else
{
if (gradient_data_height(m_simpleGradients.size(),
m_complexGradients.size() + 1) >
kMaxTextureHeight)
{
// We ran out of rows in the gradient texture. Caller has to
// flush and try again.
return false;
}
row = static_cast<uint32_t>(m_complexGradients.size());
m_complexGradients.emplace(std::move(key), row);
m_pendingComplexGradDraws.push_back(gradient);
size_t spanCount = stopCount - 1;
m_pendingGradSpanCount += spanCount;
}
// Store the row relative to the first complex gradient for now.
// PaintData::set() will offset this value by the number of simple
// gradient rows once its final value is known.
colorRampLocation->row = row;
colorRampLocation->col = ColorRampLocation::kComplexGradientMarker;
}
return true;
}
bool RenderContext::LogicalFlush::allocateAtlasDraw(
PathDraw* pathDraw,
uint16_t drawWidth,
uint16_t drawHeight,
uint16_t desiredPadding,
uint16_t* x,
uint16_t* y,
TAABB<uint16_t>* paddedRegion)
{
RIVE_PROF_SCOPE()
if (m_atlasRectanizer == nullptr)
{
uint16_t atlasMaxSize = m_ctx->atlasMaxSize();
// Use an atlas larger than atlasMaxSize if it's too small for the
// request (meaning the render target is larger than atlasMaxSize).
m_atlasRectanizer = std::make_unique<rive::RectanizerSkyline>(
std::max(atlasMaxSize, drawWidth),
std::max(atlasMaxSize, drawHeight));
}
const uint16_t atlasMaxWidth = m_atlasRectanizer->width();
const uint16_t atlasMaxHeight = m_atlasRectanizer->height();
uint16_t paddedWidth =
std::min<uint16_t>(drawWidth + desiredPadding * 2, atlasMaxWidth);
uint16_t paddedHeight =
std::min<uint16_t>(drawHeight + desiredPadding * 2, atlasMaxHeight);
int16_t ix, iy;
if (!m_atlasRectanizer->addRect(paddedWidth, paddedHeight, &ix, &iy))
{
// Delete the rectanizer of it wasn't big enough for this path. It will
// be reallocated to a large enough size on the next call.
if (drawWidth > atlasMaxWidth || drawHeight > atlasMaxHeight)
{
m_atlasRectanizer = nullptr;
}
m_atlasRectanizer = nullptr;
return false;
}
assert(ix >= 0);
assert(iy >= 0);
assert(ix + paddedWidth <= atlasMaxWidth);
assert(iy + paddedHeight <= atlasMaxHeight);
*x = ix + (paddedWidth - drawWidth) / 2;
*y = iy + (paddedHeight - drawHeight) / 2;
*paddedRegion = {ix, iy, ix + paddedWidth, iy + paddedHeight};
assert((TAABB<uint16_t>{0, 0, atlasMaxWidth, atlasMaxHeight})
.contains(*paddedRegion));
m_atlasMaxX = std::max<uint32_t>(m_atlasMaxX, paddedRegion->right);
m_atlasMaxY = std::max<uint32_t>(m_atlasMaxY, paddedRegion->bottom);
assert(m_atlasMaxX <= atlasMaxWidth);
assert(m_atlasMaxY <= atlasMaxHeight);
m_pendingAtlasDraws.push_back(pathDraw);
return true;
}
size_t RenderContext::LogicalFlush::allocateCoverageBufferRange(size_t length)
{
RIVE_PROF_SCOPE()
assert(m_ctx->frameInterlockMode() == gpu::InterlockMode::clockwiseAtomic);
assert(length % (32 * 32) == 0u); // Allocations must support 32x32 tiles.
uint32_t offset = m_coverageBufferLength;
if (offset + length > m_ctx->platformFeatures().maxCoverageBufferLength)
{
return -1;
}
m_coverageBufferLength += length;
return offset;
}
void RenderContext::logicalFlush()
{
assert(m_didBeginFrame);
// Reset clipping state after every logical flush because the clip buffer is
// not preserved between render passes.
m_clipContentID = 0;
// Don't issue any GPU commands between logical flushes. Instead, build up a
// list of flushes that we will submit all at once at the end of the frame.
m_logicalFlushes.emplace_back(new LogicalFlush(this));
}
void RenderContext::flush(const FlushResources& flushResources)
{
RIVE_PROF_SCOPE()
assert(m_didBeginFrame);
assert(flushResources.renderTarget->width() ==
m_frameDescriptor.renderTargetWidth);
assert(flushResources.renderTarget->height() ==
m_frameDescriptor.renderTargetHeight);
m_clipContentID = 0;
// Layout this frame's resource buffers and textures.
LogicalFlush::ResourceCounters totalFrameResourceCounts;
LogicalFlush::LayoutCounters layoutCounts;
for (size_t i = 0; i < m_logicalFlushes.size(); ++i)
{
m_logicalFlushes[i]->layoutResources(flushResources,
i,
&totalFrameResourceCounts,
&layoutCounts);
}
// Determine the minimum required resource allocation sizes to service this
// flush.
const ResourceAllocationCounts resourceRequirements = {
.flushUniformBufferCount = m_logicalFlushes.size(),
.imageDrawUniformBufferCount = totalFrameResourceCounts.imageDrawCount,
.pathBufferCount =
totalFrameResourceCounts.pathCount + layoutCounts.pathPaddingCount,
.paintBufferCount =
totalFrameResourceCounts.pathCount + layoutCounts.paintPaddingCount,
.paintAuxBufferCount = totalFrameResourceCounts.pathCount +
layoutCounts.paintAuxPaddingCount,
.contourBufferCount = totalFrameResourceCounts.contourCount +
layoutCounts.contourPaddingCount,
.gradSpanBufferCount =
layoutCounts.gradSpanCount + layoutCounts.gradSpanPaddingCount,
.tessSpanBufferCount =
totalFrameResourceCounts.maxTessellatedSegmentCount,
.triangleVertexBufferCount =
totalFrameResourceCounts.maxTriangleVertexCount,
.gradTextureHeight = layoutCounts.maxGradTextureHeight,
.tessTextureHeight = layoutCounts.maxTessTextureHeight,
.atlasTextureWidth = layoutCounts.maxAtlasWidth,
.atlasTextureHeight = layoutCounts.maxAtlasHeight,
.plsTransientBackingWidth =
(layoutCounts.maxPLSTransientBackingPlaneCount > 0)
? static_cast<size_t>(m_frameDescriptor.renderTargetWidth)
: 0,
.plsTransientBackingHeight =
(layoutCounts.maxPLSTransientBackingPlaneCount > 0)
? static_cast<size_t>(m_frameDescriptor.renderTargetHeight)
: 0,
.plsTransientBackingPlaneCount =
layoutCounts.maxPLSTransientBackingPlaneCount,
.plsAtomicCoverageBackingWidth =
(frameInterlockMode() == gpu::InterlockMode::atomics)
? static_cast<size_t>(m_frameDescriptor.renderTargetWidth)
: 0,
.plsAtomicCoverageBackingHeight =
(frameInterlockMode() == gpu::InterlockMode::atomics)
? static_cast<size_t>(m_frameDescriptor.renderTargetHeight)
: 0,
.coverageBufferLength = layoutCounts.maxCoverageBufferLength,
};
// Ensure we're within hardware limits.
assert(resourceRequirements.gradTextureHeight <= kMaxTextureHeight);
assert(resourceRequirements.tessTextureHeight <= kMaxTextureHeight);
assert(resourceRequirements.atlasTextureWidth <= atlasMaxSize() ||
resourceRequirements.atlasTextureWidth <=
frameDescriptor().renderTargetWidth);
assert(resourceRequirements.atlasTextureHeight <= atlasMaxSize() ||
resourceRequirements.atlasTextureHeight <=
frameDescriptor().renderTargetHeight);
assert(resourceRequirements.plsTransientBackingWidth <=
m_frameDescriptor.renderTargetWidth);
assert(resourceRequirements.plsTransientBackingHeight <=
m_frameDescriptor.renderTargetHeight);
assert(resourceRequirements.coverageBufferLength <=
platformFeatures().maxCoverageBufferLength);
PUSH_DISABLE_CLANG_SIMD_ABI_WARNING()
// Track m_maxRecentResourceRequirements so we can trim GPU allocations when
// steady-state usage goes down.
m_maxRecentResourceRequirements = ResourceAllocationCounts::FromVec(
simd::max(resourceRequirements.toVec(),
m_maxRecentResourceRequirements.toVec()));
// Grow resources enough to handle this flush.
// If "allocs" already fits in our current allocations, then don't change
// them.
// If they don't fit, overallocate by the specified amount in order to
// create some slack for growth.
constexpr static ResourceAllocationCounts OVERALLOC_x4 = {
.flushUniformBufferCount = 5, // 125%
.imageDrawUniformBufferCount = 5, // 125%
.pathBufferCount = 5, // 125%
.paintBufferCount = 5, // 125%
.paintAuxBufferCount = 5, // 125%
.contourBufferCount = 5, // 125%
.gradSpanBufferCount = 5, // 125%
.tessSpanBufferCount = 5, // 125%
.triangleVertexBufferCount = 5, // 125%
.gradTextureHeight = 5, // 125%
.tessTextureHeight = 5, // 125%
.atlasTextureWidth = 5, // 125%
.atlasTextureHeight = 5, // 125%
.plsTransientBackingWidth = 4, // 100% (i.e., don't overallocate)
.plsTransientBackingHeight = 4, // 100% (i.e., don't overallocate)
.plsTransientBackingPlaneCount = 4, // 100% (i.e., don't overallocate)
.plsAtomicCoverageBackingWidth = 4, // 100% (i.e., don't overallocate)
.plsAtomicCoverageBackingHeight = 4, // 100% (i.e., don't overallocate)
.coverageBufferLength = 5, // 125%
};
ResourceAllocationCounts allocs =
ResourceAllocationCounts::FromVec(simd::if_then_else(
resourceRequirements.toVec() <=
m_currentResourceAllocations.toVec(),
m_currentResourceAllocations.toVec(),
(resourceRequirements.toVec() * OVERALLOC_x4.toVec()) >> 2));
// In case the 25% growth pushed us above limits.
allocs.gradTextureHeight =
std::min<size_t>(allocs.gradTextureHeight, kMaxTextureHeight);
allocs.tessTextureHeight =
std::min<size_t>(allocs.tessTextureHeight, kMaxTextureHeight);
allocs.atlasTextureWidth = std::min<size_t>(
allocs.atlasTextureWidth,
std::max(atlasMaxSize(), frameDescriptor().renderTargetWidth));
allocs.atlasTextureHeight = std::min<size_t>(
allocs.atlasTextureHeight,
std::max(atlasMaxSize(), frameDescriptor().renderTargetHeight));
allocs.coverageBufferLength =
std::min(allocs.coverageBufferLength,
platformFeatures().maxCoverageBufferLength);
// Additionally, every 5 seconds, trim resources down to the most recent
// steady-state usage.
double flushTime = m_impl->secondsNow();
bool needsResourceTrim = flushTime - m_lastResourceTrimTimeInSeconds >= 5;
if (needsResourceTrim)
{
// Trim GPU resource allocations to their maximum recent usage, plus
// overallocation, and only if the recent usage is below a certain
// threshold.
constexpr static ResourceAllocationCounts SHRINK_THRESHOLD_x3 = {
.flushUniformBufferCount = 2, // 66.7%
.imageDrawUniformBufferCount = 2, // 66.7%
.pathBufferCount = 2, // 66.7%
.paintBufferCount = 2, // 66.7%
.paintAuxBufferCount = 2, // 66.7%
.contourBufferCount = 2, // 66.7%
.gradSpanBufferCount = 2, // 66.7%
.tessSpanBufferCount = 2, // 66.7%
.triangleVertexBufferCount = 2, // 66.7%
.gradTextureHeight = 2, // 66.7%
.tessTextureHeight = 2, // 66.7%
.atlasTextureWidth = 2, // 66.7%
.atlasTextureHeight = 2, // 66.7%
.plsTransientBackingWidth = 3, // 100% (i.e., always shrink)
.plsTransientBackingHeight = 3, // 100% (i.e., always shrink)
.plsTransientBackingPlaneCount = 3, // 100% (i.e., always shrink)
.plsAtomicCoverageBackingWidth = 3, // 100% (i.e., always shrink)
.plsAtomicCoverageBackingHeight = 3, // 100% (i.e., always shrink)
.coverageBufferLength = 2, // 66.7%
};
allocs = ResourceAllocationCounts::FromVec(simd::if_then_else(
m_maxRecentResourceRequirements.toVec() <=
(allocs.toVec() * SHRINK_THRESHOLD_x3.toVec()) / size_t(3),
// TODO: Do we actually need overallocation here?? Or should we just
// trust the past 5 seconds of steady usage?
(m_maxRecentResourceRequirements.toVec() * OVERALLOC_x4.toVec()) >>
2,
allocs.toVec()));
// Ensure we stayed within limits.
assert(allocs.gradTextureHeight <= kMaxTextureHeight);
assert(allocs.tessTextureHeight <= kMaxTextureHeight);
assert(allocs.atlasTextureWidth <= atlasMaxSize() ||
allocs.atlasTextureWidth <= frameDescriptor().renderTargetWidth);
assert(allocs.atlasTextureHeight <= atlasMaxSize() ||
allocs.atlasTextureHeight <=
frameDescriptor().renderTargetHeight);
assert(allocs.coverageBufferLength <=
platformFeatures().maxCoverageBufferLength);
// Zero out m_maxRecentResourceRequirements for the next interval.
m_maxRecentResourceRequirements = ResourceAllocationCounts();
m_lastResourceTrimTimeInSeconds = flushTime;
}
assert(simd::all(allocs.toVec() >= resourceRequirements.toVec()));
POP_DISABLE_CLANG_SIMD_ABI_WARNING()
setResourceSizes(allocs);
m_impl->prepareToFlush(flushResources.currentFrameNumber,
flushResources.safeFrameNumber);
mapResourceBuffers(resourceRequirements);
for (const auto& flush : m_logicalFlushes)
{
flush->writeResources();
}
assert(m_flushUniformData.elementsWritten() == m_logicalFlushes.size());
assert(m_imageDrawUniformData.elementsWritten() ==
totalFrameResourceCounts.imageDrawCount);
assert(m_pathData.elementsWritten() ==
totalFrameResourceCounts.pathCount + layoutCounts.pathPaddingCount);
assert(m_paintData.elementsWritten() ==
totalFrameResourceCounts.pathCount + layoutCounts.paintPaddingCount);
assert(m_paintAuxData.elementsWritten() ==
totalFrameResourceCounts.pathCount +
layoutCounts.paintAuxPaddingCount);
assert(m_contourData.elementsWritten() ==
totalFrameResourceCounts.contourCount +
layoutCounts.contourPaddingCount);
assert(m_gradSpanData.elementsWritten() ==
layoutCounts.gradSpanCount + layoutCounts.gradSpanPaddingCount);
assert(m_tessSpanData.elementsWritten() <=
totalFrameResourceCounts.maxTessellatedSegmentCount);
assert(m_triangleVertexData.elementsWritten() <=
totalFrameResourceCounts.maxTriangleVertexCount);
unmapResourceBuffers(resourceRequirements);
// Issue logical flushes to the backend.
for (const auto& flush : m_logicalFlushes)
{
m_impl->flush(flush->desc());
}
m_impl->postFlush(flushResources);
if (!m_logicalFlushes.empty())
{
m_logicalFlushes.resize(1);
m_logicalFlushes.front()->rewind();
}
// Drop all memory that was allocated for this frame using
// TrivialBlockAllocator.
m_perFrameAllocator.reset();
m_numChopsAllocator.reset();
m_chopVerticesAllocator.reset();
m_tangentPairsAllocator.reset();
m_polarSegmentCountsAllocator.reset();
m_parametricSegmentCountsAllocator.reset();
m_frameDescriptor = FrameDescriptor();
RIVE_DEBUG_CODE(m_didBeginFrame = false;)
// Wait to reset CPU-side containers until after the flush has finished.
if (needsResourceTrim)
{
resetContainers();
}
}
static uint32_t pls_transient_backing_plane_count(
gpu::InterlockMode interlockMode,
gpu::DrawContents combinedDrawContents)
{
switch (interlockMode)
{
case gpu::InterlockMode::rasterOrdering:
return 3; // clip, scratch, coverage
case gpu::InterlockMode::atomics:
return 1; // only clip (coverage is atomic)
case gpu::InterlockMode::clockwise:
{
uint32_t n = 1; // coverage
if (combinedDrawContents &
(gpu::DrawContents::activeClip | gpu::DrawContents::clipUpdate))
{
++n; // clip
}
if (combinedDrawContents & gpu::DrawContents::advancedBlend)
{
++n; // scratch color
}
return n;
}
case gpu::InterlockMode::clockwiseAtomic:
case gpu::InterlockMode::msaa:
return 0; // N/A
}
RIVE_UNREACHABLE();
}
static bool wants_msaa_manual_resolve(
const gpu::PlatformFeatures& platformFeatures,
const RenderTarget* renderTarget,
const IAABB& renderTargetUpdateBounds,
gpu::DrawContents combinedDrawContents)
{
if (platformFeatures.msaaResolveNeedsDraw)
{
return true;
}
if (platformFeatures.msaaResolveWithPartialBoundsNeedsDraw &&
!renderTargetUpdateBounds.contains(renderTarget->bounds()))
{
return true;
}
if (platformFeatures.msaaResolveAfterDstReadNeedsDraw &&
(combinedDrawContents & gpu::DrawContents::advancedBlend))
{
return true;
}
return false;
}
static bool wants_fixed_function_color_output(
const gpu::PlatformFeatures& platformFeatures,
gpu::InterlockMode interlockMode,
gpu::DrawContents combinedDrawContents,
bool msaaManualResolve)
{
switch (interlockMode)
{
case gpu::InterlockMode::rasterOrdering:
// rasterOrdering shaders always read the framebuffer, even with
// srcOver blend.
return false;
case gpu::InterlockMode::atomics:
return !(combinedDrawContents & gpu::DrawContents::advancedBlend);
case gpu::InterlockMode::clockwise: