// Ripped from Kopernicus.Utility.cs
            public static Texture2D LoadTexture(string path, bool compress, bool upload, bool unreadable)
            {
                Texture2D map = null;
                path = KSPUtil.ApplicationRootPath + "GameData/" + path;
                if (System.IO.File.Exists(path))
                {
                    bool uncaught = true;
                    try
                    {
                        if (path.ToLower().EndsWith(".dds"))
                        {
                            // Borrowed from stock KSP 1.0 DDS loader (hi Mike!)
                            // Also borrowed the extra bits from Sarbian.
                            byte[] buffer = System.IO.File.ReadAllBytes(path);
                            System.IO.BinaryReader binaryReader = new System.IO.BinaryReader(new System.IO.MemoryStream(buffer));
                            uint num = binaryReader.ReadUInt32();
                            if (num == DDSHeaders.DDSValues.uintMagic)
                            {

                                DDSHeaders.DDSHeader dDSHeader = new DDSHeaders.DDSHeader(binaryReader);

                                if (dDSHeader.ddspf.dwFourCC == DDSHeaders.DDSValues.uintDX10)
                                {
                                    new DDSHeaders.DDSHeaderDX10(binaryReader);
                                }

                                bool alpha = (dDSHeader.dwFlags & 0x00000002) != 0;
                                bool fourcc = (dDSHeader.dwFlags & 0x00000004) != 0;
                                bool rgb = (dDSHeader.dwFlags & 0x00000040) != 0;
                                bool alphapixel = (dDSHeader.dwFlags & 0x00000001) != 0;
                                bool luminance = (dDSHeader.dwFlags & 0x00020000) != 0;
                                bool rgb888 = dDSHeader.ddspf.dwRBitMask == 0x000000ff && dDSHeader.ddspf.dwGBitMask == 0x0000ff00 && dDSHeader.ddspf.dwBBitMask == 0x00ff0000;
                                //bool bgr888 = dDSHeader.ddspf.dwRBitMask == 0x00ff0000 && dDSHeader.ddspf.dwGBitMask == 0x0000ff00 && dDSHeader.ddspf.dwBBitMask == 0x000000ff;
                                bool rgb565 = dDSHeader.ddspf.dwRBitMask == 0x0000F800 && dDSHeader.ddspf.dwGBitMask == 0x000007E0 && dDSHeader.ddspf.dwBBitMask == 0x0000001F;
                                bool argb4444 = dDSHeader.ddspf.dwABitMask == 0x0000f000 && dDSHeader.ddspf.dwRBitMask == 0x00000f00 && dDSHeader.ddspf.dwGBitMask == 0x000000f0 && dDSHeader.ddspf.dwBBitMask == 0x0000000f;
                                bool rbga4444 = dDSHeader.ddspf.dwABitMask == 0x0000000f && dDSHeader.ddspf.dwRBitMask == 0x0000f000 && dDSHeader.ddspf.dwGBitMask == 0x000000f0 && dDSHeader.ddspf.dwBBitMask == 0x00000f00;

                                bool mipmap = (dDSHeader.dwCaps & DDSHeaders.DDSPixelFormatCaps.MIPMAP) != (DDSHeaders.DDSPixelFormatCaps)0u;
                                bool isNormalMap = ((dDSHeader.ddspf.dwFlags & 524288u) != 0u || (dDSHeader.ddspf.dwFlags & 2147483648u) != 0u);
                                if (fourcc)
                                {
                                    if (dDSHeader.ddspf.dwFourCC == DDSHeaders.DDSValues.uintDXT1)
                                    {
                                        map = new Texture2D((int)dDSHeader.dwWidth, (int)dDSHeader.dwHeight, TextureFormat.DXT1, mipmap);
                                        map.LoadRawTextureData(binaryReader.ReadBytes((int)(binaryReader.BaseStream.Length - binaryReader.BaseStream.Position)));
                                    }
                                    else if (dDSHeader.ddspf.dwFourCC == DDSHeaders.DDSValues.uintDXT3)
                                    {
                                        map = new Texture2D((int)dDSHeader.dwWidth, (int)dDSHeader.dwHeight, (TextureFormat)11, mipmap);
                                        map.LoadRawTextureData(binaryReader.ReadBytes((int)(binaryReader.BaseStream.Length - binaryReader.BaseStream.Position)));
                                    }
                                    else if (dDSHeader.ddspf.dwFourCC == DDSHeaders.DDSValues.uintDXT5)
                                    {
                                        map = new Texture2D((int)dDSHeader.dwWidth, (int)dDSHeader.dwHeight, TextureFormat.DXT5, mipmap);
                                        map.LoadRawTextureData(binaryReader.ReadBytes((int)(binaryReader.BaseStream.Length - binaryReader.BaseStream.Position)));
                                    }
                                    else if (dDSHeader.ddspf.dwFourCC == DDSHeaders.DDSValues.uintDXT2)
                                    {
                                        Debug.Log("[Kopernicus]: DXT2 not supported" + path);
                                    }
                                    else if (dDSHeader.ddspf.dwFourCC == DDSHeaders.DDSValues.uintDXT4)
                                    {
                                        Debug.Log("[Kopernicus]: DXT4 not supported: " + path);
                                    }
                                    else if (dDSHeader.ddspf.dwFourCC == DDSHeaders.DDSValues.uintDX10)
                                    {
                                        Debug.Log("[Kopernicus]: DX10 dds not supported: " + path);
                                    }
                                    else
                                        fourcc = false;
                                }
                                if (!fourcc)
                                {
                                    TextureFormat textureFormat = TextureFormat.ARGB32;
                                    bool ok = true;
                                    if (rgb && (rgb888 /*|| bgr888*/))
                                    {
                                        // RGB or RGBA format
                                        textureFormat = alphapixel
                                        ? TextureFormat.RGBA32
                                        : TextureFormat.RGB24;
                                    }
                                    else if (rgb && rgb565)
                                    {
                                        // Nvidia texconv B5G6R5_UNORM
                                        textureFormat = TextureFormat.RGB565;
                                    }
                                    else if (rgb && alphapixel && argb4444)
                                    {
                                        // Nvidia texconv B4G4R4A4_UNORM
                                        textureFormat = TextureFormat.ARGB4444;
                                    }
                                    else if (rgb && alphapixel && rbga4444)
                                    {
                                        textureFormat = TextureFormat.RGBA4444;
                                    }
                                    else if (!rgb && alpha != luminance)
                                    {
                                        // A8 format or Luminance 8
                                        textureFormat = TextureFormat.Alpha8;
                                    }
                                    else
                                    {
                                        ok = false;
                                        Debug.Log("[Kopernicus]: Only DXT1, DXT5, A8, RGB24, RGBA32, RGB565, ARGB4444 and RGBA4444 are supported");
                                    }
                                    if (ok)
                                    {
                                        map = new Texture2D((int)dDSHeader.dwWidth, (int)dDSHeader.dwHeight, textureFormat, mipmap);
                                        map.LoadRawTextureData(binaryReader.ReadBytes((int)(binaryReader.BaseStream.Length - binaryReader.BaseStream.Position)));
                                    }

                                }
                                if (map != null)
                                    if (upload)
                                        map.Apply(false, unreadable);
                            }
                            else
                                Debug.Log("[Kopernicus]: Bad DDS header.");
                        }
                        else
                        {
                            map = new Texture2D(2, 2);
                            map.LoadImage(System.IO.File.ReadAllBytes(path));
                            if (compress)
                                map.Compress(true);
                            if (upload)
                                map.Apply(false, unreadable);
                        }
                    }
                    catch (Exception e)
                    {
                        uncaught = false;
                        Debug.Log("[Kopernicus]: failed to load " + path + " with exception " + e.Message);
                    }
                    if (map == null && uncaught)
                    {
                        Debug.Log("[Kopernicus]: failed to load " + path);
                    }
                    map.name = path.Remove(0, (KSPUtil.ApplicationRootPath + "GameData/").Length);
                }
                else
                    Debug.Log("[Kopernicus]: texture does not exist! " + path);

                return map;
            }
Esempio n. 2
0
        public void Parse(Header header, byte[] data)
        {
            using (System.IO.MemoryStream ms = new System.IO.MemoryStream(data))
            {
                using (System.IO.BinaryReader br = new System.IO.BinaryReader(ms))
                {
                    _authCode = br.ReadInt32();
                    _accountId = br.ReadUInt32();
                    _userLevel = br.ReadUInt32();
                    _lastLoginIP = br.ReadUInt32();
                    _lastLoginTime = br.ReadBytes(26);
                    _sex = br.ReadByte();

                    _serverList = new Dictionary<string, Server>();
                    for (int i = (int)ms.Position; i < header.Size; i += 32)
                    {
                        Server s = new Server();
                        s.IP = string.Format("{0}.{1}.{2}.{3}", br.ReadByte(), br.ReadByte(), br.ReadByte(), br.ReadByte());
                        s.Port = br.ReadInt16();
                        s.Name = br.ReadBytes(22).NullByteTerminatedString();
                        s.Type = br.ReadInt16();
                        s.UserCount = br.ReadInt16();
                        _serverList.Add(s.Name, s);
                    }
                }
            }
        }
Esempio n. 3
0
 public static MachineType GetDllMachineType(this string dllPath)
 {
     // See http://www.microsoft.com/whdc/system/platform/firmware/PECOFF.mspx
     // Offset to PE header is always at 0x3C.
     // The PE header starts with "PE\0\0" =  0x50 0x45 0x00 0x00,
     // followed by a 2-byte machine type field (see the document above for the enum).
     //
     using (var fs = new System.IO.FileStream(dllPath, System.IO.FileMode.Open, System.IO.FileAccess.Read))
         using (var br = new System.IO.BinaryReader(fs)) {
             MachineType machineType = MachineType.IMAGE_FILE_MACHINE_UNKNOWN;
     //					bool isgood = false;
             try {
                 fs.Seek(0x3c, System.IO.SeekOrigin.Begin);
                 Int32 peOffset = br.ReadInt32();
                 fs.Seek(peOffset, System.IO.SeekOrigin.Begin);
                 UInt32 peHead = br.ReadUInt32();
                 if (peHead != 0x00004550)
                     // "PE\0\0", little-endian
                     throw new Exception("Can't find PE header");
                 machineType = (MachineType)br.ReadUInt16();
     //						isgood = true;
             }
             catch {
     //						isgood = false;
             }
             finally {
                 br.Close();
                 fs.Close();
             }
             return machineType;
         }
 }
Esempio n. 4
0
        static void Main( string[] args )
        {
            using ( var mem = new System.IO.MemoryStream( Consts.SuccessfulResponse ) ) {
                mem.Seek( 0, System.IO.SeekOrigin.Begin );
                var br = new System.IO.BinaryReader( mem );

                var pl = br.ReadUInt32();
                br.ReadUInt32();

                var decoded = new byte[pl];
                Buffer.BlockCopy( Consts.SuccessfulResponse,
                                  (int) br.BaseStream.Position,
                                  decoded, 0, (int) pl );
                decoded = NetworkHelper.PacketDecoding( decoded );

                NetworkHelper.DumpArray( Console.OpenStandardOutput( ), decoded );
            }

            var srv = new HatServer();
            srv.EventOccured += srv_EventOccured;
            srv.Start( "127.0.0.1", 8000 );
        }
Esempio n. 5
0
        public static System.Windows.Forms.TreeNode ParseFile(string path)
        {
            // Read archive tree
            uint nFiles, baseOffset;
            System.Windows.Forms.TreeNode node = new System.Windows.Forms.TreeNode();

            System.IO.BinaryReader stream = new System.IO.BinaryReader(System.IO.File.OpenRead(path));
            stream.ReadUInt32();
            nFiles = stream.ReadUInt32();
            baseOffset = stream.ReadUInt32();

            for (int i = 0; i < nFiles; i++)
            {
                char b;
                FileEntry f = new FileEntry();
                do
                {
                    b = (char)stream.ReadByte();
                    if (b != 0)
                        f.name += b;
                } while (b != 0);
                f.length = stream.ReadUInt32();
                stream.ReadUInt32();

                f.offset = baseOffset;
                baseOffset += f.length;

                f.idx = (uint)i;

                System.Windows.Forms.TreeNode n = new System.Windows.Forms.TreeNode(f.name);
                n.Tag = f;

                node.Nodes.Add(n);
            }

            return node;
        }
Esempio n. 6
0
        public Cursors_v2(string path)
        {
            System.IO.BinaryReader stream = new System.IO.BinaryReader(new System.IO.FileStream(path + "system\\icons.ph", System.IO.FileMode.Open, System.IO.FileAccess.Read));

            if (stream.ReadUInt32() != 0x6e6f6369 || stream.ReadUInt16() != 1)
                throw new Exception("Invalid icon file");

            _numCursors = stream.ReadUInt16();
            cursors = new V2_Cursor[_numCursors];

            for (int i = 0; i < _numCursors; i++)
            {
                readCursor(i, stream);
            }
        }
Esempio n. 7
0
		protected static bool ValidateExe(string path, long time_stamp_offset, uint time_stamp)
		{
			using (var fs = new System.IO.FileStream(path, System.IO.FileMode.Open, System.IO.FileAccess.Read))
			using (var s = new System.IO.BinaryReader(fs))
			{
				if (fs.Length > (time_stamp_offset+4))
				{
					fs.Seek(time_stamp_offset, System.IO.SeekOrigin.Begin);
					uint ts = s.ReadUInt32();

					return ts == time_stamp;
				}
			}

			return false;
		}
Esempio n. 8
0
 /// <summary>Checks whether a specified file is a valid Win32 plugin.</summary>
 /// <param name="file">The file to check.</param>
 /// <returns>Whether the file is a valid Win32 plugin.</returns>
 private static bool CheckWin32Header(string file)
 {
     using (System.IO.FileStream stream = new System.IO.FileStream(file, System.IO.FileMode.Open, System.IO.FileAccess.Read)) {
         using (System.IO.BinaryReader reader = new System.IO.BinaryReader(stream)) {
             if (reader.ReadUInt16() != 0x5A4D) {
                 /* Not MZ signature */
                 return false;
             }
             stream.Position = 0x3C;
             stream.Position = reader.ReadInt32();
             if (reader.ReadUInt32() != 0x00004550) {
                 /* Not PE signature */
                 return false;
             }
             if (reader.ReadUInt16() != 0x014C) {
                 /* Not IMAGE_FILE_MACHINE_I386 */
                 return false;
             }
         }
     }
     return true;
 }
Esempio n. 9
0
        public void UnserializeData(System.IO.BinaryReader reader)
        {
            unknown1 = reader.ReadInt16();
            short ct1 = reader.ReadInt16();
            short ct2 = reader.ReadInt16();

            headerb = reader.ReadBytes(headerb.Length);
            for (int i = 0; i < headeri.Length; i++)
            {
                headeri[i] = reader.ReadUInt32();
            }
            for (int i = 0; i < headerf.Length; i++)
            {
                headerf[i] = reader.ReadSingle();
            }

            objname = Helper.ToString(reader.ReadBytes(headerb[5]));
            reader.ReadByte();             //read the terminating 0
            objmod = Helper.ToString(reader.ReadBytes(headerb[0]));
            reader.ReadByte();             //read the terminating 0

            int ct = headerb[0] + headerb[5];

            Align(reader, ct + 2);

            //--- part1 ---
            ab1 = new AnimationMeshBlock[ct1];
            int len = 0;

            for (int i = 0; i < ab1.Length; i++)
            {
                ab1[i] = new AnimationMeshBlock(this.Parent);
                ab1[i].UnserializeData(reader);
            }
            for (int i = 0; i < ab1.Length; i++)
            {
                len += ab1[i].UnserializeName(reader);
            }
            Align(reader, len);

            //--- part2 ---
            len = 0;
            for (int i = 0; i < ab1.Length; i++)
            {
                ab1[i].UnserializePart2Data(reader);
            }
            for (int i = 0; i < ab1.Length; i++)
            {
                len += ab1[i].UnserializePart2Name(reader);
            }
            Align(reader, len);

            try
            {
                //--- part3 ---
                for (int i = 0; i < ab1.Length; i++)
                {
                    ab1[i].UnserializePart3Data(reader);
                }
                for (int i = 0; i < ab1.Length; i++)
                {
                    ab1[i].UnserializePart3AddonData(reader);
                }

                //--- part4 ---
                for (int i = 0; i < ab1.Length; i++)
                {
                    ab1[i].UnserializePart4Data(reader);
                }

                //--- part5 ---
                for (int i = 0; i < ab1.Length; i++)
                {
                    ab1[i].UnserializePart5Data(reader);
                }

                //--- part6 ---
                ab6 = new AnimBlock6[ct2];
                len = 0;
                for (int i = 0; i < ab6.Length; i++)
                {
                    ab6[i] = new AnimBlock6();
                    ab6[i].UnserializeData(reader);
                }
                for (int i = 0; i < ab6.Length; i++)
                {
                    len += ab6[i].UnserializeName(reader);
                }
            }
            catch {}

            unknowndata = reader.ReadBytes((int)(reader.BaseStream.Length - reader.BaseStream.Position));
        }
Esempio n. 10
0
        protected override void DataUpdate()
        {
            System.IO.BinaryReader BSReader = new System.IO.BinaryReader(ByteStream);
            ByteStream.Position = 0;
            HeaderSize          = BSReader.ReadByte();
            ImagePages          = BSReader.ReadUInt16();
            Reserved            = BSReader.ReadByte();
            SomeKey             = BSReader.ReadUInt32();
            Width       = (uint)Math.Pow(2, BSReader.ReadUInt16());
            MipWidth    = (ushort)(Width / 2);
            Height      = (uint)Math.Pow(2, BSReader.ReadUInt16());
            Mip         = BSReader.ReadByte();
            PaletteFlag = BSReader.ReadByte();
            PaletteSize = BSReader.ReadUInt16();
            Space       = BSReader.ReadBytes(32);
            DataType    = BSReader.ReadUInt32();
            Unexplored  = BSReader.ReadBytes(176);
            switch (DataType)
            {
            case 1:
            {
                uint DataPos = (uint)ByteStream.Position;
                Array.Resize(ref Index, (int)(Width * Height));
                Array.Resize(ref MipIndex, (int)(MipWidth * Height));
                Array.Resize(ref RawData, (int)(Width * Height));
                Array.Resize(ref Palette, ImagePages * 16);
                if ((Width == 32) && (Height == 8))
                {
                    for (int i = 0; i <= 3; i++)
                    {
                        for (int j = 0; j <= 63; j++)
                        {
                            Index[j + i * 64] = BSReader.ReadByte();
                        }
                        ByteStream.Position += 192;
                    }
                    ByteStream.Position += 12 * 256;
                    for (int i = 0; i <= 15; i++)
                    {
                        for (int j = 0; j <= 15; j++)
                        {
                            byte a, r, g, b;
                            r = BSReader.ReadByte();
                            g = BSReader.ReadByte();
                            b = BSReader.ReadByte();
                            a = (byte)(BSReader.ReadByte() << 1);
                            Palette[j + i * 16] = Color.FromArgb(a, r, g, b);
                        }
                        ByteStream.Position += 192;
                    }
                }
                else if ((Width == 16) && (Height == 16))
                {
                    for (int i = 0; i <= 7; i++)
                    {
                        for (int j = 0; j <= 31; j++)
                        {
                            Index[j + i * 32] = BSReader.ReadByte();
                        }
                        ByteStream.Position += 224;
                    }
                    for (int i = 0; i <= 3; i++)
                    {
                        for (int j = 0; j <= 31; j++)
                        {
                            MipIndex[j + i * 32] = BSReader.ReadByte();
                        }
                        ByteStream.Position += 224;
                    }
                    ByteStream.Position += 4 * 256;
                    for (int i = 0; i <= 15; i++)
                    {
                        for (int j = 0; j <= 15; j++)
                        {
                            byte a, r, g, b;
                            r = BSReader.ReadByte();
                            g = BSReader.ReadByte();
                            b = BSReader.ReadByte();
                            a = (byte)(BSReader.ReadByte() << 1);
                            Palette[j + i * 16] = Color.FromArgb(a, r, g, b);
                        }
                        ByteStream.Position += 192;
                    }
                }
                else if ((Width == 32) && (Height == 16))
                {
                    for (int i = 0; i <= 7; i++)
                    {
                        for (int j = 0; j <= 63; j++)
                        {
                            Index[j + i * 64] = BSReader.ReadByte();
                        }
                        ByteStream.Position += 192;
                    }
                    for (int i = 0; i <= 7; i++)
                    {
                        for (int j = 0; j <= 31; j++)
                        {
                            MipIndex[j + i * 32] = BSReader.ReadByte();
                        }
                        ByteStream.Position += 224;
                    }
                    for (int i = 0; i <= 15; i++)
                    {
                        for (int j = 0; j <= 15; j++)
                        {
                            byte a, r, g, b;
                            r = BSReader.ReadByte();
                            g = BSReader.ReadByte();
                            b = BSReader.ReadByte();
                            a = (byte)(BSReader.ReadByte() << 1);
                            Palette[j + i * 16] = Color.FromArgb(a, r, g, b);
                        }
                        ByteStream.Position += 192;
                    }
                }
                else if ((Width == 32) && (Height == 32))
                {
                    if (Mip == 1)
                    {
                        for (int i = 0; i <= 15; i++)
                        {
                            for (int j = 0; j <= 63; j++)
                            {
                                Index[j + i * 64] = BSReader.ReadByte();
                            }
                            ByteStream.Position += 192;
                        }
                        for (int i = 0; i <= 15; i++)
                        {
                            for (int j = 0; j <= 15; j++)
                            {
                                byte a, r, g, b;
                                r = BSReader.ReadByte();
                                g = BSReader.ReadByte();
                                b = BSReader.ReadByte();
                                a = (byte)(BSReader.ReadByte() << 1);
                                Palette[j + i * 16] = Color.FromArgb(a, r, g, b);
                            }
                            ByteStream.Position += 192;
                        }
                    }
                    else
                    {
                        for (int i = 0; i <= 15; i++)
                        {
                            for (int j = 0; j <= 63; j++)
                            {
                                Index[j + i * 64] = BSReader.ReadByte();
                            }
                            for (int j = 0; j <= 15; j++)
                            {
                                byte a, r, g, b;
                                r = BSReader.ReadByte();
                                g = BSReader.ReadByte();
                                b = BSReader.ReadByte();
                                a = (byte)(BSReader.ReadByte() << 1);
                                Palette[j + i * 16] = Color.FromArgb(a, r, g, b);
                            }
                            ByteStream.Position += 128;
                        }
                        for (int i = 0; i <= 15; i++)
                        {
                            for (int j = 0; j <= 31; j++)
                            {
                                MipIndex[j + i * 32] = BSReader.ReadByte();
                            }
                            ByteStream.Position += 224;
                        }
                    }
                }
                else if ((Width == 32) && (Height == 64))
                {
                    if (Mip == 1)
                    {
                        for (int i = 0; i <= 31; i++)
                        {
                            for (int j = 0; j <= 63; j++)
                            {
                                Index[j + i * 64] = BSReader.ReadByte();
                            }
                            for (int j = 0; j <= 15; j++)
                            {
                                byte a, r, g, b;
                                r = BSReader.ReadByte();
                                g = BSReader.ReadByte();
                                b = BSReader.ReadByte();
                                a = (byte)(BSReader.ReadByte() << 1);
                                Palette[j + i * 16] = Color.FromArgb(a, r, g, b);
                            }
                            ByteStream.Position += 128;
                        }
                    }
                    else
                    {
                        for (int i = 0; i <= 15; i++)
                        {
                            for (int j = 0; j <= 63; j++)
                            {
                                Index[j + i * 64] = BSReader.ReadByte();
                            }
                            for (int j = 0; j <= 63; j++)
                            {
                                MipIndex[j + i * 64] = BSReader.ReadByte();
                            }
                            for (int j = 0; j <= 15; j++)
                            {
                                byte a, r, g, b;
                                r = BSReader.ReadByte();
                                g = BSReader.ReadByte();
                                b = BSReader.ReadByte();
                                a = (byte)(BSReader.ReadByte() << 1);
                                Palette[j + i * 16] = Color.FromArgb(a, r, g, b);
                            }
                            ByteStream.Position += 64;
                        }
                        for (int i = 0; i <= 15; i++)
                        {
                            for (int j = 0; j <= 63; j++)
                            {
                                Index[1024 + j + i * 64] = BSReader.ReadByte();
                            }
                            ByteStream.Position += 64;
                            for (int j = 0; j <= 15; j++)
                            {
                                byte a, r, g, b;
                                r = BSReader.ReadByte();
                                g = BSReader.ReadByte();
                                b = BSReader.ReadByte();
                                a = (byte)(BSReader.ReadByte() << 1);
                                Palette[256 + j + i * 16] = Color.FromArgb(a, r, g, b);
                            }
                            ByteStream.Position += 64;
                        }
                    }
                }
                else if ((Width == 64) && (Height == 32))
                {
                    if (Mip == 1)
                    {
                        for (int i = 0; i <= 15; i++)
                        {
                            for (int j = 0; j <= 127; j++)
                            {
                                Index[j + i * 128] = BSReader.ReadByte();
                            }
                            ByteStream.Position += 128;
                        }
                        for (int i = 0; i <= 15; i++)
                        {
                            for (int j = 0; j <= 15; j++)
                            {
                                byte a, r, g, b;
                                r = BSReader.ReadByte();
                                g = BSReader.ReadByte();
                                b = BSReader.ReadByte();
                                a = (byte)(BSReader.ReadByte() << 1);
                                Palette[j + i * 16] = Color.FromArgb(a, r, g, b);
                            }
                            ByteStream.Position += 192;
                        }
                    }
                    else
                    {
                        for (int i = 0; i <= 15; i++)
                        {
                            for (int j = 0; j <= 127; j++)
                            {
                                Index[j + i * 128] = BSReader.ReadByte();
                            }
                            ByteStream.Position += 128;
                        }
                        for (int i = 0; i <= 15; i++)
                        {
                            for (int j = 0; j <= 63; j++)
                            {
                                MipIndex[j + i * 64] = BSReader.ReadByte();
                            }
                            for (int j = 0; j <= 15; j++)
                            {
                                byte a, r, g, b;
                                r = BSReader.ReadByte();
                                g = BSReader.ReadByte();
                                b = BSReader.ReadByte();
                                a = (byte)(BSReader.ReadByte() << 1);
                                Palette[j + i * 16] = Color.FromArgb(a, r, g, b);
                            }
                            ByteStream.Position += 128;
                        }
                    }
                }
                else if ((Width == 64) && (Height == 64))
                {
                    if (Mip == 1)
                    {
                        for (int i = 0; i <= 31; i++)
                        {
                            for (int j = 0; j <= 127; j++)
                            {
                                Index[j + i * 128] = BSReader.ReadByte();
                            }
                            for (int j = 0; j <= 15; j++)
                            {
                                byte a, r, g, b;
                                r = BSReader.ReadByte();
                                g = BSReader.ReadByte();
                                b = BSReader.ReadByte();
                                a = (byte)(BSReader.ReadByte() << 1);
                                Palette[j + i * 16] = Color.FromArgb(a, r, g, b);
                            }
                            ByteStream.Position += 64;
                        }
                    }
                    else
                    {
                        for (int i = 0; i <= 31; i++)
                        {
                            for (int j = 0; j <= 127; j++)
                            {
                                Index[j + i * 128] = BSReader.ReadByte();
                            }
                            for (int j = 0; j <= 63; j++)
                            {
                                MipIndex[j + i * 64] = BSReader.ReadByte();
                            }
                            for (int j = 0; j <= 15; j++)
                            {
                                byte a, r, g, b;
                                r = BSReader.ReadByte();
                                g = BSReader.ReadByte();
                                b = BSReader.ReadByte();
                                a = (byte)(BSReader.ReadByte() << 1);
                                Palette[j + i * 16] = Color.FromArgb(a, r, g, b);
                            }
                        }
                    }
                }
                else
                {
                    Interaction.MsgBox("ID:" + ID.ToString() + " Width: " + Width.ToString() + " Height: " + Height.ToString(), MsgBoxStyle.Exclamation, "Kesha, we have a problem!");
                }
                UnSwizzle(ref Index, (ushort)Width, (ushort)Height);
                UnSwizzle(ref MipIndex, MipWidth, (ushort)Height);
                Flip(ref Index, (ushort)Width, (ushort)Height);
                SwapPalette(ref Palette);
                for (int i = 0; i <= RawData.Length - 1; i++)
                {
                    RawData[i] = Palette[Index[i]];
                }
                break;
            }

            case 2:
            {
                Array.Resize(ref Index, (int)(Width * Height));
                Array.Resize(ref MipIndex, (int)(MipWidth * Height));
                Array.Resize(ref Palette, 512);
                if ((Width == 128) && (Height == 32))
                {
                    Index = BSReader.ReadBytes(4096);
                    for (int i = 0; i <= 15; i++)
                    {
                        for (int j = 0; j <= 127; j++)
                        {
                            MipIndex[j + i * 128] = BSReader.ReadByte();
                        }
                        for (int j = 0; j <= 15; j++)
                        {
                            byte a, r, g, b;
                            r = BSReader.ReadByte();
                            g = BSReader.ReadByte();
                            b = BSReader.ReadByte();
                            a = (byte)(BSReader.ReadByte() << 1);
                            Palette[j + i * 16] = Color.FromArgb(a, r, g, b);
                        }
                        ByteStream.Position += 64;
                    }
                }
                else if ((Width == 128) && (Height == 64))
                {
                    Index = BSReader.ReadBytes(8192);
                    for (int i = 0; i <= 15; i++)
                    {
                        for (int j = 0; j <= 63; j++)
                        {
                            MipIndex[j + i * 64] = BSReader.ReadByte();
                        }
                        ByteStream.Position += 192;
                    }
                    for (int i = 0; i <= 15; i++)
                    {
                        for (int j = 0; j <= 63; j++)
                        {
                            MipIndex[512 + j + i * 64] = BSReader.ReadByte();
                        }
                        for (int j = 0; j <= 15; j++)
                        {
                            byte a, r, g, b;
                            r = BSReader.ReadByte();
                            g = BSReader.ReadByte();
                            b = BSReader.ReadByte();
                            a = (byte)(BSReader.ReadByte() << 1);
                            Palette[j + i * 16] = Color.FromArgb(a, r, g, b);
                        }
                        ByteStream.Position += 128;
                    }
                }
                else if ((Width == 128) && (Height == 128))
                {
                    Index = BSReader.ReadBytes(16384);
                    if (Mip > 1)
                    {
                        for (int i = 0; i < 32; i++)
                        {
                            for (int j = 0; j < 192; j++)
                            {
                                MipIndex[j + i * 192] = BSReader.ReadByte();
                            }
                            for (int j = 0; j < 16; j++)
                            {
                                byte a, r, g, b;
                                r = BSReader.ReadByte();
                                g = BSReader.ReadByte();
                                b = BSReader.ReadByte();
                                a = (byte)(BSReader.ReadByte() << 1);
                                Palette[j + i * 16] = Color.FromArgb(a, r, g, b);
                            }
                        }
                    }
                    else
                    {
                        for (int i = 0; i <= 31; i++)
                        {
                            for (int j = 0; j <= 15; j++)
                            {
                                byte a, r, g, b;
                                r = BSReader.ReadByte();
                                g = BSReader.ReadByte();
                                b = BSReader.ReadByte();
                                a = (byte)(BSReader.ReadByte() << 1);
                                Palette[j + i * 16] = Color.FromArgb(a, r, g, b);
                            }
                            ByteStream.Position += 192;
                        }
                    }
                }
                else if ((Width == 128) && (Height == 256))
                {
                    Index = BSReader.ReadBytes(32768);
                    for (int i = 0; i < 32; i++)
                    {
                        for (int j = 0; j < 16; j++)
                        {
                            byte a, r, g, b;
                            r = BSReader.ReadByte();
                            g = BSReader.ReadByte();
                            b = BSReader.ReadByte();
                            a = (byte)(BSReader.ReadByte() << 1);
                            Palette[j + i * 16] = Color.FromArgb(a, r, g, b);
                        }
                        ByteStream.Position += 192;
                    }
                }
                else
                {
                    Interaction.MsgBox("ID:" + ID.ToString() + " Width: " + Width.ToString() + " Height: " + Height.ToString(), MsgBoxStyle.Exclamation, "Kesha, we have a problem! Abort now!");
                }
                UnSwizzle(ref Index, (ushort)Width, (ushort)Height);
                Flip(ref Index, (ushort)Width, (ushort)Height);
                SwapPalette(ref Palette);
                Array.Resize(ref RawData, Index.Length);
                for (int i = 0; i <= RawData.Length - 1; i++)
                {
                    RawData[i] = Palette[Index[i]];
                }
                break;
            }

            case 4:
            {
                Array.Resize(ref RawData, (int)(Width * Height));
                for (int i = 0; i <= (Width) * Height - 1; i++)
                {
                    byte a, r, g, b;
                    r          = BSReader.ReadByte();
                    g          = BSReader.ReadByte();
                    b          = BSReader.ReadByte();
                    a          = (byte)(BSReader.ReadByte() << 1);
                    RawData[i] = Color.FromArgb(a, r, g, b);
                }

                break;
            }
            }
        }
Esempio n. 11
0
        private void read(System.IO.Stream stream)
        {
            _intermediateOutput = new IntermediateOutput();

            System.IO.BinaryReader reader = new System.IO.BinaryReader(stream);

            SheepHeader header;

            header.Magic1 = reader.ReadUInt32();
            header.Magic2 = reader.ReadUInt32();

            if (header.Magic1 != SheepHeader.Magic1Value ||
                header.Magic2 != SheepHeader.Magic2Value)
            {
                throw new Exception("Input file is not a valid sheep file");
            }

            header.Unknown     = reader.ReadUInt32();
            header.ExtraOffset = reader.ReadUInt32();
            header.DataOffset  = reader.ReadUInt32();
            header.DataSize    = reader.ReadUInt32();
            header.DataCount   = reader.ReadUInt32();

            header.OffsetArray = new uint[header.DataCount];

            for (uint i = 0; i < header.DataCount; i++)
            {
                header.OffsetArray[i] = reader.ReadUInt32();
            }

            for (uint i = 0; i < header.DataCount; i++)
            {
                if (header.OffsetArray[i] >= stream.Length)
                {
                    throw new Exception("Input file is not a valid Sheep file");
                }

                stream.Seek(header.DataOffset + header.OffsetArray[i], System.IO.SeekOrigin.Begin);

                SectionHeader sectionHeader = readSectionHeader(reader);
                long          currentOffset = stream.Position;

                if (sectionHeader.Label == "SysImports")
                {
                    for (uint j = 0; j < sectionHeader.Datacount; j++)
                    {
                        SheepImport import;

                        stream.Seek(currentOffset + sectionHeader.OffsetArray[j], System.IO.SeekOrigin.Begin);

                        short lengthOfName = reader.ReadInt16();
                        import.Name     = readString(reader, lengthOfName);
                        import.Callback = null;

                        // skip padding
                        reader.ReadByte();

                        byte numReturns    = reader.ReadByte();
                        byte numParameters = reader.ReadByte();

                        import.ReturnType = (SheepSymbolType)numReturns;
                        import.Parameters = new SheepSymbolType[numParameters];

                        for (byte k = 0; k < numParameters; k++)
                        {
                            SheepSymbolType paramterType = (SheepSymbolType)reader.ReadByte();

                            if (paramterType == SheepSymbolType.Int ||
                                paramterType == SheepSymbolType.Float ||
                                paramterType == SheepSymbolType.String)
                            {
                                import.Parameters[k] = paramterType;
                            }
                        }

                        _intermediateOutput.Imports.Add(import);
                    }
                }
                else if (sectionHeader.Label == "StringConsts")
                {
                    for (uint j = 0; j < sectionHeader.Datacount; j++)
                    {
                        stream.Seek(currentOffset + sectionHeader.OffsetArray[j], System.IO.SeekOrigin.Begin);

                        SheepStringConstant constant;
                        constant.Offset = sectionHeader.OffsetArray[j];
                        constant.Value  = readString(reader);

                        _intermediateOutput.Constants.Add(constant);
                    }
                }
                else if (sectionHeader.Label == "Variables")
                {
                    for (uint j = 0; j < sectionHeader.Datacount; j++)
                    {
                        stream.Seek(currentOffset + sectionHeader.OffsetArray[j], System.IO.SeekOrigin.Begin);

                        SheepSymbol symbol = new SheepSymbol();
                        short       len    = reader.ReadInt16();
                        symbol.Name = readString(reader, len);

                        // skip padding
                        reader.ReadByte();

                        symbol.Type = (SheepSymbolType)reader.ReadUInt32();

                        if (symbol.Type == SheepSymbolType.Int)
                        {
                            symbol.InitialIntValue = reader.ReadInt32();
                        }
                        else if (symbol.Type == SheepSymbolType.Float)
                        {
                            symbol.InitialFloatValue = reader.ReadSingle();
                        }
                        else if (symbol.Type == SheepSymbolType.String)
                        {
                            symbol.InitialStringValue = reader.ReadInt32();
                        }
                        else
                        {
                            throw new Exception("???");
                        }

                        _intermediateOutput.Symbols.Add(symbol);
                    }
                }
                else if (sectionHeader.Label == "Functions")
                {
                    for (uint j = 0; j < sectionHeader.Datacount; j++)
                    {
                        SheepFunction func = new SheepFunction();
                        short         len  = reader.ReadInt16();
                        func.Name = readString(reader, len);

                        reader.ReadByte();
                        reader.ReadByte();
                        func.CodeOffset = reader.ReadUInt32();

                        _intermediateOutput.Functions.Add(func);
                    }
                }
                else if (sectionHeader.Label == "Code")
                {
                    if (sectionHeader.Datacount > 1)
                    {
                        throw new Exception("Extra code sections found");
                    }

                    for (int j = 0; j < _intermediateOutput.Functions.Count; j++)
                    {
                        stream.Seek(currentOffset + _intermediateOutput.Functions[j].CodeOffset, System.IO.SeekOrigin.Begin);

                        uint size;
                        if (j == _intermediateOutput.Functions.Count - 1)
                        {
                            size = sectionHeader.DataSize - _intermediateOutput.Functions[j].CodeOffset;
                        }
                        else
                        {
                            size = _intermediateOutput.Functions[j + 1].CodeOffset - _intermediateOutput.Functions[j].CodeOffset;
                        }

                        SheepFunction f = _intermediateOutput.Functions[j];
                        f.Code = reader.ReadBytes((int)size);
                        _intermediateOutput.Functions[j] = f;
                    }
                }
            }
        }
Esempio n. 12
0
        public VoxelModel LoadVoxelModel(System.IO.Stream stream, out Vector3 pivot, IProgressListener progress)
        {
            var reader = new System.IO.BinaryReader(stream);

            {
                var buf = new byte[4];
                if (stream.Read(buf, 0, 4) < 4)
                {
                    throw new System.IO.IOException("Magic not read");
                }
                if (buf[0] != 'K' ||
                   buf[1] != 'v' ||
                   buf[2] != 'x' ||
                   buf[3] != 'l')
                {
                    throw new System.IO.IOException("Invalid magic");
                }
            }

            int xsiz = reader.ReadInt32();
            int ysiz = reader.ReadInt32();
            int zsiz = reader.ReadInt32();
            float xpivot = reader.ReadSingle();
            float ypivot = reader.ReadSingle();
            float zpivot = reader.ReadSingle();
            int numblocks = reader.ReadInt32();
            var blocks = new Kv6Block[numblocks];

            progress?.Report("Reading voxels");

            for (int i = 0; i < blocks.Length; ++i)
            {
                blocks[i].color = reader.ReadUInt32();
                blocks[i].zpos = (int) reader.ReadUInt16();
                reader.ReadUInt16(); // skip visFaces & lighting
                if (((i & 8191) == 0))
                {
                    progress?.Report((double)i / blocks.Length * 0.5);
                }
            }

            var xyoffset = new int[xsiz * ysiz];

            // skip xoffset
            for (int i = 0; i < xsiz; ++i)
            {
                reader.ReadInt32();
            }
            for (int i = 0; i < xyoffset.Length; ++i)
            {
                xyoffset[i] = (int) reader.ReadUInt16();
            }

            progress?.Report("Placing voxels");

            int pos = 0;
            var model = new VoxelModel(xsiz, ysiz, zsiz);
            for (int x = 0; x < xsiz; ++x) {
                for (int y = 0; y < ysiz; ++y) {
                    int sb = xyoffset[x * ysiz + y];
                    for (int i = 0; i < sb; ++i) {
                        var b = blocks[pos];
                        model[x, y, b.zpos] = b.color;
                        pos += 1;
                    }
                }

                progress?.Report((double)pos / blocks.Length * 0.5 + 0.5);
            }

            pivot = new Vector3(xpivot, ypivot, zpivot);

            return model;
        }
Esempio n. 13
0
		public static void DeserializeVoxelAreaData (byte[] bytes, VoxelArea target) {
#if !ASTAR_RECAST_CLASS_BASED_LINKED_LIST
			Ionic.Zip.ZipFile zip = new Ionic.Zip.ZipFile();
			System.IO.MemoryStream stream = new System.IO.MemoryStream();
			stream.Write(bytes,0,bytes.Length);
			stream.Position = 0;
			zip = Ionic.Zip.ZipFile.Read(stream);
			System.IO.MemoryStream stream2 = new System.IO.MemoryStream();
			
			zip["data"].Extract (stream2);
			stream2.Position = 0;
			System.IO.BinaryReader reader = new System.IO.BinaryReader(stream2);
			
			int width = reader.ReadInt32();
			int depth = reader.ReadInt32();
			if (target.width != width) throw new System.ArgumentException ("target VoxelArea has a different width than the data ("+target.width + " != " + width + ")");
			if (target.depth != depth) throw new System.ArgumentException ("target VoxelArea has a different depth than the data ("+target.depth + " != " + depth + ")");
			LinkedVoxelSpan[] spans = new LinkedVoxelSpan[reader.ReadInt32()];
			
			for (int i=0;i<spans.Length;i++) {
				spans[i].area = reader.ReadInt32();
				spans[i].bottom = reader.ReadUInt32();
				spans[i].next = reader.ReadInt32();
				spans[i].top = reader.ReadUInt32();
			}
			target.linkedSpans = spans;
#else
			throw new System.NotImplementedException ("This method only works with !ASTAR_RECAST_CLASS_BASED_LINKED_LIST");
#endif
		}
Esempio n. 14
0
 public override object Read(object target, Package package, System.IO.BinaryReader reader, long end)
 {
     return((PropertyFlag)reader.ReadUInt32());
 }
Esempio n. 15
0
 public override void ReadFrom(System.IO.BinaryReader reader)
 {
     base.ReadFrom(reader);
     FormatChecker.CheckExpression(() => BlockSize == ExactBlockSize);
     Item.CodePage = reader.ReadUInt32();
 }
Esempio n. 16
0
        public Simulator(string filename, string[] args, int memsize = 2048)
        {
            M = new uint[memsize];

            try
            {
                int j = 0;
                string ext = System.IO.Path.GetExtension(filename);
                if (ext == ".txt")
                {
                    string[] lines = System.IO.File.ReadAllLines(filename);
                    for (int i = 0; i < lines.Length; i++)
                    {
                        string s = lines[i].Trim();
                        if (s != "")
                            try
                            {
                                M[j++] = Convert.ToUInt32(lines[i], 16);
                            }
                            catch
                            {
                                throw new FormatException();
                            }
                    }
                    if (j == 0)
                        throw new ArgumentOutOfRangeException();
                }
                else if (ext == ".bin")
                {
                    System.IO.BinaryReader r = new System.IO.BinaryReader(System.IO.File.Open(filename, System.IO.FileMode.Open));
                    while (r.BaseStream.Position < r.BaseStream.Length)
                        M[j++] = r.ReadUInt32();
                }
                else
                {
                    throw new ArgumentException();
                }
                this.codelen = j;
                this.args = args;
            }
            catch (FormatException e)
            {
                Console.WriteLine("- FATAL: Bad source file contents.");
                e.Data[0] = -4;
                throw e;
            }
            catch (ArgumentOutOfRangeException e)
            {
                Console.WriteLine("- FATAL: Empty source file.");
                e.Data[0] = -3;
                throw e;
            }
            catch (ArgumentException e)
            {
                Console.WriteLine("- FATAL: Unknown file type.");
                e.Data[0] = -2;
                throw e;
            }
            catch (Exception e)
            {
                Console.WriteLine("- FATAL: Can't read source file.");
                e.Data[0] = -1;
                throw e;
            }
        }
Esempio n. 17
0
 public void Populate(int iOffset, bool useMemoryStream)
 {
     this.isNulledOutReflexive = false;
     System.IO.BinaryReader BR = new System.IO.BinaryReader(meta.MS);
     //set offsets
     BR.BaseStream.Position = iOffset + this.chunkOffset;
     this.offsetInMap = iOffset + this.chunkOffset;
     // If we need to read / save tag info directly to file...
     if (!useMemoryStream)
     {
         map.OpenMap(MapTypes.Internal);
         BR = map.BR;
         BR.BaseStream.Position = this.offsetInMap;
     }
     else
         this.offsetInMap += meta.offset;
     switch (ValueType)
     {
         case IFPIO.ObjectEnum.Short:
             {
                 this.Value = BR.ReadInt16();
                 break;
             }
         case IFPIO.ObjectEnum.Int:
             {
                 this.Value = BR.ReadInt32();
                 break;
             }
         case IFPIO.ObjectEnum.UShort:
             {
                 this.Value = BR.ReadUInt16();
                 break;
             }
         case IFPIO.ObjectEnum.UInt:
             {
                 this.Value = BR.ReadUInt32();
                 break;
             }
         case IFPIO.ObjectEnum.Float:
             {
                 this.Value = BR.ReadSingle();
                 break;
             }
         case IFPIO.ObjectEnum.Unknown:
             {
                 this.Value = BR.ReadSingle();
                 break;
             }
         case IFPIO.ObjectEnum.Byte:
             {
                 this.Value = BR.ReadByte();
                 break;
             }
     }
     // ...and then close the file once we are done!
     if (!useMemoryStream)
         map.CloseMap();
     if (this.ValueType != IFPIO.ObjectEnum.Unused)
         this.Controls[1].Text = this.Value.ToString();
 }
Esempio n. 18
0
        private TextureHandle _LoadTexture(string name)
        {
            var device = mDevice;
            Stormlib.MPQFile fl = new Stormlib.MPQFile(name);
            System.IO.BinaryReader reader = new System.IO.BinaryReader(fl);
            uint sig = reader.ReadUInt32();
            if (sig == 0x32504C42)
            {
                return LoadBlpTexture(device, reader);
            }
            try
            {
                var tex = SlimDX.Direct3D9.Texture.FromStream(device, fl);
                if (tex != null)
                    return new TextureHandle(tex);
            }
            catch (Exception)
            {
            }

            return null;
        }
Esempio n. 19
0
        private void readGameData()
        {
            textBox2.Text = path;
            if (roq != null)
                roq.stop();
            roq = null;
            if (vdx != null)
                vdx.stop();
            vdx = null;
            switch (game)
            {
                case GameID.T7G:
                    lblGame.Text = "The 7th Guest";

                    System.IO.DirectoryInfo DI = new System.IO.DirectoryInfo(path);
                    System.IO.FileInfo[] files = DI.GetFiles("*.rl");
                    this.gjdChooser.Items.Clear();

                    foreach (System.IO.FileInfo rl in files)
                    {
                        this.gjdChooser.Items.Add(rl.Name);
                    }

                    break;
                case GameID.T11H:
                    lblGame.Text = "The 11th Hour";
                    //ROQ roq = new ROQ(new System.IO.BinaryReader(new System.IO.FileStream(path + "\\media\\final_hr.rol", System.IO.FileMode.Open)));

                    this.gjdChooser.Items.Clear();
                    System.IO.BinaryReader idx = new System.IO.BinaryReader(new System.IO.FileStream(path + "\\groovie\\gjd.gjd", System.IO.FileMode.Open));
                    string name = "";
                    while (idx.BaseStream.Position < idx.BaseStream.Length)
                    {
                        if (idx.PeekChar() == 0x0A)
                        {
                            idx.ReadChar();
                            if (name.Length > 0)
                                this.gjdChooser.Items.Add(name.Substring(0, name.IndexOf(" ")));

                            name = "";
                        }
                        else
                            name += "" + idx.ReadChar();
                    }
                    idx.Close();
                    V2_RL = new List<GJD.RLData>[this.gjdChooser.Items.Count];
                    for (int i = 0; i < V2_RL.Length; i++)
                        V2_RL[i] = new List<GJD.RLData>();

                    this.gjdChooser.Items.Add("Icons");

                    idx = new System.IO.BinaryReader(new System.IO.FileStream(path + "\\groovie\\dir.rl", System.IO.FileMode.Open));
                    uint ctr = 0;
                    while (idx.BaseStream.Position < idx.BaseStream.Length)
                    {
                        // Get RL content
                        GJD.RLData rl = new GJD.RLData();
                        idx.ReadUInt32();
                        rl.offset = idx.ReadUInt32();
                        rl.length = idx.ReadUInt32();
                        rl.number = ctr;
                        ctr++;
                        ushort target = idx.ReadUInt16();
                        byte[] filename;
                        filename = idx.ReadBytes(12);
                        rl.filename = System.Text.Encoding.ASCII.GetString(filename).Trim();
                        idx.ReadBytes(6);
                        V2_RL[target].Add(rl);
                    }

                    break;
                default:
                    lblGame.Text = "None";
                    break;
            }
        }
Esempio n. 20
0
        void TestSHRGBEEncoding()
        {
            float3[]	coeffs = null;

            System.IO.FileInfo	coeffsFileName = new System.IO.FileInfo( "SHCoeffs.sh3" );
            using ( System.IO.FileStream S = coeffsFileName.OpenRead() )
                using ( System.IO.BinaryReader R = new System.IO.BinaryReader( S ) ) {
                    uint	coeffsCount = R.ReadUInt32();
                    coeffs = new float3[coeffsCount * 9];
                    for ( int i=0; i < 9*coeffsCount; i++ ) {
                        coeffs[i] = new float3( R.ReadSingle(), R.ReadSingle(), R.ReadSingle() );

            // The exponent bias allows us to support up to 512 in luminance!
            //coeffs[i] *= 5.0f;

                    }
                }

            uint	test1_packed = EncodeRGBE( new float3( 1, 0, 1.5f ) );
            float3	test1_unpacked = DecodeRGBE( test1_packed );

            //			float3	coeffMin = new float3( float.MaxValue, float.MaxValue, float.MaxValue );
            float3	coeffMax = new float3( -float.MaxValue, -float.MaxValue, -float.MaxValue );
            float3	coeffMinAbs = new float3( float.MaxValue, float.MaxValue, float.MaxValue );
            int		coeffsWithDifferentSignsInRGBCount = 0;
            for ( int i=0; i < coeffs.Length; i++ ) {
                float3	coeff = coeffs[i];
                float3	absCoeff = new float3( Math.Abs( coeff.x ), Math.Abs( coeff.y ), Math.Abs( coeff.z ) );

                if ( coeff.x * coeff.y < 0.0f || coeff.x * coeff.z < 0.0f || coeff.y * coeff.z < 0.0f )
                    coeffsWithDifferentSignsInRGBCount++;

            //				coeffMin.Min( coeff );
                coeffMax.Max( absCoeff );
                if ( absCoeff.x > 0.0f ) coeffMinAbs.x = Math.Min( coeffMinAbs.x, absCoeff.x );
                if ( absCoeff.y > 0.0f ) coeffMinAbs.y = Math.Min( coeffMinAbs.y, absCoeff.y );
                if ( absCoeff.z > 0.0f ) coeffMinAbs.z = Math.Min( coeffMinAbs.z, absCoeff.z );
            }

            double	expMin = Math.Min( Math.Min( Math.Log( coeffMinAbs.x ) / Math.Log(2), Math.Log( coeffMinAbs.y ) / Math.Log(2) ), Math.Log( coeffMinAbs.z ) / Math.Log(2) );
            double	expMax = Math.Max( Math.Max( Math.Log( coeffMax.x ) / Math.Log(2), Math.Log( coeffMax.y ) / Math.Log(2) ), Math.Log( coeffMax.z ) / Math.Log(2) );

            // Measure discrepancies after RGBE encoding
            // 			float3	errorAbsMin = new float3( +float.MaxValue, +float.MaxValue, +float.MaxValue );
            // 			float3	errorAbsMax = new float3( -float.MaxValue, -float.MaxValue, -float.MaxValue );
            float3	errorRelMin = new float3( +float.MaxValue, +float.MaxValue, +float.MaxValue );
            float3	errorRelMax = new float3( -float.MaxValue, -float.MaxValue, -float.MaxValue );
            int		minExponent = +int.MaxValue, maxExponent = -int.MaxValue;
            int		largeRelativeErrorsCount = 0;
            for ( int i=0; i < coeffs.Length; i++ ) {
                float3	originalRGB = coeffs[i];
                uint	RGBE = EncodeRGBE( originalRGB );
                float3	decodedRGB = DecodeRGBE( RGBE );

                // Compute absolute error
            // 				float3	delta = decodedRGB - originalRGB;
            // 				float3	distanceFromOriginal = new float3( Math.Abs( delta.x ), Math.Abs( delta.y ), Math.Abs( delta.z ) );
            // 				errorAbsMin.Min( distanceFromOriginal );
            // 				errorAbsMax.Max( distanceFromOriginal );

                // Compute relative error
                float3	errorRel = new float3( Math.Abs( originalRGB.x ) > 0.0f ? Math.Abs( decodedRGB.x / originalRGB.x - 1.0f ) : 0.0f, Math.Abs( originalRGB.y ) > 0.0f ? Math.Abs( decodedRGB.y / originalRGB.y - 1.0f ) : 0.0f, Math.Abs( originalRGB.z ) > 0.0f ? Math.Abs( decodedRGB.z / originalRGB.z - 1.0f ) : 0.0f );

                // Scale the relative error by the magnitude of each component as compared to the maximum component
                // This way, if we happen to have a "large" relative error on a component that is super small compared to the component with maximum amplitude then we can safely drop that small component (it's insignificant compared to the largest contribution)
                float	maxComponent = Math.Max( Math.Max( Math.Abs( originalRGB.x ), Math.Abs( originalRGB.y ) ), Math.Abs( originalRGB.z ) );
                float3	magnitudeScale = maxComponent > 0.0f ? new float3( Math.Abs( originalRGB.x ) / maxComponent, Math.Abs( originalRGB.y ) / maxComponent, Math.Abs( originalRGB.z ) / maxComponent ) : float3.Zero;
                errorRel *= magnitudeScale;

                // Don't account for dernomalization
            // 				if ( decodedRGB.x == 0.0 && originalRGB.x != 0.0f ) errorRel.x = 0.0f;
            // 				if ( decodedRGB.y == 0.0 && originalRGB.y != 0.0f ) errorRel.y = 0.0f;
            // 				if ( decodedRGB.z == 0.0 && originalRGB.z != 0.0f ) errorRel.z = 0.0f;

                const float	errorThreshold = 0.2f;
                if ( Math.Abs( errorRel.x ) > errorThreshold || Math.Abs( errorRel.y ) > errorThreshold || Math.Abs( errorRel.z ) > errorThreshold )
                    largeRelativeErrorsCount++;
                errorRelMin.Min( errorRel );
                errorRelMax.Max( errorRel );

                int		exp = (int) ((RGBE >> 24) & 31) - EXPONENT_BIAS;
                minExponent = Math.Min( minExponent, exp );
                maxExponent = Math.Max( maxExponent, exp );
            }
        }
Esempio n. 21
0
        void TestSHRGBEEncoding()
        {
            float3[] coeffs = null;

            System.IO.FileInfo coeffsFileName = new System.IO.FileInfo("SHCoeffs.sh3");
            using (System.IO.FileStream S = coeffsFileName.OpenRead())
                using (System.IO.BinaryReader R = new System.IO.BinaryReader(S)) {
                    uint coeffsCount = R.ReadUInt32();
                    coeffs = new float3[coeffsCount * 9];
                    for (int i = 0; i < 9 * coeffsCount; i++)
                    {
                        coeffs[i] = new float3(R.ReadSingle(), R.ReadSingle(), R.ReadSingle());

// The exponent bias allows us to support up to 512 in luminance!
//coeffs[i] *= 5.0f;
                    }
                }

            uint   test1_packed   = EncodeRGBE(new float3(1, 0, 1.5f));
            float3 test1_unpacked = DecodeRGBE(test1_packed);

//			float3	coeffMin = new float3( float.MaxValue, float.MaxValue, float.MaxValue );
            float3 coeffMax    = new float3(-float.MaxValue, -float.MaxValue, -float.MaxValue);
            float3 coeffMinAbs = new float3(float.MaxValue, float.MaxValue, float.MaxValue);
            int    coeffsWithDifferentSignsInRGBCount = 0;

            for (int i = 0; i < coeffs.Length; i++)
            {
                float3 coeff    = coeffs[i];
                float3 absCoeff = new float3(Math.Abs(coeff.x), Math.Abs(coeff.y), Math.Abs(coeff.z));

                if (coeff.x * coeff.y < 0.0f || coeff.x * coeff.z < 0.0f || coeff.y * coeff.z < 0.0f)
                {
                    coeffsWithDifferentSignsInRGBCount++;
                }

//				coeffMin.Min( coeff );
                coeffMax.Max(absCoeff);
                if (absCoeff.x > 0.0f)
                {
                    coeffMinAbs.x = Math.Min(coeffMinAbs.x, absCoeff.x);
                }
                if (absCoeff.y > 0.0f)
                {
                    coeffMinAbs.y = Math.Min(coeffMinAbs.y, absCoeff.y);
                }
                if (absCoeff.z > 0.0f)
                {
                    coeffMinAbs.z = Math.Min(coeffMinAbs.z, absCoeff.z);
                }
            }

            double expMin = Math.Min(Math.Min(Math.Log(coeffMinAbs.x) / Math.Log(2), Math.Log(coeffMinAbs.y) / Math.Log(2)), Math.Log(coeffMinAbs.z) / Math.Log(2));
            double expMax = Math.Max(Math.Max(Math.Log(coeffMax.x) / Math.Log(2), Math.Log(coeffMax.y) / Math.Log(2)), Math.Log(coeffMax.z) / Math.Log(2));

            // Measure discrepancies after RGBE encoding
//          float3	errorAbsMin = new float3( +float.MaxValue, +float.MaxValue, +float.MaxValue );
//          float3	errorAbsMax = new float3( -float.MaxValue, -float.MaxValue, -float.MaxValue );
            float3 errorRelMin = new float3(+float.MaxValue, +float.MaxValue, +float.MaxValue);
            float3 errorRelMax = new float3(-float.MaxValue, -float.MaxValue, -float.MaxValue);
            int    minExponent = +int.MaxValue, maxExponent = -int.MaxValue;
            int    largeRelativeErrorsCount = 0;

            for (int i = 0; i < coeffs.Length; i++)
            {
                float3 originalRGB = coeffs[i];
                uint   RGBE        = EncodeRGBE(originalRGB);
                float3 decodedRGB  = DecodeRGBE(RGBE);

                // Compute absolute error
//              float3	delta = decodedRGB - originalRGB;
//              float3	distanceFromOriginal = new float3( Math.Abs( delta.x ), Math.Abs( delta.y ), Math.Abs( delta.z ) );
//              errorAbsMin.Min( distanceFromOriginal );
//              errorAbsMax.Max( distanceFromOriginal );

                // Compute relative error
                float3 errorRel = new float3(Math.Abs(originalRGB.x) > 0.0f ? Math.Abs(decodedRGB.x / originalRGB.x - 1.0f) : 0.0f, Math.Abs(originalRGB.y) > 0.0f ? Math.Abs(decodedRGB.y / originalRGB.y - 1.0f) : 0.0f, Math.Abs(originalRGB.z) > 0.0f ? Math.Abs(decodedRGB.z / originalRGB.z - 1.0f) : 0.0f);

                // Scale the relative error by the magnitude of each component as compared to the maximum component
                // This way, if we happen to have a "large" relative error on a component that is super small compared to the component with maximum amplitude then we can safely drop that small component (it's insignificant compared to the largest contribution)
                float  maxComponent   = Math.Max(Math.Max(Math.Abs(originalRGB.x), Math.Abs(originalRGB.y)), Math.Abs(originalRGB.z));
                float3 magnitudeScale = maxComponent > 0.0f ? new float3(Math.Abs(originalRGB.x) / maxComponent, Math.Abs(originalRGB.y) / maxComponent, Math.Abs(originalRGB.z) / maxComponent) : float3.Zero;
                errorRel *= magnitudeScale;

                // Don't account for dernomalization
//              if ( decodedRGB.x == 0.0 && originalRGB.x != 0.0f ) errorRel.x = 0.0f;
//              if ( decodedRGB.y == 0.0 && originalRGB.y != 0.0f ) errorRel.y = 0.0f;
//              if ( decodedRGB.z == 0.0 && originalRGB.z != 0.0f ) errorRel.z = 0.0f;

                const float errorThreshold = 0.2f;
                if (Math.Abs(errorRel.x) > errorThreshold || Math.Abs(errorRel.y) > errorThreshold || Math.Abs(errorRel.z) > errorThreshold)
                {
                    largeRelativeErrorsCount++;
                }
                errorRelMin.Min(errorRel);
                errorRelMax.Max(errorRel);

                int exp = (int)((RGBE >> 24) & 31) - EXPONENT_BIAS;
                minExponent = Math.Min(minExponent, exp);
                maxExponent = Math.Max(maxExponent, exp);
            }
        }
        public override void Load(ref System.IO.FileStream File, ref System.IO.BinaryReader Reader)
        {
            File.Position = Offset + Base;
            if (File.Position < File.Length && Size > 0)
            {
                Header      = Reader.ReadUInt32();
                Records     = (int)Reader.ReadUInt32();
                ContentSize = Reader.ReadUInt32();
                Array.Resize(ref _Item, Records);
                for (int i = 0; i <= Records - 1; i++)
                {
                    uint ElementOffset = Reader.ReadUInt32();
                    uint ElementSize   = Reader.ReadUInt32();
                    uint ElementID     = Reader.ReadUInt32();
                    uint Pos           = (uint)File.Position;
                    switch (ElementID)
                    {
                    case 1:
                    {
                        Behaviors Insts = new Behaviors();
                        Insts.Offset = ElementOffset;
                        Insts.Base   = Offset + Base;
                        Insts.Size   = ElementSize;
                        Insts.ID     = ElementID;
                        Insts.Load(ref File, ref Reader);
                        _Item[i] = Insts;
                        break;
                    }

                    case 2:
                    {
                        FuckingShits Insts = new FuckingShits();
                        Insts.Offset = ElementOffset;
                        Insts.Base   = Offset + Base;
                        Insts.Size   = ElementSize;
                        Insts.ID     = ElementID;
                        Insts.Load(ref File, ref Reader);
                        _Item[i] = Insts;
                        break;
                    }

                    case 3:
                    {
                        Positions Insts = new Positions();
                        Insts.Offset = ElementOffset;
                        Insts.Base   = Offset + Base;
                        Insts.Size   = ElementSize;
                        Insts.ID     = ElementID;
                        Insts.Load(ref File, ref Reader);
                        _Item[i] = Insts;
                        break;
                    }

                    case 4:
                    {
                        Paths Insts = new Paths();
                        Insts.Offset = ElementOffset;
                        Insts.Base   = Offset + Base;
                        Insts.Size   = ElementSize;
                        Insts.ID     = ElementID;
                        Insts.Load(ref File, ref Reader);
                        _Item[i] = Insts;
                        break;
                    }

                    case 5:
                    {
                        SurfaceBehaviours Insts = new SurfaceBehaviours();
                        Insts.Offset = ElementOffset;
                        Insts.Base   = Offset + Base;
                        Insts.Size   = ElementSize;
                        Insts.ID     = ElementID;
                        Insts.Load(ref File, ref Reader);
                        _Item[i] = Insts;
                        break;
                    }

                    case 6:
                    {
                        Instances Insts = new Instances();
                        Insts.Offset = ElementOffset;
                        Insts.Base   = Offset + Base;
                        Insts.Size   = ElementSize;
                        Insts.ID     = ElementID;
                        Insts.Load(ref File, ref Reader);
                        _Item[i] = Insts;
                        break;
                    }

                    case 7:
                    {
                        Triggers Trigs = new Triggers();
                        Trigs.Offset = ElementOffset;
                        Trigs.Base   = Offset + Base;
                        Trigs.Size   = ElementSize;
                        Trigs.ID     = ElementID;
                        Trigs.Load(ref File, ref Reader);
                        _Item[i] = Trigs;
                        break;
                    }

                    default:
                    {
                        BaseSection BS = new BaseSection();
                        BS.Offset = ElementOffset;
                        BS.Base   = Offset + Base;
                        BS.Size   = ElementSize;
                        BS.ID     = ElementID;
                        BS.Load(ref File, ref Reader);
                        _Item[i] = BS;
                        break;
                    }
                    }
                    File.Position = Pos;
                }
            }
        }
Esempio n. 23
0
        static UInt32 GetSerial(byte[] bytes)
        {
            using (System.IO.MemoryStream stream = new System.IO.MemoryStream(bytes, 8, 4))
            {
                System.IO.BinaryReader reader = new System.IO.BinaryReader(stream);

                return reader.ReadUInt32();
            }
        }
Esempio n. 24
0
        public static Boolean LoadImageFromFile(ref Texture2D tex, String fileNamePath)
        {
            Boolean blnReturn = false;
            bool    dds       = false;

            try
            {
                string path = fileNamePath;
                if (!System.IO.File.Exists(fileNamePath))
                {
                    // Look for the file with an appended suffix.
                    for (int i = 0; i < imgSuffixes.Length; i++)
                    {
                        if (System.IO.File.Exists(fileNamePath + imgSuffixes[i]))
                        {
                            path = fileNamePath + imgSuffixes[i];
                            dds  = imgSuffixes[i] == ".dds" || imgSuffixes[i] == ".DDS";
                            break;
                        }
                    }
                }

                //File Exists check
                if (System.IO.File.Exists(path))
                {
                    try
                    {
                        if (dds)
                        {
                            Log.Info("LoadIimageFromFile, dds");
                            byte[] bytes = System.IO.File.ReadAllBytes(path);


                            System.IO.BinaryReader binaryReader = new System.IO.BinaryReader(new System.IO.MemoryStream(bytes));
                            uint num = binaryReader.ReadUInt32();

                            if (num != DDSValues.uintMagic)
                            {
                                UnityEngine.Debug.LogError("DDS: File is not a DDS format file!");
                                return(false);
                            }
                            DDSHeader ddSHeader = new DDSHeader(binaryReader);

                            TextureFormat tf = TextureFormat.Alpha8;
                            if (ddSHeader.ddspf.dwFourCC == DDSValues.uintDXT1)
                            {
                                tf = TextureFormat.DXT1;
                            }
                            if (ddSHeader.ddspf.dwFourCC == DDSValues.uintDXT5)
                            {
                                tf = TextureFormat.DXT5;
                            }
                            if (tf == TextureFormat.Alpha8)
                            {
                                return(false);
                            }


                            tex = LoadTextureDXT(bytes, tf);
                        }
                        else
                        {
                            tex.LoadImage(System.IO.File.ReadAllBytes(path));
                        }
                        blnReturn = true;
                    }
                    catch (Exception ex)
                    {
                        Log.Error("Failed to load the texture: " + path);
                        Log.Error("Error: " + ex.Message);
                    }
                }
                else
                {
                    Log.Debug(ConfigInfo.debugMode, "Cannot find texture to load from file:" + fileNamePath);
                }
            }
            catch (Exception ex)
            {
                Log.Error("Failed to load (are you missing a file):" + fileNamePath);
                Log.Error(ex.Message);
            }
            return(blnReturn);
        }
Esempio n. 25
0
        private void readMeshFrame(System.IO.BinaryReader reader, uint frameNum, uint meshIndex, uint sectionLength)
        {
            long end        = reader.BaseStream.Position + sectionLength;
            uint frameIndex = frameNum * _numMeshes + meshIndex;

            while (reader.BaseStream.Position < end)
            {
                ActSubsectionHeader subsection;
                subsection.Type     = reader.ReadByte();
                subsection.DataSize = reader.ReadUInt32();

                if (subsection.Type == (byte)ActSubsectionType.Group)
                {
                    ushort groupIndex  = reader.ReadUInt16();
                    ushort numVertices = reader.ReadUInt16();

                    float[] vertices = new float[numVertices * 3];
                    for (ushort j = 0; j < numVertices; j++)
                    {
                        vertices[j * 3 + 0] = reader.ReadSingle();
                        vertices[j * 3 + 1] = reader.ReadSingle();
                        vertices[j * 3 + 2] = reader.ReadSingle();
                    }

                    _frames[frameIndex].Active = true;
                    if (_frames[frameIndex].Vertices == null)
                    {
                        _frames[frameIndex].Vertices = new List <FrameSectionVertices>();
                    }

                    FrameSectionVertices sectionVertices;
                    sectionVertices.SectionIndex = groupIndex;
                    sectionVertices.Vertices     = vertices;
                    _frames[frameIndex].Vertices.Add(sectionVertices);
                }
                else if (subsection.Type == (byte)ActSubsectionType.DeltaGroup)
                {
                    ushort groupIndex  = reader.ReadUInt16();
                    ushort numVertices = reader.ReadUInt16();

                    byte[] bitfield = reader.ReadBytes(numVertices / 4 + 1);

                    float[] vertices = new float[numVertices * 3];
                    for (ushort j = 0; j < numVertices; j++)
                    {
                        int type = getDeltaType(j, bitfield);
                        if (type == (int)VertexChangeType.None)
                        {
                            // nothing
                        }
                        else if (type == (int)VertexChangeType.Short)
                        {
                            vertices[j * 3 + 0] = uncompress(reader.ReadByte());
                            vertices[j * 3 + 1] = uncompress(reader.ReadByte());
                            vertices[j * 3 + 2] = uncompress(reader.ReadByte());
                        }
                        else if (type == (int)VertexChangeType.Long)
                        {
                            vertices[j * 3 + 0] = uncompress(reader.ReadUInt16());
                            vertices[j * 3 + 1] = uncompress(reader.ReadUInt16());
                            vertices[j * 3 + 2] = uncompress(reader.ReadUInt16());
                        }
                        else if (type == (int)VertexChangeType.Absolute)
                        {
                            vertices[j * 3 + 0] = reader.ReadSingle();
                            vertices[j * 3 + 1] = reader.ReadSingle();
                            vertices[j * 3 + 2] = reader.ReadSingle();
                        }
                    }

                    convertDeltaVerticesToAbsolute(vertices, (int)meshIndex, groupIndex, (int)frameNum);

                    _frames[frameIndex].Active = true;
                    if (_frames[frameIndex].Vertices == null)
                    {
                        _frames[frameIndex].Vertices = new List <FrameSectionVertices>();
                    }

                    FrameSectionVertices sectionVertices;
                    sectionVertices.SectionIndex = groupIndex;
                    sectionVertices.Vertices     = vertices;
                    _frames[frameIndex].Vertices.Add(sectionVertices);
                }
                else if (subsection.Type == (byte)ActSubsectionType.Transform)
                {
                    // read the 4x3 transform matrix
                    float[] transform = new float[4 * 3];
                    transform[0] = reader.ReadSingle();
                    transform[1] = reader.ReadSingle();
                    transform[2] = reader.ReadSingle();

                    transform[3] = reader.ReadSingle();
                    transform[4] = reader.ReadSingle();
                    transform[5] = reader.ReadSingle();

                    transform[6] = reader.ReadSingle();
                    transform[7] = reader.ReadSingle();
                    transform[8] = reader.ReadSingle();

                    transform[9]  = reader.ReadSingle();
                    transform[10] = reader.ReadSingle();
                    transform[11] = reader.ReadSingle();

                    _frames[frameIndex].Active    = true;
                    _frames[frameIndex].Transform = new FrameTransformation(transform);
                }
                else if (subsection.Type == (byte)ActSubsectionType.BoundingBox)
                {
                    _frames[frameIndex].Active      = true;
                    _frames[frameIndex].BoundingBox = new float[6];

                    // read the bounding box
                    _frames[frameIndex].BoundingBox[0] = reader.ReadSingle();
                    _frames[frameIndex].BoundingBox[1] = reader.ReadSingle();
                    _frames[frameIndex].BoundingBox[2] = reader.ReadSingle();
                    _frames[frameIndex].BoundingBox[3] = reader.ReadSingle();
                    _frames[frameIndex].BoundingBox[4] = reader.ReadSingle();
                    _frames[frameIndex].BoundingBox[5] = reader.ReadSingle();
                }
                else
                {
                    throw new Exception("Invalid subsection type found");
                }
            }
        }
Esempio n. 26
0
 /// <summary>
 /// Unserializes a BinaryStream into the Attributes of this Instance
 /// </summary>
 /// <param name="reader">The Stream that contains the FileData</param>
 public override void Unserialize(System.IO.BinaryReader reader)
 {
     version = reader.ReadUInt32();
 }
Esempio n. 27
0
        public void Populate(int iOffset, bool useMemoryStream)
        {
            this.isNulledOutReflexive = false;
            System.IO.BinaryReader BR = new System.IO.BinaryReader(meta.MS);
            //set offsets
            BR.BaseStream.Position = iOffset + this.chunkOffset;
            this.offsetInMap = iOffset + this.chunkOffset;
            // If we need to read / save tag info directly to file...
            if (!useMemoryStream)
            {
                map.OpenMap(MapTypes.Internal);
                BR = map.BR;
                BR.BaseStream.Position = this.offsetInMap;
            }
            else
                this.offsetInMap += meta.offset;

            //Decide how big the bitmask is
            switch (this.bitCount)
            {
                case 8:
                    {
                        this.value = BR.ReadByte();
                        break;
                    }
                case 16:
                    {
                        this.value = BR.ReadUInt16();
                        break;
                    }
                case 32:
                    {
                        this.value = BR.ReadUInt32();
                        break;
                    }
            }
            // ...and then close the file once we are done!
            if (!useMemoryStream)
                map.CloseMap();
            //convert this.value (an object) into a bool array, then update the checkboxes with that bool array
            BitsToBool();
            BoolsToControls();
        }
            /// <summary>
            /// reads a file and populates the map receiver instance.
            /// </summary>
            /// <returns></returns>
            public static bool Read_pachm(out Mapping.PachMapReceiver[] Map)
            {
                System.Windows.Forms.OpenFileDialog of = new System.Windows.Forms.OpenFileDialog();
                of.DefaultExt = ".pachm";
                of.AddExtension = true;
                of.Filter = "Pachyderm Mapping Data File (*.pachm)|*.pachm|" + "All Files|";
                if (of.ShowDialog() != System.Windows.Forms.DialogResult.OK)
                {
                    Map = null;
                    return false;
                }
                System.IO.BinaryReader sr = new System.IO.BinaryReader(System.IO.File.Open(of.FileName, System.IO.FileMode.Open));
                //1. Write calculation type. (string)
                string CalcType = sr.ReadString();
                if (CalcType != "Type;Map_Data" && CalcType != "Type;Map_Data_NoDir") throw new Exception("Map Data File Expected");
                bool Directional = (CalcType == "Type;Map_Data");

                //2. Write the number of samples in each histogram. (int)
                int SampleCT = (int)sr.ReadUInt32();
                //3. Write the sample rate. (int)
                int SampleRate = (int)sr.ReadUInt32();
                //4. Write the number of Receivers (int)
                int Rec_CT = (int)sr.ReadUInt32();
                //4.5 Write the version number
                double version = 1.1;
                double rev = 0;
                //5. Announce that the following data pertains to the form of the analysis mesh. (string)
                int s_ct=1;
                Rhino.Geometry.Mesh Map_Mesh = new Rhino.Geometry.Mesh();
                Map = new Mapping.PachMapReceiver[1];
                //Map[0] = new Pach_Map_Receiver();
                //double[] Rho_C = null;
                double[] delay;

                do
                {
                    switch (sr.ReadString())
                    {
                        case "Version":
                            //Pach1.7 = Versioning functionality added.
                            string v = sr.ReadString();
                            version = double.Parse(v.Substring(0, 3));
                            rev = int.Parse(v.Split(new char[1] { '.' })[3]);
                            break;
                        case "Mesh Information":
                            //6. Announce Mesh Vertices (string)
                            //Write the number of vertices & faces (int) (int)
                            if (sr.ReadString() != "Mesh Vertices") throw new Exception("Mesh Vertices Expected");

                            int VC = (int)sr.ReadUInt32();
                            int FC = (int)sr.ReadUInt32();
                            for (int i = 0; i < VC; i++)
                            {
                                //Write Vertex: (double) (double) (double)
                                Map_Mesh.Vertices.Add(new Rhino.Geometry.Point3d(sr.ReadSingle(), sr.ReadSingle(), sr.ReadSingle()));
                            }

                            //7. Announce Mesh Faces (string)
                            if (sr.ReadString() != "Mesh Faces") throw new Exception("Mesh Faces Expected");

                            for (int i = 0; i < FC; i++)
                            {
                                // Write mesh vertex indices: (int) (int) (int) (int)
                                Map_Mesh.Faces.AddFace((int)sr.ReadUInt32(), (int)sr.ReadUInt32(), (int)sr.ReadUInt32(), (int)sr.ReadUInt32());
                            }
                            break;
                        case "Sources":
                            //7.5: Announce the number of sources.
                            s_ct = sr.ReadInt32();
                            delay = new double[s_ct];
                            Map = new Mapping.PachMapReceiver[s_ct];
                            //7.5a Announce the type of source.

                            for (int s = 0; s < s_ct; s++)
                            {
                                Map[s] = new Mapping.PachMapReceiver();
                                Map[s].CutOffTime = (double)SampleCT / (double)SampleRate;
                                Map[s].SampleCT = SampleCT;
                                Map[s].SampleRate = SampleRate;
                                Map[s].Map_Mesh = Map_Mesh;
                                Map[s].Rec_List = new Mapping.PachMapReceiver.Map_Receiver[Rec_CT];
                                Map[s].SrcType = sr.ReadString();
                                //4.4 Source delay (ms)
                                if (version > 2.0 || (version == 2.0 && rev >= 1))
                                {
                                    delay[s] = sr.ReadDouble();
                                }
                            }
                            break;
                        case "SourceswLoc":
                            //7.5: Announce the number of sources.
                            s_ct = sr.ReadInt32();
                            delay = new double[s_ct];
                            Map = new Mapping.PachMapReceiver[s_ct];
                            //7.5a Announce the type of source.

                            for (int s = 0; s < s_ct; s++)
                            {
                                Map[s] = new Mapping.PachMapReceiver();
                                Map[s].CutOffTime = (double)SampleCT / (double)SampleRate * 1000;
                                Map[s].SampleCT = SampleCT;
                                Map[s].SampleRate = SampleRate;
                                Map[s].Map_Mesh = Map_Mesh;
                                Map[s].Rec_List = new Mapping.PachMapReceiver.Map_Receiver[Rec_CT];
                                Map[s].Src = new Rhino.Geometry.Point3d(sr.ReadDouble(), sr.ReadDouble(), sr.ReadDouble());
                                Map[s].SrcType = sr.ReadString();
                                //4.4 Source delay (ms)
                                if (version > 2.0 || (version == 2.0 && rev >= 1))
                                {
                                    delay[s] = sr.ReadDouble();
                                }
                            }
                            break;
                        case "Receiver Hit Data":
                            if (Map[0] == null)
                            {
                                Map = new Mapping.PachMapReceiver[1];
                                Map[0] = new Mapping.PachMapReceiver();
                                Map[0].CutOffTime = (double)SampleCT / (double)SampleRate;
                                Map[0].SampleRate = SampleRate;
                                Map[0].SampleCT = SampleCT;
                                Map[0].Map_Mesh = Map_Mesh;
                                Map[0].Rec_List = new Mapping.PachMapReceiver.Map_Receiver[Rec_CT];
                                Map[0].SrcType = "Geodesic";
                            }

                            //8. Announce that the following data pertains to the receiver histograms (string)
                            //8a. Announce whether or not data is linked to vertices rather than faces (bool)
                            bool vert_Receiver = sr.ReadBoolean();
                            for (int s = 0; s < s_ct; s++)
                            {
                                Map[s].Rec_Vertex = vert_Receiver;
                                for (int i = 0; i < Map[s].Rec_List.Length; i++)
                                {
                                    //for version 1.7 and up, write direct sound arrival time.
                                    //Write Receiver Index (int)
                                    int j = (int)sr.ReadUInt32();
                                    //Write Direct Sound Arrival Time.
                                    double Direct_Time;
                                    if (version >= 1.7) Direct_Time = sr.ReadDouble(); else Direct_Time = (Utilities.PachTools.RPttoHPt(Map[s].Src) - Map[s].Rec_List[i].H_Origin).Length() / 343f;
                                    //Write Impedance of Air
                                    double Rho_C = version >= 2.0 ? sr.ReadDouble() : 400;

                                    if (vert_Receiver)
                                    {
                                        Map[s].Rec_List[i] = new Mapping.PachMapReceiver.Map_Receiver(Map_Mesh.Vertices[i], new Rhino.Geometry.Point3f((float)Map[s].Src.X, (float)Map[s].Src.Y, (float)Map[s].Src.Z), Direct_Time, Rho_C, i, SampleRate, SampleCT, Directional);
                                    }
                                    else
                                    {
                                        Rhino.Geometry.Point3d RecLoc = Map_Mesh.Faces.GetFaceCenter(i);
                                        Map[s].Rec_List[i] = new Mapping.PachMapReceiver.Map_Receiver(new Rhino.Geometry.Point3f((float)RecLoc.X, (float)RecLoc.Y, (float)RecLoc.Z), new Rhino.Geometry.Point3f((float)Map[s].Src.X, (float)Map[s].Src.Y, (float)Map[s].Src.Z), Direct_Time, Rho_C, i, SampleRate, SampleCT, Directional);
                                    }

                                    for (int Octave = 0; Octave < 8; Octave++)
                                    {
                                        //Write Octave (int)
                                        int Oct_out = (int)sr.ReadUInt32();
                                        if (Oct_out != Octave) throw new Exception(string.Format("Octave {0} Expected", Octave));
                                        double[] Hist = Map[s].Rec_List[i].GetEnergyHistogram(Octave);
                                        if (Directional)
                                        {
                                            if (version < 1.7)
                                            {
                                                for (int e = 0; e < SampleCT; e++)
                                                    Map[s].Rec_List[i].Combine_Sample(e, sr.ReadDouble(), new Hare.Geometry.Vector(sr.ReadSingle(), sr.ReadSingle(), sr.ReadSingle()), new Hare.Geometry.Vector(sr.ReadSingle(), sr.ReadSingle(), sr.ReadSingle()), Octave);
                                            }
                                            else
                                            {
                                                for (int e = 0; e < SampleCT; e++)
                                                    Map[s].Rec_List[i].Combine_Sample(e, sr.ReadDouble(), new Hare.Geometry.Vector(sr.ReadSingle(), sr.ReadSingle(), sr.ReadSingle()), new Hare.Geometry.Vector(sr.ReadSingle(), sr.ReadSingle(), sr.ReadSingle()), Octave);
                                            }
                                        }
                                        else
                                        {
                                            if (version < 1.7)
                                            {
                                                for (int e = 0; e < SampleCT; e++)
                                                    Map[s].Rec_List[i].Combine_Sample(e, sr.ReadDouble(), new Hare.Geometry.Vector(0, 0, 0), new Hare.Geometry.Vector(0, 0, 0), Octave);
                                            }
                                            else
                                            {
                                                for (int e = 0; e < SampleCT; e++)
                                                    Map[s].Rec_List[i].Combine_Sample(e, sr.ReadDouble(), new Hare.Geometry.Vector(0, 0, 0), new Hare.Geometry.Vector(0,0,0), Octave);
                                            }
                                        }
                                    }
                                    if (sr.ReadString() != "End_Receiver_Hits") throw new Exception("End of Receiver Hits Expected");
                                }
                            }
                            break;
                        case "End_of_File":
                            sr.Close();
                            return true;
                    }
                } while (true);
                throw new Exception("Unsuccessful Read");
            }
Esempio n. 29
0
        static void Main(string[] args)
        {
            var socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            socket.Bind(new System.Net.IPEndPoint(System.Net.IPAddress.Any, 7001));
            socket.Listen(10);
            for (;;)
            {
                var client = socket.Accept();
                Console.WriteLine("connected..");
                var thread = new System.Threading.Thread(() =>
                  {
                      try
                      {
                          var clientReader = new System.IO.BinaryReader(new NetworkStream(client));
                          for (;;)
                          {
                              if (client.Poll(1, SelectMode.SelectRead) && client.Available == 0)
                              {
                                  Console.WriteLine("disconnected..");
                                  break;
                              }
                              if (client.Available > 0)
                              {
                                  var msgSize = clientReader.ReadInt32();
                                  var message = clientReader.ReadBytes(msgSize);
                                  var messageReader = new System.IO.BinaryReader(new System.IO.MemoryStream(message));
                                  var msgKind = messageReader.ReadInt32();
                                  Console.WriteLine("message: kind:{0}, len:{1}", msgKind, message.Length);
                                  switch (msgKind)
                                  {
                                      case 0:
                                          {
                                              var activeProcessId = GetWindowProcessId(GetForegroundWindow());
                                              if (activeProcessId == null)
                                                  break;
                                              if (Process.GetProcessById(activeProcessId.Value)?.ProcessName != "ZumasRevenge")
                                                  break;

                                              var flags = messageReader.ReadUInt32();
                                              var x = messageReader.ReadInt32();
                                              var y = messageReader.ReadInt32();
                                              var data = messageReader.ReadUInt32();
                                              mouse_event(flags, x, y, data, UIntPtr.Zero);
                                          }
                                          break;
                                      case 1://reset
                                          {
                                              Process.GetProcessesByName("ZumasRevenge").FirstOrDefault()?.Kill();
                                              System.Threading.Thread.Sleep(TimeSpan.FromSeconds(4));
                                              var info = new ProcessStartInfo
                                              {
                                                  FileName = @"C:\Program Files\Games\Zuma's Revenge! v1.0.4\ZumasRevenge.exe",
                                                  WorkingDirectory = @"C:\Program Files\Games\Zuma's Revenge! v1.0.4",
                                                  UseShellExecute = false,
                                              };
                                              Process.Start(info);
                                              System.Threading.Thread.Sleep(TimeSpan.FromSeconds(5));
                                          }
                                          break;
                                  }
                              }
                              else
                                  System.Threading.Thread.Sleep(10);
                          }
                      }
                      catch (Exception exc)
                      {
                          Console.WriteLine(exc);
                      }
                  })
                { IsBackground = true };
                thread.Start();
            }

        }
Esempio n. 30
0
        public ActResource(string name, System.IO.Stream stream)
            : base(name, true)
        {
            int currentStreamPosition = (int)stream.Position;

            System.IO.BinaryReader reader = new System.IO.BinaryReader(stream, Encoding.ASCII);

            ActHeader header;

            header.Magic = reader.ReadUInt32();

            if (header.Magic != 0x41435448)
            {
                throw new Resource.InvalidResourceFileFormat("Invalid ACT file header");
            }

            header.Version1  = reader.ReadUInt16();
            header.Version2  = reader.ReadUInt16();
            header.NumFrames = reader.ReadUInt32();
            header.NumMeshes = reader.ReadUInt32();
            header.DataSize  = reader.ReadUInt32();
            header.ModelName = Gk3Main.Utils.ConvertAsciiToString(reader.ReadBytes(32));

            _modelName = header.ModelName;
            _numMeshes = header.NumMeshes;
            _numFrames = header.NumFrames;
            _frames    = new ActFrame[header.NumFrames * _numMeshes];

            // read the offsets
            uint[] offsets = new uint[header.NumFrames];
            for (int i = 0; i < header.NumFrames; i++)
            {
                offsets[i] = reader.ReadUInt32();
            }

            for (uint i = 0; i < header.NumFrames; i++)
            {
                stream.Seek(currentStreamPosition + offsets[i], System.IO.SeekOrigin.Begin);
                uint frameSize;
                if (i == header.NumFrames - 1)
                {
                    frameSize = header.DataSize - offsets[i];
                }
                else
                {
                    frameSize = offsets[i + 1] - offsets[i];
                }

                readFrame(reader, i, frameSize);
            }

            // now we have all the frames loaded from the ACT file,
            // so now it's time to convert the frame data into a more
            // usable layout
            _animationFrames = new MeshAnimationFrame[_numMeshes][];
            for (uint i = 0; i < _numMeshes; i++)
            {
                // count the active frames
                uint numActiveFramesThisMesh = 0;
                for (uint j = 0; j < _numFrames; j++)
                {
                    if (_frames[j * _numMeshes + i].Active)
                    {
                        numActiveFramesThisMesh++;
                    }
                }

                // create the frames
                _animationFrames[i] = new MeshAnimationFrame[numActiveFramesThisMesh];
                uint currentFrame = 0;
                for (uint j = 0; j < _numFrames; j++)
                {
                    if (_frames[j * _numMeshes + i].Active)
                    {
                        _animationFrames[i][currentFrame].Time      = _millisecondsPerFrame * j;
                        _animationFrames[i][currentFrame].Transform = _frames[j * _numMeshes + i].Transform;
                        if (_frames[j * _numMeshes + i].Vertices != null)
                        {
                            _animationFrames[i][currentFrame].Vertices = _frames[j * _numMeshes + i].Vertices.ToArray();
                        }
                        if (_frames[j * _numMeshes + i].BoundingBox != null)
                        {
                            _animationFrames[i][currentFrame].BoundingBox = _frames[j * _numMeshes + i].BoundingBox;
                        }
                        currentFrame++;
                    }
                }
            }
        }
Esempio n. 31
0
        public override void Load(ref System.IO.FileStream File, ref System.IO.BinaryReader Reader)
        {
            File.Position = Offset + Base;
            if (File.Position < File.Length && Size > 0)
            {
                Header      = Reader.ReadUInt32();
                Records     = (int)Reader.ReadUInt32();
                ContentSize = Reader.ReadUInt32();
                Array.Resize(ref _Item, Records);
                for (int i = 0; i <= Records - 1; i++)
                {
                    uint ElementOffset = Reader.ReadUInt32();
                    uint ElementSize   = Reader.ReadUInt32();
                    uint ElementID     = Reader.ReadUInt32();
                    uint Pos           = (uint)File.Position;
                    switch (ElementID)
                    {
                    case 0:
                    {
                        GameObjects GObjs = new GameObjects();
                        GObjs.Offset = ElementOffset;
                        GObjs.Base   = Offset + Base;
                        GObjs.Size   = ElementSize;
                        GObjs.ID     = ElementID;
                        GObjs.Load(ref File, ref Reader);
                        _Item[i] = GObjs;
                        break;
                    }

                    case 1:
                    {
                        Scripts Srpts = new Scripts();
                        Srpts.Offset = ElementOffset;
                        Srpts.Base   = Offset + Base;
                        Srpts.Size   = ElementSize;
                        Srpts.ID     = ElementID;
                        Srpts.Load(ref File, ref Reader);
                        _Item[i] = Srpts;
                        break;
                    }

                    case 2:
                    {
                        Animations Anims = new Animations();
                        Anims.Offset = ElementOffset;
                        Anims.Base   = Offset + Base;
                        Anims.Size   = ElementSize;
                        Anims.ID     = ElementID;
                        Anims.Load(ref File, ref Reader);
                        _Item[i] = Anims;
                        break;
                    }

                    case 3:
                    {
                        OGIs OGInfos = new OGIs();
                        OGInfos.Offset = ElementOffset;
                        OGInfos.Base   = Offset + Base;
                        OGInfos.Size   = ElementSize;
                        OGInfos.ID     = ElementID;
                        OGInfos.Load(ref File, ref Reader);
                        _Item[i] = OGInfos;
                        break;
                    }

                    case 4:
                    {
                        BaseSection BS = new BaseSection();
                        BS.Offset = ElementOffset;
                        BS.Base   = Offset + Base;
                        BS.Size   = ElementSize;
                        BS.ID     = ElementID;
                        BS.Load(ref File, ref Reader);
                        _Item[i] = BS;
                        break;
                    }

                    case 6:
                    {
                        Sound S = new Sound();
                        if (_Item[i - 1] is SoundDescriptions)
                        {
                            S.Shift = (_Item[i - 1].Records + 1) * 12;
                            for (int j = 0; j <= _Item[i - 1].Records - 1; j++)
                            {
                                S.Shift += (int)_Item[i - 1]._Item[j].Size;
                            }
                        }
                        else
                        {
                            S.Shift = 0;
                        }
                        S.Offset = ElementOffset;
                        S.Base   = Offset + Base;
                        S.Size   = ElementSize;
                        S.ID     = ElementID;
                        S.Load(ref File, ref Reader);
                        _Item[i] = S;
                        break;
                    }

                    case 5:
                    {
                        SoundDescriptions SDs = new SoundDescriptions();
                        SDs.Offset = ElementOffset;
                        SDs.Base   = Offset + Base;
                        SDs.Size   = ElementSize;
                        SDs.ID     = ElementID;
                        SDs.Load(ref File, ref Reader);
                        _Item[i] = SDs;
                        break;
                    }

                    default:
                    {
                        SoundbankDescriptions SDs = new SoundbankDescriptions();
                        SDs.Offset = ElementOffset;
                        SDs.Base   = Offset + Base;
                        SDs.Size   = ElementSize;
                        SDs.ID     = ElementID;
                        SDs.Load(ref File, ref Reader);
                        _Item[i] = SDs;
                        break;
                    }
                    }
                    File.Position = Pos;
                }
            }
        }
Esempio n. 32
0
        public static Assembly FromAIN(string path)
        {
            Assembly asm = new Assembly();
            System.IO.FileStream fs = new System.IO.FileStream(path, System.IO.FileMode.Open);
            System.IO.BinaryReader br = new System.IO.BinaryReader(fs);
            fs.Position = 8;
            uint size = br.ReadUInt32();
            uint compressedSize = br.ReadUInt32();
            byte[] buf;
            byte[] dst = new byte[size];
            buf = br.ReadBytes((int)compressedSize);
            fixed (byte* ptr = buf)
            {
                fixed (byte* ptr2 = dst)
                {
                    uncompress(ptr2, &size, ptr, compressedSize);
                }
            }
            fs.Close();

            System.IO.MemoryStream ms = new System.IO.MemoryStream(dst);
            br = new System.IO.BinaryReader(ms);
            while (ms.Position < ms.Length)
            {
                string trunk = Encoding.ASCII.GetString(br.ReadBytes(4));
                switch (trunk)
                {
                    case "VERS":
                        asm.Version = br.ReadInt32();
                        if (asm.Version != 6)
                        {
                            throw new NotSupportedException("本SDK仅支持版本为:6的反编译");
                        }
                        break;
                    case "KEYC":
                        asm.Keyc = br.ReadInt32();
                        break;
                    case "CODE":
                        asm.CodeBuffer = br.ReadBytes(br.ReadInt32());
                        break;
                    case "FUNC":
                        {
                            int count = br.ReadInt32();
                            for (int i = 0; i < count; i++)
                            {
                                Function func = new Function();
                                func.Address = br.ReadInt32();
                                func.Assembly = asm;
                                func.Name = ReadString(br);
                                func.U1 = br.ReadInt32();
                                func.ReturnType = (VarTypes)br.ReadInt32();
                                func.StructID = br.ReadInt32();
                                func.ArgCount = br.ReadInt32();
                                func.TotalLocalCount = br.ReadInt32();
                                func.U4 = br.ReadInt32();
                                for (int j = 0; j < func.TotalLocalCount; j++)
                                {
                                    Variable arg = new Variable();
                                    arg.Name = ReadString(br);
                                    arg.Assembly = asm;
                                    arg.VarType = (VarTypes)br.ReadInt32();
                                    arg.StructID = br.ReadInt32();
                                    arg.Dimension = br.ReadInt32();
                                    if (j < func.ArgCount)
                                        func.Arguments.Add(arg);
                                    func.LocalVariables.Add(arg);
                                }
                                asm.Functions.Add(func);
                            }
                        }
                        break;
                    case "GLOB":
                        {
                            int count = br.ReadInt32();
                            for (int i = 0; i < count; i++)
                            {
                                Variable var = new Variable();
                                var.Name = ReadString(br);
                                var.Assembly = asm;
                                var.VarType = (VarTypes)br.ReadInt32();
                                var.StructID = br.ReadInt32();
                                var.Dimension = br.ReadInt32();
                                var.U3 = br.ReadInt32();
                                asm.global.Add(var);
                            }
                        }
                        break;
                    case "GSET":
                        {
                            int count = br.ReadInt32();
                            for (int i = 0; i < count; i++)
                            {
                                Variable var = asm.global[br.ReadInt32()];
                                VarTypes type = (VarTypes)br.ReadInt32();
                                switch (type)
                                {
                                    case VarTypes.Float:
                                        var.FloatVal = br.ReadSingle();
                                        break;
                                    case VarTypes.String:
                                        var.StringVal = ReadString(br);
                                        break;
                                    case VarTypes.Bool:
                                        var.BoolVal = br.ReadInt32() == 1;
                                        break;
                                    default:
                                        var.IntVal = br.ReadInt32();
                                        break;
                                }
                            }
                        }
                        break;
                    case "STRT":
                        {
                            int count = br.ReadInt32();
                            for (int i = 0; i < count; i++)
                            {
                                Struct str = new Struct();
                                str.Name = ReadString(br);
                                int func = br.ReadInt32();
                                if (func != -1)
                                    str.Constructor = asm.func[func];
                                func = br.ReadInt32();
                                if (func != -1)
                                    str.Destructor = asm.func[func];
                                str.VarCount = br.ReadInt32();
                                for (int j = 0; j < str.VarCount; j++)
                                {
                                    Variable arg = new Variable();
                                    arg.Name = ReadString(br);
                                    arg.Assembly = asm;
                                    arg.VarType = (VarTypes)br.ReadInt32();
                                    arg.StructID = br.ReadInt32();
                                    arg.Dimension = br.ReadInt32();
                                    str.Variables.Add(arg);
                                }
                                asm.structs.Add(str);
                            }
                        }
                        break;
                    case "MSG0":
                        {
                            int count = br.ReadInt32();
                            for (int i = 0; i < count; i++)
                            {
                                asm.msgs.Add(ReadString(br));
                            }
                        }
                        break;
                    case "MAIN":
                        asm.EntryPoint = asm.func[br.ReadInt32()];
                        break;
                    case "MSGF":
                        asm.MessageFunction = asm.func[br.ReadInt32()];
                        break;
                    case "HLL0":
                        {
                            int count = br.ReadInt32();
                            for (int i = 0; i < count; i++)
                            {
                                string name = ReadString(br);
                                Hll hll = new Hll();
                                hll.Name = name;
                                int count2 = br.ReadInt32();
                                for (int j = 0; j < count2; j++)
                                {
                                    Function func = new Function();
                                    func.Name = ReadString(br);
                                    func.ReturnType = (VarTypes)br.ReadInt32();
                                    func.TotalLocalCount = br.ReadInt32();
                                    func.ArgCount = func.TotalLocalCount;
                                    for (int k = 0; k < func.TotalLocalCount; k++)
                                    {
                                        Variable arg = new Variable();
                                        arg.Assembly = asm;
                                        arg.Name = ReadString(br);
                                        arg.VarType = (VarTypes)br.ReadInt32();
                                        func.Arguments.Add(arg);
                                    }
                                    hll.Functions.Add(func);
                                }
                                asm.hlls.Add(hll);
                            }
                        }
                        break;
                    case "SWI0":
                        {
                            int count = br.ReadInt32();
                            for (int i = 0; i < count; i++)
                            {
                                Switch swi = new Switch();
                                swi.SwitchType = (SwitchTypes)br.ReadInt32();
                                swi.DefaultCase = br.ReadInt32();
                                int count2 = br.ReadInt32();
                                for (int j = 0; j < count2; j++)
                                {
                                    swi.SwitchTable.Add(br.ReadInt32(), br.ReadInt32());
                                }
                                asm.switches.Add(swi);
                            }
                        }
                        break;
                    case "GVER":
                        asm.GVersion = br.ReadInt32();
                        break;
                    case "STR0":
                        {
                            int count = br.ReadInt32();
                            for (int i = 0; i < count; i++)
                            {
                                string str = ReadString(br);
                                asm.strings.Add(str);
                            }
                        }
                        break;
                    case "FNAM":
                        {
                            int count = br.ReadInt32();
                            for (int i = 0; i < count; i++)
                            {
                                string str = ReadString(br);
                                asm.fname.Add(str);
                            }
                        }
                        break;
                    case "OJMP":
                        {
                            int funcID = br.ReadInt32();
                            if (funcID >= 0)
                                asm.JumpFunction = asm.func[funcID];
                        }
                        break;
                    case "FNCT":
                        {
                            int len = br.ReadInt32();
                            int count = br.ReadInt32();
                            for (int i = 0; i < count; i++)
                            {
                                Function func = new Function();
                                func.Name = ReadString(br);
                                func.ReturnType = (VarTypes)br.ReadInt32();
                                func.StructID = br.ReadInt32();
                                func.ArgCount = br.ReadInt32();
                                func.TotalLocalCount = br.ReadInt32();
                                for (int j = 0; j < func.TotalLocalCount; j++)
                                {
                                    Variable arg = new Variable();
                                    arg.Name = ReadString(br);
                                    arg.VarType = (VarTypes)br.ReadInt32();
                                    arg.StructID = br.ReadInt32();
                                    arg.Dimension = br.ReadInt32();
                                    func.Arguments.Add(arg);
                                }
                                asm.fnct.Add(func);
                            }
                        }
                        break;
                    case "OBJG":
                        {
                            int count = br.ReadInt32();
                            for (int i = 0; i < count; i++)
                            {
                                string str = ReadString(br);
                                asm.objg.Add(str);
                            }
                        }
                        break;
                    default:
                        throw new ArgumentException(string.Format("{0}文件中包含未知的Trunk:{1}", path, trunk));
                }
            }
            return asm;
        }
Esempio n. 33
0
        private static void _ProcessStaticChunksForPCM(
            System.IO.BinaryReader r,
            List <ChunkTable> chunks,
            List <AudioChunk> ret,
            ref ChunkFmt?fmt,
            ref Endianness endi,
            bool interlace = true)
        {
            foreach (ChunkTable ct in chunks)
            {
                switch ((ChunkID)ct.chunkID)
                {
                case ChunkID.RIFX:
                    endi = Endianness.Big;
                    break;

                case ChunkID.fmt:
                    r.BaseStream.Seek(ct.filePos, System.IO.SeekOrigin.Begin);

                    ChunkFmt cfmt = new ChunkFmt();
                    cfmt.Read(r);
                    fmt = cfmt;
                    break;

                case ChunkID.data:
                    if (fmt.HasValue == false)
                    {
                        continue;
                    }

                    if (fmt.Value.numChannels == 0)
                    {
                        continue;
                    }

                    r.BaseStream.Seek(ct.filePos, System.IO.SeekOrigin.Begin);

                    {
                        // NOTE: BIG ENDIAN UNIMPLEMENTED

                        AudioChunk ac = new AudioChunk();
                        if (fmt.Value.numChannels == 1 || interlace == true)
                        {
                            byte[] rb = r.ReadBytes(ct.size);

                            switch (fmt.Value.sigBitsPerSample)
                            {
                            case 8:
                            {
                                int      sct = ct.size;
                                float [] rf  = new float[sct];
                                ac.channels = new List <float[]>();
                                ac.channels.Add(rf);
                                for (int i = 0; i < sct; ++i)
                                {
                                    rf[i] = (float)(rb[i] - 128) / 128.0f;
                                }
                                ret.Add(ac);
                            }
                            break;

                            case 16:
                            {
                                int     sct = ct.size / 2;
                                float[] rf  = new float[sct];
                                ac.channels = new List <float[]>();
                                ac.channels.Add(rf);
                                for (int i = 0; i < sct; ++i)
                                {
                                    rf[i] = (float)System.BitConverter.ToInt16(rb, i * 2) / (float)short.MaxValue;
                                }
                                ret.Add(ac);
                            }
                            break;

                            case 24:
                            {
                                const float maxSigned24 = 8388608.0f;                                                         // 24^2/2.0
                                int         sct         = ct.size / 3;
                                float[]     rf          = new float[sct];
                                ac.channels = new List <float[]>();
                                ac.channels.Add(rf);
                                for (int i = 0; i < sct; ++i)
                                {
                                    byte b0 = rb[i * 3 + 0];
                                    byte b1 = rb[i * 3 + 1];
                                    byte b2 = rb[i * 3 + 2];

                                    const int hiBit    = 1 << 23;
                                    const int negFlags = hiBit - 1;
                                    int       v        = (b0 << 0) | (b1 << 8) | (b2 << 16);

                                    if ((hiBit & v) == 0)
                                    {
                                        rf[i] = (float)(v - 1) / maxSigned24;
                                    }
                                    else
                                    {
                                        rf[i] = (float)(-(~v & negFlags) - 1) / maxSigned24;
                                    }
                                }
                                ret.Add(ac);
                            }
                            break;

                            case 32:
                            {
                                int     sct = ct.size / 4;
                                float[] rf  = new float[sct];
                                ac.channels = new List <float[]>();
                                ac.channels.Add(rf);
                                if (fmt.Value.compressionCode == (int)CompressionCode.Float)
                                {
                                    System.Buffer.BlockCopy(rb, 0, rf, 0, ct.size);
                                }
                                else
                                {
                                    for (int i = 0; i < sct; ++i)
                                    {
                                        rf[i] = (float)System.BitConverter.ToInt32(rb, i * 4) / (float)int.MaxValue;
                                    }
                                }
                                ret.Add(ac);
                            }
                            break;

                            case 64:
                            {
                                int     sct = ct.size / 8;
                                float[] rf  = new float[sct];
                                ac.channels = new List <float[]>();
                                ac.channels.Add(rf);
                                if (fmt.Value.compressionCode == (int)CompressionCode.Float)
                                {
                                    for (int i = 0; i < sct; ++i)
                                    {
                                        rf[i] = (float)System.BitConverter.ToDouble(rb, i * 8);
                                    }
                                }
                                else
                                {
                                    for (int i = 0; i < sct; ++i)
                                    {
                                        rf[i] = (float)System.BitConverter.ToInt64(rb, i * 8) / (float)long.MaxValue;
                                    }
                                }
                                ret.Add(ac);
                            }
                            break;

                            default:
                                continue;
                            }
                        }
                        else
                        {
                            // UNIMPLEMENTED
                        }
                    }

                    break;

                case ChunkID.wavl:
                    if (fmt.HasValue == false)
                    {
                        continue;
                    }

                    r.BaseStream.Seek(ct.filePos, System.IO.SeekOrigin.Begin);

                    List <ChunkTable> alternatingDataChunks = new List <ChunkTable>();
                    ParseBoundedStaticChunksInto(r, alternatingDataChunks, ct.filePos + ct.size);

                    // Recursion
                    _ProcessStaticChunksForPCM(r, alternatingDataChunks, ret, ref fmt, ref endi);
                    break;

                case ChunkID.slnt:
                    if (fmt.HasValue == false)
                    {
                        continue;
                    }

                    uint silentSamples = r.ReadUInt32();
                    ret.Add(new AudioChunk(silentSamples));
                    break;
                }
            }
        }
Esempio n. 34
0
        public bool Open(string filename)
        {
            System.IO.FileStream   stream = new System.IO.FileStream(filename, System.IO.FileMode.Open, System.IO.FileAccess.Read);
            System.IO.BinaryReader reader = new System.IO.BinaryReader(stream);
            bool re = true;

            try
            {
                byte[] magicbyte = reader.ReadBytes(52);

                string magicstring = System.Text.ASCIIEncoding.ASCII.GetString(magicbyte).Trim('\0');

                uint size       = reader.ReadUInt32();
                bool compressed = true;
                if (reader.ReadUInt32() == 0)
                {
                    compressed = false;
                }

                switch (magicstring)
                {
                case "KOG GC TEAM MASSFILE V.0.3.":

                    komtype = EKomType.newkom;

                    filetime    = reader.ReadUInt32();
                    adler32     = reader.ReadUInt32();
                    header_size = reader.ReadUInt32();

                    System.Xml.XmlDocument headerxml = new System.Xml.XmlDocument();

                    byte[] header_raw = reader.ReadBytes((int)header_size);

                    if (header_raw[0] != '<' ||
                        header_raw[1] != '?' ||
                        header_raw[2] != 'x' ||
                        header_raw[3] != 'm' ||
                        header_raw[4] != 'l')
                    {
                        if (ecb == null)
                        {
                            throw new EncryptedKomException();
                        }

                        byte[] data = (byte[])header_raw.Clone();
                        ecb.Decrypt(data, 0, header_raw, 0, (int)header_size);
                        komtype = EKomType.encrypt;
                    }
                    string xmlstring = System.Text.ASCIIEncoding.ASCII.GetString(header_raw);
                    headerxml.LoadXml(xmlstring);
                    System.Xml.XmlNodeList files = headerxml.SelectNodes("Files/File");

                    UInt32 offset = OffsetStart + header_size;

                    foreach (System.Xml.XmlElement file in files)
                    {
                        string      key     = file.GetAttribute("Name");
                        Kom2SubFile subfile = Kom2SubFile.ReadSubFileFromKom(ecb, filename, file, offset);
                        offset += subfile.CompressedSize;
                        subfiles.Add(key, subfile);
                    }
                    break;

                case "KOG GC TEAM MASSFILE V.0.1.":
                case "KOG GC TEAM MASSFILE V.0.2.":

                    komtype = EKomType.oldkom;
                    for (int i = 0; i < size; i++)
                    {
                        string      key     = System.Text.ASCIIEncoding.ASCII.GetString(reader.ReadBytes(60)).Trim('\0');
                        Kom2SubFile subfile = Kom2SubFile.ReadSubFileFromOldKom(filename, reader, 60 + size * 72);
                        if (key != "crc.xml")
                        {
                            subfiles.Add(key, subfile);
                        }
                    }
                    break;

                default:
                    re = false;
                    break;
                }
            }
            catch (System.Exception ex)
            {
                komtype = EKomType.notkom;
                re      = false;
            }

            stream.Close();
            return(re);
        }
Esempio n. 35
0
                public void             Load(System.IO.BinaryReader _Reader)
                {
                    m_Usage     = (USAGE)_Reader.ReadInt32();
                    m_FieldType = (FIELD_TYPE)_Reader.ReadInt32();
                    m_Index     = _Reader.ReadInt32();

                    int ArraySize = _Reader.ReadInt32();

                    switch (m_FieldType)
                    {
                    case FIELD_TYPE.FLOAT:
                    {
                        float[] T = new float[ArraySize];
                        m_Content = T;
                        for (int i = 0; i < ArraySize; i++)
                        {
                            T[i] = _Reader.ReadSingle();
                        }
                    }
                    break;

                    case FIELD_TYPE.FLOAT2:
                    {
                        Vector2D[] T = new Vector2D[ArraySize];
                        m_Content = T;
                        for (int i = 0; i < ArraySize; i++)
                        {
                            T[i].X = _Reader.ReadSingle();
                            T[i].Y = _Reader.ReadSingle();
                        }
                    }
                    break;

                    case FIELD_TYPE.FLOAT3:
                    {
                        Vector[] T = new Vector[ArraySize];
                        m_Content = T;
                        for (int i = 0; i < ArraySize; i++)
                        {
                            T[i].X = _Reader.ReadSingle();
                            T[i].Y = _Reader.ReadSingle();
                            T[i].Z = _Reader.ReadSingle();
                        }
                    }
                    break;

                    case FIELD_TYPE.FLOAT4:
                    {
                        Vector4D[] T = new Vector4D[ArraySize];
                        m_Content = T;
                        for (int i = 0; i < ArraySize; i++)
                        {
                            T[i].X = _Reader.ReadSingle();
                            T[i].Y = _Reader.ReadSingle();
                            T[i].Z = _Reader.ReadSingle();
                            T[i].W = _Reader.ReadSingle();
                        }
                    }
                    break;

                    case FIELD_TYPE.UINT32:
                    {
                        UInt32[] T = new UInt32[ArraySize];
                        m_Content = T;
                        for (int i = 0; i < ArraySize; i++)
                        {
                            T[i] = _Reader.ReadUInt32();
                        }
                    }
                    break;
                    }
                }
Esempio n. 36
0
        public BspResource(string name, System.IO.Stream stream, Resource.ResourceManager content)
            : base(name, true)
        {
            System.IO.BinaryReader reader =
                new System.IO.BinaryReader(stream);

            // read the header
            BspHeader header = new BspHeader();

            header.heading          = reader.ReadBytes(4);
            header.minorVersion     = reader.ReadUInt16();
            header.majorVersion     = reader.ReadUInt16();
            header.dataSectionSize  = reader.ReadUInt32();
            header.rootIndex        = reader.ReadUInt32();
            header.numModels        = reader.ReadUInt32();
            header.numVertices      = reader.ReadUInt32();
            header.numTexCoords     = reader.ReadUInt32();
            header.numVertexIndices = reader.ReadUInt32();
            header.numTexIndices    = reader.ReadUInt32();
            header.numSurfaces      = reader.ReadUInt32();
            header.numPlanes        = reader.ReadUInt32();
            header.numNodes         = reader.ReadUInt32();
            header.numPolygons      = reader.ReadUInt32();

            // read the model names
            byte[]     buffer32 = new byte[32];
            BspModel[] models   = new BspModel[header.numModels];
            _modelsNames = new string[header.numModels];
            for (uint i = 0; i < header.numModels; i++)
            {
                models[i] = new BspModel();

                models[i].name  = Gk3Main.Utils.ConvertAsciiToString(reader.ReadBytes(32));
                _modelsNames[i] = models[i].name;
            }

            // read the surfaces
            Random randomGenerator = new Random();

            _surfaces = new BspSurface[header.numSurfaces];
            for (uint i = 0; i < header.numSurfaces; i++)
            {
                if (i == 134)
                {
                    i = i;
                }

                _surfaces[i] = new BspSurface();

                _surfaces[i].modelIndex = reader.ReadUInt32();
                _surfaces[i].texture    = Gk3Main.Utils.ConvertAsciiToString(reader.ReadBytes(32));
                _surfaces[i].uCoord     = reader.ReadSingle();
                _surfaces[i].vCoord     = reader.ReadSingle();
                _surfaces[i].uScale     = reader.ReadSingle();
                _surfaces[i].vScale     = reader.ReadSingle();
                _surfaces[i].size1      = reader.ReadUInt16();
                _surfaces[i].size2      = reader.ReadUInt16();
                _surfaces[i].flags      = (BspSurfaceFlags)reader.ReadUInt32();

                _surfaces[i].r     = (float)randomGenerator.NextDouble();
                _surfaces[i].g     = (float)randomGenerator.NextDouble();
                _surfaces[i].b     = (float)randomGenerator.NextDouble();
                _surfaces[i].index = i;
            }

            // read the BSP nodes (for now throw them away)
            _nodes = new BspNode[header.numNodes];
            for (uint i = 0; i < header.numNodes; i++)
            {
                _nodes[i].Left              = reader.ReadInt16();
                _nodes[i].Right             = reader.ReadInt16();
                _nodes[i].PlaneIndex        = reader.ReadInt16();
                _nodes[i].PolygonStartIndex = reader.ReadInt16();
                reader.ReadInt16();
                _nodes[i].NumPolygons = reader.ReadInt16();

                uint i3 = reader.ReadUInt16();
                uint i4 = reader.ReadUInt16();
            }

            // TEMP: validate the BSP
            foreach (BspNode node in _nodes)
            {
                if (node.Left >= _nodes.Length ||
                    node.Right >= _nodes.Length)
                {
                    throw new Exception("OH NO!");
                }
            }

            int parent = findParent(_nodes, 0);

            // read all the polygons
            _polygons = new BspPolygon[header.numPolygons];
            for (uint i = 0; i < header.numPolygons; i++)
            {
                _polygons[i] = new BspPolygon();

                _polygons[i].vertexIndex  = reader.ReadUInt16();
                _polygons[i].flags        = reader.ReadUInt16();
                _polygons[i].numVertices  = reader.ReadUInt16();
                _polygons[i].surfaceIndex = reader.ReadUInt16();

                if (_polygons[i].surfaceIndex == 134)
                {
                    i = i;
                }
            }

            // read all the planes (thow them away)
            for (uint i = 0; i < header.numPlanes; i++)
            {
                reader.ReadBytes(16);
            }

            // read the vertices
            _vertices = new float[header.numVertices * 3];
            for (uint i = 0; i < header.numVertices; i++)
            {
                _vertices[i * 3 + 0] = reader.ReadSingle();
                _vertices[i * 3 + 1] = reader.ReadSingle();
                _vertices[i * 3 + 2] = reader.ReadSingle();
            }

            // read the texture vertices
            _texcoords = new float[header.numTexCoords * 2];
            for (uint i = 0; i < header.numTexCoords; i++)
            {
                _texcoords[i * 2 + 0] = reader.ReadSingle();
                _texcoords[i * 2 + 1] = reader.ReadSingle();
            }

            // read all the vertex indices
            ushort[] indices = new ushort[header.numVertexIndices];
            for (uint i = 0; i < header.numVertexIndices; i++)
            {
                indices[i] = reader.ReadUInt16();
            }

            // read all the texcoord indices
            ushort[] texindices = new ushort[header.numTexIndices];
            for (uint i = 0; i < header.numTexIndices; i++)
            {
                texindices[i] = reader.ReadUInt16();
            }

            // read the bounding spheres
            _boundingSpheres = new Math.Vector4[header.numNodes];
            for (uint i = 0; i < header.numNodes; i++)
            {
                _boundingSpheres[i].Z = reader.ReadSingle();
                _boundingSpheres[i].Y = reader.ReadSingle();
                _boundingSpheres[i].X = reader.ReadSingle();
                _boundingSpheres[i].W = reader.ReadSingle();
            }

            // load the "thingies", whatever that means
            _bspVertices = new List <BspVertex>();
            for (int i = 0; i < header.numSurfaces; i++)
            {
                // throw junk away
                _surfaces[i].boundingSphere.X = reader.ReadSingle();
                _surfaces[i].boundingSphere.Y = reader.ReadSingle();
                _surfaces[i].boundingSphere.Z = reader.ReadSingle();
                _surfaces[i].boundingSphere.W = reader.ReadSingle();

                reader.ReadBytes(12);

                uint numIndices = reader.ReadUInt32();
                _surfaces[i].numTriangles = reader.ReadUInt32();

                UInt16[] myindices = new UInt16[numIndices];
                for (uint j = 0; j < numIndices; j++)
                {
                    myindices[j] = reader.ReadUInt16();
                }

                _surfaces[i].VertexIndex = _bspVertices.Count;
                _surfaces[i].indices     = new ushort[_surfaces[i].numTriangles * 3];
                for (uint j = 0; j < _surfaces[i].numTriangles; j++)
                {
                    ushort x = reader.ReadUInt16();
                    ushort y = reader.ReadUInt16();
                    ushort z = reader.ReadUInt16();

                    _surfaces[i].indices[j * 3 + 0] = myindices[x];
                    _surfaces[i].indices[j * 3 + 1] = myindices[y];
                    _surfaces[i].indices[j * 3 + 2] = myindices[z];

                    // TODO: since we aren't using indices the hardware can't cache vertices,
                    // so there's some performance loss. Figure out a good way to still use indices.

                    // vertex 1
                    BspVertex vertex = new BspVertex();
                    vertex.X = _vertices[myindices[x] * 3 + 0];
                    vertex.Y = _vertices[myindices[x] * 3 + 1];
                    vertex.Z = _vertices[myindices[x] * 3 + 2];
                    vertex.U = _texcoords[myindices[x] * 2 + 0];
                    vertex.V = _texcoords[myindices[x] * 2 + 1];
                    _bspVertices.Add(vertex);

                    // vertex 2
                    vertex.X = _vertices[myindices[y] * 3 + 0];
                    vertex.Y = _vertices[myindices[y] * 3 + 1];
                    vertex.Z = _vertices[myindices[y] * 3 + 2];
                    vertex.U = _texcoords[myindices[y] * 2 + 0];
                    vertex.V = _texcoords[myindices[y] * 2 + 1];
                    _bspVertices.Add(vertex);

                    // vertex 3
                    vertex.X = _vertices[myindices[z] * 3 + 0];
                    vertex.Y = _vertices[myindices[z] * 3 + 1];
                    vertex.Z = _vertices[myindices[z] * 3 + 2];
                    vertex.U = _texcoords[myindices[z] * 2 + 0];
                    vertex.V = _texcoords[myindices[z] * 2 + 1];
                    _bspVertices.Add(vertex);
                }
                _surfaces[i].VertexCount = _bspVertices.Count - _surfaces[i].VertexIndex;
            }

            reader.Close();

            loadTextures(content);
        }
Esempio n. 37
0
        /// <summary>
        /// Unserializes a BinaryStream into the Attributes of this Instance
        /// </summary>
        /// <param name="reader">The Stream that contains the FileData</param>
        protected override void Unserialize(System.IO.BinaryReader reader)
        {
            duff   = false;
            this.e = null;

            count = reader.ReadUInt32();

            try
            {
                reffiles = new Interfaces.Files.IPackedFileDescriptor[count == 0xffff0001 ? reader.ReadUInt32() : count];
                for (int i = 0; i < reffiles.Length; i++)
                {
                    SimPe.Packages.PackedFileDescriptor pfd = new SimPe.Packages.PackedFileDescriptor();

                    pfd.Group    = reader.ReadUInt32();
                    pfd.Instance = reader.ReadUInt32();
                    pfd.SubType  = (count == 0xffff0001) ? reader.ReadUInt32() : 0;
                    pfd.Type     = reader.ReadUInt32();

                    reffiles[i] = pfd;
                }

                uint nn = reader.ReadUInt32();
                index  = new uint[nn];
                blocks = new IRcolBlock[index.Length];
                for (int i = 0; i < index.Length; i++)
                {
                    index[i] = reader.ReadUInt32();
                }


                for (int i = 0; i < index.Length; i++)
                {
                    uint       id  = index[i];
                    IRcolBlock wrp = ReadBlock(id, reader);
                    if (wrp == null)
                    {
                        break;
                    }
                    blocks[i] = wrp;
                }

                if (!fast)
                {
                    long size = reader.BaseStream.Length - reader.BaseStream.Position;
                    if (size > 0)
                    {
                        oversize = reader.ReadBytes((int)size);
                    }
                    else
                    {
                        oversize = new byte[0];
                    }
                }
            }
            catch (Exception e)
            {
                duff   = true;
                this.e = e;
                //SimPe.Helper.ExceptionMessage(e);
            }
            finally { }
        }
Esempio n. 38
0
 protected override void DataUpdate()
 {
     System.IO.BinaryReader BSReader = new System.IO.BinaryReader(ByteStream);
     ByteStream.Position = 0;
     X        = BSReader.ReadSingle();
     Y        = BSReader.ReadSingle();
     Z        = BSReader.ReadSingle();
     W        = BSReader.ReadSingle();
     RX       = BSReader.ReadUInt16();
     COMRX    = BSReader.ReadUInt16();
     RY       = BSReader.ReadUInt16();
     COMRY    = BSReader.ReadUInt16();
     RZ       = BSReader.ReadUInt16();
     COMRZ    = BSReader.ReadUInt16();
     Size1    = BSReader.ReadInt32();
     Size1    = BSReader.ReadInt32();
     SomeNum1 = BSReader.ReadInt32();
     Array.Resize(ref Something1, Size1);
     for (int i = 0; i <= Size1 - 1; i++)
     {
         Something1[i] = BSReader.ReadUInt16();
     }
     Size2    = BSReader.ReadInt32();
     Size2    = BSReader.ReadInt32();
     SomeNum2 = BSReader.ReadInt32();
     Array.Resize(ref Something2, Size2);
     for (int i = 0; i <= Size2 - 1; i++)
     {
         Something2[i] = BSReader.ReadUInt16();
     }
     Size3    = BSReader.ReadInt32();
     Size3    = BSReader.ReadInt32();
     SomeNum3 = BSReader.ReadInt32();
     Array.Resize(ref Something3, Size3);
     for (int i = 0; i <= Size3 - 1; i++)
     {
         Something3[i] = BSReader.ReadUInt16();
     }
     ObjectID         = BSReader.ReadUInt16();
     AfterOID         = BSReader.ReadUInt32();
     ParametersHeader = BSReader.ReadUInt32();
     UnkI32           = BSReader.ReadUInt32();
     UnkI321Number    = BSReader.ReadInt32();
     Array.Resize(ref UnkI321, UnkI321Number);
     for (int i = 0; i <= UnkI321Number - 1; i++)
     {
         UnkI321[i] = BSReader.ReadUInt32();
     }
     UnkI322Number = BSReader.ReadInt32();
     Array.Resize(ref UnkI322, UnkI322Number);
     for (int i = 0; i <= UnkI322Number - 1; i++)
     {
         UnkI322[i] = BSReader.ReadSingle();
     }
     UnkI323Number = BSReader.ReadInt32();
     Array.Resize(ref UnkI323, UnkI323Number);
     for (int i = 0; i <= UnkI323Number - 1; i++)
     {
         UnkI323[i] = BSReader.ReadUInt32();
     }
 }
Esempio n. 39
0
        private bool _LeeSLTBinario(String FicheroSLT)
        {
            /*****Binary STL
             *
             * Because ASCII STL files can become very large, a binary version of STL exists. A binary STL file has an 80-character header (which is generally ignored, but should never begin with
             * "solid" because that will lead most software to assume that this is an ASCII STL file). Following the header is a 4-byte unsigned integer indicating the number of triangular facets
             * in the file. Following that is data describing each triangle in turn. The file simply ends after the last triangle.
             *
             * Each triangle is described by twelve 32-bit doubleing-point numbers: three for the normal and then three for the X/Y/Z coordinate of each vertex – just as with the ASCII version of STL.
             * After these follows a 2-byte ("short") unsigned integer that is the "attribute byte count" – in the standard format, this should be zero because most software does not understand anything else.
             *
             * doubleing-point numbers are represented as IEEE doubleing-point numbers and are assumed to be little-endian, although this is not stated in documentation.
             *
             *  UINT8[80] – Header
             *  UINT32 – Number of triangles
             *
             *  foreach triangle
             *  REAL32[3] – Normal vector
             *  REAL32[3] – Vertex 1
             *  REAL32[3] – Vertex 2
             *  REAL32[3] – Vertex 3
             *  UINT16 – Attribute byte count
             *  end
             */

            bool Res = true;

            System.IO.StreamReader SR = new System.IO.StreamReader(FicheroSLT, Encoding.ASCII);
            //Evalua si es binario o ASCII
            string LineaSLT = SR.ReadLine();

            LineaSLT = LineaSLT.TrimStart(new char[2] {
                ' ', '\t'
            });
            SR.Close();
            SR.Dispose();

            if (!LineaSLT.StartsWith("solid "))
            {
                System.IO.FileStream   FS = new System.IO.FileStream(FicheroSLT, System.IO.FileMode.Open, System.IO.FileAccess.Read);
                System.IO.BinaryReader BR = new System.IO.BinaryReader(FS);

                //Cabecera UINT8[80] – Header
                for (int i = 0; i < 80; i++)
                {
                    char TempChar = BR.ReadChar();
                    if (TempChar != '\0')
                    {
                        Nombre += TempChar;
                    }
                }

                //Número de triángulos UINT32 – Number of triangles
                UInt32 NumTriangulos = BR.ReadUInt32();

                if (NumTriangulos > 0)
                {
                    LoopSLT  TempLoop  = new LoopSLT();
                    FacetSLT TempFacet = new FacetSLT();

                    for (UInt32 Ui = 0; Ui < NumTriangulos; Ui++)
                    {
                        //Vector Normal REAL32[3] – Normal vector

                        TempFacet._Normal = new VertexSLT(Round(BR.ReadSingle()), Round(BR.ReadSingle()), Round(BR.ReadSingle()));

                        //REAL32[3] – Vertex 1
                        TempLoop.Vertices.Add(new VertexSLT(Round(BR.ReadSingle()), Round(BR.ReadSingle()), Round(BR.ReadSingle())));
                        //REAL32[3] – Vertex 2
                        TempLoop.Vertices.Add(new VertexSLT(Round(BR.ReadSingle()), Round(BR.ReadSingle()), Round(BR.ReadSingle())));
                        //REAL32[3] – Vertex 3
                        TempLoop.Vertices.Add(new VertexSLT(Round(BR.ReadSingle()), Round(BR.ReadSingle()), Round(BR.ReadSingle())));

                        TempLoop.ActualizaBoundingZ();
                        TempFacet._Loops.Add(TempLoop);

                        //Attribute byte count
                        TempFacet._Attribute = BR.ReadUInt16();

                        if (TempFacet.EsValido())
                        {
                            _Facets.Add(TempFacet);
                        }
                        else
                        {
                            Res = false;
                            Fallos.Add("Lectura SLT Binario: Faceta no válida");
                        }

                        TempLoop  = new LoopSLT();
                        TempFacet = new FacetSLT();
                    }
                }
                else
                {
                    Res = false;
                    Fallos.Add("Lectura SLT Binario: Número de triángulos nulo o igual a 0");
                }

                BR.Close();
                FS.Close();
                BR.Dispose();
                FS.Dispose();
            }
            else
            {
                Res = false;
                Fallos.Add("Lectura SLT Binario: El Fichero comienza por 'solid '");
            }

            return(Res);
        }
Esempio n. 40
0
        public void readFile()
        {
            System.IO.BinaryReader sr;

            try { //TODO: test, rather than try/fail?
                sr = new System.IO.BinaryReader(System.IO.File.Open(path, System.IO.FileMode.Open));
            } catch (System.IO.IOException) {
                throw;
            }

            //====================
            //RIFF chunk id
            char[] ckID = sr.ReadChars(4);
            String a = new string(ckID);
            if (a.CompareTo("RIFF") != 0) {
                throw new FormatException("RIFF chunkID missing. Found " + ckID[0] + ckID[1] + ckID[2] + ckID[3] + ".");
            }

            UInt32 RIFFSize = sr.ReadUInt32();

            //====================
            //WAVE chunk id
            ckID = sr.ReadChars(4);
            a = new string(ckID);
            if (a.CompareTo("WAVE") != 0) {
                throw new FormatException("WAVE chunkID missing. Found " + ckID[0] + ckID[1] + ckID[2] + ckID[3] + ".");
            }

            //====================
            //fmt_ chunk id
            ckID = sr.ReadChars(4);
            a = new string(ckID);
            UInt32 chunkSize = sr.ReadUInt32();
            while (a.CompareTo("fmt ") != 0) {
                sr.ReadBytes((int)chunkSize);
                ckID = sr.ReadChars(4);
                a = new string(ckID);
                chunkSize = sr.ReadUInt32();
            }
            Int16 wFormatTag = sr.ReadInt16();
            Int16 nChannels = sr.ReadInt16();
            Int32 nSamplesPerSec = sr.ReadInt32();
            Int32 nAvgBytesPerSec = sr.ReadInt32();
            Int16 nBlockAlign = sr.ReadInt16();
            Int16 wBitsPerSample = sr.ReadInt16();
            chunkSize -= 16;
            //there may be more bytes in fmt_ so skip those.
            sr.ReadBytes((int)chunkSize);

            if (wFormatTag != 0x0001) {
                throw new FormatException("Invalid wave format. Only PCM wave files supported.");
            }

            //====================
            //data chunk id
            ckID = sr.ReadChars(4);
            a = new string(ckID);
            chunkSize = sr.ReadUInt32();
            while (a.CompareTo("data") != 0) {
                sr.ReadBytes((int)chunkSize);
                ckID = sr.ReadChars(4);
                a = new string(ckID);
                chunkSize = sr.ReadUInt32();
            }

            channels = (short)nChannels;
            bitDepth = (short)wBitsPerSample;
            sampleRate = nSamplesPerSec;
            long numSamples = chunkSize / (bitDepth / 8) / channels;
            samples = new double[channels][];
            for (int c = 0; c < channels; c++) {
                samples[c] = new double[numSamples];
            }

            //======================
            // read samples
            if (bitDepth == 16) {
                for (int i = 0; i < numSamples; i++) {
                    for (int c = 0; c < channels; c++) {
                        //assuming signed
                        //normalized to -1.0..+1.0
                        samples[c][i] = (double)sr.ReadInt16() / 32768.0;
                    }
                }
            } else if (bitDepth == 8) {
                for (int i = 0; i < numSamples; i++) {
                    for (int c = 0; c < channels; c++) {
                        //assuming unsigned
                        //normalized to -1.0..+1.0
                        samples[c][i] = (double)sr.ReadByte() / 128.0 - 1.0;
                    }
                }
            } else {
                throw new FormatException("Bit depth must be one of 8 or 16 bits.");
            }
            sr.Close();
        }
Esempio n. 41
0
        public void Populate(int iOffset, int iIndexedReflexiveOffset)
        {
            this.isNulledOutReflexive = false;
            System.IO.BinaryReader BR = new System.IO.BinaryReader(meta.MS);

            int mapMetaOffset = meta.offset;

            if (this._EntIndex.reflexiveTagType + this._EntIndex.reflexiveTagName != string.Empty)
            {
                int tagNum = map.Functions.ForMeta.FindByNameAndTagType(this._EntIndex.reflexiveTagType, this._EntIndex.reflexiveTagName);
                if (tagNum != -1)
                {
                    Meta meta2 = new Meta(map);
                    map.OpenMap(MapTypes.Internal);
                    meta2.ReadMetaFromMap(tagNum, true);
                    map.CloseMap();
                    mapMetaOffset = meta2.offset;
                    this._EntIndex.reflexiveLayer = "root";
                }
            }

            if (this._EntIndex.reflexiveLayer.ToLower() == "root")
                this._IndexedReflexiveOffset = mapMetaOffset + this._EntIndex.ReflexiveOffset;
            else if (this._EntIndex.reflexiveLayer.ToLower() == "oneup")
                this._IndexedReflexiveOffset = iIndexedReflexiveOffset + this._EntIndex.ReflexiveOffset;

            /*
            bool openedMap = false;
            if (map.isOpen == false)
            {
                map.OpenMap(MapTypes.Internal);
                openedMap = true;
            }
            map.BA.Position = iOffset + this.chunkOffset;
            */
            BR.BaseStream.Position = iOffset + this.chunkOffset;
            this.offsetInMap = meta.offset + iOffset + this.chunkOffset;

            switch (_ValueType)
            {
                case IFPIO.ObjectEnum.Short:
                    {
                        this.Value = (int)BR.ReadInt16();
                        break;
                    }
                case IFPIO.ObjectEnum.Int:
                    {
                        this.Value = BR.ReadInt32();
                        break;
                    }
                case IFPIO.ObjectEnum.UShort:
                    {
                        this.Value = (int)BR.ReadUInt16();
                        break;
                    }
                case IFPIO.ObjectEnum.UInt:
                    {
                        this.Value = (int)BR.ReadUInt32();
                        break;
                    }
                case IFPIO.ObjectEnum.Byte:
                    {
                        this.Value = (int)BR.ReadByte();
                        break;
                    }
            }
            UpdateSelectionList(false);
            /*
            if (openedMap == true)
                map.CloseMap();
            */
        }
Esempio n. 42
0
        public static Sector LoadSector(System.IO.BinaryReader bs)
        {
            var result = new Sector();

            result.sector_checksum = bs.ReadUInt32();

            result.bone_idx = bs.ReadInt32();

            result.flags = bs.ReadUInt32();

            uint num_meshes = bs.ReadUInt32();

            result.bbox = new System.Numerics.Matrix3x2(bs.ReadSingle(), bs.ReadSingle(), bs.ReadSingle(), bs.ReadSingle(), bs.ReadSingle(), bs.ReadSingle());

            result.bsphere = new System.Numerics.Vector4(bs.ReadSingle(), bs.ReadSingle(), bs.ReadSingle(), bs.ReadSingle());

            if ((result.flags & (uint)0x00800000UL) != 0)
            {
                result.billboard_type       = bs.ReadUInt32();
                result.billboard_origin     = new System.Numerics.Vector3(bs.ReadSingle(), bs.ReadSingle(), bs.ReadSingle());
                result.billboard_pivot_pos  = new System.Numerics.Vector3(bs.ReadSingle(), bs.ReadSingle(), bs.ReadSingle());
                result.billboard_pivot_axis = new System.Numerics.Vector3(bs.ReadSingle(), bs.ReadSingle(), bs.ReadSingle());
            }
            else
            {
                result.billboard_origin     = null;
                result.billboard_pivot_pos  = null;
                result.billboard_pivot_axis = null;
            }

            var num_verticies = bs.ReadInt32();

            //var vertex_stride = bs.ReadInt32();
            bs.ReadInt32(); //skip vertex stride

            var vertices = new SectorPerVertexData[num_verticies];

            for (var i = 0; i < num_verticies; i++)
            {
                vertices[i] = new SectorPerVertexData();
            }

            for (int i = 0; i < num_verticies; i++)
            {
                var vert = new System.Numerics.Vector3(bs.ReadSingle(), bs.ReadSingle(), bs.ReadSingle());
                vertices[i].position = vert;
            }

            if ((result.flags & (int)0x04) != 0)
            {
                for (int i = 0; i < num_verticies; i++)
                {
                    var vert = new System.Numerics.Vector3(bs.ReadSingle(), bs.ReadSingle(), bs.ReadSingle());
                    vertices[i].normal = vert;
                }
            }

            if ((result.flags & (int)0x10) != 0)
            {
                for (int i = 0; i < num_verticies; i++)
                {
                    vertices[i].weight = bs.ReadUInt32();
                }

                for (int i = 0; i < num_verticies; i++)
                {
                    vertices[i].bone_indices = new System.Numerics.Vector4(bs.ReadUInt16(), bs.ReadUInt16(), bs.ReadUInt16(), bs.ReadUInt16());
                }
            }


            if ((result.flags & (int)0x01) != 0)
            {
                int num_tc_sets = bs.ReadInt32();
                if (num_tc_sets > 0)
                {
                    for (var i = 0; i < num_tc_sets; i++)
                    {
                        for (var x = 0; x < num_verticies; x++)
                        {
                            if (i == 0)
                            {
                                vertices[x].texture_uvs = new System.Numerics.Vector2[num_tc_sets];
                            }
                            vertices[x].texture_uvs[i] = new System.Numerics.Vector2(bs.ReadSingle(), bs.ReadSingle());
                        }
                    }
                }
            }


            if ((result.flags & (int)0x02) != 0)
            {
                for (var i = 0; i < num_verticies; i++)
                {
                    vertices[i].vertex_colour = bs.ReadUInt32();
                }
            }

            if ((result.flags & (int)0x800) != 0)
            {
                for (var i = 0; i < num_verticies; i++)
                {
                    vertices[i].vc_wibble_index = bs.ReadByte();
                }
            }

            result.vertices = vertices;

            var meshes = new List <Mesh>();

            for (int i = 0; i < num_meshes; i++)
            {
                var mesh = Mesh.ReadMesh(bs, result.flags);
                meshes.Add(mesh);
            }
            result.meshes = meshes;

            return(result);
        }
Esempio n. 43
0
        public void read(System.IO.BinaryReader reader)
        {
            if (count <= 0)
            {
                return;
            }
            switch (type)
            {
            case TIFFdataType.Byte:
                content = new byte[count];
                for (int i = 0; i < count; i++)
                {
                    ((byte[])content)[i] = reader.ReadByte();
                }
                break;

            case TIFFdataType.Ascii:
                content = new char[count];
                for (int i = 0; i < count; i++)
                {
                    ((char[])content)[i] = (char)reader.ReadByte();
                }
                break;

            case TIFFdataType.Short:
                content = new ushort[count];
                for (int i = 0; i < count; i++)
                {
                    ((ushort[])content)[i] = reader.ReadUInt16();
                }
                break;

            case TIFFdataType.Long:
                content = new uint[count];
                for (int i = 0; i < count; i++)
                {
                    ((uint[])content)[i] = reader.ReadUInt32();
                }
                break;

            case TIFFdataType.Rational:
                content = new uint[count * 2];
                for (int i = 0; i < 2 * count; i++)
                {
                    ((uint[])content)[i] = reader.ReadUInt32();
                }
                break;

            case TIFFdataType.SignedByte:
                content = new sbyte[count];
                for (int i = 0; i < count; i++)
                {
                    ((sbyte[])content)[i] = reader.ReadSByte();
                }
                break;

            case TIFFdataType.SignedShort:
                content = new short[count];
                for (int i = 0; i < count; i++)
                {
                    ((short[])content)[i] = reader.ReadInt16();
                }
                break;

            case TIFFdataType.SignedLong:
                content = new int[count];
                for (int i = 0; i < count; i++)
                {
                    ((int[])content)[i] = reader.ReadInt32();
                }
                break;

            case TIFFdataType.SignedRational:
                content = new int[count * 2];
                for (int i = 0; i < 2 * count; i++)
                {
                    ((int[])content)[i] = reader.ReadInt32();
                }
                break;

            case TIFFdataType.Float:
                content = new float[count];
                for (int i = 0; i < count; i++)
                {
                    ((float[])content)[i] = reader.ReadSingle();
                }
                break;

            case TIFFdataType.Double:
                content = new double[count];
                for (int i = 0; i < count; i++)
                {
                    ((double[])content)[i] = reader.ReadDouble();
                }
                break;

            default:
                content = new Object[0];
                break;
            }
        }
Esempio n. 44
0
        // Per spot:
        // uint32 magic
        // uint32 reserved;
        // uint32 flags;
        // float x;
        // float y;
        // float z;
        // uint32 no_paths
        //   for each path
        //     float x;
        //     float y;
        //     float z;

        public bool Load(string baseDir)
        {
            string fileName    = FileName();
            string filenamebin = baseDir + fileName;

            System.IO.Stream       stream = null;
            System.IO.BinaryReader file   = null;
            int n_spots = 0;
            int n_steps = 0;

            try
            {
                stream = System.IO.File.OpenRead(filenamebin);
                if (stream != null)
                {
                    file = new System.IO.BinaryReader(stream);
                    if (file != null)
                    {
                        uint magic = file.ReadUInt32();
                        if (magic == FILE_MAGIC)
                        {
                            uint type;
                            while ((type = file.ReadUInt32()) != FILE_ENDMAGIC)
                            {
                                n_spots++;
                                uint  reserved = file.ReadUInt32();
                                uint  flags    = file.ReadUInt32();
                                float x        = file.ReadSingle();
                                float y        = file.ReadSingle();
                                float z        = file.ReadSingle();
                                uint  n_paths  = file.ReadUInt32();
                                if (x != 0 && y != 0)
                                {
                                    Spot s = new Spot(x, y, z);
                                    s.flags = flags;

                                    for (uint i = 0; i < n_paths; i++)
                                    {
                                        n_steps++;
                                        float sx = file.ReadSingle();
                                        float sy = file.ReadSingle();
                                        float sz = file.ReadSingle();
                                        s.AddPathTo(sx, sy, sz);
                                    }
                                    AddSpot(s);
                                }
                            }
                        }
                    }
                }
            }
            catch (System.IO.FileNotFoundException e)
            {
                logger.Debug(e.Message);
            }
            catch (System.IO.DirectoryNotFoundException e)
            {
                logger.Debug(e.Message);
            }
            catch (Exception e)
            {
                logger.Debug(e.Message);
            }

            if (file != null)
            {
                file.Close();
            }
            if (stream != null)
            {
                stream.Close();
            }

            Log("Loaded " + fileName + " " + n_spots + " spots " + n_steps + " steps");

            modified = false;
            return(false);
        }
Esempio n. 45
0
        private void btnFix_Click(object sender, EventArgs e)
        {
            System.IO.FileStream stream = null;
            try
            {
                stream = new System.IO.FileStream(txtFile.Text, System.IO.FileMode.Open);
                System.IO.BinaryReader fileR = new System.IO.BinaryReader(stream);
                System.IO.BinaryWriter fileW = new System.IO.BinaryWriter(stream);

                ushort offset = ushort.Parse(txtOffset.Text, System.Globalization.NumberStyles.HexNumber);
                ushort size   = ushort.Parse(txtSize.Text, System.Globalization.NumberStyles.HexNumber);

                ushort vtOffset  = FixOffsetAt(fileR, fileW, 0x02, offset, size); //v-table offset
                ushort refOffset = FixOffsetAt(fileR, fileW, 0x06, offset, size); //references to offsets to fix in-game
                FixOffsetAt(fileR, fileW, 0x10, offset, size);                    //spawn function

                stream.Position = 0x04;
                ushort vtCount = fileR.ReadUInt16();
                stream.Position = 0x08;
                ushort refCount = fileR.ReadUInt16();

                stream.Position = vtOffset;
                for (ushort i = 0; i < vtCount; ++i)
                {
                    uint funcPtr = fileR.ReadUInt32();
                    if ((funcPtr & 0xF0000000) != 0)
                    {
                        FixOffsetAt(fileR, fileW, (ushort)(stream.Position - 4), offset, size);
                        stream.Position += 2;
                    }
                }

                for (ushort i = 0; i < refCount; ++i)
                {
                    stream.Position = refOffset + 2 * i;
                    ushort oldVarOffset = fileR.ReadUInt16();
                    ushort varOffset    = FixOffsetAt(fileR, fileW, (ushort)(refOffset + 2 * i), offset, size);

                    //remove references whose referencees (notice: 2 e's in a row)
                    //have been deleted
                    if (varOffset < oldVarOffset && varOffset < offset || varOffset > stream.Length)
                    {
                        stream.Position = refOffset + 2 * i;
                        fileW.Write((ushort)0x0000);
                    }
                    else
                    {
                        stream.Position = varOffset;
                        uint varPtr = fileR.ReadUInt32();
                        if ((varPtr & 0xF0000000) == 0)
                        {
                            FixOffsetAt(fileR, fileW, varOffset, offset, size);
                        }
                    }
                }

                ushort j = 0;
                for (ushort i = 0; i < refCount; ++i, ++j)
                {
                    stream.Position = refOffset + 2 * i;
                    ushort varOffset = fileR.ReadUInt16();

                    if (varOffset == 0x0000)
                    {
                        --j;
                        continue;
                    }

                    stream.Position = refOffset + 2 * j;
                    fileW.Write(varOffset);
                }

                stream.Position = 0x08;
                fileW.Write(j); //new reference count
                stream.SetLength(refOffset + 2 * j);

                stream.Close();
                MessageBox.Show("Operation complete! Now go fix the offsets for loading constants.", "Good!", MessageBoxButtons.OK);
            }
            catch (Exception ex)
            {
                if (stream != null)
                {
                    stream.Close();
                }

                new ExceptionMessageBox("Error", ex).ShowDialog();
                return;
            }
        }
Esempio n. 46
0
        /////////PARENTS FUNCTION//////////
        protected override void DataUpdate()
        {
            System.IO.BinaryReader BSReader = new System.IO.BinaryReader(ByteStream);
            ByteStream.Position = 0;
            Array.Resize(ref E3, 0);
            Header          = BSReader.ReadUInt32();
            LevelNameLength = BSReader.ReadUInt32();
            LevelName       = BSReader.ReadChars((int)LevelNameLength).ToString();
            Flags           = BSReader.ReadUInt32();
            EntryHeader     = BSReader.ReadUInt32();
            NullByte        = BSReader.ReadByte();
            SBID            = BSReader.ReadUInt32();
            uint tmp = 0;
            int  p   = (int)ByteStream.Position;

            while ((!(tmp == 5651)) && (ByteStream.Position < ByteStream.Length))
            {
                tmp = BSReader.ReadByte();
                if (tmp == 19)
                {
                    ByteStream.Position -= 1;
                    tmp = BSReader.ReadUInt32();
                    if (!(tmp == 5651))
                    {
                        ByteStream.Position -= 3;
                    }
                    else
                    {
                        ByteStream.Position -= 4;
                    }
                }
            }
            p = (int)ByteStream.Position - p;
            ByteStream.Position -= p;
            Garbadge             = BSReader.ReadBytes(p);
            if (tmp == 5651 && (ByteStream.Position < ByteStream.Length))
            {
                while ((ByteStream.Position < ByteStream.Length))
                {
                    Entry3 withBlock = new Entry3();
                    {
                        withBlock.EntryHeader = BSReader.ReadUInt32();
                        withBlock.GCCount     = BSReader.ReadUInt16();
                        withBlock.SBCount     = BSReader.ReadUInt16();
                        Array.Resize(ref withBlock.Vector1, withBlock.GCCount + withBlock.SBCount);
                        Array.Resize(ref withBlock.Vector2, withBlock.GCCount + withBlock.SBCount);
                        Array.Resize(ref withBlock.GCID, withBlock.GCCount);
                        Array.Resize(ref withBlock.SBID, withBlock.SBCount);
                        Array.Resize(ref withBlock.ChunkMatrix, withBlock.GCCount + withBlock.SBCount);
                        for (int i = 0; i <= withBlock.GCCount + withBlock.SBCount - 1; i++)
                        {
                            withBlock.Vector1[i].X = BSReader.ReadSingle();
                            withBlock.Vector1[i].Y = BSReader.ReadSingle();
                            withBlock.Vector1[i].Z = BSReader.ReadSingle();
                            withBlock.Vector1[i].W = BSReader.ReadSingle();
                            withBlock.Vector2[i].X = BSReader.ReadSingle();
                            withBlock.Vector2[i].Y = BSReader.ReadSingle();
                            withBlock.Vector2[i].Z = BSReader.ReadSingle();
                            withBlock.Vector2[i].W = BSReader.ReadSingle();
                        }
                        for (int i = 0; i <= withBlock.GCCount - 1; i++)
                        {
                            withBlock.GCID[i] = BSReader.ReadUInt32();
                        }
                        for (int i = 0; i <= withBlock.SBCount - 1; i++)
                        {
                            withBlock.SBID[i] = BSReader.ReadUInt32();
                        }
                        for (int i = 0; i <= withBlock.GCCount + withBlock.SBCount - 1; i++)
                        {
                            withBlock.ChunkMatrix[i].x1 = BSReader.ReadSingle();
                            withBlock.ChunkMatrix[i].y1 = BSReader.ReadSingle();
                            withBlock.ChunkMatrix[i].z1 = BSReader.ReadSingle();
                            withBlock.ChunkMatrix[i].w1 = BSReader.ReadSingle();
                            withBlock.ChunkMatrix[i].x2 = BSReader.ReadSingle();
                            withBlock.ChunkMatrix[i].y2 = BSReader.ReadSingle();
                            withBlock.ChunkMatrix[i].z2 = BSReader.ReadSingle();
                            withBlock.ChunkMatrix[i].w2 = BSReader.ReadSingle();
                            withBlock.ChunkMatrix[i].x3 = BSReader.ReadSingle();
                            withBlock.ChunkMatrix[i].y3 = BSReader.ReadSingle();
                            withBlock.ChunkMatrix[i].z3 = BSReader.ReadSingle();
                            withBlock.ChunkMatrix[i].w3 = BSReader.ReadSingle();
                            withBlock.ChunkMatrix[i].x4 = BSReader.ReadSingle();
                            withBlock.ChunkMatrix[i].y4 = BSReader.ReadSingle();
                            withBlock.ChunkMatrix[i].z4 = BSReader.ReadSingle();
                            withBlock.ChunkMatrix[i].w4 = BSReader.ReadSingle();
                        }
                        tmp = 0;
                        var len = ByteStream.Position;
                        while ((tmp != 5651) & (ByteStream.Position < ByteStream.Length))
                        {
                            tmp = BSReader.ReadByte();
                            if (tmp == 19)
                            {
                                ByteStream.Position -= 1;
                                tmp = BSReader.ReadUInt32();
                                if (tmp != 5651)
                                {
                                    ByteStream.Position -= 3;
                                }
                                else
                                {
                                    ByteStream.Position -= 4;
                                }
                            }
                        }
                        len = ByteStream.Position - len;
                        ByteStream.Position -= len;
                        withBlock.leftovers  = BSReader.ReadBytes((int)len);
                    }
                    _Entries.Add(withBlock);
                }
                E3 = _Entries.ToArray();
            }
        }
Esempio n. 47
0
        /// <summary>
        /// Unserializes a BinaryStream into the Attributes of this Instance
        /// </summary>
        /// <param name="reader">The Stream that contains the FileData</param>
        protected override void Unserialize(System.IO.BinaryReader reader)
        {
            ver       = reader.ReadUInt16();
            subver    = reader.ReadUInt16();
            sz.Width  = reader.ReadInt32();
            sz.Height = reader.ReadInt32();
            type      = (LotType)reader.ReadByte();

            roads     = reader.ReadByte();
            rotation  = (Rotation)reader.ReadByte();
            unknown_0 = reader.ReadUInt32();

            lotname     = StreamHelper.ReadString(reader);
            description = StreamHelper.ReadString(reader);

            unknown_1 = new List <float>();
            int len = reader.ReadInt32();

            for (int i = 0; i < len; i++)
            {
                this.unknown_1.Add(reader.ReadSingle());
            }

            if (subver >= (UInt16)LtxtSubVersion.Voyage)
            {
                unknown_3 = reader.ReadSingle();
            }
            else
            {
                unknown_3 = 0;
            }
            if (subver >= (UInt16)LtxtSubVersion.Freetime)
            {
                unknown_4 = reader.ReadUInt32();
            }
            else
            {
                unknown_4 = 0;
            }

            if (ver >= (UInt16)LtxtVersion.Apartment || subver >= (UInt16)LtxtSubVersion.Apartment)
            {
                unknown_5 = reader.ReadBytes(14);
            }
            else
            {
                unknown_5 = new byte[0];
            }

            int y = reader.ReadInt32();
            int x = reader.ReadInt32();

            loc = new Point(x, y);

            elevation   = reader.ReadSingle();
            lotInstance = reader.ReadUInt32();
            orient      = (LotOrientation)reader.ReadByte();

            texture = StreamHelper.ReadString(reader);

            unknown_2 = reader.ReadByte();

            if (ver >= (int)LtxtVersion.Business)
            {
                owner = reader.ReadUInt32();
            }
            else
            {
                owner = 0;
            }

            if (ver >= (UInt16)LtxtVersion.Apartment || subver >= (UInt16)LtxtSubVersion.Apartment)
            {
                int count;

                apartmentBase = reader.ReadUInt32();
                unknown_6     = reader.ReadBytes(9);

                subLots = new List <SubLot>();
                count   = reader.ReadInt32();
                for (int i = 0; i < count; i++)
                {
                    subLots.Add(new SubLot(reader));
                }

                unknown_7 = new List <uint>();
                count     = reader.ReadInt32();
                for (int i = 0; i < count; i++)
                {
                    unknown_7.Add(reader.ReadUInt32());
                }
            }
            else
            {
                apartmentBase = 0;
                unknown_6     = new byte[0];
                subLots       = new List <SubLot>();
                unknown_7     = new List <uint>();
            }

            followup = reader.ReadBytes((int)(reader.BaseStream.Length - reader.BaseStream.Position));
        }
Esempio n. 48
0
 /// <summary>
 /// Unserializes a BinaryStream into the Attributes of this Instance
 /// </summary>
 /// <param name="reader">The Stream that contains the FileData</param>
 internal void UnserializeData(System.IO.BinaryReader reader)
 {
     datai[0] = reader.ReadUInt32();
     datai[1] = reader.ReadUInt32();
 }
Esempio n. 49
0
        protected override void Unserialize(System.IO.BinaryReader reader)
        {
            uint count;

            setVersion(reader.ReadUInt32());

            count = version >= 0x05 ? reader.ReadUInt32() : 0;
            for (int i = 0; i < count; i++)
            {
                items.Add(new SWAFItem(this, SWAFItem.SWAFItemType.LifetimeWants, reader));
            }

            maxWants = version >= 0x05 ? reader.ReadUInt32() : (uint)oldMaxWants;

            count = reader.ReadUInt32();
            for (int i = 0; i < count; i++)
            {
                items.Add(new SWAFItem(this, SWAFItem.SWAFItemType.Wants, reader));
            }

            maxFears = version >= 0x05 ? reader.ReadUInt32() : (uint)oldMaxFears;

            count = reader.ReadUInt32();
            for (int i = 0; i < count; i++)
            {
                items.Add(new SWAFItem(this, SWAFItem.SWAFItemType.Fears, reader));
            }

            unknown3 = version >= 0x05 ? reader.ReadUInt32() : 0;
            unknown1 = reader.ReadUInt32();
            unknown2 = reader.ReadUInt32();

            count = reader.ReadUInt32();
            for (int i = 0; i < count; i++)
            {
                uint            key    = reader.ReadUInt32();
                List <SWAFItem> value  = new List <SWAFItem>();
                uint            hcount = reader.ReadUInt32();
                for (int j = 0; j < hcount; j++)
                {
                    value.Add(new SWAFItem(this, SWAFItem.SWAFItemType.History, reader));
                }
                history.Add(key, value);
            }

            unknown4 = reader.ReadBytes((int)(reader.BaseStream.Length - reader.BaseStream.Position));
        }
Esempio n. 50
0
        public void Populate(int iOffset, int iIndexedReflexiveOffset)
        {
            this.isNulledOutReflexive = false;
            System.IO.BinaryReader BR = new System.IO.BinaryReader(meta.MS);

            int mapMetaOffset = meta.offset;

            if (this._EntIndex.reflexiveTagType + this._EntIndex.reflexiveTagName != string.Empty)
            {
                int tagNum = map.Functions.ForMeta.FindByNameAndTagType(this._EntIndex.reflexiveTagType, this._EntIndex.reflexiveTagName);
                if (tagNum != -1)
                {
                    Meta meta2 = new Meta(map);
                    map.OpenMap(MapTypes.Internal);
                    meta2.ReadMetaFromMap(tagNum, true);
                    map.CloseMap();
                    mapMetaOffset = meta2.offset;
                    this._EntIndex.reflexiveLayer = "root";
                }
            }

            if (this._EntIndex.reflexiveLayer.ToLower() == "root")
            {
                this._IndexedReflexiveOffset = mapMetaOffset + this._EntIndex.ReflexiveOffset;
            }
            else if (this._EntIndex.reflexiveLayer.ToLower() == "oneup")
            {
                this._IndexedReflexiveOffset = iIndexedReflexiveOffset + this._EntIndex.ReflexiveOffset;
            }

            /*
             * bool openedMap = false;
             * if (map.isOpen == false)
             * {
             *  map.OpenMap(MapTypes.Internal);
             *  openedMap = true;
             * }
             * map.BA.Position = iOffset + this.chunkOffset;
             */
            BR.BaseStream.Position = iOffset + this.chunkOffset;
            this.offsetInMap       = meta.offset + iOffset + this.chunkOffset;

            switch (_ValueType)
            {
            case IFPIO.ObjectEnum.Short:
            {
                this.Value = (int)BR.ReadInt16();
                break;
            }

            case IFPIO.ObjectEnum.Int:
            {
                this.Value = BR.ReadInt32();
                break;
            }

            case IFPIO.ObjectEnum.UShort:
            {
                this.Value = (int)BR.ReadUInt16();
                break;
            }

            case IFPIO.ObjectEnum.UInt:
            {
                this.Value = (int)BR.ReadUInt32();
                break;
            }

            case IFPIO.ObjectEnum.Byte:
            {
                this.Value = (int)BR.ReadByte();
                break;
            }
            }
            UpdateSelectionList(false);

            /*
             * if (openedMap == true)
             *  map.CloseMap();
             */
        }
Esempio n. 51
0
 /// <summary>
 /// Return an array of bytes without the length prefix and the spoofed suffix.
 /// </summary>
 /// <param name="bytes">The byte array previously encoded with the Spoof method.</param>
 /// <returns>The resulting array is the signal found in the bytes: { byte[4] signal length} + { byte[] signal } + { byte[] noise }.</returns>
 public static byte[] Despoof(byte[] bytes)
 {
     System.IO.BinaryReader reader = new System.IO.BinaryReader(new System.IO.MemoryStream(bytes, 0, bytes.Length));
     int length = (int)reader.ReadUInt32();
     byte[] message = reader.ReadBytes(length);
     return message;
 }
Esempio n. 52
0
        // Per spot:
        // uint32 magic
        // uint32 reserved;
        // uint32 flags;
        // float x;
        // float y;
        // float z;
        // uint32 no_paths
        //   for each path
        //     float x;
        //     float y;
        //     float z;
        public bool Load(string baseDir)
        {
            string fileName = FileName();
            string filenamebin = baseDir + fileName;

            System.IO.Stream stream = null;
            System.IO.BinaryReader file = null;
            int n_spots = 0;
            int n_steps = 0;
            try
            {
                stream = System.IO.File.OpenRead(filenamebin);
                if (stream != null)
                {
                    file = new System.IO.BinaryReader(stream);
                    if (file != null)
                    {
                        uint magic = file.ReadUInt32();
                        if (magic == FILE_MAGIC)
                        {

                            uint type;
                            while ((type = file.ReadUInt32()) != FILE_ENDMAGIC)
                            {
                                n_spots++;
                                uint reserved = file.ReadUInt32();
                                uint flags = file.ReadUInt32();
                                float x = file.ReadSingle();
                                float y = file.ReadSingle();
                                float z = file.ReadSingle();
                                uint n_paths = file.ReadUInt32();
                                if (x != 0 && y != 0)
                                {
                                    Spot s = new Spot(x, y, z);
                                    s.flags = flags;

                                    for (uint i = 0; i < n_paths; i++)
                                    {
                                        n_steps++;
                                        float sx = file.ReadSingle();
                                        float sy = file.ReadSingle();
                                        float sz = file.ReadSingle();
                                        s.AddPathTo(sx, sy, sz);
                                    }
                                    AddSpot(s);
                                }
                            }
                        }
                    }
                }
            }
            catch (System.IO.FileNotFoundException e)
            {
                Console.WriteLine(e.Message);
            }
            catch (System.IO.DirectoryNotFoundException e)
            {
                Console.WriteLine(e.Message);
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
            }

            if (file != null)
            {
                file.Close();
            }
            if (stream != null)
            {
                stream.Close();
            }

            Log("Loaded " + fileName + " " + n_spots + " spots " + n_steps + " steps");

            modified = false;
            return false;
        }
Esempio n. 53
0
        /// <summary>
        /// Processes the Sniffer packet record header
        /// </summary>
        /// <param name="theBinaryReader">The object that provides for binary reading from the packet capture</param>
        /// <param name="thePacketNumber">The number for the packet read from the packet capture</param>
        /// <param name="thePacketPayloadLength">The payload length of the packet read from the packet capture</param>
        /// <param name="thePacketTimestamp">The timestamp for the packet read from the packet capture</param>
        /// <returns>Boolean flag that indicates whether the Sniffer packet record header could be processed</returns>
        protected override bool ProcessPacketHeader(System.IO.BinaryReader theBinaryReader, ref ulong thePacketNumber, out long thePacketPayloadLength, out double thePacketTimestamp)
        {
            bool theResult = true;

            if (theBinaryReader == null)
            {
                throw new System.ArgumentNullException("theBinaryReader");
            }

            // Provide a default value to the output parameter for the length of the Sniffer packet payload
            thePacketPayloadLength = 0;

            // Provide a default value to the output parameter for the timestamp
            thePacketTimestamp = 0.0;

            // Read off and store the Sniffer packet record header type from the packet capture for use below
            ushort theRecordType = theBinaryReader.ReadUInt16();

            // Just read off the Sniffer packet record header record length so we can move on
            theBinaryReader.ReadUInt32();

            theResult = this.ValidateRecordHeader(theRecordType);

            if (theResult)
            {
                switch (theRecordType)
                {
                case (ushort)Constants.RecordHeaderSnifferRecordType.Type2RecordType:
                {
                    //// We have got a Sniffer type 2 data record

                    // Increment the number for the packet read from the packet capture for a Sniffer type 2 data record
                    ++thePacketNumber;

                    // Just read off the data for the Sniffer type 2 data record from the packet capture so we can move on
                    // Some of the data will be stored for use below
                    ushort theTimestampLow    = theBinaryReader.ReadUInt16();
                    ushort theTimestampMiddle = theBinaryReader.ReadUInt16();
                    byte   theTimestampHigh   = theBinaryReader.ReadByte();
                    theBinaryReader.ReadByte();         // Time Days
                    short theSize = theBinaryReader.ReadInt16();
                    theBinaryReader.ReadByte();         // Frame error status bits
                    theBinaryReader.ReadByte();         // Flags
                    theBinaryReader.ReadInt16();        // True size
                    theBinaryReader.ReadInt16();        // Reserved

                    // Set up the output parameter for the length of the Sniffer packet payload
                    // Subtract the normal Ethernet trailer of twelve bytes as this would typically not be exposed in the packet capture
                    thePacketPayloadLength = theSize - 12;

                    // Set up the output parameter for the timestamp based on the supplied timestamp slice and the timestamp from the Sniffer type 2 data record
                    // This is the number of seconds passed on this particular day
                    // To match up with a timestamp displayed since epoch would have to get the value of the Date field from the Sniffer packet capture global header
                    thePacketTimestamp =
                        (this.PacketCaptureTimestampAccuracy * (theTimestampHigh * 4294967296)) +
                        (this.PacketCaptureTimestampAccuracy * (theTimestampMiddle * 65536)) +
                        (this.PacketCaptureTimestampAccuracy * theTimestampLow);

                    break;
                }

                case (ushort)Constants.RecordHeaderSnifferRecordType.EndOfFileRecordType:
                {
                    //// We have got a Sniffer end of file record

                    //// No further reading required for the Sniffer end of file record as it only consists of the Sniffer packet capture record header!

                    //// Do not increment the number for the packet read from the packet capture for a Sniffer end of file record as it will not show in Wireshark and so would confuse comparisons with other formats

                    break;
                }

                default:
                {
                    //// We have got an Sniffer packet capture containing an unknown record type

                    // Increment the number for the packet read from the packet capture for an unknown Sniffer packet capture record
                    ++thePacketNumber;

                    //// Processing of Sniffer packet captures with record types not enumerated above is obviously not currently supported!

                    this.TheDebugInformation.WriteErrorEvent(
                        "The Sniffer packet capture contains an unexpected record type of " +
                        theRecordType.ToString(System.Globalization.CultureInfo.CurrentCulture) +
                        "!!!");

                    theResult = false;

                    break;
                }
                }
            }

            return(theResult);
        }
Esempio n. 54
0
		public static void DeserializeVoxelAreaCompactData (byte[] bytes, VoxelArea target) {
#if !ASTAR_RECAST_CLASS_BASED_LINKED_LIST
			System.IO.MemoryStream stream = new System.IO.MemoryStream(bytes);
			System.IO.BinaryReader reader = new System.IO.BinaryReader(stream);
			int width = reader.ReadInt32();
			int depth = reader.ReadInt32();
			if (target.width != width) throw new System.ArgumentException ("target VoxelArea has a different width than the data ("+target.width + " != " + width + ")");
			if (target.depth != depth) throw new System.ArgumentException ("target VoxelArea has a different depth than the data ("+target.depth + " != " + depth + ")");
			CompactVoxelCell[] cells = new CompactVoxelCell[reader.ReadInt32()];
			CompactVoxelSpan[] spans = new CompactVoxelSpan[reader.ReadInt32()];
			int[] areas = new int[reader.ReadInt32()];
			
			for (int i=0;i<cells.Length;i++) {
				cells[i].index = reader.ReadUInt32();
				cells[i].count = reader.ReadUInt32();
			}
			for (int i=0;i<spans.Length;i++) {
				spans[i].con = reader.ReadUInt32();
				spans[i].h = reader.ReadUInt32();
				spans[i].reg = reader.ReadInt32();
				spans[i].y = reader.ReadUInt16();
			}
			for (int i=0;i<areas.Length;i++) {
				areas[i] = reader.ReadInt32();
			}
			
			target.compactCells = cells;
			target.compactSpans = spans;
			target.areaTypes = areas;
#else
			throw new System.NotImplementedException ("This method only works with !ASTAR_RECAST_CLASS_BASED_LINKED_LIST");
#endif
		}
Esempio n. 55
0
        /// <summary>
        /// Processes the Sniffer packet capture global header
        /// </summary>
        /// <param name="theBinaryReader">The object that provides for binary reading from the packet capture</param>
        /// <returns>Boolean flag that indicates whether the Sniffer packet capture global header could be processed</returns>
        protected override bool ProcessPacketCaptureGlobalHeader(System.IO.BinaryReader theBinaryReader)
        {
            bool theResult = true;

            if (theBinaryReader == null)
            {
                throw new System.ArgumentNullException("theBinaryReader");
            }

            // Just read off the data for the Sniffer packet capture global header from the packet capture so we can move on
            // Some of the data will be stored for use below
            ulong  theMagicNumberHigh       = theBinaryReader.ReadUInt64();
            ulong  theMagicNumberLow        = theBinaryReader.ReadUInt64();
            byte   theMagicNumberTerminator = theBinaryReader.ReadByte();
            ushort theRecordType            = theBinaryReader.ReadUInt16();

            theBinaryReader.ReadUInt32(); // Record length
            short theVersionMajor = theBinaryReader.ReadInt16();
            short theVersionMinor = theBinaryReader.ReadInt16();

            theBinaryReader.ReadInt16(); // Time
            theBinaryReader.ReadInt16(); // Date
            sbyte theType = theBinaryReader.ReadSByte();
            byte  theNetworkEncapsulationType = theBinaryReader.ReadByte();
            sbyte theFormatVersion            = theBinaryReader.ReadSByte();
            byte  theTimestampUnits           = theBinaryReader.ReadByte();

            theBinaryReader.ReadSByte(); // Compression version
            theBinaryReader.ReadSByte(); // Compression level
            theBinaryReader.ReadInt32(); // Reserved

            // Validate fields from the Sniffer packet capture global header
            theResult = this.ValidateGlobalHeader(
                theMagicNumberHigh,
                theMagicNumberLow,
                theMagicNumberTerminator,
                theRecordType,
                theVersionMajor,
                theVersionMinor,
                theType,
                theNetworkEncapsulationType,
                theFormatVersion);

            if (theResult)
            {
                // Set up the value for the network data link type
                this.PacketCaptureNetworkDataLinkType =
                    theNetworkEncapsulationType;

                double thePacketCaptureTimestampAccuracy = 0.0;

                // Derive the value for the timestamp accuracy (actually a timestamp slice for a Sniffer packet capture) from the timestamp units in the Sniffer packet capture global header
                theResult = this.CalculateTimestampAccuracy(
                    theTimestampUnits,
                    out thePacketCaptureTimestampAccuracy);

                // Set up the value for the timestamp accuracy
                this.PacketCaptureTimestampAccuracy =
                    thePacketCaptureTimestampAccuracy;
            }

            return(theResult);
        }
Esempio n. 56
0
 public DDS(System.IO.Stream fileStream)
 {
     using (System.IO.BinaryReader b = new System.IO.BinaryReader(fileStream)) {
         b.BaseStream.Position = 12;
         header.height = b.ReadUInt32();
         header.width = b.ReadUInt32();
         b.BaseStream.Position += 8;
         header.mipMapCount = b.ReadUInt32();
         b.BaseStream.Position += 52;
         header.ddspf.fourCC = b.ReadUInt32();
         header.ddspf.rGBBitCount = b.ReadUInt32();
         b.BaseStream.Position += 20;
         header.caps2 = (DDS_HEADER.Caps2)b.ReadUInt32();
         b.BaseStream.Position += 12;
         int count = 0;
         if ((uint)header.caps2 != 0) {
             bdata2 = new Dictionary<int, byte[]>();
             if ((header.caps2 & DDS_HEADER.Caps2.DDSCAPS2_CUBEMAP_POSITIVEX) == DDS_HEADER.Caps2.DDSCAPS2_CUBEMAP_POSITIVEX) {
                 count++;
                 bdata2.Add(0, null);
             } else {
                 bdata2.Add(-1, null);
             }
             if ((header.caps2 & DDS_HEADER.Caps2.DDSCAPS2_CUBEMAP_NEGATIVEX) == DDS_HEADER.Caps2.DDSCAPS2_CUBEMAP_NEGATIVEX) {
                 count++;
                 bdata2.Add(1, null);
             } else {
                 bdata2.Add(-2, null);
             }
             if ((header.caps2 & DDS_HEADER.Caps2.DDSCAPS2_CUBEMAP_POSITIVEY) == DDS_HEADER.Caps2.DDSCAPS2_CUBEMAP_POSITIVEY) {
                 count++;
                 bdata2.Add(2, null);
             } else {
                 bdata2.Add(-3, null);
             }
             if ((header.caps2 & DDS_HEADER.Caps2.DDSCAPS2_CUBEMAP_NEGATIVEY) == DDS_HEADER.Caps2.DDSCAPS2_CUBEMAP_NEGATIVEY) {
                 count++;
                 bdata2.Add(3, null);
             } else {
                 bdata2.Add(-4, null);
             }
             if ((header.caps2 & DDS_HEADER.Caps2.DDSCAPS2_CUBEMAP_POSITIVEZ) == DDS_HEADER.Caps2.DDSCAPS2_CUBEMAP_POSITIVEZ) {
                 count++;
                 bdata2.Add(4, null);
             } else {
                 bdata2.Add(-5, null);
             }
             if ((header.caps2 & DDS_HEADER.Caps2.DDSCAPS2_CUBEMAP_NEGATIVEZ) == DDS_HEADER.Caps2.DDSCAPS2_CUBEMAP_NEGATIVEZ) {
                 count++;
                 bdata2.Add(5, null);
             } else {
                 bdata2.Add(-6, null);
             }
             if (count > 0) {
                 int length = (int)((b.BaseStream.Length - (long)128) / (long)count);
                 //System.Windows.Forms.MessageBox.Show(count.ToString() + "  " + length.ToString());
                 for (int i = 0; i < bdata2.Count; i++) {
                     if (bdata2.ContainsKey(i) == true) {
                         bdata2[i] = b.ReadBytes(length);
                     }
                 }
             } else {
                 throw new Exception("Loading cubemap failed because not all blocks were found. (Read)");
             }
         } else {
             bdata = b.ReadBytes((int)(b.BaseStream.Length - (long)128));
         }
     }
 }
Esempio n. 57
0
File: Row.cs Progetto: vebin/BD2
 public static Row Deserialize(byte[] bytes)
 {
     using (System.IO.MemoryStream MS = new System.IO.MemoryStream (bytes, false)) {
         using (System.IO.BinaryReader BR = new System.IO.BinaryReader (MS)) {
             byte[] columnSet = BR.ReadBytes (32);
             int FieldCount = BR.ReadInt32 ();
             object[] fields = new object[FieldCount];
             ColumnSet cs = css [columnSet];
             if (cs.Columns.Length != fields.Length)
                 throw new Exception ();
             for (int n = 0; n != fields.Length; n++) {
                 bool Null = BR.ReadBoolean ();
                 if (Null) {
                     fields [n] = null;
                     continue;
                 }
                 switch (cs.Columns [n].TFQN) {
                 case "System.Byte[]":
                     fields [n] = BR.ReadBytes (BR.ReadInt32 ());
                     break;
                 case "System.Byte":
                     fields [n] = BR.ReadByte ();
                     break;
                 case "System.SByte":
                     fields [n] = BR.ReadSByte ();
                     break;
                 case "System.Int16":
                     fields [n] = BR.ReadInt16 ();
                     break;
                 case "System.UInt16":
                     fields [n] = BR.ReadUInt16 ();
                     break;
                 case "System.Int32":
                     fields [n] = BR.ReadInt32 ();
                     break;
                 case "System.UInt32":
                     fields [n] = BR.ReadUInt32 ();
                     break;
                 case "System.Int64":
                     fields [n] = BR.ReadInt64 ();
                     break;
                 case "System.UInt64":
                     fields [n] = BR.ReadUInt64 ();
                     break;
                 case "System.Single":
                     fields [n] = BR.ReadSingle ();
                     break;
                 case "System.Double":
                     fields [n] = BR.ReadDouble ();
                     break;
                 case "System.String":
                     fields [n] = BR.ReadString ();
                     break;
                 case "System.Char":
                     fields [n] = BR.ReadChar ();
                     break;
                 case "System.Boolean":
                     fields [n] = BR.ReadBoolean ();
                     break;
                 case "System.DateTime":
                     fields [n] = new DateTime (BR.ReadInt64 ());
                     break;
                 case "System.Guid":
                     fields [n] = new Guid (BR.ReadBytes (16));
                     break;
                 }
             }
             return new Row (cs, fields);
         }
     }
 }