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
ToastWidget.cs
1using System.Drawing;
2using System.Numerics;
8using SkiaSharp;
9
11
15public enum ToastTransition
16{
19
22}
23
28{
31
34
37
40}
41
45public enum ToastState
46{
49
52
55
58}
59
70public sealed class ToastWidget : WidgetBase
71{
72 private bool _disposed;
73 private float _transitionDurationSec = 0.3f;
74 private float? _holdDurationSec = 3f;
75 private float _phaseElapsedSec;
76 private long _lastAnimationTick;
77 private Vector2 _phaseStartPosition;
78 private Vector2 _phaseEndPosition;
79 private float _phaseStartOpacity;
80 private float _phaseEndOpacity;
81
85 public event Action? Dismissed;
86
96 RenderSurfaceHostBase renderSurfaceHost,
97 View view,
98 Rectangle targetBounds,
99 string text,
100 string? nickname = null)
101 : base(
102 renderSurfaceHost,
104 targetBounds.Location,
105 nickname)
106 {
107 ValidateBounds(targetBounds);
108
109 TargetBounds = targetBounds;
110
112 Color.FromArgb(
113 232,
114 35,
115 38,
116 45),
117 renderSurfaceHost,
118 view,
119 targetBounds,
120 $"{Nickname}.background")
121 .SetFilled(true)
123 Color.FromArgb(
124 245,
125 215,
126 219,
127 225))
128 .SetStrokeWidth(1f)
130 .SetCornerRadius(6f);
131
132 Label = new TextBlock(
133 renderSurfaceHost,
134 view,
135 targetBounds,
136 $"{Nickname}.label")
137 .SetText(text)
138 .SetFont(SKTypeface.Default, 17f, minSize: 11f)
139 .SetColors(SKColors.White, SKColors.Transparent)
140 .SetAlignment(SKTextAlign.Center, TextBlock.VerticalAlign.Center)
141 .EnableWrapping(true);
142
143 Label.HorizontalPadding = 12f;
144 Label.VerticalPadding = 8f;
145
146 Add(
148 keepCurrentOffset: false,
149 explicitLocalOffsetPx: Vector2.Zero);
150
151 Add(
152 Label,
153 keepCurrentOffset: false,
154 explicitLocalOffsetPx: Vector2.Zero);
155
156 SetToastZOrder(int.MaxValue - 100);
157 SetIsVisible(false);
158 }
159
171 RenderSurfaceHostBase renderSurfaceHost,
172 View view,
173 Size size,
174 string text,
175 WidgetAnchor targetAnchor = WidgetAnchor.TopRight,
176 int marginPx = 16,
177 string? nickname = null)
178 : this(
179 renderSurfaceHost,
180 view,
181 GetAnchoredBounds(
182 view,
183 size,
184 targetAnchor,
185 marginPx),
186 text,
187 nickname)
188 {
189 }
190
195
199 public TextBlock Label { get; }
200
204 public ToastState CurrentState { get; private set; } = ToastState.Hidden;
205
209 public ToastTransition Transition { get; set; } = ToastTransition.Slide;
210
214 public ToastSlideOrigin SlideOrigin { get; set; } = ToastSlideOrigin.Right;
215
220 public Point? SourceLocationPx { get; set; }
221
225 public int SourceOffsetPx { get; set; } = 8;
226
231 {
232 get => _transitionDurationSec;
233 set => _transitionDurationSec = value >= 0f
234 ? value
235 : throw new ArgumentOutOfRangeException(nameof(value));
236 }
237
242 public float? HoldDurationSec
243 {
244 get => _holdDurationSec;
245 set => _holdDurationSec = value is null or >= 0f
246 ? value
247 : throw new ArgumentOutOfRangeException(nameof(value));
248 }
249
253 public EasingKind EntranceEasing { get; set; } = EasingKind.EaseOutCubic;
254
258 public EasingKind ExitEasing { get; set; } = EasingKind.EaseInCubic;
259
263 public bool AnimateDismissal { get; set; } = true;
264
268 public bool DismissOnClick { get; set; } = true;
269
273 public bool DisposeOnDismiss { get; set; } = true;
274
278 public Rectangle TargetBounds { get; private set; }
279
285 {
286 Show();
287 return this;
288 }
289
293 public void Dismiss()
294 {
295 if (_disposed || CurrentState is ToastState.Hidden or ToastState.Exiting)
296 return;
297
299 {
300 CompleteDismissal();
301 return;
302 }
303
304 CurrentState = ToastState.Exiting;
305
306 BeginPhase(
307 GetPosition(),
309 ? GetSourcePosition()
310 : GetPosition(),
311 GetCurrentOpacity(),
312 Transition == ToastTransition.Fade ? 0f : 1f);
313 }
314
320 public ToastWidget SetTargetBounds(Rectangle targetBounds)
321 {
322 ValidateBounds(targetBounds);
323
324 TargetBounds = targetBounds;
325 Background.ScreenBounds = targetBounds;
326 Label.ScreenBounds = targetBounds;
327 SetPosition(targetBounds.X, targetBounds.Y);
328
329 return this;
330 }
331
337 public ToastWidget SetText(string text)
338 {
339 Label.SetText(text);
340 return this;
341 }
342
348 public ToastWidget SetToastZOrder(int zOrder)
349 {
350 Background.ZOrder = zOrder;
351 Label.ZOrder = zOrder + 1;
352 return this;
353 }
354
356 public override void Update(long tick)
357 {
358 if (_disposed || tick <= _lastAnimationTick)
359 return;
360
361 float elapsedSec = HighResTimer.GetDuration(_lastAnimationTick, tick);
362 _lastAnimationTick = tick;
363
364 base.Update(tick);
365
366 switch (CurrentState)
367 {
368 case ToastState.Entering:
369 AdvanceTransition(elapsedSec, entering: true);
370 break;
371
372 case ToastState.Holding:
373 _phaseElapsedSec += elapsedSec;
374
375 if (HoldDurationSec is { } holdSec &&
376 _phaseElapsedSec >= holdSec)
377 {
378 Dismiss();
379 }
380
381 break;
382
383 case ToastState.Exiting:
384 AdvanceTransition(elapsedSec, entering: false);
385 break;
386 }
387 }
388
390 public override void Dispose()
391 {
392 if (_disposed)
393 return;
394
395 _disposed = true;
396 Dismissed = null;
397 base.Dispose();
398 }
399
401 protected override void ProcessShown()
402 {
403 base.ProcessShown();
404
405 CurrentState = ToastState.Entering;
406 _lastAnimationTick = HighResTimer.GetCurrentTick();
407
408 Vector2 target = new(TargetBounds.X, TargetBounds.Y);
409
410 Vector2 source = Transition == ToastTransition.Slide
411 ? GetSourcePosition()
412 : target;
413
414 BeginPhase(
415 source,
416 target,
417 Transition == ToastTransition.Fade ? 0f : 1f,
418 1f);
419
420 if (TransitionDurationSec <= 0f)
421 CompleteEntrance();
422 }
423
425 protected override void ProcessHidden()
426 {
427 CurrentState = ToastState.Hidden;
428 Movement.StopAllMovement();
429 base.ProcessHidden();
430 }
431
433 protected override void OnPointerClick(WidgetPointerEventArgs args)
434 {
435 base.OnPointerClick(args);
436
437 if (!DismissOnClick || !args.IsPrimaryButton)
438 return;
439
440 args.Handled = true;
441 Dismiss();
442 }
443
444 private void BeginPhase(
445 Vector2 startPosition,
446 Vector2 endPosition,
447 float startOpacity,
448 float endOpacity)
449 {
450 _phaseElapsedSec = 0f;
451 _phaseStartPosition = startPosition;
452 _phaseEndPosition = endPosition;
453 _phaseStartOpacity = startOpacity;
454 _phaseEndOpacity = endOpacity;
455
456 SetPosition(startPosition);
457 SetOpacity(startOpacity);
458 }
459
460 private void AdvanceTransition(float elapsedSec, bool entering)
461 {
462 _phaseElapsedSec += elapsedSec;
463
464 float progress = TransitionDurationSec <= 0f
465 ? 1f
466 : Math.Clamp(_phaseElapsedSec / TransitionDurationSec, 0f, 1f);
467
468 Func<float, float> easing = EasingFunctions.From(
469 entering ? EntranceEasing : ExitEasing);
470
471 float eased = Math.Clamp(easing(progress), 0f, 1f);
472
474 Vector2.Lerp(
475 _phaseStartPosition,
476 _phaseEndPosition,
477 eased));
478
480 _phaseStartOpacity
481 + (_phaseEndOpacity - _phaseStartOpacity) * eased);
482
483 if (progress < 1f)
484 return;
485
486 if (entering)
487 CompleteEntrance();
488 else
489 CompleteDismissal();
490 }
491
492 private void CompleteEntrance()
493 {
495 SetOpacity(1f);
496 CurrentState = ToastState.Holding;
497 _phaseElapsedSec = 0f;
498
499 if (HoldDurationSec == 0f)
500 Dismiss();
501 }
502
503 private void CompleteDismissal()
504 {
505 Hide();
506 Dismissed?.Invoke();
507
509 Dispose();
510 }
511
512 private Vector2 GetSourcePosition()
513 {
514 if (SourceLocationPx is { } explicitSource)
515 return new Vector2(explicitSource.X, explicitSource.Y);
516
517 Rectangle viewport = View!.Viewport.TargetRectPx;
518
519 return SlideOrigin switch
520 {
521 ToastSlideOrigin.Top => new Vector2(
522 TargetBounds.X,
523 viewport.Top - TargetBounds.Height - SourceOffsetPx),
524
525 ToastSlideOrigin.Right => new Vector2(
526 viewport.Right + SourceOffsetPx,
527 TargetBounds.Y),
528
529 ToastSlideOrigin.Bottom => new Vector2(
530 TargetBounds.X,
531 viewport.Bottom + SourceOffsetPx),
532
533 ToastSlideOrigin.Left => new Vector2(
534 viewport.Left - TargetBounds.Width - SourceOffsetPx,
535 TargetBounds.Y),
536
537 _ => throw new ArgumentOutOfRangeException()
538 };
539 }
540
541 private float GetCurrentOpacity()
542 {
543 return Children.Count == 0
544 ? 1f
545 : Children[0] is DirectDrawingBase drawing
546 ? drawing.Opacity
547 : 1f;
548 }
549
550 private static Rectangle GetAnchoredBounds(
551 View view,
552 Size size,
553 WidgetAnchor anchor,
554 int marginPx)
555 {
556 ArgumentNullException.ThrowIfNull(view);
557
558 if (size.Width <= 0 || size.Height <= 0)
559 throw new ArgumentOutOfRangeException(nameof(size));
560
561 if (marginPx < 0)
562 throw new ArgumentOutOfRangeException(nameof(marginPx));
563
564 Rectangle viewport = view.Viewport.TargetRectPx;
565
566 int x = anchor switch
567 {
568 WidgetAnchor.TopLeft or WidgetAnchor.CenterLeft or WidgetAnchor.BottomLeft => viewport.Left + marginPx,
569 WidgetAnchor.TopCenter or WidgetAnchor.Center or WidgetAnchor.BottomCenter => viewport.Left +
570 (viewport.Width - size.Width) / 2,
571 WidgetAnchor.TopRight or WidgetAnchor.CenterRight or WidgetAnchor.BottomRight => viewport.Right -
572 size.Width - marginPx,
573 _ => throw new ArgumentOutOfRangeException(nameof(anchor), anchor, null)
574 };
575
576 int y = anchor switch
577 {
578 WidgetAnchor.TopLeft or WidgetAnchor.TopCenter or WidgetAnchor.TopRight => viewport.Top + marginPx,
579 WidgetAnchor.CenterLeft or WidgetAnchor.Center or WidgetAnchor.CenterRight => viewport.Top +
580 (viewport.Height - size.Height) / 2,
581 WidgetAnchor.BottomLeft or WidgetAnchor.BottomCenter or WidgetAnchor.BottomRight => viewport.Bottom -
582 size.Height - marginPx,
583 _ => throw new ArgumentOutOfRangeException(nameof(anchor), anchor, null)
584 };
585
586 return new Rectangle(
587 x,
588 y,
589 size.Width,
590 size.Height);
591 }
592
593 private static void ValidateBounds(Rectangle bounds)
594 {
595 if (bounds.Width <= 0 || bounds.Height <= 0)
596 throw new ArgumentOutOfRangeException(
597 nameof(bounds),
598 "Toast bounds must have a positive width and height.");
599 }
600}
ReadOnlyCollection< IDirectCompositeChild > Children
Gets the children owned by the composite.
DirectComposite SetOpacity(float opacity)
Applies one opacity to every descendant.
DirectComposite SetIsVisible(bool visible)
Applies one visibility value to every descendant.
View? View
Gets the view shared by all children in view mode.
MovementController Movement
Gets the movement controller used to move the composite anchor.
Vector2 GetPosition()
Gets the current composite anchor.
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.
Renders a configurable rectangle with support for fill, border, rounded corners, dash patterns,...
DirectRectangle SetFilled(bool isFilled)
Sets whether the rectangle interior is filled with the base color (or pattern).
DirectRectangle SetBorderColor(Color color)
Sets a distinct border (stroke) color, independent of the fill color.
StrokeAlign
Defines how the stroke (outline) is positioned relative to the rectangle's boundary.
DirectRectangle SetStrokeWidth(float width)
Sets the width (thickness) of the rectangle's stroke (outline) in pixels.
DirectRectangle SetCornerRadius(float radius)
Sets the radius for rounded corners in pixels.
DirectRectangle SetStrokeAlign(StrokeAlign align)
Sets how the rectangle's stroke is positioned relative to its bounds.
A retained-mode text drawable with wrapping, multi-line ( ) support, horizontal/vertical alignment,...
Definition TextBlock.cs:44
TextBlock SetFont(SKTypeface typeface, float size, float? minSize=null)
Sets the font face and size (and optional minimum size for auto-shrink).
Definition TextBlock.cs:414
TextBlock EnableWrapping(bool enable=true)
Enables or disables word wrapping when laying out paragraphs.
Definition TextBlock.cs:527
TextBlock SetAlignment(SKTextAlign h, VerticalAlign v)
Sets the horizontal and vertical alignment used when drawing the laid-out lines within the bounds.
Definition TextBlock.cs:453
VerticalAlign
Vertical alignment options for multi-line text within the control's bounds.
Definition TextBlock.cs:49
TextBlock SetColors(SKColor fg, SKColor bg)
Sets the foreground (text) and background colors using Skia colors.
Definition TextBlock.cs:430
TextBlock SetText(string text)
Sets the current text content and rebuilds layout as needed. If no reveal animation is active,...
Definition TextBlock.cs:378
Represents a base class for hosting a render surface, providing functionality for managing rendering ...
Viewport Viewport
Gets the viewport that defines the screen-space rectangle, zoom level, and other rendering parameters...
Definition View.cs:44
Rectangle TargetRectPx
Screen-space rectangle (in SCREEN / RenderSurface pixels) where this view is drawn....
Definition Viewport.cs:40
EasingKind EntranceEasing
Gets or sets the easing used by the entrance transition.
Action? Dismissed
Occurs after the toast completes dismissal and is hidden.
bool DisposeOnDismiss
Gets or sets whether the toast disposes itself after dismissal.
ToastWidget SetTargetBounds(Rectangle targetBounds)
Changes the target bounds used the next time the toast is shown.
float? HoldDurationSec
Gets or sets how long the toast remains at its target before automatic dismissal. Null disables autom...
bool AnimateDismissal
Gets or sets whether dismissal reverses the configured entrance transition.
bool DismissOnClick
Gets or sets whether a primary-pointer click dismisses the toast.
ToastWidget(RenderSurfaceHostBase renderSurfaceHost, View view, Rectangle targetBounds, string text, string? nickname=null)
Initializes a toast with explicit target bounds in absolute screen pixels.
void Dismiss()
Begins dismissal. Repeated calls while exiting or hidden have no effect.
Rectangle TargetBounds
Gets the target bounds at which the toast rests, in absolute screen pixels.
override void OnPointerClick(WidgetPointerEventArgs args)
Called when a pointer click is dispatched to the widget.
EasingKind ExitEasing
Gets or sets the easing used by the dismissal transition.
ToastWidget ShowToast()
Shows the toast and begins its entrance transition.
ToastSlideOrigin SlideOrigin
Gets or sets the edge used by slide transitions.
Point? SourceLocationPx
Gets or sets an optional explicit slide source top-left in absolute screen pixels....
ToastState CurrentState
Gets the current toast lifecycle state.
float TransitionDurationSec
Gets or sets the transition duration in seconds. Zero performs the transition immediately.
ToastWidget SetToastZOrder(int zOrder)
Sets the background Z-order and places the label immediately above it.
DirectRectangle Background
Gets the rectangle used for the toast background and border.
TextBlock Label
Gets the text drawing used for the toast message.
override void ProcessShown()
Performs processing when the widget is shown before notification callbacks are invoked.
ToastWidget(RenderSurfaceHostBase renderSurfaceHost, View view, Size size, string text, WidgetAnchor targetAnchor=WidgetAnchor.TopRight, int marginPx=16, string? nickname=null)
Initializes a toast positioned from a standard anchor inside the view.
override void Update(long tick)
Advances composite movement.This method uses the tick to calculate elapsed time and advance the movem...
override void ProcessHidden()
Performs processing when the widget is hidden before notification callbacks are invoked.
ToastWidget SetText(string text)
Sets the toast message.
ToastTransition Transition
Gets or sets the entrance and animated-dismissal transition.
int SourceOffsetPx
Gets or sets the gap between a calculated slide source and the view edge.
override void Dispose()
Disposes the composite and every child it owns.
WidgetBase Show()
Shows the widget and registers it for input routing.
WidgetBase(RenderSurfaceHostBase renderSurfaceHost, DirectDrawingMode mode, PointF anchor=default, string? nickname=null)
Initializes a new instance of the WidgetBase class.
Definition WidgetBase.cs:95
WidgetBase Hide()
Hides the widget and releases any routed input state.
Event arguments for pointer-based widget callbacks.
bool IsPrimaryButton
Gets whether the pointer event represents a primary-button interaction.
@ Rectangle
Particles are spawned uniformly within a rectangular area. This is the default distribution.
DirectDrawingMode
Specifies where direct drawing operations are applied within the rendering pipeline.
EasingKind
Enumeration of all supported easing functions for animation and movement interpolation....
Definition EasingKind.cs:9
ToastSlideOrigin
Defines the view edge from which a sliding toast enters.
@ Bottom
The toast enters from below the view.
@ Right
The toast enters from the right of the view.
@ Left
The toast enters from the left of the view.
@ Top
The toast enters from above the view.
ToastState
Represents the lifecycle state of a ToastWidget.
@ Exiting
The toast is moving or fading out of view.
@ Holding
The toast is resting at its target bounds.
@ Hidden
The toast is not being shown.
@ Entering
The toast is moving or fading into view.
ToastTransition
Defines how a toast enters its view.
@ Fade
The toast remains at its target bounds and fades from transparent.
@ Slide
The toast moves from outside the view to its target bounds.
WidgetAnchor
Identifies one of the nine common anchor points on a rectangle.