Skip to content

Commit

Permalink
Remove redundant code, update README's
Browse files Browse the repository at this point in the history
  • Loading branch information
DaXcess committed Aug 26, 2024
1 parent 93bb21d commit 80ff529
Show file tree
Hide file tree
Showing 3 changed files with 42 additions and 48 deletions.
11 changes: 1 addition & 10 deletions Source/Entrypoint.cs
Original file line number Diff line number Diff line change
Expand Up @@ -17,21 +17,12 @@ private static void OnGameEntered()
StartOfRound.Instance.StartCoroutine(Start());
}

// ReSharper disable Unity.PerformanceAnalysis
private static IEnumerator Start()
{
yield return new WaitUntil(() => StartOfRound.Instance.activeCamera != null);

// Setup session manager (required for both VR and NonVR)
new GameObject("LCVR Session Manager").AddComponent<VRSession>();

// Setup Dissonance for VR movement comms
// yield return DNet.Initialize();
}

[HarmonyPatch(typeof(StartOfRound), nameof(StartOfRound.OnDestroy))]
[HarmonyPostfix]
private static void OnGameLeave()
{
// DNet.Shutdown();
}
}
77 changes: 40 additions & 37 deletions Source/Networking/NetworkSystem.cs
Original file line number Diff line number Diff line change
Expand Up @@ -20,21 +20,21 @@ public class NetworkSystem : MonoBehaviour
{
/// Protocol Version, increase this every time a change is made that is not compatible with older versions
private const ushort PROTOCOL_VERSION = 6;

private static NetworkSystem _instance;

public static NetworkSystem Instance => _instance == null
? _instance = new GameObject("VR Network System").AddComponent<NetworkSystem>()
: _instance;

private DissonanceComms dissonance;
private BaseClient<NfgoServer, NfgoClient, NfgoConn> network;

/// <summary>
/// List of active clients in the session
/// </summary>
private readonly Dictionary<ushort, ClientInfo<NfgoConn?>> clients = [];

/// <summary>
/// List of VR players
/// </summary>
Expand All @@ -44,22 +44,22 @@ public class NetworkSystem : MonoBehaviour
/// Player ID lookup table
/// </summary>
private readonly Dictionary<string, ushort> playerIdByName = [];

/// <summary>
/// List of client IDs (from Dissonance Voice) which support DNet
/// List of client IDs (from Dissonance Voice) which support LCVR networking
/// </summary>
private static readonly HashSet<ushort> subscribers = [];

/// <summary>
/// List of active channels we have, which can be used to communicate data over
/// </summary>
private readonly Dictionary<ChannelType, List<Channel>> channels = [];

private ushort? LocalId => network?._serverNegotiator.LocalId;

public bool Initialized { get; private set; }
public VRNetPlayer[] Players => players.Values.ToArray();

private void Awake()
{
StartCoroutine(Initialize());
Expand All @@ -69,7 +69,7 @@ private void OnDestroy()
{
if (!dissonance)
return;

dissonance.OnPlayerJoinedSession -= OnPlayerJoinedSession;
dissonance.OnPlayerLeftSession -= OnPlayerLeftSession;
}
Expand All @@ -78,18 +78,18 @@ private void OnDestroy()
private IEnumerator Initialize()
{
yield return new WaitUntil(() => StartOfRound.Instance != null);

dissonance = FindObjectOfType<DissonanceComms>();
network = FindObjectOfType<NfgoCommsNetwork>().Client;

// Wait until Dissonance Voip has been set up
yield return new WaitUntil(() => LocalId.HasValue);

Logger.LogDebug("Connected to Dissonance Voip");

dissonance.OnPlayerJoinedSession += OnPlayerJoinedSession;
dissonance.OnPlayerLeftSession += OnPlayerLeftSession;

foreach (var player in dissonance.Players)
if (!player.IsLocalPlayer && network._peers.TryGetClientInfoByName(player.Name, out var client))
{
Expand All @@ -116,7 +116,7 @@ private void OnPlayerJoinedSession(VoicePlayerState player)
{
if (!network._peers.TryGetClientInfoByName(player.Name, out var client))
return;

clients.Add(client.PlayerId, client);
playerIdByName.Add(player.Name, client.PlayerId);
}
Expand All @@ -125,7 +125,7 @@ private void OnPlayerLeftSession(VoicePlayerState player)
{
if (!playerIdByName.TryGetValue(player.Name, out var id))
return;

if (players.TryGetValue(id, out var networkPlayer))
Destroy(networkPlayer);

Expand Down Expand Up @@ -157,7 +157,7 @@ internal void SendPacket(MessageType type, byte[] payload, params ClientInfo<Nfg
{
if (LocalId is not { } sender)
return;

network.SendReliableP2P([.. targets], ConstructPacket(type, sender, payload));
}

Expand All @@ -168,32 +168,32 @@ internal void BroadcastPacket(MessageType type, byte[] payload)

var targets = subscribers.Where(key => clients.TryGetValue(key, out _)).Select(value => clients[value])
.ToList();

network.SendReliableP2P(targets, ConstructPacket(type, sender, payload));
}

private static byte[] ConstructPacket(MessageType type, ushort sender, byte[] payload)
{
using var memory = new MemoryStream();
using var writer = new BinaryWriter(memory);

// Magic
writer.Write((ushort)51083);

// Message type
writer.Write((byte)type);

// Sender Id
writer.Write(sender);

// Rest of payload
writer.Write(payload);

return memory.ToArray();
}

#endregion

#region PACKET HANDLING

public void OnPacketReceived(MessageType messageType, ushort sender, BinaryReader reader)
Expand All @@ -203,11 +203,11 @@ public void OnPacketReceived(MessageType messageType, ushort sender, BinaryReade
case MessageType.HandshakeRequest:
HandleHandshakeRequest(sender, reader.ReadUInt16());
break;

case MessageType.HandshakeResponse:
StartCoroutine(HandleHandshakeResponse(sender, reader.ReadBoolean()));
break;

case MessageType.Channel:
HandleChannelMessage(sender, reader);
break;
Expand All @@ -230,44 +230,47 @@ private void HandleHandshakeRequest(ushort sender, ushort protocol)
Logger.LogError($"Cannot send handshake response to {sender}: Client info is missing!");
return;
}

Logger.LogDebug($"Received handshake request from {sender}");

SendPacket(MessageType.HandshakeResponse, [VRSession.InVR ? (byte)1 : (byte)0], target);
}

// ReSharper disable Unity.PerformanceAnalysis
private IEnumerator HandleHandshakeResponse(ushort sender, bool inVR)
{
Logger.LogDebug($"Received handshake response from {sender}");

subscribers.Add(sender);

if (!inVR)
yield break;

// Wait until client is a part of the peers list
yield return new WaitUntilTimeout(10, () => network._peers.TryGetClientInfoById(sender, out _));

if (!network._peers.TryGetClientInfoById(sender, out var client))
{
Logger.LogError($"Failed to resolve client for Player Id {sender} after 10s. No VR movements will be synchronized.");
Logger.LogError(
$"Failed to resolve client for Player Id {sender} after 10s. No VR movements will be synchronized.");

yield break;
}

var player = dissonance.FindPlayer(client.PlayerName);
if (player == null)
{
Logger.LogError($"Failed to resolve client for Player {client.PlayerName}. No VR movements will be synchronized.");
Logger.LogError(
$"Failed to resolve client for Player {client.PlayerName}. No VR movements will be synchronized.");
yield break;
}

yield return new WaitUntil(() => player.Tracker != null);

// Ignore players that have already been registered
if (players.ContainsKey(sender))
yield break;

var playerObject = ((NfgoPlayer)player.Tracker!).gameObject;
var playerController = playerObject.GetComponent<PlayerControllerB>();
var networkPlayer = playerObject.AddComponent<VRNetPlayer>();
Expand All @@ -279,7 +282,7 @@ private IEnumerator HandleHandshakeResponse(ushort sender, bool inVR)

Logger.LogError(
"VR player already exists? Destroying VR player script! Player will look like a vanilla player.");

Destroy(networkPlayer);
OnPlayerLeftSession(player);
}
Expand All @@ -301,9 +304,9 @@ private void HandleChannelMessage(ushort sender, BinaryReader reader)
else
channelList.Do(channel => channel.ReceivedPacket(sender, reader.Clone()));
}

#endregion

#region CHANNELS

public Channel CreateChannel(ChannelType type, ulong? instanceId = null)
Expand All @@ -323,7 +326,7 @@ internal void CloseChannel(Channel channel)

channelList.Remove(channel);
}

#endregion

public enum MessageType : byte
Expand Down
2 changes: 1 addition & 1 deletion Source/Networking/Serialization.cs
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@
namespace LCVR.Networking;

/// <summary>
/// A special serializer that can be used within DNet.
/// A special serializer that can be used within the networking system.
///
/// This serializer allows easy serialization from structs and classes to bytes and vice-versa.
/// It supports most basic primitive types (numbers, bools, strings), Vector3's, Quaternions, and any other class
Expand Down

0 comments on commit 80ff529

Please sign in to comment.