--- a/rts/Game/WebbarBrowser.h +++ b/rts/Game/WebbarBrowser.h @@ -51,7 +51,12 @@ // 64-bit FNV-1a, for change detection of presentation-only data. struct WebbarHash { uint64_t value = 1469598103934665603ull; - void Bytes(const void* data, size_t size) { const auto* b = static_cast(data); for (size_t i = 0; i < size; ++i) { value ^= b[i]; value *= 1099511628211ull; } } + // M5 EB4: eight bytes per step (was one); a change detector only, never compared across builds. + void Bytes(const void* data, size_t size) { + const auto* b = static_cast(data); + for (; size >= 8; b += 8, size -= 8) { uint64_t w; std::memcpy(&w, b, 8); value = (value ^ w) * 1099511628211ull; value ^= value >> 29; } + for (; size > 0; ++b, --size) { value ^= *b; value *= 1099511628211ull; } + } void Word(uint32_t word) { Bytes(&word, sizeof(word)); } void String(const std::string& text) { Word(uint32_t(text.size())); Bytes(text.data(), text.size()); } }; @@ -84,6 +89,7 @@ #include "WebbarWorld.h" #include "WebbarTerrain.h" #include "WebbarTerrainFixture.h" +#include "WebbarPoses.h" static void PublishWebbarPlayState() { @@ -92,9 +98,10 @@ catalogSent = true; GetWebbarMatchResult(); GetWebbarUnitDamage(); + // 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, 4194303 /* 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, 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 */); }); PublishWebbarEngineMemory(); MAIN_THREAD_EM_ASM({ if (Module['webbarIdentity']) Module['webbarIdentity']($0, $1, $2, $3); @@ -111,7 +118,8 @@ PublishWebbarDisplayCatalog(); PublishWebbarRules(true); } - const bool cloakCommandsChanged = PublishWebbarCloak(); + bool cloakCommandsChanged = false; + { SCOPED_TIMER("Webbar::Publish::State::Cloak"); cloakCommandsChanged = PublishWebbarCloak(); } if (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. @@ -157,7 +165,7 @@ }, words.data(), words.size(), gs->frameNum); } SCOPED_TIMER("Webbar::Publish::State::Rest"); - PublishWebbarEnergyConversion(); + { SCOPED_TIMER("Webbar::Publish::State::Economy"); PublishWebbarEnergyConversion(); } const CTeam* team = teamHandler.Team(gu->myTeam); const float economy[] = {team->res.metal, team->resStorage.metal, team->resPrevIncome.metal, team->resPrevExpense.metal, team->resPrevPull.metal, team->res.energy, team->resStorage.energy, team->resPrevIncome.energy, team->resPrevExpense.energy, team->resPrevPull.energy}; @@ -184,18 +192,20 @@ MAIN_THREAD_EM_ASM({ if (Module['webbarUnitState']) Module['webbarUnitState'](HEAPU8.slice($0, $0 + $1).buffer); }, packet.data(), packet.size()); - PublishWebbarShields(); - if (gs->frameNum % 15 == 0) PublishWebbarUnitModifiers(); - if (gs->frameNum % 30 == 0) { PublishWebbarUnitExperience(); PublishWebbarRules(); } + { 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(); } PublishWebbarUnitDamage(); - PublishWebbarPveEvents(); + PublishWebbarPveEvents(); } if (gs->frameNum % 300 == 0) PublishWebbarEngineMemory(); if (gs->frameNum > 0 && gs->frameNum % (TeamStatistics::statsPeriod * GAME_SPEED) == 0) PublishWebbarTeamStats(false, nullptr); - webbarWorkAudio::Publish(); + { SCOPED_TIMER("Webbar::Publish::State::WorkAudio"); webbarWorkAudio::Publish(); } { SCOPED_TIMER("Webbar::Publish::World"); PublishWebbarWorld(); } - PublishWebbarResurrection(); + { 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. static void PollWebbarCommands() @@ -218,10 +228,16 @@ 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; + } MAIN_THREAD_EM_ASM({ if (Module['webbarState']) Module['webbarState']($0, $1); }, lastPaused, gs->frameNum); } + WebbarPoseMailbox::Refresh(&WebbarUnits); // Pinned BAR modules/customcommands.lua; its synced gadget reissues native MANUALFIRE. constexpr int BAR_MANUAL_LAUNCH = 32102; @@ -485,6 +501,18 @@ static void PublishWebbarPoses() { const auto& units = WebbarUnits(); + if (WebbarPoseMailbox::Enabled()) { + // EB4: definitions as in the legacy stream, poses through the shared mailbox (WebbarPoses.h). + static std::vector announced; + for (const CUnit* unit: units) { + if (size_t(unit->unitDef->id) >= announced.size()) announced.resize(unit->unitDef->id + 1, false); + if (announced[unit->unitDef->id]) continue; + announced[unit->unitDef->id] = true; + MAIN_THREAD_EM_ASM({ if (Module['webbarDefinition']) Module['webbarDefinition']($0, UTF8ToString($1)); }, unit->unitDef->id, unit->unitDef->name.c_str()); + } + WebbarPoseMailbox::Publish(units); + if (!WebbarPoseMailbox::Verify()) return; + } uint32_t pieceCount = 0; for (const CUnit* unit: units) pieceCount += unit->localModel.pieces.size(); @@ -593,7 +621,9 @@ 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(); } - if ((!output && !browser) || gs->frameNum % 3 != 0) + // 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)) return; SCOPED_TIMER("Webbar::Publish::Frame3"); --- /dev/null +++ b/rts/Game/WebbarLossCauses.h @@ -0,0 +1,51 @@ +/* This file is part of the Spring engine (GPL v2 or later), see LICENSE.html */ +#pragma once + +// WebBAR (parity plan M5 fold-in, engine request M3-loss-causes, capability bit 23): per-team unit +// removals by cause for the match summary. TeamStatistics only has unitsDied (every removal) and +// unitsKilled (credited kills), so most losses had no visible cause. Counted in CUnit::ForcedKillUnit, +// published with the team statistics (WLC1, WebbarReports.h). Presentation-only counters: never read +// by the simulation and not part of any sync checksum. +#ifdef __EMSCRIPTEN__ +#include +#include +#include +#include "Sim/Misc/GlobalConstants.h" +#include "Sim/Misc/GlobalSynced.h" +#include "Sim/Misc/TeamHandler.h" +#include "Sim/Units/Unit.h" + +namespace WebbarLossCauses { +// 0 enemy attacker, 1 self-destruct, 2 reclaimed, 3 unfinished (nanoframe died without an attacker), +// 4 own or allied fire, 5 enemy uncredited (no attacker, damaged by an enemy or an ownerless weapon in +// the last 3 s: e.g. its attacker died first), 6 no attacker (crash, gadget DestroyUnit, ...). +constexpr int CAUSES = 7, UNCREDITED_FRAMES = 90; +inline std::array, MAX_TEAMS>& Counts() { static std::array, MAX_TEAMS> counts{}; return counts; } +inline std::vector& HostileDamageFrames() { static std::vector frames; return frames; } + +inline void Damaged(const CUnit* victim, const CUnit* attacker) +{ + if (attacker != nullptr && teamHandler.Ally(attacker->allyteam, victim->allyteam)) return; + auto& frames = HostileDamageFrames(); + if (size_t(victim->id) >= frames.size()) frames.resize(victim->id + 1024, -1000000); + frames[victim->id] = gs->frameNum; +} + +inline void Removed(const CUnit* victim, const CUnit* attacker, bool selfDestruct, bool reclaimed, bool beingBuilt) +{ + if (victim->team < 0 || victim->team >= MAX_TEAMS) return; + int cause = 6; + if (reclaimed) cause = 2; + else if (selfDestruct) cause = 1; + else if (attacker != nullptr) cause = teamHandler.Ally(attacker->allyteam, victim->allyteam) ? 4 : 0; + else { + const auto& frames = HostileDamageFrames(); + const bool recent = size_t(victim->id) < frames.size() && frames[victim->id] >= gs->frameNum - UNCREDITED_FRAMES; + cause = recent ? 5 : (beingBuilt ? 3 : 6); + } + ++Counts()[victim->team][cause]; + auto& frames = HostileDamageFrames(); + if (size_t(victim->id) < frames.size()) frames[victim->id] = -1000000; +} +} // namespace WebbarLossCauses +#endif --- /dev/null +++ b/rts/Game/WebbarPoses.h @@ -0,0 +1,265 @@ +/* This file is part of the Spring engine (GPL v2 or later), see LICENSE.html */ +#pragma once + +// WebBAR (parity plan M5, EB4, capability bit 22): pose mailbox. +// +// The legacy pose stream (WBM2, PublishWebbarPoses) copies every visible unit's world matrix and every +// piece's 4x4 model-space matrix (80 + 72 B per piece) into a new buffer every third frame, proxies it +// to the engine's runtime Worker, which posts it to the page; at 20x speed the page decodes 200 such +// packets a second. With WEBBAR_POSE_MAILBOX set (the play page asks for it) poses instead go to a +// latest-wins triple buffer in the engine heap, which the page reads straight from the WebAssembly +// memory's SharedArrayBuffer once per snapshot it handles: +// - camera culling and LOD: the page writes its view frustum, eye and draw distance into the header; +// units outside it (with a margin for shadows) or beyond the draw distance get no piece data, and +// distant units are refreshed every second or fourth publication; +// - changed-only: rotation and piece matrices are sent only when they differ from what the page is +// known to hold. The page acknowledges the last slot sequence it consumed ("consumed"); an item is +// resent in every slot from its change until the page has consumed one of those slots (a slot +// without the item, e.g. culled, restarts that chain), so skipped slots never lose a change; +// - local transforms: a piece record is its piece-space matrix (3x4, 48 B, CalcPieceSpaceTransform), sent +// only when its own animation state changed; the page composes the hierarchy from the parent table +// (sent with the unit's structure item). The unit record carries rotation only (the snapshot has the +// position). +// Unsynced and read-only: nothing here changes simulation state or the engine's own model caches. +#include +#include +#include +#include +#include +#include + +namespace WebbarPoseMailbox { + +// Header at the start of the mailbox block (little-endian, 4-byte words unless noted). +struct Header { + uint32_t magic; // 'WPM1' + uint32_t version; // 1 + int32_t middle; // triple-buffer exchange word: slot index | 4 when it holds an unread publication + int32_t consumed; // written by the page: sequence of the last slot it read + int32_t cameraSeq; // written by the page: > 0 once view[] holds a camera + uint32_t slotCapacity; // bytes per slot + uint32_t slotOffset[3]; // from the start of the block + uint32_t reserved; + // Written by the page: 6 normalized frustum planes (a, b, c, d; inside when a*x + b*y + c*z + d >= -r), + // eye xyz, draw distance (0 = unlimited), LOD distances (near: every publication, beyond far: every + // fourth, between: every second; 0 = no LOD), culling margin in elmos. + float view[32]; + // Written by the engine: publications, slot bytes, legacy WBM2 bytes for the same units, units with + // data, piece records, culled units, LOD-skipped units, slots that had to grow. + double stats[8]; +}; +static_assert(sizeof(Header) == 232); +constexpr uint32_t HEADER_BYTES = 256, SLOT_HEADER_BYTES = 32; +constexpr uint8_t FLAG_ROTATION = 1, FLAG_CULLED = 2, FLAG_LOD = 4, FLAG_RESET = 8, FLAG_STRUCTURE = 16; + +struct PieceState { float raw[7]; uint32_t visible; float m[12]; int32_t first; bool dirty; }; +struct UnitState { + int32_t present = INT32_MIN; + int32_t def = -1; + float rot[9]; + int32_t rotFirst = -1; + int32_t structFirst = -1; + bool rotDirty = true; + bool structDirty = true; + std::vector pieces; +}; + +static uint8_t* block = nullptr; +static Header* header = nullptr; +static uint32_t capacity = 0; +static int32_t back = 2; +static int32_t seq = 0; +static int32_t publishedCameraSeq = 0; +static std::vector states; + +static bool Enabled() +{ + static const bool enabled = std::getenv("WEBBAR_POSE_MAILBOX") != nullptr && std::getenv("WEBBAR_PLAYABLE") != nullptr && std::getenv("WEBBAR_BROWSER") != nullptr; + return enabled; +} +// Verification (tests only): also send the legacy WBM2 stream so the page can compare both decodes. +static bool Verify() +{ + static const bool verify = Enabled() && std::getenv("WEBBAR_POSE_MAILBOX_VERIFY") != nullptr; + return verify; +} + +// A new block (first use, or a slot outgrew its capacity). The previous block is not freed: the page may +// still be reading it until it receives the new one (rare: capacity doubles). +static void Allocate(uint32_t needed) +{ + uint32_t next = std::max(capacity == 0 ? (4u << 20) : capacity * 2, (needed + 4095u) & ~4095u); + uint8_t* memory = static_cast(std::aligned_alloc(16, HEADER_BYTES + 3 * size_t(next))); + if (memory == nullptr) return; + std::memset(memory, 0, HEADER_BYTES + 3 * size_t(next)); + Header* h = reinterpret_cast(memory); + h->magic = 0x314d5057; h->version = 1; h->middle = 1; h->slotCapacity = next; + for (int i = 0; i < 3; ++i) h->slotOffset[i] = HEADER_BYTES + i * next; + if (header != nullptr) { + // Keep the page's acknowledgement, camera and statistics across the switch. + h->consumed = __atomic_load_n(&header->consumed, __ATOMIC_ACQUIRE); + h->cameraSeq = header->cameraSeq; + std::memcpy(h->view, header->view, sizeof(h->view)); + std::memcpy(h->stats, header->stats, sizeof(h->stats)); + h->stats[7] += 1; + } + block = memory; header = h; capacity = next; back = 2; + MAIN_THREAD_EM_ASM({ if (Module['webbarPoseMailbox']) Module['webbarPoseMailbox']($0, $1); }, block, HEADER_BYTES + 3 * next); +} + +struct Writer { + uint8_t* base; size_t at; size_t limit; bool overflow = false; + template void Put(const T& value) { if (at + sizeof(T) > limit) { overflow = true; return; } std::memcpy(base + at, &value, sizeof(T)); at += sizeof(T); } + void Bytes(const void* data, size_t size) { if (at + size > limit) { overflow = true; return; } std::memcpy(base + at, data, size); at += size; } +}; + +// Returns false when the slot overflowed (the caller grows the mailbox and publishes again). +static bool Write(const std::vector& units, int32_t slotSeq) +{ + const int32_t acknowledged = __atomic_load_n(&header->consumed, __ATOMIC_ACQUIRE); + float view[32]; + std::memcpy(view, header->view, sizeof(view)); + const int32_t cameraSeq = __atomic_load_n(&header->cameraSeq, __ATOMIC_ACQUIRE); + const bool viewKnown = cameraSeq > 0; + const float reach = view[27], lodNear = view[28], lodFar = view[29], margin = view[30]; + Writer out{block + header->slotOffset[back], SLOT_HEADER_BYTES, capacity}; + double withData = 0, pieceRecords = 0, culled = 0, lodSkipped = 0, legacy = 16; + uint32_t count = 0; + for (CUnit* unit: units) { + const auto& pieces = unit->localModel.pieces; + const uint32_t id = uint32_t(unit->id); + legacy += 80 + 72.0 * pieces.size(); + if (id >= states.size()) states.resize(std::max(id + 1, unitHandler.MaxUnits())); + UnitState& st = states[id]; + const int32_t def = unit->unitDef->id; + uint8_t flags = 0; + if (st.present != slotSeq - 1 || st.def != def || st.pieces.size() != pieces.size()) { + // New to the page (or a reused id): everything is dirty. + st.def = def; st.rotDirty = true; st.rotFirst = -1; st.structDirty = true; st.structFirst = -1; + st.pieces.assign(pieces.size(), PieceState{}); + for (PieceState& p: st.pieces) { std::fill(std::begin(p.raw), std::end(p.raw), std::numeric_limits::quiet_NaN()); p.visible = 2; p.first = -1; p.dirty = true; } + flags |= FLAG_RESET; + } + st.present = slotSeq; + bool active = true; + if (viewKnown) { + const float3 c = unit->midPos; + const float r = unit->radius * 1.5f + std::max(0.0f, margin); + for (int k = 0; k < 24 && active; k += 4) + if (view[k] * c.x + view[k + 1] * c.y + view[k + 2] * c.z + view[k + 3] < -r) active = false; + const float dx = c.x - view[24], dy = c.y - view[25], dz = c.z - view[26], d2 = dx * dx + dy * dy + dz * dz; + if (active && reach > 0.0f && d2 > (reach + r) * (reach + r)) active = false; + if (!active) { flags |= FLAG_CULLED; culled += 1; } + else if (lodNear > 0.0f && d2 > lodNear * lodNear) { + const uint32_t step = (lodFar > 0.0f && d2 > lodFar * lodFar) ? 4 : 2; + if ((uint32_t(slotSeq) + id) % step != 0) { active = false; flags |= FLAG_LOD; lodSkipped += 1; } + } + } + if (!active) { + // Not sent now: any pending item starts a new delivery chain when it is next sent. + st.rotFirst = -1; st.structFirst = -1; + for (PieceState& p: st.pieces) p.first = -1; + out.Put(id); out.Put(uint16_t(def)); out.Put(uint8_t(unit->team)); out.Put(flags); out.Put(uint16_t(pieces.size())); out.Put(uint16_t(0)); + ++count; + continue; + } + const CMatrix44f world = unit->GetTransformMatrix(true); + const float rot[9] = {world.m[0], world.m[1], world.m[2], world.m[4], world.m[5], world.m[6], world.m[8], world.m[9], world.m[10]}; + if (std::memcmp(rot, st.rot, sizeof(rot)) != 0) { std::memcpy(st.rot, rot, sizeof(rot)); st.rotDirty = true; st.rotFirst = -1; } + for (size_t i = 0; i < pieces.size(); ++i) { + const auto& piece = pieces[i]; + PieceState& p = st.pieces[i]; + const float3& pos = piece.GetPosition(); const float3& ang = piece.GetRotation(); + const float raw[7] = {pos.x, pos.y, pos.z, ang.x, ang.y, ang.z, piece.GetScaling()}; + if (std::memcmp(raw, p.raw, sizeof(raw)) != 0) { + // Piece space only (the legacy stream composed model space here for every piece of every unit). + std::memcpy(p.raw, raw, sizeof(raw)); + // Keep the matrix alive: a pointer into ToMatrix()'s temporary dangles after this statement + // (that bug sent freed stack memory as piece matrices: stretched, skewed pieces). + const CMatrix44f local = piece.CalcPieceSpaceTransform(pos, ang, raw[6]).ToMatrix(); + const float* m = local.m; + const float m12[12] = {m[0], m[1], m[2], m[4], m[5], m[6], m[8], m[9], m[10], m[12], m[13], m[14]}; + if (std::memcmp(m12, p.m, sizeof(m12)) != 0) { std::memcpy(p.m, m12, sizeof(m12)); p.dirty = true; p.first = -1; } + } + const uint32_t visible = uint32_t(piece.GetScriptVisible()); + if (visible != p.visible) { p.visible = visible; p.dirty = true; p.first = -1; } + } + // Delivery: an item sent in every slot since `first` is known to the page once it consumed one of them. + bool sendStruct = false; + if (st.structDirty) { + if (st.structFirst >= 0 && acknowledged >= st.structFirst) st.structDirty = false; + else { sendStruct = true; if (st.structFirst < 0) st.structFirst = slotSeq; } + } + bool sendRot = false; + if (st.rotDirty) { + if (st.rotFirst >= 0 && acknowledged >= st.rotFirst) st.rotDirty = false; + else { sendRot = true; if (st.rotFirst < 0) st.rotFirst = slotSeq; } + } + uint16_t included = 0; + for (PieceState& p: st.pieces) { + if (!p.dirty) continue; + if (p.first >= 0 && acknowledged >= p.first) { p.dirty = false; continue; } + if (p.first < 0) p.first = slotSeq; + ++included; + } + if (sendRot) flags |= FLAG_ROTATION; + if (sendStruct) flags |= FLAG_STRUCTURE; + out.Put(id); out.Put(uint16_t(def)); out.Put(uint8_t(unit->team)); out.Put(flags); out.Put(uint16_t(pieces.size())); out.Put(included); + if (sendStruct) for (const auto& piece: pieces) out.Put(uint16_t(piece.parent ? piece.parent->GetLModelPieceIndex() : 0xffff)); + if (sendStruct && (pieces.size() & 1)) out.Put(uint16_t(0)); + if (sendRot) out.Bytes(st.rot, sizeof(st.rot)); + for (size_t i = 0; i < st.pieces.size() && included > 0; ++i) { + const PieceState& p = st.pieces[i]; + if (!p.dirty || p.first < 0) continue; + out.Put(uint16_t(i)); out.Put(uint16_t(p.visible)); out.Bytes(p.m, sizeof(p.m)); + } + if (sendStruct || sendRot || included > 0) withData += 1; + pieceRecords += included; + ++count; + if (out.overflow) break; + } + if (out.overflow) { + // Nothing of this slot reaches the page: every chain started here must restart. + for (CUnit* unit: units) { + if (size_t(unit->id) >= states.size()) continue; + UnitState& st = states[unit->id]; + if (st.rotFirst == slotSeq) st.rotFirst = -1; + if (st.structFirst == slotSeq) st.structFirst = -1; + for (PieceState& p: st.pieces) if (p.first == slotSeq) p.first = -1; + } + return false; + } + const uint32_t slotHeader[] = {0x31535057, uint32_t(slotSeq), uint32_t(gs->frameNum), count, uint32_t(out.at), uint32_t(viewKnown), uint32_t(std::min(legacy, 4294967295.0)), 0}; + static_assert(sizeof(slotHeader) == SLOT_HEADER_BYTES); + std::memcpy(out.base, slotHeader, sizeof(slotHeader)); + header->stats[0] += 1; header->stats[1] += double(out.at); header->stats[2] += legacy; + header->stats[3] += withData; header->stats[4] += pieceRecords; header->stats[5] += culled; header->stats[6] += lodSkipped; + publishedCameraSeq = cameraSeq; + // Publish: hand the written slot to the page, take the previous middle slot as the next back slot. + back = __atomic_exchange_n(&header->middle, back | 4, __ATOMIC_ACQ_REL) & 3; + return true; +} + +static void Publish(const std::vector& units) +{ + if (block == nullptr) Allocate(0); + if (block == nullptr) return; + const int32_t slotSeq = ++seq; + for (int attempt = 0; attempt < 4; ++attempt) { + if (Write(units, slotSeq)) return; + // Units are pending again (chains reset); a larger block gets a fresh triple buffer. + const size_t pieces = std::accumulate(units.begin(), units.end(), size_t(0), [](size_t n, const CUnit* u) { return n + u->localModel.pieces.size(); }); + Allocate(uint32_t(SLOT_HEADER_BYTES + units.size() * 52 + pieces * 54 + 4096)); + } +} + +// While the game is paused no frames are published, but the page's camera can still move: republish the +// 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 (__atomic_load_n(&header->cameraSeq, __ATOMIC_ACQUIRE) == publishedCameraSeq) return; + Publish(units()); +} + +} // namespace WebbarPoseMailbox --- a/rts/Game/WebbarReports.h +++ b/rts/Game/WebbarReports.h @@ -11,6 +11,7 @@ #include "Sim/Features/FeatureMemPool.h" #include "Sim/Projectiles/ProjectileMemPool.h" #include "Sim/Weapons/WeaponMemPool.h" +#include "WebbarLossCauses.h" static_assert(sizeof(TeamStatistics) == 80); static bool webbarFinalStatsSent = false; @@ -39,6 +40,17 @@ const uint32_t header[] = {0x31545357, uint32_t(gs->frameNum), count, uint32_t(final)}; std::memcpy(packet.data(), header, 16); MAIN_THREAD_EM_ASM({ if (Module['webbarTeamStats']) Module['webbarTeamStats'](HEAPU8.slice($0, $0 + $1).buffer); }, packet.data(), packet.size()); + // Bit 23: removals by cause for the same teams (WebbarLossCauses.h). WLC1 {magic, frame, count, + // final | causes << 8} + count x {u32 team, u32 counts[causes]}. + std::vector causes = {0x31434c57, uint32_t(gs->frameNum), 0, uint32_t(final) | (uint32_t(WebbarLossCauses::CAUSES) << 8)}; + for (int t = 0; t < teamHandler.ActiveTeams() && t < MAX_TEAMS; ++t) { + if (t == teamHandler.GaiaTeamID()) continue; + if (!final && !gu->spectatingFullView && !teamHandler.AlliedTeams(t, gu->myTeam)) continue; + causes.push_back(uint32_t(t)); + for (const uint32_t n: WebbarLossCauses::Counts()[t]) causes.push_back(n); + ++causes[2]; + } + MAIN_THREAD_EM_ASM({ if (Module['webbarLossCauses']) Module['webbarLossCauses'](HEAPU8.slice($0, $0 + $1).buffer); }, causes.data(), causes.size() * 4); } // EB1 own/allied unit reports for HUD widgets (rank icons, commander-hurt, self-destruct). --- a/rts/Game/WebbarShields.h +++ b/rts/Game/WebbarShields.h @@ -19,7 +19,8 @@ std::vector records; uint32_t dropped = 0; for (const CUnit* unit: unitHandler.GetActiveUnits()) { - if (unit->isDead || !WebbarVisible(unit)) continue; + // M5 EB4: only units with a shield weapon (the rules lookups below cost two hash lookups per unit). + if (unit->unitDef->shieldWeaponDef == nullptr || unit->isDead || !WebbarVisible(unit)) continue; const auto rule = [&](const char* name, float fallback) { const auto it = unit->modParams.find(name); if (it == unit->modParams.end()) return fallback; --- a/rts/Rendering/Common/ModelDrawerData.h +++ b/rts/Rendering/Common/ModelDrawerData.h @@ -224,6 +224,11 @@ o->previousDrawFlag = o->drawFlag; UpdateObjectDrawFlags(o); +#if defined(__EMSCRIPTEN__) + // WebBAR (parity plan M5, EB4): the engine never draws (CGame::Draw); draw flags and positions stay + // current for unsynced Lua, but the GPU transform and uniform uploads are skipped. + return; +#endif if (o->alwaysUpdateMat || (o->drawFlag > DrawFlags::SO_NODRAW_FLAG && o->drawFlag < DrawFlags::SO_DRICON_FLAG)) UpdateObjectTrasform(o); --- a/rts/Sim/Units/Scripts/UnitScriptEngine.cpp +++ b/rts/Sim/Units/Scripts/UnitScriptEngine.cpp @@ -132,11 +132,19 @@ { SCOPED_TIMER("CUnitScriptEngine::Tick"); +#ifdef __EMSCRIPTEN__ + // WebBAR (M5): split of Sim::Script for the performance reports. + { SCOPED_TIMER("Sim::Script::Cob"); cobEngine->Tick(deltaTime); } +#else cobEngine->Tick(deltaTime); +#endif // tick all (COB or LUS) script instances that have registered themselves as animating { ZoneScopedN("CUnitScriptEngine::Tick(MT)"); +#ifdef __EMSCRIPTEN__ + SCOPED_TIMER("Sim::Script::Anims"); +#endif // setting currentScript = animating[i]; is not required here, only in ST section below for_mt(0, animating.size(), [&](const int i) { @@ -145,6 +153,9 @@ } { ZoneScopedN("CUnitScriptEngine::Tick(ST)"); +#ifdef __EMSCRIPTEN__ + SCOPED_TIMER("Sim::Script::AnimDone"); +#endif uint32_t cs = 0; for (size_t i = 0; i < animating.size(); /*NO-OP*/) { @@ -167,5 +178,9 @@ Sync::Assert(cs, "animating"); } +#ifdef __EMSCRIPTEN__ + { SCOPED_TIMER("Sim::Script::Deferred"); cobEngine->RunDeferredCallins(); } +#else cobEngine->RunDeferredCallins(); +#endif } --- a/rts/Sim/Units/Unit.cpp +++ b/rts/Sim/Units/Unit.cpp @@ -6,6 +6,7 @@ #ifdef __EMSCRIPTEN__ #include "Game/WebbarCloakEvents.h" #include "Game/WebbarWorkAudio.h" +#include "Game/WebbarLossCauses.h" #endif #include "UnitHandler.h" #include "UnitDefHandler.h" @@ -490,6 +491,9 @@ return; isDead = true; +#ifdef __EMSCRIPTEN__ + WebbarLossCauses::Removed(this, attacker, selfDestruct, reclaimed, beingBuilt); +#endif // release attached units ReleaseTransportees(attacker, selfDestruct, reclaimed); @@ -1354,6 +1358,9 @@ script->WorldHitByWeapon(-(impulse * impulseMult).SafeNormalize2D(), weaponDefID, /*inout*/ baseDamage); ApplyImpulse((impulse * impulseMult) / mass); +#ifdef __EMSCRIPTEN__ + if (baseDamage > 0.0f && !isParalyzer) WebbarLossCauses::Damaged(this, attacker); +#endif ApplyDamage(attacker, damages, baseDamage, experienceMod); { --- a/rts/System/Threading/ThreadPool.cpp +++ b/rts/System/Threading/ThreadPool.cpp @@ -81,6 +81,29 @@ static _threadlocal int threadnum(0); +#ifdef __EMSCRIPTEN__ +// WebBAR (parity plan M5, EB2): worker wake-up policy in the browser and Node WASM engines. +// Upstream wakes sleeping workers only when *all* of them sleep, and only a dequeue from the +// global queue passes the wake-up on; for_mt stores its group in each worker's own queue, so a +// worker that backed off to its 30 ms maximum sleep missed whole frames of parallel work (the +// calling thread did the slices alone). In WASM a wake is one Atomics.notify, so wake on every +// push and cap the back-off near 1 ms. Environment overrides (benchmarks only): +// WEBBAR_POOL_WAKE=0|1 wake sleeping workers on every push (default 1) +// WEBBAR_POOL_SLEEP_US=n maximum worker back-off sleep in microseconds (default 1000; 50..30000) +// Scheduling only: which thread runs a slice never changes results (determinism is qualified +// across pool sizes 1-4). +#include +#include +static bool WebbarPoolWake() { + static const bool wake = [] { const char* v = std::getenv("WEBBAR_POOL_WAKE"); return v == nullptr || std::atoi(v) != 0; }(); + return wake; +} +static int WebbarPoolSleepUs() { + static const int us = [] { const char* v = std::getenv("WEBBAR_POOL_SLEEP_US"); return v == nullptr ? 1000 : std::clamp(std::atoi(v), 50, 30000); }(); + return us; +} +#endif + #ifndef UNITSYNC // if enabled, allows OpenGL calls from ThreadPool tasks // so certain logic (e.g. loading models) can be written @@ -251,7 +274,11 @@ // (see NotifyWorkerThreads) // NOTE: the spin-time has to be *short* to avoid biasing thread 1's workload const auto ourSpinTime = spring_time::fromMicroSecs(30 * (tid == 1)); +#ifdef __EMSCRIPTEN__ + const auto maxSleepTime = spring_time::fromMicroSecs(WebbarPoolSleepUs()); +#else const auto maxSleepTime = spring_time::fromMilliSecs(30); +#endif while (!exitFlags[tid]) { const auto spinlockEnd = spring_now() + ourSpinTime; @@ -356,7 +383,11 @@ if (taskGroup->IsAsyncTask()) return; +#ifdef __EMSCRIPTEN__ + NotifyWorkerThreads(WebbarPoolWake(), false); +#else NotifyWorkerThreads(false, false); +#endif #else NotifyWorkerThreads(false, taskGroup->IsAsyncTask()); #endif