Rise
The Vieneo Province
Loading...
Searching...
No Matches
Tests/TelemetrySnapshotTests.cpp

Source at documentation-generation time. See Test catalog for fixture associations.

1#include "../DiscordActivityPayload.h"
2#include "../SteamPresencePayload.h"
3#include "../CrashBreadcrumbs.h"
4#include "../TelemetrySnapshot.h"
5#include "../TelemetryProtocolContract.h"
6#include "../TelemetryUploadCadence.h"
7
8#include <cstddef>
9#include <cmath>
10#include <cstdlib>
11#include <cstring>
12#include <iostream>
13#include <limits>
14#include <map>
15#include <stdexcept>
16
17namespace
18{
19 using namespace Telemetry;
20 constexpr double TestPi = 3.1415926535897932384626433832795;
21
22 void Check(bool condition, const char* message)
23 {
24 if (!condition)
25 throw std::runtime_error(message);
26 }
27
28 bool Near(double actual, double expected, double tolerance = 1.0e-6)
29 {
30 return std::abs(actual - expected) <= tolerance;
31 }
32
33 void TestCrashBreadcrumbs()
34 {
35 CrashBreadcrumbs trail;
36 char packet[256];
37 trail.FormatPacket(packet);
38 Check(packet[0] == '\0', "an empty crash history produced packet data");
39 for (int frame = 0; frame < 70; ++frame)
40 {
41 char message[32];
42 std::snprintf(message, sizeof message, "Frame%d", frame);
43 trail.Add(message);
44 }
45 Check(trail.Count() == 64 && std::strcmp(trail.Recent(0), "Frame69") == 0 &&
46 std::strcmp(trail.Recent(63), "Frame6") == 0,
47 "crash history failed to preserve the newest 64 entries across wraparound");
48 trail.FormatPacket(packet);
49 Check(std::strcmp(packet, "Frame69\nFrame68\nFrame67\nFrame66\nFrame65\n") == 0,
50 "crash packet did not contain the newest five breadcrumbs in reverse order");
51
52 const std::string oversized(500, 'X');
53 for (int i = 0; i < 5; ++i)
54 trail.Add(oversized.c_str());
55 Check(std::strlen(trail.Recent(0)) == 79, "oversized breadcrumb was not safely truncated");
56 struct GuardedPacket { char before; char text[256]; char after; } guarded = {'A', {}, 'Z'};
57 trail.FormatPacket(guarded.text);
58 Check(guarded.before == 'A' && guarded.after == 'Z' && std::strlen(guarded.text) == 250,
59 "long breadcrumbs exceeded the fixed network crash packet");
60 for (int i = 49; i < 250; i += 50)
61 Check(guarded.text[i] == '\n', "a long breadcrumb displaced another packet entry");
62 char tiny[1] = {'X'};
63 trail.FormatPacket(tiny);
64 Check(tiny[0] == '\0', "tiny crash packet was not terminated");
65 Check(trail.Count() == 64 && std::strlen(trail.Recent(0)) == 79,
66 "formatting a compact packet damaged the full local crash history");
67 }
68
69 void TestSteamPresence()
70 {
71 using namespace RiseSteam;
72 auto flight = BuildPresence("USV Wayfarer", "Docked at Cutter's Port (CPOC)");
73 Check(flight.status == "USV Wayfarer - Docked at Cutter's Port (CPOC)" &&
74 std::strcmp(flight.display, "#Rise_DetailsAndState") == 0,
75 "Steam presence omitted gameplay text or its display template");
76 auto room = BuildPresence("In their apartment", "");
77 Check(room.state.empty() && std::strcmp(room.display, "#Rise_Details") == 0,
78 "Steam indoor presence referenced an empty substitution");
79 auto onlyState = BuildPresence(nullptr, "On the ground");
80 Check(onlyState.status == "On the ground" && std::strcmp(onlyState.display, "#Rise_State") == 0,
81 "Steam state-only presence was not displayable");
82 auto empty = BuildPresence(nullptr, nullptr);
83 Check(!empty.status.empty() && std::strcmp(empty.display, "#Rise_Playing") == 0,
84 "Steam empty presence did not have a displayable fallback");
85 const char* screens[] = { "splash", "login", "loading", "immigration" };
86 const char* tokens[] = { "#Rise_Starting", "#Rise_Login", "#Rise_Loading", "#Rise_Immigration" };
87 for (size_t i = 0; i < 4; ++i)
88 Check(std::strcmp(BuildPresence("Screen", "State", screens[i]).display, tokens[i]) == 0,
89 "Steam screen presence did not use its localization token");
90
91 const std::string longText(300, 'X');
92 auto longPresence = BuildPresence(longText.c_str(), longText.c_str());
93 Check(longPresence.details.size() == 255 && longPresence.state.size() == 255 &&
94 longPresence.status.size() == 255, "Steam presence exceeded the API byte limit");
95 const std::string splitUtf8 = std::string(254, 'X') + "\xe2\x82\xac";
96 const std::string completeUtf8 = std::string(252, 'X') + "\xe2\x82\xac" + "Z";
97 Check(BuildPresence(splitUtf8.c_str(), "").details.size() == 254 &&
98 BuildPresence(completeUtf8.c_str(), "").details.size() == 255,
99 "Steam presence truncated inside a UTF-8 code point");
100
101 struct Friends
102 {
103 std::map<std::string, std::string> values;
104 std::string failKey;
105 bool SetRichPresence(const char* key, const char* value)
106 {
107 if (failKey == key && value && value[0])
108 return false;
109 if (value && value[0]) values[key] = value;
110 else values.erase(key);
111 return true;
112 }
113 } friends;
114 Check(PublishPresence(friends, flight) && friends.values["state"] == flight.state,
115 "Steam gameplay presence was not published");
116 Check(PublishPresence(friends, room) && friends.values.count("state") == 0 &&
117 friends.values["steam_display"] == "#Rise_Details",
118 "Steam screen transition retained a stale state");
119 friends.failKey = "state";
120 Check(!PublishPresence(friends, flight) && friends.values.count("steam_display") == 0,
121 "Steam advertised an incomplete presence after a rejected update");
122 friends.failKey.clear();
123 Check(PublishPresence(friends, flight) && friends.values["steam_display"] == "#Rise_DetailsAndState",
124 "Steam presence did not recover on the next update");
125 Check(friends.values.count("connect") == 0 && friends.values.count("steam_player_group") == 0,
126 "Steam presence advertised an unsupported join or party");
127 }
128
129 void TestDiscordActivityPayload()
130 {
131 RiseDiscord::Fields fields;
132 fields.state = "On the ground in Deois";
133 fields.details = "USV Wayfarer (IVR N123AB)";
134 fields.largeImageKey = "deois";
135 fields.largeImageText = "City of Deois";
136 fields.smallImageKey = "type5";
137 fields.smallImageText = "T-120 Steerhead";
138 fields.startTimestamp = 1724512345;
139
140 const auto activity = RiseDiscord::BuildActivity(fields);
141 Check(activity.state == fields.state && activity.details == fields.details,
142 "Discord activity omitted gameplay status text");
143 Check(activity.largeImageKey == fields.largeImageKey &&
144 activity.largeImageText == fields.largeImageText &&
145 activity.smallImageKey == fields.smallImageKey &&
146 activity.smallImageText == fields.smallImageText,
147 "Discord activity omitted configured artwork or hover text");
148 Check(activity.startMilliseconds == 1724512345000ULL,
149 "Discord activity did not convert Unix seconds to milliseconds");
150
151 const auto emptyActivity = RiseDiscord::BuildActivity({});
152 Check(emptyActivity.state.empty() && emptyActivity.details.empty() &&
153 emptyActivity.largeImageKey.empty() && emptyActivity.smallImageKey.empty() &&
154 emptyActivity.startMilliseconds == 0,
155 "Discord activity retained fields from a previous update");
156 fields.startTimestamp = -1;
157 Check(RiseDiscord::BuildActivity(fields).startMilliseconds == 0,
158 "Invalid Discord timestamp became a huge elapsed time");
159 fields.startTimestamp = (std::numeric_limits<std::int64_t>::max)();
160 Check(RiseDiscord::BuildActivity(fields).startMilliseconds == 0,
161 "Discord timestamp conversion overflowed");
162 char transient[] = "temporary";
163 fields.details = transient;
164 const auto owned = RiseDiscord::BuildActivity(fields);
165 transient[0] = 'X';
166 Check(owned.details == "temporary", "Pending Discord activity borrowed gameplay memory");
167 }
168
169 MotionSnapshot MakeSnapshot(std::uint16_t sequence, Vec3 position = {}, Vec3 velocity = {},
170 int reference = -1, int parent = -1, int identity = 1)
171 {
172 MotionSnapshot snapshot;
173 snapshot.sequence = sequence;
174 snapshot.position = position;
175 snapshot.velocity = velocity;
176 snapshot.orientation = {};
177 snapshot.reference = reference;
178 snapshot.parentSlot = parent;
179 snapshot.identity = identity;
180 snapshot.expectedIntervalSeconds = 0.25;
181 return snapshot;
182 }
183
184 MotionSnapshot MakeSourceSnapshot(std::uint16_t sequence, std::uint16_t sampleTimeMs,
185 std::uint16_t sourceRevision, Vec3 position = {}, Vec3 velocity = {},
186 int reference = -1, int parent = -1, int identity = 1)
187 {
188 MotionSnapshot snapshot = MakeSnapshot(sequence, position, velocity, reference, parent, identity);
189 snapshot.sampleTimeMs = sampleTimeMs;
190 snapshot.sourceRevision = sourceRevision;
191 return snapshot;
192 }
193
194 void TestPacketLayoutsAndTimestampRollover()
195 {
196 Check(sizeof(SClientPacketNew) == 72 && offsetof(SClientPacketNew, sampleTimeMs) == 70,
197 "SClientPacketNew timestamp layout changed");
198 Check(sizeof(SServerPacketNew) == 68 && offsetof(SServerPacketNew, sampleTimeMs) == 2 &&
199 offsetof(SServerPacketNew, sequence) == 60 && offsetof(SServerPacketNew, sourceRevision) == 66,
200 "SServerPacketNew source timing layout changed");
201 Check(sizeof(SWeaponPacket) == 40 && offsetof(SWeaponPacket, sampleTimeMs) == 2,
202 "SWeaponPacket timestamp layout changed");
203 Check(SourceTimeDeltaMilliseconds(34, 65520) == 50,
204 "source timestamp rollover 65520->34 was not 50 ms");
205 }
206
207 void TestJitterDoesNotEnterSourceTimeline()
208 {
209 SnapshotChannel channel;
210 channel.Configure(SequenceMode::UShort, {});
211 channel.Reset(1, -1, -1, false);
212 Check(channel.Push(MakeSourceSnapshot(10, 1000, 50, {0.00, 0, 0}, {1, 0, 0}), 0.00) == Acceptance::Accepted,
213 "source jitter setup 1 rejected");
214 Check(channel.Push(MakeSourceSnapshot(11, 1050, 51, {0.05, 0, 0}, {1, 0, 0}), 0.08) == Acceptance::Accepted,
215 "source jitter setup 2 rejected");
216 Check(channel.Push(MakeSourceSnapshot(12, 1100, 52, {0.10, 0, 0}, {1, 0, 0}), 0.21) == Acceptance::Accepted,
217 "source jitter sample 3 rejected");
218 Check(channel.Push(MakeSourceSnapshot(13, 1150, 53, {0.15, 0, 0}, {1, 0, 0}), 0.22) == Acceptance::Accepted,
219 "source jitter sample 4 rejected");
220 Check(channel.GetMetrics(0.22).sourceTimed, "vehicle did not activate source timing");
221 for (std::size_t index = 1; index < channel.Depth(); ++index)
222 Check(Near(channel.SnapshotAt(index).timelineSeconds - channel.SnapshotAt(index - 1).timelineSeconds, 0.05),
223 "receipt jitter entered the reconstructed source timeline");
224 }
225
226 void TestDeliveryLossAndSourceRevisionCoalescing()
227 {
228 SnapshotChannel loss;
230 loss.Reset(1, -1, -1, false);
231 Check(loss.Push(MakeSourceSnapshot(100, 2000, 100, {0, 0, 0}, {1, 0, 0}), 0.0) == Acceptance::Accepted, "loss setup 1");
232 Check(loss.Push(MakeSourceSnapshot(101, 2050, 101, {0.05, 0, 0}, {1, 0, 0}), 0.05) == Acceptance::Accepted, "loss setup 2");
233 Check(loss.Push(MakeSourceSnapshot(103, 2150, 103, {0.15, 0, 0}, {1, 0, 0}), 0.16) == Acceptance::Accepted, "loss sample");
234 const ChannelMetrics lossMetrics = loss.GetMetrics(0.16);
235 Check(lossMetrics.sequenceGaps == 1 && lossMetrics.coalescedSourceRevisions == 0,
236 "delivery loss was confused with source coalescing");
237 Check(Near(loss.SnapshotAt(loss.Depth() - 1).timelineSeconds - loss.SnapshotAt(loss.Depth() - 2).timelineSeconds, 0.10),
238 "delivery loss corrupted source-time motion");
239
240 SnapshotChannel coalesced;
241 coalesced.Configure(SequenceMode::UShort, {});
242 coalesced.Reset(1, -1, -1, false);
243 Check(coalesced.Push(MakeSourceSnapshot(10, 3000, 200), 0.0) == Acceptance::Accepted, "coalesce setup 1");
244 Check(coalesced.Push(MakeSourceSnapshot(11, 3050, 201), 0.05) == Acceptance::Accepted, "coalesce setup 2");
245 Check(coalesced.Push(MakeSourceSnapshot(12, 3100, 204), 0.10) == Acceptance::Accepted, "coalesce sample");
246 const ChannelMetrics coalescedMetrics = coalesced.GetMetrics(0.10);
247 Check(coalescedMetrics.sequenceGaps == 0 && coalescedMetrics.coalescedSourceRevisions == 2,
248 "consecutive delivery source-revision jump was reported as network loss");
249 }
250
251 void TestSupportedSourceCadences()
252 {
253 for (std::uint16_t intervalMs : {static_cast<std::uint16_t>(50), static_cast<std::uint16_t>(100),
254 static_cast<std::uint16_t>(200), static_cast<std::uint16_t>(250), static_cast<std::uint16_t>(5140)})
255 {
256 SnapshotChannel channel;
257 channel.Configure(SequenceMode::UShort, {});
258 channel.Reset(1, -1, -1, false);
259 const double interval = static_cast<double>(intervalMs) / 1000.0;
260 Check(channel.Push(MakeSourceSnapshot(1, 1000, 10, {0, 0, 0}, {0.01, 0, 0}), 0.0) == Acceptance::Accepted,
261 "cadence setup 1 rejected");
262 Check(channel.Push(MakeSourceSnapshot(2, static_cast<std::uint16_t>(1000 + intervalMs), 11,
263 {0.01 * interval, 0, 0}, {0.01, 0, 0}), interval) == Acceptance::Accepted,
264 "cadence setup 2 rejected");
265 Check(channel.Push(MakeSourceSnapshot(3, static_cast<std::uint16_t>(1000 + intervalMs * 2), 12,
266 {0.02 * interval, 0, 0}, {0.01, 0, 0}), interval * 2.0 + 0.03) == Acceptance::Accepted,
267 "supported source cadence rejected");
268 Check(channel.GetMetrics(interval * 2.0).sourceTimed, "supported cadence remained in fallback");
269 Check(Near(channel.SnapshotAt(1).timelineSeconds - channel.SnapshotAt(0).timelineSeconds, interval),
270 "supported source cadence changed timeline interval");
271 }
272 }
273
274 void TestLongSilenceAndImpossibleDeltaReanchor()
275 {
276 SnapshotChannel channel;
277 channel.Configure(SequenceMode::UShort, {});
278 channel.Reset(1, -1, -1, false);
279 Check(channel.Push(MakeSourceSnapshot(1, 1000, 10), 0.0) == Acceptance::Accepted, "silence setup 1");
280 Check(channel.Push(MakeSourceSnapshot(2, 1050, 11), 0.05) == Acceptance::Accepted, "silence setup 2");
281 Check(channel.Push(MakeSourceSnapshot(3, 1100, 12), 0.10) == Acceptance::Accepted, "silence setup 3");
282 Check(channel.Push(MakeSourceSnapshot(4, 1150, 13), 13.0) == Acceptance::Accepted, "long silence packet rejected");
283 Check(channel.Depth() == 1 && Near(channel.SnapshotAt(0).timelineSeconds, 13.0),
284 "long silence did not re-anchor source timeline");
285 Check(channel.Push(MakeSourceSnapshot(5, 1150, 14), 13.05) == Acceptance::Accepted,
286 "zero source delta packet rejected as delivery");
287 Check(channel.Depth() == 1 && Near(channel.SnapshotAt(0).timelineSeconds, 13.05),
288 "advanced revision with zero source delta did not re-anchor");
289 }
290
291 void TestOldServerFallbackTransition()
292 {
293 SnapshotChannel channel;
294 channel.Configure(SequenceMode::UShort, {});
295 channel.Reset(1, -1, -1, false);
296 Check(channel.Push(MakeSourceSnapshot(1, 0, 0), 0.0) == Acceptance::Accepted, "old server packet 1");
297 Check(channel.Push(MakeSourceSnapshot(2, 0, 0), 0.05) == Acceptance::Accepted, "old server packet 2");
298 Check(!channel.GetMetrics(0.05).sourceTimed, "zero padding activated source timing");
299 Check(channel.Push(MakeSourceSnapshot(3, 4000, 80), 0.10) == Acceptance::Accepted, "transition packet 1");
300 Check(!channel.GetMetrics(0.10).sourceTimed, "first nonzero transition packet activated source timing");
301 Check(channel.Push(MakeSourceSnapshot(4, 4050, 81), 0.17) == Acceptance::Accepted, "transition packet 2");
302 Check(channel.GetMetrics(0.17).sourceTimed && channel.Depth() == 1,
303 "valid source timing did not activate with a clean re-anchor");
304 }
305
306 void TestWeaponSourceTimingAtSixtyFramesPerSecond()
307 {
308 SnapshotChannel channel;
309 ChannelConfig config;
311 channel.Configure(SequenceMode::Modulo255, config);
312 channel.Reset(9, -1, -1, false);
313 for (std::uint16_t sequence = 0; sequence < 12; ++sequence)
314 {
315 MotionSnapshot snapshot = MakeSourceSnapshot(sequence, static_cast<std::uint16_t>(1000 + sequence * 50), 0,
316 {sequence * 0.05, 0, 0}, {1, 0, 0}, -1, -1, 9);
317 snapshot.expectedIntervalSeconds = 0.05;
318 const double jitter = sequence % 3 == 0 ? 0.012 : sequence % 3 == 1 ? -0.006 : 0.003;
319 Check(channel.Push(snapshot, sequence * 0.05 + jitter + 0.02) == Acceptance::Accepted,
320 "20 Hz weapon source sample rejected");
321 }
322 Check(channel.GetMetrics(0.60).sourceTimed, "weapon source timing did not activate after two packets");
323 double previousPosition = -1.0;
324 for (int frame = 0; frame < 18; ++frame)
325 {
326 const PresentationState state = channel.Sample(0.25 + frame / 60.0, 1.0 / 60.0);
327 Check(state.valid && state.position.x >= previousPosition,
328 "20 Hz weapon presentation moved backward at 60 FPS");
329 if (previousPosition >= 0.0)
330 Check(state.position.x - previousPosition <= 1.0 / 60.0 + 1.0e-5,
331 "weapon presentation advanced more than one render frame");
332 previousPosition = state.position.x;
333 }
334 for (std::size_t index = 1; index < channel.Depth(); ++index)
335 Check(channel.SnapshotAt(index).timelineSeconds > channel.SnapshotAt(index - 1).timelineSeconds,
336 "weapon source timing created a zero-duration interpolation segment");
337
338 const Vec3 authoritative = WeaponFrameEndpoint({1, 2, 3}, {6, 0, 0}, 1.0 / 60.0, true);
339 const Vec3 legacy = WeaponFrameEndpoint({1, 2, 3}, {6, 0, 0}, 1.0 / 60.0, false);
340 Check(Near(authoritative.x, 1.0), "authoritative weapon presentation was advanced a second time");
341 Check(Near(legacy.x, 1.1), "legacy weapon frame integration was removed");
342 }
343
344 void TestUShortWraparound()
345 {
346 Check(IsNewerUShort(0, 65535), "ushort wrap 65535->0 must be newer");
347 Check(IsNewerUShort(32767, 0), "ushort half-range forward delta 32767 must be newer");
348 Check(!IsNewerUShort(32768, 0), "ushort half-range delta 32768 is ambiguous/stale");
349 Check(!IsNewerUShort(22, 22), "ushort duplicate must be rejected");
350 Check(!IsNewerUShort(65535, 0), "pre-wrap packet after sequence zero must be stale");
351 }
352
353 void TestWeaponModulo255Wraparound()
354 {
355 Check(IsNewerModulo255(0, 254), "weapon 254->0 wrap must be newer");
356 Check(IsNewerModulo255(127, 0), "weapon delta 127 must be newer");
357 Check(!IsNewerModulo255(128, 0), "weapon delta 128 must be stale");
358 Check(!IsNewerModulo255(0, 0), "weapon duplicate must be rejected");
359 Check(!IsNewerModulo255(255, 254), "weapon sequence 255 is never valid");
360 }
361
362 void TestLossReorderingDuplicatesAndReliableStale()
363 {
364 SnapshotChannel channel;
365 channel.Configure(SequenceMode::UShort, {});
366 channel.Reset(1, -1, -1, false);
367 Check(channel.Push(MakeSnapshot(100), 1.0) == Acceptance::Accepted, "first sequence rejected");
368 Check(channel.Push(MakeSnapshot(103), 1.25) == Acceptance::Accepted, "loss jump rejected");
369 Check(channel.Push(MakeSnapshot(102), 1.30) == Acceptance::OutOfOrder, "reordered packet accepted");
370 Check(channel.Push(MakeSnapshot(103), 1.31) == Acceptance::Duplicate, "duplicate packet accepted");
371 MotionSnapshot reliableFinal = MakeSnapshot(101);
372 reliableFinal.finalSample = true;
373 Check(channel.Push(reliableFinal, 1.40) == Acceptance::OutOfOrder,
374 "late reliable final packet superseded newer unreliable motion");
375 const ChannelMetrics metrics = channel.GetMetrics(1.4);
376 Check(metrics.sequenceGaps == 2, "sequence gap count is wrong");
377 Check(metrics.duplicateCount == 1 && metrics.outOfOrderCount == 2, "drop counters are wrong");
378 }
379
380 void TestBurstAfterStall()
381 {
382 SnapshotChannel channel;
383 channel.Configure(SequenceMode::UShort, {});
384 channel.Reset(1, -1, -1, false);
385 Check(channel.Push(MakeSnapshot(0, {0, 0, 0}, {1, 0, 0}), 0.0) == Acceptance::Accepted, "burst setup 0");
386 Check(channel.Push(MakeSnapshot(1, {0.25, 0, 0}, {1, 0, 0}), 0.25) == Acceptance::Accepted, "burst setup 1");
387 Check(channel.Push(MakeSnapshot(2, {2.0, 0, 0}, {1, 0, 0}), 2.0) == Acceptance::Accepted, "stall recovery");
388 Check(channel.Push(MakeSnapshot(3, {2.25, 0, 0}, {1, 0, 0}), 2.0) == Acceptance::Accepted, "burst packet 1");
389 Check(channel.Push(MakeSnapshot(4, {2.50, 0, 0}, {1, 0, 0}), 2.0) == Acceptance::Accepted, "burst packet 2");
390 for (std::size_t index = 1; index < channel.Depth(); ++index)
391 Check(channel.SnapshotAt(index).timelineSeconds > channel.SnapshotAt(index - 1).timelineSeconds,
392 "burst created a zero-duration timeline segment");
393 const PresentationState state = channel.Sample(2.3, 1.0 / 60.0);
394 Check(state.valid && std::isfinite(state.position.x), "burst recovery produced invalid presentation");
395 Check(state.position.x >= -0.1 && state.position.x <= 2.7, "burst recovery visibly overshot snapshots");
396 }
397
398 void TestSlotReuseAndDelayedOldTelemetry()
399 {
400 SnapshotSystem system;
401 system.ResetVehicle(5, 1001, -1, -1, true);
402 Check(system.PushVehicle(5, MakeSnapshot(0, {}, {}, -1, -1, 1001), 1.0) == Acceptance::Accepted,
403 "new slot generation did not accept sequence zero");
404 Check(system.PushVehicle(5, MakeSnapshot(500, {}, {}, -1, -1, 1001), 1.25) == Acceptance::Accepted,
405 "large valid forward sequence rejected");
406
407 // A type-9 full update reassigns this scanner slot and resets all history.
408 system.ResetVehicle(5, 2002, -1, -1, true);
409 Check(system.PushVehicle(5, MakeSnapshot(501, {}, {}, -1, -1, 2002), 1.30) == Acceptance::GenerationMismatch,
410 "delayed telemetry from the previous slot occupant passed bootstrap quarantine");
411 Check(system.PushVehicle(5, MakeSnapshot(0, {10, 0, 0}, {}, -1, -1, 2002), 1.31) == Acceptance::Accepted,
412 "new occupant sequence zero was rejected");
413 const ChannelMetrics metrics = system.VehicleMetrics(5, 1.31);
414 Check(metrics.identity == 2002 && metrics.snapshotDepth == 1 && metrics.lastAcceptedSequence == 0,
415 "slot reuse retained old identity/history");
416 }
417
418 void TestDockingUndockingAndParentChanges()
419 {
420 SnapshotSystem system;
421 system.ResetVehicle(7, 77, 0, 3, true);
422 Check(system.PushVehicle(7, MakeSnapshot(0, {0.01, 0.02, 0.03}, {}, 0, 3, 77), 2.0) == Acceptance::Accepted,
423 "docked child snapshot rejected");
424 ChannelMetrics metrics = system.VehicleMetrics(7, 2.0);
425 Check(metrics.reference == 0 && metrics.parentSlot == 3, "docked parent metadata lost");
426
427 const std::uint32_t generation = metrics.generation;
428 system.ResetVehicle(7, 77, -1, -1, false);
429 metrics = system.VehicleMetrics(7, 2.1);
430 Check(metrics.generation == generation + 1 && metrics.snapshotDepth == 0,
431 "undocking did not hard-reset snapshot history");
432 Check(system.PushVehicle(7, MakeSnapshot(44000, {100, 0, 0}, {}, -1, -1, 77), 2.2) == Acceptance::Accepted,
433 "reference-only reset did not establish a fresh sequence baseline");
434
435 system.ResetVehicle(7, 77, 0, 9, false);
436 metrics = system.VehicleMetrics(7, 2.3);
437 Check(metrics.parentSlot == 9 && metrics.snapshotDepth == 0, "parent-slot change retained old frame history");
438 }
439
440 void TestQuaternionValidationAndInterpolation()
441 {
442 SnapshotChannel channel;
443 channel.Configure(SequenceMode::UShort, {});
444 channel.Reset(1, -1, -1, false);
445 MotionSnapshot invalid = MakeSnapshot(0);
446 invalid.orientation = {0, 0, 0, 0};
447 Check(channel.Push(invalid, 0.0) == Acceptance::Invalid, "zero quaternion accepted");
448
449 MotionSnapshot first = MakeSnapshot(0);
450 first.orientation = {0, 0, 0, 1};
451 MotionSnapshot second = MakeSnapshot(1);
452 second.orientation = {0, 1, 0, 0};
453 Check(channel.Push(first, 0.0) == Acceptance::Accepted, "valid quaternion rejected");
454 Check(channel.Push(second, 1.0) == Acceptance::Accepted, "second valid quaternion rejected");
455 const Quaternion middle = Slerp(first.orientation, second.orientation, 0.5);
456 Check(Near(QuaternionLength(middle), 1.0, 1.0e-9), "SLERP did not return a unit quaternion");
457 const Quaternion extrapolated = IntegrateAngularVelocity(first.orientation, {0, TestPi / 2.0, 0}, 1.0);
458 Check(Near(QuaternionLength(extrapolated), 1.0, 1.0e-9), "orientation extrapolation lost normalization");
459 }
460
461 void TestOneHertzPlaybackUsesBufferedKeyframes()
462 {
463 SnapshotChannel channel;
464 channel.Configure(SequenceMode::UShort, {});
465 channel.Reset(41, -1, -1, false);
466
467 MotionSnapshot bootstrap = MakeSourceSnapshot(10, 1000, 10, {-1, 0, 0}, {1, 0, 0}, -1, -1, 41);
468 bootstrap.expectedIntervalSeconds = 1.0;
469 Check(channel.Push(bootstrap, 0.0) == Acceptance::Accepted,
470 "1 Hz playback bootstrap rejected");
471
472 MotionSnapshot first = MakeSourceSnapshot(11, 2000, 11, {0, 0, 0}, {1, 0, 0}, -1, -1, 41);
473 first.expectedIntervalSeconds = 1.0;
474 first.orientation = {0, 0, 0, 1};
475 Check(channel.Push(first, 1.0) == Acceptance::Accepted,
476 "1 Hz playback first keyframe rejected");
477
478 MotionSnapshot second = MakeSourceSnapshot(12, 3000, 12, {1, 0, 0}, {1, 0, 0}, -1, -1, 41);
479 second.expectedIntervalSeconds = 1.0;
480 second.orientation = {0, 1, 0, 0};
481 Check(channel.Push(second, 2.0) == Acceptance::Accepted,
482 "1 Hz playback second keyframe rejected");
483
484 const ChannelMetrics metrics = channel.GetMetrics(2.0);
485 Check(Near(metrics.interpolationDelaySeconds, 1.10, 1.0e-6),
486 "1 Hz playback did not retain a complete keyframe interval");
487
488 const PresentationState middle = channel.Sample(2.60, 1.0 / 60.0);
489 Check(middle.valid && Near(middle.position.x, 0.50, 1.0e-5),
490 "1 Hz playback position was extrapolated instead of interpolated");
491 Check(Near(middle.extrapolationSeconds, 0.0),
492 "1 Hz playback exhausted its interpolation buffer");
493 Check(Near(middle.orientation.y, std::sqrt(0.5), 1.0e-5) &&
494 Near(middle.orientation.w, std::sqrt(0.5), 1.0e-5),
495 "1 Hz playback orientation did not SLERP between keyframes");
496
497 const PresentationState beforeArrival = channel.Sample(2.99, 1.0 / 60.0);
498 MotionSnapshot third = MakeSourceSnapshot(13, 4000, 13, {2, 0, 0}, {1, 0, 0}, -1, -1, 41);
499 third.expectedIntervalSeconds = 1.0;
500 third.orientation = {0, 1, 0, 0};
501 Check(channel.Push(third, 3.0) == Acceptance::Accepted,
502 "1 Hz playback third keyframe rejected");
503 const PresentationState afterArrival = channel.Sample(3.0, 1.0 / 60.0);
504 Check(afterArrival.valid && std::abs(afterArrival.position.x - beforeArrival.position.x) <= 0.011,
505 "1 Hz playback visibly jumped when the next keyframe arrived");
506 }
507
508 void TestMalformedPayloadAndNumerics()
509 {
510 Check(HasExactPayloadLength(69, 69), "exact payload length rejected");
511 Check(!HasExactPayloadLength(68, 69) && !HasExactPayloadLength(70, 69), "malformed payload length accepted");
512 SnapshotSystem system;
513 Check(system.PushVehicle(EntityCapacity, MakeSnapshot(0), 0.0) == Acceptance::Invalid,
514 "impossible scanner slot accepted");
515
516 SnapshotChannel channel;
517 channel.Configure(SequenceMode::UShort, {});
518 channel.Reset(1, -1, -1, false);
519 MotionSnapshot nan = MakeSnapshot(0);
520 nan.position.x = std::numeric_limits<double>::quiet_NaN();
521 Check(channel.Push(nan, 0.0) == Acceptance::Invalid, "NaN accepted");
522 MotionSnapshot infinity = MakeSnapshot(0);
523 infinity.velocity.z = std::numeric_limits<double>::infinity();
524 Check(channel.Push(infinity, 0.1) == Acceptance::Invalid, "infinity accepted");
525 Check(channel.GetMetrics(0.1).invalidCount == 2, "invalid packet metrics are wrong");
526 }
527
528 void TestCadencesAndOrbitalRendezvous()
529 {
530 for (double interval : {0.25, 0.10, 0.05})
531 {
532 SnapshotChannel channel;
533 channel.Configure(SequenceMode::UShort, {});
534 channel.Reset(1, -1, -1, false);
535 for (std::uint16_t sequence = 0; sequence < 12; ++sequence)
536 {
537 const double time = sequence * interval;
538 MotionSnapshot orbital = MakeSnapshot(sequence, {1000.0 + 0.05 * time, 0, 0}, {5, 0, 0});
539 orbital.positionDerivative = {0.05, 0, 0};
540 orbital.hasPositionDerivative = true;
541 Check(channel.Push(orbital, time) ==
542 Acceptance::Accepted, "future cadence snapshot rejected");
543 }
544 const ChannelMetrics metrics = channel.GetMetrics(12 * interval);
545 Check(std::abs(metrics.measuredIntervalSeconds - interval) < 0.01,
546 "EWMA did not track 4/10/20 Hz cadence");
547 Check(std::abs(metrics.incomingPacketsPerSecond - 1.0 / interval) < 0.1,
548 "incoming packet-rate metric did not track 4/10/20 Hz cadence");
549 const PresentationState state = channel.Sample(12 * interval, 1.0 / 60.0);
550 Check(state.valid && std::abs(state.velocity.x - 5.0) < 0.05,
551 "5 km/s rendezvous corrupted low-relative-speed velocity");
552 Check(std::abs(state.positionDerivative.x - 0.05) < 0.01,
553 "orbital rendezvous used inertial velocity as rotating-frame position derivative");
554 }
555 }
556
557 void TestHighRelativeSpeedCrossing()
558 {
559 SnapshotChannel channel;
560 channel.Configure(SequenceMode::UShort, {});
561 channel.Reset(1, -1, -1, false);
562 Check(channel.Push(MakeSnapshot(0, {-10, 0, 0}, {20, 0, 0}), 0.0) == Acceptance::Accepted, "crossing 0");
563 Check(channel.Push(MakeSnapshot(1, {-5, 0, 0}, {20, 0, 0}), 0.25) == Acceptance::Accepted, "crossing 1");
564 Check(channel.Push(MakeSnapshot(2, {0, 0, 0}, {20, 0, 0}), 0.50) == Acceptance::Accepted, "crossing 2");
565 const PresentationState first = channel.Sample(0.75, 1.0 / 60.0);
566 const PresentationState second = channel.Sample(1.00, 1.0 / 60.0);
567 Check(first.valid && second.valid && second.position.x > first.position.x,
568 "high-relative-speed crossing reversed or oscillated");
569 Check(std::abs(second.position.x) < 6.0, "high-relative-speed crossing overshot excessively");
570 }
571
572 void TestGuidedMissileTurningBetweenSparseSnapshots()
573 {
574 ChannelConfig config;
576 SnapshotChannel channel;
577 channel.Configure(SequenceMode::Modulo255, config);
578 channel.Reset(9, -1, -1, false);
579 Check(channel.Push(MakeSnapshot(0, {0, 0, 0}, {1, 0, 0}, -1, -1, 9), 0.0) == Acceptance::Accepted,
580 "missile 0");
581 Check(channel.Push(MakeSnapshot(1, {0.4, 0.1, 0}, {0.6, 0.6, 0}, -1, -1, 9), 0.5) == Acceptance::Accepted,
582 "missile 1");
583 Check(channel.Push(MakeSnapshot(2, {0.6, 0.4, 0}, {0, 1, 0}, -1, -1, 9), 1.0) == Acceptance::Accepted,
584 "missile 2");
585 const PresentationState turn = channel.Sample(1.35, 1.0 / 60.0);
586 Check(turn.valid && std::isfinite(turn.position.x) && std::isfinite(turn.position.y),
587 "guided missile interpolation produced invalid state");
588 Check(turn.velocity.y > 0.0 && turn.position.y >= 0.0,
589 "guided missile did not turn between sparse source snapshots");
590 }
591
592 void TestTwentyHertzUploadCadenceAndCoalescing()
593 {
595 int sends = 0;
596 for (int frame = 0; frame < 600; ++frame)
597 if (upload.Advance(1.0 / 60.0))
598 ++sends;
599 Check(sends == 200, "20 Hz upload gate drifted over ten seconds");
600
601 upload.Reset();
602 Check(upload.Advance(2.0), "stall did not produce one current upload");
603 Check(!upload.Advance(0.001), "stall produced a catch-up upload burst");
604 Check(upload.AccumulatedSeconds() < ClientUploadIntervalSeconds,
605 "stall retained multiple overdue upload intervals");
606
608 int presenceUpdates = 0;
609 for (int frame = 0; frame < 1800; ++frame)
610 if (presence.Advance(1.0 / 60.0))
611 ++presenceUpdates;
612 Check(presenceUpdates == 2, "Discord presence cadence is coupled to upload frequency");
613 }
614
615 void TestUploadDiagnostics()
616 {
617 UploadDiagnostics diagnostics;
618 for (int packet = 0; packet <= 10; ++packet)
619 diagnostics.RecordPacket(packet * ClientUploadIntervalSeconds);
620 const UploadMetrics metrics = diagnostics.GetMetrics(0.60);
621 Check(Near(metrics.packetsPerSecond, 20.0), "upload diagnostics did not report 20 Hz");
622 Check(metrics.totalPackets == 11, "upload diagnostics packet total is wrong");
623 Check(Near(metrics.ageOfLastPacketSeconds, 0.10), "upload diagnostics packet age is wrong");
624 }
625
626 void TestContainedVehicleBufferingPolicy()
627 {
629 "REF_INANOTHER cargo placement entered the snapshot buffer");
631 "free-flight telemetry unexpectedly bypassed the snapshot buffer");
633 "docked telemetry unexpectedly bypassed the snapshot buffer");
634 }
635}
636
637int main()
638{
639 try
640 {
641 int testGroups = 0;
642 const auto Run = [&testGroups](auto test)
643 {
644 test();
645 ++testGroups;
646 };
647 Run(TestSteamPresence);
648 Run(TestDiscordActivityPayload);
649 Run(TestCrashBreadcrumbs);
650 Run(TestPacketLayoutsAndTimestampRollover);
651 Run(TestUShortWraparound);
652 Run(TestWeaponModulo255Wraparound);
653 Run(TestJitterDoesNotEnterSourceTimeline);
654 Run(TestDeliveryLossAndSourceRevisionCoalescing);
655 Run(TestSupportedSourceCadences);
656 Run(TestLongSilenceAndImpossibleDeltaReanchor);
657 Run(TestOldServerFallbackTransition);
658 Run(TestWeaponSourceTimingAtSixtyFramesPerSecond);
659 Run(TestLossReorderingDuplicatesAndReliableStale);
660 Run(TestBurstAfterStall);
661 Run(TestSlotReuseAndDelayedOldTelemetry);
662 Run(TestDockingUndockingAndParentChanges);
663 Run(TestQuaternionValidationAndInterpolation);
664 Run(TestOneHertzPlaybackUsesBufferedKeyframes);
665 Run(TestMalformedPayloadAndNumerics);
666 Run(TestCadencesAndOrbitalRendezvous);
667 Run(TestHighRelativeSpeedCrossing);
668 Run(TestGuidedMissileTurningBetweenSparseSnapshots);
669 Run(TestTwentyHertzUploadCadenceAndCoalescing);
670 Run(TestUploadDiagnostics);
671 Run(TestContainedVehicleBufferingPolicy);
672 std::cout << "TelemetrySnapshotTests: " << testGroups << " deterministic test groups passed\n";
673 return EXIT_SUCCESS;
674 }
675 catch (const std::exception& exception)
676 {
677 std::cerr << "TelemetrySnapshotTests FAILED: " << exception.what() << '\n';
678 return EXIT_FAILURE;
679 }
680}
std::size_t Count() const
void Add(const char *message)
void FormatPacket(char(&destination)[Size]) const
const char * Recent(std::size_t index) const
void Configure(SequenceMode sequenceMode, const ChannelConfig &config)
Acceptance Push(MotionSnapshot snapshot, double receiptSeconds)
ChannelMetrics GetMetrics(double nowSeconds) const
const MotionSnapshot & SnapshotAt(std::size_t logicalIndex) const
void Reset(int identity, int reference, int parentSlot, bool requireLowBootstrapSequence)
PresentationState Sample(double nowSeconds, double elapsedSeconds)
ChannelMetrics VehicleMetrics(std::size_t slot, double nowSeconds) const
void ResetVehicle(std::size_t slot, int identity, int reference, int parentSlot, bool identityChanged)
Acceptance PushVehicle(std::size_t slot, MotionSnapshot snapshot, double receiptSeconds)
UploadMetrics GetMetrics(double nowSeconds) const
bool Near(const Body &b, const Triangle &t, double extra)
Definition RigidProp.h:141
Activity BuildActivity(const Fields &fields)
bool PublishPresence(Friends &friends, const PresencePayload &payload)
PresencePayload BuildPresence(const char *details, const char *state, const char *screen=nullptr)
Quaternion Slerp(const Quaternion &aValue, const Quaternion &bValue, double amount)
Quaternion IntegrateAngularVelocity(const Quaternion &orientation, const Vec3 &angularVelocity, double seconds)
bool HasExactPayloadLength(std::size_t actualBytes, std::size_t expectedBytes)
double QuaternionLength(const Quaternion &value)
constexpr double ClientUploadIntervalSeconds
constexpr std::size_t EntityCapacity
constexpr double DiscordPresenceIntervalSeconds
bool IsNewerModulo255(std::uint8_t incoming, std::uint8_t previous)
std::uint16_t SourceTimeDeltaMilliseconds(std::uint16_t incoming, std::uint16_t previous)
bool IsNewerUShort(std::uint16_t incoming, std::uint16_t previous)
Vec3 WeaponFrameEndpoint(const Vec3 &presentationPosition, const Vec3 &velocity, double elapsedSeconds, bool hasAuthoritativePresentation)
bool ShouldBufferVehicleReference(int reference)