thief-mission-viewer/project/code/TMV/TextureLoader.cs

100 lines
2.6 KiB
C#

using System.Collections.Generic;
using System.IO;
using System.Linq;
using Godot;
using KeepersCompound.LGS;
namespace KeepersCompound.TMV;
public partial class TextureLoader
{
private readonly string _fmName;
private readonly List<ImageTexture> _textureCache = new();
private readonly Dictionary<int, int> _idMap = new();
private readonly Dictionary<int, string> _idPathMap = new();
private readonly Dictionary<string, int> _pathMap = new();
public TextureLoader(string fmName)
{
_fmName = fmName;
LoadDefaultTexture();
}
private void LoadDefaultTexture()
{
// TODO: This should be a resource loaded from RES
const string path = "user://textures/jorge.png";
var texture = ImageTexture.CreateFromImage(Image.LoadFromFile(path));
_textureCache.Add(texture);
}
public bool Register(int id, string path)
{
return _idPathMap.TryAdd(id, path);
}
private bool Load(int id, string path)
{
var loaded = false;
var pathManager = Context.Instance.PathManager;
var (_, texPath) = pathManager.GetResourcePath(ResourceType.Texture, _fmName, path);
if (texPath != null)
{
var texture = LoadTexture(texPath);
if (texture != null)
{
_textureCache.Add(texture);
loaded = true;
}
}
var index = loaded ? _textureCache.Count - 1 : 0;
_idMap.TryAdd(id, index);
_pathMap.TryAdd(path, index);
return loaded;
}
public static ImageTexture LoadTexture(string path)
{
var ext = path.GetExtension().ToLower();
string[] validExtensions = { "png", "tga", "pcx", "gif" };
if (validExtensions.Contains(ext))
{
var texture = ext switch
{
"pcx" => LoadPcx(path),
"gif" => LoadGif(path),
_ => ImageTexture.CreateFromImage(Image.LoadFromFile(path)),
};
return texture;
}
return null;
}
// TODO: We should report load failures
public ImageTexture Get(int id)
{
if (_idMap.TryGetValue(id, out int value))
{
return _textureCache[value];
}
if (_idPathMap.TryGetValue(id, out var path) && Load(id, path))
{
return _textureCache[_idMap[id]];
}
return _textureCache[0];
}
// TODO: Load by path :)
public ImageTexture Get(string path)
{
if (!_pathMap.ContainsKey(path))
{
return _textureCache[0];
}
return _textureCache[_pathMap[path]];
}
}