-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLithTechSpritePreviewLoader.cs
More file actions
347 lines (296 loc) · 11.1 KB
/
LithTechSpritePreviewLoader.cs
File metadata and controls
347 lines (296 loc) · 11.1 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
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
using System.IO;
using System.Runtime.CompilerServices;
using System.Windows.Media;
namespace CFRezManager;
internal sealed record LithTechSpritePreviewDocument(
IReadOnlyList<ImagePreviewFrame> Frames,
int FrameRate,
string Info);
internal static class LithTechSpritePreviewLoader
{
private const int MaxSpriteBytes = 8 * 1024 * 1024;
private const int MaxFrameBytes = 64 * 1024 * 1024;
private const int MaxPreviewFrames = 512;
private static readonly ConditionalWeakTable<RezArchive, Dictionary<string, RezFileNode>> ArchiveFileLookupCache = new();
public static bool TryLoadFromArchive(
RezArchive archive,
RezFileNode spriteFile,
string displayName,
out LithTechSpritePreviewDocument? preview,
out string? errorMessage)
{
preview = null;
errorMessage = null;
byte[]? spriteBytes = ReadArchiveFileBytes(archive, spriteFile, MaxSpriteBytes);
if (spriteBytes is null)
{
errorMessage = $"SPR file is too large or unreadable: {displayName}";
return false;
}
if (!LithTechSpriteDecoder.TryDecode(spriteBytes, displayName, out LithTechSpriteDocument? sprite, out errorMessage) ||
sprite is null)
{
return false;
}
Dictionary<string, RezFileNode> filesByPath = GetArchiveFileLookup(archive);
var frames = new List<ImagePreviewFrame>(Math.Min(sprite.FramePaths.Count, MaxPreviewFrames));
var missingPaths = new List<string>();
int skippedFrames = 0;
for (int i = 0; i < sprite.FramePaths.Count && frames.Count < MaxPreviewFrames; i++)
{
string framePath = sprite.FramePaths[i];
if (!TryFindFrame(filesByPath, framePath, out RezFileNode? frameFile) || frameFile is null)
{
missingPaths.Add(framePath);
continue;
}
byte[]? frameBytes = ReadArchiveFileBytes(archive, frameFile, MaxFrameBytes);
ImageSource? image = frameBytes is null ? null : DtxThumbnailDecoder.TryDecodeOriginal(frameBytes);
if (image is null)
{
skippedFrames++;
continue;
}
frames.Add(new ImagePreviewFrame($"Frame {i:0000}", image));
}
if (frames.Count == 0)
{
errorMessage = missingPaths.Count > 0
? $"Unable to find SPR DTX frames in this REZ. First missing frame: {missingPaths[0]}"
: $"Unable to decode SPR DTX frames: {displayName}";
return false;
}
string info = FormatInfo(sprite, frames.Count, missingPaths.Count, skippedFrames);
preview = new LithTechSpritePreviewDocument(frames, sprite.FrameRate, info);
return true;
}
public static bool TryLoadFromLocalFile(
string spriteFilePath,
string displayName,
out LithTechSpritePreviewDocument? preview,
out string? errorMessage)
{
preview = null;
errorMessage = null;
byte[]? spriteBytes = ReadLocalFileBytes(spriteFilePath, MaxSpriteBytes);
if (spriteBytes is null)
{
errorMessage = $"SPR file is too large or unreadable: {displayName}";
return false;
}
if (!LithTechSpriteDecoder.TryDecode(spriteBytes, displayName, out LithTechSpriteDocument? sprite, out errorMessage) ||
sprite is null)
{
return false;
}
var frames = new List<ImagePreviewFrame>(Math.Min(sprite.FramePaths.Count, MaxPreviewFrames));
var missingPaths = new List<string>();
int skippedFrames = 0;
for (int i = 0; i < sprite.FramePaths.Count && frames.Count < MaxPreviewFrames; i++)
{
string framePath = sprite.FramePaths[i];
if (!TryFindLocalFrame(spriteFilePath, framePath, out string? localFramePath) ||
localFramePath is null)
{
missingPaths.Add(framePath);
continue;
}
ImageSource? image = TryReadLocalDtxFrame(localFramePath, decodeOriginal: true);
if (image is null)
{
skippedFrames++;
continue;
}
frames.Add(new ImagePreviewFrame($"Frame {i:0000}", image));
}
if (frames.Count == 0)
{
errorMessage = missingPaths.Count > 0
? $"Unable to find SPR DTX frames next to this file. First missing frame: {missingPaths[0]}"
: $"Unable to decode SPR DTX frames: {displayName}";
return false;
}
string info = FormatInfo(sprite, frames.Count, missingPaths.Count, skippedFrames);
preview = new LithTechSpritePreviewDocument(frames, sprite.FrameRate, info);
return true;
}
public static ImageSource? TryLoadThumbnailFromArchive(RezArchive archive, LithTechSpriteDocument sprite)
{
Dictionary<string, RezFileNode> filesByPath = GetArchiveFileLookup(archive);
foreach (string framePath in sprite.FramePaths)
{
if (!TryFindFrame(filesByPath, framePath, out RezFileNode? frameFile) || frameFile is null)
{
continue;
}
byte[]? frameBytes = ReadArchiveFileBytes(archive, frameFile, MaxFrameBytes);
ImageSource? image = frameBytes is null ? null : DtxThumbnailDecoder.TryDecode(frameBytes);
if (image is not null)
{
return image;
}
}
return null;
}
public static ImageSource? TryLoadThumbnailFromLocalFile(string spriteFilePath, LithTechSpriteDocument sprite)
{
foreach (string framePath in sprite.FramePaths)
{
if (!TryFindLocalFrame(spriteFilePath, framePath, out string? localFramePath) ||
localFramePath is null)
{
continue;
}
ImageSource? image = TryReadLocalDtxFrame(localFramePath, decodeOriginal: false);
if (image is not null)
{
return image;
}
}
return null;
}
private static string FormatInfo(
LithTechSpriteDocument sprite,
int loadedFrames,
int missingFrames,
int skippedFrames)
{
string info = $"{sprite.StorageDescription}, {sprite.FrameCount:N0} frames @ {sprite.FrameRate:N0} fps";
if (loadedFrames != sprite.FrameCount)
{
info += $", loaded {loadedFrames:N0}";
}
if (missingFrames > 0)
{
info += $", missing {missingFrames:N0}";
}
if (skippedFrames > 0)
{
info += $", skipped {skippedFrames:N0}";
}
if (sprite.FrameCount > MaxPreviewFrames)
{
info += $", capped at {MaxPreviewFrames:N0}";
}
return info;
}
private static Dictionary<string, RezFileNode> BuildFileLookup(RezDirectoryNode root)
{
var filesByPath = new Dictionary<string, RezFileNode>(StringComparer.OrdinalIgnoreCase);
AddFiles(root, filesByPath);
return filesByPath;
}
private static Dictionary<string, RezFileNode> GetArchiveFileLookup(RezArchive archive)
{
return ArchiveFileLookupCache.GetValue(archive, static archiveValue => BuildFileLookup(archiveValue.Root));
}
private static void AddFiles(RezDirectoryNode directory, Dictionary<string, RezFileNode> filesByPath)
{
foreach (RezNode child in directory.Children)
{
if (child is RezFileNode file)
{
filesByPath.TryAdd(NormalizeRezPath(file.FullPath), file);
}
else if (child is RezDirectoryNode childDirectory)
{
AddFiles(childDirectory, filesByPath);
}
}
}
private static bool TryFindFrame(
Dictionary<string, RezFileNode> filesByPath,
string framePath,
out RezFileNode? frameFile)
{
string normalized = NormalizeRezPath(framePath);
if (filesByPath.TryGetValue(normalized, out frameFile))
{
return true;
}
string fileName = Path.GetFileName(normalized);
RezFileNode? match = null;
foreach ((string path, RezFileNode candidate) in filesByPath)
{
if (!path.EndsWith(fileName, StringComparison.OrdinalIgnoreCase))
{
continue;
}
if (match is not null)
{
frameFile = null;
return false;
}
match = candidate;
}
frameFile = match;
return frameFile is not null;
}
private static string NormalizeRezPath(string path)
{
return path.Replace('\\', '/').TrimStart('/');
}
private static bool TryFindLocalFrame(string spriteFilePath, string spriteFramePath, out string? framePath)
{
framePath = null;
string? startDirectory = Path.GetDirectoryName(spriteFilePath);
if (string.IsNullOrWhiteSpace(startDirectory))
{
return false;
}
string relativePath = spriteFramePath
.Replace('/', Path.DirectorySeparatorChar)
.Replace('\\', Path.DirectorySeparatorChar)
.TrimStart(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar);
for (string? directory = startDirectory; !string.IsNullOrWhiteSpace(directory); directory = Directory.GetParent(directory)?.FullName)
{
string candidate = Path.Combine(directory, relativePath);
if (File.Exists(candidate))
{
framePath = candidate;
return true;
}
}
return false;
}
private static byte[]? ReadArchiveFileBytes(RezArchive archive, RezFileNode file, int maxBytes)
{
if (file.Size < 0 || file.Size > maxBytes)
{
return null;
}
byte[] data = new byte[file.Size];
using FileStream source = File.OpenRead(archive.FilePath);
source.Position = file.DataOffset;
source.ReadExactly(data);
return data;
}
private static byte[]? ReadLocalFileBytes(string filePath, int maxBytes)
{
var info = new FileInfo(filePath);
if (!info.Exists || info.Length < 0 || info.Length > maxBytes || info.Length > int.MaxValue)
{
return null;
}
return File.ReadAllBytes(filePath);
}
private static ImageSource? TryReadLocalDtxFrame(string framePath, bool decodeOriginal)
{
try
{
var info = new FileInfo(framePath);
if (!info.Exists || info.Length < 0 || info.Length > MaxFrameBytes || info.Length > int.MaxValue)
{
return null;
}
byte[] data = File.ReadAllBytes(framePath);
return decodeOriginal
? DtxThumbnailDecoder.TryDecodeOriginal(data)
: DtxThumbnailDecoder.TryDecode(data);
}
catch
{
return null;
}
}
}