Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 6 additions & 2 deletions Source/Client/AsyncTime/SetMapTime.cs
Original file line number Diff line number Diff line change
Expand Up @@ -205,11 +205,15 @@ public static TimeSnapshot Current()
{
if (map == null) return null;

TimeSnapshot prev = Current();

var tickManager = Find.TickManager;
if (tickManager == null) return null;

TimeSnapshot prev = Current();
var mapComp = map.AsyncTime();

if (mapComp == null)
return prev;

tickManager.ticksGameInt = mapComp.mapTicks;
tickManager.slower = mapComp.slower;
tickManager.CurTimeSpeed = mapComp.DesiredTimeSpeed;
Expand Down
42 changes: 42 additions & 0 deletions Source/Client/Comp/BootstrapCoordinator.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
using Verse;

namespace Multiplayer.Client.Comp
{
/// <summary>
/// Runs during bootstrap to detect when the new game has fully entered Playing and a map exists.
/// Keeps the save trigger logic reliable even when the bootstrap window may not receive regular updates.
/// </summary>
public class BootstrapCoordinator : GameComponent
{
private int nextCheckTick;
private const int CheckIntervalTicks = 60; // ~1s

public BootstrapCoordinator(Game game)
{
}

public override void GameComponentTick()
{
base.GameComponentTick();

var win = BootstrapConfiguratorWindow.Instance;
if (win == null)
return;

// Throttle checks
if (Find.TickManager != null && Find.TickManager.TicksGame < nextCheckTick)
return;

if (Find.TickManager != null)
nextCheckTick = Find.TickManager.TicksGame + CheckIntervalTicks;

win.BootstrapCoordinatorTick();
}

public override void ExposeData()
{
base.ExposeData();
Scribe_Values.Look(ref nextCheckTick, "mp_bootstrap_nextCheckTick", 0);
}
}
}
1 change: 1 addition & 0 deletions Source/Client/MultiplayerStatic.cs
Original file line number Diff line number Diff line change
Expand Up @@ -78,6 +78,7 @@ static MultiplayerStatic()
MpConnectionState.SetImplementation(ConnectionStateEnum.ClientJoining, typeof(ClientJoiningState));
MpConnectionState.SetImplementation(ConnectionStateEnum.ClientLoading, typeof(ClientLoadingState));
MpConnectionState.SetImplementation(ConnectionStateEnum.ClientPlaying, typeof(ClientPlayingState));
MpConnectionState.SetImplementation(ConnectionStateEnum.ClientBootstrap, typeof(ClientBootstrapState));

MultiplayerData.CollectCursorIcons();

Expand Down
3 changes: 2 additions & 1 deletion Source/Client/Networking/State/ClientBaseState.cs
Original file line number Diff line number Diff line change
Expand Up @@ -4,12 +4,13 @@

namespace Multiplayer.Client;

[PacketHandlerClass]
public abstract class ClientBaseState(ConnectionBase connection) : MpConnectionState(connection)
{
protected MultiplayerSession Session => Multiplayer.session;

[TypedPacketHandler]
public void HandleDisconnected(ServerDisconnectPacket packet)
public virtual void HandleDisconnected(ServerDisconnectPacket packet)
{
ConnectionStatusListeners.TryNotifyAll_Disconnected(SessionDisconnectInfo.From(packet.reason, new ByteReader(packet.data)));
Multiplayer.StopMultiplayer();
Expand Down
45 changes: 45 additions & 0 deletions Source/Client/Networking/State/ClientBootstrapState.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
using Multiplayer.Common;
using Multiplayer.Common.Networking.Packet;
using RimWorld;
using Verse;

namespace Multiplayer.Client;

/// <summary>
/// Client connection state used while configuring a bootstrap server.
/// The server is in ServerBootstrap and expects upload packets; the client must keep the connection alive
/// and handle bootstrap completion / disconnect packets.
/// </summary>
[PacketHandlerClass]
public class ClientBootstrapState(ConnectionBase connection) : ClientBaseState(connection)
{
[TypedPacketHandler]
public void HandleBootstrap(ServerBootstrapPacket packet)
{
// The server sends this again when entering ServerBootstrapState.StartState().
// We already have the bootstrap info from ClientJoiningState; just ignore it.
}

[TypedPacketHandler]
public override void HandleDisconnected(ServerDisconnectPacket packet)
{
// If bootstrap completed successfully, show success message before closing the window
if (packet.reason == MpDisconnectReason.BootstrapCompleted)
{
OnMainThread.Enqueue(() => Messages.Message(
"Bootstrap configuration completed. The server will now shut down; please restart it manually to start normally.",
MessageTypeDefOf.PositiveEvent, false));
}

// Close the bootstrap configurator window now that the process is complete
OnMainThread.Enqueue(() =>
{
var window = Find.WindowStack.WindowOfType<BootstrapConfiguratorWindow>();
if (window != null)
Find.WindowStack.TryRemove(window);
});

// Let the base class handle the disconnect
base.HandleDisconnected(packet);
}
}
16 changes: 16 additions & 0 deletions Source/Client/Networking/State/ClientJoiningState.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,18 +2,27 @@
using HarmonyLib;
using Multiplayer.Client.Networking;
using Multiplayer.Common;
using Multiplayer.Common.Networking.Packet;
using System.Linq;
using RimWorld;
using Verse;

namespace Multiplayer.Client
{
[PacketHandlerClass]
public class ClientJoiningState : ClientBaseState
{
public ClientJoiningState(ConnectionBase connection) : base(connection)
{
}

[TypedPacketHandler]
public void HandleBootstrap(ServerBootstrapPacket packet)
{
Multiplayer.session.serverIsInBootstrap = packet.bootstrap;
Multiplayer.session.serverBootstrapSettingsMissing = packet.settingsMissing;
}

public override void StartState()
{
connection.Send(Packets.Client_Protocol, MpVersion.Protocol);
Expand Down Expand Up @@ -132,6 +141,13 @@ void Complete()

void StartDownloading()
{
if (Multiplayer.session.serverIsInBootstrap)
{
connection.ChangeState(ConnectionStateEnum.ClientBootstrap);
Find.WindowStack.Add(new BootstrapConfiguratorWindow(connection));
return;
}

connection.Send(Packets.Client_WorldRequest);
connection.ChangeState(ConnectionStateEnum.ClientLoading);
}
Expand Down
1 change: 1 addition & 0 deletions Source/Client/Networking/State/ClientPlayingState.cs
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@

namespace Multiplayer.Client
{
[PacketHandlerClass]
public class ClientPlayingState : ClientBaseState
{
public ClientPlayingState(ConnectionBase connection) : base(connection)
Expand Down
1 change: 1 addition & 0 deletions Source/Client/Networking/State/ClientSteamState.cs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@

namespace Multiplayer.Client
{
[PacketHandlerClass]
public class ClientSteamState : MpConnectionState
{
public ClientSteamState(ConnectionBase connection) : base(connection)
Expand Down
4 changes: 4 additions & 0 deletions Source/Client/OnMainThread.cs
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,10 @@ public void Update()
{
Multiplayer.session?.netClient?.PollEvents();
}
catch (InvalidOperationException e) when (e.Message == "Queue empty." || e.Message == "Coda vuota.")
Copy link

Copilot AI Mar 27, 2026

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The InvalidOperationException filter relies on exact, localized exception messages (only English/Italian are handled). On other locales the same LiteNetLib queue-race can still crash, and message matching is generally brittle. Consider centralizing this check (there is already LiteNetManager.IsQueueEmptyRace) and/or using a more robust condition (e.g. catching the specific LiteNetLib call site) instead of comparing localized strings.

Suggested change
catch (InvalidOperationException e) when (e.Message == "Queue empty." || e.Message == "Coda vuota.")
catch (InvalidOperationException e) when (LiteNetManager.IsQueueEmptyRace(e))

Copilot uses AI. Check for mistakes.
{
// LiteNetLib can throw here during reconnect/disconnect teardown when its event queue races empty.
}
catch (Exception e)
{
Log.Error($"Exception handling network events: {e}");
Expand Down
21 changes: 21 additions & 0 deletions Source/Client/Patches/BootstrapMapInitPatch.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
using HarmonyLib;
using Verse;

namespace Multiplayer.Client
{
[HarmonyPatch(typeof(MapComponentUtility), nameof(MapComponentUtility.FinalizeInit))]
static class BootstrapMapInitPatch
{
static void Postfix(Map map)
{
if (BootstrapConfiguratorWindow.AwaitingBootstrapMapInit &&
BootstrapConfiguratorWindow.Instance != null)
{
OnMainThread.Enqueue(() =>
{
BootstrapConfiguratorWindow.Instance.OnBootstrapMapInitialized();
});
}
}
}
}
22 changes: 22 additions & 0 deletions Source/Client/Patches/BootstrapRootPlayPatch.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
using HarmonyLib;
using Verse;

namespace Multiplayer.Client
{
/// <summary>
/// Root_Play.Start is called when the game fully transitions into Playing.
/// This is a reliable signal for arming the bootstrap map init detection.
/// </summary>
[HarmonyPatch(typeof(Root_Play), nameof(Root_Play.Start))]
static class BootstrapRootPlayPatch
{
static void Postfix()
{
var inst = BootstrapConfiguratorWindow.Instance;
if (inst == null)
return;

inst.TryArmAwaitingBootstrapMapInit_FromRootPlay();
}
}
}
29 changes: 29 additions & 0 deletions Source/Client/Patches/BootstrapRootPlayUpdatePatch.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
using HarmonyLib;
using Verse;

namespace Multiplayer.Client
{
/// <summary>
/// Root_Play.Update runs through the whole transition from MapInitializing to Playing.
/// Arms the map-init trigger as soon as a map exists and ProgramState is Playing.
/// </summary>
[HarmonyPatch(typeof(Root_Play), nameof(Root_Play.Update))]
static class BootstrapRootPlayUpdatePatch
{
private static int nextCheckFrame;
private const int CheckEveryFrames = 10;

static void Postfix()
{
var win = BootstrapConfiguratorWindow.Instance;
if (win == null)
return;

if (UnityEngine.Time.frameCount < nextCheckFrame)
return;
nextCheckFrame = UnityEngine.Time.frameCount + CheckEveryFrames;

win.TryArmAwaitingBootstrapMapInit_FromRootPlayUpdate();
}
}
}
28 changes: 28 additions & 0 deletions Source/Client/Patches/BootstrapStartedNewGamePatch.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
using HarmonyLib;
using RimWorld;
using Verse;

namespace Multiplayer.Client
{
/// <summary>
/// When the vanilla flow finishes generating the new game, this fires once the map and pawns are ready.
/// Backup signal to kick the bootstrap save pipeline in case FinalizeInit was missed or delayed.
/// </summary>
[HarmonyPatch(typeof(GameComponentUtility), nameof(GameComponentUtility.StartedNewGame))]
public static class BootstrapStartedNewGamePatch
{
static void Postfix()
{
var window = BootstrapConfiguratorWindow.Instance;
if (window == null)
return;

BootstrapConfiguratorWindow.AwaitingBootstrapMapInit = true;

OnMainThread.Enqueue(() =>
{
window.OnBootstrapMapInitialized();
});
}
}
}
16 changes: 13 additions & 3 deletions Source/Client/Session/Autosaving.cs
Original file line number Diff line number Diff line change
Expand Up @@ -39,14 +39,24 @@ public static void SaveGameToFile_Overwrite(string fileNameNoExtension, bool cur

try
{
new FileInfo(Path.Combine(Multiplayer.ReplaysDir, $"{fileNameNoExtension}.zip")).Delete();
Replay.ForSaving(fileNameNoExtension).WriteData(
// Ensure the replays directory exists even when not connected to a server
Directory.CreateDirectory(Multiplayer.ReplaysDir);

var tmp = new FileInfo(Path.Combine(Multiplayer.ReplaysDir, $"{fileNameNoExtension}.tmp.zip"));
Replay.ForSaving(tmp).WriteData(
currentReplay ?
Multiplayer.session.dataSnapshot :
SaveLoad.CreateGameDataSnapshot(SaveLoad.SaveGameData(), false)
);

var dst = new FileInfo(Path.Combine(Multiplayer.ReplaysDir, $"{fileNameNoExtension}.zip"));
if (!dst.Exists) dst.Open(FileMode.Create).Close();
tmp.Replace(dst.FullName, null);

Messages.Message("MpGameSaved".Translate(fileNameNoExtension), MessageTypeDefOf.SilentInput, false);
Multiplayer.session.lastSaveAt = Time.realtimeSinceStartup;
// In bootstrap/offline mode there may be no active session
if (Multiplayer.session != null)
Multiplayer.session.lastSaveAt = Time.realtimeSinceStartup;
}
catch (Exception e)
{
Expand Down
4 changes: 4 additions & 0 deletions Source/Client/Session/MultiplayerSession.cs
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,10 @@ public class MultiplayerSession : IConnectionStatusListener
public int port;
public CSteamID? steamHost;

// Set during handshake (see Server_Bootstrap packet) to indicate the server is waiting for configuration/upload.
public bool serverIsInBootstrap;
public bool serverBootstrapSettingsMissing;

public void Stop()
{
if (client != null)
Expand Down
Loading
Loading