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
TilesheetRegion.cs
1using System.Drawing;
4using SkiaSharp;
5
7
11public sealed class TilesheetRegion : IDisposable
12{
16 public static readonly string DefaultRegionName = "default";
17
18 private TilesheetRegionSlice?[,]? _tileCache;
19 private readonly Dictionary<(int x, int y), CollisionAdjust> _frameCollisionAdjustments = [];
20 private readonly Dictionary<(int x, int y), TileCollisionType> _frameCollisionTypes = [];
22 private TileCollisionType _collisionType = TileCollisionType.None;
23 private bool _disposed;
24
25 private TilesheetRegion() { }
26
27 internal TilesheetRegion(
28 Tilesheet tilesheet,
29 string name,
30 Rectangle area,
31 Size tileSize,
32 Spacing tilePadding,
33 Spacing regionMargin,
34 Spacing overhangPixels,
35 CollisionAdjust collisionAdjust,
36 TileCollisionType collisionType)
37 {
38 Tilesheet = tilesheet ?? throw new ArgumentNullException(nameof(tilesheet));
39 Name = string.IsNullOrWhiteSpace(name) ? DefaultRegionName : name;
40
41 // Assign backing fields directly so construction performs one cache build.
42 _area = area;
43 _tileSize = tileSize;
44 _tilePadding = tilePadding;
45 _regionMargin = regionMargin;
46 Overhang = overhangPixels;
47 _collisionAdjust = collisionAdjust;
48 _collisionType = collisionType;
49
50 BuildTileCache();
51 }
52
53 private Rectangle _area;
54 private Size _tileSize;
55 private Spacing _tilePadding = Spacing.None;
56 private Spacing _regionMargin = Spacing.None;
57
61 public Tilesheet Tilesheet { get; private set; } = null!;
62
66 public string Name { get; private set; } = DefaultRegionName;
67
71 public Rectangle Area
72 {
73 get => _area;
74 set
75 {
76 _area = value;
77 BuildTileCache();
78 }
79 }
80
84 public Size TileSize
85 {
86 get => _tileSize;
87 set
88 {
89 _tileSize = value;
90 BuildTileCache();
91 }
92 }
93
98 {
99 get => _tilePadding;
100 set
101 {
102 _tilePadding = value;
103 BuildTileCache();
104 }
105 }
106
111 {
112 get => _regionMargin;
113 set
114 {
115 _regionMargin = value;
116 BuildTileCache();
117 }
118 }
119
123 public Spacing Overhang { get; set; } = Spacing.None;
124
130 {
131 get => _collisionAdjust;
132 set
133 {
134 ThrowIfDisposed();
135 _collisionAdjust = value;
136 ApplyDefaultCollisionAdjustToCache();
137 }
138 }
139
143 public Rectangle CollisionArea =>
144 _collisionAdjust.ApplyTo(new Rectangle(Point.Empty, _tileSize));
145
151 {
152 get => _collisionType;
153 set
154 {
155 ThrowIfDisposed();
156 _collisionType = value;
157 }
158 }
159
163 public int Columns => _tileCache?.GetLength(0) ?? 0;
164
168 public int Rows => _tileCache?.GetLength(1) ?? 0;
169
173 public int TileWidthIncludingPadding => _tilePadding.Left + _tileSize.Width + _tilePadding.Right;
174
178 public int TileHeightIncludingPadding => _tilePadding.Top + _tileSize.Height + _tilePadding.Bottom;
179
186 public SKImage? GetImage(int x, int y)
187 {
188 ThrowIfDisposed();
189
190 if (_tileCache == null)
191 BuildTileCache();
192
193 if (_tileCache == null ||
194 (uint)x >= (uint)_tileCache.GetLength(0) ||
195 (uint)y >= (uint)_tileCache.GetLength(1))
196 {
197 return null;
198 }
199
200 return _tileCache[x, y]?.Image;
201 }
202
209 public SKBitmap? GetBitmap(int x, int y)
210 {
211 ThrowIfDisposed();
212
213 if (_tileCache == null)
214 BuildTileCache();
215
216 if (_tileCache == null ||
217 (uint)x >= (uint)_tileCache.GetLength(0) ||
218 (uint)y >= (uint)_tileCache.GetLength(1))
219 {
220 return null;
221 }
222
223 return _tileCache[x, y]?.Bitmap;
224 }
225
230 public Dictionary<(int x, int y), SKBitmap> GetAllBitmaps()
231 {
232 ThrowIfDisposed();
233
234 if (_tileCache == null)
235 BuildTileCache();
236
237 var bitmaps = new Dictionary<(int x, int y), SKBitmap>();
238
239 if (_tileCache == null)
240 return bitmaps;
241
242 for (int y = 0; y < _tileCache.GetLength(1); y++)
243 {
244 for (int x = 0; x < _tileCache.GetLength(0); x++)
245 {
246 if (_tileCache[x, y] is { } slice)
247 bitmaps[(x, y)] = slice.Bitmap;
248 }
249 }
250
251 return bitmaps;
252 }
253
258 public Dictionary<(int x, int y), SKImage> GetAllImages()
259 {
260 ThrowIfDisposed();
261
262 if (_tileCache == null)
263 BuildTileCache();
264
265 var images = new Dictionary<(int x, int y), SKImage>();
266
267 if (_tileCache == null)
268 return images;
269
270 for (int y = 0; y < _tileCache.GetLength(1); y++)
271 {
272 for (int x = 0; x < _tileCache.GetLength(0); x++)
273 {
274 if (_tileCache[x, y] is { } slice)
275 images[(x, y)] = slice.Image;
276 }
277 }
278
279 return images;
280 }
281
289 {
290 ThrowIfDisposed();
291
292 if (!IsFrameCoordinateValid(x, y))
293 return _collisionAdjust;
294
295 if (_tileCache is not null && _tileCache[x, y] is { } slice)
296 return slice.CollisionAdjust;
297
298 return GetStoredFrameCollisionAdjust(x, y);
299 }
300
314 int x,
315 int y,
316 out CollisionAdjust collisionAdjust)
317 {
318 ThrowIfDisposed();
319
320 if (_tileCache is null)
321 BuildTileCache();
322
323 if (!IsFrameCoordinateValid(x, y))
324 {
325 collisionAdjust = default;
326 return false;
327 }
328
329 return _frameCollisionAdjustments.TryGetValue(
330 (x, y),
331 out collisionAdjust);
332 }
333
340 public void SetFrameCollisionAdjust(int x, int y, CollisionAdjust collisionAdjust)
341 {
342 ThrowIfDisposed();
343
344 if (_tileCache is null)
345 BuildTileCache();
346
347 if (!IsFrameCoordinateValid(x, y))
348 {
349 throw new ArgumentOutOfRangeException(
350 nameof(x),
351 $"Frame coordinates ({x}, {y}) are outside region '{Name}'.");
352 }
353
354 _frameCollisionAdjustments[(x, y)] = collisionAdjust;
355
356 if (_tileCache![x, y] is { } slice)
357 _tileCache[x, y] = slice.WithCollisionAdjust(collisionAdjust);
358 }
359
370 public bool ClearFrameCollisionAdjustOverride(int x, int y)
371 {
372 ThrowIfDisposed();
373
374 if (_tileCache is null)
375 BuildTileCache();
376
377 if (!IsFrameCoordinateValid(x, y))
378 {
379 throw new ArgumentOutOfRangeException(
380 nameof(x),
381 $"Frame coordinates ({x}, {y}) are outside region '{Name}'.");
382 }
383
384 if (!_frameCollisionAdjustments.Remove((x, y)))
385 return false;
386
387 if (_tileCache![x, y] is { } slice)
388 _tileCache[x, y] = slice.WithCollisionAdjust(_collisionAdjust);
389
390 return true;
391 }
392
399 public Rectangle GetFrameCollisionArea(int x, int y) =>
401 .ApplyTo(new Rectangle(Point.Empty, _tileSize));
402
410 {
411 ThrowIfDisposed();
412
413 if (!IsFrameCoordinateValid(x, y))
414 return _collisionType;
415
416 return _frameCollisionTypes.TryGetValue((x, y), out var collisionType)
417 ? collisionType
418 : _collisionType;
419 }
420
429 int x,
430 int y,
431 out TileCollisionType collisionType)
432 {
433 ThrowIfDisposed();
434
435 if (_tileCache is null)
436 BuildTileCache();
437
438 if (!IsFrameCoordinateValid(x, y))
439 {
440 collisionType = default;
441 return false;
442 }
443
444 return _frameCollisionTypes.TryGetValue((x, y), out collisionType);
445 }
446
453 public void SetFrameCollisionType(int x, int y, TileCollisionType collisionType)
454 {
455 ThrowIfDisposed();
456
457 if (_tileCache is null)
458 BuildTileCache();
459
460 if (!IsFrameCoordinateValid(x, y))
461 {
462 throw new ArgumentOutOfRangeException(
463 nameof(x),
464 $"Frame coordinates ({x}, {y}) are outside region '{Name}'.");
465 }
466
467 _frameCollisionTypes[(x, y)] = collisionType;
468 }
469
477 public bool ClearFrameCollisionTypeOverride(int x, int y)
478 {
479 ThrowIfDisposed();
480
481 if (_tileCache is null)
482 BuildTileCache();
483
484 if (!IsFrameCoordinateValid(x, y))
485 {
486 throw new ArgumentOutOfRangeException(
487 nameof(x),
488 $"Frame coordinates ({x}, {y}) are outside region '{Name}'.");
489 }
490
491 return _frameCollisionTypes.Remove((x, y));
492 }
493
497 internal void BuildTileCache()
498 {
499 ThrowIfDisposed();
500 ClearTileCache();
501
502 if (Tilesheet == null ||
503 Tilesheet.SkBitmap == null ||
504 Tilesheet.SkBitmap.IsEmpty ||
505 _tileSize.Width <= 0 ||
506 _tileSize.Height <= 0 ||
507 _area.Width <= 0 ||
508 _area.Height <= 0)
509 {
510 return;
511 }
512
513 if (_tilePadding.Left < 0 || _tilePadding.Top < 0 ||
514 _tilePadding.Right < 0 || _tilePadding.Bottom < 0)
515 {
516 throw new InvalidOperationException("Tilesheet region tile padding cannot be negative.");
517 }
518
519 if (_regionMargin.Left < 0 || _regionMargin.Top < 0 ||
520 _regionMargin.Right < -_tilePadding.Right || _regionMargin.Bottom < -_tilePadding.Bottom)
521 {
522 throw new InvalidOperationException(
523 "Leading region margins cannot be negative; trailing margins may only cancel trailing tile padding.");
524 }
525
527 return;
528
529 int xTiles = (_area.Width - _regionMargin.Left - _regionMargin.Right) /
531
532 int yTiles = (_area.Height - _regionMargin.Top - _regionMargin.Bottom) /
534
535 if (xTiles <= 0 || yTiles <= 0)
536 return;
537
538 PruneFrameCollisionAdjustments(xTiles, yTiles);
539 PruneFrameCollisionTypes(xTiles, yTiles);
540 _tileCache = new TilesheetRegionSlice?[xTiles, yTiles];
541
542 var regionArea = Area;
543 var bitmapBounds = Tilesheet.SkBitmap.Info.Rect;
544
545 for (int y = 0; y < yTiles; y++)
546 {
547 for (int x = 0; x < xTiles; x++)
548 {
549 var srcRect = GetTileBounds(x, y);
550
551 // Prevent this region from bleeding into another region or outside the image.
552 if (!regionArea.Contains(srcRect) ||
553 !bitmapBounds.Contains(srcRect.ToSKRectI()))
554 {
555 continue;
556 }
557
558 var slice = CreateSlice(
559 srcRect,
560 GetStoredFrameCollisionAdjust(x, y));
561
562 if (slice.HasValue)
563 _tileCache[x, y] = slice.Value;
564 }
565 }
566 }
567
568 internal void ClearTileCache()
569 {
570 if (_tileCache == null)
571 return;
572
573 for (int y = 0; y < _tileCache.GetLength(1); y++)
574 {
575 for (int x = 0; x < _tileCache.GetLength(0); x++)
576 {
577 _tileCache[x, y]?.Bitmap.Dispose();
578 _tileCache[x, y]?.Image.Dispose();
579 _tileCache[x, y] = null;
580 }
581 }
582
583 _tileCache = null;
584 }
585
586 internal Rectangle GetFrameSourceBounds(int xTile, int yTile)
587 {
588 ThrowIfDisposed();
589
590 if (_tileCache is null)
591 BuildTileCache();
592
593 return IsFrameCoordinateValid(xTile, yTile)
594 ? GetTileBounds(xTile, yTile)
595 : Rectangle.Empty;
596 }
597
598 private Rectangle GetTileBounds(int xTile, int yTile)
599 {
600 int x = _area.X + _regionMargin.Left + (xTile * TileWidthIncludingPadding);
601 int y = _area.Y + _regionMargin.Top + (yTile * TileHeightIncludingPadding);
602
603 return new Rectangle(
604 x + _tilePadding.Left,
605 y + _tilePadding.Top,
606 _tileSize.Width,
607 _tileSize.Height);
608 }
609
610 private TilesheetRegionSlice? CreateSlice(
611 Rectangle srcRect,
612 CollisionAdjust collisionAdjust)
613 {
614 var srcInfo = Tilesheet.SkBitmap.Info;
615
616 var sliceInfo = new SKImageInfo(
617 srcRect.Width,
618 srcRect.Height,
619 srcInfo.ColorType,
620 srcInfo.AlphaType);
621
622 var bmp = new SKBitmap(sliceInfo);
623 bmp.Erase(SKColors.Transparent);
624
625 if (!Tilesheet.SkBitmap.ExtractSubset(bmp, srcRect.ToSKRectI()))
626 {
627 bmp.Dispose();
628 return null;
629 }
630
631 var img = SKImage.FromBitmap(bmp);
632 return new TilesheetRegionSlice(bmp, img, collisionAdjust);
633 }
634
635 private CollisionAdjust GetStoredFrameCollisionAdjust(int x, int y) =>
636 _frameCollisionAdjustments.TryGetValue((x, y), out var collisionAdjust)
637 ? collisionAdjust
638 : _collisionAdjust;
639
640 private bool IsFrameCoordinateValid(int x, int y) =>
641 _tileCache is not null &&
642 (uint)x < (uint)_tileCache.GetLength(0) &&
643 (uint)y < (uint)_tileCache.GetLength(1);
644
645 private void ApplyDefaultCollisionAdjustToCache()
646 {
647 if (_tileCache is null)
648 return;
649
650 for (int y = 0; y < _tileCache.GetLength(1); y++)
651 {
652 for (int x = 0; x < _tileCache.GetLength(0); x++)
653 {
654 if (!_frameCollisionAdjustments.ContainsKey((x, y)) &&
655 _tileCache[x, y] is { } slice)
656 {
657 _tileCache[x, y] = slice.WithCollisionAdjust(_collisionAdjust);
658 }
659 }
660 }
661 }
662
663 private void PruneFrameCollisionAdjustments(int columns, int rows)
664 {
665 foreach (var key in _frameCollisionAdjustments.Keys.ToArray())
666 {
667 if ((uint)key.x >= (uint)columns || (uint)key.y >= (uint)rows)
668 _frameCollisionAdjustments.Remove(key);
669 }
670 }
671
672 private void PruneFrameCollisionTypes(int columns, int rows)
673 {
674 foreach (var key in _frameCollisionTypes.Keys.ToArray())
675 {
676 if ((uint)key.x >= (uint)columns || (uint)key.y >= (uint)rows)
677 _frameCollisionTypes.Remove(key);
678 }
679 }
680
681 private void ThrowIfDisposed()
682 {
683 if (_disposed)
684 throw new ObjectDisposedException(nameof(TilesheetRegion));
685 }
686
690 public void Dispose()
691 {
692 if (_disposed)
693 return;
694
695 _disposed = true;
696 ClearTileCache();
697 _frameCollisionAdjustments.Clear();
698 _frameCollisionTypes.Clear();
699 }
700}
Represents a rectangular region within a tilesheet that contains a grid of frames.
Spacing RegionMargin
Gets or sets the spacing inside the region boundary.
Dictionary<(int x, int y), SKBitmap > GetAllBitmaps()
Collects the cached frame bitmaps indexed by their tile coordinates.
Rectangle Area
Gets or sets the region bounds in tilesheet image pixels.
TileCollisionType CollisionType
Gets or sets the collision type inherited by frames that do not have an explicit frame-level override...
SKImage? GetImage(int x, int y)
Gets the cached image for the specified frame.
int Rows
Gets the number of tile rows in the region.
SKBitmap? GetBitmap(int x, int y)
Gets the cached bitmap for the specified frame.
static readonly string DefaultRegionName
The default name assigned to tilesheet regions when no name is specified.
Spacing Overhang
Gets or sets visual overhang. This affects rendering, not slicing.
bool TryGetFrameCollisionAdjustOverride(int x, int y, out CollisionAdjust collisionAdjust)
Attempts to get the explicit collision adjustment assigned to one frame.
Rectangle CollisionArea
Gets the region-default frame-local collision rectangle.
Spacing TilePadding
Gets or sets the spacing around each tile.
void SetFrameCollisionAdjust(int x, int y, CollisionAdjust collisionAdjust)
Sets the collision adjustment for one frame and updates its cache entry.
CollisionAdjust CollisionAdjust
Gets or sets the collision adjustment inherited by frames that do not have an explicit frame-level ov...
void SetFrameCollisionType(int x, int y, TileCollisionType collisionType)
Sets an explicit collision type for one frame.
int Columns
Gets the number of tile columns in the region.
Rectangle GetFrameCollisionArea(int x, int y)
Gets the frame-local collision rectangle for one frame.
CollisionAdjust GetFrameCollisionAdjust(int x, int y)
Gets the effective collision adjustment for one frame.
Size TileSize
Gets or sets the tile dimensions in pixels.
int TileWidthIncludingPadding
Gets the horizontal tile stride including padding.
bool ClearFrameCollisionTypeOverride(int x, int y)
Removes a frame-level collision type so the frame once again inherits CollisionType.
Dictionary<(int x, int y), SKImage > GetAllImages()
Collects the cached frame images indexed by their tile coordinates.
TileCollisionType GetFrameCollisionType(int x, int y)
Gets the effective collision type for one frame.
void Dispose()
Releases the resources owned by this instance.
bool ClearFrameCollisionAdjustOverride(int x, int y)
Removes a frame-level collision adjustment so the frame once again inherits CollisionAdjust.
bool TryGetFrameCollisionTypeOverride(int x, int y, out TileCollisionType collisionType)
Attempts to get the explicit collision type assigned to one frame.
Tilesheet Tilesheet
Gets the tilesheet that owns this region.
int TileHeightIncludingPadding
Gets the vertical tile stride including padding.
Represents a tilesheet image and metadata for rendering tiles.
Definition Tilesheet.cs:15
SKBitmap SkBitmap
Gets the current tilesheet bitmap used for rendering.
Definition Tilesheet.cs:157
@ Rectangle
Particles are spawned uniformly within a rectangular area. This is the default distribution.
record struct Spacing([property:JsonProperty("left")] int Left, [property:JsonProperty("top")] int Top, [property:JsonProperty("right")] int Right, [property:JsonProperty("bottom")] int Bottom)
Represents dimensions in pixels when spacing Tilesheets.
Definition Spacing.cs:12
TileCollisionType
Defines the default collision behavior associated with a tilesheet region, frame, or runtime tile.
Per-edge inset amounts applied to visual bounds to produce a collision rectangle.
static readonly CollisionAdjust None
Represents an adjustment with no pixel offsets.
readonly Rectangle ApplyTo(Rectangle rectangle)
Applies this adjustment to the supplied rectangle.