1using ICSharpCode.SharpZipLib.Zip;
2using Microsoft.Extensions.Logging;
16[JsonObject(IsReference =
true)]
17public sealed class AssetsFile : IDisposable
19 private static readonly List<AssetsFile> _allAssetsFiles =
new();
24 public static IReadOnlyList<AssetsFile>
AllAssetsFiles => _allAssetsFiles.AsReadOnly();
31 foreach (var assetFile
in _allAssetsFiles.ToList())
35 private ZipFile? _zipFile;
39 private readonly Dictionary<AssetsFileEntry, byte[]> _zipEntries =
new();
41 private bool _isLoaded;
50 public static void Validate(
string path,
string? password =
null,
bool testData =
true)
52 using var archive =
new ZipFile(File.OpenRead(path));
53 archive.Password = password;
54 var keys =
new HashSet<AssetsFileEntry>();
56 foreach (ZipEntry entry
in archive)
63 if (key is
null || !Enum.IsDefined(key.AssetType) ||
string.IsNullOrWhiteSpace(key.AssetName))
64 throw new InvalidDataException($
"Invalid bundle entry key: {entry.Name}");
67 throw new InvalidDataException($
"Duplicate bundle entry key: {entry.Name}");
70 if (!archive.TestArchive(testData))
71 throw new InvalidDataException(
"Bundle integrity check failed. Check the password and archive contents.");
79 private AssetsFile(
bool register)
82 _allAssetsFiles.Add(
this);
93 public static AssetsFile
LoadOrCreate(
string path,
string? password =
null,
bool encrypt =
false)
115 if (
string.IsNullOrWhiteSpace(path))
116 throw new ArgumentException(
"path cannot be null or empty.", nameof(path));
118 var assetFile =
new AssetsFile(
register)
127 if (File.Exists(path))
130 assetFile._isLoaded =
true;
153 public static AssetsFile
Load(Stream stream,
string? password =
null,
bool register =
true)
192 ArgumentNullException.ThrowIfNull(stream);
195 throw new ArgumentException(
"Stream must be readable.", nameof(stream));
197 var assetFile =
new AssetsFile(
register)
200 SourcePath =
string.IsNullOrWhiteSpace(sourcePath) ? null : sourcePath
205 assetFile.LoadZip(stream, limits);
219 public string FilePath {
get;
private set; } =
string.Empty;
239 private set => _sourcePath = value;
242 private string? _sourcePath;
244 private void EnsureLoaded()
250 private void LoadZip()
261 using var stream = File.OpenRead(
FilePath);
270 if (limits is not
null && !stream.CanSeek)
271 throw new ArgumentException(
"Bounded archive reads require a seekable stream.", nameof(stream));
275 Engine.Logger.LogInformation(
"Loading assets file.");
284 MemoryStream? bufferedStream = stream.CanSeek ? null :
new MemoryStream();
285 Stream archiveStream = stream;
287 if (bufferedStream is not
null)
289 stream.CopyTo(bufferedStream);
290 bufferedStream.Position = 0;
291 archiveStream = bufferedStream;
294 _zipFile =
new ZipFile(archiveStream) { IsStreamOwner =
false };
295 limits?.Validate(_zipFile);
297 byte[]? copyBuffer = limits is
null ? null :
new byte[81920];
299 if (!
string.IsNullOrEmpty(
Password))
303 var testEntry = _zipFile.Cast<ZipEntry>().FirstOrDefault(e => e.IsFile);
305 if (testEntry !=
null)
307 using var testStream = _zipFile.GetInputStream(testEntry);
308 testStream.ReadByte();
311 foreach (ZipEntry entry
in _zipFile)
320 var key = AssetsFileEntry.FromString(entry.Name);
324 Engine.Logger.LogWarning(
"Invalid entry in assets file: {EntryName}", entry.Name);
328 using var entryStream = _zipFile.GetInputStream(entry);
329 using var ms =
new MemoryStream();
332 entryStream.CopyTo(ms);
337 while ((count = entryStream.Read(copyBuffer!, 0, copyBuffer!.Length)) > 0)
339 if (count > limits.MaximumEntryBytes - ms.Length ||
340 count > limits.MaximumTotalBytes - totalBytes || count > entry.Size - ms.Length)
341 throw new InvalidDataException($
"Archive entry '{entry.Name}' exceeds the uncompressed read limits.");
343 ms.Write(copyBuffer!, 0, count);
348 _zipEntries[key] = ms.ToArray();
353 catch (ZipException zex)
355 Engine.Logger.LogError(zex,
"Decryption failed — check password or file integrity.");
360 Engine.Logger.LogError(ex,
"Failed to load asset file.");
383 if (streamFactory ==
null)
384 throw new ArgumentNullException(nameof(streamFactory));
388 using var stream = streamFactory();
389 Add(type, name, stream);
403 if (
string.IsNullOrWhiteSpace(filePath))
404 throw new ArgumentException(
"File path cannot be null or empty.", nameof(filePath));
406 var nameToUse = name ?? Path.GetFileName(filePath);
407 using var stream = File.OpenRead(filePath);
408 Add(type, nameToUse, stream);
426 throw new ArgumentNullException(nameof(stream));
428 if (
string.IsNullOrWhiteSpace(name))
429 throw new ArgumentException(
"Asset name cannot be null or empty.", nameof(name));
432 throw new ArgumentException(
"Stream must be readable.", nameof(stream));
442 using var ms =
new MemoryStream();
444 _zipEntries[key] = ms.ToArray();
454 if (
string.IsNullOrWhiteSpace(name))
455 throw new ArgumentException(
"Asset name cannot be null or empty.", nameof(name));
465 _zipEntries.Remove(key);
489 if (
string.IsNullOrWhiteSpace(name))
500 if (_zipEntries.TryGetValue(exactKey, out var exactData))
501 return new MemoryStream(exactData, writable:
false);
503 var requestedBaseName = Path.GetFileNameWithoutExtension(name);
505 var match = _zipEntries.Keys.FirstOrDefault(k =>
506 k.AssetType == type &&
508 Path.GetFileNameWithoutExtension(k.AssetName),
510 StringComparison.OrdinalIgnoreCase));
512 return match !=
null && _zipEntries.TryGetValue(match, out var fallbackData)
513 ?
new MemoryStream(fallbackData, writable:
false)
524 return _zipEntries.Keys.ToList();
538 using (var fs = File.Create(
FilePath))
539 using (var zipStream =
new ZipOutputStream(fs) { IsStreamOwner =
true })
541 if (!
string.IsNullOrEmpty(
Password))
544 foreach (var (key, data) in _zipEntries)
546 var entry =
new ZipEntry(key.ToString())
548 DateTime = DateTime.Now
552 entry.AESKeySize = 256;
554 zipStream.PutNextEntry(entry);
556 using var inputStream =
new MemoryStream(data, writable:
false);
557 inputStream.CopyTo(zipStream);
558 zipStream.CloseEntry();
565 "Assets file saved (Encrypted: {Encrypted}).",
581 _allAssetsFiles.Remove(
this);
Represents an entry for an engine asset file, including its type and name.
Represents an asset file used by the engine, providing functionality to load, manage,...
static void ClearAll()
Releases all assets held by the application and clears the internal collection of asset files.
void Save()
Saves the current set of entries to a zip file at the specified file path.
string FilePath
Gets the file path associated with the current instance.
static void Validate(string path, string? password=null, bool testData=true)
Strictly validates an existing bundle's entry keys and archive integrity. Unlike runtime loading,...
static AssetsFile Load(Stream stream, string? password, bool register, string? sourcePath)
Loads a buffered archive with an optional reconstructible source path.
string? SourcePath
Gets the archive's reconstructible origin, including an optional stream origin.
void Add(AssetTypes type, string name, Stream stream)
Adds an asset file entry to the collection with the specified type, name, and source stream.
string? Password
Gets the password associated with the current instance.
static AssetsFile Load(Stream stream, string? password, bool register, string? sourcePath, AssetsFileReadLimits? limits)
Loads an archive with optional bounds checked before and during decompression.
void Dispose()
Releases all resources used by the AssetsFile instance.
static IReadOnlyList< AssetsFile > AllAssetsFiles
Gets a read-only list of registered AssetsFile instances.
static AssetsFile LoadOrCreate(string path, string? password=null, bool encrypt=false)
Loads an existing asset file from the specified path or creates a new one if the file does not exist.
void Add(AssetTypes type, string filePath, string? name=null)
Adds an asset file to the engine with the specified type and file path.
bool UseEncryption
Gets a value indicating whether encryption is enabled for the current operation.
static AssetsFile Load(Stream stream, string? password=null, bool register=true)
Loads an existing asset file from a readable stream.
static AssetsFile LoadOrCreate(string path, string? password, bool encrypt, bool register)
Loads or creates an asset file, optionally without adding it to the runtime collection....
void Remove(AssetTypes type, string name)
Removes the specified asset file entry from the collection.
Stream? Get(AssetTypes type, string name)
Retrieves a stream for the specified asset type and name.
IEnumerable< AssetsFileEntry > GetAllEntries()
Retrieves all entries from the asset file.
void Add(AssetTypes type, string name, Func< Stream > streamFactory)
Adds an asset file entry to the collection with the specified type, name, and stream factory.
Represents the core game engine singleton responsible for managing the main update loop,...
static ILogger< Engine > Logger
Gets the logger instance used by the engine for diagnostic and informational messages.
record AssetsFileReadLimits(long MaximumEntryBytes, long MaximumTotalBytes, int MaximumEntries=10_000)
Optional bounds for buffering untrusted archives. Normal runtime loads remain unrestricted.
AssetTypes
Defines the types of assets that can be stored and managed by the engine.