fixes for mouse dragger, visualization for audio range, added some more callbacks to velnetmanager, added color syncing extension, take ownership of synced textbox, fix for deleting all scene objects

upm
Anton Franzluebbers 2022-01-24 21:12:13 -05:00
parent dc61c63563
commit 682c470d46
3 changed files with 324 additions and 263 deletions

View File

@ -8,6 +8,8 @@ namespace VelNet
{
public static class BinaryWriterExtensions
{
#region Writers
public static void Write(this BinaryWriter writer, Vector3 v)
{
writer.Write(v.x);
@ -23,6 +25,18 @@ namespace VelNet
writer.Write(q.w);
}
public static void Write(this BinaryWriter writer, Color c)
{
writer.Write(c.r);
writer.Write(c.g);
writer.Write(c.b);
writer.Write(c.a);
}
#endregion
#region Readers
public static Vector3 ReadVector3(this BinaryReader reader)
{
return new Vector3(reader.ReadSingle(), reader.ReadSingle(), reader.ReadSingle());
@ -38,6 +52,19 @@ namespace VelNet
);
}
public static Color ReadColor(this BinaryReader reader)
{
return new Color(
reader.ReadSingle(),
reader.ReadSingle(),
reader.ReadSingle(),
reader.ReadSingle()
);
}
#endregion
/// <summary>
/// Compresses the list of bools into bytes using a bitmask
/// </summary>
@ -88,6 +115,5 @@ namespace VelNet
{
return (b & (1 << index)) != 0;
}
}
}

View File

@ -1,5 +1,4 @@
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Net.Sockets;
@ -8,8 +7,6 @@ using System.Threading;
using UnityEngine;
using System.Net;
using UnityEngine.SceneManagement;
using System.Runtime.Serialization.Formatters.Binary;
using System.Runtime.Serialization;
using System.IO;
namespace VelNet
@ -42,10 +39,11 @@ namespace VelNet
private Thread clientReceiveThread;
private Thread clientReceiveThreadUDP;
public int userid = -1;
private int messagesReceived = 0;
public readonly Dictionary<int, VelNetPlayer> players = new Dictionary<int, VelNetPlayer>();
#region Callbacks
/// <summary>
/// We just joined a room
/// string - the room name
@ -69,8 +67,12 @@ namespace VelNet
public static Action<VelNetPlayer> OnPlayerLeft;
public static Action OnConnectedToServer;
public static Action LoggedIn;
public static Action<string[], int> RoomsReceived;
public static Action OnLoggedIn;
public static Action<RoomsMessage> RoomsReceived;
public static Action<Message> MessageReceived;
#endregion
public bool connected;
@ -107,46 +109,59 @@ namespace VelNet
public static bool IsConnected => instance != null && instance.connected && instance.udpConnected;
//this is for sending udp packets
static byte[] toSend = new byte[1024];
private static readonly byte[] toSend = new byte[1024];
// Use this for initialization
public abstract class Message
{
}
public class ListedRoom
{
public string name;
public int numUsers;
public override string ToString()
{
return "Room Name: " + name + "\tUsers: " + numUsers;
}
public class LoginMessage: Message
}
public class LoginMessage : Message
{
public int userId;
}
public class RoomsMessage: Message
public class RoomsMessage : Message
{
public List<ListedRoom> rooms;
public override string ToString()
{
return string.Join("\n", rooms);
}
public class JoinMessage: Message
}
public class JoinMessage : Message
{
public int userId;
public string room;
}
public class DataMessage: Message
public class DataMessage : Message
{
public int senderId;
public byte[] data;
}
public class ChangeMasterMessage: Message
public class ChangeMasterMessage : Message
{
public int masterId;
}
public class ConnectedMessage: Message
public class ConnectedMessage : Message
{
}
public readonly List<Message> receivedMessages = new List<Message>();
@ -180,6 +195,15 @@ namespace VelNet
//Debug.Log(messagesReceived++);
receivedMessages.Add(m);
}
try
{
MessageReceived?.Invoke(m);
}
catch (Exception e)
{
Debug.LogError(e);
}
}
private void Update()
@ -191,7 +215,7 @@ namespace VelNet
{
switch (m)
{
case ConnectedMessage connected:
case ConnectedMessage msg:
{
try
{
@ -202,16 +226,17 @@ namespace VelNet
{
Debug.LogError(e);
}
break;
}
case LoginMessage lm:
{
userid = lm.userId;
Debug.Log("joined server " + userid);
Debug.Log("Joined server " + userid);
try
{
LoggedIn?.Invoke();
OnLoggedIn?.Invoke();
}
// prevent errors in subscribers from breaking our code
catch (Exception e)
@ -221,18 +246,29 @@ namespace VelNet
//start the udp thread
clientReceiveThreadUDP = new Thread(ListenForDataUDP);
clientReceiveThreadUDP.IsBackground = true;
clientReceiveThreadUDP.Start();
break;
}
case RoomsMessage rm: {
Debug.Log("Got Rooms Message");
case RoomsMessage rm:
{
Debug.Log("Got Rooms Message:\n" + rm);
try
{
RoomsReceived?.Invoke(rm);
}
// prevent errors in subscribers from breaking our code
catch (Exception e)
{
Debug.LogError(e);
}
break;
}
case JoinMessage jm: {
if(userid == jm.userId) //this is us
case JoinMessage jm:
{
if (userid == jm.userId) //this is us
{
string oldRoom = LocalPlayer?.room;
@ -260,7 +296,6 @@ namespace VelNet
{
Debug.LogError(e);
}
}
// we just left a room
else
@ -327,7 +362,18 @@ namespace VelNet
// TODO this may check for ownership in the future. We don't need ownership here
deleteObjects.ForEach(NetworkDestroy);
VelNetPlayer leftPlayer = players[jm.userId];
players.Remove(jm.userId);
try
{
OnPlayerLeft?.Invoke(leftPlayer);
}
// prevent errors in subscribers from breaking our code
catch (Exception e)
{
Debug.LogError(e);
}
}
else
{
@ -350,10 +396,11 @@ namespace VelNet
}
}
}
break;
break;
}
case DataMessage dm: {
case DataMessage dm:
{
if (players.ContainsKey(dm.senderId))
{
players[dm.senderId]?.HandleMessage(dm); //todo
@ -364,11 +411,9 @@ namespace VelNet
}
break;
}
case ChangeMasterMessage cm: {
case ChangeMasterMessage cm:
{
if (masterPlayer == null)
{
masterPlayer = players[cm.masterId];
@ -397,7 +442,6 @@ namespace VelNet
}
break;
}
}
@ -421,7 +465,6 @@ namespace VelNet
try
{
clientReceiveThread = new Thread(ListenForData);
clientReceiveThread.IsBackground = true;
clientReceiveThread.Start();
}
catch (Exception e)
@ -432,10 +475,9 @@ namespace VelNet
/// <summary>
/// Runs in background clientReceiveThread; Listens for incomming data.
/// Runs in background clientReceiveThread; Listens for incoming data.
/// </summary>
///
private byte[] ReadExact(NetworkStream stream, int N)
private static byte[] ReadExact(Stream stream, int N)
{
byte[] toReturn = new byte[N];
@ -446,20 +488,15 @@ namespace VelNet
numRead += stream.Read(toReturn, numRead, numLeft);
numLeft = N - numRead;
}
return toReturn;
}
private int GetIntFromBytes(byte[] bytes)
private static int GetIntFromBytes(byte[] bytes)
{
if (BitConverter.IsLittleEndian)
{
return BitConverter.ToInt32(bytes.Reverse().ToArray(),0);
}
else
{
return BitConverter.ToInt32(bytes, 0);
}
return BitConverter.ToInt32(BitConverter.IsLittleEndian ? bytes.Reverse().ToArray() : bytes, 0);
}
private void ListenForData()
{
connected = true;
@ -476,7 +513,6 @@ namespace VelNet
//SendToGroup("close", Encoding.UTF8.GetBytes("HelloGroup"));
while (true)
{
// Get a stream object for reading
@ -489,9 +525,8 @@ namespace VelNet
m.userId = GetIntFromBytes(ReadExact(stream, 4)); //not really the sender...
AddMessage(m);
}
else if(type == 1) //rooms
else if (type == 1) //rooms
{
RoomsMessage m = new RoomsMessage();
m.rooms = new List<ListedRoom>();
int N = GetIntFromBytes(ReadExact(stream, 4)); //the size of the payload
@ -499,21 +534,22 @@ namespace VelNet
string roomMessage = Encoding.UTF8.GetString(utf8data);
string[] sections = roomMessage.Split(',');
foreach (string s in sections)
{
string[] pieces = s.Split(':');
if (pieces.Length == 2) {
if (pieces.Length == 2)
{
ListedRoom lr = new ListedRoom();
lr.name = pieces[0];
lr.numUsers = int.Parse(pieces[1]);
m.rooms.Add(lr);
}
}
AddMessage(m);
}
else if(type == 2) //joined
else if (type == 2) //joined
{
JoinMessage m = new JoinMessage();
m.userId = GetIntFromBytes(ReadExact(stream, 4));
@ -521,7 +557,8 @@ namespace VelNet
byte[] utf8data = ReadExact(stream, N); //the room name, encoded as utf-8
m.room = Encoding.UTF8.GetString(utf8data);
AddMessage(m);
}else if(type == 3) //data
}
else if (type == 3) //data
{
DataMessage m = new DataMessage();
m.senderId = GetIntFromBytes(ReadExact(stream, 4));
@ -529,10 +566,10 @@ namespace VelNet
m.data = ReadExact(stream, N); //the message
AddMessage(m);
}
else if(type == 4) //new master
else if (type == 4) //new master
{
ChangeMasterMessage m = new ChangeMasterMessage();
m.masterId = (int)GetIntFromBytes(ReadExact(stream, 4)); //sender is the new master
m.masterId = GetIntFromBytes(ReadExact(stream, 4)); //sender is the new master
AddMessage(m);
}
}
@ -584,10 +621,12 @@ namespace VelNet
while (true)
{
int numReceived = udpSocket.Receive(buffer);
if (buffer[0] == 0)
switch (buffer[0])
{
case 0:
Debug.Log("UDP connected");
}else if (buffer[0] == 3)
break;
case 3:
{
DataMessage m = new DataMessage();
//we should get the sender address
@ -598,6 +637,8 @@ namespace VelNet
Array.Copy(buffer, 5, messageBytes, 0, messageBytes.Length);
m.data = messageBytes;
AddMessage(m);
break;
}
}
}
}
@ -634,8 +675,7 @@ namespace VelNet
NetworkStream stream = instance.socketConnection.GetStream();
if (stream.CanWrite)
{
stream.Write(message,0,message.Length);
stream.Write(message, 0, message.Length);
}
}
catch (SocketException socketException)
@ -652,9 +692,9 @@ namespace VelNet
{
return BitConverter.GetBytes(n).Reverse().ToArray();
}
public static void Login(string username, string password)
{
MemoryStream stream = new MemoryStream();
BinaryWriter writer = new BinaryWriter(stream);
@ -667,14 +707,11 @@ namespace VelNet
writer.Write(pB);
SendTcpMessage(stream.ToArray());
}
public static void GetRooms()
{
SendTcpMessage(new byte[1] { 1 }); //very simple message
SendTcpMessage(new byte[] { 1 }); //very simple message
}
/// <summary>
@ -691,14 +728,9 @@ namespace VelNet
writer.Write((byte)R.Length);
writer.Write(R);
SendTcpMessage(stream.ToArray());
}
/// <summary>
/// Leaves a room if we're in one
/// </summary>
@ -712,7 +744,7 @@ namespace VelNet
public static void SendToRoom(byte[] message, bool include_self = false, bool reliable = true, bool ordered = false)
{
byte sendType = (byte) MessageSendType.MESSAGE_OTHERS;
byte sendType = (byte)MessageSendType.MESSAGE_OTHERS;
if (include_self && ordered) sendType = (byte)MessageSendType.MESSAGE_ALL_ORDERED;
if (include_self && !ordered) sendType = (byte)MessageSendType.MESSAGE_ALL;
if (!include_self && ordered) sendType = (byte)MessageSendType.MESSAGE_OTHERS_ORDERED;
@ -733,7 +765,7 @@ namespace VelNet
toSend[0] = sendType; //we don't
Array.Copy(get_be_bytes(instance.userid), 0, toSend, 1, 4);
Array.Copy(message, 0, toSend, 5, message.Length);
SendUdpMessage(toSend,message.Length+5); //shouldn't be over 1024...
SendUdpMessage(toSend, message.Length + 5); //shouldn't be over 1024...
}
}
@ -759,7 +791,7 @@ namespace VelNet
//also need to send the group
toSend[5] = (byte)utf8bytes.Length;
Array.Copy(utf8bytes, 0, toSend, 6, utf8bytes.Length);
Array.Copy(message, 0, toSend, 6+utf8bytes.Length, message.Length);
Array.Copy(message, 0, toSend, 6 + utf8bytes.Length, message.Length);
SendUdpMessage(toSend, 6 + utf8bytes.Length + message.Length);
}
}
@ -785,6 +817,7 @@ namespace VelNet
{
writer.Write(get_be_bytes(client_ids[i]));
}
SendTcpMessage(stream.ToArray());
}
@ -805,6 +838,7 @@ namespace VelNet
Debug.LogError("Can't instantiate object. Obj with that network ID was already instantiated.", instance.objects[networkId]);
return null;
}
NetworkObject newObject = Instantiate(prefab);
newObject.networkId = networkId;
newObject.prefabName = prefabName;
@ -812,7 +846,7 @@ namespace VelNet
instance.objects.Add(newObject.networkId, newObject);
// only sent to others, as I already instantiated this. Nice that it happens immediately.
SendToRoom(Encoding.UTF8.GetBytes("7," + newObject.networkId + "," + prefabName),false,true);
SendToRoom(Encoding.UTF8.GetBytes("7," + newObject.networkId + "," + prefabName), false, true);
return newObject;
}
@ -842,6 +876,7 @@ namespace VelNet
instance.objects.Remove(networkId);
return;
}
if (obj.isSceneObject)
{
instance.deletedSceneObjects.Add(networkId);

View File

@ -1,7 +1,7 @@
{
"name": "edu.uga.engr.vel.velnet",
"displayName": "VelNet",
"version": "1.0.7",
"version": "1.0.8",
"unity": "2019.1",
"description": "A custom networking library for Unity.",
"keywords": [