Skip to content

Commit

Permalink
Update UI, fix standalone server saves
Browse files Browse the repository at this point in the history
  • Loading branch information
Extremelyd1 committed May 10, 2024
1 parent 545af94 commit f20b2d2
Show file tree
Hide file tree
Showing 12 changed files with 592 additions and 331 deletions.
90 changes: 32 additions & 58 deletions HKMP/Game/Client/ClientManager.cs
Original file line number Diff line number Diff line change
Expand Up @@ -242,35 +242,23 @@ ModSettings modSettings
packetManager.RegisterClientPacketHandler<ChatMessage>(ClientPacketId.ChatMessage, OnChatMessage);

// Register handlers for events from UI
uiManager.ConnectInterface.ConnectButtonPressed += (address, port, username, autoConnect) => {
uiManager.RequestClientConnectEvent += (address, port, username, autoConnect) => {
_autoConnect = autoConnect;
Connect(address, port, username);
};
uiManager.ConnectInterface.DisconnectButtonPressed += Disconnect;
uiManager.SettingsInterface.OnTeamRadioButtonChange += InternalChangeTeam;
uiManager.SettingsInterface.OnSkinIdChange += InternalChangeSkin;
uiManager.RequestClientDisconnectEvent += Disconnect;

// uiManager.SettingsInterface.OnTeamRadioButtonChange += InternalChangeTeam;
// uiManager.SettingsInterface.OnSkinIdChange += InternalChangeSkin;

UiManager.InternalChatBox.ChatInputEvent += OnChatInput;

netClient.ConnectEvent += _ => uiManager.OnSuccessfulConnect();
netClient.ConnectFailedEvent += OnConnectFailed;

// Register the Hero Controller Start, which is when the local player spawns
On.HeroController.Start += (orig, self) => {
// Execute the original method
orig(self);
// If we are connect to a server, add a username to the player object
if (netClient.IsConnected) {
_playerManager.AddNameToPlayer(
HeroController.instance.gameObject,
_username,
_playerManager.LocalPlayerTeam
);
}
};

// Register handlers for scene change and player update
// Register handlers for various things
UnityEngine.SceneManagement.SceneManager.activeSceneChanged += OnSceneChange;
On.HeroController.Start += OnHeroControllerStart;
On.HeroController.Update += OnPlayerUpdate;

// Register client connect and timeout handler
Expand Down Expand Up @@ -480,39 +468,22 @@ private void OnClientConnect(LoginResponse loginResponse) {
// First relay the addon order from the login response to the addon manager
_addonManager.UpdateNetworkedAddonOrder(loginResponse.AddonOrder);

// We should only be able to connect during a gameplay scene,
// which is when the player is spawned already, so we can add the username
_playerManager.AddNameToPlayer(HeroController.instance.gameObject, _username,
_playerManager.LocalPlayerTeam);

Logger.Info("Client is connected, sending Hello packet");
_netClient.UpdateManager.SetHelloServerData(_username);
}

/// <summary>
/// Callback method for when the HeroController is started so we can add the username to the player object.
/// </summary>
private void OnHeroControllerStart(On.HeroController.orig_Start orig, HeroController self) {
orig(self);

// If we are in a non-gameplay scene, we transmit that we are not active yet
var currentSceneName = SceneUtil.GetCurrentSceneName();
if (SceneUtil.IsNonGameplayScene(currentSceneName)) {
Logger.Error(
$"Client connected during a non-gameplay scene named {currentSceneName}, this should never happen!");
return;
if (_netClient.IsConnected) {
_playerManager.AddNameToPlayer(
HeroController.instance.gameObject,
_username,
_playerManager.LocalPlayerTeam
);
}

var transform = HeroController.instance.transform;
var position = transform.position;

Logger.Info("Sending Hello packet");

_netClient.UpdateManager.SetHelloServerData(
_username,
SceneUtil.GetCurrentSceneName(),
new Vector2(position.x, position.y),
transform.localScale.x > 0,
(ushort) AnimationManager.GetCurrentAnimationClip()
);

// Since we are probably in the pause menu when we connect, set the timescale so the game
// is running while paused
PauseManager.SetTimeScale(1.0f);

UiManager.InternalChatBox.AddMessage("You are connected to the server");
}

/// <summary>
Expand All @@ -525,6 +496,7 @@ private void OnHelloClient(HelloClient helloClient) {
// If this was not an auto-connect, we set save data. Otherwise, we know we already have the save data.
if (!_autoConnect) {
_saveManager.SetSaveWithData(helloClient.CurrentSave);
_uiManager.EnterGameFromMultiplayerMenu();
}

// Fill the player data dictionary with the info from the packet
Expand Down Expand Up @@ -553,6 +525,8 @@ private void OnDisconnect(ServerClientDisconnect disconnect) {
} else if (disconnect.Reason == DisconnectReason.Shutdown) {
UiManager.InternalChatBox.AddMessage("You are disconnected from the server (server is shutting down)");
}

_uiManager.ReturnToMainMenuFromGame();

// Disconnect without sending the server that we disconnect, because the server knows that already
InternalDisconnect();
Expand Down Expand Up @@ -917,7 +891,7 @@ private void OnServerSettingsUpdated(ServerSettingsUpdate update) {
_playerManager.ResetAllTeams();
}

_uiManager.OnTeamSettingChange();
// _uiManager.OnTeamSettingChange();
}

// If the allow skins setting changed and it is no longer allowed, we reset all existing skins
Expand Down Expand Up @@ -952,12 +926,10 @@ private void OnSceneChange(Scene oldScene, Scene newScene) {
// Reset the status of whether we determined the scene host or not
_sceneHostDetermined = false;

// Ignore scene changes from and to non-gameplay scenes
if (SceneUtil.IsNonGameplayScene(oldScene.name)) {
return;
// If the old scene is a gameplay scene, we need to notify the server that we left
if (!SceneUtil.IsNonGameplayScene(oldScene.name)) {
_netClient.UpdateManager.SetLeftScene();
}

_netClient.UpdateManager.SetLeftScene();
}

/// <summary>
Expand Down Expand Up @@ -991,7 +963,6 @@ private void OnPlayerUpdate(On.HeroController.orig_Update orig, HeroController s
if (_sceneChanged) {
_sceneChanged = false;


// Set some default values for the packet variables in case we don't have a HeroController instance
// This might happen when we are in a non-gameplay scene without the knight
var position = Vector2.Zero;
Expand Down Expand Up @@ -1049,7 +1020,10 @@ private void OnTimeout() {
return;
}

Logger.Info("Connection to server timed out, disconnecting");
Logger.Info("Connection to server timed out, moving to main menu");

_uiManager.ReturnToMainMenuFromGame();

UiManager.InternalChatBox.AddMessage("You are disconnected from the server (server timed out)");

Disconnect();
Expand Down
25 changes: 25 additions & 0 deletions HKMP/Game/Client/Save/SaveDataMapping.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
using System.Linq;
using Hkmp.Collection;
using Hkmp.Logging;
using Hkmp.Util;
using Newtonsoft.Json;

namespace Hkmp.Game.Client.Save;
Expand All @@ -10,6 +11,30 @@ namespace Hkmp.Game.Client.Save;
/// Serializable data class that stores mappings for what scene data should be synchronised and their indices used for networking.
/// </summary>
internal class SaveDataMapping {
/// <summary>
/// The file path of the embedded resource file for save data.
/// </summary>
private const string SaveDataFilePath = "Hkmp.Resource.save-data.json";

/// <summary>
/// The static instance of the mapping.
/// </summary>
[JsonIgnore]
private static SaveDataMapping _instance;

/// <inheritdoc cref="_instance"/>
[JsonIgnore]
public static SaveDataMapping Instance {
get {
if (_instance == null) {
_instance = FileUtil.LoadObjectFromEmbeddedJson<SaveDataMapping>(SaveDataFilePath);
_instance.Initialize();
}

return _instance;
}
}

/// <summary>
/// Dictionary mapping player data values to booleans indicating whether they should be synchronised.
/// </summary>
Expand Down
17 changes: 2 additions & 15 deletions HKMP/Game/Client/Save/SaveManager.cs
Original file line number Diff line number Diff line change
Expand Up @@ -21,20 +21,15 @@ namespace Hkmp.Game.Client.Save;
/// Class that manages save data synchronisation.
/// </summary>
internal class SaveManager {
/// <summary>
/// The file path of the embedded resource file for save data.
/// </summary>
private const string SaveDataFilePath = "Hkmp.Resource.save-data.json";

/// <summary>
/// The index of the save data entry for the warp.
/// </summary>
private const ushort SaveWarpIndex = ushort.MaxValue;

/// <summary>
/// The save data instances that contains mappings for what to sync and their indices.
/// The save data instance that contains mappings for what to sync and their indices.
/// </summary>
private static readonly SaveDataMapping SaveDataMapping;
private static SaveDataMapping SaveDataMapping => SaveDataMapping.Instance;

/// <summary>
/// The net client instance to send save updates.
Expand Down Expand Up @@ -82,14 +77,6 @@ public SaveManager(NetClient netClient, PacketManager packetManager, EntityManag
_bsCompHashes = new Dictionary<string, BossStatue.Completion>();
}

/// <summary>
/// Static constructor to load and initialize the save data mapping.
/// </summary>
static SaveManager() {
SaveDataMapping = FileUtil.LoadObjectFromEmbeddedJson<SaveDataMapping>(SaveDataFilePath);
SaveDataMapping.Initialize();
}

/// <summary>
/// Initializes the save manager by loading the save data json.
/// </summary>
Expand Down
1 change: 0 additions & 1 deletion HKMP/Game/GameManager.cs
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,6 @@ public GameManager(ModSettings modSettings) {
var serverServerSettings = modSettings.ServerSettings;

var uiManager = new UiManager(
clientServerSettings,
modSettings,
netClient
);
Expand Down
4 changes: 2 additions & 2 deletions HKMP/Game/Server/ModServerManager.cs
Original file line number Diff line number Diff line change
Expand Up @@ -22,11 +22,11 @@ UiManager uiManager
ModHooks.FinishedLoadingModsHook += AddonManager.LoadAddons;

// Register handlers for UI events
uiManager.ConnectInterface.StartHostButtonPressed += port => {
uiManager.RequestServerStartHostEvent += port => {
CurrentSaveData = SaveManager.GetCurrentSaveData();
Start(port);
};
uiManager.ConnectInterface.StopHostButtonPressed += Stop;
uiManager.RequestServerStopHostEvent += Stop;

// Register application quit handler
ModHooks.ApplicationQuitHook += Stop;
Expand Down
10 changes: 4 additions & 6 deletions HKMP/Game/Server/ServerManager.cs
Original file line number Diff line number Diff line change
Expand Up @@ -253,11 +253,6 @@ private void OnHelloServer(ushort id, HelloServer helloServer) {
return;
}

playerData.CurrentScene = helloServer.SceneName;
playerData.Position = helloServer.Position;
playerData.Scale = helloServer.Scale;
playerData.AnimationId = helloServer.AnimationClipId;

var clientInfo = new List<(ushort, string)>();

foreach (var idPlayerDataPair in _playerData) {
Expand Down Expand Up @@ -1288,7 +1283,7 @@ private void OnChatMessage(ushort id, ChatMessage chatMessage) {
/// </summary>
/// <param name="id">The ID of the player.</param>
/// <param name="packet">The SaveUpdate packet data.</param>
private void OnSaveUpdate(ushort id, SaveUpdate packet) {
protected virtual void OnSaveUpdate(ushort id, SaveUpdate packet) {
if (!_playerData.TryGetValue(id, out var playerData)) {
Logger.Debug($"Could not process save update from unknown player ID: {id}");
return;
Expand All @@ -1300,6 +1295,9 @@ private void OnSaveUpdate(ushort id, SaveUpdate packet) {
Logger.Info(" Player is not scene host, not broadcasting update");
return;
}

// The save update is valid so we store it in our current save
CurrentSaveData[packet.SaveDataIndex] = packet.Value;

foreach (var idPlayerDataPair in _playerData) {
var otherId = idPlayerDataPair.Key;
Expand Down
6 changes: 0 additions & 6 deletions HKMP/Game/Settings/ModSettings.cs
Original file line number Diff line number Diff line change
Expand Up @@ -14,12 +14,6 @@ internal class ModSettings {
/// </summary>
public string AuthKey { get; set; } = null;

/// <summary>
/// The key to hide the HKMP UI.
/// </summary>
[JsonConverter(typeof(StringEnumConverter))]
public KeyCode HideUiKey { get; set; } = KeyCode.RightAlt;

/// <summary>
/// The key to open the chat.
/// </summary>
Expand Down
18 changes: 2 additions & 16 deletions HKMP/Networking/Client/ClientUpdateManager.cs
Original file line number Diff line number Diff line change
Expand Up @@ -358,26 +358,12 @@ public void SetSkinUpdate(byte skinId) {
/// Set hello server data in the current packet.
/// </summary>
/// <param name="username">The username of the player.</param>
/// <param name="sceneName">The name of the current scene of the player.</param>
/// <param name="position">The position of the player.</param>
/// <param name="scale">The scale of the player.</param>
/// <param name="animationClipId">The animation clip ID of the player.</param>
public void SetHelloServerData(
string username,
string sceneName,
Vector2 position,
bool scale,
ushort animationClipId
) {
public void SetHelloServerData(string username) {
lock (Lock) {
CurrentUpdatePacket.SetSendingPacketData(
ServerPacketId.HelloServer,
new HelloServer {
Username = username,
SceneName = sceneName,
Position = position,
Scale = scale,
AnimationClipId = animationClipId
Username = username
}
);
}
Expand Down
36 changes: 1 addition & 35 deletions HKMP/Networking/Packet/Data/HelloServer.cs
Original file line number Diff line number Diff line change
@@ -1,6 +1,4 @@
using Hkmp.Math;

namespace Hkmp.Networking.Packet.Data;
namespace Hkmp.Networking.Packet.Data;

/// <summary>
/// Packet data for the hello server data.
Expand All @@ -17,45 +15,13 @@ internal class HelloServer : IPacketData {
/// </summary>
public string Username { get; set; }

/// <summary>
/// The name of the current scene of the player.
/// </summary>
public string SceneName { get; set; }

/// <summary>
/// The position of the player.
/// </summary>
public Vector2 Position { get; set; }

/// <summary>
/// The scale of the player.
/// </summary>
public bool Scale { get; set; }

/// <summary>
/// The animation clip ID of the player.
/// </summary>
public ushort AnimationClipId { get; set; }

/// <inheritdoc />
public void WriteData(IPacket packet) {
packet.Write(Username);
packet.Write(SceneName);

packet.Write(Position);
packet.Write(Scale);

packet.Write(AnimationClipId);
}

/// <inheritdoc />
public void ReadData(IPacket packet) {
Username = packet.ReadString();
SceneName = packet.ReadString();

Position = packet.ReadVector2();
Scale = packet.ReadBool();

AnimationClipId = packet.ReadUShort();
}
}
Loading

0 comments on commit f20b2d2

Please sign in to comment.