implemented CPZ archives and PB3 images (#10)

This commit is contained in:
morkt 2015-12-03 16:16:54 +04:00
parent 007b835320
commit 7e30141e94
5 changed files with 1045 additions and 0 deletions

View File

@ -66,11 +66,15 @@
<Compile Include="Amaterasu\ImageGRP.cs" />
<Compile Include="AnimeGameSystem\ArcDAT.cs" />
<Compile Include="AnimeGameSystem\AudioPCM.cs" />
<Compile Include="Cmvs\ArcCPZ.cs" />
<Compile Include="ArcPBX.cs" />
<Compile Include="Banana\ArcPK.cs" />
<Compile Include="Banana\ImageMAG.cs" />
<Compile Include="CatSystem\ArcHG2.cs" />
<Compile Include="CatSystem\ImageHG2.cs" />
<Compile Include="Cmvs\CmvsMD5.cs" />
<Compile Include="Cmvs\ImagePB3.cs" />
<Compile Include="elf\ArcVSD.cs" />
<Compile Include="Eushully\ArcGPC.cs" />
<Compile Include="Eushully\ImageGP.cs" />
<Compile Include="FC01\WidgetMCG.xaml.cs">

486
ArcFormats/Cmvs/ArcCPZ.cs Normal file
View File

@ -0,0 +1,486 @@
//! \file ArcCPZ.cs
//! \date Tue Nov 24 11:27:23 2015
//! \brief Purple Software resource archive.
//
// Copyright (C) 2015 by morkt
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to
// deal in the Software without restriction, including without limitation the
// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
// sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
// IN THE SOFTWARE.
//
using System;
using System.Collections.Generic;
using System.ComponentModel.Composition;
using System.IO;
using System.Linq;
using GameRes.Utility;
using System.Security.Cryptography;
namespace GameRes.Formats.Purple
{
[Serializable]
public class CpzScheme : ResourceScheme
{
public uint[] Cpz5Secret;
}
internal class CpzEntry : Entry
{
public uint CheckSum;
public uint Key;
public uint DirKey;
}
internal class CpzHeader
{
public int DirCount;
public int DirEntriesSize;
public int FileEntriesSize;
public uint[] CmvsMd5 = new uint[4];
public uint MasterKey;
public bool IsEncrypted;
public bool IsCompressed;
}
internal class CpzArchive : ArcFile
{
public CpzHeader Header;
public Cpz5Decoder Decoder;
public CpzArchive (ArcView arc, ArchiveFormat impl, ICollection<Entry> dir, CpzHeader header, Cpz5Decoder decoder)
: base (arc, impl, dir)
{
Header = header;
Decoder = decoder;
}
}
[Export(typeof(ArchiveFormat))]
public class CpzOpener : ArchiveFormat
{
public override string Tag { get { return "CPZ"; } }
public override string Description { get { return "Purple Software resource archive"; } }
public override uint Signature { get { return 0x355A5043; } } // 'CPZ5'
public override bool IsHierarchic { get { return true; } }
public override bool CanCreate { get { return false; } }
public static CpzScheme CmvsScheme = new CpzScheme();
public override ResourceScheme Scheme
{
get { return CmvsScheme; }
set { CmvsScheme = (CpzScheme)value; }
}
public override ArcFile TryOpen (ArcView file)
{
if (null == CmvsScheme.Cpz5Secret)
throw new OperationCanceledException ("Outdated encryption schemes database");
var header = file.View.ReadBytes (0, 0x3C);
var checksum = file.View.ReadUInt32 (0x3C);
if (checksum != CheckSum (header, 0, 0x3C, 0x923A564Cu))
return null;
var cpz = new CpzHeader
{
DirCount = -0x1C5AC27 ^ LittleEndian.ToInt32 (header, 4),
DirEntriesSize = 0x37F298E7 ^ LittleEndian.ToInt32 (header, 8),
FileEntriesSize = 0x7A6F3A2C ^ LittleEndian.ToInt32 (header, 0x0C),
MasterKey = 0xAE7D39BF ^ LittleEndian.ToUInt32 (header, 0x30),
IsEncrypted = 0 != (0xFB73A955 ^ LittleEndian.ToUInt32 (header, 0x34)),
IsCompressed = 0 != (0x37ACF831 ^ LittleEndian.ToUInt32 (header, 0x38)),
};
cpz.CmvsMd5[0] = 0x43DE7C19 ^ LittleEndian.ToUInt32 (header, 0x20);
cpz.CmvsMd5[1] = 0xCC65F415 ^ LittleEndian.ToUInt32 (header, 0x24);
cpz.CmvsMd5[2] = 0xD016A93C ^ LittleEndian.ToUInt32 (header, 0x28);
cpz.CmvsMd5[3] = 0x97A3BA9A ^ LittleEndian.ToUInt32 (header, 0x2C);
var cmvs_md5 = new Cmvs.Md5VariantB();
cmvs_md5.Compute (cpz.CmvsMd5);
int index_size = cpz.DirEntriesSize + cpz.FileEntriesSize;
var index = file.View.ReadBytes (0x40, (uint)index_size);
if (index.Length != index_size)
return null;
var md5 = MD5.Create();
var hash = md5.ComputeHash (index);
if (!header.Skip (0x10).Take (0x10).SequenceEqual (hash))
return null;
DecryptIndexStage1 (index, cpz.MasterKey ^ 0x3795B39A);
// variantA: 0x1A743125, variantB: 0x1A740235
var decoder = new Cpz5Decoder (cpz.MasterKey, cpz.CmvsMd5[1], 0x1A740235);
decoder.Decode (index, 0, cpz.DirEntriesSize, 0x3A);
var key = new uint[4];
key[0] = cpz.CmvsMd5[0] ^ (cpz.MasterKey + 0x76A3BF29);
key[1] = cpz.CmvsMd5[1] ^ cpz.MasterKey;
key[2] = cpz.CmvsMd5[2] ^ (cpz.MasterKey + 0x10000000);
key[3] = cpz.CmvsMd5[3] ^ cpz.MasterKey;
DecryptIndexDirectory (index, cpz.DirEntriesSize, key);
decoder.Init (cpz.MasterKey, cpz.CmvsMd5[2], 0x1A740235);
int base_offset = 0x40 + index_size;
int dir_offset = 0;
var dir = new List<Entry>();
for (int i = 0; i < cpz.DirCount; ++i)
{
int dir_size = LittleEndian.ToInt32 (index, dir_offset);
if (dir_size <= 0x10 || dir_size > index.Length)
return null;
int file_count = LittleEndian.ToInt32 (index, dir_offset+4);
int entries_offset = LittleEndian.ToInt32 (index, dir_offset+8);
uint dir_key = LittleEndian.ToUInt32 (index, dir_offset+0xC);
var dir_name = Binary.GetCString (index, dir_offset+0x10, dir_size-0x10);
int next_entries_offset;
if (i + 1 == cpz.DirCount)
next_entries_offset = cpz.FileEntriesSize;
else
next_entries_offset = LittleEndian.ToInt32 (index, dir_offset + dir_size + 8);
int cur_entries_size = next_entries_offset - entries_offset;
int cur_offset = cpz.DirEntriesSize + entries_offset;
int cur_entries_end = cur_offset + cur_entries_size;
decoder.Decode (index, cur_offset, cur_entries_size, 0x7E);
key[0] = cpz.CmvsMd5[0] ^ dir_key;
key[1] = cpz.CmvsMd5[1] ^ (dir_key + 0x112233);
key[2] = cpz.CmvsMd5[2] ^ dir_key;
key[3] = cpz.CmvsMd5[3] ^ (dir_key + 0x34258765);
DecryptIndexEntry (index, cur_offset, cur_entries_size, key);
bool is_root_dir = dir_name == "root";
dir.Capacity = dir.Count + file_count;
for (int j = 0; j < file_count; ++j)
{
int entry_size = LittleEndian.ToInt32 (index, cur_offset);
if (entry_size > index.Length || entry_size <= 0x18)
throw new UnknownEncryptionScheme();
var name = Binary.GetCString (index, cur_offset+0x18, cur_entries_end-(cur_offset+0x18));
if (!is_root_dir)
name = Path.Combine (dir_name, name);
var entry = FormatCatalog.Instance.Create<CpzEntry> (name);
entry.Offset = LittleEndian.ToInt64 (index, cur_offset+4) + base_offset;
entry.Size = LittleEndian.ToUInt32 (index, cur_offset+0xC);
entry.CheckSum = LittleEndian.ToUInt32 (index, cur_offset+0x10);
entry.Key = LittleEndian.ToUInt32 (index, cur_offset+0x14);
entry.DirKey = dir_key;
if (!entry.CheckPlacement (file.MaxOffset))
return null;
dir.Add (entry);
cur_offset += entry_size;
}
dir_offset += dir_size;
}
if (cpz.IsEncrypted)
decoder.Init (cpz.CmvsMd5[3], cpz.MasterKey, 0x1A740235);
return new CpzArchive (file, this, dir, cpz, decoder);
}
public override Stream OpenEntry (ArcFile arc, Entry entry)
{
var carc = arc as CpzArchive;
var cent = entry as CpzEntry;
if (null == carc || null == cent)
return base.OpenEntry (arc, entry);
var data = carc.File.View.ReadBytes (entry.Offset, entry.Size);
if (carc.Header.IsEncrypted)
{
uint key = (carc.Header.MasterKey ^ (cent.DirKey + cent.Key)) + (uint)carc.Header.DirCount - 0x5C29E87B;
carc.Decoder.DecryptEntry (data, carc.Header.CmvsMd5, key);
}
if (data.Length > 0x30 && Binary.AsciiEqual (data, 0, "PS2A"))
data = UnpackPs2 (data);
else if (data.Length > 0x40 && Binary.AsciiEqual (data, 0, "PB3B"))
DecryptPb3 (data);
return new MemoryStream (data);
}
void DecryptIndexStage1 (byte[] data, uint key)
{
var sectet_key = new uint[24];
int secret_length = Math.Min (24, CmvsScheme.Cpz5Secret.Length);
for (int i = 0; i < secret_length; ++i)
sectet_key[i] = CmvsScheme.Cpz5Secret[i] - key;
uint shift = key;
shift = (shift >> 8) ^ key;
shift = (shift >> 8) ^ key;
shift = (shift >> 8) ^ key;
shift = (shift >> 8) ^ key;
shift = ((shift ^ 0xB) & 0xF) + 7;
unsafe
{
fixed (byte* raw = data)
{
uint* data32 = (uint*)raw;
int i = 5;
for (int n = data.Length / 4; n > 0; --n)
{
*data32 = Binary.RotR ((sectet_key[i] ^ *data32) + 0x784C5962, (int)shift) + 0x01010101;
++data32;
i = (i + 1) % 24;
}
byte* data8 = (byte*)data32;
for (int n = data.Length & 3; n > 0; --n)
{
*data8 = (byte)((*data8 ^ (sectet_key[i] >> (n * 4))) - 0x79);
++data8;
i = (i + 1) % 24;
}
}
}
}
void DecryptIndexDirectory (byte[] data, int length, uint[] key)
{
uint seed = 0x76548AEF;
unsafe
{
fixed (byte* raw = data)
{
uint* data32 = (uint*)raw;
int i;
for (i = 0; i < length / 4; ++i)
{
*data32 = Binary.RotL ((*data32 ^ key[i & 3]) - 0x4A91C262, 3) - seed;
++data32;
seed += 0x10FB562A;
}
byte* data8 = (byte*)data32;
for (int j = length & 3; j > 0; --j)
{
*data8 = (byte)((*data8 ^ (key[i++ & 3] >> 6)) + 0x37);
++data8;
}
}
}
}
void DecryptIndexEntry (byte[] data, int offset, int length, uint[] key)
{
if (offset < 0 || offset > data.Length)
throw new ArgumentOutOfRangeException ("offset");
if (length < 0 || length > data.Length || length > data.Length-offset)
throw new ArgumentException ("length");
uint seed = 0x2A65CB4E;
unsafe
{
fixed (byte* raw = &data[offset])
{
uint* data32 = (uint*)raw;
int i;
for (i = 0; i < length / 4; ++i)
{
*data32 = Binary.RotL ((*data32 ^ key[i & 3]) - seed, 2) + 0x37A19E8B;
++data32;
seed -= 0x139FA9B;
}
byte* data8 = (byte*)data32;
for (int j = length & 3; j > 0; --j)
{
*data8 = (byte)((*data8 ^ (key[i++ & 3] >> 4)) + 5);
++data8;
}
}
}
}
public static uint CheckSum (byte[] data, int index, int length, uint crc)
{
if (null == data)
throw new ArgumentNullException ("data");
if (index < 0 || index > data.Length)
throw new ArgumentOutOfRangeException ("index");
if (length < 0 || length > data.Length || length > data.Length-index)
throw new ArgumentException ("length");
int dwords = length / 4;
if (dwords > 0)
{
unsafe
{
fixed (byte* raw = &data[index])
{
uint* raw32 = (uint*)raw;
for (int i = 0; i < dwords; ++i)
crc += raw32[i];
}
}
index += length & -4;
}
for (int i = 0; i < (length & 3); ++i)
crc += data[index+i];
return crc;
}
byte[] UnpackPs2 (byte[] data)
{
DecryptPs2 (data);
byte[] frame = new byte[0x800];
int frame_pos = 0x7DF;
int unpacked_size = LittleEndian.ToInt32 (data, 0x28);
byte[] output = new byte[0x30+unpacked_size];
Buffer.BlockCopy (data, 0, output, 0, 0x30);
int src = 0x30;
int dst = 0x30;
int ctl = 1;
while (dst < output.Length && src < data.Length)
{
if (1 == ctl)
ctl = data[src++] | 0x100;
if (0 != (ctl & 1))
{
byte b = data[src++];
output[dst++] = b;
frame[frame_pos++] = b;
frame_pos &= 0x7FF;
}
else
{
int lo = data[src++];
int hi = data[src++];
int offset = lo | (hi & 0xE0) << 3;
int count = (hi & 0x1F) + 2;
for (int i = 0; i < count; ++i)
{
byte b = frame[(offset + i) & 0x7FF];
output[dst++] = b;
frame[frame_pos++] = b;
frame_pos &= 0x7FF;
}
}
ctl >>= 1;
}
return output;
}
void DecryptPs2 (byte[] data)
{
uint key = LittleEndian.ToUInt32 (data, 12);
int shift = (int)(key >> 20) % 5 + 1;
key = (key >> 24) + (key >> 3);
for (int i = 0x30; i < data.Length; ++i)
{
data[i] = Binary.RotByteR ((byte)(key ^ (data[i] - 0x7Cu)), shift);
}
}
void DecryptPb3 (byte[] data)
{
byte key1 = data[data.Length-3];
byte key2 = data[data.Length-2];
int src = data.Length - 0x2F;
for (int i = 8; i < 0x34; i += 2)
{
data[i ] ^= key1;
data[i ] -= data[src++];
data[i+1] ^= key2;
data[i+1] -= data[src++];
}
}
}
internal class Cpz5Decoder
{
protected byte[] m_decode_table = new byte[0x100];
public Cpz5Decoder (uint key, uint summand, uint factor)
{
Init (key, summand, factor);
}
public void Init (uint key, uint summand, uint factor)
{
for (int i = 0; i < 0x100; ++i)
m_decode_table[i] = (byte)i;
for (int i = 0; i < 0x100; ++i)
{
uint i0 = (key >> 16) & 0xFF;
uint i1 = key & 0xFF;
var tmp = m_decode_table[i0];
m_decode_table[i0] = m_decode_table[i1];
m_decode_table[i1] = tmp;
i0 = (key >> 8) & 0xFF;
i1 = key >> 24;
tmp = m_decode_table[i0];
m_decode_table[i0] = m_decode_table[i1];
m_decode_table[i1] = tmp;
key = summand + factor * Binary.RotR (key, 2);
}
}
public void Decode (byte[] data, int offset, int length, byte key)
{
for (int i = 0; i < length; ++i)
data[offset+i] = m_decode_table[key ^ data[offset+i]];
}
public void DecryptEntry (byte[] data, uint[] cmvs_md5, uint seed)
{
if (null == data)
throw new ArgumentNullException ("data");
if (null == cmvs_md5 || cmvs_md5.Length < 4)
throw new ArgumentException ("cmvs_md5");
int secret_length = Math.Min (CpzOpener.CmvsScheme.Cpz5Secret.Length, 0x10) * 4;
byte[] key_bytes = new byte[secret_length];
uint[] secret_key = new uint[0x10];
uint key = cmvs_md5[1] >> 2;
Buffer.BlockCopy (CpzOpener.CmvsScheme.Cpz5Secret, 0, key_bytes, 0, secret_length);
for (int i = 0; i < secret_length; ++i)
key_bytes[i] = (byte)(key ^ m_decode_table[key_bytes[i]]);
Buffer.BlockCopy (key_bytes, 0, secret_key, 0, secret_length);
for (int i = 0; i < secret_key.Length; ++i)
secret_key[i] ^= seed;
unsafe
{
fixed (byte* raw = data)
{
uint* data32 = (uint*)raw;
key = 0x2547B39E;
int k = 9;
for (int i = data.Length / 4; i > 0; --i)
{
*data32 = cmvs_md5[key & 3] ^ ((*data32 ^ secret_key[(key >> 6) & 0xf] ^ (secret_key[k] >> 1)) - seed);
k = (k + 1) & 0xf;
key += seed + *data32++;
}
byte* data8 = (byte*)data32;
for (int i = data.Length & 3; i > 0; --i)
{
*data8 = m_decode_table[*data8 ^ 0xCB];
++data8;
}
}
}
}
}
}

147
ArcFormats/Cmvs/CmvsMD5.cs Normal file
View File

@ -0,0 +1,147 @@
//! \file CmvsMD5.cs
//! \date Mon Nov 30 13:29:27 2015
//! \brief Cmvs engine MD5 update algorithm.
//
// Copyright (C) 2015 by morkt
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to
// deal in the Software without restriction, including without limitation the
// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
// sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
// IN THE SOFTWARE.
//
using GameRes.Utility;
namespace GameRes.Formats.Cmvs
{
public abstract class MD5
{
protected uint[] m_state;
protected uint[] m_buffer;
static readonly byte[,] ShiftsTable = {
{ 7, 12, 17, 22 }, { 5, 9, 14, 20 }, { 4, 11, 16, 23 }, { 6, 10, 15, 21 },
};
static readonly uint[] SineTable = {
0xd76aa478, 0xe8c7b756, 0x242070db, 0xc1bdceee, 0xf57c0faf, 0x4787c62a, 0xa8304613, 0xfd469501,
0x698098d8, 0x8b44f7af, 0xffff5bb1, 0x895cd7be, 0x6b901122, 0xfd987193, 0xa679438e, 0x49b40821,
0xf61e2562, 0xc040b340, 0x265e5a51, 0xe9b6c7aa, 0xd62f105d, 0x02441453, 0xd8a1e681, 0xe7d3fbc8,
0x21e1cde6, 0xc33707d6, 0xf4d50d87, 0x455a14ed, 0xa9e3e905, 0xfcefa3f8, 0x676f02d9, 0x8d2a4c8a,
0xfffa3942, 0x8771f681, 0x6d9d6122, 0xfde5380c, 0xa4beea44, 0x4bdecfa9, 0xf6bb4b60, 0xbebfbc70,
0x289b7ec6, 0xeaa127fa, 0xd4ef3085, 0x04881d05, 0xd9d4d039, 0xe6db99e5, 0x1fa27cf8, 0xc4ac5665,
0xf4292244, 0x432aff97, 0xab9423a7, 0xfc93a039, 0x655b59c3, 0x8f0ccc92, 0xffeff47d, 0x85845dd1,
0x6fa87e4f, 0xfe2ce6e0, 0xa3014314, 0x4e0811a1, 0xf7537e82, 0xbd3af235, 0x2ad7d2bb, 0xeb86d391,
};
public MD5 ()
{
m_state = InitState();
m_buffer = new uint[16];
}
protected abstract uint[] InitState ();
protected abstract void SetResult (uint[] data);
public void Compute (uint[] data)
{
m_buffer[0] = data[0];
m_buffer[1] = data[1];
m_buffer[2] = data[2];
m_buffer[3] = data[3];
m_buffer[4] = 0x80;
m_buffer[14] = 0x80;
Transform();
SetResult (data);
}
void Transform ()
{
uint a = m_state[0];
uint b = m_state[1];
uint c = m_state[2];
uint d = m_state[3];
for (int i = 0; i < 64; ++i)
{
uint f;
int g;
if (i < 16)
{
f = d ^ (b & (c ^ d));
g = i;
}
else if (i < 32)
{
f = c ^ (d & (b ^ c));
g = (5 * i + 1) & 0xF;
}
else if (i < 48)
{
f = b ^ c ^ d;
g = (3 * i + 5) & 0xF;
}
else
{
f = c ^ (b | ~d);
g = (7 * i) & 0xF;
}
uint t = d;
d = c;
c = b;
b += Binary.RotL (a + f + m_buffer[g] + SineTable[i], ShiftsTable[i>>4, i&3]);
a = t;
}
m_state[0] += a;
m_state[1] += b;
m_state[2] += c;
m_state[3] += d;
}
}
public class Md5VariantA : MD5
{
protected override uint[] InitState ()
{
return new uint[] { 0xC74A2B01, 0xE7C8AB8F, 0xD8BEDC4E, 0x7302A4C5 };
}
protected override void SetResult (uint[] data)
{
data[0] = m_state[3];
data[1] = m_state[1];
data[2] = m_state[2];
data[3] = m_state[0];
}
}
public class Md5VariantB : MD5
{
protected override uint[] InitState ()
{
return new uint[] { 0x53FE9B2C, 0xF2C93EA8, 0xEE81BA59, 0xA2C8973E };
}
protected override void SetResult (uint[] data)
{
data[0] = m_state[1] ^ 0x49875325;
data[1] = m_state[2] + 0x54F46D7D;
data[2] = m_state[3] ^ 0xAD7948B7;
data[3] = m_state[0] + 0x1D0638AD;
}
}
}

403
ArcFormats/Cmvs/ImagePB3.cs Normal file
View File

@ -0,0 +1,403 @@
//! \file ImagePB3.cs
//! \date Wed Dec 02 13:55:45 2015
//! \brief Cmvs engine image format.
//
// Copyright (C) 2015 by morkt
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to
// deal in the Software without restriction, including without limitation the
// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
// sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
// IN THE SOFTWARE.
//
using GameRes.Utility;
using System;
using System.ComponentModel.Composition;
using System.IO;
using System.Windows.Media;
namespace GameRes.Formats.Purple
{
internal class Pb3MetaData : ImageMetaData
{
public int Type;
public int SubType;
public int InputSize;
}
[Export(typeof(ImageFormat))]
public class Pb3Format : ImageFormat
{
public override string Tag { get { return "PB3"; } }
public override string Description { get { return "Purple Software image format"; } }
public override uint Signature { get { return 0x42334250; } } // 'PB3B'
public override ImageMetaData ReadMetaData (Stream stream)
{
stream.Position = 4;
using (var reader = new ArcView.Reader (stream))
{
int input_size = reader.ReadInt32();
stream.Position = 0x18;
int t2 = reader.ReadInt32();
int t1 = reader.ReadUInt16();
uint width = reader.ReadUInt16();
uint height = reader.ReadUInt16();
int bpp = reader.ReadUInt16();
return new Pb3MetaData
{
Width = width,
Height = height,
BPP = bpp,
Type = t1,
SubType = t2,
InputSize = input_size,
};
}
}
public override ImageData Read (Stream stream, ImageMetaData info)
{
var reader = new Pb3Reader (stream, (Pb3MetaData)info);
reader.Unpack();
return ImageData.Create (info, reader.Format, null, reader.Data);
}
public override void Write (Stream file, ImageData image)
{
throw new System.NotImplementedException ("Pb3Format.Write not implemented");
}
}
internal sealed class Pb3Reader
{
byte[] m_input;
Pb3MetaData m_info;
int m_channels;
int m_stride;
byte[] m_output;
byte[] m_lzss_frame;
public PixelFormat Format { get; private set; }
public byte[] Data { get { return m_output; } }
public Pb3Reader (Stream input, Pb3MetaData info)
{
if (info.Type == 1 && info.SubType != 0x10)
throw new NotSupportedException();
m_info = info;
m_input = new byte[m_info.InputSize];
if (m_input.Length != input.Read (m_input, 0, m_input.Length))
throw new EndOfStreamException();
m_channels = m_info.BPP / 8;
m_stride = 4 * (int)m_info.Width;
m_lzss_frame = new byte[0x800];
Format = m_channels < 4 ? PixelFormats.Bgr32 : PixelFormats.Bgra32;
// output array created by unpack methods as needed.
}
public void Unpack ()
{
switch (m_info.Type)
{
case 1: UnpackV1(); break;
case 5: UnpackV5(); break;
case 8:
case 6: UnpackV6(); break;
default: throw new NotSupportedException(string.Format ("PB3 v{0} images not supported", m_info.Type));
// V3 is pain in the ass to implement, machine code is full of unrolled loops resulting in a
// thousands lines of spaghetti code.
}
}
void UnpackV1 ()
{
int width = (int)m_info.Width;
int height = (int)m_info.Height;
m_output = new byte[m_stride * height];
int plane_size = width * height;
byte[] plane = new byte[plane_size];
int data1 = LittleEndian.ToInt32 (m_input, 0x2C);
int data2 = LittleEndian.ToInt32 (m_input, 0x30);
for (int channel = 0; channel < m_channels; ++channel)
{
int channel_offset = 4 * m_channels;
for (int i = 0; i < channel; ++i)
channel_offset += LittleEndian.ToInt32 (m_input, data1 + 4*i);
int v21 = data1 + channel_offset;
int bit_src = v21 + 12 + LittleEndian.ToInt32 (m_input, v21) + LittleEndian.ToInt32 (m_input, v21+4);
int channel_size = LittleEndian.ToInt32 (m_input, v21 + 8);
channel_offset = 4 * m_channels;
for (int i = 0; i < channel; ++i)
channel_offset += LittleEndian.ToInt32 (m_input, data2 + 4*i);
int data_src = data2 + channel_offset;
for (int i = 0; i < 0x7DE; ++i)
m_lzss_frame[i] = 0;
LzssUnpack (bit_src, data_src, plane, channel_size);
int x_blocks = width >> 4;
if (0 != (width & 0xF))
++x_blocks;
int y_blocks = height >> 4;
if (0 != (height & 0xF))
++y_blocks;
if (0 == y_blocks || 0 == x_blocks)
continue;
int plane_src = 0;
bit_src = v21 + 12;
int bit_mask = 128;
data_src = bit_src + LittleEndian.ToInt32 (m_input, v21);
int v68 = 16;
for (int y = 0; y < y_blocks; ++y)
{
int row = 16 * y;
int v66 = 16;
int dst_origin = m_stride * row + channel; // within m_output
for (int x = 0; x < x_blocks; ++x)
{
int dst = dst_origin;
int block_width = v66 > width ? width - 16 * x : 16;
int block_height = v68 > height ? height - row : 16;
if (0 == bit_mask)
{
++bit_src;
bit_mask = 128;
}
if (0 != (bit_mask & m_input[bit_src]))
{
byte b = m_input[data_src++];
for (int j = 0; j < block_height; ++j)
{
int v49 = dst;
for (int i = 0; i < block_width; ++i)
{
m_output[v49] = b;
v49 += 4;
}
dst += m_stride;
}
}
else
{
for (int j = 0; j < block_height; ++j)
{
int v49 = dst;
for (int i = 0; i < block_width; ++i)
{
m_output[v49] = plane[plane_src++];
v49 += 4;
}
dst += m_stride;
}
}
bit_mask >>= 1;
v66 += 16;
dst_origin += 64;
}
v68 += 16;
}
}
}
void UnpackV5 ()
{
m_output = new byte[m_stride * (int)m_info.Height];
for (int i = 0; i < 4; ++i)
{
int bit_src = 0x54 + LittleEndian.ToInt32 (m_input, 8 * i + 0x34);
int data_src = 0x54 + LittleEndian.ToInt32 (m_input, 8 * i + 0x38);
for (int j = 0; j < 0x7DE; ++j)
m_lzss_frame[j] = 0;
int frame_offset = 0x7DE;
byte accum = 0;
int bit_mask = 128;
int dst = i;
while (dst < m_output.Length)
{
if (0 == bit_mask)
{
++bit_src;
bit_mask = 128;
}
if (0 != (bit_mask & m_input[bit_src]))
{
int v = LittleEndian.ToUInt16 (m_input, data_src);
data_src += 2;
int count = (v & 0x1F) + 3;
int offset = v >> 5;
for (int k = 0; k < count; ++k)
{
byte b = m_lzss_frame[(k + offset) & 0x7FF];
m_lzss_frame[frame_offset++] = b;
accum += b;
m_output[dst] = accum;
dst += 4;
frame_offset &= 0x7FF;
}
}
else
{
byte b = m_input[data_src++];
m_lzss_frame[frame_offset++] = b;
accum += b;
m_output[dst] = accum;
dst += 4;
frame_offset &= 0x7FF;
}
bit_mask >>= 1;
}
}
}
static readonly byte[] NameKeyV6 = {
0xA6, 0x75, 0xF3, 0x9C, 0xC5, 0x69, 0x78, 0xA3, 0x3E, 0xA5, 0x4F, 0x79, 0x59, 0xFE, 0x3A, 0xC7,
};
void UnpackV6 ()
{
var name_bytes = new byte[0x20];
int name_offset = 0x34;
int i;
for (i = 0; i < 0x20; ++i)
{
name_bytes[i] = (byte)(m_input[name_offset+i] ^ NameKeyV6[i & 0xF]);
if (0 == name_bytes[i])
break;
}
m_output = LoadBaseImage (Encodings.cp932.GetString (name_bytes, 0, i) + ".pb3");
BlendInput();
}
byte[] LoadBaseImage (string name)
{
// judging by the code, files with "pb3" extension could as well contain PNG or BMP images,
// so we couldn't just shortcut to another instance of Pb3Reader here.
var path = Path.GetDirectoryName (m_info.FileName);
name = VFS.CombinePath (path, name);
if (name.Equals (m_info.FileName, StringComparison.InvariantCultureIgnoreCase))
throw new InvalidFormatException();
// two files referencing each other still could create infinite recursion
using (var base_file = VFS.OpenSeekableStream (name))
{
var image_data = ImageFormat.Read (name, base_file);
int stride = image_data.Bitmap.PixelWidth * 4;
var pixels = new byte[stride * image_data.Bitmap.PixelHeight];
image_data.Bitmap.CopyPixels (pixels, stride, 0);
return pixels;
}
}
void LzssUnpack (int bit_src, int data_src, byte[] output, int output_size)
{
int dst = 0;
int bit_mask = 0x80;
int frame_offset = 0x7DE;
while (dst < output_size)
{
if (0 == bit_mask)
{
bit_mask = 0x80;
++bit_src;
}
if (0 != (bit_mask & m_input[bit_src]))
{
int v = LittleEndian.ToUInt16 (m_input, data_src);
data_src += 2;
int count = (v & 0x1F) + 3;
int offset = v >> 5;
for (int i = 0; i < count; ++i)
{
byte b = m_lzss_frame[(i + offset) & 0x7FF];
output[dst++] = b;
m_lzss_frame[frame_offset++] = b;
frame_offset &= 0x7FF;
}
}
else
{
byte b = m_input[data_src++];
output[dst++] = b;
m_lzss_frame[frame_offset++] = b;
frame_offset &= 0x7FF;
}
bit_mask >>= 1;
}
}
void BlendInput ()
{
int bit_src = 0x20 + LittleEndian.ToInt32 (m_input, 0xC);
int data_src = bit_src + LittleEndian.ToInt32 (m_input, 0x2C);
int overlay_size = LittleEndian.ToInt32 (m_input, 0x18);
var overlay = new byte[overlay_size];
LzssUnpack (bit_src, data_src, overlay, overlay_size);
int width = (int)m_info.Width;
int height = (int)m_info.Height;
bit_src = 8; // within overlay
data_src = 8 + LittleEndian.ToInt32 (overlay, 0); // within overlay
int bit_mask = 0x80;
int x_blocks = width >> 3;
if (0 != (width & 7))
++x_blocks;
int y_blocks = height >> 3;
if (0 != (height & 7))
++y_blocks;
if (0 == x_blocks)
return;
int h = 0;
int dst_origin = 0;
while (y_blocks > 0)
{
int w = 0;
for (int x = 0; x < x_blocks; ++x)
{
if (0 == bit_mask)
{
++bit_src;
bit_mask = 0x80;
}
if (0 == (bit_mask & overlay[bit_src]))
{
int dst = 8 * (dst_origin + 4 * x); // within m_output
int x_count = Math.Min (8, width - w);
int y_count = Math.Min (8, height - h);
for (int v30 = y_count; v30 > 0; --v30)
{
int count = 4 * x_count;
Buffer.BlockCopy (overlay, data_src, m_output, dst, count);
data_src += count;
dst += m_stride;
}
}
bit_mask >>= 1;
w += 8;
}
dst_origin += m_stride;
h += 8;
--y_blocks;
}
}
}
}

View File

@ -363,6 +363,7 @@ Zettai Meikyuu Grimm<br/>
</td></tr>
<tr class="odd"><td>*.mgf</td><td><tt>MalieGF</tt></td><td>Yes</td></tr>
<tr><td>*.arc</td><td>-</td><td>No</td><td rowspan="2">AI5WIN</td><td rowspan="2">
Ai Shimai ~Docchi ni Suru no!!~<br/>
Ai Shimai Tsubomi...<br/>
Dorei Kaigo<br/>
Jokei Kazoku ~Inbou~<br/>
@ -541,6 +542,10 @@ Tama Tama Christmas Box<br/>
Gakuen Saimin Reido<br/>
</td></tr>
<tr class="odd"><td>*.akb</td><td><tt>AKB</tt></td><td>No</td></tr>
<tr><td>*.cpz</td><td><tt>CPZ5</tt></td><td>No</td><td rowspan="2">CMVS</td><td rowspan="2">
Hapymaher<br/>
</td></tr>
<tr><td>*.pb3</td><td><tt>PB3B</tt></td><td>No</td></tr>
</table>
<p><a name="note-1" class="footnote">1</a> Non-encrypted only</p>
</body>