--- a/rts/Game/Camera.cpp +++ b/rts/Game/Camera.cpp @@ -567,11 +567,16 @@ float3 CCamera::CalcPixelDir(int x, int y) const { - RECOIL_DETAILED_TRACY_ZONE; - const int vsx = std::max(1, globalRendering->viewSizeX); - const int vsy = std::max(1, globalRendering->viewSizeY); + return CalcPixelDir(x,y,globalRendering->viewSizeX,globalRendering->viewSizeY,globalRendering->viewPosX); +} - const float dx = float(x - globalRendering->viewPosX - (vsx >> 1)) / vsy * (tanHalfFov * 2.0f); +float3 CCamera::CalcPixelDir(int x, int y, int width, int height, int offsetX) const +{ + RECOIL_DETAILED_TRACY_ZONE; + const int vsx = std::max(1, width); + const int vsy = std::max(1, height); + + const float dx = float(x - offsetX - (vsx >> 1)) / vsy * (tanHalfFov * 2.0f); const float dy = float(y - (vsy >> 1)) / vsy * (tanHalfFov * 2.0f); return ((forward - up * dy + right * dx).Normalize()); --- a/rts/Game/Camera.h +++ b/rts/Game/Camera.h @@ -139,6 +139,7 @@ void SetRotZ(const float z) { SetRot(float3(rot.x, rot.y, z)); } float3 CalcPixelDir(int x, int y) const; + float3 CalcPixelDir(int x, int y, int width, int height, int offsetX) const; float3 CalcViewPortCoordinates(const float3& objPos) const; bool InView(const float3& point, float radius = 0.0f) const; --- a/rts/Game/Game.cpp +++ b/rts/Game/Game.cpp @@ -293,6 +293,7 @@ // The private unsynced presentation VM must close before game definitions. #if defined(__EMSCRIPTEN__) static void FreeWebbarNativeBeams(); +static void PrepareWebbarNativeBeams(); #endif CGame::~CGame() @@ -897,8 +898,12 @@ #if defined(__EMSCRIPTEN__) // Browser practice supplies its own UI. Native scenario widgets would // otherwise pause at an invisible mission briefing on frame zero. - if (std::getenv("WEBBAR_PLAYABLE") != nullptr) + if (std::getenv("WEBBAR_PLAYABLE") != nullptr) { + // Initialize the replacement original visual widgets at the native + // LuaUI phase, before GamePreload creates initial units/events. + if (std::getenv("WEBBAR_NATIVE_DISTORTION_VBO") != nullptr) PrepareWebbarNativeBeams(); return; + } #endif loadscreen->SetLoadMessage("Loading LuaUI"); auto lock = CLoadLock::GetUniqueLock(); --- /dev/null +++ b/rts/Game/WebbarDistortionAdapter.h @@ -0,0 +1,104 @@ +/* This file is part of the Spring engine (GPL v2 or later), see LICENSE.html */ +#pragma once +// CPU storage boundary only. Original BAR widgets/configurations and the +// original InstanceVBOTable implementation own all admission and lifetimes. +static constexpr const char* WEBBAR_DISTORTION_ADAPTER=R"WB_DISTORT_LUA( +local function noop() end +local activeShader +webbarDistortionVBOs={} +webbarDistortionDraws={} +webbarDistortionUniforms={} +webbarDistortionGlobals={} +webbarDistortionInitialized=false +local function buffer() + return {Define=noop,Upload=noop,Delete=noop,GetID=function()return 0 end, + InstanceDataFromUnitIDs=noop,InstanceDataFromFeatureIDs=noop} +end +local function vao() + return {AttachIndexBuffer=noop,AttachVertexBuffer=noop,AttachInstanceBuffer=noop, + Delete=noop,DrawArrays=noop,DrawElements=noop} +end +GL={ONE=1,SRC_ALPHA=770,ONE_MINUS_SRC_ALPHA=771,TRIANGLES=4, + ARRAY_BUFFER=34962,ELEMENT_ARRAY_BUFFER=34963,UNSIGNED_INT=5125, + COLOR_BUFFER_BIT=16384,LINEAR=9729,NEAREST=9728,CLAMP=10496,BACK=1029} +gl={GetVBO=buffer,GetVAO=vao,ObjectLabel=noop, + Blending=noop,Texture=noop,DepthTest=noop,DepthMask=noop,Culling=noop, + Clear=noop,CopyToTexture=noop,DeleteTexture=noop, + CreateTexture=function()return {} end, + RenderToTexture=function(_,fn,...)return fn(...)end, + GetMapRendering=WebbarDistortionMapRendering, + CreateShader=function()error('CPU adapter cannot compile GPU shaders')end, + LuaShader={CheckShaderUpdates=function(cache) + assert(cache.shaderName=='Deferred Distortions GL4' or cache.shaderName=='ScreenDistortionShader GL4') + webbarDistortionShaderConfig=cache.shaderConfig + return {Activate=function()activeShader=cache.shaderName end, + Deactivate=function()activeShader=nil end,Delete=noop, + SetUniformFloat=function(_,name,...) + webbarDistortionUniforms[name]={...} + end} + end}} +widget={} +WG={} +-- No lobby transport in this single-player presentation handle. +-- The tracker notification does not change admission or any VBO state. +widgetHandler={AddAction=noop,RemoveAction=noop,AddSpadsMessage=noop, + RemoveWidget=function()error('Original distortion widget rejected CPU storage')end, + RegisterGlobal=function(_,name,fn) + assert(name=='AddDistortion' or name=='RemoveDistortion' or name=='GetDistortionVBO' or name=='GadgetCrashingAircraft1') + webbarDistortionGlobals[name]=fn + end, + DeregisterGlobal=function(_,name)webbarDistortionGlobals[name]=nil end} +-- Original unit tracker broadcasts to original distortion widget methods. +-- No visibility policy or new unit admission belongs in this boundary. +local calls={} +setmetatable(calls,{__call=function(_,name) + return webbarDistortionInitialized and type(webbarNativeDistortion[name])=='function' + end,__index=function(_,name) + return function(...) + if webbarDistortionInitialized and webbarNativeDistortion[name] then + return webbarNativeDistortion[name](webbarNativeDistortion,...) + end + end end}) +Script.LuaUI=calls +function WebbarDistortionStorage() + local originalMake=gl.InstanceVBOTable.makeInstanceVBOTable + gl.InstanceVBOTable.makeInstanceVBOTable=function(...) + local v=assert(originalMake(...)) + assert(v.instanceStep==29,'Pinned distortion instance layout differs') + assert(not webbarDistortionVBOs[v.myName],'Duplicate original distortion bin') + webbarDistortionVBOs[v.myName]=v + local draw=v.draw + function v:draw(...) + if self.usedElements>0 then + assert(activeShader=='Deferred Distortions GL4','Unexpected original distortion draw shader') + webbarDistortionDraws[#webbarDistortionDraws+1]=self + end + return draw(self,...) + end + return v + end +end +function WebbarDistortionInitialize() + webbarNativeTracker:Initialize() + webbarNativeDistortion:Initialize() + webbarDistortionInitialized=true + assert(WG.distortionsgl4 and WG.unittrackerapi,'Original distortion widgets not initialized') +end +function WebbarDistortionSim(frame) + webbarNativeTracker:GameFrame(frame) + webbarNativeDistortion:GameFrame(frame) +end +function WebbarDistortionEvent(name,...) + if webbarNativeTracker[name] then webbarNativeTracker[name](webbarNativeTracker,...) end + if webbarNativeDistortion[name] then webbarNativeDistortion[name](webbarNativeDistortion,...) end +end +function WebbarDistortionDraw() + webbarDistortionDraws={} + webbarDistortionUniforms={} + webbarNativeDistortion:Update(0) + webbarNativeDistortion:DrawWorld() +end +function VisibleExplosion(...)return webbarNativeDistortion:VisibleExplosion(...)end +function Barrelfire(...)return webbarNativeDistortion:Barrelfire(...)end +function UnitScriptDistortion(...)return webbarNativeDistortion:UnitScriptDistortion(...)end +)WB_DISTORT_LUA"; --- /dev/null +++ b/rts/Game/WebbarDistortionEvents.h @@ -0,0 +1,11 @@ +/* This file is part of the Spring engine (GPL v2 or later), see LICENSE.html */ +#pragma once +#include +#include +#include "Lua/LuaHandle.h" +namespace WebbarDistortionEvents { +inline CLuaHandle* handle=nullptr; +inline bool Enabled(){static const bool value=std::getenv("WEBBAR_NATIVE_DISTORTION_VBO")!=nullptr;return value;} +inline bool Has(const char* name){return Enabled()&&handle&&(std::strcmp(name,"VisibleExplosion")==0||std::strcmp(name,"Barrelfire")==0||std::strcmp(name,"UnitScriptDistortion")==0)&&handle->HasXCall(name);} +inline void Call(lua_State* L,const char* name){if(Has(name))handle->XCall(L,name);} +} --- a/rts/Game/WebbarNativeBeams.h +++ b/rts/Game/WebbarNativeBeams.h @@ -21,7 +21,7 @@ #include "Game/Camera.h" #include "Map/ReadMap.h" -static bool WebbarFlamesEnabled() { static const bool enabled=std::getenv("WEBBAR_NATIVE_FLAME_VBO")!=nullptr;return enabled; } +static bool WebbarFlamesEnabled() { static const bool enabled=(std::getenv("WEBBAR_NATIVE_FLAME_VBO")!=nullptr || std::getenv("WEBBAR_NATIVE_DISTORTION_VBO")!=nullptr);return enabled; } // WBR1 is separate from WPM1/bridge9. Only the browser writes request fields; @@ -36,7 +36,8 @@ uint32_t padding[2]={},counters[4]={},tail[16]={}; // WBR2 appends actual projection/FPS/rotation. WBR1 reserves stay zero. float flameCamera[8]={}; - uint32_t extensionPadding[56]={}; + float distortionViewport[2]={}; + uint32_t extensionPadding[54]={}; }; static_assert(sizeof(WebbarBeamDrawMailbox)==512); static_assert(offsetof(WebbarBeamDrawMailbox,flameCamera)==256); @@ -48,7 +49,8 @@ float fraction=0,reserved[3]={}; float planes[24]={},eye[3]={},direction[3]={}; float flameCamera[8]={}; - bool flames=false; + float distortionViewport[2]={}; + bool flames=false,distortions=false; }; static_assert(offsetof(WebbarBeamDrawRequest,flameCamera)==144); static bool ReadWebbarBeamDrawRequest(WebbarBeamDrawRequest& request,int32_t& sequence) @@ -57,14 +59,16 @@ sequence=__atomic_load_n(&box.sequence,__ATOMIC_ACQUIRE); if(sequence<=0 || (sequence&1) || sequence==__atomic_load_n(&box.acknowledged,__ATOMIC_RELAXED)) return false; std::memcpy(&request,&box.frame,144); - request.flames=(box.version==2); + request.flames=(box.version>=2);request.distortions=(box.version==3); if(request.flames) std::memcpy(request.flameCamera,box.flameCamera,sizeof(request.flameCamera)); + if(request.distortions) std::memcpy(request.distortionViewport,box.distortionViewport,sizeof(request.distortionViewport)); if(sequence!=__atomic_load_n(&box.sequence,__ATOMIC_ACQUIRE)) return false; if(request.flames) { for(float value:request.flameCamera) if(!std::isfinite(value)) return false; const float* c=request.flameCamera; if(c[0]<=1 || c[0]>=179 || c[1]<=0 || c[1]>100 || c[2]<=0 || c[3]<=c[2] || c[3]>1e9f || c[4]<0 || c[4]>1000) return false; } + if(request.distortions) for(float v:request.distortionViewport) if(!std::isfinite(v)||v<1||v>16384||v!=std::floor(v)) return false; if(request.flags || !std::isfinite(request.fraction) || request.fraction<0 || request.fraction>1) return false; for(float value:request.reserved) if(value!=0) return false; for(float value:request.planes) if(!std::isfinite(value)) return false; @@ -316,8 +320,10 @@ bool full=gu->spectatingFullView,ready=false,reported=false; }; +#include "WebbarNativeDistortion.h" + static WebbarNativeBeamRenderer* webbarNativeBeams=nullptr; -static void FreeWebbarNativeBeams() { delete webbarNativeBeams; webbarNativeBeams=nullptr; } +static void FreeWebbarNativeBeams() { FreeWebbarNativeDistortion();delete webbarNativeBeams; webbarNativeBeams=nullptr; } static void PrepareWebbarNativeBeams() { static const bool enabled=std::getenv("WEBBAR_NATIVE_BEAM_VBO")!=nullptr; @@ -326,7 +332,7 @@ static bool announced=false; if(!announced) { announced=true; - webbarBeamDrawMailbox.version=WebbarFlamesEnabled()?2:1;webbarBeamDrawMailbox.bytes=WebbarFlamesEnabled()?512:256; + webbarBeamDrawMailbox.version=WebbarDistortionEvents::Enabled()?3:WebbarFlamesEnabled()?2:1;webbarBeamDrawMailbox.bytes=webbarBeamDrawMailbox.version>=2?512:256; MAIN_THREAD_EM_ASM({ if(Module['webbarNativeBeamMailbox']) Module['webbarNativeBeamMailbox']($0,$1); },&webbarBeamDrawMailbox,webbarBeamDrawMailbox.bytes); } if(webbarNativeBeams && !webbarNativeBeams->MatchesView()) FreeWebbarNativeBeams(); @@ -334,6 +340,7 @@ webbarNativeBeams=new WebbarNativeBeamRenderer; webbarNativeBeams->epoch=++epoch; __atomic_store_n(&webbarBeamDrawMailbox.counters[3],epoch,__ATOMIC_RELEASE); + PrepareWebbarNativeDistortion(epoch); } } static void UpdateWebbarNativeBeams() @@ -343,5 +350,6 @@ WebbarBeamDrawRequest request;int32_t sequence; if(!ReadWebbarBeamDrawRequest(request,sequence)) return; webbarNativeBeams->Publish(request,sequence); + if(request.distortions) PublishWebbarNativeDistortion(request,sequence); __atomic_store_n(&webbarBeamDrawMailbox.acknowledged,sequence,__ATOMIC_RELEASE); } --- /dev/null +++ b/rts/Game/WebbarNativeDistortion.h @@ -0,0 +1,123 @@ +/* This file is part of the Spring engine (GPL v2 or later), see LICENSE.html */ +#pragma once +#include +#include +#include "WebbarDistortionAdapter.h" +#include "WebbarDistortionEvents.h" +#include "Lua/LuaFeatureDefs.h" +#include "Lua/LuaConstEngine.h" +#include "Lua/LuaUtils.h" +#include "Rendering/Env/MapRendering.h" +#include "Rendering/GlobalRendering.h" +#include "Rendering/Models/LocalModelPiece.hpp" +#include "System/Transform.hpp" +#include "System/TimeUtil.h" + +class WebbarNativeDistortion final: public CLuaHandle { +public: + WebbarNativeDistortion(uint32_t epoch_):CLuaHandle("WebBAR original distortion widgets",LUA_HANDLE_ORDER_UI,false,false),epoch(epoch_){ + SetFullCtrl(false);SetCtrlTeam(NoAccessTeam);SetSelectTeam(NoAccessTeam);Perspective();LuaLibs::OpenSynced(L,false); + lua_pushcfunction(L,luaopen_debug);lua_pushliteral(L,"debug");lua_call(L,1,0); + lua_pushvalue(L,LUA_GLOBALSINDEX); + ready=AddBasicCalls(L)&&AddEntriesToTable(L,"Spring",LuaSyncedRead::PushEntries)&&AddEntriesToTable(L,"Spring",LuaUnsyncedRead::PushEntries)&&AddEntriesToTable(L,"UnitDefs",LuaUnitDefs::PushEntries)&&AddEntriesToTable(L,"WeaponDefs",LuaWeaponDefs::PushEntries)&&AddEntriesToTable(L,"FeatureDefs",LuaFeatureDefs::PushEntries)&&AddEntriesToTable(L,"Game",LuaConstGame::PushEntries)&&AddEntriesToTable(L,"Engine",LuaConstEngine::PushEntries)&&AddEntriesToTable(L,"LOG",LuaUtils::PushLogEntries);lua_settop(L,0); + if(ready){lua_getglobal(L,"Spring");Function("Echo",LuaUtils::Echo);Function("GetVisibleProjectiles",VisibleProjectiles);Function("IsSphereInView",SphereInView);Function("GetCameraPosition",CameraPosition);Function("GetCameraDirection",CameraDirection);Function("GetViewGeometry",ViewGeometry);Function("GetDrawFrame",DrawFrame);Function("GetFPS",FPS);Function("TraceScreenRay",ScreenRay);lua_pop(L,1);lua_newtable(L);Function("Include",Include);lua_setglobal(L,"VFS");lua_pushcfunction(L,MapRendering);lua_setglobal(L,"WebbarDistortionMapRendering");} + if(ready)ready=LoadCode(L,WEBBAR_DISTORTION_ADAPTER,"Original distortion CPU storage"); + if(ready)ready=LoadCode(L,R"LUA( +local configString=Spring.GetConfigString +-- The browser port supplies both actual deferred depth targets, including +-- on Low while distortion is active; headless GL settings describe no GPU. +Spring.GetConfigString=function(key,...) + if key=='AllowDeferredMapRendering' or key=='AllowDeferredModelRendering' then return '1' end + return configString(key,...) +end +UnitDefNames={};for id,d in pairs(UnitDefs)do UnitDefNames[d.name]=d end +WeaponDefNames={};for id,d in pairs(WeaponDefs)do WeaponDefNames[d.name]=d end +FeatureDefNames={};for id,d in pairs(FeatureDefs)do FeatureDefNames[d.name]=d end +VFS.Include('common/numberfunctions.lua') +VFS.Include('common/stringFunctions.lua') +VFS.Include('common/tablefunctions.lua') +local common=VFS.Include('common/springFunctions.lua') +Spring.Utilities=common.Utilities;Spring.Debug=common.Debug +-- Only the original graphics storage module runs; GPU shader evaluation and +-- textures live in the browser and do not exist in this CPU-only handle. +gl.InstanceVBOTable=VFS.Include('modules/graphics/instancevbotable.lua') +WebbarDistortionStorage() +widget={};VFS.Include('LuaUI/Widgets/api_unit_tracker_gl4.lua');webbarNativeTracker=widget +widget={};VFS.Include('LuaUI/Widgets/gfx_distortion_gl4.lua');webbarNativeDistortion=widget +for _,key in ipairs({'UnitCreated','UnitFinished','UnitFromFactory','UnitDestroyed','UnitTaken','UnitGiven','UnitEnteredLos','UnitLeftLos','UnitIdle','UnitCloaked','UnitDecloaked','UnitMoveFailed','StockpileChanged','FeatureCreated','FeatureDestroyed','PlayerChanged','GameStart'})do + local name=key + _G[name]=function(...) + local ok,why=pcall(WebbarDistortionEvent,name,...) + if not ok then webbarDistortionFailure=tostring(why);error(why) end + end +end +)LUA","Original distortion widget contexts"); + if(ready)ready=Call("WebbarDistortionInitialize"); + if(ready){WebbarDistortionEvents::handle=this;ready=PublishConfig();} + if(ready)eventHandler.AddClient(this);else Report(); + } + ~WebbarNativeDistortion()override{if(WebbarDistortionEvents::handle==this)WebbarDistortionEvents::handle=nullptr;KillLua();} + bool WantsEvent(const std::string& name)override{return ready&&(name=="GameFrame"||name=="CollectGarbage"||CLuaHandle::WantsEvent(name));} + void GameFrame(int frame)override{if(!ready)return;lua_getglobal(L,"WebbarDistortionSim");lua_pushnumber(L,frame);ready=RunCallIn(L,LuaHashString("WebbarDistortionSim"),1,0);if(!ready)Report();} + void PlayerChanged(int player)override{Perspective();CLuaHandle::PlayerChanged(player);} + void Publish(const WebbarBeamDrawRequest& next,int32_t sequence){ + if(!ready)return;request=next;const int width=int(next.distortionViewport[0]),height=int(next.distortionViewport[1]); + view.SetPos(float3(next.eye[0],next.eye[1],next.eye[2]));view.SetRot(float3(next.flameCamera[5],next.flameCamera[6],next.flameCamera[7]));view.SetVFOV(next.flameCamera[0]);view.SetAspectRatio(next.flameCamera[1]);view.SetFrustumScales(float4(0,0,next.flameCamera[2],next.flameCamera[3]));view.UpdateFrustum();hasCamera=true;++drawFrame; + if(width!=viewportWidth||height!=viewportHeight){viewportWidth=width;viewportHeight=height;ready=LoadCode(L,"webbarNativeDistortion:ViewResize()","Original distortion viewport");} + if(ready)ready=Call("WebbarDistortionDraw");lua_getglobal(L,"webbarDistortionFailure");const bool failed=!lua_isnil(L,-1);lua_pop(L,1);if(!ready||failed){ready=false;Report();return;} + std::vector payload;uint32_t bins=0,total=0;poses.clear(); + lua_getglobal(L,"webbarDistortionDraws");const int draws=lua_objlen(L,-1);int last=-1;bool valid=draws>=0&&draws<=9; + for(int n=1;n<=draws&&valid;n++){ + lua_rawgeti(L,-1,n);lua_getfield(L,-1,"myName");const char* name=lua_tostring(L,-1);int bin=-1;for(int i=0;i<9;i++)if(name&&std::strcmp(name,names[i])==0)bin=i;lua_pop(L,1); + lua_getfield(L,-1,"usedElements");const int count=lua_tointeger(L,-1);lua_pop(L,1);if(bin<=last||count<1||count>1000000||total+uint32_t(count)>1000000){valid=false;lua_pop(L,1);break;}last=bin; + const uint32_t record[]={uint32_t(bin),uint32_t(count),uint32_t(count)*180,0};Append(payload,record,sizeof(record));++bins;total+=uint32_t(count);lua_getfield(L,-1,"instanceData"); + for(int row=0;row out{};for(int i=0;i<24;i++){lua_rawgeti(L,-1,row*29+i+1);out[i]=lua_tonumber(L,-1);valid=valid&&lua_isnumber(L,-1)&&std::isfinite(out[i]);lua_pop(L,1);} + if(bin>=6){lua_getfield(L,-2,"indextoUnitID");lua_rawgeti(L,-1,row+1);const int id=lua_tointeger(L,-1);const bool hasID=lua_isnumber(L,-1);lua_pop(L,2);lua_rawgeti(L,-1,row*29+25);const int piece=lua_tointeger(L,-1);valid=valid&&hasID&&lua_isnumber(L,-1)&&piece>=0;lua_pop(L,1);if(valid)valid=Pose(id,piece,out.data()+24,out.data()+40,out.data()+41);} + else for(int i=0;i<4;i++)out[24+i*5]=1; + if(valid)Append(payload,out.data(),sizeof(out)); + } + lua_pop(L,2); + } + lua_pop(L,1);if(!valid){ready=false;Report();return;} + float uniforms[12]={float(gs->frameNum),spring_tomsecs(globalRendering->grTime)*.001f,(gs->GetLuaSimFrame()+next.fraction)/GAME_SPEED,next.fraction}; + if(bins){lua_getglobal(L,"webbarDistortionUniforms");valid=Uniform("windXZ",uniforms+4,2)&&Uniform("radiusMultiplier",uniforms+6,1)&&Uniform("intensityMultiplier",uniforms+7,1)&&Uniform("distortionOverallStrength",uniforms+8,1);lua_pop(L,1);} + if(!valid){ready=false;Report();return;} + const uint32_t header[]={0x31544457,1,uint32_t(gs->frameNum),bins,180,epoch,uint32_t(sequence),total};std::vector packet;packet.reserve(sizeof(header)+sizeof(uniforms)+payload.size());Append(packet,header,sizeof(header));Append(packet,uniforms,sizeof(uniforms));Append(packet,payload.data(),payload.size()); + MAIN_THREAD_EM_ASM({if(Module['webbarNativeDistortionVBO'])Module['webbarNativeDistortionVBO'](HEAPU8.slice($0,$0+$1).buffer);},packet.data(),packet.size()); + } +private: + static constexpr std::array names={"Point Distortion VBO","Projectile Point Distortion VBO","Beam Distortion VBO","Projectile Beam Distortion VBO","Cone Distortion VBO","Projectile Cone Distortion VBO","Unit Point Distortion VBO","Unit Beam Distortion VBO","Unit Cone Distortion VBO"}; + struct UnitPose{Transform world;std::vector current;}; + std::unordered_map poses; + static Transform Interpolate(const Transform& a,const Transform& b,float fraction){const float s=std::max(0.f,std::min(1.f,fraction)),t=1.f-s;const float sign=a.r.x*b.r.x+a.r.y*b.r.y+a.r.z*b.r.z+a.r.r*b.r.r<0?-1.f:1.f;CQuaternion q(a.r.x*t+b.r.x*s*sign,a.r.y*t+b.r.y*s*sign,a.r.z*t+b.r.z*s*sign,a.r.r*t+b.r.r*s*sign);const float length=std::sqrt(q.x*q.x+q.y*q.y+q.z*q.z+q.r*q.r);if(length>0){q.x/=length;q.y/=length;q.z/=length;q.r/=length;}return Transform{q,a.t*t+b.t*s,a.s*t+b.s*s};} + bool Pose(int id,int piece,float* matrix,float* identity,float* speed){ + const CUnit* unit=id>=0&&size_t(id)spectatingFullView&&(gu->myAllyTeam<0||!(unit->losStatus[gu->myAllyTeam]&LOS_INLOS))))return true; + auto it=poses.find(id);if(it==poses.end()){UnitPose p;p.world=Interpolate(unit->preFrameTra,Transform::FromMatrix(unit->GetTransformMatrix(true)),request.fraction);const auto& parts=unit->localModel.pieces;p.current.reserve(parts.size());for(const auto& part:parts){const Transform local=part.CalcPieceSpaceTransform(part.GetPosition(),part.GetRotation(),part.GetScaling());if(part.parent&&part.parent->GetLModelPieceIndex()>=p.current.size())return false;p.current.push_back(part.parent?p.current[part.parent->GetLModelPieceIndex()]*local:local);}it=poses.emplace(id,std::move(p)).first;} + auto& pose=it->second;Transform result=pose.world;if(piece){if(size_t(piece)>pose.current.size())return false;const auto& part=unit->localModel.pieces[piece-1];if(!part.GetScriptVisible())return true;result=result*Interpolate(part.GetEffectivePrevModelSpaceTransformFor(pose.current[piece-1]),pose.current[piece-1],request.fraction);} + const CMatrix44f m=result.ToMatrix();for(int i=0;i<16;i++){matrix[i]=m[i];if(!std::isfinite(matrix[i]))return false;}*identity=float(id);for(int i=0;i<4;i++)speed[i]=unit->speed[i];return true; + } + static void Append(std::vector& out,const void* data,size_t size){if(!size)return;const auto* p=static_cast(data);out.insert(out.end(),p,p+size);} + bool Uniform(const char* name,float* out,int count){lua_getfield(L,-1,name);if(!lua_istable(L,-1)){lua_pop(L,1);return false;}bool valid=true;for(int i=0;ispectatingFullView);SetReadTeam(gu->myTeam);SetReadAllyTeam(gu->spectatingFullView?AllAccessTeam:gu->myAllyTeam);} + void Function(const char* name,lua_CFunction fn){lua_pushcfunction(L,fn);lua_setfield(L,-2,name);} + bool Call(const char* name){lua_getglobal(L,name);return RunCallIn(L,LuaHashString(name),0,0);} + bool PublishConfig(){std::string config="{";lua_getglobal(L,"webbarDistortionShaderConfig");if(!lua_istable(L,-1)){lua_pop(L,1);return false;}int n=0;for(const char* key:{"CHROMATIC_ABERRATION","DEBUGCOMBINER"}){lua_getfield(L,-1,key);if(!lua_isnumber(L,-1)||!std::isfinite(lua_tonumber(L,-1))){lua_pop(L,2);return false;}const std::string value=lua_tostring(L,-1);lua_pop(L,1);if(n++)config+=",";config+="\""+std::string(key)+"\":\""+value+"\"";}lua_pop(L,1);config+="}";MAIN_THREAD_EM_ASM({if(Module['webbarNativeDistortionConfig'])Module['webbarNativeDistortionConfig'](JSON.parse(UTF8ToString($0)));},config.c_str());return true;} + void Report(){WebbarDistortionEvents::handle=nullptr;if(reported)return;reported=true;MAIN_THREAD_EM_ASM({if(Module['webbarNativeDistortionError'])Module['webbarNativeDistortionError']('Original distortion CPU widget failed');});} + static WebbarNativeDistortion* Self(lua_State* L){return static_cast(CLuaHandle::GetHandle(L));} + static int Include(lua_State* L){const int top=lua_gettop(L);const std::string path=luaL_checkstring(L,1);if(path.find("..")!=std::string::npos||path.empty()||path[0]=='/')return luaL_error(L,"Invalid original widget include");std::string source;CFileHandler file(path,SPRING_VFS_MOD);if(!file.LoadStringData(source))return luaL_error(L,"Original widget source unavailable: %s",path.c_str());if(luaL_loadbuffer(L,source.data(),source.size(),path.c_str())!=0)return lua_error(L);if(lua_istable(L,2)){lua_pushvalue(L,2);lua_setfenv(L,-2);}if(lua_pcall(L,0,LUA_MULTRET,0)!=0)return lua_error(L);return lua_gettop(L)-top;} + static int ViewGeometry(lua_State* L){const auto* s=Self(L);lua_pushnumber(L,s->viewportWidth?s->viewportWidth:globalRendering->viewSizeX);lua_pushnumber(L,s->viewportHeight?s->viewportHeight:globalRendering->viewSizeY);lua_pushnumber(L,0);lua_pushnumber(L,0);return 4;} + static int DrawFrame(lua_State* L){lua_pushnumber(L,Self(L)->drawFrame);return 1;} + static int FPS(lua_State* L){const auto* s=Self(L);lua_pushnumber(L,s->hasCamera?int(s->request.flameCamera[4]):globalRendering->FPS);return 1;} + static int CameraPosition(lua_State* L){const auto* s=Self(L);const float3 p=s->hasCamera?float3(s->request.eye[0],s->request.eye[1],s->request.eye[2]):camera->GetPos();for(int i=0;i<3;i++)lua_pushnumber(L,p[i]);return 3;} + static int CameraDirection(lua_State* L){const auto* s=Self(L);const float3 d=s->hasCamera?float3(s->request.direction[0],s->request.direction[1],s->request.direction[2]):camera->GetDir();for(int i=0;i<3;i++)lua_pushnumber(L,d[i]);return 3;} + static int MapRendering(lua_State* L){const char* key=luaL_checkstring(L,1);if(std::strcmp(key,"voidWater")!=0)return luaL_error(L,"Unexpected original map rendering query");lua_pushboolean(L,mapRendering->voidWater);return 1;} + static int SphereInView(lua_State* L){auto* s=Self(L);lua_pushboolean(L,(s->hasCamera?&s->view:camera)->InView(float3(luaL_checkfloat(L,1),luaL_checkfloat(L,2),luaL_checkfloat(L,3)),luaL_optfloat(L,4,0)));return 1;} + static int VisibleProjectiles(lua_State* L){auto* s=Self(L);return LuaUnsyncedRead::GetVisibleProjectilesForCamera(L,s->hasCamera?&s->view:nullptr);} + static int ScreenRay(lua_State* L){auto* s=Self(L);return LuaUnsyncedRead::TraceScreenRayForCamera(L,s->hasCamera?&s->view:nullptr,s->viewportWidth,s->viewportHeight);} + WebbarBeamDrawRequest request;CCamera view{CCamera::CAMTYPE_VISCUL};uint32_t epoch=0,drawFrame=0;int viewportWidth=0,viewportHeight=0;bool hasCamera=false,ready=false,reported=false; +}; +static WebbarNativeDistortion* webbarNativeDistortion=nullptr; +static void FreeWebbarNativeDistortion(){delete webbarNativeDistortion;webbarNativeDistortion=nullptr;} +static void PrepareWebbarNativeDistortion(uint32_t epoch){if(WebbarDistortionEvents::Enabled()&&!webbarNativeDistortion)webbarNativeDistortion=new WebbarNativeDistortion(epoch);} +static void PublishWebbarNativeDistortion(const WebbarBeamDrawRequest& request,int32_t sequence){if(webbarNativeDistortion)webbarNativeDistortion->Publish(request,sequence);} --- a/rts/Lua/LuaUnsyncedRead.cpp +++ b/rts/Lua/LuaUnsyncedRead.cpp @@ -3222,12 +3222,19 @@ */ int LuaUnsyncedRead::TraceScreenRay(lua_State* L) { + return TraceScreenRayForCamera(L,nullptr,0,0); +} + +int LuaUnsyncedRead::TraceScreenRayForCamera(lua_State* L, CCamera* view, int width, int height) +{ + const int viewSizeX=view?width:globalRendering->viewSizeX,viewSizeY=view?height:globalRendering->viewSizeY,viewPosX=view?0:globalRendering->viewPosX; + const CCamera* traceCamera=view?view:camera; // window coordinates const int mx = luaL_checkint(L, 1); const int my = luaL_checkint(L, 2); - const int wx = mx + globalRendering->viewPosX; - const int wy = globalRendering->viewSizeY - 1 - my; + const int wx = mx + viewPosX; + const int wy = viewSizeY - 1 - my; const int optArgIdx = 3 + lua_isnumber(L, 3); // 3 or 4 const int newArgIdx = 3 + 4 * (optArgIdx == 3); // 7 or 3 @@ -3238,7 +3245,7 @@ const bool ignoreWater = luaL_optboolean(L, optArgIdx + 3, false); if (useMiniMap && (minimap != nullptr) && !minimap->GetMinimized()) { - const int px = minimap->GetPosX() - globalRendering->viewPosX; + const int px = minimap->GetPosX() - viewPosX; const int py = minimap->GetPosY() - globalRendering->viewPosY; const int sx = minimap->GetSizeX(); const int sy = minimap->GetSizeY(); @@ -3265,19 +3272,19 @@ } } - if ((mx < 0) || (mx >= globalRendering->viewSizeX)) + if ((mx < 0) || (mx >= viewSizeX)) return 0; - if ((my < 0) || (my >= globalRendering->viewSizeY)) + if ((my < 0) || (my >= viewSizeY)) return 0; const CUnit* unit = nullptr; const CFeature* feature = nullptr; - const float rawRange = camera->GetFarPlaneDist() * 1.4f; + const float rawRange = traceCamera->GetFarPlaneDist() * 1.4f; const float badRange = rawRange - 300.0f; - const float3 camPos = camera->GetPos(); - const float3 pxlDir = camera->CalcPixelDir(wx, wy); + const float3 camPos = traceCamera->GetPos(); + const float3 pxlDir = view?view->CalcPixelDir(wx,wy,width,height,0):camera->CalcPixelDir(wx,wy); // trace for player's allyteam const float traceDist = TraceRay::GuiTraceRay(camPos, pxlDir, rawRange, nullptr, unit, feature, true, onlyCoords, ignoreWater); --- a/rts/Lua/LuaUnsyncedRead.h +++ b/rts/Lua/LuaUnsyncedRead.h @@ -134,6 +134,7 @@ static int GetCameraVectors(lua_State* L); static int WorldToScreenCoords(lua_State* L); static int TraceScreenRay(lua_State* L); + static int TraceScreenRayForCamera(lua_State* L, CCamera* view, int width, int height); static int GetPixelDir(lua_State* L); static int GetTimer(lua_State* L); --- a/rts/Lua/WebbarLuaUI.h +++ b/rts/Lua/WebbarLuaUI.h @@ -4,17 +4,19 @@ #include #include #include "Game/WebbarUiEvents.h" +#include "Game/WebbarDistortionEvents.h" #include "Sim/Misc/TeamHandler.h" // The original unsynced BAR broadcaster already performs its recipient check. // Expose exactly these two absent-LuaUI calls, never a general LuaUI substitute. static bool WebbarLuaUiCall(const char* name) { - return WebbarUiEvents::Enabled() && (std::strcmp(name, "NotificationEvent") == 0 || std::strcmp(name, "GadgetReceiveAwards") == 0); + return WebbarDistortionEvents::Has(name) || (WebbarUiEvents::Enabled() && (std::strcmp(name, "NotificationEvent") == 0 || std::strcmp(name, "GadgetReceiveAwards") == 0)); } static void CaptureWebbarLuaUiCall(lua_State* L, const char* name) { + if (WebbarDistortionEvents::Has(name)) { WebbarDistortionEvents::Call(L,name); return; } using namespace WebbarUiEvents; if (std::strcmp(name, "NotificationEvent") == 0) { if (gu->spectating || webbarReplay::Enabled() || CatchingUp() || gs->frameNum < 60 || !lua_israwstring(L, 1)) return; --- a/rts/Rendering/Models/LocalModelPiece.hpp +++ b/rts/Rendering/Models/LocalModelPiece.hpp @@ -96,6 +96,11 @@ void SavePrevModelSpaceTransform(); Transform GetEffectivePrevModelSpaceTransform() const; + // Read-only presentation equivalent when the caller calculated current + // model space without touching dirty/wasUpdated engine caches. + Transform GetEffectivePrevModelSpaceTransformFor(const Transform& current) const { + return Transform{noInterpolation[0]?current.r:prevModelSpaceTra.r,noInterpolation[1]?current.t:prevModelSpaceTra.t,noInterpolation[2]?current.s:prevModelSpaceTra.s}; + } void PostLoad(); private: