1using System.Collections;
2using System.Collections.ObjectModel;
33[JsonObject(IsReference =
true)]
34public class Scene : IEnumerable<SceneLayer>, IDisposable
36 [Newtonsoft.Json.JsonIgnore]
internal DefinitionProvenance? DefinitionProvenance {
get;
set; }
38 [JsonProperty(
"SceneLayers")]
private readonly List<SceneLayer> _sceneLayers = [];
42#pragma warning disable IDE0051
43 [JsonProperty(
"_sceneLayers")]
44 private List<SceneLayer>? LegacySceneLayers
48 if (value is
null || _sceneLayers.Count != 0)
51 foreach (var sceneLayer
in value)
53 _sceneLayers.Add(sceneLayer);
59#pragma warning restore IDE0051
61 [JsonIgnore]
private readonly
object _renderSurfaceHostSync =
new();
97 #endregion Scene events
99 #region constructors / finalizer
111 _sceneLayers =
new List<SceneLayer>();
124 List<SceneLayer>? sceneLayers,
129 _sceneLayers = sceneLayers ??
new List<SceneLayer>();
130 ID =
string.IsNullOrWhiteSpace(
id) ? Guid.NewGuid().ToString() : id;
154 SetSceneLayerEventDelegates();
156 foreach (var sceneLayer
in _sceneLayers)
162 if (
this is not EmptyScene)
163 _allScenes.Add(
this);
166 #endregion constructors / finalizer
168 #region public properties
194 public string ID {
get;
protected internal set; } = Guid.NewGuid().ToString();
205 public int Count => _sceneLayers?.Count ?? 0;
219 lock (_renderSurfaceHostSync)
220 return _boundRenderSurfaceHost;
229 internal bool UsesDirtyRegionRendering => BoundRenderSurfaceHost?.
Backbuffer.IsGlThreadRendered !=
true;
265 public ReadOnlyCollection<SceneLayer>
SceneLayers => _sceneLayers.AsReadOnly();
267 private ReadOnlyCollection<SceneLayer>? _visibleSortedCache;
268 private bool _visibleSortedDirty =
true;
294 if (_visibleSortedDirty || _visibleSortedCache ==
null)
296 _visibleSortedCache = _sceneLayers
297 .Where(sl => sl.Visible)
298 .OrderBy(sl => sl.ZOrder)
302 _visibleSortedDirty =
false;
305 return _visibleSortedCache;
337 #endregion public properties
339 #region internal properties and methods
350 ArgumentNullException.ThrowIfNull(host);
354 if (ReferenceEquals(
this,
Empty))
357 lock (_renderSurfaceHostSync)
359 if (_boundRenderSurfaceHost is not
null &&
360 !ReferenceEquals(_boundRenderSurfaceHost, host))
362 throw new InvalidOperationException(
363 $
"Scene '{ID}' is already bound to another RenderSurfaceHost.");
366 _boundRenderSurfaceHost = host;
372 if (!UsesDirtyRegionRendering)
374 foreach (var layer
in _sceneLayers)
375 layer.RefreshQueue.ClearRefreshQueue();
384 internal void UnbindRenderSurfaceHost(RenderSurfaceHostBase host)
386 ArgumentNullException.ThrowIfNull(host);
388 if (ReferenceEquals(
this,
Empty))
391 lock (_renderSurfaceHostSync)
393 if (ReferenceEquals(_boundRenderSurfaceHost, host))
394 _boundRenderSurfaceHost =
null;
410 internal bool IsDirty
424 #endregion internal properties and methods
426 #region public methods
483 sceneLayer.ZOrder = zOrder;
485 _sceneLayers.Add(sceneLayer);
506 _sceneLayers.Add(sceneLayer);
532 foreach (var sceneLayer
in _sceneLayers.ToArray())
535 _sceneLayers.Clear();
556 _sceneLayers.Remove(sceneLayer);
576 foreach (var sceneLayer
in _sceneLayers)
578 if (sceneLayer.ID ==
id)
599 if (_sceneLayers.Count == 0)
600 return RectangleF.Empty;
602 RectangleF result = RectangleF.Empty;
603 bool hasBounds =
false;
605 foreach (var layer
in _sceneLayers)
607 var lb = layer.GetLayerBoundsPx();
619 result = RectangleF.Union(result, lb);
626 #endregion public methods
628 #region raise Scene events
652 sceneLayer.Scene =
this;
653 sceneLayer.ApplyDefaultTileCollisionProfile();
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;
666 _visibleSortedDirty =
true;
692 sceneLayer.Scene =
null;
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;
704 _visibleSortedDirty =
true;
718 #endregion raise handle Scene events
720 #region handle SceneLayer events
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;
732 private void SetSceneLayerEventDelegates()
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();
745 private void _SceneLayerVisibleChanged()
747 _visibleSortedDirty =
true;
765 #endregion handle SceneLayer events
781 public SceneLayer?
this[
int i] => (i >= 0 && i < _sceneLayers.Count) ? _sceneLayers[i] : null;
798 #region enumerable code
822 IEnumerator<SceneLayer> IEnumerable<SceneLayer>.GetEnumerator()
824 for (
int i = 0; i < _sceneLayers.Count; i++)
826 yield
return _sceneLayers[i];
830 #endregion enumerable code
832 #region IDisposable Members
859 GC.SuppressFinalize(
this);
865 _allScenes.Remove(
this);
873 #endregion IDisposable Members
875 #region static helpers
877 internal readonly
static List<Scene> _allScenes = [];
900 public static List<string>
GetAllSceneIDs() => _allScenes.FindAll(s => s !=
null).ConvertAll(s => s.ID);
914 public static ReadOnlyCollection<Scene>
GetAllScenes() => _allScenes.AsReadOnly();
932 var tmp =
new List<Scene>(_allScenes);
934 foreach (var scene
in tmp)
938 #endregion static helpers
963 private sealed class EmptyScene :
Scene
965 internal EmptyScene()
967 _sceneLayers.Clear();
971 SceneLayer.Empty.Scene =
this;
980 protected override void OnSceneLayerAdded(SceneLayer sceneLayer)
981 =>
throw new InvalidOperationException(
"Cannot add layers to Scene.Empty");
987 protected override void OnSceneLayerRemoved(SceneLayer sceneLayer)
1001 #endregion empty Scene
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...
static SceneLayer Empty
Gets the singleton empty scene layer instance.
Represents a game scene containing multiple layers of tiles, sprites, and game objects....
SceneLayer? GetSceneLayerByID(string id)
Retrieves a layer from this scene by its unique identifier.
virtual void OnSceneLayerAdded(SceneLayer sceneLayer)
Raises the SceneLayerAdded event and performs internal setup when a layer is added to the scene.
Scene()
Initializes a new instance of the Scene class with an empty layer collection.
Action< SceneLayer >? SceneLayerRemoved
Occurs when a SceneLayer is removed from this scene.
SceneLayer AddLayer(SceneLayer sceneLayer)
Adds an existing SceneLayer to this scene.
CollisionGroupRegistry CollisionGroups
Gets the registry of collision groups used to organize and manage collision detection within the scen...
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.
bool FullRefreshNeeded
Gets or sets a value indicating whether the entire scene needs to be refreshed on the next render.
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.
ReadOnlyCollection< SceneLayer > SceneLayers
Gets a read-only collection of all layers in this scene, in their current order.
ReadOnlyCollection< SceneLayer > VisibleSceneLayers
Gets a read-only collection of visible layers sorted by z-order for rendering.
virtual void OnSceneLayerRemoved(SceneLayer sceneLayer)
Raises the SceneLayerRemoved event and performs internal cleanup when a layer is removed from the sce...
static void ClearAllScenes()
Disposes all active scenes in the global scene collection, releasing all resources.
string ID
Gets or sets the unique identifier for this scene.
virtual void Dispose()
Releases all resources used by the Scene and removes it from the global scene collection.
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.
static Scene Empty
Gets the singleton empty scene instance.
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.
CollisionProfileRegistry CollisionProfiles
Gets the named collision-filtering profiles used by layers and sprites in this scene....
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.
void RemoveLayer(SceneLayer sceneLayer)
Removes the specified layer from this scene.
Action< Scene >? SceneDisposing
Occurs when this scene is being disposed.
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.
void RemoveAllLayers()
Removes all layers from this scene.
int Count
Gets the total number of layers in this scene, including hidden layers.
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 ...