Esempio n. 1
0
        public void initVisibilityEditor(bool isShadow, string fileName)
        {
            if (isShadow)
            {
                openVisibilityFile = null;
                byte[] bytes = File.ReadAllBytes(fileName);
                ChunkList           = LoadShadowVisibilityFile(Archive.FromONEFile(ref bytes));
                labelLoadedBLK.Text = "";
            }
            else
            {
                openVisibilityFile  = fileName;
                ChunkList           = loadHeroesVisibilityFile(openVisibilityFile);
                labelLoadedBLK.Text = "Loaded " + fileName;
            }

            numericCurrentChunk.Minimum = 1;
            numericCurrentChunk.Maximum = ChunkList.Count();
            numericCurrentChunk.Value   = ChunkList.Count();
            if (numericCurrentChunk.Maximum != 0)
            {
                numericCurrentChunk.Value = 1;
            }

            labelChunkAmount.Text = "Amount: " + ChunkList.Count();
        }
Esempio n. 2
0
        private void importToolStripMenuItem_Click(object sender, EventArgs e)
        {
            OpenFileDialog openFile = new OpenFileDialog()
            {
                Filter = "All supported files|*.bin;*.bdt|BIN files|*.bin|BDT files|*.bdt"
            };

            if (openFile.ShowDialog() == DialogResult.OK)
            {
                if (Path.GetExtension(openFile.FileName).ToLower() == ".bdt")
                {
                    ChunkList.AddRange(LoadShadowVisibilityFile(new FileStream(openFile.FileName, FileMode.Open)));
                }
                else if (Path.GetExtension(openFile.FileName).ToLower() == ".bin")
                {
                    ChunkList.AddRange(loadHeroesVisibilityFile(openFile.FileName));
                }

                numericCurrentChunk.Minimum = 1;
                numericCurrentChunk.Maximum = ChunkList.Count();
                numericCurrentChunk.Value   = ChunkList.Count();
                if (numericCurrentChunk.Maximum != 0)
                {
                    numericCurrentChunk.Value = 1;
                }

                labelChunkAmount.Text = "Amount: " + ChunkList.Count();
            }
        }
Esempio n. 3
0
        void AddSlopedTile(Point3D p, ChunkList chunks, int row, int col, int color_index)
        {
            double x2  = p.X + Tile.SIZE;
            double z2  = p.Z + Tile.SIZE;
            int    y11 = chunks.GetTileAt(row, col).Height;
            int    y21 = chunks.GetTileAt(row + 1, col).Height;

            int y12 = y11;
            int y22 = y21;

            if (col < TileRow.NUM_COLUMNS - 1)
            {
                y12 = chunks.GetTileAt(row, col + 1).Height;
                y22 = chunks.GetTileAt(row + 1, col + 1).Height;
            }

            // adjust slope color to reflect tile height
            int ymax = Math.Max(Math.Max(Math.Max(Math.Abs(y11), Math.Abs(y12)), Math.Abs(y21)), Math.Abs(y22));

            color_index = (int)(color_index + Math.Abs(ymax) / 84 + 1.5);

            // limit "darkest" color to be base color + intensity 1
            int min_color = (color_index & 0xF8) + 1;

            color_index = Math.Max(color_index, min_color);

            AddRectangle(
                new Point3D(p.X, y11, p.Z),
                new Point3D(x2, y12, p.Z),
                new Point3D(x2, y22, z2),
                new Point3D(p.X, y21, z2),
                Palette.DiffuseMaterial[color_index]);
        }
Esempio n. 4
0
        public override void DecodeFrame(byte[] buffer)
        {
            Chunk     frmeChunk = frmeChunks[currentFrame];
            ChunkList subChunks = frmeChunk.Select("*");

            foreach (Chunk subChunk in subChunks)
            {
                switch (subChunk.ChunkTypeId)
                {
                case "FOBJ":
                    HandleFOBJ(subChunk, buffer);
                    break;

                case "NPAL":
                    HandleNPAL(subChunk, buffer);
                    break;

                case "XPAL":
                    HandleXPAL(subChunk, buffer);
                    break;

                case "STOR":
                    HandleSTOR(subChunk, buffer);
                    break;

                case "FTCH":
                    HandleFTCH(subChunk, buffer);
                    break;
                }
            }
        }
        /// <summary>
        /// Function to read in the chunk table from the file.
        /// </summary>
        /// <param name="reader">The reader for the stream.</param>
        /// <param name="offset">Offset of the chunk table from the file start.</param>
        private void ReadChunkTable(GorgonBinaryReader reader, long offset)
        {
            long prevPosition = Stream.Position;

            try
            {
                Stream.Position = offset;

                ulong chunkID = reader.ReadUInt64();

                if (chunkID != ChunkTableID)
                {
                    throw new GorgonException(GorgonResult.CannotRead, Resources.GOR_ERR_CHUNK_FILE_TABLE_CHUNK_INVALID);
                }

                int count = reader.ReadInt32();

                if (count < 0)
                {
                    throw new GorgonException(GorgonResult.CannotRead, Resources.GOR_ERR_CHUNK_FILE_TABLE_INVALID_COUNT);
                }

                // Retrieve the chunk table.
                for (int i = 0; i < count; ++i)
                {
                    ChunkList.Add(new GorgonChunk(reader.ReadUInt64(), reader.ReadInt32(), reader.ReadUInt64()));
                }
            }
            finally
            {
                Stream.Position = prevPosition;
            }
        }
Esempio n. 6
0
        /// <summary>
        /// Function to open a chunked file within the stream.
        /// </summary>
        /// <remarks>
        /// <para>
        /// This opens a Gorgon chunk file that exists within the <see cref="Stream"/> passed to the constructor of this object. Typically this would be in a <see cref="FileStream"/>, but any type of stream
        /// is valid and can contain a chunk file.
        /// </para>
        /// <para>
        /// If the this method is called and the file is already opened, then it will be closed and reopened.
        /// </para>
        /// <note type="Important">
        /// Always pair a call to <c>Open</c> with a call to <see cref="Close"/>, otherwise the file may become corrupted or the stream may not be updated to the correct position.
        /// </note>
        /// <note type="Important">
        /// When this file is opened for <i>reading</i>, then validation is performed on the file header to ensure that it is a genuine GCFF file. If it is not, then an exception will be thrown
        /// detailing what's wrong with the header.
        /// </note>
        /// </remarks>
        /// <exception cref="GorgonException">Thrown when the chunk file format header ID does not match when reading.
        /// <para>-or-</para>
        /// <para>Thrown when application specific header ID in the file was not found in the list passed to the constructor when reading.</para>
        /// <para>-or-</para>
        /// <para>Thrown if the chunk file table offset is less than or equal to the size of the header when reading.</para>
        /// <para>-or-</para>
        /// <para>Thrown if the file size recorded in the header is less than the size of the header when reading.</para>
        /// </exception>
        public void Open()
        {
            if (IsOpen)
            {
                Close();
            }

            // Reset the stream position back to the beginning of the file.
            // This is a stream wrapper, so it'll be relative to the actual stream position.
            Stream.Position = 0;

            ChunkList.Clear();

            switch (Mode)
            {
            case ChunkFileMode.Read:
                ReadHeaderValidate();
                break;

            case ChunkFileMode.Write:
                WriteHeader();
                break;

            default:
                throw new ArgumentException(Resources.GOR_ERR_CHUNK_ILLEGAL_OPEN_MODE);
            }

            IsOpen = true;
        }
Esempio n. 7
0
        private ChunkList GetDirectoryRootChunks()
        {
            var result = new ChunkList();

            result.Add(new UnknownChunk(this, RootChunk, 0, Size));
            return(result);
        }
Esempio n. 8
0
        public IdxPage()
        {
            Magic = new Magic(new byte[] { 201, 0, 0, 0,
                                           0, 0, 0, 0,
                                           0, 0, 0, 0,
                                           0, 0, 0, 0,
                                           0, 0, 0, 0, });

            Unknown0        = new Chararray();
            Unknown0.Length = (4 * 10);

            AllocationBitmap        = new Chararray();
            AllocationBitmap.Length = 125;
            ListItems = new ChunkList <IdxListItem>(ChunkListRepeat.ToCount, 1000);

            SetupChunkFields();
            AutomaticFields = new List <ChunkField>()
            {
                Magic,
                Next,
                Unknown1,
                BytesPerSlot,
                Fragments,
                EmptySlots,
                Unknown0,
                AllocationBitmap,
            };
        }
Esempio n. 9
0
        // BLK Editor

        private void newToolStripMenuItem1_Click(object sender, EventArgs e)
        {
            openVisibilityFile = null;
            ChunkList.Clear();
            numericCurrentChunk.Maximum = ChunkList.Count();
            labelChunkAmount.Text       = "Amount: " + ChunkList.Count();
            labelLoadedBLK.Text         = "No BLK loaded";
        }
Esempio n. 10
0
        public override ChunkList GetRootChunks()
        {
            Position = 0;
            ChunkList result = new ChunkList();

            result.Add(new LB83Chunk(this, RootChunk));
            return(result);
        }
Esempio n. 11
0
        private void buttonRemoveChunk_Click(object sender, EventArgs e)
        {
            if (ChunkList.Count > 0)
            {
                ChunkList.RemoveAt((int)numericCurrentChunk.Value - 1);
            }

            numericCurrentChunk.Maximum = ChunkList.Count();
            labelChunkAmount.Text       = "Amount: " + ChunkList.Count();
            numericCurrentChunk_ValueChanged(new object(), new EventArgs());
        }
Esempio n. 12
0
        private ChunkList GetResourceRootChunks()
        {
            var map    = GetResourceMap();
            var result = new ChunkList();

            Position = 0;
            ulong offset    = Position;
            uint  chunkSize = ReadU16LE();
            var   chunk     = new SCUMM1Chunk(this, RootChunk, "ROOMv1", offset, chunkSize);

            result.Add(chunk);

            Position += chunkSize - 2;

            string chunkName;

            while (Position < Size)
            {
                offset    = Position;
                chunkSize = ReadU16LE();

                if (offset + chunkSize > Size)
                {
                    chunkSize = (uint)(Size - offset);
                    chunkName = "????v1";
                }
                else
                {
                    SCUMM1ResourceType type;
                    if (!map.TryGetValue(offset, out type))
                    {
                        chunkName = "????v1";
                    }
                    else
                    {
                        switch (type)
                        {
                        case SCUMM1ResourceType.Costume: chunkName = "COSTv1"; break;

                        case SCUMM1ResourceType.Script: chunkName = "SCRPv1"; break;

                        case SCUMM1ResourceType.Sound: chunkName = "SOUNv1"; break;

                        default:
                            throw new FileFormatException("Unknown resource type: {0}", type);
                        }
                    }
                }
                result.Add(new SCUMM1Chunk(this, RootChunk, chunkName, offset, chunkSize));
                Position += chunkSize - 2;
            }

            return(result);
        }
Esempio n. 13
0
        private void buttonAddChunkClick(object sender, EventArgs e)
        {
            Chunk NewChunk = new Chunk();

            NewChunk.CalculateModel();
            ChunkList.Add(NewChunk);
            numericCurrentChunk.Minimum = 1;
            numericCurrentChunk.Maximum = ChunkList.Count();
            numericCurrentChunk.Value   = ChunkList.Count();
            labelChunkAmount.Text       = "Amount: " + ChunkList.Count();
        }
Esempio n. 14
0
        public override void AfterAutomaticRead(IReader rdr)
        {
            if (Length.Value % 3 != 0)
            {
                throw new FileParserException("PLTE: length not a multiple of 3");
            }

            Entries = new ChunkList <RGBTriplet>(ChunkListRepeat.ToCount, Length.Value / 3);
            Entries.ReadAll(rdr);

            base.AfterAutomaticRead(rdr);
        }
Esempio n. 15
0
        private void LoadPixels(Pixel[] pixels)
        {
            if (ChunkList == null)
            {
                ChunkList = new List <ColorChunk>();
            }

            List <Pixel> pixelList = new List <Pixel>(pixels);

            Stopwatch stopwatch = new Stopwatch();

            Console.WriteLine("Loading pixels...");

            int count = 0;

            stopwatch.Start();

            pixelList = new List <Pixel>(pixelList.OrderBy(pixel => pixel.Color.AsInt()));

            int i;

            while (pixelList.Any())
            {
                for (i = 0; i < pixelList.Count - 1; i++)
                {
                    if (!pixelList[i].Color.Equals(pixelList[i + 1].Color))
                    {
                        break;
                    }
                }

                ChunkList.Add(new ColorChunk(pixelList.First().Color, i + 1));

                pixelList.RemoveRange(0, i + 1);

                count++;
            }

            stopwatch.Restart();

            // Sort by Count
            ChunkList = new List <ColorChunk>(ChunkList.OrderBy(chunk => chunk.Count));

            ColorList = ChunkList.Select(chunk => chunk.Color).ToList();

            stopwatch.Stop();

            Console.WriteLine("Pixels was loaded successfully!");
            Console.WriteLine("Elapsed: " + stopwatch.Elapsed.ToString());
            Console.WriteLine("CaluculateTime: " + count.ToString());
        }
Esempio n. 16
0
        public override ChunkList GetRootChunks()
        {
            ChunkList result = new ChunkList();

            Position = 0;

            while (Position < Size)
            {
                Chunk chunk = new BUNDChunk(this, RootChunk, "BUND", 0, Size - 8);
                result.Add(chunk);
                Position = chunk.Offset + chunk.Size;
            }
            return(result);
        }
Esempio n. 17
0
        public override ChunkList GetRootChunks()
        {
            ChunkList result = new ChunkList();

            Position = 0;

            while (Position < Size)
            {
                Chunk chunk = SCUMM3Chunk.ReadChunk(this, RootChunk);
                result.Add(chunk);
                Position = chunk.Offset + chunk.Size;
            }

            return(result);
        }
Esempio n. 18
0
        public bool Type(string typedLetter)
        {
            if (IsTyped)
            {
                return(false);
            }
            var chunk  = ChunkList.Select(c => c).Where(c => !c.IsTyped).First();
            var result = chunk.Type(typedLetter);

            if (result)
            {
                TypedLetters = TypedLetters + typedLetter;
            }
            return(result);
        }
Esempio n. 19
0
        /// <summary>
        ///     Creates a copy of the storage info and filters chunks
        /// </summary>
        /// <returns>Copied storage info</returns>
        internal StorageInfo StableChunks()
        {
            if (_stableChunkList == null)
            {
                _stableChunkList = ChunkList.Where(c => !c.Changing && c.Type != ChunkTypes.Free).ToList();
                if (Cache != null && Cache._stableChunkList == null)
                {
                    Cache._stableChunkList = _stableChunkList;
                }
            }

            return(new StorageInfo {
                Initialized = Initialized, ModifiedVersion = ModifiedVersion, AddedVersion = AddedVersion, RemovedVersion = RemovedVersion, ChunkList = _stableChunkList
            });
        }
Esempio n. 20
0
        void BuildChunkList(ChunkList chunks, ref Point3D p)
        {
            int num_rows = chunks.NumRows;// + level.BonusPyramid?.NumRows ?? 0;
            int num_cols = chunks.NumColumns;

            for (int r = 0; r < num_rows; r++)
            {
                p.X = 0;
                for (int c = 0; c < num_cols; c++, p.X += Tile.SIZE)
                {
                    BuildTile3D(chunks, r, c, p);
                }
                p.Z += Tile.SIZE;
            }
        }
Esempio n. 21
0
        public static void HandleList(Game _assets, BinaryReader _reader, ChunkList _handler)
        {
            Int32 _listOffset = _reader.ReadInt32(), _listBase = (Int32)_reader.BaseStream.Position;

            _reader.BaseStream.Seek(_listOffset, SeekOrigin.Begin);
            Int32 _itemCount = _reader.ReadInt32();

            for (Int32 i = 0; i < _itemCount; i++)
            {
                Int32 _itemOffset = _reader.ReadInt32(), _itemBase = (Int32)_reader.BaseStream.Position;
                _reader.BaseStream.Seek(_itemOffset, SeekOrigin.Begin);
                _handler(_itemOffset);
                _reader.BaseStream.Seek(_itemBase, SeekOrigin.Begin);
            }
            _reader.BaseStream.Seek(_listBase, SeekOrigin.Begin);
        }
Esempio n. 22
0
        public override void Initialize(Chunk chunk)
        {
            frmeChunks     = chunk.Select("FRME");
            currentFrame   = 0;
            currentPalette = new Palette(256);

            info = GetInfo(chunk);
            // TODO: Make work for other pixel depths than 8 bit?

            frameStore   = new byte[info.Width * info.Height];
            frameInStore = false;

            Chunk ahdrChunk = chunk.SelectSingle("AHDR");

            HandleAHDRPalette(ahdrChunk);
        }
        /// <summary>
        /// Function to close an open chunk.
        /// </summary>
        /// <remarks>
        /// <para>
        /// This will close the active chunk, and add it to the chunk table list. It will reposition the stream pointer for the stream passed to the constructor of this object to the next position for
        /// a chunk, or the end of the chunk data.
        /// </para>
        /// <para>
        /// If this method is not called, then the chunk will not be added to the chunk table in the file and the file will lose that chunk. This, however, does not mean the file is necessarily corrupt,
        /// just that the chunk will not exist. Regardless, this method should always be called when one of the <see cref="O:Gorgon.IO.GorgonChunkFile`1.OpenChunk"/> are called.
        /// </para>
        /// </remarks>
        public override void CloseChunk()
        {
            if (_activeChunk.ID == 0)
            {
                return;
            }

            // Move the stream forward by the amount written.
            _activeChunk     = new GorgonChunk(_activeChunk.ID, (int)(_activeWriter.BaseStream.Length), _activeChunk.FileOffset);
            Stream.Position += _activeChunk.Size;

            ChunkList.Add(_activeChunk);

            _activeChunk = default;
            _activeWriter.Dispose();
            _activeWriter = null;
        }
Esempio n. 24
0
        public Sentence(SentenceDefinition sd)
        {
            KanjiKana = sd.KanjiKana;
            Kana      = sd.Kana;
            var charArray = Kana.ToCharArray();
            var charList  = new List <char>(charArray);
            var strList   = charList.Select(c => c.ToString()).ToList();

            var isSokuon = false;
            var from     = 0;

            for (int i = 0; i < strList.Count(); i++)
            {
                if (i < strList.Count() - 1) //最終文字ならチャンク確定
                {
                    if (!isSokuon)
                    {
                        isSokuon = KanaUtils.IsSokuon(strList[i]);
                        if (isSokuon)
                        {
                            from--;
                            continue;
                        }
                    }

                    var chkStr = strList[i] + strList[i + 1];
                    if (KanaUtils.Henkan.ContainsKey(chkStr))
                    {
                        from--;
                        continue;
                    }
                }

                var chunkStr = "";
                for (int j = from; j < 1; j++)
                {
                    chunkStr = chunkStr + strList[i + j];
                }
                ;

                ChunkList.Add(new Chunk(chunkStr, isSokuon));
                isSokuon = false;
                from     = 0;
            }
        }
Esempio n. 25
0
        void BuildTile3D(ChunkList chunks, int row, int col, Point3D p)
        {
            Tile tile = chunks.GetTileAt(row, col);

            int color = 0;

            switch (tile.Type)
            {
            case Tile.TYPE.EMPTY_0: return;

            case Tile.TYPE.BLUE_1: color = 0x37; break;

            case Tile.TYPE.BLUE_JEWEL_2: color = 0x37; AddMathboxObject(Mathbox.Mesh.JEWEL, p + new Vector3D(Tile.SIZE / 2, -p.Y - Tile.SIZE, Tile.SIZE / 2)); break;

            case Tile.TYPE.UP_DOWN_3: color = 0x17; break;

            case Tile.TYPE.BRIDGE_4: color = 0x39; break;

            case Tile.TYPE.RED_5: color = 0x0F; break;

            case Tile.TYPE.BLACK_6: return;

            case Tile.TYPE.KILL_EYE_7: color = 0x0F; break;

            case Tile.TYPE.BLUE_SLOPE_8: AddSlopedTile(p, chunks, row, col, 0x30); return;

            case Tile.TYPE.DESTRUCTABLE_9: color = 0x34; break;

            case Tile.TYPE.GREEN_10: color = 0x25; break;

            case Tile.TYPE.BLUE_11: color = 0x37; break;

            case Tile.TYPE.BLUE_12: color = 0x37; break;

            case Tile.TYPE.RED_SLOPE_13: AddSlopedTile(p, chunks, row, col, 0x8); return;

            case Tile.TYPE.YELLOW_14: color = 0x1F; break;

            case Tile.TYPE.ILLEGAL_15: return;
            }

            AddFlatTile(chunks, row, col, p, tile);
        }
    private void UpdateDataView()
    {
        System.Int64 refItemId                = -1;
        int          possibleValuesCount      = 0;                                                                           // Possible value count
        ChunkList    possibleValues           = null;                                                                        // Possible values list
        int          chunkPossibleValuesCount = Convert.ToInt32(SessionState.CacheParams["ChunkPossibleValuesCount"].Value); // Retrieve possible values count
        string       cultureCode              = SessionState.Culture.Code;                                                   // current culture code

        // Get ref item for search possible values
        if ((uwDDL_Filters != null) && (uwDDL_Filters.SelectedRow != null))
        {
            refItemId = Convert.ToInt64(uwDDL_Filters.SelectedRow.Cells.FromKey("Id").Value);
        }
        HyperCatalog.Business.Container container = SessionState.QDEContainer;

        if (container != null)
        {
            possibleValues      = container.PossibleValues(cultureCode, chunkPossibleValuesCount, refItemId, inputformId);
            possibleValuesCount = container.PossibleValuesCount(cultureCode, refItemId, inputformId);

            // If too much values are available, we will only show a certain limit
            LbSubSet.Visible = possibleValuesCount > chunkPossibleValuesCount;
        }
        UITools.RefreshTab(Page, "PossibleValues", possibleValuesCount);

        if (possibleValues != null && possibleValues.Count > 0)
        {
            panelGrid.Visible           = true;
            dgPossibleValues.DataSource = possibleValues;
            Utils.InitGridSort(ref dgPossibleValues);
            dgPossibleValues.DataBind();
            dgPossibleValues.DisplayLayout.CellClickActionDefault = Infragistics.WebUI.UltraWebGrid.CellClickAction.CellSelect;
        }
        else
        {
            panelGrid.Visible = false;
        }
    }
Esempio n. 27
0
        public override byte[] Decode(Chunk chunk, uint index)
        {
            if (GetCount(chunk) <= index)
            {
                throw new DecodingException("Invalid image index");
            }

            ImageInfo info = GetInfo(chunk, index);

            bool bomp = false; // TODO: Implement bomp

            ChunkList smapChunks = chunk.Select("WRAP/SMAP");

            Chunk dataChunk = smapChunks[(int)index];

            if (dataChunk == null)
            {
                throw new DecodingException("BOMP or SMAP chunk not found");
            }

            byte[] destBuffer = bomp ? DecodeBomp(dataChunk, info) : DecodeSmap(dataChunk, info);

            return(destBuffer);
        }
        /// <summary>
        /// Processes all pages, computing checksums to determine chunks of virtual pages that have changed
        /// </summary>
        private void ProcessPages()
        {
            // Check for newly allocated pages
            lock (this.ChunkLock)
            {
                foreach (RegionProperties newPage in this.CollectNewPages())
                {
                    this.ChunkList.AddFirst(newPage);
                }
            }

            Int32 chunkLimit;

            if (this.IsTaskComplete)
            {
                chunkLimit = ChunkLinkedListPrefilter.ChunkLimit;
            }
            else
            {
                chunkLimit = ChunkLinkedListPrefilter.RampUpChunkLimit;
            }

            lock (this.ChunkLock)
            {
                // Process the allowed amount of chunks from the priority queue
                Parallel.For(
                    0,
                    Math.Min(this.ChunkList.Count, chunkLimit),
                    SettingsViewModel.GetInstance().ParallelSettings,
                    index =>
                {
                    RegionProperties chunk;
                    Boolean success = false;

                    // Grab next available element
                    lock (this.ElementLock)
                    {
                        chunk = this.ChunkList.FirstOrDefault();

                        if (chunk == null)
                        {
                            return;
                        }

                        this.ChunkList.RemoveFirst();

                        // Do not process chunks that have been marked as changed
                        if (chunk.HasChanged)
                        {
                            this.ChunkList.AddLast(chunk);
                            return;
                        }
                    }

                    // Read current page data for chunk
                    Byte[] pageData = EngineCore.GetInstance().OperatingSystemAdapter?.ReadBytes(chunk.BaseAddress, chunk.RegionSize, out success);

                    // Read failed; Deallocated page
                    if (!success)
                    {
                        return;
                    }

                    // Update chunk
                    chunk.Update(pageData);

                    // Recycle it
                    lock (this.ElementLock)
                    {
                        ChunkList.AddLast(chunk);
                    }
                });
            }
        }
Esempio n. 29
0
 private void OnChunkList(ChunkList chunks)
 {
     _minecraft.DoReceiveEvent(typeof(OnChunkList), new OnChunkList(chunks));
 }
Esempio n. 30
0
        private void ParseChunks(Stream st)
        {
            // When reaches the end, stop.
            if (st.Position == st.Length)
            {
                return;
            }

            // If it is a valid chunk, it has to be at least 8
            Sanity.Requires(st.Position + 8 <= st.Length, $"Stream length mismatch, at position {st.Position}.");

            // Offset is the current position.
            int offset = (int)st.Position;

            // The first four bytes(of the 8 bytes) is the name.
            st.Read(ChunkNameBytes, 0, 4);
            string name = GetName();

            // The next four bytes(of the 8 bytes) is the chunk siz/length.
            st.Read(Int32Bytes, 0, 4);
            int length = GetInt32();

            // The chunk length should not exceed the end of the file.
            Sanity.Requires(st.Position + length <= st.Length, $"Stream length mismatch, at position {st.Position}, in chunk {name}.");
            // Move forward.
            st.Seek(length, SeekOrigin.Current);

            // Set the chunk.
            WaveChunk chunk = new WaveChunk
            {
                ChunkName   = name,
                ChunkLength = length,
                ChunkOffset = offset
            };

            // Format chunk is special.
            if (chunk.ChunkName == "fmt ")
            {
                // There should be only 1 format chunk.
                Sanity.Requires(FormatChunk.ChunkName == null, $"Format error, at most 1 format chunk.");
                // The smallest format chunk for PCM is 16.
                Sanity.Requires(chunk.ChunkLength >= 16, $"Format error, format chunk length {FormatChunk.ChunkLength}, should be at least 16.");
                FormatChunk = chunk;
            }

            // Data chunk is special.
            if (chunk.ChunkName == "data")
            {
                // There should be only 1 data chunk.
                // NOTE: I'M NOT SURE ABOUT THIS, THERE IS NOWHERE SAY ONLY 1 DATA CHUNK IS ALLOWED.
                // JUST FOR SIMPLE HERE.
                Sanity.Requires(DataChunk.ChunkName == null, $"Format error, at most 1 data chunk.");
                DataChunk = chunk;
            }

            // Add this chunk into the list.
            ChunkList.Add(chunk);


            // Parse the next chunk recursively.
            ParseChunks(st);
        }
        public IPacket ReadPacket(IMinecraftDataReader reader)
        {
            ChunkList = ChunkList.FromReader(reader);

            return this;
        }