-
Notifications
You must be signed in to change notification settings - Fork 10
/
Program.cs
1584 lines (1432 loc) · 62.1 KB
/
Program.cs
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
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Drawing;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using DiscUtils;
using DiscUtils.Iso9660;
using PSXPrev.Common;
using PSXPrev.Common.Animator;
using PSXPrev.Common.Parsers;
using PSXPrev.Common.Utils;
using PSXPrev.Forms;
namespace PSXPrev
{
public class Program
{
public static string Name = "PSXPrev";
public static string RootNamespace = "PSXPrev";
public static readonly Logger Logger = new Logger();
// For use with non-scanners
public static readonly Logger ConsoleLogger = new Logger();
private static PreviewForm PreviewForm;
private static readonly List<RootEntity> _allEntities = new List<RootEntity>();
private static readonly List<Texture> _allTextures = new List<Texture>();
private static readonly List<Animation> _allAnimations = new List<Animation>();
private static int _scannedEntityCount;
private static int _scannedTextureCount;
private static int _scannedAnimationCount;
// Lock for _currentFileLength and _largestCurrentFilePosition, because longs can't be volatile.
private static readonly object _fileProgressLock = new object();
private static readonly Dictionary<FileOffsetScanner, long> _currentParserPositions = new Dictionary<FileOffsetScanner, long>();
private static long _currentFilePosition; // Farthest position of all the active parsers
private static long _currentFileLength;
private static int _currentFileIndex;
private static int _totalFiles;
private static int _lastUpdateFileIndex;
private static ScanOptions _options = new ScanOptions();
private static ScanOptions _commandLineOptions;
private static Action<ScanProgressReport> _progressCallback;
private static volatile bool _scanning; // Is a scan currently running?
private static volatile bool _pauseRequested; // Is the scan currently paused? Reset when _scanning is false.
private static volatile bool _cancelRequested; // Is the scan being canceled? Reset when _scanning is false.
public static bool IsScanning => _scanning;
public static bool IsScanPaused => _pauseRequested;
public static bool IsScanCanceling => _cancelRequested;
public static ScanOptions CommandLineOptions => _commandLineOptions;
public static bool HasCommandLineArguments => _commandLineOptions != null;
public static bool HasEntityResults
{
get { lock (_allEntities) return _allEntities.Count > 0; }
}
public static bool HasTextureResults
{
get { lock (_allTextures) return _allTextures.Count > 0; }
}
public static bool HasAnimationResults
{
get { lock (_allAnimations) return _allAnimations.Count > 0; }
}
public static bool Debug => _options.DebugLogging;
public static bool ShowErrors => _options.ErrorLogging;
// The ";1" is appended to file names in raw PS1 CDs. Extractors may include them.
private const string BINPostfix = ";1";
// Ignore movies, audio, and (unsure).
private static readonly string[] IgnoreFileExtensions =
{
".str", ".str"+BINPostfix, ".xa", ".xa"+BINPostfix, ".vb", ".vb"+BINPostfix,
};
private static readonly string[] ISOFileExtensions = { ".iso" };
private static readonly string[] BINFileExtensions = { ".bin" };
// This attribute is necessary since PreviewForm now runs on the main thread.
[STAThread]
private static void Main(string[] args)
{
Initialize(args);
}
public static void PrintUsage()
{
Console.ResetColor();
Console.WriteLine($"usage: PSXPrev <PATH> [FILTER=\"{ScanOptions.DefaultFilter}\"] [-help] [...options]");
}
public static void PrintHelp()
{
PrintUsage();
Console.ResetColor();
Console.WriteLine();
//Console.WriteLine("positional arguments:");
Console.WriteLine("arguments:");
Console.WriteLine(" PATH : folder or file path to scan");
Console.WriteLine(" FILTER : wildcard filter for files to include (default: \"" + ScanOptions.DefaultFilter + "\")");
Console.WriteLine();
Console.WriteLine("scanner formats: (default: all formats except SPT)");
Console.WriteLine(" -an : scan for AN animations");
Console.WriteLine(" -bff : scan for BFF models and animations (Blitz Games)");
Console.WriteLine(" -hmd : scan for HMD models, textures, and animations");
Console.WriteLine(" -mod/-croc : scan for MOD models (Croc)");
Console.WriteLine(" -pil : scan for PIL models and animations (Blitz Games)");
//Console.WriteLine(" -pil/-psi : scan for PIL models and animations (Blitz Games)");
Console.WriteLine(" -pmd : scan for PMD models");
Console.WriteLine(" -psx : scan for PSX models, textures, and animations (Neversoft)");
Console.WriteLine(" -spt : scan for SPT textures (Blitz Games)");
Console.WriteLine(" -tim : scan for TIM textures");
Console.WriteLine(" -tmd : scan for TMD models");
Console.WriteLine(" -tod : scan for TOD animations");
Console.WriteLine(" -vdf : scan for VDF animations");
Console.WriteLine();
Console.WriteLine("scanner options:");
Console.WriteLine(" -ignorehmdversion : less strict scanning of HMD models");
Console.WriteLine(" -ignorepmdversion : less strict scanning of PMD models");
Console.WriteLine(" -ignoretimversion : less strict scanning of TIM textures");
Console.WriteLine(" -ignoretmdversion : less strict scanning of TMD models");
Console.WriteLine(" -align <ALIGN> : scan offsets at specified increments");
Console.WriteLine(" -start <OFFSET> : scan files starting at offset (hex)");
Console.WriteLine(" -stop <OFFSET> : scan files up to offset (hex, exclusive)");
Console.WriteLine(" -range [START],[STOP] : shorthand for [-start <START>] [-stop <STOP>]");
Console.WriteLine(" -startonly : shorthand for -stop <START+1>");
Console.WriteLine(" -nextoffset : continue scan at end of previous match");
Console.WriteLine(" -regex : treat FILTER as Regular Expression");
Console.WriteLine(" -depthlast : scan files at lower folder depths first");
Console.WriteLine(" -syncscan : disable multi-threaded scanning per format");
Console.WriteLine(" -scaniso : scan individual files inside .iso files");
Console.WriteLine(" -scanbin : scan individual files inside raw PS1 .bin files");
Console.WriteLine(" not all files may be listed in a .bin file, use -databin as a fallback");
Console.WriteLine(" -databin : scan data contents of raw PS1 .bin files");
Console.WriteLine(" -binsector <START>,<SIZE> : change sector reading of .bin files (default: 24,2048)");
Console.WriteLine(" combined values must not exceed " + BinCDStream.SectorRawSize);
Console.WriteLine();
Console.WriteLine("log options:");
Console.WriteLine(" -log : write output to log file");
Console.WriteLine(" -debug : output file format details and other information");
Console.WriteLine(" -error : show error (exception) messages when reading files");
Console.WriteLine(" -noverbose/-quiet : don't write output to console");
Console.WriteLine();
Console.WriteLine("program options:");
//Console.WriteLine(" -help : show this help message"); // It's redundant to display this
Console.WriteLine(" -drawvram : draw all loaded textures to VRAM (not advised when scanning many files)");
Console.WriteLine();
Console.WriteLine();
Console.WriteLine("notes:");
Console.WriteLine("Star Ocean 2 seems to use -binsector 40,2032. However most observed games use the defaut.");
}
private static void PressAnyKeyToContinue()
{
Console.ResetColor();
Console.WriteLine();
Console.WriteLine("Press any key to continue...");
Console.ReadKey();
}
private static bool TryParseHelp(string arg)
{
switch (arg)
{
// Add all -help aliases here
case "-help":
return true;
default:
return false;
}
}
// consumedParameters is number of extra arguments consumed after index.
private static bool TryParseOption(string[] args, int index, ScanOptions options, ref bool help, out int parameterCount, out bool invalidParameter)
{
parameterCount = 0;
invalidParameter = false;
var arg = args[index];
if (options == null)
{
// Use dummy options. We're just checking for a valid argument.
options = new ScanOptions();
}
if (TryParseHelp(arg))
{
help = true;
return true;
}
switch (arg)
{
// Scanner formats:
case "-an":
options.AddFormat(ANParser.FormatNameConst);
break;
case "-bff":
options.AddFormat(BFFParser.FormatNameConst);
break;
case "-hmd":
options.AddFormat(HMDParser.FormatNameConst);
break;
case "-croc": // Alias for -mod
case "-mod": // Previously called -croc
options.AddFormat(MODParser.FormatNameConst);
break;
case "-pil":
//case "-psi": // Alias for -pil
options.AddFormat(PILParser.FormatNameConst);
break;
case "-pmd":
options.AddFormat(PMDParser.FormatNameConst);
break;
case "-psx":
options.AddFormat(PSXParser.FormatNameConst);
break;
case "-spt":
options.AddFormat(SPTParser.FormatNameConst);
break;
case "-tim":
options.AddFormat(TIMParser.FormatNameConst);
break;
case "-tmd":
options.AddFormat(TMDParser.FormatNameConst);
break;
case "-tod":
options.AddFormat(TODParser.FormatNameConst);
break;
case "-vdf":
options.AddFormat(VDFParser.FormatNameConst);
break;
// Scanner options:
case "-ignorehmdversion":
options.AddUnstrict(HMDParser.FormatNameConst);
break;
case "-ignorepmdversion":
options.AddUnstrict(PMDParser.FormatNameConst);
break;
case "-ignoretimversion":
options.AddUnstrict(TIMParser.FormatNameConst);
break;
case "-ignoretmdversion":
options.AddUnstrict(TMDParser.FormatNameConst);
break;
case "-align":
parameterCount++;
if (index + 1 < args.Length)
{
invalidParameter = !TryParseValue(args[index + 1], false, out var align);
if (!invalidParameter)
{
options.Alignment = align;
break;
}
}
return false;
case "-start": // -start <OFFSET>
parameterCount++;
if (index + 1 < args.Length)
{
invalidParameter = !TryParseValue(args[index + 1], true, out var startOffset);
if (!invalidParameter)
{
options.StartOffsetHasValue = true;
options.StartOffsetValue = startOffset;
break;
}
}
return false;
case "-stop": // -stop <OFFSET>
parameterCount++;
if (index + 1 < args.Length)
{
invalidParameter = !TryParseValue(args[index + 1], true, out var stopOffset);
if (!invalidParameter)
{
options.StopOffsetHasValue = true;
options.StopOffsetValue = stopOffset;
break;
}
}
return false;
case "-range": // -range [START],[STOP] Shorthand for -start <START> -stop <STOP>
parameterCount++;
if (index + 1 < args.Length)
{
invalidParameter = !TryParseRange(args[index + 1], true, false, out var startRange, out var stopRange);
if (!invalidParameter)
{
options.StartOffsetHasValue = startRange.HasValue;
options.StopOffsetHasValue = stopRange.HasValue;
options.StartOffsetValue = startRange ?? options.StartOffsetValue;
options.StopOffsetValue = stopRange ?? options.StopOffsetValue;
break;
}
}
return false;
case "-startonly": // Shorthand for -stop <START+1>
options.StartOffsetOnly = true;
break;
case "-nextoffset":
options.NextOffset = true;
break;
case "-regex":
options.UseRegex = true;
break;
case "-depthlast":
options.TopDownFileSearch = false;
break;
case "-syncscan":
options.AsyncFileScan = false;
break;
case "-scaniso":
options.ReadISOContents = true;
break;
case "-scanbin":
options.ReadBINContents = true;
break;
case "-databin":
options.ReadBINSectorData = true;
break;
case "-binsector":
parameterCount++;
if (index + 1 < args.Length)
{
invalidParameter = !TryParseBINSector(args[index + 1], false, out var sectorStart, out var sectorSize);
if (!invalidParameter)
{
options.BINSectorUserStartSizeHasValue = true;
options.BINSectorUserStartValue = sectorStart;
options.BINSectorUserSizeValue = sectorSize;
break;
}
}
return false;
// Log options:
case "-log":
options.LogToFile = true;
break;
case "-noverbose":
case "-quiet":
options.LogToConsole = false;
break;
case "-debug":
options.DebugLogging = true;
break;
case "-error":
options.ErrorLogging = true;
break;
// Program options:
case "-drawvram":
options.DrawAllToVRAM = true;
break;
default:
return false;
}
return true;
}
private static bool TryParseValue(string text, bool hex, out long offset)
{
var style = hex ? NumberStyles.AllowHexSpecifier : NumberStyles.None;
if (text.StartsWith("0x", StringComparison.InvariantCultureIgnoreCase))
{
text = text.Substring(2); // Strip prefix
// This style has a terrible name. "0x" prefix is illegal and the number is always parsed as hex.
style = NumberStyles.AllowHexSpecifier; // Hexadecimal integer
}
else if (text.StartsWith(".", StringComparison.InvariantCulture))
{
// Use the decimal prefix observed in OllyDbg, I'm at a loss for what else could be used...
text = text.Substring(1); // Strip prefix
style = NumberStyles.None; // Decimal integer
}
return long.TryParse(text, style, CultureInfo.InvariantCulture, out offset);
}
private static bool TryParseRange(string text, bool hex, bool require, out long? start, out long? stop)
{
//-range BE740 : BE740-BE741
//-range BE740, : BE740-end
//-range ,F580A : 0-F580A
//-range BE740,F580A : BE740-F580A
start = stop = null;
var param = text.Split(new[] { ',' }, StringSplitOptions.None);
if (param.Length == 1)
{
// Parse a single offset as both the start and stop.
if (!TryParseValue(param[0], hex, out var offset))
{
return false;
}
start = offset;
stop = offset + 1;
return true;
}
else if (param.Length == 2)
{
// Parse a start and/or stop offset.
// Empty strings are treated as null.
if (require || !string.IsNullOrEmpty(param[0]))
{
if (!TryParseValue(param[0], hex, out var startOffset))
{
return false;
}
start = startOffset;
}
if (require || !string.IsNullOrEmpty(param[1]))
{
if (!TryParseValue(param[1], hex, out var stopOffset))
{
return false;
}
stop = stopOffset;
}
return true;
}
return false;
}
private static bool TryParseBINSector(string text, bool hex, out int start, out int size)
{
//-binsector 24,2048 (default)
//-binsector 40,2032 (Star Ocean 2)
start = size = 0;
var param = text.Split(new[] { ',' }, StringSplitOptions.None);
if (param.Length == 2)
{
// Parse a start and/or stop offset.
// Empty strings are treated as null.
if (!TryParseValue(param[0], hex, out var sectorStart))
{
return false;
}
start = (int)sectorStart;
if (!TryParseValue(param[1], hex, out var sectorSize))
{
return false;
}
size = (int)sectorSize;
// Validate sector info so that we don't cause problems parsing the file
if (sectorStart < 0 || sectorSize <= 0 || sectorStart + sectorSize > BinCDStream.SectorRawSize)
{
return false;
}
return true;
}
return false;
}
// Returns true if the program should quit after this.
private static bool ParseCommandLineOptions(string[] args)
{
if (args == null)
{
return false; // This was not called from main. Don't do anything or print usage again.
}
else if (args.Length == 0)
{
// No arguments specified. Print usage so that the user can either
// ask for help, or specify what they want without the GUI in the future.
PrintUsage();
return false; // No command line arguments
}
// Change settings whose defaults differ between the command line and ScannerForm.
var options = new ScanOptions
{
ReadISOContents = false,
};
var help = false; // Skip scanning and print the help message.
// Check if the user is asking for -help in-place of positional arguments.
for (var a = 0; a < Math.Min(2, args.Length); a++)
{
if (TryParseHelp(args[a]))
{
help = true;
break;
}
}
string filter = null;
// Still parse when -help to check for -debug
//if (!help)
{
// Parse positional arguments PATH and FILTER.
options.Path = args[0];
if (args.Length > 1)
{
filter = args[1];
}
// If we want, we can make FILTER truly optional by checking TryParseOption, and skipping FILTER if one was found.
// However, this would prevent the user from specifying a filter that matches a command line option.
// This is a pretty unlikely scenario, but it's worth considering.
//if (args.Length > 1 && !TryParseOption(args, 1, options, ref help, out _, out _))
//{
// filter = args[1];
//}
// Parse all remaining options that aren't PATH or FILTER.
var startIndex = help ? 0 : 2;
for (var a = startIndex; a < args.Length; a++)
{
if (!TryParseOption(args, a, options, ref help, out var parameterCount, out var invalidParameter))
{
if (a + 1 + parameterCount > args.Length)
{
var missing = (a + 1 + parameterCount) - args.Length;
Program.ConsoleLogger.WriteErrorLine($"Missing {missing} parameters for argument: {args[a]}");
}
else if (invalidParameter)
{
var paramList = new List<string>();
for (var p = 0; p < parameterCount; p++)
{
paramList.Add(args[a + 1 + p]);
}
var paramStr = string.Join(" ", paramList);
Program.ConsoleLogger.WriteErrorLine($"Invalid parameters for argument: {args[a]} {paramStr}");
}
else if (a == 1)
{
// If we want to make filter optional, then handle it here.
filter = args[a];
}
else
{
// If we want, we can show some warning or error that an unknown option was passed.
Program.ConsoleLogger.WriteWarningLine($"Unknown or invalid usage of argument: {args[a]}");
}
}
// Skip consumed extra arguments (parameterCount does not include the base argument).
a += parameterCount;
}
}
if (!options.UseRegex)
{
options.WildcardFilter = filter;
}
else
{
options.RegexPattern = filter;
}
options.Validate();
// Show help and quit.
if (help)
{
PrintHelp();
if (options.DebugLogging)
{
PressAnyKeyToContinue(); // Make it easier to check console output before closing.
}
return true; // Quit program after this
}
_commandLineOptions = options;
return false; // Command line arguments, but no help
}
public static void Initialize(string[] args)
{
Application.EnableVisualStyles();
Settings.Load(true);
Logger.ReadSettings(Settings.Instance);
ConsoleLogger.ReadSettings(Settings.Instance);
if (ParseCommandLineOptions(args))
{
return; // Help command was used, close the program.
}
PreviewForm = new PreviewForm();
Application.Run(PreviewForm);
}
public static RootEntity[] GetEntityResults()
{
lock (_allEntities)
{
return _allEntities.ToArray();
}
}
public static Texture[] GetTextureResults()
{
lock (_allTextures)
{
return _allTextures.ToArray();
}
}
public static Animation[] GetAnimationResults()
{
lock (_allAnimations)
{
return _allAnimations.ToArray();
}
}
internal static void ClearResults()
{
if (!_scanning)
{
_allEntities.Clear();
_allTextures.Clear();
_allAnimations.Clear();
if (Settings.Instance.ClearConsoleAfterClearResults)
{
Console.Clear();
}
}
}
// Returns false if the path argument was not found.
internal static bool ScanCommandLineAsync(Action<ScanProgressReport> progressCallback = null)
{
var options = _commandLineOptions;
_commandLineOptions = null; // Clear so that HasCommandLineOptions returns false
return ScanInternal(options, progressCallback, true);
}
// Returns false if the path was not found.
internal static bool ScanAsync(ScanOptions options = null, Action<ScanProgressReport> progressCallback = null)
{
return ScanInternal(options, progressCallback, true);
}
// Returns false if the path was not found.
private static bool ScanInternal(ScanOptions options, Action<ScanProgressReport> progressCallback, bool @async)
{
if (_scanning)
{
return true; // Can't start scan while another is in-progress.
}
if (options == null)
{
options = new ScanOptions(); // Use default options if none given.
}
options = options.Clone();
options.Validate();
// Read settings and also update LogTo_ properties
Logger.LogToFile = options.LogToFile;
Logger.LogToConsole = options.LogToConsole;
Logger.ReadSettings(Settings.Instance);
if (!Directory.Exists(options.Path) && !File.Exists(options.Path))
{
Program.ConsoleLogger.WriteErrorLine($"Directory/File not found: {options.Path}");
return false;
}
try
{
// Ensure regex pattern is valid
options.GetRegexFilter(false);
}
catch (Exception exp)
{
// Message starts as "parsing ...", so prefix with "Error "
Program.ConsoleLogger.WriteErrorLine($"Invalid filter: Error {exp.Message}");
return false;
}
// Assign parser settings that are no longer stored in Program
Limits.IgnoreHMDVersion = options.ContainsUnstrict(HMDParser.FormatNameConst);
Limits.IgnorePMDVersion = options.ContainsUnstrict(PMDParser.FormatNameConst);
Limits.IgnoreTIMVersion = options.ContainsUnstrict(TIMParser.FormatNameConst);
Limits.IgnoreTMDVersion = options.ContainsUnstrict(TMDParser.FormatNameConst);
_options = options;
_progressCallback = progressCallback;
_scanning = true;
_pauseRequested = false;
_cancelRequested = false;
_currentParserPositions.Clear();
_currentFilePosition = 0;
_currentFileLength = 0;
_currentFileIndex = 0;
_lastUpdateFileIndex = 0;
_totalFiles = 0;
_scannedEntityCount = 0;
_scannedTextureCount = 0;
_scannedAnimationCount = 0;
if (@async)
{
var thread = new Thread(new ThreadStart(ScanThread));
thread.SetApartmentState(ApartmentState.MTA);
thread.Start();
}
else
{
ScanThread();
}
return true;
}
private static void ScanThread()
{
try
{
_progressCallback?.Invoke(new ScanProgressReport
{
State = ScanProgressState.Started,
});
//Program.Logger.WriteLine();
Program.Logger.WriteLine("Scan begin {0}", DateTime.Now.ToString(CultureInfo.InvariantCulture));
var watch = Stopwatch.StartNew();
try
{
ScanFiles();
}
catch (Exception exp)
{
Program.Logger.WriteExceptionLine(exp, "Error scanning files");
}
watch.Stop();
var hours = (int)watch.Elapsed.TotalHours;
var minutes = watch.Elapsed.Minutes;
var seconds = watch.Elapsed.Seconds;
var milliseconds = watch.Elapsed.Milliseconds;
//Program.Logger.WriteLine();
Program.Logger.WriteLine("Scan end {0}", DateTime.Now.ToString(CultureInfo.InvariantCulture));
var millisecondsStr = string.Empty;
#if DEBUG
// Always print time taken to console for debug builds, and include milliseconds
var oldLogToConsole = Program.Logger.LogToConsole;
Program.Logger.LogToConsole = true;
millisecondsStr = $" {milliseconds} milliseconds";
#endif
Program.Logger.WriteLine("Scan took {0} hours {1} minutes {2} seconds{3}", hours, minutes, seconds, millisecondsStr);
#if DEBUG
Program.Logger.LogToConsole = oldLogToConsole;
#endif
Program.Logger.WritePositiveLine("Found {0} Models", _scannedEntityCount);
Program.Logger.WritePositiveLine("Found {0} Textures", _scannedTextureCount);
Program.Logger.WritePositiveLine("Found {0} Animations", _scannedAnimationCount);
// Scan finished, perform end-of-scan actions specified by the user.
_progressCallback?.Invoke(new ScanProgressReport
{
State = ScanProgressState.Finished,
CurrentPosition = 0,
CurrentLength = 0,
CurrentFile = _totalFiles,
TotalFiles = _totalFiles,
});
}
catch (Exception exp)
{
Program.Logger.WriteExceptionLine(exp, "Error during ScanThread");
}
// Ensure text written to log file is flushed at the end of the scan
Program.Logger.Flush();
_progressCallback = null; // Nullify to remove references to instanced method object
_scanning = false;
_pauseRequested = false;
_cancelRequested = false;
}
private static void ResetFileProgress(bool nextParser)
{
var shouldUpdateProgress = false;
lock (_fileProgressLock)
{
if (_currentFilePosition > 1 * 1024 * 1024)
{
// Always update progress if the last scan was over 1MB
shouldUpdateProgress = true;
}
if (!nextParser)
{
_currentParserPositions.Clear();
_currentFilePosition = 0;
_currentFileLength = 0;
var filesIncrease = _currentFileIndex - _lastUpdateFileIndex;
var percentIncrease = (float)filesIncrease / _totalFiles;
// Because we've changed how progress is handled, it's now fine to update every file.
// Update progress if 20 files or 10% of files scanned since last update
// todo: These numbers may need some tweaking...
//if (filesIncrease >= 20 || percentIncrease >= 0.10f)
{
shouldUpdateProgress = true;
}
}
else
{
_currentFilePosition = 0; // Start of next synchronous parser
}
}
if (shouldUpdateProgress)
{
UpdateFileProgress(null, 0, null);
}
}
private static void UpdateFileProgress(FileOffsetScanner scanner, long fp, object result)
{
long currentPosition, currentLength;
int fileIndex, totalFiles;
lock (_fileProgressLock)
{
_lastUpdateFileIndex = _currentFileIndex;
if (scanner != null)
{
// This is being called by a scanner callback, so update the current file progress.
_currentParserPositions[scanner] = fp;
var maxfp = _currentParserPositions.Values.Max();
if (maxfp != _currentFilePosition || _currentFileIndex != _totalFiles)
{
_currentFilePosition = maxfp;
}
else if (result == null)
{
return; // Position hasn't changed and we didn't find a file, don't update progress
}
}
// We need to store these as local variables before leaving the lock.
currentPosition = _currentFilePosition;
currentLength = Math.Max(1, _currentFileLength); // Max of 1 to prevent showing complete bar before we have a length
fileIndex = _currentFileIndex;
totalFiles = _totalFiles;
}
_progressCallback?.Invoke(new ScanProgressReport
{
State = ScanProgressState.Updated,
CurrentFile = fileIndex,
TotalFiles = totalFiles,
CurrentPosition = currentPosition,
CurrentLength = currentLength,
Result = result,
});
}
private static bool AddEntity(FileOffsetScanner scanner, RootEntity entity, long fp)
{
// Prevent another thread from enumerating or modifying the list while adding to it.
lock (_allEntities)
{
_allEntities.Add(entity);
_scannedEntityCount++;
}
UpdateFileProgress(scanner, fp, entity);
return true;
}
private static bool AddTexture(FileOffsetScanner scanner, Texture texture, long fp)
{
// Prevent another thread from enumerating or modifying the list while adding to it.
lock (_allTextures)
{
_allTextures.Add(texture);
_scannedTextureCount++;
}
UpdateFileProgress(scanner, fp, texture);
return true;
}
private static bool AddAnimation(FileOffsetScanner scanner, Animation animation, long fp)
{
// Prevent another thread from enumerating or modifying the list while adding to it.
lock (_allAnimations)
{
_allAnimations.Add(animation);
_scannedAnimationCount++;
}
UpdateFileProgress(scanner, fp, animation);
return true;
}
private static void ProgressCallback(FileOffsetScanner scanner, long fp)
{
UpdateFileProgress(scanner, fp, null); // Update progress bar but don't reload items
}
internal static bool PauseScan(bool paused)
{
if (_scanning)
{
if (!paused)
{
_pauseRequested = false;
}
else if (!_cancelRequested)
{
_pauseRequested = true; // Cannot pause while scan is canceled.
}
}
return _pauseRequested;
}
internal static bool CancelScan()
{
if (_scanning)
{
_pauseRequested = false; // Prevent waiting in while loop if canceled.
_cancelRequested = true;
}
return _cancelRequested;
}
// Returns true if the program has requested to cancel the scan.
internal static bool WaitOnScanState()
{
// Currently the code is written so that _pauseRequested and _cancelRequested
// will never be true at the same time. Otherwise we could wait in an endless loop,
// even if we canceled the scan.
//
// If we want to be lazier when managing the state of these two variables then
// change the while loop condition to: `_pauseRequested && !_cancelRequested`.
while (_pauseRequested)
{
// Give priority to other threads and don't run up the CPU with constant looping.
// This is fine to use here, because we don't expect _pauseRequested to change frequently.
// Note that lms will average at least 10ms due to how Sleep works, which is fine.
Thread.Sleep(1);
}
return _cancelRequested;
}
private static bool HasFileExtension(string file, string[] extensions)
{
var ext = Path.GetExtension(file).ToLowerInvariant();
return Array.IndexOf(extensions, ext) != -1;
}
private static string StripBINPostfix(string file)
{
// The ";1" postfix is seen in raw PS1 CD files for all file names.
// We want to ignore it.
if (Path.GetExtension(file).EndsWith(BINPostfix))
{
return file.Substring(0, file.Length - BINPostfix.Length);
}
return file;
}
private static bool ShouldIncludeFile(string file, Regex regex)
{
if (!HasFileExtension(file, IgnoreFileExtensions))
{
return regex?.IsMatch(Path.GetFileName(file)) ?? true;
}
return false;
}
private static bool ShouldProcessISOContents(string file)
{
return _options.ReadISOContents && HasFileExtension(file, ISOFileExtensions);
}
private static bool ShouldProcessBINContents(string file)
{
return (_options.ReadBINContents || _options.ReadBINSectorData) &&
HasFileExtension(file, BINFileExtensions) &&