/// <summary> /// Reads a Vector2 /// </summary> public static Vector2 ReadVector2(NetBuffer buffer) { Vector2 retval; retval.X = buffer.ReadSingle(); retval.Y = buffer.ReadSingle(); return retval; }
public void SendMessageTCP(SocketMessageCMD rCMD, NetBuffer rBuffer) { NetBuffer buf = new NetBuffer(); buf.WriteShort((UInt16)rCMD); buf.WriteBytes(rBuffer.ToBytes()); SocketClient.SendMessageTCP(buf); }
/// <summary> /// Writes a Vector4 /// </summary> public static void Write(NetBuffer buffer, Vector4 vector) { buffer.Write(vector.X); buffer.Write(vector.Y); buffer.Write(vector.Z); buffer.Write(vector.W); }
/// <summary> /// Reads a matrix written using WriteMatrix() /// </summary> public static void ReadMatrix(NetBuffer buffer, ref Matrix destination) { Quaternion rot = ReadRotation(buffer, 24); destination = Matrix.CreateFromQuaternion(rot); destination.M41 = buffer.ReadSingle(); destination.M42 = buffer.ReadSingle(); destination.M43 = buffer.ReadSingle(); }
/// <summary> /// Reads a unit quaternion written using WriteRotation(... ,bitsPerElement) /// </summary> public static Quaternion ReadRotation(NetBuffer buffer, int bitsPerElement) { Quaternion retval; retval.X = buffer.ReadSignedSingle(bitsPerElement); retval.Y = buffer.ReadSignedSingle(bitsPerElement); retval.Z = buffer.ReadSignedSingle(bitsPerElement); retval.W = buffer.ReadSignedSingle(bitsPerElement); return retval; }
/// <summary> /// Reads a bounding sphere written using Write(buffer, BoundingSphere) /// </summary> public static BoundingSphere ReadBoundingSphere(NetBuffer buffer) { BoundingSphere retval; retval.Center.X = buffer.ReadSingle(); retval.Center.Y = buffer.ReadSingle(); retval.Center.Z = buffer.ReadSingle(); retval.Radius = buffer.ReadSingle(); return retval; }
/// <summary> /// Reads a Vector4 /// </summary> public static Vector4 ReadVector4(NetBuffer buffer) { Vector4 retval; retval.X = buffer.ReadSingle(); retval.Y = buffer.ReadSingle(); retval.Z = buffer.ReadSingle(); retval.W = buffer.ReadSingle(); return retval; }
/// <summary> /// Reads a matrix written using WriteMatrix() /// </summary> public static Matrix ReadMatrix(NetBuffer buffer) { Quaternion rot = ReadRotation(buffer, 24); Matrix retval = Matrix.CreateFromQuaternion(rot); retval.M41 = buffer.ReadSingle(); retval.M42 = buffer.ReadSingle(); retval.M43 = buffer.ReadSingle(); return retval; }
/// <summary> /// Reads a unit vector written using WriteUnitVector3(numberOfBits) /// </summary> public static Vector3 ReadUnitVector3(NetBuffer buffer, int numberOfBits) { int halfBits = numberOfBits / 2; float phi = buffer.ReadSignedSingle(halfBits) * (float)Math.PI; float theta = buffer.ReadSignedSingle(numberOfBits - halfBits) * (float)(Math.PI * 0.5); Vector3 retval; retval.X = (float)(Math.Sin(phi) * Math.Cos(theta)); retval.Y = (float)(Math.Cos(phi) * Math.Cos(theta)); retval.Z = (float)Math.Sin(theta); return retval; }
internal SerializedAssetBundle(NetBuffer buffer) { uint size = buffer.ReadVariableUInt32(); _bytes = buffer.ReadBytes((int)size); }
/// <summary> /// Append all the bits of message to this message /// </summary> public void Write(NetBuffer buffer) { EnsureBufferSize(m_bitLength + (buffer.LengthBytes * 8)); Write(buffer.m_data, 0, buffer.LengthBytes); // did we write excessive bits? int bitsInLastByte = (buffer.m_bitLength % 8); if (bitsInLastByte != 0) { int excessBits = 8 - bitsInLastByte; m_bitLength -= excessBits; } }
/// <summary> /// Creates messages to every GridCell from the players positions that has been changed and /// sends them to the players in the GridCell and its neighbours. /// </summary> /// <returns>Returns the overall sent bytes by this call.</returns> public int SendPlayerMovementInfoByGridCell() { List <byte[]> gridData = new List <byte[]>(); int sentBytes = 0; NetOutgoingMessage msgOut; NetBuffer buffer; //Serializing data for every GridCell at once. foreach (var grid in Data.Grid) { buffer = new NetBuffer(); buffer.Write((byte)MessageType.PlayerMovement); buffer.Write((ushort)grid.PlayersById.Count, 16); ushort dataCount = 0; foreach (var player in grid.PlayersById.Values) { if (player.DirtyPos) { buffer.Write(player.Id, 16); buffer.Write(TransformFloatToUshort(player.Position.X), 16); buffer.Write(TransformFloatToUshort(player.Position.Z), 16); player.DirtyPos = false; dataCount++; } } buffer.WriteAt(8, dataCount); gridData.Add(buffer.Data); } int i = 0; int gridIndex; int index; int GRID_RESOLUTION = WorldDataHandler.GRID_RESOLUTION; //Iterating through every GridCell and sending the data from it to its neighbours players including itself. foreach (var grid in Data.Grid) { foreach (var player in grid.PlayersById.Values) { index = 0; gridIndex = i / GRID_RESOLUTION; for (int y = gridIndex - 1; y < gridIndex + 2; y++) { for (int x = (i % GRID_RESOLUTION) - 1; x < (i % GRID_RESOLUTION) + 2; x++) { index = y * GRID_RESOLUTION + x; if (index >= 0 && index < gridData.Count && x >= 0 && x < GRID_RESOLUTION) { msgOut = Server.CreateMessage(); msgOut.Write(gridData[index]); if (player.GetConnection() != null) { player.GetConnection().SendMessage(msgOut, NetDeliveryMethod.Unreliable, 0); } sentBytes += gridData[index].Length; } } } } i++; } return(sentBytes); }
void SendSnapshotTo(NetConnection conn, NetConnectionSnapshotState connState, float deltaTime) { WorldSnapshot worldSnapshot = connState.WorldSnapshot; ushort epid = connState.OutboundSnapshotId; connState.OutboundSnapshotId++; //connState.TimeSinceLastSend -= deltaTime; //connState.GotPacket = false; connState.WorldSnapshot.MaxClientTickrate = DashCMD.GetCVar <ushort>("ag_max_cl_tickrate"); connState.WorldSnapshot.ForceSnapshotAwait = DashCMD.GetCVar <bool>("ag_cl_force_await_snap"); NetOutboundPacket packet = new NetOutboundPacket(NetDeliveryMethod.Unreliable); packet.SendImmediately = true; int size = packet.Length; packet.Write((byte)CustomPacketType.Snapshot); packet.Write(epid); int _packetheader = packet.Length - size; size = packet.Length; // Write snapshot system data snapshotSystem.OnOutbound(packet, conn); int _acks = packet.Length - size; size = packet.Length; // Write players charSnapshotSystem.OnServerOutbound(packet, connState); // Invoke event if (OnWorldSnapshotOutbound != null) { OnWorldSnapshotOutbound(this, worldSnapshot); } // Serialize snapshot NetBuffer buffer = new NetBuffer(); worldSnapshot.Serialize(buffer); packet.Write((ushort)buffer.Length); packet.WriteBytes(buffer.Data, 0, buffer.Length); int _playerdata = packet.Length - size; size = packet.Length; int _terraindata = connState.WorldSnapshot.TerrainSnapshot.LastByteSize; _playerdata -= _terraindata; // Send packet conn.SendPacket(packet); if (connState != null) { SnapshotStats stats = connState.Stats; stats.PacketHeader = _packetheader; stats.Acks = _acks; stats.PlayerData = _playerdata; stats.TerrainData = _terraindata; } }
public void ClientWrite(NetBuffer msg, object[] extraData = null) { SharedWrite(msg, extraData); syncItemsDelay = 1.0f; }
public void ServerWrite(NetBuffer msg, Client c, object[] extraData = null) { //ID of the launched projectile msg.Write(((Item)extraData[2]).ID); }
public abstract void Read(NetBuffer msg);
public void ServerRead(ClientNetObject type, NetBuffer msg, Client c) { List <Wire>[] wires = new List <Wire> [Connections.Count]; //read wire IDs for each connection for (int i = 0; i < Connections.Count; i++) { wires[i] = new List <Wire>(); int wireCount = msg.ReadRangedInteger(0, Connection.MaxLinked); for (int j = 0; j < wireCount; j++) { ushort wireId = msg.ReadUInt16(); Item wireItem = Entity.FindEntityByID(wireId) as Item; if (wireItem == null) { continue; } Wire wireComponent = wireItem.GetComponent <Wire>(); if (wireComponent != null) { wires[i].Add(wireComponent); } } } item.CreateServerEvent(this); //check if the character can access this connectionpanel //and all the wires they're trying to connect if (!item.CanClientAccess(c)) { return; } for (int i = 0; i < Connections.Count; i++) { foreach (Wire wire in wires[i]) { //wire not found in any of the connections yet (client is trying to connect a new wire) // -> we need to check if the client has access to it if (!Connections.Any(connection => connection.Wires.Contains(wire))) { if (!wire.Item.CanClientAccess(c)) { return; } } } } //go through existing wire links for (int i = 0; i < Connections.Count; i++) { for (int j = 0; j < Connection.MaxLinked; j++) { Wire existingWire = Connections[i].Wires[j]; if (existingWire == null) { continue; } //existing wire not in the list of new wires -> disconnect it if (!wires[i].Contains(existingWire)) { if (existingWire.Locked) { //this should not be possible unless the client is running a modified version of the game GameServer.Log(c.Character.LogName + " attempted to disconnect a locked wire from " + Connections[i].Item.Name + " (" + Connections[i].Name + ")", ServerLog.MessageType.Error); continue; } existingWire.RemoveConnection(item); if (existingWire.Connections[0] == null && existingWire.Connections[1] == null) { GameServer.Log(c.Character.LogName + " disconnected a wire from " + Connections[i].Item.Name + " (" + Connections[i].Name + ")", ServerLog.MessageType.ItemInteraction); } else if (existingWire.Connections[0] != null) { GameServer.Log(c.Character.LogName + " disconnected a wire from " + Connections[i].Item.Name + " (" + Connections[i].Name + ") to " + existingWire.Connections[0].Item.Name + " (" + existingWire.Connections[0].Name + ")", ServerLog.MessageType.ItemInteraction); //wires that are not in anyone's inventory (i.e. not currently being rewired) //can never be connected to only one connection // -> the client must have dropped the wire from the connection panel if (existingWire.Item.ParentInventory == null && !wires.Any(w => w.Contains(existingWire))) { //let other clients know the item was also disconnected from the other connection existingWire.Connections[0].Item.CreateServerEvent(existingWire.Connections[0].Item.GetComponent <ConnectionPanel>()); existingWire.Item.Drop(c.Character); } } else if (existingWire.Connections[1] != null) { GameServer.Log(c.Character.LogName + " disconnected a wire from " + Connections[i].Item.Name + " (" + Connections[i].Name + ") to " + existingWire.Connections[1].Item.Name + " (" + existingWire.Connections[1].Name + ")", ServerLog.MessageType.ItemInteraction); if (existingWire.Item.ParentInventory == null && !wires.Any(w => w.Contains(existingWire))) { //let other clients know the item was also disconnected from the other connection existingWire.Connections[1].Item.CreateServerEvent(existingWire.Connections[1].Item.GetComponent <ConnectionPanel>()); existingWire.Item.Drop(c.Character); } } Connections[i].Wires[j] = null; } } } //go through new wires for (int i = 0; i < Connections.Count; i++) { foreach (Wire newWire in wires[i]) { //already connected, no need to do anything if (Connections[i].Wires.Contains(newWire)) { continue; } Connections[i].TryAddLink(newWire); newWire.Connect(Connections[i], true, true); var otherConnection = newWire.OtherConnection(Connections[i]); if (otherConnection == null) { GameServer.Log(c.Character.LogName + " connected a wire to " + Connections[i].Item.Name + " (" + Connections[i].Name + ")", ServerLog.MessageType.ItemInteraction); } else { GameServer.Log(c.Character.LogName + " connected a wire from " + Connections[i].Item.Name + " (" + Connections[i].Name + ") to " + (otherConnection == null ? "none" : otherConnection.Item.Name + " (" + (otherConnection.Name) + ")"), ServerLog.MessageType.ItemInteraction); } } } }
public void Read(NetBuffer msg) { long oldPos = msg.Position; UInt32 size = msg.ReadVariableUInt32(); float x; float y; float z; float w; byte r; byte g; byte b; byte a; int ix; int iy; int width; int height; switch (typeString) { case "float": if (size != 4) { break; } property.SetValue(serverSettings, msg.ReadFloat()); return; case "vector2": if (size != 8) { break; } x = msg.ReadFloat(); y = msg.ReadFloat(); property.SetValue(serverSettings, new Vector2(x, y)); return; case "vector3": if (size != 12) { break; } x = msg.ReadFloat(); y = msg.ReadFloat(); z = msg.ReadFloat(); property.SetValue(serverSettings, new Vector3(x, y, z)); return; case "vector4": if (size != 16) { break; } x = msg.ReadFloat(); y = msg.ReadFloat(); z = msg.ReadFloat(); w = msg.ReadFloat(); property.SetValue(serverSettings, new Vector4(x, y, z, w)); return; case "color": if (size != 4) { break; } r = msg.ReadByte(); g = msg.ReadByte(); b = msg.ReadByte(); a = msg.ReadByte(); property.SetValue(serverSettings, new Color(r, g, b, a)); return; case "rectangle": if (size != 16) { break; } ix = msg.ReadInt32(); iy = msg.ReadInt32(); width = msg.ReadInt32(); height = msg.ReadInt32(); property.SetValue(serverSettings, new Rectangle(ix, iy, width, height)); return; default: msg.Position = oldPos; //reset position to properly read the string string incVal = msg.ReadString(); property.TrySetValue(serverSettings, incVal); return; } //size didn't match: skip this msg.Position += 8 * size; }
public abstract void Write(NetBuffer msg);
protected virtual void WriteEvent(NetBuffer buffer, NetEntityEvent entityEvent, Client recipient = null) { throw new NotImplementedException(); }
/// <summary> /// Write the events to the outgoing message. The recipient parameter is only needed for ServerEntityEventManager /// </summary> protected void Write(NetOutgoingMessage msg, List <NetEntityEvent> eventsToSync, Client recipient = null) { //write into a temporary buffer so we can write the number of events before the actual data NetBuffer tempBuffer = new NetBuffer(); int eventCount = 0; foreach (NetEntityEvent e in eventsToSync) { //write into a temporary buffer so we can write the length before the actual data NetBuffer tempEventBuffer = new NetBuffer(); try { WriteEvent(tempEventBuffer, e, recipient); } catch (Exception exception) { DebugConsole.ThrowError("Failed to write an event for the entity \"" + e.Entity + "\"", exception); GameAnalyticsManager.AddErrorEventOnce("NetEntityEventManager.Write:WriteFailed" + e.Entity.ToString(), GameAnalyticsSDK.Net.EGAErrorSeverity.Error, "Failed to write an event for the entity \"" + e.Entity + "\"\n" + exception.StackTrace); //write an empty event to avoid messing up IDs //(otherwise the clients might read the next event in the message and think its ID //is consecutive to the previous one, even though we skipped over this broken event) tempBuffer.Write((UInt16)0); tempBuffer.WritePadBits(); eventCount++; continue; } if (msg.LengthBytes + tempBuffer.LengthBytes + tempEventBuffer.LengthBytes > NetPeerConfiguration.kDefaultMTU - 20) { //no more room in this packet break; } if (tempEventBuffer.LengthBytes > 255) { DebugConsole.ThrowError("Too much data in network event for entity \"" + e.Entity.ToString() + "\" (" + tempEventBuffer.LengthBytes + " bytes"); GameAnalyticsManager.AddErrorEventOnce("NetEntityEventManager.Write:TooLong" + e.Entity.ToString(), GameAnalyticsSDK.Net.EGAErrorSeverity.Error, "Too much data in network event for entity \"" + e.Entity.ToString() + "\" (" + tempEventBuffer.LengthBytes + " bytes"); //write an empty event breaking the event syncing tempBuffer.Write((UInt16)0); tempBuffer.WritePadBits(); eventCount++; continue; } //the ID has been taken by another entity (the original entity has been removed) -> write an empty event else if (Entity.FindEntityByID(e.Entity.ID) != e.Entity || e.Entity.IdFreed) { //technically the clients don't have any use for these, but removing events and shifting the IDs of all //consecutive ones is so error-prone that I think this is a safer option tempBuffer.Write((UInt16)0); tempBuffer.WritePadBits(); } else { tempBuffer.Write((UInt16)e.Entity.ID); tempBuffer.Write((byte)tempEventBuffer.LengthBytes); tempBuffer.Write(tempEventBuffer); tempBuffer.WritePadBits(); } eventCount++; } if (eventCount > 0) { msg.Write(eventsToSync[0].ID); msg.Write((byte)eventCount); msg.Write(tempBuffer); } }
public void ClientReadPosition(ServerNetObject type, NetBuffer msg, float sendingTime) { Vector2 newPosition = new Vector2(msg.ReadFloat(), msg.ReadFloat()); float newRotation = msg.ReadRangedSingle(0.0f, MathHelper.TwoPi, 7); bool awake = msg.ReadBoolean(); Vector2 newVelocity = Vector2.Zero; if (awake) { newVelocity = new Vector2( msg.ReadRangedSingle(-MaxVel, MaxVel, 12), msg.ReadRangedSingle(-MaxVel, MaxVel, 12)); } if (body == null) { DebugConsole.ThrowError("Received a position update for an item with no physics body (" + Name + ")"); return; } body.FarseerBody.Awake = awake; if (body.FarseerBody.Awake) { if ((newVelocity - body.LinearVelocity).Length() > 8.0f) { body.LinearVelocity = newVelocity; } } else { try { body.FarseerBody.Enabled = false; } catch (Exception e) { DebugConsole.ThrowError("Exception in PhysicsBody.Enabled = false (" + body.PhysEnabled + ")", e); if (body.UserData != null) { DebugConsole.NewMessage("PhysicsBody UserData: " + body.UserData.GetType().ToString(), Color.Red); } if (GameMain.World.ContactManager == null) { DebugConsole.NewMessage("ContactManager is null!", Color.Red); } else if (GameMain.World.ContactManager.BroadPhase == null) { DebugConsole.NewMessage("Broadphase is null!", Color.Red); } if (body.FarseerBody.FixtureList == null) { DebugConsole.NewMessage("FixtureList is null!", Color.Red); } } } if ((newPosition - SimPosition).Length() > body.LinearVelocity.Length() * 2.0f) { body.SetTransform(newPosition, newRotation); Vector2 displayPos = ConvertUnits.ToDisplayUnits(body.SimPosition); rect.X = (int)(displayPos.X - rect.Width / 2.0f); rect.Y = (int)(displayPos.Y + rect.Height / 2.0f); } }
/// <summary> /// Writes an orthonormal matrix (rotation, translation but no scaling or projection) /// </summary> public static void WriteMatrix(NetBuffer buffer, Matrix matrix) { Quaternion rot = Quaternion.CreateFromRotationMatrix(matrix); WriteRotation(buffer, rot, 24); buffer.Write(matrix.M41); buffer.Write(matrix.M42); buffer.Write(matrix.M43); }
override public void Write(NetBuffer msg) { }
public override void Write(NetBuffer buffer) { buffer.Write(Serializer.Serialize(_get())); StoreValue(); }
override public void Read(NetBuffer msg) { }
public override void Write(NetBuffer msg) { msg.Write(success); }
public void ServerWrite(NetBuffer msg, Client c, object[] extraData = null) { ClientWrite(msg, extraData); }
//static because we may need to instantiate the campaign if it hasn't been done yet public static void ClientRead(NetBuffer msg) { byte campaignID = msg.ReadByte(); UInt16 updateID = msg.ReadUInt16(); UInt16 saveID = msg.ReadUInt16(); string mapSeed = msg.ReadString(); UInt16 currentLocIndex = msg.ReadUInt16(); UInt16 selectedLocIndex = msg.ReadUInt16(); int money = msg.ReadInt32(); UInt16 purchasedItemCount = msg.ReadUInt16(); List <PurchasedItem> purchasedItems = new List <PurchasedItem>(); for (int i = 0; i < purchasedItemCount; i++) { UInt16 itemPrefabIndex = msg.ReadUInt16(); UInt16 itemQuantity = msg.ReadUInt16(); purchasedItems.Add(new PurchasedItem(MapEntityPrefab.List[itemPrefabIndex] as ItemPrefab, itemQuantity)); } MultiPlayerCampaign campaign = GameMain.GameSession?.GameMode as MultiPlayerCampaign; if (campaign == null || campaignID != campaign.CampaignID) { string savePath = SaveUtil.CreateSavePath(SaveUtil.SaveType.Multiplayer); GameMain.GameSession = new GameSession(null, savePath, GameModePreset.list.Find(g => g.Name == "Campaign")); campaign = ((MultiPlayerCampaign)GameMain.GameSession.GameMode); campaign.CampaignID = campaignID; campaign.GenerateMap(mapSeed); } GameMain.NetLobbyScreen.ToggleCampaignMode(true); if (NetIdUtils.IdMoreRecent(campaign.lastUpdateID, updateID)) { return; } //server has a newer save file if (NetIdUtils.IdMoreRecent(saveID, campaign.PendingSaveID)) { /*//stop any active campaign save transfers, they're outdated now * List<FileReceiver.FileTransferIn> saveTransfers = * GameMain.Client.FileReceiver.ActiveTransfers.FindAll(t => t.FileType == FileTransferType.CampaignSave); * * foreach (var transfer in saveTransfers) * { * GameMain.Client.FileReceiver.StopTransfer(transfer); * } * * GameMain.Client.RequestFile(FileTransferType.CampaignSave, null, null);*/ campaign.PendingSaveID = saveID; } //we've got the latest save file else if (!NetIdUtils.IdMoreRecent(saveID, campaign.lastSaveID)) { campaign.Map.SetLocation(currentLocIndex == UInt16.MaxValue ? -1 : currentLocIndex); campaign.Map.SelectLocation(selectedLocIndex == UInt16.MaxValue ? -1 : selectedLocIndex); campaign.Money = money; campaign.CargoManager.SetPurchasedItems(purchasedItems); campaign.lastUpdateID = updateID; } }
public void ClientWrite(NetBuffer msg, object[] extraData) { msg.WriteRangedInteger(0, 10, (int)(rechargeSpeed / MaxRechargeSpeed * 10)); }
/// <summary> /// Sends a buff remove message that will be sent to /// the players in the entity's GridCell and its neighbours. /// </summary> /// <param name="entity">The buff removed from this entity</param> /// <param name="buff">The buff that is removed</param> public void SendBuffRemove(Entity entity, Buff buff) { NetBuffer data = CreateBuffRemovePackage(entity, buff); SendDataToNeigbours(data.Data, entity.GridCell); }
/// <summary> /// Runs the server /// </summary> public void Start(object state) { NetBuffer buffer = new NetBuffer(bufferSize); CancellationToken cts = (CancellationToken)state; while (true) { // Listen for a new connection server.Listen(1); using (Socket socket = server.Accept()) { // Attempt pairing with the new client socket.Receive(buffer); // Receive the dimensions of the image uint requestedWidth = buffer.GetUInt(0); uint requestedHeight = buffer.GetUInt(4); // Dimesions are too large if (requestedHeight > MAX_DIMENSION_SIZE || requestedWidth > MAX_DIMENSION_SIZE) { socket.Send(buffer.Reset().Write(DIMENSIONS_TOO_LARGE)); continue; } // Sends the dimensions to client to verify socket.Send(buffer); socket.Receive(buffer); // Dimensions mismatch if (requestedHeight != buffer.GetUInt(4) || requestedWidth != buffer.GetUInt(0)) { socket.Send(buffer.Write(DIMENSIONS_MISMATCH)); continue; } StreamImage image = new StreamImage((int)requestedWidth, (int)requestedHeight); IndexCompressor compressor = new IndexCompressor(requestedWidth, requestedHeight, 0x01000000); // Initialize image socket.Send(buffer.Reset().Write(REQUEST_IMAGE)); int x = 0; int y = 0; bool ended = false; do { socket.Receive(buffer); int i = 0; while (i < buffer.Length - sizeof(int)) { image.SetPixel(x, y, buffer.GetInt(i)); i += sizeof(int); x++; if (x >= requestedWidth) { x = 0; y++; } } if (buffer.GetUInt(i) == END_OF_IMAGE) { ended = true; } else { image.SetPixel(x, y, buffer.GetInt(i)); x++; if (x >= requestedWidth) { x = 0; y++; } } } while (!ended); OnConnectionAstablished?.Invoke(image.Width, image.Height, image.image, this); socket.Send(buffer.Reset().Write(PAIR_SUCCESSFUL)); IIndexable pixel = new RISPImagePixel(); // Start streaming loop while (true) { try { socket.Receive(buffer); if (buffer.GetULong(0) == TERMINATE_CONNECTION) { break; } int index = 0; RISPImagePixel[] diffrences = new RISPImagePixel[buffer.Length / sizeof(ulong)]; while (index < buffer.Length) { ulong compressedValue = buffer.GetULong(index); compressor.Decompress(compressedValue, ref pixel); RISPImagePixel iPixel = (RISPImagePixel)pixel; System.Console.WriteLine(iPixel.color.ToString("X")); diffrences[index / sizeof(ulong)] = iPixel; image.SetPixel((int)iPixel.x, (int)iPixel.y, new RGB((int)iPixel.color)); index += sizeof(ulong); } // Call stream updates if (diffrences.Length > 0) { OnStreamUpdate?.Invoke(diffrences, this); } } catch (SocketException) { break; } } } } }
/// <summary> /// Writes a Point /// </summary> public static void Write(NetBuffer buffer, Point pt) { buffer.Write(pt.X); buffer.Write(pt.Y); }
public ServerInformation(NetBuffer netBuffer) { ipEndPoint = netBuffer.ReadIPEndPoint(); serverName = ipEndPoint.Address.ToString(); lanServer = true; }
void OnReceivedInternal(MemoryStream ms) { BinaryReader br = new BinaryReader(ms); byte[] message = br.ReadBytes((int)(ms.Length - ms.Position)); br.Close(); ms.Close(); ms.Dispose(); NetBuffer temp = new NetBuffer(message); ushort cmd = temp.ReadShort(); byte[] buf = temp.ReadRemaining(); SocketClientManager.AddEvent(cmd.ToString(), new NetBuffer(buf)); }
public ReceiveEventArgs(NetBuffer rBuf) { this.buf = rBuf; }
/// <summary> /// Read a Point /// </summary> public static Point ReadPoint(NetBuffer buffer) { return new Point(buffer.ReadInt32(), buffer.ReadInt32()); }
public void ClientRead(ServerNetObject type, NetBuffer msg, float sendingTime) { SetState(msg.ReadBoolean(), true); }
void Disconnected(DisconnectType dis, string msg) { Close(); string protocal = dis == DisconnectType.System ? SocketStatusCMD.Exception : SocketStatusCMD.Disconnect; NetBuffer buffer = new NetBuffer(); buffer.WriteString(protocal); SocketClientManager.AddEvent(protocal, buffer); DebugConsole.LogError("Disconnected :>" + msg + " DisconnectType:>" + dis); }
/// <summary> /// Write a Single with half precision (16 bits) /// </summary> public static void WriteHalfPrecision(NetBuffer buffer, float value) { buffer.Write(new HalfSingle(value).PackedValue); }
public static void SendMessageTCP(NetBuffer buffer) { _events.Enqueue(new KeyValuePair<NetActionType, NetBuffer>(NetActionType.Message, buffer)); }
/// <summary> /// Reads a half precision Single written using WriteHalfPrecision(float) /// </summary> public static float ReadHalfPrecisionSingle(NetBuffer buffer) { HalfSingle h = new HalfSingle(); h.PackedValue = buffer.ReadUInt16(); return h.ToSingle(); }
public static void AddEvent(string _event, NetBuffer data) { _respondQueue.Enqueue(new KeyValuePair<string, NetBuffer>(_event, data)); }
public void RespawnPlayer() { if (netClient.Status != NetConnectionStatus.Connected) { return; } playerDead = false; // Respawn a few blocks above a safe position above altitude 0. bool positionFound = false; // Try 20 times; use a potentially invalid position if we fail. for (int i = 0; i < 20; i++) { // Pick a random starting point. Vector3 startPos = new Vector3(randGen.Next(2, 62), 63, randGen.Next(2, 62)); // See if this is a safe place to drop. for (startPos.Y = 63; startPos.Y >= 54; startPos.Y--) { BlockType blockType = blockEngine.BlockAtPoint(startPos); if (blockType == BlockType.Lava) { break; } else if (blockType != BlockType.None) { // We have found a valid place to spawn, so spawn a few above it. playerPosition = startPos + Vector3.UnitY * 5; positionFound = true; break; } } // If we found a position, no need to try anymore! if (positionFound) { break; } } // If we failed to find a spawn point, drop randomly. if (!positionFound) { playerPosition = new Vector3(randGen.Next(2, 62), 66, randGen.Next(2, 62)); } // Drop the player on the middle of the block, not at the corner. playerPosition += new Vector3(0.5f, 0, 0.5f); // Zero out velocity and reset camera and screen effects. playerVelocity = Vector3.Zero; screenEffect = ScreenEffect.None; screenEffectCounter = 0; UpdateCamera(); // Tell the server we have respawned. NetBuffer msgBuffer = netClient.CreateBuffer(); msgBuffer.Write((byte)InfiniminerMessage.PlayerAlive); netClient.SendMessage(msgBuffer, NetChannel.ReliableUnordered); }
public qmsg(NetBuffer buff, NetChannel chan) { Buffer = buff; Channel = chan; }
public static void Write <T>(this NetBuffer buffer, INetworked <T> networkedObject) where T : INetworked <T>, new() => networkedObject.Serialize(buffer);
/// <summary> /// Writes a unit quaternion using the specified number of bits per element /// for a total of 4 x bitsPerElements bits. Suggested value are: /// 8 bits = 4 bytes total, very low precision /// 12 bits = 6 bytes total, low precision /// 16 bits = 8 bytes total, average precision /// 20 bits = 10 bytes total, good precision /// 24 bits = 12 bytes total, full precision /// </summary> public static void WriteRotation(NetBuffer buffer, Quaternion quaternion, int bitsPerElement) { if (quaternion.X > 1.0f) quaternion.X = 1.0f; if (quaternion.Y > 1.0f) quaternion.Y = 1.0f; if (quaternion.Z > 1.0f) quaternion.Z = 1.0f; if (quaternion.W > 1.0f) quaternion.W = 1.0f; if (quaternion.X < -1.0f) quaternion.X = -1.0f; if (quaternion.Y < -1.0f) quaternion.Y = -1.0f; if (quaternion.Z < -1.0f) quaternion.Z = -1.0f; if (quaternion.W < -1.0f) quaternion.W = -1.0f; buffer.WriteSignedSingle(quaternion.X, bitsPerElement); buffer.WriteSignedSingle(quaternion.Y, bitsPerElement); buffer.WriteSignedSingle(quaternion.Z, bitsPerElement); buffer.WriteSignedSingle(quaternion.W, bitsPerElement); }
public override void Send(int clientId, NetBuffer inOutputStream) { NetworkManagerClient.sInstance.GetClient().SendMessage((NetOutgoingMessage)inOutputStream, NetDeliveryMethod.ReliableSequenced); }
/// <summary> /// Writes a bounding sphere /// </summary> public static void Write(NetBuffer buffer, BoundingSphere bounds) { buffer.Write(bounds.Center.X); buffer.Write(bounds.Center.Y); buffer.Write(bounds.Center.Z); buffer.Write(bounds.Radius); }
public static void Write(this NetBuffer msg, Point3D point) { msg.Write(point.X); msg.Write(point.Y); msg.Write(point.Z); }
public void ServerWrite(NetBuffer msg, Client c, object[] extraData = null) { msg.Write(IsOn); }
public void ClientRead(ServerNetObject type, NetBuffer msg, float sendingTime) { IsOn = msg.ReadBoolean(); }
/// <summary> /// Writes a unit vector (ie. a vector of length 1.0, for example a surface normal) /// using specified number of bits /// </summary> public static void WriteUnitVector3(NetBuffer buffer, Vector3 unitVector, int numberOfBits) { float x = unitVector.X; float y = unitVector.Y; float z = unitVector.Z; double invPi = 1.0 / Math.PI; float phi = (float)(Math.Atan2(x, y) * invPi); float theta = (float)(Math.Atan2(z, Math.Sqrt(x * x + y * y)) * (invPi * 2)); int halfBits = numberOfBits / 2; buffer.WriteSignedSingle(phi, halfBits); buffer.WriteSignedSingle(theta, numberOfBits - halfBits); }
public override void Read(NetBuffer msg) { success = msg.ReadBoolean(); }