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
Sprite.cs
1using System.Drawing;
2using System.Numerics;
3using System.Runtime.Serialization;
10using Gondwana.Scenes;
12using Newtonsoft.Json;
13
15
19[JsonObject(IsReference = true)]
20public partial class Sprite : Tile, IMovableOnSceneLayer, ICollisionMovableEntity, IDisposable
21{
23 [JsonIgnore]
24 internal DefinitionProvenance? DefinitionProvenance { get; set; }
25
29 public event Action<SpriteMovedEventArgs>? SpriteMoved;
30
34 public event Action<Sprite>? VisualBoundsChanged;
35
39 public event Action<Sprite>? Disposing;
40
41 [JsonIgnore] internal SceneLayer _sceneLayer;
42
43 private string? _serializedSceneId;
44 private string? _serializedSceneLayerId;
45
46#pragma warning disable IDE0051 // Used by Newtonsoft.Json via reflection for state serialization.
47
51 [JsonProperty("SceneId")]
52 private string? SerializedSceneId
53 {
54 get => !ReferenceEquals(_sceneLayer, SceneLayer.Empty)
55 ? _sceneLayer.Scene?.ID ?? _serializedSceneId
56 : _serializedSceneId;
57 set => _serializedSceneId = value;
58 }
59
63 [JsonProperty("SceneLayerId")]
64 private string? SerializedSceneLayerId
65 {
66 get => !ReferenceEquals(_sceneLayer, SceneLayer.Empty)
67 ? _sceneLayer.ID
68 : _serializedSceneLayerId;
69 set => _serializedSceneLayerId = value;
70 }
71
76 [JsonProperty("SceneLayer")]
77 private SceneLayer? LegacySerializedSceneLayer
78 {
79 set
80 {
81 if (value is null)
82 return;
83
84 _sceneLayer = value;
85 _serializedSceneId = value.Scene?.ID;
86 _serializedSceneLayerId = value.ID;
87 }
88 }
89
90#pragma warning restore IDE0051
91
92 private HorizontalAlignment _horizAlign;
93 private VerticalAlignment _vertAlign;
94 private int _nudgeX;
95 private int _nudgeY;
96 private Size _renderSize;
97 private float _rotation;
98
99 internal bool _pendingDispose;
100
101 [JsonProperty("SceneLayerCoordinates")]
102 private PointF _sceneLayerCoordinates;
103
104 [JsonConstructor]
105 private Sprite()
106 {
107 // New EngineState files bind sprites to the restored scene graph by stable
108 // Scene/SceneLayer IDs after the snapshot's scenes have been materialized.
109 _sceneLayer = SceneLayer.Empty;
110 }
111
117 protected internal Sprite(SceneLayer sceneLayer, Frame frame)
118 : this(
119 sceneLayer,
120 frame,
121 SpriteManager.Instance.DefaultCollisionProfile)
122 {
123 }
124
131 protected internal Sprite(
132 SceneLayer sceneLayer,
133 Frame frame,
134 string collisionProfileName)
135 {
136 _sceneLayer = sceneLayer
137 ?? throw new ArgumentNullException(
138 nameof(sceneLayer),
139 "Sprite must be attached to a SceneLayer.");
140
141 animator = new Animator(this);
142 pauseAnimation = false;
143 _horizAlign = HorizontalAlignment.Center;
144 _vertAlign = VerticalAlignment.Bottom;
145 _nudgeX = 0;
146 _nudgeY = 0;
147
148 Movement = new MovementController(
149 this,
150 MovementState.ForSceneLayer(),
151 SceneLayer);
152
154 new TileCollider(
155 this,
156 collisionGroup: CollisionMasks.None,
157 collidesWith: CollisionMasks.None));
158
159 SetCollisionProfile(collisionProfileName);
160 CurrentFrame = frame;
161
162 _renderSize = SpriteManager.Instance.SizeNewSpritesToSceneLayer
163 ? new Size(_sceneLayer.TileWidth, _sceneLayer.TileHeight)
164 : CurrentFrame.TileSize;
165
166 zOrder = 1;
167
168 _sceneLayer.RefreshQueue.AddWorldRect(VisualBoundsWorld);
169 SpriteManager.Instance.AddSprite(this);
170 }
171
177 internal Sprite(Sprite sprite, SceneLayer sceneLayer)
178 {
179 ArgumentNullException.ThrowIfNull(sprite);
180
181 _sceneLayer = sceneLayer
182 ?? throw new ArgumentNullException(
183 nameof(sceneLayer),
184 "Sprite must be attached to a SceneLayer.");
185
186 animator = new Animator(this);
187
188 frame = sprite.frame;
190 _horizAlign = sprite._horizAlign;
191 _vertAlign = sprite._vertAlign;
192 _nudgeX = sprite._nudgeX;
193 _nudgeY = sprite._nudgeY;
194 _renderSize = sprite._renderSize;
195 _rotation = sprite._rotation;
196 ZOrder = sprite.zOrder;
197 visible = sprite.visible;
198 _sceneLayerCoordinates = sprite.SceneLayerCoordinates;
199
200 Movement = new MovementController(
201 this,
202 MovementState.ForSceneLayer(),
203 SceneLayer);
204
206 new TileCollider(
207 this,
208 collisionGroup: CollisionMasks.None,
209 collidesWith: CollisionMasks.None));
210
211 if (string.IsNullOrWhiteSpace(CollisionProfileName))
212 SetCollisionProfile(SpriteManager.Instance.DefaultCollisionProfile);
213
214 _sceneLayer.RefreshQueue.AddWorldRect(VisualBoundsWorld);
215 SpriteManager.Instance.AddSprite(this);
216 }
217
218 ~Sprite()
219 {
220 Dispose();
221 }
222
223 [OnDeserialized]
224 private void OnDeserialized(StreamingContext context)
225 {
226 animator = new Animator(this);
227 pauseAnimation = false;
228
229 // Legacy files may still supply the old serialized SceneLayer object/reference.
230 // New files carry SceneId + SceneLayerId and are rebound by EngineState only after
231 // the corresponding GSCN scene has been restored.
232 if (!ReferenceEquals(_sceneLayer, SceneLayer.Empty))
233 {
234 InitializeDeserializedRuntimeBindings();
235 SpriteManager.Instance.AddSprite(this);
236 }
237 }
238
242 [JsonIgnore]
243 internal string? SerializedSceneIdForBinding =>
244 !ReferenceEquals(_sceneLayer, SceneLayer.Empty)
245 ? _sceneLayer.Scene?.ID ?? _serializedSceneId
246 : _serializedSceneId;
247
251 [JsonIgnore]
252 internal string? SerializedSceneLayerIdForBinding =>
253 !ReferenceEquals(_sceneLayer, SceneLayer.Empty)
254 ? _sceneLayer.ID
255 : _serializedSceneLayerId;
256
261 internal void RebindSceneLayerAfterDeserialization(SceneLayer sceneLayer)
262 {
263 ArgumentNullException.ThrowIfNull(sceneLayer);
264
265 if (ReferenceEquals(_sceneLayer, sceneLayer) && Movement is not null)
266 return;
267
268 Movement?.Dispose();
270
271 _sceneLayer = sceneLayer;
272 _serializedSceneId = sceneLayer.Scene?.ID;
273 _serializedSceneLayerId = sceneLayer.ID;
274
275 InitializeDeserializedRuntimeBindings();
276 }
277
278 private void InitializeDeserializedRuntimeBindings()
279 {
280 Movement = new MovementController(
281 this,
282 MovementState.ForSceneLayer(),
283 SceneLayer);
284
286 new TileCollider(
287 this,
288 collisionGroup: CollisionMasks.None,
289 collidesWith: CollisionMasks.None));
290
291 if (string.IsNullOrWhiteSpace(CollisionProfileName))
292 SetCollisionProfile(SpriteManager.Instance.DefaultCollisionProfile);
293 else
294 RefreshCollisionProfile();
295
296 _sceneLayer.RefreshQueue.AddWorldRect(VisualBoundsWorld);
297 }
298
303
308 public Vector2 GetPosition() =>
309 new(_sceneLayerCoordinates.X, _sceneLayerCoordinates.Y);
310
315 public void SetPosition(Vector2 pos)
316 {
317 PointF oldCoord = _sceneLayerCoordinates;
318 Rectangle oldDraw = VisualBoundsWorld;
319
320 _sceneLayerCoordinates = new PointF(pos.X, pos.Y);
321
322 Rectangle newDraw = VisualBoundsWorld;
323 Rectangle movementWorldRect = Rectangle.Union(oldDraw, newDraw);
324 movementWorldRect.Inflate(5, 5);
325
326 _sceneLayer.RefreshQueue.AddWorldRect(movementWorldRect);
327
328 SpriteMoved?.Invoke(
329 new SpriteMovedEventArgs(this, oldCoord, _sceneLayerCoordinates));
330 }
331
340 [JsonProperty]
341 public float Rotation
342 {
343 get => _rotation;
344 set
345 {
346 if (!float.IsFinite(value))
347 throw new ArgumentOutOfRangeException(nameof(value), "Rotation must be a finite number of degrees.");
348
349 float normalized = value % 360f;
350
351 if (normalized < 0f)
352 normalized += 360f;
353
354 if (_rotation.Equals(normalized))
355 return;
356
357 Rectangle oldBounds = VisualBoundsWorld;
358 _rotation = normalized;
359 InvalidateVisualChange(oldBounds, VisualBoundsWorld);
360 }
361 }
362
366 [JsonIgnore]
367 public Rectangle VisualBoundsWorld =>
368 GetRotatedBounds(DrawLocationWorld, Rotation);
369
375 public RectangleF GetVisualBoundsScreen(View view) =>
376 GetRotatedBounds(GetDrawLocationScreen(view), Rotation);
377
378 internal RectangleF GetVisualBoundsScreen(RectangleF renderRectScreen) =>
379 GetRotatedBounds(renderRectScreen, Rotation);
380
382 public override void Draw(
383 BackbufferBase backbuffer,
384 RectangleF destRectScreen)
385 {
386 if (Rotation == 0f)
387 {
388 base.Draw(backbuffer, destRectScreen);
389 return;
390 }
391
392 float centerX = destRectScreen.Left + destRectScreen.Width * 0.5f;
393 float centerY = destRectScreen.Top + destRectScreen.Height * 0.5f;
394 var canvas = backbuffer.Canvas;
395
396 canvas.Save();
397
398 try
399 {
400 canvas.RotateDegrees(Rotation, centerX, centerY);
401 base.Draw(backbuffer, destRectScreen);
402 }
403 finally
404 {
405 canvas.Restore();
406 }
407 }
408
415 public void TranslateWorldPx(int dx, int dy)
416 {
417 if (dx == 0 && dy == 0)
418 return;
419
420 var originalRect = CollisionArea;
421 var translatedRect = originalRect;
422 translatedRect.X += dx;
423 translatedRect.Y += dy;
424
425 var originalSceneCoord =
426 GetSceneLayerCoordsFromSpriteWorldRect(originalRect);
427
428 var translatedSceneCoord =
429 GetSceneLayerCoordsFromSpriteWorldRect(translatedRect);
430
431 var sceneDelta = new Vector2(
432 translatedSceneCoord.X - originalSceneCoord.X,
433 translatedSceneCoord.Y - originalSceneCoord.Y);
434
435 SetPosition(GetPosition() + sceneDelta);
436 }
437
443 public void CancelVelocityComponent(bool cancelX, bool cancelY)
444 {
445 Movement.ZeroVelocityComponent(cancelX, cancelY);
446 }
447
451 [JsonIgnore]
452 public MovementController Movement { get; private set; } = null!;
453
455 [JsonProperty]
456 public override Frame CurrentFrame
457 {
458 get => base.CurrentFrame;
459 set
460 {
461 Rectangle oldBounds = VisualBoundsWorld;
462 base.CurrentFrame = value;
463 InvalidateVisualChange(oldBounds, VisualBoundsWorld);
464 }
465 }
466
468 [JsonProperty]
469 public override bool Visible
470 {
471 get => visible;
472 set
473 {
474 visible = value;
475 _sceneLayer.RefreshQueue.AddWorldRect(VisualBoundsWorld);
476 }
477 }
478
482 [JsonProperty]
484 {
485 get => _horizAlign;
486 set
487 {
488 if (_sceneLayer != null)
489 {
490 var oldRect = VisualBoundsWorld;
491 _horizAlign = value;
492 InvalidateVisualChange(oldRect, VisualBoundsWorld);
493 }
494 else
495 {
496 _horizAlign = value;
497 }
498 }
499 }
500
504 [JsonProperty]
506 {
507 get => _vertAlign;
508 set
509 {
510 if (_sceneLayer != null)
511 {
512 var oldRect = VisualBoundsWorld;
513 _vertAlign = value;
514 InvalidateVisualChange(oldRect, VisualBoundsWorld);
515 }
516 else
517 {
518 _vertAlign = value;
519 }
520 }
521 }
522
526 [JsonProperty]
527 public int NudgeX
528 {
529 get => _nudgeX;
530 set
531 {
532 if (_sceneLayer != null)
533 {
534 var oldRect = VisualBoundsWorld;
535 _nudgeX = value;
536 InvalidateVisualChange(oldRect, VisualBoundsWorld);
537 }
538 else
539 {
540 _nudgeX = value;
541 }
542 }
543 }
544
548 [JsonProperty]
549 public int NudgeY
550 {
551 get => _nudgeY;
552 set
553 {
554 if (_sceneLayer != null)
555 {
556 var oldRect = VisualBoundsWorld;
557 _nudgeY = value;
558 InvalidateVisualChange(oldRect, VisualBoundsWorld);
559 }
560 else
561 {
562 _nudgeY = value;
563 }
564 }
565 }
566
570 [JsonProperty]
571 public Size RenderSize
572 {
573 get => _renderSize;
574 set
575 {
576 if (_sceneLayer != null)
577 {
578 var oldRect = VisualBoundsWorld;
579 _renderSize = value;
580 InvalidateVisualChange(oldRect, VisualBoundsWorld);
581 }
582 else
583 {
584 _renderSize = value;
585 }
586 }
587 }
588
590 [JsonIgnore]
591 public override Rectangle DrawLocationWorld =>
593 _sceneLayer,
595 _renderSize,
597 VertAlign,
598 new(NudgeX, NudgeY));
599
601 public static Rectangle GetPlacementBounds(
602 SceneLayer layer,
603 PointF position,
604 Size size,
605 HorizontalAlignment horizontal,
606 VerticalAlignment vertical,
607 Point nudge)
608 {
609 var anchor = layer.CoordinateSystem.GetAnchorPixelAtSceneLayerCoordinates(layer, position);
610
611 int x = horizontal switch
612 {
613 HorizontalAlignment.Center => (layer.TileWidth - size.Width) / 2,
614 HorizontalAlignment.Right => layer.TileWidth - size.Width,
615 _ => 0
616 };
617
618 int y = vertical switch
619 {
620 VerticalAlignment.Middle => (layer.TileHeight - size.Height) / 2,
621 VerticalAlignment.Bottom => layer.TileHeight - size.Height,
622 _ => 0
623 };
624
625 return new Rectangle(
626 anchor.X + x + nudge.X,
627 anchor.Y + y + nudge.Y,
628 size.Width,
629 size.Height);
630 }
631
633 [JsonIgnore]
634 public override bool IsPositionFixed => false;
635
637 [JsonIgnore]
638 public override PointF SceneLayerCoordinates => _sceneLayerCoordinates;
639
641 [JsonIgnore]
642 public override SceneLayer SceneLayer => _sceneLayer;
643
645 [JsonProperty]
646 public override int ZOrder
647 {
648 get => zOrder;
649 set
650 {
651 zOrder = Math.Max(1, value);
652 _sceneLayer.RefreshQueue.AddWorldRect(VisualBoundsWorld);
653 }
654 }
655
656 internal PointF GetSceneLayerCoordsFromSpriteWorldRect(Rectangle worldRectPx)
657 {
658 worldRectPx.X -= NudgeX;
659 worldRectPx.Y -= NudgeY;
660
661 switch (HorizAlign)
662 {
663 case HorizontalAlignment.Center:
664 worldRectPx.X -= (_sceneLayer.TileWidth - worldRectPx.Width) / 2;
665 break;
666 case HorizontalAlignment.Right:
667 worldRectPx.X -= _sceneLayer.TileWidth - worldRectPx.Width;
668 break;
669 }
670
671 switch (VertAlign)
672 {
673 case VerticalAlignment.Middle:
674 worldRectPx.Y -= (_sceneLayer.TileHeight - worldRectPx.Height) / 2;
675 break;
676 case VerticalAlignment.Bottom:
677 worldRectPx.Y -= _sceneLayer.TileHeight - worldRectPx.Height;
678 break;
679 }
680
681 return _sceneLayer.CoordinateSystem.GetSceneLayerCoordinatesAtPixel(
682 _sceneLayer,
683 worldRectPx.Location);
684 }
685
687 public override void Dispose()
688 {
689 _pendingDispose = true;
690 }
691
692 internal void DisposeImmediate()
693 {
694 GC.SuppressFinalize(this);
695 Disposing?.Invoke(this);
696
697 if (_sceneLayer != null)
698 _sceneLayer.RefreshQueue.AddWorldRect(VisualBoundsWorld);
699
700 SpriteMoved = null;
701 VisualBoundsChanged = null;
702 Disposing = null;
703
704 base.Dispose();
705 }
706
707 private void InvalidateVisualChange(Rectangle oldBounds, Rectangle newBounds)
708 {
709 Rectangle dirtyBounds = Rectangle.Union(oldBounds, newBounds);
710 dirtyBounds.Inflate(2, 2);
711 _sceneLayer.RefreshQueue.AddWorldRect(dirtyBounds);
712 VisualBoundsChanged?.Invoke(this);
713 }
714
715 private static Rectangle GetRotatedBounds(Rectangle rect, float degrees)
716 {
717 RectangleF bounds = GetRotatedBounds(
718 new RectangleF(
719 rect.X,
720 rect.Y,
721 rect.Width,
722 rect.Height),
723 degrees);
724
725 return Rectangle.FromLTRB(
726 (int)MathF.Floor(bounds.Left),
727 (int)MathF.Floor(bounds.Top),
728 (int)MathF.Ceiling(bounds.Right),
729 (int)MathF.Ceiling(bounds.Bottom));
730 }
731
732 private static RectangleF GetRotatedBounds(RectangleF rect, float degrees)
733 {
734 if (rect.IsEmpty || degrees % 360f == 0f)
735 return rect;
736
737 float radians = degrees * MathF.PI / 180f;
738 float sin = MathF.Abs(MathF.Sin(radians));
739 float cos = MathF.Abs(MathF.Cos(radians));
740 float width = rect.Width * cos + rect.Height * sin;
741 float height = rect.Width * sin + rect.Height * cos;
742 float centerX = rect.Left + rect.Width * 0.5f;
743 float centerY = rect.Top + rect.Height * 0.5f;
744
745 return new RectangleF(
746 centerX - width * 0.5f,
747 centerY - height * 0.5f,
748 width,
749 height);
750 }
751}
Provides data for sprite movement events.
void TranslateWorldPx(int dx, int dy)
Applies a world-pixel translation without rebuilding the absolute position from an integer rectangle,...
Definition Sprite.cs:415
override void Draw(BackbufferBase backbuffer, RectangleF destRectScreen)
Draws the current content into the backbuffer at the supplied screen-pixel bounds.
Definition Sprite.cs:382
int NudgeX
Gets or sets the nudge x.
Definition Sprite.cs:528
Action< Sprite >? Disposing
Occurs when disposal begins.
Definition Sprite.cs:39
override Rectangle DrawLocationWorld
Definition Sprite.cs:591
VerticalAlignment VertAlign
Gets or sets the vert align.
Definition Sprite.cs:506
MovementController Movement
Gets the controller that manages sprite movement.
Definition Sprite.cs:452
Size RenderSize
Gets or sets the render size.
Definition Sprite.cs:572
Action< SpriteMovedEventArgs >? SpriteMoved
Occurs when the sprite position changes.
Definition Sprite.cs:29
void CancelVelocityComponent(bool cancelX, bool cancelY)
Clears the requested horizontal and vertical velocity components.
Definition Sprite.cs:443
override bool Visible
Gets a value indicating whether the object is visible.
Definition Sprite.cs:470
Action< Sprite >? VisualBoundsChanged
Occurs when the sprite visual bounds change.
Definition Sprite.cs:34
MovementSpace PositionSpace
Gets the coordinate space used by the position API.
Definition Sprite.cs:302
void SetPosition(Vector2 pos)
Sets the sprite position in scene-layer grid coordinates and invalidates its old and new bounds.
Definition Sprite.cs:315
int NudgeY
Gets or sets the nudge y.
Definition Sprite.cs:550
static Rectangle GetPlacementBounds(SceneLayer layer, PointF position, Size size, HorizontalAlignment horizontal, VerticalAlignment vertical, Point nudge)
Computes the unrotated drawable bounds for a sprite position without materializing a sprite.
Definition Sprite.cs:601
override bool IsPositionFixed
Definition Sprite.cs:634
HorizontalAlignment HorizAlign
Gets or sets the horiz align.
Definition Sprite.cs:484
float Rotation
Gets or sets the clockwise visual rotation, in degrees, around the center of the sprite's render rect...
Definition Sprite.cs:342
override void Dispose()
Releases the resources owned by this instance.
Definition Sprite.cs:687
RectangleF GetVisualBoundsScreen(View view)
Gets the axis-aligned screen-pixel bounds enclosing the rotated sprite.
override PointF SceneLayerCoordinates
Definition Sprite.cs:638
Rectangle VisualBoundsWorld
Gets the axis-aligned world-pixel bounds enclosing the rotated sprite.
Definition Sprite.cs:367
override SceneLayer SceneLayer
Definition Sprite.cs:642
override int ZOrder
Gets the z-order of the element, which determines its visual stacking order relative to other element...
Definition Sprite.cs:647
Vector2 GetPosition()
Gets the sprite position in scene-layer grid coordinates.
override Frame CurrentFrame
Definition Sprite.cs:457
Represents an abstract base class for drawable tiles in the Gondwana engine. Provides core functional...
Definition Tile.cs:19
virtual RectangleF GetDrawLocationScreen(View view)
Transforms the drawable bounds into screen pixels for the specified view.
void AttachCollider(ICollider collider)
Attaches this tile's collider and applies any collision state that was set before the collider became...
Definition Tile.cs:516
virtual Rectangle CollisionArea
Gets the effective collision area in world coordinates.
Definition Tile.cs:245
bool pauseAnimation
The pause animation.
Definition Tile.cs:59
void CopyCollisionSettingsFrom(Tile source)
Copies collision behavior, profile, and effective frame metadata from another tile.
Definition Tile.cs:414
void SetCollisionProfile(string profileName)
Applies a named profile from this tile's parent scene. If the layer has not yet been attached to a sc...
Definition Tile.cs:386
void DetachCollider()
Detaches the current collider from its scene-layer registry without otherwise changing this tile's se...
Definition Tile.cs:502
string? CollisionProfileName
Gets the scene-level collision profile currently associated with this tile.
Definition Tile.cs:341
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...
SKCanvas Canvas
Gets the SkiaSharp canvas used for drawing operations on this backbuffer.
Represents a rendered view of a scene, combining a camera position with a viewport configuration to c...
Definition View.cs:14
Represents a single layer within a Scene, containing a grid of tiles and supporting various coordinat...
Definition SceneLayer.cs:40
string ID
Gets or sets the unique identifier for this layer.
int TileHeight
Gets or sets the height of each tile in this layer, measured in pixels.
Scene Scene
Gets or sets the parent scene that contains this layer.
int TileWidth
Gets or sets the width of each tile in this layer, measured in pixels.
static SceneLayer Empty
Gets the singleton empty scene layer instance.
string ID
Gets or sets the unique identifier for this scene.
Definition Scene.cs:194
Represents a collision entity that can be moved or repositioned in response to collision resolution.
Implemented by grid-space IMovable objects that belong to a specific Scenes.SceneLayer.
VerticalAlignment
Specifies the vertical alignment of a sprite or element.
@ Middle
Align to the middle (center).
HorizontalAlignment
Specifies the horizontal alignment of an element.
MovementSpace
Specifies the coordinate system used for movement calculations and updates.
Represents the source Tilesheet and its coordinates to render on a destination.
Definition Frame.cs:12