--- a/rts/ExternalAI/EngineOutHandler.cpp +++ b/rts/ExternalAI/EngineOutHandler.cpp @@ -1,6 +1,7 @@ /* This file is part of the Spring engine (GPL v2 or later), see LICENSE.html */ #include "EngineOutHandler.h" +#include "Net/WebbarReplay.h" #include "ExternalAI/SkirmishAIWrapper.h" #include "ExternalAI/SkirmishAIData.h" @@ -530,7 +531,9 @@ if (aiData->status != SKIRMAISTATE_RELOADING) clientNet->Send(CBaseNetProtocol::Get().SendAIStateChanged(gu->myPlayerNum, skirmishAIId, SKIRMAISTATE_INITIALIZING)); - if (aiData->isLuaAI) { + if (aiData->isLuaAI || webbarReplay::Enabled()) { + // Replay retains the AI slot and ready handshake, but never constructs an AI. + if (webbarReplay::Enabled()) LOG("[WebbarReplay] AI %u uses recorded commands only", skirmishAIId); // currently, we need to do nothing for Lua AIs clientNet->Send(CBaseNetProtocol::Get().SendAIStateChanged(gu->myPlayerNum, skirmishAIId, SKIRMAISTATE_ALIVE)); return; --- a/rts/Game/Game.cpp +++ b/rts/Game/Game.cpp @@ -68,6 +68,7 @@ #include "Map/ReadMap.h" #include "Map/Ground.h" #include "Net/GameServer.h" +#include "Net/WebbarReplay.h" #include "Net/Protocol/NetProtocol.h" #include "Sim/Ecs/Registry.h" #include "Sim/Ecs/Helper.h" @@ -1891,6 +1892,7 @@ ASSERT_SYNCED(gsRNG.GetGenState()); LEAVE_SYNCED_CODE(); + if (webbarReplay::Enabled()) webbarReplay::frame = gs->frameNum; #if defined(__EMSCRIPTEN__) { SCOPED_TIMER("Webbar::Publish"); --- a/rts/Game/PreGame.cpp +++ b/rts/Game/PreGame.cpp @@ -7,6 +7,7 @@ #include #include "PreGame.h" +#include "Net/WebbarReplay.h" #include "ClientData.h" #include "ClientSetup.h" @@ -660,7 +661,7 @@ if (clientSetup->isHost && !gameSetup->recordDemo) wantDemo = false; - if (clientNet != nullptr && wantDemo) { + if (clientNet != nullptr && wantDemo && !webbarReplay::Enabled()) { CDemoRecorder recorder = {gameSetup->mapName, gameSetup->modName, false}; recorder.WriteSetupText(gameData->GetSetupText()); --- a/rts/Game/WebbarBrowser.h +++ b/rts/Game/WebbarBrowser.h @@ -3,6 +3,7 @@ #include #include "Net/WebbarResume.h" +#include "Net/WebbarReplay.h" #include "System/LoadSave/DemoRecorder.h" #include #include @@ -23,16 +24,26 @@ #include "Sim/Features/FeatureDef.h" #include "Sim/Units/CommandAI/FactoryCAI.h" +// Full authoritative publication for view changes, handover and paused commands. +static bool webbarStateRefresh = false; +static bool webbarPausedCommandsChanged = false; +static bool webbarRepublish = false; +static int webbarReplayPublishedFrame = -1; +static uint32_t webbarFrameChecksum = 0; +static void ApplyWebbarReplayView(); +static void PublishWebbarReplayState(); +static void PollWebbarReplay(); + static bool WebbarVisible(const CUnit* unit) { - return unit->team == gu->myTeam || unit->IsInLosForAllyTeam(gu->myAllyTeam); + return gu->spectatingFullView || unit->team == gu->myTeam || unit->IsInLosForAllyTeam(gu->myAllyTeam); } // Match the native projectile drawer: owned/allied shots remain visible and // airborne projectiles use the engine's air-LOS test, including motion bounds. static bool WebbarProjectileVisible(const CProjectile* projectile) { const int allyTeam = projectile->GetAllyteamID(); - return (teamHandler.IsValidAllyTeam(allyTeam) && teamHandler.Ally(allyTeam, gu->myAllyTeam)) || losHandler->InLos(projectile, gu->myAllyTeam); + return gu->spectatingFullView || (teamHandler.IsValidAllyTeam(allyTeam) && teamHandler.Ally(allyTeam, gu->myAllyTeam)) || losHandler->InLos(projectile, gu->myAllyTeam); } // Visible units, computed once per published frame (snapshot, unit state and poses share it). static const std::vector& WebbarUnits() @@ -40,8 +51,9 @@ static std::vector units; static int frame = INT32_MIN; static const bool playable = std::getenv("WEBBAR_PLAYABLE") != nullptr; - if (frame == gs->frameNum && !units.empty()) return units; - frame = gs->frameNum; + static int team = -1; static bool full = false; + if (!webbarStateRefresh && frame == gs->frameNum && team == gu->myTeam && full == gu->spectatingFullView && !units.empty()) return units; + frame = gs->frameNum; team = gu->myTeam; full = gu->spectatingFullView; units.clear(); for (CUnit* unit: unitHandler.GetActiveUnits()) if (!playable || WebbarVisible(unit)) units.push_back(unit); @@ -101,7 +113,7 @@ // EB4 (M5) bits: 22 pose mailbox (only used when the page asks for it) | 23 removals by cause. // EB1 bits: 17 solo result from BAR game_end | 18 PvE GameRulesParams | 19 RaptorEvent/ScavEvent | // 20 display-only PvE catalog | 21 own/allied experience, self-destruct and damage reports. - MAIN_THREAD_EM_ASM({ if (Module['webbarProtocol']) Module['webbarProtocol'](9, 16777215 /* bit 23: unit removals by cause (WLC1) | bit 22: pose mailbox (WEBBAR_POSE_MAILBOX, WebbarPoses.h) | bits 17-21: EB1 (above) | bit 16: match recovery stream export + resume | restore | shields | cloak | resurrection | native work effects | area resurrection | manual launch | capture | smart trajectory | energy conversion | geothermal | selectability | build restrictions | queue edit | game speed | engine memory */); }); + MAIN_THREAD_EM_ASM({ if (Module['webbarProtocol']) Module['webbarProtocol'](9, 33554431 /* bit 24: read-only replay playback, controls and perspectives | bit 23: unit removals by cause (WLC1) | bit 22: pose mailbox (WEBBAR_POSE_MAILBOX, WebbarPoses.h) | bits 17-21: EB1 (above) | bit 16: match recovery stream export + resume | restore | shields | cloak | resurrection | native work effects | area resurrection | manual launch | capture | smart trajectory | energy conversion | geothermal | selectability | build restrictions | queue edit | game speed | engine memory */); }); PublishWebbarEngineMemory(); MAIN_THREAD_EM_ASM({ if (Module['webbarIdentity']) Module['webbarIdentity']($0, $1, $2, $3); @@ -120,7 +132,7 @@ } bool cloakCommandsChanged = false; { SCOPED_TIMER("Webbar::Publish::State::Cloak"); cloakCommandsChanged = PublishWebbarCloak(); } - if (cloakCommandsChanged || gs->frameNum % 30 == 0) { + if (webbarStateRefresh || cloakCommandsChanged || gs->frameNum % 30 == 0) { // Batch descriptions into one host call, including native state labels. // Strings are decoded synchronously before the temporary pointer table dies. // Only units whose descriptions changed since their last publication (or that have no @@ -193,18 +205,17 @@ if (Module['webbarUnitState']) Module['webbarUnitState'](HEAPU8.slice($0, $0 + $1).buffer); }, packet.data(), packet.size()); { SCOPED_TIMER("Webbar::Publish::State::Shields"); PublishWebbarShields(); } - { SCOPED_TIMER("Webbar::Publish::State::Modifiers"); if (gs->frameNum % 15 == 0) PublishWebbarUnitModifiers(); } - { SCOPED_TIMER("Webbar::Publish::State::Reports"); if (gs->frameNum % 30 == 0) { PublishWebbarUnitExperience(); PublishWebbarRules(); } + { SCOPED_TIMER("Webbar::Publish::State::Modifiers"); if (webbarStateRefresh || gs->frameNum % 15 == 0) PublishWebbarUnitModifiers(); } + { SCOPED_TIMER("Webbar::Publish::State::Reports"); if (webbarStateRefresh || gs->frameNum % 30 == 0) { PublishWebbarUnitExperience(); PublishWebbarRules(webbarStateRefresh); } PublishWebbarUnitDamage(); PublishWebbarPveEvents(); } if (gs->frameNum % 300 == 0) PublishWebbarEngineMemory(); - if (gs->frameNum > 0 && gs->frameNum % (TeamStatistics::statsPeriod * GAME_SPEED) == 0) PublishWebbarTeamStats(false, nullptr); + if (webbarStateRefresh || (gs->frameNum > 0 && gs->frameNum % (TeamStatistics::statsPeriod * GAME_SPEED) == 0)) PublishWebbarTeamStats(false, nullptr); { SCOPED_TIMER("Webbar::Publish::State::WorkAudio"); webbarWorkAudio::Publish(); } { SCOPED_TIMER("Webbar::Publish::World"); PublishWebbarWorld(); } { SCOPED_TIMER("Webbar::Publish::State::Resurrection"); PublishWebbarResurrection(); } } -static bool webbarPublishPaused = false; static void PublishWebbarFrame(); // Input is polled on the engine thread outside the synced simulation. Orders use // the same local server protocol as a desktop player's selection and commands. @@ -213,6 +224,7 @@ static const bool enabled = std::getenv("WEBBAR_PLAYABLE") != nullptr; if (!enabled || !game->playing || gs->frameNum < 0) return; + if (webbarReplay::Enabled()) { PollWebbarReplay(); return; } GetWebbarEffects(); GetWebbarMatchResult(); PollWebbarTerrainFixture(); @@ -225,17 +237,26 @@ } PublishWebbarSpeed(); + // UnitCommand runs when the networked order reaches native command AI. + // Refresh on the following unsynced poll, after its queue edits have finished. + const int resumeTarget = webbarResumeTarget.load(); + const bool catchingUp = resumeTarget >= 0 && gs->frameNum < resumeTarget; static int lastPaused = -1; if (lastPaused != int(gs->paused)) { lastPaused = int(gs->paused); - if (gs->paused && gs->frameNum > 0 && gs->frameNum % 3 != 0 && WebbarPoseMailbox::Enabled()) { - webbarPublishPaused = true; - PublishWebbarFrame(); - webbarPublishPaused = false; - } + webbarPausedCommandsChanged = gs->paused; MAIN_THREAD_EM_ASM({ if (Module['webbarState']) Module['webbarState']($0, $1); }, lastPaused, gs->frameNum); + } + if (!gs->paused) webbarPausedCommandsChanged = false; + if (gs->paused && !catchingUp && webbarPausedCommandsChanged) { + webbarPausedCommandsChanged = false; + webbarStateRefresh = true; + webbarRepublish = true; + PublishWebbarFrame(); + webbarRepublish = false; + webbarStateRefresh = false; } WebbarPoseMailbox::Refresh(&WebbarUnits); @@ -248,8 +269,6 @@ }; static_assert(sizeof(BrowserOrder) == 288); // A resumed match takes its input from the recording until it catches up. - const int resumeTarget = webbarResumeTarget.load(); - const bool catchingUp = resumeTarget >= 0 && gs->frameNum < resumeTarget; for (int batch = 0; !catchingUp && batch < 8; ++batch) { BrowserOrder order = {}; const int available = MAIN_THREAD_EM_ASM_INT({ @@ -581,6 +600,7 @@ return false; if (gs->frameNum >= target) { done = true; + webbarStateRefresh = true; // publish every full-state channel before live input MAIN_THREAD_EM_ASM({ if (Module['webbarResume']) Module['webbarResume'](2, $0, $1); }, gs->frameNum, target); return false; } @@ -609,7 +629,19 @@ // Read-only observer, after LEAVE_SYNCED_CODE. This never drives game state. static void PublishWebbarFrame() { - static const bool recoveryStream = std::getenv("WEBBAR_PLAYABLE") != nullptr && std::getenv("WEBBAR_NETWORK") == nullptr && std::getenv("WEBBAR_BROWSER") != nullptr; + // NetCommands adds sync assertions after this per-frame observer returns. + // Preserve the original frame checksum for later unsynced UI refreshes. + if (!webbarRepublish) webbarFrameChecksum = CSyncChecker::GetChecksum(); + if (webbarReplay::Enabled()) { + ApplyWebbarReplayView(); + const int seek = webbarReplay::seek.load(); + if (seek >= 0 && gs->frameNum >= seek) webbarStateRefresh = true; + if (seek >= 0 && gs->frameNum < seek) { + DiscardWebbarPresentationQueues(); + if (gs->frameNum % 300 != 0 && !webbarStateRefresh) { PublishWebbarReplayState(); return; } + } + } + static const bool recoveryStream = !webbarReplay::Enabled() && std::getenv("WEBBAR_PLAYABLE") != nullptr && std::getenv("WEBBAR_NETWORK") == nullptr && std::getenv("WEBBAR_BROWSER") != nullptr; if (recoveryStream && gs->frameNum % 150 == 0) PublishWebbarDemoStream(); if (recoveryStream && WebbarResumeCatchingUp()) { @@ -621,9 +653,8 @@ static const bool browser = std::getenv("WEBBAR_BROWSER") != nullptr; static const bool playableBrowser = browser && std::getenv("WEBBAR_PLAYABLE") != nullptr; if (playableBrowser && gs->frameNum >= 0) { SCOPED_TIMER("Webbar::Publish::Effects"); GetWebbarEffects().Publish(); } - // webbarPublishPaused: a pause that lands between publications publishes its frame once (M5 EB4), so the - // paused picture (snapshot, poses, mailbox) is the frame the simulation actually stopped on. - if ((!output && !browser) || (gs->frameNum % 3 != 0 && !webbarPublishPaused)) + // Forced publications keep snapshot, poses and low-frequency state at one frame. + if ((!output && !browser) || (gs->frameNum % 3 != 0 && !webbarStateRefresh && !(webbarReplay::Enabled() && (gs->frameNum == webbarReplay::total.load() || gs->frameNum == webbarReplay::seek.load())))) return; SCOPED_TIMER("Webbar::Publish::Frame3"); @@ -639,7 +670,7 @@ struct ProjectileRecord { uint32_t id, team; float x, y, z; }; static_assert(sizeof(UnitRecord) == 48 && sizeof(ProjectileRecord) == 20); const uint32_t header[] = {0x31524257, uint32_t(gs->frameNum), uint32_t(units.size()), - uint32_t(projectiles.size()), CSyncChecker::GetChecksum(), uint32_t(mapDims.mapx * SQUARE_SIZE), + uint32_t(projectiles.size()), webbarRepublish ? webbarFrameChecksum : CSyncChecker::GetChecksum(), uint32_t(mapDims.mapx * SQUARE_SIZE), uint32_t(mapDims.mapy * SQUARE_SIZE), 2}; std::vector packet(sizeof(header) + units.size() * sizeof(UnitRecord) + projectiles.size() * sizeof(ProjectileRecord)); uint8_t* cursor = packet.data(); @@ -682,5 +713,16 @@ MAIN_THREAD_EM_ASM({ if (Module['webbarSnapshot']) Module['webbarSnapshot'](HEAPU8.slice($0, $0 + $1).buffer); }, packet.data(), packet.size()); + if (webbarReplay::Enabled()) { + webbarReplayPublishedFrame = gs->frameNum; + // Complete a seek only after its full perspective and checksum publish. + // The server waits at the target while this observer finishes. + int seek = webbarReplay::seek.load(); + if (seek >= 0 && gs->frameNum >= seek) webbarReplay::seek.compare_exchange_strong(seek, -1); + PublishWebbarReplayState(); + } } + webbarStateRefresh = false; } + +#include "WebbarReplayBrowser.h" --- a/rts/Game/WebbarCloak.h +++ b/rts/Game/WebbarCloak.h @@ -23,10 +23,10 @@ const auto* def = unit->unitDef; // BAR's converters need actual stun status too. This is presentation // eligibility, not a prediction of allocation, payment or MMStatus. - const bool converter = !gu->spectating && def->customParams.contains("energyconv_capacity") && def->customParams.contains("energyconv_efficiency"); + const bool converter = (!gu->spectating || webbarReplay::Enabled()) && def->customParams.contains("energyconv_capacity") && def->customParams.contains("energyconv_efficiency"); // A jammer's native stun state is distinct from activation and sensor // coverage. Preserve the original simulation and publish only its state. - const bool jammer = !gu->spectating && (def->jammerRadius > 0 || def->sonarJamRadius > 0); + const bool jammer = (!gu->spectating || webbarReplay::Enabled()) && (def->jammerRadius > 0 || def->sonarJamRadius > 0); if (!def->canCloak && !unit->isCloaked && !unit->stealth && !unit->sonarStealth && !def->canResurrect && unit->stockpileWeapon == nullptr && !converter && !jammer) continue; if (records.size() >= 4096) { ++dropped; continue; } commandsChanged |= webbarCloakEvents::CommandMetadataChanged(unit->id, unit->beingBuilt); --- a/rts/Game/WebbarEconomy.h +++ b/rts/Game/WebbarEconomy.h @@ -9,7 +9,7 @@ static uint32_t ReadWebbarEnergyConversion(float (&values)[4]) { std::fill(std::begin(values), std::end(values), 0.0f); - if (gu->spectating || !teamHandler.IsValidTeam(gu->myTeam)) return 0; + if ((gu->spectating && !webbarReplay::Enabled()) || !teamHandler.IsValidTeam(gu->myTeam)) return 0; const CTeam* team = teamHandler.Team(gu->myTeam); const char* names[] = {"mmLevel", "mmCapacity", "mmUse", "mmAvgEffi"}; uint32_t mask = 0; @@ -28,7 +28,7 @@ { float values[4]; const uint32_t mask = ReadWebbarEnergyConversion(values); - if (gu->spectating || !teamHandler.IsValidTeam(gu->myTeam)) return; + if ((gu->spectating && !webbarReplay::Enabled()) || !teamHandler.IsValidTeam(gu->myTeam)) return; MAIN_THREAD_EM_ASM({ if (Module['webbarEnergyConversion']) Module['webbarEnergyConversion']($0, $1, $2, Array.from(HEAPF32.subarray($3 >>> 2, ($3 >>> 2) + 4))); }, gs->frameNum, gu->myTeam, mask, values); --- a/rts/Game/WebbarPoses.h +++ b/rts/Game/WebbarPoses.h @@ -257,7 +257,7 @@ // current frame when the camera changed, so units panned into view get their real pose (not a stale one). static void Refresh(const std::vector& (*units)()) { - if (!Enabled() || block == nullptr || !gs->paused || gs->frameNum < 0) return; + if (!Enabled() || block == nullptr || (!gs->paused && !(webbarReplay::Enabled() && (webbarReplay::paused.load() || gs->frameNum >= webbarReplay::total.load()))) || gs->frameNum < 0) return; if (__atomic_load_n(&header->cameraSeq, __ATOMIC_ACQUIRE) == publishedCameraSeq) return; Publish(units()); } --- /dev/null +++ b/rts/Game/WebbarReplayBrowser.h @@ -0,0 +1,85 @@ +/* This file is part of the Spring engine (GPL v2 or later), see LICENSE.html */ +#pragma once + +// Included after the ordinary publishers. All mutations below are unsynced +// viewing state or server pacing; recorded simulation inputs stay untouched. +static int webbarReplayTeam = webbarReplay::EnvironmentInt("WEBBAR_REPLAY_TEAM", 0); +static bool webbarReplayFullView = webbarReplay::EnvironmentInt("WEBBAR_REPLAY_FULL_VIEW", 1) != 0; + +static void ApplyWebbarReplayView() +{ + if (!teamHandler.IsValidTeam(webbarReplayTeam) || webbarReplayTeam == teamHandler.GaiaTeamID()) webbarReplayTeam = 0; + if (gu->myTeam != webbarReplayTeam || gu->spectatingFullView != webbarReplayFullView || !gu->spectating) { + DiscardWebbarPresentationQueues(); + webbarStateRefresh = true; + webbarCloakEvents::publishedCommandSignatures.clear(); + gu->myTeam = webbarReplayTeam; + gu->myAllyTeam = teamHandler.AllyTeam(webbarReplayTeam); + gu->spectating = true; + gu->spectatingFullView = webbarReplayFullView; + gu->spectatingFullSelect = true; + MAIN_THREAD_EM_ASM({ if (Module['webbarIdentity']) Module['webbarIdentity']($0, $1, $2, 1); }, gu->myPlayerNum, gu->myTeam, gu->myAllyTeam); + } +} + +static void PublishWebbarReplayState() +{ + const int total = webbarReplay::total.load(), seek = webbarReplay::seek.load(); + const int phase = gs->frameNum >= total ? 2 : (seek >= 0 && gs->frameNum < seek ? 1 : 0); + // The terminal callback may not precede the final checksum-bearing snapshot. + if (phase == 2 && webbarReplayPublishedFrame < total) return; + const int paused = webbarReplay::paused.load(); + const float speed = webbarReplay::speed.load(); + static int lastFrame = -2, lastPhase = -1, lastPaused = -1, lastTeam = -1, lastFull = -1; + static float lastSpeed = -1.0f; + if (lastPhase == phase && lastPaused == paused && lastSpeed == speed && lastTeam == webbarReplayTeam && lastFull == int(webbarReplayFullView) && gs->frameNum - lastFrame < (phase == 1 ? 30 : 3)) return; + lastFrame = gs->frameNum; lastPhase = phase; lastPaused = paused; lastSpeed = speed; lastTeam = webbarReplayTeam; lastFull = webbarReplayFullView; + MAIN_THREAD_EM_ASM({ if (Module['webbarReplayState']) Module['webbarReplayState']($0, $1, $2, $3, $4, $5, $6); }, gs->frameNum, total, phase, paused, speed, webbarReplayTeam, int(webbarReplayFullView)); +} + +static void PollWebbarReplay() +{ + struct Control { uint32_t request, kind; int32_t frame, team; uint32_t fullView; float speed; }; + static_assert(sizeof(Control) == 24); + ApplyWebbarReplayView(); + for (int i = 0; i < 8; ++i) { + Control control = {}; + if (!MAIN_THREAD_EM_ASM_INT({ return Module['webbarPollReplay'] ? Module['webbarPollReplay']($0) : 0; }, &control)) break; + int status = 0; + switch (control.kind) { + case 1: + if (control.frame != 0 && control.frame != 1) status = 2; + else { + webbarReplay::paused = control.frame != 0; + if (control.frame != 0) webbarStateRefresh = true; + } + break; + case 2: + if (!std::isfinite(control.speed) || control.speed < 0.25f || control.speed > 20.0f) status = 2; + else webbarReplay::speed = control.speed; + break; + case 3: + if (control.frame < gs->frameNum) status = 3; // restart the Worker for a backward seek + else if (control.frame > webbarReplay::total.load()) status = 2; + else { + webbarReplay::seek = control.frame; + if (control.frame == gs->frameNum) webbarStateRefresh = true; + } + break; + case 4: + if (!teamHandler.IsValidTeam(control.team) || control.team == teamHandler.GaiaTeamID() || control.fullView > 1) status = 2; + else { webbarReplayTeam = control.team; webbarReplayFullView = control.fullView != 0; ApplyWebbarReplayView(); } + break; + default: status = 1; + } + MAIN_THREAD_EM_ASM({ if (Module['webbarReplayResult']) Module['webbarReplayResult']($0, $1, $2); }, control.request, status, gs->frameNum); + } + if (webbarStateRefresh) { + webbarRepublish = true; + PublishWebbarFrame(); + webbarRepublish = false; + webbarStateRefresh = false; + } + PublishWebbarReplayState(); + WebbarPoseMailbox::Refresh(&WebbarUnits); +} --- a/rts/Game/WebbarReports.h +++ b/rts/Game/WebbarReports.h @@ -66,7 +66,7 @@ bool WantsEvent(const std::string& name) override { return name == "UnitDamaged"; } int GetReadAllyTeam() const override { return AllAccessTeam; } void UnitDamaged(const CUnit* unit, const CUnit* attacker, float damage, int weaponDefID, int, bool paralyzer) override { - if (gs->frameNum < 0 || damage <= 0.0f || unit == nullptr || !teamHandler.Ally(gu->myAllyTeam, unit->allyteam)) return; + if (gs->frameNum < 0 || damage <= 0.0f || unit == nullptr || (!gu->spectatingFullView && !teamHandler.Ally(gu->myAllyTeam, unit->allyteam))) return; if (records.size() >= 1024) { ++dropped; return; } const bool seen = attacker != nullptr && WebbarVisible(attacker); records.push_back({uint32_t(unit->id), uint32_t(unit->unitDef->id), paralyzer ? 0.0f : damage, paralyzer ? damage : 0.0f, @@ -125,7 +125,7 @@ static_assert(sizeof(Record) == 16); std::vector records; for (const CUnit* unit: unitHandler.GetActiveUnits()) { - if (unit->isDead || !teamHandler.Ally(gu->myAllyTeam, unit->allyteam) || (unit->experience <= 0.0f && unit->selfDCountdown <= 0)) continue; + if (unit->isDead || (!gu->spectatingFullView && !teamHandler.Ally(gu->myAllyTeam, unit->allyteam)) || (unit->experience <= 0.0f && unit->selfDCountdown <= 0)) continue; if (records.size() >= 8192) break; records.push_back({uint32_t(unit->id), unit->experience, int32_t(unit->selfDCountdown), unit->team == gu->myTeam ? 1u : 2u}); } --- a/rts/Game/WebbarResurrection.h +++ b/rts/Game/WebbarResurrection.h @@ -5,7 +5,7 @@ // No resurrection, resource or completion logic is implemented by the bridge. static void PublishWebbarResurrection() { - if (gs->frameNum % 15 != 0) return; + if (!webbarStateRefresh && gs->frameNum % 15 != 0) return; struct FeatureRecord { uint32_t feature, definition; float progress, reclaim; }; struct BuilderRecord { uint32_t unit, feature; }; static_assert(sizeof(FeatureRecord) == 16 && sizeof(BuilderRecord) == 8); --- a/rts/Game/WebbarWorld.h +++ b/rts/Game/WebbarWorld.h @@ -5,7 +5,7 @@ // feature or queue streams. Radar contacts contain positions, not unit identity. static void PublishWebbarWorld() { - if (gs->frameNum % 15 != 0) return; + if (!webbarStateRefresh && gs->frameNum % 15 != 0) return; PublishWebbarGeothermal(); { // Native wind for smoke drift (CSmokeProjectile / CGeoThermSmokeProjectile). @@ -23,7 +23,7 @@ for (uint32_t z = 0; z < grid; ++z) for (uint32_t x = 0; x < grid; ++x) { const float px = (x + 0.5f) * visionHeader[4] / grid, pz = (z + 0.5f) * visionHeader[5] / grid; const float3 pos(px, CGround::GetHeightReal(px, pz), pz); - vision[sizeof(visionHeader) + z * grid + x] = (losHandler->InLos(pos, gu->myAllyTeam) ? 1 : 0) | (losHandler->InRadar(pos, gu->myAllyTeam) ? 2 : 0); + vision[sizeof(visionHeader) + z * grid + x] = gu->spectatingFullView ? 3 : ((losHandler->InLos(pos, gu->myAllyTeam) ? 1 : 0) | (losHandler->InRadar(pos, gu->myAllyTeam) ? 2 : 0)); } std::memcpy(vision.data() + sizeof(visionHeader) + grid * grid, contacts.data(), contacts.size() * sizeof(float3)); MAIN_THREAD_EM_ASM({ if (Module['webbarVision']) Module['webbarVision'](HEAPU8.slice($0, $0 + $1).buffer); }, vision.data(), vision.size()); @@ -36,7 +36,7 @@ const CFeature* feature = featureHandler.GetFeature(id); // Geovents have their own stream; undrawn features have no model. Non-reclaimable // scenery is drawn but carries reclaim = -1 (schema 1) so it is never a reclaim target. - if (feature->def->geoThermal || feature->def->drawType == DRAWTYPE_NONE || !losHandler->InLos(feature->pos, gu->myAllyTeam)) continue; + if (feature->def->geoThermal || feature->def->drawType == DRAWTYPE_NONE || (!gu->spectatingFullView && !losHandler->InLos(feature->pos, gu->myAllyTeam))) continue; if (std::find(featureDefs.begin(), featureDefs.end(), feature->def->id) == featureDefs.end()) { featureDefs.push_back(feature->def->id); MAIN_THREAD_EM_ASM({ if (Module['webbarFeatureDef']) Module['webbarFeatureDef']($0, UTF8ToString($1)); }, feature->def->id, feature->def->modelName.c_str()); @@ -53,8 +53,8 @@ std::memcpy(featurePacket.data() + sizeof(featureHeader), features.data(), features.size() * sizeof(FeatureRecord)); MAIN_THREAD_EM_ASM({ if (Module['webbarFeatures']) Module['webbarFeatures'](HEAPU8.slice($0, $0 + $1).buffer); }, featurePacket.data(), featurePacket.size()); - struct QueueRecord { uint32_t unit, tag; int32_t command; uint32_t target; float x, y, z; uint32_t index; }; - static_assert(sizeof(QueueRecord) == 32); + struct QueueRecord { uint32_t unit, tag; int32_t command; uint32_t target; float x, y, z; uint32_t index, facing; }; + static_assert(sizeof(QueueRecord) == 36); std::vector queues; for (const CUnit* unit: unitHandler.GetActiveUnits()) { if (unit->team != gu->myTeam) continue; @@ -69,18 +69,25 @@ const unsigned int offset = areaChild ? 1 : 0; const bool areaResurrect = command.GetID() == CMD_RESURRECT && command.GetNumParams() == 4; const uint32_t flags = (internal ? 0x80000000u : 0u) | (areaResurrect ? 0x40000000u : 0u); + // WBQ2: BuildInfo::Parse uses the fourth parameter only on four-param + // build orders. A missing/invalid facing stays unknown, never guessed. + uint32_t facing = 0xffffffffu; + if (command.GetID() < 0 && command.GetNumParams() == 4) { + const float value = command.GetParam(3); + if (std::isfinite(value) && value >= 0.0f && value <= 3.0f && value == std::floor(value)) facing = uint32_t(value); + } queues.push_back({uint32_t(unit->id), command.GetTag(), command.GetID(), (command.GetNumParams() == 1 || areaChild) ? uint32_t(command.GetParam(0)) : 0xffffffff, - position ? command.GetParam(offset) : 0.0f, position ? command.GetParam(offset + 1) : 0.0f, position ? command.GetParam(offset + 2) : 0.0f, (index++) | flags}); + position ? command.GetParam(offset) : 0.0f, position ? command.GetParam(offset + 1) : 0.0f, position ? command.GetParam(offset + 2) : 0.0f, (index++) | flags, facing}); } if (unit->unitDef->IsFactoryUnit()) { const auto& rally = static_cast(unit->commandAI)->newUnitCommands; if (!rally.empty() && rally.back().GetNumParams() >= 3) { const auto& command = rally.back(); - queues.push_back({uint32_t(unit->id), 0, CMD_MOVE, 0xffffffff, command.GetParam(0), command.GetParam(1), command.GetParam(2), 0xffffffff}); + queues.push_back({uint32_t(unit->id), 0, CMD_MOVE, 0xffffffff, command.GetParam(0), command.GetParam(1), command.GetParam(2), 0xffffffff, 0xffffffff}); } } } - const uint32_t queueHeader[] = {0x31514257, uint32_t(gs->frameNum), uint32_t(queues.size()), 0}; + const uint32_t queueHeader[] = {0x32514257, uint32_t(gs->frameNum), uint32_t(queues.size()), 0}; std::vector queuePacket(sizeof(queueHeader) + queues.size() * sizeof(QueueRecord)); std::memcpy(queuePacket.data(), queueHeader, sizeof(queueHeader)); std::memcpy(queuePacket.data() + sizeof(queueHeader), queues.data(), queues.size() * sizeof(QueueRecord)); --- a/rts/Net/GameServer.cpp +++ b/rts/Net/GameServer.cpp @@ -53,6 +53,8 @@ #include "System/LoadSave/DemoRecorder.h" #include "System/LoadSave/DemoReader.h" #include "Net/WebbarResume.h" +#include "Net/WebbarReplay.h" +#include "System/Exceptions.h" #include "System/Log/ILog.h" #include "System/Platform/errorhandler.h" #include "System/Platform/Threading.h" @@ -190,12 +192,18 @@ } if (demoReader == nullptr) { - if (const char* path = std::getenv("WEBBAR_RESUME_STREAM")) { + if (const char* path = std::getenv(webbarReplay::Enabled() ? "WEBBAR_REPLAY_STREAM" : "WEBBAR_RESUME_STREAM")) { resumeReader.reset(new WebbarResumeReader()); - if (resumeReader->Load(path)) { - webbarResumeTarget = resumeReader->frames; + if (resumeReader->Load(path, webbarReplay::Enabled())) { + if (webbarReplay::Enabled()) { + webbarReplay::Initialize(resumeReader->frames - 1); + minUserSpeed = 0.25f; maxUserSpeed = 20.0f; + } else { + webbarResumeTarget = resumeReader->frames; + } Message(spring::format("[WebbarResume] replaying %d recorded frames (%u packets)", resumeReader->frames, unsigned(resumeReader->packets.size())), false); } else { + if (webbarReplay::Enabled()) throw content_error("WebBAR replay stream is invalid or truncated; playback stopped"); Message("[WebbarResume] the recorded stream could not be read; starting live", false); resumeReader.reset(); webbarResumeTarget = -2; // failure, reported to the browser @@ -264,7 +272,7 @@ std::sort(commandBlacklist.begin(), commandBlacklist.end()); } - if (configHandler->GetBool("ServerRecordDemos")) { + if (!webbarReplay::Enabled() && configHandler->GetBool("ServerRecordDemos")) { demoRecorder.reset(new CDemoRecorder(myGameSetup->mapName, myGameSetup->modName, true)); demoRecorder->WriteSetupText(myGameData->GetSetupText()); const netcode::RawPacket* ret = myGameData->Pack(); @@ -571,7 +579,30 @@ { // Pace by the local client's progress (not wall time), so catch-up runs as fast as it simulates. unsigned int sent = 0; - while (resumeReader->HasData() && sent < 2 * GAME_SPEED) { + unsigned int budget = 2 * GAME_SPEED; + int limit = INT_MAX; + if (webbarReplay::Enabled()) { + const int current = webbarReplay::frame.load(); + const int target = webbarReplay::seek.load(); + // The game thread clears seek only after publishing the target's full view. + // Clearing it here races that observer and can omit a non-cadence target. + if (target >= 0 && current >= target) return; + const bool seeking = target >= 0; + const float speed = seeking ? 20.0f : webbarReplay::speed.load(); + if (userSpeedFactor != speed) UserSpeedChange(speed, SERVER_PLAYER); + const spring_time now = spring_gettime(); + const float elapsed = std::clamp((now - lastNewFrameTick).toMilliSecsf(), 0.0f, 200.0f); + lastNewFrameTick = now; + if (!seeking && webbarReplay::paused.load() && current >= 0) { frameTimeLeft = 0.0f; return; } + if (!seeking) { + frameTimeLeft = std::min(frameTimeLeft + elapsed * (GAME_SPEED * 0.001f) * speed, 3.0f); + budget = static_cast(frameTimeLeft); + frameTimeLeft -= budget; + } + limit = seeking ? target : current + 3; + } + while (resumeReader->HasData() && sent < budget) { + if (webbarReplay::Enabled() && serverFrameNum >= limit) break; if (HasLocalClient() && (serverFrameNum - players[localClientNumber].lastFrameResponse) >= 2 * GAME_SPEED) break; const WebbarResumeReader::Packet p = resumeReader->Peek(); @@ -589,7 +620,7 @@ } Broadcast(std::make_shared(bytes, p.length)); } - if (!resumeReader->HasData()) { + if (!resumeReader->HasData() && !webbarReplay::Enabled()) { resumeActive = false; UserSpeedChange(1.0f, SERVER_PLAYER); frameTimeLeft = 0.0f; @@ -1103,7 +1134,7 @@ if (players[a].myState == GameParticipant::DISCONNECTING) return; // A resumed match takes all synced input from the recording until it catches up. - if (resumeActive && WebbarResumeReader::LiveInputDropped(msgCode)) + if ((resumeActive || webbarReplay::Enabled()) && (WebbarResumeReader::LiveInputDropped(msgCode) || (webbarReplay::Enabled() && msgCode == NETMSG_CCOMMAND))) return; switch (msgCode) { @@ -2387,7 +2418,7 @@ // Catch up at the fastest allowed speed (the client consumes frames at its speed factor); // the speed factor is not synced state, so this does not change the simulation. if (resumeActive) - UserSpeedChange(maxUserSpeed, SERVER_PLAYER); + UserSpeedChange(webbarReplay::Enabled() ? webbarReplay::speed.load() : maxUserSpeed, SERVER_PLAYER); if (hostif != nullptr) { if (demoRecorder != nullptr) { @@ -3250,4 +3281,3 @@ freeSkirmishAIs.pop_back(); return id; } - --- /dev/null +++ b/rts/Net/WebbarReplay.h @@ -0,0 +1,34 @@ +/* This file is part of the Spring engine (GPL v2 or later), see LICENSE.html */ +#pragma once + +// EB5: a local recorded-command stream that can never hand over to live play. +// These controls are presentation/server pacing state, never simulation input. +#include +#include +#include +#include + +namespace webbarReplay { +inline bool Enabled() +{ + static const bool enabled = std::getenv("WEBBAR_REPLAY_STREAM") != nullptr; + return enabled; +} +inline int EnvironmentInt(const char* name, int fallback) +{ + const char* value = std::getenv(name); + return value != nullptr ? std::atoi(value) : fallback; +} +inline std::atomic frame{-1}, total{-1}, seek{-1}; +inline std::atomic paused{false}; +inline std::atomic speed{1.0f}; +inline void Initialize(int lastFrame) +{ + total = lastFrame; + seek = std::clamp(EnvironmentInt("WEBBAR_REPLAY_FRAME", 0), 0, lastFrame); + paused = EnvironmentInt("WEBBAR_REPLAY_PAUSED", 0) != 0; + const char* value = std::getenv("WEBBAR_REPLAY_SPEED"); + const float requested = value != nullptr ? std::strtof(value, nullptr) : 1.0f; + speed = std::isfinite(requested) ? std::clamp(requested, 0.25f, 20.0f) : 1.0f; +} +} --- a/rts/Net/WebbarResume.h +++ b/rts/Net/WebbarResume.h @@ -26,7 +26,7 @@ public: struct Packet { size_t offset; uint32_t length; }; - bool Load(const char* path) { + bool Load(const char* path, bool strict = false) { std::ifstream in(path, std::ios::binary); if (!in) return false; @@ -38,7 +38,7 @@ std::memcpy(&h, &data[o], sizeof(h)); h.swab(); const size_t p = o + sizeof(h); - if (h.length == 0 || p + h.length > data.size()) + if (h.length == 0 || h.length > data.size() - p) break; // a truncated tail (interrupted export) ends the recording const uint8_t msg = data[p]; if (msg == NETMSG_GAMEID && h.length >= 17) { @@ -53,7 +53,7 @@ } o = p + h.length; } - return started && frames > 0; + return started && frames > 0 && (!strict || o == data.size()); } bool HasData() const { return next < packets.size(); } @@ -65,6 +65,10 @@ static bool Forwarded(uint8_t msg) { switch (msg) { case NETMSG_NEWFRAME: case NETMSG_KEYFRAME: + // Commands entered while paused deliberately skip CommandAI::SlowUpdate. + // Preserve that state around recorded commands, without replaying the + // wall-clock wait (the server still advances solely by recorded frames). + case NETMSG_PAUSE: case NETMSG_COMMAND: case NETMSG_SELECT: case NETMSG_AICOMMAND: case NETMSG_AICOMMANDS: case NETMSG_AICOMMAND_TRACKED: case NETMSG_AISHARE: case NETMSG_LUAMSG: case NETMSG_SHARE: case NETMSG_SETSHARE: