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
DirectDrawingBase.cs
1using System.Drawing;
8using SkiaSharp;
9
11
38public abstract class DirectDrawingBase : IDirectDrawable, IComparable<DirectDrawingBase>
39{
47 public event EventHandler<IDirectDrawable>? Disposing;
48
57 public event EventHandler<DirectDrawingBase>? FadeToCompleted;
58
63
67 protected Rectangle _screenBounds;
68
72 protected Rectangle _worldBounds;
73
77 protected int _zOrder;
78
82 protected bool _visible;
83
87 protected long _lastTick = HighResTimer.GetCurrentTick();
88
89 private bool _disposed = false;
90
91 // Fade/opacity state
92 private float _opacity = 1f; // 0..1
93 private float _fadeFrom, _fadeTo;
94 private float _fadeDurationSec, _fadeElapsedSec;
95 private bool _isFading;
96
110 public bool HideWhenFullyTransparent { get; set; } = true;
111
112 // Reveal state
113 private float _revealT = 1f; // 0 = hidden, 1 = fully shown
114 private RevealDirection _revealDir = RevealDirection.LeftToRight;
115
116 // optional tween state
117 private bool _revealAnimating;
118 private float _revealElapsedSec, _revealDurationSec;
119 private Func<float, float>? _revealEasing;
120 private float _revealStart = 1f, _revealTarget = 1f;
121
147 protected abstract void OnDraw(BackbufferBase backbuffer, RectangleF destRectScreen);
148
174 RenderSurfaceHostBase renderSurfaceHost,
176 SceneLayer? sceneLayer,
177 View? view,
178 Rectangle? screenBounds,
179 Rectangle? worldBounds,
180 string? nickname = null)
181 {
182 if (renderSurfaceHost is null)
183 throw new ArgumentNullException(nameof(renderSurfaceHost));
184
185 if (mode == DirectDrawingMode.SceneLayer && sceneLayer is null)
186 throw new ArgumentException(
187 "SceneLayer cannot be null when using DirectDrawingMode.SceneLayer",
188 nameof(sceneLayer));
189
190 if (mode == DirectDrawingMode.View && view is null)
191 throw new ArgumentException("View cannot be null when using DirectDrawingMode.View", nameof(view));
192
193 if (mode == DirectDrawingMode.SceneLayer && worldBounds is null)
194 throw new ArgumentException(
195 "worldBounds cannot be null when using DirectDrawingMode.SceneLayer",
196 nameof(worldBounds));
197
198 if (mode == DirectDrawingMode.View && screenBounds is null)
199 throw new ArgumentException(
200 "screenBounds cannot be null when using DirectDrawingMode.View",
201 nameof(screenBounds));
202
203 _renderSurfaceHost = renderSurfaceHost;
204 _zOrder = 0;
205 _visible = true;
206 Mode = mode;
207 SceneLayer = sceneLayer;
208 View = view;
209 Nickname = nickname ?? Id.ToString();
210
211 if (mode == DirectDrawingMode.SceneLayer)
212 {
213 _worldBounds = worldBounds!.Value;
214 _screenBounds = Rectangle.Empty;
215 }
216 else // View
217 {
218 _worldBounds = Rectangle.Empty;
219 // Preserve layout bounds even when the viewport is not yet fully sized.
220 // The rendering pipeline clips drawings to the current viewport.
221 _screenBounds = screenBounds!.Value;
222 }
223
224 DirectDrawingManager.Instance.AddOrReplace(this);
225 ForceRefresh();
226 }
227
228 ~DirectDrawingBase() => Dispose(false);
229
238
251 public DirectDrawingMode Mode { get; }
252
265 public SceneLayer? SceneLayer { get; private set; }
266
279 public View? View { get; private set; }
280
300 public Rectangle ScreenBounds
301 {
302 get => _screenBounds;
303 set
304 {
305 if (Mode != DirectDrawingMode.View)
306 return;
307
308 ForceRefresh();
309 _screenBounds = value;
310 ForceRefresh();
311 }
312 }
313
333 public Rectangle WorldBounds
334 {
335 get => _worldBounds;
336 set
337 {
338 if (Mode != DirectDrawingMode.SceneLayer)
339 return;
340
341 ForceRefresh();
342 _worldBounds = value;
343 ForceRefresh();
344 }
345 }
346
357 public TypedValueBag ValueBag { get; } = new();
358
359 #region IDrawable members
360
371 public Guid Id { get; } = Guid.NewGuid();
372
383 public string? Nickname { get; private set; }
384
397 public int ZOrder
398 {
399 get => _zOrder;
400 set
401 {
402 if (_zOrder != value)
403 {
404 _zOrder = value;
405 ForceRefresh();
406 }
407 }
408 }
409
427 public bool Visible
428 {
429 get => _visible;
430 set
431 {
432 if (_visible != value)
433 {
434 _visible = value;
435 ForceRefresh();
436 }
437 }
438 }
439
454 public RectangleF GetDrawLocationScreen(View view)
455 {
456 // View-mode drawings participate in View-level presentation transforms.
457 if (Mode == DirectDrawingMode.View)
458 {
459 PointF offset = view.GetEffectOffsetPx(layer: null);
460
461 return new RectangleF(
462 _screenBounds.Left + offset.X,
463 _screenBounds.Top + offset.Y,
464 _screenBounds.Width,
465 _screenBounds.Height);
466 }
467
468 // translate world bounds to screen via view transform
470 }
471
498 public void Draw(BackbufferBase backbuffer, RectangleF destRectScreen)
499 {
500 if (!Visible)
501 return;
502
503 var canvas = backbuffer.Canvas;
504
505 // Compute reveal clip rect (screen pixel space) from bounds
506 bool useClip = _revealT < 0.999f;
507
508 if (useClip)
509 {
510 var r = new SKRect(
511 destRectScreen.Left,
512 destRectScreen.Top,
513 destRectScreen.Right,
514 destRectScreen.Bottom);
515
516 SKRect clipRect = _revealDir switch
517 {
518 RevealDirection.LeftToRight => new SKRect(
519 r.Left,
520 r.Top,
521 r.Left + r.Width * _revealT,
522 r.Bottom),
523 RevealDirection.RightToLeft => new SKRect(
524 r.Right - r.Width * _revealT,
525 r.Top,
526 r.Right,
527 r.Bottom),
528 RevealDirection.TopToBottom => new SKRect(
529 r.Left,
530 r.Top,
531 r.Right,
532 r.Top + r.Height * _revealT),
533 RevealDirection.BottomToTop => new SKRect(
534 r.Left,
535 r.Bottom - r.Height * _revealT,
536 r.Right,
537 r.Bottom),
538 _ => r
539 };
540
541 // Early-out if reveal window is empty
542 if (clipRect.Width <= 0f || clipRect.Height <= 0f)
543 return;
544
545 // Outer save owns the clip lifetime
546 canvas.Save();
547
548 // Capture current matrix
549 var m = canvas.TotalMatrix;
550
551 canvas.ResetMatrix();
552 canvas.ClipRect(clipRect, SKClipOperation.Intersect, antialias: false);
553
554 // Put the prior matrix back so Draw() sees the same transform state
555 canvas.SetMatrix(m);
556 }
557
558 if (_opacity >= 0.999f)
559 {
560 OnDraw(backbuffer, destRectScreen);
561 }
562 else
563 {
564 using var layerPaint = new SKPaint
565 {
566 Color = new SKColor(
567 255,
568 255,
569 255,
570 (byte)(_opacity * 255))
571 };
572
573 canvas.SaveLayer(destRectScreen.ToSKRect(), layerPaint);
574 OnDraw(backbuffer, destRectScreen);
575 canvas.Restore(); // end SaveLayer
576 }
577
578 if (useClip)
579 canvas.Restore(); // end outer clip Save
580 }
581
582 #endregion IDrawable members
583
607 public float Opacity
608 {
609 get => _opacity;
610 set
611 {
612 var clamped = Math.Clamp(value, 0f, 1f);
613
614 if (Math.Abs(clamped - _opacity) < 0.0001f)
615 return;
616
617 _opacity = clamped;
618
619 if (HideWhenFullyTransparent && _opacity <= 0f)
620 Visible = false;
621 else if (_opacity > 0f)
622 Visible = true;
623
624 ForceRefresh();
625 }
626 }
627
637 public DirectDrawingBase SetOpacity(float opacity)
638 {
639 Opacity = opacity;
640 return this;
641 }
642
665 public DirectDrawingBase FadeTo(float targetOpacity, float durationSec)
666 {
667 _fadeFrom = _opacity;
668 _fadeTo = Math.Clamp(targetOpacity, 0f, 1f);
669 _fadeDurationSec = Math.Max(0.0001f, durationSec);
670 _fadeElapsedSec = 0f;
671 _isFading = true;
672
673 if (_fadeTo > 0f)
674 Visible = true; // ensure we draw during fade-in
675
676 ForceRefresh();
677
678 return this;
679 }
680
691 public DirectDrawingBase FadeIn(float durationSec)
692 {
693 if (_opacity <= 0f)
694 Opacity = 0f;
695
696 return FadeTo(1f, durationSec);
697 }
698
715 public DirectDrawingBase FadeOut(float durationSec)
716 {
717 return FadeTo(0f, durationSec);
718 }
719
730 {
731 _isFading = false;
732 return this;
733 }
734
751 public DirectDrawingBase SetReveal(float t01)
752 {
753 _revealT = Math.Clamp(t01, 0f, 1f);
754 ForceRefresh();
755 return this;
756 }
757
769 {
770 _revealDir = dir;
771 ForceRefresh();
772 return this;
773 }
774
796 public DirectDrawingBase RevealTo(float t01, float durationSec, Func<float, float>? easing = null)
797 {
798 _revealAnimating = true;
799 _revealElapsedSec = 0f;
800 _revealDurationSec = Math.Max(0.0001f, durationSec);
801 _revealEasing = easing;
802 // target is t01; we'll lerp in Update
803 _revealTarget = Math.Clamp(t01, 0f, 1f);
804 _revealStart = _revealT;
805 return this;
806 }
807
811 {
812 _revealAnimating = false;
813 return this;
814 }
815
835 protected internal void ForceRefresh()
836 {
837 switch (Mode)
838 {
839 case DirectDrawingMode.SceneLayer:
840 // bounds is WORLD-space
841 // there will only be one SceneLayer per DirectDrawing in this mode
842 SceneLayer!.RefreshQueue.AddWorldRect(_worldBounds);
843 break;
844
845 case DirectDrawingMode.View:
846 // bounds is SCREEN-space
847 // need to cycle through all SceneLayers for the View to which this DirectDrawing belongs
848 foreach (var sceneLayer in RenderSurfaceHost.Scene.SceneLayers)
849 {
850 sceneLayer.RefreshQueue.AddViewScreenRect(View!, sceneLayer, _screenBounds);
851 }
852
853 break;
854
855 default:
856 break;
857 }
858 }
859
881 public virtual void Update(long tick)
882 {
883 if (tick <= _lastTick)
884 return;
885
886 // Advance fade tween
887 if (_isFading)
888 {
889 float dt = HighResTimer.GetDuration(_lastTick, tick);
890
891 _fadeElapsedSec += dt;
892 float timeElapsed = Math.Clamp(_fadeElapsedSec / _fadeDurationSec, 0f, 1f);
893 // linear; swap in easing if you like
894 _opacity = _fadeFrom + (_fadeTo - _fadeFrom) * timeElapsed;
895
897 Visible = _opacity > 0f; // hides when hit zero
898
899 ForceRefresh();
900
901 if (timeElapsed >= 1f)
902 {
903 _isFading = false;
904 FadeToCompleted?.Invoke(this, this);
905 }
906 }
907
908 // Advance reveal tween
909 if (_revealAnimating)
910 {
911 float dt = HighResTimer.GetDuration(_lastTick, tick);
912 _revealElapsedSec = Math.Min(_revealElapsedSec + dt, _revealDurationSec);
913
914 float u = _revealElapsedSec / _revealDurationSec;
915 _revealT = (_revealEasing is null ? u : _revealEasing(u));
916 _revealT = _revealStart + (_revealTarget - _revealStart) * _revealT;
917
918 ForceRefresh();
919
920 if (_revealElapsedSec >= _revealDurationSec)
921 _revealAnimating = false;
922 }
923
924 _lastTick = tick;
925 }
926
940 public int CompareTo(DirectDrawingBase? other) => _zOrder.CompareTo(other?._zOrder ?? 0);
941
942 #region IDisposable members
943
957 public void Dispose()
958 {
959 lock (RenderStateSynchronization.SyncRoot)
960 {
961 Dispose(true);
962 GC.SuppressFinalize(this);
963 }
964 }
965
987 protected virtual void Dispose(bool disposing)
988 {
989 if (_disposed)
990 return;
991
992 if (disposing)
993 {
994 ForceRefresh();
995 Disposing?.Invoke(this, this);
996 Disposing = null;
997 }
998
999 _disposed = true;
1000 }
1001
1002 #endregion IDisposable members
1003
1004 #region Equality & Operators
1005
1018 public override bool Equals(object? obj) => ReferenceEquals(this, obj);
1019
1029 public override int GetHashCode() => HashCode.Combine(Nickname);
1030
1040 public static bool operator ==(DirectDrawingBase? left, DirectDrawingBase? right) =>
1041 ReferenceEquals(left, null) ? ReferenceEquals(right, null) : left.Equals(right);
1042
1052 public static bool operator !=(DirectDrawingBase? left, DirectDrawingBase? right) => !(left == right);
1053
1063 public static bool operator <(DirectDrawingBase? left, DirectDrawingBase? right) =>
1064 ReferenceEquals(left, null) ? !ReferenceEquals(right, null) : left.CompareTo(right) < 0;
1065
1075 public static bool operator <=(DirectDrawingBase? left, DirectDrawingBase? right) =>
1076 ReferenceEquals(left, null) || left.CompareTo(right) <= 0;
1077
1087 public static bool operator >(DirectDrawingBase? left, DirectDrawingBase? right) =>
1088 !ReferenceEquals(left, null) && left.CompareTo(right) > 0;
1089
1099 public static bool operator >=(DirectDrawingBase? left, DirectDrawingBase? right) =>
1100 ReferenceEquals(left, null) ? ReferenceEquals(right, null) : left.CompareTo(right) >= 0;
1101
1102 #endregion Equality & Operators
1103
1134}
Provides the base implementation for direct drawing objects that can be rendered to the backbuffer wi...
void OnDraw(BackbufferBase backbuffer, RectangleF destRectScreen)
Performs the concrete drawing for this direct drawing to the backbuffer.
DirectDrawingBase SetRevealDirection(RevealDirection dir)
Sets the direction from which the reveal animation progresses.
DirectDrawingBase CancelReveal()
Stops an active reveal animation at its current progress.
int ZOrder
Gets or sets the Z-order (depth) used for sorting this direct drawing relative to other drawables.
static bool operator>(DirectDrawingBase? left, DirectDrawingBase? right)
Determines whether the Z-order of the left direct drawing is greater than the right.
DirectDrawingBase RevealTo(float t01, float durationSec, Func< float, float >? easing=null)
Initiates a smooth reveal animation to the specified target progress over the given duration,...
int _zOrder
The Z-order used for draw sorting. Higher values draw later (on top).
static bool operator==(DirectDrawingBase? left, DirectDrawingBase? right)
Determines whether two direct drawing instances are equal using reference equality.
DirectDrawingBase FadeOut(float durationSec)
Fades this direct drawing from its current opacity to fully transparent over the specified duration.
void Dispose()
Releases all resources used by this DirectDrawingBase instance.
bool HideWhenFullyTransparent
Gets or sets a value indicating whether this direct drawing should be automatically hidden when its o...
override int GetHashCode()
Returns a hash code for this direct drawing.
View? View
Gets the view to which this direct drawing is attached, or null if the drawing is in scene-layer mode...
long _lastTick
The last engine tick value used for delta-time calculations in Update.
TypedValueBag ValueBag
Gets the extensible value bag for storing arbitrary key-value data associated with this direct drawin...
bool _visible
Indicates whether this direct drawing is currently visible and should be rendered.
virtual void Update(long tick)
Performs per-frame update logic for this direct drawing, including fade and reveal animations.
int CompareTo(DirectDrawingBase? other)
Compares this direct drawing to another for sorting by ZOrder.
bool Visible
Gets or sets a value indicating whether this direct drawing is visible and should be rendered.
RectangleF GetDrawLocationScreen(View view)
Gets the screen-space drawing location for this direct drawing as seen from the specified view.
float Opacity
Gets or sets the current opacity of this direct drawing.
static bool operator>=(DirectDrawingBase? left, DirectDrawingBase? right)
Determines whether the Z-order of the left direct drawing is greater than or equal to the right.
static bool operator!=(DirectDrawingBase? left, DirectDrawingBase? right)
Determines whether two direct drawing instances are not equal using reference equality.
DirectDrawingBase FadeTo(float targetOpacity, float durationSec)
Initiates a smooth fade transition to the specified target opacity over the given duration.
static bool operator<(DirectDrawingBase? left, DirectDrawingBase? right)
Determines whether the Z-order of the left direct drawing is less than the right.
readonly RenderSurfaceHostBase _renderSurfaceHost
The render surface host that manages this direct drawing's rendering pipeline.
string? Nickname
Gets the optional human-readable name for this direct drawing.
EventHandler< IDirectDrawable >? Disposing
Occurs when this direct drawing is being disposed.
DirectDrawingBase SetReveal(float t01)
Instantly sets the reveal progress to the specified value without animation.
Guid Id
Gets the unique identifier for this direct drawing.
RenderSurfaceHostBase RenderSurfaceHost
Gets the render surface host that manages this direct drawing's rendering pipeline.
override bool Equals(object? obj)
Determines whether the specified object is equal to the current direct drawing.
DirectDrawingBase FadeIn(float durationSec)
Fades this direct drawing from its current opacity to fully opaque over the specified duration.
Rectangle _worldBounds
The current world-space bounds for scene-layer-mode direct drawings, in pixels.
SceneLayer? SceneLayer
Gets the scene layer to which this direct drawing is attached, or null if the drawing is in view mode...
static bool operator<=(DirectDrawingBase? left, DirectDrawingBase? right)
Determines whether the Z-order of the left direct drawing is less than or equal to the right.
Rectangle _screenBounds
The current screen-space bounds for view-mode direct drawings, in pixels.
DirectDrawingBase CancelFade()
Cancels any active fade transition, leaving the opacity at its current value.
Rectangle WorldBounds
Gets or sets the world-space bounds of this direct drawing in pixels.
DirectDrawingMode Mode
Gets the drawing mode that determines how this direct drawing is positioned and transformed.
void Draw(BackbufferBase backbuffer, RectangleF destRectScreen)
Renders this direct drawing to the backbuffer at the specified screen location.
virtual void Dispose(bool disposing)
Releases resources used by this DirectDrawingBase instance.
RevealDirection
Defines the direction from which a reveal animation progressively displays the direct drawing.
@ BottomToTop
Reveals the drawing from the bottom edge toward the top edge.
@ RightToLeft
Reveals the drawing from the right edge toward the left edge.
@ LeftToRight
Reveals the drawing from the left edge toward the right edge.
@ TopToBottom
Reveals the drawing from the top edge toward the bottom edge.
EventHandler< DirectDrawingBase >? FadeToCompleted
Occurs when a fade transition initiated by FadeTo, FadeIn, or FadeOut completes.
DirectDrawingBase SetOpacity(float opacity)
Instantly sets the opacity to the specified value without animation.
DirectDrawingBase(RenderSurfaceHostBase renderSurfaceHost, DirectDrawingMode mode, SceneLayer? sceneLayer, View? view, Rectangle? screenBounds, Rectangle? worldBounds, string? nickname=null)
Initializes a new instance of the DirectDrawingBase class.
Rectangle ScreenBounds
Gets or sets the screen-space bounds of this direct drawing in pixels.
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.
Represents a base class for managing a graphical backbuffer, and is the in-memory surface where rende...
SKCanvas Canvas
Gets the SkiaSharp canvas used for drawing operations on this backbuffer.
Represents a base class for hosting a render surface, providing functionality for managing rendering ...
Scene Scene
Gets the source Scenes.Scene used for rendering operations.
RectangleF WorldRectToScreenRect(SceneLayer layer, RectangleF worldRect)
Converts a world-space pixel rectangle into a screen-space rectangle for this View,...
Definition View.cs:340
ReadOnlyCollection< SceneLayer > SceneLayers
Gets a read-only collection of all layers in this scene, in their current order.
Definition Scene.cs:265
A flexible, strongly-typed value container intended for runtime-attached metadata and ephemeral engin...
Represents any drawable object (movable or static) that can render directly to a RenderSurfaceHost,...
DirectDrawingMode
Specifies where direct drawing operations are applied within the rendering pipeline.
@ View
Performs direct drawing at the view level using screen-space coordinates.
@ SceneLayer
Performs direct drawing within a scene layer using world-space coordinates.