20 private const int MaxAtlasBatchSize = 256;
21 private const int MaxSnappedVertexBatchSize = 4096;
22 private static readonly
int[] PartialBatchSizes = [128, 64, 32, 16, 8, 4, 2, 1];
24 private static readonly
int[] PartialSnappedVertexBatchSizes =
25 [2048, 1024, 512, 256, 128, 64, 32, 16, 8, 4, 2, 1];
27 private sealed class AtlasBatchBuffer(int size)
29 internal SKRect[]
Sprites {
get; } =
new SKRect[size];
30 internal SKRotationScaleMatrix[] Transforms {
get; } =
new SKRotationScaleMatrix[size];
33 private sealed class SnappedVertexBatchBuffer(int tileCount)
35 internal SKPoint[] Positions {
get; } =
new SKPoint[tileCount * 4];
36 internal SKPoint[] TextureCoordinates {
get; } =
new SKPoint[tileCount * 4];
37 internal ushort[] Indices {
get; } = CreateQuadIndices(tileCount);
40 private readonly record
struct FrameAtlasKey(
46 private readonly record
struct FrameAtlasInfo(
51 internal readonly record
struct FixedGridRenderPlan(
55 private readonly record
struct LayerScreenMap(
78 internal RectangleF Map(Rectangle world) =>
80 OffsetX + world.Left * ScaleX,
81 OffsetY + world.Top * ScaleY,
83 world.Height * ScaleY);
85 internal RectangleF MapPixelSnapped(Rectangle world)
87 float left = Snap(OffsetX + world.Left * ScaleX);
88 float top = Snap(OffsetY + world.Top * ScaleY);
89 float right = Snap(OffsetX + world.Right * ScaleX);
90 float bottom = Snap(OffsetY + world.Bottom * ScaleY);
92 return RectangleF.FromLTRB(
99 private static float Snap(
float value) =>
100 MathF.Round(value, MidpointRounding.AwayFromZero);
102 internal SKMatrix CreateWorldToScreenMatrix() =>
103 SKMatrix.CreateScaleTranslation(
110 private readonly SKPictureRecorder _recorder =
new();
111 private readonly SKRect[] _pendingSprites =
new SKRect[MaxAtlasBatchSize];
113 private readonly SKRotationScaleMatrix[] _pendingTransforms =
114 new SKRotationScaleMatrix[MaxAtlasBatchSize];
116 private readonly SKPoint[] _pendingSnappedPositions =
117 new SKPoint[MaxSnappedVertexBatchSize * 4];
119 private readonly SKPoint[] _pendingSnappedTextureCoordinates =
120 new SKPoint[MaxSnappedVertexBatchSize * 4];
122 private readonly ushort[] _fullSnappedVertexIndices =
123 CreateQuadIndices(MaxSnappedVertexBatchSize);
125 private readonly Dictionary<FrameAtlasKey, FrameAtlasInfo> _frameAtlasCache = [];
126 private readonly Dictionary<SKImage, SKShader> _atlasShaderCache = [];
128 private readonly Dictionary<int, AtlasBatchBuffer> _partialBatchBuffers =
new()
140 private readonly Dictionary<int, SnappedVertexBatchBuffer> _partialSnappedVertexBuffers =
141 PartialSnappedVertexBatchSizes.ToDictionary(
143 size =>
new SnappedVertexBatchBuffer(size));
145 private readonly SKPaint _snappedVertexPaint =
new()
148 BlendMode = SKBlendMode.SrcOver
151 private SKCanvas? _canvas;
152 private SKImage? _pendingAtlas;
153 private SKImage? _pendingSnappedVertexAtlas;
154 private int _pendingCount;
155 private int _pendingSnappedVertexCount;
157 internal int AtlasBatchCount {
get;
private set; }
158 internal int AtlasBatchedTileCount {
get;
private set; }
160 internal RecordingBackbuffer() : base(1, 1) { }
163 public override SKCanvas Canvas => _canvas ??
throw new InvalidOperationException(
"No recording is active.");
166 public override bool IsGlThreadRendered =>
true;
168 internal void Start(BackbufferBase source)
171 ResetSnappedVertexBatch();
172 DisposeAtlasShaders();
173 _frameAtlasCache.Clear();
175 AtlasBatchedTileCount = 0;
177 UpdateSize(source.Width, source.Height);
178 ClearColor = source.ClearColor;
180 GridLinePaint.Dispose();
181 CollisionBoxPaint.Dispose();
182 FogPaint = source.FogPaint.Clone();
183 GridLinePaint = source.GridLinePaint.Clone();
184 CollisionBoxPaint = source.CollisionBoxPaint.Clone();
186 _canvas = _recorder.BeginRecording(
194 internal SKPicture Complete()
197 FlushSnappedVertexBatch();
198 var picture = _recorder.EndRecording();
201 ResetSnappedVertexBatch();
202 DisposeAtlasShaders();
209 ResetSnappedVertexBatch();
213 DisposeAtlasShaders();
217 var picture = _recorder.EndRecording();
220 DisposeAtlasShaders();
223 internal bool TryPrepareFixedGridLayer(
226 out FixedGridRenderPlan plan)
232 layer.TransformedTiles.Count != 0 ||
235 !layer.IsFixedGridSnapshotFastPathEligible ||
236 !RenderTileQuery.IsRenderOrdered(layer))
241 var queryRect = worldRect;
243 queryRect.Inflate(1, 1);
245 if (SpriteManager.Instance.HasVisibleSpriteInWorldRect(queryRect, layer) ||
246 DirectDrawingManager.Instance.HasVisibleDrawingForLayer(layer, worldRect))
251 plan =
new(layer, worldRect);
255 internal int DrawFixedGridLayer(
257 FixedGridRenderPlan plan,
260 var layer = plan.Layer;
261 LayerScreenMap screen = LayerScreenMap.Create(view, layer);
262 bool snapOrthogonalEdges = layer.CoordinateSystem is OrthogonalCoordinates;
266 Canvas.ClipRect(clipRect.ToSKRect());
268 if (!snapOrthogonalEdges)
270 var worldToScreen = screen.CreateWorldToScreenMatrix();
271 Canvas.Concat(ref worldToScreen);
276 RenderTileQuery.VisitCandidates(
277 layer.CoordinateSystem,
280 includeOverhang:
true,
283 if (!tile.Visible || tile.CurrentFrame.Tilesheet is null)
288 if (snapOrthogonalEdges)
289 DrawOrthogonalFixedGridTileSnapped(layer, screen, tile);
291 DrawFixedGridTileInWorldSpace(layer, tile);
296 if (snapOrthogonalEdges)
297 FlushSnappedVertexBatch();
309 internal bool TryDrawFixedGridDrawables(
311 IReadOnlyList<IDrawable> drawables,
314 if (drawables.Count == 0)
321 for (
int i = 0; i < drawables.Count; i++)
323 if (drawables[i].GetType() != typeof(SceneLayerTile) ||
324 drawables[i] is not SceneLayerTile tile ||
330 layer ??= tile.SceneLayer;
332 if (!ReferenceEquals(layer, tile.SceneLayer))
343 LayerScreenMap screen = LayerScreenMap.Create(view, layer);
346 Canvas.ClipRect(clipRect.ToSKRect());
348 if (layer.CoordinateSystem is OrthogonalCoordinates)
352 for (
int i = 0; i < drawables.Count; i++)
353 DrawOrthogonalFixedGridTileSnapped(
356 (SceneLayerTile)drawables[i]);
358 FlushSnappedVertexBatch();
367 var worldToScreen = screen.CreateWorldToScreenMatrix();
368 bool worldSpaceActive =
false;
372 for (
int i = 0; i < drawables.Count; i++)
374 var tile = (SceneLayerTile)drawables[i];
377 TryGetFrameAtlasInfo(tile.CurrentFrame, out _))
379 if (!worldSpaceActive)
382 Canvas.Concat(ref worldToScreen);
383 worldSpaceActive =
true;
386 DrawFixedGridTileInWorldSpace(layer, tile);
390 if (worldSpaceActive)
394 worldSpaceActive =
false;
404 if (worldSpaceActive)
408 worldSpaceActive =
false;
415 if (worldSpaceActive)
425 private void DrawOrthogonalFixedGridTileSnapped(
427 LayerScreenMap screen,
433 Rectangle world = GetScaledFixedTileBounds(layer, tile, frame);
435 RectangleF destination = screen.MapPixelSnapped(world);
437 if (destination.Width <= 0f || destination.Height <= 0f)
440 QueueSnappedVertexAtlas(
448 FlushSnappedVertexBatch();
450 RectangleF transformedDestination =
453 if (transformedDestination.Width > 0f &&
454 transformedDestination.Height > 0f)
456 tile.
Draw(
this, transformedDestination);
460 private void DrawFixedGridTileInWorldSpace(
464 if (!TryGetFrameAtlasInfo(tile.
CurrentFrame, out var frame))
467 Rectangle world = GetScaledFixedTileBounds(layer, tile, frame);
473 if (TryQueueAtlas(frame.Atlas, frame.Source, world))
482 SKSamplingOptions.Default);
485 private void DrawFixedGridTile(
488 LayerScreenMap screen,
498 if (!TryGetFrameAtlasInfo(tile.
CurrentFrame, out var frame))
505 Rectangle world = GetScaledFixedTileBounds(layer, tile, frame);
507 RectangleF destination = screen.Map(world);
509 if (!TryQueueAtlas(frame.Atlas, frame.Source, destination))
512 tile.
Draw(
this, destination);
516 private static Rectangle GetScaledFixedTileBounds(
519 FrameAtlasInfo frame)
521 Rectangle cell = RenderTileQuery.GetFixedTileCellBounds(layer, tile);
522 Spacing overhang = TileTransformGeometry.ScaleOverhang(
523 new Size((
int)frame.Source.Width, (
int)frame.Source.Height),
527 return TileBounds.ApplyOverhang(cell, overhang,
true);
530 private void QueueSnappedVertexAtlas(
533 RectangleF destination)
535 if (_pendingSnappedVertexAtlas is not
null &&
536 !ReferenceEquals(_pendingSnappedVertexAtlas, atlas))
538 FlushSnappedVertexBatch();
541 _pendingSnappedVertexAtlas = atlas;
543 int tileIndex = _pendingSnappedVertexCount++;
544 int vertexIndex = tileIndex * 4;
546 float left = destination.Left;
547 float top = destination.Top;
548 float right = destination.Right;
549 float bottom = destination.Bottom;
551 _pendingSnappedPositions[vertexIndex] =
new(left, top);
552 _pendingSnappedPositions[vertexIndex + 1] =
new(right, top);
553 _pendingSnappedPositions[vertexIndex + 2] =
new(right, bottom);
554 _pendingSnappedPositions[vertexIndex + 3] =
new(left, bottom);
556 _pendingSnappedTextureCoordinates[vertexIndex] =
557 new(source.Left, source.Top);
559 _pendingSnappedTextureCoordinates[vertexIndex + 1] =
560 new(source.Right, source.Top);
562 _pendingSnappedTextureCoordinates[vertexIndex + 2] =
563 new(source.Right, source.Bottom);
565 _pendingSnappedTextureCoordinates[vertexIndex + 3] =
566 new(source.Left, source.Bottom);
568 if (_pendingSnappedVertexCount == MaxSnappedVertexBatchSize)
569 FlushFullSnappedVertexBatch();
572 private void FlushSnappedVertexBatch()
574 if (_pendingSnappedVertexCount == 0)
576 _pendingSnappedVertexAtlas =
null;
580 if (_pendingSnappedVertexAtlas is
null)
582 throw new InvalidOperationException(
583 "Snapped vertex batch has queued tiles without an atlas image.");
587 int remaining = _pendingSnappedVertexCount;
589 foreach (
int size
in PartialSnappedVertexBatchSizes)
591 while (remaining >= size)
593 var buffers = _partialSnappedVertexBuffers[size];
596 _pendingSnappedPositions,
603 _pendingSnappedTextureCoordinates,
605 buffers.TextureCoordinates,
609 DrawSnappedVertexBatch(
610 _pendingSnappedVertexAtlas,
612 buffers.TextureCoordinates,
621 ResetSnappedVertexBatch();
624 private void FlushFullSnappedVertexBatch()
626 if (_pendingSnappedVertexAtlas is
null ||
627 _pendingSnappedVertexCount != MaxSnappedVertexBatchSize)
632 DrawSnappedVertexBatch(
633 _pendingSnappedVertexAtlas,
634 _pendingSnappedPositions,
635 _pendingSnappedTextureCoordinates,
636 _fullSnappedVertexIndices,
637 MaxSnappedVertexBatchSize);
639 _pendingSnappedVertexCount = 0;
642 private void DrawSnappedVertexBatch(
645 SKPoint[] textureCoordinates,
649 using var vertices = SKVertices.CreateCopy(
650 SKVertexMode.Triangles,
656 if (!_atlasShaderCache.TryGetValue(atlas, out var shader))
658 shader = atlas.ToShader(
659 SKShaderTileMode.Clamp,
660 SKShaderTileMode.Clamp,
661 new SKSamplingOptions(
662 SKFilterMode.Nearest,
665 _atlasShaderCache.Add(atlas, shader);
668 _snappedVertexPaint.Shader = shader;
672 SKBlendMode.Modulate,
673 _snappedVertexPaint);
676 AtlasBatchedTileCount += tileCount;
679 private static ushort[] CreateQuadIndices(
int tileCount)
681 var indices =
new ushort[tileCount * 6];
683 for (
int tile = 0; tile < tileCount; tile++)
685 int vertex = tile * 4;
686 int index = tile * 6;
688 indices[index] = (ushort)vertex;
689 indices[index + 1] = (ushort)(vertex + 1);
690 indices[index + 2] = (ushort)(vertex + 2);
691 indices[index + 3] = (ushort)vertex;
692 indices[index + 4] = (ushort)(vertex + 2);
693 indices[index + 5] = (ushort)(vertex + 3);
699 private void ResetSnappedVertexBatch()
701 _pendingSnappedVertexAtlas =
null;
702 _pendingSnappedVertexCount = 0;
705 private void DisposeAtlasShaders()
707 _snappedVertexPaint.Shader =
null;
709 foreach (var shader
in _atlasShaderCache.Values)
712 _atlasShaderCache.Clear();
715 internal bool TryQueueTile(SceneLayerTile tile, RectangleF destination)
718 !TryGetFrameAtlasInfo(tile.
CurrentFrame, out var frame))
723 return TryQueueAtlas(frame.Atlas, frame.Source, destination);
726 private bool TryGetFrameAtlasInfo(Frame frame, out FrameAtlasInfo info)
734 var key =
new FrameAtlasKey(
740 if (_frameAtlasCache.TryGetValue(key, out info))
743 var atlas = frame.AtlasImage;
744 Rectangle source = frame.AtlasSourceBounds;
746 if (atlas is
null || source.IsEmpty)
757 _frameAtlasCache.Add(key, info);
761 private bool TryQueueAtlas(
764 RectangleF destination)
766 if (source.Width <= 0 ||
767 source.Height <= 0 ||
768 destination.Width <= 0 ||
769 destination.Height <= 0)
774 float scaleX = destination.Width / source.Width;
775 float scaleY = destination.Height / source.Height;
776 float tolerance = MathF.Max(0.0001f, MathF.Abs(scaleX) * 0.0001f);
778 if (!
float.IsFinite(scaleX) ||
779 !
float.IsFinite(scaleY) ||
780 MathF.Abs(scaleX - scaleY) > tolerance)
785 if (_pendingAtlas is not
null && !ReferenceEquals(_pendingAtlas, atlas))
788 _pendingAtlas = atlas;
789 int index = _pendingCount++;
790 _pendingSprites[index] = source;
792 _pendingTransforms[index] =
new SKRotationScaleMatrix(
798 if (_pendingCount == MaxAtlasBatchSize)
799 FlushFullTileBatch();
804 internal void FlushTileBatch()
806 if (_pendingCount == 0)
808 _pendingAtlas =
null;
812 if (_pendingAtlas is
null)
813 throw new InvalidOperationException(
"Atlas batch has queued tiles without an atlas image.");
816 int remaining = _pendingCount;
818 foreach (
int size
in PartialBatchSizes)
820 while (remaining >= size)
822 var buffers = _partialBatchBuffers[size];
842 SKSamplingOptions.Default);
845 AtlasBatchedTileCount += size;
854 private void FlushFullTileBatch()
856 if (_pendingAtlas is
null || _pendingCount != MaxAtlasBatchSize)
863 SKSamplingOptions.Default);
866 AtlasBatchedTileCount += MaxAtlasBatchSize;
870 private void ResetPendingBatch()
872 _pendingAtlas =
null;
877 protected internal override void BeginFrame() { }
880 protected internal override void EndFrame() { }
883 protected internal override SKImage Snapshot() =>
884 throw new NotSupportedException(
885 "A recording has commands, not pixels. Read pixels on the GL thread after replay.");
888 protected internal override void DrawTileFrame(Tile tile, RectangleF destRectScreen)
892 if (image is not
null)
893 Canvas.DrawImage(image, destRectScreen.ToSKRect());
897 public override void Dispose()
900 _snappedVertexPaint.Dispose();
virtual Frame CurrentFrame
Gets or sets the current frame. The initial frame supplies the tile's default collision adjustment an...
virtual RectangleF GetDrawLocationScreen(View view)
Transforms the drawable bounds into screen pixels for the specified view.
Represents a base class for managing a graphical backbuffer, and is the in-memory surface where rende...
RectangleF WorldRectToScreenRect(SceneLayer layer, RectangleF worldRect)
Converts a world-space pixel rectangle into a screen-space rectangle for this View,...
override void Draw(Gondwana.Rendering.Backbuffers.BackbufferBase backbuffer, RectangleF destRectScreen)
Draws the current content into the backbuffer at the supplied screen-pixel bounds.
TileTransform Transform
Gets or sets this placement's orthogonal orientation without changing its source frame.
override Rectangle DrawLocationWorld
Gets the world-space pixel rectangle where this tile should be drawn.
bool WrapVertically
Gets or sets a value indicating whether this layer repeats along its row axis at the grid boundaries.
bool WrapHorizontally
Gets or sets a value indicating whether this layer repeats along its column axis at the grid boundari...
bool ShowGridLines
Gets or sets a value indicating whether grid lines should be rendered over this layer for debugging.
int TileHeight
Gets or sets the height of each tile in this layer, measured in pixels.
int TileWidth
Gets or sets the width of each tile in this layer, measured in pixels.
bool ShowCollisionBoxes
Gets or sets a value indicating whether collision boxes should be rendered over this layer for debugg...
@ Rectangle
Particles are spawned uniformly within a rectangular area. This is the default distribution.
@ View
Performs direct drawing at the view level using screen-space coordinates.
@ SceneLayer
Performs direct drawing within a scene layer using world-space coordinates.
TileTransform
The eight orthogonal orientations of artwork placed in a fixed scene cell.
record struct Spacing([property:JsonProperty("left")] int Left, [property:JsonProperty("top")] int Top, [property:JsonProperty("right")] int Right, [property:JsonProperty("bottom")] int Bottom)
Represents dimensions in pixels when spacing Tilesheets.
@ Sprites
Represents the sprites state, including sprite instances, positions, properties, and sprite-related g...
readonly int YTile
The vertical tile coordinate (row index) within the tilesheet.
readonly Tilesheet Tilesheet
The tilesheet that contains the source bitmap for this frame.
readonly string RegionName
The tilesheet region that contains the source bitmap for this frame.
readonly int XTile
The horizontal tile coordinate (column index) within the tilesheet.
readonly? SKImage SkImage
Gets the SkiaSharp image for this frame.
readonly Spacing Overhang
Gets the overhang dimensions for this frame.