Example #1
0
 public int Decode(IBitStream stream, BitStreamCtx ctx)
 {
     int min = 0;
     int galloping = 1;
     int check;
     int u = 0;
     while (true) {
         check = (1 << galloping) - 1;
         if (stream.Read (ctx)) {
             min = check + 1;
             ++galloping;
         } else {
             if (galloping == 1) {
                 if (stream.Read(ctx)) {
                     u++;
                 }
                 return u;
             } else {
                 u += min;
                 min = 0;
                 galloping = 1;
             }
         }
     }
 }
Example #2
0
 public long Decode(IBitStream stream, BitStreamCtx ctx)
 {
     long min = 0;
     long check;
     long u = 0;
     int galloping = 1;
     while (true) {
         check = (1L << galloping) - 1L;
         if (stream.Read (ctx)) {
             min = check + 1L;
             ++galloping;
         } else {
             if (galloping == 1) {
                 if (stream.Read (ctx)) {
                     u++;
                 }
                 return u;
             } else {
                 u += min;
                 min = 0L;
                 galloping = 1;
             }
         }
     }
 }
Example #3
0
 public void Encode(IBitStream stream, int u)
 {
     var size = this.Huffman.Encode (stream, u);
     if (size == 0) {
         throw new KeyNotFoundException ("HuffmanCoding.Encode unknown symbol:" + u.ToString());
     }
 }
Example #4
0
		public static Vector DecodeVector(SendTableProperty prop, IBitStream reader)
		{
			if (prop.Flags.HasFlagFast(SendPropertyFlags.Normal)) {
            
			}

			Vector v = new Vector();

			v.X = DecodeFloat(prop, reader);
			v.Y = DecodeFloat(prop, reader);

			if (!prop.Flags.HasFlagFast(SendPropertyFlags.Normal)) {
				v.Z = DecodeFloat(prop, reader);
			} else {
				bool isNegative = reader.ReadBit();

				//v0v0v1v1 in original instead of margin. 
				float absolute = v.X * v.X + v.Y * v.Y;
				if (absolute < 1.0f) {
					v.Z = (float)Math.Sqrt(1 - absolute);
				} else {
					v.Z = 0f;
				}

				if (isNegative)
					v.Z *= -1;
			}

			return v;
		}
Example #5
0
        public void Parse(IBitStream bitstream, DemoParser parser)
        {
            while (!bitstream.ChunkFinished) {
                var desc = bitstream.ReadProtobufVarInt();
                var wireType = desc & 7;
                var fieldnum = desc >> 3;
                if (wireType != 0)
                    throw new InvalidDataException();

                var val = (uint)bitstream.ReadProtobufVarInt();

                switch (fieldnum) {
                case 1:
                    Tick = val;
                    break;
                case 4:
                    HostComputationTime = val;
                    break;
                case 5:
                    HostComputationTimeStdDeviation = val;
                    break;
                case 6:
                    HostFramestartTimeStdDeviation = val;
                    break;
                default:
                    // silently drop
                    break;
                }
            }

            parser.IngameTick = (int)Tick;
        }
Example #6
0
 public int Decode(IBitStream Buffer, BitStreamCtx ctx)
 {
     int u = Buffer.ReadZeros (ctx);
     //int u = Buffer.ReadOnes ();
     Buffer.Read (ctx);
     return u;
 }
Example #7
0
		public void Init()
		{
			rng = new Random(1337);
			data = new byte[128 * 1024]; // 128K
			rng.NextBytes(data);

			dbgAll = CreateBS(data);
		}
Example #8
0
 public int ArrayGet(IBitStream Buffer, int pos)
 {
     long p = pos;
     p *= this.NumBits;
     var ctx = new BitStreamCtx (p);
     int number = (int)Buffer.Read (this.NumBits, ctx);
     return number;
 }
Example #9
0
 public void Encode(IBitStream Buffer, int u)
 {
     if (u < 1) {
         throw new ArgumentOutOfRangeException (String.Format ("Invalid range for elias delta coding, u: {0}", u));
     }
     var log2 = BitAccess.Log2 (u);
     gammacoder.Encode (Buffer, log2);
     Buffer.Write (u, log2-1);
 }
Example #10
0
		public void Parse(IBitStream bitstream, DemoParser parser)
		{
			while (!bitstream.ChunkFinished) {
				var desc = bitstream.ReadProtobufVarInt();
				var wireType = desc & 7;
				var fieldnum = desc >> 3;

				if (wireType == 2) {
					if (fieldnum == 1) {
						Name = bitstream.ReadProtobufString();
						continue;
					} else if (fieldnum == 8) {
						// String data is special.
						// We'll simply hope that gaben is nice and sends
						// string_data last, just like he should.
						var len = bitstream.ReadProtobufVarInt();
						bitstream.BeginChunk(len * 8);
						DemoInfo.DP.Handler.CreateStringTableUserInfoHandler.Apply(this, bitstream, parser);
						bitstream.EndChunk();
						if (!bitstream.ChunkFinished)
							throw new NotImplementedException("Lord Gaben wasn't nice to us :/");
						break;
					} else
						throw new InvalidDataException("yes I know we should drop this but we" +
							"probably want to know that they added a new big field");
				}

				if (wireType != 0)
					throw new InvalidDataException();

				var val = bitstream.ReadProtobufVarInt();

				switch (fieldnum) {
				case 2:
					MaxEntries = val;
					break;
				case 3:
					NumEntries = val;
					break;
				case 4:
					_UserDataFixedSize = val;
					break;
				case 5:
					UserDataSize = val;
					break;
				case 6:
					UserDataSizeBits = val;
					break;
				case 7:
					Flags = val;
					break;
				default:
					// silently drop
					break;
				}
			}
		}
Example #11
0
			public void Parse(IBitStream bitstream)
			{
				while (!bitstream.ChunkFinished) {
					var desc = bitstream.ReadProtobufVarInt();
					var wireType = desc & 7;
					var fieldnum = desc >> 3;

					if (wireType == 2) {
						if (fieldnum == 2) {
							VarName = bitstream.ReadProtobufString();
						} else if (fieldnum == 5) {
							DtName = bitstream.ReadProtobufString();
						} else
							throw new InvalidDataException("yes I know we should drop this but we" +
								"probably want to know that they added a new big field");
					} else if (wireType == 0) {
						var val = bitstream.ReadProtobufVarInt();

						switch (fieldnum) {
						case 1:
							Type = val;
							break;
						case 3:
							Flags = val;
							break;
						case 4:
							Priority = val;
							break;
						case 6:
							NumElements = val;
							break;
						case 9:
							NumBits = val;
							break;
						default:
							// silently drop
							break;
						}
					} else if (wireType == 5) {
						var val = bitstream.ReadFloat();

						switch (fieldnum) {
						case 7:
							LowValue = val;
							break;
						case 8:
							HighValue = val;
							break;
						default:
							// silently drop
							break;
						}
					} else
						throw new InvalidDataException();
				}
			}
Example #12
0
		public void ParseStringTable(IBitStream reader, string tableName, DemoParser parser)
		{
            int numStrings = (int)reader.ReadInt(16);

			if (tableName == "modelprecache") {
				parser.modelprecache.Clear ();
			}

            for (int i = 0; i < numStrings; i++)
            {
                string stringName = reader.ReadString();

                if (stringName.Length >= 100)
                    throw new Exception("Roy said I should throw this.");

                if (reader.ReadBit())
                {
                    int userDataSize = (int)reader.ReadInt(16);

                    byte[] data = reader.ReadBytes(userDataSize);

					if (tableName == "userinfo") {
						PlayerInfo info = PlayerInfo.ParseFrom(new BinaryReader(new MemoryStream(data)));

						parser.RawPlayers[int.Parse(stringName)] = info;
					} else if (tableName == "instancebaseline") {
						int classid = int.Parse(stringName); //wtf volvo?

						parser.instanceBaseline[classid] = data; 
					} else if (tableName == "modelprecache") {
						parser.modelprecache.Add (stringName);
					}
                }
            }

            // Client side stuff
	        if ( reader.ReadBit() )
	        {
		        int numstrings = (int)reader.ReadInt(16);
		        for ( int i = 0 ; i < numstrings; i++ )
		        {
			        reader.ReadString(); // stringname

			        if ( reader.ReadBit() )
			        {
				        int userDataSize = ( int )reader.ReadInt(16);

				        reader.ReadBytes( userDataSize );

			        }
			        else
			        {
			        }
		        }
	        }
        }
Example #13
0
 public void Encode(IBitStream Buffer, int u)
 {
     if (u < 0) {
         throw new ArgumentOutOfRangeException (String.Format ("Invalid range for UnaryCoding, u: {0}", u));
     }
     Buffer.Write (false, u);
     Buffer.Write (true);
     //Buffer.Write (true, u);
     //Buffer.Write (false);
 }
Example #14
0
		public void ParsePacket(IBitStream reader, DemoParser parser)
        {
			int numTables = reader.ReadByte();

			for (int i = 0; i < numTables; i++) {
				string tableName = reader.ReadString();

				ParseStringTable(reader, tableName, parser);
			}
        }
Example #15
0
 public void Encode(IBitStream Buffer, int u)
 {
     if (u < 0) {
         throw new ArgumentOutOfRangeException (String.Format ("Invalid range for BlockCoding, u: {0}", u));
     }
     int skip = u >> this.Power;
     this.SkipCoder.Encode (Buffer, skip);
     u &= (1 << this.Power) - 1;
     Buffer.Write(u, this.Power);
 }
Example #16
0
 public int Decode(IBitStream Buffer, BitStreamCtx ctx)
 {
     int len_code = gammacoder.Decode (Buffer, ctx);
     len_code--;
     if (len_code == 0) {
         return 1;
     } else {
         int output = (int)Buffer.Read (len_code, ctx);
         // Console.WriteLine ("Decode> count: {0}, output: {1}", count, output);
         return (1 << len_code) + output;
     }
 }
		public static void Apply(UpdateStringTable update, IBitStream reader, DemoParser parser)
		{
			CreateStringTable create = parser.stringTables[update.TableId];
			if (create.Name == "userinfo" || create.Name == "modelprecache" || create.Name == "instancebaseline") {
				/*
				 * Ignore updates for everything except the 3 used tables.
				 * Create a fake CreateStringTable message and parse it.
				 */
				create.NumEntries = update.NumChangedEntries;
				CreateStringTableUserInfoHandler.Apply(create, reader, parser);
			}
		}
Example #18
0
		public void Parse(IBitStream bitstream, DemoParser parser)
		{
			while (!bitstream.ChunkFinished) {
				var desc = bitstream.ReadProtobufVarInt();
				var wireType = desc & 7;
				var fieldnum = desc >> 3;

				if ((fieldnum == 7) && (wireType == 2)) {
					// Entity data is special.
					// We'll simply hope that gaben is nice and sends
					// entity_data last, just like he should.

					var len = bitstream.ReadProtobufVarInt();
					bitstream.BeginChunk(len * 8);
					DemoInfo.DP.Handler.PacketEntitesHandler.Apply(this, bitstream, parser);
					bitstream.EndChunk();
					if (!bitstream.ChunkFinished)
						throw new NotImplementedException("Lord Gaben wasn't nice to us :/");
					break;
				}

				if (wireType != 0)
					throw new InvalidDataException();

				var val = bitstream.ReadProtobufVarInt();

				switch (fieldnum) {
				case 1:
					MaxEntries = val;
					break;
				case 2:
					UpdatedEntries = val;
					break;
				case 3:
					_IsDelta = val;
					break;
				case 4:
					_UpdateBaseline = val;
					break;
				case 5:
					Baseline = val;
					break;
				case 6:
					DeltaFrom = val;
					break;
				default:
					// silently drop
					break;
				}
			}
		}
Example #19
0
		/// <summary>
		/// Parses a demo-packet. 
		/// </summary>
		/// <param name="bitstream">Bitstream.</param>
		/// <param name="demo">Demo.</param>
		public static void ParsePacket(IBitStream bitstream, DemoParser demo)
        {
			//As long as there is stuff to read
			while (!bitstream.ChunkFinished)
            {
				int cmd = bitstream.ReadProtobufVarInt(); //What type of packet is this?
				int length = bitstream.ReadProtobufVarInt(); //And how long is it?
				bitstream.BeginChunk(length * 8); //read length bytes
				if (cmd == (int)SVC_Messages.svc_PacketEntities) { //Parse packet entities
					new PacketEntities().Parse(bitstream, demo); 
				} else if (cmd == (int)SVC_Messages.svc_GameEventList) { //and all this other stuff
					new GameEventList().Parse(bitstream, demo);
				} else if (cmd == (int)SVC_Messages.svc_GameEvent) {
					new GameEvent().Parse(bitstream, demo);
				} else if (cmd == (int)SVC_Messages.svc_CreateStringTable) {
					new CreateStringTable().Parse(bitstream, demo);
				} else if (cmd == (int)SVC_Messages.svc_UpdateStringTable) {
					new UpdateStringTable().Parse(bitstream, demo);
				} else if (cmd == (int)NET_Messages.net_Tick) { //and all this other stuff
						new NETTick().Parse(bitstream, demo);
				} else {
					//You can use this flag to see what information the other packets contain, 
					//if you want. Then you can look into the objects. Has some advnatages, and some disdavantages (mostly speed), 
					//so we use our own lightning-fast parsing code. 
					#if SLOW_PROTOBUF 
					Type toParse = null;

					if (Enum.IsDefined(typeof(SVC_Messages), cmd)) {
						SVC_Messages msg = (SVC_Messages)cmd;
						toParse = Assembly.GetExecutingAssembly().GetType("DemoInfo.Messages.CSVCMsg_" + msg.ToString().Substring(4));
					} else if (Enum.IsDefined(typeof(NET_Messages), cmd)) {
						NET_Messages msg = (NET_Messages)cmd;
						toParse = Assembly.GetExecutingAssembly().GetType("DemoInfo.Messages.CNETMsg_" + msg.ToString().Substring(4));
					}

					var data = bitstream.ReadBytes(length);
					if (toParse == null)
						continue;

					ProtoBuf.IExtensible result;
					using (var memstream = new MemoryStream(data))
						result = memstream.ReadProtobufMessage(toParse);

					foreach (var parser in Parsers)
						if (parser.TryApplyMessage(result, demo) && (parser.Priority > 0))
							break;
					#endif
				}
				bitstream.EndChunk();
            }
        }
Example #20
0
        public static Split Parse(IBitStream reader)
        {
            return(new Split
            {
                Flags = reader.ReadSignedInt(32),
                viewOrigin = Vector.Parse(reader),
                viewAngles = QAngle.Parse(reader),
                localViewAngles = QAngle.Parse(reader),

                viewOrigin2 = Vector.Parse(reader),
                viewAngles2 = QAngle.Parse(reader),
                localViewAngles2 = QAngle.Parse(reader),
            });
        }
        public static ClientBarrierResults DeSerializeClientBarrierResultsFromStream(Component context,
                                                                                     ref IBitStream stream)
        {
            var   barrierGUID       = -1;
            sbyte invalidActorIndex = (sbyte)ActorData.s_invalidActorIndex;

            stream.Serialize(ref barrierGUID);
            stream.Serialize(ref invalidActorIndex);
            var       actorToHitResults = DeSerializeActorHitResultsDictionaryFromStream(context, ref stream);
            var       posToHitResults   = DeSerializePositionHitResultsDictionaryFromStream(context, ref stream);
            ActorData actorByActorIndex = context.GameFlowData.FindActorByActorIndex(invalidActorIndex);

            return(new ClientBarrierResults(barrierGUID, actorByActorIndex, actorToHitResults, posToHitResults));
        }
 public void Serialize(Dictionary <int, double> newValues, IBitStream bitStream)
 {
     foreach (var newValue in newValues)
     {
         if (_lastValues.ContainsKey(newValue.Key))
         {
             _lastValues[newValue.Key] = newValue.Value;
         }
     }
     foreach (var serializer in _serializers)
     {
         serializer.Value.Serialize(_lastValues[serializer.Key], bitStream);
     }
 }
Example #23
0
        public void ParsePacket(Stream stream, DemoParser parser)
        {
            using (IBitStream reader = BitStreamUtil.Create(stream))
            {
                int numTables = reader.ReadByte();

                for (int i = 0; i < numTables; i++)
                {
                    string tableName = reader.ReadString();

                    ParseStringTable(reader, tableName, parser);
                }
            }
        }
Example #24
0
			public void Parse(IBitStream bitstream)
			{
				while (!bitstream.ChunkFinished) {
					var desc = bitstream.ReadProtobufVarInt();
					var wireType = desc & 7;
					var fieldnum = desc >> 3;
					if ((wireType == 0) && (fieldnum == 1)) {
						Type = bitstream.ReadProtobufVarInt();
					} else if ((wireType == 2) && (fieldnum == 2)) {
						Name = bitstream.ReadProtobufString();
					} else
						throw new InvalidDataException();
				}
			}
Example #25
0
        protected override void SerializeOverride(IBitStream stream, EventShuttle eventShuttle)
        {
            PrimitiveCollectionSerializeOverride(stream);

            var typeNode = (CollectionTypeNode)TypeNode;

            /* Add termination */
            if (typeNode.TerminationChild != null)
            {
                var terminationChild = typeNode.TerminationChild.CreateSerializer(this);
                terminationChild.Value = typeNode.TerminationValue;
                terminationChild.Serialize(stream, eventShuttle);
            }
        }
        /// <summary>
        /// Returns a string of count length containing characters extracted from the bit stream.
        /// </summary>
        /// <param name="bitStream"></param>
        /// <param name="count"></param>
        /// <returns></returns>
        public static string ExtractCharacters(IBitStream bitStream, int count)
        {
            var result = new StringBuilder();
            for(int i = 0;i < count;++i) {
                var ch = '\0';
                var encodedCh = bitStream.ReadByte(6);
                if(encodedCh > 0 && encodedCh < 27) ch = (char)('A' + (encodedCh - 1));
                else if(encodedCh == 32) ch = ' ';
                else if(encodedCh > 47 && encodedCh < 58) ch = (char)('0' + (encodedCh - 48));
                if(ch != '\0') result.Append(ch);
            }

            return result.ToString();
        }
Example #27
0
        public static void Apply(UpdateStringTable update, IBitStream reader, DemoParser parser)
        {
            CreateStringTable create = parser.stringTables[update.TableId];

            if (create.Name == "userinfo" || create.Name == "modelprecache" || create.Name == "instancebaseline")
            {
                /*
                 * Ignore updates for everything except the 3 used tables.
                 * Create a fake CreateStringTable message and parse it.
                 */
                create.NumEntries = update.NumChangedEntries;
                CreateStringTableUserInfoHandler.Apply(create, reader, parser);
            }
        }
Example #28
0
        int ReadABits(IBitStream input, int prev)
        {
            prev &= 0xFC;
            if (input.GetNextBit() == 0)
            {
                if (input.GetNextBit() == 0)
                {
                    return(prev);
                }
                else
                {
                    return(input.GetBits(6) << 2);
                }
            }
            else if (input.GetNextBit() == 0)
            {
                if (input.GetNextBit() == 0)
                {
                    return(prev + 4);
                }
                else
                {
                    return(prev - 4);
                }
            }
            else if (input.GetNextBit() == 0)
            {
                if (input.GetNextBit() == 0)
                {
                    return(prev + 8);
                }
                else
                {
                    return(prev - 8);
                }
            }
            else
            {
                switch (input.GetBits(2))
                {
                case 0:  return(Math.Min(prev + 16, 0xFC));

                case 1:  return(Math.Max(prev - 16, 0));

                case 2:  return(Math.Min(prev + 24, 0xFC));

                default: return(Math.Max(prev - 24, 0));
                }
            }
        }
Example #29
0
        int ReadShort(IBitStream input, int prev)
        {
            prev &= 0xFE;
            if (input.GetNextBit() == 0)
            {
                if (input.GetNextBit() == 0)
                {
                    return(prev);
                }
                else
                {
                    return(input.GetBits(6) << 2);
                }
            }
            else if (input.GetNextBit() == 0)
            {
                if (input.GetNextBit() == 0)
                {
                    return(prev + 2);
                }
                else
                {
                    return(prev - 2);
                }
            }
            else if (input.GetNextBit() == 0)
            {
                if (input.GetNextBit() == 0)
                {
                    return(prev + 4);
                }
                else
                {
                    return(prev - 4);
                }
            }
            else
            {
                switch (input.GetBits(2))
                {
                case 0:  return(Math.Min(prev + 8, 0xFE));

                case 1:  return(Math.Max(prev - 8, 0));

                case 2:  return(Math.Min(prev + 12, 0xFE));

                default: return(Math.Max(prev - 12, 0));
                }
            }
        }
Example #30
0
            public void SequenceStartData_SerializeToStream(ref IBitStream stream)
            {
                throw new NotImplementedException();
//                uint position = stream.Position;
//                byte bitfieldFromBools = CreateBitfieldFromBools(m_useTargetPos, m_useTargetSquare, m_useTargetRotation,
//                    m_sourceRemoveAtEndOfTurn, m_waitForClientEnable, false, false, false);
//                stream.Serialize(ref m_prefabID);
//                stream.Serialize(ref bitfieldFromBools);
//                if (m_useTargetPos)
//                    stream.Serialize(ref m_targetPos);
//                if (m_useTargetSquare)
//                {
//                    byte targetSquareX = (byte) m_targetSquareX;
//                    byte targetSquareY = (byte) m_targetSquareY;
//                    stream.Serialize(ref targetSquareX);
//                    stream.Serialize(ref targetSquareY);
//                }
//
//                if (m_useTargetRotation)
//                {
//                    float num = VectorUtils.HorizontalAngle_Deg(m_targetRotation * new Vector3(1f, 0.0f, 0.0f));
//                    stream.Serialize(ref num);
//                }
//
//                stream.Serialize(ref m_numTargetActors);
//                for (byte index = 0; (int) index < (int) m_numTargetActors; ++index)
//                {
//                    sbyte targetActorIndex = (sbyte) m_targetActorIndices[index];
//                    stream.Serialize(ref targetActorIndex);
//                }
//
//                sbyte casterActorIndex = (sbyte) m_casterActorIndex;
//                stream.Serialize(ref casterActorIndex);
//                stream.Serialize(ref m_sourceRootID);
//                stream.Serialize(ref m_numExtraParams);
//                for (int index = 0; index < (int) m_numExtraParams; ++index)
//                {
//                    var extraParam = m_extraParams[index];
//                    short enumOfExtraParam = (short) SequenceLookup.GetEnumOfExtraParam(extraParam);
//                    stream.Serialize(ref enumOfExtraParam);
//                    extraParam.XSP_SerializeToStream(stream);
//                }
//
//                uint num1 = stream.Position - position;
//                if (!ClientAbilityResults.Boolean_1)
//                    return;
//                Log.Print(LogType.Warning,
//                    $"\t\t\t\t\t Serializing Sequence Start Data, using targetPos? {m_useTargetPos} prefab id {m_prefabID}: \n\t\t\t\t\t numBytes: {num1}");
            }
Example #31
0
        void UnpackZeChunk(IBitStream bits, byte[] output, int dst, int unpacked_size)
        {
            int output_end = dst + unpacked_size;

            while (dst < output_end)
            {
                int count = LzeGetInteger(bits);
                if (-1 == count)
                {
                    break;
                }

                while (--count > 0)
                {
                    int data = bits.GetBits(8);
                    if (-1 == data)
                    {
                        break;
                    }

                    if (dst < output_end)
                    {
                        output[dst++] = (byte)data;
                    }
                }
                if (count > 0 || dst >= output_end)
                {
                    break;
                }

                int offset = LzeGetInteger(bits);
                if (-1 == offset)
                {
                    break;
                }
                count = LzeGetInteger(bits);
                if (-1 == count)
                {
                    break;
                }

                Binary.CopyOverlapped(output, dst - offset, dst, count);
                dst += count;
            }
            if (dst < output_end)
            {
                throw new EndOfStreamException("Premature end of compressed stream");
            }
        }
Example #32
0
        private static float ReadBitNormal(IBitStream reader)
        {
            var isNegative = reader.ReadBit();

            var fractVal = reader.ReadInt(NORMAL_FRACTIONAL_BITS);

            var value = fractVal * NORMAL_RESOLUTION;

            if (isNegative)
            {
                value *= -1;
            }

            return(value);
        }
        public static ClientAbilityResults DeSerializeClientAbilityResultsFromStream(Component context,
                                                                                     ref IBitStream stream)
        {
            sbyte invalidActorIndex = (sbyte)ActorData.s_invalidActorIndex;
            sbyte num = -1;

            stream.Serialize(ref invalidActorIndex);
            stream.Serialize(ref num);
            var seqStartDataList  = DeSerializeSequenceStartDataListFromStream(ref stream);
            var actorToHitResults = DeSerializeActorHitResultsDictionaryFromStream(context, ref stream);
            var posToHitResults   = DeSerializePositionHitResultsDictionaryFromStream(context, ref stream);

            return(new ClientAbilityResults(context, invalidActorIndex, num, seqStartDataList, actorToHitResults,
                                            posToHitResults));
        }
        public static List <int> DeSerializePowerupsToRemoveFromStream(ref IBitStream stream)
        {
            var   intList = new List <int>();
            sbyte num1    = 0;

            stream.Serialize(ref num1);
            for (var index = 0; index < (int)num1; ++index)
            {
                var num2 = 0;
                stream.Serialize(ref num2);
                intList.Add(num2);
            }

            return(intList);
        }
        public static List <int> DeSerializeClientOverconListFromStream(ref IBitStream stream)
        {
            var   intList = new List <int>();
            sbyte num1    = 0;

            stream.Serialize(ref num1);
            for (var index = 0; index < (int)num1; ++index)
            {
                var num2 = -1;
                stream.Serialize(ref num2);
                intList.Add(num2);
            }

            return(intList);
        }
        /// <summary>
        /// Counts different bits between two streams
        /// </summary>
        /// <param name="bitStream"><see cref="BitStream"/> to compare to</param>
        /// <returns>Number of different bits</returns>
        public int Difference(IBitStream bitStream)
        {
            var errorCount    = 0;
            var bitsToCompare = bitStream.ReadAllBits();

            for (int i = 0; i < _data.Length; i++)
            {
                if (_data[i] != bitsToCompare[i])
                {
                    errorCount++;
                }
            }

            return(errorCount);
        }
Example #37
0
        public IGameEvent DeSerialize(IBitStream stream)
        {
            var v1             = stream.ReadBits(8);//target, if mapvote this is a map index
            var v2             = stream.ReadBits(8);
            var v3             = stream.ReadBits(8);
            var v4             = stream.ReadBits(8);//target, if mapvote this is a map index
            var v5             = stream.ReadBits(8);
            var v6             = stream.ReadBits(8);
            var voteCaster     = stream.ReadBits(8);
            var updateVoteType = stream.ReadBits(8); //8 = updateparticipant status, 9 = updateclientstate
            var voteType       = stream.ReadBits(8); //0 = updatePendingVote, 1 = map, 2 = kick, 3 = mutiny
            var v10            = stream.ReadBits(32);

            return(new VoteEvent());
        }
Example #38
0
        public StreamResetter(IBitStream stream, bool resetOnDispose = true)
        {
            if (!resetOnDispose)
            {
                return;
            }

            if (!stream.CanSeek)
            {
                throw new InvalidOperationException("Not supported on non-seekable streams");
            }

            _stream   = stream;
            _position = _stream.Position;
        }
Example #39
0
 public void Encode(IBitStream Buffer, long u)
 {
     if (u < 1) {
         throw new ArgumentOutOfRangeException (String.Format ("Invalid range for elias gamma coding, u: {0}", u));
     }
     var log2 = BitAccess.Log2 (u);
     --log2;
     unary.Encode (Buffer, log2);
     if (log2 <= 32) {
         Buffer.Write ((int)u, log2);
     } else {
         Buffer.Write ((int)u, 32);
         Buffer.Write (u >> 32, log2 - 32);
     }
 }
Example #40
0
        static float ReadBitNormal(IBitStream reader)
        {
            bool isNegative = reader.ReadBit();

            uint fractVal = reader.ReadInt(NORMAL_FRACTIONAL_BITS);

            float value = (float)fractVal * NORMAL_RESOLUTION;

            if (isNegative)
            {
                value *= -1;
            }

            return(value);
        }
Example #41
0
        public static string ReadString(this IBitStream bs, int limit)
        {
            var result = new List <byte>(512);

            for (int pos = 0; pos < limit; pos++)
            {
                var b = bs.ReadByte();
                if ((b == 0) || (b == 10))
                {
                    break;
                }
                result.Add(b);
            }
            return(Encoding.ASCII.GetString(result.ToArray()));
        }
Example #42
0
        public void ParsePacket(IBitStream bitstream)
        {
            while (true)
            {
                var type = (SVC_Messages)bitstream.ReadProtobufVarInt();
                if (type != SVC_Messages.svc_SendTable)
                {
                    throw new Exception("Expected SendTable, got " + type);
                }

                var size = bitstream.ReadProtobufVarInt();
                bitstream.BeginChunk(size * 8);
                var sendTable = new SendTable(bitstream);
                bitstream.EndChunk();

                if (sendTable.IsEnd)
                {
                    break;
                }

                DataTables.Add(sendTable);
            }

            int serverClassCount = checked ((int)bitstream.ReadInt(16));

            for (int i = 0; i < serverClassCount; i++)
            {
                ServerClass entry = new ServerClass();
                entry.ClassID = checked ((int)bitstream.ReadInt(16));

                if (entry.ClassID > serverClassCount)
                {
                    throw new Exception("Invalid class index");
                }

                entry.Name   = bitstream.ReadDataTableString();
                entry.DTName = bitstream.ReadDataTableString();

                entry.DataTableID = DataTables.FindIndex(a => a.Name == entry.DTName);

                ServerClasses.Add(entry);
            }

            for (int i = 0; i < serverClassCount; i++)
            {
                FlattenDataTable(i);
            }
        }
 public void Serialize(IBitStream stream)//datablock events are different from game events
 {
     stream.WriteBits((uint)GameMode.Length, 0x10);
     stream.WriteString(GameMode, (uint)GameMode.Length);
     stream.WriteBits((uint)MapPath.Length, 0x10);
     stream.WriteString(MapPath, (uint)MapPath.Length);
     stream.WriteBits((uint)MapName.Length, 0x10);
     stream.WriteString(MapName, (uint)MapName.Length);
     stream.WriteBits(0, 1);
     stream.WriteBits(MaxPlayers, 31);
     stream.WriteBits(CommanderEnabled, 1);
     stream.WriteBits(0, 1);
     stream.WriteBits(ChallengeOrdinal, 31);
     stream.WriteBits(0, 1);
     stream.WriteBits(0, 1);
 }
Example #44
0
        public static uint ReadVarInt(this IBitStream bs)
        {
            uint tmpByte = 0x80;
            uint result  = 0;

            for (int count = 0; (tmpByte & 0x80) != 0; count++)
            {
                if (count > 5)
                {
                    throw new InvalidDataException("VarInt32 out of range");
                }
                tmpByte = bs.ReadByte();
                result |= (tmpByte & 0x7F) << (7 * count);
            }
            return(result);
        }
        public static List <int> DeSerializeBarriersForRemovalFromStream(ref IBitStream stream)
        {
            sbyte num1 = 0;

            stream.Serialize(ref num1);
            var intList = new List <int>(num1);

            for (var index = 0; index < (int)num1; ++index)
            {
                var num2 = -1;
                stream.Serialize(ref num2);
                intList.Add(num2);
            }

            return(intList);
        }
        public static List <ServerClientUtils.SequenceEndData> DeSerializeSequenceEndDataListFromStream(
            ref IBitStream stream)
        {
            var   sequenceEndDataList = new List <ServerClientUtils.SequenceEndData>();
            sbyte num = 0;

            stream.Serialize(ref num);
            for (var index = 0; index < (int)num; ++index)
            {
                ServerClientUtils.SequenceEndData sequenceEndData =
                    ServerClientUtils.SequenceEndData.SequenceEndData_DeserializeFromStream(ref stream);
                sequenceEndDataList.Add(sequenceEndData);
            }

            return(sequenceEndDataList);
        }
Example #47
0
        static int GetBitLength(IBitStream input)
        {
            int count = 0;

            while (0 == input.GetNextBit())
            {
                ++count;
            }
            int n = 1 << count;

            if (count > 0)
            {
                n |= input.GetBits(count);
            }
            return(n);
        }
Example #48
0
 public static int DecodeInt(SendTableProperty prop, IBitStream reader)
 {
     if (prop.Flags.HasFlagFast(SendPropertyFlags.VarInt))
     {
         if (prop.Flags.HasFlagFast(SendPropertyFlags.Unsigned))
         {
             return((int)reader.ReadVarInt());
         }
         return((int)reader.ReadSignedVarInt());
     }
     if (prop.Flags.HasFlagFast(SendPropertyFlags.Unsigned))
     {
         return((int)reader.ReadInt(prop.NumberOfBits));
     }
     return(reader.ReadSignedInt(prop.NumberOfBits));
 }
Example #49
0
        public static float DecodeFloat(SendTableProperty prop, IBitStream reader)
        {
            float fVal = 0.0f;
            ulong dwInterp;

            if (DecodeSpecialFloat(prop, reader, out fVal))
                return fVal;

            //Encoding: The range between lowVal and highVal is splitted into the same steps.
            //Read an int, fit it into the range.
            dwInterp = reader.ReadInt(prop.NumberOfBits);
            fVal = (float)dwInterp / ( ( 1 << prop.NumberOfBits ) - 1 );
            fVal = prop.LowValue + ( prop.HighValue - prop.LowValue ) * fVal;

            return fVal;
        }
Example #50
0
        public void ApplyUpdate(IBitStream reader)
        {
            bool newWay  = reader.ReadBit();
            int  index   = -1;
            var  entries = new List <PropertyEntry>();

            while ((index = ReadFieldIndex(reader, index, newWay)) != -1)
            {
                entries.Add(this.Props[index]);
            }

            foreach (var prop in entries)
            {
                prop.Decode(reader, this);
            }
        }
Example #51
0
//            public SequenceEndData(
//                GameObject prefabToEnd,
//                AssociationType associationType,
//                int guid,
//                Vector3 targetPos)
//            {
//                m_prefabId = SequenceLookup.Get().GetSequenceIdOfPrefab(prefabToEnd);
//                m_associationType = associationType;
//                m_association = (uint) Mathf.Max(0, guid);
//                m_targetPos = targetPos;
//            }

            public void SequenceEndData_SerializeToStream(ref IBitStream stream)
            {
                sbyte associationType = (sbyte)m_associationType;

                stream.Serialize(ref m_prefabId);
                stream.Serialize(ref associationType);
                stream.Serialize(ref m_association);
                bool flag = m_targetPos != Vector3.Zero;

                stream.Serialize(ref flag);
                if (!flag)
                {
                    return;
                }
                stream.Serialize(ref m_targetPos);
            }
Example #52
0
		public static int DecodeInt(SendTableProperty prop, IBitStream reader)
		{
			if (prop.Flags.HasFlagFast(SendPropertyFlags.VarInt)) {
				if (prop.Flags.HasFlagFast(SendPropertyFlags.Unsigned)) {
					return (int)reader.ReadVarInt();
				} else {
					return (int)reader.ReadSignedVarInt();
				}
			} else {
				if (prop.Flags.HasFlagFast(SendPropertyFlags.Unsigned)) {
					return (int)reader.ReadInt(prop.NumberOfBits);
				} else {
					return reader.ReadSignedInt(prop.NumberOfBits);
				}
			}
		}
        public virtual int ProcessReceivedPacket(IBitStream stream)
        {
            uint val1 = stream.ReadBits(1);

            if (val1 != 1)
            {
                return(1);
            }
            uint someVal  = stream.ReadBits(32);
            uint someVal2 = stream.ReadBits(8);
            uint someVal3 = stream.ReadBits(1);

            ReadControlObjectState(stream);
            ReadData(stream);
            return(0);
        }
        /// <summary>
        /// Counts different bits between two streams
        /// </summary>
        /// <param name="bitStream"><see cref="BitStream"/> to compare to</param>
        /// <returns>All the positions that are different</returns>
        public List <int> DifferenceWithPositions(IBitStream bitStream)
        {
            var errors        = new List <int>();
            var bitsToCompare = bitStream.ReadAllBits();

            for (int i = 0; i < _data.Length; i++)
            {
                if (_data[i] != bitsToCompare[i])
                {
                    // Add position as human readable number
                    errors.Add(i + 1);
                }
            }

            return(errors);
        }
Example #55
0
		private IEnumerable<Descriptor> ReadDescriptors(IBitStream bitstream)
		{
			while (!bitstream.ChunkFinished) {
				var desc = bitstream.ReadProtobufVarInt();
				var wireType = desc & 7;
				var fieldnum = desc >> 3;
				if ((wireType != 2) || (fieldnum != 1))
					throw new InvalidDataException();

				var length = bitstream.ReadProtobufVarInt();
				bitstream.BeginChunk(length * 8);
				var descriptor = new Descriptor();
				descriptor.Parse(bitstream);
				yield return descriptor;
				bitstream.EndChunk();
			}
		}
Example #56
0
 public static int DecodeInt(SendTableProperty prop, IBitStream reader)
 {
     if (prop.Flags.HasFlagFast(SendPropertyFlags.VarInt)) {
         if (prop.Flags.HasFlagFast(SendPropertyFlags.Unsigned)) {
             return (int)reader.ReadVarInt();
         } else {
             Trace.WriteLine("signed varints are not implemented. BAAAAAAD.", "PropDecoder:DecodeInt()");
             return (int)reader.ReadVarInt();
         }
     } else {
         if (prop.Flags.HasFlagFast(SendPropertyFlags.Unsigned)) {
             return (int)reader.ReadInt(prop.NumberOfBits);
         } else {
             return reader.ReadSignedInt(prop.NumberOfBits);
         }
     }
 }
Example #57
0
 public long Decode(IBitStream Buffer, BitStreamCtx ctx)
 {
     int numbits = unary.Decode (Buffer, ctx);
     if (numbits == 0) {
         return 1L;
     } else {
         ulong number;
         if (numbits <= 32) {
             number = Buffer.Read (numbits, ctx);
         } else {
             number = Buffer.Read (32, ctx);
             number |= Buffer.Read (numbits - 32, ctx) << 32;
         }
         number = (1UL << numbits) | number;
         return (long)number;
     }
 }
Example #58
0
        public int SignonLength { get; private set; }				// length of sigondata in bytes

        public static DemoHeader ParseFrom(IBitStream reader)
        {
            return new DemoHeader() {
                Filestamp = reader.ReadCString(8),
                Protocol = reader.ReadSignedInt(32),
				NetworkProtocol = reader.ReadSignedInt(32),
                ServerName = reader.ReadCString(MAX_OSPATH),

                ClientName = reader.ReadCString(MAX_OSPATH),
                MapName = reader.ReadCString(MAX_OSPATH),
                GameDirectory = reader.ReadCString(MAX_OSPATH),
				PlaybackTime = reader.ReadFloat(),

				PlaybackTicks = reader.ReadSignedInt(32),
				PlaybackFrames = reader.ReadSignedInt(32),
				SignonLength = reader.ReadSignedInt(32),
            };
        }
Example #59
0
 public int Decode(IBitStream stream, int N, BitStreamCtx ctx)
 {
     int min = 0;
     int max = N - 1;
     int mid;
     do {
         mid = (min >> 1) + (max >> 1);
         if (1 == (min & 1 & max)) {
             mid++;
         }
         if (!stream.Read (ctx)) {
             max = mid;
         } else {
             min = mid + 1;
         }
     } while (min < max);
     return min;
 }
Example #60
0
 public int Decode(IBitStream stream, BitStreamCtx ctx)
 {
     HuffmanInner node = this.Huffman.Root;
     while (true) {
         bool b = stream.Read (ctx);
         HuffmanNode next;
         if (b) {
             next = node.Right;
         } else {
             next = node.Left;
         }
         var leaf = next as HuffmanLeaf;
         if (leaf != null) {
             return leaf.Symbol;
         }
         node = next as HuffmanInner;
     }
 }