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

98 lines
2.5 KiB
C#
Raw Normal View History

2024-08-11 14:23:56 +00:00
using System.Collections.Generic;
using System.Linq;
using Godot;
using KeepersCompound.LGS;
2024-08-11 14:23:56 +00:00
namespace KeepersCompound.TMV;
2024-08-12 17:46:30 +00:00
public partial class TextureLoader
2024-08-11 14:23:56 +00:00
{
private readonly string _fmName;
2024-09-07 12:42:16 +00:00
private readonly List<Texture2D> _textureCache = new();
2024-08-11 14:23:56 +00:00
private readonly Dictionary<int, int> _idMap = new();
private readonly Dictionary<int, string> _idPathMap = new();
2024-08-11 14:23:56 +00:00
private readonly Dictionary<string, int> _pathMap = new();
2024-09-05 16:39:54 +00:00
public TextureLoader(string fmName)
2024-08-11 14:23:56 +00:00
{
_fmName = fmName;
2024-08-11 14:23:56 +00:00
LoadDefaultTexture();
}
private void LoadDefaultTexture()
{
2024-09-07 12:43:11 +00:00
const string path = "res://project/jorge.png";
var texture = ResourceLoader.Load<CompressedTexture2D>(path);
2024-08-11 14:23:56 +00:00
_textureCache.Add(texture);
}
public bool Register(int id, string path)
{
return _idPathMap.TryAdd(id, path);
}
private bool Load(int id, string path)
2024-08-11 14:23:56 +00:00
{
var loaded = false;
var pathManager = Context.Instance.PathManager;
var (_, texPath) = pathManager.GetResourcePath(ResourceType.Texture, _fmName, path);
if (texPath != null)
2024-08-11 14:23:56 +00:00
{
var texture = LoadTexture(texPath);
if (texture != null)
{
_textureCache.Add(texture);
loaded = true;
}
2024-08-11 14:23:56 +00:00
}
var index = loaded ? _textureCache.Count - 1 : 0;
_idMap.TryAdd(id, index);
_pathMap.TryAdd(path, index);
return loaded;
}
public static ImageTexture LoadTexture(string path)
2024-08-12 17:46:30 +00:00
{
var ext = path.GetExtension().ToLower();
string[] validExtensions = { "png", "tga", "pcx", "gif" };
if (validExtensions.Contains(ext))
2024-08-12 17:46:30 +00:00
{
var texture = ext switch
{
"pcx" => LoadPcx(path),
"gif" => LoadGif(path),
_ => ImageTexture.CreateFromImage(Image.LoadFromFile(path)),
};
return texture;
}
return null;
2024-08-12 17:46:30 +00:00
}
// TODO: We should report load failures
2024-09-07 12:42:16 +00:00
public Texture2D Get(int id)
2024-08-11 14:23:56 +00:00
{
if (_idMap.TryGetValue(id, out int value))
2024-08-11 14:23:56 +00:00
{
return _textureCache[value];
2024-08-11 14:23:56 +00:00
}
if (_idPathMap.TryGetValue(id, out var path) && Load(id, path))
{
return _textureCache[_idMap[id]];
}
return _textureCache[0];
2024-08-11 14:23:56 +00:00
}
// TODO: Load by path :)
2024-09-07 12:42:16 +00:00
public Texture2D Get(string path)
2024-08-11 14:23:56 +00:00
{
if (!_pathMap.ContainsKey(path))
{
return _textureCache[0];
}
return _textureCache[_pathMap[path]];
}
}