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
DirectComposite.cs
1using System.Collections.ObjectModel;
2using System.Drawing;
3using System.Numerics;
10
12
29{
30 private static readonly object _parentSyncRoot = new();
31
32 private static readonly Dictionary<IDirectCompositeChild, DirectComposite> _parents =
33 new(ReferenceEqualityComparer.Instance);
34
35 private readonly List<IDirectCompositeChild> _children = [];
36
37 private readonly Dictionary<IDirectCompositeChild, Vector2> _localOffsetPx =
38 new(ReferenceEqualityComparer.Instance);
39
40 private readonly ReadOnlyCollection<IDirectCompositeChild> _readOnlyChildren;
41
42 private PointF _anchor;
43 private long _lastTick = HighResTimer.GetCurrentTick();
44 private bool _disposed;
45
46 #region events
47
51 public event EventHandler<IDirectDrawable>? Disposing;
52
53 #endregion events
54
55 #region constructors
56
65 RenderSurfaceHostBase renderSurfaceHost,
67 PointF anchor = default,
68 string? nickname = null)
69 {
70 RenderSurfaceHost = renderSurfaceHost ?? throw new ArgumentNullException(nameof(renderSurfaceHost));
71
72 Mode = mode;
73 _anchor = anchor;
74 Nickname = nickname ?? Id.ToString();
75
76 _readOnlyChildren = new ReadOnlyCollection<IDirectCompositeChild>(_children);
77
78 Movement = new MovementController(this, MovementState.ForPixel());
79
80 DirectDrawingManager.Instance.AddOrReplace(this);
81 }
82
83 #endregion constructors
84
85 #region public properties
86
90 public Guid Id { get; } = Guid.NewGuid();
91
95 public string? Nickname { get; private set; }
96
101
105 public DirectDrawingMode Mode { get; }
106
114 public SceneLayer? SceneLayer { get; private set; }
115
123 public View? View { get; private set; }
124
131 public ReadOnlyCollection<IDirectCompositeChild> Children => _readOnlyChildren;
132
137
142
146 public bool Visible
147 {
148 get => _children.Any(static child => child.Visible);
149 set
150 {
151 foreach (IDirectCompositeChild child in _children)
152 child.SetIsVisible(value);
153 }
154 }
155
163 public int ZOrder => 0;
164
168 public Rectangle ScreenBounds => GetBounds(static child => child.ScreenBounds);
169
173 public Rectangle WorldBounds => GetBounds(static child => child.WorldBounds);
174
175 #endregion public properties
176
177 #region public methods
178
183 public Vector2 GetPosition() => new(_anchor.X, _anchor.Y);
184
189 public void SetPosition(Vector2 position)
190 {
191 SetPosition(position.X, position.Y);
192 }
193
200 public DirectComposite SetPosition(float x, float y)
201 {
202 ObjectDisposedException.ThrowIf(_disposed, this);
203
204 _anchor = new PointF(x, y);
205 var anchor = new Vector2(x, y);
206
207 foreach (IDirectCompositeChild child in _children)
208 {
209 Vector2 offset = _localOffsetPx.TryGetValue(child, out Vector2 value) ? value : Vector2.Zero;
210 child.SetPosition(anchor + offset);
211 }
212
213 return this;
214 }
215
236 public virtual DirectComposite Add(
238 bool keepCurrentOffset = true,
239 Vector2? explicitLocalOffsetPx = null)
240 {
241 ObjectDisposedException.ThrowIf(_disposed, this);
242 ArgumentNullException.ThrowIfNull(child);
243
244 if (_children.Contains(child))
245 return this;
246
247 ValidateChildIdentity(child);
248 ValidateParentRelationship(child);
249 ValidateAndAssignTarget(child);
250
251 Vector2 offset = keepCurrentOffset
252 ? child.GetPosition() - new Vector2(_anchor.X, _anchor.Y)
253 : explicitLocalOffsetPx ?? Vector2.Zero;
254
255 RegisterParent(child);
256
257 try
258 {
259 _children.Add(child);
260 _localOffsetPx[child] = offset;
261 child.Disposing += OnChildDisposing;
262
263 child.SetPosition(new Vector2(_anchor.X, _anchor.Y) + offset);
264
265 OnChildAdded(child);
266 }
267 catch
268 {
269 child.Disposing -= OnChildDisposing;
270 _children.Remove(child);
271 _localOffsetPx.Remove(child);
272 UnregisterParent(child);
273 ResetTargetWhenEmpty();
274 throw;
275 }
276
277 return this;
278 }
279
286 {
287 ObjectDisposedException.ThrowIf(_disposed, this);
288 ArgumentNullException.ThrowIfNull(child);
289
290 if (!_children.Remove(child))
291 return this;
292
293 child.Disposing -= OnChildDisposing;
294 _localOffsetPx.Remove(child);
295 UnregisterParent(child);
296 ResetTargetWhenEmpty();
297
298 OnChildRemoved(child);
299
300 return this;
301 }
302
307 public virtual DirectComposite Clear()
308 {
309 ObjectDisposedException.ThrowIf(_disposed, this);
310
311 IDirectCompositeChild[] children = [.. _children];
312
313 foreach (IDirectCompositeChild child in children)
314 {
315 child.Disposing -= OnChildDisposing;
316 UnregisterParent(child);
317 }
318
319 _children.Clear();
320 _localOffsetPx.Clear();
321 ResetTargetWhenEmpty();
322
323 foreach (IDirectCompositeChild child in children)
324 OnChildRemoved(child);
325
326 return this;
327 }
328
337 Vector2 newLocalOffsetPx)
338 {
339 ObjectDisposedException.ThrowIf(_disposed, this);
340 ArgumentNullException.ThrowIfNull(child);
341
342 if (!_children.Contains(child))
343 return this;
344
345 _localOffsetPx[child] = newLocalOffsetPx;
346
347 child.SetPosition(new Vector2(_anchor.X, _anchor.Y) + newLocalOffsetPx);
348
349 return this;
350 }
351
357 public DirectComposite SetZOrder(int zOrder)
358 {
359 foreach (IDirectCompositeChild child in _children)
360 child.SetZOrder(zOrder);
361
362 return this;
363 }
364
370 public DirectComposite SetOpacity(float opacity)
371 {
372 foreach (IDirectCompositeChild child in _children)
373 child.SetOpacity(opacity);
374
375 return this;
376 }
377
383 public DirectComposite SetIsVisible(bool visible)
384 {
385 Visible = visible;
386 return this;
387 }
388
395 public DirectComposite FadeTo(float targetOpacity, float durationSec)
396 {
397 foreach (IDirectCompositeChild child in _children)
398 child.FadeTo(targetOpacity, durationSec);
399
400 return this;
401 }
402
408 public DirectComposite FadeIn(float durationSec) => FadeTo(1f, durationSec);
409
415 public DirectComposite FadeOut(float durationSec) => FadeTo(0f, durationSec);
416
422 public RectangleF GetDrawLocationScreen(View view)
423 {
424 ArgumentNullException.ThrowIfNull(view);
425
426 if (Mode == DirectDrawingMode.View && !ReferenceEquals(View, view))
427 {
428 return RectangleF.Empty;
429 }
430
431 float minX = float.MaxValue;
432 float minY = float.MaxValue;
433 float maxX = float.MinValue;
434 float maxY = float.MinValue;
435
436 foreach (IDirectCompositeChild child in _children)
437 {
438 if (!child.Visible)
439 continue;
440
441 RectangleF bounds = child.GetDrawLocationScreen(view);
442
443 if (bounds.IsEmpty)
444 continue;
445
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);
450 }
451
452 if (minX == float.MaxValue)
453 return RectangleF.Empty;
454
455 return RectangleF.FromLTRB(
456 (float)Math.Floor(minX),
457 (float)Math.Floor(minY),
458 (float)Math.Ceiling(maxX),
459 (float)Math.Ceiling(maxY));
460 }
461
467 public void Draw(BackbufferBase backbuffer, RectangleF destRectScreen) { }
468
477 public virtual void Update(long tick)
478 {
479 if (_disposed || tick <= _lastTick)
480 return;
481
482 Movement.AdvanceMovement(
483 HighResTimer.GetDuration(_lastTick, tick));
484
485 _lastTick = tick;
486 }
487
491 public virtual void Dispose()
492 {
493 if (_disposed)
494 return;
495
496 _disposed = true;
497
498 Disposing?.Invoke(this, this);
499
500 IDirectCompositeChild[] children = [.. _children];
501
502 foreach (IDirectCompositeChild child in children)
503 child.Dispose();
504
505 foreach (IDirectCompositeChild child in _children)
506 {
507 child.Disposing -= OnChildDisposing;
508 UnregisterParent(child);
509 }
510
511 _children.Clear();
512 _localOffsetPx.Clear();
513 ResetTargetWhenEmpty();
514 Disposing = null;
515
516 GC.SuppressFinalize(this);
517 }
518
519 #endregion public methods
520
521 #region IDirectCompositeChild explicit interface implementations
522
523 void IDirectCompositeChild.SetIsVisible(bool visible) => SetIsVisible(visible);
524
525 void IDirectCompositeChild.SetZOrder(int zOrder) => SetZOrder(zOrder);
526
527 void IDirectCompositeChild.SetOpacity(float opacity) => SetOpacity(opacity);
528
529 void IDirectCompositeChild.FadeTo(float targetOpacity, float durationSec) => FadeTo(targetOpacity, durationSec);
530
531 #endregion IDirectCompositeChild explicit interface implementations
532
533 #region IDirectCompositeContainer explicit interface implementations
534
535 IReadOnlyCollection<IDirectCompositeChild> IDirectCompositeContainer.Children => Children;
536
539 bool keepCurrentOffset,
540 Vector2? explicitLocalOffsetPx)
541 {
542 return Add(child, keepCurrentOffset, explicitLocalOffsetPx);
543 }
544
545 IDirectCompositeContainer IDirectCompositeContainer.Remove(IDirectCompositeChild child)
546 {
547 return Remove(child);
548 }
549
550 IDirectCompositeContainer IDirectCompositeContainer.Clear()
551 {
552 return Clear();
553 }
554
555 #endregion IDirectCompositeContainer explicit interface implementations
556
557 #region protected hooks
558
569 protected virtual void OnChildAdded(IDirectCompositeChild child)
570 {
571 }
572
577 protected virtual void OnChildRemoved(IDirectCompositeChild child)
578 {
579 }
580
581 #endregion protected hooks
582
583 #region private methods
584
585 private Rectangle GetBounds(Func<IDirectCompositeChild, Rectangle> selector)
586 {
587 float minX = float.MaxValue;
588 float minY = float.MaxValue;
589 float maxX = float.MinValue;
590 float maxY = float.MinValue;
591
592 foreach (IDirectCompositeChild child in _children)
593 {
594 if (!child.Visible)
595 continue;
596
597 Rectangle bounds = selector(child);
598
599 if (bounds.IsEmpty)
600 continue;
601
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);
606 }
607
608 if (minX == float.MaxValue)
609 return Rectangle.Empty;
610
611 return Rectangle.FromLTRB(
612 (int)Math.Floor(minX),
613 (int)Math.Floor(minY),
614 (int)Math.Ceiling(maxX),
615 (int)Math.Ceiling(maxY));
616 }
617
618 private void ValidateChildIdentity(IDirectCompositeChild child)
619 {
620 if (!ReferenceEquals(child.RenderSurfaceHost, RenderSurfaceHost))
621 {
622 throw new ArgumentException(
623 "The child must belong to the same RenderSurfaceHost as the composite.",
624 nameof(child));
625 }
626
627 if (child.Mode != Mode)
628 {
629 throw new ArgumentException(
630 $"The child drawing mode '{child.Mode}' does not match the composite drawing mode '{Mode}'.",
631 nameof(child));
632 }
633 }
634
635 private void ValidateAndAssignTarget(IDirectCompositeChild child)
636 {
637 if (Mode == DirectDrawingMode.SceneLayer)
638 {
639 SceneLayer childLayer = child.SceneLayer ?? throw new ArgumentException(
640 "A scene-layer child must reference a SceneLayer.",
641 nameof(child));
642
643 if (SceneLayer is null)
644 {
645 SceneLayer = childLayer;
646 }
647 else if (!ReferenceEquals(SceneLayer, childLayer))
648 {
649 throw new ArgumentException(
650 "All scene-layer children in a composite must reference the same SceneLayer.",
651 nameof(child));
652 }
653
654 return;
655 }
656
657 if (child.View is null)
658 {
659 if (child is DirectComposite compositeChild &&
660 compositeChild.Children.Count == 0)
661 {
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.",
664 nameof(child));
665 }
666
667 throw new ArgumentException("A view child must reference a View.", nameof(child));
668 }
669
670 View childView = child.View;
671
672 if (View is null)
673 {
674 View = childView;
675 }
676 else if (!ReferenceEquals(View, childView))
677 {
678 throw new ArgumentException(
679 "All view children in a composite must reference the same View.",
680 nameof(child));
681 }
682 }
683
684 private void ValidateParentRelationship(IDirectCompositeChild child)
685 {
686 lock (_parentSyncRoot)
687 {
688 if (_parents.TryGetValue(child, out DirectComposite? existingParent))
689 {
690 throw new InvalidOperationException(
691 $"The child already belongs to composite '{existingParent.Nickname}'.");
692 }
693
694 if (child is not DirectComposite childComposite)
695 return;
696
697 DirectComposite? ancestor = this;
698
699 while (ancestor is not null)
700 {
701 if (ReferenceEquals(ancestor, childComposite))
702 {
703 throw new InvalidOperationException("Adding the child would create a recursive composite cycle.");
704 }
705
706 _parents.TryGetValue(ancestor, out ancestor);
707 }
708 }
709 }
710
711 private void RegisterParent(IDirectCompositeChild child)
712 {
713 lock (_parentSyncRoot)
714 _parents.Add(child, this);
715 }
716
717 private void UnregisterParent(IDirectCompositeChild child)
718 {
719 lock (_parentSyncRoot)
720 {
721 if (_parents.TryGetValue(child, out DirectComposite? parent) &&
722 ReferenceEquals(parent, this))
723 {
724 _parents.Remove(child);
725 }
726 }
727 }
728
729 private void ResetTargetWhenEmpty()
730 {
731 if (_children.Count != 0)
732 return;
733
734 SceneLayer = null;
735 View = null;
736 }
737
738 private void OnChildDisposing(object? sender, IDirectDrawable drawing)
739 {
740 if (drawing is not IDirectCompositeChild child)
741 return;
742
743 child.Disposing -= OnChildDisposing;
744
745 if (!_children.Remove(child))
746 return;
747
748 _localOffsetPx.Remove(child);
749 UnregisterParent(child);
750 ResetTargetWhenEmpty();
751
752 OnChildRemoved(child);
753 }
754
755 #endregion private methods
756}
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.
Definition IDrawable.cs:28
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,...