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
Scene.cs
1using System.Collections;
2using System.Collections.ObjectModel;
3using System.Drawing;
9using Newtonsoft.Json;
10
11namespace Gondwana.Scenes;
12
33[JsonObject(IsReference = true)]
34public class Scene : IEnumerable<SceneLayer>, IDisposable
35{
36 [Newtonsoft.Json.JsonIgnore] internal DefinitionProvenance? DefinitionProvenance { get; set; }
37
38 [JsonProperty("SceneLayers")] private readonly List<SceneLayer> _sceneLayers = [];
39
40 // Read legacy state files that used the private field name without
41 // continuing to emit that implementation detail in new JSON.
42#pragma warning disable IDE0051 // Used by Newtonsoft.Json via reflection for legacy state.
43 [JsonProperty("_sceneLayers")]
44 private List<SceneLayer>? LegacySceneLayers
45 {
46 set
47 {
48 if (value is null || _sceneLayers.Count != 0)
49 return;
50
51 foreach (var sceneLayer in value)
52 {
53 _sceneLayers.Add(sceneLayer);
54 OnSceneLayerAdded(sceneLayer);
55 }
56 }
57 }
58
59#pragma warning restore IDE0051
60
61 [JsonIgnore] private readonly object _renderSurfaceHostSync = new();
62
63 [JsonIgnore] private RenderSurfaceHostBase? _boundRenderSurfaceHost;
64
65 #region Scene events
66
75 public event Action<SceneLayer>? SceneLayerAdded;
76
85 public event Action<SceneLayer>? SceneLayerRemoved;
86
95 public event Action<Scene>? SceneDisposing;
96
97 #endregion Scene events
98
99 #region constructors / finalizer
100
109 public Scene()
110 {
111 _sceneLayers = new List<SceneLayer>();
112 Init();
113 }
114
122 [JsonConstructor]
123 protected Scene(
124 List<SceneLayer>? sceneLayers,
125 string? id,
126 CollisionGroupRegistry? collisionGroups,
127 CollisionProfileRegistry? collisionProfiles)
128 {
129 _sceneLayers = sceneLayers ?? new List<SceneLayer>();
130 ID = string.IsNullOrWhiteSpace(id) ? Guid.NewGuid().ToString() : id;
131 CollisionGroups = collisionGroups ?? new CollisionGroupRegistry();
132 CollisionProfiles = collisionProfiles ?? new CollisionProfileRegistry();
133 ValueBag = new TypedValueBag();
134
135 Init();
136 }
137
147 ~Scene()
148 {
149 Dispose();
150 }
151
152 private void Init()
153 {
154 SetSceneLayerEventDelegates();
155
156 foreach (var sceneLayer in _sceneLayers)
157 OnSceneLayerAdded(sceneLayer);
158
159 // During static initialization the Empty property has not yet been assigned
160 // while the EmptyScene base constructor is running, so ReferenceEquals(this, Empty)
161 // is not a reliable discriminator here. Use the runtime type instead.
162 if (this is not EmptyScene)
163 _allScenes.Add(this);
164 }
165
166 #endregion constructors / finalizer
167
168 #region public properties
169
181 [JsonIgnore]
182 public TypedValueBag ValueBag { get; private set; } = new();
183
193 [JsonProperty]
194 public string ID { get; protected internal set; } = Guid.NewGuid().ToString();
195
204 [JsonIgnore]
205 public int Count => _sceneLayers?.Count ?? 0;
206
214 [JsonIgnore]
215 internal RenderSurfaceHostBase? BoundRenderSurfaceHost
216 {
217 get
218 {
219 lock (_renderSurfaceHostSync)
220 return _boundRenderSurfaceHost;
221 }
222 }
223
228 [JsonIgnore]
229 internal bool UsesDirtyRegionRendering => BoundRenderSurfaceHost?.Backbuffer.IsGlThreadRendered != true;
230
249 [JsonIgnore]
250 public bool FullRefreshNeeded { get; set; }
251
264 [JsonIgnore]
265 public ReadOnlyCollection<SceneLayer> SceneLayers => _sceneLayers.AsReadOnly();
266
267 private ReadOnlyCollection<SceneLayer>? _visibleSortedCache;
268 private bool _visibleSortedDirty = true;
269
289 [JsonIgnore]
290 public ReadOnlyCollection<SceneLayer> VisibleSceneLayers
291 {
292 get
293 {
294 if (_visibleSortedDirty || _visibleSortedCache == null)
295 {
296 _visibleSortedCache = _sceneLayers
297 .Where(sl => sl.Visible)
298 .OrderBy(sl => sl.ZOrder)
299 .ToList()
300 .AsReadOnly();
301
302 _visibleSortedDirty = false;
303 }
304
305 return _visibleSortedCache;
306 }
307 }
308
318 [JsonIgnore]
319 public int CountOfVisibleLayers => VisibleSceneLayers?.Count ?? 0;
320
327 [JsonProperty]
328 public CollisionGroupRegistry CollisionGroups { get; private set; } = new();
329
334 [JsonProperty]
335 public CollisionProfileRegistry CollisionProfiles { get; private set; } = new();
336
337 #endregion public properties
338
339 #region internal properties and methods
340
348 internal void BindRenderSurfaceHost(RenderSurfaceHostBase host)
349 {
350 ArgumentNullException.ThrowIfNull(host);
351
352 // Scene.Empty is a shared null-object placeholder and is never treated as an
353 // actively rendered scene for binding ownership purposes.
354 if (ReferenceEquals(this, Empty))
355 return;
356
357 lock (_renderSurfaceHostSync)
358 {
359 if (_boundRenderSurfaceHost is not null &&
360 !ReferenceEquals(_boundRenderSurfaceHost, host))
361 {
362 throw new InvalidOperationException(
363 $"Scene '{ID}' is already bound to another RenderSurfaceHost.");
364 }
365
366 _boundRenderSurfaceHost = host;
367 }
368
369 // A GPU host redraws the full frame and never consumes RefreshQueue. Remove
370 // anything accumulated before binding; future additions are rejected by the
371 // queue's scene-policy callback.
372 if (!UsesDirtyRegionRendering)
373 {
374 foreach (var layer in _sceneLayers)
375 layer.RefreshQueue.ClearRefreshQueue();
376 }
377 }
378
384 internal void UnbindRenderSurfaceHost(RenderSurfaceHostBase host)
385 {
386 ArgumentNullException.ThrowIfNull(host);
387
388 if (ReferenceEquals(this, Empty))
389 return;
390
391 lock (_renderSurfaceHostSync)
392 {
393 if (ReferenceEquals(_boundRenderSurfaceHost, host))
394 _boundRenderSurfaceHost = null;
395 }
396 }
397
410 internal bool IsDirty
411 {
412 get
413 {
414 for (int i = 0; i < CountOfVisibleLayers; i++)
415 {
416 if (VisibleSceneLayers[i].RefreshQueue.IsDirty)
417 return true;
418 }
419
420 return false;
421 }
422 }
423
424 #endregion internal properties and methods
425
426 #region public methods
427
467 int columnCount,
468 int rowCount,
469 int width = 32,
470 int height = 32,
471 int zOrder = 0,
472 float parallax = 1f,
473 CoordinateSystemTypes coordinateSystem = CoordinateSystemTypes.Orthogonal)
474 {
475 var sceneLayer = new SceneLayer(
476 columnCount,
477 rowCount,
478 width,
479 height,
480 parallax,
481 coordinateSystem);
482
483 sceneLayer.ZOrder = zOrder;
484
485 _sceneLayers.Add(sceneLayer);
486 OnSceneLayerAdded(sceneLayer);
487
488 FullRefreshNeeded = true;
489
490 return sceneLayer;
491 }
492
504 public SceneLayer AddLayer(SceneLayer sceneLayer)
505 {
506 _sceneLayers.Add(sceneLayer);
507 OnSceneLayerAdded(sceneLayer);
508 FullRefreshNeeded = true;
509 return sceneLayer;
510 }
511
526 public void RemoveAllLayers()
527 {
528 // Iterate a snapshot to avoid mutating the collection while raising
529 // removal events. Event handlers may call back into RemoveLayer which
530 // would otherwise modify _sceneLayers during enumeration and cause
531 // an ArgumentOutOfRangeException.
532 foreach (var sceneLayer in _sceneLayers.ToArray())
533 OnSceneLayerRemoved(sceneLayer);
534
535 _sceneLayers.Clear();
536
537 FullRefreshNeeded = true;
538 }
539
554 public void RemoveLayer(SceneLayer sceneLayer)
555 {
556 _sceneLayers.Remove(sceneLayer);
557 OnSceneLayerRemoved(sceneLayer);
558
559 FullRefreshNeeded = true;
560 }
561
574 public SceneLayer? GetSceneLayerByID(string id)
575 {
576 foreach (var sceneLayer in _sceneLayers)
577 {
578 if (sceneLayer.ID == id)
579 return sceneLayer;
580 }
581
582 return null;
583 }
584
597 public RectangleF GetWorldBoundsPx()
598 {
599 if (_sceneLayers.Count == 0)
600 return RectangleF.Empty;
601
602 RectangleF result = RectangleF.Empty;
603 bool hasBounds = false;
604
605 foreach (var layer in _sceneLayers)
606 {
607 var lb = layer.GetLayerBoundsPx();
608
609 if (lb.IsEmpty)
610 continue;
611
612 if (!hasBounds)
613 {
614 result = lb;
615 hasBounds = true;
616 }
617 else
618 {
619 result = RectangleF.Union(result, lb);
620 }
621 }
622
623 return result;
624 }
625
626 #endregion public methods
627
628 #region raise Scene events
629
650 protected virtual void OnSceneLayerAdded(SceneLayer sceneLayer)
651 {
652 sceneLayer.Scene = this;
653 sceneLayer.ApplyDefaultTileCollisionProfile();
654 SpriteManager.Instance.RefreshCollisionProfiles(sceneLayer);
655
656 sceneLayer.Disposing += sceneLayerDisposing;
657 sceneLayer.VisibleChanged += visChgDel;
658 sceneLayer.SceneLayerTileSizeChanged += sceneLayerTileSizeDel;
659 sceneLayer.WrappingChanged += wrappingDel;
660 sceneLayer.ShowGridLinesChanged += gridLinesShowChanged;
661 sceneLayer.ShowCollisionBoxesChanged += showCollisionBoxesChanged;
662 sceneLayer.ZOrderChanged += zOrderChangedDel;
663 sceneLayer.ParallaxChanged += parallaxChangedDel;
664 sceneLayer.OriginPxChanged += originPxChangedDel;
665
666 _visibleSortedDirty = true;
667 SceneLayerAdded?.Invoke(sceneLayer);
668 }
669
690 protected virtual void OnSceneLayerRemoved(SceneLayer sceneLayer)
691 {
692 sceneLayer.Scene = null;
693
694 sceneLayer.Disposing -= sceneLayerDisposing;
695 sceneLayer.VisibleChanged -= visChgDel;
696 sceneLayer.SceneLayerTileSizeChanged -= sceneLayerTileSizeDel;
697 sceneLayer.WrappingChanged -= wrappingDel;
698 sceneLayer.ShowGridLinesChanged -= gridLinesShowChanged;
699 sceneLayer.ShowCollisionBoxesChanged -= showCollisionBoxesChanged;
700 sceneLayer.ZOrderChanged -= zOrderChangedDel;
701 sceneLayer.ParallaxChanged -= parallaxChangedDel;
702 sceneLayer.OriginPxChanged -= originPxChangedDel;
703
704 _visibleSortedDirty = true;
705 SceneLayerRemoved?.Invoke(sceneLayer);
706 }
707
716 protected virtual void OnSceneDisposing() => SceneDisposing?.Invoke(this);
717
718 #endregion raise handle Scene events
719
720 #region handle SceneLayer events
721
722 private Action<SceneLayer> sceneLayerDisposing;
723 private Action<SceneLayer> visChgDel;
724 private Action<SceneLayer> sceneLayerTileSizeDel;
725 private Action<SceneLayer> wrappingDel;
726 private Action<SceneLayer> gridLinesShowChanged;
727 private Action<SceneLayer> showCollisionBoxesChanged;
728 private Action<SceneLayer> zOrderChangedDel;
729 private Action<SceneLayer> parallaxChangedDel;
730 private Action<SceneLayer> originPxChangedDel;
731
732 private void SetSceneLayerEventDelegates()
733 {
734 sceneLayerDisposing = (sceneLayer) => RemoveLayer(sceneLayer);
735 visChgDel = (sceneLayer) => _SceneLayerVisibleChanged();
736 sceneLayerTileSizeDel = (sceneLayer) => _SceneLayerTileSizeChanged();
737 wrappingDel = (sceneLayer) => _SceneLayerWrappingChanged();
738 gridLinesShowChanged = (sceneLayer) => _SceneLayerGridLinesShowChanged();
739 showCollisionBoxesChanged = (sceneLayer) => _SceneLayerShowCollisionBoxChanged();
740 zOrderChangedDel = (sceneLayer) => _SceneLayerZOrderChanged();
741 parallaxChangedDel = (sceneLayer) => _SceneLayerParallaxChanged();
742 originPxChangedDel = (sceneLayer) => _SceneLayerZeroPixelChanged();
743 }
744
745 private void _SceneLayerVisibleChanged()
746 {
747 _visibleSortedDirty = true;
748 FullRefreshNeeded = true;
749 }
750
751 private void _SceneLayerTileSizeChanged() => FullRefreshNeeded = true;
752
753 private void _SceneLayerWrappingChanged() => FullRefreshNeeded = true;
754
755 private void _SceneLayerGridLinesShowChanged() => FullRefreshNeeded = true;
756
757 private void _SceneLayerShowCollisionBoxChanged() => FullRefreshNeeded = true;
758
759 private void _SceneLayerZOrderChanged() => FullRefreshNeeded = true;
760
761 private void _SceneLayerParallaxChanged() => FullRefreshNeeded = true;
762
763 private void _SceneLayerZeroPixelChanged() => FullRefreshNeeded = true;
764
765 #endregion handle SceneLayer events
766
767 #region indexers
768
781 public SceneLayer? this[int i] => (i >= 0 && i < _sceneLayers.Count) ? _sceneLayers[i] : null;
782
794 public SceneLayer? this[string id] => GetSceneLayerByID(id);
795
796 #endregion indexers
797
798 #region enumerable code
799
809 public IEnumerator GetEnumerator() => ((IEnumerable<SceneLayer>)this).GetEnumerator();
810
822 IEnumerator<SceneLayer> IEnumerable<SceneLayer>.GetEnumerator()
823 {
824 for (int i = 0; i < _sceneLayers.Count; i++)
825 {
826 yield return _sceneLayers[i];
827 }
828 }
829
830 #endregion enumerable code
831
832 #region IDisposable Members
833
857 public virtual void Dispose()
858 {
859 GC.SuppressFinalize(this);
860
862
864
865 _allScenes.Remove(this);
866
867 // cancel all subscriptions to this object
868 SceneLayerAdded = null;
869 SceneLayerRemoved = null;
870 SceneDisposing = null;
871 }
872
873 #endregion IDisposable Members
874
875 #region static helpers
876
877 internal readonly static List<Scene> _allScenes = [];
878
890 public static Scene? GetSceneByID(string id) => _allScenes.Find(s => s.ID == id);
891
900 public static List<string> GetAllSceneIDs() => _allScenes.FindAll(s => s != null).ConvertAll(s => s.ID);
901
914 public static ReadOnlyCollection<Scene> GetAllScenes() => _allScenes.AsReadOnly();
915
930 public static void ClearAllScenes()
931 {
932 var tmp = new List<Scene>(_allScenes);
933
934 foreach (var scene in tmp)
935 scene.Dispose();
936 }
937
938 #endregion static helpers
939
940 #region empty Scene
941
961 public static Scene Empty { get; } = new EmptyScene();
962
963 private sealed class EmptyScene : Scene
964 {
965 internal EmptyScene()
966 {
967 _sceneLayers.Clear();
968
969 // Attach the singleton empty layer
970 _sceneLayers.Add(SceneLayer.Empty);
971 SceneLayer.Empty.Scene = this;
972
973 FullRefreshNeeded = false;
974 }
975
980 protected override void OnSceneLayerAdded(SceneLayer sceneLayer)
981 => throw new InvalidOperationException("Cannot add layers to Scene.Empty");
982
987 protected override void OnSceneLayerRemoved(SceneLayer sceneLayer)
988 {
989 // no-op
990 }
991
995 public override void Dispose()
996 {
997 // Intentionally empty - singleton
998 }
999 }
1000
1001 #endregion empty Scene
1002}
Manages the lifecycle, lookup, and per-frame updates of all active Sprite instances.
static SpriteManager Instance
Gets the singleton instance of the sprite manager.
Manages collision group definitions and provides bitwise mask values for collision filtering....
Stores named collision-filtering profiles for a scene. Profiles resolve their group names through the...
Represents a base class for hosting a render surface, providing functionality for managing rendering ...
BackbufferBase Backbuffer
Gets the in-memory BackbufferBase associated with the current rendering context.
Represents a single layer within a Scene, containing a grid of tiles and supporting various coordinat...
Definition SceneLayer.cs:40
static SceneLayer Empty
Gets the singleton empty scene layer instance.
Represents a game scene containing multiple layers of tiles, sprites, and game objects....
Definition Scene.cs:35
SceneLayer? GetSceneLayerByID(string id)
Retrieves a layer from this scene by its unique identifier.
Definition Scene.cs:574
virtual void OnSceneLayerAdded(SceneLayer sceneLayer)
Raises the SceneLayerAdded event and performs internal setup when a layer is added to the scene.
Definition Scene.cs:650
Scene()
Initializes a new instance of the Scene class with an empty layer collection.
Definition Scene.cs:109
Action< SceneLayer >? SceneLayerRemoved
Occurs when a SceneLayer is removed from this scene.
Definition Scene.cs:85
SceneLayer AddLayer(SceneLayer sceneLayer)
Adds an existing SceneLayer to this scene.
Definition Scene.cs:504
CollisionGroupRegistry CollisionGroups
Gets the registry of collision groups used to organize and manage collision detection within the scen...
Definition Scene.cs:328
static ? Scene GetSceneByID(string id)
Retrieves a scene from the global scene collection by its unique identifier.
TypedValueBag ValueBag
Gets the extensible value bag for storing arbitrary scene-specific metadata.
Definition Scene.cs:182
bool FullRefreshNeeded
Gets or sets a value indicating whether the entire scene needs to be refreshed on the next render.
Definition Scene.cs:250
static List< string > GetAllSceneIDs()
Gets a list of unique identifiers for all active scenes in the global scene collection.
Action< SceneLayer >? SceneLayerAdded
Occurs when a SceneLayer is added to this scene.
Definition Scene.cs:75
ReadOnlyCollection< SceneLayer > SceneLayers
Gets a read-only collection of all layers in this scene, in their current order.
Definition Scene.cs:265
ReadOnlyCollection< SceneLayer > VisibleSceneLayers
Gets a read-only collection of visible layers sorted by z-order for rendering.
Definition Scene.cs:291
virtual void OnSceneLayerRemoved(SceneLayer sceneLayer)
Raises the SceneLayerRemoved event and performs internal cleanup when a layer is removed from the sce...
Definition Scene.cs:690
static void ClearAllScenes()
Disposes all active scenes in the global scene collection, releasing all resources.
Definition Scene.cs:930
string ID
Gets or sets the unique identifier for this scene.
Definition Scene.cs:194
virtual void Dispose()
Releases all resources used by the Scene and removes it from the global scene collection.
Definition Scene.cs:857
static ReadOnlyCollection< Scene > GetAllScenes()
Gets a read-only collection of all active scenes in the global scene collection.
int CountOfVisibleLayers
Gets the number of currently visible layers in this scene.
Definition Scene.cs:319
static Scene Empty
Gets the singleton empty scene instance.
Definition Scene.cs:961
virtual void OnSceneDisposing()
Raises the SceneDisposing event when the scene is being disposed.
Scene(List< SceneLayer >? sceneLayers, string? id, CollisionGroupRegistry? collisionGroups, CollisionProfileRegistry? collisionProfiles)
Initializes a new instance of the Scene class from serialized state.
Definition Scene.cs:123
CollisionProfileRegistry CollisionProfiles
Gets the named collision-filtering profiles used by layers and sprites in this scene....
Definition Scene.cs:335
SceneLayer AddLayer(int columnCount, int rowCount, int width=32, int height=32, int zOrder=0, float parallax=1f, CoordinateSystemTypes coordinateSystem=CoordinateSystemTypes.Orthogonal)
Creates and adds a new SceneLayer to this scene with the specified properties.
Definition Scene.cs:466
void RemoveLayer(SceneLayer sceneLayer)
Removes the specified layer from this scene.
Definition Scene.cs:554
Action< Scene >? SceneDisposing
Occurs when this scene is being disposed.
Definition Scene.cs:95
IEnumerator GetEnumerator()
Returns an enumerator that iterates through the scene's layers.
RectangleF GetWorldBoundsPx()
Computes a world-space pixel bounding rectangle that encloses all layers in the scene.
Definition Scene.cs:597
void RemoveAllLayers()
Removes all layers from this scene.
Definition Scene.cs:526
int Count
Gets the total number of layers in this scene, including hidden layers.
Definition Scene.cs:205
A flexible, strongly-typed value container intended for runtime-attached metadata and ephemeral engin...
CoordinateSystemTypes
Identifies the layout and math rules used to map tiles to world pixels and world pixels back to grid ...