--- a/rts/Game/WebbarNativeGroundTracks.h +++ b/rts/Game/WebbarNativeGroundTracks.h @@ -2,13 +2,17 @@ #pragma once #include "WebbarGroundTrackPolicy.h" #include "WebbarGroundTrackEvents.h" +#include "WebbarGroundTrackDelta.h" +#include namespace WebbarNativeGroundTracks { class Reader final:public CEventClient,public WebbarOriginalGroundTracks::Policy { public: uint32_t epoch=0; uint32_t version=1; - bool reported=false; + bool reported=false,deltaFailed=false; + std::unique_ptr delta; + std::vector deltaRows; std::array perspective{-2,-2,-2,-2,-2}; Reader():CEventClient("[WebBAR original ground tracks]",314159,false){ Perspective();eventHandler.AddClient(this); @@ -72,6 +76,33 @@ if(++reader->version==0)++reader->version; reader->decalsUpdateList.ResetNeedUpdateAll(); } + + // Optional observer only. A legacy client never opts in and receives the + // unchanged WGT2 path. Reset/mode controls are unsynced host state. + const auto control=uint32_t(MAIN_THREAD_EM_ASM_INT({return Module['webbarNativeGroundTrackControl']?Module['webbarNativeGroundTrackControl']():0;})); + if((control&1u)&&request.flags==3u&&!reader->deltaFailed){ + try{ + if(!reader->delta)reader->delta=std::make_unique(); + auto& drawable=reader->deltaRows;drawable.clear();drawable.reserve(count); + for(const auto& decal:reader->decals)if(decal.info.type==uint8_t(GroundDecal::Type::DECAL_TRACK)&&DrawVisible(decal,adjustedFrame))drawable.push_back(&decal); + if(drawable.size()!=count)throw std::runtime_error("Native drawable track count changed during publication"); + static_assert(offsetof(GroundDecal,userDefined)==160); + const auto flags=uint32_t(gu->spectating)|(uint32_t(gu->spectatingFullView)<<1); + const WebbarGroundTrackDelta::Scope scope{drawEpoch,generation,reader->epoch,uint32_t(gu->myPlayerNum),uint32_t(gu->myTeam),uint32_t(gu->myAllyTeam),flags,control>>1}; + const auto& delta=reader->delta->Pack(uint32_t(count),scope,[&](uint32_t at){return drawable[at];}); + std::array header{0x31544757u,3,uint32_t(gs->frameNum),drawEpoch,uint32_t(sequence),0,0,reader->epoch,uint32_t(gu->myPlayerNum),uint32_t(gu->myTeam),uint32_t(gu->myAllyTeam),flags,request.flags}; + const float time[]={float(gs->frameNum),spring_tomsecs(globalRendering->grTime)*.001f,(gs->GetLuaSimFrame()+request.fraction)/GAME_SPEED,request.fraction};std::memcpy(header.data()+16,time,sizeof(time));header[21]=generation; + WebbarGroundTrackDelta::EmitPages(delta,header,[](const uint32_t* page,size_t bytes){MAIN_THREAD_EM_ASM({if(Module['webbarNativeGroundTracks'])Module['webbarNativeGroundTracks'](HEAPU8.slice($0,$0+$1).buffer);},page,bytes);}); + return; + }catch(const std::exception& error){ + reader->deltaFailed=true;reader->delta.reset();std::vector().swap(reader->deltaRows); + MAIN_THREAD_EM_ASM({if(Module['webbarNativeGroundTrackDeltaError'])Module['webbarNativeGroundTrackDeltaError'](UTF8ToString($0));},error.what()); + // Complete this same native request through the original WGT2 path. The + // optional codec must not strand pose admission or disable valid tracks. + } + } + if(reader->delta){reader->delta.reset();std::vector().swap(reader->deltaRows);} + std::vector packet{0x31544757u,2,uint32_t(gs->frameNum),drawEpoch,uint32_t(sequence),0,96,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}; --- /dev/null +++ b/rts/Game/WebbarGroundTrackDelta.h @@ -0,0 +1,71 @@ +/* This file is part of the Spring engine (GPL v2 or later), see LICENSE.html */ +#pragma once +#include +#include +#include +#include +#include +#include +namespace WebbarGroundTrackDelta { +constexpr uint32_t Budget=16u*1024u*1024u, HeaderWords=24, PageWords=4096u*24u, MaxRows=174719; +using Row=std::array; +using Scope=std::array; +constexpr std::array CompactWords{4,5,6,7,8,9,10,11,12,20,21,25,28,29,30,31,32,33,34,35,36,37,38,39}; +constexpr std::array ZeroWords{0,1,2,3,13,14,15,16,17,18,19,22,23,24,26}; +inline uint64_t WireBytes(uint64_t payloadWords){return payloadWords*4+std::max(uint64_t(1),(payloadWords+PageWords-1)/PageWords)*96;} +inline uint32_t Identity(const void* record){uint32_t word;std::memcpy(&word,static_cast(record)+36*4,4);if((word&255u)!=3u||!(word>>8))throw std::runtime_error("Original track identity differs");return word>>8;} +inline Row Compact(const void* record){std::array words;std::memcpy(words.data(),record,160);uint32_t zero=0;for(auto at:ZeroWords)zero|=words[at];if(zero||words[27]!=0x3f800000u)throw std::runtime_error("Original track compact defaults differ");Identity(record);Row row;for(size_t i=0;i<24;++i)row[i]=words[CompactWords[i]];return row;} +struct Message {bool snapshot=true,orderChanged=true;uint32_t serial=0,base=0,count=0,changed=0,retired=0;std::vector payload;}; +class Packer { + uint32_t capacity=0,mask=0,used=0,count=0,serial=0,revision=0;bool valid=false;Scope scope{}; + std::vector rows; + std::vector keys,values,ids,seen,order,free,changed,retired; + Message message; + uint32_t Home(uint32_t id)const{return(id*2654435761u)&mask;} + uint32_t Bucket(uint32_t id)const{auto at=Home(id);while(keys[at]&&keys[at]!=id)at=(at+1)&mask;return at;} + uint32_t Find(uint32_t id)const{if(keys.empty())return 0;const auto at=Bucket(id);return keys[at]?values[at]+1:0;} + void Insert(uint32_t id,uint32_t slot){const auto at=Bucket(id);if(keys[at])throw std::runtime_error("Duplicate original track ID");keys[at]=id;values[at]=slot;} + void Erase(uint32_t id){auto hole=Bucket(id);if(!keys[hole])throw std::runtime_error("Missing original track ID");for(auto at=(hole+1)&mask;keys[at];at=(at+1)&mask){const auto home=Home(keys[at]);if(((hole-home)&mask)<((at-home)&mask)){keys[hole]=keys[at];values[hole]=values[at];hole=at;}}keys[hole]=0;} + void Ensure(uint32_t n){ + if(n<=capacity)return;uint32_t next=32;while(next const Message& Snapshot(uint32_t n,const Scope& nextScope,At&& at){ + Invalidate();scope=nextScope;revision=1;Ensure(n);Begin(n,true,0,true,size_t(n)*24); + for(uint32_t i=0;i>8;if(Find(id))throw std::runtime_error("Duplicate snapshot track ID");Insert(id,i);rows[i]=row;ids[i]=id;seen[i]=revision;order[i]=i;message.payload.insert(message.payload.end(),row.begin(),row.end());} + used=count=n;valid=true;return message; + } +public: + Packer()=default; + void Invalidate(){std::fill(keys.begin(),keys.end(),0);std::fill(ids.begin(),ids.end(),0);std::fill(seen.begin(),seen.end(),0);free.clear();changed.clear();retired.clear();used=count=revision=0;valid=false;} + template const Message& Pack(uint32_t n,const Scope& nextScope,At&& at){ + if(n>MaxRows||WireBytes(uint64_t(n)*24)>Budget)throw std::runtime_error("Native track logical-frame budget");Ensure(n);const auto base=serial;const bool wrapped=++serial==0;if(wrapped)serial=1; + if(!valid||scope!=nextScope||wrapped)return Snapshot(n,nextScope,at); + changed.clear();retired.clear();bool orderChanged=n!=count;if(++revision>=0x7fffffffu){std::fill(seen.begin(),seen.end(),0);revision=1;} + for(uint32_t i=0;i>8,found=Find(id);uint32_t slot;bool dirty=!found; + if(found){slot=found-1;if(seen[slot]!=revision)throw std::runtime_error("Duplicate native delta track");} + else{if(free.empty()){if(used>=capacity)throw std::runtime_error("Native track cache full");slot=used++;}else{slot=free.back();free.pop_back();}Insert(id,slot);ids[slot]=id;seen[slot]=revision;} + if(seen[slot]!=revision)throw std::runtime_error("Duplicate new native track");seen[slot]=revision|0x80000000u;dirty=dirty||rows[slot]!=row;if(dirty){rows[slot]=row;changed.push_back(slot);}if(order[i]!=slot){order[i]=slot;orderChanged=true;} + } + for(uint32_t i=0;i=WireBytes(uint64_t(n)*24)||WireBytes(payloadWords)>Budget)return Snapshot(n,nextScope,at); + Begin(n,false,base,orderChanged,size_t(payloadWords));message.payload.push_back(uint32_t(retired.size()));message.payload.insert(message.payload.end(),retired.begin(),retired.end()); + for(auto slot:changed){message.payload.push_back(slot);message.payload.insert(message.payload.end(),3,0);message.payload.insert(message.payload.end(),rows[slot].begin(),rows[slot].end());}if(orderChanged)message.payload.insert(message.payload.end(),order.begin(),order.begin()+n);return message; + } + size_t ReservedBytes()const{return rows.capacity()*96+(keys.capacity()+values.capacity()+ids.capacity()+seen.capacity()+order.capacity()+free.capacity()+changed.capacity()+retired.capacity()+message.payload.capacity())*4;} +}; +// Preserve the existing96-byte native identity/time header and page budget. +// WGT3 words:5pagewords,6mode(reset1/order2),13serial,14base,15currentcount, +//20changedcount,22payloadwordoffset,23payloadwordtotal. Other native fields stay. +template void EmitPages(const Message& message,const std::array& identity,Emit&& emit){ + if(message.count>MaxRows||WireBytes(message.payload.size())>Budget)throw std::runtime_error("Native delta page budget");std::vector page;page.reserve(HeaderWords+std::min(size_t(PageWords),message.payload.size()));size_t offset=0; + do{const auto length=std::min(size_t(PageWords),message.payload.size()-offset);page.assign(identity.begin(),identity.end());page[1]=3;page[5]=uint32_t(length);page[6]=uint32_t(message.snapshot)|(uint32_t(message.orderChanged)<<1);page[13]=message.serial;page[14]=message.base;page[15]=message.count;page[20]=message.changed;page[22]=uint32_t(offset);page[23]=uint32_t(message.payload.size());page.insert(page.end(),message.payload.begin()+offset,message.payload.begin()+offset+length);emit(page.data(),page.size()*4);offset+=length;}while(offset=count*20; if(ok){packet[12+group]=count;packet[5]+=count;if(!Fits(packet[5])){failure="Original persistent decal transport exceeds 16 MiB";ok=false;}} - for(size_t i=1;ok&&i<=count*20;++i){ - lua_rawgeti(L,data,i);const float value=lua_tonumber(L,-1);ok=lua_type(L,-1)==LUA_TNUMBER&&std::isfinite(value); - if(ok){uint32_t word;std::memcpy(&word,&value,4);packet.push_back(word);}lua_pop(L,1); - } + if(ok)ok=WebbarLuaNumericArray::AppendFiniteWords(L,data,count*20,packet); lua_pop(L,2); } lua_pop(L,1); diff --git a/rts/Game/WebbarLuaNumericArray.h b/rts/Game/WebbarLuaNumericArray.h new file mode 100644 --- /dev/null +++ b/rts/Game/WebbarLuaNumericArray.h @@ -0,0 +1,29 @@ +/* This file is part of the Spring engine (GPL v2 or later), see LICENSE.html */ +#pragma once +#include +#include +#include +#include +#include +#include "lua.h" +#include "lib/lua/src/lobject.h" +#include "lib/lua/src/ltable.h" + +// Pinned Lua5.1 raw numeric-table read, with the same strict type/finite and +// float-word semantics as rawgeti + tonumber + type. The table stays rooted on +// the Lua stack; there are no VM calls/allocations/reentry while its slots are +// borrowed. No pointer is retained and no Lua object or stack slot is changed. +namespace WebbarLuaNumericArray { +static bool AppendFiniteWords(lua_State* L,int index,size_t count,std::vector& out) { + if(!lua_istable(L,index)||count>16u*1024u*1024u/sizeof(float)||count>size_t(std::numeric_limits::max())||count>out.max_size()-out.size())return false; + const auto* table=static_cast(lua_topointer(L,index)); + out.reserve(out.size()+count); + for(size_t at=0;atsizearray)?table->array+at:luaH_getnum(const_cast(table),int(at+1)); + if(!ttisnumber(slot))return false; + const float value=nvalue(slot);if(!std::isfinite(value))return false; + uint32_t word;std::memcpy(&word,&value,sizeof(word));out.push_back(word); + } + return true; +} +}