Gondwana Game Engine Development (master) - 2.7.0
Gondwana is a cross-platform 2.5D game and rendering engine written in C#/.NET 8. It provides fine-grained control over rendering, timing, and scene composition, with built-in support for parallax, z-ordering, pixel overhang, collision detection, and particle effects. Gondwana targets desktop and web platforms using SkiaSharp for graphics and pluggable audio backends for desktop and browser targets.
Loading...
Searching...
No Matches
SceneLayer.cs
1using System.Collections;
2using System.Drawing;
3using System.Runtime.Serialization;
11using Gondwana.Timers;
12using Newtonsoft.Json;
13
14namespace Gondwana.Scenes;
15
38[JsonObject(IsReference = true)]
39public class SceneLayer : IEnumerable<SceneLayerTile>, IDisposable
40{
41 #region events
42
52 public event Action<SceneLayer>? SceneLayerTileSizeChanged;
53
62 public event Action<SceneLayer>? VisibleChanged;
63
72 public event Action<SceneLayer>? WrappingChanged;
73
82 public event Action<SceneLayer>? ShowGridLinesChanged;
83
92 public event Action<SceneLayer>? ShowCollisionBoxesChanged;
93
102 public event Action<SceneLayer>? ZOrderChanged;
103
112 public event Action<SceneLayer>? ParallaxChanged;
113
122 public event Action<SceneLayer>? OriginPxChanged;
123
132 public event Action<SceneLayer>? Disposing;
133
134 #endregion events
135
136 #region private fields
137
138 private int _tileWidth; // rendered width
139 private int _tileHeight; // rendered height
140 private bool _visible; // is SceneLayer to be rendered; useful with multiple layers
141 private string _defaultTileCollisionProfile = CollisionProfileNames.World;
142 private bool _fixedGridRenderEligibilityDirty;
143 private bool _fixedGridRenderEligible = true;
144 private bool _sceneLayerTileArrayExternallyExposed;
145
146 [JsonIgnore] internal float EffectOpacity { get; set; } = 1f;
147
148 [JsonIgnore] internal float EffectReveal { get; set; } = 1f;
149
150 [JsonIgnore] internal EffectDirection EffectRevealDirection { get; set; } = EffectDirection.FromLeftToRight;
151
152 [JsonIgnore] internal PointF EffectOffsetFactor { get; set; } = PointF.Empty;
153
154 [JsonIgnore] internal PointF EffectOffsetPx { get; set; } = PointF.Empty;
155
156 #endregion private fields
157
158 #region constructors / finalizer
159
170 protected internal SceneLayer(
171 int columnCount,
172 int rowCount,
173 int width = 32,
174 int height = 32,
175 float parallax = 1,
176 CoordinateSystemTypes coordinateSystem = CoordinateSystemTypes.Orthogonal)
177 {
178 var tileArray = new SceneLayerTile[columnCount, rowCount];
179
180 InitValues(
181 tileArray,
182 width,
183 height,
184 parallax,
185 coordinateSystem);
186 }
187
188 [JsonConstructor]
189 private SceneLayer() : this(0, 0) { }
190
191 [OnDeserialized]
192 private void OnDeserialized(StreamingContext context)
193 {
194 // Preserve the deserialized tiles and presentation state. Re-running
195 // InitValues here used to replace every loaded tile with an empty cell.
196 bool fastPathEligible = true;
197 int? fixedZOrder = null;
198
199 for (int x = 0; x < GridColumnCount; x++)
200 for (int y = 0; y < GridRowCount; y++)
201 {
202 var tile = _sceneLayerTileArray[x, y] ??= new SceneLayerTile(this);
203 tile.parentSceneLayer = this;
204
205 if (tile.Transform != TileTransform.Identity)
206 TransformedTiles.Add(tile);
207
208 tile.sceneLayerCoordinates = new Point(x, y);
209
210 if (tile.GetType() != typeof(SceneLayerTile) || tile.EnableFog)
211 fastPathEligible = false;
212
213 if (fixedZOrder.HasValue && fixedZOrder.Value != tile.ZOrder)
214 fastPathEligible = false;
215 else
216 fixedZOrder ??= tile.ZOrder;
217 }
218
219 _fixedGridRenderEligible = fastPathEligible;
220 _fixedGridRenderEligibilityDirty = false;
221 _sceneLayerTileArrayExternallyExposed = false;
222 BuildTileColliders();
223 }
224
234 ~SceneLayer()
235 {
236 Dispose();
237 }
238
239 #endregion constructors / finalizer
240
241 #region properties
242
254 [JsonIgnore]
255 public TypedValueBag ValueBag { get; } = new();
256
257 [JsonIgnore] internal ISceneLayerCoordinates CoordinateSystem { get; private set; } = new OrthogonalCoordinates();
258
283 [JsonProperty]
285 {
286 get
287 {
288 return CoordinateSystem switch
289 {
290 OrthogonalCoordinates => CoordinateSystemTypes.Orthogonal,
291 IsometricRhombicCoordinates => CoordinateSystemTypes.IsometricRhombic,
292 IsometricAxialCoordinates => CoordinateSystemTypes.IsometricAxial,
293 HexAxialFlatTopCoordinates => CoordinateSystemTypes.HexAxialFlatTop,
294 HexAxialPointedTop => CoordinateSystemTypes.HexAxialPointedTop,
295 ObliqueRightCoordinates => CoordinateSystemTypes.ObliqueRight,
296 ObliqueLeftCoordinates => CoordinateSystemTypes.ObliqueLeft,
297 _ => throw new InvalidOperationException(
298 $"Unknown coordinate system type: {CoordinateSystem.GetType().Name}")
299 };
300 }
301 set
302 {
303 CoordinateSystem = value switch
304 {
305 CoordinateSystemTypes.Orthogonal => new OrthogonalCoordinates(),
306 CoordinateSystemTypes.IsometricRhombic => new IsometricRhombicCoordinates(),
307 CoordinateSystemTypes.IsometricAxial => new IsometricAxialCoordinates(),
308 CoordinateSystemTypes.HexAxialFlatTop => new HexAxialFlatTopCoordinates(),
310 CoordinateSystemTypes.ObliqueRight => new ObliqueRightCoordinates(),
311 CoordinateSystemTypes.ObliqueLeft => new ObliqueLeftCoordinates(),
312 _ => throw new ArgumentOutOfRangeException(nameof(value), $"Unknown coordinate system type: {value}")
313 };
314 }
315 }
316
326 [JsonProperty]
327 public string ID { get; protected internal set; } = Guid.NewGuid().ToString();
328
338 [JsonIgnore]
339 public Scene Scene { get; internal set; }
340
341 [JsonIgnore] internal RefreshQueue RefreshQueue { get; set; }
342
343 private int _zOrder = 0;
344
359 [JsonProperty]
360 public int ZOrder
361 {
362 get => _zOrder;
363 set
364 {
365 _zOrder = value;
366 ZOrderChanged?.Invoke(this);
367 }
368 }
369
370 private float _parallax = 1f; // 1 = default; <1 is slower, >1 is faster
371
392 [JsonProperty]
393 public float Parallax
394 {
395 get { return _parallax; }
396 set
397 {
398 _parallax = value;
399 ParallaxChanged?.Invoke(this);
400 }
401 }
402
418 [JsonProperty]
419 public int TileHeight
420 {
421 get { return _tileHeight; }
422 set
423 {
424 _tileHeight = value;
425 SceneLayerTileSizeChanged?.Invoke(this);
426 }
427 }
428
444 [JsonProperty]
445 public int TileWidth
446 {
447 get { return _tileWidth; }
448 set
449 {
450 _tileWidth = value;
451 SceneLayerTileSizeChanged?.Invoke(this);
452 }
453 }
454
470 [JsonProperty]
471 public bool Visible
472 {
473 get { return _visible; }
474 set
475 {
476 _visible = value;
477 VisibleChanged?.Invoke(this);
478 }
479 }
480
481 [JsonIgnore] internal HashSet<SceneLayerTile> TransformedTiles { get; } = new();
482
483 [JsonProperty("SceneLayerTileArray")]
484 [JsonConverter(typeof(SceneLayerTileArrayConverter))]
485 private SceneLayerTile[,] _sceneLayerTileArray; // array of points; 2 dimensions (X, Y)
486
506 [JsonIgnore]
508 {
509 get
510 {
511 // Element replacement through the returned array bypasses SceneLayer mutation
512 // notifications. Disable the persistent fast path for this layer rather than risk
513 // recording custom/reparented tiles with fixed-grid assumptions.
514 _sceneLayerTileArrayExternallyExposed = true;
515 return _sceneLayerTileArray;
516 }
517 }
518
527 [JsonIgnore]
528 public int GridColumnCount => _sceneLayerTileArray.GetUpperBound(0) + 1;
529
538 [JsonIgnore]
539 public int GridRowCount => _sceneLayerTileArray.GetUpperBound(1) + 1;
540
541 [JsonProperty("WrapHorizontally")] private bool _wrapHoriz = false;
542
557 [JsonIgnore]
559 {
560 get { return _wrapHoriz; }
561 set
562 {
563 _wrapHoriz = value;
564 WrappingChanged?.Invoke(this);
565 }
566 }
567
568 [JsonProperty("WrapVertically")] private bool _wrapVerti = false;
569
584 [JsonIgnore]
585 public bool WrapVertically
586 {
587 get { return _wrapVerti; }
588 set
589 {
590 _wrapVerti = value;
591 WrappingChanged?.Invoke(this);
592 }
593 }
594
595 [JsonProperty("ShowGridLines")] private bool showGridLines = false;
596
610 [JsonIgnore]
611 public bool ShowGridLines
612 {
613 get { return showGridLines; }
614 set
615 {
616 showGridLines = value;
617 ShowGridLinesChanged?.Invoke(this);
618 }
619 }
620
621 [JsonProperty("ShowCollisionBoxes")] private bool showCollisionBoxes = false;
622
637 [JsonIgnore]
639 {
640 get { return showCollisionBoxes; }
641 set
642 {
643 showCollisionBoxes = value;
644 ShowCollisionBoxesChanged?.Invoke(this);
645 }
646 }
647
648 // World-space origin (in pixels) of this layer's (0,0) tile.
649 // Usually (0,0); can be shifted to move the entire layer as a block.
650 [JsonProperty("OriginPx")] private Point _originPx = Point.Empty;
651
667 [JsonIgnore]
668 public Point OriginPx
669 {
670 get => _originPx;
671 set
672 {
673 if (_originPx == value)
674 return;
675
676 _originPx = value;
677 OriginPxChanged?.Invoke(this);
678 }
679 }
680
690 [JsonIgnore]
691 public ColliderRegistry ColliderRegistry { get; private set; } = new();
692
693 [JsonIgnore] internal CollisionResolver CollisionResolver { get; private set; } = null!;
694
702 [JsonIgnore]
704
709 [JsonProperty]
711 {
712 get => _defaultTileCollisionProfile;
713 set
714 {
715 if (string.IsNullOrWhiteSpace(value))
716 {
717 throw new ArgumentException(
718 "Default tile collision profile cannot be empty.",
719 nameof(value));
720 }
721
722 if (Scene is not null)
723 {
724 var profile = Scene.CollisionProfiles.Get(value);
725 _ = profile.ResolveCollisionGroup(Scene.CollisionGroups);
726 _ = profile.ResolveCollidesWith(Scene.CollisionGroups);
727 }
728
729 _defaultTileCollisionProfile = value;
730
731 if (Scene is not null && _sceneLayerTileArray is not null)
732 ApplyDefaultTileCollisionProfile();
733 }
734 }
735
736 #endregion properties
737
738 #region public methods
739
756 public void SetTileSize(int newWidth, int newHeight)
757 {
758 _tileWidth = newWidth;
759 _tileHeight = newHeight;
760 SceneLayerTileSizeChanged?.Invoke(this);
761 }
762
767 internal void ApplyDefaultTileCollisionProfile()
768 {
769 if (Scene is null || _sceneLayerTileArray is null)
770 return;
771
772 // Resolve once up front so an invalid profile fails before partially
773 // updating the layer.
774 Scene.CollisionProfiles.Get(_defaultTileCollisionProfile);
775
776 foreach (var tile in _sceneLayerTileArray)
777 tile?.SetCollisionProfile(_defaultTileCollisionProfile);
778 }
779
787 public PointF GridToWorldPx(PointF grid) => CoordinateSystem.GetAnchorPixelAtSceneLayerCoordinates(this, grid);
788
796 public PointF WorldPxToGrid(PointF worldPx) => CoordinateSystem.GetSceneLayerCoordinatesAtPixel(this, worldPx);
797
799 public PointF WorldPxToContinuousGrid(PointF worldPx) => CoordinateSystem.GetContinuousGridAtPixel(this, worldPx);
800
810 CoordinateSystem.GetAdjacentSceneLayerTile(tile, direction);
811
819 public PointF WrapGrid(PointF grid)
820 {
822 return grid;
823
824 _ = GetPeriod();
825
826 if (!float.IsFinite(grid.X) || !float.IsFinite(grid.Y))
827 throw new ArgumentOutOfRangeException(nameof(grid));
828
829 var wrapped = CoordinateSystem.FindEquivalentSceneLayerCoordinates(grid, GridColumnCount - 1, GridRowCount - 1);
830 return new PointF(WrapHorizontally ? wrapped.X : grid.X, WrapVertically ? wrapped.Y : grid.Y);
831 }
832
840 public SceneLayerTile? ResolveWrappedTile(int column, int row)
841 {
843 _ = GetPeriod();
844
845 static int Mod(int value, int period)
846 {
847 int remainder = value % period;
848 return remainder < 0 ? remainder + period : remainder;
849 }
850
851 return this[WrapHorizontally ? Mod(column, GridColumnCount) : column,
852 WrapVertically ? Mod(row, GridRowCount) : row];
853 }
854
864 public IEnumerable<PointF> GetWrappedOffsets(RectangleF contentBounds, RectangleF queryBounds)
865 {
867 return GetPeriod().Offsets(contentBounds, queryBounds);
868
869 return contentBounds.IntersectsWith(queryBounds) ? new[] { PointF.Empty } : Array.Empty<PointF>();
870 }
871
872 internal LayerPeriod GetPeriod() => CoordinateSystem.GetWrapPeriod(this);
873
881 public virtual RectangleF GetLayerBoundsPx()
882 {
883 if (GridColumnCount == 0 || GridRowCount == 0)
884 return RectangleF.Empty;
885
886 int maxCol = GridColumnCount - 1;
887 int maxRow = GridRowCount - 1;
888
889 // Corner tiles
890 var corners = new[]
891 {
892 this[0, 0],
893 this[maxCol, 0],
894 this[0, maxRow],
895 this[maxCol, maxRow]
896 };
897
898 RectangleF result = RectangleF.Empty;
899 bool hasBounds = false;
900
901 foreach (var tile in corners)
902 {
903 var px = CoordinateSystem.GetPixelRangeForTile(tile, includeOverhang: true);
904
905 var rf = RectangleF.FromLTRB(
906 px.Left,
907 px.Top,
908 px.Right,
909 px.Bottom);
910
911 if (!hasBounds)
912 {
913 result = rf;
914 hasBounds = true;
915 }
916 else
917 {
918 result = RectangleF.Union(result, rf);
919 }
920 }
921
922 // Interior placements can extend beyond the corner cells after rotation.
923 foreach (var tile in TransformedTiles)
924 result = RectangleF.Union(result, tile.DrawLocationWorld);
925
926 return result;
927 }
928
929 #endregion public methods
930
931 #region private methods
932
933 private void InitValues(
934 SceneLayerTile[,] tileArray,
935 int width,
936 int height,
937 float parallax,
938 CoordinateSystemTypes coordinateSystem)
939 {
940 _sceneLayerTileArray = tileArray;
941 _parallax = parallax;
942 _tileWidth = width;
943 _tileHeight = height;
944 _visible = true;
945
946 _originPx = Point.Empty; // layer world origin
947 EffectOpacity = 1f;
948 EffectReveal = 1f;
949 EffectRevealDirection = EffectDirection.FromLeftToRight;
950 EffectOffsetFactor = PointF.Empty;
951 EffectOffsetPx = PointF.Empty;
952
953 CoordinateSystemType = coordinateSystem;
954
956 CollisionResolver = new CollisionResolver(ColliderRegistry);
957
958 // let each SceneLayerTile in array know its position in the array
959 SaveGridCoordinatesToSceneLayerTiles();
960 _fixedGridRenderEligible = true;
961 _fixedGridRenderEligibilityDirty = false;
962 _sceneLayerTileArrayExternallyExposed = false;
963 BuildTileColliders();
964 // Unbound scenes retain dirty regions for a future bitmap host. Once bound,
965 // the scene policy disables queue writes for full-frame GL rendering.
966 RefreshQueue = new RefreshQueue(() => Scene?.UsesDirtyRegionRendering ?? true);
967 }
968
969 private void SaveGridCoordinatesToSceneLayerTiles()
970 {
971 // let each SceneLayerTile in array know its position in the array
972 for (int X = 0; X <= _sceneLayerTileArray.GetUpperBound(0); X++)
973 {
974 for (int Y = 0; Y <= _sceneLayerTileArray.GetUpperBound(1); Y++)
975 {
976 _sceneLayerTileArray[X, Y] = new SceneLayerTile(this);
977 _sceneLayerTileArray[X, Y].sceneLayerCoordinates = new Point(X, Y);
978 }
979 }
980 }
981
982 private void BuildTileColliders()
983 {
984 foreach (var tile in _sceneLayerTileArray)
985 {
986 if (tile is null)
987 continue;
988
989 tile.EnsureCollider();
990 }
991 }
992
993 internal bool IsFixedGridSnapshotFastPathEligible
994 {
995 get
996 {
997 if (_sceneLayerTileArrayExternallyExposed)
998 return false;
999
1000 if (_fixedGridRenderEligibilityDirty)
1001 RecalculateFixedGridRenderEligibility();
1002
1003 return _fixedGridRenderEligible;
1004 }
1005 }
1006
1007 internal void InvalidateFixedGridRenderEligibility() =>
1008 _fixedGridRenderEligibilityDirty = true;
1009
1010 private void RecalculateFixedGridRenderEligibility()
1011 {
1012 bool eligible = true;
1013 int? fixedZOrder = null;
1014
1015 foreach (var tile in _sceneLayerTileArray)
1016 {
1017 if (tile is null ||
1018 tile.GetType() != typeof(SceneLayerTile) ||
1019 !ReferenceEquals(tile.SceneLayer, this) ||
1020 tile.EnableFog)
1021 {
1022 eligible = false;
1023 break;
1024 }
1025
1026 if (fixedZOrder.HasValue && fixedZOrder.Value != tile.ZOrder)
1027 {
1028 eligible = false;
1029 break;
1030 }
1031
1032 fixedZOrder ??= tile.ZOrder;
1033 }
1034
1035 _fixedGridRenderEligible = eligible;
1036 _fixedGridRenderEligibilityDirty = false;
1037 }
1038
1039 internal virtual List<IDrawable> GetDrawablesInWorldRect(Rectangle worldRect, bool includeOverhang = true) =>
1040 GetDrawablesInWorldRectCore(
1041 worldRect,
1042 includeOverhang,
1043 collectSortDiagnostics: false,
1044 out _);
1045
1046 internal virtual List<IDrawable> GetDrawablesInWorldRectWithDiagnostics(
1047 Rectangle worldRect,
1048 out long sortTicks,
1049 bool includeOverhang = true) =>
1050 GetDrawablesInWorldRectCore(
1051 worldRect,
1052 includeOverhang,
1053 collectSortDiagnostics: true,
1054 out sortTicks);
1055
1056 private List<IDrawable> GetDrawablesInWorldRectCore(
1057 Rectangle worldRect,
1058 bool includeOverhang,
1059 bool collectSortDiagnostics,
1060 out long sortTicks)
1061 {
1063 return GetWrappedDrawables(worldRect, collectSortDiagnostics, out sortTicks);
1064
1065 // Make selection rect covering so we never miss the edge tile.
1066 // Drawing is still clipped later, so over-selecting is safe.
1067 var queryRect = worldRect;
1068 queryRect.Inflate(TileWidth, TileHeight);
1069 queryRect.Inflate(1, 1);
1070
1071 // 1) Grid tiles. Every projection supplies a conservative render query whose
1072 // traversal follows fixed-tile depth order for that coordinate system.
1073 var renderTiles = CoordinateSystem.GetSceneLayerTilesForRendering(
1074 this,
1075 worldRect,
1076 includeOverhang);
1077
1078 var sceneLayerTiles = renderTiles.Tiles;
1079
1080 var list = new List<IDrawable>(sceneLayerTiles.Count);
1081 bool uniformGridZOrder = true;
1082 int? gridZOrder = null;
1083
1084 for (int i = 0; i < sceneLayerTiles.Count; i++)
1085 {
1086 var tile = sceneLayerTiles[i];
1087
1088 if (!tile.Visible || !HasRenderableTileContent(tile))
1089 continue;
1090
1091 int tileZ = tile.ZOrder;
1092
1093 if (gridZOrder.HasValue && gridZOrder.Value != tileZ)
1094 uniformGridZOrder = false;
1095 else
1096 gridZOrder ??= tileZ;
1097
1098 list.Add(tile);
1099 }
1100
1101 bool hasNonGridDrawables = false;
1102
1103 // 2) Sprites
1104 var sprites = SpriteManager.Instance.GetSpritesInWorldRectRange(
1105 queryRect,
1106 this,
1107 fullEnclosures: false);
1108
1109 for (int i = 0; i < sprites.Count; i++)
1110 {
1111 var sprite = sprites[i];
1112
1113 if (sprite is null)
1114 continue;
1115
1116 if (!sprite.VisualBoundsWorld.IntersectsWith(queryRect))
1117 continue;
1118
1119 list.Add(sprite);
1120 hasNonGridDrawables = true;
1121 }
1122
1123 // 3) DirectDrawing instances
1124 var drawings = DirectDrawingManager.Instance.GetDrawingsForLayer(this);
1125
1126 for (int i = 0; i < drawings.Count; i++)
1127 {
1128 var drawing = drawings[i];
1129
1130 if (!drawing.Visible)
1131 continue;
1132
1133 if (drawing.Mode != DirectDrawingMode.SceneLayer)
1134 continue;
1135
1136 if (!drawing.WorldBounds.IntersectsWith(worldRect))
1137 continue;
1138
1139 list.Add(drawing);
1140 hasNonGridDrawables = true;
1141 }
1142
1143 // Projection-specific render queries are emitted in fixed-tile depth order.
1144 // Per-tile Z differences or geometry-changing transforms still fall back to
1145 // verification/sort so the optimization cannot change rendering semantics.
1146 bool gridOrderGuaranteed =
1147 renderTiles.IsRenderOrdered &&
1148 uniformGridZOrder;
1149
1150 long sortStartTick = collectSortDiagnostics ? HighResTimer.GetCurrentTick() : 0;
1151
1152 if (hasNonGridDrawables)
1153 {
1154 list.Sort(CompareDrawables);
1155 }
1156 else if (!gridOrderGuaranteed && !IsSorted(list, CompareDrawables))
1157 {
1158 list.Sort(CompareDrawables);
1159 }
1160
1161 sortTicks = collectSortDiagnostics
1162 ? Math.Max(0, HighResTimer.GetCurrentTick() - sortStartTick)
1163 : 0;
1164
1165 return list;
1166 }
1167
1168 private List<IDrawable> GetWrappedDrawables(
1169 Rectangle worldRect,
1170 bool collectSortDiagnostics,
1171 out long sortTicks)
1172 {
1173 var period = GetPeriod();
1174 var instances = new List<IDrawable>();
1175
1176 void Add(IDrawable drawable, RectangleF bounds)
1177 {
1178 if (!drawable.Visible)
1179 return;
1180
1181 foreach (var offset in period.Offsets(bounds, worldRect))
1182 {
1183 if (instances.Count >= 1_000_000)
1184 throw new InvalidOperationException("Too many visible wrapped instances.");
1185
1186 instances.Add(new WrappedDrawable(drawable, this, offset));
1187 }
1188 }
1189
1190 // Inspect actual artwork bounds, including overhang, rather than assuming
1191 // a tile-sized margin can enclose all content.
1192 foreach (var tile in _sceneLayerTileArray)
1193 if (tile is not null)
1194 Add(tile, tile.DrawLocationWorld);
1195
1196 foreach (var sprite in SpriteManager.Instance.AllSprites)
1197 if (ReferenceEquals(sprite.SceneLayer, this))
1198 Add(sprite, sprite.VisualBoundsWorld);
1199
1200 foreach (var drawing in DirectDrawingManager.Instance.GetDrawingsForLayer(this))
1201 if (drawing.Mode == DirectDrawingMode.SceneLayer)
1202 Add(drawing, drawing.WorldBounds);
1203
1204 long sortStartTick = collectSortDiagnostics ? HighResTimer.GetCurrentTick() : 0;
1205 instances.Sort(CompareWrappedDrawables);
1206
1207 sortTicks = collectSortDiagnostics
1208 ? Math.Max(0, HighResTimer.GetCurrentTick() - sortStartTick)
1209 : 0;
1210
1211 return instances;
1212 }
1213
1214 private bool HasRenderableTileContent(SceneLayerTile tile)
1215 {
1216 // Derived tiles may provide custom Draw behavior even without a frame.
1217 if (tile.GetType() != typeof(SceneLayerTile))
1218 return true;
1219
1220 if (tile.CurrentFrame.Tilesheet is not null)
1221 return true;
1222
1223 // Empty cells still participate when a diagnostic/post-draw overlay needs
1224 // their geometry.
1225 return tile.EnableFog ||
1226 ShowGridLines ||
1227 (ShowCollisionBoxes && tile.CollisionsEnabled);
1228 }
1229
1230 private static bool IsSorted(
1231 List<IDrawable> drawables,
1232 Comparison<IDrawable> comparison)
1233 {
1234 for (int i = 1; i < drawables.Count; i++)
1235 {
1236 if (comparison(drawables[i - 1], drawables[i]) > 0)
1237 return false;
1238 }
1239
1240 return true;
1241 }
1242
1243 private static int CompareWrappedDrawables(IDrawable a, IDrawable b)
1244 {
1245 var x = (WrappedDrawable)a;
1246 var y = (WrappedDrawable)b;
1247 int z = a.ZOrder.CompareTo(b.ZOrder);
1248
1249 if (z != 0)
1250 return z;
1251
1252 if (x.Owner is Tile ta && y.Owner is Tile tb)
1253 {
1254 if (ta.IsPositionFixed != tb.IsPositionFixed)
1255 return ta.IsPositionFixed ? -1 : 1;
1256
1257 float ay =
1258 (ta.IsPositionFixed
1259 ? ta.DrawLocationWorld.Top + ta.Overhang.Top
1260 : ta.DrawLocationWorld.Bottom - ta.Overhang.Bottom - 1) +
1261 x.Offset.Y;
1262
1263 float by =
1264 (tb.IsPositionFixed
1265 ? tb.DrawLocationWorld.Top + tb.Overhang.Top
1266 : tb.DrawLocationWorld.Bottom - tb.Overhang.Bottom - 1) +
1267 y.Offset.Y;
1268
1269 int depth = ay.CompareTo(by);
1270
1271 if (depth != 0)
1272 return depth;
1273
1274 int horizontal =
1275 (ta.DrawLocationWorld.Left + x.Offset.X)
1276 .CompareTo(tb.DrawLocationWorld.Left + y.Offset.X);
1277
1278 if (horizontal != 0)
1279 return horizontal;
1280 }
1281
1282 int identity = a.Id.CompareTo(b.Id);
1283
1284 return identity != 0
1285 ? identity
1286 : (x.Offset.Y, x.Offset.X).CompareTo((y.Offset.Y, y.Offset.X));
1287 }
1288
1289 private static int CompareDrawables(IDrawable a, IDrawable b)
1290 {
1291 int z = a.ZOrder.CompareTo(b.ZOrder);
1292
1293 if (z != 0)
1294 return z;
1295
1296 if (a is Tile ta && b is Tile tb)
1297 return ta.CompareTo(tb);
1298
1299 return a.Id.CompareTo(b.Id);
1300 }
1301
1302 #endregion private methods
1303
1304 #region indexers
1305
1320 public SceneLayerTile? this[int x, int y] => GetIndexer_NoWrap(x, y);
1321
1334 public SceneLayerTile? this[Point pt] => this[pt.X, pt.Y];
1335
1352 public SceneLayerTile? this[PointF ptF] => this[(int)ptF.X, (int)ptF.Y];
1353
1354 private SceneLayerTile? GetIndexer_NoWrap(int x, int y)
1355 {
1356 if (x > _sceneLayerTileArray.GetUpperBound(0)
1357 || y > _sceneLayerTileArray.GetUpperBound(1)
1358 || x < 0
1359 || y < 0)
1360 return null;
1361 else
1362 return _sceneLayerTileArray[x, y];
1363 }
1364
1365 #endregion indexers
1366
1367 #region IEnumerable Members
1368
1378 public IEnumerator GetEnumerator() => ((IEnumerable<SceneLayerTile>)this).GetEnumerator();
1379
1390 IEnumerator<SceneLayerTile> IEnumerable<SceneLayerTile>.GetEnumerator()
1391 {
1392 for (int x = 0; x <= _sceneLayerTileArray.GetUpperBound(0); x++)
1393 {
1394 for (int y = 0; y <= _sceneLayerTileArray.GetUpperBound(1); y++)
1395 {
1396 yield return _sceneLayerTileArray[x, y];
1397 }
1398 }
1399 }
1400
1401 #endregion IEnumerable Members
1402
1403 #region IDisposable Members
1404
1427 public virtual void Dispose()
1428 {
1429 GC.SuppressFinalize(this);
1430
1431 Disposing?.Invoke(this);
1432
1433 foreach (SceneLayerTile gridPt in this)
1434 gridPt.Dispose();
1435
1436 // cancel all subscriptions to this object
1438 VisibleChanged = null;
1439 WrappingChanged = null;
1440 Disposing = null;
1441 }
1442
1443 #endregion IDisposable Members
1444
1445 #region empty SceneLayer
1446
1470 public static SceneLayer Empty { get; } = new EmptySceneLayer();
1471
1472 private sealed class EmptySceneLayer : SceneLayer
1473 {
1474 internal EmptySceneLayer()
1475 : base(
1476 columnCount: 0,
1477 rowCount: 0,
1478 width: 1,
1479 height: 1)
1480 {
1481 Visible = false;
1482 ZOrder = int.MinValue;
1483 Parallax = 1f;
1484 }
1485 }
1486
1487 #endregion empty SceneLayer
1488}
Manages registration and querying of colliders, separating them into static and dynamic collections f...
Manages collision group definitions and provides bitwise mask values for collision filtering....
CollisionProfile Get(string name)
Gets a previously defined profile.
Represents the values stored at a single location on a SceneLayer.
override void Dispose()
Releases the resources owned by this instance.
Represents a single layer within a Scene, containing a grid of tiles and supporting various coordinat...
Definition SceneLayer.cs:40
IEnumerator GetEnumerator()
Returns an enumerator that iterates through the layer's tiles.
SceneLayerTile? GetAdjacentTile(SceneLayerTile tile, CardinalDirections direction)
Returns the neighboring tile in the given direction, or null if the direction would move off the laye...
bool WrapVertically
Gets or sets a value indicating whether this layer repeats along its row axis at the grid boundaries.
CollisionGroupRegistry CollisionGroups
Gets the registry of collision groups used to organize and manage collision detection within the scen...
bool Visible
Gets or sets a value indicating whether this layer should be rendered.
virtual RectangleF GetLayerBoundsPx()
Computes the world-space pixel bounding rectangle for this SceneLayer. This uses the coordinate syste...
PointF WrapGrid(PointF grid)
Resolves a virtual grid coordinate to canonical coordinates on enabled wrapping axes....
SceneLayerTile[,] SceneLayerTileArray
Gets the two-dimensional array of tiles that comprise this layer's grid.
Action< SceneLayer >? ShowGridLinesChanged
Occurs when the grid line display setting changes.
Definition SceneLayer.cs:82
Point OriginPx
Gets or sets the world-space pixel origin of this layer's (0,0) tile position.
void SetTileSize(int newWidth, int newHeight)
Sets both the width and height of tiles in this layer atomically, raising only a single SceneLayerTil...
string ID
Gets or sets the unique identifier for this layer.
Action< SceneLayer >? SceneLayerTileSizeChanged
Occurs when the tile dimensions of this layer change.
Definition SceneLayer.cs:52
IEnumerable< PointF > GetWrappedOffsets(RectangleF contentBounds, RectangleF queryBounds)
Returns world-space translations of a canonical content rectangle that intersect a query rectangle....
CoordinateSystemTypes CoordinateSystemType
Gets or sets the coordinate system type used by this layer for transforming between grid coordinates ...
bool WrapHorizontally
Gets or sets a value indicating whether this layer repeats along its column axis at the grid boundari...
ColliderRegistry ColliderRegistry
Gets the collision world associated with this scene, used for physics and collision detection.
bool ShowGridLines
Gets or sets a value indicating whether grid lines should be rendered over this layer for debugging.
PointF WorldPxToGrid(PointF worldPx)
Converts a world-space pixel position into this layer's grid coordinates. This uses the layer's activ...
int GridRowCount
Gets the number of rows (tiles high) in this layer's grid.
int TileHeight
Gets or sets the height of each tile in this layer, measured in pixels.
PointF WorldPxToContinuousGrid(PointF worldPx)
Inverts the drawable anchor projection, retaining fractional coordinates even on hex layers.
TypedValueBag ValueBag
Gets the extensible value bag for storing arbitrary layer-specific metadata.
string DefaultTileCollisionProfile
Gets or sets the scene collision profile applied to fixed tiles on this layer. The default is Collisi...
SceneLayerTile? ResolveWrappedTile(int column, int row)
Resolves a virtual grid cell to its canonical tile. Only enabled axes wrap; an out-of-range disabled ...
PointF GridToWorldPx(PointF grid)
Converts a grid coordinate (col,row) into the projection-defined world-space pixel anchor for that ti...
Action< SceneLayer >? VisibleChanged
Occurs when the visibility state of this layer changes.
Definition SceneLayer.cs:62
int GridColumnCount
Gets the number of columns (tiles wide) in this layer's grid.
Action< SceneLayer >? ParallaxChanged
Occurs when the parallax scrolling factor of this layer changes.
Scene Scene
Gets or sets the parent scene that contains this layer.
float Parallax
Gets or sets the parallax scrolling factor for this layer.
int ZOrder
Gets or sets the z-order (rendering depth) of this layer within its parent scene.
Action< SceneLayer >? WrappingChanged
Occurs when the wrapping configuration of this layer changes.
Definition SceneLayer.cs:72
Action< SceneLayer >? ZOrderChanged
Occurs when the z-order (rendering depth) of this layer changes.
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...
virtual void Dispose()
Releases all resources used by the SceneLayer and disposes all tiles.
static SceneLayer Empty
Gets the singleton empty scene layer instance.
Action< SceneLayer >? OriginPxChanged
Occurs when the world-space origin point of this layer changes.
Action< SceneLayer >? Disposing
Occurs when this layer is being disposed.
Action< SceneLayer >? ShowCollisionBoxesChanged
Occurs when the collision box display setting changes.
Definition SceneLayer.cs:92
Represents a game scene containing multiple layers of tiles, sprites, and game objects....
Definition Scene.cs:35
CollisionProfileRegistry CollisionProfiles
Gets the named collision-filtering profiles used by layers and sprites in this scene....
Definition Scene.cs:335
A flexible, strongly-typed value container intended for runtime-attached metadata and ephemeral engin...
bool Visible
Gets a value indicating whether the object is visible.
Definition IDrawable.cs:28
Guid Id
Auto-assigned unique identifier for the object.
Definition IDrawable.cs:18
int ZOrder
Gets the z-order of the element, which determines its visual stacking order relative to other element...
Definition IDrawable.cs:34
CardinalDirections
Represents the eight cardinal and intercardinal directions of the compass.
CoordinateSystemTypes
Identifies the layout and math rules used to map tiles to world pixels and world pixels back to grid ...
@ ObliqueRight
Oblique projection using a right-receding, sheared square lattice. Numeric value 5 is retained for co...
@ Orthogonal
Axis-aligned square grid (Cartesian lattice).
@ HexAxialFlatTop
Hexagonal grid using axial coordinates with flat-topped hexes.
@ HexAxialPointedTop
Hexagonal grid using axial coordinates with pointy-topped hexes.
@ IsometricAxial
Isometric projection using an underlying square lattice with diagonal basis vectors.
@ ObliqueLeft
Oblique projection using a left-receding, sheared square lattice.
@ IsometricRhombic
Isometric projection using a rhombic (diamond) lattice.
DirectDrawingMode
Specifies where direct drawing operations are applied within the rendering pipeline.
@ 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.
EffectDirection
Specifies the direction in which a directional display effect travels.