Skip to content

Commit e4e1954

Browse files
jakuserprex
authored andcommitted
Run Crowd Control effects on the game thread and prevent negative ammo counts
Queue network payloads for game-thread processing, retry timed-effect cleanup after disabling, and clamp negative ammo counts before drawing. Report commit hash to Crowd Control
1 parent e2a6b59 commit e4e1954

3 files changed

Lines changed: 231 additions & 52 deletions

File tree

‎soh/soh/Enhancements/game-interactor/GameInteractor_RawAction.cpp‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
#include <algorithm>
12
#include <spdlog/spdlog.h>
23
#include <libultraship/bridge/consolevariablebridge.h>
34

@@ -416,7 +417,8 @@ void GameInteractor::RawAction::EmulateRandomButtonPress(uint32_t chancePercenta
416417
}
417418

418419
void GameInteractor::RawAction::AddOrTakeAmmo(int16_t amount, int16_t item) {
419-
Inventory_ChangeAmmo(item, amount);
420+
// Don't take more than the player has, negative counts crash when drawn
421+
Inventory_ChangeAmmo(item, std::max<int16_t>(amount, -AMMO(item)));
420422
}
421423

422424
void GameInteractor::RawAction::SetRandomWind(bool active) {

‎soh/soh/Network/CrowdControl/CrowdControl.cpp‎

Lines changed: 199 additions & 45 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@
88

99
extern "C" {
1010
#include <z64.h>
11+
#include "variables.h"
1112
extern PlayState* gPlayState;
1213
}
1314

@@ -18,19 +19,131 @@ void CrowdControl::Enable() {
1819
}
1920

2021
void CrowdControl::Disable() {
22+
// Joins the network thread, so after this only the game thread touches CC state
2123
Network::Disable();
24+
25+
ClearPayloadQueues();
26+
27+
// Timed effects stop ticking once disabled, so undo them rather than leaving them stuck on. Removal can be
28+
// refused (e.g. during a textbox or cutscene), so they're moved to a pending list that the frame hook keeps
29+
// retrying until each one is actually removed. They're kept apart from activeEffects so re-enabling doesn't
30+
// resume them against the new CC session.
31+
for (auto& effect : activeEffects) {
32+
effectsPendingRemoval.push_back(std::move(effect));
33+
}
34+
activeEffects.clear();
35+
SPDLOG_INFO("[CrowdControl] Disabled, removing {} timed effect(s)", effectsPendingRemoval.size());
36+
ProcessPendingRemovals();
37+
2238
ShipInit::Init(CVAR_REMOTE_CROWD_CONTROL("Enabled"));
2339
}
2440

25-
void CrowdControl::OnConnected() {
26-
ccThreadProcess = std::thread(&CrowdControl::ProcessActiveEffects, this);
41+
// Returns true once the effect no longer needs removing (removed, or can never be removed). Returns false when
42+
// removal is only temporarily refused (gameplay paused, textbox, cutscene, no save loaded), so the caller should
43+
// retry later. Ignoring that result would drop the effect while its state stays applied for good.
44+
bool CrowdControl::TryRemoveEffect(Effect* effect) {
45+
auto* removable = dynamic_cast<RemovableGameInteractionEffect*>(effect->giEffect.get());
46+
if (removable == nullptr) {
47+
return true;
48+
}
49+
50+
GameInteractionEffectQueryResult result = GameInteractor::RemoveEffect(*removable);
51+
if (result == GameInteractionEffectQueryResult::TemporarilyNotPossible) {
52+
return false;
53+
}
54+
if (result != GameInteractionEffectQueryResult::Possible) {
55+
SPDLOG_WARN("[CrowdControl] Timed effect {} could not be removed", effect->id);
56+
}
57+
return true;
58+
}
59+
60+
void CrowdControl::ProcessPendingRemovals() {
61+
auto it = effectsPendingRemoval.begin();
62+
while (it != effectsPendingRemoval.end()) {
63+
if (TryRemoveEffect(it->get())) {
64+
it = effectsPendingRemoval.erase(it);
65+
} else {
66+
it++;
67+
}
68+
}
69+
}
70+
71+
bool CrowdControl::NeedsFrameUpdate() {
72+
return isEnabled || !effectsPendingRemoval.empty();
2773
}
2874

29-
void CrowdControl::OnDisconnected() {
30-
ccThreadProcess.join();
75+
// Only cleared on a manual disable. Connection hiccups keep both queues, so effects already received still run
76+
// and any status updates emitted while disconnected are sent once the connection comes back.
77+
void CrowdControl::ClearPayloadQueues() {
78+
{
79+
std::lock_guard<std::mutex> lock(incomingPayloadQueueMutex);
80+
std::queue<nlohmann::json>().swap(incomingPayloadQueue);
81+
}
82+
{
83+
std::lock_guard<std::mutex> lock(outgoingPayloadQueueMutex);
84+
std::queue<nlohmann::json>().swap(outgoingPayloadQueue);
85+
}
3186
}
3287

88+
// Effects touch game state (spawning actors, inventory, player), so they must only ever run on the game
89+
// thread. The network thread queues incoming payloads here, and they're executed in OnGameFrameUpdate.
3390
void CrowdControl::OnIncomingJson(nlohmann::json payload) {
91+
// Version requests don't touch game state, so answer them right away instead of queuing them as effects
92+
if (payload.contains("type") && payload["type"].is_number_integer() &&
93+
payload["type"].get<int>() == ResponseType::Version) {
94+
SendVersion(payload.value("id", 0u));
95+
return;
96+
}
97+
98+
std::lock_guard<std::mutex> lock(incomingPayloadQueueMutex);
99+
incomingPayloadQueue.push(payload);
100+
}
101+
102+
// Announce our version on every connection instead of waiting to be asked. The pack does request it when the
103+
// connection opens, but that request can be lost if it arrives before the pack has finished registering this
104+
// client, and it isn't retried. An unsolicited response with id 0 is accepted all the same.
105+
void CrowdControl::OnConnected() {
106+
SendVersion(0);
107+
}
108+
109+
void CrowdControl::OnGameFrameUpdate() {
110+
// Effects left over from a disable are retried every frame until they've all been removed.
111+
ProcessPendingRemovals();
112+
113+
if (!isEnabled) {
114+
return;
115+
}
116+
117+
// Copy all queued payloads while holding the lock, then process them after releasing
118+
std::queue<nlohmann::json> payloadsToProcess;
119+
{
120+
std::lock_guard<std::mutex> lock(incomingPayloadQueueMutex);
121+
payloadsToProcess.swap(incomingPayloadQueue);
122+
}
123+
124+
while (!payloadsToProcess.empty()) {
125+
try {
126+
ProcessIncomingPayload(payloadsToProcess.front());
127+
} catch (const std::exception& e) {
128+
SPDLOG_ERROR("[CrowdControl] Exception handling incoming JSON: {}", e.what());
129+
} catch (...) { SPDLOG_ERROR("[CrowdControl] Unknown exception handling incoming JSON"); }
130+
payloadsToProcess.pop();
131+
}
132+
133+
// Timed effects are ticked once per second. Advance by exactly one second so frame timing doesn't make
134+
// effects run longer than CC's overlay timer, but resync if we've fallen far behind (e.g. a long stall)
135+
// instead of firing a burst of catch-up ticks.
136+
auto now = std::chrono::steady_clock::now();
137+
if (now - lastActiveEffectsTick >= std::chrono::seconds(1)) {
138+
lastActiveEffectsTick += std::chrono::seconds(1);
139+
if (now - lastActiveEffectsTick >= std::chrono::seconds(1)) {
140+
lastActiveEffectsTick = now;
141+
}
142+
ProcessActiveEffects();
143+
}
144+
}
145+
146+
void CrowdControl::ProcessIncomingPayload(nlohmann::json payload) {
34147
std::unique_ptr<Effect> incomingEffect = ParseMessage(payload);
35148
if (!incomingEffect) {
36149
return;
@@ -60,65 +173,78 @@ void CrowdControl::OnIncomingJson(nlohmann::json payload) {
60173
return;
61174
}
62175

63-
activeEffectsMutex.lock();
64176
activeEffects.push_back(std::move(incomingEffect));
65-
activeEffectsMutex.unlock();
66177
}
67178
}
68179
}
69180

70181
void CrowdControl::ProcessActiveEffects() {
71-
while (isEnabled) {
72-
// We only want to send events when status changes, on start we send Success.
73-
// If it fails at some point, we send Pause, and when it starts to succeed again we send Success.
74-
// CC uses this to pause the timer on the overlay.
75-
activeEffectsMutex.lock();
76-
auto it = activeEffects.begin();
77-
78-
while (it != activeEffects.end()) {
79-
Effect* effect = it->get();
80-
EffectResult result = CrowdControl::ExecuteEffect(effect);
81-
82-
if (result == EffectResult::Success) {
83-
// If time remaining has reached 0, we have finished the effect.
84-
if (effect->timeRemaining <= 0) {
85-
GameInteractor::RemoveEffect(
86-
*dynamic_cast<RemovableGameInteractionEffect*>(effect->giEffect.get()));
182+
// We only want to send events when status changes, on start we send Success.
183+
// If it fails at some point, we send Pause, and when it starts to succeed again we send Success.
184+
// CC uses this to pause the timer on the overlay.
185+
auto it = activeEffects.begin();
186+
187+
while (it != activeEffects.end()) {
188+
Effect* effect = it->get();
189+
EffectResult result = CrowdControl::ExecuteEffect(effect);
190+
191+
if (result == EffectResult::Success) {
192+
// If time remaining has reached 0, we have finished the effect.
193+
// If removal is temporarily refused, keep it and retry on the next tick.
194+
if (effect->timeRemaining <= 0) {
195+
if (TryRemoveEffect(effect)) {
87196
it = activeEffects.erase(it);
88197
} else {
89-
// If we have a success after previously being paused, tell CC to resume timer.
90-
if (effect->isPaused) {
91-
effect->isPaused = false;
92-
EmitMessage(effect->id, effect->timeRemaining, EffectResult::Resumed);
93-
// If not paused before, subtract time from the timer and send a Success event if
94-
// the result is different from the last time this was ran.
95-
// Timed events are put on a thread that runs once per second.
96-
} else {
97-
effect->timeRemaining -= 1000;
98-
if (result != effect->lastExecutionResult) {
99-
effect->lastExecutionResult = result;
100-
EmitMessage(effect->id, effect->timeRemaining, EffectResult::Success);
101-
}
102-
}
103198
it++;
104199
}
105-
} else { // Timed effects only do Success or Retry
106-
if (!effect->isPaused && effect->timeRemaining > 0) {
107-
effect->isPaused = true;
108-
EmitMessage(effect->id, effect->timeRemaining, EffectResult::Paused);
200+
} else {
201+
// If we have a success after previously being paused, tell CC to resume timer.
202+
if (effect->isPaused) {
203+
effect->isPaused = false;
204+
EmitMessage(effect->id, effect->timeRemaining, EffectResult::Resumed);
205+
// If not paused before, subtract time from the timer and send a Success event if
206+
// the result is different from the last time this was ran.
207+
// Timed events are ticked once per second.
208+
} else {
209+
effect->timeRemaining -= 1000;
210+
if (result != effect->lastExecutionResult) {
211+
effect->lastExecutionResult = result;
212+
EmitMessage(effect->id, effect->timeRemaining, EffectResult::Success);
213+
}
109214
}
110215
it++;
111216
}
217+
} else { // Timed effects only do Success or Retry
218+
if (!effect->isPaused && effect->timeRemaining > 0) {
219+
effect->isPaused = true;
220+
EmitMessage(effect->id, effect->timeRemaining, EffectResult::Paused);
221+
}
222+
it++;
112223
}
224+
}
225+
}
113226

114-
activeEffectsMutex.unlock();
115-
std::this_thread::sleep_for(std::chrono::seconds(1));
227+
void CrowdControl::ProcessOutgoingPackets() {
228+
// Copy all queued payloads while holding the lock, then send them after releasing
229+
std::queue<nlohmann::json> payloadsToSend;
230+
{
231+
std::lock_guard<std::mutex> lock(outgoingPayloadQueueMutex);
232+
payloadsToSend.swap(outgoingPayloadQueue);
116233
}
117234

118-
SPDLOG_TRACE("[CrowdControl] Ending Process thread...");
235+
while (!payloadsToSend.empty()) {
236+
SendJsonToRemote(payloadsToSend.front());
237+
payloadsToSend.pop();
238+
}
119239
}
120240

121241
void CrowdControl::EmitMessage(uint32_t eventId, long timeRemaining, EffectResult status) {
242+
// Queued even while disconnected, so CC catches up on effect status after a connection hiccup.
243+
// A manual disable clears the queue.
244+
if (!isEnabled) {
245+
return;
246+
}
247+
122248
nlohmann::json payload;
123249

124250
payload["id"] = eventId;
@@ -128,7 +254,27 @@ void CrowdControl::EmitMessage(uint32_t eventId, long timeRemaining, EffectResul
128254

129255
SPDLOG_INFO("[CrowdControl] Sending payload:\n{}", payload.dump());
130256

131-
SendJsonToRemote(payload);
257+
// Queue the payload to be sent on the network thread
258+
std::lock_guard<std::mutex> lock(outgoingPayloadQueueMutex);
259+
outgoingPayloadQueue.push(payload);
260+
}
261+
262+
// Reports this build to CC so the pack can require a minimum version. Team and commit hash tell forks apart.
263+
// The client only reads "version", extra fields are ignored by older clients.
264+
void CrowdControl::SendVersion(uint32_t id) {
265+
nlohmann::json payload;
266+
267+
payload["id"] = id;
268+
payload["type"] = ResponseType::Version;
269+
payload["version"] = std::to_string(gBuildVersionMajor) + "." + std::to_string(gBuildVersionMinor) + "." +
270+
std::to_string(gBuildVersionPatch);
271+
payload["team"] = std::string((const char*)gBuildTeam);
272+
payload["commit"] = std::string(gGitCommitHash);
273+
274+
SPDLOG_INFO("[CrowdControl] Sending version:\n{}", payload.dump());
275+
276+
std::lock_guard<std::mutex> lock(outgoingPayloadQueueMutex);
277+
outgoingPayloadQueue.push(payload);
132278
}
133279

134280
CrowdControl::EffectResult CrowdControl::ExecuteEffect(Effect* effect) {
@@ -186,7 +332,7 @@ std::unique_ptr<CrowdControl::Effect> CrowdControl::ParseMessage(nlohmann::json
186332

187333
// "parameters" is intentionally not required: most effects (spawn enemies, teleports, status
188334
// effects, etc.) carry no parameters. Its absence is handled safely below, and any type error
189-
// is caught by the guard in Network::HandleRemoteJson.
335+
// is caught by the guard in CrowdControl::OnGameFrameUpdate.
190336
if (!dataReceived.contains("code") || !dataReceived.contains("viewer")) {
191337
// This seems to happen when the CC session ends
192338
SPDLOG_ERROR("[CrowdControl] Payload does not contain code or viewer, ignoring.");
@@ -683,3 +829,11 @@ std::unique_ptr<CrowdControl::Effect> CrowdControl::ParseMessage(nlohmann::json
683829

684830
return effect;
685831
}
832+
833+
static void RegisterCrowdControl() {
834+
// Stays registered after a disable until any leftover timed effects have been removed
835+
COND_HOOK(OnGameFrameUpdate, CrowdControl::Instance != nullptr && CrowdControl::Instance->NeedsFrameUpdate(),
836+
[]() { CrowdControl::Instance->OnGameFrameUpdate(); });
837+
}
838+
839+
static RegisterShipInitFunc initFunc(RegisterCrowdControl, { CVAR_REMOTE_CROWD_CONTROL("Enabled") });

‎soh/soh/Network/CrowdControl/CrowdControl.h‎

Lines changed: 29 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -2,9 +2,10 @@
22

33
#ifdef __cplusplus
44

5-
#include <thread>
5+
#include <chrono>
66
#include <memory>
77
#include <mutex>
8+
#include <queue>
89
#include <vector>
910

1011
#include "soh/Network/Network.h"
@@ -41,7 +42,14 @@ class CrowdControl : public Network {
4142
NotReady = 0xFF
4243
};
4344

44-
enum ResponseType { EffectRequest = 0x00, Login = 0xF0, LoginSuccess = 0xF1, Disconnect = 0xFE, KeepAlive = 0xFF };
45+
enum ResponseType {
46+
EffectRequest = 0x00,
47+
Login = 0xF0,
48+
LoginSuccess = 0xF1,
49+
Version = 0xFC,
50+
Disconnect = 0xFE,
51+
KeepAlive = 0xFF
52+
};
4553

4654
struct Response {
4755
int id;
@@ -63,15 +71,28 @@ class CrowdControl : public Network {
6371
EffectResult lastExecutionResult;
6472
} Effect;
6573

66-
std::thread ccThreadProcess;
67-
74+
// Only touched on the game thread
6875
std::vector<std::unique_ptr<Effect>> activeEffects;
69-
std::mutex activeEffectsMutex;
76+
std::chrono::steady_clock::time_point lastActiveEffectsTick;
77+
// Timed effects left over from a disable, retried each frame until removal succeeds
78+
std::vector<std::unique_ptr<Effect>> effectsPendingRemoval;
79+
80+
// Payloads received on the network thread, executed on the game thread
81+
std::queue<nlohmann::json> incomingPayloadQueue;
82+
std::mutex incomingPayloadQueueMutex;
83+
// Payloads emitted on the game thread, sent on the network thread
84+
std::queue<nlohmann::json> outgoingPayloadQueue;
85+
std::mutex outgoingPayloadQueueMutex;
7086

7187
void HandleRemoteData(nlohmann::json payload);
88+
void ProcessIncomingPayload(nlohmann::json payload);
89+
void ClearPayloadQueues();
90+
bool TryRemoveEffect(Effect* effect);
91+
void ProcessPendingRemovals();
7292
void ProcessActiveEffects();
7393

7494
void EmitMessage(uint32_t eventId, long timeRemaining, EffectResult status);
95+
void SendVersion(uint32_t id);
7596
std::unique_ptr<Effect> ParseMessage(nlohmann::json payload);
7697
EffectResult ExecuteEffect(Effect* effect);
7798
EffectResult CanApplyEffect(Effect* effect);
@@ -83,7 +104,9 @@ class CrowdControl : public Network {
83104
void Disable();
84105
void OnIncomingJson(nlohmann::json payload);
85106
void OnConnected();
86-
void OnDisconnected();
107+
void ProcessOutgoingPackets();
108+
void OnGameFrameUpdate();
109+
bool NeedsFrameUpdate();
87110
};
88111

89112
#endif // __cplusplus

0 commit comments

Comments
 (0)