--- a/rts/Game/Game.cpp +++ b/rts/Game/Game.cpp @@ -294,6 +294,7 @@ #if defined(__EMSCRIPTEN__) static void FreeWebbarNativeBeams(); static void FreeWebbarNativeInfo(); +static void FreeWebbarNativeAttack(); static void FreeWebbarNativeSensorRanges(); static void PrepareWebbarNativeSensorRanges(); static void PrepareWebbarNativeHealthbars(); @@ -310,6 +311,7 @@ { #if defined(__EMSCRIPTEN__) FreeWebbarNativeBeams(); + FreeWebbarNativeAttack(); FreeWebbarNativeInfo(); FreeWebbarNativeSensorRanges(); FreeWebbarNativeHealthbars(); --- a/rts/Game/WebbarBrowser.h +++ b/rts/Game/WebbarBrowser.h @@ -117,6 +117,7 @@ #include "WebbarAutomationBrowser.h" #include "WebbarWidgetQueries.h" #include "WebbarNativeInfo.h" +#include "WebbarNativeAttack.h" #include "WebbarNativeSensorRanges.h" #include "WebbarNativeHealthbars.h" #include "WebbarNativeEta.h" @@ -253,6 +254,7 @@ if (!enabled || !game->playing || gs->frameNum < 0) return; WebbarNativeInfo::PollCursor(); + WebbarNativeAttack::Poll(); WebbarNativeInfo::Poll(); PollWebbarNativeMetal(); if (webbarReplay::Enabled()) { PollWebbarReplay(); UpdateWebbarNativeBeams(); return; } --- /dev/null +++ b/rts/Game/WebbarNativeAttack.h @@ -0,0 +1,199 @@ +/* This file is part of the Spring engine (GPL v2 or later), see LICENSE.html */ +#pragma once +#include "WebbarNativeAttackPolicy.h" + +// Original tracker/widget in a separate read-only Lua handle. The ordinary +// Info/cursor reader validates the actual camera, selection and active command; +// no global GUI selection, mouse, command or simulation state is replaced. +class WebbarNativeAttackReader final: public CLuaHandle { +public: + bool ready = false; + WebbarNativeAttackReader(): CLuaHandle("WebBAR original weapon range policy", LUA_HANDLE_ORDER_UI, false, false) { + SetFullCtrl(false); SetCtrlTeam(NoAccessTeam); SetSelectTeam(NoAccessTeam); + SetFullRead(gu->spectatingFullView); + SetReadTeam(gu->spectatingFullView ? AllAccessTeam : gu->myTeam); + SetReadAllyTeam(gu->spectatingFullView ? AllAccessTeam : gu->myAllyTeam); + LuaLibs::OpenSynced(L, false); lua_pushvalue(L, LUA_GLOBALSINDEX); + ready = AddBasicCalls(L) && AddCommonModules(L) + && AddEntriesToTable(L,"Spring",LuaSyncedRead::PushEntries) + && AddEntriesToTable(L,"UnitDefs",LuaUnitDefs::PushEntries) + && AddEntriesToTable(L,"WeaponDefs",LuaWeaponDefs::PushEntries) + && AddEntriesToTable(L,"Game",LuaConstGame::PushEntries) + && AddEntriesToTable(L,"CMD",LuaConstCMD::PushEntries); + if (ready) { + lua_getglobal(L,"Spring"); + #define RANGE_READ(name, method) lua_pushcfunction(L,LuaUnsyncedRead::method);lua_setfield(L,-2,name) + RANGE_READ("GetMyPlayerID",GetLocalPlayerID); + RANGE_READ("GetMyTeamID",GetLocalTeamID); + RANGE_READ("GetMyAllyTeamID",GetLocalAllyTeamID); + RANGE_READ("GetLocalTeamID",GetLocalTeamID); + RANGE_READ("GetLocalAllyTeamID",GetLocalAllyTeamID); + RANGE_READ("GetSpectatingState",GetSpectatingState); + RANGE_READ("GetConfigInt",GetConfigInt); + #undef RANGE_READ + lua_pushcfunction(L,ScreenRay);lua_setfield(L,-2,"TraceScreenRay");lua_pop(L,1); + lua_pushcfunction(L,Lifetime);lua_setglobal(L,"WebbarAttackLifetime"); + } + lua_settop(L,0); + if (ready) ready=LoadCode(L,WEBBAR_ATTACK_POLICY,"Original BAR weapon ranges and unit tracker"); + if (ready) { + lua_getglobal(L,"WebbarAttackInitialize"); + ready=RunCallIn(L,LuaHashString("WebbarAttackInitialize"),0,1)&&lua_toboolean(L,-1); + lua_settop(L,0); + } + if (ready) eventHandler.AddClient(this); + else LOG_L(L_ERROR,"[WebBAR] original weapon range policy initialization failed"); + } + ~WebbarNativeAttackReader() override { 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=="UnitCommand"); + } + void GameFrame(int frame) override { framed=true;CLuaHandle::GameFrame(frame); } + bool Read(const WebbarInfoWorldView& view,const std::vector& ids,int command,bool active,uint32_t inputFlags,const std::array& minimapArea,uint32_t epoch,std::vector& packet) { + if (!ready||!WebbarNativeInfo::reader) return false; + // Reuse the exact qualified native cursor admission, command layout and + // private icon/selection volumes. Its original DefaultCommand only reads. + std::string cursor;int activeIndex=0; + if (!WebbarNativeInfo::reader->ReadCursor(view,ids,active,command,cursor,&activeIndex)) return false; + auto mouse=WebbarNativeInfo::reader->AttackMouse(view); + if(mouse[4]==1){ + const auto* unit=unitHandler.GetUnit(mouse[5]); + if(!Admitted(unit)||!(mouse[6]=RangeLifetime(unit))){mouse={};mouse[4]=2;} + } + const int top=lua_gettop(L);lua_getglobal(L,"WebbarAttackRead");lua_createtable(L,0,6); + const auto boolean=[&](const char* key,bool value){lua_pushboolean(L,value);lua_setfield(L,-2,key);}; + const auto number=[&](const char* key,float value){lua_pushnumber(L,value);lua_setfield(L,-2,key);}; + lua_createtable(L,ids.size(),0);for(size_t i=0;i>12)&3); + lua_createtable(L,4,0);for(int i=0;i<4;++i){lua_pushnumber(L,minimapArea[i]);lua_rawseti(L,-2,i+1);}lua_setfield(L,-2,"minimapArea"); + if(active){lua_createtable(L,0,2);number("index",activeIndex);number("id",command);lua_setfield(L,-2,"active");} + const auto now=std::chrono::steady_clock::now(); + const float dt=lastRead==std::chrono::steady_clock::time_point::min()?0:std::chrono::duration(now-lastRead).count();lastRead=now; + // A newly created reader has not received the engine's current GameFrame. + // Supply that actual frame once; never advance a cosmetic synthetic frame. + if(!framed){const int input=lua_gettop(L);lua_getglobal(L,"GameFrame");lua_pushnumber(L,gs->frameNum);const bool ok=RunCallIn(L,LuaHashString("GameFrame"),1,0);lua_settop(L,input);if(!ok){lua_settop(L,top);return false;}framed=true;} + lua_pushnumber(L,dt); + const bool called=RunCallIn(L,LuaHashString("WebbarAttackRead"),2,1); + if(!called)ready=false; + bool ok=called&&lua_istable(L,-1); + if(ok)ok=Encode(lua_gettop(L),epoch,mouse,packet); + lua_settop(L,top);if(now>=nextGc){CollectGarbage(true);nextGc=now+std::chrono::milliseconds(100);}if(!ok)packet.clear();return ok; + } +private: + bool framed=false; + std::chrono::steady_clock::time_point lastRead=std::chrono::steady_clock::time_point::min(); + std::chrono::steady_clock::time_point nextGc=std::chrono::steady_clock::time_point::min(); + static bool Admitted(const CUnit* unit){return unit&&!unit->isDead&&(gu->spectatingFullView||unit->allyteam==gu->myAllyTeam||unit->IsInLosForAllyTeam(gu->myAllyTeam));} + // Enemy body poses deliberately withhold ownership authority. Use their + // already-public creation frame as a range-only birth identity, not a command + // token. Capture it on insertion and revalidate it before publishing a row. + static uint32_t RangeLifetime(const CUnit* unit){ + return !gu->spectatingFullView&&unit->allyteam!=gu->myAllyTeam + ?uint32_t(unit->creationFrame)+2u:WebbarHudLifetime(unit); + } + static int Lifetime(lua_State* state){ + const auto* unit=unitHandler.GetUnit(luaL_checkint(state,1));if(!Admitted(unit))return 0; + char token[9];std::snprintf(token,sizeof(token),"%08x",RangeLifetime(unit));lua_pushstring(state,token);return 1; + } + static int ScreenRay(lua_State* state){return WebbarNativeInfo::reader?WebbarNativeInfo::reader->TraceAttackRay(state):0;} + // Commands contain only the original bounded graphics records. Numeric Lua + // array keys stay explicit, preserving false values and f32 formatting. + bool Json(int index,std::string& out,uint32_t depth,uint32_t& nodes){ + if(depth>12||++nodes>65536||out.size()>262144)return false; + if(index<0)index=lua_gettop(L)+index+1; + switch(lua_type(L,index)){ + case LUA_TBOOLEAN:out+=lua_toboolean(L,index)?"true":"false";break; + case LUA_TNUMBER:{const float n=lua_tonumber(L,index);if(!std::isfinite(n))return false;WebbarJsonNumber(out,n);}break; + case LUA_TSTRING:{size_t n=0;const char* s=lua_tolstring(L,index,&n);if(n>256)return false;WebbarJsonString(out,std::string(s,n));}break; + case LUA_TTABLE:{out+='{';bool first=true;lua_pushnil(L);while(lua_next(L,index)){ + if(!first)out+=',';first=false; + if(lua_type(L,-2)==LUA_TSTRING){size_t n=0;const char* s=lua_tolstring(L,-2,&n);if(n>256){lua_pop(L,2);return false;}WebbarJsonString(out,std::string(s,n));} + else if(lua_type(L,-2)==LUA_TNUMBER){const float key=lua_tonumber(L,-2);if(key<1||key>65535||std::floor(key)!=key){lua_pop(L,2);return false;}WebbarJsonString(out,std::to_string(uint32_t(key)));} + else{lua_pop(L,2);return false;} + out+=':';if(!Json(-1,out,depth+1,nodes)){lua_pop(L,2);return false;}lua_pop(L,1); + }out+='}';}break; + default:return false; + } + return out.size()<=262144; + } + bool Encode(int result,uint32_t epoch,const std::array& mouse,std::vector& packet){ + constexpr size_t HEADER=24,DESCRIPTOR=8,GROUPS=10,STRIDE=22,MAX_ROWS=262144; + const std::array names{"allyAA_attackrange_gl4","allycannon_attackrange_gl4","allyground_attackrange_gl4","allylrpc_attackrange_gl4","allynano_attackrange_gl4","enemyAA_attackrange_gl4","enemycannon_attackrange_gl4","enemyground_attackrange_gl4","enemylrpc_attackrange_gl4","enemynano_attackrange_gl4"}; + packet.assign(HEADER+DESCRIPTOR*GROUPS,0);packet[0]=0x32415257u;packet[1]=gs->frameNum;packet[2]=epoch; + packet[3]=gu->myPlayerNum;packet[4]=gu->myTeam;packet[5]=gu->myAllyTeam;packet[6]=uint32_t(gu->spectating)|(uint32_t(gu->spectatingFullView)<<1); + packet[7]=GROUPS;packet[9]=STRIDE;packet[10]=DESCRIPTOR; + packet[13]=HEADER;std::copy(mouse.begin(),mouse.end(),packet.begin()+16); + lua_getfield(L,result,"state");if(!lua_istable(L,-1))return false;const int state=lua_gettop(L); + lua_getfield(L,state,"disabled");if(lua_type(L,-1)!=LUA_TBOOLEAN)return false;if(lua_toboolean(L,-1))packet[6]|=4;lua_pop(L,1); + lua_getfield(L,state,"shaderConfig");if(!lua_istable(L,-1))return false;lua_getfield(L,-1,"MYGRAVITY"); + const float gravity=lua_tonumber(L,-1);if(lua_type(L,-1)!=LUA_TNUMBER||!std::isfinite(gravity))return false;std::memcpy(&packet[12],&gravity,4);lua_pop(L,2); + lua_getfield(L,state,"groups");if(!lua_istable(L,-1)||lua_objlen(L,-1)!=GROUPS)return false;const int groups=lua_gettop(L); + for(size_t g=0;g4096||std::floor(vertices)!=vertices)return false;lua_pop(L,1); + lua_getfield(L,group,"rows");if(!lua_istable(L,-1)||lua_objlen(L,-1)>65536)return false;const int rows=lua_gettop(L),count=lua_objlen(L,rows); + if(packet[8]+count>MAX_ROWS||((packet[6]&4)&&count))return false; + packet[at]=g+1;packet[at+1]=vertices;packet[at+2]=count;packet[at+3]=packet.size();packet[8]+=count; + for(int i=1;i<=count;++i){ + lua_rawgeti(L,rows,i);if(!lua_istable(L,-1))return false;const int row=lua_gettop(L); + lua_getfield(L,row,"id");const float id=lua_tonumber(L,-1);if(lua_type(L,-1)!=LUA_TNUMBER||id<0||id>65535||std::floor(id)!=id)return false;lua_pop(L,1); + const auto* unit=unitHandler.GetUnit(int(id));if(!Admitted(unit)||(g<5)!=(unit->allyteam==gu->myAllyTeam))return false; + char token[9];std::snprintf(token,sizeof(token),"%08x",RangeLifetime(unit)); + lua_getfield(L,row,"lifetime");size_t length=0;const char* life=lua_tolstring(L,-1,&length);if(lua_type(L,-1)!=LUA_TSTRING||length!=8||std::memcmp(life,token,8))return false;lua_pop(L,1); + packet.push_back(uint32_t(id));packet.push_back(RangeLifetime(unit)); + lua_getfield(L,row,"params");if(!lua_istable(L,-1)||lua_objlen(L,-1)!=20)return false; + for(int p=1;p<=20;++p){lua_rawgeti(L,-1,p);const float value=lua_tonumber(L,-1);if(lua_type(L,-1)!=LUA_TNUMBER||!std::isfinite(value))return false;uint32_t word;std::memcpy(&word,&value,4);packet.push_back(word);lua_pop(L,1);}lua_pop(L,2); + }lua_pop(L,2); + }lua_pop(L,2); + std::string json="{\"commands\":";uint32_t nodes=0;lua_getfield(L,result,"commands");if(!Json(-1,json,0,nodes))return false;lua_pop(L,1); + json+=",\"minimapCommands\":";lua_getfield(L,result,"minimapCommands");if(!Json(-1,json,0,nodes))return false;lua_pop(L,1);json+='}'; + packet[11]=json.size();const size_t offset=packet.size();packet.resize(offset+(json.size()+3)/4,0);std::memcpy(packet.data()+offset,json.data(),json.size());return true; + } +}; + +namespace WebbarNativeAttack { +static WebbarNativeAttackReader* reader=nullptr; +static std::array perspective{-2,-2,-2,-2,-2};static uint32_t epoch=0; +static void Free(){delete reader;reader=nullptr;perspective={-2,-2,-2,-2,-2};} +static void Poll(){ + if(!std::getenv("WEBBAR_NATIVE_ATTACK_RANGES")||!std::getenv("WEBBAR_BROWSER")||std::getenv("WEBBAR_NETWORK")||WebbarUiEvents::CatchingUp())return; + static auto next=std::chrono::steady_clock::time_point::min();const auto now=std::chrono::steady_clock::now();if(now bytes{}; + const int size=MAIN_THREAD_EM_ASM_INT({return Module['webbarPollNativeAttack']?Module['webbarPollNativeAttack']($0,$1):0;},bytes.data(),bytes.size()); + if(sizeint(bytes.size()))return;next=now+std::chrono::microseconds(33334); + Header h;std::memcpy(&h,bytes.data(),sizeof(h));if(h.magic!=0x32515257u||h.version!=2||!h.request||h.request==0xffffffffu||!h.generation||h.generation==0xffffffffu)return; + const auto reply=[&](uint32_t status,const std::vector& packet=std::vector{}){ + const std::string json="{\"version\":1,\"request\":"+std::to_string(h.request)+",\"generation\":"+std::to_string(h.generation)+",\"team\":"+std::to_string(gu->myTeam)+",\"allyTeam\":"+std::to_string(gu->myAllyTeam)+",\"fullView\":"+(gu->spectatingFullView?"true":"false")+",\"frame\":"+std::to_string(gs->frameNum)+",\"status\":"+std::to_string(status)+"}"; + MAIN_THREAD_EM_ASM({if(Module['webbarNativeAttackResult'])Module['webbarNativeAttackResult'](UTF8ToString($0),$2?HEAPU8.slice($1,$1+$2).buffer:null);},json.c_str(),packet.data(),packet.size()*4); + }; + const bool active=h.reserved[1]&1;const int command=int32_t(h.reserved[0]);const uint32_t input=h.reserved[1]>>1; + if(h.kind!=1||h.count>8192||h.flags>1||(input&~16383u)||(!active&&command)||command<=-16777216||command>=16777216||size!=int(sizeof(Header)+sizeof(WebbarInfoWorldView)+16+h.count*sizeof(Row))){reply(1);return;} + if(!teamHandler.IsValidTeam(gu->myTeam)||!teamHandler.IsValidAllyTeam(gu->myAllyTeam)||h.team!=gu->myTeam||h.allyTeam!=gu->myAllyTeam||h.flags!=uint32_t(gu->spectatingFullView)){reply(2);return;} + if(h.frame>uint32_t(gs->frameNum)||uint32_t(gs->frameNum)-h.frame>30){reply(3);return;} + WebbarInfoWorldView view;std::memcpy(&view,bytes.data()+sizeof(Header),sizeof(view));if(!WebbarNativeInfoReader::ValidCursorView(view)){reply(1);return;} + std::array minimapArea;std::memcpy(minimapArea.data(),bytes.data()+sizeof(Header)+sizeof(view),16); + for(const float value:minimapArea)if(!std::isfinite(value)||std::fabs(value)>1048576){reply(1);return;} + if(minimapArea[0]>=minimapArea[1]||minimapArea[2]==minimapArea[3]){reply(1);return;} + std::vector ids;std::unordered_set seen; + for(uint32_t i=0;i65535||!seen.insert(row.id).second){reply(1);return;} + const auto* unit=unitHandler.GetUnit(row.id); + if(!unit||unit->isDead||unit->noSelect||!WebbarVisible(unit)||!CSelectedUnitsHandler::CanISelectTeam(playerHandler.Player(gu->myPlayerNum),unit->team) + ||(row.lifetime&&(row.lifetime==0xffffffffu||unit->team!=gu->myTeam||WebbarHudLifetime(unit)!=row.lifetime))){reply(2);return;}ids.push_back(row.id); + } + const std::array actual{gu->myPlayerNum,gu->myTeam,gu->myAllyTeam,int(gu->spectating),int(gu->spectatingFullView)}; + if(perspective!=actual){Free();perspective=actual;if(++epoch==0)++epoch;} + if(!WebbarNativeInfo::reader)WebbarNativeInfo::reader=new WebbarNativeInfoReader; + if(!reader)reader=new WebbarNativeAttackReader; + std::vector packet;if(!reader->Read(view,ids,command,active,input,minimapArea,epoch,packet)){if(!reader->ready)Free();reply(4);return;}reply(0,packet); +} +} +static void FreeWebbarNativeAttack(){WebbarNativeAttack::Free();} --- /dev/null +++ b/rts/Game/WebbarNativeAttackPolicy.h @@ -0,0 +1,8204 @@ +/* Original BAR GPL-2.0-or-later policy; generated by scripts/native-attack-ranges.mjs. */ +#pragma once +static constexpr const char* WEBBAR_ATTACK_POLICY=R"WEBBAR_ATTACK( +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 + +-- Read-only native host for the unchanged tracker/radar widget sources. +-- Graphics storage is observed in Lua; no GL, commands, VFS, IO or text actions +-- are exposed. Only the finite event aliases in after.lua reach the engine. +local function noop()end +local function copy(t)local out={};for k,v in pairs(t)do out[k]=type(v)=='table'and copy(v)or v end;return out end +table.copy=copy +WG={} +LOG={DEPRECATED=0} +GL={ARRAY_BUFFER=34962,UNSIGNED_INT=5125,TRIANGLES=4,NOTEQUAL=517,LINE_LOOP=2,KEEP=7680,REPLACE=7681} +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} +gl={GetVBO=function()return setmetatable({},{__index=storage})end,GetVAO=function()return setmetatable({},{__index=vao})end, + CreateShader=noop,CreateTexture=function()return 1 end,DeleteTexture=noop,LuaShader={CheckShaderUpdates=function()return shader end}} +-- Headless has no viewport. These values only initialize unused graphical +-- storage; browser draw width/resolution come from its actual current viewport. +Spring.GetViewGeometry=function()return 1280,720 end +-- Keep the actual native configuration reader. +local removed=false +widgetHandler={RegisterGlobal=noop,DeregisterGlobal=noop,RemoveWidget=function()removed=true end,AddSpadsMessage=noop} +local listeners={} +Script.LuaUI=setmetatable({},{__call=function(_,name)return listeners[name]~=nil end,__index=function(_,name)return listeners[name]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)() +-- UI input is supplied only after native selection/command/camera validation. +-- All unit, weapon, terrain, LOS and team facts remain native Spring queries. +local rangeInput={selection={},mouse={x=-1,y=-1,offscreen=true},mods={false,false,false,false},hidden=false,quitting=false} +local Spring=setmetatable({ + GetSelectedUnits=function()return rangeInput.selection end, + GetMouseState=function() + local m=rangeInput.mouse + return m.x,m.y,m.left==true,m.middle==true,m.right==true,m.offscreen==true,m.pan==true + end, + GetModKeyState=function()return unpack(rangeInput.mods)end, + GetActiveCommand=function() + local active=rangeInput.active + if active then return active.index,active.id end + end, + GetMiniMapRotation=function()return(rangeInput.minimapRotation or 0)*math.pi*.5 end, + IsGUIHidden=function()return rangeInput.hidden end, +}, {__index=Spring}) +local native={Spring=Spring,UnitDefs=UnitDefs,WeaponDefs=WeaponDefs,Game=Game,CMD=CMD, + topbar={showingQuit=function()return rangeInput.quitting end},lifetime=WebbarAttackLifetime, + minimap=setmetatable({getNormalizedVisibleArea=function()return unpack(rangeInput.minimapArea or{0,1,0,1})end}, + {__index=function(_,key)if key=='isDrawingInPip'then return rangeInput.pip==true end end})} + +local factory=(function() +return function(native) +-- Only the caller's read-only native Spring handle supplies game facts. +-- All graphics, actions and settings below belong to this private Lua state. +local function noop()end +local function copy(t)local out={};for k,v in pairs(t)do out[k]=type(v)=='table'and copy(v)or v end;return out end +local savedSettings +local table=setmetatable({copy=copy,save=function(value,path) + assert(path=='LuaUI/config/AttackRangeConfig2.lua');savedSettings=copy(value) +end,toString=function()return ''end},{__index=table}) +local Spring=setmetatable({Echo=noop,PlaySoundFile=noop,Debug={TraceFullEcho=noop}},{__index=assert(native.Spring)}) +local UnitDefs,WeaponDefs,Game=assert(native.UnitDefs),assert(native.WeaponDefs),assert(native.Game) +local CMD=assert(native.CMD) +local math=native.math or math +local WG={topbar=native.topbar,minimap=native.minimap} +-- The stock widget handler gives each widget its own script environment. +-- Keep its undeclared per-widget fields private in this factory as well. +local chobbyInterface,myTeamID,myAllyTeamID +local KEYSYMS +local function loadfile(path) + assert(path=='LuaUI/config/AttackRangeConfig2.lua') + if native.savedSettings then return function()return copy(native.savedSettings)end end +end +local LOG={DEPRECATED=0} +local GL={ARRAY_BUFFER=34962,FLOAT=5126,UNSIGNED_INT=5125,TRIANGLES=4,TRIANGLE_FAN=6,NOTEQUAL=517,LINE_LOOP=2,LEQUAL=515,STENCIL_BUFFER_BIT=1024,KEEP=7680,REPLACE=7681} +local actions,removed,recording,commands={},false,false,{} +local widgetHandler={RemoveWidget=function()removed=true end, + AddAction=function(_,name,fn,data)actions[name]={fn=fn,data=data}end, + RemoveAction=function(_,name)actions[name]=nil end} +local function record(name,...) + if recording then commands[#commands+1]={name=name,args={...}}end +end +local currentShader +local storage={Define=noop,Delete=noop,InstanceDataFromUnitIDs=noop,InstanceDataFromFeatureIDs=noop,GetID=function()return 1 end, + Upload=function(self,data)self.data=copy(data)end} +local gl +local pendingVAOs={} +local function groupName(name)return assert(name:match('^(.-_attackrange_gl4)'),'Unknown original range group')end +local vao={AttachVertexBuffer=noop,AttachInstanceBuffer=noop,AttachIndexBuffer=noop,Delete=noop, + DrawArrays=function(self,...) + if not recording then return end + local name + for key,buffer in pairs(WG.VBOTableRegistry or{})do if buffer.VAO==self then name=groupName(key);break end end + assert(name,'Original range draw uses an unknown VBO') + assert(currentShader,'Original range draw has no active shader') + commands[#commands+1]={name='DrawArrays',group=name,args={...},uniforms=copy(currentShader.uniforms)} + end} +local shaderMethods={Activate=function(self)currentShader=self end,Deactivate=function()currentShader=nil end, + SetUniform=function(self,name,...)self.uniforms[name]={...}end, + SetUniformInt=function(self,name,...)self.uniforms[name]={...}end} +local shaderConfig +gl={ObjectLabel=noop,GetVBO=function()return setmetatable({},{__index=storage})end,GetVAO=function() + local object=setmetatable({},{__index=vao});pendingVAOs[object]=true;return object +end, + LuaShader={CheckShaderUpdates=function(cache) + shaderConfig=copy(cache.shaderConfig) + local uniforms={};for _,kind in ipairs({'uniformInt','uniformFloat'})do + for name,value in pairs(cache[kind]or{})do uniforms[name]=type(value)=='table'and copy(value)or{value}end + end + return setmetatable({uniforms=uniforms},{__index=shaderMethods}) + end}} +for _,name in ipairs({'Clear','ColorMask','DepthTest','LineWidth','StencilFunc','StencilMask','StencilOp','StencilTest','Texture'})do + gl[name]=function(...)record(name,...)end +end + +local function include(path)assert(path=="keysym.h.lua");return(function() +-------------------------------------------------------------------------------- +-------------------------------------------------------------------------------- +-- +-- file: keysym.h.lua +-- brief: key symbol constants +-- author: Dave Rodgers +-- +-- Copyright (C) 2007. +-- Licensed under the terms of the GNU GPL, v2 or later. +-- +-------------------------------------------------------------------------------- +-------------------------------------------------------------------------------- + +-- From SDL_keysym.h + +KEYSYMS = { + + UNKNOWN = 0, + FIRST = 0, + BACKSPACE = 8, + TAB = 9, + CLEAR = 12, + RETURN = 13, + PAUSE = 19, + ESCAPE = 27, + SPACE = 32, + EXCLAIM = 33, + QUOTEDBL = 34, + HASH = 35, + DOLLAR = 36, + AMPERSAND = 38, + QUOTE = 39, + LEFTPAREN = 40, + RIGHTPAREN = 41, + ASTERISK = 42, + PLUS = 43, + COMMA = 44, + MINUS = 45, + PERIOD = 46, + SLASH = 47, + + -- '0' to '9' + N_0 = 48, + N_1 = 49, + N_2 = 50, + N_3 = 51, + N_4 = 52, + N_5 = 53, + N_6 = 54, + N_7 = 55, + N_8 = 56, + N_9 = 57, + + COLON = 58, + SEMICOLON = 59, + LESS = 60, + EQUALS = 61, + GREATER = 62, + QUESTION = 63, + AT = 64, + + -- + -- Skip uppercase letters + -- + + LEFTBRACKET = 91, + BACKSLASH = 92, + RIGHTBRACKET = 93, + CARET = 94, + UNDERSCORE = 95, + BACKQUOTE = 96, + A = 97, -- actually 'a' ascii + B = 98, + C = 99, + D = 100, + E = 101, + F = 102, + G = 103, + H = 104, + I = 105, + J = 106, + K = 107, + L = 108, + M = 109, + N = 110, + O = 111, + P = 112, + Q = 113, + R = 114, + S = 115, + T = 116, + U = 117, + V = 118, + W = 119, + X = 120, + Y = 121, + Z = 122, + DELETE = 127, + -- End of ASCII mapped keysyms + + -- International keyboard syms + WORLD_0 = 160, -- 0xA0 + WORLD_1 = 161, + WORLD_2 = 162, + WORLD_3 = 163, + WORLD_4 = 164, + WORLD_5 = 165, + WORLD_6 = 166, + WORLD_7 = 167, + WORLD_8 = 168, + WORLD_9 = 169, + WORLD_10 = 170, + WORLD_11 = 171, + WORLD_12 = 172, + WORLD_13 = 173, + WORLD_14 = 174, + WORLD_15 = 175, + WORLD_16 = 176, + WORLD_17 = 177, + WORLD_18 = 178, + WORLD_19 = 179, + WORLD_20 = 180, + WORLD_21 = 181, + WORLD_22 = 182, + WORLD_23 = 183, + WORLD_24 = 184, + WORLD_25 = 185, + WORLD_26 = 186, + WORLD_27 = 187, + WORLD_28 = 188, + WORLD_29 = 189, + WORLD_30 = 190, + WORLD_31 = 191, + WORLD_32 = 192, + WORLD_33 = 193, + WORLD_34 = 194, + WORLD_35 = 195, + WORLD_36 = 196, + WORLD_37 = 197, + WORLD_38 = 198, + WORLD_39 = 199, + WORLD_40 = 200, + WORLD_41 = 201, + WORLD_42 = 202, + WORLD_43 = 203, + WORLD_44 = 204, + WORLD_45 = 205, + WORLD_46 = 206, + WORLD_47 = 207, + WORLD_48 = 208, + WORLD_49 = 209, + WORLD_50 = 210, + WORLD_51 = 211, + WORLD_52 = 212, + WORLD_53 = 213, + WORLD_54 = 214, + WORLD_55 = 215, + WORLD_56 = 216, + WORLD_57 = 217, + WORLD_58 = 218, + WORLD_59 = 219, + WORLD_60 = 220, + WORLD_61 = 221, + WORLD_62 = 222, + WORLD_63 = 223, + WORLD_64 = 224, + WORLD_65 = 225, + WORLD_66 = 226, + WORLD_67 = 227, + WORLD_68 = 228, + WORLD_69 = 229, + WORLD_70 = 230, + WORLD_71 = 231, + WORLD_72 = 232, + WORLD_73 = 233, + WORLD_74 = 234, + WORLD_75 = 235, + WORLD_76 = 236, + WORLD_77 = 237, + WORLD_78 = 238, + WORLD_79 = 239, + WORLD_80 = 240, + WORLD_81 = 241, + WORLD_82 = 242, + WORLD_83 = 243, + WORLD_84 = 244, + WORLD_85 = 245, + WORLD_86 = 246, + WORLD_87 = 247, + WORLD_88 = 248, + WORLD_89 = 249, + WORLD_90 = 250, + WORLD_91 = 251, + WORLD_92 = 252, + WORLD_93 = 253, + WORLD_94 = 254, + WORLD_95 = 255, -- 0xFF + + -- Numeric keypad + KP0 = 256, + KP1 = 257, + KP2 = 258, + KP3 = 259, + KP4 = 260, + KP5 = 261, + KP6 = 262, + KP7 = 263, + KP8 = 264, + KP9 = 265, + KP_PERIOD = 266, + KP_DIVIDE = 267, + KP_MULTIPLY = 268, + KP_MINUS = 269, + KP_PLUS = 270, + KP_ENTER = 271, + KP_EQUALS = 272, + + -- Arrows + Home/End pad + UP = 273, + DOWN = 274, + RIGHT = 275, + LEFT = 276, + INSERT = 277, + HOME = 278, + END = 279, + PAGEUP = 280, + PAGEDOWN = 281, + + -- Function keys + F1 = 282, + F2 = 283, + F3 = 284, + F4 = 285, + F5 = 286, + F6 = 287, + F7 = 288, + F8 = 289, + F9 = 290, + F10 = 291, + F11 = 292, + F12 = 293, + F13 = 294, + F14 = 295, + F15 = 296, + + -- Key state modifier keys + NUMLOCK = 300, + CAPSLOCK = 301, + SCROLLOCK = 302, + RSHIFT = 303, + LSHIFT = 304, + RCTRL = 305, + LCTRL = 306, + RALT = 307, + LALT = 308, + RMETA = 309, + LMETA = 310, + LSUPER = 311, -- Left "Windows" key + RSUPER = 312, -- Right "Windows" key + MODE = 313, -- "Alt Gr" key + COMPOSE = 314, -- Multi-key compose key + + -- Miscellaneous function keys + HELP = 315, + PRINT = 316, + SYSREQ = 317, + BREAK = 318, + MENU = 319, + POWER = 320, -- Power Macintosh power key + EURO = 321, -- Some european keyboards + UNDO = 322, -- Atari keyboard has Undo + + -- Add any other keys here + LAST = 323 +} + +end)()end +local VFS={Include=function(path)assert(path=="luaui/Include/minimap_utils.lua");return(function() +local mapWidth = Game.mapSizeX +local mapHeight = Game.mapSizeZ + +local spGetMiniMapGeometry = Spring.GetMiniMapGeometry +local spGetGroundHeight = Spring.GetGroundHeight +local spGetMiniMapRotation = Spring.GetMiniMapRotation + +local math_floor = math.floor +local PI_HALF = math.pi / 2 +local PI_THREE_HALF = 3 * math.pi / 2 + +local function getMiniMapFlipped() + if not spGetMiniMapRotation then return false end + + local rot = spGetMiniMapRotation() + + return rot > PI_HALF and rot <= PI_THREE_HALF; +end + +local ROTATION = { + DEG_0 = 0, -- 0 degrees + DEG_90 = 1, -- 90 degrees clockwise + DEG_180 = 2, -- 180 degrees + DEG_270 = 3 -- 270 degrees clockwise (or 90 degrees counter-clockwise) +} + +local function getCurrentMiniMapRotationOption() -- Spring.GetMiniMapRotation() returns rads, instead here we return iterations of 90 degrees (0, 1, 2, 3) + if not spGetMiniMapRotation then return ROTATION.NONE end + + return math_floor((spGetMiniMapRotation() / math.pi * 2 + 0.5) % 4) +end + +local function minimapToWorld(x, y, vpy, dualScreen) + local px, py, sx, sy = spGetMiniMapGeometry() + if dualScreen == "left" then + x = x + sx + px + end + x = ((x - px) / sx) + local z = (1 - (y - py + vpy)/sy) + + local currRot = getCurrentMiniMapRotationOption() + + if currRot == ROTATION.DEG_90 then -- rotate 90 degrees + x,z = z,x + x = 1 - x + elseif currRot == ROTATION.DEG_180 then -- rotate 180 degrees + x = 1 - x + z = 1 - z + elseif currRot == ROTATION.DEG_270 then -- rotate 270 degrees + x, z = z, x + z = 1 - z + end + + x = x * mapWidth + z = z * mapHeight + + y = spGetGroundHeight(x, z) + + return x, y, z +end + +return { getMiniMapFlipped = getMiniMapFlipped, minimapToWorld = minimapToWorld, getCurrentMiniMapRotationOption = getCurrentMiniMapRotationOption, ROTATION = ROTATION } + +end)()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)() +-- Observe original VBO insertion/removal, without changing its data or return +-- values. A reused unit ID must never inherit an older ring's authority. +local rangeLives=setmetatable({},{__mode='k'}) +local pushRange=gl.InstanceVBOTable.pushElementInstance +gl.InstanceVBOTable.pushElementInstance=function(buffer,data,instance,update,noUpload,unit) + local fresh=instance==nil or buffer.instanceIDtoIndex[instance]==nil + local result=pushRange(buffer,data,instance,update,noUpload,unit) + if result and fresh then + local lives=rangeLives[buffer]or{};rangeLives[buffer]=lives + lives[result]=assert(native.lifetime(unit),'Native range insertion requires a lifetime') + end + return result +end +local popRange=gl.InstanceVBOTable.popElementInstance +gl.InstanceVBOTable.popElementInstance=function(buffer,instance,noUpload) + local result=popRange(buffer,instance,noUpload) + if result and rangeLives[buffer]then rangeLives[buffer][instance]=nil end + return result +end + +local widget=(function()local widget={} +include("keysym.h.lua") + +local versionNumber = "1.2" + +local widget = widget ---@type Widget + +function widget:GetInfo() + return { + name = "Attack Range GL4", + desc = + "[v" .. string.format("%s", versionNumber ) .. "] Displays attack ranges of selected units. Alt+, and alt+. (alt comma and alt period) to cycle backward and forward through display config of current unit (saved through games!). Custom keybind to toggle cursor unit range on and off.", + author = "Errrrrrr, Beherith", + date = "July 20, 2023", + license = "Lua: GPLv2, GLSL: (c) Beherith (mysterme@gmail.com)", + layer = -99, + enabled = true, + depends = {'gl4'}, + } +end + +-- Localized functions for performance +local mathAbs = math.abs +local mathFloor = math.floor +local mathMax = math.max +local mathPi = math.pi + +-- Localized Spring API for performance +local spGetMyTeamID = Spring.GetMyTeamID +local spEcho = Spring.Echo + +--------------------------- + +--[[ +Notes 2025.04.21 +Could we try to disable all engine range rings - and add them where needed? + +- [ ] attack + - Should already be completely handled by attack range gl4 +build +radar +- [ ] Needs a circle within radarpreview +- [ ] Needs a circle when mouseovered? +sonar +seismic +jammer +sonarjammer +shield + +decloak (already in widget Cloak/EMP range?) +extract + - [ ] I dont think this is needed at all any more with mex snap +Kamikaze? (do we use that) +SelfDestruct +InterceptorOn +InterceptorOff + + +]]-- + + +------------------------------------- +local autoReload = false + +--------------------------------------------------------------------------------------------------------------------------- +-- Bindable actions: cursor_range_toggle - Toggles display of the attack range of the unit under the mouse cursor. +-- attack_range_inc - Cycle to next attack range display config for current unit type. +-- attack_range_dec - Cycle to previous attack range display config for current unit type. +-- The widget's individual unit type's display setup is saved in LuaUI/config/AttackRangeConfig2.lua +--------------------------------------------------------------------------------------------------------------------------- +local shift_only = false -- only show ranges when shift is held down +local cursor_unit_range = true -- displays the range of the unit at the mouse cursor (if there is one) +local selectionDisableThreshold = 512 -- turns off when selection is above this number +local selectionDisableThresholdMult = 0.7 + +--------------------------------------------------------------------------------------------------------------------------- +------------------ CONFIGURABLES -------------- + +local DYNAMIC_RANGE_UPDATE_RATE = 3.0 + +local buttonConfig = { + ally = { ground = true, AA = true, nano = true }, + enemy = { ground = true, AA = true, nano = true } +} + +local colorConfig = { + drawStencil = true, -- whether to draw the outer, merged rings (quite expensive!) + cannon_separate_stencil = false, -- set to true to have cannon and ground be on different stencil mask + drawInnerRings = true, -- whether to draw inner, per attack rings (very cheap) + + externalalpha = 0.75, -- alpha of outer rings + internalalpha = 0.12, -- alpha of inner rings + fill_alpha = 0.12, -- this is the solid color in the middle of the stencil + outer_fade_height_difference = 2500, -- this is the height difference at which the outer ring starts to fade out compared to inner rings + ground = { + color = { 1.0, 0.22, 0.05, 0.60 }, + fadeparams = { 4000, 6000, 1.0, 0.0 }, -- FadeStart, FadeEnd, StartAlpha, EndAlpha + groupselectionfadescale = 0.75, + externallinethickness = 3.0, + internallinethickness = 1.8, + minimapexternallinethickness = 1.0, + minimapinternallinethickness = 0.5, + }, + nano = { + color = { 0.24, 1.0, 0.2, 0.60 }, + fadeparams = { 2000, 4000, 1.0, 0.0 }, -- FadeStart, FadeEnd, StartAlpha, EndAlpha + groupselectionfadescale = 0.05, + externallinethickness = 3.0, + internallinethickness = 2.0, + minimapexternallinethickness = 1.0, + minimapinternallinethickness = 0.5, + }, + AA = { + color = { 0.8, 0.44, 2.0, 0.40 }, + fadeparams = { 2000, 5000, 1.0, 0.0 }, -- FadeStart, FadeEnd, StartAlpha, EndAlpha + groupselectionfadescale = 0.75, + externallinethickness = 3.0, + internallinethickness = 1.8, + minimapexternallinethickness = 1.5, + minimapinternallinethickness = 0.5, + }, + cannon = { + color = {1.0, 0.22, 0.05, 0.60}, + fadeparams = { 5000, 8500, 1.0, 0.0 }, -- FadeStart, FadeEnd, StartAlpha, EndAlpha + groupselectionfadescale = 0.75, + externallinethickness = 3.0, + internallinethickness = 1.8, + minimapexternallinethickness = 1.0, + minimapinternallinethickness = 0.5, + }, + lrpc = { + color = {1.0, 0.22, 0.05, 0.60}, + fadeparams = { 5000, 1000, 1.0, 0.5 }, -- FadeStart, FadeEnd, StartAlpha, EndAlpha + groupselectionfadescale = 0.75, + externallinethickness = 2.0, + internallinethickness = 2.0, -- Not used as LRPC is not stencilled + minimapexternallinethickness = 2.0, + minimapinternallinethickness = 0.5, + }, + -- ground_water = { + -- color = { 0.2, 0.5, 1.0, 0.60 }, -- RGBA blue + -- fadeparams = colorConfig.ground.fadeparams, + -- groupselectionfadescale = colorConfig.ground.groupselectionfadescale, + -- externallinethickness = colorConfig.ground.externallinethickness, + -- internallinethickness = colorConfig.ground.internallinethickness, + -- minimapexternallinethickness = colorConfig.ground.minimapexternallinethickness, + -- minimapinternallinethickness = colorConfig.ground.minimapinternallinethickness, + -- }, +} + +-- Sub WEAPON types: + +-- DGUN +colorConfig.ground_dgun = { + color = colorConfig.ground.color, -- reuse ground colour + fadeparams = colorConfig.ground.fadeparams, -- same fade curve + groupselectionfadescale = colorConfig.ground.groupselectionfadescale, + externallinethickness = colorConfig.ground.externallinethickness, + internallinethickness = colorConfig.ground.internallinethickness, + minimapexternallinethickness = colorConfig.ground.minimapexternallinethickness, + minimapinternallinethickness = colorConfig.ground.minimapinternallinethickness, +} + +-- WATER WEAPONS +colorConfig.ground_water = { + color = {0.32, 0.48, 1.0, 0.30}, + fadeparams = colorConfig.ground.fadeparams, + groupselectionfadescale = colorConfig.ground.groupselectionfadescale, + externallinethickness = colorConfig.ground.externallinethickness, + internallinethickness = colorConfig.ground.internallinethickness, + minimapexternallinethickness = colorConfig.ground.minimapexternallinethickness, + minimapinternallinethickness = colorConfig.ground.minimapinternallinethickness, +} + +-- EMP (paralyzer) weapons +colorConfig.ground_emp = { + color = { 0.72, 0.72, 1.0, 0.60 }, -- EMP light blue + fadeparams = colorConfig.ground.fadeparams, + groupselectionfadescale = colorConfig.ground.groupselectionfadescale, + externallinethickness = colorConfig.ground.externallinethickness, + internallinethickness = colorConfig.ground.internallinethickness, + minimapexternallinethickness= colorConfig.ground.minimapexternallinethickness, + minimapinternallinethickness= colorConfig.ground.minimapinternallinethickness, +} + +---------------------------------- +local show_selected_weapon_ranges = true +local weaponTypeMap = { 'ground', 'nano', 'AA', 'cannon', 'lrpc' } + +local unitDefRings = {} --each entry should be a unitdefIDkey to a table: + +local vtoldamagetag = Game.armorTypes['vtol'] +local defaultdamagetag = Game.armorTypes['default'] + +-- globals +local minimapUtils = VFS.Include("luaui/Include/minimap_utils.lua") +local getCurrentMiniMapRotationOption = minimapUtils.getCurrentMiniMapRotationOption +local ROTATION = minimapUtils.ROTATION +local selUnitCount = 0 +local selBuilderCount = 0 -- we need builder count separately +local shifted = false +local isBuilding = false +local builders = {} -- { unitID = unitDef, ...} + +local unitToggles = {} +local unitTogglesChunked = {} + + +local unitName = {} +local unitWeapons = {} +local unitMaxWeaponRange = {} +local unitBuildDistance = {} +local unitBuilder = {} +local unitOnOffable = {} +local unitOnOffName = {} +local unitDefRangeScale = {} +for udid, ud in pairs(UnitDefs) do + unitBuilder[udid] = ud.isBuilder and (ud.canAssist or ud.canReclaim) and not (ud.isFactory and #ud.buildOptions > 0) + if unitBuilder[udid] then + unitBuildDistance[udid] = ud.buildDistance + end + unitName[udid] = ud.name + unitWeapons[udid] = ud.weapons + unitMaxWeaponRange[udid] = ud.maxWeaponRange + unitOnOffable[udid] = ud.onOffable + if ud.customParams.onoffname then + unitOnOffName[udid] = ud.customParams.onoffname + end + if ud.customParams.rangexpscale then + unitDefRangeScale[udid] = ud.customParams.rangexpscale + end +end + +local chunk, err = loadfile("LuaUI/config/AttackRangeConfig2.lua") +if chunk then + local tmp = {} + setfenv(chunk, tmp) + unitTogglesChunked = chunk() +end + +--helpers +local function convertToBitmap(statusTable) + if type(statusTable) ~= "table" then + return 0 + end + local bitmap = 0 + for i, status in ipairs(statusTable) do + if status then + bitmap = bitmap + 2 ^ (i - 1) + end + end + return bitmap +end + +local function convertToStatusTable(bitmap, numWeapons) + local statusTable = {} + for i = 1, numWeapons do + local status = bitmap % 2 == 1 + table.insert(statusTable, status) + bitmap = (bitmap - (bitmap % 2)) / 2 + end + return statusTable +end + +local function getNextWeaponCombination(currentCombination, direction) + local numWeapons = #currentCombination + local bitmap = convertToBitmap(currentCombination) + + if direction == 1 then + bitmap = (bitmap + 1) % (2 ^ numWeapons) + elseif direction == -1 then + bitmap = (bitmap - 1) % (2 ^ numWeapons) + end + + return convertToStatusTable(bitmap, numWeapons) +end + +local function initializeUnitDefRing(unitDefID) + local weapons = unitWeapons[unitDefID] + unitDefRings[unitDefID]['rings'] = {} + local weaponCount = #weapons or 0 + for weaponNum = 1, #weapons do + local weaponDefID = weapons[weaponNum].weaponDef + local weaponDef = WeaponDefs[weaponDefID] + + -- ── your debug & color‐pick here ── + -- spEcho(string.format( + -- "[AttackRange] %s.waterweapon = %s", + -- weaponDef.name, tostring(weaponDef.waterweapon) + -- )) + + local range = weaponDef.range + local dps = 0 + local weaponType = unitDefRings[unitDefID]['weapons'][weaponNum] + + if weaponType ~= nil and weaponType > 0 then + local damage = 0 + if weaponType == 3 then --AA + damage = weaponDef.damages[vtoldamagetag] + else + damage = weaponDef.damages[defaultdamagetag] + end + dps = damage * (weaponDef.salvoSize or 1) / (weaponDef.reload or 1) + -- local color = colorConfig[weaponTypeMap[weaponType]].color + -- local fadeparams = colorConfig[weaponTypeMap[weaponType]].fadeparams + + -- after you have `weaponDef` and `weaponType`… + local baseKey = weaponTypeMap[ weaponType ] -- e.g. "ground", "AA", etc. + local cfgKey = baseKey + + -- 1) paralyzer/EMP weapons + if weaponDef.paralyzer then + cfgKey = baseKey .. "_emp" + --spEcho("[AttackRange] using EMP colour for:", weaponDef.name) + -- 2) DGun override + elseif weaponDef.type == "DGun" then + cfgKey = baseKey .. "_dgun" + --spEcho("[AttackRange] using DGun style for:", weaponDef.name) + -- 2) then water override + elseif weaponDef.waterWeapon + or (weaponDef.customParams and weaponDef.customParams.waterweapon == "true") + then + cfgKey = baseKey .. "_water" + --spEcho("[AttackRange] using water style for:", weaponDef.name) + end + + -- safety fallback if you typo the key + if not colorConfig[cfgKey] then + cfgKey = baseKey + end + + local color = colorConfig[cfgKey].color + local fadeparams = colorConfig[cfgKey].fadeparams + + local isCylinder = 0 + if (weaponDef.cylinderTargeting) and (weaponDef.cylinderTargeting > 0.0) then + isCylinder = 1 + end + local isDgun = (weaponDef.type == "DGun") and 1 or 0 + + local wName = weaponDef.name + if (weaponDef.type == "AircraftBomb") or weaponDef.customParams.bogus == "1" or weaponDef.customParams.norangering then + range = 0 + end + --spEcho("weaponNum: ".. weaponNum ..", name: " .. tableToString(weaponDef.name)) + local groupselectionfadescale = colorConfig[weaponTypeMap[weaponType]].groupselectionfadescale + + --local udwp = UnitDefs[unitDefID].weapons + -- weapons[weaponNum].maxAngleDif is : + -- 0 for 180 + -- -1 for 360 + -- 0.707 for 90 + + -- Because I cant be assed to calculate the full 3d cone-ground intersection slice within the vertex shader: + -- We are only going to display angles for weapons that actually point forward, e.g. mainDirXYZ of 0 0 1 + -- we need to output two numbers here, and pack it into one float + -- The integer part will be the offset around the circle, from forward dir, in degrees, +-180 + -- the fractional part will be the max left-right attack angle around the ground plane. + -- maindir = "0 0 1" is forward + -- exactly zero means no angle limits! + -- maindir "0 1 0" is designed for shooting at feet prevention! + + local maxangledif = 0 + + -- customParams (note the case), is a table of strings always + if (weapons[weaponNum].maxAngleDif > -1) and + (not (weaponDef.customParams and weaponDef.customParams.noattackrangearc)) then + --spEcho(weaponDef.customParams)--, weapons[weaponNum].customParams.noattackarc) + local offsetdegrees = 0 + local difffract = 0 + + local weaponParams = weapons[weaponNum] + local mdx = weaponParams.mainDirX + local mdy = weaponParams.mainDirY + local mdz = weaponParams.mainDirZ + local angledif = math.acos(weapons[weaponNum].maxAngleDif) / mathPi + + -- Normalize maindir + local length = math.diag(mdx,mdy,mdz) + mdx = mdx/length + mdy = mdy/length + mdz = mdz/length + + offsetdegrees = math.atan2(mdx,mdz) * 180 / mathPi + difffract = angledif --(1.0 - angledif ) * (0.5) -- So 0.001 is tiny aim angle, 0.9999 is full aim angle + + maxangledif = mathFloor(offsetdegrees) + + if mathAbs(mdy) > 0.01 and mathAbs(mdy) < 0.99 then -- its off the Y plane + local modifier = math.sqrt ( 1.0 - mdy*mdy) + difffract = difffract * modifier + maxangledif = maxangledif + difffract + elseif mathAbs(mdy) < 0.99 then + maxangledif = maxangledif + difffract + else + + end + + + + --spEcho(string.format("%s has params offsetdegrees = %.2f MAD = %.3f (%.1f deg), diffract = %.3f md(xyz) = (%.3f,%.3f,%.3f)", weaponDef.name, offsetdegrees, weapons[weaponNum].maxAngleDif, angledif*180, difffract, mdx,mdy,mdz)) + + + --spEcho("weapons[weaponNum].maxAngleDif",weapons[weaponNum].maxAngleDif, maxangledif) + --for k,v in pairs(weapons[weaponNum]) do spEcho(k,v)end + end + + --if weapons[weaponNum].maxAngleDif then spEcho(weapons[weaponNum].maxAngleDif,'for',weaponDef.name, 'saved as',maxangledif ) end + + local ringParams = { range, color[1], color[2], color[3], color[4], --5 + fadeparams[1], fadeparams[2], fadeparams[3], fadeparams[4], --9 + weaponDef.projectilespeed or 1, --10 + isCylinder,-- and 1 or 0, (11) + weaponDef.heightBoostFactor or 0, --12 + weaponDef.heightMod or 0, --13 + groupselectionfadescale, --14 + weaponType, --15 + isDgun, --16 + maxangledif --17 + } + unitDefRings[unitDefID]['rings'][weaponNum] = ringParams + end + end + + -- for builders, we need to add a special nano ring def + if unitBuilder[unitDefID] then + local range = unitBuildDistance[unitDefID] + local color = colorConfig['nano'].color + local fadeparams = colorConfig['nano'].fadeparams + local groupselectionfadescale = colorConfig['nano'].groupselectionfadescale + + local ringParams = { range, color[1], color[2], color[3], color[4], + fadeparams[1], fadeparams[2], fadeparams[3], fadeparams[4], + 1, + false, + 0, + 0, + groupselectionfadescale, + 2, + 0 + } + unitDefRings[unitDefID]['rings'][weaponCount + 1] = ringParams -- weaponCount + 1 is nano + end +end + +local function initUnitList() + unitDefRings = {} + + for unitDefID, _ in pairs(unitDefRings) do + initializeUnitDefRing(unitDefID) + end +end + +--Button display configuration +--position only relevant if no saved config data found + +local myAllyTeam = Spring.GetMyAllyTeamID() +local myTeamID = spGetMyTeamID() + +-------------------------------------------------------------------------------- + +local glDepthTest = gl.DepthTest +local glLineWidth = gl.LineWidth +local glTexture = gl.Texture +local glClear = gl.Clear +local glColorMask = gl.ColorMask +local glStencilTest = gl.StencilTest +local glStencilMask = gl.StencilMask +local glStencilFunc = gl.StencilFunc +local glStencilOp = gl.StencilOp +local GL_STENCIL_BUFFER_BIT = GL.STENCIL_BUFFER_BIT +local GL_TRIANGLE_FAN = GL.TRIANGLE_FAN +local GL_LEQUAL = GL.LEQUAL +local GL_LINE_LOOP = GL.LINE_LOOP +local GL_NOTEQUAL = GL.NOTEQUAL + +local GL_KEEP = 0x1E00 --GL.KEEP +local GL_REPLACE = GL.REPLACE --GL.KEEP + +local spGetUnitDefID = Spring.GetUnitDefID +local spGetUnitPosition = Spring.GetUnitPosition +local spGetUnitWeaponVectors=Spring.GetUnitWeaponVectors +local spGetUnitWeaponState = Spring.GetUnitWeaponState +local spGetUnitAllyTeam = Spring.GetUnitAllyTeam +local spGetMouseState = Spring.GetMouseState +local spTraceScreenRay = Spring.TraceScreenRay +local GetModKeyState = Spring.GetModKeyState +local GetActiveCommand = Spring.GetActiveCommand +local GetSelectedUnits = Spring.GetSelectedUnits +local chobbyInterface + +local CMD_ATTACK = CMD.ATTACK +local CMD_FIGHT = CMD.FIGHT +local CMD_AREA_ATTACK = CMD.AREA_ATTACK +local CMD_MANUALFIRE = CMD.MANUALFIRE + +local function defrangeCmd(_, line) + local command = line or "" + local ally = 'ally' + local rangetype = 'ground' + local enabled = false + if string.find(command, "enemy", nil, true) then + ally = 'enemy' + end + if string.find(command, "nano", nil, true) then + rangetype = 'nano' + elseif string.find(command, "AA", nil, true) then + rangetype = 'AA' + end + if string.find(command, "+", nil, true) then + enabled = true + end + buttonConfig[ally][rangetype] = enabled + spEcho("Range visibility of " .. ally .. " " .. rangetype .. " attacks set to", enabled) + return true +end + +------ GL4 THINGS ----- +-- AA and cannons: +local largeCircleVBO = nil +local largeCircleSegments = 1024 + +-- others: +local smallCircleVBO = nil +local smallCircleSegments = 128 + +local weaponTypeToString = { "ground", "nano", "AA", "cannon", 'lrpc' } +local allyenemypairs = { "ally", "enemy" } +local attackRangeClasses = { 'enemyground', 'enemyAA', 'enemynano', 'allyground', 'allyAA', 'enemycannon', 'allycannon', + 'allynano', 'allylrpc', 'enemylrpc' } +local attackRangeVAOs = {} + +local circleInstanceVBOLayout = { + { id = 1, name = 'posscale', size = 4 }, -- abs pos for static units, offset for dynamic units, scale is actual range, Y is turretheight + { id = 2, name = 'color1', size = 4 }, -- vec4 the color of this new + { id = 3, name = 'visibility', size = 4 }, --- vec4 FadeStart, FadeEnd, StartAlpha, EndAlpha + { id = 4, name = 'projectileParams', size = 4 }, --- projectileSpeed, iscylinder, heightBoostFactor , heightMod + { id = 5, name = 'additionalParams', size = 4 }, --- groupselectionfadescale, weaponType, ISDGUN, MAXANGLEDIF + { id = 6, name = 'instData', size = 4, type = GL.UNSIGNED_INT }, +} + +local LuaShader = gl.LuaShader +local InstanceVBOTable = gl.InstanceVBOTable +local popElementInstance = InstanceVBOTable.popElementInstance +local pushElementInstance = InstanceVBOTable.pushElementInstance + +local attackRangeShader = nil + +local shaderSourceCache = { + shaderName = 'Attack Range GL4', + vssrcpath = "LuaUI/Shaders/weapon_range_rings_unified_gl4.vert.glsl", + fssrcpath = "LuaUI/Shaders/weapon_range_rings_unified_gl4.frag.glsl", + shaderConfig = { + MYGRAVITY = Game.gravity + 0.1, + STATICUNITS = 0, + DEBUG = autoReload and 1 or 0, + MOUSEOVERALPHAMULTIPLIER = 1.0, + }, + uniformInt = { + heightmapTex = 0, + losTex = 1, + mapNormalTex = 2, + }, + uniformFloat = { + lineAlphaUniform = 1, + cannonmode = 0, + fadeDistOffset = 0, + drawMode = 0, + selBuilderCount = 1.0, + selUnitCount = 1.0, + inMiniMap = 0.0, + pipVisibleArea = {0, 1, 0, 1}, -- left, right, bottom, top in normalized [0,1] coords for PIP minimap + }, +} + +local function goodbye(reason) + spEcho("AttackRange GL4 widget exiting with reason: " .. reason) + widgetHandler:RemoveWidget() +end + + +local cacheTable = {} +for i = 1, 24 do cacheTable[i] = 0 end + + +-- code for selected units start here +local selectedUnits = {} +local selUnits = {} +local updateSelection = false +local selections = {} -- contains params for added vaos +local mouseUnit +local mouseovers = {} -- mirroring selections, but for mouseovers + +local unitsOnOff = {} -- unit weapon toggle states, tracked from CommandNotify (also building on off status) +local unitRangeScale = { selections = {}, mouseovers = {} } -- stores info for units with scaling ranges +local numScalingUnits = 0 +local myTeam = spGetMyTeamID() + +-- mirrors functionality of UnitDetected +local function AddSelectedUnit(unitID, mouseover, newRange) + --if not show_selected_weapon_ranges then return end + local collections = selections + if mouseover then + collections = mouseovers + end + + local unitDefID = spGetUnitDefID(unitID) + if not unitDefID then return end + if collections[unitID] ~= nil then return end + + --- if unittype is toggled off we don't proceed at all + local currentUnitName = unitName[unitDefID] + local alliedUnit = (spGetUnitAllyTeam(unitID) == myAllyTeam) + local allystring = alliedUnit and "ally" or "enemy" + + local weapons = unitWeapons[unitDefID] + if (not weapons or #weapons == 0) and not unitBuilder[unitDefID] then return end -- no weapons and not builder, nothing to add + -- we want to add to unitDefRings here if it doesn't exist + if not unitDefRings[unitDefID] then + -- read weapons and add them to weapons table, then add to entry + local entry = { weapons = {} } + for weaponNum = 1, #weapons do + local weaponDefID = weapons[weaponNum].weaponDef + local weaponDef = WeaponDefs[weaponDefID] + local weapon = weapons[weaponNum] + + if true then --range > 0 then -- trying something different + if weapon.onlyTargets and weapon.onlyTargets.vtol then + entry.weapons[weaponNum] = 3 -- weaponTypeMap[3] is "AA" + elseif weaponDef.type == "Cannon" then + -- if weaponDef.range < 700 then + -- entry.weapons[weaponNum] = 1 -- weaponTypeMap[1] is "ground" + if weaponDef.range > 2600 then + entry.weapons[weaponNum] = 5 -- weaponTypeMap[5] is "lrpc" + else + entry.weapons[weaponNum] = 4 -- weaponTypeMap[4] is "cannon" + end + elseif weaponDef.type == "Melee" then + entry.weapons[weaponNum] = 1 -- weaponTypeMap[1] is "ground" + else + if weaponDef.range < 700 then + entry.weapons[weaponNum] = 1 -- weaponTypeMap[1] is "ground + elseif weaponDef.range > 2600 then + entry.weapons[weaponNum] = 5 -- weaponTypeMap[5] is "lrpc" + else + entry.weapons[weaponNum] = 1 -- weaponTypeMap[1] is "ground" + end + end + end + end + -- builder can have no weapon but still need to be added + if unitBuilder[unitDefID] then + local wt = entry.weapons + wt[#wt + 1] = 2 -- 2 is nano + end + + unitDefRings[unitDefID] = entry -- we insert the entry so we can reuse existing code + -- we need to initialize the other params + initializeUnitDefRing(unitDefID) + end + + local scalingUnitDefs = unitDefRangeScale + local scalingUnitParams = unitRangeScale.selections + if mouseover then scalingUnitParams = unitRangeScale.mouseovers end + local oldRange = {} + if scalingUnitDefs[unitDefID] and alliedUnit then -- Can't read enemy unit ranges. + if not newRange then newRange = {} end + scalingUnitParams[unitID] = { oldRange = {} } + numScalingUnits = numScalingUnits + 1 + oldRange[unitID] = {} + for weaponNum = 1, #weapons do + if not newRange[weaponNum] then -- Prevent unnecessary duplicate engine calls. + newRange[weaponNum] = spGetUnitWeaponState(unitID, weaponNum, "range") + end + oldRange[unitID][weaponNum] = {weaponNum, newRange[weaponNum]} + end + end + + local x, y, z, mpx, mpy, mpz, apx, apy, apz = spGetUnitPosition(unitID, true, true) + + --for weaponNum = 1, #weapons do + local addedRings = 0 + local weaponTypes = unitDefRings[unitDefID]['weapons'] + for j, weaponType in pairs(weaponTypes) do + local drawIt = true + -- we need to check if the unit has on/off weapon states, and only add the one active + local weaponOnOff + -- on off can be set on a building, we need to check that + if unitOnOffable[unitDefID] and not unitOnOffName[unitDefID] then -- if it's a building with actual on/off, we display range if it's on + weaponOnOff = unitsOnOff[unitID] or 1 + drawIt = (weaponOnOff == 1) + elseif unitOnOffable[unitDefID] and unitOnOffName[unitDefID] then -- this is a unit or building with 2 weapons + weaponOnOff = unitsOnOff[unitID] or 0 + drawIt = ((weaponOnOff + 1) == j) or + #weaponTypes == 1 -- remember weaponOnOff is 0 or 1, weapon number starts from 1 + end + + -- we add checks here for the display toggle status from config + if unitToggles[currentUnitName] then -- only if there's a config, else default is to draw it + local wToggleStatuses = unitToggles[currentUnitName][allystring] + if type(wToggleStatuses) == 'table' then + drawIt = wToggleStatuses[j] and drawIt + else + -- fixing the unitToggles table since something was corrupted + local entry = {} + for i=1, #weaponTypes do + entry[i] = true + end + unitToggles[currentUnitName][allystring] = entry + end + end + + local ringParams = {} + if newRange then + for i = 2, 17 do -- See line 405. + ringParams[i] = unitDefRings[unitDefID]['rings'][j][i] -- Preserves default range from unitDefs for use with enemy units. + end + ringParams[1] = newRange[j] + else + ringParams = unitDefRings[unitDefID]['rings'][j] + end + if drawIt and ringParams[1] > 0 then + + local weaponID = j + -- TODO: + -- Weapons aim from their WPY positions, but that can change for e.g. popups! + -- This is quite important to pass in as posscale.y! + -- Need to cache weaponID of the respective weapon for this to work + -- also assumes that weapons are centered onto drawpos + local wpx, wpy, wpz, wdx, wdy, wdz = spGetUnitWeaponVectors(unitID, weaponID) + --spEcho("unitID", unitID,"weaponID", weaponID, "y", y, "mpy", mpy,"wpy", wpy) + + -- Now this is a truly terrible hack, we cache each unitDefID's max weapon turret height at position 18 in the table + -- so it only goes up with popups + local turretHeight = mathMax(ringParams[18] or 0, (wpy or mpy ) - y) + ringParams[18] = turretHeight + + + cacheTable[1] = mpx + cacheTable[2] = turretHeight + cacheTable[3] = mpz + local vaokey = allystring .. weaponTypeToString[weaponType] + + for i = 1, 17 do + cacheTable[i + 3] = ringParams[i] + end + + if false then + local s = ' ' + for i = 1, 20 do + s = s .. "; " .. tostring(cacheTable[i]) + end + if true then + spEcho("Adding rings for", unitID, x, z) + spEcho("added", vaokey, s) + end + end + local instanceID = 10000000 * (mouseover and 1 or 0) + 1000000 * weaponType + unitID + + 100000 * + j -- weapon index needs to be included here for uniqueness + pushElementInstance(attackRangeVAOs[vaokey], cacheTable, instanceID, true, false, unitID) + addedRings = addedRings + 1 + if collections[unitID] == nil then + --lazy creation + collections[unitID] = { + posx = mpx, + posy = mpy, + posz = mpz, + vaokeys = {}, + allied = alliedUnit, + unitDefID = unitDefID + } + end + collections[unitID].vaokeys[instanceID] = vaokey + if newRange then + scalingUnitParams[unitID].oldRange[instanceID] = oldRange[unitID][j] + end + end + end + -- we cheat here and update builder count + if unitBuilder[unitDefID] and addedRings > 0 then + selBuilderCount = selBuilderCount + 1 + end +end + +local function RemoveSelectedUnit(unitID, mouseover) + --if not show_selected_weapon_ranges then return end + local collections = selections + if mouseover then collections = mouseovers end + local scalingUnitParams = unitRangeScale.selections + if mouseover then scalingUnitParams = unitRangeScale.mouseovers end + + local removedRings = 0 + if collections[unitID] then + local collection = collections[unitID] + if not collection then return end + for instanceKey, vaoKey in pairs(collection.vaokeys) do + --spEcho(vaoKey,instanceKey) + popElementInstance(attackRangeVAOs[vaoKey], instanceKey) + removedRings = removedRings + 1 + end + -- before we get rid of the definition we cheat again + if unitBuilder[collections[unitID].unitDefID] then + selBuilderCount = selBuilderCount - 1 + end + collections[unitID] = nil + if scalingUnitParams[unitID] then + scalingUnitParams[unitID] = nil + numScalingUnits = numScalingUnits - 1 + end + end +end + +function widget:SelectionChanged(sel) + updateSelection = true +end + +local function InitializeBuilders() + builders = {} + for _, unitID in ipairs(Spring.GetTeamUnits(spGetMyTeamID())) do + if unitBuilder[spGetUnitDefID(unitID)] then + builders[unitID] = true + end + end +end + +local function makeShaders() + attackRangeShader = LuaShader.CheckShaderUpdates(shaderSourceCache, 0) or attackRangeShader + if not attackRangeShader then + goodbye("Failed to compile attackRangeShader GL4 ") + return false + end + return true +end + +local function initGL4() + smallCircleVBO = InstanceVBOTable.makeCircleVBO(smallCircleSegments) + largeCircleVBO = InstanceVBOTable.makeCircleVBO(largeCircleSegments) + for i, atkRangeClass in ipairs(attackRangeClasses) do + attackRangeVAOs + [atkRangeClass] = InstanceVBOTable.makeInstanceVBOTable(circleInstanceVBOLayout, 20, atkRangeClass.. "_attackrange_gl4", 6) -- 6 is unitIDattribID (instData) + if atkRangeClass:find("lrpc", nil, true) or atkRangeClass:find("AA", nil, true) then + attackRangeVAOs + [atkRangeClass].vertexVBO = largeCircleVBO + attackRangeVAOs + [atkRangeClass].numVertices = largeCircleSegments + else + attackRangeVAOs + [atkRangeClass].vertexVBO = smallCircleVBO + attackRangeVAOs + [atkRangeClass].numVertices = smallCircleSegments + end + local newVAO = InstanceVBOTable.makeVAOandAttach(attackRangeVAOs + [atkRangeClass].vertexVBO, attackRangeVAOs + [atkRangeClass].instanceVBO) + attackRangeVAOs + [atkRangeClass].VAO = newVAO + end + return makeShaders() +end + +local function DoRangeUpdate(unitID, scalingUnit, mouseover) + local newRange = {} + local update + for instanceID, oldRange in pairs(scalingUnit.oldRange) do + local weaponNum = oldRange[1] + newRange[weaponNum] = spGetUnitWeaponState(unitID, weaponNum, "range") + if oldRange[2] ~= newRange[weaponNum] then + update = true + end + end + if update then + RemoveSelectedUnit(unitID, mouseover) -- need to refresh this unit's ring + AddSelectedUnit(unitID, mouseover, newRange) + end +end + +local function UpdateScalingRange() -- This function, and anything related to unitRangeScale, scalingUnitParams, and newRange are parts of a hook for Gunslingers or future/modded units that gain range with EXP. + local scalingUnitParams = unitRangeScale + for unitID, scalingUnit in pairs(scalingUnitParams.selections) do + DoRangeUpdate(unitID, scalingUnit) + end + for unitID, scalingUnit in pairs(scalingUnitParams.mouseovers) do + local mouseover = true + DoRangeUpdate(unitID, scalingUnit, mouseover) + end +end + +-- refresh all display according to toggle status +local function RefreshEverything() + -- what about just reinitialize? + attackRangeVAOs = {} + selections = {} + selUnitCount = 0 + selectedUnits = {} + selUnits = {} + mouseovers = {} + unitRangeScale = { selections = {}, mouseovers = {} } + numScalingUnits = 0 + + widget:Initialize() +end + +local function toggleShowSelectedRanges(on) + if show_selected_weapon_ranges == on then return end + show_selected_weapon_ranges = on +end + +local function toggleCursorRange(_, _, args) + cursor_unit_range = not cursor_unit_range + spEcho("Cursor unit range set to: " .. (cursor_unit_range and "ON" or "OFF")) +end + +-- direction should be 1 or -1 (next or previous bitmap value) +local function cycleUnitDisplay(direction) + if (selUnitCount > 1) or (selUnitCount == 0) then + spEcho("Please select only one unit to change display setting!") + return + end + local unitID = selectedUnits[1] + if not unitID then return end + + local alliedUnit = (spGetUnitAllyTeam(unitID) == myAllyTeam) + local allystring = alliedUnit and "ally" or "enemy" + local unitDefID = spGetUnitDefID(unitID) + if unitMaxWeaponRange[unitDefID] == 0 and not unitBuilder[unitDefID] then + spEcho("Unit has no weapon range!") + return + end + local name = unitName[unitDefID] + local wToggleStatuses = {} + local newToggleStatuses = {} + unitToggles[name] = unitToggles[name] or {} + if not unitToggles[name][allystring] then -- default toggle is on, we set it to off (0) + for i = 1, #unitDefRings[unitDefID].weapons do + wToggleStatuses[i] = true -- every ring defined weapon is on by default + end + newToggleStatuses = getNextWeaponCombination(wToggleStatuses, direction) + unitToggles[name][allystring] = newToggleStatuses + else -- there's already something stored here so we toggle this value + wToggleStatuses = unitToggles[name][allystring] + newToggleStatuses = getNextWeaponCombination(wToggleStatuses, direction) + unitToggles[name][allystring] = newToggleStatuses + end + local bitmap = convertToBitmap(newToggleStatuses) + local maxConfigBitmap = 2 ^ #newToggleStatuses - 1 + -- some crude info display for now + spEcho("Changed range display of " .. name .. + " to config " .. tostring(bitmap) .. + ": " .. table.toString(unitToggles[name][allystring])) + + -- write toggle changes to file + table.save(unitToggles, "LuaUI/config/AttackRangeConfig2.lua", "--Attack Range Display Configuration (v2)") + -- play a sound cue based on status bitmap state: max means all on, 0 means all off + local soundEffect = 'Sounds/commands/cmd-defaultweapon.wav' + local soundEffectOn = 'Sounds/commands/cmd-on.wav' + local soundEffectOff = 'Sounds/commands/cmd-off.wav' + local volume = 0.3 + if bitmap == maxConfigBitmap then + soundEffect = soundEffectOn + volume = 1.0 + elseif bitmap == 0 then + soundEffect = soundEffectOff + volume = 0.6 + end + Spring.PlaySoundFile(soundEffect, volume, 'ui') + + RefreshEverything() +end + +local function cycleUnitDisplayHandler(_, _, _, data) + local data = data or {} + local direction = data["direction"] + cycleUnitDisplay(direction) +end + +function widget:PlayerChanged(playerID) + myAllyTeamID = Spring.GetLocalAllyTeamID() + myTeamID = Spring.GetLocalTeamID() + + InitializeBuilders() +end + +function widget:Initialize() + widgetHandler:AddAction("defrange", defrangeCmd, nil, "t") + + initUnitList() + + if initGL4() == false then + widgetHandler:RemoveWidget(self) + return + end + + unitTogglesChunked = unitTogglesChunked or {} + for i, v in pairs(unitTogglesChunked) do + unitToggles[i] = v + end + + widgetHandler:AddAction("cursor_range_toggle", toggleCursorRange, nil, "p") + widgetHandler:AddAction("attack_range_inc", cycleUnitDisplayHandler, {direction = 1}, "p") + widgetHandler:AddAction("attack_range_dec", cycleUnitDisplayHandler, {direction = -1}, "p") + + myAllyTeam = Spring.GetMyAllyTeamID() + myTeamID = spGetMyTeamID() + + updateSelection = true + local _, _, _, shift = GetModKeyState() + if shift_only and not shift then + toggleShowSelectedRanges(false) + end + InitializeBuilders() + + WG.attackrange = {} + WG.attackrange.getShiftOnly = function() + return shift_only + end + WG.attackrange.setShiftOnly = function(value) + shift_only = value + widget:Initialize() + end + WG.attackrange.getCursorUnitRange = function() + return cursor_unit_range + end + WG.attackrange.setCursorUnitRange = function(value) + cursor_unit_range = value + widget:Initialize() + end + WG.attackrange.getNumRangesMult = function() + return selectionDisableThresholdMult + end + WG.attackrange.setNumRangesMult = function(value) + selectionDisableThresholdMult = value + end +end + +function widget:Shutdown() + widgetHandler:RemoveAction("defrange", "t") + widgetHandler:RemoveAction("cursor_range_toggle", "p") + widgetHandler:RemoveAction("attack_range_inc", "p") + widgetHandler:RemoveAction("attack_range_dec", "p") +end + +local gameFrame = 0 + +function widget:GameFrame(gf) + gameFrame = gf +end + +local function RefreshSelectedUnits() + local newSelUnits = {} + for i, unitID in ipairs(selectedUnits) do + newSelUnits[unitID] = true + if not selUnits[unitID] and selUnitCount < mathFloor(selectionDisableThreshold * selectionDisableThresholdMult) then + AddSelectedUnit(unitID) + end + end + for unitID, _ in pairs(selUnits) do + if not newSelUnits[unitID] then + RemoveSelectedUnit(unitID) + end + end + selUnits = newSelUnits +end + +local function UpdateSelectedUnits() + selectedUnits = GetSelectedUnits() + selUnitCount = #selectedUnits + updateSelection = false + + RefreshSelectedUnits() +end + +-- whether to draw the build range of all builders - only happens when isBuilding +local function DrawBuilders() + if isBuilding then + for unitID, _ in pairs(builders) do + if not selUnits[unitID] then + AddSelectedUnit(unitID) + end + end + else -- not building, we remove all builders that aren't selected + for unitID, _ in pairs(builders) do + if not selUnits[unitID] then + RemoveSelectedUnit(unitID) + end + end + end +end + +function widget:KeyPress(key, mods, isRepeat) + if key == 304 then + shifted = true + end +end + +function widget:KeyRelease(key, mods, isRepeat) + if key == 304 then + shifted = false + end +end + +local timeSinceLastRangeUpdate = 0 +function widget:Update(dt) + if updateSelection and gameFrame % 3 == 0 then + UpdateSelectedUnits() + end + + if numScalingUnits > 0 then + timeSinceLastRangeUpdate = timeSinceLastRangeUpdate + dt + else + timeSinceLastRangeUpdate = 0 + end + + if timeSinceLastRangeUpdate > DYNAMIC_RANGE_UPDATE_RATE then + UpdateScalingRange() -- This function is relatively expensive, so we only run it when we need to. + timeSinceLastRangeUpdate = 0 + end + + if show_selected_weapon_ranges and cursor_unit_range and gameFrame % 3 == 1 then + local mx, my, _, mmb, _, mouseOffScreen, cameraPanMode = spGetMouseState() + if mouseOffScreen or mmb or cameraPanMode then return end + + local desc, args = spTraceScreenRay(mx, my, false) + local mUnitID + if desc and desc == "unit" then + mUnitID = args + else + mUnitID = nil + RemoveSelectedUnit(mouseUnit, true) + mouseUnit = nil + end + if mUnitID and (mUnitID ~= mouseUnit) then + RemoveSelectedUnit(mouseUnit, true) + if not selections[mUnitID] then + AddSelectedUnit(mUnitID, true) + end + mouseUnit = mUnitID + end + end + + if gameFrame % 3 == 2 then + local cmdIndex, cmdID, cmdType, cmdName = GetActiveCommand() + if shift_only then + if shifted then + toggleShowSelectedRanges(true) + else + if cmdID == 20 then toggleShowSelectedRanges(true) end + if not cmdID or cmdID ~= 20 then toggleShowSelectedRanges(false) end + end + end + local isBuildingNow = (cmdID ~= nil) and (cmdID < 0) -- we're building, need to draw builder ranges + if isBuilding ~= isBuildingNow then + isBuilding = isBuildingNow + DrawBuilders() + end + end +end + +function widget:UnitCommand(unitID, unitDefID, unitTeam, cmdID, cmdParams, cmdOpts, cmdTag) + if unitTeam == myTeam and cmdID == 85 then -- my unit, "OnOff" command + unitsOnOff[unitID] = cmdParams[1] + RemoveSelectedUnit(unitID) -- need to refresh this unit's ring + AddSelectedUnit(unitID) + end +end + +function widget:RecvLuaMsg(msg, playerID) + if msg:sub(1, 18) == 'LobbyOverlayActive' then + chobbyInterface = (msg:sub(1, 19) == 'LobbyOverlayActive1') + end +end + +local drawcounts = {} + +local cameraHeightFactor = 0 + +local function GetCameraHeightFactor() + return 1 +end + +local groundnukeair = { "ground", "nano", "AA" } +local cannonlrpc = { "cannon", "lrpc" } +local function DRAWRINGS(primitiveType, linethickness) + if not show_selected_weapon_ranges and not isBuilding then return end + local stencilMask + attackRangeShader:SetUniform("cannonmode", 0) + for i, allyState in ipairs(allyenemypairs) do + for j, wt in ipairs(groundnukeair) do + local atkRangeClass = allyState .. wt + local iT = attackRangeVAOs[atkRangeClass] + stencilMask = 2 ^ (4 * (i - 1) + (j - 1)) -- from 1 to 128 + drawcounts[stencilMask] = iT.usedElements + if iT.usedElements > 0 then --and buttonConfig[allyState][wt] then + if linethickness then + glLineWidth(colorConfig[wt][linethickness] * cameraHeightFactor) + end + glStencilMask(stencilMask) -- only allow these bits to get written + -- Bitwise AND the stencil buffer with stencilMask when GL_NOTEQUAL: + glStencilFunc(GL_NOTEQUAL, stencilMask, stencilMask) -- what to do with the stencil + iT.VAO:DrawArrays(primitiveType, iT.numVertices, 0, iT.usedElements, 0) -- +1!!! + end + end + end + + attackRangeShader:SetUniform("cannonmode", 1) + for i, allyState in ipairs(allyenemypairs) do + for j, wt in ipairs(cannonlrpc) do + if linethickness or wt == 'cannon' then + local atkRangeClass = allyState .. wt + local iT = attackRangeVAOs[atkRangeClass] + local stencilOffset = colorConfig.cannon_separate_stencil and 3 or 0 + stencilMask = 2 ^ (4 * (i - 1) + stencilOffset) -- if 0 then it's on the same as "ground" + drawcounts[stencilMask] = iT.usedElements + if iT.usedElements > 0 then + if linethickness then + glLineWidth(colorConfig[wt][linethickness] * cameraHeightFactor) + end + glStencilMask(stencilMask) + glStencilFunc(GL_NOTEQUAL, stencilMask, stencilMask) + iT.VAO:DrawArrays(primitiveType, iT.numVertices, 0, iT.usedElements, 0) -- +1!!! + end + end + end + end +end + +function widget:DrawWorld(inMiniMap) + + if autoReload then + attackRangeShader = LuaShader.CheckShaderUpdates(shaderSourceCache) or attackRangeShader + end + + if chobbyInterface or not (selUnitCount > 0 or mouseUnit) then return end + if not Spring.IsGUIHidden() and (not WG['topbar'] or not WG['topbar'].showingQuit()) then + -- For PIP minimap, use thicker lines since PIP is larger than engine minimap + local inPip = inMiniMap and WG['minimap'] and WG['minimap'].isDrawingInPip + if inPip then + cameraHeightFactor = 2.5 -- PIP is larger, needs thicker lines + else + cameraHeightFactor = GetCameraHeightFactor() * 0.5 + 0.5 + end + glTexture(0, "$heightmap") + glTexture(1, "$info") + -- glTexture(2, '$normals') + -- Stencil Setup + -- https://learnopengl.com/Advanced-OpenGL/Stencil-testing + if colorConfig.drawStencil then + glClear(GL_STENCIL_BUFFER_BIT) -- clear previous stencil + glDepthTest(false) -- always draw, ignore depth test + + -- Draw the filled circles onto the stencil buffer + glStencilTest(true) -- enable stencil test + glStencilMask(255) -- set all 8 bits to writeable + + -- 1. Stencil test fails: GL_KEEP existing stencil value + -- 2. Z test fails: GL_KEEP existing stencil value + -- 3. Both tests pass: GL_REPLACE stencil value with desired number + glStencilOp(GL_KEEP, GL_KEEP, GL_REPLACE) -- Set The Stencil Buffer To [mask] Where Draw Any Polygon + + attackRangeShader:Activate() + attackRangeShader:SetUniform("selUnitCount", selUnitCount) + attackRangeShader:SetUniform("selBuilderCount", selBuilderCount) + attackRangeShader:SetUniform("drawMode", 0.0) + attackRangeShader:SetUniform("inMiniMap", inMiniMap and 1.0 or 0.0) + attackRangeShader:SetUniformInt("rotationMiniMap", getCurrentMiniMapRotationOption() or ROTATION.DEG_0) + attackRangeShader:SetUniform("drawAlpha", colorConfig.fill_alpha) + attackRangeShader:SetUniform("fadeDistOffset", colorConfig.outer_fade_height_difference) + + -- Pass PIP visible area if drawing in PIP minimap + if inMiniMap and WG['minimap'] and WG['minimap'].isDrawingInPip and WG['minimap'].getNormalizedVisibleArea then + local left, right, bottom, top = WG['minimap'].getNormalizedVisibleArea() + attackRangeShader:SetUniform("pipVisibleArea", left, right, bottom, top) + else + attackRangeShader:SetUniform("pipVisibleArea", 0, 1, 0, 1) + end + + DRAWRINGS(GL_TRIANGLE_FAN) -- FILL THE CIRCLES + + -- Draw the outside rings by testing the stencil buffer + glLineWidth(mathMax(0.1, 4 + math.sin(gameFrame * 0.04) * 10)) + glColorMask(true, true, true, true) -- re-enable color drawing + glStencilMask(0) + glDepthTest(GL_LEQUAL) -- test for depth on these outside cases + + attackRangeShader:SetUniform("lineAlphaUniform", colorConfig.externalalpha) + attackRangeShader:SetUniform("drawMode", 1.0) + attackRangeShader:SetUniform("drawAlpha", 1.0) + + DRAWRINGS(GL_LINE_LOOP, inMiniMap and 'minimapexternallinethickness' or 'externallinethickness') -- DRAW THE OUTER RINGS + + -- This is the correct way to exit out of the stencil mode, to not break drawing of area commands: + glStencilTest(false) -- Disable the stencil test + glStencilMask(255) -- Set all bits of stencil buffer to writeable + glStencilOp(GL_KEEP, GL_KEEP, GL_KEEP) -- Reset default stencil operation (which is the do nothing operation) + glClear(GL_STENCIL_BUFFER_BIT) -- Clear the stencil buffer for whichever widget wants it next (this is probably redundant) + -- All the above are needed :O + end + + -- After all the stenciled drawings, we have disabled the stencil test, so we can draw the inner rings + if colorConfig.drawInnerRings then + attackRangeShader:SetUniform("lineAlphaUniform", colorConfig.internalalpha) + attackRangeShader:SetUniform("drawMode", 2.0) + attackRangeShader:SetUniform("fadeDistOffset", 0) + DRAWRINGS(GL_LINE_LOOP, inMiniMap and 'minimapinternallinethickness' or 'internallinethickness') -- DRAW THE INNER RINGS + end + + attackRangeShader:Deactivate() + + glTexture(0, false) + glTexture(1, false) + glDepthTest(false) + end +end + +function widget:DrawInMiniMap() + -- TODO: + -- do a sanity check and dont draw here if there are too many units selected... + widget:DrawWorld(true) +end + +function widget:VisibleUnitAdded(unitID, unitDefID, unitTeam) + if unitTeam == myTeamID and unitBuilder[unitDefID] then + builders[unitID] = true + end +end + +function widget:VisibleUnitRemoved(unitID, unitDefID, unitTeam) + unitDefID = unitDefID or spGetUnitDefID(unitID) + unitTeam = unitTeam or Spring.GetUnitTeam(unitID) + RemoveSelectedUnit(unitID, false) + builders[unitID] = nil +end + + + + +if autoReload then + function widget:DrawScreen() + if attackRangeShader.DrawPrintf then attackRangeShader.DrawPrintf(0, 64) end + end +end + + +--SAVE / LOAD CONFIG FILE +----------------------------------------------------------------------------------------- +-- Useful config options to have for players in options menu are: +-- 1. "shift_only" - only show ranges when shift is held +-- 2. "cursor_unit_range" - show range of unit under cursor +-- 3. "colorConfig" - table of color options BUT ONLY THE FOLLOWING FIELDS: +-- "fill_alpha", "externalalpha", "internalalpha", "outer_fade_height_difference" +-- "ground.externallinethickness", "ground.internallinethickness" +-- "AA.externallinethickness", "AA.internallinethickness" +-- "cannon.externallinethickness", "cannon.internallinethickness" +-- "nano.externallinethickness", "nano.internallinethickness" +-- Other values inside colorConfig are potentially useful but not nearly as important +-- +-- The rest of the config data should be left to advanced users to tweak in widget's own config files (which will be generated upon use) +-- The config file is saved and load at LuaUI/config/AttackRangeConfig2.lua +----------------------------------------------------------------------------------------- +function widget:GetConfigData() + return { + shift_only = shift_only, + cursor_unit_range = cursor_unit_range, + selectionDisableThresholdMult = selectionDisableThresholdMult, + } +end + +function widget:SetConfigData(data) + if data.shift_only ~= nil then + shift_only = data.shift_only + end + if data.cursor_unit_range ~= nil then + cursor_unit_range = data.cursor_unit_range + end + if data.selectionDisableThresholdMult ~= nil then + selectionDisableThresholdMult = data.selectionDisableThresholdMult + end +end + +return widget end)() +local events={GameFrame=true,Update=true,SelectionChanged=true,PlayerChanged=true,VisibleUnitAdded=true,VisibleUnitRemoved=true,VisibleUnitsChanged=true,UnitCommand=true,KeyPress=true,KeyRelease=true,RecvLuaMsg=true} +local activeBuffers={} +local originalInitialize=widget.Initialize +widget.Initialize=function(self,...) + -- Observe the graphics objects created by the complete original callback. + -- Keep table identities: stock resizing replaces a VAO inside the same VBO + -- table, whereas a display action creates new tables and keeps debug entries. + pendingVAOs={} + local result=originalInitialize(self,...) + activeBuffers={} + for _,buffer in pairs(WG.VBOTableRegistry or{})do if pendingVAOs[buffer.VAO]then activeBuffers[buffer]=true end end + pendingVAOs={} + return result +end +local function invoke(name,...) + if not removed and widget[name]then return widget[name](widget,...)end +end +local function state(includeGeometry) + local result={disabled=removed,config=copy(widget:GetConfigData()),shaderConfig=copy(shaderConfig or{}),groups={}} + if removed then return result end + local names={};for name,buffer in pairs(WG.VBOTableRegistry or{})do if activeBuffers[buffer]then names[#names+1]=name end end;table.sort(names) + for _,name in ipairs(names)do + local buffer=WG.VBOTableRegistry[name] + assert(buffer.instanceStep==24 and buffer.usedElements<=65536) + local group={name=groupName(name),vertices=buffer.numVertices,rows={}} + if includeGeometry then group.mesh=copy(buffer.vertexVBO.data)end + result.groups[#result.groups+1]=group + for i=1,buffer.usedElements do + local instance=assert(buffer.indextoInstanceID[i]) + local row={instance=instance,id=assert(buffer.indextoUnitID[i]),lifetime=assert(rangeLives[buffer]and rangeLives[buffer][instance]),params={}} + for j=1,20 do + local value=buffer.instanceData[(i-1)*24+j] + -- Original LuaVBOImpl::Upload raw_get_or(...,0) maps + -- nil/boolean slots in the stock nano ring to zero, without rewriting Lua. + row.params[j]=type(value)=='number'and value or 0 + end + group.rows[i]=row + end + end + return result +end +local initialized=false +return{ + initialize=function()assert(not initialized,'Original range policy already initialized');initialized=true;invoke('Initialize');return not removed end, + event=function(name,...)assert(events[name],'Unsupported original range event');return invoke(name,...)end, + draw=function(minimap) + commands={};recording=true;invoke('DrawWorld',minimap==true);recording=false + return{state=state(),commands=commands} + end, + state=state, + geometry=function()return state(true).groups end, + action=function(name,args) + assert(type(name)=='string');local action=actions[name] + if not removed and action then return action.fn(nil,nil,args,action.data)end + end, + configure=function(data)assert(not initialized and type(data)=='table');invoke('SetConfigData',data)end, + savedSettings=function()return savedSettings and copy(savedSettings)end, +} + +end + +end)() +local policy=factory(native) +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)() +-- The unchanged original tracker, not a browser membership approximation, +-- supplies visibility, ownership, construction and removal callbacks. +for _,name in ipairs({'VisibleUnitAdded','VisibleUnitRemoved','VisibleUnitsChanged'})do + listeners[name]=function(...)return policy.event(name,...)end +end +local function trackerCall(name,...) + if not removed and tracker[name]then return tracker[name](tracker,...)end +end +for _,name in ipairs({'UnitCreated','UnitFinished','UnitDestroyed','UnitTaken','UnitGiven','UnitEnteredLos','UnitLeftLos'})do + _G[name]=function(...)return trackerCall(name,...)end +end +function GameFrame(frame) + trackerCall('GameFrame',frame);policy.event('GameFrame',frame) +end +function UnitCommand(...)return policy.event('UnitCommand',...)end +function WebbarAttackInitialize() + trackerCall('Initialize') + return not removed and policy.initialize() +end +local priorSelection,priorShift={},false +function WebbarAttackRead(input,dt) + assert(type(input)=='table'and type(dt)=='number'and dt>=0) + rangeInput=input + local changed=#priorSelection~=#input.selection + if not changed then for i,id in ipairs(input.selection)do if priorSelection[i]~=id then changed=true;break end end end + if changed then + priorSelection=copy(input.selection);policy.event('SelectionChanged',input.selection) + end + local shift=input.mods[4]==true + if shift~=priorShift then + policy.event(shift and 'KeyPress'or 'KeyRelease',304,{},false);priorShift=shift + end + policy.event('Update',dt) + local result=policy.draw(false) + result.minimapCommands=policy.draw(true).commands + return result +end + +)WEBBAR_ATTACK"; --- a/rts/Game/WebbarNativeCursorHost.inc +++ b/rts/Game/WebbarNativeCursorHost.inc @@ -3,7 +3,7 @@ // is separate work; this entry point does not synthesize mouse presses/orders. static bool ValidCursorView(const WebbarInfoWorldView& view) { return ValidOrderView(view) && view.mouseFlags == 0; } bool ReadCursor(const WebbarInfoWorldView& view, const std::vector& ids, - bool active, int commandID, std::string& json) + bool active, int commandID, std::string& json, int* selectedCommandIndex = nullptr) { if (!ready || std::getenv("WEBBAR_NATIVE_CURSOR_READS") == nullptr || std::getenv("WEBBAR_NATIVE_ORDER_READS") == nullptr || !ValidCursorView(view) || ids.size() > 8192 || (!active && commandID != 0)) return false; @@ -44,6 +44,7 @@ } if (activeIndex < 0) return false; } + if(selectedCommandIndex)*selectedCommandIndex=activeIndex+CMD_INDEX_OFFSET; for (const auto& entry: current) cursorAdmitted[entry.first] = entry.second; PrepareOrderCamera(view); // This profile uses BAR's pinned intro screen-icon settings, matching the --- a/rts/Game/WebbarNativeInfo.h +++ b/rts/Game/WebbarNativeInfo.h @@ -332,6 +332,28 @@ return ok; } + // The original range widget uses the same native world ray and original + // cursor/icon volumes as the qualified GUI read, under its own read scope. + int TraceAttackRay(lua_State* state) { + return LuaUnsyncedRead::TraceScreenRayForCameraWithVolumes(state,&worldView,worldWidth,worldHeight,&cursorIconVolumes); + } + // UniformConstants::UpdateParamsImpl's original mouse ray, with the same + // private native selection/icon volumes as the original cursor widgets. + // Do not expose the raw true position of a radar-only/hidden object. + std::array AttackMouse(const WebbarInfoWorldView& view) { + std::array result{}; + const float rawRange=worldView.GetFarPlaneDist()*1.4f,badRange=rawRange-300.0f; + const float3 origin=worldView.GetPos(),direction=worldView.CalcPixelDir(view.mouseX,int(view.height)-1-view.mouseY,view.width,view.height,0); + const CUnit* unit=nullptr;const CFeature* feature=nullptr; + const float distance=WebbarNativeOrder::CursorGuiTraceRay(cursorIconVolumes,origin,direction,rawRange,nullptr,unit,feature,true,false,true); + if((unit&&!gu->spectatingFullView&&unit->allyteam!=gu->myAllyTeam&&!unit->IsInLosForAllyTeam(gu->myAllyTeam)) + ||(feature&&!gu->spectatingFullView&&!feature->IsInLosForAllyTeam(gu->myAllyTeam))){result[4]=2;return result;} + const float3 point=unit?unit->drawPos:feature?feature->drawPos:origin+direction*distance; + const std::array value{point.x,point.y,point.z,((distance<0||distance>badRange)&&!unit&&!feature)?0.0f:1.0f}; + std::memcpy(result.data(),value.data(),16); + if(unit){result[4]=1;result[5]=unit->id;result[6]=WebbarHudLifetime(unit);} + return result; + } private: bool ready = false; spring::unordered_set orderSelected;