Compare commits

..

12 Commits

Author SHA1 Message Date
morkt
0b8eb1f9d4 implemented Will co. archives creation. 2014-11-01 02:14:51 +04:00
morkt
56d2a45d94 implemented Will co. engine resources. 2014-10-31 18:50:43 +04:00
morkt
6736819db1 cosmetic changes. 2014-10-31 18:47:37 +04:00
morkt
6aeb3ea27e automatically update assembly build/revision number. 2014-10-31 18:47:02 +04:00
morkt
1faea63667 cosmetic changes. 2014-09-12 16:04:38 +04:00
morkt
82b1fc0603 (ArcFile.OverwriteNotify): new event.
preliminary support for extracted file overwrite notification.
2014-09-12 16:04:18 +04:00
morkt
ae559f34a6 (ArchiveFormat.CopyEntry): new virtual method.
the idea is to allow implementations to give extracted file a name
different from the one it stored within archive.
2014-09-12 16:03:30 +04:00
morkt
f02cc382a1 BGI/Ethornell engine archive implementation. 2014-09-12 15:59:56 +04:00
morkt
58018d3c67 (ArcStream): added constructors from ArcView.Frame 2014-09-12 15:58:18 +04:00
morkt
12df1dcdfd (GetScheme): fixed potential bug when looking up unknown encryption scheme. 2014-09-09 01:04:27 +04:00
morkt
1c5008d799 fixed empty 'recent files' menu. 2014-09-08 12:15:13 +04:00
morkt
58f8b4845d incremented version number. 2014-09-08 11:54:39 +04:00
25 changed files with 1012 additions and 33 deletions

310
ArcFormats/ArcBGI.cs Normal file
View File

@@ -0,0 +1,310 @@
//! \file ArcBGI.cs
//! \date Tue Sep 09 09:29:12 2014
//! \brief BGI/Ethornell engine archive implementation.
//
// Copyright (C) 2014 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 GameRes.Utility;
namespace GameRes.Formats.BGI
{
[Export(typeof(ArchiveFormat))]
public class ArcOpener : ArchiveFormat
{
public override string Tag { get { return "BGI"; } }
public override string Description { get { return "BGI/Ethornell engine resource archive"; } }
public override uint Signature { get { return 0x6b636150; } } // "Pack"
public override bool IsHierarchic { get { return false; } }
public override bool CanCreate { get { return false; } }
public ArcOpener ()
{
Extensions = new string[] { "arc" };
}
public override ArcFile TryOpen (ArcView file)
{
if (!file.View.AsciiEqual (4, "File "))
return null;
uint count = file.View.ReadUInt32 (12);
if (count > 0xfffff)
return null;
uint index_size = 0x20 * count;
if (index_size > file.View.Reserve (0x10, index_size))
return null;
var dir = new List<Entry> ((int)count);
long index_offset = 0x10;
long base_offset = index_offset + index_size;
for (uint i = 0; i < count; ++i)
{
string name = file.View.ReadString (index_offset, 0x10);
var entry = FormatCatalog.Instance.CreateEntry (name);
entry.Offset = base_offset + file.View.ReadUInt32 (index_offset+0x10);
entry.Size = file.View.ReadUInt32 (index_offset+0x14);
if (!entry.CheckPlacement (file.MaxOffset))
return null;
dir.Add (entry);
index_offset += 0x20;
}
return new ArcFile (file, this, dir);
}
public override Stream OpenEntry (ArcFile arc, Entry entry)
{
var entry_offset = entry.Offset;
var input = new ArcView.Frame (arc.File, entry_offset, entry.Size);
try
{
if (entry.Size > 0x220 && input.AsciiEqual (entry_offset, "DSC FORMAT 1.00\0"))
{
using (var decoder = new DscDecoder (input))
{
decoder.Unpack();
byte[] data = decoder.Output;
if (data.Length > 0x40)
{
uint data_offset = LittleEndian.ToUInt32 (data, 0);
if (data_offset < data.Length-4 && 0x20207762 == LittleEndian.ToUInt32 (data, 4))
{
if (0x5367674f == LittleEndian.ToUInt32 (data, (int)data_offset)) // 'OggS'
{
return new MemoryStream (data, (int)data_offset, data.Length-(int)data_offset, false);
}
}
}
return new MemoryStream (data, false);
}
}
if (entry.Size > 0x40)
{
uint data_offset = input.ReadUInt32 (entry_offset);
if (data_offset < entry.Size-4 && 0x20207762 == input.ReadUInt32 (entry_offset+4))
{
if (0x5367674f == input.ReadUInt32 (entry_offset+data_offset)) // 'OggS'
{
return new ArcView.ArcStream (input, entry_offset+data_offset, entry.Size-data_offset);
}
}
}
return new ArcView.ArcStream (input);
}
catch
{
input.Dispose();
throw;
}
}
}
internal sealed class DscDecoder : IDisposable
{
private Stream m_input;
private byte[] m_output;
private uint m_key;
private uint m_dst_size;
private uint m_dec_count;
private uint m_magic;
public byte[] Output { get { return m_output; } }
public DscDecoder (ArcView.Frame input)
{
m_magic = (uint)input.ReadUInt16 (input.Offset) << 16;
m_key = input.ReadUInt32 (input.Offset+0x10);
m_dst_size = input.ReadUInt32 (input.Offset+0x14);
m_dec_count = input.ReadUInt32 (input.Offset+0x18);
m_input = new ArcView.ArcStream (input, input.Offset+0x20, input.Reserved-0x20);
m_output = new byte[m_dst_size];
}
struct HuffmanCode : IComparable<HuffmanCode>
{
public ushort Code;
public ushort Depth;
public int CompareTo (HuffmanCode other)
{
int cmp = (int)Depth - (int)other.Depth;
if (0 == cmp)
cmp = (int)Code - (int)other.Code;
return cmp;
}
}
class HuffmanNode
{
public bool IsParent;
public uint Code;
public uint LeftChildIndex;
public uint RightChildIndex;
}
public void Unpack ()
{
HuffmanCode[] hcodes = new HuffmanCode[512];
HuffmanNode[] hnodes = new HuffmanNode[1023];
int leaf_node_count = 0;
for (ushort i = 0; i < 512; i++)
{
int src = m_input.ReadByte();
if (-1 == src)
throw new EndOfStreamException ("Incomplete compressed stream");
byte depth = (byte)(src - UpdateKey());
if (0 != depth)
{
hcodes[leaf_node_count].Depth = depth;
hcodes[leaf_node_count].Code = i;
leaf_node_count++;
}
}
Array.Sort (hcodes, 0, leaf_node_count);
CreateHuffmanTree (hnodes, hcodes, leaf_node_count);
HuffmanDecompress (hnodes, m_dec_count);
}
void CreateHuffmanTree (HuffmanNode[] hnodes, HuffmanCode[] hcode, int node_count)
{
uint[,] nodes_index = new uint[2,512];
uint next_node_index = 1;
int depth_nodes = 1;
uint depth = 0;
int switch_flag = 0;
nodes_index[0,0] = 0;
for (int n = 0; n < node_count; )
{
int huffman_nodes_index = switch_flag;
switch_flag ^= 1;
int child_index = switch_flag;
int depth_existed_nodes = 0;
while (hcode[n].Depth == depth)
{
var node = new HuffmanNode { IsParent = false, Code = hcode[n++].Code };
hnodes[nodes_index[huffman_nodes_index, depth_existed_nodes]] = node;
depth_existed_nodes++;
}
int depth_nodes_to_create = depth_nodes - depth_existed_nodes;
for (int i = 0; i < depth_nodes_to_create; i++)
{
var node = new HuffmanNode { IsParent = true };
nodes_index[child_index, i * 2] = node.LeftChildIndex = next_node_index++;
nodes_index[child_index, i * 2 + 1] = node.RightChildIndex = next_node_index++;
hnodes[nodes_index[huffman_nodes_index, depth_existed_nodes+i]] = node;
}
depth++;
depth_nodes = depth_nodes_to_create * 2;
}
}
int m_bits = 0;
bool GetNextBit ()
{
bool carry = 0 != (m_bits & 0x80);
m_bits <<= 1;
if (0 == (m_bits & 0xff))
{
m_bits = m_input.ReadByte();
if (-1 == m_bits)
throw new EndOfStreamException ("Invalid compressed stream");
carry = 0 != (m_bits & 0x80);
m_bits = (m_bits << 1) | 1;
}
return carry;
}
bool GetBits (int count, out int bits)
{
bits = 0;
for (int i = 0; i < count; ++i)
{
bits <<= 1;
bits |= GetNextBit() ? 1 : 0;
}
return true;
}
uint HuffmanDecompress (HuffmanNode[] hnodes, uint dec_count)
{
uint dst_ptr = 0;
for (uint k = 0; k < dec_count; k++)
{
uint node_index = 0;
do
{
if (!GetNextBit())
node_index = hnodes[node_index].LeftChildIndex;
else
node_index = hnodes[node_index].RightChildIndex;
}
while (hnodes[node_index].IsParent);
uint code = hnodes[node_index].Code;
if (code >= 256)
{
int win_pos;
if (!GetBits (12, out win_pos))
break;
uint copy_bytes = (code & 0xff) + 2;
win_pos += 2;
for (uint i = 0; i < copy_bytes; i++)
{
m_output[dst_ptr] = m_output[dst_ptr - win_pos];
dst_ptr++;
}
} else
m_output[dst_ptr++] = (byte)code;
}
return dst_ptr;
}
byte UpdateKey ()
{
uint v0 = 20021 * (m_key & 0xffff);
uint v1 = m_magic | (m_key >> 16);
v1 = v1 * 20021 + m_key * 346;
v1 = (v1 + (v0 >> 16)) & 0xffff;
m_key = (v1 << 16) + (v0 & 0xffff) + 1;
return (byte)v1;
}
#region IDisposable Members
public void Dispose ()
{
if (null != m_input)
{
m_input.Dispose();
m_input = null;
}
GC.SuppressFinalize (this);
}
#endregion
}
}

View File

@@ -57,6 +57,7 @@
</ItemGroup>
<ItemGroup>
<Compile Include="ArcAMI.cs" />
<Compile Include="ArcBGI.cs" />
<Compile Include="ArcDRS.cs" />
<Compile Include="ArcINT.cs" />
<Compile Include="ArcKogado.cs" />
@@ -66,6 +67,7 @@
<Compile Include="ArcPD.cs" />
<Compile Include="ArcRPA.cs" />
<Compile Include="ArcSteinsGate.cs" />
<Compile Include="ArcWILL.cs" />
<Compile Include="ArcXFL.cs" />
<Compile Include="ArcXP3.cs" />
<Compile Include="ArcYPF.cs" />
@@ -91,6 +93,9 @@
<Compile Include="CreateSGWidget.xaml.cs">
<DependentUpon>CreateSGWidget.xaml</DependentUpon>
</Compile>
<Compile Include="CreateWARCWidget.xaml.cs">
<DependentUpon>CreateWARCWidget.xaml</DependentUpon>
</Compile>
<Compile Include="CreateXP3Widget.xaml.cs">
<DependentUpon>CreateXP3Widget.xaml</DependentUpon>
</Compile>
@@ -102,6 +107,7 @@
<Compile Include="ImageRCT.cs" />
<Compile Include="ImageTLG.cs" />
<Compile Include="ImageWCG.cs" />
<Compile Include="ImageWIP.cs" />
<Compile Include="KiriKiriCx.cs" />
<Compile Include="KogadoCocotte.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
@@ -181,6 +187,10 @@
<SubType>Designer</SubType>
<Generator>MSBuild:Compile</Generator>
</Page>
<Page Include="CreateWARCWidget.xaml">
<SubType>Designer</SubType>
<Generator>MSBuild:Compile</Generator>
</Page>
<Page Include="CreateXP3Widget.xaml">
<SubType>Designer</SubType>
<Generator>MSBuild:Compile</Generator>
@@ -214,6 +224,9 @@
<EmbeddedResource Include="Strings\arcStrings.ru-RU.resx" />
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
<PropertyGroup>
<PreBuildEvent>perl "$(SolutionDir)inc-revision.pl" "$(ProjectPath)" $(ConfigurationName)</PreBuildEvent>
</PropertyGroup>
<!-- To modify your build process, add your task inside one of the targets below and uncomment it.
Other similar extension points exist, see Microsoft.Common.targets.
<Target Name="BeforeBuild">

View File

@@ -176,9 +176,7 @@ namespace GameRes.Formats.ONScripter
break;
if (name_buffer.Length == name_len)
{
byte[] new_buffer = new byte[checked(name_len/2*3)];
Array.Copy (name_buffer, new_buffer, name_len);
name_buffer = new_buffer;
Array.Resize (ref name_buffer, checked(name_len/2*3));
}
name_buffer[name_len] = b;
}

226
ArcFormats/ArcWILL.cs Normal file
View File

@@ -0,0 +1,226 @@
//! \file ArcWILL.cs
//! \date Fri Oct 31 13:37:11 2014
//! \brief ARC archive format implementation.
//
// Copyright (C) 2014 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 GameRes.Formats.Properties;
using GameRes.Formats.Strings;
namespace GameRes.Formats.Will
{
internal class ExtRecord
{
public string Extension;
public int FileCount;
public uint DirOffset;
}
public class ArcOptions : ResourceOptions
{
public int NameLength { get; set; }
}
[Export(typeof(ArchiveFormat))]
public class ArcOpener : ArchiveFormat
{
public override string Tag { get { return "WARC"; } }
public override string Description { get { return "Will Co. game engine resource archive"; } }
public override uint Signature { get { return 0; } }
public override bool IsHierarchic { get { return false; } }
public override bool CanCreate { get { return true; } }
ArcOpener ()
{
Extensions = new string[] { "arc" };
}
public override ArcFile TryOpen (ArcView file)
{
int ext_count = file.View.ReadInt32 (0);
if (ext_count <= 0 || ext_count > 0xff)
return null;
uint dir_offset = 4;
var ext_list = new List<ExtRecord> (ext_count);
for (int i = 0; i < ext_count; ++i)
{
string ext = file.View.ReadString (dir_offset, 4).ToLowerInvariant();
int count = file.View.ReadInt32 (dir_offset+4);
uint offset = file.View.ReadUInt32 (dir_offset+8);
if (count <= 0 || count > 0xffff || offset <= dir_offset || offset > file.MaxOffset)
return null;
ext_list.Add (new ExtRecord { Extension = ext, FileCount = count, DirOffset = offset });
dir_offset += 12;
}
var dir = ReadFileList (file, ext_list, 9);
if (null == dir)
dir = ReadFileList (file, ext_list, 13);
if (null == dir)
return null;
return new ArcFile (file, this, dir);
}
List<Entry> ReadFileList (ArcView file, IEnumerable<ExtRecord> ext_list, uint name_size)
{
var dir = new List<Entry>();
foreach (var ext in ext_list)
{
dir.Capacity = dir.Count + ext.FileCount;
uint dir_offset = ext.DirOffset;
for (int i = 0; i < ext.FileCount; ++i)
{
string name = file.View.ReadString (dir_offset, name_size);
if (string.IsNullOrEmpty (name))
return null;
name = name.ToLowerInvariant()+'.'+ext.Extension;
var entry = FormatCatalog.Instance.CreateEntry (name);
entry.Size = file.View.ReadUInt32 (dir_offset+name_size);
entry.Offset = file.View.ReadUInt32 (dir_offset+name_size+4);
if (!entry.CheckPlacement (file.MaxOffset))
return null;
dir.Add (entry);
dir_offset += name_size+8;
}
}
return dir;
}
public override ResourceOptions GetDefaultOptions ()
{
return new ArcOptions { NameLength = Settings.Default.WARCNameLength };
}
public override object GetCreationWidget ()
{
return new GUI.CreateWARCWidget();
}
internal class ArcEntry : Entry
{
public byte[] RawName;
}
internal class ArcDirectory
{
public byte[] Extension;
public uint DirOffset;
public List<ArcEntry> Files;
}
public override void Create (Stream output, IEnumerable<Entry> list, ResourceOptions options,
EntryCallback callback)
{
var arc_options = GetOptions<ArcOptions> (options);
var encoding = Encodings.cp932.WithFatalFallback();
int file_count = 0;
var file_table = new SortedDictionary<string, ArcDirectory>();
foreach (var entry in list)
{
string ext = Path.GetExtension (entry.Name).TrimStart ('.').ToUpperInvariant();
if (string.IsNullOrEmpty (ext))
throw new InvalidFileName (entry.Name, arcStrings.MsgNoExtension);
if (ext.Length > 3)
throw new InvalidFileName (entry.Name, arcStrings.MsgExtensionTooLong);
string name = Path.GetFileNameWithoutExtension (entry.Name).ToUpperInvariant();
byte[] raw_name = encoding.GetBytes (name);
if (raw_name.Length > arc_options.NameLength)
throw new InvalidFileName (entry.Name, arcStrings.MsgFileNameTooLong);
ArcDirectory dir;
if (!file_table.TryGetValue (ext, out dir))
{
byte[] raw_ext = encoding.GetBytes (ext);
if (raw_ext.Length > 3)
throw new InvalidFileName (entry.Name, arcStrings.MsgExtensionTooLong);
dir = new ArcDirectory { Extension = raw_ext, Files = new List<ArcEntry>() };
file_table[ext] = dir;
}
dir.Files.Add (new ArcEntry { Name = entry.Name, RawName = raw_name });
++file_count;
}
if (null != callback)
callback (file_count+1, null, null);
int callback_count = 0;
long dir_offset = 4 + file_table.Count * 12;
long data_offset = dir_offset + (arc_options.NameLength + 9) * file_count;
output.Position = data_offset;
foreach (var ext in file_table.Keys)
{
var dir = file_table[ext];
dir.DirOffset = (uint)dir_offset;
dir_offset += (arc_options.NameLength + 9) * dir.Files.Count;
foreach (var entry in dir.Files)
{
if (null != callback)
callback (callback_count++, entry, arcStrings.MsgAddingFile);
entry.Offset = data_offset;
using (var input = File.OpenRead (entry.Name))
{
var size = input.Length;
if (size > uint.MaxValue || data_offset + size > uint.MaxValue)
throw new FileSizeException();
data_offset += size;
entry.Size = (uint)size;
input.CopyTo (output);
}
}
}
if (null != callback)
callback (callback_count++, null, arcStrings.MsgWritingIndex);
output.Position = 0;
using (var header = new BinaryWriter (output, encoding, true))
{
byte[] buffer = new byte[arc_options.NameLength+1];
header.Write (file_table.Count);
foreach (var ext in file_table)
{
Array.Copy (ext.Value.Extension, buffer, ext.Value.Extension.Length);
for (int i = ext.Value.Extension.Length; i < 4; ++i)
buffer[i] = 0;
header.Write (buffer, 0, 4);
header.Write (ext.Value.Files.Count);
header.Write (ext.Value.DirOffset);
}
foreach (var ext in file_table)
{
foreach (var entry in ext.Value.Files)
{
Array.Copy (entry.RawName, buffer, entry.RawName.Length);
for (int i = entry.RawName.Length; i < buffer.Length; ++i)
buffer[i] = 0;
header.Write (buffer);
header.Write (entry.Size);
header.Write ((uint)entry.Offset);
}
}
}
}
}
}

View File

@@ -290,11 +290,9 @@ NextEntry:
public static ICrypt GetScheme (string scheme)
{
ICrypt algorithm = NoCryptAlgorithm;
if (!string.IsNullOrEmpty (scheme))
{
KnownSchemes.TryGetValue (scheme, out algorithm);
}
ICrypt algorithm;
if (string.IsNullOrEmpty (scheme) || !KnownSchemes.TryGetValue (scheme, out algorithm))
algorithm = NoCryptAlgorithm;
return algorithm;
}
@@ -425,7 +423,7 @@ NextEntry:
}
header.BaseStream.Position = 0;
writer.Write ((byte)(compress_index ? 1 : 0));
writer.Write (compress_index);
long unpacked_dir_size = header.BaseStream.Length;
if (compress_index)
{

View File

@@ -0,0 +1,16 @@
<Grid x:Class="GameRes.Formats.GUI.CreateWARCWidget"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:s="clr-namespace:GameRes.Formats.Strings"
xmlns:p="clr-namespace:GameRes.Formats.Properties">
<Grid.ColumnDefinitions>
<ColumnDefinition/>
<ColumnDefinition/>
</Grid.ColumnDefinitions>
<Label Content="{x:Static s:arcStrings.WARCLabelLength}" Target="{Binding ElementName=NameLength}" Grid.Column="0" Margin="0"/>
<ComboBox Name="NameLength" Width="40" SelectedValuePath="Content" Grid.Column="1" Margin="8"
SelectedValue="{Binding Source={x:Static p:Settings.Default}, Path=WARCNameLength, Mode=TwoWay}">
<ComboBoxItem Content="8"/>
<ComboBoxItem Content="12"/>
</ComboBox>
</Grid>

View File

@@ -0,0 +1,15 @@
using System.Windows.Controls;
namespace GameRes.Formats.GUI
{
/// <summary>
/// Interaction logic for CreateWARCWidget.xaml
/// </summary>
public partial class CreateWARCWidget : Grid
{
public CreateWARCWidget ()
{
InitializeComponent ();
}
}
}

View File

@@ -95,12 +95,12 @@ namespace GameRes.Formats.DRS
int stride = (int)info.Width*((info.BPP+7)/8);
if (8 == info.BPP)
{
file.Position = 44;
format = PixelFormats.Indexed8;
var palette_data = new byte[0x400];
if (palette_data.Length != file.Read (palette_data, 0, palette_data.Length))
throw new InvalidFormatException();
var palette = new Color[256];
file.Position = 44;
for (int i = 0; i < 256; ++i)
{
palette[i] = Color.FromRgb (palette_data[i*4+2], palette_data[i*4+1], palette_data[i*4]);

230
ArcFormats/ImageWIP.cs Normal file
View File

@@ -0,0 +1,230 @@
//! \file ImageWIP.cs
//! \date Fri Oct 31 14:52:49 2014
//! \brief Will image format implementation.
//
// Copyright (C) 2014 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.IO;
using System.Text;
using System.Diagnostics;
using System.ComponentModel.Composition;
using System.Windows.Media;
using System.Windows.Media.Imaging;
namespace GameRes.Formats.Will
{
internal class WipMetaData : ImageMetaData
{
public int FrameCount;
public uint FrameSize;
}
[Export(typeof(ImageFormat))]
public class WipFormat : ImageFormat
{
public override string Tag { get { return "WIP"; } }
public override string Description { get { return "Will Co. image format"; } }
public override uint Signature { get { return 0x46504957u; } } // 'WIPF'
public WipFormat ()
{
Extensions = new string[] { "wip", "msk" };
}
public override ImageMetaData ReadMetaData (Stream stream)
{
using (var file = new BinaryReader (stream, Encoding.ASCII, true))
{
if (Signature != file.ReadUInt32())
return null;
int frames = file.ReadUInt16();
int bpp = file.ReadUInt16();
uint width = file.ReadUInt32();
uint height = file.ReadUInt32();
int x = file.ReadInt32();
int y = file.ReadInt32();
file.ReadUInt32(); // 0
uint frame_size = file.ReadUInt32();
if (24 != bpp && 8 != bpp)
{
Trace.WriteLine ("unsupported bpp", "WipFormat");
return null;
}
if (frames > 1)
Trace.WriteLine ("Extra frames ignored", "WipFormat");
return new WipMetaData
{
Width = width,
Height = height,
OffsetX = x,
OffsetY = y,
BPP = bpp,
FrameCount = frames,
FrameSize = frame_size,
};
}
}
public override void Write (Stream file, ImageData image)
{
throw new NotImplementedException ("WipFormat.Write not implemented");
}
public override ImageData Read (Stream file, ImageMetaData info)
{
var meta = info as WipMetaData;
if (null == meta)
throw new ArgumentException ("WipFormat.Read should be supplied with WipMetaData", "info");
file.Position = 8 + 24 * meta.FrameCount;
Color[] palette = null;
if (8 == meta.BPP)
{
var palette_data = new byte[0x400];
if (palette_data.Length != file.Read (palette_data, 0, palette_data.Length))
throw new InvalidFormatException();
palette = new Color[0x100];
for (int i = 0; i < 0x100; ++i)
{
palette[i] = Color.FromRgb (palette_data[i*4], palette_data[i*4+1], palette_data[i*4+2]);
}
}
using (var reader = new Reader (file, meta))
{
reader.Unpack();
BitmapSource bitmap;
if (24 == meta.BPP)
{
byte[] raw = reader.Data;
int size = (int)meta.Width * (int)meta.Height;
byte[] pixels = new byte[size*3];
for (int i = 0; i < size; ++i)
{
pixels[i*3] = raw[i];
pixels[i*3+1] = raw[i+size];
pixels[i*3+2] = raw[i+size*2];
}
bitmap = BitmapSource.Create ((int)meta.Width, (int)meta.Height, 96, 96,
PixelFormats.Bgr24, null, pixels, (int)meta.Width*3);
}
else if (8 == meta.BPP)
{
byte[] pixels = reader.Data;
bitmap = BitmapSource.Create ((int)meta.Width, (int)meta.Height, 96, 96,
PixelFormats.Indexed8, new BitmapPalette (palette), pixels, (int)meta.Width);
}
else
throw new InvalidFormatException();
bitmap.Freeze();
return new ImageData (bitmap, meta);
}
}
internal class Reader : IDisposable
{
private BinaryReader m_input;
private uint m_length;
private byte[] m_data;
public byte[] Data { get { return m_data; } }
public Reader (Stream file, WipMetaData info)
{
m_length = info.FrameSize;
// int stride = (int)info.Width*((info.BPP+7)/8);
int stride = (int)info.Width*4;
m_data = new byte[stride * (int)info.Height];
m_input = new BinaryReader (file, Encoding.ASCII, true);
}
private byte[] m_window = new byte[0x1000];
public void Unpack ()
{
int current = 0;
int window_index = 1;
int control = 0;
byte input = 0;
for (uint length = m_length; length > 0; )
{
control >>= 1;
if (0 == (control & 0x100))
{
input = m_input.ReadByte();
--length;
control = input | 0xff00;
}
if (0 != (control & 1))
{
if (length < 1)
throw new InvalidFormatException();
input = m_input.ReadByte();
--length;
m_data[current++] = input;
m_window[window_index++] = input;
window_index &= 0xfff;
}
else
{
if (length < 2)
throw new InvalidFormatException();
int di = m_input.ReadByte();
input = m_input.ReadByte();
length -= 2;
int offset = ((di << 8) | input) >> 4;
int count = (input & 0xf) + 2;
for (int i = 0; i < count; ++i)
{
int src = (i + offset) & 0xfff;
input = m_window[src];
m_data[current++] = input;
m_window[window_index++] = input;
window_index &= 0xfff;
}
}
}
}
#region IDisposable Members
bool disposed = false;
public void Dispose ()
{
Dispose (true);
GC.SuppressFinalize (this);
}
protected virtual void Dispose (bool disposing)
{
if (!disposed)
{
if (disposing)
m_input.Dispose();
m_input = null;
m_data = null;
disposed = true;
}
}
#endregion
}
}
}

View File

@@ -8,7 +8,7 @@ using System.Runtime.InteropServices;
[assembly: AssemblyTitle("ArcFormats")]
[assembly: AssemblyDescription("Visual Novel resources library")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyCompany ("mørkt")]
[assembly: AssemblyProduct("ArcFormats")]
[assembly: AssemblyCopyright("Copyright © 2014 mørkt")]
[assembly: AssemblyTrademark("")]
@@ -32,5 +32,5 @@ using System.Runtime.InteropServices;
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: AssemblyVersion ("1.0.2.21")]
[assembly: AssemblyFileVersion ("1.0.2.21")]

View File

@@ -237,5 +237,17 @@ namespace GameRes.Formats.Properties {
this["NPAKey2"] = value;
}
}
[global::System.Configuration.UserScopedSettingAttribute()]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Configuration.DefaultSettingValueAttribute("8")]
public int WARCNameLength {
get {
return ((int)(this["WARCNameLength"]));
}
set {
this["WARCNameLength"] = value;
}
}
}
}

View File

@@ -56,5 +56,8 @@
<Setting Name="NPAKey2" Type="System.UInt32" Scope="User">
<Value Profile="(Default)">555831124</Value>
</Setting>
<Setting Name="WARCNameLength" Type="System.Int32" Scope="User">
<Value Profile="(Default)">8</Value>
</Setting>
</Settings>
</SettingsFile>

View File

@@ -279,6 +279,15 @@ namespace GameRes.Formats.Strings {
}
}
/// <summary>
/// Looks up a localized string similar to File name extension too long..
/// </summary>
public static string MsgExtensionTooLong {
get {
return ResourceManager.GetString("MsgExtensionTooLong", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to File name is too long.
/// </summary>
@@ -315,6 +324,15 @@ namespace GameRes.Formats.Strings {
}
}
/// <summary>
/// Looks up a localized string similar to File name without extension..
/// </summary>
public static string MsgNoExtension {
get {
return ResourceManager.GetString("MsgNoExtension", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Number of files exceedes archive limit..
/// </summary>
@@ -487,6 +505,16 @@ namespace GameRes.Formats.Strings {
}
}
/// <summary>
/// Looks up a localized string similar to Maximum file name length
///(not including extension).
/// </summary>
public static string WARCLabelLength {
get {
return ResourceManager.GetString("WARCLabelLength", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Liar-soft game resource archive.
/// </summary>

View File

@@ -192,6 +192,9 @@ predefined encryption scheme.</value>
<data name="MsgEncNotImplemented" xml:space="preserve">
<value>Encryption method not implemented</value>
</data>
<data name="MsgExtensionTooLong" xml:space="preserve">
<value>File name extension too long.</value>
</data>
<data name="MsgFileNameTooLong" xml:space="preserve">
<value>File name is too long</value>
</data>
@@ -204,6 +207,9 @@ predefined encryption scheme.</value>
<data name="MsgInvalidVersion" xml:space="preserve">
<value>Invalid archive version specified.</value>
</data>
<data name="MsgNoExtension" xml:space="preserve">
<value>File name without extension.</value>
</data>
<data name="MsgTooManyFiles" xml:space="preserve">
<value>Number of files exceedes archive limit.</value>
</data>
@@ -262,6 +268,10 @@ predefined encryption scheme.</value>
<data name="TooltipHex" xml:space="preserve">
<value>Hex number</value>
</data>
<data name="WARCLabelLength" xml:space="preserve">
<value>Maximum file name length
(not including extension)</value>
</data>
<data name="XFLDescription" xml:space="preserve">
<value>Liar-soft game resource archive</value>
</data>

View File

@@ -174,6 +174,9 @@
<data name="MsgEncNotImplemented" xml:space="preserve">
<value>Метод шифрования не реализован</value>
</data>
<data name="MsgExtensionTooLong" xml:space="preserve">
<value>Слишком длинное расширение имени файла.</value>
</data>
<data name="MsgFileNameTooLong" xml:space="preserve">
<value>Слишком длинное имя файла</value>
</data>
@@ -186,6 +189,9 @@
<data name="MsgInvalidVersion" xml:space="preserve">
<value>Указана некорректная версия архива.</value>
</data>
<data name="MsgNoExtension" xml:space="preserve">
<value>Имя файла без расширения.</value>
</data>
<data name="MsgTooManyFiles" xml:space="preserve">
<value>Количество файлов превышает ограничения архива.</value>
</data>
@@ -226,6 +232,10 @@
<data name="TooltipHex" xml:space="preserve">
<value>Шестнадцатеричное число</value>
</data>
<data name="WARCLabelLength" xml:space="preserve">
<value>Максимальная длина имени файла
(не считая расширения)</value>
</data>
<data name="XP3CompressContents" xml:space="preserve">
<value>Сжать содержимое</value>
</data>

View File

@@ -58,6 +58,9 @@
<setting name="NPAKey2" serializeAs="String">
<value>555831124</value>
</setting>
<setting name="WARCNameLength" serializeAs="String">
<value>8</value>
</setting>
</GameRes.Formats.Properties.Settings>
</userSettings>
<startup><supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5"/></startup></configuration>

View File

@@ -316,6 +316,9 @@
</BootstrapperPackage>
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
<PropertyGroup>
<PreBuildEvent>perl "$(SolutionDir)inc-revision.pl" "$(ProjectPath)" $(ConfigurationName)</PreBuildEvent>
</PropertyGroup>
<!-- To modify your build process, add your task inside one of the targets below and uncomment it.
Other similar extension points exist, see Microsoft.Common.targets.
<Target Name="BeforeBuild">

View File

@@ -49,6 +49,8 @@ namespace GameRes
/// <summary>Archive contents.</summary>
public ICollection<Entry> Dir { get { return m_dir; } }
public event EventHandler<OverwriteEventArgs> OverwriteNotify;
public ArcFile (ArcView arc, ArchiveFormat impl, ICollection<Entry> dir)
{
m_arc = arc;
@@ -147,7 +149,7 @@ namespace GameRes
/// </summary>
public Stream CreateFile (Entry entry)
{
return m_interface.CreateFile (entry);
return m_interface.CreateFile (entry.Name);
}
#region IDisposable Members
@@ -172,6 +174,12 @@ namespace GameRes
#endregion
}
public class OverwriteEventArgs : EventArgs
{
public string Filename { get; set; }
public bool Overwrite { get; set; }
}
public class AppendStream : System.IO.Stream
{
private Stream m_base;

View File

@@ -392,8 +392,8 @@ namespace GameRes
private uint m_size;
private long m_position;
public override bool CanRead { get { return true; } }
public override bool CanSeek { get { return true; } }
public override bool CanRead { get { return !disposed; } }
public override bool CanSeek { get { return !disposed; } }
public override bool CanWrite { get { return false; } }
public override long Length { get { return m_size; } }
public override long Position
@@ -410,14 +410,27 @@ namespace GameRes
m_position = 0;
}
public ArcStream (ArcView file, long offset, uint size)
public ArcStream (Frame view)
{
m_view = new Frame (file, offset, size);
m_view = view;
m_start = m_view.Offset;
m_size = m_view.Reserved;
m_position = 0;
}
public ArcStream (ArcView file, long offset, uint size)
: this (new Frame (file, offset, size))
{
}
public ArcStream (Frame view, long offset, uint size)
{
m_view = view;
m_start = offset;
m_size = Math.Min (size, m_view.Reserve (offset, size));
m_position = 0;
}
/// <summary>
/// Read stream signature (first 4 bytes) without altering current read position.
/// </summary>

View File

@@ -143,12 +143,7 @@ namespace GameRes
public void Extract (ArcFile file, Entry entry)
{
using (var reader = OpenEntry (file, entry))
{
using (var writer = CreateFile (entry))
{
reader.CopyTo (writer);
}
}
CopyEntry (file, reader, entry);
}
/// <summary>
@@ -159,13 +154,28 @@ namespace GameRes
return arc.File.CreateStream (entry.Offset, entry.Size);
}
public virtual void CopyEntry (ArcFile arc, Stream input, Entry entry)
{
using (var output = CreateFile (entry.Name))
input.CopyTo (output);
}
/// <summary>
/// Create file corresponding to <paramref name="entry"/> in current directory and open it
/// for writing. Overwrites existing file, if any.
/// </summary>
public virtual Stream CreateFile (Entry entry)
public Stream CreateFile (string filename)
{
filename = CreatePath (filename);
if (File.Exists (filename))
{
// query somehow whether to overwrite existing file or not.
}
return File.Create (filename);
}
static public string CreatePath (string filename)
{
string filename = entry.Name;
string dir = Path.GetDirectoryName (filename);
if (!string.IsNullOrEmpty (dir)) // check for malformed filenames
{
@@ -185,7 +195,7 @@ namespace GameRes
filename = Path.Combine (dir, filename);
}
}
return File.Create (filename);
return filename;
}
/// <summary>

View File

@@ -79,6 +79,9 @@
<EmbeddedResource Include="Strings\garStrings.ru-RU.resx" />
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
<PropertyGroup>
<PreBuildEvent>perl "$(SolutionDir)inc-revision.pl" "$(ProjectPath)" $(ConfigurationName)</PreBuildEvent>
</PropertyGroup>
<!-- To modify your build process, add your task inside one of the targets below and uncomment it.
Other similar extension points exist, see Microsoft.Common.targets.
<Target Name="BeforeBuild">

View File

@@ -8,7 +8,7 @@ using System.Runtime.InteropServices;
[assembly: AssemblyTitle("GameRes")]
[assembly: AssemblyDescription("Game Resources class library")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyCompany ("mørkt")]
[assembly: AssemblyProduct("GameRes")]
[assembly: AssemblyCopyright("Copyright © 2014 mørkt")]
[assembly: AssemblyTrademark("")]
@@ -32,5 +32,5 @@ using System.Runtime.InteropServices;
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: AssemblyVersion ("1.0.0.3")]
[assembly: AssemblyFileVersion ("1.0.0.3")]

View File

@@ -162,7 +162,7 @@ namespace GARbro.GUI
void PushRecentFile (string file)
{
var node = m_recent_files.Find (file);
if (node == m_recent_files.First)
if (node != null && node == m_recent_files.First)
return;
if (null == node)
{

View File

@@ -51,5 +51,5 @@ using System.Windows;
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion ("1.0.1.0")]
[assembly: AssemblyFileVersion ("1.0.1.0")]
[assembly: AssemblyVersion ("1.0.2.10")]
[assembly: AssemblyFileVersion ("1.0.1.10")]

70
inc-revision.pl Normal file
View File

@@ -0,0 +1,70 @@
#!/usr/bin/perl
#
# increment .Net assembly revision
use strict;
use Win32;
use File::Basename;
use File::Spec;
use File::Temp;
sub get_git_exe {
my $user_app_data = Win32::GetFolderPath (Win32::CSIDL_LOCAL_APPDATA);
my $git_glob = File::Spec->catfile ($user_app_data, 'GitHub', 'PortableGit_*', 'bin', 'git.exe');
my $git_path = glob ($git_glob);
die "PortableGit not found\n" unless -x $git_path;
return $git_path;
}
sub match_version {
return $_[0] =~ /^(\d+)\.(\d+)(?:\.(\d+)\.(\d+))?/;
}
unless (1 == $#ARGV) {
print "usage: inc-revision.pl PROJECT-FILE CONFIG\n";
exit 0;
}
my ($project_path, $config) = @ARGV;
my $project_dir = dirname ($project_path);
my $project_file = basename ($project_path);
my $is_release = 'release' eq lc $config;
chdir $project_dir or die "$project_dir: $!\n";
my $git_exe = get_git_exe;
my $prop_dir = File::Spec->catfile ('.', 'Properties');
my $assembly_info = File::Spec->catfile ($prop_dir, 'AssemblyInfo.cs');
my $revision = `$git_exe rev-list master --count $project_file`;
die "git.exe failed\n" if $? != 0;
chomp $revision;
my $version_changed = 0;
my $tmp_filename;
{
open (my $assembly_file, '<', $assembly_info) or die "${assembly_info}: $!";
my $tmp_output = File::Temp->new (DIR => $prop_dir, UNLINK => 0);
$tmp_filename = $tmp_output->filename;
binmode ($tmp_output, ':crlf');
while (<$assembly_file>) {
m,^//, and next;
/^\[assembly:\s*(Assembly(?:File)?Version)\s*\("(.*?)"\)\]/ and do {
my ($attr, $version) = ($1, $2);
my ($major, $minor, $build, $rev) = match_version ($version);
$build += 1 if $is_release;
my $new_version = "${major}.${minor}.${build}.${revision}";
$_ = "[assembly: ${attr} (\"${new_version}\")]\n";
print "AssemblyVersion: $new_version\n" if $attr eq 'AssemblyVersion';
$version_changed ||= $version ne $new_version;
};
} continue {
print $tmp_output $_;
}
}
if ($version_changed) {
rename $assembly_info, "${assembly_info}~" or die "${assembly_info}: $!";
rename $tmp_filename, $assembly_info or die "${tmp_filename}: $!";
} else {
unlink $tmp_filename;
}