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
Tilesheet.cs
1using System.Drawing;
6using Microsoft.Extensions.Logging;
7using SkiaSharp;
8
10
14public sealed class Tilesheet : IDisposable
15{
16 private SKImage? _atlasImage;
17
18 [Newtonsoft.Json.JsonIgnore] internal DefinitionProvenance? DefinitionProvenance { get; set; }
19
24 internal SKImage? AtlasImage
25 {
26 get
27 {
28 if (_disposed || SkBitmap is null || SkBitmap.IsEmpty)
29 return null;
30
31 return _atlasImage ??= SKImage.FromBitmap(SkBitmap);
32 }
33 }
34
38 public event Action<Tilesheet>? Disposed;
39
40 private Tilesheet() { }
41
42 internal Tilesheet(string name, SKBitmap bitmap, bool addDefaultRegion = true)
43 {
44 Name = name;
45 SkBitmap = bitmap ?? throw new ArgumentNullException(nameof(bitmap));
46
47 if (addDefaultRegion)
48 AddDefaultRegion();
49 }
50
51 internal Tilesheet(string name, Stream stream, bool addDefaultRegion = true)
52 : this(
53 name,
54 SKBitmap.Decode(stream) ?? throw new ArgumentException("Invalid image stream."),
55 addDefaultRegion)
56 {
57 }
58
59 internal Tilesheet(string name, string file, bool addDefaultRegion = true)
60 : this(
61 name,
62 SKBitmap.Decode(file) ?? throw new ArgumentException($"Invalid image file: {file}"),
63 addDefaultRegion)
64 {
65 ImageFilePath = file;
66 }
67
68 internal Tilesheet(AssetsFile resFile, string entryName, bool addDefaultRegion = true)
69 {
70 ArgumentNullException.ThrowIfNull(resFile);
71
72 if (string.IsNullOrWhiteSpace(entryName))
73 throw new ArgumentException("Asset entry name must be a non-empty string.", nameof(entryName));
74
75 AssetIdentifier = new AssetsFileIdentifier(resFile, AssetTypes.Image, entryName);
76
77 using var assetStream = AssetIdentifier.Data
78 ?? throw new InvalidOperationException(
79 $"Tilesheet asset '{entryName}' could not be loaded from AssetsFile '{resFile.FilePath}'. " +
80 "The asset entry does not exist or returned a null data stream.");
81
82 SkBitmap = SKBitmap.Decode(assetStream)
83 ?? throw new ArgumentException(
84 $"Failed to decode tilesheet bitmap from asset '{entryName}' in AssetsFile '{resFile.FilePath}'. " +
85 "The asset data is corrupt or not a supported image format.");
86
87 Name = entryName;
88
89 if (addDefaultRegion)
90 AddDefaultRegion();
91 }
92
100 internal Tilesheet(Tilesheet baseSheet, string name, string file)
101 {
102 ArgumentNullException.ThrowIfNull(baseSheet);
103
104 Name = name;
105
106 SkBitmap = SKBitmap.Decode(file)
107 ?? throw new ArgumentException($"Invalid image file: {file}");
108
109 ImageFilePath = file;
110 ValueBag = new(baseSheet.ValueBag);
111
112 foreach (var region in baseSheet.Regions)
113 {
114 var copiedRegion = AddRegion(
115 region.Name,
116 region.Area,
117 region.TileSize,
118 region.TilePadding,
119 region.RegionMargin,
120 region.Overhang,
121 region.CollisionAdjust,
122 region.CollisionType);
123
124 for (int y = 0; y < region.Rows; y++)
125 {
126 for (int x = 0; x < region.Columns; x++)
127 {
128 if (region.TryGetFrameCollisionAdjustOverride(
129 x,
130 y,
131 out var frameCollisionAdjust))
132 {
133 copiedRegion.SetFrameCollisionAdjust(
134 x,
135 y,
136 frameCollisionAdjust);
137 }
138
139 if (region.TryGetFrameCollisionTypeOverride(
140 x,
141 y,
142 out var frameCollisionType))
143 {
144 copiedRegion.SetFrameCollisionType(
145 x,
146 y,
147 frameCollisionType);
148 }
149 }
150 }
151 }
152 }
153
157 public SKBitmap SkBitmap { get; private set; } = null!;
158
162 public SKBitmap? SkBitmapOriginal { get; private set; }
163
167 public string Name { get; internal set; } = string.Empty;
168
172 public List<TilesheetRegion> Regions { get; private set; } = new();
173
178
182 public TypedValueBag ValueBag { get; set; } = new();
183
187 public AssetsFileIdentifier? AssetIdentifier { get; private set; }
188
192 public string ImageFilePath { get; private set; } = string.Empty;
193
197 public SKColor? MaskColor { get; private set; }
198
202 public byte MaskTolerance { get; private set; } = 5;
203
207 public bool Premultiplied { get; private set; }
208
222 string name,
223 Rectangle area,
224 Size tileSize,
225 Spacing? tilePadding = null,
226 Spacing? regionMargin = null,
227 Spacing? overhangPixels = null,
228 CollisionAdjust? collisionAdjust = null,
229 TileCollisionType collisionType = TileCollisionType.None)
230 {
231 if (string.IsNullOrWhiteSpace(name))
232 throw new ArgumentException("Region name must be a non-empty string.", nameof(name));
233
234 if (GetRegion(name) != null)
235 throw new ArgumentException($"A tilesheet region named '{name}' already exists.", nameof(name));
236
237 var region = new TilesheetRegion(
238 this,
239 name,
240 area,
241 tileSize,
242 tilePadding ?? Spacing.None,
243 regionMargin ?? Spacing.None,
244 overhangPixels ?? Spacing.None,
245 collisionAdjust ?? CollisionAdjust.None,
246 collisionType);
247
248 Regions.Add(region);
249 return region;
250 }
251
257 public TilesheetRegion? GetRegion(string name)
258 {
259 if (string.IsNullOrWhiteSpace(name))
260 return null;
261
262 foreach (var region in Regions)
263 {
264 if (string.Equals(region.Name, name, StringComparison.OrdinalIgnoreCase))
265 return region;
266 }
267
268 return null;
269 }
270
277 public bool RemoveRegion(string name, bool dispose = true)
278 {
279 var region = GetRegion(name);
280
281 if (region == null)
282 return false;
283
284 Regions.Remove(region);
285
286 if (dispose)
287 region.Dispose();
288
289 return true;
290 }
291
299 public Frame GetFrame(string regionName, int x, int y) =>
300 new(
301 this,
302 regionName,
303 x,
304 y);
305
312 public Frame GetFrame(int x, int y) =>
313 new(
314 this,
316 x,
317 y);
318
324 public void ApplyMask(SKColor? maskColor = null, byte tolerance = 5)
325 {
326 if (SkBitmap == null || SkBitmap.IsEmpty)
327 throw new ArgumentException("Invalid bitmap.");
328
329 var targetColor = maskColor ?? SKColors.White;
330
331 MaskColor = targetColor;
332 MaskTolerance = tolerance;
333 Premultiplied = true;
334
335 InvalidateAtlasImage();
336 ClearTileCache();
337
338 if (SkBitmap.Info.AlphaType == SKAlphaType.Opaque)
339 {
340 var info = new SKImageInfo(
341 SkBitmap.Width,
342 SkBitmap.Height,
343 SkBitmap.Info.ColorType,
344 SKAlphaType.Premul);
345
346 var withAlpha = new SKBitmap(info);
347
348 using (var canvas = new SKCanvas(withAlpha))
349 canvas.DrawBitmap(SkBitmap, 0, 0);
350
351 SkBitmap.Dispose();
352 SkBitmap = withAlpha;
353 }
354
355 SkBitmapOriginal?.Dispose();
356 SkBitmapOriginal = SkBitmap.Copy();
357
358 SkBitmap.ApplyAlphaMask(targetColor, tolerance);
359 SkBitmap = SkBitmap.PremultiplyAlpha();
360
361 BuildTileCache();
362 }
363
368 {
369 if (SkBitmap == null || SkBitmap.IsEmpty)
370 throw new ArgumentException("Invalid bitmap.");
371
372 Premultiplied = true;
373 InvalidateAtlasImage();
374 ClearTileCache();
375
376 SkBitmapOriginal?.Dispose();
377 SkBitmapOriginal = SkBitmap.Copy();
378 SkBitmap = SkBitmap.PremultiplyAlpha();
379
380 BuildTileCache();
381 }
382
389 public byte[] ToByteArray(
390 SKEncodedImageFormat format = SKEncodedImageFormat.Png,
391 int quality = 100)
392 {
393 if (SkBitmap == null || SkBitmap.IsEmpty)
394 throw new ArgumentException("Invalid bitmap.");
395
396 return SkBitmap.EncodeBitmapToBytes(format, quality);
397 }
398
412 string imageFilePath,
413 SKEncodedImageFormat format = SKEncodedImageFormat.Png,
414 int quality = 100)
415 {
416 if (_disposed)
417 throw new ObjectDisposedException(nameof(Tilesheet));
418
419 if (string.IsNullOrWhiteSpace(imageFilePath))
420 {
421 throw new ArgumentException(
422 "Image file path must be a non-empty string.",
423 nameof(imageFilePath));
424 }
425
426 if (quality is < 0 or > 100)
427 {
428 throw new ArgumentOutOfRangeException(
429 nameof(quality),
430 quality,
431 "Image encoding quality must be between 0 and 100.");
432 }
433
434 if (SkBitmap == null || SkBitmap.IsEmpty)
435 {
436 throw new InvalidOperationException(
437 "Tilesheet does not contain a valid bitmap to persist.");
438 }
439
440 var fullPath = Path.GetFullPath(imageFilePath);
441 var directory = Path.GetDirectoryName(fullPath);
442
443 if (!string.IsNullOrWhiteSpace(directory))
444 Directory.CreateDirectory(directory);
445
446 var sourceBitmap = SkBitmapOriginal ?? SkBitmap;
447 var imageBytes = sourceBitmap.EncodeBitmapToBytes(format, quality);
448 File.WriteAllBytes(fullPath, imageBytes);
449
450 ImageFilePath = fullPath;
451 AssetIdentifier = null;
452 }
453
461 public SKImage? GetImage(string regionName, int x, int y) =>
462 GetRegion(regionName)?.GetImage(x, y);
463
471 public SKBitmap? GetBitmap(string regionName, int x, int y) =>
472 GetRegion(regionName)?.GetBitmap(x, y);
473
478 public Dictionary<(string regionName, int x, int y), SKBitmap> GetAllBitmaps()
479 {
480 var tiles = new Dictionary<(string regionName, int x, int y), SKBitmap>();
481
482 foreach (var region in Regions)
483 {
484 foreach (var tile in region.GetAllBitmaps())
485 tiles[(region.Name, tile.Key.x, tile.Key.y)] = tile.Value;
486 }
487
488 return tiles;
489 }
490
495 public Dictionary<(string regionName, int x, int y), SKImage> GetAllImages()
496 {
497 var tiles = new Dictionary<(string regionName, int x, int y), SKImage>();
498
499 foreach (var region in Regions)
500 {
501 foreach (var tile in region.GetAllImages())
502 tiles[(region.Name, tile.Key.x, tile.Key.y)] = tile.Value;
503 }
504
505 return tiles;
506 }
507
512 public TilesheetRegion this[string regionName] =>
513 GetRegion(regionName)
514 ?? throw new ArgumentException(
515 $"No tilesheet region named '{regionName}' exists.",
516 nameof(regionName));
517
524 public Frame this[string regionName, int x, int y] =>
525 GetFrame(regionName, x, y);
526
532 public Frame this[int x, int y] => GetFrame(x, y);
533
534 private void BuildTileCache()
535 {
536 foreach (var region in Regions)
537 region.BuildTileCache();
538 }
539
540 private void ClearTileCache()
541 {
542 foreach (var region in Regions)
543 region.ClearTileCache();
544 }
545
546 private void InvalidateAtlasImage()
547 {
548 _atlasImage?.Dispose();
549 _atlasImage = null;
550 }
551
552 private void AddDefaultRegion(
553 Size? tileSize = null,
554 Spacing? tilePadding = null,
555 Spacing? regionMargin = null,
556 Spacing? overhangPixels = null,
557 CollisionAdjust? collisionAdjust = null,
558 TileCollisionType collisionType = TileCollisionType.None)
559 {
560 AddRegion(
561 TilesheetRegion.DefaultRegionName,
562 new Rectangle(
563 0,
564 0,
565 SkBitmap.Width,
566 SkBitmap.Height),
567 tileSize ?? Size.Empty,
568 tilePadding ?? Spacing.None,
569 regionMargin ?? Spacing.None,
570 overhangPixels ?? Spacing.None,
571 collisionAdjust ?? CollisionAdjust.None,
572 collisionType);
573 }
574
575 private bool _disposed;
576
580 public void Dispose()
581 {
582 Dispose(true);
583 GC.SuppressFinalize(this);
584 }
585
586 private void Dispose(bool disposing)
587 {
588 if (_disposed)
589 return;
590
591 _disposed = true;
592
593 if (!disposing)
594 return;
595
596 foreach (var region in Regions)
597 region.Dispose();
598
599 Regions.Clear();
600
601 InvalidateAtlasImage();
602 SkBitmap?.Dispose();
603 SkBitmapOriginal?.Dispose();
604
605 try
606 {
607 Disposed?.Invoke(this);
608 }
609 catch (Exception ex)
610 {
611 Engine.Logger.LogError(ex, "Error during Tilesheet Disposed event handling.");
612 }
613
614 Disposed = null;
615 }
616}
Represents an identifier for a specific asset within a file, including its type and name.
Represents an asset file used by the engine, providing functionality to load, manage,...
Definition AssetsFile.cs:18
Represents a rectangular region within a tilesheet that contains a grid of frames.
SKImage? GetImage(int x, int y)
Gets the cached image for the specified frame.
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.
Represents a tilesheet image and metadata for rendering tiles.
Definition Tilesheet.cs:15
bool Premultiplied
Gets whether alpha premultiplication has been applied.
Definition Tilesheet.cs:207
TilesheetRegion DefaultRegion
Gets the default tilesheet region.
Definition Tilesheet.cs:177
TypedValueBag ValueBag
Gets or sets the custom typed values associated with this object.
Definition Tilesheet.cs:182
void PersistImageToFile(string imageFilePath, SKEncodedImageFormat format=SKEncodedImageFormat.Png, int quality=100)
Persists this tilesheet's source image to a file and promotes the tilesheet from a runtime-only bitma...
Definition Tilesheet.cs:411
AssetsFileIdentifier? AssetIdentifier
Gets the packed asset from which the image was loaded, if any.
Definition Tilesheet.cs:187
Frame GetFrame(string regionName, int x, int y)
Creates a frame reference at the specified tile coordinates.
SKImage? GetImage(string regionName, int x, int y)
Gets the cached image for the specified frame.
Action< Tilesheet >? Disposed
Occurs after the object releases its resources.
Definition Tilesheet.cs:38
void ApplyMask(SKColor? maskColor=null, byte tolerance=5)
Applies a color-key transparency mask and rebuilds the frame cache.
Definition Tilesheet.cs:324
byte MaskTolerance
Gets the per-channel tolerance used for transparency masking.
Definition Tilesheet.cs:202
void ApplyPremultiplyAlpha()
Premultiplies the bitmap alpha and rebuilds the frame cache.
Definition Tilesheet.cs:367
Dictionary<(string regionName, int x, int y), SKImage > GetAllImages()
Collects the cached frame images indexed by their tile coordinates.
Definition Tilesheet.cs:495
bool RemoveRegion(string name, bool dispose=true)
Removes the named tilesheet region and optionally disposes it.
Definition Tilesheet.cs:277
SKBitmap? GetBitmap(string regionName, int x, int y)
Gets the cached bitmap for the specified frame.
void Dispose()
Releases the resources owned by this instance.
Definition Tilesheet.cs:580
Dictionary<(string regionName, int x, int y), SKBitmap > GetAllBitmaps()
Collects the cached frame bitmaps indexed by their tile coordinates.
Definition Tilesheet.cs:478
List< TilesheetRegion > Regions
Gets the named frame regions in the tilesheet.
Definition Tilesheet.cs:172
SKColor? MaskColor
Gets the color used for transparency masking.
Definition Tilesheet.cs:197
byte[] ToByteArray(SKEncodedImageFormat format=SKEncodedImageFormat.Png, int quality=100)
Encodes the tilesheet bitmap using the requested image format and quality.
Definition Tilesheet.cs:389
string ImageFilePath
Gets the loose source image path, when available.
Definition Tilesheet.cs:192
SKBitmap? SkBitmapOriginal
Gets the source bitmap retained before masking or alpha conversion.
Definition Tilesheet.cs:162
SKBitmap SkBitmap
Gets the current tilesheet bitmap used for rendering.
Definition Tilesheet.cs:157
Frame GetFrame(int x, int y)
Creates a frame reference at the specified tile coordinates.
TilesheetRegion? GetRegion(string name)
Finds a tilesheet region by its case-insensitive name.
Definition Tilesheet.cs:257
TilesheetRegion AddRegion(string name, Rectangle area, Size tileSize, Spacing? tilePadding=null, Spacing? regionMargin=null, Spacing? overhangPixels=null, CollisionAdjust? collisionAdjust=null, TileCollisionType collisionType=TileCollisionType.None)
Adds a region with the supplied default collision adjustment and collision type.
Definition Tilesheet.cs:221
Represents the core game engine singleton responsible for managing the main update loop,...
Definition Engine.cs:36
static ILogger< Engine > Logger
Gets the logger instance used by the engine for diagnostic and informational messages.
Definition Engine.cs:59
A flexible, strongly-typed value container intended for runtime-attached metadata and ephemeral engin...
AssetTypes
Defines the types of assets that can be stored and managed by the engine.
Definition AssetTypes.cs:8
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.
Represents the source Tilesheet and its coordinates to render on a destination.
Definition Frame.cs:12
Per-edge inset amounts applied to visual bounds to produce a collision rectangle.
static readonly CollisionAdjust None
Represents an adjustment with no pixel offsets.