Skip to content

Commit

Permalink
code clean
Browse files Browse the repository at this point in the history
  • Loading branch information
UlyssesWu committed Aug 14, 2021
1 parent 7ab7dd7 commit fa52d8d
Show file tree
Hide file tree
Showing 7 changed files with 58 additions and 61 deletions.
18 changes: 8 additions & 10 deletions FreeMote.PsBuild/PsbDecompiler.cs
Original file line number Diff line number Diff line change
Expand Up @@ -74,13 +74,11 @@ public static string Decompile(string path, out PSB psb, Dictionary<string, obje
{
try
{
using (var mms = new MemoryStream((int) stream.Length))
{
PsbFile.Encode(key.Value, EncodeMode.Decrypt, EncodePosition.Auto, stream, mms);
stream.Dispose();
psb = new PSB(mms);
ctx.Context[Consts.Context_CryptKey] = key;
}
using var mms = new MemoryStream((int)stream.Length);
PsbFile.Encode(key.Value, EncodeMode.Decrypt, EncodePosition.Auto, stream, mms);
stream.Dispose();
psb = new PSB(mms);
ctx.Context[Consts.Context_CryptKey] = key;
}
catch
{
Expand Down Expand Up @@ -125,15 +123,15 @@ internal static void OutputResources(PSB psb, FreeMountContext context, string f
var name = Path.GetFileNameWithoutExtension(filePath);
var dirPath = Path.Combine(Path.GetDirectoryName(filePath), name);
PsbResourceJson resx = new PsbResourceJson(psb, context.Context);

if (File.Exists(dirPath))
{
name += "-resources";
dirPath += "-resources";
}

var extraDir = Path.Combine(dirPath, Consts.ExtraResourceFolderName);

if (!Directory.Exists(dirPath)) //ensure there is no file with same name!
{
if (psb.Resources.Count != 0)
Expand Down Expand Up @@ -333,7 +331,7 @@ public static void ExtractImageFiles(string inputPath, PsbImageFormat format = P
}

var texs = PsbResHelper.UnlinkImages(psb);

foreach (var tex in texs)
{
tex.Save(Path.Combine(dirPath, tex.Tag + texExt), texFormat);
Expand Down
2 changes: 1 addition & 1 deletion FreeMote.Psb/Plugins/FreeMount.cs
Original file line number Diff line number Diff line change
Expand Up @@ -429,7 +429,7 @@ public MemoryStream PackToShell(Stream stream, string type, Dictionary<string, o
{
return _keyProvider?.Value?.GetKey(stream, context);
}

public void Dispose()
{
_container?.Dispose();
Expand Down
32 changes: 16 additions & 16 deletions FreeMote.Psb/PsbResHelper.cs
Original file line number Diff line number Diff line change
Expand Up @@ -81,12 +81,12 @@ public static List<T> CollectResources<T>(this PSB psb, bool deDuplication = tru
{
resourceList = new List<T>();
if (psb.Resources != null)
resourceList.AddRange(psb.Resources.Select(r => new ImageMetadata {Resource = r}).Cast<T>());
resourceList.AddRange(psb.Resources.Select(r => new ImageMetadata { Resource = r }).Cast<T>());
}

//Set Spec
resourceList.ForEach(r => r.Spec = psb.Platform);
resourceList.Sort((md1, md2) => (int) (md1.Index - md2.Index));
resourceList.Sort((md1, md2) => (int)(md1.Index - md2.Index));

return resourceList;
}
Expand Down Expand Up @@ -123,7 +123,7 @@ public static void LinkImages(PSB psb, FreeMountContext context, IList<string> r
}

resList.Sort((md1, md2) =>
(int) (((ImageMetadata) md1).TextureIndex ?? 0) - (int) (((ImageMetadata) md2).TextureIndex ?? 0));
(int)(((ImageMetadata)md1).TextureIndex ?? 0) - (int)(((ImageMetadata)md2).TextureIndex ?? 0));
}

for (var i = 0; i < resPaths.Count; i++)
Expand Down Expand Up @@ -165,7 +165,7 @@ public static void LinkImages(PSB psb, FreeMountContext context, IList<string> r
continue;
}

resMd = resList[(int) texIdx.Value];
resMd = resList[(int)texIdx.Value];
}
}
else //if (order == PsbLinkOrderBy.Convention)
Expand Down Expand Up @@ -248,7 +248,7 @@ internal static void LinkImages(PSB psb, FreeMountContext context, IDictionary<s
continue;
}

if (!overwrite && resMd.Data is { Length: > 0 }) //skip if resource is already filled and we don't want not overwrite
if (!overwrite && resMd.Data is { Length: > 0 }) //skip if resource is already filled and we don't want to overwrite
{
continue;
}
Expand Down Expand Up @@ -304,7 +304,7 @@ bool LinkFromFile(PsbResource res, string key)
res.Data = File.ReadAllBytes(fullPath);
return true;
}

return false;
}

Expand Down Expand Up @@ -710,10 +710,10 @@ internal static ImageMetadata GenerateImageMetadata(PsbDictionary d, PsbResource
{
is2D = true;
clip = RectangleF.FromLTRB(
left: clipDic["left"] == null ? 0f : (float) (PsbNumber) clipDic["left"],
top: clipDic["top"] == null ? 0f : (float) (PsbNumber) clipDic["top"],
right: clipDic["right"] == null ? 1f : (float) (PsbNumber) clipDic["right"],
bottom: clipDic["bottom"] == null ? 1f : (float) (PsbNumber) clipDic["bottom"]
left: clipDic["left"] == null ? 0f : (float)(PsbNumber)clipDic["left"],
top: clipDic["top"] == null ? 0f : (float)(PsbNumber)clipDic["top"],
right: clipDic["right"] == null ? 1f : (float)(PsbNumber)clipDic["right"],
bottom: clipDic["bottom"] == null ? 1f : (float)(PsbNumber)clipDic["bottom"]
);
}

Expand All @@ -732,25 +732,25 @@ internal static ImageMetadata GenerateImageMetadata(PsbDictionary d, PsbResource
if (d["width"] is PsbNumber nw)
{
is2D = true;
width = (int) nw;
width = (int)nw;
}

if (d["height"] is PsbNumber nh)
{
is2D = true;
height = (int) nh;
height = (int)nh;
}

if (d["originX"] is PsbNumber nx)
{
is2D = true;
originX = (float) nx;
originX = (float)nx;
}

if (d["originY"] is PsbNumber ny)
{
is2D = true;
originY = (float) ny;
originY = (float)ny;
}

PsbString typeString = null;
Expand All @@ -763,13 +763,13 @@ internal static ImageMetadata GenerateImageMetadata(PsbDictionary d, PsbResource
if (d["top"] is PsbNumber nt)
{
is2D = true;
top = (int) nt;
top = (int)nt;
}

if (d["left"] is PsbNumber nl)
{
is2D = true;
left = (int) nl;
left = (int)nl;
}

PsbResource palResource = null;
Expand Down
6 changes: 3 additions & 3 deletions FreeMote.Psb/Resources/ImageMetadata.cs
Original file line number Diff line number Diff line change
Expand Up @@ -15,8 +15,8 @@ namespace FreeMote.Psb
[DebuggerDisplay("{" + nameof(DebuggerString) + "}")]
public class ImageMetadata : IResourceMetadata
{
private static readonly List<string> SupportedImageExt = new List<string> {".png", ".bmp", ".jpg", ".jpeg"};
private static readonly List<string> SupportedImageExt = new List<string> { ".png", ".bmp", ".jpg", ".jpeg" };

/// <summary>
/// Name 1
/// </summary>
Expand Down Expand Up @@ -424,7 +424,7 @@ static bool IsPowOf2(int n)
{
//it's not a combined image, do nothing
}
else if((image.Width >= Width || image.Height >= Height) && image.Width >= Left && image.Height >= Height)
else if ((image.Width >= Width || image.Height >= Height) && image.Width >= Left && image.Height >= Height)
{
Bitmap chunk = new Bitmap(Width, Height, image.PixelFormat);
//it should be a combined image
Expand Down
7 changes: 3 additions & 4 deletions FreeMote.Psb/Types/ImageType.cs
Original file line number Diff line number Diff line change
Expand Up @@ -63,9 +63,8 @@ public override Dictionary<string, string> OutputResources(PSB psb, FreeMountCon

return base.OutputResources(psb, context, name, dirPath, extractOption);
}


public List<T> CollectResources<T>(PSB psb, bool deDuplication = true) where T: IResourceMetadata

public List<T> CollectResources<T>(PSB psb, bool deDuplication = true) where T : IResourceMetadata
{
List<T> resourceList = psb.Resources == null
? new List<T>()
Expand All @@ -76,7 +75,7 @@ public List<T> CollectResources<T>(PSB psb, bool deDuplication = true) where T:
return resourceList;
}

private static void FindTachieResources<T>(List<T> list, IPsbValue obj, string currentLabel = "") where T: IResourceMetadata
private static void FindTachieResources<T>(List<T> list, IPsbValue obj, string currentLabel = "") where T : IResourceMetadata
{
switch (obj)
{
Expand Down
20 changes: 10 additions & 10 deletions FreeMote.Tools.PsBuild/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -231,9 +231,9 @@ PsBuild replace sample.psb sample.json
JsonUseDoubleOnly = true;
}

ushort? ver = optVer.HasValue() ? optVer.ParsedValue : (ushort?) null;
uint? key = optKey.HasValue() ? optKey.ParsedValue : (uint?) null;
PsbSpec? spec = optSpec.HasValue() ? optSpec.ParsedValue : (PsbSpec?) null;
ushort? ver = optVer.HasValue() ? optVer.ParsedValue : null;
uint? key = optKey.HasValue() ? optKey.ParsedValue : null;
PsbSpec? spec = optSpec.HasValue() ? optSpec.ParsedValue : null;
var canRename = !optNoRename.HasValue();
var canPack = !optNoShell.HasValue();

Expand Down Expand Up @@ -393,7 +393,7 @@ public static void PackArchive(string jsonPath, string key, bool intersect, bool
List<string> sourceDirs = null;
if (resx.Context[Context_ArchiveSource] is string path)
{
sourceDirs = new List<string> {path};
sourceDirs = new List<string> { path };
}
else if (resx.Context[Context_ArchiveSource] is IList paths)
{
Expand All @@ -412,7 +412,7 @@ public static void PackArchive(string jsonPath, string key, bool intersect, bool
List<string> filter = null;
if (intersect) //only collect files appeared in json
{
filter = ArchiveInfoCollectFiles(infoPsb, suffix).Select(p => p.Replace('\\','/')).ToList();
filter = ArchiveInfoCollectFiles(infoPsb, suffix).Select(p => p.Replace('\\', '/')).ToList();
}

void CollectFilesFromList(string targetDir, List<string> infoFiles)
Expand All @@ -432,7 +432,7 @@ void CollectFilesFromList(string targetDir, List<string> infoFiles)
{
files[infoFile] = (f, keepRaw ? ProcessMethod.None : ProcessMethod.Compile);
}
else if(File.Exists(source))
else if (File.Exists(source))
{
files[infoFile] = (f, ProcessMethod.Compile);
}
Expand All @@ -456,7 +456,7 @@ void CollectFiles(string targetDir)
foreach (var f in Directory.EnumerateFiles(targetDir, "*", SearchOption.AllDirectories))
{
if (skipDirs.Contains(Path.GetDirectoryName(f))) //this dir is a source dir for json, just skip
{
{
continue;
}

Expand All @@ -483,7 +483,7 @@ void CollectFiles(string targetDir)
}
else
{
files[name] = (f, keepRaw? ProcessMethod.None: ProcessMethod.Compile);
files[name] = (f, keepRaw ? ProcessMethod.None : ProcessMethod.Compile);
}
}
}
Expand All @@ -506,7 +506,7 @@ void CollectFiles(string targetDir)
using var fs = File.OpenRead(f);
if (!MdfFile.IsSignatureMdf(fs) && name.DefaultShellType() == "MDF")
{
files[name] = (f, keepRaw? ProcessMethod.None: ProcessMethod.EncodeMdf);
files[name] = (f, keepRaw ? ProcessMethod.None : ProcessMethod.EncodeMdf);
}
else
{
Expand Down Expand Up @@ -580,7 +580,7 @@ void CollectFiles(string targetDir)
if (kv.Value.Method == ProcessMethod.EncodeMdf)
{
using var mmFs = MemoryMappedFile.CreateFromFile(kv.Value.Path, FileMode.Open);

//using var fs = File.OpenRead(kv.Value.Path);
contents.Add((relativePathWithoutSuffix, context.PackToShell(mmFs.CreateViewStream(), "MDF"))); //disposed later
}
Expand Down
34 changes: 17 additions & 17 deletions FreeMote.Tools.PsbDecompile/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -92,7 +92,7 @@ PsbDecompile image sample-resource-folder
}
else if (Directory.Exists(psbPath))
{
var files = FreeMoteExtension.GetFiles(psbPath, new[] {"*.psb", "*.pimg", "*.m", "*.bytes"});
var files = FreeMoteExtension.GetFiles(psbPath, new[] { "*.psb", "*.pimg", "*.m", "*.bytes" });

if (enableParallel)
{
Expand Down Expand Up @@ -242,7 +242,7 @@ PsbDecompile info-psb -k 1234567890ab -l 131 -a sample_info.psb.m

if (keyLen >= 0)
{
context[Context_MdfKeyLength] = (uint) keyLen;
context[Context_MdfKeyLength] = (uint)keyLen;
}

Stopwatch sw = Stopwatch.StartNew();
Expand Down Expand Up @@ -286,7 +286,7 @@ PsbDecompile info-psb -k 1234567890ab -l 131 -a sample_info.psb.m

bool useRaw = optRaw.HasValue();
//PsbImageFormat format = optFormat.HasValue() ? optFormat.ParsedValue : PsbImageFormat.png;
uint? key = optKey.HasValue() ? optKey.ParsedValue : (uint?) null;
uint? key = optKey.HasValue() ? optKey.ParsedValue : (uint?)null;

PsbType type = PsbType.PSB;
if (optType.HasValue())
Expand All @@ -302,7 +302,7 @@ PsbDecompile info-psb -k 1234567890ab -l 131 -a sample_info.psb.m
else if (Directory.Exists(s))
{
foreach (var file in FreeMoteExtension.GetFiles(s,
new[] {"*.psb", "*.mmo", "*.pimg", "*.scn", "*.dpak", "*.psz", "*.psp", "*.bytes", "*.m"}))
new[] { "*.psb", "*.mmo", "*.pimg", "*.scn", "*.dpak", "*.psz", "*.psp", "*.bytes", "*.m" }))
{
Decompile(s, useRaw, PsbImageFormat.png, key, type, context);
}
Expand Down Expand Up @@ -450,17 +450,17 @@ static void ExtractArchive(string filePath, string key, Dictionary<string, objec
PsbResourceJson resx = new PsbResourceJson(psb, context);

var dic = psb.Objects["file_info"] as PsbDictionary;
var suffixList = (PsbList) psb.Objects["expire_suffix_list"];
var suffixList = (PsbList)psb.Objects["expire_suffix_list"];
var suffix = "";
if (suffixList.Count > 0)
{
suffix = suffixList[0] as PsbString ?? "";
}

if (!hasBody)
{
//Write resx.json
resx.Context[Context_ArchiveSource] = new List<string> {name};
resx.Context[Context_ArchiveSource] = new List<string> { name };
File.WriteAllText(Path.GetFullPath(filePath) + ".resx.json", resx.SerializeToJson());
return;
}
Expand All @@ -478,17 +478,17 @@ static void ExtractArchive(string filePath, string key, Dictionary<string, objec
{
Directory.CreateDirectory(extractDir);
}

if (enableParallel) //parallel!
{
using var mmFile =
MemoryMappedFile.CreateFromFile(body, FileMode.Open, name, 0, MemoryMappedFileAccess.Read);
Parallel.ForEach(dic, pair =>
{
//Console.WriteLine($"{(extractAll ? "Decompiling" : "Extracting")} {pair.Key} ...");
var range = ((PsbList) pair.Value);
var start = ((PsbNumber) range[0]).UIntValue;
var len = ((PsbNumber) range[1]).IntValue;
var range = ((PsbList)pair.Value);
var start = ((PsbNumber)range[0]).UIntValue;
var len = ((PsbNumber)range[1]).IntValue;

using var mmAccessor = mmFile.CreateViewAccessor(start, len, MemoryMappedFileAccess.Read);
var bodyBytes = new byte[len];
Expand Down Expand Up @@ -555,9 +555,9 @@ static void ExtractArchive(string filePath, string key, Dictionary<string, objec
{
Console.WriteLine(
$"{(extractAll ? "Decompiling" : "Extracting")} {pair.Key} ...");
var range = ((PsbList) pair.Value);
var start = ((PsbNumber) range[0]).IntValue;
var len = ((PsbNumber) range[1]).IntValue;
var range = ((PsbList)pair.Value);
var start = ((PsbNumber)range[0]).IntValue;
var len = ((PsbNumber)range[1]).IntValue;

using var mmAccessor = mmFile.CreateViewAccessor(start, len, MemoryMappedFileAccess.Read);
var bodyBytes = new byte[len];
Expand All @@ -581,7 +581,7 @@ static void ExtractArchive(string filePath, string key, Dictionary<string, objec
{
context[Context_MdfKey] = key + fileNameWithSuffix;
var shellType = relativePathWithSuffix.DefaultShellType();
var mms = string.IsNullOrEmpty(shellType)? ms : MdfConvert(ms, shellType, context);
var mms = string.IsNullOrEmpty(shellType) ? ms : MdfConvert(ms, shellType, context);
if (extractAll && PsbFile.CheckSignature(mms))
{
try
Expand Down Expand Up @@ -611,11 +611,11 @@ static void ExtractArchive(string filePath, string key, Dictionary<string, objec
}

//Write resx.json
resx.Context[Context_ArchiveSource] = new List<string> {name};
resx.Context[Context_ArchiveSource] = new List<string> { name };
resx.Context[Context_MdfMtKey] = key;
resx.Context[Context_MdfKey] = archiveMdfKey;
File.WriteAllText(Path.GetFullPath(filePath) + ".resx.json", resx.SerializeToJson());

}
catch (Exception e)
{
Expand Down

0 comments on commit fa52d8d

Please sign in to comment.