-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMain.cs
More file actions
198 lines (165 loc) · 7.71 KB
/
Main.cs
File metadata and controls
198 lines (165 loc) · 7.71 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
using System.Collections.Generic;
using System.Net.Http;
using System.Text.Json;
using BepInEx.Logging;
using HarmonyLib;
using Polytopia.Data;
using Il2CppSystem.IO;
using BinaryReader = Il2CppSystem.IO.BinaryReader;
using EndOfStreamException = System.IO.EndOfStreamException;
namespace DystopiaPolyScript;
public class ServerConfig
{
public string ServerUrl { get; init; } = "https://dev.polydystopia.xyz";
}
public static class Main
{
private const string CONFIG_FILE_NAME = "polydystopia_server_config.json";
private const string DEFAULT_SERVER_URL = "https://dev.polydystopia.xyz";
private const string GldMarker = "##GLD:";
private static string _serverUrl = DEFAULT_SERVER_URL;
private static ManualLogSource _logger = null!;
// Cache parsed GLD by game Seed to handle rewinds/reloads
private static readonly Dictionary<int, GameLogicData> _gldCache = new();
private static readonly Dictionary<int, int> _versionCache = new(); // Seed -> modGldVersion
public static void Load(ManualLogSource logger)
{
_logger = logger;
_serverUrl = LoadServerUrlFromFile(logger);
BuildConfigHelper.GetSelectedBuildConfig().buildServerURL = BuildServerURL.Custom;
BuildConfigHelper.GetSelectedBuildConfig().customServerURL = _serverUrl;
// Apply Harmony patches
Harmony.CreateAndPatchAll(typeof(Main));
logger.LogInfo($"Polydystopia> Server URL set to: {_serverUrl}");
logger.LogInfo("Polydystopia> GLD patches applied");
}
/// <summary>
/// After GameState deserialization, check for trailing GLD version ID and set mockedGameLogicData.
/// The server appends "##GLD:" + modGldVersion (int) after the normal serialized data.
/// </summary>
[HarmonyPostfix]
[HarmonyPatch(typeof(GameState), nameof(GameState.Deserialize))]
private static void Deserialize_Postfix(GameState __instance, BinaryReader __0)
{
_logger?.LogDebug("Deserialize_Postfix: Entered");
try
{
var reader = __0;
if (reader == null)
{
_logger?.LogWarning("Deserialize_Postfix: reader is null");
return;
}
var position = reader.BaseStream.Position;
var length = reader.BaseStream.Length;
var remaining = length - position;
_logger?.LogDebug($"Deserialize_Postfix: Stream position={position}, length={length}, remaining={remaining}");
// Check if there's more data after normal deserialization
if (position >= length)
{
_logger?.LogDebug("Deserialize_Postfix: No trailing data (position >= length)");
var sd = __instance.Seed;
if (_gldCache.TryGetValue(sd, out var cachedGld))
{
__instance.mockedGameLogicData = cachedGld;
var cachedVersion = _versionCache.GetValueOrDefault(sd, -1);
_logger?.LogInfo($"Deserialize_Postfix: Applied cached GLD for Seed={sd}, ModGldVersion={cachedVersion}");
}
return;
}
_logger?.LogDebug($"Deserialize_Postfix: Found {remaining} bytes of trailing data, attempting to read marker");
var marker = reader.ReadString();
_logger?.LogDebug($"Deserialize_Postfix: Read marker string: '{marker}'");
if (marker != GldMarker)
{
_logger?.LogDebug($"Deserialize_Postfix: Marker mismatch - expected '{GldMarker}', got '{marker}'");
return;
}
_logger?.LogInfo($"Deserialize_Postfix: Found GLD marker '{GldMarker}'");
var modGldVersion = reader.ReadInt32();
_logger?.LogInfo($"Deserialize_Postfix: Found embedded ModGldVersion: {modGldVersion}");
_logger?.LogDebug($"Deserialize_Postfix: Fetching GLD from server for version {modGldVersion}");
var gldJson = FetchGldById(modGldVersion);
if (string.IsNullOrEmpty(gldJson))
{
_logger?.LogError($"Deserialize_Postfix: Failed to fetch GLD for ModGldVersion: {modGldVersion}");
return;
}
_logger?.LogDebug($"Deserialize_Postfix: Parsing GLD JSON ({gldJson.Length} chars)");
var customGld = new GameLogicData();
customGld.Parse(gldJson);
__instance.mockedGameLogicData = customGld;
// Cache for subsequent deserializations (rewinds, reloads)
var seed = __instance.Seed;
_gldCache[seed] = customGld;
_versionCache[seed] = modGldVersion;
_logger?.LogInfo($"Deserialize_Postfix: Successfully set mockedGameLogicData from ModGldVersion: {modGldVersion}, cached for Seed={seed}");
}
catch (EndOfStreamException)
{
_logger?.LogDebug("Deserialize_Postfix: EndOfStreamException - no trailing data");
}
catch (Exception ex)
{
_logger?.LogError($"Deserialize_Postfix: Exception: {ex.GetType().Name}: {ex.Message}");
_logger?.LogDebug($"Deserialize_Postfix: Stack trace: {ex.StackTrace}");
}
}
/// <summary>
/// Fetch GLD from server using ModGldVersion ID
/// </summary>
private static string? FetchGldById(int modGldVersion)
{
try
{
using var client = new HttpClient();
var url = $"{_serverUrl.TrimEnd('/')}/api/mods/gld/{modGldVersion}";
_logger?.LogDebug($"FetchGldById: Requesting URL: {url}");
var response = client.GetAsync(url).Result;
_logger?.LogDebug($"FetchGldById: Response status: {response.StatusCode}");
if (response.IsSuccessStatusCode)
{
var gld = response.Content.ReadAsStringAsync().Result;
_logger?.LogInfo($"FetchGldById: Successfully fetched mod GLD ({gld.Length} chars)");
return gld;
}
var errorContent = response.Content.ReadAsStringAsync().Result;
_logger?.LogError($"FetchGldById: Failed with status {response.StatusCode}: {errorContent}");
}
catch (Exception ex)
{
_logger?.LogError($"FetchGldById: Exception: {ex.GetType().Name}: {ex.Message}");
if (ex.InnerException != null)
{
_logger?.LogError($"FetchGldById: Inner exception: {ex.InnerException.Message}");
}
}
return null;
}
private static string LoadServerUrlFromFile(ManualLogSource logger)
{
try
{
if (System.IO.File.Exists(CONFIG_FILE_NAME))
{
var jsonContent = System.IO.File.ReadAllText(CONFIG_FILE_NAME);
var config = JsonSerializer.Deserialize<ServerConfig>(jsonContent);
if (config != null && !string.IsNullOrEmpty(config.ServerUrl))
{
logger.LogInfo($"Polydystopia> Loaded server URL from {CONFIG_FILE_NAME}: {config.ServerUrl}");
return config.ServerUrl;
}
}
var defaultConfig = new ServerConfig { ServerUrl = DEFAULT_SERVER_URL };
var defaultJson = JsonSerializer.Serialize(defaultConfig, new JsonSerializerOptions { WriteIndented = true });
System.IO.File.WriteAllText(CONFIG_FILE_NAME, defaultJson);
logger.LogInfo($"Polydystopia> Created default config file {CONFIG_FILE_NAME} with URL: {DEFAULT_SERVER_URL}");
return DEFAULT_SERVER_URL;
}
catch (Exception ex)
{
logger.LogError($"Polydystopia> Error reading config file: {ex.Message}. Using default URL: {DEFAULT_SERVER_URL}");
return DEFAULT_SERVER_URL;
}
}
}