Refactoring

C# 6.0

Fixed lz decompression arguments from toolstrip.
This commit is contained in:
Kaphotics
2016-01-25 21:02:54 -08:00
parent 9a5a1e0d15
commit 75f44d2af5
49 changed files with 869 additions and 901 deletions

View File

@@ -6,9 +6,9 @@ namespace CTR
{
public class AesCtr
{
private AesManaged Aes = new AesManaged();
private ICryptoTransform Encryptor;
private AesCounter Counter;
private readonly AesManaged Aes = new AesManaged();
private readonly ICryptoTransform Encryptor;
private readonly AesCounter Counter;
public AesCtr(byte[] key, byte[] iv)
{
@@ -35,7 +35,7 @@ public int TransformBlock(byte[] inputBuffer, int inputOffset, int inputCount, b
{
BlockLength = inputCount - i > AesCounter.BufferSize ? AesCounter.BufferSize : inputCount - i;
Encryptor.TransformBlock(Counter.ManageBufferCounters(BlockLength), 0, BlockLength, outputBuffer, outputOffset + i);
for (int BlockWalker = i; BlockWalker < (i + BlockLength); BlockWalker += 8)
for (int BlockWalker = i; BlockWalker < i + BlockLength; BlockWalker += 8)
{
Array.Copy(BitConverter.GetBytes(BitConverter.ToInt64(outputBuffer, outputOffset + BlockWalker) ^ BitConverter.ToInt64(inputBuffer, inputOffset + BlockWalker)), 0, outputBuffer, outputOffset + BlockWalker, 8);
}
@@ -46,8 +46,8 @@ public int TransformBlock(byte[] inputBuffer, int inputOffset, int inputCount, b
public class AesCounter
{
public const int BufferSize = 0x400000; //4 MB Buffer
private byte[] Counter = new byte[0x10];
private byte[] Buffer = new byte[BufferSize];
private readonly byte[] Counter = new byte[0x10];
private readonly byte[] Buffer = new byte[BufferSize];
public AesCounter(ulong high, ulong low)
{
@@ -64,7 +64,7 @@ public void Increment()
{
for (int i = Counter.Length - 1; i >= 0; i--)
{
if ((++Counter[i]) != 0)
if (++Counter[i] != 0)
return;
}
}
@@ -83,14 +83,14 @@ public ulong SwapBytes(ulong value)
{
ulong uvalue = value;
ulong swapped =
((0x00000000000000FF) & (uvalue >> 56)
| (0x000000000000FF00) & (uvalue >> 40)
| (0x0000000000FF0000) & (uvalue >> 24)
| (0x00000000FF000000) & (uvalue >> 8)
| (0x000000FF00000000) & (uvalue << 8)
| (0x0000FF0000000000) & (uvalue << 24)
| (0x00FF000000000000) & (uvalue << 40)
| (0xFF00000000000000) & (uvalue << 56));
0x00000000000000FF & (uvalue >> 56)
| 0x000000000000FF00 & (uvalue >> 40)
| 0x0000000000FF0000 & (uvalue >> 24)
| 0x00000000FF000000 & (uvalue >> 8)
| 0x000000FF00000000 & (uvalue << 8)
| 0x0000FF0000000000 & (uvalue << 24)
| 0x00FF000000000000 & (uvalue << 40)
| 0xFF00000000000000 & (uvalue << 56);
return swapped;
}
}

View File

@@ -272,7 +272,7 @@ internal static Bitmap getIMG_ETC(CLIM bclim)
GCHandle pInput = GCHandle.Alloc(input, GCHandleType.Pinned);
/* Marshal data around, invoke ETC1.dll for conversion, etc */
UInt32 size1 = 0;
uint size1 = 0;
UInt16 w = (ushort)img.Width, h = (ushort)img.Height;
ETC1.ConvertETC1(IntPtr.Zero, ref size1, IntPtr.Zero, w, h, bclim.FileFormat == 0xB); // true = etc1a4, false = etc1
@@ -317,8 +317,8 @@ internal static Bitmap getIMG_ETC(CLIM bclim)
for (int j = 0; j < 8; j++)
// Treat every 8 vertical pixels as 1 pixel for purposes of calculation, add to offset later.
{
int x1 = (x + ((y/8)*h))%img2.Width; // Reshift x
int y1 = ((x + ((y/8)*h))/img2.Width)*8; // Reshift y
int x1 = (x + y/8*h)%img2.Width; // Reshift x
int y1 = (x + y/8*h)/img2.Width*8; // Reshift y
img2.SetPixel(x1, y1 + j, img.GetPixel(x, y + j)); // Reswizzle
}
}
@@ -336,7 +336,7 @@ internal static Bitmap getIMG_ETC(CLIM bclim)
// Treat every 8 vertical pixels as 1 pixel for purposes of calculation, add to offset later.
{
int x1 = x%img2.Width; // Reshift x
int y1 = ((x + ((y/8)*h))/img2.Width)*8; // Reshift y
int y1 = (x + y/8*h)/img2.Width*8; // Reshift y
img2.SetPixel(x1, y1 + j, img.GetPixel(x, y + j)); // Reswizzle
}
}
@@ -416,7 +416,7 @@ internal static int write16BitColorPalette(Bitmap img, ref MemoryStream ms)
if (c.A == 0) index = 0;
if (index < 0) // If new color
{ pcs[ctr] = c; index = ctr; ctr++; }
pixelarray[i / div] |= (byte)(index);
pixelarray[i / div] |= (byte)index;
i++;
}
@@ -448,7 +448,7 @@ internal static byte[] getPixelData(Bitmap img, int format, bool rectangle = tru
int w = img.Width;
int h = img.Height;
bool perfect = (w == h && (w != 0) && ((w & (w - 1)) == 0));
bool perfect = w == h && (w != 0) && ((w & (w - 1)) == 0);
if (!perfect) // Check if square power of two, else resize
{
// Square Format Checks
@@ -567,7 +567,7 @@ private static Color DecodeColor(uint val, int format)
alpha = (byte)(val & 0x0F);
return Color.FromArgb(alpha, red, red, red);
case 3: // LA8
red = (byte)((val >> 8 & 0xFF));
red = (byte)(val >> 8 & 0xFF);
alpha = (byte)(val & 0xFF);
return Color.FromArgb(alpha, red, red, red);
case 4: // HILO8
@@ -628,15 +628,15 @@ internal static byte GetA8(Color c)
} // A8
internal static byte GetLA4(Color c)
{
return (byte)((c.A / 0x11) + (c.R / 0x11) << 4);
return (byte)(c.A / 0x11 + c.R / 0x11 << 4);
} // LA4
internal static ushort GetLA8(Color c)
{
return (ushort)((c.A) + ((c.R) << 8));
return (ushort)(c.A + (c.R << 8));
} // LA8
internal static ushort GetHILO8(Color c)
{
return (ushort)((c.G) + ((c.R) << 8));
return (ushort)(c.G + (c.R << 8));
} // HILO8
internal static ushort GetRGB565(Color c)
{
@@ -662,10 +662,10 @@ internal static ushort GetRGBA5551(Color c)
internal static ushort GetRGBA4444(Color c)
{
int val = 0;
val += (c.A / 0x11);
val += ((c.B / 0x11) << 4);
val += ((c.G / 0x11) << 8);
val += ((c.R / 0x11) << 12);
val += c.A / 0x11;
val += (c.B / 0x11) << 4;
val += (c.G / 0x11) << 8;
val += (c.R / 0x11) << 12;
return (ushort)val;
}// RGBA4444
internal static uint GetRGBA8888(Color c) // RGBA8888
@@ -690,15 +690,15 @@ internal static byte convert8to5(int colorval)
while (colorval > Convert8to5[i]) i++;
return i;
}
internal static UInt32 DM2X(UInt32 code)
internal static uint DM2X(uint code)
{
return C11(code >> 0);
}
internal static UInt32 DM2Y(UInt32 code)
internal static uint DM2Y(uint code)
{
return C11(code >> 1);
}
internal static UInt32 C11(UInt32 x)
internal static uint C11(uint x)
{
x &= 0x55555555; // x = -f-e -d-c -b-a -9-8 -7-6 -5-4 -3-2 -1-0
x = (x ^ (x >> 1)) & 0x33333333; // x = --fe --dc --ba --98 --76 --54 --32 --10
@@ -716,7 +716,7 @@ internal static UInt32 C11(UInt32 x)
/// <returns>Rounded up number.</returns>
internal static int gcm(int n, int m)
{
return ((n + m - 1) / m) * m;
return (n + m - 1) / m * m;
}
/// <summary>
/// Next Largest Power of 2
@@ -726,12 +726,12 @@ internal static int gcm(int n, int m)
internal static int nlpo2(int x)
{
x--; // comment out to always take the next biggest power of two, even if x is already a power of two
x |= (x >> 1);
x |= (x >> 2);
x |= (x >> 4);
x |= (x >> 8);
x |= (x >> 16);
return (x+1);
x |= x >> 1;
x |= x >> 2;
x |= x >> 4;
x |= x >> 8;
x |= x >> 16;
return x+1;
}
// Morton Translation
@@ -745,20 +745,20 @@ internal static uint xy2d(uint x, uint y)
{
x &= 0x0000ffff;
y &= 0x0000ffff;
x |= (x << 8);
y |= (y << 8);
x |= x << 8;
y |= y << 8;
x &= 0x00ff00ff;
y &= 0x00ff00ff;
x |= (x << 4);
y |= (y << 4);
x |= x << 4;
y |= y << 4;
x &= 0x0f0f0f0f;
y &= 0x0f0f0f0f;
x |= (x << 2);
y |= (y << 2);
x |= x << 2;
y |= y << 2;
x &= 0x33333333;
y &= 0x33333333;
x |= (x << 1);
y |= (y << 1);
x |= x << 1;
y |= y << 1;
x &= 0x55555555;
y &= 0x55555555;
return x | (y << 1);
@@ -772,23 +772,23 @@ internal static uint xy2d(uint x, uint y)
internal static void d2xy(uint d, out uint x, out uint y)
{
x = d;
y = (x >> 1);
y = x >> 1;
x &= 0x55555555;
y &= 0x55555555;
x |= (x >> 1);
y |= (y >> 1);
x |= x >> 1;
y |= y >> 1;
x &= 0x33333333;
y &= 0x33333333;
x |= (x >> 2);
y |= (y >> 2);
x |= x >> 2;
y |= y >> 2;
x &= 0x0f0f0f0f;
y &= 0x0f0f0f0f;
x |= (x >> 4);
y |= (y >> 4);
x |= x >> 4;
y |= y >> 4;
x &= 0x00ff00ff;
y &= 0x00ff00ff;
x |= (x >> 8);
y |= (y >> 8);
x |= x >> 8;
y |= y >> 8;
x &= 0x0000ffff;
y &= 0x0000ffff;
}
@@ -867,24 +867,24 @@ public static CLIM analyze(string path)
}
public struct CLIM
{
public UInt32 Magic; // CLIM = 0x4D494C43
public uint Magic; // CLIM = 0x4D494C43
public UInt16 BOM; // 0xFFFE
public UInt32 CLIMLength; // HeaderLength - 14
public uint CLIMLength; // HeaderLength - 14
public int TileWidth; // 1<<[[n]]
public int TileHeight; // 1<<[[n]]
public UInt32 totalLength; // Total Length of file
public UInt32 Count; // "1" , guessing it's just Count.
public uint totalLength; // Total Length of file
public uint Count; // "1" , guessing it's just Count.
public char[] imag; // imag = 0x67616D69
public UInt32 imagLength; // HeaderLength - 10
public uint imagLength; // HeaderLength - 10
public UInt16 Width; // Final Dimensions
public UInt16 Height; // Final Dimensions
public Int32 FileFormat; // ??
public UInt32 dataLength; // Pixel Data Region Length
public int FileFormat; // ??
public uint dataLength; // Pixel Data Region Length
public byte[] Data;
public Int32 BaseSize;
public int BaseSize;
//// Contained Data
//public int ColorFormat;

View File

@@ -28,7 +28,7 @@ namespace CTR
{
public class BLZCoder
{
public static void main(String[] args)
public static void main(string[] args)
{
new BLZCoder(args);
}
@@ -46,13 +46,13 @@ public static void main(String[] args)
private const int BLZ_MAXIM = 0x01400000;
private const int RAW_MAXIM = 0x00FFFFFF;
bool arm9;
readonly bool arm9;
int new_len;
static void EXIT(string text)
{
Console.Write(text);
}
private ProgressBar pBar1;
private readonly ProgressBar pBar1;
private void initpBar(int max)
{
if (pBar1.InvokeRequired)
@@ -103,7 +103,7 @@ public BLZCoder(string[] args, ProgressBar pBar = null)
BLZ_Decode(args[arg]);
break;
case 1:
arm9 = (args[0].Length > 3 && args[0][3] == '9');
arm9 = args[0].Length > 3 && args[0][3] == '9';
for (arg = 1; arg < args.Length; arg++)
BLZ_Encode(args[arg], mode);
break;
@@ -112,7 +112,7 @@ public BLZCoder(string[] args, ProgressBar pBar = null)
Console.Write(Environment.NewLine + "Done" + Environment.NewLine);
}
private void Save(String filename, byte[] buffer, int length)
private void Save(string filename, byte[] buffer, int length)
{
Array.Resize(ref buffer, length);
try
@@ -124,7 +124,7 @@ private void Save(String filename, byte[] buffer, int length)
Console.Write(Environment.NewLine + "Wrote to 'blz.bin' instead." + Environment.NewLine);
}
}
private void BLZ_Decode(String filename)
private void BLZ_Decode(string filename)
{
try
{
@@ -222,7 +222,7 @@ private BLZResult BLZ_Decode(byte[] data)
}
else
{
if ((pak + 1) >= pak_end)
if (pak + 1 >= pak_end)
break;
int pos = pak_buffer[pak++] << 8;
@@ -234,7 +234,7 @@ private BLZResult BLZ_Decode(byte[] data)
len = raw_end - raw;
}
pos = (pos & 0xFFF) + 3;
while ((len--) > 0)
while (len-- > 0)
{
int charHere = raw_buffer[raw - pos];
raw_buffer[raw++] = (byte)charHere;
@@ -286,7 +286,7 @@ private void writeUnsigned(byte[] buffer, int offset, int value)
buffer[offset + 2] = (byte)((value >> 16) & 0xFF);
buffer[offset + 3] = (byte)((value >> 24) & 0x7F);
}
private void BLZ_Encode(String filename, int mode)
private void BLZ_Encode(string filename, int mode)
{
try
{
@@ -300,7 +300,7 @@ private void BLZ_Encode(String filename, int mode)
Save(filename, result.buffer, result.length);
stopwatch.Stop();
Console.Write(Environment.NewLine + "Done, time elapsed = " + (stopwatch.ElapsedMilliseconds) + "ms" + Environment.NewLine);
Console.Write(Environment.NewLine + "Done, time elapsed = " + stopwatch.ElapsedMilliseconds + "ms" + Environment.NewLine);
}
catch (IOException e)
{ Console.Write(Environment.NewLine + "File read error" + Environment.NewLine + e + Environment.NewLine); }
@@ -315,7 +315,7 @@ private byte[] BLZ_Code(byte[] raw_buffer, int raw_len, int best)
int pak_tmp = 0;
int raw_tmp = raw_len;
int pak_len = raw_len + ((raw_len + 7) / 8) + 11;
int pak_len = raw_len + (raw_len + 7) / 8 + 11;
byte[] pak_buffer = new byte[pak_len];
int raw_new = raw_len;
@@ -338,7 +338,7 @@ private byte[] BLZ_Code(byte[] raw_buffer, int raw_len, int best)
setpBarPos(raw);
if ((mask = (int)((uint)mask >> BLZ_SHIFT)) == 0)
{
pak_buffer[(flg = pak++)] = 0;
pak_buffer[flg = pak++] = 0;
mask = BLZ_MASK;
}
@@ -358,7 +358,7 @@ private byte[] BLZ_Code(byte[] raw_buffer, int raw_len, int best)
raw_end);
int len_next = sl2.l;
pos_next = sl2.p;
raw -= (len_best - 1);
raw -= len_best - 1;
SearchPair sl3 = SEARCH(pos_post, raw_buffer, raw,
raw_end);
int len_post = sl3.l;
@@ -369,7 +369,7 @@ private byte[] BLZ_Code(byte[] raw_buffer, int raw_len, int best)
len_next = 1;
if (len_post <= BLZ_THRESHOLD)
len_post = 1;
if ((len_best + len_next) <= (1 + len_post))
if (len_best + len_next <= 1 + len_post)
len_best = 1;
}
}
@@ -381,7 +381,7 @@ private byte[] BLZ_Code(byte[] raw_buffer, int raw_len, int best)
raw += len_best;
pak_buffer[flg] |= 1;
pak_buffer[pak++] = (byte)((byte)((len_best - (BLZ_THRESHOLD + 1)) << 4) | ((uint)(pos_best - 3) >> 8));
pak_buffer[pak++] = (byte)((pos_best - 3));
pak_buffer[pak++] = (byte)(pos_best - 3);
}
else
pak_buffer[pak++] = raw_buffer[raw++];
@@ -459,8 +459,8 @@ private byte[] BLZ_Code(byte[] raw_buffer, int raw_len, int best)
private class SearchPair
{
public int l;
public int p;
public readonly int l;
public readonly int p;
public SearchPair(int l, int p)
{
@@ -471,7 +471,7 @@ public SearchPair(int l, int p)
private SearchPair SEARCH(int p, IList<byte> raw_buffer, int raw, int raw_end)
{
int l = BLZ_THRESHOLD;
int max = (raw >= BLZ_N) ? BLZ_N : raw;
int max = raw >= BLZ_N ? BLZ_N : raw;
for (int pos = 3; pos <= max; pos++)
{
int len;
@@ -503,8 +503,8 @@ public BLZResult(byte[] raw_buffer, int raw_len)
length = raw_len;
}
public byte[] buffer;
public int length;
public readonly byte[] buffer;
public readonly int length;
}
private void BLZ_Invert(byte[] buffer, int offset, int length)
{

View File

@@ -39,7 +39,7 @@ internal static int IndexOfBytes(byte[] array, byte[] pattern, int startIndex, i
while (i++ != endIndex - 1)
{
if (array[i] != pattern[fidx]) i -= fidx;
fidx = (array[i] == pattern[fidx]) ? ++fidx : 0;
fidx = array[i] == pattern[fidx] ? ++fidx : 0;
if (fidx == pattern.Length)
return i - fidx + 1;
}
@@ -78,7 +78,7 @@ internal static string[] verifyCRR(string PATH_CRR, string PATH_CRO)
byte[] hash = hashCRO(ref data);
hashes[i] = getHexString(hash).ToUpper();
}
Array.Sort(hashes, String.Compare);
Array.Sort(hashes, string.Compare);
// Convert Hash Strings to Bytes
byte[][] hashData = new byte[hashes.Length][];
for (int i = 0; i < hashes.Length; i++)
@@ -91,7 +91,8 @@ internal static string[] verifyCRR(string PATH_CRR, string PATH_CRO)
// A little validation...
if (hashCount != hashData.Length)
throw new Exception(String.Format("Amount of input file-hashes does not equal the hash count in CRR. Expected {0}, got {1}.", hashCount, hashData.Length));
throw new Exception(
$"Amount of input file-hashes does not equal the hash count in CRR. Expected {hashCount}, got {hashData.Length}.");
string[] results = new string[hashData.Length];
// Store Hashes in CRR
@@ -119,7 +120,8 @@ internal static bool rehashCRR(string PATH_CRR, string PATH_CRO, bool saveCRO =
// A little validation...
if (hashCount != CROFiles.Length)
{
updateTB(TB_Progress, String.Format("Amount of input file-hashes does not equal the hash count in CRR. Expected {0}, got {1}.", hashCount, CROFiles.Length));
updateTB(TB_Progress,
$"Amount of input file-hashes does not equal the hash count in CRR. Expected {hashCount}, got {CROFiles.Length}.");
updateTB(TB_Progress, "Did not modify files. Aborting.");
return false;
}
@@ -149,7 +151,7 @@ internal static bool rehashCRR(string PATH_CRR, string PATH_CRO, bool saveCRO =
}
updateTB(TB_Progress, "Hashes computed, now sorting."); // Don't need to fiddle the ProgressBar because this should be quite quick.
string[] hashCopy = (string[])hashes.Clone(); // Store an unsorted list for later.
Array.Sort(hashes, String.Compare);
Array.Sort(hashes, string.Compare);
// Convert Hash Strings to Bytes
byte[][] hashData = new byte[hashes.Length][];
for (int i = 0; i < hashes.Length; i++)
@@ -167,7 +169,7 @@ internal static bool rehashCRR(string PATH_CRR, string PATH_CRO, bool saveCRO =
{
// CRO was updated.
string file = CROFiles[Array.IndexOf(hashCopy, hashes[i])];
updateTB(TB_Progress, String.Format("{0} hash has been updated.", Path.GetFileName(file)));
updateTB(TB_Progress, $"{Path.GetFileName(file)} hash has been updated.");
updatedCTR++;
}
}
@@ -177,7 +179,7 @@ internal static bool rehashCRR(string PATH_CRR, string PATH_CRO, bool saveCRO =
updateTB(TB_Progress,
updatedCTR > 0
? String.Format("{0} hashes have been updated.", updatedCTR)
? $"{updatedCTR} hashes have been updated."
: "CRR is fine. No modifications are necessary.");
// Save File

View File

@@ -30,9 +30,9 @@ public class CTR
return false;
// If ExeFS and RomFS are not built, build.
if (!(File.Exists(EXEFS_PATH)) && Directory.Exists(EXEFS_PATH))
if (!File.Exists(EXEFS_PATH) && Directory.Exists(EXEFS_PATH))
ExeFS.set(Directory.GetFiles(EXEFS_PATH), EXEFS_PATH = "exefs.bin");
if (!(File.Exists(ROMFS_PATH)) && Directory.Exists(ROMFS_PATH))
if (!File.Exists(ROMFS_PATH) && Directory.Exists(ROMFS_PATH))
RomFS.BuildRomFS(ROMFS_PATH, ROMFS_PATH = "romfs.bin", TB_Progress, PB_Show);
NCCH NCCH = setNCCH(EXEFS_PATH, ROMFS_PATH, EXHEADER_PATH, SERIAL_TEXT, LOGO_NAME, PB_Show, TB_Progress);
@@ -80,7 +80,7 @@ public class CTR
NCCH.header.ProductCode = Encoding.ASCII.GetBytes(TB_Serial);
Array.Resize(ref NCCH.header.ProductCode, 0x10);
NCCH.header.ExheaderHash = NCCH.exheader.GetSuperBlockHash();
NCCH.header.ExheaderSize = (uint)(NCCH.exheader.Data.Length);
NCCH.header.ExheaderSize = (uint)NCCH.exheader.Data.Length;
Len += NCCH.header.ExheaderSize + (uint)NCCH.exheader.AccessDescriptor.Length;
NCCH.header.Flags = new byte[0x8];
//FLAGS
@@ -92,7 +92,7 @@ public class CTR
NCCH.header.LogoOffset = (uint)(Len / MEDIA_UNIT_SIZE);
NCCH.header.LogoSize = (uint)(NCCH.logo.Length / MEDIA_UNIT_SIZE);
Len += (uint)NCCH.logo.Length;
NCCH.header.PlainRegionOffset = (uint)((NCCH.plainregion.Length > 0) ? Len / MEDIA_UNIT_SIZE : 0);
NCCH.header.PlainRegionOffset = (uint)(NCCH.plainregion.Length > 0 ? Len / MEDIA_UNIT_SIZE : 0);
NCCH.header.PlainRegionSize = (uint)NCCH.plainregion.Length / MEDIA_UNIT_SIZE;
Len += (uint)NCCH.plainregion.Length;
NCCH.header.ExefsOffset = (uint)(Len / MEDIA_UNIT_SIZE);
@@ -101,7 +101,7 @@ public class CTR
Len += (uint)NCCH.exefs.Data.Length;
Len = (uint)Align(Len, 0x1000); //Romfs Start is aligned to 0x1000
NCCH.header.RomfsOffset = (uint)(Len / MEDIA_UNIT_SIZE);
NCCH.header.RomfsSize = (uint)((new FileInfo(NCCH.romfs.FileName)).Length / MEDIA_UNIT_SIZE);
NCCH.header.RomfsSize = (uint)(new FileInfo(NCCH.romfs.FileName).Length / MEDIA_UNIT_SIZE);
NCCH.header.RomfsSuperBlockSize = NCCH.romfs.SuperBlockLen / MEDIA_UNIT_SIZE;
Len += NCCH.header.RomfsSize * MEDIA_UNIT_SIZE;
NCCH.header.ExefsHash = NCCH.exefs.SuperBlockHash;
@@ -164,7 +164,7 @@ public class CTR
}
NCSD.cardinfoheader = new NCSD.CardInfoHeader
{
WritableAddress = (uint)(NCSD.GetWritableAddress()),
WritableAddress = (uint)NCSD.GetWritableAddress(),
CardInfoBitmask = 0,
CIN = new NCSD.CardInfoHeader.CardInfoNotes
{
@@ -209,7 +209,7 @@ public class CTR
byte[] key = new byte[0x10]; //Fixed-Crypto key is all zero.
for (int i = 0; i < 3; i++)
{
AesCtr aesctr = new AesCtr(key, NCSD.NCCH_Array[0].header.ProgramId, ((ulong)(i + 1)) << 56); //CTR is ProgramID, section id<<88
AesCtr aesctr = new AesCtr(key, NCSD.NCCH_Array[0].header.ProgramId, (ulong)(i + 1) << 56); //CTR is ProgramID, section id<<88
switch (i)
{
case 0: //Exheader + AccessDesc
@@ -242,15 +242,15 @@ public class CTR
PB_Show.Value = 0;
PB_Show.Step = 1;
}));
for (ulong j = 0; j < (RomfsLen); j += BUFFER_SIZE)
for (ulong j = 0; j < RomfsLen; j += BUFFER_SIZE)
{
BUFFER_SIZE = (RomfsLen - j) > 0x400000 ? 0x400000 : (uint)(RomfsLen - j);
BUFFER_SIZE = RomfsLen - j > 0x400000 ? 0x400000 : (uint)(RomfsLen - j);
byte[] buf = new byte[BUFFER_SIZE];
byte[] outbuf = new byte[BUFFER_SIZE];
InFileStream.Read(buf, 0, (int)BUFFER_SIZE);
aesctr.TransformBlock(buf, 0, (int)BUFFER_SIZE, outbuf, 0);
OutFileStream.Write(outbuf, 0, (int)BUFFER_SIZE);
PB_Show.Invoke((Action)(PB_Show.PerformStep));
PB_Show.Invoke((Action)PB_Show.PerformStep);
}
}
break;
@@ -273,7 +273,7 @@ public class CTR
updateTB(TB_Progress, "Writing NCSD Padding...");
while ((ulong)OutFileStream.Position < TotalLen)
{
int BUFFER_LEN = ((TotalLen - (ulong)OutFileStream.Position) < 0x400000) ? (int)(TotalLen - (ulong)OutFileStream.Position) : 0x400000;
int BUFFER_LEN = TotalLen - (ulong)OutFileStream.Position < 0x400000 ? (int)(TotalLen - (ulong)OutFileStream.Position) : 0x400000;
OutFileStream.Write(Buffer, 0, BUFFER_LEN);
}
}
@@ -349,7 +349,7 @@ internal static ulong Align(ulong input, ulong alignsize)
ulong output = input;
if (output % alignsize != 0)
{
output += (alignsize - (output % alignsize));
output += alignsize - output % alignsize;
}
return output;
}

View File

@@ -29,7 +29,7 @@ public DARC(byte[] Data = null)
uint offs = 0;
for (int i = 0; i < root.DataLength; i++)
{
char c; string s = String.Empty;
char c; string s = string.Empty;
while ((c = (char) br.ReadUInt16()) > 0) s += c;
FileNameTable[i] = new NameTableEntry(offs, s);
@@ -57,14 +57,14 @@ public DARCHeader(BinaryReader br = null)
FileTableLength = br.ReadUInt32();
FileDataOffset = br.ReadUInt32();
}
public String Signature;
public string Signature;
public UInt16 Endianness;
public UInt16 HeaderSize;
public UInt32 Version;
public UInt32 FileSize;
public UInt32 FileTableOffset;
public UInt32 FileTableLength;
public UInt32 FileDataOffset;
public uint Version;
public uint FileSize;
public uint FileTableOffset;
public uint FileTableLength;
public uint FileDataOffset;
}
public class FileTableEntry
{
@@ -72,20 +72,20 @@ public FileTableEntry(BinaryReader br = null)
{
if (br == null) return;
NameOffset = br.ReadUInt32();
IsFolder = (NameOffset >> 24) == 1;
IsFolder = NameOffset >> 24 == 1;
NameOffset &= 0xFFFFFF;
DataOffset = br.ReadUInt32();
DataLength = br.ReadUInt32();
}
public UInt32 NameOffset;
public uint NameOffset;
public Boolean IsFolder;
public UInt32 DataOffset; // FOLDER: Parent Entry Index
public UInt32 DataLength; // FOLDER: Next Folder Index
public uint DataOffset; // FOLDER: Parent Entry Index
public uint DataLength; // FOLDER: Next Folder Index
}
public class NameTableEntry
{
public UInt32 NameOffset;
public String FileName;
public uint NameOffset;
public string FileName;
public NameTableEntry(uint offset, string fileName)
{
NameOffset = offset;
@@ -112,7 +112,7 @@ internal static byte[] setDARC(DARC darc)
// Write FileTableEntries
foreach (FileTableEntry entry in darc.Entries)
{
bw.Write(entry.NameOffset | ((entry.IsFolder) ? (uint)1 << 24 : 0));
bw.Write(entry.NameOffset | (entry.IsFolder ? (uint)1 << 24 : 0));
bw.Write(entry.DataOffset);
bw.Write(entry.DataLength);
}
@@ -187,7 +187,7 @@ internal static DARC getDARC(string folderName)
int darcFileCount = NameList.Count;
int NameListOffset = darcFileCount * 0xC;
int NameListLength = (int)(nameOffset + NameListOffset);
int DataOffset = (NameListLength % 4 == 0) ? NameListLength : NameListLength + (4 - NameListLength % 4);
int DataOffset = NameListLength % 4 == 0 ? NameListLength : NameListLength + (4 - NameListLength % 4);
Array.Resize(ref Data, Data.Length % 4 == 0 ? Data.Length : Data.Length + 4 - Data.Length % 4);
int FinalSize = DataOffset + Data.Length;

View File

@@ -6,6 +6,6 @@ namespace CTR
class ETC1
{
[DllImport("ETC1Lib.dll", EntryPoint = "ConvertETC1", CallingConvention = CallingConvention.Cdecl)]
public static extern void ConvertETC1(IntPtr dataOut, ref UInt32 dataOutSize, IntPtr dataIn, UInt16 width, UInt16 height, bool alpha);
public static extern void ConvertETC1(IntPtr dataOut, ref uint dataOutSize, IntPtr dataIn, UInt16 width, UInt16 height, bool alpha);
}
}

View File

@@ -16,7 +16,7 @@ public ExeFS(string EXEFS_PATH)
{
if (Directory.Exists(EXEFS_PATH))
{
var files = (new DirectoryInfo(EXEFS_PATH)).GetFiles().Select(f => f.FullName).ToArray();
var files = new DirectoryInfo(EXEFS_PATH).GetFiles().Select(f => f.FullName).ToArray();
setData(files);
}
else
@@ -78,7 +78,7 @@ internal static bool set(string[] files, string outFile)
uint size = (uint)fi.Length;
Array.Copy(BitConverter.GetBytes(offset), 0, headerData, 0x8 + i * 0x10, 0x4);
Array.Copy(BitConverter.GetBytes(size), 0, headerData, 0xC + i * 0x10, 0x4);
offset += (0x200 - size % 0x200) + size;
offset += 0x200 - size % 0x200 + size;
// Do the Bottom (Hashes)
byte[] hash = sha.ComputeHash(File.ReadAllBytes(files[i]));
@@ -122,7 +122,7 @@ public void setData(string[] files)
uint size = (uint)fi.Length;
Array.Copy(BitConverter.GetBytes(offset), 0, headerData, 0x8 + i * 0x10, 0x4);
Array.Copy(BitConverter.GetBytes(size), 0, headerData, 0xC + i * 0x10, 0x4);
offset += (0x200 - size % 0x200) + size;
offset += 0x200 - size % 0x200 + size;
// Do the Bottom (Hashes)
byte[] hash = sha.ComputeHash(File.ReadAllBytes(files[i]));

View File

@@ -55,15 +55,15 @@ public string GetSerial()
public bool isPokemon()
{
return (isORAS() || isXY());
return isORAS() || isXY();
}
public bool isORAS()
{
return (((TitleID & 0xFFFFFFFF) >> 8) == 0x11C5) || (((TitleID & 0xFFFFFFFF) >> 8) == 0x11C4);
return ((TitleID & 0xFFFFFFFF) >> 8 == 0x11C5) || ((TitleID & 0xFFFFFFFF) >> 8 == 0x11C4);
}
public bool isXY()
{
return (((TitleID & 0xFFFFFFFF) >> 8) == 0x55D) || (((TitleID & 0xFFFFFFFF) >> 8) == 0x55E);
return ((TitleID & 0xFFFFFFFF) >> 8 == 0x55D) || ((TitleID & 0xFFFFFFFF) >> 8 == 0x55E);
}
public string GetPokemonSerial()
{

View File

@@ -80,7 +80,7 @@ internal static bool GuessMini(BinaryReader br, out string ext)
// Return BaseStream position to the start.
br.BaseStream.Position = position;
return (ext.Length > 0);
return ext.Length > 0;
}
internal static bool GuessHeaderedDARC(BinaryReader br, out string ext)
{
@@ -102,7 +102,7 @@ internal static bool GuessHeaderedDARC(BinaryReader br, out string ext)
// Return BaseStream position to the start.
br.BaseStream.Position = position;
return (ext.Length > 0);
return ext.Length > 0;
}
internal static bool GuessBCLIM(BinaryReader br, out string ext)
{
@@ -122,7 +122,7 @@ internal static bool GuessBCLIM(BinaryReader br, out string ext)
// Return BaseStream position to the start.
br.BaseStream.Position = position;
return (ext.Length > 0);
return ext.Length > 0;
}
internal static bool GuessLZ11(BinaryReader br, out string ext)
{
@@ -136,13 +136,13 @@ internal static bool GuessLZ11(BinaryReader br, out string ext)
byte[] sizeBytes = new byte[3];
br.Read(sizeBytes, 0, 3);
int decompressedSize = (sizeBytes[0] | sizeBytes[1] << 8 | sizeBytes[2]);
int decompressedSize = sizeBytes[0] | sizeBytes[1] << 8 | sizeBytes[2];
if (decompressedSize > br.BaseStream.Length && decompressedSize < br.BaseStream.Length * 10) // assuming 10x compression isn't feasible
ext = "lz"; // really weak LZ detection, at most 16MB
}
catch { }
br.BaseStream.Position = position;
return (ext.Length > 0);
return ext.Length > 0;
}
internal static bool Guess4CHAR(BinaryReader br, out string ext)
{

View File

@@ -29,16 +29,16 @@ internal static bool garcPackMS(string folderPath, string garcPath, ProgressBar
{
string fn = Path.GetFileNameWithoutExtension(f);
int compressed = fn.IndexOf("dec_", StringComparison.Ordinal);
int fileNumber = (compressed < 0)
? Int32.Parse(fn)
: Int32.Parse(fn.Substring(compressed + 4));
int fileNumber = compressed < 0
? int.Parse(fn)
: int.Parse(fn.Substring(compressed + 4));
packOrder[fileNumber] = f;
filectr++;
}
foreach (string f in folders)
{
packOrder[Int32.Parse(new DirectoryInfo(f).Name)] = f;
packOrder[int.Parse(new DirectoryInfo(f).Name)] = f;
filectr += Directory.GetFiles(f).Length;
}
}
@@ -92,9 +92,9 @@ internal static bool garcPackMS(string folderPath, string garcPath, ProgressBar
string fn = Path.GetFileNameWithoutExtension(packOrder[i]);
int compressed = fn.IndexOf("dec_", StringComparison.Ordinal);
int fileNumber = (compressed < 0)
? Int32.Parse(fn)
: Int32.Parse(fn.Substring(compressed + 4));
int fileNumber = compressed < 0
? int.Parse(fn)
: int.Parse(fn.Substring(compressed + 4));
if (compressed >= 0)
{
@@ -108,7 +108,7 @@ internal static bool garcPackMS(string folderPath, string garcPath, ProgressBar
// Assemble Entry
FileInfo fi = new FileInfo(packOrder[i]);
int actualLength = (int)((fi.Length % 4 == 0) ? fi.Length : fi.Length + 4 - (fi.Length % 4));
int actualLength = (int)(fi.Length % 4 == 0 ? fi.Length : fi.Length + 4 - fi.Length % 4);
garc.fatb.Entries[i].SubEntries[0].Start = od;
garc.fatb.Entries[i].SubEntries[0].End = actualLength + garc.fatb.Entries[i].SubEntries[0].Start;
garc.fatb.Entries[i].SubEntries[0].Length = (int)fi.Length;
@@ -119,7 +119,7 @@ internal static bool garcPackMS(string folderPath, string garcPath, ProgressBar
if (pBar1.InvokeRequired)
pBar1.Invoke((MethodInvoker)(() => pBar1.PerformStep()));
else { pBar1.PerformStep(); }
string update = String.Format("{0:P2} - {1}/{2} - {3}", ((float)index) / ((float)filectr), index, filectr, packOrder[i]);
string update = $"{(float) index/(float) filectr:P2} - {index}/{filectr} - {packOrder[i]}";
index++;
if (label.InvokeRequired)
label.Invoke((MethodInvoker)delegate { label.Text = update; });
@@ -135,9 +135,9 @@ internal static bool garcPackMS(string folderPath, string garcPath, ProgressBar
string s = f;
string fn = Path.GetFileNameWithoutExtension(f);
int compressed = fn.IndexOf("dec_", StringComparison.Ordinal);
int fileNumber = (compressed < 0)
? Int32.Parse(fn)
: Int32.Parse(fn.Substring(compressed + 4));
int fileNumber = compressed < 0
? int.Parse(fn)
: int.Parse(fn.Substring(compressed + 4));
garc.fatb.Entries[i].SubEntries[fileNumber].Exists = true;
if (compressed >= 0)
@@ -151,7 +151,7 @@ internal static bool garcPackMS(string folderPath, string garcPath, ProgressBar
// Assemble Entry
FileInfo fi = new FileInfo(s);
int actualLength = (int)((fi.Length % 4 == 0) ? fi.Length : fi.Length + 4 - (fi.Length % 4));
int actualLength = (int)(fi.Length % 4 == 0 ? fi.Length : fi.Length + 4 - fi.Length % 4);
garc.fatb.Entries[i].SubEntries[fileNumber].Start = od;
garc.fatb.Entries[i].SubEntries[fileNumber].End = actualLength + garc.fatb.Entries[i].SubEntries[fileNumber].Start;
garc.fatb.Entries[i].SubEntries[fileNumber].Length = (int)fi.Length;
@@ -162,7 +162,7 @@ internal static bool garcPackMS(string folderPath, string garcPath, ProgressBar
if (pBar1.InvokeRequired)
pBar1.Invoke((MethodInvoker)(() => pBar1.PerformStep()));
else { pBar1.PerformStep(); }
string update = String.Format("{0:P2} - {1}/{2} - {3}", ((float)index) / ((float)filectr), index, filectr, f);
string update = $"{(float) index/(float) filectr:P2} - {index}/{filectr} - {f}";
index++;
if (label.InvokeRequired)
label.Invoke((MethodInvoker)delegate { label.Text = update; });
@@ -172,7 +172,7 @@ internal static bool garcPackMS(string folderPath, string garcPath, ProgressBar
}
garc.fatb.Entries[i].Vector = (uint)v;
}
garc.fatb.HeaderSize = (0xC + op);
garc.fatb.HeaderSize = 0xC + op;
}
#endregion
@@ -358,7 +358,7 @@ internal static bool garcUnpack(string garcPath, string outPath, bool skipDecomp
if (pBar1.InvokeRequired) pBar1.Invoke((MethodInvoker)(() => pBar1.PerformStep()));
else pBar1.PerformStep();
string update = String.Format("{0:P2} - {1}/{2}", (filectr) / (fileCount), filectr, fileCount);
string update = $"{filectr/fileCount:P2} - {filectr}/{fileCount}";
if (label.InvokeRequired)
label.Invoke((MethodInvoker)delegate { label.Text = update; });
else { label.Text = update; }
@@ -443,13 +443,13 @@ internal static GARCFile unpackGARC(string path)
public struct GARCFile
{
public Char[] Magic; // Always GARC = 0x4E415243
public UInt32 HeaderSize; // Always 0x001C
public uint HeaderSize; // Always 0x001C
public UInt16 Endianess; // 0xFFFE
public UInt16 ChunkCount; // Always 0x0400 chunk count
public UInt32 DataOffset;
public UInt32 FileSize;
public UInt32 LastSize;
public uint DataOffset;
public uint FileSize;
public uint LastSize;
public FATO fato;
public FATB fatb;
@@ -459,7 +459,7 @@ public struct GARCFile
public struct FATO
{
public Char[] Magic;
public Int32 HeaderSize;
public int HeaderSize;
public UInt16 EntryCount;
public UInt16 Padding;
@@ -467,36 +467,36 @@ public struct FATO
}
public struct FATO_Entry
{
public Int32 Offset;
public int Offset;
}
public struct FATB
{
public Char[] Magic;
public Int32 HeaderSize;
public Int32 FileCount;
public int HeaderSize;
public int FileCount;
public FATB_Entry[] Entries;
}
public struct FATB_Entry
{
public UInt32 Vector;
public uint Vector;
public Boolean IsFolder;
public FATB_SubEntry[] SubEntries;
}
public struct FATB_SubEntry
{
public Boolean Exists;
public Int32 Start;
public Int32 End;
public Int32 Length;
public int Start;
public int End;
public int Length;
}
public struct FIMG
{
public Char[] Magic;
public Int32 HeaderSize;
public Int32 DataSize;
public int HeaderSize;
public int DataSize;
}
}
#endregion

View File

@@ -325,7 +325,7 @@ internal unsafe static int Compress(Stream instream, long inLength, Stream outst
// length not 3 or more? next byte is raw data
if (length < 3)
{
outbuffer[bufferlength++] = *(instart + (readBytes++));
outbuffer[bufferlength++] = *(instart + readBytes++);
}
else
{
@@ -434,7 +434,7 @@ internal unsafe static int CompressWithLA(Stream instream, long inLength, Stream
if (lengths[readBytes] == 1)
{
outbuffer[bufferlength++] = *(instart + (readBytes++));
outbuffer[bufferlength++] = *(instart + readBytes++);
}
else
{
@@ -579,8 +579,8 @@ public InputTooLargeException()
/// </summary>
public class NotEnoughDataException : IOException
{
private long currentOutSize;
private long totalOutSize;
private readonly long currentOutSize;
private readonly long totalOutSize;
/// <summary>
/// Gets the actual number of written bytes.
/// </summary>
@@ -597,7 +597,7 @@ public class NotEnoughDataException : IOException
/// <param name="totalOutSize">The desired number of written bytes.</param>
public NotEnoughDataException(long currentOutSize, long totalOutSize)
: base("Not enough data availble; 0x" + currentOutSize.ToString("X")
+ " of " + (totalOutSize < 0 ? "???" : ("0x" + totalOutSize.ToString("X")))
+ " of " + (totalOutSize < 0 ? "???" : "0x" + totalOutSize.ToString("X"))
+ " bytes written.")
{
this.currentOutSize = currentOutSize;

View File

@@ -58,8 +58,8 @@ public ulong GetWritableAddress()
{
const ulong MEDIA_UNIT_SIZE = 0x200;
return Card2
? (Align(header.OffsetSizeTable[NCCH_Array.Count - 1].Offset * NCCH.MEDIA_UNIT_SIZE
+ header.OffsetSizeTable[NCCH_Array.Count - 1].Size * NCCH.MEDIA_UNIT_SIZE + 0x1000, 0x10000) / MEDIA_UNIT_SIZE)
? Align(header.OffsetSizeTable[NCCH_Array.Count - 1].Offset * NCCH.MEDIA_UNIT_SIZE
+ header.OffsetSizeTable[NCCH_Array.Count - 1].Size * NCCH.MEDIA_UNIT_SIZE + 0x1000, 0x10000) / MEDIA_UNIT_SIZE
: 0x00000000FFFFFFFF;
}
public void BuildHeader()
@@ -102,7 +102,7 @@ internal static ulong Align(ulong input, ulong alignsize)
ulong output = input;
if (output % alignsize != 0)
{
output += (alignsize - (output % alignsize));
output += alignsize - output % alignsize;
}
return output;
}

View File

@@ -25,7 +25,7 @@ public RomFS(string fn)
uint mhlen = (uint)(fs.ReadByte() | (fs.ReadByte() << 8) | (fs.ReadByte() << 16) | (fs.ReadByte() << 24));
SuperBlockLen = mhlen + 0x50;
if (SuperBlockLen % 0x200 != 0)
SuperBlockLen += (0x200 - (SuperBlockLen % 0x200));
SuperBlockLen += 0x200 - SuperBlockLen % 0x200;
byte[] superblock = new byte[SuperBlockLen];
fs.Seek(0, SeekOrigin.Begin);
fs.Read(superblock, 0, superblock.Length);
@@ -101,7 +101,7 @@ internal static ulong Align(ulong input, ulong alignsize)
ulong output = input;
if (output % alignsize != 0)
{
output += (alignsize - (output % alignsize));
output += alignsize - output % alignsize;
}
return output;
}
@@ -114,9 +114,9 @@ internal static void MakeRomFSData(RomfsFile[] RomFiles, MemoryStream metadata,
ivfc.Levels[i] = new IVFCLevel { BlockSize = 0x1000 };
}
ivfc.Levels[2].DataLength = RomfsFile.GetDataBlockLength(RomFiles, (ulong)metadata.Length);
ivfc.Levels[1].DataLength = (Align(ivfc.Levels[2].DataLength, ivfc.Levels[2].BlockSize) / ivfc.Levels[2].BlockSize) * 0x20; //0x20 per SHA256 hash
ivfc.Levels[0].DataLength = (Align(ivfc.Levels[1].DataLength, ivfc.Levels[1].BlockSize) / ivfc.Levels[1].BlockSize) * 0x20; //0x20 per SHA256 hash
ulong MasterHashLen = (Align(ivfc.Levels[0].DataLength, ivfc.Levels[0].BlockSize) / ivfc.Levels[0].BlockSize) * 0x20;
ivfc.Levels[1].DataLength = Align(ivfc.Levels[2].DataLength, ivfc.Levels[2].BlockSize) / ivfc.Levels[2].BlockSize * 0x20; //0x20 per SHA256 hash
ivfc.Levels[0].DataLength = Align(ivfc.Levels[1].DataLength, ivfc.Levels[1].BlockSize) / ivfc.Levels[1].BlockSize * 0x20; //0x20 per SHA256 hash
ulong MasterHashLen = Align(ivfc.Levels[0].DataLength, ivfc.Levels[0].BlockSize) / ivfc.Levels[0].BlockSize * 0x20;
ulong lofs = 0;
foreach (IVFCLevel t in ivfc.Levels)
{
@@ -139,7 +139,7 @@ internal static void MakeRomFSData(RomfsFile[] RomFiles, MemoryStream metadata,
{
OutFileStream.Write(BitConverter.GetBytes(t.HashOffset), 0, 0x8);
OutFileStream.Write(BitConverter.GetBytes(t.DataLength), 0, 0x8);
OutFileStream.Write(BitConverter.GetBytes((int)(Math.Log(t.BlockSize, 2))), 0, 0x4);
OutFileStream.Write(BitConverter.GetBytes((int)Math.Log(t.BlockSize, 2)), 0, 0x4);
OutFileStream.Write(BitConverter.GetBytes(RESERVED), 0, 0x4);
}
OutFileStream.Write(BitConverter.GetBytes(HeaderLen), 0, 0x4);
@@ -316,7 +316,7 @@ internal static void CalcRomfsSize(Romfs_MetaData MetaData)
MetaData.M_DirHashTableEntry = GetHashTableEntryCount(MetaData.DirNum);
MetaData.M_FileHashTableEntry = GetHashTableEntryCount(MetaData.FileNum);
uint MetaDataSize = (uint)Align((0x28 + MetaData.M_DirHashTableEntry * 4 + MetaData.M_DirTableLen + MetaData.M_FileHashTableEntry * 4 + MetaData.M_FileTableLen), PADDING_ALIGN);
uint MetaDataSize = (uint)Align(0x28 + MetaData.M_DirHashTableEntry * 4 + MetaData.M_DirTableLen + MetaData.M_FileHashTableEntry * 4 + MetaData.M_FileTableLen, PADDING_ALIGN);
for (int i = 0; i < MetaData.M_DirHashTableEntry; i++)
MetaData.DirHashTable.Add(ROMFS_UNUSED_ENTRY);
@@ -407,7 +407,7 @@ internal static void AddDirHashKey(Romfs_MetaData MetaData, int index)
{
uint parent = MetaData.DirTable.DirectoryTable[index].ParentOffset;
string Name = MetaData.DirTable.DirectoryTable[index].Name;
byte[] NArr = (index == 0) ? Encoding.Unicode.GetBytes("") : Encoding.Unicode.GetBytes(Name);
byte[] NArr = index == 0 ? Encoding.Unicode.GetBytes("") : Encoding.Unicode.GetBytes(Name);
uint hash = CalcPathHash(parent, NArr, 0, NArr.Length);
int ind2 = (int)(hash % MetaData.M_DirHashTableEntry);
if (MetaData.DirHashTable[ind2] == ROMFS_UNUSED_ENTRY)
@@ -466,7 +466,7 @@ internal static uint CalcPathHash(uint ParentOffset, byte[] NameArray, int start
for (int i = 0; i < NameArray.Length; i += 2)
{
hash = (hash >> 5) | (hash << 27);
hash ^= (ushort)((NameArray[start + i]) | (NameArray[start + i + 1] << 8));
hash ^= (ushort)(NameArray[start + i] | (NameArray[start + i + 1] << 8));
}
return hash;
}
@@ -487,10 +487,10 @@ internal static void AddDir(Romfs_MetaData MetaData, DirectoryInfo Dir, uint par
Entry.ChildOffset = Entry.HashKeyPointer = Entry.FileOffset = ROMFS_UNUSED_ENTRY;
Entry.SiblingOffset = sibling;
Entry.FullName = Dir.FullName;
Entry.Name = (Entry.FullName == ROOT_DIR) ? "" : Dir.Name;
Entry.Name = Entry.FullName == ROOT_DIR ? "" : Dir.Name;
Entry.Offset = CurrentDir;
MetaData.DirTable.DirectoryTable.Add(Entry);
MetaData.DirTableLen += (CurrentDir == 0) ? 0x18 : 0x18 + (uint)Align((ulong)Dir.Name.Length * 2, 4);
MetaData.DirTableLen += CurrentDir == 0 ? 0x18 : 0x18 + (uint)Align((ulong)Dir.Name.Length * 2, 4);
// int ParentIndex = GetRomfsDirEntry(MetaData, Dir.FullName);
// uint poff = MetaData.DirTable.DirectoryTable[ParentIndex].Offset;
}
@@ -610,7 +610,7 @@ internal static void WriteMetaDataToStream(Romfs_MetaData MetaData, MemoryStream
//Padding
while (stream.Position % PADDING_ALIGN != 0)
stream.Write(new byte[PADDING_ALIGN - (stream.Position % 0x10)], 0, (int)(PADDING_ALIGN - (stream.Position % 0x10)));
stream.Write(new byte[PADDING_ALIGN - stream.Position % 0x10], 0, (int)(PADDING_ALIGN - stream.Position % 0x10));
//All Done.
}
@@ -718,7 +718,7 @@ public class RomfsFile
public static ulong GetDataBlockLength(RomfsFile[] files, ulong PreData)
{
return (files.Length == 0) ? PreData : PreData + files[files.Length - 1].Offset + files[files.Length - 1].Size;
return files.Length == 0 ? PreData : PreData + files[files.Length - 1].Offset + files[files.Length - 1].Size;
}
}
public class IVFCInfo
@@ -784,7 +784,7 @@ public static ulong Align(ulong input, ulong alignsize)
{
ulong output = input;
if (output % alignsize != 0)
output += (alignsize - (output % alignsize));
output += alignsize - output % alignsize;
return output;
}

View File

@@ -63,9 +63,9 @@ public byte[] Write()
// Thanks to Gericom for EveryFileExplorer's SMDH.cs as a basis for the object code (and AppSettings enumeration)
class ApplicationInfo
{
public String ShortDescription; //0x80
public String LongDescription; //0x100
public String Publisher; //0x80
public string ShortDescription; //0x80
public string LongDescription; //0x100
public string Publisher; //0x80
public ApplicationInfo(BinaryReader br)
{
ShortDescription = Encoding.Unicode.GetString(br.ReadBytes(0x80)).TrimEnd('\0');
@@ -84,13 +84,13 @@ class ApplicationSettings
{
public byte[] GameRatings; //0x10
public RegionLockoutFlags RegionLockout;
public UInt32 MatchMakerID;
public uint MatchMakerID;
public UInt64 MatchMakerBITID;
public AppSettingsFlags Flags;
public UInt16 EULAVersion;
public UInt16 Reserved;
public Single AnimationDefaultFrame;
public UInt32 StreetPassID;
public uint StreetPassID;
public enum RegionLockoutFlags : uint
{

View File

@@ -19,7 +19,7 @@ internal static byte[] adjustMiniHeader(byte[] data, int headerLength)
if (headerLength < dataStart)
throw new Exception("Specified Header length is too small!?");
byte[] pack = data.Skip(dataStart).ToArray(); // pull out payload
byte[] newData = (new byte[headerLength].Concat(pack).ToArray()); // append payload onto new header
byte[] newData = new byte[headerLength].Concat(pack).ToArray(); // append payload onto new header
Array.Copy(data, 0, newData, 0, dataStart); // copy in old header (then repoint)
int diff = headerLength - dataStart; // shift pointer
@@ -242,7 +242,7 @@ internal static string getIsMini(string path)
}
offsets[offsets.Length - 1] = length;
return (fi.Length == length) ? fx : null;
return fi.Length == length ? fx : null;
}
catch { return null; }
}

View File

@@ -9,7 +9,7 @@ namespace pk3DS
public class ARC
{
// Multi Type Archive Handling
internal static Boolean onefile = true;
internal static bool onefile = true;
internal static SARC analyzeSARC(string path)
{
SARC sarc = new SARC
@@ -188,7 +188,7 @@ internal static DARC analyze(string path)
using (BinaryReader br = new BinaryReader(File.OpenRead(path))) {
long len = br.BaseStream.Length;
darc.Magic = br.ReadUInt32();
UInt32 m = darc.Magic;
uint m = darc.Magic;
darc.HeaderOffset = 0;
while (m != 0x63726164 && darc.HeaderOffset < len - 4)
{
@@ -263,7 +263,7 @@ internal static FARC analyzeFARC(string path)
BinaryReader br = new BinaryReader(File.OpenRead(path));
long len = br.BaseStream.Length;
farc.Magic = br.ReadUInt32();
UInt32 m = farc.Magic;
uint m = farc.Magic;
farc.HeaderOffset = 0;
while (m != 0x43524146 && farc.HeaderOffset < len - 4) //FARC
{
@@ -563,7 +563,7 @@ internal static void repackDARC(string path, string fileName, string outfolder =
if (data.SequenceEqual(donorBytes.Take(data.Length)))
{
int headerLen = data.Length + BitConverter.ToInt32(donorBytes, data.Length)*0x20;
headerLen += (0x80 - headerLen%0x80);
headerLen += 0x80 - headerLen%0x80;
data = donorBytes.Take(headerLen).ToArray();
}
else
@@ -619,7 +619,7 @@ internal static string ParseShuffleText(string path)
for (int i = 0; i < st.StringCount; i++)
{
br.BaseStream.Seek(st.offsets[i], SeekOrigin.Begin);
uint len = (i < st.StringCount - 1)
uint len = i < st.StringCount - 1
? st.offsets[i + 1] - st.offsets[i]
: StringDataLen + 0x40 - st.offsets[i];
byte[] data = br.ReadBytes((int)len);
@@ -638,15 +638,15 @@ internal static string ParseShuffleText(string path)
public struct FARC
{
public UInt32 Magic;
public UInt32 SirMagic;
public UInt32 SirOffset;
public UInt32 HeaderOffset;
public UInt32 MetaPointer; //from start of file
public UInt32 NamesOffset;
public UInt32 TableOffset; //from start of file
public UInt32 DataOffset; //from start of file
public UInt32 FileCount;
public uint Magic;
public uint SirMagic;
public uint SirOffset;
public uint HeaderOffset;
public uint MetaPointer; //from start of file
public uint NamesOffset;
public uint TableOffset; //from start of file
public uint DataOffset; //from start of file
public uint FileCount;
public FARCFileTable Files;
public string FileName;
@@ -734,7 +734,7 @@ public class ShuffleText
public uint StringMetaLen;
public uint StringCount;
public List<uint> offsets;
public List<String> strings;
public List<string> strings;
public string FileName;
public string FilePath;
@@ -774,16 +774,16 @@ public class GARFile
public struct DARC
{
public UInt32 HeaderOffset; // Where is header in file?
public uint HeaderOffset; // Where is header in file?
public UInt32 Magic; // 0x64617263 "darc"
public uint Magic; // 0x64617263 "darc"
public UInt16 BOM; // 0xFFFE
public UInt16 HeaderLength; // HeaderLength - 0x1C
public UInt32 Unknown; // 0x10000000
public UInt32 totalLength; // Total Length of file
public UInt32 TableOffset; // Offset from Start of File
public UInt32 TableLength; // Table Length
public UInt32 DataOffset; // Data Offset
public uint Unknown; // 0x10000000
public uint totalLength; // Total Length of file
public uint TableOffset; // Offset from Start of File
public uint TableLength; // Table Length
public uint DataOffset; // Data Offset
public FileTable Files;
@@ -811,11 +811,11 @@ public struct DarcFile
public class CRC16
{
private const ushort polynomial = 0xA001;
private ushort[] table = new ushort[256];
private readonly ushort[] table = new ushort[256];
public ushort ComputeChecksum(byte[] bytes)
{
return bytes.Aggregate<byte, ushort>(0, (current, t) => (ushort) ((current >> 8) ^ table[(current ^ t)]));
return bytes.Aggregate<byte, ushort>(0, (current, t) => (ushort) ((current >> 8) ^ table[current ^ t]));
}
public byte[] ComputeChecksumBytes(byte[] bytes)

View File

@@ -64,18 +64,18 @@ public Main()
if (path.Length > 0) openQuick(path);
}
string filename = Path.GetFileNameWithoutExtension(System.Diagnostics.Process.GetCurrentProcess().MainModule.FileName);
skipBoth = (filename.IndexOf("3DSkip", StringComparison.Ordinal) >= 0);
skipBoth = filename.IndexOf("3DSkip", StringComparison.Ordinal) >= 0;
}
public static bool oras;
public static string RomFSPath;
public static string ExeFSPath;
public static string ExHeaderPath;
public volatile int threads;
internal volatile static int Language;
internal static volatile int Language;
internal static CTR.SMDH SMDH;
private uint HANSgameID; // for exporting RomFS/ExeFS with correct X8 gameID
internal static string[] allGARCs = { "gametext", "storytext", "personal", "trpoke", "trdata", "evolution", "megaevo", "levelup", "eggmove", "item", "move", "maisonpkS", "maisontrS", "maisonpkN", "maisontrN", "titlescreen", "mapMatrix", "mapGR" };
private bool skipBoth;
private readonly bool skipBoth;
internal static PersonalInfo[] SpeciesStat;
// Main Form Methods
@@ -87,8 +87,8 @@ private void L_GARCInfo_Click(object sender, EventArgs e)
{
if (RomFSPath != null)
{
string s = "Game Type: " + ((oras) ? "ORAS" : "XY") + Environment.NewLine;
s = allGARCs.Aggregate(s, (current, t) => current + String.Format(Environment.NewLine + "{0} - {1}", t, getGARCFileName(t)));
string s = "Game Type: " + (oras ? "ORAS" : "XY") + Environment.NewLine;
s = allGARCs.Aggregate(s, (current, t) => current + string.Format(Environment.NewLine + "{0} - {1}", t, getGARCFileName(t)));
if (DialogResult.Yes != Util.Prompt(MessageBoxButtons.YesNo, s, "Copy to Clipboard?")) return;
@@ -122,13 +122,13 @@ private void changeLanguage(object sender, EventArgs e)
// Let all other operations finish first (ie, if the user quickly switches languages on load)
while (threads > 0) Thread.Sleep(50);
// Gather the Text Language Strings
updateStatus(String.Format("GARC Get: {0} @ {1}... ", "gametext", getGARCFileName("gametext")));
updateStatus($"GARC Get: {"gametext"} @ {getGARCFileName("gametext")}... ");
threadGet(RomFSPath + getGARCFileName("gametext"), "gametext", true, true);
while (threads > 0) Thread.Sleep(50);
if (!Directory.Exists("personal"))
{
updateStatus(String.Format("GARC Get: {0} @ {1}... ", "personal", getGARCFileName("personal")));
updateStatus($"GARC Get: {"personal"} @ {getGARCFileName("personal")}... ");
threadGet(RomFSPath + getGARCFileName("personal"), "personal", true, true);
}
while (threads > 0) Thread.Sleep(50);
@@ -151,13 +151,13 @@ private void formClosing(object sender, FormClosingEventArgs e)
if (!GB_RomFS.Enabled || skipBoth) return; // No data/threads need to be addressed if we haven't loaded anything.
// Set the GameText back as other forms may have edited it.
updateStatus(String.Format("GARC Get: {0} @ {1}... ", "gametext", getGARCFileName("gametext")));
updateStatus($"GARC Get: {"gametext"} @ {getGARCFileName("gametext")}... ");
threadSet(RomFSPath + getGARCFileName("gametext"), "gametext", false);
while (threads > 0) Thread.Sleep(100);
Thread.Sleep(200); // Small gap between beeps for faster computers.
updateStatus(String.Format("GARC Get: {0} @ {1}... ", "personal", getGARCFileName("personal")));
updateStatus($"GARC Get: {"personal"} @ {getGARCFileName("personal")}... ");
threadSet(RomFSPath + getGARCFileName("personal"), "personal", false);
while (threads > 0) Thread.Sleep(100);
@@ -208,14 +208,14 @@ private void openQuick(string path)
Util.Alert("pk3DS will function best if you keep your Game Files folder clean and free of unnecessary folders.");
// Enable buttons if applicable
GB_RomFS.Enabled = Menu_Restore.Enabled = GB_CRO.Enabled = Menu_CRO.Enabled = Menu_Shuffler.Enabled = (RomFSPath != null);
GB_ExeFS.Enabled = (RomFSPath != null && ExeFSPath != null);
GB_RomFS.Enabled = Menu_Restore.Enabled = GB_CRO.Enabled = Menu_CRO.Enabled = Menu_Shuffler.Enabled = RomFSPath != null;
GB_ExeFS.Enabled = RomFSPath != null && ExeFSPath != null;
B_MoveTutor.Enabled = oras; // Default false unless loaded
if (RomFSPath != null)
{
if (L_Game.Text == "Game Loaded: ORAS" || L_Game.Text == "Game Loaded: XY")
{ Directory.Delete("personal", true); } // Force reloading of personal data if the game is switched.
L_Game.Text = (oras) ? "Game Loaded: ORAS" : "Game Loaded: XY"; TB_Path.Text = path;
L_Game.Text = oras ? "Game Loaded: ORAS" : "Game Loaded: XY"; TB_Path.Text = path;
}
else if (ExeFSPath != null)
{ L_Game.Text = "ExeFS loaded - no RomFS"; TB_Path.Text = path; }
@@ -236,12 +236,12 @@ private void openQuick(string path)
Menu_RomFS.Enabled = Menu_Restore.Enabled = Menu_GARCs.Enabled = RomFSPath != null;
Menu_Patch.Enabled = RomFSPath != null && ExeFSPath != null;
Menu_3DS.Enabled =
(ExHeaderPath != null && RomFSPath != null && ExeFSPath != null);
ExHeaderPath != null && RomFSPath != null && ExeFSPath != null;
// Change L_Game if RomFS and ExeFS exists to a better descriptor
SMDH = ExeFSPath != null ? (File.Exists(Path.Combine(ExeFSPath, "icon.bin"))) ? new CTR.SMDH(Path.Combine(ExeFSPath, "icon.bin")) : null : null;
HANSgameID = SMDH != null ? ((SMDH.AppSettings != null) ? SMDH.AppSettings.StreetPassID : 0) : 0;
L_Game.Visible = (SMDH == null && RomFSPath != null);
SMDH = ExeFSPath != null ? File.Exists(Path.Combine(ExeFSPath, "icon.bin")) ? new CTR.SMDH(Path.Combine(ExeFSPath, "icon.bin")) : null : null;
HANSgameID = SMDH != null ? (SMDH.AppSettings?.StreetPassID ?? 0) : 0;
L_Game.Visible = SMDH == null && RomFSPath != null;
updateGameInfo();
TB_Path.Select(TB_Path.TextLength, 0);
// Method finished.
@@ -260,9 +260,9 @@ private void updateGameInfo()
// 6 - XX
// 7 - KO
int[] AILang = { 0, 0, 1, 2, 4, 3, 5, 7 };
Text = ((SMDH == null || SMDH.AppSettings == null)
Text = SMDH?.AppSettings == null
? "pk3DS" // nothing else
: "pk3DS - " + SMDH.AppInfo[AILang[Language]].ShortDescription);
: "pk3DS - " + SMDH.AppInfo[AILang[Language]].ShortDescription;
}
private int checkGameType(string[] files)
{
@@ -285,7 +285,7 @@ private int checkGameType(string[] files)
private bool checkIfRomFS(string path)
{
string[] top = Directory.GetDirectories(path);
FileInfo fi = new FileInfo(top[(top.Length > 1) ? 1 : 0]);
FileInfo fi = new FileInfo(top[top.Length > 1 ? 1 : 0]);
// Check to see if the folder is romfs
if (fi.Name == "a")
{
@@ -298,7 +298,7 @@ private bool checkIfRomFS(string path)
else { RomFSPath = null; oras = false; return false; }
}
else
oras = (game == 1);
oras = game == 1;
RomFSPath = path;
backupGARCs(false, allGARCs);
backupCROs(false, RomFSPath);
@@ -345,7 +345,7 @@ private bool checkIfExHeader(string path)
ExHeaderPath = null;
// Input folder path should contain the ExHeader.
string[] files = Directory.GetFiles(path);
foreach (string fp in (from s in files let f = new FileInfo(s) where (f.Name.ToLower().StartsWith("exh") && f.Length == 0x800) select s))
foreach (string fp in from s in files let f = new FileInfo(s) where f.Name.ToLower().StartsWith("exh") && f.Length == 0x800 select s)
ExHeaderPath = fp;
return ExHeaderPath != null;
@@ -370,7 +370,7 @@ private void rebuildRomFS(object sender, EventArgs e)
SaveFileDialog sfd = new SaveFileDialog
{
FileName = (HANSgameID != 0) ? HANSgameID.ToString("X8") + ".romfs" : "romfs.bin",
FileName = HANSgameID != 0 ? HANSgameID.ToString("X8") + ".romfs" : "romfs.bin",
Filter = "HANS RomFS|*.romfs" + "|Binary File|*.bin" + "|All Files|*.*"
};
sfd.FilterIndex = HANSgameID != 0 ? 0 : sfd.Filter.Length - 1;
@@ -420,8 +420,8 @@ private void B_Maison_Click(object sender, EventArgs e)
new Thread(() =>
{
bool super = (dr == DialogResult.Yes);
string[] files = { (super) ? "maisontrS" : "maisontrN", (super) ? "maisonpkS" : "maisonpkN" };
bool super = dr == DialogResult.Yes;
string[] files = { super ? "maisontrS" : "maisontrN", super ? "maisonpkS" : "maisonpkN" };
fileGet(files);
Invoke((Action)(() => new MaisonEditor(super).ShowDialog()));
fileSet(files);
@@ -574,7 +574,7 @@ private void fileGet(string[] files, bool skipDecompression = true, bool skipGet
foreach (string toEdit in files)
{
string GARC = getGARCFileName(toEdit);
updateStatus(String.Format("GARC Get: {0} @ {1}... ", toEdit, GARC));
updateStatus($"GARC Get: {toEdit} @ {GARC}... ");
threadGet(RomFSPath + GARC, toEdit, true, skipDecompression);
while (threads > 0) Thread.Sleep(50);
}
@@ -585,7 +585,7 @@ private void fileSet(IEnumerable<string> files, bool keep = false)
foreach (string toEdit in files)
{
string GARC = getGARCFileName(toEdit);
updateStatus(String.Format("GARC Set: {0} @ {1}... ", toEdit, GARC));
updateStatus($"GARC Set: {toEdit} @ {GARC}... ");
threadSet(RomFSPath + GARC, toEdit);
while (threads > 0) Thread.Sleep(50);
if (!keep && Directory.Exists(toEdit)) Directory.Delete(toEdit, true);
@@ -603,7 +603,7 @@ private void rebuildExeFS(object sender, EventArgs e)
SaveFileDialog sfd = new SaveFileDialog
{
FileName = (HANSgameID != 0) ? HANSgameID.ToString("X8") + ".exefs" : "exefs.bin",
FileName = HANSgameID != 0 ? HANSgameID.ToString("X8") + ".exefs" : "exefs.bin",
Filter = "HANS ExeFS|*.exefs" + "|Binary File|*.bin" + "|All Files|*.*"
};
sfd.FilterIndex = HANSgameID != 0 ? 0 : sfd.Filter.Length - 1;
@@ -813,19 +813,22 @@ private void Menu_LZ11_Click(object sender, EventArgs e)
byte[] data = File.ReadAllBytes(path);
string predict = data[0] == 0x11 ? "compressed" : "decompressed";
var dr = Util.Prompt(MessageBoxButtons.YesNoCancel, String.Format("Detected {0} file. Do what?", predict),
var dr = Util.Prompt(MessageBoxButtons.YesNoCancel, $"Detected {predict} file. Do what?",
"Yes = Decompress\nNo = Compress\nCancel = Abort");
new Thread(() =>
{
threads++;
if (dr == DialogResult.Yes)
{
CTR.LZSS.Decompress(path, path);
try
{
CTR.LZSS.Decompress(path, Path.Combine(Directory.GetParent(path).FullName, "dec_" + Path.GetFileNameWithoutExtension(path) + ".bin"));
} catch (Exception err) { Util.Alert("Tried decompression, may have worked:", err.ToString()); }
Util.Alert("File Decompressed!", path);
}
if (dr == DialogResult.No)
{
CTR.LZSS.Compress(path, path);
CTR.LZSS.Compress(path, Path.Combine(Directory.GetParent(path).FullName, Path.GetFileNameWithoutExtension(path).Replace("_dec", "") + ".lz"));
Util.Alert("File Compressed!", path);
}
threads--;
@@ -851,45 +854,45 @@ internal static string getGARCFileName(string requestedGARC, int lang)
switch (requestedGARC)
{
case "movesprite": ans = getGARCPath(0, 0, 5); break;
case "encdata": ans = (oras) ? getGARCPath(0, 1, 3) : getGARCPath(0, 1, 2); break;
case "trdata": ans = (oras) ? getGARCPath(0, 3, 6) : getGARCPath(0, 3, 8); break;
case "trpoke": ans = (oras) ? getGARCPath(0, 3, 8) : getGARCPath(0, 4, 0); break;
case "mapGR": ans = (oras) ? getGARCPath(0, 3, 9) : getGARCPath(0, 4, 1); break;
case "mapMatrix": ans = (oras) ? getGARCPath(0, 4, 0) : getGARCPath(0, 4, 2); break;
case "gametext": ans = (oras) ? getGARCPath(0, 7, 1 + lang) : getGARCPath(0, 7, 2 + lang); break;
case "storytext": ans = (oras) ? getGARCPath(0, 7 + ((lang + 9) / 10), (10 + (lang + 9)) % 10) : getGARCPath(0, 8, lang); break;
case "wallpaper": ans = (oras) ? getGARCPath(1, 0, 3) : getGARCPath(1, 0, 4); break;
case "titlescreen": ans = (oras) ? getGARCPath(1, 5, 2) : getGARCPath(1, 6, 5); break;
case "maisonpkN": ans = (oras) ? getGARCPath(1, 8, 2) : getGARCPath(2, 0, 3); break;
case "maisontrN": ans = (oras) ? getGARCPath(1, 8, 3) : getGARCPath(2, 0, 4); break;
case "maisonpkS": ans = (oras) ? getGARCPath(1, 8, 4) : getGARCPath(2, 0, 5); break;
case "maisontrS": ans = (oras) ? getGARCPath(1, 8, 5) : getGARCPath(2, 0, 6); break;
case "move": ans = (oras) ? getGARCPath(1, 8, 9) : getGARCPath(2, 1, 2); break;
case "eggmove": ans = (oras) ? getGARCPath(1, 9, 0) : getGARCPath(2, 1, 3); break;
case "levelup": ans = (oras) ? getGARCPath(1, 9, 1) : getGARCPath(2, 1, 4); break;
case "evolution": ans = (oras) ? getGARCPath(1, 9, 2) : getGARCPath(2, 1, 5); break;
case "megaevo": ans = (oras) ? getGARCPath(1, 9, 3) : getGARCPath(2, 1, 6); break;
case "personal": ans = (oras) ? getGARCPath(1, 9, 5) : getGARCPath(2, 1, 8); break;
case "item": ans = (oras) ? getGARCPath(1, 9, 7) : getGARCPath(2, 2, 0); break;
case "encdata": ans = oras ? getGARCPath(0, 1, 3) : getGARCPath(0, 1, 2); break;
case "trdata": ans = oras ? getGARCPath(0, 3, 6) : getGARCPath(0, 3, 8); break;
case "trpoke": ans = oras ? getGARCPath(0, 3, 8) : getGARCPath(0, 4, 0); break;
case "mapGR": ans = oras ? getGARCPath(0, 3, 9) : getGARCPath(0, 4, 1); break;
case "mapMatrix": ans = oras ? getGARCPath(0, 4, 0) : getGARCPath(0, 4, 2); break;
case "gametext": ans = oras ? getGARCPath(0, 7, 1 + lang) : getGARCPath(0, 7, 2 + lang); break;
case "storytext": ans = oras ? getGARCPath(0, 7 + (lang + 9) / 10, (10 + lang + 9) % 10) : getGARCPath(0, 8, lang); break;
case "wallpaper": ans = oras ? getGARCPath(1, 0, 3) : getGARCPath(1, 0, 4); break;
case "titlescreen": ans = oras ? getGARCPath(1, 5, 2) : getGARCPath(1, 6, 5); break;
case "maisonpkN": ans = oras ? getGARCPath(1, 8, 2) : getGARCPath(2, 0, 3); break;
case "maisontrN": ans = oras ? getGARCPath(1, 8, 3) : getGARCPath(2, 0, 4); break;
case "maisonpkS": ans = oras ? getGARCPath(1, 8, 4) : getGARCPath(2, 0, 5); break;
case "maisontrS": ans = oras ? getGARCPath(1, 8, 5) : getGARCPath(2, 0, 6); break;
case "move": ans = oras ? getGARCPath(1, 8, 9) : getGARCPath(2, 1, 2); break;
case "eggmove": ans = oras ? getGARCPath(1, 9, 0) : getGARCPath(2, 1, 3); break;
case "levelup": ans = oras ? getGARCPath(1, 9, 1) : getGARCPath(2, 1, 4); break;
case "evolution": ans = oras ? getGARCPath(1, 9, 2) : getGARCPath(2, 1, 5); break;
case "megaevo": ans = oras ? getGARCPath(1, 9, 3) : getGARCPath(2, 1, 6); break;
case "personal": ans = oras ? getGARCPath(1, 9, 5) : getGARCPath(2, 1, 8); break;
case "item": ans = oras ? getGARCPath(1, 9, 7) : getGARCPath(2, 2, 0); break;
}
return ans;
}
internal static string getGARCPath(int A, int B, int C)
{
return String.Format("{0}a{0}{1}{0}{2}{0}{3}", Path.DirectorySeparatorChar, A, B, C);
return string.Format("{0}a{0}{1}{0}{2}{0}{3}", Path.DirectorySeparatorChar, A, B, C);
}
public bool getGARC(string infile, string outfolder, bool PB, bool bypassExt = false)
{
if (skipBoth && Directory.Exists(outfolder))
{
updateStatus(String.Format("Skipped - Exists!"), false);
updateStatus("Skipped - Exists!", false);
threads--;
return true;
}
try
{
bool success = CTR.GARC.garcUnpack(infile, outfolder, bypassExt, (PB) ? pBar1 : null, null, true, bypassExt);
updateStatus(String.Format(success ? "Success!" : "Failed!"), false);
bool success = CTR.GARC.garcUnpack(infile, outfolder, bypassExt, PB ? pBar1 : null, null, true, bypassExt);
updateStatus(string.Format(success ? "Success!" : "Failed!"), false);
threads--;
return success;
}
@@ -898,13 +901,13 @@ public bool getGARC(string infile, string outfolder, bool PB, bool bypassExt = f
public bool setGARC(string outfile, string infolder, bool PB)
{
if (skipBoth || (ModifierKeys == Keys.Control && Util.Prompt(MessageBoxButtons.YesNo, "Cancel writing data back to GARC?") == DialogResult.Yes))
{ threads--; updateStatus(String.Format("Aborted!"), false); return false; }
{ threads--; updateStatus("Aborted!", false); return false; }
try
{
bool success = CTR.GARC.garcPackMS(infolder, outfile, (PB) ? pBar1 : null, null, true);
bool success = CTR.GARC.garcPackMS(infolder, outfile, PB ? pBar1 : null, null, true);
threads--;
updateStatus(String.Format(success ? "Success!" : "Failed!"), false);
updateStatus(string.Format(success ? "Success!" : "Failed!"), false);
return success;
}
catch (Exception e) { Util.Error("Could not set the GARC back:", e.ToString()); threads--; return false; }
@@ -927,7 +930,8 @@ public void backupGARCs(bool overwrite, params string[] g)
foreach (string s in g)
{
string GARC = getGARCFileName(s);
string dest = "backup" + Path.DirectorySeparatorChar + s + String.Format(" ({0})", GARC.Replace(Path.DirectorySeparatorChar.ToString(), ""));
string dest = "backup" + Path.DirectorySeparatorChar + s +
$" ({GARC.Replace(Path.DirectorySeparatorChar.ToString(), "")})";
if (overwrite || !File.Exists(dest))
File.Copy(RomFSPath + GARC, dest);
}
@@ -938,7 +942,8 @@ public void restoreGARCs(bool oras_define, params string[] g)
foreach (string s in g)
{
string dest = RomFSPath + getGARCFileName(s);
string src = "backup" + Path.DirectorySeparatorChar + s + String.Format(" ({0})", getGARCFileName(s).Replace(Path.DirectorySeparatorChar.ToString(), ""));
string src = "backup" + Path.DirectorySeparatorChar + s +
$" ({getGARCFileName(s).Replace(Path.DirectorySeparatorChar.ToString(), "")})";
File.Copy(src, dest, true);
if (s == "personal" || s == "gametext")
Util.Alert("In order to restore " + s + ", restart the program. While exiting, hold the Control Key to prevent writebacks.");
@@ -963,7 +968,7 @@ internal static bool setText(int file, string[] strings)
// Update RichTextBox
public void updateStatus(string status, bool preBreak = true)
{
string newtext = ((preBreak) ? Environment.NewLine : "") + status;
string newtext = (preBreak ? Environment.NewLine : "") + status;
try
{
if (RTB_Status.InvokeRequired)

View File

@@ -53,12 +53,12 @@ public PersonalInfo(byte[] data)
EvoStage = br.ReadByte();
EVs = br.ReadUInt16();
EV_HP = ((EVs >> 0) & 0x3);
EV_ATK = ((EVs >> 2) & 0x3);
EV_DEF = ((EVs >> 4) & 0x3);
EV_SPE = ((EVs >> 6) & 0x3);
EV_SPA = ((EVs >> 8) & 0x3);
EV_SPD = ((EVs >> 10) & 0x3);
EV_HP = (EVs >> 0) & 0x3;
EV_ATK = (EVs >> 2) & 0x3;
EV_DEF = (EVs >> 4) & 0x3;
EV_SPE = (EVs >> 6) & 0x3;
EV_SPA = (EVs >> 8) & 0x3;
EV_SPD = (EVs >> 10) & 0x3;
Items = new[] { br.ReadUInt16(), br.ReadUInt16(), br.ReadUInt16() };
Gender = br.ReadByte();
@@ -141,12 +141,12 @@ public byte[] Write()
byte[] TMHMData = new byte[0x10];
for (int i = 0; i < TMHM.Length; i++)
TMHMData[i / 8] |= (byte)(TMHM[i] ? (1 << (i % 8)) : 0);
TMHMData[i / 8] |= (byte)(TMHM[i] ? 1 << (i % 8) : 0);
bw.Write(TMHMData);
byte[] TutorData = new byte[8];
for (int i = 0; i < Tutors.Length; i++)
TutorData[i / 8] |= (byte)(Tutors[i] ? (1 << (i % 8)) : 0);
TutorData[i / 8] |= (byte)(Tutors[i] ? 1 << (i % 8) : 0);
bw.Write(TutorData);
while (bw.BaseStream.Length != 0x40) bw.Write((byte)0);
@@ -162,7 +162,7 @@ public byte[] Write()
};
for (int i = 0; i < 4; i++)
for (int b = 0; b < ORASTutors[i].Length; b++)
ORASTutorData[i][b / 8] |= (byte)(ORASTutors[i][b] ? (1 << b % 8) : 0);
ORASTutorData[i][b / 8] |= (byte)(ORASTutors[i][b] ? 1 << b % 8 : 0);
foreach (byte[] ORASTutor in ORASTutorData) bw.Write(ORASTutor);
@@ -404,7 +404,7 @@ public Heal(byte val)
Full = Val == 0xFF;
Half = Val == 0xFE;
Quarter = Val == 0xFD;
Value = (Val < 0xFD);
Value = Val < 0xFD;
}
public byte Write()
{
@@ -485,7 +485,7 @@ public Item(byte[] data)
BoostSPD &= 0xF;
BoostACC = br.ReadByte();
BoostCRIT = (BoostACC >> 4) & 0x3;
BoostPP = (BoostACC >> 6);
BoostPP = BoostACC >> 6;
BoostACC &= 0xF;
FunctionFlags = br.ReadUInt16();
@@ -563,7 +563,7 @@ public Heal(byte val)
Full = Val == 0xFF;
Half = Val == 0xFE;
Quarter = Val == 0xFD;
Value = (Val < 0xFD);
Value = Val < 0xFD;
}
public byte Write()
{
@@ -616,7 +616,8 @@ public class Pokemon
public ushort[] Moves;
public bool HP, ATK, DEF, SPE, SPA, SPD;
private byte _u1, _u2;
private readonly byte _u1;
private readonly byte _u2;
public Pokemon(byte[] data)
{
@@ -675,7 +676,7 @@ public class Learnset
public Learnset(byte[] data)
{
if (data.Length < 4 || data.Length % 4 != 0) return; // Detect invalid files, weakly.
Count = (data.Length / 4) - 1;
Count = data.Length / 4 - 1;
Moves = new short[Count];
Levels = new short[Count];
using (BinaryReader br = new BinaryReader(new MemoryStream(data)))
@@ -914,7 +915,7 @@ public class MapMatrix
public uint u0;
public ushort uL;
public ushort Width, Height;
private int Area;
private readonly int Area;
public ushort[] EntryList;
public Entry[] Entries;
public Unknown[] Unknowns;
@@ -964,7 +965,7 @@ public Bitmap Preview(int Scale, int ColorShift)
// Fetch Singular Images first
Bitmap[] EntryImages = new Bitmap[Area];
for (int i = 0; i < Area; i++)
EntryImages[i] = (Entries[i] == null)
EntryImages[i] = Entries[i] == null
? new Bitmap(40 * Scale, 40 * Scale)
: Entries[i].Preview(Scale, ColorShift);
@@ -974,7 +975,7 @@ public Bitmap Preview(int Scale, int ColorShift)
using (Graphics g = Graphics.FromImage(img))
for (int i = 0; i < Area; i++)
{
g.DrawImage(EntryImages[i], new Point((i * EntryImages[0].Width) % (img.Width), EntryImages[0].Height * ((i / Width))));
g.DrawImage(EntryImages[i], new Point(i * EntryImages[0].Width % img.Width, EntryImages[0].Height * (i / Width)));
}
return img;
}
@@ -984,7 +985,7 @@ public class Entry
public Collision coll;
public ushort Width, Height;
private int Area;
private readonly int Area;
public uint[] Tiles; // Certain bits?
public Entry(byte[] data)
{
@@ -1029,11 +1030,11 @@ public byte[] BytePreview(int s, int ColorShift)
int Y = i / 40;
uint colorValue = Tiles[i] == 0x01000021
? 0xFF000000
: (RNG.Forward32(Tiles[i], ColorShift) | 0xFF000000);
: RNG.Forward32(Tiles[i], ColorShift) | 0xFF000000;
byte[] pixel = BitConverter.GetBytes(colorValue);
for (int x = 0; x < s * s; x++)
pixel.CopyTo(bmpData, 4 * (((Y * s + x / s) * Width * s) + (X * s + x % s)));
pixel.CopyTo(bmpData, 4 * ((Y * s + x / s) * Width * s + X * s + x % s));
}
return bmpData;
}
@@ -1088,16 +1089,17 @@ public Collision(byte[] data)
}
public class CollisionObject
{
private float _0;
private float _1;
private float _2;
private float _3; // rarely used
private readonly float _0;
private readonly float _1;
private readonly float _2;
private readonly float _3; // rarely used
// I don't even know...
public float F1 { get { return _0 / 2; } }
public float F2 { get { return _1 * 80; } }
public float F3 { get { return _2 / 2; } }
public float F4 { get { return _3; } }
public float F1 => _0 / 2;
public float F2 => _1 * 80;
public float F3 => _2 / 2;
public float F4 => _3;
public CollisionObject(byte[] data)
{
_0 = BitConverter.ToSingle(data, 0x0);
@@ -1107,14 +1109,14 @@ public CollisionObject(byte[] data)
}
public override string ToString()
{
return String.Join(", ", new[] { F1.ToString(), F2.ToString(), F3.ToString(), F4.ToString() });
return string.Join(", ", F1.ToString(), F2.ToString(), F3.ToString(), F4.ToString());
}
}
}
public string Unk2String()
{
return Unknowns.Aggregate("", (current, l) => current + String.Format("{0}: {1,3} {2,3} {3,3} {4,3}{5,3}", l.Direction, l.p1, l.p2, l.p3, l.p4, Environment.NewLine));
return Unknowns.Aggregate("", (current, l) => current + $"{l.Direction}: {l.p1,3} {l.p2,3} {l.p3,3} {l.p4,3}{Environment.NewLine,3}");
}
private void parseUnk(byte[] data)
{
@@ -1130,7 +1132,7 @@ private void parseUnk(byte[] data)
_4 = br.ReadSingle(),
});
} while (unk.Last().Direction != 0);
unk.RemoveAt(unk.Count()-1);
unk.RemoveAt(unk.Count-1);
Unknowns = unk.ToArray();
}
@@ -1142,10 +1144,10 @@ public class Unknown
public float _3;
public float _4;
public int p1 { get { return (int)_1 / 18; } }
public int p2 { get { return (int)_2 / 18; } }
public int p3 { get { return (int)_3 / 18; } }
public int p4 { get { return (int)_4 / 18; } }
public int p1 => (int)_1 / 18;
public int p2 => (int)_2 / 18;
public int p3 => (int)_3 / 18;
public int p4 => (int)_4 / 18;
}
}
public class ZoneData
@@ -1217,7 +1219,7 @@ public Zone(byte[][] Zone)
public byte[][] Write()
{
byte[][] Zone = new byte[(File5 != null) ? 5 : 4][];
byte[][] Zone = new byte[File5 != null ? 5 : 4][];
Zone[0] = ZD.Data;
Zone[1] = Entities.Write();
Zone[2] = MapScript.Write();
@@ -1233,8 +1235,8 @@ public class ZoneEntities
{
public byte[] Data;
public Int32 Length;
public Int32 FurnitureCount, NPCCount, WarpCount, TriggerCount, UnknownCount;
public int Length;
public int FurnitureCount, NPCCount, WarpCount, TriggerCount, UnknownCount;
public EntityFurniture[] Furniture;
public EntityNPC[] NPCs;
public EntityWarp[] Warps;
@@ -1312,7 +1314,7 @@ public byte[] Write()
// Add padding zeroes if required (yield size % 4 == 0)
if (finalData.Length % 4 != 0)
Array.Resize(ref finalData, finalData.Length + 4 - (finalData.Length % 4));
Array.Resize(ref finalData, finalData.Length + 4 - finalData.Length % 4);
return finalData;
}
@@ -1390,7 +1392,7 @@ public class EntityNPC
// -360, 360 ????
public float Degrees { get { return BitConverter.ToSingle(Raw, 0x2C); } set { BitConverter.GetBytes(value).CopyTo(Raw, 0x2C); } }
public float Deg18 { get { return Degrees/18; } }
public float Deg18 => Degrees/18;
public byte[] Raw;
public byte[] OriginalData;
@@ -1422,8 +1424,8 @@ public class EntityWarp
public int Z { get { return BitConverter.ToInt16(Raw, 0x0A); } set { BitConverter.GetBytes((short)value).CopyTo(Raw, 0x0A); } }
public int Y { get { return BitConverter.ToUInt16(Raw, 0x0C); } set { BitConverter.GetBytes((ushort)value).CopyTo(Raw, 0x0C); } }
public decimal pX { get { return (decimal)X / 18; } }
public decimal pY { get { return (decimal)Y / 18; } }
public decimal pX => (decimal)X / 18;
public decimal pY => (decimal)Y / 18;
// Stretches RIGHT
public int Width { get { return BitConverter.ToInt16(Raw, 0x0E); } set { BitConverter.GetBytes((short)value).CopyTo(Raw, 0x0E); } }
@@ -1603,45 +1605,39 @@ public byte[] Write()
}
public class Script
{
public int Length { get { return BitConverter.ToInt32(Raw, 0x00); } }
public uint Magic { get { return BitConverter.ToUInt32(Raw, 0x04); } }
public int Length => BitConverter.ToInt32(Raw, 0x00);
public uint Magic => BitConverter.ToUInt32(Raw, 0x04);
// case 0x0A0AF1E0: code = read_code_block(f); break;
// case 0x0A0AF1EF: debug = read_debug_block(f); break;
public bool Debug { get { return Magic == 0x0A0AF1EF; } }
public bool Debug => Magic == 0x0A0AF1EF;
public ushort PtrOffset { get { return BitConverter.ToUInt16(Raw, 0x08); } }
public ushort PtrCount { get { return BitConverter.ToUInt16(Raw, 0x0A); } }
public ushort PtrOffset => BitConverter.ToUInt16(Raw, 0x08);
public ushort PtrCount => BitConverter.ToUInt16(Raw, 0x0A);
public int ScriptInstructionStart { get { return BitConverter.ToInt32(Raw, 0x0C); } }
public int ScriptMovementStart { get { return BitConverter.ToInt32(Raw, 0x10); } }
public int FinalOffset { get { return BitConverter.ToInt32(Raw, 0x14); } }
public int AllocatedMemory { get { return BitConverter.ToInt32(Raw, 0x18); } }
public int ScriptInstructionStart => BitConverter.ToInt32(Raw, 0x0C);
public int ScriptMovementStart => BitConverter.ToInt32(Raw, 0x10);
public int FinalOffset => BitConverter.ToInt32(Raw, 0x14);
public int AllocatedMemory => BitConverter.ToInt32(Raw, 0x18);
// Generated Attributes
public int CompressedLength { get { return Length - ScriptInstructionStart; } }
public byte[] CompressedBytes { get { return Raw.Skip(ScriptInstructionStart).ToArray(); } }
public int DecompressedLength { get { return FinalOffset - ScriptInstructionStart; } }
public uint[] DecompressedInstructions { get { return Scripts.quickDecompress(CompressedBytes, DecompressedLength/4); } }
public int CompressedLength => Length - ScriptInstructionStart;
public byte[] CompressedBytes => Raw.Skip(ScriptInstructionStart).ToArray();
public int DecompressedLength => FinalOffset - ScriptInstructionStart;
public uint[] DecompressedInstructions => Scripts.quickDecompress(CompressedBytes, DecompressedLength/4);
public uint[] ScriptCommands { get { return DecompressedInstructions.Take((ScriptMovementStart - ScriptInstructionStart) / 4).ToArray(); } }
public uint[] MoveCommands { get { return DecompressedInstructions.Skip((ScriptMovementStart - ScriptInstructionStart) / 4).ToArray(); } }
public string[] ParseScript { get { return Scripts.parseScript(ScriptCommands); } }
public string[] ParseMoves { get { return Scripts.parseMovement(MoveCommands); } }
public uint[] ScriptCommands => DecompressedInstructions.Take((ScriptMovementStart - ScriptInstructionStart) / 4).ToArray();
public uint[] MoveCommands => DecompressedInstructions.Skip((ScriptMovementStart - ScriptInstructionStart) / 4).ToArray();
public string[] ParseScript => Scripts.parseScript(ScriptCommands);
public string[] ParseMoves => Scripts.parseMovement(MoveCommands);
public string Info
{
get
{
return "Data Start: 0x" + ScriptInstructionStart.ToString("X4")
+ Environment.NewLine + "Movement Offset: 0x" + ScriptMovementStart.ToString("X4")
+ Environment.NewLine + "Total Used Size: 0x" + FinalOffset.ToString("X4")
+ Environment.NewLine + "Reserved Size: 0x" + AllocatedMemory.ToString("X4")
+ Environment.NewLine + "Compressed Len: 0x" + CompressedLength.ToString("X4")
+ Environment.NewLine + "Decompressed Len: 0x" + DecompressedLength.ToString("X4")
+ Environment.NewLine + "Compression Ratio: " +
((DecompressedLength - CompressedLength)/(decimal)DecompressedLength).ToString("p1");
}
}
public string Info => "Data Start: 0x" + ScriptInstructionStart.ToString("X4")
+ Environment.NewLine + "Movement Offset: 0x" + ScriptMovementStart.ToString("X4")
+ Environment.NewLine + "Total Used Size: 0x" + FinalOffset.ToString("X4")
+ Environment.NewLine + "Reserved Size: 0x" + AllocatedMemory.ToString("X4")
+ Environment.NewLine + "Compressed Len: 0x" + CompressedLength.ToString("X4")
+ Environment.NewLine + "Decompressed Len: 0x" + DecompressedLength.ToString("X4")
+ Environment.NewLine + "Compression Ratio: " +
((DecompressedLength - CompressedLength)/(decimal)DecompressedLength).ToString("p1");
public byte[] Raw;
public Script(byte[] data = null)

View File

@@ -15,7 +15,7 @@ public partial class EggMove : Form
public EggMove()
{
InitializeComponent();
string[] specieslist = Main.getText((Main.oras) ? 98 : 80);
string[] specieslist = Main.getText(Main.oras ? 98 : 80);
specieslist[0] = movelist[0] = "";
string[] sortedspecies = (string[])specieslist.Clone();
@@ -31,10 +31,10 @@ public EggMove()
CB_Species.DataSource = newlist;
CB_Species.SelectedIndex = 0;
}
private string[] files = Directory.GetFiles("eggmove");
private byte[] data = File.ReadAllBytes(Directory.GetFiles("personal", "*.*", SearchOption.TopDirectoryOnly).Last());
private readonly string[] files = Directory.GetFiles("eggmove");
private readonly byte[] data = File.ReadAllBytes(Directory.GetFiles("personal", "*.*", SearchOption.TopDirectoryOnly).Last());
private int entry = -1;
private string[] movelist = Main.getText((Main.oras) ? 14 : 13);
private readonly string[] movelist = Main.getText(Main.oras ? 14 : 13);
bool dumping;
private void setupDGV()
{
@@ -59,7 +59,7 @@ private void getList()
entry = Util.getIndex(CB_Species);
int[] specForm = Personal.getSpecies(data, Main.oras, entry);
string filename = "_" + specForm[0] + ((entry > 721) ? "_" + (specForm[1] + 1) : "");
string filename = "_" + specForm[0] + (entry > 721 ? "_" + (specForm[1] + 1) : "");
PB_MonSprite.Image = (Bitmap)Resources.ResourceManager.GetObject(filename);
dgv.Rows.Clear();
@@ -137,7 +137,7 @@ private void B_RandAll_Click(object sender, EventArgs e)
for (int j = 0; j < dgv.Rows.Count - 1; j++)
{
// Assign New Moves
bool forceSTAB = (CHK_STAB.Checked && rnd.Next(0, 99) < NUD_STAB.Value);
bool forceSTAB = CHK_STAB.Checked && rnd.Next(0, 99) < NUD_STAB.Value;
int move = Randomizer.getRandomSpecies(ref randomMoves, ref ctr);
while ( // Move is invalid
(!CHK_HMs.Checked && banned.Contains(move)) // HM Moves Not Allowed
@@ -225,9 +225,8 @@ private void calcStats()
stab++;
}
}
Util.Alert(String.Format("Moves Learned: {0}\r\nMost Learned: {1} @ {2}\r\nSTAB Count: {3}\r\nSpecies with EggMoves: {4}",
movectr, max,
spec, stab, species));
Util.Alert(
$"Moves Learned: {movectr}\r\nMost Learned: {max} @ {spec}\r\nSTAB Count: {stab}\r\nSpecies with EggMoves: {species}");
}
}
}

View File

@@ -1,5 +1,4 @@
using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Linq;
@@ -28,15 +27,15 @@ public Evolution()
"Level Up",
"Trade",
"Trade with Held Item",
String.Format("Trade for opposite {0}/{1}", specieslist[588], specieslist[616]), // Shelmet&Karrablast
$"Trade for opposite {specieslist[588]}/{specieslist[616]}", // Shelmet&Karrablast
"Used Item",
"Level Up (Attack > Defense)",
"Level Up (Attack = Defense)",
"Level Up (Attack < Defense)",
"Level Up (Random < 5)",
"Level Up (Random > 5)",
String.Format("Level Up ({0})", specieslist[291]), // Ninjask
String.Format("Level Up ({0})", specieslist[292]), // Shedinja
$"Level Up ({specieslist[291]})", // Ninjask
$"Level Up ({specieslist[292]})", // Shedinja
"Level Up (Beauty)",
"Level Up with Held Item (Male)",
"Level Up with Held Item (Female)",
@@ -51,7 +50,7 @@ public Evolution()
"Level Up at Cold",
"Level Up with 3DS Upside Down",
"Level Up with 50 Affection + MoveType",
String.Format("{0} Type in Party", typelist[16]),
$"{typelist[16]} Type in Party",
"Overworld Rain",
"Level Up (@) at Night",
"Level Up (@) at Night",
@@ -75,15 +74,17 @@ public Evolution()
CB_Species.SelectedIndex = 0;
}
private string[] files = Directory.GetFiles("evolution");
private ComboBox[] pb, rb, mb;
private PictureBox[] pic;
private readonly string[] files = Directory.GetFiles("evolution");
private readonly ComboBox[] pb;
private readonly ComboBox[] rb;
private readonly ComboBox[] mb;
private readonly PictureBox[] pic;
private int entry = -1;
private string[] sortedspecies;
private string[] specieslist = Main.getText((Main.oras) ? 98 : 80);
private string[] movelist = Main.getText((Main.oras) ? 14 : 13);
private string[] itemlist = Main.getText((Main.oras) ? 114 : 96);
private string[] typelist = Main.getText((Main.oras) ? 18 : 17);
private readonly string[] sortedspecies;
private readonly string[] specieslist = Main.getText(Main.oras ? 98 : 80);
private readonly string[] movelist = Main.getText(Main.oras ? 14 : 13);
private readonly string[] itemlist = Main.getText(Main.oras ? 114 : 96);
private readonly string[] typelist = Main.getText(Main.oras ? 18 : 17);
bool dumping;
private Evolutions evo = new Evolutions(new byte[0x30]);
private void getList()
@@ -202,7 +203,7 @@ private void B_Dump_Click(object sender, EventArgs e)
// int param = pb[j].SelectedIndex;
int poke = rb[j].SelectedIndex;
if (poke > 0 && methodval > 0)
result += mb[j].Text + ((pb[j].Visible) ? " [" + pb[j].Text + "]" : "") + " into " + rb[j].Text + Environment.NewLine;
result += mb[j].Text + (pb[j].Visible ? " [" + pb[j].Text + "]" : "") + " into " + rb[j].Text + Environment.NewLine;
}
result += Environment.NewLine;
@@ -239,7 +240,7 @@ private void changeMethod(object sender, EventArgs e)
1, // 34 - Gender Branch
};
pb[op].Visible = pic[op].Visible = rb[op].Visible = (mb[op].SelectedIndex > 0);
pb[op].Visible = pic[op].Visible = rb[op].Visible = mb[op].SelectedIndex > 0;
pb[op].Items.Clear();
int cv = methodCase[mb[op].SelectedIndex];

View File

@@ -32,14 +32,14 @@ public Gifts()
}
internal static string FieldPath = Path.Combine(Main.RomFSPath, "DllField.cro");
private byte[] FieldData;
private int fieldOffset = Main.oras ? 0xF906C : 0xF805C;
private int fieldSize = Main.oras ? 0x24 : 0x18;
private int count = Main.oras ? 0x25 : 0x13;
private readonly int fieldOffset = Main.oras ? 0xF906C : 0xF805C;
private readonly int fieldSize = Main.oras ? 0x24 : 0x18;
private readonly int count = Main.oras ? 0x25 : 0x13;
private Gift[] GiftData;
private string[] abilitylist = Main.getText((Main.oras) ? 37 : 34);
private string[] movelist = Main.getText((Main.oras) ? 14 : 13);
private string[] itemlist = Main.getText((Main.oras) ? 114 : 96);
private string[] specieslist = Main.getText((Main.oras) ? 98 : 80);
private readonly string[] abilitylist = Main.getText(Main.oras ? 37 : 34);
private readonly string[] movelist = Main.getText(Main.oras ? 14 : 13);
private readonly string[] itemlist = Main.getText(Main.oras ? 114 : 96);
private readonly string[] specieslist = Main.getText(Main.oras ? 98 : 80);
private void B_Save_Click(object sender, EventArgs e)
{
saveEntry();
@@ -58,7 +58,7 @@ private void loadData()
for (int i = 0; i < GiftData.Length; i++)
{
GiftData[i] = new Gift(FieldData.Skip(fieldOffset + i * fieldSize).Take(fieldSize).ToArray(), Main.oras);
LB_Gifts.Items.Add(String.Format("{0} - {1}", i.ToString("00"), specieslist[GiftData[i].Species]));
LB_Gifts.Items.Add($"{i.ToString("00")} - {specieslist[GiftData[i].Species]}");
}
loaded = true;
LB_Gifts.SelectedIndex = 0;

View File

@@ -13,9 +13,10 @@ public ItemEditor()
InitializeComponent();
Setup();
}
string[] files = Directory.GetFiles("item");
string[] itemlist = Main.getText((Main.oras) ? 114 : 96);
string[] itemflavor = Main.getText((Main.oras) ? 117 : 99);
readonly string[] files = Directory.GetFiles("item");
readonly string[] itemlist = Main.getText(Main.oras ? 114 : 96);
readonly string[] itemflavor = Main.getText(Main.oras ? 117 : 99);
private void Setup()
{
@@ -56,7 +57,7 @@ private void formClosing(object sender, FormClosingEventArgs e)
private void changePrice(object sender, EventArgs e)
{
MT_Sell.Text = ((Math.Min(Util.ToUInt32(MT_Price) / 10, 0x7FFF)) * 10 / 2).ToString();
MT_Sell.Text = (Math.Min(Util.ToUInt32(MT_Price) / 10, 0x7FFF) * 10 / 2).ToString();
}
private int getItemMapOffset()
@@ -66,7 +67,7 @@ private int getItemMapOffset()
if (!File.Exists(files[0]) || !Path.GetFileNameWithoutExtension(files[0]).Contains("code")) { Util.Alert("No .code.bin detected."); return -1; }
byte[] data = File.ReadAllBytes(files[0]);
byte[] reference = (Main.oras)
byte[] reference = Main.oras
? new byte[] { 0x92, 0x0A, 0x06, 0x3F, 0x75, 0x02 } // ORAS (vanilla @ 47C640)
: new byte[] { 0x92, 0x0A, 0x06, 0x3F, 0x41, 0x02 }; // XY (vanilla @ 43DB74)

View File

@@ -33,10 +33,10 @@ public LevelUp()
CB_Species.DataSource = newlist;
CB_Species.SelectedIndex = 0;
}
private string[] files = Directory.GetFiles("levelup");
private byte[] data = File.ReadAllBytes(Directory.GetFiles("personal", "*.*", SearchOption.TopDirectoryOnly).Last());
private readonly string[] files = Directory.GetFiles("levelup");
private readonly byte[] data = File.ReadAllBytes(Directory.GetFiles("personal", "*.*", SearchOption.TopDirectoryOnly).Last());
private int entry = -1;
private string[] movelist = Main.getText((Main.oras) ? 14 : 13);
private readonly string[] movelist = Main.getText(Main.oras ? 14 : 13);
bool dumping;
private void setupDGV()
{
@@ -69,7 +69,7 @@ private void getList()
entry = Util.getIndex(CB_Species);
int[] specForm = Personal.getSpecies(data, Main.oras, entry);
string filename = "_" + specForm[0] + ((entry > 721) ? "_" + (specForm[1] + 1) : "");
string filename = "_" + specForm[0] + (entry > 721 ? "_" + (specForm[1] + 1) : "");
PB_MonSprite.Image = (Bitmap)Resources.ResourceManager.GetObject(filename);
dgv.Rows.Clear();
@@ -164,7 +164,7 @@ private void B_RandAll_Click(object sender, EventArgs e)
for (int j = 1; j < dgv.Rows.Count - 1; j++)
{
// Assign New Moves
bool forceSTAB = (CHK_STAB.Checked && rnd.Next(0, 99) < NUD_STAB.Value);
bool forceSTAB = CHK_STAB.Checked && rnd.Next(0, 99) < NUD_STAB.Value;
int move = Randomizer.getRandomSpecies(ref randomMoves, ref ctr);
while ( // Move is invalid
(!CHK_HMs.Checked && banned.Contains(move)) // HM Moves Not Allowed
@@ -209,7 +209,7 @@ private void B_Dump_Click(object sender, EventArgs e)
CB_Species.SelectedIndex = i; // Get new Species
result += "======" + Environment.NewLine + entry + " " + CB_Species.Text + Environment.NewLine + "======" + Environment.NewLine;
for (int j = 0; j < dgv.Rows.Count - 1; j++)
result += String.Format("{0} - {1}", dgv.Rows[j].Cells[0].Value, dgv.Rows[j].Cells[1].Value + Environment.NewLine);
result += $"{dgv.Rows[j].Cells[0].Value} - {dgv.Rows[j].Cells[1].Value + Environment.NewLine}";
result += Environment.NewLine;
}
@@ -266,9 +266,7 @@ private void CHK_TypeBias_CheckedChanged(object sender, EventArgs e)
stab++;
}
}
Util.Alert(String.Format("Moves Learned: {0}\r\nMost Learned: {1} @ {2}\r\nSTAB Count: {3}",
movectr, max,
spec, stab));
Util.Alert($"Moves Learned: {movectr}\r\nMost Learned: {max} @ {spec}\r\nSTAB Count: {stab}");
}
}
}

View File

@@ -10,18 +10,19 @@ namespace pk3DS
{
public partial class MEE : Form
{
private string[] files = Directory.GetFiles("megaevo");
private string[] forms = Main.getText((Main.oras) ? 5 : 5);
private string[] types = Main.getText((Main.oras) ? 18 : 17);
private string[] specieslist = Main.getText((Main.oras) ? 98 : 80);
private string[] itemlist = Main.getText((Main.oras) ? 114 : 96);
private byte[] personalData = File.ReadAllBytes(Directory.GetFiles("personal").Last());
private GroupBox[] groupbox_spec;
private ComboBox[] forme_spec, item_spec;
private CheckBox[] checkbox_spec;
private PictureBox[][] picturebox_spec;
private readonly string[] files = Directory.GetFiles("megaevo");
private readonly string[] forms = Main.getText(Main.oras ? 5 : 5);
private readonly string[] types = Main.getText(Main.oras ? 18 : 17);
private readonly string[] specieslist = Main.getText(Main.oras ? 98 : 80);
private readonly string[] itemlist = Main.getText(Main.oras ? 114 : 96);
private readonly byte[] personalData = File.ReadAllBytes(Directory.GetFiles("personal").Last());
private readonly GroupBox[] groupbox_spec;
private readonly ComboBox[] forme_spec;
private readonly ComboBox[] item_spec;
private readonly CheckBox[] checkbox_spec;
private readonly PictureBox[][] picturebox_spec;
private bool loaded;
private string[][] AltForms;
private readonly string[][] AltForms;
int entry = -1;
public MEE() //All the initial settings
@@ -112,7 +113,7 @@ private void getEntry()
me = new MegaEvolutions(data);
for (int i = 0; i < 3; i++)
{
checkbox_spec[i].Checked = (me.Method[i] == 1);
checkbox_spec[i].Checked = me.Method[i] == 1;
item_spec[i].SelectedValue = (int)me.Argument[i];
forme_spec[i].SelectedIndex = me.Form[i];
}
@@ -124,7 +125,7 @@ private void setEntry()
{
if (me.Method[i] > 1)
return; // Shouldn't hit this.
me.Method[i] = (ushort)((checkbox_spec[i].Checked) ? 1 : 0);
me.Method[i] = (ushort)(checkbox_spec[i].Checked ? 1 : 0);
me.Argument[i] = (ushort)Util.getIndex(item_spec[i]);
me.Form[i] = (ushort)forme_spec[i].SelectedIndex;
}
@@ -140,7 +141,7 @@ private void Update_PBs(object sender, EventArgs e)
if (CB.Checked)
{
UpdateImage(picturebox_spec[0][i], entry, 0, Util.getIndex(item_spec[i]), 0);
UpdateImage(picturebox_spec[1][i], entry, (forme_spec[i]).SelectedIndex, Util.getIndex(item_spec[i]), 0);
UpdateImage(picturebox_spec[1][i], entry, forme_spec[i].SelectedIndex, Util.getIndex(item_spec[i]), 0);
}
else
{
@@ -157,7 +158,7 @@ private void Update_PBs(int i)
if (CB.Checked)
{
UpdateImage(picturebox_spec[0][i], entry, 0, Util.getIndex(item_spec[i]), 0);
UpdateImage(picturebox_spec[1][i], entry, (forme_spec[i]).SelectedIndex, Util.getIndex(item_spec[i]), 0);
UpdateImage(picturebox_spec[1][i], entry, forme_spec[i].SelectedIndex, Util.getIndex(item_spec[i]), 0);
}
else
{
@@ -196,7 +197,7 @@ private void B_Dump_Click(object sender, EventArgs e)
{
if (!checkbox_spec[j].Checked) continue;
if (!headered) { result += header; headered = true; }
result += String.Format("Can Mega Evolve into {1} if its held item is {0}." + Environment.NewLine, itemlist[(int)item_spec[j].SelectedValue], forme_spec[j].Text);
result += string.Format("Can Mega Evolve into {1} if its held item is {0}." + Environment.NewLine, itemlist[(int)item_spec[j].SelectedValue], forme_spec[j].Text);
}
if (headered)

View File

@@ -14,23 +14,24 @@ public MaisonEditor(bool super)
Array.Resize(ref specieslist, 722);
movelist[0] = specieslist[0] = itemlist[0] = "";
trFiles = Directory.GetFiles((super) ? "maisontrS" : "maisontrN");
pkFiles = Directory.GetFiles((super) ? "maisonpkS" : "maisonpkN");
trFiles = Directory.GetFiles(super ? "maisontrS" : "maisontrN");
pkFiles = Directory.GetFiles(super ? "maisonpkS" : "maisonpkN");
int trTXTFile = (Main.oras) ? 153 : 130;
trNames = Main.getText((super) ? trTXTFile : trTXTFile + 1); Array.Resize(ref trNames, trFiles.Length);
int trTXTFile = Main.oras ? 153 : 130;
trNames = Main.getText(super ? trTXTFile : trTXTFile + 1); Array.Resize(ref trNames, trFiles.Length);
InitializeComponent();
Setup();
}
string[] trFiles;
string[] trNames;
string[] pkFiles;
string[] natures = Main.getText((Main.oras) ? 51 : 47);
string[] movelist = Main.getText((Main.oras) ? 14 : 13);
string[] specieslist = Main.getText((Main.oras) ? 98 : 80);
string[] trClass = Main.getText((Main.oras) ? 21 : 20);
string[] itemlist = Main.getText((Main.oras) ? 114 : 96);
readonly string[] trFiles;
readonly string[] trNames;
readonly string[] pkFiles;
readonly string[] natures = Main.getText(Main.oras ? 51 : 47);
readonly string[] movelist = Main.getText(Main.oras ? 14 : 13);
readonly string[] specieslist = Main.getText(Main.oras ? 98 : 80);
readonly string[] trClass = Main.getText(Main.oras ? 21 : 20);
readonly string[] itemlist = Main.getText(Main.oras ? 114 : 96);
int trEntry = -1;
int pkEntry = -1;
bool dumping;
@@ -225,20 +226,20 @@ private void B_DumpPKs_Click(object sender, EventArgs e)
if (CB_Species.SelectedIndex > 0)
{
result += "======" + Environment.NewLine + i + " - " + CB_Species.Text + Environment.NewLine + "======" + Environment.NewLine;
result += String.Format("Held Item: {0}" + Environment.NewLine, CB_Item.Text);
result += String.Format("Nature: {0}" + Environment.NewLine, CB_Nature.Text);
result += String.Format("Move 1: {0}" + Environment.NewLine, CB_Move1.Text);
result += String.Format("Move 2: {0}" + Environment.NewLine, CB_Move2.Text);
result += String.Format("Move 3: {0}" + Environment.NewLine, CB_Move3.Text);
result += String.Format("Move 4: {0}" + Environment.NewLine, CB_Move4.Text);
result += string.Format("Held Item: {0}" + Environment.NewLine, CB_Item.Text);
result += string.Format("Nature: {0}" + Environment.NewLine, CB_Nature.Text);
result += string.Format("Move 1: {0}" + Environment.NewLine, CB_Move1.Text);
result += string.Format("Move 2: {0}" + Environment.NewLine, CB_Move2.Text);
result += string.Format("Move 3: {0}" + Environment.NewLine, CB_Move3.Text);
result += string.Format("Move 4: {0}" + Environment.NewLine, CB_Move4.Text);
result += "EV'd in: ";
result += (CHK_HP.Checked) ? "HP, " : "";
result += (CHK_ATK.Checked) ? "ATK, " : "";
result += (CHK_DEF.Checked) ? "DEF, " : "";
result += (CHK_SpA.Checked) ? "SpA, " : "";
result += (CHK_SpD.Checked) ? "SpD, " : "";
result += (CHK_Spe.Checked) ? "Spe, " : "";
result += CHK_HP.Checked ? "HP, " : "";
result += CHK_ATK.Checked ? "ATK, " : "";
result += CHK_DEF.Checked ? "DEF, " : "";
result += CHK_SpA.Checked ? "SpA, " : "";
result += CHK_SpD.Checked ? "SpD, " : "";
result += CHK_Spe.Checked ? "Spe, " : "";
result += Environment.NewLine;
result += Environment.NewLine;

View File

@@ -15,14 +15,14 @@ public MapPermView()
MapGRs = Directory.GetFiles("mapGR");
}
private string[] MapMatrixes;
private string[] MapGRs;
private readonly string[] MapMatrixes;
private readonly string[] MapGRs;
public int mapScale = -1;
public int DrawMap = -1;
public void drawMap(int Map)
{
DrawMap = Map;
PB_Map.Image = (CHK_AutoDraw.Checked) ? getMapImage(sliceArea: true) : null;
PB_Map.Image = CHK_AutoDraw.Checked ? getMapImage(sliceArea: true) : null;
}
public Bitmap getMapImage(bool crop = false, bool entity = true, bool sliceArea = false)
{
@@ -49,7 +49,7 @@ public Bitmap getMapImage(bool crop = false, bool entity = true, bool sliceArea
if (sliceArea && mapScale > 3)
{
int area = (40*mapScale);
int area = 40*mapScale;
for (int x = 0; x < img.Width; x++)
for (int y = 0; y < img.Height; y++)
if ((x % area == 0) || (y % area == 0))
@@ -93,7 +93,7 @@ private Bitmap overlayEntities(Bitmap img)
int y = (int)e.pY; // shifted warps look weird
for (int sx = 0; sx < e.Width; sx++) // Stretch X
for (int sy = 0; sy < e.Height; sy++) // Stretch Y
try { Util.LayerImage(img, Resources.W, ((x + sx) * mapScale), ((y + sy) * mapScale), opacity); }
try { Util.LayerImage(img, Resources.W, (x + sx) * mapScale, (y + sy) * mapScale, opacity); }
catch { }
}
foreach (var e in OWSE.CurrentZone.Entities.Triggers1)
@@ -145,8 +145,8 @@ private void hoverMap(object sender, MouseEventArgs e)
if (PB_Map.Image == null)
return;
int X = e.X / (mapScale);
int Y = e.Y / (mapScale);
int X = e.X / mapScale;
int Y = e.Y / mapScale;
int entryX = X/40;
int entryY = Y/40;
@@ -157,11 +157,11 @@ private void hoverMap(object sender, MouseEventArgs e)
int tile = epY * 40 + epX;
try
{
var tileVal = (OWSE.mm.Entries[entry] == null)
var tileVal = OWSE.mm.Entries[entry] == null
? "No Tile"
: OWSE.mm.Entries[entry].Tiles[tile].ToString("X8");
L_MapCoord.Text = String.Format("V:0x{3}{2}X:{0,3} Y:{1,3}", X, Y, Environment.NewLine, tileVal);
L_MapCoord.Text = string.Format("V:0x{3}{2}X:{0,3} Y:{1,3}", X, Y, Environment.NewLine, tileVal);
}
catch { }
}

View File

@@ -21,11 +21,12 @@ public Mart()
foreach (string s in locations) CB_Location.Items.Add(s);
CB_Location.SelectedIndex = 0;
}
string codebin;
string[] itemlist = Main.getText((Main.oras) ? 114 : 96);
byte[] data;
private byte[] entries = Main.oras
readonly string codebin;
readonly string[] itemlist = Main.getText(Main.oras ? 114 : 96);
readonly byte[] data;
private readonly byte[] entries = Main.oras
? new byte[] // ORAS
{
3, 10, 14, 17, 18, 19, 19, 19, 19, // General
@@ -50,9 +51,10 @@ public Mart()
3, // Balls
};
private int offset = Main.oras ? 0x0047AB58 : 0x0043C89E;
private readonly int offset = Main.oras ? 0x0047AB58 : 0x0043C89E;
int dataoffset;
string[] locations = Main.oras
readonly string[] locations = Main.oras
? new[] // ORAS
{
"No Badges", "1 Badge", "2 Badges", "3 Badges", "4 Badges", "5 Badges", "6 Badges", "7 Badges", "8 Badges",

View File

@@ -19,19 +19,21 @@ public Moves()
Setup();
}
string[] files = Directory.GetFiles("move");
string[] types = Main.getText((Main.oras) ? 18 : 17);
string[] moveflavor = Main.getText((Main.oras) ? 16 : 15);
string[] movelist = Main.getText((Main.oras) ? 14 : 13);
string[] sortedmoves;
string[] MoveCategories = { "Status", "Physical", "Special", };
string[] StatCategories = { "None", "Attack", "Defense", "Special Attack", "Special Defense", "Speed", "Accuracy", "Evasion", "All", };
string[] TargetingTypes =
readonly string[] types = Main.getText(Main.oras ? 18 : 17);
readonly string[] moveflavor = Main.getText(Main.oras ? 16 : 15);
readonly string[] movelist = Main.getText(Main.oras ? 14 : 13);
readonly string[] sortedmoves;
readonly string[] MoveCategories = { "Status", "Physical", "Special", };
readonly string[] StatCategories = { "None", "Attack", "Defense", "Special Attack", "Special Defense", "Speed", "Accuracy", "Evasion", "All", };
readonly string[] TargetingTypes =
{ "Single Adjacent Ally/Foe",
"Any Ally", "Any Adjacent Ally", "Single Adjacent Foe", "Everyone but User", "All Foes",
"All Allies", "Self", "All Pokemon on Field", "Single Adjacent Foe (2)", "Entire Field",
"Opponent's Field", "User's Field", "Self",
};
string[] InflictionTypes =
readonly string[] InflictionTypes =
{ "None",
"Paralyze", "Sleep", "Freeze", "Burn", "Poison",
"Confusion", "Attract", "Capture", "Nightmare", "Curse",
@@ -39,7 +41,8 @@ public Moves()
"?", "Detect", "Leech Seed", "Embargo", "Perish Song",
"Ingrain",
};
string[] MoveQualities =
readonly string[] MoveQualities =
{ "Only DMG",
"No DMG -> Inflict Status", "No DMG -> -Target/+User Stat", "No DMG | Heal User", "DMG | Inflict Status", "No DMG | STATUS | +Target Stat",
"DMG | -Target Stat", "DMG | +User Stat", "DMG | Absorbs DMG", "One-Hit KO", "Affects Whole Field",
@@ -86,7 +89,7 @@ private void getEntry()
NUD_HitMin.Value = data[0x7] & 0xF;
NUD_HitMax.Value = data[0x7] >> 4;
short inflictVal = BitConverter.ToInt16(data, 0x08);
CB_Inflict.SelectedIndex = (inflictVal < 0) ? CB_Inflict.Items.Count - 1 : inflictVal;
CB_Inflict.SelectedIndex = inflictVal < 0 ? CB_Inflict.Items.Count - 1 : inflictVal;
NUD_Inflict.Value = data[0xA];
NUD_0xB.Value = data[0xB]; // 0xB ~ Something to deal with skipImmunity
NUD_TurnMin.Value = data[0xC];
@@ -130,7 +133,7 @@ private void setEntry()
data[0x03] = (byte)NUD_Power.Value;
data[0x04] = (byte)NUD_Accuracy.Value;
data[0x05] = (byte)NUD_PP.Value;
data[0x06] = (byte)((int)NUD_Priority.Value);
data[0x06] = (byte)(int)NUD_Priority.Value;
data[0x07] = (byte)((byte)NUD_HitMin.Value | ((byte)NUD_HitMax.Value << 4));
int inflictval = CB_Inflict.SelectedIndex; if (inflictval == CB_Inflict.Items.Count) inflictval = -1;
Array.Copy(BitConverter.GetBytes((short)inflictval), 0, data, 0x08, 2);
@@ -141,15 +144,15 @@ private void setEntry()
data[0x0E] = (byte)NUD_CritStage.Value;
data[0x0F] = (byte)NUD_Flinch.Value;
Array.Copy(BitConverter.GetBytes((ushort)NUD_Effect.Value), 0, data, 0x10, 2);
data[0x12] = (byte)((int)NUD_Recoil.Value);
data[0x12] = (byte)(int)NUD_Recoil.Value;
data[0x13] = (byte)NUD_Heal.Value;
data[0x14] = (byte)CB_Targeting.SelectedIndex;
data[0x15] = (byte)CB_Stat1.SelectedIndex;
data[0x16] = (byte)CB_Stat2.SelectedIndex;
data[0x17] = (byte)CB_Stat3.SelectedIndex;
data[0x18] = (byte)((int)NUD_Stat1.Value);
data[0x19] = (byte)((int)NUD_Stat2.Value);
data[0x1A] = (byte)((int)NUD_Stat3.Value);
data[0x18] = (byte)(int)NUD_Stat1.Value;
data[0x19] = (byte)(int)NUD_Stat2.Value;
data[0x1A] = (byte)(int)NUD_Stat3.Value;
data[0x1B] = (byte)NUD_StatP1.Value;
data[0x1C] = (byte)NUD_StatP2.Value;
data[0x1D] = (byte)NUD_StatP3.Value;

View File

@@ -32,11 +32,11 @@ public OPower()
Util.Alert("More research is required for giving S/MAX O-Powers ingame.");
}
private string codebin;
private int offset;
private byte[] exefsData;
private byte[][] powerData = new byte[65][];
private string[] powerFlavor = Main.getText((Main.oras) ? 165 : 141);
private readonly string codebin;
private readonly int offset;
private readonly byte[] exefsData;
private readonly byte[][] powerData = new byte[65][];
private readonly string[] powerFlavor = Main.getText(Main.oras ? 165 : 141);
int entry = -1;
private void changeEntry(object sender, EventArgs e)

View File

@@ -24,7 +24,7 @@ public OWSE()
mapView.Show();
tb_Zone.SelectedIndex = 1; // Show Overworlds tab
}
private string[] gameLocations = Main.getText((Main.oras) ? 90 : 72);
private readonly string[] gameLocations = Main.getText(Main.oras ? 90 : 72);
private string[] filepaths;
private string[] encdatapaths;
private byte[] masterZoneData;
@@ -38,7 +38,7 @@ public OWSE()
// Map Viewer References
internal static Zone CurrentZone;
internal static MapMatrix mm;
private MapPermView mapView = new MapPermView();
private readonly MapPermView mapView = new MapPermView();
private void openQuick(string[] encdata)
{
@@ -60,7 +60,7 @@ private void openQuick(string[] encdata)
int LocationNum = Convert.ToInt16(name.Substring(4, name.Length - 4));
ZoneData zo = new ZoneData(masterZoneData.Skip(f * ZoneData.Size).Take(ZoneData.Size).ToArray());
string LocationName = gameLocations[zo.ParentMap];
zdLocations[f] = (LocationNum.ToString("000") + " - " + LocationName);
zdLocations[f] = LocationNum.ToString("000") + " - " + LocationName;
rawLocations[f] = LocationName;
}
@@ -154,7 +154,7 @@ private void getZoneData()
L_ZDPreview.Text = "Text File: " + CurrentZone.ZD.TextFile
+ Environment.NewLine + "Map File: " + CurrentZone.ZD.MapMatrix;
L_ZD.Text = String.Format("X: {0,5}{3}Y: {1,5}{3}Z:{2,6}{3}{3}X: {4,5}{3}Y: {5,5}{3}Z:{6,6}", CurrentZone.ZD.pX, CurrentZone.ZD.pY,
L_ZD.Text = string.Format("X: {0,5}{3}Y: {1,5}{3}Z:{2,6}{3}{3}X: {4,5}{3}Y: {5,5}{3}Z:{6,6}", CurrentZone.ZD.pX, CurrentZone.ZD.pY,
CurrentZone.ZD.Z, Environment.NewLine, CurrentZone.ZD.pX2, CurrentZone.ZD.pY2,
CurrentZone.ZD.Z2);
@@ -181,11 +181,11 @@ private void getOWSData()
NUD_UnkCount.Value = CurrentZone.Entities.UnknownCount; changeUnkCount(null, null);
// Collect/Load Data
NUD_FE.Value = (NUD_FE.Maximum < 0) ? -1 : 0; changeFurniture(null, null);
NUD_NE.Value = (NUD_NE.Maximum < 0) ? -1 : 0; changeNPC(null, null);
NUD_WE.Value = (NUD_WE.Maximum < 0) ? -1 : 0; changeWarp(null, null);
NUD_TE.Value = (NUD_TE.Maximum < 0) ? -1 : 0; changeTrigger1(null, null);
NUD_UE.Value = (NUD_UE.Maximum < 0) ? -1 : 0; changeTrigger2(null, null);
NUD_FE.Value = NUD_FE.Maximum < 0 ? -1 : 0; changeFurniture(null, null);
NUD_NE.Value = NUD_NE.Maximum < 0 ? -1 : 0; changeNPC(null, null);
NUD_WE.Value = NUD_WE.Maximum < 0 ? -1 : 0; changeWarp(null, null);
NUD_TE.Value = NUD_TE.Maximum < 0 ? -1 : 0; changeTrigger1(null, null);
NUD_UE.Value = NUD_UE.Maximum < 0 ? -1 : 0; changeTrigger2(null, null);
// Process Scripts
var script = CurrentZone.Entities.Script;
@@ -246,7 +246,7 @@ internal static void toggleEnable(NumericUpDown master, NumericUpDown slave, Gro
{
slave.Maximum = master.Value - 1;
slave.Enabled = display.Visible = slave.Maximum > -1;
slave.Minimum = (slave.Enabled) ? 0 : -1;
slave.Minimum = slave.Enabled ? 0 : -1;
}
private void changeFurnitureCount(object sender, EventArgs e)
{
@@ -361,9 +361,9 @@ private void getNPC()
// Uneditables
TB_NDeg.Text = NPC.Deg18.ToString();
TB_Leash.Text = (NPC.L1 == NPC.L2 && NPC.L2 == NPC.L3 && NPC.L3 == -1)
TB_Leash.Text = NPC.L1 == NPC.L2 && NPC.L2 == NPC.L3 && NPC.L3 == -1
? TB_Leash.Text = "No Leash!"
: String.Format("{0}, {1}, {2} -- {3}", NPC.L1, NPC.L2, NPC.L3, NPC.LDir);
: $"{NPC.L1}, {NPC.L2}, {NPC.L3} -- {NPC.LDir}";
RTB_N.Text = Util.getHexString(NPC.Raw);
}
@@ -479,7 +479,7 @@ private void setTrigger2()
// Overworld User Enhancements
private void changeNPC_ID(object sender, EventArgs e)
{
L_NID.ForeColor = (NUD_NID.Value != NUD_NE.Value) ? Color.Red : Color.Black;
L_NID.ForeColor = NUD_NID.Value != NUD_NE.Value ? Color.Red : Color.Black;
}
private void changeNPC_Model(object sender, EventArgs e)
{
@@ -507,7 +507,7 @@ private void changeWarp_Y(object sender, EventArgs e)
private void B_HLCMD_Click(object sender, EventArgs e)
{
int ctr = Util.highlightText(RTB_OSP, "**", Color.Red) + Util.highlightText(RTB_MSP, "**", Color.Red) / 2;
Util.Alert(String.Format("{0} instance{1} of \"*\" present.", ctr, ctr > 1 ? "s" : ""));
Util.Alert($"{ctr} instance{(ctr > 1 ? "s" : "")} of \"*\" present.");
}
private void tabMain_DragEnter(object sender, DragEventArgs e)
{
@@ -695,10 +695,10 @@ private void B_DumpMaps_Click(object sender, EventArgs e)
//error will throw from here
img.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
byte[] data = ms.ToArray();
File.WriteAllBytes(Path.Combine(folder, String.Format("{0} ({1}).png", zdLocations[i].Replace('?', '-'), i)), data);
File.WriteAllBytes(Path.Combine(folder, $"{zdLocations[i].Replace('?', '-')} ({i}).png"), data);
}
string l = mm.EntryList.Where(t => t != 0xFFFF).Aggregate("", (current, t) => current + t.ToString("000" + " "));
result[i] = String.Format("{0}\t{1}\t{2}", i.ToString("000"), CB_LocationID.Items[i], l);
result[i] = $"{i.ToString("000")}\t{CB_LocationID.Items[i]}\t{l}";
}
if (Util.Prompt(MessageBoxButtons.YesNoCancel, "Write Map parse output?") == DialogResult.Yes)
File.WriteAllLines("MapLocations.txt", result);

View File

@@ -57,7 +57,7 @@ internal static bool patchExeFS(string path, string[] oldstr, string[] newstr, s
if (ctr == 0)
{ result = "Did not find the old path strings to replace."; return false; }
result += String.Format("Redirected {0} file paths.", ctr);
result += $"Redirected {ctr} file paths.";
Directory.CreateDirectory(Directory.GetParent(outPath).Name);
File.WriteAllText(outPath ?? path, text, Encoding.Unicode);
return true;
@@ -79,7 +79,7 @@ internal static string exportGARCs(string[] garcPaths, string[] newPaths, string
private void B_PatchCIA_Click(object sender, EventArgs e)
{
string patchFolder = String.Format("{0} ({1})", "Patch", (DateTime.Now).ToString("yy-MM-dd@HH-mm-ss"));
string patchFolder = $"{"Patch"} ({DateTime.Now.ToString("yy-MM-dd@HH-mm-ss")})";
try
{
string[] garcs = getGARCs();
@@ -96,7 +96,7 @@ private void B_PatchCIA_Click(object sender, EventArgs e)
for (int i = 0; i < newPaths.Length; i++)
{
int posA = newPaths[i].LastIndexOf(oldA, StringComparison.Ordinal);
newPaths[i] = (posA == -1) ? null : newPaths[i].Remove(posA, oldA.Length).Insert(posA, newA);
newPaths[i] = posA == -1 ? null : newPaths[i].Remove(posA, oldA.Length).Insert(posA, newA);
}
string result = "";
string ExeFS = Directory.GetFiles(Main.ExeFSPath)[0];

View File

@@ -27,8 +27,8 @@ public Personal()
CB_Species.SelectedIndex = 1;
}
#region Global Variables
private string[] paths = Directory.GetFiles("personal", "*.*", SearchOption.TopDirectoryOnly);
private string mode = (Main.oras) ? "ORAS" : "XY";
private readonly string[] paths = Directory.GetFiles("personal", "*.*", SearchOption.TopDirectoryOnly);
private readonly string mode = Main.oras ? "ORAS" : "XY";
private string[] items = { };
private string[] moves = { };
@@ -36,16 +36,16 @@ public Personal()
private string[] abilities = { };
private string[] forms = { };
private byte[] data = { };
private readonly byte[] data = { };
private ComboBox[] helditem_boxes;
private ComboBox[] ability_boxes;
private ComboBox[] typing_boxes;
private ComboBox[] eggGroup_boxes;
private readonly ComboBox[] helditem_boxes;
private readonly ComboBox[] ability_boxes;
private readonly ComboBox[] typing_boxes;
private readonly ComboBox[] eggGroup_boxes;
private MaskedTextBox[] byte_boxes;
private MaskedTextBox[] ev_boxes;
private CheckBox[] rstat_boxes;
private readonly MaskedTextBox[] byte_boxes;
private readonly MaskedTextBox[] ev_boxes;
private readonly CheckBox[] rstat_boxes;
public string[] types = { };
@@ -67,17 +67,17 @@ public Personal()
public ushort[] tutor4 = { 380, 388, 180, 495, 270, 271, 478, 472, 283, 200, 278, 289, 446, 214, 285 };
private string[][] AltForms;
int entrysize = (Main.oras) ? 0x50 : 0x40;
int entrysize = Main.oras ? 0x50 : 0x40;
int entry = -1;
#endregion
private void Setup()
{
abilities = Main.getText((Main.oras) ? 37 : 34);
moves = Main.getText((Main.oras) ? 14 : 13);
items = Main.getText((Main.oras) ? 114 : 96);
species = Main.getText((Main.oras) ? 98 : 80);
types = Main.getText((Main.oras) ? 18 : 17);
forms = Main.getText((Main.oras) ? 5 : 5);
abilities = Main.getText(Main.oras ? 37 : 34);
moves = Main.getText(Main.oras ? 14 : 13);
items = Main.getText(Main.oras ? 114 : 96);
species = Main.getText(Main.oras ? 98 : 80);
types = Main.getText(Main.oras ? 18 : 17);
forms = Main.getText(Main.oras ? 5 : 5);
species[0] = "---";
abilities[0] = items[0] = moves[0] = "";
AltForms = getFormList(data, Main.oras, species, forms, types, items);
@@ -87,7 +87,7 @@ private void Setup()
ushort[] HMs = new ushort[0];
TMHM.getTMHMList(Main.oras, ref TMs, ref HMs);
CLB_TMHM.Items.Clear();
int hmcount = (Main.oras) ? 7 : 5;
int hmcount = Main.oras ? 7 : 5;
if (TMs.Length == 0) // No ExeFS to grab TMs from.
{
@@ -99,9 +99,9 @@ private void Setup()
else // Use TMHM moves.
{
for (int i = 1; i <= 100; i++)
CLB_TMHM.Items.Add(String.Format("TM{0} {1}", i.ToString("00"), moves[TMs[i - 1]]));
CLB_TMHM.Items.Add($"TM{i.ToString("00")} {moves[TMs[i - 1]]}");
for (int i = 1; i <= hmcount; i++)
CLB_TMHM.Items.Add(String.Format("HM{0} {1}", i.ToString("00"), moves[HMs[i - 1]]));
CLB_TMHM.Items.Add($"HM{i.ToString("00")} {moves[HMs[i - 1]]}");
}
for (int i = 0; i < tutormoves.Length - 1; i++)
CLB_MoveTutors.Items.Add(moves[tutormoves[i]]);
@@ -141,7 +141,7 @@ private void Setup()
L_ORASTutors.Visible = true;
}
for (int i = 0; i < species.Length; i++)
CB_Species.Items.Add(String.Format("{0} - {1}", species[i], i.ToString("000")));
CB_Species.Items.Add($"{species[i]} - {i.ToString("000")}");
foreach (ComboBox cb in helditem_boxes)
foreach (string it in items)
@@ -176,7 +176,7 @@ private void ByteLimiter(object sender, EventArgs e)
{
MaskedTextBox mtb = sender as MaskedTextBox;
int val;
Int32.TryParse(mtb.Text, out val);
int.TryParse(mtb.Text, out val);
if (Array.IndexOf(byte_boxes, mtb) > -1 && val > 255)
mtb.Text = "255";
else if (Array.IndexOf(ev_boxes, mtb) > -1 && val > 3)
@@ -230,7 +230,7 @@ private void readInfo()
TB_FormeSprite.Text = pkm.FormeSprite.ToString("000");
TB_RawColor.Text = pkm.Color.ToString("000");
CB_Color.SelectedIndex = (pkm.Color & 0xF);
CB_Color.SelectedIndex = pkm.Color & 0xF;
TB_BaseExp.Text = pkm.BaseEXP.ToString("000");
@@ -258,7 +258,7 @@ private void readEntry()
if (dumping) return;
int[] specForm = getSpecies(data, Main.oras, CB_Species.SelectedIndex);
string filename = "_" + specForm[0] + ((CB_Species.SelectedIndex > 721) ? "_" + (specForm[1] + 1) : "");
string filename = "_" + specForm[0] + (CB_Species.SelectedIndex > 721 ? "_" + (specForm[1] + 1) : "");
Bitmap rawImg = (Bitmap)Resources.ResourceManager.GetObject(filename);
Bitmap bigImg = new Bitmap(rawImg.Width * 2, rawImg.Height * 2);
for (int x = 0; x < rawImg.Width; x++)
@@ -347,7 +347,7 @@ private void B_Randomize_Click(object sender, EventArgs e)
const int TMPercent = 35; // Average Learnable TMs is 35.260.
const int TutorPercent = 2; //136 special tutor moves learnable by species in Untouched ORAS.
const int OrasTutorPercent = 30; //10001 tutor moves learnable by 826 species in Untouched ORAS.
ushort[] itemlist = (Main.oras) ? Legal.Pouch_Items_ORAS : Legal.Pouch_Items_XY;
ushort[] itemlist = Main.oras ? Legal.Pouch_Items_ORAS : Legal.Pouch_Items_XY;
ushort[] berrylist = Legal.Pouch_Berry_XY;
Array.Resize(ref itemlist, itemlist.Length + berrylist.Length);
Array.Copy(berrylist, 0, itemlist, itemlist.Length - berrylist.Length, berrylist.Length);
@@ -371,7 +371,7 @@ private void B_Randomize_Click(object sender, EventArgs e)
{
for (int t = 0; t < CLB_MoveTutors.Items.Count; t++)
CLB_MoveTutors.SetItemCheckState(t, rnd.Next(0, 100) < TutorPercent ? CheckState.Checked : CheckState.Unchecked);
if ((Main.oras) && (CB_Species.SelectedIndex == 384 || CB_Species.SelectedIndex == 814)) //Make sure Rayquaza can learn Dragon Ascent.
if (Main.oras && (CB_Species.SelectedIndex == 384 || CB_Species.SelectedIndex == 814)) //Make sure Rayquaza can learn Dragon Ascent.
CLB_MoveTutors.SetItemCheckState(CLB_MoveTutors.Items.Count-1, CheckState.Checked);
}
if (Main.oras && CHK_ORASTutors.Checked)
@@ -421,9 +421,9 @@ private void B_Randomize_Click(object sender, EventArgs e)
// Items
if (CHK_Item.Checked)
{
CB_HeldItem1.SelectedIndex = (CB_HeldItem1.SelectedIndex > 0) ? itemlist[rnd.Next(1, itemlen)] : 0;
CB_HeldItem2.SelectedIndex = (CB_HeldItem2.SelectedIndex > 0) ? itemlist[rnd.Next(1, itemlen)] : 0;
CB_HeldItem3.SelectedIndex = (CB_HeldItem3.SelectedIndex > 0) ? itemlist[rnd.Next(1, itemlen)] : 0;
CB_HeldItem1.SelectedIndex = CB_HeldItem1.SelectedIndex > 0 ? itemlist[rnd.Next(1, itemlen)] : 0;
CB_HeldItem2.SelectedIndex = CB_HeldItem2.SelectedIndex > 0 ? itemlist[rnd.Next(1, itemlen)] : 0;
CB_HeldItem3.SelectedIndex = CB_HeldItem3.SelectedIndex > 0 ? itemlist[rnd.Next(1, itemlen)] : 0;
}
// Type
@@ -477,15 +477,17 @@ private void B_Dump_Click(object sender, EventArgs e)
CB_Species.SelectedIndex = i; // Get new Species
result += "======" + Environment.NewLine + entry + " " + CB_Species.Text + Environment.NewLine + "======" + Environment.NewLine;
result += String.Format("Base Stats: {0}.{1}.{2}.{3}.{4}.{5} (BST: {6})", TB_BaseHP.Text, TB_BaseATK.Text, TB_BaseDEF.Text, TB_BaseSPA.Text, TB_BaseSPD.Text, TB_BaseSPE.Text, pkm.BST) + Environment.NewLine;
result += String.Format("EV Yield: {0}.{1}.{2}.{3}.{4}.{5}", TB_HPEVs.Text, TB_ATKEVs.Text, TB_DEFEVs.Text, TB_SPAEVs.Text, TB_SPDEVs.Text, TB_SPEEVs.Text) + Environment.NewLine;
result += String.Format("Abilities: {0} (1) | {1} (2) | {2} (H)", CB_Ability1.Text, CB_Ability2.Text, CB_Ability3.Text) + Environment.NewLine;
result +=
$"Base Stats: {TB_BaseHP.Text}.{TB_BaseATK.Text}.{TB_BaseDEF.Text}.{TB_BaseSPA.Text}.{TB_BaseSPD.Text}.{TB_BaseSPE.Text} (BST: {pkm.BST})" + Environment.NewLine;
result +=
$"EV Yield: {TB_HPEVs.Text}.{TB_ATKEVs.Text}.{TB_DEFEVs.Text}.{TB_SPAEVs.Text}.{TB_SPDEVs.Text}.{TB_SPEEVs.Text}" + Environment.NewLine;
result += $"Abilities: {CB_Ability1.Text} (1) | {CB_Ability2.Text} (2) | {CB_Ability3.Text} (H)" + Environment.NewLine;
result += String.Format(((CB_Type1.SelectedIndex != CB_Type2.SelectedIndex) ? "Type: {0} / {1}" : "Type: {0}"), CB_Type1.Text, CB_Type2.Text);
result += string.Format(CB_Type1.SelectedIndex != CB_Type2.SelectedIndex ? "Type: {0} / {1}" : "Type: {0}", CB_Type1.Text, CB_Type2.Text);
result += String.Format("Item 1 (50%): {0}", CB_HeldItem1.Text) + Environment.NewLine;
result += String.Format("Item 2 (5%): {0}", CB_HeldItem2.Text) + Environment.NewLine;
result += String.Format("Item 3 (1%): {0}", CB_HeldItem3.Text) + Environment.NewLine;
result += $"Item 1 (50%): {CB_HeldItem1.Text}" + Environment.NewLine;
result += $"Item 2 (5%): {CB_HeldItem2.Text}" + Environment.NewLine;
result += $"Item 3 (1%): {CB_HeldItem3.Text}" + Environment.NewLine;
// I don't want to add anything else. Should be pretty easy for anyone else to expand.
result += Environment.NewLine;
@@ -520,7 +522,7 @@ private void formClosing(object sender, FormClosingEventArgs e)
// Utility (Shared)
internal static int[] getSpecies(byte[] data, bool oras, int PersonalEntry)
{
int entrysize = (oras) ? 0x50 : 0x40;
int entrysize = oras ? 0x50 : 0x40;
if (PersonalEntry < 722) return new[] { PersonalEntry, 0 };
for (int i = 0; i < 722; i++)
@@ -540,14 +542,14 @@ internal static string[][] getFormList(byte[] data, bool oras, string[] species,
try
{
string[][] FormList = new string[722][];
int entrysize = (oras) ? 0x50 : 0x40;
int entrysize = oras ? 0x50 : 0x40;
int AltFormOfs = 723; //null + 721 species + 1 gap
for (int i = 0; i < 722; i++) //Hardcode 721 species + null
{
int FormCount = data[i * entrysize + 0x20]; // Mons with no alt forms have a FormCount of 1.
FormList[i] = new string[FormCount];
if (FormCount <= 0) continue;
FormList[i][0] = (forms[i] == "") ? species[i] : forms[i];
FormList[i][0] = forms[i] == "" ? species[i] : forms[i];
for (int j = 1; j < FormCount; j++)
FormList[i][j] = forms[AltFormOfs++];
}
@@ -570,7 +572,7 @@ internal static string[][] getFormList(byte[] data, bool oras, string[] species,
}
internal static string[] getPersonalEntryList(byte[] data, bool oras, string[][] AltForms, string[] species)
{
int entrysize = (oras) ? 0x50 : 0x40;
int entrysize = oras ? 0x50 : 0x40;
string[] result = new string[data.Length / entrysize];
for (int i = 0; i < 722; i++)
{
@@ -586,7 +588,7 @@ internal static string[] getPersonalEntryList(byte[] data, bool oras, string[][]
internal static ushort[] getPersonalIndexList(byte[] data, bool oras)
{
ushort[] result = new ushort[722];
int entrysize = (oras) ? 0x50 : 0x40;
int entrysize = oras ? 0x50 : 0x40;
for (int i = 0; i < result.Length; i++)
result[i] = BitConverter.ToUInt16(data, entrysize * i + 0x1C);
return result;
@@ -611,10 +613,10 @@ internal static void setForms(int species, ComboBox cb, string[][] AltForms)
internal static string[] getSpeciesIndexStrings(bool oras)
{
string[] items = Main.getText((Main.oras) ? 114 : 96);
string[] species = Main.getText((Main.oras) ? 98 : 80);
string[] types = Main.getText((Main.oras) ? 18 : 17);
string[] forms = Main.getText((Main.oras) ? 5 : 5);
string[] items = Main.getText(Main.oras ? 114 : 96);
string[] species = Main.getText(Main.oras ? 98 : 80);
string[] types = Main.getText(Main.oras ? 18 : 17);
string[] forms = Main.getText(Main.oras ? 5 : 5);
species[0] = "---";
byte[] data = File.ReadAllBytes(Directory.GetFiles("personal").Last());
string[][] AltForms = getFormList(data, Main.oras, species, forms, types, items);

View File

@@ -21,10 +21,11 @@ public Pickup()
setupDGV();
getList();
}
string codebin;
string[] itemlist = Main.getText((Main.oras) ? 114 : 96);
int offset = (Main.oras) ? 0x004872FC : 0x004455A8;
byte[] data;
readonly string codebin;
readonly string[] itemlist = Main.getText(Main.oras ? 114 : 96);
readonly int offset = Main.oras ? 0x004872FC : 0x004455A8;
readonly byte[] data;
int dataoffset;
private void getDataOffset()
{

View File

@@ -124,28 +124,42 @@ public RSTE()
internal static Random rand = new Random();
internal static uint rnd32()
{
return (uint)(rand.Next(1 << 30)) << 2 | (uint)(rand.Next(1 << 2));
return (uint)rand.Next(1 << 30) << 2 | (uint)rand.Next(1 << 2);
}
bool start = true;
bool loading = true;
int index = -1;
#region Global Variables
private ComboBox[] trpk_pkm, trpk_lvl, trpk_item, trpk_abil,
trpk_m1, trpk_m2, trpk_m3, trpk_m4, trpk_IV, trpk_form, trpk_gender;
private readonly ComboBox[] trpk_pkm;
private readonly ComboBox[] trpk_lvl;
private readonly ComboBox[] trpk_item;
private readonly ComboBox[] trpk_abil;
private readonly ComboBox[] trpk_m1;
private readonly ComboBox[] trpk_m2;
private readonly ComboBox[] trpk_m3;
private readonly ComboBox[] trpk_m4;
private readonly ComboBox[] trpk_IV;
private readonly ComboBox[] trpk_form;
private readonly ComboBox[] trpk_gender;
private PictureBox[] pba;
// Top Level Functions
private string[] trdatapaths = Directory.GetFiles("trdata");
private string[] trpokepaths = Directory.GetFiles("trpoke");
private string[] abilitylist = Main.getText((Main.oras) ? 37 : 34);
private string[] movelist = Main.getText((Main.oras) ? 14 : 13);
private string[] itemlist = Main.getText((Main.oras) ? 114 : 96);
private string[] specieslist = Main.getText((Main.oras) ? 98 : 80);
private string[] types = Main.getText((Main.oras) ? 18 : 17);
private string[] forms = Main.getText((Main.oras) ? 5 : 5);
private string[] trName = Main.getText((Main.oras) ? 22 : 21);
private string[] trClass = Main.getText((Main.oras) ? 21 : 20);
private string[] trText = Main.getText((Main.oras) ? 23 : 22);
private readonly string[] trdatapaths = Directory.GetFiles("trdata");
private readonly string[] trpokepaths = Directory.GetFiles("trpoke");
private readonly string[] abilitylist = Main.getText(Main.oras ? 37 : 34);
private readonly string[] movelist = Main.getText(Main.oras ? 14 : 13);
private readonly string[] itemlist = Main.getText(Main.oras ? 114 : 96);
private readonly string[] specieslist = Main.getText(Main.oras ? 98 : 80);
private readonly string[] types = Main.getText(Main.oras ? 18 : 17);
private readonly string[] forms = Main.getText(Main.oras ? 5 : 5);
private string[] trName = Main.getText(Main.oras ? 22 : 21);
private readonly string[] trClass = Main.getText(Main.oras ? 21 : 20);
private readonly string[] trText = Main.getText(Main.oras ? 23 : 22);
#endregion
// Ability Loading
@@ -166,8 +180,8 @@ private void refreshPKMSlotAbility(int slot)
int species = trpk_pkm[slot].SelectedIndex;
int formnum = trpk_form[slot].SelectedIndex;
species = (formnum > 0)
? ((indexList[species] > 0)
species = formnum > 0
? (indexList[species] > 0
? indexList[species] + formnum - 1
: species)
: species;
@@ -194,14 +208,14 @@ private void changeTrainerType(object sender, EventArgs e)
trpk_gender[i].Enabled =
trpk_abil[i].Enabled =
trpk_IV[i].Enabled =
trpk_lvl[i].Enabled = (i < pkm);
trpk_lvl[i].Enabled = i < pkm;
trpk_item[i].Enabled = (i < pkm) && (checkBox_Item.Checked);
trpk_item[i].Enabled = (i < pkm) && checkBox_Item.Checked;
trpk_m1[i].Enabled =
trpk_m2[i].Enabled =
trpk_m3[i].Enabled =
trpk_m4[i].Enabled = (i < pkm) && (checkBox_Moves.Checked);
trpk_m4[i].Enabled = (i < pkm) && checkBox_Moves.Checked;
if (!trpk_pkm[i].Enabled)
{
@@ -258,7 +272,7 @@ private string getTRSummary()
if (trpk_m4[i].SelectedIndex > 0) toret += " / " + trpk_m4[i].Text;
toret += ")";
}
toret += " IVs: All " + (Convert.ToInt32(trpk_IV[i].SelectedIndex) / 8);
toret += " IVs: All " + Convert.ToInt32(trpk_IV[i].SelectedIndex) / 8;
toret += Environment.NewLine;
}
toret += Environment.NewLine;
@@ -428,11 +442,11 @@ private void Setup()
Array.Resize(ref trName, trdatapaths.Length);
CB_TrainerID.Items.Clear();
for (int i = 0; i < trdatapaths.Length; i++)
CB_TrainerID.Items.Add(String.Format("{1} - {0}", i.ToString("000"), trName[i] ?? "UNKNOWN"));
CB_TrainerID.Items.Add(string.Format("{1} - {0}", i.ToString("000"), trName[i] ?? "UNKNOWN"));
CB_Trainer_Class.Items.Clear();
for (int i = 0; i < trClass.Length; i++)
CB_Trainer_Class.Items.Add(String.Format("{1} - {0}", i.ToString("000"), trClass[i]));
CB_Trainer_Class.Items.Add(string.Format("{1} - {0}", i.ToString("000"), trClass[i]));
specieslist[0] = "---";
abilitylist[0] = itemlist[0] = movelist[0] = "";
@@ -462,7 +476,7 @@ private void Setup()
trpk_lvl[i].Items.Clear();
for (int z = 0; z <= 100; z++)
trpk_lvl[i].Items.Add((z).ToString());
trpk_lvl[i].Items.Add(z.ToString());
trpk_IV[i].Items.Clear();
for (int z = 0; z < 256; z++)
@@ -501,7 +515,7 @@ private void Setup()
CB_Battle_Type.Items.Add("Triple");
CB_Battle_Type.Items.Add("Rotation");
CB_Battle_Type.Items.Add("Horde");
megaEvos = (Main.oras)
megaEvos = Main.oras
? new[] { 15, 18, 80, 208, 254, 260, 302, 319, 323, 334, 362, 373, 376, 380, 381, 428, 475, 531, 719, 3, 6, 9, 65, 94, 115, 127, 130, 142, 150, 181, 212, 214, 229, 248, 257, 282, 303, 306, 308, 310, 354, 359, 445, 448, 460 }
: new[] { 3, 6, 9, 65, 94, 115, 127, 130, 142, 150, 181, 212, 214, 229, 248, 257, 282, 303, 306, 308, 310, 354, 359, 445, 448, 460 };
@@ -522,15 +536,15 @@ private void Setup()
public static int rDMGCount, rSTABCount;
private int[] mEvoTypes;
private string[] rImportant;
private List<string> Tags = new List<string>();
private Dictionary<string, int> TagTypes = new Dictionary<string, int>();
private readonly List<string> Tags = new List<string>();
private readonly Dictionary<string, int> TagTypes = new Dictionary<string, int>();
public static int[] sL; // Random Species List
public static decimal rGiftPercent, rLevelPercent;
private void B_Randomize_Click(object sender, EventArgs e)
{
rPKM = rMove = rAbility = rDiffAI = rDiffIV = rClass = rGift = rItem = rDoRand = false; // init to false
rGiftPercent = 0; // 0
(new TrainerRand()).ShowDialog(); // Open Randomizer Config to get config vals
new TrainerRand().ShowDialog(); // Open Randomizer Config to get config vals
if (rDoRand)
Randomize();
}
@@ -538,7 +552,7 @@ private void Randomize()
{
int[] banned = { 165, 621 }; // Struggle, Hyperspace Fury
rImportant = new string[CB_TrainerID.Items.Count];
rTags = (Main.oras) ? GetTagsORAS() : GetTagsXY();
rTags = Main.oras ? GetTagsORAS() : GetTagsXY();
mEvoTypes = GetMegaEvolvableTypes();
List<int> GymE4Types = new List<int>();
@@ -621,10 +635,10 @@ private void Randomize()
&& !rIgnoreClass.Contains(CB_Trainer_Class.SelectedIndex) // Current class isn't a special class
)
{
int rv = (int)(rnd32() % (CB_Trainer_Class.Items.Count));
int rv = (int)(rnd32() % CB_Trainer_Class.Items.Count);
// Ensure the Random Class isn't an exclusive class
while (rIgnoreClass.Contains(rv) && !trClass[rv].StartsWith("[~")) // don't allow disallowed classes
rv = (int)(rnd32() % (CB_Trainer_Class.Items.Count));
rv = (int)(rnd32() % CB_Trainer_Class.Items.Count);
CB_Trainer_Class.SelectedIndex = rv;
}
@@ -635,18 +649,18 @@ private void Randomize()
ushort[] items;
uint rnd = rnd32() % 10;
if (rnd < 2) // held item
items = (Main.oras) ? Legal.Pouch_Items_ORAS : Legal.Pouch_Items_XY;
items = Main.oras ? Legal.Pouch_Items_ORAS : Legal.Pouch_Items_XY;
else if (rnd < 5) // medicine
items = (Main.oras) ? Legal.Pouch_Medicine_ORAS : Legal.Pouch_Medicine_XY;
items = Main.oras ? Legal.Pouch_Medicine_ORAS : Legal.Pouch_Medicine_XY;
else // berry
items = Legal.Pouch_Berry_XY;
CB_Prize.SelectedIndex = items[(rnd32() % items.Length)];
CB_Prize.SelectedIndex = items[rnd32() % items.Length];
}
#endregion
else if (rGift)
CB_Prize.SelectedIndex = 0;
ushort[] itemvals = (Main.oras) ? Legal.Pouch_Items_ORAS : Legal.Pouch_Items_XY;
ushort[] itemvals = Main.oras ? Legal.Pouch_Items_ORAS : Legal.Pouch_Items_XY;
itemvals = itemvals.Concat(Legal.Pouch_Berry_XY).ToArray();
int itemC = itemvals.Length;
int ctr = 0;
@@ -670,13 +684,13 @@ private void Randomize()
if (typerand)
{
int tries = 0;
while (((pkm.Types[0] != type && pkm.Types[1] != type) || ((mevo && p == CB_numPokemon.SelectedIndex - 1 && !megaEvos.Contains(species)))) && tries < 0x10000)
while (((pkm.Types[0] != type && pkm.Types[1] != type) || mevo && p == CB_numPokemon.SelectedIndex - 1 && !megaEvos.Contains(species)) && tries < 0x10000)
if (p == CB_numPokemon.SelectedIndex - 1 && mevo)
pkm = Main.SpeciesStat[species = GetRandomMegaEvolvablePokemon(type)];
else if (rSmart) // Get a new Pokemon with a close BST
{
pkm = Main.SpeciesStat[species = Randomizer.getRandomSpecies(ref sL, ref ctr)];
while (!((pkm.BST * (5 - ++tries / 722) / 6 < oldpkm.BST) && (pkm.BST * (6 + ++tries / 722) / 5) > oldpkm.BST))
while (!((pkm.BST * (5 - ++tries / 722) / 6 < oldpkm.BST) && pkm.BST * (6 + ++tries / 722) / 5 > oldpkm.BST))
{
pkm = Main.SpeciesStat[species = Randomizer.getRandomSpecies(ref sL, ref ctr)];
}
@@ -689,7 +703,7 @@ private void Randomize()
else if (rSmart) // Get a new Pokemon with a close BST
{
int tries = 0;
while (!((pkm.BST * (5 - ++tries / 722) / 6 < oldpkm.BST) && (pkm.BST * (6 + ++tries / 722) / 5) > oldpkm.BST))
while (!((pkm.BST * (5 - ++tries / 722) / 6 < oldpkm.BST) && pkm.BST * (6 + ++tries / 722) / 5 > oldpkm.BST))
{
pkm = Main.SpeciesStat[species = Randomizer.getRandomSpecies(ref sL, ref ctr)];
}
@@ -719,7 +733,7 @@ private void Randomize()
}
else if (rItem)
#region RandomItem
trpk_item[p].SelectedIndex = itemvals[(rnd32() % itemC)];
trpk_item[p].SelectedIndex = itemvals[rnd32() % itemC];
#endregion
if (rMove)

View File

@@ -269,12 +269,12 @@ public RSWE()
for (int i = 0; i < personalList.Length; i++)
personal[i] = File.ReadAllBytes("personal" + Path.DirectorySeparatorChar + i.ToString("000") + ".bin");
}
private ComboBox[] spec;
private NumericUpDown[] min;
private NumericUpDown[] max;
private NumericUpDown[] form;
private readonly ComboBox[] spec;
private readonly NumericUpDown[] min;
private readonly NumericUpDown[] max;
private readonly NumericUpDown[] form;
string[] specieslist = { };
string[] formlist = { };
readonly string[] formlist = { };
string[] metRS_00000 = { };
byte[] zonedata = { };
byte[] decStorage = { };
@@ -282,11 +282,11 @@ public RSWE()
private string[] encdatapaths;
private string[] filepaths;
byte[][] personal;
readonly byte[][] personal;
private void RSWE_Load()
{
specieslist = Main.getText((Main.oras) ? 98 : 80);
specieslist = Main.getText(Main.oras ? 98 : 80);
specieslist[0] = "---";
foreach (string s in formlist)
@@ -307,7 +307,7 @@ private void RSWE_Load()
internal static Random rand = new Random();
internal static uint rnd32()
{
return (uint)(rand.Next(1 << 30)) << 2 | (uint)(rand.Next(1 << 2));
return (uint)rand.Next(1 << 30) << 2 | (uint)rand.Next(1 << 2);
}
private void openQuick(string[] encdata)
@@ -316,7 +316,7 @@ private void openQuick(string[] encdata)
Array.Sort(encdatapaths);
filepaths = new string[encdatapaths.Length - 2];
Array.Copy(encdatapaths, 2, filepaths, 0, filepaths.Length);
metRS_00000 = Main.getText((Main.oras) ? 90 : 72);
metRS_00000 = Main.getText(Main.oras ? 90 : 72);
zonedata = File.ReadAllBytes(encdatapaths[0]);
decStorage = File.ReadAllBytes(encdatapaths[1]);
LocationNames = new string[filepaths.Length];
@@ -326,8 +326,8 @@ private void openQuick(string[] encdata)
int LocationNum = Convert.ToInt16(name.Substring(4, name.Length - 4));
int indNum = LocationNum * 56 + 0x1C;
string LocationName = metRS_00000[zonedata[indNum] + (0x100 * (zonedata[indNum + 1] & 1))];
LocationNames[f] = (LocationNum.ToString("000") + " - " + LocationName);
string LocationName = metRS_00000[zonedata[indNum] + 0x100 * (zonedata[indNum + 1] & 1)];
LocationNames[f] = LocationNum.ToString("000") + " - " + LocationName;
}
CB_LocationID.DataSource = LocationNames;
B_Save.Enabled = B_Dump.Enabled = B_Randomize.Enabled = true;
@@ -440,8 +440,8 @@ private void CB_LocationID_SelectedIndexChanged(object sender, EventArgs e)
private bool needsInsertion(int mapID)
{
if (mapID != 535) // Hardcoded, bad, I know.
return (BitConverter.ToUInt32(decStorage, (mapID + 2) * 4) - BitConverter.ToUInt32(decStorage, (mapID + 1) * 4) == 0);
return (BitConverter.ToUInt32(decStorage, (mapID + 1) * 4) == decStorage.Length);
return BitConverter.ToUInt32(decStorage, (mapID + 2) * 4) - BitConverter.ToUInt32(decStorage, (mapID + 1) * 4) == 0;
return BitConverter.ToUInt32(decStorage, (mapID + 1) * 4) == decStorage.Length;
}
private bool hasData()
@@ -592,7 +592,7 @@ private void B_Randomize_Click(object sender, EventArgs e)
// Assign Levels
if (CHK_Level.Checked)
for (int l = 0; l < max.Length; l++)
min[l].Value = max[l].Value = (max[l].Value <= 1) ? max[l].Value : Math.Max(1, Math.Min(100, (int)((leveldiff) * max[l].Value)));
min[l].Value = max[l].Value = max[l].Value <= 1 ? max[l].Value : Math.Max(1, Math.Min(100, (int)(leveldiff * max[l].Value)));
// Get a new list of Pokemon so that DexNav does not crash.
int[] list = new int[max.Length];
@@ -605,7 +605,7 @@ private void B_Randomize_Click(object sender, EventArgs e)
// At most 18, but don't chew if there's only a few slots.
int cons = list.Count(a => a != 0);
int[] RandomList = new int[(cons > 18) ? (18 - (cons / 8)) : cons];
int[] RandomList = new int[cons > 18 ? 18 - cons / 8 : cons];
// Fill Location List
if (!CHK_BST.Checked)
@@ -769,7 +769,7 @@ private void modifyLevels(object sender, EventArgs e)
// Amp Levels
for (int l = 0; l < max.Length; l++)
min[l].Value = max[l].Value = (max[l].Value <= 1) ? max[l].Value : Math.Max(1, Math.Min(100, (int)(leveldiff * max[l].Value)));
min[l].Value = max[l].Value = max[l].Value <= 1 ? max[l].Value : Math.Max(1, Math.Min(100, (int)(leveldiff * max[l].Value)));
// Save Changes
B_Save_Click(sender, e);

View File

@@ -6,7 +6,7 @@ namespace pk3DS
{
public partial class Starters : Form
{
private byte[][] personal;
private readonly byte[][] personal;
public Starters()
{
specieslist[0] = "---";
@@ -51,16 +51,16 @@ public Starters()
}
internal static string CROPath = Path.Combine(Main.RomFSPath, "DllPoke3Select.cro");
internal static string FieldPath = Path.Combine(Main.RomFSPath, "DllField.cro");
private string[] specieslist = Main.getText((Main.oras) ? 98 : 80);
private ComboBox[][] Choices;
private PictureBox[][] Previews;
private Label[] Labels;
private string[] StarterSummary = Main.oras
private readonly string[] specieslist = Main.getText(Main.oras ? 98 : 80);
private readonly ComboBox[][] Choices;
private readonly PictureBox[][] Previews;
private readonly Label[] Labels;
private readonly string[] StarterSummary = Main.oras
? new[] { "Gen 3 Starters", "Gen 2 Starters", "Gen 4 Starters", "Gen 5 Starters" }
: new[] { "Gen 6 Starters", "Gen 1 Starters" };
private byte[] Data;
private byte[] FieldData;
private int Count = Main.oras ? 4 : 2;
private readonly int Count = Main.oras ? 4 : 2;
private int offset;
private void B_Save_Click(object sender, EventArgs e)
{
@@ -129,8 +129,8 @@ private void changeSpecies(object sender, EventArgs e)
{
// Fetch the corresponding PictureBox to update
string name = (sender as ComboBox).Name;
int group = Int32.Parse(name[4]+"") - 1;
int index = Int32.Parse(name[6]+"");
int group = int.Parse(name[4]+"") - 1;
int index = int.Parse(name[6]+"");
int species = (sender as ComboBox).SelectedIndex;
Previews[group][index].Image = Util.scaleImage(Util.getSprite(species, 0, 0, 0), 3);
@@ -148,7 +148,7 @@ private void B_Randomize_Click(object sender, EventArgs e)
for (int i = 0; i < Count; i++)
{
// Get Species List
int gen = Int32.Parse(Labels[i].Text[4]+"");
int gen = int.Parse(Labels[i].Text[4]+"");
int[] sL = CHK_Gen.Checked
? Randomizer.getSpeciesList(gen==1, gen==2, gen==3, gen==4, gen==5, gen==6, false, false, false)
: Randomizer.getSpeciesList(true, true, true, true, true, true, false, false, false);

View File

@@ -22,10 +22,11 @@ public TMHM()
setupDGV();
getList();
}
string codebin;
string[] movelist = Main.getText((Main.oras) ? 14 : 13);
int offset = (Main.oras) ? 0x004A67EE : 0x00464796; // Default
byte[] data;
readonly string codebin;
readonly string[] movelist = Main.getText(Main.oras ? 14 : 13);
readonly int offset = Main.oras ? 0x004A67EE : 0x00464796; // Default
readonly byte[] data;
int dataoffset;
private void getDataOffset()
{
@@ -127,7 +128,7 @@ private void setList()
}
// Set Move Text Descriptions back into Item Text File
int itemFile = (Main.oras) ? 117 : 99;
int itemFile = Main.oras ? 117 : 99;
string[] itemDescriptions = Main.getText(itemFile);
string[] moveDescriptions = Main.getText(Main.oras ? 16 : 15);
for (int i = 1 - 1; i <= 92 - 1; i++) // TM01 - TM92

View File

@@ -9,7 +9,7 @@ namespace pk3DS
{
public partial class TitleScreen : Form
{
private bool compressed = Main.oras;
private readonly bool compressed = Main.oras;
public TitleScreen()
{
InitializeComponent();
@@ -40,9 +40,9 @@ public TitleScreen()
string[] languages = (Main.oras ? new[] {"JP1"} : new string[] {}).Concat(new[] {"DE", "ES", "FR", "IT", "JP", "KO", "EN"}).ToArray();
string[] games = Main.oras ? new[] {"OR", "AS"} : new[] {"X", "Y"};
for (int i = 0; i < darcs.Length/2; i++)
CB_DARC.Items.Add(String.Format("{0} - {1}", games[0], languages[i]));
CB_DARC.Items.Add($"{games[0]} - {languages[i]}");
for (int i = darcs.Length/2; i < darcs.Length; i++)
CB_DARC.Items.Add(String.Format("{0} - {1}", games[1], languages[i - darcs.Length/2]));
CB_DARC.Items.Add($"{games[1]} - {languages[i - darcs.Length/2]}");
// Load darcs
for (int i = 0; i < darcs.Length; i++)
@@ -68,10 +68,11 @@ public TitleScreen()
CB_DARC.SelectedIndex = CB_DARC.Items.Count - 1; // last (english game2)
}
private string[] files = Directory.GetFiles("titlescreen");
private CTR.DARC[] darcs = new CTR.DARC[2 * (Main.oras ? 8 : 7)];
private string[] usedFiles = new string[2 * (Main.oras ? 8 : 7)];
int[] darcFiles = Main.oras
private readonly string[] files = Directory.GetFiles("titlescreen");
private readonly CTR.DARC[] darcs = new CTR.DARC[2 * (Main.oras ? 8 : 7)];
private readonly string[] usedFiles = new string[2 * (Main.oras ? 8 : 7)];
readonly int[] darcFiles = Main.oras
? new[]
{
1120, 1121, 1122, 1123, 1124, 1125, 1126, 1127,
@@ -128,7 +129,7 @@ private void changeFile(object sender, EventArgs e)
// store image locally for saving if need be
currentBytes = data;
L_Dimensions.Text = String.Format("Dimensions: {0}w && {1}h", PB_Image.Width, PB_Image.Height);
L_Dimensions.Text = $"Dimensions: {PB_Image.Width}w && {PB_Image.Height}h";
}
private byte[] currentBytes;
private void insertFile(string path)
@@ -144,8 +145,7 @@ private void insertFile(string path)
if (img.Width != PB_Image.Width || img.Height != PB_Image.Height)
{
Util.Alert("Image sizes do not match.",
String.Format("Width: {0} - {1}\nHeight: {2} - {3}",
img.Width, PB_Image.Width, img.Height, PB_Image.Height));
$"Width: {img.Width} - {PB_Image.Width}\nHeight: {img.Height} - {PB_Image.Height}");
return;
}
bclim = data;
@@ -158,8 +158,7 @@ private void insertFile(string path)
if (img.Width != PB_Image.Width || img.Height != PB_Image.Height)
{
Util.Alert("Image sizes do not match.",
String.Format("Width: {0} - {1}\nHeight: {2} - {3}",
img.Width, PB_Image.Width, img.Height, PB_Image.Height));
$"Width: {img.Width} - {PB_Image.Width}\nHeight: {img.Height} - {PB_Image.Height}");
return;
}
bclim = CTR.BCLIM.IMGToBCLIM(img, '9');
@@ -192,8 +191,7 @@ private void tabMain_DragEnter(object sender, DragEventArgs e)
}
private void tabMain_DragDrop(object sender, DragEventArgs e)
{
string[] files = (string[])e.Data.GetData(DataFormats.FileDrop);
string path = files[0]; // open first D&D
string path = ((string[])e.Data.GetData(DataFormats.FileDrop))[0]; // open first D&D
insertFile(path);
}

View File

@@ -17,9 +17,9 @@ public TrainerRand()
trClassnorep.Sort();
}
private string[] trName = Main.getText((Main.oras) ? 22 : 21);
private string[] trClass = Main.getText((Main.oras) ? 21 : 20);
private List<string> trClassnorep;
private string[] trName = Main.getText(Main.oras ? 22 : 21);
private readonly string[] trClass = Main.getText(Main.oras ? 21 : 20);
private readonly List<string> trClassnorep;
private void B_Close_Click(object sender, EventArgs e)
{
@@ -51,7 +51,7 @@ private void B_Save_Click(object sender, EventArgs e)
RSTE.rClass = CHK_RandomClass.Checked;
if (RSTE.rClass)
{
RSTE.rIgnoreClass = (CHK_IgnoreSpecialClass.Checked)
RSTE.rIgnoreClass = CHK_IgnoreSpecialClass.Checked
? Main.oras
? Legal.SpecialClasses_ORAS
: Legal.SpecialClasses_XY
@@ -70,8 +70,8 @@ private void B_Save_Click(object sender, EventArgs e)
if (CHK_StoryMEvos.Checked)
{
RSTE.rEnsureMEvo = Main.oras
? (new [] { 178, 235, 557, 583, 687, 698, 699, 700, 701, 713, 906, 907, 908, 909, 910, 911, 912, 913, 942, 944, 946 })
: (new [] { 188, 263, 276, 277, 519, 520, 521, 526, 599, 600, 601 });
? new [] { 178, 235, 557, 583, 687, 698, 699, 700, 701, 713, 906, 907, 908, 909, 910, 911, 912, 913, 942, 944, 946 }
: new [] { 188, 263, 276, 277, 519, 520, 521, 526, 599, 600, 601 };
}
else
{
@@ -103,7 +103,7 @@ private void CHK_Level_CheckedChanged(object sender, EventArgs e)
}
private void changeLevelPercent(object sender, EventArgs e)
{
CHK_Level.Checked = (NUD_Level.Value != 0);
CHK_Level.Checked = NUD_Level.Value != 0;
}
private void CHK_RandomGift_CheckedChanged(object sender, EventArgs e)
{
@@ -112,7 +112,7 @@ private void CHK_RandomGift_CheckedChanged(object sender, EventArgs e)
}
private void changeGiftPercent(object sender, EventArgs e)
{
CHK_RandomGift.Checked = (NUD_GiftPercent.Value != 0);
CHK_RandomGift.Checked = NUD_GiftPercent.Value != 0;
}
private void CHK_TypeTheme_CheckedChanged(object sender, EventArgs e)
@@ -132,7 +132,7 @@ private void changeMoveRandomization(object sender, EventArgs e)
{
CHK_Damage.Checked = CHK_STAB.Checked =
CHK_Damage.Enabled = CHK_STAB.Enabled =
NUD_Damage.Enabled = NUD_STAB.Enabled = (CB_Moves.SelectedIndex == 1);
NUD_Damage.Enabled = NUD_STAB.Enabled = CB_Moves.SelectedIndex == 1;
if (CB_Moves.SelectedIndex == 0)
CHK_6PKM.Checked = false;

View File

@@ -21,13 +21,14 @@ public Tutors()
CB_Location.SelectedIndex = 0;
Util.Alert("Changes made do not reflect ingame.", "Still needs more research.");
}
string codebin;
string[] movelist = Main.getText((Main.oras) ? 14 : 13);
byte[] data;
byte[] entries = { 0xF, 0x11, 0x10, 0xF }; // Entries per Tutor
readonly string codebin;
readonly string[] movelist = Main.getText(Main.oras ? 14 : 13);
readonly byte[] data;
readonly byte[] entries = { 0xF, 0x11, 0x10, 0xF }; // Entries per Tutor
private const int offset = 0x004960F8;
int dataoffset;
string[] locations = { "1", "2", "3", "4" };
readonly string[] locations = { "1", "2", "3", "4" };
private void getDataOffset(int index)
{
dataoffset = offset; // reset

View File

@@ -9,11 +9,12 @@ namespace pk3DS
public partial class TypeChart : Form
{
internal static string CROPath = Path.Combine(Main.RomFSPath, "DllBattle.cro");
private string[] types = Main.getText((Main.oras) ? 18 : 17);
private int offset = Main.oras ? 0x000DB428 : 0x000D12A8;
private byte[] chart = new byte[0x144];
private byte[] CROData;
uint[] Colors = { 0xFF000000,
private readonly string[] types = Main.getText(Main.oras ? 18 : 17);
private readonly int offset = Main.oras ? 0x000DB428 : 0x000D12A8;
private readonly byte[] chart = new byte[0x144];
private readonly byte[] CROData;
readonly uint[] Colors = { 0xFF000000,
0, // unused
0xFFFF0000,
0, // unused
@@ -57,13 +58,13 @@ private Bitmap getGrid(int itemsize, int itemsPerRow, byte[] vals)
// Plop into image
for (int x = 0; x < itemsize * itemsize; x++)
Buffer.BlockCopy(BitConverter.GetBytes(itemColor), 0, bmpData,
((Y * itemsize + x % itemsize) * width * 4) + ((X * itemsize + x / itemsize) * 4), 4);
(Y * itemsize + x % itemsize) * width * 4 + (X * itemsize + x / itemsize) * 4, 4);
}
// slap on a grid
for (int i = 0; i < width * height; i++)
if (i % (itemsize) == 0 || (i / (itemsize * itemsPerRow)) % (itemsize) == 0)
if (i % itemsize == 0 || i / (itemsize * itemsPerRow) % itemsize == 0)
Buffer.BlockCopy(BitConverter.GetBytes(0x17000000), 0, bmpData,
((i / (itemsize * itemsPerRow)) * width * 4) + ((i % (itemsize * itemsPerRow)) * 4), 4);
i / (itemsize * itemsPerRow) * width * 4 + i % (itemsize * itemsPerRow) * 4, 4);
// assemble image
Bitmap b = new Bitmap(width, height, PixelFormat.Format32bppArgb);
@@ -85,8 +86,8 @@ private void B_Cancel_Click(object sender, EventArgs e)
private void moveMouse(object sender, MouseEventArgs e)
{
int X = e.X / (32);
int Y = e.Y / (32);
int X = e.X / 32;
int Y = e.Y / 32;
if (e.X == (sender as PictureBox).Width - 1 - 2) // tweak because the furthest pixel is unused for transparent effect, and 2 px are used for border
X -= 1;
if (e.Y == (sender as PictureBox).Height - 1 - 2)
@@ -97,8 +98,8 @@ private void moveMouse(object sender, MouseEventArgs e)
}
private void clickMouse(object sender, MouseEventArgs e)
{
int X = e.X / (32);
int Y = e.Y / (32);
int X = e.X / 32;
int Y = e.Y / 32;
if (e.X == (sender as PictureBox).Width - 1 - 2) // tweak because the furthest pixel is unused for transparent effect, and 2 px are used for border
X -= 1;
if (e.Y == (sender as PictureBox).Height - 1 - 2)
@@ -142,10 +143,10 @@ private void clickMouse(object sender, MouseEventArgs e)
}
private void updateLabel(int X, int Y, int value)
{
L_Hover.Text = String.Format("[{0}x{1}: {2}] {4} attacking {3} {5}", X.ToString("00"), Y.ToString("00"),
L_Hover.Text = string.Format("[{0}x{1}: {2}] {4} attacking {3} {5}", X.ToString("00"), Y.ToString("00"),
value.ToString("00"), types[X], types[Y], effects[value]);
}
private string[] effects =
private readonly string[] effects =
{
"has no effect!",
"",

View File

@@ -275,23 +275,23 @@ public XYWE()
for (int i = 0; i < personalList.Length; i++)
personal[i] = File.ReadAllBytes("personal" + Path.DirectorySeparatorChar + i.ToString("000") + ".bin");
}
private ComboBox[] spec;
private NumericUpDown[] min;
private NumericUpDown[] max;
private NumericUpDown[] form;
private readonly ComboBox[] spec;
private readonly NumericUpDown[] min;
private readonly NumericUpDown[] max;
private readonly NumericUpDown[] form;
string[] specieslist = { };
string[] formlist = { };
readonly string[] formlist = { };
string[] metXY_00000 = { };
byte[] zonedata = { };
string[] LocationNames = { };
private string[] encdatapaths;
private string[] filepaths;
byte[][] personal;
readonly byte[][] personal;
private void Load_XYWE()
{
specieslist = Main.getText((Main.oras) ? 98 : 80);
specieslist = Main.getText(Main.oras ? 98 : 80);
specieslist[0] = "---";
CB_FormeList.Items.AddRange(formlist);
@@ -312,7 +312,7 @@ private void openQuick(string[] encdata)
Array.Sort(encdatapaths);
filepaths = new string[encdatapaths.Length - 1];
Array.Copy(encdatapaths, 1, filepaths, 0, filepaths.Length);
metXY_00000 = Main.getText((Main.oras) ? 90 : 72);
metXY_00000 = Main.getText(Main.oras ? 90 : 72);
zonedata = File.ReadAllBytes(encdatapaths[0]);
LocationNames = new string[filepaths.Length];
for (int f = 0; f < filepaths.Length; f++)
@@ -321,8 +321,8 @@ private void openQuick(string[] encdata)
int LocationNum = Convert.ToInt16(name.Substring(4, name.Length - 4));
int indNum = LocationNum * 56 + 0x1C;
string LocationName = metXY_00000[zonedata[indNum] + (0x100 * (zonedata[indNum + 1] & 1))];
LocationNames[f] = (LocationNum.ToString("000") + " - " + LocationName);
string LocationName = metXY_00000[zonedata[indNum] + 0x100 * (zonedata[indNum + 1] & 1)];
LocationNames[f] = LocationNum.ToString("000") + " - " + LocationName;
}
CB_LocationID.DataSource = LocationNames;
B_Save.Enabled = B_Dump.Enabled = B_Randomize.Enabled = true;
@@ -489,7 +489,7 @@ private void PreloadTabs(object sender, EventArgs e)
internal static Random rand = new Random();
internal static uint rnd32()
{
return (uint)(rand.Next(1 << 30)) << 2 | (uint)(rand.Next(1 << 2));
return (uint)rand.Next(1 << 30) << 2 | (uint)rand.Next(1 << 2);
}
private void B_Randomize_Click(object sender, EventArgs e)
@@ -515,7 +515,7 @@ private void B_Randomize_Click(object sender, EventArgs e)
// Assign Levels
if (CHK_Level.Checked)
for (int l = 0; l < max.Length; l++)
min[l].Value = max[l].Value = (max[l].Value <= 1) ? max[l].Value : Math.Max(1, Math.Min(100, (int)((leveldiff) * max[l].Value)));
min[l].Value = max[l].Value = max[l].Value <= 1 ? max[l].Value : Math.Max(1, Math.Min(100, (int)(leveldiff * max[l].Value)));
for (int slot = 0; slot < max.Length; slot++)
{
@@ -626,7 +626,7 @@ private void modifyLevels(object sender, EventArgs e)
// Amp Levels
for (int l = 0; l < max.Length; l++)
min[l].Value = max[l].Value = (max[l].Value <= 1) ? max[l].Value : Math.Max(1, Math.Min(100, (int)(leveldiff * max[l].Value)));
min[l].Value = max[l].Value = max[l].Value <= 1 ? max[l].Value : Math.Max(1, Math.Min(100, (int)(leveldiff * max[l].Value)));
// Save Changes
B_Save_Click(sender, e);

View File

@@ -17,7 +17,7 @@ public xytext(string[] infiles)
CB_Entry.Items.Add(i.ToString());
CB_Entry.SelectedIndex = 0;
}
private string[] files;
private readonly string[] files;
private int entry = -1;
// IO
private void B_Export_Click(object sender, EventArgs e)
@@ -91,10 +91,10 @@ private bool importTextFile(string fileName)
continue;
string[] brokenLine = fileText[i++ + 1].Split(new[] {" : "}, StringSplitOptions.None);
if (brokenLine.Length != 2)
{ Util.Error(String.Format("Invalid Line @ {0}, expected Text File : {1}", i, ctr)); return false; }
{ Util.Error($"Invalid Line @ {i}, expected Text File : {ctr}"); return false; }
int file = Util.ToInt32(brokenLine[1]);
if (file != ctr)
{ Util.Error(String.Format("Invalid Line @ {0}, expected Text File : {1}", i, ctr)); return false; }
{ Util.Error($"Invalid Line @ {i}, expected Text File : {ctr}"); return false; }
i+=2; // Skip over the other header line
List<string> Lines = new List<string>();
while (i < fileText.Length && fileText[i] != "~~~~~~~~~~~~~~~")
@@ -110,7 +110,7 @@ private bool importTextFile(string fileName)
// Error Check
if (ctr != files.Length)
{ Util.Error("The amount of Text Files in the input file does not match the required for the text file.",
String.Format("Received: {0}, Expected: {1}", ctr, files.Length)); return false; }
$"Received: {ctr}, Expected: {files.Length}"); return false; }
if (!newlineFormatting)
{ Util.Error("The input Text Files do not have the ingame newline formatting codes (\\n,\\r,\\c).",
"When exporting text, do not remove newline formatting."); return false; }
@@ -324,7 +324,7 @@ internal static byte[] getBytesForFile(string[] lines)
{
ushort key = baseKey;
uint pos = (uint)data.Position;
if (lines[i] == null) lines[i] = String.Format("[~ {0}]", i);
if (lines[i] == null) lines[i] = $"[~ {i}]";
// Get crypted line data.
{
{
@@ -391,8 +391,8 @@ internal static ushort getVariableBytes(string varType, ref List<ushort> args, b
{
// Fetch the variable name...
int bracket = varType.IndexOf('(');
string variable = (noArgs) ? varType : varType.Substring(0, bracket);
string[] arguments = (noArgs) ? null : varType.Substring(bracket + 1, varType.Length - bracket - 2).Split(',');
string variable = noArgs ? varType : varType.Substring(0, bracket);
string[] arguments = noArgs ? null : varType.Substring(bracket + 1, varType.Length - bracket - 2).Split(',');
ushort varVal;
@@ -490,8 +490,8 @@ internal static void encryptVar(BinaryWriter bw, string line, ref int i, ref ush
{
if (DialogResult.Yes != Util.Prompt(
MessageBoxButtons.YesNo,
"Encoding Error - Please Resolve:",
String.Format("File: {3}{0}Char: {1}{0}Line:{0}{2}", Environment.NewLine, line[i+1], line, i),
"Encoding Error - Please Resolve:",
string.Format("File: {3}{0}Char: {1}{0}Line:{0}{2}", Environment.NewLine, line[i+1], line, i),
"Treat as literal '\\'?"))
throw new Exception("Invalid terminated line: " + line);
@@ -510,7 +510,7 @@ internal static void encryptVar(BinaryWriter bw, string line, ref int i, ref ush
string[] split = varCMD.Split(' ');
string varMethod = split[0]; // Returns VAR or WAIT or ~
string varType = (split.Length > 1) ? varCMD.Substring(varMethod.Length + 1) : ""; // Returns the remainder of the var command data.
string varType = split.Length > 1 ? varCMD.Substring(varMethod.Length + 1) : ""; // Returns the remainder of the var command data.
ushort varValue;
// Set up argument storage (even if it not used)
@@ -534,7 +534,7 @@ internal static void encryptVar(BinaryWriter bw, string line, ref int i, ref ush
}
case "VAR": // Text Variable
{
varValue = getVariableBytes(varType, ref args, (varCMD.IndexOf('(') < 0));
varValue = getVariableBytes(varType, ref args, varCMD.IndexOf('(') < 0);
break;
}
default: throw new Exception("Unknown variable method type!");

View File

@@ -13,7 +13,7 @@ public Icon()
{
InitializeComponent();
SMDH = Main.SMDH;
if (SMDH == null || SMDH.AppSettings == null || SMDH.LargeIcon.Bytes == null)
if (SMDH?.AppSettings == null || SMDH.LargeIcon.Bytes == null)
{
byte[] data = new byte[0x3C0]; // Feed a blank SMDH
Array.Copy(BitConverter.GetBytes(0x48444D53), data, 4); // SMDH header
@@ -174,14 +174,14 @@ private void importIcon(byte[] data, bool prompt = false)
Image img = Image.FromStream(BitmapStream);
Bitmap mBitmap = new Bitmap(img);
bool small = (img.Width == 24 && img.Height == 24);
bool large = (img.Width == 48 && img.Height == 48);
bool small = img.Width == 24 && img.Height == 24;
bool large = img.Width == 48 && img.Height == 48;
if (!small && !large)
Util.Alert("Image size is not correct.",
String.Format("Width: {0}\nHeight: {1}", img.Width, img.Height),
$"Width: {img.Width}\nHeight: {img.Height}",
"Expected Dimensions (24x24 or 48x48)");
if (prompt && DialogResult.Yes != Util.Prompt(MessageBoxButtons.YesNo, "Import image?", (small) ? "Small Icon" : "Large Icon"))
if (prompt && DialogResult.Yes != Util.Prompt(MessageBoxButtons.YesNo, "Import image?", small ? "Small Icon" : "Large Icon"))
return;
if (small)
SMDH.SmallIcon.ChangeIcon(mBitmap);

View File

@@ -33,7 +33,7 @@ internal static byte[] decompressScript(byte[] data)
internal static byte[] readCompressed(byte[] data, int pos)
{
byte[] c1 = data.Skip(pos).TakeWhile(b => b >> 7 > 0).ToArray(); // Take while >= 0x80
return c1.Concat(data.Skip(pos + c1.Count()).Take(1)).ToArray(); // Take another
return c1.Concat(data.Skip(pos + c1.Length).Take(1)).ToArray(); // Take another
}
internal static byte[] decompressBytes(byte[] cb)
{
@@ -42,7 +42,7 @@ internal static byte[] decompressBytes(byte[] cb)
if ((cb[0] & 0x40) > 0) // Signed Parameter
{
// Check the next bytecode
if (cb.Length > 1 && (cb[1] >> 7) > 0) // Many-bits-required command
if (cb.Length > 1 && cb[1] >> 7 > 0) // Many-bits-required command
{
// 2 Byte Signed Parameter
int cmd = (cb[0] & 0x3 << 14) | (cb[1] & 0x7F << 7) | cb[2]; // 16 Bits total
@@ -51,10 +51,10 @@ internal static byte[] decompressBytes(byte[] cb)
int dev = ((cb[0] & 0x3F) - 0x40) >> 2; // Lowest 2 bits have already been used for the command
db = db.Concat(BitConverter.GetBytes(dev).Take(2)).ToArray(); // 16 Bits
}
else if ((cb[0] >> 7) > 0) // Signed Command
else if (cb[0] >> 7 > 0) // Signed Command
{
// 3 Byte Signed Parameter
int cmd = ((cb[0] << 7) | cb[1]);
int cmd = (cb[0] << 7) | cb[1];
db = db.Concat(BitConverter.GetBytes(cmd).Take(1)).ToArray(); // 8 Bits Total
int dev = ((cb[0] & 0x3F) - 0x40) >> 1; // Lowest bit has already been used for the command
@@ -67,12 +67,12 @@ internal static byte[] decompressBytes(byte[] cb)
db = db.Concat(BitConverter.GetBytes(dev).Take(4)).ToArray(); // 32 Bits
}
}
else if ((cb[0] >> 7) > 0) // Manybit
else if (cb[0] >> 7 > 0) // Manybit
{
Array.Reverse(cb);
int cmd = 0;
for (int i = 0; i < cb.Length; i++)
cmd |= ((cb[i] & 0x7F) << (7 * i));
cmd |= (cb[i] & 0x7F) << (7 * i);
db = db.Concat(BitConverter.GetBytes((uint)cmd).Take(4)).ToArray();
}
@@ -92,10 +92,10 @@ internal static uint[] quickDecompress(byte[] data, int count)
int b = data[f++],
v = b & 0x7F;
if (++j == 1) // sign extension possible
x = (uint)(((((v >> 6) == 0 ? 1 : 0) - 1) << 6) | v); // only for bit6 being set
else x = ((x << 7) | (byte)v); // shift data into place
x = (uint)((((v >> 6 == 0 ? 1 : 0) - 1) << 6) | v); // only for bit6 being set
else x = (x << 7) | (byte)v; // shift data into place
if (((b & 0x80) != 0)) continue; // more data to read
if ((b & 0x80) != 0) continue; // more data to read
code[i++] = x; j = 0; // write finalized instruction
}
return code;
@@ -168,9 +168,9 @@ internal static byte[] compressBytes(byte[] db)
int ctr = 0;
while (dv != 0) // bits remaining
{
byte bits = (byte)(((byte)dv) & 0x7F); dv >>= 7; // Take off 7 bits at a time
byte bits = (byte)((byte)dv & 0x7F); dv >>= 7; // Take off 7 bits at a time
bitStorage |= (byte)(bits << (ctr*8)); // Write the 7 bits into storage
bitStorage |= (byte)(1 << (7 + (ctr++*8))); // continue reading flag
bitStorage |= (byte)(1 << (7 + ctr++*8)); // continue reading flag
}
byte[] compressedBits = BitConverter.GetBytes(bitStorage);
@@ -190,7 +190,7 @@ internal static string[] getHexLines(byte[] data, int count = 4)
{
data = data ?? new byte[0];
// Generates an x-byte wide space separated string array; leftovers included at the end.
string[] s = new string[data.Length/count + ((data.Length % count > 0) ? 1 : 0)];
string[] s = new string[data.Length/count + (data.Length % count > 0 ? 1 : 0)];
for (int i = 0; i < s.Length;i++)
s[i] = BitConverter.ToString(data.Skip(i*count).Take(count).ToArray()).Replace('-', ' ');
return s;
@@ -250,59 +250,37 @@ internal static string[] parseScript(uint[] cmd)
case 0x2E: op = "Begin"; break;
case 0x30: op = "Return\n"; break;
case 0x31: op = "CallFunc";
op += String.Format("[0x{0}] ({1})",
(i * 4 + (int)cmd[++i]).ToString("X4"),
(int)cmd[i]);
op += $"[0x{(i*4 + (int)cmd[++i]).ToString("X4")}] ({(int)cmd[i]})";
break;
case 0x33: op = "$33";
op += String.Format(" => 0x{0} ({1})",
(i * 4 + (int)cmd[++i]).ToString("X4"),
(int)cmd[i]);
op += $" => 0x{(i*4 + (int)cmd[++i]).ToString("X4")} ({(int)cmd[i]})";
break;
case 0x34: op = "$34";
op += String.Format(" => 0x{0} ({1})",
(i * 4 + (int)cmd[++i]).ToString("X4"),
(int)cmd[i]);
op += $" => 0x{(i*4 + (int)cmd[++i]).ToString("X4")} ({(int)cmd[i]})";
break;
case 0x35: op = "Jump!=";
op += String.Format(" => 0x{0} ({1})",
(i*4 + (int)cmd[++i]).ToString("X4"),
(int)cmd[i]);
op += $" => 0x{(i*4 + (int)cmd[++i]).ToString("X4")} ({(int)cmd[i]})";
break;
case 0x36: op = "Jump==";
op += String.Format(" => 0x{0} ({1})",
(i * 4 + (int)cmd[++i]).ToString("X4"),
(int)cmd[i]);
op += $" => 0x{(i*4 + (int)cmd[++i]).ToString("X4")} ({(int)cmd[i]})";
break;
case 0x37: op = "$37";
op += String.Format(" => 0x{0} ({1})",
(i * 4 + (int)cmd[++i]).ToString("X4"),
(int)cmd[i]);
op += $" => 0x{(i*4 + (int)cmd[++i]).ToString("X4")} ({(int)cmd[i]})";
break;
case 0x38: op = "$38";
op += String.Format(" => 0x{0} ({1})",
(i * 4 + (int)cmd[++i]).ToString("X4"),
(int)cmd[i]);
op += $" => 0x{(i*4 + (int)cmd[++i]).ToString("X4")} ({(int)cmd[i]})";
break;
case 0x3D: op = "$3D";
op += String.Format(" => 0x{0} ({1})",
(i * 4 + (int)cmd[++i]).ToString("X4"),
(int)cmd[i]);
op += $" => 0x{(i*4 + (int)cmd[++i]).ToString("X4")} ({(int)cmd[i]})";
break;
case 0x3E: op = "$3E";
op += String.Format(" => 0x{0} ({1})",
(i * 4 + (int)cmd[++i]).ToString("X4"),
(int)cmd[i]);
op += $" => 0x{(i*4 + (int)cmd[++i]).ToString("X4")} ({(int)cmd[i]})";
break;
case 0x3F: op = "$3F";
op += String.Format(" => 0x{0} ({1})",
(i * 4 + (int)cmd[++i]).ToString("X4"),
(int)cmd[i]);
op += $" => 0x{(i*4 + (int)cmd[++i]).ToString("X4")} ({(int)cmd[i]})";
break;
case 0x40: op = "$40";
op += String.Format(" => 0x{0} ({1})",
(i * 4 + (int)cmd[++i]).ToString("X4"),
(int)cmd[i]);
op += $" => 0x{(i*4 + (int)cmd[++i]).ToString("X4")} ({(int)cmd[i]})";
break;
case 0x41: op = "$41";
op += eA(new[] { c >> 16 }); break;
@@ -349,9 +327,7 @@ internal static string[] parseScript(uint[] cmd)
case 0x78: op = "$78";
op += eA(new[] { cmd[++i] }); break;
case 0x81: op = "Jump";
op += String.Format(" => 0x{0} ({1})",
(i*4 + (int)cmd[++i]).ToString("X4"),
(int)cmd[i]);
op += $" => 0x{(i*4 + (int)cmd[++i]).ToString("X4")} ({(int)cmd[i]})";
break;
case 0x82:
{
@@ -365,7 +341,7 @@ internal static string[] parseScript(uint[] cmd)
jump[j] = (int)cmd[++i];
val[j] = (int)cmd[++i];
op += Environment.NewLine +
String.Format("\t{2} => 0x{0} ({1})",
string.Format("\t{2} => 0x{0} ({1})",
((i-1)*4 + jump[j]).ToString("X4"),
jump[j],
val[j]);
@@ -373,9 +349,7 @@ internal static string[] parseScript(uint[] cmd)
// Else-Default
int elsejump = (int)cmd[++i];
op += Environment.NewLine +
String.Format("\t * => 0x{0} ({1})",
(((i - 1) * 4 + elsejump).ToString("X4")),
elsejump);
$"\t * => 0x{((i - 1)*4 + elsejump).ToString("X4")} ({elsejump})";
break;
}
case 0x87: op = "DoCommand?";
@@ -451,10 +425,10 @@ internal static string[] parseScript(uint[] cmd)
case 0xD2: op = "BeginScript"+Environment.NewLine; break;
case 0x0: op = "Nop"; break;
default: op = String.Format("**${0}**", (c & 0xFFFF).ToString("X2"));
default: op = $"**${(c & 0xFFFF).ToString("X2")}**";
op += eA(new[] { c >> 16 }); break;
}
rv[used++] = String.Format("0x{2}: [{0}] {1}", (c & 0x7FF).ToString("X2"), op, offset.ToString("X4"));
rv[used++] = string.Format("0x{2}: [{0}] {1}", (c & 0x7FF).ToString("X2"), op, offset.ToString("X4"));
}
Array.Resize(ref rv, used); // End result will cap out at lines used.
return rv;
@@ -469,14 +443,14 @@ internal static string eA(uint[] arr)
{
string s = "";
for (int i = 0; i < arr.Length; i++)
s += String.Format("0x{0}{1}", arr[i].ToString("X4"), (i+1 < arr.Length ? ", " : ""));
s += $"0x{arr[i].ToString("X4")}{(i + 1 < arr.Length ? ", " : "")}";
return "("+s+")";
}
internal static string eF(uint[] arr)
{
string s = "";
for (int i = 0; i < arr.Length; i++) // stupid hack, Convert.ToSingle((uint)) doesn't behave.
s += String.Format("{0}{1}", BitConverter.ToSingle(BitConverter.GetBytes(arr[i]), 0), (i + 1 < arr.Length ? ", " : ""));
s += $"{BitConverter.ToSingle(BitConverter.GetBytes(arr[i]), 0)}{(i + 1 < arr.Length ? ", " : "")}";
return "(" + s + ")";
}
}

View File

@@ -27,7 +27,7 @@ public Shuffler()
"a218" };
}
private string garc;
private string[] banlist;
private readonly string[] banlist;
private void updateLabel(object sender, EventArgs e)
{
@@ -36,8 +36,7 @@ private void updateLabel(object sender, EventArgs e)
if (File.Exists(garc))
{
L_File.Text = String.Format("File: a\\{0}\\{1}\\{2}",
CB_a.SelectedIndex, CB_b.SelectedIndex, CB_c.SelectedIndex);
L_File.Text = $"File: a\\{CB_a.SelectedIndex}\\{CB_b.SelectedIndex}\\{CB_c.SelectedIndex}";
B_Shuffle.Enabled = true;
}
else
@@ -72,7 +71,7 @@ private void B_Shuffle_Click(object sender, EventArgs e)
{ Util.Alert("No files to shuffle...?"); return; }
// Create backup
string dest = "backup" + Path.DirectorySeparatorChar + String.Format("PreShuffle {0}", garcID);
string dest = "backup" + Path.DirectorySeparatorChar + $"PreShuffle {garcID}";
if (!File.Exists(dest))
File.Copy(garc, dest);

View File

@@ -219,7 +219,7 @@ private void saveARC(string path)
else
file = null;
byte[] oldData = (file != null) ? File.ReadAllBytes(file) : null;
byte[] oldData = file != null ? File.ReadAllBytes(file) : null;
bool r = CTR.mini.packMini2(path, fileExt, Path.Combine(parentName, fileNum + "." + fileExt));
if (!r)
{
@@ -232,7 +232,7 @@ private void saveARC(string path)
break;
byte[] newData = File.ReadAllBytes(Path.Combine(parentName, fileNum + "." + fileExt));
if ((newData[2] == oldData[2]))
if (newData[2] == oldData[2])
{
int newPtr = BitConverter.ToInt32(newData, 4);
int oldPtr = BitConverter.ToInt32(oldData, 4);
@@ -269,7 +269,7 @@ private void PB_BCLIM_Click(object sender, EventArgs e)
}
// Utility
private Size CLIMWindow;
private readonly Size CLIMWindow;
private void B_Reset_Click(object sender, EventArgs e)
{
PB_BCLIM.Size = CLIMWindow;

View File

@@ -6,7 +6,6 @@
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text.RegularExpressions;
using System.Windows.Forms;
namespace pk3DS
@@ -15,64 +14,39 @@ class Util
{ // Image Layering/Blending Utility
internal static Bitmap LayerImage(Image baseLayer, Image overLayer, int x, int y, double trans)
{
Bitmap overlayImage = (Bitmap)overLayer;
Bitmap newImage = (Bitmap)baseLayer;
if (baseLayer == null) return overlayImage;
for (int i = 0; i < (overlayImage.Width * overlayImage.Height); i++)
Bitmap img = new Bitmap(baseLayer.Width, baseLayer.Height);
using (Graphics gr = Graphics.FromImage(img))
{
Color newColor = overlayImage.GetPixel(i % (overlayImage.Width), i / (overlayImage.Width));
Color oldColor = newImage.GetPixel(i % (overlayImage.Width) + x, i / (overlayImage.Width) + y);
newColor = Color.FromArgb((int)(newColor.A * trans), newColor.R, newColor.G, newColor.B); // Apply transparency change
// if (newColor.A != 0) // If Pixel isn't transparent, we'll overwrite the color.
{
// if (newColor.A < 100)
newColor = AlphaBlend(newColor, oldColor);
newImage.SetPixel(
i % (overlayImage.Width) + x,
i / (overlayImage.Width) + y,
newColor);
}
gr.DrawImage(baseLayer, new Point(0, 0));
Bitmap o = ChangeOpacity(overLayer, trans);
gr.DrawImage(o, new Rectangle(x, y, overLayer.Width, overLayer.Height));
}
return newImage;
return img;
}
internal static Bitmap ChangeOpacity(Image img, double trans)
{
if (img == null) return null;
Bitmap bmp = new Bitmap(img.Width, img.Height); // Determining Width and Height of Source Image
Graphics graphics = Graphics.FromImage(bmp);
ColorMatrix colormatrix = new ColorMatrix();
colormatrix.Matrix33 = (float)trans;
ImageAttributes imgAttribute = new ImageAttributes();
imgAttribute.SetColorMatrix(colormatrix, ColorMatrixFlag.Default, ColorAdjustType.Bitmap);
graphics.DrawImage(img, new Rectangle(0, 0, bmp.Width, bmp.Height), 0, 0, img.Width, img.Height, GraphicsUnit.Pixel, imgAttribute);
graphics.Dispose(); // Releasing all resource used by graphics
if (img == null)
return null;
if (img.PixelFormat.HasFlag(PixelFormat.Indexed))
return (Bitmap)img;
Bitmap bmp = (Bitmap)img.Clone();
BitmapData bmpData = bmp.LockBits(new Rectangle(0, 0, bmp.Width, bmp.Height), ImageLockMode.ReadWrite, PixelFormat.Format32bppArgb);
IntPtr ptr = bmpData.Scan0;
int len = bmp.Width * bmp.Height * 4;
byte[] data = new byte[len];
Marshal.Copy(ptr, data, 0, len);
for (int i = 0; i < data.Length; i += 4)
data[i + 3] = (byte)(data[i + 3] * trans);
Marshal.Copy(data, 0, ptr, len);
bmp.UnlockBits(bmpData);
return bmp;
}
internal static Color AlphaBlend(Color ForeGround, Color BackGround)
{
if (ForeGround.A == 0)
return BackGround;
if (BackGround.A == 0)
return ForeGround;
if (ForeGround.A == 255)
return ForeGround;
int Alpha = Convert.ToInt32(ForeGround.A);
int B = Alpha * ForeGround.B + (255 - Alpha) * BackGround.B >> 8;
int G = Alpha * ForeGround.G + (255 - Alpha) * BackGround.G >> 8;
int R = Alpha * ForeGround.R + (255 - Alpha) * BackGround.R >> 8;
int A = ForeGround.A;
if (BackGround.A == 255)
A = 255;
if (A > 255)
A = 255;
if (R > 255)
R = 255;
if (G > 255)
G = 255;
if (B > 255)
B = 255;
return Color.FromArgb(Math.Abs(A), Math.Abs(R), Math.Abs(G), Math.Abs(B));
}
internal static Bitmap getSprite(int species, int form, int gender, int item)
{
string file;
@@ -123,8 +97,8 @@ internal static Bitmap scaleImage(Bitmap rawImg, int s)
internal static FileInfo GetNewestFile(DirectoryInfo directory)
{
return directory.GetFiles()
.Union(directory.GetDirectories().Select(d => GetNewestFile(d)))
.OrderByDescending(f => (f == null ? DateTime.MinValue : f.LastWriteTime))
.Union(directory.GetDirectories().Select(GetNewestFile))
.OrderByDescending(f => f?.LastWriteTime ?? DateTime.MinValue)
.FirstOrDefault();
}
internal static string NormalizePath(string path)
@@ -147,7 +121,7 @@ internal static string TrimFromZero(string input)
internal static string[] getStringList(string f, string l)
{
object txt = Properties.Resources.ResourceManager.GetObject("text_" + f + "_" + l); // Fetch File, \n to list.
List<string> rawlist = ((string)txt).Split(new char[] { '\n' }).ToList();
List<string> rawlist = ((string)txt).Split('\n').ToList();
string[] stringdata = new string[rawlist.Count];
for (int i = 0; i < rawlist.Count; i++)
@@ -158,7 +132,7 @@ internal static string[] getStringList(string f, string l)
internal static string[] getSimpleStringList(string f)
{
object txt = Properties.Resources.ResourceManager.GetObject(f); // Fetch File, \n to list.
List<string> rawlist = ((string)txt).Split(new char[] { '\n' }).ToList();
List<string> rawlist = ((string)txt).Split('\n').ToList();
string[] stringdata = new string[rawlist.Count];
for (int i = 0; i < rawlist.Count; i++)
@@ -194,27 +168,27 @@ internal static uint ToUInt32(MaskedTextBox tb)
string value = tb.Text;
return ToUInt32(value);
}
internal static int ToInt32(String value)
internal static int ToInt32(string value)
{
value = value.Replace(" ", "");
if (String.IsNullOrEmpty(value))
if (string.IsNullOrEmpty(value))
return 0;
try
{
value = value.TrimEnd(new char[] { '_' });
return Int32.Parse(value);
value = value.TrimEnd('_');
return int.Parse(value);
}
catch { return 0; }
}
internal static uint ToUInt32(String value)
internal static uint ToUInt32(string value)
{
value = value.Replace(" ", "");
if (String.IsNullOrEmpty(value))
if (string.IsNullOrEmpty(value))
return 0;
try
{
value = value.TrimEnd(new char[] { '_' });
return UInt32.Parse(value);
value = value.TrimEnd('_');
return uint.Parse(value);
}
catch { return 0; }
}
@@ -223,11 +197,11 @@ internal static uint getHEXval(TextBox tb)
if (tb.Text == null)
return 0;
string str = getOnlyHex(tb.Text);
return UInt32.Parse(str, NumberStyles.HexNumber);
return uint.Parse(str, NumberStyles.HexNumber);
}
internal static int getIndex(ComboBox cb)
{
int val = 0;
int val;
if (cb.SelectedValue == null)
return 0;
@@ -241,12 +215,11 @@ internal static string getOnlyHex(string str)
{
if (str == null) return "0";
char c;
string s = "";
for (int i = 0; i < str.Length; i++)
foreach (char t in str)
{
c = str[i];
var c = t;
// filter for hex
if ((c < 0x0047 && c > 0x002F) || (c < 0x0067 && c > 0x0060))
s += c;
@@ -272,24 +245,18 @@ internal static void Shuffle<T>(T[] array)
}
// Form Translation
internal static void TranslateInterface(Control form, string lang, MenuStrip menu = null)
internal static void TranslateInterface(Control form, string lang)
{
string FORM_NAME = form.Name;
Control.ControlCollection Controls = form.Controls;
// debug(Controls);
// Fetch a File
// Check to see if a the translation file exists in the same folder as the executable
string externalLangPath = System.Windows.Forms.Application.StartupPath + Path.DirectorySeparatorChar + "lang_" + lang + ".txt";
string externalLangPath = "lang_" + lang + ".txt";
string[] rawlist;
if (File.Exists(externalLangPath))
rawlist = File.ReadAllLines(externalLangPath);
else
{
object txt;
txt = Properties.Resources.ResourceManager.GetObject("lang_" + lang); // Fetch File, \n to list.
object txt = Properties.Resources.ResourceManager.GetObject("lang_" + lang);
if (txt == null) return; // Translation file does not exist as a resource; abort this function and don't translate UI.
string[] stringSeparators = new string[] { "\r\n" }; // Resource files are notepad compatible
rawlist = ((string)txt).Split(stringSeparators, StringSplitOptions.None);
rawlist = ((string)txt).Split(new[] { "\n" }, StringSplitOptions.None);
rawlist = rawlist.Select(i => i.Trim()).ToArray(); // Remove trailing spaces
}
@@ -298,78 +265,89 @@ internal static void TranslateInterface(Control form, string lang, MenuStrip men
for (int i = 0; i < rawlist.Length; i++)
{
// Find our starting point
if (rawlist[i].Contains("! " + FORM_NAME)) // Start our data
if (!rawlist[i].Contains("! " + form.Name)) continue;
// Allow renaming of the Window Title
string[] WindowName = rawlist[i].Split(new[] { " = " }, StringSplitOptions.None);
if (WindowName.Length > 1) form.Text = WindowName[1];
// Copy our Control Names and Text to a new array for later processing.
for (int j = i + 1; j < rawlist.Length; j++)
{
// Allow renaming of the Window Title
string[] WindowName = Regex.Split(rawlist[i], " = ");
if (WindowName.Length > 1) form.Text = WindowName[1];
// Copy our Control Names and Text to a new array for later processing.
for (int j = i + 1; j < rawlist.Length; j++)
{
if (rawlist[j].Length == 0)
continue; // Skip Over Empty Lines, errhandled
if (rawlist[j][0].ToString() != "-") // If line is not a comment line...
{
if (rawlist[j][0].ToString() == "!") // Stop if we have reached the end of translation
goto rename;
stringdata[itemsToRename] = rawlist[j]; // Add the entry to process later.
itemsToRename++;
}
}
if (rawlist[j].Length == 0) continue; // Skip Over Empty Lines, errhandled
if (rawlist[j][0].ToString() == "-") continue; // Keep translating if line is a comment line
if (rawlist[j][0].ToString() == "!") // Stop if we have reached the end of translation
goto rename;
stringdata[itemsToRename] = rawlist[j]; // Add the entry to process later.
itemsToRename++;
}
}
return; // Not Found
// Now that we have our items to rename in: Control = Text format, let's execute the changes!
rename:
rename:
for (int i = 0; i < itemsToRename; i++)
{
string[] SplitString = Regex.Split(stringdata[i], " = ");
string[] SplitString = stringdata[i].Split(new[] { " = " }, StringSplitOptions.None);
if (SplitString.Length < 2)
continue; // Error in Input, errhandled
string ctrl = SplitString[0]; // Control to change the text of...
string text = SplitString[1]; // Text to set Control.Text to...
Control[] controllist = Controls.Find(ctrl, true);
if (controllist.Length == 0) // If Control isn't found...
try
{
// Menu Items can't be found with Controls.Find as they aren't Controls
ToolStripDropDownItem TSI = (ToolStripDropDownItem)menu.Items[ctrl];
if (TSI != null)
{
// We'll rename the main and child in a row.
string[] ToolItems = Regex.Split(SplitString[1], " ; ");
TSI.Text = ToolItems[0]; // Set parent's text first
if (TSI.DropDownItems.Count != ToolItems.Length - 1)
continue; // Error in Input, errhandled
for (int ti = 1; ti <= TSI.DropDownItems.Count; ti++)
TSI.DropDownItems[ti - 1].Text = ToolItems[ti]; // Set child text
}
// If not found, it is not something to rename and is thus skipped.
}
catch { }
else // Set the input control's text.
controllist[0].Text = text;
Control[] controllist = form.Controls.Find(ctrl, true);
if (controllist.Length != 0) // If Control is found
{ controllist[0].Text = text; goto next; }
// Check MenuStrips
foreach (MenuStrip menu in form.Controls.OfType<MenuStrip>())
{
// Menu Items aren't in the Form's Control array. Find within the menu's Control array.
ToolStripItem[] TSI = menu.Items.Find(ctrl, true);
if (TSI.Length <= 0) continue;
TSI[0].Text = text; goto next;
}
// Check ContextMenuStrips
foreach (ContextMenuStrip cs in FindContextMenuStrips(form.Controls.OfType<Control>()).Distinct())
{
ToolStripItem[] TSI = cs.Items.Find(ctrl, true);
if (TSI.Length <= 0) continue;
TSI[0].Text = text; goto next;
}
next:;
}
}
internal static List<ContextMenuStrip> FindContextMenuStrips(IEnumerable<Control> c)
{
List<ContextMenuStrip> cs = new List<ContextMenuStrip>();
foreach (Control control in c)
{
if (control.ContextMenuStrip != null)
cs.Add(control.ContextMenuStrip);
else if (control.Controls.Count > 0)
cs.AddRange(FindContextMenuStrips(control.Controls.OfType<Control>()));
}
return cs;
}
// Message Displays
internal static DialogResult Error(params string[] lines)
{
System.Media.SystemSounds.Exclamation.Play();
string msg = String.Join(Environment.NewLine + Environment.NewLine, lines);
string msg = string.Join(Environment.NewLine + Environment.NewLine, lines);
return MessageBox.Show(msg, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
internal static DialogResult Alert(params string[] lines)
{
System.Media.SystemSounds.Asterisk.Play();
string msg = String.Join(Environment.NewLine + Environment.NewLine, lines);
string msg = string.Join(Environment.NewLine + Environment.NewLine, lines);
return MessageBox.Show(msg, "Alert", MessageBoxButtons.OK, MessageBoxIcon.Warning);
}
internal static DialogResult Prompt(MessageBoxButtons btn, params string[] lines)
{
System.Media.SystemSounds.Question.Play();
string msg = String.Join(Environment.NewLine + Environment.NewLine, lines);
string msg = string.Join(Environment.NewLine + Environment.NewLine, lines);
return MessageBox.Show(msg, "Prompt", btn, MessageBoxIcon.Asterisk);
}
@@ -382,11 +360,10 @@ public class cbItem
internal static List<cbItem> getCBList(string textfile, string lang)
{
// Set up
List<cbItem> cbList = new List<cbItem>();
string[] inputCSV = Util.getSimpleStringList(textfile);
string[] inputCSV = getSimpleStringList(textfile);
// Get Language we're fetching for
int index = Array.IndexOf(new string[] { "ja", "en", "fr", "de", "it", "es", "ko", "zh", }, lang);
int index = Array.IndexOf(new[] { "ja", "en", "fr", "de", "it", "es", "ko", "zh", }, lang);
// Set up our Temporary Storage
string[] unsortedList = new string[inputCSV.Length - 1];
@@ -406,20 +383,16 @@ internal static List<cbItem> getCBList(string textfile, string lang)
Array.Sort(sortedList);
// Arrange the input data based on original number
for (int i = 0; i < sortedList.Length; i++)
return sortedList.Select(t => new cbItem
{
cbItem ncbi = new cbItem();
ncbi.Text = sortedList[i];
ncbi.Value = indexes[Array.IndexOf(unsortedList, sortedList[i])];
cbList.Add(ncbi);
}
return cbList;
Text = t, Value = indexes[Array.IndexOf(unsortedList, t)]
}).ToList();
}
internal static List<cbItem> getCBList(string[] inStrings, params int[][] allowed)
{
List<cbItem> cbList = new List<cbItem>();
if (allowed == null)
allowed = new int[][] { Enumerable.Range(0, inStrings.Length).ToArray() };
allowed = new[] { Enumerable.Range(0, inStrings.Length).ToArray() };
foreach (int[] list in allowed)
{
@@ -433,13 +406,10 @@ internal static List<cbItem> getCBList(string[] inStrings, params int[][] allowe
Array.Sort(sortedChoices);
// Add the rest of the items
for (int i = 0; i < sortedChoices.Length; i++)
cbList.AddRange(sortedChoices.Select(t => new cbItem
{
cbItem ncbi = new cbItem();
ncbi.Text = sortedChoices[i];
ncbi.Value = list[Array.IndexOf(unsortedChoices, sortedChoices[i])];
cbList.Add(ncbi);
}
Text = t, Value = list[Array.IndexOf(unsortedChoices, t)]
}));
}
return cbList;
}
@@ -463,13 +433,10 @@ internal static List<cbItem> getOffsetCBList(List<cbItem> cbList, string[] inStr
Array.Sort(sortedChoices);
// Add the rest of the items
for (int i = 0; i < sortedChoices.Length; i++)
cbList.AddRange(sortedChoices.Select(t => new cbItem
{
cbItem ncbi = new cbItem();
ncbi.Text = sortedChoices[i];
ncbi.Value = allowed[Array.IndexOf(unsortedChoices, sortedChoices[i])];
cbList.Add(ncbi);
}
Text = t, Value = allowed[Array.IndexOf(unsortedChoices, t)]
}));
}
return cbList;
}
@@ -481,9 +448,11 @@ internal static List<cbItem> getVariedCBList(List<cbItem> cbList, string[] inStr
for (int i = 4; i > 1; i--) // add 4,3,2
{
// First 3 Balls are always first
cbItem ncbi = new cbItem();
ncbi.Text = inStrings[i];
ncbi.Value = i;
cbItem ncbi = new cbItem
{
Text = inStrings[i],
Value = i
};
newlist.Add(ncbi);
}
@@ -497,28 +466,27 @@ internal static List<cbItem> getVariedCBList(List<cbItem> cbList, string[] inStr
Array.Sort(sortedballs);
// Add the rest of the balls
for (int i = 0; i < sortedballs.Length; i++)
newlist.AddRange(sortedballs.Select(t => new cbItem
{
cbItem ncbi = new cbItem();
ncbi.Text = sortedballs[i];
ncbi.Value = stringVal[Array.IndexOf(ballnames, sortedballs[i])];
newlist.Add(ncbi);
}
Text = t, Value = stringVal[Array.IndexOf(ballnames, t)]
}));
return newlist;
}
internal static List<cbItem> getUnsortedCBList(string textfile)
{
// Set up
List<cbItem> cbList = new List<cbItem>();
string[] inputCSV = Util.getSimpleStringList(textfile);
string[] inputCSV = getSimpleStringList(textfile);
// Gather our data from the input file
for (int i = 1; i < inputCSV.Length; i++)
{
string[] inputData = inputCSV[i].Split(',');
cbItem ncbi = new cbItem();
ncbi.Value = Convert.ToInt32(inputData[0]);
ncbi.Text = inputData[1];
cbItem ncbi = new cbItem
{
Value = Convert.ToInt32(inputData[0]),
Text = inputData[1]
};
cbList.Add(ncbi);
}
return cbList;
@@ -562,7 +530,7 @@ internal static string GuessExtension(BinaryReader br, string defaultExt, bool b
if (br.ReadUInt32() == 0x63726164)
return "darc";
}
catch { };
catch { }
// check for bclim
try
@@ -606,8 +574,8 @@ internal static string GuessExtension(BinaryReader br, string defaultExt, bool b
}
internal static string GuessExtension(string path, bool bypass)
{
using (BinaryReader br = new BinaryReader(System.IO.File.OpenRead(path)))
return Util.GuessExtension(br, "bin", bypass);
using (BinaryReader br = new BinaryReader(File.OpenRead(path)))
return GuessExtension(br, "bin", bypass);
}
internal static uint Reverse(uint x)
{
@@ -650,7 +618,7 @@ internal static string getHexString(byte[] data)
}
internal static void resizeJagged(ref byte[][] array, int size, int lowLen)
{
int oldSize = (array == null) ? 0 : array.Length;
int oldSize = array?.Length ?? 0;
Array.Resize(ref array, size);
// Zero fill new data
@@ -688,7 +656,7 @@ internal static int highlightText(RichTextBox RTB, string word, Color hlColor)
// http://stackoverflow.com/questions/4820212/automatically-trim-a-bitmap-to-minimum-size
internal static Bitmap TrimBitmap(Bitmap source)
{
Rectangle srcRect = default(Rectangle);
Rectangle srcRect;
BitmapData data = null;
try
{