1using System.Collections.ObjectModel;
30 private static readonly
object _parentSyncRoot =
new();
32 private static readonly Dictionary<IDirectCompositeChild, DirectComposite> _parents =
33 new(ReferenceEqualityComparer.Instance);
35 private readonly List<IDirectCompositeChild> _children = [];
37 private readonly Dictionary<IDirectCompositeChild, Vector2> _localOffsetPx =
38 new(ReferenceEqualityComparer.Instance);
40 private readonly ReadOnlyCollection<IDirectCompositeChild> _readOnlyChildren;
42 private PointF _anchor;
43 private long _lastTick = HighResTimer.GetCurrentTick();
44 private bool _disposed;
51 public event EventHandler<IDirectDrawable>?
Disposing;
67 PointF anchor =
default,
68 string? nickname =
null)
70 RenderSurfaceHost = renderSurfaceHost ??
throw new ArgumentNullException(nameof(renderSurfaceHost));
76 _readOnlyChildren =
new ReadOnlyCollection<IDirectCompositeChild>(_children);
83 #endregion constructors
85 #region public properties
90 public Guid
Id {
get; } = Guid.NewGuid();
131 public ReadOnlyCollection<IDirectCompositeChild>
Children => _readOnlyChildren;
148 get => _children.Any(
static child => child.Visible);
168 public Rectangle
ScreenBounds => GetBounds(
static child => child.ScreenBounds);
173 public Rectangle
WorldBounds => GetBounds(
static child => child.WorldBounds);
175 #endregion public properties
177 #region public methods
202 ObjectDisposedException.ThrowIf(_disposed,
this);
204 _anchor =
new PointF(x, y);
205 var anchor =
new Vector2(x, y);
209 Vector2 offset = _localOffsetPx.TryGetValue(child, out Vector2 value) ? value : Vector2.Zero;
238 bool keepCurrentOffset =
true,
239 Vector2? explicitLocalOffsetPx =
null)
241 ObjectDisposedException.ThrowIf(_disposed,
this);
242 ArgumentNullException.ThrowIfNull(child);
244 if (_children.Contains(child))
247 ValidateChildIdentity(child);
248 ValidateParentRelationship(child);
249 ValidateAndAssignTarget(child);
251 Vector2 offset = keepCurrentOffset
252 ? child.
GetPosition() -
new Vector2(_anchor.X, _anchor.Y)
253 : explicitLocalOffsetPx ?? Vector2.Zero;
255 RegisterParent(child);
259 _children.Add(child);
260 _localOffsetPx[child] = offset;
261 child.Disposing += OnChildDisposing;
263 child.
SetPosition(
new Vector2(_anchor.X, _anchor.Y) + offset);
269 child.Disposing -= OnChildDisposing;
270 _children.Remove(child);
271 _localOffsetPx.Remove(child);
272 UnregisterParent(child);
273 ResetTargetWhenEmpty();
287 ObjectDisposedException.ThrowIf(_disposed,
this);
288 ArgumentNullException.ThrowIfNull(child);
290 if (!_children.Remove(child))
293 child.Disposing -= OnChildDisposing;
294 _localOffsetPx.
Remove(child);
295 UnregisterParent(child);
296 ResetTargetWhenEmpty();
309 ObjectDisposedException.ThrowIf(_disposed,
this);
315 child.Disposing -= OnChildDisposing;
316 UnregisterParent(child);
320 _localOffsetPx.Clear();
321 ResetTargetWhenEmpty();
337 Vector2 newLocalOffsetPx)
339 ObjectDisposedException.ThrowIf(_disposed,
this);
340 ArgumentNullException.ThrowIfNull(child);
342 if (!_children.Contains(child))
345 _localOffsetPx[child] = newLocalOffsetPx;
347 child.
SetPosition(
new Vector2(_anchor.X, _anchor.Y) + newLocalOffsetPx);
398 child.
FadeTo(targetOpacity, durationSec);
424 ArgumentNullException.ThrowIfNull(view);
428 return RectangleF.Empty;
431 float minX =
float.MaxValue;
432 float minY =
float.MaxValue;
433 float maxX =
float.MinValue;
434 float maxY =
float.MinValue;
446 minX = Math.Min(minX, bounds.Left);
447 minY = Math.Min(minY, bounds.Top);
448 maxX = Math.Max(maxX, bounds.Right);
449 maxY = Math.Max(maxY, bounds.Bottom);
452 if (minX ==
float.MaxValue)
453 return RectangleF.Empty;
455 return RectangleF.FromLTRB(
456 (
float)Math.Floor(minX),
457 (
float)Math.Floor(minY),
458 (
float)Math.Ceiling(maxX),
459 (
float)Math.Ceiling(maxY));
479 if (_disposed || tick <= _lastTick)
483 HighResTimer.GetDuration(_lastTick, tick));
507 child.Disposing -= OnChildDisposing;
508 UnregisterParent(child);
512 _localOffsetPx.Clear();
513 ResetTargetWhenEmpty();
516 GC.SuppressFinalize(
this);
519 #endregion public methods
521 #region IDirectCompositeChild explicit interface implementations
531 #endregion IDirectCompositeChild explicit interface implementations
533 #region IDirectCompositeContainer explicit interface implementations
539 bool keepCurrentOffset,
540 Vector2? explicitLocalOffsetPx)
542 return Add(child, keepCurrentOffset, explicitLocalOffsetPx);
545 IDirectCompositeContainer IDirectCompositeContainer.
Remove(IDirectCompositeChild child)
550 IDirectCompositeContainer IDirectCompositeContainer.
Clear()
555 #endregion IDirectCompositeContainer explicit interface implementations
557 #region protected hooks
581 #endregion protected hooks
583 #region private methods
585 private Rectangle GetBounds(Func<IDirectCompositeChild, Rectangle> selector)
587 float minX =
float.MaxValue;
588 float minY =
float.MaxValue;
589 float maxX =
float.MinValue;
590 float maxY =
float.MinValue;
597 Rectangle bounds = selector(child);
602 minX = Math.Min(minX, bounds.Left);
603 minY = Math.Min(minY, bounds.Top);
604 maxX = Math.Max(maxX, bounds.Right);
605 maxY = Math.Max(maxY, bounds.Bottom);
608 if (minX ==
float.MaxValue)
609 return Rectangle.Empty;
611 return Rectangle.FromLTRB(
612 (
int)Math.Floor(minX),
613 (
int)Math.Floor(minY),
614 (
int)Math.Ceiling(maxX),
615 (
int)Math.Ceiling(maxY));
618 private void ValidateChildIdentity(IDirectCompositeChild child)
622 throw new ArgumentException(
623 "The child must belong to the same RenderSurfaceHost as the composite.",
627 if (child.Mode !=
Mode)
629 throw new ArgumentException(
630 $
"The child drawing mode '{child.Mode}' does not match the composite drawing mode '{Mode}'.",
635 private void ValidateAndAssignTarget(IDirectCompositeChild child)
639 SceneLayer childLayer = child.SceneLayer ??
throw new ArgumentException(
640 "A scene-layer child must reference a SceneLayer.",
647 else if (!ReferenceEquals(
SceneLayer, childLayer))
649 throw new ArgumentException(
650 "All scene-layer children in a composite must reference the same SceneLayer.",
657 if (child.View is
null)
660 compositeChild.Children.Count == 0)
662 throw new ArgumentException(
663 "An empty composite cannot be added in view mode because it has no View yet. Add at least one descendant first.",
667 throw new ArgumentException(
"A view child must reference a View.", nameof(child));
670 View childView = child.View;
676 else if (!ReferenceEquals(
View, childView))
678 throw new ArgumentException(
679 "All view children in a composite must reference the same View.",
684 private void ValidateParentRelationship(IDirectCompositeChild child)
686 lock (_parentSyncRoot)
690 throw new InvalidOperationException(
691 $
"The child already belongs to composite '{existingParent.Nickname}'.");
699 while (ancestor is not
null)
701 if (ReferenceEquals(ancestor, childComposite))
703 throw new InvalidOperationException(
"Adding the child would create a recursive composite cycle.");
706 _parents.TryGetValue(ancestor, out ancestor);
711 private void RegisterParent(IDirectCompositeChild child)
713 lock (_parentSyncRoot)
714 _parents.Add(child,
this);
717 private void UnregisterParent(IDirectCompositeChild child)
719 lock (_parentSyncRoot)
722 ReferenceEquals(parent,
this))
724 _parents.Remove(child);
729 private void ResetTargetWhenEmpty()
731 if (_children.Count != 0)
738 private void OnChildDisposing(
object? sender, IDirectDrawable drawing)
740 if (drawing is not IDirectCompositeChild child)
743 child.Disposing -= OnChildDisposing;
745 if (!_children.Remove(child))
748 _localOffsetPx.Remove(child);
749 UnregisterParent(child);
750 ResetTargetWhenEmpty();
755 #endregion private methods
bool Visible
Gets or sets the visibility of all descendants.
DirectComposite SetPosition(float x, float y)
Sets the composite anchor and repositions all children from their stored offsets.
virtual DirectComposite Remove(IDirectCompositeChild child)
Removes a child without disposing it.
string? Nickname
Gets the optional diagnostic nickname of the composite.
virtual void OnChildAdded(IDirectCompositeChild child)
Called after a child has been successfully added.
ReadOnlyCollection< IDirectCompositeChild > Children
Gets the children owned by the composite.
virtual void OnChildRemoved(IDirectCompositeChild child)
Called after a child has been removed from the composite.
DirectComposite FadeIn(float durationSec)
Fades every descendant to full opacity.
RenderSurfaceHostBase RenderSurfaceHost
Gets the render surface host shared by the composite and its children.
SceneLayer? SceneLayer
Gets the scene layer shared by all children in scene-layer mode.
DirectComposite SetZOrder(int zOrder)
Applies one Z-order to every descendant.
virtual void Update(long tick)
Advances composite movement.
DirectComposite FadeTo(float targetOpacity, float durationSec)
Fades every descendant to the requested opacity.
RectangleF GetDrawLocationScreen(View view)
Gets the union of all visible descendants as projected through a view.
DirectComposite FadeOut(float durationSec)
Fades every descendant to zero opacity.
DirectComposite SetOpacity(float opacity)
Applies one opacity to every descendant.
DirectComposite SetLocalOffset(IDirectCompositeChild child, Vector2 newLocalOffsetPx)
Changes one child's local offset and reapplies its position.
DirectComposite SetIsVisible(bool visible)
Applies one visibility value to every descendant.
Rectangle WorldBounds
Gets the union of all visible descendants' world-space bounds.
EventHandler< IDirectDrawable >? Disposing
Occurs when the composite is being disposed.
Guid Id
Gets the unique identifier of the composite.
Rectangle ScreenBounds
Gets the union of all visible descendants' screen-space bounds.
int ZOrder
Gets the composite Z-order.
virtual DirectComposite Clear()
Removes every child without disposing them.
View? View
Gets the view shared by all children in view mode.
virtual void Dispose()
Disposes the composite and every child it owns.
MovementController Movement
Gets the movement controller used to move the composite anchor.
DirectComposite(RenderSurfaceHostBase renderSurfaceHost, DirectDrawingMode mode, PointF anchor=default, string? nickname=null)
Initializes a new instance of the DirectComposite class.
void Draw(BackbufferBase backbuffer, RectangleF destRectScreen)
Performs no direct rendering because descendants render independently.
Vector2 GetPosition()
Gets the current composite anchor.
MovementSpace PositionSpace
Gets the coordinate space used by the movement controller.
virtual DirectComposite Add(IDirectCompositeChild child, bool keepCurrentOffset=true, Vector2? explicitLocalOffsetPx=null)
Adds a composite-compatible direct drawable as a child.
void SetPosition(Vector2 position)
Sets the composite anchor and repositions all children from their stored offsets.
DirectDrawingMode Mode
Gets the coordinate mode shared by the composite and its children.
Manages the lifecycle, registration, and retrieval of all direct drawing objects in the Gondwana engi...
static DirectDrawingManager Instance
Gets the singleton instance of the direct drawing manager.
Central controller responsible for managing all movement modes for a single IMovable object....
Represents a base class for managing a graphical backbuffer, and is the in-memory surface where rende...
Represents a base class for hosting a render surface, providing functionality for managing rendering ...
Defines a movable direct drawable that may be owned by a DirectComposite.
void FadeTo(float targetOpacity, float durationSec)
Fades this child to the requested opacity.
void SetIsVisible(bool visible)
Applies a visibility value to this child.
void SetZOrder(int zOrder)
Applies a Z-order value to this child.
void SetOpacity(float opacity)
Applies an opacity value to this child.
Defines a container that can hold and manage a collection of direct composite children.
IDirectCompositeContainer Add(IDirectCompositeChild child, bool keepCurrentOffset=true, Vector2? explicitLocalOffsetPx=null)
Adds a child element to this container.
IReadOnlyCollection< IDirectCompositeChild > Children
Gets the read-only collection of child elements in this container.
IDirectCompositeContainer Remove(IDirectCompositeChild child)
Removes a child element from this container.
IDirectCompositeContainer Clear()
Removes all child elements from this container.
bool Visible
Gets a value indicating whether the object is visible.
RectangleF GetDrawLocationScreen(View view)
Computes the object's destination rectangle in SCREEN pixels for rendering on the Backbuffer,...
Vector2 GetPosition()
Get the current position in the mover's PositionSpace.
void SetPosition(Vector2 pos)
Set the position in the mover's PositionSpace.
DirectDrawingMode
Specifies where direct drawing operations are applied within the rendering pipeline.
MovementSpace
Specifies the coordinate system used for movement calculations and updates.
Represents the current motion state of an IMovable object, including velocity, acceleration,...