Esempio n. 1
0
        public static T Parse <T>(GameBoxReader r, uint?classID = null, GameBox <T> gbx = null, IProgress <GameBoxReadProgress> progress = null) where T : Node
        {
            var stopwatch = Stopwatch.StartNew();

            if (!classID.HasValue)
            {
                classID = r.ReadUInt32();
            }

            if (classID == uint.MaxValue)
            {
                return(null);
            }

            classID = Remap(classID.Value);

            if (!AvailableClasses.TryGetValue(classID.Value, out Type type))
            {
                throw new NotImplementedException($"Node ID 0x{classID.Value:X8} is not implemented. ({Names.Where(x => x.Key == Chunk.Remap(classID.Value)).Select(x => x.Value).FirstOrDefault() ?? "unknown class"})");
            }

            T node = null;

            if (gbx == null)
            {
                node = (T)Activator.CreateInstance(type);
            }
            else
            {
                node = gbx.MainNode;
            }

            IGameBoxBody body;

            if (r.Lookbackable is Chunk ch)
            {
                body = (IGameBoxBody)ch.Part;
            }
            else
            {
                body = (IGameBoxBody)r.Lookbackable;
            }

            node.Body = body;

            var chunks = new ChunkSet {
                Node = node
            };

            node.Chunks = chunks;

            uint?previousChunk = null;

            while (r.BaseStream.Position < r.BaseStream.Length)
            {
                if (r.BaseStream.Position + 4 > r.BaseStream.Length)
                {
                    Debug.WriteLine($"Unexpected end of the stream: {r.BaseStream.Position}/{r.BaseStream.Length}");
                    var bytes = r.ReadBytes((int)(r.BaseStream.Length - r.BaseStream.Position));
                    break;
                }

                var chunkID = r.ReadUInt32();

                if (chunkID == 0xFACADE01) // no more chunks
                {
                    break;
                }
                else if (chunkID == 0)
                {
                    // weird case after ending node reference
                }
                else
                {
                    var logChunk = $"[{node.ClassName}] 0x{chunkID:X8} ({(float)r.BaseStream.Position / r.BaseStream.Length:0.00%})";
                    if (node.Body?.GBX.ClassID.HasValue == true && Remap(node.Body.GBX.ClassID.Value) == node.ID)
                    {
                        Log.Write(logChunk);
                    }
                    else
                    {
                        Log.Write($"~ {logChunk}");
                    }
                }

                Type  chunkClass = null;
                Chunk chunk      = null;

                var chunkRemapped = Chunk.Remap(chunkID);

                var reflected = ((chunkRemapped & 0xFFFFF000) == node.ID || AvailableInheritanceClasses[type].Contains(chunkRemapped & 0xFFFFF000)) &&
                                (AvailableChunkClasses[type].TryGetValue(chunkRemapped, out chunkClass) || AvailableChunkClasses[type].TryGetValue(chunkID & 0xFFF, out chunkClass));

                var skippable = reflected && chunkClass.BaseType.GetGenericTypeDefinition() == typeof(SkippableChunk <>);

                if (!reflected || skippable)
                {
                    var skip = r.ReadUInt32();

                    if (skip != 0x534B4950)
                    {
                        if (chunkID != 0 && !reflected)
                        {
                            node.FaultyChunk = chunkID;

                            var logChunkError = $"[{node.ClassName}] 0x{chunkID:X8} ERROR (wrong chunk format or unknown unskippable chunk)";
                            if (node.Body?.GBX.ClassID.HasValue == true && Remap(node.Body.GBX.ClassID.Value) == node.ID)
                            {
                                Log.Write(logChunkError, ConsoleColor.Red);
                            }
                            else
                            {
                                Log.Write($"~ {logChunkError}", ConsoleColor.Red);
                            }

                            throw new Exception($"Wrong chunk format or unskippable chunk: 0x{chunkID:X8} (" +
                                                $"{Names.Where(x => x.Key == Chunk.Remap(chunkID & 0xFFFFF000)).Select(x => x.Value).FirstOrDefault() ?? "unknown class"})" +
                                                $"\nPrevious chunk: 0x{previousChunk ?? 0:X8} (" +
                                                $"{(previousChunk.HasValue ? (Names.Where(x => x.Key == Chunk.Remap(previousChunk.Value & 0xFFFFF000)).Select(x => x.Value).FirstOrDefault() ?? "unknown class") : "not a class")})");

                            /* Usually breaks in the current state and causes confusion
                             *
                             * var buffer = BitConverter.GetBytes(chunkID);
                             * using (var restMs = new MemoryStream(ushort.MaxValue))
                             * {
                             *  restMs.Write(buffer, 0, buffer.Length);
                             *
                             *  while (r.PeekUInt32() != 0xFACADE01)
                             *      restMs.WriteByte(r.ReadByte());
                             *
                             *  node.Rest = restMs.ToArray();
                             * }
                             * Debug.WriteLine("FACADE found.");*/
                        }
                        break;
                    }

                    var chunkDataSize = r.ReadInt32();
                    var chunkData     = new byte[chunkDataSize];
                    if (chunkDataSize > 0)
                    {
                        r.Read(chunkData, 0, chunkDataSize);
                    }

                    if (reflected && chunkClass.GetCustomAttribute <IgnoreChunkAttribute>() == null)
                    {
                        ISkippableChunk c;

                        var constructor       = chunkClass.GetConstructors().First();
                        var constructorParams = constructor.GetParameters();
                        if (constructorParams.Length == 0)
                        {
                            c        = (ISkippableChunk)constructor.Invoke(new object[0]);
                            c.Node   = node;
                            c.Part   = (GameBoxPart)body;
                            c.Stream = new MemoryStream(chunkData, 0, chunkData.Length, false);
                            if (chunkData == null || chunkData.Length == 0)
                            {
                                c.Discovered = true;
                            }
                            c.OnLoad();
                        }
                        else if (constructorParams.Length == 2)
                        {
                            c = (ISkippableChunk)constructor.Invoke(new object[] { node, chunkData });
                        }
                        else
                        {
                            throw new ArgumentException($"{type.FullName} has an invalid amount of parameters.");
                        }

                        chunks.Add((Chunk)c);

                        if (chunkClass.GetCustomAttribute <ChunkAttribute>().ProcessSync)
                        {
                            c.Discover();
                        }

                        chunk = (Chunk)c;
                    }
                    else
                    {
                        Debug.WriteLine("Unknown skippable chunk: " + chunkID.ToString("X"));
                        chunk = (Chunk)Activator.CreateInstance(typeof(SkippableChunk <>).MakeGenericType(type), node, chunkRemapped, chunkData);
                        chunks.Add(chunk);
                    }
                }

                if (reflected && !skippable)
                {
                    if (skippable) // Does it ever happen?
                    {
                        var skip          = r.ReadUInt32();
                        var chunkDataSize = r.ReadInt32();
                    }

                    IChunk c;

                    var constructor       = chunkClass.GetConstructors().First();
                    var constructorParams = constructor.GetParameters();
                    if (constructorParams.Length == 0)
                    {
                        c      = (IChunk)constructor.Invoke(new object[0]);
                        c.Node = node;
                    }
                    else if (constructorParams.Length == 1)
                    {
                        c = (IChunk)constructor.Invoke(new object[] { node });
                    }
                    else
                    {
                        throw new ArgumentException($"{type.FullName} has an invalid amount of parameters.");
                    }

                    c.Part = (GameBoxPart)body;
                    c.OnLoad();

                    chunks.Add((Chunk)c);

                    r.Chunk = (Chunk)c; // Set chunk temporarily for reading

                    var posBefore = r.BaseStream.Position;

                    GameBoxReaderWriter gbxrw = new GameBoxReaderWriter(r);

                    try
                    {
                        if (chunkClass.GetCustomAttribute <IgnoreChunkAttribute>() == null)
                        {
                            if (chunkClass.GetCustomAttribute <AutoReadWriteChunkAttribute>() == null)
                            {
                                c.ReadWrite(node, gbxrw);
                            }
                            else
                            {
                                var unknown     = new GameBoxWriter(((Chunk)c).Unknown, r.Lookbackable);
                                var unknownData = r.ReadTillFacade();
                                unknown.Write(unknownData, 0, unknownData.Length);
                            }
                        }
                        else
                        {
                            throw new Exception($"Chunk 0x{chunkID & 0xFFF:x3} from class {node.ClassName} is known but its content is unknown to read.");
                        }
                    }
                    catch (EndOfStreamException)
                    {
                        Debug.WriteLine($"Unexpected end of the stream while reading the chunk.");
                    }

                    c.Progress = (int)(r.BaseStream.Position - posBefore);

                    r.Chunk = null;

                    chunk = (Chunk)c;
                }

                progress?.Report(new GameBoxReadProgress(GameBoxReadProgressStage.Body, (float)r.BaseStream.Position / r.BaseStream.Length, gbx, chunk));

                previousChunk = chunkID;
            }

            stopwatch.Stop();

            var logNodeCompletion = $"[{node.ClassName}] DONE! ({stopwatch.Elapsed.TotalMilliseconds}ms)";

            if (node.Body?.GBX.ClassID.HasValue == true && Remap(node.Body.GBX.ClassID.Value) == node.ID)
            {
                Log.Write(logNodeCompletion, ConsoleColor.Green);
            }
            else
            {
                Log.Write($"~ {logNodeCompletion}", ConsoleColor.Green);
            }

            return(node);
        }
Esempio n. 2
0
        public void Read(byte[] userData, IProgress <GameBoxReadProgress> progress)
        {
            var gbx = (GameBox <T>)GBX;

            if (gbx.Version >= 6)
            {
                if (userData != null && userData.Length > 0)
                {
                    using (var ms = new MemoryStream(userData))
                        using (var r = new GameBoxReader(ms, this))
                        {
                            var numHeaderChunks = r.ReadInt32();

                            Chunks = new ChunkSet();

                            var chunkList = new Dictionary <uint, (int Size, bool IsHeavy)>();

                            for (var i = 0; i < numHeaderChunks; i++)
                            {
                                var chunkID   = r.ReadUInt32();
                                var chunkSize = r.ReadUInt32();

                                var chId = chunkID & 0xFFF;
                                var clId = chunkID & 0xFFFFF000;

                                chunkList[clId + chId] = ((int)(chunkSize & ~0x80000000), (chunkSize & (1 << 31)) != 0);
                            }

                            Log.Write("Header data chunk list:");

                            foreach (var c in chunkList)
                            {
                                if (c.Value.IsHeavy)
                                {
                                    Log.Write($"| 0x{c.Key:X8} | {c.Value.Size} B (Heavy)");
                                }
                                else
                                {
                                    Log.Write($"| 0x{c.Key:X8} | {c.Value.Size} B");
                                }
                            }

                            foreach (var chunkInfo in chunkList)
                            {
                                var chunkId = Chunk.Remap(chunkInfo.Key);
                                var nodeId  = chunkId & 0xFFFFF000;

                                if (!Node.AvailableClasses.TryGetValue(nodeId, out Type nodeType))
                                {
                                    Log.Write($"Node ID 0x{nodeId:X8} is not implemented. This occurs only in the header therefore it's not a fatal problem. ({Node.Names.Where(x => x.Key == nodeId).Select(x => x.Value).FirstOrDefault() ?? "unknown class"})");
                                }

                                var chunkTypes = new Dictionary <uint, Type>();

                                if (nodeType != null)
                                {
                                    Node.AvailableHeaderChunkClasses.TryGetValue(nodeType, out chunkTypes);
                                }

                                var   d     = r.ReadBytes(chunkInfo.Value.Size);
                                Chunk chunk = null;

                                if (chunkTypes.TryGetValue(chunkId, out Type type))
                                {
                                    var constructor       = type.GetConstructors().First();
                                    var constructorParams = constructor.GetParameters();
                                    if (constructorParams.Length == 0)
                                    {
                                        ISkippableChunk headerChunk = (ISkippableChunk)constructor.Invoke(new object[0]);
                                        headerChunk.Node   = gbx.MainNode;
                                        headerChunk.Part   = this;
                                        headerChunk.Stream = new MemoryStream(d, 0, d.Length, false);
                                        if (d == null || d.Length == 0)
                                        {
                                            headerChunk.Discovered = true;
                                        }
                                        chunk = (Chunk)headerChunk;
                                    }
                                    else if (constructorParams.Length == 2)
                                    {
                                        chunk = (HeaderChunk <T>)constructor.Invoke(new object[] { gbx.MainNode, d });
                                    }
                                    else
                                    {
                                        throw new ArgumentException($"{type.FullName} has an invalid amount of parameters.");
                                    }

                                    using (var msChunk = new MemoryStream(d))
                                        using (var rChunk = new GameBoxReader(msChunk, this))
                                        {
                                            var rw = new GameBoxReaderWriter(rChunk);
                                            ((IHeaderChunk)chunk).ReadWrite(gbx.MainNode, rw);
                                            ((ISkippableChunk)chunk).Discovered = true;
                                        }

                                    ((IHeaderChunk)chunk).IsHeavy = chunkInfo.Value.IsHeavy;
                                }
                                else if (nodeType != null)
                                {
                                    chunk = (Chunk)Activator.CreateInstance(typeof(HeaderChunk <>).MakeGenericType(nodeType), gbx.MainNode, chunkId, d);
                                }
                                else
                                {
                                    chunk = new HeaderChunk(chunkId, d)
                                    {
                                        IsHeavy = chunkInfo.Value.IsHeavy
                                    }
                                };

                                Chunks.Add(chunk);

                                progress?.Report(new GameBoxReadProgress(
                                                     GameBoxReadProgressStage.HeaderUserData,
                                                     r.BaseStream.Position / (float)r.BaseStream.Length,
                                                     gbx,
                                                     chunk));
                            }
                        }
                }
            }
        }