Skip to content

Commit

Permalink
Clean up testing code
Browse files Browse the repository at this point in the history
Use the multifaction hosting option
Fix hosting from singleplayer saves
  • Loading branch information
Zetrith committed Oct 16, 2023
1 parent 73ccc5c commit c50a0ba
Show file tree
Hide file tree
Showing 18 changed files with 43 additions and 146 deletions.
8 changes: 5 additions & 3 deletions Source/Client/AsyncTime/AsyncWorldTimeComp.cs
Original file line number Diff line number Diff line change
Expand Up @@ -142,12 +142,14 @@ public void PreContext()
Rand.PushState();
Rand.StateCompressed = randState;

FactionExtensions.PushFaction(null, Multiplayer.WorldComp.spectatorFaction);
if (Multiplayer.GameComp.multifaction)
FactionExtensions.PushFaction(null, Multiplayer.WorldComp.spectatorFaction);
}

public void PostContext()
{
FactionExtensions.PopFaction();
if (Multiplayer.GameComp.multifaction)
FactionExtensions.PopFaction();

randState = Rand.StateCompressed;
Rand.PopState();
Expand Down Expand Up @@ -237,7 +239,7 @@ public void ExecuteCmd(ScheduledCommand cmd)

private static void CreateJoinPointAndSendIfHost()
{
Multiplayer.session.dataSnapshot = SaveLoad.CreateGameDataSnapshot(SaveLoad.SaveAndReload());
Multiplayer.session.dataSnapshot = SaveLoad.CreateGameDataSnapshot(SaveLoad.SaveAndReload(), Multiplayer.GameComp.multifaction);

if (!TickPatch.Simulating && !Multiplayer.IsReplay &&
(Multiplayer.LocalServer != null || Multiplayer.arbiterInstance))
Expand Down
4 changes: 2 additions & 2 deletions Source/Client/Debug/DebugPatches.cs
Original file line number Diff line number Diff line change
Expand Up @@ -177,8 +177,8 @@ static void Prefix(ref string text)
{
// On Windows, Debug.Log used by Verse.Log replaces \n with \r\n
// Without this patch printing \r\n results in \r\r\n
// if (Native.Windows)
// text = text?.Replace("\r\n", "\n");
if (Application.platform == RuntimePlatform.WindowsPlayer)
text = text?.Replace("\r\n", "\n");
}
}

Expand Down
2 changes: 1 addition & 1 deletion Source/Client/Debug/DebugTools.cs
Original file line number Diff line number Diff line change
Expand Up @@ -153,7 +153,7 @@ public static void SendCmd(DebugSource source, int hash, string path, Map map)
public static DebugActionNode RecreateGraphAndGetNode(string path)
{
// Some actions (like quest generation) invoke the RNG during global graph caching
// so we it recreate to avoid desyncs
// so we recreate it to avoid desyncs
Dialog_Debug.ResetStaticData();
Dialog_Debug.TrySetupNodeGraph();

Expand Down
18 changes: 1 addition & 17 deletions Source/Client/EarlyInit.cs
Original file line number Diff line number Diff line change
Expand Up @@ -63,25 +63,9 @@ internal static void InitSync()
Sync.ValidateAll();
}

internal static void LatePatches(Harmony harmony)
internal static void LatePatches()
{
// optimization, cache DescendantThingDefs
// harmony.PatchMeasure(
// AccessTools.Method(typeof(ThingCategoryDef), "get_DescendantThingDefs"),
// new HarmonyMethod(typeof(ThingCategoryDef_DescendantThingDefsPatch), "Prefix"),
// new HarmonyMethod(typeof(ThingCategoryDef_DescendantThingDefsPatch), "Postfix")
// );

// optimization, cache ThisAndChildCategoryDefs
// harmony.PatchMeasure(
// AccessTools.Method(typeof(ThingCategoryDef), "get_ThisAndChildCategoryDefs"),
// new HarmonyMethod(typeof(ThingCategoryDef_ThisAndChildCategoryDefsPatch), "Prefix"),
// new HarmonyMethod(typeof(ThingCategoryDef_ThisAndChildCategoryDefsPatch), "Postfix")
// );

if (MpVersion.IsDebug)
{
Log.Message("== Structure == \n" + SyncDict.syncWorkers.PrintStructure());
}
}
}
40 changes: 1 addition & 39 deletions Source/Client/Factions/MultifactionPatches.cs
Original file line number Diff line number Diff line change
Expand Up @@ -77,17 +77,10 @@ static bool Prefix(MapParent __instance)
}
}

// todo this is temporary
[HarmonyPatch(typeof(GoodwillSituationManager), nameof(GoodwillSituationManager.GoodwillManagerTick))]
static class GoodwillManagerTickCancel
{
static bool Prefix() => false;
}

[HarmonyPatch(typeof(Settlement), nameof(Settlement.Attackable), MethodType.Getter)]
static class SettlementAttackablePatch
{
static bool Prefix() => false; // todo should only be player
static bool Prefix(Settlement __instance) => __instance.Faction is not { IsPlayer: true };
}

[HarmonyPatch(typeof(Settlement), nameof(Settlement.Material), MethodType.Getter)]
Expand All @@ -108,37 +101,6 @@ static bool Prefix(Settlement __instance, ref Material __result)
[HarmonyPatch(typeof(Settlement), nameof(Settlement.ExpandingIcon), MethodType.Getter)]
static class SettlementNullFactionPatch2
{
static void OnCodeReload(int version)
{
var harmony = new Harmony("mptestpatches");
harmony.UnpatchAll("mptestpatches");

static bool GoodwillPrefix(Faction other)
{
return other is not { IsPlayer: true };
}

static void PrintPrefix()
{
Log.Message("add pawn");
}

harmony.Patch(
MethodOf.Inner((GoodwillSituationManager m) => m.GetNaturalGoodwill),
MethodOf.Lambda(GoodwillPrefix).Harmony()
);

harmony.Patch(
MethodOf.Inner((GoodwillSituationManager m) => m.GetMaxGoodwill),
MethodOf.Lambda(GoodwillPrefix).Harmony()
);

harmony.Patch(
MethodOf.Inner((WorldPawns w) => w.AddPawn(null)),
MethodOf.Lambda(PrintPrefix).Harmony()
);
}

static bool Prefix(Settlement __instance, ref Texture2D __result)
{
if (__instance.factionInt == null)
Expand Down
2 changes: 1 addition & 1 deletion Source/Client/Multiplayer.cs
Original file line number Diff line number Diff line change
Expand Up @@ -121,7 +121,7 @@ public static void InitMultiplayer()

LongEventHandler.ExecuteWhenFinished(() => {
// Double Execute ensures it'll run last.
LongEventHandler.ExecuteWhenFinished(() => EarlyInit.LatePatches(harmony));
LongEventHandler.ExecuteWhenFinished(EarlyInit.LatePatches);
});

#if DEBUG
Expand Down
4 changes: 3 additions & 1 deletion Source/Client/MultiplayerSession.cs
Original file line number Diff line number Diff line change
Expand Up @@ -268,7 +268,9 @@ public static void SaveGameToFile_Overwrite(string fileNameNoExtension, bool cur
{
new FileInfo(Path.Combine(Multiplayer.ReplaysDir, $"{fileNameNoExtension}.zip")).Delete();
Replay.ForSaving(fileNameNoExtension).WriteData(
currentReplay ? Multiplayer.session.dataSnapshot : SaveLoad.CreateGameDataSnapshot(SaveLoad.SaveGameData())
currentReplay ?
Multiplayer.session.dataSnapshot :
SaveLoad.CreateGameDataSnapshot(SaveLoad.SaveGameData(), false)
);
Messages.Message("MpGameSaved".Translate(fileNameNoExtension), MessageTypeDefOf.SilentInput, false);
Multiplayer.session.lastSaveAt = Time.realtimeSinceStartup;
Expand Down
2 changes: 1 addition & 1 deletion Source/Client/Networking/HostUtil.cs
Original file line number Diff line number Diff line change
Expand Up @@ -117,7 +117,7 @@ private static void SetGameState(ServerSettings settings)
private static async Task<GameDataSnapshot> CreateGameData()
{
await LongEventTask.ContinueInLongEvent("MpSaving", false);
return SaveLoad.CreateGameDataSnapshot(SaveLoad.SaveAndReload());
return SaveLoad.CreateGameDataSnapshot(SaveLoad.SaveAndReload(), Multiplayer.GameComp.multifaction);
}

private static void SetupGameFromSingleplayer()
Expand Down
2 changes: 0 additions & 2 deletions Source/Client/Networking/State/ClientLoadingState.cs
Original file line number Diff line number Diff line change
Expand Up @@ -72,8 +72,6 @@ public void HandleWorldData(ByteReader data)
mapsToLoad.Add(mapId);
}

//mapsToLoad.RemoveAt(Multiplayer.LocalServer != null ? 1 : 0); // todo dbg

Session.dataSnapshot = new GameDataSnapshot(
0,
worldData,
Expand Down
52 changes: 0 additions & 52 deletions Source/Client/Patches/Optimizations.cs

This file was deleted.

12 changes: 12 additions & 0 deletions Source/Client/Patches/Patches.cs
Original file line number Diff line number Diff line change
Expand Up @@ -546,4 +546,16 @@ static IEnumerable<CodeInstruction> Transpiler(IEnumerable<CodeInstruction> inst
return list;
}
}

[HarmonyPatch(typeof(PawnTextureAtlas), MethodType.Constructor)]
static class PawnTextureAtlasCtorPatch
{
static void Postfix(PawnTextureAtlas __instance)
{
// Pawn ids can change during deserialization when fixing local (negative) ids in CrossRefHandler_Clear_Patch
__instance.frameAssignments = new Dictionary<Pawn, PawnTextureAtlasFrameSet>(
IdentityComparer<Pawn>.Instance
);
}
}
}
2 changes: 1 addition & 1 deletion Source/Client/Saving/LoadPatch.cs
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ static bool Prefix()

try
{
ScribeUtil.StartLoading(gameToLoad.SaveData);
ScribeUtil.InitFromXmlDoc(gameToLoad.SaveData);
ScribeMetaHeaderUtility.LoadGameDataHeader(ScribeMetaHeaderUtility.ScribeHeaderMode.Map, false);
Scribe.EnterNode("game");
Current.Game = new Game();
Expand Down
8 changes: 0 additions & 8 deletions Source/Client/Saving/Loader.cs
Original file line number Diff line number Diff line change
Expand Up @@ -63,10 +63,6 @@ private static void PostLoad(bool forceAsyncTime)
);
Multiplayer.game.myFactionLoading = null;

// todo temporary
// Current.Game.InitData = new GameInitData() { mapSize = 50 };
// Find.WindowStack.Add(new Page_SelectStartingSite());

if (forceAsyncTime)
Multiplayer.game.gameComp.asyncTime = true;

Expand All @@ -86,10 +82,6 @@ private static XmlDocument DataSnapshotToXml(GameDataSnapshot dataSnapshot, List
using XmlReader reader = XmlReader.Create(new MemoryStream(dataSnapshot.MapData[map]));
XmlNode mapNode = gameDoc.ReadNode(reader);
gameNode["maps"].AppendChild(mapNode);

// todo temporary
// if (gameNode["currentMapIndex"] == null)
// gameNode.AddNode("currentMapIndex", map.ToString());
}

return gameDoc;
Expand Down
6 changes: 4 additions & 2 deletions Source/Client/Saving/SaveLoad.cs
Original file line number Diff line number Diff line change
Expand Up @@ -184,7 +184,7 @@ public static XmlDocument SaveGameToDoc()
return ScribeUtil.FinishWritingToDoc();
}

public static GameDataSnapshot CreateGameDataSnapshot(TempGameData data)
public static GameDataSnapshot CreateGameDataSnapshot(TempGameData data, bool removeCurrentMapId)
{
XmlNode gameNode = data.SaveData.DocumentElement["game"];
XmlNode mapsNode = gameNode["maps"];
Expand All @@ -200,7 +200,9 @@ public static GameDataSnapshot CreateGameDataSnapshot(TempGameData data)
mapCmdsDict[id] = new List<ScheduledCommand>(Find.Maps.First(m => m.uniqueID == id).AsyncTime().cmds);
}

gameNode["currentMapIndex"].RemoveFromParent();
if (removeCurrentMapId)
gameNode["currentMapIndex"].RemoveFromParent();

mapsNode.RemoveAll();

byte[] gameData = ScribeUtil.XmlToByteArray(data.SaveData);
Expand Down
12 changes: 3 additions & 9 deletions Source/Client/Saving/ScribeUtil.cs
Original file line number Diff line number Diff line change
Expand Up @@ -66,21 +66,14 @@ public static XmlDocument FinishWritingToDoc()
return doc;
}

public static void StartLoading(XmlDocument doc)
public static void InitFromXmlDoc(XmlDocument doc)
{
loading = true;

ScribeMetaHeaderUtility.loadedGameVersion = VersionControl.CurrentVersionStringWithRev;

Scribe.loader.curXmlParent = doc.DocumentElement;
Scribe.mode = LoadSaveMode.LoadingVars;
}

public static void StartLoading(byte[] data)
{
StartLoading(LoadDocument(data));
}

public static void FinalizeLoading()
{
if (!loading)
Expand Down Expand Up @@ -181,7 +174,8 @@ public static byte[] WriteExposable(IExposable element, string name = RootNode,

public static T ReadExposable<T>(byte[] data, Action<T> beforeFinish = null) where T : IExposable
{
StartLoading(data);
loading = true;
InitFromXmlDoc(LoadDocument(data));
SupplyCrossRefs();

T element = default;
Expand Down
4 changes: 2 additions & 2 deletions Source/Client/Util/MpUtil.cs
Original file line number Diff line number Diff line change
Expand Up @@ -177,9 +177,9 @@ IEnumerator IEnumerable.GetEnumerator()
}
}

public class DefaultComparer<T> : IEqualityComparer<T>
public class IdentityComparer<T> : IEqualityComparer<T>
{
public static DefaultComparer<T> Instance = new DefaultComparer<T>();
public static IdentityComparer<T> Instance = new();

public bool Equals(T x, T y)
{
Expand Down
7 changes: 3 additions & 4 deletions Source/Client/Windows/ServerBrowser.cs
Original file line number Diff line number Diff line change
Expand Up @@ -19,13 +19,12 @@

namespace Multiplayer.Client
{

public class ServerBrowser : Window
{
private NetManager lanListener;
private List<LanServer> servers = new List<LanServer>();
private List<LanServer> servers = new();

public override Vector2 InitialSize => new Vector2(800f, 500f);
public override Vector2 InitialSize => new(800f, 500f);

public ServerBrowser()
{
Expand Down Expand Up @@ -53,7 +52,7 @@ public ServerBrowser()

private Vector2 lanScroll;
private Vector2 steamScroll;
private Vector2 hostScroll;
private static Vector2 hostScroll;
private static Tabs tab;

enum Tabs
Expand Down
4 changes: 3 additions & 1 deletion Source/Common/PlayerManager.cs
Original file line number Diff line number Diff line change
Expand Up @@ -131,7 +131,9 @@ public void OnDesync(ServerPlayer player, int tick, int diffAt)
public void OnJoin(ServerPlayer player)
{
player.hasJoined = true;
player.FactionId = player.id == 0 ? server.worldData.hostFactionId : server.worldData.spectatorFactionId;
player.FactionId = player.id == 0 || !server.settings.multifaction ?
server.worldData.hostFactionId :
server.worldData.spectatorFactionId;

server.SendNotification("MpPlayerConnected", player.Username);
server.SendChat($"{player.Username} has joined.");
Expand Down

0 comments on commit c50a0ba

Please sign in to comment.