--- /dev/null +++ b/rts/Game/WebbarNanoAdapter.h @@ -0,0 +1,306 @@ +#pragma once +// GPL-2.0. CPU storage and unchanged original BAR nano-light callbacks. +static constexpr const char* WEBBAR_NANO_ADAPTER=R"WB_NANO_LUA(-- GPL-2.0. CPU storage boundary for the pinned, unchanged nano gadget. +-- All Spring queries remain engine-owned. No simulation mutator is exposed. +local function noop() end +local function buffer() + return {Define=noop,Upload=noop,Delete=noop,GetID=function()return 0 end} +end +local activeShader +webbarNanoVBO=nil +webbarNanoDraws=0 +webbarNanoUniforms={} +GL={ONE=1,SRC_ALPHA=770,ONE_MINUS_SRC_ALPHA=771,TRIANGLES=4,ARRAY_BUFFER=34962,ELEMENT_ARRAY_BUFFER=34963,UNSIGNED_INT=5125,FLOAT=5126,LEQUAL=515,FRONT_AND_BACK=1032,FILL=6914,KEEP=7680,NOTEQUAL=517,EQUAL=514,ALWAYS=519} +gl={GetVBO=buffer,ObjectLabel=noop,DepthTest=noop,DepthMask=noop,Culling=noop,AlphaTest=noop,Color=noop,ColorMask=noop,Scissor=noop,PolygonOffset=noop,PolygonMode=noop,StencilTest=noop,Blending=noop,Texture=noop,StencilMask=noop,StencilOp=noop,StencilFunc=noop} +gl.GetVAO=function() + local function draw() + assert(activeShader=='NanoParticlesGL4_Shape','Unexpected nano shader') + webbarNanoDraws=webbarNanoDraws+1 + end + return {AttachIndexBuffer=noop,AttachVertexBuffer=noop,AttachInstanceBuffer=noop,Delete=noop,DrawArrays=draw,DrawElements=draw} +end +gl.LuaShader={CheckShaderUpdates=function(cache) + assert(cache.shaderName=='NanoParticlesGL4_Shape','Unexpected nano shape path') + webbarNanoUniforms={} + for key,value in pairs(cache.uniformFloat or{})do webbarNanoUniforms[key]=value end + for key,value in pairs(cache.uniformInt or{})do webbarNanoUniforms[key]=value end + return {Activate=function()activeShader=cache.shaderName end,Deactivate=function()activeShader=nil end, + SetUniform=function(_,name,value)webbarNanoUniforms[name]=value end} +end} +gadget={} +GG={} +gadgetHandler={IsSyncedCode=function()return false end,RemoveGadget=function()error('Original nano gadget rejected its CPU adapter')end} +Platform={gpuVendor='WebBAR native CPU storage',osFamily='Browser'} +tracy={ZoneBeginN=noop,ZoneEnd=noop} +-- Original graphics options are private to this unsynced renderer. Retained +-- engine-spray observation/audio stays available for old presentation routes. +local getConfig=Spring.GetConfigInt +local config={NanoParticleMode=1,MaxNanoParticles=0,MaxParticles=30000,NanoParticleLights=1} +Spring.GetConfigInt=function(key,default)local value=config[key];if value~=nil then return value end;return getConfig(key,default)end +Spring.SetConfigInt=function(key,value)assert(key=='NanoParticleMode'or key=='MaxNanoParticles','Unexpected nano config write');config[key]=value end +Script=Script or{} +Script.LuaUI=setmetatable({},{__call=function(self,name)return type(self[name])=='function'end}) +function WebbarNanoInstallStorage() + local original=gl.InstanceVBOTable.makeInstanceVBOTable + gl.InstanceVBOTable.makeInstanceVBOTable=function(...) + local v=assert(original(...)) + if v.myName=='nanoParticleVBO'then assert(v.instanceStep==16);webbarNanoVBO=v end + return v + end +end + +-- Original storage is loaded before these original light callbacks. +)WB_NANO_LUA"; +static constexpr const char* WEBBAR_NANO_LIGHT_ADAPTER=R"WB_NANO_LIGHT(-- Original gfx_deferred_rendering_gl4.lua nano callbacks and expiry logic. +local InstanceVBOTable=gl.InstanceVBOTable +local popElementInstance,pushElementInstance=InstanceVBOTable.popElementInstance,InstanceVBOTable.pushElementInstance +local math_ceil,mathFloor=math.ceil,math.floor +local spawnFramePos,pieceIndexPos=17,25 +local autoLightInstanceID,numAddLights=128000,0 +local gameFrame,windX,windZ=Spring.GetGameFrame(),0,0 +local spGetWind=Spring.GetWind +local lightRemoveQueue,unitAttachedLights={},{} +WG={lightsgl4={}} +local widgetHandler={RegisterGlobal=function(_,name,fn)Script.LuaUI[name]=fn end} +webbarNanoLights=assert(InstanceVBOTable.makeInstanceVBOTable({{id=3,size=4},{id=4,size=4},{id=5,size=4},{id=6,size=4},{id=7,size=4},{id=8,size=4},{id=9,size=1,type=GL.UNSIGNED_INT},{id=10,size=4,type=GL.UNSIGNED_INT}},16,'Predictive Point Light VBO')) +local predictivePointLightVBO=webbarNanoLights +webbarNanoLightWidget={} +local function calcLightExpiry(targetVBO, lightParamTable, instanceID) + if lightParamTable[18] <= 0 then -- LifeTime less than 0 means never expires + return nil + end + local deathtime = math_ceil(lightParamTable[17] + lightParamTable[18]) + if lightRemoveQueue[deathtime] == nil then + lightRemoveQueue[deathtime] = {} + end + lightRemoveQueue[deathtime][instanceID] = targetVBO + return deathtime +end + +---AddLight(instanceID, unitID, pieceIndex, targetVBO, lightparams, noUpload) +---Note that instanceID can be nil if an auto-generated one is OK. +---If the light is not attached to a unit, and its lifetime is > 0, then it will be automatically added to the removal queue +---@param instanceID any usually nil, supply an existing instance ID if you want to update an existing light, +---@param unitID nil if worldpos, supply valid unitID if you want to attach it to something +---@param pieceIndex number if worldpos, supply valid piece index if you want to attach it to something, 0 attaches to world offset +---@param targetVBO table specify which one you want it to +---@param lightparams table a valid table of light parameters +---@param noUpload bool true if it shouldnt be uploaded to gpu yet +---@return instanceID for future reuse +local function AddLight(instanceID, unitID, pieceIndex, targetVBO, lightparams, noUpload) + if instanceID == nil then + autoLightInstanceID = autoLightInstanceID + 1 + instanceID = autoLightInstanceID + end + -- Preserve spawnframe on push-updates so time-based animations (lifetime/sustain/colortime) + -- don't get reset every time a light is updated in-place. + local existingIndex = targetVBO.instanceIDtoIndex[instanceID] + if existingIndex then + lightparams[spawnFramePos] = targetVBO.instanceData[(existingIndex - 1) * targetVBO.instanceStep + spawnFramePos] + else + lightparams[spawnFramePos] = gameFrame + end + lightparams[pieceIndexPos] = pieceIndex or 0 + --tracy.ZoneBeginN("pushElementInstance") + instanceID = pushElementInstance(targetVBO, lightparams, instanceID, true, noUpload, unitID) + --tracy.ZoneEnd() + if lightparams[18] > 0 then + calcLightExpiry(targetVBO, lightparams, instanceID) -- This will add lights that have >0 lifetime to the removal queue + end + if unitID then + if unitAttachedLights[unitID] == nil then + unitAttachedLights[unitID] = {[instanceID] = targetVBO} + else + unitAttachedLights[unitID][instanceID] = targetVBO + end + end + numAddLights = numAddLights + 1 + return instanceID +end + + WG['lightsgl4'].EnvNanoBallisticLightSpawn = function(instanceID, + x, y, z, vx, vy, vz, + radius, r, g, b, a, + lifetime, sustain, + modelfactor, specular, scattering, lensflare, + spawnframe, + updateEvery, + correctionMinFrames) + if not instanceID or not lifetime or lifetime < 1 then + return false + end + local sf = spawnframe or gameFrame + local lightparams = { + x, y, z, radius, + vx, vy, vz, 1.0, + r, g, b, a, + modelfactor or 0.35, specular or 0.15, scattering or 0.25, lensflare or 0, + sf, lifetime, sustain or lifetime, 0, + r, g, b, 0, + 0, + 0, 0, 0, 0, + } + AddLight(instanceID, nil, nil, predictivePointLightVBO, lightparams) + return true + end + WG['lightsgl4'].EnvNanoBallisticLightCorrect = function(instanceID, x, y, z, vx, vy, vz, frame) + local f = frame or gameFrame + local instanceIndex = predictivePointLightVBO.instanceIDtoIndex[instanceID] + if not instanceIndex then return false end + if instanceIndex then + instanceIndex = (instanceIndex - 1) * predictivePointLightVBO.instanceStep + local instData = predictivePointLightVBO.instanceData + instData[instanceIndex + 1] = x + instData[instanceIndex + 2] = y + instData[instanceIndex + 3] = z + instData[instanceIndex + 5] = vx + instData[instanceIndex + 6] = vy + instData[instanceIndex + 7] = vz + instData[instanceIndex + 8] = 1.0 + instData[instanceIndex + spawnFramePos] = f + predictivePointLightVBO.dirty = true + end + return true + end + WG['lightsgl4'].EnvNanoBallisticLightFade = function(instanceID, frame, fadeFrames) + local f = frame or gameFrame + local instanceIndex = predictivePointLightVBO.instanceIDtoIndex[instanceID] + if not instanceIndex then return false end + local ff = mathFloor(fadeFrames or 1) + if ff < 1 then ff = 1 end + instanceIndex = (instanceIndex - 1) * predictivePointLightVBO.instanceStep + local instData = predictivePointLightVBO.instanceData + instData[instanceIndex + spawnFramePos] = f + instData[instanceIndex + 18] = ff + instData[instanceIndex + 19] = 0 + local deathtime = math_ceil(f + ff) + if lightRemoveQueue[deathtime] == nil then + lightRemoveQueue[deathtime] = {} + end + lightRemoveQueue[deathtime][instanceID] = predictivePointLightVBO + predictivePointLightVBO.dirty = true + return true + end + WG['lightsgl4'].EnvNanoBallisticLightRemove = function(instanceID) + if predictivePointLightVBO.instanceIDtoIndex[instanceID] then + popElementInstance(predictivePointLightVBO, instanceID) + end + return true + end + widgetHandler:RegisterGlobal('EnvNanoBallisticLightSpawn', WG['lightsgl4'].EnvNanoBallisticLightSpawn) + widgetHandler:RegisterGlobal('EnvNanoBallisticLightCorrect', WG['lightsgl4'].EnvNanoBallisticLightCorrect) + widgetHandler:RegisterGlobal('EnvNanoBallisticLightFade', WG['lightsgl4'].EnvNanoBallisticLightFade) + widgetHandler:RegisterGlobal('EnvNanoBallisticLightRemove', WG['lightsgl4'].EnvNanoBallisticLightRemove) +function webbarNanoLightWidget:GameFrame(n) + if addrandomlights and (n % 100 == 0) then + AddRandomDecayingPointLight() + end + gameFrame = n + local windDirX, _, windDirZ, windStrength = spGetWind() + --windStrength = mathMin(20, mathMax(3, windStrength)) + --spEcho(windDirX,windDirZ,windStrength) + windX = windX + windDirX * 0.016 + windZ = windZ + windDirZ * 0.016 + local lightQueue = lightRemoveQueue[n] + if lightQueue then + for instanceID, targetVBO in pairs(lightQueue) do + if targetVBO.instanceIDtoIndex[instanceID] then + --spEcho("removing dead light", targetVBO.usedElements, 'id:', instanceID) + popElementInstance(targetVBO, instanceID) + end + end + lightRemoveQueue[n] = nil + end +end +)WB_NANO_LIGHT"; +static constexpr const char* WEBBAR_NANO_OWNERSHIP=R"WB_NANO_OWNER(WebbarNanoOwnershipInstall=(function() +-- GPL-2.0. Read-only provenance boundary around the unchanged nano gadget. +-- Install once after Initialize, before the first Update/Draw. No source +-- rewriting, unit-state writes, timing changes or random draws. IDs stay in +-- this engine-owned table; they are never a render packet. +return function(gadget, lightWidget, particleVBO, lightVBO, luaUI) + local getupvalue,setupvalue=debug.getupvalue,debug.setupvalue + local unpack=unpack or table.unpack + local function pack(...)return{n=select('#',...),...}end + local state={particles={},lights={}} + local context,anchors,seen=nil,{},{} + local roles={emitNano=true,spawnParticle=true,popElementInstance=true} + local function visit(fn) + if type(fn)~='function'or seen[fn]then return end + seen[fn]=true + for index=1,256 do + local name,value=getupvalue(fn,index);if not name then break end + if roles[name]then + assert(type(value)=='function','Unexpected original nano boundary: '..name) + anchors[#anchors+1]={fn=fn,index=index,role=name,original=value} + end + if type(value)=='function'then visit(value) + elseif name=='U'and type(value)=='table'then + for _,member in pairs(value)do if type(member)=='function'then visit(member)end end + end + end + end + for _,root in ipairs({gadget,lightWidget})do for _,fn in pairs(root)do visit(fn)end end + local found={};for _,a in ipairs(anchors)do found[a.role]=true end + assert(found.emitNano and found.spawnParticle and found.popElementInstance,'Original nano ownership boundaries unavailable') + local cache={emitNano={},spawnParticle={},popElementInstance={}} + for _,a in ipairs(anchors)do + local wrapper=cache[a.role][a.original] + if not wrapper then + local original=a.original + if a.role=='emitNano'then + wrapper=function(builderID,info,...) + local previous=context + context={builder=builderID,allyTeam=assert(info.allyTeam,'Missing native nano ally identity')} + local result=pack(pcall(original,builderID,info,...)) + context=previous + if not result[1]then error(result[2],0)end + return unpack(result,2,result.n) + end + elseif a.role=='spawnParticle'then + wrapper=function(...) + local result=pack(original(...));local id=result[1] + if id then + assert(context,'Original particle spawned outside observed emission') + state.particles[id]={builder=context.builder,allyTeam=context.allyTeam} + end + return unpack(result,1,result.n) + end + else + wrapper=function(vbo,id,...) + local result=pack(original(vbo,id,...)) + if not vbo.instanceIDtoIndex[id]then + if vbo==particleVBO then state.particles[id]=nil + elseif vbo==lightVBO then state.lights[id]=nil end + end + return unpack(result,1,result.n) + end + end + cache[a.role][original]=wrapper + end + setupvalue(a.fn,a.index,wrapper) + end + local originalSpawn=assert(luaUI.EnvNanoBallisticLightSpawn,'Missing original nano light callback') + luaUI.EnvNanoBallisticLightSpawn=function(id,...) + local result=pack(originalSpawn(id,...)) + if result[1]then + assert(context,'Original light spawned outside observed emission') + state.lights[id]={builder=context.builder,allyTeam=context.allyTeam} + end + return unpack(result,1,result.n) + end + local shutdown=gadget.Shutdown + if shutdown then + gadget.Shutdown=function(...) + local result=pack(pcall(shutdown,...)) + for id in pairs(state.particles)do state.particles[id]=nil end + for id in pairs(state.lights)do state.lights[id]=nil end + context=nil + if not result[1]then error(result[2],0)end + return unpack(result,2,result.n) + end + end + return state +end + +end)())WB_NANO_OWNER"; --- /dev/null +++ b/rts/Game/WebbarNanoPresentation.h @@ -0,0 +1,35 @@ +/* GPL-2.0. Original shader presentation evaluation; no unit/target state. */ +#pragma once +#include +#include +#include +namespace WebbarNanoPresentation { +enum class Result { Invalid, Expired, Ready }; +template inline bool Finite(const std::array& row){for(float v:row)if(!std::isfinite(v))return false;return true;} +inline Result Particle(const std::array& source,float time,std::array& out){ + if(!Finite(source)||!std::isfinite(time)||source[3]==0||source[11]<0||source[15]<=source[7])return Result::Invalid; + if(time>=source[15])return Result::Expired; + out=source;const float age=std::max(0.f,time-source[7]); + for(int i=0;i<3;i++){out[i]=source[i]+source[i+4]*age;out[i+4]=0;} + // Retain birth/rotation/noise/fade, but transport no source position or + // velocity. At this exact draw the unchanged shader produces the same mesh. + return Finite(out)?Result::Ready:Result::Invalid; +} +inline float ParticleRadius(const std::array& row,float time,float drawRadius,float glowScale){ + const float packed=std::abs(row[3]),fadeFrames=std::floor(packed/1024.f),sizeMult=(packed-fadeFrames*1024.f)/256.f; + const float fade=fadeFrames>.5f?std::clamp((row[15]-time)/fadeFrames,0.f,1.f):1.f; + return drawRadius*sizeMult*(.5f+.5f*fade)*std::max(std::sqrt(3.f),std::sqrt(2.f)*glowScale); +} +inline Result Light(const std::array& source,float time,std::array& out){ + if(!Finite(source)||!std::isfinite(time)||source[3]<=0||source[7]!=1||source[11]<0||source[17]<=0)return Result::Invalid; + if(time-source[16]>=source[17])return Result::Expired; + out.fill(0);std::copy_n(source.begin(),24,out.begin()); + // Original deferred point branch: movement = velocity * elapsedframes for + // Nano's ballistic flag1. Keep original lifetime/colour behavior, replacing + // only the already-evaluated world position and private trajectory vector. + const float elapsed=time-source[16];for(int i=0;i<3;i++){out[i]=source[i]+source[i+4]*elapsed;out[i+4]=0;} + for(int i=0;i<4;i++){out[24+i*5]=1;out[40+i]=1;} + // Slot44 is a unit ID in attached batches. World nano lights carry none. + return Finite(out)?Result::Ready:Result::Invalid; +} +} --- a/rts/Game/WebbarNativeBeams.h +++ b/rts/Game/WebbarNativeBeams.h @@ -52,7 +52,7 @@ float flameCamera[8]={}; float distortionViewport[2]={}; double nativeAtEpochMs=0;float nativeSimFPS=0;uint32_t nativeReserved=0; - bool flames=false,distortions=false; + bool flames=false,distortions=false;uint32_t nanoMode=0; }; static_assert(offsetof(WebbarBeamDrawRequest,flameCamera)==144); static bool ReadWebbarBeamDrawRequest(WebbarBeamDrawRequest& request,int32_t& sequence) @@ -61,7 +61,8 @@ 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.distortions=(box.version==3); + request.flames=(box.version>=2);request.distortions=(box.version>=3); + if(box.version==4){request.nanoMode=box.extensionPadding[0];if(request.nanoMode>7)return false;for(int i=1;i<50;i++)if(box.extensionPadding[i])return false;} 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; @@ -330,9 +331,10 @@ }; #include "WebbarNativeDistortion.h" +#include "WebbarNativeNano.h" static WebbarNativeBeamRenderer* webbarNativeBeams=nullptr; -static void FreeWebbarNativeBeams() { FreeWebbarNativeDistortion();delete webbarNativeBeams; webbarNativeBeams=nullptr; } +static void FreeWebbarNativeBeams() { FreeWebbarNativeNano();FreeWebbarNativeDistortion();delete webbarNativeBeams; webbarNativeBeams=nullptr; } static void PrepareWebbarNativeBeams() { static const bool enabled=std::getenv("WEBBAR_NATIVE_BEAM_VBO")!=nullptr; @@ -341,20 +343,21 @@ static bool announced=false; if(!announced) { announced=true; - webbarBeamDrawMailbox.version=WebbarDistortionEvents::Enabled()?3:WebbarFlamesEnabled()?2:1;webbarBeamDrawMailbox.bytes=webbarBeamDrawMailbox.version>=2?512:256; + webbarBeamDrawMailbox.version=WebbarNativeNanoRenderEnabled()?4: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()) { // Beam caches are view-specific. Original distortion wind and world-effect // lifetimes survive a spectator switch, as in native LuaUI. if(webbarNativeBeams->HasRewound()) FreeWebbarNativeDistortion(); - delete webbarNativeBeams;webbarNativeBeams=nullptr; + FreeWebbarNativeNano();delete webbarNativeBeams;webbarNativeBeams=nullptr; } if(!webbarNativeBeams) { webbarNativeBeams=new WebbarNativeBeamRenderer; webbarNativeBeams->epoch=++epoch; __atomic_store_n(&webbarBeamDrawMailbox.counters[3],epoch,__ATOMIC_RELEASE); PrepareWebbarNativeDistortion(epoch); + PrepareWebbarNativeNano(epoch); } } static void PublishWebbarNativeEtaDraw(float offset,int32_t sequence,uint32_t drawEpoch); @@ -380,6 +383,7 @@ } } webbarNativeBeams->Publish(request,sequence); + PublishWebbarNativeNanoDraw(request,sequence); if(request.distortions) PublishWebbarNativeDistortion(request,sequence); 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); --- /dev/null +++ b/rts/Game/WebbarNativeNano.h @@ -0,0 +1,132 @@ +/* This file is part of the Spring engine (GPL v2 or later), see LICENSE.html */ +#pragma once +#include "WebbarNanoAdapter.h" +#include "Lua/LuaFeatureDefs.h" +#include "Lua/LuaConstCMD.h" +#include "WebbarNanoPresentation.h" +static bool WebbarNativeNanoRenderEnabled(){static const bool enabled=std::getenv("WEBBAR_NATIVE_NANO_VBO")!=nullptr;return enabled;} + +// Original-gadget host. Optional WNN1 carries only draw-resolved positions. +// Owner identity, source positions and trajectory history stay inside this VM. +class WebbarNativeNano final: public CLuaHandle { +public: + explicit WebbarNativeNano(uint32_t epoch_):CLuaHandle("WebBAR original nano renderer",LUA_HANDLE_ORDER_RULES+2,false,false),epoch(epoch_),ally(gu->myAllyTeam),full(gu->spectatingFullView){ + SetFullCtrl(false);SetCtrlTeam(NoAccessTeam);SetSelectTeam(NoAccessTeam); + SetFullRead(true);SetReadTeam(AllAccessTeam);SetReadAllyTeam(full?AllAccessTeam:ally); + 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,"FeatureDefs",LuaFeatureDefs::PushEntries)&&AddEntriesToTable(L,"Game",LuaConstGame::PushEntries)&&AddEntriesToTable(L,"CMD",LuaConstCMD::PushEntries); + lua_settop(L,0); + if(ready){ + lua_getglobal(L,"Spring");Function("GetCameraPosition",CameraPosition);Function("IsSphereInView",SphereInView);Function("IsAABBInView",AABBInView);Function("IsUnitVisible",UnitVisible);Function("GetMapDrawMode",MapMode);lua_pop(L,1); + lua_newtable(L);Function("Include",Include);lua_setglobal(L,"VFS"); + ready=LoadCode(L,WEBBAR_NANO_ADAPTER,"Original nano CPU boundary"); + } + if(ready)ready=LoadCode(L,"gl.InstanceVBOTable=VFS.Include('modules/graphics/instancevbotable.lua');WebbarNanoInstallStorage()","Original nano instance storage"); + if(ready)ready=LoadCode(L,WEBBAR_NANO_LIGHT_ADAPTER,"Original nano light callbacks"); + if(ready)ready=LoadCode(L,"VFS.Include('LuaRules/Gadgets/gfx_nano_particles_gl4.lua')","Original nano gadget"); + if(ready)ready=LoadCode(L,WEBBAR_NANO_OWNERSHIP,"Read-only original nano ownership"); + if(ready)ready=LoadCode(L,R"NANO( +webbarNativeNanoGadget=gadget +function WebbarNanoInitialize() + webbarNativeNanoGadget:Initialize();assert(webbarNanoVBO) + webbarNanoOwnership=WebbarNanoOwnershipInstall(webbarNativeNanoGadget,webbarNanoLightWidget,webbarNanoVBO,webbarNanoLights,Script.LuaUI) + WebbarNanoOwnershipInstall=nil;debug=nil +end +function WebbarNanoSim(frame) webbarNanoLightWidget:GameFrame(frame) end +function WebbarNanoDraw() + assert(not webbarNanoFailure,webbarNanoFailure) + webbarNanoDraws=0 + webbarNativeNanoGadget:Update() + webbarNativeNanoGadget:DrawWorld() +end +function WebbarNanoShutdown() webbarNativeNanoGadget:Shutdown() end +for _,key in ipairs({'UnitCreated','UnitFinished','UnitDestroyed','UnitTaken','UnitGiven','FeatureDestroyed','RenderUnitDestroyed','PlayerChanged'}) do + local name=key + if webbarNativeNanoGadget[name] then + _G[name]=function(...) + local ok,why=pcall(webbarNativeNanoGadget[name],webbarNativeNanoGadget,...) + if not ok then webbarNanoFailure=tostring(why);error(why,0)end + end + end +end +)NANO","Original nano callins"); + if(ready)ready=Call("WebbarNanoInitialize"); + if(ready)eventHandler.AddClient(this);else Report(); + } + ~WebbarNativeNano()override{if(ready)Call("WebbarNanoShutdown");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,"WebbarNanoSim");lua_pushnumber(L,frame);ready=RunCallIn(L,LuaHashString("WebbarNanoSim"),1,0);if(!ready)Report();} + bool MatchesView()const{return ally==gu->myAllyTeam&&full==gu->spectatingFullView&&gs->frameNum>=lastFrame;} + void Publish(const WebbarBeamDrawRequest& next,int32_t sequence){ + if(!ready||!next.flames)return; + request=next;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;lastFrame=gs->frameNum; + ready=Call("WebbarNanoDraw");if(!ready){Report();return;} + int particles=0,lights=0,draws=0; + ready=Count("webbarNanoVBO",16,10000,particles)&&Count("webbarNanoLights",29,16384,lights); + lua_getglobal(L,"webbarNanoDraws");draws=lua_tointeger(L,-1);ready=ready&&lua_isnumber(L,-1)&&(draws==0||draws==2);lua_pop(L,1); + if(!ready){Report();return;} + if(WebbarNativeNanoRenderEnabled()&&!PublishPacket(sequence,particles,lights)){ready=false;Report();return;} + MAIN_THREAD_EM_ASM({if(Module['webbarNativeNanoProbe'])Module['webbarNativeNanoProbe']({frame:$0,epoch:$1,sequence:$2,particles:$3,lights:$4,draws:$5});},gs->frameNum,epoch,sequence,particles,lights,draws); + } +private: + static void Append(std::vector& out,const void* data,size_t bytes){const auto* p=static_cast(data);if(bytes)out.insert(out.end(),p,p+bytes);} + template bool Row(int row,std::array& values){for(size_t i=0;i=0&&value==std::floor(value);lua_pop(L,1);}lua_settop(L,top);return ok; + } + bool Shader(float* out){ + constexpr const char* names[]={"drawRadius","u_shape","glowScale","glowIntensity","cubeShowInside","cubeNoise","cubeNoiseSpeed","cubeNoiseScale","glowFalloff","coreBoost","hueJitter","losAlwaysVisible","whiteHotspot","whiteHotspotThreshold"}; + lua_getglobal(L,"webbarNanoUniforms");bool ok=lua_istable(L,-1);for(int i=0;i<14&&ok;i++){lua_getfield(L,-1,names[i]);out[i]=lua_tonumber(L,-1);ok=lua_isnumber(L,-1)&&std::isfinite(out[i]);lua_pop(L,1);}lua_pop(L,1);return ok&&out[0]>0&&(out[1]==0||out[1]==1)&&out[2]>=0&&(out[11]==0||out[11]==1); + } + bool PublishPacket(int32_t sequence,int particles,int lights){ + float state[20]={request.fraction};if(!Shader(state+4))return false;const float time=float(gs->frameNum)+request.fraction;if(!std::isfinite(time))return false; + std::vector p,l;uint32_t count=0,lightCount=0;p.reserve(particles*64);l.reserve(lights*180);bool ok=true; + lua_getglobal(L,"webbarNanoVBO");lua_getfield(L,-1,"instanceData"); + for(int i=0;i source{},out{};if(!Row(i,source)||!Owner("webbarNanoVBO","particles",i)){ok=false;break;} + const auto result=WebbarNanoPresentation::Particle(source,time,out);if(result==WebbarNanoPresentation::Result::Invalid){ok=false;break;}if(result==WebbarNanoPresentation::Result::Expired)continue; + const float radius=WebbarNanoPresentation::ParticleRadius(out,time,state[4],state[6]);if(!std::isfinite(radius)||radius<=0){ok=false;break;}if(!view.InView(float3(out[0],out[1],out[2]),radius))continue;Append(p,out.data(),sizeof(out));count++; + } + lua_pop(L,2);lua_getglobal(L,"webbarNanoLights");lua_getfield(L,-1,"instanceData"); + for(int i=0;i source{};std::array out{};if(!Row(i,source)||!Owner("webbarNanoLights","lights",i)){ok=false;break;} + const auto result=WebbarNanoPresentation::Light(source,time,out);if(result==WebbarNanoPresentation::Result::Invalid){ok=false;break;}if(result==WebbarNanoPresentation::Result::Expired||!view.InView(float3(out[0],out[1],out[2]),out[3]))continue;Append(l,out.data(),sizeof(out));lightCount++; + } + lua_pop(L,2);if(!ok)return false; + const uint32_t header[]={0x314e4e57,1,uint32_t(gs->frameNum),epoch,uint32_t(sequence),request.nanoMode,count,lightCount,64,180,1u|((request.flags&1u)?2u:0u),16,80,0,0,0}; + std::vector packet;packet.reserve(sizeof(header)+sizeof(state)+p.size()+l.size());Append(packet,header,sizeof(header));Append(packet,state,sizeof(state));Append(packet,p.data(),p.size());Append(packet,l.data(),l.size()); + MAIN_THREAD_EM_ASM({if(Module['webbarNativeNanoVBO'])Module['webbarNativeNanoVBO'](HEAPU8.slice($0,$0+$1).buffer);},packet.data(),packet.size());return true; + } + bool Count(const char* name,int stride,int limit,int& count){ + lua_getglobal(L,name);if(!lua_istable(L,-1)){lua_pop(L,1);return false;} + lua_getfield(L,-1,"usedElements");const bool integer=lua_isnumber(L,-1)&&lua_tonumber(L,-1)==std::floor(lua_tonumber(L,-1));count=lua_tointeger(L,-1);lua_pop(L,1); + if(!integer||count<0||count>limit){lua_pop(L,1);return false;} + if(WebbarNativeNanoRenderEnabled()){lua_pop(L,1);return true;} + lua_getfield(L,-1,"instanceData");bool valid=lua_istable(L,-1); + for(int i=1;i<=count*stride&&valid;i++){lua_rawgeti(L,-1,i);valid=lua_isnumber(L,-1)&&std::isfinite(lua_tonumber(L,-1));lua_pop(L,1);} + lua_pop(L,2);return valid; + } + void Report(){if(reported)return;reported=true;MAIN_THREAD_EM_ASM({if(Module['webbarNativeNanoError'])Module['webbarNativeNanoError']('Original nano CPU host failed; publication unavailable');});} + 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);} + static WebbarNativeNano* 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 nano include");std::string source;CFileHandler file(path,SPRING_VFS_MOD);if(!file.LoadStringData(source))return luaL_error(L,"Original nano source unavailable: %s",path.c_str());if(luaL_loadbuffer(L,source.data(),source.size(),path.c_str())!=0)return lua_error(L);if(lua_pcall(L,0,LUA_MULTRET,0)!=0)return lua_error(L);return lua_gettop(L)-top;} + static int MapMode(lua_State* L){constexpr const char* modes[]={"normal","los","metal","height","pathTraversability","pathHeat","pathFlow","pathCost"};const auto* s=Self(L);lua_pushstring(L,modes[s->request.nanoMode]);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 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 AABBInView(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)),float3(luaL_checkfloat(L,4),luaL_checkfloat(L,5),luaL_checkfloat(L,6))));return 1;} + static int UnitVisible(lua_State* L){auto* s=Self(L);return LuaUnsyncedRead::IsUnitVisibleForCamera(L,s->hasCamera?&s->view:nullptr);} + WebbarBeamDrawRequest request;CCamera view{CCamera::CAMTYPE_VISCUL};uint32_t epoch=0;int ally=-1,lastFrame=0;bool full=false,hasCamera=false,ready=false,reported=false; +}; +static WebbarNativeNano* webbarNativeNano=nullptr; +static void FreeWebbarNativeNano(){delete webbarNativeNano;webbarNativeNano=nullptr;} +static void PrepareWebbarNativeNano(uint32_t epoch){ + static const bool enabled=(std::getenv("WEBBAR_NATIVE_NANO_PROBE")!=nullptr||WebbarNativeNanoRenderEnabled());if(!enabled)return; + if(webbarNativeNano&&!webbarNativeNano->MatchesView())FreeWebbarNativeNano(); + if(!webbarNativeNano)webbarNativeNano=new WebbarNativeNano(epoch); +} +static void PublishWebbarNativeNanoDraw(const WebbarBeamDrawRequest& request,int32_t sequence){if(webbarNativeNano)webbarNativeNano->Publish(request,sequence);} --- a/rts/Lua/LuaUnsyncedRead.cpp +++ b/rts/Lua/LuaUnsyncedRead.cpp @@ -1865,6 +1865,11 @@ */ int LuaUnsyncedRead::IsUnitVisible(lua_State* L) { + return IsUnitVisibleForCamera(L, nullptr); +} + +int LuaUnsyncedRead::IsUnitVisibleForCamera(lua_State* L, CCamera* view) +{ CUnit* unit = ParseUnit(L, __func__, 1); if (unit == nullptr) @@ -1881,7 +1886,7 @@ } else { lua_pushboolean(L, (!checkIcon || !unit->GetIsIcon()) && - camera->InView(unit->midPos, radius)); + (view != nullptr ? view : camera)->InView(unit->midPos, radius)); } } else { @@ -1890,7 +1895,7 @@ } else { lua_pushboolean(L, (!checkIcon || !unit->GetIsIcon()) && - camera->InView(unit->midPos, radius)); + (view != nullptr ? view : camera)->InView(unit->midPos, radius)); } } return 1; --- a/rts/Lua/LuaUnsyncedRead.h +++ b/rts/Lua/LuaUnsyncedRead.h @@ -55,6 +55,7 @@ static int IsUnitAllied(lua_State* L); static int IsUnitInView(lua_State* L); static int IsUnitVisible(lua_State* L); + static int IsUnitVisibleForCamera(lua_State* L, CCamera* view); static int IsUnitIcon(lua_State* L); static int IsUnitSelected(lua_State* L);