forked from Rollocraft/CS2MultiplayerMod
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCityStateSyncSystem.cs
More file actions
337 lines (298 loc) · 15.6 KB
/
Copy pathCityStateSyncSystem.cs
File metadata and controls
337 lines (298 loc) · 15.6 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
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Diagnostics;
using System.Threading;
using Game;
using Unity.Entities;
using CS2MPMod.Core.Diagnostics;
using CS2MPMod.Core.Protocol;
using CS2MPMod.Core.Protocol.Messages;
using CS2MPMod.Core.Session;
using CS2MPMod.Game.Diagnostics;
using CS2MPMod.Game.Sync.Infrastructure;
using CS2MPMod.Game.Sync.Channels;
namespace CS2MPMod.Game.Sync.Systems
{
/// <summary>
/// Replicates city state via <see cref="IStateChannel"/> snapshots: host periodically
/// captures and broadcasts; clients apply snapshots and detect edits via <see cref="StateEditMessage"/>.
/// Two channel types: authoritative (money, XP, etc., host to clients);
/// editable (taxes, policies, etc., client edit -> host -> broadcast). Host is arbiter.
/// </summary>
public partial class CityStateSyncSystem : GameSystemBase
{
/// <summary>How often the host publishes a fresh snapshot.</summary>
private const long SnapshotIntervalMs = 1000;
/// <summary>How often a client compares its local editable state against the host's.</summary>
private const long EditDetectIntervalMs = 250;
/// <summary>How long a client trusts its own in-flight edit over incoming snapshots.</summary>
private const long EditPendingTimeoutMs = 5000;
private const int OrderedApplyPerFrame = 16;
private const int OrderedDeferredCap = 256;
private readonly Dictionary<byte, IStateChannel> _channels = new Dictionary<byte, IStateChannel>();
private readonly List<IPumpedStateChannel> _pumped = new List<IPumpedStateChannel>();
private readonly HashSet<byte> _editable = new HashSet<byte>();
private readonly HashSet<byte> _ordered = new HashSet<byte>();
// Newest queued snapshot per channel, rebuilt per drain.
private readonly Dictionary<byte, StateSnapshotMessage> _newestSnapshot =
new Dictionary<byte, StateSnapshotMessage>();
private readonly List<byte> _newestOrder = new List<byte>();
private readonly ConcurrentQueue<StateSnapshotMessage> _incoming = new ConcurrentQueue<StateSnapshotMessage>();
private readonly ConcurrentQueue<StateEditMessage> _incomingEdits = new ConcurrentQueue<StateEditMessage>();
private readonly ConcurrentQueue<StateSnapshotMessage> _orderedDeferred =
new ConcurrentQueue<StateSnapshotMessage>();
private readonly Stopwatch _clock = Stopwatch.StartNew();
// Client-side edit tracking: what the host last sent per editable channel, and
// the edit we shipped and are waiting to see confirmed in a snapshot.
private readonly Dictionary<byte, byte[]> _lastHostPayload = new Dictionary<byte, byte[]>();
private readonly Dictionary<byte, PendingEdit> _pendingEdits = new Dictionary<byte, PendingEdit>();
private Observer _observer;
private TreeStateChannel _treeStateChannel;
private long _lastSnapshotMs;
private long _lastEditScanMs;
private long _lastLogMs;
private int _applied;
private int _superseded;
private bool _orderedInvalidated;
private int _orderedPoisonRequested;
private struct PendingEdit
{
public byte[] Payload;
public long SentMs;
}
protected override void OnCreate()
{
base.OnCreate();
// Simulation-owned values: one source of truth, host → clients.
Register(new MoneyStateChannel());
// No population channel: the HUD population count is a cosmetic output of each
// peer's own simulation. Overwriting it once a second made the client's number
// flicker as the local sim and the snapshot fought over it. Channel id 2 is retired.
Register(new XpStateChannel());
Register(new MilestoneStateChannel());
Register(new DevTreePointsStateChannel());
Register(new TourismStateChannel());
Register(new StatisticsStateChannel());
// Taxation's displayed residential/commercial/industrial/office amounts come from
// parameterized taxable-income statistics, independently of the editable rate table.
Register(new TaxIncomeStateChannel());
// Fee events from every service path and the collected building/net upkeep records
// converge into one native accounting view. Keep that terminal view host-owned while
// channel 8 remains the separately editable fee-slider table.
Register(new ServiceAccountingStateChannel(
World.GetOrCreateSystemManaged<ServiceAccountingCorrectionSystem>()));
Register(new WeatherStateChannel());
Register(new GameClockStateChannel());
_treeStateChannel = new TreeStateChannel();
Register(_treeStateChannel);
// Full native demand state. On a client the channel holds the three redundant demand
// writers after its first valid snapshot and feeds their host arrays to native readers.
Register(new ZoneDemandChannel());
// Numeric rent only. The channel queues rolling absolute pages; its runtime applies
// them in GameSimulation after vanilla recalculates rent and before rent is charged.
Register(new PropertyRentStateChannel(
World.GetOrCreateSystemManaged<PropertyRentSyncSystem>()));
// Who lives in each residential building, and the people in those households. Rolling
// absolute pages; the runtime reconciles them in GameSimulation through the game's own
// renter pipeline. See ResidentialOccupancySyncSystem.
Register(new ResidentialOccupancyChannel(
World.GetOrCreateSystemManaged<ResidentialOccupancySyncSystem>()));
// The money-facing figures behind every shop, factory and office, and the goods they
// hold. Rolling absolute pages; the runtime corrects them in GameSimulation in the
// same frame the game recomputes them. See CompanyStatsSyncSystem.
Register(new CompanyStatsStateChannel(
World.GetOrCreateSystemManaged<CompanyStatsSyncSystem>()));
// Player-editable settings: every player may change them; the host arbitrates.
RegisterEditable(new TaxStateChannel());
RegisterEditable(new CityPolicyStateChannel());
RegisterEditable(new ServiceFeeStateChannel());
RegisterEditable(new ServiceBudgetStateChannel());
RegisterEditable(new SimulationSpeedStateChannel());
RegisterEditable(new LoanStateChannel());
RegisterEditable(new CityNameStateChannel());
SyncLog.Detail(LogTopic.City, nameof(CityStateSyncSystem) + " ready with " +
_channels.Count + " state channel(s), " + _editable.Count + " player-editable.");
_observer = SyncObserverBinding.Bind(
() => new Observer(_incoming, _incomingEdits, RequestOrderedPoison,
channelId => _editable.Contains(channelId)),
DrainQueues);
}
protected override void OnDestroy()
{
SyncObserverBinding.Unbind(_observer, DrainQueues);
if (_treeStateChannel != null) _treeStateChannel.Dispose();
base.OnDestroy();
}
/// <summary>Ensure a newly placed host tree is included in the next bounded snapshot.</summary>
internal void PrioritizeTree(Entity entity)
{
if (_treeStateChannel != null) _treeStateChannel.Prioritize(entity);
}
private void Register(IStateChannel channel)
{
_channels[channel.ChannelId] = channel;
var pumped = channel as IPumpedStateChannel;
if (pumped != null) _pumped.Add(pumped);
if (channel is IOrderedStateChannel) _ordered.Add(channel.ChannelId);
}
private void RegisterEditable(IStateChannel channel)
{
Register(channel);
_editable.Add(channel.ChannelId);
}
protected override void OnUpdate()
{
using (Diagnostics.SyncProfiler.Measure("CityState"))
{
if (Interlocked.Exchange(ref _orderedPoisonRequested, 0) != 0)
PoisonOrderedStream("invalid or overflowed ordered-state ingress");
MultiplayerService service = Mod.Service;
if (service == null) return;
MultiplayerSession session = service.Session;
if (!service.GameplaySyncReady)
{
// Leaving a session invalidates everything we knew about the host's state.
if (_lastHostPayload.Count > 0) { _lastHostPayload.Clear(); _pendingEdits.Clear(); }
for (int i = 0; i < _pumped.Count; i++) _pumped[i].ResetPending();
SyncInbox.Clear(_incoming);
SyncInbox.Clear(_incomingEdits);
SyncInbox.Clear(_orderedDeferred);
_newestSnapshot.Clear();
_newestOrder.Clear();
_orderedInvalidated = false;
Interlocked.Exchange(ref _orderedPoisonRequested, 0);
return;
}
if (session.Role == SessionRole.Host)
{
ApplyIncomingEdits();
CaptureAndBroadcast(session);
}
else
{
DetectLocalEdits(session);
ApplyIncoming();
PumpChannels();
}
}
}
// ---- Host ------------------------------------------------------------
private void CaptureAndBroadcast(MultiplayerSession session)
{
long now = _clock.ElapsedMilliseconds;
if (_lastSnapshotMs != 0 && now - _lastSnapshotMs < SnapshotIntervalMs) return;
_lastSnapshotMs = now;
int sent = 0;
foreach (var pair in _channels)
{
var writer = new NetworkWriter(64);
if (pair.Value.Capture(EntityManager, writer)) { session.SendState(pair.Key, writer.ToArray()); sent++; }
}
// Heartbeat every ~30 s so the log shows state replication is alive without spam.
if (now - _lastLogMs >= 30000)
{
_lastLogMs = now;
SyncLog.Detail(LogTopic.City, "CityState: broadcasting " + sent +
" channel(s)/snapshot to clients.");
}
}
// ---- Client ------------------------------------------------------------
/// <summary>
/// A local edit shows up as the channel capturing something different from what
/// the host last sent (and from anything we already shipped). Runs before
/// <see cref="ApplyIncoming"/> so a fresh edit is sent before a stale snapshot
/// could overwrite it.
/// </summary>
private void DetectLocalEdits(MultiplayerSession session)
{
long now = _clock.ElapsedMilliseconds;
if (now - _lastEditScanMs < EditDetectIntervalMs) return;
_lastEditScanMs = now;
foreach (byte channelId in _editable)
{
// Until the host has told us its state once, "different" means nothing —
// we may simply still hold pre-join defaults.
byte[] hostPayload;
if (!_lastHostPayload.TryGetValue(channelId, out hostPayload)) continue;
var writer = new NetworkWriter(64);
if (!_channels[channelId].Capture(EntityManager, writer)) continue;
byte[] local = writer.ToArray();
if (BytesEqual(local, hostPayload)) { _pendingEdits.Remove(channelId); continue; }
PendingEdit pending;
if (_pendingEdits.TryGetValue(channelId, out pending) &&
BytesEqual(local, pending.Payload) &&
now - pending.SentMs < EditPendingTimeoutMs)
continue; // already in flight
_pendingEdits[channelId] = new PendingEdit { Payload = local, SentMs = now };
session.SendStateEdit(channelId, local);
SyncLog.Detail(LogTopic.City, "CityState: local edit on channel " + channelId +
" sent to host.");
}
}
/// <summary>Bridges session callbacks (sim thread) into this system's queues.</summary>
private sealed class Observer : SessionObserver
{
private const int EditIngressCap = 256;
private readonly ConcurrentQueue<StateSnapshotMessage> _snapshots;
private readonly ConcurrentQueue<StateEditMessage> _edits;
private readonly System.Action _poisonOrdered;
private readonly System.Func<byte, bool> _isEditable;
public Observer(ConcurrentQueue<StateSnapshotMessage> snapshots,
ConcurrentQueue<StateEditMessage> edits, System.Action poisonOrdered,
System.Func<byte, bool> isEditable)
{
_snapshots = snapshots;
_edits = edits;
_poisonOrdered = poisonOrdered;
_isEditable = isEditable;
}
public override void OnStateReceived(StateSnapshotMessage snapshot)
{
if (!SyncInbox.Push(_snapshots, snapshot)) _poisonOrdered();
}
public override void OnStateEditReceived(StateEditMessage edit)
{
// Reject channel probing before it can occupy the shared edit inbox. In particular,
// channel 19 is host-only and must never be client-injectable through StateEdit.
if (edit == null || !_isEditable(edit.ChannelId)) return;
// Edits are absolute proposals, not an ordered dependency stream. Under a hostile
// burst it is safer to drop excess proposals than trigger a multi-megabyte world
// resync; the next host snapshot remains authoritative.
lock (_edits)
{
if (_edits.Count >= EditIngressCap) return;
_edits.Enqueue(edit);
}
}
}
private void DrainQueues()
{
SyncInbox.Clear(_incoming);
SyncInbox.Clear(_incomingEdits);
_newestSnapshot.Clear();
_newestOrder.Clear();
SyncInbox.Clear(_orderedDeferred);
_orderedInvalidated = false;
Interlocked.Exchange(ref _orderedPoisonRequested, 0);
_lastHostPayload.Clear();
_pendingEdits.Clear();
for (int i = 0; i < _pumped.Count; i++) _pumped[i].ResetPending();
}
private void RequestOrderedPoison()
{
Interlocked.Exchange(ref _orderedPoisonRequested, 1);
}
private void PoisonOrderedStream(string reason)
{
if (_orderedInvalidated) return;
_orderedInvalidated = true;
SyncInbox.Clear(_orderedDeferred);
// The ordered city-state stream is revisioned: once a page is lost or refused, every
// later page describes a state this machine never reached. Nothing local supplies it.
SyncInbox.RequestResync(CS2MPMod.Game.Diagnostics.ResyncReport
.Create(reason, "city-state", CS2MPMod.Game.Diagnostics.ResyncEvidence.StreamLoss)
.About("ordered city-state stream")
.Tried("nothing - the ordered stream was invalidated and its deferred pages dropped"));
}
}
}