--- /dev/null +++ b/rts/Game/WebbarGroundTrackPolicy.h @@ -0,0 +1,564 @@ +/* This file is part of the Spring engine (GPL v2 or later), see LICENSE.html */ +#pragma once +#include +#include +#include +#include +#include +#include +#include +#include "Rendering/Env/Decals/GroundDecal.h" +#include "Rendering/Common/UpdateList.h" +#include "Map/Ground.h" +#include "Map/MapInfo.h" +#include "Map/ReadMap.h" +#include "Sim/MoveTypes/MoveType.h" +#include "System/UnorderedMap.hpp" +#include "System/FileSystem/FileSystem.h" +#include "System/StringUtil.h" +class GhostSolidObject; +class CColorMap; +namespace WebbarOriginalGroundTracks { +using std::string; +static inline std::string GetExtraTextureName(const std::string& mainTex) { + RECOIL_DETAILED_TRACY_ZONE; + auto dotPos = mainTex.find_last_of("."); + return mainTex.substr(0, dotPos) + "_normal" + (dotPos == string::npos ? "" : mainTex.substr(dotPos)); +} +static inline bool CanReceiveTracks(const float3& pos) +{ + //ZoneScoped; + // calculate typemap-index + const int tmz = pos.z / (SQUARE_SIZE * 2); + const int tmx = pos.x / (SQUARE_SIZE * 2); + const int tmi = std::clamp(tmz * mapDims.hmapx + tmx, 0, mapDims.hmapx * mapDims.hmapy - 1); + + const uint8_t* typeMap = readMap->GetTypeMapSynced(); + const uint8_t typeNum = typeMap[tmi]; + + return mapInfo->terrainTypes[typeNum].receiveTracks; +} +// Generated from pinned original GroundDecalHandler CPU methods. No shader, +// texture upload, RNG, synced writes or command delivery occurs in this class. +class Policy { +public: + struct UnitMinMaxHeight {float min=std::numeric_limits::max(),max=std::numeric_limits::lowest();}; + using DecalOwner=std::variant; + spring::unordered_map> decalOwners; + spring::unordered_map unitMinMaxHeights; + spring::unordered_map idToPos; + spring::unordered_map>> idToCmInfo; + std::vector decals; + UpdateList decalsUpdateList; + uint32_t nextId=0; + std::vector freeIds; + static constexpr auto DECAL_LEVEL_MULT=3; + static constexpr uint32_t TRACKS_UPDATE_RATE=4u; + Policy(){decals.reserve(1<<16);decalsUpdateList.Reserve(decals.capacity());} + bool GetDrawDecals()const{return true;} + static float4 Material(const std::string& name){ + static constexpr std::array names={"arm_acv_tracks_2","armacv_tracks","armbull_tracks","armcroc_tracks","armgremlin_tracks","armpincer_tracks","armsam_tracks","armseer_tracks","armstump_tracks","armyork_tracks","bigfoot","corparrowtracks","corwidetracks","raptortrack","raptortrackpointy"}; + // This is material addressing, not an approximation of native atlas UVs. + const auto normalized=FileSystem::GetBasename(StringToLower(name)); + for(size_t i=0;ipos);} + void MoveSolidObject(const CSolidObject*,const float3&); + void RemoveSolidObject(const CSolidObject*,const GhostSolidObject*); + void SetUnitLeaveTracks(CUnit*,bool); + void AddTrack(const CUnit*,const float3&,bool forceEval=false); + void CompactDecalsVector(int); + void GameFramePost(int); +}; + +uint32_t Policy::GetNextId() +{ + RECOIL_DETAILED_TRACY_ZONE; + if (freeIds.empty()) + return ++nextId; + + const auto newId = freeIds.back(); freeIds.pop_back(); + return newId; + + return 0; +} + +void Policy::MoveSolidObject(const CSolidObject* object, const float3& pos) +{ + RECOIL_DETAILED_TRACY_ZONE; + if (!GetDrawDecals()) + return; + + const SolidObjectDecalDef& decalDef = object->GetDef()->decalDef; + + if (!decalDef.useGroundDecal || decalDef.groundDecalTypeName.empty()) + return; + + int sizex = decalDef.groundDecalSizeX * SQUARE_SIZE; + int sizey = decalDef.groundDecalSizeY * SQUARE_SIZE; + + const float2 midPoint = float2(static_cast(pos.x / SQUARE_SIZE), static_cast(pos.z / SQUARE_SIZE)) * SQUARE_SIZE; + const float midPointHeight = CGround::GetHeightReal(midPoint.x, midPoint.y); + + auto posTL = midPoint + float2(-sizex, -sizey); + auto posTR = midPoint + float2( sizex, -sizey); + auto posBR = midPoint + float2( sizex, sizey); + auto posBL = midPoint + float2(-sizex, sizey); + + const float height = argmax( + math::fabs(midPointHeight - CGround::GetHeightReal(posTL.x, posTL.y)), + math::fabs(midPointHeight - CGround::GetHeightReal(posTR.x, posTR.y)), + math::fabs(midPointHeight - CGround::GetHeightReal(posBR.x, posBR.y)), + math::fabs(midPointHeight - CGround::GetHeightReal(posBL.x, posBL.y)) + ) + 25.0f; + + const auto createFrame = static_cast(std::max(gs->frameNum, 0)); + + if (const auto doIt = decalOwners.find(object); doIt != decalOwners.end()) { + assert(doIt->second < decals.size()); + auto& decal = decals[doIt->second]; + decal.posTL = posTL; + decal.posTR = posTR; + decal.posBR = posBR; + decal.posBL = posBL; + decal.height = height; + decalsUpdateList.SetUpdate(doIt->second); + return; + } + + const auto& decal = decals.emplace_back(GroundDecal{ + .refHeight = 0.0f, + .minHeight = 0.0f, + .maxHeight = 0.0f, + .forceHeightMode = 0.0f, + .posTL = posTL, + .posTR = posTR, + .posBR = posBR, + .posBL = posBL, + .texMainOffsets = Material((decalDef.groundDecalTypeName)), + .texNormOffsets = Material(GetExtraTextureName(decalDef.groundDecalTypeName)), + .alpha = 1.0f, + .alphaFalloff = 0.0f, + .glow = 0.0f, + .glowFalloff = 0.0f, + .rot = -object->buildFacing * math::HALFPI, + .height = height, + .dotElimExp = 0.0f, + .cmAlphaMult = 1.0f, + .createFrameMin = createFrame, + .createFrameMax = createFrame, + .uvWrapDistance = 0.0f, + .uvTraveledDistance = 0.0f, + .forcedNormal = float3{}, + .visMult = 1.0f, + .info = GroundDecal::TypeID{.type = static_cast(GroundDecal::Type::DECAL_PLATE), .id = GetNextId() }, + .tintColor = SColor{0.5f, 0.5f, 0.5f, 0.5f}, + .glowColorMap = { SColor{0.0f, 0.0f, 0.0f, 0.0f}, SColor{0.0f, 0.0f, 0.0f, 0.0f} } + }); + + decalsUpdateList.EmplaceBackUpdate(); + idToPos[decal.info.id] = decals.size() - 1; + decalOwners[object] = decals.size() - 1; +} + +void Policy::RemoveSolidObject(const CSolidObject* object, const GhostSolidObject* gb) +{ + RECOIL_DETAILED_TRACY_ZONE; + assert(object); + + const auto doIt = decalOwners.find(object); + if (doIt == decalOwners.end()) { + // it's ok for an object to not have any decals + return; + } + + const auto pos = doIt->second; + decalOwners.erase(doIt); + + if (gb) { + // gb is the new owner + decalOwners.emplace(gb, pos); + return; + } + + assert(pos < decals.size()); + auto& decayingDecal = decals[pos]; + + // we only care about DECAL_PLATE decals below + if (decayingDecal.info.type != static_cast(GroundDecal::Type::DECAL_PLATE)) { + return; + } + + const auto createFrame = static_cast(std::max(gs->frameNum, 0)); + + decayingDecal.alphaFalloff = object->GetDef()->decalDef.groundDecalDecaySpeed / GAME_SPEED; + decayingDecal.createFrameMin = createFrame; + decayingDecal.createFrameMax = createFrame; + + decalsUpdateList.SetUpdate(pos); +} + +void Policy::SetUnitLeaveTracks(CUnit* unit, bool leaveTracks) +{ + //ZoneScoped; + // The original drawer already applied unit->leaveTracks; observe only. + if (!leaveTracks) { + if (auto it = decalOwners.find(unit); it != decalOwners.end()) { + auto& mm = unitMinMaxHeights[unit->id]; + + decalOwners.erase(it); // restart with new decal next time + mm = {}; + } + } + else { + AddTrack(unit, unit->pos, false); + } +} + +void Policy::AddTrack(const CUnit* unit, const float3& newPos, bool forceEval) +{ + RECOIL_DETAILED_TRACY_ZONE; + if (!GetDrawDecals()) + return; + + if (!unit->leaveTracks) + return; + + if (!gu->spectatingFullView && !unit->IsInLosForAllyTeam(gu->myAllyTeam)) + return; + + const UnitDef* unitDef = unit->unitDef; + + if (!unitDef->IsGroundUnit()) + return; + + const SolidObjectDecalDef& decalDef = unitDef->decalDef; + + const float trackLifeTime = DECAL_LEVEL_MULT * GAME_SPEED * decalDef.trackDecalStrength; + if (trackLifeTime <= 0.0f) + return; + + const float3 decalPos = newPos + unit->frontdir * decalDef.trackDecalOffset; + + auto& mm = unitMinMaxHeights[unit->id]; + + if (!CanReceiveTracks(decalPos) || (unit->IsInWater() && !unit->IsOnGround())) { + decalOwners.erase(unit); // restart with new decal next time + mm = {}; + return; + } + + const float2 decalPos2 = float2(decalPos.x, decalPos.z); + const float2 wc = float2( + unit->rightdir.x * decalDef.trackDecalWidth * 0.5f, + unit->rightdir.z * decalDef.trackDecalWidth * 0.5f + ); + + const auto createFrameInt = static_cast(std::max(gs->frameNum, 0)); + const auto createFrame = static_cast(createFrameInt); + const auto doIt = decalOwners.find(unit); + if (doIt == decalOwners.end()) { + // new decal + + // the decal texture name is stored as a basename + const auto& mainName = FileSystem::GetBasename(StringToLower(decalDef.trackDecalTypeName)); + const auto normName = GetExtraTextureName(mainName); + + const float alphaDecay = 1.0f / trackLifeTime; + + const auto& decal = decals.emplace_back(GroundDecal{ + .refHeight = 0.0f, + .minHeight = 0.0f, + .maxHeight = 0.0f, + .forceHeightMode = 0.0f, + .posTL = decalPos2 - wc, + .posTR = decalPos2 - wc, + .posBR = decalPos2 + wc, + .posBL = decalPos2 + wc, + .texMainOffsets = Material(mainName), + .texNormOffsets = Material(normName), + .alpha = 1.0f, + .alphaFalloff = alphaDecay, + .glow = 0.0f, + .glowFalloff = 0.0f, + .rot = 0.0f, + .height = 0.0f, + .dotElimExp = 0.0f, + .cmAlphaMult = 1.0f, + .createFrameMin = createFrame, + .createFrameMax = createFrame, + .uvWrapDistance = decalDef.trackDecalWidth * decalDef.trackDecalStretch, + .uvTraveledDistance = 0.0f, + .forcedNormal = float3{unit->updir}, + .visMult = 1.0f, + .info = GroundDecal::TypeID{.type = static_cast(GroundDecal::Type::DECAL_TRACK), .id = GetNextId() }, + .tintColor = SColor{0.5f, 0.5f, 0.5f, 0.5f}, + .glowColorMap = { SColor{0.0f, 0.0f, 0.0f, 0.0f}, SColor{0.0f, 0.0f, 0.0f, 0.0f} } + }); + + mm = {}; + + decalOwners[unit] = decals.size() - 1; + idToPos[decal.info.id] = decals.size() - 1; + decalsUpdateList.EmplaceBackUpdate(); + + return; + } + + float decalHeight = CGround::GetHeightReal(decalPos.x, decalPos.z, false); + mm.min = std::min(mm.min, decalHeight); + mm.max = std::max(mm.max, decalHeight); + + if (!forceEval && createFrameInt % TRACKS_UPDATE_RATE != 0) + return; + + assert(doIt->second < decals.size()); + GroundDecal& oldDecal = decals[doIt->second]; + + // just updated + if (oldDecal.createFrameMax == createFrame) + return; + + // check if the unit is standing still + if (oldDecal.createFrameMax + TRACKS_UPDATE_RATE < createFrame) { + decalOwners.erase(unit); + mm = {}; + return; + } + + const float2 posL = (oldDecal.posTL + oldDecal.posBL) * 0.5f; + const float2 posR = (oldDecal.posTR + oldDecal.posBR) * 0.5f; + + const float2 dirO = (posR - posL).SafeNormalize(); + const float2 dirN = (decalPos2 - posR).SafeNormalize(); + + // dirN was ~zero + if (dirN.Dot(dirN) < 0.25f) + return; + + // the old decal had zero len (was a new track decal) or similar dir and the unit updir is same-ish as before + if ((dirO.Dot(dirO) == 0.0f || dirO.Dot(dirN) >= 0.9999f) && oldDecal.forcedNormal.dot(unit->updir) >= 0.99f) { + oldDecal.posTR = decalPos2 - wc; + oldDecal.posBR = decalPos2 + wc; + oldDecal.createFrameMax = createFrame; + + const float2 midPointDist = (oldDecal.posTL + oldDecal.posTR + oldDecal.posBR + oldDecal.posBL) * 0.25f; + const float midPointHeight = CGround::GetHeightReal(midPointDist.x, midPointDist.y, false); + oldDecal.height = argmax(mm.max - midPointHeight, midPointHeight - mm.min) + 25.0f; + + decalsUpdateList.SetUpdate(doIt->second); + return; + } + + // new decal, starting where the previous ended + auto& newDecal = decals.emplace_back(GroundDecal{ + .refHeight = 0.0f, + .minHeight = 0.0f, + .maxHeight = 0.0f, + .forceHeightMode = 0.0f, + .posTL = oldDecal.posTR, + .posTR = decalPos2 - wc, + .posBR = decalPos2 + wc, + .posBL = oldDecal.posBR, + .texMainOffsets = oldDecal.texMainOffsets, + .texNormOffsets = oldDecal.texNormOffsets, + .alpha = oldDecal.alpha, + .alphaFalloff = oldDecal.alphaFalloff, + .glow = 0.0f, + .glowFalloff = 0.0f, + .rot = 0.0f, + .height = oldDecal.height, //also set later + .dotElimExp = oldDecal.dotElimExp, + .cmAlphaMult = oldDecal.cmAlphaMult, + .createFrameMin = oldDecal.createFrameMax, + .createFrameMax = createFrame, + .uvWrapDistance = decalDef.trackDecalWidth * decalDef.trackDecalStretch, + .uvTraveledDistance = oldDecal.uvTraveledDistance + posL.Distance(posR)/*oldDecal.posTL.Distance(oldDecal.posTR)*/, + .forcedNormal = float3{ unit->updir }, + .visMult = 1.0f, + .info = GroundDecal::TypeID{.type = static_cast(GroundDecal::Type::DECAL_TRACK), .id = GetNextId() }, + .tintColor = SColor{0.5f, 0.5f, 0.5f, 0.5f}, + .glowColorMap = { SColor{0.0f, 0.0f, 0.0f, 0.0f}, SColor{0.0f, 0.0f, 0.0f, 0.0f} } + }); + + const float2 midPointDist = (newDecal.posTL + newDecal.posTR + newDecal.posBR + newDecal.posBL) * 0.25f; + const float midPointHeight = CGround::GetHeightReal(midPointDist.x, midPointDist.y, false); + newDecal.height = argmax(newDecal.height, mm.max - midPointHeight, midPointHeight - mm.min, 25.0f); + mm = {}; + + // replace the old entry + decalOwners[unit] = decals.size() - 1; + + idToPos[newDecal.info.id] = decals.size() - 1; + decalsUpdateList.EmplaceBackUpdate(); +} + +void Policy::CompactDecalsVector(int frameNum) +{ + RECOIL_DETAILED_TRACY_ZONE; + if (frameNum % 300 != 0) + return; + + if (decals.empty()) + return; + + // only bother with the following code, if number of items is big enough + if (decals.size() < decals.capacity() >> 6) + return; + + size_t numToDelete = 0; + for (auto& decal : decals) { + if (!decal.IsValid()) { + numToDelete++; + continue; + } + const auto targetExpirationFrame = static_cast(decal.alpha / std::max(decal.alphaFalloff, 1e-6f)); + if (decal.info.type != static_cast(GroundDecal::Type::DECAL_LUA) && frameNum - decal.createFrameMax > targetExpirationFrame) { + decal.MarkInvalid(); + numToDelete++; + } + } + + if (numToDelete == 0) + return; + + // resort if number of expired items > 25.0% + static constexpr float RESORT_THRESHOLD = 1.0f / 4.0f; + if (static_cast(decals.size()) / static_cast(numToDelete) <= RESORT_THRESHOLD) + return; + +#if 0 + LOG("DH:CompactDecalsVector[1](fn=%d) Decals.size()=%u", frameNum, static_cast(decals.size())); + for (int cnt = 0; const auto & [owner, offset] : decalOwners) { + const void* ptr = std::holds_alternative(owner) ? static_cast(std::get(owner)) : nullptr; + int id = (ptr != nullptr) ? std::get(owner)->id : -1; + + LOG("DH:CompactDecalsVector[1] [cnt=%d][ptr=%p][id=%d]=[pos=%u]", + cnt++, + ptr, + id, + static_cast(offset) + ); + } +#endif + + // temporary store the id --> DecalOwner relationship, + // for the convinience to restore decalOwners correctness, + // after the compaction is complete + spring::unordered_map tmpOwnerToId; + + // Remove owners of expired items + for (const auto& [owner, pos] : decalOwners) { + assert(pos < decals.size()); + if (const auto& decal = decals[pos]; decal.IsValid()) { + const uint32_t id = decal.info.id; //can't use bitfield directly below + tmpOwnerToId.emplace(id, owner); + } + } + + // clean to restore it later + decalOwners.clear(); + + // group all expired items towards the end of the vector + // Lua items are not considered expired + const auto expIt = std::stable_partition(decals.begin(), decals.end(), [](const GroundDecal& decal) { + return decal.IsValid(); + }); + + // remove expired items from idToCmInfo map + // and push expired ids to the freeIds vector + for (auto decalIt = expIt; decalIt != decals.end(); ++decalIt) { + freeIds.push_back(decalIt->info.id); + + if (auto it = idToCmInfo.find(decalIt->info.id); it != idToCmInfo.end()) + idToCmInfo.erase(it); + } + + // remove expired decals + decals.resize(decals.size() - numToDelete); + decalsUpdateList.Resize(decals.size()); + + idToPos.clear(); + for (size_t i = 0; i < decals.size(); ++i) { + idToPos.emplace(decals[i].info.id, i); + } + + // update the new positions of shrunk decals vector + for (const auto& [id, owner] : tmpOwnerToId) { + const auto ipIt = idToPos.find(id); + if (ipIt == idToPos.end()) { + assert(false); + continue; + } + + decalOwners.emplace(owner, ipIt->second); + } + + +#if 0 + LOG("DH:CompactDecalsVector[2](fn=%d) Decals.size()=%u", frameNum, static_cast(decals.size())); + for (int cnt = 0; const auto & [owner, offset] : decalOwners) { + const void* ptr = std::holds_alternative(owner) ? static_cast(std::get(owner)) : nullptr; + int id = (ptr != nullptr) ? std::get(owner)->id : -1; + + LOG("DH:CompactDecalsVector[2] [cnt=%d][ptr=%p][id=%d]=[pos=%u]", + cnt++, + ptr, + id, + static_cast(offset) + ); + } +#endif +} + +void Policy::GameFramePost(int frameNum) +{ + RECOIL_DETAILED_TRACY_ZONE; +#if 0 + LOG("DH:GD(fn=%d) Decals.size()=%u", frameNum, static_cast(decals.size())); + for (int cnt = 0; const auto & [owner, offset] : decalOwners) { + const void* ptr = std::holds_alternative(owner) ? static_cast(std::get(owner)) : nullptr; + int id = (ptr != nullptr) ? std::get(owner)->id : -1; + + LOG("DH:GD [cnt=%d][ptr=%p][id=%d]=[pos=%u]", + cnt++, + ptr, + id, + static_cast(offset) + ); + } +#endif + // can't call AddTrack() directly in the loop below as it messes with decalOwners iteration order + std::vector deferredTrackUpdate; + + for (const auto& [owner, _] : decalOwners) { + if (!std::holds_alternative(owner)) + continue; + + const CUnit* unit = dynamic_cast(std::get(owner)); + if (unit == nullptr) + continue; + + if (unit->moveType == nullptr) + continue; + + if (unit->moveType->progressState == AMoveType::ProgressState::Active) + continue; + + deferredTrackUpdate.emplace_back(unit); + } + + for (const auto* unit : deferredTrackUpdate) { + // call this one for stopped units, as AddTrack() is only called natively for moving units + // This will be called several times before it's erased from decalOwners, not a big deal + AddTrack(unit, unit->pos, true); + } + + if (frameNum % 16 == 0) { + CompactDecalsVector(frameNum); + } +} + +} --- /dev/null +++ b/rts/Game/WebbarNativeGroundTracks.h @@ -0,0 +1,74 @@ +/* This file is part of the Spring engine (GPL v2 or later), see LICENSE.html */ +#pragma once +#include "WebbarGroundTrackPolicy.h" +#include "WebbarGroundTrackEvents.h" + +namespace WebbarNativeGroundTracks { +class Reader final:public CEventClient,public WebbarOriginalGroundTracks::Policy { +public: + uint32_t epoch=0; + uint32_t version=1; + bool reported=false; + std::array perspective{-2,-2,-2,-2,-2}; + Reader():CEventClient("[WebBAR original ground tracks]",314159,false){ + Perspective();eventHandler.AddClient(this); + WebbarGroundTrackEvents::Attach(this,[](void* self,CUnit* unit,bool enabled){static_cast(self)->SetUnitLeaveTracks(unit,enabled);}); + } + ~Reader()override{WebbarGroundTrackEvents::Detach(this);eventHandler.RemoveClient(this);} + bool WantsEvent(const std::string& name)override{ + return name=="RenderUnitCreated"||name=="RenderUnitDestroyed"||name=="RenderFeatureCreated"||name=="RenderFeatureDestroyed"||name=="FeatureMoved"||name=="UnitMoved"||name=="UnitLoaded"||name=="UnitUnloaded"||name=="GameFramePost"; + } + bool GetFullRead()const override{return true;} + int GetReadAllyTeam()const override{return AllAccessTeam;} + void Perspective(){ + const std::array actual{gu->myPlayerNum,gu->myTeam,gu->myAllyTeam,int(gu->spectating),int(gu->spectatingFullView)}; + if(actual!=perspective){perspective=actual;if(++epoch==0)++epoch;} + } + void RenderUnitCreated(const CUnit* unit,int)override{AddSolidObject(unit);} + void RenderUnitDestroyed(const CUnit* unit)override{ + unitMinMaxHeights.erase(unit->id);RemoveSolidObject(unit,nullptr); + } + void RenderFeatureCreated(const CFeature* feature)override{AddSolidObject(feature);} + void RenderFeatureDestroyed(const CFeature* feature)override{RemoveSolidObject(feature,nullptr);} + void FeatureMoved(const CFeature* feature,const float3&)override{MoveSolidObject(feature,feature->pos);} + void UnitMoved(const CUnit* unit)override{AddTrack(unit,unit->pos);} + void UnitLoaded(const CUnit* unit,const CUnit*)override{RemoveSolidObject(unit,nullptr);} + void UnitUnloaded(const CUnit* unit,const CUnit*)override{AddSolidObject(unit);} + void GameFramePost(int frame)override{Perspective();Policy::GameFramePost(frame);} +}; +static Reader* reader=nullptr; +static uint32_t generation=0; +static bool Enabled(){return std::getenv("WEBBAR_NATIVE_GROUND_TRACKS")&&std::getenv("WEBBAR_BROWSER")&&!std::getenv("WEBBAR_NETWORK");} +static void Prepare(){ + if(!Enabled()||gs->frameNum< -1)return; + if(!reader){if(++generation==0)++generation;reader=new Reader;} + else reader->Perspective(); +} +static void Free(){delete reader;reader=nullptr;} +static void Publish(const WebbarBeamDrawRequest& request,int32_t sequence,uint32_t drawEpoch){ + if(!Enabled()||!(request.flags&2u)||request.frame!=uint32_t(gs->frameNum))return; + Prepare();if(!reader||reader->reported)return; + // Optional WGT1 drawing state; bridge9, simulation and saved command format + // stay intact. UV words carry authenticated original material IDs; browser + // atlas addressing replaces them, while all native geometry/age bits survive. + size_t count=0;for(const auto& decal:reader->decals)if(decal.info.type==uint8_t(GroundDecal::Type::DECAL_TRACK))++count; + if(count>65536){reader->reported=true;MAIN_THREAD_EM_ASM({if(Module['webbarNativeGroundTrackError'])Module['webbarNativeGroundTrackError']('Original ground track drawing packet exceeds bounded transport');});return;} + if(reader->decalsUpdateList.NeedUpdate()){ + if(++reader->version==0)++reader->version; + reader->decalsUpdateList.ResetNeedUpdateAll(); + } + std::vector packet{0x31544757u,1,uint32_t(gs->frameNum),drawEpoch,uint32_t(sequence),uint32_t(count),160,reader->epoch, + uint32_t(gu->myPlayerNum),uint32_t(gu->myTeam),uint32_t(gu->myAllyTeam),uint32_t(gu->spectating)|(uint32_t(gu->spectatingFullView)<<1),request.flags,15,0,0}; + const float time[]={float(gs->frameNum),spring_tomsecs(globalRendering->grTime)*.001f,(gs->GetLuaSimFrame()+request.fraction)/GAME_SPEED,request.fraction}; + for(float value:time){uint32_t word;std::memcpy(&word,&value,4);packet.push_back(word);}packet.resize(24);packet[20]=reader->version;packet[21]=generation; + for(const auto& decal:reader->decals){ + if(decal.info.type!=uint8_t(GroundDecal::Type::DECAL_TRACK))continue; + static_assert(offsetof(GroundDecal,userDefined)==160); + const size_t at=packet.size();packet.resize(at+40);std::memcpy(packet.data()+at,&decal,160); + } + MAIN_THREAD_EM_ASM({if(Module['webbarNativeGroundTracks'])Module['webbarNativeGroundTracks'](HEAPU8.slice($0,$0+$1).buffer);},packet.data(),packet.size()*4); +} +} +static void PrepareWebbarNativeGroundTracks(){WebbarNativeGroundTracks::Prepare();} +static void FreeWebbarNativeGroundTracks(){WebbarNativeGroundTracks::Free();} +static void PublishWebbarNativeGroundTracks(const WebbarBeamDrawRequest& request,int32_t sequence,uint32_t epoch){WebbarNativeGroundTracks::Publish(request,sequence,epoch);} --- /dev/null +++ b/rts/Game/WebbarGroundTrackEvents.h @@ -0,0 +1,14 @@ +/* This file is part of the Spring engine (GPL v2 or later), see LICENSE.html */ +#pragma once +#include +class CUnit; +// Observe the existing unsynced control only after the original drawer applies +// it. The observer never changes the unit, permissions, arguments or Lua stack. +namespace WebbarGroundTrackEvents { +using Listener=void(*)(void*,CUnit*,bool); +inline void* owner=nullptr; +inline Listener listener=nullptr; +inline void Attach(void* next,Listener fn){assert(owner==nullptr);owner=next;listener=fn;} +inline void Detach(void* previous){if(owner==previous){owner=nullptr;listener=nullptr;}} +inline void Observe(CUnit* unit,bool enabled){if(listener)listener(owner,unit,enabled);} +} --- a/rts/Game/WebbarBrowser.h +++ b/rts/Game/WebbarBrowser.h @@ -126,6 +126,7 @@ #include "WebbarNativeEta.h" #include "WebbarNativeScum.h" #include "WebbarNativeExplosionDecals.h" +#include "WebbarNativeGroundTracks.h" #include "WebbarMetalRead.h" static void PublishWebbarPlayState() --- a/rts/Game/WebbarNativeBeams.h +++ b/rts/Game/WebbarNativeBeams.h @@ -366,6 +366,7 @@ static void PublishWebbarNativeDeferredLights(const WebbarBeamDrawRequest&, int32_t, uint32_t); static void PublishWebbarNativeLasers(const WebbarBeamDrawRequest&, int32_t, uint32_t); static void PublishWebbarNativeExplosionDecals(const WebbarBeamDrawRequest&, int32_t, uint32_t); +static void PublishWebbarNativeGroundTracks(const WebbarBeamDrawRequest&, int32_t, uint32_t); static void UpdateWebbarNativeBeams() { PrepareWebbarNativeBeams(); @@ -393,6 +394,7 @@ PublishWebbarNativeDeferredLights(request,sequence,webbarNativeBeams->epoch); PublishWebbarNativeLasers(request,sequence,webbarNativeBeams->epoch); PublishWebbarNativeExplosionDecals(request,sequence,webbarNativeBeams->epoch); + PublishWebbarNativeGroundTracks(request,sequence,webbarNativeBeams->epoch); if((request.flags & 2u) && request.frame == uint32_t(gs->frameNum)) PublishWebbarNativeEtaDraw(request.fraction,sequence,webbarNativeBeams->epoch); if((request.flags & 2u) && request.frame == uint32_t(gs->frameNum)) PublishWebbarNativeScumDraw(sequence); __atomic_store_n(&webbarBeamDrawMailbox.acknowledged,sequence,__ATOMIC_RELEASE); --- a/rts/Game/Game.cpp +++ b/rts/Game/Game.cpp @@ -303,6 +303,8 @@ static void PrepareWebbarNativeScum(); static void PrepareWebbarNativeExplosionDecals(); static void FreeWebbarNativeExplosionDecals(); +static void PrepareWebbarNativeGroundTracks(); +static void FreeWebbarNativeGroundTracks(); static void FreeWebbarNativeScum(); static void FreeWebbarNativeEta(); static void PrepareWebbarNativeBeams(); @@ -320,6 +322,7 @@ FreeWebbarNativeEta(); FreeWebbarNativeScum(); FreeWebbarNativeExplosionDecals(); + FreeWebbarNativeGroundTracks(); #endif ENTER_SYNCED_CODE(); LOG("[Game::%s][1]", __func__); @@ -931,6 +934,7 @@ PrepareWebbarNativeEta(); PrepareWebbarNativeScum(); PrepareWebbarNativeExplosionDecals(); + PrepareWebbarNativeGroundTracks(); return; } #endif --- a/rts/Lua/LuaUnsyncedCtrl.cpp +++ b/rts/Lua/LuaUnsyncedCtrl.cpp @@ -1,3 +1,4 @@ +#include "Game/WebbarGroundTrackEvents.h" /* This file is part of the Spring engine (GPL v2 or later), see LICENSE.html */ #include "LuaUnsyncedCtrl.h" @@ -2335,6 +2336,7 @@ return 0; groundDecals->SetUnitLeaveTracks(unit, lua_toboolean(L, 2)); + WebbarGroundTrackEvents::Observe(unit,lua_toboolean(L,2)); return 0; }