--- a/rts/Game/WebbarBrowser.h +++ b/rts/Game/WebbarBrowser.h @@ -121,6 +121,7 @@ #include "WebbarNativeSensorRanges.h" #include "WebbarNativeHealthbars.h" #include "WebbarNativeOrbs.h" +#include "WebbarNativeDeferredLights.h" #include "WebbarNativeEta.h" #include "WebbarNativeScum.h" #include "WebbarMetalRead.h" --- /dev/null +++ b/rts/Game/WebbarDeferredLightEvents.h @@ -0,0 +1,41 @@ +/* This file is part of the Spring engine (GPL v2 or later), see LICENSE.html */ +#pragma once +#include +#include +#include +#include "lib/lua/include/LuaInclude.h" + +// Observe existing LuaRules messages only. No watch registration, synced +// event injection, stack conversion or controller mutation is introduced. +// These are private inputs to the unchanged unsynced LOS relays, not public +// packets. Nil explosion owners and the native ProjectileCreated owner=-1 +// sentinel retain their distinct values for original policy. +namespace WebbarDeferredLightEvents { +using Listener = void(*)(void*, lua_State*, int); +inline Listener listener = nullptr; +inline void* owner = nullptr; +inline void Attach(void* next, Listener callback) { assert(owner == nullptr); owner = next; listener = callback; } +inline void Detach(void* previous) { if (owner == previous) { listener = nullptr; owner = nullptr; } } +inline bool Integer(lua_State* source, int index, double low, double high) { + if (lua_type(source, index) != LUA_TNUMBER) return false; + const double value = lua_tonumber(source, index); + return std::isfinite(value) && value >= low && value <= high && value == std::floor(value); +} +inline void Observe(lua_State* source, int args) { + if (!listener || args < 5 || args > 6 || lua_type(source, 1) != LUA_TSTRING) return; + const char* name = lua_tostring(source, 1); + const bool explosion = std::strcmp(name, "explosion_light") == 0; + const bool barrel = std::strcmp(name, "barrelfire_light") == 0; + const bool script = std::strcmp(name, "cob_UnitScriptLight") == 0; + if (explosion || barrel) { + if (args != 6 || !Integer(source, 5, 0, 65535)) return; + for (int i = 2; i <= 4; ++i) + if (lua_type(source, i) != LUA_TNUMBER || !std::isfinite(lua_tonumber(source, i))) return; + if (lua_type(source, 6) != LUA_TNIL && !Integer(source, 6, -1, 65535)) return; + } else if (script) { + if (args != 5 || !Integer(source, 2, 0, 65535) || !Integer(source, 3, 0, 65535) + || !Integer(source, 4, 0, 65535) || !Integer(source, 5, -2147483648.0, 2147483520.0)) return; + } else return; + listener(owner, source, args); +} +} --- /dev/null +++ b/rts/Game/WebbarDeferredLightReader.inc @@ -0,0 +1,130 @@ +// Optional methods inside WebbarNativeHealthbarReader. Existing HUD readiness +// and permission flags remain independent of this presentation producer. +bool deferredReady=false, deferredHasCamera=false, deferredReported=false; +double deferredLastAt=0; +CCamera deferredView{CCamera::CAMTYPE_VISCUL}; +WebbarBeamDrawRequest deferredRequest; +static WebbarNativeHealthbarReader* DeferredSelf(lua_State* state) { + return static_cast(CLuaHandle::GetHandle(state)); +} +static int DeferredSphere(lua_State* state) { + auto* self=DeferredSelf(state); + const float3 position(luaL_checkfloat(state,1),luaL_checkfloat(state,2),luaL_checkfloat(state,3)); + const float radius=luaL_optfloat(state,4,0); + lua_pushboolean(state,self->deferredHasCamera&&self->deferredView.InView(position,radius));return 1; +} +static int DeferredProjectiles(lua_State* state) { + auto* self=DeferredSelf(state); + if(!self->deferredHasCamera){lua_newtable(state);return 1;} + return LuaUnsyncedRead::GetVisibleProjectilesForCamera(state,&self->deferredView); +} +static int DeferredEye(lua_State* state) { + auto* self=DeferredSelf(state); + for(float value:self->deferredRequest.eye)lua_pushnumber(state,value);return 3; +} +static int DeferredDirection(lua_State* state) { + auto* self=DeferredSelf(state); + for(float value:self->deferredRequest.direction)lua_pushnumber(state,value);return 3; +} +void PrepareDeferredLights() { + if(!ready||!std::getenv("WEBBAR_NATIVE_DEFERRED_LIGHTS"))return; + lua_getglobal(L,"Spring"); + #define DEFERRED_READ(name,method) lua_pushcfunction(L,LuaUnsyncedRead::method);lua_setfield(L,-2,name) + DEFERRED_READ("GetTeamColor",GetTeamColor); + DEFERRED_READ("GetConfigString",GetConfigString); + DEFERRED_READ("GetTimer",GetTimer); + DEFERRED_READ("GetTimerMicros",GetTimerMicros); + DEFERRED_READ("DiffTimers",DiffTimers); + DEFERRED_READ("GetDrawFrame",GetDrawFrame); + DEFERRED_READ("GetFPS",GetFPS); + DEFERRED_READ("GetModKeyState",GetModKeyState); + DEFERRED_READ("IsGUIHidden",IsGUIHidden); + DEFERRED_READ("GetMouseState",GetMouseState); + DEFERRED_READ("TraceScreenRay",TraceScreenRay); + #undef DEFERRED_READ + for(const auto& entry:std::initializer_list>{ + {"IsSphereInView",DeferredSphere},{"GetVisibleProjectiles",DeferredProjectiles}, + {"GetCameraPosition",DeferredEye},{"GetCameraDirection",DeferredDirection}}){ + lua_pushcfunction(L,entry.second);lua_setfield(L,-2,entry.first); + } + lua_pop(L,1); + const auto now=std::time(nullptr);const auto* local=std::localtime(&now); + if(!local||local->tm_mday<1||local->tm_mday>31)return; + const std::string code="assert(WebbarDeferredLightInitialize({dateDay="+std::to_string(local->tm_mday)+ + ",voidWater="+(mapInfo->map.voidWater?std::string("true"):std::string("false"))+ + ",deferredMap=true,deferredModel=true,platform={gpuVendor='Unknown',gpuMemorySize=0},featureSupport={transformsInGL4=true}}))"; + deferredReady=LoadCode(L,code,"Original deferred-light initialization");lua_settop(L,0); + if(deferredReady)WebbarDeferredLightEvents::Attach(this,[](void* owner,lua_State* source,int args){static_cast(owner)->DeferredSync(source,args);}); + else LOG_L(L_ERROR,"[WebBAR] original deferred-light policy initialization failed; existing HUD remains active"); +} +void DeferredSync(lua_State* source,int args) { + if(!deferredReady)return; + const int top=lua_gettop(L); + lua_getglobal(L,"WebbarDeferredLightSync");lua_pushstring(L,lua_tostring(source,1)); + for(int i=2;i<=args;i++){ + if(lua_type(source,i)==LUA_TNIL)lua_pushnil(L); + else lua_pushnumber(L,lua_tonumber(source,i)); + } + deferredReady=RunCallIn(L,LuaHashString("WebbarDeferredLightSync"),args,0);lua_settop(L,top); +} +bool DeferredState(std::vector& packet,const WebbarBeamDrawRequest& request) { + if(!deferredReady||!request.flames||packet.size()!=24)return false; + deferredRequest=request; + deferredView.SetPos(float3(request.eye[0],request.eye[1],request.eye[2])); + deferredView.SetRot(float3(request.flameCamera[5],request.flameCamera[6],request.flameCamera[7])); + deferredView.SetVFOV(request.flameCamera[0]);deferredView.SetAspectRatio(request.flameCamera[1]); + deferredView.SetFrustumScales(float4(0,0,request.flameCamera[2],request.flameCamera[3]));deferredView.UpdateFrustum();deferredHasCamera=true; + const double now=spring_tomsecs(globalRendering->grTime),dt=deferredLastAt>0?(now-deferredLastAt)*.001:0; + deferredLastAt=now;if(!std::isfinite(dt)||dt<0)return false; + const int top=lua_gettop(L);lua_getglobal(L,"WebbarDeferredLightState");lua_pushnumber(L,dt); + bool ok=RunCallIn(L,LuaHashString("WebbarDeferredLightState"),1,1)&&lua_istable(L,-1); + const int result=lua_gettop(L); + const auto field=[&](int table,const char* name,double& value){ + lua_getfield(L,table,name);const bool number=lua_type(L,-1)==LUA_TNUMBER;value=lua_tonumber(L,-1);lua_pop(L,1);return number&&std::isfinite(value); + }; + const auto word=[&](int offset,float value){if(!std::isfinite(value))return false;std::memcpy(&packet[offset],&value,4);return true;}; + double frame=0;ok=ok&&field(result,"frame",frame)&&frame==gs->frameNum; + if(ok){ + lua_getfield(L,result,"config");const int config=lua_gettop(L);double intensity=0,radius=0,shadows=0; + ok=lua_istable(L,config)&&field(config,"intensityMultiplier",intensity)&&field(config,"radiusMultiplier",radius)&&field(config,"screenSpaceShadows",shadows); + if(ok)ok=word(20,intensity)&&word(21,radius)&&word(22,1)&&word(23,shadows>0?std::min(64.0,std::floor(std::pow(2.0,shadows)*4)):0); + lua_pop(L,1); + } + if(ok){ + lua_getfield(L,result,"batches");const int batches=lua_gettop(L);ok=lua_istable(L,batches)&&lua_objlen(L,batches)<=11; + constexpr const char* names[]={"Cursor Point Light VBO","Point Light VBO","Predictive Point Light VBO","Projectile Point Light VBO","Beam Light VBO","Projectile Beam Light VBO","Cone Light VBO","Projectile Cone Light VBO","Unit Point Light VBO","Unit Beam Light VBO","Unit Cone Light VBO"}; + constexpr int shapes[]={0,0,0,0,1,1,2,2,0,1,2}; + int previous=-1;size_t total=0; + for(size_t b=1;ok&&b<=lua_objlen(L,batches);b++){ + lua_rawgeti(L,batches,b);const int batch=lua_gettop(L);ok=lua_istable(L,batch); + if(!ok){lua_pop(L,1);break;} + int group=-1;if(ok){lua_getfield(L,batch,"name");if(lua_type(L,-1)==LUA_TSTRING)for(int g=0;g<11;g++)if(std::strcmp(names[g],lua_tostring(L,-1))==0)group=g;lua_pop(L,1);} + double shape=0;ok=group>previous&&field(batch,"type",shape)&&shape==shapes[group];previous=group; + if(!ok){lua_pop(L,1);break;} + lua_getfield(L,batch,"attached");const bool attached=lua_toboolean(L,-1);ok=ok&&lua_type(L,-1)==LUA_TBOOLEAN&&attached==(group>=8);lua_pop(L,1); + lua_getfield(L,batch,"rows");const int rows=lua_gettop(L);ok=ok&&lua_istable(L,rows);const size_t count=ok?lua_objlen(L,rows):0;total+=count;ok=ok&&total<=65536&&(group!=2||count==0); + for(size_t r=1;ok&&r<=count;r++){ + lua_rawgeti(L,rows,r);const int row=lua_gettop(L);ok=lua_istable(L,row); + if(!ok){lua_pop(L,1);break;} + std::array data{}; + data[0]=uint32_t(shape);data[1]=attached;data[2]=0xffffffffu;data[6]=uint32_t(group); + double piece=0;ok=ok&&field(row,"piece",piece)&&piece>=0&&piece<=65535&&piece==std::floor(piece);data[5]=uint32_t(ok?piece:0); + bool admitted=true; + if(ok&&attached){ + double id=0;ok=field(row,"unit",id)&&id>=0&&id<=65535&&id==std::floor(id); + const CUnit* unit=ok&&idisDead&&!unit->noDraw&&!unit->IsInVoid()&&(gu->spectatingFullView||unit->allyteam==gu->myAllyTeam||unit->IsInLosForAllyTeam(gu->myAllyTeam)); + if(admitted){data[2]=unit->id;data[3]=unit->unitDef->id;data[4]=uint32_t(unit->creationFrame);} + } + lua_getfield(L,row,"params");const int params=lua_gettop(L);ok=ok&&lua_istable(L,params)&&lua_objlen(L,params)==24; + for(int j=0;ok&&j<24;j++){lua_rawgeti(L,params,j+1);const float value=lua_tonumber(L,-1);ok=lua_type(L,-1)==LUA_TNUMBER&&std::isfinite(value);if(ok)std::memcpy(&data[8+j],&value,4);lua_pop(L,1);} + lua_pop(L,1); + if(ok&&admitted){packet.insert(packet.end(),data.begin(),data.end());++packet[5];} + lua_pop(L,1); + } + lua_pop(L,2); + } + lua_pop(L,1); + } + lua_settop(L,top);if(!ok)deferredReady=false;return ok; +} --- a/rts/Game/WebbarNativeBeams.h +++ b/rts/Game/WebbarNativeBeams.h @@ -363,6 +363,7 @@ static void PublishWebbarNativeEtaDraw(float offset,int32_t sequence,uint32_t drawEpoch); static void PublishWebbarNativeScumDraw(int32_t sequence); static void PublishWebbarNativeOrbs(const WebbarBeamDrawRequest&, int32_t, uint32_t); +static void PublishWebbarNativeDeferredLights(const WebbarBeamDrawRequest&, int32_t, uint32_t); static void UpdateWebbarNativeBeams() { PrepareWebbarNativeBeams(); @@ -387,6 +388,7 @@ PublishWebbarNativeNanoDraw(request,sequence); if(request.distortions) PublishWebbarNativeDistortion(request,sequence); PublishWebbarNativeOrbs(request,sequence,webbarNativeBeams->epoch); + PublishWebbarNativeDeferredLights(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); --- /dev/null +++ b/rts/Game/WebbarNativeDeferredLights.h @@ -0,0 +1,17 @@ +/* This file is part of the Spring engine (GPL v2 or later), see LICENSE.html */ +#pragma once +// WDL1 is optional presentation, independent of bridge9 saves and commands. +static void PublishWebbarNativeDeferredLights(const WebbarBeamDrawRequest& request,int32_t sequence,uint32_t epoch) { + if(!std::getenv("WEBBAR_NATIVE_DEFERRED_LIGHTS"))return; + WebbarNativeHealthbars::Prepare();auto* reader=WebbarNativeHealthbars::reader; + if(reader&&reader->deferredReported)return; + std::vector packet{0x314c4457u,1,uint32_t(gs->frameNum),epoch,uint32_t(sequence),0,128,WebbarNativeHealthbars::epoch, + uint32_t(gu->myPlayerNum),uint32_t(gu->myTeam),uint32_t(gu->myAllyTeam),uint32_t(gu->spectating)|(uint32_t(gu->spectatingFullView)<<1),request.flags,0,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); + if(!reader||!reader->DeferredState(packet,request)){ + if(reader)reader->deferredReported=true; + MAIN_THREAD_EM_ASM({if(Module['webbarNativeDeferredLightError'])Module['webbarNativeDeferredLightError']('Original deferred-light policy unavailable');});return; + } + MAIN_THREAD_EM_ASM({if(Module['webbarNativeDeferredLightVBO'])Module['webbarNativeDeferredLightVBO'](HEAPU8.slice($0,$0+$1).buffer);},packet.data(),packet.size()*4); +} --- a/rts/Game/WebbarNativeHealthbarPolicy.h +++ b/rts/Game/WebbarNativeHealthbarPolicy.h @@ -1,8590 +1,53414 @@ -/* Original BAR GPL v2 or later policy; generated by scripts/native-orb-engine.mjs. */ -#pragma once -static constexpr const char* WEBBAR_HEALTHBAR_POLICY=R"WEBBAR_BARS( ---[[ -IMPORTANT NOTICE: Tests for these functions are provided via -`common/tableFunctionsTests.lua`, but the tests do not run unless you uncomment -them in `init.lua` (because they're not free to run, so we don't want them to -run for end users.) -]] - --- Lua 5.1 backwards compatibility -table.pack = table.pack or function(...) return { n = select("#", ...), ... } end - -if not table.copy then - function table.copy(tbl) - local copy = {} - for key, value in pairs(tbl) do - if type(value) == "table" then - copy[key] = table.copy(value) - else - copy[key] = value - end - end - return copy - end -end - -if not table.merge then - ---Return a new table of values from mergeData recursively merged into - ---mergeTarget, using deep copies. When there is a conflict, values in - ---mergeData take precedence. - ---@param mergeTarget table - ---@param mergeData table - ---@return table - function table.merge(mergeTarget, mergeData) - local new = table.copy(mergeTarget) - for key, value in pairs(mergeData) do - -- key not used in default, assign it the value at same key in override - if not new[key] and type(value) == "table" then - new[key] = table.copy(value) - -- values at key in both default and override are tables, merge those - elseif type(new[key]) == "table" and type(value) == "table" then - new[key] = table.merge(new[key], value) - else - new[key] = value - end - end - return new - end -end - -if not table.mergeInPlace then - ---Recursively in-place merge values from mergeData into mergeTarget. When - ---there is a conflict, values in mergeData take precedence. - ---@param mergeTarget table - ---@param mergeData table - ---@param deep? boolean if true, deep copy tables coming from mergeData (default: false) - ---@return table mergeTarget - function table.mergeInPlace(mergeTarget, mergeData, deep) - deep = deep or false - for key, value in pairs(mergeData) do - if type(value) == 'table' and type(mergeTarget[key] or false) == 'table' then - table.mergeInPlace(mergeTarget[key], value, deep) - elseif type(value) == "table" and deep then - mergeTarget[key] = table.copy(value) - else - mergeTarget[key] = value - end - end - return mergeTarget - end -end - -if not table.sortStable then - local function compareDefault(a, b) - return a < b - end - - ---Sorts list elements in a given order, *in-place*, from `list[1]` to `list[#list]`. - ---This method preserves elements' original order when possible, unlike `table.sort`. - ---@generic T - ---@param tbl T[] - ---@param compare fun(a: T, b: T) : boolean|nil where true := less than, false := greater than, nil := equal to - table.sortStable = function(tbl, compare) - if not compare then - compare = compareDefault - end - local index = table.getKeyOf -- local speedup - table.sort(tbl, function(a, b) - local comparison = compare(a, b) - return comparison or (comparison == nil and index(tbl, a) < index(tbl, b)) - end) - end -end - -if not table.ensureTable then - ---Ensures a table exists at the specified key, creating one if needed. - ---@param tbl table - ---@param key any - ---@return table nested in tbl at key - function table.ensureTable(tbl, key) - local sub = tbl[key] - if sub == nil then - sub = {} - tbl[key] = sub - elseif type(sub) ~= "table" then - error("existing entry is not a table") - end - return sub - end -end - -if not table.toString then - local stringRep = string.rep - local tableSort = table.sort - local DEFAULT_INDENT_STEP = 2 - - local function tableToString(tbl, options, _seen, _depth) - end - - local function keyCmp(a, b) - local ta = type(a) - local tb = type(b) - - -- numbers always sort before other keys - -- compare pairs of numbers directly - -- for everything else, convert to string first - if ta == "number" and tb == "number" then - return a < b - elseif ta == "number" and tb ~= "number" then - return true - elseif tb == "number" and ta ~= "number" then - return false - else - return tableToString(a) < tableToString(b) - end - end - - local tableConcat = table.concat - - tableToString = function(tbl, options, _seen, _depth) - _seen = _seen or {} - _depth = _depth or 0 - - local inputType = type(tbl) - - if inputType == "string" then - return "\"" .. tbl .. "\"" - elseif inputType == "userdata" then - return tostring(tbl) or "" - elseif inputType ~= "table" then - return tostring(tbl) - end - - if _seen[tbl] then - return "" - end - - _seen[tbl] = true - - local keys = {} - local keyCount = 0 - for key in pairs(tbl) do - keyCount = keyCount + 1 - keys[keyCount] = key - end - tableSort(keys, (options and options.keyCmp) or keyCmp) - - local indent = (options and options.indent) or DEFAULT_INDENT_STEP - local pretty = options and options.pretty - - local parts = {} - local n = 0 - - n = n + 1; parts[n] = "{" - if keyCount > 0 and pretty then - n = n + 1; parts[n] = "\n" - end - for i = 1, keyCount do - local key = keys[i] - if pretty then - n = n + 1; parts[n] = stringRep(" ", (_depth + 1) * indent) - end - if key ~= i then - local keyType = type(key) - if keyType == "string" then - n = n + 1; parts[n] = key - n = n + 1; parts[n] = "=" - elseif keyType == "number" then - n = n + 1; parts[n] = "[" - n = n + 1; parts[n] = tostring(key) - n = n + 1; parts[n] = "]=" - else - n = n + 1; parts[n] = "[" - n = n + 1; parts[n] = tableToString(key, options, _seen) - n = n + 1; parts[n] = "]=" - end - end - n = n + 1; parts[n] = tableToString(tbl[key], options, _seen, _depth + 1) - if i < keyCount or pretty then - n = n + 1; parts[n] = "," - end - if pretty then - n = n + 1; parts[n] = "\n" - end - end - if keyCount > 0 and pretty then - n = n + 1; parts[n] = stringRep(" ", _depth * indent) - end - n = n + 1; parts[n] = "}" - - return tableConcat(parts) - end - - ---Recursively turns a table into a string, suitable for printing. - --- - ---All types of keys and values are valid. How some special types are handled: - --- * `function` types are turned into "" - --- * `userdata` types are turned into "", unless they have a `tostring` metamethod, which is used instead - --- * cyclic or recursive references are turned into "" - --- * keys that are not strings or numbers (tables, functions, etc) are first run through table.toString - --- - ---In order to keep the output deterministic, keys are sorted. - ---@param tbl table - ---@param options table Optional parameters - ---@param options.pretty boolean Whether to add newlines and indentation (default: false) - ---@param options.indent number If pretty=true, the number of spaces to indent by at each indent step (default: 2) - ---@param options.keyCmp function Custom comparison function for sorting keys. If provided, this function will be used instead of the default comparison based on `table.toString(key)`. - ---@return string - table.toString = tableToString -end - -if not table.invert then - function table.invert(tbl) - local inverted = {} - for key, value in pairs(tbl) do - inverted[value] = key - end - return inverted - end -end - -if not table.getUniqueArray then - local sort, floor = table.sort, math.floor - - local lookup = {} - local function sortLookup(a, b) - return lookup[a] < lookup[b] - end - - ---Produces a new table that contains no duplicate and/or non-sequence-able entries. - --- - ---Values with non-integer keys are _ignored_. Values with integer keys are _sorted_. - --- - ---The final/sorted array forms a compact sequence with no gaps so can have new keys. - ---@param tbl table may contain array, hash, or mixed data and can have gaps - ---@return table sequence containing only unique entries, ordered by their integer indices - function table.getUniqueArray(tbl) - local unique, count = {}, 0 - local invert = {} - - -- Iterate the hash part to pull hashed integer keys back into the array part. - for index, option in pairs(tbl) do - if type(index) == "number" and index >= 1 and index == floor(index) then - if not invert[option] then - count = count + 1 - unique[count] = option - invert[option] = index - elseif invert[option] > index then - invert[option] = index - end - end - end - - lookup = invert - sort(unique, sortLookup) - - return unique - end -end - -if not table.append then - function table.append(appendTarget, appendData) - local n = #appendTarget - for i = 1, #appendData do - n = n + 1 - appendTarget[n] = appendData[i] - end - end -end - -if not table.count then - ---Count the number of values in table. - ---Note that this always works, whereas the default length operator (#table) - ---only works if the table is a Lua sequence (i.e. indexes form a contiguous - ---sequence starting from 1). - ---@param tbl table - ---@return number - function table.count(tbl) - local count = 0 - for _ in pairs(tbl) do - count = count + 1 - end - return count - end -end - -if not table.isEmpty then - ---Check if the table is empty. - ---@param tbl table - ---@return boolean - function table.isEmpty(tbl) - return next(tbl) == nil - end -end - -if not table.isNilOrEmpty then - ---Check if the table is empty. - ---@param tbl table - ---@return number - function table.isNilOrEmpty(tbl) - return tbl == nil or table.isEmpty(tbl) - end -end - -if not table.getKeyOf then - ---Find key of value in table. - ---Will always return the first key found, no matter if the table contains - ---multiple instances of the value. - ---@generic K, V - ---@param tbl table - ---@param value V - ---@return K? # key if found, nil otherwise - function table.getKeyOf(tbl, value) - for key, v in pairs(tbl) do - if v == value then - return key - end - end - return nil - end -end - -if not table.contains then - ---Check if value is in table. - ---@generic V - ---@param tbl table - ---@param value V - ---@return boolean - function table.contains(tbl, value) - return table.getKeyOf(tbl, value) ~= nil - end -end - -if not table.keys then - ---Returns all keys of a table as an array, and the count of keys. - ---@generic K - ---@param tbl table - ---@return K[] keys - ---@return number count - function table.keys(tbl) - local keys, count = {}, 0 - for key in pairs(tbl) do - count = count + 1 - keys[count] = key - end - return keys, count - end -end - -if not table.removeIf then - ---Remove values in table if they match the given predicate. - ---@generic V - ---@param tbl table - ---@param predicate fun(value: V): boolean - function table.removeIf(tbl, predicate) - for key, value in pairs(tbl) do - if predicate(value) then - tbl[key] = nil - end - end - end -end - -if not table.removeAll then - ---Remove all instances of value in table. - ---@generic V - ---@param tbl table - ---@param value V - function table.removeAll(tbl, value) - table.removeIf(tbl, function(v) return v == value end) - end -end - -if not table.removeFirst then - ---Remove first instance of value in table. - ---If table is a Lua sequence (i.e. indexes form a contiguous sequence - ---starting from 1), it will use `table.remove` to keep the sequence - ---contiguous, otherwise it will `nil` the instance. - ---@generic V - ---@param tbl V[]|table - ---@param value V - ---@return boolean # true if a value was removed, false otherwise - function table.removeFirst(tbl, value) - -- first, try to handle the table as a proper Lua sequence - -- this will fail as soon as there's a gap (missing integer index), but if - -- the table is a sequence then we want to keep that property by using - -- `table.remove` to keep the sequence intact without any gaps - for index, v in ipairs(tbl) do - if v == value then - table.remove(tbl, index) - return true - end - end - - -- otherwise, try to handle the table normally and simply `nil` the value - local found = table.getKeyOf(tbl, value) - if found ~= nil then - tbl[found] = nil - return true - end - - return false - end -end - -if not table.shuffle then - ---Shuffle sequence using Knuth (Fisher–Yates) algorithm. - ---@param sequence any[] must be a Lua sequence (i.e. indexes form a contiguous sequence starting from 1), with the exception that we optionally allow starting from 0 - ---@param firstIndex? 0|1 first index in the sequence (optional, default: 1) - function table.shuffle(sequence, firstIndex) - firstIndex = firstIndex or 1 - for i = firstIndex, #sequence - 2 + firstIndex do - local j = math.random(i, #sequence) - sequence[i], sequence[j] = sequence[j], sequence[i] - end - end -end - -if not table.map then - --- Applies a function to all elements of a table and returns a new table with the results. - ---@generic K, V, RV, RK - ---@param tbl table The input table. - ---@param callback fun(value: V, key: K, tbl: table): RV, RK The function to apply to each element. It receives three arguments: the element's value, its key, and the original table. It should return the new value, and optionally, a new key. - ---@return table A new table containing the results of applying the callback to each element. - function table.map(tbl, callback) - local result = {} - for k, v in pairs(tbl) do - local mappedValue, mappedKey = callback(v, k, tbl) - if mappedKey ~= nil then - result[mappedKey] = mappedValue - else - result[k] = mappedValue - end - end - return result - end -end - -if not table.reduce then - --- Reduces a table to a single value by applying a function to each element in order. - ---@generic K, V, R - ---@param tbl table The input table. - ---@param callback fun(acc: R, value: V, key: K, tbl: table): R The function to apply to each element. It receives four arguments: the accumulator, the element's value, its key, and the original table. - ---@param initial R The initial value of the accumulator. If no value is specified, the first callback will receive nil as the accumulator value. - ---@return R The final value of the accumulator after applying the callback to all elements. - function table.reduce(tbl, callback, initial) - local accumulator = initial - - for k, v in pairs(tbl) do - accumulator = callback(accumulator, v, k, tbl) - end - - return accumulator - end -end - -if not table.filterArray then - --- Creates a new (array-style) table containing only the elements that satisfy a given condition. - ---@generic V - ---@param tbl V[] The input table. - ---@param callback fun(value: V, index: number, tbl: V[]): boolean The condition to check for each element. It receives three arguments: the element's value, its key, and the original table. It should return true if the element satisfies the condition, false otherwise. - ---@return V[] A new table containing only the elements that satisfy the condition. - function table.filterArray(tbl, callback) - local result = {} - for i, v in ipairs(tbl) do - if callback(v, i, tbl) then - result[#result + 1] = v - end - end - return result - end -end - -if not table.filterTable then - --- Creates a new (dictionary-style) table containing only the elements that satisfy a given condition. - ---@generic K, V, R - ---@param tbl table The input table. - ---@param callback fun(value: V, key: K, tbl: table): boolean The condition to check for each element. It receives three arguments: the element's value, its index, and the original table. It should return true if the element satisfies the condition, false otherwise. - ---@return table A new table containing only the elements that satisfy the condition. - function table.filterTable(tbl, callback) - local result = {} - for k, v in pairs(tbl) do - if callback(v, k, tbl) then - result[k] = v - end - end - return result - end -end - -if not table.all then - --- Checks if all elements of a table satisfy a condition. - ---@generic K, V, R - ---@param tbl table The input table. - ---@param callback fun(value: V, key: K, tbl: table): boolean The condition to check for each element. It receives three arguments: the element's value, its key, and the original table. It should return true if the element satisfies the condition, false otherwise. - ---@return boolean True if all elements satisfy the condition, false otherwise. - function table.all(tbl, callback) - for k, v in pairs(tbl) do - if not callback(v, k, tbl) then - return false - end - end - return true - end -end - -if not table.any then - --- Checks if at least one element of a table satisfies a condition. - ---@generic K, V, R - ---@param tbl table The input table. - ---@param callback fun(value: V, key: K, tbl: table): boolean The condition to check for each element. It receives three arguments: the element's value, its key, and the original table. It should return true if the element satisfies the condition, false otherwise. - ---@return boolean True if at least one element satisfies the condition, false otherwise. - function table.any(tbl, callback) - for k, v in pairs(tbl) do - if callback(v, k, tbl) then - return true - end - end - return false - end -end - -if not table.valueIntersection then - ---Creates a new array-style table containing the intersection of all input arrays. - ---Returns only unique elements that appear in all input arrays. - ---@generic V - ---@param ... V[] Any number of array-style tables. - ---@return V[] A new array containing only values present in all input arrays. - function table.valueIntersection(...) - local tables = { ...} - - -- Count occurrences of each value across all arrays - local valueCounts = {} - for _, tbl in pairs(tables) do - -- Use a set for each array to handle duplicates correctly - local seen = {} - for _, value in pairs(tbl) do - if not seen[value] then - seen[value] = true - valueCounts[value] = (valueCounts[value] or 0) + 1 - end - end - end - - -- Keep only values that appear in all arrays - local result = {} - local numTables = table.count(tables) - for value, count in pairs(valueCounts) do - if count == numTables then - result[#result + 1] = value - end - end - - return result - end -end - -if not pairsByKeys then - ---pairs-like iterator function traversing the table in the order of its keys. - ---Natural sort order will be used by default, optionally pass a comparator - ---function for custom sorting. - ---@generic K, V - ---@param tbl table - ---@param keySortFunction? fun(a: K, b: K): boolean comparator function passed to table.sort for sorting keys - ---@return fun(table: table, index?: K): K, V - ---@return table - ---(Implementation copied straight from the docs at https://www.lua.org/pil/19.3.html.) - function pairsByKeys(tbl, keySortFunction) - local keys = {} - for key in pairs(tbl) do table.insert(keys, key) end - table.sort(keys, keySortFunction) - local i = 0 -- iterator variable - local iter = function() -- iterator function - i = i + 1 - if keys[i] == nil then - return nil - else - return keys[i], tbl[keys[i]] - end - end - return iter - end -end - -local originalSpring=Spring -local Spring=setmetatable({GetModOptions=originalSpring.GetModOptions},{__index=originalSpring}) -local options=(function() --- Custom Options Definition Table format --- NOTES: --- using an enumerated table lets you specify the options order --- --- These keywords must be lowercase for LuaParser to read them. --- --- key: the string used in the script.txt --- name: the displayed name --- desc: the description (could be used as a tooltip) --- hint: greyed out text that appears in input field when empty --- type: the option type ('list','string','number','bool','subheader','separator') --- def: the default value --- min: minimum value for number options --- max: maximum value for number options --- step: quantization step, aligned to the def value --- maxlen: the maximum string length for string options --- items: array of item strings for list options --- section: so lobbies can order options in categories/panels --- scope: 'all', 'player', 'team', 'allyteam' <<< not supported yet >>> --- collumn: moves the option 1 row up if value is greater than the preivous row's one, default: 1 --- | negative value forces new row, absolute value is used --- | zero moves to the left, 1 is default, 2 is half way to the right --- | recommened values: for 2 columns: 1 and 2, for 3 columns 1, 1.66, and 2.33 --- --- lock: if type is bool: hides the table of keys when set to TRUE <<< can not hide separators >>> --- | if type is list: add under each item what it should SHOW when set to --- unlock: if type is bool: hides the table of keys when set to FALSE <<< can not hide separators >>> --- | if type is list: add under each item what it should HIDE when set to --- bitmask: int (1|2|4|8...etc), for when multiple options can hide an item - -local options = { - - --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- - --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- - -- Main + Restrictions - --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- - --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- - { - key = "options_main", - name = "Main", - desc = "", - type = "section", - weight = 7, - }, - - { - key = "sub_header", - name = "Options for changing base game settings.", - desc = "", - section = "options_main", - type = "subheader", - def = true, - }, - - { - key = "sub_header", - section = "options_main", - type = "separator", - }, - - { - key = "ranked_game", - name = "Ranked Game", - desc = "Should game results affect OpenSkill. Note that games with AI or games that are not balanced are always unranked.", - type = "bool", - section = "options_main", - def = true, - }, - - - { - key = "allowuserwidgets", - name = "Allow Custom Widgets", - desc = "Allow custom user widgets or disallow them", - type = "bool", - def = true, - hidden = true, - section = "options_main", - }, - - { - key = "allowunitcontrolwidgets", - name = "Allow Custom 'Unit Control' Widgets", - desc = "Allow custom user 'unit control' widgets or disallow them", - type = "bool", - def = true, - section = "options_main", - }, - - { - key = "allowpausegameplay", - name = "Allow Commands While Paused", - desc = "Allow giving unit commands while paused", - type = "bool", - def = true, - section = "options_main", - }, - - { - key = "sub_header", - section = "options_main", - type = "separator", - }, - - { - key = "sub_header", - name = "-- Gameplay Settings", - desc = "", - section = "options_main", - type = "subheader", - def = true, - }, - - { - key = "maxunits", - name = "Max Units Per Player", - desc = "Keep in mind there is an absolute limit of units, 32 000, divided between each team. If you set this value higher than possible it will force itself down to the maximum it can be.", - type = "number", - def = 2000, - min = 500, - max = 32000, - step = 1, -- quantization is aligned to the def value, (step <= 0) means that there is no quantization - section = "options_main", - }, - { - key = "deathmode", - name = "Game End Mode", - desc = "What it takes to eliminate a team", - type = "list", - def = "com", - section = "options_main", - items = { - { key = "neverend", name = "Never ending", desc = "Teams are never eliminated", lock = { "territorial_domination_config", "territorial_domination_elimination_threshold_multiplier" } }, - { key = "com", name = "Kill all enemy Commanders", desc = "When a team has no Commanders left, it loses", lock = { "territorial_domination_config", "territorial_domination_elimination_threshold_multiplier" } }, - { key= "territorial_domination", name= "Territorial Domination", desc="Teams earn points by capturing territory to stay in the game. At the end of the final round, the team with the most points wins.", unlock = {"territorial_domination_config", "territorial_domination_elimination_threshold_multiplier"} }, - { key = "builders", name = "Kill all Builders", desc = "When a team has no builders left, it loses", lock = { "territorial_domination_config", "territorial_domination_elimination_threshold_multiplier" } }, - { key = "killall", name = "Kill everything", desc = "Every last unit must be eliminated, no exceptions!", lock = { "territorial_domination_config", "territorial_domination_elimination_threshold_multiplier" } }, - { key = "own_com", name = "Player resign on Com death", desc = "When player commander dies, you auto-resign.", lock = { "territorial_domination_config", "territorial_domination_elimination_threshold_multiplier" } }, - } - }, - - { - key = "territorial_domination_config", - name = "Territorial Domination Length", - desc = - "Configures the grace period and the amount of time in minutes it takes to reach the maximum required territory.", - type = "list", - def = "25_minutes", - section = "options_main", - items = { - { key = "20_minutes", name = "4 Rounds, 20 Minutes", desc = "Early tech emphasis, comebacks very likely, elimination unlikely." }, - { key = "25_minutes", name = "5 Rounds, 25 Minutes(Default)", desc = "Mid/late-game tech, comebacks a significant factor, eliminations uncommon" }, - { key = "30_minutes", name = "6 Rounds, 30 Minutes", desc = "Late-game tech, comebacks less significant, eliminations likely" }, - { key = "35_minutes", name = "7 Rounds, 35 Minutes", desc = "Super lategame tech, eliminations extremely likely" }, - } - }, - - { - key = "territorial_domination_elimination_threshold_multiplier", - name = "Elimination Threshold Multiplier", - desc = "Teams are eliminated at round end when score < elimination threshold which is set by highest score multiplied by this value. Lower values are more lenient.", - type = "number", - def = 1.2, - min = 1.0, - max = 1.5, - step = 0.1, - section = "options_main", - }, - - { - key = "draft_mode", - name = "Draft Spawn Order Mode", - desc = "Random/Captain/Skill/Fair based startPosType modes. Default: Random.", - type = "list", - section = "options_main", - def = "random", - items = { - { key = "disabled", name = "Disabled", desc = "Disable draft mod. Fast-PC place first." }, - { key = "random", name = "Random Order", desc = "Players get to pick a start position with a delay in a random order." }, - { key = "captain", name = "Captains First", desc = "Captain picks first, then everyone else in a random order." }, - { key = "skill", name = "Skill Order", desc = "Skill-based order, instead of random." }, - { key = "fair", name = "After full team has loaded", desc = "Everyone must join the game first - after that (+2sec delay) everyone can place." } - }, - }, - - { - key = "teamcolors_anonymous_mode", - name = "Anonymous Mode", - desc = "Anonymize players by changing colors (based on chosen mode) and replacing names with question marks, making it harder to know who's who.", - type = "list", - section = "options_main", - def = "disabled", - items = { - { key = "disabled", name = "Disabled" }, - { key = "global", name = "Shuffle Globally", desc = "You can distinguish different players and everyone sees the same colors globally. Diplomacy is the same as usual except using colors instead of names (e.g. \"Red, let's ally against Blue\")." }, - { key = "local", name = "Shuffle Locally", desc = "You can distinguish different players but everyone sees different colors locally. Diplomacy is harder but possible using positions (e.g. \"Southeast, let's ally against Northeast\")." }, - { key = "disco", name = "Shuffle Locally (Continiously)", desc = "Same as local shuffle, except that colors are reshuffled every 2 mins for extra spicyness." }, - { key = "allred", name = "Everyone Is Red", desc = "You cannot distinguish different players, they all have the same color (red by default, can be changed in accessibility settings). Diplomacy is very hard." }, - }, - }, - - { - key = "transportenemy", - name = "Enemy Transporting", - desc = "Toggle which enemy units you can kidnap with an air transport", - hidden = true, - type = "list", - def = "notcoms", - section = "options_main", - items = { - { key= "notcoms", name= "All But Commanders", desc= "Only commanders are immune to napping" }, - { key= "none", name= "Disallow All", desc= "No enemy units can be napped" }, - } - }, - - { - key = "teamffa_start_boxes_shuffle", - name = "Shuffle TeamFFA Start Boxes", - desc = "In TeamFFA games (more than 2 teams, excluding Raptors / Scavengers), start boxes will be randomly assigned to each team: team 1 might be assigned any start box rather than team 1 always being assigned start box 1.", - type = "bool", - section = "options_main", - def = true, - }, - - { - key = "fixedallies", - name = "Disabled Dynamic Alliances", - desc = "Disables the possibility of players to dynamically change alliances ingame", - type = "bool", - def = true, - hidden = true, - section = "options_main", - }, - - { - key = "disablemapdamage", - name = "Disable Map Deformation", - desc = "Prevents the map shape from being changed by weapons", - type = "bool", - def = false, - section = "options_main", - }, - - { - key = "disable_fogofwar", - name = "Disable Fog of War", - desc = "Disable Fog of War", - type = "bool", - section = "options_main", - def = false, - }, - - { - key = "norushtimer", - name = "No Rush Time".."\255\128\128\128".." [minutes]", - desc = "Set timer in which players cannot get out of their startbox, so you have time to prepare before fighting.\n".. - "PLEASE NOTE: For this to work, the game needs to have set startboxes.\n".. - -- tabs don't do much in chobby - " It won't work in FFA mode without boxes.\n".. - " Also, it does not affect Scavengers and Raptors.\n".. - "\255\75\0\100".."WARNING: No Rush Time over 30 minutes may cause performance or stability issues due to excessive unit buildup.", - type = "number", - section = "options_main", - def = 0, - min = 0, - max = 120, - step = 1, - }, - { - key = "norushmiddlefree", - name = "No Rush Non Base FFA", - desc = "Allows units to leave startboxes but disallows commands issued in enemy startboxes.\n".. - "Does not prevent commands onto the other side of startboxes so recommend East/West or North/South startboxes.", - type = "bool", - section = "options_main", - def = false, - }, - - { - key = "comm_trans_slow", - name = "Slow Commander Transport", - desc = "T2 transports carrying a Commander, move at speed 120. A temporary option available, until bigger transport changes get finished.", - type = "bool", - section = "options_main", - def = false, - }, - - { - key = "sub_header", - section = "options_main", - type = "separator", - }, - { - key = "sub_header", - name = "-- Sharing and Taxes", - section = "options_main", - type = "subheader", - def = true, - }, - { - key = "tax_resource_sharing_amount", - name = "Resource Sharing Tax", - desc = "Taxes resource sharing".."\255\128\128\128".." and overflow (engine TODO:)\n".. - "Set to [0] to turn off. Recommended: [0.4]. (Ranges: 0 - 0.99)", - type = "number", - def = 0, - min = 0, - max = 0.99, - step = 0.01, - section = "options_main", - column = 1, - }, - { - key = "disable_unit_sharing", - name = "Disable Unit Sharing", - desc = "Disable sharing units and structures to allies", - type = "bool", - section = "options_main", - def = false, - }, - { - key = "disable_assist_ally_construction", - name = "Disable Assist Ally Construction", - desc = "Disables assisting allied blueprints and labs.", - type = "bool", - section = "options_main", - def = false, - column = 1.66, - }, - { - key = "sub_header", - section = "options_main", - type = "separator", - }, - - { - key = "sub_header", - name = "-- Unit Restrictions", - desc = "", - section = "options_main", - type = "subheader", - def = true, - }, - - { - key = "unit_restrictions_notech15", - name = "Disable Tech 1.5", - desc = "Disables: Sea Plane Labs, Hovercraft labs, and Amphibious labs. (Considered Tier 1.5)", - type = "bool", - section = "options_main", - def = false, - column = 1, - }, - - { - key = "unit_restrictions_notech2", - name = "Disable Tech 2", - desc = "Disable Tech 2", - type = "bool", - section = "options_main", - def = false, - column = 1.66, - }, - - { - key = "unit_restrictions_notech3", - name = "Disable Tech 3", - desc = "Disable Tech 3", - type = "bool", - section = "options_main", - def = false, - column = 2.33, - }, - - { - key = "unit_restrictions_noair", - name = "Disable Air Units", - desc = "Disable Air Units", - type = "bool", - section = "options_main", - def = false, - column = 1, - }, - - { - key = "unit_restrictions_nosea", - name = "Disable Sea Units", - desc = "Disable Sea Units", - type = "bool", - section = "options_main", - def = false, - column = 1.66, - }, - - { - key = "unit_restrictions_noextractors", - name = "Disable Metal Extractors", - desc = "Disable Metal Extractors", - type = "bool", - section = "options_main", - def = false, - column = 1, - }, - - { - key = "unit_restrictions_noconverters", - name = "Disable Energy Converters", - desc = "Disable Energy Converters", - type = "bool", - section = "options_main", - def = false, - column = 1.66, - }, - - { - key = "unit_restrictions_nofusion", - name = "Disable Fusion Generators", - desc = "Disables Normal and Advanced Fusion Energy Generators", - type = "bool", - section = "options_main", - def = false, - column = 2.33, - }, - - { - key = "unit_restrictions_notacnukes", - name = "Disable Tactical Missiles/EMPs", - desc = "Disables Cortex Tactical Missile Launcher and Armada EMP Missile Launcher", - type = "bool", - section = "options_main", - def = false, - column = 1, - }, - - { - key = "unit_restrictions_nonukes", - name = "Disable Nuclear Missiles", - desc = "Disable Nuclear Missiles", - type = "bool", - section = "options_main", - def = false, - column = 1.66, - }, - - { - key = "unit_restrictions_noantinuke", - name = "Disable Anti-Nuke Defence", - desc = "Disables Nuke Interceptor Units and Structures.", - type = "bool", - section = "options_main", - def = false, - column = 2.33, - }, - - { - key = "unit_restrictions_nolrpc", - name = "Disable Long Range Artilery (LRPC)", - desc = "Disable Long Range Plasma Artilery (LRPC) structures", - type = "bool", - section = "options_main", - def = false, - column = 1, - }, - - { - key = "unit_restrictions_noendgamelrpc", - name = "Disable Endgame Artilery (LRPC)", - desc = "Disable Endgame Long Range Plasma Artilery (LRPC) structures (AKA lolcannons)", - type = "bool", - section = "options_main", - def = false, - column = 1.66, - }, - - - --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- - --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- - -- Other Options - --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- - --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- - - { - key = "options", - name = "Other", - desc = "Options", - type = "section", - }, - - { - key = "map_tidal", - name = "Tidal Strength", - desc = "Unchanged = map setting, low = 13e/sec, medium = 18e/sec, high = 23e/sec.", - hidden = true, - type = "list", - def = "unchanged", - section = "options", - items = { - { key = "unchanged", name = "Unchanged", desc = "Use map settings" }, - { key = "low", name = "Low", desc = "Set tidal incomes to 13 energy per second" }, - { key = "medium", name = "Medium", desc = "Set tidal incomes to 18 energy per second" }, - { key = "high", name = "High", desc = "Set tidal incomes to 23 energy per second" }, - } - }, - - { - key = "critters", - name = "Animal amount", - desc = "This multiplier will be applied on the amount of critters a map will end up with", - hidden = true, - type = "number", - section = "options", - def = 1, - min = 0, - max = 2, - step = 0.2, - }, - - { - key = "map_atmosphere", - name = "Map Atmosphere and Ambient Sounds", - desc = "", - type = "bool", - def = true, - hidden = true, - section = "options", - }, - - { - key = "ffa_wreckage", - name = "FFA Mode Wreckage", - desc = "Killed players will blow up but leave wreckages", - hidden = true, - type = "bool", - def = false, - section = "options", - }, - - { - key = "wreck_metal_ratio", - name = "Wreck Metal Percent", - desc = "Percent of unit metal that is left in its wrecks", - hidden = true, - type = "number", - section = "options", - def = 0.6, - min = 0, - max = 1, - step = 0.05, - }, - - { - key = "heap_metal_ratio", - name = "Heap Metal Percent", - desc = "Percent of unit metal that is left in its heaps", - hidden = true, - type = "number", - section = "options", - def = 0.25, - min = 0, - max = 1, - step = 0.05, - }, - - { - key = "coop", - name = "Cooperative mode", - desc = "Adds extra commanders to id-sharing teams, 1 com per player", - type = "bool", - hidden = true, - def = false, - section = "options", - }, - - --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- - --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- - -- Multiplier Options - --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- - --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- - - --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- - --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- - -- Raptors - --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- - --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- - { - key = "raptor_defense_options", - name = "Raptors", - desc = "Various gameplay options that will change how the Raptor Defense is played.", - type = "section", - weight = 4, - }, - - { - key = "sub_header", - name = "Raptors Gamemode Options.", - desc = "", - section = "raptor_defense_options", - type = "subheader", - def = true, - }, - - { - key = "raptors_dev_channel_link", - name = "Development Discussion", - desc = "Raptors development discussion.", - section = "raptor_defense_options", - type = "link", - link = "https://discord.com/channels/549281623154229250/781097030692110346", - width = 275, - column = 1.65, - linkheight = 325, - linkwidth = 350, - }, - - { - key = "sub_header", - name = "To Play Add a Raptors AI to the enemy Team: [Add AI], [RaptorsDefense AI]", - desc = "", - section = "raptor_defense_options", - type = "subheader", - }, - - { - key = "sub_header", - section = "raptor_defense_options", - type = "separator", - }, - - { - key = "raptor_difficulty", - name = "Base Difficulty", - desc = "Raptors difficulty", - type = "list", - def = "normal", - section = "raptor_defense_options", - items = { - { key = "veryeasy", name = "Very Easy", desc="Very Easy" }, - { key = "easy", name = "Easy", desc="Easy" }, - { key = "normal", name = "Normal", desc="Normal" }, - { key = "hard", name = "Hard", desc="Hard" }, - { key = "veryhard", name = "Very Hard", desc="Very Hard" }, - { key = "epic", name = "Epic", desc="Epic" }, - } - }, - - { - key = "sub_header", - section = "raptor_defense_options", - type = "separator", - }, - - { - key = "raptor_raptorstart", - name = "Hives Placement", - desc = "Control where hives spawn", - type = "list", - def = "initialbox", - section = "raptor_defense_options", - items = { - { key = "avoid", name = "Spawn Anywhere", desc = "Hives avoid player units" }, - { key = "initialbox", name = "Growing Spawn Box", desc = "Hives spawn in limited area that increases over time" }, - { key = "alwaysbox", name = "Always Start Box", desc = "Hives always spawn in raptor start box" }, - } - }, - - { - key = "raptor_endless", - name = "Endless Mode", - desc = "When you kill the queen, the game doesn't end, but loops around at higher difficulty instead, infinitely.", - type = "bool", - def = false, - section = "raptor_defense_options", - }, - - { - key = "sub_header", - section = "raptor_defense_options", - type = "separator", - }, - - { - key = "sub_header", - name = "-- Advanced Options, Change at your own risk.", - desc = "", - section = "raptor_defense_options", - type = "subheader", - def = true, - }, - - { - key = "raptor_queentimemult", - name = "Queen Hatching Time Multiplier", - desc = "(Range: 0.1 - 2). How quickly Queen Hatch goes from 0 to 100%", - type = "number", - def = 1, - min = 0.1, - max = 2, - step = 0.1, - section = "raptor_defense_options", - }, - - { - key = "raptor_queen_count", - name = "Raptor Queen Count", - desc = "(Range: 1 - 100). Number of queens that will spawn.", - type = "number", - def = 1, - min = 1, - max = 100, - step = 1, - section = "raptor_defense_options", - }, - - { - key = "raptor_spawncountmult", - name = "Unit Spawn Per Wave Multiplier", - desc = "(Range: 1 - 5). How many times more raptors will spawn per wave.", - type = "number", - def = 1, - min = 1, - max = 5, - step = 1, - section = "raptor_defense_options", - }, - - { - key = "raptor_firstwavesboost", - name = "First Waves Size Boost", - desc = "(Range: 1 - 10). Intended to use with heavily modified settings. Makes first waves larger, the bigger the number the larger they are. Cools down within first few waves.", - type = "number", - def = 1, - min = 1, - max = 10, - step = 1, - section = "raptor_defense_options", - }, - - { - key = "raptor_spawntimemult", - name = "Waves Amount Multiplier", - desc = "(Range: 1 - 5). How often new waves will spawn. Bigger Number = More Waves", - type = "number", - def = 1, - min = 1, - max = 5, - step = 0.1, - section = "raptor_defense_options", - }, - - { - key = "raptor_graceperiodmult", - name = "Grace Period Time Multiplier", - desc = "(Range: 0.1 - 3). Time before Raptors become active. ", - type = "number", - def = 1, - min = 0.1, - max = 3, - step = 0.1, - section = "raptor_defense_options", - }, - - - --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- - --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- - -- Scavengers - --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- - --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- - { - key = "scav_defense_options", - name = "Scavengers", - desc = "Gameplay options for Scavengers gamemode", - type = "section", - weight = 3, - }, - - { - key = "sub_header", - name = "Scavengers Gamemode Options.", - desc = "", - section = "scav_defense_options", - type = "subheader", - def = true, - }, - - { - key = "scavengers_dev_channel_link", - name = "Development Discussion", - desc = "Scavengers development discussion.", - section = "scav_defense_options", - type = "link", - link = "https://discord.com/channels/549281623154229250/659550298653589504", - width = 275, - column = 1.65, - linkheight = 325, - linkwidth = 350, - }, - - { - key = "sub_header", - name = "To Play Add a Scavangers AI to the enemy Team: [Add AI], [ScavengersDefense AI]", - desc = "", - section = "scav_defense_options", - type = "subheader", - }, - - - { - key = "sub_header", - section = "scav_defense_options", - type = "separator", - }, - - { - key = "scav_difficulty", - name = "Base Difficulty", - desc = "Scavs difficulty", - type = "list", - def = "normal", - section = "scav_defense_options", - items = { - { key = "veryeasy", name = "Very Easy", desc = "Very Easy" }, - { key = "easy", name = "Easy", desc = "Easy" }, - { key = "normal", name = "Normal", desc = "Normal" }, - { key = "hard", name = "Hard", desc = "Hard" }, - { key = "veryhard", name = "Very Hard", desc = "Very Hard" }, - { key = "epic", name = "Epic", desc = "Epic" }, - } - }, - - { - key = "sub_header", - section = "scav_defense_options", - type = "separator", - }, - - { - key = "scav_scavstart", - name = "Spawn Beacons Placement", - desc = "Control where spawners appear", - type = "list", - def = "initialbox", - section = "scav_defense_options", - items = { - { key = "avoid", name = "Spawn Anywhere", desc="Beacons avoid player units" }, - { key = "initialbox", name = "Growing Spawn Box", desc="Beacons spawn in limited area that increases over time" }, - --{ key = "alwaysbox", name = "Always Start Box", desc="Beacons always spawn in scav start box" }, - } - }, - - { - key = "scav_endless", - name = "Endless Mode", - desc = "When you kill the boss, the game doesn't end, but loops around at higher difficulty instead, infinitely.", - type = "bool", - def = false, - section = "scav_defense_options", - }, - - { - key = "sub_header", - section = "scav_defense_options", - type = "separator", - }, - - { - key = "sub_header", - name = "-- Advanced Options, Change at your own risk.", - desc = "", - section = "scav_defense_options", - type = "subheader", - def = true, - }, - - { - key = "scav_bosstimemult", - name = "Boss Preparation Time Multiplier", - desc = "(Range: 0.1 - 2). How quickly Boss Anger goes from 0 to 100%.", - type = "number", - def = 1, - min = 0.1, - max = 2, - step = 0.1, - section = "scav_defense_options", - }, - - { - key = "scav_boss_count", - name = "Scavengers Boss Count", - desc = "(Range: 1 - 20). Number of bosses that will spawn.", - type = "number", - def = 1, - min = 1, - max = 20, - step = 1, - section = "scav_defense_options", - }, - - { - key = "scav_spawncountmult", - name = "Unit Spawn Per Wave Multiplier", - desc = "(Range: 1 - 5). How many times more scavs will spawn per wave.", - type = "number", - def = 1, - min = 1, - max = 5, - step = 1, - section = "scav_defense_options", - }, - - { - key = "scav_spawntimemult", - name = "Waves Amount Multiplier", - desc = "(Range: 1 - 5). How often new waves will spawn. Bigger Number = More Waves", - type = "number", - def = 1, - min = 1, - max = 5, - step = 0.1, - section = "scav_defense_options", - }, - - { - key = "scav_graceperiodmult", - name = "Grace Period Time Multiplier", - desc = "(Range: 0.1 - 3). Time before Scavs become active. ", - type = "number", - def = 1, - min = 0.1, - max = 3, - step = 0.1, - section = "scav_defense_options", - }, - - --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- - --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- - -- Extra Options - --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- - --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- - - { - key = "options_extra", - name = "Extras", - desc = "Extra options", - type = "section", - weight = 2, - }, - - - { - key = "sub_header", - name = "Extra options for shaking up the gameplay or balancing. Not intended for ranked games.", - desc = "", - section = "options_extra", - type = "subheader", - def = true, - }, - - { - key = "sub_header", - section = "options_extra", - type = "separator", - }, - - - { - key = "experimentalextraunits", - name = "Extra Units Pack", - desc = "Pack of units that didn't make it to the main game roster. Balanced for PvP", - type = "bool", - section = "options_extra", - def = false, - }, - - { - key = "scavunitsforplayers", - name = "Scavengers Units Pack", - desc = "Units made for Scavengers, mostly silly and unbalanced for PvP.", - type = "bool", - section = "options_extra", - def = false, - }, - - { - key = "sub_header", - section = "options_extra", - type = "separator", - }, - - - { - key = "map_waterlevel", - name = "Water Level", - desc = "Doesn't work if Map Deformation is disabled! <0 = Decrease water level, >0 = Increase water level", - type = "number", - def = 0, - min = -10000, - max = 10000, - step = 1, - section = "options_extra", - }, - - { - key = "map_waterislava", - name = "Water Is Lava", - desc = "Turns water into Lava", - type = "bool", - def = false, - section = "options_extra", - unlock = {"map_lavatiderhythm", "map_lavatidemode", "map_lavahighlevel", "map_lavahighdwell", "map_lavalowlevel", "map_lavalowdwell","map_tweaklava"}, - lock = {"sub_header_lava3", "sub_header_lava4"}, - bitmask = 1, - }, - - { - key = "map_lavatiderhythm", - name = "Lava Tides", - desc = "Lava level periodicially cycles height when tides are present", - type = "list", - def = "default", - section = "options_extra", - column = 1, - items = { - { key= "default", name= "Default", desc= "Map Settings", - lock = - {"map_lavatidemode", "map_lavahighlevel", "map_lavahighdwell", "map_lavalowlevel", "map_lavalowdwell", "sub_header_lava3", "sub_header_lava4"}, - unlock = - { "sub_header_lava1", "sub_header_lava2"}}, - { key= "enabled", name= "Enable/Override",desc= "Lava tides will use these settings over the map defaults", - unlock = - {"map_lavatidemode", "map_lavahighlevel", "map_lavahighdwell", "map_lavalowlevel", "map_lavalowdwell", "sub_header_lava3", "sub_header_lava4"}, - lock = - { "sub_header_lava1", "sub_header_lava2"}}, - { key= "disabled", name= "Disable",desc= "Lava will not have tides, even on maps that normally have it", - lock = - {"map_lavatidemode", "map_lavahighlevel", "map_lavahighdwell", "map_lavalowlevel", "map_lavalowdwell", "sub_header_lava3", "sub_header_lava4"}, - unlock = - { "sub_header_lava1", "sub_header_lava2"}}, - }, - bitmask = 2, - }, - - { - key = "map_lavatidemode", - name = "Lava Tide Mode", - desc = "Toggle whether lava starts at high or low tide.", - hidden = false, - type = "list", - def = "lavastartlow", - section = "options_extra", - items = { - { key= "lavastartlow", name= "Start Low", desc= "Lava starts at low tide" }, - { key= "lavastarthigh", name= "Start High",desc= "Lava starts at high tide" }, - } - }, - - { - key = "map_lavahighlevel", - name = "Lava High Tide Level", - desc = "Lava level at high tide", - type = "number", - def = 0, - min = 0, - max = 10000, - step = 1, - section = "options_extra", - column = 1, - }, - - { - key = "map_lavahighdwell", - name = "Lava High Tide Time", - desc = "Time in seconds lava waits at high tide", - type = "number", - def = 60, - min = 1, - max = 30000, - step = 1, - section = "options_extra", - column = 2.0, - }, - - { - key = "map_lavalowlevel", - name = "Lava Low Tide Level", - desc = "Lava level at low tide", - type = "number", - def = 0, - min = 0, - max = 10000, - step = 1, - section = "options_extra", - column = 1, - }, - - { - key = "map_lavalowdwell", - name = "Lava Low Tide Time", - desc = "Time in seconds lava waits at low tide", - type = "number", - def = 300, - min = 1, - max = 30000, - step = 1, - section = "options_extra", - column = 2.0, - }, - - { - key = "map_tweaklava", - name = "Advanced Tide Rhythm", - desc = "Table with format {MapHeight (elmo), Rate (elmo/s), Dwell Time (s)}, e.g. {0, 6, 60},{100, 3, 20}", - hidden = true, - hint = "{Lava Height, Rise/Fall Rate, Dwell Time}", - type = "string", - def = "", - section = "options_extra", - }, - - { key = "sub_header_lava1", section = "options_extra", type = "subheader", name = "",}, - { key = "sub_header_lava2", section = "options_extra", type = "subheader", name = "",}, - { key = "sub_header_lava3", section = "options_extra", type = "subheader", name = "",}, - { key = "sub_header_lava4", section = "options_extra", type = "subheader", name = "",}, - - - { - key = "sub_header", - section = "options_extra", - type = "separator", - }, - - { - key = "ruins", - name = "Ruins", - desc = "Remains of the battles once fought", - type = "list", - def = "scav_only", - section = "options_extra", - items = { - { key = "enabled", name = "Enabled", unlock = {"ruins_density", "ruins_only_t1"} }, - { key = "scav_only", name = "Enabled for Scavengers only", unlock = {"ruins_density", "ruins_only_t1"} }, - { key = "disabled", name = "Disabled", lock = {"ruins_density", "ruins_only_t1"} }, - } - }, - - { - key = "ruins_density", - name = "Ruins: Density", - type = "list", - def = "normal", - section = "options_extra", - items = { - { key = "verydense", name = "Very Dense" }, - { key = "dense", name = "Dense" }, - { key = "normal", name = "Normal" }, - { key = "rare", name = "Rare" }, - { key = "veryrare", name = "Very Rare" }, - } - }, - - { - key = "ruins_only_t1", - name = "Ruins: Only Tech 1", - type = "bool", - def = false, - section = "options_extra", - }, - - { - key = "ruins_civilian_disable", - name = "Ruins: Disable Civilian (Not Implemented Yet)", - type = "bool", - def = false, - section = "options", - hidden = true, - }, - - { - key = "sub_header", - section = "options_extra", - type = "separator", - }, - - - { - key = "lootboxes", - name = "Lootboxes", - desc = "Random drops of valuable stuff.", - type = "list", - def = "scav_only", - section = "options_extra", - items = { - { key = "enabled", name = "Enabled", unlock = {"lootboxes_density"} }, - { key = "scav_only", name = "Enabled for Scavengers only", unlock = {"lootboxes_density"} }, - { key = "disabled", name = "Disabled", lock = {"lootboxes_density"} }, - } - }, - - { - key = "lootboxes_density", - name = "Lootboxes: Density", - type = "list", - def = "normal", - section = "options_extra", - items = { - { key = "normal", name = "Normal" }, - { key = "rare", name = "Rare" }, - { key = "veryrare", name = "Very Rare" }, - } - }, - - { - key = "sub_header", - section = "options_extra", - type = "separator", - }, - - { - key = "evocom", - name = "Evolving Commanders", - desc = "Commanders evolve, gaining new weapons and abilities.", - type = "bool", - def = false, - section = "options_extra", - bitmask = 1, - unlock = {"evocomlevelupmethod","evocomlevelcap","evocomxpmultiplier", "evocomleveluptime", "evocomlevelupmultiplier"}, - --lock = {"buffer_fix"}, - }, - - { - key = "evocom_feedback_thread_link", - name = "Feedback thread", - desc = "Discord discussion about Evolving Commanders.", - section = "options_extra", - type = "link", - link = "https://discord.com/channels/549281623154229250/1233887661291343913", - width = 215, - column = 2, - linkheight = 325, - linkwidth = 350, - }, - - { - key = "evocomlevelupmethod", - name = "EvoCom: Leveling Method", - desc = "Dynamic: Commanders evolve to keep up with the highest power player. Timed: Static Evolution Rate", - type = "list", - def = "dynamic", - section = "options_extra", - bitmask = 2, - items = { - { key = "dynamic", name = "Dynamic", lock = {"evocomleveluptime"}, unlock = {"evocomlevelupmultiplier"}}, - { key = "timed", name = "Timed", lock = {"evocomlevelupmultiplier"}, unlock = {"evocomleveluptime"}}, - } - }, - - - { - key = "evocomlevelupmultiplier", - name = "EvoCom: Evolution Mult.", - desc = "(Range 0.1x - 3x Multiplier) Adjusts the thresholds at which Dynamic evolutions occur", - type = "number", - section = "options_extra", - def = 1, - min = 0.1, - max = 3, - step = 0.1, - }, - - { - key = "evocomleveluptime", - name = "EvoCom: Evolution Time ", - desc = "(Range 0.1 - 20 Minutes) Rate at which commanders will evolve if Timed method is selected.", - type = "number", - section = "options_extra", - def = 5, - min = 0.1, - max = 20, - step = 0.1, - }, - - { - key = "evocomlevelcap", - name = "EvoCom: Max Level", - desc = "(Range 2 - 10) Changes the Evolving Commanders maximum level", - type = "number", - section = "options_extra", - def = 10, - min = 2, - max = 10, - step = 1, - }, - - { - key = "evocomxpmultiplier", - name = "EvoCom: Commander XP Multiplier", - desc = "(Range 0.1 - 10) Does not affect leveling! Changes the rate at which Evolving Commanders gain Experience.", - type = "number", - section = "options_extra", - def = 1, - min = 0.1, - max = 10, - step = 0.1, - }, - - { - key = "sub_header", - section = "options_extra", - type = "separator", - }, - - - { - key = "comrespawn", - name = "Commander Respawning", - desc = "Commanders can build one Effigy. The first one is free and given for you at the start. When the commander dies, the Effigy is sacrificed in its place.", - type = "list", - def = "evocom", - section = "options_extra", - items = { - { key = "evocom", name = "Evolving Commanders Only" }, - { key = "all", name = "All Commanders" }, - { key = "disabled", name = "Disabled" }, - } - }, - - { - key = "sub_header", - section = "options_extra", - type = "separator", - }, - - { - key = "quick_start", - name = "Quick Start", - desc = "Each player gets pre-game resources to spend on structures to be instantly spawned at the beginning of the game.", - type = "list", - def = "default", - section = "options_extra", - unlock = {"quick_start_amount"}, - items = { - { key = "default", name = "Default", lock = {"quick_start_amount"}, desc = "Default settings for game modes." }, - { key = "enabled", name = "Enabled", unlock = {"quick_start_amount"}, desc = "Quick Start alone, deducts 400 energy and 800 metal from starting resources." }, - { key = "factory_discount", name = "Enabled: Discounted First Factory", desc = - "Quick Start The commander's first factory is discounted at any time. Deducts 400 energy and 800 metal from starting resources.", unlock = {"quick_start_amount"} }, - { key = "factory_discount_only", name = "First Factory Discount Only", desc = "No base budget, only first factory discount. No deduction from starting resources.", lock = {"quick_start_amount"} }, - { key = "disabled", name = "Disabled", desc = "Disabled quick start for all game modes.", lock = {"quick_start_amount"} }, - } - }, - - { - key = "quick_start_link", - name = "Feedback thread", - desc = "Discord discussion about quick start.", - section = "options_extra", - type = "link", - link = "https://discord.com/channels/549281623154229250/1413936809980858408", - width = 215, - column = 2, - linkheight = 325, - linkwidth = 350, - }, - - { - key = "quick_start_amount", - name = "Quick Start Base Budget", - desc = "How much pre-game resources you have to spend on pre-queuing structures.", - type = "list", - def = "default", - section = "options_extra", - items = { - { key = "default", name = "Default", desc = "Uses the default amount based on game mode" }, - { key = "small", name = "Small", desc = "800 Base Budget" }, - { key = "normal", name = "Normal", desc = "1200 Base Budget" }, - { key = "large", name = "Large", desc = "2400 Base Budget" }, - } - }, - - { - key = "enable_quickstart_overrides", - name = "Enable Quick Start Overrides", - desc = "Allow overriding quick start range and budget (for debugging/modding).", - type = "bool", - def = false, - section = "options_extra", - hidden = true, - }, - - { - key = "override_quick_start_range", - name = "Override Quick Start Range", - desc = "Override the quick start build range when overrides are enabled (values below 200 are clamped to 200).", - type = "number", - def = 600, - min = 200, - max = 2000, - step = 1, - section = "options_extra", - hidden = true, - }, - - { - key = "override_quick_start_budget", - name = "Override Quick Start Budget", - desc = "Override the quick start starting resources when overrides are enabled.", - type = "number", - def = 1200, - min = 100, - max = 1000000, - step = 1, - section = "options_extra", - hidden = true, - }, - - { - key = "sub_header", - section = "options_extra", - type = "separator", - }, - - { - key = "assistdronesenabled", -- TODO, turn this into booleam modoption - name = "Commander Drones", - type = "list", - def = "disabled", - section = "options_extra", - items = { - { key = "enabled", name = "Enabled", unlock = {"assistdronesbuildpowermultiplier", "assistdronescount", "assistdronesair"} }, - { key = "disabled", name = "Disabled", lock = {"assistdronesbuildpowermultiplier", "assistdronescount", "assistdronesair"} }, - } - }, - - { - key = "assistdronesbuildpowermultiplier", - name = "ComDrones: Buildpower Multiplier", - desc = "(Range 0.5 - 5). How much buildpower commander drones should have", - type = "number", - section = "options_extra", - def = 1, - min = 0.5, - max = 5, - step = 0.1, - }, - - { - key = "assistdronescount", - name = "ComDrones: Count", - desc = "How many assist drones per commander should be spawned", - type = "number", - section = "options_extra", - def = 10, - min = 1, - max = 30, - step = 1, - }, - - { - key = "assistdronesair", - name = "ComDrones: Use Air Drones", - desc = "Switch between aircraft drones and amphibious vehicle drones.", - type = "bool", - def = true, - section = "options_extra", - }, - - { - key = "sub_header", - section = "options_extra", - type = "separator", - }, - - - { - key = "commanderbuildersenabled", -- TODO, turn this into boolean modoption - name = "Base Builder Turret", - type = "list", - def = "disabled", - section = "options_extra", - items = { - { key = "enabled", name = "Enabled", unlock = {"commanderbuildersrange", "commanderbuildersbuildpower"} }, - { key = "disabled", name = "Disabled", lock = {"commanderbuildersrange", "commanderbuildersbuildpower"} }, - } - }, - - { - key = "commanderbuildersrange", - name = "Base Builder Turret: Range", - desc = "(Range 500 - 2000).", - type = "number", - section = "options_extra", - def = 1000, - min = 500, - max = 2000, - step = 1, - }, - - { - key = "commanderbuildersbuildpower", - name = "Base Builder Turret: Buildpower", - desc = "(Range 100 - 1000).", - type = "number", - section = "options_extra", - def = 400, - min = 100, - max = 1000, - step = 1, - }, - - { - key = "sub_header", - section = "options_extra", - type = "separator", - }, - - { - key = "zombies", - name = "Scavenger Zombies", - type = "list", - def = "disabled", - section = "options_extra", - hidden = false, - items = { - { key = "disabled", name = "Disabled", desc = "Disabled"}, - { key = "normal", name = "Normal", desc = "Slow revival rate, normal strength."}, - { key = "hard", name = "Hard", desc = "Fast revival rate, stronger Scavenger Zombies." }, - { key = "nightmare", name = "Nightmare", desc = "Extreme revival rate, stronger Scavenger Zombies, 2-5 spawn per corpse." }, - } - }, - - --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- - --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- - -- Experimental Options - --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- - --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- - - { - key = "options_experimental", - name = "Experimental", - desc = "Experimental options", - type = "section", - weight = 1, - }, - - { - key = "sub_header", - name = "Options for testing various new and unfinished features. Not intended for ranked games.", - desc = "", - section = "options_experimental", - type = "subheader", - def = true, - }, - - { - key = "sub_header", - name = "When any of these options are changed, there is no guarantee they will work properly, especially when combined.", - desc = "", - section = "options_experimental", - type = "subheader", - def = true, - }, - - { - key = "sub_header", - section = "options_experimental", - type = "separator", - }, - - { - key = "proposed_unit_reworks", - name = "Placeholder for BLT testing", - desc = "Placeholder for official balance testing mod option", - type = "bool", - hidden = true, - section = "options_experimental", - def = false, - }, - - { - key = "community_balance_patch", - name = "Community Balance Patch 5-6/26", - desc = "Enable community balance patch changes\n(overwrites changes in official seasonal balance test)", - type = "list", - def = "disabled", - section = "options_experimental", - items = { - { key = "disabled", name = "Disabled", desc = "No community balance changes", - lock = {"community_balance_corspy","community_balance_armmav","community_balance_corcan","community_balance_corkarg","community_balance_armkam","community_balance_armblade"} }, - - { key = "enabled", name = "Enabled", desc = "Enable all community balance changes\nSpectre\nGunslinger\nSumo\nKarganeth\nBanshee\nHornet", - lock = {"community_balance_corspy","community_balance_armmav","community_balance_corcan","community_balance_corkarg","community_balance_armkam","community_balance_armblade"} }, - - { key = "custom", name = "Custom", desc = "Customize individual community balance changes", - unlock = {"community_balance_corspy", "community_balance_armmav", "community_balance_corcan", "community_balance_corkarg", "community_balance_armkam", "community_balance_armblade"} }, - } - }, - - { - key = "community_balance_patch_changelog_link", - name = "Changelog/Feedback", - desc = "Community Balance Patch discussion", - section = "options_experimental", - type = "link", - link = "https://discord.com/channels/549281623154229250/1512596823070740550", - width = 235, - column = 2.025, - linkheight = 325, - linkwidth = 350, - }, - - { - key = "community_balance_corspy", - name = "(CBP) Spectre", - desc = "(From February)\nEnergy cost: 8800 (from 12500)\nMetal cost: 135 (from 165)", - type = "bool", - def = false, - section = "options_experimental", - }, - - { - key = "community_balance_armmav", - name = "(CBP) Gunslinger", - desc = "(From April)\nMetal cost: 520 (from 650)\nEnergy cost: 6500 (from 11000)", - type = "bool", - def = false, - section = "options_experimental", - }, - - { - key = "community_balance_corcan", - name = "(CBP) Sumo", - desc = "(From April)\nMain laser range: 300 (from 275)\nMain laser beam time: 0.24 (from 0.16)", - type = "bool", - def = false, - section = "options_experimental", - }, - - { - key = "community_balance_corkarg", - name = "(CBP) Karganeth", - desc = "(New)\nSight distance: 515 (from 455)\nMax acceleration: 0.18 (from 0.1104)\nTurn rate: 515 (from 400)\nTurn-in-place speed limit: 1.25 (from 0.99)\nStrafe to attack: true (from false)\nMissile trajectory height: 0.25 (from none)\nMetal cost: 2650 (from 2500)\nBuild time: 100000 (from 94000)", - type = "bool", - def = false, - section = "options_experimental", - }, - - { - key = "community_balance_armkam", - name = "(CBP) Banshee", - desc = "(New)\nMax acceleration: 0.35 (from 0.15)\nWeapon range: 400 (from 350)\nWeapon reload: 3.0 (from 0.7)\nWeapon damage: 141 single shot (from 9 x 3 burst)\nArea of effect: 32 (from 40)\nEdge effectiveness: 0.40 (from 0.5)\nProjectile velocity: 1090 (from 1000)\nWeapon accuracy: 0 (from 13), spray angle removed (from 1024)\nCylindrical targeting: 0 (from 1)\nWeapon timer: 0 (from 0.1)\nWeapon tolerance: 2000 (from 5000)\nImpulse factor: 2.14 (from 0.123)\nWeapon visual: impulse-trail / genericshellexplosion-small-bomb (from plasmahit-small)\nWeapon sound: mavgun4 (from flashemg)\nTurret: true (from false)\nFiring arc: 45° forward, hidden attack range arc (from unrestricted/fixed)", - type = "bool", - def = false, - section = "options_experimental", - }, - - { - key = "community_balance_armblade", - name = "(CBP) Hornet", - desc = "(New)\nMax acceleration: 0.28 (from 0.6)\nMax deceleration: 0.55 (from 0.35)\nHealth: 3350 (from 3000)\nSpeed: 125 (from 204)\nTurn angle limit: 120 (from 360)\nTurn rate: 420 (from 720)\nSight distance: 720 (from 624)\nWeapon range: 1100 (from 420)\nWeapon reload: 4.0 (from 2.26667)\nWeapon damage: 425 x 2 burst (from 190 x 2 burst)\nCommander damage: 200 x 2 burst\nBurst rate: 0.15 (from 0.23333)\nArea of effect: 64 (from 32)\nEdge effectiveness: 0.40 (from 0.15)\nProjectile type: Cannon (from MissileLauncher)\nProjectile velocity: 1090 (from 1000)\nImpulse factor: 1.5 (from 0.123)\nWeapon visual: impulse-trail / genericshellexplosion-medium-bomb (from missiletrailsmall-simple / genericshellexplosion-medium)\nWeapon sound: mavgun5 / xplomed2 (from SabotFire / SabotHit)\nTurret: true (from false)\nFiring arc: 45° forward (from unrestricted)", - type = "bool", - def = false, - section = "options_experimental", - }, - - { - key = "experimentallegionfaction", - name = "Legion Faction", - desc = "3rd experimental faction", - type = "bool", - section = "options_experimental", - def = false, - }, - - { - key = "legionsimplifiedmexes", - name = "Legion Simplified Mexes", - desc = "Changes the legion T1 mex to act the same as the other T1 mexes. Legion light T1 units are given a higher metal cost but lower E cost, and heavy T1 units are given a higher E cost and slightly lower metal cost.", - type = "bool", - section = "options_experimental", - def = false, - }, - - { - key = "experimentallegionfaction_link", - name = "Development Discussion", - desc = "Discord discussion about Legion faction.", - section = "options_experimental", - type = "link", - link = "https://discord.com/channels/549281623154229250/1063217502898884701/1441480747629412675", - width = 275, - column = 1.65, - linkheight = 325, - linkwidth = 350, - }, - - { - key = "easytax", - name = "Easy Tax v2", - desc = "Anti co-op sharing tax mod. Overwrites other tax settings. Don't combine with other sharing restriction mods, everything you need is included with easy tax.", - type = "bool", - section = "options_experimental", - def = false, - }, - - { - key = "easytax_link", - name = "Changelog", - desc = "Easy Tax v2 description.", - section = "options_experimental", - type = "link", - link = "https://gist.github.com/RebelNode/43b986f29b9cfacbe95cf634cac25c49", - width = 215, - column = 1.65, - linkheight = 325, - linkwidth = 350, - }, - - -- Hidden Tests - - { - key = "techsplit", - name = "Tech Split", - desc = "Adds a new tier between T1 and T2 for bots and vehicles", - type = "bool", - hidden = true, - section = "options_experimental", - def = false, - }, - - { - key = "techsplit_balance", - name = "Tech Split Balance Test", - desc = "Adjusts the balance of units in the proposed tech split.", - type = "bool", - hidden = true, - section = "options_experimental", - def = false, - }, - - { - key = "experimental_defend_firestate", - name = "Defend Combat Stance", - desc = "Replaces Return Fire with the new Defend combat stance.\nDefending units will shoot threats to themselves when they become threats on a 1v1 basis.", - type = "bool", - section = "options_experimental", - def = false, - }, - - { - key = "experimental_defend_firestate_link", - name = "Feedback thread", - desc = "Discord discussion about the Defend Combat Stance rework.", - section = "options_experimental", - type = "link", - link = "https://discord.com/channels/549281623154229250/1520166826435280998", - width = 215, - column = 1.65, - linkheight = 325, - linkwidth = 350, - }, - - { - key = "air_rework", - name = "Air Rework", - desc = "Prototype version with more maneuverable, slower air units and more differentiation between them.", - hidden = true, - type = "bool", - section = "options_experimental", - def = false, - }, - - { - key = "skyshift", - name = "Skyshift: Air Rework", - desc = "A complete overhaul of air units and mechanics", - type = "bool", - def = false, - section = "options_experimental", - hidden = true, - }, - - { - key = "emprework", - name = "EMP Rework", - desc = "EMP is changed to slow units movement and firerate, before eventually stunning.", - type = "bool", - hidden = true, - section = "options_experimental", - - def = false, - }, - - { - key = "junorework", - name = "Juno Rework", - desc = "Juno stuns certain units (such as radars and jammers) rather than magically deleting them", - type = "bool", - hidden = true, - section = "options_experimental", - def = false, - }, - - { - key = "releasecandidates", - name = "Release Candidate Units", - desc = "Adds additional units to the game which are being considered for mainline integration and are balanced, or in end tuning stages. Currently adds Printer, Siegebreaker, Phantom (Core T2 veh), Shockwave (Arm T2 EMP Mex), and Drone Carriers for armada and cortex", - type = "bool", - hidden = true, - section = "options_experimental", - def = false, - }, - - { - key = "naval_balance_tweaks", - name = "Proposed Naval Balance Tweaks", - desc = "Modoption used to test specific balance adjustments dedicated towards naval units.", - type = "bool", - --hidden = true, - section = "options_experimental", - def = false, - }, - - { - key = "naval_balance_tweaks_link", - name = "Feedback thread", - desc = "Discord discussion about naval balance tweaks.", - section = "options_experimental", - type = "link", - link = "https://discord.com/channels/549281623154229250/1428031834045939833", - width = 215, - column = 1.65, - linkheight = 325, - linkwidth = 350, - }, - - { - key = "forge_volcano", - name = "Forge Volcano Event", - desc = "Enable the cinematic volcano eruption event on Forge v2.3.", - type = "bool", - hidden = true, - section = "options_experimental", - def = false, - }, - - { - key = "factory_costs", - name = "Factory Costs Test Patch", - desc = "Cheaper and more efficient factories, more expensive nanos, and slower to build higher-tech units. Experimental, not expected to be balanced by itself - a test to try how the game plays if each player is more able to afford their own T2 factory, while making assisting them less efficient.", - type = "bool", - hidden = true, - section = "options_experimental", - def = false, - }, - - --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- - --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- - -- Unused Options - --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- - --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- - - { - key = "modes", - name = "GameModes", - desc = "Game Modes", - hidden = true, - type = "section", - }, - - { - key = "shareddynamicalliancevictory", - name = "Dynamic Ally Victory", - desc = "Ingame alliance should count for game over condition.", - hidden = true, - type = "bool", - section = "options", - def = false, - }, - - { - key = "ai_incomemultiplier", - name = "AI Income Multiplier", - desc = "Multiplies AI resource income", - hidden = true, - type = "number", - section = "options", - def = 1, - min = 1, - max = 10, - step = 0.1, - }, - - { - key = "defaultdecals", - name = "Default Decals", - desc = "Use the default explosion decals instead of Decals GL4", - section = "options_experimental", - type = "bool", - def = true, - hidden = true, - }, - - --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- - --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- - -- DEV mode only mod option otherwise hidden by chobby - --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- - --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- - - { - key = "dev", - name = "_DEV", - desc = "tab that should be hidden by chobby", - hidden = true, - type = "section", - }, - { - key = "teamcolors_icon_dev_mode", - name = "Icon Dev Mode ", - desc = "(Don't use in normal games) Forces teamcolors to be an specific one, for all teams", - type = "list", - section = "dev", - def = "disabled", - items = { - { key = "disabled", name = "Disabled", desc = "description" }, - { key = "armblue", name = "Armada Blue", desc = "description" }, - { key = "corred", name = "Cortex Red", desc = "description" }, - { key = "scavpurp", name = "Scavenger Purple", desc = "description" }, - { key = "raptororange", name = "Raptor Orange", desc = "description" }, - { key = "gaiagray", name = "Gaia Gray", desc = "description" }, - { key = "leggren", name = "Legion Green", desc = "description" }, - } - }, - { - key = "debugcommands", - name = "Debug Commands", - desc = "A pipe separated list of commands to execute at [gameframe]:luarules benchmark|100:forcequit...", -- example: debugcommands=150:cheat 1|200:luarules benchmark|600:quitforce; - section = "dev", - type = "string", - def = "", - }, - { - key = "animationcleanup", - name = "Animation Cleanup", - desc = "Use animations from the BOSCleanup branch", -- example: debugcommands=150:cheat 1|200:luarules benchmark|600:quitforce; - section = "dev", - type = "bool", - def = false, - }, - { - key = "pushresistant", - name = "Pushresistance", - desc = "Enable to do desync test by the use of pushresistance", - section = "dev", - type = "bool", - def = false, - }, - { - key = "dummyboolfeelfreetotouch", - name = "dummy to hide some modoptions", - desc = "This is a dummy to hide some modoptions to not bloat the changed options panel with unneeded information", - section = "dev", - type = "bool", - -- This doesn't have a default on purpse, do not add one - unlock = {"dummyboolfeelfreetotouch", "factionlimiter", "date_year", "date_month", "date_day", "date_hour"}, - }, - { key = "date_year", name = "Year", desc = "Spads (Multiplayer) / Skirmish Interface (Singleplayer) fed, auto-overwriten", section = "dev", type = "number", def = 0, min = 0, max = 3000, step = 1, }, - { key = "date_month", name = "Month", desc = "Spads (Multiplayer) / Skirmish Interface (Singleplayer) fed, auto-overwriten", section = "dev", type = "number", def = 0, min = 0, max = 12, step = 1, }, - { key = "date_day", name = "Day", desc = "Spads (Multiplayer) / Skirmish Interface (Singleplayer) fed, auto-overwriten", section = "dev", type = "number", def = 0, min = 0, max = 31, step = 1, }, - { key = "date_hour", name = "Hour", desc = "Spads (Multiplayer) / Skirmish Interface (Singleplayer) fed, auto-overwriten", section = "dev", type = "number", def = 0, min = 0, max = 24, step = 1, }, - { - key = "factionlimiter", - name = "Faction Limiter:".."\255\255\191\76".." ON\n".."\255\125\125\125".."BITMASK", - desc = [[BITMASK to be used via custom ui, only visible when boss -Set to [0] To disable. -Otherwise: 0th, 1st and 2nd bit are armada, cortex and legion respectively. -Offset by 3 for each consecutive team. -If a team's bitmask is 0, All are Enabled. -Example: Armada VS Cortex VS Legion: 273 or 100 010 001 or 256 + 16 + 1]], - section = "dev", - type = "number", - def = 0, - min = 0, - max = 16777215,-- math hard, 24 bit limitish? - step = 1, - }, - - --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- - --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- - -- Map Metadata options - --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- - --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- - -- - -- The modoptions below are intended to be set automatically by lobby/spads based on the selected - -- map name. They are used for a dynamic map configuration where the configruation values are not - -- tied to either game version or reside inside of the map file, allowing for independent distribution - -- from the maps metadata source of truth: https://github.com/beyond-all-reason/maps-metadata - { - key = "mapmetadata", - name = "MapMetadata", - desc = "mapmetadata tab that should be hidden by chobby, which would have ideally been achieved by just not listing it and the following options here in the first place, but then SPADS refuses to set the modoption", - hidden = true, - type = "section", - }, - { - key = "sub_header", - name = "Hidden map metadata options that are supposed to be set automatically by lobby/spads based on the map name.", - desc = "", - section = "mapmetadata", - type = "subheader", - hidden = true, - def = true, - }, - { - key = "mapmetadata_startpos", - name = "Map Metadata: StartPos", - desc = "StartPos configuration. Format is: base64url(zlib(json))", - hidden = true, - section = "mapmetadata", - type = "string", - def = "", - }, - { - key = "mapmetadata_startboxes_set", - name = "Map Metadata: Startboxes Set", - desc = "Per-team-count startbox arrangements (rect or polygon). Format is: base64url(zlib(json))", - hidden = true, - section = "mapmetadata", - type = "string", - def = "", - }, - { - key = "mapmetadata_startbox_override", - name = "Map Metadata: Startbox Override", - desc = "Custom startbox arrangement that overrides the set when its team count matches. Format is: base64url(zlib(json))", - hidden = true, - section = "mapmetadata", - type = "string", - def = "", - }, - --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- - --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- - -- Cheats - --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- - --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- - - { - key = "options_cheats", - name = "Cheats", - desc = "Options that alter the game balance in unintended way, Use at your own risk.", - type = "section", - weight = -1, - }, - - { - key = "sub_header", - name = "Warning: changing these options will alter the intended game experience and may have bad results. Proceed at your own risk!", - desc = "", - section = "options_cheats", - type = "subheader", - def = true, - }, - - { - key = "sub_header", - name = "When any of these options are changed, there is no guarantee they will work properly, especially when combined.", - desc = "", - section = "options_cheats", - type = "subheader", - def = true, - }, - - { - key = "sub_header", - section = "options_cheats", - type = "separator", - }, - - { - key = "sub_header", - name = "-- AI Cheats", - desc = "", - section = "options_cheats", - type = "subheader", - def = true, - }, - - { - key = "dynamiccheats", - name = "Dynamic Cheats", - desc = "Cheats marked as [Dynamic] react to the game state and are suspended when the opposition is losing", - type = "bool", - def = true, - section = "options_cheats", - }, - - { - key = "nowasting", - name = "No Resource Wasting", - desc = "[Dynamic] Increases Buildpower for the affected team's builders and factories to prevent resource", - type = "list", - def = "default", - section = "options_cheats", - items = { - { key= "default", name= "Default", desc="Disabled, unless other features use it"}, - { key= "disabled", name= "Disabled", desc="Disabled"}, - { key= "ai", name= "AI Only", desc="All AI except Scavengers and Raptors"}, - { key= "all", name= "All", desc="AI and Player Teams both excluding Scavengers and Raptors" }, - } - }, - - { - key = "allow_enemy_ai_spawn_placement", - name = "Allow Hostile AI Spawn Placement", - desc = "When enabled, allows enemy allyteams to view and place enemy AI start positions during the pregame", - type = "bool", - def = false, - section = "options_cheats", - }, - - { - key = "sub_header", - section = "options_cheats", - type = "separator", - }, - - { - key = "sub_header", - name = "-- Starting Resources", - desc = "", - section = "options_cheats", - type = "subheader", - def = true, - }, - - { - key = "startmetal", - name = "Starting Metal", - desc = "(Range 0 - 10 000). Determines amount of metal and metal storage that each player will start with", - type = "number", - section = "options_cheats", - def = 1000, - min = 0, - max = 10000, - step = 1, - }, - - { - key = "startmetalstorage", - name = "Starting Metal Storage", - desc = "(Range 1000 - 20 000). Only works if it's higher than Starting metal. Determines amount of metal and metal storage that each player will start with", - type = "number", - section = "options_cheats", - def = 1000, - min = 1000, - max = 20000, - step = 1, - }, - - { - key = "startenergy", - name = "Starting Energy", - desc = "(Range 0 - 10 000). Determines amount of energy and energy storage that each player will start with", - type = "number", - section = "options_cheats", - def = 1000, - min = 0, - max = 10000, - step = 1, - }, - - { - key = "startenergystorage", - name = "Starting Energy Storage", - desc = "(Range 1000 - 20 000). Only works if it's higher than Starting energy. Determines amount of energy and energy storage that each player will start with", - type = "number", - section = "options_cheats", - def = 1000, - min = 1000, - max = 20000, - step = 1, - }, - - { - key = "bonusstartresourcemultiplier", - name = "Apply Bonus to Starting Resources", - desc = "If enabled, multiplies each players starting resources with their bonus.", - type = "bool", - section = "options_cheats", - def = false, - }, - - { - key = "sub_header", - section = "options_cheats", - type = "separator", - }, - - { - key = "sub_header", - name = "-- Resource Multipliers", - desc = "", - section = "options_cheats", - type = "subheader", - def = true, - }, - - { - key = "multiplier_resourceincome", - name = "Overall Resource Income", - desc = "(Range 0.1 - 10). Stacks up with the three options below.", - type = "number", - section = "options_cheats", - def = 1, - min = 0.1, - max = 10, - step = 0.1, - }, - - { - key = "multiplier_metalextraction", - name = "Metal Extraction ", - desc = "(Range 0.1 - 10).", - type = "number", - section = "options_cheats", - def = 1, - min = 0.1, - max = 10, - step = 0.1, - }, - - { - key = "multiplier_energyconversion", - name = "Energy Conversion Efficiency", - desc = "(Range 0.1 - 2). lower means you get less metal per energy converted", - type = "number", - section = "options_cheats", - def = 1, - min = 0.1, - max = 2, - step = 0.1, - }, - - { - key = "multiplier_energyproduction", - name = "Energy Production", - desc = "(Range 0.1 - 10).", - type = "number", - section = "options_cheats", - def = 1, - min = 0.1, - max = 10, - step = 0.1, - }, - - { - key = "sub_header", - section = "options_cheats", - type = "separator", - }, - - { - key = "cheatsdescription7", - name = "-- Unit Parameter Multipliers", - desc = "", - section = "options_cheats", - type = "subheader", - def = true, - }, - - { - key = "multiplier_maxvelocity", - name = "Unit Max Velocity", - desc = "(Range 0.1 - 10).", - type = "number", - section = "options_cheats", - def = 1, - min = 0.1, - max = 10, - step = 0.1, - }, - - { - key = "multiplier_turnrate", - name = "Unit Turn Rate", - desc = "(Range 0.1 - 10).", - type = "number", - section = "options_cheats", - def = 1, - min = 0.1, - max = 10, - step = 0.1, - }, - - { - key = "multiplier_builddistance", - name = "Build Range", - desc = "(Range 0.5 - 10).", - type = "number", - section = "options_cheats", - def = 1, - min = 0.5, - max = 10, - step = 0.1, - }, - - { - key = "multiplier_buildpower", - name = "Build Power", - desc = "(Range 0.1 - 10).", - type = "number", - section = "options_cheats", - def = 1, - min = 0.1, - max = 10, - step = 0.1, - }, - - { - key = "multiplier_losrange", - name = "Vision Range", - desc = "(Range 0.5 - 10).", - type = "number", - section = "options_cheats", - def = 1, - min = 0.5, - max = 10, - step = 0.1, - }, - - { - key = "multiplier_radarrange", - name = "Radar And Sonar Range", - desc = "(Range 0.5 - 10).", - type = "number", - section = "options_cheats", - def = 1, - min = 0.5, - max = 10, - step = 0.1, - }, - - { - key = "multiplier_weaponrange", - name = "Weapon Range", - desc = "(Range 0.5 - 10).", - type = "number", - section = "options_cheats", - def = 1, - min = 0.5, - max = 10, - step = 0.1, - }, - - { - key = "multiplier_weapondamage", - name = "Weapon Damage", - desc = "(Range 0.1 - 10). Also affects unit death explosions.", - type = "number", - section = "options_cheats", - def = 1, - min = 0.1, - max = 10, - step = 0.1, - }, - - { - key = "multiplier_shieldpower", - name = "Shield Power", - desc = "(Range 0.1 - 10)", - type = "number", - section = "options_cheats", - def = 1, - min = 0.1, - max = 10, - step = 0.1, - }, - - { - key = "sub_header", - section = "options_cheats", - type = "separator", - }, - - { - key = "cheatsdescription7", - name = "-- Other", - desc = "", - section = "options_cheats", - type = "subheader", - def = true, - }, - - { - key = "experimentalshields", - name = "Shield Type Override", - desc = "Shield Type Override", - type = "list", - section = "options_cheats", - def = "unchanged", - hidden = true, - items = { - { key = "unchanged", name = "Unchanged", desc = "Unchanged" }, - { key = "absorbeverything", name = "Absorb Everything", desc = "Shields absorb everything" }, - { key = "bounceplasma", name = "Deflect Plasma", desc = "Shields deflect plasma only" }, - { key = "bounceeverything", name = "Deflect Everything", desc = "Shields deflect everything" }, - } - }, - - { - key = "tweakunits", - name = "Tweak Units", - desc = "For advanced users!!! A base64 encoded lua table of unit parameters to change.", - hint = "Input must be base64", - section = "options_cheats", - type = "string", - def = "", - }, - - { - key = "tweakdefs", - name = "Tweak Defs", - desc = "For advanced users!!! A base64 encoded snippet of code that modifies game definitions.", - hint = "Input must be base64", - section = "options_cheats", - type = "string", - def = "", - }, - - { - key = "forceallunits", - name = "Force Load All Units (Dev/Modding)", - desc = "Load all UnitDefs even if ais or options for them aren't enabled", - section = "options_cheats", - type = "bool", - def = false, - }, - - { - key = "holiday_events", - name = "Enable Holiday Events", - desc = "", - section = "options_cheats", - type = "bool", - def = true, - hidden = true, - }, - -} - --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- - --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- - -- End Options - --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- - --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- - -for i = 1, 9 do - options[#options + 1] = { - key = "tweakunits" .. i, - name = "Tweak Units " .. i, - desc = "A base64 encoded lua table of unit parameters to change.", - section = "options_extra", - type = "string", - def = "", - hidden = true, - } -end - -for i = 1, 9 do - options[#options + 1] = { - key = "tweakdefs" .. i, - name = "Tweak Defs " .. i, - desc = "A base64 encoded snippet of code that modifies game definitions.", - section = "options_extra", - type = "string", - def = "", - hidden = true, - } -end - -return options - -end)() -local VFS={Include=function(path)assert(path=="modoptions.lua");return options end} -if Spring.GetModOptions then - local modOptions = Spring.GetModOptions() - local modOptionsFile = VFS.Include('modoptions.lua') - - for _, modOption in ipairs(modOptionsFile) do - local key = modOption.key - - if modOption.type ~= "section" then - if modOptions[key] == nil then - modOptions[key] = modOption.def - end - - if (modOption.type == 'bool') and (type(modOptions[key]) ~= 'boolean') then - local value = tonumber(modOptions[key]) - modOptions[key] = value == 1 and true or false - end - - if modOption.type == 'number' then - modOptions[key] = tonumber(modOptions[key]) - end - end - end - - -- Prevent widgets from messing with each other's modoptions table. - -- The native engine call does this by returning a new table each time but that is wasteful - local readOnlyModOptions = {} - setmetatable(readOnlyModOptions, { - __index = modOptions, - __newindex = function(t, k, v) - error("attempt to update a read-only Spring.GetModOptions table", 2) - end - }) - - Spring.GetModOptions = function () - return readOnlyModOptions - end - - -- Returns a copy of the modOptions table. Slower, but allows iterating over - -- the returned table using pairs/ipairs. - Spring.GetModOptionsCopy = function () - return table.copy(modOptions) - end -end - -if Spring.Echo then - local echo = Spring.Echo - local printOptions = { pretty = true } - - local function multiEcho(...) - local n = select('#', ...) - local firstTableIndex - local tableCount = 0 - - for index = 1, n do - if type(select(index, ...)) == 'table' then - tableCount = tableCount + 1 - if not firstTableIndex then - firstTableIndex = index - end - end - end - - if tableCount == 0 then - echo(...) - return - end - - -- When Spring.Echo is called with a single table parameter, engine will echo "TABLE: {value}", - -- where {value} is whatever value happens to be the first value in the table - if tableCount == 1 and n == 1 then - echo("") - else - echo(...) - end - - local args = table.pack(...) - for index = firstTableIndex, n do - if type(args[index]) == 'table' then - echo(table.toString(args[index], printOptions)) - end - end - end - - Spring.Echo = multiEcho -end - -Spring.Debug=(function() -local function paramsEcho(...) - local called_from = "Called from: " .. tostring(debug.getinfo(2).name) .. " args:" - Spring.Echo(called_from) - local args = { ... } - Spring.Echo( table.toString(args) ) - return ... -end - -local function traceEcho(...) - local myargs = {...} - local parts = {} - local n = 0 - for i = 1, #myargs do - n = n + 1; parts[n] = tostring(myargs[i]) - n = n + 1; parts[n] = "\t" - end - local infostr = n > 0 and (table.concat(parts) .. " ") or "" - local functionstr = "Trace:[" - for i = 2, 10 do - local info = debug.getinfo(i) - if info then - local funcName = info.name - if funcName then - functionstr = functionstr .. tostring(funcName) .. " <- " - else break end - else break end - end - functionstr = functionstr .. "]" - local arguments = "" - local info2 = debug and debug.getinfo(2) - local funcName1 = (info2 and info2.name) or "??" - if funcName1 ~= "??" then - for i = 1, 10 do - local name, value = debug.getlocal(2, i) - if not name then break end - local sep = ((arguments == "") and "") or "; " - arguments = arguments .. sep .. ((name and tostring(name)) or "name?") .. "=" .. tostring(value) - end - end - Spring.Echo(infostr .. functionstr .. " Args:(" .. arguments .. ")") -end - -local function traceFullEcho(maxdepth, maxwidth, maxtableelements, ...) - -- Call it at any point, and it will give you the name of each function on the stack (up to maxdepth), - -- all arguments and first #maxwidth local variables of that function - -- if any of the values of the locals are tables, then it will try to shallow print + count them up to maxtablelements numbers. - -- It will also just print any args after the first 3. (the ... part) - -- It will also try to print the source file+line of each function - if (debug) then - else - Spring.Echo("traceFullEcho needs debug to work, this seems to be missing or overwritten", debug) - return - end - local tracedebug = false -- to debug itself - local functionsource = true - maxdepth = maxdepth or 16 - maxwidth = maxwidth or 10 - maxtableelements = maxtableelements or 6 -- max amount of elements to expand from table type values - - local function dbgt(t, maxtableelements) - local count = 0 - local res = '' - for k,v in pairs(t) do - count = count + 1 - if count < maxtableelements then - if tracedebug then Spring.Echo(count, k) end - if type(k) == "number" and type(v) == "function" then -- try to get function lists? - local vinfo = debug.getinfo(v) - if tracedebug then Spring.Echo(k,v, vinfo, vinfo.name) end --debug.getinfo(v).short_src)? - res = res .. tostring(k) .. ':' .. ((vinfo and vinfo.name) or "") ..', ' - else - res = res .. tostring(k) .. ':' .. tostring(v) ..', ' - end - end - end - res = '{'..res .. '}[#'..count..']' - return res - end - - local myargs = {...} - local infostr = "TraceFullEcho:[" - for i,v in ipairs(myargs) do - infostr = infostr .. tostring(v) .. "\t" - end - infostr = infostr .. "]\n" - local functionstr = "" -- "Trace:[" - for i = 2, maxdepth do - local info = debug.getinfo(i) - if info then - local funcName = info.name - if funcName then - functionstr = functionstr .. tostring(i-1) .. ": " .. tostring(funcName) .. " " - local arguments = "" - if funcName ~= "??" then - if functionsource and info.source then - local source = info.source - if string.len(source) > 128 then source = "sourcetoolong" end - functionstr = functionstr .. " @" .. source - end - if functionsource and info.linedefined then - functionstr = functionstr .. ":" .. tostring(info.linedefined) - end - for j = 1, maxwidth do - local name, value = debug.getlocal(i, j) - if not name then break end - if tracedebug then Spring.Echo(i,j, funcName,name) end - local sep = ((arguments == "") and "") or "; " - if tostring(name) == 'self' then - arguments = arguments .. sep .. ((name and tostring(name)) or "name?") .. "=" .. tostring("??") - else - local newvalue - if maxtableelements > 0 and type({}) == type(value) then newvalue = dbgt(value, maxtableelements) else newvalue = value end - arguments = arguments .. sep .. ((name and tostring(name)) or "name?") .. "=" .. tostring(newvalue) - end - end - end - functionstr = functionstr .. " Locals:(" .. arguments .. ")" .. "\n" - else - functionstr = functionstr .. tostring(i-1) .. ": ??\n" - end - else break end - end - Spring.Echo(infostr .. functionstr) -end - -return { - ParamsEcho = paramsEcho, - TraceEcho = traceEcho, - TraceFullEcho = traceFullEcho, -} -end)() --- Graphics-only compatibility storage for original policy. No drawing, engine --- buffer upload, commands, VFS/IO, configuration or selection mutation. -local function noop()end -WG={};LOG={DEPRECATED=0} -GL={ARRAY_BUFFER=34962,UNSIGNED_INT=5125,POINTS=0,TRIANGLES=4,TRIANGLE_STRIP=5} -local storage={Define=noop,Upload=noop,Delete=noop,InstanceDataFromUnitIDs=noop,InstanceDataFromFeatureIDs=noop,GetID=function()return 1 end} -local vao={AttachVertexBuffer=noop,AttachInstanceBuffer=noop,AttachIndexBuffer=noop,DrawArrays=noop,DrawElements=noop,Delete=noop} -local shader={Activate=noop,Deactivate=noop,SetUniform=noop} -local unitUniforms,featureUniforms={},{} -local function uniforms(target,id,values,offset) - assert(type(id)=='number'and id>=0 and id%1==0 and type(values)=='table','Invalid original healthbar uniform write') - offset=math.max(offset or 0,0);local count=math.min(#values,16-offset) - if count<1 then return 0 end - local row=target[id];if not row then row={};for i=1,16 do row[i]=0 end;target[id]=row end - for i=1,count do row[offset+i]=values[i]end - return count -end -gl={GetVBO=function()return setmetatable({},{__index=storage})end,GetVAO=function()return setmetatable({},{__index=vao})end, - CreateShader=noop,LuaShader={isGeometryShaderSupported=true,CheckShaderUpdates=function()return shader end}, - SetUnitBufferUniforms=function(id,values,offset)return uniforms(unitUniforms,id,values,offset)end, - SetFeatureBufferUniforms=function(id,values,offset)return uniforms(featureUniforms,id,values,offset)end} --- This handle supplies policy to a graphical browser. Headless GL calls are --- replaced by private storage, so the original forwarder can retain its writes. -Spring.GetConfigInt=function(name,default)if name=='Headless'then return 0 end;return default or 0 end -Spring.GetViewGeometry=function()return 1280,720 end -local removed=false -widgetHandler={RegisterGlobal=noop,DeregisterGlobal=noop,AddAction=noop,RemoveAction=noop,RemoveWidget=function()removed=true end,AddSpadsMessage=noop} -local listeners,actions={},{} -local widgetEventUnit,widgetEventLos -Script.LuaUI=setmetatable({},{__call=function(_,name)return listeners[name]~=nil end,__index=function(_,name)return function(...)return assert(listeners[name],'Unbound original healthbar LuaUI callback '..name)(...)end end}) -gadgetHandler={IsSyncedCode=function()return false end,AddSyncAction=function(_,name,fn)assert(not actions[name]);actions[name]=fn end,RemoveSyncAction=function(_,name)actions[name]=nil end} - --------------------------------------------------------------------------------- --------------------------------------------------------------------------------- --- --- file: setupdefs.lua --- brief: setup some custom UnitDefs parameters, --- and UnitDefNames, FeatureDefNames, WeaponDefNames --- author: Dave Rodgers --- --- Copyright (C) 2007. --- Licensed under the terms of the GNU GPL, v2 or later. --- --------------------------------------------------------------------------------- --------------------------------------------------------------------------------- - -for _,ud in pairs(UnitDefs) do - -- set the cost value (same as shown in the tooltip) - ud.cost = ud.metalCost + (ud.energyCost / 60.0) - - -- add the custom weapons based parameters - ud.hasShield = false - ud.canParalyze = false - ud.canStockpile = false - ud.canAttackWater = false - ud.wDefs = {} - for i, wt in ipairs(ud.weapons) do - local wd = WeaponDefs[wt.weaponDef] - ud.wDefs[i] = wd - if (wd) then - if (wd.isShield) then ud.hasShield = true end - if (wd.paralyzer) then ud.canParalyze = true end - if (wd.stockpile) then ud.canStockpile = true end - if (wd.waterWeapon) then ud.canAttackWater = true end - end - end -end - --------------------------------------------------------------------------------- --------------------------------------------------------------------------------- - --- setup the UnitDefNames{} table -do - local tbl = {} - for _,def in pairs(UnitDefs) do - tbl[def.name] = def - end - UnitDefNames = tbl -end - --- setup the FeatureDefNames{} table -do - local tbl = {} - for _,def in pairs(FeatureDefs) do - tbl[def.name] = def - end - FeatureDefNames = tbl -end - --- setup the WeaponDefNames{} table -do - local tbl = {} - for _,def in pairs(WeaponDefs) do - tbl[def.name] = def - end - WeaponDefNames = tbl -end - --------------------------------------------------------------------------------- --------------------------------------------------------------------------------- - - -gl.InstanceVBOTable=(function() -local GL_BUFFER = 0x82E0 -local gldebugannotations = (Spring.GetConfigInt("gldebugannotations") == 1) ---Spring.Echo("gldebugannotations", gldebugannotations) -local function makeInstanceVBOTable(layout, maxElements, myName, unitIDattribID) - -- layout: this must be an array of tables with at least the following specified: {{id = 1, name = 'optional', size = 4}} - -- maxElements: will be dynamic anyway, but defaults to 64 - -- myName: optional name, useful for debugging - -- unitIDattribID: the attribute ID in the layout of the uvec4 of unitID bindings (e.g. 4 for {id = 4, name = 'instData', type = GL.UNSIGNED_INT, size= 4} ) - -- returns: nil | instanceTable - if maxElements == nil then maxElements = 64 end -- default size - if myName == nil then myName = "InstanceVBOTable" end - local newInstanceVBO = gl.GetVBO(GL.ARRAY_BUFFER,true) - if newInstanceVBO == nil then Spring.Echo("makeInstanceVBOTable, cannot get VBO for", myName); return nil end - newInstanceVBO:Define( - maxElements, - layout - ) - - - - local instanceStep = 0 - for i,attribute in pairs(layout) do - instanceStep = instanceStep + attribute.size - end - local instanceData = {} - for i = 1, instanceStep * maxElements do - instanceData[i] = 0 - end - local instanceTable = { - instanceVBO = newInstanceVBO, - instanceData = instanceData, - instanceStep = instanceStep, - usedElements = 0, - maxElements = maxElements, - myName = myName, - instanceIDtoIndex = {}, -- this maps each instance ID to where it is in the buffer, 1 based - indextoInstanceID = {}, -- this tells us what instanceID is located in any given pos - layout = layout, - dirty = false, - numVertices = 0, - primitiveType = GL.TRIANGLES, - debugZombies = true, -- this is new, and its for debugging non-existing stuff on unitdestroyed - lastInstanceID = 0, - } - - if unitIDattribID ~= nil then - instanceTable.indextoUnitID = {} - instanceTable.unitIDattribID = unitIDattribID - instanceTable.popUnitIDFailuresInGameFrame = {} - end - - function instanceTable:clearInstanceTable() - -- this wont resize it, but quickly sets it to empty - self.usedElements = 0 - self.instanceIDtoIndex = {} - self.indextoInstanceID = {} - if self.indextoUnitID then self.indextoUnitID = {} end - end - - function instanceTable:makeVAOandAttach(vertexVBO, instanceVBO, indexVBO) -- Attach a vertex buffer to an instance buffer, and optionally, an index buffer if one is supplied. - -- There is a special case for this, when we are using a vertexVBO as a quasi-instanceVBO, e.g. when we are using the geometry shader to draw a vertex as each instance. - --iT.vertexVBO = vertexVBO - --iT.indexVBO = indexVBO - local newVAO = nil - newVAO = gl.GetVAO() - if newVAO == nil then goodbye("Failed to create newVAO") end - self.VAO = newVAO - if vertexVBO == nil then -- the special case where are using 'vertices' as 'instances' - newVAO:AttachVertexBuffer(instanceVBO) - else - newVAO:AttachVertexBuffer(vertexVBO) - newVAO:AttachInstanceBuffer(instanceVBO) - self.vertexVBO = vertexVBO - self.instanceVBO = instanceVBO - end - if indexVBO then - newVAO:AttachIndexBuffer(indexVBO) - self.indexVBO = indexVBO - function self:Draw() - self.VAO:DrawElements(GL.TRIANGLES, nil, 0, self.usedElements, 0) - end - else - function self:Draw() - self.VAO:DrawArrays(GL.TRIANGLES, nil, 0, self.usedElements, 0) - end - end - return newVAO - end - - function instanceTable:clearInstanceTable() - -- this wont resize it, but quickly sets it to empty - self.usedElements = 0 - self.instanceIDtoIndex = {} - self.indextoInstanceID = {} - if self.indextoUnitID then self.indextoUnitID = {} end - end - - function instanceTable:compact() - self.destroyedElements = 0 - -- so this is for the edge case, where we have silently removed elements from instanceIDtoIndex - -- where we have holes everywhere, so we have to 'compact' the table, - -- by copying back contiguously while preserving element order - local newInstanceIDtoIndex = {} - local newIndexToInstanceID = {} - local newInstanceData = {} - local newUsedElements = 0 - for i = 1, self.usedElements do - local instanceID = self.indextoInstanceID[i] - local index = self.instanceIDtoIndex[self.indextoInstanceID[i]] - if index then - local instanceStep = self.instanceStep - local instanceData = self.instanceData - - local dstpos = newUsedElements * instanceStep - local srcpos = (i - 1) * instanceStep - for j=1, instanceStep do - newInstanceData[dstpos + j] = instanceData[srcpos +j] - end - newUsedElements = newUsedElements + 1 - newInstanceIDtoIndex[instanceID] = newUsedElements - newIndexToInstanceID[newUsedElements] = instanceID - else - --Spring.Echo("compacting index",i, 'instanceID', instanceID) - end - end - --Spring.Echo("Post compacting", self.usedElements, newUsedElements) - self.usedElements = newUsedElements - self.instanceIDtoIndex = newInstanceIDtoIndex - self.indextoInstanceID = newIndexToInstanceID - self.instanceData = newInstanceData - --iT.instanceVBO:Upload(iT.instanceData,nil,oldElementIndex-1,oldOffset +1,oldOffset + iTStep) - if self.usedElements > 0 then - self.instanceVBO:Upload(self.instanceData) - end - end - - - function instanceTable:draw(primitiveType) - if self.usedElements > 0 then - if self.indexVBO then - self.VAO:DrawElements(primitiveType or self.primitiveType, self.numVertices, 0, self.usedElements,0) - else - self.VAO:DrawArrays (primitiveType or self.primitiveType, self.numVertices, 0, self.usedElements,0) - end - end - end - - function instanceTable:getMemUsage() - -- arrays are 16 bytes per element - -- Hash tables are 40 bytes per element - local totalMem = 0 - totalMem = totalMem + self.usedElements * self.instanceStep * 16 -- the actual instance data - totalMem = totalMem + self.usedElements * 16 -- indextoinstanceid - totalMem = totalMem + self.usedElements * 40 -- instanceIDtoIndex - if self.indextoUnitID then totalMem = totalMem + self.usedElements * 16 end - return totalMem - end - - function instanceTable:Delete() - -- Frees the instancevbo and vao for this instance table. Does not touch the vertex and index vbos. - -- returns an estimate of how much ram was used - if self.instanceVBO then self.instanceVBO:Delete() end - if self.VAO then self.VAO:Delete() end - local memusage = self:getMemUsage() - self:clearInstanceTable() - return memusage - end - - - newInstanceVBO:Upload(instanceData) - - -- I believe that the openGL spec doesnt guarantee that a buffer has an idea before data is uploaded to it, so we will fill it with zeros. - if gldebugannotations then - gl.ObjectLabel(GL_BUFFER, newInstanceVBO:GetID(), myName) - end - - - --register self in WG if possible - if WG then - if WG.VBOTableRegistry == nil then - --Spring.Echo("WG.VBORegistry == nil, creating registry on first load") - WG.VBOTableRegistry = {} - end - if WG.VBOTableRegistry[instanceTable.myName] then - local newname = instanceTable.myName .. tostring(math.random()) - --Spring.Echo(instanceTable.myName, 'already registered, renaming to', newname) - instanceTable.myName = newname - end - --Spring.Echo("Registered ", instanceTable.myName) - WG.VBOTableRegistry[instanceTable.myName] = instanceTable - end - - return instanceTable -end - -local function nextInstanceID(iT) - iT.lastInstanceID = iT.lastInstanceID + 1 - return iT.lastInstanceID -end - -local function clearInstanceTable(iT) - -- this wont resize it, but quickly sets it to empty - iT.usedElements = 0 - iT.instanceIDtoIndex = {} - iT.indextoInstanceID = {} - if iT.indextoUnitID then iT.indextoUnitID = {} end -end - -local function makeVAOandAttach(vertexVBO, instanceVBO, indexVBO) -- Attach a vertex buffer to an instance buffer, and optionally, an index buffer if one is supplied. - -- There is a special case for this, when we are using a vertexVBO as a quasi-instanceVBO, e.g. when we are using the geometry shader to draw a vertex as each instance. - --iT.vertexVBO = vertexVBO - --iT.indexVBO = indexVBO - local newVAO = nil - newVAO = gl.GetVAO() - if newVAO == nil then goodbye("Failed to create newVAO") end - if vertexVBO == nil then -- the special case where are using 'vertices' as 'instances' - newVAO:AttachVertexBuffer(instanceVBO) - else - newVAO:AttachVertexBuffer(vertexVBO) - newVAO:AttachInstanceBuffer(instanceVBO) - end - if indexVBO then - newVAO:AttachIndexBuffer(indexVBO) - end - -- this allows us to set up our sane - - - return newVAO -end - - ---------------- DEBUG HELPERS -------------------------- -local function comparetables(t1, t2, name) - for k,v in pairs(t1) do - if t2[k] == nil then - Spring.Echo("Key ",k,"with value",v,"existing in t1 does not exist in t2 in ", name) - elseif t2[k] ~= v then - Spring.Echo("Value ",v,"for",k,"existing in t1 does not match value for t2",t2[k]," in ", name) - end - end - - for k,v in pairs(t2) do - if t1[k] == nil then - Spring.Echo("Key ",k,"with value",v,"existing in t2 does not exist in t1 in ", name) - elseif t1[k] ~= v then - Spring.Echo("Value ",v,"for",k,"existing in t2 does not match value for t1",t1[k]," in ", name) - end - end -end - -local function dbgt(t, name) - name = name or "" - local gf = Spring.GetGameFrame() - local count = 0 - local res = '' - for k,v in pairs(t) do - if type(k) == 'number' and type(v) == 'number' then - res = res .. tostring(k) .. ':' .. tostring(v) ..',' - count = count + 1 - end - end - Spring.Echo(tostring(gf).. " " ..name .. ' #' .. tostring(count) .. ' {'..res .. '}') - return res -end - -local function counttable(t) - local count = 0 - if type(t) ~= type({}) then return 0 end - for k, v in pairs(t) do count = count + 1 end - return count -end - -local function validateInstanceVBOTable(iT, calledfrom) - -- check that instanceIDtoIndex and indextoInstanceID are valid and contigous: - for i=1, iT.usedElements do - if iT.indextoInstanceID[i] == nil then - Spring.Echo("There is a hole in indextoInstanceID", iT.myName, "at", i,"out of",iT.usedElements, calledfrom) - --Spring.Echo() - if iT.indextoUnitID[i] == nil then - Spring.Echo("It is also missing from indextoUnitID") - else - Spring.Echo("But it does exist in indextoUnitID with an unitID of ", iT.indextoUnitID[i]) - Spring.Echo("This is valid?", Spring.GetUnitPosition(iT.indextoUnitID[i])) - end - - else - local instanceID = iT.indextoInstanceID[i] - if iT.instanceIDtoIndex[instanceID] == nil then - Spring.Echo("There is a hole instanceIDtoIndex", iT.myName, "at", i," iT.instanceIDtoIndex[instanceID] == nil ") - elseif iT.instanceIDtoIndex[instanceID] ~= i then - Spring.Echo("There is a problem in indextoInstanceID", iT.myName, "at i =", i," iT.indextoInstanceID[instanceID] ~= i, it is instead: ", iT.indextoInstanceID[instanceID] ) - end - end - end - local indextoInstanceIDsize = counttable(iT.indextoInstanceID) - local instanceIDtoIndexsize = counttable(iT.instanceIDtoIndex) - local indextoUnitID = counttable(iT.indextoUnitID) - if (indextoInstanceIDsize ~= instanceIDtoIndexsize) or (instanceIDtoIndexsize ~= indextoUnitID) then - Spring.Echo("Table size mismatch during validation of", iT.myName, indextoInstanceIDsize, instanceIDtoIndexsize, indextoUnitID) - end - -end - -function locateInvalidUnits(iT) - if iT.validinfo == nil then iT.validinfo = {} end - local invalidcount = 0 - for i, unitID in ipairs(iT.indextoUnitID) do - if iT.featureIDs then - if Spring.ValidFeatureID(unitID) then - local px, py, pz = Spring.GetFeaturePosition(unitID) - local fdefname = FeatureDefs[Spring.GetFeatureDefID(unitID)].name - iT.validinfo[unitID] = {px = px, py = py, pz = pz, fdefname = fdefname} - else - Spring.SendCommands({"pause 1"}) - Spring.Echo("INVALID feature, last seen at", unitID) - local vi = iT.validinfo[unitID] - local markertext = tostring(unitID) .. "," .. dbgt(vi) - Spring.MarkerAddPoint(vi.px, vi.py, vi.pz, markertext ) - invalidcount = invalidcount + 1 - end - else - if Spring.ValidUnitID(unitID) then - local px, py, pz = Spring.GetUnitPosition(unitID) - local unitDefID = Spring.GetUnitDefID(unitID) - local unitdefname = (unitDefID and UnitDefs[unitDefID].name) or "unknown:nil" - iT.validinfo[unitID] = {px = px, py = py, pz = pz, unitdefname = unitdefname} - else - Spring.SendCommands({"pause 1"}) - Spring.Echo(iT.myName, " INVALID unitID",unitID,"#elements", iT.usedElements, "last seen at tablepos:", i) - - local vi = iT.validinfo[unitID] - local markertext = tostring(unitID) .. "," .. dbgt(vi) - Spring.MarkerAddPoint(vi.px, vi.py, vi.pz, markertext ) - invalidcount = invalidcount + 1 - end - end - end - return invalidcount -end - -------------------------------END DEBUG HELPERS --------------------------- - -local function resizeInstanceVBOTable(iT) - -- iT: the InstanceVBOTable to double in size 'dynamically' resize the VBO, to double its size - -- this is called automatically when the existing instanceVBO gets full - -- Also performs a busload of sanity checking - -- Spring.Echo("instanceVBOTable full, resizing to double size",iT.myName, iT.usedElements,iT.maxElements) - iT.maxElements = iT.maxElements * 2 - local newInstanceVBO = gl.GetVBO(GL.ARRAY_BUFFER,true) - newInstanceVBO:Define(iT.maxElements, iT.layout) - - if iT.instanceVBO then iT.instanceVBO:Delete() end -- release if previous one existed - iT.instanceVBO = newInstanceVBO - -- ok this needs some sanitation right here, with reporting. - if iT.indextoUnitID then - -- we need to walk through both tables at the same time, and virtually pop all invalid unit/featureIDs on a resize, or else face dire consequences (crashes) later on - -- the tables we need to keep updated are: - local new_instanceData = {} - local new_instanceData_count = 0 - local new_usedElements = 0 - local new_instanceIDtoIndex = {} - local new_indextoInstanceID = {} - local new_indextoUnitID = {} - local invalidcount = 0 - local iTStep = iT.instanceStep - - for i, objectID in ipairs(iT.indextoUnitID) do - local isValidID = false - if iT.featureIDs then isValidID = Spring.ValidFeatureID(objectID) - else isValidID = Spring.ValidUnitID(objectID) end - if isValidID then - local offset = new_usedElements * iTStep - for j = 1, iTStep do - new_instanceData_count = new_instanceData_count + 1 - new_instanceData[new_instanceData_count] = iT.instanceData[j + offset] - end - new_usedElements = new_usedElements + 1 - local currentInstanceID = iT.indextoInstanceID[i] - new_indextoInstanceID[new_usedElements] = iT.indextoInstanceID[i] - new_indextoUnitID[new_usedElements] = iT.indextoUnitID[i] - new_instanceIDtoIndex[currentInstanceID] = new_usedElements - --Spring.Echo("Resize:",currentInstanceID, iT.indextoUnitID[i] ) - invalidcount = invalidcount + 1 - else - Spring.Echo("Warning: Found invalid unit/featureID",objectID,"at",i,"while resizing",iT.myName) - end - end - - if invalidcount == 0 then - comparetables( iT.instanceData, new_instanceData, "instanceData") - comparetables( iT.instanceIDtoIndex, new_instanceIDtoIndex, "instanceIDtoIndex") - comparetables( iT.indextoInstanceID, new_indextoInstanceID, "indextoInstanceID") - comparetables( iT.indextoUnitID, new_indextoUnitID, "indextoUnitID") - end - - iT.instanceData = new_instanceData - iT.usedElements = new_usedElements - iT.instanceIDtoIndex = new_instanceIDtoIndex - iT.indextoInstanceID = new_indextoInstanceID - iT.indextoUnitID = new_indextoUnitID - end - - iT.instanceVBO:Upload(iT.instanceData,nil,0,1,iT.usedElements * iT.instanceStep) - - if gldebugannotations then - gl.ObjectLabel(GL_BUFFER, iT.instanceVBO:GetID(), iT.myName) - end - - if iT.VAO then -- reattach new if updated :D - iT.VAO:Delete() - iT.VAO = makeVAOandAttach(iT.vertexVBO,iT.instanceVBO, iT.indexVBO) - end - - if iT.indextoUnitID then - if iT.featureIDs then - iT.instanceVBO:InstanceDataFromFeatureIDs(iT.indextoUnitID, iT.unitIDattribID) - else - iT.instanceVBO:InstanceDataFromUnitIDs(iT.indextoUnitID, iT.unitIDattribID) - end - end - return iT.maxElements -end - ---[[ from Ivand: -instVBO:Upload({ - 100, 0, 0, - -100, 0, 0, - 0, 0, 100, - 0, 0, -100, - }, 7, 1, 4, 6) -Here is how you upload starting from 1st element and starting from 4th element in Lua array (-100) and finishing with 6th element (0), essentially it will upload (-100, 0, 0) into 7th attribute of 2nd instance. -]]-- - -local function pushElementInstance(iT,thisInstance, instanceID, updateExisting, noUpload, unitID) - -- iT: instanceTable created with makeInstanceTable - -- thisInstance: is a lua array of values to add to table, MUST BE INSTANCESTEP SIZED LUA ARRAY - -- instanceID: an optional key given to the item, so it can be easily removed/updated by reference, defaults to the index of the instance in the buffer (1 based) - -- updateExisting: allow updating an existing element (same instanceID key) - -- noUpload: prevent the VBO from being uploaded, if you feel like you are going to do a lot of ops and wish to manually upload when done instead - -- unitID: if given, it will store then unitID corresponding to this instance, and will try to update the InstanceDataFromUnitIDs for this unit - -- returns: the index of the instanceID in the table on success, else nil - if #thisInstance ~= iT.instanceStep then - Spring.Echo("Trying to upload an oddly sized instance into",iT.myName, #thisInstance, "instead of ",iT.instanceStep) - Spring.Debug.TraceFullEcho(20,20,20, "pushElementInstance Failure:"..iT.myName ) - end - local iTusedElements = iT.usedElements - local iTStep = iT.instanceStep - local endOffset = iTusedElements * iTStep - if instanceID == nil then instanceID = nextInstanceID(iT) end - local thisInstanceIndex = iT.instanceIDtoIndex[instanceID] - - if (iTusedElements + 1 ) >= iT.maxElements then -- add 1 extra for safety (not the best idea, but we seem to be running over it by 1) - resizeInstanceVBOTable(iT) - iTusedElements = iT.usedElements -- because during validation of unitIDs during resizing, we can decrease the actual size of the table! - thisInstanceIndex = iT.instanceIDtoIndex[instanceID] -- this too, can change, TODO, also do this in VBOIDtable! - end - - if thisInstanceIndex == nil then -- new, register it - thisInstanceIndex = iTusedElements + 1 - iT.usedElements = iTusedElements + 1 - iT.instanceIDtoIndex[instanceID] = thisInstanceIndex - iT.indextoInstanceID[thisInstanceIndex] = instanceID - else -- pre-existing ID, update or bail - if updateExisting == nil then - Spring.Echo("Tried to add existing element to an instanceTable",iT.myName, instanceID) - return nil - else - endOffset = (thisInstanceIndex - 1) * iTStep - end - end - local instanceData = iT.instanceData - for i =1, iTStep do -- copy data, but fast - instanceData[endOffset + i] = thisInstance[i] - end - - if unitID ~= nil then - local isvalidid - if iT.featureIDs then isvalidid = Spring.ValidFeatureID(unitID) - else isvalidid = Spring.ValidUnitID(unitID) end - if isvalidid == false then - Spring.Echo("Error: Attempted to push an invalid unit/featureID",unitID, "into", iT.myName) - noUpload = true - Spring.Debug.TraceFullEcho(20,20,20,"invalid unit/featureID in " ..iT.myName) - end - iT.indextoUnitID[thisInstanceIndex] = unitID - end - - if noUpload ~= true then --upload or mark as dirty - iT.instanceVBO:Upload(thisInstance, nil, thisInstanceIndex - 1) - --Spring.Echo("pushElementInstance,unitID, iT.unitIDattribID, thisInstanceIndex",unitID, iT.unitIDattribID, thisInstanceIndex) - if unitID ~= nil then - if iT.featureIDs then - iT.instanceVBO:InstanceDataFromFeatureIDs(unitID, iT.unitIDattribID, thisInstanceIndex-1) - else - iT.instanceVBO:InstanceDataFromUnitIDs(unitID, iT.unitIDattribID, thisInstanceIndex-1) - end - end - else - iT.dirty = true - end - - if iT.debug then validateInstanceVBOTable(iT, 'push') end - return instanceID -end - -local function popElementInstance(iT, instanceID, noUpload) - -- iT: instanceTable created with makeInstanceTable - -- instanceID: an optional key given to the item, so it can be easily removed by reference, defaults to the last element of the buffer, but this will screw up the instanceIDtoIndex table if used in mixed keys mode - -- noUpload: prevent the VBO from being uploaded, if you feel like you are going to do a lot of ops and wish to manually upload when done instead - -- returns nil on failure, the the index of the element on success - if instanceID == nil then - Spring.Echo("Tried to remove element with nil instanceID from instanceTable " .. iT.myName) - return nil - end - - if iT.instanceIDtoIndex[instanceID] == nil then -- if key is instanceID yet does not exist, then warn and bail - Spring.Echo("Tried to remove element ",instanceID,'From instanceTable', iT.myName, 'but it does not exist in it') - Spring.Debug.TraceFullEcho(10,10,3, iT.myName) - return nil - end - if iT.usedElements == 0 then -- Dont remove the last element - Spring.Echo("Tried to remove element ",instanceID,'From instanceTable', iT.myName, 'but it should be empty') - return nil - end - - --Fetch the position of the element we want to remove from the 'middle' of the table - local oldElementIndex = iT.instanceIDtoIndex[instanceID] - iT.instanceIDtoIndex[instanceID] = nil -- clean these out - iT.indextoInstanceID[oldElementIndex] = nil - - -- get the index of the last element - local lastElementIndex = iT.usedElements - - -- if this one was already at the end of the queue, do nothing but decrement usedElements and clear mappings - if oldElementIndex == lastElementIndex then - --Spring.Echo("Removed end element of instanceTable", iT.myName) - iT.usedElements = iT.usedElements - 1 - -- if it had a related unitID stored, remove that: - if iT.indextoUnitID then iT.indextoUnitID[oldElementIndex] = nil end - - if iT.debugZombies then - if iT.zombies and iT.zombies[instanceID] then - --Spring.Echo("Good, we are killing a stupid zombie at the end", instanceID, iT.numZombies) - iT.zombies[instanceID] = nil - iT.numZombies = iT.numZombies - 1 - end - end - - else - local lastElementInstanceID = iT.indextoInstanceID[lastElementIndex] - if lastElementInstanceID == nil then -- - Spring.Echo("We somehow have a nil element at the back of the array, which is completely invalid, probably about to crash", iT.myName) - dbgt(iT.instanceIDtoIndex, "instanceIDtoIndex") - dbgt(iT.indextoInstanceID, "indextoInstanceID") - dbgt(iT.indextoUnitID, "indextoUnitID") - end - local iTStep = iT.instanceStep - local endOffset = (iT.usedElements - 1)*iTStep - - iT.instanceIDtoIndex[lastElementInstanceID] = oldElementIndex -- lastElementInstanceID was somehow nil here? - iT.indextoInstanceID[oldElementIndex] = lastElementInstanceID - iT.indextoInstanceID[lastElementIndex] = nil --- somehow this got forgotten? TODO for VBOIDtable - - local oldOffset = (oldElementIndex-1)*iTStep - local instanceData = iT.instanceData - for i = 1, iTStep do - instanceData[oldOffset + i ] = instanceData[endOffset + i] - end - --size_t LuaVBOImpl::Upload(const sol::stack_table& luaTblData, const sol::optional attribIdxOpt, const sol::optional elemOffsetOpt, const sol::optional luaStartIndexOpt, const sol::optional luaFinishIndexOpt) - --Spring.Echo("Removing instanceID",instanceID,"from iT at position", oldElementIndex, "shuffling back at", iT.usedElements,"endoffset=",endOffset,'oldOffset=',oldOffset) - if noUpload ~= true then - --Spring.Echo("Upload", oldElementIndex -1, oldOffset+1, oldOffset+iTStep) - iT.instanceVBO:Upload(iT.instanceData,nil,oldElementIndex-1,oldOffset +1,oldOffset + iTStep) - else - iT.dirty = true - end - -- Do the unitID shuffle if needed: - if iT.indextoUnitID then - --Spring.Echo("popElementInstance,unitID, iT.unitIDattribID, thisInstanceIndex",unitID, iT.unitIDattribID, oldElementIndex) - local popunitID = iT.indextoUnitID[lastElementIndex] - if popunitID == nil then - Spring.Echo("TODO: what the f is happening here?, how the f could we have popped a nil from the back of?", iT.myName) -- TODO TODO - end - - if iT.debugZombies then - local gf = Spring.GetGameFrame() - --Spring.Echo("Popping", instanceID) - if iT.lastpopgameframe == nil then - iT.lastpopgameframe = gf - iT.zombies = {} - iT.numZombies = 0 - else - if iT.lastpopgameframe ~= gf then -- New gameframe - iT.lastpopgameframe = gf - if iT.numZombies and iT.numZombies > 0 then -- WE HAVE ZOMBIES AAAAARGH - local s = "Warning: We have " .. tostring(iT.numZombies) .. " zombie units left over in " .. iT.myName - for zombie, gf in pairs(iT.zombies) do - s = s .. " " .. tostring(zombie) ..'/'..tostring(gf) - Spring.Echo("ZOMBIE instanceID", zombie, 'gf',gf) - --Spring.SendCommands({"pause 1"}) - Spring.Debug.TraceFullEcho(nil,nil,nil, iT.myName) - end - Spring.Echo(s) - iT.zombies = {} - iT.numZombies = 0 - end - else -- same gameframe - if iT.zombies[instanceID] then - --Spring.Echo("Good, we are killing a stupid zombie", gf, instanceID, iT.numZombies) - iT.zombies[instanceID] = nil - iT.numZombies = iT.numZombies - 1 - end - end - end - end - - iT.indextoUnitID[oldElementIndex] = popunitID - iT.indextoUnitID[lastElementIndex] = nil - - if (iT.featureIDs and Spring.ValidFeatureID(popunitID)) or Spring.ValidUnitID(popunitID) then - if noUpload ~= true then - if iT.featureIDs then - iT.instanceVBO:InstanceDataFromFeatureIDs(popunitID, iT.unitIDattribID, oldElementIndex-1) - else - iT.instanceVBO:InstanceDataFromUnitIDs(popunitID, iT.unitIDattribID, oldElementIndex-1) - end - end - else - if iT.debugZombies then - --Spring.Echo("Warning: Tried to pop back an invalid" .. ((iT.featureIDs and "featureID") or "unitID"), popunitID, "from", iT.myName, "while removing instance", instanceID, counttable(iT.instanceIDtoIndex), counttable(iT.indextoInstanceID), counttable(iT.indextoUnitID)) - --Spring.Debug.TraceFullEcho() - local gf = Spring.GetGameFrame() - if iT.lastpopgameframe == nil or iT.lastpopgameframe ~= gf then -- New gameframe - iT.lastpopgameframe = gf - iT.zombies = {} - iT.numZombies = 0 - end - if iT.zombies[lastElementInstanceID] == nil then - iT.zombies[lastElementInstanceID] = gf - iT.numZombies = iT.numZombies + 1 - end - end - end - end - iT.usedElements = iT.usedElements - 1 - end - - if iT.debug then validateInstanceVBOTable(iT,'pop') end - return oldElementIndex -end - -local function getElementInstanceData(iT, instanceID, cacheTable) - -- iT: instanceTable created with makeInstanceTable - -- instanceID: an optional key given to the item, so it can be easily removed by reference, defaults to the index of the instance in the buffer (1 based) - local instanceIndex = iT.instanceIDtoIndex[instanceID] - if instanceIndex == nil then - Spring.Echo("Tried to getElementInstanceData from",iT.myName,instanceID, "but it does not exist") - return nil - end - local iData = cacheTable or {} - local iTStep = iT.instanceStep - instanceIndex = (instanceIndex-1) * iTStep - local instanceData = iT.instanceData - for i = 1, iTStep do - iData[i] = instanceData[instanceIndex + i] - end - return iData -end - -local function uploadAllElements(iT) - -- upload all USED elements - if iT.usedElements == 0 then return end - - iT.instanceVBO:Upload(iT.instanceData,nil,0, 1, iT.usedElements * iT.instanceStep) - iT.dirty = false - if iT.indextoUnitID then - if iT.featureIDs then - iT.instanceVBO:InstanceDataFromFeatureIDs(iT.indextoUnitID, iT.unitIDattribID) - else - iT.instanceVBO:InstanceDataFromUnitIDs(iT.indextoUnitID, iT.unitIDattribID) - end - end -end - -local function uploadElementRange(iT, startElementIndex, endElementIndex) - iT.instanceVBO:Upload(iT.instanceData, -- The lua mirrored VBO data - nil, -- the attribute index, nil for all attributes - startElementIndex, -- vboOffset optional, , what ELEMENT offset of the VBO to start uploading into, 0 based - startElementIndex * iT.instanceStep + 1, -- luaStartIndex, default 1, what element of the lua array to start uploading from. 1 is the 1st element of a lua table. - endElementIndex * iT.instanceStep --] luaEndIndex, default #{array}, what element of the lua array to upload up to, inclusively - ) - if iT.indextoUnitID then - --we need to reslice the table - local unitIDRange = {} - local indextoUnitID = iT.indextoUnitID - for i = startElementIndex, endElementIndex do - unitIDRange[#unitIDRange + 1] = indextoUnitID[i] - end - if iT.featureIDs then - iT.instanceVBO:InstanceDataFromFeatureIDs(unitIDRange, iT.unitIDattribID, startElementIndex - 1) - else - iT.instanceVBO:InstanceDataFromUnitIDs(unitIDRange, iT.unitIDattribID, startElementIndex - 1) - end - end -end - --- This function allows for order-preserving compacting of a list of instances based on these funcs. --- It is designed for Decals GL4, where draw order matters a lot! --- remove takes priority over keep -local function compactInstanceVBO(iT, removelist, keeplist) - local usedElements = iT.usedElements - if usedElements == 0 then return 0 end - local instanceStep = iT.instanceStep - local instanceData = iT.instanceData - local indextoInstanceID = iT.indextoInstanceID - local newindextoInstanceID = {} - local newinstanceIDtoIndex = {} - local newUsedElements = 0 - local numremoved = 0 - local removemode = (removelist ~= nil) and (keeplist == nil) - for index, instanceID in ipairs(indextoInstanceID) do - -- If its in keeplist, - if (removemode and (removelist[instanceID]== nil) ) or ((removemode == false) and keeplist[instanceID]) then - local instanceOffset = (index-1) * instanceStep - local newInstanceOffset = newUsedElements * instanceStep - for i = 1, instanceStep do - instanceData[newInstanceOffset + i] = instanceData[instanceOffset + i] - end - newUsedElements = newUsedElements + 1 - newindextoInstanceID[newUsedElements] = instanceID - newinstanceIDtoIndex[instanceID] = newUsedElements - else - numremoved = numremoved + 1 - end - end - if numremoved > 0 then - iT.dirty = true -- we set the flag to notify that CPU and GPU contents dont match! - iT.usedElements = newUsedElements - iT.instanceIDtoIndex = newinstanceIDtoIndex - iT.indextoInstanceID = newindextoInstanceID - end - return numremoved -end - -local function drawInstanceVBO(iT) - if iT.usedElements > 0 then - if iT.indexVBO then - iT.VAO:DrawElements(iT.primitiveType, iT.numVertices, 0, iT.usedElements,0) - else - iT.VAO:DrawArrays(iT.primitiveType, iT.numVertices, 0, iT.usedElements,0) - end - end -end - -local function countInvalidUnitIDs(iT) - local invalids = {} - for i, objectID in ipairs(iT.indextoUnitID) do - local isValidID = false - if iT.featureIDs then isValidID = Spring.ValidFeatureID(objectID) - else isValidID = Spring.ValidUnitID(objectID) end - if isValidID then - - else - invalids[#invalids + 1] = objectID - end - end - if #invalids > 0 then - Spring.Echo(#invalids, "invalid IDs found in ", iT.myName) - end - return invalids -end - - ---------- HELPERS FOR PRIMITIVES ------------------ - -local function makeCircleVBO(circleSegments, radius, startCenter, name) - -- Makes circle of radius in xy space - -- can be used in both GL.LINES and GL.TRIANGLE_FAN mode - -- Startcenter places a vertex in the center, this is nice for triangle fans, - -- but when drawing lines with this vbo, start at an offset of 1 - -- Fun note: its NOT faster to draw stenciled circles with this. - if not radius then radius = 1 end - circleSegments = circleSegments -1 -- for po2 buffers - local circleVBO = gl.GetVBO(GL.ARRAY_BUFFER,true) - if circleVBO == nil then return nil end - - local VBOLayout = { - {id = 0, name = "position", size = 4}, - } - - local VBOData = {} - if startCenter then - VBOData[#VBOData+1] = 0 -- X - VBOData[#VBOData+1] = 0 -- Y - VBOData[#VBOData+1] = 0 -- circumference [0-1] - VBOData[#VBOData+1] = radius - end - - for i = 0, circleSegments do -- this is +1 - VBOData[#VBOData+1] = math.sin(math.pi*2* i / circleSegments) * radius -- X - VBOData[#VBOData+1] = math.cos(math.pi*2* i / circleSegments) * radius-- Y - VBOData[#VBOData+1] = i / circleSegments -- circumference [0-1] - VBOData[#VBOData+1] = radius - end - - circleVBO:Define( - circleSegments + 1 + (startCenter and 1 or 0) , -- +1 for center point if startCenter is true - VBOLayout - ) - circleVBO:Upload(VBOData) - if gldebugannotations then - gl.ObjectLabel(GL_BUFFER, circleVBO:GetID(), name or "CircleVBO") - end - return circleVBO, #VBOData/4 -end - -local function makePlaneVBO(xsize, ysize, xresolution, yresolution, name) -- makes a plane from [-xsize to xsize] with xresolution subdivisions - if not xsize then xsize = 1 end - if not ysize then ysize = xsize end - if not xresolution then xresolution = 1 end - if not yresolution then yresolution = xresolution end - xresolution = math.floor(xresolution) - yresolution = math.floor(yresolution) - local planeVBO = gl.GetVBO(GL.ARRAY_BUFFER,false) - if planeVBO == nil then return nil end - - local VBOLayout = { - {id = 0, name = "xyworld_xyfract", size = 2}, - } - - local VBOData = {} - - for x = 0, xresolution do -- this is +1 - for y = 0, yresolution do - VBOData[#VBOData+1] = xsize * ((x / xresolution) -0.5 ) *2 - VBOData[#VBOData+1] = ysize * ((y / yresolution) -0.5 ) * 2 - end - end - - planeVBO:Define( - (xresolution + 1) * (yresolution + 1) , - VBOLayout - ) - planeVBO:Upload(VBOData) - - if gldebugannotations then - gl.ObjectLabel(GL_BUFFER, planeVBO:GetID(), name or "PlaneVBO") - end - - --Spring.Echo("PlaneVBOData up:",#VBOData, "Down", #planeVBO:Download()) - return planeVBO, #VBOData/2 -end - -local function makePlaneIndexVBO(xresolution, yresolution, cutcircle, name) - xresolution = math.floor(xresolution) - if not yresolution then yresolution = xresolution end - local planeIndexVBO = gl.GetVBO(GL.ELEMENT_ARRAY_BUFFER,false) - if planeIndexVBO == nil then return nil end - - local function xyinrad(lx, ly) - local px = (lx / xresolution) * 2 - 1 - local py = (ly / yresolution) * 2 - 1 - return (px*px + py*py) <= 1 - end - - local IndexVBOData = {} - local qindex = 0 - local colsize = yresolution + 1 - for x = 0, xresolution-1 do -- this is +1 - for y = 0, yresolution-1 do - --this is only 20% optimization - if cutcircle == nil or (xyinrad(x,y) or xyinrad(x + 1,y) or xyinrad(x,y + 1 )) then - -- top left one - IndexVBOData[#IndexVBOData + 1] = qindex - IndexVBOData[#IndexVBOData + 1] = qindex +1 - IndexVBOData[#IndexVBOData + 1] = qindex + colsize - end - - if cutcircle == nil or (xyinrad(x+1,y+1) or xyinrad(x + 1,y) or xyinrad(x,y + 1 )) then - -- bottom right one? - IndexVBOData[#IndexVBOData + 1] = qindex +1 - IndexVBOData[#IndexVBOData + 1] = qindex + colsize + 1 - IndexVBOData[#IndexVBOData + 1] = qindex + colsize - end - qindex = qindex + 1 - - end - qindex = qindex + 1 - end - planeIndexVBO:Define( - # IndexVBOData - ) - planeIndexVBO:Upload(IndexVBOData) - - if gldebugannotations then - gl.ObjectLabel(GL_BUFFER, planeIndexVBO:GetID(), name or "planeIndexVBO") - end - --Spring.Echo("PlaneIndexVBO up:",#IndexVBOData, "Down", #planeIndexVBO:Download()) - return planeIndexVBO, IndexVBOData -end - -local function makePointVBO(numPoints, randomFactor, name) - -- makes points with xyzw - -- can be used in both GL.LINES and GL.TRIANGLE_FAN mode - numPoints = numPoints or 1 - randomFactor = randomFactor or 0 - local pointVBO = gl.GetVBO(GL.ARRAY_BUFFER,true) - if pointVBO == nil then return nil end - - local VBOLayout = { - {id = 0, name = "position_w", size = 4}, - } - - local VBOData = {} - - for i = 1, numPoints do -- - VBOData[#VBOData+1] = randomFactor * math.random()-- X - VBOData[#VBOData+1] = randomFactor * math.random()-- Y - VBOData[#VBOData+1] = randomFactor * math.random()---Z - VBOData[#VBOData+1] = i/numPoints -- index for lolz? - end - - pointVBO:Define( - numPoints, - VBOLayout - ) - pointVBO:Upload(VBOData) - - if gldebugannotations then - gl.ObjectLabel(GL_BUFFER, pointVBO:GetID(), name or "pointVBO") - end - return pointVBO, numPoints -end - -local function makeRectVBO(minX,minY, maxX, maxY, minU, minV, maxU, maxV, name) - if minX == nil then - minX, minY, maxX, maxY, minU, minV, maxU, maxV = 0,0,1,1,0,0,1,1 - end - -- makes points with xyzw - -- can be used in both GL.LINES and GL.TRIANGLE_FAN mode - local rectVBO = gl.GetVBO(GL.ARRAY_BUFFER,false) - if rectVBO == nil then return nil end - - local VBOLayout = { - {id = 0, name = "position_xy_uv", size = 4}, - } - - local VBOData = { - --bl - minX,minY, minU, minV, --bl - minX,maxY, minU, maxV, --tr - maxX,maxY, maxU, maxV, --tr - maxX,maxY, maxU, maxV, --tr - maxX,minY, maxU, minV, --br - minX,minY, minU, minV, --bl - } - - rectVBO:Define( - 6, - VBOLayout - ) - rectVBO:Upload(VBOData) - - if gldebugannotations then - gl.ObjectLabel(GL_BUFFER, rectVBO:GetID(), name or "rectVBO") - end - return rectVBO, 6 -end - -local function makeRectIndexVBO(name) - local rectIndexVBO = gl.GetVBO(GL.ELEMENT_ARRAY_BUFFER,false) - if rectIndexVBO == nil then return nil end - - rectIndexVBO:Define( - 6 - ) - rectIndexVBO:Upload({0,1,2,3,4,5}) - if gldebugannotations then - gl.ObjectLabel(GL_BUFFER, rectIndexVBO:GetID(), name or "rectIndexVBO") - end - return rectIndexVBO,6 -end - - - -local function makeConeVBO(numSegments, height, radius, name) - -- make a cone that points up, (y = height), with radius specified - -- returns the VBO object, and the number of elements in it (usually == numvertices) - -- needs GL.TRIANGLES - if not height then height = 1 end - if not radius then radius = 1 end - local coneVBO = gl.GetVBO(GL.ARRAY_BUFFER,true) - if coneVBO == nil then return nil end - - local VBOData = {} - - for i = 1, numSegments do - -- center vertex - VBOData[#VBOData+1] = 0 - VBOData[#VBOData+1] = 0 - VBOData[#VBOData+1] = 0 - VBOData[#VBOData+1] = (i - 1) / numSegments - - --- first cone flat - VBOData[#VBOData+1] = math.sin(math.pi*2* (i - 1) / numSegments) * radius -- X - VBOData[#VBOData+1] = 0 - VBOData[#VBOData+1] = -1* math.cos(math.pi*2* (i - 1) / numSegments) * radius-- Y - VBOData[#VBOData+1] = (i - 1) / numSegments - - --- second cone flat - VBOData[#VBOData+1] = math.sin(math.pi*2* (i - 0) / numSegments) * radius-- X - VBOData[#VBOData+1] = 0 - VBOData[#VBOData+1] = -1* math.cos(math.pi*2* (i - 0) / numSegments) * radius -- Y - VBOData[#VBOData+1] =(i - 0) / numSegments - - -- top vertex - VBOData[#VBOData+1] = 0 - VBOData[#VBOData+1] = height - VBOData[#VBOData+1] = 0 - VBOData[#VBOData+1] = (i - 1) / numSegments - - --- first cone flat - VBOData[#VBOData+1] = math.sin(math.pi*2* (i - 0) / numSegments) * radius -- X - VBOData[#VBOData+1] = 0 - VBOData[#VBOData+1] = -1*math.cos(math.pi*2* (i - 0) / numSegments) * radius -- Y - VBOData[#VBOData+1] =(i - 0) / numSegments - - --- second cone flat - VBOData[#VBOData+1] = math.sin(math.pi*2* (i - 1) / numSegments) * radius -- X - VBOData[#VBOData+1] = 0 - VBOData[#VBOData+1] = -1*math.cos(math.pi*2* (i - 1) / numSegments) * radius -- Y - VBOData[#VBOData+1] =(i - 1) / numSegments - end - - - coneVBO:Define(#VBOData/4, {{id = 0, name = "localpos_progress", size = 4}}) - coneVBO:Upload(VBOData) - - if gldebugannotations then - gl.ObjectLabel(GL_BUFFER, coneVBO:GetID(), name or "coneVBO") - end - - return coneVBO, #VBOData/4 -end - - - -local function makeCylinderVBO(numSegments, height, radius, hastop, hasbottom, name) - -- make a cylinder that points up, (y = height), with radius specified - -- returns the VBO object, and the number of elements in it (usually == numvertices) - -- needs GL.TRIANGLES - if not height then height = 1 end - if not radius then radius = 1 end - local cylinderVBO = gl.GetVBO(GL.ARRAY_BUFFER,true) - if cylinderVBO == nil then return nil end - - local VBOData = {} - - for i = 1, numSegments do - if hasbottom then - -- center vertex - VBOData[#VBOData+1] = 0 - VBOData[#VBOData+1] = -1* height - VBOData[#VBOData+1] = 0 - VBOData[#VBOData+1] = (i - 1) / numSegments - - --- first cone flat - VBOData[#VBOData+1] = math.sin(math.pi*2* (i - 1) / numSegments) * radius -- X - VBOData[#VBOData+1] = -1* height - VBOData[#VBOData+1] = -1* math.cos(math.pi*2* (i - 1) / numSegments) * radius-- Y - VBOData[#VBOData+1] = (i - 1) / numSegments - - --- second cone flat - VBOData[#VBOData+1] = math.sin(math.pi*2* (i - 0) / numSegments) * radius-- X - VBOData[#VBOData+1] = -1* height - VBOData[#VBOData+1] = -1* math.cos(math.pi*2* (i - 0) / numSegments) * radius -- Y - VBOData[#VBOData+1] =(i - 0) / numSegments - end - - - --- first cone flat - VBOData[#VBOData+1] = math.sin(math.pi*2* (i - 0) / numSegments) * radius -- X - VBOData[#VBOData+1] = height - VBOData[#VBOData+1] = -1*math.cos(math.pi*2* (i - 0) / numSegments) * radius -- Y - VBOData[#VBOData+1] =(i - 0) / numSegments - - --- second cone flat - VBOData[#VBOData+1] = math.sin(math.pi*2* (i - 1) / numSegments) * radius -- X - VBOData[#VBOData+1] = height - VBOData[#VBOData+1] = -1*math.cos(math.pi*2* (i - 1) / numSegments) * radius -- Y - VBOData[#VBOData+1] =(i - 1) / numSegments - - - - --- first cone flat - VBOData[#VBOData+1] = math.sin(math.pi*2* (i - 0) / numSegments) * radius -- X - VBOData[#VBOData+1] = -1 * height - VBOData[#VBOData+1] = -1*math.cos(math.pi*2* (i - 0) / numSegments) * radius -- Y - VBOData[#VBOData+1] =(i - 0) / numSegments - - --- second cone flat - VBOData[#VBOData+1] = math.sin(math.pi*2* (i - 1) / numSegments) * radius -- X - VBOData[#VBOData+1] = height - VBOData[#VBOData+1] = -1*math.cos(math.pi*2* (i - 1) / numSegments) * radius -- Y - VBOData[#VBOData+1] =(i - 1) / numSegments - - - --- first cone flat - VBOData[#VBOData+1] = math.sin(math.pi*2* (i - 0) / numSegments) * radius -- X - VBOData[#VBOData+1] = -1 * height - VBOData[#VBOData+1] = -1*math.cos(math.pi*2* (i - 0) / numSegments) * radius -- Y - VBOData[#VBOData+1] =(i - 0) / numSegments - - - --- second cone flat - VBOData[#VBOData+1] = math.sin(math.pi*2* (i - 1) / numSegments) * radius -- X - VBOData[#VBOData+1] = -1 * height - VBOData[#VBOData+1] = -1*math.cos(math.pi*2* (i - 1) / numSegments) * radius -- Y - VBOData[#VBOData+1] =(i - 1) / numSegments - - - - if hastop then - -- center vertex - VBOData[#VBOData+1] = 0 - VBOData[#VBOData+1] = height - VBOData[#VBOData+1] = 0 - VBOData[#VBOData+1] = (i - 1) / numSegments - - --- first cone flat - VBOData[#VBOData+1] = math.sin(math.pi*2* (i - 1) / numSegments) * radius -- X - VBOData[#VBOData+1] = height - VBOData[#VBOData+1] = -1* math.cos(math.pi*2* (i - 1) / numSegments) * radius-- Y - VBOData[#VBOData+1] = (i - 1) / numSegments - - --- second cone flat - VBOData[#VBOData+1] = math.sin(math.pi*2* (i - 0) / numSegments) * radius-- X - VBOData[#VBOData+1] = height - VBOData[#VBOData+1] = -1* math.cos(math.pi*2* (i - 0) / numSegments) * radius -- Y - VBOData[#VBOData+1] =(i - 0) / numSegments - end - end - - - cylinderVBO:Define(#VBOData/4, {{id = 0, name = "localpos_progress", size = 4}}) - cylinderVBO:Upload(VBOData) - - if gldebugannotations then - gl.ObjectLabel(GL_BUFFER, cylinderVBO:GetID(), name or "cylinderVBO") - end - - return cylinderVBO, #VBOData/4 -end - - - -local function makeBoxVBO(minX, minY, minZ, maxX, maxY, maxZ, name) -- make a box - -- needs GL.TRIANGLES - local boxVBO = gl.GetVBO(GL.ARRAY_BUFFER,true) - if boxVBO == nil then return nil end - - local VBOData = { - minX,minY,minZ,0 - ,minX,minY,maxZ,0 - ,minX,maxY,maxZ,0 - ,maxX,maxY,minZ,0 - ,minX,minY,minZ,0 - ,minX,maxY,minZ,0 - ,maxX,minY,maxZ,0 - ,minX,minY,minZ,0 - ,maxX,minY,minZ,0 - ,maxX,maxY,minZ,0 - ,maxX,minY,minZ,0 - ,minX,minY,minZ,0 - ,minX,minY,minZ,0 - ,minX,maxY,maxZ,0 - ,minX,maxY,minZ,0 - ,maxX,minY,maxZ,0 - ,minX,minY,maxZ,0 - ,minX,minY,minZ,0 - ,minX,maxY,maxZ,0 - ,minX,minY,maxZ,0 - ,maxX,minY,maxZ,0 - ,maxX,maxY,maxZ,0 - ,maxX,minY,minZ,0 - ,maxX,maxY,minZ,0 - ,maxX,minY,minZ,0 - ,maxX,maxY,maxZ,0 - ,maxX,minY,maxZ,0 - ,maxX,maxY,maxZ,0 - ,maxX,maxY,minZ,0 - ,minX,maxY,minZ,0 - ,maxX,maxY,maxZ,0 - ,minX,maxY,minZ,0 - ,minX,maxY,maxZ,0 - ,maxX,maxY,maxZ,0 - ,minX,maxY,maxZ,0 - ,maxX,minY,maxZ,0 - } - boxVBO:Define(#VBOData/4, {{id = 0, name = "localpos_progress", size = 4}}) - boxVBO:Upload(VBOData) - - if gldebugannotations then - gl.ObjectLabel(GL_BUFFER, boxVBO:GetID(), name or "boxVBO") - end - - return boxVBO, #VBOData/4 -end - - - ----Generate a sphere vertex VBO and the corresponding indexVBO ----The sphere is oriented in the Z direction ----Layout: ----{id = 0, name = "position", size = 4}, -- cake slices along Z, w is sector angle. ----{id = 1, name = "normals", size = 3}, -- normal vector ----{id = 2, name = "uvs", size = 2}, -- UV vector, where x goes around the belly and y goes along Z ----@param sectorCount number is the number of orange slices around the belly in XY ----@param stackCount number how many horizontal slices along Z, usually less than sectorcount ----@param radius number how many elmos in radius, default 1 -local function makeSphereVBO(sectorCount, stackCount, radius, name) -- http://www.songho.ca/opengl/gl_sphere.html - - - local sphereVBO = gl.GetVBO(GL.ARRAY_BUFFER,true) - if sphereVBO == nil then return nil end - local vertVBOLayout = { - {id = 0, name = "position", size = 4}, - {id = 1, name = "normals", size = 3}, - {id = 2, name = "uvs", size = 2}, - } - - local VBOData = {} - radius = radius or 1 - local x, y, z, xy; -- vertex position - local nx, ny, nz - local lengthInv = 1.0 / radius; -- vertex normal - local s, t; -- vertex texCoord - - local sectorStep = 2 * math.pi / sectorCount; - local stackStep = math.pi / stackCount; - local sectorAngle, stackAngle; - - for i = 0, stackCount do - - stackAngle = math.pi / 2 - i * stackStep; -- starting from pi/2 to -pi/2 - xy = radius * math.cos(stackAngle); -- r * cos(u) - z = radius * math.sin(stackAngle); -- r * sin(u) - - -- add (sectorCount+1) vertices per stack - -- the first and last vertices have same position and normal, but different tex coords - for j = 0, sectorCount do -- for (int j = 0; j <= sectorCount; ++j) - - sectorAngle = j * sectorStep; -- starting from 0 to 2pi - - -- vertex position (x, y, z) - x = xy * math.cos(sectorAngle); -- r * cos(u) * cos(v) - y = xy * math.sin(sectorAngle); -- r * cos(u) * sin(v) - VBOData[#VBOData + 1] = x; - VBOData[#VBOData + 1] = y; - VBOData[#VBOData + 1] = z; - VBOData[#VBOData + 1] = sectorAngle; - --Spring.Echo(x,y,z) - -- normalized vertex normal (nx, ny, nz) - nx = x * lengthInv; - ny = y * lengthInv; - nz = z * lengthInv; - - - VBOData[#VBOData + 1] = nx; - VBOData[#VBOData + 1] = ny; - VBOData[#VBOData + 1] = nz; - - -- vertex tex coord (s, t) range between [0, 1] - s = j / sectorCount; - t = i / stackCount; - - VBOData[#VBOData + 1] = s; - VBOData[#VBOData + 1] = t; - end - end - sphereVBO:Define(#VBOData/9, vertVBOLayout) - sphereVBO:Upload(VBOData) - - if gldebugannotations then - gl.ObjectLabel(GL_BUFFER, sphereVBO:GetID(), name or "sphereVBO") - end - - local numVerts = #VBOData/9 - - local sphereIndexVBO = gl.GetVBO(GL.ELEMENT_ARRAY_BUFFER,false) - VBOData = {} - - -- generate CCW index list of sphere triangles - -- k1--k1+1 - -- | / | - -- | / | - -- k2--k2+1 - local k1, k2 - for i = 0, stackCount-1 do -- for(int i = 0; i < stackCount; ++i) - - k1 = i * (sectorCount + 1) -- beginning of current stack - k2 = k1 + sectorCount + 1 -- beginning of next stack - - for j = 0, sectorCount-1 do --for(int j = 0; j < sectorCount; ++j, ++k1, ++k2) - -- Spring.Echo('indices', k1, k2) - -- 2 triangles per sector excluding first and last stacks - -- k1 => k2 => k1+1 - if i ~= 0 then - - VBOData[#VBOData + 1] = k1 - VBOData[#VBOData + 1] = k2 - VBOData[#VBOData + 1] = k1 + 1 - end - - -- k1+1 => k2 => k2+1 - if i ~= (stackCount-1) then - - VBOData[#VBOData + 1] = k1 + 1 - VBOData[#VBOData + 1] = k2 - VBOData[#VBOData + 1] = k2 + 1 - - end - - k1 = k1 + 1 - k2 = k2 + 1 - end - end - - - sphereIndexVBO:Define(#VBOData) - sphereIndexVBO:Upload(VBOData) - - if gldebugannotations then - gl.ObjectLabel(GL_BUFFER, sphereIndexVBO:GetID(), name or "sphereIndexVBO") - end - - return sphereVBO, numVerts, sphereIndexVBO, #VBOData -end - - -local function MakeTexRectVAO(minX,minY, maxX, maxY, minU, minV, maxU, maxV, name) - -- Draw with myGL4TexRectVAO:DrawArrays(GL.TRIANGLES) - minX,minY,maxX,maxY,minU,minV,maxU,maxV = minX or -1,minY or -1,maxX or 1, maxY or 1, minU or 0, minV or 0, maxU or 1, maxV or 1 - - local myGL4TexRectVAO - local rectVBO = gl.GetVBO(GL.ARRAY_BUFFER,false) - if rectVBO == nil then return nil end - - --rectVBO:Define( 6, {{id = 0, name = "position_xy_uv", size = 8}}) - local z = 0.5 - local w = 1 - rectVBO:Define( 6, {{id = 0, name = "pos", size = 4}}) - rectVBO:Upload({ - - minX,minY, minU, minV, --bl - maxX,maxY, maxU, maxV, --tr - minX,maxY, minU, maxV, --tl - maxX,maxY, maxU, maxV, --tr - minX,minY, minU, minV, --bl - maxX,minY, maxU, minV, --br - }) - - - if gldebugannotations then - gl.ObjectLabel(GL_BUFFER, rectVBO:GetID(), name or "rectVBO") - end - - myGL4TexRectVAO = gl.GetVAO() - if myGL4TexRectVAO == nil then return nil end - myGL4TexRectVAO:AttachVertexBuffer(rectVBO) - return myGL4TexRectVAO -end - -return { - makeInstanceVBOTable = makeInstanceVBOTable, - clearInstanceTable = clearInstanceTable, - makeVAOandAttach = makeVAOandAttach, - locateInvalidUnits = locateInvalidUnits, - pushElementInstance = pushElementInstance, - popElementInstance = popElementInstance, - getElementInstanceData = getElementInstanceData, - uploadAllElements = uploadAllElements, - uploadElementRange = uploadElementRange, - compactInstanceVBO = compactInstanceVBO, - drawInstanceVBO = drawInstanceVBO, - makeCircleVBO = makeCircleVBO, - makePlaneVBO = makePlaneVBO, - makePlaneIndexVBO = makePlaneIndexVBO, - makePointVBO = makePointVBO, - makeRectVBO = makeRectVBO, - makeRectIndexVBO = makeRectIndexVBO, - makeConeVBO = makeConeVBO, - makeCylinderVBO = makeCylinderVBO, - makeBoxVBO = makeBoxVBO, - makeSphereVBO = makeSphereVBO, - MakeTexRectVAO = MakeTexRectVAO, -} - -end)() -local buildProgresses,uniformCache={},{} -local spGetUnitHealth,glSetUnitBufferUniforms=Spring.GetUnitHealth,gl.SetUnitBufferUniforms -local function originalBuildAdded(objectID) - local health, maxHealth, paralyzeDamage, capture, build = spGetUnitHealth(objectID) - if health then - uniformCache[1] = ((build < 1) and build) or -1 - glSetUnitBufferUniforms(objectID, uniformCache, 0) -- buildprogress (0.x) - if build < 1 then buildProgresses[objectID] = build end - - --uniformCache[1] = spGetUnitHeight(objectID) - --glSetUnitBufferUniforms(objectID, uniformCache, 11) -- height is 11 (2.w) - end -end -local function originalBuildUpdated() - for unitID, buildProgress in pairs(buildProgresses) do - local health, maxHealth, paralyzeDamage, capture, build = spGetUnitHealth(unitID) - if health and build ~= buildProgress then - uniformCache[1] = ((build < 1) and build) or -1 - gl.SetUnitBufferUniforms(unitID, uniformCache, 0) -- buildprogress (0.x) - if build < 1 then - buildProgresses[unitID] = build - else - buildProgresses[unitID] = nil - end - end - end -end -local function originalBuildFinished(unitID) - gl.SetUnitBufferUniforms(unitID, {-1}, 0) -- set build progress to built - buildProgresses[unitID] = nil -end -local tracker=(function()local widget={} -local widget = widget ---@type Widget - -function widget:GetInfo() - return { - name = "API Unit Tracker DEVMODE GL4", - desc = "Manages alliedunitslist, visibleunitslist", - author = "Beherith", - date = "2022.02.18", - license = "GNU GPL, v2 or later", - layer = -828888, - handler = true, - enabled = true, - depends = {'gl4'} - } -end - - --- Localized Spring API for performance -local spGetGameFrame = Spring.GetGameFrame -local spGetMyTeamID = Spring.GetMyTeamID -local spGetMyAllyTeamID = Spring.GetMyAllyTeamID -local spEcho = Spring.Echo -local spGetAllUnits = Spring.GetAllUnits -local spGetSpectatingState = Spring.GetSpectatingState - -local debuglevel = 0 --- debuglevel 0 is no debugging --- debuglevel 1 is show warnings for stuff periodicly and make self crash --- debuglevel 2 is verbose --- debuglevel 3 is super verbose mode - -local debugdrawvisible = false -local L_DEPRECATED = LOG.DEPRECATED --- This widget's job is to provide a common interface for GL4 drawing widgets, that rely on having visible units present --- Widget draw classes: --- widgets that draw stuff for all visible units (trivial case) --- widgets that only draw for allies, turn into widgets that draw for all once you enter specfullview - -- which is pretty much just sensor ranges los - -- rank icons - -- flank icons - --- TODO: --- filter decoration unitDefIDs, but not gaia (neutrals) -- done --- do taken/given correctly by add-remove -- done --- the callins should all pass unitID, unitDefID, and unitTeam (note the issues with taken unitteams!) --- remove crashing aircraft - not actually needed methinks, since no bugs came up --- BIG ASS TODO: dont reinit when in spec mode! --- -- WE DONT HAVE WIDGETS THAT REMAIN PLAYER ONLY!!!!!!!!!! --- todo: make debug mode an int (verbosity) -- done --- todo: make addunit not call callins on reinit -- done --- todo: make a callout or a WG table entry -- yes we need a wg entry --- todo: finalize alliedunit/visibleunit differences -- done --- todo: also pass unitteam, as it must be present! - done --- todo: fix drawdebugvisible to be changeable - done --- todo: test this in singleplayer scenarios, and loaded games! - --- SUPER IMPORTANT: NEVER EVER ADD UNITS TO A VBO TABLE THAT ARE IN unitDefIgnore! --- As the unit tracker api wont track them as actual units, and wont ever remove them either! - - -local alliedUnits = {} -- table of unitID : unitDefID -local alliedUnitsTeam = {} -- table of unitID : unitTeam -local numAlliedUnits = 0 - -local visibleUnits = {} -- table of unitID : unitDefID -local visibleUnitsTeam = {} -- table of unitID : unitTeam -local numVisibleUnits = 0 - -local unitDefIgnore = {} - -local factoryUnitDefIDs = {} -- key unitdefid, internalname - -local lastknownunitpos = {} -- table on unitID to {x,y,z} - -local gameFrame = spGetGameFrame() - -for unitDefID, unitDef in pairs(UnitDefs) do - if unitDef.customParams and unitDef.customParams.nohealthbars then - --unitDefIgnore[unitDefID] = true - end --ignore debug units - if unitDef.isFactory then - factoryUnitDefIDs[unitDefID] = unitDef.name - end - -end - ---- GL4 STUFF --- - -local LuaShader = gl.LuaShader -local InstanceVBOTable = gl.InstanceVBOTable - -local pushElementInstance = InstanceVBOTable.pushElementInstance -local popElementInstance = InstanceVBOTable.popElementInstance - -local unitTrackerVBO = nil -local unitTrackerShader = nil -local luaShaderDir = "LuaUI/Include/" -local texture = "luaui/images/solid.png" - -local function initGL4() - local DrawPrimitiveAtUnit = VFS.Include(luaShaderDir.."DrawPrimitiveAtUnit.lua") - local InitDrawPrimitiveAtUnit = DrawPrimitiveAtUnit.InitDrawPrimitiveAtUnit - local shaderConfig = DrawPrimitiveAtUnit.shaderConfig -- MAKE SURE YOU READ THE SHADERCONFIG TABLE in DrawPrimitiveAtUnit.lua - shaderConfig.TRANSPARENCY = 0.5 - shaderConfig.ANIMATION = 0 - shaderConfig.HEIGHTOFFSET = 3.99 - -- MATCH CUS position as seed to sin, then pass it through geoshader into fragshader - --shaderConfig.POST_VERTEX = "v_parameters.w = max(-0.2, sin(timeInfo.x * 2.0/30.0 + (v_centerpos.x + v_centerpos.z) * 0.1)) + 0.2; // match CUS glow rate" - unitTrackerVBO, unitTrackerShader = InitDrawPrimitiveAtUnit(shaderConfig, "unitTracker") -end - --- speedups -local spGetUnitTeam = Spring.GetUnitTeam -local spGetUnitDefID = Spring.GetUnitDefID -local spGetUnitPosition = Spring.GetUnitPosition -local spValidUnitID = Spring.ValidUnitID -local spGetUnitIsDead = Spring.GetUnitIsDead -local spGetUnitLosState = Spring.GetUnitLosState -local spAreTeamsAllied = Spring.AreTeamsAllied -local spGetUnitHealth = Spring.GetUnitHealth - --- scriptproxies: ---[[ NB: these are proxies, not the actual lua functions currently linked LuaUI-side, - so it is safe to cache them here even if the underlying func changes afterwards ]] -local scriptLuauiVisibleUnitAdded -local scriptLuauiVisibleUnitRemoved -local scriptLuauiVisibleUnitsChanged - -local scriptLuauiAlliedUnitAdded -local scriptLuauiAlliedUnitRemoved -local scriptLuauiAlliedUnitsChanged - -local function Scream(reason, unitID) -- This will pause the game and play some sound to alert anyone in debug mode of issue - --Spring.Debug.TraceFullEcho(nil,nil,nil, reason) - Spring.Debug.TraceEcho('API Unit Tracker error', reason) - if unitID ~= nil then - -- gather as much info as possible about this unitID - local unitDefID = spGetUnitDefID(unitID) - local unitTeam = spGetUnitTeam(unitID) - local ux,uy,uz = spGetUnitPosition(unitID) - spEcho('API Unit Tracker error unitID', unitID, unitDefID and (UnitDefs[unitDefID].name) or "nil", unitTeam, px, pz) - end - if lastknownunitpos[unitID] then - Spring.MarkerAddPoint(lastknownunitpos[unitID][1], lastknownunitpos[unitID][2], lastknownunitpos[unitID][3], lastknownunitpos[unitID][4], true) - end - Spring.Debug.TraceFullEcho() - local unittrackerapinil = nil - unittrackerapinil = unittrackerapinil + 1 -- this intentionally crashes this widget so that it will show up in analytics - if debuglevel >=3 then - Spring.SendCommands({"pause 1"}) - Spring.PlaySoundFile("commanderspawn", 1.0, 'ui') - end -end - -local function alliedUnitsChanged() - if debuglevel >= 2 then Spring.Debug.TraceEcho() end - if Script.LuaUI('AlliedUnitsChanged') then - Script.LuaUI.AlliedUnitsChanged(visibleUnits, numVisibleUnits) - else - if debuglevel > 0 then spEcho("Script.LuaUI.AlliedUnitsChanged() unavailable") end - end -end - -local function alliedUnitsAdd(unitID, unitDefID, unitTeam, silent) - if debuglevel >= 3 then Spring.Debug.TraceEcho(numAlliedUnits) end - if alliedUnits[unitID] then - if debuglevel >= 2 then spEcho("alliedUnitsAdd", "tried to add existing unitID", unitID) end - return - end -- already known - alliedUnits[unitID] = unitDefID - alliedUnitsTeam[unitID] = unitTeam - numAlliedUnits = numAlliedUnits + 1 - if silent then return end - if Script.LuaUI('AlliedUnitAdded') then - Script.LuaUI.AlliedUnitAdded(unitID, unitDefID, unitTeam) - else - if debuglevel >= 1 then spEcho("Script.LuaUI.AlliedUnitAdded() unavailable") end - end - -- call all listeners -end - -local function alliedUnitsRemove(unitID, reason) - if debuglevel >= 3 then Spring.Debug.TraceEcho(numAlliedUnits) end - if alliedUnits[unitID] then - local unitDefID = alliedUnits[unitID] - alliedUnits[unitID] = nil - local unitTeam = alliedUnitsTeam[unitID] - alliedUnitsTeam[unitID] = nil - numAlliedUnits = numAlliedUnits - 1 - -- call all listeners - if Script.LuaUI('AlliedUnitRemoved') then - Script.LuaUI.AlliedUnitRemoved(unitID, unitDefID, unitTeam) - end - else - if debuglevel >= 2 then spEcho("alliedUnitsRemove", "tried to remove non-existing unitID", unitID, reason) end - end -end - -local function GetAlliedUnits() - if debuglevel >= 2 then Spring.Debug.TraceEcho() end - return alliedUnits, numAlliedUnits -end - -local function visibleUnitsChanged() - if debuglevel >=3 then Spring.Debug.TraceEcho() end - if Script.LuaUI('VisibleUnitsChanged') then - Script.LuaUI.VisibleUnitsChanged(visibleUnits, numVisibleUnits) - else - if debuglevel > 0 then spEcho("Script.LuaUI.VisibleUnitsChanged() unavailable") end - end -end - -local instanceVBOCacheTable = { - 96, 32, 8, 8, -- lengthwidthcornerheight - 0, -- teamID - 2, -- how many trianges should we make (2 = cornerrect) - 0, 0, 0, 0, -- the gameFrame (for animations), and any other parameters one might want to add - 0, 1, 0, 1, -- These are our default UV atlas tranformations - 0, 0, 0, 0 -- these are just padding zeros, that will get filled in - } - -local function visibleUnitsAdd(unitID, unitDefID, unitTeam, silent, reason) - if debuglevel >= 3 then Spring.Debug.TraceEcho(numVisibleUnits) end - if visibleUnits[unitID] then -- already known - if debuglevel >= 2 then spEcho("visibleUnitsAdd", "tried to add existing unitID", unitID) end - return - end - visibleUnits[unitID] = unitDefID - visibleUnitsTeam[unitID] = unitTeam - numVisibleUnits = numVisibleUnits + 1 - if debugdrawvisible then - unitTeam = unitTeam or spGetUnitTeam(unitID) or 0 - instanceVBOCacheTable[5] = unitTeam - instanceVBOCacheTable[7] = gameFrame - - pushElementInstance( - unitTrackerVBO, -- push into this Instance VBO Table - instanceVBOCacheTable, - unitID, -- this is the key inside the VBO TAble, - true, -- update existing element - nil, -- noupload, dont use unless you know what you are doing - unitID -- last one should be UNITID? - ) - end - -- call all listeners: - if silent then return end - if Script.LuaUI('VisibleUnitAdded') then - Script.LuaUI.VisibleUnitAdded(unitID, unitDefID, unitTeam, reason) - else - if debuglevel >= 1 then spEcho("Script.LuaUI.VisibleUnitAdded() unavailable") end - end -end - -local function visibleUnitsRemove(unitID, reason) - if debuglevel >= 3 then - Spring.Debug.TraceEcho(numVisibleUnits) - if lastknownunitpos[unitID] then lastknownunitpos[unitID] = nil end - end - if visibleUnits[unitID] then - local unitDefID = visibleUnits[unitID] - visibleUnits[unitID] = nil - local unitTeam = visibleUnitsTeam[unitID] - visibleUnitsTeam[unitID] = nil - numVisibleUnits = numVisibleUnits - 1 - - if debugdrawvisible then - popElementInstance(unitTrackerVBO, unitID) - end - -- call all listeners - if Script.LuaUI('VisibleUnitRemoved') then - Script.LuaUI.VisibleUnitRemoved(unitID, unitDefID, unitTeam, reason) - end - else - if debuglevel >= 2 then spEcho("visibleUnitsRemove", "tried to remove non-existing unitID", unitID, reason) end - end -end - -local function GetVisibleUnits() - if debuglevel >= 2 then Spring.Debug.TraceEcho() end - return visibleUnits, numVisibleUnits -end - -local spec, fullview = spGetSpectatingState() -local myTeamID = spGetMyTeamID() -local myAllyTeamID = spGetMyAllyTeamID() -local myPlayerID = Spring.GetMyPlayerID() - -local function isValidLivingSeenUnit(unitID, unitDefID, verbose) - --[[ - -- This isnt helping - if type(myAllyTeamID) ~= "number" or (type(myAllyTeamID) == "number" and ((myAllyTeamID < 0 ) or (myAllyTeamID > 32))) then - local localMyAllyTeamID = myAllyTeamID - Spring.Debug.TraceFullEcho(nil,nil,nil, "api_unit_tracker_gl4 error on myAllyTeamID") - end - ]]-- - - -- strange, ALL of these will be evaluated, which explains the crash, because according to the evaluation order, - -- unitDef is not nil yet - -- unitID is valid - -- unit - -- SPECTATING SYNTHETIC in that replay from start and /skip 1 DOES THIS SHIT! 20220307_201548_DSDR 4_105.1.1-861-ge8bf8a9 BAR105.sdfz - -- Which is odd, because that commander belongs to petTurtle, who is on the other allyteam anyway, so this shouldnt really ever get called - -- now why that allyteamID is invalid, I dont really know yet, as the allyteamID == 1, which seems sane - - if unitDefID == nil then return false end - if spValidUnitID(unitID) ~= true then return false end - if spGetUnitIsDead(unitID) == true then return false end - if unitDefIgnore[unitDefID] then return false end - if ((not fullview) and (spGetUnitLosState(unitID, myAllyTeamID, true) % 2 == 0)) then return false end - - if debuglevel >= (verbose or 0) then - if unitDefID == nil or - spValidUnitID(unitID) ~= true or - spGetUnitIsDead(unitID) == true or - ((not fullview) and (spGetUnitLosState(unitID, myAllyTeamID, true) % 2 == 0)) or -- outside of LOS - unitDefIgnore[unitDefID] then - if debuglevel >= (verbose or 0) then - Spring.Debug.TraceEcho() - spEcho("not isValidLivingSeenUnit", - 'unitDefID', unitDefID, - 'ValidUnitID', spValidUnitID(unitID), - 'GetUnitIsDead', spGetUnitIsDead(unitID), - 'Ignore', unitDefIgnore[unitDefID], - 'LOSstate', spGetUnitLosState(unitID, myAllyTeamID, true) - ) - end - return false - end - end - - return true -end - - -function widget:UnitCreated(unitID, unitDefID, unitTeam, builderID, reason, silent) -- this was visible at the time - - --[[ - local currentspec, currentfullview = spGetSpectatingState() - local currentAllyTeamID = Spring.GetMyAllyTeamID() - local currentTeamID = spGetMyTeamID() - local currentPlayerID = Spring.GetMyPlayerID() - if true or debuglevel >= 2 then - spEcho("UnitCreated PlayerChanged", - "spec", spec, "->",currentspec, - " fullview:", fullview , "->", currentfullview, - " team:", myTeamID , "->", currentTeamID, - " allyteam:", myAllyTeamID , "->", currentAllyTeamID, - " player:", myPlayerID , "->", currentPlayerID - ) - end - - if gameFrame <= 1000 then - spEcho("UnitCreated Pre-gameFrame", unitID, unitDefID, unitTeam, builderID, reason, silent, gameFrame) - spEcho(UnitDefs[unitDefID].name) - local px, py, pz = Spring.GetUnitPosition(unitID) - spEcho('pos',px, py, pz) - spEcho("Mystate", spec, fullview, myAllyTeamID, myTeamID, myPlayerID ) - end - ]]-- - - if gameFrame <= 0 and not fullview then - local currentAllyTeamID = spGetMyAllyTeamID() - if myAllyTeamID ~= currentAllyTeamID then - widget:PlayerChanged() - end - end - - unitDefID = unitDefID or spGetUnitDefID(unitID) - if debuglevel >= 3 then spEcho("UnitCreated", unitID, unitDefID and UnitDefs[unitDefID].name, unitTeam, reason) end - - if isValidLivingSeenUnit(unitID, unitDefID, 3) == false then return end - - -- Units that are cheated or spawned will fire unitcreated, then unitfinished right after each other - -- In this case, their health is already maxhealth, and their buildprogress is 0. - -- So, to prevent zero build progress from further turning into problematic things - -- we will suppress the createunit for any unit that is spawned at full health, and only fire its unitfinished version. - -- So we are relying on UnitFinished to be called right after this one - -- Sensibly enough, this is not a problem for players, as they see the units only after their LOS status is checked, later in the same gameframe. - -- So spectators, and 'own team' suffers this hit only - local health,maxhealth, paralyzeDamage,captureProgress,buildProgress = spGetUnitHealth(unitID) - if health == maxhealth and buildProgress == 0 then - if debuglevel >= 3 then - spEcho("Skipping visibleUnitsAdd for CreateUnit'ed unit", UnitDefs[unitDefID].name, unitID, unitDefID, unitTeam, builderID, reason, silent) - end - return - end - - -- alliedunits - if spAreTeamsAllied(unitTeam, myTeamID) then - alliedUnitsAdd(unitID, unitDefID, unitTeam, silent) - end - - -- visibleUnits - if visibleUnits[unitID] == nil then - visibleUnitsAdd(unitID, unitDefID, unitTeam, silent, reason) - end -end - -function widget:UnitDestroyed(unitID, unitDefID, unitTeam, attackerID, attackerDefID, attackerTeam, weaponDefID, reason) - if debuglevel >= 3 then - unitDefID = unitDefID or spGetUnitDefID(unitID) - spEcho("UnitDestroyed",unitID, unitDefID and UnitDefs[unitDefID].name, unitTeam, nil, nil, nil, nil, reason) - end - visibleUnitsRemove(unitID, reason or "UnitDestroyed") - alliedUnitsRemove(unitID, reason or "UnitDestroyed") -end - ---function widget:CrashingAircraft(unitID, unitDefID, teamID) - --spEcho("Global:GadgetCrashingAircraft",unitID, unitDefID, teamID) ---end - - ---function widget:UnitDestroyedByTeam(unitID, unitDefID, unitTeam) - --alliedUnitsRemove(unitID) - --visibleUnitsRemove(unitID) ---end - -function widget:UnitFinished(unitID, unitDefID, unitTeam) -- todo, this should probably add-remove a unit - widget:UnitDestroyed(unitID, unitDefID, unitTeam, nil, nil, nil, nil, "UnitFinished") - widget:UnitCreated(unitID, unitDefID, unitTeam, nil, "UnitFinished") - if unitTeam == myTeamID and factoryUnitDefIDs[unitDefID] then - widgetHandler:AddSpadsMessage("UnitFinished:"..tostring(factoryUnitDefIDs[unitDefID])) - end -end - -function widget:UnitTaken(unitID, unitDefID, oldTeam, newTeam) --1. this is only called when one if my units gets captured - widget:UnitDestroyed(unitID, unitDefID, oldTeam, nil, nil, nil, nil, "UnitTaken") - -- not needed, as the unit will call enemyenteredlos, but what if we are spec? - if not fullview then - -- todo, look at this real closely if its even needed! - --widget:UnitCreated(unitID, unitDefID, newTeam, nil, "UnitTaken") - end -end - -function widget:UnitGiven(unitID, unitDefID, newTeam, oldTeam) --2. this is only called when my team captures a unit - widget:UnitDestroyed(unitID, unitDefID, oldTeam, nil, nil, nil, nil, "UnitGiven") -- to ensure that team changes will trigger from this! - widget:UnitCreated(unitID, unitDefID, newTeam, nil, "UnitGiven") -end - --- one of the most difficult test cases here, when the transfer of a unit happens between two other teams (1 and 2, we are 0) --- only the unitenteredlos part gets called for us! --- this is quite a severe problem, as we can see that only the unitenteredlos/radar gets recalled! --- solution: in the api_widget_events gadget, we need to forward this too! - ---[[ -[t=00:04:53.877051][f=0004348] g:UnitTaken, 24007, armacv, 2, 1 -[t=00:04:53.877107][f=0004348] g:UnitEnteredLos, 24007, 1 -[t=00:04:53.877163][f=0004348] w:UnitEnteredLos, 24007, 1 -[t=00:04:53.877198][f=0004348] g:UnitEnteredRadar, 24007, 1 -[t=00:04:53.877213][f=0004348] w:UnitEnteredRadar, 24007, 1 -[t=00:04:53.877228][f=0004348] g:UnitEnteredLos, 24007, 1 -[t=00:04:53.877240][f=0004348] g:UnitEnteredRadar, 24007, 1 -[t=00:04:53.877277][f=0004348] g:UnitGiven, 24007, armacv, 1, 2 -[t=00:04:53.877451][f=0004348] g:UnitIdle, 24007, armacv, 1 -[t=00:04:53.909507][f=0004349] g:UnitLeftLos, 14177, 1 -[t=00:04:53.909535][f=0004349] g:UnitLeftRadar, 14177, 1 -[t=00:04:53.909549][f=0004349] g:UnitLeftLos, 24007, 1 -[t=00:04:53.909562][f=0004349] g:UnitLeftRadar, 24007, 1 -[t=00:04:54.109905][f=0004355] g:UnitCmdDone, 14177, corcom, 1, 130,
,
, 16 -[t=00:04:54.109951][f=0004355] g:UnitIdle, 14177, corcom, 1 -]]-- - - -function widget:UnitEnteredLos(unitID, unitTeam, allyTeam, unitDefID) - if not fullview then - widget:UnitCreated(unitID, unitDefID, unitTeam, nil, "UnitEnteredLos") - end -end - -function widget:UnitLeftLos(unitID, unitTeam, allyTeam, unitDefID) - if not fullview then - widget:UnitDestroyed(unitID, unitDefID, unitTeam, nil, nil, nil, nil, "UnitLeftLos") - end -end - -function widget:GameFrame() - --spEcho("GameFrame", gameFrame, "->", spGetGameFrame()) - gameFrame = spGetGameFrame() - if debuglevel >= 1 then -- here we will scan all units and ensure that they match what we expect - if (debuglevel <= 2) and (math.random() > 0.05 ) then return end -- lower frequency at smaller debug levels - local allunits = spGetAllUnits() - local allunitsTable = {} - for i = 1, #allunits do - local unitID = allunits[i] - if isValidLivingSeenUnit(unitID, spGetUnitDefID(unitID), 3) then - allunitsTable[unitID] = true - end - end - - local cntvisibleunits = 0 - for unitID, unitDefID in pairs(visibleUnits) do - if allunitsTable[unitID] == nil then - Scream("A unitID from visibleUnits is not in allunitstable: " .. tostring(unitID)) - end - - if isValidLivingSeenUnit(unitID, unitDefID, 3) then - cntvisibleunits = cntvisibleunits + 1 - local ux, uy, uz = spGetUnitPosition(unitID) - local unitDefName = UnitDefs[spGetUnitDefID(unitID)].name - if lastknownunitpos[unitID] then - lastknownunitpos[unitID][1] = ux - lastknownunitpos[unitID][2] = uy - lastknownunitpos[unitID][3] = uz - lastknownunitpos[unitID][4] = unitDefName - else - lastknownunitpos[unitID] = {ux,uy,uz, unitDefName} - end - else - isValidLivingSeenUnit(unitID, unitDefID, 1) - Scream("Unit in visibleUnits does not exist", unitID) - end - end - if cntvisibleunits ~= numVisibleUnits then - Scream("cntvisibleunits ~= numVisibleUnits " .. tostring(cntvisibleunits) .. " vs " .. tostring(numVisibleUnits)) - end - - if drawdebugvisible then - InstanceVBOTable.locateInvalidUnits(unitTrackerVBO) - end - - local cntalliedunits = 0 - for unitID, unitDefID in pairs(alliedUnits) do - if allunitsTable[unitID] == nil then - Scream("A unitID from alliedUnits is not in allunitstable: " .. tostring(unitID)) - end - - if isValidLivingSeenUnit(unitID, unitDefID, 3) then - cntalliedunits = cntalliedunits + 1 - else - isValidLivingSeenUnit(unitID, unitDefID, 1) - Scream("Unit in alliedunits does not exist", unitID) - end - end - if cntalliedunits ~= numAlliedUnits then - Scream("cntalliedunits ~= numAlliedUnits " .. tostring(cntalliedunits) .. " vs " .. tostring(numAlliedUnits)) - end - - if debugdrawvisible then - unitTrackerVBO.debug = true - end - end -end - -function widget:DrawWorldPreUnit() - if Spring.IsGUIHidden() then - return - end - - if debugdrawvisible then - -- spEcho("Drawing unitTracker", unitTrackerVBO.usedElements) - if unitTrackerVBO.usedElements > 0 then - gl.Texture(0, texture) - unitTrackerShader:Activate() - unitTrackerShader:SetUniform("iconDistance", 99999) -- pass - unitTrackerShader:SetUniform("addRadius", 0) - gl.DepthTest(true) - gl.DepthMask(false) - unitTrackerVBO.VAO:DrawArrays(GL.POINTS, unitTrackerVBO.usedElements) - unitTrackerShader:Deactivate() - gl.Texture(0, false) - end - end -end - -local function initializeAllUnits() - alliedUnits = {} - alliedUnitsTeam = {} - numAlliedUnits = 0 - - visibleUnits = {} - visibleUnitsTeam = {} - numVisibleUnits = 0 - - if debuglevel >= 2 then - spEcho("initializeAllUnits()", - "spec", spec, - " fullview:", fullview , - " team:", myTeamID , - " allyteam:", myAllyTeamID , - " player:", myPlayerID - ) - end - - if debugdrawvisible then - InstanceVBOTable.clearInstanceTable(unitTrackerVBO) - end - - local allunits = spGetAllUnits() - for i, unitID in pairs (allunits) do - widget:UnitCreated(unitID, spGetUnitDefID(unitID), spGetUnitTeam(unitID), nil, "initializeAllUnits", true) -- silent is true - end - - WG['unittrackerapi'].visibleUnits = visibleUnits - WG['unittrackerapi'].visibleUnitsTeam = visibleUnitsTeam - WG['unittrackerapi'].alliedUnits = alliedUnits - WG['unittrackerapi'].alliedUnitsTeam = alliedUnitsTeam - visibleUnitsChanged() - alliedUnitsChanged() -end - -local function debugapiunittrackerCmd(_, line) - local param = line or "" - if param == 'draw' then - spEcho("Debug mode for API Unit Tracker GL4 set to draw:", not debugdrawvisible) - if debugdrawvisible then - InstanceVBOTable.clearInstanceTable(unitTrackerVBO) - debugdrawvisible = false - else - debugdrawvisible = true - initGL4() - initializeAllUnits() - end - end - if tonumber(param) then - local newdebuglevel = tonumber(param) - if newdebuglevel ~= debuglevel then - spEcho("Debug level for API Unit Tracker GL4 set to:", newdebuglevel) - debuglevel = newdebuglevel - end - end - return true -end - -local function executeCmd(_, line) - local cmd = line or "" - local success, functionize = pcall(loadstring('return function() return {' .. cmd .. '} end')) - if not success then - spEcho("Failed to parse command:", success, cmd) - else - local ok, data = pcall(functionize) - if not ok then - spEcho("Failed to execute command:", ok, cmd) - else - if type(data) == type({}) then - if #data == 1 then - spEcho(data[1]) - elseif #data == 0 then - spEcho("nil") - else - spEcho(data) - end - else - spEcho(data) - end - end - end - return true -end - -local function noreturnexecuteCmd(_, line) - local cmd = line or "" - local success, functionize = pcall(loadstring('return function() ' .. cmd .. ' end')) - if not success then - spEcho("Failed to parse command:", success, cmd) - else - local ok, data = pcall(functionize) - if not ok then - spEcho("Failed to execute command:", ok, cmd) - else - if type(data) == type({}) then - if #data == 1 then - spEcho(data[1]) - elseif #data == 0 then - spEcho("nil") - else - spEcho(data) - end - else - spEcho(data) - end - end - end - return true -end - -local function RegisterTextAction(actionName, handler) - if widgetHandler.AddAction then - widgetHandler:AddAction(actionName, handler, nil, "t") - elseif widgetHandler.actionHandler and widgetHandler.actionHandler.AddAction then - widgetHandler.actionHandler:AddAction(widget, actionName, handler, nil, "t") - end -end - -local function UnregisterTextAction(actionName) - if widgetHandler.RemoveAction then - widgetHandler:RemoveAction(actionName, "t") - elseif widgetHandler.actionHandler and widgetHandler.actionHandler.RemoveAction then - widgetHandler.actionHandler:RemoveAction(widget, actionName) - end -end - -function widget:PlayerChanged(playerID) - -- VERY IMPORTANT NOTE: - -- When starting up a game, and spectating a player (e.g. /spec 2), or clicking on them in playerTV, - -- My allyTeamID and myTeamID BOTH get RESET internally by the engine on game start! - -- and this does NOT result in a playerchanged callin - -- the fullview variable is not changed, however - - local currentspec, currentfullview = spGetSpectatingState() - local currentAllyTeamID = spGetMyAllyTeamID() - local currentTeamID = spGetMyTeamID() - local currentPlayerID = Spring.GetMyPlayerID() - - local reinit = false - - -- testing for visibleUnitsChanged and alliedUnitsChanged - - if debuglevel >= 2 then - spEcho("PlayerChanged", - "spec", spec, "->",currentspec, - " fullview:", fullview , "->", currentfullview, - " team:", myTeamID , "->", currentTeamID, - " allyteam:", myAllyTeamID , "->", currentAllyTeamID, - " player:", myPlayerID , "->", currentPlayerID - ) - end - - -- testing for visible units changed - if (currentspec ~= spec) or -- we change from spec to non spec (I dont think its possible to go from player to non-fullview spec in one go) - (currentfullview ~= fullview) or - ((currentAllyTeamID ~= myAllyTeamID) and not currentspec and not currentfullview) then -- our ALLYteam changes while playing, and we are not in fullview - reinit = true - end - - -- which can happen if we are spec and only want to show for allies what the FUCK - -- WHAT EFFECTS DO WE HAVE THAT ONLY SHOW FOR ALLIES IN sPEC MODE? - - spec = currentspec - fullview = currentfullview - myAllyTeamID = currentAllyTeamID - myTeamID = currentTeamID - myPlayerID = currentPlayerID - - if reinit then initializeAllUnits() end -end - -function widget:GameStart() - local function LobbyInfo() - local test = false - if not test then - if Spring.IsReplay() then return end - if Spring.Utilities.GetPlayerCount() < 2 then return end - if Spring.Utilities.Gametype.IsSinglePlayer == true then return end - end - - local pnl = {a = "a"} - for ct, id in ipairs(Spring.GetPlayerList()) do - local playername, _, spec = Spring.GetPlayerInfo(id, false) - pnl[ct] = playername - if (not test) and spec and (string.find(playername,"[teh]cluster", nil, true) or string.find(playername,"Host[", nil, true) )then - return - end - end - - for j, script in ipairs({"script.txt", "_script.txt"}) do - if VFS.FileExists(script) then - for i, line in ipairs(string.lines(VFS.LoadFile(script))) do - if string.find(string.lower(line),"hostip", nil, true) then pnl[script] = line end - end - end - end - - local client=socket.tcp() - local res, err = client:connect("server4.beyondallreason.info", 8200) - if not res and err ~= "timeout" then - --spEcho("Failure",res,err) - else - local message = "c.telemetry.log_client_event lobby:info " .. string.base64Encode(Json.encode(pnl)).." ZGVhZGJlZWZkZWFkYmVlZmRlYWRiZWVmZGVhZGJlZWY=\n" - client:send(message) - end - client:close() - end - --local succes, res = pcall(LobbyInfo) -end - -function widget:Initialize() - gameFrame = spGetGameFrame() - spec, fullview = spGetSpectatingState() - myTeamID = spGetMyTeamID() - myAllyTeamID = spGetMyAllyTeamID() - myPlayerID = Spring.GetMyPlayerID() - - scriptLuauiVisibleUnitAdded = Script.LuaUI.VisibleUnitAdded - scriptLuauiVisibleUnitRemoved = Script.LuaUI.VisibleUnitRemoved - scriptLuauiVisibleUnitsChanged = Script.LuaUI.VisibleUnitChanged - - scriptLuauiAlliedUnitAdded = Script.LuaUI.AlliedUnitAdded - scriptLuauiAlliedUnitRemoved = Script.LuaUI.AlliedUnitRemoved - scriptLuauiAlliedUnitsChanged = Script.LuaUI.AlliedUnitChanged - - - if debugdrawvisible then - initGL4() - end - - WG['unittrackerapi'] = {} - WG['unittrackerapi'].visibleUnits = visibleUnits - WG['unittrackerapi'].visibleUnitsTeam = visibleUnitsTeam - WG['unittrackerapi'].alliedUnits = alliedUnits - WG['unittrackerapi'].alliedUnitsTeam = alliedUnitsTeam - initializeAllUnits() - widgetHandler:RegisterGlobal('GadgetCrashingAircraft1', GadgetCrashingAircraft) - RegisterTextAction("debugapiunittracker", debugapiunittrackerCmd) - RegisterTextAction("execute", executeCmd) - RegisterTextAction("noreturnexecute", noreturnexecuteCmd) -end - - -local iHaveDesynced = false --- Example console line: --- [t=00:01:41.862230][f=0011049] Sync error for UnnamedPlayer in frame 11044 (got 5537e3ca, correct is cc130165) -local syncerrorpattern = "Sync error for ([%w%[%]_]+) in frame (%d+) %(got (%x+), correct is (%x+)%)" - -function widget:AddConsoleLine(lines, priority) - if priority and priority == L_DEPRECATED then return end - --spEcho(lines) - if iHaveDesynced then return end - local username, frameNumber, gotChecksum, correctChecksum = lines:match(syncerrorpattern) - if username and frameNumber and gotChecksum and correctChecksum then - local myPlayerName = Spring.GetPlayerInfo(Spring.GetMyPlayerID()) - if myPlayerName == username then - -- Yes, we have desynced, time to send a LuaUIMsg to notify the server - -- desyncee, gameID, frame, gameversion, engine version, map, chobby version? - local jsondict = { - eventtype = "syncerror", - username = username, -- desyncee - lobbyName = tostring(Spring.GetMenuName and Spring.GetMenuName()), -- this returns rapid://byar-chobby:test, which is completely useless - gameVersion = tostring(Game.gameVersion), -- this better not be the rapid tag - engineVersion = tostring(Engine.versionFull), -- full complete engine version string - mapName = tostring(Game.mapName), -- full map name - gameID = tostring(Game.gameID and Game.gameID or Spring.GetGameRulesParam("GameID")), -- gameID parameter, not the same as server_match_id, we will match that in teiserver - frame = frameNumber, -- the frame where it happened. - gotChecksum = gotChecksum, - correctChecksum = correctChecksum, - } - --spEcho(jsondict) - - local complex_match_event = string.format("complex-match-event:%s", string.base64Encode(Json.encode(jsondict))) - - -- We will be forwarding this as a complex event: - -- sayPrivate complex-match-event <67> - -- !sendLobby SAYPRIVATE AutohostMonitor 'complex-match-event <[teh]Beherith> <67> ' - Spring.SendLuaUIMsg(complex_match_event) - - -- then remove ourselves, no point to keep running after the first desync is detected - iHaveDesynced = true - end - end -end - - -function widget:Shutdown() - -- ok this is quite sensitive, in order to prevent taking down the rest of the world with it - -- we need to clear the visible units, and call the respective callins - alliedUnits = {} - alliedUnitsTeam = {} - numAlliedUnits = 0 - visibleUnits = {} - visibleUnitsTeam = {} - numVisibleUnits = 0 - - - WG['unittrackerapi'].visibleUnits = visibleUnits - WG['unittrackerapi'].visibleUnitsTeam = visibleUnitsTeam - WG['unittrackerapi'].alliedUnits = alliedUnits - WG['unittrackerapi'].alliedUnitsTeam = alliedUnitsTeam - visibleUnitsChanged() - alliedUnitsChanged() - - widgetHandler:DeregisterGlobal('GadgetCrashingAircraft1') - UnregisterTextAction("debugapiunittracker") - UnregisterTextAction("execute") - UnregisterTextAction("noreturnexecute") -end - -return widget end)() -local bars=(function()local widget={} -local widget = widget ---@type Widget - -function widget:GetInfo() - return { - name = "Health Bars GL4", - desc = "Yes this healthbars, just gl4", - author = "Beherith", - date = "October 2019", - license = "GNU GPL v2", - layer = -10, - enabled = true - } -end - - --- Localized functions for performance -local mathMin = math.min - --- Localized Spring API for performance -local spGetUnitDefID = Spring.GetUnitDefID -local spGetUnitHealth = Spring.GetUnitHealth -local spGetUnitPosition = Spring.GetUnitPosition -local spGetGameFrame = Spring.GetGameFrame -local spEcho = Spring.Echo -local spGetUnitTeam = Spring.GetUnitTeam -local spGetSpectatingState = Spring.GetSpectatingState -local spGetFeaturePosition = Spring.GetFeaturePosition -local spIsPosInLos = Spring.IsPosInLos - --- wellity wellity the time has come, and yes, this is design documentation --- what can we do with 64 verts per healthbars? - -- 9 verts bg - -- 9 verts fg - -- 20 verts for numbers like an asshole --- fade bars in and out based on last modified times of values? --- what info do we need outputted from GS? --- for fg/bg --- color? is that it? - --- for numbers: --- uv coords --- we also need one extra for text - no bueno for translations tho - --- use billboards, --- THE TYPES OF UNIT BARS: - -- timer based, all these need a start and (predicted) end time. - -- EMP time left - -- 3 floats, start, end, empdamage - -- needs update on every fucking unitdamaged callin - -- handle cases where uni is empd outside of view? - - - -- reload - -- 2 floats, lastshot, nextshot - -- time left in construction - -- this is a special hybrid bar added on unitcreated, and removed on unitfinished... - -- 2 floats, buildpct, eta? (eta could get liveupdated cause unitfinished?) - -- static percentage based: - -- health -- - -- emp damage - -- capture - -- stockpile build progress - -- shield - --- stuff that needs to occupy a contiguouis stretch in the user uniforms: - --- spGetUnitHealth ( number unitID ) --- return: nil | number health, number maxHealth, number paralyzeDamage, number captureProgress, number buildProgress - --- local shieldOn, shieldPower = GetUnitShieldState(unitID) --- numStockpiled, numStockpileQued, stockpileBuild = GetUnitStockpile(unitID) --- local stunned = GetUnitIsStunned(unitID) --- local _, reloaded, reloadFrame = GetUnitWeaponState(unitID, ci.primaryWeapon) - --- Features can only have: Health, reclaim and resurrectprogress - in fact they should be completely separate bar ids, and all of them are static percentage based - -- feature resurrect -- this list must be handled in-widget, maintained and updated accordingly for in-los features. - -- advanced concepts include priority watch lists of features actively being resurrected (or hooking into allowcommand, but that is garbage!) - - -- feature health - -- feature reclaim --- AllowFeatureBuildStep() called when wreck is resurrected - --- Spring.GetFeatureHealth ( number featureID ) ---return: nil | number health, number maxHealth, number resurrectProgress ---Spring.GetFeatureResources ( number featureID ) ---return: nil | number RemainingMetal, number maxMetal, number RemainingEnergy, number maxEnergy, number reclaimLeft, number reclaimTime - - - --- the vertex shader: - -- Job of the VS: - -- read the data and position - -- identify if the bar needs to be drawn based on : - -- visibility of unit - -- distance of bar - -- value of the bar - -- the colormap of the bar needs to be interpolated here from a fixed define string? - --[[ -- https://community.khronos.org/t/constant-vec3-array-no-go/60184/8 - vec3 MyArray[4]=vec3[4]( - vec3(1.5,34.4,3.2), - vec3(1.6,34.1,1.2), - vec3(18.981777,6.258294,-27.141813), - vec3(1.0,3.0,1.0) - ); - ]]-- - -- - -- VS input: - -- uint barindex - -- this is the index of how manyeth bar it is in the list, where 0 is always health. and if an additional bar is needed, then increment accordingly - -- uint bartype - -- this is for where to get the colortable and 'icon' from - -- float unitheight - -- for correct offsetting - -- uint uniformSSBOloc - -- this is what uniform offset to read, 0 will be health? - -- float2 timers - -- this is for setting the time from which to calculate the timer based bars, set to 0 for no timer, start and end time maybe to calc diff? - -- uint unitID - -- or a featureID for features, those will be a separate list, but use hopefully the same shader. - -- - -- VS output - -- unit position - -- bar position - -- bar 'scale' - -- bar basecolor - -- bar colormap vec3[3] - -- bar value - -- bar type - -- bar alpha - -- corner size - - --- Geometry shader: - -- should only output anything if the bar actually needs to be drawn --- Job of the geometry shader: - -- take the VS output params, and create the following bar components: - -- At furthest detail: - -- background which is same size as bar - -- the bar itself - -- 2*4 vertices - -- midrange: - -- a nicer 6 triangle cornered bar background - -- a cornered bar foreground - -- 2*8 vertices - -- closeup: - -- add the percentage value to the left of the bar - -- this is 4*4 vertices - -- full closeness - -- also write the 'name' of the bar type - -- GS output per vertex: - -- position on screen - -- Z depth (somehow with emission ordering from back to front? - -- UV coordinates -- this could get nasty quickly - -- vertex color - -- solid or textured - --- Fragment shader: - -- if solid, interpolate vertex color, and straight up draw it - -- if uv mapped, sample the texture and draw it - --- atlas plans: - -- 512 x 512 atlas - -- 16 rows in it - -- each number from 0 to 9, '.' % and space (the 15th.) 's', ':' - -- the text? - -- overlay textures for bars - -- symbol glyphs - --- TODO --- 1. enemy paralyzed is not visible? --- enemy comms and fusions health? hide the ones which should be hidden! --- check for invalidness on addbars -- dont --- better maintenance of bartypes and watch lists --- feature bars fade out faster -- done --- CLOAKED UNITSES -- done --- Healthbars color correction -- done --- Hide buildbars when at full hp - or convert them to build bars? -- done --- todo some tex filtering issues on healthbar tops and bottoms :/ -- done --- TODO: some GAIA shit? -- done --- TODO: enemy comms and fus and decoy fus should not get healthbars! -- done --- TODO: allies dont get reload bars? Do Specs see them? -- done (it was f'ed up previously) --- TODO: correct draw order (after highlightunit) -- done --- TODO: when reiniting feature bars, also check for resurrect/reclaim status -- done, just dont reinit them on playerchanged, no point! - -- now this is problematic, as the gadget only sends us an event on first reclaim event - -- we must assume that all features - -- feature bars dont actually need a reinit, now do they? --- TODO: make numbers, glyphs optional? -- done, but untested - ---/luarules benchmark corak armpw 100 10 2000 - -local drawWhenGuiHidden = false - -local healthbartexture = "LuaUI/Images/healtbars_exo4.tga" - --- a little explanation for 'bartype' --- 0: default percentage progress bar --- 1: timer based full textured bar, with time left being read from unitformindex --- 2: timer based progress bar, with start and end times reading time left from uniformindex, uniformindex + 1 and timeInfo.x --- 3: default percentage bar with overlayed texture progression --- 5: The stockpile bar, nasty as hell but whatevs, it - --- TODO: should be a freaking bitmask instead --- bit 0: use overlay texture false/true --- bit 1: show glyph icon --- bit 2: use percentage style display --- bit 3: use timeleft style display (2 and 3 mutually exclusive!) --- bit 4: use integernumber style display (stockpile) --- bit 5: get progress from nowtime-uniform2 / (uniform3 - uniform2) --- bit 6: flash bar at 1hz -local bitUseOverlay = 1 -local bitShowGlyph = 2 -local bitPercentage = 4 -local bitTimeLeft = 8 -local bitIntegerNumber = 16 -local bitGetProgress = 32 -local bitFlashBar = 64 -local bitColorCorrect = 128 - --- unit uniform index map: --- 0: building --- 1: NONE , --- 2: shield/reloadstart/stockpile --- 3: reloadend? --- 4: emp damage /paralyze --- 5: capture - --- Feature uniform index map: --- 0: NONE --- 1: resurrect --- 2: reclaim - -local barTypeMap = { -- WHERE SHOULD WE STORE THE FUCKING COLORS? - health = { - mincolor = {1.0, 0.0, 0.0, 1.0}, - maxcolor = {0.0, 1.0, 0.0, 1.0}, - --bartype = 0, - bartype = bitPercentage + bitColorCorrect, - hidethreshold = 0.99, - uniformindex = 32, -- if its >20, then its health/maxhealth - uvoffset = 0.0625, -- the X offset of the icon for this bar - }, - shield = { - mincolor = {0.15, 0.4, 0.4, 1.0}, - maxcolor = {0.3, 0.8, 0.8, 1.0}, - --bartype = 3, - bartype = bitShowGlyph + bitUseOverlay + bitPercentage, - hidethreshold = 0.99, - uniformindex = 2, -- if its >20, then its health/maxhealth - uvoffset = 0.3125, -- the X offset of the icon for this bar - }, - capture = { - mincolor = {0.5, 0.25, 0.0, 1.0}, - maxcolor = {1.0, 0.5, 0.0, 1.0}, - --bartype = 3, - bartype = bitShowGlyph + bitUseOverlay + bitPercentage, - hidethreshold = 0.99, - uniformindex = 5, -- if its >20, then its health/maxhealth - uvoffset = 0.1875, -- the X offset of the icon for this bar - }, - stockpile = { - mincolor = {0.1, 0.1, 0.1, 1.0}, - maxcolor = {0.1, 0.1, 0.1, 1.0}, - --bartype = 5, - bartype = bitShowGlyph + bitUseOverlay + bitIntegerNumber, - hidethreshold = 1.99, - uniformindex = 2, -- if its >20, then its health/maxhealth - uvoffset = 0.4375, -- the X offset of the icon for this bar - }, - emp_damage = { - mincolor = {0.4, 0.4, 0.8, 1.0}, - maxcolor = {0.6, 0.6, 1.0, 1.0}, - --bartype = 3, - bartype = bitShowGlyph + bitUseOverlay + bitPercentage, - hidethreshold = 0.99, - uniformindex = 4, -- if its >20, then its health/maxhealth - uvoffset = 0.5625, -- the X offset of the icon for this bar - }, - reload = { - mincolor = {0.03, 0.4, 0.4, 1.0}, - maxcolor = {0.05, 0.6, 0.6, 1.0}, - --bartype = 2, - bartype = bitShowGlyph + bitUseOverlay + bitGetProgress, - hidethreshold = 0.99, - uniformindex = 2, -- and 3! - uvoffset = 0.6875, -- the X offset of the icon for this bar - }, - building = { - mincolor = {1.0, 1.0, 1.0, 1.0}, - maxcolor = {1.0, 1.0, 1.0, 1.0}, - --bartype = 3, - bartype = bitShowGlyph + bitUseOverlay + bitPercentage, - hidethreshold = 0.999, - uniformindex = 0, -- if its >20, then its health/maxhealth - uvoffset = 0.9375, -- the X offset of the icon for this bar - }, - paralyzed = { - mincolor = {0.6, 0.6, 1.0, 1.0}, - maxcolor = {0.6, 0.6, 1.0, 1.0}, - --bartype = 1, - bartype = bitShowGlyph + bitUseOverlay + bitFlashBar + bitTimeLeft, - hidethreshold = 0.99, - uniformindex = 4, -- if its >20, then its health/maxhealth - uvoffset = 0.8125, -- the X offset of the icon for this bar - }, - featurehealth = { - mincolor = {0.25, 0.25, 0.25, 1.0}, - maxcolor = {0.65, 0.65, 0.65, 1.0}, - --bartype = 0, - bartype = bitShowGlyph + bitPercentage, - hidethreshold = 0.99, - uniformindex = 33, -- if its >20, then its health/maxhealth - uvoffset = 0.125, -- the X offset of the icon for this bar - }, - featurereclaim = { - mincolor = {0.00, 1.00, 0.00, 1.0}, - maxcolor = {0.85, 1.00, 0.85, 1.0}, - --bartype = 0, - bartype = bitShowGlyph + bitPercentage, - hidethreshold = 0.99, - uniformindex = 2, -- if its >20, then its health/maxhealth - uvoffset = 0.5, -- the X offset of the icon for this bar - }, - featureresurrect = { - mincolor = {0.75, 0.15, 0.75, 1.0}, - maxcolor = {1.0, 0.2, 1.0, 1.0}, - --bartype = 0, - bartype = bitShowGlyph + bitPercentage, - hidethreshold = 0.99, - uniformindex = 1, -- if its >20, then its health/maxhealth - uvoffset = 0.25, -- the X offset of the icon for this bar - }, -} - -for barname, bt in pairs(barTypeMap) do - local cache = {} - for i=1,20 do cache[i] = 0 end - - --cache[1] = unitDefHeights[unitDefID] + additionalheightaboveunit * effectiveScale -- height - --cache[2] = effectiveScale - --cache[3] = 0.0 -- unused - cache[4] = bt.uvoffset -- glyph uv offset - - cache[5] = bt.bartype -- bartype int - --cache[6] = unitBars[unitID] - 1 -- bar index (how manyeth per unit) - cache[7] = bt.uniformindex -- ssbo location offset (> 20 for health) - - cache[9] = bt.mincolor[1] - cache[10] = bt.mincolor[2] - cache[11] = bt.mincolor[3] - cache[12] = bt.mincolor[4] - - cache[13] = bt.maxcolor[1] - cache[14] = bt.maxcolor[2] - cache[15] = bt.maxcolor[3] - cache[16] = bt.maxcolor[4] - - bt['cache'] = cache -end - - --------------------------------------------------------------------------------- --------------------------------------------------------------------------------- - -local spec, fullview = spGetSpectatingState() -local myAllyTeamID = Spring.GetMyAllyTeamID() -local GetUnitWeaponState = Spring.GetUnitWeaponState - -local chobbyInterface - -local unitDefIgnore = {} -- commanders! -local unitDefhasShield = {} -- value is shield max power -local unitDefReactiveArmor = {} -- value is armor health -local unitDefCanStockpile = {} -- 0/1? -local unitDefHeights = {} -- maps unitDefs to height -local unitDefHideDamage = {} -local unitDefPrimaryWeapon = {} -- the index for reloadable weapon on unitdef weapons - -local unitBars = {} -- we need this additional table of {[unitID] = {barhealth, barrez, barreclaim}} -local unitCaptureWatch = {} -local unitShieldWatch = {} -- maps unitID to last shield value -local unitReactiveArmorWatch = {} -local unitEmpDamagedWatch = {} -local unitParalyzedWatch = {} -local unitStockPileWatch = {} -local unitReloadWatch = {} - -local featureDefHeights = {} -- maps FeatureDefs to height -local featureBars = {} -- we need this additional table of {[featureid] = {barhealth, barrez, barreclaim}} - ---local empDecline = 1 / 40 --magic -local minReloadTime = 4 -- weapons reloading slower than this willget bars - -local featureHealthVBO -local featureResurrectVBO -local featureReclaimVBO - -local barScale = 1 -- Option 'healthbarsscale' -local variableBarSizes = true -- Option 'healthbarsvariable' - ---local resurrectableFeaturesFast = {} -- value is this is for keeping an eye on resurrectable features, maybe store resurrect progress here? ---local resurrectableFeaturesSlow = {} -- this is for keeping an eye on resurrectable features, maybe store resurrect progress here? ---local reclaimableFeaturesSlow = {} -- for faster updates of features being reclaimed/rezzed ---local reclaimableFeaturesFast = {} -- for faster updates of features being reclaimed/rezzed - --------------------------------------------------------------------------------- --- GL4 Backend stuff: -local healthBarVBO = nil -local healthBarShader = nil - -local LuaShader = gl.LuaShader -local InstanceVBOTable = gl.InstanceVBOTable - ---local uploadAllElements = InstanceVBOTable.uploadAllElements -local pushElementInstance = InstanceVBOTable.pushElementInstance -local popElementInstance = InstanceVBOTable.popElementInstance - --------------------- configurables ----------------------- -local additionalheightaboveunit = 24 --16? -local featureHealthDistMult = 7 -- how many times closer features have to be for their bars to show -local featureReclaimDistMult = 2 -- how many times closer features have to be for their bars to show -local featureResurrectDistMult = 1 -- how many times closer features have to be for their bars to show -local glphydistmult = 3.5 -- how much closer than BARFADEEND the bar has to be to start drawing numbers/icons. Numbers closer to 1 will make the glyphs be drawn earlier, high numbers will only shows glyphs when zoomed in hard. -local glyphdistmultfeatures = 1.8 -- how much closer than BARFADEEND the bar has to be to start drawing numbers/icons - - -local unitDefSizeMultipliers = {} -- table of unitdefID to a size mult (default 1.0) to override sizing of bars per unitdef -local skipGlyphsNumbers = 0.0 -- 0.0 is draw glyph and number, 1.0 means only numbers, 2.0 means only bars, - -local debugmode = false - -local barHeight = 0.9 -local shaderConfig = { -- these are our shader defines - HEIGHTOFFSET = 3, -- Additional height added to everything - CLIPTOLERANCE = 1.1, -- At 1.0 it wont draw at units just outside of view (may pop in), 1.1 is a good safe amount - MAXVERTICES = 64, -- The max number of vertices we can emit, make sure this is consistent with what you are trying to draw (tris 3, quads 4, corneredrect 8, circle 64 - CLIPTOLERANCE = 1.2, - BARWIDTH = 2.56, - BARHEIGHT = barHeight, - BGBOTTOMCOLOR = "vec4(0.25, 0.25, 0.25, 0.8)", - BGTOPCOLOR = "vec4(0.1, 0.1, 0.1, 0.8)", - BARSCALE = 4.0, - PERCENT_VISIBILITY_MAX = 0.99, - TIMER_VISIBILITY_MIN = 0.0, - BARSTEP = 10, -- pixels to downshift per new bar - BOTTOMDARKENFACTOR = 0.5, - BARFADESTART = 3200, - BARFADEEND = 3800, - ATLASSTEP = 0.0625, - MINALPHA = 0.2, -} -shaderConfig.BARCORNER = 0.06 + (shaderConfig.BARHEIGHT / 9) -shaderConfig.SMALLERCORNER = shaderConfig.BARCORNER * 0.6 - -if debugmode then - shaderConfig.DEBUGSHOW = 1 -- comment this to always show all bars -end - -local vsSrcPath = "LuaUI/Shaders/HealthbarsGL4.vert.glsl" -local gsSrcPath = "LuaUI/Shaders/HealthbarsGL4.geom.glsl" -local fsSrcPath = "LuaUI/Shaders/HealthbarsGL4.frag.glsl" -local fallbackVsSrcPath = "LuaUI/Shaders/HealthbarsGL4_nogs.vert.glsl" -local fallbackFsSrcPath = "LuaUI/Shaders/HealthbarsGL4_nogs.frag.glsl" - -local useGeometryShader = LuaShader.isGeometryShaderSupported - -local unitQuadVBO - -local shaderSourceCache = { - vssrcpath = vsSrcPath, - fssrcpath = fsSrcPath, - gssrcpath = gsSrcPath, - shaderName = "Health Bars Shader GL4", - uniformInt = { - healthbartexture = 0; - }, - uniformFloat = { - --addRadius = 1, - iconDistance = 27, - cameraDistanceMult = 1.0, - cameraDistanceMultGlyph = 4.0, - skipGlyphsNumbers = 0.0, - globalSizeMult = 1.0, - }, - shaderConfig = shaderConfig, - } - -local fallbackShaderSourceCache = { - vssrcpath = fallbackVsSrcPath, - fssrcpath = fallbackFsSrcPath, - shaderName = "Health Bars Shader GL4 (NoGS)", - uniformInt = { - healthbartexture = 0; - }, - uniformFloat = { - iconDistance = 27, - cameraDistanceMult = 1.0, - cameraDistanceMultGlyph = 4.0, - skipGlyphsNumbers = 0.0, - globalSizeMult = 1.0, - }, - shaderConfig = shaderConfig, - } - - --- Walk through unitdefs for the stuff we need: -for udefID, unitDef in pairs(UnitDefs) do - if unitDef.customParams and unitDef.customParams.nohealthbars then - unitDefIgnore[udefID] = true - end --ignore debug units - - local shieldDefID = unitDef.shieldWeaponDef - local shieldPower = ((shieldDefID) and (WeaponDefs[shieldDefID].shieldPower)) or (-1) - if shieldPower > 1 then unitDefhasShield[udefID] = shieldPower - --spEcho("HAS SHIELD") - end - - local weapons = unitDef.weapons - local reloadTime = unitDef.reloadTime or 0 - local primaryWeapon = 1 - for i = 1, #weapons do - local WeaponDef = WeaponDefs[weapons[i].weaponDef] - if WeaponDef and WeaponDef.reload and WeaponDef.reload > reloadTime then - reloadTime = WeaponDef.reload - primaryWeapon = i - end - end - unitDefHeights[udefID] = unitDef.height - unitDefSizeMultipliers[udefID] = mathMin(1.45, math.max(0.85, (Spring.GetUnitDefDimensions(udefID).radius / 150) + mathMin(0.6, unitDef.power / 4000))) + mathMin(0.6, unitDef.health / 22000) - if unitDef.canStockpile then unitDefCanStockpile[udefID] = unitDef.canStockpile end - if reloadTime and reloadTime > minReloadTime then - if debugmode then spEcho("Unit with watched reload time:", unitDef.name, reloadTime, minReloadTime) end - unitDefPrimaryWeapon[udefID] = primaryWeapon - end - if unitDef.hideDamage == true then - unitDefHideDamage[udefID] = true - end - - if not unitDefhasShield[udefID] and not unitDef.hideDamage then - if unitDef.customParams.reactive_armor_health and unitDef.customParams.reactive_armor_restore then - unitDefReactiveArmor[udefID] = tonumber(unitDef.customParams.reactive_armor_health) - end - end -end - -for fdefID, featureDef in pairs(FeatureDefs) do - --spEcho(featureDef.name, featureDef.height) - featureDefHeights[fdefID] = featureDef.height or 32 -end - - -local function goodbye(reason) - spEcho("Healthbars GL4 widget exiting with reason: "..reason) - widgetHandler:RemoveWidget() -end - - - -local function initializeInstanceVBOTable(myName, usesFeatures) - local newVBOTable - local layout - local unitIDAttribID - if useGeometryShader then - layout = { - {id = 0, name = 'height_timers', size = 4}, - {id = 1, name = 'type_index_ssboloc', size = 4, type = GL.UNSIGNED_INT}, - {id = 2, name = 'startcolor', size = 4}, - {id = 3, name = 'endcolor', size = 4}, - {id = 4, name = 'instData', size = 4, type = GL.UNSIGNED_INT}, - } - unitIDAttribID = 4 - else - layout = { - {id = 2, name = 'height_timers', size = 4}, - {id = 3, name = 'type_index_ssboloc', size = 4, type = GL.UNSIGNED_INT}, - {id = 4, name = 'startcolor', size = 4}, - {id = 5, name = 'endcolor', size = 4}, - {id = 6, name = 'instData', size = 4, type = GL.UNSIGNED_INT}, - } - unitIDAttribID = 6 - end - newVBOTable = InstanceVBOTable.makeInstanceVBOTable( - layout, - 256, -- maxelements - myName, -- name - unitIDAttribID -- unitIDattribID (instData) - ) - if newVBOTable == nil then goodbye("Failed to create " .. myName) end - - if useGeometryShader then - local newVAO = gl.GetVAO() - newVAO:AttachVertexBuffer(newVBOTable.instanceVBO) - newVBOTable.VAO = newVAO - else - newVBOTable.VAO = InstanceVBOTable.makeVAOandAttach(unitQuadVBO, newVBOTable.instanceVBO) - end - if usesFeatures then newVBOTable.featureIDs = true end - return newVBOTable -end - - -local function initGL4() - -- Prefer geometry shader path when it actually compiles. This avoids false - -- negatives from capability detection on some Linux/AMD driver stacks. - healthBarShader = LuaShader.CheckShaderUpdates(shaderSourceCache) - useGeometryShader = (healthBarShader ~= nil) - - if not useGeometryShader then - -- A simple quad used by the non-GS path. - unitQuadVBO = gl.GetVBO(GL.ARRAY_BUFFER, false) - unitQuadVBO:Define(4, { - {id = 0, name = 'quadPos', size = 2}, - }) - unitQuadVBO:Upload({ - 0.0, 0.0, - 1.0, 0.0, - 0.0, 1.0, - 1.0, 1.0, - }) - - healthBarShader = LuaShader.CheckShaderUpdates(fallbackShaderSourceCache) - end - - if not healthBarShader then goodbye("Failed to compile health bars GL4 ") end - - healthBarVBO = initializeInstanceVBOTable("healthBarVBO", false) - - featureHealthVBO = initializeInstanceVBOTable("featureHealthVBO", true) -- we need separate ones for all feature health bars, as they seem to be - featureResurrectVBO = initializeInstanceVBOTable("featureResurrectVBO", true) - featureReclaimVBO = initializeInstanceVBOTable("featureReclaimVBO", true) - - if debugmode then - healthBarVBO.debug = true - end -end - --------------------------------------------------------------------------------- --------------------------------------------------------------------------------- - -local function addBarForUnit(unitID, unitDefID, barname, reason) - --Spring.Debug.TraceFullEcho() - if debugmode then Spring.Debug.TraceEcho(unitBars[unitID]) end - --spEcho("Caller1:", tostring()".name), "caller2:", tostring(debug.getinfo(3).name)) - unitDefID = unitDefID or spGetUnitDefID(unitID) - - -- Why? Because adding additional bars can be triggered from outside of unit tracker api - -- like EMP, where we assume that unit is already visible, however - -- debug units are not present in unittracker api! - if (unitDefID == nil) or unitDefIgnore[unitDefID] then return nil end - - local bt = barTypeMap[barname] - --if cnt == 1 then bt = barTypeMap.building end - --if cnt == 2 then bt = barTypeMap.reload end - local instanceID = unitID .. '_' .. barname - --spEcho(instanceID, barname, unitBars[unitID]) - if healthBarVBO.instanceIDtoIndex[instanceID] then - if debugmode then spEcho("Trying to add duplicate bar", unitID, instanceID, barname, reason, unitBars[unitID]) end - return - end -- we already have this bar ! - - if unitDefID == nil or Spring.ValidUnitID(unitID) == false or Spring.GetUnitIsDead(unitID) == true then -- dead or invalid - if debugmode then - Spring.Debug.TraceEcho("Tried to add a bar to dead/invalid/nounitdef unit", unitID, unitdefID, barname) - end - return nil - end - - if unitBars[unitID] == nil then - if debugmode then - spEcho("A unit has no bars yet", UnitDefs[unitDefID].name, spGetUnitPosition(unitID)) - Spring.Debug.TraceFullEcho() - Spring.SendCommands({"pause 1"}) - spEcho("No bars unit, last seen at", unitID) - Spring.MarkerAddPoint(spGetUnitPosition(unitID) ) - end - unitBars[unitID] = 1 - end - - unitBars[unitID] = unitBars[unitID] + 1 - - local effectiveScale = ((variableBarSizes and unitDefSizeMultipliers[unitDefID]) or 1.0) * barScale - - local healthBarTableCache = bt.cache - - healthBarTableCache[1] = unitDefHeights[unitDefID] + additionalheightaboveunit * effectiveScale -- height - healthBarTableCache[2] = effectiveScale - healthBarTableCache[6] = unitBars[unitID] - 1 -- bar index (how manyeth per unit) - - return pushElementInstance( - healthBarVBO, -- push into this Instance VBO Table - healthBarTableCache, - instanceID, -- this is the key inside the VBO Table, should be unique per unit - true, -- update existing element - nil, -- noupload, dont use unless you know what you want to batch push/pop - unitID) -- last one should be featureID! - -- we are returning here, to sign successful adds -end - - -local uniformcache = {0.0} - -local function updateReloadBar(unitID, unitDefID, reason) - if not unitDefPrimaryWeapon[unitDefID] then - return - end - - local reloadFrame = GetUnitWeaponState(unitID, unitDefPrimaryWeapon[unitDefID], 'reloadFrame') - local reloadTime = GetUnitWeaponState(unitID, unitDefPrimaryWeapon[unitDefID], 'reloadTime') - local gf = spGetGameFrame() - - if (reloadFrame == nil or reloadFrame > gf) and unitReloadWatch[unitID] == nil then - addBarForUnit(unitID, unitDefID, "reload", reason) - end - - if (reloadFrame and reloadTime and gl.SetUnitBufferUniforms) then - uniformcache[1] = reloadFrame - 30 * reloadTime - gl.SetUnitBufferUniforms(unitID, uniformcache, 2) - uniformcache[1] = reloadFrame - gl.SetUnitBufferUniforms(unitID, uniformcache, 3) - end -end - -local function removeBarFromUnit(unitID, barname, reason) -- this will bite me in the ass later, im sure, yes it did, we need to just update them :P - local instanceKey = unitID .. "_" .. barname - if healthBarVBO.instanceIDtoIndex[instanceKey] then - if debugmode then Spring.Debug.TraceEcho(reason) end - unitBars[unitID] = unitBars[unitID] - 1 - popElementInstance(healthBarVBO, instanceKey) - end -end - - -local function addBarsForUnit(unitID, unitDefID, unitTeam, unitAllyTeam, reason) -- TODO, actually, we need to check for all of these for stuff entering LOS - - if unitDefID == nil or Spring.ValidUnitID(unitID) == false or Spring.GetUnitIsDead(unitID) == true then - if debugmode then spEcho("Tried to add a bar to a dead or invalid unit", unitID, "at", spGetUnitPosition(unitID), reason) end - return - end - - unitBars[unitID] = unitBars[unitID] or 0 - - -- This is optionally passed, and it only important in one edge case: - -- If a unit is captured and thus immediately become outside of LOS, then the getunitallyteam is still the old ally team according to getUnitAllyTEam, and not the new allyteam. - unitAllyTeam = unitAllyTeam or Spring.GetUnitAllyTeam(unitID) - local health, maxHealth, paralyzeDamage, capture, build = spGetUnitHealth(unitID) - if (fullview or (unitAllyTeam == myAllyTeamID) or (unitDefHideDamage[unitDefID] == nil)) and (unitDefIgnore[unitDefID] == nil ) then - if debugmode and health == nil then - spEcho("Trying to add a healthbar to nil health unit", unitID, unitDefID) - local ux, uy, uz = spGetUnitPosition(unitID) - Spring.MarkerAddPoint(ux, uy, uz, "health") - end - addBarForUnit(unitID, unitDefID, "health", reason) - end - if unitDefhasShield[unitDefID] then - --spEcho("hasshield") - addBarForUnit(unitID, unitDefID, "shield", reason) - unitShieldWatch[unitID] = -1.0 - elseif unitDefReactiveArmor[unitDefID] then - unitReactiveArmorWatch[unitID] = unitDefReactiveArmor[unitDefID] - addBarForUnit(unitID, unitDefID, "shield", reason) - local armorHealth = Spring.GetUnitRulesParam(unitID, "reactiveArmorHealth") - if armorHealth then - uniformcache[1] = armorHealth / unitDefReactiveArmor[unitDefID] - gl.SetUnitBufferUniforms(unitID, uniformcache, 2) - end - end - - updateReloadBar(unitID, unitDefID, reason) - - if health ~= nil then - if build < 1 then - addBarForUnit(unitID, unitDefID, "building", reason) - end - --spEcho(unitID, unitDefID, unitDefCanStockpile[unitDefID]) - if debugmode then - if unitDefCanStockpile[unitDefID] then - spEcho("unitDefCanStockpile", unitAllyTeam, myAllyTeamID, fullview) - end - - end - - if unitDefCanStockpile[unitDefID] and ((unitAllyTeam == myAllyTeamID) or fullview) then - unitStockPileWatch[unitID] = 0.0 - addBarForUnit(unitID, unitDefID, "stockpile", reason) - end - if capture > 0 then - addBarForUnit(unitID, unitDefID, "capture", reason) - uniformcache[1] = capture - gl.SetUnitBufferUniforms(unitID, uniformcache, 5) - unitCaptureWatch[unitID] = capture - end - - if paralyzeDamage > 0 then - --TODO - - if Spring.GetUnitIsStunned(unitID) then - if unitParalyzedWatch[unitID] == nil then -- already paralyzed - unitParalyzedWatch[unitID] = 0.0 - -- if unit was already empd, remove that bar - if unitEmpDamagedWatch[unitID] then - unitEmpDamagedWatch[unitID] = nil - removeBarFromUnit(unitID, 'emp_damage', 'unitEmpDamagedWatch') - end - addBarForUnit(unitID, unitDefID, "paralyzed", reason) - end - else - if unitEmpDamagedWatch[unitID] == nil then - unitEmpDamagedWatch[unitID] = 0.0 - addBarForUnit(unitID, unitDefID, "emp_damage", reason) - end - end - end - end -end - -local function removeBarsFromUnit(unitID, reason) - for barname,v in pairs(barTypeMap) do - removeBarFromUnit(unitID, barname, reason) - end - unitShieldWatch[unitID] = nil - unitReactiveArmorWatch[unitID] = nil - unitCaptureWatch[unitID] = nil - unitEmpDamagedWatch[unitID] = nil - unitParalyzedWatch[unitID] = nil - unitStockPileWatch[unitID] = nil - unitReloadWatch[unitID] = nil - unitBars[unitID] = nil -end - - -local function addBarToFeature(featureID, barname) - if debugmode then Spring.Debug.TraceEcho() end - local featureDefID = Spring.GetFeatureDefID(featureID) - - local bt = barTypeMap[barname] - - local targetVBO = featureHealthVBO - if barname == 'featurereclaim' then targetVBO = featureReclaimVBO end - if barname == 'featureresurrect' then targetVBO = featureResurrectVBO end - - if targetVBO.instanceIDtoIndex[featureID] then return end -- already exists, bail - if featureBars[featureID] == nil then - featureBars[featureID] = 0 - end - featureBars[featureID] = featureBars[featureID] + 1 - - pushElementInstance( - targetVBO, -- push into this Instance VBO Table - {featureDefHeights[featureDefID] + additionalheightaboveunit, -- height - 1.0 * barScale, -- size mult - 0, -- timer end - bt.uvoffset, -- unused float - - bt.bartype, -- bartype int - featureBars[featureID] - 1, -- bar index (how manyeth per unit) - bt.uniformindex, -- ssbo location offset (> 20 for health) - 0, -- unused int - - bt.mincolor[1], bt.mincolor[2], bt.mincolor[3], bt.mincolor[4], - bt.maxcolor[1], bt.maxcolor[2], bt.maxcolor[3], bt.maxcolor[4], - 0, 0, 0, 0}, -- these are just padding zeros for instData, that will get filled in - featureID, -- this is the key inside the VBO Table, should be unique per unit - true, -- update existing element - nil, -- noupload, dont use unless you know what you want to batch push/pop - featureID) -- last one should be featureID! -end - - -local function removeBarFromFeature(featureID, targetVBO) - --spEcho("removeBarFromFeature", featureID, targetVBO.myName) - if not targetVBO.instanceIDtoIndex[featureID] then - return - end - - popElementInstance(targetVBO, featureID) - - local barCount = featureBars[featureID] - if not barCount then - return - end - - barCount = barCount - 1 - if barCount > 0 then - featureBars[featureID] = barCount - else - featureBars[featureID] = nil - end -end - -local function removeBarsFromFeature(featureID) - removeBarFromFeature(featureID, featureHealthVBO) - removeBarFromFeature(featureID, featureReclaimVBO) - removeBarFromFeature(featureID, featureResurrectVBO) -end - - -local function init() - InstanceVBOTable.clearInstanceTable(healthBarVBO) - unitCaptureWatch = {} - unitShieldWatch = {} -- maps unitID to last shield value - unitReactiveArmorWatch = {} - unitEmpDamagedWatch = {} - unitParalyzedWatch = {} - unitStockPileWatch = {} - unitReloadWatch = {} - unitBars = {} - for i, unitID in ipairs(Spring.GetAllUnits()) do -- gets radar blips too! - -- probably shouldnt be adding non-visible units - - if fullview then - addBarsForUnit(unitID, spGetUnitDefID(unitID), spGetUnitTeam(unitID), nil, 'initfullview') - else - local losstate = Spring.GetUnitLosState(unitID, myAllyTeamID) - if losstate.los then - addBarsForUnit(unitID, spGetUnitDefID(unitID), spGetUnitTeam(unitID), nil, 'initlos') - --spEcho(unitID, "IS in los") - else - --spEcho(unitID, "is not in los for ", myAllyTeamID) - end - end - end - -end - -local function initfeaturebars() - InstanceVBOTable.clearInstanceTable(featureHealthVBO) - InstanceVBOTable.clearInstanceTable(featureResurrectVBO) - InstanceVBOTable.clearInstanceTable(featureReclaimVBO) - for i, featureID in ipairs(Spring.GetAllFeatures()) do - local featureDefID = Spring.GetFeatureDefID(featureID) - --local resurrectname = Spring.GetFeatureResurrect(featureID) - --if resurrectname then - -- resurrectableFeatures[featureID] = true - -- if it has resurrect progress, then just straight up just store a bar here for it? - -- or shall we only instantiate bars when needed? probably number 2 is smarter... - --end -- maybe store resurrect progress here? - - if featureDefID then -- dont add features that we cant get the ID of - -- add a health bar for it (dont add one for pre-existing stuff) - widget:FeatureCreated(featureID) - else - - end - end -end - ---12:32 PM] Beherith: widget:PlayerChanged generalizations ---[12:33 PM] Beherith: So, I would like to ask if we have a general guideline or if @Floris knows anything about what circumstances should trigger UI GFX widget reinitialization ---[12:36 PM] Beherith: Here, I assume we can live with a few assumptions: ---1. UI GFX widgets are LOS dependent things, that either --- A. Should look the same for all players on an ALLYteam --- B. Could look different for each member of an ALLYTeam ---2. Always render different things for different ALLYteams ---This presents and interesting state for most widgets especially for SPECFULLVIEW ---Obviously, the biggest reason for needing to abstract this is to avoid boilerplate mistakes for most new GL4 widgets, which are --stateful, unlike most previous widgets (most of which collected things they wanted to draw every frame) ---[12:39 PM] Beherith: So I assume widget:PlayerChanged gets called on any legal player change, and should keep track of the following: ---1. spectating state ---2. specfullview state ---3. myAllyTeamID ---4. myTeamID ---[12:40 PM] Beherith: There are 3 real states someone can be in: ---1. player ---2. spectator no fullview ---3. spectator with fullview - ---(excluding godmode /globallos et al) ---[12:40 PM] Beherith: Transitions between any of the above 3 should trigger a full reinit ---[12:41 PM] Beherith: But some internal transitions, for stuff that is draw differently for allies might require additional checks, for spectators who have fullview off? - - -local function FeatureReclaimStartedHealthbars (featureID, step) -- step is negative for reclaim, positive for resurrect - --spEcho("FeatureReclaimStartedHealthbars", featureID) - - --gl.SetFeatureBufferUniforms(featureID, 0.5, 2) -- update GL - if step > 0 then addBarToFeature(featureID, 'featureresurrect') - else addBarToFeature(featureID, 'featurereclaim') end -end - -local function UnitCaptureStartedHealthbars(unitID, step) -- step is negative for reclaim, positive for resurrect - if debugmode then spEcho("UnitCaptureStartedHealthbars", unitID) end - --gl.SetFeatureBufferUniforms(featureID, 0.5, 2) -- update GL - local capture = select(4, spGetUnitHealth(unitID)) - uniformcache[1] = capture - gl.SetUnitBufferUniforms(unitID, uniformcache, 5) - unitCaptureWatch[unitID] = capture - addBarForUnit(unitID, spGetUnitDefID(unitID), 'capture', 'UnitCaptureStartedHealthbars') - -end - ---function widget:UnitDamaged(unitID, unitDefID, unitTeam, damage, paralyzer) -local function UnitParalyzeDamageHealthbars(unitID, unitDefID, damage) - if Spring.GetUnitIsStunned(unitID) then -- DO NOTE THAT: return: nil | bool stunned_or_inbuild, bool stunned, bool inbuild - if unitParalyzedWatch[unitID] == nil then -- already paralyzed - unitParalyzedWatch[unitID] = 0.0 - -- if unit was already empd, remove that bar - if unitEmpDamagedWatch[unitID] then - unitEmpDamagedWatch[unitID] = nil - removeBarFromUnit(unitID, 'emp_damage', 'unitEmpDamagedWatch') - end - addBarForUnit(unitID, unitDefID, "paralyzed", 'unitParalyzedWatch') - end - else - if unitEmpDamagedWatch[unitID] == nil then - unitEmpDamagedWatch[unitID] = 0.0 - addBarForUnit(unitID, unitDefID, "emp_damage", 'unitEmpDamagedWatch') - end - end -end - -local function ProjectileCreatedReloadHB(projectileID, unitID, weaponID, unitDefID) - local unitDefID = spGetUnitDefID(unitID) - - updateReloadBar(unitID, unitDefID, 'ProjectileCreatedReloadHB') -end - -local function debughealthbarsCmd(_, line) - debugmode = not debugmode - spEcho("Debug mode for HealthBars GL4 set to", debugmode) - healthBarVBO.debug = debugmode - return true -end - -function widget:Initialize() - widgetHandler:AddAction("debughealthbars", debughealthbarsCmd, nil, "t") - - if not gl.CreateShader then -- no shader support, so just remove the widget itself, especially for headless - widgetHandler:RemoveWidget() - return - end - WG['healthbars'] = {} - WG['healthbars'].getScale = function() - return barScale - end - WG['healthbars'].setScale = function(value) - barScale = value - init() - initfeaturebars() - end - WG['healthbars'].getHeight = function() - return barHeight - end - WG['healthbars'].setHeight = function(value) - barHeight = value - shaderSourceCache.shaderConfig.BARHEIGHT = barHeight - shaderSourceCache.shaderConfig.BARCORNER = 0.06 + (shaderConfig.BARHEIGHT / 9) - shaderSourceCache.shaderConfig.SMALLERCORNER = shaderConfig.BARCORNER * 0.6 - init() - initfeaturebars() - end - WG['healthbars'].getVariableSizes = function() - return variableBarSizes - end - WG['healthbars'].setVariableSizes = function(value) - variableBarSizes = value - init() - initfeaturebars() - end - WG['healthbars'].getDrawWhenGuiHidden = function() - return drawWhenGuiHidden - end - WG['healthbars'].setDrawWhenGuiHidden = function(value) - drawWhenGuiHidden = value - end - - initGL4() - - -- TODO: dont even bother drawing health bars for features that were present on frame 0 - no point in doing so - -- This is stuff like trees and map features, and scenario features - init() - initfeaturebars() -end - -function widget:Shutdown() - widgetHandler:RemoveAction("debughealthbars", "t") - spEcho("Healthbars GL4 unloaded hooks") -end - -function widget:FeatureReclaimStartedHealthbars(featureID, step) - FeatureReclaimStartedHealthbars(featureID, step) -end - -function widget:UnitCaptureStartedHealthbars(unitID, step) - UnitCaptureStartedHealthbars(unitID, step) -end - -function widget:UnitParalyzeDamageHealthbars(unitID, unitDefID, damage) - UnitParalyzeDamageHealthbars(unitID, unitDefID, damage) -end - -function widget:ProjectileCreatedReloadHB(projectileID, ownerID, weaponID) - ProjectileCreatedReloadHB(projectileID, ownerID, weaponID) -end - -function widget:RecvLuaMsg(msg, playerID) - if msg:sub(1,18) == 'LobbyOverlayActive' then - chobbyInterface = (msg:sub(1,19) == 'LobbyOverlayActive1') - end -end - -function widget:VisibleUnitAdded(unitID, unitDefID, unitTeam) - addBarsForUnit(unitID, unitDefID, unitTeam, nil, 'VisibleUnitAdded') -end - -function widget:VisibleUnitRemoved(unitID) - removeBarsFromUnit(unitID, 'VisibleUnitRemoved') -end - -function widget:CrashingAircraft(unitID, unitDefID, teamID) - removeBarsFromUnit(unitID,'CrashingAircraft') -end - -function widget:VisibleUnitsChanged(extVisibleUnits, extNumVisibleUnits) - unitBars = {} - unitShieldWatch = {} - unitReactiveArmorWatch = {} - unitCaptureWatch = {} - unitEmpDamagedWatch = {} - unitParalyzedWatch = {} - unitStockPileWatch = {} - unitReloadWatch = {} - spec, fullview = spGetSpectatingState() - myAllyTeamID = Spring.GetMyAllyTeamID() - - - InstanceVBOTable.clearInstanceTable(healthBarVBO) -- clear all instances - for unitID, unitDefID in pairs(extVisibleUnits) do - addBarsForUnit(unitID, unitDefID, spGetUnitTeam(unitID), nil, "VisibleUnitsChanged") -- TODO: add them with noUpload = true - end - --uploadAllElements(healthBarVBO) -- upload them all -end - -function widget:PlayerChanged(playerID) - - local currentspec, currentfullview = spGetSpectatingState() - local currentTeamID = Spring.GetMyTeamID() - local currentAllyTeamID = Spring.GetMyAllyTeamID() - local currentPlayerID = Spring.GetMyPlayerID() - local reinit = false - - if debugmode then spEcho("HBGL4 widget:PlayerChanged",'spec', currentspec, 'fullview', currentfullview, 'teamID', currentTeamID, 'allyTeamID', currentAllyTeamID, "playerID", currentPlayerID) end - - -- cases where we need to trigger: - if (currentspec ~= spec) or -- we transition from spec to player, yes this is needed - (currentfullview ~= fullview) or -- we turn on or off fullview - ((currentAllyTeamID ~= myAllyTeamID) and not currentfullview) -- our ALLYteam changes, and we are not in fullview - - then - -- do the actual reinit stuff, but first change my own - reinit = true - if debugmode then spEcho("HBGL4 triggered a playerchanged reinit") end - - end - -- save the state: - spec = currentspec - fullview = currentfullview - myAllyTeamID = currentAllyTeamID - --if reinit then init() end -end - - -function widget:GameFrame(n) - - if debugmode then - InstanceVBOTable.locateInvalidUnits(healthBarVBO) - InstanceVBOTable.locateInvalidUnits(featureHealthVBO) - end - -- Units: - -- check shields and armor - if n % 3 == 0 then - for unitID, oldshieldPower in pairs(unitShieldWatch) do - local shieldOn, shieldPower = Spring.GetUnitShieldState(unitID) - if shieldOn == false then shieldPower = 0.0 end - if oldshieldPower ~= shieldPower then - if shieldPower == nil then - removeBarFromUnit(unitID, "shield", "unitShieldWatch") - else - uniformcache[1] = shieldPower / (unitDefhasShield[spGetUnitDefID(unitID)]) - gl.SetUnitBufferUniforms(unitID, uniformcache, 2) - end - unitShieldWatch[unitID] = shieldPower - end - end - - -- todo: armor should be completely different but idk how to set up a new bar type - for unitID, oldArmorValue in pairs(unitReactiveArmorWatch) do - local newArmorValue = Spring.GetUnitRulesParam(unitID, "reactiveArmorHealth") - if newArmorValue ~= oldArmorValue then - if newArmorValue == nil then - removeBarFromUnit(unitID, "shield", "unitReactiveArmorWatch") - else - if not newArmorValue then - newArmorValue = 0 - end - uniformcache[1] = newArmorValue / unitDefReactiveArmor[spGetUnitDefID(unitID)] - gl.SetUnitBufferUniforms(unitID, uniformcache, 2) - end - unitReactiveArmorWatch[unitID] = newArmorValue - end - end - end - - -- todo paralyzed and EMP doesnt work for enemy units :( - -- check EMP'd units - if (n + 1) % 3 == 0 then - for unitID, oldempvalue in pairs(unitEmpDamagedWatch) do - local health, maxHealth, newparalyzeDamage, capture, build = spGetUnitHealth(unitID) - if newparalyzeDamage and oldempvalue ~= newparalyzeDamage then - if newparalyzeDamage == 0 then - unitEmpDamagedWatch[unitID] = nil - removeBarFromUnit(unitID, "emp_damage",'unitEmpDamagedWatch') - else - uniformcache[1] = newparalyzeDamage/ maxHealth - unitEmpDamagedWatch[unitID] = newparalyzeDamage - gl.SetUnitBufferUniforms(unitID, uniformcache, 4) - end - end - end - end - - -- check Paralyzed units - if (n+2) % 3 == 0 then - for unitID, paralyzetime in pairs(unitParalyzedWatch) do - if Spring.GetUnitIsStunned(unitID) then - local health, maxHealth, paralyzeDamage, capture, build = spGetUnitHealth(unitID) - --uniformcache[1] = math.floor((paralyzeDamage - maxHealth)) / (maxHealth * empDecline)) - if paralyzeDamage then - - -- this returns something like 1.20 which somehow turns into seconds somewhere unsearchable, currently wrong display - -- this needs conditional fixing within an if Spring.GetModOptions().emprework - uniformcache[1] = paralyzeDamage / maxHealth - --spEcho("Paralyze damages", paralyzeDamage, maxHealth) - --spEcho("Paralyze damage cur", (paralyzeDamage / maxHealth)) - - gl.SetUnitBufferUniforms(unitID, uniformcache, 4) - end - else - unitParalyzedWatch[unitID] = nil - removeBarFromUnit(unitID, "paralyzed", 'unitEmpDamagedWatch') - addBarForUnit(unitID, unitDefID, "emp_damage",'unitEmpDamagedWatch') - unitEmpDamagedWatch[unitID] = 1.0 - end - end - end - - -- check capture progress? - if (n % 3) == 2 then - for unitID, captureprogress in pairs(unitCaptureWatch) do - local capture = select(4, spGetUnitHealth(unitID)) - if capture and capture ~= captureprogress then - uniformcache[1] = capture - gl.SetUnitBufferUniforms(unitID, uniformcache, 5) - unitCaptureWatch[unitID] = capture - end - if capture == 0 or capture == nil then - removeBarFromUnit(unitID, 'capture', 'unitCaptureWatch') - unitCaptureWatch[unitID] = nil - end - end - end - - -- check stockpile progress - if (n % 5) == 2 then - for unitID, stockpilebuild in pairs(unitStockPileWatch) do - local numStockpiled, numStockpileQued, stockpileBuild = Spring.GetUnitStockpile(unitID) - if stockpileBuild and stockpileBuild ~= stockpilebuild then - -- we somehow need to forward 3 vars, all 3 of the above. packed into a float, this is nasty - --spEcho("Stockpiling", numStockpiled, numStockpileQued, stockpileBuild) - if numStockpiled == nil then Spring.Debug.TraceFullEcho(nil,nil,nil, 'nostockpile', unitID, spGetUnitPosition(unitID)) end - - uniformcache[1] = numStockpiled + stockpileBuild -- less hacky - --uniformcache[1] = 128*numStockpileQued + numStockpiled + stockpileBuild -- the worlds nastiest hack - unitStockPileWatch[unitID] = stockpileBuild - gl.SetUnitBufferUniforms(unitID, uniformcache, 2) - end - end - end -end - -local rezreclaim = {0.0, 1.0} -function widget:FeatureCreated(featureID) - local featureDefID = Spring.GetFeatureDefID(featureID) - local gameFrame = spGetGameFrame() - -- some map-supplied features dont have a model, in these cases modelpath == "" - if FeatureDefs[featureDefID].name ~= 'geovent' and FeatureDefs[featureDefID].modelpath ~= '' then - --spEcho(FeatureDefs[featureDefID].name) - --featureBars[featureID] = 0 -- this is already done in AddBarToFeature - - local health,maxhealth,rezProgress = Spring.GetFeatureHealth(featureID) - - if gameFrame > 0 then - addBarToFeature(featureID, 'featurehealth') - else - if health ~= maxhealth then addBarToFeature(featureID, 'featurehealth') end - end - - if not fullview then - local featureX, featureY, featureZ = spGetFeaturePosition(featureID) - if featureX and not spIsPosInLos(featureX, featureY, featureZ, myAllyTeamID) then - return - end - end - - if rezProgress > 0 then - addBarToFeature(featureID, 'featureresurrect') - end - - local _, _, _, _, reclaimLeft = Spring.GetFeatureResources(featureID) - - if reclaimLeft < 1.0 then - addBarToFeature(featureID, 'featurereclaim') - end - - if rezProgress > 0 or reclaimLeft < 1 then - -- We have to update the feature uniform buffers in this case, as features can be created with less than max health on the map with FP_featureplacer - rezreclaim[1] = rezProgress -- resurrect progress - rezreclaim[2] = reclaimLeft -- reclaim percent - gl.SetFeatureBufferUniforms(featureID, rezreclaim, 1) -- update GL, at offset of 1 - end - - end -end - -function widget:FeatureDestroyed(featureID) - if debugmode then spEcho("FeatureDestroyed",featureID, featureBars[featureID]) end - removeBarsFromFeature(featureID) - featureBars[featureID] = nil -end - -function widget:DrawScreenEffects() - -- using DrawScreenEffects so healthbars render after deferred lighting, - -- distortion, bloom and tonemapping passes — keeps bar colors uncolored - -- and unaffected by water/heat distortion. The shader still does world->clip - -- via engine cameraViewProj UBO, and depth-test still occludes against terrain. - --spEcho(Engine.versionFull ) - if chobbyInterface then return end - if not drawWhenGuiHidden and Spring.IsGUIHidden() then return end - - if spGetGameFrame() % 90 == 0 then - --spEcho("healthBarVBO",healthBarVBO.usedElements, "featureHealthVBO",featureHealthVBO.usedElements) - end - if healthBarVBO.usedElements > 0 or featureHealthVBO.usedElements > 0 then -- which quite strictly, is impossible anyway - local disticon = Spring.GetConfigInt("UnitIconDistance", 200) * 27.5 -- iconLength = unitIconDist * unitIconDist * 750.0f; - gl.Culling(false) - gl.Blending(GL.SRC_ALPHA, GL.ONE_MINUS_SRC_ALPHA) - gl.DepthTest(true) - gl.DepthMask(true) - gl.Texture(0,healthbartexture) - healthBarShader:Activate() - healthBarShader:SetUniform("iconDistance",disticon) - if not debugmode then healthBarShader:SetUniform("cameraDistanceMult",1.0) end - healthBarShader:SetUniform("cameraDistanceMultGlyph", glphydistmult) - healthBarShader:SetUniform("skipGlyphsNumbers",skipGlyphsNumbers) --0.0 is everything, 1.0 means only numbers, 2.0 means only bars, - if healthBarVBO.usedElements > 0 then - if useGeometryShader then - healthBarVBO.VAO:DrawArrays(GL.POINTS,healthBarVBO.usedElements) - else - healthBarVBO.VAO:DrawArrays(GL.TRIANGLE_STRIP, 4, 0, healthBarVBO.usedElements) - end - end - -- below its the feature bars being drawn: - healthBarShader:SetUniform("cameraDistanceMultGlyph", glyphdistmultfeatures) - if featureHealthVBO.usedElements > 0 then - if not debugmode then healthBarShader:SetUniform("cameraDistanceMult",featureHealthDistMult) end - if useGeometryShader then - featureHealthVBO.VAO:DrawArrays(GL.POINTS,featureHealthVBO.usedElements) - else - featureHealthVBO.VAO:DrawArrays(GL.TRIANGLE_STRIP, 4, 0, featureHealthVBO.usedElements) - end - end - if featureResurrectVBO.usedElements > 0 then - if not debugmode then healthBarShader:SetUniform("cameraDistanceMult",featureResurrectDistMult) end - if useGeometryShader then - featureResurrectVBO.VAO:DrawArrays(GL.POINTS,featureResurrectVBO.usedElements) - else - featureResurrectVBO.VAO:DrawArrays(GL.TRIANGLE_STRIP, 4, 0, featureResurrectVBO.usedElements) - end - end - if featureReclaimVBO.usedElements > 0 then - if not debugmode then healthBarShader:SetUniform("cameraDistanceMult",featureReclaimDistMult) end - if useGeometryShader then - featureReclaimVBO.VAO:DrawArrays(GL.POINTS,featureReclaimVBO.usedElements) - else - featureReclaimVBO.VAO:DrawArrays(GL.TRIANGLE_STRIP, 4, 0, featureReclaimVBO.usedElements) - end - end - - healthBarShader:Deactivate() - gl.Texture(false) - gl.Blending(GL.SRC_ALPHA, GL.ONE_MINUS_SRC_ALPHA) - gl.Culling(false) - gl.DepthTest(false) - gl.DepthMask(false) --"BK OpenGL state resets", reset to default state - end -end - -function widget:GetConfigData(data) - return { - barScale = barScale, - barHeight = barHeight, - variableBarSizes = variableBarSizes, - drawWhenGuiHidden = drawWhenGuiHidden - } -end - -function widget:SetConfigData(data) - barScale = data.barScale or barScale - if data.variableBarSizes ~= nil then - variableBarSizes = data.variableBarSizes - end - if data.drawWhenGuiHidden ~= nil then - drawWhenGuiHidden = data.drawWhenGuiHidden - end - if data.barHeight ~= nil then - barHeight = data.barHeight - shaderSourceCache.shaderConfig.BARHEIGHT = barHeight - shaderSourceCache.shaderConfig.BARCORNER = 0.06 + (shaderConfig.BARHEIGHT / 9) - shaderSourceCache.shaderConfig.SMALLERCORNER = shaderConfig.BARCORNER * 0.6 - end -end - -return widget end)() -local forward=(function()local gadget={} -local gadget = gadget ---@type Gadget - -function gadget:GetInfo() - return { - name = "Healthbars Widget Forwarding", - desc = "Notifies widgets that a feature reclaim or resurrect action has begun, updates GL Uniforms, and also notifies on capture start, emp damage, reload", - author = "Beherith", -- ty Sprung - date = "2021.11.25", - license = "GNU GPL, v2 or later", - layer = -1, - enabled = true - } -end - - -if gadgetHandler:IsSyncedCode() then - - local SendToUnsynced = SendToUnsynced - local spGetGameFrame = Spring.GetGameFrame - local spGetUnitWeaponState = Spring.GetUnitWeaponState - - local forwardedFeatureIDs = {} -- so we only forward the start event once - local forwardedCaptureUnitIDs = {} - local weapondefsreload = {} - local unitreloadframe = {} -- maps unitID to next frame it can shoot its primary weapon, cause lasers retrigger projetileCreated every frame - local minReloadTime = 5 -- in concerto with healthbars widget - - function gadget:AllowFeatureBuildStep(builderID, builderTeam, featureID, featureDefID, step) - -- VERY IMPORTANT: This also gets called on resurrect!, but its very hard to tell if its a reclaim, but we can make the mother of all assumptions: - -- features die at 100% metal value - -- step is negative if 'reclaiming' - -- step is large positive if refilling - -- step is small positive if rezzing - - local gf = spGetGameFrame() - --Spring.Echo("AllowFeatureBuildStep",gf,builderID, builderTeam, featureID, featureDefID, step) - if forwardedFeatureIDs[featureID] == nil or forwardedFeatureIDs[featureID] < gf then - forwardedFeatureIDs[featureID] = gf - SendToUnsynced("featureReclaimFrame", featureID, step) - end - return true - end - - function gadget:AllowUnitCaptureStep(builderID, builderTeam, unitID, unitDefID, part) - if forwardedCaptureUnitIDs[unitID] == nil then - forwardedCaptureUnitIDs[unitID] = true - SendToUnsynced("unitCaptureFrame", unitID, part) - end - return true - end - - function gadget:FeatureDestroyed(featureID, allyTeamID) - forwardedFeatureIDs[featureID] = nil - end - - function gadget:UnitDestroyed(unitID, unitDefID, unitTeam, attackerID, attackerDefID, attackerTeam, weaponDefID) - forwardedCaptureUnitIDs[unitID] = nil - unitreloadframe[unitID] = nil - end - - function gadget:UnitTaken(unitID) - forwardedCaptureUnitIDs[unitID] = nil - end - - function gadget:Initialize() - for udefID, unitDef in pairs(UnitDefs) do - local weapons = unitDef.weapons - local watchweaponID = nil - local longestreloadtime = -1 - local longestreloadindex - for i = 1, #weapons do - local WeaponDefID = weapons[i].weaponDef - local WeaponDef = WeaponDefs[WeaponDefID] - if WeaponDef.reload and WeaponDef.reload >0 and WeaponDef.reload >= longestreloadtime then - longestreloadtime = WeaponDef.reload - watchweaponID = WeaponDefID - longestreloadindex = i - end - end - if watchweaponID and longestreloadtime > minReloadTime then - --Spring.Echo("Unit with watched reload time:", unitDef.name, longestreloadtime, watchweaponID, udefID) - weapondefsreload[watchweaponID] = longestreloadindex - Script.SetWatchProjectile(watchweaponID, true) - end - end - end - - function gadget:ProjectileCreated(projectileID, ownerID, weaponID) -- needs: Script.SetWatchProjectile(weaponDefID, true) - --local unitDef = Spring.GetUnitDefID(ownerID) - --Spring.Echo("gadget:ProjectileCreated(",projectileID, ownerID, weaponID,weapondefsreload[weaponID],unitreloadframe[ownerID], ")") - local weaponIndex = weapondefsreload[weaponID] - - if weaponIndex then - local gf = spGetGameFrame() - local reloadFrame = spGetUnitWeaponState(ownerID, weaponIndex, 'reloadFrame') - - if unitreloadframe[ownerID] == nil or unitreloadframe[ownerID] <= gf then - SendToUnsynced("projetileCreatedReload", projectileID, ownerID, weaponID) - unitreloadframe[ownerID] = reloadFrame - end - end - end - -else - - local glSetFeatureBufferUniforms = gl.SetFeatureBufferUniforms - local GetFeatureResources = Spring.GetFeatureResources - local GetFeaturePosition = Spring.GetFeaturePosition - local IsPosInLos = Spring.IsPosInLos - local rezreclaim = {0.0, 1.0} -- this is just a small table cache, so we dont allocate a new table for every update - local forwardedFeatureIDsResurrect = {} -- so we only forward the start event once - local forwardedFeatureIDsReclaim = {} -- so we only forward the start event once - local myTeamID = Spring.GetMyTeamID() - local myAllyTeamID = Spring.GetMyAllyTeamID() - local _, fullview = Spring.GetSpectatingState() - local IsUnitInLos = Spring.IsUnitInLos - local GetFeatureHealth = Spring.GetFeatureHealth - local headless = false - - function gadget:PlayerChanged(playerID) - myTeamID = Spring.GetMyTeamID() - myAllyTeamID = Spring.GetMyAllyTeamID() - _, fullview = Spring.GetSpectatingState() - end - - function featureReclaimFrame(cmd, featureID, step) - --Spring.Echo("HandleFeatureReclaimStarted", featureID) - if not fullview then - local x, y, z = GetFeaturePosition(featureID) - if x and not IsPosInLos(x, y, z, myAllyTeamID) then - return - end - end - - rezreclaim[1] = select(3, GetFeatureHealth( featureID )) -- resurrect progress - rezreclaim[2] = select(5, GetFeatureResources(featureID)) -- reclaim percent - - --Spring.Echo('rezreclaim', rezreclaim[1], rezreclaim[2]) - - if not headless then glSetFeatureBufferUniforms(featureID, rezreclaim, 1) end -- update GL, at offset of 1 - - if step > 0 and forwardedFeatureIDsResurrect[featureID] == nil and Script.LuaUI("FeatureReclaimStartedHealthbars") then - forwardedFeatureIDsResurrect[featureID] = true - --Spring.Echo("HandleFeatureReclaimStartedHealthbars", featureID, step) - Script.LuaUI.FeatureReclaimStartedHealthbars(featureID, step) - end - - if step < 0 and forwardedFeatureIDsReclaim[featureID] == nil and Script.LuaUI("FeatureReclaimStartedHealthbars") then - forwardedFeatureIDsReclaim[featureID] = true - --Spring.Echo("HandleFeatureReclaimStartedHealthbars", featureID, step) - Script.LuaUI.FeatureReclaimStartedHealthbars(featureID, step) - end - end - - function unitCaptureFrame(cmd, unitID, step) - if not fullview and not IsUnitInLos(unitID, myAllyTeamID) then return end - if Script.LuaUI("UnitCaptureStartedHealthbars") then - --Spring.Echo("UnitCaptureStartedHealthbars", unitID, step) - Script.LuaUI.UnitCaptureStartedHealthbars(unitID, step) - end - end - - function projetileCreatedReload(cmd, projectileID, ownerID, weaponID) - --Spring.Echo("unsynced projetileCreatedReload", projectileID, ownerID, weaponID, fullview, Spring.GetUnitTeam(ownerID)) - if fullview or Spring.GetUnitTeam(ownerID) == myTeamID then - if Script.LuaUI("ProjectileCreatedReloadHB") then - --Spring.Echo("G:ProjectileCreatedReloadHB", projectileID, ownerID, weaponID) - Script.LuaUI.ProjectileCreatedReloadHB(projectileID, ownerID, weaponID) - end - end - end - - function gadget:FeatureDestroyed(featureID, allyTeamID) - forwardedFeatureIDsResurrect[featureID] = nil - forwardedFeatureIDsReclaim[featureID] = nil - end - - function gadget:UnitDamaged(unitID, unitDefID, unitTeam, damage, paralyzer) - --Spring.Echo("gadget:UnitDamaged",unitID, unitDefID, unitTeam, damage, paralyzer) - if paralyzer then - if not fullview and not IsUnitInLos(unitID, myAllyTeamID) then return end - - if damage > 0 then - if Script.LuaUI("UnitParalyzeDamageHealthbars") then - --Spring.Echo("UnitParalyzeDamageHealthbars", unitID, step) - Script.LuaUI.UnitParalyzeDamageHealthbars(unitID, unitDefID, damage) - end - if Script.LuaUI("UnitParalyzeDamageEffect") then - --Spring.Echo("UnitParalyzeDamageHealthbars", unitID, step) - Script.LuaUI.UnitParalyzeDamageEffect(unitID, unitDefID, damage) - end - end - end - end - - function gadget:Initialize() - headless = Spring.GetConfigInt("Headless", 0) > 0 - gadgetHandler:AddSyncAction("featureReclaimFrame", featureReclaimFrame) - gadgetHandler:AddSyncAction("unitCaptureFrame", unitCaptureFrame) - gadgetHandler:AddSyncAction("projetileCreatedReload", projetileCreatedReload) - end - - function gadget:ShutDown() - gadgetHandler:RemoveSyncAction("featureReclaimFrame") - gadgetHandler:RemoveSyncAction("unitCaptureFrame") - gadgetHandler:RemoveSyncAction("projetileCreatedReload") - end -end - -return gadget end)() -local widgetEvents=(function()local gadget={} -local ordinarySpring=Spring -local Spring=setmetatable({GetUnitLosState=function(id,ally,raw)if id==widgetEventUnit and ally==ordinarySpring.GetMyAllyTeamID()and raw==true then return widgetEventLos end;return ordinarySpring.GetUnitLosState(id,ally,raw)end},{__index=ordinarySpring}) -if gadgetHandler:IsSyncedCode() then return end - -local gadget = gadget ---@type Gadget - -function gadget:GetInfo() - return { - name = "Widget Events", - desc = "Tells widgets about events they can know about", - author = "Sprung, Klon, Beherith", - date = "2015-05-27", - license = "PD", - layer = 0, - enabled = true, - } -end - -local spAreTeamsAllied = Spring.AreTeamsAllied -local spGetMyAllyTeamID = Spring.GetMyAllyTeamID -local spGetSpectatingState = Spring.GetSpectatingState -local spGetUnitLosState = Spring.GetUnitLosState - -local myAllyTeamID, myTeamID, spec, specFullView - -function gadget:Initialize() - myTeamID = Spring.GetMyTeamID() - myAllyTeamID = Spring.GetMyAllyTeamID() - spec, specFullView = spGetSpectatingState() -end - -function gadget:PlayerChanged() - myTeamID = Spring.GetMyTeamID() - myAllyTeamID = Spring.GetMyAllyTeamID() - spec, specFullView = spGetSpectatingState() -end - - ---[[ NB: these are proxies, not the actual lua functions currently linked LuaUI-side, - so it is safe to cache them here even if the underlying func changes afterwards ]] -local scriptUnitDestroyed = Script.LuaUI.UnitDestroyed -local scriptUnitDestroyedByTeam = Script.LuaUI.UnitDestroyedByTeam - -function gadget:UnitDestroyed (unitID, unitDefID, unitTeam, attUnitID, attUnitDefID, attTeamID) - local isAllyUnit = spAreTeamsAllied(unitTeam, myTeamID) - --Spring.Echo("Gadget:UnitDest", unitID, Script.LuaUI('UnitDestroyedByTeam') , "isAllyUnit", isAllyUnit, "spec", spec, "specFullView", specFullView) - -- we need to check if any widget uses the callin, otherwise it is not bound and will produce error spam - if Script.LuaUI('UnitDestroyedByTeam') then - if spec then - scriptUnitDestroyedByTeam (unitID, unitDefID, unitTeam, attTeamID) - if not specFullView and not isAllyUnit and (spGetUnitLosState(unitID, myAllyTeamID, true) % 2 == 1) then - scriptUnitDestroyed (unitID, unitDefID, unitTeam) - end - else - local attackerInLos = attUnitID and (spGetUnitLosState(attUnitID, myAllyTeamID, true) % 2 == 1) - if isAllyUnit then - scriptUnitDestroyedByTeam (unitID, unitDefID, unitTeam, attackerInLos and attTeamID or nil) - elseif spGetUnitLosState(unitID, myAllyTeamID, true) % 2 == 1 then - scriptUnitDestroyed (unitID, unitDefID, unitTeam) - scriptUnitDestroyedByTeam (unitID, unitDefID, unitTeam, attackerInLos and attTeamID or nil) - end - end - else - if not isAllyUnit and (not (spec and specFullView) and (spGetUnitLosState(unitID, spGetMyAllyTeamID(), true) % 2 == 1)) then - scriptUnitDestroyed (unitID, unitDefID, unitTeam) - end - end -end - -local scriptUnitTaken = Script.LuaUI.UnitTaken -function gadget:UnitTaken(unitID, unitDefID, oldTeamID, newTeamID) - -- we need to notify my team if a unit transfer between two other teams happens, within my radar or los - local unitwasandisenemy = not (spAreTeamsAllied(oldTeamID, myTeamID) or spAreTeamsAllied(newTeamID, myTeamID)) - local unitinmyradarorlos = (spGetUnitLosState(unitID, myAllyTeamID, true) % 4 > 0) - -- Spring.Echo("gadget:UnitGiven",unitID, unitDefID, oldTeamID, newTeamID, unitwasandisenemy, unitinmyradarorlos) - if unitwasandisenemy and unitinmyradarorlos then - scriptUnitTaken(unitID, unitDefID, oldTeamID, newTeamID) - end -end - -local scriptUnitGiven = Script.LuaUI.UnitGiven -function gadget:UnitGiven(unitID, unitDefID, newTeamID, oldTeamID) - -- we need to notify my team if a unit transfer between two other teams happens, within my radar or los - local unitwasandisenemy = not (spAreTeamsAllied(oldTeamID, myTeamID) or spAreTeamsAllied(newTeamID, myTeamID)) - local unitinmyradarorlos = (spGetUnitLosState(unitID, myAllyTeamID, true) % 4 > 0) - -- Spring.Echo("gadget:UnitGiven",unitID, unitDefID, newTeamID, oldTeamID, unitwasandisenemy, unitinmyradarorlos) - if unitwasandisenemy and unitinmyradarorlos then - scriptUnitGiven(unitID, unitDefID, newTeamID, oldTeamID) - end -end - -local scriptUnitFinished = Script.LuaUI.UnitFinished -function gadget:UnitFinished(unitID, unitDefID, unitTeam) - if spec and specFullView then return end - -- Important: Enemy units finished within LOS do not get the respective widget:UnitFinished calls! - -- Also important: units that are created and finished in the same gameframe (like /give, or created fully built) are not in los yet, so this wont trigger! - local unitisenemy = not spAreTeamsAllied(unitTeam, myTeamID) - local isinlos = spGetUnitLosState(unitID, myAllyTeamID, true) % 2 - --Spring.Echo("gadget:UnitFinished",unitID, unitDefID, unitTeam, unitisenemy, isinlos) - if unitisenemy and (isinlos == 1) then - scriptUnitFinished(unitID, unitDefID, unitTeam) - end -end - -local scriptFeatureCreated = Script.LuaUI.FeatureCreated -function gadget:FeatureCreated(featureID, allyTeam) -- assume that features are always in LOS - local isAllyUnit = (allyTeam == myAllyTeamID) - --Spring.Echo("Gadget:FeatureCreated", featureID, FeatureDefs[Spring.GetFeatureDefID(featureID)].name, Script.LuaUI('FeatureCreated') , "isAllyUnit", isAllyUnit, "spec", spec, "specFullView", specFullView) - -- we need to check if any widget uses the callin, otherwise it is not bound and will produce error spam - if not isAllyUnit and (not (spec and specFullView)) and Script.LuaUI('FeatureCreated') then - --Spring.Echo("gadget:FeatureCreated",featureID, allyTeam) - scriptFeatureCreated(featureID, allyTeam) - end -end - -local scriptFeatureDestroyed = Script.LuaUI.FeatureDestroyed -function gadget:FeatureDestroyed(featureID, allyTeam) - -- assume that features are always in LOS - -- feauture allyTeam is equal to my allyteam when its a gaia feature, that is wierd - -- am i always allied with gaia? - local isAllyUnit = (allyTeam == myAllyTeamID) - --Spring.Echo("Gadget:FeatureDestroyed", featureID, FeatureDefs[Spring.GetFeatureDefID(featureID)].name, Script.LuaUI('FeatureDestroyed') , "isAllyUnit", isAllyUnit, "spec", spec, "specFullView", specFullView, allyTeam, Spring.GetMyTeamID()) - -- we need to check if any widget uses the callin, otherwise it is not bound and will produce error spam - if not isAllyUnit and (not (spec and specFullView)) and Script.LuaUI('FeatureDestroyed') then - --Spring.Echo("gadget:FeatureDestroyed",featureID, allyTeam) - scriptFeatureDestroyed(featureID, allyTeam) - end -end - -return gadget end)() --- Original call order: tracker updates visibility, then stock healthbar policy. --- All callback arguments originate in native admitted events, never browser UI. -local barsReady=false -for _,name in ipairs({'VisibleUnitAdded','VisibleUnitRemoved','VisibleUnitsChanged','FeatureReclaimStartedHealthbars','UnitCaptureStartedHealthbars','UnitParalyzeDamageHealthbars','ProjectileCreatedReloadHB'})do - listeners[name]=function(...) - if removed or not barsReady then return end - if name=='VisibleUnitAdded'then originalBuildAdded((...)) - elseif name=='VisibleUnitsChanged'then unitUniforms={};buildProgresses={};for id in pairs((...))do originalBuildAdded(id)end end - local result=bars[name](bars,...) - if name=='VisibleUnitRemoved'then local id=(...);unitUniforms[id]=nil;buildProgresses[id]=nil end - return result - end -end -for _,name in ipairs({'UnitCreated','UnitFinished','UnitDestroyed','UnitTaken','UnitGiven','UnitEnteredLos','UnitLeftLos'})do - _G[name]=function(...) - if name=='UnitFinished'then originalBuildFinished((...))end - tracker[name](tracker,...) - if name=='UnitDestroyed'then local id=(...);unitUniforms[id]=nil;buildProgresses[id]=nil end - end -end -for _,name in ipairs({'UnitDestroyed','UnitTaken','UnitGiven','UnitFinished','FeatureCreated','FeatureDestroyed'})do - listeners[name]=function(...)return _G[name](...)end -end -local widgetEventNames={UnitDestroyed=true,UnitTaken=true,UnitGiven=true,UnitFinished=true,FeatureCreated=true,FeatureDestroyed=true} -function WebbarHealthbarWidgetEvent(name,los,...) - assert(widgetEventNames[name],'Unknown original widget event') - assert(type(los)=='number'and los>=0 and los<=65535 and los%1==0,'Invalid native event LOS') - widgetEventUnit,widgetEventLos=(...),los - local ok,failure=pcall(widgetEvents[name],widgetEvents,...) - widgetEventUnit,widgetEventLos=nil,nil - if not ok then error(failure)end -end -function GameFrame(frame)originalBuildUpdated();tracker:GameFrame(frame);if not removed then bars:GameFrame(frame)end end -function PlayerChanged(player)widgetEvents:PlayerChanged(player);forward:PlayerChanged(player);tracker:PlayerChanged(player);if not removed then bars:PlayerChanged(player)end end -function UnitDamaged(id,definition,team,damage,paralyzer) - local publicDefinition=Spring.GetUnitDefID(id) - if publicDefinition then forward:UnitDamaged(id,publicDefinition,team,damage,paralyzer)end -end -function FeatureCreated(id,...)featureUniforms[id]=nil;if not removed and Spring.GetFeatureDefID(id)then bars:FeatureCreated(id,...)end end -function FeatureDestroyed(id,ally)forward:FeatureDestroyed(id,ally);if not removed then bars:FeatureDestroyed(id)end;featureUniforms[id]=nil end -function WebbarHealthbarSync(name,...) - local action=actions[name];if not action then return false end - -- Native event lists can include Gaia features outside this handle's reads. - -- Reject absent typed reads before the original forwarding body's callbacks. - if name=='featureReclaimFrame'and not Spring.GetFeatureDefID((...))then return false end - if name=='unitCaptureFrame'and not Spring.GetUnitDefID((...))then return false end - if name=='projetileCreatedReload'and not Spring.GetUnitDefID(select(2,...))then return false end - action(name,...);return true -end -function WebbarHealthbarInitialize() - widgetEvents:Initialize();forward:Initialize();tracker:Initialize() - for id in pairs(WG.unittrackerapi.visibleUnits)do originalBuildAdded(id)end - bars:Initialize();barsReady=true;return not removed -end -function WebbarHealthbarState() - local result={frame=Spring.GetGameFrame(),disabled=removed,rows={}} - if removed then return result end - for _,entry in ipairs({{'healthBarVBO',0},{'featureHealthVBO',1},{'featureResurrectVBO',2},{'featureReclaimVBO',3}})do - local buffer=assert(WG.VBOTableRegistry[entry[1]]);assert(buffer.instanceStep==20 and buffer.usedElements<=65536) - for i=1,buffer.usedElements do - local key,id=assert(buffer.indextoInstanceID[i]),nil - if entry[2]==0 then id=tonumber(key:match('^(%d+)_'))else id=key end - assert(type(id)=='number'and id>=0 and id%1==0) - local row={id=id,kind=entry[2],key=key,params={},uniforms={}} - local offset=(i-1)*20;for j=1,16 do row.params[j]=buffer.instanceData[offset+j]end - local data=(entry[2]==0 and unitUniforms or featureUniforms)[id] - for j=1,16 do row.uniforms[j]=data and data[j]or 0 end - local health,maxHealth - if entry[2]==0 then health,maxHealth=Spring.GetUnitHealth(id)else health,maxHealth=Spring.GetFeatureHealth(id)end - if health and maxHealth and maxHealth>0 then row.health={maxHealth,health} - elseif row.params[7]<20 then - -- No health read is published for hidden-damage units. This neutral pair - -- is unused by a non-health bar, whose original shader selects uniforms. - row.health={1,0} - end - if row.health then result.rows[#result.rows+1]=row end - end - end - assert(#result.rows<=65536);return result -end - - --- Optional original Orb Effects shares the stock Unit Tracker and the actual --- Healthbars GL4 userDefined[0].z storage. Shader compilation happens in the --- browser; this private native handle retains only original Lua policy. -local orb,orbReady -if webbarNativeOrbsEnabled == true then - GL.ELEMENT_ARRAY_BUFFER=34963 - gl.DepthTest=function()end;gl.DepthMask=function()end;gl.Culling=function()end - gl.LuaShader.GetEngineUniformBufferDefs=function()return '' end - setmetatable(gl.LuaShader,{__call=function(_,params,name) - assert(name=='orbShader GL4' and type(params.vertex)=='string' and type(params.fragment)=='string') - return {Initialize=function()return true end,Activate=function()end,Deactivate=function()end,SetUniform=function()end} - end}) - orb=(function()local widget={} --------------------------------------------------------------------------------- -local widget = widget ---@type Widget - -function widget:GetInfo() - return { - name = "Orb Effects GL4", - desc = "Pretty orbs for Fusions, Shields and Junos", - author = "Beherith, Shader by jK", - date = "2024.02.10", - license = "GNU GPL v2", - layer = -1, - enabled = true, - } -end - - --- Localized Spring API for performance -local spGetGameFrame = Spring.GetGameFrame -local spEcho = Spring.Echo - -local spGetUnitTeam = Spring.GetUnitTeam - - - - --------------------------------------------------------------------------------- --- Beherith's notes --------------------------------------------------------------------------------- --- TODO: --- [x] Add health-based brightening --- [x] Add shield based darkening --- [ ] Optimize shader --- [ ] Combine Effects of techniques --- [x] LightningOrb() TOO EXPENSIVE! - -- do multiple wraps, like 4 instead of 18 goddamn passes! --- [ ] Ensure SphereVBO indices to triangles are ordered bottom to top! --- [x] Draw order is incorrect, we are drawing after gadget's shield jitter - --------------------------------------------------------------------------------- --- Configuration --------------------------------------------------------------------------------- -local defaults = { - layer = -35, - life = 600, - light = 2.5, - repeatEffect = true, -} - -local corafusShieldSphere = table.merge(defaults, { - pos = { 0, 60, 0 }, - size = 32, - light = 4, - --colormap1 = { {0.9, 0.9, 1, 0.75},{0.9, 0.9, 1, 1.0},{0.9, 0.9, 1, 1.0},{0.9, 0.9, 1, 0.75} }, - --colormap2 = { {0.2, 0.2, 1, 0.7},{0.2, 0.2, 1, 0.75},{0.2, 0.2, 1, 0.75},{0.2, 0.2, 1, 0.7} }, -}) - -local corafust3ShieldSphere = table.merge(defaults, { - pos = { 0, 120, 0 }, - size = 64, - light = 8, - --colormap1 = { {0.9, 0.9, 1, 0.75},{0.9, 0.9, 1, 1.0},{0.9, 0.9, 1, 1.0},{0.9, 0.9, 1, 0.75} }, - --colormap2 = { {0.2, 0.2, 1, 0.7},{0.2, 0.2, 1, 0.75},{0.2, 0.2, 1, 0.75},{0.2, 0.2, 1, 0.7} }, -}) - -local armafusShieldSphere = table.merge(defaults, { - pos = { 0, 60, 0 }, - size = 28, - light = 4.25, - --colormap1 = { {0.9, 0.9, 1, 0.75},{0.9, 0.9, 1, 1.0},{0.9, 0.9, 1, 1.0},{0.9, 0.9, 1, 0.75} }, - --colormap2 = { {0.2, 0.2, 1, 0.7},{0.2, 0.2, 1, 0.75},{0.2, 0.2, 1, 0.75},{0.2, 0.2, 1, 0.7} }, -}) - -local armafust3ShieldSphere = table.merge(defaults, { - pos = { 0, 120, 0 }, - size = 56, - light = 8.5, - --colormap1 = { {0.9, 0.9, 1, 0.75},{0.9, 0.9, 1, 1.0},{0.9, 0.9, 1, 1.0},{0.9, 0.9, 1, 0.75} }, - --colormap2 = { {0.2, 0.2, 1, 0.7},{0.2, 0.2, 1, 0.75},{0.2, 0.2, 1, 0.75},{0.2, 0.2, 1, 0.7} }, -}) - -local legafusShieldSphere = table.merge(defaults, { - pos = { 0, 60, 0 }, - size = 36, - light = 4.25, - --colormap1 = { {0.9, 0.9, 1, 0.75},{0.9, 0.9, 1, 1.0},{0.9, 0.9, 1, 1.0},{0.9, 0.9, 1, 0.75} }, - --colormap2 = { {0.2, 0.2, 1, 0.7},{0.2, 0.2, 1, 0.75},{0.2, 0.2, 1, 0.75},{0.2, 0.2, 1, 0.7} }, -}) - -local legafust3ShieldSphere = table.merge(defaults, { - pos = { 0, 120, 0 }, - size = 72, - light = 8.5, - --colormap1 = { {0.9, 0.9, 1, 0.75},{0.9, 0.9, 1, 1.0},{0.9, 0.9, 1, 1.0},{0.9, 0.9, 1, 0.75} }, - --colormap2 = { {0.2, 0.2, 1, 0.7},{0.2, 0.2, 1, 0.75},{0.2, 0.2, 1, 0.75},{0.2, 0.2, 1, 0.7} }, -}) - -local corfusShieldSphere = table.merge(defaults, { - pos = { 0, 51, 0 }, - size = 23, - light = 3.25, - --colormap1 = { {0.9, 0.9, 1, 0.75},{0.9, 0.9, 1, 1.0},{0.9, 0.9, 1, 1.0},{0.9, 0.9, 1, 0.75} }, - --colormap2 = { {0.2, 0.6, 0.2, 0.4},{0.2, 0.6, 0.2, 0.45},{0.2, 0.6, 0.2, 0.45},{0.2, 0.6, 0.2, 0.4} }, -}) - -local legfusShieldSphere = table.merge(defaults, { - pos = { 0, 10, 0 }, - size = 23, - light = 3.25, - --colormap1 = { {0.9, 0.9, 1, 0.75},{0.9, 0.9, 1, 1.0},{0.9, 0.9, 1, 1.0},{0.9, 0.9, 1, 0.75} }, - --colormap2 = { {0.2, 0.6, 0.2, 0.4},{0.2, 0.6, 0.2, 0.45},{0.2, 0.6, 0.2, 0.45},{0.2, 0.6, 0.2, 0.4} }, -}) - - -local corgateShieldSphere = table.merge(defaults, { - pos = { 0, 42, 0 }, - size = 11, - colormap1 = { { 0.9, 0.9, 1, 0.75 }, { 0.9, 0.9, 1, 1.0 }, { 0.9, 0.9, 1, 1.0 }, { 0.9, 0.9, 1, 0.75 } }, - colormap2 = { { 0.2, 0.6, 0.2, 0.4 }, { 0.2, 0.6, 0.2, 0.45 }, { 0.2, 0.6, 0.2, 0.45 }, { 0.2, 0.6, 0.2, 0.4 } }, - isShield = true, -}) - -local corgatet3ShieldSphere = table.merge(defaults, { - pos = { 0, 75, -1 }, - size = 18, - colormap1 = { { 0.9, 0.9, 1, 0.75 }, { 0.9, 0.9, 1, 1.0 }, { 0.9, 0.9, 1, 1.0 }, { 0.9, 0.9, 1, 0.75 } }, - colormap2 = { { 0.2, 0.6, 0.2, 0.4 }, { 0.2, 0.6, 0.2, 0.45 }, { 0.2, 0.6, 0.2, 0.45 }, { 0.2, 0.6, 0.2, 0.4 } }, - isShield = true, -}) - -local armjunoShieldSphere = table.merge(defaults, { - pos = { 0, 72, 0 }, - size = 13, - colormap1 = { { 0.9, 0.9, 1, 0.75 }, { 0.9, 0.9, 1, 1.0 }, { 0.9, 0.9, 1, 1.0 }, { 0.9, 0.9, 1, 0.75 } }, - colormap2 = { { 0.8, 0.2, 0.2, 0.4 }, { 0.8, 0.2, 0.2, 0.45 }, { 0.9, 0.2, 0.2, 0.45 }, { 0.9, 0.1, 0.2, 0.4 } }, -}) - -local legjunoShieldSphere = table.merge(defaults, { - pos = { 0, 69, 0 }, - size = 9, - colormap1 = { { 0.9, 0.9, 1, 0.75 }, { 0.9, 0.9, 1, 1.0 }, { 0.9, 0.9, 1, 1.0 }, { 0.9, 0.9, 1, 0.75 } }, - colormap2 = { { 0.8, 0.2, 0.2, 0.4 }, { 0.8, 0.2, 0.2, 0.45 }, { 0.9, 0.2, 0.2, 0.45 }, { 0.9, 0.1, 0.2, 0.4 } }, -}) - -local corjunoShieldSphere = table.merge(defaults, { - pos = { 0, 72, 0 }, - size = 13, - colormap1 = { { 0.9, 0.9, 1, 0.75 }, { 0.9, 0.9, 1, 1.0 }, { 0.9, 0.9, 1, 1.0 }, { 0.9, 0.9, 1, 0.75 } }, - colormap2 = { { 0.8, 0.2, 0.2, 0.4 }, { 0.8, 0.2, 0.2, 0.45 }, { 0.9, 0.2, 0.2, 0.45 }, { 0.9, 0.1, 0.2, 0.4 } }, -}) - -local armgateShieldSphere = table.merge(defaults, { - pos = { 0, 23.5, -5 }, - size = 14.5, - colormap1 = { { 0.9, 0.9, 1, 0.75 }, { 0.9, 0.9, 1, 1.0 }, { 0.9, 0.9, 1, 1.0 }, { 0.9, 0.9, 1, 0.75 } }, - colormap2 = { { 0.2, 0.6, 0.2, 0.4 }, { 0.2, 0.6, 0.2, 0.45 }, { 0.2, 0.6, 0.2, 0.45 }, { 0.2, 0.6, 0.2, 0.4 } }, - isShield = true, -}) - -local armgatet3ShieldSphere = table.merge(defaults, { - pos = { 0, 42, -6 }, - size = 20, - colormap1 = { { 0.9, 0.9, 1, 0.75 }, { 0.9, 0.9, 1, 1.0 }, { 0.9, 0.9, 1, 1.0 }, { 0.9, 0.9, 1, 0.75 } }, - colormap2 = { { 0.2, 0.6, 0.2, 0.4 }, { 0.2, 0.6, 0.2, 0.45 }, { 0.2, 0.6, 0.2, 0.45 }, { 0.2, 0.6, 0.2, 0.4 } }, - isShield = true, -}) -local leggatet3ShieldSphere = table.merge(defaults, { - pos = { 0, 45, 0 }, - size = 18, - colormap1 = { { 0.9, 0.9, 1, 0.75 }, { 0.9, 0.9, 1, 1.0 }, { 0.9, 0.9, 1, 1.0 }, { 0.9, 0.9, 1, 0.75 } }, - colormap2 = { { 0.2, 0.6, 0.2, 0.4 }, { 0.2, 0.6, 0.2, 0.45 }, { 0.2, 0.6, 0.2, 0.45 }, { 0.2, 0.6, 0.2, 0.4 } }, - isShield = true, -}) - -local legdeflectorShieldSphere = table.merge(defaults, { - pos = { 0, 21, 0 }, - size = 12, - colormap1 = { { 0.9, 0.9, 1, 0.75 }, { 0.9, 0.9, 1, 1.0 }, { 0.9, 0.9, 1, 1.0 }, { 0.9, 0.9, 1, 0.75 } }, - colormap2 = { { 0.2, 0.6, 0.2, 0.4 }, { 0.2, 0.6, 0.2, 0.45 }, { 0.2, 0.6, 0.2, 0.45 }, { 0.2, 0.6, 0.2, 0.4 } }, - isShield = true, -}) - -local UnitEffects = { - ["armjuno"] = { - { class = 'ShieldSphere', options = armjunoShieldSphere }, - { class = 'ShieldJitter', options = { life = math.huge, pos = { 0, 72, 0 }, size = 14, precision = 22, repeatEffect = true } }, - }, - ["legjuno"] = { - { class = 'ShieldSphere', options = legjunoShieldSphere }, - { class = 'ShieldJitter', options = { life = math.huge, pos = { 0, 72, 0 }, size = 14, precision = 22, repeatEffect = true } }, - }, - ["corjuno"] = { - { class = 'ShieldSphere', options = corjunoShieldSphere }, - { class = 'ShieldJitter', options = { life = math.huge, pos = { 0, 72, 0 }, size = 14, precision = 22, repeatEffect = true } }, - }, - - --// FUSIONS //-------------------------- - ["corafus"] = { - { class = 'ShieldSphere', options = corafusShieldSphere }, - { class = 'ShieldJitter', options = { layer = -16, life = math.huge, pos = { 0, 60, 0 }, size = 32.5, precision = 22, repeatEffect = true } }, - }, - ["corfus"] = { - { class = 'ShieldSphere', options = corfusShieldSphere }, - { class = 'ShieldJitter', options = { life = math.huge, pos = { 0, 50, 0 }, size = 23.5, precision = 22, repeatEffect = true } }, - }, - ["legfus"] = { - { class = 'ShieldSphere', options = legfusShieldSphere }, - { class = 'ShieldJitter', options = { life = math.huge, pos = { 0, 19, 0 }, size = 23.5, precision = 22, repeatEffect = true } }, - }, - ["armafus"] = { - { class = 'ShieldSphere', options = armafusShieldSphere }, - { class = 'ShieldJitter', options = { layer = -16, life = math.huge, pos = { 0, 60, 0 }, size = 28.5, precision = 22, repeatEffect = true } }, - }, - ["legafus"] = { - { class = 'ShieldSphere', options = legafusShieldSphere }, - { class = 'ShieldJitter', options = { layer = -16, life = math.huge, pos = { 0, 60, 0 }, size = 38.5, precision = 22, repeatEffect = true } }, - }, - ["armafust3"] = { - { class = 'ShieldSphere', options = armafust3ShieldSphere }, - { class = 'ShieldJitter', options = { layer = -16, life = math.huge, pos = { 0, 120, 0 }, size = 57, precision = 22, repeatEffect = true } }, - }, - ["corafust3"] = { - { class = 'ShieldSphere', options = corafust3ShieldSphere }, - { class = 'ShieldJitter', options = { layer = -16, life = math.huge, pos = { 0, 120, 0 }, size = 65, precision = 22, repeatEffect = true } }, - }, - ["legafust3"] = { - { class = 'ShieldSphere', options = legafust3ShieldSphere }, - { class = 'ShieldJitter', options = { layer = -16, life = math.huge, pos = { 0, 120, 0 }, size = 77, precision = 22, repeatEffect = true } }, - }, - ["resourcecheat"] = { - { class = 'ShieldSphere', options = armafusShieldSphere }, - { class = 'ShieldJitter', options = { layer = -16, life = math.huge, pos = { 0, 60, 0 }, size = 28.5, precision = 22, repeatEffect = true } }, - }, - ["corgate"] = { - { class = 'ShieldJitter', options = { delay = 0, life = math.huge, pos = { 0, 42, 0 }, size = 12, precision = 22, repeatEffect = true , isShiedl } }, - { class = 'ShieldSphere', options = corgateShieldSphere }, - --{class='ShieldJitter', options={delay=0,life=math.huge, pos={0,42,0.0}, size=555, precision=0, strength= 0.001, repeatEffect=true}}, - --{class='ShieldJitter',options={life=math.huge, pos={0,42,0}, size=20, precision=2, repeatEffect=true}}, - }, - ["corgatet3"] = { - { class = 'ShieldJitter', options = { delay = 0, life = math.huge, pos = { 0, 75, 0 }, size = 18, precision = 22, repeatEffect = true , isShiedl } }, - { class = 'ShieldSphere', options = corgatet3ShieldSphere }, - --{class='ShieldJitter', options={delay=0,life=math.huge, pos={0,42,0.0}, size=555, precision=0, strength= 0.001, repeatEffect=true}}, - --{class='ShieldJitter',options={life=math.huge, pos={0,42,0}, size=20, precision=2, repeatEffect=true}}, - }, - ["corfgate"] = { - { class = 'ShieldJitter', options = { delay = 0, life = math.huge, pos = { 0, 42, 0 }, size = 12, precision = 22, repeatEffect = true } }, - { class = 'ShieldSphere', options = corgateShieldSphere }, - --{class='ShieldJitter', options={delay=0,life=math.huge, pos={0,42,0.0}, size=555, precision=0, strength= 0.001, repeatEffect=true}}, - --{class='ShieldJitter',options={life=math.huge, pos={0,42,0}, size=20, precision=2, repeatEffect=true}}, - }, - ["armgate"] = { - { class = 'ShieldJitter', options = { delay = 0, life = math.huge, pos = { 0, 20, -5 }, size = 15, precision = 22, repeatEffect = true } }, - { class = 'ShieldSphere', options = armgateShieldSphere }, - --{class='ShieldJitter', options={delay=0,life=math.huge, pos={0,23.5,-5}, size=555, precision=0, strength=0.001, repeatEffect=true}}, - }, - ["armgatet3"] = { - { class = 'ShieldJitter', options = { delay = 0, life = math.huge, pos = { 0, 37, -5 }, size = 21, precision = 22, repeatEffect = true } }, - { class = 'ShieldSphere', options = armgatet3ShieldSphere }, - --{class='ShieldJitter', options={delay=0,life=math.huge, pos={0,23.5,-5}, size=555, precision=0, strength=0.001, repeatEffect=true}}, - }, - ["leggatet3"] = { - { class = 'ShieldJitter', options = { delay = 0, life = math.huge, pos = { 0, 45, 0 }, size = 20, precision = 22, repeatEffect = true } }, - { class = 'ShieldSphere', options = leggatet3ShieldSphere }, - --{class='ShieldJitter', options={delay=0,life=math.huge, pos={0,23.5,-5}, size=555, precision=0, strength=0.001, repeatEffect=true}}, - }, - ["armfgate"] = { - { class = 'ShieldJitter', options = { delay = 0, life = math.huge, pos = { 0, 25, 0 }, size = 15, precision = 22, repeatEffect = true } }, - { class = 'ShieldSphere', options = table.merge(armgateShieldSphere, { pos = { 0, 25, 0 } }) }, - --{class='ShieldJitter', options={delay=0,life=math.huge, pos={0,25,0}, size=555, precision=0, strength= 0.001, repeatEffect=true}}, - }, - ["legdeflector"] = { - { class = 'ShieldJitter', options = { delay = 0, life = math.huge, pos = { 0, 20, -5 }, size = 15, precision = 22, repeatEffect = true } }, - { class = 'ShieldSphere', options = legdeflectorShieldSphere }, - --{class='ShieldJitter', options={delay=0,life=math.huge, pos={0,23.5,-5}, size=555, precision=0, strength=0.001, repeatEffect=true}}, - }, - ["lootboxbronze"] = { - { class = 'ShieldSphere', options = table.merge(corfusShieldSphere, {pos = { 0, 34, 0 }, size = 10} ) }, - { class = 'ShieldJitter', options = { life = math.huge, pos = { 0, 34, 0 }, size = 10.5, precision = 22, repeatEffect = true } }, - }, - ["lootboxsilver"] = { - { class = 'ShieldSphere', options = table.merge(corfusShieldSphere, {pos = { 0, 52, 0 }, size = 15} ) }, - { class = 'ShieldJitter', options = { life = math.huge, pos = { 0, 52, 0 }, size = 15.5, precision = 22, repeatEffect = true } }, - }, - ["lootboxgold"] = { - { class = 'ShieldSphere', options = table.merge(corfusShieldSphere, {pos = { 0, 69, 0 }, size = 20} ) }, - { class = 'ShieldJitter', options = { life = math.huge, pos = { 0, 69, 0 }, size = 20.5, precision = 22, repeatEffect = true } }, - }, - ["lootboxplatinum"] = { - { class = 'ShieldSphere', options = table.merge(corfusShieldSphere, {pos = { 0, 87, 0 }, size = 25} ) }, - { class = 'ShieldJitter', options = { life = math.huge, pos = { 0, 87, 0 }, size = 25.5, precision = 22, repeatEffect = true } }, - }, - -} - -local scavEffects = {} -if UnitDefNames['armcom_scav'] then - for k, effect in pairs(UnitEffects) do - scavEffects[k .. '_scav'] = effect - if scavEffects[k .. '_scav'].options then - if scavEffects[k .. '_scav'].options.color then - scavEffects[k .. '_scav'].options.color = { 0.92, 0.32, 1.0 } - end - if scavEffects[k .. '_scav'].options.colormap then - scavEffects[k .. '_scav'].options.colormap = { { 0.92, 0.32, 1.0 } } - end - if scavEffects[k .. '_scav'].options.colormap1 then - scavEffects[k .. '_scav'].options.colormap1 = { { 0.92, 0.32, 1.0 } } - end - if scavEffects[k .. '_scav'].options.colormap2 then - scavEffects[k .. '_scav'].options.colormap2 = { { 0.92, 0.32, 1.0 } } - end - end - end - for k, effect in pairs(scavEffects) do - UnitEffects[k] = effect - end - scavEffects = nil -end - -local orbUnitDefs = {} - - -for unitname, effect in pairs(UnitEffects) do - if UnitDefNames[unitname] then - for _, effectdef in ipairs(effect) do - if effectdef.class == "ShieldSphere" then - local attr = {} - local opts = effectdef.options - --orbUnitDefs[UnitDefNames[unitname].id] = - attr[1], attr[2], attr[3] = unpack(opts.pos) - attr[4] = opts.size - - attr[5] = 1 -- margin - attr[6] = 0 -- precision - attr[7] = (opts.isShield and 1) or 0 -- isShield - attr[8] = 1 -- technique - - attr[ 9], attr[10], attr[11], attr[12] = unpack((opts.colormap1 and opts.colormap1[1]) or {-1,-1,-1,-1}) - attr[13], attr[14], attr[15], attr[16] = unpack((opts.colormap2 and opts.colormap2[1]) or {-1,-1,-1,-1}) - - attr[17], attr[18], attr[19], attr[20] = 0, 0, 0, 0 -- padding for instData - orbUnitDefs[UnitDefNames[unitname].id] = attr - end - end - end -end - -UnitEffects = nil - --------------------------------------------------------------------------------- --- Variables --------------------------------------------------------------------------------- - -local orbVBO = nil -local orbShader = nil - -local LuaShader = gl.LuaShader -local InstanceVBOTable = gl.InstanceVBOTable - -local popElementInstance = InstanceVBOTable.popElementInstance -local pushElementInstance = InstanceVBOTable.pushElementInstance -local drawInstanceVBO = InstanceVBOTable.drawInstanceVBO - -local vsSrc = -[[ -#version 420 -#extension GL_ARB_uniform_buffer_object : require -#extension GL_ARB_shader_storage_buffer_object : require -#extension GL_ARB_shading_language_420pack: require -#line 10000 - -layout (location = 0) in vec3 position; -layout (location = 1) in vec3 normals; -layout (location = 2) in vec2 uvs; - -layout (location = 3) in vec4 posrad; // time is gameframe spawned :D -layout (location = 4) in vec4 margin_teamID_shield_technique; -layout (location = 5) in vec4 color1; -layout (location = 6) in vec4 color2; -layout (location = 7) in uvec4 instData; // unitID, teamID, ?? - -out DataVS { - vec4 color1_vs; - //flat vec4 color2_vs; - float unitID_vs; - flat float gameFrame_vs; - flat int technique_vs; - float opac_vs; - vec4 modelPos_vs; -}; - -//__ENGINEUNIFORMBUFFERDEFS__ - -struct SUniformsBuffer { - uint composite; // u8 drawFlag; u8 unused1; u16 id; - - uint unused2; - uint unused3; - uint unused4; - - float maxHealth; - float health; - float unused5; - float unused6; - - vec4 drawPos; - vec4 speed; - vec4[4] userDefined; //can't use float[16] because float in arrays occupies 4 * float space -}; - -layout(std140, binding=1) readonly buffer UniformsBuffer { - SUniformsBuffer uni[]; -}; - - -uniform float reflectionPass = 0.0; - -#line 10468 -void main() -{ - if ((uni[instData.y].composite & 0x00000003u) < 1u ) { // not drawn - // Ivand's recommendation is to place vertices outside of NDC space: - gl_Position = vec4(2.0,2.0,2.0,1.0); - return; - } - - vec3 modelWorldPos = uni[instData.y].drawPos.xyz;// + vec3(100,100,100); - unitID_vs = 0.1 + float(uni[instData.y].composite >> 16 ) / 256000.0; - - float modelRot = uni[instData.y].drawPos.w; - mat3 rotY = rotation3dY(modelRot); - - vec4 vertexWorldPos = vec4(1); - vec3 flippedPos = vec3(1,-1,1) * position.xzy; - - - float radius = 0.99 * posrad.w; - float startFrame = margin_teamID_shield_technique.x; - //float lifeScale = clamp(((timeInfo.x + timeInfo.w) - startFrame) / 100.0, 0.001, 1.0); - float lifeScale = 1.0 - exp(-0.10 * ((timeInfo.x + timeInfo.w) - startFrame)); - radius *= lifeScale; - radius += (sin(timeInfo.z)) - 1.0; - - vertexWorldPos.xyz = rotY * ( flippedPos * (radius) + posrad.xyz + vec3(0,0,0) ) + modelWorldPos; - if (reflectionPass < 0.5){ - gl_Position = cameraViewProj * vertexWorldPos; - }else{ - gl_Position = reflectionViewProj * vertexWorldPos; - } - - - - mat3 normalMatrix = mat3( cameraView[0].xyz, cameraView[1].xyz, cameraView[2].xyz); - - vec3 normal = (rotY * normals.xzy); - normal.y *= -1; - vec3 camPos = cameraViewInv[3].xyz; - vec3 camToWorldPos = normalize(cameraViewInv[3].xyz - vertexWorldPos.xyz); - //vec3 vertex = vec3(gl_ModelViewMatrix * gl_Vertex); - color1_vs.rgb = camToWorldPos.xyz; - float angle = dot(normal,camToWorldPos); //*inversesqrt( dot(normal,normal)*dot(position,position) ); //dot(norm(n),norm(v)) - opac_vs = pow( abs( angle ) , 1.0); - //opac_vs = 1.0; - //color1_vs.rgb = vec3(angle); - - vec4 color2_vs; - if (color1.r < 0) { // negative numbers mean teamcolor - vec4 teamcolor = teamColor[int(margin_teamID_shield_technique.y)]; - // ShieldSphereParticle.Default.colormap1 = {{(r*0.45)+0.3, (g*0.45)+0.3, (b*0.45)+0.3, 0.6}} - //ShieldSphereParticle.Default.colormap2 = {{r*0.5, g*0.5, b*0.5, 0.66} } - color1_vs = vec4(teamcolor.rgb, 0.5); - color1_vs.rgb = color1_vs.rgb * 0.45 + 0.3; - color2_vs = vec4(teamcolor.rgb, 0.66); - color2_vs.rgb = color2_vs.rgb * 0.5; - }else{ // base color - color1_vs = color1; - color2_vs = color2; - } - - color1_vs = mix(color1_vs, color2_vs, opac_vs); - - if (margin_teamID_shield_technique.z > 0.5){ - float shieldPower = clamp(uni[instData.y].userDefined[0].z, 0, 1); - color1_vs = mix(vec4(0.8,0.4, 0,1.0),color1_vs, shieldPower); - } - - float relHealth = clamp(uni[instData.y].health/uni[instData.y].maxHealth, 0, 1); - //color1_vs.rgb *= 1.0 + relHealth; - - - modelPos_vs = vec4(position.xzy*posrad.w, 0); - //modelPos_vs.z = fract(modelPos_vs.z * 10); - modelPos_vs.w = relHealth; - gameFrame_vs = timeInfo.z; - - technique_vs = int(floor(margin_teamID_shield_technique.w)); - - // fix issue for amd/linux when drawing to DrawWorldPreParticles - // https://github.com/beyond-all-reason/RecoilEngine/issues/2791 - gl_ClipDistance[0] = 1.0; - gl_ClipDistance[1] = 1.0; - gl_ClipDistance[2] = 1.0; -} -]] - -local fsSrc = -[[ -#version 420 -#extension GL_ARB_uniform_buffer_object : require -#extension GL_ARB_shading_language_420pack: require -#line 20000 -uniform sampler2D noiseMap; -uniform sampler2D mask; - -//__ENGINEUNIFORMBUFFERDEFS__ - -uniform float reflectionPass = 0.0; - -#define DISTORTION 0.01 -in DataVS { - vec4 color1_vs; - float unitID_vs; - flat float gameFrame_vs; - flat int technique_vs; - float opac_vs; - vec4 modelPos_vs; -}; - -out vec4 fragColor; - - const float PI = acos(0.0) * 2.0; - - float hash13(vec3 p3) { - const float HASHSCALE1 = 44.38975; - p3 = fract(p3 * HASHSCALE1); - p3 += dot(p3, p3.yzx + 19.19); - return fract((p3.x + p3.y) * p3.z); - } - - float noise12(vec2 p){ - vec2 ij = floor(p); - vec2 xy = fract(p); - xy = 3.0 * xy * xy - 2.0 * xy * xy * xy; - //xy = 0.5 * (1.0 - cos(PI * xy)); - float a = hash13(vec3(ij + vec2(0.0, 0.0), unitID_vs)); - float b = hash13(vec3(ij + vec2(1.0, 0.0), unitID_vs)); - float c = hash13(vec3(ij + vec2(0.0, 1.0), unitID_vs)); - float d = hash13(vec3(ij + vec2(1.0, 1.0), unitID_vs)); - float x1 = mix(a, b, xy.x); - float x2 = mix(c, d, xy.x); - return mix(x1, x2, xy.y); - } - - float noise13( vec3 P ) { - // https://github.com/BrianSharpe/Wombat/blob/master/Perlin3D.glsl - - // establish our grid cell and unit position - vec3 Pi = floor(P); - vec3 Pf = P - Pi; - vec3 Pf_min1 = Pf - 1.0; - - // clamp the domain - Pi.xyz = Pi.xyz - floor(Pi.xyz * ( 1.0 / 69.0 )) * 69.0; - vec3 Pi_inc1 = step( Pi, vec3( 69.0 - 1.5 ) ) * ( Pi + 1.0 ); - - // calculate the hash - vec4 Pt = vec4( Pi.xy, Pi_inc1.xy ) + vec2( 50.0, 161.0 ).xyxy; - Pt *= Pt; - Pt = Pt.xzxz * Pt.yyww; - const vec3 SOMELARGEFLOATS = vec3( 635.298681, 682.357502, 668.926525 ); - const vec3 ZINC = vec3( 48.500388, 65.294118, 63.934599 ); - vec3 lowz_mod = vec3( 1.0 / ( SOMELARGEFLOATS + Pi.zzz * ZINC ) ); - vec3 highz_mod = vec3( 1.0 / ( SOMELARGEFLOATS + Pi_inc1.zzz * ZINC ) ); - vec4 hashx0 = fract( Pt * lowz_mod.xxxx ); - vec4 hashx1 = fract( Pt * highz_mod.xxxx ); - vec4 hashy0 = fract( Pt * lowz_mod.yyyy ); - vec4 hashy1 = fract( Pt * highz_mod.yyyy ); - vec4 hashz0 = fract( Pt * lowz_mod.zzzz ); - vec4 hashz1 = fract( Pt * highz_mod.zzzz ); - - // calculate the gradients - vec4 grad_x0 = hashx0 - 0.49999; - vec4 grad_y0 = hashy0 - 0.49999; - vec4 grad_z0 = hashz0 - 0.49999; - vec4 grad_x1 = hashx1 - 0.49999; - vec4 grad_y1 = hashy1 - 0.49999; - vec4 grad_z1 = hashz1 - 0.49999; - vec4 grad_results_0 = inversesqrt( grad_x0 * grad_x0 + grad_y0 * grad_y0 + grad_z0 * grad_z0 ) * ( vec2( Pf.x, Pf_min1.x ).xyxy * grad_x0 + vec2( Pf.y, Pf_min1.y ).xxyy * grad_y0 + Pf.zzzz * grad_z0 ); - vec4 grad_results_1 = inversesqrt( grad_x1 * grad_x1 + grad_y1 * grad_y1 + grad_z1 * grad_z1 ) * ( vec2( Pf.x, Pf_min1.x ).xyxy * grad_x1 + vec2( Pf.y, Pf_min1.y ).xxyy * grad_y1 + Pf_min1.zzzz * grad_z1 ); - - // Classic Perlin Interpolation - vec3 blend = Pf * Pf * Pf * (Pf * (Pf * 6.0 - 15.0) + 10.0); - vec4 res0 = mix( grad_results_0, grad_results_1, blend.z ); - vec4 blend2 = vec4( blend.xy, vec2( 1.0 - blend.xy ) ); - float final = dot( res0, blend2.zxzx * blend2.wwyy ); - return ( final * 1.1547005383792515290182975610039 ); // scale things to a strict -1.0->1.0 range *= 1.0/sqrt(0.75) - } - - float Fbm12(vec2 P) { - const int octaves = 4; - const float lacunarity = 1.8; - const float gain = 0.80; - - float sum = 0.0; - float amp = 0.8; - vec2 pp = P; - - int i; - - for(i = 0; i < octaves; ++i) - { - amp *= gain; - sum += amp * noise12(pp); - pp *= lacunarity; - } - return sum; - } - - float Fbm31Magic(vec3 p) { - float v = 0.0; - v += noise13(p * 1.0) * 2.200; - v -= noise13(p * 4.0) * 3.125; - return v; - } - - float Fbm31Electro(vec3 p) { - float v = 0.0; - v += noise13(p * 0.9) * 0.99; - v += noise13(p * 3.99) * 0.49; - v += noise13(p * 8.01) * 0.249; - v += noise13(p * 25.05) * 0.124; - return v; - } - - #define SNORM2NORM(value) (value * 0.5 + 0.5) - #define NORM2SNORM(value) (value * 2.0 - 1.0) - - float orbTime; // per-unit offset time, set in main() before any function calls - #define time orbTime - - vec3 LightningOrb(vec2 vUv, vec3 color) { - vec2 uv = NORM2SNORM(vUv); - - const float strength = 0.01; - const float dx = 0.2; - - float t = 0.0; - - for (int k = -4; k < 14; ++k) { - vec2 thisUV = uv; - thisUV.x -= dx * float(k); - thisUV.y += float(k); - t += abs(strength / ((thisUV.x + Fbm12( thisUV + time )))); - } - - return color * t; - } - -float mirroredRepeat(float x, float repeats) { - x *= repeats; - float i = floor(x); - float f = fract(x); - // If i is odd, mirror the fractional part - if (mod(i, 2.0) == 1.0) { - f = 1.0 - f; - } - return f; -} - -vec3 LightningOrb2(vec2 vUv, vec3 color) { - - // Example: NO fract(), but still repeating: - // vUv.x *= 3.0; - - // Or: mirror repeat for 2 tiles - vUv.x = mirroredRepeat(vUv.x, 2.0); - - // Animated surface distortion - warp UVs with slow turbulent noise - vec2 distortUV = vUv * 3.0 + vec2(time * 0.3, time * 0.17); - vUv.x += Fbm12(distortUV) * 0.04; - vUv.y += Fbm12(distortUV + vec2(7.3, 3.1)) * 0.03; - - // From here on, continue as you did before: - vec2 uv = NORM2SNORM(vUv); - - float violence = (1 - modelPos_vs.w); - const float strength = 0.06 + 0.3 * violence; - const float dx = 0.16; - - float t = 0.1; - for (int k = -4; k < 5; ++k) { - vec2 thisUV = uv; - thisUV.x -= dx * float(k); - thisUV.y += 2.0 * float(k); - vec2 fbmUV = vec2(thisUV.x * 1.0 + time, thisUV.y + 0.3 * time); - - // Your fract()-free or tiled/noise logic remains the same here: - t += abs(strength / (thisUV.x + (3.0 * Fbm12(fbmUV) - 1.9))); - } - - return color * t; -} - - - - vec3 MagicOrb(vec3 noiseVec, vec3 color) { - float t = 0.0; - - for( int i = 1; i < 2; ++i ) { - t = abs(2.0 / ((noiseVec.y + Fbm31Magic( noiseVec + 0.5 * time / float(i)) ) * 75.0)); - t += 1.3 * float(i); - } - return color * t; - } - - vec3 ElectroOrb(vec3 noiseVec, vec3 color) { - float t = 0.0; - - for( int i = 0; i < 5; ++i ) { - noiseVec = noiseVec.zyx; - t = abs(2.0 / (Fbm31Electro(noiseVec + vec3(0.0, time / float(i + 1), 0.0)) * 120.0)); - t += 0.2 * float(i + 1); - } - - return color * t; - } - - // Returns the X coords (around the belly) as [0-1], the Y coords as down-up [0-1] - vec2 RadialCoords(vec3 a_coords) - { - vec3 a_coords_n = normalize(a_coords); - float lon = atan(a_coords_n.z, a_coords_n.x); - float lat = acos(a_coords_n.y); - vec2 sphereCoords = vec2(lon, lat) / PI; - return vec2(sphereCoords.x * 0.5 + 0.5, 1.0 - sphereCoords.y); - } - - vec3 RotAroundY(vec3 p) - { - float ra = -time * 0.5; - mat4 tr = mat4(cos(ra), 0.0, sin(ra), 0.0, - 0.0, 1.0, 0.0, 0.0, - -sin(ra), 0.0, cos(ra), 0.0, - 0.0, 0.0, 0.0, 1.0); - - return (tr * vec4(p, 1.0)).xyz; - } - -void main(void) -{ - // Per-unit time offset so orbs don't animate in sync - float unitPhase = fract(unitID_vs * 1337.7); - orbTime = gameFrame_vs + unitPhase * 120.0; - - fragColor = color1_vs; - - //modelPos_vs contains the sphere's coords. - - if (technique_vs == 1) { // LightningOrb - vec3 noiseVec = modelPos_vs.xyz; - noiseVec = RotAroundY(noiseVec); - vec3 nDir = normalize(noiseVec); - - // Primary projection (poles at top/bottom of sphere) - vec2 vUv = RadialCoords(noiseVec); - vec3 baseColor = fragColor.rgb; - vec3 col = LightningOrb2(vUv, baseColor); - - // Near the poles, blend in a second projection rotated 90° around X - // so its pole singularity is at the equator of the primary projection - float poleFade = abs(nDir.y); - if (poleFade > 0.45) { - vec3 rotatedVec = vec3(noiseVec.x, -noiseVec.z, noiseVec.y); - vec2 vUv2 = RadialCoords(rotatedVec); - vec3 col2 = LightningOrb2(vUv2, baseColor); - float blendWeight = smoothstep(0.45, 0.85, poleFade); - col = mix(col, col2, blendWeight); - } - - // Color variation - bright white on arc peaks, base color in gaps - float arcIntensity = clamp(length(col) / (length(baseColor) + 0.001), 0.0, 3.0) / 3.0; - vec3 hotColor = mix(baseColor, vec3(1.0), 0.35); - col = mix(col, col * hotColor / (baseColor + 0.001), arcIntensity); - - // Rim glow - bright edge halo - float rim = pow(1.0 - opac_vs, 2.5); - col += baseColor * rim * 0.8; - - // Inner core glow - bright volumetric center - float core = pow(opac_vs, 2.0); - col += baseColor * core * 0.6; - - // Pulse / breathing brightness - float pulse = 1.0 + 0.08 * sin(time * 2.3) + 0.05 * sin(time * 5.7); - col *= pulse; - - fragColor.rgba = vec4(col, 1.0) * 1.2; return; - //fragColor.rgb = max(fragColor.rgb, col * col); - //fragColor.rgb = max(fragColor.rgb, col * 2); - } - else if (technique_vs == 2) { // MagicOrb - vec3 noiseVec = modelPos_vs.xyz; - noiseVec = RotAroundY(noiseVec); - vec3 baseColor = fragColor.rgb; - vec3 col = MagicOrb(noiseVec, baseColor); - fragColor.rgb = max(baseColor, col * col); - - float rim = pow(1.0 - opac_vs, 2.5); - fragColor.rgb += baseColor * rim * 0.8; - float core = pow(opac_vs, 2.0); - fragColor.rgb += baseColor * core * 0.6; - - float pulse = 1.0 + 0.08 * sin(time * 2.3) + 0.05 * sin(time * 5.7); - fragColor.rgb *= pulse; - } - else if (technique_vs == 3) { // ElectroOrb - vec3 noiseVec = modelPos_vs.xyz; - noiseVec = RotAroundY(noiseVec); - vec3 baseColor = fragColor.rgb; - vec3 col = ElectroOrb(noiseVec, baseColor); - fragColor.rgb = max(baseColor, col * col); - - float rim = pow(1.0 - opac_vs, 2.5); - fragColor.rgb += baseColor * rim * 0.8; - float core = pow(opac_vs, 2.0); - fragColor.rgb += baseColor * core * 0.6; - - float pulse = 1.0 + 0.08 * sin(time * 2.3) + 0.05 * sin(time * 5.7); - fragColor.rgb *= pulse; - } - - fragColor.a = length(fragColor.rgb); - if (reflectionPass > 0) fragColor.rgba *= 3.0; - //fragColor.rgba = vec4(1.0); - //fragColor.rgb = modelPos_vs.xyz; - //fragColor.rgba = vec4(opac_vs,opac_vs, opac_vs, 1.0); - //fragColor.rgb = color1_vs.rgb; -} -]] - -local function goodbye(reason) - spEcho("Orb GL4 widget exiting with reason: "..reason) - widgetHandler:RemoveWidget() -end - -local function initGL4() - - local engineUniformBufferDefs = LuaShader.GetEngineUniformBufferDefs() - vsSrc = vsSrc:gsub("//__ENGINEUNIFORMBUFFERDEFS__", engineUniformBufferDefs) - fsSrc = fsSrc:gsub("//__ENGINEUNIFORMBUFFERDEFS__", engineUniformBufferDefs) - orbShader = LuaShader( - { - vertex = vsSrc, - fragment = fsSrc, - uniformInt = { - noiseMap = 0, - mask = 1, - }, - uniformFloat = { - reflectionPass = 0.0, - }, - }, - "orbShader GL4" - ) - shaderCompiled = orbShader:Initialize() - if not shaderCompiled then goodbye("Failed to compile orbShader GL4 ") end - local sphereVBO, numVerts, sphereIndexVBO, numIndices = InstanceVBOTable.makeSphereVBO(32,24,1) - --spEcho("SphereVBO has", numVerts, "vertices and ", numIndices,"indices") - local orbVBOLayout = { - {id = 3, name = 'posrad', size = 4}, -- widthlength - {id = 4, name = 'margin_teamID_shield_technique', size = 4}, -- emit dir - {id = 5, name = 'color1', size = 4}, --- color - {id = 6, name = 'color2', size = 4}, --- color - {id = 7, name = 'instData', type = GL.UNSIGNED_INT, size= 4}, - } - orbVBO = InstanceVBOTable.makeInstanceVBOTable(orbVBOLayout,256, "orbVBO", 7) - orbVBO.numVertices = numIndices - orbVBO.vertexVBO = sphereVBO - orbVBO.VAO = InstanceVBOTable.makeVAOandAttach(orbVBO.vertexVBO, orbVBO.instanceVBO) - orbVBO.primitiveType = GL.TRIANGLES - orbVBO.indexVBO = sphereIndexVBO - orbVBO.VAO:AttachIndexBuffer(orbVBO.indexVBO) -end - --------------------------------------------------------------------------------- --- Draw Iteration --------------------------------------------------------------------------------- -local function DrawOrbs(reflectionPass) - if orbVBO.usedElements > 0 then - gl.DepthTest(true) - gl.DepthMask(false) --"BK OpenGL state resets", default is already false, could remove both state changes - --gl.Culling(GL.FRONT) - gl.Culling(false) - orbShader:Activate() - orbShader:SetUniform("reflectionPass", (reflectionPass and 1 ) or 0 ) - drawInstanceVBO(orbVBO) - orbShader:Deactivate() - end -end --------------------------------------------------------------------------------- --- Widget Interface --------------------------------------------------------------------------------- --- Note that we rely on VisibleUnitRemoved triggering right before VisibleUnitAdded on UnitFinished -local shieldFinishFrames = {} -- unitID to gameframe - -function widget:DrawWorldPreParticles(drawAboveWater, drawBelowWater, drawReflection, drawRefraction) - if next(shieldFinishFrames) then shieldFinishFrames = {} end - -- NOTE: This is called TWICE per draw frame, once before water and once after, even if no water is present. - -- If water is present on the map, then it gets called again between the two for the refraction pass - -- Solution is to draw it only on the first call, and draw reflections from widget:DrawWorldReflection - - if drawAboveWater and not drawReflection and not drawRefraction then - DrawOrbs(false) - end -end - -function widget:DrawWorldReflection() - DrawOrbs(true) -end - -function widget:Initialize() - if not gl.CreateShader then -- no shader support, so just remove the widget itself, especially for headless - widgetHandler:RemoveWidget() - return - end - initGL4() - if WG['unittrackerapi'] and WG['unittrackerapi'].visibleUnits then - widget:VisibleUnitsChanged(WG['unittrackerapi'].visibleUnits, nil) - else - spEcho("Unit Tracker API unavailable, exiting Orb GL4") - widgetHandler:RemoveWidget() - return - end -end - - -function widget:VisibleUnitAdded(unitID, unitDefID, unitTeam, noupload) - --spEcho("widget:VisibleUnitAdded",unitID, unitDefID, unitTeam, noupload,shieldFinishFrames[unitID]) - if unitDefID and orbUnitDefs[unitDefID] then - - unitTeam = unitTeam or spGetUnitTeam(unitID) - - local _, _, _, _, buildProgress = Spring.GetUnitHealth(unitID) - if buildProgress < 1 then return end - - local instanceCache = orbUnitDefs[unitDefID] - instanceCache[5] = shieldFinishFrames[unitID] or 0 - instanceCache[6] = unitTeam - --instanceCache[7] = spGetGameFrame() - shieldFinishFrames[unitID] = nil - - pushElementInstance(orbVBO, - instanceCache, - unitID, --key - true, -- updateExisting - noupload, - unitID -- unitID for uniform buffers - ) - end -end - -function widget:VisibleUnitsChanged(extVisibleUnits, extNumVisibleUnits) - if orbVBO.usedElements > 0 then - InstanceVBOTable.clearInstanceTable(orbVBO) - end - for unitID, unitDefID in pairs(extVisibleUnits) do - widget:VisibleUnitAdded(unitID, unitDefID, nil, true) - end - InstanceVBOTable.uploadAllElements(orbVBO) -end - -function widget:VisibleUnitRemoved(unitID) - shieldFinishFrames[unitID] = spGetGameFrame() - if orbVBO.instanceIDtoIndex[unitID] then - popElementInstance(orbVBO, unitID) - end -end - -function widget:Shutdown() - -- FIXME: clean up after thyself! -end - - return widget end)() - local initialize=WebbarHealthbarInitialize - function WebbarHealthbarInitialize() - if not initialize() then return false end - orb:Initialize();orbReady=true - assert(WG.VBOTableRegistry.orbVBO.instanceStep==20,'Original orb layout changed') - return true - end - for _,name in ipairs({'VisibleUnitAdded','VisibleUnitRemoved','VisibleUnitsChanged'})do - local ordinary=assert(listeners[name]) - listeners[name]=function(...) - if orbReady then orb[name](orb,...)end - return ordinary(...) - end - end -end -function WebbarOrbState() - if not orbReady then return nil end - -- Original draw boundary clears the temporary finish-frame map. Do not - -- approximate it with simulation frames or snapshot arrival times. - orb:DrawWorldPreParticles(true,false,false,false) - local v=assert(WG.VBOTableRegistry.orbVBO) - assert(v.instanceStep==20 and v.usedElements<=65536) - local rows={} - for i=1,v.usedElements do - local id=assert(v.indextoInstanceID[i]);local params={} - for j=1,16 do params[j]=v.instanceData[(i-1)*20+j]end - local uniforms=unitUniforms[id] - rows[#rows+1]={id=id,params=params,shield=uniforms and uniforms[3]or 0} - end - return rows +/* Original BAR GPL v2 or later policy; generated by scripts/native-deferred-lights/engine.mjs. */ +#pragma once +static constexpr const char* WEBBAR_HEALTHBAR_POLICY=R"WEBBAR_BARS( +--[[ +IMPORTANT NOTICE: Tests for these functions are provided via +`common/tableFunctionsTests.lua`, but the tests do not run unless you uncomment +them in `init.lua` (because they're not free to run, so we don't want them to +run for end users.) +]] + +-- Lua 5.1 backwards compatibility +table.pack = table.pack or function(...) return { n = select("#", ...), ... } end + +if not table.copy then + function table.copy(tbl) + local copy = {} + for key, value in pairs(tbl) do + if type(value) == "table" then + copy[key] = table.copy(value) + else + copy[key] = value + end + end + return copy + end +end + +if not table.merge then + ---Return a new table of values from mergeData recursively merged into + ---mergeTarget, using deep copies. When there is a conflict, values in + ---mergeData take precedence. + ---@param mergeTarget table + ---@param mergeData table + ---@return table + function table.merge(mergeTarget, mergeData) + local new = table.copy(mergeTarget) + for key, value in pairs(mergeData) do + -- key not used in default, assign it the value at same key in override + if not new[key] and type(value) == "table" then + new[key] = table.copy(value) + -- values at key in both default and override are tables, merge those + elseif type(new[key]) == "table" and type(value) == "table" then + new[key] = table.merge(new[key], value) + else + new[key] = value + end + end + return new + end +end + +if not table.mergeInPlace then + ---Recursively in-place merge values from mergeData into mergeTarget. When + ---there is a conflict, values in mergeData take precedence. + ---@param mergeTarget table + ---@param mergeData table + ---@param deep? boolean if true, deep copy tables coming from mergeData (default: false) + ---@return table mergeTarget + function table.mergeInPlace(mergeTarget, mergeData, deep) + deep = deep or false + for key, value in pairs(mergeData) do + if type(value) == 'table' and type(mergeTarget[key] or false) == 'table' then + table.mergeInPlace(mergeTarget[key], value, deep) + elseif type(value) == "table" and deep then + mergeTarget[key] = table.copy(value) + else + mergeTarget[key] = value + end + end + return mergeTarget + end +end + +if not table.sortStable then + local function compareDefault(a, b) + return a < b + end + + ---Sorts list elements in a given order, *in-place*, from `list[1]` to `list[#list]`. + ---This method preserves elements' original order when possible, unlike `table.sort`. + ---@generic T + ---@param tbl T[] + ---@param compare fun(a: T, b: T) : boolean|nil where true := less than, false := greater than, nil := equal to + table.sortStable = function(tbl, compare) + if not compare then + compare = compareDefault + end + local index = table.getKeyOf -- local speedup + table.sort(tbl, function(a, b) + local comparison = compare(a, b) + return comparison or (comparison == nil and index(tbl, a) < index(tbl, b)) + end) + end +end + +if not table.ensureTable then + ---Ensures a table exists at the specified key, creating one if needed. + ---@param tbl table + ---@param key any + ---@return table nested in tbl at key + function table.ensureTable(tbl, key) + local sub = tbl[key] + if sub == nil then + sub = {} + tbl[key] = sub + elseif type(sub) ~= "table" then + error("existing entry is not a table") + end + return sub + end +end + +if not table.toString then + local stringRep = string.rep + local tableSort = table.sort + local DEFAULT_INDENT_STEP = 2 + + local function tableToString(tbl, options, _seen, _depth) + end + + local function keyCmp(a, b) + local ta = type(a) + local tb = type(b) + + -- numbers always sort before other keys + -- compare pairs of numbers directly + -- for everything else, convert to string first + if ta == "number" and tb == "number" then + return a < b + elseif ta == "number" and tb ~= "number" then + return true + elseif tb == "number" and ta ~= "number" then + return false + else + return tableToString(a) < tableToString(b) + end + end + + local tableConcat = table.concat + + tableToString = function(tbl, options, _seen, _depth) + _seen = _seen or {} + _depth = _depth or 0 + + local inputType = type(tbl) + + if inputType == "string" then + return "\"" .. tbl .. "\"" + elseif inputType == "userdata" then + return tostring(tbl) or "" + elseif inputType ~= "table" then + return tostring(tbl) + end + + if _seen[tbl] then + return "" + end + + _seen[tbl] = true + + local keys = {} + local keyCount = 0 + for key in pairs(tbl) do + keyCount = keyCount + 1 + keys[keyCount] = key + end + tableSort(keys, (options and options.keyCmp) or keyCmp) + + local indent = (options and options.indent) or DEFAULT_INDENT_STEP + local pretty = options and options.pretty + + local parts = {} + local n = 0 + + n = n + 1; parts[n] = "{" + if keyCount > 0 and pretty then + n = n + 1; parts[n] = "\n" + end + for i = 1, keyCount do + local key = keys[i] + if pretty then + n = n + 1; parts[n] = stringRep(" ", (_depth + 1) * indent) + end + if key ~= i then + local keyType = type(key) + if keyType == "string" then + n = n + 1; parts[n] = key + n = n + 1; parts[n] = "=" + elseif keyType == "number" then + n = n + 1; parts[n] = "[" + n = n + 1; parts[n] = tostring(key) + n = n + 1; parts[n] = "]=" + else + n = n + 1; parts[n] = "[" + n = n + 1; parts[n] = tableToString(key, options, _seen) + n = n + 1; parts[n] = "]=" + end + end + n = n + 1; parts[n] = tableToString(tbl[key], options, _seen, _depth + 1) + if i < keyCount or pretty then + n = n + 1; parts[n] = "," + end + if pretty then + n = n + 1; parts[n] = "\n" + end + end + if keyCount > 0 and pretty then + n = n + 1; parts[n] = stringRep(" ", _depth * indent) + end + n = n + 1; parts[n] = "}" + + return tableConcat(parts) + end + + ---Recursively turns a table into a string, suitable for printing. + --- + ---All types of keys and values are valid. How some special types are handled: + --- * `function` types are turned into "" + --- * `userdata` types are turned into "", unless they have a `tostring` metamethod, which is used instead + --- * cyclic or recursive references are turned into "" + --- * keys that are not strings or numbers (tables, functions, etc) are first run through table.toString + --- + ---In order to keep the output deterministic, keys are sorted. + ---@param tbl table + ---@param options table Optional parameters + ---@param options.pretty boolean Whether to add newlines and indentation (default: false) + ---@param options.indent number If pretty=true, the number of spaces to indent by at each indent step (default: 2) + ---@param options.keyCmp function Custom comparison function for sorting keys. If provided, this function will be used instead of the default comparison based on `table.toString(key)`. + ---@return string + table.toString = tableToString +end + +if not table.invert then + function table.invert(tbl) + local inverted = {} + for key, value in pairs(tbl) do + inverted[value] = key + end + return inverted + end +end + +if not table.getUniqueArray then + local sort, floor = table.sort, math.floor + + local lookup = {} + local function sortLookup(a, b) + return lookup[a] < lookup[b] + end + + ---Produces a new table that contains no duplicate and/or non-sequence-able entries. + --- + ---Values with non-integer keys are _ignored_. Values with integer keys are _sorted_. + --- + ---The final/sorted array forms a compact sequence with no gaps so can have new keys. + ---@param tbl table may contain array, hash, or mixed data and can have gaps + ---@return table sequence containing only unique entries, ordered by their integer indices + function table.getUniqueArray(tbl) + local unique, count = {}, 0 + local invert = {} + + -- Iterate the hash part to pull hashed integer keys back into the array part. + for index, option in pairs(tbl) do + if type(index) == "number" and index >= 1 and index == floor(index) then + if not invert[option] then + count = count + 1 + unique[count] = option + invert[option] = index + elseif invert[option] > index then + invert[option] = index + end + end + end + + lookup = invert + sort(unique, sortLookup) + + return unique + end +end + +if not table.append then + function table.append(appendTarget, appendData) + local n = #appendTarget + for i = 1, #appendData do + n = n + 1 + appendTarget[n] = appendData[i] + end + end +end + +if not table.count then + ---Count the number of values in table. + ---Note that this always works, whereas the default length operator (#table) + ---only works if the table is a Lua sequence (i.e. indexes form a contiguous + ---sequence starting from 1). + ---@param tbl table + ---@return number + function table.count(tbl) + local count = 0 + for _ in pairs(tbl) do + count = count + 1 + end + return count + end +end + +if not table.isEmpty then + ---Check if the table is empty. + ---@param tbl table + ---@return boolean + function table.isEmpty(tbl) + return next(tbl) == nil + end +end + +if not table.isNilOrEmpty then + ---Check if the table is empty. + ---@param tbl table + ---@return number + function table.isNilOrEmpty(tbl) + return tbl == nil or table.isEmpty(tbl) + end +end + +if not table.getKeyOf then + ---Find key of value in table. + ---Will always return the first key found, no matter if the table contains + ---multiple instances of the value. + ---@generic K, V + ---@param tbl table + ---@param value V + ---@return K? # key if found, nil otherwise + function table.getKeyOf(tbl, value) + for key, v in pairs(tbl) do + if v == value then + return key + end + end + return nil + end +end + +if not table.contains then + ---Check if value is in table. + ---@generic V + ---@param tbl table + ---@param value V + ---@return boolean + function table.contains(tbl, value) + return table.getKeyOf(tbl, value) ~= nil + end +end + +if not table.keys then + ---Returns all keys of a table as an array, and the count of keys. + ---@generic K + ---@param tbl table + ---@return K[] keys + ---@return number count + function table.keys(tbl) + local keys, count = {}, 0 + for key in pairs(tbl) do + count = count + 1 + keys[count] = key + end + return keys, count + end +end + +if not table.removeIf then + ---Remove values in table if they match the given predicate. + ---@generic V + ---@param tbl table + ---@param predicate fun(value: V): boolean + function table.removeIf(tbl, predicate) + for key, value in pairs(tbl) do + if predicate(value) then + tbl[key] = nil + end + end + end +end + +if not table.removeAll then + ---Remove all instances of value in table. + ---@generic V + ---@param tbl table + ---@param value V + function table.removeAll(tbl, value) + table.removeIf(tbl, function(v) return v == value end) + end +end + +if not table.removeFirst then + ---Remove first instance of value in table. + ---If table is a Lua sequence (i.e. indexes form a contiguous sequence + ---starting from 1), it will use `table.remove` to keep the sequence + ---contiguous, otherwise it will `nil` the instance. + ---@generic V + ---@param tbl V[]|table + ---@param value V + ---@return boolean # true if a value was removed, false otherwise + function table.removeFirst(tbl, value) + -- first, try to handle the table as a proper Lua sequence + -- this will fail as soon as there's a gap (missing integer index), but if + -- the table is a sequence then we want to keep that property by using + -- `table.remove` to keep the sequence intact without any gaps + for index, v in ipairs(tbl) do + if v == value then + table.remove(tbl, index) + return true + end + end + + -- otherwise, try to handle the table normally and simply `nil` the value + local found = table.getKeyOf(tbl, value) + if found ~= nil then + tbl[found] = nil + return true + end + + return false + end +end + +if not table.shuffle then + ---Shuffle sequence using Knuth (Fisher–Yates) algorithm. + ---@param sequence any[] must be a Lua sequence (i.e. indexes form a contiguous sequence starting from 1), with the exception that we optionally allow starting from 0 + ---@param firstIndex? 0|1 first index in the sequence (optional, default: 1) + function table.shuffle(sequence, firstIndex) + firstIndex = firstIndex or 1 + for i = firstIndex, #sequence - 2 + firstIndex do + local j = math.random(i, #sequence) + sequence[i], sequence[j] = sequence[j], sequence[i] + end + end +end + +if not table.map then + --- Applies a function to all elements of a table and returns a new table with the results. + ---@generic K, V, RV, RK + ---@param tbl table The input table. + ---@param callback fun(value: V, key: K, tbl: table): RV, RK The function to apply to each element. It receives three arguments: the element's value, its key, and the original table. It should return the new value, and optionally, a new key. + ---@return table A new table containing the results of applying the callback to each element. + function table.map(tbl, callback) + local result = {} + for k, v in pairs(tbl) do + local mappedValue, mappedKey = callback(v, k, tbl) + if mappedKey ~= nil then + result[mappedKey] = mappedValue + else + result[k] = mappedValue + end + end + return result + end +end + +if not table.reduce then + --- Reduces a table to a single value by applying a function to each element in order. + ---@generic K, V, R + ---@param tbl table The input table. + ---@param callback fun(acc: R, value: V, key: K, tbl: table): R The function to apply to each element. It receives four arguments: the accumulator, the element's value, its key, and the original table. + ---@param initial R The initial value of the accumulator. If no value is specified, the first callback will receive nil as the accumulator value. + ---@return R The final value of the accumulator after applying the callback to all elements. + function table.reduce(tbl, callback, initial) + local accumulator = initial + + for k, v in pairs(tbl) do + accumulator = callback(accumulator, v, k, tbl) + end + + return accumulator + end +end + +if not table.filterArray then + --- Creates a new (array-style) table containing only the elements that satisfy a given condition. + ---@generic V + ---@param tbl V[] The input table. + ---@param callback fun(value: V, index: number, tbl: V[]): boolean The condition to check for each element. It receives three arguments: the element's value, its key, and the original table. It should return true if the element satisfies the condition, false otherwise. + ---@return V[] A new table containing only the elements that satisfy the condition. + function table.filterArray(tbl, callback) + local result = {} + for i, v in ipairs(tbl) do + if callback(v, i, tbl) then + result[#result + 1] = v + end + end + return result + end +end + +if not table.filterTable then + --- Creates a new (dictionary-style) table containing only the elements that satisfy a given condition. + ---@generic K, V, R + ---@param tbl table The input table. + ---@param callback fun(value: V, key: K, tbl: table): boolean The condition to check for each element. It receives three arguments: the element's value, its index, and the original table. It should return true if the element satisfies the condition, false otherwise. + ---@return table A new table containing only the elements that satisfy the condition. + function table.filterTable(tbl, callback) + local result = {} + for k, v in pairs(tbl) do + if callback(v, k, tbl) then + result[k] = v + end + end + return result + end +end + +if not table.all then + --- Checks if all elements of a table satisfy a condition. + ---@generic K, V, R + ---@param tbl table The input table. + ---@param callback fun(value: V, key: K, tbl: table): boolean The condition to check for each element. It receives three arguments: the element's value, its key, and the original table. It should return true if the element satisfies the condition, false otherwise. + ---@return boolean True if all elements satisfy the condition, false otherwise. + function table.all(tbl, callback) + for k, v in pairs(tbl) do + if not callback(v, k, tbl) then + return false + end + end + return true + end +end + +if not table.any then + --- Checks if at least one element of a table satisfies a condition. + ---@generic K, V, R + ---@param tbl table The input table. + ---@param callback fun(value: V, key: K, tbl: table): boolean The condition to check for each element. It receives three arguments: the element's value, its key, and the original table. It should return true if the element satisfies the condition, false otherwise. + ---@return boolean True if at least one element satisfies the condition, false otherwise. + function table.any(tbl, callback) + for k, v in pairs(tbl) do + if callback(v, k, tbl) then + return true + end + end + return false + end +end + +if not table.valueIntersection then + ---Creates a new array-style table containing the intersection of all input arrays. + ---Returns only unique elements that appear in all input arrays. + ---@generic V + ---@param ... V[] Any number of array-style tables. + ---@return V[] A new array containing only values present in all input arrays. + function table.valueIntersection(...) + local tables = { ...} + + -- Count occurrences of each value across all arrays + local valueCounts = {} + for _, tbl in pairs(tables) do + -- Use a set for each array to handle duplicates correctly + local seen = {} + for _, value in pairs(tbl) do + if not seen[value] then + seen[value] = true + valueCounts[value] = (valueCounts[value] or 0) + 1 + end + end + end + + -- Keep only values that appear in all arrays + local result = {} + local numTables = table.count(tables) + for value, count in pairs(valueCounts) do + if count == numTables then + result[#result + 1] = value + end + end + + return result + end +end + +if not pairsByKeys then + ---pairs-like iterator function traversing the table in the order of its keys. + ---Natural sort order will be used by default, optionally pass a comparator + ---function for custom sorting. + ---@generic K, V + ---@param tbl table + ---@param keySortFunction? fun(a: K, b: K): boolean comparator function passed to table.sort for sorting keys + ---@return fun(table: table, index?: K): K, V + ---@return table + ---(Implementation copied straight from the docs at https://www.lua.org/pil/19.3.html.) + function pairsByKeys(tbl, keySortFunction) + local keys = {} + for key in pairs(tbl) do table.insert(keys, key) end + table.sort(keys, keySortFunction) + local i = 0 -- iterator variable + local iter = function() -- iterator function + i = i + 1 + if keys[i] == nil then + return nil + else + return keys[i], tbl[keys[i]] + end + end + return iter + end +end + +local originalSpring=Spring +local Spring=setmetatable({GetModOptions=originalSpring.GetModOptions},{__index=originalSpring}) +local options=(function() +-- Custom Options Definition Table format +-- NOTES: +-- using an enumerated table lets you specify the options order +-- +-- These keywords must be lowercase for LuaParser to read them. +-- +-- key: the string used in the script.txt +-- name: the displayed name +-- desc: the description (could be used as a tooltip) +-- hint: greyed out text that appears in input field when empty +-- type: the option type ('list','string','number','bool','subheader','separator') +-- def: the default value +-- min: minimum value for number options +-- max: maximum value for number options +-- step: quantization step, aligned to the def value +-- maxlen: the maximum string length for string options +-- items: array of item strings for list options +-- section: so lobbies can order options in categories/panels +-- scope: 'all', 'player', 'team', 'allyteam' <<< not supported yet >>> +-- collumn: moves the option 1 row up if value is greater than the preivous row's one, default: 1 +-- | negative value forces new row, absolute value is used +-- | zero moves to the left, 1 is default, 2 is half way to the right +-- | recommened values: for 2 columns: 1 and 2, for 3 columns 1, 1.66, and 2.33 +-- +-- lock: if type is bool: hides the table of keys when set to TRUE <<< can not hide separators >>> +-- | if type is list: add under each item what it should SHOW when set to +-- unlock: if type is bool: hides the table of keys when set to FALSE <<< can not hide separators >>> +-- | if type is list: add under each item what it should HIDE when set to +-- bitmask: int (1|2|4|8...etc), for when multiple options can hide an item + +local options = { + + --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + -- Main + Restrictions + --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + { + key = "options_main", + name = "Main", + desc = "", + type = "section", + weight = 7, + }, + + { + key = "sub_header", + name = "Options for changing base game settings.", + desc = "", + section = "options_main", + type = "subheader", + def = true, + }, + + { + key = "sub_header", + section = "options_main", + type = "separator", + }, + + { + key = "ranked_game", + name = "Ranked Game", + desc = "Should game results affect OpenSkill. Note that games with AI or games that are not balanced are always unranked.", + type = "bool", + section = "options_main", + def = true, + }, + + + { + key = "allowuserwidgets", + name = "Allow Custom Widgets", + desc = "Allow custom user widgets or disallow them", + type = "bool", + def = true, + hidden = true, + section = "options_main", + }, + + { + key = "allowunitcontrolwidgets", + name = "Allow Custom 'Unit Control' Widgets", + desc = "Allow custom user 'unit control' widgets or disallow them", + type = "bool", + def = true, + section = "options_main", + }, + + { + key = "allowpausegameplay", + name = "Allow Commands While Paused", + desc = "Allow giving unit commands while paused", + type = "bool", + def = true, + section = "options_main", + }, + + { + key = "sub_header", + section = "options_main", + type = "separator", + }, + + { + key = "sub_header", + name = "-- Gameplay Settings", + desc = "", + section = "options_main", + type = "subheader", + def = true, + }, + + { + key = "maxunits", + name = "Max Units Per Player", + desc = "Keep in mind there is an absolute limit of units, 32 000, divided between each team. If you set this value higher than possible it will force itself down to the maximum it can be.", + type = "number", + def = 2000, + min = 500, + max = 32000, + step = 1, -- quantization is aligned to the def value, (step <= 0) means that there is no quantization + section = "options_main", + }, + { + key = "deathmode", + name = "Game End Mode", + desc = "What it takes to eliminate a team", + type = "list", + def = "com", + section = "options_main", + items = { + { key = "neverend", name = "Never ending", desc = "Teams are never eliminated", lock = { "territorial_domination_config", "territorial_domination_elimination_threshold_multiplier" } }, + { key = "com", name = "Kill all enemy Commanders", desc = "When a team has no Commanders left, it loses", lock = { "territorial_domination_config", "territorial_domination_elimination_threshold_multiplier" } }, + { key= "territorial_domination", name= "Territorial Domination", desc="Teams earn points by capturing territory to stay in the game. At the end of the final round, the team with the most points wins.", unlock = {"territorial_domination_config", "territorial_domination_elimination_threshold_multiplier"} }, + { key = "builders", name = "Kill all Builders", desc = "When a team has no builders left, it loses", lock = { "territorial_domination_config", "territorial_domination_elimination_threshold_multiplier" } }, + { key = "killall", name = "Kill everything", desc = "Every last unit must be eliminated, no exceptions!", lock = { "territorial_domination_config", "territorial_domination_elimination_threshold_multiplier" } }, + { key = "own_com", name = "Player resign on Com death", desc = "When player commander dies, you auto-resign.", lock = { "territorial_domination_config", "territorial_domination_elimination_threshold_multiplier" } }, + } + }, + + { + key = "territorial_domination_config", + name = "Territorial Domination Length", + desc = + "Configures the grace period and the amount of time in minutes it takes to reach the maximum required territory.", + type = "list", + def = "25_minutes", + section = "options_main", + items = { + { key = "20_minutes", name = "4 Rounds, 20 Minutes", desc = "Early tech emphasis, comebacks very likely, elimination unlikely." }, + { key = "25_minutes", name = "5 Rounds, 25 Minutes(Default)", desc = "Mid/late-game tech, comebacks a significant factor, eliminations uncommon" }, + { key = "30_minutes", name = "6 Rounds, 30 Minutes", desc = "Late-game tech, comebacks less significant, eliminations likely" }, + { key = "35_minutes", name = "7 Rounds, 35 Minutes", desc = "Super lategame tech, eliminations extremely likely" }, + } + }, + + { + key = "territorial_domination_elimination_threshold_multiplier", + name = "Elimination Threshold Multiplier", + desc = "Teams are eliminated at round end when score < elimination threshold which is set by highest score multiplied by this value. Lower values are more lenient.", + type = "number", + def = 1.2, + min = 1.0, + max = 1.5, + step = 0.1, + section = "options_main", + }, + + { + key = "draft_mode", + name = "Draft Spawn Order Mode", + desc = "Random/Captain/Skill/Fair based startPosType modes. Default: Random.", + type = "list", + section = "options_main", + def = "random", + items = { + { key = "disabled", name = "Disabled", desc = "Disable draft mod. Fast-PC place first." }, + { key = "random", name = "Random Order", desc = "Players get to pick a start position with a delay in a random order." }, + { key = "captain", name = "Captains First", desc = "Captain picks first, then everyone else in a random order." }, + { key = "skill", name = "Skill Order", desc = "Skill-based order, instead of random." }, + { key = "fair", name = "After full team has loaded", desc = "Everyone must join the game first - after that (+2sec delay) everyone can place." } + }, + }, + + { + key = "teamcolors_anonymous_mode", + name = "Anonymous Mode", + desc = "Anonymize players by changing colors (based on chosen mode) and replacing names with question marks, making it harder to know who's who.", + type = "list", + section = "options_main", + def = "disabled", + items = { + { key = "disabled", name = "Disabled" }, + { key = "global", name = "Shuffle Globally", desc = "You can distinguish different players and everyone sees the same colors globally. Diplomacy is the same as usual except using colors instead of names (e.g. \"Red, let's ally against Blue\")." }, + { key = "local", name = "Shuffle Locally", desc = "You can distinguish different players but everyone sees different colors locally. Diplomacy is harder but possible using positions (e.g. \"Southeast, let's ally against Northeast\")." }, + { key = "disco", name = "Shuffle Locally (Continiously)", desc = "Same as local shuffle, except that colors are reshuffled every 2 mins for extra spicyness." }, + { key = "allred", name = "Everyone Is Red", desc = "You cannot distinguish different players, they all have the same color (red by default, can be changed in accessibility settings). Diplomacy is very hard." }, + }, + }, + + { + key = "transportenemy", + name = "Enemy Transporting", + desc = "Toggle which enemy units you can kidnap with an air transport", + hidden = true, + type = "list", + def = "notcoms", + section = "options_main", + items = { + { key= "notcoms", name= "All But Commanders", desc= "Only commanders are immune to napping" }, + { key= "none", name= "Disallow All", desc= "No enemy units can be napped" }, + } + }, + + { + key = "teamffa_start_boxes_shuffle", + name = "Shuffle TeamFFA Start Boxes", + desc = "In TeamFFA games (more than 2 teams, excluding Raptors / Scavengers), start boxes will be randomly assigned to each team: team 1 might be assigned any start box rather than team 1 always being assigned start box 1.", + type = "bool", + section = "options_main", + def = true, + }, + + { + key = "fixedallies", + name = "Disabled Dynamic Alliances", + desc = "Disables the possibility of players to dynamically change alliances ingame", + type = "bool", + def = true, + hidden = true, + section = "options_main", + }, + + { + key = "disablemapdamage", + name = "Disable Map Deformation", + desc = "Prevents the map shape from being changed by weapons", + type = "bool", + def = false, + section = "options_main", + }, + + { + key = "disable_fogofwar", + name = "Disable Fog of War", + desc = "Disable Fog of War", + type = "bool", + section = "options_main", + def = false, + }, + + { + key = "norushtimer", + name = "No Rush Time".."\255\128\128\128".." [minutes]", + desc = "Set timer in which players cannot get out of their startbox, so you have time to prepare before fighting.\n".. + "PLEASE NOTE: For this to work, the game needs to have set startboxes.\n".. + -- tabs don't do much in chobby + " It won't work in FFA mode without boxes.\n".. + " Also, it does not affect Scavengers and Raptors.\n".. + "\255\75\0\100".."WARNING: No Rush Time over 30 minutes may cause performance or stability issues due to excessive unit buildup.", + type = "number", + section = "options_main", + def = 0, + min = 0, + max = 120, + step = 1, + }, + { + key = "norushmiddlefree", + name = "No Rush Non Base FFA", + desc = "Allows units to leave startboxes but disallows commands issued in enemy startboxes.\n".. + "Does not prevent commands onto the other side of startboxes so recommend East/West or North/South startboxes.", + type = "bool", + section = "options_main", + def = false, + }, + + { + key = "comm_trans_slow", + name = "Slow Commander Transport", + desc = "T2 transports carrying a Commander, move at speed 120. A temporary option available, until bigger transport changes get finished.", + type = "bool", + section = "options_main", + def = false, + }, + + { + key = "sub_header", + section = "options_main", + type = "separator", + }, + { + key = "sub_header", + name = "-- Sharing and Taxes", + section = "options_main", + type = "subheader", + def = true, + }, + { + key = "tax_resource_sharing_amount", + name = "Resource Sharing Tax", + desc = "Taxes resource sharing".."\255\128\128\128".." and overflow (engine TODO:)\n".. + "Set to [0] to turn off. Recommended: [0.4]. (Ranges: 0 - 0.99)", + type = "number", + def = 0, + min = 0, + max = 0.99, + step = 0.01, + section = "options_main", + column = 1, + }, + { + key = "disable_unit_sharing", + name = "Disable Unit Sharing", + desc = "Disable sharing units and structures to allies", + type = "bool", + section = "options_main", + def = false, + }, + { + key = "disable_assist_ally_construction", + name = "Disable Assist Ally Construction", + desc = "Disables assisting allied blueprints and labs.", + type = "bool", + section = "options_main", + def = false, + column = 1.66, + }, + { + key = "sub_header", + section = "options_main", + type = "separator", + }, + + { + key = "sub_header", + name = "-- Unit Restrictions", + desc = "", + section = "options_main", + type = "subheader", + def = true, + }, + + { + key = "unit_restrictions_notech15", + name = "Disable Tech 1.5", + desc = "Disables: Sea Plane Labs, Hovercraft labs, and Amphibious labs. (Considered Tier 1.5)", + type = "bool", + section = "options_main", + def = false, + column = 1, + }, + + { + key = "unit_restrictions_notech2", + name = "Disable Tech 2", + desc = "Disable Tech 2", + type = "bool", + section = "options_main", + def = false, + column = 1.66, + }, + + { + key = "unit_restrictions_notech3", + name = "Disable Tech 3", + desc = "Disable Tech 3", + type = "bool", + section = "options_main", + def = false, + column = 2.33, + }, + + { + key = "unit_restrictions_noair", + name = "Disable Air Units", + desc = "Disable Air Units", + type = "bool", + section = "options_main", + def = false, + column = 1, + }, + + { + key = "unit_restrictions_nosea", + name = "Disable Sea Units", + desc = "Disable Sea Units", + type = "bool", + section = "options_main", + def = false, + column = 1.66, + }, + + { + key = "unit_restrictions_noextractors", + name = "Disable Metal Extractors", + desc = "Disable Metal Extractors", + type = "bool", + section = "options_main", + def = false, + column = 1, + }, + + { + key = "unit_restrictions_noconverters", + name = "Disable Energy Converters", + desc = "Disable Energy Converters", + type = "bool", + section = "options_main", + def = false, + column = 1.66, + }, + + { + key = "unit_restrictions_nofusion", + name = "Disable Fusion Generators", + desc = "Disables Normal and Advanced Fusion Energy Generators", + type = "bool", + section = "options_main", + def = false, + column = 2.33, + }, + + { + key = "unit_restrictions_notacnukes", + name = "Disable Tactical Missiles/EMPs", + desc = "Disables Cortex Tactical Missile Launcher and Armada EMP Missile Launcher", + type = "bool", + section = "options_main", + def = false, + column = 1, + }, + + { + key = "unit_restrictions_nonukes", + name = "Disable Nuclear Missiles", + desc = "Disable Nuclear Missiles", + type = "bool", + section = "options_main", + def = false, + column = 1.66, + }, + + { + key = "unit_restrictions_noantinuke", + name = "Disable Anti-Nuke Defence", + desc = "Disables Nuke Interceptor Units and Structures.", + type = "bool", + section = "options_main", + def = false, + column = 2.33, + }, + + { + key = "unit_restrictions_nolrpc", + name = "Disable Long Range Artilery (LRPC)", + desc = "Disable Long Range Plasma Artilery (LRPC) structures", + type = "bool", + section = "options_main", + def = false, + column = 1, + }, + + { + key = "unit_restrictions_noendgamelrpc", + name = "Disable Endgame Artilery (LRPC)", + desc = "Disable Endgame Long Range Plasma Artilery (LRPC) structures (AKA lolcannons)", + type = "bool", + section = "options_main", + def = false, + column = 1.66, + }, + + + --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + -- Other Options + --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + + { + key = "options", + name = "Other", + desc = "Options", + type = "section", + }, + + { + key = "map_tidal", + name = "Tidal Strength", + desc = "Unchanged = map setting, low = 13e/sec, medium = 18e/sec, high = 23e/sec.", + hidden = true, + type = "list", + def = "unchanged", + section = "options", + items = { + { key = "unchanged", name = "Unchanged", desc = "Use map settings" }, + { key = "low", name = "Low", desc = "Set tidal incomes to 13 energy per second" }, + { key = "medium", name = "Medium", desc = "Set tidal incomes to 18 energy per second" }, + { key = "high", name = "High", desc = "Set tidal incomes to 23 energy per second" }, + } + }, + + { + key = "critters", + name = "Animal amount", + desc = "This multiplier will be applied on the amount of critters a map will end up with", + hidden = true, + type = "number", + section = "options", + def = 1, + min = 0, + max = 2, + step = 0.2, + }, + + { + key = "map_atmosphere", + name = "Map Atmosphere and Ambient Sounds", + desc = "", + type = "bool", + def = true, + hidden = true, + section = "options", + }, + + { + key = "ffa_wreckage", + name = "FFA Mode Wreckage", + desc = "Killed players will blow up but leave wreckages", + hidden = true, + type = "bool", + def = false, + section = "options", + }, + + { + key = "wreck_metal_ratio", + name = "Wreck Metal Percent", + desc = "Percent of unit metal that is left in its wrecks", + hidden = true, + type = "number", + section = "options", + def = 0.6, + min = 0, + max = 1, + step = 0.05, + }, + + { + key = "heap_metal_ratio", + name = "Heap Metal Percent", + desc = "Percent of unit metal that is left in its heaps", + hidden = true, + type = "number", + section = "options", + def = 0.25, + min = 0, + max = 1, + step = 0.05, + }, + + { + key = "coop", + name = "Cooperative mode", + desc = "Adds extra commanders to id-sharing teams, 1 com per player", + type = "bool", + hidden = true, + def = false, + section = "options", + }, + + --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + -- Multiplier Options + --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + + --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + -- Raptors + --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + { + key = "raptor_defense_options", + name = "Raptors", + desc = "Various gameplay options that will change how the Raptor Defense is played.", + type = "section", + weight = 4, + }, + + { + key = "sub_header", + name = "Raptors Gamemode Options.", + desc = "", + section = "raptor_defense_options", + type = "subheader", + def = true, + }, + + { + key = "raptors_dev_channel_link", + name = "Development Discussion", + desc = "Raptors development discussion.", + section = "raptor_defense_options", + type = "link", + link = "https://discord.com/channels/549281623154229250/781097030692110346", + width = 275, + column = 1.65, + linkheight = 325, + linkwidth = 350, + }, + + { + key = "sub_header", + name = "To Play Add a Raptors AI to the enemy Team: [Add AI], [RaptorsDefense AI]", + desc = "", + section = "raptor_defense_options", + type = "subheader", + }, + + { + key = "sub_header", + section = "raptor_defense_options", + type = "separator", + }, + + { + key = "raptor_difficulty", + name = "Base Difficulty", + desc = "Raptors difficulty", + type = "list", + def = "normal", + section = "raptor_defense_options", + items = { + { key = "veryeasy", name = "Very Easy", desc="Very Easy" }, + { key = "easy", name = "Easy", desc="Easy" }, + { key = "normal", name = "Normal", desc="Normal" }, + { key = "hard", name = "Hard", desc="Hard" }, + { key = "veryhard", name = "Very Hard", desc="Very Hard" }, + { key = "epic", name = "Epic", desc="Epic" }, + } + }, + + { + key = "sub_header", + section = "raptor_defense_options", + type = "separator", + }, + + { + key = "raptor_raptorstart", + name = "Hives Placement", + desc = "Control where hives spawn", + type = "list", + def = "initialbox", + section = "raptor_defense_options", + items = { + { key = "avoid", name = "Spawn Anywhere", desc = "Hives avoid player units" }, + { key = "initialbox", name = "Growing Spawn Box", desc = "Hives spawn in limited area that increases over time" }, + { key = "alwaysbox", name = "Always Start Box", desc = "Hives always spawn in raptor start box" }, + } + }, + + { + key = "raptor_endless", + name = "Endless Mode", + desc = "When you kill the queen, the game doesn't end, but loops around at higher difficulty instead, infinitely.", + type = "bool", + def = false, + section = "raptor_defense_options", + }, + + { + key = "sub_header", + section = "raptor_defense_options", + type = "separator", + }, + + { + key = "sub_header", + name = "-- Advanced Options, Change at your own risk.", + desc = "", + section = "raptor_defense_options", + type = "subheader", + def = true, + }, + + { + key = "raptor_queentimemult", + name = "Queen Hatching Time Multiplier", + desc = "(Range: 0.1 - 2). How quickly Queen Hatch goes from 0 to 100%", + type = "number", + def = 1, + min = 0.1, + max = 2, + step = 0.1, + section = "raptor_defense_options", + }, + + { + key = "raptor_queen_count", + name = "Raptor Queen Count", + desc = "(Range: 1 - 100). Number of queens that will spawn.", + type = "number", + def = 1, + min = 1, + max = 100, + step = 1, + section = "raptor_defense_options", + }, + + { + key = "raptor_spawncountmult", + name = "Unit Spawn Per Wave Multiplier", + desc = "(Range: 1 - 5). How many times more raptors will spawn per wave.", + type = "number", + def = 1, + min = 1, + max = 5, + step = 1, + section = "raptor_defense_options", + }, + + { + key = "raptor_firstwavesboost", + name = "First Waves Size Boost", + desc = "(Range: 1 - 10). Intended to use with heavily modified settings. Makes first waves larger, the bigger the number the larger they are. Cools down within first few waves.", + type = "number", + def = 1, + min = 1, + max = 10, + step = 1, + section = "raptor_defense_options", + }, + + { + key = "raptor_spawntimemult", + name = "Waves Amount Multiplier", + desc = "(Range: 1 - 5). How often new waves will spawn. Bigger Number = More Waves", + type = "number", + def = 1, + min = 1, + max = 5, + step = 0.1, + section = "raptor_defense_options", + }, + + { + key = "raptor_graceperiodmult", + name = "Grace Period Time Multiplier", + desc = "(Range: 0.1 - 3). Time before Raptors become active. ", + type = "number", + def = 1, + min = 0.1, + max = 3, + step = 0.1, + section = "raptor_defense_options", + }, + + + --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + -- Scavengers + --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + { + key = "scav_defense_options", + name = "Scavengers", + desc = "Gameplay options for Scavengers gamemode", + type = "section", + weight = 3, + }, + + { + key = "sub_header", + name = "Scavengers Gamemode Options.", + desc = "", + section = "scav_defense_options", + type = "subheader", + def = true, + }, + + { + key = "scavengers_dev_channel_link", + name = "Development Discussion", + desc = "Scavengers development discussion.", + section = "scav_defense_options", + type = "link", + link = "https://discord.com/channels/549281623154229250/659550298653589504", + width = 275, + column = 1.65, + linkheight = 325, + linkwidth = 350, + }, + + { + key = "sub_header", + name = "To Play Add a Scavangers AI to the enemy Team: [Add AI], [ScavengersDefense AI]", + desc = "", + section = "scav_defense_options", + type = "subheader", + }, + + + { + key = "sub_header", + section = "scav_defense_options", + type = "separator", + }, + + { + key = "scav_difficulty", + name = "Base Difficulty", + desc = "Scavs difficulty", + type = "list", + def = "normal", + section = "scav_defense_options", + items = { + { key = "veryeasy", name = "Very Easy", desc = "Very Easy" }, + { key = "easy", name = "Easy", desc = "Easy" }, + { key = "normal", name = "Normal", desc = "Normal" }, + { key = "hard", name = "Hard", desc = "Hard" }, + { key = "veryhard", name = "Very Hard", desc = "Very Hard" }, + { key = "epic", name = "Epic", desc = "Epic" }, + } + }, + + { + key = "sub_header", + section = "scav_defense_options", + type = "separator", + }, + + { + key = "scav_scavstart", + name = "Spawn Beacons Placement", + desc = "Control where spawners appear", + type = "list", + def = "initialbox", + section = "scav_defense_options", + items = { + { key = "avoid", name = "Spawn Anywhere", desc="Beacons avoid player units" }, + { key = "initialbox", name = "Growing Spawn Box", desc="Beacons spawn in limited area that increases over time" }, + --{ key = "alwaysbox", name = "Always Start Box", desc="Beacons always spawn in scav start box" }, + } + }, + + { + key = "scav_endless", + name = "Endless Mode", + desc = "When you kill the boss, the game doesn't end, but loops around at higher difficulty instead, infinitely.", + type = "bool", + def = false, + section = "scav_defense_options", + }, + + { + key = "sub_header", + section = "scav_defense_options", + type = "separator", + }, + + { + key = "sub_header", + name = "-- Advanced Options, Change at your own risk.", + desc = "", + section = "scav_defense_options", + type = "subheader", + def = true, + }, + + { + key = "scav_bosstimemult", + name = "Boss Preparation Time Multiplier", + desc = "(Range: 0.1 - 2). How quickly Boss Anger goes from 0 to 100%.", + type = "number", + def = 1, + min = 0.1, + max = 2, + step = 0.1, + section = "scav_defense_options", + }, + + { + key = "scav_boss_count", + name = "Scavengers Boss Count", + desc = "(Range: 1 - 20). Number of bosses that will spawn.", + type = "number", + def = 1, + min = 1, + max = 20, + step = 1, + section = "scav_defense_options", + }, + + { + key = "scav_spawncountmult", + name = "Unit Spawn Per Wave Multiplier", + desc = "(Range: 1 - 5). How many times more scavs will spawn per wave.", + type = "number", + def = 1, + min = 1, + max = 5, + step = 1, + section = "scav_defense_options", + }, + + { + key = "scav_spawntimemult", + name = "Waves Amount Multiplier", + desc = "(Range: 1 - 5). How often new waves will spawn. Bigger Number = More Waves", + type = "number", + def = 1, + min = 1, + max = 5, + step = 0.1, + section = "scav_defense_options", + }, + + { + key = "scav_graceperiodmult", + name = "Grace Period Time Multiplier", + desc = "(Range: 0.1 - 3). Time before Scavs become active. ", + type = "number", + def = 1, + min = 0.1, + max = 3, + step = 0.1, + section = "scav_defense_options", + }, + + --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + -- Extra Options + --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + + { + key = "options_extra", + name = "Extras", + desc = "Extra options", + type = "section", + weight = 2, + }, + + + { + key = "sub_header", + name = "Extra options for shaking up the gameplay or balancing. Not intended for ranked games.", + desc = "", + section = "options_extra", + type = "subheader", + def = true, + }, + + { + key = "sub_header", + section = "options_extra", + type = "separator", + }, + + + { + key = "experimentalextraunits", + name = "Extra Units Pack", + desc = "Pack of units that didn't make it to the main game roster. Balanced for PvP", + type = "bool", + section = "options_extra", + def = false, + }, + + { + key = "scavunitsforplayers", + name = "Scavengers Units Pack", + desc = "Units made for Scavengers, mostly silly and unbalanced for PvP.", + type = "bool", + section = "options_extra", + def = false, + }, + + { + key = "sub_header", + section = "options_extra", + type = "separator", + }, + + + { + key = "map_waterlevel", + name = "Water Level", + desc = "Doesn't work if Map Deformation is disabled! <0 = Decrease water level, >0 = Increase water level", + type = "number", + def = 0, + min = -10000, + max = 10000, + step = 1, + section = "options_extra", + }, + + { + key = "map_waterislava", + name = "Water Is Lava", + desc = "Turns water into Lava", + type = "bool", + def = false, + section = "options_extra", + unlock = {"map_lavatiderhythm", "map_lavatidemode", "map_lavahighlevel", "map_lavahighdwell", "map_lavalowlevel", "map_lavalowdwell","map_tweaklava"}, + lock = {"sub_header_lava3", "sub_header_lava4"}, + bitmask = 1, + }, + + { + key = "map_lavatiderhythm", + name = "Lava Tides", + desc = "Lava level periodicially cycles height when tides are present", + type = "list", + def = "default", + section = "options_extra", + column = 1, + items = { + { key= "default", name= "Default", desc= "Map Settings", + lock = + {"map_lavatidemode", "map_lavahighlevel", "map_lavahighdwell", "map_lavalowlevel", "map_lavalowdwell", "sub_header_lava3", "sub_header_lava4"}, + unlock = + { "sub_header_lava1", "sub_header_lava2"}}, + { key= "enabled", name= "Enable/Override",desc= "Lava tides will use these settings over the map defaults", + unlock = + {"map_lavatidemode", "map_lavahighlevel", "map_lavahighdwell", "map_lavalowlevel", "map_lavalowdwell", "sub_header_lava3", "sub_header_lava4"}, + lock = + { "sub_header_lava1", "sub_header_lava2"}}, + { key= "disabled", name= "Disable",desc= "Lava will not have tides, even on maps that normally have it", + lock = + {"map_lavatidemode", "map_lavahighlevel", "map_lavahighdwell", "map_lavalowlevel", "map_lavalowdwell", "sub_header_lava3", "sub_header_lava4"}, + unlock = + { "sub_header_lava1", "sub_header_lava2"}}, + }, + bitmask = 2, + }, + + { + key = "map_lavatidemode", + name = "Lava Tide Mode", + desc = "Toggle whether lava starts at high or low tide.", + hidden = false, + type = "list", + def = "lavastartlow", + section = "options_extra", + items = { + { key= "lavastartlow", name= "Start Low", desc= "Lava starts at low tide" }, + { key= "lavastarthigh", name= "Start High",desc= "Lava starts at high tide" }, + } + }, + + { + key = "map_lavahighlevel", + name = "Lava High Tide Level", + desc = "Lava level at high tide", + type = "number", + def = 0, + min = 0, + max = 10000, + step = 1, + section = "options_extra", + column = 1, + }, + + { + key = "map_lavahighdwell", + name = "Lava High Tide Time", + desc = "Time in seconds lava waits at high tide", + type = "number", + def = 60, + min = 1, + max = 30000, + step = 1, + section = "options_extra", + column = 2.0, + }, + + { + key = "map_lavalowlevel", + name = "Lava Low Tide Level", + desc = "Lava level at low tide", + type = "number", + def = 0, + min = 0, + max = 10000, + step = 1, + section = "options_extra", + column = 1, + }, + + { + key = "map_lavalowdwell", + name = "Lava Low Tide Time", + desc = "Time in seconds lava waits at low tide", + type = "number", + def = 300, + min = 1, + max = 30000, + step = 1, + section = "options_extra", + column = 2.0, + }, + + { + key = "map_tweaklava", + name = "Advanced Tide Rhythm", + desc = "Table with format {MapHeight (elmo), Rate (elmo/s), Dwell Time (s)}, e.g. {0, 6, 60},{100, 3, 20}", + hidden = true, + hint = "{Lava Height, Rise/Fall Rate, Dwell Time}", + type = "string", + def = "", + section = "options_extra", + }, + + { key = "sub_header_lava1", section = "options_extra", type = "subheader", name = "",}, + { key = "sub_header_lava2", section = "options_extra", type = "subheader", name = "",}, + { key = "sub_header_lava3", section = "options_extra", type = "subheader", name = "",}, + { key = "sub_header_lava4", section = "options_extra", type = "subheader", name = "",}, + + + { + key = "sub_header", + section = "options_extra", + type = "separator", + }, + + { + key = "ruins", + name = "Ruins", + desc = "Remains of the battles once fought", + type = "list", + def = "scav_only", + section = "options_extra", + items = { + { key = "enabled", name = "Enabled", unlock = {"ruins_density", "ruins_only_t1"} }, + { key = "scav_only", name = "Enabled for Scavengers only", unlock = {"ruins_density", "ruins_only_t1"} }, + { key = "disabled", name = "Disabled", lock = {"ruins_density", "ruins_only_t1"} }, + } + }, + + { + key = "ruins_density", + name = "Ruins: Density", + type = "list", + def = "normal", + section = "options_extra", + items = { + { key = "verydense", name = "Very Dense" }, + { key = "dense", name = "Dense" }, + { key = "normal", name = "Normal" }, + { key = "rare", name = "Rare" }, + { key = "veryrare", name = "Very Rare" }, + } + }, + + { + key = "ruins_only_t1", + name = "Ruins: Only Tech 1", + type = "bool", + def = false, + section = "options_extra", + }, + + { + key = "ruins_civilian_disable", + name = "Ruins: Disable Civilian (Not Implemented Yet)", + type = "bool", + def = false, + section = "options", + hidden = true, + }, + + { + key = "sub_header", + section = "options_extra", + type = "separator", + }, + + + { + key = "lootboxes", + name = "Lootboxes", + desc = "Random drops of valuable stuff.", + type = "list", + def = "scav_only", + section = "options_extra", + items = { + { key = "enabled", name = "Enabled", unlock = {"lootboxes_density"} }, + { key = "scav_only", name = "Enabled for Scavengers only", unlock = {"lootboxes_density"} }, + { key = "disabled", name = "Disabled", lock = {"lootboxes_density"} }, + } + }, + + { + key = "lootboxes_density", + name = "Lootboxes: Density", + type = "list", + def = "normal", + section = "options_extra", + items = { + { key = "normal", name = "Normal" }, + { key = "rare", name = "Rare" }, + { key = "veryrare", name = "Very Rare" }, + } + }, + + { + key = "sub_header", + section = "options_extra", + type = "separator", + }, + + { + key = "evocom", + name = "Evolving Commanders", + desc = "Commanders evolve, gaining new weapons and abilities.", + type = "bool", + def = false, + section = "options_extra", + bitmask = 1, + unlock = {"evocomlevelupmethod","evocomlevelcap","evocomxpmultiplier", "evocomleveluptime", "evocomlevelupmultiplier"}, + --lock = {"buffer_fix"}, + }, + + { + key = "evocom_feedback_thread_link", + name = "Feedback thread", + desc = "Discord discussion about Evolving Commanders.", + section = "options_extra", + type = "link", + link = "https://discord.com/channels/549281623154229250/1233887661291343913", + width = 215, + column = 2, + linkheight = 325, + linkwidth = 350, + }, + + { + key = "evocomlevelupmethod", + name = "EvoCom: Leveling Method", + desc = "Dynamic: Commanders evolve to keep up with the highest power player. Timed: Static Evolution Rate", + type = "list", + def = "dynamic", + section = "options_extra", + bitmask = 2, + items = { + { key = "dynamic", name = "Dynamic", lock = {"evocomleveluptime"}, unlock = {"evocomlevelupmultiplier"}}, + { key = "timed", name = "Timed", lock = {"evocomlevelupmultiplier"}, unlock = {"evocomleveluptime"}}, + } + }, + + + { + key = "evocomlevelupmultiplier", + name = "EvoCom: Evolution Mult.", + desc = "(Range 0.1x - 3x Multiplier) Adjusts the thresholds at which Dynamic evolutions occur", + type = "number", + section = "options_extra", + def = 1, + min = 0.1, + max = 3, + step = 0.1, + }, + + { + key = "evocomleveluptime", + name = "EvoCom: Evolution Time ", + desc = "(Range 0.1 - 20 Minutes) Rate at which commanders will evolve if Timed method is selected.", + type = "number", + section = "options_extra", + def = 5, + min = 0.1, + max = 20, + step = 0.1, + }, + + { + key = "evocomlevelcap", + name = "EvoCom: Max Level", + desc = "(Range 2 - 10) Changes the Evolving Commanders maximum level", + type = "number", + section = "options_extra", + def = 10, + min = 2, + max = 10, + step = 1, + }, + + { + key = "evocomxpmultiplier", + name = "EvoCom: Commander XP Multiplier", + desc = "(Range 0.1 - 10) Does not affect leveling! Changes the rate at which Evolving Commanders gain Experience.", + type = "number", + section = "options_extra", + def = 1, + min = 0.1, + max = 10, + step = 0.1, + }, + + { + key = "sub_header", + section = "options_extra", + type = "separator", + }, + + + { + key = "comrespawn", + name = "Commander Respawning", + desc = "Commanders can build one Effigy. The first one is free and given for you at the start. When the commander dies, the Effigy is sacrificed in its place.", + type = "list", + def = "evocom", + section = "options_extra", + items = { + { key = "evocom", name = "Evolving Commanders Only" }, + { key = "all", name = "All Commanders" }, + { key = "disabled", name = "Disabled" }, + } + }, + + { + key = "sub_header", + section = "options_extra", + type = "separator", + }, + + { + key = "quick_start", + name = "Quick Start", + desc = "Each player gets pre-game resources to spend on structures to be instantly spawned at the beginning of the game.", + type = "list", + def = "default", + section = "options_extra", + unlock = {"quick_start_amount"}, + items = { + { key = "default", name = "Default", lock = {"quick_start_amount"}, desc = "Default settings for game modes." }, + { key = "enabled", name = "Enabled", unlock = {"quick_start_amount"}, desc = "Quick Start alone, deducts 400 energy and 800 metal from starting resources." }, + { key = "factory_discount", name = "Enabled: Discounted First Factory", desc = + "Quick Start The commander's first factory is discounted at any time. Deducts 400 energy and 800 metal from starting resources.", unlock = {"quick_start_amount"} }, + { key = "factory_discount_only", name = "First Factory Discount Only", desc = "No base budget, only first factory discount. No deduction from starting resources.", lock = {"quick_start_amount"} }, + { key = "disabled", name = "Disabled", desc = "Disabled quick start for all game modes.", lock = {"quick_start_amount"} }, + } + }, + + { + key = "quick_start_link", + name = "Feedback thread", + desc = "Discord discussion about quick start.", + section = "options_extra", + type = "link", + link = "https://discord.com/channels/549281623154229250/1413936809980858408", + width = 215, + column = 2, + linkheight = 325, + linkwidth = 350, + }, + + { + key = "quick_start_amount", + name = "Quick Start Base Budget", + desc = "How much pre-game resources you have to spend on pre-queuing structures.", + type = "list", + def = "default", + section = "options_extra", + items = { + { key = "default", name = "Default", desc = "Uses the default amount based on game mode" }, + { key = "small", name = "Small", desc = "800 Base Budget" }, + { key = "normal", name = "Normal", desc = "1200 Base Budget" }, + { key = "large", name = "Large", desc = "2400 Base Budget" }, + } + }, + + { + key = "enable_quickstart_overrides", + name = "Enable Quick Start Overrides", + desc = "Allow overriding quick start range and budget (for debugging/modding).", + type = "bool", + def = false, + section = "options_extra", + hidden = true, + }, + + { + key = "override_quick_start_range", + name = "Override Quick Start Range", + desc = "Override the quick start build range when overrides are enabled (values below 200 are clamped to 200).", + type = "number", + def = 600, + min = 200, + max = 2000, + step = 1, + section = "options_extra", + hidden = true, + }, + + { + key = "override_quick_start_budget", + name = "Override Quick Start Budget", + desc = "Override the quick start starting resources when overrides are enabled.", + type = "number", + def = 1200, + min = 100, + max = 1000000, + step = 1, + section = "options_extra", + hidden = true, + }, + + { + key = "sub_header", + section = "options_extra", + type = "separator", + }, + + { + key = "assistdronesenabled", -- TODO, turn this into booleam modoption + name = "Commander Drones", + type = "list", + def = "disabled", + section = "options_extra", + items = { + { key = "enabled", name = "Enabled", unlock = {"assistdronesbuildpowermultiplier", "assistdronescount", "assistdronesair"} }, + { key = "disabled", name = "Disabled", lock = {"assistdronesbuildpowermultiplier", "assistdronescount", "assistdronesair"} }, + } + }, + + { + key = "assistdronesbuildpowermultiplier", + name = "ComDrones: Buildpower Multiplier", + desc = "(Range 0.5 - 5). How much buildpower commander drones should have", + type = "number", + section = "options_extra", + def = 1, + min = 0.5, + max = 5, + step = 0.1, + }, + + { + key = "assistdronescount", + name = "ComDrones: Count", + desc = "How many assist drones per commander should be spawned", + type = "number", + section = "options_extra", + def = 10, + min = 1, + max = 30, + step = 1, + }, + + { + key = "assistdronesair", + name = "ComDrones: Use Air Drones", + desc = "Switch between aircraft drones and amphibious vehicle drones.", + type = "bool", + def = true, + section = "options_extra", + }, + + { + key = "sub_header", + section = "options_extra", + type = "separator", + }, + + + { + key = "commanderbuildersenabled", -- TODO, turn this into boolean modoption + name = "Base Builder Turret", + type = "list", + def = "disabled", + section = "options_extra", + items = { + { key = "enabled", name = "Enabled", unlock = {"commanderbuildersrange", "commanderbuildersbuildpower"} }, + { key = "disabled", name = "Disabled", lock = {"commanderbuildersrange", "commanderbuildersbuildpower"} }, + } + }, + + { + key = "commanderbuildersrange", + name = "Base Builder Turret: Range", + desc = "(Range 500 - 2000).", + type = "number", + section = "options_extra", + def = 1000, + min = 500, + max = 2000, + step = 1, + }, + + { + key = "commanderbuildersbuildpower", + name = "Base Builder Turret: Buildpower", + desc = "(Range 100 - 1000).", + type = "number", + section = "options_extra", + def = 400, + min = 100, + max = 1000, + step = 1, + }, + + { + key = "sub_header", + section = "options_extra", + type = "separator", + }, + + { + key = "zombies", + name = "Scavenger Zombies", + type = "list", + def = "disabled", + section = "options_extra", + hidden = false, + items = { + { key = "disabled", name = "Disabled", desc = "Disabled"}, + { key = "normal", name = "Normal", desc = "Slow revival rate, normal strength."}, + { key = "hard", name = "Hard", desc = "Fast revival rate, stronger Scavenger Zombies." }, + { key = "nightmare", name = "Nightmare", desc = "Extreme revival rate, stronger Scavenger Zombies, 2-5 spawn per corpse." }, + } + }, + + --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + -- Experimental Options + --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + + { + key = "options_experimental", + name = "Experimental", + desc = "Experimental options", + type = "section", + weight = 1, + }, + + { + key = "sub_header", + name = "Options for testing various new and unfinished features. Not intended for ranked games.", + desc = "", + section = "options_experimental", + type = "subheader", + def = true, + }, + + { + key = "sub_header", + name = "When any of these options are changed, there is no guarantee they will work properly, especially when combined.", + desc = "", + section = "options_experimental", + type = "subheader", + def = true, + }, + + { + key = "sub_header", + section = "options_experimental", + type = "separator", + }, + + { + key = "proposed_unit_reworks", + name = "Placeholder for BLT testing", + desc = "Placeholder for official balance testing mod option", + type = "bool", + hidden = true, + section = "options_experimental", + def = false, + }, + + { + key = "community_balance_patch", + name = "Community Balance Patch 5-6/26", + desc = "Enable community balance patch changes\n(overwrites changes in official seasonal balance test)", + type = "list", + def = "disabled", + section = "options_experimental", + items = { + { key = "disabled", name = "Disabled", desc = "No community balance changes", + lock = {"community_balance_corspy","community_balance_armmav","community_balance_corcan","community_balance_corkarg","community_balance_armkam","community_balance_armblade"} }, + + { key = "enabled", name = "Enabled", desc = "Enable all community balance changes\nSpectre\nGunslinger\nSumo\nKarganeth\nBanshee\nHornet", + lock = {"community_balance_corspy","community_balance_armmav","community_balance_corcan","community_balance_corkarg","community_balance_armkam","community_balance_armblade"} }, + + { key = "custom", name = "Custom", desc = "Customize individual community balance changes", + unlock = {"community_balance_corspy", "community_balance_armmav", "community_balance_corcan", "community_balance_corkarg", "community_balance_armkam", "community_balance_armblade"} }, + } + }, + + { + key = "community_balance_patch_changelog_link", + name = "Changelog/Feedback", + desc = "Community Balance Patch discussion", + section = "options_experimental", + type = "link", + link = "https://discord.com/channels/549281623154229250/1512596823070740550", + width = 235, + column = 2.025, + linkheight = 325, + linkwidth = 350, + }, + + { + key = "community_balance_corspy", + name = "(CBP) Spectre", + desc = "(From February)\nEnergy cost: 8800 (from 12500)\nMetal cost: 135 (from 165)", + type = "bool", + def = false, + section = "options_experimental", + }, + + { + key = "community_balance_armmav", + name = "(CBP) Gunslinger", + desc = "(From April)\nMetal cost: 520 (from 650)\nEnergy cost: 6500 (from 11000)", + type = "bool", + def = false, + section = "options_experimental", + }, + + { + key = "community_balance_corcan", + name = "(CBP) Sumo", + desc = "(From April)\nMain laser range: 300 (from 275)\nMain laser beam time: 0.24 (from 0.16)", + type = "bool", + def = false, + section = "options_experimental", + }, + + { + key = "community_balance_corkarg", + name = "(CBP) Karganeth", + desc = "(New)\nSight distance: 515 (from 455)\nMax acceleration: 0.18 (from 0.1104)\nTurn rate: 515 (from 400)\nTurn-in-place speed limit: 1.25 (from 0.99)\nStrafe to attack: true (from false)\nMissile trajectory height: 0.25 (from none)\nMetal cost: 2650 (from 2500)\nBuild time: 100000 (from 94000)", + type = "bool", + def = false, + section = "options_experimental", + }, + + { + key = "community_balance_armkam", + name = "(CBP) Banshee", + desc = "(New)\nMax acceleration: 0.35 (from 0.15)\nWeapon range: 400 (from 350)\nWeapon reload: 3.0 (from 0.7)\nWeapon damage: 141 single shot (from 9 x 3 burst)\nArea of effect: 32 (from 40)\nEdge effectiveness: 0.40 (from 0.5)\nProjectile velocity: 1090 (from 1000)\nWeapon accuracy: 0 (from 13), spray angle removed (from 1024)\nCylindrical targeting: 0 (from 1)\nWeapon timer: 0 (from 0.1)\nWeapon tolerance: 2000 (from 5000)\nImpulse factor: 2.14 (from 0.123)\nWeapon visual: impulse-trail / genericshellexplosion-small-bomb (from plasmahit-small)\nWeapon sound: mavgun4 (from flashemg)\nTurret: true (from false)\nFiring arc: 45° forward, hidden attack range arc (from unrestricted/fixed)", + type = "bool", + def = false, + section = "options_experimental", + }, + + { + key = "community_balance_armblade", + name = "(CBP) Hornet", + desc = "(New)\nMax acceleration: 0.28 (from 0.6)\nMax deceleration: 0.55 (from 0.35)\nHealth: 3350 (from 3000)\nSpeed: 125 (from 204)\nTurn angle limit: 120 (from 360)\nTurn rate: 420 (from 720)\nSight distance: 720 (from 624)\nWeapon range: 1100 (from 420)\nWeapon reload: 4.0 (from 2.26667)\nWeapon damage: 425 x 2 burst (from 190 x 2 burst)\nCommander damage: 200 x 2 burst\nBurst rate: 0.15 (from 0.23333)\nArea of effect: 64 (from 32)\nEdge effectiveness: 0.40 (from 0.15)\nProjectile type: Cannon (from MissileLauncher)\nProjectile velocity: 1090 (from 1000)\nImpulse factor: 1.5 (from 0.123)\nWeapon visual: impulse-trail / genericshellexplosion-medium-bomb (from missiletrailsmall-simple / genericshellexplosion-medium)\nWeapon sound: mavgun5 / xplomed2 (from SabotFire / SabotHit)\nTurret: true (from false)\nFiring arc: 45° forward (from unrestricted)", + type = "bool", + def = false, + section = "options_experimental", + }, + + { + key = "experimentallegionfaction", + name = "Legion Faction", + desc = "3rd experimental faction", + type = "bool", + section = "options_experimental", + def = false, + }, + + { + key = "legionsimplifiedmexes", + name = "Legion Simplified Mexes", + desc = "Changes the legion T1 mex to act the same as the other T1 mexes. Legion light T1 units are given a higher metal cost but lower E cost, and heavy T1 units are given a higher E cost and slightly lower metal cost.", + type = "bool", + section = "options_experimental", + def = false, + }, + + { + key = "experimentallegionfaction_link", + name = "Development Discussion", + desc = "Discord discussion about Legion faction.", + section = "options_experimental", + type = "link", + link = "https://discord.com/channels/549281623154229250/1063217502898884701/1441480747629412675", + width = 275, + column = 1.65, + linkheight = 325, + linkwidth = 350, + }, + + { + key = "easytax", + name = "Easy Tax v2", + desc = "Anti co-op sharing tax mod. Overwrites other tax settings. Don't combine with other sharing restriction mods, everything you need is included with easy tax.", + type = "bool", + section = "options_experimental", + def = false, + }, + + { + key = "easytax_link", + name = "Changelog", + desc = "Easy Tax v2 description.", + section = "options_experimental", + type = "link", + link = "https://gist.github.com/RebelNode/43b986f29b9cfacbe95cf634cac25c49", + width = 215, + column = 1.65, + linkheight = 325, + linkwidth = 350, + }, + + -- Hidden Tests + + { + key = "techsplit", + name = "Tech Split", + desc = "Adds a new tier between T1 and T2 for bots and vehicles", + type = "bool", + hidden = true, + section = "options_experimental", + def = false, + }, + + { + key = "techsplit_balance", + name = "Tech Split Balance Test", + desc = "Adjusts the balance of units in the proposed tech split.", + type = "bool", + hidden = true, + section = "options_experimental", + def = false, + }, + + { + key = "experimental_defend_firestate", + name = "Defend Combat Stance", + desc = "Replaces Return Fire with the new Defend combat stance.\nDefending units will shoot threats to themselves when they become threats on a 1v1 basis.", + type = "bool", + section = "options_experimental", + def = false, + }, + + { + key = "experimental_defend_firestate_link", + name = "Feedback thread", + desc = "Discord discussion about the Defend Combat Stance rework.", + section = "options_experimental", + type = "link", + link = "https://discord.com/channels/549281623154229250/1520166826435280998", + width = 215, + column = 1.65, + linkheight = 325, + linkwidth = 350, + }, + + { + key = "air_rework", + name = "Air Rework", + desc = "Prototype version with more maneuverable, slower air units and more differentiation between them.", + hidden = true, + type = "bool", + section = "options_experimental", + def = false, + }, + + { + key = "skyshift", + name = "Skyshift: Air Rework", + desc = "A complete overhaul of air units and mechanics", + type = "bool", + def = false, + section = "options_experimental", + hidden = true, + }, + + { + key = "emprework", + name = "EMP Rework", + desc = "EMP is changed to slow units movement and firerate, before eventually stunning.", + type = "bool", + hidden = true, + section = "options_experimental", + + def = false, + }, + + { + key = "junorework", + name = "Juno Rework", + desc = "Juno stuns certain units (such as radars and jammers) rather than magically deleting them", + type = "bool", + hidden = true, + section = "options_experimental", + def = false, + }, + + { + key = "releasecandidates", + name = "Release Candidate Units", + desc = "Adds additional units to the game which are being considered for mainline integration and are balanced, or in end tuning stages. Currently adds Printer, Siegebreaker, Phantom (Core T2 veh), Shockwave (Arm T2 EMP Mex), and Drone Carriers for armada and cortex", + type = "bool", + hidden = true, + section = "options_experimental", + def = false, + }, + + { + key = "naval_balance_tweaks", + name = "Proposed Naval Balance Tweaks", + desc = "Modoption used to test specific balance adjustments dedicated towards naval units.", + type = "bool", + --hidden = true, + section = "options_experimental", + def = false, + }, + + { + key = "naval_balance_tweaks_link", + name = "Feedback thread", + desc = "Discord discussion about naval balance tweaks.", + section = "options_experimental", + type = "link", + link = "https://discord.com/channels/549281623154229250/1428031834045939833", + width = 215, + column = 1.65, + linkheight = 325, + linkwidth = 350, + }, + + { + key = "forge_volcano", + name = "Forge Volcano Event", + desc = "Enable the cinematic volcano eruption event on Forge v2.3.", + type = "bool", + hidden = true, + section = "options_experimental", + def = false, + }, + + { + key = "factory_costs", + name = "Factory Costs Test Patch", + desc = "Cheaper and more efficient factories, more expensive nanos, and slower to build higher-tech units. Experimental, not expected to be balanced by itself - a test to try how the game plays if each player is more able to afford their own T2 factory, while making assisting them less efficient.", + type = "bool", + hidden = true, + section = "options_experimental", + def = false, + }, + + --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + -- Unused Options + --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + + { + key = "modes", + name = "GameModes", + desc = "Game Modes", + hidden = true, + type = "section", + }, + + { + key = "shareddynamicalliancevictory", + name = "Dynamic Ally Victory", + desc = "Ingame alliance should count for game over condition.", + hidden = true, + type = "bool", + section = "options", + def = false, + }, + + { + key = "ai_incomemultiplier", + name = "AI Income Multiplier", + desc = "Multiplies AI resource income", + hidden = true, + type = "number", + section = "options", + def = 1, + min = 1, + max = 10, + step = 0.1, + }, + + { + key = "defaultdecals", + name = "Default Decals", + desc = "Use the default explosion decals instead of Decals GL4", + section = "options_experimental", + type = "bool", + def = true, + hidden = true, + }, + + --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + -- DEV mode only mod option otherwise hidden by chobby + --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + + { + key = "dev", + name = "_DEV", + desc = "tab that should be hidden by chobby", + hidden = true, + type = "section", + }, + { + key = "teamcolors_icon_dev_mode", + name = "Icon Dev Mode ", + desc = "(Don't use in normal games) Forces teamcolors to be an specific one, for all teams", + type = "list", + section = "dev", + def = "disabled", + items = { + { key = "disabled", name = "Disabled", desc = "description" }, + { key = "armblue", name = "Armada Blue", desc = "description" }, + { key = "corred", name = "Cortex Red", desc = "description" }, + { key = "scavpurp", name = "Scavenger Purple", desc = "description" }, + { key = "raptororange", name = "Raptor Orange", desc = "description" }, + { key = "gaiagray", name = "Gaia Gray", desc = "description" }, + { key = "leggren", name = "Legion Green", desc = "description" }, + } + }, + { + key = "debugcommands", + name = "Debug Commands", + desc = "A pipe separated list of commands to execute at [gameframe]:luarules benchmark|100:forcequit...", -- example: debugcommands=150:cheat 1|200:luarules benchmark|600:quitforce; + section = "dev", + type = "string", + def = "", + }, + { + key = "animationcleanup", + name = "Animation Cleanup", + desc = "Use animations from the BOSCleanup branch", -- example: debugcommands=150:cheat 1|200:luarules benchmark|600:quitforce; + section = "dev", + type = "bool", + def = false, + }, + { + key = "pushresistant", + name = "Pushresistance", + desc = "Enable to do desync test by the use of pushresistance", + section = "dev", + type = "bool", + def = false, + }, + { + key = "dummyboolfeelfreetotouch", + name = "dummy to hide some modoptions", + desc = "This is a dummy to hide some modoptions to not bloat the changed options panel with unneeded information", + section = "dev", + type = "bool", + -- This doesn't have a default on purpse, do not add one + unlock = {"dummyboolfeelfreetotouch", "factionlimiter", "date_year", "date_month", "date_day", "date_hour"}, + }, + { key = "date_year", name = "Year", desc = "Spads (Multiplayer) / Skirmish Interface (Singleplayer) fed, auto-overwriten", section = "dev", type = "number", def = 0, min = 0, max = 3000, step = 1, }, + { key = "date_month", name = "Month", desc = "Spads (Multiplayer) / Skirmish Interface (Singleplayer) fed, auto-overwriten", section = "dev", type = "number", def = 0, min = 0, max = 12, step = 1, }, + { key = "date_day", name = "Day", desc = "Spads (Multiplayer) / Skirmish Interface (Singleplayer) fed, auto-overwriten", section = "dev", type = "number", def = 0, min = 0, max = 31, step = 1, }, + { key = "date_hour", name = "Hour", desc = "Spads (Multiplayer) / Skirmish Interface (Singleplayer) fed, auto-overwriten", section = "dev", type = "number", def = 0, min = 0, max = 24, step = 1, }, + { + key = "factionlimiter", + name = "Faction Limiter:".."\255\255\191\76".." ON\n".."\255\125\125\125".."BITMASK", + desc = [[BITMASK to be used via custom ui, only visible when boss +Set to [0] To disable. +Otherwise: 0th, 1st and 2nd bit are armada, cortex and legion respectively. +Offset by 3 for each consecutive team. +If a team's bitmask is 0, All are Enabled. +Example: Armada VS Cortex VS Legion: 273 or 100 010 001 or 256 + 16 + 1]], + section = "dev", + type = "number", + def = 0, + min = 0, + max = 16777215,-- math hard, 24 bit limitish? + step = 1, + }, + + --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + -- Map Metadata options + --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + -- + -- The modoptions below are intended to be set automatically by lobby/spads based on the selected + -- map name. They are used for a dynamic map configuration where the configruation values are not + -- tied to either game version or reside inside of the map file, allowing for independent distribution + -- from the maps metadata source of truth: https://github.com/beyond-all-reason/maps-metadata + { + key = "mapmetadata", + name = "MapMetadata", + desc = "mapmetadata tab that should be hidden by chobby, which would have ideally been achieved by just not listing it and the following options here in the first place, but then SPADS refuses to set the modoption", + hidden = true, + type = "section", + }, + { + key = "sub_header", + name = "Hidden map metadata options that are supposed to be set automatically by lobby/spads based on the map name.", + desc = "", + section = "mapmetadata", + type = "subheader", + hidden = true, + def = true, + }, + { + key = "mapmetadata_startpos", + name = "Map Metadata: StartPos", + desc = "StartPos configuration. Format is: base64url(zlib(json))", + hidden = true, + section = "mapmetadata", + type = "string", + def = "", + }, + { + key = "mapmetadata_startboxes_set", + name = "Map Metadata: Startboxes Set", + desc = "Per-team-count startbox arrangements (rect or polygon). Format is: base64url(zlib(json))", + hidden = true, + section = "mapmetadata", + type = "string", + def = "", + }, + { + key = "mapmetadata_startbox_override", + name = "Map Metadata: Startbox Override", + desc = "Custom startbox arrangement that overrides the set when its team count matches. Format is: base64url(zlib(json))", + hidden = true, + section = "mapmetadata", + type = "string", + def = "", + }, + --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + -- Cheats + --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + + { + key = "options_cheats", + name = "Cheats", + desc = "Options that alter the game balance in unintended way, Use at your own risk.", + type = "section", + weight = -1, + }, + + { + key = "sub_header", + name = "Warning: changing these options will alter the intended game experience and may have bad results. Proceed at your own risk!", + desc = "", + section = "options_cheats", + type = "subheader", + def = true, + }, + + { + key = "sub_header", + name = "When any of these options are changed, there is no guarantee they will work properly, especially when combined.", + desc = "", + section = "options_cheats", + type = "subheader", + def = true, + }, + + { + key = "sub_header", + section = "options_cheats", + type = "separator", + }, + + { + key = "sub_header", + name = "-- AI Cheats", + desc = "", + section = "options_cheats", + type = "subheader", + def = true, + }, + + { + key = "dynamiccheats", + name = "Dynamic Cheats", + desc = "Cheats marked as [Dynamic] react to the game state and are suspended when the opposition is losing", + type = "bool", + def = true, + section = "options_cheats", + }, + + { + key = "nowasting", + name = "No Resource Wasting", + desc = "[Dynamic] Increases Buildpower for the affected team's builders and factories to prevent resource", + type = "list", + def = "default", + section = "options_cheats", + items = { + { key= "default", name= "Default", desc="Disabled, unless other features use it"}, + { key= "disabled", name= "Disabled", desc="Disabled"}, + { key= "ai", name= "AI Only", desc="All AI except Scavengers and Raptors"}, + { key= "all", name= "All", desc="AI and Player Teams both excluding Scavengers and Raptors" }, + } + }, + + { + key = "allow_enemy_ai_spawn_placement", + name = "Allow Hostile AI Spawn Placement", + desc = "When enabled, allows enemy allyteams to view and place enemy AI start positions during the pregame", + type = "bool", + def = false, + section = "options_cheats", + }, + + { + key = "sub_header", + section = "options_cheats", + type = "separator", + }, + + { + key = "sub_header", + name = "-- Starting Resources", + desc = "", + section = "options_cheats", + type = "subheader", + def = true, + }, + + { + key = "startmetal", + name = "Starting Metal", + desc = "(Range 0 - 10 000). Determines amount of metal and metal storage that each player will start with", + type = "number", + section = "options_cheats", + def = 1000, + min = 0, + max = 10000, + step = 1, + }, + + { + key = "startmetalstorage", + name = "Starting Metal Storage", + desc = "(Range 1000 - 20 000). Only works if it's higher than Starting metal. Determines amount of metal and metal storage that each player will start with", + type = "number", + section = "options_cheats", + def = 1000, + min = 1000, + max = 20000, + step = 1, + }, + + { + key = "startenergy", + name = "Starting Energy", + desc = "(Range 0 - 10 000). Determines amount of energy and energy storage that each player will start with", + type = "number", + section = "options_cheats", + def = 1000, + min = 0, + max = 10000, + step = 1, + }, + + { + key = "startenergystorage", + name = "Starting Energy Storage", + desc = "(Range 1000 - 20 000). Only works if it's higher than Starting energy. Determines amount of energy and energy storage that each player will start with", + type = "number", + section = "options_cheats", + def = 1000, + min = 1000, + max = 20000, + step = 1, + }, + + { + key = "bonusstartresourcemultiplier", + name = "Apply Bonus to Starting Resources", + desc = "If enabled, multiplies each players starting resources with their bonus.", + type = "bool", + section = "options_cheats", + def = false, + }, + + { + key = "sub_header", + section = "options_cheats", + type = "separator", + }, + + { + key = "sub_header", + name = "-- Resource Multipliers", + desc = "", + section = "options_cheats", + type = "subheader", + def = true, + }, + + { + key = "multiplier_resourceincome", + name = "Overall Resource Income", + desc = "(Range 0.1 - 10). Stacks up with the three options below.", + type = "number", + section = "options_cheats", + def = 1, + min = 0.1, + max = 10, + step = 0.1, + }, + + { + key = "multiplier_metalextraction", + name = "Metal Extraction ", + desc = "(Range 0.1 - 10).", + type = "number", + section = "options_cheats", + def = 1, + min = 0.1, + max = 10, + step = 0.1, + }, + + { + key = "multiplier_energyconversion", + name = "Energy Conversion Efficiency", + desc = "(Range 0.1 - 2). lower means you get less metal per energy converted", + type = "number", + section = "options_cheats", + def = 1, + min = 0.1, + max = 2, + step = 0.1, + }, + + { + key = "multiplier_energyproduction", + name = "Energy Production", + desc = "(Range 0.1 - 10).", + type = "number", + section = "options_cheats", + def = 1, + min = 0.1, + max = 10, + step = 0.1, + }, + + { + key = "sub_header", + section = "options_cheats", + type = "separator", + }, + + { + key = "cheatsdescription7", + name = "-- Unit Parameter Multipliers", + desc = "", + section = "options_cheats", + type = "subheader", + def = true, + }, + + { + key = "multiplier_maxvelocity", + name = "Unit Max Velocity", + desc = "(Range 0.1 - 10).", + type = "number", + section = "options_cheats", + def = 1, + min = 0.1, + max = 10, + step = 0.1, + }, + + { + key = "multiplier_turnrate", + name = "Unit Turn Rate", + desc = "(Range 0.1 - 10).", + type = "number", + section = "options_cheats", + def = 1, + min = 0.1, + max = 10, + step = 0.1, + }, + + { + key = "multiplier_builddistance", + name = "Build Range", + desc = "(Range 0.5 - 10).", + type = "number", + section = "options_cheats", + def = 1, + min = 0.5, + max = 10, + step = 0.1, + }, + + { + key = "multiplier_buildpower", + name = "Build Power", + desc = "(Range 0.1 - 10).", + type = "number", + section = "options_cheats", + def = 1, + min = 0.1, + max = 10, + step = 0.1, + }, + + { + key = "multiplier_losrange", + name = "Vision Range", + desc = "(Range 0.5 - 10).", + type = "number", + section = "options_cheats", + def = 1, + min = 0.5, + max = 10, + step = 0.1, + }, + + { + key = "multiplier_radarrange", + name = "Radar And Sonar Range", + desc = "(Range 0.5 - 10).", + type = "number", + section = "options_cheats", + def = 1, + min = 0.5, + max = 10, + step = 0.1, + }, + + { + key = "multiplier_weaponrange", + name = "Weapon Range", + desc = "(Range 0.5 - 10).", + type = "number", + section = "options_cheats", + def = 1, + min = 0.5, + max = 10, + step = 0.1, + }, + + { + key = "multiplier_weapondamage", + name = "Weapon Damage", + desc = "(Range 0.1 - 10). Also affects unit death explosions.", + type = "number", + section = "options_cheats", + def = 1, + min = 0.1, + max = 10, + step = 0.1, + }, + + { + key = "multiplier_shieldpower", + name = "Shield Power", + desc = "(Range 0.1 - 10)", + type = "number", + section = "options_cheats", + def = 1, + min = 0.1, + max = 10, + step = 0.1, + }, + + { + key = "sub_header", + section = "options_cheats", + type = "separator", + }, + + { + key = "cheatsdescription7", + name = "-- Other", + desc = "", + section = "options_cheats", + type = "subheader", + def = true, + }, + + { + key = "experimentalshields", + name = "Shield Type Override", + desc = "Shield Type Override", + type = "list", + section = "options_cheats", + def = "unchanged", + hidden = true, + items = { + { key = "unchanged", name = "Unchanged", desc = "Unchanged" }, + { key = "absorbeverything", name = "Absorb Everything", desc = "Shields absorb everything" }, + { key = "bounceplasma", name = "Deflect Plasma", desc = "Shields deflect plasma only" }, + { key = "bounceeverything", name = "Deflect Everything", desc = "Shields deflect everything" }, + } + }, + + { + key = "tweakunits", + name = "Tweak Units", + desc = "For advanced users!!! A base64 encoded lua table of unit parameters to change.", + hint = "Input must be base64", + section = "options_cheats", + type = "string", + def = "", + }, + + { + key = "tweakdefs", + name = "Tweak Defs", + desc = "For advanced users!!! A base64 encoded snippet of code that modifies game definitions.", + hint = "Input must be base64", + section = "options_cheats", + type = "string", + def = "", + }, + + { + key = "forceallunits", + name = "Force Load All Units (Dev/Modding)", + desc = "Load all UnitDefs even if ais or options for them aren't enabled", + section = "options_cheats", + type = "bool", + def = false, + }, + + { + key = "holiday_events", + name = "Enable Holiday Events", + desc = "", + section = "options_cheats", + type = "bool", + def = true, + hidden = true, + }, + +} + --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + -- End Options + --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +for i = 1, 9 do + options[#options + 1] = { + key = "tweakunits" .. i, + name = "Tweak Units " .. i, + desc = "A base64 encoded lua table of unit parameters to change.", + section = "options_extra", + type = "string", + def = "", + hidden = true, + } +end + +for i = 1, 9 do + options[#options + 1] = { + key = "tweakdefs" .. i, + name = "Tweak Defs " .. i, + desc = "A base64 encoded snippet of code that modifies game definitions.", + section = "options_extra", + type = "string", + def = "", + hidden = true, + } +end + +return options + +end)() +local VFS={Include=function(path)assert(path=="modoptions.lua");return options end} +if Spring.GetModOptions then + local modOptions = Spring.GetModOptions() + local modOptionsFile = VFS.Include('modoptions.lua') + + for _, modOption in ipairs(modOptionsFile) do + local key = modOption.key + + if modOption.type ~= "section" then + if modOptions[key] == nil then + modOptions[key] = modOption.def + end + + if (modOption.type == 'bool') and (type(modOptions[key]) ~= 'boolean') then + local value = tonumber(modOptions[key]) + modOptions[key] = value == 1 and true or false + end + + if modOption.type == 'number' then + modOptions[key] = tonumber(modOptions[key]) + end + end + end + + -- Prevent widgets from messing with each other's modoptions table. + -- The native engine call does this by returning a new table each time but that is wasteful + local readOnlyModOptions = {} + setmetatable(readOnlyModOptions, { + __index = modOptions, + __newindex = function(t, k, v) + error("attempt to update a read-only Spring.GetModOptions table", 2) + end + }) + + Spring.GetModOptions = function () + return readOnlyModOptions + end + + -- Returns a copy of the modOptions table. Slower, but allows iterating over + -- the returned table using pairs/ipairs. + Spring.GetModOptionsCopy = function () + return table.copy(modOptions) + end +end + +if Spring.Echo then + local echo = Spring.Echo + local printOptions = { pretty = true } + + local function multiEcho(...) + local n = select('#', ...) + local firstTableIndex + local tableCount = 0 + + for index = 1, n do + if type(select(index, ...)) == 'table' then + tableCount = tableCount + 1 + if not firstTableIndex then + firstTableIndex = index + end + end + end + + if tableCount == 0 then + echo(...) + return + end + + -- When Spring.Echo is called with a single table parameter, engine will echo "TABLE: {value}", + -- where {value} is whatever value happens to be the first value in the table + if tableCount == 1 and n == 1 then + echo("
") + else + echo(...) + end + + local args = table.pack(...) + for index = firstTableIndex, n do + if type(args[index]) == 'table' then + echo(table.toString(args[index], printOptions)) + end + end + end + + Spring.Echo = multiEcho +end + +Spring.Debug=(function() +local function paramsEcho(...) + local called_from = "Called from: " .. tostring(debug.getinfo(2).name) .. " args:" + Spring.Echo(called_from) + local args = { ... } + Spring.Echo( table.toString(args) ) + return ... +end + +local function traceEcho(...) + local myargs = {...} + local parts = {} + local n = 0 + for i = 1, #myargs do + n = n + 1; parts[n] = tostring(myargs[i]) + n = n + 1; parts[n] = "\t" + end + local infostr = n > 0 and (table.concat(parts) .. " ") or "" + local functionstr = "Trace:[" + for i = 2, 10 do + local info = debug.getinfo(i) + if info then + local funcName = info.name + if funcName then + functionstr = functionstr .. tostring(funcName) .. " <- " + else break end + else break end + end + functionstr = functionstr .. "]" + local arguments = "" + local info2 = debug and debug.getinfo(2) + local funcName1 = (info2 and info2.name) or "??" + if funcName1 ~= "??" then + for i = 1, 10 do + local name, value = debug.getlocal(2, i) + if not name then break end + local sep = ((arguments == "") and "") or "; " + arguments = arguments .. sep .. ((name and tostring(name)) or "name?") .. "=" .. tostring(value) + end + end + Spring.Echo(infostr .. functionstr .. " Args:(" .. arguments .. ")") +end + +local function traceFullEcho(maxdepth, maxwidth, maxtableelements, ...) + -- Call it at any point, and it will give you the name of each function on the stack (up to maxdepth), + -- all arguments and first #maxwidth local variables of that function + -- if any of the values of the locals are tables, then it will try to shallow print + count them up to maxtablelements numbers. + -- It will also just print any args after the first 3. (the ... part) + -- It will also try to print the source file+line of each function + if (debug) then + else + Spring.Echo("traceFullEcho needs debug to work, this seems to be missing or overwritten", debug) + return + end + local tracedebug = false -- to debug itself + local functionsource = true + maxdepth = maxdepth or 16 + maxwidth = maxwidth or 10 + maxtableelements = maxtableelements or 6 -- max amount of elements to expand from table type values + + local function dbgt(t, maxtableelements) + local count = 0 + local res = '' + for k,v in pairs(t) do + count = count + 1 + if count < maxtableelements then + if tracedebug then Spring.Echo(count, k) end + if type(k) == "number" and type(v) == "function" then -- try to get function lists? + local vinfo = debug.getinfo(v) + if tracedebug then Spring.Echo(k,v, vinfo, vinfo.name) end --debug.getinfo(v).short_src)? + res = res .. tostring(k) .. ':' .. ((vinfo and vinfo.name) or "") ..', ' + else + res = res .. tostring(k) .. ':' .. tostring(v) ..', ' + end + end + end + res = '{'..res .. '}[#'..count..']' + return res + end + + local myargs = {...} + local infostr = "TraceFullEcho:[" + for i,v in ipairs(myargs) do + infostr = infostr .. tostring(v) .. "\t" + end + infostr = infostr .. "]\n" + local functionstr = "" -- "Trace:[" + for i = 2, maxdepth do + local info = debug.getinfo(i) + if info then + local funcName = info.name + if funcName then + functionstr = functionstr .. tostring(i-1) .. ": " .. tostring(funcName) .. " " + local arguments = "" + if funcName ~= "??" then + if functionsource and info.source then + local source = info.source + if string.len(source) > 128 then source = "sourcetoolong" end + functionstr = functionstr .. " @" .. source + end + if functionsource and info.linedefined then + functionstr = functionstr .. ":" .. tostring(info.linedefined) + end + for j = 1, maxwidth do + local name, value = debug.getlocal(i, j) + if not name then break end + if tracedebug then Spring.Echo(i,j, funcName,name) end + local sep = ((arguments == "") and "") or "; " + if tostring(name) == 'self' then + arguments = arguments .. sep .. ((name and tostring(name)) or "name?") .. "=" .. tostring("??") + else + local newvalue + if maxtableelements > 0 and type({}) == type(value) then newvalue = dbgt(value, maxtableelements) else newvalue = value end + arguments = arguments .. sep .. ((name and tostring(name)) or "name?") .. "=" .. tostring(newvalue) + end + end + end + functionstr = functionstr .. " Locals:(" .. arguments .. ")" .. "\n" + else + functionstr = functionstr .. tostring(i-1) .. ": ??\n" + end + else break end + end + Spring.Echo(infostr .. functionstr) +end + +return { + ParamsEcho = paramsEcho, + TraceEcho = traceEcho, + TraceFullEcho = traceFullEcho, +} +end)() +-- Graphics-only compatibility storage for original policy. No drawing, engine +-- buffer upload, commands, VFS/IO, configuration or selection mutation. +local function noop()end +WG={};LOG={DEPRECATED=0} +GL={ARRAY_BUFFER=34962,UNSIGNED_INT=5125,POINTS=0,TRIANGLES=4,TRIANGLE_STRIP=5} +local storage={Define=noop,Upload=noop,Delete=noop,InstanceDataFromUnitIDs=noop,InstanceDataFromFeatureIDs=noop,GetID=function()return 1 end} +local vao={AttachVertexBuffer=noop,AttachInstanceBuffer=noop,AttachIndexBuffer=noop,DrawArrays=noop,DrawElements=noop,Delete=noop} +local shader={Activate=noop,Deactivate=noop,SetUniform=noop} +local unitUniforms,featureUniforms={},{} +local function uniforms(target,id,values,offset) + assert(type(id)=='number'and id>=0 and id%1==0 and type(values)=='table','Invalid original healthbar uniform write') + offset=math.max(offset or 0,0);local count=math.min(#values,16-offset) + if count<1 then return 0 end + local row=target[id];if not row then row={};for i=1,16 do row[i]=0 end;target[id]=row end + for i=1,count do row[offset+i]=values[i]end + return count +end +gl={GetVBO=function()return setmetatable({},{__index=storage})end,GetVAO=function()return setmetatable({},{__index=vao})end, + CreateShader=noop,LuaShader={isGeometryShaderSupported=true,CheckShaderUpdates=function()return shader end}, + SetUnitBufferUniforms=function(id,values,offset)return uniforms(unitUniforms,id,values,offset)end, + SetFeatureBufferUniforms=function(id,values,offset)return uniforms(featureUniforms,id,values,offset)end} +-- This handle supplies policy to a graphical browser. Headless GL calls are +-- replaced by private storage, so the original forwarder can retain its writes. +Spring.GetConfigInt=function(name,default)if name=='Headless'then return 0 end;return default or 0 end +Spring.GetViewGeometry=function()return 1280,720 end +local removed=false +widgetHandler={RegisterGlobal=noop,DeregisterGlobal=noop,AddAction=noop,RemoveAction=noop,RemoveWidget=function()removed=true end,AddSpadsMessage=noop} +local listeners,actions={},{} +local widgetEventUnit,widgetEventLos +Script.LuaUI=setmetatable({},{__call=function(_,name)return listeners[name]~=nil end,__index=function(_,name)return function(...)return assert(listeners[name],'Unbound original healthbar LuaUI callback '..name)(...)end end}) +gadgetHandler={IsSyncedCode=function()return false end,AddSyncAction=function(_,name,fn)assert(not actions[name]);actions[name]=fn end,RemoveSyncAction=function(_,name)actions[name]=nil end} + +-------------------------------------------------------------------------------- +-------------------------------------------------------------------------------- +-- +-- file: setupdefs.lua +-- brief: setup some custom UnitDefs parameters, +-- and UnitDefNames, FeatureDefNames, WeaponDefNames +-- author: Dave Rodgers +-- +-- Copyright (C) 2007. +-- Licensed under the terms of the GNU GPL, v2 or later. +-- +-------------------------------------------------------------------------------- +-------------------------------------------------------------------------------- + +for _,ud in pairs(UnitDefs) do + -- set the cost value (same as shown in the tooltip) + ud.cost = ud.metalCost + (ud.energyCost / 60.0) + + -- add the custom weapons based parameters + ud.hasShield = false + ud.canParalyze = false + ud.canStockpile = false + ud.canAttackWater = false + ud.wDefs = {} + for i, wt in ipairs(ud.weapons) do + local wd = WeaponDefs[wt.weaponDef] + ud.wDefs[i] = wd + if (wd) then + if (wd.isShield) then ud.hasShield = true end + if (wd.paralyzer) then ud.canParalyze = true end + if (wd.stockpile) then ud.canStockpile = true end + if (wd.waterWeapon) then ud.canAttackWater = true end + end + end +end + +-------------------------------------------------------------------------------- +-------------------------------------------------------------------------------- + +-- setup the UnitDefNames{} table +do + local tbl = {} + for _,def in pairs(UnitDefs) do + tbl[def.name] = def + end + UnitDefNames = tbl +end + +-- setup the FeatureDefNames{} table +do + local tbl = {} + for _,def in pairs(FeatureDefs) do + tbl[def.name] = def + end + FeatureDefNames = tbl +end + +-- setup the WeaponDefNames{} table +do + local tbl = {} + for _,def in pairs(WeaponDefs) do + tbl[def.name] = def + end + WeaponDefNames = tbl +end + +-------------------------------------------------------------------------------- +-------------------------------------------------------------------------------- + + +gl.InstanceVBOTable=(function() +local GL_BUFFER = 0x82E0 +local gldebugannotations = (Spring.GetConfigInt("gldebugannotations") == 1) +--Spring.Echo("gldebugannotations", gldebugannotations) +local function makeInstanceVBOTable(layout, maxElements, myName, unitIDattribID) + -- layout: this must be an array of tables with at least the following specified: {{id = 1, name = 'optional', size = 4}} + -- maxElements: will be dynamic anyway, but defaults to 64 + -- myName: optional name, useful for debugging + -- unitIDattribID: the attribute ID in the layout of the uvec4 of unitID bindings (e.g. 4 for {id = 4, name = 'instData', type = GL.UNSIGNED_INT, size= 4} ) + -- returns: nil | instanceTable + if maxElements == nil then maxElements = 64 end -- default size + if myName == nil then myName = "InstanceVBOTable" end + local newInstanceVBO = gl.GetVBO(GL.ARRAY_BUFFER,true) + if newInstanceVBO == nil then Spring.Echo("makeInstanceVBOTable, cannot get VBO for", myName); return nil end + newInstanceVBO:Define( + maxElements, + layout + ) + + + + local instanceStep = 0 + for i,attribute in pairs(layout) do + instanceStep = instanceStep + attribute.size + end + local instanceData = {} + for i = 1, instanceStep * maxElements do + instanceData[i] = 0 + end + local instanceTable = { + instanceVBO = newInstanceVBO, + instanceData = instanceData, + instanceStep = instanceStep, + usedElements = 0, + maxElements = maxElements, + myName = myName, + instanceIDtoIndex = {}, -- this maps each instance ID to where it is in the buffer, 1 based + indextoInstanceID = {}, -- this tells us what instanceID is located in any given pos + layout = layout, + dirty = false, + numVertices = 0, + primitiveType = GL.TRIANGLES, + debugZombies = true, -- this is new, and its for debugging non-existing stuff on unitdestroyed + lastInstanceID = 0, + } + + if unitIDattribID ~= nil then + instanceTable.indextoUnitID = {} + instanceTable.unitIDattribID = unitIDattribID + instanceTable.popUnitIDFailuresInGameFrame = {} + end + + function instanceTable:clearInstanceTable() + -- this wont resize it, but quickly sets it to empty + self.usedElements = 0 + self.instanceIDtoIndex = {} + self.indextoInstanceID = {} + if self.indextoUnitID then self.indextoUnitID = {} end + end + + function instanceTable:makeVAOandAttach(vertexVBO, instanceVBO, indexVBO) -- Attach a vertex buffer to an instance buffer, and optionally, an index buffer if one is supplied. + -- There is a special case for this, when we are using a vertexVBO as a quasi-instanceVBO, e.g. when we are using the geometry shader to draw a vertex as each instance. + --iT.vertexVBO = vertexVBO + --iT.indexVBO = indexVBO + local newVAO = nil + newVAO = gl.GetVAO() + if newVAO == nil then goodbye("Failed to create newVAO") end + self.VAO = newVAO + if vertexVBO == nil then -- the special case where are using 'vertices' as 'instances' + newVAO:AttachVertexBuffer(instanceVBO) + else + newVAO:AttachVertexBuffer(vertexVBO) + newVAO:AttachInstanceBuffer(instanceVBO) + self.vertexVBO = vertexVBO + self.instanceVBO = instanceVBO + end + if indexVBO then + newVAO:AttachIndexBuffer(indexVBO) + self.indexVBO = indexVBO + function self:Draw() + self.VAO:DrawElements(GL.TRIANGLES, nil, 0, self.usedElements, 0) + end + else + function self:Draw() + self.VAO:DrawArrays(GL.TRIANGLES, nil, 0, self.usedElements, 0) + end + end + return newVAO + end + + function instanceTable:clearInstanceTable() + -- this wont resize it, but quickly sets it to empty + self.usedElements = 0 + self.instanceIDtoIndex = {} + self.indextoInstanceID = {} + if self.indextoUnitID then self.indextoUnitID = {} end + end + + function instanceTable:compact() + self.destroyedElements = 0 + -- so this is for the edge case, where we have silently removed elements from instanceIDtoIndex + -- where we have holes everywhere, so we have to 'compact' the table, + -- by copying back contiguously while preserving element order + local newInstanceIDtoIndex = {} + local newIndexToInstanceID = {} + local newInstanceData = {} + local newUsedElements = 0 + for i = 1, self.usedElements do + local instanceID = self.indextoInstanceID[i] + local index = self.instanceIDtoIndex[self.indextoInstanceID[i]] + if index then + local instanceStep = self.instanceStep + local instanceData = self.instanceData + + local dstpos = newUsedElements * instanceStep + local srcpos = (i - 1) * instanceStep + for j=1, instanceStep do + newInstanceData[dstpos + j] = instanceData[srcpos +j] + end + newUsedElements = newUsedElements + 1 + newInstanceIDtoIndex[instanceID] = newUsedElements + newIndexToInstanceID[newUsedElements] = instanceID + else + --Spring.Echo("compacting index",i, 'instanceID', instanceID) + end + end + --Spring.Echo("Post compacting", self.usedElements, newUsedElements) + self.usedElements = newUsedElements + self.instanceIDtoIndex = newInstanceIDtoIndex + self.indextoInstanceID = newIndexToInstanceID + self.instanceData = newInstanceData + --iT.instanceVBO:Upload(iT.instanceData,nil,oldElementIndex-1,oldOffset +1,oldOffset + iTStep) + if self.usedElements > 0 then + self.instanceVBO:Upload(self.instanceData) + end + end + + + function instanceTable:draw(primitiveType) + if self.usedElements > 0 then + if self.indexVBO then + self.VAO:DrawElements(primitiveType or self.primitiveType, self.numVertices, 0, self.usedElements,0) + else + self.VAO:DrawArrays (primitiveType or self.primitiveType, self.numVertices, 0, self.usedElements,0) + end + end + end + + function instanceTable:getMemUsage() + -- arrays are 16 bytes per element + -- Hash tables are 40 bytes per element + local totalMem = 0 + totalMem = totalMem + self.usedElements * self.instanceStep * 16 -- the actual instance data + totalMem = totalMem + self.usedElements * 16 -- indextoinstanceid + totalMem = totalMem + self.usedElements * 40 -- instanceIDtoIndex + if self.indextoUnitID then totalMem = totalMem + self.usedElements * 16 end + return totalMem + end + + function instanceTable:Delete() + -- Frees the instancevbo and vao for this instance table. Does not touch the vertex and index vbos. + -- returns an estimate of how much ram was used + if self.instanceVBO then self.instanceVBO:Delete() end + if self.VAO then self.VAO:Delete() end + local memusage = self:getMemUsage() + self:clearInstanceTable() + return memusage + end + + + newInstanceVBO:Upload(instanceData) + + -- I believe that the openGL spec doesnt guarantee that a buffer has an idea before data is uploaded to it, so we will fill it with zeros. + if gldebugannotations then + gl.ObjectLabel(GL_BUFFER, newInstanceVBO:GetID(), myName) + end + + + --register self in WG if possible + if WG then + if WG.VBOTableRegistry == nil then + --Spring.Echo("WG.VBORegistry == nil, creating registry on first load") + WG.VBOTableRegistry = {} + end + if WG.VBOTableRegistry[instanceTable.myName] then + local newname = instanceTable.myName .. tostring(math.random()) + --Spring.Echo(instanceTable.myName, 'already registered, renaming to', newname) + instanceTable.myName = newname + end + --Spring.Echo("Registered ", instanceTable.myName) + WG.VBOTableRegistry[instanceTable.myName] = instanceTable + end + + return instanceTable +end + +local function nextInstanceID(iT) + iT.lastInstanceID = iT.lastInstanceID + 1 + return iT.lastInstanceID +end + +local function clearInstanceTable(iT) + -- this wont resize it, but quickly sets it to empty + iT.usedElements = 0 + iT.instanceIDtoIndex = {} + iT.indextoInstanceID = {} + if iT.indextoUnitID then iT.indextoUnitID = {} end +end + +local function makeVAOandAttach(vertexVBO, instanceVBO, indexVBO) -- Attach a vertex buffer to an instance buffer, and optionally, an index buffer if one is supplied. + -- There is a special case for this, when we are using a vertexVBO as a quasi-instanceVBO, e.g. when we are using the geometry shader to draw a vertex as each instance. + --iT.vertexVBO = vertexVBO + --iT.indexVBO = indexVBO + local newVAO = nil + newVAO = gl.GetVAO() + if newVAO == nil then goodbye("Failed to create newVAO") end + if vertexVBO == nil then -- the special case where are using 'vertices' as 'instances' + newVAO:AttachVertexBuffer(instanceVBO) + else + newVAO:AttachVertexBuffer(vertexVBO) + newVAO:AttachInstanceBuffer(instanceVBO) + end + if indexVBO then + newVAO:AttachIndexBuffer(indexVBO) + end + -- this allows us to set up our sane + + + return newVAO +end + + +--------------- DEBUG HELPERS -------------------------- +local function comparetables(t1, t2, name) + for k,v in pairs(t1) do + if t2[k] == nil then + Spring.Echo("Key ",k,"with value",v,"existing in t1 does not exist in t2 in ", name) + elseif t2[k] ~= v then + Spring.Echo("Value ",v,"for",k,"existing in t1 does not match value for t2",t2[k]," in ", name) + end + end + + for k,v in pairs(t2) do + if t1[k] == nil then + Spring.Echo("Key ",k,"with value",v,"existing in t2 does not exist in t1 in ", name) + elseif t1[k] ~= v then + Spring.Echo("Value ",v,"for",k,"existing in t2 does not match value for t1",t1[k]," in ", name) + end + end +end + +local function dbgt(t, name) + name = name or "" + local gf = Spring.GetGameFrame() + local count = 0 + local res = '' + for k,v in pairs(t) do + if type(k) == 'number' and type(v) == 'number' then + res = res .. tostring(k) .. ':' .. tostring(v) ..',' + count = count + 1 + end + end + Spring.Echo(tostring(gf).. " " ..name .. ' #' .. tostring(count) .. ' {'..res .. '}') + return res +end + +local function counttable(t) + local count = 0 + if type(t) ~= type({}) then return 0 end + for k, v in pairs(t) do count = count + 1 end + return count +end + +local function validateInstanceVBOTable(iT, calledfrom) + -- check that instanceIDtoIndex and indextoInstanceID are valid and contigous: + for i=1, iT.usedElements do + if iT.indextoInstanceID[i] == nil then + Spring.Echo("There is a hole in indextoInstanceID", iT.myName, "at", i,"out of",iT.usedElements, calledfrom) + --Spring.Echo() + if iT.indextoUnitID[i] == nil then + Spring.Echo("It is also missing from indextoUnitID") + else + Spring.Echo("But it does exist in indextoUnitID with an unitID of ", iT.indextoUnitID[i]) + Spring.Echo("This is valid?", Spring.GetUnitPosition(iT.indextoUnitID[i])) + end + + else + local instanceID = iT.indextoInstanceID[i] + if iT.instanceIDtoIndex[instanceID] == nil then + Spring.Echo("There is a hole instanceIDtoIndex", iT.myName, "at", i," iT.instanceIDtoIndex[instanceID] == nil ") + elseif iT.instanceIDtoIndex[instanceID] ~= i then + Spring.Echo("There is a problem in indextoInstanceID", iT.myName, "at i =", i," iT.indextoInstanceID[instanceID] ~= i, it is instead: ", iT.indextoInstanceID[instanceID] ) + end + end + end + local indextoInstanceIDsize = counttable(iT.indextoInstanceID) + local instanceIDtoIndexsize = counttable(iT.instanceIDtoIndex) + local indextoUnitID = counttable(iT.indextoUnitID) + if (indextoInstanceIDsize ~= instanceIDtoIndexsize) or (instanceIDtoIndexsize ~= indextoUnitID) then + Spring.Echo("Table size mismatch during validation of", iT.myName, indextoInstanceIDsize, instanceIDtoIndexsize, indextoUnitID) + end + +end + +function locateInvalidUnits(iT) + if iT.validinfo == nil then iT.validinfo = {} end + local invalidcount = 0 + for i, unitID in ipairs(iT.indextoUnitID) do + if iT.featureIDs then + if Spring.ValidFeatureID(unitID) then + local px, py, pz = Spring.GetFeaturePosition(unitID) + local fdefname = FeatureDefs[Spring.GetFeatureDefID(unitID)].name + iT.validinfo[unitID] = {px = px, py = py, pz = pz, fdefname = fdefname} + else + Spring.SendCommands({"pause 1"}) + Spring.Echo("INVALID feature, last seen at", unitID) + local vi = iT.validinfo[unitID] + local markertext = tostring(unitID) .. "," .. dbgt(vi) + Spring.MarkerAddPoint(vi.px, vi.py, vi.pz, markertext ) + invalidcount = invalidcount + 1 + end + else + if Spring.ValidUnitID(unitID) then + local px, py, pz = Spring.GetUnitPosition(unitID) + local unitDefID = Spring.GetUnitDefID(unitID) + local unitdefname = (unitDefID and UnitDefs[unitDefID].name) or "unknown:nil" + iT.validinfo[unitID] = {px = px, py = py, pz = pz, unitdefname = unitdefname} + else + Spring.SendCommands({"pause 1"}) + Spring.Echo(iT.myName, " INVALID unitID",unitID,"#elements", iT.usedElements, "last seen at tablepos:", i) + + local vi = iT.validinfo[unitID] + local markertext = tostring(unitID) .. "," .. dbgt(vi) + Spring.MarkerAddPoint(vi.px, vi.py, vi.pz, markertext ) + invalidcount = invalidcount + 1 + end + end + end + return invalidcount +end + +------------------------------END DEBUG HELPERS --------------------------- + +local function resizeInstanceVBOTable(iT) + -- iT: the InstanceVBOTable to double in size 'dynamically' resize the VBO, to double its size + -- this is called automatically when the existing instanceVBO gets full + -- Also performs a busload of sanity checking + -- Spring.Echo("instanceVBOTable full, resizing to double size",iT.myName, iT.usedElements,iT.maxElements) + iT.maxElements = iT.maxElements * 2 + local newInstanceVBO = gl.GetVBO(GL.ARRAY_BUFFER,true) + newInstanceVBO:Define(iT.maxElements, iT.layout) + + if iT.instanceVBO then iT.instanceVBO:Delete() end -- release if previous one existed + iT.instanceVBO = newInstanceVBO + -- ok this needs some sanitation right here, with reporting. + if iT.indextoUnitID then + -- we need to walk through both tables at the same time, and virtually pop all invalid unit/featureIDs on a resize, or else face dire consequences (crashes) later on + -- the tables we need to keep updated are: + local new_instanceData = {} + local new_instanceData_count = 0 + local new_usedElements = 0 + local new_instanceIDtoIndex = {} + local new_indextoInstanceID = {} + local new_indextoUnitID = {} + local invalidcount = 0 + local iTStep = iT.instanceStep + + for i, objectID in ipairs(iT.indextoUnitID) do + local isValidID = false + if iT.featureIDs then isValidID = Spring.ValidFeatureID(objectID) + else isValidID = Spring.ValidUnitID(objectID) end + if isValidID then + local offset = new_usedElements * iTStep + for j = 1, iTStep do + new_instanceData_count = new_instanceData_count + 1 + new_instanceData[new_instanceData_count] = iT.instanceData[j + offset] + end + new_usedElements = new_usedElements + 1 + local currentInstanceID = iT.indextoInstanceID[i] + new_indextoInstanceID[new_usedElements] = iT.indextoInstanceID[i] + new_indextoUnitID[new_usedElements] = iT.indextoUnitID[i] + new_instanceIDtoIndex[currentInstanceID] = new_usedElements + --Spring.Echo("Resize:",currentInstanceID, iT.indextoUnitID[i] ) + invalidcount = invalidcount + 1 + else + Spring.Echo("Warning: Found invalid unit/featureID",objectID,"at",i,"while resizing",iT.myName) + end + end + + if invalidcount == 0 then + comparetables( iT.instanceData, new_instanceData, "instanceData") + comparetables( iT.instanceIDtoIndex, new_instanceIDtoIndex, "instanceIDtoIndex") + comparetables( iT.indextoInstanceID, new_indextoInstanceID, "indextoInstanceID") + comparetables( iT.indextoUnitID, new_indextoUnitID, "indextoUnitID") + end + + iT.instanceData = new_instanceData + iT.usedElements = new_usedElements + iT.instanceIDtoIndex = new_instanceIDtoIndex + iT.indextoInstanceID = new_indextoInstanceID + iT.indextoUnitID = new_indextoUnitID + end + + iT.instanceVBO:Upload(iT.instanceData,nil,0,1,iT.usedElements * iT.instanceStep) + + if gldebugannotations then + gl.ObjectLabel(GL_BUFFER, iT.instanceVBO:GetID(), iT.myName) + end + + if iT.VAO then -- reattach new if updated :D + iT.VAO:Delete() + iT.VAO = makeVAOandAttach(iT.vertexVBO,iT.instanceVBO, iT.indexVBO) + end + + if iT.indextoUnitID then + if iT.featureIDs then + iT.instanceVBO:InstanceDataFromFeatureIDs(iT.indextoUnitID, iT.unitIDattribID) + else + iT.instanceVBO:InstanceDataFromUnitIDs(iT.indextoUnitID, iT.unitIDattribID) + end + end + return iT.maxElements +end + +--[[ from Ivand: +instVBO:Upload({ + 100, 0, 0, + -100, 0, 0, + 0, 0, 100, + 0, 0, -100, + }, 7, 1, 4, 6) +Here is how you upload starting from 1st element and starting from 4th element in Lua array (-100) and finishing with 6th element (0), essentially it will upload (-100, 0, 0) into 7th attribute of 2nd instance. +]]-- + +local function pushElementInstance(iT,thisInstance, instanceID, updateExisting, noUpload, unitID) + -- iT: instanceTable created with makeInstanceTable + -- thisInstance: is a lua array of values to add to table, MUST BE INSTANCESTEP SIZED LUA ARRAY + -- instanceID: an optional key given to the item, so it can be easily removed/updated by reference, defaults to the index of the instance in the buffer (1 based) + -- updateExisting: allow updating an existing element (same instanceID key) + -- noUpload: prevent the VBO from being uploaded, if you feel like you are going to do a lot of ops and wish to manually upload when done instead + -- unitID: if given, it will store then unitID corresponding to this instance, and will try to update the InstanceDataFromUnitIDs for this unit + -- returns: the index of the instanceID in the table on success, else nil + if #thisInstance ~= iT.instanceStep then + Spring.Echo("Trying to upload an oddly sized instance into",iT.myName, #thisInstance, "instead of ",iT.instanceStep) + Spring.Debug.TraceFullEcho(20,20,20, "pushElementInstance Failure:"..iT.myName ) + end + local iTusedElements = iT.usedElements + local iTStep = iT.instanceStep + local endOffset = iTusedElements * iTStep + if instanceID == nil then instanceID = nextInstanceID(iT) end + local thisInstanceIndex = iT.instanceIDtoIndex[instanceID] + + if (iTusedElements + 1 ) >= iT.maxElements then -- add 1 extra for safety (not the best idea, but we seem to be running over it by 1) + resizeInstanceVBOTable(iT) + iTusedElements = iT.usedElements -- because during validation of unitIDs during resizing, we can decrease the actual size of the table! + thisInstanceIndex = iT.instanceIDtoIndex[instanceID] -- this too, can change, TODO, also do this in VBOIDtable! + end + + if thisInstanceIndex == nil then -- new, register it + thisInstanceIndex = iTusedElements + 1 + iT.usedElements = iTusedElements + 1 + iT.instanceIDtoIndex[instanceID] = thisInstanceIndex + iT.indextoInstanceID[thisInstanceIndex] = instanceID + else -- pre-existing ID, update or bail + if updateExisting == nil then + Spring.Echo("Tried to add existing element to an instanceTable",iT.myName, instanceID) + return nil + else + endOffset = (thisInstanceIndex - 1) * iTStep + end + end + local instanceData = iT.instanceData + for i =1, iTStep do -- copy data, but fast + instanceData[endOffset + i] = thisInstance[i] + end + + if unitID ~= nil then + local isvalidid + if iT.featureIDs then isvalidid = Spring.ValidFeatureID(unitID) + else isvalidid = Spring.ValidUnitID(unitID) end + if isvalidid == false then + Spring.Echo("Error: Attempted to push an invalid unit/featureID",unitID, "into", iT.myName) + noUpload = true + Spring.Debug.TraceFullEcho(20,20,20,"invalid unit/featureID in " ..iT.myName) + end + iT.indextoUnitID[thisInstanceIndex] = unitID + end + + if noUpload ~= true then --upload or mark as dirty + iT.instanceVBO:Upload(thisInstance, nil, thisInstanceIndex - 1) + --Spring.Echo("pushElementInstance,unitID, iT.unitIDattribID, thisInstanceIndex",unitID, iT.unitIDattribID, thisInstanceIndex) + if unitID ~= nil then + if iT.featureIDs then + iT.instanceVBO:InstanceDataFromFeatureIDs(unitID, iT.unitIDattribID, thisInstanceIndex-1) + else + iT.instanceVBO:InstanceDataFromUnitIDs(unitID, iT.unitIDattribID, thisInstanceIndex-1) + end + end + else + iT.dirty = true + end + + if iT.debug then validateInstanceVBOTable(iT, 'push') end + return instanceID +end + +local function popElementInstance(iT, instanceID, noUpload) + -- iT: instanceTable created with makeInstanceTable + -- instanceID: an optional key given to the item, so it can be easily removed by reference, defaults to the last element of the buffer, but this will screw up the instanceIDtoIndex table if used in mixed keys mode + -- noUpload: prevent the VBO from being uploaded, if you feel like you are going to do a lot of ops and wish to manually upload when done instead + -- returns nil on failure, the the index of the element on success + if instanceID == nil then + Spring.Echo("Tried to remove element with nil instanceID from instanceTable " .. iT.myName) + return nil + end + + if iT.instanceIDtoIndex[instanceID] == nil then -- if key is instanceID yet does not exist, then warn and bail + Spring.Echo("Tried to remove element ",instanceID,'From instanceTable', iT.myName, 'but it does not exist in it') + Spring.Debug.TraceFullEcho(10,10,3, iT.myName) + return nil + end + if iT.usedElements == 0 then -- Dont remove the last element + Spring.Echo("Tried to remove element ",instanceID,'From instanceTable', iT.myName, 'but it should be empty') + return nil + end + + --Fetch the position of the element we want to remove from the 'middle' of the table + local oldElementIndex = iT.instanceIDtoIndex[instanceID] + iT.instanceIDtoIndex[instanceID] = nil -- clean these out + iT.indextoInstanceID[oldElementIndex] = nil + + -- get the index of the last element + local lastElementIndex = iT.usedElements + + -- if this one was already at the end of the queue, do nothing but decrement usedElements and clear mappings + if oldElementIndex == lastElementIndex then + --Spring.Echo("Removed end element of instanceTable", iT.myName) + iT.usedElements = iT.usedElements - 1 + -- if it had a related unitID stored, remove that: + if iT.indextoUnitID then iT.indextoUnitID[oldElementIndex] = nil end + + if iT.debugZombies then + if iT.zombies and iT.zombies[instanceID] then + --Spring.Echo("Good, we are killing a stupid zombie at the end", instanceID, iT.numZombies) + iT.zombies[instanceID] = nil + iT.numZombies = iT.numZombies - 1 + end + end + + else + local lastElementInstanceID = iT.indextoInstanceID[lastElementIndex] + if lastElementInstanceID == nil then -- + Spring.Echo("We somehow have a nil element at the back of the array, which is completely invalid, probably about to crash", iT.myName) + dbgt(iT.instanceIDtoIndex, "instanceIDtoIndex") + dbgt(iT.indextoInstanceID, "indextoInstanceID") + dbgt(iT.indextoUnitID, "indextoUnitID") + end + local iTStep = iT.instanceStep + local endOffset = (iT.usedElements - 1)*iTStep + + iT.instanceIDtoIndex[lastElementInstanceID] = oldElementIndex -- lastElementInstanceID was somehow nil here? + iT.indextoInstanceID[oldElementIndex] = lastElementInstanceID + iT.indextoInstanceID[lastElementIndex] = nil --- somehow this got forgotten? TODO for VBOIDtable + + local oldOffset = (oldElementIndex-1)*iTStep + local instanceData = iT.instanceData + for i = 1, iTStep do + instanceData[oldOffset + i ] = instanceData[endOffset + i] + end + --size_t LuaVBOImpl::Upload(const sol::stack_table& luaTblData, const sol::optional attribIdxOpt, const sol::optional elemOffsetOpt, const sol::optional luaStartIndexOpt, const sol::optional luaFinishIndexOpt) + --Spring.Echo("Removing instanceID",instanceID,"from iT at position", oldElementIndex, "shuffling back at", iT.usedElements,"endoffset=",endOffset,'oldOffset=',oldOffset) + if noUpload ~= true then + --Spring.Echo("Upload", oldElementIndex -1, oldOffset+1, oldOffset+iTStep) + iT.instanceVBO:Upload(iT.instanceData,nil,oldElementIndex-1,oldOffset +1,oldOffset + iTStep) + else + iT.dirty = true + end + -- Do the unitID shuffle if needed: + if iT.indextoUnitID then + --Spring.Echo("popElementInstance,unitID, iT.unitIDattribID, thisInstanceIndex",unitID, iT.unitIDattribID, oldElementIndex) + local popunitID = iT.indextoUnitID[lastElementIndex] + if popunitID == nil then + Spring.Echo("TODO: what the f is happening here?, how the f could we have popped a nil from the back of?", iT.myName) -- TODO TODO + end + + if iT.debugZombies then + local gf = Spring.GetGameFrame() + --Spring.Echo("Popping", instanceID) + if iT.lastpopgameframe == nil then + iT.lastpopgameframe = gf + iT.zombies = {} + iT.numZombies = 0 + else + if iT.lastpopgameframe ~= gf then -- New gameframe + iT.lastpopgameframe = gf + if iT.numZombies and iT.numZombies > 0 then -- WE HAVE ZOMBIES AAAAARGH + local s = "Warning: We have " .. tostring(iT.numZombies) .. " zombie units left over in " .. iT.myName + for zombie, gf in pairs(iT.zombies) do + s = s .. " " .. tostring(zombie) ..'/'..tostring(gf) + Spring.Echo("ZOMBIE instanceID", zombie, 'gf',gf) + --Spring.SendCommands({"pause 1"}) + Spring.Debug.TraceFullEcho(nil,nil,nil, iT.myName) + end + Spring.Echo(s) + iT.zombies = {} + iT.numZombies = 0 + end + else -- same gameframe + if iT.zombies[instanceID] then + --Spring.Echo("Good, we are killing a stupid zombie", gf, instanceID, iT.numZombies) + iT.zombies[instanceID] = nil + iT.numZombies = iT.numZombies - 1 + end + end + end + end + + iT.indextoUnitID[oldElementIndex] = popunitID + iT.indextoUnitID[lastElementIndex] = nil + + if (iT.featureIDs and Spring.ValidFeatureID(popunitID)) or Spring.ValidUnitID(popunitID) then + if noUpload ~= true then + if iT.featureIDs then + iT.instanceVBO:InstanceDataFromFeatureIDs(popunitID, iT.unitIDattribID, oldElementIndex-1) + else + iT.instanceVBO:InstanceDataFromUnitIDs(popunitID, iT.unitIDattribID, oldElementIndex-1) + end + end + else + if iT.debugZombies then + --Spring.Echo("Warning: Tried to pop back an invalid" .. ((iT.featureIDs and "featureID") or "unitID"), popunitID, "from", iT.myName, "while removing instance", instanceID, counttable(iT.instanceIDtoIndex), counttable(iT.indextoInstanceID), counttable(iT.indextoUnitID)) + --Spring.Debug.TraceFullEcho() + local gf = Spring.GetGameFrame() + if iT.lastpopgameframe == nil or iT.lastpopgameframe ~= gf then -- New gameframe + iT.lastpopgameframe = gf + iT.zombies = {} + iT.numZombies = 0 + end + if iT.zombies[lastElementInstanceID] == nil then + iT.zombies[lastElementInstanceID] = gf + iT.numZombies = iT.numZombies + 1 + end + end + end + end + iT.usedElements = iT.usedElements - 1 + end + + if iT.debug then validateInstanceVBOTable(iT,'pop') end + return oldElementIndex +end + +local function getElementInstanceData(iT, instanceID, cacheTable) + -- iT: instanceTable created with makeInstanceTable + -- instanceID: an optional key given to the item, so it can be easily removed by reference, defaults to the index of the instance in the buffer (1 based) + local instanceIndex = iT.instanceIDtoIndex[instanceID] + if instanceIndex == nil then + Spring.Echo("Tried to getElementInstanceData from",iT.myName,instanceID, "but it does not exist") + return nil + end + local iData = cacheTable or {} + local iTStep = iT.instanceStep + instanceIndex = (instanceIndex-1) * iTStep + local instanceData = iT.instanceData + for i = 1, iTStep do + iData[i] = instanceData[instanceIndex + i] + end + return iData +end + +local function uploadAllElements(iT) + -- upload all USED elements + if iT.usedElements == 0 then return end + + iT.instanceVBO:Upload(iT.instanceData,nil,0, 1, iT.usedElements * iT.instanceStep) + iT.dirty = false + if iT.indextoUnitID then + if iT.featureIDs then + iT.instanceVBO:InstanceDataFromFeatureIDs(iT.indextoUnitID, iT.unitIDattribID) + else + iT.instanceVBO:InstanceDataFromUnitIDs(iT.indextoUnitID, iT.unitIDattribID) + end + end +end + +local function uploadElementRange(iT, startElementIndex, endElementIndex) + iT.instanceVBO:Upload(iT.instanceData, -- The lua mirrored VBO data + nil, -- the attribute index, nil for all attributes + startElementIndex, -- vboOffset optional, , what ELEMENT offset of the VBO to start uploading into, 0 based + startElementIndex * iT.instanceStep + 1, -- luaStartIndex, default 1, what element of the lua array to start uploading from. 1 is the 1st element of a lua table. + endElementIndex * iT.instanceStep --] luaEndIndex, default #{array}, what element of the lua array to upload up to, inclusively + ) + if iT.indextoUnitID then + --we need to reslice the table + local unitIDRange = {} + local indextoUnitID = iT.indextoUnitID + for i = startElementIndex, endElementIndex do + unitIDRange[#unitIDRange + 1] = indextoUnitID[i] + end + if iT.featureIDs then + iT.instanceVBO:InstanceDataFromFeatureIDs(unitIDRange, iT.unitIDattribID, startElementIndex - 1) + else + iT.instanceVBO:InstanceDataFromUnitIDs(unitIDRange, iT.unitIDattribID, startElementIndex - 1) + end + end +end + +-- This function allows for order-preserving compacting of a list of instances based on these funcs. +-- It is designed for Decals GL4, where draw order matters a lot! +-- remove takes priority over keep +local function compactInstanceVBO(iT, removelist, keeplist) + local usedElements = iT.usedElements + if usedElements == 0 then return 0 end + local instanceStep = iT.instanceStep + local instanceData = iT.instanceData + local indextoInstanceID = iT.indextoInstanceID + local newindextoInstanceID = {} + local newinstanceIDtoIndex = {} + local newUsedElements = 0 + local numremoved = 0 + local removemode = (removelist ~= nil) and (keeplist == nil) + for index, instanceID in ipairs(indextoInstanceID) do + -- If its in keeplist, + if (removemode and (removelist[instanceID]== nil) ) or ((removemode == false) and keeplist[instanceID]) then + local instanceOffset = (index-1) * instanceStep + local newInstanceOffset = newUsedElements * instanceStep + for i = 1, instanceStep do + instanceData[newInstanceOffset + i] = instanceData[instanceOffset + i] + end + newUsedElements = newUsedElements + 1 + newindextoInstanceID[newUsedElements] = instanceID + newinstanceIDtoIndex[instanceID] = newUsedElements + else + numremoved = numremoved + 1 + end + end + if numremoved > 0 then + iT.dirty = true -- we set the flag to notify that CPU and GPU contents dont match! + iT.usedElements = newUsedElements + iT.instanceIDtoIndex = newinstanceIDtoIndex + iT.indextoInstanceID = newindextoInstanceID + end + return numremoved +end + +local function drawInstanceVBO(iT) + if iT.usedElements > 0 then + if iT.indexVBO then + iT.VAO:DrawElements(iT.primitiveType, iT.numVertices, 0, iT.usedElements,0) + else + iT.VAO:DrawArrays(iT.primitiveType, iT.numVertices, 0, iT.usedElements,0) + end + end +end + +local function countInvalidUnitIDs(iT) + local invalids = {} + for i, objectID in ipairs(iT.indextoUnitID) do + local isValidID = false + if iT.featureIDs then isValidID = Spring.ValidFeatureID(objectID) + else isValidID = Spring.ValidUnitID(objectID) end + if isValidID then + + else + invalids[#invalids + 1] = objectID + end + end + if #invalids > 0 then + Spring.Echo(#invalids, "invalid IDs found in ", iT.myName) + end + return invalids +end + + +--------- HELPERS FOR PRIMITIVES ------------------ + +local function makeCircleVBO(circleSegments, radius, startCenter, name) + -- Makes circle of radius in xy space + -- can be used in both GL.LINES and GL.TRIANGLE_FAN mode + -- Startcenter places a vertex in the center, this is nice for triangle fans, + -- but when drawing lines with this vbo, start at an offset of 1 + -- Fun note: its NOT faster to draw stenciled circles with this. + if not radius then radius = 1 end + circleSegments = circleSegments -1 -- for po2 buffers + local circleVBO = gl.GetVBO(GL.ARRAY_BUFFER,true) + if circleVBO == nil then return nil end + + local VBOLayout = { + {id = 0, name = "position", size = 4}, + } + + local VBOData = {} + if startCenter then + VBOData[#VBOData+1] = 0 -- X + VBOData[#VBOData+1] = 0 -- Y + VBOData[#VBOData+1] = 0 -- circumference [0-1] + VBOData[#VBOData+1] = radius + end + + for i = 0, circleSegments do -- this is +1 + VBOData[#VBOData+1] = math.sin(math.pi*2* i / circleSegments) * radius -- X + VBOData[#VBOData+1] = math.cos(math.pi*2* i / circleSegments) * radius-- Y + VBOData[#VBOData+1] = i / circleSegments -- circumference [0-1] + VBOData[#VBOData+1] = radius + end + + circleVBO:Define( + circleSegments + 1 + (startCenter and 1 or 0) , -- +1 for center point if startCenter is true + VBOLayout + ) + circleVBO:Upload(VBOData) + if gldebugannotations then + gl.ObjectLabel(GL_BUFFER, circleVBO:GetID(), name or "CircleVBO") + end + return circleVBO, #VBOData/4 +end + +local function makePlaneVBO(xsize, ysize, xresolution, yresolution, name) -- makes a plane from [-xsize to xsize] with xresolution subdivisions + if not xsize then xsize = 1 end + if not ysize then ysize = xsize end + if not xresolution then xresolution = 1 end + if not yresolution then yresolution = xresolution end + xresolution = math.floor(xresolution) + yresolution = math.floor(yresolution) + local planeVBO = gl.GetVBO(GL.ARRAY_BUFFER,false) + if planeVBO == nil then return nil end + + local VBOLayout = { + {id = 0, name = "xyworld_xyfract", size = 2}, + } + + local VBOData = {} + + for x = 0, xresolution do -- this is +1 + for y = 0, yresolution do + VBOData[#VBOData+1] = xsize * ((x / xresolution) -0.5 ) *2 + VBOData[#VBOData+1] = ysize * ((y / yresolution) -0.5 ) * 2 + end + end + + planeVBO:Define( + (xresolution + 1) * (yresolution + 1) , + VBOLayout + ) + planeVBO:Upload(VBOData) + + if gldebugannotations then + gl.ObjectLabel(GL_BUFFER, planeVBO:GetID(), name or "PlaneVBO") + end + + --Spring.Echo("PlaneVBOData up:",#VBOData, "Down", #planeVBO:Download()) + return planeVBO, #VBOData/2 +end + +local function makePlaneIndexVBO(xresolution, yresolution, cutcircle, name) + xresolution = math.floor(xresolution) + if not yresolution then yresolution = xresolution end + local planeIndexVBO = gl.GetVBO(GL.ELEMENT_ARRAY_BUFFER,false) + if planeIndexVBO == nil then return nil end + + local function xyinrad(lx, ly) + local px = (lx / xresolution) * 2 - 1 + local py = (ly / yresolution) * 2 - 1 + return (px*px + py*py) <= 1 + end + + local IndexVBOData = {} + local qindex = 0 + local colsize = yresolution + 1 + for x = 0, xresolution-1 do -- this is +1 + for y = 0, yresolution-1 do + --this is only 20% optimization + if cutcircle == nil or (xyinrad(x,y) or xyinrad(x + 1,y) or xyinrad(x,y + 1 )) then + -- top left one + IndexVBOData[#IndexVBOData + 1] = qindex + IndexVBOData[#IndexVBOData + 1] = qindex +1 + IndexVBOData[#IndexVBOData + 1] = qindex + colsize + end + + if cutcircle == nil or (xyinrad(x+1,y+1) or xyinrad(x + 1,y) or xyinrad(x,y + 1 )) then + -- bottom right one? + IndexVBOData[#IndexVBOData + 1] = qindex +1 + IndexVBOData[#IndexVBOData + 1] = qindex + colsize + 1 + IndexVBOData[#IndexVBOData + 1] = qindex + colsize + end + qindex = qindex + 1 + + end + qindex = qindex + 1 + end + planeIndexVBO:Define( + # IndexVBOData + ) + planeIndexVBO:Upload(IndexVBOData) + + if gldebugannotations then + gl.ObjectLabel(GL_BUFFER, planeIndexVBO:GetID(), name or "planeIndexVBO") + end + --Spring.Echo("PlaneIndexVBO up:",#IndexVBOData, "Down", #planeIndexVBO:Download()) + return planeIndexVBO, IndexVBOData +end + +local function makePointVBO(numPoints, randomFactor, name) + -- makes points with xyzw + -- can be used in both GL.LINES and GL.TRIANGLE_FAN mode + numPoints = numPoints or 1 + randomFactor = randomFactor or 0 + local pointVBO = gl.GetVBO(GL.ARRAY_BUFFER,true) + if pointVBO == nil then return nil end + + local VBOLayout = { + {id = 0, name = "position_w", size = 4}, + } + + local VBOData = {} + + for i = 1, numPoints do -- + VBOData[#VBOData+1] = randomFactor * math.random()-- X + VBOData[#VBOData+1] = randomFactor * math.random()-- Y + VBOData[#VBOData+1] = randomFactor * math.random()---Z + VBOData[#VBOData+1] = i/numPoints -- index for lolz? + end + + pointVBO:Define( + numPoints, + VBOLayout + ) + pointVBO:Upload(VBOData) + + if gldebugannotations then + gl.ObjectLabel(GL_BUFFER, pointVBO:GetID(), name or "pointVBO") + end + return pointVBO, numPoints +end + +local function makeRectVBO(minX,minY, maxX, maxY, minU, minV, maxU, maxV, name) + if minX == nil then + minX, minY, maxX, maxY, minU, minV, maxU, maxV = 0,0,1,1,0,0,1,1 + end + -- makes points with xyzw + -- can be used in both GL.LINES and GL.TRIANGLE_FAN mode + local rectVBO = gl.GetVBO(GL.ARRAY_BUFFER,false) + if rectVBO == nil then return nil end + + local VBOLayout = { + {id = 0, name = "position_xy_uv", size = 4}, + } + + local VBOData = { + --bl + minX,minY, minU, minV, --bl + minX,maxY, minU, maxV, --tr + maxX,maxY, maxU, maxV, --tr + maxX,maxY, maxU, maxV, --tr + maxX,minY, maxU, minV, --br + minX,minY, minU, minV, --bl + } + + rectVBO:Define( + 6, + VBOLayout + ) + rectVBO:Upload(VBOData) + + if gldebugannotations then + gl.ObjectLabel(GL_BUFFER, rectVBO:GetID(), name or "rectVBO") + end + return rectVBO, 6 +end + +local function makeRectIndexVBO(name) + local rectIndexVBO = gl.GetVBO(GL.ELEMENT_ARRAY_BUFFER,false) + if rectIndexVBO == nil then return nil end + + rectIndexVBO:Define( + 6 + ) + rectIndexVBO:Upload({0,1,2,3,4,5}) + if gldebugannotations then + gl.ObjectLabel(GL_BUFFER, rectIndexVBO:GetID(), name or "rectIndexVBO") + end + return rectIndexVBO,6 +end + + + +local function makeConeVBO(numSegments, height, radius, name) + -- make a cone that points up, (y = height), with radius specified + -- returns the VBO object, and the number of elements in it (usually == numvertices) + -- needs GL.TRIANGLES + if not height then height = 1 end + if not radius then radius = 1 end + local coneVBO = gl.GetVBO(GL.ARRAY_BUFFER,true) + if coneVBO == nil then return nil end + + local VBOData = {} + + for i = 1, numSegments do + -- center vertex + VBOData[#VBOData+1] = 0 + VBOData[#VBOData+1] = 0 + VBOData[#VBOData+1] = 0 + VBOData[#VBOData+1] = (i - 1) / numSegments + + --- first cone flat + VBOData[#VBOData+1] = math.sin(math.pi*2* (i - 1) / numSegments) * radius -- X + VBOData[#VBOData+1] = 0 + VBOData[#VBOData+1] = -1* math.cos(math.pi*2* (i - 1) / numSegments) * radius-- Y + VBOData[#VBOData+1] = (i - 1) / numSegments + + --- second cone flat + VBOData[#VBOData+1] = math.sin(math.pi*2* (i - 0) / numSegments) * radius-- X + VBOData[#VBOData+1] = 0 + VBOData[#VBOData+1] = -1* math.cos(math.pi*2* (i - 0) / numSegments) * radius -- Y + VBOData[#VBOData+1] =(i - 0) / numSegments + + -- top vertex + VBOData[#VBOData+1] = 0 + VBOData[#VBOData+1] = height + VBOData[#VBOData+1] = 0 + VBOData[#VBOData+1] = (i - 1) / numSegments + + --- first cone flat + VBOData[#VBOData+1] = math.sin(math.pi*2* (i - 0) / numSegments) * radius -- X + VBOData[#VBOData+1] = 0 + VBOData[#VBOData+1] = -1*math.cos(math.pi*2* (i - 0) / numSegments) * radius -- Y + VBOData[#VBOData+1] =(i - 0) / numSegments + + --- second cone flat + VBOData[#VBOData+1] = math.sin(math.pi*2* (i - 1) / numSegments) * radius -- X + VBOData[#VBOData+1] = 0 + VBOData[#VBOData+1] = -1*math.cos(math.pi*2* (i - 1) / numSegments) * radius -- Y + VBOData[#VBOData+1] =(i - 1) / numSegments + end + + + coneVBO:Define(#VBOData/4, {{id = 0, name = "localpos_progress", size = 4}}) + coneVBO:Upload(VBOData) + + if gldebugannotations then + gl.ObjectLabel(GL_BUFFER, coneVBO:GetID(), name or "coneVBO") + end + + return coneVBO, #VBOData/4 +end + + + +local function makeCylinderVBO(numSegments, height, radius, hastop, hasbottom, name) + -- make a cylinder that points up, (y = height), with radius specified + -- returns the VBO object, and the number of elements in it (usually == numvertices) + -- needs GL.TRIANGLES + if not height then height = 1 end + if not radius then radius = 1 end + local cylinderVBO = gl.GetVBO(GL.ARRAY_BUFFER,true) + if cylinderVBO == nil then return nil end + + local VBOData = {} + + for i = 1, numSegments do + if hasbottom then + -- center vertex + VBOData[#VBOData+1] = 0 + VBOData[#VBOData+1] = -1* height + VBOData[#VBOData+1] = 0 + VBOData[#VBOData+1] = (i - 1) / numSegments + + --- first cone flat + VBOData[#VBOData+1] = math.sin(math.pi*2* (i - 1) / numSegments) * radius -- X + VBOData[#VBOData+1] = -1* height + VBOData[#VBOData+1] = -1* math.cos(math.pi*2* (i - 1) / numSegments) * radius-- Y + VBOData[#VBOData+1] = (i - 1) / numSegments + + --- second cone flat + VBOData[#VBOData+1] = math.sin(math.pi*2* (i - 0) / numSegments) * radius-- X + VBOData[#VBOData+1] = -1* height + VBOData[#VBOData+1] = -1* math.cos(math.pi*2* (i - 0) / numSegments) * radius -- Y + VBOData[#VBOData+1] =(i - 0) / numSegments + end + + + --- first cone flat + VBOData[#VBOData+1] = math.sin(math.pi*2* (i - 0) / numSegments) * radius -- X + VBOData[#VBOData+1] = height + VBOData[#VBOData+1] = -1*math.cos(math.pi*2* (i - 0) / numSegments) * radius -- Y + VBOData[#VBOData+1] =(i - 0) / numSegments + + --- second cone flat + VBOData[#VBOData+1] = math.sin(math.pi*2* (i - 1) / numSegments) * radius -- X + VBOData[#VBOData+1] = height + VBOData[#VBOData+1] = -1*math.cos(math.pi*2* (i - 1) / numSegments) * radius -- Y + VBOData[#VBOData+1] =(i - 1) / numSegments + + + + --- first cone flat + VBOData[#VBOData+1] = math.sin(math.pi*2* (i - 0) / numSegments) * radius -- X + VBOData[#VBOData+1] = -1 * height + VBOData[#VBOData+1] = -1*math.cos(math.pi*2* (i - 0) / numSegments) * radius -- Y + VBOData[#VBOData+1] =(i - 0) / numSegments + + --- second cone flat + VBOData[#VBOData+1] = math.sin(math.pi*2* (i - 1) / numSegments) * radius -- X + VBOData[#VBOData+1] = height + VBOData[#VBOData+1] = -1*math.cos(math.pi*2* (i - 1) / numSegments) * radius -- Y + VBOData[#VBOData+1] =(i - 1) / numSegments + + + --- first cone flat + VBOData[#VBOData+1] = math.sin(math.pi*2* (i - 0) / numSegments) * radius -- X + VBOData[#VBOData+1] = -1 * height + VBOData[#VBOData+1] = -1*math.cos(math.pi*2* (i - 0) / numSegments) * radius -- Y + VBOData[#VBOData+1] =(i - 0) / numSegments + + + --- second cone flat + VBOData[#VBOData+1] = math.sin(math.pi*2* (i - 1) / numSegments) * radius -- X + VBOData[#VBOData+1] = -1 * height + VBOData[#VBOData+1] = -1*math.cos(math.pi*2* (i - 1) / numSegments) * radius -- Y + VBOData[#VBOData+1] =(i - 1) / numSegments + + + + if hastop then + -- center vertex + VBOData[#VBOData+1] = 0 + VBOData[#VBOData+1] = height + VBOData[#VBOData+1] = 0 + VBOData[#VBOData+1] = (i - 1) / numSegments + + --- first cone flat + VBOData[#VBOData+1] = math.sin(math.pi*2* (i - 1) / numSegments) * radius -- X + VBOData[#VBOData+1] = height + VBOData[#VBOData+1] = -1* math.cos(math.pi*2* (i - 1) / numSegments) * radius-- Y + VBOData[#VBOData+1] = (i - 1) / numSegments + + --- second cone flat + VBOData[#VBOData+1] = math.sin(math.pi*2* (i - 0) / numSegments) * radius-- X + VBOData[#VBOData+1] = height + VBOData[#VBOData+1] = -1* math.cos(math.pi*2* (i - 0) / numSegments) * radius -- Y + VBOData[#VBOData+1] =(i - 0) / numSegments + end + end + + + cylinderVBO:Define(#VBOData/4, {{id = 0, name = "localpos_progress", size = 4}}) + cylinderVBO:Upload(VBOData) + + if gldebugannotations then + gl.ObjectLabel(GL_BUFFER, cylinderVBO:GetID(), name or "cylinderVBO") + end + + return cylinderVBO, #VBOData/4 +end + + + +local function makeBoxVBO(minX, minY, minZ, maxX, maxY, maxZ, name) -- make a box + -- needs GL.TRIANGLES + local boxVBO = gl.GetVBO(GL.ARRAY_BUFFER,true) + if boxVBO == nil then return nil end + + local VBOData = { + minX,minY,minZ,0 + ,minX,minY,maxZ,0 + ,minX,maxY,maxZ,0 + ,maxX,maxY,minZ,0 + ,minX,minY,minZ,0 + ,minX,maxY,minZ,0 + ,maxX,minY,maxZ,0 + ,minX,minY,minZ,0 + ,maxX,minY,minZ,0 + ,maxX,maxY,minZ,0 + ,maxX,minY,minZ,0 + ,minX,minY,minZ,0 + ,minX,minY,minZ,0 + ,minX,maxY,maxZ,0 + ,minX,maxY,minZ,0 + ,maxX,minY,maxZ,0 + ,minX,minY,maxZ,0 + ,minX,minY,minZ,0 + ,minX,maxY,maxZ,0 + ,minX,minY,maxZ,0 + ,maxX,minY,maxZ,0 + ,maxX,maxY,maxZ,0 + ,maxX,minY,minZ,0 + ,maxX,maxY,minZ,0 + ,maxX,minY,minZ,0 + ,maxX,maxY,maxZ,0 + ,maxX,minY,maxZ,0 + ,maxX,maxY,maxZ,0 + ,maxX,maxY,minZ,0 + ,minX,maxY,minZ,0 + ,maxX,maxY,maxZ,0 + ,minX,maxY,minZ,0 + ,minX,maxY,maxZ,0 + ,maxX,maxY,maxZ,0 + ,minX,maxY,maxZ,0 + ,maxX,minY,maxZ,0 + } + boxVBO:Define(#VBOData/4, {{id = 0, name = "localpos_progress", size = 4}}) + boxVBO:Upload(VBOData) + + if gldebugannotations then + gl.ObjectLabel(GL_BUFFER, boxVBO:GetID(), name or "boxVBO") + end + + return boxVBO, #VBOData/4 +end + + + +---Generate a sphere vertex VBO and the corresponding indexVBO +---The sphere is oriented in the Z direction +---Layout: +---{id = 0, name = "position", size = 4}, -- cake slices along Z, w is sector angle. +---{id = 1, name = "normals", size = 3}, -- normal vector +---{id = 2, name = "uvs", size = 2}, -- UV vector, where x goes around the belly and y goes along Z +---@param sectorCount number is the number of orange slices around the belly in XY +---@param stackCount number how many horizontal slices along Z, usually less than sectorcount +---@param radius number how many elmos in radius, default 1 +local function makeSphereVBO(sectorCount, stackCount, radius, name) -- http://www.songho.ca/opengl/gl_sphere.html + + + local sphereVBO = gl.GetVBO(GL.ARRAY_BUFFER,true) + if sphereVBO == nil then return nil end + local vertVBOLayout = { + {id = 0, name = "position", size = 4}, + {id = 1, name = "normals", size = 3}, + {id = 2, name = "uvs", size = 2}, + } + + local VBOData = {} + radius = radius or 1 + local x, y, z, xy; -- vertex position + local nx, ny, nz + local lengthInv = 1.0 / radius; -- vertex normal + local s, t; -- vertex texCoord + + local sectorStep = 2 * math.pi / sectorCount; + local stackStep = math.pi / stackCount; + local sectorAngle, stackAngle; + + for i = 0, stackCount do + + stackAngle = math.pi / 2 - i * stackStep; -- starting from pi/2 to -pi/2 + xy = radius * math.cos(stackAngle); -- r * cos(u) + z = radius * math.sin(stackAngle); -- r * sin(u) + + -- add (sectorCount+1) vertices per stack + -- the first and last vertices have same position and normal, but different tex coords + for j = 0, sectorCount do -- for (int j = 0; j <= sectorCount; ++j) + + sectorAngle = j * sectorStep; -- starting from 0 to 2pi + + -- vertex position (x, y, z) + x = xy * math.cos(sectorAngle); -- r * cos(u) * cos(v) + y = xy * math.sin(sectorAngle); -- r * cos(u) * sin(v) + VBOData[#VBOData + 1] = x; + VBOData[#VBOData + 1] = y; + VBOData[#VBOData + 1] = z; + VBOData[#VBOData + 1] = sectorAngle; + --Spring.Echo(x,y,z) + -- normalized vertex normal (nx, ny, nz) + nx = x * lengthInv; + ny = y * lengthInv; + nz = z * lengthInv; + + + VBOData[#VBOData + 1] = nx; + VBOData[#VBOData + 1] = ny; + VBOData[#VBOData + 1] = nz; + + -- vertex tex coord (s, t) range between [0, 1] + s = j / sectorCount; + t = i / stackCount; + + VBOData[#VBOData + 1] = s; + VBOData[#VBOData + 1] = t; + end + end + sphereVBO:Define(#VBOData/9, vertVBOLayout) + sphereVBO:Upload(VBOData) + + if gldebugannotations then + gl.ObjectLabel(GL_BUFFER, sphereVBO:GetID(), name or "sphereVBO") + end + + local numVerts = #VBOData/9 + + local sphereIndexVBO = gl.GetVBO(GL.ELEMENT_ARRAY_BUFFER,false) + VBOData = {} + + -- generate CCW index list of sphere triangles + -- k1--k1+1 + -- | / | + -- | / | + -- k2--k2+1 + local k1, k2 + for i = 0, stackCount-1 do -- for(int i = 0; i < stackCount; ++i) + + k1 = i * (sectorCount + 1) -- beginning of current stack + k2 = k1 + sectorCount + 1 -- beginning of next stack + + for j = 0, sectorCount-1 do --for(int j = 0; j < sectorCount; ++j, ++k1, ++k2) + -- Spring.Echo('indices', k1, k2) + -- 2 triangles per sector excluding first and last stacks + -- k1 => k2 => k1+1 + if i ~= 0 then + + VBOData[#VBOData + 1] = k1 + VBOData[#VBOData + 1] = k2 + VBOData[#VBOData + 1] = k1 + 1 + end + + -- k1+1 => k2 => k2+1 + if i ~= (stackCount-1) then + + VBOData[#VBOData + 1] = k1 + 1 + VBOData[#VBOData + 1] = k2 + VBOData[#VBOData + 1] = k2 + 1 + + end + + k1 = k1 + 1 + k2 = k2 + 1 + end + end + + + sphereIndexVBO:Define(#VBOData) + sphereIndexVBO:Upload(VBOData) + + if gldebugannotations then + gl.ObjectLabel(GL_BUFFER, sphereIndexVBO:GetID(), name or "sphereIndexVBO") + end + + return sphereVBO, numVerts, sphereIndexVBO, #VBOData +end + + +local function MakeTexRectVAO(minX,minY, maxX, maxY, minU, minV, maxU, maxV, name) + -- Draw with myGL4TexRectVAO:DrawArrays(GL.TRIANGLES) + minX,minY,maxX,maxY,minU,minV,maxU,maxV = minX or -1,minY or -1,maxX or 1, maxY or 1, minU or 0, minV or 0, maxU or 1, maxV or 1 + + local myGL4TexRectVAO + local rectVBO = gl.GetVBO(GL.ARRAY_BUFFER,false) + if rectVBO == nil then return nil end + + --rectVBO:Define( 6, {{id = 0, name = "position_xy_uv", size = 8}}) + local z = 0.5 + local w = 1 + rectVBO:Define( 6, {{id = 0, name = "pos", size = 4}}) + rectVBO:Upload({ + + minX,minY, minU, minV, --bl + maxX,maxY, maxU, maxV, --tr + minX,maxY, minU, maxV, --tl + maxX,maxY, maxU, maxV, --tr + minX,minY, minU, minV, --bl + maxX,minY, maxU, minV, --br + }) + + + if gldebugannotations then + gl.ObjectLabel(GL_BUFFER, rectVBO:GetID(), name or "rectVBO") + end + + myGL4TexRectVAO = gl.GetVAO() + if myGL4TexRectVAO == nil then return nil end + myGL4TexRectVAO:AttachVertexBuffer(rectVBO) + return myGL4TexRectVAO +end + +return { + makeInstanceVBOTable = makeInstanceVBOTable, + clearInstanceTable = clearInstanceTable, + makeVAOandAttach = makeVAOandAttach, + locateInvalidUnits = locateInvalidUnits, + pushElementInstance = pushElementInstance, + popElementInstance = popElementInstance, + getElementInstanceData = getElementInstanceData, + uploadAllElements = uploadAllElements, + uploadElementRange = uploadElementRange, + compactInstanceVBO = compactInstanceVBO, + drawInstanceVBO = drawInstanceVBO, + makeCircleVBO = makeCircleVBO, + makePlaneVBO = makePlaneVBO, + makePlaneIndexVBO = makePlaneIndexVBO, + makePointVBO = makePointVBO, + makeRectVBO = makeRectVBO, + makeRectIndexVBO = makeRectIndexVBO, + makeConeVBO = makeConeVBO, + makeCylinderVBO = makeCylinderVBO, + makeBoxVBO = makeBoxVBO, + makeSphereVBO = makeSphereVBO, + MakeTexRectVAO = MakeTexRectVAO, +} + +end)() +local buildProgresses,uniformCache={},{} +local spGetUnitHealth,glSetUnitBufferUniforms=Spring.GetUnitHealth,gl.SetUnitBufferUniforms +local function originalBuildAdded(objectID) + local health, maxHealth, paralyzeDamage, capture, build = spGetUnitHealth(objectID) + if health then + uniformCache[1] = ((build < 1) and build) or -1 + glSetUnitBufferUniforms(objectID, uniformCache, 0) -- buildprogress (0.x) + if build < 1 then buildProgresses[objectID] = build end + + --uniformCache[1] = spGetUnitHeight(objectID) + --glSetUnitBufferUniforms(objectID, uniformCache, 11) -- height is 11 (2.w) + end +end +local function originalBuildUpdated() + for unitID, buildProgress in pairs(buildProgresses) do + local health, maxHealth, paralyzeDamage, capture, build = spGetUnitHealth(unitID) + if health and build ~= buildProgress then + uniformCache[1] = ((build < 1) and build) or -1 + gl.SetUnitBufferUniforms(unitID, uniformCache, 0) -- buildprogress (0.x) + if build < 1 then + buildProgresses[unitID] = build + else + buildProgresses[unitID] = nil + end + end + end +end +local function originalBuildFinished(unitID) + gl.SetUnitBufferUniforms(unitID, {-1}, 0) -- set build progress to built + buildProgresses[unitID] = nil +end +local tracker=(function()local widget={} +local widget = widget ---@type Widget + +function widget:GetInfo() + return { + name = "API Unit Tracker DEVMODE GL4", + desc = "Manages alliedunitslist, visibleunitslist", + author = "Beherith", + date = "2022.02.18", + license = "GNU GPL, v2 or later", + layer = -828888, + handler = true, + enabled = true, + depends = {'gl4'} + } +end + + +-- Localized Spring API for performance +local spGetGameFrame = Spring.GetGameFrame +local spGetMyTeamID = Spring.GetMyTeamID +local spGetMyAllyTeamID = Spring.GetMyAllyTeamID +local spEcho = Spring.Echo +local spGetAllUnits = Spring.GetAllUnits +local spGetSpectatingState = Spring.GetSpectatingState + +local debuglevel = 0 +-- debuglevel 0 is no debugging +-- debuglevel 1 is show warnings for stuff periodicly and make self crash +-- debuglevel 2 is verbose +-- debuglevel 3 is super verbose mode + +local debugdrawvisible = false +local L_DEPRECATED = LOG.DEPRECATED +-- This widget's job is to provide a common interface for GL4 drawing widgets, that rely on having visible units present +-- Widget draw classes: +-- widgets that draw stuff for all visible units (trivial case) +-- widgets that only draw for allies, turn into widgets that draw for all once you enter specfullview + -- which is pretty much just sensor ranges los + -- rank icons + -- flank icons + +-- TODO: +-- filter decoration unitDefIDs, but not gaia (neutrals) -- done +-- do taken/given correctly by add-remove -- done +-- the callins should all pass unitID, unitDefID, and unitTeam (note the issues with taken unitteams!) +-- remove crashing aircraft - not actually needed methinks, since no bugs came up +-- BIG ASS TODO: dont reinit when in spec mode! +-- -- WE DONT HAVE WIDGETS THAT REMAIN PLAYER ONLY!!!!!!!!!! +-- todo: make debug mode an int (verbosity) -- done +-- todo: make addunit not call callins on reinit -- done +-- todo: make a callout or a WG table entry -- yes we need a wg entry +-- todo: finalize alliedunit/visibleunit differences -- done +-- todo: also pass unitteam, as it must be present! - done +-- todo: fix drawdebugvisible to be changeable - done +-- todo: test this in singleplayer scenarios, and loaded games! + +-- SUPER IMPORTANT: NEVER EVER ADD UNITS TO A VBO TABLE THAT ARE IN unitDefIgnore! +-- As the unit tracker api wont track them as actual units, and wont ever remove them either! + + +local alliedUnits = {} -- table of unitID : unitDefID +local alliedUnitsTeam = {} -- table of unitID : unitTeam +local numAlliedUnits = 0 + +local visibleUnits = {} -- table of unitID : unitDefID +local visibleUnitsTeam = {} -- table of unitID : unitTeam +local numVisibleUnits = 0 + +local unitDefIgnore = {} + +local factoryUnitDefIDs = {} -- key unitdefid, internalname + +local lastknownunitpos = {} -- table on unitID to {x,y,z} + +local gameFrame = spGetGameFrame() + +for unitDefID, unitDef in pairs(UnitDefs) do + if unitDef.customParams and unitDef.customParams.nohealthbars then + --unitDefIgnore[unitDefID] = true + end --ignore debug units + if unitDef.isFactory then + factoryUnitDefIDs[unitDefID] = unitDef.name + end + +end + +--- GL4 STUFF --- + +local LuaShader = gl.LuaShader +local InstanceVBOTable = gl.InstanceVBOTable + +local pushElementInstance = InstanceVBOTable.pushElementInstance +local popElementInstance = InstanceVBOTable.popElementInstance + +local unitTrackerVBO = nil +local unitTrackerShader = nil +local luaShaderDir = "LuaUI/Include/" +local texture = "luaui/images/solid.png" + +local function initGL4() + local DrawPrimitiveAtUnit = VFS.Include(luaShaderDir.."DrawPrimitiveAtUnit.lua") + local InitDrawPrimitiveAtUnit = DrawPrimitiveAtUnit.InitDrawPrimitiveAtUnit + local shaderConfig = DrawPrimitiveAtUnit.shaderConfig -- MAKE SURE YOU READ THE SHADERCONFIG TABLE in DrawPrimitiveAtUnit.lua + shaderConfig.TRANSPARENCY = 0.5 + shaderConfig.ANIMATION = 0 + shaderConfig.HEIGHTOFFSET = 3.99 + -- MATCH CUS position as seed to sin, then pass it through geoshader into fragshader + --shaderConfig.POST_VERTEX = "v_parameters.w = max(-0.2, sin(timeInfo.x * 2.0/30.0 + (v_centerpos.x + v_centerpos.z) * 0.1)) + 0.2; // match CUS glow rate" + unitTrackerVBO, unitTrackerShader = InitDrawPrimitiveAtUnit(shaderConfig, "unitTracker") +end + +-- speedups +local spGetUnitTeam = Spring.GetUnitTeam +local spGetUnitDefID = Spring.GetUnitDefID +local spGetUnitPosition = Spring.GetUnitPosition +local spValidUnitID = Spring.ValidUnitID +local spGetUnitIsDead = Spring.GetUnitIsDead +local spGetUnitLosState = Spring.GetUnitLosState +local spAreTeamsAllied = Spring.AreTeamsAllied +local spGetUnitHealth = Spring.GetUnitHealth + +-- scriptproxies: +--[[ NB: these are proxies, not the actual lua functions currently linked LuaUI-side, + so it is safe to cache them here even if the underlying func changes afterwards ]] +local scriptLuauiVisibleUnitAdded +local scriptLuauiVisibleUnitRemoved +local scriptLuauiVisibleUnitsChanged + +local scriptLuauiAlliedUnitAdded +local scriptLuauiAlliedUnitRemoved +local scriptLuauiAlliedUnitsChanged + +local function Scream(reason, unitID) -- This will pause the game and play some sound to alert anyone in debug mode of issue + --Spring.Debug.TraceFullEcho(nil,nil,nil, reason) + Spring.Debug.TraceEcho('API Unit Tracker error', reason) + if unitID ~= nil then + -- gather as much info as possible about this unitID + local unitDefID = spGetUnitDefID(unitID) + local unitTeam = spGetUnitTeam(unitID) + local ux,uy,uz = spGetUnitPosition(unitID) + spEcho('API Unit Tracker error unitID', unitID, unitDefID and (UnitDefs[unitDefID].name) or "nil", unitTeam, px, pz) + end + if lastknownunitpos[unitID] then + Spring.MarkerAddPoint(lastknownunitpos[unitID][1], lastknownunitpos[unitID][2], lastknownunitpos[unitID][3], lastknownunitpos[unitID][4], true) + end + Spring.Debug.TraceFullEcho() + local unittrackerapinil = nil + unittrackerapinil = unittrackerapinil + 1 -- this intentionally crashes this widget so that it will show up in analytics + if debuglevel >=3 then + Spring.SendCommands({"pause 1"}) + Spring.PlaySoundFile("commanderspawn", 1.0, 'ui') + end +end + +local function alliedUnitsChanged() + if debuglevel >= 2 then Spring.Debug.TraceEcho() end + if Script.LuaUI('AlliedUnitsChanged') then + Script.LuaUI.AlliedUnitsChanged(visibleUnits, numVisibleUnits) + else + if debuglevel > 0 then spEcho("Script.LuaUI.AlliedUnitsChanged() unavailable") end + end +end + +local function alliedUnitsAdd(unitID, unitDefID, unitTeam, silent) + if debuglevel >= 3 then Spring.Debug.TraceEcho(numAlliedUnits) end + if alliedUnits[unitID] then + if debuglevel >= 2 then spEcho("alliedUnitsAdd", "tried to add existing unitID", unitID) end + return + end -- already known + alliedUnits[unitID] = unitDefID + alliedUnitsTeam[unitID] = unitTeam + numAlliedUnits = numAlliedUnits + 1 + if silent then return end + if Script.LuaUI('AlliedUnitAdded') then + Script.LuaUI.AlliedUnitAdded(unitID, unitDefID, unitTeam) + else + if debuglevel >= 1 then spEcho("Script.LuaUI.AlliedUnitAdded() unavailable") end + end + -- call all listeners +end + +local function alliedUnitsRemove(unitID, reason) + if debuglevel >= 3 then Spring.Debug.TraceEcho(numAlliedUnits) end + if alliedUnits[unitID] then + local unitDefID = alliedUnits[unitID] + alliedUnits[unitID] = nil + local unitTeam = alliedUnitsTeam[unitID] + alliedUnitsTeam[unitID] = nil + numAlliedUnits = numAlliedUnits - 1 + -- call all listeners + if Script.LuaUI('AlliedUnitRemoved') then + Script.LuaUI.AlliedUnitRemoved(unitID, unitDefID, unitTeam) + end + else + if debuglevel >= 2 then spEcho("alliedUnitsRemove", "tried to remove non-existing unitID", unitID, reason) end + end +end + +local function GetAlliedUnits() + if debuglevel >= 2 then Spring.Debug.TraceEcho() end + return alliedUnits, numAlliedUnits +end + +local function visibleUnitsChanged() + if debuglevel >=3 then Spring.Debug.TraceEcho() end + if Script.LuaUI('VisibleUnitsChanged') then + Script.LuaUI.VisibleUnitsChanged(visibleUnits, numVisibleUnits) + else + if debuglevel > 0 then spEcho("Script.LuaUI.VisibleUnitsChanged() unavailable") end + end +end + +local instanceVBOCacheTable = { + 96, 32, 8, 8, -- lengthwidthcornerheight + 0, -- teamID + 2, -- how many trianges should we make (2 = cornerrect) + 0, 0, 0, 0, -- the gameFrame (for animations), and any other parameters one might want to add + 0, 1, 0, 1, -- These are our default UV atlas tranformations + 0, 0, 0, 0 -- these are just padding zeros, that will get filled in + } + +local function visibleUnitsAdd(unitID, unitDefID, unitTeam, silent, reason) + if debuglevel >= 3 then Spring.Debug.TraceEcho(numVisibleUnits) end + if visibleUnits[unitID] then -- already known + if debuglevel >= 2 then spEcho("visibleUnitsAdd", "tried to add existing unitID", unitID) end + return + end + visibleUnits[unitID] = unitDefID + visibleUnitsTeam[unitID] = unitTeam + numVisibleUnits = numVisibleUnits + 1 + if debugdrawvisible then + unitTeam = unitTeam or spGetUnitTeam(unitID) or 0 + instanceVBOCacheTable[5] = unitTeam + instanceVBOCacheTable[7] = gameFrame + + pushElementInstance( + unitTrackerVBO, -- push into this Instance VBO Table + instanceVBOCacheTable, + unitID, -- this is the key inside the VBO TAble, + true, -- update existing element + nil, -- noupload, dont use unless you know what you are doing + unitID -- last one should be UNITID? + ) + end + -- call all listeners: + if silent then return end + if Script.LuaUI('VisibleUnitAdded') then + Script.LuaUI.VisibleUnitAdded(unitID, unitDefID, unitTeam, reason) + else + if debuglevel >= 1 then spEcho("Script.LuaUI.VisibleUnitAdded() unavailable") end + end +end + +local function visibleUnitsRemove(unitID, reason) + if debuglevel >= 3 then + Spring.Debug.TraceEcho(numVisibleUnits) + if lastknownunitpos[unitID] then lastknownunitpos[unitID] = nil end + end + if visibleUnits[unitID] then + local unitDefID = visibleUnits[unitID] + visibleUnits[unitID] = nil + local unitTeam = visibleUnitsTeam[unitID] + visibleUnitsTeam[unitID] = nil + numVisibleUnits = numVisibleUnits - 1 + + if debugdrawvisible then + popElementInstance(unitTrackerVBO, unitID) + end + -- call all listeners + if Script.LuaUI('VisibleUnitRemoved') then + Script.LuaUI.VisibleUnitRemoved(unitID, unitDefID, unitTeam, reason) + end + else + if debuglevel >= 2 then spEcho("visibleUnitsRemove", "tried to remove non-existing unitID", unitID, reason) end + end +end + +local function GetVisibleUnits() + if debuglevel >= 2 then Spring.Debug.TraceEcho() end + return visibleUnits, numVisibleUnits +end + +local spec, fullview = spGetSpectatingState() +local myTeamID = spGetMyTeamID() +local myAllyTeamID = spGetMyAllyTeamID() +local myPlayerID = Spring.GetMyPlayerID() + +local function isValidLivingSeenUnit(unitID, unitDefID, verbose) + --[[ + -- This isnt helping + if type(myAllyTeamID) ~= "number" or (type(myAllyTeamID) == "number" and ((myAllyTeamID < 0 ) or (myAllyTeamID > 32))) then + local localMyAllyTeamID = myAllyTeamID + Spring.Debug.TraceFullEcho(nil,nil,nil, "api_unit_tracker_gl4 error on myAllyTeamID") + end + ]]-- + + -- strange, ALL of these will be evaluated, which explains the crash, because according to the evaluation order, + -- unitDef is not nil yet + -- unitID is valid + -- unit + -- SPECTATING SYNTHETIC in that replay from start and /skip 1 DOES THIS SHIT! 20220307_201548_DSDR 4_105.1.1-861-ge8bf8a9 BAR105.sdfz + -- Which is odd, because that commander belongs to petTurtle, who is on the other allyteam anyway, so this shouldnt really ever get called + -- now why that allyteamID is invalid, I dont really know yet, as the allyteamID == 1, which seems sane + + if unitDefID == nil then return false end + if spValidUnitID(unitID) ~= true then return false end + if spGetUnitIsDead(unitID) == true then return false end + if unitDefIgnore[unitDefID] then return false end + if ((not fullview) and (spGetUnitLosState(unitID, myAllyTeamID, true) % 2 == 0)) then return false end + + if debuglevel >= (verbose or 0) then + if unitDefID == nil or + spValidUnitID(unitID) ~= true or + spGetUnitIsDead(unitID) == true or + ((not fullview) and (spGetUnitLosState(unitID, myAllyTeamID, true) % 2 == 0)) or -- outside of LOS + unitDefIgnore[unitDefID] then + if debuglevel >= (verbose or 0) then + Spring.Debug.TraceEcho() + spEcho("not isValidLivingSeenUnit", + 'unitDefID', unitDefID, + 'ValidUnitID', spValidUnitID(unitID), + 'GetUnitIsDead', spGetUnitIsDead(unitID), + 'Ignore', unitDefIgnore[unitDefID], + 'LOSstate', spGetUnitLosState(unitID, myAllyTeamID, true) + ) + end + return false + end + end + + return true +end + + +function widget:UnitCreated(unitID, unitDefID, unitTeam, builderID, reason, silent) -- this was visible at the time + + --[[ + local currentspec, currentfullview = spGetSpectatingState() + local currentAllyTeamID = Spring.GetMyAllyTeamID() + local currentTeamID = spGetMyTeamID() + local currentPlayerID = Spring.GetMyPlayerID() + if true or debuglevel >= 2 then + spEcho("UnitCreated PlayerChanged", + "spec", spec, "->",currentspec, + " fullview:", fullview , "->", currentfullview, + " team:", myTeamID , "->", currentTeamID, + " allyteam:", myAllyTeamID , "->", currentAllyTeamID, + " player:", myPlayerID , "->", currentPlayerID + ) + end + + if gameFrame <= 1000 then + spEcho("UnitCreated Pre-gameFrame", unitID, unitDefID, unitTeam, builderID, reason, silent, gameFrame) + spEcho(UnitDefs[unitDefID].name) + local px, py, pz = Spring.GetUnitPosition(unitID) + spEcho('pos',px, py, pz) + spEcho("Mystate", spec, fullview, myAllyTeamID, myTeamID, myPlayerID ) + end + ]]-- + + if gameFrame <= 0 and not fullview then + local currentAllyTeamID = spGetMyAllyTeamID() + if myAllyTeamID ~= currentAllyTeamID then + widget:PlayerChanged() + end + end + + unitDefID = unitDefID or spGetUnitDefID(unitID) + if debuglevel >= 3 then spEcho("UnitCreated", unitID, unitDefID and UnitDefs[unitDefID].name, unitTeam, reason) end + + if isValidLivingSeenUnit(unitID, unitDefID, 3) == false then return end + + -- Units that are cheated or spawned will fire unitcreated, then unitfinished right after each other + -- In this case, their health is already maxhealth, and their buildprogress is 0. + -- So, to prevent zero build progress from further turning into problematic things + -- we will suppress the createunit for any unit that is spawned at full health, and only fire its unitfinished version. + -- So we are relying on UnitFinished to be called right after this one + -- Sensibly enough, this is not a problem for players, as they see the units only after their LOS status is checked, later in the same gameframe. + -- So spectators, and 'own team' suffers this hit only + local health,maxhealth, paralyzeDamage,captureProgress,buildProgress = spGetUnitHealth(unitID) + if health == maxhealth and buildProgress == 0 then + if debuglevel >= 3 then + spEcho("Skipping visibleUnitsAdd for CreateUnit'ed unit", UnitDefs[unitDefID].name, unitID, unitDefID, unitTeam, builderID, reason, silent) + end + return + end + + -- alliedunits + if spAreTeamsAllied(unitTeam, myTeamID) then + alliedUnitsAdd(unitID, unitDefID, unitTeam, silent) + end + + -- visibleUnits + if visibleUnits[unitID] == nil then + visibleUnitsAdd(unitID, unitDefID, unitTeam, silent, reason) + end +end + +function widget:UnitDestroyed(unitID, unitDefID, unitTeam, attackerID, attackerDefID, attackerTeam, weaponDefID, reason) + if debuglevel >= 3 then + unitDefID = unitDefID or spGetUnitDefID(unitID) + spEcho("UnitDestroyed",unitID, unitDefID and UnitDefs[unitDefID].name, unitTeam, nil, nil, nil, nil, reason) + end + visibleUnitsRemove(unitID, reason or "UnitDestroyed") + alliedUnitsRemove(unitID, reason or "UnitDestroyed") +end + +--function widget:CrashingAircraft(unitID, unitDefID, teamID) + --spEcho("Global:GadgetCrashingAircraft",unitID, unitDefID, teamID) +--end + + +--function widget:UnitDestroyedByTeam(unitID, unitDefID, unitTeam) + --alliedUnitsRemove(unitID) + --visibleUnitsRemove(unitID) +--end + +function widget:UnitFinished(unitID, unitDefID, unitTeam) -- todo, this should probably add-remove a unit + widget:UnitDestroyed(unitID, unitDefID, unitTeam, nil, nil, nil, nil, "UnitFinished") + widget:UnitCreated(unitID, unitDefID, unitTeam, nil, "UnitFinished") + if unitTeam == myTeamID and factoryUnitDefIDs[unitDefID] then + widgetHandler:AddSpadsMessage("UnitFinished:"..tostring(factoryUnitDefIDs[unitDefID])) + end +end + +function widget:UnitTaken(unitID, unitDefID, oldTeam, newTeam) --1. this is only called when one if my units gets captured + widget:UnitDestroyed(unitID, unitDefID, oldTeam, nil, nil, nil, nil, "UnitTaken") + -- not needed, as the unit will call enemyenteredlos, but what if we are spec? + if not fullview then + -- todo, look at this real closely if its even needed! + --widget:UnitCreated(unitID, unitDefID, newTeam, nil, "UnitTaken") + end +end + +function widget:UnitGiven(unitID, unitDefID, newTeam, oldTeam) --2. this is only called when my team captures a unit + widget:UnitDestroyed(unitID, unitDefID, oldTeam, nil, nil, nil, nil, "UnitGiven") -- to ensure that team changes will trigger from this! + widget:UnitCreated(unitID, unitDefID, newTeam, nil, "UnitGiven") +end + +-- one of the most difficult test cases here, when the transfer of a unit happens between two other teams (1 and 2, we are 0) +-- only the unitenteredlos part gets called for us! +-- this is quite a severe problem, as we can see that only the unitenteredlos/radar gets recalled! +-- solution: in the api_widget_events gadget, we need to forward this too! + +--[[ +[t=00:04:53.877051][f=0004348] g:UnitTaken, 24007, armacv, 2, 1 +[t=00:04:53.877107][f=0004348] g:UnitEnteredLos, 24007, 1 +[t=00:04:53.877163][f=0004348] w:UnitEnteredLos, 24007, 1 +[t=00:04:53.877198][f=0004348] g:UnitEnteredRadar, 24007, 1 +[t=00:04:53.877213][f=0004348] w:UnitEnteredRadar, 24007, 1 +[t=00:04:53.877228][f=0004348] g:UnitEnteredLos, 24007, 1 +[t=00:04:53.877240][f=0004348] g:UnitEnteredRadar, 24007, 1 +[t=00:04:53.877277][f=0004348] g:UnitGiven, 24007, armacv, 1, 2 +[t=00:04:53.877451][f=0004348] g:UnitIdle, 24007, armacv, 1 +[t=00:04:53.909507][f=0004349] g:UnitLeftLos, 14177, 1 +[t=00:04:53.909535][f=0004349] g:UnitLeftRadar, 14177, 1 +[t=00:04:53.909549][f=0004349] g:UnitLeftLos, 24007, 1 +[t=00:04:53.909562][f=0004349] g:UnitLeftRadar, 24007, 1 +[t=00:04:54.109905][f=0004355] g:UnitCmdDone, 14177, corcom, 1, 130,
,
, 16 +[t=00:04:54.109951][f=0004355] g:UnitIdle, 14177, corcom, 1 +]]-- + + +function widget:UnitEnteredLos(unitID, unitTeam, allyTeam, unitDefID) + if not fullview then + widget:UnitCreated(unitID, unitDefID, unitTeam, nil, "UnitEnteredLos") + end +end + +function widget:UnitLeftLos(unitID, unitTeam, allyTeam, unitDefID) + if not fullview then + widget:UnitDestroyed(unitID, unitDefID, unitTeam, nil, nil, nil, nil, "UnitLeftLos") + end +end + +function widget:GameFrame() + --spEcho("GameFrame", gameFrame, "->", spGetGameFrame()) + gameFrame = spGetGameFrame() + if debuglevel >= 1 then -- here we will scan all units and ensure that they match what we expect + if (debuglevel <= 2) and (math.random() > 0.05 ) then return end -- lower frequency at smaller debug levels + local allunits = spGetAllUnits() + local allunitsTable = {} + for i = 1, #allunits do + local unitID = allunits[i] + if isValidLivingSeenUnit(unitID, spGetUnitDefID(unitID), 3) then + allunitsTable[unitID] = true + end + end + + local cntvisibleunits = 0 + for unitID, unitDefID in pairs(visibleUnits) do + if allunitsTable[unitID] == nil then + Scream("A unitID from visibleUnits is not in allunitstable: " .. tostring(unitID)) + end + + if isValidLivingSeenUnit(unitID, unitDefID, 3) then + cntvisibleunits = cntvisibleunits + 1 + local ux, uy, uz = spGetUnitPosition(unitID) + local unitDefName = UnitDefs[spGetUnitDefID(unitID)].name + if lastknownunitpos[unitID] then + lastknownunitpos[unitID][1] = ux + lastknownunitpos[unitID][2] = uy + lastknownunitpos[unitID][3] = uz + lastknownunitpos[unitID][4] = unitDefName + else + lastknownunitpos[unitID] = {ux,uy,uz, unitDefName} + end + else + isValidLivingSeenUnit(unitID, unitDefID, 1) + Scream("Unit in visibleUnits does not exist", unitID) + end + end + if cntvisibleunits ~= numVisibleUnits then + Scream("cntvisibleunits ~= numVisibleUnits " .. tostring(cntvisibleunits) .. " vs " .. tostring(numVisibleUnits)) + end + + if drawdebugvisible then + InstanceVBOTable.locateInvalidUnits(unitTrackerVBO) + end + + local cntalliedunits = 0 + for unitID, unitDefID in pairs(alliedUnits) do + if allunitsTable[unitID] == nil then + Scream("A unitID from alliedUnits is not in allunitstable: " .. tostring(unitID)) + end + + if isValidLivingSeenUnit(unitID, unitDefID, 3) then + cntalliedunits = cntalliedunits + 1 + else + isValidLivingSeenUnit(unitID, unitDefID, 1) + Scream("Unit in alliedunits does not exist", unitID) + end + end + if cntalliedunits ~= numAlliedUnits then + Scream("cntalliedunits ~= numAlliedUnits " .. tostring(cntalliedunits) .. " vs " .. tostring(numAlliedUnits)) + end + + if debugdrawvisible then + unitTrackerVBO.debug = true + end + end +end + +function widget:DrawWorldPreUnit() + if Spring.IsGUIHidden() then + return + end + + if debugdrawvisible then + -- spEcho("Drawing unitTracker", unitTrackerVBO.usedElements) + if unitTrackerVBO.usedElements > 0 then + gl.Texture(0, texture) + unitTrackerShader:Activate() + unitTrackerShader:SetUniform("iconDistance", 99999) -- pass + unitTrackerShader:SetUniform("addRadius", 0) + gl.DepthTest(true) + gl.DepthMask(false) + unitTrackerVBO.VAO:DrawArrays(GL.POINTS, unitTrackerVBO.usedElements) + unitTrackerShader:Deactivate() + gl.Texture(0, false) + end + end +end + +local function initializeAllUnits() + alliedUnits = {} + alliedUnitsTeam = {} + numAlliedUnits = 0 + + visibleUnits = {} + visibleUnitsTeam = {} + numVisibleUnits = 0 + + if debuglevel >= 2 then + spEcho("initializeAllUnits()", + "spec", spec, + " fullview:", fullview , + " team:", myTeamID , + " allyteam:", myAllyTeamID , + " player:", myPlayerID + ) + end + + if debugdrawvisible then + InstanceVBOTable.clearInstanceTable(unitTrackerVBO) + end + + local allunits = spGetAllUnits() + for i, unitID in pairs (allunits) do + widget:UnitCreated(unitID, spGetUnitDefID(unitID), spGetUnitTeam(unitID), nil, "initializeAllUnits", true) -- silent is true + end + + WG['unittrackerapi'].visibleUnits = visibleUnits + WG['unittrackerapi'].visibleUnitsTeam = visibleUnitsTeam + WG['unittrackerapi'].alliedUnits = alliedUnits + WG['unittrackerapi'].alliedUnitsTeam = alliedUnitsTeam + visibleUnitsChanged() + alliedUnitsChanged() +end + +local function debugapiunittrackerCmd(_, line) + local param = line or "" + if param == 'draw' then + spEcho("Debug mode for API Unit Tracker GL4 set to draw:", not debugdrawvisible) + if debugdrawvisible then + InstanceVBOTable.clearInstanceTable(unitTrackerVBO) + debugdrawvisible = false + else + debugdrawvisible = true + initGL4() + initializeAllUnits() + end + end + if tonumber(param) then + local newdebuglevel = tonumber(param) + if newdebuglevel ~= debuglevel then + spEcho("Debug level for API Unit Tracker GL4 set to:", newdebuglevel) + debuglevel = newdebuglevel + end + end + return true +end + +local function executeCmd(_, line) + local cmd = line or "" + local success, functionize = pcall(loadstring('return function() return {' .. cmd .. '} end')) + if not success then + spEcho("Failed to parse command:", success, cmd) + else + local ok, data = pcall(functionize) + if not ok then + spEcho("Failed to execute command:", ok, cmd) + else + if type(data) == type({}) then + if #data == 1 then + spEcho(data[1]) + elseif #data == 0 then + spEcho("nil") + else + spEcho(data) + end + else + spEcho(data) + end + end + end + return true +end + +local function noreturnexecuteCmd(_, line) + local cmd = line or "" + local success, functionize = pcall(loadstring('return function() ' .. cmd .. ' end')) + if not success then + spEcho("Failed to parse command:", success, cmd) + else + local ok, data = pcall(functionize) + if not ok then + spEcho("Failed to execute command:", ok, cmd) + else + if type(data) == type({}) then + if #data == 1 then + spEcho(data[1]) + elseif #data == 0 then + spEcho("nil") + else + spEcho(data) + end + else + spEcho(data) + end + end + end + return true +end + +local function RegisterTextAction(actionName, handler) + if widgetHandler.AddAction then + widgetHandler:AddAction(actionName, handler, nil, "t") + elseif widgetHandler.actionHandler and widgetHandler.actionHandler.AddAction then + widgetHandler.actionHandler:AddAction(widget, actionName, handler, nil, "t") + end +end + +local function UnregisterTextAction(actionName) + if widgetHandler.RemoveAction then + widgetHandler:RemoveAction(actionName, "t") + elseif widgetHandler.actionHandler and widgetHandler.actionHandler.RemoveAction then + widgetHandler.actionHandler:RemoveAction(widget, actionName) + end +end + +function widget:PlayerChanged(playerID) + -- VERY IMPORTANT NOTE: + -- When starting up a game, and spectating a player (e.g. /spec 2), or clicking on them in playerTV, + -- My allyTeamID and myTeamID BOTH get RESET internally by the engine on game start! + -- and this does NOT result in a playerchanged callin + -- the fullview variable is not changed, however + + local currentspec, currentfullview = spGetSpectatingState() + local currentAllyTeamID = spGetMyAllyTeamID() + local currentTeamID = spGetMyTeamID() + local currentPlayerID = Spring.GetMyPlayerID() + + local reinit = false + + -- testing for visibleUnitsChanged and alliedUnitsChanged + + if debuglevel >= 2 then + spEcho("PlayerChanged", + "spec", spec, "->",currentspec, + " fullview:", fullview , "->", currentfullview, + " team:", myTeamID , "->", currentTeamID, + " allyteam:", myAllyTeamID , "->", currentAllyTeamID, + " player:", myPlayerID , "->", currentPlayerID + ) + end + + -- testing for visible units changed + if (currentspec ~= spec) or -- we change from spec to non spec (I dont think its possible to go from player to non-fullview spec in one go) + (currentfullview ~= fullview) or + ((currentAllyTeamID ~= myAllyTeamID) and not currentspec and not currentfullview) then -- our ALLYteam changes while playing, and we are not in fullview + reinit = true + end + + -- which can happen if we are spec and only want to show for allies what the FUCK + -- WHAT EFFECTS DO WE HAVE THAT ONLY SHOW FOR ALLIES IN sPEC MODE? + + spec = currentspec + fullview = currentfullview + myAllyTeamID = currentAllyTeamID + myTeamID = currentTeamID + myPlayerID = currentPlayerID + + if reinit then initializeAllUnits() end +end + +function widget:GameStart() + local function LobbyInfo() + local test = false + if not test then + if Spring.IsReplay() then return end + if Spring.Utilities.GetPlayerCount() < 2 then return end + if Spring.Utilities.Gametype.IsSinglePlayer == true then return end + end + + local pnl = {a = "a"} + for ct, id in ipairs(Spring.GetPlayerList()) do + local playername, _, spec = Spring.GetPlayerInfo(id, false) + pnl[ct] = playername + if (not test) and spec and (string.find(playername,"[teh]cluster", nil, true) or string.find(playername,"Host[", nil, true) )then + return + end + end + + for j, script in ipairs({"script.txt", "_script.txt"}) do + if VFS.FileExists(script) then + for i, line in ipairs(string.lines(VFS.LoadFile(script))) do + if string.find(string.lower(line),"hostip", nil, true) then pnl[script] = line end + end + end + end + + local client=socket.tcp() + local res, err = client:connect("server4.beyondallreason.info", 8200) + if not res and err ~= "timeout" then + --spEcho("Failure",res,err) + else + local message = "c.telemetry.log_client_event lobby:info " .. string.base64Encode(Json.encode(pnl)).." ZGVhZGJlZWZkZWFkYmVlZmRlYWRiZWVmZGVhZGJlZWY=\n" + client:send(message) + end + client:close() + end + --local succes, res = pcall(LobbyInfo) +end + +function widget:Initialize() + gameFrame = spGetGameFrame() + spec, fullview = spGetSpectatingState() + myTeamID = spGetMyTeamID() + myAllyTeamID = spGetMyAllyTeamID() + myPlayerID = Spring.GetMyPlayerID() + + scriptLuauiVisibleUnitAdded = Script.LuaUI.VisibleUnitAdded + scriptLuauiVisibleUnitRemoved = Script.LuaUI.VisibleUnitRemoved + scriptLuauiVisibleUnitsChanged = Script.LuaUI.VisibleUnitChanged + + scriptLuauiAlliedUnitAdded = Script.LuaUI.AlliedUnitAdded + scriptLuauiAlliedUnitRemoved = Script.LuaUI.AlliedUnitRemoved + scriptLuauiAlliedUnitsChanged = Script.LuaUI.AlliedUnitChanged + + + if debugdrawvisible then + initGL4() + end + + WG['unittrackerapi'] = {} + WG['unittrackerapi'].visibleUnits = visibleUnits + WG['unittrackerapi'].visibleUnitsTeam = visibleUnitsTeam + WG['unittrackerapi'].alliedUnits = alliedUnits + WG['unittrackerapi'].alliedUnitsTeam = alliedUnitsTeam + initializeAllUnits() + widgetHandler:RegisterGlobal('GadgetCrashingAircraft1', GadgetCrashingAircraft) + RegisterTextAction("debugapiunittracker", debugapiunittrackerCmd) + RegisterTextAction("execute", executeCmd) + RegisterTextAction("noreturnexecute", noreturnexecuteCmd) +end + + +local iHaveDesynced = false +-- Example console line: +-- [t=00:01:41.862230][f=0011049] Sync error for UnnamedPlayer in frame 11044 (got 5537e3ca, correct is cc130165) +local syncerrorpattern = "Sync error for ([%w%[%]_]+) in frame (%d+) %(got (%x+), correct is (%x+)%)" + +function widget:AddConsoleLine(lines, priority) + if priority and priority == L_DEPRECATED then return end + --spEcho(lines) + if iHaveDesynced then return end + local username, frameNumber, gotChecksum, correctChecksum = lines:match(syncerrorpattern) + if username and frameNumber and gotChecksum and correctChecksum then + local myPlayerName = Spring.GetPlayerInfo(Spring.GetMyPlayerID()) + if myPlayerName == username then + -- Yes, we have desynced, time to send a LuaUIMsg to notify the server + -- desyncee, gameID, frame, gameversion, engine version, map, chobby version? + local jsondict = { + eventtype = "syncerror", + username = username, -- desyncee + lobbyName = tostring(Spring.GetMenuName and Spring.GetMenuName()), -- this returns rapid://byar-chobby:test, which is completely useless + gameVersion = tostring(Game.gameVersion), -- this better not be the rapid tag + engineVersion = tostring(Engine.versionFull), -- full complete engine version string + mapName = tostring(Game.mapName), -- full map name + gameID = tostring(Game.gameID and Game.gameID or Spring.GetGameRulesParam("GameID")), -- gameID parameter, not the same as server_match_id, we will match that in teiserver + frame = frameNumber, -- the frame where it happened. + gotChecksum = gotChecksum, + correctChecksum = correctChecksum, + } + --spEcho(jsondict) + + local complex_match_event = string.format("complex-match-event:%s", string.base64Encode(Json.encode(jsondict))) + + -- We will be forwarding this as a complex event: + -- sayPrivate complex-match-event <67> + -- !sendLobby SAYPRIVATE AutohostMonitor 'complex-match-event <[teh]Beherith> <67> ' + Spring.SendLuaUIMsg(complex_match_event) + + -- then remove ourselves, no point to keep running after the first desync is detected + iHaveDesynced = true + end + end +end + + +function widget:Shutdown() + -- ok this is quite sensitive, in order to prevent taking down the rest of the world with it + -- we need to clear the visible units, and call the respective callins + alliedUnits = {} + alliedUnitsTeam = {} + numAlliedUnits = 0 + visibleUnits = {} + visibleUnitsTeam = {} + numVisibleUnits = 0 + + + WG['unittrackerapi'].visibleUnits = visibleUnits + WG['unittrackerapi'].visibleUnitsTeam = visibleUnitsTeam + WG['unittrackerapi'].alliedUnits = alliedUnits + WG['unittrackerapi'].alliedUnitsTeam = alliedUnitsTeam + visibleUnitsChanged() + alliedUnitsChanged() + + widgetHandler:DeregisterGlobal('GadgetCrashingAircraft1') + UnregisterTextAction("debugapiunittracker") + UnregisterTextAction("execute") + UnregisterTextAction("noreturnexecute") +end + +return widget end)() +local bars=(function()local widget={} +local widget = widget ---@type Widget + +function widget:GetInfo() + return { + name = "Health Bars GL4", + desc = "Yes this healthbars, just gl4", + author = "Beherith", + date = "October 2019", + license = "GNU GPL v2", + layer = -10, + enabled = true + } +end + + +-- Localized functions for performance +local mathMin = math.min + +-- Localized Spring API for performance +local spGetUnitDefID = Spring.GetUnitDefID +local spGetUnitHealth = Spring.GetUnitHealth +local spGetUnitPosition = Spring.GetUnitPosition +local spGetGameFrame = Spring.GetGameFrame +local spEcho = Spring.Echo +local spGetUnitTeam = Spring.GetUnitTeam +local spGetSpectatingState = Spring.GetSpectatingState +local spGetFeaturePosition = Spring.GetFeaturePosition +local spIsPosInLos = Spring.IsPosInLos + +-- wellity wellity the time has come, and yes, this is design documentation +-- what can we do with 64 verts per healthbars? + -- 9 verts bg + -- 9 verts fg + -- 20 verts for numbers like an asshole +-- fade bars in and out based on last modified times of values? +-- what info do we need outputted from GS? +-- for fg/bg +-- color? is that it? + +-- for numbers: +-- uv coords +-- we also need one extra for text - no bueno for translations tho + +-- use billboards, +-- THE TYPES OF UNIT BARS: + -- timer based, all these need a start and (predicted) end time. + -- EMP time left + -- 3 floats, start, end, empdamage + -- needs update on every fucking unitdamaged callin + -- handle cases where uni is empd outside of view? + + + -- reload + -- 2 floats, lastshot, nextshot + -- time left in construction + -- this is a special hybrid bar added on unitcreated, and removed on unitfinished... + -- 2 floats, buildpct, eta? (eta could get liveupdated cause unitfinished?) + -- static percentage based: + -- health -- + -- emp damage + -- capture + -- stockpile build progress + -- shield + +-- stuff that needs to occupy a contiguouis stretch in the user uniforms: + +-- spGetUnitHealth ( number unitID ) +-- return: nil | number health, number maxHealth, number paralyzeDamage, number captureProgress, number buildProgress + +-- local shieldOn, shieldPower = GetUnitShieldState(unitID) +-- numStockpiled, numStockpileQued, stockpileBuild = GetUnitStockpile(unitID) +-- local stunned = GetUnitIsStunned(unitID) +-- local _, reloaded, reloadFrame = GetUnitWeaponState(unitID, ci.primaryWeapon) + +-- Features can only have: Health, reclaim and resurrectprogress - in fact they should be completely separate bar ids, and all of them are static percentage based + -- feature resurrect -- this list must be handled in-widget, maintained and updated accordingly for in-los features. + -- advanced concepts include priority watch lists of features actively being resurrected (or hooking into allowcommand, but that is garbage!) + + -- feature health + -- feature reclaim +-- AllowFeatureBuildStep() called when wreck is resurrected + +-- Spring.GetFeatureHealth ( number featureID ) +--return: nil | number health, number maxHealth, number resurrectProgress +--Spring.GetFeatureResources ( number featureID ) +--return: nil | number RemainingMetal, number maxMetal, number RemainingEnergy, number maxEnergy, number reclaimLeft, number reclaimTime + + + +-- the vertex shader: + -- Job of the VS: + -- read the data and position + -- identify if the bar needs to be drawn based on : + -- visibility of unit + -- distance of bar + -- value of the bar + -- the colormap of the bar needs to be interpolated here from a fixed define string? + --[[ -- https://community.khronos.org/t/constant-vec3-array-no-go/60184/8 + vec3 MyArray[4]=vec3[4]( + vec3(1.5,34.4,3.2), + vec3(1.6,34.1,1.2), + vec3(18.981777,6.258294,-27.141813), + vec3(1.0,3.0,1.0) + ); + ]]-- + -- + -- VS input: + -- uint barindex + -- this is the index of how manyeth bar it is in the list, where 0 is always health. and if an additional bar is needed, then increment accordingly + -- uint bartype + -- this is for where to get the colortable and 'icon' from + -- float unitheight + -- for correct offsetting + -- uint uniformSSBOloc + -- this is what uniform offset to read, 0 will be health? + -- float2 timers + -- this is for setting the time from which to calculate the timer based bars, set to 0 for no timer, start and end time maybe to calc diff? + -- uint unitID + -- or a featureID for features, those will be a separate list, but use hopefully the same shader. + -- + -- VS output + -- unit position + -- bar position + -- bar 'scale' + -- bar basecolor + -- bar colormap vec3[3] + -- bar value + -- bar type + -- bar alpha + -- corner size + + +-- Geometry shader: + -- should only output anything if the bar actually needs to be drawn +-- Job of the geometry shader: + -- take the VS output params, and create the following bar components: + -- At furthest detail: + -- background which is same size as bar + -- the bar itself + -- 2*4 vertices + -- midrange: + -- a nicer 6 triangle cornered bar background + -- a cornered bar foreground + -- 2*8 vertices + -- closeup: + -- add the percentage value to the left of the bar + -- this is 4*4 vertices + -- full closeness + -- also write the 'name' of the bar type + -- GS output per vertex: + -- position on screen + -- Z depth (somehow with emission ordering from back to front? + -- UV coordinates -- this could get nasty quickly + -- vertex color + -- solid or textured + +-- Fragment shader: + -- if solid, interpolate vertex color, and straight up draw it + -- if uv mapped, sample the texture and draw it + +-- atlas plans: + -- 512 x 512 atlas + -- 16 rows in it + -- each number from 0 to 9, '.' % and space (the 15th.) 's', ':' + -- the text? + -- overlay textures for bars + -- symbol glyphs + +-- TODO +-- 1. enemy paralyzed is not visible? +-- enemy comms and fusions health? hide the ones which should be hidden! +-- check for invalidness on addbars -- dont +-- better maintenance of bartypes and watch lists +-- feature bars fade out faster -- done +-- CLOAKED UNITSES -- done +-- Healthbars color correction -- done +-- Hide buildbars when at full hp - or convert them to build bars? -- done +-- todo some tex filtering issues on healthbar tops and bottoms :/ -- done +-- TODO: some GAIA shit? -- done +-- TODO: enemy comms and fus and decoy fus should not get healthbars! -- done +-- TODO: allies dont get reload bars? Do Specs see them? -- done (it was f'ed up previously) +-- TODO: correct draw order (after highlightunit) -- done +-- TODO: when reiniting feature bars, also check for resurrect/reclaim status -- done, just dont reinit them on playerchanged, no point! + -- now this is problematic, as the gadget only sends us an event on first reclaim event + -- we must assume that all features + -- feature bars dont actually need a reinit, now do they? +-- TODO: make numbers, glyphs optional? -- done, but untested + +--/luarules benchmark corak armpw 100 10 2000 + +local drawWhenGuiHidden = false + +local healthbartexture = "LuaUI/Images/healtbars_exo4.tga" + +-- a little explanation for 'bartype' +-- 0: default percentage progress bar +-- 1: timer based full textured bar, with time left being read from unitformindex +-- 2: timer based progress bar, with start and end times reading time left from uniformindex, uniformindex + 1 and timeInfo.x +-- 3: default percentage bar with overlayed texture progression +-- 5: The stockpile bar, nasty as hell but whatevs, it + +-- TODO: should be a freaking bitmask instead +-- bit 0: use overlay texture false/true +-- bit 1: show glyph icon +-- bit 2: use percentage style display +-- bit 3: use timeleft style display (2 and 3 mutually exclusive!) +-- bit 4: use integernumber style display (stockpile) +-- bit 5: get progress from nowtime-uniform2 / (uniform3 - uniform2) +-- bit 6: flash bar at 1hz +local bitUseOverlay = 1 +local bitShowGlyph = 2 +local bitPercentage = 4 +local bitTimeLeft = 8 +local bitIntegerNumber = 16 +local bitGetProgress = 32 +local bitFlashBar = 64 +local bitColorCorrect = 128 + +-- unit uniform index map: +-- 0: building +-- 1: NONE , +-- 2: shield/reloadstart/stockpile +-- 3: reloadend? +-- 4: emp damage /paralyze +-- 5: capture + +-- Feature uniform index map: +-- 0: NONE +-- 1: resurrect +-- 2: reclaim + +local barTypeMap = { -- WHERE SHOULD WE STORE THE FUCKING COLORS? + health = { + mincolor = {1.0, 0.0, 0.0, 1.0}, + maxcolor = {0.0, 1.0, 0.0, 1.0}, + --bartype = 0, + bartype = bitPercentage + bitColorCorrect, + hidethreshold = 0.99, + uniformindex = 32, -- if its >20, then its health/maxhealth + uvoffset = 0.0625, -- the X offset of the icon for this bar + }, + shield = { + mincolor = {0.15, 0.4, 0.4, 1.0}, + maxcolor = {0.3, 0.8, 0.8, 1.0}, + --bartype = 3, + bartype = bitShowGlyph + bitUseOverlay + bitPercentage, + hidethreshold = 0.99, + uniformindex = 2, -- if its >20, then its health/maxhealth + uvoffset = 0.3125, -- the X offset of the icon for this bar + }, + capture = { + mincolor = {0.5, 0.25, 0.0, 1.0}, + maxcolor = {1.0, 0.5, 0.0, 1.0}, + --bartype = 3, + bartype = bitShowGlyph + bitUseOverlay + bitPercentage, + hidethreshold = 0.99, + uniformindex = 5, -- if its >20, then its health/maxhealth + uvoffset = 0.1875, -- the X offset of the icon for this bar + }, + stockpile = { + mincolor = {0.1, 0.1, 0.1, 1.0}, + maxcolor = {0.1, 0.1, 0.1, 1.0}, + --bartype = 5, + bartype = bitShowGlyph + bitUseOverlay + bitIntegerNumber, + hidethreshold = 1.99, + uniformindex = 2, -- if its >20, then its health/maxhealth + uvoffset = 0.4375, -- the X offset of the icon for this bar + }, + emp_damage = { + mincolor = {0.4, 0.4, 0.8, 1.0}, + maxcolor = {0.6, 0.6, 1.0, 1.0}, + --bartype = 3, + bartype = bitShowGlyph + bitUseOverlay + bitPercentage, + hidethreshold = 0.99, + uniformindex = 4, -- if its >20, then its health/maxhealth + uvoffset = 0.5625, -- the X offset of the icon for this bar + }, + reload = { + mincolor = {0.03, 0.4, 0.4, 1.0}, + maxcolor = {0.05, 0.6, 0.6, 1.0}, + --bartype = 2, + bartype = bitShowGlyph + bitUseOverlay + bitGetProgress, + hidethreshold = 0.99, + uniformindex = 2, -- and 3! + uvoffset = 0.6875, -- the X offset of the icon for this bar + }, + building = { + mincolor = {1.0, 1.0, 1.0, 1.0}, + maxcolor = {1.0, 1.0, 1.0, 1.0}, + --bartype = 3, + bartype = bitShowGlyph + bitUseOverlay + bitPercentage, + hidethreshold = 0.999, + uniformindex = 0, -- if its >20, then its health/maxhealth + uvoffset = 0.9375, -- the X offset of the icon for this bar + }, + paralyzed = { + mincolor = {0.6, 0.6, 1.0, 1.0}, + maxcolor = {0.6, 0.6, 1.0, 1.0}, + --bartype = 1, + bartype = bitShowGlyph + bitUseOverlay + bitFlashBar + bitTimeLeft, + hidethreshold = 0.99, + uniformindex = 4, -- if its >20, then its health/maxhealth + uvoffset = 0.8125, -- the X offset of the icon for this bar + }, + featurehealth = { + mincolor = {0.25, 0.25, 0.25, 1.0}, + maxcolor = {0.65, 0.65, 0.65, 1.0}, + --bartype = 0, + bartype = bitShowGlyph + bitPercentage, + hidethreshold = 0.99, + uniformindex = 33, -- if its >20, then its health/maxhealth + uvoffset = 0.125, -- the X offset of the icon for this bar + }, + featurereclaim = { + mincolor = {0.00, 1.00, 0.00, 1.0}, + maxcolor = {0.85, 1.00, 0.85, 1.0}, + --bartype = 0, + bartype = bitShowGlyph + bitPercentage, + hidethreshold = 0.99, + uniformindex = 2, -- if its >20, then its health/maxhealth + uvoffset = 0.5, -- the X offset of the icon for this bar + }, + featureresurrect = { + mincolor = {0.75, 0.15, 0.75, 1.0}, + maxcolor = {1.0, 0.2, 1.0, 1.0}, + --bartype = 0, + bartype = bitShowGlyph + bitPercentage, + hidethreshold = 0.99, + uniformindex = 1, -- if its >20, then its health/maxhealth + uvoffset = 0.25, -- the X offset of the icon for this bar + }, +} + +for barname, bt in pairs(barTypeMap) do + local cache = {} + for i=1,20 do cache[i] = 0 end + + --cache[1] = unitDefHeights[unitDefID] + additionalheightaboveunit * effectiveScale -- height + --cache[2] = effectiveScale + --cache[3] = 0.0 -- unused + cache[4] = bt.uvoffset -- glyph uv offset + + cache[5] = bt.bartype -- bartype int + --cache[6] = unitBars[unitID] - 1 -- bar index (how manyeth per unit) + cache[7] = bt.uniformindex -- ssbo location offset (> 20 for health) + + cache[9] = bt.mincolor[1] + cache[10] = bt.mincolor[2] + cache[11] = bt.mincolor[3] + cache[12] = bt.mincolor[4] + + cache[13] = bt.maxcolor[1] + cache[14] = bt.maxcolor[2] + cache[15] = bt.maxcolor[3] + cache[16] = bt.maxcolor[4] + + bt['cache'] = cache +end + + +-------------------------------------------------------------------------------- +-------------------------------------------------------------------------------- + +local spec, fullview = spGetSpectatingState() +local myAllyTeamID = Spring.GetMyAllyTeamID() +local GetUnitWeaponState = Spring.GetUnitWeaponState + +local chobbyInterface + +local unitDefIgnore = {} -- commanders! +local unitDefhasShield = {} -- value is shield max power +local unitDefReactiveArmor = {} -- value is armor health +local unitDefCanStockpile = {} -- 0/1? +local unitDefHeights = {} -- maps unitDefs to height +local unitDefHideDamage = {} +local unitDefPrimaryWeapon = {} -- the index for reloadable weapon on unitdef weapons + +local unitBars = {} -- we need this additional table of {[unitID] = {barhealth, barrez, barreclaim}} +local unitCaptureWatch = {} +local unitShieldWatch = {} -- maps unitID to last shield value +local unitReactiveArmorWatch = {} +local unitEmpDamagedWatch = {} +local unitParalyzedWatch = {} +local unitStockPileWatch = {} +local unitReloadWatch = {} + +local featureDefHeights = {} -- maps FeatureDefs to height +local featureBars = {} -- we need this additional table of {[featureid] = {barhealth, barrez, barreclaim}} + +--local empDecline = 1 / 40 --magic +local minReloadTime = 4 -- weapons reloading slower than this willget bars + +local featureHealthVBO +local featureResurrectVBO +local featureReclaimVBO + +local barScale = 1 -- Option 'healthbarsscale' +local variableBarSizes = true -- Option 'healthbarsvariable' + +--local resurrectableFeaturesFast = {} -- value is this is for keeping an eye on resurrectable features, maybe store resurrect progress here? +--local resurrectableFeaturesSlow = {} -- this is for keeping an eye on resurrectable features, maybe store resurrect progress here? +--local reclaimableFeaturesSlow = {} -- for faster updates of features being reclaimed/rezzed +--local reclaimableFeaturesFast = {} -- for faster updates of features being reclaimed/rezzed + +-------------------------------------------------------------------------------- +-- GL4 Backend stuff: +local healthBarVBO = nil +local healthBarShader = nil + +local LuaShader = gl.LuaShader +local InstanceVBOTable = gl.InstanceVBOTable + +--local uploadAllElements = InstanceVBOTable.uploadAllElements +local pushElementInstance = InstanceVBOTable.pushElementInstance +local popElementInstance = InstanceVBOTable.popElementInstance + +-------------------- configurables ----------------------- +local additionalheightaboveunit = 24 --16? +local featureHealthDistMult = 7 -- how many times closer features have to be for their bars to show +local featureReclaimDistMult = 2 -- how many times closer features have to be for their bars to show +local featureResurrectDistMult = 1 -- how many times closer features have to be for their bars to show +local glphydistmult = 3.5 -- how much closer than BARFADEEND the bar has to be to start drawing numbers/icons. Numbers closer to 1 will make the glyphs be drawn earlier, high numbers will only shows glyphs when zoomed in hard. +local glyphdistmultfeatures = 1.8 -- how much closer than BARFADEEND the bar has to be to start drawing numbers/icons + + +local unitDefSizeMultipliers = {} -- table of unitdefID to a size mult (default 1.0) to override sizing of bars per unitdef +local skipGlyphsNumbers = 0.0 -- 0.0 is draw glyph and number, 1.0 means only numbers, 2.0 means only bars, + +local debugmode = false + +local barHeight = 0.9 +local shaderConfig = { -- these are our shader defines + HEIGHTOFFSET = 3, -- Additional height added to everything + CLIPTOLERANCE = 1.1, -- At 1.0 it wont draw at units just outside of view (may pop in), 1.1 is a good safe amount + MAXVERTICES = 64, -- The max number of vertices we can emit, make sure this is consistent with what you are trying to draw (tris 3, quads 4, corneredrect 8, circle 64 + CLIPTOLERANCE = 1.2, + BARWIDTH = 2.56, + BARHEIGHT = barHeight, + BGBOTTOMCOLOR = "vec4(0.25, 0.25, 0.25, 0.8)", + BGTOPCOLOR = "vec4(0.1, 0.1, 0.1, 0.8)", + BARSCALE = 4.0, + PERCENT_VISIBILITY_MAX = 0.99, + TIMER_VISIBILITY_MIN = 0.0, + BARSTEP = 10, -- pixels to downshift per new bar + BOTTOMDARKENFACTOR = 0.5, + BARFADESTART = 3200, + BARFADEEND = 3800, + ATLASSTEP = 0.0625, + MINALPHA = 0.2, +} +shaderConfig.BARCORNER = 0.06 + (shaderConfig.BARHEIGHT / 9) +shaderConfig.SMALLERCORNER = shaderConfig.BARCORNER * 0.6 + +if debugmode then + shaderConfig.DEBUGSHOW = 1 -- comment this to always show all bars +end + +local vsSrcPath = "LuaUI/Shaders/HealthbarsGL4.vert.glsl" +local gsSrcPath = "LuaUI/Shaders/HealthbarsGL4.geom.glsl" +local fsSrcPath = "LuaUI/Shaders/HealthbarsGL4.frag.glsl" +local fallbackVsSrcPath = "LuaUI/Shaders/HealthbarsGL4_nogs.vert.glsl" +local fallbackFsSrcPath = "LuaUI/Shaders/HealthbarsGL4_nogs.frag.glsl" + +local useGeometryShader = LuaShader.isGeometryShaderSupported + +local unitQuadVBO + +local shaderSourceCache = { + vssrcpath = vsSrcPath, + fssrcpath = fsSrcPath, + gssrcpath = gsSrcPath, + shaderName = "Health Bars Shader GL4", + uniformInt = { + healthbartexture = 0; + }, + uniformFloat = { + --addRadius = 1, + iconDistance = 27, + cameraDistanceMult = 1.0, + cameraDistanceMultGlyph = 4.0, + skipGlyphsNumbers = 0.0, + globalSizeMult = 1.0, + }, + shaderConfig = shaderConfig, + } + +local fallbackShaderSourceCache = { + vssrcpath = fallbackVsSrcPath, + fssrcpath = fallbackFsSrcPath, + shaderName = "Health Bars Shader GL4 (NoGS)", + uniformInt = { + healthbartexture = 0; + }, + uniformFloat = { + iconDistance = 27, + cameraDistanceMult = 1.0, + cameraDistanceMultGlyph = 4.0, + skipGlyphsNumbers = 0.0, + globalSizeMult = 1.0, + }, + shaderConfig = shaderConfig, + } + + +-- Walk through unitdefs for the stuff we need: +for udefID, unitDef in pairs(UnitDefs) do + if unitDef.customParams and unitDef.customParams.nohealthbars then + unitDefIgnore[udefID] = true + end --ignore debug units + + local shieldDefID = unitDef.shieldWeaponDef + local shieldPower = ((shieldDefID) and (WeaponDefs[shieldDefID].shieldPower)) or (-1) + if shieldPower > 1 then unitDefhasShield[udefID] = shieldPower + --spEcho("HAS SHIELD") + end + + local weapons = unitDef.weapons + local reloadTime = unitDef.reloadTime or 0 + local primaryWeapon = 1 + for i = 1, #weapons do + local WeaponDef = WeaponDefs[weapons[i].weaponDef] + if WeaponDef and WeaponDef.reload and WeaponDef.reload > reloadTime then + reloadTime = WeaponDef.reload + primaryWeapon = i + end + end + unitDefHeights[udefID] = unitDef.height + unitDefSizeMultipliers[udefID] = mathMin(1.45, math.max(0.85, (Spring.GetUnitDefDimensions(udefID).radius / 150) + mathMin(0.6, unitDef.power / 4000))) + mathMin(0.6, unitDef.health / 22000) + if unitDef.canStockpile then unitDefCanStockpile[udefID] = unitDef.canStockpile end + if reloadTime and reloadTime > minReloadTime then + if debugmode then spEcho("Unit with watched reload time:", unitDef.name, reloadTime, minReloadTime) end + unitDefPrimaryWeapon[udefID] = primaryWeapon + end + if unitDef.hideDamage == true then + unitDefHideDamage[udefID] = true + end + + if not unitDefhasShield[udefID] and not unitDef.hideDamage then + if unitDef.customParams.reactive_armor_health and unitDef.customParams.reactive_armor_restore then + unitDefReactiveArmor[udefID] = tonumber(unitDef.customParams.reactive_armor_health) + end + end +end + +for fdefID, featureDef in pairs(FeatureDefs) do + --spEcho(featureDef.name, featureDef.height) + featureDefHeights[fdefID] = featureDef.height or 32 +end + + +local function goodbye(reason) + spEcho("Healthbars GL4 widget exiting with reason: "..reason) + widgetHandler:RemoveWidget() +end + + + +local function initializeInstanceVBOTable(myName, usesFeatures) + local newVBOTable + local layout + local unitIDAttribID + if useGeometryShader then + layout = { + {id = 0, name = 'height_timers', size = 4}, + {id = 1, name = 'type_index_ssboloc', size = 4, type = GL.UNSIGNED_INT}, + {id = 2, name = 'startcolor', size = 4}, + {id = 3, name = 'endcolor', size = 4}, + {id = 4, name = 'instData', size = 4, type = GL.UNSIGNED_INT}, + } + unitIDAttribID = 4 + else + layout = { + {id = 2, name = 'height_timers', size = 4}, + {id = 3, name = 'type_index_ssboloc', size = 4, type = GL.UNSIGNED_INT}, + {id = 4, name = 'startcolor', size = 4}, + {id = 5, name = 'endcolor', size = 4}, + {id = 6, name = 'instData', size = 4, type = GL.UNSIGNED_INT}, + } + unitIDAttribID = 6 + end + newVBOTable = InstanceVBOTable.makeInstanceVBOTable( + layout, + 256, -- maxelements + myName, -- name + unitIDAttribID -- unitIDattribID (instData) + ) + if newVBOTable == nil then goodbye("Failed to create " .. myName) end + + if useGeometryShader then + local newVAO = gl.GetVAO() + newVAO:AttachVertexBuffer(newVBOTable.instanceVBO) + newVBOTable.VAO = newVAO + else + newVBOTable.VAO = InstanceVBOTable.makeVAOandAttach(unitQuadVBO, newVBOTable.instanceVBO) + end + if usesFeatures then newVBOTable.featureIDs = true end + return newVBOTable +end + + +local function initGL4() + -- Prefer geometry shader path when it actually compiles. This avoids false + -- negatives from capability detection on some Linux/AMD driver stacks. + healthBarShader = LuaShader.CheckShaderUpdates(shaderSourceCache) + useGeometryShader = (healthBarShader ~= nil) + + if not useGeometryShader then + -- A simple quad used by the non-GS path. + unitQuadVBO = gl.GetVBO(GL.ARRAY_BUFFER, false) + unitQuadVBO:Define(4, { + {id = 0, name = 'quadPos', size = 2}, + }) + unitQuadVBO:Upload({ + 0.0, 0.0, + 1.0, 0.0, + 0.0, 1.0, + 1.0, 1.0, + }) + + healthBarShader = LuaShader.CheckShaderUpdates(fallbackShaderSourceCache) + end + + if not healthBarShader then goodbye("Failed to compile health bars GL4 ") end + + healthBarVBO = initializeInstanceVBOTable("healthBarVBO", false) + + featureHealthVBO = initializeInstanceVBOTable("featureHealthVBO", true) -- we need separate ones for all feature health bars, as they seem to be + featureResurrectVBO = initializeInstanceVBOTable("featureResurrectVBO", true) + featureReclaimVBO = initializeInstanceVBOTable("featureReclaimVBO", true) + + if debugmode then + healthBarVBO.debug = true + end +end + +-------------------------------------------------------------------------------- +-------------------------------------------------------------------------------- + +local function addBarForUnit(unitID, unitDefID, barname, reason) + --Spring.Debug.TraceFullEcho() + if debugmode then Spring.Debug.TraceEcho(unitBars[unitID]) end + --spEcho("Caller1:", tostring()".name), "caller2:", tostring(debug.getinfo(3).name)) + unitDefID = unitDefID or spGetUnitDefID(unitID) + + -- Why? Because adding additional bars can be triggered from outside of unit tracker api + -- like EMP, where we assume that unit is already visible, however + -- debug units are not present in unittracker api! + if (unitDefID == nil) or unitDefIgnore[unitDefID] then return nil end + + local bt = barTypeMap[barname] + --if cnt == 1 then bt = barTypeMap.building end + --if cnt == 2 then bt = barTypeMap.reload end + local instanceID = unitID .. '_' .. barname + --spEcho(instanceID, barname, unitBars[unitID]) + if healthBarVBO.instanceIDtoIndex[instanceID] then + if debugmode then spEcho("Trying to add duplicate bar", unitID, instanceID, barname, reason, unitBars[unitID]) end + return + end -- we already have this bar ! + + if unitDefID == nil or Spring.ValidUnitID(unitID) == false or Spring.GetUnitIsDead(unitID) == true then -- dead or invalid + if debugmode then + Spring.Debug.TraceEcho("Tried to add a bar to dead/invalid/nounitdef unit", unitID, unitdefID, barname) + end + return nil + end + + if unitBars[unitID] == nil then + if debugmode then + spEcho("A unit has no bars yet", UnitDefs[unitDefID].name, spGetUnitPosition(unitID)) + Spring.Debug.TraceFullEcho() + Spring.SendCommands({"pause 1"}) + spEcho("No bars unit, last seen at", unitID) + Spring.MarkerAddPoint(spGetUnitPosition(unitID) ) + end + unitBars[unitID] = 1 + end + + unitBars[unitID] = unitBars[unitID] + 1 + + local effectiveScale = ((variableBarSizes and unitDefSizeMultipliers[unitDefID]) or 1.0) * barScale + + local healthBarTableCache = bt.cache + + healthBarTableCache[1] = unitDefHeights[unitDefID] + additionalheightaboveunit * effectiveScale -- height + healthBarTableCache[2] = effectiveScale + healthBarTableCache[6] = unitBars[unitID] - 1 -- bar index (how manyeth per unit) + + return pushElementInstance( + healthBarVBO, -- push into this Instance VBO Table + healthBarTableCache, + instanceID, -- this is the key inside the VBO Table, should be unique per unit + true, -- update existing element + nil, -- noupload, dont use unless you know what you want to batch push/pop + unitID) -- last one should be featureID! + -- we are returning here, to sign successful adds +end + + +local uniformcache = {0.0} + +local function updateReloadBar(unitID, unitDefID, reason) + if not unitDefPrimaryWeapon[unitDefID] then + return + end + + local reloadFrame = GetUnitWeaponState(unitID, unitDefPrimaryWeapon[unitDefID], 'reloadFrame') + local reloadTime = GetUnitWeaponState(unitID, unitDefPrimaryWeapon[unitDefID], 'reloadTime') + local gf = spGetGameFrame() + + if (reloadFrame == nil or reloadFrame > gf) and unitReloadWatch[unitID] == nil then + addBarForUnit(unitID, unitDefID, "reload", reason) + end + + if (reloadFrame and reloadTime and gl.SetUnitBufferUniforms) then + uniformcache[1] = reloadFrame - 30 * reloadTime + gl.SetUnitBufferUniforms(unitID, uniformcache, 2) + uniformcache[1] = reloadFrame + gl.SetUnitBufferUniforms(unitID, uniformcache, 3) + end +end + +local function removeBarFromUnit(unitID, barname, reason) -- this will bite me in the ass later, im sure, yes it did, we need to just update them :P + local instanceKey = unitID .. "_" .. barname + if healthBarVBO.instanceIDtoIndex[instanceKey] then + if debugmode then Spring.Debug.TraceEcho(reason) end + unitBars[unitID] = unitBars[unitID] - 1 + popElementInstance(healthBarVBO, instanceKey) + end +end + + +local function addBarsForUnit(unitID, unitDefID, unitTeam, unitAllyTeam, reason) -- TODO, actually, we need to check for all of these for stuff entering LOS + + if unitDefID == nil or Spring.ValidUnitID(unitID) == false or Spring.GetUnitIsDead(unitID) == true then + if debugmode then spEcho("Tried to add a bar to a dead or invalid unit", unitID, "at", spGetUnitPosition(unitID), reason) end + return + end + + unitBars[unitID] = unitBars[unitID] or 0 + + -- This is optionally passed, and it only important in one edge case: + -- If a unit is captured and thus immediately become outside of LOS, then the getunitallyteam is still the old ally team according to getUnitAllyTEam, and not the new allyteam. + unitAllyTeam = unitAllyTeam or Spring.GetUnitAllyTeam(unitID) + local health, maxHealth, paralyzeDamage, capture, build = spGetUnitHealth(unitID) + if (fullview or (unitAllyTeam == myAllyTeamID) or (unitDefHideDamage[unitDefID] == nil)) and (unitDefIgnore[unitDefID] == nil ) then + if debugmode and health == nil then + spEcho("Trying to add a healthbar to nil health unit", unitID, unitDefID) + local ux, uy, uz = spGetUnitPosition(unitID) + Spring.MarkerAddPoint(ux, uy, uz, "health") + end + addBarForUnit(unitID, unitDefID, "health", reason) + end + if unitDefhasShield[unitDefID] then + --spEcho("hasshield") + addBarForUnit(unitID, unitDefID, "shield", reason) + unitShieldWatch[unitID] = -1.0 + elseif unitDefReactiveArmor[unitDefID] then + unitReactiveArmorWatch[unitID] = unitDefReactiveArmor[unitDefID] + addBarForUnit(unitID, unitDefID, "shield", reason) + local armorHealth = Spring.GetUnitRulesParam(unitID, "reactiveArmorHealth") + if armorHealth then + uniformcache[1] = armorHealth / unitDefReactiveArmor[unitDefID] + gl.SetUnitBufferUniforms(unitID, uniformcache, 2) + end + end + + updateReloadBar(unitID, unitDefID, reason) + + if health ~= nil then + if build < 1 then + addBarForUnit(unitID, unitDefID, "building", reason) + end + --spEcho(unitID, unitDefID, unitDefCanStockpile[unitDefID]) + if debugmode then + if unitDefCanStockpile[unitDefID] then + spEcho("unitDefCanStockpile", unitAllyTeam, myAllyTeamID, fullview) + end + + end + + if unitDefCanStockpile[unitDefID] and ((unitAllyTeam == myAllyTeamID) or fullview) then + unitStockPileWatch[unitID] = 0.0 + addBarForUnit(unitID, unitDefID, "stockpile", reason) + end + if capture > 0 then + addBarForUnit(unitID, unitDefID, "capture", reason) + uniformcache[1] = capture + gl.SetUnitBufferUniforms(unitID, uniformcache, 5) + unitCaptureWatch[unitID] = capture + end + + if paralyzeDamage > 0 then + --TODO + + if Spring.GetUnitIsStunned(unitID) then + if unitParalyzedWatch[unitID] == nil then -- already paralyzed + unitParalyzedWatch[unitID] = 0.0 + -- if unit was already empd, remove that bar + if unitEmpDamagedWatch[unitID] then + unitEmpDamagedWatch[unitID] = nil + removeBarFromUnit(unitID, 'emp_damage', 'unitEmpDamagedWatch') + end + addBarForUnit(unitID, unitDefID, "paralyzed", reason) + end + else + if unitEmpDamagedWatch[unitID] == nil then + unitEmpDamagedWatch[unitID] = 0.0 + addBarForUnit(unitID, unitDefID, "emp_damage", reason) + end + end + end + end +end + +local function removeBarsFromUnit(unitID, reason) + for barname,v in pairs(barTypeMap) do + removeBarFromUnit(unitID, barname, reason) + end + unitShieldWatch[unitID] = nil + unitReactiveArmorWatch[unitID] = nil + unitCaptureWatch[unitID] = nil + unitEmpDamagedWatch[unitID] = nil + unitParalyzedWatch[unitID] = nil + unitStockPileWatch[unitID] = nil + unitReloadWatch[unitID] = nil + unitBars[unitID] = nil +end + + +local function addBarToFeature(featureID, barname) + if debugmode then Spring.Debug.TraceEcho() end + local featureDefID = Spring.GetFeatureDefID(featureID) + + local bt = barTypeMap[barname] + + local targetVBO = featureHealthVBO + if barname == 'featurereclaim' then targetVBO = featureReclaimVBO end + if barname == 'featureresurrect' then targetVBO = featureResurrectVBO end + + if targetVBO.instanceIDtoIndex[featureID] then return end -- already exists, bail + if featureBars[featureID] == nil then + featureBars[featureID] = 0 + end + featureBars[featureID] = featureBars[featureID] + 1 + + pushElementInstance( + targetVBO, -- push into this Instance VBO Table + {featureDefHeights[featureDefID] + additionalheightaboveunit, -- height + 1.0 * barScale, -- size mult + 0, -- timer end + bt.uvoffset, -- unused float + + bt.bartype, -- bartype int + featureBars[featureID] - 1, -- bar index (how manyeth per unit) + bt.uniformindex, -- ssbo location offset (> 20 for health) + 0, -- unused int + + bt.mincolor[1], bt.mincolor[2], bt.mincolor[3], bt.mincolor[4], + bt.maxcolor[1], bt.maxcolor[2], bt.maxcolor[3], bt.maxcolor[4], + 0, 0, 0, 0}, -- these are just padding zeros for instData, that will get filled in + featureID, -- this is the key inside the VBO Table, should be unique per unit + true, -- update existing element + nil, -- noupload, dont use unless you know what you want to batch push/pop + featureID) -- last one should be featureID! +end + + +local function removeBarFromFeature(featureID, targetVBO) + --spEcho("removeBarFromFeature", featureID, targetVBO.myName) + if not targetVBO.instanceIDtoIndex[featureID] then + return + end + + popElementInstance(targetVBO, featureID) + + local barCount = featureBars[featureID] + if not barCount then + return + end + + barCount = barCount - 1 + if barCount > 0 then + featureBars[featureID] = barCount + else + featureBars[featureID] = nil + end +end + +local function removeBarsFromFeature(featureID) + removeBarFromFeature(featureID, featureHealthVBO) + removeBarFromFeature(featureID, featureReclaimVBO) + removeBarFromFeature(featureID, featureResurrectVBO) +end + + +local function init() + InstanceVBOTable.clearInstanceTable(healthBarVBO) + unitCaptureWatch = {} + unitShieldWatch = {} -- maps unitID to last shield value + unitReactiveArmorWatch = {} + unitEmpDamagedWatch = {} + unitParalyzedWatch = {} + unitStockPileWatch = {} + unitReloadWatch = {} + unitBars = {} + for i, unitID in ipairs(Spring.GetAllUnits()) do -- gets radar blips too! + -- probably shouldnt be adding non-visible units + + if fullview then + addBarsForUnit(unitID, spGetUnitDefID(unitID), spGetUnitTeam(unitID), nil, 'initfullview') + else + local losstate = Spring.GetUnitLosState(unitID, myAllyTeamID) + if losstate.los then + addBarsForUnit(unitID, spGetUnitDefID(unitID), spGetUnitTeam(unitID), nil, 'initlos') + --spEcho(unitID, "IS in los") + else + --spEcho(unitID, "is not in los for ", myAllyTeamID) + end + end + end + +end + +local function initfeaturebars() + InstanceVBOTable.clearInstanceTable(featureHealthVBO) + InstanceVBOTable.clearInstanceTable(featureResurrectVBO) + InstanceVBOTable.clearInstanceTable(featureReclaimVBO) + for i, featureID in ipairs(Spring.GetAllFeatures()) do + local featureDefID = Spring.GetFeatureDefID(featureID) + --local resurrectname = Spring.GetFeatureResurrect(featureID) + --if resurrectname then + -- resurrectableFeatures[featureID] = true + -- if it has resurrect progress, then just straight up just store a bar here for it? + -- or shall we only instantiate bars when needed? probably number 2 is smarter... + --end -- maybe store resurrect progress here? + + if featureDefID then -- dont add features that we cant get the ID of + -- add a health bar for it (dont add one for pre-existing stuff) + widget:FeatureCreated(featureID) + else + + end + end +end + +--12:32 PM] Beherith: widget:PlayerChanged generalizations +--[12:33 PM] Beherith: So, I would like to ask if we have a general guideline or if @Floris knows anything about what circumstances should trigger UI GFX widget reinitialization +--[12:36 PM] Beherith: Here, I assume we can live with a few assumptions: +--1. UI GFX widgets are LOS dependent things, that either +-- A. Should look the same for all players on an ALLYteam +-- B. Could look different for each member of an ALLYTeam +--2. Always render different things for different ALLYteams +--This presents and interesting state for most widgets especially for SPECFULLVIEW +--Obviously, the biggest reason for needing to abstract this is to avoid boilerplate mistakes for most new GL4 widgets, which are --stateful, unlike most previous widgets (most of which collected things they wanted to draw every frame) +--[12:39 PM] Beherith: So I assume widget:PlayerChanged gets called on any legal player change, and should keep track of the following: +--1. spectating state +--2. specfullview state +--3. myAllyTeamID +--4. myTeamID +--[12:40 PM] Beherith: There are 3 real states someone can be in: +--1. player +--2. spectator no fullview +--3. spectator with fullview + +--(excluding godmode /globallos et al) +--[12:40 PM] Beherith: Transitions between any of the above 3 should trigger a full reinit +--[12:41 PM] Beherith: But some internal transitions, for stuff that is draw differently for allies might require additional checks, for spectators who have fullview off? + + +local function FeatureReclaimStartedHealthbars (featureID, step) -- step is negative for reclaim, positive for resurrect + --spEcho("FeatureReclaimStartedHealthbars", featureID) + + --gl.SetFeatureBufferUniforms(featureID, 0.5, 2) -- update GL + if step > 0 then addBarToFeature(featureID, 'featureresurrect') + else addBarToFeature(featureID, 'featurereclaim') end +end + +local function UnitCaptureStartedHealthbars(unitID, step) -- step is negative for reclaim, positive for resurrect + if debugmode then spEcho("UnitCaptureStartedHealthbars", unitID) end + --gl.SetFeatureBufferUniforms(featureID, 0.5, 2) -- update GL + local capture = select(4, spGetUnitHealth(unitID)) + uniformcache[1] = capture + gl.SetUnitBufferUniforms(unitID, uniformcache, 5) + unitCaptureWatch[unitID] = capture + addBarForUnit(unitID, spGetUnitDefID(unitID), 'capture', 'UnitCaptureStartedHealthbars') + +end + +--function widget:UnitDamaged(unitID, unitDefID, unitTeam, damage, paralyzer) +local function UnitParalyzeDamageHealthbars(unitID, unitDefID, damage) + if Spring.GetUnitIsStunned(unitID) then -- DO NOTE THAT: return: nil | bool stunned_or_inbuild, bool stunned, bool inbuild + if unitParalyzedWatch[unitID] == nil then -- already paralyzed + unitParalyzedWatch[unitID] = 0.0 + -- if unit was already empd, remove that bar + if unitEmpDamagedWatch[unitID] then + unitEmpDamagedWatch[unitID] = nil + removeBarFromUnit(unitID, 'emp_damage', 'unitEmpDamagedWatch') + end + addBarForUnit(unitID, unitDefID, "paralyzed", 'unitParalyzedWatch') + end + else + if unitEmpDamagedWatch[unitID] == nil then + unitEmpDamagedWatch[unitID] = 0.0 + addBarForUnit(unitID, unitDefID, "emp_damage", 'unitEmpDamagedWatch') + end + end +end + +local function ProjectileCreatedReloadHB(projectileID, unitID, weaponID, unitDefID) + local unitDefID = spGetUnitDefID(unitID) + + updateReloadBar(unitID, unitDefID, 'ProjectileCreatedReloadHB') +end + +local function debughealthbarsCmd(_, line) + debugmode = not debugmode + spEcho("Debug mode for HealthBars GL4 set to", debugmode) + healthBarVBO.debug = debugmode + return true +end + +function widget:Initialize() + widgetHandler:AddAction("debughealthbars", debughealthbarsCmd, nil, "t") + + if not gl.CreateShader then -- no shader support, so just remove the widget itself, especially for headless + widgetHandler:RemoveWidget() + return + end + WG['healthbars'] = {} + WG['healthbars'].getScale = function() + return barScale + end + WG['healthbars'].setScale = function(value) + barScale = value + init() + initfeaturebars() + end + WG['healthbars'].getHeight = function() + return barHeight + end + WG['healthbars'].setHeight = function(value) + barHeight = value + shaderSourceCache.shaderConfig.BARHEIGHT = barHeight + shaderSourceCache.shaderConfig.BARCORNER = 0.06 + (shaderConfig.BARHEIGHT / 9) + shaderSourceCache.shaderConfig.SMALLERCORNER = shaderConfig.BARCORNER * 0.6 + init() + initfeaturebars() + end + WG['healthbars'].getVariableSizes = function() + return variableBarSizes + end + WG['healthbars'].setVariableSizes = function(value) + variableBarSizes = value + init() + initfeaturebars() + end + WG['healthbars'].getDrawWhenGuiHidden = function() + return drawWhenGuiHidden + end + WG['healthbars'].setDrawWhenGuiHidden = function(value) + drawWhenGuiHidden = value + end + + initGL4() + + -- TODO: dont even bother drawing health bars for features that were present on frame 0 - no point in doing so + -- This is stuff like trees and map features, and scenario features + init() + initfeaturebars() +end + +function widget:Shutdown() + widgetHandler:RemoveAction("debughealthbars", "t") + spEcho("Healthbars GL4 unloaded hooks") +end + +function widget:FeatureReclaimStartedHealthbars(featureID, step) + FeatureReclaimStartedHealthbars(featureID, step) +end + +function widget:UnitCaptureStartedHealthbars(unitID, step) + UnitCaptureStartedHealthbars(unitID, step) +end + +function widget:UnitParalyzeDamageHealthbars(unitID, unitDefID, damage) + UnitParalyzeDamageHealthbars(unitID, unitDefID, damage) +end + +function widget:ProjectileCreatedReloadHB(projectileID, ownerID, weaponID) + ProjectileCreatedReloadHB(projectileID, ownerID, weaponID) +end + +function widget:RecvLuaMsg(msg, playerID) + if msg:sub(1,18) == 'LobbyOverlayActive' then + chobbyInterface = (msg:sub(1,19) == 'LobbyOverlayActive1') + end +end + +function widget:VisibleUnitAdded(unitID, unitDefID, unitTeam) + addBarsForUnit(unitID, unitDefID, unitTeam, nil, 'VisibleUnitAdded') +end + +function widget:VisibleUnitRemoved(unitID) + removeBarsFromUnit(unitID, 'VisibleUnitRemoved') +end + +function widget:CrashingAircraft(unitID, unitDefID, teamID) + removeBarsFromUnit(unitID,'CrashingAircraft') +end + +function widget:VisibleUnitsChanged(extVisibleUnits, extNumVisibleUnits) + unitBars = {} + unitShieldWatch = {} + unitReactiveArmorWatch = {} + unitCaptureWatch = {} + unitEmpDamagedWatch = {} + unitParalyzedWatch = {} + unitStockPileWatch = {} + unitReloadWatch = {} + spec, fullview = spGetSpectatingState() + myAllyTeamID = Spring.GetMyAllyTeamID() + + + InstanceVBOTable.clearInstanceTable(healthBarVBO) -- clear all instances + for unitID, unitDefID in pairs(extVisibleUnits) do + addBarsForUnit(unitID, unitDefID, spGetUnitTeam(unitID), nil, "VisibleUnitsChanged") -- TODO: add them with noUpload = true + end + --uploadAllElements(healthBarVBO) -- upload them all +end + +function widget:PlayerChanged(playerID) + + local currentspec, currentfullview = spGetSpectatingState() + local currentTeamID = Spring.GetMyTeamID() + local currentAllyTeamID = Spring.GetMyAllyTeamID() + local currentPlayerID = Spring.GetMyPlayerID() + local reinit = false + + if debugmode then spEcho("HBGL4 widget:PlayerChanged",'spec', currentspec, 'fullview', currentfullview, 'teamID', currentTeamID, 'allyTeamID', currentAllyTeamID, "playerID", currentPlayerID) end + + -- cases where we need to trigger: + if (currentspec ~= spec) or -- we transition from spec to player, yes this is needed + (currentfullview ~= fullview) or -- we turn on or off fullview + ((currentAllyTeamID ~= myAllyTeamID) and not currentfullview) -- our ALLYteam changes, and we are not in fullview + + then + -- do the actual reinit stuff, but first change my own + reinit = true + if debugmode then spEcho("HBGL4 triggered a playerchanged reinit") end + + end + -- save the state: + spec = currentspec + fullview = currentfullview + myAllyTeamID = currentAllyTeamID + --if reinit then init() end +end + + +function widget:GameFrame(n) + + if debugmode then + InstanceVBOTable.locateInvalidUnits(healthBarVBO) + InstanceVBOTable.locateInvalidUnits(featureHealthVBO) + end + -- Units: + -- check shields and armor + if n % 3 == 0 then + for unitID, oldshieldPower in pairs(unitShieldWatch) do + local shieldOn, shieldPower = Spring.GetUnitShieldState(unitID) + if shieldOn == false then shieldPower = 0.0 end + if oldshieldPower ~= shieldPower then + if shieldPower == nil then + removeBarFromUnit(unitID, "shield", "unitShieldWatch") + else + uniformcache[1] = shieldPower / (unitDefhasShield[spGetUnitDefID(unitID)]) + gl.SetUnitBufferUniforms(unitID, uniformcache, 2) + end + unitShieldWatch[unitID] = shieldPower + end + end + + -- todo: armor should be completely different but idk how to set up a new bar type + for unitID, oldArmorValue in pairs(unitReactiveArmorWatch) do + local newArmorValue = Spring.GetUnitRulesParam(unitID, "reactiveArmorHealth") + if newArmorValue ~= oldArmorValue then + if newArmorValue == nil then + removeBarFromUnit(unitID, "shield", "unitReactiveArmorWatch") + else + if not newArmorValue then + newArmorValue = 0 + end + uniformcache[1] = newArmorValue / unitDefReactiveArmor[spGetUnitDefID(unitID)] + gl.SetUnitBufferUniforms(unitID, uniformcache, 2) + end + unitReactiveArmorWatch[unitID] = newArmorValue + end + end + end + + -- todo paralyzed and EMP doesnt work for enemy units :( + -- check EMP'd units + if (n + 1) % 3 == 0 then + for unitID, oldempvalue in pairs(unitEmpDamagedWatch) do + local health, maxHealth, newparalyzeDamage, capture, build = spGetUnitHealth(unitID) + if newparalyzeDamage and oldempvalue ~= newparalyzeDamage then + if newparalyzeDamage == 0 then + unitEmpDamagedWatch[unitID] = nil + removeBarFromUnit(unitID, "emp_damage",'unitEmpDamagedWatch') + else + uniformcache[1] = newparalyzeDamage/ maxHealth + unitEmpDamagedWatch[unitID] = newparalyzeDamage + gl.SetUnitBufferUniforms(unitID, uniformcache, 4) + end + end + end + end + + -- check Paralyzed units + if (n+2) % 3 == 0 then + for unitID, paralyzetime in pairs(unitParalyzedWatch) do + if Spring.GetUnitIsStunned(unitID) then + local health, maxHealth, paralyzeDamage, capture, build = spGetUnitHealth(unitID) + --uniformcache[1] = math.floor((paralyzeDamage - maxHealth)) / (maxHealth * empDecline)) + if paralyzeDamage then + + -- this returns something like 1.20 which somehow turns into seconds somewhere unsearchable, currently wrong display + -- this needs conditional fixing within an if Spring.GetModOptions().emprework + uniformcache[1] = paralyzeDamage / maxHealth + --spEcho("Paralyze damages", paralyzeDamage, maxHealth) + --spEcho("Paralyze damage cur", (paralyzeDamage / maxHealth)) + + gl.SetUnitBufferUniforms(unitID, uniformcache, 4) + end + else + unitParalyzedWatch[unitID] = nil + removeBarFromUnit(unitID, "paralyzed", 'unitEmpDamagedWatch') + addBarForUnit(unitID, unitDefID, "emp_damage",'unitEmpDamagedWatch') + unitEmpDamagedWatch[unitID] = 1.0 + end + end + end + + -- check capture progress? + if (n % 3) == 2 then + for unitID, captureprogress in pairs(unitCaptureWatch) do + local capture = select(4, spGetUnitHealth(unitID)) + if capture and capture ~= captureprogress then + uniformcache[1] = capture + gl.SetUnitBufferUniforms(unitID, uniformcache, 5) + unitCaptureWatch[unitID] = capture + end + if capture == 0 or capture == nil then + removeBarFromUnit(unitID, 'capture', 'unitCaptureWatch') + unitCaptureWatch[unitID] = nil + end + end + end + + -- check stockpile progress + if (n % 5) == 2 then + for unitID, stockpilebuild in pairs(unitStockPileWatch) do + local numStockpiled, numStockpileQued, stockpileBuild = Spring.GetUnitStockpile(unitID) + if stockpileBuild and stockpileBuild ~= stockpilebuild then + -- we somehow need to forward 3 vars, all 3 of the above. packed into a float, this is nasty + --spEcho("Stockpiling", numStockpiled, numStockpileQued, stockpileBuild) + if numStockpiled == nil then Spring.Debug.TraceFullEcho(nil,nil,nil, 'nostockpile', unitID, spGetUnitPosition(unitID)) end + + uniformcache[1] = numStockpiled + stockpileBuild -- less hacky + --uniformcache[1] = 128*numStockpileQued + numStockpiled + stockpileBuild -- the worlds nastiest hack + unitStockPileWatch[unitID] = stockpileBuild + gl.SetUnitBufferUniforms(unitID, uniformcache, 2) + end + end + end +end + +local rezreclaim = {0.0, 1.0} +function widget:FeatureCreated(featureID) + local featureDefID = Spring.GetFeatureDefID(featureID) + local gameFrame = spGetGameFrame() + -- some map-supplied features dont have a model, in these cases modelpath == "" + if FeatureDefs[featureDefID].name ~= 'geovent' and FeatureDefs[featureDefID].modelpath ~= '' then + --spEcho(FeatureDefs[featureDefID].name) + --featureBars[featureID] = 0 -- this is already done in AddBarToFeature + + local health,maxhealth,rezProgress = Spring.GetFeatureHealth(featureID) + + if gameFrame > 0 then + addBarToFeature(featureID, 'featurehealth') + else + if health ~= maxhealth then addBarToFeature(featureID, 'featurehealth') end + end + + if not fullview then + local featureX, featureY, featureZ = spGetFeaturePosition(featureID) + if featureX and not spIsPosInLos(featureX, featureY, featureZ, myAllyTeamID) then + return + end + end + + if rezProgress > 0 then + addBarToFeature(featureID, 'featureresurrect') + end + + local _, _, _, _, reclaimLeft = Spring.GetFeatureResources(featureID) + + if reclaimLeft < 1.0 then + addBarToFeature(featureID, 'featurereclaim') + end + + if rezProgress > 0 or reclaimLeft < 1 then + -- We have to update the feature uniform buffers in this case, as features can be created with less than max health on the map with FP_featureplacer + rezreclaim[1] = rezProgress -- resurrect progress + rezreclaim[2] = reclaimLeft -- reclaim percent + gl.SetFeatureBufferUniforms(featureID, rezreclaim, 1) -- update GL, at offset of 1 + end + + end +end + +function widget:FeatureDestroyed(featureID) + if debugmode then spEcho("FeatureDestroyed",featureID, featureBars[featureID]) end + removeBarsFromFeature(featureID) + featureBars[featureID] = nil +end + +function widget:DrawScreenEffects() + -- using DrawScreenEffects so healthbars render after deferred lighting, + -- distortion, bloom and tonemapping passes — keeps bar colors uncolored + -- and unaffected by water/heat distortion. The shader still does world->clip + -- via engine cameraViewProj UBO, and depth-test still occludes against terrain. + --spEcho(Engine.versionFull ) + if chobbyInterface then return end + if not drawWhenGuiHidden and Spring.IsGUIHidden() then return end + + if spGetGameFrame() % 90 == 0 then + --spEcho("healthBarVBO",healthBarVBO.usedElements, "featureHealthVBO",featureHealthVBO.usedElements) + end + if healthBarVBO.usedElements > 0 or featureHealthVBO.usedElements > 0 then -- which quite strictly, is impossible anyway + local disticon = Spring.GetConfigInt("UnitIconDistance", 200) * 27.5 -- iconLength = unitIconDist * unitIconDist * 750.0f; + gl.Culling(false) + gl.Blending(GL.SRC_ALPHA, GL.ONE_MINUS_SRC_ALPHA) + gl.DepthTest(true) + gl.DepthMask(true) + gl.Texture(0,healthbartexture) + healthBarShader:Activate() + healthBarShader:SetUniform("iconDistance",disticon) + if not debugmode then healthBarShader:SetUniform("cameraDistanceMult",1.0) end + healthBarShader:SetUniform("cameraDistanceMultGlyph", glphydistmult) + healthBarShader:SetUniform("skipGlyphsNumbers",skipGlyphsNumbers) --0.0 is everything, 1.0 means only numbers, 2.0 means only bars, + if healthBarVBO.usedElements > 0 then + if useGeometryShader then + healthBarVBO.VAO:DrawArrays(GL.POINTS,healthBarVBO.usedElements) + else + healthBarVBO.VAO:DrawArrays(GL.TRIANGLE_STRIP, 4, 0, healthBarVBO.usedElements) + end + end + -- below its the feature bars being drawn: + healthBarShader:SetUniform("cameraDistanceMultGlyph", glyphdistmultfeatures) + if featureHealthVBO.usedElements > 0 then + if not debugmode then healthBarShader:SetUniform("cameraDistanceMult",featureHealthDistMult) end + if useGeometryShader then + featureHealthVBO.VAO:DrawArrays(GL.POINTS,featureHealthVBO.usedElements) + else + featureHealthVBO.VAO:DrawArrays(GL.TRIANGLE_STRIP, 4, 0, featureHealthVBO.usedElements) + end + end + if featureResurrectVBO.usedElements > 0 then + if not debugmode then healthBarShader:SetUniform("cameraDistanceMult",featureResurrectDistMult) end + if useGeometryShader then + featureResurrectVBO.VAO:DrawArrays(GL.POINTS,featureResurrectVBO.usedElements) + else + featureResurrectVBO.VAO:DrawArrays(GL.TRIANGLE_STRIP, 4, 0, featureResurrectVBO.usedElements) + end + end + if featureReclaimVBO.usedElements > 0 then + if not debugmode then healthBarShader:SetUniform("cameraDistanceMult",featureReclaimDistMult) end + if useGeometryShader then + featureReclaimVBO.VAO:DrawArrays(GL.POINTS,featureReclaimVBO.usedElements) + else + featureReclaimVBO.VAO:DrawArrays(GL.TRIANGLE_STRIP, 4, 0, featureReclaimVBO.usedElements) + end + end + + healthBarShader:Deactivate() + gl.Texture(false) + gl.Blending(GL.SRC_ALPHA, GL.ONE_MINUS_SRC_ALPHA) + gl.Culling(false) + gl.DepthTest(false) + gl.DepthMask(false) --"BK OpenGL state resets", reset to default state + end +end + +function widget:GetConfigData(data) + return { + barScale = barScale, + barHeight = barHeight, + variableBarSizes = variableBarSizes, + drawWhenGuiHidden = drawWhenGuiHidden + } +end + +function widget:SetConfigData(data) + barScale = data.barScale or barScale + if data.variableBarSizes ~= nil then + variableBarSizes = data.variableBarSizes + end + if data.drawWhenGuiHidden ~= nil then + drawWhenGuiHidden = data.drawWhenGuiHidden + end + if data.barHeight ~= nil then + barHeight = data.barHeight + shaderSourceCache.shaderConfig.BARHEIGHT = barHeight + shaderSourceCache.shaderConfig.BARCORNER = 0.06 + (shaderConfig.BARHEIGHT / 9) + shaderSourceCache.shaderConfig.SMALLERCORNER = shaderConfig.BARCORNER * 0.6 + end +end + +return widget end)() +local forward=(function()local gadget={} +local gadget = gadget ---@type Gadget + +function gadget:GetInfo() + return { + name = "Healthbars Widget Forwarding", + desc = "Notifies widgets that a feature reclaim or resurrect action has begun, updates GL Uniforms, and also notifies on capture start, emp damage, reload", + author = "Beherith", -- ty Sprung + date = "2021.11.25", + license = "GNU GPL, v2 or later", + layer = -1, + enabled = true + } +end + + +if gadgetHandler:IsSyncedCode() then + + local SendToUnsynced = SendToUnsynced + local spGetGameFrame = Spring.GetGameFrame + local spGetUnitWeaponState = Spring.GetUnitWeaponState + + local forwardedFeatureIDs = {} -- so we only forward the start event once + local forwardedCaptureUnitIDs = {} + local weapondefsreload = {} + local unitreloadframe = {} -- maps unitID to next frame it can shoot its primary weapon, cause lasers retrigger projetileCreated every frame + local minReloadTime = 5 -- in concerto with healthbars widget + + function gadget:AllowFeatureBuildStep(builderID, builderTeam, featureID, featureDefID, step) + -- VERY IMPORTANT: This also gets called on resurrect!, but its very hard to tell if its a reclaim, but we can make the mother of all assumptions: + -- features die at 100% metal value + -- step is negative if 'reclaiming' + -- step is large positive if refilling + -- step is small positive if rezzing + + local gf = spGetGameFrame() + --Spring.Echo("AllowFeatureBuildStep",gf,builderID, builderTeam, featureID, featureDefID, step) + if forwardedFeatureIDs[featureID] == nil or forwardedFeatureIDs[featureID] < gf then + forwardedFeatureIDs[featureID] = gf + SendToUnsynced("featureReclaimFrame", featureID, step) + end + return true + end + + function gadget:AllowUnitCaptureStep(builderID, builderTeam, unitID, unitDefID, part) + if forwardedCaptureUnitIDs[unitID] == nil then + forwardedCaptureUnitIDs[unitID] = true + SendToUnsynced("unitCaptureFrame", unitID, part) + end + return true + end + + function gadget:FeatureDestroyed(featureID, allyTeamID) + forwardedFeatureIDs[featureID] = nil + end + + function gadget:UnitDestroyed(unitID, unitDefID, unitTeam, attackerID, attackerDefID, attackerTeam, weaponDefID) + forwardedCaptureUnitIDs[unitID] = nil + unitreloadframe[unitID] = nil + end + + function gadget:UnitTaken(unitID) + forwardedCaptureUnitIDs[unitID] = nil + end + + function gadget:Initialize() + for udefID, unitDef in pairs(UnitDefs) do + local weapons = unitDef.weapons + local watchweaponID = nil + local longestreloadtime = -1 + local longestreloadindex + for i = 1, #weapons do + local WeaponDefID = weapons[i].weaponDef + local WeaponDef = WeaponDefs[WeaponDefID] + if WeaponDef.reload and WeaponDef.reload >0 and WeaponDef.reload >= longestreloadtime then + longestreloadtime = WeaponDef.reload + watchweaponID = WeaponDefID + longestreloadindex = i + end + end + if watchweaponID and longestreloadtime > minReloadTime then + --Spring.Echo("Unit with watched reload time:", unitDef.name, longestreloadtime, watchweaponID, udefID) + weapondefsreload[watchweaponID] = longestreloadindex + Script.SetWatchProjectile(watchweaponID, true) + end + end + end + + function gadget:ProjectileCreated(projectileID, ownerID, weaponID) -- needs: Script.SetWatchProjectile(weaponDefID, true) + --local unitDef = Spring.GetUnitDefID(ownerID) + --Spring.Echo("gadget:ProjectileCreated(",projectileID, ownerID, weaponID,weapondefsreload[weaponID],unitreloadframe[ownerID], ")") + local weaponIndex = weapondefsreload[weaponID] + + if weaponIndex then + local gf = spGetGameFrame() + local reloadFrame = spGetUnitWeaponState(ownerID, weaponIndex, 'reloadFrame') + + if unitreloadframe[ownerID] == nil or unitreloadframe[ownerID] <= gf then + SendToUnsynced("projetileCreatedReload", projectileID, ownerID, weaponID) + unitreloadframe[ownerID] = reloadFrame + end + end + end + +else + + local glSetFeatureBufferUniforms = gl.SetFeatureBufferUniforms + local GetFeatureResources = Spring.GetFeatureResources + local GetFeaturePosition = Spring.GetFeaturePosition + local IsPosInLos = Spring.IsPosInLos + local rezreclaim = {0.0, 1.0} -- this is just a small table cache, so we dont allocate a new table for every update + local forwardedFeatureIDsResurrect = {} -- so we only forward the start event once + local forwardedFeatureIDsReclaim = {} -- so we only forward the start event once + local myTeamID = Spring.GetMyTeamID() + local myAllyTeamID = Spring.GetMyAllyTeamID() + local _, fullview = Spring.GetSpectatingState() + local IsUnitInLos = Spring.IsUnitInLos + local GetFeatureHealth = Spring.GetFeatureHealth + local headless = false + + function gadget:PlayerChanged(playerID) + myTeamID = Spring.GetMyTeamID() + myAllyTeamID = Spring.GetMyAllyTeamID() + _, fullview = Spring.GetSpectatingState() + end + + function featureReclaimFrame(cmd, featureID, step) + --Spring.Echo("HandleFeatureReclaimStarted", featureID) + if not fullview then + local x, y, z = GetFeaturePosition(featureID) + if x and not IsPosInLos(x, y, z, myAllyTeamID) then + return + end + end + + rezreclaim[1] = select(3, GetFeatureHealth( featureID )) -- resurrect progress + rezreclaim[2] = select(5, GetFeatureResources(featureID)) -- reclaim percent + + --Spring.Echo('rezreclaim', rezreclaim[1], rezreclaim[2]) + + if not headless then glSetFeatureBufferUniforms(featureID, rezreclaim, 1) end -- update GL, at offset of 1 + + if step > 0 and forwardedFeatureIDsResurrect[featureID] == nil and Script.LuaUI("FeatureReclaimStartedHealthbars") then + forwardedFeatureIDsResurrect[featureID] = true + --Spring.Echo("HandleFeatureReclaimStartedHealthbars", featureID, step) + Script.LuaUI.FeatureReclaimStartedHealthbars(featureID, step) + end + + if step < 0 and forwardedFeatureIDsReclaim[featureID] == nil and Script.LuaUI("FeatureReclaimStartedHealthbars") then + forwardedFeatureIDsReclaim[featureID] = true + --Spring.Echo("HandleFeatureReclaimStartedHealthbars", featureID, step) + Script.LuaUI.FeatureReclaimStartedHealthbars(featureID, step) + end + end + + function unitCaptureFrame(cmd, unitID, step) + if not fullview and not IsUnitInLos(unitID, myAllyTeamID) then return end + if Script.LuaUI("UnitCaptureStartedHealthbars") then + --Spring.Echo("UnitCaptureStartedHealthbars", unitID, step) + Script.LuaUI.UnitCaptureStartedHealthbars(unitID, step) + end + end + + function projetileCreatedReload(cmd, projectileID, ownerID, weaponID) + --Spring.Echo("unsynced projetileCreatedReload", projectileID, ownerID, weaponID, fullview, Spring.GetUnitTeam(ownerID)) + if fullview or Spring.GetUnitTeam(ownerID) == myTeamID then + if Script.LuaUI("ProjectileCreatedReloadHB") then + --Spring.Echo("G:ProjectileCreatedReloadHB", projectileID, ownerID, weaponID) + Script.LuaUI.ProjectileCreatedReloadHB(projectileID, ownerID, weaponID) + end + end + end + + function gadget:FeatureDestroyed(featureID, allyTeamID) + forwardedFeatureIDsResurrect[featureID] = nil + forwardedFeatureIDsReclaim[featureID] = nil + end + + function gadget:UnitDamaged(unitID, unitDefID, unitTeam, damage, paralyzer) + --Spring.Echo("gadget:UnitDamaged",unitID, unitDefID, unitTeam, damage, paralyzer) + if paralyzer then + if not fullview and not IsUnitInLos(unitID, myAllyTeamID) then return end + + if damage > 0 then + if Script.LuaUI("UnitParalyzeDamageHealthbars") then + --Spring.Echo("UnitParalyzeDamageHealthbars", unitID, step) + Script.LuaUI.UnitParalyzeDamageHealthbars(unitID, unitDefID, damage) + end + if Script.LuaUI("UnitParalyzeDamageEffect") then + --Spring.Echo("UnitParalyzeDamageHealthbars", unitID, step) + Script.LuaUI.UnitParalyzeDamageEffect(unitID, unitDefID, damage) + end + end + end + end + + function gadget:Initialize() + headless = Spring.GetConfigInt("Headless", 0) > 0 + gadgetHandler:AddSyncAction("featureReclaimFrame", featureReclaimFrame) + gadgetHandler:AddSyncAction("unitCaptureFrame", unitCaptureFrame) + gadgetHandler:AddSyncAction("projetileCreatedReload", projetileCreatedReload) + end + + function gadget:ShutDown() + gadgetHandler:RemoveSyncAction("featureReclaimFrame") + gadgetHandler:RemoveSyncAction("unitCaptureFrame") + gadgetHandler:RemoveSyncAction("projetileCreatedReload") + end +end + +return gadget end)() +local widgetEvents=(function()local gadget={} +local ordinarySpring=Spring +local Spring=setmetatable({GetUnitLosState=function(id,ally,raw)if id==widgetEventUnit and ally==ordinarySpring.GetMyAllyTeamID()and raw==true then return widgetEventLos end;return ordinarySpring.GetUnitLosState(id,ally,raw)end},{__index=ordinarySpring}) +if gadgetHandler:IsSyncedCode() then return end + +local gadget = gadget ---@type Gadget + +function gadget:GetInfo() + return { + name = "Widget Events", + desc = "Tells widgets about events they can know about", + author = "Sprung, Klon, Beherith", + date = "2015-05-27", + license = "PD", + layer = 0, + enabled = true, + } +end + +local spAreTeamsAllied = Spring.AreTeamsAllied +local spGetMyAllyTeamID = Spring.GetMyAllyTeamID +local spGetSpectatingState = Spring.GetSpectatingState +local spGetUnitLosState = Spring.GetUnitLosState + +local myAllyTeamID, myTeamID, spec, specFullView + +function gadget:Initialize() + myTeamID = Spring.GetMyTeamID() + myAllyTeamID = Spring.GetMyAllyTeamID() + spec, specFullView = spGetSpectatingState() +end + +function gadget:PlayerChanged() + myTeamID = Spring.GetMyTeamID() + myAllyTeamID = Spring.GetMyAllyTeamID() + spec, specFullView = spGetSpectatingState() +end + + +--[[ NB: these are proxies, not the actual lua functions currently linked LuaUI-side, + so it is safe to cache them here even if the underlying func changes afterwards ]] +local scriptUnitDestroyed = Script.LuaUI.UnitDestroyed +local scriptUnitDestroyedByTeam = Script.LuaUI.UnitDestroyedByTeam + +function gadget:UnitDestroyed (unitID, unitDefID, unitTeam, attUnitID, attUnitDefID, attTeamID) + local isAllyUnit = spAreTeamsAllied(unitTeam, myTeamID) + --Spring.Echo("Gadget:UnitDest", unitID, Script.LuaUI('UnitDestroyedByTeam') , "isAllyUnit", isAllyUnit, "spec", spec, "specFullView", specFullView) + -- we need to check if any widget uses the callin, otherwise it is not bound and will produce error spam + if Script.LuaUI('UnitDestroyedByTeam') then + if spec then + scriptUnitDestroyedByTeam (unitID, unitDefID, unitTeam, attTeamID) + if not specFullView and not isAllyUnit and (spGetUnitLosState(unitID, myAllyTeamID, true) % 2 == 1) then + scriptUnitDestroyed (unitID, unitDefID, unitTeam) + end + else + local attackerInLos = attUnitID and (spGetUnitLosState(attUnitID, myAllyTeamID, true) % 2 == 1) + if isAllyUnit then + scriptUnitDestroyedByTeam (unitID, unitDefID, unitTeam, attackerInLos and attTeamID or nil) + elseif spGetUnitLosState(unitID, myAllyTeamID, true) % 2 == 1 then + scriptUnitDestroyed (unitID, unitDefID, unitTeam) + scriptUnitDestroyedByTeam (unitID, unitDefID, unitTeam, attackerInLos and attTeamID or nil) + end + end + else + if not isAllyUnit and (not (spec and specFullView) and (spGetUnitLosState(unitID, spGetMyAllyTeamID(), true) % 2 == 1)) then + scriptUnitDestroyed (unitID, unitDefID, unitTeam) + end + end +end + +local scriptUnitTaken = Script.LuaUI.UnitTaken +function gadget:UnitTaken(unitID, unitDefID, oldTeamID, newTeamID) + -- we need to notify my team if a unit transfer between two other teams happens, within my radar or los + local unitwasandisenemy = not (spAreTeamsAllied(oldTeamID, myTeamID) or spAreTeamsAllied(newTeamID, myTeamID)) + local unitinmyradarorlos = (spGetUnitLosState(unitID, myAllyTeamID, true) % 4 > 0) + -- Spring.Echo("gadget:UnitGiven",unitID, unitDefID, oldTeamID, newTeamID, unitwasandisenemy, unitinmyradarorlos) + if unitwasandisenemy and unitinmyradarorlos then + scriptUnitTaken(unitID, unitDefID, oldTeamID, newTeamID) + end +end + +local scriptUnitGiven = Script.LuaUI.UnitGiven +function gadget:UnitGiven(unitID, unitDefID, newTeamID, oldTeamID) + -- we need to notify my team if a unit transfer between two other teams happens, within my radar or los + local unitwasandisenemy = not (spAreTeamsAllied(oldTeamID, myTeamID) or spAreTeamsAllied(newTeamID, myTeamID)) + local unitinmyradarorlos = (spGetUnitLosState(unitID, myAllyTeamID, true) % 4 > 0) + -- Spring.Echo("gadget:UnitGiven",unitID, unitDefID, newTeamID, oldTeamID, unitwasandisenemy, unitinmyradarorlos) + if unitwasandisenemy and unitinmyradarorlos then + scriptUnitGiven(unitID, unitDefID, newTeamID, oldTeamID) + end +end + +local scriptUnitFinished = Script.LuaUI.UnitFinished +function gadget:UnitFinished(unitID, unitDefID, unitTeam) + if spec and specFullView then return end + -- Important: Enemy units finished within LOS do not get the respective widget:UnitFinished calls! + -- Also important: units that are created and finished in the same gameframe (like /give, or created fully built) are not in los yet, so this wont trigger! + local unitisenemy = not spAreTeamsAllied(unitTeam, myTeamID) + local isinlos = spGetUnitLosState(unitID, myAllyTeamID, true) % 2 + --Spring.Echo("gadget:UnitFinished",unitID, unitDefID, unitTeam, unitisenemy, isinlos) + if unitisenemy and (isinlos == 1) then + scriptUnitFinished(unitID, unitDefID, unitTeam) + end +end + +local scriptFeatureCreated = Script.LuaUI.FeatureCreated +function gadget:FeatureCreated(featureID, allyTeam) -- assume that features are always in LOS + local isAllyUnit = (allyTeam == myAllyTeamID) + --Spring.Echo("Gadget:FeatureCreated", featureID, FeatureDefs[Spring.GetFeatureDefID(featureID)].name, Script.LuaUI('FeatureCreated') , "isAllyUnit", isAllyUnit, "spec", spec, "specFullView", specFullView) + -- we need to check if any widget uses the callin, otherwise it is not bound and will produce error spam + if not isAllyUnit and (not (spec and specFullView)) and Script.LuaUI('FeatureCreated') then + --Spring.Echo("gadget:FeatureCreated",featureID, allyTeam) + scriptFeatureCreated(featureID, allyTeam) + end +end + +local scriptFeatureDestroyed = Script.LuaUI.FeatureDestroyed +function gadget:FeatureDestroyed(featureID, allyTeam) + -- assume that features are always in LOS + -- feauture allyTeam is equal to my allyteam when its a gaia feature, that is wierd + -- am i always allied with gaia? + local isAllyUnit = (allyTeam == myAllyTeamID) + --Spring.Echo("Gadget:FeatureDestroyed", featureID, FeatureDefs[Spring.GetFeatureDefID(featureID)].name, Script.LuaUI('FeatureDestroyed') , "isAllyUnit", isAllyUnit, "spec", spec, "specFullView", specFullView, allyTeam, Spring.GetMyTeamID()) + -- we need to check if any widget uses the callin, otherwise it is not bound and will produce error spam + if not isAllyUnit and (not (spec and specFullView)) and Script.LuaUI('FeatureDestroyed') then + --Spring.Echo("gadget:FeatureDestroyed",featureID, allyTeam) + scriptFeatureDestroyed(featureID, allyTeam) + end +end + +return gadget end)() +-- Original call order: tracker updates visibility, then stock healthbar policy. +-- All callback arguments originate in native admitted events, never browser UI. +local barsReady=false +for _,name in ipairs({'VisibleUnitAdded','VisibleUnitRemoved','VisibleUnitsChanged','FeatureReclaimStartedHealthbars','UnitCaptureStartedHealthbars','UnitParalyzeDamageHealthbars','ProjectileCreatedReloadHB'})do + listeners[name]=function(...) + if removed or not barsReady then return end + if name=='VisibleUnitAdded'then originalBuildAdded((...)) + elseif name=='VisibleUnitsChanged'then unitUniforms={};buildProgresses={};for id in pairs((...))do originalBuildAdded(id)end end + local result=bars[name](bars,...) + if name=='VisibleUnitRemoved'then local id=(...);unitUniforms[id]=nil;buildProgresses[id]=nil end + return result + end +end +for _,name in ipairs({'UnitCreated','UnitFinished','UnitDestroyed','UnitTaken','UnitGiven','UnitEnteredLos','UnitLeftLos'})do + _G[name]=function(...) + if name=='UnitFinished'then originalBuildFinished((...))end + tracker[name](tracker,...) + if name=='UnitDestroyed'then local id=(...);unitUniforms[id]=nil;buildProgresses[id]=nil end + end +end +for _,name in ipairs({'UnitDestroyed','UnitTaken','UnitGiven','UnitFinished','FeatureCreated','FeatureDestroyed'})do + listeners[name]=function(...)return _G[name](...)end +end +local widgetEventNames={UnitDestroyed=true,UnitTaken=true,UnitGiven=true,UnitFinished=true,FeatureCreated=true,FeatureDestroyed=true} +function WebbarHealthbarWidgetEvent(name,los,...) + assert(widgetEventNames[name],'Unknown original widget event') + assert(type(los)=='number'and los>=0 and los<=65535 and los%1==0,'Invalid native event LOS') + widgetEventUnit,widgetEventLos=(...),los + local ok,failure=pcall(widgetEvents[name],widgetEvents,...) + widgetEventUnit,widgetEventLos=nil,nil + if not ok then error(failure)end +end +function GameFrame(frame)originalBuildUpdated();tracker:GameFrame(frame);if not removed then bars:GameFrame(frame)end end +function PlayerChanged(player)widgetEvents:PlayerChanged(player);forward:PlayerChanged(player);tracker:PlayerChanged(player);if not removed then bars:PlayerChanged(player)end end +function UnitDamaged(id,definition,team,damage,paralyzer) + local publicDefinition=Spring.GetUnitDefID(id) + if publicDefinition then forward:UnitDamaged(id,publicDefinition,team,damage,paralyzer)end +end +function FeatureCreated(id,...)featureUniforms[id]=nil;if not removed and Spring.GetFeatureDefID(id)then bars:FeatureCreated(id,...)end end +function FeatureDestroyed(id,ally)forward:FeatureDestroyed(id,ally);if not removed then bars:FeatureDestroyed(id)end;featureUniforms[id]=nil end +function WebbarHealthbarSync(name,...) + local action=actions[name];if not action then return false end + -- Native event lists can include Gaia features outside this handle's reads. + -- Reject absent typed reads before the original forwarding body's callbacks. + if name=='featureReclaimFrame'and not Spring.GetFeatureDefID((...))then return false end + if name=='unitCaptureFrame'and not Spring.GetUnitDefID((...))then return false end + if name=='projetileCreatedReload'and not Spring.GetUnitDefID(select(2,...))then return false end + action(name,...);return true +end +function WebbarHealthbarInitialize() + widgetEvents:Initialize();forward:Initialize();tracker:Initialize() + for id in pairs(WG.unittrackerapi.visibleUnits)do originalBuildAdded(id)end + bars:Initialize();barsReady=true;return not removed +end +function WebbarHealthbarState() + local result={frame=Spring.GetGameFrame(),disabled=removed,rows={}} + if removed then return result end + for _,entry in ipairs({{'healthBarVBO',0},{'featureHealthVBO',1},{'featureResurrectVBO',2},{'featureReclaimVBO',3}})do + local buffer=assert(WG.VBOTableRegistry[entry[1]]);assert(buffer.instanceStep==20 and buffer.usedElements<=65536) + for i=1,buffer.usedElements do + local key,id=assert(buffer.indextoInstanceID[i]),nil + if entry[2]==0 then id=tonumber(key:match('^(%d+)_'))else id=key end + assert(type(id)=='number'and id>=0 and id%1==0) + local row={id=id,kind=entry[2],key=key,params={},uniforms={}} + local offset=(i-1)*20;for j=1,16 do row.params[j]=buffer.instanceData[offset+j]end + local data=(entry[2]==0 and unitUniforms or featureUniforms)[id] + for j=1,16 do row.uniforms[j]=data and data[j]or 0 end + local health,maxHealth + if entry[2]==0 then health,maxHealth=Spring.GetUnitHealth(id)else health,maxHealth=Spring.GetFeatureHealth(id)end + if health and maxHealth and maxHealth>0 then row.health={maxHealth,health} + elseif row.params[7]<20 then + -- No health read is published for hidden-damage units. This neutral pair + -- is unused by a non-health bar, whose original shader selects uniforms. + row.health={1,0} + end + if row.health then result.rows[#result.rows+1]=row end + end + end + assert(#result.rows<=65536);return result +end + + +-- Optional original Orb Effects shares the stock Unit Tracker and the actual +-- Healthbars GL4 userDefined[0].z storage. Shader compilation happens in the +-- browser; this private native handle retains only original Lua policy. +local orb,orbReady +if webbarNativeOrbsEnabled == true then + GL.ELEMENT_ARRAY_BUFFER=34963 + gl.DepthTest=function()end;gl.DepthMask=function()end;gl.Culling=function()end + gl.LuaShader.GetEngineUniformBufferDefs=function()return '' end + setmetatable(gl.LuaShader,{__call=function(_,params,name) + assert(name=='orbShader GL4' and type(params.vertex)=='string' and type(params.fragment)=='string') + return {Initialize=function()return true end,Activate=function()end,Deactivate=function()end,SetUniform=function()end} + end}) + orb=(function()local widget={} +-------------------------------------------------------------------------------- +local widget = widget ---@type Widget + +function widget:GetInfo() + return { + name = "Orb Effects GL4", + desc = "Pretty orbs for Fusions, Shields and Junos", + author = "Beherith, Shader by jK", + date = "2024.02.10", + license = "GNU GPL v2", + layer = -1, + enabled = true, + } +end + + +-- Localized Spring API for performance +local spGetGameFrame = Spring.GetGameFrame +local spEcho = Spring.Echo + +local spGetUnitTeam = Spring.GetUnitTeam + + + + +-------------------------------------------------------------------------------- +-- Beherith's notes +-------------------------------------------------------------------------------- +-- TODO: +-- [x] Add health-based brightening +-- [x] Add shield based darkening +-- [ ] Optimize shader +-- [ ] Combine Effects of techniques +-- [x] LightningOrb() TOO EXPENSIVE! + -- do multiple wraps, like 4 instead of 18 goddamn passes! +-- [ ] Ensure SphereVBO indices to triangles are ordered bottom to top! +-- [x] Draw order is incorrect, we are drawing after gadget's shield jitter + +-------------------------------------------------------------------------------- +-- Configuration +-------------------------------------------------------------------------------- +local defaults = { + layer = -35, + life = 600, + light = 2.5, + repeatEffect = true, +} + +local corafusShieldSphere = table.merge(defaults, { + pos = { 0, 60, 0 }, + size = 32, + light = 4, + --colormap1 = { {0.9, 0.9, 1, 0.75},{0.9, 0.9, 1, 1.0},{0.9, 0.9, 1, 1.0},{0.9, 0.9, 1, 0.75} }, + --colormap2 = { {0.2, 0.2, 1, 0.7},{0.2, 0.2, 1, 0.75},{0.2, 0.2, 1, 0.75},{0.2, 0.2, 1, 0.7} }, +}) + +local corafust3ShieldSphere = table.merge(defaults, { + pos = { 0, 120, 0 }, + size = 64, + light = 8, + --colormap1 = { {0.9, 0.9, 1, 0.75},{0.9, 0.9, 1, 1.0},{0.9, 0.9, 1, 1.0},{0.9, 0.9, 1, 0.75} }, + --colormap2 = { {0.2, 0.2, 1, 0.7},{0.2, 0.2, 1, 0.75},{0.2, 0.2, 1, 0.75},{0.2, 0.2, 1, 0.7} }, +}) + +local armafusShieldSphere = table.merge(defaults, { + pos = { 0, 60, 0 }, + size = 28, + light = 4.25, + --colormap1 = { {0.9, 0.9, 1, 0.75},{0.9, 0.9, 1, 1.0},{0.9, 0.9, 1, 1.0},{0.9, 0.9, 1, 0.75} }, + --colormap2 = { {0.2, 0.2, 1, 0.7},{0.2, 0.2, 1, 0.75},{0.2, 0.2, 1, 0.75},{0.2, 0.2, 1, 0.7} }, +}) + +local armafust3ShieldSphere = table.merge(defaults, { + pos = { 0, 120, 0 }, + size = 56, + light = 8.5, + --colormap1 = { {0.9, 0.9, 1, 0.75},{0.9, 0.9, 1, 1.0},{0.9, 0.9, 1, 1.0},{0.9, 0.9, 1, 0.75} }, + --colormap2 = { {0.2, 0.2, 1, 0.7},{0.2, 0.2, 1, 0.75},{0.2, 0.2, 1, 0.75},{0.2, 0.2, 1, 0.7} }, +}) + +local legafusShieldSphere = table.merge(defaults, { + pos = { 0, 60, 0 }, + size = 36, + light = 4.25, + --colormap1 = { {0.9, 0.9, 1, 0.75},{0.9, 0.9, 1, 1.0},{0.9, 0.9, 1, 1.0},{0.9, 0.9, 1, 0.75} }, + --colormap2 = { {0.2, 0.2, 1, 0.7},{0.2, 0.2, 1, 0.75},{0.2, 0.2, 1, 0.75},{0.2, 0.2, 1, 0.7} }, +}) + +local legafust3ShieldSphere = table.merge(defaults, { + pos = { 0, 120, 0 }, + size = 72, + light = 8.5, + --colormap1 = { {0.9, 0.9, 1, 0.75},{0.9, 0.9, 1, 1.0},{0.9, 0.9, 1, 1.0},{0.9, 0.9, 1, 0.75} }, + --colormap2 = { {0.2, 0.2, 1, 0.7},{0.2, 0.2, 1, 0.75},{0.2, 0.2, 1, 0.75},{0.2, 0.2, 1, 0.7} }, +}) + +local corfusShieldSphere = table.merge(defaults, { + pos = { 0, 51, 0 }, + size = 23, + light = 3.25, + --colormap1 = { {0.9, 0.9, 1, 0.75},{0.9, 0.9, 1, 1.0},{0.9, 0.9, 1, 1.0},{0.9, 0.9, 1, 0.75} }, + --colormap2 = { {0.2, 0.6, 0.2, 0.4},{0.2, 0.6, 0.2, 0.45},{0.2, 0.6, 0.2, 0.45},{0.2, 0.6, 0.2, 0.4} }, +}) + +local legfusShieldSphere = table.merge(defaults, { + pos = { 0, 10, 0 }, + size = 23, + light = 3.25, + --colormap1 = { {0.9, 0.9, 1, 0.75},{0.9, 0.9, 1, 1.0},{0.9, 0.9, 1, 1.0},{0.9, 0.9, 1, 0.75} }, + --colormap2 = { {0.2, 0.6, 0.2, 0.4},{0.2, 0.6, 0.2, 0.45},{0.2, 0.6, 0.2, 0.45},{0.2, 0.6, 0.2, 0.4} }, +}) + + +local corgateShieldSphere = table.merge(defaults, { + pos = { 0, 42, 0 }, + size = 11, + colormap1 = { { 0.9, 0.9, 1, 0.75 }, { 0.9, 0.9, 1, 1.0 }, { 0.9, 0.9, 1, 1.0 }, { 0.9, 0.9, 1, 0.75 } }, + colormap2 = { { 0.2, 0.6, 0.2, 0.4 }, { 0.2, 0.6, 0.2, 0.45 }, { 0.2, 0.6, 0.2, 0.45 }, { 0.2, 0.6, 0.2, 0.4 } }, + isShield = true, +}) + +local corgatet3ShieldSphere = table.merge(defaults, { + pos = { 0, 75, -1 }, + size = 18, + colormap1 = { { 0.9, 0.9, 1, 0.75 }, { 0.9, 0.9, 1, 1.0 }, { 0.9, 0.9, 1, 1.0 }, { 0.9, 0.9, 1, 0.75 } }, + colormap2 = { { 0.2, 0.6, 0.2, 0.4 }, { 0.2, 0.6, 0.2, 0.45 }, { 0.2, 0.6, 0.2, 0.45 }, { 0.2, 0.6, 0.2, 0.4 } }, + isShield = true, +}) + +local armjunoShieldSphere = table.merge(defaults, { + pos = { 0, 72, 0 }, + size = 13, + colormap1 = { { 0.9, 0.9, 1, 0.75 }, { 0.9, 0.9, 1, 1.0 }, { 0.9, 0.9, 1, 1.0 }, { 0.9, 0.9, 1, 0.75 } }, + colormap2 = { { 0.8, 0.2, 0.2, 0.4 }, { 0.8, 0.2, 0.2, 0.45 }, { 0.9, 0.2, 0.2, 0.45 }, { 0.9, 0.1, 0.2, 0.4 } }, +}) + +local legjunoShieldSphere = table.merge(defaults, { + pos = { 0, 69, 0 }, + size = 9, + colormap1 = { { 0.9, 0.9, 1, 0.75 }, { 0.9, 0.9, 1, 1.0 }, { 0.9, 0.9, 1, 1.0 }, { 0.9, 0.9, 1, 0.75 } }, + colormap2 = { { 0.8, 0.2, 0.2, 0.4 }, { 0.8, 0.2, 0.2, 0.45 }, { 0.9, 0.2, 0.2, 0.45 }, { 0.9, 0.1, 0.2, 0.4 } }, +}) + +local corjunoShieldSphere = table.merge(defaults, { + pos = { 0, 72, 0 }, + size = 13, + colormap1 = { { 0.9, 0.9, 1, 0.75 }, { 0.9, 0.9, 1, 1.0 }, { 0.9, 0.9, 1, 1.0 }, { 0.9, 0.9, 1, 0.75 } }, + colormap2 = { { 0.8, 0.2, 0.2, 0.4 }, { 0.8, 0.2, 0.2, 0.45 }, { 0.9, 0.2, 0.2, 0.45 }, { 0.9, 0.1, 0.2, 0.4 } }, +}) + +local armgateShieldSphere = table.merge(defaults, { + pos = { 0, 23.5, -5 }, + size = 14.5, + colormap1 = { { 0.9, 0.9, 1, 0.75 }, { 0.9, 0.9, 1, 1.0 }, { 0.9, 0.9, 1, 1.0 }, { 0.9, 0.9, 1, 0.75 } }, + colormap2 = { { 0.2, 0.6, 0.2, 0.4 }, { 0.2, 0.6, 0.2, 0.45 }, { 0.2, 0.6, 0.2, 0.45 }, { 0.2, 0.6, 0.2, 0.4 } }, + isShield = true, +}) + +local armgatet3ShieldSphere = table.merge(defaults, { + pos = { 0, 42, -6 }, + size = 20, + colormap1 = { { 0.9, 0.9, 1, 0.75 }, { 0.9, 0.9, 1, 1.0 }, { 0.9, 0.9, 1, 1.0 }, { 0.9, 0.9, 1, 0.75 } }, + colormap2 = { { 0.2, 0.6, 0.2, 0.4 }, { 0.2, 0.6, 0.2, 0.45 }, { 0.2, 0.6, 0.2, 0.45 }, { 0.2, 0.6, 0.2, 0.4 } }, + isShield = true, +}) +local leggatet3ShieldSphere = table.merge(defaults, { + pos = { 0, 45, 0 }, + size = 18, + colormap1 = { { 0.9, 0.9, 1, 0.75 }, { 0.9, 0.9, 1, 1.0 }, { 0.9, 0.9, 1, 1.0 }, { 0.9, 0.9, 1, 0.75 } }, + colormap2 = { { 0.2, 0.6, 0.2, 0.4 }, { 0.2, 0.6, 0.2, 0.45 }, { 0.2, 0.6, 0.2, 0.45 }, { 0.2, 0.6, 0.2, 0.4 } }, + isShield = true, +}) + +local legdeflectorShieldSphere = table.merge(defaults, { + pos = { 0, 21, 0 }, + size = 12, + colormap1 = { { 0.9, 0.9, 1, 0.75 }, { 0.9, 0.9, 1, 1.0 }, { 0.9, 0.9, 1, 1.0 }, { 0.9, 0.9, 1, 0.75 } }, + colormap2 = { { 0.2, 0.6, 0.2, 0.4 }, { 0.2, 0.6, 0.2, 0.45 }, { 0.2, 0.6, 0.2, 0.45 }, { 0.2, 0.6, 0.2, 0.4 } }, + isShield = true, +}) + +local UnitEffects = { + ["armjuno"] = { + { class = 'ShieldSphere', options = armjunoShieldSphere }, + { class = 'ShieldJitter', options = { life = math.huge, pos = { 0, 72, 0 }, size = 14, precision = 22, repeatEffect = true } }, + }, + ["legjuno"] = { + { class = 'ShieldSphere', options = legjunoShieldSphere }, + { class = 'ShieldJitter', options = { life = math.huge, pos = { 0, 72, 0 }, size = 14, precision = 22, repeatEffect = true } }, + }, + ["corjuno"] = { + { class = 'ShieldSphere', options = corjunoShieldSphere }, + { class = 'ShieldJitter', options = { life = math.huge, pos = { 0, 72, 0 }, size = 14, precision = 22, repeatEffect = true } }, + }, + + --// FUSIONS //-------------------------- + ["corafus"] = { + { class = 'ShieldSphere', options = corafusShieldSphere }, + { class = 'ShieldJitter', options = { layer = -16, life = math.huge, pos = { 0, 60, 0 }, size = 32.5, precision = 22, repeatEffect = true } }, + }, + ["corfus"] = { + { class = 'ShieldSphere', options = corfusShieldSphere }, + { class = 'ShieldJitter', options = { life = math.huge, pos = { 0, 50, 0 }, size = 23.5, precision = 22, repeatEffect = true } }, + }, + ["legfus"] = { + { class = 'ShieldSphere', options = legfusShieldSphere }, + { class = 'ShieldJitter', options = { life = math.huge, pos = { 0, 19, 0 }, size = 23.5, precision = 22, repeatEffect = true } }, + }, + ["armafus"] = { + { class = 'ShieldSphere', options = armafusShieldSphere }, + { class = 'ShieldJitter', options = { layer = -16, life = math.huge, pos = { 0, 60, 0 }, size = 28.5, precision = 22, repeatEffect = true } }, + }, + ["legafus"] = { + { class = 'ShieldSphere', options = legafusShieldSphere }, + { class = 'ShieldJitter', options = { layer = -16, life = math.huge, pos = { 0, 60, 0 }, size = 38.5, precision = 22, repeatEffect = true } }, + }, + ["armafust3"] = { + { class = 'ShieldSphere', options = armafust3ShieldSphere }, + { class = 'ShieldJitter', options = { layer = -16, life = math.huge, pos = { 0, 120, 0 }, size = 57, precision = 22, repeatEffect = true } }, + }, + ["corafust3"] = { + { class = 'ShieldSphere', options = corafust3ShieldSphere }, + { class = 'ShieldJitter', options = { layer = -16, life = math.huge, pos = { 0, 120, 0 }, size = 65, precision = 22, repeatEffect = true } }, + }, + ["legafust3"] = { + { class = 'ShieldSphere', options = legafust3ShieldSphere }, + { class = 'ShieldJitter', options = { layer = -16, life = math.huge, pos = { 0, 120, 0 }, size = 77, precision = 22, repeatEffect = true } }, + }, + ["resourcecheat"] = { + { class = 'ShieldSphere', options = armafusShieldSphere }, + { class = 'ShieldJitter', options = { layer = -16, life = math.huge, pos = { 0, 60, 0 }, size = 28.5, precision = 22, repeatEffect = true } }, + }, + ["corgate"] = { + { class = 'ShieldJitter', options = { delay = 0, life = math.huge, pos = { 0, 42, 0 }, size = 12, precision = 22, repeatEffect = true , isShiedl } }, + { class = 'ShieldSphere', options = corgateShieldSphere }, + --{class='ShieldJitter', options={delay=0,life=math.huge, pos={0,42,0.0}, size=555, precision=0, strength= 0.001, repeatEffect=true}}, + --{class='ShieldJitter',options={life=math.huge, pos={0,42,0}, size=20, precision=2, repeatEffect=true}}, + }, + ["corgatet3"] = { + { class = 'ShieldJitter', options = { delay = 0, life = math.huge, pos = { 0, 75, 0 }, size = 18, precision = 22, repeatEffect = true , isShiedl } }, + { class = 'ShieldSphere', options = corgatet3ShieldSphere }, + --{class='ShieldJitter', options={delay=0,life=math.huge, pos={0,42,0.0}, size=555, precision=0, strength= 0.001, repeatEffect=true}}, + --{class='ShieldJitter',options={life=math.huge, pos={0,42,0}, size=20, precision=2, repeatEffect=true}}, + }, + ["corfgate"] = { + { class = 'ShieldJitter', options = { delay = 0, life = math.huge, pos = { 0, 42, 0 }, size = 12, precision = 22, repeatEffect = true } }, + { class = 'ShieldSphere', options = corgateShieldSphere }, + --{class='ShieldJitter', options={delay=0,life=math.huge, pos={0,42,0.0}, size=555, precision=0, strength= 0.001, repeatEffect=true}}, + --{class='ShieldJitter',options={life=math.huge, pos={0,42,0}, size=20, precision=2, repeatEffect=true}}, + }, + ["armgate"] = { + { class = 'ShieldJitter', options = { delay = 0, life = math.huge, pos = { 0, 20, -5 }, size = 15, precision = 22, repeatEffect = true } }, + { class = 'ShieldSphere', options = armgateShieldSphere }, + --{class='ShieldJitter', options={delay=0,life=math.huge, pos={0,23.5,-5}, size=555, precision=0, strength=0.001, repeatEffect=true}}, + }, + ["armgatet3"] = { + { class = 'ShieldJitter', options = { delay = 0, life = math.huge, pos = { 0, 37, -5 }, size = 21, precision = 22, repeatEffect = true } }, + { class = 'ShieldSphere', options = armgatet3ShieldSphere }, + --{class='ShieldJitter', options={delay=0,life=math.huge, pos={0,23.5,-5}, size=555, precision=0, strength=0.001, repeatEffect=true}}, + }, + ["leggatet3"] = { + { class = 'ShieldJitter', options = { delay = 0, life = math.huge, pos = { 0, 45, 0 }, size = 20, precision = 22, repeatEffect = true } }, + { class = 'ShieldSphere', options = leggatet3ShieldSphere }, + --{class='ShieldJitter', options={delay=0,life=math.huge, pos={0,23.5,-5}, size=555, precision=0, strength=0.001, repeatEffect=true}}, + }, + ["armfgate"] = { + { class = 'ShieldJitter', options = { delay = 0, life = math.huge, pos = { 0, 25, 0 }, size = 15, precision = 22, repeatEffect = true } }, + { class = 'ShieldSphere', options = table.merge(armgateShieldSphere, { pos = { 0, 25, 0 } }) }, + --{class='ShieldJitter', options={delay=0,life=math.huge, pos={0,25,0}, size=555, precision=0, strength= 0.001, repeatEffect=true}}, + }, + ["legdeflector"] = { + { class = 'ShieldJitter', options = { delay = 0, life = math.huge, pos = { 0, 20, -5 }, size = 15, precision = 22, repeatEffect = true } }, + { class = 'ShieldSphere', options = legdeflectorShieldSphere }, + --{class='ShieldJitter', options={delay=0,life=math.huge, pos={0,23.5,-5}, size=555, precision=0, strength=0.001, repeatEffect=true}}, + }, + ["lootboxbronze"] = { + { class = 'ShieldSphere', options = table.merge(corfusShieldSphere, {pos = { 0, 34, 0 }, size = 10} ) }, + { class = 'ShieldJitter', options = { life = math.huge, pos = { 0, 34, 0 }, size = 10.5, precision = 22, repeatEffect = true } }, + }, + ["lootboxsilver"] = { + { class = 'ShieldSphere', options = table.merge(corfusShieldSphere, {pos = { 0, 52, 0 }, size = 15} ) }, + { class = 'ShieldJitter', options = { life = math.huge, pos = { 0, 52, 0 }, size = 15.5, precision = 22, repeatEffect = true } }, + }, + ["lootboxgold"] = { + { class = 'ShieldSphere', options = table.merge(corfusShieldSphere, {pos = { 0, 69, 0 }, size = 20} ) }, + { class = 'ShieldJitter', options = { life = math.huge, pos = { 0, 69, 0 }, size = 20.5, precision = 22, repeatEffect = true } }, + }, + ["lootboxplatinum"] = { + { class = 'ShieldSphere', options = table.merge(corfusShieldSphere, {pos = { 0, 87, 0 }, size = 25} ) }, + { class = 'ShieldJitter', options = { life = math.huge, pos = { 0, 87, 0 }, size = 25.5, precision = 22, repeatEffect = true } }, + }, + +} + +local scavEffects = {} +if UnitDefNames['armcom_scav'] then + for k, effect in pairs(UnitEffects) do + scavEffects[k .. '_scav'] = effect + if scavEffects[k .. '_scav'].options then + if scavEffects[k .. '_scav'].options.color then + scavEffects[k .. '_scav'].options.color = { 0.92, 0.32, 1.0 } + end + if scavEffects[k .. '_scav'].options.colormap then + scavEffects[k .. '_scav'].options.colormap = { { 0.92, 0.32, 1.0 } } + end + if scavEffects[k .. '_scav'].options.colormap1 then + scavEffects[k .. '_scav'].options.colormap1 = { { 0.92, 0.32, 1.0 } } + end + if scavEffects[k .. '_scav'].options.colormap2 then + scavEffects[k .. '_scav'].options.colormap2 = { { 0.92, 0.32, 1.0 } } + end + end + end + for k, effect in pairs(scavEffects) do + UnitEffects[k] = effect + end + scavEffects = nil +end + +local orbUnitDefs = {} + + +for unitname, effect in pairs(UnitEffects) do + if UnitDefNames[unitname] then + for _, effectdef in ipairs(effect) do + if effectdef.class == "ShieldSphere" then + local attr = {} + local opts = effectdef.options + --orbUnitDefs[UnitDefNames[unitname].id] = + attr[1], attr[2], attr[3] = unpack(opts.pos) + attr[4] = opts.size + + attr[5] = 1 -- margin + attr[6] = 0 -- precision + attr[7] = (opts.isShield and 1) or 0 -- isShield + attr[8] = 1 -- technique + + attr[ 9], attr[10], attr[11], attr[12] = unpack((opts.colormap1 and opts.colormap1[1]) or {-1,-1,-1,-1}) + attr[13], attr[14], attr[15], attr[16] = unpack((opts.colormap2 and opts.colormap2[1]) or {-1,-1,-1,-1}) + + attr[17], attr[18], attr[19], attr[20] = 0, 0, 0, 0 -- padding for instData + orbUnitDefs[UnitDefNames[unitname].id] = attr + end + end + end +end + +UnitEffects = nil + +-------------------------------------------------------------------------------- +-- Variables +-------------------------------------------------------------------------------- + +local orbVBO = nil +local orbShader = nil + +local LuaShader = gl.LuaShader +local InstanceVBOTable = gl.InstanceVBOTable + +local popElementInstance = InstanceVBOTable.popElementInstance +local pushElementInstance = InstanceVBOTable.pushElementInstance +local drawInstanceVBO = InstanceVBOTable.drawInstanceVBO + +local vsSrc = +[[ +#version 420 +#extension GL_ARB_uniform_buffer_object : require +#extension GL_ARB_shader_storage_buffer_object : require +#extension GL_ARB_shading_language_420pack: require +#line 10000 + +layout (location = 0) in vec3 position; +layout (location = 1) in vec3 normals; +layout (location = 2) in vec2 uvs; + +layout (location = 3) in vec4 posrad; // time is gameframe spawned :D +layout (location = 4) in vec4 margin_teamID_shield_technique; +layout (location = 5) in vec4 color1; +layout (location = 6) in vec4 color2; +layout (location = 7) in uvec4 instData; // unitID, teamID, ?? + +out DataVS { + vec4 color1_vs; + //flat vec4 color2_vs; + float unitID_vs; + flat float gameFrame_vs; + flat int technique_vs; + float opac_vs; + vec4 modelPos_vs; +}; + +//__ENGINEUNIFORMBUFFERDEFS__ + +struct SUniformsBuffer { + uint composite; // u8 drawFlag; u8 unused1; u16 id; + + uint unused2; + uint unused3; + uint unused4; + + float maxHealth; + float health; + float unused5; + float unused6; + + vec4 drawPos; + vec4 speed; + vec4[4] userDefined; //can't use float[16] because float in arrays occupies 4 * float space +}; + +layout(std140, binding=1) readonly buffer UniformsBuffer { + SUniformsBuffer uni[]; +}; + + +uniform float reflectionPass = 0.0; + +#line 10468 +void main() +{ + if ((uni[instData.y].composite & 0x00000003u) < 1u ) { // not drawn + // Ivand's recommendation is to place vertices outside of NDC space: + gl_Position = vec4(2.0,2.0,2.0,1.0); + return; + } + + vec3 modelWorldPos = uni[instData.y].drawPos.xyz;// + vec3(100,100,100); + unitID_vs = 0.1 + float(uni[instData.y].composite >> 16 ) / 256000.0; + + float modelRot = uni[instData.y].drawPos.w; + mat3 rotY = rotation3dY(modelRot); + + vec4 vertexWorldPos = vec4(1); + vec3 flippedPos = vec3(1,-1,1) * position.xzy; + + + float radius = 0.99 * posrad.w; + float startFrame = margin_teamID_shield_technique.x; + //float lifeScale = clamp(((timeInfo.x + timeInfo.w) - startFrame) / 100.0, 0.001, 1.0); + float lifeScale = 1.0 - exp(-0.10 * ((timeInfo.x + timeInfo.w) - startFrame)); + radius *= lifeScale; + radius += (sin(timeInfo.z)) - 1.0; + + vertexWorldPos.xyz = rotY * ( flippedPos * (radius) + posrad.xyz + vec3(0,0,0) ) + modelWorldPos; + if (reflectionPass < 0.5){ + gl_Position = cameraViewProj * vertexWorldPos; + }else{ + gl_Position = reflectionViewProj * vertexWorldPos; + } + + + + mat3 normalMatrix = mat3( cameraView[0].xyz, cameraView[1].xyz, cameraView[2].xyz); + + vec3 normal = (rotY * normals.xzy); + normal.y *= -1; + vec3 camPos = cameraViewInv[3].xyz; + vec3 camToWorldPos = normalize(cameraViewInv[3].xyz - vertexWorldPos.xyz); + //vec3 vertex = vec3(gl_ModelViewMatrix * gl_Vertex); + color1_vs.rgb = camToWorldPos.xyz; + float angle = dot(normal,camToWorldPos); //*inversesqrt( dot(normal,normal)*dot(position,position) ); //dot(norm(n),norm(v)) + opac_vs = pow( abs( angle ) , 1.0); + //opac_vs = 1.0; + //color1_vs.rgb = vec3(angle); + + vec4 color2_vs; + if (color1.r < 0) { // negative numbers mean teamcolor + vec4 teamcolor = teamColor[int(margin_teamID_shield_technique.y)]; + // ShieldSphereParticle.Default.colormap1 = {{(r*0.45)+0.3, (g*0.45)+0.3, (b*0.45)+0.3, 0.6}} + //ShieldSphereParticle.Default.colormap2 = {{r*0.5, g*0.5, b*0.5, 0.66} } + color1_vs = vec4(teamcolor.rgb, 0.5); + color1_vs.rgb = color1_vs.rgb * 0.45 + 0.3; + color2_vs = vec4(teamcolor.rgb, 0.66); + color2_vs.rgb = color2_vs.rgb * 0.5; + }else{ // base color + color1_vs = color1; + color2_vs = color2; + } + + color1_vs = mix(color1_vs, color2_vs, opac_vs); + + if (margin_teamID_shield_technique.z > 0.5){ + float shieldPower = clamp(uni[instData.y].userDefined[0].z, 0, 1); + color1_vs = mix(vec4(0.8,0.4, 0,1.0),color1_vs, shieldPower); + } + + float relHealth = clamp(uni[instData.y].health/uni[instData.y].maxHealth, 0, 1); + //color1_vs.rgb *= 1.0 + relHealth; + + + modelPos_vs = vec4(position.xzy*posrad.w, 0); + //modelPos_vs.z = fract(modelPos_vs.z * 10); + modelPos_vs.w = relHealth; + gameFrame_vs = timeInfo.z; + + technique_vs = int(floor(margin_teamID_shield_technique.w)); + + // fix issue for amd/linux when drawing to DrawWorldPreParticles + // https://github.com/beyond-all-reason/RecoilEngine/issues/2791 + gl_ClipDistance[0] = 1.0; + gl_ClipDistance[1] = 1.0; + gl_ClipDistance[2] = 1.0; +} +]] + +local fsSrc = +[[ +#version 420 +#extension GL_ARB_uniform_buffer_object : require +#extension GL_ARB_shading_language_420pack: require +#line 20000 +uniform sampler2D noiseMap; +uniform sampler2D mask; + +//__ENGINEUNIFORMBUFFERDEFS__ + +uniform float reflectionPass = 0.0; + +#define DISTORTION 0.01 +in DataVS { + vec4 color1_vs; + float unitID_vs; + flat float gameFrame_vs; + flat int technique_vs; + float opac_vs; + vec4 modelPos_vs; +}; + +out vec4 fragColor; + + const float PI = acos(0.0) * 2.0; + + float hash13(vec3 p3) { + const float HASHSCALE1 = 44.38975; + p3 = fract(p3 * HASHSCALE1); + p3 += dot(p3, p3.yzx + 19.19); + return fract((p3.x + p3.y) * p3.z); + } + + float noise12(vec2 p){ + vec2 ij = floor(p); + vec2 xy = fract(p); + xy = 3.0 * xy * xy - 2.0 * xy * xy * xy; + //xy = 0.5 * (1.0 - cos(PI * xy)); + float a = hash13(vec3(ij + vec2(0.0, 0.0), unitID_vs)); + float b = hash13(vec3(ij + vec2(1.0, 0.0), unitID_vs)); + float c = hash13(vec3(ij + vec2(0.0, 1.0), unitID_vs)); + float d = hash13(vec3(ij + vec2(1.0, 1.0), unitID_vs)); + float x1 = mix(a, b, xy.x); + float x2 = mix(c, d, xy.x); + return mix(x1, x2, xy.y); + } + + float noise13( vec3 P ) { + // https://github.com/BrianSharpe/Wombat/blob/master/Perlin3D.glsl + + // establish our grid cell and unit position + vec3 Pi = floor(P); + vec3 Pf = P - Pi; + vec3 Pf_min1 = Pf - 1.0; + + // clamp the domain + Pi.xyz = Pi.xyz - floor(Pi.xyz * ( 1.0 / 69.0 )) * 69.0; + vec3 Pi_inc1 = step( Pi, vec3( 69.0 - 1.5 ) ) * ( Pi + 1.0 ); + + // calculate the hash + vec4 Pt = vec4( Pi.xy, Pi_inc1.xy ) + vec2( 50.0, 161.0 ).xyxy; + Pt *= Pt; + Pt = Pt.xzxz * Pt.yyww; + const vec3 SOMELARGEFLOATS = vec3( 635.298681, 682.357502, 668.926525 ); + const vec3 ZINC = vec3( 48.500388, 65.294118, 63.934599 ); + vec3 lowz_mod = vec3( 1.0 / ( SOMELARGEFLOATS + Pi.zzz * ZINC ) ); + vec3 highz_mod = vec3( 1.0 / ( SOMELARGEFLOATS + Pi_inc1.zzz * ZINC ) ); + vec4 hashx0 = fract( Pt * lowz_mod.xxxx ); + vec4 hashx1 = fract( Pt * highz_mod.xxxx ); + vec4 hashy0 = fract( Pt * lowz_mod.yyyy ); + vec4 hashy1 = fract( Pt * highz_mod.yyyy ); + vec4 hashz0 = fract( Pt * lowz_mod.zzzz ); + vec4 hashz1 = fract( Pt * highz_mod.zzzz ); + + // calculate the gradients + vec4 grad_x0 = hashx0 - 0.49999; + vec4 grad_y0 = hashy0 - 0.49999; + vec4 grad_z0 = hashz0 - 0.49999; + vec4 grad_x1 = hashx1 - 0.49999; + vec4 grad_y1 = hashy1 - 0.49999; + vec4 grad_z1 = hashz1 - 0.49999; + vec4 grad_results_0 = inversesqrt( grad_x0 * grad_x0 + grad_y0 * grad_y0 + grad_z0 * grad_z0 ) * ( vec2( Pf.x, Pf_min1.x ).xyxy * grad_x0 + vec2( Pf.y, Pf_min1.y ).xxyy * grad_y0 + Pf.zzzz * grad_z0 ); + vec4 grad_results_1 = inversesqrt( grad_x1 * grad_x1 + grad_y1 * grad_y1 + grad_z1 * grad_z1 ) * ( vec2( Pf.x, Pf_min1.x ).xyxy * grad_x1 + vec2( Pf.y, Pf_min1.y ).xxyy * grad_y1 + Pf_min1.zzzz * grad_z1 ); + + // Classic Perlin Interpolation + vec3 blend = Pf * Pf * Pf * (Pf * (Pf * 6.0 - 15.0) + 10.0); + vec4 res0 = mix( grad_results_0, grad_results_1, blend.z ); + vec4 blend2 = vec4( blend.xy, vec2( 1.0 - blend.xy ) ); + float final = dot( res0, blend2.zxzx * blend2.wwyy ); + return ( final * 1.1547005383792515290182975610039 ); // scale things to a strict -1.0->1.0 range *= 1.0/sqrt(0.75) + } + + float Fbm12(vec2 P) { + const int octaves = 4; + const float lacunarity = 1.8; + const float gain = 0.80; + + float sum = 0.0; + float amp = 0.8; + vec2 pp = P; + + int i; + + for(i = 0; i < octaves; ++i) + { + amp *= gain; + sum += amp * noise12(pp); + pp *= lacunarity; + } + return sum; + } + + float Fbm31Magic(vec3 p) { + float v = 0.0; + v += noise13(p * 1.0) * 2.200; + v -= noise13(p * 4.0) * 3.125; + return v; + } + + float Fbm31Electro(vec3 p) { + float v = 0.0; + v += noise13(p * 0.9) * 0.99; + v += noise13(p * 3.99) * 0.49; + v += noise13(p * 8.01) * 0.249; + v += noise13(p * 25.05) * 0.124; + return v; + } + + #define SNORM2NORM(value) (value * 0.5 + 0.5) + #define NORM2SNORM(value) (value * 2.0 - 1.0) + + float orbTime; // per-unit offset time, set in main() before any function calls + #define time orbTime + + vec3 LightningOrb(vec2 vUv, vec3 color) { + vec2 uv = NORM2SNORM(vUv); + + const float strength = 0.01; + const float dx = 0.2; + + float t = 0.0; + + for (int k = -4; k < 14; ++k) { + vec2 thisUV = uv; + thisUV.x -= dx * float(k); + thisUV.y += float(k); + t += abs(strength / ((thisUV.x + Fbm12( thisUV + time )))); + } + + return color * t; + } + +float mirroredRepeat(float x, float repeats) { + x *= repeats; + float i = floor(x); + float f = fract(x); + // If i is odd, mirror the fractional part + if (mod(i, 2.0) == 1.0) { + f = 1.0 - f; + } + return f; +} + +vec3 LightningOrb2(vec2 vUv, vec3 color) { + + // Example: NO fract(), but still repeating: + // vUv.x *= 3.0; + + // Or: mirror repeat for 2 tiles + vUv.x = mirroredRepeat(vUv.x, 2.0); + + // Animated surface distortion - warp UVs with slow turbulent noise + vec2 distortUV = vUv * 3.0 + vec2(time * 0.3, time * 0.17); + vUv.x += Fbm12(distortUV) * 0.04; + vUv.y += Fbm12(distortUV + vec2(7.3, 3.1)) * 0.03; + + // From here on, continue as you did before: + vec2 uv = NORM2SNORM(vUv); + + float violence = (1 - modelPos_vs.w); + const float strength = 0.06 + 0.3 * violence; + const float dx = 0.16; + + float t = 0.1; + for (int k = -4; k < 5; ++k) { + vec2 thisUV = uv; + thisUV.x -= dx * float(k); + thisUV.y += 2.0 * float(k); + vec2 fbmUV = vec2(thisUV.x * 1.0 + time, thisUV.y + 0.3 * time); + + // Your fract()-free or tiled/noise logic remains the same here: + t += abs(strength / (thisUV.x + (3.0 * Fbm12(fbmUV) - 1.9))); + } + + return color * t; +} + + + + vec3 MagicOrb(vec3 noiseVec, vec3 color) { + float t = 0.0; + + for( int i = 1; i < 2; ++i ) { + t = abs(2.0 / ((noiseVec.y + Fbm31Magic( noiseVec + 0.5 * time / float(i)) ) * 75.0)); + t += 1.3 * float(i); + } + return color * t; + } + + vec3 ElectroOrb(vec3 noiseVec, vec3 color) { + float t = 0.0; + + for( int i = 0; i < 5; ++i ) { + noiseVec = noiseVec.zyx; + t = abs(2.0 / (Fbm31Electro(noiseVec + vec3(0.0, time / float(i + 1), 0.0)) * 120.0)); + t += 0.2 * float(i + 1); + } + + return color * t; + } + + // Returns the X coords (around the belly) as [0-1], the Y coords as down-up [0-1] + vec2 RadialCoords(vec3 a_coords) + { + vec3 a_coords_n = normalize(a_coords); + float lon = atan(a_coords_n.z, a_coords_n.x); + float lat = acos(a_coords_n.y); + vec2 sphereCoords = vec2(lon, lat) / PI; + return vec2(sphereCoords.x * 0.5 + 0.5, 1.0 - sphereCoords.y); + } + + vec3 RotAroundY(vec3 p) + { + float ra = -time * 0.5; + mat4 tr = mat4(cos(ra), 0.0, sin(ra), 0.0, + 0.0, 1.0, 0.0, 0.0, + -sin(ra), 0.0, cos(ra), 0.0, + 0.0, 0.0, 0.0, 1.0); + + return (tr * vec4(p, 1.0)).xyz; + } + +void main(void) +{ + // Per-unit time offset so orbs don't animate in sync + float unitPhase = fract(unitID_vs * 1337.7); + orbTime = gameFrame_vs + unitPhase * 120.0; + + fragColor = color1_vs; + + //modelPos_vs contains the sphere's coords. + + if (technique_vs == 1) { // LightningOrb + vec3 noiseVec = modelPos_vs.xyz; + noiseVec = RotAroundY(noiseVec); + vec3 nDir = normalize(noiseVec); + + // Primary projection (poles at top/bottom of sphere) + vec2 vUv = RadialCoords(noiseVec); + vec3 baseColor = fragColor.rgb; + vec3 col = LightningOrb2(vUv, baseColor); + + // Near the poles, blend in a second projection rotated 90° around X + // so its pole singularity is at the equator of the primary projection + float poleFade = abs(nDir.y); + if (poleFade > 0.45) { + vec3 rotatedVec = vec3(noiseVec.x, -noiseVec.z, noiseVec.y); + vec2 vUv2 = RadialCoords(rotatedVec); + vec3 col2 = LightningOrb2(vUv2, baseColor); + float blendWeight = smoothstep(0.45, 0.85, poleFade); + col = mix(col, col2, blendWeight); + } + + // Color variation - bright white on arc peaks, base color in gaps + float arcIntensity = clamp(length(col) / (length(baseColor) + 0.001), 0.0, 3.0) / 3.0; + vec3 hotColor = mix(baseColor, vec3(1.0), 0.35); + col = mix(col, col * hotColor / (baseColor + 0.001), arcIntensity); + + // Rim glow - bright edge halo + float rim = pow(1.0 - opac_vs, 2.5); + col += baseColor * rim * 0.8; + + // Inner core glow - bright volumetric center + float core = pow(opac_vs, 2.0); + col += baseColor * core * 0.6; + + // Pulse / breathing brightness + float pulse = 1.0 + 0.08 * sin(time * 2.3) + 0.05 * sin(time * 5.7); + col *= pulse; + + fragColor.rgba = vec4(col, 1.0) * 1.2; return; + //fragColor.rgb = max(fragColor.rgb, col * col); + //fragColor.rgb = max(fragColor.rgb, col * 2); + } + else if (technique_vs == 2) { // MagicOrb + vec3 noiseVec = modelPos_vs.xyz; + noiseVec = RotAroundY(noiseVec); + vec3 baseColor = fragColor.rgb; + vec3 col = MagicOrb(noiseVec, baseColor); + fragColor.rgb = max(baseColor, col * col); + + float rim = pow(1.0 - opac_vs, 2.5); + fragColor.rgb += baseColor * rim * 0.8; + float core = pow(opac_vs, 2.0); + fragColor.rgb += baseColor * core * 0.6; + + float pulse = 1.0 + 0.08 * sin(time * 2.3) + 0.05 * sin(time * 5.7); + fragColor.rgb *= pulse; + } + else if (technique_vs == 3) { // ElectroOrb + vec3 noiseVec = modelPos_vs.xyz; + noiseVec = RotAroundY(noiseVec); + vec3 baseColor = fragColor.rgb; + vec3 col = ElectroOrb(noiseVec, baseColor); + fragColor.rgb = max(baseColor, col * col); + + float rim = pow(1.0 - opac_vs, 2.5); + fragColor.rgb += baseColor * rim * 0.8; + float core = pow(opac_vs, 2.0); + fragColor.rgb += baseColor * core * 0.6; + + float pulse = 1.0 + 0.08 * sin(time * 2.3) + 0.05 * sin(time * 5.7); + fragColor.rgb *= pulse; + } + + fragColor.a = length(fragColor.rgb); + if (reflectionPass > 0) fragColor.rgba *= 3.0; + //fragColor.rgba = vec4(1.0); + //fragColor.rgb = modelPos_vs.xyz; + //fragColor.rgba = vec4(opac_vs,opac_vs, opac_vs, 1.0); + //fragColor.rgb = color1_vs.rgb; +} +]] + +local function goodbye(reason) + spEcho("Orb GL4 widget exiting with reason: "..reason) + widgetHandler:RemoveWidget() +end + +local function initGL4() + + local engineUniformBufferDefs = LuaShader.GetEngineUniformBufferDefs() + vsSrc = vsSrc:gsub("//__ENGINEUNIFORMBUFFERDEFS__", engineUniformBufferDefs) + fsSrc = fsSrc:gsub("//__ENGINEUNIFORMBUFFERDEFS__", engineUniformBufferDefs) + orbShader = LuaShader( + { + vertex = vsSrc, + fragment = fsSrc, + uniformInt = { + noiseMap = 0, + mask = 1, + }, + uniformFloat = { + reflectionPass = 0.0, + }, + }, + "orbShader GL4" + ) + shaderCompiled = orbShader:Initialize() + if not shaderCompiled then goodbye("Failed to compile orbShader GL4 ") end + local sphereVBO, numVerts, sphereIndexVBO, numIndices = InstanceVBOTable.makeSphereVBO(32,24,1) + --spEcho("SphereVBO has", numVerts, "vertices and ", numIndices,"indices") + local orbVBOLayout = { + {id = 3, name = 'posrad', size = 4}, -- widthlength + {id = 4, name = 'margin_teamID_shield_technique', size = 4}, -- emit dir + {id = 5, name = 'color1', size = 4}, --- color + {id = 6, name = 'color2', size = 4}, --- color + {id = 7, name = 'instData', type = GL.UNSIGNED_INT, size= 4}, + } + orbVBO = InstanceVBOTable.makeInstanceVBOTable(orbVBOLayout,256, "orbVBO", 7) + orbVBO.numVertices = numIndices + orbVBO.vertexVBO = sphereVBO + orbVBO.VAO = InstanceVBOTable.makeVAOandAttach(orbVBO.vertexVBO, orbVBO.instanceVBO) + orbVBO.primitiveType = GL.TRIANGLES + orbVBO.indexVBO = sphereIndexVBO + orbVBO.VAO:AttachIndexBuffer(orbVBO.indexVBO) +end + +-------------------------------------------------------------------------------- +-- Draw Iteration +-------------------------------------------------------------------------------- +local function DrawOrbs(reflectionPass) + if orbVBO.usedElements > 0 then + gl.DepthTest(true) + gl.DepthMask(false) --"BK OpenGL state resets", default is already false, could remove both state changes + --gl.Culling(GL.FRONT) + gl.Culling(false) + orbShader:Activate() + orbShader:SetUniform("reflectionPass", (reflectionPass and 1 ) or 0 ) + drawInstanceVBO(orbVBO) + orbShader:Deactivate() + end +end +-------------------------------------------------------------------------------- +-- Widget Interface +-------------------------------------------------------------------------------- +-- Note that we rely on VisibleUnitRemoved triggering right before VisibleUnitAdded on UnitFinished +local shieldFinishFrames = {} -- unitID to gameframe + +function widget:DrawWorldPreParticles(drawAboveWater, drawBelowWater, drawReflection, drawRefraction) + if next(shieldFinishFrames) then shieldFinishFrames = {} end + -- NOTE: This is called TWICE per draw frame, once before water and once after, even if no water is present. + -- If water is present on the map, then it gets called again between the two for the refraction pass + -- Solution is to draw it only on the first call, and draw reflections from widget:DrawWorldReflection + + if drawAboveWater and not drawReflection and not drawRefraction then + DrawOrbs(false) + end +end + +function widget:DrawWorldReflection() + DrawOrbs(true) +end + +function widget:Initialize() + if not gl.CreateShader then -- no shader support, so just remove the widget itself, especially for headless + widgetHandler:RemoveWidget() + return + end + initGL4() + if WG['unittrackerapi'] and WG['unittrackerapi'].visibleUnits then + widget:VisibleUnitsChanged(WG['unittrackerapi'].visibleUnits, nil) + else + spEcho("Unit Tracker API unavailable, exiting Orb GL4") + widgetHandler:RemoveWidget() + return + end +end + + +function widget:VisibleUnitAdded(unitID, unitDefID, unitTeam, noupload) + --spEcho("widget:VisibleUnitAdded",unitID, unitDefID, unitTeam, noupload,shieldFinishFrames[unitID]) + if unitDefID and orbUnitDefs[unitDefID] then + + unitTeam = unitTeam or spGetUnitTeam(unitID) + + local _, _, _, _, buildProgress = Spring.GetUnitHealth(unitID) + if buildProgress < 1 then return end + + local instanceCache = orbUnitDefs[unitDefID] + instanceCache[5] = shieldFinishFrames[unitID] or 0 + instanceCache[6] = unitTeam + --instanceCache[7] = spGetGameFrame() + shieldFinishFrames[unitID] = nil + + pushElementInstance(orbVBO, + instanceCache, + unitID, --key + true, -- updateExisting + noupload, + unitID -- unitID for uniform buffers + ) + end +end + +function widget:VisibleUnitsChanged(extVisibleUnits, extNumVisibleUnits) + if orbVBO.usedElements > 0 then + InstanceVBOTable.clearInstanceTable(orbVBO) + end + for unitID, unitDefID in pairs(extVisibleUnits) do + widget:VisibleUnitAdded(unitID, unitDefID, nil, true) + end + InstanceVBOTable.uploadAllElements(orbVBO) +end + +function widget:VisibleUnitRemoved(unitID) + shieldFinishFrames[unitID] = spGetGameFrame() + if orbVBO.instanceIDtoIndex[unitID] then + popElementInstance(orbVBO, unitID) + end +end + +function widget:Shutdown() + -- FIXME: clean up after thyself! +end + + return widget end)() + local initialize=WebbarHealthbarInitialize + function WebbarHealthbarInitialize() + if not initialize() then return false end + orb:Initialize();orbReady=true + assert(WG.VBOTableRegistry.orbVBO.instanceStep==20,'Original orb layout changed') + return true + end + for _,name in ipairs({'VisibleUnitAdded','VisibleUnitRemoved','VisibleUnitsChanged'})do + local ordinary=assert(listeners[name]) + listeners[name]=function(...) + if orbReady then orb[name](orb,...)end + return ordinary(...) + end + end +end +function WebbarOrbState() + if not orbReady then return nil end + -- Original draw boundary clears the temporary finish-frame map. Do not + -- approximate it with simulation frames or snapshot arrival times. + orb:DrawWorldPreParticles(true,false,false,false) + local v=assert(WG.VBOTableRegistry.orbVBO) + assert(v.instanceStep==20 and v.usedElements<=65536) + local rows={} + for i=1,v.usedElements do + local id=assert(v.indextoInstanceID[i]);local params={} + for j=1,16 do params[j]=v.instanceData[(i-1)*20+j]end + local uniforms=unitUniforms[id] + rows[#rows+1]={id=id,params=params,shield=uniforms and uniforms[3]or 0} + end + return rows +end + +function WebbarCreateDeferredLightPolicy(graphics) +-- Only graphics storage and calls are adapted. The complete pinned widget, +-- configs and unsynced LOS relays below execute unchanged. Native read APIs +-- must be bound by the caller; no control, filesystem or wider read permission. +assert(type(graphics)=='table'and type(graphics.platform)=='table'and type(graphics.featureSupport)=='table') +assert(type(graphics.dateDay)=='number'and graphics.dateDay%1==0 and graphics.dateDay>=1 and graphics.dateDay<=31) +assert(type(graphics.deferredMap)=='boolean'and type(graphics.deferredModel)=='boolean') +local originalSpring,originalGL=Spring,gl +local Spring=setmetatable({Utilities=setmetatable({},{__index=Spring.Utilities}), + GetConfigString=function(name,default) + if name=='AllowDeferredMapRendering'then return graphics.deferredMap and'1'or'0'end + if name=='AllowDeferredModelRendering'then return graphics.deferredModel and'1'or'0'end + return originalSpring.GetConfigString(name,default) + end},{__index=originalSpring}) +local Platform,Engine=graphics.platform,{FeatureSupport=graphics.featureSupport} +local os={date=function(format)assert(format=='%d','Unexpected original light date query');return string.format('%02d',graphics.dateDay)end} +local includes={} +local VFS={Include=function(path) + local name=string.lower(path) + if name=='mapinfo.lua'then return assert(graphics.mapInfo,'No original map configuration supplied')end + return assert(includes[name],'Unprepared original deferred-light include '..path)() +end} +local removed,ready=false,false +local globals,actions,batches,uniforms={},{},{},{} +local function noop()end +local widgetHandler={AddAction=noop,RemoveAction=noop, + RemoveWidget=function()removed=true;ready=false end, + RegisterGlobal=function(_,name,fn)assert(not globals[name]);globals[name]=fn end, + DeregisterGlobal=function(_,name)globals[name]=nil end} +local ui=setmetatable({},{__call=function(_,name)return globals[name]~=nil end, + __index=function(_,name)return function(...)return assert(globals[name],'Unbound original light callback '..name)(...)end end}) +local Script={LuaUI=ui} +local gadgetHandler={IsSyncedCode=function()return false end, + AddSyncAction=function(_,name,fn)assert(not actions[name]);actions[name]=fn end, + RemoveSyncAction=function(_,name)actions[name]=nil end} +local GL=setmetatable({BACK=1029,SRC_ALPHA=770,ONE=1,ONE_MINUS_SRC_ALPHA=771},{__index=GL}) +local shader={Activate=noop,Deactivate=noop,Delete=noop, + SetUniformFloat=function(_,name,value)uniforms[name]=value end, + SetUniformInt=function(_,name,value)uniforms[name]=value end} +local instanceAPI=setmetatable({},{__index=originalGL.InstanceVBOTable}) +instanceAPI.makeInstanceVBOTable=function(...) + local v=assert(originalGL.InstanceVBOTable.makeInstanceVBOTable(...)) + local draw=v.draw + function v:draw(primitive) + draw(self,primitive) + assert(self.instanceStep==29 and self.usedElements<=65536,'Original deferred-light storage differs') + local batch={name=self.myName,type=assert(uniforms.pointbeamcone),attached=uniforms.attachedtounitID==1,rows={}} + for i=1,self.usedElements do + local row={params={},piece=self.instanceData[(i-1)*29+25]} + if batch.attached then row.unit=assert(self.indextoUnitID[i],'Missing original attached-light owner')end + for j=1,24 do + local value=self.instanceData[(i-1)*29+j] + assert(type(value)=='number'and value==value and math.abs(value) unitEventLights +local unitEventLights = {} +for key, subtables in pairs(unitEventLightsNames) do + unitEventLights[key] = {} + for subKey, lights in pairs(subtables) do + if UnitDefNames[subKey] then + unitEventLights[key][UnitDefNames[subKey].id] = lights + else + unitEventLights[key][subKey] = lights --preserve defaults etc + end + end +end +unitEventLightsNames = nil + + +-- convert unitname -> unitDefID +local unitDefLights = {} +for unitName, lights in pairs(unitLights) do + if UnitDefNames[unitName] then + unitDefLights[UnitDefNames[unitName].id] = lights + end +end +unitLights = nil + +if not (Spring.GetConfigInt("headlights", 1) == 1) then + for unitDefID, lights in pairs(unitDefLights) do + for name, params in pairs(lights) do + if string.find(name, "headlight") or string.find(name, "searchlight") then + unitDefLights[unitDefID][name] = nil + end + end + end +end + +if not (Spring.GetConfigInt("buildlights", 1) == 1) then + for unitDefID, lights in pairs(unitDefLights) do + for name, params in pairs(lights) do + if string.find(name, "buildlight") then + unitDefLights[unitDefID][name] = nil + end + end + end +end + +-- deep copy helper +local function deepcopy(orig) + local orig_type = type(orig) + if orig_type ~= 'table' then + return orig + end + local copy = {} + for k, v in pairs(orig) do + copy[k] = deepcopy(v) + end + return copy +end + +-- add scavenger equivalents with adjusted head/search-light colors +local scavUnitDefLights = {} +for unitDefID, lights in pairs(unitDefLights) do + local baseName = UnitDefs[unitDefID].name + local scavUD = UnitDefNames[baseName .. '_scav'] + if scavUD then + local newLights = {} + for lightName, lightDef in pairs(lights) do + local ld = deepcopy(lightDef) + -- only tweak headlight or searchlight variants + local lname = lightName:lower() + if lname:find('headlight') or lname:find('searchlight') then + ld.lightConfig.r = 0.50 + ld.lightConfig.g = 0.20 + ld.lightConfig.b = 1.1 + ld.lightConfig.a = 1.0 + ld.lightConfig.color2r = 0.58 + ld.lightConfig.color2g = 0.42 + ld.lightConfig.color2b = 1.15 + end + if lname:find('eye') or lname:find('eyes') or lname:find('thrust') or lname:find('engine') or lname:find('lightning') then + ld.lightConfig.r = 0.48 + ld.lightConfig.g = 0.20 + ld.lightConfig.b = 1.1 + --ld.lightConfig.a = 2.5 + ld.lightConfig.color2r = 0.55 + ld.lightConfig.color2g = 0.38 + ld.lightConfig.color2b = 1.2 + end + if lname:find('flash') then + ld.lightConfig.r = 0.48 + ld.lightConfig.g = 0.20 + ld.lightConfig.b = 1.1 + end + newLights[lightName] = ld + end + scavUnitDefLights[scavUD.id] = newLights + end +end + +unitDefLights = table.merge(unitDefLights, scavUnitDefLights) +scavUnitDefLights = nil + + + +-------------------- Feature Lights + +local featureDefLights = { +} + +local WreckBaseLight = { + lightType = 'point', + lightConfig = { posx = 1, posy = -2 , posz = 1, radius = 9, -- underground relative to unit, radius will be overwritten + dirx = 0.003, diry = 0.0035, dirz = 0.003, theta = 0.9, + r = 1.2, g = 0.60, b = 0, a = 0.12, -- start at orange + color2r = 0.6, color2g = 0.08, color2b = -0.5, colortime = 28, -- in 450 frames, transition to dull red + modelfactor = 3.0, specular = -0.25, scattering = 4.6, lensflare = 0, -- no scatterin + lifetime = 300, sustain = 1.1, selfshadowing = 0}, -- remove at 300 frames, sustain is exp alpha fade +} + +for featureDefID, featureDef in pairs(FeatureDefs) do + local name = featureDef.name + if string.sub(name, string.len(name)-4) == "_dead" then + local wreckRng = math.random() * 2 - 1 + local featureSize = math.sqrt((featureDef.xsize or 1) * (featureDef.zsize or 1)) / 2.1 + --Spring.Echo(name, featureDef.xsize , featureDef.zsize) + local featureDefLight = table.copy(WreckBaseLight) + featureDefLight.lightConfig.radius = featureSize * 19 + featureDefLight.lightConfig.colortime = featureDefLight.lightConfig.colortime * featureSize * 1.5 + --featureDefLight.lightConfig.lifetime = featureDefLight.lightConfig.lifetime * featureSize * 0.5 + --featureDefLight.lightConfig.sustain = featureDefLight.lightConfig.sustain / (featureSize * 1.4) + featureDefLight.lightConfig.posx = featureDefLight.lightConfig.posx * (wreckRng * featureSize * 7) + featureDefLight.lightConfig.posz = featureDefLight.lightConfig.posz * (wreckRng * featureSize * 7) + if (featureSize > 3) then --for super large structures/units - lower light posy + featureDefLight.lightConfig.posy = featureDefLight.lightConfig.posy * (featureSize * 4) + end + featureDefLight.lightConfig.dirx = featureDefLight.lightConfig.dirx * (wreckRng * (featureSize / 4) * 2) + featureDefLight.lightConfig.dirz = featureDefLight.lightConfig.dirz * (wreckRng * (featureSize / 4) * 2) + featureDefLights[featureDefID] = {FeatureCreated = featureDefLight} + end +end + + + + +local crystalLightBase = { + lightType = 'point', + lightConfig = { posx = 0, posy = 12, posz = 0, radius = 72, + color2r = 0, color2g = 0, color2b = 0, colortime = 0.1, + r = -1, g = 1, b = 1, a = 0.66, + modelfactor = 1.1, specular = 0.9, scattering = 0.8, lensflare = 0, + lifetime = 0, sustain = 0, selfshadowing = 0}, + } + +local crystalColors = { -- note that the underscores are needed here + [""] = {0.78,0.46,0.94,0.11}, -- same as violet + _violet = {0.8,0.5,0.95,0.33}, + _blue = {0.1,0.2,0.9,0.33}, + _green = {0.1,0.8,0.1,0.15}, + _lime = {0.4,1,0.2,0.15}, + _obsidian = {0.3,0.2,0.2,0.33}, + _quartz = {0.3,0.3,0.5,0.33}, + _orange = {1,0.5,0,0.11}, + _red = {1,0.2,0.2,0.067}, + _teal = {0,1,1,0.15}, + _team = {1,1,1,0.15}, + } + +for colorname, colorvalues in pairs(crystalColors) do + for size = 1,3 do + local crystaldefname = 'pilha_crystal' .. colorname .. tostring(size) + if FeatureDefNames[crystaldefname] then + local crystalLight = table.copy(crystalLightBase) + crystalLight.lightConfig.r = colorvalues[1] + crystalLight.lightConfig.g = colorvalues[2] + crystalLight.lightConfig.b = colorvalues[3] + crystalLight.lightConfig.a = colorvalues[4] + + crystalLight.lightConfig.color2r = colorvalues[1] * 0.6 + crystalLight.lightConfig.color2g = colorvalues[2] * 0.6 + crystalLight.lightConfig.color2b = colorvalues[3] * 0.6 + crystalLight.lightConfig.colortime = 0.002 + 0.01 / size + + + crystalLight.lightConfig.radius = (size + 0.2) * (crystalLight.lightConfig.radius * 0.6) + crystalLight.lightConfig.posy = (size + 1.5) * crystalLight.lightConfig.posy + featureDefLights[FeatureDefNames[crystaldefname].id] = {crystalLight = crystalLight} + end + end +end + +local fraction = 5 +local day = tonumber(os.date("%d")) +if day <= 25 then + fraction = fraction + (25 - day) +end +local xmaslightbase = { + fraction = fraction, + lightType = 'point', + lightConfig = { posx = 0, posy = 0, posz = 0, radius = 5, + color2r = 0, color2g = 0, color2b = 0, colortime = 0.1, + r = 1, g = 1, b = 1, a = 0.12, + modelfactor = 1.1, specular = 0.9, scattering = 4.5, lensflare = 20, + lifetime = 0, sustain = 0, selfshadowing = 0}, +} + + +-- Supreme Isthmus Winter 1.8.2 +-- Ascendancy 2.2 +-- Avalanche 3.4 +-- blindside remake +-- Frozen Ford v2 +-- Glacier pass 1.2 +-- Nuclear Winter BAR 1.4 +-- The cold place BAR v 1.1 +-- White Fire Remake 1.3 +-- Ice Scream v2.5.1 +-- add colorful xmas lights to a percentage of certain snowy trees +if Spring.Utilities.Gametype.GetCurrentHolidays()["xmas"] then --and os.date("%d") <= "26" + local snowy_tree_keys = {allpinesb_ad0 = 60, __tree_fir_tall_3 = 60, __tree_fir_ = 60} + local xmasColors = { + [1] = {234,13,13}, -- red + [2] = {251,11,36}, -- orange + [3] = {251,242,26}, -- yellow + [4] = {36, 208, 36}, -- green + [5] = {10,83, 222}, -- blue + } + + for featureDefID , featureDef in pairs(FeatureDefs) do + local featureName = featureDef.name + -- Check if its a snowy tree: + -- estimate its height/ radius via model extrema + -- spawn lights in a cone shape around it + for key, count in pairs(snowy_tree_keys) do + if string.find(featureName, key, nil, true) then + --Spring.Echo("Found snowy tree: " .. featureName, key) + + featureDefLights[featureDefID] = {} + local maxy = featureDef.model.maxy + local maxx = featureDef.model.maxx + local maxz = featureDef.model.maxz + + for i= 1, count do + local xmaslight = table.copy(xmaslightbase) + + local y = maxy * (math.random() * 0.8 + 0.1) + local rely = 1.0 - y / maxy + + local x = rely * maxx * (math.random() - 0.5) * 1.5 + local z = rely * maxz * (math.random() - 0.5) * 1.5 + --Spring.Echo(maxx, maxy, maxz, x,y,z) + xmaslight.lightConfig.posy = y + xmaslight.lightConfig.posx = x + xmaslight.lightConfig.posz = z + + local color = math.ceil(math.random() * 4) + + xmaslight.lightConfig.r = xmasColors[color][1] / 255 + xmaslight.lightConfig.g = xmasColors[color][2] / 255 + xmaslight.lightConfig.b = xmasColors[color][3] / 255 + + xmaslight.lightConfig.color2r = xmasColors[color+1][1] /255 + xmaslight.lightConfig.color2g = xmasColors[color+1][2] /255 + xmaslight.lightConfig.color2b = xmasColors[color+1][3] /255 + + + --[[ + + xmaslight.lightConfig.r = math.random() > 0.5 and 1 or 0 + xmaslight.lightConfig.g = math.random()> 0.5 and 1 or 0 + xmaslight.lightConfig.b = math.random()> 0.5 and 1 or 0 + + xmaslight.lightConfig.color2r = math.random() > 0.5 and 1 or 0 + xmaslight.lightConfig.color2g = math.random()> 0.5 and 1 or 0 + xmaslight.lightConfig.color2b = math.random()> 0.5 and 1 or 0 + ]]-- + + xmaslight.lightConfig.colortime = 0.005 + math.random()* 0.005 + + featureDefLights[featureDefID]['xmaslight' .. tostring(i)] = xmaslight + + end + break + end + end + end +end + +local allLights = {unitEventLights = unitEventLights, unitDefLights = unitDefLights, featureDefLights = featureDefLights} + +----------------- Debugging code to do the reverse dump --------------- +--[[ +local lightParamKeyOrder = { posx = 1, posy = 2, posz = 3, radius = 4, + r = 9, g = 10, b = 11, a = 12, + color2r = 5, color2g = 6, color2b = 7, colortime = 8, -- point lights only, colortime in seconds for unit-attached + dirx = 5, diry = 6, dirz = 7, theta = 8, -- cone lights only, specify direction and half-angle in radians + pos2x = 5, pos2y = 6, pos2z = 7, -- beam lights only, specifies the endpoint of the beam + modelfactor = 13, specular = 14, scattering = 15, lensflare = 16, + lifetime = 18, sustain = 19, selfshadowing = 20 +} + +for typename, typetable in pairs(allLights) do + Spring.Echo(typename) + for lightunitclass, classinfo in pairs(typetable) do + if type(lightunitclass) == type(1) then + Spring.Echo(UnitDefs[lightunitclass].name) + else + Spring.Echo(lightunitclass) + end + for lightname, lightinfo in pairs(classinfo) do + Spring.Echo(lightname) + local lightParamTable = lightinfo.lightParamTable + Spring.Echo(string.format(" lightConfig = { posx = %f, posy = %f, posz = %f, radius = %f,", lightinfo.lightParamTable[1], lightParamTable[2],lightParamTable[3],lightParamTable[4] )) + if lightinfo.lightType == 'point' then + Spring.Echo(string.format(" color2r = %f, color2g = %f, color2b = %f, colortime = %f,", lightinfo.lightParamTable[5], lightParamTable[6],lightParamTable[7],lightParamTable[8] )) + + elseif lightinfo.lightType == 'beam' then + Spring.Echo(string.format(" pos2x = %f, pos2y = %f, pos2z = %f,", lightinfo.lightParamTable[5], lightParamTable[6],lightParamTable[7])) + elseif lightinfo.lightType == 'cone' then + Spring.Echo(string.format(" dirx = %f, diry = %f, dirz = %f, theta = %f,", lightinfo.lightParamTable[5], lightParamTable[6],lightParamTable[7],lightParamTable[8] )) + + end + Spring.Echo(string.format(" r = %f, g = %f, b = %f, a = %f,", lightinfo.lightParamTable[9], lightParamTable[10],lightParamTable[11],lightParamTable[12] )) + Spring.Echo(string.format(" modelfactor = %f, specular = %f, scattering = %f, lensflare = %f,", lightinfo.lightParamTable[13], lightParamTable[14],lightParamTable[15],lightParamTable[16] )) + Spring.Echo(string.format(" lifetime = %f, sustain = %f, selfshadowing = %f},", lightinfo.lightParamTable[18], lightParamTable[19],lightParamTable[20])) + + end + end +end +]]-- + +-- Icexuick Check-list + + +return allLights + + + +end + includes["luaui/configs/deferredlightsgl4weaponsconfig.lua"]=function() +-- This configures all the lights weapon effects, including: + -- Projectile attached lights + -- Muzzle flashes + -- Explosion lights + -- Pieceprojectiles (gibs on death) lights +-- note that weapondef customparams need to be moved out of unitdefs, for ease of configability. + -- customparams= { + -- expl_light_skip = bool , -- no explosion on projectile death + -- expl_light_color = {rgba} , -- color of the explosion light at peak? + -- expl_light_opacity = a, -- alpha or power of the light + -- expl_light_mult = ,-- fuck if i know? + -- expl_light_radius = , -- radius + -- expl_light_radius_mult = , -- why? + -- expl_light_life = , life of the expl light? +-- concept is: + -- Make a few base classes of lights + -- auto-assign the majority + -- offer overrideability +-- note that Y offset will be very different for points and for beams! +-- (c) Beherith (mysterme@gmail.com) + +local exampleLight = { + lightType = 'point', -- or cone or beam + pieceName = nil, -- optional + yOffset = 10, -- optional, gives extra Y height + fraction = 3, -- optional, only every nth projectile gets the effect (randomly) + lightConfig = { + posx = 0, posy = 0, posz = 0, radius = 0, + r = 1, g = 1, b = 1, a = 1, + color2r = 1, color2g = 1, color2b = 1, colortime = 15, -- point lights only, colortime in seconds for unit-attached + dirx = 0, diry = 0, dirz = 1, theta = 0.5, -- cone lights only, specify direction and half-angle in radians + pos2x = 100, pos2y = 100, pos2z = 100, -- beam lights only, specifies the endpoint of the beam + modelfactor = 1, specular = 1, scattering = 1, lensflare = 1, + lifetime = 0, sustain = 1, selfshadowing = 0, + }, +} + + +-- Local Variables + +-------------------------------------------------------------------------------- +-- Config + +-- Config order is: +-- Auto-assign a lightclass to each weaponDefID +-- Override on a per-weaponDefID basis, and copy table before overriding + +--------------------------------General Base Light Classes for further useage -------- +local BaseClasses = { + LaserProjectile = { + lightType = 'beam', -- or cone or beam + lightConfig = { + posx = 0, posy = 10, posz = 0, radius = 100, + r = 1, g = 1, b = 1, a = 0.75, + color2r = 0.2, color2g = 0.2, color2b = 0.2, colortime = 1.6, + pos2x = 100, pos2y = 1000, pos2z = 100, -- beam lights only, specifies the endpoint of the beam + modelfactor = 1, specular = 0.5, scattering = 2.5, lensflare = 1, + lifetime = 15, sustain = 1.5, selfshadowing = 0, + }, + }, + + GreenLaserProjectile = { + lightType = 'beam', -- or cone or beam + lightConfig = { + posx = 0, posy = 10, posz = 0, radius = 100, + r = 1, g = 1, b = 1, a = 1.0, + color2r = 0.2, color2g = 0.2, color2b = 0.2, colortime = 9, + pos2x = 100, pos2y = 1000, pos2z = 100, -- beam lights only, specifies the endpoint of the beam + modelfactor = 0.3, specular = 0.4, scattering = 2.0, lensflare = 1, + lifetime = 20, sustain = 2, selfshadowing = 0, + }, + }, + + BlueLaserProjectile = { + lightType = 'beam', -- or cone or beam + lightConfig = { + posx = 0, posy = 10, posz = 0, radius = 100, + r = 1, g = 1, b = 1, a = 0.75, + color2r = 0.2, color2g = 0.2, color2b = 0.2, colortime = 1.6, + pos2x = 100, pos2y = 1000, pos2z = 100, -- beam lights only, specifies the endpoint of the beam + modelfactor = 1, specular = 0.5, scattering = 1.5, lensflare = 1, + lifetime = 15, sustain = 1.5, selfshadowing = 0, + }, + }, + + CannonProjectile = { + lightType = 'point', -- or cone or beam + lightConfig = { + posx = 0, posy = 10, posz = 0, radius = 125, + r = 1, g = 0.8, b = 0.45, a = 0.11, + --color2r = 0.5, color2g = 0.4, color2b = 0.23, colortime = 1.5, -- point lights only, colortime in seconds for unit-attached + modelfactor = 0.5, specular = 0.6, scattering = 0.5, lensflare = 0, + lifetime = 0, sustain = 0, selfshadowing = 0, + }, + }, + + LRPCProjectile = { + lightType = 'point', -- or cone or beam + lightConfig = { + posx = 0, posy = 0, posz = 0, radius = 150, + --pos2x = 100, pos2y = 100, pos2z = 100, + --dirx = 1, diry = 0, dirz = 1, theta = 0.4, + r = 1.2, g = 0.80, b = 0.3, a = 0.2, + color2r = 0.9, color2g = 0.45, color2b = 0.15, colortime = 60, -- point lights only, colortime in seconds for unit-attached + modelfactor = 0.1, specular = -0.2, scattering = 0.6, lensflare = 2, + lifetime = 0, sustain = 0, selfshadowing = 0, + }, + }, + + + MissileProjectile = { + lightType = 'point', -- or cone or beam + lightConfig = { + posx = 0, posy = 0, posz = 0, radius = 150, + r = 1, g = 0.7, b = 0.2, a = 0.15, + color2r = 0.6, color2g = 0.4, color2b = 0.10, colortime = 1.6, -- point lights only, colortime in seconds for unit-attached + modelfactor = 0.3, specular = 0.1, scattering = 0.6, lensflare = 8, + lifetime = 0, sustain = 0, selfshadowing = 0, + }, + }, + + MissileProjectileEMP = { + lightType = 'point', -- or cone or beam + lightConfig = { + posx = 0, posy = 0, posz = 0, radius = 150, + r = 1, g = 1, b = 2, a = 0.7, + color2r = 0.2, color2g = 0.2, color2b = 0.5, colortime = 8, -- point lights only, colortime in seconds for unit-attached + modelfactor = 0.3, specular = 0.1, scattering = 0.5, lensflare = 8, + lifetime = 0, sustain = 0, selfshadowing = 3, + }, + }, + + LaserAimProjectile = { + lightType = 'cone', -- or cone or beam + lightConfig = { + posx = 0, posy = 0, posz = 0, radius = 500, + r = 5, g = 0, b = 0, a = 1, + dirx = 1, diry = 0, dirz = 1, theta = 0.02, -- cone lights only, specify direction and half-angle in radians + modelfactor = 10, specular = 0.5, scattering = 1, lensflare = 1, + lifetime = 0, sustain = 1, selfshadowing = 0, + }, + }, + + TorpedoProjectile = { + lightType = 'cone', -- or cone or beam + delayUntilSubmerged = true, + delayWaterline = 2, + delayFrames = 8, + lightConfig = { + posx = 0, posy = 0, posz = 0, radius = 77, + r = 1.15, g = 0.32, b = 0.03, a = 1, + dirx = 1, diry = 0, dirz = 1, theta = 0.15, -- cone lights only, specify direction and half-angle in radians + modelfactor = 1, specular = 0, scattering = 1, lensflare = 1, + lifetime = 0, sustain = 1, selfshadowing = 4, + }, + }, + + FlameProjectile = { + lightType = 'point', -- or cone or beam + fraction = 3, -- only spawn every nth light + lightConfig = { + posx = 0, posy = 15, posz = 0, radius = 25, + r = 0.2, g = 0.12, b = 0.05, a = 0.2, + color2r = 1.0, color2g = 0.45, color2b = 0.22, colortime = 33, -- point lights only, colortime in seconds for unit-attached + modelfactor = -0.2, specular = -0.3, scattering = 0.05, lensflare = 0, + lifetime = 33, sustain = 10, selfshadowing = 0, + }, + }, + + Explosion = { -- spawned on explosions + lightType = 'point', -- or cone or beam + yOffset = 0, -- Y offsets are only ever used for explosions! + lightConfig = { + posx = 0, posy = 0, posz = 0, radius = 240, + dirx = 0, diry = 10, dirz = 0, theta = 0.93, -- Give explosions a bit of a vertical bounce component + r = 2, g = 2, b = 2, a = 0.6, + color2r = 0.7, color2g = 0.55, color2b = 0.28, colortime = 0.1, -- point lights only, colortime in seconds for unit-attached + modelfactor = 0.15, specular = 0.15, scattering = 0.4, lensflare = 1, + lifetime = 12, sustain = 3, selfshadowing = 4, + }, + }, + ExplosionXL = { -- spawned on explosions + lightType = 'point', -- or cone or beam + yOffset = 0, -- Y offsets are only ever used for explosions! + lightConfig = { + posx = 0, posy = 0, posz = 0, radius = 240, + dirx = 0, diry = 5, dirz = 0, theta = 0.93, -- Give explosions a bit of a vertical bounce component + r = 2, g = 2, b = 2, a = 0.6, + color2r = 0.7, color2g = 0.55, color2b = 0.28, colortime = 0.1, -- point lights only, colortime in seconds for unit-attached + modelfactor = 0.15, specular = 0.15, scattering = 0.4, lensflare = 1, + lifetime = 12, sustain = 3, selfshadowing = 4, + }, + }, + + ExplosionEMP = { -- spawned on explosions + lightType = 'point', -- or cone or beam + yOffset = 12, -- Y offsets are only ever used for explosions! + lightConfig = { + posx = 0, posy = 0, posz = 0, radius = 140, + --dirx = 0, diry = 0.018, dirz = 0, theta = 0.93, + dirx = 0, diry = 0.2, dirz = 0, theta = 0.93, + r = 2, g = 2, b = 4, a = 1.2, + color2r = 0.3, color2g = 0.3, color2b = 0.6, colortime = 1.5, -- point lights only, colortime in seconds for unit-attached + modelfactor = 0.3, specular = -0.5, scattering = 0.5, lensflare = 0, + lifetime = 90, sustain = 50, selfshadowing = 2, + }, + }, + + MuzzleFlash = { -- spawned on projectilecreated + lightType = 'point', -- or cone or beam + lightConfig = { + posx = 0, posy = 0, posz = 0, radius = 150, + r = 2, g = 2, b = 2, a = 0.7, + color2r = 0.75, color2g = 0.72, color2b = 0.6, colortime = 0, -- point lights only, colortime in seconds for unit-attached + modelfactor = 0.8, specular = 0.5, scattering = 0.6, lensflare = 8, + lifetime = 6, sustain = 0.0035, selfshadowing = 4, + }, + }, + + MuzzleFlashCone = { -- not used yet - no idea + lightType = 'cone', -- or cone or beam + lightConfig = { + posx = 0, posy = 0, posz = 0, radius = 150, + r = 2, g = 2, b = 2, a = 0.7, + dirx = 1, diry = 0, dirz = 1, theta = 0.15, + color2r = 0.75, color2g = 0.72, color2b = 0.6, colortime = 0, -- point lights only, colortime in seconds for unit-attached + modelfactor = 0.8, specular = 0.5, scattering = 0.6, lensflare = 8, + lifetime = 6, sustain = 0.0035, selfshadowing = 0, + }, + }, +} + + +local SizeRadius = { + Pico = 26, + Nano = 34, + Micro = 44, + Tiniest = 56, + Tiny = 72, + Smallest = 90, + Smaller = 115, + Small = 140, + Smallish = 165, + SmallMedium = 190, + Medium = 220, + Mediumer = 260, + MediumLarge = 300, + Large = 400, + Larger = 500, + Largest = 650, + Mega = 800, + MegaXL = 1000, + MegaXXL = 1500, + Giga = 2000, + Tera = 3500, + Planetary = 5000, +} +local ColorSets = { -- TODO add advanced dual-color sets! + Red = {r = 1, g = 0, b = 0}, + Green = {r = 0, g = 1, b = 0}, + Blue = {r = 0, g = 0, b = 1}, + Purple = {r = 0.7, g = 0.3, b = 1}, + Yellow = {r = 1, g = 1, b = 0}, + White = {r = 1, g = 1, b = 1}, + Plasma = {r = 1, g = 0.8, b = 0.45}, + HeatRay = {r = 0.88, g = 0.65, b = 0.10}, + Emg = {r = 0.42, g = 0.32, b = 0.07}, + Fire = {r = 0.8, g = 0.3, b = 0.05}, + Warm = {r = 0.7, g = 0.7, b = 0.1}, + Cold = {r = 0.5, g = 0.75, b = 1.0}, + Emp = {r = 0.5, g = 0.5, b = 1.0}, + Team = {r = -1, g = -1, b = -1}, +} + +local globalDamageMult = Spring.GetModOptions().multiplier_weapondamage or 1 + +local function GetClosestSizeClass(desiredsize) + local delta = math.huge + local best = nil + for classname, size in pairs(SizeRadius) do + if math.abs(size-desiredsize) < delta then + delta = math.abs(size-desiredsize) + best = classname + end + end + return best, SizeRadius[best] +end + +local Lifetimes = {Fast = 5, Quick = 10, Moderate = 30, Long = 90, Glacial = 270} + +local lightClasses = {} + +local function deepcopy(orig) + local orig_type = type(orig) + local copy + if orig_type == 'table' then + copy = {} + for orig_key, orig_value in next, orig, nil do + copy[deepcopy(orig_key)] = deepcopy(orig_value) + end + --setmetatable(copy, deepcopy(getmetatable(orig))) + else -- number, string, boolean, etc + copy = orig + end + return copy +end +local usedclasses = 0 +local function GetLightClass(baseClassname, colorkey, sizekey, additionaloverrides) + local lightClassKey = baseClassname .. (colorkey or "") .. (sizekey or "") + if additionaloverrides and type(additionaloverrides) == 'table' then + for k,v in pairs(additionaloverrides) do + lightClassKey = lightClassKey .. "_" .. tostring(k) .. "=" .. tostring(v) + end + end + + if lightClasses[lightClassKey] then + return lightClasses[lightClassKey] + else + lightClasses[lightClassKey] = deepcopy(BaseClasses[baseClassname]) + lightClasses[lightClassKey].lightClassName = lightClassKey + usedclasses = usedclasses + 1 + local lightConfig = lightClasses[lightClassKey].lightConfig + if sizekey then + lightConfig.radius = SizeRadius[sizekey] + end + if colorkey then + lightConfig.r = ColorSets[colorkey].r + lightConfig.g = ColorSets[colorkey].g + lightConfig.b = ColorSets[colorkey].b + if lightClasses[lightClassKey].lightType == 'point' then + lightConfig.color2r = ColorSets[colorkey].color2r or lightConfig.color2r + lightConfig.color2g = ColorSets[colorkey].color2g or lightConfig.color2g + lightConfig.color2b = ColorSets[colorkey].color2b or lightConfig.color2b + lightConfig.colortime = ColorSets[colorkey].colortime or lightConfig.colortime + end + end + if additionaloverrides then + for k,v in pairs(additionaloverrides) do + lightConfig[k] = v + end + end + end + return lightClasses[lightClassKey] +end + +-------------------------------------------------------------------------------- + +local gibLight = { + lightType = 'point', -- or cone or beam + pieceName = nil, -- optional + lightConfig = { + posx = 0, posy = 0, posz = 0, radius = 36, + r = 1, g = 0.9, b = 0.5, a = 0.08, + color2r = 0.9, color2g = 0.75, color2b = 0.25, colortime = 0.3, -- point lights only, colortime in seconds for unit-attache + modelfactor = 0.4, specular = 0.5, scattering = 0.5, lensflare = 0, + lifetime = 300, sustain = 3, selfshadowing = 0 + }, +} + +-------------------------------------------------------------------------------- + +local muzzleFlashLights = {} +local explosionLights = {} +local projectileDefLights = { + ['default'] = { + lightType = 'point', + lightConfig = { posx = 0, posy = 16, posz = 0, radius = 420, + color2r = 1, color2g = 1, color2b = 1, colortime = 15, + r = -1, g = 1, b = 1, a = 1, + modelfactor = 0.2, specular = 1, scattering = 1, lensflare = 1, + lifetime = 50, sustain = 20, selfshadowing = 0}, + } +} + +----------------------------------- + +local function AssignLightsToAllWeapons() + for weaponID=0, #WeaponDefs do + local weaponDef = WeaponDefs[weaponID] + local damage = 100 + for cat=0, #weaponDef.damages do + if Game.armorTypes[cat] and Game.armorTypes[cat] == 'default' then + damage = weaponDef.damages[cat] + break + end + end + + -- correct damage multiplier modoption to more sane value + damage = (damage / globalDamageMult) + ((damage * (globalDamageMult-1))*0.25) + + local radius = ((weaponDef.damageAreaOfEffect*2) + (weaponDef.damageAreaOfEffect * weaponDef.edgeEffectiveness * 1.35)) + local orgMult = math.clamp(damage/1600, 0.1, 0.6) + (radius/2800) + local life = 8 + (5*(radius/2000)+(orgMult * 5)) + radius = ((orgMult * 75) + (radius * 2.4)) * 0.33 + + local r, g, b = 1, 0.8, 0.45 + local weaponVisuals = weaponDef.visuals + if weaponVisuals ~= nil and weaponVisuals.colorR ~= nil then + r = weaponVisuals.colorR + g = weaponVisuals.colorG + b = weaponVisuals.colorB + end + local muzzleFlash = true + local explosionLight = true + local sizeclass = GetClosestSizeClass(radius) + local t = {} + local aa = string.find(weaponDef.cegTag, 'aa') + if aa then + r, g, b = 1, 0.5, 0.6 + t.color2r, t.color2g, t.color2b = 1, 0.5, 0.6 + end + if weaponDef.paralyzer then + r, g, b = 0.5, 0.5, 1 + t.color2r, t.color2g, t.color2b = 0.25, 0.25, 1 + end + local scavenger = string.find(weaponDef.name, '_scav') + if scavenger then + r, g, b = 0.3, 0.1, 0.7 + t.color2r, t.color2g, t.color2b = 0.3, 0.1, 0.7 + end + t.r, t.g, t.b = r, g, b + + -- if string.find(weaponDef.name, 'juno') then + -- radius = 140 + -- orgMult = 1 + -- r, g, b = 0.45, 1, 0.45 + -- end + + if weaponDef.type == 'BeamLaser' then + --muzzleFlash = true -- doesnt work + + + if not weaponDef.paralyzer then + local muzzleFlash = true + t.color2r, t.color2g, t.color2b = (r *0.1), (g*0.1), (b *0.1) + t.r, t.g, t.b = math.min(1, r+0.25), math.min(1, g+0.25), math.min(1, b+0.25) + t.life = 4 + t.colortime = 10 + (weaponDef.beamtime * 50) + t.sustain = 1.5 + (weaponDef.beamtime * 10) + + end + + radius = (6.3 * (weaponDef.size * weaponDef.size)) + (4 * radius * orgMult) + t.a = (orgMult * 0.14) / (0.25 + weaponDef.beamtime) + --projectileDefLights[weaponID].yOffset = 64 + + if weaponDef.paralyzer then + radius = radius * 0.5 + end + + sizeclass = GetClosestSizeClass(radius) + + if damage < 100 then + --life = 5 + projectileDefLights[weaponID] = GetLightClass("LaserProjectile", nil, sizeclass, t) + projectileDefLights[weaponID].lightConfig.selfshadowing = 5 -- Screen Space Light Shadows + elseif damage < 500 then + projectileDefLights[weaponID] = GetLightClass("GreenLaserProjectile", nil, sizeclass, t) + projectileDefLights[weaponID].lightConfig.selfshadowing = 5 -- Screen Space Light Shadows + else + projectileDefLights[weaponID] = GetLightClass("BlueLaserProjectile", nil, sizeclass, t) + projectileDefLights[weaponID].lightConfig.selfshadowing = 5 -- Screen Space Light Shadows + end + + if not weaponDef.paralyzer then + radius = ((orgMult * 2500) + radius) * 0.2 + sizeclass = GetClosestSizeClass(radius) + end + + elseif weaponDef.type == 'LaserCannon' then + radius = (4 * (weaponDef.size * weaponDef.size * weaponDef.size)) + (3 * radius * orgMult) + t.a = (orgMult * 0.1) + weaponDef.duration + + sizeclass = GetClosestSizeClass(radius) + projectileDefLights[weaponID] = GetLightClass("CannonProjectile", "Warm", sizeclass, t) + --projectileDefLights[weaponID].lightConfig.selfshadowing = 1 -- Screen Space Light Shadows + + elseif weaponDef.type == 'LightningCannon' then + if not scavenger then + t.r, t.g, t.b = 0.2, 0.45, 1 + end + t.a = 0.13 + (orgMult * 0.5) + sizeclass = GetClosestSizeClass(33 + (radius*2.5)) + projectileDefLights[weaponID] = GetLightClass("LaserProjectile", "Cold", sizeclass, t) + + elseif weaponDef.type == 'MissileLauncher' then + t.a = orgMult * 0.33 + if string.find(weaponDef.name, 'advsam') then --for LRAA + radius = radius * 0.45 + t.a = orgMult * 0.44 + end + sizeclass = GetClosestSizeClass(radius) + projectileDefLights[weaponID] = GetLightClass("MissileProjectile", "Warm", sizeclass, t) + + elseif weaponDef.type == 'StarburstLauncher' then + t.a = orgMult * 0.44 + + if weaponDef.interceptor == 1 then + --t.a = orgMult * 1.33 + t.r, t.g, t.b = 0.5, 0.75, 1.0 + t.color2r, t.color2g, t.color2b = 0.22, 0.37, 0.79 + projectileDefLights[weaponID] = GetLightClass("MissileProjectile", "Cold", sizeclass, t) + elseif weaponDef.paralyzer then + t.a = orgMult * 1.2 + sizeclass = GetClosestSizeClass(radius * 0.4) + projectileDefLights[weaponID] = GetLightClass("MissileProjectileEMP", "Warm", sizeclass, t) + else + sizeclass = GetClosestSizeClass(radius) + radius = ((orgMult * 75) + (radius * 4)) * 0.4 + life = 8 + (5*(radius/2000)+(orgMult * 5)) + projectileDefLights[weaponID] = GetLightClass("MissileProjectile", "Warm", sizeclass, t) + end + + + elseif weaponDef.type == 'Cannon' then + t.a = orgMult*0.17 + radius = (radius + (weaponDef.size * 35)) * 0.48 + sizeclass = GetClosestSizeClass(radius) + projectileDefLights[weaponID] = GetLightClass("CannonProjectile", "Plasma", sizeclass, t) + radius = ((weaponDef.damageAreaOfEffect*2) + (weaponDef.damageAreaOfEffect * weaponDef.edgeEffectiveness * 1.35)) + projectileDefLights[weaponID].lightConfig.selfshadowing = 1 -- Screen Space Light Shadows + + elseif weaponDef.type == 'DGun' then + muzzleFlash = true --doesnt work + sizeclass = "Medium" + t.a = orgMult*0.66 * 1.5 + projectileDefLights[weaponID] = GetLightClass("CannonProjectile", "Warm", sizeclass, t) + projectileDefLights[weaponID].yOffset = 32 + projectileDefLights[weaponID].lightConfig.selfshadowing = 1 -- Screen Space Light Shadows + --Spring.Echo(WeaponDefNames[weaponID], weaponDef.type, weaponDef.name) + + elseif weaponDef.type == 'TorpedoLauncher' and not Spring.GetModOptions().map_waterislava then + -- Torpedo projectile lights are assigned here, but activation is delayed until water entry. + projectileDefLights[weaponID] = GetLightClass("TorpedoProjectile", nil, nil, {}) + + elseif weaponDef.type == 'Shield' then + sizeclass = "Large" + projectileDefLights[weaponID] = GetLightClass("CannonProjectile", "Cold", sizeclass, t) + + -- elseif weaponDef.type == 'AircraftBomb' then + -- t.a = life * 1.8 + -- projectileDefLights[weaponID] = GetLightClass("MissileProjectile", "Warm", sizeclass, t) + + elseif weaponDef.type == 'Flame' then + --sizeclass = "Small" + sizeclass = GetClosestSizeClass(radius*2.5) + --t.a = orgMult * 0.17 + projectileDefLights[weaponID] = GetLightClass("FlameProjectile", nil, sizeclass, t) + end + + if muzzleFlash then + if aa then + t.r, t.g, t.b = 1, 0.7, 0.85 + end + if scavenger then + t.r, t.g, t.b = 0.35, 0.15, 0.7 + end + t.a = orgMult*2.3 + t.colortime = 2.5 + + if string.find(weaponDef.name, 'flak') then + radius = radius * 0.25 + --t.a = orgMult*0.8 + end + + if string.find(weaponDef.name, 'legflak') then + radius = radius * 3 + t.a = orgMult*1.2 + end + + local adjusted_radius = radius * 0.65 + + if damage < 150 then -- increase muzzleflash for low-damage units to remain visible + adjusted_radius = adjusted_radius * 2.9 -- Increase for low-damage weapons + t.colortime = 2.0 + end + + muzzleFlashLights[weaponID] = GetLightClass("MuzzleFlash", "White", GetClosestSizeClass(adjusted_radius), t) + muzzleFlashLights[weaponID].yOffset = muzzleFlashLights[weaponID].lightConfig.radius / 5 + end + + if explosionLight then + if aa then + t.r, t.g, t.b = 1, 0.7, 0.85 + end + if scavenger then + t.r, t.g, t.b = 0.3, 0.1, 0.7 + end + t.lifetime = life + t.colortime = 35 / life --t.colortime = life * 0.17 + t.a = orgMult * 1.1 + + if weaponDef.type == 'DGun' then + t.a = orgMult*0.17 + --Spring.Echo('-==DGUN==-', weaponDef.name, radius, lightclass, sizeclass, t.a) + elseif weaponDef.type == 'Flame' then + t.a = orgMult*0.22 + elseif weaponDef.type == 'MissileLauncher' then + if string.find(weaponDef.name, 'advsam') then --for LRAA + --damage = 1000 + --radius = 675 + orgMult = 0.25 + radius = radius * 0.5 + --t.a = orgMult * 2.44 + --Spring.Echo(WeaponDefNames[weaponID], weaponDef.type, weaponDef.name) + --Spring.Echo('-==--===-', weaponDef.name, radius, lightClassName, sizeclass, t.a) + sizeclass = GetClosestSizeClass(radius) + explosionLights[weaponID] = GetLightClass("Explosion", nil, sizeclass, t) + end + elseif weaponDef.type == 'TorpedoLauncher' then + -- t.r = t.r * 0.5 -- make more red + -- t.g = t.g * 0.5 -- make more red + -- t.b = t.b * 1.4 -- make more red + -- t.color2r = 0.9 + -- t.color2g = 0.6 + -- t.color2b = 0.8 + elseif weaponDef.type == 'BeamLaser' then + local mult = 0.85 + t.color2r, t.color2g, t.color2b = r*mult, g*mult, b*mult + t.colortime = 8 + t.lifetime = life * 0.6 + t.a = 0.02 + ((orgMult*0.055) / weaponDef.beamtime) + (weaponDef.range*0.000035) + radius = 1.2 * ((weaponDef.damageAreaOfEffect*4) + (weaponDef.damageAreaOfEffect * weaponDef.edgeEffectiveness * 1.1)) + (weaponDef.range*0.08) + if string.find(weaponDef.name, 'heat') then + radius = (radius / 2.5) + t.a = 0.01 + ((orgMult*0.035) / weaponDef.beamtime) + (weaponDef.range*0.000025) + t.color2r = 1.2 + t.color2g = 0.5 + t.color2b = 0.2 + t.colortime = 0.3 + t.lifetime = 4 + end + sizeclass = GetClosestSizeClass(radius) + elseif weaponDef.type == 'LightningCannon' then + t.a = orgMult*1.25 + t.color2r = 0.1 + t.color2g = 0.3 + t.color2b = 0.9 + sizeclass = GetClosestSizeClass(radius*1.2) + else + if weaponDef.type == 'AircraftBomb' then + if weaponDef.paralyzer then + t.r = t.r * 1.7 -- make more red + t.g = t.g * 0.4 -- make more red + t.b = t.b * 0.4 -- make more red + life = life * 1.1 -- too high and it will flicker somehow! + orgMult = orgMult * 0.15 + t.colortime = 31 / life + else + t.r = t.r * 1.7 -- make more red + t.g = t.g * 0.4 -- make more red + t.b = t.b * 0.4 -- make more red + life = life * 1.2 + t.colortime = 19 / life + end + t.lifetime = life + + end + radius = ((weaponDef.damageAreaOfEffect*1.9) + (weaponDef.damageAreaOfEffect * weaponDef.edgeEffectiveness * 1.35)) + if string.find(weaponDef.name, 'juno') then + radius = 675 + orgMult = 0.25 + t.r = 1.05 + t.g = 1.3 + t.b = 0.6 + t.color2r = 0.32 + t.color2g = 0.5 + t.color2b = 0.12 + t.colortime = 200 + t.lifetime = 500 + end + if weaponDef.customParams.unitexplosion then + radius = radius * 1.25 + -- make more white + t.r = (1.7 + t.r) / 2.7 + t.g = (1.7 + t.g) / 2.7 + t.b = (1.7 + t.b) / 2.7 + -- t.r = 3 + -- t.g = 3 + -- t.b = 3 + -- t.color2r = (1.5 + t.color2r) / 2.3 + -- t.color2g = (1.5 + t.color2g) / 2.3 + -- t.color2b = (1.5 + t.color2b) / 2.3 + t.a = orgMult*2.8 + t.lifetime = life * 1.15 + --t.colortime = 8 + else + -- make more white + t.r = (1.4 + t.r) / 1.8 + t.g = (1.4 + t.g) / 1.8 + t.b = (1.4 + t.b) / 1.8 + t.a = orgMult*1.3 --make all explosions bit stronger + end + local mult = 0.6 + + t.color2r, t.color2g, t.color2b = r*mult, g*mult, b*mult + sizeclass = GetClosestSizeClass(radius) + end + if not weaponDef.customParams.noexplosionlight then + explosionLights[weaponID] = GetLightClass("Explosion", nil, sizeclass, t) + explosionLights[weaponID].yOffset = explosionLights[weaponID].lightConfig.radius / 5 + end + end + end + Spring.Echo(Spring.GetGameFrame(),"DLGL4 weapons conf using",usedclasses,"light types") +end +AssignLightsToAllWeapons() + + +-----------------Manual Overrides-------------------- +local explosionLightsNames = {} +local muzzleFlashLightsNames = {} +local projectileDefLightsNames = {} + +--cortrem +explosionLightsNames["cortrem_tremor_focus_fire"] = +GetLightClass("Explosion", nil, "Tiny", { + colortime = 3.5, sustain = 1, lifetime = 1, scattering = 0.7}) + +explosionLightsNames["cortrem_tremor_spread_fire"] = +GetLightClass("Explosion", nil, "Smallish", { + colortime = 2.5, sustain = 2, lifetime = 6, scattering = 0.7}) + +--corforge +projectileDefLightsNames["corforge_flamethrower_ce"] = +GetLightClass("FlameProjectile", "Fire", "Micro", { + r = 1, a = 0.02791886, g = 0.94, b = 0.88}) + +--armthor +explosionLightsNames["armthor_thunder"] = +GetLightClass("Explosion", nil, "Smallish", { + r = 1.5, g = 1.5, b = 1.5, a = 0.08, radius = 120, + color2r = 0.3, color2g = 0.3, color2b = 0.4, colortime = 5, + sustain = 1.5, lifetime = 5, + modelfactor = 0.1, specular = 0.4, scattering = 0.1, lensflare = 4}) + +--corint +muzzleFlashLightsNames["corint_lrpc"] = +GetLightClass("MuzzleFlash", nil, "Large", { + posx = 0, posy = 0, posz = 0, radius = 240, + color2r = 0.5, color2g = 0.1, color2b = 0, colortime = 50, + r = 1.2, g = 1.0, b = 0.9, a = 0.5, + modelfactor = 0.5, specular = 0.3, scattering = 0.3, lensflare = 0, + lifetime = 17, sustain = 2}) +muzzleFlashLightsNames["corint_lrpc"].yOffset = 16 + +explosionLightsNames["corint_lrpc"] = +GetLightClass("ExplosionXL", nil, "Large", {colortime = 4, sustain = 12, lifetime = 26, scattering = 0.7}) + +-- muzzleFlashLightsNames["corint_lrpc"] = +-- GetLightClass("MuzzleFlash", nil, "Large", {posx = 0, posy = 0, posz = 0, radius = 240, +-- color2r = 0.5, color2g = 0.1, color2b = 0, colortime = 50, +-- r = 1.2, g = 1.0, b = 0.9, a = 0.5, +-- modelfactor = 0.5, specular = 0.3, scattering = 0.3, lensflare = 0, +-- lifetime = 17, sustain = 2}) +-- muzzleFlashLightsNames["corint_lrpc"].yOffset = 16 + +--armstil +explosionLightsNames["armstil_stiletto_bomb"] = +GetLightClass("ExplosionEMP", nil, "Medium", { +}) + +-- --armemp +-- projectileDefLightsNames["armemp_armemp_weapon"] = +-- GetLightClass("MissileProjectile", "Emp", "Small", { +-- a = 1.6, +-- modelfactor = 0.1, specular = 0.1, scattering = 0.5, lensflare = 0, +-- }) + +--armbrtha +muzzleFlashLightsNames["armbrtha_lrpc"] = +GetLightClass("MuzzleFlash", nil, "Medium", { + posx = 0, posy = 0, posz = 0, + color2r = 0.3, color2g = 0.1, color2b = 0.05, colortime = 13, + r = 1.2, g = 1.1, b = 1.0, a = 0.6, + modelfactor = 0.5, specular = 0.3, scattering = 0.3, lensflare = 0, + lifetime = 20, sustain = 2}) + +muzzleFlashLightsNames["armbrtha_lrpc"].yOffset = 8 + +explosionLightsNames["armbrtha_lrpc"] = +GetLightClass("ExplosionXL", nil, "Large", { + colortime = 4, sustain = 12, lifetime = 26, scattering = 0.7}) + +--armvulc +muzzleFlashLightsNames["armvulc_rflrpc"] = +GetLightClass("MuzzleFlash", nil, "Medium", {posx = 0, posy = 0, posz = 0, + r = 1.2, g = 1.1, b = 1.0, a = 0.5, + color2r = 0.3, color2g = 0.12, color2b = 0.05, colortime = 4, + modelfactor = 0.5, specular = 0.3, scattering = 0.8, lensflare = 14, + lifetime = 17, sustain = 2}) +muzzleFlashLightsNames["armvulc_rflrpc"].yOffset = 4 +explosionLightsNames["armvulc_rflrpc"] = +GetLightClass("ExplosionXL", nil, "Large", {colortime = 3.5, sustain = 14, lifetime = 26, scattering = 0.7}) + +projectileDefLightsNames["armvulc_rflrpc"] = +GetLightClass("LRPCProjectile", nil, "Mediumer") + + +--corbuzz +muzzleFlashLightsNames["corbuzz_rflrpc"] = +GetLightClass("MuzzleFlash", nil, "Medium", {posx = 0, posy = 0, posz = 0, + r = 1.2, g = 1.1, b = 1.0, a = 0.5, + color2r = 0.3, color2g = 0.12, color2b = 0.05, colortime = 4, + modelfactor = 0.5, specular = 0.3, scattering = 0.8, lensflare = 14, + lifetime = 17, sustain = 2}) +muzzleFlashLightsNames["corbuzz_rflrpc"].yOffset = 4 +explosionLightsNames["corbuzz_rflrpc"] = +GetLightClass("ExplosionXL", nil, "Large", {colortime = 3.5, sustain = 14, lifetime = 26, scattering = 0.7}) + +projectileDefLightsNames["corbuzz_rflrpc"] = +GetLightClass("LRPCProjectile", nil, "Mediumer") + +muzzleFlashLightsNames["armsnipe_old_armsnipe_weapon"] = +GetLightClass("MuzzleFlash", nil, "SmallMedium", {posx = 0, posy = 0, posz = 0, + r = 1.2, g = 0.85, b = 0.6, a = 0.5, + color2r = 0.3, color2g = 0.12, color2b = 0.05, colortime = 4, + modelfactor = 0.5, specular = 0.3, scattering = 0.8, lensflare = 14, + lifetime = 13, sustain = 1.5}) + +muzzleFlashLightsNames["armpb_armpb_weapon"] = +GetLightClass("MuzzleFlash", nil, "Smaller", {posx = 0, posy = 0, posz = 0, + r = 1.2, g = 0.85, b = 0.6, a = 0.5, + color2r = 0.3, color2g = 0.12, color2b = 0.05, colortime = 4, + modelfactor = 0.5, specular = 0.3, scattering = 0.8, lensflare = 14, + lifetime = 13, sustain = 1.5}) +-- arm t1 naval def turret +muzzleFlashLightsNames["armnavaldefturret_arm_medium_gauss_cannon"] = +GetLightClass("MuzzleFlash", nil, "Smaller", {posx = 0, posy = 0, posz = 0, + r = 1.2, g = 0.85, b = 0.6, a = 0.35, + color2r = 0.3, color2g = 0.12, color2b = 0.05, colortime = 4, + modelfactor = 0.5, specular = 0.3, scattering = 0.8, lensflare = 14, + lifetime = 13, sustain = 1.5}) + +muzzleFlashLightsNames["corlevlr_corlevlr_weapon"] = +GetLightClass("MuzzleFlash", nil, "Smaller", {posx = 0, posy = 0, posz = 0, + r = 1.2, g = 0.85, b = 0.6, a = 0.5, + color2r = 0.3, color2g = 0.12, color2b = 0.05, colortime = 4, + modelfactor = 0.5, specular = 0.3, scattering = 0.8, lensflare = 14, + lifetime = 13, sustain = 1.5}) + +muzzleFlashLightsNames["cormort_cor_mort"] = +GetLightClass("MuzzleFlash", nil, "Tiniest", {posx = 0, posy = 0, posz = 0, + r = 1.2, g = 1, b = 0.9, a = 0.5, + color2r = 0.25, color2g = 0.14, color2b = 0.07, colortime = 4, + modelfactor = 0.5, specular = 0.3, scattering = 0.8, lensflare = 14, + lifetime = 13, sustain = 1.5}) + +-- muzzleFlashLightsNames["corvipe_vipersabot"] = +-- GetLightClass("MuzzleFlash", nil, "Smaller", {posx = 0, posy = 0, posz = 0, +-- r = 1.2, g = 0.85, b = 0.6, a = 0.5, +-- color2r = 0.3, color2g = 0.12, color2b = 0.05, colortime = 4, +-- modelfactor = 0.5, specular = 0.3, scattering = 0.8, lensflare = 14, +-- lifetime = 13, sustain = 1.5}) + +-- --cortex anitnuke engine exhaust +-- projectileDefLightsNames["corfmd_fmd_rocket"] = +-- GetLightClass("MissileProjectile", "Cold", "MediumLarge", {a = 0.6, +-- --r = 0.1, g = 0.5, b = 1.0, +-- modelfactor = 0.1, specular = 0.1, scattering = 0.5, lensflare = 0, +-- color2r = 0.22, color2g = 0.37, color2b = 0.79, colortime = 5, +-- }) + + +--corsilo +explosionLightsNames["corsilo_crblmssl"] = +GetLightClass("Explosion", nil, "Tera", {r = 3, g = 3, b = 2.8, a = 0.2, + color2r = 1.0, color2g = 0.6, color2b = 0.18, colortime = 120, + sustain = 30, lifetime = 200, + modelfactor = 0.1, specular = 0.2, scattering = 0.1, lensflare = 4}) + +--corsilo engine +projectileDefLightsNames["corsilo_crblmssl"] = +GetLightClass("MissileProjectile", "Warm", "Large", {a = 0.6, + modelfactor = 0.1, specular = 0.1, scattering = 0.5, lensflare = 0}) + +--RAPTOR Nuclear Meteor +explosionLightsNames["raptor_turret_meteor_t4_v1_weapon"] = +GetLightClass("Explosion", nil, "Tera", {r = 3, g = 3, b = 2.8, a = 0.2, + color2r = 1.0, color2g = 0.6, color2b = 0.18, colortime = 120, + sustain = 30, lifetime = 200, + modelfactor = 0.1, specular = 0.2, scattering = 0.1, lensflare = 4}) + +--RAPTOR Nuclear Meteor engine +projectileDefLightsNames["raptor_turret_meteor_t4_v1_weapon"] = +GetLightClass("MissileProjectile", "Fire", "Large", {a = 0.8, + modelfactor = 0.1, specular = 0.1, scattering = 0.5, lensflare = 0}) + +-- --corsilo SCAV +-- explosionLightsNames["corsilo_scav_crblmssl"] = +-- GetLightClass("Explosion", nil, "Tera", {r = 2, g = 1, b = 3, a = 0.18, +-- color2r = 0.6, color2g = 0.3, color2b = 1, colortime = 120, +-- sustain = 30, lifetime = 200, +-- modelfactor = 0.1, specular = 0.2, scattering = 0.1, lensflare = 4}) + +-- --corsilo engine SCAV +-- projectileDefLightsNames["corsilo_scav_crblmssl"] = +-- GetLightClass("MissileProjectile", nil, "Large", {r = 2, g = 1, b = 3, a = 0.4, +-- color2r = 0.75, color2g = 0.3, color2b = 0.9, +-- modelfactor = 0.1, specular = 0.1, scattering = 0.5, lensflare = 0}) + +--armsilo +explosionLightsNames["armsilo_nuclear_missile"] = +GetLightClass("Explosion", nil, "Giga", {r = 3, g = 3, b = 2.8, a = 0.18, + color2r = 1.0, color2g = 0.6, color2b = 0.18, colortime = 110, + sustain = 25, lifetime = 180, selfshadowing = 4, + modelfactor = 0.1, specular = 0.2, scattering = 0.1, lensflare = 4}) + + --armsilo +explosionLightsNames["armguardnuke_plasma"] = +GetLightClass("Explosion", nil, "Giga", {r = 3, g = 2.9, b = 2.8, a = 0.18, + posx = 0, posy = 1, posz = 0, + dirx = 0, diry = -0.12, dirz = 0, + color2r = 1.0, color2g = 0.6, color2b = 0.18, colortime = 110, + sustain = 25, lifetime = 155, selfshadowing = 3, + modelfactor = 0.1, specular = 0.2, scattering = 0.1, lensflare = 4}) + +projectileDefLightsNames["armguardnuke_plasma"] = +GetLightClass("MissileProjectile", "Warm", "Medium", {a = 0.4, + modelfactor = 0.1, specular = 0.1, scattering = 0.5, lensflare = 0}) + +projectileDefLightsNames["armguardnuke_plasma_high"] = +GetLightClass("MissileProjectile", "Warm", "Medium", {a = 0.4, + modelfactor = 0.1, specular = 0.1, scattering = 0.5, lensflare = 0}) + + + +--armsilo engine +projectileDefLightsNames["armsilo_nuclear_missile"] = +GetLightClass("MissileProjectile", "Warm", "Large", {a = 0.6, + modelfactor = 0.1, specular = 0.1, scattering = 0.5, lensflare = 0}) + +--legsilo +explosionLightsNames["legsilo_legicbm"] = +GetLightClass("Explosion", nil, "Tera", {r = 3, g = 3, b = 2.8, a = 0.2, + color2r = 1.0, color2g = 0.6, color2b = 0.18, colortime = 120, + sustain = 30, lifetime = 200, + modelfactor = 0.1, specular = 0.2, scattering = 0.1, lensflare = 4}) + +--legsilo engine +projectileDefLightsNames["legsilo_legicbm"] = +GetLightClass("MissileProjectile", "Warm", "Large", {a = 0.6, + modelfactor = 0.1, specular = 0.1, scattering = 0.5, lensflare = 0}) + + +-- --armsilo SCAV +-- explosionLightsNames["armsilo_scav_nuclear_missile"] = +-- GetLightClass("Explosion", nil, "Giga", {r = 2, g = 1, b = 3, a = 0.18, +-- color2r = 0.6, color2g = 0.3, color2b = 1, colortime = 110, +-- sustain = 25, lifetime = 180, +-- modelfactor = 0.1, specular = 0.2, scattering = 0.1, lensflare = 4}) + +-- --armsilo engine SCAV +-- projectileDefLightsNames["armsilo_scav_nuclear_missile"] = +-- GetLightClass("MissileProjectile", nil, "Large", {r = 2, g = 1, b = 3, a = 0.4, +-- color2r = 0.75, color2g = 0.3, color2b = 0.9, +-- modelfactor = 0.1, specular = 0.1, scattering = 0.4, lensflare = 0}) + +--legbart +explosionLightsNames["legbart_clusternapalm"] = +GetLightClass("Explosion", "Fire", "SmallMedium", {r = 0.32, g = 0.24, b = 0.1, a = 0.1, + color2r = 0.8, color2g = 0.4, color2b = 0.1, colortime = 44, + sustain = 120, lifetime = 180, + modelfactor = -0.3, specular = -0.3, scattering = 0.3, lensflare = 0}) + +--legbar +explosionLightsNames["legbar_clusternapalm"] = +GetLightClass("Explosion", "Fire", "Small", {r = 0.32, g = 0.24, b = 0.1, a = 0.005, + color2r = 0.8, color2g = 0.4, color2b = 0.1, colortime = 44, + sustain = 120, lifetime = 180, + modelfactor = -0.3, specular = -0.3, scattering = 0.3, lensflare = 0}) + +--leginf +explosionLightsNames["leginf_rapidnapalm"] = +GetLightClass("Explosion", "Fire", "Small", {r = 0.32, g = 0.24, b = 0.1, a = 0.001, + color2r = 0.8, color2g = 0.4, color2b = 0.1, colortime = 180, + sustain = 30, lifetime = 180, + modelfactor = -0.3, specular = -0.3, scattering = 0.3, lensflare = 0}) + +--legnap +explosionLightsNames["legnap_napalmbombs"] = +GetLightClass("Explosion", "Fire", "Small", {r = 0.32, g = 0.24, b = 0.1, a = 0.1, + color2r = 0.8, color2g = 0.4, color2b = 0.1, colortime = 44, + sustain = 120, lifetime = 180, + modelfactor = -0.3, specular = -0.3, scattering = 0.3, lensflare = 0}) + +--legperdition +explosionLightsNames["legperdition_napalmmissile"] = +GetLightClass("Explosion", "Fire", "Large", {r = 0.32, g = 0.24, b = 0.1, a = 0.1, + color2r = 0.8, color2g = 0.4, color2b = 0.1, colortime = 44, + sustain = 120, lifetime = 180, + modelfactor = -0.3, specular = -0.3, scattering = 0.3, lensflare = 0}) + +--legphoenix +explosionLightsNames["legphoenix_skybeam"] = +GetLightClass("Explosion", "Fire", "Small", {r = 0.54, g = 0.45, b = 0.12, a = 0.35, + color2r = 1.2, color2g = 0.5, color2b = 0.2, colortime = 0.25, + sustain = 2, lifetime = 3, + modelfactor = -0.3, specular = -0.3, scattering = 0.45, lensflare = 0}) + +projectileDefLightsNames["legphoenix_skybeam"] = +GetLightClass("LaserProjectile", "Warm", "Tiny", {a = 0.25, + r = 1.0, g = 0.65, b = 0.1, + color2r = 0.3, color2g = 0.1, color2b = 0.03, colortime = 15, + pos2x = 0, pos2y = 0, pos2z = 0, + modelfactor = 0.5, specular = 0.05, scattering = 1.3, lensflare = 16, + lifetime = 3, sustain = 2,}) + +--legaheattank +-- explosionLightsNames["legaheattank_heat_ray"] = +-- GetLightClass("Explosion", nil, "Smaller", {r = 0.26, g = 0.26, b = 0.06, a = 0.18, +-- color2r = 0.9, color2g = 0.5, color2b = 0.2, colortime = 0.3, +-- sustain = 2, lifetime = 4, +-- modelfactor = -0.3, specular = -0.3, scattering = 0.25, lensflare = 0}) + +-- explosionLightsNames["legaheattank_heat_ray"].yOffset = 19 + +--legbastion +-- explosionLightsNames["legbastion_t2heatray"] = +-- GetLightClass("Explosion", nil, "SmallMedium", {r = 0.26, g = 0.26, b = 0.06, a = 0.20, +-- color2r = 0.9, color2g = 0.5, color2b = 0.2, colortime = 0.3, +-- sustain = 2, lifetime = 4, +-- modelfactor = -0.3, specular = -0.3, scattering = 0.55, lensflare = 0}) + +--explosionLightsNames["legbastion_t2heatray"].yOffset = 28 + +projectileDefLightsNames["legbastion_t2heatray"] = +GetLightClass("LaserProjectile", nil, "Small", {r = 1.0, g = 0.65, b = 0.1, a = 0.18, + color2r = 0.15, color2g = 0.04, color2b = 0.015, colortime = 0.03, + --pos2x = 0, pos2y = 0, pos2z = 0, + modelfactor = 0.5, specular = -0.1, scattering = 2.9, lensflare = 0, + lifetime = 3, sustain = 2}) + +--leginc +explosionLightsNames["leginc_heatraylarge"] = +GetLightClass("Explosion", "Fire", "Smaller", {r = 0.54, g = 0.45, b = 0.12, a = 0.15, + color2r = 1.2, color2g = 0.5, color2b = 0.2, colortime = 0.3, + sustain = 2, lifetime = 3, + modelfactor = -0.3, specular = -0.1, scattering = 1.95, lensflare = 0}) + +explosionLightsNames["leginc_heatraylarge"].yOffset = 32 + +projectileDefLightsNames["leginc_heatraylarge"] = +GetLightClass("LaserProjectile", "Warm", "Smallest", {r = 1.0, g = 0.65, b = 0.1, a = 0.15, + color2r = 0.15, color2g = 0.05, color2b = 0.015, colortime = 0.03, + --pos2x = 0, pos2y = 0, pos2z = 0, + modelfactor = 0.3, specular = -0.05, scattering = 0.3, lensflare = 16, + sustain = 2, lifetime = 3, }) + +--legeheatraymech +explosionLightsNames["legeheatraymech_heatray1"] = +GetLightClass("Explosion", "Fire", "SmallMedium", {r = 0.26, g = 0.26, b = 0.06, a = 0.09, + color2r = 0.9, color2g = 0.5, color2b = 0.2, colortime = 0.5, + sustain = 2, lifetime = 3, + modelfactor = -0.3, specular = -0.2, scattering = 0.8, lensflare = 0}) + +explosionLightsNames["legeheatraymech_heatray1"].yOffset = 32 + +projectileDefLightsNames["legeheatraymech_heatray1"] = +GetLightClass("LaserProjectile", "Warm", "Smallest", {r = 1.0, g = 0.65, b = 0.1, a = 0.25, + color2r = 0.15, color2g = 0.05, color2b = 0.015, colortime = 0.03, + --pos2x = 0, pos2y = 0, pos2z = 0, + modelfactor = 0.3, specular = -0.05, scattering = 3.9, lensflare = 16, + sustain = 2, lifetime = 3, }) + + +--armthundt4 +explosionLightsNames["armthundt4_armbomb"] = +GetLightClass("Explosion", nil, "Large", {r = 2, g = 1.5, b = 1.0, a = 0.22, + color2r = 0.9, color2g = 0.5, color2b = 0.15, colortime = 65, + sustain = 4, lifetime = 55, + modelfactor = 0.1, specular = 0.4, scattering = 0.4, lensflare = 6}) + +--armmerl +projectileDefLightsNames["armmerl_armtruck_rocket"] = +GetLightClass("MissileProjectile", "Warm", "Small", {a = 0.60, + modelfactor = 0.1, specular = 0.01, scattering = 0.5, lensflare = 8}) + +--armmerl +projectileDefLightsNames["corvroc_cortruck_rocket"] = +GetLightClass("MissileProjectile", "Warm", "Small", {a = 0.60, + modelfactor = 0.1, specular = 0.01, scattering = 0.5, lensflare = 8}) + +-- armbeamer +projectileDefLightsNames["armbeamer_armbeamer_weapon"] = +GetLightClass("LaserProjectile", nil, "Medium", {a = 0.20, + --r = 1.0, g = 0.65, b = 0.1, radius = 240, + r = 0.1, g = 0.1, b = 1, radius = 110, + color2r = 0.03, color2g = 0.05, color2b = 0.3, colortime = 1.6, + pos2x = 0, pos2y = 100, pos2z = 0, + modelfactor = 0.5, specular = 0.05, scattering = 0.5, lensflare = 16, + selfshadowing = 5, + lifetime = 6, sustain = 0}) + +-- corcan +projectileDefLightsNames["corcan_cor_canlaser"] = +GetLightClass("LaserProjectile", nil, "Medium", {a = 0.15, + --r = 1.0, g = 0.65, b = 0.1, radius = 240, + r = 0.3, g = 1, b = 0.3, radius = 110, + color2r = 0.1, color2g = 0.5, color2b = 0.1, colortime = 2.5, + pos2x = 0, pos2y = 100, pos2z = 0, + modelfactor = 0.5, specular = 0.05, scattering = 0.5, lensflare = 16, + lifetime = 4, sustain = 0, selfshadowing = 5,}) + +-- corsumo +projectileDefLightsNames["corsumo_corsumo_weapon"] = +GetLightClass("LaserProjectile", nil, "Medium", {a = 0.15, + --r = 1.0, g = 0.65, b = 0.1, radius = 240, + r = 0.4, g = 1.0, b = 0.4, radius = 110, + color2r = 0.05, color2g = 0.1, color2b = 0.05, colortime = 5.6, + pos2x = 0, pos2y = 100, pos2z = 0, + modelfactor = 0.5, specular = 0.2, scattering = 0.5, lensflare = 16, + lifetime = 2.8, sustain = 0, selfshadowing = 5,}) + +--corsumo +muzzleFlashLightsNames["corsumo_corsumo_weapon"] = +GetLightClass("MuzzleFlashCone", nil, "Large", { + posx = 0, posy = 0, posz = 0, radius = 240, + color2r = 0.5, color2g = 0.1, color2b = 0, colortime = 50, + r = 1.2, g = 1.0, b = 0.9, a = 0.5, + modelfactor = 0.5, specular = 0.3, scattering = 0.3, lensflare = 0, + lifetime = 17, sustain = 2}) + +--legflak +-- muzzleFlashLightsNames["legflak_legflak_gun"] = +-- GetLightClass("MuzzleFlash", nil, "Small") + + +--corkorg +explosionLightsNames["corkorg_corkorg_laser"] = +GetLightClass("Explosion", "Fire", "Smallish", {r = 0.54, g = 0.45, b = 0.12, a = 0.33, + color2r = 1.2, color2g = 0.5, color2b = 0.2, colortime = 0.3, + sustain = 2, lifetime = 3, + modelfactor = -0.3, specular = -0.1, scattering = 1.95, lensflare = 0}) + +-- org korglaser +projectileDefLightsNames["corkorg_corkorg_laser"] = +GetLightClass("LaserProjectile", nil, "Medium", {a = 0.09, + --r = 1.0, g = 0.65, b = 0.1, radius = 240, + r = 1.0, g = 0.75, b = 0.4, radius = 240, + color2r = 0.33, color2g = 0.05, color2b = 0.03, colortime = 3, + pos2x = 0, pos2y = 100, pos2z = 0, + modelfactor = 0.5, specular = 0.05, scattering = 0.05, lensflare = 16, + selfshadowing = 5, + lifetime = 6, sustain = 2}) + +-- custom sharp white center beam +-- projectileDefLightsNames["corkorg_corkorg_laser"] = +-- GetLightClass("LaserProjectile", nil, "Medium", {a = 3.0, +-- --r = 1.0, g = 0.65, b = 0.1, radius = 240, +-- r = 1.0, g = 0.85, b = 0.5, radius = 1.3, +-- color2r = 0.33, color2g = 0.05, color2b = 0.03, colortime = 3, +-- pos2x = 0, pos2y = 100, pos2z = 0, +-- modelfactor = 0.5, specular = 0.5, scattering = 5, lensflare = 16, +-- selfshadowing = 8, +-- lifetime = 23, sustain = 2}) + +muzzleFlashLightsNames["corkorg_corkorg_laser"] = +GetLightClass("MuzzleFlash", "Fire", "Mega", {posx = 120, posy = 82, posz = 0, + r = 1.2, g = 1.1, b = 0.5, a = 0.9, + color2r = 0.3, color2g = 0.12, color2b = 0.05, colortime = 20, + modelfactor = 0.5, specular = 0.3, scattering = 2.8, lensflare = 9, + lifetime = 120, sustain = 4}) + +--muzzleflashes for corkorg broken?? +muzzleFlashLightsNames["corkorg_corkorg_fire"] = +GetLightClass("MuzzleFlash", "Plasma", "Tiny", { + r = 1.1, g = 0.85, b = 0.3, a = 0.6, + color2r = 0.3, color2g = 0.12, color2b = 0.04, colortime = 15, + modelfactor = 0.5, specular = 0.3, scattering = 0.1, lensflare = 0, + lifetime = 20, sustain = 2}) + +--corkorg_shotgun +projectileDefLightsNames["corkorg_corkorg_fire"] = +GetLightClass("CannonProjectile", "Plasma", "Smaller", {a = 0.012, radius = 200, + selfshadowing = 4, + modelfactor = 0.2, specular = 0.2, scattering = 0.3, lensflare = 3}) + +explosionLightsNames["corkorg_corkorg_fire"] = +GetLightClass("Explosion", "Fire", "Tiny", {r = 0.5, g = 0.3, b = 0.08, a = 0.4, + color2r = 1.2, color2g = 0.6, color2b = 0.4, colortime = 0.6, + sustain = 2, lifetime = 6, + modelfactor = -0.3, specular = -0.1, scattering = 1.95, lensflare = 0 + }) + +projectileDefLightsNames["corpyro_flamethrower"] = +GetLightClass("FlameProjectile", nil, "Tiny", { + r = 0.7, g = 0.7, b = 0.65, a = 0.14, + color2r = 1.0, color2g = 0.70, color2b = 0.4, colortime = 12, + lifetime = 30, sustain = 15, + }) + +explosionLightsNames["corpyro_flamethrower"] = +GetLightClass("FlameProjectile", nil, "Smallest", { + r = 1.7, g = 0.7, b = 0.65, a = 0.03, + color2r = 1.0, color2g = 0.70, color2b = 0.4, colortime = 12, + lifetime = 6, sustain = 2, + }) + +--explosionLightsNames["corpyro_flamethrower"].fraction = 5 + +projectileDefLightsNames["cormaw_dmaw"] = +GetLightClass("FlameProjectile", nil, "Smallish", { + r = 0.7, g = 0.7, b = 0.65, a = 0.03, + color2r = 1.0, color2g = 0.70, color2b = 0.4, colortime = 12, + lifetime = 70, sustain = 30, + }) + +projectileDefLightsNames["corfship_dmaw"] = +GetLightClass("FlameProjectile", nil, "Smallish", { + r = 0.7, g = 0.7, b = 0.65, a = 0.05, + color2r = 1.0, color2g = 0.70, color2b = 0.4, colortime = 12, + lifetime = 70, sustain = 30, + }) + + +projectileDefLightsNames["corcrwh_dragonmawh"] = +GetLightClass("FlameProjectile", nil, "Smallest", { + r = 0.7, g = 0.7, b = 0.65, a = 0.19, + color2r = 1.0, color2g = 0.70, color2b = 0.4, colortime = 12, + lifetime = 70, sustain = 30, selfshadowing = 0, + }) + +projectileDefLightsNames["corcrwh_dragonmawh"].yOffset = 32 + +explosionLightsNames["corcrwh_dragonmawh"] = +GetLightClass("FlameProjectile", nil, "Smaller", { + r = 0.3, g = 0.2, b = 0.09, a = 0.020, + color2r = 1.0, color2g = 0.45, color2b = 0.22, colortime = 10, + lifetime = 20, sustain = 3, selfshadowing = 0, + }) + +explosionLightsNames["corcrwh_dragonmawh"].yOffset = 32 +--explosionLightsNames["corcrwh_dragonmawh"].fraction = 5 + +explosionLightsNames["corcrwh_krowlaserh"] = +GetLightClass("Explosion", "Red", "Micro", { + r = 1, g = 0.3, b = 0.08, a = 0.4, + color2r = 1.2, color2g = 0.6, color2b = 0.4, colortime = 0.6, + sustain = 1, lifetime = 3, + --modelfactor = -0.3, specular = -0.1, scattering = 1.95, lensflare = 0 + }) + + + +projectileDefLightsNames["corcrwt4_kmaw"] = +GetLightClass("FlameProjectile", nil, "Medium", { + r = 0.7, g = 0.7, b = 0.65, a = 0.13, + color2r = 1.0, color2g = 0.70, color2b = 0.4, colortime = 12, + lifetime = 70, sustain = 30, + }) + +projectileDefLightsNames["cordemon_newdmaw"] = +GetLightClass("FlameProjectile", nil, "Medium", { + r = 0.7, g = 0.7, b = 0.65, a = 0.05, + color2r = 1.0, color2g = 0.70, color2b = 0.4, colortime = 12, + lifetime = 40, sustain = 30, + }) + +--corkorg_rocket +projectileDefLightsNames["corkorg_corkorg_rocket"] = +GetLightClass("MissileProjectile", "Warm", "SmallMedium", {a = 0.40, + r = 1.2, g = 0.65, b = 0.1, radius = 80, + color2r = 1.2, color2g = 0.7, color2b = 0.4, + modelfactor = 0.5, specular = 0.05, scattering = 0.45, lensflare = 5}) + +explosionLightsNames["corkorg_corkorg_rocket"] = +GetLightClass("Explosion", "Fire", "Medium", {r = 0.4, g = 0.2, b = 0.08, a = 0.5, radius = 240, + color2r = 1.2, color2g = 0.9, color2b = 0.4, + sustain = 4, lifetime = 10, + --modelfactor = -0.3, specular = -0.1, scattering = 1.95, lensflare = 0 + }) + +-- --corkorg_scav +-- projectileDefLightsNames["corkorg_scav_corkorg_laser"] = +-- GetLightClass("LaserProjectile", "Purple", "Large", {a = 0.15, +-- color2r = 0.5, color2g = 0.3, color2b = 0.2, colortime = 10, +-- modelfactor = 0.5, specular = 0.2, scattering = 0.1, lensflare = 0, +-- lifetime = 4, sustain = 0}) + +--cordoomt3 +projectileDefLightsNames["cordoomt3_armagmheat"] = +GetLightClass("LaserProjectile", "HeatRay", "Mediumer", {a = 0.09, + color2r = 0.5, color2g = 0.3, color2b = 0.2, colortime = 10, + modelfactor = 0.5, specular = 0.1, scattering = 0.1, lensflare = 0, + lifetime = 4, sustain = 0}) + +--cortron +explosionLightsNames["cortron_cortron_weapon"] = +GetLightClass("Explosion", nil, "Large", {r = 3, g = 2.5, b = 2.0, a = 0.25, + color2r = 0.5, color2g = 0.2, color2b = 0.09, colortime = 10, + sustain = 4, lifetime = 120, + modelfactor = 0.1, specular = 0.2, scattering = 0.1, lensflare = 4}) + +projectileDefLightsNames["cortron_cortron_weapon"] = +GetLightClass("MissileProjectile", "Red", "SmallMedium", { + --lifetime = 200, + --color2r = 0.75, color2g = 0.9, color2b = 0.3, colortime = 25, + modelfactor = 0.3, specular = 0.1, scattering = 0.4, lensflare = 7}) + + +--armjuno +projectileDefLightsNames["armjuno_juno_pulse"] = +GetLightClass("MissileProjectile", "Green", "SmallMedium", {r = 0.02, g = 0.05, b = 0.01, a = 0.25, + color2r = 0.88, color2g = 1.5, color2b = 0.6, colortime = 150, + --lifetime = 200, + --color2r = 0.75, color2g = 0.9, color2b = 0.3, colortime = 25, + modelfactor = 0.3, specular = 0.1, scattering = 0.4, lensflare = 7}) +explosionLightsNames["armjuno_juno_pulse"] = +GetLightClass("Explosion", "Green", "Largest", {a = 0.6, + posx = 0, posy = 100, posz = 0, + r = 0.9, g = 1.1, b = 0.45, + color2r = 0.32, color2g = 0.5, color2b = 0.12, colortime = 100, + sustain = 15, lifetime = 500, + modelfactor = 0.1, specular = 0.2, scattering = 0.3, lensflare = 6}) + +-- --armjuno SCAV +-- projectileDefLightsNames["armjuno_scav_juno_pulse"] = +-- GetLightClass("MissileProjectile", "Green", "Medium", {r = 0.8, g = 0.4, b = 1.5, a = 0.45, +-- color2r = 0.75, color2g = 0.3, color2b = 0.9, colortime = 25, +-- modelfactor = 0.3, specular = 0.1, scattering = 0.3, lensflare = 8}) +-- explosionLightsNames["armjuno_scav_juno_pulse"] = +-- GetLightClass("Explosion", "Green", "Largest", {a = 0.6, +-- posx = 0, posy = 100, posz = 0, +-- r = 0.75, g = 0.6, b = 1.0, +-- color2r = 0.36, color2g = 0.12, color2b = 0.48, colortime = 75, +-- sustain = 15, lifetime = 500, +-- modelfactor = 0.1, specular = 0.2, scattering = 0.3, lensflare = 6}) + +--corjuno +projectileDefLightsNames["corjuno_juno_pulse"] = +GetLightClass("MissileProjectile", "Green", "SmallMedium", {r = 0.02, g = 0.05, b = 0.01, a = 0.25, + color2r = 0.88, color2g = 1.5, color2b = 0.6, colortime = 150, + --lifetime = 200, + --color2r = 0.75, color2g = 0.9, color2b = 0.3, colortime = 25, + modelfactor = 0.3, specular = 0.1, scattering = 0.4, lensflare = 7}) +explosionLightsNames["corjuno_juno_pulse"] = +GetLightClass("Explosion", "Green", "Largest", {a = 0.6, + posx = 0, posy = 100, posz = 0, + r = 0.9, g = 1.1, b = 0.45, + color2r = 0.32, color2g = 0.5, color2b = 0.12, colortime = 50, + sustain = 10, lifetime = 400, + modelfactor = 0.1, specular = 0.2, scattering = 0.3, lensflare = 6}) + +--legjuno +projectileDefLightsNames["legjuno_juno_pulse"] = +GetLightClass("MissileProjectile", "Green", "SmallMedium", {r = 0.02, g = 0.05, b = 0.01, a = 0.25, + color2r = 0.88, color2g = 1.5, color2b = 0.6, colortime = 150, + --lifetime = 200, + --color2r = 0.75, color2g = 0.9, color2b = 0.3, colortime = 25, + modelfactor = 0.3, specular = 0.1, scattering = 0.4, lensflare = 7}) +explosionLightsNames["legjuno_juno_pulse"] = +GetLightClass("Explosion", "Green", "Largest", {a = 0.6, + posx = 0, posy = 100, posz = 0, + r = 0.9, g = 1.1, b = 0.45, + color2r = 0.32, color2g = 0.5, color2b = 0.12, colortime = 100, + sustain = 15, lifetime = 500, + modelfactor = 0.1, specular = 0.2, scattering = 0.3, lensflare = 6}) + + +--armpw machinegun +muzzleFlashLightsNames["armpw_emg"] = +GetLightClass("MuzzleFlash", "Warm", "Medium", {posx = 1, posy = 1, posz = 1, radius = 50, + r = 1.2, g = 1.1, b = 1.0, a = 0.5, + color2r = 0.3, color2g = 0.12, color2b = 0.05, colortime = 4, + modelfactor = 0.5, specular = 0.3, scattering = 0.8, lensflare = 14, + lifetime = 17, sustain = 2}) + +--armmanni +projectileDefLightsNames["armmanni_atam"] = +GetLightClass("LaserProjectile", "Blue", "SmallMedium", {a = 0.09, + color2r = 0.6, color2g = 0.6, color2b = 0.6, colortime = 10, + modelfactor = 0.5, specular = 0.1, scattering = 0.7, lensflare = 0, + selfshadowing = 8, + lifetime = 0, sustain = 0}) + +--corjugg +explosionLightsNames["corjugg_juggernaut_fire"] = +GetLightClass("Explosion", nil, "Small", {r = 1.3, g = 1.1, b = 0.8, a = 0.4, + color2r = 0.35, color2g = 0.20, color2b = 0.05, colortime = 3, + sustain = 4, lifetime = 20, scattering = 0.2}) + +projectileDefLightsNames["corjugg_juggernaut_fire"] = +GetLightClass("CannonProjectile", nil, "Large", {a = 0.5, + color2r = 0.5, color2g = 0.5, color2b = 0.6, colortime = 10, + modelfactor = 0.5, specular = 0.1, scattering = 0.1, lensflare = 0, + lifetime = 26, sustain = 20}) + +-- --armanni +projectileDefLightsNames["armanni_ata"] = +GetLightClass("LaserProjectile", "Blue", "Medium", {a = 0.09, + color2r = 0.5, color2g = 0.5, color2b = 0.6, colortime = 10, + modelfactor = 0.5, specular = 0.1, scattering = 0.1, lensflare = 0, + lifetime = 0, sustain = 0}) + +--corcat +explosionLightsNames["corcat_exp_heavyrocket"] = +GetLightClass("Explosion", nil, "Mediumer", {r = 3, g = 2.5, b = 2.0, a = 0.25, + color2r = 0.75, color2g = 0.40, color2b = 0.09, colortime = 4, + sustain = 7, lifetime = 32, + modelfactor = 0.1, specular = 0.2, scattering = 0.1, lensflare = 4}) + + +-- --corjuno SCAV +-- projectileDefLightsNames["corjuno_scav_juno_pulse"] = +-- GetLightClass("MissileProjectile", "Green", "Medium", {r = 0.8, g = 0.4, b = 1.5, a = 0.45, +-- color2r = 0.75, color2g = 0.3, color2b = 0.9, colortime = 25, +-- modelfactor = 0.3, specular = 0.1, scattering = 0.3, lensflare = 8}) +-- explosionLightsNames["corjuno_scav_juno_pulse"] = +-- GetLightClass("Explosion", "Green", "Largest", {a = 0.6, +-- posx = 0, posy = 100, posz = 0, +-- r = 0.75, g = 0.6, b = 1.0, +-- color2r = 0.36, color2g = 0.12, color2b = 0.48, colortime = 75, +-- sustain = 10, lifetime = 400, +-- modelfactor = 0.1, specular = 0.2, scattering = 0.3, lensflare = 6}) +--scavengerbossv4 +explosionLightsNames['scavengerbossv4_normal_turbo_napalm'] = +GetLightClass("Explosion", "Fire", "SmallMedium", {r = 0.54, g = 0.45, b = 0.12, a = 0.29, + color2r = 1.2, color2g = 0.5, color2b = 0.2, colortime = 0.03, + sustain = 40, lifetime = 150, + modelfactor = 0.3, specular = 0.8, scattering = 1.5, lensflare = 0}) + + + +--duplicate lights from scavengerbossv4_normal_turbo_napalm for all scavengerbossv4 variants, including _scav +local scavengerBossV4Table = {'scavengerbossv4_veryeasy_turbo_napalm', 'scavengerbossv4_easy_turbo_napalm', 'scavengerbossv4_hard_turbo_napalm', 'scavengerbossv4_veryhard_turbo_napalm', 'scavengerbossv4_epic_turbo_napalm', + 'scavengerbossv4_veryeasy_scav_turbo_napalm', 'scavengerbossv4_easy_scav_turbo_napalm', 'scavengerbossv4_normal_scav_turbo_napalm', 'scavengerbossv4_hard_scav_turbo_napalm', 'scavengerbossv4_veryhard_scav_turbo_napalm', 'scavengerbossv4_epic_scav_turbo_napalm'} +for _, name in pairs(scavengerBossV4Table) do + explosionLightsNames[name] = table.copy(explosionLightsNames['scavengerbossv4_normal_turbo_napalm']) +end + + +-- --armannit3 +-- projectileDefLightsNames["armannit3_ata"] = +-- GetLightClass("LaserProjectile", "Blue", "Mediumer", {a = 0.09, +-- color2r = 0.5, color2g = 0.5, color2b = 0.5, colortime = 4, +-- modelfactor = 0.4, specular = 0.1, scattering = 0.1, lensflare = 0, +-- lifetime = 0, sustain = 0}) + +-- --armannit3_scav +-- projectileDefLightsNames["armannit3_scav_ata"] = +-- GetLightClass("LaserProjectile", "Purple", "Mediumer", {a = 0.09, +-- color2r = 0.5, color2g = 0.5, color2b = 0.5, colortime = 4, +-- modelfactor = 0.4, specular = 0.1, scattering = 0.1, lensflare = 0, +-- lifetime = 0, sustain = 0}) + +--[[ +--armpw +explosionLightsNames["armpw_emg"] = +GetLightClass("Explosion", nil, "Micro", {r = 2.4, g = 1.8, b = 1.0, a = 0.12, colortime = 2.4, + sustain = 8, lifetime = 14, + modelfactor = 0.2, specular = 0.2, scattering = 0.4}) +projectileDefLightsNames["armpw_emg"] = +GetLightClass("CannonProjectile", "Emg", "Tiny", {a = 0.1, radius = 25, + color2r = 0.5, color2g = 0.5, color2b = 0.5, colortime = 2, + modelfactor = 0.5, specular = 0.2, scattering = 0.1, lensflare = 0, + lifetime = 3, sustain = 0}) + +--armfast +explosionLightsNames["armfast_arm_fast"] = +GetLightClass("Explosion", nil, "Micro", {r = 2.8, g = 2.2, b = 1.2, a = 0.14, colortime = 2.8, + sustain = 8, lifetime = 22, scattering = 0.7}) +projectileDefLightsNames["armfast_arm_fast"] = +GetLightClass("CannonProjectile", "Emg", "Tiny", {a = 0.1, radius = 25, + color2r = 0.5, color2g = 0.5, color2b = 0.5, colortime = 2, + modelfactor = 0.5, specular = 0.2, scattering = 0.1, lensflare = 0, + lifetime = 3, sustain = 0}) + +--armanni_scav +-- could use a custom script that replaces color for all _scav units with "purple" +projectileDefLightsNames["armanni_scav_ata"] = +GetLightClass("LaserProjectile", "Purple", "Larger", {a = 0.12, + color2r = 0.5, color2g = 0.5, color2b = 0.5, colortime = 4, + modelfactor = 0.5, specular = 0.2, scattering = 0.1, lensflare = 0, + lifetime = 0, sustain = 0}) + + +--cordoom +projectileDefLightsNames["cordoom_atadr"] = +GetLightClass("LaserProjectile", "Blue", "Large", {a = 0.14, + color2r = 0.5, color2g = 0.5, color2b = 0.5, colortime = 4, + modelfactor = 0.5, specular = 0.2, scattering = 0.1, lensflare = 0, + lifetime = 0, sustain = 0}) + +--cordoom_scav +projectileDefLightsNames["cordoom_scav_atadr"] = +GetLightClass("LaserProjectile", "Purple", "Large", {a = 0.14, + color2r = 0.5, color2g = 0.5, color2b = 0.5, colortime = 4, + modelfactor = 0.5, specular = 0.2, scattering = 0.1, lensflare = 0, + lifetime = 0, sustain = 0}) + +--cordoomt3 +projectileDefLightsNames["cordoomt3_armagmheat"] = +GetLightClass("LaserProjectile", "HeatRay", "Larger", {a = 0.14, + color2r = 0.5, color2g = 0.5, color2b = 0.5, colortime = 4, + modelfactor = 0.5, specular = 0.2, scattering = 0.1, lensflare = 0, + lifetime = 0, sustain = 0}) + +--cordoomt3_scav +projectileDefLightsNames["cordoomt3_scav_armagmheat"] = +GetLightClass("LaserProjectile", "Purple", "Larger", {a = 0.14, + color2r = 0.5, color2g = 0.5, color2b = 0.5, colortime = 4, + modelfactor = 0.5, specular = 0.2, scattering = 0.1, lensflare = 0, + lifetime = 0, sustain = 0}) +--armcom +muzzleFlashLightsNames["armcom_disintegrator"] = +GetLightClass("MuzzleFlash", nil, "Medium", {posx = 0, posy = 0, posz = 0, + color2r = 0.3, color2g = 0.1, color2b = 0.05, colortime = 13, + r = 1.2, g = 1.1, b = 1.0, a = 0.6, + modelfactor = 0.5, specular = 0.3, scattering = 0.3, lensflare = 0, + lifetime = 20, sustain = 2}) + +--armmg +muzzleFlashLightsNames["armmg_armmg_weapon"] = +GetLightClass("MuzzleFlash", nil, "SmallMedium", {r = 0.4, g = 0.4, b = 0.4, + lifetime = 3, colortime = 4, + scattering = 0.1, specular = 0.4,}) +explosionLightsNames["armmg_armmg_weapon"] = +GetLightClass("Explosion", nil, "Micro", { r = 1.8, g = 1.8, b = 1.8, a = 0.2, + color2r = 0.6, color2g = 0.6, color2b = 0.6, colortime = 4.8, + sustain = 8, lifetime = 20, scattering = 0.4}) +projectileDefLightsNames["armmg_armmg_weapon"] = +GetLightClass("CannonProjectile", "Warm", "Micro", {r = 1, g = 1, b = 1, a = 0.1, + modelfactor = 0.1, specular = 0.1, scattering = 0.2, lensflare = 0}) + +--leggat +muzzleFlashLightsNames["leggat_armmg_weapon"] = +GetLightClass("MuzzleFlash", nil, "SmallMedium", {r = 0.4, g = 0.4, b = 0.4, scattering = 0.1, specular = 0.4, lensflare = 3,}) +explosionLightsNames["leggat_armmg_weapon"] = +GetLightClass("Explosion", nil, "Micro", { r = 3.8, g = 3.2, b = 2.2, colortime = 2.8, sustain = 14, lifetime = 22, scattering = 0.4}) + +--armkam +explosionLightsNames["armkam_med_emg"] = +GetLightClass("Explosion", nil, "Micro", { r = 1.8, g = 1.8, b = 1.8, a = 0.2, + colortime = 2.8, + sustain = 12, lifetime = 20, scattering = 0.4}) +projectileDefLightsNames["armkam_med_emg"] = +GetLightClass("CannonProjectile", "Warm", "Micro", {r = 1, g = 1, b = 1, a = 0.1, + modelfactor = 0.1, specular = 0.1, scattering = 0.2, lensflare = 0}) + +--armrl engine +projectileDefLightsNames["armrl_armrl_missile"] = +GetLightClass("MissileProjectile", "Purple", "Tiny", {a = 0.7, + color2r = 0.5, color2g = 0.2, color2b = 0.8, colortime = 1.6, + modelfactor = 0.1, specular = 0.1, scattering = 0.5, lensflare = 2}) + +--cordemon +projectileDefLightsNames["cordemont4_dmaw"] = +GetLightClass("FlameProjectile", nil, "SmallMedium", {posy = 80, a = 0.08, colortime = 15, lifetime = 40}) + +--corjugg +explosionLightsNames["corjugg_juggernaut_fire"] = +GetLightClass("Explosion", nil, "Small", {r = 1.3, g = 1.1, b = 0.8, a = 0.75, + color2r = 0.35, color2g = 0.20, color2b = 0.05, colortime = 7, + sustain = 8, lifetime = 26, scattering = 0.7}) +]] + + +-- hue hue turning these on will completely break the game... +--projectileDefLightsNames["armrock_arm_bot_rocket"] = GetLightClass("LaserAimProjectile", "Red", "Large") +--projectileDefLightsNames["corstorm_cor_bot_rocket"] = GetLightClass("LaserAimProjectile", "Red", "Large") + + + +-- duplicate all weapons for scavengers +function applyScavVariants(name, params) + local pos = name:find("_", 1, true) + local scavName = string.sub(name, 1, pos-1)..'_scav'..string.sub(name, pos) + if WeaponDefNames[scavName] then + local paramsScav = deepcopy(params) + paramsScav.lightConfig.r, paramsScav.lightConfig.g, paramsScav.lightConfig.b = 0.3, 0.1, 0.7 + paramsScav.lightConfig.color2r, paramsScav.lightConfig.color2g, paramsScav.lightConfig.color2b = 0.3, 0.1, 0.7 + return scavName, paramsScav + end +end + +-- convert weaponname -> weaponDefID +for name, params in pairs(explosionLightsNames) do + if WeaponDefNames[name] then + explosionLights[WeaponDefNames[name].id] = params + end + local scavName, paramsScav = applyScavVariants(name, params) + if scavName and WeaponDefNames[scavName] then + explosionLights[WeaponDefNames[scavName].id] = paramsScav + end +end +explosionLightsNames = nil + +-- convert weaponname -> weaponDefID +for name, params in pairs(muzzleFlashLightsNames) do + if WeaponDefNames[name] then + muzzleFlashLights[WeaponDefNames[name].id] = params + end + local scavName, paramsScav = applyScavVariants(name, params) + if scavName and WeaponDefNames[scavName] then + muzzleFlashLights[WeaponDefNames[scavName].id] = paramsScav + end +end +muzzleFlashLightsNames = nil + +-- convert weaponname -> weaponDefID +for name, params in pairs(projectileDefLightsNames) do + if WeaponDefNames[name] then + projectileDefLights[WeaponDefNames[name].id] = params + end + local scavName, paramsScav = applyScavVariants(name, params) + if scavName and WeaponDefNames[scavName] then + projectileDefLights[WeaponDefNames[scavName].id] = paramsScav + end +end +projectileDefLightsNames = nil + + + +-- verification questions: +-- colortime determines how slow the initial rgb color(1) fades to color2 ? +-- too low colortime can induce flicker, why? + +-- sustain determines how long color1 + color2 remain fully visible (before going into fade-out) +-- lifetime determines total life length and gets removed after this + +-- Icexuick Check-list + +-- 1. posy on FlameProjectile does not have any effect +-- 2. Cannon/Missile Projectiles with color2 seem to not loop the effect, but only play it once, making it hard(er) to use it +-- currently disabled this for CannonProjectile, so lights don't disappear half-way down trajectory +-- For FlameProjectile this does work very nice to add more colorvariation - and with manual lifetime tweaks makes it work for pyro + cordemont4 +-- 3. DGun only has explosion GL4 lights, projectile lights do not seem to show/work properly (also muzzleflash does not work on DGun weapons) +-- 4. When projectiles hit water, they get asigned a different explosion CEG, but also lighting is removed. I think some subtle blue-ish explo light on water can make it look better.. but how? + + +-------------------------------------------------------------------------------- +-------------------------------------------------------------------------------- +-- Projectile Collection +return {muzzleFlashLights = muzzleFlashLights, projectileDefLights = projectileDefLights, explosionLights = explosionLights, gibLight = gibLight} + +end + includes["common/springutilities/teamfunctions.lua"]=function() +local smallTeamThreshold = 4 +local initialized = false +local settings = { } + +local holidaysList = VFS.Include("common/holidays.lua") + +local function getSettings() + if initialized then + return settings + end + + local allyTeamCount, playerCount = 0, 0 + local isSinglePlayer, is1v1, isTeams, isBigTeams, isSmallTeams, isRaptors, isScavengers, isPvE, isCoop, isFFA, isSandbox = false, false, false, false, false, false, false, false, false, false, false + local scavTeamID, scavAllyTeamID, raptorTeamID, raptorAllyTeamID + local isHoliday = {} + + local gaiaAllyTeamID = select(6, Spring.GetTeamInfo(Spring.GetGaiaTeamID(), false)) + local springAllyTeamList = Spring.GetAllyTeamList() + local allyTeamList = {} + local allyTeamSizes = {} + local entirelyHumanAllyTeams = {} + + for _, allyTeamID in ipairs(springAllyTeamList) do + local teamList = Spring.GetTeamList(allyTeamID) or {} + local allyteamEntirelyHuman = true + + if #teamList > 0 and allyTeamID ~= gaiaAllyTeamID then + local isAllyTeamValid = true + + for _, teamID in ipairs(teamList) do + if select (4, Spring.GetTeamInfo(teamID, false)) then + allyteamEntirelyHuman = false + else + local teamPlayers = Spring.GetPlayerList(teamID) + for _, playerID in ipairs(teamPlayers) do + playerCount = playerCount + 1 + end + end + + local luaAI = Spring.GetTeamLuaAI(teamID) + + if luaAI then + if luaAI:find("Raptors") then + isRaptors = true + isAllyTeamValid = false + raptorTeamID = teamID + raptorAllyTeamID = allyTeamID + elseif luaAI:find("Scavengers") then + isScavengers = true + isAllyTeamValid = false + scavTeamID = teamID + scavAllyTeamID = allyTeamID + end + end + end + + if isAllyTeamValid then + allyTeamList[#allyTeamList+1] = allyTeamID + allyTeamSizes[#allyTeamSizes+1] = #teamList + end + + if allyteamEntirelyHuman then + entirelyHumanAllyTeams[#entirelyHumanAllyTeams+1] = allyTeamID + end + end + end + + allyTeamCount = #allyTeamList + + isSmallTeams = true + for _, teamSize in ipairs(allyTeamSizes) do + if teamSize > 1 then + isTeams = true + end + + isSmallTeams = isSmallTeams and teamSize <= smallTeamThreshold + end + + isSinglePlayer = playerCount == 1 + isSmallTeams = isTeams and isSmallTeams + isBigTeams = isTeams and not isSmallTeams + isPvE = isRaptors or isScavengers + + if allyTeamCount > 2 then + isFFA = true + elseif allyTeamCount < 2 and not isPvE then + isSandbox = true + elseif allyTeamCount == 2 and not isTeams then + is1v1 = true + end + + if #entirelyHumanAllyTeams == 1 and #Spring.GetTeamList(entirelyHumanAllyTeams[1]) > 1 then + isCoop = true + end + + if holidaysList and Spring.GetModOptions and Spring.GetModOptions().date_day then + local currentDay = Spring.GetModOptions().date_day + local currentMonth = Spring.GetModOptions().date_month + local currentYear = Spring.GetModOptions().date_year + + -- FIXME: This doesn't support events that start and end in different years. + for holiday, dates in pairs(holidaysList) do + local afterStart = false + local beforeEnd = false + if (dates.firstDay.month == currentMonth and dates.firstDay.day <= currentDay) or (dates.firstDay.month < currentMonth) then + afterStart = true + end + if (dates.lastDay.month == currentMonth and dates.lastDay.day >= currentDay) or (dates.lastDay.month > currentMonth) then + beforeEnd = true + end + + if afterStart and beforeEnd then + isHoliday[holiday] = true + else + isHoliday[holiday] = false + end + end + end + + initialized = true + + settings = { + allyTeamCount = allyTeamCount, + allyTeamList = allyTeamList, + playerCount = playerCount, + isSinglePlayer = isSinglePlayer, + is1v1 = is1v1, + isTeams = isTeams, + isBigTeams = isBigTeams, + isSmallTeams = isSmallTeams, + isRaptors = isRaptors, + isScavengers = isScavengers, + isPvE = isPvE, + isCoop = isCoop, + isFFA = isFFA, + isSandbox = isSandbox, + scavTeamID = scavTeamID, + scavAllyTeamID = scavAllyTeamID, + raptorTeamID = raptorTeamID, + raptorAllyTeamID = raptorAllyTeamID, + isHoliday = isHoliday, + } + + return settings +end + +return { + ---Get number of ally teams (humans and AIs, but not Raptors and Scavengers). + GetAllyTeamCount = function() return getSettings().allyTeamCount end, + ---Get ally team list (humans and AIs, but not Raptors and Scavengers). + ---@return integer[] allyTeamList table[i] = allyTeamID + GetAllyTeamList = function () return getSettings().allyTeamList end, + ---@return integer? playerCount Get number of players in a game, nil If it's an AI only game. + GetPlayerCount = function () return getSettings().playerCount end, + Gametype = { + ---@return boolean + IsSinglePlayer = function () return getSettings().isSinglePlayer end, + ---@return boolean + Is1v1 = function () return getSettings().is1v1 end, + ---@return boolean + IsTeams = function () return getSettings().isTeams end, + ---@return boolean + IsBigTeams = function () return getSettings().isBigTeams end, + ---@return boolean + IsSmallTeams = function () return getSettings().isSmallTeams end, + ---@return boolean + IsRaptors = function () return getSettings().isRaptors end, + ---@return boolean + IsScavengers = function () return getSettings().isScavengers end, + ---@return boolean + IsPvE = function () return getSettings().isPvE end, + ---@return boolean + IsCoop = function () return getSettings().isCoop end, + ---@return boolean + IsFFA = function () return getSettings().isFFA end, + ---@return boolean + IsSandbox = function () return getSettings().isSandbox end, + ---@return table? isHoliday Currently running holiday events. + ---See common/holidays.lua for more information. + GetCurrentHolidays = function () return getSettings().isHoliday end, + }, + ---@return integer? scavTeamID Team ID for the scavenger team. + GetScavTeamID = function () return getSettings().scavTeamID end, + ---@return integer? scavAllyTeamID Team ID for the scavenger ally team. + GetScavAllyTeamID = function () return getSettings().scavAllyTeamID end, + ---@return integer? raptorTeamID Team ID for the raptor team. + GetRaptorTeamID = function () return getSettings().raptorTeamID end, + ---@return integer? raptorAllyTeamID Team ID for the raptor ally team. + GetRaptorAllyTeamID = function () return getSettings().raptorAllyTeamID end, + +} + +end + includes["common/holidays.lua"]=function() +if not Spring.GetModOptions then + return +end + +if not Spring.GetModOptions().holiday_events then + return +end + +local modOptions = Spring.GetModOptions() +local currentDay = modOptions.date_day +local currentMonth = modOptions.date_month +local currentYear = modOptions.date_year + +-- Meeus's Julian algorithm Function to calculate Easter Sunday for a given year. Magic. +local function EasterDate(year) + local a = year % 19 + local b = math.floor(year / 100) + local c = year % 100 + local d = math.floor(b / 4) + local e = b % 4 + local f = math.floor((b + 8) / 25) + local g = math.floor((b - f + 1) / 3) + local h = (19 * a + b - d - g + 15) % 30 + local i = math.floor(c / 4) + local k = c % 4 + local l = (32 + 2 * e + 2 * i - h - k) % 7 + local m = math.floor((a + 11 * h + 22 * l) / 451) + local month = math.floor((h + l - 7 * m + 114) / 31) + local day = ((h + l - 7 * m + 114) % 31) + 1 + + return year, month, day +end + +local function GetEasterStartEnd() + local easterYear, easterMonth, easterDay = EasterDate(currentYear) + local firstDay = easterDay - 6 -- We start at Monday before Easter + local firstMonth = easterMonth + local lastDay = easterDay + 1 -- We end at Monday after Easter + local lastMonth = easterMonth + + if easterMonth%2 == 0 then -- Easter is in April - 30 days month + if firstDay < 1 then + firstDay = firstDay + 31 + firstMonth = firstMonth - 1 + end + if lastDay > 30 then + lastDay = lastDay - 30 + lastMonth = lastMonth + 1 + end + + else -- Easter is in March or May - 31 days month + if firstDay < 1 then + firstDay = firstDay + 30 + firstMonth = firstMonth - 1 + end + if lastDay > 31 then + lastDay = lastDay - 31 + lastMonth = lastMonth + 1 + end + end + + return { + firstDay = firstDay, + firstMonth = firstMonth, + lastDay = lastDay, + lastMonth = lastMonth, + easterDay = easterDay, + easterMonth = easterMonth, + } +end + +local EasterEventDates = GetEasterStartEnd() + +-- FIXME: This doesn't support events that start and end in different years. Don't do that for now. Split it into two events if you have to do that. + +-- Spring.Utilities.Gametype.GetCurrentHolidays()["aprilfools"] + +local holidaysList = { + -- Static ----------------------------- + ["aprilfools"] = { + firstDay = { day = 1, month = 4}, + lastDay = { day = 7, month = 4} + }, + ["aprilfools_specialDay"] = { + firstDay = { day = 1, month = 4}, + lastDay = { day = 1, month = 4} + }, + + ["halloween"] = { + firstDay = { day = 17, month = 10}, + lastDay = { day = 31, month = 10} + }, + ["halloween_specialDay"] = { + firstDay = { day = 31, month = 10}, + lastDay = { day = 31, month = 10} + }, + + ["xmas"] = { + firstDay = { day = 12, month = 12}, + lastDay = { day = 31, month = 12} + }, + ["xmas_specialDay"] = { + firstDay = { day = 24, month = 12}, + lastDay = { day = 26, month = 12} + }, + + -- We split these into two events because yes + ["newyearbefore"] = { + firstDay = { day = 31, month = 12}, + lastDay = { day = 31, month = 12} + }, + ["newyearafter"] = { + firstDay = { day = 1, month = 1}, + lastDay = { day = 1, month = 1} + }, + + -- Dynamic ----------------------------- + ["easter"] = { + firstDay = { day = EasterEventDates.firstDay, month = EasterEventDates.firstMonth}, + lastDay = { day = EasterEventDates.lastDay, month = EasterEventDates.lastMonth} + }, + ["easter_specialDay"] = { + firstDay = { day = EasterEventDates.easterDay, month = EasterEventDates.easterMonth}, + lastDay = { day = EasterEventDates.easterDay, month = EasterEventDates.easterMonth} + }, +} + +return holidaysList +end + +Spring.Utilities.Gametype=VFS.Include("common/springutilities/teamfunctions.lua").Gametype +local stock=(function()local widget={} +-------------------------------------------------------------------------------- + +local widget = widget ---@type Widget + +function widget:GetInfo() + return { + name = "Deferred rendering GL4", + version = 3, + desc = "Collects and renders cone, point and beam lights", + author = "Beherith", + date = "2022.06.10", + license = "GNU GPL v2", + layer = -99999990, + enabled = true, + depends = {'gl4'}, + } +end + + +-- Localized functions for performance +local mathFloor = math.floor +local mathMax = math.max +local mathMin = math.min +local mathRandom = math.random +local mathCeil = math.ceil +local mathSqrt = math.sqrt +local mathPow = math.pow + +-- Localized string functions +local stringFind = string.find +local stringFormat = string.format +local stringLower = string.lower + +-- Localized Spring API for performance +local spGetGameFrame = Spring.GetGameFrame +local spEcho = Spring.Echo +local spGetSpectatingState = Spring.GetSpectatingState +local spGetPlayerList = Spring.GetPlayerList +local spGetTeamColor = Spring.GetTeamColor +local spGetPlayerInfo = Spring.GetPlayerInfo +local spIsUnitAllied = Spring.IsUnitAllied +local spGetUnitIsBeingBuilt = Spring.GetUnitIsBeingBuilt +local spGetUnitDefID = Spring.GetUnitDefID +local spGetUnitPieceMap = Spring.GetUnitPieceMap +local spGetWind = Spring.GetWind +local spGetMouseState = Spring.GetMouseState +local spTraceScreenRay = Spring.TraceScreenRay +local spGetModKeyState = Spring.GetModKeyState +local spGetCameraPosition = Spring.GetCameraPosition +local spGetCameraDirection = Spring.GetCameraDirection +local spGetConfigInt = Spring.GetConfigInt +local spSetSunLighting = Spring.SetSunLighting +local spGetAllFeatures = Spring.GetAllFeatures +local spGetFeatureDefID = Spring.GetFeatureDefID +local spGetFeaturePosition = Spring.GetFeaturePosition +local spGetUnitHeight = Spring.GetUnitHeight +local spGetUnitLosState = Spring.GetUnitLosState +local spDiffTimers = Spring.DiffTimers +local spGetTimer = Spring.GetTimer +local spGetTimerMicros = Spring.GetTimerMicros +local spGetDrawFrame = Spring.GetDrawFrame +local spGetFPS = Spring.GetFPS +local spGetConfigString = Spring.GetConfigString +local spGetTeamInfo = Spring.GetTeamInfo +local spGetAllyTeamList = Spring.GetAllyTeamList +local spGetTeamList = Spring.GetTeamList + +-------------------------------- Notes, TODO ---------------------------------- +do +-- GL4 notes: +-- A spot light is a sphere? +-- A cone light is a cone +-- A beam light is a box +-- all prims should be back-face only rendered! + +-- Full documentation: +-- https://docs.google.com/document/d/16mvYJX8WJ8cNjGe_3zhrymTOzPoSkFprr78i_vpH7yA/edit# + +-- Separate VBO's for spheres, cones, beams +-- no geometry shader for now, its kinda pointless, might change my mind later + +-- Sources of light +-- Projectiles + -- beamlasers + -- might get away with not updating their pos each frame? + -- probably not, due to continuous lasers like beamer turret (though that one may be spawned every frame...) + -- TODO: beamttl needs to be fixes, as we are way over spamming these, with up to 3 lights per beam + -- lightning + -- TODO: see if the multi-spawn + -- plasma balls + -- these are actually easy to sim, but might not be worth it, not simmed + -- missiles + -- unsimable, must be queried + -- rockets + -- hard to sim + -- gibs + -- hard to sim +-- Explosions + -- actually spawn once, reasonably easy (separate vbotable for them?) + -- always spherical, should be able to override a param with them + -- +-- mapdefined lights + -- animating them might be a challenge +-- headlights + -- would rock, needs their own vbo for position maybe? + -- or just extend +-- piecelights + -- for thrusters, would be truly epic! + -- fusion lights + +-- Notes on self-point lights: + -- these are probably best billboarded, then depth tested! + +-- would be nice to have: + -- full map-level dense atmosphere + -- explosions should kick up dust + -- simulate wind and other movements + -- at a rez of 32 elmos, dsd would need: + -- 256*256*16 voxels (1 million?) yeesh + +-- Features are not light-attachable at the moment, and shouldnt be as they are immobile, use global lights + +-- preliminary perf: + -- yeah raymarch is expensive! + +--TODO: + -- XX Reload config + -- XX Fix initialize + -- XX convert config to dicts + -- XX load config to tale on init + -- XX noupload pass + -- reload shaderconfig + -- cursorlight + -- ally and own, click sensitive! + -- XX light types should know their vbo? + -- this one is much harder than expected + -- XX initialize config dicts -- DONE + -- XX rework dicts -- DONE + -- XX unitdefidpiecemapcache -- DONE + -- Draw pre-water? + -- optimizations: + -- XX only upload dirty VBOs + -- Smaller, single channel noise texture + -- XX Beam lights double length for projectiles! + -- Some falloff issues result in a bit of overdraw + -- allow for customizable attenuation + -- XX list type configs for events + -- Handle playerchanged -- hasnt crashed yet :P + -- clear every goddamned unit light and buffer + -- FIX SSAO widget for day-night cycle changes - done! + +end + + +local cursorLights +local cursorLightHeight = 35 +local cursorLightParams = { + lightType = 'point', -- or cone or beam + pieceName = nil, -- optional + lightConfig = { + posx = 0, posy = 0, posz = 0, radius = 350, -- (radius is set elsewhere) + r = 1, g = 1, b = 1, a = 0.1, -- (alpha is set elsewhere) + color2r = 0, color2g = 0, color2b = 0, colortime = 0, -- point lights only, colortime in seconds for unit-attache + modelfactor = 0.3, specular = 0.7, scattering = 0, lensflare = 0, + lifetime = 0, sustain = 0, selfshadowing = 0 + } +} + +local cursorLightAlpha = 0.5 +local cursorLightRadius = 0.85 +local cursorLightSelfShadowing = false + +-- This is for the player himself! +local showPlayerCursorLight = false + +local playerCursorLightRadius = 1 +local playerCursorLightBrightness = 1 +local playerCursorLightParams = { + lightType = 'point', -- or cone or beam + pieceName = nil, -- optional + lightConfig = { + posx = 0, posy = 0, posz = 0, radius = 250, + r = 1, g = 0.8, b = 0.6, a = 0.1, -- (alpha is set elsewhere) + color2r = 0, color2g = 0, color2b = 0, colortime = 0, -- point lights only, colortime in seconds for unit-attache + modelfactor = 0.3, specular = 0.4, scattering = 0, lensflare = 0, + lifetime = 0, sustain = 0, selfshadowing = 8 + } +} + + +local teamColors = {} +local function loadTeamColors() + local playerList = spGetPlayerList() + local playerListLen = #playerList + for i = 1, playerListLen do + local playerID = playerList[i] + local teamID = select(4, spGetPlayerInfo(playerID, false)) + local r, g, b = spGetTeamColor(teamID) + teamColors[playerID] = {r, g, b} + end +end +loadTeamColors() + +----------------------------- Localize for optmization ------------------------------------ + +-- Localized GL functions +local glBlending = gl.Blending +local glTexture = gl.Texture +local glCulling = gl.Culling +local glDepthTest = gl.DepthTest +local glDepthMask = gl.DepthMask +local glColor = gl.Color +local glPushMatrix = gl.PushMatrix +local glPopMatrix = gl.PopMatrix +local glTranslate = gl.Translate +local glBillboard = gl.Billboard +local glRect = gl.Rect + +-- Localized GL constants +local GL_BACK = GL.BACK +local GL_SRC_ALPHA = GL.SRC_ALPHA +local GL_ONE = GL.ONE +local GL_ONE_MINUS_SRC_ALPHA = GL.ONE_MINUS_SRC_ALPHA + + +-- Strong: +local spGetProjectilePosition = Spring.GetProjectilePosition +local spGetProjectileVelocity = Spring.GetProjectileVelocity +local spGetProjectileType = Spring.GetProjectileType +local spGetProjectileDefID = Spring.GetProjectileDefID +local spGetGroundHeight = Spring.GetGroundHeight +local spIsSphereInView = Spring.IsSphereInView +local spGetUnitPosition = Spring.GetUnitPosition +local spGetUnitIsDead = Spring.GetUnitIsDead +local spValidUnitID = Spring.ValidUnitID + + +-- Weak: +local spIsGUIHidden = Spring.IsGUIHidden + +local math_max = mathMax +local math_ceil = mathCeil + +local unitName = {} +for udid, ud in pairs(UnitDefs) do + unitName[udid] = ud.name +end + +--------------------------------------------------------------------------------- +--Light falloff functions: http://gamedev.stackexchange.com/questions/56897/glsl-light-attenuation-color-and-intensity-formula + +------------------------------ Light and Shader configurations ------------------ + +local enableProjectileLightFlares = false -- set to true to show lens flare textures on projectile lights + +local unitDefLights +local featureDefLights +local unitEventLights -- Table of lights per unitDefID +local muzzleFlashLights -- one light per weaponDefID +local projectileDefLights -- one light per weaponDefID +local explosionLights -- one light per weaponDefID +local gibLight -- one light for all pieceprojectiles + +local isSinglePlayer = Spring.Utilities.Gametype.IsSinglePlayer() + +local shaderConfig = { + MIERAYLEIGHRATIO = 0.1, -- The ratio of Rayleigh scattering to Mie scattering + RAYMARCHSTEPS = 4, -- must be at least one, this one one of the main quality parameters + USE3DNOISE = 1, -- dont touch this + SURFACECOLORMODULATION = 0.05, -- This specifies how much the lit surfaces color affects direct light blending, 0 is does not effect it, 1.0 is full effect + BLEEDFACTOR = 0.15, -- How much oversaturated color channels will bleed into other color channels. + VOIDWATER = gl.GetMapRendering("voidWater") and 1 or 0, + SCREENSPACESHADOWS = 1, -- set to nil to disable completely + USEQUATERNIONS = Engine.FeatureSupport.transformsInGL4 and "1" or "0", +} + +local radiusMultiplier = 1.0 +local intensityMultiplier = 1.0 +local screenSpaceShadows = 2 + +local isPotatoGpu = false +local gpuMem = (Platform.gpuMemorySize and Platform.gpuMemorySize or 1000) / 1000 +if Platform ~= nil and Platform.gpuVendor == 'Intel' then + isPotatoGpu = true +end +if gpuMem and gpuMem > 0 and gpuMem < 1800 then + isPotatoGpu = true +end +if isPotatoGpu then + screenSpaceShadows = 0 +elseif gpuMem and gpuMem > 0 and gpuMem < 5000 then + screenSpaceShadows = 1 +end + +-- the 3d noise texture used for this shader +local noisetex3dcube = "LuaUI/images/noisetextures/noise64_cube_3.dds" +local blueNoise2D = "LuaUI/images/noisetextures/blue_noise_64.tga" + +--[[ +local examplePointLight = { + lightType = 'point', + pieceName = nil, + alwaysVisible = true, + posx = 0, posy = 0, posz = 0, radius = 0, + r = 1, g = 1, b = 1, a = 1, + color2r = 1, color2g = 1, color2b = 1, colortime = 15, -- point lights only, colortime in seconds for unit-attached + dirx = 0, diry = 0, dirz = 1, theta = 0.5, -- cone lights only, specify direction and half-angle in radians + pos2x = 100, pos2y = 100, pos2z = 100, -- beam lights only, specifies the endpoint of the beam + modelfactor = 1, specular = 1, scattering = 1, lensflare = 1, + lifetime = 0, sustain = 1, selfshadowing = 0 +} +]]-- + +------------------------------ Debug switches ------------------------------ +local autoupdate = false +local debugproj = false +local addrandomlights = false +local skipdraw = false +------------------------------ Data structures and management variables ------------ + +-- These will contain 'global' type lights, ones that dont get updated every frame +local pointLightVBO = {} -- an instanceVBOTable +local coneLightVBO = {} -- an instanceVBOTable +local beamLightVBO = {} -- an instanceVBOTable +local lightVBOMap -- a table of the above 3, keyed by light type, {point = pointLightVBO, ...} + +-- These contain the unitdef defined, cob-instanced and unit event based lights +local unitPointLightVBO = {} -- an instanceVBOTable, with unit-attachment +local unitConeLightVBO = {} -- an instanceVBOTable +local unitBeamLightVBO = {} -- an instanceVBOTable +local unitLightVBOMap -- a table of the above 3, keyed by light type, {point = unitPointLightVBO, ...} + +local unitAttachedLights = {} -- this is a table mapping unitID's to all their attached instanceIDs and vbos + --{unitID = { instanceID = targetVBO, ... }} +local visibleUnits = {} -- this is a proxy for the widget callins, used to ensure we dont add unitscriptlights to units that are not visible + +-- these will be separate, as they need per-frame updates! +local projectilePointLightVBO = {} -- for plasma balls +local projectileBeamLightVBO = {} -- for lasers +local projectileConeLightVBO = {} -- for rockets +local projectileLightVBOMap -- a table of the above 3, keyed by light type + +local cursorPointLightVBO = {} -- this will contain ally and player cursor lights +local predictivePointLightVBO = {} -- dedicated VBO for gadget-fed predictive nano lights + +local lightRemoveQueue = {} -- stores lights that have expired life {gameframe = {lightIDs ... }} + +local unitDefPeiceMapCache = {} -- maps unitDefID to piecemap + +local lightParamTableSize = 29 +local lightCacheTable = {} -- this is a reusable table cache for saving memory later on +for i = 1, lightParamTableSize do lightCacheTable[i] = 0 end +local pieceIndexPos = 25 +local spawnFramePos = 17 +lightCacheTable[13] = 1 --modelfactor_specular_scattering_lensflare +lightCacheTable[14] = 1 +lightCacheTable[15] = 1 +lightCacheTable[16] = 1 + +local lightParamKeyOrder = { -- This table is a 'quick-ish' way of building the lua array from human-readable light parameters + posx = 1, posy = 2, posz = 3, radius = 4, + r = 9, g = 10, b = 11, a = 12, + dirx = 5, diry = 6, dirz = 7, theta = 8, -- specify direction and half-angle in radians + pos2x = 5, pos2y = 6, pos2z = 7, -- beam lights only, specifies the endpoint of the beam + modelfactor = 13, specular = 14, scattering = 15, lensflare = 16, + lifetime = 18, sustain = 19, selfshadowing = 20, -- selfshadowing unused + + -- NOTE THERE ARE 4 MORE UNUSED SLOTS HERE RESERVED FOR FUTURE USE! -- Nope, beherith ate these like a greedy boy + color2r = 21, color2g = 22, color2b = 23, colortime = 24, -- point lights only, colortime in seconds for unit-attached +} + +local autoLightInstanceID = 128000 -- as MAX_PROJECTILES = 128000, so they get unique ones + + +local gameFrame = 0 + +local trackedProjectiles = {} -- used for finding out which projectiles can be culled {projectileID = updateFrame, ...} +local trackedProjectileTypes = {} -- we have to track the types [point, light, cone] of projectile lights for efficient updates +local lastGameFrame = -2 + +local LuaShader = gl.LuaShader +local InstanceVBOTable = gl.InstanceVBOTable + +local uploadAllElements = InstanceVBOTable.uploadAllElements +local popElementInstance = InstanceVBOTable.popElementInstance +local pushElementInstance = InstanceVBOTable.pushElementInstance + +local deferredLightShader = nil + +local shaderSourceCache = { + shaderName = 'Deferred Lights GL4', + vssrcpath = "LuaUI/Shaders/deferred_lights_gl4.vert.glsl", + fssrcpath = "LuaUI/Shaders/deferred_lights_gl4.frag.glsl", + shaderConfig = shaderConfig, + uniformInt = { + mapDepths = 0, + modelDepths = 1, + mapNormals = 2, + modelNormals = 3, + --mapExtra = 4, + --modelExtra = 5, + mapDiffuse = 6, + modelDiffuse = 7, + noise3DCube = 8, + blueNoise = 9, + --heightmapTex = 9, + --mapnormalsTex = 10, + screenSpaceShadows = 16, + }, + uniformFloat = { + pointbeamcone = 0, + --fadeDistance = 3000, + attachedtounitID = 0, + nightFactor = 1.0, + windX = 0.0, + windZ = 0.0, + radiusMultiplier = 1.0, + intensityMultiplier = 1.0, + }, +} +local testprojlighttable = {0,16,0,200, --pos + radius + 0.25, 0.25,0.125, 5, -- color2, colortime + 1.0,1.0,0.5,0.5, -- RGBA + 0.1,1,0.25,1, -- modelfactor_specular_scattering_lensflare + 0,0,200,0, -- spawnframe, lifetime (frames), sustain (frames), selfshadowing + 0,0,0,0, -- color2 + 0, -- pieceIndex + 0,0,0,0 -- instData always 0! + } +local numAddLights = 0 -- how many times AddLight was called + +local spec = spGetSpectatingState() + +---------------------- INITIALIZATION FUNCTIONS ---------------------------------- + + + +local function goodbye(reason) + spEcho('Deferred Lights GL4 exiting:', reason) + widgetHandler:RemoveWidget() +end + +local function createLightInstanceVBO(vboLayout, vertexVBO, numVertices, indexVBO, VBOname, unitIDattribID) + local targetLightVBO = InstanceVBOTable.makeInstanceVBOTable( vboLayout, 16, VBOname, unitIDattribID) + if vertexVBO == nil or targetLightVBO == nil then goodbye("Failed to make "..VBOname) end + targetLightVBO.vertexVBO = vertexVBO + targetLightVBO.numVertices = numVertices + targetLightVBO.indexVBO = indexVBO + targetLightVBO.VAO = InstanceVBOTable.makeVAOandAttach(targetLightVBO.vertexVBO, targetLightVBO.instanceVBO, targetLightVBO.indexVBO) + return targetLightVBO +end + +local function initGL4() + deferredLightShader = LuaShader.CheckShaderUpdates(shaderSourceCache, 0) + if not deferredLightShader then + goodbye("Failed to compile Deferred Lights GL4 shader") + return false + end + -- init the VBO + local vboLayout = { + {id = 3, name = 'worldposrad', size = 4}, + -- for spot, this is center.xyz and radius + -- for cone, this is center.xyz and height + -- for beam this is center.xyz and radiusleft + {id = 4, name = 'worldposrad2', size = 4}, + -- for spot, this is direction.xyz for unitattached, or world anim params + -- for cone, this is direction.xyz and angle in radians + -- for beam this is end.xyz and radiusright + {id = 5, name = 'lightcolor', size = 4}, + -- this is light color rgba for all + {id = 6, name = 'modelfactor_specular_scattering_lensflare', size = 4}, + {id = 7, name = 'otherparams', size = 4}, + -- Otherparams must be spawnframe, dieframe + {id = 8, name = 'color2', size = 4}, + {id = 9, name = 'pieceIndex', size = 1, type = GL.UNSIGNED_INT}, + {id = 10, name = 'instData', size = 4, type = GL.UNSIGNED_INT}, + } + + local pointVBO, _, pointIndexVBO, _ = InstanceVBOTable.makeSphereVBO(8, 4, 1) + pointLightVBO = createLightInstanceVBO(vboLayout, pointVBO, nil, pointIndexVBO, "Point Light VBO") + unitPointLightVBO = createLightInstanceVBO(vboLayout, pointVBO, nil, pointIndexVBO, "Unit Point Light VBO", 10) + cursorPointLightVBO = createLightInstanceVBO(vboLayout, pointVBO, nil, pointIndexVBO, "Cursor Point Light VBO") + predictivePointLightVBO = createLightInstanceVBO(vboLayout, pointVBO, nil, pointIndexVBO, "Predictive Point Light VBO") + projectilePointLightVBO = createLightInstanceVBO(vboLayout, pointVBO, nil, pointIndexVBO, "Projectile Point Light VBO") + + local coneVBO, numConeVertices = InstanceVBOTable.makeConeVBO(12, 1, 1) + coneLightVBO = createLightInstanceVBO(vboLayout, coneVBO, numConeVertices, nil, "Cone Light VBO") + unitConeLightVBO = createLightInstanceVBO(vboLayout, coneVBO, numConeVertices, nil, "Unit Cone Light VBO", 10) + projectileConeLightVBO = createLightInstanceVBO(vboLayout, coneVBO, numConeVertices, nil, "Projectile Cone Light VBO") + + local beamVBO, numBeamVertices = InstanceVBOTable.makeBoxVBO(-1, -1, -1, 1, 1, 1) + beamLightVBO = createLightInstanceVBO(vboLayout, beamVBO, numBeamVertices, nil, "Beam Light VBO") + unitBeamLightVBO = createLightInstanceVBO(vboLayout, beamVBO, numBeamVertices, nil, "Unit Beam Light VBO", 10) + projectileBeamLightVBO = createLightInstanceVBO(vboLayout, beamVBO, numBeamVertices, nil, "Projectile Beam Light VBO") + + projectileLightVBOMap = { point = projectilePointLightVBO, beam = projectileBeamLightVBO, cone = projectileConeLightVBO, } + unitLightVBOMap = { point = unitPointLightVBO, beam = unitBeamLightVBO, cone = unitConeLightVBO, } + lightVBOMap = { point = pointLightVBO, beam = beamLightVBO, cone = coneLightVBO, } + return pointLightVBO and unitPointLightVBO and coneLightVBO and beamLightVBO +end + + +---InitializeLight(lightTable, unitID) +---Takes a light definition table, and tries to check wether its already been initialized, if not, it inits it in-place +---@param lightTable table +---@param unitID number +local function InitializeLight(lightTable, unitID) + if not lightTable.initComplete then -- late init + -- do the table to flattable conversion, if it doesnt exist yet + if not lightTable.lightParamTable then -- perform correct init + local lightparams = {} + for i = 1, lightParamTableSize do lightparams[i] = 0 end + if lightTable.lightConfig == nil then Spring.Debug.TraceFullEcho() end + for paramname, tablepos in pairs(lightParamKeyOrder) do + lightparams[tablepos] = lightTable.lightConfig[paramname] or lightparams[tablepos] + end + lightparams[lightParamKeyOrder.radius] = lightparams[lightParamKeyOrder.radius] + lightparams[lightParamKeyOrder.a] = lightparams[lightParamKeyOrder.a] + lightparams[lightParamKeyOrder.lifetime] = mathFloor( lightparams[lightParamKeyOrder.lifetime] ) + lightTable.lightParamTable = lightparams + lightTable.lightConfig = nil -- never used again after initialization + end + + if unitID then + local unitDefID = spGetUnitDefID(unitID) + if unitDefID and not unitDefPeiceMapCache[unitDefID] then + unitDefPeiceMapCache[unitDefID] = spGetUnitPieceMap(unitID) + end + local pieceMap = unitDefPeiceMapCache[unitDefID] + + if pieceMap == nil or unitDefID == nil then + return false + --Spring.Debug.TraceFullEcho(nil,nil,nil,"InitializeLight, pieceMap == nil") + end + + if pieceMap[lightTable.pieceName] then -- if its not a real piece, it will default to the model worldpos! + lightTable.pieceIndex = pieceMap[lightTable.pieceName] + lightTable.lightParamTable[pieceIndexPos] = lightTable.pieceIndex + end + --spEcho(lightname, lightParams.pieceName, pieceMap[lightParams.pieceName]) + end + + lightTable.initComplete = true + end + return true +end +InitializeLight(cursorLightParams) +InitializeLight(playerCursorLightParams) + +-------------------------------------------------------------------------------- + +---calcLightExpiry(targetVBO, lightParamTable, instanceID) +---Calculates the gameframe that a light might expire at, and if it will, then it places it into the removal queue +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 + +---AddPointLight +---DEPRECATED 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 nil if worldpos, supply valid piece index if you want to attach it to something, 0 attaches to world offset +---@param targetVBO nil if you want to automatically add it to pointlightvbo/unitPointLightVBO, specify other if you do not +---@param px_or_table float position X or a valid table of parameters +---@param py float Y position of the light +---@param pz float Z position of the light +---@param radius float radius position of the light +---@param r float red color of the light (0-1), but can go higher +---@param g float green color of the light (0-1), but can go higher +---@param b float blue color of the light (0-1), but can go higher +---@param a float global brightness modifier of the light (0-1), but can go higher +---@param r2 float red secondary color of the light (0-1), but can go higher +---@param g2 float green secondary color of the light (0-1), but can go higher +---@param b2 float blue secondary color of the light (0-1), but can go higher +---@param colortime float time in seconds for the light to transition to secondary color. For unitlights, specify in frames the period you want +---@param modelfactor float how much more light gets applied to models vs terrain (default 1) +---@param specular float how strong specular highlights of this light are (default 1) +---@param scattering float how strong the atmospheric scattering effect is (default 1) +---@param lensflare float intensity of the lens flare effect( default 1) +---@param spawnframe float the gameframe the light was spawned in (for anims, in frames, default current game frame) +---@param lifetime float how many frames the light will live, with decreasing brightness +---@param sustain float how much sustain time the light will have at its original brightness (in game frames) +---@param selfshadowing int what further type of animation will be used (0 is default 1 is for screen space shadow) +---@return instanceID for future reuse +local function AddPointLight(instanceID, unitID, pieceIndex, targetVBO, px_or_table, py, pz, radius, r,g,b,a, r2,g2,b2, colortime, + modelfactor, specular, scattering, lensflare, spawnframe, lifetime, sustain, selfshadowing) + + if instanceID == nil then + autoLightInstanceID = autoLightInstanceID + 1 + instanceID = autoLightInstanceID + end + --spEcho("AddPointLight",instanceID) + local noUpload + local lightparams + if type(px_or_table) ~= "table" then + lightparams = lightCacheTable + lightparams[1] = px_or_table or 0 + lightparams[2] = py or 0 + lightparams[3] = pz or 0 + lightparams[4] = radius or 100 + lightparams[5] = r2 or 0 + lightparams[6] = g2 or 0 + lightparams[7] = b2 or 0 + lightparams[8] = colortime or 0 + + lightparams[9] = r or 1 + lightparams[10] = g or 1 + lightparams[11] = b or 1 + lightparams[12] = a or 1 + + lightparams[13] = modelfactor or 1 + lightparams[14] = specular or 1 + lightparams[15] = scattering or 1 + lightparams[16] = lensflare or 1 + + lightparams[spawnFramePos] = spawnframe or gameFrame + lightparams[18] = lifetime or 0 + lightparams[19] = sustain or 1 + lightparams[20] = selfshadowing or 0 + lightparams[21] = r2 or 0 + lightparams[22] = g2 or 0 + lightparams[23] = b2 or 0 + lightparams[24] = colortime or 0 + lightparams[pieceIndexPos] = pieceIndex or 0 + else + lightparams = px_or_table + lightparams[spawnFramePos] = gameFrame -- this might be problematic, as we will be modifying a table passed by reference! + noUpload = py + end + if targetVBO == nil then targetVBO = pointLightVBO end + if unitID then targetVBO = unitPointLightVBO end + instanceID = pushElementInstance(targetVBO, lightparams, instanceID, true, noUpload, unitID) + calcLightExpiry(targetVBO, lightparams, instanceID) -- This will add lights that have >0 lifetime to the removal queue + return instanceID +end + +local function AddRandomDecayingPointLight() + AddPointLight(nil,nil,nil, nil, + Game.mapSizeX * 0.5 + mathRandom()*2000, + spGetGroundHeight(Game.mapSizeX * 0.5,Game.mapSizeZ * 0.5) + 50, + Game.mapSizeZ * 0.5, + 250, + 1,0,0,1, + 0,1,0,60, + 1,1,1,1, + gameFrame, 100, 20, 1) + --spEcho("AddRandomDecayingPointLight", instanceID) + + AddPointLight(nil,nil,nil,nil, + Game.mapSizeX * 0.5 + mathRandom()*2000, + spGetGroundHeight(Game.mapSizeX * 0.5,Game.mapSizeZ * 0.5) + 50, + Game.mapSizeZ * 0.5 + 400, + 250, + 1,1,1,1, + 1,0.5,0.2,5, + 1,1,1,1, + gameFrame, 30, 0.2, 1) + --spEcho("AddRandomExplosionPointLight", instanceID) + + AddPointLight(nil,nil,nil,nil, + Game.mapSizeX * 0.5 + mathRandom()*2000, + spGetGroundHeight(Game.mapSizeX * 0.5,Game.mapSizeZ * 0.5) + 50, + Game.mapSizeZ * 0.5 + 800, + 250, + 0,0,0,1, -- start from black + 1,0.5,0.25,3, -- go to yellow in 3 frames + 1,1,1,1, + gameFrame, 100, 20, 1) -- Sustain peak brightness for 20 frames, and go down to 0 brightness by 100 frames. + --spEcho("AddRandomDecayingPointLight", instanceID) +end + +---AddBeamLight +---DEPRECATED 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 nil if worldpos, supply valid piece index if you want to attach it to something, 0 attaches to world offset +---@param targetVBO nil if you want to automatically add it to pointlightvbo/unitPointLightVBO, specify other if you do not +---@param px_or_table float position X or a valid table of parameters +---@param py float Y position of the light +---@param pz float Z position of the light +---@param radius float radius position of the light +---@param r float red color of the light (0-1), but can go higher +---@param g float green color of the light (0-1), but can go higher +---@param b float blue color of the light (0-1), but can go higher +---@param a float global brightness modifier of the light (0-1), but can go higher +---@param sx float pos of the endpoint of the beam +---@param sy float pos of the endpoint of the beam +---@param sz float pos of the endpoint of the beam +---@param r2 float radius2 is unused at the moment +---@param modelfactor float how much more light gets applied to models vs terrain (default 1) +---@param specular float how strong specular highlights of this light are (default 1) +---@param scattering float how strong the atmospheric scattering effect is (default 1) +---@param lensflare float intensity of the lens flare effect( default 1) +---@param spawnframe float the gameframe the light was spawned in (for anims, in frames, default current game frame) +---@param lifetime float how many frames the light will live, with decreasing brightness +---@param sustain float how much sustain time the light will have at its original brightness (in game frames) +---@param selfshadowing int what further type of animation will be used +---@return instanceID for future reuse +local function AddBeamLight(instanceID, unitID, pieceIndex, targetVBO, px_or_table, py, pz, radius, r,g,b,a, sx, sy, sz, r2, colortime, + modelfactor, specular, scattering, lensflare, spawnframe, lifetime, sustain, selfshadowing) + + if instanceID == nil then + autoLightInstanceID = autoLightInstanceID + 1 + instanceID = autoLightInstanceID + end + + local noUpload + local lightparams + if type(px_or_table) ~= "table" then + lightparams = lightCacheTable + lightparams[1] = px_or_table or 0 + lightparams[2] = py or 0 + lightparams[3] = pz or 0 + lightparams[4] = radius or 100 + lightparams[5] = sx or 0 + lightparams[6] = sy or 0 + lightparams[7] = sz or 0 + lightparams[8] = radius or 100 + + lightparams[9] = r or 1 + lightparams[10] = g or 1 + lightparams[11] = b or 1 + lightparams[12] = a or 1 + + lightparams[13] = modelfactor or 1 + lightparams[14] = specular or 1 + lightparams[15] = scattering or 1 + lightparams[16] = lensflare or 1 + + lightparams[spawnFramePos] = spawnframe or gameFrame + lightparams[18] = lifetime or 0 + lightparams[19] = sustain or 1 + lightparams[20] = selfshadowing or 0 + lightparams[21] = 0 --unused + lightparams[22] = 0 --unused + lightparams[23] = 0 --unused + lightparams[24] = 0 --unused + lightparams[pieceIndexPos] = pieceIndex or 0 + else + lightparams = px_or_table + lightparams[spawnFramePos] = gameFrame + noUpload = py + end + + if targetVBO == nil then targetVBO = beamLightVBO end + if unitID then targetVBO = unitBeamLightVBO end + instanceID = pushElementInstance(targetVBO, lightparams, instanceID, true, noUpload, unitID) + calcLightExpiry(targetVBO, lightparams, instanceID) -- This will add lights that have >0 lifetime to the removal queue + return instanceID +end + +---AddConeLight +---DEPRECATED! 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 nil if worldpos, supply valid piece index if you want to attach it to something, 0 attaches to world offset +---@param targetVBO nil if you want to automatically add it to pointlightvbo/unitPointLightVBO, specify other if you do not +---@param px_or_table float position X or a valid table of parameters +---@param py float Y position of the light +---@param pz float Z position of the light +---@param radius float height of the cone +---@param r float red color of the light (0-1), but can go higher +---@param g float green color of the light (0-1), but can go higher +---@param b float blue color of the light (0-1), but can go higher +---@param a float global brightness modifier of the light (0-1), but can go higher +---@param dx float dirx of the cone +---@param dy float diry of the cone +---@param dz float dirz of the cone +---@param theta float half-angle of the cone in radians +---@param modelfactor float how much more light gets applied to models vs terrain (default 1) +---@param specular float how strong specular highlights of this light are (default 1) +---@param scattering float how strong the atmospheric scattering effect is (default 1) +---@param lensflare float intensity of the lens flare effect( default 1) +---@param spawnframe float the gameframe the light was spawned in (for anims, in frames, default current game frame) +---@param lifetime float how many frames the light will live, with decreasing brightness +---@param sustain float how much sustain time the light will have at its original brightness (in game frames) +---@param selfshadowing int what further type of animation will be used +---@return instanceID for future reuse +local function AddConeLight(instanceID, unitID, pieceIndex, targetVBO, px_or_table, py, pz, radius, r,g,b,a, dx,dy,dz,theta, colortime, + modelfactor, specular, scattering, lensflare, spawnframe, lifetime, sustain, selfshadowing) + + if instanceID == nil then + autoLightInstanceID = autoLightInstanceID + 1 + instanceID = autoLightInstanceID + end + local noUpload + local lightparams + if type(px_or_table) ~= "table" then + lightparams = lightCacheTable + lightparams[1] = px_or_table or 0 + lightparams[2] = py or 0 + lightparams[3] = pz or 0 + lightparams[4] = radius or 100 + lightparams[5] = dx or 0 + lightparams[6] = dy or 0 + lightparams[7] = dz or 0 + lightparams[8] = theta or 0.5 + + lightparams[9] = r or 1 + lightparams[10] = g or 1 + lightparams[11] = b or 1 + lightparams[12] = a or 1 + + lightparams[13] = modelfactor or 1 + lightparams[14] = specular or 1 + lightparams[15] = scattering or 1 + lightparams[16] = lensflare or 1 + + lightparams[spawnFramePos] = spawnframe or gameFrame + lightparams[18] = lifetime or 0 + lightparams[19] = sustain or 1 + lightparams[20] = selfshadowing or 0 + lightparams[21] = 0 -- RESERVED + lightparams[22] = 0 --RESERVED + lightparams[23] = 0 --RESERVED + lightparams[24] = 0 --RESERVED + lightparams[pieceIndexPos] = pieceIndex or 0 + else + lightparams = px_or_table + lightparams[spawnFramePos] = gameFrame + noUpload = py + end + + if targetVBO == nil then targetVBO = coneLightVBO end + if unitID then targetVBO = unitConeLightVBO end + instanceID = pushElementInstance(targetVBO, lightparams, instanceID, true, noUpload, unitID) + calcLightExpiry(targetVBO, lightparams, instanceID) -- This will add lights that have >0 lifetime to the removal queue + return instanceID +end + +---updateLightPosition(lightVBO, instanceID, posx, posy, posz, radius, p2x, p2y, p2z, theta) +---This function is for internal use only, to update the position of a light. +---Only use if you know the consequences of updating a VBO in-place! +local function updateLightPosition(lightVBO, instanceID, posx, posy, posz, radius, p2x, p2y, p2z, theta) + local instanceIndex = lightVBO.instanceIDtoIndex[instanceID] + if instanceIndex == nil then return nil end + instanceIndex = (instanceIndex - 1 ) * lightVBO.instanceStep + local instData = lightVBO.instanceData + if posx then + instData[instanceIndex + 1] = posx + instData[instanceIndex + 2] = posy + instData[instanceIndex + 3] = posz + end + if radius then instData[instanceIndex + 4] = radius end + + if p2x then + instData[instanceIndex + 5] = p2x + instData[instanceIndex + 6] = p2y + instData[instanceIndex + 7] = p2z + end + if theta then instData[instanceIndex + 8] = theta end + lightVBO.dirty = true + return instanceIndex +end + +-- multiple lights per unitdef/piece are possible, as the lights are keyed by lightname + +local function AddStaticLightsForUnit(unitID, unitDefID, noUpload, reason) + if unitDefLights[unitDefID] then + if spGetUnitIsBeingBuilt(unitID) then return end + local unitDefLight = unitDefLights[unitDefID] + if unitDefLight.initComplete ~= true then -- late init + for lightname, lightParams in pairs(unitDefLight) do + if not InitializeLight(lightParams, unitID) then return end + end + unitDefLight.initComplete = true + end + for lightname, lightParams in pairs(unitDefLight) do + if lightname ~= 'initComplete' then + local targetVBO = unitLightVBOMap[lightParams.lightType] + + if (not spec) and lightParams.alliedOnly == true and spIsUnitAllied(unitID) == false then return end + AddLight(tostring(unitID) .. lightname, unitID, lightParams.pieceIndex, targetVBO, lightParams.lightParamTable, noUpload) + end + end + end +end + +---RemoveUnitAttachedLights(unitID, instanceID) +---Removes all or 1 light attached to a unit +---@param unitID the unit to remove lights from +---@param instanceID which light to remove, if nil, then all lights will be removed +---@returns the number of lights that got removed +local function RemoveUnitAttachedLights(unitID, instanceID) + local numremoved = 0 + if unitAttachedLights[unitID] then + if instanceID and unitAttachedLights[unitID][instanceID] then + popElementInstance(unitAttachedLights[unitID][instanceID],instanceID) + numremoved = numremoved + 1 + unitAttachedLights[unitID][instanceID] = nil + else + for instanceID, targetVBO in pairs(unitAttachedLights[unitID]) do + if targetVBO.instanceIDtoIndex[instanceID] then + numremoved = numremoved + 1 + popElementInstance(targetVBO,instanceID) + else + --spEcho("Light attached to unit no longer is in targetVBO", unitID, instanceID, targetVBO.myName) + end + end + --spEcho("Removed lights from unitID", unitID, numremoved, successes) + unitAttachedLights[unitID] = nil + end + else + --spEcho("RemoveUnitAttachedLights: No lights attached to", unitID) + end + return numremoved +end + +---RemoveLight(lightshape, instanceID, unitID) +---Remove a light +---@param lightshape string 'point'|'beam'|'cone' +---@param instanceID any the ID of the light to remove +---@param unitID number make this non-nil to remove it from a unit +---@returns the same instanceID on success, nil if the light was not found +local function RemoveLight(lightshape, instanceID, unitID, noUpload) + if unitID then + if unitAttachedLights[unitID] and unitAttachedLights[unitID][instanceID] then + local targetVBO = unitAttachedLights[unitID][instanceID] + unitAttachedLights[unitID][instanceID] = nil + return popElementInstance(targetVBO, instanceID) + else + spEcho("RemoveLight tried to remove a non-existing unitlight", lightshape, instanceID, unitID) + end + elseif lightshape then + if lightVBOMap[lightshape].instanceIDtoIndex[instanceID] then + return popElementInstance(lightVBOMap[lightshape], instanceID) + else + if not noUpload then + if type(instanceID) == "string" and (not string.find(instanceID, "FeatureCreated", nil, true)) then + spEcho("RemoveLight tried to remove a non-existing light", lightshape, instanceID, unitID) + end + end + end + else + spEcho("RemoveLight tried to remove a non-existing light", lightshape, instanceID, unitID) + end + return nil +end + + +function AddRandomLight(which) + local gf = gameFrame + local radius = mathRandom() * 150 + 50 + local posx = Game.mapSizeX * mathRandom() * 1.0 + local posz = Game.mapSizeZ * mathRandom() * 1.0 + local posy = spGetGroundHeight(posx, posz) + mathRandom() * 0.5 * radius + -- randomize color + local r = mathRandom() + 0.1 --r + local g = mathRandom() + 0.1 --g + local b = mathRandom() + 0.1 --b + local a = mathRandom() * 1.0 + 0.5 -- intensity or alpha + + lightCacheTable[13] = 1 -- modelfactor + lightCacheTable[14] = 1 -- specular + lightCacheTable[15] = 1 -- rayleigh-mie + lightCacheTable[16] = 1 -- lensflare + + + if which < 0.33 then -- point + AddPointLight(nil, nil, nil, nil, posx, posy, posz, radius, r,g,b,a) + elseif which < 0.66 then -- beam + local s = (mathRandom() - 0.5) * 500 + local t = (mathRandom() + 0.5) * 100 + local u = (mathRandom() - 0.5) * 500 + AddBeamLight(nil,nil,nil,nil, posx, posy , posz, radius, r,g,b,a, posx + s, posy + t, posz + u) + else -- cone + local s = (mathRandom() - 0.5) * 2 + local t = (mathRandom() + 0.0) * -1 + local u = (mathRandom() - 0.5) * 2 + local lenstu = 1.0 / mathSqrt(s*s + t*t + u*u) + local theta = mathRandom() * 0.9 + AddConeLight(nil,nil,nil,nil, posx, posy + radius, posz, 3* radius, r,g,b,a,s * lenstu, t * lenstu, u * lenstu, theta) + end + +end + + +local function LoadLightConfig() + local success, result = pcall(VFS.Include, 'luaui/configs/DeferredLightsGL4config.lua') + --spEcho("Loading GL4 light config", success, result) + if success then + --spEcho("Loaded GL4 light config") + unitDefLights = result.unitDefLights + unitEventLights = result.unitEventLights + featureDefLights = result.featureDefLights + --projectileDefLights = result.projectileDefLights + + else + spEcho("Failed to load GL4 Unit light config", success, result) + end + + local success2, result2 = pcall(VFS.Include, 'luaui/configs/DeferredLightsGL4WeaponsConfig.lua') + --spEcho("Loading GL4 weapon light config", success2, result2) + if success2 then + gibLight = result2.gibLight + InitializeLight(gibLight) + + muzzleFlashLights = result2.muzzleFlashLights + for weaponID, lightTable in pairs(muzzleFlashLights) do + InitializeLight(lightTable) + end + + explosionLights = result2.explosionLights + for weaponID, lightTable in pairs(explosionLights) do + InitializeLight(lightTable) + end + + projectileDefLights = result2.projectileDefLights + for weaponID, lightTable in pairs(projectileDefLights) do + InitializeLight(lightTable) + if not enableProjectileLightFlares and lightTable.lightParamTable then + lightTable.lightParamTable[16] = 0 -- lensflare + end + end + else + spEcho("Failed to load GL4 weapon light config", success2, result2) + end + return success and success2 +end + +local nightFactor = 1 --0.33 +local unitNightFactor = 1 -- applied above nightFactor default 1.2 +local adjustfornight = {'unitAmbientColor', 'unitDiffuseColor', 'unitSpecularColor','groundAmbientColor', 'groundDiffuseColor', 'groundSpecularColor' } + + +local targetable = {} +for wdid, wd in pairs(WeaponDefs) do + if wd.targetable then + targetable[wdid] = true + end +end + +function widget:VisibleExplosion(px, py, pz, weaponID, ownerID) + if targetable[weaponID] and py-300 > Spring.GetGroundHeight(px, pz) then -- dont add light to (likely) intercepted explosions (mainly to curb nuke flashes) + return + end + if explosionLights[weaponID] then + local lightParamTable = explosionLights[weaponID].lightParamTable + if explosionLights[weaponID].alwaysVisible or spIsSphereInView(px,py,pz, lightParamTable[4]) then + local groundHeight = spGetGroundHeight(px,pz) or 1 + py = math_max(groundHeight + (explosionLights[weaponID].yOffset or 0), py) + lightParamTable[1] = px + lightParamTable[2] = py + lightParamTable[3] = pz + AddLight(nil, nil, nil, pointLightVBO, lightParamTable) --(instanceID, unitID, pieceIndex, targetVBO, lightparams, noUpload) + end + end +end + +function widget:Barrelfire(px, py, pz, weaponID, ownerID) + if muzzleFlashLights[weaponID] then + local lightParamTable = muzzleFlashLights[weaponID].lightParamTable + if muzzleFlashLights[weaponID].alwaysVisible or spIsSphereInView(px,py,pz, lightParamTable[4]) then + lightParamTable[1] = px + lightParamTable[2] = py + lightParamTable[3] = pz + AddLight(nil, nil, nil, pointLightVBO, lightParamTable) --(instanceID, unitID, pieceIndex, targetVBO, lightparams, noUpload) + end + end +end + +local function UnitScriptLight(unitID, unitDefID, lightIndex, param) + if spValidUnitID(unitID) and spGetUnitIsDead(unitID) == false and visibleUnits[unitID] and unitEventLights.UnitScriptLights[unitDefID] and unitEventLights.UnitScriptLights[unitDefID][lightIndex] then + local lightTable = unitEventLights.UnitScriptLights[unitDefID][lightIndex] + if not lightTable.alwaysVisible then + local px,py,pz = spGetUnitPosition(unitID) + if px == nil or spIsSphereInView(px,py,pz, lightTable[4]) == false then return end + end + if (not spec) and lightTable.alliedOnly == true and spIsUnitAllied(unitID) == false then return end + if lightTable.initComplete == nil then InitializeLight(lightTable, unitID) end + local instanceID = tostring(unitID) .. "_" .. tostring(unitName[unitDefID]) .. "UnitScriptLight" .. tostring(lightIndex) .. "_" .. tostring(param) + AddLight(instanceID, unitID, lightTable.pieceIndex, unitLightVBOMap[lightTable.lightType], lightTable.lightParamTable) + end +end + +local function GetLightVBO(vboName) + if vboName == 'cursorPointLightVBO' then return cursorPointLightVBO end + return nil +end + +function widget:PlayerChanged(playerID) + spec = spGetSpectatingState() + + local _, _, isSpec, teamID = spGetPlayerInfo(playerID, false) + local r, g, b = spGetTeamColor(teamID) + if isSpec then + teamColors[playerID] = { 1, 1, 1 } + elseif r and g and b then + teamColors[playerID] = { r, g, b } + end + if cursorLights and cursorLights[playerID] and isSpec then + popElementInstance(cursorPointLightVBO, cursorLights[playerID]) + cursorLights[playerID] = nil + end +end + + +function widget:VisibleUnitAdded(unitID, unitDefID, unitTeam) + visibleUnits[unitID] = unitDefID + AddStaticLightsForUnit(unitID, unitDefID, false, "VisibleUnitAdded") +end + +function widget:VisibleUnitsChanged(extVisibleUnits, extNumVisibleUnits) + InstanceVBOTable.clearInstanceTable(unitPointLightVBO) -- clear all instances + InstanceVBOTable.clearInstanceTable(unitBeamLightVBO) -- clear all instances + InstanceVBOTable.clearInstanceTable(unitConeLightVBO) -- clear all instances + visibleUnits = {} + + for unitID, unitDefID in pairs(extVisibleUnits) do + visibleUnits[unitID] = unitDefID + AddStaticLightsForUnit(unitID, unitDefID, true, "VisibleUnitsChanged") -- add them with noUpload = true + end + uploadAllElements(unitPointLightVBO) -- upload them all + uploadAllElements(unitBeamLightVBO) -- upload them all + uploadAllElements(unitConeLightVBO) -- upload them all +end + +function widget:VisibleUnitRemoved(unitID) -- remove all the lights for this unit + --if debugmode then Spring.Debug.TraceEcho("remove",unitID,reason) end + RemoveUnitAttachedLights(unitID) + visibleUnits[unitID] = nil +end + +function widget:Shutdown() + widgetHandler:RemoveAction("dlgl4stats", "t") + widgetHandler:RemoveAction("dlgl4skipdraw", "t") + WG['lightsgl4'] = nil + widgetHandler:DeregisterGlobal('AddPointLight') + widgetHandler:DeregisterGlobal('AddBeamLight') + widgetHandler:DeregisterGlobal('AddConeLight') + widgetHandler:DeregisterGlobal('AddLight') + widgetHandler:DeregisterGlobal('RemoveLight') + widgetHandler:DeregisterGlobal('GetLightVBO') + + widgetHandler:DeregisterGlobal('EnvLightningPointLight') + widgetHandler:DeregisterGlobal('EnvNanoBallisticLightSpawn') + widgetHandler:DeregisterGlobal('EnvNanoBallisticLightCorrect') + widgetHandler:DeregisterGlobal('EnvNanoBallisticLightFade') + widgetHandler:DeregisterGlobal('EnvNanoBallisticLightRemove') + + deferredLightShader:Delete() + local ram = 0 + for lighttype, vbo in pairs(unitLightVBOMap) do ram = ram + vbo:Delete() end + for lighttype, vbo in pairs(projectileLightVBOMap) do ram = ram + vbo:Delete() end + for lighttype, vbo in pairs(lightVBOMap) do ram = ram + vbo:Delete() end + ram = ram + cursorPointLightVBO:Delete() + ram = ram + predictivePointLightVBO:Delete() + + --spEcho("DLGL4 ram usage MB = ", ram / 1000000) + --spEcho("featureDefLights", table.countMem(featureDefLights)) + --spEcho("unitEventLights", table.countMem(unitEventLights)) + --spEcho("unitDefLights", table.countMem(unitDefLights)) + --spEcho("projectileDefLights", table.countMem(projectileDefLights)) + --spEcho("explosionLights", table.countMem(explosionLights)) + + -- Note, these must be nil'ed manually, because + -- tables included from VFS.Include dont get GC'd unless specifically nil'ed + unitDefLights = nil + featureDefLights = nil + unitEventLights = nil + muzzleFlashLights = nil + projectileDefLights = nil + explosionLights = nil + gibLight = nil + + --collectgarbage("collect") + --collectgarbage("collect") + +end + +local windX = 0 +local windZ = 0 + +function widget: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 + +-- This should simplify adding all kinds of events +-- You are permitted to define as many lights as you wish, but its probably stupid to do so. +local function eventLightSpawner(eventName, unitID, unitDefID, teamID) + if spValidUnitID(unitID) and spGetUnitIsDead(unitID) == false and unitEventLights[eventName] then + if unitEventLights[eventName] then + -- get the default event if it is defined + local lightList = unitEventLights[eventName][unitDefID] or unitEventLights[eventName]['default'] + if lightList then + for lightname, lightTable in pairs(lightList) do + local visible = lightTable.alwaysVisible + local px,py,pz = spGetUnitPosition(unitID) + if not visible then + if px and spIsSphereInView(px,py,pz, lightTable[4]) then visible = true end + end + + -- bail if only for allies + if (not spec) and lightTable.alliedOnly == true and spIsUnitAllied(unitID) == false then + visible = false + end + + -- bail if unable to initialize light + if not lightTable.initComplete then + if not InitializeLight(lightTable, unitID) then + visible = false + end + end + + -- bail if invalid unitID wants a unit-attached light + if lightTable.pieceName and (visibleUnits[unitID] == nil) then + visible = false + end + + if visible then + --if lightTable.aboveUnit then lightTable.lightParamTable end + local lightParamTable = lightTable.lightParamTable + if lightTable.pieceName then + if lightTable.aboveUnit then -- if its above the unit, then add the aboveunit offset to the units height too! + -- this is done via a quick copy of the table + for i=1, lightParamTableSize do lightCacheTable[i] = lightParamTable[i] end + local unitHeight = spGetUnitHeight(unitID) + if unitHeight == nil then + local losstate = spGetUnitLosState(unitID) + spEcho("Unitheight is nil for unitID", unitID, "unitDefName", unitName[unitDefID], eventName, lightname, 'losstate', losstate and losstate.los) + end + + lightCacheTable[2] = lightCacheTable[2] + lightTable.aboveUnit + (unitHeight or 0) + lightParamTable = lightCacheTable + end + AddLight(eventName .. tostring(unitID) .. lightname, unitID, lightTable.pieceIndex, unitLightVBOMap[lightTable.lightType], lightParamTable) + else + for i=1, lightParamTableSize do lightCacheTable[i] = lightParamTable[i] end + lightCacheTable[1] = lightCacheTable[1] + px + lightCacheTable[2] = lightParamTable[2] + py + ((lightTable.aboveUnit and spGetUnitHeight(unitID)) or 0) + lightCacheTable[3] = lightCacheTable[3] + pz + AddLight(eventName .. tostring(unitID) .. lightname, nil, lightTable.pieceIndex, lightVBOMap[lightTable.lightType], lightCacheTable) + end + end + + end + end + end + end +end + +-- Below are the registered spawners for events +function widget:UnitIdle(unitID, unitDefID, teamID) -- oh man we need a sane way to handle height :D + eventLightSpawner("UnitIdle", unitID, unitDefID, teamID) +end +function widget:UnitFinished(unitID, unitDefID, teamID) + eventLightSpawner("UnitFinished", unitID, unitDefID, teamID) +end +function widget:UnitCreated(unitID, unitDefID, teamID) + eventLightSpawner("UnitCreated", unitID, unitDefID, teamID) +end +function widget:UnitFromFactory(unitID, unitDefID, unitTeam, factID, factDefID, userOrders) + eventLightSpawner("UnitFromFactory", unitID, unitDefID, teamID) -- i have no idea of the differences here + eventLightSpawner("UnitFromFactoryBuilder", factID, factDefID, teamID) +end +function widget:UnitDestroyed(unitID, unitDefID, teamID) -- dont do piece-attached lights here! + eventLightSpawner("UnitDestroyed", unitID, unitDefID, teamID) +end +function widget:CrashingAircraft(unitID, unitDefID, teamID) + RemoveUnitAttachedLights(unitID) +end + +-- THIS ONE DOESNT WORK, some shit is being pulled and i cant get the unit height of the unit being taken here! +--function widget:UnitTaken(unitID, unitDefID, teamID) + --eventLightSpawner("UnitTaken", unitID, unitDefID, teamID) +--end +function widget:UnitGiven(unitID, unitDefID, teamID) + eventLightSpawner("UnitGiven", unitID, unitDefID, teamID) +end +function widget:UnitCloaked(unitID, unitDefID, teamID) + eventLightSpawner("UnitCloaked", unitID, unitDefID, teamID) +end +function widget:UnitDecloaked(unitID, unitDefID, teamID) + eventLightSpawner("UnitDecloaked", unitID, unitDefID, teamID) +end +function widget:UnitMoveFailed(unitID, unitDefID, teamID) + eventLightSpawner("UnitMoveFailed", unitID, unitDefID, teamID) +end + +function widget:StockpileChanged(unitID, unitDefID, teamID, weaponNum, oldCount, newCount) + if newCount > oldCount then + eventLightSpawner("StockpileChanged", unitID, unitDefID, teamID) + end +end + +function widget:FeatureCreated(featureID, noUpload) + if type(noUpload) ~= 'boolean' then noUpload = nil end + -- TODO: Allow team-colored feature lights by getting teamcolor and putting it into lightCacheTable + local featureDefID = spGetFeatureDefID(featureID) + if featureDefLights[featureDefID] then + for lightname, lightTable in pairs(featureDefLights[featureDefID]) do + if not lightTable.initComplete then InitializeLight(lightTable) end + local px, py, pz = spGetFeaturePosition(featureID) + if px and featureID%(lightTable.fraction or 1 ) == 0 then + + local lightParamTable = lightTable.lightParamTable + for i=1, lightParamTableSize do lightCacheTable[i] = lightParamTable[i] end + lightCacheTable[1] = lightParamTable[1] + px + lightCacheTable[2] = lightParamTable[2] + py + lightCacheTable[3] = lightParamTable[3] + pz + AddLight(tostring(featureID) .. lightname, nil, nil, lightVBOMap[lightTable.lightType], lightCacheTable, noUpload) + end + end + end +end + +function widget:FeatureDestroyed(featureID, noUpload) + if type(noUpload) ~= 'boolean' then noUpload = nil end + local featureDefID = spGetFeatureDefID(featureID) + if featureDefLights[featureDefID] then + for lightname, lightTable in pairs(featureDefLights[featureDefID]) do + if featureID % (lightTable.fraction or 1 ) == 0 then + RemoveLight(lightTable.lightType, tostring(featureID) .. lightname, nil, noUpload) + end + end + end +end + +-- Beam type projectiles are indeed an oddball, as they live for exactly 3 frames, no? + +local function PrintProjectileInfo(projectileID) + local px, py, pz = spGetProjectilePosition(projectileID) + local weapon, piece = Spring.GetProjectileType(projectileID) + local weaponDefID = weapon and Spring.GetProjectileDefID ( projectileID ) + Spring.Debug.TraceFullEcho() +end + +local defaultProjectileLightDelayWaterline = 2 +local defaultProjectileLightDelayFrames = 0 +local delayedProjectileLightFrames = {} +local function ShouldDelayProjectileLight(projectileLight, projectileID, py) + if not projectileLight or not projectileLight.delayUntilSubmerged then + return false + end + + -- Skipped projectiles are intentionally not tracked yet, so this can try again + -- on later frames after they enter the water. + if not py or py > (projectileLight.delayWaterline or defaultProjectileLightDelayWaterline) then + delayedProjectileLightFrames[projectileID] = nil + return true + end + + local delayFrames = projectileLight.delayFrames or defaultProjectileLightDelayFrames + if delayFrames <= 0 then + return false + end + + local readyFrame = delayedProjectileLightFrames[projectileID] + if not readyFrame then + readyFrame = gameFrame + delayFrames + delayedProjectileLightFrames[projectileID] = readyFrame + end + if gameFrame < readyFrame then + return true + end + + delayedProjectileLightFrames[projectileID] = nil + return false +end + + +local function updateProjectileLights(newgameframe) + local nowprojectiles = Spring.GetVisibleProjectiles() + gameFrame = spGetGameFrame() + local newgameframe = true + if gameFrame == lastGameFrame then newgameframe = false end + --spEcho(gameFrame, lastGameFrame, newgameframe) + lastGameFrame = gameFrame + -- turn off uploading vbo + -- one known issue regarding to every gameframe respawning lights is to actually get them to update existing dead light candidates, this is very very hard to do sanely + -- BUG: having a lifetime associated with each projectile kind of bugs out updates + local numadded = 0 + local noUpload = true + for i= 1, #nowprojectiles do + local projectileID = nowprojectiles[i] + local px, py, pz = spGetProjectilePosition(projectileID) + if px then -- we are somehow getting projectiles with no position? + local lightType = 'point' -- default + if trackedProjectiles[projectileID] then + if newgameframe then + --update proj pos + lightType = trackedProjectileTypes[projectileID] + if lightType ~= 'beam' then + local dx,dy,dz = spGetProjectileVelocity(projectileID) + local instanceIndex = updateLightPosition(projectileLightVBOMap[lightType], + projectileID, px,py,pz, nil, dx,dy,dz) + if debugproj then spEcho("Updated", instanceIndex, projectileID, px, py, pz,dx,dy,dz) end + end + + end + else + -- add projectile + local weapon, piece = spGetProjectileType(projectileID) + local skipProjectileTracking = false + + if piece then + local gib = gibLight.lightParamTable + gib[1] = px + gib[2] = py + gib[3] = pz + AddLight(projectileID, nil, nil, projectilePointLightVBO, gib, noUpload) + else + local weaponDefID = spGetProjectileDefID(projectileID) + local projectileLight = projectileDefLights[weaponDefID] + + if ShouldDelayProjectileLight(projectileLight, projectileID, py) then + skipProjectileTracking = true + elseif projectileLight and (projectileID % (projectileLight.fraction or 1) == 0) then + local lightParamTable = projectileLight.lightParamTable + lightType = projectileLight.lightType + + lightParamTable[1] = px + lightParamTable[2] = py + lightParamTable[3] = pz + if debugproj then spEcho(lightType, projectileLight.lightClassName) end + + local dx, dy, dz = spGetProjectileVelocity(projectileID) + + if lightType == 'beam' then + lightParamTable[5] = px + dx + lightParamTable[6] = py + dy + lightParamTable[7] = pz + dz + else + -- for points and cones, velocity gives the pointing dir, and for cones it gives the pos super well. + lightParamTable[5] = dx + lightParamTable[6] = dy + lightParamTable[7] = dz + end + if debugproj then spEcho(lightType, px,py,pz, dx, dy,dz) end + + AddLight(projectileID, nil, nil, projectileLightVBOMap[lightType], lightParamTable,noUpload) + --AddLight(projectileID, nil, nil, projectilePointLightVBO, lightParamTable) + else + --spEcho("No projectile light defined for", projectileID, weaponDefID, px, pz) + --testprojlighttable[1] = px + --testprojlighttable[2] = py + --testprojlighttable[3] = pz + --AddPointLight(projectileID, nil, nil, projectilePointLightVBO, testprojlighttable) + end + end + + if not skipProjectileTracking then + numadded = numadded + 1 + --trackedProjectiles[] + trackedProjectileTypes[projectileID] = lightType + trackedProjectiles[projectileID] = gameFrame + end + end + end + end + for projectileID, readyFrame in pairs(delayedProjectileLightFrames) do + if readyFrame < gameFrame - 300 then + delayedProjectileLightFrames[projectileID] = nil + end + end + -- remove theones that werent updated + local numremoved = 0 + for projectileID, gf in pairs(trackedProjectiles) do + if gf < gameFrame then + -- SO says we can modify or remove elements while iterating, we just cant add + -- a possible hack to keep projectiles visible, is trying to keep getting their pos + local px, py, pz = spGetProjectilePosition(projectileID) + if px then -- this means that this projectile + local lightType = trackedProjectileTypes[projectileID] + if newgameframe and lightType ~= 'beam' then + local dx,dy,dz = spGetProjectileVelocity(projectileID) + updateLightPosition(projectileLightVBOMap[lightType], + projectileID, px,py,pz, nil, dx,dy,dz ) + end + else + numremoved = numremoved + 1 + trackedProjectiles[projectileID] = nil + local lightType = trackedProjectileTypes[projectileID] + --RemoveLight('point', projectileID, nil) + if projectileLightVBOMap[lightType].instanceIDtoIndex[projectileID] then -- god the indirections here ... + local success = popElementInstance(projectileLightVBOMap[lightType], projectileID, noUpload) + if success == nil then PrintProjectileInfo(projectileID) end + end + trackedProjectileTypes[projectileID] = nil + end + end + end + -- upload all changed elements in one go + for _, targetVBO in pairs(projectileLightVBOMap) do + if targetVBO.dirty then + uploadAllElements(targetVBO) + end + end + --if debugproj then + -- spEcho("#points", projectilePointLightVBO.usedElements, '#projs', #nowprojectiles ) + --end +end + +local AUTOUPDATE_CONFIG_POLL_INTERVAL = 1.5 +local AUTOUPDATE_SHADER_POLL_INTERVAL = 0.5 + +local configCache = {lastUpdate = spGetTimer()} +local shaderUpdateCache = {lastUpdate = spGetTimer()} +local function checkConfigUpdates() + local now = spGetTimer() + if spDiffTimers(now, configCache.lastUpdate) <= AUTOUPDATE_CONFIG_POLL_INTERVAL then + return + end + + local newconfa = VFS.LoadFile('luaui/configs/DeferredLightsGL4config.lua') + local newconfb = VFS.LoadFile('luaui/configs/DeferredLightsGL4WeaponsConfig.lua') + if newconfa ~= configCache.confa or newconfb ~= configCache.confb then + LoadLightConfig() + if WG['unittrackerapi'] and WG['unittrackerapi'].visibleUnits then + widget:VisibleUnitsChanged(WG['unittrackerapi'].visibleUnits, nil) + end + local allFeatures = spGetAllFeatures() + local allFeaturesLen = #allFeatures + for i = 1, allFeaturesLen do + widget:FeatureDestroyed(allFeatures[i], true) + end + for i = 1, allFeaturesLen do + widget:FeatureCreated(allFeatures[i], true) + end + if pointLightVBO.dirty then uploadAllElements(pointLightVBO) end + configCache.confa = newconfa + configCache.confb = newconfb + end + configCache.lastUpdate = now +end + +local expavg = 0 +local sec = 1 +function widget:Update(dt) + if autoupdate then checkConfigUpdates() end + local tus = spGetTimerMicros() + if predictivePointLightVBO.dirty then + uploadAllElements(predictivePointLightVBO) + end + + -- update/handle Cursor Lights! + if WG['allycursors'] and WG['allycursors'].getLights() then + sec = sec + dt + if sec >= 0.25 then + if cursorLightAlpha ~= WG['allycursors'].getLightStrength() or cursorLightRadius ~= WG['allycursors'].getLightRadius() or cursorLightSelfShadowing ~= WG['allycursors'].getLightSelfShadowing() then + cursorLightAlpha = WG['allycursors'].getLightStrength() + cursorLightRadius = WG['allycursors'].getLightRadius() + cursorLightSelfShadowing = WG['allycursors'].getLightSelfShadowing() + InstanceVBOTable.clearInstanceTable(cursorPointLightVBO) + cursorLights = nil + end + end + if not cursorLights then + cursorLights = {} + end + local cursors, notIdle = WG['allycursors'].getCursors() + local isCursorVisible = WG['allycursors'].isCursorVisible + for playerID, cursor in pairs(cursors) do + local teamColor = teamColors[playerID] + local visibleToViewer = (not isCursorVisible) or isCursorVisible(playerID) + if teamColor and not cursor[8] and notIdle[playerID] and visibleToViewer then + if not cursorLights[playerID] and not cursor[8] then + local params = cursorLightParams.lightParamTable -- see lightParamKeyOrder for which key contains what + params[1], params[2], params[3] = cursor[1], cursor[2] + cursorLightHeight, cursor[3] + params[4] = cursorLightRadius * 250 + params[9], params[10], params[11] = teamColor[1], teamColor[2], teamColor[3] + params[12] = cursorLightAlpha * 0.2 + params[20] = cursorLightSelfShadowing and 8 or 0 + cursorLights[playerID] = AddLight(nil, nil, nil, cursorPointLightVBO, params) --pointLightVBO + else + if cursor[8] or cursor[7] < 0.01 then + popElementInstance(cursorPointLightVBO, cursorLights[playerID]) + cursorLights[playerID] = nil + else + updateLightPosition(cursorPointLightVBO, cursorLights[playerID], cursor[1], cursor[2]+cursorLightHeight, cursor[3]) + end + end + elseif cursorLights[playerID] then + popElementInstance(cursorPointLightVBO, cursorLights[playerID]) + cursorLights[playerID] = nil + end + end + uploadAllElements(cursorPointLightVBO) + else + if cursorLights then + InstanceVBOTable.clearInstanceTable(cursorPointLightVBO) + cursorLights = nil + end + end + + -- This is the player cursor! + if showPlayerCursorLight then + local mx,my,m1,m2,m3, _ , camPanning = spGetMouseState() + local traceType, tracedScreenRay = spTraceScreenRay(mx, my, true) + if not camPanning and tracedScreenRay ~= nil then + local params = playerCursorLightParams.lightParamTable + params[1], params[2], params[3] = tracedScreenRay[1],tracedScreenRay[2] + cursorLightHeight,tracedScreenRay[3] + params[4] = playerCursorLightRadius * 250 + params[12] = playerCursorLightBrightness * 0.1 + AddLight("PLAYERCURSOR", nil, nil, cursorPointLightVBO, params) + else + if cursorPointLightVBO.instanceIDtoIndex["PLAYERCURSOR"] then + popElementInstance(cursorPointLightVBO, "PLAYERCURSOR") + end + end + end + + updateProjectileLights() + expavg = expavg * 0.98 + 0.02 * spDiffTimers(spGetTimerMicros(),tus) + --if spGetGameFrame() % 120 ==0 then spEcho("Update is on average", expavg,'ms') end +end + +------------------------------- Drawing all the lights --------------------------------- + + +-- local tf = Spring.GetTimerMicros() +function widget:DrawWorld() -- We are drawing in world space, probably a bad idea but hey + --local t0 = Spring.GetTimerMicros() + --if true then return end + if skipdraw then return end + if autoupdate then + local now = spGetTimer() + if spDiffTimers(now, shaderUpdateCache.lastUpdate) > AUTOUPDATE_SHADER_POLL_INTERVAL then + deferredLightShader = LuaShader.CheckShaderUpdates(shaderSourceCache, 0) or deferredLightShader + shaderUpdateCache.lastUpdate = now + end + end + + if pointLightVBO.usedElements > 0 or + predictivePointLightVBO.usedElements > 0 or + unitPointLightVBO.usedElements > 0 or + beamLightVBO.usedElements > 0 or + unitConeLightVBO.usedElements > 0 or + coneLightVBO.usedElements > 0 or + cursorPointLightVBO.usedElements > 0 or + projectilePointLightVBO.usedElements > 0 or + projectileBeamLightVBO.usedElements > 0 or + projectileConeLightVBO.usedElements > 0 + then + + local alt, ctrl = spGetModKeyState() + local devui = (spGetConfigInt('DevUI', 0) == 1) + + if autoupdate and alt and ctrl and (isSinglePlayer or spec) and devui then + -- draw a full-screen black quad first! + local camX, camY, camZ = spGetCameraPosition() + local camDirX,camDirY,camDirZ = spGetCameraDirection() + glBlending(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA) + glCulling(GL_BACK) + glDepthTest(false) + glDepthMask(false) --"BK OpenGL state resets", default is already false, could remove + glColor(0,0,0,1) + glPushMatrix() + glColor(0,0,0,1.0) + glTranslate(camX+(camDirX*360),camY+(camDirY*360),camZ+(camDirZ*360)) + glBillboard() + glRect(-5000, -5000, 5000, 5000) + glPopMatrix() + end + + if autoupdate and ctrl and (not alt) and (isSinglePlayer or spec) and devui then + glBlending(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA) + else + glBlending(GL_SRC_ALPHA, GL_ONE) + end + --if autoupdate and alt and (not ctrl) and (isSinglePlayer or spec) and devui then return end + + glCulling(GL_BACK) + glDepthTest(false) + glDepthMask(false) --"BK OpenGL state resets", default is already false, could remove + glTexture(0, "$map_gbuffer_zvaltex") + glTexture(1, "$model_gbuffer_zvaltex") + glTexture(2, "$map_gbuffer_normtex") + glTexture(3, "$model_gbuffer_normtex") + --glTexture(4, "$map_gbuffer_spectex") + --glTexture(5, "$model_gbuffer_spectex") + glTexture(6, "$map_gbuffer_difftex") + glTexture(7, "$model_gbuffer_difftex") + glTexture(8, noisetex3dcube) + glTexture(9, blueNoise2D) + + deferredLightShader:Activate() + deferredLightShader:SetUniformFloat("nightFactor", nightFactor) + + deferredLightShader:SetUniformFloat("intensityMultiplier", intensityMultiplier) + deferredLightShader:SetUniformFloat("radiusMultiplier", radiusMultiplier) + + -- As the setting goes from 0 to 4, map to 0,8,16,32,64 + local screenSpaceShadowSampleCount = 0 + if screenSpaceShadows > 0 then + screenSpaceShadowSampleCount = mathMin(64, mathFloor( mathPow(2, screenSpaceShadows) * 4) ) + end + deferredLightShader:SetUniformInt("screenSpaceShadows", screenSpaceShadowSampleCount) + --spEcho(windX, windZ) + + + -- Fixed worldpos lights, cursors, projectiles, world lights + deferredLightShader:SetUniformFloat("attachedtounitID", 0) -- worldpos stuff + deferredLightShader:SetUniformFloat("pointbeamcone", 0) + + if not spIsGUIHidden() then + cursorPointLightVBO:draw() + end + + pointLightVBO:draw() + predictivePointLightVBO:draw() + projectilePointLightVBO:draw() + + + deferredLightShader:SetUniformFloat("pointbeamcone", 1) + beamLightVBO:draw() + projectileBeamLightVBO:draw() + + deferredLightShader:SetUniformFloat("pointbeamcone", 2) + coneLightVBO:draw() + projectileConeLightVBO:draw() + + -- Unit Attached Lights + deferredLightShader:SetUniformFloat("attachedtounitID", 1) + + deferredLightShader:SetUniformFloat("pointbeamcone", 0) + unitPointLightVBO:draw() + + deferredLightShader:SetUniformFloat("pointbeamcone", 1) + unitBeamLightVBO:draw() + + deferredLightShader:SetUniformFloat("pointbeamcone", 2) + unitConeLightVBO:draw() + + deferredLightShader:Deactivate() + + for i = 0, 8 do glTexture(i, false) end + glCulling(GL_BACK) + glDepthTest(true) + --gl.DepthMask(true) --"BK OpenGL state resets", was true but now commented out (redundant set of false states) + glBlending(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA) + end + --local t1 = Spring.GetTimerMicros() + --if (Spring.GetDrawFrame() % 50 == 0 ) then + -- local dt = Spring.DiffTimers(t1,t0) + -- spEcho("Deltat is ", dt,'us, so total load should be', dt * Spring.GetFPS() / 10 ,'%') + -- spEcho("epoch is ", Spring.DiffTimers(t1,tf)) + --end +end + +local function dlgl4statsCmd(_, line) + spEcho(stringFormat("DLGLStats Total = %d , (PBC=%d,%d,%d), (unitPBC=%d,%d,%d), (projPBC=%d,%d,%d), Cursor = %d", + numAddLights, + pointLightVBO.usedElements, beamLightVBO.usedElements, coneLightVBO.usedElements, + unitPointLightVBO.usedElements, unitBeamLightVBO.usedElements, unitConeLightVBO.usedElements, + projectilePointLightVBO.usedElements, projectileBeamLightVBO.usedElements, projectileConeLightVBO.usedElements, + cursorPointLightVBO.usedElements)) + return true +end + +local function dlgl4skipdrawCmd(_, line) + skipdraw = not skipdraw + spEcho("Deferred Rendering GL4 skipdraw set to", skipdraw) + return true +end + +function widget:Initialize() + widgetHandler:AddAction("dlgl4stats", dlgl4statsCmd, nil, "t") + widgetHandler:AddAction("dlgl4skipdraw", dlgl4skipdrawCmd, nil, "t") + + Spring.Debug.TraceEcho("Initialize DLGL4") + if spGetConfigString("AllowDeferredMapRendering") == '0' or spGetConfigString("AllowDeferredModelRendering") == '0' then + spEcho('Deferred Rendering (gfx_deferred_rendering.lua) requires AllowDeferredMapRendering and AllowDeferredModelRendering to be enabled in springsettings.cfg!') + widgetHandler:RemoveWidget() + return + end + if not LoadLightConfig() then + widgetHandler:RemoveWidget() + return + end + + if initGL4() == false then return end + + local success, mapinfo = pcall(VFS.Include,"mapinfo.lua") -- load mapinfo.lua confs + + if nightFactor ~= 1 then + local nightLightingParams = {} + for _,v in ipairs(adjustfornight) do + nightLightingParams[v] = mapinfo.lighting[stringLower(v)] + if nightLightingParams[v] ~= nil then + for k2, v2 in pairs(nightLightingParams[v]) do + if tonumber(v2) then + if stringFind(v, 'unit', nil, true) then + nightLightingParams[v][k2] = v2 * nightFactor * unitNightFactor + else + nightLightingParams[v][k2] = v2 * nightFactor + end + end + end + else + spEcho("Deferred Lights GL4: Warning: This map does not specify ",v, "in mapinfo.lua!") + end + end + spSetSunLighting(nightLightingParams) + end + + if addrandomlights then + math.randomseed(1) + for i=1, 1 do AddRandomLight( mathRandom()) end + end + + if WG['unittrackerapi'] and WG['unittrackerapi'].visibleUnits then + widget:VisibleUnitsChanged(WG['unittrackerapi'].visibleUnits, nil) + end + + local allFeatures = spGetAllFeatures() + local allFeaturesLen = #allFeatures + for i = 1, allFeaturesLen do + widget:FeatureCreated(allFeatures[i]) + end + + WG['lightsgl4'] = {} + WG['lightsgl4'].AddPointLight = AddPointLight + WG['lightsgl4'].AddBeamLight = AddBeamLight + WG['lightsgl4'].AddConeLight = AddConeLight + WG['lightsgl4'].AddLight = AddLight + WG['lightsgl4'].RemoveLight = RemoveLight + WG['lightsgl4'].GetLightVBO = GetLightVBO + + WG['lightsgl4'].IntensityMultiplier = function(value) + intensityMultiplier = value + end + WG['lightsgl4'].RadiusMultiplier = function(value) + radiusMultiplier = value + end + WG['lightsgl4'].ScreenSpaceShadows = function(value) + screenSpaceShadows = value + end + + WG['lightsgl4'].ShowPlayerCursorLight = function(value) + showPlayerCursorLight = value + -- Remove the player's cursor light on disabling this feature + if not showPlayerCursorLight and cursorPointLightVBO.instanceIDtoIndex["PLAYERCURSOR"] then + popElementInstance(cursorPointLightVBO, "PLAYERCURSOR") + end + end + WG['lightsgl4'].PlayerCursorLightRadius = function(value) + playerCursorLightRadius = value + end + WG['lightsgl4'].PlayerCursorLightBrightness = function(value) + playerCursorLightBrightness = value + end + + widgetHandler:RegisterGlobal('AddPointLight', WG['lightsgl4'].AddPointLight) + widgetHandler:RegisterGlobal('AddBeamLight', WG['lightsgl4'].AddBeamLight) + widgetHandler:RegisterGlobal('AddConeLight', WG['lightsgl4'].AddConeLight) + widgetHandler:RegisterGlobal('AddLight', WG['lightsgl4'].AddLight) + widgetHandler:RegisterGlobal('RemoveLight', WG['lightsgl4'].RemoveLight) + widgetHandler:RegisterGlobal('GetLightVBO', WG['lightsgl4'].GetLightVBO) + + -- Gadget bridge: gfx_environmental_lightning_gl4 (a gadget, no WG access) flashes + -- a short-lived point light at each lightning burst origin via Script.LuaUI. + -- The gadget owns all tuning (see its lightning configs); this just forwards the + -- already-resolved values to AddPointLight. r2/g2/b2 = same color so the light + -- does not animate toward black; sustain holds full brightness before the fade. + -- Args: x,y,z, radius, r,g,b,a, lifetime, sustain, modelfactor, specular, + -- scattering, lensflare, spawnframe. + WG['lightsgl4'].EnvLightningPointLight = function(x, y, z, radius, r, g, b, a, + lifetime, sustain, modelfactor, specular, scattering, lensflare, spawnframe) + AddPointLight(nil, nil, nil, pointLightVBO, + x, y, z, radius, + r, g, b, a, -- color + brightness + r, g, b, 0, -- r2,g2,b2 = same color, colortime 0 + modelfactor, specular, scattering, lensflare, -- light surface response + spawnframe, lifetime, sustain) -- spawnframe, lifetime, sustain (auto-expire) + end + widgetHandler:RegisterGlobal('EnvLightningPointLight', WG['lightsgl4'].EnvLightningPointLight) + + -- Gadget bridge: predictive nano point lights. Gadget sends one spawn event + -- per selected particle, plus sparse correction events when trajectory + -- changes (homing / terrain correction). Widget integrates in-between. + 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) +end + +if autoupdate then + function widget:DrawScreen() + if deferredLightShader.DrawPrintf then deferredLightShader.DrawPrintf() end + end +end + +function widget:UnitScriptLight(unitID, unitDefID, lightIndex, param) + UnitScriptLight(unitID, unitDefID, lightIndex, param) +end +--------------------------- Ingame Configurables ------------------- + +function widget:GetConfigData(_) -- Called by RemoveWidget + local savedTable = { + intensityMultiplier = intensityMultiplier, + radiusMultiplier = radiusMultiplier, + screenSpaceShadows = screenSpaceShadows, + showPlayerCursorLight = showPlayerCursorLight, + playerCursorLightRadius = playerCursorLightRadius, + playerCursorLightBrightness = playerCursorLightBrightness, + } + return savedTable +end + +function widget:SetConfigData(data) -- Called on load (and config change), just before Initialize! + if data.intensityMultiplier ~= nil then + intensityMultiplier = data.intensityMultiplier + end + if data.radiusMultiplier ~= nil then + radiusMultiplier = data.radiusMultiplier + end + if data.screenSpaceShadows ~= nil then + screenSpaceShadows = data.screenSpaceShadows + end + if data.showPlayerCursorLight ~= nil then + showPlayerCursorLight = data.showPlayerCursorLight + end + if data.playerCursorLightRadius ~= nil then + playerCursorLightRadius = data.playerCursorLightRadius + end + if data.playerCursorLightBrightness ~= nil then + playerCursorLightBrightness = data.playerCursorLightBrightness + end +end + +return widget end)() +local explosionRelay=(function()local gadget={} + +local gadget = gadget ---@type Gadget + +function gadget:GetInfo() + return { + name = "Explosion_lights", + desc = "", + author = "Floris", + date = "April 2017", + license = "GNU GPL, v2 or later", + layer = 0, + enabled = true + } +end + +if gadgetHandler:IsSyncedCode() then + + local SendToUnsynced = SendToUnsynced + local spGetProjectilePosition = Spring.GetProjectilePosition + + local explosionTypes = { + Flame = true, + Cannon = true, + LaserCannon = true, + BeamLaser = true, + MissileLauncher = true, + AircraftBomb = true, + StarburstLauncher = true, + TorpedoLauncher = true, + } + + local cannonWeapons = {} + local watchedExplosions = {} + local watchedProjectiles = {} + + function gadget:Initialize() + for wdid, wd in pairs(WeaponDefs) do + if explosionTypes[wd.type] then + Script.SetWatchExplosion(wdid, true) + watchedExplosions[wdid] = true + end + if wd.type == "Cannon" or wd.type == "LaserCannon" then + cannonWeapons[wdid] = true + end + if wd.type == "Cannon" and wd.damages[0] >= 20 then + Script.SetWatchProjectile(wdid, true) + watchedProjectiles[wdid] = true + elseif wd.type == "LaserCannon" and wd.damages[0] >= 10 then + Script.SetWatchProjectile(wdid, true) + watchedProjectiles[wdid] = true + end + end + end + + function gadget:Shutdown() + for wdid in pairs(watchedExplosions) do + Script.SetWatchExplosion(wdid, false) + end + for wdid in pairs(watchedProjectiles) do + Script.SetWatchProjectile(wdid, false) + end + end + + function gadget:Explosion(weaponID, px, py, pz, ownerID, projectileID) + SendToUnsynced("explosion_light", px, py, pz, weaponID, ownerID) + end + + function gadget:ProjectileCreated(projectileID, ownerID, weaponID) + if cannonWeapons[weaponID] then + local px, py, pz = spGetProjectilePosition(projectileID) + SendToUnsynced("barrelfire_light", px, py, pz, weaponID, ownerID) + end + end + + +else -- Unsynced + + + local myPlayerID = Spring.GetMyPlayerID() + local myAllyID = Spring.GetMyAllyTeamID() + local fullView = select(2, Spring.GetSpectatingState()) + local spGetUnitAllyTeam = Spring.GetUnitAllyTeam + local spIsPosInLos = Spring.IsPosInLos + + function gadget:PlayerChanged(playerID) + if playerID == myPlayerID then + myPlayerID = Spring.GetMyPlayerID() + myAllyID = Spring.GetMyAllyTeamID() + fullView = select(2, Spring.GetSpectatingState()) + end + end + + local function SpawnExplosion(_,px,py,pz, weaponID, ownerID) + if ownerID ~= nil and Script.LuaUI("VisibleExplosion") then + if fullView or spGetUnitAllyTeam(ownerID) == myAllyID or spIsPosInLos(px, py, pz, myAllyID) then + Script.LuaUI.VisibleExplosion(px, py, pz, weaponID, ownerID) + end + end + end + + local function SpawnBarrelfire(_,px,py,pz, weaponID, ownerID) + if ownerID ~= nil and Script.LuaUI("Barrelfire") then + if fullView or spGetUnitAllyTeam(ownerID) == myAllyID or spIsPosInLos(px, py, pz, myAllyID) then + Script.LuaUI.Barrelfire(px, py, pz, weaponID, ownerID) + end + end + end + + function gadget:Initialize() + gadgetHandler:AddSyncAction("explosion_light", SpawnExplosion) + gadgetHandler:AddSyncAction("barrelfire_light", SpawnBarrelfire) + end + + function gadget:Shutdown() + gadgetHandler.RemoveSyncAction("explosion_light") + gadgetHandler.RemoveSyncAction("barrelfire_light") + end +end + +return gadget end)() +local scriptRelay=(function()local gadget={} +local gadget = gadget ---@type Gadget + +function gadget:GetInfo() + return { + name = "Unit Script Lights and Distortion", + desc = "Forwards Lighting Events to Widgets from COB Unit scripts", + author = "Beherith", + date = "Apr, 2008", + license = "GNU GPL, v2 or later", + layer = 0, + enabled = true, + } +end + + +if gadgetHandler:IsSyncedCode() then + local SendToUnsynced = SendToUnsynced + + local function UnitScriptLight(unitID, unitDefID, _, lightIndex, param) + --Spring.Echo("Synced Gadget UnitScriptLight", unitID, unitDefID, lightIndex, param) + SendToUnsynced("cob_UnitScriptLight", unitID, unitDefID, lightIndex, param) + end + + local function UnitScriptDistortion(unitID, unitDefID, _, lightIndex, param) + --Spring.Echo("Synced Gadget UnitScriptDistortion", unitID, unitDefID, lightIndex, param) + SendToUnsynced("cob_UnitScriptDistortion", unitID, unitDefID, lightIndex, param) + end + + function gadget:Initialize() + gadgetHandler:RegisterGlobal("UnitScriptLight", UnitScriptLight) + gadgetHandler:RegisterGlobal("UnitScriptDistortion", UnitScriptDistortion) + end + + function gadget:Shutdown() + gadgetHandler:DeregisterGlobal("UnitScriptLight") + gadgetHandler:DeregisterGlobal("UnitScriptDistortion") + end + + + +else -- UNSYNCED + local myAllyTeamID = Spring.GetMyAllyTeamID() + local myPlayerID = Spring.GetMyPlayerID() + local mySpec, fullview = Spring.GetSpectatingState() + local spIsUnitInLos = Spring.IsUnitInLos + + function gadget:PlayerChanged(playerID) + if playerID == myPlayerID then + myAllyTeamID = Spring.GetMyAllyTeamID() + mySpec, fullview = Spring.GetSpectatingState() + end + end + + local scriptUnitScriptLight = Script.LuaUI.UnitScriptLight + + local function UnitScriptLight(_, unitID, unitDefID, lightIndex, param) + if not fullview and not spIsUnitInLos(unitID, myAllyTeamID) then + return + end + --Spring.Echo("Unsynced UnitScriptLight", unitID, unitDefID, lightIndex, param) + if Script.LuaUI('UnitScriptLight') then + Script.LuaUI.UnitScriptLight(unitID, unitDefID, lightIndex, param) + end + end + + local scriptUnitScriptDistortion = Script.LuaUI.UnitScriptDistortion + + local function UnitScriptDistortion(_, unitID, unitDefID, lightIndex, param) + if not fullview and not spIsUnitInLos(unitID, myAllyTeamID) then + return + end + --Spring.Echo("Unsynced UnitScriptDistortion", unitID, unitDefID, lightIndex, param) + if Script.LuaUI('UnitScriptDistortion') then + Script.LuaUI.UnitScriptDistortion(unitID, unitDefID, lightIndex, param) + end + end + + function gadget:Initialize() + gadgetHandler:AddSyncAction("cob_UnitScriptLight", UnitScriptLight) + gadgetHandler:AddSyncAction("cob_UnitScriptDistortion", UnitScriptDistortion) + end + + function gadget:Shutdown() + gadgetHandler:RemoveSyncAction("cob_UnitScriptLight") + gadgetHandler:RemoveSyncAction("cob_UnitScriptDistortion") + end + +end + +return gadget end)() +local events={VisibleUnitAdded=true,VisibleUnitRemoved=true,VisibleUnitsChanged=true, + UnitCreated=true,UnitFinished=true,UnitDestroyed=true,UnitGiven=true, + UnitFromFactory=true,CrashingAircraft=true,UnitCloaked=true,UnitDecloaked=true, + UnitMoveFailed=true,UnitIdle=true,StockpileChanged=true,FeatureCreated=true,FeatureDestroyed=true} +for _,name in ipairs({'VisibleExplosion','Barrelfire','UnitScriptLight'})do + globals[name]=function(...)return stock[name](stock,...)end +end +return { + Initialize=function() + assert(not ready and not removed,'Original deferred-light host already initialized or removed') + stock:Initialize() + if removed then return false end + explosionRelay:Initialize();scriptRelay:Initialize();ready=true + return true + end, + GameFrame=function(frame)if ready then stock:GameFrame(frame)end end, + Event=function(name,...) + assert(events[name],'Unadmitted original deferred-light event '..tostring(name)) + if ready and stock[name]then return stock[name](stock,...)end + end, + PlayerChanged=function(player) + if not ready then return end + explosionRelay:PlayerChanged(player);scriptRelay:PlayerChanged(player);stock:PlayerChanged(player) + end, + Sync=function(name,...) + -- Distortion has its own accepted original host; do not duplicate it here. + if not ready or(name~='explosion_light'and name~='barrelfire_light'and name~='cob_UnitScriptLight')then return false end + assert(actions[name])(name,...);return true + end, + Draw=function(dt) + if not ready then return nil end + batches={};uniforms={} + stock:Update(dt);stock:DrawWorld() + local total=0;for _,batch in ipairs(batches)do total=total+#batch.rows end + assert(total<=65536,'Original deferred-light publication capacity exceeded') + return {frame=Spring.GetGameFrame(),batches=batches,uniforms=uniforms,config=stock:GetConfigData()} + end, + SetConfigData=function(data)stock:SetConfigData(data)end, + Ready=function()return ready and not removed end, +} + +end +-- Explicit opt-in installation in the existing original HUD handle. A light +-- failure stays local; it must never disable the accepted HUD/orb policies. +function WebbarDeferredLightInitialize(graphics) + local host=WebbarCreateDeferredLightPolicy(graphics) + assert(host.Initialize(),'Original deferred-light initialization failed') + local alive=true + local function invoke(method,...) + if not alive then return end + local ok,result=pcall(host[method],...) + if not ok then alive=false;webbarDeferredLightFailure=tostring(result);return end + return result + end + for _,name in ipairs({'VisibleUnitAdded','VisibleUnitRemoved','VisibleUnitsChanged'})do + local ordinary=assert(listeners[name]) + listeners[name]=function(...) + local result=ordinary(...) + invoke('Event',name,...) + return result + end + end + for _,name in ipairs({'UnitCreated','UnitFinished','UnitDestroyed','UnitGiven', + 'UnitFromFactory','CrashingAircraft','UnitCloaked','UnitDecloaked','UnitMoveFailed', + 'UnitIdle','StockpileChanged','FeatureCreated','FeatureDestroyed'})do + local ordinary=_G[name] + _G[name]=function(...) + local result;if ordinary then result=ordinary(...)end + invoke('Event',name,...) + return result + end + end + local ordinaryFrame,ordinaryPlayer=GameFrame,PlayerChanged + function GameFrame(frame)ordinaryFrame(frame);invoke('GameFrame',frame)end + function PlayerChanged(player)ordinaryPlayer(player);invoke('PlayerChanged',player)end + function WebbarDeferredLightSync(...)return invoke('Sync',...)end + function WebbarDeferredLightState(dt) + assert(alive,webbarDeferredLightFailure) + return assert(invoke('Draw',dt),webbarDeferredLightFailure) + end + return true end )WEBBAR_BARS"; --- a/rts/Game/WebbarNativeHealthbars.h +++ b/rts/Game/WebbarNativeHealthbars.h @@ -3,6 +3,8 @@ #include #include "WebbarNativeHealthbarPolicy.h" #include "WebbarHealthbarEvents.h" +#include "WebbarDeferredLightEvents.h" +#include #include "Lua/LuaWeaponDefs.h" #include "Lua/LuaUnsyncedCtrl.h" #include "Lua/LuaFeatureDefs.h" @@ -34,6 +36,7 @@ class WebbarNativeHealthbarReader final: public CLuaHandle { public: bool ready = false; +#include "WebbarDeferredLightReader.inc" WebbarHealthbarRuleEvents ruleEvents; WebbarNativeHealthbarReader(): CLuaHandle("WebBAR original healthbar policy", LUA_HANDLE_ORDER_UI, false, false),ruleEvents(this) { SetFullCtrl(false); SetCtrlTeam(NoAccessTeam); SetSelectTeam(NoAccessTeam); @@ -79,13 +82,14 @@ lua_settop(L, 0); } if (ready) { + PrepareDeferredLights(); WebbarHealthbarEvents::Attach(this, [](void* self, lua_State* source, int args) { static_cast(self)->Sync(source, args); }); eventHandler.AddClient(this); eventHandler.AddClient(&ruleEvents); } else LOG_L(L_ERROR, "[WebBAR] original healthbar policy initialization failed"); } - ~WebbarNativeHealthbarReader() override { WebbarHealthbarEvents::Detach(this); eventHandler.RemoveClient(&ruleEvents); KillLua(); } + ~WebbarNativeHealthbarReader() override { WebbarDeferredLightEvents::Detach(this);WebbarHealthbarEvents::Detach(this); eventHandler.RemoveClient(&ruleEvents); KillLua(); } bool WantsEvent(const std::string& name) override { - return ready && (name == "CollectGarbage" || name == "GameFrame" || name == "UnitCreated" || name == "UnitFinished" || name == "UnitDestroyed" || name == "UnitTaken" || name == "UnitGiven" || name == "UnitEnteredLos" || name == "UnitLeftLos" || name == "FeatureCreated" || name == "FeatureDestroyed"); + return ready && (name == "CollectGarbage" || name == "GameFrame" || name == "UnitCreated" || name == "UnitFinished" || name == "UnitDestroyed" || name == "UnitTaken" || name == "UnitGiven" || name == "UnitEnteredLos" || name == "UnitLeftLos" || name == "FeatureCreated" || name == "FeatureDestroyed" || (deferredReady && CLuaHandle::WantsEvent(name))); } void Sync(lua_State* source, int args) { if (!ready) return; --- a/rts/Lua/LuaHandleSynced.cpp +++ b/rts/Lua/LuaHandleSynced.cpp @@ -9,6 +9,7 @@ #include "Game/WebbarPveEvents.h" #include "WebbarDistortionForwarders.h" #include "Game/WebbarHealthbarEvents.h" +#include "Game/WebbarDeferredLightEvents.h" #include "Game/WebbarEtaEvents.h" #include "Game/WebbarScumEvents.h" #endif @@ -196,6 +197,7 @@ void CUnsyncedLuaHandle::RecvFromSynced(lua_State* srcState, int args) { #ifdef __EMSCRIPTEN__ + if (GetName()=="LuaRules") WebbarDeferredLightEvents::Observe(srcState,args); WebbarHealthbarEvents::Observe(srcState,args); WebbarEtaEvents::Observe(srcState,args); if (GetName()=="LuaRules") WebbarScumEvents::Observe(srcState,L,args);