public DependencyInfo GetDependencyInfo(Stream stream, Mesh mesh)
        {
            BinaryMemoryReader reader = new BinaryMemoryReader(stream);

            // read the header ID
            ushort headerID = ReadUShort(reader);

            if (headerID != (ushort)MeshChunkID.Header) {
                throw new AxiomException("File header not found.");
            }

            // read version
            string fileVersion = ReadString(reader);

            // set jump back to the start of the reader
            Seek(reader, 0, SeekOrigin.Begin);

            // barf if there specified version is not supported
            if (!implementations.ContainsKey(fileVersion)) {
                throw new AxiomException("Cannot find serializer implementation for version '{0}'.", fileVersion);
            }

            LogManager.Instance.Write("Mesh: Fetching dependency info '{0}'...", mesh.Name);

            // call implementation
            MeshSerializerImpl serializer = (MeshSerializerImpl)implementations[fileVersion];
            DependencyInfo rv = serializer.GetDependencyInfo(stream, mesh);

            // warn on old version of mesh
            if (fileVersion != currentVersion) {
                LogManager.Instance.Write("WARNING: {0} is an older format ({1}); you should upgrade it as soon as possible using the OgreMeshUpdate tool.", mesh.Name, fileVersion);
            }
            return rv;
        }
        /// <summary>
        ///		Reads a specified number of floats and copies them into the destination pointer.
        /// </summary>
        /// <param name="count">Number of values to read.</param>
        /// <param name="dest">Pointer to copy the values into.</param>
        protected void ReadBytes(BinaryMemoryReader reader, int count, IntPtr dest)
        {
            // blast the data into the buffer
            unsafe {
                byte* pointer = (byte*)dest.ToPointer();

                for(int i = 0; i < count; i++) {
                    pointer[i] = reader.ReadByte();
                }
            }
        }
        public void ImportSkeleton(Stream stream, Skeleton skeleton)
        {
            // store a local reference to the mesh for modification
            this.skeleton = skeleton;

            BinaryMemoryReader reader = new BinaryMemoryReader(stream, System.Text.Encoding.ASCII);

            // start off by taking a look at the header
            ReadFileHeader(reader);

            SkeletonChunkID chunkID = 0;

            while (!IsEOF(reader)) {
                chunkID = ReadChunk(reader);

                switch (chunkID) {
                    case SkeletonChunkID.Bone:
                        ReadBone(reader);
                        break;

                    case SkeletonChunkID.BoneParent:
                        ReadBoneParent(reader);
                        break;

                    case SkeletonChunkID.Animation:
                        ReadAnimation(reader);
                        break;

                    case SkeletonChunkID.AttachmentPoint:
                        ReadAttachmentPoint(reader);
                        break;

                    default:
                        log.Warn("Can only parse bones, parents, and animations at the top level during skeleton loading.");
                        log.Warn("Unexpected chunk: " + chunkID.ToString());
                        break;
                } // switch
            } // while

            // assume bones are stored in binding pose
            skeleton.SetBindingPose();
        }
        public DependencyInfo GetDependencyInfo(Stream stream, Mesh mesh)
        {
            BinaryMemoryReader reader = new BinaryMemoryReader(stream, System.Text.Encoding.ASCII);

            // check header
            ReadFileHeader(reader);

            MeshChunkID chunkID = 0;

            // read until the end
            while (!IsEOF(reader)) {
                chunkID = ReadChunk(reader);
                if (chunkID == MeshChunkID.DependencyInfo) {
                    DependencyInfo info = new DependencyInfo();
                    ReadDependencyInfo(reader, info);
                    return info;
                } else {
                    break;
                }
            }
            return null;
        }
        public unsafe void BytesRead()
        {
            Random rng = new Random();

            byte[] src = new byte[1024];
            byte[] chk = new byte[1024];

            rng.NextBytes(src);

            byte[] data;

            using (MemoryStream ms = new MemoryStream())
            {
                using (BinaryWriter writer = new BinaryWriter(ms))
                    for (int count = 0; count < 256; count++)
                    {
                        writer.Write(src);
                    }

                data = ms.ToArray();
            }

            fixed(byte *pData = data)
            {
                BinaryMemoryReader reader = new BinaryMemoryReader(pData, data.Length);

                for (int count = 0; count < 256; count++)
                {
                    reader.ReadBytes(chk, 0, 1024);

                    for (int position = 0; position < 1024; position++)
                    {
                        Assert.AreEqual(chk[position], src[position], $"Invalid content at position {position}.");
                    }
                }
            }
        }
Esempio n. 6
0
        public unsafe void ULongLimits()
        {
            byte[] data;

            using (MemoryStream ms = new MemoryStream())
            {
                using (BinaryWriter writer = new BinaryWriter(ms))
                    writer.Write(0x5555555555555555UL);

                data = ms.ToArray();
            }

            fixed(byte *pData = data)
            {
                BinaryMemoryReader reader = new BinaryMemoryReader(pData, data.Length);

                try
                {
                    reader.ReadUInt64();
                }
                catch
                {
                    Assert.Fail("Should not have thrown an Exception.");
                }

                BinaryMemoryWriter writer = new BinaryMemoryWriter(pData, data.Length);

                try
                {
                    writer.Write(0x5555555555555555UL);
                }
                catch
                {
                    Assert.Fail("Should not have thrown an Exception.");
                }
            }
        }
 protected ushort ReadUShort(BinaryMemoryReader reader)
 {
     return reader.ReadUInt16();
 }
 protected uint ReadUInt(BinaryMemoryReader reader)
 {
     return reader.ReadUInt32();
 }
 /// <summary>
 ///		Reads from the stream up to the first endline character.
 /// </summary>
 /// <returns>A string formed from characters up to the first '\n' character.</returns>
 protected string ReadString(BinaryMemoryReader reader)
 {
     // note: Not using Environment.NewLine here, this character is specifically used in Ogre files.
     return ReadString(reader, '\n');
 }
 protected short ReadShort(BinaryMemoryReader reader)
 {
     return reader.ReadInt16();
 }
 protected long ReadLong(BinaryMemoryReader reader)
 {
     return reader.ReadInt64();
 }
 protected float ReadFloat(BinaryMemoryReader reader)
 {
     return reader.ReadSingle();
 }
 protected bool ReadBool(BinaryMemoryReader reader)
 {
     return reader.ReadBoolean();
 }
        protected virtual void ReadPoses(BinaryMemoryReader reader)
        {
            if (!IsEOF(reader)) {
                MeshChunkID chunkID = ReadChunk(reader);

                while (!IsEOF(reader) &&
                    chunkID == MeshChunkID.Pose) {

                    string name = ReadString(reader);
                    ushort target = ReadUShort(reader);
                    Pose pose = mesh.CreatePose(target, name);

                    while (!IsEOF(reader) &&
                           (chunkID = ReadChunk(reader)) == MeshChunkID.PoseVertex) {

                        int vertexIndex = ReadInt(reader);
                        Vector3 offset = ReadVector3(reader);
                        pose.VertexOffsetMap[vertexIndex] = offset;
                    }
                }

                // grab the next chunk
                if (!IsEOF(reader)) {
                    // backpedal to the start of chunk
                    Seek(reader, -ChunkOverheadSize);
                }
            }
        }
        protected void ReadPoseKeyframe(BinaryMemoryReader reader, VertexAnimationTrack track)
        {
            float time = ReadFloat(reader);
            VertexPoseKeyFrame vkf = track.CreateVertexPoseKeyFrame(time);

            if (!IsEOF(reader)) {
                MeshChunkID chunkID = ReadChunk(reader);
                while (!IsEOF(reader) &&
                       chunkID == MeshChunkID.AnimationPoseRef) {
                    switch (chunkID) {
                        case MeshChunkID.AnimationPoseRef: {
                                ushort poseIndex = ReadUShort(reader);
                                float influence = ReadFloat(reader);
                                vkf.AddPoseReference(poseIndex, influence);
                                break;
                            }
                    }
                    if (!IsEOF(reader))
                        chunkID = ReadChunk(reader);
                }
                if (!IsEOF(reader)) {
                    // backpedal to the start of chunk
                    Seek(reader, -ChunkOverheadSize);
                }
            }
        }
 protected void ReadMorphKeyframe(BinaryMemoryReader reader, VertexAnimationTrack track)
 {
     float time = ReadFloat(reader);
     VertexMorphKeyFrame mkf = track.CreateVertexMorphKeyFrame(time);
     int vertexCount = track.TargetVertexData.vertexCount;
     // create/populate vertex buffer
     HardwareVertexBuffer buffer =
         HardwareBufferManager.Instance.CreateVertexBuffer(
                 VertexElement.GetTypeSize(VertexElementType.Float3),
                 vertexCount, BufferUsage.Static, true);
     // lock the buffer for editing
     IntPtr vertices = buffer.Lock(BufferLocking.Discard);
     // stuff the floats into the normal buffer
     ReadFloats(reader, vertexCount * 3, vertices);
     // unlock the buffer to commit
     buffer.Unlock();
     mkf.VertexBuffer = buffer;
 }
        protected virtual void ReadMeshLodUsageManual(BinaryMemoryReader reader, int lodNum, ref MeshLodUsage usage)
        {
            MeshChunkID chunkId = ReadChunk(reader);

            if(chunkId != MeshChunkID.MeshLODManual) {
                throw new AxiomException("Missing MeshLODManual chunk in '{0}'.", mesh.Name);
            }

            usage.manualName = ReadString(reader);

            // clearing the reference just in case
            usage.manualMesh = null;
        }
 protected void Seek(BinaryMemoryReader reader, long length)
 {
     Seek(reader, length, SeekOrigin.Current);
 }
 /// <summary>
 ///		Skips past a particular chunk.
 /// </summary>
 /// <remarks>
 ///		Only really used during development, when logic for handling particular chunks is not yet complete.
 /// </remarks>
 protected void IgnoreCurrentChunk(BinaryMemoryReader reader)
 {
     Seek(reader, currentChunkLength - ChunkOverheadSize);
 }
 protected void ReadSkeletonDependency(BinaryMemoryReader reader, DependencyInfo depends)
 {
     int count = reader.ReadInt16();
     for (int i = 0; i < count; ++i) {
         string name = reader.ReadString();
         depends.skeletons.Add(name);
     }
 }
        public unsafe void CompressedTimeSpanRead()
        {
            int required = 0;

            List <long> timeLongs = new List <long>()
            {
                //Limits 1 Byte -> 3 Byte
                0, 1, -1, 0x1F, -0x1F, 0x20, -0x20,

                0xFF_FF, -0xFF_FF, 0x01_00_00, -0x01_00_00,

                //Limits 3 Byte -> 5 Byte
                0x1F_FF_FF, -0x1F_FF_FF, 0x20_00_00, -0x20_00_00,

                0x01_00_00_00, -0x01_00_00_00,
                0xFF_FF_FF_FF, -0xFF_FF_FF_FF,
                0x01_00_00_00_00, -0x01_00_00_00_00,
                0x01_01_00_00_00, -0x01_01_00_00_00,
                0x01_00_01_00_00, -0x01_00_01_00_00,
                0x01_00_00_01_00, -0x01_00_00_01_00,
                0x01_00_00_00_01, -0x01_00_00_00_01,

                //Limits 5 Byte -> 8 Byte
                0x1F_FF_FF_FF_FF, -0x1F_FF_FF_FF_FF, 0x20_00_00_00_00, -0x20_00_00_00_00,

                0x01_00_00_00_00, -0x01_00_00_00_00,
                0xFF_FF_FF_FF_FF, -0xFF_FF_FF_FF_FF,
                0xFF_00_FF_FF_FF, -0xFF_00_FF_FF_FF,
                0xFF_FF_00_FF_FF, -0xFF_FF_00_FF_FF,
                0xFF_FF_FF_00_FF, -0xFF_FF_FF_00_FF,
                0xFF_FF_FF_FF_00, -0xFF_FF_FF_FF_00,
                0x01_00_00_00_00_00, -0x01_00_00_00_00_00,
                0x01_00_00_01_00_00, -0x01_00_00_01_00_00,
                0x01_00_00_00_01_00, -0x01_00_00_00_01_00,
                0x01_00_00_00_00_01, -0x01_00_00_00_00_01,
                0xFF_FF_FF_FF_FF_FF, -0xFF_FF_FF_FF_FF_FF,
                0x01_00_00_00_00_00_00, -0x01_00_00_00_00_00_00,
                0x01_00_00_00_00_01_00, -0x01_00_00_00_00_01_00,
                0x01_00_00_00_00_00_01, -0x01_00_00_00_00_00_01,
                0xFF_FF_FF_FF_FF_FF_FF, -0xFF_FF_FF_FF_FF_FF_FF,
                0x01_00_00_00_00_00_00_00, -0x01_00_00_00_00_00_00_00,
                0x01_00_00_00_00_00_01_00, -0x01_00_00_00_00_00_01_00,
                0x01_00_00_00_00_00_00_01, -0x01_00_00_00_00_00_00_01,

                //Limits -> 8 Byte
                0x1F_FF_FF_FF_FF_FF_FF_FF, -0x1F_FF_FF_FF_FF_FF_FF_FF
            };

            foreach (long timeLong in timeLongs)
            {
                long checkLong = timeLong;
                if (checkLong < 0)
                {
                    checkLong = -checkLong;
                }

                if (checkLong >= 137438953472)
                {
                    required += 8;
                }
                else if (checkLong >= 2097152)
                {
                    required += 5;
                }
                else if (checkLong >= 32)
                {
                    required += 3;
                }
                else
                {
                    required += 1;
                }
            }

            byte[] data = new byte[required];

            List <TimeSpan> timeSpans = new List <TimeSpan>();

            foreach (long timeLong in timeLongs)
                timeSpans.Add(new TimeSpan(timeLong));

            fixed(byte *pData = data)
            {
                BinaryMemoryWriter writer = new BinaryMemoryWriter(pData, data.Length);

                foreach (TimeSpan timeSpan in timeSpans)
                {
                    writer.WriteCompressed(timeSpan);
                }
            }

            fixed(byte *pData = data)
            {
                BinaryMemoryReader reader = new BinaryMemoryReader(pData, data.Length);

                foreach (TimeSpan timeSpan in timeSpans)
                {
                    Assert.AreEqual(timeSpan, reader.ReadCompressedTimeSpan(), "BinaryMemoryReader TimeSpan Compressed incompatible to BinaryMemoryWriter.");
                }
            }
        }
 protected virtual void ReadSkeletonLink(BinaryMemoryReader reader)
 {
     mesh.SkeletonName = ReadString(reader);
 }
        /// <summary>
        ///		Reads a specified number of floats and copies them into the destination pointer.
        /// </summary>
        /// <remarks>This overload will also copy the values into the specified destination array.</remarks>
        /// <param name="count">Number of values to read.</param>
        /// <param name="dest">Pointer to copy the values into.</param>
        /// <param name="destArray">A float array that is to have the values copied into it at the same time as 'dest'.</param>
        protected void ReadFloats(BinaryMemoryReader reader, int count, IntPtr dest, float[] destArray)
        {
            // blast the data into the buffer
            unsafe {
                float* pointer = (float*)dest.ToPointer();

                for(int i = 0; i < count; i++) {
                    float val = reader.ReadSingle();
                    pointer[i] = val;
                    destArray[i] = val;
                }
            }
        }
        protected virtual void ReadSubMesh(BinaryMemoryReader reader)
        {
            MeshChunkID chunkID;

            SubMesh subMesh = mesh.CreateSubMesh();

            // get the material name
            string materialName = ReadString(reader);
            subMesh.MaterialName = materialName;

            // use shared vertices?
            subMesh.useSharedVertices = ReadBool(reader);

            subMesh.indexData.indexStart = 0;
            subMesh.indexData.indexCount = ReadInt(reader);

            // does this use 32 bit index buffer
            bool idx32bit = ReadBool(reader);

            HardwareIndexBuffer idxBuffer = null;

            if(idx32bit) {
                // create the index buffer
                idxBuffer =
                    HardwareBufferManager.Instance.
                    CreateIndexBuffer(
                    IndexType.Size32,
                    subMesh.indexData.indexCount,
                    mesh.IndexBufferUsage,
                    mesh.UseIndexShadowBuffer);

                IntPtr indices = idxBuffer.Lock(BufferLocking.Discard);

                // read the ints into the buffer data
                ReadInts(reader, subMesh.indexData.indexCount, indices);

                // unlock the buffer to commit
                idxBuffer.Unlock();
            }
            else { // 16-bit
                // create the index buffer
                idxBuffer =
                    HardwareBufferManager.Instance.
                    CreateIndexBuffer(
                    IndexType.Size16,
                    subMesh.indexData.indexCount,
                    mesh.IndexBufferUsage,
                    mesh.UseIndexShadowBuffer);

                IntPtr indices = idxBuffer.Lock(BufferLocking.Discard);

                // read the shorts into the buffer data
                ReadShorts(reader, subMesh.indexData.indexCount, indices);

                idxBuffer.Unlock();
            }

            // save the index buffer
            subMesh.indexData.indexBuffer = idxBuffer;

            // Geometry chunk (optional, only present if useSharedVertices = false)
            if(!subMesh.useSharedVertices) {
                chunkID = ReadChunk(reader);

                if(chunkID != MeshChunkID.Geometry) {
                    throw new AxiomException("Missing geometry data in mesh file.");
                }

                subMesh.vertexData = new VertexData();

                // read the geometry data
                 ReadGeometry(reader, subMesh.vertexData);
            }

            // get the next chunkID
            chunkID = ReadChunk(reader);

            // walk through all the bone assignments for this submesh
            while(!IsEOF(reader) &&
                (chunkID == MeshChunkID.SubMeshBoneAssignment ||
                chunkID == MeshChunkID.SubMeshOperation)) {

                switch(chunkID) {
                    case MeshChunkID.SubMeshBoneAssignment:
                        ReadSubMeshBoneAssignment(reader, subMesh);
                        break;

                    case MeshChunkID.SubMeshOperation:
                        ReadSubMeshOperation(reader, subMesh);
                        break;
                }

                // read the next chunkID
                if(!IsEOF(reader)) {
                    chunkID = ReadChunk(reader);
                }
            } // while

            // walk back to the beginning of the last chunk ID read since
            // we already moved past it and it wasnt of interest to us
            if(!IsEOF(reader)) {
                Seek(reader, -ChunkOverheadSize);
            }

            // Create the bounding box for the submesh
            CreateSubMeshBoundingBox(subMesh);
        }
        /// <summary>
        ///    Reads and returns a Quaternion.
        /// </summary>
        /// <returns></returns>
        protected Quaternion ReadQuat(BinaryMemoryReader reader)
        {
            Quaternion quat = new Quaternion();

            quat.x = reader.ReadSingle();
            quat.y = reader.ReadSingle();
            quat.z = reader.ReadSingle();
            quat.w = reader.ReadSingle();

            return quat;
        }
Esempio n. 26
0
 internal SunCorona(byte plasma, ref BinaryMemoryReader reader)
 {
     Plasma = (Plasma)plasma;
     Amount = reader.ReadSingle();
     Radius = reader.ReadSingle();
 }
        /// <summary>
        ///		Reads a specified number of shorts and copies them into the destination pointer.
        /// </summary>
        /// <param name="count">Number of values to read.</param>
        /// <param name="dest">Pointer to copy the values into.</param>
        protected void ReadShorts(BinaryMemoryReader reader, int count, IntPtr dest)
        {
            // blast the data into the buffer
            unsafe {
                short* pointer = (short*)dest.ToPointer();

                for (int i = 0; i < count; i++) {
                    pointer[i] = reader.ReadInt16();
                }
            }
        }
Esempio n. 28
0
 internal Vector(ref BinaryMemoryReader reader)
 {
     x = reader.ReadSingle();
     y = reader.ReadSingle();
 }
        /// <summary>
        ///		Reads from the stream up to the specified delimiter character.
        /// </summary>
        /// <param name="delimiter">The character that signals the end of the string.</param>
        /// <returns>A string formed from characters up to the first instance of the specified delimeter.</returns>
        protected string ReadString(BinaryMemoryReader reader, char delimiter)
        {
            StringBuilder sb = new StringBuilder();

            char c;

            // sift through each character until we hit the delimiter
            while((c = reader.ReadChar()) != delimiter) {
                sb.Append(c);
            }

            // return the accumulated string
            return sb.ToString();
        }
Esempio n. 30
0
 internal Shot(Universe universe, Galaxy galaxy, ref BinaryMemoryReader reader) : base(universe, galaxy, ref reader)
 {
     Ammunition = (FlattiverseResourceKind)reader.ReadByte();
 }
 protected ulong ReadULong(BinaryMemoryReader reader)
 {
     return reader.ReadUInt64();
 }
Esempio n. 32
0
 internal Meteoroid(Universe universe, Galaxy galaxy, ref BinaryMemoryReader reader) : base(universe, galaxy, ref reader)
 {
 }
        /// <summary>
        ///    Reads and returns a Vector4 structure.
        /// </summary>
        /// <returns></returns>
        protected Vector4 ReadVector4(BinaryMemoryReader reader)
        {
            Vector4 vector = new Vector4();

            vector.x = ReadFloat(reader);
            vector.y = ReadFloat(reader);
            vector.z = ReadFloat(reader);
            vector.w = ReadFloat(reader);

            return vector;
        }
Esempio n. 34
0
        internal void Answer(Packet packet)
        {
            if (packet.Command == 0xFF)
            {
                Exception exception;

                switch (packet.Helper)
                {
                case 0x01:
                    exception = new UniverseServerUnhandledException();
                    break;

                case 0x02:
                    exception = new InvalidParameterException();
                    break;

                case 0x03:
                    exception = new AccountDoesntExistException();
                    break;

                case 0x04:
                    exception = new OperationRequiresAdminStatusException();
                    break;

                case 0x05:
                    exception = new PermissionDeniedException(packet.SubAddress);
                    break;

                case 0x06:
                    exception = new IllegalNameException();
                    break;

                case 0x07:
                    exception = new UnitDoesntExistException();
                    break;

                case 0x08:
                    exception = new NoUniverseAssignmentException();
                    break;

                case 0x09:
                    exception = new WrongStateException();
                    break;

                case 0x0A:
                    exception = new TooManyEntriesException();
                    break;

                case 0x10:
                    exception = new JoinRefusedException(packet.SubAddress);
                    break;

                case 0x11:
                    exception = new PartException(packet.SubAddress);
                    break;

                case 0x20:
                    exception = new UniverseDoesntExistException();
                    break;

                case 0x21:
                    exception = new UniverseOfflineException();
                    break;

                case 0x22:
                    exception = new UniverseGoneWhileExecutingRequestException();
                    break;

                case 0x23:
                    exception = new NoUniverseAvailableException();
                    break;

                case 0x24:
                    exception = new GalaxyDoesntExistException();
                    break;

                case 0x60:
                    exception = new NonEditableUnitException();
                    break;

                case 0x61:
                    exception = new AmbiguousXmlDataException();
                    break;

                case 0xFB:
                {
                    BinaryMemoryReader tmpReader = packet.Read();

                    string message   = tmpReader.ReadString();
                    string parameter = tmpReader.ReadString();

                    exception = new ArgumentException(message, parameter);
                }
                break;

                case 0xFC:
                {
                    BinaryMemoryReader tmpReader = packet.Read();

                    string message   = tmpReader.ReadString();
                    string parameter = tmpReader.ReadString();

                    exception = new ArgumentNullException(parameter, message);
                }
                break;

                case 0xFD:
                {
                    string message = packet.Read().ReadString();

                    exception = new InvalidOperationException(message);
                }
                break;

                case 0xFE:
                    exception = new Exception("This exception will be replaced with an generic exception.");
                    break;

                case 0xFF:
                    BinaryMemoryReader reader = packet.Read();
                    exception = new InvalidProgramException($"!!! INVALID EXCEPTION COUGHT BY SERVER !!!\n\nThe server has cought a \"{reader.ReadString()}\" and did just forward this to the client (you). The exception has the following message:\n\n{reader.ReadString()}\n\nAnd the following stack trace:\n\n{reader.ReadString()}\n\nIf you are in the C# course of the HS-Esslingen: Contact your teacher.");
                    break;

                default:
                    exception = new Exception($"Unknown Exception Code: 0x{packet.Helper.ToString()}.");
                    break;
                }

                ThreadPool.QueueUserWorkItem(delegate { tcs.SetException(exception); });

                return;
            }

            ThreadPool.QueueUserWorkItem(delegate { tcs.SetResult(packet); });
        }
 /// <summary>
 ///		Skips to a particular part of the binary stream.
 /// </summary>
 /// <param name="length">Number of bytes to skip.</param>
 protected void Seek(BinaryMemoryReader reader, long length, SeekOrigin origin)
 {
     reader.Seek(length, origin);
 }
        /// <summary>
        ///		Reads a chunk ID and chunk size.
        /// </summary>
        /// <returns>The chunk ID at the current location.</returns>
        protected short ReadFileChunk(BinaryMemoryReader reader)
        {
            // get the chunk id
            short id = reader.ReadInt16();

            // read the length for this chunk
            currentChunkLength = reader.ReadInt32();

            return id;
        }
 protected bool IsEOF(BinaryMemoryReader reader)
 {
     return reader.PeekChar() == -1;
 }
Esempio n. 38
0
 internal Buoy(Universe universe, Galaxy galaxy, ref BinaryMemoryReader reader) : base(universe, galaxy, ref reader)
 {
     Message = reader.ReadString();
 }
Esempio n. 39
0
        private unsafe void received(object socketObject, SocketAsyncEventArgs eventArgs)
        {
            Socket socket = (Socket)socketObject;

            try
            {
                do
                {
                    if (eventArgs.SocketError != SocketError.Success || eventArgs.BytesTransferred == 0)
                    {
                        lock (sync)
                        {
                            closed = true;

                            try
                            {
                                Disconnected?.Invoke();
                            }
                            catch { }

                            eventArgs.Dispose();

                            socket.Close();

                            foreach (Session session in sessions)
                            {
                                session.Disconnected();
                            }

                            return;
                        }
                    }

                    recvBufferPosition += eventArgs.BytesTransferred;

                    if (recvBufferPosition > 15)
                    {
                        int useableData = recvBufferPosition - (recvBufferPosition % 16);

                        if (recvPlainPosition + useableData > 262144)
                        {
                            useableData = (262144 - recvPlainPosition) - ((262144 - recvPlainPosition) % 16);
                        }

                        recvAES.TransformBlock(recvBuffer, 0, useableData, recvPlain, recvPlainPosition);

                        recvPlainPosition += useableData;

                        if (useableData == recvBufferPosition)
                        {
                            recvBufferPosition = 0;
                        }
                        else
                        {
                            Buffer.BlockCopy(recvBuffer, useableData, recvBuffer, 0, recvBufferPosition - useableData);
                            recvBufferPosition -= useableData;
                        }

                        List <Packet> packets = new List <Packet>();

                        Packet packet = new Packet();

                        fixed(byte *bRecvPlain = recvPlain)
                        {
                            BinaryMemoryReader reader = new BinaryMemoryReader(bRecvPlain, recvPlainPosition);

                            while (packet.Parse(ref reader))
                            {
                                if (packet.OutOfBand == 0)
                                {
                                    packets.Add(packet);
                                }

                                packet = new Packet();
                            }

                            if (Received != null && packets.Count > 0)
                            {
                                Received(packets);
                            }

                            if (reader.Position - bRecvPlain == recvPlainPosition)
                            {
                                recvPlainPosition = 0;
                            }
                            else
                            {
                                Buffer.BlockCopy(recvPlain, (int)(reader.Position - bRecvPlain), recvPlain, 0, recvPlainPosition - (int)(reader.Position - bRecvPlain));
                                recvPlainPosition -= (int)(reader.Position - bRecvPlain);
                            }
                        }
                    }

                    eventArgs.SetBuffer(recvBufferPosition, 262144 - recvBufferPosition);
                }while (!socket.ReceiveAsync(eventArgs));
            }
            catch
            {
                lock (sync)
                    if (!closed)
                    {
                        closed = true;

                        try
                        {
                            Disconnected?.Invoke();
                        }
                        catch { }

                        eventArgs.Dispose();

                        socket.Close();

                        foreach (Session session in sessions)
                        {
                            session.Disconnected();
                        }
                    }
            }
        }
Esempio n. 40
0
 internal SteadyUnit(Universe universe, Galaxy galaxy, ref BinaryMemoryReader reader) : base(universe, galaxy, ref reader)
 {
 }
 internal CommodityUnit(Universe universe, Galaxy galaxy, ref BinaryMemoryReader reader) : base(universe, galaxy, ref reader)
 {
     Resource = (FlattiverseResource)reader.ReadByte();
 }
        /// <summary>
        ///		Reads a file header and checks the version string.
        /// </summary>
        protected void ReadFileHeader(BinaryMemoryReader reader)
        {
            short headerID = 0;

            // read the header ID
            headerID = reader.ReadInt16();

            // better hope this is the header
            if(headerID == (short)MeshChunkID.Header) {
                string fileVersion = ReadString(reader);

                // read the version string
                if(version != fileVersion) {
                    throw new AxiomException("Invalid file: version incompatible, file reports {0}, Serializer is version {1}", fileVersion, version);
                }
            }
            else {
                throw new AxiomException("Invalid file: no header found.");
            }
        }