-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLithTechModelTextureLoader.cs
More file actions
299 lines (264 loc) · 9.32 KB
/
LithTechModelTextureLoader.cs
File metadata and controls
299 lines (264 loc) · 9.32 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
using System.IO;
using System.Runtime.CompilerServices;
using System.Windows.Media;
using System.Windows.Media.Imaging;
namespace CFRezManager;
internal static class LithTechModelTextureLoader
{
private const int MaxTextureBytes = 64 * 1024 * 1024;
private static readonly string[] TextureExtensions = [".dtx", ".dds", ".tga", ".png", ".jpg", ".jpeg", ".bmp"];
private static readonly ConditionalWeakTable<RezArchive, Dictionary<string, RezFileNode>> ArchiveFileLookupCache = new();
public static Func<string, ImageSource?>? CreateResolver(ExplorerItem item)
{
return item.Kind switch
{
ExplorerItemKind.RezFile when item.Archive is not null => CreateArchiveResolver(item.Archive),
ExplorerItemKind.LocalFile when !string.IsNullOrWhiteSpace(item.SourcePath) => CreateLocalResolver(item.SourcePath),
_ => null
};
}
public static Func<string, ImageSource?>? CreateLocalResolver(string modelFilePath)
{
string? modelDirectory = Path.GetDirectoryName(modelFilePath);
if (string.IsNullOrWhiteSpace(modelDirectory))
{
return null;
}
var cache = new Dictionary<string, ImageSource?>(StringComparer.OrdinalIgnoreCase);
return texturePath =>
{
string normalized = NormalizeTexturePath(texturePath);
if (cache.TryGetValue(normalized, out ImageSource? cached))
{
return cached;
}
ImageSource? image = TryResolveLocalTexture(modelDirectory, normalized);
cache[normalized] = image;
return image;
};
}
private static Func<string, ImageSource?> CreateArchiveResolver(RezArchive archive)
{
Dictionary<string, RezFileNode> filesByPath = GetArchiveFileLookup(archive);
var cache = new Dictionary<string, ImageSource?>(StringComparer.OrdinalIgnoreCase);
return texturePath =>
{
string normalized = NormalizeTexturePath(texturePath);
if (cache.TryGetValue(normalized, out ImageSource? cached))
{
return cached;
}
ImageSource? image = TryResolveArchiveTexture(archive, filesByPath, normalized);
cache[normalized] = image;
return image;
};
}
private static ImageSource? TryResolveArchiveTexture(
RezArchive archive,
Dictionary<string, RezFileNode> filesByPath,
string texturePath)
{
foreach (string candidate in GetTexturePathCandidates(texturePath))
{
if (filesByPath.TryGetValue(candidate, out RezFileNode? file))
{
return TryReadArchiveTexture(archive, file);
}
}
foreach (string candidateName in GetTextureFileNameCandidates(texturePath))
{
RezFileNode? match = null;
foreach ((string path, RezFileNode file) in filesByPath)
{
if (!PathMatchesFileName(path, candidateName))
{
continue;
}
if (match is not null)
{
match = null;
break;
}
match = file;
}
if (match is not null)
{
return TryReadArchiveTexture(archive, match);
}
}
return null;
}
private static bool PathMatchesFileName(string path, string fileName)
{
return string.Equals(path, fileName, StringComparison.OrdinalIgnoreCase) ||
path.EndsWith("/" + fileName, StringComparison.OrdinalIgnoreCase);
}
private static ImageSource? TryResolveLocalTexture(string modelDirectory, string texturePath)
{
foreach (string candidate in GetLocalTexturePathCandidates(modelDirectory, texturePath))
{
if (File.Exists(candidate))
{
return TryReadLocalTexture(candidate);
}
}
return null;
}
private static IEnumerable<string> GetLocalTexturePathCandidates(string modelDirectory, string texturePath)
{
foreach (string candidate in GetTexturePathCandidates(texturePath))
{
string platformPath = candidate.Replace('/', Path.DirectorySeparatorChar);
if (Path.IsPathFullyQualified(platformPath))
{
yield return platformPath;
continue;
}
for (string? directory = modelDirectory; !string.IsNullOrWhiteSpace(directory); directory = Directory.GetParent(directory)?.FullName)
{
yield return Path.Combine(directory, platformPath);
}
}
}
private static IEnumerable<string> GetTexturePathCandidates(string texturePath)
{
string normalized = NormalizeTexturePath(texturePath);
if (string.IsNullOrWhiteSpace(normalized))
{
yield break;
}
yield return normalized;
string extension = Path.GetExtension(normalized);
if (string.IsNullOrWhiteSpace(extension))
{
foreach (string textureExtension in TextureExtensions)
{
yield return normalized + textureExtension;
}
}
else
{
string withoutExtension = normalized[..^extension.Length];
foreach (string textureExtension in TextureExtensions)
{
if (!string.Equals(extension, textureExtension, StringComparison.OrdinalIgnoreCase))
{
yield return withoutExtension + textureExtension;
}
}
}
}
private static IEnumerable<string> GetTextureFileNameCandidates(string texturePath)
{
foreach (string candidate in GetTexturePathCandidates(texturePath))
{
string fileName = Path.GetFileName(candidate);
if (!string.IsNullOrWhiteSpace(fileName))
{
yield return fileName;
}
}
}
private static ImageSource? TryReadArchiveTexture(RezArchive archive, RezFileNode file)
{
if (file.Size < 0 || file.Size > MaxTextureBytes)
{
return null;
}
try
{
byte[] data = new byte[file.Size];
using FileStream source = File.OpenRead(archive.FilePath);
source.Position = file.DataOffset;
source.ReadExactly(data);
return TryDecodeTexture(file.Extension, data);
}
catch
{
return null;
}
}
private static ImageSource? TryReadLocalTexture(string filePath)
{
try
{
var info = new FileInfo(filePath);
if (!info.Exists || info.Length < 0 || info.Length > MaxTextureBytes || info.Length > int.MaxValue)
{
return null;
}
byte[] data = File.ReadAllBytes(filePath);
return TryDecodeTexture(info.Extension.TrimStart('.'), data);
}
catch
{
return null;
}
}
private static ImageSource? TryDecodeTexture(string extension, byte[] data)
{
if (string.Equals(extension, "dtx", StringComparison.OrdinalIgnoreCase))
{
return DtxThumbnailDecoder.TryDecodeOriginal(data);
}
if (string.Equals(extension, "dds", StringComparison.OrdinalIgnoreCase))
{
return DdsThumbnailDecoder.TryDecodeOriginal(data);
}
if (string.Equals(extension, "tga", StringComparison.OrdinalIgnoreCase))
{
return TgaThumbnailDecoder.TryDecodeOriginal(data);
}
return TryLoadBitmapImage(data);
}
private static ImageSource? TryLoadBitmapImage(byte[] data)
{
try
{
using var stream = new MemoryStream(data);
var image = new BitmapImage();
image.BeginInit();
image.CacheOption = BitmapCacheOption.OnLoad;
image.CreateOptions = BitmapCreateOptions.IgnoreColorProfile;
image.StreamSource = stream;
image.EndInit();
image.Freeze();
return image;
}
catch
{
return null;
}
}
private static Dictionary<string, RezFileNode> GetArchiveFileLookup(RezArchive archive)
{
return ArchiveFileLookupCache.GetValue(archive, static archiveValue =>
{
var filesByPath = new Dictionary<string, RezFileNode>(StringComparer.OrdinalIgnoreCase);
AddArchiveFiles(archiveValue.Root, filesByPath);
return filesByPath;
});
}
private static void AddArchiveFiles(RezDirectoryNode directory, Dictionary<string, RezFileNode> filesByPath)
{
foreach (RezNode child in directory.Children)
{
if (child is RezFileNode file)
{
filesByPath.TryAdd(NormalizeTexturePath(file.FullPath), file);
}
else if (child is RezDirectoryNode childDirectory)
{
AddArchiveFiles(childDirectory, filesByPath);
}
}
}
private static string NormalizeTexturePath(string path)
{
return path
.Trim()
.Trim('"', '\'')
.Replace('\\', '/')
.TrimStart('/');
}
}