--- a/rts/Game/Game.cpp +++ b/rts/Game/Game.cpp @@ -294,6 +294,14 @@ #if defined(__EMSCRIPTEN__) static void FreeWebbarNativeBeams(); static void FreeWebbarNativeInfo(); +static void FreeWebbarNativeSensorRanges(); +static void PrepareWebbarNativeSensorRanges(); +static void PrepareWebbarNativeHealthbars(); +static void FreeWebbarNativeHealthbars(); +static void PrepareWebbarNativeEta(); +static void PrepareWebbarNativeScum(); +static void FreeWebbarNativeScum(); +static void FreeWebbarNativeEta(); static void PrepareWebbarNativeBeams(); static void InitializeWebbarReplayView(); #endif @@ -303,6 +311,10 @@ #if defined(__EMSCRIPTEN__) FreeWebbarNativeBeams(); FreeWebbarNativeInfo(); + FreeWebbarNativeSensorRanges(); + FreeWebbarNativeHealthbars(); + FreeWebbarNativeEta(); + FreeWebbarNativeScum(); #endif ENTER_SYNCED_CODE(); LOG("[Game::%s][1]", __func__); @@ -909,6 +921,10 @@ // Initialize the replacement original visual widgets at the native // LuaUI phase, before GamePreload creates initial units/events. if (std::getenv("WEBBAR_NATIVE_DISTORTION_VBO") != nullptr) PrepareWebbarNativeBeams(); + PrepareWebbarNativeSensorRanges(); + PrepareWebbarNativeHealthbars(); + PrepareWebbarNativeEta(); + PrepareWebbarNativeScum(); return; } #endif --- a/rts/Game/WebbarBrowser.h +++ b/rts/Game/WebbarBrowser.h @@ -103,6 +103,7 @@ #include "WebbarGeoSmoke.h" #include "WebbarTerrain.h" #include "WebbarTerrainFixture.h" +static uint32_t WebbarHudLifetime(const CUnit* unit); #include "WebbarPoses.h" static void PublishWebbarPoses(); #include "WebbarNativeBeams.h" @@ -116,6 +117,11 @@ #include "WebbarAutomationBrowser.h" #include "WebbarWidgetQueries.h" #include "WebbarNativeInfo.h" +#include "WebbarNativeSensorRanges.h" +#include "WebbarNativeHealthbars.h" +#include "WebbarNativeEta.h" +#include "WebbarNativeScum.h" +#include "WebbarMetalRead.h" static void PublishWebbarPlayState() { @@ -246,7 +252,9 @@ static const bool enabled = std::getenv("WEBBAR_PLAYABLE") != nullptr; if (!enabled || !game->playing || gs->frameNum < 0) return; + WebbarNativeInfo::PollCursor(); WebbarNativeInfo::Poll(); + PollWebbarNativeMetal(); if (webbarReplay::Enabled()) { PollWebbarReplay(); UpdateWebbarNativeBeams(); return; } GetWebbarEffects(); GetWebbarMatchResult(); @@ -312,12 +320,16 @@ int status = 0; float3 buildPos(order.x, 0.0f, order.z); std::vector ids; - if (order.count > 64 || gu->spectating || !playerHandler.IsValidPlayer(gu->myPlayerNum)) { + if (order.count > ((order.kind == 1020 || order.kind == 1021) ? 8192u : 64u) || gu->spectating || !playerHandler.IsValidPlayer(gu->myPlayerNum)) { status = 1; } else if (order.kind == 1017 || order.kind == 1018) { status = SetWebbarResourceShare(order.kind == 1017, order.count, order.target, order.options, order.x, order.z, order.radius); } else if (order.kind == 1010) { status = SetWebbarEnergyReserve(order.count, order.target, order.options); + } else if (order.kind == 1021) { + status = WebbarNativeInfo::PlayerControl::Execute(order.request, order.count, order.target, order.options, order.x, order.z, order.radius, order.units, fromPlayerNetwork, ids); + } else if (order.kind == 1020) { + status = WebbarNativeInfo::ExecuteOrder(order.request, order.count, order.target, order.options, order.x, order.z, order.radius, order.units, fromPlayerNetwork, ids); } else if (order.kind == 1019) { status = WebbarNativeInfo::Unload(order.count, order.units, order.target, order.options, order.x, order.z, order.radius, fromPlayerNetwork); if (status == 0) ids.push_back(int(order.units[0])); @@ -707,7 +719,7 @@ if (!webbarRepublish) webbarFrameChecksum = CSyncChecker::GetChecksum(); // Register before replay/resume can suppress presentation. The same event // history, including ownership transfers, must reconstruct quota identities. - if (std::getenv("WEBBAR_PLAYABLE") != nullptr) { GetWebbarQuotaOwnership(); GetWebbarHudEvents(); GetWebbarOrderEvents(); } + if (std::getenv("WEBBAR_PLAYABLE") != nullptr) { GetWebbarQuotaOwnership(); GetWebbarHudEvents(); GetWebbarOrderEvents(); WebbarNativeSensors::Prepare(); WebbarNativeHealthbars::Prepare(); } if (webbarReplay::Enabled()) { ApplyWebbarReplayView(); const int seek = webbarReplay::seek.load(); @@ -728,10 +740,12 @@ static const char* output = std::getenv("WEBBAR_SNAPSHOTS"); static const bool browser = std::getenv("WEBBAR_BROWSER") != nullptr; static const bool playableBrowser = browser && std::getenv("WEBBAR_PLAYABLE") != nullptr; + if (playableBrowser && gs->frameNum >= 0) WebbarNativeEta::Tick(); if (playableBrowser && gs->frameNum >= 0) PrepareWebbarNativeBeams(); if (playableBrowser && gs->frameNum >= 0) { SCOPED_TIMER("Webbar::Publish::Effects"); GetWebbarEffects().Publish(); } if (playableBrowser && gs->frameNum >= 0) UpdateWebbarNativeBeams(); if (playableBrowser && gs->frameNum >= 0) { SCOPED_TIMER("Webbar::Publish::GeoSmoke"); PublishWebbarGeoSmoke(); } + if (playableBrowser && gs->frameNum >= 0) { SCOPED_TIMER("Webbar::Publish::ChangedFeatures"); PublishChangedWebbarFeatures(); } if (playableBrowser) { PublishWebbarAutomationReports(); PublishWebbarBomberTargets(); PublishWebbarOrderEvents(); } // Optional native transforms use actual simulation-frame endpoints. Legacy // clients retain the established three-frame publication and slot layout. @@ -745,6 +759,9 @@ return; SCOPED_TIMER("Webbar::Publish::Frame3"); + if (playableBrowser) WebbarNativeSensors::Publish(); + if (playableBrowser) WebbarNativeScum::Publish(); + if (playableBrowser) WebbarNativeHealthbars::Publish(); const auto& units = WebbarUnits(); std::vector projectiles; const bool playable = playableBrowser; --- /dev/null +++ b/rts/Game/WebbarCursorWorldAdapter.h @@ -0,0 +1,678 @@ +/* This file is part of the Spring engine (GPL v2 or later), see LICENSE.html */ +#pragma once +static constexpr const char* WEBBAR_CURSOR_WORLD_ADAPTER=R"CURSOR_WORLD( +do +local factory=(function() +return function(native) +local originalSpring=assert(native.Spring) +local UnitDefs,CMD,GameCMD=assert(native.UnitDefs),assert(native.CMD),assert(native.GameCMD) +assert(native.privateSelectionVolumes==true,'DefaultCommand requires private native selection volumes') +local Spring=setmetatable({GetUnitSelectionVolumeData=assert(native.getSelectionVolume),SetUnitSelectionVolumeData=assert(native.setSelectionVolume)},{__index=originalSpring}) +local WG=native.WG or{} +local tracy=native.tracy or{ZoneBeginN=function()end,ZoneEnd=function()end} +local widgetHandler={DefaultCommandList={}} +local globals={} +local function ArrayInsert(t, f, w) + if f then + local layer = w.whInfo.layer + local index = 1 + for i, v in ipairs(t) do + if v == w then + return -- already in the table + end + if layer >= v.whInfo.layer then + index = i + 1 + end + end + table.insert(t, index, w) + end +end + + +local function ArrayRemove(t, value) + for i = #t, 1, -1 do + if t[i] == value then + table.remove(t, i) + end + end +end + + +-------------------------------------------------------------------------------- + +function widgetHandler:DefaultCommand(...) + tracy.ZoneBeginN("W:DefaultCommand") + local list = self.DefaultCommandList + for i = #list, 1, -1 do + local result = list[i]:DefaultCommand(...) + if type(result) == 'number' then + tracy.ZoneEnd() + return result + end + end + tracy.ZoneEnd() + return nil -- not a number, use the default engine command +end + + +local function privateHandler(widget) + return setmetatable({ + RemoveWidget=function()ArrayRemove(widgetHandler.DefaultCommandList,widget)end, + RegisterGlobal=function(_,name,fn)assert(name=='RemoveSelectionVolume'or name=='RestoreSelectionVolume');assert(type(fn)=='function');globals[name]=fn end, + DeregisterGlobal=function(_,name)globals[name]=nil end, + },{__index=widgetHandler}) +end +local ignoreSelf=(function()local widget={} +local widgetHandler=privateHandler(widget) +local widget = widget ---@class Widget + +function widget:GetInfo() + return { + name = "Ignore Self", + desc = "Avoid self-targeting with default commands (e.g. Guard on self)", + author = "efrec", + date = "2025-10-13", + version = "v1.0", + license = "GNU GPL, v2 or later", + layer = -1e9, -- before other w:DefaultCommand + enabled = true, + } +end + +-------------------------------------------------------------------------------- +-- Configuration --------------------------------------------------------------- + +---@type number in seconds +local doubleClickTime = Spring.GetConfigInt("DoubleClickTime", 200) / 1000 +---@type integer in pixels, as the Manhattan norm +local doubleClickDist = 12 +---@type table +local allowSelfCommand = { + -- None so far. +} + +-------------------------------------------------------------------------------- +-- Globals --------------------------------------------------------------------- + +local math_abs = math.abs + +local sp_GetActiveCommand = Spring.GetActiveCommand +local sp_GetMouseState = Spring.GetMouseState +local sp_GetUnitDefID = Spring.GetUnitDefID +local sp_GetUnitSelectionVolumeData = Spring.GetUnitSelectionVolumeData +local sp_SetUnitSelectionVolumeData = Spring.SetUnitSelectionVolumeData +local sp_TraceScreenRay = Spring.TraceScreenRay + +-------------------------------------------------------------------------------- +-- Initialization -------------------------------------------------------------- + +-- Factories need to self-select because their commands go to their built units. +local isFactory = {} +for unitDefID, unitDef in ipairs(UnitDefs) do + -- todo: weird things to consider, like enqueued self-reclaim commands, etc. + isFactory[unitDefID] = unitDef.isFactory and unitDef.canGuard +end + +local selectedUnitID -- widget ignores/sees through only a single unit +local selectClickTime = 0 +local cx, cy + +local restoreVolumeData = {} +local isVolumeHidden = false +local inActiveCommand = false + +-------------------------------------------------------------------------------- +-- Local functions ------------------------------------------------------------- + +local function cacheSelectionVolume(unitID) + restoreVolumeData = { sp_GetUnitSelectionVolumeData(unitID) } +end + +-- Prevent a unit from being hovered, clicked, or selected via raycast (e.g. by the cursor). +-- This way you cannot give nonsense commands, such as self-guard, and it becomes easy to +-- target things obscured by the unit (sub under battleship, things under large aircraft or tall buildings) +-- +-- Since the camera can be rotated to extreme perspectives, even units that do not allow any +-- other unit underneath themselves will have their selection volumes shrunk to zero radius. +local function removeSelectionVolume(unitID) + -- The xyz scale and volume shape are unused. We want an unambiguous point volume. + local _, _, _, ox, oy, oz, _, cont, axis = sp_GetUnitSelectionVolumeData(unitID) + local shape = 1 -- spherical volume + + -- Handle headless testing and/or godmode selection of invisible enemy units. + -- This creates a potential inconsistency in the test, dependent on your LOS. + if not ox then + selectedUnitID = nil + return + end + + sp_SetUnitSelectionVolumeData(unitID, 0, 0, 0, ox, oy, oz, shape, cont, axis) + isVolumeHidden = true +end + +local function restoreSelectionVolume(unitID) + local data = restoreVolumeData + + if not data[1] then + cacheSelectionVolume(unitID) + data = restoreVolumeData + if not data[1] then + return -- godmode/LOS shenanigans + end + end + + sp_SetUnitSelectionVolumeData(unitID, unpack(data)) + isVolumeHidden = false +end + +local function inDoubleClickDistance(mx, my) + return cx and math_abs(mx - cx) + math_abs(my - cy) <= doubleClickDist +end + +---Determine the time delay to apply an effect so that double clicks can register. +local function getSingleClickDuration() + local mx, my, leftButton = sp_GetMouseState() + + if leftButton then + if selectClickTime <= 0 or not inDoubleClickDistance(mx, my) then + -- Start of a new single- or double-click. + cx, cy = mx, my + return doubleClickTime + else + -- Double-click consumes the single-click. + cx, cy = nil, nil + return 0 + end + end + + return 0 +end + +-------------------------------------------------------------------------------- +-- Engine callins -------------------------------------------------------------- + +function widget:SelectionChanged(selected) + local firstID = selected[1] + local isSingleSelection = firstID and not selected[2] + + if (not isSingleSelection or firstID ~= selectedUnitID) and selectedUnitID then + restoreSelectionVolume(selectedUnitID) + selectedUnitID = nil + end + + if isSingleSelection and not selectedUnitID then + -- todo: not as good as allowing self-select only on certain commands + -- todo: so otherwise we can "peek through" unit volumes conveniently + if isFactory[sp_GetUnitDefID(firstID)] then + return + end + + cacheSelectionVolume(firstID) + selectedUnitID = firstID + selectClickTime = getSingleClickDuration() + end +end + +function widget:MousePress(x, y, button) + if button == 1 and isVolumeHidden then + local _, commandID = sp_GetActiveCommand() + if not commandID then + restoreSelectionVolume(selectedUnitID) + selectClickTime = doubleClickTime + end + end +end + +function widget:Update(dt) + if selectedUnitID then + if selectClickTime > 0 then + selectClickTime = selectClickTime - dt + elseif not isVolumeHidden and not inActiveCommand then + selectClickTime = 0 + removeSelectionVolume(selectedUnitID) + end + end +end + +function widget:DefaultCommand(type, id, cmd) + if selectedUnitID then + if id == selectedUnitID and not allowSelfCommand[cmd] then + return CMD.MOVE + end + end +end + +function widget:ActiveCommandChanged(cmdid, type) + if cmdid and allowSelfCommand[cmdid] then + if isVolumeHidden then + restoreSelectionVolume(selectedUnitID) + end + inActiveCommand = true + elseif inActiveCommand and not cmdid then + inActiveCommand = false + if selectedUnitID then + removeSelectionVolume(selectedUnitID) + end + end +end + +-- Godmode and headless testing LOS fixes. + +local function unitAccessLost(self, unitID, unitTeam, unitAllyTeam, unitDefID) + if unitID == selectedUnitID then + if isVolumeHidden then + restoreSelectionVolume(selectedUnitID) + end + end +end + +local function unitAccessGained(self, unitID, unitTeam, unitAllyTeam, unitDefID) + if unitID == selectedUnitID then + if not isVolumeHidden and selectClickTime < 0 then + removeSelectionVolume(selectedUnitID) + end + end +end + +widget.UnitLeftLos = unitAccessLost +widget.UnitLeftRadar = unitAccessLost +widget.UnitEnteredLos = unitAccessGained +widget.UnitEnteredRadar = unitAccessGained + +-- Interwupget communications and compatability + +---Get information about a ray traced from screen to world position. +-- +-- This method is an override of the engine-provided TraceScreenRay, +-- and can peek selection volumes hidden by `cmd_no_self_selection`. +---@param screenX number position on x axis in mouse coordinates (origin on left border of view) +---@param screenY number position on y axis in mouse coordinates (origin on top border of view) +---@param onlyCoords boolean? (default: `false`) `result` includes only coordinates +---@param useMinimap boolean? (default: `false`) if position arguments are contained by minimap, use the minimap corresponding world position +---@param includeSky boolean? (default: `false`) +---@param ignoreWater boolean? (default: `false`) +---@param heightOffset number? (default: `0`) +---@return ("unit"|"feature"|"ground"|"sky")? description of traced object or position +---@return (integer|xyz)? result unitID or featureID (integer), or position triple (xyz) +local function traceScreenRay(screenX, screenY, onlyCoords, useMinimap, includeSky, ignoreWater, heightOffset) + -- Explicitly check onlyCoords because `TraceScreenRay` accepts arguments (screenX, screenY, heightOffset). + local hiddenID = (onlyCoords ~= true) and not useMinimap and isVolumeHidden and selectedUnitID + + if hiddenID then + restoreSelectionVolume(hiddenID) + end + + local description, result = sp_TraceScreenRay(screenX, screenY, onlyCoords, useMinimap, includeSky, ignoreWater, heightOffset) + + if hiddenID then + removeSelectionVolume(hiddenID) + end + + return description, result +end + +local function naiveRemoveSelectionVolume() + if not isVolumeHidden and selectedUnitID and selectClickTime <= 0 and not inActiveCommand then + removeSelectionVolume(selectedUnitID) + end +end + +local function naiveRestoreSelectionVolume() + if isVolumeHidden and selectedUnitID then + restoreSelectionVolume(selectedUnitID) + end +end + +function widget:Initialize() + WG.SpringTraceScreenRay = sp_TraceScreenRay + Spring.TraceScreenRay = traceScreenRay + widgetHandler:RegisterGlobal("RemoveSelectionVolume", naiveRemoveSelectionVolume) + widgetHandler:RegisterGlobal("RestoreSelectionVolume", naiveRestoreSelectionVolume) +end + +function widget:Shutdown() + naiveRestoreSelectionVolume() + Spring.TraceScreenRay = sp_TraceScreenRay + widgetHandler:DeregisterGlobal("RemoveSelectionVolume") + widgetHandler:DeregisterGlobal("RestoreSelectionVolume") +end + +return widget end)() + +local pip=(function()local widget={DefaultCommand=function(_,...)return assert(native.pipDefault)(...)end} +widget.GetInfo = function() + return { + name = "Picture-in-Picture Minimap", + desc = "Replaces minimap with an interactive PIP-style map view. Supports panning, zooming, and unit tracking.", + author = "Floris", + version = "1.0", + date = "January 2026", + license = "GNU GPL, v2 or later", + layer = -99000, + enabled = true, + handler = true, + } +end + + +return widget end)() +local cloakMove=(function()local widget={} +local widgetHandler=privateHandler(widget) +local widget = widget ---@type Widget + +function widget:GetInfo() + return { + name = "Cloaked Buildpower Default Move", + desc = "Prevents accidental reclaim, load, and attack commands on cloaked units\nMakes move the default command for commanders, decoys, and spies when cloaked", + author = "Catcow, BrainDamage", + date = "11/14/25", + license = "GNU GPL, v2 or later", + layer = 0, + enabled = true, + } +end + +-- Localized Spring API for performance +local spGetSelectedUnitsCount = Spring.GetSelectedUnitsCount +local spGetGameFrame = Spring.GetGameFrame + +local spGetSelectedUnitsSorted = Spring.GetSelectedUnitsSorted +local spGetMyTeamID = Spring.GetMyTeamID +local spGetUnitStates = Spring.GetUnitStates + +local idCanBuildCloakMove = {} +for unitDefID, unitDef in pairs(UnitDefs) do + if unitDef.canCloak and unitDef.canReclaim and unitDef.canMove then + idCanBuildCloakMove[unitDefID] = true + end +end + +local gameStarted + +local CMD_MOVE = CMD.MOVE +local CMD_WANT_CLOAK = GameCMD.WANT_CLOAK + +local function maybeRemoveSelf() + if Spring.GetSpectatingState() and (spGetGameFrame() > 0 or gameStarted) then + widgetHandler:RemoveWidget() + end +end + +function widget:GameStart() + gameStarted = true + maybeRemoveSelf() +end + +function widget:PlayerChanged(playerID) + maybeRemoveSelf() +end + +function widget:Initialize() + if Spring.IsReplay() or spGetGameFrame() > 0 then + maybeRemoveSelf() + end +end + +local cloakedBuilderMovableSelected = false + +local function update() + local selectedUnitsCount = spGetSelectedUnitsCount() + + cloakedBuilderMovableSelected = false + -- above a little amount we likely aren't micro-ing cloaked things anymore... + if selectedUnitsCount == 0 or selectedUnitsCount > 20 then return end + + local selectedUnitTypes = spGetSelectedUnitsSorted() + for unitDefID, units in pairs(selectedUnitTypes) do + if idCanBuildCloakMove[unitDefID] then + for _, unitID in pairs(units) do + local _, _, _, _, cloak = spGetUnitStates(unitID, false, true) + if cloak then + cloakedBuilderMovableSelected = true + return + end + end + end + end +end + +function widget:SelectionChanged(sel) + update() +end + +function widget:UnitCommand(unitID, unitDefID, teamID, cmdID, cmdParams, cmdOpts, cmdTag, playerID, fromSynced, fromLua) + if (cmdID == CMD_WANT_CLOAK) and (idCanBuildCloakMove[unitDefID]) and (teamID == spGetMyTeamID()) then + update() + end +end + +function widget:DefaultCommand() + if cloakedBuilderMovableSelected then + return CMD_MOVE + end +end + +return widget end)() + +local guardDamaged=(function()local widget={} +local widgetHandler=privateHandler(widget) +local widget = widget ---@type Widget + +function widget:GetInfo() + return { + name = "Guard damaged constructors", + desc = "Replace repair command with guard command when right click targeting damaged constructors and factories", + license = "GNU GPL, v2 or later", + layer = 0, + enabled = true + } +end + +local guardConstructors = true +local guardFactories = true + +local isConstructor, isFactory = {}, {} +for unitDefID, unitDef in pairs(UnitDefs) do + if unitDef.isMobileBuilder then + isConstructor[unitDefID] = true + end + if unitDef.isFactory then + isFactory[unitDefID] = true + end +end + +function widget:DefaultCommand(targetType, targetID, engineCmd) + if targetType ~= "unit" then + return + end + + if engineCmd == CMD.REPAIR then + if Spring.GetUnitIsBeingBuilt(targetID) then + return + end + + local unitDefID = Spring.GetUnitDefID(targetID) + if (isConstructor[unitDefID] and guardConstructors) or (isFactory[unitDefID] and guardFactories) + then + return CMD.GUARD + end + end +end + +return widget end)() + +local widgets={ignoreSelf,pip,cloakMove,guardDamaged} +-- Actual native-f active-widget order. BAR ArrayInsert and DefaultCommand keep +-- their own layer/tie ordering; do not substitute the engine LuaHandler list. +for _,widget in ipairs(widgets)do widget.whInfo=widget:GetInfo();ArrayInsert(widgetHandler.DefaultCommandList,widget.DefaultCommand,widget)end +return {handler=widgetHandler,widgets={ignoreSelf=ignoreSelf,pip=pip,cloakMove=cloakMove,guardDamaged=guardDamaged},globals=globals,Spring=Spring,WG=WG} +end + +end)() +local GameCMD=(function() +-------------------------------------------------------------------------------- +-- +-- Proposed Command ID Ranges: +-- +-- all negative: Engine (build commands) +-- 0 - 999: Engine +-- 1000 - 9999: Group AI +-- 10000 - 19999: LuaUI +-- 20000 - 29999: LuaCob +-- 30000 - 39999: LuaRules +-- + +-- if you add a command, please order it by ID! + +local gameCommands = { + FACTORY_GUARD = 13921, + AREA_GUARD = 13922, -- unused + STOP_PRODUCTION = 13923, + + -- blueprint + BLUEPRINT_PLACE = 18200, + BLUEPRINT_CREATE = 18201, + + -- quota + QUOTA_BUILD_TOGGLE = 23000, + + AREA_MEX = 30100, + SELL_UNIT = 30101, + + CARRIER_SPAWN_ONOFF = 31200, + MORPH = 31210, + USER_FIRESTATE = 31300, + MANUAL_LAUNCH = 32102, + UNIT_SET_TARGET_NO_GROUND = 34922, -- unit_target_on_the_move + UNIT_SET_TARGET = 34923, + UNIT_CANCEL_TARGET = 34924, + UNIT_SET_TARGET_RECTANGLE = 34925, + LAND_AT = 34569, + PRIORITY = 34571, + WANT_CLOAK = 37382, + HOUND_WEAPON_TOGGLE = 37383, -- unused + SMART_TOGGLE = 37384, + AREA_ATTACK_GROUND = 39954, + + -- terraform + RAW_MOVE = 39812, +} + +local globalCmdDeprecatedShown = false + +local importCommandsToObject = function(object) + if not globalCmdDeprecatedShown and not object.gadgetHandler then + local msg = 'Should not use customcmds.h.lua or importCommandsToObject. Use the CMD table directly, or read modules/customcommands.lua for more information.' + Spring.Log('CMD', LOG.DEPRECATED, msg) + globalCmdDeprecatedShown = true + end + for code, cmdID in pairs(gameCommands) do + if type(code) == 'string' then + object['CMD_' .. code] = cmdID + end + end + +end + +for code, cmdID in pairs(gameCommands) do + if CMD[cmdID] then + Spring.Log('CMD', LOG.ERROR, 'Duplicate command id: ' .. code .. ' ' .. tostring(cmdID) .. '!') + end + if CMD[code] then + Spring.Log('CMD', LOG.ERROR, 'Duplicate command code: ' .. code .. ' ' .. tostring(cmdID) .. '!') + end + gameCommands[cmdID] = code +end + +local getCommandCode = function(cmdID) + return CMD[cmdID] or gameCommands[cmdID] +end + +return { + GameCMD = gameCommands, + ImportCommandsToObject = importCommandsToObject, + GetCommandCode = getCommandCode, + } + +end)().GameCMD +local originalSpring=Spring +local selected,pointer,active={},{x=0,y=0,left=false,middle=false,right=false},nil +local program,context,lastTime,lastFrame,life,cloak=nil,nil,nil,nil,{},{} +local privateSpring=setmetatable({ + GetSelectedUnits=function()return selected end, + GetSelectedUnitsCount=function()return #selected end, + GetSelectedUnitsSorted=function() + local sorted={} + for _,id in ipairs(selected)do + local def=originalSpring.GetUnitDefID(id) + if def then sorted[def]=sorted[def]or{};sorted[def][#sorted[def]+1]=id end + end + return sorted + end, + GetMouseState=function()return pointer.x,pointer.y,pointer.left,pointer.middle,pointer.right end, + GetActiveCommand=function()if active then return active.index,active.id end end, + TraceScreenRay=assert(WebbarCursorTraceScreenRay), +},{__index=originalSpring}) +local function shutdown() + if program then program.widgets.ignoreSelf:Shutdown()end + program,context,lastTime,lastFrame,life,cloak=nil,nil,nil,nil,{},{} +end +function WebbarResetCursor()shutdown();selected={}end +local function advance(seconds) + assert(type(seconds)=='number'and seconds==seconds and seconds>=0) + local dt=lastTime and math.max(0,seconds-lastTime)or 0 + lastTime=seconds + if program then program.widgets.ignoreSelf:Update(dt)end +end +function WebbarPrepareCursor(ids,mouse,descriptor,seconds,view,tokens) + assert(type(ids)=='table'and type(mouse)=='table'and type(view)=='string'and type(tokens)=='table') + local reset=context~=view + for _,id in ipairs(ids)do if life[id]and life[id]~=tokens[id]then reset=true end end + if reset then shutdown()end + -- Shutdown restores the previous private selection before these inputs move. + local previous=selected + selected,pointer,active=ids,mouse,descriptor + local changed=#previous~=#ids or reset + if not changed then for i,id in ipairs(ids)do if previous[i]~=id then changed=true;break end end end + if not program then + program=factory({Spring=privateSpring,UnitDefs=UnitDefs,CMD=CMD,GameCMD=GameCMD, + privateSelectionVolumes=true,getSelectionVolume=assert(WebbarCursorGetSelectionVolume), + setSelectionVolume=assert(WebbarCursorSetSelectionVolume),pipDefault=function()end}) + program.widgets.ignoreSelf:Initialize();program.widgets.cloakMove:Initialize() + context=view + end + if changed then + program.widgets.ignoreSelf:SelectionChanged(ids) + program.widgets.cloakMove:SelectionChanged(ids) + end + -- Replay the original cloak call-in when its native want-cloak state changes. + -- No guessed cloak/definition facts arrive from the page. + local nextCloak={} + for _,id in ipairs(ids)do + local _,_,_,_,want=originalSpring.GetUnitStates(id,false,true) + nextCloak[id]=want + if not changed and cloak[id]~=want then + program.widgets.cloakMove:UnitCommand(id,originalSpring.GetUnitDefID(id),originalSpring.GetMyTeamID(),GameCMD.WANT_CLOAK) + end + end + cloak,life=nextCloak,tokens + local frame=originalSpring.GetGameFrame() + if lastFrame and lastFrame==0 and frame>0 then program.widgets.cloakMove:GameStart()end + lastFrame=frame + program.widgets.ignoreSelf:ActiveCommandChanged(active and active.id) + advance(seconds) +end +-- The host supplies actual ordered press events, not inferred button edges. +-- This preserves Ignore Self's selection/double-click grace period. +function WebbarCursorMousePress(x,y,button,seconds) + if not program then return end + advance(seconds) + program.widgets.ignoreSelf:MousePress(x,y,button) +end +function WebbarCursorDefault(kind,id,command) + assert(program,'Native cursor lifecycle was not prepared') + return program.handler:DefaultCommand(kind,id,command) +end +end + +)CURSOR_WORLD"; --- /dev/null +++ b/rts/Game/WebbarEtaEvents.h @@ -0,0 +1,27 @@ +/* This file is part of the Spring engine (GPL v2 or later), see LICENSE.html */ +#pragma once +#include +#include +#include +#include "lib/lua/include/LuaInclude.h" + +// Observe the existing synced ETA message without changing its source stack, +// emitting a synced event, installing watches or issuing commands. +namespace WebbarEtaEvents { +using Listener = void(*)(void*, lua_State*, int); +inline Listener listener = nullptr; +inline void* owner = nullptr; +inline void Attach(void* next, Listener callback) { assert(owner == nullptr); owner = next; listener = callback; } +inline void Detach(void* previous) { if (owner == previous) { owner = nullptr; listener = nullptr; } } +inline void Observe(lua_State* source, int args) +{ + if (!listener || args != 4 || lua_type(source, 1) != LUA_TSTRING || std::strcmp(lua_tostring(source, 1), "etaFeatureReclaimStartFrame") != 0) return; + for (int i = 2; i <= 4; ++i) { + if (lua_type(source, i) != LUA_TNUMBER) return; + const float value = lua_tonumber(source, i); + if (!std::isfinite(value)) return; + if (i < 4 && (value < 0 || value > (i == 2 ? 65535 : 255) || std::floor(value) != value)) return; + } + listener(owner, source, args); +} +} --- /dev/null +++ b/rts/Game/WebbarHealthbarEvents.h @@ -0,0 +1,33 @@ +/* This file is part of the Spring engine (GPL v2 or later), see LICENSE.html */ +#pragma once +#include +#include +#include +#include "lib/lua/include/LuaInclude.h" + +// Observe only BAR's three existing healthbar forwarding messages. The source +// stack is read without conversions or writes. No synthetic synced event, +// command, watch registration or engine buffer mutation is introduced. +namespace WebbarHealthbarEvents { +using Listener = void(*)(void*, lua_State*, int); +inline Listener listener = nullptr; +inline void* owner = nullptr; +inline void Attach(void* next, Listener callback) { assert(owner == nullptr); owner = next; listener = callback; } +inline void Detach(void* previous) { if (owner == previous) { listener = nullptr; owner = nullptr; } } +inline void Observe(lua_State* source, int args) { + if (!listener || args < 3 || args > 4 || lua_type(source, 1) != LUA_TSTRING) return; + const char* name = lua_tostring(source, 1); + const bool feature = std::strcmp(name, "featureReclaimFrame") == 0; + const bool capture = std::strcmp(name, "unitCaptureFrame") == 0; + const bool reload = std::strcmp(name, "projetileCreatedReload") == 0; + if ((!feature && !capture && !reload) || args != (reload ? 4 : 3)) return; + for (int i = 2; i <= args; ++i) { + if (lua_type(source, i) != LUA_TNUMBER) return; + const float value = lua_tonumber(source, i); + if (!std::isfinite(value)) return; + // Step sizes are the original signed floats; all other fields are IDs. + if ((reload || i == 2) && (value < 0 || value > 2147483520.0f || std::floor(value) != value)) return; + } + listener(owner, source, args); +} +} --- /dev/null +++ b/rts/Game/WebbarMetalRead.h @@ -0,0 +1,34 @@ +/* This file is part of the Spring engine (GPL v2 or later), see LICENSE.html */ +#pragma once +#include "WebbarMetalTexture.h" +#include "Map/MetalMap.h" +#include + +// Read-only request path, including while paused or replaying. The caller owns +// render-update cadence; this never changes simulation, LOS or extraction. +static void PollWebbarNativeMetal() +{ + static const bool enabled = std::getenv("WEBBAR_NATIVE_METAL_INPUT") != nullptr; + if (!enabled) return; + alignas(uint32_t) std::array bytes{}; + const int size = MAIN_THREAD_EM_ASM_INT({ + return Module['webbarPollNativeMetal'] ? Module['webbarPollNativeMetal']($0, $1) : 0; + }, bytes.data(), bytes.size()); + if (size == 0) return; + WebbarMetalTexture::Request q{}; + std::memcpy(&q, bytes.data(), sizeof(q)); + uint32_t status = 2; + std::vector packet; + if (size == int(sizeof(q)) && losHandler != nullptr && WebbarMetalTexture::Current(q, gu->myTeam, gu->myAllyTeam, gu->spectatingFullView, gs->frameNum)) { + // CLosTexture::Update's original ground map and GetGlobalLOS policy. + // Full-view identity authorizes the request; it does not replace the + // original ground-LOS sampling rule with a different presentation mask. + const auto& los = losHandler->los; + const auto ground = WebbarInfoTexture::Binary(los.size.x, los.size.y, los.losMaps[gu->myAllyTeam].GetLosMap(), losHandler->GetGlobalLOS(gu->myAllyTeam)); + packet = WebbarMetalTexture::Packet(WebbarMetalTexture::Prepare(metalMap.GetSizeX(), metalMap.GetSizeZ(), metalMap.GetDistributionMap(), metalMap.GetExtractionMap(), ground)); + status = packet.empty() ? 4 : 0; + } + MAIN_THREAD_EM_ASM({ + if (Module['webbarNativeMetalResult']) Module['webbarNativeMetalResult']($0, $1, $2, $3, $4, $5, $6, $8 ? HEAPU8.slice($7, $7 + $8).buffer : null); + }, q.request, q.generation, status, gs->frameNum, gu->myTeam, gu->myAllyTeam, uint32_t(gu->spectatingFullView), packet.data(), packet.size()); +} --- /dev/null +++ b/rts/Game/WebbarMetalTexture.h @@ -0,0 +1,87 @@ +/* This file is part of the Spring engine (GPL v2 or later), see LICENSE.html */ +#pragma once +#include "WebbarInfoTexture.h" +#include + +// Modern/Metal.cpp uploads public map density as R8. MetalExtraction.cpp +// multiplies raw R32F depth by (linearly filtered ground LOS * 800) in the +// native process. Only that resulting field may cross the browser boundary. +// This helper does not select a team, publish data, or choose update cadence. +namespace WebbarMetalTexture { +constexpr uint32_t MAGIC = 0x31544d57; // WMT1, optional presentation-only input +constexpr size_t MAX_BYTES = 32u * 1024u * 1024u; +constexpr uint32_t QUERY_MAGIC = 0x31514d57; // WMQ1 +struct Request { + uint32_t magic, version, request, generation; + int32_t team, allyTeam; + uint32_t frame, fullView, reserved[4]; +}; +static_assert(sizeof(Request) == 48); +inline bool Current(const Request& q, int team, int allyTeam, bool fullView, int frame) +{ + return q.magic == QUERY_MAGIC && q.version == 1 && q.request != 0 && q.generation != 0 + && team >= 0 && team <= 254 && allyTeam >= 0 && allyTeam <= 254 + && q.team == team && q.allyTeam == allyTeam && q.fullView == uint32_t(fullView) + && frame >= 0 && q.frame <= uint32_t(frame) && uint32_t(frame) - q.frame <= 30 + && std::all_of(std::begin(q.reserved), std::end(q.reserved), [](uint32_t n) { return n == 0; }); +} +struct Field { + uint32_t width = 0, height = 0; + std::vector density; + std::vector extraction; +}; + +// GL_LINEAR at the native half-resolution metal texel centres, CLAMP_TO_EDGE. +// Retain normalized floating-point LOS: the radar helper's rounded R8 sample +// would lose fractional coverage before the 800x multiplication. +inline float SampleLos(const WebbarInfoTexture::Plane& los, uint32_t x, uint32_t y, uint32_t width, uint32_t height) +{ + const float px = (float(x) + 0.5f) * float(los.width) / float(width) - 0.5f; + const float py = (float(y) + 0.5f) * float(los.height) / float(height) - 0.5f; + const int ix = int(std::floor(px)), iy = int(std::floor(py)); + const float fx = px - ix, fy = py - iy; + const auto at = [&](int a, int b) { + return float(los.pixels[size_t(std::clamp(b, 0, int(los.height) - 1)) * los.width + std::clamp(a, 0, int(los.width) - 1)]) / 255.0f; + }; + return (at(ix, iy) * (1.0f - fx) + at(ix + 1, iy) * fx) * (1.0f - fy) + + (at(ix, iy + 1) * (1.0f - fx) + at(ix + 1, iy + 1) * fx) * fy; +} + +inline Field Prepare(uint32_t width, uint32_t height, const uint8_t* density, const float* depth, const WebbarInfoTexture::Plane& ground) +{ + const size_t count = size_t(width) * height; + if (!width || !height || width > 8192 || height > 8192 || count > (MAX_BYTES - 36) / 5 || !density || !depth + || !ground.width || !ground.height || ground.width > width || ground.height > height + || size_t(ground.width) * ground.height != ground.pixels.size() + || std::any_of(ground.pixels.begin(), ground.pixels.end(), [](uint8_t n) { return n != 0 && n != 255; })) return {}; + Field result; + result.width = width; result.height = height; + result.density.assign(density, density + count); + result.extraction.resize(count); + for (uint32_t y = 0; y < height; ++y) for (uint32_t x = 0; x < width; ++x) { + const size_t i = size_t(y) * width + x; + const float mask = SampleLos(ground, x, y, width, height); + // Do not inspect or propagate even the sign/NaN state of hidden depth. + // All fully hidden values yield exactly the same positive zero bytes. + if (mask == 0.0f) { result.extraction[i] = 0.0f; continue; } + const float value = depth[i] * (mask * 800.0f); + if (!std::isfinite(value) || value < 0.0f) return {}; + result.extraction[i] = value == 0.0f ? 0.0f : value; + } + return result; +} + +inline std::vector Packet(const Field& field) +{ + const size_t count = size_t(field.width) * field.height, aligned = (count + 3) & ~size_t(3), length = 32 + aligned + count * sizeof(float); + if (!field.width || !field.height || field.width > 8192 || field.height > 8192 || count != field.density.size() + || count != field.extraction.size() || length > MAX_BYTES + || std::any_of(field.extraction.begin(), field.extraction.end(), [](float n) { return !std::isfinite(n) || n < 0.0f || (n == 0.0f && std::signbit(n)); })) return {}; + const uint32_t header[] = { MAGIC, 1, field.width, field.height, uint32_t(count), uint32_t(count * sizeof(float)), 0, 0 }; + std::vector bytes(length, 0); + std::memcpy(bytes.data(), header, sizeof(header)); + std::memcpy(bytes.data() + sizeof(header), field.density.data(), count); + std::memcpy(bytes.data() + sizeof(header) + aligned, field.extraction.data(), count * sizeof(float)); + return bytes; +} +} --- a/rts/Game/WebbarNativeBeams.h +++ b/rts/Game/WebbarNativeBeams.h @@ -357,6 +357,8 @@ PrepareWebbarNativeDistortion(epoch); } } +static void PublishWebbarNativeEtaDraw(float offset,int32_t sequence,uint32_t drawEpoch); +static void PublishWebbarNativeScumDraw(int32_t sequence); static void UpdateWebbarNativeBeams() { PrepareWebbarNativeBeams(); @@ -379,5 +381,7 @@ } webbarNativeBeams->Publish(request,sequence); if(request.distortions) PublishWebbarNativeDistortion(request,sequence); + if((request.flags & 2u) && request.frame == uint32_t(gs->frameNum)) PublishWebbarNativeEtaDraw(request.fraction,sequence,webbarNativeBeams->epoch); + if((request.flags & 2u) && request.frame == uint32_t(gs->frameNum)) PublishWebbarNativeScumDraw(sequence); __atomic_store_n(&webbarBeamDrawMailbox.acknowledged,sequence,__ATOMIC_RELEASE); } --- /dev/null +++ b/rts/Game/WebbarNativeCursorHost.inc @@ -0,0 +1,185 @@ +// Members of the independent native reader. This passive world read uses the +// original GUI selection and BAR DefaultCommand widgets. Press-history routing +// 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) +{ + 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; + // CLuaHandle stops automatic GC between calls. Bound cursor-only allocation + // even when no rich HUD reader is active; retain the existing 10Hz GC pace. + const auto now = std::chrono::steady_clock::now(); + if (now >= cursorNextGc) { CollectGarbage(true); cursorNextGc = now + std::chrono::milliseconds(100); } + SetView(); + std::unordered_map current; + for (const auto id: ids) { + const auto* unit = unitHandler.GetUnit(id); + if (!unit || unit->isDead || unit->noSelect || !WebbarVisible(unit) + || !CSelectedUnitsHandler::CanISelectTeam(playerHandler.Player(gu->myPlayerNum), unit->team) + || !current.emplace(id, WebbarHudLifetime(unit)).second) return false; + } + const std::array context{gu->myTeam, gu->myAllyTeam, int(gu->spectatingFullView), int(gu->spectating), int(webbarReplay::Enabled())}; + bool reset = context != cursorContext; + for (const auto& entry: current) { + const auto old = cursorAdmitted.find(entry.first); + reset |= old != cursorAdmitted.end() && old->second != entry.second; + } + if (reset) { + // Old widget caches restore only to old private lives. Never authorize a + // reused ID before Shutdown has had a chance to restore its prior copy. + const int top = lua_gettop(L); lua_getglobal(L, "WebbarResetCursor"); + const bool ok = RunCallIn(L, LuaHashString("WebbarResetCursor"), 0, 0); + lua_settop(L, top); cursorVolumes.Clear(); cursorIcons.Clear(); cursorAdmitted.clear(); + if (!ok) return false; + cursorContext = context; + } + std::vector commands; int page = 0, activeIndex = -1; + if (!OrderCommands(ids, commands, page)) return false; + if (active) { + for (size_t i = 0; i < commands.size(); ++i) { + if (commands[i].id != commandID) continue; + if (activeIndex >= 0 || commands[i].disabled) return false; + activeIndex = int(i); + } + if (activeIndex < 0) return false; + } + for (const auto& entry: current) cursorAdmitted[entry.first] = entry.second; + PrepareOrderCamera(view); + // This profile uses BAR's pinned intro screen-icon settings, matching the + // browser painter. Its rendered and controller cameras are the same explicit + // browser view; never consult the unrelated headless/global draw camera. + const WebbarNativeOrder::CursorIconPolicy iconPolicy(worldView, worldView, + view.width, view.height, WebbarNativeOrder::CursorIconDefaults::scale, + WebbarNativeOrder::CursorIconDefaults::fadeStart, false, + WebbarNativeOrder::CursorIconDefaults::hideWithUI); + cursorIcons.Update(unitHandler.GetActiveUnits(), iconPolicy); + const int top = lua_gettop(L); + lua_getglobal(L, "WebbarPrepareCursor"); + lua_createtable(L, ids.size(), 0); + for (size_t i = 0; i < ids.size(); ++i) { lua_pushnumber(L, ids[i]); lua_rawseti(L, -2, i + 1); } + lua_createtable(L, 0, 5); + lua_pushnumber(L, view.mouseX); lua_setfield(L, -2, "x"); + lua_pushnumber(L, view.mouseY); lua_setfield(L, -2, "y"); + for (const char* button: {"left", "middle", "right"}) { lua_pushboolean(L, false); lua_setfield(L, -2, button); } + if (active) { + lua_createtable(L, 0, 2); + lua_pushnumber(L, activeIndex + CMD_INDEX_OFFSET); lua_setfield(L, -2, "index"); + lua_pushnumber(L, commandID); lua_setfield(L, -2, "id"); + } else lua_pushnil(L); + lua_pushnumber(L, cursorClock.Seconds()); + const std::string contextKey = std::to_string(context[0]) + "/" + std::to_string(context[1]) + "/" + std::to_string(context[2]) + "/" + std::to_string(context[3]) + "/" + std::to_string(context[4]); + lua_pushlstring(L, contextKey.data(), contextKey.size()); + lua_createtable(L, 0, current.size()); + for (const auto& entry: current) { + char token[9]; std::snprintf(token, sizeof(token), "%08x", entry.second); + lua_pushnumber(L, entry.first); lua_pushstring(L, token); lua_rawset(L, -3); + } + const bool prepared = RunCallIn(L, LuaHashString("WebbarPrepareCursor"), 6, 0); + lua_settop(L, top); + cursorAdmitted = std::move(current); + std::unordered_set selectedSet; for (const auto id: ids) selectedSet.insert(id); + cursorVolumes.Retain(selectedSet); + if (!prepared) return false; + struct Default final: WebbarNativeOrder::CursorDefaultCommand { + WebbarNativeInfoReader* reader; mutable bool ok = true; + explicit Default(WebbarNativeInfoReader* owner): reader(owner) {} + void DefaultCommand(const CUnit* unit, const CFeature* feature, int& id) const override { ok = reader->CursorDefault(unit, feature, id) && ok; } + } delegate(this); + WebbarNativeOrder::CursorInput input{}; + input.route = WebbarNativeOrder::CursorInput::WORLD; input.viewCamera = &worldView; + input.mouseX = view.mouseX; input.mouseY = view.mouseY; + input.worldDirection = worldView.CalcPixelDir(view.mouseX, int(view.height) - 1 - view.mouseY, view.width, view.height, 0); + input.activeIndex = activeIndex; input.rememberedDefaultIndex = -1; input.volumes = &cursorIconVolumes; + const std::vector selected(ids.begin(), ids.end()); + WebbarNativeOrder::CursorPlan plan(commands, selected, delegate, input); + const auto cursor = plan.Resolve(); const int index = plan.DefaultIndex(); + if (!delegate.ok) return false; + json = "{\"cursor\":{\"name\":"; WebbarJsonString(json, cursor.command); + json += ",\"scale\":"; WebbarJsonNumber(json, cursor.scale); + json += "},\"defaultIndex\":" + std::to_string(index + CMD_INDEX_OFFSET) + + ",\"defaultCommand\":" + (index >= 0 ? std::to_string(commands[index].id) : "null") + + ",\"mouse\":[" + std::to_string(view.mouseX) + "," + std::to_string(view.mouseY) + "]}"; + return true; +} + +private: +WebbarNativeOrder::CursorPrivateVolumes cursorVolumes{WebbarHudLifetime}; +WebbarNativeOrder::CursorPrivateIcons cursorIcons{WebbarHudLifetime}; +WebbarNativeOrder::CursorIconVolumes cursorIconVolumes{cursorVolumes, cursorIcons}; +// Info's existing physical selection-volume reads stay unchanged. Supply only +// the native graphical icon state that the headless drawer cannot provide. +struct InfoPhysicalVolumes final: WebbarNativeOrder::CursorSelectionVolumes { + const CollisionVolume& Get(const CUnit& unit) const override { return unit.selectionVolume; } +}; +InfoPhysicalVolumes infoPhysicalVolumes; +WebbarNativeOrder::CursorPrivateIcons infoIcons{WebbarHudLifetime}; +WebbarNativeOrder::CursorIconVolumes infoIconVolumes{infoPhysicalVolumes, infoIcons}; +std::array infoIconContext{-1, -1, -1, -1, -1}; +bool readingWorldInfo = false; +void PrepareInfoIcons() +{ + const std::array context{gu->myTeam, gu->myAllyTeam, int(gu->spectatingFullView), int(gu->spectating), int(webbarReplay::Enabled())}; + if (infoIconContext != context) { infoIcons.Clear(); infoIconContext = context; } + const WebbarNativeOrder::CursorIconPolicy policy(worldView, worldView, + worldWidth, worldHeight, WebbarNativeOrder::CursorIconDefaults::scale, + WebbarNativeOrder::CursorIconDefaults::fadeStart, false, + WebbarNativeOrder::CursorIconDefaults::hideWithUI); + infoIcons.Update(unitHandler.GetActiveUnits(), policy); +} +std::unordered_map cursorAdmitted; +std::array cursorContext{-1, -1, -1, -1, -1}; +WebbarPipClock cursorClock; +std::chrono::steady_clock::time_point cursorNextGc = std::chrono::steady_clock::time_point::min(); +const CUnit* CursorVolumeUnit(lua_State* state) +{ + const int id = luaL_checkint(state, 1); + const auto entry = cursorAdmitted.find(id); + const auto* unit = unitHandler.GetUnit(id); + if (!unit || entry == cursorAdmitted.end() || entry->second != WebbarHudLifetime(unit) || !WebbarVisible(unit)) return nullptr; + return unit; +} +static int CursorGetVolume(lua_State* state) +{ + auto* self = static_cast(CLuaHandle::GetHandle(state)); + const auto* unit = self->CursorVolumeUnit(state); + return unit ? LuaUtils::PushColVolData(state, &self->cursorVolumes.Get(*unit)) : 0; +} +static int CursorSetVolume(lua_State* state) +{ + auto* self = static_cast(CLuaHandle::GetHandle(state)); + const auto* unit = self->CursorVolumeUnit(state); + return unit ? LuaUtils::ParseColVolData(state, 2, &self->cursorVolumes.Edit(*unit)) : 0; +} +static int CursorScreenRay(lua_State* state) +{ + auto* self = static_cast(CLuaHandle::GetHandle(state)); + return LuaUnsyncedRead::TraceScreenRayForCameraWithVolumes(state, &self->worldView, self->worldWidth, self->worldHeight, &self->cursorIconVolumes); +} +bool CursorDefault(const CUnit* unit, const CFeature* feature, int& command) +{ + const int top = lua_gettop(L); lua_getglobal(L, "WebbarCursorDefault"); + if (unit || feature) { + lua_pushstring(L, unit ? "unit" : "feature"); lua_pushnumber(L, unit ? unit->id : feature->id); + } else { lua_pushnil(L); lua_pushnil(L); } + lua_pushnumber(L, command); + const bool ok = RunCallIn(L, LuaHashString("WebbarCursorDefault"), 3, 1); + if (ok && lua_isnumber(L, -1)) command = lua_toint(L, -1); + lua_settop(L, top); return ok; +} +bool InstallCursorReads() +{ + const int top = lua_gettop(L); lua_pushvalue(L, LUA_GLOBALSINDEX); + if (!AddEntriesToTable(L, "CMD", LuaConstCMD::PushEntries)) { lua_settop(L, top); return false; } + lua_getglobal(L, "Spring"); + lua_pushcfunction(L, LuaUnsyncedRead::GetConfigInt); lua_setfield(L, -2, "GetConfigInt"); + lua_pushcfunction(L, LuaUnsyncedRead::GetLocalTeamID); lua_setfield(L, -2, "GetMyTeamID"); + lua_pushcfunction(L, LuaUnsyncedRead::GetSpectatingState); lua_setfield(L, -2, "GetSpectatingState"); + lua_pushcfunction(L, LuaUnsyncedRead::IsReplay); lua_setfield(L, -2, "IsReplay"); + lua_settop(L, top); + lua_pushcfunction(L, CursorGetVolume); lua_setglobal(L, "WebbarCursorGetSelectionVolume"); + lua_pushcfunction(L, CursorSetVolume); lua_setglobal(L, "WebbarCursorSetSelectionVolume"); + lua_pushcfunction(L, CursorScreenRay); lua_setglobal(L, "WebbarCursorTraceScreenRay"); + return true; +} +public: --- /dev/null +++ b/rts/Game/WebbarNativeCursorIcons.h @@ -0,0 +1,174 @@ +/* This file is part of the Spring engine (GPL v2 or later), see LICENSE.html */ +#pragma once +#include +#include +#include +#include +#include +#include "Game/Camera.h" +#include "Game/GlobalUnsynced.h" +#include "Game/GameSetup.h" +#include "Map/Ground.h" +#include "Map/ReadMap.h" +#include "Rendering/IconHandler.h" +#include "Sim/Misc/LosHandler.h" +#include "Sim/Units/Unit.h" +#include "System/Misc/TracyDefs.h" +#include "WebbarNativeCursorTrace.h" +namespace WebbarNativeOrder { +// Pinned BAR intro defaults, shared with the browser's ordinary screen icons. +// Hidden-interface views do not enter this passive cursor profile. +struct CursorIconDefaults { + static constexpr float scale = 1.0499999523162842f; + static constexpr float fadeStart = 3000.0f; + static constexpr bool hideWithUI = true; +}; +struct CursorIconState { + size_t index = icon::INVALID_ICON_INDEX; + float radius = 0; + bool asIcon = false; +}; +class CursorIconPolicy { +public: + // Render and controller views are explicit: the native zoom-distance read + // uses the controller, while projection uses the current render camera. + CursorIconPolicy(const CCamera& renderView, const CCamera& controllerView, + int width, int height, float scale, float fadeStart, bool hidden, bool hideWithUI): + viewCamera(&renderView), gameState{hidden}, iconFadeStart(fadeStart), iconHideWithUI(hideWithUI) { + iconSizeBase = std::max(1.0f, std::max(width, height) * iconSizeMult * scale); + const float3 camPos = controllerView.GetPos(); + const float3 camDir = controllerView.GetDir(); + float dist = CGround::LineGroundCol(camPos, camDir * 150000.0f, false); + if (dist < 0) + dist = std::max(0.0f, CGround::LinePlaneCol(camPos, camDir, 150000.0f, readMap->GetCurrAvgHeight())); + iconZoomDist = dist; + } + CursorIconPolicy(const CursorIconPolicy&) = delete; + CursorIconPolicy& operator=(const CursorIconPolicy&) = delete; + CursorIconPolicy(CursorIconPolicy&&) = delete; + CursorIconPolicy& operator=(CursorIconPolicy&&) = delete; + CursorIconState Read(const CUnit& unit, float previousRadius) const { + CursorIconState state; state.index = Index(&unit, gu->myAllyTeam, gu->spectatingFullView); state.radius = previousRadius; + Update(&unit, state); return state; + } +private: + static constexpr float iconSizeMult = 0.005f; + const CCamera* viewCamera; + struct Game {bool hideInterface;}; + Game gameState; + const Game* game = &gameState; + float iconSizeBase, iconZoomDist; + const float iconFadeStart; + const bool iconHideWithUI; + size_t Index(const CUnit* unit, int allyTeam, bool fullView) const { + const unsigned short losStatus = unit->losStatus[allyTeam]; + constexpr unsigned short prevMask = (LOS_PREVLOS | LOS_CONTRADAR); + + // use the unit's custom icon if the viewer can currently see it, + // or has seen it before and did not lose contact since + const bool isInLOS = (losStatus & LOS_INLOS ) == LOS_INLOS; + const bool isInPrvLos = (losStatus & LOS_PREVLOS) == LOS_PREVLOS; + const bool isInRadar = (losStatus & LOS_INRADAR) == LOS_INRADAR; + const bool seenUnit = (losStatus & prevMask ) == prevMask; + const bool isGhostBuilding = gameSetup->ghostedBuildings && unit->leavesGhost && isInPrvLos; + + const bool unitVisible = isInLOS || (isInRadar && seenUnit) || isGhostBuilding; + + if (unitVisible || fullView) + return (unit->customIconIndex != icon::INVALID_ICON_INDEX) ? unit->customIconIndex : icon::iconHandler.GetIconIdxOrDefault(unit->definedIconName); + + if ((losStatus & LOS_INRADAR) != 0) + return icon::iconHandler.GetDefaultIconIdx(); + + return icon::INVALID_ICON_INDEX; +} + void Update(const CUnit* unit, CursorIconState& state) const { + RECOIL_DETAILED_TRACY_ZONE; + if (game->hideInterface && iconHideWithUI) // icons are hidden with UI + { + state.asIcon = false; // draw unit model always + return; + } + + if (state.index == icon::INVALID_ICON_INDEX || unit->health <= 0 || unit->beingBuilt || unit->noDraw || unit->IsInVoid()) + { + state.asIcon = false; + return; + } + + const unsigned short losStatus = unit->losStatus[gu->myAllyTeam]; + + const auto& iconData = icon::iconHandler.GetIconData(state.index); + + float iconSizeMult = iconData.GetSize(); + if (iconData.GetRadiusAdjust()) + iconSizeMult *= (unit->radius / iconData.GetRadiusScale()); + iconSizeMult = iconSizeMult * 0.75f + 0.25f; + + float limit = iconSizeBase / 2 * iconSizeMult; + + // calculate unit's radius in screen space and compare with the size of the icon + float3 pos = unit->pos; + float3 radiusPos = pos + viewCamera->right * unit->radius; + + pos = viewCamera->CalcViewPortCoordinates(pos); + radiusPos = viewCamera->CalcViewPortCoordinates(radiusPos); + + state.radius = unit->radius * ((limit * 0.9) / std::abs(pos.x - radiusPos.x)); // used for clicking on iconified units (world space!!!) + + if (!(losStatus & LOS_INLOS) && !gu->spectatingFullView) // no LOS on unit + { + state.asIcon = losStatus & LOS_INRADAR; // draw icon if unit is on radar + return; + } + + // don't render unit's model if it is smaller than icon by 10% in screen space + // render it anyway in case icon isn't completely opaque (below FadeStart distance) + state.asIcon = iconZoomDist / iconSizeMult > iconFadeStart && std::abs(pos.x - radiusPos.x) < limit * 0.9; +} +}; +// The native drawer retains iconRadius on early returns. Preserve that history +// for every live unit in this view, including units outside the cursor ray. +// Bind it to the engine lifetime so a reused ID starts with native radius zero. +class CursorPrivateIcons { +public: + using Lifetime = uint32_t (*)(const CUnit*); + explicit CursorPrivateIcons(Lifetime token): lifetime(token) {} + template void Update(const Units& units, const CursorIconPolicy& policy) { + // Keep a mark in the existing per-life cache rather than allocating another + // hash node for every live unit on each 30 Hz read. + if (++revision == 0) { entries.clear(); revision = 1; } + for (const CUnit* unit: units) { + const auto token = lifetime(unit); + auto it = entries.find(unit->id); + const float previous = it != entries.end() && it->second.token == token ? it->second.state.radius : 0; + entries.insert_or_assign(unit->id, Entry{token, policy.Read(*unit, previous), revision}); + } + for (auto it = entries.begin(); it != entries.end();) { + if (it->second.revision != revision) it = entries.erase(it); else ++it; + } + } + CursorIconState Read(const CUnit& unit) const { + const auto it = entries.find(unit.id); + return it != entries.end() && it->second.token == lifetime(&unit) ? it->second.state : CursorIconState{}; + } + void Clear() { entries.clear(); revision = 0; } +private: + struct Entry {uint32_t token; CursorIconState state; uint64_t revision;}; + const Lifetime lifetime; + uint64_t revision = 0; + std::unordered_map entries; +}; +// Compose the private selection mask and graphical icon state into one trace +// view. Neither fallback reads stale graphical fields from the headless unit. +class CursorIconVolumes final: public CursorSelectionVolumes { +public: + CursorIconVolumes(const CursorSelectionVolumes& volumes, const CursorPrivateIcons& icons): volumes(volumes), icons(icons) {} + const CollisionVolume& Get(const CUnit& unit) const override { return volumes.Get(unit); } + bool IsIcon(const CUnit& unit) const override { return icons.Read(unit).asIcon; } + float IconRadius(const CUnit& unit) const override { return icons.Read(unit).radius; } +private: + const CursorSelectionVolumes& volumes; + const CursorPrivateIcons& icons; +}; +} --- /dev/null +++ b/rts/Game/WebbarNativeCursorPoll.inc @@ -0,0 +1,48 @@ +// A separate read-only cursor slot. Do not queue the visible pointer behind +// rich Info/Order/Players reads or change bridge9's saved command protocol. +static void PollCursor() +{ + static const bool enabled = std::getenv("WEBBAR_NATIVE_CURSOR_READS") != nullptr; + if (!enabled || WebbarUiEvents::CatchingUp() || std::getenv("WEBBAR_NETWORK") != nullptr) return; + static auto next = std::chrono::steady_clock::time_point::min(); + const auto now = std::chrono::steady_clock::now(); + if (now < next) return; + static std::array bytes{}; + const int size = MAIN_THREAD_EM_ASM_INT({ return Module['webbarPollNativeCursor'] ? Module['webbarPollNativeCursor']($0, $1) : 0; }, bytes.data(), bytes.size()); + if (size < int(sizeof(Header)) || size > int(bytes.size())) return; + next = now + std::chrono::microseconds(33334); + Header h; std::memcpy(&h, bytes.data(), sizeof(h)); + if (h.magic != 0x31554357u || h.version != 1 || h.request == 0 || h.request == 0xffffffffu || h.generation == 0 || h.generation == 0xffffffffu) return; // WCU1 + const auto reply = [&](uint32_t status, const std::string& data = "null") { + 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) + ",\"data\":" + data + '}'; + MAIN_THREAD_EM_ASM({ if (Module['webbarNativeCursorResult']) Module['webbarNativeCursorResult'](UTF8ToString($0)); }, json.c_str()); + }; + const int commandID = int32_t(h.reserved[0]); const bool active = h.reserved[1] == 1; + if (h.kind != 1 || h.count > 8192 || h.flags > 1 || h.reserved[1] > 1 || (!active && commandID != 0) + || commandID <= -16777216 || commandID >= 16777216 + || size != int(sizeof(Header) + sizeof(WebbarInfoWorldView) + 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)); + // This passive read deliberately carries no inferred press history. Actual + // ordered presses and remembered RMB defaults need the input-event route. + if (!WebbarNativeInfoReader::ValidCursorView(view)) { reply(1); return; } + std::vector ids; std::unordered_set seen; + for (uint32_t i = 0; i < h.count; ++i) { + Row row; std::memcpy(&row, bytes.data() + sizeof(Header) + sizeof(view) + i * sizeof(Row), sizeof(Row)); + if (row.id > 65535 || !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 != 0 && (row.lifetime == 0xffffffffu || unit->team != gu->myTeam || WebbarHudLifetime(unit) != row.lifetime))) { reply(2); return; } + ids.push_back(row.id); + } + if (!reader) reader = new WebbarNativeInfoReader; + std::string json; + if (!reader->ReadCursor(view, ids, active, commandID, json)) { reply(4); return; } + reply(0, json); +} --- /dev/null +++ b/rts/Game/WebbarNativeCursorSelection.h @@ -0,0 +1,365 @@ +/* This file is part of the Spring engine (GPL v2 or later), see LICENSE.html */ +#pragma once +#include +#include +#include +#include +#include "WebbarNativeMinimap.h" +#include "WebbarNativeCursorTrace.h" +#include "Game/Camera.h" +#include "Game/TraceRay.h" +#include "Sim/Features/Feature.h" +#include "Sim/Units/BuildInfo.h" +#include "Sim/Units/Unit.h" +#include "Sim/Units/UnitDef.h" +#include "Sim/Units/UnitDefHandler.h" +#include "Sim/Units/UnitHandler.h" +#include "Sim/Units/CommandAI/CommandAI.h" +#include "Sim/Units/CommandAI/CommandDescription.h" +#include "Sim/Weapons/Weapon.h" +#include "System/EventHandler.h" +#include "System/UnorderedSet.hpp" +namespace WebbarNativeOrder { +// The host supplies the original LuaUI DefaultCommand dispatch. A bare engine +// event handler is insufficient when the graphical LuaUI is not instantiated. +struct CursorDefaultCommand { + virtual ~CursorDefaultCommand() = default; + virtual void DefaultCommand(const CUnit*, const CFeature*, int&) const = 0; +}; +class CursorSelection { +public: + explicit CursorSelection(const CursorDefaultCommand& delegate): eventHandler(delegate) {} + spring::unordered_set selectedUnits; + int GetDefaultCmd(const CUnit* unit, const CFeature* feature) { + RECOIL_DETAILED_TRACY_ZONE; + // return the default if there are no units selected + if (selectedUnits.empty()) + return CMD_STOP; + + // setup the locals for IsBetterLeader() + targetUnit = unit; + targetFeature = feature; + + if (targetUnit != nullptr) + targetIsEnemy = !teamHandler.Ally(gu->myAllyTeam, targetUnit->allyteam); + + // find the best leader to pick the command + const CUnit* leaderUnit = unitHandler.GetUnit(*selectedUnits.begin()); + const UnitDef* leaderDef = leaderUnit->unitDef; + + for (const int unitID: selectedUnits) { + const CUnit* testUnit = unitHandler.GetUnit(unitID); + const UnitDef* testDef = testUnit->unitDef; + + if (testDef == leaderDef) + continue; + + if (!IsBetterLeader(testDef, leaderDef)) + continue; + + leaderDef = testDef; + leaderUnit = testUnit; + } + + int cmd = leaderUnit->commandAI->GetDefaultCmd(unit, feature); + eventHandler.DefaultCommand(unit, feature, cmd); + return cmd; +} +private: + const CursorDefaultCommand& eventHandler; + bool targetIsEnemy = false; + const CUnit* targetUnit = nullptr; + const CFeature* targetFeature = nullptr; + bool IsBetterLeader(const UnitDef* newDef, const UnitDef* oldDef) { + RECOIL_DETAILED_TRACY_ZONE; + // There is a lot more that could be done here to make better + // selections, but the users may prefer simplicity over smarts. + + if (targetUnit != nullptr) { + if (targetIsEnemy) { + const bool newCanDamage = newDef->CanDamage(); + const bool oldCanDamage = oldDef->CanDamage(); + + if ( newCanDamage && !oldCanDamage) + return true; + if (!newCanDamage && oldCanDamage) + return false; + if (!targetUnit->unitDef->CanDamage()) { + if ( newDef->canReclaim && !oldDef->canReclaim) + return true; + if (!newDef->canReclaim && oldDef->canReclaim) + return false; + } + } else { // targetIsAlly + if (targetUnit->health < targetUnit->maxHealth) { + if ( newDef->canRepair && !oldDef->canRepair) + return true; + if (!newDef->canRepair && oldDef->canRepair) + return false; + } + + const bool newCanLoad = (newDef->transportCapacity > 0); + const bool oldCanLoad = (oldDef->transportCapacity > 0); + + if ( newCanLoad && !oldCanLoad) + return true; + if (!newCanLoad && oldCanLoad) + return false; + if ( newDef->canGuard && !oldDef->canGuard) + return true; + if (!newDef->canGuard && oldDef->canGuard) + return false; + } + } + else if (targetFeature != nullptr) { + if (targetFeature->udef != nullptr) { + if ( newDef->canResurrect && !oldDef->canResurrect) + return true; + if (!newDef->canResurrect && oldDef->canResurrect) + return false; + } + if ( newDef->canReclaim && !oldDef->canReclaim) + return true; + if (!newDef->canReclaim && oldDef->canReclaim) + return false; + } + + return (newDef->speed > oldDef->speed); // CMD_MOVE? +} +}; +struct CursorInput { + enum Route { WORLD, HUD, MINIMAP } route; + const CCamera* viewCamera; + const MinimapProxy* minimap; + float3 worldDirection; + int mouseX, mouseY, minimapMouseX, minimapMouseY; + int activeIndex, rememberedDefaultIndex, facing; + float minimapScale; + bool rightPressed, proxyMode, worldReceiver, fullProxy, hideInterface, offscreen, gatherMode; + const CursorSelectionVolumes* volumes = nullptr; +}; +struct CursorResult { std::string command = "cursornormal"; float scale = 1.0f; }; +class CursorPlan { +public: + CursorPlan(std::vector descriptors, const std::vector& ids, const CursorDefaultCommand& delegate, const CursorInput& input): + commands(std::move(descriptors)), viewCamera(input.viewCamera), route(input.route), worldReceiver(input.worldReceiver), gatherMode(input.gatherMode), + inCommand(input.activeIndex), defaultCmdMemory(input.rememberedDefaultIndex), buildFacing(input.facing), volumes(input.volumes), selectedUnitsHandler(delegate) { + for (int id: ids) selectedUnitsHandler.selectedUnits.insert(id); + gameState.hideInterface = input.hideInterface; + mouseState.lastx = input.mouseX; mouseState.lasty = input.mouseY; mouseState.dir = input.worldDirection; mouseState.offscreen = input.offscreen; + mouseState.buttons[SDL_BUTTON_RIGHT].pressed = input.rightPressed; + miniState.proxy = input.minimap; miniState.scale = input.minimapScale; miniState.full = input.fullProxy; miniState.proxied = input.proxyMode; + miniState.offsetX = input.mouseX - input.minimapMouseX; miniState.offsetY = input.mouseY - input.minimapMouseY; + } + CursorPlan(const CursorPlan&) = delete; + CursorPlan& operator=(const CursorPlan&) = delete; + CursorPlan(CursorPlan&&) = delete; + CursorPlan& operator=(CursorPlan&&) = delete; + CursorResult Resolve() const { SetCursorIcon(); return mouseState.result; } + int DefaultIndex() const { return GetDefaultCommand(mouse->lastx, mouse->lasty); } +private: + using string = std::string; + std::vector commands; + struct Receiver {}; + struct Mini: Receiver { + const MinimapProxy* proxy = nullptr; + int offsetX=0, offsetY=0; + float scale = 1; + bool full = true, proxied = false; + float CursorScale() const { return scale; } + bool FullProxy() const { return full; } + bool ProxyMode() const { return proxied; } + float3 GetMapPosition(int x,int y) const { return proxy->Position(x-offsetX,y-offsetY); } + CUnit* GetSelectUnit(const float3& position) const { return proxy->Select(position); } + } miniState; + const Mini* minimap = &miniState; + Receiver hudReceiver; + const CCamera* viewCamera; + CursorInput::Route route; + bool worldReceiver, gatherMode; + int inCommand, defaultCmdMemory, buildFacing; + const CursorSelectionVolumes* volumes; + mutable CursorSelection selectedUnitsHandler; + struct Game { bool hideInterface=false; } gameState; + const Game* game = &gameState; + struct Mouse { + struct Button { bool pressed=false; } buttons[4]; + int lastx=0,lasty=0; + bool offscreen=false; + float3 dir; + CursorResult result; + void ChangeCursor(const std::string& command,float scale) { result={command,scale}; } + }; + mutable Mouse mouseState; + Mouse* mouse = &mouseState; + Receiver* GetReceiverAt(int,int) const { return route==CursorInput::HUD ? const_cast(&hudReceiver) : route==CursorInput::MINIMAP ? const_cast(&miniState) : nullptr; } + float TraceWorld(const float3& start,const float3& direction,float length,const CUnit* exclude,const CUnit*& unit,const CFeature*& feature,bool radar,bool groundOnly=false,bool ignoreWater=false) const { + return volumes ? CursorGuiTraceRay(*volumes,start,direction,length,exclude,unit,feature,radar,groundOnly,ignoreWater) : TraceRay::GuiTraceRay(start,direction,length,exclude,unit,feature,radar,groundOnly,ignoreWater); + } + int GetDefaultCommand(int x,int y) const { return GetDefaultCommand(x,y,viewCamera->GetPos(),mouse->dir); } + int GetDefaultCommand(int x,int y,const float3& cameraPos,const float3& mouseDir) const { + RECOIL_DETAILED_TRACY_ZONE; + Receiver* ir = nullptr; + + if (!game->hideInterface && !mouse->offscreen) + ir = GetReceiverAt(x, y); + + if ((ir != nullptr) && (ir != minimap)) + return -1; + + int cmdID = -1; + + { + const CUnit* unit = nullptr; + const CFeature* feature = nullptr; + + if ((ir == minimap) && (minimap->FullProxy())) { + unit = minimap->GetSelectUnit(minimap->GetMapPosition(x, y)); + } else { + const float viewRange = viewCamera->GetFarPlaneDist() * 1.4f; + const float dist = TraceWorld(cameraPos, mouseDir, viewRange, nullptr, unit, feature, true); + const float3 hit = cameraPos + mouseDir * dist; + + // make sure the ray hit in the map + if (unit == nullptr && feature == nullptr && !hit.IsInBounds()) + return -1; + } + + cmdID = selectedUnitsHandler.GetDefaultCmd(unit, feature); + } + + // make sure the command is currently available + for (int c = 0; c < (int)commands.size(); c++) { + if (cmdID == commands[c].id) { + return c; + } + } + return -1; +} + bool TryTarget(const SCommandDescription& cmdDesc) const { + RECOIL_DETAILED_TRACY_ZONE; + if (cmdDesc.id != CMD_ATTACK) + return true; + + if (selectedUnitsHandler.selectedUnits.empty()) + return true; + + // get mouse-hovered map pos + const CUnit* targetUnit = nullptr; + const CFeature* targetFeature = nullptr; + + const float viewRange = viewCamera->GetFarPlaneDist() * 1.4f; + const float dist = TraceWorld(viewCamera->GetPos(), mouse->dir, viewRange, NULL, targetUnit, targetFeature, true); + const float3 groundPos = viewCamera->GetPos() + mouse->dir * dist; + + if (dist <= 0.0f) + return false; + + for (const int unitID: selectedUnitsHandler.selectedUnits) { + const CUnit* u = unitHandler.GetUnit(unitID); + + // mobile kamikaze can always move into range + //FIXME do a range check in case of immobile kamikaze (-> mines) + if (u->unitDef->canKamikaze && !u->immobile) + return true; + + for (const CWeapon* w: u->weapons) { + float3 modGroundPos = groundPos; + w->AdjustTargetPosToWater(modGroundPos, targetUnit == NULL); + const SWeaponTarget wtrg = SWeaponTarget(targetUnit, modGroundPos); + + if (u->immobile) { + // immobile unit + // check range and weapon target properties + if (w->TryTarget(wtrg)) { + return true; + } + } else { + // mobile units can always move into range + // only check if we got a weapon that can shot the target (i.e. anti-air/anti-sub) + if (w->TestTarget(w->GetLeadTargetPos(wtrg), wtrg)) { + return true; + } + } + } + } + + return false; +} + void SetCursorIcon() const { + RECOIL_DETAILED_TRACY_ZONE; + string newCursor = "cursornormal"; + float cursorScale = 1.0f; + + Receiver* ir = nullptr; + + if (!game->hideInterface && !mouse->offscreen) + ir = GetReceiverAt(mouse->lastx, mouse->lasty); + + if ((ir != nullptr) && (ir != minimap)) { + mouse->ChangeCursor(newCursor, cursorScale); + return; + } + + if (ir == minimap) + cursorScale = minimap->CursorScale(); + + const bool useMinimap = (minimap->ProxyMode() || ((!worldReceiver) && (ir == minimap))); + + if ((inCommand >= 0) && ((size_t)inCommandGetMapPosition(mouse->lastx, mouse->lasty); + bi.buildFacing = buildFacing; + bi.def = unitDefHandler->GetUnitDefByID(-cmdDesc.id); + bi.pos = CGameHelper::Pos2BuildPos(bi, false); + // if an unit (enemy), is not in LOS, then TestUnitBuildSquare() + // does not consider it when checking for position blocking + CFeature* feature = nullptr; + + if (!CGameHelper::TestUnitBuildSquare(bi, feature, gu->myAllyTeam, false)) { + newCursor = "BuildBad"; + } else { + newCursor = "BuildGood"; + } + } + + if (!TryTarget(cmdDesc)) { + newCursor = "AttackBad"; + } + } + else if (!useMinimap || minimap->FullProxy()) { + int defcmd; + + if (mouse->buttons[SDL_BUTTON_RIGHT].pressed && ((worldReceiver) || (minimap->ProxyMode()))) { + defcmd = defaultCmdMemory; + } else { + defcmd = GetDefaultCommand(mouse->lastx, mouse->lasty); + } + + if ((defcmd >= 0) && ((size_t)defcmd < commands.size())) { + const SCommandDescription& cmdDesc = commands[defcmd]; + + if (!cmdDesc.mouseicon.empty()) { + newCursor = cmdDesc.mouseicon; + } else { + newCursor = cmdDesc.name; + } + } + } + + if (gatherMode && ((newCursor == "Move") || (newCursor == "Fight"))) + newCursor = "GatherWait"; + + mouse->ChangeCursor(newCursor, cursorScale); +} +}; +} --- /dev/null +++ b/rts/Game/WebbarNativeCursorTrace.h @@ -0,0 +1,181 @@ +/* This file is part of the Spring engine (GPL v2 or later), see LICENSE.html */ +#pragma once +#include +#include "Game/GlobalUnsynced.h" +#include "Map/Ground.h" +#include "Sim/Features/Feature.h" +#include "Sim/Misc/CollisionHandler.h" +#include "Sim/Misc/CollisionVolume.h" +#include "Sim/Misc/LosHandler.h" +#include "Sim/Misc/QuadField.h" +#include "Sim/Misc/TeamHandler.h" +#include "Sim/Units/Unit.h" +#include "Sim/Units/UnitDef.h" +#include "System/GlobalConfig.h" +#include "System/Misc/TracyDefs.h" +namespace WebbarNativeOrder { +struct CursorSelectionVolumes { + virtual ~CursorSelectionVolumes() = default; + // Read through private copies; leave unit volumes and simulation untouched. + virtual const CollisionVolume& Get(const CUnit&) const = 0; + // Defaults preserve the original graphical fields. A private render view can + // override both reads together, without changing native unit draw state. + virtual bool IsIcon(const CUnit& unit) const { return unit.GetIsIcon(); } + virtual float IconRadius(const CUnit& unit) const { return unit.iconRadius; } +}; +inline float CursorGuiTraceRay( + const CursorSelectionVolumes& volumes, + const float3& start, + const float3& dir, + const float length, + const CUnit* exclude, + const CUnit*& hitUnit, + const CFeature*& hitFeature, + bool useRadar, + bool groundOnly, + bool ignoreWater +) { + RECOIL_DETAILED_TRACY_ZONE; + hitUnit = nullptr; + hitFeature = nullptr; + + if (dir == ZeroVector) + return -1.0f; + + // ground and water-plane intersection + const float guiRayLength = length; + const float groundRayLength = CGround::LineGroundCol(start, dir, guiRayLength, false); + const float waterRayLength = CGround::LinePlaneCol(start, dir, guiRayLength, CGround::GetWaterPlaneLevel()); + + float minRayLength = groundRayLength; + float minIngressDist = length; + float minEgressDist = length; + + bool hitFactory = false; + + // if ray cares about water, take minimum + // of distance to ground and water surface + if (!ignoreWater) + minRayLength = std::min(groundRayLength, waterRayLength); + if (groundOnly) + return minRayLength; + + // set maximum ray until ground intersection taking lenience into account later + float maxRayLength; + if (minRayLength >= 0.0) { + // normal intersection + maxRayLength = minRayLength; + } else if (waterRayLength >= 0.0) { + // out of map we still want to intersect somewhere if possible + maxRayLength = waterRayLength; + } else { + // pointing upwards + maxRayLength = length; + } + maxRayLength = std::min(maxRayLength + globalConfig.selectThroughGround, length); + + CollisionQuery cq; + + QuadFieldQuery qfQuery; + if (useRadar) { + const float allyTeamError = losHandler->GetAllyTeamRadarErrorSize(gu->myAllyTeam); + quadField.GetQuadsOnWideRay(qfQuery, start, dir, maxRayLength, allyTeamError); + } else { + quadField.GetQuadsOnRay(qfQuery, start, dir, maxRayLength); + } + + for (const int quadIdx: *qfQuery.quads) { + const CQuadField::Quad& quad = quadField.GetQuad(quadIdx); + + // Unit Intersection + for (const CUnit* u: quad.units) { + const bool unitIsEnemy = !teamHandler.Ally(u->allyteam, gu->myAllyTeam); + const bool unitOnRadar = (useRadar && losHandler->InRadar(u, gu->myAllyTeam)); + const bool unitInSight = (u->losStatus[gu->myAllyTeam] & (LOS_INLOS | LOS_CONTRADAR)); + const bool unitVisible = !unitIsEnemy || unitOnRadar || unitInSight || gu->spectatingFullView; + + if (u == exclude) + continue; + #if 0 + // test this bit only in synced traces, rely on noSelect here + if (!u->HasCollidableStateBit(CSolidObject::CSTATE_BIT_QUADMAPRAYS)) + continue; + #endif + if (u->noSelect) + continue; + if (!unitVisible) + continue; + + CollisionVolume cv = volumes.Get(*u); + + // for iconified units, just pretend the collision + // volume is a sphere of radius IconRadius> + // (count radar blips as such too) + if (volumes.IsIcon(*u) || (!unitInSight && unitOnRadar && unitIsEnemy)) + cv.InitSphere(volumes.IconRadius(*u)); + + if (CCollisionHandler::MouseHit(u, u->GetTransformMatrix(false), start, start + dir * guiRayLength, &cv, &cq)) { + // get the distance to the ray-volume ingress point + // (not likely to generate inside-hit special cases) + const float ingressDist = cq.GetIngressPosDist(start, dir); + const float egressDist = cq.GetEgressPosDist(start, dir); + + const bool factoryUnderCursor = u->unitDef->IsFactoryUnit(); + const bool factoryHitBeforeUnit = ((hitFactory && ingressDist < minIngressDist) || (!hitFactory && egressDist < minIngressDist)); + const bool unitHitInsideFactory = ((hitFactory && ingressDist < minEgressDist) || (!hitFactory && ingressDist < minIngressDist)); + + // give units in a factory higher priority than the factory itself + if (hitUnit == nullptr || (factoryUnderCursor && factoryHitBeforeUnit) || (!factoryUnderCursor && unitHitInsideFactory)) { + hitFactory = factoryUnderCursor; + minIngressDist = ingressDist; + minEgressDist = egressDist; + + hitUnit = u; + hitFeature = nullptr; + } + } + } + + // Feature Intersection + for (const CFeature* f: quad.features) { + if (!gu->spectatingFullView && !f->IsInLosForAllyTeam(gu->myAllyTeam)) + continue; + #if 0 + // test this bit only in synced traces, rely on noSelect here + if (!f->HasCollidableStateBit(CSolidObject::CSTATE_BIT_QUADMAPRAYS)) + continue; + #endif + if (f->noSelect) + continue; + + const CollisionVolume& cv = f->selectionVolume; + + if (CCollisionHandler::MouseHit(f, f->GetTransformMatrix(false), start, start + dir * guiRayLength, &cv, &cq)) { + const float hitDist = cq.GetHitPosDist(start, dir); + + const bool factoryHitBeforeUnit = ( hitFactory && hitDist < minEgressDist); + const bool unitHitInsideFactory = (!hitFactory && hitDist < minIngressDist); + + // we want the closest feature (intersection point) on the ray + // give features in a factory (?) higher priority than the factory itself + if (hitUnit == nullptr || factoryHitBeforeUnit || unitHitInsideFactory) { + hitFactory = false; + minIngressDist = hitDist; + + hitFeature = f; + hitUnit = nullptr; + } + } + } + } + + if ((minRayLength > 0.0f) && (maxRayLength < minIngressDist)) { + minIngressDist = minRayLength; + + hitUnit = nullptr; + hitFeature = nullptr; + } + + return minIngressDist; +} +} --- /dev/null +++ b/rts/Game/WebbarNativeCursorVolumes.h @@ -0,0 +1,38 @@ +/* This file is part of the Spring engine (GPL v2 or later), see LICENSE.html */ +#pragma once +#include +#include +#include +#include "WebbarNativeCursorTrace.h" + +namespace WebbarNativeOrder { +// Ignore Self needs mutable volumes within the independent UI reader. Keep +// those copies bound to the native unit lifetime; never write CUnit volumes. +class CursorPrivateVolumes final: public CursorSelectionVolumes { +public: + using Lifetime = uint32_t (*)(const CUnit*); + explicit CursorPrivateVolumes(Lifetime token): lifetime(token) {} + const CollisionVolume& Get(const CUnit& unit) const override { + const auto it = entries.find(unit.id); + return it != entries.end() && it->second.token == lifetime(&unit) + ? it->second.volume : unit.selectionVolume; + } + CollisionVolume& Edit(const CUnit& unit) { + const auto token = lifetime(&unit); + auto it = entries.find(unit.id); + if (it == entries.end()) it = entries.emplace(unit.id, Entry{token, unit.selectionVolume}).first; + if (it->second.token != token) it->second = Entry{token, unit.selectionVolume}; + return it->second.volume; + } + void Retain(const std::unordered_set& selected) { + for (auto it = entries.begin(); it != entries.end();) { + if (selected.find(it->first) == selected.end()) it = entries.erase(it); else ++it; + } + } + void Clear() { entries.clear(); } +private: + struct Entry { uint32_t token; CollisionVolume volume; }; + const Lifetime lifetime; + std::unordered_map entries; +}; +} --- /dev/null +++ b/rts/Game/WebbarNativeEta.h @@ -0,0 +1,185 @@ +/* This file is part of the Spring engine (GPL v2 or later), see LICENSE.html */ +#pragma once +#include +#include +#include +#include +#include "WebbarNativeEtaPolicy.h" +#include "WebbarEtaEvents.h" +#include "Lua/LuaFeatureDefs.h" +#include "Sim/Features/FeatureHandler.h" + +class WebbarNativeEtaReader; +class WebbarNativeEtaEvents final: public CEventClient +{ +public: + explicit WebbarNativeEtaEvents(WebbarNativeEtaReader* value): CEventClient("WebBAR original ETA events", LUA_HANDLE_ORDER_UI, false), reader(value) {} + bool GetFullRead() const override { return true; } + bool WantsEvent(const std::string& name) override { return name == "UnitCreated" || name == "UnitFinished" || name == "UnitDestroyed" || name == "UnitTaken" || name == "FeatureDestroyed"; } + void UnitCreated(const CUnit*, const CUnit*) override; + void UnitFinished(const CUnit*) override; + void UnitDestroyed(const CUnit*, const CUnit*, int) override; + void UnitTaken(const CUnit*, int, int) override; + void FeatureDestroyed(const CFeature*) override; +private: + WebbarNativeEtaReader* reader; +}; +static uint32_t webbarNativeEtaEpoch = 0; +static uint32_t NextWebbarNativeEtaEpoch() { if (++webbarNativeEtaEpoch == 0) ++webbarNativeEtaEpoch; return webbarNativeEtaEpoch; } + +// A separate private native VM keeps an optional ETA failure isolated from the +// already qualified healthbar VM. Only admitted native reads are installed. +class WebbarNativeEtaReader final: public CLuaHandle +{ +public: + bool ready = false; + uint32_t epoch = 0; + std::array view{-2,-2,-2,-2,-2}; + WebbarNativeEtaEvents events; + WebbarNativeEtaReader(): CLuaHandle("WebBAR original ETA policy", LUA_HANDLE_ORDER_UI, false, false), events(this) + { + SetFullCtrl(false); SetCtrlTeam(NoAccessTeam); SetSelectTeam(NoAccessTeam); EnsureView(); + 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, "FeatureDefs", LuaFeatureDefs::PushEntries); + if (ready) { + lua_getglobal(L, "Spring"); + #define ETA_READ(name, method) lua_pushcfunction(L, LuaUnsyncedRead::method); lua_setfield(L, -2, name) + ETA_READ("GetMyPlayerID", GetLocalPlayerID); + ETA_READ("GetMyTeamID", GetLocalTeamID); + ETA_READ("GetMyAllyTeamID", GetLocalAllyTeamID); + ETA_READ("GetSpectatingState", GetSpectatingState); + #undef ETA_READ + } + lua_settop(L, 0); + if (ready) ready = LoadCode(L, WEBBAR_ETA_POLICY, "Original BAR ETA and feature forwarding"); + if (ready) Call("WebbarEtaInitialize"); + if (ready) { + WebbarEtaEvents::Attach(this, [](void* self, lua_State* source, int args) { static_cast(self)->Sync(source, args); }); + eventHandler.AddClient(this); eventHandler.AddClient(&events); + } else LOG_L(L_ERROR, "[WebBAR] original ETA initialization failed"); + } + ~WebbarNativeEtaReader() override { WebbarEtaEvents::Detach(this); eventHandler.RemoveClient(&events); KillLua(); } + bool WantsEvent(const std::string& name) override { return ready && name == "CollectGarbage"; } + void Call(const char* name, std::initializer_list args = {}) + { + if (!ready) return; + const int top = lua_gettop(L); lua_getglobal(L, name); + for (const int value: args) lua_pushnumber(L, value); + ready = RunCallIn(L, LuaHashString(name), args.size(), 0); lua_settop(L, top); + } + void EnsureView() + { + const std::array actual{gu->myPlayerNum,gu->myTeam,gu->myAllyTeam,int(gu->spectating),int(gu->spectatingFullView)}; + if (view == actual) return; + view = actual; epoch = NextWebbarNativeEtaEpoch(); + SetFullRead(gu->spectatingFullView); SetReadTeam(gu->spectatingFullView ? AllAccessTeam : gu->myTeam); + SetReadAllyTeam(gu->spectatingFullView ? AllAccessTeam : gu->myAllyTeam); + // Keep the original forwarder's private team cache across perspective changes. + if (ready) Call("PlayerChanged", {gu->myPlayerNum}); + } + void Event(const char* name, std::initializer_list args) { EnsureView(); Call(name, args); } + void Sync(lua_State* source, int args) + { + EnsureView(); if (!ready) return; + const int top = lua_gettop(L); lua_getglobal(L, "WebbarEtaSync"); lua_pushstring(L, lua_tostring(source, 1)); + for (int i = 2; i <= args; ++i) lua_pushnumber(L, lua_tonumber(source, i)); + ready = RunCallIn(L, LuaHashString("WebbarEtaSync"), args, 0); lua_settop(L, top); + } + void Tick() { EnsureView(); Call("WebbarEtaTick"); } + bool State(std::vector& packet, float offset) + { + if (!ready) return false; + const int top = lua_gettop(L); lua_getglobal(L, "WebbarEtaState"); + bool ok = RunCallIn(L, LuaHashString("WebbarEtaState"), 0, 1) && lua_istable(L, -1); + const auto integer = [&](const char* name, uint32_t limit, uint32_t& result) { + lua_getfield(L, -1, name); const double value = lua_tonumber(L, -1); + const bool valid = lua_type(L, -1) == LUA_TNUMBER && std::isfinite(value) && value >= 0 && value <= limit && std::floor(value) == value; + result = valid ? uint32_t(value) : 0; lua_pop(L, 1); return valid; + }; + if (ok) ok = integer("unitCount",8192,packet[9]) && integer("featureCount",8192,packet[10]); + if (ok) { + lua_getfield(L, -1, "rows"); ok = lua_istable(L, -1) && lua_objlen(L, -1) <= 16384; + const int rows = lua_gettop(L), count = ok ? lua_objlen(L, rows) : 0; + for (int i = 1; ok && i <= count; ++i) { + lua_rawgeti(L, rows, i); if (!lua_istable(L, -1)) { ok = false; break; } + std::array row{}; + ok = integer("id",65535,row[0]) && integer("kind",1,row[1]); + lua_getfield(L,-1,"unknown"); ok = ok && lua_type(L,-1) == LUA_TBOOLEAN; row[3] = lua_toboolean(L,-1) ? 1 : 0; lua_pop(L,1); + for (const auto& field: {std::pair{"yoffset",4},std::pair{"timeLeft",5}}) { + lua_getfield(L,-1,field.first); const bool unknown = field.second == 5 && row[3]; + const float value = unknown ? 0.0f : lua_tonumber(L,-1); + ok = ok && (unknown ? lua_isnil(L,-1) : lua_type(L,-1) == LUA_TNUMBER) && std::isfinite(value); + if (field.second == 4) ok = ok && value >= 0 && value < 1e7; + std::memcpy(&row[field.second],&value,4); lua_pop(L,1); + } + const CUnit* unit = ok && row[1] == 0 ? unitHandler.GetUnit(row[0]) : nullptr; + const CFeature* feature = ok && row[1] == 1 ? featureHandler.GetFeature(row[0]) : nullptr; + const bool admitted = unit ? (!unit->isDead && (gu->spectatingFullView || unit->allyteam == gu->myAllyTeam)) : feature && (gu->spectatingFullView || (teamHandler.IsValidAllyTeam(gu->myAllyTeam) && feature->IsInLosForAllyTeam(gu->myAllyTeam))); + if (ok && admitted) { + float3 position; + if (unit) { + const CUnit* transport = unit->GetTransporter(); + position = transport ? unit->GetDrawPosOther(transport->preFrameTra.t,transport->pos,offset) : unit->GetDrawPos(offset); + row[2] = uint32_t(unit->creationFrame); + } else position = feature->pos; + for (int j = 0; j < 3; ++j) { const float value = position[j]; ok = ok && std::isfinite(value); std::memcpy(&row[6+j],&value,4); } + if (ok) { packet.insert(packet.end(),row.begin(),row.end()); ++packet[7]; } + } + lua_pop(L,1); + } + } + lua_settop(L,top); if (!ok) ready = false; return ok; + } +}; +inline void WebbarNativeEtaEvents::UnitCreated(const CUnit* unit,const CUnit*) +{ + if (unit && (gu->spectatingFullView || unit->allyteam == gu->myAllyTeam)) reader->Event("UnitCreated",{unit->id,unit->unitDef->id,unit->team}); +} +inline void WebbarNativeEtaEvents::UnitFinished(const CUnit* unit) +{ + if (unit && (gu->spectatingFullView || unit->allyteam == gu->myAllyTeam)) reader->Event("UnitFinished",{unit->id,unit->unitDef->id,unit->team}); +} +inline void WebbarNativeEtaEvents::UnitDestroyed(const CUnit* unit,const CUnit*,int) +{ + if (unit && (gu->spectatingFullView || unit->allyteam == gu->myAllyTeam)) reader->Event("UnitDestroyed",{unit->id,unit->unitDef->id,unit->team}); +} +inline void WebbarNativeEtaEvents::UnitTaken(const CUnit* unit,int oldTeam,int newTeam) +{ + if (unit && (gu->spectatingFullView || teamHandler.AllyTeam(oldTeam) == gu->myAllyTeam || teamHandler.AllyTeam(newTeam) == gu->myAllyTeam)) reader->Event("UnitTaken",{unit->id,unit->unitDef->id,oldTeam,newTeam}); +} +inline void WebbarNativeEtaEvents::FeatureDestroyed(const CFeature* feature) +{ + // Original widget forwarding removes feature keys regardless of LOS. This + // callback only deletes private state; no hidden identity leaves this handle. + if (feature) reader->Event("FeatureDestroyed",{feature->id,feature->allyteam}); +} +namespace WebbarNativeEta { +inline WebbarNativeEtaReader* reader = nullptr; +inline int lastFrame = -1; +inline bool Enabled() { return std::getenv("WEBBAR_NATIVE_BUILD_ETA") && std::getenv("WEBBAR_BROWSER") && !std::getenv("WEBBAR_NETWORK"); } +inline void Free() { delete reader; reader = nullptr; lastFrame = -1; } +inline void Prepare() +{ + if (!Enabled() || gs->frameNum < -1) return; + if (gs->frameNum < lastFrame) Free(); + lastFrame = gs->frameNum; + if (!reader) reader = new WebbarNativeEtaReader; + else reader->EnsureView(); +} +inline void Tick() { Prepare(); if (reader) reader->Tick(); } +inline void Publish(float offset, int32_t sequence, uint32_t drawEpoch) +{ + Prepare(); if (!reader || !std::isfinite(offset) || sequence <= 0 || (sequence & 1) || !drawEpoch) return; + reader->Tick(); + std::vector packet{0x31455357u,uint32_t(gs->frameNum),reader->epoch,uint32_t(gu->myPlayerNum),uint32_t(gu->myTeam),uint32_t(gu->myAllyTeam),uint32_t(gu->spectating)|(uint32_t(gu->spectatingFullView)<<1),0,uint32_t(sequence),0,0,0,drawEpoch,0,0,0}; + std::memcpy(&packet[11],&offset,4); + if (!reader->State(packet,offset)) { packet.resize(16); packet[7] = packet[9] = packet[10] = 0; packet[6] |= 4; } + MAIN_THREAD_EM_ASM({ if (Module['webbarNativeBuildEta']) Module['webbarNativeBuildEta'](HEAPU8.slice($0,$0+$1).buffer); },packet.data(),packet.size()*4); +} +} +static void PrepareWebbarNativeEta() { WebbarNativeEta::Prepare(); } +static void FreeWebbarNativeEta() { WebbarNativeEta::Free(); } +static void PublishWebbarNativeEtaDraw(float offset,int32_t sequence,uint32_t drawEpoch) { WebbarNativeEta::Publish(offset,sequence,drawEpoch); } --- /dev/null +++ b/rts/Game/WebbarNativeEtaPolicy.h @@ -0,0 +1,611 @@ +/* Original BAR GPL v2 or later ETA policy; generated by scripts/native-build-eta-engine.mjs. */ +#pragma once +static constexpr const char* WEBBAR_ETA_POLICY=R"WEBBAR_ETA( +local translations={["ui.buildEstimate.time"]="ETA",["ui.buildEstimate.cancelled"]="Decaying"} +-- Private read-only native policy. No commands, configuration writes or GL. +-- The original widget's screen drawing is not invoked in this handle. +-- SPDX-License-Identifier: GPL-2.0-or-later +local nativeUnitDefs,nativeFeatureDefs=UnitDefs,FeatureDefs +local function noop()end +Spring.GetViewGeometry=function()return 1280,720 end +Spring.I18N=function(key)return assert(translations[key],'Missing original ETA translation')end +WG={fonts={getFont=function()return{}end}} +gl={Color=noop,PushMatrix=noop,PopMatrix=noop,Translate=noop,Scale=noop} +widgetHandler={RegisterGlobal=noop,DeregisterGlobal=noop} +local listeners,actions={},{} +Script.LuaUI=setmetatable({},{__call=function(_,name)return listeners[name]~=nil end,__index=function(_,name)return function(...)return assert(listeners[name],'Unbound original ETA callback')(...)end end}) +gadgetHandler={IsSyncedCode=function()return false end,AddSyncAction=function(_,name,fn)assert(not actions[name]);actions[name]=fn end,RemoveSyncAction=function(_,name)actions[name]=nil end} + +local eta=(function() +local UnitDefs,FeatureDefs={},{} +local widget={} +local widget = widget ---@type Widget + +function widget:GetInfo() + return { + name = "BuildETA", + desc = "Displays estimated time of arrival for builds", + author = "trepan (modified by jK)", + date = "2007", + license = "GNU GPL, v2 or later", + layer = -90, + enabled = true + } +end + +local lastGameUpdate = Spring.GetGameSeconds() + +local spGetUnitViewPosition = Spring.GetUnitViewPosition +local spGetGameSeconds = Spring.GetGameSeconds +local spGetGameFrame = Spring.GetGameFrame +local spGetUnitIsBeingBuilt = Spring.GetUnitIsBeingBuilt +local spGetCameraPosition = Spring.GetCameraPosition +local spWorldToScreenCoords = Spring.WorldToScreenCoords +local spGetViewGeometry = Spring.GetViewGeometry +local spGetUnitAllyTeam = Spring.GetUnitAllyTeam +local spGetSpectatingState = Spring.GetSpectatingState +local spGetFeatureResources = Spring.GetFeatureResources +local spGetFeatureHealth = Spring.GetFeatureHealth +local spGetFeatureDefID = Spring.GetFeatureDefID +local spGetFeaturePosition = Spring.GetFeaturePosition +local spec, fullview = spGetSpectatingState() +local myAllyTeam = Spring.GetMyAllyTeamID() + +local glColor = gl.Color +local glPushMatrix = gl.PushMatrix +local glPopMatrix = gl.PopMatrix +local glTranslate = gl.Translate +local glScale = gl.Scale + +local font +local vsx, vsy = spGetViewGeometry() + +local unitETATable = {} +local featureETATable = {} +-- Distance thresholds in world units (elmos). Camera height is roughly the main dial. +-- At ETA_DIST_FULL the text is fully visible at max font size. +-- Between ETA_DIST_FULL and ETA_DIST_FADE the text fades out linearly. +-- Beyond ETA_DIST_FADE the text is invisible. +local ETA_DIST_FULL = 500 -- fully opaque + largest font below this distance +local ETA_DIST_FADE = 1000 -- completely transparent / hidden beyond this distance +local ETA_FONT_CLOSE = 44 -- font size (px) when closer than ETA_DIST_FULL +local ETA_FONT_FAR = 11 -- font size (px) when at ETA_DIST_FADE +local ETA_SCREEN_OFFSET_Y = -35 -- pixels below the projected world position (negative = down on screen) +local blinkTime = 20 +local minETASecs = 5 -- Don't show ETA if it is less than 5 seconds + +-- Pre-cache I18N strings to avoid per-unit per-frame lookups +local i18n_buildTime = "\255\255\255\1" .. Spring.I18N('ui.buildEstimate.time') .. "\255\255\255\255 " +local i18n_cancelled = Spring.I18N('ui.buildEstimate.cancelled') .. " " + +local unitHeight = {} +for udid, unitDef in pairs(UnitDefs) do + unitHeight[udid] = unitDef.height +end +local featureHeight = {} +for featureDefID, featureDef in pairs(FeatureDefs) do + featureHeight[featureDefID] = featureDef.height +end + + +function widget:ViewResize() + vsx, vsy = spGetViewGeometry() + font = WG['fonts'].getFont(nil, 1.2, 0.2, 20) +end + +local function makeUnitETA(unitID, unitDefID) + if unitDefID == nil then + return nil + end + local isBuilding, buildProgress = spGetUnitIsBeingBuilt(unitID) + if not isBuilding then + return nil + end + + local alreadyStarted = buildProgress > 0.001 + return { + firstSet = not alreadyStarted, + lastTime = spGetGameSeconds(), + lastProg = buildProgress, + rate = nil, + timeLeft = nil, + display = alreadyStarted or nil, -- show immediately for existing units (will show ??? until rate is known) + yoffset = unitHeight[unitDefID] + 14 + } +end + +local function makeFeatureETA(featureID, featureDefID) + if featureDefID == nil then + return nil + end + local progress + progress = select(5, spGetFeatureResources(featureID)) + if progress == 1 then + progress = select(3, spGetFeatureHealth(featureID)) + end + + return { + firstSet = true, + lastTime = spGetGameSeconds(), + lastProg = progress, + rate = nil, + timeLeft = nil, + yoffset = featureHeight[featureDefID] + 14 + } +end + +local function init() + unitETATable = {} + local units = Spring.GetAllUnits() + for i=1, #units do + local unitID = units[i] + if fullview or spGetUnitAllyTeam(unitID) == myAllyTeam then + unitETATable[unitID] = makeUnitETA(unitID, Spring.GetUnitDefID(unitID)) + end + end +end +-- step is negative for reclaim, positive for resurrect, zero for stop +-- only called for features that my ally team is reclaiming or resurrecting or all if I am spectator +local function featureReclaimStartedETA(featureID, step) + if step == 0 then + featureETATable[featureID] = nil + else + featureETATable[featureID] = makeFeatureETA(featureID, spGetFeatureDefID(featureID)) + end +end + +function widget:FeatureReclaimStartedETA(featureID, step) + featureReclaimStartedETA(featureID, step) +end + +function widget:Initialize() + widget:ViewResize() + init() +end + +function widget:LanguageChanged() + i18n_buildTime = "\255\255\255\1" .. Spring.I18N('ui.buildEstimate.time') .. "\255\255\255\255 " + i18n_cancelled = Spring.I18N('ui.buildEstimate.cancelled') .. " " +end + +local function updateEta(eta, newProgress, gameSeconds, abs) + local dp = newProgress - eta.lastProg + local dt = gameSeconds - eta.lastTime + if dt > 2 then + eta.firstSet = true + eta.rate = nil + eta.timeLeft = nil + end + + local rate = dp / dt + + if rate ~= 0 then + if eta.firstSet then + if (newProgress > 0.001) then + eta.firstSet = false + end + else + local rf = 0.5 + if eta.rate == nil then + eta.rate = rate + else + eta.rate = ((1 - rf) * eta.rate) + (rf * rate) + end + + local tf = 0.1 + if rate > 0 then + local newTime = (1 - newProgress) / rate + if eta.timeLeft and eta.timeLeft > 0 then + eta.timeLeft = ((1 - tf) * eta.timeLeft) + (tf * newTime) + else + eta.timeLeft = newTime + end + elseif rate < 0 then + local newTime + if eta.timeLeft and eta.timeLeft < 0 then + newTime = newProgress / eta.rate -- use smooth rate. we don't need to smoothen the time if the rate is smooth + else + newTime = newProgress / rate + end + if abs then newTime = math.abs(newTime) end + eta.timeLeft = newTime + end + + if eta.display == nil and eta.timeLeft and eta.timeLeft < minETASecs then + eta.display = false + elseif eta.timeLeft and eta.timeLeft >= minETASecs then + eta.display = true + end + end + eta.lastTime = gameSeconds + eta.lastProg = newProgress + end +end + +function widget:Update(dt) + + local gs = spGetGameSeconds() + if gs == lastGameUpdate then + return + end + lastGameUpdate = gs + + for unitID, eta in pairs(unitETATable) do + local isBuilding, buildProgress = spGetUnitIsBeingBuilt(unitID) + if not isBuilding then + unitETATable[unitID] = nil + else + updateEta(eta, buildProgress, gs) + end + end + + for featureID, eta in pairs(featureETATable) do + local progress + progress = select(5, spGetFeatureResources(featureID)) + if progress == 1 then + progress = select(3, spGetFeatureHealth(featureID)) + end + updateEta(eta, progress, gs, true) + end + +end + +function widget:PlayerChanged() + if myAllyTeam ~= Spring.GetMyAllyTeamID() or fullview ~= select(2, spGetSpectatingState()) then + myAllyTeam = Spring.GetMyAllyTeamID() + spec, fullview = spGetSpectatingState() + init() + end +end + +function widget:UnitCreated(unitID, unitDefID, unitTeam) + if fullview or spGetUnitAllyTeam(unitID) == myAllyTeam then + unitETATable[unitID] = makeUnitETA(unitID, unitDefID) + end +end + +function widget:UnitDestroyed(unitID, unitDefID, unitTeam, attackerID, attackerDefID, attackerTeam, weaponDefID) + unitETATable[unitID] = nil +end + +function widget:UnitTaken(unitID, unitDefID, unitTeam, newTeam) + unitETATable[unitID] = nil +end + +function widget:UnitFinished(unitID, unitDefID, unitTeam) + unitETATable[unitID] = nil +end + +function widget:FeatureDestroyed(featureID, allyTeamID) + featureETATable[featureID] = nil +end + +local function drawEtaText(timeLeft, alpha, fontSize) + local etaText + local etaPrefix = i18n_buildTime + if timeLeft == nil then + etaText = etaPrefix .. "\255\1\1\255???" + else + local canceled = timeLeft<0 + etaPrefix = (not canceled and etaPrefix) or (((spGetGameFrame()%blinkTime>=blinkTime/2) and "\255\255\255\255" or"\255\255\1\1")..i18n_cancelled) + timeLeft = math.abs(timeLeft) + local minutes = timeLeft / 60 + local seconds = timeLeft % 60 + etaText = etaPrefix .. string.format((not canceled and "\255\1\255\1" or "") .. "%02d:%02d", minutes, seconds) + end + + glColor(1, 1, 1, alpha) + font:Begin() + font:Print(etaText, 0, 0, fontSize, "co") + font:End() + glColor(1, 1, 1, 1) +end + + + +function widget:DrawScreenEffects() + if Spring.IsGUIHidden() then return end + + local cx, cy, cz = spGetCameraPosition() + + for unitID, eta in pairs(unitETATable) do + if eta.display then + local ux, uy, uz = spGetUnitViewPosition(unitID) + if ux ~= nil then + local dx, dy, dz = ux - cx, uy - cy, uz - cz + local dist = math.sqrt(dx*dx + dy*dy + dz*dz) + if dist < ETA_DIST_FADE then + local alpha, fontSize + if dist <= ETA_DIST_FULL then + alpha = 1.0 + fontSize = ETA_FONT_CLOSE + else + local t = (dist - ETA_DIST_FULL) / (ETA_DIST_FADE - ETA_DIST_FULL) + alpha = 1.0 - t + fontSize = ETA_FONT_CLOSE + t * (ETA_FONT_FAR - ETA_FONT_CLOSE) + end + local sx, sy = spWorldToScreenCoords(ux, uy + eta.yoffset, uz) + if sx and sy and sx > -200 and sx < vsx + 200 and sy > -50 and sy < vsy + 50 then + glPushMatrix() + glTranslate(sx, sy + ETA_SCREEN_OFFSET_Y, 0) + drawEtaText(eta.timeLeft, alpha, fontSize) + glPopMatrix() + end + end + end + end + end + + for featureID, eta in pairs(featureETATable) do + if eta.display then + local fx, fy, fz = spGetFeaturePosition(featureID) + if fx ~= nil then + local dx, dy, dz = fx - cx, fy - cy, fz - cz + local dist = math.sqrt(dx*dx + dy*dy + dz*dz) + if dist < ETA_DIST_FADE then + local alpha, fontSize + if dist <= ETA_DIST_FULL then + alpha = 1.0 + fontSize = ETA_FONT_CLOSE + else + local t = (dist - ETA_DIST_FULL) / (ETA_DIST_FADE - ETA_DIST_FULL) + alpha = 1.0 - t + fontSize = ETA_FONT_CLOSE + t * (ETA_FONT_FAR - ETA_FONT_CLOSE) + end + local sx, sy = spWorldToScreenCoords(fx, fy + eta.yoffset, fz) + if sx and sy and sx > -200 and sx < vsx + 200 and sy > -50 and sy < vsy + 50 then + glPushMatrix() + glTranslate(sx, sy + ETA_SCREEN_OFFSET_Y, 0) + drawEtaText(eta.timeLeft, alpha, fontSize) + glPopMatrix() + end + end + end + end + end +end + +return{widget=widget,units=function()return unitETATable end,features=function()return featureETATable end,unitHeight=unitHeight,featureHeight=featureHeight} +end)() + +local forward=(function() +local gadget={} +local gadget = gadget ---@type Gadget + +function gadget:GetInfo() + return { + name = "Feature ETA Widget Forwarding", + desc = "Notifies widgets that a feature reclaim or resurrect action has begun", + author = "Saul Goodman, copied from Beherith", -- ty Sprung + date = "March 2026", + license = "GNU GPL, v2 or later", + layer = -1, + enabled = true + } +end + + +if gadgetHandler:IsSyncedCode() then + + local SendToUnsynced = SendToUnsynced + local spGetGameFrame = Spring.GetGameFrame + local fps = Game.gameSpeed + local dayFrames = fps * 24 * 60 * 60 + local noProgressTimeout = 5 * fps -- ETAs will disappear after this many frames without progress + -- Cached teamID to its allyTeamID + local teamToAllyTeam = {} + + -- Map of featureID to map of allyTeamID to frame of last build step + local forwardedFeatures = {} -- so we only forward the start event once + -- Map of featureID to most recent build step frame for any ally team + local featureLastStepTime = {} -- used to remove ETA's for ally teams that are no longer working on a feature + + function gadget:AllowFeatureBuildStep(builderID, builderTeamID, featureID, featureDefID, step) + + local currentDayFrames, days = spGetGameFrame() + local currentFrame = currentDayFrames + (days * dayFrames) + local builderAllyTeamID = teamToAllyTeam[builderTeamID] + + local lastStepFrames = forwardedFeatures[featureID] + if lastStepFrames == nil then + lastStepFrames = {} + forwardedFeatures[featureID] = lastStepFrames + end + + if lastStepFrames[builderAllyTeamID] == nil then + SendToUnsynced("etaFeatureReclaimStartFrame", featureID, builderAllyTeamID, step) + end + lastStepFrames[builderAllyTeamID] = currentFrame + featureLastStepTime[featureID] = currentFrame + + return true + end + + local updateInterval = 6 + local updateCounter = updateInterval + function gadget:GameFrame(frame) + if updateCounter > 1 then + updateCounter = updateCounter - 1 + return + end + updateCounter = updateInterval + + --Check if there are any ally teams that are no longer reclaiming or resurrecting a feature and + --send a stop signal + --There may be two ally teams reclaiming the same feature and we want to remove the ETA when an + --ally team stops reclaiming + for featureID, allyTeamFrames in pairs(forwardedFeatures) do + local mostRecentStepFrame = featureLastStepTime[featureID] + local stopAllETAs = frame - mostRecentStepFrame >= noProgressTimeout --No progress for any team => remove ETA for all teams + for allyTeamID, lastStepFrame in pairs(allyTeamFrames) do + if stopAllETAs or lastStepFrame < mostRecentStepFrame then + SendToUnsynced("etaFeatureReclaimStartFrame", featureID, allyTeamID, 0) + allyTeamFrames[allyTeamID] = nil + end + end + end + + end + + function gadget:FeatureDestroyed(featureID, allyTeamID) + forwardedFeatures[featureID] = nil + end + + function gadget:Initialize() + for _, allyTeamID in ipairs(Spring.GetAllyTeamList()) do + for _, teamID in ipairs(Spring.GetTeamList(allyTeamID)) do + teamToAllyTeam[teamID] = allyTeamID + end + end + end + +else + + local spGetMyAllyTeamID = Spring.GetMyAllyTeamID + local spGetSpectatingState = Spring.GetSpectatingState + + local myPlayerID = Spring.GetMyPlayerID() + local myAllyTeamID = spGetMyAllyTeamID() + local _, fullview = spGetSpectatingState() + + --Map of allyTeamID to set of featureIDs. Used to resend ETAs when player changes ally team + local featureETATeamCache = {} + + local function getFeatureEtaLuaUI() + local luaUI = Script.LuaUI + if luaUI("FeatureReclaimStartedETA") then + return luaUI.FeatureReclaimStartedETA + end + end + + local function resendAllFeatureETAs() + local featureReclaimStartedETA = getFeatureEtaLuaUI() + if not featureReclaimStartedETA then + return + end + + local myAllyTeamCache = featureETATeamCache[myAllyTeamID] + for _, featureIDs in pairs(featureETATeamCache) do + for featureID, _ in pairs(featureIDs) do + local step = (fullview or (myAllyTeamCache and myAllyTeamCache[featureID])) and 0.001 or 0 + featureReclaimStartedETA(featureID, step) + end + end + end + + local function resendChangedAllyTeamFeatureETAs(prevAllyTeamID) + local featureReclaimStartedETA = getFeatureEtaLuaUI() + if not featureReclaimStartedETA then + return + end + + local prevAllyTeamCache = featureETATeamCache[prevAllyTeamID] + local myAllyTeamCache = featureETATeamCache[myAllyTeamID] + if prevAllyTeamCache then + for featureID, _ in pairs(prevAllyTeamCache) do + if not (myAllyTeamCache and myAllyTeamCache[featureID]) then + featureReclaimStartedETA(featureID, 0) + end + end + end + if myAllyTeamCache then + for featureID, _ in pairs(myAllyTeamCache) do + if not (prevAllyTeamCache and prevAllyTeamCache[featureID]) then + featureReclaimStartedETA(featureID, 0.001) + end + end + end + end + + function gadget:PlayerChanged(playerID) + if playerID == myPlayerID then + local prevAllyTeamID = myAllyTeamID + local prevFullview = fullview + myAllyTeamID = spGetMyAllyTeamID() + _, fullview = spGetSpectatingState() + + if prevFullview == fullview and (fullview or prevAllyTeamID == myAllyTeamID) then + return + end + + if prevFullview ~= fullview then + resendAllFeatureETAs() + else + resendChangedAllyTeamFeatureETAs(prevAllyTeamID) + end + end + end + + local function etaFeatureReclaimStartFrame(cmd, featureID, allyTeamID, step) + if (fullview or allyTeamID == myAllyTeamID) and Script.LuaUI("FeatureReclaimStartedETA") then + Script.LuaUI.FeatureReclaimStartedETA(featureID, step) + end + featureETATeamCache[allyTeamID][featureID] = step ~= 0 and true or nil + end + + function gadget:Initialize() + for _, allyTeamID in ipairs(Spring.GetAllyTeamList()) do + featureETATeamCache[allyTeamID] = {} + end + gadgetHandler:AddSyncAction("etaFeatureReclaimStartFrame", etaFeatureReclaimStartFrame) + end + + function gadget:ShutDown() + gadgetHandler:RemoveSyncAction("etaFeatureReclaimStartFrame") + end +end + +return gadget +end)() +-- Preserve native height values while loading only already instantiated types. +-- Eager iteration of all UnitDefs.height would load every game model in WASM. +-- The original widget body and its per-definition immutable cache are retained. +-- SPDX-License-Identifier: GPL-2.0-or-later +local function heights(target,definitions) + setmetatable(target,{__index=function(cache,id) + local value=assert(definitions[id],'Missing native ETA definition').height + assert(type(value)=='number'and value==value and value>=0 and value<1e7,'Invalid native ETA model height') + rawset(cache,id,value);return value + end}) +end +heights(eta.unitHeight,nativeUnitDefs);heights(eta.featureHeight,nativeFeatureDefs) +listeners.FeatureReclaimStartedETA=function(...)return eta.widget:FeatureReclaimStartedETA(...)end +for _,name in ipairs({'UnitCreated','UnitFinished','UnitDestroyed','UnitTaken','FeatureDestroyed'})do + _G[name]=function(...)return eta.widget[name](eta.widget,...)end +end +function PlayerChanged(player) + -- Original unsynced gadget forwarding precedes LuaUI's player callback. + forward:PlayerChanged(player);eta.widget:PlayerChanged(player) +end +function WebbarEtaInitialize() + eta.widget:Initialize();forward:Initialize();return true +end +function WebbarEtaSync(name,...) + if name~='etaFeatureReclaimStartFrame'then return false end + assert(select('#',...)==3,'Invalid native ETA sync action') + assert(actions[name],'Original ETA forwarding unavailable')(name,...);return true +end +local lastTick=-1 +function WebbarEtaTick() + local frame=Spring.GetGameFrame();assert(frame>=lastTick,'Native ETA policy rewound; replace its handle') + if frame~=lastTick then eta.widget:Update(0);lastTick=frame end +end +function WebbarEtaState() + local rows,unitCount,featureCount={},0,0 + -- Preserve original pairs order: label outlines/glyphs can overlap. + for kind,values in ipairs({eta.units(),eta.features()})do + for id,value in pairs(values)do + if kind==1 then unitCount=unitCount+1 else featureCount=featureCount+1 end + if value.display then + assert(type(id)=='number'and id>=0 and id<=65535 and id%1==0) + assert(type(value.yoffset)=='number'and value.yoffset==value.yoffset and value.yoffset>=0 and value.yoffset<1e7) + assert(value.timeLeft==nil or(type(value.timeLeft)=='number'and value.timeLeft==value.timeLeft and math.abs(value.timeLeft)<1e12)) + rows[#rows+1]={id=id,kind=kind-1,yoffset=value.yoffset,timeLeft=value.timeLeft,unknown=value.timeLeft==nil} + end + end + end + assert(unitCount<=8192 and featureCount<=8192 and #rows<=16384,'Native ETA policy exceeds budget') + return{frame=Spring.GetGameFrame(),rows=rows,unitCount=unitCount,featureCount=featureCount} +end + +)WEBBAR_ETA"; --- /dev/null +++ b/rts/Game/WebbarNativeHealthbarPolicy.h @@ -0,0 +1,7561 @@ +/* Original BAR GPL v2 or later healthbar policy; generated by scripts/native-healthbars.mjs. */ +#pragma once +static constexpr const char* WEBBAR_HEALTHBAR_POLICY=R"WEBBAR_BARS( +--[[ +IMPORTANT NOTICE: Tests for these functions are provided via +`common/tableFunctionsTests.lua`, but the tests do not run unless you uncomment +them in `init.lua` (because they're not free to run, so we don't want them to +run for end users.) +]] + +-- Lua 5.1 backwards compatibility +table.pack = table.pack or function(...) return { n = select("#", ...), ... } end + +if not table.copy then + function table.copy(tbl) + local copy = {} + for key, value in pairs(tbl) do + if type(value) == "table" then + copy[key] = table.copy(value) + else + copy[key] = value + end + end + return copy + end +end + +if not table.merge then + ---Return a new table of values from mergeData recursively merged into + ---mergeTarget, using deep copies. When there is a conflict, values in + ---mergeData take precedence. + ---@param mergeTarget table + ---@param mergeData table + ---@return table + function table.merge(mergeTarget, mergeData) + local new = table.copy(mergeTarget) + for key, value in pairs(mergeData) do + -- key not used in default, assign it the value at same key in override + if not new[key] and type(value) == "table" then + new[key] = table.copy(value) + -- values at key in both default and override are tables, merge those + elseif type(new[key]) == "table" and type(value) == "table" then + new[key] = table.merge(new[key], value) + else + new[key] = value + end + end + return new + end +end + +if not table.mergeInPlace then + ---Recursively in-place merge values from mergeData into mergeTarget. When + ---there is a conflict, values in mergeData take precedence. + ---@param mergeTarget table + ---@param mergeData table + ---@param deep? boolean if true, deep copy tables coming from mergeData (default: false) + ---@return table mergeTarget + function table.mergeInPlace(mergeTarget, mergeData, deep) + deep = deep or false + for key, value in pairs(mergeData) do + if type(value) == 'table' and type(mergeTarget[key] or false) == 'table' then + table.mergeInPlace(mergeTarget[key], value, deep) + elseif type(value) == "table" and deep then + mergeTarget[key] = table.copy(value) + else + mergeTarget[key] = value + end + end + return mergeTarget + end +end + +if not table.sortStable then + local function compareDefault(a, b) + return a < b + end + + ---Sorts list elements in a given order, *in-place*, from `list[1]` to `list[#list]`. + ---This method preserves elements' original order when possible, unlike `table.sort`. + ---@generic T + ---@param tbl T[] + ---@param compare fun(a: T, b: T) : boolean|nil where true := less than, false := greater than, nil := equal to + table.sortStable = function(tbl, compare) + if not compare then + compare = compareDefault + end + local index = table.getKeyOf -- local speedup + table.sort(tbl, function(a, b) + local comparison = compare(a, b) + return comparison or (comparison == nil and index(tbl, a) < index(tbl, b)) + end) + end +end + +if not table.ensureTable then + ---Ensures a table exists at the specified key, creating one if needed. + ---@param tbl table + ---@param key any + ---@return table nested in tbl at key + function table.ensureTable(tbl, key) + local sub = tbl[key] + if sub == nil then + sub = {} + tbl[key] = sub + elseif type(sub) ~= "table" then + error("existing entry is not a table") + end + return sub + end +end + +if not table.toString then + local stringRep = string.rep + local tableSort = table.sort + local DEFAULT_INDENT_STEP = 2 + + local function tableToString(tbl, options, _seen, _depth) + end + + local function keyCmp(a, b) + local ta = type(a) + local tb = type(b) + + -- numbers always sort before other keys + -- compare pairs of numbers directly + -- for everything else, convert to string first + if ta == "number" and tb == "number" then + return a < b + elseif ta == "number" and tb ~= "number" then + return true + elseif tb == "number" and ta ~= "number" then + return false + else + return tableToString(a) < tableToString(b) + end + end + + local tableConcat = table.concat + + tableToString = function(tbl, options, _seen, _depth) + _seen = _seen or {} + _depth = _depth or 0 + + local inputType = type(tbl) + + if inputType == "string" then + return "\"" .. tbl .. "\"" + elseif inputType == "userdata" then + return tostring(tbl) or "" + elseif inputType ~= "table" then + return tostring(tbl) + end + + if _seen[tbl] then + return "" + end + + _seen[tbl] = true + + local keys = {} + local keyCount = 0 + for key in pairs(tbl) do + keyCount = keyCount + 1 + keys[keyCount] = key + end + tableSort(keys, (options and options.keyCmp) or keyCmp) + + local indent = (options and options.indent) or DEFAULT_INDENT_STEP + local pretty = options and options.pretty + + local parts = {} + local n = 0 + + n = n + 1; parts[n] = "{" + if keyCount > 0 and pretty then + n = n + 1; parts[n] = "\n" + end + for i = 1, keyCount do + local key = keys[i] + if pretty then + n = n + 1; parts[n] = stringRep(" ", (_depth + 1) * indent) + end + if key ~= i then + local keyType = type(key) + if keyType == "string" then + n = n + 1; parts[n] = key + n = n + 1; parts[n] = "=" + elseif keyType == "number" then + n = n + 1; parts[n] = "[" + n = n + 1; parts[n] = tostring(key) + n = n + 1; parts[n] = "]=" + else + n = n + 1; parts[n] = "[" + n = n + 1; parts[n] = tableToString(key, options, _seen) + n = n + 1; parts[n] = "]=" + end + end + n = n + 1; parts[n] = tableToString(tbl[key], options, _seen, _depth + 1) + if i < keyCount or pretty then + n = n + 1; parts[n] = "," + end + if pretty then + n = n + 1; parts[n] = "\n" + end + end + if keyCount > 0 and pretty then + n = n + 1; parts[n] = stringRep(" ", _depth * indent) + end + n = n + 1; parts[n] = "}" + + return tableConcat(parts) + end + + ---Recursively turns a table into a string, suitable for printing. + --- + ---All types of keys and values are valid. How some special types are handled: + --- * `function` types are turned into "" + --- * `userdata` types are turned into "", unless they have a `tostring` metamethod, which is used instead + --- * cyclic or recursive references are turned into "" + --- * keys that are not strings or numbers (tables, functions, etc) are first run through table.toString + --- + ---In order to keep the output deterministic, keys are sorted. + ---@param tbl table + ---@param options table Optional parameters + ---@param options.pretty boolean Whether to add newlines and indentation (default: false) + ---@param options.indent number If pretty=true, the number of spaces to indent by at each indent step (default: 2) + ---@param options.keyCmp function Custom comparison function for sorting keys. If provided, this function will be used instead of the default comparison based on `table.toString(key)`. + ---@return string + table.toString = tableToString +end + +if not table.invert then + function table.invert(tbl) + local inverted = {} + for key, value in pairs(tbl) do + inverted[value] = key + end + return inverted + end +end + +if not table.getUniqueArray then + local sort, floor = table.sort, math.floor + + local lookup = {} + local function sortLookup(a, b) + return lookup[a] < lookup[b] + end + + ---Produces a new table that contains no duplicate and/or non-sequence-able entries. + --- + ---Values with non-integer keys are _ignored_. Values with integer keys are _sorted_. + --- + ---The final/sorted array forms a compact sequence with no gaps so can have new keys. + ---@param tbl table may contain array, hash, or mixed data and can have gaps + ---@return table sequence containing only unique entries, ordered by their integer indices + function table.getUniqueArray(tbl) + local unique, count = {}, 0 + local invert = {} + + -- Iterate the hash part to pull hashed integer keys back into the array part. + for index, option in pairs(tbl) do + if type(index) == "number" and index >= 1 and index == floor(index) then + if not invert[option] then + count = count + 1 + unique[count] = option + invert[option] = index + elseif invert[option] > index then + invert[option] = index + end + end + end + + lookup = invert + sort(unique, sortLookup) + + return unique + end +end + +if not table.append then + function table.append(appendTarget, appendData) + local n = #appendTarget + for i = 1, #appendData do + n = n + 1 + appendTarget[n] = appendData[i] + end + end +end + +if not table.count then + ---Count the number of values in table. + ---Note that this always works, whereas the default length operator (#table) + ---only works if the table is a Lua sequence (i.e. indexes form a contiguous + ---sequence starting from 1). + ---@param tbl table + ---@return number + function table.count(tbl) + local count = 0 + for _ in pairs(tbl) do + count = count + 1 + end + return count + end +end + +if not table.isEmpty then + ---Check if the table is empty. + ---@param tbl table + ---@return boolean + function table.isEmpty(tbl) + return next(tbl) == nil + end +end + +if not table.isNilOrEmpty then + ---Check if the table is empty. + ---@param tbl table + ---@return number + function table.isNilOrEmpty(tbl) + return tbl == nil or table.isEmpty(tbl) + end +end + +if not table.getKeyOf then + ---Find key of value in table. + ---Will always return the first key found, no matter if the table contains + ---multiple instances of the value. + ---@generic K, V + ---@param tbl table + ---@param value V + ---@return K? # key if found, nil otherwise + function table.getKeyOf(tbl, value) + for key, v in pairs(tbl) do + if v == value then + return key + end + end + return nil + end +end + +if not table.contains then + ---Check if value is in table. + ---@generic V + ---@param tbl table + ---@param value V + ---@return boolean + function table.contains(tbl, value) + return table.getKeyOf(tbl, value) ~= nil + end +end + +if not table.keys then + ---Returns all keys of a table as an array, and the count of keys. + ---@generic K + ---@param tbl table + ---@return K[] keys + ---@return number count + function table.keys(tbl) + local keys, count = {}, 0 + for key in pairs(tbl) do + count = count + 1 + keys[count] = key + end + return keys, count + end +end + +if not table.removeIf then + ---Remove values in table if they match the given predicate. + ---@generic V + ---@param tbl table + ---@param predicate fun(value: V): boolean + function table.removeIf(tbl, predicate) + for key, value in pairs(tbl) do + if predicate(value) then + tbl[key] = nil + end + end + end +end + +if not table.removeAll then + ---Remove all instances of value in table. + ---@generic V + ---@param tbl table + ---@param value V + function table.removeAll(tbl, value) + table.removeIf(tbl, function(v) return v == value end) + end +end + +if not table.removeFirst then + ---Remove first instance of value in table. + ---If table is a Lua sequence (i.e. indexes form a contiguous sequence + ---starting from 1), it will use `table.remove` to keep the sequence + ---contiguous, otherwise it will `nil` the instance. + ---@generic V + ---@param tbl V[]|table + ---@param value V + ---@return boolean # true if a value was removed, false otherwise + function table.removeFirst(tbl, value) + -- first, try to handle the table as a proper Lua sequence + -- this will fail as soon as there's a gap (missing integer index), but if + -- the table is a sequence then we want to keep that property by using + -- `table.remove` to keep the sequence intact without any gaps + for index, v in ipairs(tbl) do + if v == value then + table.remove(tbl, index) + return true + end + end + + -- otherwise, try to handle the table normally and simply `nil` the value + local found = table.getKeyOf(tbl, value) + if found ~= nil then + tbl[found] = nil + return true + end + + return false + end +end + +if not table.shuffle then + ---Shuffle sequence using Knuth (Fisher–Yates) algorithm. + ---@param sequence any[] must be a Lua sequence (i.e. indexes form a contiguous sequence starting from 1), with the exception that we optionally allow starting from 0 + ---@param firstIndex? 0|1 first index in the sequence (optional, default: 1) + function table.shuffle(sequence, firstIndex) + firstIndex = firstIndex or 1 + for i = firstIndex, #sequence - 2 + firstIndex do + local j = math.random(i, #sequence) + sequence[i], sequence[j] = sequence[j], sequence[i] + end + end +end + +if not table.map then + --- Applies a function to all elements of a table and returns a new table with the results. + ---@generic K, V, RV, RK + ---@param tbl table The input table. + ---@param callback fun(value: V, key: K, tbl: table): RV, RK The function to apply to each element. It receives three arguments: the element's value, its key, and the original table. It should return the new value, and optionally, a new key. + ---@return table A new table containing the results of applying the callback to each element. + function table.map(tbl, callback) + local result = {} + for k, v in pairs(tbl) do + local mappedValue, mappedKey = callback(v, k, tbl) + if mappedKey ~= nil then + result[mappedKey] = mappedValue + else + result[k] = mappedValue + end + end + return result + end +end + +if not table.reduce then + --- Reduces a table to a single value by applying a function to each element in order. + ---@generic K, V, R + ---@param tbl table The input table. + ---@param callback fun(acc: R, value: V, key: K, tbl: table): R The function to apply to each element. It receives four arguments: the accumulator, the element's value, its key, and the original table. + ---@param initial R The initial value of the accumulator. If no value is specified, the first callback will receive nil as the accumulator value. + ---@return R The final value of the accumulator after applying the callback to all elements. + function table.reduce(tbl, callback, initial) + local accumulator = initial + + for k, v in pairs(tbl) do + accumulator = callback(accumulator, v, k, tbl) + end + + return accumulator + end +end + +if not table.filterArray then + --- Creates a new (array-style) table containing only the elements that satisfy a given condition. + ---@generic V + ---@param tbl V[] The input table. + ---@param callback fun(value: V, index: number, tbl: V[]): boolean The condition to check for each element. It receives three arguments: the element's value, its key, and the original table. It should return true if the element satisfies the condition, false otherwise. + ---@return V[] A new table containing only the elements that satisfy the condition. + function table.filterArray(tbl, callback) + local result = {} + for i, v in ipairs(tbl) do + if callback(v, i, tbl) then + result[#result + 1] = v + end + end + return result + end +end + +if not table.filterTable then + --- Creates a new (dictionary-style) table containing only the elements that satisfy a given condition. + ---@generic K, V, R + ---@param tbl table The input table. + ---@param callback fun(value: V, key: K, tbl: table): boolean The condition to check for each element. It receives three arguments: the element's value, its index, and the original table. It should return true if the element satisfies the condition, false otherwise. + ---@return table A new table containing only the elements that satisfy the condition. + function table.filterTable(tbl, callback) + local result = {} + for k, v in pairs(tbl) do + if callback(v, k, tbl) then + result[k] = v + end + end + return result + end +end + +if not table.all then + --- Checks if all elements of a table satisfy a condition. + ---@generic K, V, R + ---@param tbl table The input table. + ---@param callback fun(value: V, key: K, tbl: table): boolean The condition to check for each element. It receives three arguments: the element's value, its key, and the original table. It should return true if the element satisfies the condition, false otherwise. + ---@return boolean True if all elements satisfy the condition, false otherwise. + function table.all(tbl, callback) + for k, v in pairs(tbl) do + if not callback(v, k, tbl) then + return false + end + end + return true + end +end + +if not table.any then + --- Checks if at least one element of a table satisfies a condition. + ---@generic K, V, R + ---@param tbl table The input table. + ---@param callback fun(value: V, key: K, tbl: table): boolean The condition to check for each element. It receives three arguments: the element's value, its key, and the original table. It should return true if the element satisfies the condition, false otherwise. + ---@return boolean True if at least one element satisfies the condition, false otherwise. + function table.any(tbl, callback) + for k, v in pairs(tbl) do + if callback(v, k, tbl) then + return true + end + end + return false + end +end + +if not table.valueIntersection then + ---Creates a new array-style table containing the intersection of all input arrays. + ---Returns only unique elements that appear in all input arrays. + ---@generic V + ---@param ... V[] Any number of array-style tables. + ---@return V[] A new array containing only values present in all input arrays. + function table.valueIntersection(...) + local tables = { ...} + + -- Count occurrences of each value across all arrays + local valueCounts = {} + for _, tbl in pairs(tables) do + -- Use a set for each array to handle duplicates correctly + local seen = {} + for _, value in pairs(tbl) do + if not seen[value] then + seen[value] = true + valueCounts[value] = (valueCounts[value] or 0) + 1 + end + end + end + + -- Keep only values that appear in all arrays + local result = {} + local numTables = table.count(tables) + for value, count in pairs(valueCounts) do + if count == numTables then + result[#result + 1] = value + end + end + + return result + end +end + +if not pairsByKeys then + ---pairs-like iterator function traversing the table in the order of its keys. + ---Natural sort order will be used by default, optionally pass a comparator + ---function for custom sorting. + ---@generic K, V + ---@param tbl table + ---@param keySortFunction? fun(a: K, b: K): boolean comparator function passed to table.sort for sorting keys + ---@return fun(table: table, index?: K): K, V + ---@return table + ---(Implementation copied straight from the docs at https://www.lua.org/pil/19.3.html.) + function pairsByKeys(tbl, keySortFunction) + local keys = {} + for key in pairs(tbl) do table.insert(keys, key) end + table.sort(keys, keySortFunction) + local i = 0 -- iterator variable + local iter = function() -- iterator function + i = i + 1 + if keys[i] == nil then + return nil + else + return keys[i], tbl[keys[i]] + end + end + return iter + end +end + +local originalSpring=Spring +local Spring=setmetatable({GetModOptions=originalSpring.GetModOptions},{__index=originalSpring}) +local options=(function() +-- Custom Options Definition Table format +-- NOTES: +-- using an enumerated table lets you specify the options order +-- +-- These keywords must be lowercase for LuaParser to read them. +-- +-- key: the string used in the script.txt +-- name: the displayed name +-- desc: the description (could be used as a tooltip) +-- hint: greyed out text that appears in input field when empty +-- type: the option type ('list','string','number','bool','subheader','separator') +-- def: the default value +-- min: minimum value for number options +-- max: maximum value for number options +-- step: quantization step, aligned to the def value +-- maxlen: the maximum string length for string options +-- items: array of item strings for list options +-- section: so lobbies can order options in categories/panels +-- scope: 'all', 'player', 'team', 'allyteam' <<< not supported yet >>> +-- collumn: moves the option 1 row up if value is greater than the preivous row's one, default: 1 +-- | negative value forces new row, absolute value is used +-- | zero moves to the left, 1 is default, 2 is half way to the right +-- | recommened values: for 2 columns: 1 and 2, for 3 columns 1, 1.66, and 2.33 +-- +-- lock: if type is bool: hides the table of keys when set to TRUE <<< can not hide separators >>> +-- | if type is list: add under each item what it should SHOW when set to +-- unlock: if type is bool: hides the table of keys when set to FALSE <<< can not hide separators >>> +-- | if type is list: add under each item what it should HIDE when set to +-- bitmask: int (1|2|4|8...etc), for when multiple options can hide an item + +local options = { + + --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + -- Main + Restrictions + --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + { + key = "options_main", + name = "Main", + desc = "", + type = "section", + weight = 7, + }, + + { + key = "sub_header", + name = "Options for changing base game settings.", + desc = "", + section = "options_main", + type = "subheader", + def = true, + }, + + { + key = "sub_header", + section = "options_main", + type = "separator", + }, + + { + key = "ranked_game", + name = "Ranked Game", + desc = "Should game results affect OpenSkill. Note that games with AI or games that are not balanced are always unranked.", + type = "bool", + section = "options_main", + def = true, + }, + + + { + key = "allowuserwidgets", + name = "Allow Custom Widgets", + desc = "Allow custom user widgets or disallow them", + type = "bool", + def = true, + hidden = true, + section = "options_main", + }, + + { + key = "allowunitcontrolwidgets", + name = "Allow Custom 'Unit Control' Widgets", + desc = "Allow custom user 'unit control' widgets or disallow them", + type = "bool", + def = true, + section = "options_main", + }, + + { + key = "allowpausegameplay", + name = "Allow Commands While Paused", + desc = "Allow giving unit commands while paused", + type = "bool", + def = true, + section = "options_main", + }, + + { + key = "sub_header", + section = "options_main", + type = "separator", + }, + + { + key = "sub_header", + name = "-- Gameplay Settings", + desc = "", + section = "options_main", + type = "subheader", + def = true, + }, + + { + key = "maxunits", + name = "Max Units Per Player", + desc = "Keep in mind there is an absolute limit of units, 32 000, divided between each team. If you set this value higher than possible it will force itself down to the maximum it can be.", + type = "number", + def = 2000, + min = 500, + max = 32000, + step = 1, -- quantization is aligned to the def value, (step <= 0) means that there is no quantization + section = "options_main", + }, + { + key = "deathmode", + name = "Game End Mode", + desc = "What it takes to eliminate a team", + type = "list", + def = "com", + section = "options_main", + items = { + { key = "neverend", name = "Never ending", desc = "Teams are never eliminated", lock = { "territorial_domination_config", "territorial_domination_elimination_threshold_multiplier" } }, + { key = "com", name = "Kill all enemy Commanders", desc = "When a team has no Commanders left, it loses", lock = { "territorial_domination_config", "territorial_domination_elimination_threshold_multiplier" } }, + { key= "territorial_domination", name= "Territorial Domination", desc="Teams earn points by capturing territory to stay in the game. At the end of the final round, the team with the most points wins.", unlock = {"territorial_domination_config", "territorial_domination_elimination_threshold_multiplier"} }, + { key = "builders", name = "Kill all Builders", desc = "When a team has no builders left, it loses", lock = { "territorial_domination_config", "territorial_domination_elimination_threshold_multiplier" } }, + { key = "killall", name = "Kill everything", desc = "Every last unit must be eliminated, no exceptions!", lock = { "territorial_domination_config", "territorial_domination_elimination_threshold_multiplier" } }, + { key = "own_com", name = "Player resign on Com death", desc = "When player commander dies, you auto-resign.", lock = { "territorial_domination_config", "territorial_domination_elimination_threshold_multiplier" } }, + } + }, + + { + key = "territorial_domination_config", + name = "Territorial Domination Length", + desc = + "Configures the grace period and the amount of time in minutes it takes to reach the maximum required territory.", + type = "list", + def = "25_minutes", + section = "options_main", + items = { + { key = "20_minutes", name = "4 Rounds, 20 Minutes", desc = "Early tech emphasis, comebacks very likely, elimination unlikely." }, + { key = "25_minutes", name = "5 Rounds, 25 Minutes(Default)", desc = "Mid/late-game tech, comebacks a significant factor, eliminations uncommon" }, + { key = "30_minutes", name = "6 Rounds, 30 Minutes", desc = "Late-game tech, comebacks less significant, eliminations likely" }, + { key = "35_minutes", name = "7 Rounds, 35 Minutes", desc = "Super lategame tech, eliminations extremely likely" }, + } + }, + + { + key = "territorial_domination_elimination_threshold_multiplier", + name = "Elimination Threshold Multiplier", + desc = "Teams are eliminated at round end when score < elimination threshold which is set by highest score multiplied by this value. Lower values are more lenient.", + type = "number", + def = 1.2, + min = 1.0, + max = 1.5, + step = 0.1, + section = "options_main", + }, + + { + key = "draft_mode", + name = "Draft Spawn Order Mode", + desc = "Random/Captain/Skill/Fair based startPosType modes. Default: Random.", + type = "list", + section = "options_main", + def = "random", + items = { + { key = "disabled", name = "Disabled", desc = "Disable draft mod. Fast-PC place first." }, + { key = "random", name = "Random Order", desc = "Players get to pick a start position with a delay in a random order." }, + { key = "captain", name = "Captains First", desc = "Captain picks first, then everyone else in a random order." }, + { key = "skill", name = "Skill Order", desc = "Skill-based order, instead of random." }, + { key = "fair", name = "After full team has loaded", desc = "Everyone must join the game first - after that (+2sec delay) everyone can place." } + }, + }, + + { + key = "teamcolors_anonymous_mode", + name = "Anonymous Mode", + desc = "Anonymize players by changing colors (based on chosen mode) and replacing names with question marks, making it harder to know who's who.", + type = "list", + section = "options_main", + def = "disabled", + items = { + { key = "disabled", name = "Disabled" }, + { key = "global", name = "Shuffle Globally", desc = "You can distinguish different players and everyone sees the same colors globally. Diplomacy is the same as usual except using colors instead of names (e.g. \"Red, let's ally against Blue\")." }, + { key = "local", name = "Shuffle Locally", desc = "You can distinguish different players but everyone sees different colors locally. Diplomacy is harder but possible using positions (e.g. \"Southeast, let's ally against Northeast\")." }, + { key = "disco", name = "Shuffle Locally (Continiously)", desc = "Same as local shuffle, except that colors are reshuffled every 2 mins for extra spicyness." }, + { key = "allred", name = "Everyone Is Red", desc = "You cannot distinguish different players, they all have the same color (red by default, can be changed in accessibility settings). Diplomacy is very hard." }, + }, + }, + + { + key = "transportenemy", + name = "Enemy Transporting", + desc = "Toggle which enemy units you can kidnap with an air transport", + hidden = true, + type = "list", + def = "notcoms", + section = "options_main", + items = { + { key= "notcoms", name= "All But Commanders", desc= "Only commanders are immune to napping" }, + { key= "none", name= "Disallow All", desc= "No enemy units can be napped" }, + } + }, + + { + key = "teamffa_start_boxes_shuffle", + name = "Shuffle TeamFFA Start Boxes", + desc = "In TeamFFA games (more than 2 teams, excluding Raptors / Scavengers), start boxes will be randomly assigned to each team: team 1 might be assigned any start box rather than team 1 always being assigned start box 1.", + type = "bool", + section = "options_main", + def = true, + }, + + { + key = "fixedallies", + name = "Disabled Dynamic Alliances", + desc = "Disables the possibility of players to dynamically change alliances ingame", + type = "bool", + def = true, + hidden = true, + section = "options_main", + }, + + { + key = "disablemapdamage", + name = "Disable Map Deformation", + desc = "Prevents the map shape from being changed by weapons", + type = "bool", + def = false, + section = "options_main", + }, + + { + key = "disable_fogofwar", + name = "Disable Fog of War", + desc = "Disable Fog of War", + type = "bool", + section = "options_main", + def = false, + }, + + { + key = "norushtimer", + name = "No Rush Time".."\255\128\128\128".." [minutes]", + desc = "Set timer in which players cannot get out of their startbox, so you have time to prepare before fighting.\n".. + "PLEASE NOTE: For this to work, the game needs to have set startboxes.\n".. + -- tabs don't do much in chobby + " It won't work in FFA mode without boxes.\n".. + " Also, it does not affect Scavengers and Raptors.\n".. + "\255\75\0\100".."WARNING: No Rush Time over 30 minutes may cause performance or stability issues due to excessive unit buildup.", + type = "number", + section = "options_main", + def = 0, + min = 0, + max = 120, + step = 1, + }, + { + key = "norushmiddlefree", + name = "No Rush Non Base FFA", + desc = "Allows units to leave startboxes but disallows commands issued in enemy startboxes.\n".. + "Does not prevent commands onto the other side of startboxes so recommend East/West or North/South startboxes.", + type = "bool", + section = "options_main", + def = false, + }, + + { + key = "comm_trans_slow", + name = "Slow Commander Transport", + desc = "T2 transports carrying a Commander, move at speed 120. A temporary option available, until bigger transport changes get finished.", + type = "bool", + section = "options_main", + def = false, + }, + + { + key = "sub_header", + section = "options_main", + type = "separator", + }, + { + key = "sub_header", + name = "-- Sharing and Taxes", + section = "options_main", + type = "subheader", + def = true, + }, + { + key = "tax_resource_sharing_amount", + name = "Resource Sharing Tax", + desc = "Taxes resource sharing".."\255\128\128\128".." and overflow (engine TODO:)\n".. + "Set to [0] to turn off. Recommended: [0.4]. (Ranges: 0 - 0.99)", + type = "number", + def = 0, + min = 0, + max = 0.99, + step = 0.01, + section = "options_main", + column = 1, + }, + { + key = "disable_unit_sharing", + name = "Disable Unit Sharing", + desc = "Disable sharing units and structures to allies", + type = "bool", + section = "options_main", + def = false, + }, + { + key = "disable_assist_ally_construction", + name = "Disable Assist Ally Construction", + desc = "Disables assisting allied blueprints and labs.", + type = "bool", + section = "options_main", + def = false, + column = 1.66, + }, + { + key = "sub_header", + section = "options_main", + type = "separator", + }, + + { + key = "sub_header", + name = "-- Unit Restrictions", + desc = "", + section = "options_main", + type = "subheader", + def = true, + }, + + { + key = "unit_restrictions_notech15", + name = "Disable Tech 1.5", + desc = "Disables: Sea Plane Labs, Hovercraft labs, and Amphibious labs. (Considered Tier 1.5)", + type = "bool", + section = "options_main", + def = false, + column = 1, + }, + + { + key = "unit_restrictions_notech2", + name = "Disable Tech 2", + desc = "Disable Tech 2", + type = "bool", + section = "options_main", + def = false, + column = 1.66, + }, + + { + key = "unit_restrictions_notech3", + name = "Disable Tech 3", + desc = "Disable Tech 3", + type = "bool", + section = "options_main", + def = false, + column = 2.33, + }, + + { + key = "unit_restrictions_noair", + name = "Disable Air Units", + desc = "Disable Air Units", + type = "bool", + section = "options_main", + def = false, + column = 1, + }, + + { + key = "unit_restrictions_nosea", + name = "Disable Sea Units", + desc = "Disable Sea Units", + type = "bool", + section = "options_main", + def = false, + column = 1.66, + }, + + { + key = "unit_restrictions_noextractors", + name = "Disable Metal Extractors", + desc = "Disable Metal Extractors", + type = "bool", + section = "options_main", + def = false, + column = 1, + }, + + { + key = "unit_restrictions_noconverters", + name = "Disable Energy Converters", + desc = "Disable Energy Converters", + type = "bool", + section = "options_main", + def = false, + column = 1.66, + }, + + { + key = "unit_restrictions_nofusion", + name = "Disable Fusion Generators", + desc = "Disables Normal and Advanced Fusion Energy Generators", + type = "bool", + section = "options_main", + def = false, + column = 2.33, + }, + + { + key = "unit_restrictions_notacnukes", + name = "Disable Tactical Missiles/EMPs", + desc = "Disables Cortex Tactical Missile Launcher and Armada EMP Missile Launcher", + type = "bool", + section = "options_main", + def = false, + column = 1, + }, + + { + key = "unit_restrictions_nonukes", + name = "Disable Nuclear Missiles", + desc = "Disable Nuclear Missiles", + type = "bool", + section = "options_main", + def = false, + column = 1.66, + }, + + { + key = "unit_restrictions_noantinuke", + name = "Disable Anti-Nuke Defence", + desc = "Disables Nuke Interceptor Units and Structures.", + type = "bool", + section = "options_main", + def = false, + column = 2.33, + }, + + { + key = "unit_restrictions_nolrpc", + name = "Disable Long Range Artilery (LRPC)", + desc = "Disable Long Range Plasma Artilery (LRPC) structures", + type = "bool", + section = "options_main", + def = false, + column = 1, + }, + + { + key = "unit_restrictions_noendgamelrpc", + name = "Disable Endgame Artilery (LRPC)", + desc = "Disable Endgame Long Range Plasma Artilery (LRPC) structures (AKA lolcannons)", + type = "bool", + section = "options_main", + def = false, + column = 1.66, + }, + + + --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + -- Other Options + --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + + { + key = "options", + name = "Other", + desc = "Options", + type = "section", + }, + + { + key = "map_tidal", + name = "Tidal Strength", + desc = "Unchanged = map setting, low = 13e/sec, medium = 18e/sec, high = 23e/sec.", + hidden = true, + type = "list", + def = "unchanged", + section = "options", + items = { + { key = "unchanged", name = "Unchanged", desc = "Use map settings" }, + { key = "low", name = "Low", desc = "Set tidal incomes to 13 energy per second" }, + { key = "medium", name = "Medium", desc = "Set tidal incomes to 18 energy per second" }, + { key = "high", name = "High", desc = "Set tidal incomes to 23 energy per second" }, + } + }, + + { + key = "critters", + name = "Animal amount", + desc = "This multiplier will be applied on the amount of critters a map will end up with", + hidden = true, + type = "number", + section = "options", + def = 1, + min = 0, + max = 2, + step = 0.2, + }, + + { + key = "map_atmosphere", + name = "Map Atmosphere and Ambient Sounds", + desc = "", + type = "bool", + def = true, + hidden = true, + section = "options", + }, + + { + key = "ffa_wreckage", + name = "FFA Mode Wreckage", + desc = "Killed players will blow up but leave wreckages", + hidden = true, + type = "bool", + def = false, + section = "options", + }, + + { + key = "wreck_metal_ratio", + name = "Wreck Metal Percent", + desc = "Percent of unit metal that is left in its wrecks", + hidden = true, + type = "number", + section = "options", + def = 0.6, + min = 0, + max = 1, + step = 0.05, + }, + + { + key = "heap_metal_ratio", + name = "Heap Metal Percent", + desc = "Percent of unit metal that is left in its heaps", + hidden = true, + type = "number", + section = "options", + def = 0.25, + min = 0, + max = 1, + step = 0.05, + }, + + { + key = "coop", + name = "Cooperative mode", + desc = "Adds extra commanders to id-sharing teams, 1 com per player", + type = "bool", + hidden = true, + def = false, + section = "options", + }, + + --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + -- Multiplier Options + --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + + --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + -- Raptors + --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + { + key = "raptor_defense_options", + name = "Raptors", + desc = "Various gameplay options that will change how the Raptor Defense is played.", + type = "section", + weight = 4, + }, + + { + key = "sub_header", + name = "Raptors Gamemode Options.", + desc = "", + section = "raptor_defense_options", + type = "subheader", + def = true, + }, + + { + key = "raptors_dev_channel_link", + name = "Development Discussion", + desc = "Raptors development discussion.", + section = "raptor_defense_options", + type = "link", + link = "https://discord.com/channels/549281623154229250/781097030692110346", + width = 275, + column = 1.65, + linkheight = 325, + linkwidth = 350, + }, + + { + key = "sub_header", + name = "To Play Add a Raptors AI to the enemy Team: [Add AI], [RaptorsDefense AI]", + desc = "", + section = "raptor_defense_options", + type = "subheader", + }, + + { + key = "sub_header", + section = "raptor_defense_options", + type = "separator", + }, + + { + key = "raptor_difficulty", + name = "Base Difficulty", + desc = "Raptors difficulty", + type = "list", + def = "normal", + section = "raptor_defense_options", + items = { + { key = "veryeasy", name = "Very Easy", desc="Very Easy" }, + { key = "easy", name = "Easy", desc="Easy" }, + { key = "normal", name = "Normal", desc="Normal" }, + { key = "hard", name = "Hard", desc="Hard" }, + { key = "veryhard", name = "Very Hard", desc="Very Hard" }, + { key = "epic", name = "Epic", desc="Epic" }, + } + }, + + { + key = "sub_header", + section = "raptor_defense_options", + type = "separator", + }, + + { + key = "raptor_raptorstart", + name = "Hives Placement", + desc = "Control where hives spawn", + type = "list", + def = "initialbox", + section = "raptor_defense_options", + items = { + { key = "avoid", name = "Spawn Anywhere", desc = "Hives avoid player units" }, + { key = "initialbox", name = "Growing Spawn Box", desc = "Hives spawn in limited area that increases over time" }, + { key = "alwaysbox", name = "Always Start Box", desc = "Hives always spawn in raptor start box" }, + } + }, + + { + key = "raptor_endless", + name = "Endless Mode", + desc = "When you kill the queen, the game doesn't end, but loops around at higher difficulty instead, infinitely.", + type = "bool", + def = false, + section = "raptor_defense_options", + }, + + { + key = "sub_header", + section = "raptor_defense_options", + type = "separator", + }, + + { + key = "sub_header", + name = "-- Advanced Options, Change at your own risk.", + desc = "", + section = "raptor_defense_options", + type = "subheader", + def = true, + }, + + { + key = "raptor_queentimemult", + name = "Queen Hatching Time Multiplier", + desc = "(Range: 0.1 - 2). How quickly Queen Hatch goes from 0 to 100%", + type = "number", + def = 1, + min = 0.1, + max = 2, + step = 0.1, + section = "raptor_defense_options", + }, + + { + key = "raptor_queen_count", + name = "Raptor Queen Count", + desc = "(Range: 1 - 100). Number of queens that will spawn.", + type = "number", + def = 1, + min = 1, + max = 100, + step = 1, + section = "raptor_defense_options", + }, + + { + key = "raptor_spawncountmult", + name = "Unit Spawn Per Wave Multiplier", + desc = "(Range: 1 - 5). How many times more raptors will spawn per wave.", + type = "number", + def = 1, + min = 1, + max = 5, + step = 1, + section = "raptor_defense_options", + }, + + { + key = "raptor_firstwavesboost", + name = "First Waves Size Boost", + desc = "(Range: 1 - 10). Intended to use with heavily modified settings. Makes first waves larger, the bigger the number the larger they are. Cools down within first few waves.", + type = "number", + def = 1, + min = 1, + max = 10, + step = 1, + section = "raptor_defense_options", + }, + + { + key = "raptor_spawntimemult", + name = "Waves Amount Multiplier", + desc = "(Range: 1 - 5). How often new waves will spawn. Bigger Number = More Waves", + type = "number", + def = 1, + min = 1, + max = 5, + step = 0.1, + section = "raptor_defense_options", + }, + + { + key = "raptor_graceperiodmult", + name = "Grace Period Time Multiplier", + desc = "(Range: 0.1 - 3). Time before Raptors become active. ", + type = "number", + def = 1, + min = 0.1, + max = 3, + step = 0.1, + section = "raptor_defense_options", + }, + + + --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + -- Scavengers + --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + { + key = "scav_defense_options", + name = "Scavengers", + desc = "Gameplay options for Scavengers gamemode", + type = "section", + weight = 3, + }, + + { + key = "sub_header", + name = "Scavengers Gamemode Options.", + desc = "", + section = "scav_defense_options", + type = "subheader", + def = true, + }, + + { + key = "scavengers_dev_channel_link", + name = "Development Discussion", + desc = "Scavengers development discussion.", + section = "scav_defense_options", + type = "link", + link = "https://discord.com/channels/549281623154229250/659550298653589504", + width = 275, + column = 1.65, + linkheight = 325, + linkwidth = 350, + }, + + { + key = "sub_header", + name = "To Play Add a Scavangers AI to the enemy Team: [Add AI], [ScavengersDefense AI]", + desc = "", + section = "scav_defense_options", + type = "subheader", + }, + + + { + key = "sub_header", + section = "scav_defense_options", + type = "separator", + }, + + { + key = "scav_difficulty", + name = "Base Difficulty", + desc = "Scavs difficulty", + type = "list", + def = "normal", + section = "scav_defense_options", + items = { + { key = "veryeasy", name = "Very Easy", desc = "Very Easy" }, + { key = "easy", name = "Easy", desc = "Easy" }, + { key = "normal", name = "Normal", desc = "Normal" }, + { key = "hard", name = "Hard", desc = "Hard" }, + { key = "veryhard", name = "Very Hard", desc = "Very Hard" }, + { key = "epic", name = "Epic", desc = "Epic" }, + } + }, + + { + key = "sub_header", + section = "scav_defense_options", + type = "separator", + }, + + { + key = "scav_scavstart", + name = "Spawn Beacons Placement", + desc = "Control where spawners appear", + type = "list", + def = "initialbox", + section = "scav_defense_options", + items = { + { key = "avoid", name = "Spawn Anywhere", desc="Beacons avoid player units" }, + { key = "initialbox", name = "Growing Spawn Box", desc="Beacons spawn in limited area that increases over time" }, + --{ key = "alwaysbox", name = "Always Start Box", desc="Beacons always spawn in scav start box" }, + } + }, + + { + key = "scav_endless", + name = "Endless Mode", + desc = "When you kill the boss, the game doesn't end, but loops around at higher difficulty instead, infinitely.", + type = "bool", + def = false, + section = "scav_defense_options", + }, + + { + key = "sub_header", + section = "scav_defense_options", + type = "separator", + }, + + { + key = "sub_header", + name = "-- Advanced Options, Change at your own risk.", + desc = "", + section = "scav_defense_options", + type = "subheader", + def = true, + }, + + { + key = "scav_bosstimemult", + name = "Boss Preparation Time Multiplier", + desc = "(Range: 0.1 - 2). How quickly Boss Anger goes from 0 to 100%.", + type = "number", + def = 1, + min = 0.1, + max = 2, + step = 0.1, + section = "scav_defense_options", + }, + + { + key = "scav_boss_count", + name = "Scavengers Boss Count", + desc = "(Range: 1 - 20). Number of bosses that will spawn.", + type = "number", + def = 1, + min = 1, + max = 20, + step = 1, + section = "scav_defense_options", + }, + + { + key = "scav_spawncountmult", + name = "Unit Spawn Per Wave Multiplier", + desc = "(Range: 1 - 5). How many times more scavs will spawn per wave.", + type = "number", + def = 1, + min = 1, + max = 5, + step = 1, + section = "scav_defense_options", + }, + + { + key = "scav_spawntimemult", + name = "Waves Amount Multiplier", + desc = "(Range: 1 - 5). How often new waves will spawn. Bigger Number = More Waves", + type = "number", + def = 1, + min = 1, + max = 5, + step = 0.1, + section = "scav_defense_options", + }, + + { + key = "scav_graceperiodmult", + name = "Grace Period Time Multiplier", + desc = "(Range: 0.1 - 3). Time before Scavs become active. ", + type = "number", + def = 1, + min = 0.1, + max = 3, + step = 0.1, + section = "scav_defense_options", + }, + + --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + -- Extra Options + --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + + { + key = "options_extra", + name = "Extras", + desc = "Extra options", + type = "section", + weight = 2, + }, + + + { + key = "sub_header", + name = "Extra options for shaking up the gameplay or balancing. Not intended for ranked games.", + desc = "", + section = "options_extra", + type = "subheader", + def = true, + }, + + { + key = "sub_header", + section = "options_extra", + type = "separator", + }, + + + { + key = "experimentalextraunits", + name = "Extra Units Pack", + desc = "Pack of units that didn't make it to the main game roster. Balanced for PvP", + type = "bool", + section = "options_extra", + def = false, + }, + + { + key = "scavunitsforplayers", + name = "Scavengers Units Pack", + desc = "Units made for Scavengers, mostly silly and unbalanced for PvP.", + type = "bool", + section = "options_extra", + def = false, + }, + + { + key = "sub_header", + section = "options_extra", + type = "separator", + }, + + + { + key = "map_waterlevel", + name = "Water Level", + desc = "Doesn't work if Map Deformation is disabled! <0 = Decrease water level, >0 = Increase water level", + type = "number", + def = 0, + min = -10000, + max = 10000, + step = 1, + section = "options_extra", + }, + + { + key = "map_waterislava", + name = "Water Is Lava", + desc = "Turns water into Lava", + type = "bool", + def = false, + section = "options_extra", + unlock = {"map_lavatiderhythm", "map_lavatidemode", "map_lavahighlevel", "map_lavahighdwell", "map_lavalowlevel", "map_lavalowdwell","map_tweaklava"}, + lock = {"sub_header_lava3", "sub_header_lava4"}, + bitmask = 1, + }, + + { + key = "map_lavatiderhythm", + name = "Lava Tides", + desc = "Lava level periodicially cycles height when tides are present", + type = "list", + def = "default", + section = "options_extra", + column = 1, + items = { + { key= "default", name= "Default", desc= "Map Settings", + lock = + {"map_lavatidemode", "map_lavahighlevel", "map_lavahighdwell", "map_lavalowlevel", "map_lavalowdwell", "sub_header_lava3", "sub_header_lava4"}, + unlock = + { "sub_header_lava1", "sub_header_lava2"}}, + { key= "enabled", name= "Enable/Override",desc= "Lava tides will use these settings over the map defaults", + unlock = + {"map_lavatidemode", "map_lavahighlevel", "map_lavahighdwell", "map_lavalowlevel", "map_lavalowdwell", "sub_header_lava3", "sub_header_lava4"}, + lock = + { "sub_header_lava1", "sub_header_lava2"}}, + { key= "disabled", name= "Disable",desc= "Lava will not have tides, even on maps that normally have it", + lock = + {"map_lavatidemode", "map_lavahighlevel", "map_lavahighdwell", "map_lavalowlevel", "map_lavalowdwell", "sub_header_lava3", "sub_header_lava4"}, + unlock = + { "sub_header_lava1", "sub_header_lava2"}}, + }, + bitmask = 2, + }, + + { + key = "map_lavatidemode", + name = "Lava Tide Mode", + desc = "Toggle whether lava starts at high or low tide.", + hidden = false, + type = "list", + def = "lavastartlow", + section = "options_extra", + items = { + { key= "lavastartlow", name= "Start Low", desc= "Lava starts at low tide" }, + { key= "lavastarthigh", name= "Start High",desc= "Lava starts at high tide" }, + } + }, + + { + key = "map_lavahighlevel", + name = "Lava High Tide Level", + desc = "Lava level at high tide", + type = "number", + def = 0, + min = 0, + max = 10000, + step = 1, + section = "options_extra", + column = 1, + }, + + { + key = "map_lavahighdwell", + name = "Lava High Tide Time", + desc = "Time in seconds lava waits at high tide", + type = "number", + def = 60, + min = 1, + max = 30000, + step = 1, + section = "options_extra", + column = 2.0, + }, + + { + key = "map_lavalowlevel", + name = "Lava Low Tide Level", + desc = "Lava level at low tide", + type = "number", + def = 0, + min = 0, + max = 10000, + step = 1, + section = "options_extra", + column = 1, + }, + + { + key = "map_lavalowdwell", + name = "Lava Low Tide Time", + desc = "Time in seconds lava waits at low tide", + type = "number", + def = 300, + min = 1, + max = 30000, + step = 1, + section = "options_extra", + column = 2.0, + }, + + { + key = "map_tweaklava", + name = "Advanced Tide Rhythm", + desc = "Table with format {MapHeight (elmo), Rate (elmo/s), Dwell Time (s)}, e.g. {0, 6, 60},{100, 3, 20}", + hidden = true, + hint = "{Lava Height, Rise/Fall Rate, Dwell Time}", + type = "string", + def = "", + section = "options_extra", + }, + + { key = "sub_header_lava1", section = "options_extra", type = "subheader", name = "",}, + { key = "sub_header_lava2", section = "options_extra", type = "subheader", name = "",}, + { key = "sub_header_lava3", section = "options_extra", type = "subheader", name = "",}, + { key = "sub_header_lava4", section = "options_extra", type = "subheader", name = "",}, + + + { + key = "sub_header", + section = "options_extra", + type = "separator", + }, + + { + key = "ruins", + name = "Ruins", + desc = "Remains of the battles once fought", + type = "list", + def = "scav_only", + section = "options_extra", + items = { + { key = "enabled", name = "Enabled", unlock = {"ruins_density", "ruins_only_t1"} }, + { key = "scav_only", name = "Enabled for Scavengers only", unlock = {"ruins_density", "ruins_only_t1"} }, + { key = "disabled", name = "Disabled", lock = {"ruins_density", "ruins_only_t1"} }, + } + }, + + { + key = "ruins_density", + name = "Ruins: Density", + type = "list", + def = "normal", + section = "options_extra", + items = { + { key = "verydense", name = "Very Dense" }, + { key = "dense", name = "Dense" }, + { key = "normal", name = "Normal" }, + { key = "rare", name = "Rare" }, + { key = "veryrare", name = "Very Rare" }, + } + }, + + { + key = "ruins_only_t1", + name = "Ruins: Only Tech 1", + type = "bool", + def = false, + section = "options_extra", + }, + + { + key = "ruins_civilian_disable", + name = "Ruins: Disable Civilian (Not Implemented Yet)", + type = "bool", + def = false, + section = "options", + hidden = true, + }, + + { + key = "sub_header", + section = "options_extra", + type = "separator", + }, + + + { + key = "lootboxes", + name = "Lootboxes", + desc = "Random drops of valuable stuff.", + type = "list", + def = "scav_only", + section = "options_extra", + items = { + { key = "enabled", name = "Enabled", unlock = {"lootboxes_density"} }, + { key = "scav_only", name = "Enabled for Scavengers only", unlock = {"lootboxes_density"} }, + { key = "disabled", name = "Disabled", lock = {"lootboxes_density"} }, + } + }, + + { + key = "lootboxes_density", + name = "Lootboxes: Density", + type = "list", + def = "normal", + section = "options_extra", + items = { + { key = "normal", name = "Normal" }, + { key = "rare", name = "Rare" }, + { key = "veryrare", name = "Very Rare" }, + } + }, + + { + key = "sub_header", + section = "options_extra", + type = "separator", + }, + + { + key = "evocom", + name = "Evolving Commanders", + desc = "Commanders evolve, gaining new weapons and abilities.", + type = "bool", + def = false, + section = "options_extra", + bitmask = 1, + unlock = {"evocomlevelupmethod","evocomlevelcap","evocomxpmultiplier", "evocomleveluptime", "evocomlevelupmultiplier"}, + --lock = {"buffer_fix"}, + }, + + { + key = "evocom_feedback_thread_link", + name = "Feedback thread", + desc = "Discord discussion about Evolving Commanders.", + section = "options_extra", + type = "link", + link = "https://discord.com/channels/549281623154229250/1233887661291343913", + width = 215, + column = 2, + linkheight = 325, + linkwidth = 350, + }, + + { + key = "evocomlevelupmethod", + name = "EvoCom: Leveling Method", + desc = "Dynamic: Commanders evolve to keep up with the highest power player. Timed: Static Evolution Rate", + type = "list", + def = "dynamic", + section = "options_extra", + bitmask = 2, + items = { + { key = "dynamic", name = "Dynamic", lock = {"evocomleveluptime"}, unlock = {"evocomlevelupmultiplier"}}, + { key = "timed", name = "Timed", lock = {"evocomlevelupmultiplier"}, unlock = {"evocomleveluptime"}}, + } + }, + + + { + key = "evocomlevelupmultiplier", + name = "EvoCom: Evolution Mult.", + desc = "(Range 0.1x - 3x Multiplier) Adjusts the thresholds at which Dynamic evolutions occur", + type = "number", + section = "options_extra", + def = 1, + min = 0.1, + max = 3, + step = 0.1, + }, + + { + key = "evocomleveluptime", + name = "EvoCom: Evolution Time ", + desc = "(Range 0.1 - 20 Minutes) Rate at which commanders will evolve if Timed method is selected.", + type = "number", + section = "options_extra", + def = 5, + min = 0.1, + max = 20, + step = 0.1, + }, + + { + key = "evocomlevelcap", + name = "EvoCom: Max Level", + desc = "(Range 2 - 10) Changes the Evolving Commanders maximum level", + type = "number", + section = "options_extra", + def = 10, + min = 2, + max = 10, + step = 1, + }, + + { + key = "evocomxpmultiplier", + name = "EvoCom: Commander XP Multiplier", + desc = "(Range 0.1 - 10) Does not affect leveling! Changes the rate at which Evolving Commanders gain Experience.", + type = "number", + section = "options_extra", + def = 1, + min = 0.1, + max = 10, + step = 0.1, + }, + + { + key = "sub_header", + section = "options_extra", + type = "separator", + }, + + + { + key = "comrespawn", + name = "Commander Respawning", + desc = "Commanders can build one Effigy. The first one is free and given for you at the start. When the commander dies, the Effigy is sacrificed in its place.", + type = "list", + def = "evocom", + section = "options_extra", + items = { + { key = "evocom", name = "Evolving Commanders Only" }, + { key = "all", name = "All Commanders" }, + { key = "disabled", name = "Disabled" }, + } + }, + + { + key = "sub_header", + section = "options_extra", + type = "separator", + }, + + { + key = "quick_start", + name = "Quick Start", + desc = "Each player gets pre-game resources to spend on structures to be instantly spawned at the beginning of the game.", + type = "list", + def = "default", + section = "options_extra", + unlock = {"quick_start_amount"}, + items = { + { key = "default", name = "Default", lock = {"quick_start_amount"}, desc = "Default settings for game modes." }, + { key = "enabled", name = "Enabled", unlock = {"quick_start_amount"}, desc = "Quick Start alone, deducts 400 energy and 800 metal from starting resources." }, + { key = "factory_discount", name = "Enabled: Discounted First Factory", desc = + "Quick Start The commander's first factory is discounted at any time. Deducts 400 energy and 800 metal from starting resources.", unlock = {"quick_start_amount"} }, + { key = "factory_discount_only", name = "First Factory Discount Only", desc = "No base budget, only first factory discount. No deduction from starting resources.", lock = {"quick_start_amount"} }, + { key = "disabled", name = "Disabled", desc = "Disabled quick start for all game modes.", lock = {"quick_start_amount"} }, + } + }, + + { + key = "quick_start_link", + name = "Feedback thread", + desc = "Discord discussion about quick start.", + section = "options_extra", + type = "link", + link = "https://discord.com/channels/549281623154229250/1413936809980858408", + width = 215, + column = 2, + linkheight = 325, + linkwidth = 350, + }, + + { + key = "quick_start_amount", + name = "Quick Start Base Budget", + desc = "How much pre-game resources you have to spend on pre-queuing structures.", + type = "list", + def = "default", + section = "options_extra", + items = { + { key = "default", name = "Default", desc = "Uses the default amount based on game mode" }, + { key = "small", name = "Small", desc = "800 Base Budget" }, + { key = "normal", name = "Normal", desc = "1200 Base Budget" }, + { key = "large", name = "Large", desc = "2400 Base Budget" }, + } + }, + + { + key = "enable_quickstart_overrides", + name = "Enable Quick Start Overrides", + desc = "Allow overriding quick start range and budget (for debugging/modding).", + type = "bool", + def = false, + section = "options_extra", + hidden = true, + }, + + { + key = "override_quick_start_range", + name = "Override Quick Start Range", + desc = "Override the quick start build range when overrides are enabled (values below 200 are clamped to 200).", + type = "number", + def = 600, + min = 200, + max = 2000, + step = 1, + section = "options_extra", + hidden = true, + }, + + { + key = "override_quick_start_budget", + name = "Override Quick Start Budget", + desc = "Override the quick start starting resources when overrides are enabled.", + type = "number", + def = 1200, + min = 100, + max = 1000000, + step = 1, + section = "options_extra", + hidden = true, + }, + + { + key = "sub_header", + section = "options_extra", + type = "separator", + }, + + { + key = "assistdronesenabled", -- TODO, turn this into booleam modoption + name = "Commander Drones", + type = "list", + def = "disabled", + section = "options_extra", + items = { + { key = "enabled", name = "Enabled", unlock = {"assistdronesbuildpowermultiplier", "assistdronescount", "assistdronesair"} }, + { key = "disabled", name = "Disabled", lock = {"assistdronesbuildpowermultiplier", "assistdronescount", "assistdronesair"} }, + } + }, + + { + key = "assistdronesbuildpowermultiplier", + name = "ComDrones: Buildpower Multiplier", + desc = "(Range 0.5 - 5). How much buildpower commander drones should have", + type = "number", + section = "options_extra", + def = 1, + min = 0.5, + max = 5, + step = 0.1, + }, + + { + key = "assistdronescount", + name = "ComDrones: Count", + desc = "How many assist drones per commander should be spawned", + type = "number", + section = "options_extra", + def = 10, + min = 1, + max = 30, + step = 1, + }, + + { + key = "assistdronesair", + name = "ComDrones: Use Air Drones", + desc = "Switch between aircraft drones and amphibious vehicle drones.", + type = "bool", + def = true, + section = "options_extra", + }, + + { + key = "sub_header", + section = "options_extra", + type = "separator", + }, + + + { + key = "commanderbuildersenabled", -- TODO, turn this into boolean modoption + name = "Base Builder Turret", + type = "list", + def = "disabled", + section = "options_extra", + items = { + { key = "enabled", name = "Enabled", unlock = {"commanderbuildersrange", "commanderbuildersbuildpower"} }, + { key = "disabled", name = "Disabled", lock = {"commanderbuildersrange", "commanderbuildersbuildpower"} }, + } + }, + + { + key = "commanderbuildersrange", + name = "Base Builder Turret: Range", + desc = "(Range 500 - 2000).", + type = "number", + section = "options_extra", + def = 1000, + min = 500, + max = 2000, + step = 1, + }, + + { + key = "commanderbuildersbuildpower", + name = "Base Builder Turret: Buildpower", + desc = "(Range 100 - 1000).", + type = "number", + section = "options_extra", + def = 400, + min = 100, + max = 1000, + step = 1, + }, + + { + key = "sub_header", + section = "options_extra", + type = "separator", + }, + + { + key = "zombies", + name = "Scavenger Zombies", + type = "list", + def = "disabled", + section = "options_extra", + hidden = false, + items = { + { key = "disabled", name = "Disabled", desc = "Disabled"}, + { key = "normal", name = "Normal", desc = "Slow revival rate, normal strength."}, + { key = "hard", name = "Hard", desc = "Fast revival rate, stronger Scavenger Zombies." }, + { key = "nightmare", name = "Nightmare", desc = "Extreme revival rate, stronger Scavenger Zombies, 2-5 spawn per corpse." }, + } + }, + + --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + -- Experimental Options + --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + + { + key = "options_experimental", + name = "Experimental", + desc = "Experimental options", + type = "section", + weight = 1, + }, + + { + key = "sub_header", + name = "Options for testing various new and unfinished features. Not intended for ranked games.", + desc = "", + section = "options_experimental", + type = "subheader", + def = true, + }, + + { + key = "sub_header", + name = "When any of these options are changed, there is no guarantee they will work properly, especially when combined.", + desc = "", + section = "options_experimental", + type = "subheader", + def = true, + }, + + { + key = "sub_header", + section = "options_experimental", + type = "separator", + }, + + { + key = "proposed_unit_reworks", + name = "Placeholder for BLT testing", + desc = "Placeholder for official balance testing mod option", + type = "bool", + hidden = true, + section = "options_experimental", + def = false, + }, + + { + key = "community_balance_patch", + name = "Community Balance Patch 5-6/26", + desc = "Enable community balance patch changes\n(overwrites changes in official seasonal balance test)", + type = "list", + def = "disabled", + section = "options_experimental", + items = { + { key = "disabled", name = "Disabled", desc = "No community balance changes", + lock = {"community_balance_corspy","community_balance_armmav","community_balance_corcan","community_balance_corkarg","community_balance_armkam","community_balance_armblade"} }, + + { key = "enabled", name = "Enabled", desc = "Enable all community balance changes\nSpectre\nGunslinger\nSumo\nKarganeth\nBanshee\nHornet", + lock = {"community_balance_corspy","community_balance_armmav","community_balance_corcan","community_balance_corkarg","community_balance_armkam","community_balance_armblade"} }, + + { key = "custom", name = "Custom", desc = "Customize individual community balance changes", + unlock = {"community_balance_corspy", "community_balance_armmav", "community_balance_corcan", "community_balance_corkarg", "community_balance_armkam", "community_balance_armblade"} }, + } + }, + + { + key = "community_balance_patch_changelog_link", + name = "Changelog/Feedback", + desc = "Community Balance Patch discussion", + section = "options_experimental", + type = "link", + link = "https://discord.com/channels/549281623154229250/1512596823070740550", + width = 235, + column = 2.025, + linkheight = 325, + linkwidth = 350, + }, + + { + key = "community_balance_corspy", + name = "(CBP) Spectre", + desc = "(From February)\nEnergy cost: 8800 (from 12500)\nMetal cost: 135 (from 165)", + type = "bool", + def = false, + section = "options_experimental", + }, + + { + key = "community_balance_armmav", + name = "(CBP) Gunslinger", + desc = "(From April)\nMetal cost: 520 (from 650)\nEnergy cost: 6500 (from 11000)", + type = "bool", + def = false, + section = "options_experimental", + }, + + { + key = "community_balance_corcan", + name = "(CBP) Sumo", + desc = "(From April)\nMain laser range: 300 (from 275)\nMain laser beam time: 0.24 (from 0.16)", + type = "bool", + def = false, + section = "options_experimental", + }, + + { + key = "community_balance_corkarg", + name = "(CBP) Karganeth", + desc = "(New)\nSight distance: 515 (from 455)\nMax acceleration: 0.18 (from 0.1104)\nTurn rate: 515 (from 400)\nTurn-in-place speed limit: 1.25 (from 0.99)\nStrafe to attack: true (from false)\nMissile trajectory height: 0.25 (from none)\nMetal cost: 2650 (from 2500)\nBuild time: 100000 (from 94000)", + type = "bool", + def = false, + section = "options_experimental", + }, + + { + key = "community_balance_armkam", + name = "(CBP) Banshee", + desc = "(New)\nMax acceleration: 0.35 (from 0.15)\nWeapon range: 400 (from 350)\nWeapon reload: 3.0 (from 0.7)\nWeapon damage: 141 single shot (from 9 x 3 burst)\nArea of effect: 32 (from 40)\nEdge effectiveness: 0.40 (from 0.5)\nProjectile velocity: 1090 (from 1000)\nWeapon accuracy: 0 (from 13), spray angle removed (from 1024)\nCylindrical targeting: 0 (from 1)\nWeapon timer: 0 (from 0.1)\nWeapon tolerance: 2000 (from 5000)\nImpulse factor: 2.14 (from 0.123)\nWeapon visual: impulse-trail / genericshellexplosion-small-bomb (from plasmahit-small)\nWeapon sound: mavgun4 (from flashemg)\nTurret: true (from false)\nFiring arc: 45° forward, hidden attack range arc (from unrestricted/fixed)", + type = "bool", + def = false, + section = "options_experimental", + }, + + { + key = "community_balance_armblade", + name = "(CBP) Hornet", + desc = "(New)\nMax acceleration: 0.28 (from 0.6)\nMax deceleration: 0.55 (from 0.35)\nHealth: 3350 (from 3000)\nSpeed: 125 (from 204)\nTurn angle limit: 120 (from 360)\nTurn rate: 420 (from 720)\nSight distance: 720 (from 624)\nWeapon range: 1100 (from 420)\nWeapon reload: 4.0 (from 2.26667)\nWeapon damage: 425 x 2 burst (from 190 x 2 burst)\nCommander damage: 200 x 2 burst\nBurst rate: 0.15 (from 0.23333)\nArea of effect: 64 (from 32)\nEdge effectiveness: 0.40 (from 0.15)\nProjectile type: Cannon (from MissileLauncher)\nProjectile velocity: 1090 (from 1000)\nImpulse factor: 1.5 (from 0.123)\nWeapon visual: impulse-trail / genericshellexplosion-medium-bomb (from missiletrailsmall-simple / genericshellexplosion-medium)\nWeapon sound: mavgun5 / xplomed2 (from SabotFire / SabotHit)\nTurret: true (from false)\nFiring arc: 45° forward (from unrestricted)", + type = "bool", + def = false, + section = "options_experimental", + }, + + { + key = "experimentallegionfaction", + name = "Legion Faction", + desc = "3rd experimental faction", + type = "bool", + section = "options_experimental", + def = false, + }, + + { + key = "legionsimplifiedmexes", + name = "Legion Simplified Mexes", + desc = "Changes the legion T1 mex to act the same as the other T1 mexes. Legion light T1 units are given a higher metal cost but lower E cost, and heavy T1 units are given a higher E cost and slightly lower metal cost.", + type = "bool", + section = "options_experimental", + def = false, + }, + + { + key = "experimentallegionfaction_link", + name = "Development Discussion", + desc = "Discord discussion about Legion faction.", + section = "options_experimental", + type = "link", + link = "https://discord.com/channels/549281623154229250/1063217502898884701/1441480747629412675", + width = 275, + column = 1.65, + linkheight = 325, + linkwidth = 350, + }, + + { + key = "easytax", + name = "Easy Tax v2", + desc = "Anti co-op sharing tax mod. Overwrites other tax settings. Don't combine with other sharing restriction mods, everything you need is included with easy tax.", + type = "bool", + section = "options_experimental", + def = false, + }, + + { + key = "easytax_link", + name = "Changelog", + desc = "Easy Tax v2 description.", + section = "options_experimental", + type = "link", + link = "https://gist.github.com/RebelNode/43b986f29b9cfacbe95cf634cac25c49", + width = 215, + column = 1.65, + linkheight = 325, + linkwidth = 350, + }, + + -- Hidden Tests + + { + key = "techsplit", + name = "Tech Split", + desc = "Adds a new tier between T1 and T2 for bots and vehicles", + type = "bool", + hidden = true, + section = "options_experimental", + def = false, + }, + + { + key = "techsplit_balance", + name = "Tech Split Balance Test", + desc = "Adjusts the balance of units in the proposed tech split.", + type = "bool", + hidden = true, + section = "options_experimental", + def = false, + }, + + { + key = "experimental_defend_firestate", + name = "Defend Combat Stance", + desc = "Replaces Return Fire with the new Defend combat stance.\nDefending units will shoot threats to themselves when they become threats on a 1v1 basis.", + type = "bool", + section = "options_experimental", + def = false, + }, + + { + key = "experimental_defend_firestate_link", + name = "Feedback thread", + desc = "Discord discussion about the Defend Combat Stance rework.", + section = "options_experimental", + type = "link", + link = "https://discord.com/channels/549281623154229250/1520166826435280998", + width = 215, + column = 1.65, + linkheight = 325, + linkwidth = 350, + }, + + { + key = "air_rework", + name = "Air Rework", + desc = "Prototype version with more maneuverable, slower air units and more differentiation between them.", + hidden = true, + type = "bool", + section = "options_experimental", + def = false, + }, + + { + key = "skyshift", + name = "Skyshift: Air Rework", + desc = "A complete overhaul of air units and mechanics", + type = "bool", + def = false, + section = "options_experimental", + hidden = true, + }, + + { + key = "emprework", + name = "EMP Rework", + desc = "EMP is changed to slow units movement and firerate, before eventually stunning.", + type = "bool", + hidden = true, + section = "options_experimental", + + def = false, + }, + + { + key = "junorework", + name = "Juno Rework", + desc = "Juno stuns certain units (such as radars and jammers) rather than magically deleting them", + type = "bool", + hidden = true, + section = "options_experimental", + def = false, + }, + + { + key = "releasecandidates", + name = "Release Candidate Units", + desc = "Adds additional units to the game which are being considered for mainline integration and are balanced, or in end tuning stages. Currently adds Printer, Siegebreaker, Phantom (Core T2 veh), Shockwave (Arm T2 EMP Mex), and Drone Carriers for armada and cortex", + type = "bool", + hidden = true, + section = "options_experimental", + def = false, + }, + + { + key = "naval_balance_tweaks", + name = "Proposed Naval Balance Tweaks", + desc = "Modoption used to test specific balance adjustments dedicated towards naval units.", + type = "bool", + --hidden = true, + section = "options_experimental", + def = false, + }, + + { + key = "naval_balance_tweaks_link", + name = "Feedback thread", + desc = "Discord discussion about naval balance tweaks.", + section = "options_experimental", + type = "link", + link = "https://discord.com/channels/549281623154229250/1428031834045939833", + width = 215, + column = 1.65, + linkheight = 325, + linkwidth = 350, + }, + + { + key = "forge_volcano", + name = "Forge Volcano Event", + desc = "Enable the cinematic volcano eruption event on Forge v2.3.", + type = "bool", + hidden = true, + section = "options_experimental", + def = false, + }, + + { + key = "factory_costs", + name = "Factory Costs Test Patch", + desc = "Cheaper and more efficient factories, more expensive nanos, and slower to build higher-tech units. Experimental, not expected to be balanced by itself - a test to try how the game plays if each player is more able to afford their own T2 factory, while making assisting them less efficient.", + type = "bool", + hidden = true, + section = "options_experimental", + def = false, + }, + + --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + -- Unused Options + --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + + { + key = "modes", + name = "GameModes", + desc = "Game Modes", + hidden = true, + type = "section", + }, + + { + key = "shareddynamicalliancevictory", + name = "Dynamic Ally Victory", + desc = "Ingame alliance should count for game over condition.", + hidden = true, + type = "bool", + section = "options", + def = false, + }, + + { + key = "ai_incomemultiplier", + name = "AI Income Multiplier", + desc = "Multiplies AI resource income", + hidden = true, + type = "number", + section = "options", + def = 1, + min = 1, + max = 10, + step = 0.1, + }, + + { + key = "defaultdecals", + name = "Default Decals", + desc = "Use the default explosion decals instead of Decals GL4", + section = "options_experimental", + type = "bool", + def = true, + hidden = true, + }, + + --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + -- DEV mode only mod option otherwise hidden by chobby + --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + + { + key = "dev", + name = "_DEV", + desc = "tab that should be hidden by chobby", + hidden = true, + type = "section", + }, + { + key = "teamcolors_icon_dev_mode", + name = "Icon Dev Mode ", + desc = "(Don't use in normal games) Forces teamcolors to be an specific one, for all teams", + type = "list", + section = "dev", + def = "disabled", + items = { + { key = "disabled", name = "Disabled", desc = "description" }, + { key = "armblue", name = "Armada Blue", desc = "description" }, + { key = "corred", name = "Cortex Red", desc = "description" }, + { key = "scavpurp", name = "Scavenger Purple", desc = "description" }, + { key = "raptororange", name = "Raptor Orange", desc = "description" }, + { key = "gaiagray", name = "Gaia Gray", desc = "description" }, + { key = "leggren", name = "Legion Green", desc = "description" }, + } + }, + { + key = "debugcommands", + name = "Debug Commands", + desc = "A pipe separated list of commands to execute at [gameframe]:luarules benchmark|100:forcequit...", -- example: debugcommands=150:cheat 1|200:luarules benchmark|600:quitforce; + section = "dev", + type = "string", + def = "", + }, + { + key = "animationcleanup", + name = "Animation Cleanup", + desc = "Use animations from the BOSCleanup branch", -- example: debugcommands=150:cheat 1|200:luarules benchmark|600:quitforce; + section = "dev", + type = "bool", + def = false, + }, + { + key = "pushresistant", + name = "Pushresistance", + desc = "Enable to do desync test by the use of pushresistance", + section = "dev", + type = "bool", + def = false, + }, + { + key = "dummyboolfeelfreetotouch", + name = "dummy to hide some modoptions", + desc = "This is a dummy to hide some modoptions to not bloat the changed options panel with unneeded information", + section = "dev", + type = "bool", + -- This doesn't have a default on purpse, do not add one + unlock = {"dummyboolfeelfreetotouch", "factionlimiter", "date_year", "date_month", "date_day", "date_hour"}, + }, + { key = "date_year", name = "Year", desc = "Spads (Multiplayer) / Skirmish Interface (Singleplayer) fed, auto-overwriten", section = "dev", type = "number", def = 0, min = 0, max = 3000, step = 1, }, + { key = "date_month", name = "Month", desc = "Spads (Multiplayer) / Skirmish Interface (Singleplayer) fed, auto-overwriten", section = "dev", type = "number", def = 0, min = 0, max = 12, step = 1, }, + { key = "date_day", name = "Day", desc = "Spads (Multiplayer) / Skirmish Interface (Singleplayer) fed, auto-overwriten", section = "dev", type = "number", def = 0, min = 0, max = 31, step = 1, }, + { key = "date_hour", name = "Hour", desc = "Spads (Multiplayer) / Skirmish Interface (Singleplayer) fed, auto-overwriten", section = "dev", type = "number", def = 0, min = 0, max = 24, step = 1, }, + { + key = "factionlimiter", + name = "Faction Limiter:".."\255\255\191\76".." ON\n".."\255\125\125\125".."BITMASK", + desc = [[BITMASK to be used via custom ui, only visible when boss +Set to [0] To disable. +Otherwise: 0th, 1st and 2nd bit are armada, cortex and legion respectively. +Offset by 3 for each consecutive team. +If a team's bitmask is 0, All are Enabled. +Example: Armada VS Cortex VS Legion: 273 or 100 010 001 or 256 + 16 + 1]], + section = "dev", + type = "number", + def = 0, + min = 0, + max = 16777215,-- math hard, 24 bit limitish? + step = 1, + }, + + --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + -- Map Metadata options + --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + -- + -- The modoptions below are intended to be set automatically by lobby/spads based on the selected + -- map name. They are used for a dynamic map configuration where the configruation values are not + -- tied to either game version or reside inside of the map file, allowing for independent distribution + -- from the maps metadata source of truth: https://github.com/beyond-all-reason/maps-metadata + { + key = "mapmetadata", + name = "MapMetadata", + desc = "mapmetadata tab that should be hidden by chobby, which would have ideally been achieved by just not listing it and the following options here in the first place, but then SPADS refuses to set the modoption", + hidden = true, + type = "section", + }, + { + key = "sub_header", + name = "Hidden map metadata options that are supposed to be set automatically by lobby/spads based on the map name.", + desc = "", + section = "mapmetadata", + type = "subheader", + hidden = true, + def = true, + }, + { + key = "mapmetadata_startpos", + name = "Map Metadata: StartPos", + desc = "StartPos configuration. Format is: base64url(zlib(json))", + hidden = true, + section = "mapmetadata", + type = "string", + def = "", + }, + { + key = "mapmetadata_startboxes_set", + name = "Map Metadata: Startboxes Set", + desc = "Per-team-count startbox arrangements (rect or polygon). Format is: base64url(zlib(json))", + hidden = true, + section = "mapmetadata", + type = "string", + def = "", + }, + { + key = "mapmetadata_startbox_override", + name = "Map Metadata: Startbox Override", + desc = "Custom startbox arrangement that overrides the set when its team count matches. Format is: base64url(zlib(json))", + hidden = true, + section = "mapmetadata", + type = "string", + def = "", + }, + --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + -- Cheats + --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + + { + key = "options_cheats", + name = "Cheats", + desc = "Options that alter the game balance in unintended way, Use at your own risk.", + type = "section", + weight = -1, + }, + + { + key = "sub_header", + name = "Warning: changing these options will alter the intended game experience and may have bad results. Proceed at your own risk!", + desc = "", + section = "options_cheats", + type = "subheader", + def = true, + }, + + { + key = "sub_header", + name = "When any of these options are changed, there is no guarantee they will work properly, especially when combined.", + desc = "", + section = "options_cheats", + type = "subheader", + def = true, + }, + + { + key = "sub_header", + section = "options_cheats", + type = "separator", + }, + + { + key = "sub_header", + name = "-- AI Cheats", + desc = "", + section = "options_cheats", + type = "subheader", + def = true, + }, + + { + key = "dynamiccheats", + name = "Dynamic Cheats", + desc = "Cheats marked as [Dynamic] react to the game state and are suspended when the opposition is losing", + type = "bool", + def = true, + section = "options_cheats", + }, + + { + key = "nowasting", + name = "No Resource Wasting", + desc = "[Dynamic] Increases Buildpower for the affected team's builders and factories to prevent resource", + type = "list", + def = "default", + section = "options_cheats", + items = { + { key= "default", name= "Default", desc="Disabled, unless other features use it"}, + { key= "disabled", name= "Disabled", desc="Disabled"}, + { key= "ai", name= "AI Only", desc="All AI except Scavengers and Raptors"}, + { key= "all", name= "All", desc="AI and Player Teams both excluding Scavengers and Raptors" }, + } + }, + + { + key = "allow_enemy_ai_spawn_placement", + name = "Allow Hostile AI Spawn Placement", + desc = "When enabled, allows enemy allyteams to view and place enemy AI start positions during the pregame", + type = "bool", + def = false, + section = "options_cheats", + }, + + { + key = "sub_header", + section = "options_cheats", + type = "separator", + }, + + { + key = "sub_header", + name = "-- Starting Resources", + desc = "", + section = "options_cheats", + type = "subheader", + def = true, + }, + + { + key = "startmetal", + name = "Starting Metal", + desc = "(Range 0 - 10 000). Determines amount of metal and metal storage that each player will start with", + type = "number", + section = "options_cheats", + def = 1000, + min = 0, + max = 10000, + step = 1, + }, + + { + key = "startmetalstorage", + name = "Starting Metal Storage", + desc = "(Range 1000 - 20 000). Only works if it's higher than Starting metal. Determines amount of metal and metal storage that each player will start with", + type = "number", + section = "options_cheats", + def = 1000, + min = 1000, + max = 20000, + step = 1, + }, + + { + key = "startenergy", + name = "Starting Energy", + desc = "(Range 0 - 10 000). Determines amount of energy and energy storage that each player will start with", + type = "number", + section = "options_cheats", + def = 1000, + min = 0, + max = 10000, + step = 1, + }, + + { + key = "startenergystorage", + name = "Starting Energy Storage", + desc = "(Range 1000 - 20 000). Only works if it's higher than Starting energy. Determines amount of energy and energy storage that each player will start with", + type = "number", + section = "options_cheats", + def = 1000, + min = 1000, + max = 20000, + step = 1, + }, + + { + key = "bonusstartresourcemultiplier", + name = "Apply Bonus to Starting Resources", + desc = "If enabled, multiplies each players starting resources with their bonus.", + type = "bool", + section = "options_cheats", + def = false, + }, + + { + key = "sub_header", + section = "options_cheats", + type = "separator", + }, + + { + key = "sub_header", + name = "-- Resource Multipliers", + desc = "", + section = "options_cheats", + type = "subheader", + def = true, + }, + + { + key = "multiplier_resourceincome", + name = "Overall Resource Income", + desc = "(Range 0.1 - 10). Stacks up with the three options below.", + type = "number", + section = "options_cheats", + def = 1, + min = 0.1, + max = 10, + step = 0.1, + }, + + { + key = "multiplier_metalextraction", + name = "Metal Extraction ", + desc = "(Range 0.1 - 10).", + type = "number", + section = "options_cheats", + def = 1, + min = 0.1, + max = 10, + step = 0.1, + }, + + { + key = "multiplier_energyconversion", + name = "Energy Conversion Efficiency", + desc = "(Range 0.1 - 2). lower means you get less metal per energy converted", + type = "number", + section = "options_cheats", + def = 1, + min = 0.1, + max = 2, + step = 0.1, + }, + + { + key = "multiplier_energyproduction", + name = "Energy Production", + desc = "(Range 0.1 - 10).", + type = "number", + section = "options_cheats", + def = 1, + min = 0.1, + max = 10, + step = 0.1, + }, + + { + key = "sub_header", + section = "options_cheats", + type = "separator", + }, + + { + key = "cheatsdescription7", + name = "-- Unit Parameter Multipliers", + desc = "", + section = "options_cheats", + type = "subheader", + def = true, + }, + + { + key = "multiplier_maxvelocity", + name = "Unit Max Velocity", + desc = "(Range 0.1 - 10).", + type = "number", + section = "options_cheats", + def = 1, + min = 0.1, + max = 10, + step = 0.1, + }, + + { + key = "multiplier_turnrate", + name = "Unit Turn Rate", + desc = "(Range 0.1 - 10).", + type = "number", + section = "options_cheats", + def = 1, + min = 0.1, + max = 10, + step = 0.1, + }, + + { + key = "multiplier_builddistance", + name = "Build Range", + desc = "(Range 0.5 - 10).", + type = "number", + section = "options_cheats", + def = 1, + min = 0.5, + max = 10, + step = 0.1, + }, + + { + key = "multiplier_buildpower", + name = "Build Power", + desc = "(Range 0.1 - 10).", + type = "number", + section = "options_cheats", + def = 1, + min = 0.1, + max = 10, + step = 0.1, + }, + + { + key = "multiplier_losrange", + name = "Vision Range", + desc = "(Range 0.5 - 10).", + type = "number", + section = "options_cheats", + def = 1, + min = 0.5, + max = 10, + step = 0.1, + }, + + { + key = "multiplier_radarrange", + name = "Radar And Sonar Range", + desc = "(Range 0.5 - 10).", + type = "number", + section = "options_cheats", + def = 1, + min = 0.5, + max = 10, + step = 0.1, + }, + + { + key = "multiplier_weaponrange", + name = "Weapon Range", + desc = "(Range 0.5 - 10).", + type = "number", + section = "options_cheats", + def = 1, + min = 0.5, + max = 10, + step = 0.1, + }, + + { + key = "multiplier_weapondamage", + name = "Weapon Damage", + desc = "(Range 0.1 - 10). Also affects unit death explosions.", + type = "number", + section = "options_cheats", + def = 1, + min = 0.1, + max = 10, + step = 0.1, + }, + + { + key = "multiplier_shieldpower", + name = "Shield Power", + desc = "(Range 0.1 - 10)", + type = "number", + section = "options_cheats", + def = 1, + min = 0.1, + max = 10, + step = 0.1, + }, + + { + key = "sub_header", + section = "options_cheats", + type = "separator", + }, + + { + key = "cheatsdescription7", + name = "-- Other", + desc = "", + section = "options_cheats", + type = "subheader", + def = true, + }, + + { + key = "experimentalshields", + name = "Shield Type Override", + desc = "Shield Type Override", + type = "list", + section = "options_cheats", + def = "unchanged", + hidden = true, + items = { + { key = "unchanged", name = "Unchanged", desc = "Unchanged" }, + { key = "absorbeverything", name = "Absorb Everything", desc = "Shields absorb everything" }, + { key = "bounceplasma", name = "Deflect Plasma", desc = "Shields deflect plasma only" }, + { key = "bounceeverything", name = "Deflect Everything", desc = "Shields deflect everything" }, + } + }, + + { + key = "tweakunits", + name = "Tweak Units", + desc = "For advanced users!!! A base64 encoded lua table of unit parameters to change.", + hint = "Input must be base64", + section = "options_cheats", + type = "string", + def = "", + }, + + { + key = "tweakdefs", + name = "Tweak Defs", + desc = "For advanced users!!! A base64 encoded snippet of code that modifies game definitions.", + hint = "Input must be base64", + section = "options_cheats", + type = "string", + def = "", + }, + + { + key = "forceallunits", + name = "Force Load All Units (Dev/Modding)", + desc = "Load all UnitDefs even if ais or options for them aren't enabled", + section = "options_cheats", + type = "bool", + def = false, + }, + + { + key = "holiday_events", + name = "Enable Holiday Events", + desc = "", + section = "options_cheats", + type = "bool", + def = true, + hidden = true, + }, + +} + --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + -- End Options + --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +for i = 1, 9 do + options[#options + 1] = { + key = "tweakunits" .. i, + name = "Tweak Units " .. i, + desc = "A base64 encoded lua table of unit parameters to change.", + section = "options_extra", + type = "string", + def = "", + hidden = true, + } +end + +for i = 1, 9 do + options[#options + 1] = { + key = "tweakdefs" .. i, + name = "Tweak Defs " .. i, + desc = "A base64 encoded snippet of code that modifies game definitions.", + section = "options_extra", + type = "string", + def = "", + hidden = true, + } +end + +return options + +end)() +local VFS={Include=function(path)assert(path=="modoptions.lua");return options end} +if Spring.GetModOptions then + local modOptions = Spring.GetModOptions() + local modOptionsFile = VFS.Include('modoptions.lua') + + for _, modOption in ipairs(modOptionsFile) do + local key = modOption.key + + if modOption.type ~= "section" then + if modOptions[key] == nil then + modOptions[key] = modOption.def + end + + if (modOption.type == 'bool') and (type(modOptions[key]) ~= 'boolean') then + local value = tonumber(modOptions[key]) + modOptions[key] = value == 1 and true or false + end + + if modOption.type == 'number' then + modOptions[key] = tonumber(modOptions[key]) + end + end + end + + -- Prevent widgets from messing with each other's modoptions table. + -- The native engine call does this by returning a new table each time but that is wasteful + local readOnlyModOptions = {} + setmetatable(readOnlyModOptions, { + __index = modOptions, + __newindex = function(t, k, v) + error("attempt to update a read-only Spring.GetModOptions table", 2) + end + }) + + Spring.GetModOptions = function () + return readOnlyModOptions + end + + -- Returns a copy of the modOptions table. Slower, but allows iterating over + -- the returned table using pairs/ipairs. + Spring.GetModOptionsCopy = function () + return table.copy(modOptions) + end +end + +if Spring.Echo then + local echo = Spring.Echo + local printOptions = { pretty = true } + + local function multiEcho(...) + local n = select('#', ...) + local firstTableIndex + local tableCount = 0 + + for index = 1, n do + if type(select(index, ...)) == 'table' then + tableCount = tableCount + 1 + if not firstTableIndex then + firstTableIndex = index + end + end + end + + if tableCount == 0 then + echo(...) + return + end + + -- When Spring.Echo is called with a single table parameter, engine will echo "TABLE: {value}", + -- where {value} is whatever value happens to be the first value in the table + if tableCount == 1 and n == 1 then + echo("") + else + echo(...) + end + + local args = table.pack(...) + for index = firstTableIndex, n do + if type(args[index]) == 'table' then + echo(table.toString(args[index], printOptions)) + end + end + end + + Spring.Echo = multiEcho +end + +Spring.Debug=(function() +local function paramsEcho(...) + local called_from = "Called from: " .. tostring(debug.getinfo(2).name) .. " args:" + Spring.Echo(called_from) + local args = { ... } + Spring.Echo( table.toString(args) ) + return ... +end + +local function traceEcho(...) + local myargs = {...} + local parts = {} + local n = 0 + for i = 1, #myargs do + n = n + 1; parts[n] = tostring(myargs[i]) + n = n + 1; parts[n] = "\t" + end + local infostr = n > 0 and (table.concat(parts) .. " ") or "" + local functionstr = "Trace:[" + for i = 2, 10 do + local info = debug.getinfo(i) + if info then + local funcName = info.name + if funcName then + functionstr = functionstr .. tostring(funcName) .. " <- " + else break end + else break end + end + functionstr = functionstr .. "]" + local arguments = "" + local info2 = debug and debug.getinfo(2) + local funcName1 = (info2 and info2.name) or "??" + if funcName1 ~= "??" then + for i = 1, 10 do + local name, value = debug.getlocal(2, i) + if not name then break end + local sep = ((arguments == "") and "") or "; " + arguments = arguments .. sep .. ((name and tostring(name)) or "name?") .. "=" .. tostring(value) + end + end + Spring.Echo(infostr .. functionstr .. " Args:(" .. arguments .. ")") +end + +local function traceFullEcho(maxdepth, maxwidth, maxtableelements, ...) + -- Call it at any point, and it will give you the name of each function on the stack (up to maxdepth), + -- all arguments and first #maxwidth local variables of that function + -- if any of the values of the locals are tables, then it will try to shallow print + count them up to maxtablelements numbers. + -- It will also just print any args after the first 3. (the ... part) + -- It will also try to print the source file+line of each function + if (debug) then + else + Spring.Echo("traceFullEcho needs debug to work, this seems to be missing or overwritten", debug) + return + end + local tracedebug = false -- to debug itself + local functionsource = true + maxdepth = maxdepth or 16 + maxwidth = maxwidth or 10 + maxtableelements = maxtableelements or 6 -- max amount of elements to expand from table type values + + local function dbgt(t, maxtableelements) + local count = 0 + local res = '' + for k,v in pairs(t) do + count = count + 1 + if count < maxtableelements then + if tracedebug then Spring.Echo(count, k) end + if type(k) == "number" and type(v) == "function" then -- try to get function lists? + local vinfo = debug.getinfo(v) + if tracedebug then Spring.Echo(k,v, vinfo, vinfo.name) end --debug.getinfo(v).short_src)? + res = res .. tostring(k) .. ':' .. ((vinfo and vinfo.name) or "") ..', ' + else + res = res .. tostring(k) .. ':' .. tostring(v) ..', ' + end + end + end + res = '{'..res .. '}[#'..count..']' + return res + end + + local myargs = {...} + local infostr = "TraceFullEcho:[" + for i,v in ipairs(myargs) do + infostr = infostr .. tostring(v) .. "\t" + end + infostr = infostr .. "]\n" + local functionstr = "" -- "Trace:[" + for i = 2, maxdepth do + local info = debug.getinfo(i) + if info then + local funcName = info.name + if funcName then + functionstr = functionstr .. tostring(i-1) .. ": " .. tostring(funcName) .. " " + local arguments = "" + if funcName ~= "??" then + if functionsource and info.source then + local source = info.source + if string.len(source) > 128 then source = "sourcetoolong" end + functionstr = functionstr .. " @" .. source + end + if functionsource and info.linedefined then + functionstr = functionstr .. ":" .. tostring(info.linedefined) + end + for j = 1, maxwidth do + local name, value = debug.getlocal(i, j) + if not name then break end + if tracedebug then Spring.Echo(i,j, funcName,name) end + local sep = ((arguments == "") and "") or "; " + if tostring(name) == 'self' then + arguments = arguments .. sep .. ((name and tostring(name)) or "name?") .. "=" .. tostring("??") + else + local newvalue + if maxtableelements > 0 and type({}) == type(value) then newvalue = dbgt(value, maxtableelements) else newvalue = value end + arguments = arguments .. sep .. ((name and tostring(name)) or "name?") .. "=" .. tostring(newvalue) + end + end + end + functionstr = functionstr .. " Locals:(" .. arguments .. ")" .. "\n" + else + functionstr = functionstr .. tostring(i-1) .. ": ??\n" + end + else break end + end + Spring.Echo(infostr .. functionstr) +end + +return { + ParamsEcho = paramsEcho, + TraceEcho = traceEcho, + TraceFullEcho = traceFullEcho, +} +end)() +-- Graphics-only compatibility storage for original policy. No drawing, engine +-- buffer upload, commands, VFS/IO, configuration or selection mutation. +local function noop()end +WG={};LOG={DEPRECATED=0} +GL={ARRAY_BUFFER=34962,UNSIGNED_INT=5125,POINTS=0,TRIANGLES=4,TRIANGLE_STRIP=5} +local storage={Define=noop,Upload=noop,Delete=noop,InstanceDataFromUnitIDs=noop,InstanceDataFromFeatureIDs=noop,GetID=function()return 1 end} +local vao={AttachVertexBuffer=noop,AttachInstanceBuffer=noop,AttachIndexBuffer=noop,DrawArrays=noop,DrawElements=noop,Delete=noop} +local shader={Activate=noop,Deactivate=noop,SetUniform=noop} +local unitUniforms,featureUniforms={},{} +local function uniforms(target,id,values,offset) + assert(type(id)=='number'and id>=0 and id%1==0 and type(values)=='table','Invalid original healthbar uniform write') + offset=math.max(offset or 0,0);local count=math.min(#values,16-offset) + if count<1 then return 0 end + local row=target[id];if not row then row={};for i=1,16 do row[i]=0 end;target[id]=row end + for i=1,count do row[offset+i]=values[i]end + return count +end +gl={GetVBO=function()return setmetatable({},{__index=storage})end,GetVAO=function()return setmetatable({},{__index=vao})end, + CreateShader=noop,LuaShader={isGeometryShaderSupported=true,CheckShaderUpdates=function()return shader end}, + SetUnitBufferUniforms=function(id,values,offset)return uniforms(unitUniforms,id,values,offset)end, + SetFeatureBufferUniforms=function(id,values,offset)return uniforms(featureUniforms,id,values,offset)end} +-- This handle supplies policy to a graphical browser. Headless GL calls are +-- replaced by private storage, so the original forwarder can retain its writes. +Spring.GetConfigInt=function(name,default)if name=='Headless'then return 0 end;return default or 0 end +Spring.GetViewGeometry=function()return 1280,720 end +local removed=false +widgetHandler={RegisterGlobal=noop,DeregisterGlobal=noop,AddAction=noop,RemoveAction=noop,RemoveWidget=function()removed=true end,AddSpadsMessage=noop} +local listeners,actions={},{} +local widgetEventUnit,widgetEventLos +Script.LuaUI=setmetatable({},{__call=function(_,name)return listeners[name]~=nil end,__index=function(_,name)return function(...)return assert(listeners[name],'Unbound original healthbar LuaUI callback '..name)(...)end end}) +gadgetHandler={IsSyncedCode=function()return false end,AddSyncAction=function(_,name,fn)assert(not actions[name]);actions[name]=fn end,RemoveSyncAction=function(_,name)actions[name]=nil end} + +-------------------------------------------------------------------------------- +-------------------------------------------------------------------------------- +-- +-- file: setupdefs.lua +-- brief: setup some custom UnitDefs parameters, +-- and UnitDefNames, FeatureDefNames, WeaponDefNames +-- author: Dave Rodgers +-- +-- Copyright (C) 2007. +-- Licensed under the terms of the GNU GPL, v2 or later. +-- +-------------------------------------------------------------------------------- +-------------------------------------------------------------------------------- + +for _,ud in pairs(UnitDefs) do + -- set the cost value (same as shown in the tooltip) + ud.cost = ud.metalCost + (ud.energyCost / 60.0) + + -- add the custom weapons based parameters + ud.hasShield = false + ud.canParalyze = false + ud.canStockpile = false + ud.canAttackWater = false + ud.wDefs = {} + for i, wt in ipairs(ud.weapons) do + local wd = WeaponDefs[wt.weaponDef] + ud.wDefs[i] = wd + if (wd) then + if (wd.isShield) then ud.hasShield = true end + if (wd.paralyzer) then ud.canParalyze = true end + if (wd.stockpile) then ud.canStockpile = true end + if (wd.waterWeapon) then ud.canAttackWater = true end + end + end +end + +-------------------------------------------------------------------------------- +-------------------------------------------------------------------------------- + +-- setup the UnitDefNames{} table +do + local tbl = {} + for _,def in pairs(UnitDefs) do + tbl[def.name] = def + end + UnitDefNames = tbl +end + +-- setup the FeatureDefNames{} table +do + local tbl = {} + for _,def in pairs(FeatureDefs) do + tbl[def.name] = def + end + FeatureDefNames = tbl +end + +-- setup the WeaponDefNames{} table +do + local tbl = {} + for _,def in pairs(WeaponDefs) do + tbl[def.name] = def + end + WeaponDefNames = tbl +end + +-------------------------------------------------------------------------------- +-------------------------------------------------------------------------------- + + +gl.InstanceVBOTable=(function() +local GL_BUFFER = 0x82E0 +local gldebugannotations = (Spring.GetConfigInt("gldebugannotations") == 1) +--Spring.Echo("gldebugannotations", gldebugannotations) +local function makeInstanceVBOTable(layout, maxElements, myName, unitIDattribID) + -- layout: this must be an array of tables with at least the following specified: {{id = 1, name = 'optional', size = 4}} + -- maxElements: will be dynamic anyway, but defaults to 64 + -- myName: optional name, useful for debugging + -- unitIDattribID: the attribute ID in the layout of the uvec4 of unitID bindings (e.g. 4 for {id = 4, name = 'instData', type = GL.UNSIGNED_INT, size= 4} ) + -- returns: nil | instanceTable + if maxElements == nil then maxElements = 64 end -- default size + if myName == nil then myName = "InstanceVBOTable" end + local newInstanceVBO = gl.GetVBO(GL.ARRAY_BUFFER,true) + if newInstanceVBO == nil then Spring.Echo("makeInstanceVBOTable, cannot get VBO for", myName); return nil end + newInstanceVBO:Define( + maxElements, + layout + ) + + + + local instanceStep = 0 + for i,attribute in pairs(layout) do + instanceStep = instanceStep + attribute.size + end + local instanceData = {} + for i = 1, instanceStep * maxElements do + instanceData[i] = 0 + end + local instanceTable = { + instanceVBO = newInstanceVBO, + instanceData = instanceData, + instanceStep = instanceStep, + usedElements = 0, + maxElements = maxElements, + myName = myName, + instanceIDtoIndex = {}, -- this maps each instance ID to where it is in the buffer, 1 based + indextoInstanceID = {}, -- this tells us what instanceID is located in any given pos + layout = layout, + dirty = false, + numVertices = 0, + primitiveType = GL.TRIANGLES, + debugZombies = true, -- this is new, and its for debugging non-existing stuff on unitdestroyed + lastInstanceID = 0, + } + + if unitIDattribID ~= nil then + instanceTable.indextoUnitID = {} + instanceTable.unitIDattribID = unitIDattribID + instanceTable.popUnitIDFailuresInGameFrame = {} + end + + function instanceTable:clearInstanceTable() + -- this wont resize it, but quickly sets it to empty + self.usedElements = 0 + self.instanceIDtoIndex = {} + self.indextoInstanceID = {} + if self.indextoUnitID then self.indextoUnitID = {} end + end + + function instanceTable:makeVAOandAttach(vertexVBO, instanceVBO, indexVBO) -- Attach a vertex buffer to an instance buffer, and optionally, an index buffer if one is supplied. + -- There is a special case for this, when we are using a vertexVBO as a quasi-instanceVBO, e.g. when we are using the geometry shader to draw a vertex as each instance. + --iT.vertexVBO = vertexVBO + --iT.indexVBO = indexVBO + local newVAO = nil + newVAO = gl.GetVAO() + if newVAO == nil then goodbye("Failed to create newVAO") end + self.VAO = newVAO + if vertexVBO == nil then -- the special case where are using 'vertices' as 'instances' + newVAO:AttachVertexBuffer(instanceVBO) + else + newVAO:AttachVertexBuffer(vertexVBO) + newVAO:AttachInstanceBuffer(instanceVBO) + self.vertexVBO = vertexVBO + self.instanceVBO = instanceVBO + end + if indexVBO then + newVAO:AttachIndexBuffer(indexVBO) + self.indexVBO = indexVBO + function self:Draw() + self.VAO:DrawElements(GL.TRIANGLES, nil, 0, self.usedElements, 0) + end + else + function self:Draw() + self.VAO:DrawArrays(GL.TRIANGLES, nil, 0, self.usedElements, 0) + end + end + return newVAO + end + + function instanceTable:clearInstanceTable() + -- this wont resize it, but quickly sets it to empty + self.usedElements = 0 + self.instanceIDtoIndex = {} + self.indextoInstanceID = {} + if self.indextoUnitID then self.indextoUnitID = {} end + end + + function instanceTable:compact() + self.destroyedElements = 0 + -- so this is for the edge case, where we have silently removed elements from instanceIDtoIndex + -- where we have holes everywhere, so we have to 'compact' the table, + -- by copying back contiguously while preserving element order + local newInstanceIDtoIndex = {} + local newIndexToInstanceID = {} + local newInstanceData = {} + local newUsedElements = 0 + for i = 1, self.usedElements do + local instanceID = self.indextoInstanceID[i] + local index = self.instanceIDtoIndex[self.indextoInstanceID[i]] + if index then + local instanceStep = self.instanceStep + local instanceData = self.instanceData + + local dstpos = newUsedElements * instanceStep + local srcpos = (i - 1) * instanceStep + for j=1, instanceStep do + newInstanceData[dstpos + j] = instanceData[srcpos +j] + end + newUsedElements = newUsedElements + 1 + newInstanceIDtoIndex[instanceID] = newUsedElements + newIndexToInstanceID[newUsedElements] = instanceID + else + --Spring.Echo("compacting index",i, 'instanceID', instanceID) + end + end + --Spring.Echo("Post compacting", self.usedElements, newUsedElements) + self.usedElements = newUsedElements + self.instanceIDtoIndex = newInstanceIDtoIndex + self.indextoInstanceID = newIndexToInstanceID + self.instanceData = newInstanceData + --iT.instanceVBO:Upload(iT.instanceData,nil,oldElementIndex-1,oldOffset +1,oldOffset + iTStep) + if self.usedElements > 0 then + self.instanceVBO:Upload(self.instanceData) + end + end + + + function instanceTable:draw(primitiveType) + if self.usedElements > 0 then + if self.indexVBO then + self.VAO:DrawElements(primitiveType or self.primitiveType, self.numVertices, 0, self.usedElements,0) + else + self.VAO:DrawArrays (primitiveType or self.primitiveType, self.numVertices, 0, self.usedElements,0) + end + end + end + + function instanceTable:getMemUsage() + -- arrays are 16 bytes per element + -- Hash tables are 40 bytes per element + local totalMem = 0 + totalMem = totalMem + self.usedElements * self.instanceStep * 16 -- the actual instance data + totalMem = totalMem + self.usedElements * 16 -- indextoinstanceid + totalMem = totalMem + self.usedElements * 40 -- instanceIDtoIndex + if self.indextoUnitID then totalMem = totalMem + self.usedElements * 16 end + return totalMem + end + + function instanceTable:Delete() + -- Frees the instancevbo and vao for this instance table. Does not touch the vertex and index vbos. + -- returns an estimate of how much ram was used + if self.instanceVBO then self.instanceVBO:Delete() end + if self.VAO then self.VAO:Delete() end + local memusage = self:getMemUsage() + self:clearInstanceTable() + return memusage + end + + + newInstanceVBO:Upload(instanceData) + + -- I believe that the openGL spec doesnt guarantee that a buffer has an idea before data is uploaded to it, so we will fill it with zeros. + if gldebugannotations then + gl.ObjectLabel(GL_BUFFER, newInstanceVBO:GetID(), myName) + end + + + --register self in WG if possible + if WG then + if WG.VBOTableRegistry == nil then + --Spring.Echo("WG.VBORegistry == nil, creating registry on first load") + WG.VBOTableRegistry = {} + end + if WG.VBOTableRegistry[instanceTable.myName] then + local newname = instanceTable.myName .. tostring(math.random()) + --Spring.Echo(instanceTable.myName, 'already registered, renaming to', newname) + instanceTable.myName = newname + end + --Spring.Echo("Registered ", instanceTable.myName) + WG.VBOTableRegistry[instanceTable.myName] = instanceTable + end + + return instanceTable +end + +local function nextInstanceID(iT) + iT.lastInstanceID = iT.lastInstanceID + 1 + return iT.lastInstanceID +end + +local function clearInstanceTable(iT) + -- this wont resize it, but quickly sets it to empty + iT.usedElements = 0 + iT.instanceIDtoIndex = {} + iT.indextoInstanceID = {} + if iT.indextoUnitID then iT.indextoUnitID = {} end +end + +local function makeVAOandAttach(vertexVBO, instanceVBO, indexVBO) -- Attach a vertex buffer to an instance buffer, and optionally, an index buffer if one is supplied. + -- There is a special case for this, when we are using a vertexVBO as a quasi-instanceVBO, e.g. when we are using the geometry shader to draw a vertex as each instance. + --iT.vertexVBO = vertexVBO + --iT.indexVBO = indexVBO + local newVAO = nil + newVAO = gl.GetVAO() + if newVAO == nil then goodbye("Failed to create newVAO") end + if vertexVBO == nil then -- the special case where are using 'vertices' as 'instances' + newVAO:AttachVertexBuffer(instanceVBO) + else + newVAO:AttachVertexBuffer(vertexVBO) + newVAO:AttachInstanceBuffer(instanceVBO) + end + if indexVBO then + newVAO:AttachIndexBuffer(indexVBO) + end + -- this allows us to set up our sane + + + return newVAO +end + + +--------------- DEBUG HELPERS -------------------------- +local function comparetables(t1, t2, name) + for k,v in pairs(t1) do + if t2[k] == nil then + Spring.Echo("Key ",k,"with value",v,"existing in t1 does not exist in t2 in ", name) + elseif t2[k] ~= v then + Spring.Echo("Value ",v,"for",k,"existing in t1 does not match value for t2",t2[k]," in ", name) + end + end + + for k,v in pairs(t2) do + if t1[k] == nil then + Spring.Echo("Key ",k,"with value",v,"existing in t2 does not exist in t1 in ", name) + elseif t1[k] ~= v then + Spring.Echo("Value ",v,"for",k,"existing in t2 does not match value for t1",t1[k]," in ", name) + end + end +end + +local function dbgt(t, name) + name = name or "" + local gf = Spring.GetGameFrame() + local count = 0 + local res = '' + for k,v in pairs(t) do + if type(k) == 'number' and type(v) == 'number' then + res = res .. tostring(k) .. ':' .. tostring(v) ..',' + count = count + 1 + end + end + Spring.Echo(tostring(gf).. " " ..name .. ' #' .. tostring(count) .. ' {'..res .. '}') + return res +end + +local function counttable(t) + local count = 0 + if type(t) ~= type({}) then return 0 end + for k, v in pairs(t) do count = count + 1 end + return count +end + +local function validateInstanceVBOTable(iT, calledfrom) + -- check that instanceIDtoIndex and indextoInstanceID are valid and contigous: + for i=1, iT.usedElements do + if iT.indextoInstanceID[i] == nil then + Spring.Echo("There is a hole in indextoInstanceID", iT.myName, "at", i,"out of",iT.usedElements, calledfrom) + --Spring.Echo() + if iT.indextoUnitID[i] == nil then + Spring.Echo("It is also missing from indextoUnitID") + else + Spring.Echo("But it does exist in indextoUnitID with an unitID of ", iT.indextoUnitID[i]) + Spring.Echo("This is valid?", Spring.GetUnitPosition(iT.indextoUnitID[i])) + end + + else + local instanceID = iT.indextoInstanceID[i] + if iT.instanceIDtoIndex[instanceID] == nil then + Spring.Echo("There is a hole instanceIDtoIndex", iT.myName, "at", i," iT.instanceIDtoIndex[instanceID] == nil ") + elseif iT.instanceIDtoIndex[instanceID] ~= i then + Spring.Echo("There is a problem in indextoInstanceID", iT.myName, "at i =", i," iT.indextoInstanceID[instanceID] ~= i, it is instead: ", iT.indextoInstanceID[instanceID] ) + end + end + end + local indextoInstanceIDsize = counttable(iT.indextoInstanceID) + local instanceIDtoIndexsize = counttable(iT.instanceIDtoIndex) + local indextoUnitID = counttable(iT.indextoUnitID) + if (indextoInstanceIDsize ~= instanceIDtoIndexsize) or (instanceIDtoIndexsize ~= indextoUnitID) then + Spring.Echo("Table size mismatch during validation of", iT.myName, indextoInstanceIDsize, instanceIDtoIndexsize, indextoUnitID) + end + +end + +function locateInvalidUnits(iT) + if iT.validinfo == nil then iT.validinfo = {} end + local invalidcount = 0 + for i, unitID in ipairs(iT.indextoUnitID) do + if iT.featureIDs then + if Spring.ValidFeatureID(unitID) then + local px, py, pz = Spring.GetFeaturePosition(unitID) + local fdefname = FeatureDefs[Spring.GetFeatureDefID(unitID)].name + iT.validinfo[unitID] = {px = px, py = py, pz = pz, fdefname = fdefname} + else + Spring.SendCommands({"pause 1"}) + Spring.Echo("INVALID feature, last seen at", unitID) + local vi = iT.validinfo[unitID] + local markertext = tostring(unitID) .. "," .. dbgt(vi) + Spring.MarkerAddPoint(vi.px, vi.py, vi.pz, markertext ) + invalidcount = invalidcount + 1 + end + else + if Spring.ValidUnitID(unitID) then + local px, py, pz = Spring.GetUnitPosition(unitID) + local unitDefID = Spring.GetUnitDefID(unitID) + local unitdefname = (unitDefID and UnitDefs[unitDefID].name) or "unknown:nil" + iT.validinfo[unitID] = {px = px, py = py, pz = pz, unitdefname = unitdefname} + else + Spring.SendCommands({"pause 1"}) + Spring.Echo(iT.myName, " INVALID unitID",unitID,"#elements", iT.usedElements, "last seen at tablepos:", i) + + local vi = iT.validinfo[unitID] + local markertext = tostring(unitID) .. "," .. dbgt(vi) + Spring.MarkerAddPoint(vi.px, vi.py, vi.pz, markertext ) + invalidcount = invalidcount + 1 + end + end + end + return invalidcount +end + +------------------------------END DEBUG HELPERS --------------------------- + +local function resizeInstanceVBOTable(iT) + -- iT: the InstanceVBOTable to double in size 'dynamically' resize the VBO, to double its size + -- this is called automatically when the existing instanceVBO gets full + -- Also performs a busload of sanity checking + -- Spring.Echo("instanceVBOTable full, resizing to double size",iT.myName, iT.usedElements,iT.maxElements) + iT.maxElements = iT.maxElements * 2 + local newInstanceVBO = gl.GetVBO(GL.ARRAY_BUFFER,true) + newInstanceVBO:Define(iT.maxElements, iT.layout) + + if iT.instanceVBO then iT.instanceVBO:Delete() end -- release if previous one existed + iT.instanceVBO = newInstanceVBO + -- ok this needs some sanitation right here, with reporting. + if iT.indextoUnitID then + -- we need to walk through both tables at the same time, and virtually pop all invalid unit/featureIDs on a resize, or else face dire consequences (crashes) later on + -- the tables we need to keep updated are: + local new_instanceData = {} + local new_instanceData_count = 0 + local new_usedElements = 0 + local new_instanceIDtoIndex = {} + local new_indextoInstanceID = {} + local new_indextoUnitID = {} + local invalidcount = 0 + local iTStep = iT.instanceStep + + for i, objectID in ipairs(iT.indextoUnitID) do + local isValidID = false + if iT.featureIDs then isValidID = Spring.ValidFeatureID(objectID) + else isValidID = Spring.ValidUnitID(objectID) end + if isValidID then + local offset = new_usedElements * iTStep + for j = 1, iTStep do + new_instanceData_count = new_instanceData_count + 1 + new_instanceData[new_instanceData_count] = iT.instanceData[j + offset] + end + new_usedElements = new_usedElements + 1 + local currentInstanceID = iT.indextoInstanceID[i] + new_indextoInstanceID[new_usedElements] = iT.indextoInstanceID[i] + new_indextoUnitID[new_usedElements] = iT.indextoUnitID[i] + new_instanceIDtoIndex[currentInstanceID] = new_usedElements + --Spring.Echo("Resize:",currentInstanceID, iT.indextoUnitID[i] ) + invalidcount = invalidcount + 1 + else + Spring.Echo("Warning: Found invalid unit/featureID",objectID,"at",i,"while resizing",iT.myName) + end + end + + if invalidcount == 0 then + comparetables( iT.instanceData, new_instanceData, "instanceData") + comparetables( iT.instanceIDtoIndex, new_instanceIDtoIndex, "instanceIDtoIndex") + comparetables( iT.indextoInstanceID, new_indextoInstanceID, "indextoInstanceID") + comparetables( iT.indextoUnitID, new_indextoUnitID, "indextoUnitID") + end + + iT.instanceData = new_instanceData + iT.usedElements = new_usedElements + iT.instanceIDtoIndex = new_instanceIDtoIndex + iT.indextoInstanceID = new_indextoInstanceID + iT.indextoUnitID = new_indextoUnitID + end + + iT.instanceVBO:Upload(iT.instanceData,nil,0,1,iT.usedElements * iT.instanceStep) + + if gldebugannotations then + gl.ObjectLabel(GL_BUFFER, iT.instanceVBO:GetID(), iT.myName) + end + + if iT.VAO then -- reattach new if updated :D + iT.VAO:Delete() + iT.VAO = makeVAOandAttach(iT.vertexVBO,iT.instanceVBO, iT.indexVBO) + end + + if iT.indextoUnitID then + if iT.featureIDs then + iT.instanceVBO:InstanceDataFromFeatureIDs(iT.indextoUnitID, iT.unitIDattribID) + else + iT.instanceVBO:InstanceDataFromUnitIDs(iT.indextoUnitID, iT.unitIDattribID) + end + end + return iT.maxElements +end + +--[[ from Ivand: +instVBO:Upload({ + 100, 0, 0, + -100, 0, 0, + 0, 0, 100, + 0, 0, -100, + }, 7, 1, 4, 6) +Here is how you upload starting from 1st element and starting from 4th element in Lua array (-100) and finishing with 6th element (0), essentially it will upload (-100, 0, 0) into 7th attribute of 2nd instance. +]]-- + +local function pushElementInstance(iT,thisInstance, instanceID, updateExisting, noUpload, unitID) + -- iT: instanceTable created with makeInstanceTable + -- thisInstance: is a lua array of values to add to table, MUST BE INSTANCESTEP SIZED LUA ARRAY + -- instanceID: an optional key given to the item, so it can be easily removed/updated by reference, defaults to the index of the instance in the buffer (1 based) + -- updateExisting: allow updating an existing element (same instanceID key) + -- noUpload: prevent the VBO from being uploaded, if you feel like you are going to do a lot of ops and wish to manually upload when done instead + -- unitID: if given, it will store then unitID corresponding to this instance, and will try to update the InstanceDataFromUnitIDs for this unit + -- returns: the index of the instanceID in the table on success, else nil + if #thisInstance ~= iT.instanceStep then + Spring.Echo("Trying to upload an oddly sized instance into",iT.myName, #thisInstance, "instead of ",iT.instanceStep) + Spring.Debug.TraceFullEcho(20,20,20, "pushElementInstance Failure:"..iT.myName ) + end + local iTusedElements = iT.usedElements + local iTStep = iT.instanceStep + local endOffset = iTusedElements * iTStep + if instanceID == nil then instanceID = nextInstanceID(iT) end + local thisInstanceIndex = iT.instanceIDtoIndex[instanceID] + + if (iTusedElements + 1 ) >= iT.maxElements then -- add 1 extra for safety (not the best idea, but we seem to be running over it by 1) + resizeInstanceVBOTable(iT) + iTusedElements = iT.usedElements -- because during validation of unitIDs during resizing, we can decrease the actual size of the table! + thisInstanceIndex = iT.instanceIDtoIndex[instanceID] -- this too, can change, TODO, also do this in VBOIDtable! + end + + if thisInstanceIndex == nil then -- new, register it + thisInstanceIndex = iTusedElements + 1 + iT.usedElements = iTusedElements + 1 + iT.instanceIDtoIndex[instanceID] = thisInstanceIndex + iT.indextoInstanceID[thisInstanceIndex] = instanceID + else -- pre-existing ID, update or bail + if updateExisting == nil then + Spring.Echo("Tried to add existing element to an instanceTable",iT.myName, instanceID) + return nil + else + endOffset = (thisInstanceIndex - 1) * iTStep + end + end + local instanceData = iT.instanceData + for i =1, iTStep do -- copy data, but fast + instanceData[endOffset + i] = thisInstance[i] + end + + if unitID ~= nil then + local isvalidid + if iT.featureIDs then isvalidid = Spring.ValidFeatureID(unitID) + else isvalidid = Spring.ValidUnitID(unitID) end + if isvalidid == false then + Spring.Echo("Error: Attempted to push an invalid unit/featureID",unitID, "into", iT.myName) + noUpload = true + Spring.Debug.TraceFullEcho(20,20,20,"invalid unit/featureID in " ..iT.myName) + end + iT.indextoUnitID[thisInstanceIndex] = unitID + end + + if noUpload ~= true then --upload or mark as dirty + iT.instanceVBO:Upload(thisInstance, nil, thisInstanceIndex - 1) + --Spring.Echo("pushElementInstance,unitID, iT.unitIDattribID, thisInstanceIndex",unitID, iT.unitIDattribID, thisInstanceIndex) + if unitID ~= nil then + if iT.featureIDs then + iT.instanceVBO:InstanceDataFromFeatureIDs(unitID, iT.unitIDattribID, thisInstanceIndex-1) + else + iT.instanceVBO:InstanceDataFromUnitIDs(unitID, iT.unitIDattribID, thisInstanceIndex-1) + end + end + else + iT.dirty = true + end + + if iT.debug then validateInstanceVBOTable(iT, 'push') end + return instanceID +end + +local function popElementInstance(iT, instanceID, noUpload) + -- iT: instanceTable created with makeInstanceTable + -- instanceID: an optional key given to the item, so it can be easily removed by reference, defaults to the last element of the buffer, but this will screw up the instanceIDtoIndex table if used in mixed keys mode + -- noUpload: prevent the VBO from being uploaded, if you feel like you are going to do a lot of ops and wish to manually upload when done instead + -- returns nil on failure, the the index of the element on success + if instanceID == nil then + Spring.Echo("Tried to remove element with nil instanceID from instanceTable " .. iT.myName) + return nil + end + + if iT.instanceIDtoIndex[instanceID] == nil then -- if key is instanceID yet does not exist, then warn and bail + Spring.Echo("Tried to remove element ",instanceID,'From instanceTable', iT.myName, 'but it does not exist in it') + Spring.Debug.TraceFullEcho(10,10,3, iT.myName) + return nil + end + if iT.usedElements == 0 then -- Dont remove the last element + Spring.Echo("Tried to remove element ",instanceID,'From instanceTable', iT.myName, 'but it should be empty') + return nil + end + + --Fetch the position of the element we want to remove from the 'middle' of the table + local oldElementIndex = iT.instanceIDtoIndex[instanceID] + iT.instanceIDtoIndex[instanceID] = nil -- clean these out + iT.indextoInstanceID[oldElementIndex] = nil + + -- get the index of the last element + local lastElementIndex = iT.usedElements + + -- if this one was already at the end of the queue, do nothing but decrement usedElements and clear mappings + if oldElementIndex == lastElementIndex then + --Spring.Echo("Removed end element of instanceTable", iT.myName) + iT.usedElements = iT.usedElements - 1 + -- if it had a related unitID stored, remove that: + if iT.indextoUnitID then iT.indextoUnitID[oldElementIndex] = nil end + + if iT.debugZombies then + if iT.zombies and iT.zombies[instanceID] then + --Spring.Echo("Good, we are killing a stupid zombie at the end", instanceID, iT.numZombies) + iT.zombies[instanceID] = nil + iT.numZombies = iT.numZombies - 1 + end + end + + else + local lastElementInstanceID = iT.indextoInstanceID[lastElementIndex] + if lastElementInstanceID == nil then -- + Spring.Echo("We somehow have a nil element at the back of the array, which is completely invalid, probably about to crash", iT.myName) + dbgt(iT.instanceIDtoIndex, "instanceIDtoIndex") + dbgt(iT.indextoInstanceID, "indextoInstanceID") + dbgt(iT.indextoUnitID, "indextoUnitID") + end + local iTStep = iT.instanceStep + local endOffset = (iT.usedElements - 1)*iTStep + + iT.instanceIDtoIndex[lastElementInstanceID] = oldElementIndex -- lastElementInstanceID was somehow nil here? + iT.indextoInstanceID[oldElementIndex] = lastElementInstanceID + iT.indextoInstanceID[lastElementIndex] = nil --- somehow this got forgotten? TODO for VBOIDtable + + local oldOffset = (oldElementIndex-1)*iTStep + local instanceData = iT.instanceData + for i = 1, iTStep do + instanceData[oldOffset + i ] = instanceData[endOffset + i] + end + --size_t LuaVBOImpl::Upload(const sol::stack_table& luaTblData, const sol::optional attribIdxOpt, const sol::optional elemOffsetOpt, const sol::optional luaStartIndexOpt, const sol::optional luaFinishIndexOpt) + --Spring.Echo("Removing instanceID",instanceID,"from iT at position", oldElementIndex, "shuffling back at", iT.usedElements,"endoffset=",endOffset,'oldOffset=',oldOffset) + if noUpload ~= true then + --Spring.Echo("Upload", oldElementIndex -1, oldOffset+1, oldOffset+iTStep) + iT.instanceVBO:Upload(iT.instanceData,nil,oldElementIndex-1,oldOffset +1,oldOffset + iTStep) + else + iT.dirty = true + end + -- Do the unitID shuffle if needed: + if iT.indextoUnitID then + --Spring.Echo("popElementInstance,unitID, iT.unitIDattribID, thisInstanceIndex",unitID, iT.unitIDattribID, oldElementIndex) + local popunitID = iT.indextoUnitID[lastElementIndex] + if popunitID == nil then + Spring.Echo("TODO: what the f is happening here?, how the f could we have popped a nil from the back of?", iT.myName) -- TODO TODO + end + + if iT.debugZombies then + local gf = Spring.GetGameFrame() + --Spring.Echo("Popping", instanceID) + if iT.lastpopgameframe == nil then + iT.lastpopgameframe = gf + iT.zombies = {} + iT.numZombies = 0 + else + if iT.lastpopgameframe ~= gf then -- New gameframe + iT.lastpopgameframe = gf + if iT.numZombies and iT.numZombies > 0 then -- WE HAVE ZOMBIES AAAAARGH + local s = "Warning: We have " .. tostring(iT.numZombies) .. " zombie units left over in " .. iT.myName + for zombie, gf in pairs(iT.zombies) do + s = s .. " " .. tostring(zombie) ..'/'..tostring(gf) + Spring.Echo("ZOMBIE instanceID", zombie, 'gf',gf) + --Spring.SendCommands({"pause 1"}) + Spring.Debug.TraceFullEcho(nil,nil,nil, iT.myName) + end + Spring.Echo(s) + iT.zombies = {} + iT.numZombies = 0 + end + else -- same gameframe + if iT.zombies[instanceID] then + --Spring.Echo("Good, we are killing a stupid zombie", gf, instanceID, iT.numZombies) + iT.zombies[instanceID] = nil + iT.numZombies = iT.numZombies - 1 + end + end + end + end + + iT.indextoUnitID[oldElementIndex] = popunitID + iT.indextoUnitID[lastElementIndex] = nil + + if (iT.featureIDs and Spring.ValidFeatureID(popunitID)) or Spring.ValidUnitID(popunitID) then + if noUpload ~= true then + if iT.featureIDs then + iT.instanceVBO:InstanceDataFromFeatureIDs(popunitID, iT.unitIDattribID, oldElementIndex-1) + else + iT.instanceVBO:InstanceDataFromUnitIDs(popunitID, iT.unitIDattribID, oldElementIndex-1) + end + end + else + if iT.debugZombies then + --Spring.Echo("Warning: Tried to pop back an invalid" .. ((iT.featureIDs and "featureID") or "unitID"), popunitID, "from", iT.myName, "while removing instance", instanceID, counttable(iT.instanceIDtoIndex), counttable(iT.indextoInstanceID), counttable(iT.indextoUnitID)) + --Spring.Debug.TraceFullEcho() + local gf = Spring.GetGameFrame() + if iT.lastpopgameframe == nil or iT.lastpopgameframe ~= gf then -- New gameframe + iT.lastpopgameframe = gf + iT.zombies = {} + iT.numZombies = 0 + end + if iT.zombies[lastElementInstanceID] == nil then + iT.zombies[lastElementInstanceID] = gf + iT.numZombies = iT.numZombies + 1 + end + end + end + end + iT.usedElements = iT.usedElements - 1 + end + + if iT.debug then validateInstanceVBOTable(iT,'pop') end + return oldElementIndex +end + +local function getElementInstanceData(iT, instanceID, cacheTable) + -- iT: instanceTable created with makeInstanceTable + -- instanceID: an optional key given to the item, so it can be easily removed by reference, defaults to the index of the instance in the buffer (1 based) + local instanceIndex = iT.instanceIDtoIndex[instanceID] + if instanceIndex == nil then + Spring.Echo("Tried to getElementInstanceData from",iT.myName,instanceID, "but it does not exist") + return nil + end + local iData = cacheTable or {} + local iTStep = iT.instanceStep + instanceIndex = (instanceIndex-1) * iTStep + local instanceData = iT.instanceData + for i = 1, iTStep do + iData[i] = instanceData[instanceIndex + i] + end + return iData +end + +local function uploadAllElements(iT) + -- upload all USED elements + if iT.usedElements == 0 then return end + + iT.instanceVBO:Upload(iT.instanceData,nil,0, 1, iT.usedElements * iT.instanceStep) + iT.dirty = false + if iT.indextoUnitID then + if iT.featureIDs then + iT.instanceVBO:InstanceDataFromFeatureIDs(iT.indextoUnitID, iT.unitIDattribID) + else + iT.instanceVBO:InstanceDataFromUnitIDs(iT.indextoUnitID, iT.unitIDattribID) + end + end +end + +local function uploadElementRange(iT, startElementIndex, endElementIndex) + iT.instanceVBO:Upload(iT.instanceData, -- The lua mirrored VBO data + nil, -- the attribute index, nil for all attributes + startElementIndex, -- vboOffset optional, , what ELEMENT offset of the VBO to start uploading into, 0 based + startElementIndex * iT.instanceStep + 1, -- luaStartIndex, default 1, what element of the lua array to start uploading from. 1 is the 1st element of a lua table. + endElementIndex * iT.instanceStep --] luaEndIndex, default #{array}, what element of the lua array to upload up to, inclusively + ) + if iT.indextoUnitID then + --we need to reslice the table + local unitIDRange = {} + local indextoUnitID = iT.indextoUnitID + for i = startElementIndex, endElementIndex do + unitIDRange[#unitIDRange + 1] = indextoUnitID[i] + end + if iT.featureIDs then + iT.instanceVBO:InstanceDataFromFeatureIDs(unitIDRange, iT.unitIDattribID, startElementIndex - 1) + else + iT.instanceVBO:InstanceDataFromUnitIDs(unitIDRange, iT.unitIDattribID, startElementIndex - 1) + end + end +end + +-- This function allows for order-preserving compacting of a list of instances based on these funcs. +-- It is designed for Decals GL4, where draw order matters a lot! +-- remove takes priority over keep +local function compactInstanceVBO(iT, removelist, keeplist) + local usedElements = iT.usedElements + if usedElements == 0 then return 0 end + local instanceStep = iT.instanceStep + local instanceData = iT.instanceData + local indextoInstanceID = iT.indextoInstanceID + local newindextoInstanceID = {} + local newinstanceIDtoIndex = {} + local newUsedElements = 0 + local numremoved = 0 + local removemode = (removelist ~= nil) and (keeplist == nil) + for index, instanceID in ipairs(indextoInstanceID) do + -- If its in keeplist, + if (removemode and (removelist[instanceID]== nil) ) or ((removemode == false) and keeplist[instanceID]) then + local instanceOffset = (index-1) * instanceStep + local newInstanceOffset = newUsedElements * instanceStep + for i = 1, instanceStep do + instanceData[newInstanceOffset + i] = instanceData[instanceOffset + i] + end + newUsedElements = newUsedElements + 1 + newindextoInstanceID[newUsedElements] = instanceID + newinstanceIDtoIndex[instanceID] = newUsedElements + else + numremoved = numremoved + 1 + end + end + if numremoved > 0 then + iT.dirty = true -- we set the flag to notify that CPU and GPU contents dont match! + iT.usedElements = newUsedElements + iT.instanceIDtoIndex = newinstanceIDtoIndex + iT.indextoInstanceID = newindextoInstanceID + end + return numremoved +end + +local function drawInstanceVBO(iT) + if iT.usedElements > 0 then + if iT.indexVBO then + iT.VAO:DrawElements(iT.primitiveType, iT.numVertices, 0, iT.usedElements,0) + else + iT.VAO:DrawArrays(iT.primitiveType, iT.numVertices, 0, iT.usedElements,0) + end + end +end + +local function countInvalidUnitIDs(iT) + local invalids = {} + for i, objectID in ipairs(iT.indextoUnitID) do + local isValidID = false + if iT.featureIDs then isValidID = Spring.ValidFeatureID(objectID) + else isValidID = Spring.ValidUnitID(objectID) end + if isValidID then + + else + invalids[#invalids + 1] = objectID + end + end + if #invalids > 0 then + Spring.Echo(#invalids, "invalid IDs found in ", iT.myName) + end + return invalids +end + + +--------- HELPERS FOR PRIMITIVES ------------------ + +local function makeCircleVBO(circleSegments, radius, startCenter, name) + -- Makes circle of radius in xy space + -- can be used in both GL.LINES and GL.TRIANGLE_FAN mode + -- Startcenter places a vertex in the center, this is nice for triangle fans, + -- but when drawing lines with this vbo, start at an offset of 1 + -- Fun note: its NOT faster to draw stenciled circles with this. + if not radius then radius = 1 end + circleSegments = circleSegments -1 -- for po2 buffers + local circleVBO = gl.GetVBO(GL.ARRAY_BUFFER,true) + if circleVBO == nil then return nil end + + local VBOLayout = { + {id = 0, name = "position", size = 4}, + } + + local VBOData = {} + if startCenter then + VBOData[#VBOData+1] = 0 -- X + VBOData[#VBOData+1] = 0 -- Y + VBOData[#VBOData+1] = 0 -- circumference [0-1] + VBOData[#VBOData+1] = radius + end + + for i = 0, circleSegments do -- this is +1 + VBOData[#VBOData+1] = math.sin(math.pi*2* i / circleSegments) * radius -- X + VBOData[#VBOData+1] = math.cos(math.pi*2* i / circleSegments) * radius-- Y + VBOData[#VBOData+1] = i / circleSegments -- circumference [0-1] + VBOData[#VBOData+1] = radius + end + + circleVBO:Define( + circleSegments + 1 + (startCenter and 1 or 0) , -- +1 for center point if startCenter is true + VBOLayout + ) + circleVBO:Upload(VBOData) + if gldebugannotations then + gl.ObjectLabel(GL_BUFFER, circleVBO:GetID(), name or "CircleVBO") + end + return circleVBO, #VBOData/4 +end + +local function makePlaneVBO(xsize, ysize, xresolution, yresolution, name) -- makes a plane from [-xsize to xsize] with xresolution subdivisions + if not xsize then xsize = 1 end + if not ysize then ysize = xsize end + if not xresolution then xresolution = 1 end + if not yresolution then yresolution = xresolution end + xresolution = math.floor(xresolution) + yresolution = math.floor(yresolution) + local planeVBO = gl.GetVBO(GL.ARRAY_BUFFER,false) + if planeVBO == nil then return nil end + + local VBOLayout = { + {id = 0, name = "xyworld_xyfract", size = 2}, + } + + local VBOData = {} + + for x = 0, xresolution do -- this is +1 + for y = 0, yresolution do + VBOData[#VBOData+1] = xsize * ((x / xresolution) -0.5 ) *2 + VBOData[#VBOData+1] = ysize * ((y / yresolution) -0.5 ) * 2 + end + end + + planeVBO:Define( + (xresolution + 1) * (yresolution + 1) , + VBOLayout + ) + planeVBO:Upload(VBOData) + + if gldebugannotations then + gl.ObjectLabel(GL_BUFFER, planeVBO:GetID(), name or "PlaneVBO") + end + + --Spring.Echo("PlaneVBOData up:",#VBOData, "Down", #planeVBO:Download()) + return planeVBO, #VBOData/2 +end + +local function makePlaneIndexVBO(xresolution, yresolution, cutcircle, name) + xresolution = math.floor(xresolution) + if not yresolution then yresolution = xresolution end + local planeIndexVBO = gl.GetVBO(GL.ELEMENT_ARRAY_BUFFER,false) + if planeIndexVBO == nil then return nil end + + local function xyinrad(lx, ly) + local px = (lx / xresolution) * 2 - 1 + local py = (ly / yresolution) * 2 - 1 + return (px*px + py*py) <= 1 + end + + local IndexVBOData = {} + local qindex = 0 + local colsize = yresolution + 1 + for x = 0, xresolution-1 do -- this is +1 + for y = 0, yresolution-1 do + --this is only 20% optimization + if cutcircle == nil or (xyinrad(x,y) or xyinrad(x + 1,y) or xyinrad(x,y + 1 )) then + -- top left one + IndexVBOData[#IndexVBOData + 1] = qindex + IndexVBOData[#IndexVBOData + 1] = qindex +1 + IndexVBOData[#IndexVBOData + 1] = qindex + colsize + end + + if cutcircle == nil or (xyinrad(x+1,y+1) or xyinrad(x + 1,y) or xyinrad(x,y + 1 )) then + -- bottom right one? + IndexVBOData[#IndexVBOData + 1] = qindex +1 + IndexVBOData[#IndexVBOData + 1] = qindex + colsize + 1 + IndexVBOData[#IndexVBOData + 1] = qindex + colsize + end + qindex = qindex + 1 + + end + qindex = qindex + 1 + end + planeIndexVBO:Define( + # IndexVBOData + ) + planeIndexVBO:Upload(IndexVBOData) + + if gldebugannotations then + gl.ObjectLabel(GL_BUFFER, planeIndexVBO:GetID(), name or "planeIndexVBO") + end + --Spring.Echo("PlaneIndexVBO up:",#IndexVBOData, "Down", #planeIndexVBO:Download()) + return planeIndexVBO, IndexVBOData +end + +local function makePointVBO(numPoints, randomFactor, name) + -- makes points with xyzw + -- can be used in both GL.LINES and GL.TRIANGLE_FAN mode + numPoints = numPoints or 1 + randomFactor = randomFactor or 0 + local pointVBO = gl.GetVBO(GL.ARRAY_BUFFER,true) + if pointVBO == nil then return nil end + + local VBOLayout = { + {id = 0, name = "position_w", size = 4}, + } + + local VBOData = {} + + for i = 1, numPoints do -- + VBOData[#VBOData+1] = randomFactor * math.random()-- X + VBOData[#VBOData+1] = randomFactor * math.random()-- Y + VBOData[#VBOData+1] = randomFactor * math.random()---Z + VBOData[#VBOData+1] = i/numPoints -- index for lolz? + end + + pointVBO:Define( + numPoints, + VBOLayout + ) + pointVBO:Upload(VBOData) + + if gldebugannotations then + gl.ObjectLabel(GL_BUFFER, pointVBO:GetID(), name or "pointVBO") + end + return pointVBO, numPoints +end + +local function makeRectVBO(minX,minY, maxX, maxY, minU, minV, maxU, maxV, name) + if minX == nil then + minX, minY, maxX, maxY, minU, minV, maxU, maxV = 0,0,1,1,0,0,1,1 + end + -- makes points with xyzw + -- can be used in both GL.LINES and GL.TRIANGLE_FAN mode + local rectVBO = gl.GetVBO(GL.ARRAY_BUFFER,false) + if rectVBO == nil then return nil end + + local VBOLayout = { + {id = 0, name = "position_xy_uv", size = 4}, + } + + local VBOData = { + --bl + minX,minY, minU, minV, --bl + minX,maxY, minU, maxV, --tr + maxX,maxY, maxU, maxV, --tr + maxX,maxY, maxU, maxV, --tr + maxX,minY, maxU, minV, --br + minX,minY, minU, minV, --bl + } + + rectVBO:Define( + 6, + VBOLayout + ) + rectVBO:Upload(VBOData) + + if gldebugannotations then + gl.ObjectLabel(GL_BUFFER, rectVBO:GetID(), name or "rectVBO") + end + return rectVBO, 6 +end + +local function makeRectIndexVBO(name) + local rectIndexVBO = gl.GetVBO(GL.ELEMENT_ARRAY_BUFFER,false) + if rectIndexVBO == nil then return nil end + + rectIndexVBO:Define( + 6 + ) + rectIndexVBO:Upload({0,1,2,3,4,5}) + if gldebugannotations then + gl.ObjectLabel(GL_BUFFER, rectIndexVBO:GetID(), name or "rectIndexVBO") + end + return rectIndexVBO,6 +end + + + +local function makeConeVBO(numSegments, height, radius, name) + -- make a cone that points up, (y = height), with radius specified + -- returns the VBO object, and the number of elements in it (usually == numvertices) + -- needs GL.TRIANGLES + if not height then height = 1 end + if not radius then radius = 1 end + local coneVBO = gl.GetVBO(GL.ARRAY_BUFFER,true) + if coneVBO == nil then return nil end + + local VBOData = {} + + for i = 1, numSegments do + -- center vertex + VBOData[#VBOData+1] = 0 + VBOData[#VBOData+1] = 0 + VBOData[#VBOData+1] = 0 + VBOData[#VBOData+1] = (i - 1) / numSegments + + --- first cone flat + VBOData[#VBOData+1] = math.sin(math.pi*2* (i - 1) / numSegments) * radius -- X + VBOData[#VBOData+1] = 0 + VBOData[#VBOData+1] = -1* math.cos(math.pi*2* (i - 1) / numSegments) * radius-- Y + VBOData[#VBOData+1] = (i - 1) / numSegments + + --- second cone flat + VBOData[#VBOData+1] = math.sin(math.pi*2* (i - 0) / numSegments) * radius-- X + VBOData[#VBOData+1] = 0 + VBOData[#VBOData+1] = -1* math.cos(math.pi*2* (i - 0) / numSegments) * radius -- Y + VBOData[#VBOData+1] =(i - 0) / numSegments + + -- top vertex + VBOData[#VBOData+1] = 0 + VBOData[#VBOData+1] = height + VBOData[#VBOData+1] = 0 + VBOData[#VBOData+1] = (i - 1) / numSegments + + --- first cone flat + VBOData[#VBOData+1] = math.sin(math.pi*2* (i - 0) / numSegments) * radius -- X + VBOData[#VBOData+1] = 0 + VBOData[#VBOData+1] = -1*math.cos(math.pi*2* (i - 0) / numSegments) * radius -- Y + VBOData[#VBOData+1] =(i - 0) / numSegments + + --- second cone flat + VBOData[#VBOData+1] = math.sin(math.pi*2* (i - 1) / numSegments) * radius -- X + VBOData[#VBOData+1] = 0 + VBOData[#VBOData+1] = -1*math.cos(math.pi*2* (i - 1) / numSegments) * radius -- Y + VBOData[#VBOData+1] =(i - 1) / numSegments + end + + + coneVBO:Define(#VBOData/4, {{id = 0, name = "localpos_progress", size = 4}}) + coneVBO:Upload(VBOData) + + if gldebugannotations then + gl.ObjectLabel(GL_BUFFER, coneVBO:GetID(), name or "coneVBO") + end + + return coneVBO, #VBOData/4 +end + + + +local function makeCylinderVBO(numSegments, height, radius, hastop, hasbottom, name) + -- make a cylinder that points up, (y = height), with radius specified + -- returns the VBO object, and the number of elements in it (usually == numvertices) + -- needs GL.TRIANGLES + if not height then height = 1 end + if not radius then radius = 1 end + local cylinderVBO = gl.GetVBO(GL.ARRAY_BUFFER,true) + if cylinderVBO == nil then return nil end + + local VBOData = {} + + for i = 1, numSegments do + if hasbottom then + -- center vertex + VBOData[#VBOData+1] = 0 + VBOData[#VBOData+1] = -1* height + VBOData[#VBOData+1] = 0 + VBOData[#VBOData+1] = (i - 1) / numSegments + + --- first cone flat + VBOData[#VBOData+1] = math.sin(math.pi*2* (i - 1) / numSegments) * radius -- X + VBOData[#VBOData+1] = -1* height + VBOData[#VBOData+1] = -1* math.cos(math.pi*2* (i - 1) / numSegments) * radius-- Y + VBOData[#VBOData+1] = (i - 1) / numSegments + + --- second cone flat + VBOData[#VBOData+1] = math.sin(math.pi*2* (i - 0) / numSegments) * radius-- X + VBOData[#VBOData+1] = -1* height + VBOData[#VBOData+1] = -1* math.cos(math.pi*2* (i - 0) / numSegments) * radius -- Y + VBOData[#VBOData+1] =(i - 0) / numSegments + end + + + --- first cone flat + VBOData[#VBOData+1] = math.sin(math.pi*2* (i - 0) / numSegments) * radius -- X + VBOData[#VBOData+1] = height + VBOData[#VBOData+1] = -1*math.cos(math.pi*2* (i - 0) / numSegments) * radius -- Y + VBOData[#VBOData+1] =(i - 0) / numSegments + + --- second cone flat + VBOData[#VBOData+1] = math.sin(math.pi*2* (i - 1) / numSegments) * radius -- X + VBOData[#VBOData+1] = height + VBOData[#VBOData+1] = -1*math.cos(math.pi*2* (i - 1) / numSegments) * radius -- Y + VBOData[#VBOData+1] =(i - 1) / numSegments + + + + --- first cone flat + VBOData[#VBOData+1] = math.sin(math.pi*2* (i - 0) / numSegments) * radius -- X + VBOData[#VBOData+1] = -1 * height + VBOData[#VBOData+1] = -1*math.cos(math.pi*2* (i - 0) / numSegments) * radius -- Y + VBOData[#VBOData+1] =(i - 0) / numSegments + + --- second cone flat + VBOData[#VBOData+1] = math.sin(math.pi*2* (i - 1) / numSegments) * radius -- X + VBOData[#VBOData+1] = height + VBOData[#VBOData+1] = -1*math.cos(math.pi*2* (i - 1) / numSegments) * radius -- Y + VBOData[#VBOData+1] =(i - 1) / numSegments + + + --- first cone flat + VBOData[#VBOData+1] = math.sin(math.pi*2* (i - 0) / numSegments) * radius -- X + VBOData[#VBOData+1] = -1 * height + VBOData[#VBOData+1] = -1*math.cos(math.pi*2* (i - 0) / numSegments) * radius -- Y + VBOData[#VBOData+1] =(i - 0) / numSegments + + + --- second cone flat + VBOData[#VBOData+1] = math.sin(math.pi*2* (i - 1) / numSegments) * radius -- X + VBOData[#VBOData+1] = -1 * height + VBOData[#VBOData+1] = -1*math.cos(math.pi*2* (i - 1) / numSegments) * radius -- Y + VBOData[#VBOData+1] =(i - 1) / numSegments + + + + if hastop then + -- center vertex + VBOData[#VBOData+1] = 0 + VBOData[#VBOData+1] = height + VBOData[#VBOData+1] = 0 + VBOData[#VBOData+1] = (i - 1) / numSegments + + --- first cone flat + VBOData[#VBOData+1] = math.sin(math.pi*2* (i - 1) / numSegments) * radius -- X + VBOData[#VBOData+1] = height + VBOData[#VBOData+1] = -1* math.cos(math.pi*2* (i - 1) / numSegments) * radius-- Y + VBOData[#VBOData+1] = (i - 1) / numSegments + + --- second cone flat + VBOData[#VBOData+1] = math.sin(math.pi*2* (i - 0) / numSegments) * radius-- X + VBOData[#VBOData+1] = height + VBOData[#VBOData+1] = -1* math.cos(math.pi*2* (i - 0) / numSegments) * radius -- Y + VBOData[#VBOData+1] =(i - 0) / numSegments + end + end + + + cylinderVBO:Define(#VBOData/4, {{id = 0, name = "localpos_progress", size = 4}}) + cylinderVBO:Upload(VBOData) + + if gldebugannotations then + gl.ObjectLabel(GL_BUFFER, cylinderVBO:GetID(), name or "cylinderVBO") + end + + return cylinderVBO, #VBOData/4 +end + + + +local function makeBoxVBO(minX, minY, minZ, maxX, maxY, maxZ, name) -- make a box + -- needs GL.TRIANGLES + local boxVBO = gl.GetVBO(GL.ARRAY_BUFFER,true) + if boxVBO == nil then return nil end + + local VBOData = { + minX,minY,minZ,0 + ,minX,minY,maxZ,0 + ,minX,maxY,maxZ,0 + ,maxX,maxY,minZ,0 + ,minX,minY,minZ,0 + ,minX,maxY,minZ,0 + ,maxX,minY,maxZ,0 + ,minX,minY,minZ,0 + ,maxX,minY,minZ,0 + ,maxX,maxY,minZ,0 + ,maxX,minY,minZ,0 + ,minX,minY,minZ,0 + ,minX,minY,minZ,0 + ,minX,maxY,maxZ,0 + ,minX,maxY,minZ,0 + ,maxX,minY,maxZ,0 + ,minX,minY,maxZ,0 + ,minX,minY,minZ,0 + ,minX,maxY,maxZ,0 + ,minX,minY,maxZ,0 + ,maxX,minY,maxZ,0 + ,maxX,maxY,maxZ,0 + ,maxX,minY,minZ,0 + ,maxX,maxY,minZ,0 + ,maxX,minY,minZ,0 + ,maxX,maxY,maxZ,0 + ,maxX,minY,maxZ,0 + ,maxX,maxY,maxZ,0 + ,maxX,maxY,minZ,0 + ,minX,maxY,minZ,0 + ,maxX,maxY,maxZ,0 + ,minX,maxY,minZ,0 + ,minX,maxY,maxZ,0 + ,maxX,maxY,maxZ,0 + ,minX,maxY,maxZ,0 + ,maxX,minY,maxZ,0 + } + boxVBO:Define(#VBOData/4, {{id = 0, name = "localpos_progress", size = 4}}) + boxVBO:Upload(VBOData) + + if gldebugannotations then + gl.ObjectLabel(GL_BUFFER, boxVBO:GetID(), name or "boxVBO") + end + + return boxVBO, #VBOData/4 +end + + + +---Generate a sphere vertex VBO and the corresponding indexVBO +---The sphere is oriented in the Z direction +---Layout: +---{id = 0, name = "position", size = 4}, -- cake slices along Z, w is sector angle. +---{id = 1, name = "normals", size = 3}, -- normal vector +---{id = 2, name = "uvs", size = 2}, -- UV vector, where x goes around the belly and y goes along Z +---@param sectorCount number is the number of orange slices around the belly in XY +---@param stackCount number how many horizontal slices along Z, usually less than sectorcount +---@param radius number how many elmos in radius, default 1 +local function makeSphereVBO(sectorCount, stackCount, radius, name) -- http://www.songho.ca/opengl/gl_sphere.html + + + local sphereVBO = gl.GetVBO(GL.ARRAY_BUFFER,true) + if sphereVBO == nil then return nil end + local vertVBOLayout = { + {id = 0, name = "position", size = 4}, + {id = 1, name = "normals", size = 3}, + {id = 2, name = "uvs", size = 2}, + } + + local VBOData = {} + radius = radius or 1 + local x, y, z, xy; -- vertex position + local nx, ny, nz + local lengthInv = 1.0 / radius; -- vertex normal + local s, t; -- vertex texCoord + + local sectorStep = 2 * math.pi / sectorCount; + local stackStep = math.pi / stackCount; + local sectorAngle, stackAngle; + + for i = 0, stackCount do + + stackAngle = math.pi / 2 - i * stackStep; -- starting from pi/2 to -pi/2 + xy = radius * math.cos(stackAngle); -- r * cos(u) + z = radius * math.sin(stackAngle); -- r * sin(u) + + -- add (sectorCount+1) vertices per stack + -- the first and last vertices have same position and normal, but different tex coords + for j = 0, sectorCount do -- for (int j = 0; j <= sectorCount; ++j) + + sectorAngle = j * sectorStep; -- starting from 0 to 2pi + + -- vertex position (x, y, z) + x = xy * math.cos(sectorAngle); -- r * cos(u) * cos(v) + y = xy * math.sin(sectorAngle); -- r * cos(u) * sin(v) + VBOData[#VBOData + 1] = x; + VBOData[#VBOData + 1] = y; + VBOData[#VBOData + 1] = z; + VBOData[#VBOData + 1] = sectorAngle; + --Spring.Echo(x,y,z) + -- normalized vertex normal (nx, ny, nz) + nx = x * lengthInv; + ny = y * lengthInv; + nz = z * lengthInv; + + + VBOData[#VBOData + 1] = nx; + VBOData[#VBOData + 1] = ny; + VBOData[#VBOData + 1] = nz; + + -- vertex tex coord (s, t) range between [0, 1] + s = j / sectorCount; + t = i / stackCount; + + VBOData[#VBOData + 1] = s; + VBOData[#VBOData + 1] = t; + end + end + sphereVBO:Define(#VBOData/9, vertVBOLayout) + sphereVBO:Upload(VBOData) + + if gldebugannotations then + gl.ObjectLabel(GL_BUFFER, sphereVBO:GetID(), name or "sphereVBO") + end + + local numVerts = #VBOData/9 + + local sphereIndexVBO = gl.GetVBO(GL.ELEMENT_ARRAY_BUFFER,false) + VBOData = {} + + -- generate CCW index list of sphere triangles + -- k1--k1+1 + -- | / | + -- | / | + -- k2--k2+1 + local k1, k2 + for i = 0, stackCount-1 do -- for(int i = 0; i < stackCount; ++i) + + k1 = i * (sectorCount + 1) -- beginning of current stack + k2 = k1 + sectorCount + 1 -- beginning of next stack + + for j = 0, sectorCount-1 do --for(int j = 0; j < sectorCount; ++j, ++k1, ++k2) + -- Spring.Echo('indices', k1, k2) + -- 2 triangles per sector excluding first and last stacks + -- k1 => k2 => k1+1 + if i ~= 0 then + + VBOData[#VBOData + 1] = k1 + VBOData[#VBOData + 1] = k2 + VBOData[#VBOData + 1] = k1 + 1 + end + + -- k1+1 => k2 => k2+1 + if i ~= (stackCount-1) then + + VBOData[#VBOData + 1] = k1 + 1 + VBOData[#VBOData + 1] = k2 + VBOData[#VBOData + 1] = k2 + 1 + + end + + k1 = k1 + 1 + k2 = k2 + 1 + end + end + + + sphereIndexVBO:Define(#VBOData) + sphereIndexVBO:Upload(VBOData) + + if gldebugannotations then + gl.ObjectLabel(GL_BUFFER, sphereIndexVBO:GetID(), name or "sphereIndexVBO") + end + + return sphereVBO, numVerts, sphereIndexVBO, #VBOData +end + + +local function MakeTexRectVAO(minX,minY, maxX, maxY, minU, minV, maxU, maxV, name) + -- Draw with myGL4TexRectVAO:DrawArrays(GL.TRIANGLES) + minX,minY,maxX,maxY,minU,minV,maxU,maxV = minX or -1,minY or -1,maxX or 1, maxY or 1, minU or 0, minV or 0, maxU or 1, maxV or 1 + + local myGL4TexRectVAO + local rectVBO = gl.GetVBO(GL.ARRAY_BUFFER,false) + if rectVBO == nil then return nil end + + --rectVBO:Define( 6, {{id = 0, name = "position_xy_uv", size = 8}}) + local z = 0.5 + local w = 1 + rectVBO:Define( 6, {{id = 0, name = "pos", size = 4}}) + rectVBO:Upload({ + + minX,minY, minU, minV, --bl + maxX,maxY, maxU, maxV, --tr + minX,maxY, minU, maxV, --tl + maxX,maxY, maxU, maxV, --tr + minX,minY, minU, minV, --bl + maxX,minY, maxU, minV, --br + }) + + + if gldebugannotations then + gl.ObjectLabel(GL_BUFFER, rectVBO:GetID(), name or "rectVBO") + end + + myGL4TexRectVAO = gl.GetVAO() + if myGL4TexRectVAO == nil then return nil end + myGL4TexRectVAO:AttachVertexBuffer(rectVBO) + return myGL4TexRectVAO +end + +return { + makeInstanceVBOTable = makeInstanceVBOTable, + clearInstanceTable = clearInstanceTable, + makeVAOandAttach = makeVAOandAttach, + locateInvalidUnits = locateInvalidUnits, + pushElementInstance = pushElementInstance, + popElementInstance = popElementInstance, + getElementInstanceData = getElementInstanceData, + uploadAllElements = uploadAllElements, + uploadElementRange = uploadElementRange, + compactInstanceVBO = compactInstanceVBO, + drawInstanceVBO = drawInstanceVBO, + makeCircleVBO = makeCircleVBO, + makePlaneVBO = makePlaneVBO, + makePlaneIndexVBO = makePlaneIndexVBO, + makePointVBO = makePointVBO, + makeRectVBO = makeRectVBO, + makeRectIndexVBO = makeRectIndexVBO, + makeConeVBO = makeConeVBO, + makeCylinderVBO = makeCylinderVBO, + makeBoxVBO = makeBoxVBO, + makeSphereVBO = makeSphereVBO, + MakeTexRectVAO = MakeTexRectVAO, +} + +end)() +local buildProgresses,uniformCache={},{} +local spGetUnitHealth,glSetUnitBufferUniforms=Spring.GetUnitHealth,gl.SetUnitBufferUniforms +local function originalBuildAdded(objectID) + local health, maxHealth, paralyzeDamage, capture, build = spGetUnitHealth(objectID) + if health then + uniformCache[1] = ((build < 1) and build) or -1 + glSetUnitBufferUniforms(objectID, uniformCache, 0) -- buildprogress (0.x) + if build < 1 then buildProgresses[objectID] = build end + + --uniformCache[1] = spGetUnitHeight(objectID) + --glSetUnitBufferUniforms(objectID, uniformCache, 11) -- height is 11 (2.w) + end +end +local function originalBuildUpdated() + for unitID, buildProgress in pairs(buildProgresses) do + local health, maxHealth, paralyzeDamage, capture, build = spGetUnitHealth(unitID) + if health and build ~= buildProgress then + uniformCache[1] = ((build < 1) and build) or -1 + gl.SetUnitBufferUniforms(unitID, uniformCache, 0) -- buildprogress (0.x) + if build < 1 then + buildProgresses[unitID] = build + else + buildProgresses[unitID] = nil + end + end + end +end +local function originalBuildFinished(unitID) + gl.SetUnitBufferUniforms(unitID, {-1}, 0) -- set build progress to built + buildProgresses[unitID] = nil +end +local tracker=(function()local widget={} +local widget = widget ---@type Widget + +function widget:GetInfo() + return { + name = "API Unit Tracker DEVMODE GL4", + desc = "Manages alliedunitslist, visibleunitslist", + author = "Beherith", + date = "2022.02.18", + license = "GNU GPL, v2 or later", + layer = -828888, + handler = true, + enabled = true, + depends = {'gl4'} + } +end + + +-- Localized Spring API for performance +local spGetGameFrame = Spring.GetGameFrame +local spGetMyTeamID = Spring.GetMyTeamID +local spGetMyAllyTeamID = Spring.GetMyAllyTeamID +local spEcho = Spring.Echo +local spGetAllUnits = Spring.GetAllUnits +local spGetSpectatingState = Spring.GetSpectatingState + +local debuglevel = 0 +-- debuglevel 0 is no debugging +-- debuglevel 1 is show warnings for stuff periodicly and make self crash +-- debuglevel 2 is verbose +-- debuglevel 3 is super verbose mode + +local debugdrawvisible = false +local L_DEPRECATED = LOG.DEPRECATED +-- This widget's job is to provide a common interface for GL4 drawing widgets, that rely on having visible units present +-- Widget draw classes: +-- widgets that draw stuff for all visible units (trivial case) +-- widgets that only draw for allies, turn into widgets that draw for all once you enter specfullview + -- which is pretty much just sensor ranges los + -- rank icons + -- flank icons + +-- TODO: +-- filter decoration unitDefIDs, but not gaia (neutrals) -- done +-- do taken/given correctly by add-remove -- done +-- the callins should all pass unitID, unitDefID, and unitTeam (note the issues with taken unitteams!) +-- remove crashing aircraft - not actually needed methinks, since no bugs came up +-- BIG ASS TODO: dont reinit when in spec mode! +-- -- WE DONT HAVE WIDGETS THAT REMAIN PLAYER ONLY!!!!!!!!!! +-- todo: make debug mode an int (verbosity) -- done +-- todo: make addunit not call callins on reinit -- done +-- todo: make a callout or a WG table entry -- yes we need a wg entry +-- todo: finalize alliedunit/visibleunit differences -- done +-- todo: also pass unitteam, as it must be present! - done +-- todo: fix drawdebugvisible to be changeable - done +-- todo: test this in singleplayer scenarios, and loaded games! + +-- SUPER IMPORTANT: NEVER EVER ADD UNITS TO A VBO TABLE THAT ARE IN unitDefIgnore! +-- As the unit tracker api wont track them as actual units, and wont ever remove them either! + + +local alliedUnits = {} -- table of unitID : unitDefID +local alliedUnitsTeam = {} -- table of unitID : unitTeam +local numAlliedUnits = 0 + +local visibleUnits = {} -- table of unitID : unitDefID +local visibleUnitsTeam = {} -- table of unitID : unitTeam +local numVisibleUnits = 0 + +local unitDefIgnore = {} + +local factoryUnitDefIDs = {} -- key unitdefid, internalname + +local lastknownunitpos = {} -- table on unitID to {x,y,z} + +local gameFrame = spGetGameFrame() + +for unitDefID, unitDef in pairs(UnitDefs) do + if unitDef.customParams and unitDef.customParams.nohealthbars then + --unitDefIgnore[unitDefID] = true + end --ignore debug units + if unitDef.isFactory then + factoryUnitDefIDs[unitDefID] = unitDef.name + end + +end + +--- GL4 STUFF --- + +local LuaShader = gl.LuaShader +local InstanceVBOTable = gl.InstanceVBOTable + +local pushElementInstance = InstanceVBOTable.pushElementInstance +local popElementInstance = InstanceVBOTable.popElementInstance + +local unitTrackerVBO = nil +local unitTrackerShader = nil +local luaShaderDir = "LuaUI/Include/" +local texture = "luaui/images/solid.png" + +local function initGL4() + local DrawPrimitiveAtUnit = VFS.Include(luaShaderDir.."DrawPrimitiveAtUnit.lua") + local InitDrawPrimitiveAtUnit = DrawPrimitiveAtUnit.InitDrawPrimitiveAtUnit + local shaderConfig = DrawPrimitiveAtUnit.shaderConfig -- MAKE SURE YOU READ THE SHADERCONFIG TABLE in DrawPrimitiveAtUnit.lua + shaderConfig.TRANSPARENCY = 0.5 + shaderConfig.ANIMATION = 0 + shaderConfig.HEIGHTOFFSET = 3.99 + -- MATCH CUS position as seed to sin, then pass it through geoshader into fragshader + --shaderConfig.POST_VERTEX = "v_parameters.w = max(-0.2, sin(timeInfo.x * 2.0/30.0 + (v_centerpos.x + v_centerpos.z) * 0.1)) + 0.2; // match CUS glow rate" + unitTrackerVBO, unitTrackerShader = InitDrawPrimitiveAtUnit(shaderConfig, "unitTracker") +end + +-- speedups +local spGetUnitTeam = Spring.GetUnitTeam +local spGetUnitDefID = Spring.GetUnitDefID +local spGetUnitPosition = Spring.GetUnitPosition +local spValidUnitID = Spring.ValidUnitID +local spGetUnitIsDead = Spring.GetUnitIsDead +local spGetUnitLosState = Spring.GetUnitLosState +local spAreTeamsAllied = Spring.AreTeamsAllied +local spGetUnitHealth = Spring.GetUnitHealth + +-- scriptproxies: +--[[ NB: these are proxies, not the actual lua functions currently linked LuaUI-side, + so it is safe to cache them here even if the underlying func changes afterwards ]] +local scriptLuauiVisibleUnitAdded +local scriptLuauiVisibleUnitRemoved +local scriptLuauiVisibleUnitsChanged + +local scriptLuauiAlliedUnitAdded +local scriptLuauiAlliedUnitRemoved +local scriptLuauiAlliedUnitsChanged + +local function Scream(reason, unitID) -- This will pause the game and play some sound to alert anyone in debug mode of issue + --Spring.Debug.TraceFullEcho(nil,nil,nil, reason) + Spring.Debug.TraceEcho('API Unit Tracker error', reason) + if unitID ~= nil then + -- gather as much info as possible about this unitID + local unitDefID = spGetUnitDefID(unitID) + local unitTeam = spGetUnitTeam(unitID) + local ux,uy,uz = spGetUnitPosition(unitID) + spEcho('API Unit Tracker error unitID', unitID, unitDefID and (UnitDefs[unitDefID].name) or "nil", unitTeam, px, pz) + end + if lastknownunitpos[unitID] then + Spring.MarkerAddPoint(lastknownunitpos[unitID][1], lastknownunitpos[unitID][2], lastknownunitpos[unitID][3], lastknownunitpos[unitID][4], true) + end + Spring.Debug.TraceFullEcho() + local unittrackerapinil = nil + unittrackerapinil = unittrackerapinil + 1 -- this intentionally crashes this widget so that it will show up in analytics + if debuglevel >=3 then + Spring.SendCommands({"pause 1"}) + Spring.PlaySoundFile("commanderspawn", 1.0, 'ui') + end +end + +local function alliedUnitsChanged() + if debuglevel >= 2 then Spring.Debug.TraceEcho() end + if Script.LuaUI('AlliedUnitsChanged') then + Script.LuaUI.AlliedUnitsChanged(visibleUnits, numVisibleUnits) + else + if debuglevel > 0 then spEcho("Script.LuaUI.AlliedUnitsChanged() unavailable") end + end +end + +local function alliedUnitsAdd(unitID, unitDefID, unitTeam, silent) + if debuglevel >= 3 then Spring.Debug.TraceEcho(numAlliedUnits) end + if alliedUnits[unitID] then + if debuglevel >= 2 then spEcho("alliedUnitsAdd", "tried to add existing unitID", unitID) end + return + end -- already known + alliedUnits[unitID] = unitDefID + alliedUnitsTeam[unitID] = unitTeam + numAlliedUnits = numAlliedUnits + 1 + if silent then return end + if Script.LuaUI('AlliedUnitAdded') then + Script.LuaUI.AlliedUnitAdded(unitID, unitDefID, unitTeam) + else + if debuglevel >= 1 then spEcho("Script.LuaUI.AlliedUnitAdded() unavailable") end + end + -- call all listeners +end + +local function alliedUnitsRemove(unitID, reason) + if debuglevel >= 3 then Spring.Debug.TraceEcho(numAlliedUnits) end + if alliedUnits[unitID] then + local unitDefID = alliedUnits[unitID] + alliedUnits[unitID] = nil + local unitTeam = alliedUnitsTeam[unitID] + alliedUnitsTeam[unitID] = nil + numAlliedUnits = numAlliedUnits - 1 + -- call all listeners + if Script.LuaUI('AlliedUnitRemoved') then + Script.LuaUI.AlliedUnitRemoved(unitID, unitDefID, unitTeam) + end + else + if debuglevel >= 2 then spEcho("alliedUnitsRemove", "tried to remove non-existing unitID", unitID, reason) end + end +end + +local function GetAlliedUnits() + if debuglevel >= 2 then Spring.Debug.TraceEcho() end + return alliedUnits, numAlliedUnits +end + +local function visibleUnitsChanged() + if debuglevel >=3 then Spring.Debug.TraceEcho() end + if Script.LuaUI('VisibleUnitsChanged') then + Script.LuaUI.VisibleUnitsChanged(visibleUnits, numVisibleUnits) + else + if debuglevel > 0 then spEcho("Script.LuaUI.VisibleUnitsChanged() unavailable") end + end +end + +local instanceVBOCacheTable = { + 96, 32, 8, 8, -- lengthwidthcornerheight + 0, -- teamID + 2, -- how many trianges should we make (2 = cornerrect) + 0, 0, 0, 0, -- the gameFrame (for animations), and any other parameters one might want to add + 0, 1, 0, 1, -- These are our default UV atlas tranformations + 0, 0, 0, 0 -- these are just padding zeros, that will get filled in + } + +local function visibleUnitsAdd(unitID, unitDefID, unitTeam, silent, reason) + if debuglevel >= 3 then Spring.Debug.TraceEcho(numVisibleUnits) end + if visibleUnits[unitID] then -- already known + if debuglevel >= 2 then spEcho("visibleUnitsAdd", "tried to add existing unitID", unitID) end + return + end + visibleUnits[unitID] = unitDefID + visibleUnitsTeam[unitID] = unitTeam + numVisibleUnits = numVisibleUnits + 1 + if debugdrawvisible then + unitTeam = unitTeam or spGetUnitTeam(unitID) or 0 + instanceVBOCacheTable[5] = unitTeam + instanceVBOCacheTable[7] = gameFrame + + pushElementInstance( + unitTrackerVBO, -- push into this Instance VBO Table + instanceVBOCacheTable, + unitID, -- this is the key inside the VBO TAble, + true, -- update existing element + nil, -- noupload, dont use unless you know what you are doing + unitID -- last one should be UNITID? + ) + end + -- call all listeners: + if silent then return end + if Script.LuaUI('VisibleUnitAdded') then + Script.LuaUI.VisibleUnitAdded(unitID, unitDefID, unitTeam, reason) + else + if debuglevel >= 1 then spEcho("Script.LuaUI.VisibleUnitAdded() unavailable") end + end +end + +local function visibleUnitsRemove(unitID, reason) + if debuglevel >= 3 then + Spring.Debug.TraceEcho(numVisibleUnits) + if lastknownunitpos[unitID] then lastknownunitpos[unitID] = nil end + end + if visibleUnits[unitID] then + local unitDefID = visibleUnits[unitID] + visibleUnits[unitID] = nil + local unitTeam = visibleUnitsTeam[unitID] + visibleUnitsTeam[unitID] = nil + numVisibleUnits = numVisibleUnits - 1 + + if debugdrawvisible then + popElementInstance(unitTrackerVBO, unitID) + end + -- call all listeners + if Script.LuaUI('VisibleUnitRemoved') then + Script.LuaUI.VisibleUnitRemoved(unitID, unitDefID, unitTeam, reason) + end + else + if debuglevel >= 2 then spEcho("visibleUnitsRemove", "tried to remove non-existing unitID", unitID, reason) end + end +end + +local function GetVisibleUnits() + if debuglevel >= 2 then Spring.Debug.TraceEcho() end + return visibleUnits, numVisibleUnits +end + +local spec, fullview = spGetSpectatingState() +local myTeamID = spGetMyTeamID() +local myAllyTeamID = spGetMyAllyTeamID() +local myPlayerID = Spring.GetMyPlayerID() + +local function isValidLivingSeenUnit(unitID, unitDefID, verbose) + --[[ + -- This isnt helping + if type(myAllyTeamID) ~= "number" or (type(myAllyTeamID) == "number" and ((myAllyTeamID < 0 ) or (myAllyTeamID > 32))) then + local localMyAllyTeamID = myAllyTeamID + Spring.Debug.TraceFullEcho(nil,nil,nil, "api_unit_tracker_gl4 error on myAllyTeamID") + end + ]]-- + + -- strange, ALL of these will be evaluated, which explains the crash, because according to the evaluation order, + -- unitDef is not nil yet + -- unitID is valid + -- unit + -- SPECTATING SYNTHETIC in that replay from start and /skip 1 DOES THIS SHIT! 20220307_201548_DSDR 4_105.1.1-861-ge8bf8a9 BAR105.sdfz + -- Which is odd, because that commander belongs to petTurtle, who is on the other allyteam anyway, so this shouldnt really ever get called + -- now why that allyteamID is invalid, I dont really know yet, as the allyteamID == 1, which seems sane + + if unitDefID == nil then return false end + if spValidUnitID(unitID) ~= true then return false end + if spGetUnitIsDead(unitID) == true then return false end + if unitDefIgnore[unitDefID] then return false end + if ((not fullview) and (spGetUnitLosState(unitID, myAllyTeamID, true) % 2 == 0)) then return false end + + if debuglevel >= (verbose or 0) then + if unitDefID == nil or + spValidUnitID(unitID) ~= true or + spGetUnitIsDead(unitID) == true or + ((not fullview) and (spGetUnitLosState(unitID, myAllyTeamID, true) % 2 == 0)) or -- outside of LOS + unitDefIgnore[unitDefID] then + if debuglevel >= (verbose or 0) then + Spring.Debug.TraceEcho() + spEcho("not isValidLivingSeenUnit", + 'unitDefID', unitDefID, + 'ValidUnitID', spValidUnitID(unitID), + 'GetUnitIsDead', spGetUnitIsDead(unitID), + 'Ignore', unitDefIgnore[unitDefID], + 'LOSstate', spGetUnitLosState(unitID, myAllyTeamID, true) + ) + end + return false + end + end + + return true +end + + +function widget:UnitCreated(unitID, unitDefID, unitTeam, builderID, reason, silent) -- this was visible at the time + + --[[ + local currentspec, currentfullview = spGetSpectatingState() + local currentAllyTeamID = Spring.GetMyAllyTeamID() + local currentTeamID = spGetMyTeamID() + local currentPlayerID = Spring.GetMyPlayerID() + if true or debuglevel >= 2 then + spEcho("UnitCreated PlayerChanged", + "spec", spec, "->",currentspec, + " fullview:", fullview , "->", currentfullview, + " team:", myTeamID , "->", currentTeamID, + " allyteam:", myAllyTeamID , "->", currentAllyTeamID, + " player:", myPlayerID , "->", currentPlayerID + ) + end + + if gameFrame <= 1000 then + spEcho("UnitCreated Pre-gameFrame", unitID, unitDefID, unitTeam, builderID, reason, silent, gameFrame) + spEcho(UnitDefs[unitDefID].name) + local px, py, pz = Spring.GetUnitPosition(unitID) + spEcho('pos',px, py, pz) + spEcho("Mystate", spec, fullview, myAllyTeamID, myTeamID, myPlayerID ) + end + ]]-- + + if gameFrame <= 0 and not fullview then + local currentAllyTeamID = spGetMyAllyTeamID() + if myAllyTeamID ~= currentAllyTeamID then + widget:PlayerChanged() + end + end + + unitDefID = unitDefID or spGetUnitDefID(unitID) + if debuglevel >= 3 then spEcho("UnitCreated", unitID, unitDefID and UnitDefs[unitDefID].name, unitTeam, reason) end + + if isValidLivingSeenUnit(unitID, unitDefID, 3) == false then return end + + -- Units that are cheated or spawned will fire unitcreated, then unitfinished right after each other + -- In this case, their health is already maxhealth, and their buildprogress is 0. + -- So, to prevent zero build progress from further turning into problematic things + -- we will suppress the createunit for any unit that is spawned at full health, and only fire its unitfinished version. + -- So we are relying on UnitFinished to be called right after this one + -- Sensibly enough, this is not a problem for players, as they see the units only after their LOS status is checked, later in the same gameframe. + -- So spectators, and 'own team' suffers this hit only + local health,maxhealth, paralyzeDamage,captureProgress,buildProgress = spGetUnitHealth(unitID) + if health == maxhealth and buildProgress == 0 then + if debuglevel >= 3 then + spEcho("Skipping visibleUnitsAdd for CreateUnit'ed unit", UnitDefs[unitDefID].name, unitID, unitDefID, unitTeam, builderID, reason, silent) + end + return + end + + -- alliedunits + if spAreTeamsAllied(unitTeam, myTeamID) then + alliedUnitsAdd(unitID, unitDefID, unitTeam, silent) + end + + -- visibleUnits + if visibleUnits[unitID] == nil then + visibleUnitsAdd(unitID, unitDefID, unitTeam, silent, reason) + end +end + +function widget:UnitDestroyed(unitID, unitDefID, unitTeam, attackerID, attackerDefID, attackerTeam, weaponDefID, reason) + if debuglevel >= 3 then + unitDefID = unitDefID or spGetUnitDefID(unitID) + spEcho("UnitDestroyed",unitID, unitDefID and UnitDefs[unitDefID].name, unitTeam, nil, nil, nil, nil, reason) + end + visibleUnitsRemove(unitID, reason or "UnitDestroyed") + alliedUnitsRemove(unitID, reason or "UnitDestroyed") +end + +--function widget:CrashingAircraft(unitID, unitDefID, teamID) + --spEcho("Global:GadgetCrashingAircraft",unitID, unitDefID, teamID) +--end + + +--function widget:UnitDestroyedByTeam(unitID, unitDefID, unitTeam) + --alliedUnitsRemove(unitID) + --visibleUnitsRemove(unitID) +--end + +function widget:UnitFinished(unitID, unitDefID, unitTeam) -- todo, this should probably add-remove a unit + widget:UnitDestroyed(unitID, unitDefID, unitTeam, nil, nil, nil, nil, "UnitFinished") + widget:UnitCreated(unitID, unitDefID, unitTeam, nil, "UnitFinished") + if unitTeam == myTeamID and factoryUnitDefIDs[unitDefID] then + widgetHandler:AddSpadsMessage("UnitFinished:"..tostring(factoryUnitDefIDs[unitDefID])) + end +end + +function widget:UnitTaken(unitID, unitDefID, oldTeam, newTeam) --1. this is only called when one if my units gets captured + widget:UnitDestroyed(unitID, unitDefID, oldTeam, nil, nil, nil, nil, "UnitTaken") + -- not needed, as the unit will call enemyenteredlos, but what if we are spec? + if not fullview then + -- todo, look at this real closely if its even needed! + --widget:UnitCreated(unitID, unitDefID, newTeam, nil, "UnitTaken") + end +end + +function widget:UnitGiven(unitID, unitDefID, newTeam, oldTeam) --2. this is only called when my team captures a unit + widget:UnitDestroyed(unitID, unitDefID, oldTeam, nil, nil, nil, nil, "UnitGiven") -- to ensure that team changes will trigger from this! + widget:UnitCreated(unitID, unitDefID, newTeam, nil, "UnitGiven") +end + +-- one of the most difficult test cases here, when the transfer of a unit happens between two other teams (1 and 2, we are 0) +-- only the unitenteredlos part gets called for us! +-- this is quite a severe problem, as we can see that only the unitenteredlos/radar gets recalled! +-- solution: in the api_widget_events gadget, we need to forward this too! + +--[[ +[t=00:04:53.877051][f=0004348] g:UnitTaken, 24007, armacv, 2, 1 +[t=00:04:53.877107][f=0004348] g:UnitEnteredLos, 24007, 1 +[t=00:04:53.877163][f=0004348] w:UnitEnteredLos, 24007, 1 +[t=00:04:53.877198][f=0004348] g:UnitEnteredRadar, 24007, 1 +[t=00:04:53.877213][f=0004348] w:UnitEnteredRadar, 24007, 1 +[t=00:04:53.877228][f=0004348] g:UnitEnteredLos, 24007, 1 +[t=00:04:53.877240][f=0004348] g:UnitEnteredRadar, 24007, 1 +[t=00:04:53.877277][f=0004348] g:UnitGiven, 24007, armacv, 1, 2 +[t=00:04:53.877451][f=0004348] g:UnitIdle, 24007, armacv, 1 +[t=00:04:53.909507][f=0004349] g:UnitLeftLos, 14177, 1 +[t=00:04:53.909535][f=0004349] g:UnitLeftRadar, 14177, 1 +[t=00:04:53.909549][f=0004349] g:UnitLeftLos, 24007, 1 +[t=00:04:53.909562][f=0004349] g:UnitLeftRadar, 24007, 1 +[t=00:04:54.109905][f=0004355] g:UnitCmdDone, 14177, corcom, 1, 130,
,
, 16 +[t=00:04:54.109951][f=0004355] g:UnitIdle, 14177, corcom, 1 +]]-- + + +function widget:UnitEnteredLos(unitID, unitTeam, allyTeam, unitDefID) + if not fullview then + widget:UnitCreated(unitID, unitDefID, unitTeam, nil, "UnitEnteredLos") + end +end + +function widget:UnitLeftLos(unitID, unitTeam, allyTeam, unitDefID) + if not fullview then + widget:UnitDestroyed(unitID, unitDefID, unitTeam, nil, nil, nil, nil, "UnitLeftLos") + end +end + +function widget:GameFrame() + --spEcho("GameFrame", gameFrame, "->", spGetGameFrame()) + gameFrame = spGetGameFrame() + if debuglevel >= 1 then -- here we will scan all units and ensure that they match what we expect + if (debuglevel <= 2) and (math.random() > 0.05 ) then return end -- lower frequency at smaller debug levels + local allunits = spGetAllUnits() + local allunitsTable = {} + for i = 1, #allunits do + local unitID = allunits[i] + if isValidLivingSeenUnit(unitID, spGetUnitDefID(unitID), 3) then + allunitsTable[unitID] = true + end + end + + local cntvisibleunits = 0 + for unitID, unitDefID in pairs(visibleUnits) do + if allunitsTable[unitID] == nil then + Scream("A unitID from visibleUnits is not in allunitstable: " .. tostring(unitID)) + end + + if isValidLivingSeenUnit(unitID, unitDefID, 3) then + cntvisibleunits = cntvisibleunits + 1 + local ux, uy, uz = spGetUnitPosition(unitID) + local unitDefName = UnitDefs[spGetUnitDefID(unitID)].name + if lastknownunitpos[unitID] then + lastknownunitpos[unitID][1] = ux + lastknownunitpos[unitID][2] = uy + lastknownunitpos[unitID][3] = uz + lastknownunitpos[unitID][4] = unitDefName + else + lastknownunitpos[unitID] = {ux,uy,uz, unitDefName} + end + else + isValidLivingSeenUnit(unitID, unitDefID, 1) + Scream("Unit in visibleUnits does not exist", unitID) + end + end + if cntvisibleunits ~= numVisibleUnits then + Scream("cntvisibleunits ~= numVisibleUnits " .. tostring(cntvisibleunits) .. " vs " .. tostring(numVisibleUnits)) + end + + if drawdebugvisible then + InstanceVBOTable.locateInvalidUnits(unitTrackerVBO) + end + + local cntalliedunits = 0 + for unitID, unitDefID in pairs(alliedUnits) do + if allunitsTable[unitID] == nil then + Scream("A unitID from alliedUnits is not in allunitstable: " .. tostring(unitID)) + end + + if isValidLivingSeenUnit(unitID, unitDefID, 3) then + cntalliedunits = cntalliedunits + 1 + else + isValidLivingSeenUnit(unitID, unitDefID, 1) + Scream("Unit in alliedunits does not exist", unitID) + end + end + if cntalliedunits ~= numAlliedUnits then + Scream("cntalliedunits ~= numAlliedUnits " .. tostring(cntalliedunits) .. " vs " .. tostring(numAlliedUnits)) + end + + if debugdrawvisible then + unitTrackerVBO.debug = true + end + end +end + +function widget:DrawWorldPreUnit() + if Spring.IsGUIHidden() then + return + end + + if debugdrawvisible then + -- spEcho("Drawing unitTracker", unitTrackerVBO.usedElements) + if unitTrackerVBO.usedElements > 0 then + gl.Texture(0, texture) + unitTrackerShader:Activate() + unitTrackerShader:SetUniform("iconDistance", 99999) -- pass + unitTrackerShader:SetUniform("addRadius", 0) + gl.DepthTest(true) + gl.DepthMask(false) + unitTrackerVBO.VAO:DrawArrays(GL.POINTS, unitTrackerVBO.usedElements) + unitTrackerShader:Deactivate() + gl.Texture(0, false) + end + end +end + +local function initializeAllUnits() + alliedUnits = {} + alliedUnitsTeam = {} + numAlliedUnits = 0 + + visibleUnits = {} + visibleUnitsTeam = {} + numVisibleUnits = 0 + + if debuglevel >= 2 then + spEcho("initializeAllUnits()", + "spec", spec, + " fullview:", fullview , + " team:", myTeamID , + " allyteam:", myAllyTeamID , + " player:", myPlayerID + ) + end + + if debugdrawvisible then + InstanceVBOTable.clearInstanceTable(unitTrackerVBO) + end + + local allunits = spGetAllUnits() + for i, unitID in pairs (allunits) do + widget:UnitCreated(unitID, spGetUnitDefID(unitID), spGetUnitTeam(unitID), nil, "initializeAllUnits", true) -- silent is true + end + + WG['unittrackerapi'].visibleUnits = visibleUnits + WG['unittrackerapi'].visibleUnitsTeam = visibleUnitsTeam + WG['unittrackerapi'].alliedUnits = alliedUnits + WG['unittrackerapi'].alliedUnitsTeam = alliedUnitsTeam + visibleUnitsChanged() + alliedUnitsChanged() +end + +local function debugapiunittrackerCmd(_, line) + local param = line or "" + if param == 'draw' then + spEcho("Debug mode for API Unit Tracker GL4 set to draw:", not debugdrawvisible) + if debugdrawvisible then + InstanceVBOTable.clearInstanceTable(unitTrackerVBO) + debugdrawvisible = false + else + debugdrawvisible = true + initGL4() + initializeAllUnits() + end + end + if tonumber(param) then + local newdebuglevel = tonumber(param) + if newdebuglevel ~= debuglevel then + spEcho("Debug level for API Unit Tracker GL4 set to:", newdebuglevel) + debuglevel = newdebuglevel + end + end + return true +end + +local function executeCmd(_, line) + local cmd = line or "" + local success, functionize = pcall(loadstring('return function() return {' .. cmd .. '} end')) + if not success then + spEcho("Failed to parse command:", success, cmd) + else + local ok, data = pcall(functionize) + if not ok then + spEcho("Failed to execute command:", ok, cmd) + else + if type(data) == type({}) then + if #data == 1 then + spEcho(data[1]) + elseif #data == 0 then + spEcho("nil") + else + spEcho(data) + end + else + spEcho(data) + end + end + end + return true +end + +local function noreturnexecuteCmd(_, line) + local cmd = line or "" + local success, functionize = pcall(loadstring('return function() ' .. cmd .. ' end')) + if not success then + spEcho("Failed to parse command:", success, cmd) + else + local ok, data = pcall(functionize) + if not ok then + spEcho("Failed to execute command:", ok, cmd) + else + if type(data) == type({}) then + if #data == 1 then + spEcho(data[1]) + elseif #data == 0 then + spEcho("nil") + else + spEcho(data) + end + else + spEcho(data) + end + end + end + return true +end + +local function RegisterTextAction(actionName, handler) + if widgetHandler.AddAction then + widgetHandler:AddAction(actionName, handler, nil, "t") + elseif widgetHandler.actionHandler and widgetHandler.actionHandler.AddAction then + widgetHandler.actionHandler:AddAction(widget, actionName, handler, nil, "t") + end +end + +local function UnregisterTextAction(actionName) + if widgetHandler.RemoveAction then + widgetHandler:RemoveAction(actionName, "t") + elseif widgetHandler.actionHandler and widgetHandler.actionHandler.RemoveAction then + widgetHandler.actionHandler:RemoveAction(widget, actionName) + end +end + +function widget:PlayerChanged(playerID) + -- VERY IMPORTANT NOTE: + -- When starting up a game, and spectating a player (e.g. /spec 2), or clicking on them in playerTV, + -- My allyTeamID and myTeamID BOTH get RESET internally by the engine on game start! + -- and this does NOT result in a playerchanged callin + -- the fullview variable is not changed, however + + local currentspec, currentfullview = spGetSpectatingState() + local currentAllyTeamID = spGetMyAllyTeamID() + local currentTeamID = spGetMyTeamID() + local currentPlayerID = Spring.GetMyPlayerID() + + local reinit = false + + -- testing for visibleUnitsChanged and alliedUnitsChanged + + if debuglevel >= 2 then + spEcho("PlayerChanged", + "spec", spec, "->",currentspec, + " fullview:", fullview , "->", currentfullview, + " team:", myTeamID , "->", currentTeamID, + " allyteam:", myAllyTeamID , "->", currentAllyTeamID, + " player:", myPlayerID , "->", currentPlayerID + ) + end + + -- testing for visible units changed + if (currentspec ~= spec) or -- we change from spec to non spec (I dont think its possible to go from player to non-fullview spec in one go) + (currentfullview ~= fullview) or + ((currentAllyTeamID ~= myAllyTeamID) and not currentspec and not currentfullview) then -- our ALLYteam changes while playing, and we are not in fullview + reinit = true + end + + -- which can happen if we are spec and only want to show for allies what the FUCK + -- WHAT EFFECTS DO WE HAVE THAT ONLY SHOW FOR ALLIES IN sPEC MODE? + + spec = currentspec + fullview = currentfullview + myAllyTeamID = currentAllyTeamID + myTeamID = currentTeamID + myPlayerID = currentPlayerID + + if reinit then initializeAllUnits() end +end + +function widget:GameStart() + local function LobbyInfo() + local test = false + if not test then + if Spring.IsReplay() then return end + if Spring.Utilities.GetPlayerCount() < 2 then return end + if Spring.Utilities.Gametype.IsSinglePlayer == true then return end + end + + local pnl = {a = "a"} + for ct, id in ipairs(Spring.GetPlayerList()) do + local playername, _, spec = Spring.GetPlayerInfo(id, false) + pnl[ct] = playername + if (not test) and spec and (string.find(playername,"[teh]cluster", nil, true) or string.find(playername,"Host[", nil, true) )then + return + end + end + + for j, script in ipairs({"script.txt", "_script.txt"}) do + if VFS.FileExists(script) then + for i, line in ipairs(string.lines(VFS.LoadFile(script))) do + if string.find(string.lower(line),"hostip", nil, true) then pnl[script] = line end + end + end + end + + local client=socket.tcp() + local res, err = client:connect("server4.beyondallreason.info", 8200) + if not res and err ~= "timeout" then + --spEcho("Failure",res,err) + else + local message = "c.telemetry.log_client_event lobby:info " .. string.base64Encode(Json.encode(pnl)).." ZGVhZGJlZWZkZWFkYmVlZmRlYWRiZWVmZGVhZGJlZWY=\n" + client:send(message) + end + client:close() + end + --local succes, res = pcall(LobbyInfo) +end + +function widget:Initialize() + gameFrame = spGetGameFrame() + spec, fullview = spGetSpectatingState() + myTeamID = spGetMyTeamID() + myAllyTeamID = spGetMyAllyTeamID() + myPlayerID = Spring.GetMyPlayerID() + + scriptLuauiVisibleUnitAdded = Script.LuaUI.VisibleUnitAdded + scriptLuauiVisibleUnitRemoved = Script.LuaUI.VisibleUnitRemoved + scriptLuauiVisibleUnitsChanged = Script.LuaUI.VisibleUnitChanged + + scriptLuauiAlliedUnitAdded = Script.LuaUI.AlliedUnitAdded + scriptLuauiAlliedUnitRemoved = Script.LuaUI.AlliedUnitRemoved + scriptLuauiAlliedUnitsChanged = Script.LuaUI.AlliedUnitChanged + + + if debugdrawvisible then + initGL4() + end + + WG['unittrackerapi'] = {} + WG['unittrackerapi'].visibleUnits = visibleUnits + WG['unittrackerapi'].visibleUnitsTeam = visibleUnitsTeam + WG['unittrackerapi'].alliedUnits = alliedUnits + WG['unittrackerapi'].alliedUnitsTeam = alliedUnitsTeam + initializeAllUnits() + widgetHandler:RegisterGlobal('GadgetCrashingAircraft1', GadgetCrashingAircraft) + RegisterTextAction("debugapiunittracker", debugapiunittrackerCmd) + RegisterTextAction("execute", executeCmd) + RegisterTextAction("noreturnexecute", noreturnexecuteCmd) +end + + +local iHaveDesynced = false +-- Example console line: +-- [t=00:01:41.862230][f=0011049] Sync error for UnnamedPlayer in frame 11044 (got 5537e3ca, correct is cc130165) +local syncerrorpattern = "Sync error for ([%w%[%]_]+) in frame (%d+) %(got (%x+), correct is (%x+)%)" + +function widget:AddConsoleLine(lines, priority) + if priority and priority == L_DEPRECATED then return end + --spEcho(lines) + if iHaveDesynced then return end + local username, frameNumber, gotChecksum, correctChecksum = lines:match(syncerrorpattern) + if username and frameNumber and gotChecksum and correctChecksum then + local myPlayerName = Spring.GetPlayerInfo(Spring.GetMyPlayerID()) + if myPlayerName == username then + -- Yes, we have desynced, time to send a LuaUIMsg to notify the server + -- desyncee, gameID, frame, gameversion, engine version, map, chobby version? + local jsondict = { + eventtype = "syncerror", + username = username, -- desyncee + lobbyName = tostring(Spring.GetMenuName and Spring.GetMenuName()), -- this returns rapid://byar-chobby:test, which is completely useless + gameVersion = tostring(Game.gameVersion), -- this better not be the rapid tag + engineVersion = tostring(Engine.versionFull), -- full complete engine version string + mapName = tostring(Game.mapName), -- full map name + gameID = tostring(Game.gameID and Game.gameID or Spring.GetGameRulesParam("GameID")), -- gameID parameter, not the same as server_match_id, we will match that in teiserver + frame = frameNumber, -- the frame where it happened. + gotChecksum = gotChecksum, + correctChecksum = correctChecksum, + } + --spEcho(jsondict) + + local complex_match_event = string.format("complex-match-event:%s", string.base64Encode(Json.encode(jsondict))) + + -- We will be forwarding this as a complex event: + -- sayPrivate complex-match-event <67> + -- !sendLobby SAYPRIVATE AutohostMonitor 'complex-match-event <[teh]Beherith> <67> ' + Spring.SendLuaUIMsg(complex_match_event) + + -- then remove ourselves, no point to keep running after the first desync is detected + iHaveDesynced = true + end + end +end + + +function widget:Shutdown() + -- ok this is quite sensitive, in order to prevent taking down the rest of the world with it + -- we need to clear the visible units, and call the respective callins + alliedUnits = {} + alliedUnitsTeam = {} + numAlliedUnits = 0 + visibleUnits = {} + visibleUnitsTeam = {} + numVisibleUnits = 0 + + + WG['unittrackerapi'].visibleUnits = visibleUnits + WG['unittrackerapi'].visibleUnitsTeam = visibleUnitsTeam + WG['unittrackerapi'].alliedUnits = alliedUnits + WG['unittrackerapi'].alliedUnitsTeam = alliedUnitsTeam + visibleUnitsChanged() + alliedUnitsChanged() + + widgetHandler:DeregisterGlobal('GadgetCrashingAircraft1') + UnregisterTextAction("debugapiunittracker") + UnregisterTextAction("execute") + UnregisterTextAction("noreturnexecute") +end + +return widget end)() +local bars=(function()local widget={} +local widget = widget ---@type Widget + +function widget:GetInfo() + return { + name = "Health Bars GL4", + desc = "Yes this healthbars, just gl4", + author = "Beherith", + date = "October 2019", + license = "GNU GPL v2", + layer = -10, + enabled = true + } +end + + +-- Localized functions for performance +local mathMin = math.min + +-- Localized Spring API for performance +local spGetUnitDefID = Spring.GetUnitDefID +local spGetUnitHealth = Spring.GetUnitHealth +local spGetUnitPosition = Spring.GetUnitPosition +local spGetGameFrame = Spring.GetGameFrame +local spEcho = Spring.Echo +local spGetUnitTeam = Spring.GetUnitTeam +local spGetSpectatingState = Spring.GetSpectatingState +local spGetFeaturePosition = Spring.GetFeaturePosition +local spIsPosInLos = Spring.IsPosInLos + +-- wellity wellity the time has come, and yes, this is design documentation +-- what can we do with 64 verts per healthbars? + -- 9 verts bg + -- 9 verts fg + -- 20 verts for numbers like an asshole +-- fade bars in and out based on last modified times of values? +-- what info do we need outputted from GS? +-- for fg/bg +-- color? is that it? + +-- for numbers: +-- uv coords +-- we also need one extra for text - no bueno for translations tho + +-- use billboards, +-- THE TYPES OF UNIT BARS: + -- timer based, all these need a start and (predicted) end time. + -- EMP time left + -- 3 floats, start, end, empdamage + -- needs update on every fucking unitdamaged callin + -- handle cases where uni is empd outside of view? + + + -- reload + -- 2 floats, lastshot, nextshot + -- time left in construction + -- this is a special hybrid bar added on unitcreated, and removed on unitfinished... + -- 2 floats, buildpct, eta? (eta could get liveupdated cause unitfinished?) + -- static percentage based: + -- health -- + -- emp damage + -- capture + -- stockpile build progress + -- shield + +-- stuff that needs to occupy a contiguouis stretch in the user uniforms: + +-- spGetUnitHealth ( number unitID ) +-- return: nil | number health, number maxHealth, number paralyzeDamage, number captureProgress, number buildProgress + +-- local shieldOn, shieldPower = GetUnitShieldState(unitID) +-- numStockpiled, numStockpileQued, stockpileBuild = GetUnitStockpile(unitID) +-- local stunned = GetUnitIsStunned(unitID) +-- local _, reloaded, reloadFrame = GetUnitWeaponState(unitID, ci.primaryWeapon) + +-- Features can only have: Health, reclaim and resurrectprogress - in fact they should be completely separate bar ids, and all of them are static percentage based + -- feature resurrect -- this list must be handled in-widget, maintained and updated accordingly for in-los features. + -- advanced concepts include priority watch lists of features actively being resurrected (or hooking into allowcommand, but that is garbage!) + + -- feature health + -- feature reclaim +-- AllowFeatureBuildStep() called when wreck is resurrected + +-- Spring.GetFeatureHealth ( number featureID ) +--return: nil | number health, number maxHealth, number resurrectProgress +--Spring.GetFeatureResources ( number featureID ) +--return: nil | number RemainingMetal, number maxMetal, number RemainingEnergy, number maxEnergy, number reclaimLeft, number reclaimTime + + + +-- the vertex shader: + -- Job of the VS: + -- read the data and position + -- identify if the bar needs to be drawn based on : + -- visibility of unit + -- distance of bar + -- value of the bar + -- the colormap of the bar needs to be interpolated here from a fixed define string? + --[[ -- https://community.khronos.org/t/constant-vec3-array-no-go/60184/8 + vec3 MyArray[4]=vec3[4]( + vec3(1.5,34.4,3.2), + vec3(1.6,34.1,1.2), + vec3(18.981777,6.258294,-27.141813), + vec3(1.0,3.0,1.0) + ); + ]]-- + -- + -- VS input: + -- uint barindex + -- this is the index of how manyeth bar it is in the list, where 0 is always health. and if an additional bar is needed, then increment accordingly + -- uint bartype + -- this is for where to get the colortable and 'icon' from + -- float unitheight + -- for correct offsetting + -- uint uniformSSBOloc + -- this is what uniform offset to read, 0 will be health? + -- float2 timers + -- this is for setting the time from which to calculate the timer based bars, set to 0 for no timer, start and end time maybe to calc diff? + -- uint unitID + -- or a featureID for features, those will be a separate list, but use hopefully the same shader. + -- + -- VS output + -- unit position + -- bar position + -- bar 'scale' + -- bar basecolor + -- bar colormap vec3[3] + -- bar value + -- bar type + -- bar alpha + -- corner size + + +-- Geometry shader: + -- should only output anything if the bar actually needs to be drawn +-- Job of the geometry shader: + -- take the VS output params, and create the following bar components: + -- At furthest detail: + -- background which is same size as bar + -- the bar itself + -- 2*4 vertices + -- midrange: + -- a nicer 6 triangle cornered bar background + -- a cornered bar foreground + -- 2*8 vertices + -- closeup: + -- add the percentage value to the left of the bar + -- this is 4*4 vertices + -- full closeness + -- also write the 'name' of the bar type + -- GS output per vertex: + -- position on screen + -- Z depth (somehow with emission ordering from back to front? + -- UV coordinates -- this could get nasty quickly + -- vertex color + -- solid or textured + +-- Fragment shader: + -- if solid, interpolate vertex color, and straight up draw it + -- if uv mapped, sample the texture and draw it + +-- atlas plans: + -- 512 x 512 atlas + -- 16 rows in it + -- each number from 0 to 9, '.' % and space (the 15th.) 's', ':' + -- the text? + -- overlay textures for bars + -- symbol glyphs + +-- TODO +-- 1. enemy paralyzed is not visible? +-- enemy comms and fusions health? hide the ones which should be hidden! +-- check for invalidness on addbars -- dont +-- better maintenance of bartypes and watch lists +-- feature bars fade out faster -- done +-- CLOAKED UNITSES -- done +-- Healthbars color correction -- done +-- Hide buildbars when at full hp - or convert them to build bars? -- done +-- todo some tex filtering issues on healthbar tops and bottoms :/ -- done +-- TODO: some GAIA shit? -- done +-- TODO: enemy comms and fus and decoy fus should not get healthbars! -- done +-- TODO: allies dont get reload bars? Do Specs see them? -- done (it was f'ed up previously) +-- TODO: correct draw order (after highlightunit) -- done +-- TODO: when reiniting feature bars, also check for resurrect/reclaim status -- done, just dont reinit them on playerchanged, no point! + -- now this is problematic, as the gadget only sends us an event on first reclaim event + -- we must assume that all features + -- feature bars dont actually need a reinit, now do they? +-- TODO: make numbers, glyphs optional? -- done, but untested + +--/luarules benchmark corak armpw 100 10 2000 + +local drawWhenGuiHidden = false + +local healthbartexture = "LuaUI/Images/healtbars_exo4.tga" + +-- a little explanation for 'bartype' +-- 0: default percentage progress bar +-- 1: timer based full textured bar, with time left being read from unitformindex +-- 2: timer based progress bar, with start and end times reading time left from uniformindex, uniformindex + 1 and timeInfo.x +-- 3: default percentage bar with overlayed texture progression +-- 5: The stockpile bar, nasty as hell but whatevs, it + +-- TODO: should be a freaking bitmask instead +-- bit 0: use overlay texture false/true +-- bit 1: show glyph icon +-- bit 2: use percentage style display +-- bit 3: use timeleft style display (2 and 3 mutually exclusive!) +-- bit 4: use integernumber style display (stockpile) +-- bit 5: get progress from nowtime-uniform2 / (uniform3 - uniform2) +-- bit 6: flash bar at 1hz +local bitUseOverlay = 1 +local bitShowGlyph = 2 +local bitPercentage = 4 +local bitTimeLeft = 8 +local bitIntegerNumber = 16 +local bitGetProgress = 32 +local bitFlashBar = 64 +local bitColorCorrect = 128 + +-- unit uniform index map: +-- 0: building +-- 1: NONE , +-- 2: shield/reloadstart/stockpile +-- 3: reloadend? +-- 4: emp damage /paralyze +-- 5: capture + +-- Feature uniform index map: +-- 0: NONE +-- 1: resurrect +-- 2: reclaim + +local barTypeMap = { -- WHERE SHOULD WE STORE THE FUCKING COLORS? + health = { + mincolor = {1.0, 0.0, 0.0, 1.0}, + maxcolor = {0.0, 1.0, 0.0, 1.0}, + --bartype = 0, + bartype = bitPercentage + bitColorCorrect, + hidethreshold = 0.99, + uniformindex = 32, -- if its >20, then its health/maxhealth + uvoffset = 0.0625, -- the X offset of the icon for this bar + }, + shield = { + mincolor = {0.15, 0.4, 0.4, 1.0}, + maxcolor = {0.3, 0.8, 0.8, 1.0}, + --bartype = 3, + bartype = bitShowGlyph + bitUseOverlay + bitPercentage, + hidethreshold = 0.99, + uniformindex = 2, -- if its >20, then its health/maxhealth + uvoffset = 0.3125, -- the X offset of the icon for this bar + }, + capture = { + mincolor = {0.5, 0.25, 0.0, 1.0}, + maxcolor = {1.0, 0.5, 0.0, 1.0}, + --bartype = 3, + bartype = bitShowGlyph + bitUseOverlay + bitPercentage, + hidethreshold = 0.99, + uniformindex = 5, -- if its >20, then its health/maxhealth + uvoffset = 0.1875, -- the X offset of the icon for this bar + }, + stockpile = { + mincolor = {0.1, 0.1, 0.1, 1.0}, + maxcolor = {0.1, 0.1, 0.1, 1.0}, + --bartype = 5, + bartype = bitShowGlyph + bitUseOverlay + bitIntegerNumber, + hidethreshold = 1.99, + uniformindex = 2, -- if its >20, then its health/maxhealth + uvoffset = 0.4375, -- the X offset of the icon for this bar + }, + emp_damage = { + mincolor = {0.4, 0.4, 0.8, 1.0}, + maxcolor = {0.6, 0.6, 1.0, 1.0}, + --bartype = 3, + bartype = bitShowGlyph + bitUseOverlay + bitPercentage, + hidethreshold = 0.99, + uniformindex = 4, -- if its >20, then its health/maxhealth + uvoffset = 0.5625, -- the X offset of the icon for this bar + }, + reload = { + mincolor = {0.03, 0.4, 0.4, 1.0}, + maxcolor = {0.05, 0.6, 0.6, 1.0}, + --bartype = 2, + bartype = bitShowGlyph + bitUseOverlay + bitGetProgress, + hidethreshold = 0.99, + uniformindex = 2, -- and 3! + uvoffset = 0.6875, -- the X offset of the icon for this bar + }, + building = { + mincolor = {1.0, 1.0, 1.0, 1.0}, + maxcolor = {1.0, 1.0, 1.0, 1.0}, + --bartype = 3, + bartype = bitShowGlyph + bitUseOverlay + bitPercentage, + hidethreshold = 0.999, + uniformindex = 0, -- if its >20, then its health/maxhealth + uvoffset = 0.9375, -- the X offset of the icon for this bar + }, + paralyzed = { + mincolor = {0.6, 0.6, 1.0, 1.0}, + maxcolor = {0.6, 0.6, 1.0, 1.0}, + --bartype = 1, + bartype = bitShowGlyph + bitUseOverlay + bitFlashBar + bitTimeLeft, + hidethreshold = 0.99, + uniformindex = 4, -- if its >20, then its health/maxhealth + uvoffset = 0.8125, -- the X offset of the icon for this bar + }, + featurehealth = { + mincolor = {0.25, 0.25, 0.25, 1.0}, + maxcolor = {0.65, 0.65, 0.65, 1.0}, + --bartype = 0, + bartype = bitShowGlyph + bitPercentage, + hidethreshold = 0.99, + uniformindex = 33, -- if its >20, then its health/maxhealth + uvoffset = 0.125, -- the X offset of the icon for this bar + }, + featurereclaim = { + mincolor = {0.00, 1.00, 0.00, 1.0}, + maxcolor = {0.85, 1.00, 0.85, 1.0}, + --bartype = 0, + bartype = bitShowGlyph + bitPercentage, + hidethreshold = 0.99, + uniformindex = 2, -- if its >20, then its health/maxhealth + uvoffset = 0.5, -- the X offset of the icon for this bar + }, + featureresurrect = { + mincolor = {0.75, 0.15, 0.75, 1.0}, + maxcolor = {1.0, 0.2, 1.0, 1.0}, + --bartype = 0, + bartype = bitShowGlyph + bitPercentage, + hidethreshold = 0.99, + uniformindex = 1, -- if its >20, then its health/maxhealth + uvoffset = 0.25, -- the X offset of the icon for this bar + }, +} + +for barname, bt in pairs(barTypeMap) do + local cache = {} + for i=1,20 do cache[i] = 0 end + + --cache[1] = unitDefHeights[unitDefID] + additionalheightaboveunit * effectiveScale -- height + --cache[2] = effectiveScale + --cache[3] = 0.0 -- unused + cache[4] = bt.uvoffset -- glyph uv offset + + cache[5] = bt.bartype -- bartype int + --cache[6] = unitBars[unitID] - 1 -- bar index (how manyeth per unit) + cache[7] = bt.uniformindex -- ssbo location offset (> 20 for health) + + cache[9] = bt.mincolor[1] + cache[10] = bt.mincolor[2] + cache[11] = bt.mincolor[3] + cache[12] = bt.mincolor[4] + + cache[13] = bt.maxcolor[1] + cache[14] = bt.maxcolor[2] + cache[15] = bt.maxcolor[3] + cache[16] = bt.maxcolor[4] + + bt['cache'] = cache +end + + +-------------------------------------------------------------------------------- +-------------------------------------------------------------------------------- + +local spec, fullview = spGetSpectatingState() +local myAllyTeamID = Spring.GetMyAllyTeamID() +local GetUnitWeaponState = Spring.GetUnitWeaponState + +local chobbyInterface + +local unitDefIgnore = {} -- commanders! +local unitDefhasShield = {} -- value is shield max power +local unitDefReactiveArmor = {} -- value is armor health +local unitDefCanStockpile = {} -- 0/1? +local unitDefHeights = {} -- maps unitDefs to height +local unitDefHideDamage = {} +local unitDefPrimaryWeapon = {} -- the index for reloadable weapon on unitdef weapons + +local unitBars = {} -- we need this additional table of {[unitID] = {barhealth, barrez, barreclaim}} +local unitCaptureWatch = {} +local unitShieldWatch = {} -- maps unitID to last shield value +local unitReactiveArmorWatch = {} +local unitEmpDamagedWatch = {} +local unitParalyzedWatch = {} +local unitStockPileWatch = {} +local unitReloadWatch = {} + +local featureDefHeights = {} -- maps FeatureDefs to height +local featureBars = {} -- we need this additional table of {[featureid] = {barhealth, barrez, barreclaim}} + +--local empDecline = 1 / 40 --magic +local minReloadTime = 4 -- weapons reloading slower than this willget bars + +local featureHealthVBO +local featureResurrectVBO +local featureReclaimVBO + +local barScale = 1 -- Option 'healthbarsscale' +local variableBarSizes = true -- Option 'healthbarsvariable' + +--local resurrectableFeaturesFast = {} -- value is this is for keeping an eye on resurrectable features, maybe store resurrect progress here? +--local resurrectableFeaturesSlow = {} -- this is for keeping an eye on resurrectable features, maybe store resurrect progress here? +--local reclaimableFeaturesSlow = {} -- for faster updates of features being reclaimed/rezzed +--local reclaimableFeaturesFast = {} -- for faster updates of features being reclaimed/rezzed + +-------------------------------------------------------------------------------- +-- GL4 Backend stuff: +local healthBarVBO = nil +local healthBarShader = nil + +local LuaShader = gl.LuaShader +local InstanceVBOTable = gl.InstanceVBOTable + +--local uploadAllElements = InstanceVBOTable.uploadAllElements +local pushElementInstance = InstanceVBOTable.pushElementInstance +local popElementInstance = InstanceVBOTable.popElementInstance + +-------------------- configurables ----------------------- +local additionalheightaboveunit = 24 --16? +local featureHealthDistMult = 7 -- how many times closer features have to be for their bars to show +local featureReclaimDistMult = 2 -- how many times closer features have to be for their bars to show +local featureResurrectDistMult = 1 -- how many times closer features have to be for their bars to show +local glphydistmult = 3.5 -- how much closer than BARFADEEND the bar has to be to start drawing numbers/icons. Numbers closer to 1 will make the glyphs be drawn earlier, high numbers will only shows glyphs when zoomed in hard. +local glyphdistmultfeatures = 1.8 -- how much closer than BARFADEEND the bar has to be to start drawing numbers/icons + + +local unitDefSizeMultipliers = {} -- table of unitdefID to a size mult (default 1.0) to override sizing of bars per unitdef +local skipGlyphsNumbers = 0.0 -- 0.0 is draw glyph and number, 1.0 means only numbers, 2.0 means only bars, + +local debugmode = false + +local barHeight = 0.9 +local shaderConfig = { -- these are our shader defines + HEIGHTOFFSET = 3, -- Additional height added to everything + CLIPTOLERANCE = 1.1, -- At 1.0 it wont draw at units just outside of view (may pop in), 1.1 is a good safe amount + MAXVERTICES = 64, -- The max number of vertices we can emit, make sure this is consistent with what you are trying to draw (tris 3, quads 4, corneredrect 8, circle 64 + CLIPTOLERANCE = 1.2, + BARWIDTH = 2.56, + BARHEIGHT = barHeight, + BGBOTTOMCOLOR = "vec4(0.25, 0.25, 0.25, 0.8)", + BGTOPCOLOR = "vec4(0.1, 0.1, 0.1, 0.8)", + BARSCALE = 4.0, + PERCENT_VISIBILITY_MAX = 0.99, + TIMER_VISIBILITY_MIN = 0.0, + BARSTEP = 10, -- pixels to downshift per new bar + BOTTOMDARKENFACTOR = 0.5, + BARFADESTART = 3200, + BARFADEEND = 3800, + ATLASSTEP = 0.0625, + MINALPHA = 0.2, +} +shaderConfig.BARCORNER = 0.06 + (shaderConfig.BARHEIGHT / 9) +shaderConfig.SMALLERCORNER = shaderConfig.BARCORNER * 0.6 + +if debugmode then + shaderConfig.DEBUGSHOW = 1 -- comment this to always show all bars +end + +local vsSrcPath = "LuaUI/Shaders/HealthbarsGL4.vert.glsl" +local gsSrcPath = "LuaUI/Shaders/HealthbarsGL4.geom.glsl" +local fsSrcPath = "LuaUI/Shaders/HealthbarsGL4.frag.glsl" +local fallbackVsSrcPath = "LuaUI/Shaders/HealthbarsGL4_nogs.vert.glsl" +local fallbackFsSrcPath = "LuaUI/Shaders/HealthbarsGL4_nogs.frag.glsl" + +local useGeometryShader = LuaShader.isGeometryShaderSupported + +local unitQuadVBO + +local shaderSourceCache = { + vssrcpath = vsSrcPath, + fssrcpath = fsSrcPath, + gssrcpath = gsSrcPath, + shaderName = "Health Bars Shader GL4", + uniformInt = { + healthbartexture = 0; + }, + uniformFloat = { + --addRadius = 1, + iconDistance = 27, + cameraDistanceMult = 1.0, + cameraDistanceMultGlyph = 4.0, + skipGlyphsNumbers = 0.0, + globalSizeMult = 1.0, + }, + shaderConfig = shaderConfig, + } + +local fallbackShaderSourceCache = { + vssrcpath = fallbackVsSrcPath, + fssrcpath = fallbackFsSrcPath, + shaderName = "Health Bars Shader GL4 (NoGS)", + uniformInt = { + healthbartexture = 0; + }, + uniformFloat = { + iconDistance = 27, + cameraDistanceMult = 1.0, + cameraDistanceMultGlyph = 4.0, + skipGlyphsNumbers = 0.0, + globalSizeMult = 1.0, + }, + shaderConfig = shaderConfig, + } + + +-- Walk through unitdefs for the stuff we need: +for udefID, unitDef in pairs(UnitDefs) do + if unitDef.customParams and unitDef.customParams.nohealthbars then + unitDefIgnore[udefID] = true + end --ignore debug units + + local shieldDefID = unitDef.shieldWeaponDef + local shieldPower = ((shieldDefID) and (WeaponDefs[shieldDefID].shieldPower)) or (-1) + if shieldPower > 1 then unitDefhasShield[udefID] = shieldPower + --spEcho("HAS SHIELD") + end + + local weapons = unitDef.weapons + local reloadTime = unitDef.reloadTime or 0 + local primaryWeapon = 1 + for i = 1, #weapons do + local WeaponDef = WeaponDefs[weapons[i].weaponDef] + if WeaponDef and WeaponDef.reload and WeaponDef.reload > reloadTime then + reloadTime = WeaponDef.reload + primaryWeapon = i + end + end + unitDefHeights[udefID] = unitDef.height + unitDefSizeMultipliers[udefID] = mathMin(1.45, math.max(0.85, (Spring.GetUnitDefDimensions(udefID).radius / 150) + mathMin(0.6, unitDef.power / 4000))) + mathMin(0.6, unitDef.health / 22000) + if unitDef.canStockpile then unitDefCanStockpile[udefID] = unitDef.canStockpile end + if reloadTime and reloadTime > minReloadTime then + if debugmode then spEcho("Unit with watched reload time:", unitDef.name, reloadTime, minReloadTime) end + unitDefPrimaryWeapon[udefID] = primaryWeapon + end + if unitDef.hideDamage == true then + unitDefHideDamage[udefID] = true + end + + if not unitDefhasShield[udefID] and not unitDef.hideDamage then + if unitDef.customParams.reactive_armor_health and unitDef.customParams.reactive_armor_restore then + unitDefReactiveArmor[udefID] = tonumber(unitDef.customParams.reactive_armor_health) + end + end +end + +for fdefID, featureDef in pairs(FeatureDefs) do + --spEcho(featureDef.name, featureDef.height) + featureDefHeights[fdefID] = featureDef.height or 32 +end + + +local function goodbye(reason) + spEcho("Healthbars GL4 widget exiting with reason: "..reason) + widgetHandler:RemoveWidget() +end + + + +local function initializeInstanceVBOTable(myName, usesFeatures) + local newVBOTable + local layout + local unitIDAttribID + if useGeometryShader then + layout = { + {id = 0, name = 'height_timers', size = 4}, + {id = 1, name = 'type_index_ssboloc', size = 4, type = GL.UNSIGNED_INT}, + {id = 2, name = 'startcolor', size = 4}, + {id = 3, name = 'endcolor', size = 4}, + {id = 4, name = 'instData', size = 4, type = GL.UNSIGNED_INT}, + } + unitIDAttribID = 4 + else + layout = { + {id = 2, name = 'height_timers', size = 4}, + {id = 3, name = 'type_index_ssboloc', size = 4, type = GL.UNSIGNED_INT}, + {id = 4, name = 'startcolor', size = 4}, + {id = 5, name = 'endcolor', size = 4}, + {id = 6, name = 'instData', size = 4, type = GL.UNSIGNED_INT}, + } + unitIDAttribID = 6 + end + newVBOTable = InstanceVBOTable.makeInstanceVBOTable( + layout, + 256, -- maxelements + myName, -- name + unitIDAttribID -- unitIDattribID (instData) + ) + if newVBOTable == nil then goodbye("Failed to create " .. myName) end + + if useGeometryShader then + local newVAO = gl.GetVAO() + newVAO:AttachVertexBuffer(newVBOTable.instanceVBO) + newVBOTable.VAO = newVAO + else + newVBOTable.VAO = InstanceVBOTable.makeVAOandAttach(unitQuadVBO, newVBOTable.instanceVBO) + end + if usesFeatures then newVBOTable.featureIDs = true end + return newVBOTable +end + + +local function initGL4() + -- Prefer geometry shader path when it actually compiles. This avoids false + -- negatives from capability detection on some Linux/AMD driver stacks. + healthBarShader = LuaShader.CheckShaderUpdates(shaderSourceCache) + useGeometryShader = (healthBarShader ~= nil) + + if not useGeometryShader then + -- A simple quad used by the non-GS path. + unitQuadVBO = gl.GetVBO(GL.ARRAY_BUFFER, false) + unitQuadVBO:Define(4, { + {id = 0, name = 'quadPos', size = 2}, + }) + unitQuadVBO:Upload({ + 0.0, 0.0, + 1.0, 0.0, + 0.0, 1.0, + 1.0, 1.0, + }) + + healthBarShader = LuaShader.CheckShaderUpdates(fallbackShaderSourceCache) + end + + if not healthBarShader then goodbye("Failed to compile health bars GL4 ") end + + healthBarVBO = initializeInstanceVBOTable("healthBarVBO", false) + + featureHealthVBO = initializeInstanceVBOTable("featureHealthVBO", true) -- we need separate ones for all feature health bars, as they seem to be + featureResurrectVBO = initializeInstanceVBOTable("featureResurrectVBO", true) + featureReclaimVBO = initializeInstanceVBOTable("featureReclaimVBO", true) + + if debugmode then + healthBarVBO.debug = true + end +end + +-------------------------------------------------------------------------------- +-------------------------------------------------------------------------------- + +local function addBarForUnit(unitID, unitDefID, barname, reason) + --Spring.Debug.TraceFullEcho() + if debugmode then Spring.Debug.TraceEcho(unitBars[unitID]) end + --spEcho("Caller1:", tostring()".name), "caller2:", tostring(debug.getinfo(3).name)) + unitDefID = unitDefID or spGetUnitDefID(unitID) + + -- Why? Because adding additional bars can be triggered from outside of unit tracker api + -- like EMP, where we assume that unit is already visible, however + -- debug units are not present in unittracker api! + if (unitDefID == nil) or unitDefIgnore[unitDefID] then return nil end + + local bt = barTypeMap[barname] + --if cnt == 1 then bt = barTypeMap.building end + --if cnt == 2 then bt = barTypeMap.reload end + local instanceID = unitID .. '_' .. barname + --spEcho(instanceID, barname, unitBars[unitID]) + if healthBarVBO.instanceIDtoIndex[instanceID] then + if debugmode then spEcho("Trying to add duplicate bar", unitID, instanceID, barname, reason, unitBars[unitID]) end + return + end -- we already have this bar ! + + if unitDefID == nil or Spring.ValidUnitID(unitID) == false or Spring.GetUnitIsDead(unitID) == true then -- dead or invalid + if debugmode then + Spring.Debug.TraceEcho("Tried to add a bar to dead/invalid/nounitdef unit", unitID, unitdefID, barname) + end + return nil + end + + if unitBars[unitID] == nil then + if debugmode then + spEcho("A unit has no bars yet", UnitDefs[unitDefID].name, spGetUnitPosition(unitID)) + Spring.Debug.TraceFullEcho() + Spring.SendCommands({"pause 1"}) + spEcho("No bars unit, last seen at", unitID) + Spring.MarkerAddPoint(spGetUnitPosition(unitID) ) + end + unitBars[unitID] = 1 + end + + unitBars[unitID] = unitBars[unitID] + 1 + + local effectiveScale = ((variableBarSizes and unitDefSizeMultipliers[unitDefID]) or 1.0) * barScale + + local healthBarTableCache = bt.cache + + healthBarTableCache[1] = unitDefHeights[unitDefID] + additionalheightaboveunit * effectiveScale -- height + healthBarTableCache[2] = effectiveScale + healthBarTableCache[6] = unitBars[unitID] - 1 -- bar index (how manyeth per unit) + + return pushElementInstance( + healthBarVBO, -- push into this Instance VBO Table + healthBarTableCache, + instanceID, -- this is the key inside the VBO Table, should be unique per unit + true, -- update existing element + nil, -- noupload, dont use unless you know what you want to batch push/pop + unitID) -- last one should be featureID! + -- we are returning here, to sign successful adds +end + + +local uniformcache = {0.0} + +local function updateReloadBar(unitID, unitDefID, reason) + if not unitDefPrimaryWeapon[unitDefID] then + return + end + + local reloadFrame = GetUnitWeaponState(unitID, unitDefPrimaryWeapon[unitDefID], 'reloadFrame') + local reloadTime = GetUnitWeaponState(unitID, unitDefPrimaryWeapon[unitDefID], 'reloadTime') + local gf = spGetGameFrame() + + if (reloadFrame == nil or reloadFrame > gf) and unitReloadWatch[unitID] == nil then + addBarForUnit(unitID, unitDefID, "reload", reason) + end + + if (reloadFrame and reloadTime and gl.SetUnitBufferUniforms) then + uniformcache[1] = reloadFrame - 30 * reloadTime + gl.SetUnitBufferUniforms(unitID, uniformcache, 2) + uniformcache[1] = reloadFrame + gl.SetUnitBufferUniforms(unitID, uniformcache, 3) + end +end + +local function removeBarFromUnit(unitID, barname, reason) -- this will bite me in the ass later, im sure, yes it did, we need to just update them :P + local instanceKey = unitID .. "_" .. barname + if healthBarVBO.instanceIDtoIndex[instanceKey] then + if debugmode then Spring.Debug.TraceEcho(reason) end + unitBars[unitID] = unitBars[unitID] - 1 + popElementInstance(healthBarVBO, instanceKey) + end +end + + +local function addBarsForUnit(unitID, unitDefID, unitTeam, unitAllyTeam, reason) -- TODO, actually, we need to check for all of these for stuff entering LOS + + if unitDefID == nil or Spring.ValidUnitID(unitID) == false or Spring.GetUnitIsDead(unitID) == true then + if debugmode then spEcho("Tried to add a bar to a dead or invalid unit", unitID, "at", spGetUnitPosition(unitID), reason) end + return + end + + unitBars[unitID] = unitBars[unitID] or 0 + + -- This is optionally passed, and it only important in one edge case: + -- If a unit is captured and thus immediately become outside of LOS, then the getunitallyteam is still the old ally team according to getUnitAllyTEam, and not the new allyteam. + unitAllyTeam = unitAllyTeam or Spring.GetUnitAllyTeam(unitID) + local health, maxHealth, paralyzeDamage, capture, build = spGetUnitHealth(unitID) + if (fullview or (unitAllyTeam == myAllyTeamID) or (unitDefHideDamage[unitDefID] == nil)) and (unitDefIgnore[unitDefID] == nil ) then + if debugmode and health == nil then + spEcho("Trying to add a healthbar to nil health unit", unitID, unitDefID) + local ux, uy, uz = spGetUnitPosition(unitID) + Spring.MarkerAddPoint(ux, uy, uz, "health") + end + addBarForUnit(unitID, unitDefID, "health", reason) + end + if unitDefhasShield[unitDefID] then + --spEcho("hasshield") + addBarForUnit(unitID, unitDefID, "shield", reason) + unitShieldWatch[unitID] = -1.0 + elseif unitDefReactiveArmor[unitDefID] then + unitReactiveArmorWatch[unitID] = unitDefReactiveArmor[unitDefID] + addBarForUnit(unitID, unitDefID, "shield", reason) + local armorHealth = Spring.GetUnitRulesParam(unitID, "reactiveArmorHealth") + if armorHealth then + uniformcache[1] = armorHealth / unitDefReactiveArmor[unitDefID] + gl.SetUnitBufferUniforms(unitID, uniformcache, 2) + end + end + + updateReloadBar(unitID, unitDefID, reason) + + if health ~= nil then + if build < 1 then + addBarForUnit(unitID, unitDefID, "building", reason) + end + --spEcho(unitID, unitDefID, unitDefCanStockpile[unitDefID]) + if debugmode then + if unitDefCanStockpile[unitDefID] then + spEcho("unitDefCanStockpile", unitAllyTeam, myAllyTeamID, fullview) + end + + end + + if unitDefCanStockpile[unitDefID] and ((unitAllyTeam == myAllyTeamID) or fullview) then + unitStockPileWatch[unitID] = 0.0 + addBarForUnit(unitID, unitDefID, "stockpile", reason) + end + if capture > 0 then + addBarForUnit(unitID, unitDefID, "capture", reason) + uniformcache[1] = capture + gl.SetUnitBufferUniforms(unitID, uniformcache, 5) + unitCaptureWatch[unitID] = capture + end + + if paralyzeDamage > 0 then + --TODO + + if Spring.GetUnitIsStunned(unitID) then + if unitParalyzedWatch[unitID] == nil then -- already paralyzed + unitParalyzedWatch[unitID] = 0.0 + -- if unit was already empd, remove that bar + if unitEmpDamagedWatch[unitID] then + unitEmpDamagedWatch[unitID] = nil + removeBarFromUnit(unitID, 'emp_damage', 'unitEmpDamagedWatch') + end + addBarForUnit(unitID, unitDefID, "paralyzed", reason) + end + else + if unitEmpDamagedWatch[unitID] == nil then + unitEmpDamagedWatch[unitID] = 0.0 + addBarForUnit(unitID, unitDefID, "emp_damage", reason) + end + end + end + end +end + +local function removeBarsFromUnit(unitID, reason) + for barname,v in pairs(barTypeMap) do + removeBarFromUnit(unitID, barname, reason) + end + unitShieldWatch[unitID] = nil + unitReactiveArmorWatch[unitID] = nil + unitCaptureWatch[unitID] = nil + unitEmpDamagedWatch[unitID] = nil + unitParalyzedWatch[unitID] = nil + unitStockPileWatch[unitID] = nil + unitReloadWatch[unitID] = nil + unitBars[unitID] = nil +end + + +local function addBarToFeature(featureID, barname) + if debugmode then Spring.Debug.TraceEcho() end + local featureDefID = Spring.GetFeatureDefID(featureID) + + local bt = barTypeMap[barname] + + local targetVBO = featureHealthVBO + if barname == 'featurereclaim' then targetVBO = featureReclaimVBO end + if barname == 'featureresurrect' then targetVBO = featureResurrectVBO end + + if targetVBO.instanceIDtoIndex[featureID] then return end -- already exists, bail + if featureBars[featureID] == nil then + featureBars[featureID] = 0 + end + featureBars[featureID] = featureBars[featureID] + 1 + + pushElementInstance( + targetVBO, -- push into this Instance VBO Table + {featureDefHeights[featureDefID] + additionalheightaboveunit, -- height + 1.0 * barScale, -- size mult + 0, -- timer end + bt.uvoffset, -- unused float + + bt.bartype, -- bartype int + featureBars[featureID] - 1, -- bar index (how manyeth per unit) + bt.uniformindex, -- ssbo location offset (> 20 for health) + 0, -- unused int + + bt.mincolor[1], bt.mincolor[2], bt.mincolor[3], bt.mincolor[4], + bt.maxcolor[1], bt.maxcolor[2], bt.maxcolor[3], bt.maxcolor[4], + 0, 0, 0, 0}, -- these are just padding zeros for instData, that will get filled in + featureID, -- this is the key inside the VBO Table, should be unique per unit + true, -- update existing element + nil, -- noupload, dont use unless you know what you want to batch push/pop + featureID) -- last one should be featureID! +end + + +local function removeBarFromFeature(featureID, targetVBO) + --spEcho("removeBarFromFeature", featureID, targetVBO.myName) + if not targetVBO.instanceIDtoIndex[featureID] then + return + end + + popElementInstance(targetVBO, featureID) + + local barCount = featureBars[featureID] + if not barCount then + return + end + + barCount = barCount - 1 + if barCount > 0 then + featureBars[featureID] = barCount + else + featureBars[featureID] = nil + end +end + +local function removeBarsFromFeature(featureID) + removeBarFromFeature(featureID, featureHealthVBO) + removeBarFromFeature(featureID, featureReclaimVBO) + removeBarFromFeature(featureID, featureResurrectVBO) +end + + +local function init() + InstanceVBOTable.clearInstanceTable(healthBarVBO) + unitCaptureWatch = {} + unitShieldWatch = {} -- maps unitID to last shield value + unitReactiveArmorWatch = {} + unitEmpDamagedWatch = {} + unitParalyzedWatch = {} + unitStockPileWatch = {} + unitReloadWatch = {} + unitBars = {} + for i, unitID in ipairs(Spring.GetAllUnits()) do -- gets radar blips too! + -- probably shouldnt be adding non-visible units + + if fullview then + addBarsForUnit(unitID, spGetUnitDefID(unitID), spGetUnitTeam(unitID), nil, 'initfullview') + else + local losstate = Spring.GetUnitLosState(unitID, myAllyTeamID) + if losstate.los then + addBarsForUnit(unitID, spGetUnitDefID(unitID), spGetUnitTeam(unitID), nil, 'initlos') + --spEcho(unitID, "IS in los") + else + --spEcho(unitID, "is not in los for ", myAllyTeamID) + end + end + end + +end + +local function initfeaturebars() + InstanceVBOTable.clearInstanceTable(featureHealthVBO) + InstanceVBOTable.clearInstanceTable(featureResurrectVBO) + InstanceVBOTable.clearInstanceTable(featureReclaimVBO) + for i, featureID in ipairs(Spring.GetAllFeatures()) do + local featureDefID = Spring.GetFeatureDefID(featureID) + --local resurrectname = Spring.GetFeatureResurrect(featureID) + --if resurrectname then + -- resurrectableFeatures[featureID] = true + -- if it has resurrect progress, then just straight up just store a bar here for it? + -- or shall we only instantiate bars when needed? probably number 2 is smarter... + --end -- maybe store resurrect progress here? + + if featureDefID then -- dont add features that we cant get the ID of + -- add a health bar for it (dont add one for pre-existing stuff) + widget:FeatureCreated(featureID) + else + + end + end +end + +--12:32 PM] Beherith: widget:PlayerChanged generalizations +--[12:33 PM] Beherith: So, I would like to ask if we have a general guideline or if @Floris knows anything about what circumstances should trigger UI GFX widget reinitialization +--[12:36 PM] Beherith: Here, I assume we can live with a few assumptions: +--1. UI GFX widgets are LOS dependent things, that either +-- A. Should look the same for all players on an ALLYteam +-- B. Could look different for each member of an ALLYTeam +--2. Always render different things for different ALLYteams +--This presents and interesting state for most widgets especially for SPECFULLVIEW +--Obviously, the biggest reason for needing to abstract this is to avoid boilerplate mistakes for most new GL4 widgets, which are --stateful, unlike most previous widgets (most of which collected things they wanted to draw every frame) +--[12:39 PM] Beherith: So I assume widget:PlayerChanged gets called on any legal player change, and should keep track of the following: +--1. spectating state +--2. specfullview state +--3. myAllyTeamID +--4. myTeamID +--[12:40 PM] Beherith: There are 3 real states someone can be in: +--1. player +--2. spectator no fullview +--3. spectator with fullview + +--(excluding godmode /globallos et al) +--[12:40 PM] Beherith: Transitions between any of the above 3 should trigger a full reinit +--[12:41 PM] Beherith: But some internal transitions, for stuff that is draw differently for allies might require additional checks, for spectators who have fullview off? + + +local function FeatureReclaimStartedHealthbars (featureID, step) -- step is negative for reclaim, positive for resurrect + --spEcho("FeatureReclaimStartedHealthbars", featureID) + + --gl.SetFeatureBufferUniforms(featureID, 0.5, 2) -- update GL + if step > 0 then addBarToFeature(featureID, 'featureresurrect') + else addBarToFeature(featureID, 'featurereclaim') end +end + +local function UnitCaptureStartedHealthbars(unitID, step) -- step is negative for reclaim, positive for resurrect + if debugmode then spEcho("UnitCaptureStartedHealthbars", unitID) end + --gl.SetFeatureBufferUniforms(featureID, 0.5, 2) -- update GL + local capture = select(4, spGetUnitHealth(unitID)) + uniformcache[1] = capture + gl.SetUnitBufferUniforms(unitID, uniformcache, 5) + unitCaptureWatch[unitID] = capture + addBarForUnit(unitID, spGetUnitDefID(unitID), 'capture', 'UnitCaptureStartedHealthbars') + +end + +--function widget:UnitDamaged(unitID, unitDefID, unitTeam, damage, paralyzer) +local function UnitParalyzeDamageHealthbars(unitID, unitDefID, damage) + if Spring.GetUnitIsStunned(unitID) then -- DO NOTE THAT: return: nil | bool stunned_or_inbuild, bool stunned, bool inbuild + if unitParalyzedWatch[unitID] == nil then -- already paralyzed + unitParalyzedWatch[unitID] = 0.0 + -- if unit was already empd, remove that bar + if unitEmpDamagedWatch[unitID] then + unitEmpDamagedWatch[unitID] = nil + removeBarFromUnit(unitID, 'emp_damage', 'unitEmpDamagedWatch') + end + addBarForUnit(unitID, unitDefID, "paralyzed", 'unitParalyzedWatch') + end + else + if unitEmpDamagedWatch[unitID] == nil then + unitEmpDamagedWatch[unitID] = 0.0 + addBarForUnit(unitID, unitDefID, "emp_damage", 'unitEmpDamagedWatch') + end + end +end + +local function ProjectileCreatedReloadHB(projectileID, unitID, weaponID, unitDefID) + local unitDefID = spGetUnitDefID(unitID) + + updateReloadBar(unitID, unitDefID, 'ProjectileCreatedReloadHB') +end + +local function debughealthbarsCmd(_, line) + debugmode = not debugmode + spEcho("Debug mode for HealthBars GL4 set to", debugmode) + healthBarVBO.debug = debugmode + return true +end + +function widget:Initialize() + widgetHandler:AddAction("debughealthbars", debughealthbarsCmd, nil, "t") + + if not gl.CreateShader then -- no shader support, so just remove the widget itself, especially for headless + widgetHandler:RemoveWidget() + return + end + WG['healthbars'] = {} + WG['healthbars'].getScale = function() + return barScale + end + WG['healthbars'].setScale = function(value) + barScale = value + init() + initfeaturebars() + end + WG['healthbars'].getHeight = function() + return barHeight + end + WG['healthbars'].setHeight = function(value) + barHeight = value + shaderSourceCache.shaderConfig.BARHEIGHT = barHeight + shaderSourceCache.shaderConfig.BARCORNER = 0.06 + (shaderConfig.BARHEIGHT / 9) + shaderSourceCache.shaderConfig.SMALLERCORNER = shaderConfig.BARCORNER * 0.6 + init() + initfeaturebars() + end + WG['healthbars'].getVariableSizes = function() + return variableBarSizes + end + WG['healthbars'].setVariableSizes = function(value) + variableBarSizes = value + init() + initfeaturebars() + end + WG['healthbars'].getDrawWhenGuiHidden = function() + return drawWhenGuiHidden + end + WG['healthbars'].setDrawWhenGuiHidden = function(value) + drawWhenGuiHidden = value + end + + initGL4() + + -- TODO: dont even bother drawing health bars for features that were present on frame 0 - no point in doing so + -- This is stuff like trees and map features, and scenario features + init() + initfeaturebars() +end + +function widget:Shutdown() + widgetHandler:RemoveAction("debughealthbars", "t") + spEcho("Healthbars GL4 unloaded hooks") +end + +function widget:FeatureReclaimStartedHealthbars(featureID, step) + FeatureReclaimStartedHealthbars(featureID, step) +end + +function widget:UnitCaptureStartedHealthbars(unitID, step) + UnitCaptureStartedHealthbars(unitID, step) +end + +function widget:UnitParalyzeDamageHealthbars(unitID, unitDefID, damage) + UnitParalyzeDamageHealthbars(unitID, unitDefID, damage) +end + +function widget:ProjectileCreatedReloadHB(projectileID, ownerID, weaponID) + ProjectileCreatedReloadHB(projectileID, ownerID, weaponID) +end + +function widget:RecvLuaMsg(msg, playerID) + if msg:sub(1,18) == 'LobbyOverlayActive' then + chobbyInterface = (msg:sub(1,19) == 'LobbyOverlayActive1') + end +end + +function widget:VisibleUnitAdded(unitID, unitDefID, unitTeam) + addBarsForUnit(unitID, unitDefID, unitTeam, nil, 'VisibleUnitAdded') +end + +function widget:VisibleUnitRemoved(unitID) + removeBarsFromUnit(unitID, 'VisibleUnitRemoved') +end + +function widget:CrashingAircraft(unitID, unitDefID, teamID) + removeBarsFromUnit(unitID,'CrashingAircraft') +end + +function widget:VisibleUnitsChanged(extVisibleUnits, extNumVisibleUnits) + unitBars = {} + unitShieldWatch = {} + unitReactiveArmorWatch = {} + unitCaptureWatch = {} + unitEmpDamagedWatch = {} + unitParalyzedWatch = {} + unitStockPileWatch = {} + unitReloadWatch = {} + spec, fullview = spGetSpectatingState() + myAllyTeamID = Spring.GetMyAllyTeamID() + + + InstanceVBOTable.clearInstanceTable(healthBarVBO) -- clear all instances + for unitID, unitDefID in pairs(extVisibleUnits) do + addBarsForUnit(unitID, unitDefID, spGetUnitTeam(unitID), nil, "VisibleUnitsChanged") -- TODO: add them with noUpload = true + end + --uploadAllElements(healthBarVBO) -- upload them all +end + +function widget:PlayerChanged(playerID) + + local currentspec, currentfullview = spGetSpectatingState() + local currentTeamID = Spring.GetMyTeamID() + local currentAllyTeamID = Spring.GetMyAllyTeamID() + local currentPlayerID = Spring.GetMyPlayerID() + local reinit = false + + if debugmode then spEcho("HBGL4 widget:PlayerChanged",'spec', currentspec, 'fullview', currentfullview, 'teamID', currentTeamID, 'allyTeamID', currentAllyTeamID, "playerID", currentPlayerID) end + + -- cases where we need to trigger: + if (currentspec ~= spec) or -- we transition from spec to player, yes this is needed + (currentfullview ~= fullview) or -- we turn on or off fullview + ((currentAllyTeamID ~= myAllyTeamID) and not currentfullview) -- our ALLYteam changes, and we are not in fullview + + then + -- do the actual reinit stuff, but first change my own + reinit = true + if debugmode then spEcho("HBGL4 triggered a playerchanged reinit") end + + end + -- save the state: + spec = currentspec + fullview = currentfullview + myAllyTeamID = currentAllyTeamID + --if reinit then init() end +end + + +function widget:GameFrame(n) + + if debugmode then + InstanceVBOTable.locateInvalidUnits(healthBarVBO) + InstanceVBOTable.locateInvalidUnits(featureHealthVBO) + end + -- Units: + -- check shields and armor + if n % 3 == 0 then + for unitID, oldshieldPower in pairs(unitShieldWatch) do + local shieldOn, shieldPower = Spring.GetUnitShieldState(unitID) + if shieldOn == false then shieldPower = 0.0 end + if oldshieldPower ~= shieldPower then + if shieldPower == nil then + removeBarFromUnit(unitID, "shield", "unitShieldWatch") + else + uniformcache[1] = shieldPower / (unitDefhasShield[spGetUnitDefID(unitID)]) + gl.SetUnitBufferUniforms(unitID, uniformcache, 2) + end + unitShieldWatch[unitID] = shieldPower + end + end + + -- todo: armor should be completely different but idk how to set up a new bar type + for unitID, oldArmorValue in pairs(unitReactiveArmorWatch) do + local newArmorValue = Spring.GetUnitRulesParam(unitID, "reactiveArmorHealth") + if newArmorValue ~= oldArmorValue then + if newArmorValue == nil then + removeBarFromUnit(unitID, "shield", "unitReactiveArmorWatch") + else + if not newArmorValue then + newArmorValue = 0 + end + uniformcache[1] = newArmorValue / unitDefReactiveArmor[spGetUnitDefID(unitID)] + gl.SetUnitBufferUniforms(unitID, uniformcache, 2) + end + unitReactiveArmorWatch[unitID] = newArmorValue + end + end + end + + -- todo paralyzed and EMP doesnt work for enemy units :( + -- check EMP'd units + if (n + 1) % 3 == 0 then + for unitID, oldempvalue in pairs(unitEmpDamagedWatch) do + local health, maxHealth, newparalyzeDamage, capture, build = spGetUnitHealth(unitID) + if newparalyzeDamage and oldempvalue ~= newparalyzeDamage then + if newparalyzeDamage == 0 then + unitEmpDamagedWatch[unitID] = nil + removeBarFromUnit(unitID, "emp_damage",'unitEmpDamagedWatch') + else + uniformcache[1] = newparalyzeDamage/ maxHealth + unitEmpDamagedWatch[unitID] = newparalyzeDamage + gl.SetUnitBufferUniforms(unitID, uniformcache, 4) + end + end + end + end + + -- check Paralyzed units + if (n+2) % 3 == 0 then + for unitID, paralyzetime in pairs(unitParalyzedWatch) do + if Spring.GetUnitIsStunned(unitID) then + local health, maxHealth, paralyzeDamage, capture, build = spGetUnitHealth(unitID) + --uniformcache[1] = math.floor((paralyzeDamage - maxHealth)) / (maxHealth * empDecline)) + if paralyzeDamage then + + -- this returns something like 1.20 which somehow turns into seconds somewhere unsearchable, currently wrong display + -- this needs conditional fixing within an if Spring.GetModOptions().emprework + uniformcache[1] = paralyzeDamage / maxHealth + --spEcho("Paralyze damages", paralyzeDamage, maxHealth) + --spEcho("Paralyze damage cur", (paralyzeDamage / maxHealth)) + + gl.SetUnitBufferUniforms(unitID, uniformcache, 4) + end + else + unitParalyzedWatch[unitID] = nil + removeBarFromUnit(unitID, "paralyzed", 'unitEmpDamagedWatch') + addBarForUnit(unitID, unitDefID, "emp_damage",'unitEmpDamagedWatch') + unitEmpDamagedWatch[unitID] = 1.0 + end + end + end + + -- check capture progress? + if (n % 3) == 2 then + for unitID, captureprogress in pairs(unitCaptureWatch) do + local capture = select(4, spGetUnitHealth(unitID)) + if capture and capture ~= captureprogress then + uniformcache[1] = capture + gl.SetUnitBufferUniforms(unitID, uniformcache, 5) + unitCaptureWatch[unitID] = capture + end + if capture == 0 or capture == nil then + removeBarFromUnit(unitID, 'capture', 'unitCaptureWatch') + unitCaptureWatch[unitID] = nil + end + end + end + + -- check stockpile progress + if (n % 5) == 2 then + for unitID, stockpilebuild in pairs(unitStockPileWatch) do + local numStockpiled, numStockpileQued, stockpileBuild = Spring.GetUnitStockpile(unitID) + if stockpileBuild and stockpileBuild ~= stockpilebuild then + -- we somehow need to forward 3 vars, all 3 of the above. packed into a float, this is nasty + --spEcho("Stockpiling", numStockpiled, numStockpileQued, stockpileBuild) + if numStockpiled == nil then Spring.Debug.TraceFullEcho(nil,nil,nil, 'nostockpile', unitID, spGetUnitPosition(unitID)) end + + uniformcache[1] = numStockpiled + stockpileBuild -- less hacky + --uniformcache[1] = 128*numStockpileQued + numStockpiled + stockpileBuild -- the worlds nastiest hack + unitStockPileWatch[unitID] = stockpileBuild + gl.SetUnitBufferUniforms(unitID, uniformcache, 2) + end + end + end +end + +local rezreclaim = {0.0, 1.0} +function widget:FeatureCreated(featureID) + local featureDefID = Spring.GetFeatureDefID(featureID) + local gameFrame = spGetGameFrame() + -- some map-supplied features dont have a model, in these cases modelpath == "" + if FeatureDefs[featureDefID].name ~= 'geovent' and FeatureDefs[featureDefID].modelpath ~= '' then + --spEcho(FeatureDefs[featureDefID].name) + --featureBars[featureID] = 0 -- this is already done in AddBarToFeature + + local health,maxhealth,rezProgress = Spring.GetFeatureHealth(featureID) + + if gameFrame > 0 then + addBarToFeature(featureID, 'featurehealth') + else + if health ~= maxhealth then addBarToFeature(featureID, 'featurehealth') end + end + + if not fullview then + local featureX, featureY, featureZ = spGetFeaturePosition(featureID) + if featureX and not spIsPosInLos(featureX, featureY, featureZ, myAllyTeamID) then + return + end + end + + if rezProgress > 0 then + addBarToFeature(featureID, 'featureresurrect') + end + + local _, _, _, _, reclaimLeft = Spring.GetFeatureResources(featureID) + + if reclaimLeft < 1.0 then + addBarToFeature(featureID, 'featurereclaim') + end + + if rezProgress > 0 or reclaimLeft < 1 then + -- We have to update the feature uniform buffers in this case, as features can be created with less than max health on the map with FP_featureplacer + rezreclaim[1] = rezProgress -- resurrect progress + rezreclaim[2] = reclaimLeft -- reclaim percent + gl.SetFeatureBufferUniforms(featureID, rezreclaim, 1) -- update GL, at offset of 1 + end + + end +end + +function widget:FeatureDestroyed(featureID) + if debugmode then spEcho("FeatureDestroyed",featureID, featureBars[featureID]) end + removeBarsFromFeature(featureID) + featureBars[featureID] = nil +end + +function widget:DrawScreenEffects() + -- using DrawScreenEffects so healthbars render after deferred lighting, + -- distortion, bloom and tonemapping passes — keeps bar colors uncolored + -- and unaffected by water/heat distortion. The shader still does world->clip + -- via engine cameraViewProj UBO, and depth-test still occludes against terrain. + --spEcho(Engine.versionFull ) + if chobbyInterface then return end + if not drawWhenGuiHidden and Spring.IsGUIHidden() then return end + + if spGetGameFrame() % 90 == 0 then + --spEcho("healthBarVBO",healthBarVBO.usedElements, "featureHealthVBO",featureHealthVBO.usedElements) + end + if healthBarVBO.usedElements > 0 or featureHealthVBO.usedElements > 0 then -- which quite strictly, is impossible anyway + local disticon = Spring.GetConfigInt("UnitIconDistance", 200) * 27.5 -- iconLength = unitIconDist * unitIconDist * 750.0f; + gl.Culling(false) + gl.Blending(GL.SRC_ALPHA, GL.ONE_MINUS_SRC_ALPHA) + gl.DepthTest(true) + gl.DepthMask(true) + gl.Texture(0,healthbartexture) + healthBarShader:Activate() + healthBarShader:SetUniform("iconDistance",disticon) + if not debugmode then healthBarShader:SetUniform("cameraDistanceMult",1.0) end + healthBarShader:SetUniform("cameraDistanceMultGlyph", glphydistmult) + healthBarShader:SetUniform("skipGlyphsNumbers",skipGlyphsNumbers) --0.0 is everything, 1.0 means only numbers, 2.0 means only bars, + if healthBarVBO.usedElements > 0 then + if useGeometryShader then + healthBarVBO.VAO:DrawArrays(GL.POINTS,healthBarVBO.usedElements) + else + healthBarVBO.VAO:DrawArrays(GL.TRIANGLE_STRIP, 4, 0, healthBarVBO.usedElements) + end + end + -- below its the feature bars being drawn: + healthBarShader:SetUniform("cameraDistanceMultGlyph", glyphdistmultfeatures) + if featureHealthVBO.usedElements > 0 then + if not debugmode then healthBarShader:SetUniform("cameraDistanceMult",featureHealthDistMult) end + if useGeometryShader then + featureHealthVBO.VAO:DrawArrays(GL.POINTS,featureHealthVBO.usedElements) + else + featureHealthVBO.VAO:DrawArrays(GL.TRIANGLE_STRIP, 4, 0, featureHealthVBO.usedElements) + end + end + if featureResurrectVBO.usedElements > 0 then + if not debugmode then healthBarShader:SetUniform("cameraDistanceMult",featureResurrectDistMult) end + if useGeometryShader then + featureResurrectVBO.VAO:DrawArrays(GL.POINTS,featureResurrectVBO.usedElements) + else + featureResurrectVBO.VAO:DrawArrays(GL.TRIANGLE_STRIP, 4, 0, featureResurrectVBO.usedElements) + end + end + if featureReclaimVBO.usedElements > 0 then + if not debugmode then healthBarShader:SetUniform("cameraDistanceMult",featureReclaimDistMult) end + if useGeometryShader then + featureReclaimVBO.VAO:DrawArrays(GL.POINTS,featureReclaimVBO.usedElements) + else + featureReclaimVBO.VAO:DrawArrays(GL.TRIANGLE_STRIP, 4, 0, featureReclaimVBO.usedElements) + end + end + + healthBarShader:Deactivate() + gl.Texture(false) + gl.Blending(GL.SRC_ALPHA, GL.ONE_MINUS_SRC_ALPHA) + gl.Culling(false) + gl.DepthTest(false) + gl.DepthMask(false) --"BK OpenGL state resets", reset to default state + end +end + +function widget:GetConfigData(data) + return { + barScale = barScale, + barHeight = barHeight, + variableBarSizes = variableBarSizes, + drawWhenGuiHidden = drawWhenGuiHidden + } +end + +function widget:SetConfigData(data) + barScale = data.barScale or barScale + if data.variableBarSizes ~= nil then + variableBarSizes = data.variableBarSizes + end + if data.drawWhenGuiHidden ~= nil then + drawWhenGuiHidden = data.drawWhenGuiHidden + end + if data.barHeight ~= nil then + barHeight = data.barHeight + shaderSourceCache.shaderConfig.BARHEIGHT = barHeight + shaderSourceCache.shaderConfig.BARCORNER = 0.06 + (shaderConfig.BARHEIGHT / 9) + shaderSourceCache.shaderConfig.SMALLERCORNER = shaderConfig.BARCORNER * 0.6 + end +end + +return widget end)() +local forward=(function()local gadget={} +local gadget = gadget ---@type Gadget + +function gadget:GetInfo() + return { + name = "Healthbars Widget Forwarding", + desc = "Notifies widgets that a feature reclaim or resurrect action has begun, updates GL Uniforms, and also notifies on capture start, emp damage, reload", + author = "Beherith", -- ty Sprung + date = "2021.11.25", + license = "GNU GPL, v2 or later", + layer = -1, + enabled = true + } +end + + +if gadgetHandler:IsSyncedCode() then + + local SendToUnsynced = SendToUnsynced + local spGetGameFrame = Spring.GetGameFrame + local spGetUnitWeaponState = Spring.GetUnitWeaponState + + local forwardedFeatureIDs = {} -- so we only forward the start event once + local forwardedCaptureUnitIDs = {} + local weapondefsreload = {} + local unitreloadframe = {} -- maps unitID to next frame it can shoot its primary weapon, cause lasers retrigger projetileCreated every frame + local minReloadTime = 5 -- in concerto with healthbars widget + + function gadget:AllowFeatureBuildStep(builderID, builderTeam, featureID, featureDefID, step) + -- VERY IMPORTANT: This also gets called on resurrect!, but its very hard to tell if its a reclaim, but we can make the mother of all assumptions: + -- features die at 100% metal value + -- step is negative if 'reclaiming' + -- step is large positive if refilling + -- step is small positive if rezzing + + local gf = spGetGameFrame() + --Spring.Echo("AllowFeatureBuildStep",gf,builderID, builderTeam, featureID, featureDefID, step) + if forwardedFeatureIDs[featureID] == nil or forwardedFeatureIDs[featureID] < gf then + forwardedFeatureIDs[featureID] = gf + SendToUnsynced("featureReclaimFrame", featureID, step) + end + return true + end + + function gadget:AllowUnitCaptureStep(builderID, builderTeam, unitID, unitDefID, part) + if forwardedCaptureUnitIDs[unitID] == nil then + forwardedCaptureUnitIDs[unitID] = true + SendToUnsynced("unitCaptureFrame", unitID, part) + end + return true + end + + function gadget:FeatureDestroyed(featureID, allyTeamID) + forwardedFeatureIDs[featureID] = nil + end + + function gadget:UnitDestroyed(unitID, unitDefID, unitTeam, attackerID, attackerDefID, attackerTeam, weaponDefID) + forwardedCaptureUnitIDs[unitID] = nil + unitreloadframe[unitID] = nil + end + + function gadget:UnitTaken(unitID) + forwardedCaptureUnitIDs[unitID] = nil + end + + function gadget:Initialize() + for udefID, unitDef in pairs(UnitDefs) do + local weapons = unitDef.weapons + local watchweaponID = nil + local longestreloadtime = -1 + local longestreloadindex + for i = 1, #weapons do + local WeaponDefID = weapons[i].weaponDef + local WeaponDef = WeaponDefs[WeaponDefID] + if WeaponDef.reload and WeaponDef.reload >0 and WeaponDef.reload >= longestreloadtime then + longestreloadtime = WeaponDef.reload + watchweaponID = WeaponDefID + longestreloadindex = i + end + end + if watchweaponID and longestreloadtime > minReloadTime then + --Spring.Echo("Unit with watched reload time:", unitDef.name, longestreloadtime, watchweaponID, udefID) + weapondefsreload[watchweaponID] = longestreloadindex + Script.SetWatchProjectile(watchweaponID, true) + end + end + end + + function gadget:ProjectileCreated(projectileID, ownerID, weaponID) -- needs: Script.SetWatchProjectile(weaponDefID, true) + --local unitDef = Spring.GetUnitDefID(ownerID) + --Spring.Echo("gadget:ProjectileCreated(",projectileID, ownerID, weaponID,weapondefsreload[weaponID],unitreloadframe[ownerID], ")") + local weaponIndex = weapondefsreload[weaponID] + + if weaponIndex then + local gf = spGetGameFrame() + local reloadFrame = spGetUnitWeaponState(ownerID, weaponIndex, 'reloadFrame') + + if unitreloadframe[ownerID] == nil or unitreloadframe[ownerID] <= gf then + SendToUnsynced("projetileCreatedReload", projectileID, ownerID, weaponID) + unitreloadframe[ownerID] = reloadFrame + end + end + end + +else + + local glSetFeatureBufferUniforms = gl.SetFeatureBufferUniforms + local GetFeatureResources = Spring.GetFeatureResources + local GetFeaturePosition = Spring.GetFeaturePosition + local IsPosInLos = Spring.IsPosInLos + local rezreclaim = {0.0, 1.0} -- this is just a small table cache, so we dont allocate a new table for every update + local forwardedFeatureIDsResurrect = {} -- so we only forward the start event once + local forwardedFeatureIDsReclaim = {} -- so we only forward the start event once + local myTeamID = Spring.GetMyTeamID() + local myAllyTeamID = Spring.GetMyAllyTeamID() + local _, fullview = Spring.GetSpectatingState() + local IsUnitInLos = Spring.IsUnitInLos + local GetFeatureHealth = Spring.GetFeatureHealth + local headless = false + + function gadget:PlayerChanged(playerID) + myTeamID = Spring.GetMyTeamID() + myAllyTeamID = Spring.GetMyAllyTeamID() + _, fullview = Spring.GetSpectatingState() + end + + function featureReclaimFrame(cmd, featureID, step) + --Spring.Echo("HandleFeatureReclaimStarted", featureID) + if not fullview then + local x, y, z = GetFeaturePosition(featureID) + if x and not IsPosInLos(x, y, z, myAllyTeamID) then + return + end + end + + rezreclaim[1] = select(3, GetFeatureHealth( featureID )) -- resurrect progress + rezreclaim[2] = select(5, GetFeatureResources(featureID)) -- reclaim percent + + --Spring.Echo('rezreclaim', rezreclaim[1], rezreclaim[2]) + + if not headless then glSetFeatureBufferUniforms(featureID, rezreclaim, 1) end -- update GL, at offset of 1 + + if step > 0 and forwardedFeatureIDsResurrect[featureID] == nil and Script.LuaUI("FeatureReclaimStartedHealthbars") then + forwardedFeatureIDsResurrect[featureID] = true + --Spring.Echo("HandleFeatureReclaimStartedHealthbars", featureID, step) + Script.LuaUI.FeatureReclaimStartedHealthbars(featureID, step) + end + + if step < 0 and forwardedFeatureIDsReclaim[featureID] == nil and Script.LuaUI("FeatureReclaimStartedHealthbars") then + forwardedFeatureIDsReclaim[featureID] = true + --Spring.Echo("HandleFeatureReclaimStartedHealthbars", featureID, step) + Script.LuaUI.FeatureReclaimStartedHealthbars(featureID, step) + end + end + + function unitCaptureFrame(cmd, unitID, step) + if not fullview and not IsUnitInLos(unitID, myAllyTeamID) then return end + if Script.LuaUI("UnitCaptureStartedHealthbars") then + --Spring.Echo("UnitCaptureStartedHealthbars", unitID, step) + Script.LuaUI.UnitCaptureStartedHealthbars(unitID, step) + end + end + + function projetileCreatedReload(cmd, projectileID, ownerID, weaponID) + --Spring.Echo("unsynced projetileCreatedReload", projectileID, ownerID, weaponID, fullview, Spring.GetUnitTeam(ownerID)) + if fullview or Spring.GetUnitTeam(ownerID) == myTeamID then + if Script.LuaUI("ProjectileCreatedReloadHB") then + --Spring.Echo("G:ProjectileCreatedReloadHB", projectileID, ownerID, weaponID) + Script.LuaUI.ProjectileCreatedReloadHB(projectileID, ownerID, weaponID) + end + end + end + + function gadget:FeatureDestroyed(featureID, allyTeamID) + forwardedFeatureIDsResurrect[featureID] = nil + forwardedFeatureIDsReclaim[featureID] = nil + end + + function gadget:UnitDamaged(unitID, unitDefID, unitTeam, damage, paralyzer) + --Spring.Echo("gadget:UnitDamaged",unitID, unitDefID, unitTeam, damage, paralyzer) + if paralyzer then + if not fullview and not IsUnitInLos(unitID, myAllyTeamID) then return end + + if damage > 0 then + if Script.LuaUI("UnitParalyzeDamageHealthbars") then + --Spring.Echo("UnitParalyzeDamageHealthbars", unitID, step) + Script.LuaUI.UnitParalyzeDamageHealthbars(unitID, unitDefID, damage) + end + if Script.LuaUI("UnitParalyzeDamageEffect") then + --Spring.Echo("UnitParalyzeDamageHealthbars", unitID, step) + Script.LuaUI.UnitParalyzeDamageEffect(unitID, unitDefID, damage) + end + end + end + end + + function gadget:Initialize() + headless = Spring.GetConfigInt("Headless", 0) > 0 + gadgetHandler:AddSyncAction("featureReclaimFrame", featureReclaimFrame) + gadgetHandler:AddSyncAction("unitCaptureFrame", unitCaptureFrame) + gadgetHandler:AddSyncAction("projetileCreatedReload", projetileCreatedReload) + end + + function gadget:ShutDown() + gadgetHandler:RemoveSyncAction("featureReclaimFrame") + gadgetHandler:RemoveSyncAction("unitCaptureFrame") + gadgetHandler:RemoveSyncAction("projetileCreatedReload") + end +end + +return gadget end)() +local widgetEvents=(function()local gadget={} +local ordinarySpring=Spring +local Spring=setmetatable({GetUnitLosState=function(id,ally,raw)if id==widgetEventUnit and ally==ordinarySpring.GetMyAllyTeamID()and raw==true then return widgetEventLos end;return ordinarySpring.GetUnitLosState(id,ally,raw)end},{__index=ordinarySpring}) +if gadgetHandler:IsSyncedCode() then return end + +local gadget = gadget ---@type Gadget + +function gadget:GetInfo() + return { + name = "Widget Events", + desc = "Tells widgets about events they can know about", + author = "Sprung, Klon, Beherith", + date = "2015-05-27", + license = "PD", + layer = 0, + enabled = true, + } +end + +local spAreTeamsAllied = Spring.AreTeamsAllied +local spGetMyAllyTeamID = Spring.GetMyAllyTeamID +local spGetSpectatingState = Spring.GetSpectatingState +local spGetUnitLosState = Spring.GetUnitLosState + +local myAllyTeamID, myTeamID, spec, specFullView + +function gadget:Initialize() + myTeamID = Spring.GetMyTeamID() + myAllyTeamID = Spring.GetMyAllyTeamID() + spec, specFullView = spGetSpectatingState() +end + +function gadget:PlayerChanged() + myTeamID = Spring.GetMyTeamID() + myAllyTeamID = Spring.GetMyAllyTeamID() + spec, specFullView = spGetSpectatingState() +end + + +--[[ NB: these are proxies, not the actual lua functions currently linked LuaUI-side, + so it is safe to cache them here even if the underlying func changes afterwards ]] +local scriptUnitDestroyed = Script.LuaUI.UnitDestroyed +local scriptUnitDestroyedByTeam = Script.LuaUI.UnitDestroyedByTeam + +function gadget:UnitDestroyed (unitID, unitDefID, unitTeam, attUnitID, attUnitDefID, attTeamID) + local isAllyUnit = spAreTeamsAllied(unitTeam, myTeamID) + --Spring.Echo("Gadget:UnitDest", unitID, Script.LuaUI('UnitDestroyedByTeam') , "isAllyUnit", isAllyUnit, "spec", spec, "specFullView", specFullView) + -- we need to check if any widget uses the callin, otherwise it is not bound and will produce error spam + if Script.LuaUI('UnitDestroyedByTeam') then + if spec then + scriptUnitDestroyedByTeam (unitID, unitDefID, unitTeam, attTeamID) + if not specFullView and not isAllyUnit and (spGetUnitLosState(unitID, myAllyTeamID, true) % 2 == 1) then + scriptUnitDestroyed (unitID, unitDefID, unitTeam) + end + else + local attackerInLos = attUnitID and (spGetUnitLosState(attUnitID, myAllyTeamID, true) % 2 == 1) + if isAllyUnit then + scriptUnitDestroyedByTeam (unitID, unitDefID, unitTeam, attackerInLos and attTeamID or nil) + elseif spGetUnitLosState(unitID, myAllyTeamID, true) % 2 == 1 then + scriptUnitDestroyed (unitID, unitDefID, unitTeam) + scriptUnitDestroyedByTeam (unitID, unitDefID, unitTeam, attackerInLos and attTeamID or nil) + end + end + else + if not isAllyUnit and (not (spec and specFullView) and (spGetUnitLosState(unitID, spGetMyAllyTeamID(), true) % 2 == 1)) then + scriptUnitDestroyed (unitID, unitDefID, unitTeam) + end + end +end + +local scriptUnitTaken = Script.LuaUI.UnitTaken +function gadget:UnitTaken(unitID, unitDefID, oldTeamID, newTeamID) + -- we need to notify my team if a unit transfer between two other teams happens, within my radar or los + local unitwasandisenemy = not (spAreTeamsAllied(oldTeamID, myTeamID) or spAreTeamsAllied(newTeamID, myTeamID)) + local unitinmyradarorlos = (spGetUnitLosState(unitID, myAllyTeamID, true) % 4 > 0) + -- Spring.Echo("gadget:UnitGiven",unitID, unitDefID, oldTeamID, newTeamID, unitwasandisenemy, unitinmyradarorlos) + if unitwasandisenemy and unitinmyradarorlos then + scriptUnitTaken(unitID, unitDefID, oldTeamID, newTeamID) + end +end + +local scriptUnitGiven = Script.LuaUI.UnitGiven +function gadget:UnitGiven(unitID, unitDefID, newTeamID, oldTeamID) + -- we need to notify my team if a unit transfer between two other teams happens, within my radar or los + local unitwasandisenemy = not (spAreTeamsAllied(oldTeamID, myTeamID) or spAreTeamsAllied(newTeamID, myTeamID)) + local unitinmyradarorlos = (spGetUnitLosState(unitID, myAllyTeamID, true) % 4 > 0) + -- Spring.Echo("gadget:UnitGiven",unitID, unitDefID, newTeamID, oldTeamID, unitwasandisenemy, unitinmyradarorlos) + if unitwasandisenemy and unitinmyradarorlos then + scriptUnitGiven(unitID, unitDefID, newTeamID, oldTeamID) + end +end + +local scriptUnitFinished = Script.LuaUI.UnitFinished +function gadget:UnitFinished(unitID, unitDefID, unitTeam) + if spec and specFullView then return end + -- Important: Enemy units finished within LOS do not get the respective widget:UnitFinished calls! + -- Also important: units that are created and finished in the same gameframe (like /give, or created fully built) are not in los yet, so this wont trigger! + local unitisenemy = not spAreTeamsAllied(unitTeam, myTeamID) + local isinlos = spGetUnitLosState(unitID, myAllyTeamID, true) % 2 + --Spring.Echo("gadget:UnitFinished",unitID, unitDefID, unitTeam, unitisenemy, isinlos) + if unitisenemy and (isinlos == 1) then + scriptUnitFinished(unitID, unitDefID, unitTeam) + end +end + +local scriptFeatureCreated = Script.LuaUI.FeatureCreated +function gadget:FeatureCreated(featureID, allyTeam) -- assume that features are always in LOS + local isAllyUnit = (allyTeam == myAllyTeamID) + --Spring.Echo("Gadget:FeatureCreated", featureID, FeatureDefs[Spring.GetFeatureDefID(featureID)].name, Script.LuaUI('FeatureCreated') , "isAllyUnit", isAllyUnit, "spec", spec, "specFullView", specFullView) + -- we need to check if any widget uses the callin, otherwise it is not bound and will produce error spam + if not isAllyUnit and (not (spec and specFullView)) and Script.LuaUI('FeatureCreated') then + --Spring.Echo("gadget:FeatureCreated",featureID, allyTeam) + scriptFeatureCreated(featureID, allyTeam) + end +end + +local scriptFeatureDestroyed = Script.LuaUI.FeatureDestroyed +function gadget:FeatureDestroyed(featureID, allyTeam) + -- assume that features are always in LOS + -- feauture allyTeam is equal to my allyteam when its a gaia feature, that is wierd + -- am i always allied with gaia? + local isAllyUnit = (allyTeam == myAllyTeamID) + --Spring.Echo("Gadget:FeatureDestroyed", featureID, FeatureDefs[Spring.GetFeatureDefID(featureID)].name, Script.LuaUI('FeatureDestroyed') , "isAllyUnit", isAllyUnit, "spec", spec, "specFullView", specFullView, allyTeam, Spring.GetMyTeamID()) + -- we need to check if any widget uses the callin, otherwise it is not bound and will produce error spam + if not isAllyUnit and (not (spec and specFullView)) and Script.LuaUI('FeatureDestroyed') then + --Spring.Echo("gadget:FeatureDestroyed",featureID, allyTeam) + scriptFeatureDestroyed(featureID, allyTeam) + end +end + +return gadget end)() +-- Original call order: tracker updates visibility, then stock healthbar policy. +-- All callback arguments originate in native admitted events, never browser UI. +local barsReady=false +for _,name in ipairs({'VisibleUnitAdded','VisibleUnitRemoved','VisibleUnitsChanged','FeatureReclaimStartedHealthbars','UnitCaptureStartedHealthbars','UnitParalyzeDamageHealthbars','ProjectileCreatedReloadHB'})do + listeners[name]=function(...) + if removed or not barsReady then return end + if name=='VisibleUnitAdded'then originalBuildAdded((...)) + elseif name=='VisibleUnitsChanged'then unitUniforms={};buildProgresses={};for id in pairs((...))do originalBuildAdded(id)end end + local result=bars[name](bars,...) + if name=='VisibleUnitRemoved'then local id=(...);unitUniforms[id]=nil;buildProgresses[id]=nil end + return result + end +end +for _,name in ipairs({'UnitCreated','UnitFinished','UnitDestroyed','UnitTaken','UnitGiven','UnitEnteredLos','UnitLeftLos'})do + _G[name]=function(...) + if name=='UnitFinished'then originalBuildFinished((...))end + tracker[name](tracker,...) + if name=='UnitDestroyed'then local id=(...);unitUniforms[id]=nil;buildProgresses[id]=nil end + end +end +for _,name in ipairs({'UnitDestroyed','UnitTaken','UnitGiven','UnitFinished','FeatureCreated','FeatureDestroyed'})do + listeners[name]=function(...)return _G[name](...)end +end +local widgetEventNames={UnitDestroyed=true,UnitTaken=true,UnitGiven=true,UnitFinished=true,FeatureCreated=true,FeatureDestroyed=true} +function WebbarHealthbarWidgetEvent(name,los,...) + assert(widgetEventNames[name],'Unknown original widget event') + assert(type(los)=='number'and los>=0 and los<=65535 and los%1==0,'Invalid native event LOS') + widgetEventUnit,widgetEventLos=(...),los + local ok,failure=pcall(widgetEvents[name],widgetEvents,...) + widgetEventUnit,widgetEventLos=nil,nil + if not ok then error(failure)end +end +function GameFrame(frame)originalBuildUpdated();tracker:GameFrame(frame);if not removed then bars:GameFrame(frame)end end +function PlayerChanged(player)widgetEvents:PlayerChanged(player);forward:PlayerChanged(player);tracker:PlayerChanged(player);if not removed then bars:PlayerChanged(player)end end +function UnitDamaged(id,definition,team,damage,paralyzer) + local publicDefinition=Spring.GetUnitDefID(id) + if publicDefinition then forward:UnitDamaged(id,publicDefinition,team,damage,paralyzer)end +end +function FeatureCreated(id,...)featureUniforms[id]=nil;if not removed and Spring.GetFeatureDefID(id)then bars:FeatureCreated(id,...)end end +function FeatureDestroyed(id,ally)forward:FeatureDestroyed(id,ally);if not removed then bars:FeatureDestroyed(id)end;featureUniforms[id]=nil end +function WebbarHealthbarSync(name,...) + local action=actions[name];if not action then return false end + -- Native event lists can include Gaia features outside this handle's reads. + -- Reject absent typed reads before the original forwarding body's callbacks. + if name=='featureReclaimFrame'and not Spring.GetFeatureDefID((...))then return false end + if name=='unitCaptureFrame'and not Spring.GetUnitDefID((...))then return false end + if name=='projetileCreatedReload'and not Spring.GetUnitDefID(select(2,...))then return false end + action(name,...);return true +end +function WebbarHealthbarInitialize() + widgetEvents:Initialize();forward:Initialize();tracker:Initialize() + for id in pairs(WG.unittrackerapi.visibleUnits)do originalBuildAdded(id)end + bars:Initialize();barsReady=true;return not removed +end +function WebbarHealthbarState() + local result={frame=Spring.GetGameFrame(),disabled=removed,rows={}} + if removed then return result end + for _,entry in ipairs({{'healthBarVBO',0},{'featureHealthVBO',1},{'featureResurrectVBO',2},{'featureReclaimVBO',3}})do + local buffer=assert(WG.VBOTableRegistry[entry[1]]);assert(buffer.instanceStep==20 and buffer.usedElements<=65536) + for i=1,buffer.usedElements do + local key,id=assert(buffer.indextoInstanceID[i]),nil + if entry[2]==0 then id=tonumber(key:match('^(%d+)_'))else id=key end + assert(type(id)=='number'and id>=0 and id%1==0) + local row={id=id,kind=entry[2],key=key,params={},uniforms={}} + local offset=(i-1)*20;for j=1,16 do row.params[j]=buffer.instanceData[offset+j]end + local data=(entry[2]==0 and unitUniforms or featureUniforms)[id] + for j=1,16 do row.uniforms[j]=data and data[j]or 0 end + local health,maxHealth + if entry[2]==0 then health,maxHealth=Spring.GetUnitHealth(id)else health,maxHealth=Spring.GetFeatureHealth(id)end + if health and maxHealth and maxHealth>0 then row.health={maxHealth,health} + elseif row.params[7]<20 then + -- No health read is published for hidden-damage units. This neutral pair + -- is unused by a non-health bar, whose original shader selects uniforms. + row.health={1,0} + end + if row.health then result.rows[#result.rows+1]=row end + end + end + assert(#result.rows<=65536);return result +end + +)WEBBAR_BARS"; --- /dev/null +++ b/rts/Game/WebbarNativeHealthbars.h @@ -0,0 +1,187 @@ +/* This file is part of the Spring engine (GPL v2 or later), see LICENSE.html */ +#pragma once +#include +#include "WebbarNativeHealthbarPolicy.h" +#include "WebbarHealthbarEvents.h" +#include "Lua/LuaWeaponDefs.h" +#include "Lua/LuaUnsyncedCtrl.h" +#include "Lua/LuaFeatureDefs.h" +#include "Lua/LuaConstGame.h" +#include "Sim/Features/Feature.h" +#include "Sim/Features/FeatureHandler.h" + +class WebbarNativeHealthbarReader; +// The original unsynced gadgets receive events for all teams and check native +// LOS/alliance before LuaUI. This event-only proxy preserves that routing; +// it has no Lua state and cannot elevate the reader's public API permissions. +class WebbarHealthbarRuleEvents final: public CEventClient { + WebbarNativeHealthbarReader* reader; +public: + explicit WebbarHealthbarRuleEvents(WebbarNativeHealthbarReader* reader): CEventClient("WebBAR original healthbar gadget forwarding",LUA_HANDLE_ORDER_RULES_UNSYNCED,false),reader(reader) {} + bool GetFullRead() const override { return true; } + bool WantsEvent(const std::string& name) override { return name == "UnitDamaged" || name == "UnitDestroyed" || name == "UnitFinished" || name == "UnitTaken" || name == "UnitGiven" || name == "FeatureCreated" || name == "FeatureDestroyed"; } + void UnitDamaged(const CUnit*,const CUnit*,float,int,int,bool) override; + void UnitDestroyed(const CUnit*,const CUnit*,int) override; + void UnitFinished(const CUnit*) override; + void UnitTaken(const CUnit*,int,int) override; + void UnitGiven(const CUnit*,int,int) override; + void FeatureCreated(const CFeature*) override; + void FeatureDestroyed(const CFeature*) override; +}; + +// Original stock policy in an unsynced, read-only native handle. Its GL +// compatibility boundary stores presentation values only in its own Lua state. +class WebbarNativeHealthbarReader final: public CLuaHandle { +public: + bool ready = false; + WebbarHealthbarRuleEvents ruleEvents; + WebbarNativeHealthbarReader(): CLuaHandle("WebBAR original healthbar policy", LUA_HANDLE_ORDER_UI, false, false),ruleEvents(this) { + 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); + // Original BAR diagnostics inspect only this private presentation state. + // Keep stack reads/traceback, without debug mutation, IO or OS libraries. + LUA_OPEN_LIB(L, luaopen_debug); + lua_getglobal(L, "debug"); lua_pushnil(L); + while (lua_next(L, -2)) { + const char* name = lua_tostring(L, -2); + const bool keep = name && (std::strcmp(name, "getinfo") == 0 || std::strcmp(name, "getlocal") == 0 || std::strcmp(name, "traceback") == 0); + lua_pop(L, 1); + if (!keep) { lua_pushvalue(L, -1); lua_pushnil(L); lua_rawset(L, -4); } + } + lua_pop(L, 1); 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, "FeatureDefs", LuaFeatureDefs::PushEntries) + && AddEntriesToTable(L, "Game", LuaConstGame::PushEntries); + if (ready) { + lua_getglobal(L, "Spring"); + // Echo only: the complete controller API would expose unrelated authority. + lua_pushcfunction(L, LuaUnsyncedCtrl::Echo); lua_setfield(L, -2, "Echo"); + #define HEALTHBAR_READ(name, method) lua_pushcfunction(L, LuaUnsyncedRead::method); lua_setfield(L, -2, name) + HEALTHBAR_READ("GetMyPlayerID", GetLocalPlayerID); + HEALTHBAR_READ("GetMyTeamID", GetLocalTeamID); + HEALTHBAR_READ("GetMyAllyTeamID", GetLocalAllyTeamID); + HEALTHBAR_READ("GetSpectatingState", GetSpectatingState); + HEALTHBAR_READ("IsUnitAllied", IsUnitAllied); + #undef HEALTHBAR_READ + } + lua_settop(L, 0); + if (ready) ready = LoadCode(L, WEBBAR_HEALTHBAR_POLICY, "Original BAR healthbar/tracker/forwarding policy"); + if (ready) { + lua_getglobal(L, "WebbarHealthbarInitialize"); + ready = RunCallIn(L, LuaHashString("WebbarHealthbarInitialize"), 0, 1) && lua_toboolean(L, -1); + lua_settop(L, 0); + } + if (ready) { + WebbarHealthbarEvents::Attach(this, [](void* self, lua_State* source, int args) { static_cast(self)->Sync(source, args); }); + eventHandler.AddClient(this); eventHandler.AddClient(&ruleEvents); + } else LOG_L(L_ERROR, "[WebBAR] original healthbar policy initialization failed"); + } + ~WebbarNativeHealthbarReader() override { WebbarHealthbarEvents::Detach(this); eventHandler.RemoveClient(&ruleEvents); KillLua(); } + bool WantsEvent(const std::string& name) override { + return ready && (name == "CollectGarbage" || name == "GameFrame" || name == "UnitCreated" || name == "UnitFinished" || name == "UnitDestroyed" || name == "UnitTaken" || name == "UnitGiven" || name == "UnitEnteredLos" || name == "UnitLeftLos" || name == "FeatureCreated" || name == "FeatureDestroyed"); + } + void Sync(lua_State* source, int args) { + if (!ready) return; + const int top = lua_gettop(L); + lua_getglobal(L, "WebbarHealthbarSync"); lua_pushstring(L, lua_tostring(source, 1)); + for (int i = 2; i <= args; ++i) lua_pushnumber(L, lua_tonumber(source, i)); + ready = RunCallIn(L, LuaHashString("WebbarHealthbarSync"), args, 0); + lua_settop(L, top); + } + int WidgetLos(const CUnit* unit) const { + // Original LuaRules has full read for this admission query. Supply only + // the actual event unit's flags for the viewed ally team, never a general + // hidden-unit read API or a broader permission on the presentation handle. + return teamHandler.IsValidAllyTeam(gu->myAllyTeam) ? unit->losStatus[gu->myAllyTeam] : 0; + } + void WidgetEvent(const char* name, int los, std::initializer_list args) { + if (!ready) return; + const int top = lua_gettop(L); + lua_getglobal(L, "WebbarHealthbarWidgetEvent"); lua_pushstring(L, name); lua_pushnumber(L, los); + for (const int value: args) lua_pushnumber(L, value); + ready = RunCallIn(L, LuaHashString("WebbarHealthbarWidgetEvent"), args.size()+2, 0); + lua_settop(L, top); + } + bool State(std::vector& packet) { + if (!ready) return false; + const int top = lua_gettop(L); + lua_getglobal(L, "WebbarHealthbarState"); + bool ok = RunCallIn(L, LuaHashString("WebbarHealthbarState"), 0, 1) && lua_istable(L, -1); + if (ok) { + lua_getfield(L, -1, "disabled"); ok = lua_type(L, -1) == LUA_TBOOLEAN; + if (lua_toboolean(L, -1)) packet[6] |= 4; lua_pop(L, 1); + lua_getfield(L, -1, "rows"); ok = ok && lua_istable(L, -1) && lua_objlen(L, -1) <= 65536; + const int rows = lua_gettop(L), count = ok ? lua_objlen(L, rows) : 0; + for (int i = 1; ok && i <= count; ++i) { + lua_rawgeti(L, rows, i); if (!lua_istable(L, -1)) { ok = false; break; } + lua_getfield(L, -1, "id"); const float id = lua_tonumber(L, -1); + ok = lua_type(L, -1) == LUA_TNUMBER && id >= 0 && id <= 65535 && std::floor(id) == id; lua_pop(L, 1); + lua_getfield(L, -1, "kind"); const float kind = lua_tonumber(L, -1); + ok = ok && lua_type(L, -1) == LUA_TNUMBER && kind >= 0 && kind <= 3 && std::floor(kind) == kind; lua_pop(L, 1); + const CUnit* unit = ok && kind == 0 ? unitHandler.GetUnit(int(id)) : nullptr; + const CFeature* feature = ok && kind != 0 ? featureHandler.GetFeature(int(id)) : nullptr; + const bool admitted = unit ? (!unit->isDead && (gu->spectatingFullView || unit->allyteam == gu->myAllyTeam || unit->IsInLosForAllyTeam(gu->myAllyTeam))) : feature && (gu->spectatingFullView || feature->IsInLosForAllyTeam(gu->myAllyTeam)); + std::array row{}; row[0] = uint32_t(ok ? id : 0); row[1] = uint32_t(ok ? kind : 0); + const auto floats = [&](const char* name, int length, int offset, bool params) { + lua_getfield(L, -1, name); bool valid = lua_istable(L, -1) && lua_objlen(L, -1) == size_t(length); + for (int j = 0; valid && j < length; ++j) { + lua_rawgeti(L, -1, j+1); const float value = lua_tonumber(L, -1); + valid = lua_type(L, -1) == LUA_TNUMBER && std::isfinite(value); + if (params && j >= 4 && j < 8) { + valid = valid && value >= 0 && value <= (j == 4 ? 255 : j == 5 ? 63 : 65535) && std::floor(value) == value; + row[offset+j] = uint32_t(valid ? value : 0); + } else std::memcpy(&row[offset+j], &value, 4); + lua_pop(L, 1); + } + lua_pop(L, 1); return valid; + }; + ok = ok && floats("params",16,2,true) && floats("uniforms",16,18,false) && floats("health",2,34,false); + if (ok && admitted) { packet.insert(packet.end(), row.begin(), row.end()); ++packet[7]; } + lua_pop(L, 1); + } + } + lua_settop(L, top); return ok; + } +}; +inline void WebbarHealthbarRuleEvents::UnitDamaged(const CUnit* unit,const CUnit* attacker,float damage,int weaponDefID,int projectileID,bool paralyzer) { + if (!reader->ready || !unit || !paralyzer || !(gu->spectatingFullView || unit->allyteam == gu->myAllyTeam || unit->IsInLosForAllyTeam(gu->myAllyTeam))) return; + reader->CLuaHandle::UnitDamaged(unit,attacker,damage,weaponDefID,projectileID,paralyzer); +} +inline void WebbarHealthbarRuleEvents::UnitDestroyed(const CUnit* unit,const CUnit*,int) { reader->WidgetEvent("UnitDestroyed",reader->WidgetLos(unit),{unit->id,unit->unitDef->id,unit->team}); } +inline void WebbarHealthbarRuleEvents::UnitFinished(const CUnit* unit) { reader->WidgetEvent("UnitFinished",reader->WidgetLos(unit),{unit->id,unit->unitDef->id,unit->team}); } +inline void WebbarHealthbarRuleEvents::UnitTaken(const CUnit* unit,int oldTeam,int newTeam) { reader->WidgetEvent("UnitTaken",reader->WidgetLos(unit),{unit->id,unit->unitDef->id,oldTeam,newTeam}); } +inline void WebbarHealthbarRuleEvents::UnitGiven(const CUnit* unit,int oldTeam,int newTeam) { reader->WidgetEvent("UnitGiven",reader->WidgetLos(unit),{unit->id,unit->unitDef->id,newTeam,oldTeam}); } +inline void WebbarHealthbarRuleEvents::FeatureCreated(const CFeature* feature) { reader->WidgetEvent("FeatureCreated",0,{feature->id,feature->allyteam}); } +inline void WebbarHealthbarRuleEvents::FeatureDestroyed(const CFeature* feature) { reader->WidgetEvent("FeatureDestroyed",0,{feature->id,feature->allyteam}); } +namespace WebbarNativeHealthbars { +inline WebbarNativeHealthbarReader* reader = nullptr; +inline std::array perspective{-2,-2,-2,-2,-2}; +inline uint32_t epoch = 0; +inline std::vector published; +inline bool Enabled() { return std::getenv("WEBBAR_NATIVE_HEALTHBARS") && std::getenv("WEBBAR_BROWSER") && !std::getenv("WEBBAR_NETWORK"); } +inline void Prepare() { + if (!Enabled() || gs->frameNum < -1) return; + const std::array actual{gu->myPlayerNum,gu->myTeam,gu->myAllyTeam,int(gu->spectating),int(gu->spectatingFullView)}; + if (reader && perspective == actual) return; + delete reader; reader = nullptr; perspective = actual; if (++epoch == 0) ++epoch; + published.clear(); reader = new WebbarNativeHealthbarReader; +} +inline void Publish() { + Prepare(); if (!reader) return; + // WSH1 is optional visual state, independent of bridge9 saves and orders. + std::vector packet{0x31485357u,uint32_t(gs->frameNum),epoch,uint32_t(gu->myPlayerNum),uint32_t(gu->myTeam),uint32_t(gu->myAllyTeam),uint32_t(gu->spectating)|(uint32_t(gu->spectatingFullView)<<1),0,0,0,0,0}; + if (!reader->State(packet)) { packet.resize(12); packet[7] = 0; packet[6] |= 4; } + if (packet.size() == published.size() && std::equal(packet.begin()+2,packet.end(),published.begin()+2)) return; + published = packet; + MAIN_THREAD_EM_ASM({ if (Module['webbarNativeHealthbars']) Module['webbarNativeHealthbars'](HEAPU8.slice($0,$0+$1).buffer); },packet.data(),packet.size()*4); +} +inline void Free() { delete reader; reader = nullptr; published.clear(); } +} +static void PrepareWebbarNativeHealthbars() { WebbarNativeHealthbars::Prepare(); } +static void FreeWebbarNativeHealthbars() { WebbarNativeHealthbars::Free(); } --- a/rts/Game/WebbarNativeInfo.h +++ b/rts/Game/WebbarNativeInfo.h @@ -19,11 +19,33 @@ #include "Lua/LuaWeaponDefs.h" #include "Lua/LuaFeatureDefs.h" #include "Lua/LuaUnsyncedRead.h" +#include "Lua/LuaUnsyncedCtrl.h" #include "Game/Camera.h" #include "Lua/LuaConstGame.h" +#include "Lua/LuaConstCMD.h" +#include "Lua/LuaConfig.h" +#include "WebbarNativePipView.h" +#include "WebbarPipReadAdapter.h" +#include "WebbarNativeCursorSelection.h" +#include "WebbarNativeCursorVolumes.h" +#include "WebbarNativeCursorIcons.h" +#include "WebbarCursorWorldAdapter.h" #include "System/FileSystem/FileHandler.h" #include "System/FileSystem/VFSModes.h" #include "WebbarInfoReadAdapter.h" +#include "WebbarPlayerReadAdapter.h" +#include "WebbarNativeOrderRead.h" +#include "WebbarNativeOrderControl.h" +#include "WebbarNativeOrderTransport.h" +#include "WebbarNativeOrderWorld.h" +#include "WebbarNativeMinimap.h" +#include "WebbarOrderActionAdapter.h" +#include "WebbarOrderActionHost.h" +#include "WebbarOrderProposalStore.h" +#include "System/Config/ConfigHandler.h" +#include "WebbarNativeOrderLayout.h" +#include "WebbarOrderReadAdapter.h" +#include "Lua/LuaUtils.h" #include "System/UnorderedSet.hpp" struct WebbarInfoWorldView { @@ -54,16 +76,37 @@ && AddEntriesToTable(L, "WeaponDefs", LuaWeaponDefs::PushEntries) && AddEntriesToTable(L, "FeatureDefs", LuaFeatureDefs::PushEntries) && AddEntriesToTable(L, "Game", LuaConstGame::PushEntries); + if (ready && std::getenv("WEBBAR_NATIVE_ORDER_WORLD") != nullptr) ready = InstallOrderActionLogging(); if (ready) { lua_getglobal(L, "Spring"); lua_pushcfunction(L, ScreenRay); lua_setfield(L, -2, "TraceScreenRay"); + if (std::getenv("WEBBAR_NATIVE_PLAYER_READS") != nullptr) { + lua_pushcfunction(L, LuaUnsyncedRead::GetLocalTeamID); lua_setfield(L, -2, "GetLocalTeamID"); + lua_pushcfunction(L, LuaUnsyncedRead::GetLocalAllyTeamID); lua_setfield(L, -2, "GetLocalAllyTeamID"); + lua_pushcfunction(L, LuaUnsyncedRead::GetLocalPlayerID); lua_setfield(L, -2, "GetLocalPlayerID"); + lua_pushcfunction(L, LuaUnsyncedRead::GetSpectatingState); lua_setfield(L, -2, "GetSpectatingState"); + lua_pushcfunction(L, LuaUnsyncedRead::GetTeamColor); lua_setfield(L, -2, "GetTeamColor"); + } + if (std::getenv("WEBBAR_NATIVE_ORDER_READS") != nullptr) { + lua_pushcfunction(L, LuaUnsyncedRead::GetLocalAllyTeamID); lua_setfield(L, -2, "GetMyAllyTeamID"); + lua_pushcfunction(L, LuaUnsyncedRead::GetSpectatingState); lua_setfield(L, -2, "GetSpectatingState"); + lua_pushcfunction(L, LuaUnsyncedRead::GetLocalTeamID); lua_setfield(L, -2, "GetMyTeamID"); + lua_pushcfunction(L, ScreenCoordinates); lua_setfield(L, -2, "WorldToScreenCoords"); + } } + if (ready && std::getenv("WEBBAR_NATIVE_PIP_READS") != nullptr) ready = InstallPipReads(); + if (ready && std::getenv("WEBBAR_NATIVE_CURSOR_READS") != nullptr) ready = InstallCursorReads(); lua_settop(L, 0); std::string icons; CFileHandler file("gamedata/icontypes.lua", SPRING_VFS_MOD); ready = ready && file.LoadStringData(icons) && !icons.empty(); if (ready) ready = LoadCode(L, "webbarInfoIconTypes=(function()\n" + icons + "\nend)()", "Original Info icon types"); if (ready) ready = LoadCode(L, WEBBAR_INFO_READ_ADAPTER, "Original Info match specifications and native reads"); + if (ready && std::getenv("WEBBAR_NATIVE_ORDER_READS") != nullptr) ready = LoadCode(L, WEBBAR_ORDER_READ_ADAPTER, "Original Order native reads"); + if (ready && std::getenv("WEBBAR_NATIVE_ORDER_WORLD") != nullptr) ready = LoadCode(L, WEBBAR_ORDER_ACTION_ADAPTER, "Original Order action controllers"); + if (ready && std::getenv("WEBBAR_NATIVE_PLAYER_READS") != nullptr) ready = LoadCode(L, WEBBAR_PLAYER_READ_ADAPTER, "Original player-list native reads"); + if (ready && std::getenv("WEBBAR_NATIVE_PIP_READS") != nullptr) ready = LoadCode(L, WEBBAR_PIP_READ_ADAPTER, "Original PIP native reads"); + if (ready && std::getenv("WEBBAR_NATIVE_CURSOR_READS") != nullptr) ready = LoadCode(L, WEBBAR_CURSOR_WORLD_ADAPTER, "Original world cursor widgets"); if (!ready) LOG_L(L_ERROR, "[WebBAR] original Info read initialization failed"); } ~WebbarNativeInfoReader() override { KillLua(); } @@ -145,31 +188,130 @@ return ok; } - bool ReadWorld(const WebbarInfoWorldView& request, const std::vector& ids, uint32_t sampleDefinition, std::string& json) + bool OrderCommands(const std::vector& ids, std::vector& commands, int& commandPage) { if (!ready) return false; SetView(); - worldWidth = request.width; worldHeight = request.height; - // This private camera never replaces the engine's active camera or - // controller. Ray selection uses the original native volume/LOS logic. - worldView.SetPos(float3(request.position[0], request.position[1], request.position[2])); - worldView.SetRot(float3(request.rotation[0], request.rotation[1], request.rotation[2])); - worldView.SetVFOV(request.verticalFov); worldView.SetAspectRatio(request.aspect); - worldView.SetFrustumScales(float4(0, 0, request.nearPlane, request.farPlane)); - worldView.UpdateFrustum(); - // GuiTraceRay uses GetTransformMatrix(false). Headless feature creation - // initializes only the synced matrix; the native model drawer normally - // prepares these unsynced caches before a ray can inspect a feature. - // Carry over CFeatureDrawerData::UpdateDrawPos + UpdateCommon's matrix - // step. The browser feature stream draws the current native transform, - // so use that same interpolation endpoint, with no terrain correction. - for (const int id: featureHandler.GetActiveFeatureIDs()) { - CFeature* feature = featureHandler.GetFeature(id); - if (feature->noSelect || (!gu->spectatingFullView && !feature->IsInLosForAllyTeam(gu->myAllyTeam))) continue; - feature->drawPos = feature->GetDrawPos(1.0f); - feature->drawMidPos = feature->GetMdlDrawMidPos(); - feature->UpdateTransform(feature->drawPos, false); + const std::array view{gu->myTeam, gu->myAllyTeam, int(gu->spectatingFullView)}; + if (view != orderView) { orderSelected.clear(); orderView = view; } + std::unordered_set current(ids.begin(), ids.end()); + for (auto it = orderSelected.begin(); it != orderSelected.end();) { + if (current.find(*it) == current.end()) it = orderSelected.erase(it); else ++it; + } + for (const uint32_t id: ids) orderSelected.insert(int(id)); + const auto available = WebbarNativeOrder::Merge(orderSelected, selectedUnitsHandler.BuildIconsFirst()); + commands = available.commands; + if (!commands.empty()) { + // Pinned BAR ctrlpanel retains the original constructor defaults. + WebbarNativeOrder::Convert(commands, true, false); + WebbarNativeOrder::AppendPages(commands); + } + if (commands.size() > 8192) return false; + const int top = lua_gettop(L); + lua_getglobal(L, "WebbarLayoutOrder"); + lua_createtable(L, orderSelected.size(), 0); + int selectedIndex = 0; + for (const int id: orderSelected) { lua_pushnumber(L, id); lua_rawseti(L, -2, ++selectedIndex); } + lua_createtable(L, commands.size(), 0); selectedIndex = 0; + for (const auto& command: commands) { LuaUtils::PushCommandDesc(L, command); lua_rawseti(L, -2, ++selectedIndex); } + const bool layoutOk = RunCallIn(L, LuaHashString("WebbarLayoutOrder"), 2, LUA_MULTRET) + && WebbarNativeOrderLayout::Apply(L, top, commands); + lua_settop(L, top); + if (!layoutOk) return false; + commandPage = available.commandPage; + return true; + } + + bool ReadPlayers(std::string& json) + { + if (!ready) return false; + SetView(); + const int top = lua_gettop(L); + lua_getglobal(L, "WebbarReadPlayers"); + bool ok = RunCallIn(L, LuaHashString("WebbarReadPlayers"), 0, 1); + uint32_t nodes = 0; + if (ok) ok = JsonValue(-1, json, 0, nodes); + lua_settop(L, top); + CollectGarbage(true); + return ok; + } + + bool ReadOrder(const std::vector& ids, std::string& json) + { + std::vector commands; int page = 0; + if (!OrderCommands(ids, commands, page)) return false; + const int top = lua_gettop(L); + lua_getglobal(L, "WebbarReadOrder"); + lua_createtable(L, orderSelected.size(), 0); + int index = 0; + for (const int id: orderSelected) { lua_pushnumber(L, id); lua_rawseti(L, -2, ++index); } + lua_createtable(L, commands.size(), 0); index = 0; + for (const auto& command: commands) { LuaUtils::PushCommandDesc(L, command); lua_rawseti(L, -2, ++index); } + lua_pushnumber(L, page); + bool ok = RunCallIn(L, LuaHashString("WebbarReadOrder"), 3, 1); + if (ok) AddLifetimes(-1); + uint32_t nodes = 0; + if (ok) ok = JsonValue(-1, json, 0, nodes); + lua_settop(L, top); + CollectGarbage(true); + return ok; + } + + bool PlanOrderControl(const std::vector& ids, uint32_t kind, int commandID, int commandType, uint32_t flags, uint32_t paramCount, const float* params, std::vector& plan, std::string& activation) + { + std::vector commands; + int page = 0; + if (!OrderCommands(ids, commands, page)) return false; + const int availableID = kind == 2 && commandID == 31300 ? CMD_FIRE_STATE : commandID; + int index = -1; + for (size_t n = 0; n < commands.size(); ++n) { + const auto& desc = commands[n]; + if (desc.id != availableID || desc.type != commandType) continue; + if (index >= 0 || desc.disabled) return false; + index = int(n); } + if (index < 0) return false; + if (kind == 2) { + if (commandType != CMDTYPE_ICON_MODE || flags != 0 || (commandID != CMD_FIRE_STATE && commandID != 31300)) return false; + const int top = lua_gettop(L); + lua_getglobal(L, "WebbarReadOrder"); lua_newtable(L); lua_newtable(L); lua_pushnumber(L, 0); + bool ok = RunCallIn(L, LuaHashString("WebbarReadOrder"), 3, 1); + bool experimental = false; + if (ok && lua_istable(L, -1)) { + lua_getfield(L, -1, "modOptions"); + ok = lua_istable(L, -1); + if (ok) { lua_getfield(L, -1, "experimental_defend_firestate"); ok = lua_isboolean(L, -1); experimental = lua_toboolean(L, -1); } + } else ok = false; + lua_settop(L, top); + if (!ok || experimental != (commandID == 31300) || paramCount != (experimental ? 2u : 1u) || !std::isfinite(params[0]) || params[0] != std::floor(params[0]) || params[0] < 0 || params[0] > (experimental ? 4 : 2) || (experimental && params[1] != 1)) return false; + Command command(commandID); + for (uint32_t n = 0; n < paramCount; ++n) command.PushParam(params[n]); + plan.push_back(std::move(command)); + return true; + } + if (kind != 1 || paramCount != 0 || (flags & ~255u) || (flags & 3u) == 0 || commandType == CMDTYPE_CUSTOM || commandType == CMDTYPE_NEXT || commandType == CMDTYPE_PREV || commandType == CMDTYPE_ICON_BUILDING || (commandType == CMDTYPE_ICON_MODE && commands[index].params.size() < 2)) return false; + const WebbarNativeOrder::ControlInput input{bool(flags & 4u), bool(flags & 8u), bool(flags & 16u), bool(flags & 32u), bool(flags & 64u), bool(flags & 128u), configHandler->GetBool("InvertQueueKey")}; + WebbarNativeOrder::ControlPlan native(std::move(commands), input); + if (!native.SetActiveCommand(index, (flags & 3u) != SDL_BUTTON_LEFT) || native.unsupportedCustom) return false; + for (const auto& entry: native.commandsToGive) plan.push_back(std::get<0>(entry)); + if (native.activeIndex >= 0) { + const int top = lua_gettop(L); LuaUtils::PushCommandDesc(L, native.commands[native.activeIndex]); + uint32_t nodes = 0; const bool ok = JsonValue(-1, activation, 0, nodes); lua_settop(L, top); + if (!ok) return false; + } + return !plan.empty() || !activation.empty(); + } + +#include "WebbarNativeOrderWorldHost.inc" +#include "WebbarNativePipHost.inc" +#include "WebbarNativeCursorHost.inc" + + bool ReadWorld(const WebbarInfoWorldView& request, const std::vector& ids, uint32_t sampleDefinition, std::string& json) + { + if (!ready) return false; + SetView(); + PrepareOrderCamera(request); + PrepareInfoIcons(); const int top = lua_gettop(L); lua_getglobal(L, "WebbarReadInfoWorld"); lua_createtable(L, ids.size(), 0); @@ -179,7 +321,9 @@ lua_pushnumber(L, request.mouseX); lua_rawseti(L, -2, 1); lua_pushnumber(L, request.mouseY); lua_rawseti(L, -2, 2); for (int i = 0; i < 5; ++i) { lua_pushboolean(L, request.mouseFlags & (1u << i)); lua_rawseti(L, -2, i + 3); } + const bool previousInfoRead = readingWorldInfo; readingWorldInfo = true; bool ok = RunCallIn(L, LuaHashString("WebbarReadInfoWorld"), 3, 1); + readingWorldInfo = previousInfoRead; if (ok) AddLifetimes(-1); uint32_t nodes = 0; if (ok) ok = JsonValue(-1, json, 0, nodes); @@ -190,11 +334,14 @@ private: bool ready = false; + spring::unordered_set orderSelected; + std::array orderView{-1, -1, -1}; CCamera worldView{CCamera::CAMTYPE_VISCUL}; int worldWidth = 0, worldHeight = 0; static int ScreenRay(lua_State* L) { auto* self = static_cast(CLuaHandle::GetHandle(L)); + if (self->readingWorldInfo) return LuaUnsyncedRead::TraceScreenRayForCameraWithVolumes(L, &self->worldView, self->worldWidth, self->worldHeight, &self->infoIconVolumes); return LuaUnsyncedRead::TraceScreenRayForCamera(L, &self->worldView, self->worldWidth, self->worldHeight); } void AddLifetimes(int result) @@ -358,6 +505,9 @@ return 0; } +#include "WebbarNativeOrderPolicyHost.inc" +#include "WebbarNativePlayerControl.h" + static void Poll() { static const bool enabled = std::getenv("WEBBAR_NATIVE_INFO_READS") != nullptr; @@ -374,10 +524,13 @@ next = now + std::chrono::milliseconds(100); Header h; std::memcpy(&h, bytes.data(), sizeof(h)); if (h.magic != MAGIC || h.version != 1 || h.request == 0 || h.request == 0xffffffffu || h.generation == 0 || h.generation == 0xffffffffu) return; - const size_t rowOffset = sizeof(Header) + (h.kind == 5 ? sizeof(WebbarInfoWorldView) : 0); - if (h.kind < 1 || h.kind > 5 || (h.count == 0 && h.kind != 5) || h.count > (h.kind >= 3 ? 8192u : 64u) || (h.kind != 3 && h.kind != 5 && h.reserved[0]) || h.reserved[0] > 65535 || h.reserved[1] || size != int(rowOffset + h.count * sizeof(Row))) { Reply(h, 1); return; } + const size_t rowOffset = sizeof(Header) + ((h.kind == 5 || h.kind == 8) ? sizeof(WebbarInfoWorldView) : 0); + if (h.kind < 1 || h.kind > 8 || (h.kind == 7 && h.count != 0) || (h.count == 0 && h.kind != 5 && h.kind != 6 && h.kind != 7 && h.kind != 8) || h.count > (h.kind >= 3 ? 8192u : 64u) || (h.kind != 3 && h.kind != 5 && h.reserved[0]) || h.reserved[0] > 65535 || h.reserved[1] || size != int(rowOffset + h.count * sizeof(Row))) { Reply(h, 1); return; } if (h.kind == 4 && (std::getenv("WEBBAR_NATIVE_INFO_CAMERA") == nullptr || gu->spectating || webbarReplay::Enabled() || std::getenv("WEBBAR_NETWORK") != nullptr)) { Reply(h, 2); return; } if (h.kind == 5 && (std::getenv("WEBBAR_NATIVE_INFO_WORLD") == nullptr || std::getenv("WEBBAR_NETWORK") != nullptr)) { Reply(h, 2); return; } + if (h.kind == 6 && (std::getenv("WEBBAR_NATIVE_ORDER_READS") == nullptr || std::getenv("WEBBAR_NETWORK") != nullptr)) { Reply(h, 2); return; } + if (h.kind == 7 && (std::getenv("WEBBAR_NATIVE_PLAYER_READS") == nullptr || std::getenv("WEBBAR_NETWORK") != nullptr)) { Reply(h, 2); return; } + if (h.kind == 8 && (std::getenv("WEBBAR_NATIVE_PIP_READS") == nullptr || std::getenv("WEBBAR_NETWORK") != nullptr)) { Reply(h, 2); return; } const bool full = gu->spectatingFullView; if (h.team != gu->myTeam || h.allyTeam != gu->myAllyTeam || h.flags != uint32_t(full)) { Reply(h, 2); return; } if (h.frame > uint32_t(gs->frameNum) || uint32_t(gs->frameNum) - h.frame > 30) { Reply(h, 3); return; } @@ -391,11 +544,23 @@ const CUnit* unit = unitHandler.GetUnit(row.id); if (row.lifetime == 0xffffffffu || unit == nullptr || unit->team != gu->myTeam || WebbarHudLifetime(unit) != row.lifetime) { Reply(h, 2); return; } } + if (h.kind == 6 || h.kind == 8) { + const CUnit* unit = unitHandler.GetUnit(row.id); + if (!unit || unit->isDead || unit->noSelect || !CSelectedUnitsHandler::CanISelectTeam(playerHandler.Player(gu->myPlayerNum), unit->team)) { Reply(h, 2); return; } + } ids.push_back(row.id); } if (h.kind == 4) { std::string json; if (!ViewSelection(ids, json)) { Reply(h, 4); return; } Reply(h, 0, json); return; } if (!reader) reader = new WebbarNativeInfoReader; std::string json; + if (h.kind == 8) { + WebbarPipView view; std::memcpy(&view, bytes.data() + sizeof(Header), sizeof(view)); + if (!ValidWebbarPipView(view)) { Reply(h, 1); return; } + if (!reader->ReadPip(view, ids, json)) { Reply(h, 4); return; } + Reply(h, 0, json); return; + } + if (h.kind == 7) { if (!reader->ReadPlayers(json)) { Reply(h, 4); return; } Reply(h, 0, json); return; } + if (h.kind == 6) { if (!reader->ReadOrder(ids, json)) { Reply(h, 4); return; } Reply(h, 0, json); return; } if (h.kind == 5) { WebbarInfoWorldView view; std::memcpy(&view, bytes.data() + sizeof(Header), sizeof(view)); bool valid = view.width > 0 && view.width <= 16384 && view.height > 0 && view.height <= 16384 && view.mouseX >= -16384 && view.mouseX <= 16384 && view.mouseY >= -16384 && view.mouseY <= 16384 && !(view.mouseFlags & ~31u) && view.reserved == 0; @@ -408,6 +573,7 @@ if (!reader->Read(h.kind, ids, h.reserved[0], json)) { Reply(h, 4); return; } Reply(h, 0, json); } +#include "WebbarNativeCursorPoll.inc" } // namespace WebbarNativeInfo static void FreeWebbarNativeInfo() --- /dev/null +++ b/rts/Game/WebbarNativeMinimap.h @@ -0,0 +1,126 @@ +/* This file is part of the Spring engine (GPL v2 or later), see LICENSE.html */ +#pragma once +#include +#include +#include +#include "Game/GameHelper.h" +#include "Map/ReadMap.h" +#include "Sim/Units/Unit.h" +#include "System/SpringMath.h" +#include "System/FastMath.h" +namespace WebbarNativeOrder { +struct MinimapView { + int32_t mouseX, mouseY; + uint32_t width, height; + float originX, originZ, extentX, extentZ; + uint32_t rotation; + float farPlane; + uint32_t reserved[6]; +}; +static_assert(sizeof(MinimapView) == 64); +class MinimapProxy { +public: + static constexpr float DefaultUnitSize = 2.5f, DefaultUnitExp = 0.25f, DefaultCursorScale = -0.5f; + static bool Valid(const MinimapView& v) { + if (!v.width || !v.height || v.width > 16384 || v.height > 16384 || v.mouseX < -16384 || v.mouseY < -16384 || v.mouseX > 16384 || v.mouseY > 16384 || v.rotation > 3) return false; + for (auto value: v.reserved) if (value) return false; + return std::isfinite(v.originX) && std::isfinite(v.originZ) && std::isfinite(v.extentX) && std::isfinite(v.extentZ) + && v.originX >= 0 && v.originZ >= 0 && v.extentX > 0 && v.extentZ > 0 + && v.originX + v.extentX <= float3::maxxpos + 1 && v.originZ + v.extentZ <= float3::maxzpos + 1 + && std::isfinite(v.farPlane) && v.farPlane > 0 && v.farPlane <= 1048576; + } + MinimapProxy(const MinimapView& v, float unitBaseSize, float unitExponent): rotation(v.rotation), originX(v.originX), originZ(v.originZ), extentX(v.extentX), extentZ(v.extentZ) { + curDim = {int(v.width), int(v.height)}; + view.viewSizeY = v.height; + // setup the unit scaling + const float w = float(curDim.x); + const float h = float(curDim.y); + const float mapx = extentX; + const float mapy = extentZ; + const float ref = unitBaseSize / math::pow((200.0f * 200.0f), unitExponent); + const float dpr = ref * math::pow((w * h), unitExponent); + + unitSizeX = dpr * (mapx / w); + unitSizeY = dpr * (mapy / h); + unitSelectRadius = fastmath::apxsqrt(unitSizeX * unitSizeY); + + } + float3 Position(int x, int y) const { return GetMapPosition(x,y); } + CUnit* Select(const float3& position) const { return GetSelectUnit(position); } + float3 ProxyPosition(int x, int y) const { + RECOIL_DETAILED_TRACY_ZONE; + float3 mapPos = GetMapPosition(x, y); + const CUnit* unit = GetSelectUnit(mapPos); + + if (unit != nullptr) { + if (gu->spectatingFullView) { + mapPos = unit->midPos; + } else { + mapPos = unit->GetObjDrawErrorPos(gu->myAllyTeam); + mapPos.y = readMap->GetCurrMaxHeight(); + } + } + + return mapPos;} +private: + enum { ROTATION_0, ROTATION_90, ROTATION_180, ROTATION_270 }; + struct Point { int x=0,y=0; } curDim, tmpPos; + struct View { int viewPosY=0, viewSizeY=0; } view; + const View* globalRendering = &view; + int rotation; + float originX, originZ, extentX, extentZ, unitSizeX, unitSizeY, unitSelectRadius; + CUnit* GetSelectUnit(const float3& pos) const { + RECOIL_DETAILED_TRACY_ZONE; + CUnit* unit = CGameHelper::GetClosestUnit(pos, unitSelectRadius); + + if (unit == nullptr) + return unit; + + if ((unit->losStatus[gu->myAllyTeam] & (LOS_INLOS | LOS_INRADAR)) || gu->spectatingFullView) + return unit; + + return nullptr; +} + float3 GetMapPosition(int x, int y) const { + RECOIL_DETAILED_TRACY_ZONE; + const float mapX = extentX; + const float mapZ = extentZ; + + // mouse coordinate-origin is top-left of screen while + // the minimap origin is in its bottom-left corner, so + // (x = 0, y = 0) maps to world-coors ( 0, h, 0) + // (x = dim.x, y = 0) maps to world-coors (mapX, h, 0) + // (x = dim.x, y = dim.y) maps to world-coors (mapX, h, mapZ) + // (x = 0, y = dim.y) maps to world-coors ( 0, h, mapZ) + + // translate mouse coords orientation and origin to map coords + y = y - globalRendering->viewPosY + curDim.y - globalRendering->viewSizeY; + + float sx = std::clamp(float(x - tmpPos.x) / curDim.x, 0.0f, 1.0f); + float sz = std::clamp(float(y + tmpPos.y) / curDim.y, 0.0f, 1.0f); + + switch (rotation) + { + case ROTATION_0: + break; + + case ROTATION_90: + std::swap(sx, sz); + sx = 1.0f - sx; + break; + + case ROTATION_180: + sx = 1.0f - sx; + sz = 1.0f - sz; + break; + + case ROTATION_270: + std::swap(sx, sz); + sz = 1.0f - sz; + break; + } + + return {originX + mapX * sx, readMap->GetCurrMaxHeight(), originZ + mapZ * sz}; +} +}; +} --- /dev/null +++ b/rts/Game/WebbarNativeOrderControl.h @@ -0,0 +1,173 @@ +/* This file is part of the Spring engine (GPL v2 or later), see LICENSE.html */ +#pragma once + +#include +#include +#include +#include +#include +#include +#include +#include "System/MainDefines.h" +#include "System/Log/ILog.h" +#include "System/Misc/TracyDefs.h" +#include "Sim/Units/CommandAI/Command.h" +#include "Sim/Units/CommandAI/CommandDescription.h" + +namespace WebbarNativeOrder { +// Binding values are private inputs to original GUI code, never SDL globals. +struct ControlInput { + bool left, right, alt, ctrl, meta, shift, invertQueue; + uint8_t GetKeyModState(int key) const { + if (key == KMOD_ALT) return alt; + if (key == KMOD_CTRL) return ctrl; + if (key == KMOD_GUI) return meta; + if (key == KMOD_SHIFT) return shift; + return 0; + } +}; +class ControlPlan { +public: + ControlPlan(std::vector descriptors, ControlInput input): commands(std::move(descriptors)), keys(input), invertQueueKey(input.invertQueue) { + mouseState.buttons[SDL_BUTTON_LEFT].pressed = input.left; + mouseState.buttons[SDL_BUTTON_RIGHT].pressed = input.right; + } + std::vector commands; + std::vector> commandsToGive; + int activeIndex = -1; + bool unsupportedCustom = false; + unsigned char Options(bool rightMouseButton) { return CreateOptions(rightMouseButton); } + bool SetActiveCommand(int cmdIndex, bool rightMouseButton, bool fromPlayerInput = false) + { + RECOIL_DETAILED_TRACY_ZONE; + if (cmdIndex >= (int)commands.size()) + return false; + + if (cmdIndex < 0) { + // cancel the current command + defaultCmdMemory = -1; + needShift = false; + activeMousePress = false; + SetActiveCommandIndex(-1); + return true; + } + + SCommandDescription& cd = commands[cmdIndex]; + if (cd.disabled) + return false; + + lastKeySet.Reset(); + + switch (cd.type) { + case CMDTYPE_ICON: { + Command c(cd.id); + if (cd.id != CMD_STOP) { + c.SetOpts(CreateOptions(rightMouseButton)); + + if (invertQueueKey && ((cd.id < 0) || (cd.id == CMD_STOCKPILE))) + c.SetOpts(c.GetOpts() ^ SHIFT_KEY); + } + GiveCommand(c, true, fromPlayerInput); + break; + } + case CMDTYPE_ICON_MODE: { + int newMode = atoi(cd.params[0].c_str()) + 1; + + if (newMode > (static_cast(cd.params.size())-2)) + newMode = 0; + + // not really required + char t[16]; + SNPRINTF(t, sizeof(t), "%d", newMode); + cd.params[0] = t; + + GiveCommand(Command(cd.id, CreateOptions(rightMouseButton), newMode), true, fromPlayerInput); + forceLayoutUpdate = true; + break; + } + case CMDTYPE_NUMBER: + case CMDTYPE_ICON_MAP: + case CMDTYPE_ICON_AREA: + case CMDTYPE_ICON_UNIT: + case CMDTYPE_ICON_UNIT_OR_MAP: + case CMDTYPE_ICON_FRONT: + case CMDTYPE_ICON_UNIT_OR_AREA: + case CMDTYPE_ICON_UNIT_OR_RECTANGLE: + case CMDTYPE_ICON_UNIT_FEATURE_OR_AREA: { + SetActiveCommandIndex(cmdIndex); + activeMousePress = false; + break; + } + case CMDTYPE_ICON_BUILDING: { + SetActiveCommandIndex(cmdIndex); + activeMousePress = false; + break; + } + case CMDTYPE_NEXT: { + ++activePage; + if (activePage > maxPage) { + activePage = 0; + } + selectedUnitsHandler.SetCommandPage(activePage); + break; + } + case CMDTYPE_PREV: { + --activePage; + if (activePage < 0) { + activePage=maxPage; + } + selectedUnitsHandler.SetCommandPage(activePage); + break; + } + case CMDTYPE_CUSTOM: { + RunCustomCommands(cd.params, rightMouseButton); + break; + } + default: + break; + } + + return true; +} +private: + ControlInput keys; + bool invertQueueKey, needShift = false, activeMousePress = false, forceLayoutUpdate = false; + int defaultCmdMemory = -1, activePage = 0, maxPage = 0; + struct { void Reset() {} } lastKeySet; + struct Mouse { struct Button { bool pressed = false; }; Button buttons[4]; } mouseState; + Mouse* mouse = &mouseState; + struct Page { int value = 0; void SetCommandPage(int page) { value = page; } } selectedUnitsHandler; + void SetActiveCommandIndex(int index) { activeIndex = index; } + void RunCustomCommands(const std::vector&, bool) { unsupportedCustom = true; } + void GiveCommand(const Command& command, bool fromUser = true, bool fromPlayerInput = false) { commandsToGive.emplace_back(command, fromUser, fromPlayerInput); } + bool GetQueueKeystate() const + { + RECOIL_DETAILED_TRACY_ZONE; + return (!invertQueueKey && keys.GetKeyModState(KMOD_SHIFT)) || + (invertQueueKey && !keys.GetKeyModState(KMOD_SHIFT)); +} + unsigned char CreateOptions(bool rightMouseButton) + { + RECOIL_DETAILED_TRACY_ZONE; + unsigned char options = 0; + + if (rightMouseButton) { + options |= RIGHT_MOUSE_KEY; + } + if (GetQueueKeystate()) { + // allow mouse button 'rocker' movements to force + // immediate mode (when queuing is the default mode) + if (!invertQueueKey || + (!mouse->buttons[SDL_BUTTON_LEFT].pressed && + !mouse->buttons[SDL_BUTTON_RIGHT].pressed)) { + options |= SHIFT_KEY; + } + } + if (keys.GetKeyModState(KMOD_CTRL)) { options |= CONTROL_KEY; } + if (keys.GetKeyModState(KMOD_ALT) ) { options |= ALT_KEY; } + if (keys.GetKeyModState(KMOD_GUI)) { options |= META_KEY; } + + return options; +} +}; +} --- /dev/null +++ b/rts/Game/WebbarNativeOrderLayout.h @@ -0,0 +1,315 @@ +/* This file is part of the Spring engine (GPL v2 or later), see LICENSE.html */ +#pragma once + +#include "Lua/LuaUI.h" +#include "Lua/LuaConfig.h" +#include "LuaInclude.h" +#include "System/StringUtil.h" +#include "Sim/Units/CommandAI/CommandDescription.h" + +namespace WebbarNativeOrderLayout { +using std::vector; +using std::string; +using ReStringPair = CLuaUI::ReStringPair; +using ReParamsPair = CLuaUI::ReParamsPair; +static bool GetLuaIntMap(lua_State* L, int index, spring::unordered_map& intMap) +{ + const int table = index; + if (!lua_istable(L, table)) + return false; + + for (lua_pushnil(L); lua_next(L, table) != 0; lua_pop(L, 1)) { + if (!lua_isnumber(L, -1) || !lua_israwnumber(L, -2)) { + lua_pop(L, 2); + return false; + } + const int key = lua_toint(L, -2); + const int value = lua_toint(L, -1) - CMD_INDEX_OFFSET; + intMap[key] = value; + } + + return true; +} + + +static bool GetLuaIntList(lua_State* L, int index, vector& intList) +{ + const int table = index; + if (!lua_istable(L, table)) { + return false; + } + for (lua_pushnil(L); lua_next(L, table) != 0; lua_pop(L, 1)) { + if (!lua_isnumber(L, -1)) { // the value (key is at -2) + lua_pop(L, 2); + return false; + } + const int value = lua_toint(L, -1) - CMD_INDEX_OFFSET; + intList.push_back(value); + } + + return true; +} + + +static bool GetLuaReStringList(lua_State* L, int index, + vector& reStringList) +{ + const int table = index; + if (!lua_istable(L, table)) { + return false; + } + + for (lua_pushnil(L); lua_next(L, table) != 0; lua_pop(L, 1)) { + if (!lua_israwnumber(L, -2) || !lua_isstring(L, -1)) { + lua_pop(L, 2); + return false; + } + ReStringPair rp; + rp.cmdIndex = lua_toint(L, -2) - CMD_INDEX_OFFSET; + rp.texture = lua_tostring(L, -1); + reStringList.push_back(rp); + } + + return true; +} + + +static bool GetLuaReParamsList(lua_State* L, int index, + vector& reParamsCmds) +{ + const int table = index; + if (!lua_istable(L, table)) { + return false; + } + + for (lua_pushnil(L); lua_next(L, table) != 0; lua_pop(L, 1)) { + if (!lua_israwnumber(L, -2) || !lua_istable(L, -1)) { + lua_pop(L, 2); + return false; + } + ReParamsPair paramsPair; + paramsPair.cmdIndex = lua_toint(L, -2) - CMD_INDEX_OFFSET; + const int paramTable = lua_gettop(L); + for (lua_pushnil(L); lua_next(L, paramTable) != 0; lua_pop(L, 1)) { + if (!lua_israwnumber(L, -2) || !lua_isstring(L, -1)) { + lua_pop(L, 4); + return false; + } + const int paramIndex = lua_toint(L, -2); + const string paramValue = string(lua_tostring(L, -1), lua_strlen(L, -1)); + paramsPair.params[paramIndex] = paramValue; + } + reParamsCmds.push_back(paramsPair); + } + + return true; +} + + +static bool GetLuaCmdDescList(lua_State* L, int index, vector& cmdDescs) +{ + const int table = index; + if (!lua_istable(L, table)) + return false; + + int paramIndex = 1; + for (lua_rawgeti(L, table, paramIndex); + lua_istable(L, -1); + lua_pop(L, 1), paramIndex++, lua_rawgeti(L, table, paramIndex)) { + SCommandDescription cd; + cd.id = CMD_INTERNAL; + cd.type = CMDTYPE_CUSTOM; + const int cmdDescTable = lua_gettop(L); + for (lua_pushnil(L); lua_next(L, cmdDescTable) != 0; lua_pop(L, 1)) { + if (lua_israwstring(L, -2) && lua_isstring(L, -1)) { + const string key = StringToLower(string(lua_tostring(L, -2), lua_strlen(L, -2))); + const string value(lua_tostring(L, -1), lua_strlen(L, -1)); + if (key == "id") { + cd.id = atoi(value.c_str()); + } else if (key == "type") { + cd.type = atoi(value.c_str()); + } else if (key == "name") { + cd.name = value; + } else if (key == "action") { + cd.action = value; + } else if (key == "texture") { + cd.iconname = value; + } else if (key == "cursor") { + cd.mouseicon = value; + } else if (key == "tooltip") { + cd.tooltip = value; + } else if (key == "nwtext") { + cd.params.push_back(string("$nw$") + value); + } else if (key == "swtext") { + cd.params.push_back(string("$sw$") + value); + } else if (key == "netext") { + cd.params.push_back(string("$ne$") + value); + } else if (key == "setext") { + cd.params.push_back(string("$se$") + value); + } else { + LOG_L(L_WARNING, "GetLuaCmdDescList() unknown key (%s)", key.c_str()); + } + } + else if (lua_israwstring(L, -2) && lua_istable(L, -1)) { + const string key = StringToLower(lua_tostring(L, -2)); + if (key != "actions") { + LOG_L(L_WARNING, "GetLuaCmdDescList() non \"actions\" table: %s", + key.c_str()); + continue; + } + const int actionsTable = lua_gettop(L); + for (lua_pushnil(L); lua_next(L, actionsTable) != 0; lua_pop(L, 1)) { + if (lua_isstring(L, -1)) { + string action = lua_tostring(L, -1); + if (action[0] != '@') { + action = "@@" + action; + } + cd.params.push_back(action); + } + } + } + else { + LOG_L(L_WARNING, "GetLuaCmdDescList() bad entry"); + } + } + cmdDescs.push_back(cd); + } + + if (!lua_isnil(L, -1)) { + LOG_L(L_WARNING, "GetLuaCmdDescList() entry %i is not a table", paramIndex); + lua_pop(L, 1); + return false; + } + lua_pop(L, 1); + + return true; +} + +static bool Apply(lua_State* L, int base, vector& cmds) +{ + if (lua_gettop(L) - base != 11 || !lua_isstring(L, base + 1) + || !lua_isnumber(L, base + 2) || !lua_isnumber(L, base + 3) + || lua_toint(L, base + 2) < 2 || lua_toint(L, base + 3) < 2) return false; + vector removeCmds, onlyTextureCmds; + vector customCmds; + vector reTextureCmds, reNamedCmds, reTooltipCmds; + vector reParamsCmds; + spring::unordered_map iconMap; + if (!GetLuaIntList(L, base + 4, removeCmds) + || !GetLuaCmdDescList(L, base + 5, customCmds) + || !GetLuaIntList(L, base + 6, onlyTextureCmds) + || !GetLuaReStringList(L, base + 7, reTextureCmds) + || !GetLuaReStringList(L, base + 8, reNamedCmds) + || !GetLuaReStringList(L, base + 9, reTooltipCmds) + || !GetLuaReParamsList(L, base + 10, reParamsCmds) + || !GetLuaIntMap(L, base + 11, iconMap)) return false; + spring::unordered_set removeIDs; + std::vector tmpCmds; + std::vector iconList; + + removeIDs.reserve(removeCmds.size()); + tmpCmds.reserve(cmds.size()); + iconList.reserve(iconMap.size()); + + + // build a set to better find unwanted commands + for (unsigned int i = 0; i < removeCmds.size(); i++) { + const size_t index = removeCmds[i]; + + if (index < cmds.size()) { + removeIDs.insert(index); + } else { + LOG_L(L_ERROR, "[GUIHandler::%s] skipping bad removeCmd (%i)", __func__, int(index)); + } + } + + // remove unwanted commands (and mark all as hidden) + for (unsigned int i = 0; i < cmds.size(); i++) { + if (removeIDs.find(i) == removeIDs.end()) { + cmds[i].hidden = true; + tmpCmds.push_back(cmds[i]); + } + } + + cmds = tmpCmds; + + // add the custom commands + for (unsigned int i = 0; i < customCmds.size(); i++) { + customCmds[i].hidden = true; + cmds.push_back(customCmds[i]); + } + const size_t cmdCount = cmds.size(); + + // set commands to onlyTexture + for (unsigned int i = 0; i < onlyTextureCmds.size(); i++) { + const size_t index = onlyTextureCmds[i]; + + if (index < cmdCount) { + cmds[index].onlyTexture = true; + } else { + LOG_L(L_ERROR, "[GUIHandler::%s] skipping bad onlyTexture (%i)", __func__, int(index)); + } + } + + // retexture commands + for (unsigned int i = 0; i < reTextureCmds.size(); i++) { + const size_t index = reTextureCmds[i].cmdIndex; + + if (index < cmdCount) { + cmds[index].iconname = reTextureCmds[i].texture; + } else { + LOG_L(L_ERROR, "[GUIHandler::%s] skipping bad reTexture (%i)", __func__, int(index)); + } + } + + // reNamed commands + for (unsigned int i = 0; i < reNamedCmds.size(); i++) { + const size_t index = reNamedCmds[i].cmdIndex; + + if (index < cmdCount) { + cmds[index].name = reNamedCmds[i].texture; + } else { + LOG_L(L_ERROR, "[GUIHandler::%s] skipping bad reNamed (%i)", __func__, int(index)); + } + } + + // reTooltip commands + for (unsigned int i = 0; i < reTooltipCmds.size(); i++) { + const size_t index = reTooltipCmds[i].cmdIndex; + + if (index < cmdCount) { + cmds[index].tooltip = reTooltipCmds[i].texture; + } else { + LOG_L(L_ERROR, "[GUIHandler::%s] skipping bad reNamed (%i)", __func__, int(index)); + } + } + + // reParams commands + for (unsigned int i = 0; i < reParamsCmds.size(); i++) { + const size_t index = reParamsCmds[i].cmdIndex; + + if (index < cmdCount) { + const auto& params = reParamsCmds[i].params; + + for (auto pit = params.cbegin(); pit != params.cend(); ++pit) { + const size_t p = pit->first; + + if (p < cmds[index].params.size()) { + cmds[index].params[p] = pit->second; + } + } + } else { + LOG_L(L_ERROR, "[GUIHandler::%s] skipping bad reParams (%i)", __func__, int(index)); + } + } + + // The pinned BAR dummy layout returns either no icons or its deliberately + // invalid [1337]=9001 sentinel. With the 8192 descriptor bound, no command + // becomes visible in the native engine icon panel. Order owns its drawing. + if (cmds.size() > 8192) return false; + for (const auto& entry: iconMap) { + if (entry.first != 1337 || entry.second != 9000) return false; + } + return true; +} +} --- /dev/null +++ b/rts/Game/WebbarNativeOrderPolicyHost.inc @@ -0,0 +1,144 @@ +// Included inside WebbarNativeInfo. Plans use original native geometry and +// controllers. Review returns their logical CommandNotify input, not raw +// authority to construct or replace network packets from the page. +struct PreparedOrder { + std::vector commands; + WebbarNativeOrder::ActionPlan actions; + std::string result; + std::optional ground; + size_t Bytes() const { + auto commandBytes = [](const std::vector& commands) { + size_t bytes = commands.capacity() * sizeof(Command); + for (const auto& command: commands) bytes += command.GetNumParams() * sizeof(float) * 2; + return bytes; + }; + size_t bytes = sizeof(*this) + result.capacity() + commandBytes(commands); + bytes += actions.groups.capacity() * sizeof(std::vector) + actions.effects.capacity() * sizeof(WebbarNativeOrder::ActionEffect); + bytes += actions.admitted.size() * 64 + (actions.selected.capacity() + actions.affected.capacity()) * sizeof(int); + for (const auto& group: actions.groups) bytes += group.capacity() * sizeof(int); + for (const auto& effect: actions.effects) bytes += commandBytes(effect.commands); + return bytes; + } + bool RedirectToGround() { + // Only the existing no-allied-fire policy needs a command rewrite. Keep the + // cached native ID/options and selection; accept no arbitrary replacement + // command or action array from the page. Normal dispatch still validates it. + if (actions.prepared || commands.size() != 1) return false; + const auto& original = commands.front(); + if ((original.GetID() != CMD_ATTACK && original.GetID() != CMD_MANUALFIRE) || original.GetNumParams() != 1) return false; + const float id = original.GetParam(0); + if (!std::isfinite(id) || id < 0 || id > 32767 || id != std::floor(id)) return false; + const auto* target = unitHandler.GetUnit(int(id)); + if (!target || target->isDead || !teamHandler.AlliedTeams(gu->myTeam, target->team)) return false; + if (!ground || !ground->IsInBounds()) return false; + Command replacement(original.GetID(), original.GetOpts(), *ground); + if (!WebbarNativeOrder::DirectCommand(replacement)) return false; + commands.front() = std::move(replacement); return true; + } + bool Dispatch(const std::vector& ids, bool fromPlayerNetwork, std::vector& admitted) const { + if (actions.prepared) { + if (!actions.Dispatch(fromPlayerNetwork)) return false; + admitted = actions.affected; return true; + } + if (commands.empty()) return true; + admitted.assign(ids.begin(), ids.end()); + if (WebbarNativeOrder::SendSelectionCommands(admitted, commands, fromPlayerNetwork)) return true; + admitted.clear(); return false; + } +}; +static void AppendPolicyCommand(std::string& out, const Command& command) +{ + out += "{\"id\":" + std::to_string(command.GetID()) + ",\"options\":" + std::to_string(command.GetOpts()) + ",\"params\":["; + for (unsigned p = 0; p < command.GetNumParams(); ++p) { if (p) out += ','; WebbarJsonNumber(out, command.GetParam(p)); } + out += "]}"; +} +static std::string OrderExecutionResult(const PreparedOrder& prepared, const std::string& activation) +{ + if (prepared.actions.prepared) return prepared.actions.Result(); + std::string result = "{\"activation\":" + (activation.empty() ? std::string("null") : activation) + ",\"commands\":["; + for (size_t n = 0; n < prepared.commands.size(); ++n) { if (n) result += ','; AppendPolicyCommand(result, prepared.commands[n]); } + return result + "]}"; +} + +// Complete input lives in its own bounded one-shot payload. Bridge9 remains +// unchanged. K/retained engines retain their one-phase path; the new phases +// require an explicit optional capability and original native validation. +static uint32_t ExecuteOrder(uint32_t request, uint32_t count, uint32_t commandID, uint32_t options, float x, float z, float radius, const uint32_t* legacyWords, bool fromPlayerNetwork, std::vector& admitted) +{ + static WebbarNativeOrder::ProposalStore proposals; + if (std::getenv("WEBBAR_NATIVE_ORDER_CONTROLS") == nullptr || gu->spectating || webbarReplay::Enabled() || std::getenv("WEBBAR_NETWORK") != nullptr) { proposals.Clear(); return 5; } + if (gs->frameNum < 0) { proposals.Clear(); return 5; } + proposals.Expire(uint32_t(gs->frameNum), uint32_t(gu->myTeam)); + if (!request || count == 0 || count > 8192 || commandID > 0x7fffffffu || options || x != 0 || z != 0 || radius != 0) return 1; + for (int n = 0; n < 64; ++n) if (legacyWords[n]) return 1; + struct InputHeader { uint32_t magic, version, request, kind, count, commandID, commandType, flags, paramCount; float params[3]; }; + static_assert(sizeof(InputHeader) == 48); + static std::array words{}; + const int size = MAIN_THREAD_EM_ASM_INT({ return Module['webbarNativeOrderInput'] ? Module['webbarNativeOrderInput']($0 >>> 0, $1, $2) : 0; }, request, words.data(), sizeof(words)); + if (size < int(sizeof(InputHeader)) || size > int(sizeof(words))) return 1; + InputHeader h; std::memcpy(&h, words.data(), sizeof(h)); + if (h.magic != 0x574f4331u || h.version != 1 || h.request != request || h.count != count || h.commandID != commandID || h.commandType > 23 || h.paramCount > 3) return 1; + const bool prepare = ((h.kind >= 17 && h.kind <= 19) || h.kind == 23), commit = h.kind == 4, cancel = h.kind == 5, redirect = h.kind == 6; + if ((prepare || commit || cancel || redirect) && std::getenv("WEBBAR_NATIVE_ORDER_POLICY") == nullptr) return 5; + if (prepare) h.kind -= 16; + if (h.kind < 1 || h.kind > 7) return 1; + if ((h.kind == 3 || redirect) && std::getenv("WEBBAR_NATIVE_ORDER_WORLD") == nullptr) return 5; + if (h.kind == 7 && (std::getenv("WEBBAR_NATIVE_MINIMAP_CONTROLS") == nullptr || std::getenv("WEBBAR_NATIVE_ORDER_WORLD") == nullptr)) return 5; + const uint32_t row = h.kind == 7 ? 60 : h.kind == 3 ? 44 : 12; + if (size != int(row * 4 + count * 8)) return 1; + if (commit || cancel || redirect) { + if (h.flags || h.paramCount || !words[9] || words[10] || words[11]) return 1; + } else { + if ((h.kind == 3 || h.kind == 7) && (h.paramCount != 2 || !std::isfinite(h.params[0]) || h.params[0] != std::floor(h.params[0]) || h.params[0] < 0 || h.params[0] > 0xffffff || !std::isfinite(h.params[1]) || h.params[1] != std::floor(h.params[1]) || h.params[1] < 0 || h.params[1] > 3)) return 3; + for (uint32_t n = h.paramCount; n < 3; ++n) if (h.params[n] != 0) return 3; + } + WebbarNativeOrder::ProposalScope scope{uint32_t(gs->frameNum), uint32_t(gu->myTeam), commandID, h.commandType, {}}; + std::vector ids; ids.reserve(count); std::unordered_set seen; + for (uint32_t n = 0; n < count; ++n) { + const auto id = words[row + n * 2], token = words[row + 1 + n * 2]; + if (id > 32767 || !token || token == 0xffffffffu || !seen.insert(id).second) return 1; + const auto* unit = unitHandler.GetUnit(id); + if (!WebbarSelectable(unit) || WebbarHudLifetime(unit) != token) return 4; + ids.push_back(id); scope.units.emplace_back(id, token); + } + auto publish = [&](const std::string& result) { + MAIN_THREAD_EM_ASM({ if (Module['webbarNativeOrderResult']) Module['webbarNativeOrderResult']($0 >>> 0, UTF8ToString($1)); }, request, result.c_str()); + }; + proposals.Expire(scope.frame, scope.team); + if (commit || cancel || redirect) { + auto prepared = proposals.Take(words[9], scope); if (!prepared) return 4; + if (cancel) { publish("{\"cancelled\":" + std::to_string(words[9]) + "}"); return 0; } + if (redirect) { + if (!prepared->RedirectToGround()) return 6; + prepared->result = OrderExecutionResult(*prepared, {}); + } + if (!prepared->Dispatch(ids, fromPlayerNetwork, admitted)) return 6; + publish(prepared->result); return 0; + } + if (!reader) reader = new WebbarNativeInfoReader; + PreparedOrder prepared; std::string activation; Command input; + if (h.kind == 7) { + WebbarNativeOrder::MinimapView release, press; WebbarInfoWorldView view; + std::memcpy(&release, words.data() + 12, sizeof(release)); std::memcpy(&press, words.data() + 28, sizeof(press)); std::memcpy(&view, words.data() + 44, sizeof(view)); + if (!reader->PlanOrderWorld(ids, h.commandID, h.commandType, h.flags, int(h.params[0]), int(h.params[1]), view, view, prepared.commands, prepared.actions, &input, prepare ? &prepared.ground : nullptr, &release, &press)) return 6; + } else if (h.kind == 3) { + WebbarInfoWorldView release, press; std::memcpy(&release, words.data() + 12, sizeof(release)); std::memcpy(&press, words.data() + 28, sizeof(press)); + if (!reader->PlanOrderWorld(ids, h.commandID, h.commandType, h.flags, int(h.params[0]), int(h.params[1]), release, press, prepared.commands, prepared.actions, &input, prepare ? &prepared.ground : nullptr)) return 6; + } else { + if (!reader->PlanOrderControl(ids, h.kind, h.commandID, h.commandType, h.flags, h.paramCount, h.params, prepared.commands, activation)) return 6; + if (!prepared.commands.empty()) input = prepared.commands.front(); + } + prepared.result = OrderExecutionResult(prepared, activation); + if (prepare) { + std::string result = "{\"proposal\":{\"token\":" + std::to_string(request) + ",\"frame\":" + std::to_string(scope.frame) + ",\"input\":"; + if (prepared.commands.empty() && !prepared.actions.prepared) result += "null"; else AppendPolicyCommand(result, input); + result += ",\"inserted\":" + std::string(prepared.actions.prepared && prepared.actions.id != 30100 && prepared.actions.id != 455624 ? "true" : "false") + ",\"ground\":"; + if (prepared.ground) { result += '['; for (int n = 0; n < 3; ++n) { if (n) result += ','; WebbarJsonNumber(result, (*prepared.ground)[n]); } result += ']'; } else result += "null"; + result += ",\"result\":" + prepared.result + "}}"; + const size_t bytes = prepared.Bytes() + result.capacity() + scope.units.capacity() * sizeof(scope.units[0]); + if (!proposals.Put(request, std::move(scope), std::move(prepared), bytes)) return 6; + publish(result); return 0; + } + if (!prepared.Dispatch(ids, fromPlayerNetwork, admitted)) return 6; + publish(prepared.result); return 0; +} --- /dev/null +++ b/rts/Game/WebbarNativeOrderRead.h @@ -0,0 +1,126 @@ +/* This file is part of the Spring engine (GPL v2 or later), see LICENSE.html */ +#pragma once + +#include "Game/SelectedUnitsHandler.h" +#include "Sim/Units/CommandAI/CommandDescription.h" +#include "Sim/Units/CommandAI/CommandAI.h" +#include "System/UnorderedMap.hpp" + +// Original GetAvailableCommands body; omit only its global UI invalidation +// write. No CObject/GUI instance is constructed and no unit is selected. +namespace WebbarNativeOrder { +using AvailableCommandsStruct = CSelectedUnitsHandler::AvailableCommandsStruct; +static AvailableCommandsStruct Merge(const spring::unordered_set& selectedUnits, bool buildIconsFirst) +{ + RECOIL_DETAILED_TRACY_ZONE; + + + int commandPage = 1000; + + spring::unordered_map states; + std::vector commands; + + for (const int unitID: selectedUnits) { + const CUnit* u = unitHandler.GetUnit(unitID); + const CCommandAI* cai = u->commandAI; + + for (const SCommandDescription* cmdDesc: cai->GetPossibleCommands()) { + // Disable unit commands if we have a group selected. + if (cmdDesc->showUnique && selectedUnits.size() > 1) + states[cmdDesc->id] = 0; + else + states[cmdDesc->id] = cmdDesc->disabled ? 2 : 1; + } + + if (cai->lastSelectedCommandPage < commandPage) + commandPage = cai->lastSelectedCommandPage; + } + + // load the first set (separating build and non-build commands) + for (const int unitID: selectedUnits) { + const CUnit* u = unitHandler.GetUnit(unitID); + const CCommandAI* cai = u->commandAI; + + for (const SCommandDescription* cmdDesc: cai->GetPossibleCommands()) { + // If the id < 0, it is a build command. + if (buildIconsFirst != (cmdDesc->id < 0)) + continue; + + // Prevent duplicates across different units. + if (states[cmdDesc->id] > 0) { + commands.push_back(*cmdDesc); + states[cmdDesc->id] = 0; + } + } + } + + // load the second set (all those that have not already been included) + for (const int unitID: selectedUnits) { + const CUnit* u = unitHandler.GetUnit(unitID); + const CCommandAI* cai = u->commandAI; + + for (const SCommandDescription* cmdDesc: cai->GetPossibleCommands()) { + if (buildIconsFirst != (cmdDesc->id >= 0)) + continue; + + if (states[cmdDesc->id] > 0) { + commands.push_back(*cmdDesc); + states[cmdDesc->id] = 0; + } + } + } + + AvailableCommandsStruct ac; + ac.commandPage = commandPage; + ac.commands = commands; + return ac; +} +static void Convert(std::vector& cmds, bool newAttackMode, bool attackRect) +{ + RECOIL_DETAILED_TRACY_ZONE; + if (!newAttackMode) + return; + + const int count = (int)cmds.size(); + for (int i = 0; i < count; i++) { + SCommandDescription& cd = cmds[i]; + + if ((cd.id != CMD_ATTACK) || (cd.type != CMDTYPE_ICON_UNIT_OR_MAP)) + continue; + + if (attackRect) { + cd.type = CMDTYPE_ICON_UNIT_OR_RECTANGLE; + } else { + cd.type = CMDTYPE_ICON_UNIT_OR_AREA; + } + } +} +static void AppendPages(std::vector& cmds) +{ + RECOIL_DETAILED_TRACY_ZONE; + { + cmds.emplace_back(); + + SCommandDescription& cd = cmds.back(); + + cd.id = CMD_INTERNAL; + cd.type = CMDTYPE_PREV; + + cd.name = ""; + cd.action = "prevmenu"; + cd.tooltip = "Previous menu"; + } + { + cmds.emplace_back(); + + SCommandDescription& cd = cmds.back(); + + cd.id = CMD_INTERNAL; + cd.type = CMDTYPE_NEXT; + + cd.name = ""; + cd.action = "nextmenu"; + cd.tooltip = "Next menu"; + } +} +} --- /dev/null +++ b/rts/Game/WebbarNativeOrderTransport.h @@ -0,0 +1,153 @@ +/* This file is part of the Spring engine (GPL v2 or later), see LICENSE.html */ +#pragma once +#include +#include +#include +#include +#include +#include "Game/SelectedUnitsHandler.h" +#include "Game/GlobalUnsynced.h" +#include "Game/Players/Player.h" +#include "Game/Players/PlayerHandler.h" +#include "Net/Protocol/NetProtocol.h" +#include "Sim/Misc/GlobalSynced.h" +#include "Sim/Misc/Team.h" +#include "Sim/Misc/TeamHandler.h" +#include "Sim/Units/Unit.h" +#include "Sim/Units/UnitHandler.h" + +namespace WebbarNativeOrder { +inline bool ArrayPacketFits(const std::vector& unitIDs, const std::vector& commands) { + if (unitIDs.empty() || commands.empty()) return true; + if (unitIDs.size() > 8192 || commands.size() > 65535) return false; + uint64_t paramBytes = 0; + for (const auto& c: commands) { + paramBytes += uint64_t(c.GetNumParams()) * sizeof(float); + if (paramBytes > 8192) return false; + } + // Exact original coalesced packet-size calculation, after bounding its u32 + // accumulation. Reject a whole controller plan before any packet is emitted. + const unsigned unitIDCount = unitIDs.size(); + const unsigned commandCount = commands.size(); + + if ((unitIDCount == 0) || (commandCount == 0)) + return true; + + uint32_t totalParams = 0; + + // if all commands share the same ID / options / number of parameters, + // insert only these values into the packet to save a bit of bandwidth + int32_t refCmdID = commands[0].GetID(); + uint8_t refCmdOpts = commands[0].GetOpts(); + int32_t refCmdSize = commands[0].GetNumParams(); + + for (unsigned int c = 0; c < commandCount; c++) { + totalParams += commands[c].GetNumParams(); + + if (refCmdID != 0 && refCmdID != commands[c].GetID()) + refCmdID = 0; + if (refCmdOpts != 0xFF && refCmdOpts != commands[c].GetOpts()) + refCmdOpts = 0xFF; + if (refCmdSize != 0xFFFF && refCmdSize != commands[c].GetNumParams()) + refCmdSize = 0xFFFF; + } + + unsigned int optBytesPerCmd = 0; + unsigned int totalPacketLen = 0; + + // optional data per command (cmdID, cmdOpts, #cmdParams) + optBytesPerCmd += (sizeof(uint32_t) * (refCmdID == 0 )); + optBytesPerCmd += (sizeof(uint8_t ) * (refCmdOpts == 0xFF )); + optBytesPerCmd += (sizeof(uint16_t) * (refCmdSize == 0xFFFF)); + + // msg type, msg size + totalPacketLen += (sizeof(uint8_t) + sizeof(static_cast(totalPacketLen))); + // player ID, AI ID, pairwise + totalPacketLen += (sizeof(uint8_t) * 3); + totalPacketLen += ( + sizeof(static_cast(refCmdID )) + + sizeof(static_cast(refCmdOpts)) + + sizeof(static_cast(refCmdSize)) + ); + + totalPacketLen += sizeof(static_cast(unitIDCount)); + totalPacketLen += (unitIDCount * sizeof(uint16_t)); + + totalPacketLen += sizeof(static_cast(commandCount)); + totalPacketLen += (commandCount * optBytesPerCmd); + totalPacketLen += (totalParams * sizeof(float)); // params are floats + + + return totalPacketLen <= 8192; +} +// The caller has already checked current ownership, lifetimes and descriptors. +// Native NETMSG_SELECT reads signed int16 IDs. Never narrow an unsigned ID or +// split/truncate a roster to fit the unrelated 8192-byte Lua-array packet. +inline bool SelectionPacket(const std::vector& ids, std::vector& packet, bool allowEmpty = false) { + // The private browser roster is capped at8192. A restoration may contain the + // larger native GUI roster, bounded by NETMSG_SELECT's original u16 length. + const size_t limit = allowEmpty ? (65535u - 4u) / sizeof(int16_t) : 8192u; + if ((!allowEmpty && ids.empty()) || ids.size() > limit) return false; + std::unordered_set seen; + for (int id: ids) if (id < 0 || id > std::numeric_limits::max() || !seen.insert(id).second) return false; + packet.assign(ids.begin(), ids.end()); + return true; +} +inline bool DirectCommand(const Command& c) { + // These GUI commands use group/wait helpers rather than SendCommand in the + // original handler. The pinned Order widget hides them; do not raw-send them. + switch (c.GetID()) { + case CMD_GROUPCLEAR: case CMD_GROUPSELECT: case CMD_GROUPADD: + case CMD_TIMEWAIT: case CMD_DEATHWAIT: case CMD_SQUADWAIT: case CMD_GATHERWAIT: + return false; + } + if (c.GetNumParams() > (65535u - 17u) / 4u) return false; + for (unsigned n = 0; n < c.GetNumParams(); ++n) if (!std::isfinite(c.GetParam(n))) return false; + return true; +} +inline bool SendSelectionCommands(const std::vector& ids, const std::vector& commands, bool fromPlayerInput) { + std::vector selectedUnitIDs, restore; + if (commands.empty() || !SelectionPacket(ids, selectedUnitIDs)) return false; + for (const auto& c: commands) if (!DirectCommand(c)) return false; + // Restore the native GUI's network selection after these ordered packets. + // Its private cache and selected set stay untouched, so a later SendSelect + // may safely reuse its original selectionChanged state. + const std::vector guiSelection(selectedUnitsHandler.selectedUnits.begin(), selectedUnitsHandler.selectedUnits.end()); + if (!SelectionPacket(guiSelection, restore, true)) return false; + clientNet->Send(CBaseNetProtocol::Get().SendSelect(gu->myPlayerNum, selectedUnitIDs)); + for (const auto& c: commands) { + clientNet->Send(CBaseNetProtocol::Get().SendCommand(gu->myPlayerNum, c.GetID(), c.GetTimeOut(), c.GetOpts(), c.GetNumParams(), c.GetParams(), fromPlayerInput)); + } + clientNet->Send(CBaseNetProtocol::Get().SendSelect(gu->myPlayerNum, restore)); + // Original GiveCommand accounts for the private selection, never an unrelated + // global GUI group. Lua GiveOrder also uses this default from-user accounting. + auto& stats = playerHandler.Player(gu->myPlayerNum)->currentStats; + stats.numCommands += commands.size(); + stats.unitCommands += ids.size() * commands.size(); + return true; +} +inline bool CanShareSelection(const std::vector& ids, int teamID) { + if (gu->spectating || gs->noHelperAIs || gs->PreSimFrame() || !teamHandler.IsValidTeam(teamID) || teamID == gu->myTeam) return false; + const CTeam* team = teamHandler.Team(teamID); + if (team == nullptr || team->isDead || !teamHandler.AlliedTeams(gu->myTeam, teamID)) return false; + std::vector packet; + if (!SelectionPacket(ids, packet)) return false; + for (int id: ids) { + const CUnit* unit = unitHandler.GetUnit(id); + if (unit == nullptr || unit->isDead || unit->team != gu->myTeam) return false; + } + return true; +} +inline bool ShareSelection(const std::vector& ids, int teamID) { + if (!CanShareSelection(ids, teamID)) return false; + std::vector selectedUnitIDs, restore; + const std::vector guiSelection(selectedUnitsHandler.selectedUnits.begin(), selectedUnitsHandler.selectedUnits.end()); + if (!SelectionPacket(ids, selectedUnitIDs) || !SelectionPacket(guiSelection, restore, true)) return false; + clientNet->Send(CBaseNetProtocol::Get().SendSelect(gu->myPlayerNum, selectedUnitIDs)); + clientNet->Send(CBaseNetProtocol::Get().SendShare(gu->myPlayerNum, teamID, 1, 0.0f, 0.0f)); + clientNet->Send(CBaseNetProtocol::Get().SendSelect(gu->myPlayerNum, restore)); + // The original controller's selection-clear intention belongs to the browser + // view that supplied these IDs. Never ClearSelected on the global native GUI. + return true; +} +} --- /dev/null +++ b/rts/Game/WebbarNativeOrderWorld.h @@ -0,0 +1,458 @@ +/* This file is part of the Spring engine (GPL v2 or later), see LICENSE.html */ +#pragma once +#include +#include +#include +#include +#include "WebbarNativeOrderControl.h" +#include "Game/Camera.h" +#include "Game/GameHelper.h" +#include "Game/TraceRay.h" +#include "Map/Ground.h" +#include "Sim/Features/Feature.h" +#include "Sim/Units/Unit.h" +#include "Sim/Units/UnitHandler.h" +#include "Sim/Units/UnitDefHandler.h" +#include "Sim/Units/BuildInfo.h" +#include "Sim/Units/CommandAI/CommandAI.h" + +namespace WebbarNativeOrder { +struct WorldInput { + ControlInput keys; + const CCamera* viewCamera; + float3 startPosition, startDirection; + int width, mouseX, mouseY, movement, facing; + int circleThreshold, boxThreshold, frontThreshold; + bool frontByEnds; +}; +class WorldPlan { +public: + WorldPlan(std::vector descriptors, const std::vector& ids, WorldInput input): commands(std::move(descriptors)), keys(input.keys), viewCamera(input.viewCamera), invertQueueKey(input.keys.invertQueue), frontByEnds(input.frontByEnds), buildFacing(input.facing) { + selectedUnitsHandler.selectedUnits = ids; view.viewSizeX = input.width; + mouseState.lastx = input.mouseX; + mouseState.dragCircleCommandThreshold = input.circleThreshold; + mouseState.dragBoxCommandThreshold = input.boxThreshold; + mouseState.dragFrontCommandThreshold = input.frontThreshold; + for (int button = SDL_BUTTON_LEFT; button <= SDL_BUTTON_RIGHT; ++button) { + mouseState.buttons[button].camPos = input.startPosition; + mouseState.buttons[button].dir = input.startDirection; + mouseState.buttons[button].movement = input.movement; + } + mouseState.buttons[SDL_BUTTON_LEFT].pressed = input.keys.left; + mouseState.buttons[SDL_BUTTON_RIGHT].pressed = input.keys.right; + } + static bool TargetType(int type) { + switch (type) { + case CMDTYPE_ICON_MAP: case CMDTYPE_ICON_AREA: case CMDTYPE_ICON_UNIT: + case CMDTYPE_ICON_UNIT_OR_MAP: case CMDTYPE_ICON_FRONT: case CMDTYPE_ICON_UNIT_OR_AREA: + case CMDTYPE_ICON_UNIT_FEATURE_OR_AREA: case CMDTYPE_ICON_UNIT_OR_RECTANGLE: case CMDTYPE_NUMBER: return true; + } + return false; + } + Command Plan(int index, int mouseX, int mouseY, const float3& position, const float3& direction) { + if (index < 0 || size_t(index) >= commands.size() || commands[index].disabled || !TargetType(commands[index].type)) return Command(CMD_FAILED); + inCommand = explicitCommand = index; + // Explicit Order targeting is released with the left button. Default/right + // world orders and construction keep their separate accepted input paths. + return GetCommand(mouseX, mouseY, SDL_BUTTON_LEFT, false, position, direction, true); + } + bool unsupportedWorld = false; +private: + std::vector commands; + ControlInput keys; + const CCamera* viewCamera; + bool invertQueueKey, frontByEnds; + int inCommand = -1, explicitCommand = -1, defaultCmdMemory = -1, buildFacing; + struct Selection { std::vector selectedUnits; } selectedUnitsHandler; + struct Mouse { + struct Button { bool pressed = false; float3 camPos, dir; int movement = 0; } buttons[4]; + int lastx = 0, dragCircleCommandThreshold = 4, dragBoxCommandThreshold = 16, dragFrontCommandThreshold = 30; + } mouseState; + Mouse* mouse = &mouseState; + struct View { int viewSizeX = 0; } view; + const View* globalRendering = &view; + std::vector buildInfos; + std::vector buildCommands; + void SetActiveCommandIndex(int index) { inCommand = index; } + // These original branches cannot be admitted by TargetType/Plan. Keep the + // complete native mapper, but never proxy construction/default selection into + // global handlers as a side effect of an explicit Order target. + int GetDefaultCommand(int, int, const float3&, const float3&) { unsupportedWorld = true; return -1; } + size_t GetBuildPositions(const BuildInfo&, const BuildInfo&, const float3&, const float3&) { unsupportedWorld = true; return 0; } + void GiveCommand(const Command&, bool, bool) { unsupportedWorld = true; } + bool GetQueueKeystate() const { + RECOIL_DETAILED_TRACY_ZONE; + return (!invertQueueKey && keys.GetKeyModState(KMOD_SHIFT)) || + (invertQueueKey && !keys.GetKeyModState(KMOD_SHIFT)); +} + unsigned char CreateOptions(bool rightMouseButton) { + RECOIL_DETAILED_TRACY_ZONE; + unsigned char options = 0; + + if (rightMouseButton) { + options |= RIGHT_MOUSE_KEY; + } + if (GetQueueKeystate()) { + // allow mouse button 'rocker' movements to force + // immediate mode (when queuing is the default mode) + if (!invertQueueKey || + (!mouse->buttons[SDL_BUTTON_LEFT].pressed && + !mouse->buttons[SDL_BUTTON_RIGHT].pressed)) { + options |= SHIFT_KEY; + } + } + if (keys.GetKeyModState(KMOD_CTRL)) { options |= CONTROL_KEY; } + if (keys.GetKeyModState(KMOD_ALT) ) { options |= ALT_KEY; } + if (keys.GetKeyModState(KMOD_GUI)) { options |= META_KEY; } + + return options; +} + unsigned char CreateOptions(int button) { return CreateOptions(button != SDL_BUTTON_LEFT); } + Command CheckCommand(Command c) { + // always allow queued commands, since conditions may change s.t. the command becomes valid + if (selectedUnitsHandler.selectedUnits.empty() || (c.GetOpts() & SHIFT_KEY)) + return c; + + for (const int unitID: selectedUnitsHandler.selectedUnits) { + const CUnit* u = unitHandler.GetUnit(unitID); + CCommandAI* cai = u->commandAI; + + if (cai->AllowedCommand(c, false)) + return c; + } + + return Command(CMD_FAILED); +} + bool ZeroRadiusAllowed(const Command& c) { + switch (c.GetID()) { + case CMD_CAPTURE: + case CMD_GUARD: + case CMD_LOAD_UNITS: + case CMD_RECLAIM: + case CMD_REPAIR: + case CMD_RESTORE: + case CMD_RESURRECT: + return false; + } + + return true; +} + void ProcessFrontPositions(float3& pos0, const float3& pos1) { + RECOIL_DETAILED_TRACY_ZONE; + // rotate around corner + if (!frontByEnds) + return; + + // rotate around center + pos0 = pos1 + ((pos0 - pos1) * 0.5f); + pos0.y = CGround::GetHeightReal(pos0.x, pos0.z, false); +} + float GetNumberInput(const SCommandDescription& cd) const { + RECOIL_DETAILED_TRACY_ZONE; + float minV = 0.0f; + float maxV = 100.0f; + if (!cd.params.empty()) { minV = atof(cd.params[0].c_str()); } + if (cd.params.size() >= 2) { maxV = atof(cd.params[1].c_str()); } + const int minX = (globalRendering->viewSizeX * 1) / 4; + const int maxX = (globalRendering->viewSizeX * 3) / 4; + const int effX = std::max(std::min(mouse->lastx, maxX), minX); + const float factor = float(effX - minX) / float(maxX - minX); + + return (minV + (factor * (maxV - minV))); +} + Command GetCommand(int mouseX, int mouseY, int buttonHint, bool preview, const float3& cameraPos, const float3& mouseDir, bool fromPlayerInput) { + RECOIL_DETAILED_TRACY_ZONE; + const Command defaultRet(CMD_FAILED); + + int tempInCommand = inCommand; + int button; + + if (buttonHint >= SDL_BUTTON_LEFT) { + button = buttonHint; + } else if (inCommand != -1) { + button = SDL_BUTTON_LEFT; + } else if (mouse->buttons[SDL_BUTTON_RIGHT].pressed) { + button = SDL_BUTTON_RIGHT; + } else { + return Command(CMD_STOP); + } + + if (button == SDL_BUTTON_RIGHT && preview) { + // right click -> default cmd + // (in preview we might not have default cmd memory set) + if (mouse->buttons[SDL_BUTTON_RIGHT].pressed) { + tempInCommand = defaultCmdMemory; + } else { + tempInCommand = GetDefaultCommand(mouseX, mouseY, cameraPos, mouseDir); + } + } + + if (size_t(tempInCommand) >= commands.size()) { + if (!preview) + SetActiveCommandIndex(-1); + + return Command(CMD_STOP); + } + + switch (commands[tempInCommand].type) { + case CMDTYPE_NUMBER: { + return CheckCommand(Command(commands[tempInCommand].id, CreateOptions(button), GetNumberInput(commands[tempInCommand]))); + } + + case CMDTYPE_ICON: { + Command c(commands[tempInCommand].id, CreateOptions(button)); + if (button == SDL_BUTTON_LEFT && !preview) + LOG_L(L_WARNING, "CMDTYPE_ICON left button press in incommand test? This should not happen."); + + return CheckCommand(c); + } + + case CMDTYPE_ICON_MAP: { + float dist = CGround::LineGroundCol(cameraPos, cameraPos + (mouseDir * viewCamera->GetFarPlaneDist() * 1.4f), false); + + if (dist < 0.0f) + dist = CGround::LinePlaneCol(cameraPos, mouseDir, viewCamera->GetFarPlaneDist() * 1.4f, cameraPos.y + (mouseDir.y * viewCamera->GetFarPlaneDist() * 1.4f)); + + return CheckCommand(Command(commands[tempInCommand].id, CreateOptions(button), cameraPos + (mouseDir * dist))); + } + + case CMDTYPE_ICON_BUILDING: { + const UnitDef* unitdef = unitDefHandler->GetUnitDefByID(-commands[inCommand].id); + const float dist = CGround::LineGroundWaterCol(cameraPos, mouseDir, viewCamera->GetFarPlaneDist() * 1.4f, unitdef->floatOnWater, false); + + if (dist < 0.0f) + return defaultRet; + + + if (unitdef == nullptr) + return Command(CMD_STOP); + + const BuildInfo bi(unitdef, cameraPos + mouseDir * dist, buildFacing); + + if (GetQueueKeystate() && (button == SDL_BUTTON_LEFT)) { + const float3 camTracePos = mouse->buttons[SDL_BUTTON_LEFT].camPos; + const float3 camTraceDir = mouse->buttons[SDL_BUTTON_LEFT].dir; + + const float traceDist = viewCamera->GetFarPlaneDist() * 1.4f; + const float isectDist = CGround::LineGroundWaterCol(camTracePos, camTraceDir, traceDist, unitdef->floatOnWater, false); + + GetBuildPositions(BuildInfo(unitdef, camTracePos + camTraceDir * isectDist, buildFacing), bi, cameraPos, mouseDir); + } else { + GetBuildPositions(bi, bi, cameraPos, mouseDir); + } + + if (buildInfos.empty()) + return Command(CMD_STOP); + + if (buildInfos.size() == 1) { + CFeature* feature = nullptr; + + // TODO: maybe also check out-of-range for immobile builder? + if (!CGameHelper::TestUnitBuildSquare(buildInfos[0], feature, gu->myAllyTeam, false)) + return defaultRet; + + } + + if (!preview) { + // only issue if more than one entry, i.e. user created some + // kind of line/area queue (caller handles the last command) + for (auto beg = buildInfos.cbegin(), end = --buildInfos.cend(); beg != end; ++beg) { + GiveCommand(beg->CreateCommand(CreateOptions(button)), true, fromPlayerInput); + } + } + + buildCommands.clear(); + return CheckCommand((buildInfos.back()).CreateCommand(CreateOptions(button))); + } + + case CMDTYPE_ICON_UNIT: { + const CUnit* unit = nullptr; + const CFeature* feature = nullptr; + + TraceRay::GuiTraceRay(cameraPos, mouseDir, viewCamera->GetFarPlaneDist() * 1.4f, nullptr, unit, feature, true); + + if (unit == nullptr) + return defaultRet; + + Command c(commands[tempInCommand].id, CreateOptions(button)); + c.PushParam(unit->id); + return CheckCommand(c); + } + + case CMDTYPE_ICON_UNIT_OR_MAP: { + Command c(commands[tempInCommand].id, CreateOptions(button)); + + const CUnit* unit = nullptr; + const CFeature* feature = nullptr; + + const float traceDist = viewCamera->GetFarPlaneDist() * 1.4f; + const float isectDist = TraceRay::GuiTraceRay(cameraPos, mouseDir, traceDist, nullptr, unit, feature, true); + + if (isectDist > (traceDist - 300.0f)) + return defaultRet; + + if (unit != nullptr) { + // clicked on unit + c.PushParam(unit->id); + } else { + // clicked in map + c.PushPos(cameraPos + (mouseDir * isectDist)); + } + return CheckCommand(c); + } + + case CMDTYPE_ICON_FRONT: { + const float3 camTracePos = mouse->buttons[button].camPos; + const float3 camTraceDir = mouse->buttons[button].dir; + + const float traceDist = viewCamera->GetFarPlaneDist() * 1.4f; + const float innerDist = CGround::LineGroundCol(camTracePos, camTracePos + camTraceDir * traceDist, false); + float outerDist = -1.0f; + + if (innerDist < 0.0f) + return defaultRet; + + float3 innerPos = camTracePos + (camTraceDir * innerDist); + float3 outerPos; + + Command c(commands[tempInCommand].id, CreateOptions(button), innerPos); + + if (mouse->buttons[button].movement > mouse->dragFrontCommandThreshold) { + // only create the front if the mouse has moved enough + if ((outerDist = CGround::LineGroundCol(cameraPos, cameraPos + mouseDir * traceDist, false)) < 0.0f) + outerDist = CGround::LinePlaneCol(cameraPos, mouseDir, traceDist, innerPos.y); + + ProcessFrontPositions(innerPos, outerPos = cameraPos + (mouseDir * outerDist)); + + const char* paramStr = (commands[tempInCommand].params.empty())? nullptr: commands[tempInCommand].params[0].c_str(); + + if (paramStr != nullptr && innerPos.SqDistance2D(outerPos) > Square(std::atof(paramStr))) + outerPos = innerPos + (outerPos - innerPos).ANormalize() * std::atof(paramStr); + + c.SetPos(0, innerPos); + c.PushPos(outerPos); + } + + return CheckCommand(c); + } + + case CMDTYPE_ICON_UNIT_OR_AREA: + case CMDTYPE_ICON_UNIT_FEATURE_OR_AREA: + case CMDTYPE_ICON_AREA: { + float maxRadius = 100000.0f; + + if (commands[tempInCommand].params.size() == 1) + maxRadius = atof(commands[tempInCommand].params[0].c_str()); + + Command c(commands[tempInCommand].id, CreateOptions(button)); + + if (mouse->buttons[button].movement <= mouse->dragCircleCommandThreshold) { + const CUnit* unit = nullptr; + const CFeature* feature = nullptr; + const float dist2 = TraceRay::GuiTraceRay(cameraPos, mouseDir, viewCamera->GetFarPlaneDist() * 1.4f, NULL, unit, feature, true); + + if (dist2 > (viewCamera->GetFarPlaneDist() * 1.4f - 300) && (commands[tempInCommand].type != CMDTYPE_ICON_UNIT_FEATURE_OR_AREA)) + return defaultRet; + + if (feature && commands[tempInCommand].type == CMDTYPE_ICON_UNIT_FEATURE_OR_AREA) { // clicked on feature + c.PushParam(unitHandler.MaxUnits() + feature->id); + } else if (unit && commands[tempInCommand].type != CMDTYPE_ICON_AREA) { // clicked on unit + if (c.GetID() == CMD_RESURRECT) + return defaultRet; // cannot resurrect units! + + c.PushParam(unit->id); + } else { + // clicked in map; only attack ground if command explicitly set + if (explicitCommand < 0 || !ZeroRadiusAllowed(c)) + return defaultRet; + + c.PushPos(cameraPos + (mouseDir * dist2)); + c.PushParam(0); // zero radius + + if (c.GetID() == CMD_UNLOAD_UNITS) + c.PushParam((float)buildFacing); + } + } else { + // create circular area-command + // find area center-position by tracing from viewCamera along + // mouse direction stored when area started being dragged + const float3 camTracePos = mouse->buttons[button].camPos; + const float3 camTraceDir = mouse->buttons[button].dir; + + const float traceDist = viewCamera->GetFarPlaneDist() * 1.4f; + float innerDist = CGround::LineGroundCol(camTracePos, camTracePos + camTraceDir * traceDist, false); + float outerDist = -1.0f; + + if (innerDist < 0.0f) // in case area center is out of map + innerDist = CGround::LinePlaneCol(camTracePos, camTraceDir, traceDist, CGround::GetWaterPlaneLevel()); + + if (innerDist < 0.0f) + return defaultRet; + + const float3 innerPos = camTracePos + camTraceDir * innerDist; + + if ((outerDist = CGround::LineGroundCol(cameraPos, cameraPos + mouseDir * traceDist, false)) < 0.0f) + outerDist = CGround::LinePlaneCol(cameraPos, mouseDir, traceDist, innerPos.y); + + c.PushPos(innerPos); + c.PushParam(std::min(maxRadius, innerPos.distance2D(cameraPos + mouseDir * outerDist))); + + if (c.GetID() == CMD_UNLOAD_UNITS) + c.PushParam((float)buildFacing); + } + + return CheckCommand(c); + } + + case CMDTYPE_ICON_UNIT_OR_RECTANGLE: { + Command c(commands[tempInCommand].id, CreateOptions(button)); + + if (mouse->buttons[button].movement <= mouse->dragBoxCommandThreshold) { + const CUnit* unit = nullptr; + const CFeature* feature = nullptr; + + const float traceDist = viewCamera->GetFarPlaneDist() * 1.4f; + const float outerDist = TraceRay::GuiTraceRay(cameraPos, mouseDir, traceDist, nullptr, unit, feature, true); + + if (outerDist > (traceDist - 300.0f)) + return defaultRet; + + if (unit != nullptr) { + // clicked on unit + c.PushParam(unit->id); + } else { + // clicked in map; only attack ground if command explicitly set + if (explicitCommand < 0) + return defaultRet; + + c.PushPos(cameraPos + (mouseDir * outerDist)); + } + } else { + // create rectangular area-command + const float3 camTracePos = mouse->buttons[button].camPos; + const float3 camTraceDir = mouse->buttons[button].dir; + + const float traceDist = viewCamera->GetFarPlaneDist() * 1.4f; + const float innerDist = CGround::LineGroundCol(camTracePos, camTracePos + camTraceDir * traceDist, false); + float outerDist = -1.0f; + + if (innerDist < 0.0f) + return defaultRet; + + const float3 innerPos = camTracePos + camTraceDir * innerDist; + + if ((outerDist = CGround::LineGroundCol(cameraPos, cameraPos + mouseDir * traceDist, false)) < 0.0f) + outerDist = CGround::LinePlaneCol(cameraPos, mouseDir, traceDist, innerPos.y); + + c.PushPos(camTracePos + camTraceDir * innerDist); + c.PushPos(cameraPos + mouseDir * outerDist); + } + + return CheckCommand(c); + } + } + + return Command(CMD_STOP); +} +}; +} --- /dev/null +++ b/rts/Game/WebbarNativeOrderWorldHost.inc @@ -0,0 +1,161 @@ +// Members of the independent native read handle; never replace a global camera, +// GUI handler, SDL input state or native GUI selection. +bool PlanOrderWorld(const std::vector& ids, int commandID, int commandType, uint32_t flags, int movement, int facing, + const WebbarInfoWorldView& release, const WebbarInfoWorldView& press, std::vector& plan, WebbarNativeOrder::ActionPlan& actions, Command* policyCommand = nullptr, std::optional* policyGround = nullptr, + const WebbarNativeOrder::MinimapView* miniRelease = nullptr, const WebbarNativeOrder::MinimapView* miniPress = nullptr) +{ + const bool minimap = miniRelease != nullptr; + if (minimap && (std::getenv("WEBBAR_NATIVE_MINIMAP_CONTROLS") == nullptr || miniPress == nullptr || !WebbarNativeOrder::MinimapProxy::Valid(*miniRelease) || !WebbarNativeOrder::MinimapProxy::Valid(*miniPress) + || miniPress->mouseX < 0 || miniPress->mouseY < 0 || uint32_t(miniPress->mouseX) >= miniPress->width || uint32_t(miniPress->mouseY) >= miniPress->height + || miniRelease->width != miniPress->width || miniRelease->height != miniPress->height || miniRelease->originX != miniPress->originX || miniRelease->originZ != miniPress->originZ + || miniRelease->extentX != miniPress->extentX || miniRelease->extentZ != miniPress->extentZ || miniRelease->rotation != miniPress->rotation || miniRelease->farPlane != release.farPlane || miniPress->farPlane != press.farPlane)) return false; + if (!ready || std::getenv("WEBBAR_NATIVE_ORDER_WORLD") == nullptr || gs->PreSimFrame() || gs->noHelperAIs || !ValidOrderView(release) || !ValidOrderView(press) + || release.width != press.width || release.height != press.height || (flags & ~1023u) || (flags & 3u) != SDL_BUTTON_LEFT || (flags & 4u) + || movement < 0 || movement > 0xffffff || facing < 0 || facing > 3 || !WebbarNativeOrder::WorldPlan::TargetType(commandType)) return false; + std::vector commands; int page = 0, index = -1; + if (!OrderCommands(ids, commands, page)) return false; + for (size_t n = 0; n < commands.size(); ++n) { + const auto& desc = commands[n]; + if (desc.id != commandID || desc.type != commandType) continue; + if (index >= 0 || desc.disabled) return false; + index = n; + } + if (index < 0) return false; + CCamera pressView{CCamera::CAMTYPE_VISCUL}; ConfigureOrderCamera(pressView, press); + PrepareOrderCamera(release); + const WebbarNativeOrder::ControlInput keys{false, bool(flags & 8u), bool(flags & 16u), bool(flags & 32u), bool(flags & 64u), bool(flags & 128u), configHandler->GetBool("InvertQueueKey")}; + float3 pressPosition = pressView.GetPos(), pressDirection = pressView.CalcPixelDir(press.mouseX, press.height - 1 - press.mouseY, press.width, press.height, 0); + float3 releasePosition = worldView.GetPos(), releaseDirection = worldView.CalcPixelDir(release.mouseX, release.height - 1 - release.mouseY, release.width, release.height, 0); + int mouseX = release.mouseX, mouseY = release.height - 1 - release.mouseY, width = release.width; + std::optional minimapGround; + if (minimap) { + const auto setting = [](const char* name, float fallback) { return configHandler->IsSet(name) ? configHandler->GetFloat(name) : fallback; }; + const float size = setting("MiniMapUnitSize", WebbarNativeOrder::MinimapProxy::DefaultUnitSize), exponent = setting("MiniMapUnitExp", WebbarNativeOrder::MinimapProxy::DefaultUnitExp); + if (!std::isfinite(size) || size < 0 || size > 1000 || !std::isfinite(exponent) || exponent < -4 || exponent > 4) return false; + const WebbarNativeOrder::MinimapProxy start(*miniPress, size, exponent), end(*miniRelease, size, exponent); + pressPosition = start.ProxyPosition(miniPress->mouseX, miniPress->mouseY); + releasePosition = end.ProxyPosition(miniRelease->mouseX, miniRelease->mouseY); + pressDirection = releaseDirection = -UpVector; + mouseX = miniRelease->mouseX; mouseY = miniRelease->mouseY; width = miniRelease->width; + // TraceScreenRay(x,y,true,true) on a minimap returns the original map + // position at native terrain height, without snapping to a nearby unit. + float3 ground = end.Position(mouseX, mouseY); ground.y = CGround::GetHeightReal(ground.x, ground.z, false); minimapGround = ground; + } + const WebbarNativeOrder::WorldInput input{keys, &worldView, pressPosition, pressDirection, + width, mouseX, mouseY, movement, facing, + configHandler->GetInt("MouseDragCircleCommandThreshold"), configHandler->GetInt("MouseDragBoxCommandThreshold"), configHandler->GetInt("MouseDragFrontCommandThreshold"), false}; + const std::vector selected(ids.begin(), ids.end()); + WebbarNativeOrder::WorldPlan native(std::move(commands), selected, input); + const Command command = native.Plan(index, mouseX, mouseY, releasePosition, releaseDirection); + if (native.unsupportedWorld || command.GetID() == CMD_FAILED || command.GetID() != commandID || !WebbarNativeOrder::DirectCommand(command)) return false; + if (policyCommand != nullptr) *policyCommand = command; + if (policyGround != nullptr) { + policyGround->reset(); + if ((command.GetID() == CMD_ATTACK || command.GetID() == CMD_MANUALFIRE) && command.GetNumParams() == 1) { + if (minimap) *policyGround = minimapGround; else ReadOrderPolicyGround(release, *policyGround); + } + } + if (!PlanOrderActions(ids, command, flags, facing, actions)) return false; + if (commandID == 30100 || commandID == 455624 || actions.consumed) { actions.prepared = true; return true; } + // CommandInsert declined this ordinary command. Preserve the original GUI + // fallback without labelling an empty action plan as a consumed command. + actions = WebbarNativeOrder::ActionPlan{}; + plan.push_back(command); + return true; +} + +private: +void ReadOrderPolicyGround(const WebbarInfoWorldView& release, std::optional& ground) +{ + // The original no-allied-fire widget calls TraceScreenRay(x,y,true). Use + // that exact native API against the retained release camera, not a later + // display camera or a page-supplied destination. + const int top = lua_gettop(L); + lua_pushcfunction(L, ScreenRay); lua_pushinteger(L, release.mouseX); lua_pushinteger(L, release.mouseY); lua_pushboolean(L, true); + if (lua_pcall(L, 3, 2, 0) == 0 && lua_isstring(L, top + 1) && std::strcmp(lua_tostring(L, top + 1), "ground") == 0 && lua_istable(L, top + 2)) { + float3 position; bool valid = true; + for (int n = 0; n < 3; ++n) { lua_rawgeti(L, top + 2, n + 1); position[n] = lua_tonumber(L, -1); valid = valid && lua_type(L, -1) == LUA_TNUMBER && std::isfinite(position[n]); lua_pop(L, 1); } + if (valid && position.IsInBounds() && std::fabs(position.y) <= 1048576) ground = position; + } + lua_settop(L, top); +} +bool InstallOrderActionLogging() +{ + // The original blueprint controllers use these exact LuaUI log levels and + // logging function. Register only logging, retaining the read-only handle. + if (!AddEntriesToTable(L, "LOG", LuaUtils::PushLogEntries)) return false; + lua_getglobal(L, "Spring"); + lua_pushcfunction(L, LuaUtils::Log); lua_setfield(L, -2, "Log"); + lua_pushcfunction(L, LuaUnsyncedRead::IsReplay); lua_setfield(L, -2, "IsReplay"); + lua_pop(L, 1); + return true; +} +static bool ValidOrderView(const WebbarInfoWorldView& view) +{ + bool valid = view.width > 0 && view.width <= 16384 && view.height > 0 && view.height <= 16384 && view.mouseX >= 0 && uint32_t(view.mouseX) < view.width + && view.mouseY >= 0 && uint32_t(view.mouseY) < view.height && !(view.mouseFlags & ~31u) && view.reserved == 0; + for (int i = 0; i < 3; ++i) valid = valid && std::isfinite(view.position[i]) && std::fabs(view.position[i]) <= 1048576 && std::isfinite(view.rotation[i]) && std::fabs(view.rotation[i]) <= 1048576; + return valid && std::isfinite(view.verticalFov) && view.verticalFov > 0 && view.verticalFov < 179 && view.aspect == float(view.width) / float(view.height) + && std::isfinite(view.nearPlane) && view.nearPlane > 0 && std::isfinite(view.farPlane) && view.farPlane > view.nearPlane && view.farPlane <= 1048576; +} +static void ConfigureOrderCamera(CCamera& viewCamera, const WebbarInfoWorldView& view) +{ + viewCamera.SetPos(float3(view.position[0], view.position[1], view.position[2])); + viewCamera.SetRot(float3(view.rotation[0], view.rotation[1], view.rotation[2])); + viewCamera.SetVFOV(view.verticalFov); viewCamera.SetAspectRatio(view.aspect); + viewCamera.SetFrustumScales(float4(0, 0, view.nearPlane, view.farPlane)); + viewCamera.UpdateMatrices(view.width, view.height, view.aspect); + viewCamera.UpdateViewPort(0, 0, view.width, view.height); + viewCamera.UpdateFrustum(); + // CCamera::Update would reset aspect from globalRendering and load GL state. + // Only these private CPU matrices/frustum are required for native projection. +} +void PrepareOrderCamera(const WebbarInfoWorldView& view) +{ + worldWidth = view.width; worldHeight = view.height; + ConfigureOrderCamera(worldView, view); + // Original unsynced feature transforms are normally prepared by the model + // drawer. Match that native matrix step for the browser's current endpoint. + for (const int id: featureHandler.GetActiveFeatureIDs()) { + CFeature* feature = featureHandler.GetFeature(id); + if (feature->noSelect || (!gu->spectatingFullView && !feature->IsInLosForAllyTeam(gu->myAllyTeam))) continue; + feature->drawPos = feature->GetDrawPos(1.0f); + feature->drawMidPos = feature->GetMdlDrawMidPos(); + feature->UpdateTransform(feature->drawPos, false); + } +} +static int ScreenCoordinates(lua_State* L) +{ + auto* self = static_cast(CLuaHandle::GetHandle(L)); + if (self->worldWidth <= 0 || self->worldHeight <= 0) return 0; + const float3 point(luaL_checkfloat(L, 1), luaL_checkfloat(L, 2), luaL_checkfloat(L, 3)); + const float3 coordinates = self->worldView.CalcViewPortCoordinates(point); + lua_pushnumber(L, coordinates.x); lua_pushnumber(L, coordinates.y); lua_pushnumber(L, coordinates.z); + return 3; +} +bool PlanOrderActions(const std::vector& ids, const Command& command, uint32_t flags, int facing, WebbarNativeOrder::ActionPlan& actions) +{ + const int top = lua_gettop(L); + actions.id = command.GetID(); actions.admitted.insert(ids.begin(), ids.end()); + lua_getglobal(L, "WebbarOrderAction"); + lua_createtable(L, ids.size(), 0); + for (size_t n = 0; n < ids.size(); ++n) { lua_pushnumber(L, ids[n]); lua_rawseti(L, -2, n + 1); } + lua_pushnumber(L, command.GetID()); + LuaUtils::PushCommandParamsTable(L, command, false); LuaUtils::PushCommandOptionsTable(L, command, false); + lua_createtable(L, 0, 4); + lua_createtable(L, 4, 0); + for (int n = 0; n < 4; ++n) { lua_pushboolean(L, flags & (16u << n)); lua_rawseti(L, -2, n + 1); } + lua_setfield(L, -2, "modifiers"); + lua_pushnumber(L, facing); lua_setfield(L, -2, "facing"); + lua_pushboolean(L, flags & 256u); lua_setfield(L, -2, "buildSplit"); + lua_pushboolean(L, flags & 512u); lua_setfield(L, -2, "skipAllied"); + bool ok = RunCallIn(L, LuaHashString("WebbarOrderAction"), 5, 1); + if (ok) { + lua_pushlightuserdata(L, &actions); lua_pushcclosure(L, WebbarNativeOrder::ParseActionResult, 1); lua_pushvalue(L, -2); + ok = lua_pcall(L, 1, 0, 0) == 0; + if (!ok) LOG_L(L_WARNING, "[WebBAR] original Order action refused: %s", lua_tostring(L, -1)); + } + lua_settop(L, top); CollectGarbage(true); + return ok && actions.ValidateDispatch(); +} +public: --- /dev/null +++ b/rts/Game/WebbarNativePipHost.inc @@ -0,0 +1,73 @@ +// Members of the independent native read handle. PIP supplies its own cursor +// after the original GUI's HUD receiver; do not enable a global GUI/minimap. +bool ReadPip(const WebbarPipView& view, const std::vector& ids, std::string& json) +{ + if (!ready || std::getenv("WEBBAR_NATIVE_PIP_READS") == nullptr || !ValidWebbarPipView(view)) return false; + SetView(); + std::vector commands; int page = 0, activeIndex = -1; + if (!OrderCommands(ids, commands, page)) return false; + if (view.active) { + for (size_t i = 0; i < commands.size(); ++i) { + if (commands[i].id != view.commandID) continue; + if (activeIndex >= 0 || commands[i].disabled) return false; + activeIndex = int(i); + } + if (activeIndex < 0) return false; + } + struct HudOnlyDefault final: WebbarNativeOrder::CursorDefaultCommand { + mutable bool called = false; + void DefaultCommand(const CUnit*, const CFeature*, int& id) const override { called = true; id = -1; } + } delegate; + WebbarNativeOrder::CursorInput input{}; + input.route = WebbarNativeOrder::CursorInput::HUD; input.viewCamera = &worldView; + input.mouseX = view.mouseX; input.mouseY = view.mouseY; input.activeIndex = activeIndex; + input.rememberedDefaultIndex = -1; + const std::vector selected(ids.begin(), ids.end()); + WebbarNativeOrder::CursorPlan plan(std::move(commands), selected, delegate, input); + const auto base = plan.Resolve(); const int defaultIndex = plan.DefaultIndex(); + // A PIP LuaUI receiver returns before world DefaultCommand dispatch. This + // delegate deliberately refuses any accidental broadening to a world route. + if (delegate.called) return false; + const int top = lua_gettop(L); + lua_getglobal(L, "WebbarReadPip"); + lua_createtable(L, ids.size(), 0); + for (size_t i = 0; i < ids.size(); ++i) { lua_pushnumber(L, ids[i]); lua_rawseti(L, -2, i + 1); } + lua_createtable(L, 0, 10); + const auto field = [this](const char* name, double value) { lua_pushnumber(L, value); lua_setfield(L, -2, name); }; + field("x", view.mouseX); field("y", view.mouseY); field("width", view.width); field("height", view.height); + field("l", view.left); field("r", view.right); field("b", view.bottom); field("t", view.top); + field("rotation", view.rotation); field("zoom", view.zoom); + if (view.active) { lua_createtable(L, 0, 2); field("index", activeIndex + CMD_INDEX_OFFSET); field("id", view.commandID); } + else lua_pushnil(L); + lua_createtable(L, 0, 3); + lua_pushlstring(L, base.command.data(), base.command.size()); lua_setfield(L, -2, "name"); + field("scale", base.scale); field("defaultIndex", defaultIndex + CMD_INDEX_OFFSET); + lua_pushnumber(L, pipClock.Seconds()); + bool ok = RunCallIn(L, LuaHashString("WebbarReadPip"), 5, 1); + if (ok) { lua_getfield(L, -1, "info"); if (lua_istable(L, -1)) AddLifetimes(-1); lua_pop(L, 1); } + uint32_t nodes = 0; + if (ok) ok = JsonValue(-1, json, 0, nodes); + lua_settop(L, top); CollectGarbage(true); + return ok; +} + +private: +WebbarPipClock pipClock; +bool InstallPipReads() +{ + // The caller may still have Spring above the globals table. Register CMD + // explicitly in the global namespace, preserving the caller's stack. + const int top = lua_gettop(L); + lua_pushvalue(L, LUA_GLOBALSINDEX); + if (!AddEntriesToTable(L, "CMD", LuaConstCMD::PushEntries)) { lua_settop(L, top); return false; } + lua_getglobal(L, "Spring"); + lua_pushcfunction(L, LuaUnsyncedRead::GetConfigInt); lua_setfield(L, -2, "GetConfigInt"); + lua_pushcfunction(L, LuaUnsyncedRead::GetConfigFloat); lua_setfield(L, -2, "GetConfigFloat"); + lua_pushcfunction(L, LuaUnsyncedRead::GetLocalTeamID); lua_setfield(L, -2, "GetMyTeamID"); + lua_pushcfunction(L, LuaUnsyncedRead::GetLocalAllyTeamID); lua_setfield(L, -2, "GetMyAllyTeamID"); + lua_pushcfunction(L, LuaUnsyncedRead::GetSpectatingState); lua_setfield(L, -2, "GetSpectatingState"); + lua_pushcfunction(L, LuaUnsyncedRead::IsUnitAllied); lua_setfield(L, -2, "IsUnitAllied"); + lua_settop(L, top); + return true; +} +public: --- /dev/null +++ b/rts/Game/WebbarNativePipView.h @@ -0,0 +1,48 @@ +/* This file is part of the Spring engine (GPL v2 or later), see LICENSE.html */ +#pragma once +#include +#include +#include +#include + +// Geometry only. Targets, visible units, definitions and capabilities never +// arrive in this packet. Mouse coordinates use the original bottom-left origin. +struct WebbarPipView { + int32_t mouseX, mouseY; + uint32_t width, height; + float left, right, bottom, top, rotation, zoom; + int32_t commandID; + uint32_t active, flags, reserved[3]; +}; +static_assert(sizeof(WebbarPipView) == 64); + +inline bool ValidWebbarPipView(const WebbarPipView& v) { + if (!v.width || v.width > 16384 || !v.height || v.height > 16384 + || v.mouseX < -16384 || v.mouseX > 16384 || v.mouseY < -16384 || v.mouseY > 16384 + || v.active > 1 || (!v.active && v.commandID) || v.flags || v.reserved[0] || v.reserved[1] || v.reserved[2]) return false; + for (float n: {v.left, v.right, v.bottom, v.top, v.rotation, v.zoom}) if (!std::isfinite(n) || std::fabs(n) > 1048576) return false; + if (v.left >= v.right || v.top >= v.bottom || v.right - v.left > 1048576 || v.bottom - v.top > 1048576 + || std::fabs(v.rotation) > 6.283186f || v.zoom <= 0 || v.zoom > 2) return false; + // Original RecalculateWorldCoordinates, contentScale1: at quarter-turn views + // the widget swaps the dimensions used by its world rectangle. Admit the + // native full-map aspect padding, which can extend slightly past map edges. + const float degrees = std::fmod(std::fabs(v.rotation * 180.0f / 3.14159265358979323846f), 180.0f); + const bool swapped = degrees > 45 && degrees < 135; + const float x = float(swapped ? v.height : v.width) / (v.right - v.left); + const float z = float(swapped ? v.width : v.height) / (v.bottom - v.top); + const float tolerance = 0.00001f * std::max(1.0f, v.zoom); + return std::fabs(x - v.zoom) <= tolerance && std::fabs(z - v.zoom) <= tolerance; +} + +// Emscripten's steady clock may include performance.timeOrigin. Subtract its +// origin before converting to float32 Lua, preserving the stock 0.1s throttle. +// The initial second makes the first ready hover eligible, as after native load. +struct WebbarPipClock { + using Clock = std::chrono::steady_clock; + explicit WebbarPipClock(Clock::time_point start = Clock::now()): origin(start) {} + float Seconds(Clock::time_point now = Clock::now()) const { + return float(std::chrono::duration(now - origin).count() + 1.0); + } + private: + const Clock::time_point origin; +}; --- /dev/null +++ b/rts/Game/WebbarNativePlayerControl.h @@ -0,0 +1,80 @@ +/* This file is part of the Spring engine (GPL v2 or later), see LICENSE.html */ +#pragma once + +// Included inside WebbarNativeInfo. This sender is separate from the readonly +// native getter handle. It installs no Lua API or user-provided source. +namespace PlayerControl { +constexpr uint32_t MAGIC = 0x31415057; // WPA1; optional bridge9 sidecar +struct Header { + uint32_t magic, version, request, generation, team, allyTeam, frame, kind, targetTeam; + float amount; + uint32_t count, reserved; +}; +static_assert(sizeof(Header) == 48); + +class ResourceSender final: public CLuaHandle { +public: + ResourceSender(): CLuaHandle("WebBAR original resource share sender", LUA_HANDLE_ORDER_UI, false, false) { + SetFullCtrl(false); SetCtrlTeam(NoAccessTeam); SetSelectTeam(NoAccessTeam); + SetFullRead(false); SetReadTeam(NoAccessTeam); SetReadAllyTeam(NoAccessTeam); + } + ~ResourceSender() override { KillLua(); } + bool Share(int target, const char* resource, float amount) { + const int top = lua_gettop(L); + lua_pushcfunction(L, LuaUnsyncedCtrl::ShareResources); + lua_pushnumber(L, target); lua_pushstring(L, resource); lua_pushnumber(L, amount); + const bool ok = RunCallIn(L, LuaHashString("WebbarOriginalResourceShare"), 3, 0); + lua_settop(L, top); CollectGarbage(true); return ok; + } +}; +static ResourceSender* sender = nullptr; + +// The original ShareResources selection belongs to the browser view. Send the +// same native selection/share packets for it, restoring the unrelated native +// GUI's network selection as the existing original Order transport does. +// Never construct a GUI/CObject or mutate the global selected-unit container. +static bool ShareUnits(const std::vector& ids, int target) { + std::vector selected, restore; + const std::vector gui(selectedUnitsHandler.selectedUnits.begin(), selectedUnitsHandler.selectedUnits.end()); + if (!WebbarNativeOrder::SelectionPacket(ids, selected, true) || !WebbarNativeOrder::SelectionPacket(gui, restore, true)) return false; + clientNet->Send(CBaseNetProtocol::Get().SendSelect(gu->myPlayerNum, selected)); + clientNet->Send(CBaseNetProtocol::Get().SendShare(gu->myPlayerNum, target, 1, 0.0f, 0.0f)); + clientNet->Send(CBaseNetProtocol::Get().SendSelect(gu->myPlayerNum, restore)); + return true; +} + +static uint32_t Execute(uint32_t request, uint32_t count, uint32_t target, uint32_t options, float x, float z, float radius, const uint32_t* legacy, bool fromPlayer, std::vector& admitted) { + if (std::getenv("WEBBAR_NATIVE_PLAYER_CONTROLS") == nullptr || !fromPlayer || gu->spectating || gu->spectatingFullView || webbarReplay::Enabled() || std::getenv("WEBBAR_NETWORK") != nullptr || gs->noHelperAIs || gs->PreSimFrame()) return 5; + if (!request || count > 8192 || options != 0 || x != 0 || z != 0 || radius != 0) return 1; + for (int n = 0; n < 64; ++n) if (legacy[n] != 0) return 1; + static std::array words{}; + const int received = MAIN_THREAD_EM_ASM_INT({ + return Module['webbarPollPlayerInput'] ? Module['webbarPollPlayerInput']($0 >>> 0, $1 >>> 0, $2 >>> 0) : 0; + }, request, words.data(), sizeof(words)); + if (received < int(sizeof(Header)) || received > int(sizeof(words)) || received % 8 != 0) return 1; + Header h; std::memcpy(&h, words.data(), sizeof(h)); + if (h.magic != MAGIC || h.version != 1 || h.request != request || !h.generation || h.generation == 0xffffffffu || h.reserved || h.count != count || h.count > 8192 || received != int(sizeof(Header) + h.count * 8)) return 1; + if (!teamHandler.IsValidTeam(gu->myTeam) || h.team != uint32_t(gu->myTeam) || h.allyTeam != uint32_t(gu->myAllyTeam) || h.frame > uint32_t(gs->frameNum) || uint32_t(gs->frameNum) - h.frame > 30) return 2; + if (h.kind < 1 || h.kind > 3 || h.targetTeam != target || target > 254 || !teamHandler.IsValidTeam(target) || target == uint32_t(gu->myTeam) || target == uint32_t(teamHandler.GaiaTeamID())) return 3; + const auto* own = teamHandler.Team(gu->myTeam); const auto* other = teamHandler.Team(target); + if (own == nullptr || own->isDead || other == nullptr || other->isDead || teamHandler.AllyTeam(target) != gu->myAllyTeam) return 4; + if (h.kind != 3) { + if (h.count != 0 || !std::isfinite(h.amount) || h.amount <= 0) return 3; + if (sender == nullptr) sender = new ResourceSender; + return sender->Share(target, h.kind == 1 ? "metal" : "energy", h.amount) ? 0 : 6; + } + if (words[9] != 0) return 3; + std::vector ids; std::unordered_set seen; + for (uint32_t n = 0; n < h.count; ++n) { + const uint32_t id = words[12 + n * 2], lifetime = words[13 + n * 2]; + if (id > 32767 || lifetime == 0 || lifetime == 0xffffffffu || !seen.insert(id).second) return 1; + const auto* unit = unitHandler.GetUnit(id); + if (!WebbarSelectable(unit) || WebbarHudLifetime(unit) != lifetime) return 4; + const auto* carrier = unit->GetTransporter(); + if (carrier != nullptr && carrier->unitDef->IsTransportUnit() && !carrier->unitDef->isFirePlatform) return 4; + ids.push_back(int(id)); + } + if (!ShareUnits(ids, target)) return 6; + admitted = std::move(ids); return 0; +} +} --- a/rts/Game/WebbarNativePoses.h +++ b/rts/Game/WebbarNativePoses.h @@ -39,6 +39,7 @@ }; struct NativeUnitState { int32_t def = -1, creation = INT32_MIN, computedFrame = INT32_MIN, lastActive = -1; + uint32_t lifetime = 0; float world[16] = {}; std::vector pieces; }; @@ -57,7 +58,7 @@ static bool NativePiecePair(const CUnit* unit, size_t piece, Transform& previous, Transform& current) { if (!NativeRequested() || size_t(unit->id) >= nativeStates.size()) return false; const auto& state = nativeStates[unit->id]; - if (state.def != unit->unitDef->id || state.creation != unit->creationFrame || state.computedFrame != gs->frameNum || piece >= state.pieces.size()) return false; + if (state.def != unit->unitDef->id || state.creation != unit->creationFrame || state.computedFrame != gs->frameNum || (state.lifetime && state.lifetime != WebbarHudLifetime(unit)) || piece >= state.pieces.size()) return false; const auto& row = state.pieces[piece]; if (!row.initialized || !row.visible) return false; previous = NativeTransformValue(row.values); current = NativeTransformValue(row.values + 8); return true; } @@ -107,6 +108,8 @@ const uint32_t features = __atomic_load_n(&header->requestedFeatures, __ATOMIC_ACQUIRE) & header->supportedFeatures; const bool propertiesKnown = (features & FEATURE_NATIVE_PROPERTIES) != 0, coupled = NativeCoupledRequested() && NativeDrawStarted(); const bool cloakTimingKnown = propertiesKnown && (features & FEATURE_NATIVE_CLOAK_TIMING) != 0; + const bool lifetimeKnown = propertiesKnown && (features & FEATURE_NATIVE_LIFETIME) != 0; + const bool sensorPositionKnown = lifetimeKnown && coupled && (features & FEATURE_NATIVE_SENSOR_POSITION) != 0; const bool boundsKnown = (features & FEATURE_BOUNDS) != 0, viewKnown = cameraSeq > 0, reflectionKnown = viewKnown && (features & FEATURE_REFLECTION) != 0; float view[32], reflection[28]; std::memcpy(view, header->view, sizeof(view)); if (reflectionKnown) std::memcpy(reflection, header->reflectionView, sizeof(reflection)); @@ -117,9 +120,11 @@ const auto& pieces = unit->localModel.pieces; const uint32_t id = uint32_t(unit->id); const int32_t def = unit->unitDef->id; legacy += 80 + 72.0 * pieces.size(); if (id >= nativeStates.size()) nativeStates.resize(std::max(id + 1, unitHandler.MaxUnits())); + // Zero is deliberate for enemy lives outside allied/full-view admission. + const uint32_t lifetime = lifetimeKnown && (gu->spectatingFullView || unit->allyteam == gu->myAllyTeam) ? WebbarHudLifetime(unit) : 0; auto& state = nativeStates[id]; - if (state.def != def || state.creation != unit->creationFrame || state.pieces.size() != pieces.size()) { - state = NativeUnitState{}; state.def = def; state.creation = unit->creationFrame; state.pieces.resize(pieces.size()); + if (state.def != def || state.creation != unit->creationFrame || state.lifetime != lifetime || state.pieces.size() != pieces.size()) { + state = NativeUnitState{}; state.def = def; state.creation = unit->creationFrame; state.lifetime = lifetime; state.pieces.resize(pieces.size()); } float bounds[4] = {}; uint8_t flags = 0; const uint32_t kind = unit->unitDef->canfly ? 1u : (unit->unitDef->IsImmobileUnit() ? 2u : 0u); @@ -127,6 +132,14 @@ const NativeProperties properties{uint32_t(unit->creationFrame),kind|material,unit->health/std::max(1.f,unit->maxHealth),unit->buildProgress,unit->radius,unit->pos.x,unit->pos.y,unit->pos.z,float(unit->heading)*(3.14159265358979323846f/32768.f),unit->speed.x,unit->speed.z}; // WBC history stays owner-only. Never expose other teams' transition times. const int32_t cloakTransition = unit->team == gu->myTeam ? webbarCloakEvents::Frame(unit->id) : 0; + float sensorPosition[3] = {}; + if (sensorPositionKnown) { + // Same original drawPos as UnitDrawerData/ETA, even when this model's + // pieces are culled. Do not replace it with simulation pos or TRS mixing. + const CUnit* transport = unit->GetTransporter(); + const float3 p = transport ? unit->GetDrawPosOther(transport->preFrameTra.t,transport->pos,nativeDrawStamp.offset) : unit->GetDrawPos(nativeDrawStamp.offset); + sensorPosition[0]=p.x; sensorPosition[1]=p.y; sensorPosition[2]=p.z; + } if(propertiesKnown)flags |= FLAG_NATIVE_PROPERTIES; if (boundsKnown) { const float3 rel = unit->localModel.GetRelMidPos(), offset = unit->GetObjectSpaceVec(float3(-rel.x, rel.y, rel.z)); @@ -144,7 +157,7 @@ if (!active) { flags |= FLAG_CULLED;culled++;for(auto& piece:state.pieces)piece.first=-1; out.Put(id);out.Put(uint16_t(def));out.Put(uint8_t(unit->team));out.Put(flags);out.Put(uint16_t(pieces.size()));out.Put(uint16_t(0)); - if(propertiesKnown)out.Put(properties);if(cloakTimingKnown)out.Put(cloakTransition);if(boundsKnown)out.Bytes(bounds,sizeof(bounds));count++;continue; + if(propertiesKnown)out.Put(properties);if(cloakTimingKnown)out.Put(cloakTransition);if(lifetimeKnown)out.Put(lifetime);if(sensorPositionKnown)out.Bytes(sensorPosition,sizeof(sensorPosition));if(boundsKnown)out.Bytes(bounds,sizeof(bounds));count++;continue; } if (state.lastActive != slotSeq-1) {flags |= FLAG_RESET;for(auto& piece:state.pieces){piece.dirty=true;piece.first=-1;}} NativeStep(unit,state);state.lastActive=slotSeq; @@ -152,12 +165,12 @@ for(auto& piece:state.pieces){if(!piece.dirty)continue;if(piece.first>=0 && acknowledged>=piece.first){piece.dirty=false;continue;}if(piece.first<0)piece.first=slotSeq;included++;} flags |= FLAG_NATIVE_TRS; out.Put(id);out.Put(uint16_t(def));out.Put(uint8_t(unit->team));out.Put(flags);out.Put(uint16_t(pieces.size()));out.Put(included); - if(propertiesKnown)out.Put(properties);if(cloakTimingKnown)out.Put(cloakTransition);if(boundsKnown)out.Bytes(bounds,sizeof(bounds));out.Bytes(state.world,sizeof(state.world)); + if(propertiesKnown)out.Put(properties);if(cloakTimingKnown)out.Put(cloakTransition);if(lifetimeKnown)out.Put(lifetime);if(sensorPositionKnown)out.Bytes(sensorPosition,sizeof(sensorPosition));if(boundsKnown)out.Bytes(bounds,sizeof(bounds));out.Bytes(state.world,sizeof(state.world)); for(size_t i=0;iframeNum),count,uint32_t(out.at),uint32_t(viewKnown),uint32_t(std::min(legacy,4294967295.0)),FEATURE_NATIVE_TRS|(propertiesKnown?FEATURE_NATIVE_PROPERTIES:0u)|(coupled?FEATURE_NATIVE_COUPLED:0u)|(cloakTimingKnown?FEATURE_NATIVE_CLOAK_TIMING:0u)}; + const uint32_t info[]={0x31535057,uint32_t(slotSeq),uint32_t(gs->frameNum),count,uint32_t(out.at),uint32_t(viewKnown),uint32_t(std::min(legacy,4294967295.0)),FEATURE_NATIVE_TRS|(propertiesKnown?FEATURE_NATIVE_PROPERTIES:0u)|(coupled?FEATURE_NATIVE_COUPLED:0u)|(cloakTimingKnown?FEATURE_NATIVE_CLOAK_TIMING:0u)|(lifetimeKnown?FEATURE_NATIVE_LIFETIME:0u)|(sensorPositionKnown?FEATURE_NATIVE_SENSOR_POSITION:0u)}; std::memcpy(out.base,info,sizeof(info));header->stats[0]++;header->stats[1]+=out.at;header->stats[2]+=legacy;header->stats[3]+=withData;header->stats[4]+=records;header->stats[5]+=culled; publishedCameraSeq=cameraSeq;back=__atomic_exchange_n(&header->middle,back|4,__ATOMIC_ACQ_REL)&3;return true; } --- /dev/null +++ b/rts/Game/WebbarNativeScum.h @@ -0,0 +1,144 @@ +/* This file is part of the Spring engine (GPL v2 or later), see LICENSE.html */ +#pragma once +#include "WebbarNativeScumPolicy.h" +#include "WebbarScumEvents.h" +#include +#include "Rendering/Env/MapRendering.h" +#include "Lua/LuaConstGame.h" + +// A presentation-only VM over authentic existing public messages. Its native +// read API cannot select, command, write rules, alter units, GL or the engine. +class WebbarNativeScumReader final:public CLuaHandle { +public: + bool ready=false,enabled=false,reportedFailure=false; + lua_State* originalUnsynced=nullptr; + WebbarNativeScumReader():CLuaHandle("WebBAR original scum policy",LUA_HANDLE_ORDER_RULES+2,false,false){ + SetFullCtrl(false);SetCtrlTeam(NoAccessTeam);SetSelectTeam(NoAccessTeam); + SetFullRead(false);SetReadTeam(NoAccessTeam);SetReadAllyTeam(NoAccessTeam); + LuaLibs::OpenSynced(L,false);lua_pushvalue(L,LUA_GLOBALSINDEX); + ready=AddBasicCalls(L)&&AddCommonModules(L)&&AddEntriesToTable(L,"Spring",LuaSyncedRead::PushEntries)&&AddEntriesToTable(L,"Game",LuaConstGame::PushEntries); + if(ready){ + lua_getglobal(L,"Spring");lua_pushcfunction(L,DrawFrame);lua_setfield(L,-2,"GetDrawFrame");lua_pop(L,1); + lua_pushboolean(L,mapRendering->voidWater);lua_setglobal(L,"WEBBAR_NATIVE_SCUM_VOID_WATER"); + } + lua_settop(L,0); + if(ready)ready=LoadCode(L,WEBBAR_SCUM_POLICY,"Original BAR unsynced scum policy"); + if(ready){ + lua_getglobal(L,"WebbarRaptorScumInitialize"); + ready=RunCallIn(L,LuaHashString("WebbarRaptorScumInitialize"),0,1)&&lua_type(L,-1)==LUA_TBOOLEAN; + enabled=ready&&lua_toboolean(L,-1);lua_settop(L,0); + } + if(ready){WebbarScumEvents::Attach(this,[](void* self,lua_State* source,lua_State* unsynced,int args){static_cast(self)->Sync(source,unsynced,args);});eventHandler.AddClient(this);} + else LOG_L(L_ERROR,"[WebBAR] original scum policy initialization failed"); + } + ~WebbarNativeScumReader()override{WebbarScumEvents::Detach(this);KillLua();} + // This private draw sequence is the native coupled draw request. GetDrawFrame + // has the original low/high16-bit interface, without changing the engine's + // graphical clock or introducing a wall-clock animation source. + static int DrawFrame(lua_State* state){const uint32_t sequence=WebbarPoseMailbox::nativeDrawStamp.sequence;lua_pushnumber(state,sequence&65535u);lua_pushnumber(state,sequence>>16);return 2;} + bool WantsEvent(const std::string& name)override{return ready&&(name=="CollectGarbage"||(enabled&&name=="GameFrame"));} + void GameFrame(int frame)override{ + if(!ready||!enabled)return;const int top=lua_gettop(L); + lua_getglobal(L,"WebbarRaptorScumGameFrame");lua_pushnumber(L,frame); + ready=RunCallIn(L,LuaHashString("WebbarRaptorScumGameFrame"),1,0);lua_settop(L,top); + } + void Sync(lua_State* source,lua_State* unsynced,int args){ + if(!ready)return;originalUnsynced=unsynced;if(!enabled)return; + const int top=lua_gettop(L);lua_getglobal(L,"WebbarRaptorScumEvent");lua_pushstring(L,lua_tostring(source,1)); + for(int i=2;i<=args;++i)lua_pushnumber(L,lua_tonumber(source,i)); + ready=RunCallIn(L,LuaHashString("WebbarRaptorScumEvent"),args,0);lua_settop(L,top); + } + bool Night(){ + if(!originalUnsynced||!enabled)return true; + // GG.NightFactor is the original public unsynced graphics value. Do not + // mutate the original handle or substitute browser lighting parameters. + const int sourceTop=lua_gettop(originalUnsynced),top=lua_gettop(L); + lua_getglobal(originalUnsynced,"GG");bool present=lua_istable(originalUnsynced,-1); + if(present){lua_getfield(originalUnsynced,-1,"NightFactor");present=lua_istable(originalUnsynced,-1);} + bool ok=true; + if(present){ + lua_getglobal(L,"WebbarRaptorScumSunChanged");lua_createtable(L,0,4); + for(const char* name:{"red","green","blue","shadow"}){ + lua_getfield(originalUnsynced,-1,name);const float v=lua_tonumber(originalUnsynced,-1); + ok=ok&&lua_type(originalUnsynced,-1)==LUA_TNUMBER&&std::isfinite(v)&&std::abs(v)<=16777216.0f; + lua_pushnumber(L,v);lua_setfield(L,-2,name);lua_pop(originalUnsynced,1); + } + if(ok)ok=RunCallIn(L,LuaHashString("WebbarRaptorScumSunChanged"),1,0); + } + lua_settop(originalUnsynced,sourceTop);lua_settop(L,top);return ok; + } + bool Reject(const char* phase){if(!reportedFailure){LOG_L(L_ERROR,"[WebBAR] original scum state rejected at %s (frame=%d)",phase,gs->frameNum);reportedFailure=true;}return false;} + bool State(std::vector& packet,bool draw){ + if(!ready||packet.size()!=20)return Reject("reader/header");if(!Night())return Reject("native night factor"); + const char* phase="original state callback"; + const int top=lua_gettop(L);lua_getglobal(L,"WebbarRaptorScumState");lua_pushboolean(L,draw); + bool ok=RunCallIn(L,LuaHashString("WebbarRaptorScumState"),1,1)&&lua_istable(L,-1); + if(ok){ + const int state=lua_gettop(L);phase="native frame";lua_getfield(L,state,"frame");ok=lua_type(L,-1)==LUA_TNUMBER&&lua_tonumber(L,-1)==gs->frameNum;lua_pop(L,1); + if(ok)phase="disabled flag"; + lua_getfield(L,state,"disabled");ok=ok&&lua_type(L,-1)==LUA_TBOOLEAN;const bool disabled=lua_toboolean(L,-1);if(disabled)packet[6]|=8;lua_pop(L,1); + if(!disabled){ + if(ok)phase="original shader config"; + lua_getfield(L,state,"config");ok=ok&&lua_istable(L,-1); + if(ok){lua_getfield(L,-1,"VOIDWATER");const float value=lua_tonumber(L,-1);ok=lua_type(L,-1)==LUA_TNUMBER&&(value==0||value==1);packet[6]=(packet[6]&~16u)|(value==1?16u:0u);lua_pop(L,1);}lua_pop(L,1); + if(ok)phase="original night uniform"; + lua_getfield(L,state,"night");ok=ok&&lua_istable(L,-1)&&lua_objlen(L,-1)==4; + for(int i=1;ok&&i<=4;++i){lua_rawgeti(L,-1,i);const float v=lua_tonumber(L,-1);ok=lua_type(L,-1)==LUA_TNUMBER&&std::isfinite(v)&&std::abs(v)<=16777216.0f;std::memcpy(&packet[15+i],&v,4);lua_pop(L,1);}lua_pop(L,1); + } + for(int group=0;ok&&group<2;++group){ + phase=group==0?"instance rows":"grass rows"; + const int stride=group==0?8:4;lua_getfield(L,state,group==0?"rows":"grass"); + ok=lua_istable(L,-1)&&lua_objlen(L,-1)<=131072&&(!disabled||lua_objlen(L,-1)==0); + const int rows=lua_gettop(L),count=ok?lua_objlen(L,rows):0;packet[7+group]=count;packet[12+group]=packet.size(); + for(int i=1;ok&&i<=count;++i){ + lua_rawgeti(L,rows,i);if(!lua_istable(L,-1)){ok=false;lua_pop(L,1);break;} + phase=group==0?"instance parameters":"grass parameters"; + if(group==0){lua_getfield(L,-1,"params");ok=ok&&lua_istable(L,-1);} + ok=ok&&lua_objlen(L,-1)==stride; + for(int c=1;ok&&c<=stride;++c){ + phase=group==0?"instance scalar":"grass scalar"; + lua_rawgeti(L,-1,c);const float value=lua_tonumber(L,-1); + ok=lua_type(L,-1)==LUA_TNUMBER&&std::isfinite(value)&&std::abs(value)<=16777216.0f; + if(group==0){if(c==4)ok=ok&&value>0;if(c==7)ok=ok&&(value==0||value==1);if(c==8)ok=ok&&value==0;} + else if(c==3)ok=ok&&value>=0;else if(c==4)ok=ok&&value>=0&&value<=gs->frameNum&&std::floor(value)==value; + uint32_t word;std::memcpy(&word,&value,4);packet.push_back(word);lua_pop(L,1); + } + lua_pop(L,group==0?2:1); + } + lua_pop(L,1); + } + } + lua_settop(L,top);return ok||Reject(phase); + } +}; +namespace WebbarNativeScum { +static WebbarNativeScumReader* reader=nullptr; +static std::array perspective{-2,-2,-2,-2,-2}; +static uint32_t epoch=0,generation=0,sequence=0; +static std::vector published; +static bool Enabled(){return std::getenv("WEBBAR_NATIVE_RAPTOR_SCUM")&&std::getenv("WEBBAR_BROWSER")&&!std::getenv("WEBBAR_NETWORK");} +static void Prepare(){ + if(!Enabled()||gs->frameNum< -1)return; + const std::array actual{gu->myPlayerNum,gu->myTeam,gu->myAllyTeam,int(gu->spectating),int(gu->spectatingFullView)}; + // Original scum is a public global terrain effect; view changes update its + // packet scope, not its lifetime. Native information textures provide LOS. + if(perspective!=actual){perspective=actual;if(++epoch==0)++epoch;published.clear();} + if(!reader){if(++generation==0)++generation;sequence=0;reader=new WebbarNativeScumReader;} +} +static void Publish(bool draw=false){ + Prepare();if(!reader||gs->frameNum<0)return; + std::vector p(20,0);p[0]=0x31435357u;p[1]=gs->frameNum;p[2]=epoch;p[3]=gu->myPlayerNum;p[4]=gu->myTeam;p[5]=gu->myAllyTeam; + p[6]=uint32_t(gu->spectating)|(uint32_t(gu->spectatingFullView)<<1)|(mapRendering->voidWater?16u:0u);p[9]=20;p[10]=8;p[11]=4;p[12]=p[13]=20;p[14]=generation; + const float one=1;for(int i=16;i<20;++i)std::memcpy(&p[i],&one,4); + if(!reader->State(p,draw)){p.resize(20);p[6]|=12;p[7]=p[8]=0;p[12]=p[13]=20;for(int i=16;i<20;++i)std::memcpy(&p[i],&one,4);} + if(p.size()==published.size()&&std::equal(p.begin()+2,p.end(),published.begin()+2))return; + // The retained comparison uses sequence zero; only a changed actual state + // consumes a publication sequence, so static scum does not publish per draw. + published=p;if(++sequence==0)++sequence;p[15]=sequence; + MAIN_THREAD_EM_ASM({if(Module['webbarNativeRaptorScum'])Module['webbarNativeRaptorScum'](HEAPU8.slice($0,$0+$1).buffer);},p.data(),p.size()*4); +} +static void Free(){delete reader;reader=nullptr;published.clear();perspective={-2,-2,-2,-2,-2};} +} +static void PrepareWebbarNativeScum(){WebbarNativeScum::Prepare();} +static void FreeWebbarNativeScum(){WebbarNativeScum::Free();} +static void PublishWebbarNativeScumDraw(int32_t sequence){if(WebbarPoseMailbox::NativeCoupledRequested()&&WebbarPoseMailbox::nativeDrawStamp.sequence==uint32_t(sequence))WebbarNativeScum::Publish(true);} --- /dev/null +++ b/rts/Game/WebbarNativeScumPolicy.h @@ -0,0 +1,5407 @@ +/* Complete original BAR GPL-2.0-or-later scum policy; generated by scripts/native-raptor-scum.mjs. */ +#pragma once +static constexpr const char* WEBBAR_SCUM_POLICY=R"WEBBAR_SCUM( +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 + +local scumVoidWater=WEBBAR_NATIVE_SCUM_VOID_WATER +if type(scumVoidWater)~='boolean'then scumVoidWater=false end +-- Read-only graphical storage for the complete original unsynced gadget. +-- No GL, VFS, IO, command, random test action or chat action is exposed. +local function noop()end +local nativeSpring=Spring +local Spring=setmetatable({GetConfigInt=function()return 0 end},{__index=nativeSpring}) +local WG,GG={},{} +local LOG={DEPRECATED=0} +local GL={ARRAY_BUFFER=34962,ELEMENT_ARRAY_BUFFER=34963,UNSIGNED_INT=5125,TRIANGLES=4,LEQUAL=515} +local storage={Define=noop,Upload=noop,Delete=noop,GetID=function()return 1 end} +local vao={AttachVertexBuffer=noop,AttachInstanceBuffer=noop,AttachIndexBuffer=noop,DrawArrays=noop,DrawElements=noop,Delete=noop} +local nightFactor={1,1,1,1} +local shader={Initialize=function()return true end,Activate=noop,Deactivate=noop,SetUniform=function(_,name,...) + assert(name=='nightFactor');nightFactor={...} +end} +local shaderConfig +local gl={GetMapRendering=function(key)assert(key=='voidWater');return scumVoidWater end, + GetVBO=function()return setmetatable({},{__index=storage})end,GetVAO=function()return setmetatable({},{__index=vao})end, + CreateShader=noop,Texture=noop,Culling=noop,DepthTest=noop,StencilFunc=noop,StencilOp=noop,StencilMask=noop,Clear=noop} +gl.LuaShader=setmetatable({GetEngineUniformBufferDefs=function()return ''end,CreateShaderDefinesString=function(config)shaderConfig=config;return ''end},{__call=function()return shader end}) +local listeners,grass={},{} +local grassListener=function(x,z,radius)assert(#grass<131072);grass[#grass+1]={x,z,radius,(Spring.GetGameFrame())}end +local Script={LuaUI=setmetatable({GadgetRemoveGrass=grassListener},{__call=function(_,name)return name=='GadgetRemoveGrass'end})} +local gadgetHandler={IsSyncedCode=function()return false end, + AddSyncAction=function(_,name,callback)assert((name=='ScumCreated'or name=='ScumRemoved')and not listeners[name]);listeners[name]=callback end, + RemoveSyncAction=function(_,name)listeners[name]=nil end,AddChatAction=noop,RemoveChatAction=noop, + RemoveGadget=function()error('Original scum gadget removed itself')end} + +Spring.Utilities=(function()local VFS={Include=function(path)assert(path=="common/holidays.lua");return(function() +if not Spring.GetModOptions then + return +end + +if not Spring.GetModOptions().holiday_events then + return +end + +local modOptions = Spring.GetModOptions() +local currentDay = modOptions.date_day +local currentMonth = modOptions.date_month +local currentYear = modOptions.date_year + +-- Meeus's Julian algorithm Function to calculate Easter Sunday for a given year. Magic. +local function EasterDate(year) + local a = year % 19 + local b = math.floor(year / 100) + local c = year % 100 + local d = math.floor(b / 4) + local e = b % 4 + local f = math.floor((b + 8) / 25) + local g = math.floor((b - f + 1) / 3) + local h = (19 * a + b - d - g + 15) % 30 + local i = math.floor(c / 4) + local k = c % 4 + local l = (32 + 2 * e + 2 * i - h - k) % 7 + local m = math.floor((a + 11 * h + 22 * l) / 451) + local month = math.floor((h + l - 7 * m + 114) / 31) + local day = ((h + l - 7 * m + 114) % 31) + 1 + + return year, month, day +end + +local function GetEasterStartEnd() + local easterYear, easterMonth, easterDay = EasterDate(currentYear) + local firstDay = easterDay - 6 -- We start at Monday before Easter + local firstMonth = easterMonth + local lastDay = easterDay + 1 -- We end at Monday after Easter + local lastMonth = easterMonth + + if easterMonth%2 == 0 then -- Easter is in April - 30 days month + if firstDay < 1 then + firstDay = firstDay + 31 + firstMonth = firstMonth - 1 + end + if lastDay > 30 then + lastDay = lastDay - 30 + lastMonth = lastMonth + 1 + end + + else -- Easter is in March or May - 31 days month + if firstDay < 1 then + firstDay = firstDay + 30 + firstMonth = firstMonth - 1 + end + if lastDay > 31 then + lastDay = lastDay - 31 + lastMonth = lastMonth + 1 + end + end + + return { + firstDay = firstDay, + firstMonth = firstMonth, + lastDay = lastDay, + lastMonth = lastMonth, + easterDay = easterDay, + easterMonth = easterMonth, + } +end + +local EasterEventDates = GetEasterStartEnd() + +-- FIXME: This doesn't support events that start and end in different years. Don't do that for now. Split it into two events if you have to do that. + +-- Spring.Utilities.Gametype.GetCurrentHolidays()["aprilfools"] + +local holidaysList = { + -- Static ----------------------------- + ["aprilfools"] = { + firstDay = { day = 1, month = 4}, + lastDay = { day = 7, month = 4} + }, + ["aprilfools_specialDay"] = { + firstDay = { day = 1, month = 4}, + lastDay = { day = 1, month = 4} + }, + + ["halloween"] = { + firstDay = { day = 17, month = 10}, + lastDay = { day = 31, month = 10} + }, + ["halloween_specialDay"] = { + firstDay = { day = 31, month = 10}, + lastDay = { day = 31, month = 10} + }, + + ["xmas"] = { + firstDay = { day = 12, month = 12}, + lastDay = { day = 31, month = 12} + }, + ["xmas_specialDay"] = { + firstDay = { day = 24, month = 12}, + lastDay = { day = 26, month = 12} + }, + + -- We split these into two events because yes + ["newyearbefore"] = { + firstDay = { day = 31, month = 12}, + lastDay = { day = 31, month = 12} + }, + ["newyearafter"] = { + firstDay = { day = 1, month = 1}, + lastDay = { day = 1, month = 1} + }, + + -- Dynamic ----------------------------- + ["easter"] = { + firstDay = { day = EasterEventDates.firstDay, month = EasterEventDates.firstMonth}, + lastDay = { day = EasterEventDates.lastDay, month = EasterEventDates.lastMonth} + }, + ["easter_specialDay"] = { + firstDay = { day = EasterEventDates.easterDay, month = EasterEventDates.easterMonth}, + lastDay = { day = EasterEventDates.easterDay, month = EasterEventDates.easterMonth} + }, +} + +return holidaysList +end)()end} +local smallTeamThreshold = 4 +local initialized = false +local settings = { } + +local holidaysList = VFS.Include("common/holidays.lua") + +local function getSettings() + if initialized then + return settings + end + + local allyTeamCount, playerCount = 0, 0 + local isSinglePlayer, is1v1, isTeams, isBigTeams, isSmallTeams, isRaptors, isScavengers, isPvE, isCoop, isFFA, isSandbox = false, false, false, false, false, false, false, false, false, false, false + local scavTeamID, scavAllyTeamID, raptorTeamID, raptorAllyTeamID + local isHoliday = {} + + local gaiaAllyTeamID = select(6, Spring.GetTeamInfo(Spring.GetGaiaTeamID(), false)) + local springAllyTeamList = Spring.GetAllyTeamList() + local allyTeamList = {} + local allyTeamSizes = {} + local entirelyHumanAllyTeams = {} + + for _, allyTeamID in ipairs(springAllyTeamList) do + local teamList = Spring.GetTeamList(allyTeamID) or {} + local allyteamEntirelyHuman = true + + if #teamList > 0 and allyTeamID ~= gaiaAllyTeamID then + local isAllyTeamValid = true + + for _, teamID in ipairs(teamList) do + if select (4, Spring.GetTeamInfo(teamID, false)) then + allyteamEntirelyHuman = false + else + local teamPlayers = Spring.GetPlayerList(teamID) + for _, playerID in ipairs(teamPlayers) do + playerCount = playerCount + 1 + end + end + + local luaAI = Spring.GetTeamLuaAI(teamID) + + if luaAI then + if luaAI:find("Raptors") then + isRaptors = true + isAllyTeamValid = false + raptorTeamID = teamID + raptorAllyTeamID = allyTeamID + elseif luaAI:find("Scavengers") then + isScavengers = true + isAllyTeamValid = false + scavTeamID = teamID + scavAllyTeamID = allyTeamID + end + end + end + + if isAllyTeamValid then + allyTeamList[#allyTeamList+1] = allyTeamID + allyTeamSizes[#allyTeamSizes+1] = #teamList + end + + if allyteamEntirelyHuman then + entirelyHumanAllyTeams[#entirelyHumanAllyTeams+1] = allyTeamID + end + end + end + + allyTeamCount = #allyTeamList + + isSmallTeams = true + for _, teamSize in ipairs(allyTeamSizes) do + if teamSize > 1 then + isTeams = true + end + + isSmallTeams = isSmallTeams and teamSize <= smallTeamThreshold + end + + isSinglePlayer = playerCount == 1 + isSmallTeams = isTeams and isSmallTeams + isBigTeams = isTeams and not isSmallTeams + isPvE = isRaptors or isScavengers + + if allyTeamCount > 2 then + isFFA = true + elseif allyTeamCount < 2 and not isPvE then + isSandbox = true + elseif allyTeamCount == 2 and not isTeams then + is1v1 = true + end + + if #entirelyHumanAllyTeams == 1 and #Spring.GetTeamList(entirelyHumanAllyTeams[1]) > 1 then + isCoop = true + end + + if holidaysList and Spring.GetModOptions and Spring.GetModOptions().date_day then + local currentDay = Spring.GetModOptions().date_day + local currentMonth = Spring.GetModOptions().date_month + local currentYear = Spring.GetModOptions().date_year + + -- FIXME: This doesn't support events that start and end in different years. + for holiday, dates in pairs(holidaysList) do + local afterStart = false + local beforeEnd = false + if (dates.firstDay.month == currentMonth and dates.firstDay.day <= currentDay) or (dates.firstDay.month < currentMonth) then + afterStart = true + end + if (dates.lastDay.month == currentMonth and dates.lastDay.day >= currentDay) or (dates.lastDay.month > currentMonth) then + beforeEnd = true + end + + if afterStart and beforeEnd then + isHoliday[holiday] = true + else + isHoliday[holiday] = false + end + end + end + + initialized = true + + settings = { + allyTeamCount = allyTeamCount, + allyTeamList = allyTeamList, + playerCount = playerCount, + isSinglePlayer = isSinglePlayer, + is1v1 = is1v1, + isTeams = isTeams, + isBigTeams = isBigTeams, + isSmallTeams = isSmallTeams, + isRaptors = isRaptors, + isScavengers = isScavengers, + isPvE = isPvE, + isCoop = isCoop, + isFFA = isFFA, + isSandbox = isSandbox, + scavTeamID = scavTeamID, + scavAllyTeamID = scavAllyTeamID, + raptorTeamID = raptorTeamID, + raptorAllyTeamID = raptorAllyTeamID, + isHoliday = isHoliday, + } + + return settings +end + +return { + ---Get number of ally teams (humans and AIs, but not Raptors and Scavengers). + GetAllyTeamCount = function() return getSettings().allyTeamCount end, + ---Get ally team list (humans and AIs, but not Raptors and Scavengers). + ---@return integer[] allyTeamList table[i] = allyTeamID + GetAllyTeamList = function () return getSettings().allyTeamList end, + ---@return integer? playerCount Get number of players in a game, nil If it's an AI only game. + GetPlayerCount = function () return getSettings().playerCount end, + Gametype = { + ---@return boolean + IsSinglePlayer = function () return getSettings().isSinglePlayer end, + ---@return boolean + Is1v1 = function () return getSettings().is1v1 end, + ---@return boolean + IsTeams = function () return getSettings().isTeams end, + ---@return boolean + IsBigTeams = function () return getSettings().isBigTeams end, + ---@return boolean + IsSmallTeams = function () return getSettings().isSmallTeams end, + ---@return boolean + IsRaptors = function () return getSettings().isRaptors end, + ---@return boolean + IsScavengers = function () return getSettings().isScavengers end, + ---@return boolean + IsPvE = function () return getSettings().isPvE end, + ---@return boolean + IsCoop = function () return getSettings().isCoop end, + ---@return boolean + IsFFA = function () return getSettings().isFFA end, + ---@return boolean + IsSandbox = function () return getSettings().isSandbox end, + ---@return table? isHoliday Currently running holiday events. + ---See common/holidays.lua for more information. + GetCurrentHolidays = function () return getSettings().isHoliday end, + }, + ---@return integer? scavTeamID Team ID for the scavenger team. + GetScavTeamID = function () return getSettings().scavTeamID end, + ---@return integer? scavAllyTeamID Team ID for the scavenger ally team. + GetScavAllyTeamID = function () return getSettings().scavAllyTeamID end, + ---@return integer? raptorTeamID Team ID for the raptor team. + GetRaptorTeamID = function () return getSettings().raptorTeamID end, + ---@return integer? raptorAllyTeamID Team ID for the raptor ally team. + GetRaptorAllyTeamID = function () return getSettings().raptorAllyTeamID end, + +} + +end)() +gl.InstanceVBOTable=(function() +local GL_BUFFER = 0x82E0 +local gldebugannotations = (Spring.GetConfigInt("gldebugannotations") == 1) +--Spring.Echo("gldebugannotations", gldebugannotations) +local function makeInstanceVBOTable(layout, maxElements, myName, unitIDattribID) + -- layout: this must be an array of tables with at least the following specified: {{id = 1, name = 'optional', size = 4}} + -- maxElements: will be dynamic anyway, but defaults to 64 + -- myName: optional name, useful for debugging + -- unitIDattribID: the attribute ID in the layout of the uvec4 of unitID bindings (e.g. 4 for {id = 4, name = 'instData', type = GL.UNSIGNED_INT, size= 4} ) + -- returns: nil | instanceTable + if maxElements == nil then maxElements = 64 end -- default size + if myName == nil then myName = "InstanceVBOTable" end + local newInstanceVBO = gl.GetVBO(GL.ARRAY_BUFFER,true) + if newInstanceVBO == nil then Spring.Echo("makeInstanceVBOTable, cannot get VBO for", myName); return nil end + newInstanceVBO:Define( + maxElements, + layout + ) + + + + local instanceStep = 0 + for i,attribute in pairs(layout) do + instanceStep = instanceStep + attribute.size + end + local instanceData = {} + for i = 1, instanceStep * maxElements do + instanceData[i] = 0 + end + local instanceTable = { + instanceVBO = newInstanceVBO, + instanceData = instanceData, + instanceStep = instanceStep, + usedElements = 0, + maxElements = maxElements, + myName = myName, + instanceIDtoIndex = {}, -- this maps each instance ID to where it is in the buffer, 1 based + indextoInstanceID = {}, -- this tells us what instanceID is located in any given pos + layout = layout, + dirty = false, + numVertices = 0, + primitiveType = GL.TRIANGLES, + debugZombies = true, -- this is new, and its for debugging non-existing stuff on unitdestroyed + lastInstanceID = 0, + } + + if unitIDattribID ~= nil then + instanceTable.indextoUnitID = {} + instanceTable.unitIDattribID = unitIDattribID + instanceTable.popUnitIDFailuresInGameFrame = {} + end + + function instanceTable:clearInstanceTable() + -- this wont resize it, but quickly sets it to empty + self.usedElements = 0 + self.instanceIDtoIndex = {} + self.indextoInstanceID = {} + if self.indextoUnitID then self.indextoUnitID = {} end + end + + function instanceTable:makeVAOandAttach(vertexVBO, instanceVBO, indexVBO) -- Attach a vertex buffer to an instance buffer, and optionally, an index buffer if one is supplied. + -- There is a special case for this, when we are using a vertexVBO as a quasi-instanceVBO, e.g. when we are using the geometry shader to draw a vertex as each instance. + --iT.vertexVBO = vertexVBO + --iT.indexVBO = indexVBO + local newVAO = nil + newVAO = gl.GetVAO() + if newVAO == nil then goodbye("Failed to create newVAO") end + self.VAO = newVAO + if vertexVBO == nil then -- the special case where are using 'vertices' as 'instances' + newVAO:AttachVertexBuffer(instanceVBO) + else + newVAO:AttachVertexBuffer(vertexVBO) + newVAO:AttachInstanceBuffer(instanceVBO) + self.vertexVBO = vertexVBO + self.instanceVBO = instanceVBO + end + if indexVBO then + newVAO:AttachIndexBuffer(indexVBO) + self.indexVBO = indexVBO + function self:Draw() + self.VAO:DrawElements(GL.TRIANGLES, nil, 0, self.usedElements, 0) + end + else + function self:Draw() + self.VAO:DrawArrays(GL.TRIANGLES, nil, 0, self.usedElements, 0) + end + end + return newVAO + end + + function instanceTable:clearInstanceTable() + -- this wont resize it, but quickly sets it to empty + self.usedElements = 0 + self.instanceIDtoIndex = {} + self.indextoInstanceID = {} + if self.indextoUnitID then self.indextoUnitID = {} end + end + + function instanceTable:compact() + self.destroyedElements = 0 + -- so this is for the edge case, where we have silently removed elements from instanceIDtoIndex + -- where we have holes everywhere, so we have to 'compact' the table, + -- by copying back contiguously while preserving element order + local newInstanceIDtoIndex = {} + local newIndexToInstanceID = {} + local newInstanceData = {} + local newUsedElements = 0 + for i = 1, self.usedElements do + local instanceID = self.indextoInstanceID[i] + local index = self.instanceIDtoIndex[self.indextoInstanceID[i]] + if index then + local instanceStep = self.instanceStep + local instanceData = self.instanceData + + local dstpos = newUsedElements * instanceStep + local srcpos = (i - 1) * instanceStep + for j=1, instanceStep do + newInstanceData[dstpos + j] = instanceData[srcpos +j] + end + newUsedElements = newUsedElements + 1 + newInstanceIDtoIndex[instanceID] = newUsedElements + newIndexToInstanceID[newUsedElements] = instanceID + else + --Spring.Echo("compacting index",i, 'instanceID', instanceID) + end + end + --Spring.Echo("Post compacting", self.usedElements, newUsedElements) + self.usedElements = newUsedElements + self.instanceIDtoIndex = newInstanceIDtoIndex + self.indextoInstanceID = newIndexToInstanceID + self.instanceData = newInstanceData + --iT.instanceVBO:Upload(iT.instanceData,nil,oldElementIndex-1,oldOffset +1,oldOffset + iTStep) + if self.usedElements > 0 then + self.instanceVBO:Upload(self.instanceData) + end + end + + + function instanceTable:draw(primitiveType) + if self.usedElements > 0 then + if self.indexVBO then + self.VAO:DrawElements(primitiveType or self.primitiveType, self.numVertices, 0, self.usedElements,0) + else + self.VAO:DrawArrays (primitiveType or self.primitiveType, self.numVertices, 0, self.usedElements,0) + end + end + end + + function instanceTable:getMemUsage() + -- arrays are 16 bytes per element + -- Hash tables are 40 bytes per element + local totalMem = 0 + totalMem = totalMem + self.usedElements * self.instanceStep * 16 -- the actual instance data + totalMem = totalMem + self.usedElements * 16 -- indextoinstanceid + totalMem = totalMem + self.usedElements * 40 -- instanceIDtoIndex + if self.indextoUnitID then totalMem = totalMem + self.usedElements * 16 end + return totalMem + end + + function instanceTable:Delete() + -- Frees the instancevbo and vao for this instance table. Does not touch the vertex and index vbos. + -- returns an estimate of how much ram was used + if self.instanceVBO then self.instanceVBO:Delete() end + if self.VAO then self.VAO:Delete() end + local memusage = self:getMemUsage() + self:clearInstanceTable() + return memusage + end + + + newInstanceVBO:Upload(instanceData) + + -- I believe that the openGL spec doesnt guarantee that a buffer has an idea before data is uploaded to it, so we will fill it with zeros. + if gldebugannotations then + gl.ObjectLabel(GL_BUFFER, newInstanceVBO:GetID(), myName) + end + + + --register self in WG if possible + if WG then + if WG.VBOTableRegistry == nil then + --Spring.Echo("WG.VBORegistry == nil, creating registry on first load") + WG.VBOTableRegistry = {} + end + if WG.VBOTableRegistry[instanceTable.myName] then + local newname = instanceTable.myName .. tostring(math.random()) + --Spring.Echo(instanceTable.myName, 'already registered, renaming to', newname) + instanceTable.myName = newname + end + --Spring.Echo("Registered ", instanceTable.myName) + WG.VBOTableRegistry[instanceTable.myName] = instanceTable + end + + return instanceTable +end + +local function nextInstanceID(iT) + iT.lastInstanceID = iT.lastInstanceID + 1 + return iT.lastInstanceID +end + +local function clearInstanceTable(iT) + -- this wont resize it, but quickly sets it to empty + iT.usedElements = 0 + iT.instanceIDtoIndex = {} + iT.indextoInstanceID = {} + if iT.indextoUnitID then iT.indextoUnitID = {} end +end + +local function makeVAOandAttach(vertexVBO, instanceVBO, indexVBO) -- Attach a vertex buffer to an instance buffer, and optionally, an index buffer if one is supplied. + -- There is a special case for this, when we are using a vertexVBO as a quasi-instanceVBO, e.g. when we are using the geometry shader to draw a vertex as each instance. + --iT.vertexVBO = vertexVBO + --iT.indexVBO = indexVBO + local newVAO = nil + newVAO = gl.GetVAO() + if newVAO == nil then goodbye("Failed to create newVAO") end + if vertexVBO == nil then -- the special case where are using 'vertices' as 'instances' + newVAO:AttachVertexBuffer(instanceVBO) + else + newVAO:AttachVertexBuffer(vertexVBO) + newVAO:AttachInstanceBuffer(instanceVBO) + end + if indexVBO then + newVAO:AttachIndexBuffer(indexVBO) + end + -- this allows us to set up our sane + + + return newVAO +end + + +--------------- DEBUG HELPERS -------------------------- +local function comparetables(t1, t2, name) + for k,v in pairs(t1) do + if t2[k] == nil then + Spring.Echo("Key ",k,"with value",v,"existing in t1 does not exist in t2 in ", name) + elseif t2[k] ~= v then + Spring.Echo("Value ",v,"for",k,"existing in t1 does not match value for t2",t2[k]," in ", name) + end + end + + for k,v in pairs(t2) do + if t1[k] == nil then + Spring.Echo("Key ",k,"with value",v,"existing in t2 does not exist in t1 in ", name) + elseif t1[k] ~= v then + Spring.Echo("Value ",v,"for",k,"existing in t2 does not match value for t1",t1[k]," in ", name) + end + end +end + +local function dbgt(t, name) + name = name or "" + local gf = Spring.GetGameFrame() + local count = 0 + local res = '' + for k,v in pairs(t) do + if type(k) == 'number' and type(v) == 'number' then + res = res .. tostring(k) .. ':' .. tostring(v) ..',' + count = count + 1 + end + end + Spring.Echo(tostring(gf).. " " ..name .. ' #' .. tostring(count) .. ' {'..res .. '}') + return res +end + +local function counttable(t) + local count = 0 + if type(t) ~= type({}) then return 0 end + for k, v in pairs(t) do count = count + 1 end + return count +end + +local function validateInstanceVBOTable(iT, calledfrom) + -- check that instanceIDtoIndex and indextoInstanceID are valid and contigous: + for i=1, iT.usedElements do + if iT.indextoInstanceID[i] == nil then + Spring.Echo("There is a hole in indextoInstanceID", iT.myName, "at", i,"out of",iT.usedElements, calledfrom) + --Spring.Echo() + if iT.indextoUnitID[i] == nil then + Spring.Echo("It is also missing from indextoUnitID") + else + Spring.Echo("But it does exist in indextoUnitID with an unitID of ", iT.indextoUnitID[i]) + Spring.Echo("This is valid?", Spring.GetUnitPosition(iT.indextoUnitID[i])) + end + + else + local instanceID = iT.indextoInstanceID[i] + if iT.instanceIDtoIndex[instanceID] == nil then + Spring.Echo("There is a hole instanceIDtoIndex", iT.myName, "at", i," iT.instanceIDtoIndex[instanceID] == nil ") + elseif iT.instanceIDtoIndex[instanceID] ~= i then + Spring.Echo("There is a problem in indextoInstanceID", iT.myName, "at i =", i," iT.indextoInstanceID[instanceID] ~= i, it is instead: ", iT.indextoInstanceID[instanceID] ) + end + end + end + local indextoInstanceIDsize = counttable(iT.indextoInstanceID) + local instanceIDtoIndexsize = counttable(iT.instanceIDtoIndex) + local indextoUnitID = counttable(iT.indextoUnitID) + if (indextoInstanceIDsize ~= instanceIDtoIndexsize) or (instanceIDtoIndexsize ~= indextoUnitID) then + Spring.Echo("Table size mismatch during validation of", iT.myName, indextoInstanceIDsize, instanceIDtoIndexsize, indextoUnitID) + end + +end + +function locateInvalidUnits(iT) + if iT.validinfo == nil then iT.validinfo = {} end + local invalidcount = 0 + for i, unitID in ipairs(iT.indextoUnitID) do + if iT.featureIDs then + if Spring.ValidFeatureID(unitID) then + local px, py, pz = Spring.GetFeaturePosition(unitID) + local fdefname = FeatureDefs[Spring.GetFeatureDefID(unitID)].name + iT.validinfo[unitID] = {px = px, py = py, pz = pz, fdefname = fdefname} + else + Spring.SendCommands({"pause 1"}) + Spring.Echo("INVALID feature, last seen at", unitID) + local vi = iT.validinfo[unitID] + local markertext = tostring(unitID) .. "," .. dbgt(vi) + Spring.MarkerAddPoint(vi.px, vi.py, vi.pz, markertext ) + invalidcount = invalidcount + 1 + end + else + if Spring.ValidUnitID(unitID) then + local px, py, pz = Spring.GetUnitPosition(unitID) + local unitDefID = Spring.GetUnitDefID(unitID) + local unitdefname = (unitDefID and UnitDefs[unitDefID].name) or "unknown:nil" + iT.validinfo[unitID] = {px = px, py = py, pz = pz, unitdefname = unitdefname} + else + Spring.SendCommands({"pause 1"}) + Spring.Echo(iT.myName, " INVALID unitID",unitID,"#elements", iT.usedElements, "last seen at tablepos:", i) + + local vi = iT.validinfo[unitID] + local markertext = tostring(unitID) .. "," .. dbgt(vi) + Spring.MarkerAddPoint(vi.px, vi.py, vi.pz, markertext ) + invalidcount = invalidcount + 1 + end + end + end + return invalidcount +end + +------------------------------END DEBUG HELPERS --------------------------- + +local function resizeInstanceVBOTable(iT) + -- iT: the InstanceVBOTable to double in size 'dynamically' resize the VBO, to double its size + -- this is called automatically when the existing instanceVBO gets full + -- Also performs a busload of sanity checking + -- Spring.Echo("instanceVBOTable full, resizing to double size",iT.myName, iT.usedElements,iT.maxElements) + iT.maxElements = iT.maxElements * 2 + local newInstanceVBO = gl.GetVBO(GL.ARRAY_BUFFER,true) + newInstanceVBO:Define(iT.maxElements, iT.layout) + + if iT.instanceVBO then iT.instanceVBO:Delete() end -- release if previous one existed + iT.instanceVBO = newInstanceVBO + -- ok this needs some sanitation right here, with reporting. + if iT.indextoUnitID then + -- we need to walk through both tables at the same time, and virtually pop all invalid unit/featureIDs on a resize, or else face dire consequences (crashes) later on + -- the tables we need to keep updated are: + local new_instanceData = {} + local new_instanceData_count = 0 + local new_usedElements = 0 + local new_instanceIDtoIndex = {} + local new_indextoInstanceID = {} + local new_indextoUnitID = {} + local invalidcount = 0 + local iTStep = iT.instanceStep + + for i, objectID in ipairs(iT.indextoUnitID) do + local isValidID = false + if iT.featureIDs then isValidID = Spring.ValidFeatureID(objectID) + else isValidID = Spring.ValidUnitID(objectID) end + if isValidID then + local offset = new_usedElements * iTStep + for j = 1, iTStep do + new_instanceData_count = new_instanceData_count + 1 + new_instanceData[new_instanceData_count] = iT.instanceData[j + offset] + end + new_usedElements = new_usedElements + 1 + local currentInstanceID = iT.indextoInstanceID[i] + new_indextoInstanceID[new_usedElements] = iT.indextoInstanceID[i] + new_indextoUnitID[new_usedElements] = iT.indextoUnitID[i] + new_instanceIDtoIndex[currentInstanceID] = new_usedElements + --Spring.Echo("Resize:",currentInstanceID, iT.indextoUnitID[i] ) + invalidcount = invalidcount + 1 + else + Spring.Echo("Warning: Found invalid unit/featureID",objectID,"at",i,"while resizing",iT.myName) + end + end + + if invalidcount == 0 then + comparetables( iT.instanceData, new_instanceData, "instanceData") + comparetables( iT.instanceIDtoIndex, new_instanceIDtoIndex, "instanceIDtoIndex") + comparetables( iT.indextoInstanceID, new_indextoInstanceID, "indextoInstanceID") + comparetables( iT.indextoUnitID, new_indextoUnitID, "indextoUnitID") + end + + iT.instanceData = new_instanceData + iT.usedElements = new_usedElements + iT.instanceIDtoIndex = new_instanceIDtoIndex + iT.indextoInstanceID = new_indextoInstanceID + iT.indextoUnitID = new_indextoUnitID + end + + iT.instanceVBO:Upload(iT.instanceData,nil,0,1,iT.usedElements * iT.instanceStep) + + if gldebugannotations then + gl.ObjectLabel(GL_BUFFER, iT.instanceVBO:GetID(), iT.myName) + end + + if iT.VAO then -- reattach new if updated :D + iT.VAO:Delete() + iT.VAO = makeVAOandAttach(iT.vertexVBO,iT.instanceVBO, iT.indexVBO) + end + + if iT.indextoUnitID then + if iT.featureIDs then + iT.instanceVBO:InstanceDataFromFeatureIDs(iT.indextoUnitID, iT.unitIDattribID) + else + iT.instanceVBO:InstanceDataFromUnitIDs(iT.indextoUnitID, iT.unitIDattribID) + end + end + return iT.maxElements +end + +--[[ from Ivand: +instVBO:Upload({ + 100, 0, 0, + -100, 0, 0, + 0, 0, 100, + 0, 0, -100, + }, 7, 1, 4, 6) +Here is how you upload starting from 1st element and starting from 4th element in Lua array (-100) and finishing with 6th element (0), essentially it will upload (-100, 0, 0) into 7th attribute of 2nd instance. +]]-- + +local function pushElementInstance(iT,thisInstance, instanceID, updateExisting, noUpload, unitID) + -- iT: instanceTable created with makeInstanceTable + -- thisInstance: is a lua array of values to add to table, MUST BE INSTANCESTEP SIZED LUA ARRAY + -- instanceID: an optional key given to the item, so it can be easily removed/updated by reference, defaults to the index of the instance in the buffer (1 based) + -- updateExisting: allow updating an existing element (same instanceID key) + -- noUpload: prevent the VBO from being uploaded, if you feel like you are going to do a lot of ops and wish to manually upload when done instead + -- unitID: if given, it will store then unitID corresponding to this instance, and will try to update the InstanceDataFromUnitIDs for this unit + -- returns: the index of the instanceID in the table on success, else nil + if #thisInstance ~= iT.instanceStep then + Spring.Echo("Trying to upload an oddly sized instance into",iT.myName, #thisInstance, "instead of ",iT.instanceStep) + Spring.Debug.TraceFullEcho(20,20,20, "pushElementInstance Failure:"..iT.myName ) + end + local iTusedElements = iT.usedElements + local iTStep = iT.instanceStep + local endOffset = iTusedElements * iTStep + if instanceID == nil then instanceID = nextInstanceID(iT) end + local thisInstanceIndex = iT.instanceIDtoIndex[instanceID] + + if (iTusedElements + 1 ) >= iT.maxElements then -- add 1 extra for safety (not the best idea, but we seem to be running over it by 1) + resizeInstanceVBOTable(iT) + iTusedElements = iT.usedElements -- because during validation of unitIDs during resizing, we can decrease the actual size of the table! + thisInstanceIndex = iT.instanceIDtoIndex[instanceID] -- this too, can change, TODO, also do this in VBOIDtable! + end + + if thisInstanceIndex == nil then -- new, register it + thisInstanceIndex = iTusedElements + 1 + iT.usedElements = iTusedElements + 1 + iT.instanceIDtoIndex[instanceID] = thisInstanceIndex + iT.indextoInstanceID[thisInstanceIndex] = instanceID + else -- pre-existing ID, update or bail + if updateExisting == nil then + Spring.Echo("Tried to add existing element to an instanceTable",iT.myName, instanceID) + return nil + else + endOffset = (thisInstanceIndex - 1) * iTStep + end + end + local instanceData = iT.instanceData + for i =1, iTStep do -- copy data, but fast + instanceData[endOffset + i] = thisInstance[i] + end + + if unitID ~= nil then + local isvalidid + if iT.featureIDs then isvalidid = Spring.ValidFeatureID(unitID) + else isvalidid = Spring.ValidUnitID(unitID) end + if isvalidid == false then + Spring.Echo("Error: Attempted to push an invalid unit/featureID",unitID, "into", iT.myName) + noUpload = true + Spring.Debug.TraceFullEcho(20,20,20,"invalid unit/featureID in " ..iT.myName) + end + iT.indextoUnitID[thisInstanceIndex] = unitID + end + + if noUpload ~= true then --upload or mark as dirty + iT.instanceVBO:Upload(thisInstance, nil, thisInstanceIndex - 1) + --Spring.Echo("pushElementInstance,unitID, iT.unitIDattribID, thisInstanceIndex",unitID, iT.unitIDattribID, thisInstanceIndex) + if unitID ~= nil then + if iT.featureIDs then + iT.instanceVBO:InstanceDataFromFeatureIDs(unitID, iT.unitIDattribID, thisInstanceIndex-1) + else + iT.instanceVBO:InstanceDataFromUnitIDs(unitID, iT.unitIDattribID, thisInstanceIndex-1) + end + end + else + iT.dirty = true + end + + if iT.debug then validateInstanceVBOTable(iT, 'push') end + return instanceID +end + +local function popElementInstance(iT, instanceID, noUpload) + -- iT: instanceTable created with makeInstanceTable + -- instanceID: an optional key given to the item, so it can be easily removed by reference, defaults to the last element of the buffer, but this will screw up the instanceIDtoIndex table if used in mixed keys mode + -- noUpload: prevent the VBO from being uploaded, if you feel like you are going to do a lot of ops and wish to manually upload when done instead + -- returns nil on failure, the the index of the element on success + if instanceID == nil then + Spring.Echo("Tried to remove element with nil instanceID from instanceTable " .. iT.myName) + return nil + end + + if iT.instanceIDtoIndex[instanceID] == nil then -- if key is instanceID yet does not exist, then warn and bail + Spring.Echo("Tried to remove element ",instanceID,'From instanceTable', iT.myName, 'but it does not exist in it') + Spring.Debug.TraceFullEcho(10,10,3, iT.myName) + return nil + end + if iT.usedElements == 0 then -- Dont remove the last element + Spring.Echo("Tried to remove element ",instanceID,'From instanceTable', iT.myName, 'but it should be empty') + return nil + end + + --Fetch the position of the element we want to remove from the 'middle' of the table + local oldElementIndex = iT.instanceIDtoIndex[instanceID] + iT.instanceIDtoIndex[instanceID] = nil -- clean these out + iT.indextoInstanceID[oldElementIndex] = nil + + -- get the index of the last element + local lastElementIndex = iT.usedElements + + -- if this one was already at the end of the queue, do nothing but decrement usedElements and clear mappings + if oldElementIndex == lastElementIndex then + --Spring.Echo("Removed end element of instanceTable", iT.myName) + iT.usedElements = iT.usedElements - 1 + -- if it had a related unitID stored, remove that: + if iT.indextoUnitID then iT.indextoUnitID[oldElementIndex] = nil end + + if iT.debugZombies then + if iT.zombies and iT.zombies[instanceID] then + --Spring.Echo("Good, we are killing a stupid zombie at the end", instanceID, iT.numZombies) + iT.zombies[instanceID] = nil + iT.numZombies = iT.numZombies - 1 + end + end + + else + local lastElementInstanceID = iT.indextoInstanceID[lastElementIndex] + if lastElementInstanceID == nil then -- + Spring.Echo("We somehow have a nil element at the back of the array, which is completely invalid, probably about to crash", iT.myName) + dbgt(iT.instanceIDtoIndex, "instanceIDtoIndex") + dbgt(iT.indextoInstanceID, "indextoInstanceID") + dbgt(iT.indextoUnitID, "indextoUnitID") + end + local iTStep = iT.instanceStep + local endOffset = (iT.usedElements - 1)*iTStep + + iT.instanceIDtoIndex[lastElementInstanceID] = oldElementIndex -- lastElementInstanceID was somehow nil here? + iT.indextoInstanceID[oldElementIndex] = lastElementInstanceID + iT.indextoInstanceID[lastElementIndex] = nil --- somehow this got forgotten? TODO for VBOIDtable + + local oldOffset = (oldElementIndex-1)*iTStep + local instanceData = iT.instanceData + for i = 1, iTStep do + instanceData[oldOffset + i ] = instanceData[endOffset + i] + end + --size_t LuaVBOImpl::Upload(const sol::stack_table& luaTblData, const sol::optional attribIdxOpt, const sol::optional elemOffsetOpt, const sol::optional luaStartIndexOpt, const sol::optional luaFinishIndexOpt) + --Spring.Echo("Removing instanceID",instanceID,"from iT at position", oldElementIndex, "shuffling back at", iT.usedElements,"endoffset=",endOffset,'oldOffset=',oldOffset) + if noUpload ~= true then + --Spring.Echo("Upload", oldElementIndex -1, oldOffset+1, oldOffset+iTStep) + iT.instanceVBO:Upload(iT.instanceData,nil,oldElementIndex-1,oldOffset +1,oldOffset + iTStep) + else + iT.dirty = true + end + -- Do the unitID shuffle if needed: + if iT.indextoUnitID then + --Spring.Echo("popElementInstance,unitID, iT.unitIDattribID, thisInstanceIndex",unitID, iT.unitIDattribID, oldElementIndex) + local popunitID = iT.indextoUnitID[lastElementIndex] + if popunitID == nil then + Spring.Echo("TODO: what the f is happening here?, how the f could we have popped a nil from the back of?", iT.myName) -- TODO TODO + end + + if iT.debugZombies then + local gf = Spring.GetGameFrame() + --Spring.Echo("Popping", instanceID) + if iT.lastpopgameframe == nil then + iT.lastpopgameframe = gf + iT.zombies = {} + iT.numZombies = 0 + else + if iT.lastpopgameframe ~= gf then -- New gameframe + iT.lastpopgameframe = gf + if iT.numZombies and iT.numZombies > 0 then -- WE HAVE ZOMBIES AAAAARGH + local s = "Warning: We have " .. tostring(iT.numZombies) .. " zombie units left over in " .. iT.myName + for zombie, gf in pairs(iT.zombies) do + s = s .. " " .. tostring(zombie) ..'/'..tostring(gf) + Spring.Echo("ZOMBIE instanceID", zombie, 'gf',gf) + --Spring.SendCommands({"pause 1"}) + Spring.Debug.TraceFullEcho(nil,nil,nil, iT.myName) + end + Spring.Echo(s) + iT.zombies = {} + iT.numZombies = 0 + end + else -- same gameframe + if iT.zombies[instanceID] then + --Spring.Echo("Good, we are killing a stupid zombie", gf, instanceID, iT.numZombies) + iT.zombies[instanceID] = nil + iT.numZombies = iT.numZombies - 1 + end + end + end + end + + iT.indextoUnitID[oldElementIndex] = popunitID + iT.indextoUnitID[lastElementIndex] = nil + + if (iT.featureIDs and Spring.ValidFeatureID(popunitID)) or Spring.ValidUnitID(popunitID) then + if noUpload ~= true then + if iT.featureIDs then + iT.instanceVBO:InstanceDataFromFeatureIDs(popunitID, iT.unitIDattribID, oldElementIndex-1) + else + iT.instanceVBO:InstanceDataFromUnitIDs(popunitID, iT.unitIDattribID, oldElementIndex-1) + end + end + else + if iT.debugZombies then + --Spring.Echo("Warning: Tried to pop back an invalid" .. ((iT.featureIDs and "featureID") or "unitID"), popunitID, "from", iT.myName, "while removing instance", instanceID, counttable(iT.instanceIDtoIndex), counttable(iT.indextoInstanceID), counttable(iT.indextoUnitID)) + --Spring.Debug.TraceFullEcho() + local gf = Spring.GetGameFrame() + if iT.lastpopgameframe == nil or iT.lastpopgameframe ~= gf then -- New gameframe + iT.lastpopgameframe = gf + iT.zombies = {} + iT.numZombies = 0 + end + if iT.zombies[lastElementInstanceID] == nil then + iT.zombies[lastElementInstanceID] = gf + iT.numZombies = iT.numZombies + 1 + end + end + end + end + iT.usedElements = iT.usedElements - 1 + end + + if iT.debug then validateInstanceVBOTable(iT,'pop') end + return oldElementIndex +end + +local function getElementInstanceData(iT, instanceID, cacheTable) + -- iT: instanceTable created with makeInstanceTable + -- instanceID: an optional key given to the item, so it can be easily removed by reference, defaults to the index of the instance in the buffer (1 based) + local instanceIndex = iT.instanceIDtoIndex[instanceID] + if instanceIndex == nil then + Spring.Echo("Tried to getElementInstanceData from",iT.myName,instanceID, "but it does not exist") + return nil + end + local iData = cacheTable or {} + local iTStep = iT.instanceStep + instanceIndex = (instanceIndex-1) * iTStep + local instanceData = iT.instanceData + for i = 1, iTStep do + iData[i] = instanceData[instanceIndex + i] + end + return iData +end + +local function uploadAllElements(iT) + -- upload all USED elements + if iT.usedElements == 0 then return end + + iT.instanceVBO:Upload(iT.instanceData,nil,0, 1, iT.usedElements * iT.instanceStep) + iT.dirty = false + if iT.indextoUnitID then + if iT.featureIDs then + iT.instanceVBO:InstanceDataFromFeatureIDs(iT.indextoUnitID, iT.unitIDattribID) + else + iT.instanceVBO:InstanceDataFromUnitIDs(iT.indextoUnitID, iT.unitIDattribID) + end + end +end + +local function uploadElementRange(iT, startElementIndex, endElementIndex) + iT.instanceVBO:Upload(iT.instanceData, -- The lua mirrored VBO data + nil, -- the attribute index, nil for all attributes + startElementIndex, -- vboOffset optional, , what ELEMENT offset of the VBO to start uploading into, 0 based + startElementIndex * iT.instanceStep + 1, -- luaStartIndex, default 1, what element of the lua array to start uploading from. 1 is the 1st element of a lua table. + endElementIndex * iT.instanceStep --] luaEndIndex, default #{array}, what element of the lua array to upload up to, inclusively + ) + if iT.indextoUnitID then + --we need to reslice the table + local unitIDRange = {} + local indextoUnitID = iT.indextoUnitID + for i = startElementIndex, endElementIndex do + unitIDRange[#unitIDRange + 1] = indextoUnitID[i] + end + if iT.featureIDs then + iT.instanceVBO:InstanceDataFromFeatureIDs(unitIDRange, iT.unitIDattribID, startElementIndex - 1) + else + iT.instanceVBO:InstanceDataFromUnitIDs(unitIDRange, iT.unitIDattribID, startElementIndex - 1) + end + end +end + +-- This function allows for order-preserving compacting of a list of instances based on these funcs. +-- It is designed for Decals GL4, where draw order matters a lot! +-- remove takes priority over keep +local function compactInstanceVBO(iT, removelist, keeplist) + local usedElements = iT.usedElements + if usedElements == 0 then return 0 end + local instanceStep = iT.instanceStep + local instanceData = iT.instanceData + local indextoInstanceID = iT.indextoInstanceID + local newindextoInstanceID = {} + local newinstanceIDtoIndex = {} + local newUsedElements = 0 + local numremoved = 0 + local removemode = (removelist ~= nil) and (keeplist == nil) + for index, instanceID in ipairs(indextoInstanceID) do + -- If its in keeplist, + if (removemode and (removelist[instanceID]== nil) ) or ((removemode == false) and keeplist[instanceID]) then + local instanceOffset = (index-1) * instanceStep + local newInstanceOffset = newUsedElements * instanceStep + for i = 1, instanceStep do + instanceData[newInstanceOffset + i] = instanceData[instanceOffset + i] + end + newUsedElements = newUsedElements + 1 + newindextoInstanceID[newUsedElements] = instanceID + newinstanceIDtoIndex[instanceID] = newUsedElements + else + numremoved = numremoved + 1 + end + end + if numremoved > 0 then + iT.dirty = true -- we set the flag to notify that CPU and GPU contents dont match! + iT.usedElements = newUsedElements + iT.instanceIDtoIndex = newinstanceIDtoIndex + iT.indextoInstanceID = newindextoInstanceID + end + return numremoved +end + +local function drawInstanceVBO(iT) + if iT.usedElements > 0 then + if iT.indexVBO then + iT.VAO:DrawElements(iT.primitiveType, iT.numVertices, 0, iT.usedElements,0) + else + iT.VAO:DrawArrays(iT.primitiveType, iT.numVertices, 0, iT.usedElements,0) + end + end +end + +local function countInvalidUnitIDs(iT) + local invalids = {} + for i, objectID in ipairs(iT.indextoUnitID) do + local isValidID = false + if iT.featureIDs then isValidID = Spring.ValidFeatureID(objectID) + else isValidID = Spring.ValidUnitID(objectID) end + if isValidID then + + else + invalids[#invalids + 1] = objectID + end + end + if #invalids > 0 then + Spring.Echo(#invalids, "invalid IDs found in ", iT.myName) + end + return invalids +end + + +--------- HELPERS FOR PRIMITIVES ------------------ + +local function makeCircleVBO(circleSegments, radius, startCenter, name) + -- Makes circle of radius in xy space + -- can be used in both GL.LINES and GL.TRIANGLE_FAN mode + -- Startcenter places a vertex in the center, this is nice for triangle fans, + -- but when drawing lines with this vbo, start at an offset of 1 + -- Fun note: its NOT faster to draw stenciled circles with this. + if not radius then radius = 1 end + circleSegments = circleSegments -1 -- for po2 buffers + local circleVBO = gl.GetVBO(GL.ARRAY_BUFFER,true) + if circleVBO == nil then return nil end + + local VBOLayout = { + {id = 0, name = "position", size = 4}, + } + + local VBOData = {} + if startCenter then + VBOData[#VBOData+1] = 0 -- X + VBOData[#VBOData+1] = 0 -- Y + VBOData[#VBOData+1] = 0 -- circumference [0-1] + VBOData[#VBOData+1] = radius + end + + for i = 0, circleSegments do -- this is +1 + VBOData[#VBOData+1] = math.sin(math.pi*2* i / circleSegments) * radius -- X + VBOData[#VBOData+1] = math.cos(math.pi*2* i / circleSegments) * radius-- Y + VBOData[#VBOData+1] = i / circleSegments -- circumference [0-1] + VBOData[#VBOData+1] = radius + end + + circleVBO:Define( + circleSegments + 1 + (startCenter and 1 or 0) , -- +1 for center point if startCenter is true + VBOLayout + ) + circleVBO:Upload(VBOData) + if gldebugannotations then + gl.ObjectLabel(GL_BUFFER, circleVBO:GetID(), name or "CircleVBO") + end + return circleVBO, #VBOData/4 +end + +local function makePlaneVBO(xsize, ysize, xresolution, yresolution, name) -- makes a plane from [-xsize to xsize] with xresolution subdivisions + if not xsize then xsize = 1 end + if not ysize then ysize = xsize end + if not xresolution then xresolution = 1 end + if not yresolution then yresolution = xresolution end + xresolution = math.floor(xresolution) + yresolution = math.floor(yresolution) + local planeVBO = gl.GetVBO(GL.ARRAY_BUFFER,false) + if planeVBO == nil then return nil end + + local VBOLayout = { + {id = 0, name = "xyworld_xyfract", size = 2}, + } + + local VBOData = {} + + for x = 0, xresolution do -- this is +1 + for y = 0, yresolution do + VBOData[#VBOData+1] = xsize * ((x / xresolution) -0.5 ) *2 + VBOData[#VBOData+1] = ysize * ((y / yresolution) -0.5 ) * 2 + end + end + + planeVBO:Define( + (xresolution + 1) * (yresolution + 1) , + VBOLayout + ) + planeVBO:Upload(VBOData) + + if gldebugannotations then + gl.ObjectLabel(GL_BUFFER, planeVBO:GetID(), name or "PlaneVBO") + end + + --Spring.Echo("PlaneVBOData up:",#VBOData, "Down", #planeVBO:Download()) + return planeVBO, #VBOData/2 +end + +local function makePlaneIndexVBO(xresolution, yresolution, cutcircle, name) + xresolution = math.floor(xresolution) + if not yresolution then yresolution = xresolution end + local planeIndexVBO = gl.GetVBO(GL.ELEMENT_ARRAY_BUFFER,false) + if planeIndexVBO == nil then return nil end + + local function xyinrad(lx, ly) + local px = (lx / xresolution) * 2 - 1 + local py = (ly / yresolution) * 2 - 1 + return (px*px + py*py) <= 1 + end + + local IndexVBOData = {} + local qindex = 0 + local colsize = yresolution + 1 + for x = 0, xresolution-1 do -- this is +1 + for y = 0, yresolution-1 do + --this is only 20% optimization + if cutcircle == nil or (xyinrad(x,y) or xyinrad(x + 1,y) or xyinrad(x,y + 1 )) then + -- top left one + IndexVBOData[#IndexVBOData + 1] = qindex + IndexVBOData[#IndexVBOData + 1] = qindex +1 + IndexVBOData[#IndexVBOData + 1] = qindex + colsize + end + + if cutcircle == nil or (xyinrad(x+1,y+1) or xyinrad(x + 1,y) or xyinrad(x,y + 1 )) then + -- bottom right one? + IndexVBOData[#IndexVBOData + 1] = qindex +1 + IndexVBOData[#IndexVBOData + 1] = qindex + colsize + 1 + IndexVBOData[#IndexVBOData + 1] = qindex + colsize + end + qindex = qindex + 1 + + end + qindex = qindex + 1 + end + planeIndexVBO:Define( + # IndexVBOData + ) + planeIndexVBO:Upload(IndexVBOData) + + if gldebugannotations then + gl.ObjectLabel(GL_BUFFER, planeIndexVBO:GetID(), name or "planeIndexVBO") + end + --Spring.Echo("PlaneIndexVBO up:",#IndexVBOData, "Down", #planeIndexVBO:Download()) + return planeIndexVBO, IndexVBOData +end + +local function makePointVBO(numPoints, randomFactor, name) + -- makes points with xyzw + -- can be used in both GL.LINES and GL.TRIANGLE_FAN mode + numPoints = numPoints or 1 + randomFactor = randomFactor or 0 + local pointVBO = gl.GetVBO(GL.ARRAY_BUFFER,true) + if pointVBO == nil then return nil end + + local VBOLayout = { + {id = 0, name = "position_w", size = 4}, + } + + local VBOData = {} + + for i = 1, numPoints do -- + VBOData[#VBOData+1] = randomFactor * math.random()-- X + VBOData[#VBOData+1] = randomFactor * math.random()-- Y + VBOData[#VBOData+1] = randomFactor * math.random()---Z + VBOData[#VBOData+1] = i/numPoints -- index for lolz? + end + + pointVBO:Define( + numPoints, + VBOLayout + ) + pointVBO:Upload(VBOData) + + if gldebugannotations then + gl.ObjectLabel(GL_BUFFER, pointVBO:GetID(), name or "pointVBO") + end + return pointVBO, numPoints +end + +local function makeRectVBO(minX,minY, maxX, maxY, minU, minV, maxU, maxV, name) + if minX == nil then + minX, minY, maxX, maxY, minU, minV, maxU, maxV = 0,0,1,1,0,0,1,1 + end + -- makes points with xyzw + -- can be used in both GL.LINES and GL.TRIANGLE_FAN mode + local rectVBO = gl.GetVBO(GL.ARRAY_BUFFER,false) + if rectVBO == nil then return nil end + + local VBOLayout = { + {id = 0, name = "position_xy_uv", size = 4}, + } + + local VBOData = { + --bl + minX,minY, minU, minV, --bl + minX,maxY, minU, maxV, --tr + maxX,maxY, maxU, maxV, --tr + maxX,maxY, maxU, maxV, --tr + maxX,minY, maxU, minV, --br + minX,minY, minU, minV, --bl + } + + rectVBO:Define( + 6, + VBOLayout + ) + rectVBO:Upload(VBOData) + + if gldebugannotations then + gl.ObjectLabel(GL_BUFFER, rectVBO:GetID(), name or "rectVBO") + end + return rectVBO, 6 +end + +local function makeRectIndexVBO(name) + local rectIndexVBO = gl.GetVBO(GL.ELEMENT_ARRAY_BUFFER,false) + if rectIndexVBO == nil then return nil end + + rectIndexVBO:Define( + 6 + ) + rectIndexVBO:Upload({0,1,2,3,4,5}) + if gldebugannotations then + gl.ObjectLabel(GL_BUFFER, rectIndexVBO:GetID(), name or "rectIndexVBO") + end + return rectIndexVBO,6 +end + + + +local function makeConeVBO(numSegments, height, radius, name) + -- make a cone that points up, (y = height), with radius specified + -- returns the VBO object, and the number of elements in it (usually == numvertices) + -- needs GL.TRIANGLES + if not height then height = 1 end + if not radius then radius = 1 end + local coneVBO = gl.GetVBO(GL.ARRAY_BUFFER,true) + if coneVBO == nil then return nil end + + local VBOData = {} + + for i = 1, numSegments do + -- center vertex + VBOData[#VBOData+1] = 0 + VBOData[#VBOData+1] = 0 + VBOData[#VBOData+1] = 0 + VBOData[#VBOData+1] = (i - 1) / numSegments + + --- first cone flat + VBOData[#VBOData+1] = math.sin(math.pi*2* (i - 1) / numSegments) * radius -- X + VBOData[#VBOData+1] = 0 + VBOData[#VBOData+1] = -1* math.cos(math.pi*2* (i - 1) / numSegments) * radius-- Y + VBOData[#VBOData+1] = (i - 1) / numSegments + + --- second cone flat + VBOData[#VBOData+1] = math.sin(math.pi*2* (i - 0) / numSegments) * radius-- X + VBOData[#VBOData+1] = 0 + VBOData[#VBOData+1] = -1* math.cos(math.pi*2* (i - 0) / numSegments) * radius -- Y + VBOData[#VBOData+1] =(i - 0) / numSegments + + -- top vertex + VBOData[#VBOData+1] = 0 + VBOData[#VBOData+1] = height + VBOData[#VBOData+1] = 0 + VBOData[#VBOData+1] = (i - 1) / numSegments + + --- first cone flat + VBOData[#VBOData+1] = math.sin(math.pi*2* (i - 0) / numSegments) * radius -- X + VBOData[#VBOData+1] = 0 + VBOData[#VBOData+1] = -1*math.cos(math.pi*2* (i - 0) / numSegments) * radius -- Y + VBOData[#VBOData+1] =(i - 0) / numSegments + + --- second cone flat + VBOData[#VBOData+1] = math.sin(math.pi*2* (i - 1) / numSegments) * radius -- X + VBOData[#VBOData+1] = 0 + VBOData[#VBOData+1] = -1*math.cos(math.pi*2* (i - 1) / numSegments) * radius -- Y + VBOData[#VBOData+1] =(i - 1) / numSegments + end + + + coneVBO:Define(#VBOData/4, {{id = 0, name = "localpos_progress", size = 4}}) + coneVBO:Upload(VBOData) + + if gldebugannotations then + gl.ObjectLabel(GL_BUFFER, coneVBO:GetID(), name or "coneVBO") + end + + return coneVBO, #VBOData/4 +end + + + +local function makeCylinderVBO(numSegments, height, radius, hastop, hasbottom, name) + -- make a cylinder that points up, (y = height), with radius specified + -- returns the VBO object, and the number of elements in it (usually == numvertices) + -- needs GL.TRIANGLES + if not height then height = 1 end + if not radius then radius = 1 end + local cylinderVBO = gl.GetVBO(GL.ARRAY_BUFFER,true) + if cylinderVBO == nil then return nil end + + local VBOData = {} + + for i = 1, numSegments do + if hasbottom then + -- center vertex + VBOData[#VBOData+1] = 0 + VBOData[#VBOData+1] = -1* height + VBOData[#VBOData+1] = 0 + VBOData[#VBOData+1] = (i - 1) / numSegments + + --- first cone flat + VBOData[#VBOData+1] = math.sin(math.pi*2* (i - 1) / numSegments) * radius -- X + VBOData[#VBOData+1] = -1* height + VBOData[#VBOData+1] = -1* math.cos(math.pi*2* (i - 1) / numSegments) * radius-- Y + VBOData[#VBOData+1] = (i - 1) / numSegments + + --- second cone flat + VBOData[#VBOData+1] = math.sin(math.pi*2* (i - 0) / numSegments) * radius-- X + VBOData[#VBOData+1] = -1* height + VBOData[#VBOData+1] = -1* math.cos(math.pi*2* (i - 0) / numSegments) * radius -- Y + VBOData[#VBOData+1] =(i - 0) / numSegments + end + + + --- first cone flat + VBOData[#VBOData+1] = math.sin(math.pi*2* (i - 0) / numSegments) * radius -- X + VBOData[#VBOData+1] = height + VBOData[#VBOData+1] = -1*math.cos(math.pi*2* (i - 0) / numSegments) * radius -- Y + VBOData[#VBOData+1] =(i - 0) / numSegments + + --- second cone flat + VBOData[#VBOData+1] = math.sin(math.pi*2* (i - 1) / numSegments) * radius -- X + VBOData[#VBOData+1] = height + VBOData[#VBOData+1] = -1*math.cos(math.pi*2* (i - 1) / numSegments) * radius -- Y + VBOData[#VBOData+1] =(i - 1) / numSegments + + + + --- first cone flat + VBOData[#VBOData+1] = math.sin(math.pi*2* (i - 0) / numSegments) * radius -- X + VBOData[#VBOData+1] = -1 * height + VBOData[#VBOData+1] = -1*math.cos(math.pi*2* (i - 0) / numSegments) * radius -- Y + VBOData[#VBOData+1] =(i - 0) / numSegments + + --- second cone flat + VBOData[#VBOData+1] = math.sin(math.pi*2* (i - 1) / numSegments) * radius -- X + VBOData[#VBOData+1] = height + VBOData[#VBOData+1] = -1*math.cos(math.pi*2* (i - 1) / numSegments) * radius -- Y + VBOData[#VBOData+1] =(i - 1) / numSegments + + + --- first cone flat + VBOData[#VBOData+1] = math.sin(math.pi*2* (i - 0) / numSegments) * radius -- X + VBOData[#VBOData+1] = -1 * height + VBOData[#VBOData+1] = -1*math.cos(math.pi*2* (i - 0) / numSegments) * radius -- Y + VBOData[#VBOData+1] =(i - 0) / numSegments + + + --- second cone flat + VBOData[#VBOData+1] = math.sin(math.pi*2* (i - 1) / numSegments) * radius -- X + VBOData[#VBOData+1] = -1 * height + VBOData[#VBOData+1] = -1*math.cos(math.pi*2* (i - 1) / numSegments) * radius -- Y + VBOData[#VBOData+1] =(i - 1) / numSegments + + + + if hastop then + -- center vertex + VBOData[#VBOData+1] = 0 + VBOData[#VBOData+1] = height + VBOData[#VBOData+1] = 0 + VBOData[#VBOData+1] = (i - 1) / numSegments + + --- first cone flat + VBOData[#VBOData+1] = math.sin(math.pi*2* (i - 1) / numSegments) * radius -- X + VBOData[#VBOData+1] = height + VBOData[#VBOData+1] = -1* math.cos(math.pi*2* (i - 1) / numSegments) * radius-- Y + VBOData[#VBOData+1] = (i - 1) / numSegments + + --- second cone flat + VBOData[#VBOData+1] = math.sin(math.pi*2* (i - 0) / numSegments) * radius-- X + VBOData[#VBOData+1] = height + VBOData[#VBOData+1] = -1* math.cos(math.pi*2* (i - 0) / numSegments) * radius -- Y + VBOData[#VBOData+1] =(i - 0) / numSegments + end + end + + + cylinderVBO:Define(#VBOData/4, {{id = 0, name = "localpos_progress", size = 4}}) + cylinderVBO:Upload(VBOData) + + if gldebugannotations then + gl.ObjectLabel(GL_BUFFER, cylinderVBO:GetID(), name or "cylinderVBO") + end + + return cylinderVBO, #VBOData/4 +end + + + +local function makeBoxVBO(minX, minY, minZ, maxX, maxY, maxZ, name) -- make a box + -- needs GL.TRIANGLES + local boxVBO = gl.GetVBO(GL.ARRAY_BUFFER,true) + if boxVBO == nil then return nil end + + local VBOData = { + minX,minY,minZ,0 + ,minX,minY,maxZ,0 + ,minX,maxY,maxZ,0 + ,maxX,maxY,minZ,0 + ,minX,minY,minZ,0 + ,minX,maxY,minZ,0 + ,maxX,minY,maxZ,0 + ,minX,minY,minZ,0 + ,maxX,minY,minZ,0 + ,maxX,maxY,minZ,0 + ,maxX,minY,minZ,0 + ,minX,minY,minZ,0 + ,minX,minY,minZ,0 + ,minX,maxY,maxZ,0 + ,minX,maxY,minZ,0 + ,maxX,minY,maxZ,0 + ,minX,minY,maxZ,0 + ,minX,minY,minZ,0 + ,minX,maxY,maxZ,0 + ,minX,minY,maxZ,0 + ,maxX,minY,maxZ,0 + ,maxX,maxY,maxZ,0 + ,maxX,minY,minZ,0 + ,maxX,maxY,minZ,0 + ,maxX,minY,minZ,0 + ,maxX,maxY,maxZ,0 + ,maxX,minY,maxZ,0 + ,maxX,maxY,maxZ,0 + ,maxX,maxY,minZ,0 + ,minX,maxY,minZ,0 + ,maxX,maxY,maxZ,0 + ,minX,maxY,minZ,0 + ,minX,maxY,maxZ,0 + ,maxX,maxY,maxZ,0 + ,minX,maxY,maxZ,0 + ,maxX,minY,maxZ,0 + } + boxVBO:Define(#VBOData/4, {{id = 0, name = "localpos_progress", size = 4}}) + boxVBO:Upload(VBOData) + + if gldebugannotations then + gl.ObjectLabel(GL_BUFFER, boxVBO:GetID(), name or "boxVBO") + end + + return boxVBO, #VBOData/4 +end + + + +---Generate a sphere vertex VBO and the corresponding indexVBO +---The sphere is oriented in the Z direction +---Layout: +---{id = 0, name = "position", size = 4}, -- cake slices along Z, w is sector angle. +---{id = 1, name = "normals", size = 3}, -- normal vector +---{id = 2, name = "uvs", size = 2}, -- UV vector, where x goes around the belly and y goes along Z +---@param sectorCount number is the number of orange slices around the belly in XY +---@param stackCount number how many horizontal slices along Z, usually less than sectorcount +---@param radius number how many elmos in radius, default 1 +local function makeSphereVBO(sectorCount, stackCount, radius, name) -- http://www.songho.ca/opengl/gl_sphere.html + + + local sphereVBO = gl.GetVBO(GL.ARRAY_BUFFER,true) + if sphereVBO == nil then return nil end + local vertVBOLayout = { + {id = 0, name = "position", size = 4}, + {id = 1, name = "normals", size = 3}, + {id = 2, name = "uvs", size = 2}, + } + + local VBOData = {} + radius = radius or 1 + local x, y, z, xy; -- vertex position + local nx, ny, nz + local lengthInv = 1.0 / radius; -- vertex normal + local s, t; -- vertex texCoord + + local sectorStep = 2 * math.pi / sectorCount; + local stackStep = math.pi / stackCount; + local sectorAngle, stackAngle; + + for i = 0, stackCount do + + stackAngle = math.pi / 2 - i * stackStep; -- starting from pi/2 to -pi/2 + xy = radius * math.cos(stackAngle); -- r * cos(u) + z = radius * math.sin(stackAngle); -- r * sin(u) + + -- add (sectorCount+1) vertices per stack + -- the first and last vertices have same position and normal, but different tex coords + for j = 0, sectorCount do -- for (int j = 0; j <= sectorCount; ++j) + + sectorAngle = j * sectorStep; -- starting from 0 to 2pi + + -- vertex position (x, y, z) + x = xy * math.cos(sectorAngle); -- r * cos(u) * cos(v) + y = xy * math.sin(sectorAngle); -- r * cos(u) * sin(v) + VBOData[#VBOData + 1] = x; + VBOData[#VBOData + 1] = y; + VBOData[#VBOData + 1] = z; + VBOData[#VBOData + 1] = sectorAngle; + --Spring.Echo(x,y,z) + -- normalized vertex normal (nx, ny, nz) + nx = x * lengthInv; + ny = y * lengthInv; + nz = z * lengthInv; + + + VBOData[#VBOData + 1] = nx; + VBOData[#VBOData + 1] = ny; + VBOData[#VBOData + 1] = nz; + + -- vertex tex coord (s, t) range between [0, 1] + s = j / sectorCount; + t = i / stackCount; + + VBOData[#VBOData + 1] = s; + VBOData[#VBOData + 1] = t; + end + end + sphereVBO:Define(#VBOData/9, vertVBOLayout) + sphereVBO:Upload(VBOData) + + if gldebugannotations then + gl.ObjectLabel(GL_BUFFER, sphereVBO:GetID(), name or "sphereVBO") + end + + local numVerts = #VBOData/9 + + local sphereIndexVBO = gl.GetVBO(GL.ELEMENT_ARRAY_BUFFER,false) + VBOData = {} + + -- generate CCW index list of sphere triangles + -- k1--k1+1 + -- | / | + -- | / | + -- k2--k2+1 + local k1, k2 + for i = 0, stackCount-1 do -- for(int i = 0; i < stackCount; ++i) + + k1 = i * (sectorCount + 1) -- beginning of current stack + k2 = k1 + sectorCount + 1 -- beginning of next stack + + for j = 0, sectorCount-1 do --for(int j = 0; j < sectorCount; ++j, ++k1, ++k2) + -- Spring.Echo('indices', k1, k2) + -- 2 triangles per sector excluding first and last stacks + -- k1 => k2 => k1+1 + if i ~= 0 then + + VBOData[#VBOData + 1] = k1 + VBOData[#VBOData + 1] = k2 + VBOData[#VBOData + 1] = k1 + 1 + end + + -- k1+1 => k2 => k2+1 + if i ~= (stackCount-1) then + + VBOData[#VBOData + 1] = k1 + 1 + VBOData[#VBOData + 1] = k2 + VBOData[#VBOData + 1] = k2 + 1 + + end + + k1 = k1 + 1 + k2 = k2 + 1 + end + end + + + sphereIndexVBO:Define(#VBOData) + sphereIndexVBO:Upload(VBOData) + + if gldebugannotations then + gl.ObjectLabel(GL_BUFFER, sphereIndexVBO:GetID(), name or "sphereIndexVBO") + end + + return sphereVBO, numVerts, sphereIndexVBO, #VBOData +end + + +local function MakeTexRectVAO(minX,minY, maxX, maxY, minU, minV, maxU, maxV, name) + -- Draw with myGL4TexRectVAO:DrawArrays(GL.TRIANGLES) + minX,minY,maxX,maxY,minU,minV,maxU,maxV = minX or -1,minY or -1,maxX or 1, maxY or 1, minU or 0, minV or 0, maxU or 1, maxV or 1 + + local myGL4TexRectVAO + local rectVBO = gl.GetVBO(GL.ARRAY_BUFFER,false) + if rectVBO == nil then return nil end + + --rectVBO:Define( 6, {{id = 0, name = "position_xy_uv", size = 8}}) + local z = 0.5 + local w = 1 + rectVBO:Define( 6, {{id = 0, name = "pos", size = 4}}) + rectVBO:Upload({ + + minX,minY, minU, minV, --bl + maxX,maxY, maxU, maxV, --tr + minX,maxY, minU, maxV, --tl + maxX,maxY, maxU, maxV, --tr + minX,minY, minU, minV, --bl + maxX,minY, maxU, minV, --br + }) + + + if gldebugannotations then + gl.ObjectLabel(GL_BUFFER, rectVBO:GetID(), name or "rectVBO") + end + + myGL4TexRectVAO = gl.GetVAO() + if myGL4TexRectVAO == nil then return nil end + myGL4TexRectVAO:AttachVertexBuffer(rectVBO) + return myGL4TexRectVAO +end + +return { + makeInstanceVBOTable = makeInstanceVBOTable, + clearInstanceTable = clearInstanceTable, + makeVAOandAttach = makeVAOandAttach, + locateInvalidUnits = locateInvalidUnits, + pushElementInstance = pushElementInstance, + popElementInstance = popElementInstance, + getElementInstanceData = getElementInstanceData, + uploadAllElements = uploadAllElements, + uploadElementRange = uploadElementRange, + compactInstanceVBO = compactInstanceVBO, + drawInstanceVBO = drawInstanceVBO, + makeCircleVBO = makeCircleVBO, + makePlaneVBO = makePlaneVBO, + makePlaneIndexVBO = makePlaneIndexVBO, + makePointVBO = makePointVBO, + makeRectVBO = makeRectVBO, + makeRectIndexVBO = makeRectIndexVBO, + makeConeVBO = makeConeVBO, + makeCylinderVBO = makeCylinderVBO, + makeBoxVBO = makeBoxVBO, + makeSphereVBO = makeSphereVBO, + MakeTexRectVAO = MakeTexRectVAO, +} + +end)() +local original=(function()local gadget={} +local gadget = gadget ---@type Gadget + +function gadget:GetInfo() + return { + name = "Raptor Scum GL4", + desc = "Draws scum with global overlap texturing", + author = "Beherith", + date = "2022.04.20", + license = "GNU GPL v2", + layer = -1, + enabled = true, + } +end + +-- TODO: + -- maybe even use parallax + -- add a moving distortion texture + -- also write to deferred buffers maybe? + -- fix stencil testing + + +if gadgetHandler:IsSyncedCode() then + local pveTeamID = Spring.Utilities.GetScavTeamID() or Spring.Utilities.GetRaptorTeamID() + + local scumSpawnerIDs = {} + + local scums = {} -- {posx = 123, posz = 123, radius = 123, spawnframe = 0, growthrate = 1.0} -- in elmos per sec + local numscums = 0 + local scumBins = {} -- a table keyed with (posx / 1024) + 1024 + (posz/1024), values are tables of scumindexes that can overlap that bin + local scumRemoveQueue = {} -- maps gameframes to list of scums that will be removed + local debugmode = false + + local sqrt = math.sqrt + local floor = math.floor + local max = math.max + local min = math.min + local clamp = math.clamp + local spGetGroundHeight = Spring.GetGroundHeight + local spGetGameFrame = Spring.GetGameFrame + local mapSizeX = Game.mapSizeX + local mapSizeZ = Game.mapSizeZ + local initialized = false + local boundary = 128 -- how many elmos closer to the center of the scum than the actual edge of the scum the unit must be to be considered on the scum + + local function GetScumCurrentRadius(scum, gf) + gf = gf or spGetGameFrame() + if scum.growthrate > 0 then + return clamp((gf - scum.spawnframe) * scum.growthrate, 0, scum.radius) + else + return clamp(scum.radius - (gf - scum.spawnframe) *(-1.0 * scum.growthrate), 0, scum.radius) + end + end + + local function GetMapSquareKey(posx, posz) + if posx < 0 or posz < 0 or posx > mapSizeX or posz > mapSizeZ then return nil end + return (floor(posx*0.0009765625) * 1024 + floor(posz* 0.0009765625)) + end + + for x= 0, math.ceil(mapSizeX/1024) do + for z = 0, math.ceil(mapSizeZ/1024) do + scumBins[x*1024+z] = {} + end + end + + function gadget:Initialize() + local scumGenerators = { + raptor_hive = {radius = 800, growthrate = 0.8}, + raptor_turret_basic_t3_v1 = {radius = 600, growthrate = 0.4}, + raptor_turret_basic_t2_v1 = {radius = 400, growthrate = 0.2}, + raptor_turret_basic_t4_v1 = {radius = 800, growthrate = 0.8}, + raptor_turret_basic_t4_v2 = {radius = 800, growthrate = 0.8}, + raptor_turret_antiair_t3_v1 = {radius = 600, growthrate = 0.4}, + raptor_turret_antiair_t2_v1 = {radius = 400, growthrate = 0.2}, + raptor_turret_antiair_t4_v1 = {radius = 800, growthrate = 0.8}, + raptor_turret_acid_t3_v1 = {radius = 600, growthrate = 0.4}, + raptor_turret_acid_t2_v1 = {radius = 400, growthrate = 0.2}, + raptor_turret_acid_t4_v1 = {radius = 800, growthrate = 0.8}, + raptor_turret_acid_t4_v2 = {radius = 800, growthrate = 0.8}, + raptor_turret_emp_t3_v1 = {radius = 600, growthrate = 0.4}, + raptor_turret_emp_t2_v1 = {radius = 400, growthrate = 0.2}, + raptor_turret_emp_t4_v1 = {radius = 800, growthrate = 0.8}, + raptor_turret_emp_t4_v2 = {radius = 800, growthrate = 0.8}, + raptor_turret_brood_t3_v1 = {radius = 600, growthrate = 0.4}, + raptor_turret_brood_t2_v1 = {radius = 400, growthrate = 0.2}, + raptor_turret_brood_t4_v1 = {radius = 800, growthrate = 0.8}, + raptor_turret_brood_t4_v2 = {radius = 800, growthrate = 0.8}, + raptor_turret_antinuke_t3_v1 = {radius = 600, growthrate = 0.4}, + raptor_turret_antinuke_t2_v1 = {radius = 400, growthrate = 0.2}, + raptor_turret_meteor_t4_v1 = {radius = 800, growthrate = 0.8}, + + scavbeacon_t1_scav = {radius = 600, growthrate = 0.74}, + scavbeacon_t2_scav = {radius = 800, growthrate = 0.88}, + scavbeacon_t3_scav = {radius = 1000, growthrate = 1}, + scavbeacon_t4_scav = {radius = 1200, growthrate = 1.36}, + } + for unitDefName, scumParams in pairs(scumGenerators) do + if UnitDefNames[unitDefName] then + scumSpawnerIDs[UnitDefNames[unitDefName].id] = scumParams + end + end + local scumSpawnerExclusions = { + lootdroppod_gold_scav = true, + lootdroppod_printer_scav = true, + meteor_scav = true, + mission_command_tower_scav = true, + nuketest_scav = true, + nuketestcor_scav = true, + nuketestorg_scav = true, + scavempspawner_scav = true, + scavengerdroppod_scav = true, + scavengerdroppodfriendly_scav = true, + scavtacnukespawner_scav = true + } + for unitDefID, unitDef in pairs(UnitDefs) do + if unitDef.customParams.isscavenger and not scumSpawnerExclusions[unitDef.name] and not unitDef.canMove and not string.find(unitDef.name, "lootbox") and not scumSpawnerIDs[unitDefID] and not unitDef.customParams.objectify and not unitDef.canCloak then + if unitDef.xsize and unitDef.zsize then + scumSpawnerIDs[unitDefID] = {radius = math.min(600, math.max(150, unitDef.xsize*unitDef.zsize*10)), growthrate = 1.2} + else + scumSpawnerIDs[unitDefID] = {radius = math.random(150,400), growthrate = 1.2} + end + end + end + + for x = 0, math.ceil(mapSizeX/1024) do + for z = 0, math.ceil(mapSizeZ/1024) do + scumBins[x*1024+z] = {} + end + end + end + + + -- This checks wether the unit is under any scum + local function IsPosInScum(unitx,unity, unitz) + -- out of bounds check, no scum outside of map bounds + if unitx < 0 or unitz < 0 or unitx > mapSizeX or unitz > mapSizeZ then return nil end + -- underwater scum doesnt count for hovers, ships + unity = unity or 1 + if unity > -1 and spGetGroundHeight(unitx, unitz) < 0 then return nil end + + -- Empty bins also return + local scumBinID = GetMapSquareKey(unitx, unitz) + if scumBinID == nil or scumBins[scumBinID] == nil then return nil end + local gf = spGetGameFrame() + + for scumID, scum in pairs(scumBins[scumBinID]) do + local dx = (unitx - scum.posx) + local dz = (unitz - scum.posz) + local sqrdistance = (dx*dx + dz*dz) + local scumradius = scum.radius + if sqrdistance < (scumradius * scumradius) then + local currentscumradius = GetScumCurrentRadius(scum, gf) + --Spring.Echo("testing ScumID", scumID, sqrt(sqrdistance), scumradius, currentscumradius) + if currentscumradius - sqrt(sqrdistance) > boundary then + return scumID + end + end + end + return nil + end + + GG.IsPosInRaptorScum = IsPosInScum --(x,y,z) + + local function GetRandomScumID(startID) + if numscums < 1 then return end + local scumID = startID or next(scums) -- so we can start iterating from anywhere + if not scumID then return end -- return nil on no scums + local randomindex = math.random(1, numscums) + for i = 1, randomindex do + scumID = next(scums) + end + return scumID + end + + GG.GetRandomScumID = GetRandomScumID -- Returns nil or scumID + + local function GetRandomPositionInScum() + local scumID = GetRandomScumID() + if not scumID then return end + local px, pz + + local scum = scums[scumID] + local radius = GetScumCurrentRadius(scum) + local attempts = 0 + repeat + attempts = attempts + 1 + local r = radius * math.sqrt(math.random()) + local theta = math.random() * 2 * math.pi + local x = scum.posx + r * math.cos(theta) + local z = scum.posz + r * math.sin(theta) + if x > 128 and x < Game.mapSizeX - 128 and z > 128 and z < Game.mapSizeZ - 128 and r > 32 then + px,pz = x,z + end + until (px and pz) and (attempts < 10) + return px,pz + end + + GG.GetRandomPositionInScum = GetRandomPositionInScum -- Returns nil or (X, Z) + + local function UpdateBins(scumID, removeScum) + local scumTable = scums[scumID] + if scumTable == nil then + --Spring.Echo("Tried to update a scumID",scumID,"that no longer exists because it probably shrank to death, remove = ", removeScum) + return nil + end + + local posx = scumTable.posx + local posz = scumTable.posz + local radius = scumTable.radius + + if removeScum then + scumTable = nil + scums[scumID] = nil + end + + local step = radius / 3 + for dx = -radius, radius, step do + for dz = -radius, radius, step do + local binID = GetMapSquareKey(posx + dx, posz + dz) + if binID then + scumBins[binID][scumID] = scumTable + --Spring.Echo("scum added to bin! scumID:", scumID, "binID:", binID) + end + end + end + end + + local function AddOrUpdateScum(posx, posy, posz, radius, growthrate, scumID) + if debugmode then Spring.Echo("AddOrUpdateScum",posx, posy, posz, radius, growthrate, scumID) end + -- if scumID is supplied, we are updateing an existing scum instance! + + local gf = spGetGameFrame() + local deathtime + local scum + -- thus we need to make a new scum, and register it in our scumBins + if scums[scumID] == nil then + posy = posy or Spring.GetGroundHeight(posx, posz) + scum = {posx = posx, posz = posz, radius = radius, spawnframe = gf, growthrate = growthrate, scumID = scumID} + scums[scumID] = scum + UpdateBins(scumID) + numscums = numscums + 1 + else-- a scumID is supplied, meaning we just update an existing instance + scum = scums[scumID] + -- well then, seems we have to do this after all, when we update a scum, we need to check how long its been alive + -- this is the nastiest garbage ive ever done + local currentradius = GetScumCurrentRadius(scum, gf) + + -- always remove from removal queue on update + for _, removescums in pairs(scumRemoveQueue) do + removescums[scumID] = nil + end + + if growthrate > 0 then + scum.spawnframe = gf - ( currentradius/growthrate) + -- remove it from the death queue, no matter where it is, cause its 'growing' + else + scum.spawnframe = gf - ((scum.radius - currentradius)/ (-1 * growthrate) ) + deathtime = math.floor( gf + (currentradius/(-1 * growthrate))) + end + scum.growthrate = growthrate + + if debugmode then Spring.Echo("Updated scum", scumID, "it was", currentradius,"/", scum.radius, "sized, growing at", growthrate) end + end + --Spring.Echo(scumID, growthrate, radius, gf) + + if scum.growthrate < 0 then + if debugmode then Spring.Echo("Removal of scum ID", scumID,"Scheduled for ", deathtime - gf , "from now" ) end + if scumRemoveQueue[deathtime] == nil then + scumRemoveQueue[deathtime] = {} + end + scumRemoveQueue[deathtime][scumID] = true + end + + return scumID + end + + function gadget:UnitCreated(unitID, unitDefID, unitTeam) + if scumSpawnerIDs[unitDefID] and (debugmode or (unitTeam and unitTeam == pveTeamID)) then + local px, py, pz = Spring.GetUnitPosition(unitID) + local gf = Spring.GetGameFrame() + + local scumID = AddOrUpdateScum(px, py, pz, scumSpawnerIDs[unitDefID].radius, scumSpawnerIDs[unitDefID].growthrate, unitID) + local scum = scums[scumID] + SendToUnsynced("ScumCreated",scum.posx, scum.posz, scum.radius, scum.growthrate, gf, scumID) + --Spring.Echo("Scum Created Synced") + end + end + + + function gadget:UnitDestroyed(unitID, unitDefID, unitTeam, attackerID, attackerDefID, attackerTeam, weaponDefID) + if scumSpawnerIDs[unitDefID] and scums[unitID] then + AddOrUpdateScum(nil,nil,nil,nil, -10*math.abs(scums[unitID].growthrate), unitID) + SendToUnsynced("ScumRemoved", unitID) + end + end + + function gadget:GameFrame(n) + if not initialized then + for i, unitID in ipairs(Spring.GetAllUnits()) do + gadget:UnitCreated(unitID, Spring.GetUnitDefID(unitID)) + end + initialized = true + end + if scumRemoveQueue[n] then + for scumID, _ in pairs(scumRemoveQueue[n]) do + if scums[scumID] then + numscums = numscums - 1 + end + UpdateBins(scumID, true) + end + scumRemoveQueue[n] = nil + end + end + + + +elseif not Spring.Utilities.Gametype.IsScavengers() then -- UNSYNCED + + + + local textureresolution = "low" -- low or high + local textures = { + low = { + texcolorheight = "LuaUI/images/raptor_scum/alien_guts_colorheight.dds", + texnormalspec = "LuaUI/images/raptor_scum/alien_guts_normalspec.dds", + texdistortion = "LuaUI/images/lavadistortion.dds" + }, + high = { + texcolorheight = "LuaUI/images/raptor_scum/alien_guts_colorheight.dds", + texnormalspec = "LuaUI/images/raptor_scum/alien_guts_normalspec_u8888.dds", + texdistortion = "LuaUI/images/lavadistortion.png" + }, + } + + + local resolution = 32 + local gameFrame = -1 + + local scumVBO = nil + local scumShader = nil + local debugmode = false + local headless = false + local drawScum = true + local optimizeoverlaps = true + + local glTexture = gl.Texture + local glCulling = gl.Culling + local GL_LEQUAL = GL.LEQUAL + local glStencilFunc = gl.StencilFunc + local glStencilOp = gl.StencilOp + local glStencilMask = gl.StencilMask + local glDepthTest = gl.DepthTest + local glClear = gl.Clear + local GL_ALWAYS = GL.ALWAYS + local GL_NOTEQUAL = GL.NOTEQUAL + local GL_KEEP = 0x1E00 --GL.KEEP + local GL_STENCIL_BUFFER_BIT = GL.STENCIL_BUFFER_BIT + local GL_REPLACE = GL.REPLACE + + local shaderConfig = { + SPECULAREXPONENT = 64.0, -- the specular exponent of the lava plane + SPECULARSTRENGTH = 1.0, -- The peak brightness of specular highlights + + LOSDARKNESS = 0.5, -- how much to darken the out-of-los areas of the lava plane + SHADOWSTRENGTH = 0.4, -- how much light a shadowed fragment can recieve + CREEPTEXREZ = 0.003, + JIGGLEAMPLITUDE = 0.2, + VOIDWATER = (gl.GetMapRendering("voidWater") and 1 or 0), + } + + local nightFactor = {1,1,1,1} + + ---- GL4 Backend Stuff---- + + local LuaShader = gl.LuaShader + local InstanceVBOTable = gl.InstanceVBOTable + + local uploadAllElements = InstanceVBOTable.uploadAllElements + local popElementInstance = InstanceVBOTable.popElementInstance + local pushElementInstance = InstanceVBOTable.pushElementInstance + + + local vsSrc = [[ + #version 420 + #extension GL_ARB_uniform_buffer_object : require + #extension GL_ARB_shader_storage_buffer_object : require + #extension GL_ARB_shading_language_420pack: require + + #line 5000 + + layout (location = 0) in vec4 xyworld_xyfract; // l w rot and maxalpha + layout (location = 1) in vec4 worldposradius; // xyz and radius + layout (location = 2) in vec4 lifeparams; // lifestart, growthrate, OVERLAPPED, unused; + + //__ENGINEUNIFORMBUFFERDEFS__ + //__DEFINES__ + + #line 10000 + + //uniform float fadeDistance; + uniform sampler2D heightmapTex; + uniform sampler2D mapnormalsTex; + + out DataVS { + vec4 v_worldPosRad; + vec4 v_localxz; + vec4 v_worldUV; + vec4 v_lifeparams; + vec4 v_mapnormals; + float v_trueradius; + }; + + float rand(vec2 co){ // a pretty crappy random function + return fract(sin(dot(co, vec2(12.9898, 78.233))) * 43758.5453); + } + + #line 11000 + void main() + { + v_worldPosRad = worldposradius; + v_lifeparams = lifeparams; + v_localxz = xyworld_xyfract; + // Transform the [-1, 1] rect into world space + vec4 mapPos = vec4(worldposradius.xyz, 1.0); + mapPos.xz += xyworld_xyfract.xy * worldposradius.w; + + // Sample the heightmap to get reasonable world depth + vec2 uvhm = heightmapUVatWorldPos(mapPos.xz); + mapPos.y = textureLod(heightmapTex, uvhm, 0.0).x + 3.0; + + // sample the map normals and pass it on for later use: + v_mapnormals = textureLod(mapnormalsTex, uvhm, 0.0); + + v_worldUV = mapPos.xyzw; + + float time = timeInfo.x + timeInfo.w; + + v_worldUV.x += JIGGLEAMPLITUDE * sin(time * 0.1 + 100*rand(v_worldUV.xy)); + v_worldUV.z += JIGGLEAMPLITUDE * sin(time * 0.1 + 100*rand(v_worldUV.zy)); + + if (lifeparams.y > 0.0) { + v_trueradius = clamp (lifeparams.y * (time - lifeparams.x), 0.0, v_worldPosRad.w); + } + else{ + v_trueradius = clamp (v_worldPosRad.w + lifeparams.y * (time - lifeparams.x), 0.0, v_worldPosRad.w) ; + } + //mapPos.y += fract( 10 * (time - lifeparams.x) * 0.001) * 100; + + gl_Position = cameraViewProj * mapPos; + if (lifeparams.z > 0.5){ + // Place overlapped circles outside of NDC space + gl_Position = vec4(2.0,2.0,2.0,1.0); + } + } + ]] + + local fsSrc = + [[ + #version 330 + #extension GL_ARB_uniform_buffer_object : require + #extension GL_ARB_shading_language_420pack: require + //__ENGINEUNIFORMBUFFERDEFS__ + //__DEFINES__ + + #line 30000 + uniform float iconDistance; + uniform vec4 nightFactor; + in DataVS { + vec4 v_worldPosRad; + vec4 v_localxz; + vec4 v_worldUV; + vec4 v_lifeparams; + vec4 v_mapnormals; + float v_trueradius; + }; + + uniform sampler2D heightmapTex; + uniform sampler2D mapnormalsTex; + uniform sampler2D infoTex; + uniform sampler2DShadow shadowTex; + uniform sampler2D colorheight; + uniform sampler2D normalspec; + uniform sampler2D distortion; + + out vec4 fragColor; + + vec4 shadowMapUVAtWorldPos(vec3 worldPos){ + vec4 shadowVertexPos = shadowView * vec4(worldPos,1.0); + shadowVertexPos.xy += vec2(0.5); + return shadowVertexPos; + //return clamp(textureProj(shadowTex, shadowVertexPos), 0.0, 1.0); + } + + // RNM func from: https://blog.selfshadow.com/publications/blending-in-detail/ + vec3 ReOrientNormal(vec3 basenormal, vec3 detailnormal){ + vec3 t = basenormal.xyz * vec3( 2, 2, 2) + vec3(-1, -1, 0); + vec3 u = detailnormal.xyz* vec3(-2, -2, 2) + vec3( 1, 1, -1); + vec3 r = t*dot(t, u) - u*t.z; + return normalize(r); + } + + + #line 31000 + void main(void) + { + if (any(lessThan(vec4(v_worldUV.xz, mapSize.xy - v_worldUV.xz) , vec4(0.0) ))) discard; // Discard out-of-map fragments + #if (VOIDWATER == 1) + if (v_worldUV.y < 0) discard; + #endif + + float time = timeInfo.x+timeInfo.w; + + float internalradius = length (v_localxz.xy) ; //dot(v_localxz.xy, v_localxz.xy); + float radialgrowth = v_trueradius/v_worldPosRad.w; + // discard outside of current radius + if (internalradius> radialgrowth) discard; // bail before any texture fetches + vec4 texdistort = texture(distortion, v_worldUV.xz * CREEPTEXREZ * 1.0); + float radialScum = smoothstep(radialgrowth - 0.15, radialgrowth, internalradius + 0.1 * texdistort.x ); + if (radialScum > 0.7) discard; + + vec4 texcolorheight= texture(colorheight, v_worldUV.xz * CREEPTEXREZ, -0.5); + vec4 texnormalspec = texture(normalspec, v_worldUV.xz* CREEPTEXREZ, - 0.5); + //vec4 texdistort2 = texture(distortion, v_worldUV.xz * CREEPTEXREZ * 2.0 + vec2(sin(time * 0.0002))) * 0.5 + 0.5; + + vec3 fragNormal = (texnormalspec.xzy * 2.0 -1.0); + + vec4 camPos = cameraViewInv[3]; + vec3 worldtocam = camPos.xyz - v_worldUV.xyz; + + float shadow = clamp(textureProj(shadowTex, shadowMapUVAtWorldPos(v_worldUV.xyz)), SHADOWSTRENGTH, 1.0); + + vec2 losUV = clamp(v_worldUV.xz, vec2(0.0), mapSize.xy ) / mapSize.zw; + float loslevel = dot(vec3(0.33), texture(infoTex, losUV).rgb) ; // lostex is PO2 + loslevel = clamp(loslevel * 4.0 - 1.0, LOSDARKNESS, 1.0); + + // this is the actually correct way of blending according to + // Whiteout blending https://blog.selfshadow.com/publications/blending-in-detail/ + fragNormal.xz += v_mapnormals.ra; + vec3 normal = normalize(fragNormal.xyz);// + texdistort2.xzy); + //normal = vec3(0.0, 1.0, 0.0); + + // calculate direct lighting + float lightamount = clamp(dot(sunDir.xyz, normal), 0.3, 1.0) * max(SHADOWSTRENGTH, shadow); + + // Specular Color + vec3 reflvect = reflect(normalize(-1.0 * sunDir.xyz), normal); + float specular = clamp(pow(clamp(dot(normalize(worldtocam), normalize(reflvect)), 0.0, 1.0), SPECULAREXPONENT), 0.0, SPECULARSTRENGTH);// * shadow; + //float specular = clamp(dot(normalize(worldtocam), normalize(reflvect)), 0.0, 1.0);// * shadow; + fragColor.rgb += fragColor.rgb * specular; + + vec3 outcolor = texcolorheight.rgb; + + outcolor = outcolor * ( loslevel * (lightamount ) * 0.5) + outcolor * specular * shadow; + fragColor.rgba = vec4(outcolor, 1.0 ); + + + // darken outside + + fragColor.a = 1.0 - radialScum*3; + fragColor.rgb *= ((fragColor.a -0.3)*2.0) ; + + // emulate linear fog + // vec4 fogParams; //fog {start, end, 0.0, scale} + float fogFactor = 1.0; + float fogDist = length(worldtocam.xyz); + fogFactor = (fogParams.y - fogDist) * fogParams.w; + fogFactor = clamp(fogFactor, 0.0, 1.0); + fragColor.rgb = mix( fogColor.rgb, fragColor.rgb,fogFactor); + + fragColor.rgb *= nightFactor.rgb; + } + ]] + + local function goodbye(reason) + Spring.Echo("Scum GL4 gadget exiting with reason: "..reason) + gadgetHandler:RemoveGadget() + end + + local function initGL4(shaderConfig, DPATname) + if gl.CreateShader == nil then + headless = true + return + end + + local engineUniformBufferDefs = LuaShader.GetEngineUniformBufferDefs() + vsSrc = vsSrc:gsub("//__ENGINEUNIFORMBUFFERDEFS__", engineUniformBufferDefs) + fsSrc = fsSrc:gsub("//__ENGINEUNIFORMBUFFERDEFS__", engineUniformBufferDefs) + scumShader = LuaShader( + { + vertex = vsSrc:gsub("//__DEFINES__", LuaShader.CreateShaderDefinesString(shaderConfig)), + fragment = fsSrc:gsub("//__DEFINES__", LuaShader.CreateShaderDefinesString(shaderConfig)), + uniformInt = { + heightmapTex = 0, + mapnormalsTex = 1, + infoTex = 2, + shadowTex = 3, + colorheight = 4, + normalspec = 5, + distortion = 6, + }, + uniformFloat = { + nightFactor = {1,1,1,1}, + --fadeDistance = 3000, + }, + }, + DPATname .. "Shader" + ) + local shaderCompiled = scumShader:Initialize() + if not shaderCompiled then + goodbye("Failed to compile ".. DPATname .." GL4 ") + return + end + + scumVBO = InstanceVBOTable.makeInstanceVBOTable( + { + {id = 1, name = 'worldposradius', size = 4}, -- xpos, ypos, zpos, radius + {id = 2, name = 'lifeparams', size = 4}, -- lifestart, lifeend, growthrate, unused + }, + 64, -- maxelements + DPATname .. "VBO" -- name + ) + if scumVBO == nil then + goodbye("Failed to create scumVBO") + return + end + + local planeVBO, numVertices = InstanceVBOTable.makePlaneVBO(1,1,resolution,resolution) + local planeIndexVBO, numIndices = InstanceVBOTable.makePlaneIndexVBO(resolution,resolution, true) + + scumVBO.vertexVBO = planeVBO + scumVBO.indexVBO = planeIndexVBO + + scumVBO.VAO = InstanceVBOTable.makeVAOandAttach( + scumVBO.vertexVBO, + scumVBO.instanceVBO, + scumVBO.indexVBO) + + end + + local scumRemoveQueue = {} -- maps gameframes to list of scums that will be removed + local scums = {} -- table of {posx = 123, posz = 123, radius = 123, spawnframe = 0, growthrate = -1.0} -- in elmos per sec + local numscums = 0 + local scumBins = {} -- a table keyed with (posx / 1024) + 1024 + (posz/1024), values are tables of scumindexes that can overlap that bin + + local sqrt = math.sqrt + local floor = math.floor + local clamp = math.clamp + local spGetGroundHeight = Spring.GetGroundHeight + local mapSizeX = Game.mapSizeX + local mapSizeZ = Game.mapSizeZ + local boundary = 32 -- how many elmos closer to the center of the scum than the actual edge of the scum the unit must be to be considered on the scum + + local function GetMapSquareKey(posx, posz) + if posx < 0 or posz < 0 or posx > mapSizeX or posz > mapSizeZ then return nil end + return (floor(posx*0.0009765625) * 1024 + floor(posz* 0.0009765625)) + end + + for x= 0, math.ceil(mapSizeX/1024) do + for z = 0, math.ceil(mapSizeZ/1024) do + scumBins[x*1024+z] = {} + end + end + + local function GetScumCurrentRadius(scum, gf) + gf = gf or gameFrame + if scum.growthrate > 0 then + return clamp((gf - scum.spawnframe) * scum.growthrate, 0, scum.radius) + else + return clamp(scum.radius - (gf - scum.spawnframe) *(-1.0 * scum.growthrate), 0, scum.radius) + end + end + + -- This checks wether the unit is under any scum + local function IsPosInScum(unitx,unity, unitz) + -- out of bounds check, no scum outside of map bounds + if unitx < 0 or unitz < 0 or unitx > mapSizeX or unitz > mapSizeZ then return nil end + -- underwater scum doesnt count for hovers, ships + unity = unity or 1 + if unity > -1 and spGetGroundHeight(unitx, unitz) < 0 then return nil end + + -- Empty bins also return + local scumBinID = GetMapSquareKey(unitx, unitz) + if scumBinID == nil or scumBins[scumBinID] == nil then return nil end + local gf = gameFrame + + for scumID, scum in pairs(scumBins[scumBinID]) do + local dx = (unitx - scum.posx) + local dz = (unitz - scum.posz) + local sqrdistance = (dx*dx + dz*dz) + local scumradius = scum.radius -- edges are not fully covered, so they shouldn't count, + if scumradius < 1 then scumradius = 1 end + if sqrdistance < (scumradius * scumradius) then + local currentscumradius = GetScumCurrentRadius(scum, gf) + --Spring.Echo("testing ScumID", scumID, sqrdistance, scumradius, currentscumradius) + if currentscumradius - sqrt(sqrdistance) > boundary then + return scumID + end + end + end + return nil + end + + local function UpdateBins(scumID, removeScum) + local scumTable = scums[scumID] + if scumTable == nil then + --Spring.Echo("Tried to update a scumID",scumID,"that no longer exists because it probably shrank to death, remove = ", removeScum) + return nil + end + + local posx = scumTable.posx + local posz = scumTable.posz + local radius = scumTable.radius + + if removeScum then + scumTable = nil + scums[scumID] = nil + end + + local binID = GetMapSquareKey(posx, posz) + if binID then scumBins[binID][scumID] = scumTable end + binID = GetMapSquareKey(posx + radius, posz + radius) + if binID then scumBins[binID][scumID] = scumTable end + binID = GetMapSquareKey(posx - radius, posz + radius) + if binID then scumBins[binID][scumID] = scumTable end + binID = GetMapSquareKey(posx + radius, posz - radius) + if binID then scumBins[binID][scumID] = scumTable end + binID = GetMapSquareKey(posx - radius, posz - radius) + if binID then scumBins[binID][scumID] = scumTable end + end + + -- growthrate is in elmos per frame, negative for shrinking scums + local function AddOrUpdateScum(posx, posy, posz, radius, growthrate, scumID) + if debugmode then Spring.Echo("AddOrUpdateScum",posx, posy, posz, radius, growthrate, scumID) end + -- if scumID is supplied, we are updateing an existing scum instance! + + local gf = Spring.GetGameFrame() + local deathtime + local scum + -- thus we need to make a new scum, and register it in our scumBins + if scumID == nil or scums[scumID] == nil then + posy = posy or Spring.GetGroundHeight(posx, posz) + scum = {posx = posx, posz = posz, radius = radius, spawnframe = gf, growthrate = growthrate, scumID = scumID, atmaxsize = false } + scums[scumID] = scum + UpdateBins(scumID) + numscums = numscums + 1 + else-- a scumID is supplied, meaning we just update an existing instance + scum = scums[scumID] + -- well then, seems we have to do this after all, when we update a scum, we need to check how long its been alive + -- this is the nastiest garbage ive ever done + local currentradius = GetScumCurrentRadius(scum, gf) + + -- always remove from removal queue on update + for _, removescums in pairs(scumRemoveQueue) do + removescums[scumID] = nil + end + + if growthrate > 0 then + scum.spawnframe = gf - ( currentradius/growthrate) + -- remove it from the death queue, no matter where it is, cause its 'growing' + else + scum.spawnframe = gf - ((scum.radius - currentradius)/ (-1 * growthrate) ) + deathtime = math.floor( gf + (currentradius/(-1 * growthrate))) + end + scum.growthrate = growthrate + + if debugmode then Spring.Echo("Updated scum", scumID, "it was", currentradius,"/", scum.radius, "sized, growing at", growthrate) end + end + + --Spring.Echo(scumID, growthrate, radius, gf) + if not headless then + pushElementInstance( + scumVBO, -- push into this Instance VBO Table + {scum.posx, scum.posy, scum.posz, scum.radius , -- + scum.spawnframe, scum.growthrate, 0, 0, -- alphastart_alphadecay_heatstart_heatdecay + }, + scumID, -- this is the key inside the VBO Table, should be unique per unit + true, -- update existing element + false) -- noupload, dont use unless you know what you are doing and want to batch push/pop + end + if scum.growthrate < 0 then + if debugmode then Spring.Echo("Removal of scum ID", scumID,"Scheduled for ", deathtime - gf , "from now" ) end + if scumRemoveQueue[deathtime] == nil then + scumRemoveQueue[deathtime] = {} + end + scumRemoveQueue[deathtime][scumID] = true + end + + return scumID + end + + local lastoverlapframe = 0 + local function UpdateScumOverlaps() + local overlapped = {} -- keys are scumID, value is that its either overlapped or not. + local scumRadii = {} -- keys are scumID, value is current radius + + for scumID, scum in pairs(scums) do + overlapped[scumID] = false + scumRadii[scumID] = GetScumCurrentRadius(scum) + end + local comparisons = 0 + local diag = math.diag + + for binID, scumBin in pairs(scumBins) do + for bigScumID, bigScum in pairs(scumBin) do -- for each of the scums in the bin + local bigRadius = scumRadii[bigScumID] + + if not overlapped[bigScumID] and bigRadius > 512 then + for smallScumID, smallScum in pairs(scumBin) do + if not overlapped[smallScumID] and scumRadii[smallScumID] < bigRadius then + comparisons = comparisons + 1 + if diag(bigScum.posx - smallScum.posx, bigScum.posz - smallScum.posz) < (bigRadius - scumRadii[smallScumID] - 128) then + overlapped[smallScumID] = true + end + end + end + end + end + end + + local overlapcount = 0 + for scumID, overlaps in pairs(overlapped) do + if overlaps then overlapcount = overlapcount + 1 end + end + if debugmode then + Spring.Echo(string.format("Of %d scums, %d overlaps found in %d comparisons", numscums, overlapcount, comparisons)) + end + + -- update the VBO + for i = 0, scumVBO.usedElements -1 do + local scumID = scumVBO.indextoInstanceID[i + 1] + scumVBO.instanceData[(i * scumVBO.instanceStep) + 7] = (overlapped[scumID] and optimizeoverlaps) and 1 or 0 + end + uploadAllElements(scumVBO) + return overlapcount, comparisons + end + + + local usestencil = false + + function gadget:DrawWorldPreUnit() + + if headless then return end + if debugmode then + local mx, my, mb = Spring.GetMouseState() + local _, coords = Spring.TraceScreenRay(mx, my, true) + if coords and (IsPosInScum(coords[1], coords[2],coords[3])) then + Spring.Echo("Inscum", numscums, IsPosInScum(coords[1], coords[2],coords[3])) + end + end + + if drawScum and scumVBO.usedElements > 0 then + if optimizeoverlaps and gameFrame%63 == 0 and lastoverlapframe ~= gameFrame then + lastoverlapframe = gameFrame + UpdateScumOverlaps() + end + + --Spring.Echo(scumVBO.usedElements) + --glCulling(GL.BACK) + glCulling(false) + glDepthTest(GL_LEQUAL) + --glDepthTest(false) + --gl.DepthMask(true) + glTexture(0, '$heightmap') + glTexture(1, '$normals') + glTexture(2, "$info")-- Texture file + glTexture(3, "$shadow")-- Texture file + glTexture(4, textures[textureresolution].texcolorheight) + glTexture(5, textures[textureresolution].texnormalspec) + glTexture(6, textures[textureresolution].texdistortion)-- Texture file + scumShader:Activate() + scumShader:SetUniform("nightFactor", nightFactor[1], nightFactor[2], nightFactor[3], nightFactor[4]) + + if usestencil then + gl.StencilTest(true) --https://learnopengl.com/Advanced-OpenGL/Stencil-testing + gl.DepthTest(true) + glStencilOp(GL_KEEP, GL_KEEP, GL_REPLACE) -- Set The Stencil Buffer To 1 Where Draw Any Polygon this to the shader + glClear(GL_STENCIL_BUFFER_BIT) -- set stencil buffer to 0 + + glStencilFunc(GL_NOTEQUAL, 1, 1) -- use NOTEQUAL instead of ALWAYS to ensure that overlapping transparent fragments dont get written multiple times + glStencilMask(1) + end + + --scumShader:SetUniform("fadeDistance",disticon * 1000) + scumVBO.VAO:DrawElements(GL.TRIANGLES,nil,0,scumVBO.usedElements, 0) + scumShader:Deactivate() + if usestencil then + glStencilMask(1) + glStencilFunc(GL_ALWAYS, 1, 1) + gl.StencilTest(false) + glClear(GL_STENCIL_BUFFER_BIT) -- set stencil buffer to 0 + glStencilMask(0) + end + for i = 0, 6 do glTexture(i, false) end + glCulling(false) + --glDepthTest(false) + end + end + + local lastSunChanged = -1 + function gadget:SunChanged() -- Note that map_nightmode.lua gadget has to change sun twice in a single draw frame to update all + local df = Spring.GetDrawFrame() + if df == lastSunChanged then return end + lastSunChanged = df + if GG['NightFactor'] then + local altitudefactor = 1.0 --+ (1.0 - WG['NightFactor'].altitude) * 0.5 + nightFactor[1] = GG['NightFactor'].red + nightFactor[2] = GG['NightFactor'].green + nightFactor[3] = GG['NightFactor'].blue + nightFactor[4] = GG['NightFactor'].shadow + end + end + + local function RemoveScum(instanceID) + if debugmode then Spring.Echo("Removing scum", instanceID) end + if scums[instanceID] then + numscums = numscums - 1 + end + UpdateBins(instanceID, true) + if scumVBO.instanceIDtoIndex[instanceID] and (not headless) then + popElementInstance(scumVBO, instanceID) + end + end + + local function AddRandomScum() + local posx = Game.mapSizeX * math.random() * 0.8 + local posz = Game.mapSizeZ * math.random() * 0.8 + local posy = Spring.GetGroundHeight(posx, posz) + local radius = math.random() * 256 + 128 + local growthrate = math.random() * 0.5 -- in elmos per frame + local scumID = math.random() + AddOrUpdateScum(posx, posy, posz, radius, growthrate, scumID) + end + + local scumModulo = 1 + function gadget:GameFrame(n) + gameFrame = n + if scumRemoveQueue[n] then + for scumID, _ in pairs(scumRemoveQueue[n]) do + RemoveScum(scumID) + end + scumRemoveQueue[n] = nil + end + + if n % 39 == 1 and Script.LuaUI("GadgetRemoveGrass") then + scumModulo = (scumModulo + 1) % 4 + for scumID, scum in pairs(scums) do + if ((scumID % 4) == scumModulo) and scum.growthrate > 0 and (not scum.atmaxsize) then + local currentRadius = GetScumCurrentRadius(scum, n) + if currentRadius < scum.radius then + Script.LuaUI.GadgetRemoveGrass(scum.posx, scum.posz, currentRadius * 0.87) + else + if debugmode then Spring.Echo("Scum ID", scumID, "reached max size", currentRadius, '>=', scum.radius) end + scum.atmaxsize = true + end + + end + end + end + + if debugmode then + -- randomly add a new scum instance + if n % 2 == 0 then + if numscums < 300 then + AddRandomScum() + else + for scumID, scumData in pairs(scums) do + if math.random() < 1.0 / numscums then + AddOrUpdateScum(nil,nil,nil,nil, math.random() * 1 -0.5, scumID) + break + end + end + end + end + end + end + + local function HandleScumCreated(cmd, posx, posz, radius, growthrate, gf, scumID) + --Spring.Echo("Scum Created Unsynced", cmd, posx, posz, radius, growthrate, gf, scumID) + AddOrUpdateScum(posx, nil, posz, radius, growthrate, scumID) + end + + local function HandleScumRemoved(cmd, scumID ) + if scums[scumID] then + AddOrUpdateScum(nil,nil,nil,nil, -10 * math.abs( scums[scumID].growthrate), scumID) + end + end + + local function ScumTextures() + textureresolution = ((textureresolution == 'low') and 'high') or 'low' + Spring.Echo("Scum textureresolution set to ", textureresolution) + end + + local function ScumStats() + for x= 0, math.ceil(mapSizeX/1024) do + for z = 0, math.ceil(mapSizeZ/1024) do + local scumBin = scumBins[GetMapSquareKey(x*1024, z * 1024)] + local scumCount = 0 + for _ in pairs(scumBin) do scumCount = scumCount + 1 end + Spring.Echo(string.format("%d scums are in bin %d x %d", scumCount, x, z)) + end + end + Spring.Echo(string.format("Total amount of scums on map is %d", numscums)) + local overlapcount, comparisons = UpdateScumOverlaps() + Spring.Echo("overlapcount", overlapcount, "comparisons=", comparisons) + end + + local function ScumReloadShader() + Spring.Echo("ScumReloadShader not implemented") + end + + local function ScumDrawToggle() + drawScum = not drawScum + Spring.Echo("Scum drawing toggled to", drawScum) + end + local function ScumOptimizeOverlap() + optimizeoverlaps = not optimizeoverlaps + Spring.Echo("Scum optimizeoverlaps toggled to", optimizeoverlaps) + UpdateScumOverlaps() + end + + + function gadget:Initialize() + initGL4(shaderConfig, "scum") + + gadgetHandler:AddSyncAction("ScumCreated", HandleScumCreated) + gadgetHandler:AddSyncAction("ScumRemoved", HandleScumRemoved) + + gadgetHandler:AddChatAction("scumtextures", ScumTextures, "Toggle between texture resolutions") + gadgetHandler:AddChatAction("scumreloadshader" , ScumReloadShader, "Reload the Scum Shader") + gadgetHandler:AddChatAction("scumstats" , ScumStats, "Print statistics about scum" ) + gadgetHandler:AddChatAction("scumdraw" , ScumDrawToggle, "Toggles drawing the scom" ) + gadgetHandler:AddChatAction("scumoptimizeoverlap" , ScumOptimizeOverlap, "Toggles drawing the scom" ) + end + + function gadget:ShutDown() + gadgetHandler:RemoveSyncAction("ScumCreated") + gadgetHandler:RemoveSyncAction("ScumRemoved") + + gadgetHandler:RemoveChatAction("scumhighrestextures", ScumTextures) + gadgetHandler:RemoveChatAction("scumreloadshader" , ScumReloadShader ) + gadgetHandler:RemoveChatAction("scumstats" , ScumStats ) + gadgetHandler:RemoveChatAction("scumdraw" , ScumDrawToggle ) + gadgetHandler:RemoveChatAction("scumoptimizeoverlap" , ScumOptimizeOverlap ) + end +end + +return gadget end)() +-- Only authentic original public messages and original callbacks enter here. +local enabled=false +function WebbarRaptorScumInitialize() + if original.Initialize then original:Initialize();enabled=true end + return enabled +end +function WebbarRaptorScumEvent(name,...) + assert(name=='ScumCreated'or name=='ScumRemoved') + if enabled then assert(listeners[name])(name,...)end +end +function WebbarRaptorScumGameFrame(frame) + if enabled then original:GameFrame(frame)end +end +function WebbarRaptorScumSunChanged(factor) + if not enabled then return end + GG.NightFactor=factor + original:SunChanged() +end +function WebbarRaptorScumState(draw) + if not enabled then return{disabled=true,frame=Spring.GetGameFrame(),rows={},grass={}}end + if draw~=false then original:DrawWorldPreUnit()end + local v=assert(WG.VBOTableRegistry.scumVBO) + assert(v.instanceStep==8 and v.usedElements<=131072) + local rows={} + for i=1,v.usedElements do + local row={} + -- LuaVBOImpl::Upload uses raw_get_or(...,0), including the + -- original gadget's absent posy. Preserve that GL transport behavior. + for c=1,8 do row[c]=v.instanceData[(i-1)*8+c]or 0 end + rows[i]={id=assert(v.indextoInstanceID[i]),params=row} + end + local removedGrass=grass;grass={} + return{disabled=false,frame=Spring.GetGameFrame(),rows=rows,grass=removedGrass,night=nightFactor,config=shaderConfig} +end + +)WEBBAR_SCUM"; --- /dev/null +++ b/rts/Game/WebbarNativeSensorGroups.inc @@ -0,0 +1,64 @@ +// Member of the existing read-only sensor handle. No second Lua VM/tracker. +bool Groups(std::vector& packet) +{ + if (!ready || packet.size() != 48) return false; + const int top = lua_gettop(L); + lua_getglobal(L, "WebbarSensorGroupsState"); + bool ok = RunCallIn(L, LuaHashString("WebbarSensorGroupsState"), 0, 1) && lua_istable(L, -1); + if (ok) { + lua_getfield(L, -1, "frame"); + ok = lua_type(L, -1) == LUA_TNUMBER && lua_tonumber(L, -1) == gs->frameNum; + lua_pop(L, 1); + lua_getfield(L, -1, "groups"); + ok = ok && lua_istable(L, -1) && lua_objlen(L, -1) == 4; + const int groups = lua_gettop(L); + const std::array kinds{"los", "radar", "sonar", "jammer"}; + for (int index = 0; ok && index < 4; ++index) { + const int at = 16 + index * 8; + lua_rawgeti(L, groups, index + 1); + if (!lua_istable(L, -1)) { ok = false; break; } + const int group = lua_gettop(L); + lua_getfield(L, group, "kind"); + ok = lua_type(L, -1) == LUA_TSTRING && std::strcmp(lua_tostring(L, -1), kinds[index]) == 0; + lua_pop(L, 1); + lua_getfield(L, group, "disabled"); + const bool disabled = lua_toboolean(L, -1); + ok = ok && lua_type(L, -1) == LUA_TBOOLEAN; + packet[at + 1] = disabled; lua_pop(L, 1); + lua_getfield(L, group, "opacity"); const float opacity = lua_tonumber(L, -1); + ok = ok && lua_type(L, -1) == LUA_TNUMBER && std::isfinite(opacity) && opacity >= 0 && opacity <= 1 && (!disabled || opacity == 0); + std::memcpy(&packet[at + 4], &opacity, 4); lua_pop(L, 1); + lua_getfield(L, group, "rows"); + ok = ok && lua_istable(L, -1) && lua_objlen(L, -1) <= 65536 && (!disabled || lua_objlen(L, -1) == 0); + const int rows = lua_gettop(L), count = ok ? lua_objlen(L, rows) : 0; + packet[at + 3] = packet.size(); + std::unordered_set seen; + for (int i = 1; ok && i <= count; ++i) { + lua_rawgeti(L, rows, i); + if (!lua_istable(L, -1)) { ok = false; break; } + lua_getfield(L, -1, "id"); const float id = lua_tonumber(L, -1); + ok = lua_type(L, -1) == LUA_TNUMBER && id >= 0 && id <= 65535 && std::floor(id) == id && seen.insert(int(id)).second; + lua_pop(L, 1); + const CUnit* unit = ok ? unitHandler.GetUnit(int(id)) : nullptr; + const bool admitted = unit && !unit->isDead && (gu->spectatingFullView || unit->allyteam == gu->myAllyTeam); + lua_getfield(L, -1, "params"); + ok = ok && lua_istable(L, -1) && lua_objlen(L, -1) == 4; + std::array row{uint32_t(ok ? id : 0), admitted ? WebbarHudLifetime(unit) : 0}; + ok = ok && (!admitted || (row[1] != 0 && row[1] != 0xffffffffu)); + for (int j = 1; ok && j <= 4; ++j) { + lua_rawgeti(L, -1, j); const float value = lua_tonumber(L, -1); + ok = lua_type(L, -1) == LUA_TNUMBER && std::isfinite(value) + && (j != 1 || (value >= 0 && value <= 1048576)) + && (j != 2 || std::abs(value) <= 2147483648.0f) + && (j <= 2 || value == 0); + std::memcpy(&row[j + 1], &value, 4); lua_pop(L, 1); + } + if (ok && admitted) { packet.insert(packet.end(), row.begin(), row.end()); ++packet[at + 2]; ++packet[8]; } + lua_pop(L, 2); + } + lua_pop(L, 2); + } + } + lua_settop(L, top); + return ok; +} --- /dev/null +++ b/rts/Game/WebbarNativeSensorGroupsPolicy.h @@ -0,0 +1,6408 @@ +/* Original BAR GPL v2 or later policies; generated by scripts/native-sensor-groups.mjs. */ +#pragma once +static constexpr const char* WEBBAR_SENSOR_GROUPS_POLICY=R"WEBBAR_GROUPS( +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 +Spring.GetConfigInt=function()return 0 end +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}) + +-- Read-only storage for the complete stock sensor widgets. A widget can remove +-- itself without disabling another sensor (notably sonar on an all-dry map). +local activeWidget +local removedWidgets={} +widgetHandler.RemoveWidget=function(_,target) + target=target or activeWidget + assert(target,'Sensor removal outside an original callback') + removedWidgets[target]=true +end +local function sensorCall(widget,name,...) + if removedWidgets[widget]or not widget[name]then return end + local previous=activeWidget + activeWidget=widget + local result=widget[name](widget,...) + activeWidget=previous + return result +end + +gl.InstanceVBOTable=(function() +local GL_BUFFER = 0x82E0 +local gldebugannotations = (Spring.GetConfigInt("gldebugannotations") == 1) +--Spring.Echo("gldebugannotations", gldebugannotations) +local function makeInstanceVBOTable(layout, maxElements, myName, unitIDattribID) + -- layout: this must be an array of tables with at least the following specified: {{id = 1, name = 'optional', size = 4}} + -- maxElements: will be dynamic anyway, but defaults to 64 + -- myName: optional name, useful for debugging + -- unitIDattribID: the attribute ID in the layout of the uvec4 of unitID bindings (e.g. 4 for {id = 4, name = 'instData', type = GL.UNSIGNED_INT, size= 4} ) + -- returns: nil | instanceTable + if maxElements == nil then maxElements = 64 end -- default size + if myName == nil then myName = "InstanceVBOTable" end + local newInstanceVBO = gl.GetVBO(GL.ARRAY_BUFFER,true) + if newInstanceVBO == nil then Spring.Echo("makeInstanceVBOTable, cannot get VBO for", myName); return nil end + newInstanceVBO:Define( + maxElements, + layout + ) + + + + local instanceStep = 0 + for i,attribute in pairs(layout) do + instanceStep = instanceStep + attribute.size + end + local instanceData = {} + for i = 1, instanceStep * maxElements do + instanceData[i] = 0 + end + local instanceTable = { + instanceVBO = newInstanceVBO, + instanceData = instanceData, + instanceStep = instanceStep, + usedElements = 0, + maxElements = maxElements, + myName = myName, + instanceIDtoIndex = {}, -- this maps each instance ID to where it is in the buffer, 1 based + indextoInstanceID = {}, -- this tells us what instanceID is located in any given pos + layout = layout, + dirty = false, + numVertices = 0, + primitiveType = GL.TRIANGLES, + debugZombies = true, -- this is new, and its for debugging non-existing stuff on unitdestroyed + lastInstanceID = 0, + } + + if unitIDattribID ~= nil then + instanceTable.indextoUnitID = {} + instanceTable.unitIDattribID = unitIDattribID + instanceTable.popUnitIDFailuresInGameFrame = {} + end + + function instanceTable:clearInstanceTable() + -- this wont resize it, but quickly sets it to empty + self.usedElements = 0 + self.instanceIDtoIndex = {} + self.indextoInstanceID = {} + if self.indextoUnitID then self.indextoUnitID = {} end + end + + function instanceTable:makeVAOandAttach(vertexVBO, instanceVBO, indexVBO) -- Attach a vertex buffer to an instance buffer, and optionally, an index buffer if one is supplied. + -- There is a special case for this, when we are using a vertexVBO as a quasi-instanceVBO, e.g. when we are using the geometry shader to draw a vertex as each instance. + --iT.vertexVBO = vertexVBO + --iT.indexVBO = indexVBO + local newVAO = nil + newVAO = gl.GetVAO() + if newVAO == nil then goodbye("Failed to create newVAO") end + self.VAO = newVAO + if vertexVBO == nil then -- the special case where are using 'vertices' as 'instances' + newVAO:AttachVertexBuffer(instanceVBO) + else + newVAO:AttachVertexBuffer(vertexVBO) + newVAO:AttachInstanceBuffer(instanceVBO) + self.vertexVBO = vertexVBO + self.instanceVBO = instanceVBO + end + if indexVBO then + newVAO:AttachIndexBuffer(indexVBO) + self.indexVBO = indexVBO + function self:Draw() + self.VAO:DrawElements(GL.TRIANGLES, nil, 0, self.usedElements, 0) + end + else + function self:Draw() + self.VAO:DrawArrays(GL.TRIANGLES, nil, 0, self.usedElements, 0) + end + end + return newVAO + end + + function instanceTable:clearInstanceTable() + -- this wont resize it, but quickly sets it to empty + self.usedElements = 0 + self.instanceIDtoIndex = {} + self.indextoInstanceID = {} + if self.indextoUnitID then self.indextoUnitID = {} end + end + + function instanceTable:compact() + self.destroyedElements = 0 + -- so this is for the edge case, where we have silently removed elements from instanceIDtoIndex + -- where we have holes everywhere, so we have to 'compact' the table, + -- by copying back contiguously while preserving element order + local newInstanceIDtoIndex = {} + local newIndexToInstanceID = {} + local newInstanceData = {} + local newUsedElements = 0 + for i = 1, self.usedElements do + local instanceID = self.indextoInstanceID[i] + local index = self.instanceIDtoIndex[self.indextoInstanceID[i]] + if index then + local instanceStep = self.instanceStep + local instanceData = self.instanceData + + local dstpos = newUsedElements * instanceStep + local srcpos = (i - 1) * instanceStep + for j=1, instanceStep do + newInstanceData[dstpos + j] = instanceData[srcpos +j] + end + newUsedElements = newUsedElements + 1 + newInstanceIDtoIndex[instanceID] = newUsedElements + newIndexToInstanceID[newUsedElements] = instanceID + else + --Spring.Echo("compacting index",i, 'instanceID', instanceID) + end + end + --Spring.Echo("Post compacting", self.usedElements, newUsedElements) + self.usedElements = newUsedElements + self.instanceIDtoIndex = newInstanceIDtoIndex + self.indextoInstanceID = newIndexToInstanceID + self.instanceData = newInstanceData + --iT.instanceVBO:Upload(iT.instanceData,nil,oldElementIndex-1,oldOffset +1,oldOffset + iTStep) + if self.usedElements > 0 then + self.instanceVBO:Upload(self.instanceData) + end + end + + + function instanceTable:draw(primitiveType) + if self.usedElements > 0 then + if self.indexVBO then + self.VAO:DrawElements(primitiveType or self.primitiveType, self.numVertices, 0, self.usedElements,0) + else + self.VAO:DrawArrays (primitiveType or self.primitiveType, self.numVertices, 0, self.usedElements,0) + end + end + end + + function instanceTable:getMemUsage() + -- arrays are 16 bytes per element + -- Hash tables are 40 bytes per element + local totalMem = 0 + totalMem = totalMem + self.usedElements * self.instanceStep * 16 -- the actual instance data + totalMem = totalMem + self.usedElements * 16 -- indextoinstanceid + totalMem = totalMem + self.usedElements * 40 -- instanceIDtoIndex + if self.indextoUnitID then totalMem = totalMem + self.usedElements * 16 end + return totalMem + end + + function instanceTable:Delete() + -- Frees the instancevbo and vao for this instance table. Does not touch the vertex and index vbos. + -- returns an estimate of how much ram was used + if self.instanceVBO then self.instanceVBO:Delete() end + if self.VAO then self.VAO:Delete() end + local memusage = self:getMemUsage() + self:clearInstanceTable() + return memusage + end + + + newInstanceVBO:Upload(instanceData) + + -- I believe that the openGL spec doesnt guarantee that a buffer has an idea before data is uploaded to it, so we will fill it with zeros. + if gldebugannotations then + gl.ObjectLabel(GL_BUFFER, newInstanceVBO:GetID(), myName) + end + + + --register self in WG if possible + if WG then + if WG.VBOTableRegistry == nil then + --Spring.Echo("WG.VBORegistry == nil, creating registry on first load") + WG.VBOTableRegistry = {} + end + if WG.VBOTableRegistry[instanceTable.myName] then + local newname = instanceTable.myName .. tostring(math.random()) + --Spring.Echo(instanceTable.myName, 'already registered, renaming to', newname) + instanceTable.myName = newname + end + --Spring.Echo("Registered ", instanceTable.myName) + WG.VBOTableRegistry[instanceTable.myName] = instanceTable + end + + return instanceTable +end + +local function nextInstanceID(iT) + iT.lastInstanceID = iT.lastInstanceID + 1 + return iT.lastInstanceID +end + +local function clearInstanceTable(iT) + -- this wont resize it, but quickly sets it to empty + iT.usedElements = 0 + iT.instanceIDtoIndex = {} + iT.indextoInstanceID = {} + if iT.indextoUnitID then iT.indextoUnitID = {} end +end + +local function makeVAOandAttach(vertexVBO, instanceVBO, indexVBO) -- Attach a vertex buffer to an instance buffer, and optionally, an index buffer if one is supplied. + -- There is a special case for this, when we are using a vertexVBO as a quasi-instanceVBO, e.g. when we are using the geometry shader to draw a vertex as each instance. + --iT.vertexVBO = vertexVBO + --iT.indexVBO = indexVBO + local newVAO = nil + newVAO = gl.GetVAO() + if newVAO == nil then goodbye("Failed to create newVAO") end + if vertexVBO == nil then -- the special case where are using 'vertices' as 'instances' + newVAO:AttachVertexBuffer(instanceVBO) + else + newVAO:AttachVertexBuffer(vertexVBO) + newVAO:AttachInstanceBuffer(instanceVBO) + end + if indexVBO then + newVAO:AttachIndexBuffer(indexVBO) + end + -- this allows us to set up our sane + + + return newVAO +end + + +--------------- DEBUG HELPERS -------------------------- +local function comparetables(t1, t2, name) + for k,v in pairs(t1) do + if t2[k] == nil then + Spring.Echo("Key ",k,"with value",v,"existing in t1 does not exist in t2 in ", name) + elseif t2[k] ~= v then + Spring.Echo("Value ",v,"for",k,"existing in t1 does not match value for t2",t2[k]," in ", name) + end + end + + for k,v in pairs(t2) do + if t1[k] == nil then + Spring.Echo("Key ",k,"with value",v,"existing in t2 does not exist in t1 in ", name) + elseif t1[k] ~= v then + Spring.Echo("Value ",v,"for",k,"existing in t2 does not match value for t1",t1[k]," in ", name) + end + end +end + +local function dbgt(t, name) + name = name or "" + local gf = Spring.GetGameFrame() + local count = 0 + local res = '' + for k,v in pairs(t) do + if type(k) == 'number' and type(v) == 'number' then + res = res .. tostring(k) .. ':' .. tostring(v) ..',' + count = count + 1 + end + end + Spring.Echo(tostring(gf).. " " ..name .. ' #' .. tostring(count) .. ' {'..res .. '}') + return res +end + +local function counttable(t) + local count = 0 + if type(t) ~= type({}) then return 0 end + for k, v in pairs(t) do count = count + 1 end + return count +end + +local function validateInstanceVBOTable(iT, calledfrom) + -- check that instanceIDtoIndex and indextoInstanceID are valid and contigous: + for i=1, iT.usedElements do + if iT.indextoInstanceID[i] == nil then + Spring.Echo("There is a hole in indextoInstanceID", iT.myName, "at", i,"out of",iT.usedElements, calledfrom) + --Spring.Echo() + if iT.indextoUnitID[i] == nil then + Spring.Echo("It is also missing from indextoUnitID") + else + Spring.Echo("But it does exist in indextoUnitID with an unitID of ", iT.indextoUnitID[i]) + Spring.Echo("This is valid?", Spring.GetUnitPosition(iT.indextoUnitID[i])) + end + + else + local instanceID = iT.indextoInstanceID[i] + if iT.instanceIDtoIndex[instanceID] == nil then + Spring.Echo("There is a hole instanceIDtoIndex", iT.myName, "at", i," iT.instanceIDtoIndex[instanceID] == nil ") + elseif iT.instanceIDtoIndex[instanceID] ~= i then + Spring.Echo("There is a problem in indextoInstanceID", iT.myName, "at i =", i," iT.indextoInstanceID[instanceID] ~= i, it is instead: ", iT.indextoInstanceID[instanceID] ) + end + end + end + local indextoInstanceIDsize = counttable(iT.indextoInstanceID) + local instanceIDtoIndexsize = counttable(iT.instanceIDtoIndex) + local indextoUnitID = counttable(iT.indextoUnitID) + if (indextoInstanceIDsize ~= instanceIDtoIndexsize) or (instanceIDtoIndexsize ~= indextoUnitID) then + Spring.Echo("Table size mismatch during validation of", iT.myName, indextoInstanceIDsize, instanceIDtoIndexsize, indextoUnitID) + end + +end + +function locateInvalidUnits(iT) + if iT.validinfo == nil then iT.validinfo = {} end + local invalidcount = 0 + for i, unitID in ipairs(iT.indextoUnitID) do + if iT.featureIDs then + if Spring.ValidFeatureID(unitID) then + local px, py, pz = Spring.GetFeaturePosition(unitID) + local fdefname = FeatureDefs[Spring.GetFeatureDefID(unitID)].name + iT.validinfo[unitID] = {px = px, py = py, pz = pz, fdefname = fdefname} + else + Spring.SendCommands({"pause 1"}) + Spring.Echo("INVALID feature, last seen at", unitID) + local vi = iT.validinfo[unitID] + local markertext = tostring(unitID) .. "," .. dbgt(vi) + Spring.MarkerAddPoint(vi.px, vi.py, vi.pz, markertext ) + invalidcount = invalidcount + 1 + end + else + if Spring.ValidUnitID(unitID) then + local px, py, pz = Spring.GetUnitPosition(unitID) + local unitDefID = Spring.GetUnitDefID(unitID) + local unitdefname = (unitDefID and UnitDefs[unitDefID].name) or "unknown:nil" + iT.validinfo[unitID] = {px = px, py = py, pz = pz, unitdefname = unitdefname} + else + Spring.SendCommands({"pause 1"}) + Spring.Echo(iT.myName, " INVALID unitID",unitID,"#elements", iT.usedElements, "last seen at tablepos:", i) + + local vi = iT.validinfo[unitID] + local markertext = tostring(unitID) .. "," .. dbgt(vi) + Spring.MarkerAddPoint(vi.px, vi.py, vi.pz, markertext ) + invalidcount = invalidcount + 1 + end + end + end + return invalidcount +end + +------------------------------END DEBUG HELPERS --------------------------- + +local function resizeInstanceVBOTable(iT) + -- iT: the InstanceVBOTable to double in size 'dynamically' resize the VBO, to double its size + -- this is called automatically when the existing instanceVBO gets full + -- Also performs a busload of sanity checking + -- Spring.Echo("instanceVBOTable full, resizing to double size",iT.myName, iT.usedElements,iT.maxElements) + iT.maxElements = iT.maxElements * 2 + local newInstanceVBO = gl.GetVBO(GL.ARRAY_BUFFER,true) + newInstanceVBO:Define(iT.maxElements, iT.layout) + + if iT.instanceVBO then iT.instanceVBO:Delete() end -- release if previous one existed + iT.instanceVBO = newInstanceVBO + -- ok this needs some sanitation right here, with reporting. + if iT.indextoUnitID then + -- we need to walk through both tables at the same time, and virtually pop all invalid unit/featureIDs on a resize, or else face dire consequences (crashes) later on + -- the tables we need to keep updated are: + local new_instanceData = {} + local new_instanceData_count = 0 + local new_usedElements = 0 + local new_instanceIDtoIndex = {} + local new_indextoInstanceID = {} + local new_indextoUnitID = {} + local invalidcount = 0 + local iTStep = iT.instanceStep + + for i, objectID in ipairs(iT.indextoUnitID) do + local isValidID = false + if iT.featureIDs then isValidID = Spring.ValidFeatureID(objectID) + else isValidID = Spring.ValidUnitID(objectID) end + if isValidID then + local offset = new_usedElements * iTStep + for j = 1, iTStep do + new_instanceData_count = new_instanceData_count + 1 + new_instanceData[new_instanceData_count] = iT.instanceData[j + offset] + end + new_usedElements = new_usedElements + 1 + local currentInstanceID = iT.indextoInstanceID[i] + new_indextoInstanceID[new_usedElements] = iT.indextoInstanceID[i] + new_indextoUnitID[new_usedElements] = iT.indextoUnitID[i] + new_instanceIDtoIndex[currentInstanceID] = new_usedElements + --Spring.Echo("Resize:",currentInstanceID, iT.indextoUnitID[i] ) + invalidcount = invalidcount + 1 + else + Spring.Echo("Warning: Found invalid unit/featureID",objectID,"at",i,"while resizing",iT.myName) + end + end + + if invalidcount == 0 then + comparetables( iT.instanceData, new_instanceData, "instanceData") + comparetables( iT.instanceIDtoIndex, new_instanceIDtoIndex, "instanceIDtoIndex") + comparetables( iT.indextoInstanceID, new_indextoInstanceID, "indextoInstanceID") + comparetables( iT.indextoUnitID, new_indextoUnitID, "indextoUnitID") + end + + iT.instanceData = new_instanceData + iT.usedElements = new_usedElements + iT.instanceIDtoIndex = new_instanceIDtoIndex + iT.indextoInstanceID = new_indextoInstanceID + iT.indextoUnitID = new_indextoUnitID + end + + iT.instanceVBO:Upload(iT.instanceData,nil,0,1,iT.usedElements * iT.instanceStep) + + if gldebugannotations then + gl.ObjectLabel(GL_BUFFER, iT.instanceVBO:GetID(), iT.myName) + end + + if iT.VAO then -- reattach new if updated :D + iT.VAO:Delete() + iT.VAO = makeVAOandAttach(iT.vertexVBO,iT.instanceVBO, iT.indexVBO) + end + + if iT.indextoUnitID then + if iT.featureIDs then + iT.instanceVBO:InstanceDataFromFeatureIDs(iT.indextoUnitID, iT.unitIDattribID) + else + iT.instanceVBO:InstanceDataFromUnitIDs(iT.indextoUnitID, iT.unitIDattribID) + end + end + return iT.maxElements +end + +--[[ from Ivand: +instVBO:Upload({ + 100, 0, 0, + -100, 0, 0, + 0, 0, 100, + 0, 0, -100, + }, 7, 1, 4, 6) +Here is how you upload starting from 1st element and starting from 4th element in Lua array (-100) and finishing with 6th element (0), essentially it will upload (-100, 0, 0) into 7th attribute of 2nd instance. +]]-- + +local function pushElementInstance(iT,thisInstance, instanceID, updateExisting, noUpload, unitID) + -- iT: instanceTable created with makeInstanceTable + -- thisInstance: is a lua array of values to add to table, MUST BE INSTANCESTEP SIZED LUA ARRAY + -- instanceID: an optional key given to the item, so it can be easily removed/updated by reference, defaults to the index of the instance in the buffer (1 based) + -- updateExisting: allow updating an existing element (same instanceID key) + -- noUpload: prevent the VBO from being uploaded, if you feel like you are going to do a lot of ops and wish to manually upload when done instead + -- unitID: if given, it will store then unitID corresponding to this instance, and will try to update the InstanceDataFromUnitIDs for this unit + -- returns: the index of the instanceID in the table on success, else nil + if #thisInstance ~= iT.instanceStep then + Spring.Echo("Trying to upload an oddly sized instance into",iT.myName, #thisInstance, "instead of ",iT.instanceStep) + Spring.Debug.TraceFullEcho(20,20,20, "pushElementInstance Failure:"..iT.myName ) + end + local iTusedElements = iT.usedElements + local iTStep = iT.instanceStep + local endOffset = iTusedElements * iTStep + if instanceID == nil then instanceID = nextInstanceID(iT) end + local thisInstanceIndex = iT.instanceIDtoIndex[instanceID] + + if (iTusedElements + 1 ) >= iT.maxElements then -- add 1 extra for safety (not the best idea, but we seem to be running over it by 1) + resizeInstanceVBOTable(iT) + iTusedElements = iT.usedElements -- because during validation of unitIDs during resizing, we can decrease the actual size of the table! + thisInstanceIndex = iT.instanceIDtoIndex[instanceID] -- this too, can change, TODO, also do this in VBOIDtable! + end + + if thisInstanceIndex == nil then -- new, register it + thisInstanceIndex = iTusedElements + 1 + iT.usedElements = iTusedElements + 1 + iT.instanceIDtoIndex[instanceID] = thisInstanceIndex + iT.indextoInstanceID[thisInstanceIndex] = instanceID + else -- pre-existing ID, update or bail + if updateExisting == nil then + Spring.Echo("Tried to add existing element to an instanceTable",iT.myName, instanceID) + return nil + else + endOffset = (thisInstanceIndex - 1) * iTStep + end + end + local instanceData = iT.instanceData + for i =1, iTStep do -- copy data, but fast + instanceData[endOffset + i] = thisInstance[i] + end + + if unitID ~= nil then + local isvalidid + if iT.featureIDs then isvalidid = Spring.ValidFeatureID(unitID) + else isvalidid = Spring.ValidUnitID(unitID) end + if isvalidid == false then + Spring.Echo("Error: Attempted to push an invalid unit/featureID",unitID, "into", iT.myName) + noUpload = true + Spring.Debug.TraceFullEcho(20,20,20,"invalid unit/featureID in " ..iT.myName) + end + iT.indextoUnitID[thisInstanceIndex] = unitID + end + + if noUpload ~= true then --upload or mark as dirty + iT.instanceVBO:Upload(thisInstance, nil, thisInstanceIndex - 1) + --Spring.Echo("pushElementInstance,unitID, iT.unitIDattribID, thisInstanceIndex",unitID, iT.unitIDattribID, thisInstanceIndex) + if unitID ~= nil then + if iT.featureIDs then + iT.instanceVBO:InstanceDataFromFeatureIDs(unitID, iT.unitIDattribID, thisInstanceIndex-1) + else + iT.instanceVBO:InstanceDataFromUnitIDs(unitID, iT.unitIDattribID, thisInstanceIndex-1) + end + end + else + iT.dirty = true + end + + if iT.debug then validateInstanceVBOTable(iT, 'push') end + return instanceID +end + +local function popElementInstance(iT, instanceID, noUpload) + -- iT: instanceTable created with makeInstanceTable + -- instanceID: an optional key given to the item, so it can be easily removed by reference, defaults to the last element of the buffer, but this will screw up the instanceIDtoIndex table if used in mixed keys mode + -- noUpload: prevent the VBO from being uploaded, if you feel like you are going to do a lot of ops and wish to manually upload when done instead + -- returns nil on failure, the the index of the element on success + if instanceID == nil then + Spring.Echo("Tried to remove element with nil instanceID from instanceTable " .. iT.myName) + return nil + end + + if iT.instanceIDtoIndex[instanceID] == nil then -- if key is instanceID yet does not exist, then warn and bail + Spring.Echo("Tried to remove element ",instanceID,'From instanceTable', iT.myName, 'but it does not exist in it') + Spring.Debug.TraceFullEcho(10,10,3, iT.myName) + return nil + end + if iT.usedElements == 0 then -- Dont remove the last element + Spring.Echo("Tried to remove element ",instanceID,'From instanceTable', iT.myName, 'but it should be empty') + return nil + end + + --Fetch the position of the element we want to remove from the 'middle' of the table + local oldElementIndex = iT.instanceIDtoIndex[instanceID] + iT.instanceIDtoIndex[instanceID] = nil -- clean these out + iT.indextoInstanceID[oldElementIndex] = nil + + -- get the index of the last element + local lastElementIndex = iT.usedElements + + -- if this one was already at the end of the queue, do nothing but decrement usedElements and clear mappings + if oldElementIndex == lastElementIndex then + --Spring.Echo("Removed end element of instanceTable", iT.myName) + iT.usedElements = iT.usedElements - 1 + -- if it had a related unitID stored, remove that: + if iT.indextoUnitID then iT.indextoUnitID[oldElementIndex] = nil end + + if iT.debugZombies then + if iT.zombies and iT.zombies[instanceID] then + --Spring.Echo("Good, we are killing a stupid zombie at the end", instanceID, iT.numZombies) + iT.zombies[instanceID] = nil + iT.numZombies = iT.numZombies - 1 + end + end + + else + local lastElementInstanceID = iT.indextoInstanceID[lastElementIndex] + if lastElementInstanceID == nil then -- + Spring.Echo("We somehow have a nil element at the back of the array, which is completely invalid, probably about to crash", iT.myName) + dbgt(iT.instanceIDtoIndex, "instanceIDtoIndex") + dbgt(iT.indextoInstanceID, "indextoInstanceID") + dbgt(iT.indextoUnitID, "indextoUnitID") + end + local iTStep = iT.instanceStep + local endOffset = (iT.usedElements - 1)*iTStep + + iT.instanceIDtoIndex[lastElementInstanceID] = oldElementIndex -- lastElementInstanceID was somehow nil here? + iT.indextoInstanceID[oldElementIndex] = lastElementInstanceID + iT.indextoInstanceID[lastElementIndex] = nil --- somehow this got forgotten? TODO for VBOIDtable + + local oldOffset = (oldElementIndex-1)*iTStep + local instanceData = iT.instanceData + for i = 1, iTStep do + instanceData[oldOffset + i ] = instanceData[endOffset + i] + end + --size_t LuaVBOImpl::Upload(const sol::stack_table& luaTblData, const sol::optional attribIdxOpt, const sol::optional elemOffsetOpt, const sol::optional luaStartIndexOpt, const sol::optional luaFinishIndexOpt) + --Spring.Echo("Removing instanceID",instanceID,"from iT at position", oldElementIndex, "shuffling back at", iT.usedElements,"endoffset=",endOffset,'oldOffset=',oldOffset) + if noUpload ~= true then + --Spring.Echo("Upload", oldElementIndex -1, oldOffset+1, oldOffset+iTStep) + iT.instanceVBO:Upload(iT.instanceData,nil,oldElementIndex-1,oldOffset +1,oldOffset + iTStep) + else + iT.dirty = true + end + -- Do the unitID shuffle if needed: + if iT.indextoUnitID then + --Spring.Echo("popElementInstance,unitID, iT.unitIDattribID, thisInstanceIndex",unitID, iT.unitIDattribID, oldElementIndex) + local popunitID = iT.indextoUnitID[lastElementIndex] + if popunitID == nil then + Spring.Echo("TODO: what the f is happening here?, how the f could we have popped a nil from the back of?", iT.myName) -- TODO TODO + end + + if iT.debugZombies then + local gf = Spring.GetGameFrame() + --Spring.Echo("Popping", instanceID) + if iT.lastpopgameframe == nil then + iT.lastpopgameframe = gf + iT.zombies = {} + iT.numZombies = 0 + else + if iT.lastpopgameframe ~= gf then -- New gameframe + iT.lastpopgameframe = gf + if iT.numZombies and iT.numZombies > 0 then -- WE HAVE ZOMBIES AAAAARGH + local s = "Warning: We have " .. tostring(iT.numZombies) .. " zombie units left over in " .. iT.myName + for zombie, gf in pairs(iT.zombies) do + s = s .. " " .. tostring(zombie) ..'/'..tostring(gf) + Spring.Echo("ZOMBIE instanceID", zombie, 'gf',gf) + --Spring.SendCommands({"pause 1"}) + Spring.Debug.TraceFullEcho(nil,nil,nil, iT.myName) + end + Spring.Echo(s) + iT.zombies = {} + iT.numZombies = 0 + end + else -- same gameframe + if iT.zombies[instanceID] then + --Spring.Echo("Good, we are killing a stupid zombie", gf, instanceID, iT.numZombies) + iT.zombies[instanceID] = nil + iT.numZombies = iT.numZombies - 1 + end + end + end + end + + iT.indextoUnitID[oldElementIndex] = popunitID + iT.indextoUnitID[lastElementIndex] = nil + + if (iT.featureIDs and Spring.ValidFeatureID(popunitID)) or Spring.ValidUnitID(popunitID) then + if noUpload ~= true then + if iT.featureIDs then + iT.instanceVBO:InstanceDataFromFeatureIDs(popunitID, iT.unitIDattribID, oldElementIndex-1) + else + iT.instanceVBO:InstanceDataFromUnitIDs(popunitID, iT.unitIDattribID, oldElementIndex-1) + end + end + else + if iT.debugZombies then + --Spring.Echo("Warning: Tried to pop back an invalid" .. ((iT.featureIDs and "featureID") or "unitID"), popunitID, "from", iT.myName, "while removing instance", instanceID, counttable(iT.instanceIDtoIndex), counttable(iT.indextoInstanceID), counttable(iT.indextoUnitID)) + --Spring.Debug.TraceFullEcho() + local gf = Spring.GetGameFrame() + if iT.lastpopgameframe == nil or iT.lastpopgameframe ~= gf then -- New gameframe + iT.lastpopgameframe = gf + iT.zombies = {} + iT.numZombies = 0 + end + if iT.zombies[lastElementInstanceID] == nil then + iT.zombies[lastElementInstanceID] = gf + iT.numZombies = iT.numZombies + 1 + end + end + end + end + iT.usedElements = iT.usedElements - 1 + end + + if iT.debug then validateInstanceVBOTable(iT,'pop') end + return oldElementIndex +end + +local function getElementInstanceData(iT, instanceID, cacheTable) + -- iT: instanceTable created with makeInstanceTable + -- instanceID: an optional key given to the item, so it can be easily removed by reference, defaults to the index of the instance in the buffer (1 based) + local instanceIndex = iT.instanceIDtoIndex[instanceID] + if instanceIndex == nil then + Spring.Echo("Tried to getElementInstanceData from",iT.myName,instanceID, "but it does not exist") + return nil + end + local iData = cacheTable or {} + local iTStep = iT.instanceStep + instanceIndex = (instanceIndex-1) * iTStep + local instanceData = iT.instanceData + for i = 1, iTStep do + iData[i] = instanceData[instanceIndex + i] + end + return iData +end + +local function uploadAllElements(iT) + -- upload all USED elements + if iT.usedElements == 0 then return end + + iT.instanceVBO:Upload(iT.instanceData,nil,0, 1, iT.usedElements * iT.instanceStep) + iT.dirty = false + if iT.indextoUnitID then + if iT.featureIDs then + iT.instanceVBO:InstanceDataFromFeatureIDs(iT.indextoUnitID, iT.unitIDattribID) + else + iT.instanceVBO:InstanceDataFromUnitIDs(iT.indextoUnitID, iT.unitIDattribID) + end + end +end + +local function uploadElementRange(iT, startElementIndex, endElementIndex) + iT.instanceVBO:Upload(iT.instanceData, -- The lua mirrored VBO data + nil, -- the attribute index, nil for all attributes + startElementIndex, -- vboOffset optional, , what ELEMENT offset of the VBO to start uploading into, 0 based + startElementIndex * iT.instanceStep + 1, -- luaStartIndex, default 1, what element of the lua array to start uploading from. 1 is the 1st element of a lua table. + endElementIndex * iT.instanceStep --] luaEndIndex, default #{array}, what element of the lua array to upload up to, inclusively + ) + if iT.indextoUnitID then + --we need to reslice the table + local unitIDRange = {} + local indextoUnitID = iT.indextoUnitID + for i = startElementIndex, endElementIndex do + unitIDRange[#unitIDRange + 1] = indextoUnitID[i] + end + if iT.featureIDs then + iT.instanceVBO:InstanceDataFromFeatureIDs(unitIDRange, iT.unitIDattribID, startElementIndex - 1) + else + iT.instanceVBO:InstanceDataFromUnitIDs(unitIDRange, iT.unitIDattribID, startElementIndex - 1) + end + end +end + +-- This function allows for order-preserving compacting of a list of instances based on these funcs. +-- It is designed for Decals GL4, where draw order matters a lot! +-- remove takes priority over keep +local function compactInstanceVBO(iT, removelist, keeplist) + local usedElements = iT.usedElements + if usedElements == 0 then return 0 end + local instanceStep = iT.instanceStep + local instanceData = iT.instanceData + local indextoInstanceID = iT.indextoInstanceID + local newindextoInstanceID = {} + local newinstanceIDtoIndex = {} + local newUsedElements = 0 + local numremoved = 0 + local removemode = (removelist ~= nil) and (keeplist == nil) + for index, instanceID in ipairs(indextoInstanceID) do + -- If its in keeplist, + if (removemode and (removelist[instanceID]== nil) ) or ((removemode == false) and keeplist[instanceID]) then + local instanceOffset = (index-1) * instanceStep + local newInstanceOffset = newUsedElements * instanceStep + for i = 1, instanceStep do + instanceData[newInstanceOffset + i] = instanceData[instanceOffset + i] + end + newUsedElements = newUsedElements + 1 + newindextoInstanceID[newUsedElements] = instanceID + newinstanceIDtoIndex[instanceID] = newUsedElements + else + numremoved = numremoved + 1 + end + end + if numremoved > 0 then + iT.dirty = true -- we set the flag to notify that CPU and GPU contents dont match! + iT.usedElements = newUsedElements + iT.instanceIDtoIndex = newinstanceIDtoIndex + iT.indextoInstanceID = newindextoInstanceID + end + return numremoved +end + +local function drawInstanceVBO(iT) + if iT.usedElements > 0 then + if iT.indexVBO then + iT.VAO:DrawElements(iT.primitiveType, iT.numVertices, 0, iT.usedElements,0) + else + iT.VAO:DrawArrays(iT.primitiveType, iT.numVertices, 0, iT.usedElements,0) + end + end +end + +local function countInvalidUnitIDs(iT) + local invalids = {} + for i, objectID in ipairs(iT.indextoUnitID) do + local isValidID = false + if iT.featureIDs then isValidID = Spring.ValidFeatureID(objectID) + else isValidID = Spring.ValidUnitID(objectID) end + if isValidID then + + else + invalids[#invalids + 1] = objectID + end + end + if #invalids > 0 then + Spring.Echo(#invalids, "invalid IDs found in ", iT.myName) + end + return invalids +end + + +--------- HELPERS FOR PRIMITIVES ------------------ + +local function makeCircleVBO(circleSegments, radius, startCenter, name) + -- Makes circle of radius in xy space + -- can be used in both GL.LINES and GL.TRIANGLE_FAN mode + -- Startcenter places a vertex in the center, this is nice for triangle fans, + -- but when drawing lines with this vbo, start at an offset of 1 + -- Fun note: its NOT faster to draw stenciled circles with this. + if not radius then radius = 1 end + circleSegments = circleSegments -1 -- for po2 buffers + local circleVBO = gl.GetVBO(GL.ARRAY_BUFFER,true) + if circleVBO == nil then return nil end + + local VBOLayout = { + {id = 0, name = "position", size = 4}, + } + + local VBOData = {} + if startCenter then + VBOData[#VBOData+1] = 0 -- X + VBOData[#VBOData+1] = 0 -- Y + VBOData[#VBOData+1] = 0 -- circumference [0-1] + VBOData[#VBOData+1] = radius + end + + for i = 0, circleSegments do -- this is +1 + VBOData[#VBOData+1] = math.sin(math.pi*2* i / circleSegments) * radius -- X + VBOData[#VBOData+1] = math.cos(math.pi*2* i / circleSegments) * radius-- Y + VBOData[#VBOData+1] = i / circleSegments -- circumference [0-1] + VBOData[#VBOData+1] = radius + end + + circleVBO:Define( + circleSegments + 1 + (startCenter and 1 or 0) , -- +1 for center point if startCenter is true + VBOLayout + ) + circleVBO:Upload(VBOData) + if gldebugannotations then + gl.ObjectLabel(GL_BUFFER, circleVBO:GetID(), name or "CircleVBO") + end + return circleVBO, #VBOData/4 +end + +local function makePlaneVBO(xsize, ysize, xresolution, yresolution, name) -- makes a plane from [-xsize to xsize] with xresolution subdivisions + if not xsize then xsize = 1 end + if not ysize then ysize = xsize end + if not xresolution then xresolution = 1 end + if not yresolution then yresolution = xresolution end + xresolution = math.floor(xresolution) + yresolution = math.floor(yresolution) + local planeVBO = gl.GetVBO(GL.ARRAY_BUFFER,false) + if planeVBO == nil then return nil end + + local VBOLayout = { + {id = 0, name = "xyworld_xyfract", size = 2}, + } + + local VBOData = {} + + for x = 0, xresolution do -- this is +1 + for y = 0, yresolution do + VBOData[#VBOData+1] = xsize * ((x / xresolution) -0.5 ) *2 + VBOData[#VBOData+1] = ysize * ((y / yresolution) -0.5 ) * 2 + end + end + + planeVBO:Define( + (xresolution + 1) * (yresolution + 1) , + VBOLayout + ) + planeVBO:Upload(VBOData) + + if gldebugannotations then + gl.ObjectLabel(GL_BUFFER, planeVBO:GetID(), name or "PlaneVBO") + end + + --Spring.Echo("PlaneVBOData up:",#VBOData, "Down", #planeVBO:Download()) + return planeVBO, #VBOData/2 +end + +local function makePlaneIndexVBO(xresolution, yresolution, cutcircle, name) + xresolution = math.floor(xresolution) + if not yresolution then yresolution = xresolution end + local planeIndexVBO = gl.GetVBO(GL.ELEMENT_ARRAY_BUFFER,false) + if planeIndexVBO == nil then return nil end + + local function xyinrad(lx, ly) + local px = (lx / xresolution) * 2 - 1 + local py = (ly / yresolution) * 2 - 1 + return (px*px + py*py) <= 1 + end + + local IndexVBOData = {} + local qindex = 0 + local colsize = yresolution + 1 + for x = 0, xresolution-1 do -- this is +1 + for y = 0, yresolution-1 do + --this is only 20% optimization + if cutcircle == nil or (xyinrad(x,y) or xyinrad(x + 1,y) or xyinrad(x,y + 1 )) then + -- top left one + IndexVBOData[#IndexVBOData + 1] = qindex + IndexVBOData[#IndexVBOData + 1] = qindex +1 + IndexVBOData[#IndexVBOData + 1] = qindex + colsize + end + + if cutcircle == nil or (xyinrad(x+1,y+1) or xyinrad(x + 1,y) or xyinrad(x,y + 1 )) then + -- bottom right one? + IndexVBOData[#IndexVBOData + 1] = qindex +1 + IndexVBOData[#IndexVBOData + 1] = qindex + colsize + 1 + IndexVBOData[#IndexVBOData + 1] = qindex + colsize + end + qindex = qindex + 1 + + end + qindex = qindex + 1 + end + planeIndexVBO:Define( + # IndexVBOData + ) + planeIndexVBO:Upload(IndexVBOData) + + if gldebugannotations then + gl.ObjectLabel(GL_BUFFER, planeIndexVBO:GetID(), name or "planeIndexVBO") + end + --Spring.Echo("PlaneIndexVBO up:",#IndexVBOData, "Down", #planeIndexVBO:Download()) + return planeIndexVBO, IndexVBOData +end + +local function makePointVBO(numPoints, randomFactor, name) + -- makes points with xyzw + -- can be used in both GL.LINES and GL.TRIANGLE_FAN mode + numPoints = numPoints or 1 + randomFactor = randomFactor or 0 + local pointVBO = gl.GetVBO(GL.ARRAY_BUFFER,true) + if pointVBO == nil then return nil end + + local VBOLayout = { + {id = 0, name = "position_w", size = 4}, + } + + local VBOData = {} + + for i = 1, numPoints do -- + VBOData[#VBOData+1] = randomFactor * math.random()-- X + VBOData[#VBOData+1] = randomFactor * math.random()-- Y + VBOData[#VBOData+1] = randomFactor * math.random()---Z + VBOData[#VBOData+1] = i/numPoints -- index for lolz? + end + + pointVBO:Define( + numPoints, + VBOLayout + ) + pointVBO:Upload(VBOData) + + if gldebugannotations then + gl.ObjectLabel(GL_BUFFER, pointVBO:GetID(), name or "pointVBO") + end + return pointVBO, numPoints +end + +local function makeRectVBO(minX,minY, maxX, maxY, minU, minV, maxU, maxV, name) + if minX == nil then + minX, minY, maxX, maxY, minU, minV, maxU, maxV = 0,0,1,1,0,0,1,1 + end + -- makes points with xyzw + -- can be used in both GL.LINES and GL.TRIANGLE_FAN mode + local rectVBO = gl.GetVBO(GL.ARRAY_BUFFER,false) + if rectVBO == nil then return nil end + + local VBOLayout = { + {id = 0, name = "position_xy_uv", size = 4}, + } + + local VBOData = { + --bl + minX,minY, minU, minV, --bl + minX,maxY, minU, maxV, --tr + maxX,maxY, maxU, maxV, --tr + maxX,maxY, maxU, maxV, --tr + maxX,minY, maxU, minV, --br + minX,minY, minU, minV, --bl + } + + rectVBO:Define( + 6, + VBOLayout + ) + rectVBO:Upload(VBOData) + + if gldebugannotations then + gl.ObjectLabel(GL_BUFFER, rectVBO:GetID(), name or "rectVBO") + end + return rectVBO, 6 +end + +local function makeRectIndexVBO(name) + local rectIndexVBO = gl.GetVBO(GL.ELEMENT_ARRAY_BUFFER,false) + if rectIndexVBO == nil then return nil end + + rectIndexVBO:Define( + 6 + ) + rectIndexVBO:Upload({0,1,2,3,4,5}) + if gldebugannotations then + gl.ObjectLabel(GL_BUFFER, rectIndexVBO:GetID(), name or "rectIndexVBO") + end + return rectIndexVBO,6 +end + + + +local function makeConeVBO(numSegments, height, radius, name) + -- make a cone that points up, (y = height), with radius specified + -- returns the VBO object, and the number of elements in it (usually == numvertices) + -- needs GL.TRIANGLES + if not height then height = 1 end + if not radius then radius = 1 end + local coneVBO = gl.GetVBO(GL.ARRAY_BUFFER,true) + if coneVBO == nil then return nil end + + local VBOData = {} + + for i = 1, numSegments do + -- center vertex + VBOData[#VBOData+1] = 0 + VBOData[#VBOData+1] = 0 + VBOData[#VBOData+1] = 0 + VBOData[#VBOData+1] = (i - 1) / numSegments + + --- first cone flat + VBOData[#VBOData+1] = math.sin(math.pi*2* (i - 1) / numSegments) * radius -- X + VBOData[#VBOData+1] = 0 + VBOData[#VBOData+1] = -1* math.cos(math.pi*2* (i - 1) / numSegments) * radius-- Y + VBOData[#VBOData+1] = (i - 1) / numSegments + + --- second cone flat + VBOData[#VBOData+1] = math.sin(math.pi*2* (i - 0) / numSegments) * radius-- X + VBOData[#VBOData+1] = 0 + VBOData[#VBOData+1] = -1* math.cos(math.pi*2* (i - 0) / numSegments) * radius -- Y + VBOData[#VBOData+1] =(i - 0) / numSegments + + -- top vertex + VBOData[#VBOData+1] = 0 + VBOData[#VBOData+1] = height + VBOData[#VBOData+1] = 0 + VBOData[#VBOData+1] = (i - 1) / numSegments + + --- first cone flat + VBOData[#VBOData+1] = math.sin(math.pi*2* (i - 0) / numSegments) * radius -- X + VBOData[#VBOData+1] = 0 + VBOData[#VBOData+1] = -1*math.cos(math.pi*2* (i - 0) / numSegments) * radius -- Y + VBOData[#VBOData+1] =(i - 0) / numSegments + + --- second cone flat + VBOData[#VBOData+1] = math.sin(math.pi*2* (i - 1) / numSegments) * radius -- X + VBOData[#VBOData+1] = 0 + VBOData[#VBOData+1] = -1*math.cos(math.pi*2* (i - 1) / numSegments) * radius -- Y + VBOData[#VBOData+1] =(i - 1) / numSegments + end + + + coneVBO:Define(#VBOData/4, {{id = 0, name = "localpos_progress", size = 4}}) + coneVBO:Upload(VBOData) + + if gldebugannotations then + gl.ObjectLabel(GL_BUFFER, coneVBO:GetID(), name or "coneVBO") + end + + return coneVBO, #VBOData/4 +end + + + +local function makeCylinderVBO(numSegments, height, radius, hastop, hasbottom, name) + -- make a cylinder that points up, (y = height), with radius specified + -- returns the VBO object, and the number of elements in it (usually == numvertices) + -- needs GL.TRIANGLES + if not height then height = 1 end + if not radius then radius = 1 end + local cylinderVBO = gl.GetVBO(GL.ARRAY_BUFFER,true) + if cylinderVBO == nil then return nil end + + local VBOData = {} + + for i = 1, numSegments do + if hasbottom then + -- center vertex + VBOData[#VBOData+1] = 0 + VBOData[#VBOData+1] = -1* height + VBOData[#VBOData+1] = 0 + VBOData[#VBOData+1] = (i - 1) / numSegments + + --- first cone flat + VBOData[#VBOData+1] = math.sin(math.pi*2* (i - 1) / numSegments) * radius -- X + VBOData[#VBOData+1] = -1* height + VBOData[#VBOData+1] = -1* math.cos(math.pi*2* (i - 1) / numSegments) * radius-- Y + VBOData[#VBOData+1] = (i - 1) / numSegments + + --- second cone flat + VBOData[#VBOData+1] = math.sin(math.pi*2* (i - 0) / numSegments) * radius-- X + VBOData[#VBOData+1] = -1* height + VBOData[#VBOData+1] = -1* math.cos(math.pi*2* (i - 0) / numSegments) * radius -- Y + VBOData[#VBOData+1] =(i - 0) / numSegments + end + + + --- first cone flat + VBOData[#VBOData+1] = math.sin(math.pi*2* (i - 0) / numSegments) * radius -- X + VBOData[#VBOData+1] = height + VBOData[#VBOData+1] = -1*math.cos(math.pi*2* (i - 0) / numSegments) * radius -- Y + VBOData[#VBOData+1] =(i - 0) / numSegments + + --- second cone flat + VBOData[#VBOData+1] = math.sin(math.pi*2* (i - 1) / numSegments) * radius -- X + VBOData[#VBOData+1] = height + VBOData[#VBOData+1] = -1*math.cos(math.pi*2* (i - 1) / numSegments) * radius -- Y + VBOData[#VBOData+1] =(i - 1) / numSegments + + + + --- first cone flat + VBOData[#VBOData+1] = math.sin(math.pi*2* (i - 0) / numSegments) * radius -- X + VBOData[#VBOData+1] = -1 * height + VBOData[#VBOData+1] = -1*math.cos(math.pi*2* (i - 0) / numSegments) * radius -- Y + VBOData[#VBOData+1] =(i - 0) / numSegments + + --- second cone flat + VBOData[#VBOData+1] = math.sin(math.pi*2* (i - 1) / numSegments) * radius -- X + VBOData[#VBOData+1] = height + VBOData[#VBOData+1] = -1*math.cos(math.pi*2* (i - 1) / numSegments) * radius -- Y + VBOData[#VBOData+1] =(i - 1) / numSegments + + + --- first cone flat + VBOData[#VBOData+1] = math.sin(math.pi*2* (i - 0) / numSegments) * radius -- X + VBOData[#VBOData+1] = -1 * height + VBOData[#VBOData+1] = -1*math.cos(math.pi*2* (i - 0) / numSegments) * radius -- Y + VBOData[#VBOData+1] =(i - 0) / numSegments + + + --- second cone flat + VBOData[#VBOData+1] = math.sin(math.pi*2* (i - 1) / numSegments) * radius -- X + VBOData[#VBOData+1] = -1 * height + VBOData[#VBOData+1] = -1*math.cos(math.pi*2* (i - 1) / numSegments) * radius -- Y + VBOData[#VBOData+1] =(i - 1) / numSegments + + + + if hastop then + -- center vertex + VBOData[#VBOData+1] = 0 + VBOData[#VBOData+1] = height + VBOData[#VBOData+1] = 0 + VBOData[#VBOData+1] = (i - 1) / numSegments + + --- first cone flat + VBOData[#VBOData+1] = math.sin(math.pi*2* (i - 1) / numSegments) * radius -- X + VBOData[#VBOData+1] = height + VBOData[#VBOData+1] = -1* math.cos(math.pi*2* (i - 1) / numSegments) * radius-- Y + VBOData[#VBOData+1] = (i - 1) / numSegments + + --- second cone flat + VBOData[#VBOData+1] = math.sin(math.pi*2* (i - 0) / numSegments) * radius-- X + VBOData[#VBOData+1] = height + VBOData[#VBOData+1] = -1* math.cos(math.pi*2* (i - 0) / numSegments) * radius -- Y + VBOData[#VBOData+1] =(i - 0) / numSegments + end + end + + + cylinderVBO:Define(#VBOData/4, {{id = 0, name = "localpos_progress", size = 4}}) + cylinderVBO:Upload(VBOData) + + if gldebugannotations then + gl.ObjectLabel(GL_BUFFER, cylinderVBO:GetID(), name or "cylinderVBO") + end + + return cylinderVBO, #VBOData/4 +end + + + +local function makeBoxVBO(minX, minY, minZ, maxX, maxY, maxZ, name) -- make a box + -- needs GL.TRIANGLES + local boxVBO = gl.GetVBO(GL.ARRAY_BUFFER,true) + if boxVBO == nil then return nil end + + local VBOData = { + minX,minY,minZ,0 + ,minX,minY,maxZ,0 + ,minX,maxY,maxZ,0 + ,maxX,maxY,minZ,0 + ,minX,minY,minZ,0 + ,minX,maxY,minZ,0 + ,maxX,minY,maxZ,0 + ,minX,minY,minZ,0 + ,maxX,minY,minZ,0 + ,maxX,maxY,minZ,0 + ,maxX,minY,minZ,0 + ,minX,minY,minZ,0 + ,minX,minY,minZ,0 + ,minX,maxY,maxZ,0 + ,minX,maxY,minZ,0 + ,maxX,minY,maxZ,0 + ,minX,minY,maxZ,0 + ,minX,minY,minZ,0 + ,minX,maxY,maxZ,0 + ,minX,minY,maxZ,0 + ,maxX,minY,maxZ,0 + ,maxX,maxY,maxZ,0 + ,maxX,minY,minZ,0 + ,maxX,maxY,minZ,0 + ,maxX,minY,minZ,0 + ,maxX,maxY,maxZ,0 + ,maxX,minY,maxZ,0 + ,maxX,maxY,maxZ,0 + ,maxX,maxY,minZ,0 + ,minX,maxY,minZ,0 + ,maxX,maxY,maxZ,0 + ,minX,maxY,minZ,0 + ,minX,maxY,maxZ,0 + ,maxX,maxY,maxZ,0 + ,minX,maxY,maxZ,0 + ,maxX,minY,maxZ,0 + } + boxVBO:Define(#VBOData/4, {{id = 0, name = "localpos_progress", size = 4}}) + boxVBO:Upload(VBOData) + + if gldebugannotations then + gl.ObjectLabel(GL_BUFFER, boxVBO:GetID(), name or "boxVBO") + end + + return boxVBO, #VBOData/4 +end + + + +---Generate a sphere vertex VBO and the corresponding indexVBO +---The sphere is oriented in the Z direction +---Layout: +---{id = 0, name = "position", size = 4}, -- cake slices along Z, w is sector angle. +---{id = 1, name = "normals", size = 3}, -- normal vector +---{id = 2, name = "uvs", size = 2}, -- UV vector, where x goes around the belly and y goes along Z +---@param sectorCount number is the number of orange slices around the belly in XY +---@param stackCount number how many horizontal slices along Z, usually less than sectorcount +---@param radius number how many elmos in radius, default 1 +local function makeSphereVBO(sectorCount, stackCount, radius, name) -- http://www.songho.ca/opengl/gl_sphere.html + + + local sphereVBO = gl.GetVBO(GL.ARRAY_BUFFER,true) + if sphereVBO == nil then return nil end + local vertVBOLayout = { + {id = 0, name = "position", size = 4}, + {id = 1, name = "normals", size = 3}, + {id = 2, name = "uvs", size = 2}, + } + + local VBOData = {} + radius = radius or 1 + local x, y, z, xy; -- vertex position + local nx, ny, nz + local lengthInv = 1.0 / radius; -- vertex normal + local s, t; -- vertex texCoord + + local sectorStep = 2 * math.pi / sectorCount; + local stackStep = math.pi / stackCount; + local sectorAngle, stackAngle; + + for i = 0, stackCount do + + stackAngle = math.pi / 2 - i * stackStep; -- starting from pi/2 to -pi/2 + xy = radius * math.cos(stackAngle); -- r * cos(u) + z = radius * math.sin(stackAngle); -- r * sin(u) + + -- add (sectorCount+1) vertices per stack + -- the first and last vertices have same position and normal, but different tex coords + for j = 0, sectorCount do -- for (int j = 0; j <= sectorCount; ++j) + + sectorAngle = j * sectorStep; -- starting from 0 to 2pi + + -- vertex position (x, y, z) + x = xy * math.cos(sectorAngle); -- r * cos(u) * cos(v) + y = xy * math.sin(sectorAngle); -- r * cos(u) * sin(v) + VBOData[#VBOData + 1] = x; + VBOData[#VBOData + 1] = y; + VBOData[#VBOData + 1] = z; + VBOData[#VBOData + 1] = sectorAngle; + --Spring.Echo(x,y,z) + -- normalized vertex normal (nx, ny, nz) + nx = x * lengthInv; + ny = y * lengthInv; + nz = z * lengthInv; + + + VBOData[#VBOData + 1] = nx; + VBOData[#VBOData + 1] = ny; + VBOData[#VBOData + 1] = nz; + + -- vertex tex coord (s, t) range between [0, 1] + s = j / sectorCount; + t = i / stackCount; + + VBOData[#VBOData + 1] = s; + VBOData[#VBOData + 1] = t; + end + end + sphereVBO:Define(#VBOData/9, vertVBOLayout) + sphereVBO:Upload(VBOData) + + if gldebugannotations then + gl.ObjectLabel(GL_BUFFER, sphereVBO:GetID(), name or "sphereVBO") + end + + local numVerts = #VBOData/9 + + local sphereIndexVBO = gl.GetVBO(GL.ELEMENT_ARRAY_BUFFER,false) + VBOData = {} + + -- generate CCW index list of sphere triangles + -- k1--k1+1 + -- | / | + -- | / | + -- k2--k2+1 + local k1, k2 + for i = 0, stackCount-1 do -- for(int i = 0; i < stackCount; ++i) + + k1 = i * (sectorCount + 1) -- beginning of current stack + k2 = k1 + sectorCount + 1 -- beginning of next stack + + for j = 0, sectorCount-1 do --for(int j = 0; j < sectorCount; ++j, ++k1, ++k2) + -- Spring.Echo('indices', k1, k2) + -- 2 triangles per sector excluding first and last stacks + -- k1 => k2 => k1+1 + if i ~= 0 then + + VBOData[#VBOData + 1] = k1 + VBOData[#VBOData + 1] = k2 + VBOData[#VBOData + 1] = k1 + 1 + end + + -- k1+1 => k2 => k2+1 + if i ~= (stackCount-1) then + + VBOData[#VBOData + 1] = k1 + 1 + VBOData[#VBOData + 1] = k2 + VBOData[#VBOData + 1] = k2 + 1 + + end + + k1 = k1 + 1 + k2 = k2 + 1 + end + end + + + sphereIndexVBO:Define(#VBOData) + sphereIndexVBO:Upload(VBOData) + + if gldebugannotations then + gl.ObjectLabel(GL_BUFFER, sphereIndexVBO:GetID(), name or "sphereIndexVBO") + end + + return sphereVBO, numVerts, sphereIndexVBO, #VBOData +end + + +local function MakeTexRectVAO(minX,minY, maxX, maxY, minU, minV, maxU, maxV, name) + -- Draw with myGL4TexRectVAO:DrawArrays(GL.TRIANGLES) + minX,minY,maxX,maxY,minU,minV,maxU,maxV = minX or -1,minY or -1,maxX or 1, maxY or 1, minU or 0, minV or 0, maxU or 1, maxV or 1 + + local myGL4TexRectVAO + local rectVBO = gl.GetVBO(GL.ARRAY_BUFFER,false) + if rectVBO == nil then return nil end + + --rectVBO:Define( 6, {{id = 0, name = "position_xy_uv", size = 8}}) + local z = 0.5 + local w = 1 + rectVBO:Define( 6, {{id = 0, name = "pos", size = 4}}) + rectVBO:Upload({ + + minX,minY, minU, minV, --bl + maxX,maxY, maxU, maxV, --tr + minX,maxY, minU, maxV, --tl + maxX,maxY, maxU, maxV, --tr + minX,minY, minU, minV, --bl + maxX,minY, maxU, minV, --br + }) + + + if gldebugannotations then + gl.ObjectLabel(GL_BUFFER, rectVBO:GetID(), name or "rectVBO") + end + + myGL4TexRectVAO = gl.GetVAO() + if myGL4TexRectVAO == nil then return nil end + myGL4TexRectVAO:AttachVertexBuffer(rectVBO) + return myGL4TexRectVAO +end + +return { + makeInstanceVBOTable = makeInstanceVBOTable, + clearInstanceTable = clearInstanceTable, + makeVAOandAttach = makeVAOandAttach, + locateInvalidUnits = locateInvalidUnits, + pushElementInstance = pushElementInstance, + popElementInstance = popElementInstance, + getElementInstanceData = getElementInstanceData, + uploadAllElements = uploadAllElements, + uploadElementRange = uploadElementRange, + compactInstanceVBO = compactInstanceVBO, + drawInstanceVBO = drawInstanceVBO, + makeCircleVBO = makeCircleVBO, + makePlaneVBO = makePlaneVBO, + makePlaneIndexVBO = makePlaneIndexVBO, + makePointVBO = makePointVBO, + makeRectVBO = makeRectVBO, + makeRectIndexVBO = makeRectIndexVBO, + makeConeVBO = makeConeVBO, + makeCylinderVBO = makeCylinderVBO, + makeBoxVBO = makeBoxVBO, + makeSphereVBO = makeSphereVBO, + MakeTexRectVAO = MakeTexRectVAO, +} + +end)() +local tracker=(function()local widget={} +local widget = widget ---@type Widget + +function widget:GetInfo() + return { + name = "API Unit Tracker DEVMODE GL4", + desc = "Manages alliedunitslist, visibleunitslist", + author = "Beherith", + date = "2022.02.18", + license = "GNU GPL, v2 or later", + layer = -828888, + handler = true, + enabled = true, + depends = {'gl4'} + } +end + + +-- Localized Spring API for performance +local spGetGameFrame = Spring.GetGameFrame +local spGetMyTeamID = Spring.GetMyTeamID +local spGetMyAllyTeamID = Spring.GetMyAllyTeamID +local spEcho = Spring.Echo +local spGetAllUnits = Spring.GetAllUnits +local spGetSpectatingState = Spring.GetSpectatingState + +local debuglevel = 0 +-- debuglevel 0 is no debugging +-- debuglevel 1 is show warnings for stuff periodicly and make self crash +-- debuglevel 2 is verbose +-- debuglevel 3 is super verbose mode + +local debugdrawvisible = false +local L_DEPRECATED = LOG.DEPRECATED +-- This widget's job is to provide a common interface for GL4 drawing widgets, that rely on having visible units present +-- Widget draw classes: +-- widgets that draw stuff for all visible units (trivial case) +-- widgets that only draw for allies, turn into widgets that draw for all once you enter specfullview + -- which is pretty much just sensor ranges los + -- rank icons + -- flank icons + +-- TODO: +-- filter decoration unitDefIDs, but not gaia (neutrals) -- done +-- do taken/given correctly by add-remove -- done +-- the callins should all pass unitID, unitDefID, and unitTeam (note the issues with taken unitteams!) +-- remove crashing aircraft - not actually needed methinks, since no bugs came up +-- BIG ASS TODO: dont reinit when in spec mode! +-- -- WE DONT HAVE WIDGETS THAT REMAIN PLAYER ONLY!!!!!!!!!! +-- todo: make debug mode an int (verbosity) -- done +-- todo: make addunit not call callins on reinit -- done +-- todo: make a callout or a WG table entry -- yes we need a wg entry +-- todo: finalize alliedunit/visibleunit differences -- done +-- todo: also pass unitteam, as it must be present! - done +-- todo: fix drawdebugvisible to be changeable - done +-- todo: test this in singleplayer scenarios, and loaded games! + +-- SUPER IMPORTANT: NEVER EVER ADD UNITS TO A VBO TABLE THAT ARE IN unitDefIgnore! +-- As the unit tracker api wont track them as actual units, and wont ever remove them either! + + +local alliedUnits = {} -- table of unitID : unitDefID +local alliedUnitsTeam = {} -- table of unitID : unitTeam +local numAlliedUnits = 0 + +local visibleUnits = {} -- table of unitID : unitDefID +local visibleUnitsTeam = {} -- table of unitID : unitTeam +local numVisibleUnits = 0 + +local unitDefIgnore = {} + +local factoryUnitDefIDs = {} -- key unitdefid, internalname + +local lastknownunitpos = {} -- table on unitID to {x,y,z} + +local gameFrame = spGetGameFrame() + +for unitDefID, unitDef in pairs(UnitDefs) do + if unitDef.customParams and unitDef.customParams.nohealthbars then + --unitDefIgnore[unitDefID] = true + end --ignore debug units + if unitDef.isFactory then + factoryUnitDefIDs[unitDefID] = unitDef.name + end + +end + +--- GL4 STUFF --- + +local LuaShader = gl.LuaShader +local InstanceVBOTable = gl.InstanceVBOTable + +local pushElementInstance = InstanceVBOTable.pushElementInstance +local popElementInstance = InstanceVBOTable.popElementInstance + +local unitTrackerVBO = nil +local unitTrackerShader = nil +local luaShaderDir = "LuaUI/Include/" +local texture = "luaui/images/solid.png" + +local function initGL4() + local DrawPrimitiveAtUnit = VFS.Include(luaShaderDir.."DrawPrimitiveAtUnit.lua") + local InitDrawPrimitiveAtUnit = DrawPrimitiveAtUnit.InitDrawPrimitiveAtUnit + local shaderConfig = DrawPrimitiveAtUnit.shaderConfig -- MAKE SURE YOU READ THE SHADERCONFIG TABLE in DrawPrimitiveAtUnit.lua + shaderConfig.TRANSPARENCY = 0.5 + shaderConfig.ANIMATION = 0 + shaderConfig.HEIGHTOFFSET = 3.99 + -- MATCH CUS position as seed to sin, then pass it through geoshader into fragshader + --shaderConfig.POST_VERTEX = "v_parameters.w = max(-0.2, sin(timeInfo.x * 2.0/30.0 + (v_centerpos.x + v_centerpos.z) * 0.1)) + 0.2; // match CUS glow rate" + unitTrackerVBO, unitTrackerShader = InitDrawPrimitiveAtUnit(shaderConfig, "unitTracker") +end + +-- speedups +local spGetUnitTeam = Spring.GetUnitTeam +local spGetUnitDefID = Spring.GetUnitDefID +local spGetUnitPosition = Spring.GetUnitPosition +local spValidUnitID = Spring.ValidUnitID +local spGetUnitIsDead = Spring.GetUnitIsDead +local spGetUnitLosState = Spring.GetUnitLosState +local spAreTeamsAllied = Spring.AreTeamsAllied +local spGetUnitHealth = Spring.GetUnitHealth + +-- scriptproxies: +--[[ NB: these are proxies, not the actual lua functions currently linked LuaUI-side, + so it is safe to cache them here even if the underlying func changes afterwards ]] +local scriptLuauiVisibleUnitAdded +local scriptLuauiVisibleUnitRemoved +local scriptLuauiVisibleUnitsChanged + +local scriptLuauiAlliedUnitAdded +local scriptLuauiAlliedUnitRemoved +local scriptLuauiAlliedUnitsChanged + +local function Scream(reason, unitID) -- This will pause the game and play some sound to alert anyone in debug mode of issue + --Spring.Debug.TraceFullEcho(nil,nil,nil, reason) + Spring.Debug.TraceEcho('API Unit Tracker error', reason) + if unitID ~= nil then + -- gather as much info as possible about this unitID + local unitDefID = spGetUnitDefID(unitID) + local unitTeam = spGetUnitTeam(unitID) + local ux,uy,uz = spGetUnitPosition(unitID) + spEcho('API Unit Tracker error unitID', unitID, unitDefID and (UnitDefs[unitDefID].name) or "nil", unitTeam, px, pz) + end + if lastknownunitpos[unitID] then + Spring.MarkerAddPoint(lastknownunitpos[unitID][1], lastknownunitpos[unitID][2], lastknownunitpos[unitID][3], lastknownunitpos[unitID][4], true) + end + Spring.Debug.TraceFullEcho() + local unittrackerapinil = nil + unittrackerapinil = unittrackerapinil + 1 -- this intentionally crashes this widget so that it will show up in analytics + if debuglevel >=3 then + Spring.SendCommands({"pause 1"}) + Spring.PlaySoundFile("commanderspawn", 1.0, 'ui') + end +end + +local function alliedUnitsChanged() + if debuglevel >= 2 then Spring.Debug.TraceEcho() end + if Script.LuaUI('AlliedUnitsChanged') then + Script.LuaUI.AlliedUnitsChanged(visibleUnits, numVisibleUnits) + else + if debuglevel > 0 then spEcho("Script.LuaUI.AlliedUnitsChanged() unavailable") end + end +end + +local function alliedUnitsAdd(unitID, unitDefID, unitTeam, silent) + if debuglevel >= 3 then Spring.Debug.TraceEcho(numAlliedUnits) end + if alliedUnits[unitID] then + if debuglevel >= 2 then spEcho("alliedUnitsAdd", "tried to add existing unitID", unitID) end + return + end -- already known + alliedUnits[unitID] = unitDefID + alliedUnitsTeam[unitID] = unitTeam + numAlliedUnits = numAlliedUnits + 1 + if silent then return end + if Script.LuaUI('AlliedUnitAdded') then + Script.LuaUI.AlliedUnitAdded(unitID, unitDefID, unitTeam) + else + if debuglevel >= 1 then spEcho("Script.LuaUI.AlliedUnitAdded() unavailable") end + end + -- call all listeners +end + +local function alliedUnitsRemove(unitID, reason) + if debuglevel >= 3 then Spring.Debug.TraceEcho(numAlliedUnits) end + if alliedUnits[unitID] then + local unitDefID = alliedUnits[unitID] + alliedUnits[unitID] = nil + local unitTeam = alliedUnitsTeam[unitID] + alliedUnitsTeam[unitID] = nil + numAlliedUnits = numAlliedUnits - 1 + -- call all listeners + if Script.LuaUI('AlliedUnitRemoved') then + Script.LuaUI.AlliedUnitRemoved(unitID, unitDefID, unitTeam) + end + else + if debuglevel >= 2 then spEcho("alliedUnitsRemove", "tried to remove non-existing unitID", unitID, reason) end + end +end + +local function GetAlliedUnits() + if debuglevel >= 2 then Spring.Debug.TraceEcho() end + return alliedUnits, numAlliedUnits +end + +local function visibleUnitsChanged() + if debuglevel >=3 then Spring.Debug.TraceEcho() end + if Script.LuaUI('VisibleUnitsChanged') then + Script.LuaUI.VisibleUnitsChanged(visibleUnits, numVisibleUnits) + else + if debuglevel > 0 then spEcho("Script.LuaUI.VisibleUnitsChanged() unavailable") end + end +end + +local instanceVBOCacheTable = { + 96, 32, 8, 8, -- lengthwidthcornerheight + 0, -- teamID + 2, -- how many trianges should we make (2 = cornerrect) + 0, 0, 0, 0, -- the gameFrame (for animations), and any other parameters one might want to add + 0, 1, 0, 1, -- These are our default UV atlas tranformations + 0, 0, 0, 0 -- these are just padding zeros, that will get filled in + } + +local function visibleUnitsAdd(unitID, unitDefID, unitTeam, silent, reason) + if debuglevel >= 3 then Spring.Debug.TraceEcho(numVisibleUnits) end + if visibleUnits[unitID] then -- already known + if debuglevel >= 2 then spEcho("visibleUnitsAdd", "tried to add existing unitID", unitID) end + return + end + visibleUnits[unitID] = unitDefID + visibleUnitsTeam[unitID] = unitTeam + numVisibleUnits = numVisibleUnits + 1 + if debugdrawvisible then + unitTeam = unitTeam or spGetUnitTeam(unitID) or 0 + instanceVBOCacheTable[5] = unitTeam + instanceVBOCacheTable[7] = gameFrame + + pushElementInstance( + unitTrackerVBO, -- push into this Instance VBO Table + instanceVBOCacheTable, + unitID, -- this is the key inside the VBO TAble, + true, -- update existing element + nil, -- noupload, dont use unless you know what you are doing + unitID -- last one should be UNITID? + ) + end + -- call all listeners: + if silent then return end + if Script.LuaUI('VisibleUnitAdded') then + Script.LuaUI.VisibleUnitAdded(unitID, unitDefID, unitTeam, reason) + else + if debuglevel >= 1 then spEcho("Script.LuaUI.VisibleUnitAdded() unavailable") end + end +end + +local function visibleUnitsRemove(unitID, reason) + if debuglevel >= 3 then + Spring.Debug.TraceEcho(numVisibleUnits) + if lastknownunitpos[unitID] then lastknownunitpos[unitID] = nil end + end + if visibleUnits[unitID] then + local unitDefID = visibleUnits[unitID] + visibleUnits[unitID] = nil + local unitTeam = visibleUnitsTeam[unitID] + visibleUnitsTeam[unitID] = nil + numVisibleUnits = numVisibleUnits - 1 + + if debugdrawvisible then + popElementInstance(unitTrackerVBO, unitID) + end + -- call all listeners + if Script.LuaUI('VisibleUnitRemoved') then + Script.LuaUI.VisibleUnitRemoved(unitID, unitDefID, unitTeam, reason) + end + else + if debuglevel >= 2 then spEcho("visibleUnitsRemove", "tried to remove non-existing unitID", unitID, reason) end + end +end + +local function GetVisibleUnits() + if debuglevel >= 2 then Spring.Debug.TraceEcho() end + return visibleUnits, numVisibleUnits +end + +local spec, fullview = spGetSpectatingState() +local myTeamID = spGetMyTeamID() +local myAllyTeamID = spGetMyAllyTeamID() +local myPlayerID = Spring.GetMyPlayerID() + +local function isValidLivingSeenUnit(unitID, unitDefID, verbose) + --[[ + -- This isnt helping + if type(myAllyTeamID) ~= "number" or (type(myAllyTeamID) == "number" and ((myAllyTeamID < 0 ) or (myAllyTeamID > 32))) then + local localMyAllyTeamID = myAllyTeamID + Spring.Debug.TraceFullEcho(nil,nil,nil, "api_unit_tracker_gl4 error on myAllyTeamID") + end + ]]-- + + -- strange, ALL of these will be evaluated, which explains the crash, because according to the evaluation order, + -- unitDef is not nil yet + -- unitID is valid + -- unit + -- SPECTATING SYNTHETIC in that replay from start and /skip 1 DOES THIS SHIT! 20220307_201548_DSDR 4_105.1.1-861-ge8bf8a9 BAR105.sdfz + -- Which is odd, because that commander belongs to petTurtle, who is on the other allyteam anyway, so this shouldnt really ever get called + -- now why that allyteamID is invalid, I dont really know yet, as the allyteamID == 1, which seems sane + + if unitDefID == nil then return false end + if spValidUnitID(unitID) ~= true then return false end + if spGetUnitIsDead(unitID) == true then return false end + if unitDefIgnore[unitDefID] then return false end + if ((not fullview) and (spGetUnitLosState(unitID, myAllyTeamID, true) % 2 == 0)) then return false end + + if debuglevel >= (verbose or 0) then + if unitDefID == nil or + spValidUnitID(unitID) ~= true or + spGetUnitIsDead(unitID) == true or + ((not fullview) and (spGetUnitLosState(unitID, myAllyTeamID, true) % 2 == 0)) or -- outside of LOS + unitDefIgnore[unitDefID] then + if debuglevel >= (verbose or 0) then + Spring.Debug.TraceEcho() + spEcho("not isValidLivingSeenUnit", + 'unitDefID', unitDefID, + 'ValidUnitID', spValidUnitID(unitID), + 'GetUnitIsDead', spGetUnitIsDead(unitID), + 'Ignore', unitDefIgnore[unitDefID], + 'LOSstate', spGetUnitLosState(unitID, myAllyTeamID, true) + ) + end + return false + end + end + + return true +end + + +function widget:UnitCreated(unitID, unitDefID, unitTeam, builderID, reason, silent) -- this was visible at the time + + --[[ + local currentspec, currentfullview = spGetSpectatingState() + local currentAllyTeamID = Spring.GetMyAllyTeamID() + local currentTeamID = spGetMyTeamID() + local currentPlayerID = Spring.GetMyPlayerID() + if true or debuglevel >= 2 then + spEcho("UnitCreated PlayerChanged", + "spec", spec, "->",currentspec, + " fullview:", fullview , "->", currentfullview, + " team:", myTeamID , "->", currentTeamID, + " allyteam:", myAllyTeamID , "->", currentAllyTeamID, + " player:", myPlayerID , "->", currentPlayerID + ) + end + + if gameFrame <= 1000 then + spEcho("UnitCreated Pre-gameFrame", unitID, unitDefID, unitTeam, builderID, reason, silent, gameFrame) + spEcho(UnitDefs[unitDefID].name) + local px, py, pz = Spring.GetUnitPosition(unitID) + spEcho('pos',px, py, pz) + spEcho("Mystate", spec, fullview, myAllyTeamID, myTeamID, myPlayerID ) + end + ]]-- + + if gameFrame <= 0 and not fullview then + local currentAllyTeamID = spGetMyAllyTeamID() + if myAllyTeamID ~= currentAllyTeamID then + widget:PlayerChanged() + end + end + + unitDefID = unitDefID or spGetUnitDefID(unitID) + if debuglevel >= 3 then spEcho("UnitCreated", unitID, unitDefID and UnitDefs[unitDefID].name, unitTeam, reason) end + + if isValidLivingSeenUnit(unitID, unitDefID, 3) == false then return end + + -- Units that are cheated or spawned will fire unitcreated, then unitfinished right after each other + -- In this case, their health is already maxhealth, and their buildprogress is 0. + -- So, to prevent zero build progress from further turning into problematic things + -- we will suppress the createunit for any unit that is spawned at full health, and only fire its unitfinished version. + -- So we are relying on UnitFinished to be called right after this one + -- Sensibly enough, this is not a problem for players, as they see the units only after their LOS status is checked, later in the same gameframe. + -- So spectators, and 'own team' suffers this hit only + local health,maxhealth, paralyzeDamage,captureProgress,buildProgress = spGetUnitHealth(unitID) + if health == maxhealth and buildProgress == 0 then + if debuglevel >= 3 then + spEcho("Skipping visibleUnitsAdd for CreateUnit'ed unit", UnitDefs[unitDefID].name, unitID, unitDefID, unitTeam, builderID, reason, silent) + end + return + end + + -- alliedunits + if spAreTeamsAllied(unitTeam, myTeamID) then + alliedUnitsAdd(unitID, unitDefID, unitTeam, silent) + end + + -- visibleUnits + if visibleUnits[unitID] == nil then + visibleUnitsAdd(unitID, unitDefID, unitTeam, silent, reason) + end +end + +function widget:UnitDestroyed(unitID, unitDefID, unitTeam, attackerID, attackerDefID, attackerTeam, weaponDefID, reason) + if debuglevel >= 3 then + unitDefID = unitDefID or spGetUnitDefID(unitID) + spEcho("UnitDestroyed",unitID, unitDefID and UnitDefs[unitDefID].name, unitTeam, nil, nil, nil, nil, reason) + end + visibleUnitsRemove(unitID, reason or "UnitDestroyed") + alliedUnitsRemove(unitID, reason or "UnitDestroyed") +end + +--function widget:CrashingAircraft(unitID, unitDefID, teamID) + --spEcho("Global:GadgetCrashingAircraft",unitID, unitDefID, teamID) +--end + + +--function widget:UnitDestroyedByTeam(unitID, unitDefID, unitTeam) + --alliedUnitsRemove(unitID) + --visibleUnitsRemove(unitID) +--end + +function widget:UnitFinished(unitID, unitDefID, unitTeam) -- todo, this should probably add-remove a unit + widget:UnitDestroyed(unitID, unitDefID, unitTeam, nil, nil, nil, nil, "UnitFinished") + widget:UnitCreated(unitID, unitDefID, unitTeam, nil, "UnitFinished") + if unitTeam == myTeamID and factoryUnitDefIDs[unitDefID] then + widgetHandler:AddSpadsMessage("UnitFinished:"..tostring(factoryUnitDefIDs[unitDefID])) + end +end + +function widget:UnitTaken(unitID, unitDefID, oldTeam, newTeam) --1. this is only called when one if my units gets captured + widget:UnitDestroyed(unitID, unitDefID, oldTeam, nil, nil, nil, nil, "UnitTaken") + -- not needed, as the unit will call enemyenteredlos, but what if we are spec? + if not fullview then + -- todo, look at this real closely if its even needed! + --widget:UnitCreated(unitID, unitDefID, newTeam, nil, "UnitTaken") + end +end + +function widget:UnitGiven(unitID, unitDefID, newTeam, oldTeam) --2. this is only called when my team captures a unit + widget:UnitDestroyed(unitID, unitDefID, oldTeam, nil, nil, nil, nil, "UnitGiven") -- to ensure that team changes will trigger from this! + widget:UnitCreated(unitID, unitDefID, newTeam, nil, "UnitGiven") +end + +-- one of the most difficult test cases here, when the transfer of a unit happens between two other teams (1 and 2, we are 0) +-- only the unitenteredlos part gets called for us! +-- this is quite a severe problem, as we can see that only the unitenteredlos/radar gets recalled! +-- solution: in the api_widget_events gadget, we need to forward this too! + +--[[ +[t=00:04:53.877051][f=0004348] g:UnitTaken, 24007, armacv, 2, 1 +[t=00:04:53.877107][f=0004348] g:UnitEnteredLos, 24007, 1 +[t=00:04:53.877163][f=0004348] w:UnitEnteredLos, 24007, 1 +[t=00:04:53.877198][f=0004348] g:UnitEnteredRadar, 24007, 1 +[t=00:04:53.877213][f=0004348] w:UnitEnteredRadar, 24007, 1 +[t=00:04:53.877228][f=0004348] g:UnitEnteredLos, 24007, 1 +[t=00:04:53.877240][f=0004348] g:UnitEnteredRadar, 24007, 1 +[t=00:04:53.877277][f=0004348] g:UnitGiven, 24007, armacv, 1, 2 +[t=00:04:53.877451][f=0004348] g:UnitIdle, 24007, armacv, 1 +[t=00:04:53.909507][f=0004349] g:UnitLeftLos, 14177, 1 +[t=00:04:53.909535][f=0004349] g:UnitLeftRadar, 14177, 1 +[t=00:04:53.909549][f=0004349] g:UnitLeftLos, 24007, 1 +[t=00:04:53.909562][f=0004349] g:UnitLeftRadar, 24007, 1 +[t=00:04:54.109905][f=0004355] g:UnitCmdDone, 14177, corcom, 1, 130,
,
, 16 +[t=00:04:54.109951][f=0004355] g:UnitIdle, 14177, corcom, 1 +]]-- + + +function widget:UnitEnteredLos(unitID, unitTeam, allyTeam, unitDefID) + if not fullview then + widget:UnitCreated(unitID, unitDefID, unitTeam, nil, "UnitEnteredLos") + end +end + +function widget:UnitLeftLos(unitID, unitTeam, allyTeam, unitDefID) + if not fullview then + widget:UnitDestroyed(unitID, unitDefID, unitTeam, nil, nil, nil, nil, "UnitLeftLos") + end +end + +function widget:GameFrame() + --spEcho("GameFrame", gameFrame, "->", spGetGameFrame()) + gameFrame = spGetGameFrame() + if debuglevel >= 1 then -- here we will scan all units and ensure that they match what we expect + if (debuglevel <= 2) and (math.random() > 0.05 ) then return end -- lower frequency at smaller debug levels + local allunits = spGetAllUnits() + local allunitsTable = {} + for i = 1, #allunits do + local unitID = allunits[i] + if isValidLivingSeenUnit(unitID, spGetUnitDefID(unitID), 3) then + allunitsTable[unitID] = true + end + end + + local cntvisibleunits = 0 + for unitID, unitDefID in pairs(visibleUnits) do + if allunitsTable[unitID] == nil then + Scream("A unitID from visibleUnits is not in allunitstable: " .. tostring(unitID)) + end + + if isValidLivingSeenUnit(unitID, unitDefID, 3) then + cntvisibleunits = cntvisibleunits + 1 + local ux, uy, uz = spGetUnitPosition(unitID) + local unitDefName = UnitDefs[spGetUnitDefID(unitID)].name + if lastknownunitpos[unitID] then + lastknownunitpos[unitID][1] = ux + lastknownunitpos[unitID][2] = uy + lastknownunitpos[unitID][3] = uz + lastknownunitpos[unitID][4] = unitDefName + else + lastknownunitpos[unitID] = {ux,uy,uz, unitDefName} + end + else + isValidLivingSeenUnit(unitID, unitDefID, 1) + Scream("Unit in visibleUnits does not exist", unitID) + end + end + if cntvisibleunits ~= numVisibleUnits then + Scream("cntvisibleunits ~= numVisibleUnits " .. tostring(cntvisibleunits) .. " vs " .. tostring(numVisibleUnits)) + end + + if drawdebugvisible then + InstanceVBOTable.locateInvalidUnits(unitTrackerVBO) + end + + local cntalliedunits = 0 + for unitID, unitDefID in pairs(alliedUnits) do + if allunitsTable[unitID] == nil then + Scream("A unitID from alliedUnits is not in allunitstable: " .. tostring(unitID)) + end + + if isValidLivingSeenUnit(unitID, unitDefID, 3) then + cntalliedunits = cntalliedunits + 1 + else + isValidLivingSeenUnit(unitID, unitDefID, 1) + Scream("Unit in alliedunits does not exist", unitID) + end + end + if cntalliedunits ~= numAlliedUnits then + Scream("cntalliedunits ~= numAlliedUnits " .. tostring(cntalliedunits) .. " vs " .. tostring(numAlliedUnits)) + end + + if debugdrawvisible then + unitTrackerVBO.debug = true + end + end +end + +function widget:DrawWorldPreUnit() + if Spring.IsGUIHidden() then + return + end + + if debugdrawvisible then + -- spEcho("Drawing unitTracker", unitTrackerVBO.usedElements) + if unitTrackerVBO.usedElements > 0 then + gl.Texture(0, texture) + unitTrackerShader:Activate() + unitTrackerShader:SetUniform("iconDistance", 99999) -- pass + unitTrackerShader:SetUniform("addRadius", 0) + gl.DepthTest(true) + gl.DepthMask(false) + unitTrackerVBO.VAO:DrawArrays(GL.POINTS, unitTrackerVBO.usedElements) + unitTrackerShader:Deactivate() + gl.Texture(0, false) + end + end +end + +local function initializeAllUnits() + alliedUnits = {} + alliedUnitsTeam = {} + numAlliedUnits = 0 + + visibleUnits = {} + visibleUnitsTeam = {} + numVisibleUnits = 0 + + if debuglevel >= 2 then + spEcho("initializeAllUnits()", + "spec", spec, + " fullview:", fullview , + " team:", myTeamID , + " allyteam:", myAllyTeamID , + " player:", myPlayerID + ) + end + + if debugdrawvisible then + InstanceVBOTable.clearInstanceTable(unitTrackerVBO) + end + + local allunits = spGetAllUnits() + for i, unitID in pairs (allunits) do + widget:UnitCreated(unitID, spGetUnitDefID(unitID), spGetUnitTeam(unitID), nil, "initializeAllUnits", true) -- silent is true + end + + WG['unittrackerapi'].visibleUnits = visibleUnits + WG['unittrackerapi'].visibleUnitsTeam = visibleUnitsTeam + WG['unittrackerapi'].alliedUnits = alliedUnits + WG['unittrackerapi'].alliedUnitsTeam = alliedUnitsTeam + visibleUnitsChanged() + alliedUnitsChanged() +end + +local function debugapiunittrackerCmd(_, line) + local param = line or "" + if param == 'draw' then + spEcho("Debug mode for API Unit Tracker GL4 set to draw:", not debugdrawvisible) + if debugdrawvisible then + InstanceVBOTable.clearInstanceTable(unitTrackerVBO) + debugdrawvisible = false + else + debugdrawvisible = true + initGL4() + initializeAllUnits() + end + end + if tonumber(param) then + local newdebuglevel = tonumber(param) + if newdebuglevel ~= debuglevel then + spEcho("Debug level for API Unit Tracker GL4 set to:", newdebuglevel) + debuglevel = newdebuglevel + end + end + return true +end + +local function executeCmd(_, line) + local cmd = line or "" + local success, functionize = pcall(loadstring('return function() return {' .. cmd .. '} end')) + if not success then + spEcho("Failed to parse command:", success, cmd) + else + local ok, data = pcall(functionize) + if not ok then + spEcho("Failed to execute command:", ok, cmd) + else + if type(data) == type({}) then + if #data == 1 then + spEcho(data[1]) + elseif #data == 0 then + spEcho("nil") + else + spEcho(data) + end + else + spEcho(data) + end + end + end + return true +end + +local function noreturnexecuteCmd(_, line) + local cmd = line or "" + local success, functionize = pcall(loadstring('return function() ' .. cmd .. ' end')) + if not success then + spEcho("Failed to parse command:", success, cmd) + else + local ok, data = pcall(functionize) + if not ok then + spEcho("Failed to execute command:", ok, cmd) + else + if type(data) == type({}) then + if #data == 1 then + spEcho(data[1]) + elseif #data == 0 then + spEcho("nil") + else + spEcho(data) + end + else + spEcho(data) + end + end + end + return true +end + +local function RegisterTextAction(actionName, handler) + if widgetHandler.AddAction then + widgetHandler:AddAction(actionName, handler, nil, "t") + elseif widgetHandler.actionHandler and widgetHandler.actionHandler.AddAction then + widgetHandler.actionHandler:AddAction(widget, actionName, handler, nil, "t") + end +end + +local function UnregisterTextAction(actionName) + if widgetHandler.RemoveAction then + widgetHandler:RemoveAction(actionName, "t") + elseif widgetHandler.actionHandler and widgetHandler.actionHandler.RemoveAction then + widgetHandler.actionHandler:RemoveAction(widget, actionName) + end +end + +function widget:PlayerChanged(playerID) + -- VERY IMPORTANT NOTE: + -- When starting up a game, and spectating a player (e.g. /spec 2), or clicking on them in playerTV, + -- My allyTeamID and myTeamID BOTH get RESET internally by the engine on game start! + -- and this does NOT result in a playerchanged callin + -- the fullview variable is not changed, however + + local currentspec, currentfullview = spGetSpectatingState() + local currentAllyTeamID = spGetMyAllyTeamID() + local currentTeamID = spGetMyTeamID() + local currentPlayerID = Spring.GetMyPlayerID() + + local reinit = false + + -- testing for visibleUnitsChanged and alliedUnitsChanged + + if debuglevel >= 2 then + spEcho("PlayerChanged", + "spec", spec, "->",currentspec, + " fullview:", fullview , "->", currentfullview, + " team:", myTeamID , "->", currentTeamID, + " allyteam:", myAllyTeamID , "->", currentAllyTeamID, + " player:", myPlayerID , "->", currentPlayerID + ) + end + + -- testing for visible units changed + if (currentspec ~= spec) or -- we change from spec to non spec (I dont think its possible to go from player to non-fullview spec in one go) + (currentfullview ~= fullview) or + ((currentAllyTeamID ~= myAllyTeamID) and not currentspec and not currentfullview) then -- our ALLYteam changes while playing, and we are not in fullview + reinit = true + end + + -- which can happen if we are spec and only want to show for allies what the FUCK + -- WHAT EFFECTS DO WE HAVE THAT ONLY SHOW FOR ALLIES IN sPEC MODE? + + spec = currentspec + fullview = currentfullview + myAllyTeamID = currentAllyTeamID + myTeamID = currentTeamID + myPlayerID = currentPlayerID + + if reinit then initializeAllUnits() end +end + +function widget:GameStart() + local function LobbyInfo() + local test = false + if not test then + if Spring.IsReplay() then return end + if Spring.Utilities.GetPlayerCount() < 2 then return end + if Spring.Utilities.Gametype.IsSinglePlayer == true then return end + end + + local pnl = {a = "a"} + for ct, id in ipairs(Spring.GetPlayerList()) do + local playername, _, spec = Spring.GetPlayerInfo(id, false) + pnl[ct] = playername + if (not test) and spec and (string.find(playername,"[teh]cluster", nil, true) or string.find(playername,"Host[", nil, true) )then + return + end + end + + for j, script in ipairs({"script.txt", "_script.txt"}) do + if VFS.FileExists(script) then + for i, line in ipairs(string.lines(VFS.LoadFile(script))) do + if string.find(string.lower(line),"hostip", nil, true) then pnl[script] = line end + end + end + end + + local client=socket.tcp() + local res, err = client:connect("server4.beyondallreason.info", 8200) + if not res and err ~= "timeout" then + --spEcho("Failure",res,err) + else + local message = "c.telemetry.log_client_event lobby:info " .. string.base64Encode(Json.encode(pnl)).." ZGVhZGJlZWZkZWFkYmVlZmRlYWRiZWVmZGVhZGJlZWY=\n" + client:send(message) + end + client:close() + end + --local succes, res = pcall(LobbyInfo) +end + +function widget:Initialize() + gameFrame = spGetGameFrame() + spec, fullview = spGetSpectatingState() + myTeamID = spGetMyTeamID() + myAllyTeamID = spGetMyAllyTeamID() + myPlayerID = Spring.GetMyPlayerID() + + scriptLuauiVisibleUnitAdded = Script.LuaUI.VisibleUnitAdded + scriptLuauiVisibleUnitRemoved = Script.LuaUI.VisibleUnitRemoved + scriptLuauiVisibleUnitsChanged = Script.LuaUI.VisibleUnitChanged + + scriptLuauiAlliedUnitAdded = Script.LuaUI.AlliedUnitAdded + scriptLuauiAlliedUnitRemoved = Script.LuaUI.AlliedUnitRemoved + scriptLuauiAlliedUnitsChanged = Script.LuaUI.AlliedUnitChanged + + + if debugdrawvisible then + initGL4() + end + + WG['unittrackerapi'] = {} + WG['unittrackerapi'].visibleUnits = visibleUnits + WG['unittrackerapi'].visibleUnitsTeam = visibleUnitsTeam + WG['unittrackerapi'].alliedUnits = alliedUnits + WG['unittrackerapi'].alliedUnitsTeam = alliedUnitsTeam + initializeAllUnits() + widgetHandler:RegisterGlobal('GadgetCrashingAircraft1', GadgetCrashingAircraft) + RegisterTextAction("debugapiunittracker", debugapiunittrackerCmd) + RegisterTextAction("execute", executeCmd) + RegisterTextAction("noreturnexecute", noreturnexecuteCmd) +end + + +local iHaveDesynced = false +-- Example console line: +-- [t=00:01:41.862230][f=0011049] Sync error for UnnamedPlayer in frame 11044 (got 5537e3ca, correct is cc130165) +local syncerrorpattern = "Sync error for ([%w%[%]_]+) in frame (%d+) %(got (%x+), correct is (%x+)%)" + +function widget:AddConsoleLine(lines, priority) + if priority and priority == L_DEPRECATED then return end + --spEcho(lines) + if iHaveDesynced then return end + local username, frameNumber, gotChecksum, correctChecksum = lines:match(syncerrorpattern) + if username and frameNumber and gotChecksum and correctChecksum then + local myPlayerName = Spring.GetPlayerInfo(Spring.GetMyPlayerID()) + if myPlayerName == username then + -- Yes, we have desynced, time to send a LuaUIMsg to notify the server + -- desyncee, gameID, frame, gameversion, engine version, map, chobby version? + local jsondict = { + eventtype = "syncerror", + username = username, -- desyncee + lobbyName = tostring(Spring.GetMenuName and Spring.GetMenuName()), -- this returns rapid://byar-chobby:test, which is completely useless + gameVersion = tostring(Game.gameVersion), -- this better not be the rapid tag + engineVersion = tostring(Engine.versionFull), -- full complete engine version string + mapName = tostring(Game.mapName), -- full map name + gameID = tostring(Game.gameID and Game.gameID or Spring.GetGameRulesParam("GameID")), -- gameID parameter, not the same as server_match_id, we will match that in teiserver + frame = frameNumber, -- the frame where it happened. + gotChecksum = gotChecksum, + correctChecksum = correctChecksum, + } + --spEcho(jsondict) + + local complex_match_event = string.format("complex-match-event:%s", string.base64Encode(Json.encode(jsondict))) + + -- We will be forwarding this as a complex event: + -- sayPrivate complex-match-event <67> + -- !sendLobby SAYPRIVATE AutohostMonitor 'complex-match-event <[teh]Beherith> <67> ' + Spring.SendLuaUIMsg(complex_match_event) + + -- then remove ourselves, no point to keep running after the first desync is detected + iHaveDesynced = true + end + end +end + + +function widget:Shutdown() + -- ok this is quite sensitive, in order to prevent taking down the rest of the world with it + -- we need to clear the visible units, and call the respective callins + alliedUnits = {} + alliedUnitsTeam = {} + numAlliedUnits = 0 + visibleUnits = {} + visibleUnitsTeam = {} + numVisibleUnits = 0 + + + WG['unittrackerapi'].visibleUnits = visibleUnits + WG['unittrackerapi'].visibleUnitsTeam = visibleUnitsTeam + WG['unittrackerapi'].alliedUnits = alliedUnits + WG['unittrackerapi'].alliedUnitsTeam = alliedUnitsTeam + visibleUnitsChanged() + alliedUnitsChanged() + + widgetHandler:DeregisterGlobal('GadgetCrashingAircraft1') + UnregisterTextAction("debugapiunittracker") + UnregisterTextAction("execute") + UnregisterTextAction("noreturnexecute") +end + +return widget end)() +local los=(function()local widget={} +local widget = widget ---@type Widget + +function widget:GetInfo() + return { + name = "Sensor Ranges LOS", + desc = "Shows LOS ranges of all ally units. (GL4)", + author = "Beherith GL4, Borg_King", + date = "2021.06.18", + license = "GPLv2, (c) Beherith (mysterme@gmail.com)", + layer = 20, + enabled = true + } +end + + +-- Localized Spring API for performance +local spEcho = Spring.Echo +local spGetViewGeometry = Spring.GetViewGeometry + +------- Configurables: ------------------- +local debugmode = false +--- +local rangeColor = { 0.9, 0.9, 0.9, 0.24 } -- default range color +local opacity = 0.08 +local useteamcolors = false +local rangeLineWidth = 4.5 -- (note: will end up larger for larger vertical screen resolution size) +local lineScale = 1 -- this is a multiplier for the line width, to make it look better on high res screens + +local circleSegments = 62 -- To ensure its only 2 warps per instance +local rangecorrectionelmos = debugmode and -16 or 16 -- how much smaller they are drawn than truth due to LOS mipping +--------- End configurables ------ + +local minSightDistance = 100 +local gaiaTeamID = Spring.GetGaiaTeamID() + +------- GL4 NOTES ----- +-- TODO: draw ally ranges in diff color! +-- 172 vs 123 preopt +-- TODO 2023.07.06: + -- X Use drawpos + -- X Stencil outlines too + -- X remove debug code + -- X validate options! + -- X The only actual param needed per unit is its los range :D + -- X refactor the opacity + +-- TODO: 2025.07.02: + -- [x] rangecorrectionelmos = 16 + -- [ ] DO NOT DELETE BRANCH ON MERGE! + -- [x] Fix screen resize + -- [-] Engine Version Check for baseVertex offset + -- [x] Teamcolor no worky + -- [x] override master + -- [x] profile + -- [x] Correctly reset GL state for build ETA + -- [ ] Try to use only one stencil clear op, use a mask that is unique + -- [x] Put SDscreenSphere into LuaShader.lua + -- [-] Draw los in minimap, add config optios for it. + + + +local LuaShader = gl.LuaShader +local InstanceVBOTable = gl.InstanceVBOTable + +local popElementInstance = InstanceVBOTable.popElementInstance +local pushElementInstance = InstanceVBOTable.pushElementInstance + +local losStencilShader = nil +local losCircleShader = nil +local circleInstanceVBO = nil + +local losStencilTexture +local resolution = 4 +local vsx, vsy = spGetViewGeometry() + +local circleShaderSourceCache = { + shaderName = 'LOS Ranges Circles GL4', + vssrcpath = "LuaUI/Shaders/sensor_ranges_los.vert.glsl", + fssrcpath = "LuaUI/Shaders/sensor_ranges_los.frag.glsl", + shaderConfig = { + VSX = vsx, + VSY = vsy, + RESOLUTION = resolution, + PADDING = 1, + USE_TEAMCOLOR = 1, + VISIBILITYCULLING = 1, + }, + uniformInt = { + heightmapTex = 0, + losStencilTexture = 1, + }, + uniformFloat = { + teamColorMix = 1.0, + rangeColor = rangeColor, + }, + silent = not debugmode, -- do not print shader compile timing +} + +local stencilShaderSourceCache = table.copy(circleShaderSourceCache) -- copy the circle shader source cache, and modify it for stencil pass +stencilShaderSourceCache.shaderConfig.STENCILPASS = 1 -- this is a stencil pass + +local function goodbye(reason) + spEcho("Sensor Ranges LOS widget exiting with reason: " .. reason) + widgetHandler:RemoveWidget() + return false +end + +local function CreateStencilShaderAndTexture() + vsx, vsy = spGetViewGeometry() + circleShaderSourceCache.shaderConfig.VSX = vsx + circleShaderSourceCache.shaderConfig.VSY = vsy + circleShaderSourceCache.forceupdate = true + stencilShaderSourceCache.shaderConfig.VSX = vsx + stencilShaderSourceCache.shaderConfig.VSY = vsy + stencilShaderSourceCache.forceupdate = true + + losStencilShader = LuaShader.CheckShaderUpdates(stencilShaderSourceCache,0) + + if not losStencilShader then + return goodbye("Failed to compile losrange stencil shader GL4 ") + end + losCircleShader = LuaShader.CheckShaderUpdates(circleShaderSourceCache,0) + if not losCircleShader then + return goodbye("Failed to compile losrange shader GL4 ") + end + + local GL_R8 = 0x8229 + vsx, vsy = spGetViewGeometry() + lineScale = (vsy + 500)/ 1300 + if losStencilTexture then gl.DeleteTexture(losStencilTexture) end + losStencilTexture = gl.CreateTexture(vsx/resolution, vsy/resolution, { + --format = GL.RGBA8, + format = GL_R8, + fbo = true, + min_filter = GL.NEAREST, + mag_filter = GL.LINEAR, + wrap_s = GL.CLAMP_TO_EDGE, + wrap_t = GL.CLAMP_TO_EDGE, + }) +end +local function initgl4() + -- Due to the view size being part of the shader config, we need to initialize the shaders after the view size is known. + + -- Note that we are createing a special Circle VBO, that starts at the center vertex! This is needed for triangle fans + local circleVBO, numVertices = InstanceVBOTable.makeCircleVBO(circleSegments, nil, true, "LOSRangeCircles") + local circleInstanceVBOLayout = { + { id = 1, name = 'radius_params', size = 4 }, -- radius, gameframe, 2 unused floats + { id = 2, name = 'instData', size = 4, type = GL.UNSIGNED_INT}, -- instData + } + + circleInstanceVBO = InstanceVBOTable.makeInstanceVBOTable(circleInstanceVBOLayout, 128, "losrangeVBO", 2) + circleInstanceVBO.numVertices = numVertices + circleInstanceVBO.vertexVBO = circleVBO + circleInstanceVBO.VAO = InstanceVBOTable.makeVAOandAttach(circleInstanceVBO.vertexVBO, circleInstanceVBO.instanceVBO) + + CreateStencilShaderAndTexture() +end + + +local function DrawLOSStencil() -- about 0.025 ms + if circleInstanceVBO.usedElements > 0 then + gl.Clear(GL.COLOR_BUFFER_BIT,0,0,0,0) + gl.BlendEquation(GL.MAX) + gl.Blending(GL.ONE, GL.ONE) + gl.Culling(false) + + gl.Texture(0, "$heightmap") -- Bind the heightmap texture + losStencilShader:Activate() + circleInstanceVBO.VAO:DrawArrays(GL.TRIANGLE_FAN, circleInstanceVBO.numVertices, 0, circleInstanceVBO.usedElements, 0) + losStencilShader:Deactivate() + gl.Blending(GL.SRC_ALPHA, GL.ONE_MINUS_SRC_ALPHA) + gl.BlendEquation(GL.FUNC_ADD) + end +end + +function widget:DrawGenesis() + gl.RenderToTexture(losStencilTexture, DrawLOSStencil) +end + +-- This shows the debug stencil texture in the bottom left corner of the screen +if debugmode then + function widget:DrawScreen() + losCircleShader = LuaShader.CheckShaderUpdates(circleShaderSourceCache,0) or losCircleShader + losStencilShader = LuaShader.CheckShaderUpdates(stencilShaderSourceCache,0) or losStencilShader + gl.Color(1,1,1,1) + gl.Blending(GL.ONE, GL.ZERO) + gl.Texture(losStencilTexture) + gl.TexRect(0, 0, vsx/resolution, vsy/resolution, 0, 0, 1, 1) + gl.Blending(GL.SRC_ALPHA, GL.ONE_MINUS_SRC_ALPHA) + end +end + +-- Functions shortcuts +local spGetSpectatingState = Spring.GetSpectatingState +local spIsUnitAllied = Spring.IsUnitAllied +local spGetUnitTeam = Spring.GetUnitTeam +local GL_NOTEQUAL = GL.NOTEQUAL +local GL_LINE_LOOP = GL.LINE_LOOP +local GL_KEEP = 0x1E00 --GL.KEEP +local GL_REPLACE = GL.REPLACE + +-- Globals +local spec, fullview = spGetSpectatingState() +local allyTeamID = Spring.GetMyAllyTeamID() + +-- find all unit types with radar in the game and place ranges into unitRange table +local unitRange = {} -- table of unit types with their radar ranges + +for unitDefID, unitDef in pairs(UnitDefs) do + -- save perf by excluding low los range units + if unitDef.sightDistance and unitDef.sightDistance > minSightDistance then + unitRange[unitDefID] = unitDef.sightDistance - rangecorrectionelmos + end +end + +function widget:ViewResize(newX, newY) + CreateStencilShaderAndTexture() +end + +-- a reusable table, since we will literally only modify its first element. +local instanceCache = {0,0,0,0,0,0,0,0} + +local function InitializeUnits() + --spEcho("Sensor Ranges LOS InitializeUnits") + InstanceVBOTable.clearInstanceTable(circleInstanceVBO) + if WG['unittrackerapi'] and WG['unittrackerapi'].visibleUnits then + local visibleUnits = WG['unittrackerapi'].visibleUnits + for unitID, unitDefID in pairs(visibleUnits) do + widget:VisibleUnitAdded(unitID, unitDefID, spGetUnitTeam(unitID), nil, true) + end + end + InstanceVBOTable.uploadAllElements(circleInstanceVBO) +end + +function widget:PlayerChanged() + local wasFullview = spec and fullview + local myPrevAllyTeamID = allyTeamID + spec, fullview = spGetSpectatingState() + allyTeamID = Spring.GetMyAllyTeamID() + local isFullview = spec and fullview + if isFullview ~= wasFullview or ((not isFullview) and allyTeamID ~= myPrevAllyTeamID) then + InitializeUnits() + end +end + +function widget:Initialize() + if not gl.CreateShader or Spring.GetModOptions().disable_fogofwar then -- no shader support, so just remove the widget itself, especially for headless + widgetHandler:RemoveWidget() + return + end + + WG.losrange = { + getOpacity = function() return opacity end, + setOpacity = function(value) opacity = value end, + getUseTeamColors = function() return useteamcolors end, + setUseTeamColors = function(value) useteamcolors = value end, + } + + initgl4() + + InitializeUnits() +end + +function widget:Shutdown() + if losStencilTexture then gl.DeleteTexture(losStencilTexture) end + WG.losrange = nil +end + +function widget:VisibleUnitAdded(unitID, unitDefID, unitTeam, reason, noupload) + --spEcho("widget:VisibleUnitAdded",unitID, unitDefID, unitTeam, reason, noupload) + unitTeam = unitTeam or spGetUnitTeam(unitID) + noupload = noupload == true + if unitRange[unitDefID] == nil or unitTeam == gaiaTeamID then return end + + if (not (spec and fullview)) and (not spIsUnitAllied(unitID)) then -- given units are still considered allies :/ + return + end -- display mode for specs + + if Spring.GetUnitIsBeingBuilt(unitID) then return end + + instanceCache[1] = unitRange[unitDefID] + if reason == "UnitFinished" then + instanceCache[2] = Spring.GetGameFrame() + else + instanceCache[2] = 0 -- start from full size + end + pushElementInstance(circleInstanceVBO, + instanceCache, + unitID, --key + true, -- updateExisting + noupload, + unitID -- unitID for uniform buffers + ) +end + +function widget:VisibleUnitsChanged(extVisibleUnits, extNumVisibleUnits) + -- Note that this unit uses its own VisibleUnitsChanged, to handle the case where we go into fullview. +end + +function widget:VisibleUnitRemoved(unitID) + if circleInstanceVBO.instanceIDtoIndex[unitID] then + popElementInstance(circleInstanceVBO, unitID) + end +end + +function widget:DrawWorld() + --if spec and fullview then return end + if Spring.IsGUIHidden() or + (circleInstanceVBO.usedElements == 0) or + (opacity <= 0.01) + then return end + + --gl.Clear(GL.STENCIL_BUFFER_BIT) -- Preemtively clear the stencil buffer + gl.StencilTest(true) -- Enable stencil testing + gl.StencilFunc(GL_NOTEQUAL, 1, 1) -- Always Passes, 0 Bit Plane, 0 As Mask + gl.StencilOp(GL_KEEP, GL_KEEP, GL_REPLACE) -- Set The Stencil Buffer To 1 Where Draw Any Polygon + gl.StencilMask(15) -- Only check the first bit of the stencil buffer + + losCircleShader:Activate() + gl.Texture(0, "$heightmap") -- Bind the heightmap texture + gl.Texture(1, losStencilTexture) -- Bind the heightmap texture + + losCircleShader:SetUniform("rangeColor", rangeColor[1], rangeColor[2], rangeColor[3], opacity * (useteamcolors and 2 or 1 )) + --spEcho("rangeColor", rangeColor[1], rangeColor[2], rangeColor[3], opacity * (useteamcolors and 2 or 1 )) + losCircleShader:SetUniform("teamColorMix", useteamcolors and 1 or 0) + + gl.LineWidth(rangeLineWidth * lineScale * 1.0) + + gl.DepthTest(true) + -- Note that we are skipping the first and last vertex, as those are the center of the circle : + circleInstanceVBO.VAO:DrawArrays(GL_LINE_LOOP, circleInstanceVBO.numVertices -0, 0, circleInstanceVBO.usedElements) + -- TODO: In the future, when BASE VERTEX works, use the following line instead: + --circleInstanceVBO.VAO:DrawArrays(GL_LINE_LOOP, circleInstanceVBO.numVertices -2, 1, circleInstanceVBO.usedElements) + + losCircleShader:Deactivate() + gl.Texture(0, false) + gl.Texture(1, false) + gl.DepthTest(true) + gl.StencilTest(false) -- Disable stencil testing + + gl.LineWidth(1.0) + --gl.Clear(GL.STENCIL_BUFFER_BIT) +end + + +function widget:GetConfigData(data) + return { + opacity = opacity, + useteamcolors = useteamcolors, + } +end + +function widget:SetConfigData(data) + if data.opacity ~= nil then + opacity = data.opacity + end + if data.useteamcolors ~= nil then + useteamcolors = data.useteamcolors + end +end + +return widget end)() +local radar=(function()local widget={} +local widget = widget ---@type Widget + +function widget:GetInfo() + return { + name = "Sensor Ranges Radar", + desc = "Shows Radar ranges of all ally units. (GL4)", + author = "Beherith GL4", + date = "2021.06.18", + license = "GPLv2, (c) Beherith (mysterme@gmail.com)", + layer = 19, + enabled = true + } +end + + +-- Localized Spring API for performance +local spGetGameFrame = Spring.GetGameFrame +local spEcho = Spring.Echo +local spGetViewGeometry = Spring.GetViewGeometry + +------- Configurables: ------------------- +local debugmode = false +--- +local rangeColor = { 0.0, 1.0, 0.0, 0.16 } -- default range color +local opacity = 0.16 +local rangeLineWidth = 4.5 -- (note: will end up larger for larger vertical screen resolution size) +local lineScale = 1 -- this is a multiplier for the line width, to make it look better on high res screens + +local circleSegments = 126 -- To ensure its only 2 warps per instance +local rangecorrectionelmos = debugmode and -16 or 16 -- visually align dotted line with fog-of-war radar edge (sharpened in shaders/GLSL/infoLOS.lua) +--------- End configurables ------ + +local minRadarDistance = 500 +local gaiaTeamID = Spring.GetGaiaTeamID() + +------- GL4 NOTES ----- +-- TODO: 2025.07.02: + + + + +local LuaShader = gl.LuaShader +local InstanceVBOTable = gl.InstanceVBOTable + +local popElementInstance = InstanceVBOTable.popElementInstance +local pushElementInstance = InstanceVBOTable.pushElementInstance + +local radarStencilShader = nil +local radarCircleShader = nil +local circleInstanceVBO = nil + +local radarStencilTexture +local resolution = 4 +local vsx, vsy = spGetViewGeometry() + +local circleShaderSourceCache = { + shaderName = 'Radar Ranges Circles GL4', + vssrcpath = "LuaUI/Shaders/sensor_ranges_los.vert.glsl", + fssrcpath = "LuaUI/Shaders/sensor_ranges_los.frag.glsl", + shaderConfig = { + VSX = vsx, + VSY = vsy, + RESOLUTION = resolution, + PADDING = 1, + --VISIBILITYCULLING = 1, + STIPPLE_RATE = 1.0, + }, + uniformInt = { + heightmapTex = 0, + losStencilTexture = 1, + }, + uniformFloat = { + teamColorMix = 1.0, + rangeColor = rangeColor, + }, + silent = not debugmode, -- do not print shader compile timing +} + +local stencilShaderSourceCache = table.copy(circleShaderSourceCache) -- copy the circle shader source cache, and modify it for stencil pass +stencilShaderSourceCache.shaderConfig.STENCILPASS = 1 -- this is a stencil pass +stencilShaderSourceCache.shaderName = 'Radar Ranges Stencil GL4' + +local function goodbye(reason) + spEcho("Sensor Ranges LOS widget exiting with reason: " .. reason) + widgetHandler:RemoveWidget() + return false +end + +local function CreateStencilShaderAndTexture() + vsx, vsy = spGetViewGeometry() + circleShaderSourceCache.shaderConfig.VSX = vsx + circleShaderSourceCache.shaderConfig.VSY = vsy + circleShaderSourceCache.forceupdate = true + stencilShaderSourceCache.shaderConfig.VSX = vsx + stencilShaderSourceCache.shaderConfig.VSY = vsy + stencilShaderSourceCache.forceupdate = true + + radarStencilShader = LuaShader.CheckShaderUpdates(stencilShaderSourceCache,0) + + if not radarStencilShader then + return goodbye("Failed to compile radarrange stencil shader GL4 ") + end + radarCircleShader = LuaShader.CheckShaderUpdates(circleShaderSourceCache,0) + if not radarCircleShader then + return goodbye("Failed to compile radarrange shader GL4 ") + end + + local GL_R8 = 0x8229 + vsx, vsy = spGetViewGeometry() + lineScale = (vsy + 500)/ 1300 + if radarStencilTexture then gl.DeleteTexture(radarStencilTexture) end + radarStencilTexture = gl.CreateTexture(vsx/resolution, vsy/resolution, { + --format = GL.RGBA8, + format = GL_R8, + fbo = true, + min_filter = GL.NEAREST, + mag_filter = GL.LINEAR, + wrap_s = GL.CLAMP_TO_EDGE, + wrap_t = GL.CLAMP_TO_EDGE, + }) +end +local function initgl4() + -- Due to the view size being part of the shader config, we need to initialize the shaders after the view size is known. + + -- Note that we are createing a special Circle VBO, that starts at the center vertex! This is needed for triangle fans + local circleVBO, numVertices = InstanceVBOTable.makeCircleVBO(circleSegments, nil, true, "radarrangeCircles") + local circleInstanceVBOLayout = { + { id = 1, name = 'radius_params', size = 4 }, -- radius, gameframe, 2 unused floats + { id = 2, name = 'instData', size = 4, type = GL.UNSIGNED_INT}, -- instData + } + + circleInstanceVBO = InstanceVBOTable.makeInstanceVBOTable(circleInstanceVBOLayout, 128, "radarrangeVBO", 2) + circleInstanceVBO.numVertices = numVertices + circleInstanceVBO.vertexVBO = circleVBO + circleInstanceVBO.VAO = InstanceVBOTable.makeVAOandAttach(circleInstanceVBO.vertexVBO, circleInstanceVBO.instanceVBO) + + CreateStencilShaderAndTexture() +end + + +local function DrawLOSStencil() -- about 0.025 ms + if circleInstanceVBO.usedElements > 0 then + gl.Clear(GL.COLOR_BUFFER_BIT,0,0,0,0) + gl.BlendEquation(GL.MAX) + gl.Blending(GL.ONE, GL.ONE) + gl.Culling(false) + + gl.Texture(0, "$heightmap") -- Bind the heightmap texture + radarStencilShader:Activate() + circleInstanceVBO.VAO:DrawArrays(GL.TRIANGLE_FAN, circleInstanceVBO.numVertices, 0, circleInstanceVBO.usedElements, 0) + radarStencilShader:Deactivate() + gl.Blending(GL.SRC_ALPHA, GL.ONE_MINUS_SRC_ALPHA) + gl.BlendEquation(GL.FUNC_ADD) + end +end + +function widget:DrawGenesis() + gl.RenderToTexture(radarStencilTexture, DrawLOSStencil) +end + +-- This shows the debug stencil texture in the bottom left corner of the screen +if debugmode then + function widget:DrawScreen() + radarCircleShader = LuaShader.CheckShaderUpdates(circleShaderSourceCache,0) or radarCircleShader + radarStencilShader = LuaShader.CheckShaderUpdates(stencilShaderSourceCache,0) or radarStencilShader + gl.Color(1,1,1,1) + gl.Blending(GL.ONE, GL.ZERO) + gl.Texture(radarStencilTexture) + gl.TexRect(0, 0, vsx/resolution, vsy/resolution, 0, 0, 1, 1) + gl.Blending(GL.SRC_ALPHA, GL.ONE_MINUS_SRC_ALPHA) + end +end + +-- Functions shortcuts +local spGetSpectatingState = Spring.GetSpectatingState +local spIsUnitAllied = Spring.IsUnitAllied +local spGetUnitTeam = Spring.GetUnitTeam +local spGetUnitIsActive = Spring.GetUnitIsActive +local GL_NOTEQUAL = GL.NOTEQUAL +local GL_LINE_LOOP = GL.LINE_LOOP +local GL_KEEP = 0x1E00 --GL.KEEP +local GL_REPLACE = GL.REPLACE + +-- Globals +local spec, fullview = spGetSpectatingState() +local allyTeamID = Spring.GetMyAllyTeamID() + +-- find all unit types with radar in the game and place ranges into unitRange table +local unitRange = {} -- table of unit types with their radar ranges + +local unitList = {} -- all ally units and their coordinates and radar ranges + +for unitDefID, unitDef in pairs(UnitDefs) do + if unitDef.radarDistance and unitDef.radarDistance > minRadarDistance then -- save perf by excluding low radar range units + unitRange[unitDefID] = unitDef.radarDistance - rangecorrectionelmos + end +end + +function widget:ViewResize(newX, newY) + CreateStencilShaderAndTexture() +end + +-- a reusable table, since we will literally only modify its first element. +local instanceCache = {0,0,0,0,0,0,0,0} + +local function InitializeUnits() + --spEcho("Sensor Ranges LOS InitializeUnits") + InstanceVBOTable.clearInstanceTable(circleInstanceVBO) + if WG['unittrackerapi'] and WG['unittrackerapi'].visibleUnits then + local visibleUnits = WG['unittrackerapi'].visibleUnits + for unitID, unitDefID in pairs(visibleUnits) do + widget:VisibleUnitAdded(unitID, unitDefID, spGetUnitTeam(unitID), nil, true) + end + end + InstanceVBOTable.uploadAllElements(circleInstanceVBO) +end + +function widget:PlayerChanged() + local wasFullview = spec and fullview + local myPrevAllyTeamID = allyTeamID + spec, fullview = spGetSpectatingState() + allyTeamID = Spring.GetMyAllyTeamID() + local isFullview = spec and fullview + if isFullview ~= wasFullview or ((not isFullview) and allyTeamID ~= myPrevAllyTeamID) then + InitializeUnits() + end +end + +function widget:Initialize() + if not gl.CreateShader or Spring.GetModOptions().disable_fogofwar then -- no shader support, so just remove the widget itself, especially for headless + widgetHandler:RemoveWidget() + return + end + + WG.radarrange = { + getOpacity = function() return opacity end, + setOpacity = function(value) opacity = value end, + } + + initgl4() + + InitializeUnits() +end + +function widget:Shutdown() + if radarStencilTexture then gl.DeleteTexture(radarStencilTexture) end + WG.radarrange = nil +end + +function widget:VisibleUnitAdded(unitID, unitDefID, unitTeam, reason, noupload) + --spEcho("widget:VisibleUnitAdded",unitID, unitDefID, unitTeam, reason, noupload) + unitTeam = unitTeam or spGetUnitTeam(unitID) + noupload = noupload == true + if unitRange[unitDefID] == nil or unitTeam == gaiaTeamID then return end + + if (not (spec and fullview)) and (not spIsUnitAllied(unitID)) then -- given units are still considered allies :/ + return + end -- display mode for specs + + if Spring.GetUnitIsBeingBuilt(unitID) then return end + + instanceCache[1] = unitRange[unitDefID] + + + local active = spGetUnitIsActive(unitID) + local gameFrame = spGetGameFrame() + if reason == "UnitFinished" then + if active then + instanceCache[2] = spGetGameFrame() + else + instanceCache[2] = -2 -- start from full size + end + else + if active then + instanceCache[2] = gameFrame + else + instanceCache[2] = -1 * gameFrame + end + end + unitList[unitID] = active + pushElementInstance(circleInstanceVBO, + instanceCache, + unitID, --key + true, -- updateExisting + noupload, + unitID -- unitID for uniform buffers + ) +end + +function widget:VisibleUnitsChanged(extVisibleUnits, extNumVisibleUnits) + -- Note that this unit uses its own VisibleUnitsChanged, to handle the case where we go into fullview. +end + +function widget:VisibleUnitRemoved(unitID) + if circleInstanceVBO.instanceIDtoIndex[unitID] then + popElementInstance(circleInstanceVBO, unitID) + end + unitList[unitID] = nil +end + +function widget:GameFrame(n) + if spec and fullview then return end + if n % 15 == 2 then + for unitID, oldActive in pairs(unitList) do + local active = spGetUnitIsActive(unitID) + if active ~= oldActive then + unitList[unitID] = active + widget:VisibleUnitAdded(unitID, Spring.GetUnitDefID(unitID), spGetUnitTeam(unitID) ) + end + end + end +end + +function widget:DrawWorld() + --if spec and fullview then return end + if Spring.IsGUIHidden() or + (circleInstanceVBO.usedElements == 0) or + (opacity <= 0.01) + then return end + + --gl.Clear(GL.STENCIL_BUFFER_BIT) -- Preemtively clear the stencil buffer + gl.StencilTest(true) -- Enable stencil testing + gl.StencilFunc(GL_NOTEQUAL, 4, 4) -- Always Passes, 0 Bit Plane, 0 As Mask + gl.StencilOp(GL_KEEP, GL_KEEP, GL_REPLACE) -- Set The Stencil Buffer To 1 Where Draw Any Polygon + gl.StencilMask(15) -- Only check the first bit of the stencil buffer + + radarCircleShader:Activate() + gl.Texture(0, "$heightmap") -- Bind the heightmap texture + gl.Texture(1, radarStencilTexture) -- Bind the heightmap texture + + radarCircleShader:SetUniform("rangeColor", rangeColor[1], rangeColor[2], rangeColor[3], opacity ) + --spEcho("rangeColor", rangeColor[1], rangeColor[2], rangeColor[3], opacity * (useteamcolors and 2 or 1 )) + radarCircleShader:SetUniform("teamColorMix", 0) + + gl.LineWidth(rangeLineWidth * lineScale * 1.0) + + gl.DepthTest(true) + -- Note that we are skipping the first and last vertex, as those are the center of the circle : + circleInstanceVBO.VAO:DrawArrays(GL_LINE_LOOP, circleInstanceVBO.numVertices -0, 0, circleInstanceVBO.usedElements) + -- TODO: In the future, when BASE VERTEX works, use the following line instead: + --circleInstanceVBO.VAO:DrawArrays(GL_LINE_LOOP, circleInstanceVBO.numVertices -2, 1, circleInstanceVBO.usedElements) + + radarCircleShader:Deactivate() + gl.Texture(0, false) + gl.Texture(1, false) + gl.DepthTest(true) + gl.StencilTest(false) -- Disable stencil testing + + gl.LineWidth(1.0) + --gl.Clear(GL.STENCIL_BUFFER_BIT) +end + + +function widget:GetConfigData(data) + return { + opacity = opacity, + } +end + +function widget:SetConfigData(data) + if data.opacity ~= nil then + opacity = data.opacity + end +end + +return widget end)() +local sonar=(function()local widget={} +local widget = widget ---@type Widget + +function widget:GetInfo() + return { + name = "Sensor Ranges Sonar", + desc = "Shows Sonar ranges of all ally units. (GL4)", + author = "Beherith GL4", + date = "2021.06.18", + license = "GPLv2, (c) Beherith (mysterme@gmail.com)", + layer = 18, + enabled = true + } +end + + +-- Localized Spring API for performance +local spGetGameFrame = Spring.GetGameFrame +local spEcho = Spring.Echo +local spGetViewGeometry = Spring.GetViewGeometry + +------- Configurables: ------------------- +local debugmode = false +--- +local rangeColor = { 0.5, 0.7, 0.9, 0.17 } -- default range color +local opacity = 0.17 +local rangeLineWidth = 4.5 -- (note: will end up larger for larger vertical screen resolution size) +local lineScale = 1 -- this is a multiplier for the line width, to make it look better on high res screens + +local circleSegments = 62 -- To ensure its only 2 warps per instance +local rangecorrectionelmos = debugmode and -16 or 16 -- how much smaller they are drawn than truth due to LOS mipping +--------- End configurables ------ + +local minSonarDistance = 150 +local gaiaTeamID = Spring.GetGaiaTeamID() + +------- GL4 NOTES ----- +-- TODO: 2025.07.02: + + + + +local LuaShader = gl.LuaShader +local InstanceVBOTable = gl.InstanceVBOTable + +local popElementInstance = InstanceVBOTable.popElementInstance +local pushElementInstance = InstanceVBOTable.pushElementInstance + +local sonarStencilShader = nil +local sonarCircleShader = nil +local circleInstanceVBO = nil + +local sonarStencilTexture +local resolution = 4 +local vsx, vsy = spGetViewGeometry() + +local circleShaderSourceCache = { + shaderName = 'Sonar Ranges Circles GL4', + vssrcpath = "LuaUI/Shaders/sensor_ranges_los.vert.glsl", + fssrcpath = "LuaUI/Shaders/sensor_ranges_los.frag.glsl", + shaderConfig = { + VSX = vsx, + VSY = vsy, + RESOLUTION = resolution, + PADDING = 1, + VISIBILITYCULLING = 1, + MAX_HEIGHT = 0, -- dont show above this height + STIPPLE_RATE = 1.0, + }, + uniformInt = { + heightmapTex = 0, + losStencilTexture = 1, + }, + uniformFloat = { + teamColorMix = 1.0, + rangeColor = rangeColor, + }, + silent = not debugmode, -- do not print shader compile timing +} + +local stencilShaderSourceCache = table.copy(circleShaderSourceCache) -- copy the circle shader source cache, and modify it for stencil pass +stencilShaderSourceCache.shaderConfig.STENCILPASS = 1 -- this is a stencil pass +stencilShaderSourceCache.shaderName = 'Sonar Ranges Stencil GL4' + +local function goodbye(reason) + spEcho("Sensor Ranges LOS widget exiting with reason: " .. reason) + widgetHandler:RemoveWidget() + return false +end + +local function CreateStencilShaderAndTexture() + vsx, vsy = spGetViewGeometry() + circleShaderSourceCache.shaderConfig.VSX = vsx + circleShaderSourceCache.shaderConfig.VSY = vsy + circleShaderSourceCache.forceupdate = true + stencilShaderSourceCache.shaderConfig.VSX = vsx + stencilShaderSourceCache.shaderConfig.VSY = vsy + stencilShaderSourceCache.forceupdate = true + + sonarStencilShader = LuaShader.CheckShaderUpdates(stencilShaderSourceCache,0) + + if not sonarStencilShader then + return goodbye("Failed to compile sonarrange stencil shader GL4 ") + end + sonarCircleShader = LuaShader.CheckShaderUpdates(circleShaderSourceCache,0) + if not sonarCircleShader then + return goodbye("Failed to compile sonarrange shader GL4 ") + end + + local GL_R8 = 0x8229 + vsx, vsy = spGetViewGeometry() + lineScale = (vsy + 500)/ 1300 + if sonarStencilTexture then gl.DeleteTexture(sonarStencilTexture) end + sonarStencilTexture = gl.CreateTexture(vsx/resolution, vsy/resolution, { + --format = GL.RGBA8, + format = GL_R8, + fbo = true, + min_filter = GL.NEAREST, + mag_filter = GL.LINEAR, + wrap_s = GL.CLAMP_TO_EDGE, + wrap_t = GL.CLAMP_TO_EDGE, + }) +end +local function initgl4() + -- Due to the view size being part of the shader config, we need to initialize the shaders after the view size is known. + + -- Note that we are createing a special Circle VBO, that starts at the center vertex! This is needed for triangle fans + local circleVBO, numVertices = InstanceVBOTable.makeCircleVBO(circleSegments, nil, true, "sonarrangeCircles") + local circleInstanceVBOLayout = { + { id = 1, name = 'radius_params', size = 4 }, -- radius, gameframe, 2 unused floats + { id = 2, name = 'instData', size = 4, type = GL.UNSIGNED_INT}, -- instData + } + + circleInstanceVBO = InstanceVBOTable.makeInstanceVBOTable(circleInstanceVBOLayout, 128, "sonarrangeVBO", 2) + circleInstanceVBO.numVertices = numVertices + circleInstanceVBO.vertexVBO = circleVBO + circleInstanceVBO.VAO = InstanceVBOTable.makeVAOandAttach(circleInstanceVBO.vertexVBO, circleInstanceVBO.instanceVBO) + + CreateStencilShaderAndTexture() +end + + +local function DrawLOSStencil() -- about 0.025 ms + if circleInstanceVBO.usedElements > 0 then + gl.Clear(GL.COLOR_BUFFER_BIT,0,0,0,0) + gl.BlendEquation(GL.MAX) + gl.Blending(GL.ONE, GL.ONE) + gl.Culling(false) + + gl.Texture(0, "$heightmap") -- Bind the heightmap texture + sonarStencilShader:Activate() + circleInstanceVBO.VAO:DrawArrays(GL.TRIANGLE_FAN, circleInstanceVBO.numVertices, 0, circleInstanceVBO.usedElements, 0) + sonarStencilShader:Deactivate() + gl.Blending(GL.SRC_ALPHA, GL.ONE_MINUS_SRC_ALPHA) + gl.BlendEquation(GL.FUNC_ADD) + end +end + +function widget:DrawGenesis() + gl.RenderToTexture(sonarStencilTexture, DrawLOSStencil) +end + +-- This shows the debug stencil texture in the bottom left corner of the screen +if debugmode then + function widget:DrawScreen() + sonarCircleShader = LuaShader.CheckShaderUpdates(circleShaderSourceCache,0) or sonarCircleShader + sonarStencilShader = LuaShader.CheckShaderUpdates(stencilShaderSourceCache,0) or sonarStencilShader + gl.Color(1,1,1,1) + gl.Blending(GL.ONE, GL.ZERO) + gl.Texture(sonarStencilTexture) + gl.TexRect(0, 0, vsx/resolution, vsy/resolution, 0, 0, 1, 1) + gl.Blending(GL.SRC_ALPHA, GL.ONE_MINUS_SRC_ALPHA) + end +end + +-- Functions shortcuts +local spGetSpectatingState = Spring.GetSpectatingState +local spGetUnitDefID = Spring.GetUnitDefID +local spIsUnitAllied = Spring.IsUnitAllied +local spGetUnitTeam = Spring.GetUnitTeam +local spGetUnitIsActive = Spring.GetUnitIsActive +local GL_NOTEQUAL = GL.NOTEQUAL +local GL_LINE_LOOP = GL.LINE_LOOP +local GL_KEEP = 0x1E00 --GL.KEEP +local GL_REPLACE = GL.REPLACE + +-- Globals +local spec, fullview = spGetSpectatingState() +local allyTeamID = Spring.GetMyAllyTeamID() + +-- find all unit types with sonar in the game and place ranges into unitRange table +local unitRange = {} -- table of unit types with their sonar ranges + +local unitList = {} -- all ally units and their coordinates and sonar ranges + +for unitDefID, unitDef in pairs(UnitDefs) do + if unitDef.sonarDistance and unitDef.sonarDistance >= minSonarDistance then -- save perf by excluding low sonar range units + if string.find(unitDef.name, "raptor", nil, true) then + -- skip raptors from sonar + else + unitRange[unitDefID] = unitDef.sonarDistance + end + end +end + +function widget:ViewResize(newX, newY) + CreateStencilShaderAndTexture() +end + +-- a reusable table, since we will literally only modify its first element. +local instanceCache = {0,0,0,0,0,0,0,0} + +local function InitializeUnits() + --spEcho("Sensor Ranges LOS InitializeUnits") + InstanceVBOTable.clearInstanceTable(circleInstanceVBO) + if WG['unittrackerapi'] and WG['unittrackerapi'].visibleUnits then + local visibleUnits = WG['unittrackerapi'].visibleUnits + for unitID, unitDefID in pairs(visibleUnits) do + widget:VisibleUnitAdded(unitID, unitDefID, spGetUnitTeam(unitID), nil, true) + end + end + InstanceVBOTable.uploadAllElements(circleInstanceVBO) +end + +function widget:PlayerChanged() + local wasFullview = spec and fullview + local myPrevAllyTeamID = allyTeamID + spec, fullview = spGetSpectatingState() + allyTeamID = Spring.GetMyAllyTeamID() + local isFullview = spec and fullview + if isFullview ~= wasFullview or ((not isFullview) and allyTeamID ~= myPrevAllyTeamID) then + InitializeUnits() + end +end + +function widget:Initialize() + if Spring.GetGroundExtremes() > 50 then + widgetHandler:RemoveWidget() + return + end + if not gl.CreateShader or Spring.GetModOptions().disable_fogofwar then -- no shader support, so just remove the widget itself, especially for headless + widgetHandler:RemoveWidget() + return + end + + WG.sonarrange = { + getOpacity = function() return opacity end, + setOpacity = function(value) opacity = value end, + } + + initgl4() + + InitializeUnits() +end + +function widget:Shutdown() + if sonarStencilTexture then gl.DeleteTexture(sonarStencilTexture) end + WG.sonarrange = nil +end + +function widget:VisibleUnitAdded(unitID, unitDefID, unitTeam, reason, noupload) + --spEcho("widget:VisibleUnitAdded",unitID, unitDefID, unitTeam, reason, noupload) + unitTeam = unitTeam or spGetUnitTeam(unitID) + noupload = noupload == true + if unitRange[unitDefID] == nil or unitTeam == gaiaTeamID then return end + + if (not (spec and fullview)) and (not spIsUnitAllied(unitID)) then -- given units are still considered allies :/ + return + end -- display mode for specs + + if Spring.GetUnitIsBeingBuilt(unitID) then return end + + instanceCache[1] = unitRange[unitDefID] + + local active = spGetUnitIsActive(unitID) + local gameFrame = spGetGameFrame() + if reason == "UnitFinished" then + if active then + instanceCache[2] = spGetGameFrame() + else + instanceCache[2] = -2 -- start from full size + end + else + if active then + instanceCache[2] = gameFrame + else + instanceCache[2] = -1 * gameFrame + end + end + unitList[unitID] = active + pushElementInstance(circleInstanceVBO, + instanceCache, + unitID, --key + true, -- updateExisting + noupload, + unitID -- unitID for uniform buffers + ) +end + +function widget:VisibleUnitsChanged(extVisibleUnits, extNumVisibleUnits) + -- Note that this unit uses its own VisibleUnitsChanged, to handle the case where we go into fullview. +end + +function widget:VisibleUnitRemoved(unitID) + if circleInstanceVBO.instanceIDtoIndex[unitID] then + popElementInstance(circleInstanceVBO, unitID) + end + unitList[unitID] = nil +end + +function widget:GameFrame(n) + if spec and fullview then return end + if n % 15 == 2 then + for unitID, oldActive in pairs(unitList) do + local active = spGetUnitIsActive(unitID) + if active ~= oldActive then + unitList[unitID] = active + widget:VisibleUnitAdded(unitID, spGetUnitDefID(unitID), spGetUnitTeam(unitID) ) + end + end + end +end + +function widget:DrawWorld() + --if spec and fullview then return end + if Spring.IsGUIHidden() or + (circleInstanceVBO.usedElements == 0) or + (opacity <= 0.01) + then return end + + --gl.Clear(GL.STENCIL_BUFFER_BIT) -- Preemtively clear the stencil buffer + gl.StencilTest(true) -- Enable stencil testing + gl.StencilFunc(GL_NOTEQUAL, 2, 2) -- Always Passes, 0 Bit Plane, 0 As Mask + gl.StencilOp(GL_KEEP, GL_KEEP, GL_REPLACE) -- Set The Stencil Buffer To 1 Where Draw Any Polygon + gl.StencilMask(15) -- Only check the first bit of the stencil buffer + + sonarCircleShader:Activate() + gl.Texture(0, "$heightmap") -- Bind the heightmap texture + gl.Texture(1, sonarStencilTexture) -- Bind the heightmap texture + + sonarCircleShader:SetUniform("rangeColor", rangeColor[1], rangeColor[2], rangeColor[3], opacity ) + --spEcho("rangeColor", rangeColor[1], rangeColor[2], rangeColor[3], opacity * (useteamcolors and 2 or 1 )) + sonarCircleShader:SetUniform("teamColorMix", 0) + + gl.LineWidth(rangeLineWidth * lineScale * 1.0) + + gl.DepthTest(true) + -- Note that we are skipping the first and last vertex, as those are the center of the circle : + circleInstanceVBO.VAO:DrawArrays(GL_LINE_LOOP, circleInstanceVBO.numVertices -0, 0, circleInstanceVBO.usedElements) + -- TODO: In the future, when BASE VERTEX works, use the following line instead: + --circleInstanceVBO.VAO:DrawArrays(GL_LINE_LOOP, circleInstanceVBO.numVertices -2, 1, circleInstanceVBO.usedElements) + + sonarCircleShader:Deactivate() + gl.Texture(0, false) + gl.Texture(1, false) + gl.DepthTest(true) + gl.StencilTest(false) -- Disable stencil testing + + gl.LineWidth(1.0) + --gl.Clear(GL.STENCIL_BUFFER_BIT) +end + + +function widget:GetConfigData(data) + return { + opacity = opacity, + } +end + +function widget:SetConfigData(data) + if data.opacity ~= nil then + opacity = data.opacity + end +end + +return widget end)() +local jammer=(function()local widget={} +local widget = widget ---@type Widget + +function widget:GetInfo() + return { + name = "Sensor Ranges Jammer", + desc = "Shows Jammer ranges of all ally units. (GL4)", + author = "Beherith GL4", + date = "2021.06.18", + license = "GPLv2, (c) Beherith (mysterme@gmail.com)", + layer = 17, + enabled = true + } +end + + +-- Localized Spring API for performance +local spGetGameFrame = Spring.GetGameFrame +local spEcho = Spring.Echo +local spGetViewGeometry = Spring.GetViewGeometry + +------- Configurables: ------------------- +local debugmode = false +--- +local rangeColor = { 1.0, 0.35, 0.0, 0.35 } -- default range color +local opacity = 0.08 +local rangeLineWidth = 4.5 -- (note: will end up larger for larger vertical screen resolution size) +local lineScale = 1 -- this is a multiplier for the line width, to make it look better on high res screens + +local circleSegments = 62 -- To ensure its only 2 warps per instance +local rangecorrectionelmos = debugmode and -16 or 16 -- how much smaller they are drawn than truth due to LOS mipping +--------- End configurables ------ + +local minJammerDistance = 63 +local gaiaTeamID = Spring.GetGaiaTeamID() + +------- GL4 NOTES ----- +-- TODO: 2025.07.02: + + + + +local LuaShader = gl.LuaShader +local InstanceVBOTable = gl.InstanceVBOTable + +local popElementInstance = InstanceVBOTable.popElementInstance +local pushElementInstance = InstanceVBOTable.pushElementInstance + +local jammerStencilShader = nil +local jammerCircleShader = nil +local circleInstanceVBO = nil + +local jammerStencilTexture +local resolution = 4 +local vsx, vsy = spGetViewGeometry() + +local circleShaderSourceCache = { + shaderName = 'Jammer Ranges Circles GL4', + vssrcpath = "LuaUI/Shaders/sensor_ranges_los.vert.glsl", + fssrcpath = "LuaUI/Shaders/sensor_ranges_los.frag.glsl", + shaderConfig = { + VSX = vsx, + VSY = vsy, + RESOLUTION = resolution, + PADDING = 1, + VISIBILITYCULLING = 1, + STIPPLE_RATE = 1.0, + }, + uniformInt = { + heightmapTex = 0, + losStencilTexture = 1, + }, + uniformFloat = { + teamColorMix = 1.0, + rangeColor = rangeColor, + }, + silent = not debugmode, -- do not print shader compile timing +} + +local stencilShaderSourceCache = table.copy(circleShaderSourceCache) -- copy the circle shader source cache, and modify it for stencil pass +stencilShaderSourceCache.shaderConfig.STENCILPASS = 1 -- this is a stencil pass +stencilShaderSourceCache.shaderName = 'Jammer Ranges Stencil GL4' + +local function goodbye(reason) + spEcho("Sensor Ranges LOS widget exiting with reason: " .. reason) + widgetHandler:RemoveWidget() + return false +end + +local function CreateStencilShaderAndTexture() + vsx, vsy = spGetViewGeometry() + circleShaderSourceCache.shaderConfig.VSX = vsx + circleShaderSourceCache.shaderConfig.VSY = vsy + circleShaderSourceCache.forceupdate = true + stencilShaderSourceCache.shaderConfig.VSX = vsx + stencilShaderSourceCache.shaderConfig.VSY = vsy + stencilShaderSourceCache.forceupdate = true + + jammerStencilShader = LuaShader.CheckShaderUpdates(stencilShaderSourceCache,0) + + if not jammerStencilShader then + return goodbye("Failed to compile jammerrange stencil shader GL4 ") + end + jammerCircleShader = LuaShader.CheckShaderUpdates(circleShaderSourceCache,0) + if not jammerCircleShader then + return goodbye("Failed to compile jammerrange shader GL4 ") + end + + local GL_R8 = 0x8229 + vsx, vsy = spGetViewGeometry() + lineScale = (vsy + 500)/ 1300 + if jammerStencilTexture then gl.DeleteTexture(jammerStencilTexture) end + jammerStencilTexture = gl.CreateTexture(vsx/resolution, vsy/resolution, { + --format = GL.RGBA8, + format = GL_R8, + fbo = true, + min_filter = GL.NEAREST, + mag_filter = GL.LINEAR, + wrap_s = GL.CLAMP_TO_EDGE, + wrap_t = GL.CLAMP_TO_EDGE, + }) +end +local function initgl4() + -- Due to the view size being part of the shader config, we need to initialize the shaders after the view size is known. + + -- Note that we are createing a special Circle VBO, that starts at the center vertex! This is needed for triangle fans + local circleVBO, numVertices = InstanceVBOTable.makeCircleVBO(circleSegments, nil, true, "jammerrangeCircles") + local circleInstanceVBOLayout = { + { id = 1, name = 'radius_params', size = 4 }, -- radius, gameframe, 2 unused floats + { id = 2, name = 'instData', size = 4, type = GL.UNSIGNED_INT}, -- instData + } + + circleInstanceVBO = InstanceVBOTable.makeInstanceVBOTable(circleInstanceVBOLayout, 128, "jammerrangeVBO", 2) + circleInstanceVBO.numVertices = numVertices + circleInstanceVBO.vertexVBO = circleVBO + circleInstanceVBO.VAO = InstanceVBOTable.makeVAOandAttach(circleInstanceVBO.vertexVBO, circleInstanceVBO.instanceVBO) + + CreateStencilShaderAndTexture() +end + + +local function DrawLOSStencil() -- about 0.025 ms + if circleInstanceVBO.usedElements > 0 then + gl.Clear(GL.COLOR_BUFFER_BIT,0,0,0,0) + gl.BlendEquation(GL.MAX) + gl.Blending(GL.ONE, GL.ONE) + gl.Culling(false) + + gl.Texture(0, "$heightmap") -- Bind the heightmap texture + jammerStencilShader:Activate() + circleInstanceVBO.VAO:DrawArrays(GL.TRIANGLE_FAN, circleInstanceVBO.numVertices, 0, circleInstanceVBO.usedElements, 0) + jammerStencilShader:Deactivate() + gl.Blending(GL.SRC_ALPHA, GL.ONE_MINUS_SRC_ALPHA) + gl.BlendEquation(GL.FUNC_ADD) + end +end + +function widget:DrawGenesis() + gl.RenderToTexture(jammerStencilTexture, DrawLOSStencil) +end + +-- This shows the debug stencil texture in the bottom left corner of the screen +if debugmode then + function widget:DrawScreen() + jammerCircleShader = LuaShader.CheckShaderUpdates(circleShaderSourceCache,0) or jammerCircleShader + jammerStencilShader = LuaShader.CheckShaderUpdates(stencilShaderSourceCache,0) or jammerStencilShader + gl.Color(1,1,1,1) + gl.Blending(GL.ONE, GL.ZERO) + gl.Texture(jammerStencilTexture) + gl.TexRect(0, 0, vsx/resolution, vsy/resolution, 0, 0, 1, 1) + gl.Blending(GL.SRC_ALPHA, GL.ONE_MINUS_SRC_ALPHA) + end +end + +-- Functions shortcuts +local spGetSpectatingState = Spring.GetSpectatingState +local spIsUnitAllied = Spring.IsUnitAllied +local spGetUnitTeam = Spring.GetUnitTeam +local spGetUnitIsActive = Spring.GetUnitIsActive +local GL_NOTEQUAL = GL.NOTEQUAL +local GL_LINE_LOOP = GL.LINE_LOOP +local GL_KEEP = 0x1E00 --GL.KEEP +local GL_REPLACE = GL.REPLACE + +-- Globals +local spec, fullview = spGetSpectatingState() +local allyTeamID = Spring.GetMyAllyTeamID() + +-- find all unit types with radar in the game and place ranges into unitRange table +local unitRange = {} -- table of unit types with their radar ranges + +local unitList = {} -- all ally units and their coordinates and radar ranges + +for unitDefID, unitDef in pairs(UnitDefs) do + if unitDef.radarDistanceJam and unitDef.radarDistanceJam > minJammerDistance then -- save perf by excluding low radar range units + unitRange[unitDefID] = unitDef.radarDistanceJam + end +end + +function widget:ViewResize(newX, newY) + CreateStencilShaderAndTexture() +end + +-- a reusable table, since we will literally only modify its first element. +local instanceCache = {0,0,0,0,0,0,0,0} + +local function InitializeUnits() + --spEcho("Sensor Ranges LOS InitializeUnits") + InstanceVBOTable.clearInstanceTable(circleInstanceVBO) + if WG['unittrackerapi'] and WG['unittrackerapi'].visibleUnits then + local visibleUnits = WG['unittrackerapi'].visibleUnits + for unitID, unitDefID in pairs(visibleUnits) do + widget:VisibleUnitAdded(unitID, unitDefID, spGetUnitTeam(unitID), nil, true) + end + end + InstanceVBOTable.uploadAllElements(circleInstanceVBO) +end + +function widget:PlayerChanged() + local wasFullview = spec and fullview + local myPrevAllyTeamID = allyTeamID + spec, fullview = spGetSpectatingState() + allyTeamID = Spring.GetMyAllyTeamID() + local isFullview = spec and fullview + if isFullview ~= wasFullview or ((not isFullview) and allyTeamID ~= myPrevAllyTeamID) then + InitializeUnits() + end +end + +function widget:Initialize() + if not gl.CreateShader or Spring.GetModOptions().disable_fogofwar then -- no shader support, so just remove the widget itself, especially for headless + widgetHandler:RemoveWidget() + return + end + + WG.jammerrange = { + getOpacity = function() return opacity end, + setOpacity = function(value) opacity = value end, + } + + initgl4() + + InitializeUnits() +end + +function widget:Shutdown() + if jammerStencilTexture then gl.DeleteTexture(jammerStencilTexture) end + WG.jammerrange = nil +end + +function widget:VisibleUnitAdded(unitID, unitDefID, unitTeam, reason, noupload) + --spEcho("widget:VisibleUnitAdded",unitID, unitDefID, unitTeam, reason, noupload) + unitTeam = unitTeam or spGetUnitTeam(unitID) + noupload = noupload == true + if unitRange[unitDefID] == nil or unitTeam == gaiaTeamID then return end + + if (not (spec and fullview)) and (not spIsUnitAllied(unitID)) then -- given units are still considered allies :/ + return + end -- display mode for specs + + if Spring.GetUnitIsBeingBuilt(unitID) then return end + + instanceCache[1] = unitRange[unitDefID] + + + local active = spGetUnitIsActive(unitID) + local gameFrame = spGetGameFrame() + if reason == "UnitFinished" then + if active then + instanceCache[2] = spGetGameFrame() + else + instanceCache[2] = -2 -- start from full size + end + else + if active then + instanceCache[2] = gameFrame + else + instanceCache[2] = -1 * gameFrame + end + end + unitList[unitID] = active + pushElementInstance(circleInstanceVBO, + instanceCache, + unitID, --key + true, -- updateExisting + noupload, + unitID -- unitID for uniform buffers + ) +end + +function widget:VisibleUnitsChanged(extVisibleUnits, extNumVisibleUnits) + -- Note that this unit uses its own VisibleUnitsChanged, to handle the case where we go into fullview. +end + +function widget:VisibleUnitRemoved(unitID) + if circleInstanceVBO.instanceIDtoIndex[unitID] then + popElementInstance(circleInstanceVBO, unitID) + end + unitList[unitID] = nil +end + +function widget:GameFrame(n) + if spec and fullview then return end + if n % 15 == 0 then + for unitID, oldActive in pairs(unitList) do + local active = spGetUnitIsActive(unitID) + if active ~= oldActive then + unitList[unitID] = active + widget:VisibleUnitAdded(unitID, Spring.GetUnitDefID(unitID), spGetUnitTeam(unitID) ) + end + end + end +end + +function widget:DrawWorld() + --if spec and fullview then return end + if Spring.IsGUIHidden() or + (circleInstanceVBO.usedElements == 0) or + (opacity <= 0.01) + then return end + + --gl.Clear(GL.STENCIL_BUFFER_BIT) -- Preemtively clear the stencil buffer + gl.StencilTest(true) -- Enable stencil testing + gl.StencilFunc(GL_NOTEQUAL, 8, 8) -- Always Passes, 0 Bit Plane, 0 As Mask + gl.StencilOp(GL_KEEP, GL_KEEP, GL_REPLACE) -- Set The Stencil Buffer To 1 Where Draw Any Polygon + gl.StencilMask(15) -- Only check the first bit of the stencil buffer + + jammerCircleShader:Activate() + gl.Texture(0, "$heightmap") -- Bind the heightmap texture + gl.Texture(1, jammerStencilTexture) -- Bind the heightmap texture + + jammerCircleShader:SetUniform("rangeColor", rangeColor[1], rangeColor[2], rangeColor[3], opacity ) + --spEcho("rangeColor", rangeColor[1], rangeColor[2], rangeColor[3], opacity * (useteamcolors and 2 or 1 )) + jammerCircleShader:SetUniform("teamColorMix", 0) + + gl.LineWidth(rangeLineWidth * lineScale * 1.0) + + gl.DepthTest(true) + -- Note that we are skipping the first and last vertex, as those are the center of the circle : + circleInstanceVBO.VAO:DrawArrays(GL_LINE_LOOP, circleInstanceVBO.numVertices -0, 0, circleInstanceVBO.usedElements) + -- TODO: In the future, when BASE VERTEX works, use the following line instead: + --circleInstanceVBO.VAO:DrawArrays(GL_LINE_LOOP, circleInstanceVBO.numVertices -2, 1, circleInstanceVBO.usedElements) + + jammerCircleShader:Deactivate() + gl.Texture(0, false) + gl.Texture(1, false) + gl.DepthTest(true) + gl.StencilTest(false) -- Disable stencil testing + + gl.LineWidth(1.0) + gl.Clear(GL.STENCIL_BUFFER_BIT) +end + + +function widget:GetConfigData(data) + return { + opacity = opacity, + } +end + +function widget:SetConfigData(data) + if data.opacity ~= nil then + opacity = data.opacity + end +end + +return widget end)() +local sensors={{kind="los",widget=los},{kind="radar",widget=radar},{kind="sonar",widget=sonar},{kind="jammer",widget=jammer}} +-- The original tracker owns admission; each unchanged widget owns its own +-- membership, construction timestamps, activity cadence and range correction. +-- No browser definition lookup or reconstructed activity enters this state. +for _,name in ipairs({'VisibleUnitAdded','VisibleUnitRemoved','VisibleUnitsChanged'})do + listeners[name]=function(...) + for _,entry in ipairs(sensors)do sensorCall(entry.widget,name,...)end + end +end +for _,name in ipairs({'UnitCreated','UnitFinished','UnitDestroyed','UnitTaken','UnitGiven','UnitEnteredLos','UnitLeftLos'})do + _G[name]=function(...)return sensorCall(tracker,name,...)end +end +function GameFrame(frame) + sensorCall(tracker,'GameFrame',frame) + for _,entry in ipairs(sensors)do sensorCall(entry.widget,'GameFrame',frame)end +end +function PlayerChanged(player) + sensorCall(tracker,'PlayerChanged',player) + for _,entry in ipairs(sensors)do sensorCall(entry.widget,'PlayerChanged',player)end +end +function WebbarSensorGroupsInitialize() + sensorCall(tracker,'Initialize') + for _,entry in ipairs(sensors)do sensorCall(entry.widget,'Initialize')end + return not removedWidgets[tracker] +end +function WebbarSensorGroupsState() + local result={frame=Spring.GetGameFrame(),groups={}} + for index,entry in ipairs(sensors)do + local disabled=removedWidgets[tracker]or removedWidgets[entry.widget]or false + local api=WG[entry.kind..'range'] + local group={kind=entry.kind,disabled=disabled,opacity=not disabled and api and api.getOpacity()or 0,rows={}} + result.groups[index]=group + if not disabled then + local buffer=assert(WG.VBOTableRegistry[entry.kind..'rangeVBO']) + assert(buffer.usedElements<=65536 and buffer.instanceStep==8) + for i=1,buffer.usedElements do + local id=assert(buffer.indextoInstanceID[i]);local offset=(i-1)*8 + group.rows[i]={id=id,params={buffer.instanceData[offset+1],buffer.instanceData[offset+2],buffer.instanceData[offset+3],buffer.instanceData[offset+4]}} + end + end + end + return result +end + +)WEBBAR_GROUPS"; --- /dev/null +++ b/rts/Game/WebbarNativeSensorPolicy.h @@ -0,0 +1,5265 @@ +/* Original BAR GPL v2 or later widget policy; generated by scripts/native-sensor-ranges.mjs. */ +#pragma once +static constexpr const char* WEBBAR_SENSOR_POLICY=R"WEBBAR_SENSOR( +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 +Spring.GetConfigInt=function()return 0 end +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)() +local tracker=(function()local widget={} +local widget = widget ---@type Widget + +function widget:GetInfo() + return { + name = "API Unit Tracker DEVMODE GL4", + desc = "Manages alliedunitslist, visibleunitslist", + author = "Beherith", + date = "2022.02.18", + license = "GNU GPL, v2 or later", + layer = -828888, + handler = true, + enabled = true, + depends = {'gl4'} + } +end + + +-- Localized Spring API for performance +local spGetGameFrame = Spring.GetGameFrame +local spGetMyTeamID = Spring.GetMyTeamID +local spGetMyAllyTeamID = Spring.GetMyAllyTeamID +local spEcho = Spring.Echo +local spGetAllUnits = Spring.GetAllUnits +local spGetSpectatingState = Spring.GetSpectatingState + +local debuglevel = 0 +-- debuglevel 0 is no debugging +-- debuglevel 1 is show warnings for stuff periodicly and make self crash +-- debuglevel 2 is verbose +-- debuglevel 3 is super verbose mode + +local debugdrawvisible = false +local L_DEPRECATED = LOG.DEPRECATED +-- This widget's job is to provide a common interface for GL4 drawing widgets, that rely on having visible units present +-- Widget draw classes: +-- widgets that draw stuff for all visible units (trivial case) +-- widgets that only draw for allies, turn into widgets that draw for all once you enter specfullview + -- which is pretty much just sensor ranges los + -- rank icons + -- flank icons + +-- TODO: +-- filter decoration unitDefIDs, but not gaia (neutrals) -- done +-- do taken/given correctly by add-remove -- done +-- the callins should all pass unitID, unitDefID, and unitTeam (note the issues with taken unitteams!) +-- remove crashing aircraft - not actually needed methinks, since no bugs came up +-- BIG ASS TODO: dont reinit when in spec mode! +-- -- WE DONT HAVE WIDGETS THAT REMAIN PLAYER ONLY!!!!!!!!!! +-- todo: make debug mode an int (verbosity) -- done +-- todo: make addunit not call callins on reinit -- done +-- todo: make a callout or a WG table entry -- yes we need a wg entry +-- todo: finalize alliedunit/visibleunit differences -- done +-- todo: also pass unitteam, as it must be present! - done +-- todo: fix drawdebugvisible to be changeable - done +-- todo: test this in singleplayer scenarios, and loaded games! + +-- SUPER IMPORTANT: NEVER EVER ADD UNITS TO A VBO TABLE THAT ARE IN unitDefIgnore! +-- As the unit tracker api wont track them as actual units, and wont ever remove them either! + + +local alliedUnits = {} -- table of unitID : unitDefID +local alliedUnitsTeam = {} -- table of unitID : unitTeam +local numAlliedUnits = 0 + +local visibleUnits = {} -- table of unitID : unitDefID +local visibleUnitsTeam = {} -- table of unitID : unitTeam +local numVisibleUnits = 0 + +local unitDefIgnore = {} + +local factoryUnitDefIDs = {} -- key unitdefid, internalname + +local lastknownunitpos = {} -- table on unitID to {x,y,z} + +local gameFrame = spGetGameFrame() + +for unitDefID, unitDef in pairs(UnitDefs) do + if unitDef.customParams and unitDef.customParams.nohealthbars then + --unitDefIgnore[unitDefID] = true + end --ignore debug units + if unitDef.isFactory then + factoryUnitDefIDs[unitDefID] = unitDef.name + end + +end + +--- GL4 STUFF --- + +local LuaShader = gl.LuaShader +local InstanceVBOTable = gl.InstanceVBOTable + +local pushElementInstance = InstanceVBOTable.pushElementInstance +local popElementInstance = InstanceVBOTable.popElementInstance + +local unitTrackerVBO = nil +local unitTrackerShader = nil +local luaShaderDir = "LuaUI/Include/" +local texture = "luaui/images/solid.png" + +local function initGL4() + local DrawPrimitiveAtUnit = VFS.Include(luaShaderDir.."DrawPrimitiveAtUnit.lua") + local InitDrawPrimitiveAtUnit = DrawPrimitiveAtUnit.InitDrawPrimitiveAtUnit + local shaderConfig = DrawPrimitiveAtUnit.shaderConfig -- MAKE SURE YOU READ THE SHADERCONFIG TABLE in DrawPrimitiveAtUnit.lua + shaderConfig.TRANSPARENCY = 0.5 + shaderConfig.ANIMATION = 0 + shaderConfig.HEIGHTOFFSET = 3.99 + -- MATCH CUS position as seed to sin, then pass it through geoshader into fragshader + --shaderConfig.POST_VERTEX = "v_parameters.w = max(-0.2, sin(timeInfo.x * 2.0/30.0 + (v_centerpos.x + v_centerpos.z) * 0.1)) + 0.2; // match CUS glow rate" + unitTrackerVBO, unitTrackerShader = InitDrawPrimitiveAtUnit(shaderConfig, "unitTracker") +end + +-- speedups +local spGetUnitTeam = Spring.GetUnitTeam +local spGetUnitDefID = Spring.GetUnitDefID +local spGetUnitPosition = Spring.GetUnitPosition +local spValidUnitID = Spring.ValidUnitID +local spGetUnitIsDead = Spring.GetUnitIsDead +local spGetUnitLosState = Spring.GetUnitLosState +local spAreTeamsAllied = Spring.AreTeamsAllied +local spGetUnitHealth = Spring.GetUnitHealth + +-- scriptproxies: +--[[ NB: these are proxies, not the actual lua functions currently linked LuaUI-side, + so it is safe to cache them here even if the underlying func changes afterwards ]] +local scriptLuauiVisibleUnitAdded +local scriptLuauiVisibleUnitRemoved +local scriptLuauiVisibleUnitsChanged + +local scriptLuauiAlliedUnitAdded +local scriptLuauiAlliedUnitRemoved +local scriptLuauiAlliedUnitsChanged + +local function Scream(reason, unitID) -- This will pause the game and play some sound to alert anyone in debug mode of issue + --Spring.Debug.TraceFullEcho(nil,nil,nil, reason) + Spring.Debug.TraceEcho('API Unit Tracker error', reason) + if unitID ~= nil then + -- gather as much info as possible about this unitID + local unitDefID = spGetUnitDefID(unitID) + local unitTeam = spGetUnitTeam(unitID) + local ux,uy,uz = spGetUnitPosition(unitID) + spEcho('API Unit Tracker error unitID', unitID, unitDefID and (UnitDefs[unitDefID].name) or "nil", unitTeam, px, pz) + end + if lastknownunitpos[unitID] then + Spring.MarkerAddPoint(lastknownunitpos[unitID][1], lastknownunitpos[unitID][2], lastknownunitpos[unitID][3], lastknownunitpos[unitID][4], true) + end + Spring.Debug.TraceFullEcho() + local unittrackerapinil = nil + unittrackerapinil = unittrackerapinil + 1 -- this intentionally crashes this widget so that it will show up in analytics + if debuglevel >=3 then + Spring.SendCommands({"pause 1"}) + Spring.PlaySoundFile("commanderspawn", 1.0, 'ui') + end +end + +local function alliedUnitsChanged() + if debuglevel >= 2 then Spring.Debug.TraceEcho() end + if Script.LuaUI('AlliedUnitsChanged') then + Script.LuaUI.AlliedUnitsChanged(visibleUnits, numVisibleUnits) + else + if debuglevel > 0 then spEcho("Script.LuaUI.AlliedUnitsChanged() unavailable") end + end +end + +local function alliedUnitsAdd(unitID, unitDefID, unitTeam, silent) + if debuglevel >= 3 then Spring.Debug.TraceEcho(numAlliedUnits) end + if alliedUnits[unitID] then + if debuglevel >= 2 then spEcho("alliedUnitsAdd", "tried to add existing unitID", unitID) end + return + end -- already known + alliedUnits[unitID] = unitDefID + alliedUnitsTeam[unitID] = unitTeam + numAlliedUnits = numAlliedUnits + 1 + if silent then return end + if Script.LuaUI('AlliedUnitAdded') then + Script.LuaUI.AlliedUnitAdded(unitID, unitDefID, unitTeam) + else + if debuglevel >= 1 then spEcho("Script.LuaUI.AlliedUnitAdded() unavailable") end + end + -- call all listeners +end + +local function alliedUnitsRemove(unitID, reason) + if debuglevel >= 3 then Spring.Debug.TraceEcho(numAlliedUnits) end + if alliedUnits[unitID] then + local unitDefID = alliedUnits[unitID] + alliedUnits[unitID] = nil + local unitTeam = alliedUnitsTeam[unitID] + alliedUnitsTeam[unitID] = nil + numAlliedUnits = numAlliedUnits - 1 + -- call all listeners + if Script.LuaUI('AlliedUnitRemoved') then + Script.LuaUI.AlliedUnitRemoved(unitID, unitDefID, unitTeam) + end + else + if debuglevel >= 2 then spEcho("alliedUnitsRemove", "tried to remove non-existing unitID", unitID, reason) end + end +end + +local function GetAlliedUnits() + if debuglevel >= 2 then Spring.Debug.TraceEcho() end + return alliedUnits, numAlliedUnits +end + +local function visibleUnitsChanged() + if debuglevel >=3 then Spring.Debug.TraceEcho() end + if Script.LuaUI('VisibleUnitsChanged') then + Script.LuaUI.VisibleUnitsChanged(visibleUnits, numVisibleUnits) + else + if debuglevel > 0 then spEcho("Script.LuaUI.VisibleUnitsChanged() unavailable") end + end +end + +local instanceVBOCacheTable = { + 96, 32, 8, 8, -- lengthwidthcornerheight + 0, -- teamID + 2, -- how many trianges should we make (2 = cornerrect) + 0, 0, 0, 0, -- the gameFrame (for animations), and any other parameters one might want to add + 0, 1, 0, 1, -- These are our default UV atlas tranformations + 0, 0, 0, 0 -- these are just padding zeros, that will get filled in + } + +local function visibleUnitsAdd(unitID, unitDefID, unitTeam, silent, reason) + if debuglevel >= 3 then Spring.Debug.TraceEcho(numVisibleUnits) end + if visibleUnits[unitID] then -- already known + if debuglevel >= 2 then spEcho("visibleUnitsAdd", "tried to add existing unitID", unitID) end + return + end + visibleUnits[unitID] = unitDefID + visibleUnitsTeam[unitID] = unitTeam + numVisibleUnits = numVisibleUnits + 1 + if debugdrawvisible then + unitTeam = unitTeam or spGetUnitTeam(unitID) or 0 + instanceVBOCacheTable[5] = unitTeam + instanceVBOCacheTable[7] = gameFrame + + pushElementInstance( + unitTrackerVBO, -- push into this Instance VBO Table + instanceVBOCacheTable, + unitID, -- this is the key inside the VBO TAble, + true, -- update existing element + nil, -- noupload, dont use unless you know what you are doing + unitID -- last one should be UNITID? + ) + end + -- call all listeners: + if silent then return end + if Script.LuaUI('VisibleUnitAdded') then + Script.LuaUI.VisibleUnitAdded(unitID, unitDefID, unitTeam, reason) + else + if debuglevel >= 1 then spEcho("Script.LuaUI.VisibleUnitAdded() unavailable") end + end +end + +local function visibleUnitsRemove(unitID, reason) + if debuglevel >= 3 then + Spring.Debug.TraceEcho(numVisibleUnits) + if lastknownunitpos[unitID] then lastknownunitpos[unitID] = nil end + end + if visibleUnits[unitID] then + local unitDefID = visibleUnits[unitID] + visibleUnits[unitID] = nil + local unitTeam = visibleUnitsTeam[unitID] + visibleUnitsTeam[unitID] = nil + numVisibleUnits = numVisibleUnits - 1 + + if debugdrawvisible then + popElementInstance(unitTrackerVBO, unitID) + end + -- call all listeners + if Script.LuaUI('VisibleUnitRemoved') then + Script.LuaUI.VisibleUnitRemoved(unitID, unitDefID, unitTeam, reason) + end + else + if debuglevel >= 2 then spEcho("visibleUnitsRemove", "tried to remove non-existing unitID", unitID, reason) end + end +end + +local function GetVisibleUnits() + if debuglevel >= 2 then Spring.Debug.TraceEcho() end + return visibleUnits, numVisibleUnits +end + +local spec, fullview = spGetSpectatingState() +local myTeamID = spGetMyTeamID() +local myAllyTeamID = spGetMyAllyTeamID() +local myPlayerID = Spring.GetMyPlayerID() + +local function isValidLivingSeenUnit(unitID, unitDefID, verbose) + --[[ + -- This isnt helping + if type(myAllyTeamID) ~= "number" or (type(myAllyTeamID) == "number" and ((myAllyTeamID < 0 ) or (myAllyTeamID > 32))) then + local localMyAllyTeamID = myAllyTeamID + Spring.Debug.TraceFullEcho(nil,nil,nil, "api_unit_tracker_gl4 error on myAllyTeamID") + end + ]]-- + + -- strange, ALL of these will be evaluated, which explains the crash, because according to the evaluation order, + -- unitDef is not nil yet + -- unitID is valid + -- unit + -- SPECTATING SYNTHETIC in that replay from start and /skip 1 DOES THIS SHIT! 20220307_201548_DSDR 4_105.1.1-861-ge8bf8a9 BAR105.sdfz + -- Which is odd, because that commander belongs to petTurtle, who is on the other allyteam anyway, so this shouldnt really ever get called + -- now why that allyteamID is invalid, I dont really know yet, as the allyteamID == 1, which seems sane + + if unitDefID == nil then return false end + if spValidUnitID(unitID) ~= true then return false end + if spGetUnitIsDead(unitID) == true then return false end + if unitDefIgnore[unitDefID] then return false end + if ((not fullview) and (spGetUnitLosState(unitID, myAllyTeamID, true) % 2 == 0)) then return false end + + if debuglevel >= (verbose or 0) then + if unitDefID == nil or + spValidUnitID(unitID) ~= true or + spGetUnitIsDead(unitID) == true or + ((not fullview) and (spGetUnitLosState(unitID, myAllyTeamID, true) % 2 == 0)) or -- outside of LOS + unitDefIgnore[unitDefID] then + if debuglevel >= (verbose or 0) then + Spring.Debug.TraceEcho() + spEcho("not isValidLivingSeenUnit", + 'unitDefID', unitDefID, + 'ValidUnitID', spValidUnitID(unitID), + 'GetUnitIsDead', spGetUnitIsDead(unitID), + 'Ignore', unitDefIgnore[unitDefID], + 'LOSstate', spGetUnitLosState(unitID, myAllyTeamID, true) + ) + end + return false + end + end + + return true +end + + +function widget:UnitCreated(unitID, unitDefID, unitTeam, builderID, reason, silent) -- this was visible at the time + + --[[ + local currentspec, currentfullview = spGetSpectatingState() + local currentAllyTeamID = Spring.GetMyAllyTeamID() + local currentTeamID = spGetMyTeamID() + local currentPlayerID = Spring.GetMyPlayerID() + if true or debuglevel >= 2 then + spEcho("UnitCreated PlayerChanged", + "spec", spec, "->",currentspec, + " fullview:", fullview , "->", currentfullview, + " team:", myTeamID , "->", currentTeamID, + " allyteam:", myAllyTeamID , "->", currentAllyTeamID, + " player:", myPlayerID , "->", currentPlayerID + ) + end + + if gameFrame <= 1000 then + spEcho("UnitCreated Pre-gameFrame", unitID, unitDefID, unitTeam, builderID, reason, silent, gameFrame) + spEcho(UnitDefs[unitDefID].name) + local px, py, pz = Spring.GetUnitPosition(unitID) + spEcho('pos',px, py, pz) + spEcho("Mystate", spec, fullview, myAllyTeamID, myTeamID, myPlayerID ) + end + ]]-- + + if gameFrame <= 0 and not fullview then + local currentAllyTeamID = spGetMyAllyTeamID() + if myAllyTeamID ~= currentAllyTeamID then + widget:PlayerChanged() + end + end + + unitDefID = unitDefID or spGetUnitDefID(unitID) + if debuglevel >= 3 then spEcho("UnitCreated", unitID, unitDefID and UnitDefs[unitDefID].name, unitTeam, reason) end + + if isValidLivingSeenUnit(unitID, unitDefID, 3) == false then return end + + -- Units that are cheated or spawned will fire unitcreated, then unitfinished right after each other + -- In this case, their health is already maxhealth, and their buildprogress is 0. + -- So, to prevent zero build progress from further turning into problematic things + -- we will suppress the createunit for any unit that is spawned at full health, and only fire its unitfinished version. + -- So we are relying on UnitFinished to be called right after this one + -- Sensibly enough, this is not a problem for players, as they see the units only after their LOS status is checked, later in the same gameframe. + -- So spectators, and 'own team' suffers this hit only + local health,maxhealth, paralyzeDamage,captureProgress,buildProgress = spGetUnitHealth(unitID) + if health == maxhealth and buildProgress == 0 then + if debuglevel >= 3 then + spEcho("Skipping visibleUnitsAdd for CreateUnit'ed unit", UnitDefs[unitDefID].name, unitID, unitDefID, unitTeam, builderID, reason, silent) + end + return + end + + -- alliedunits + if spAreTeamsAllied(unitTeam, myTeamID) then + alliedUnitsAdd(unitID, unitDefID, unitTeam, silent) + end + + -- visibleUnits + if visibleUnits[unitID] == nil then + visibleUnitsAdd(unitID, unitDefID, unitTeam, silent, reason) + end +end + +function widget:UnitDestroyed(unitID, unitDefID, unitTeam, attackerID, attackerDefID, attackerTeam, weaponDefID, reason) + if debuglevel >= 3 then + unitDefID = unitDefID or spGetUnitDefID(unitID) + spEcho("UnitDestroyed",unitID, unitDefID and UnitDefs[unitDefID].name, unitTeam, nil, nil, nil, nil, reason) + end + visibleUnitsRemove(unitID, reason or "UnitDestroyed") + alliedUnitsRemove(unitID, reason or "UnitDestroyed") +end + +--function widget:CrashingAircraft(unitID, unitDefID, teamID) + --spEcho("Global:GadgetCrashingAircraft",unitID, unitDefID, teamID) +--end + + +--function widget:UnitDestroyedByTeam(unitID, unitDefID, unitTeam) + --alliedUnitsRemove(unitID) + --visibleUnitsRemove(unitID) +--end + +function widget:UnitFinished(unitID, unitDefID, unitTeam) -- todo, this should probably add-remove a unit + widget:UnitDestroyed(unitID, unitDefID, unitTeam, nil, nil, nil, nil, "UnitFinished") + widget:UnitCreated(unitID, unitDefID, unitTeam, nil, "UnitFinished") + if unitTeam == myTeamID and factoryUnitDefIDs[unitDefID] then + widgetHandler:AddSpadsMessage("UnitFinished:"..tostring(factoryUnitDefIDs[unitDefID])) + end +end + +function widget:UnitTaken(unitID, unitDefID, oldTeam, newTeam) --1. this is only called when one if my units gets captured + widget:UnitDestroyed(unitID, unitDefID, oldTeam, nil, nil, nil, nil, "UnitTaken") + -- not needed, as the unit will call enemyenteredlos, but what if we are spec? + if not fullview then + -- todo, look at this real closely if its even needed! + --widget:UnitCreated(unitID, unitDefID, newTeam, nil, "UnitTaken") + end +end + +function widget:UnitGiven(unitID, unitDefID, newTeam, oldTeam) --2. this is only called when my team captures a unit + widget:UnitDestroyed(unitID, unitDefID, oldTeam, nil, nil, nil, nil, "UnitGiven") -- to ensure that team changes will trigger from this! + widget:UnitCreated(unitID, unitDefID, newTeam, nil, "UnitGiven") +end + +-- one of the most difficult test cases here, when the transfer of a unit happens between two other teams (1 and 2, we are 0) +-- only the unitenteredlos part gets called for us! +-- this is quite a severe problem, as we can see that only the unitenteredlos/radar gets recalled! +-- solution: in the api_widget_events gadget, we need to forward this too! + +--[[ +[t=00:04:53.877051][f=0004348] g:UnitTaken, 24007, armacv, 2, 1 +[t=00:04:53.877107][f=0004348] g:UnitEnteredLos, 24007, 1 +[t=00:04:53.877163][f=0004348] w:UnitEnteredLos, 24007, 1 +[t=00:04:53.877198][f=0004348] g:UnitEnteredRadar, 24007, 1 +[t=00:04:53.877213][f=0004348] w:UnitEnteredRadar, 24007, 1 +[t=00:04:53.877228][f=0004348] g:UnitEnteredLos, 24007, 1 +[t=00:04:53.877240][f=0004348] g:UnitEnteredRadar, 24007, 1 +[t=00:04:53.877277][f=0004348] g:UnitGiven, 24007, armacv, 1, 2 +[t=00:04:53.877451][f=0004348] g:UnitIdle, 24007, armacv, 1 +[t=00:04:53.909507][f=0004349] g:UnitLeftLos, 14177, 1 +[t=00:04:53.909535][f=0004349] g:UnitLeftRadar, 14177, 1 +[t=00:04:53.909549][f=0004349] g:UnitLeftLos, 24007, 1 +[t=00:04:53.909562][f=0004349] g:UnitLeftRadar, 24007, 1 +[t=00:04:54.109905][f=0004355] g:UnitCmdDone, 14177, corcom, 1, 130,
,
, 16 +[t=00:04:54.109951][f=0004355] g:UnitIdle, 14177, corcom, 1 +]]-- + + +function widget:UnitEnteredLos(unitID, unitTeam, allyTeam, unitDefID) + if not fullview then + widget:UnitCreated(unitID, unitDefID, unitTeam, nil, "UnitEnteredLos") + end +end + +function widget:UnitLeftLos(unitID, unitTeam, allyTeam, unitDefID) + if not fullview then + widget:UnitDestroyed(unitID, unitDefID, unitTeam, nil, nil, nil, nil, "UnitLeftLos") + end +end + +function widget:GameFrame() + --spEcho("GameFrame", gameFrame, "->", spGetGameFrame()) + gameFrame = spGetGameFrame() + if debuglevel >= 1 then -- here we will scan all units and ensure that they match what we expect + if (debuglevel <= 2) and (math.random() > 0.05 ) then return end -- lower frequency at smaller debug levels + local allunits = spGetAllUnits() + local allunitsTable = {} + for i = 1, #allunits do + local unitID = allunits[i] + if isValidLivingSeenUnit(unitID, spGetUnitDefID(unitID), 3) then + allunitsTable[unitID] = true + end + end + + local cntvisibleunits = 0 + for unitID, unitDefID in pairs(visibleUnits) do + if allunitsTable[unitID] == nil then + Scream("A unitID from visibleUnits is not in allunitstable: " .. tostring(unitID)) + end + + if isValidLivingSeenUnit(unitID, unitDefID, 3) then + cntvisibleunits = cntvisibleunits + 1 + local ux, uy, uz = spGetUnitPosition(unitID) + local unitDefName = UnitDefs[spGetUnitDefID(unitID)].name + if lastknownunitpos[unitID] then + lastknownunitpos[unitID][1] = ux + lastknownunitpos[unitID][2] = uy + lastknownunitpos[unitID][3] = uz + lastknownunitpos[unitID][4] = unitDefName + else + lastknownunitpos[unitID] = {ux,uy,uz, unitDefName} + end + else + isValidLivingSeenUnit(unitID, unitDefID, 1) + Scream("Unit in visibleUnits does not exist", unitID) + end + end + if cntvisibleunits ~= numVisibleUnits then + Scream("cntvisibleunits ~= numVisibleUnits " .. tostring(cntvisibleunits) .. " vs " .. tostring(numVisibleUnits)) + end + + if drawdebugvisible then + InstanceVBOTable.locateInvalidUnits(unitTrackerVBO) + end + + local cntalliedunits = 0 + for unitID, unitDefID in pairs(alliedUnits) do + if allunitsTable[unitID] == nil then + Scream("A unitID from alliedUnits is not in allunitstable: " .. tostring(unitID)) + end + + if isValidLivingSeenUnit(unitID, unitDefID, 3) then + cntalliedunits = cntalliedunits + 1 + else + isValidLivingSeenUnit(unitID, unitDefID, 1) + Scream("Unit in alliedunits does not exist", unitID) + end + end + if cntalliedunits ~= numAlliedUnits then + Scream("cntalliedunits ~= numAlliedUnits " .. tostring(cntalliedunits) .. " vs " .. tostring(numAlliedUnits)) + end + + if debugdrawvisible then + unitTrackerVBO.debug = true + end + end +end + +function widget:DrawWorldPreUnit() + if Spring.IsGUIHidden() then + return + end + + if debugdrawvisible then + -- spEcho("Drawing unitTracker", unitTrackerVBO.usedElements) + if unitTrackerVBO.usedElements > 0 then + gl.Texture(0, texture) + unitTrackerShader:Activate() + unitTrackerShader:SetUniform("iconDistance", 99999) -- pass + unitTrackerShader:SetUniform("addRadius", 0) + gl.DepthTest(true) + gl.DepthMask(false) + unitTrackerVBO.VAO:DrawArrays(GL.POINTS, unitTrackerVBO.usedElements) + unitTrackerShader:Deactivate() + gl.Texture(0, false) + end + end +end + +local function initializeAllUnits() + alliedUnits = {} + alliedUnitsTeam = {} + numAlliedUnits = 0 + + visibleUnits = {} + visibleUnitsTeam = {} + numVisibleUnits = 0 + + if debuglevel >= 2 then + spEcho("initializeAllUnits()", + "spec", spec, + " fullview:", fullview , + " team:", myTeamID , + " allyteam:", myAllyTeamID , + " player:", myPlayerID + ) + end + + if debugdrawvisible then + InstanceVBOTable.clearInstanceTable(unitTrackerVBO) + end + + local allunits = spGetAllUnits() + for i, unitID in pairs (allunits) do + widget:UnitCreated(unitID, spGetUnitDefID(unitID), spGetUnitTeam(unitID), nil, "initializeAllUnits", true) -- silent is true + end + + WG['unittrackerapi'].visibleUnits = visibleUnits + WG['unittrackerapi'].visibleUnitsTeam = visibleUnitsTeam + WG['unittrackerapi'].alliedUnits = alliedUnits + WG['unittrackerapi'].alliedUnitsTeam = alliedUnitsTeam + visibleUnitsChanged() + alliedUnitsChanged() +end + +local function debugapiunittrackerCmd(_, line) + local param = line or "" + if param == 'draw' then + spEcho("Debug mode for API Unit Tracker GL4 set to draw:", not debugdrawvisible) + if debugdrawvisible then + InstanceVBOTable.clearInstanceTable(unitTrackerVBO) + debugdrawvisible = false + else + debugdrawvisible = true + initGL4() + initializeAllUnits() + end + end + if tonumber(param) then + local newdebuglevel = tonumber(param) + if newdebuglevel ~= debuglevel then + spEcho("Debug level for API Unit Tracker GL4 set to:", newdebuglevel) + debuglevel = newdebuglevel + end + end + return true +end + +local function executeCmd(_, line) + local cmd = line or "" + local success, functionize = pcall(loadstring('return function() return {' .. cmd .. '} end')) + if not success then + spEcho("Failed to parse command:", success, cmd) + else + local ok, data = pcall(functionize) + if not ok then + spEcho("Failed to execute command:", ok, cmd) + else + if type(data) == type({}) then + if #data == 1 then + spEcho(data[1]) + elseif #data == 0 then + spEcho("nil") + else + spEcho(data) + end + else + spEcho(data) + end + end + end + return true +end + +local function noreturnexecuteCmd(_, line) + local cmd = line or "" + local success, functionize = pcall(loadstring('return function() ' .. cmd .. ' end')) + if not success then + spEcho("Failed to parse command:", success, cmd) + else + local ok, data = pcall(functionize) + if not ok then + spEcho("Failed to execute command:", ok, cmd) + else + if type(data) == type({}) then + if #data == 1 then + spEcho(data[1]) + elseif #data == 0 then + spEcho("nil") + else + spEcho(data) + end + else + spEcho(data) + end + end + end + return true +end + +local function RegisterTextAction(actionName, handler) + if widgetHandler.AddAction then + widgetHandler:AddAction(actionName, handler, nil, "t") + elseif widgetHandler.actionHandler and widgetHandler.actionHandler.AddAction then + widgetHandler.actionHandler:AddAction(widget, actionName, handler, nil, "t") + end +end + +local function UnregisterTextAction(actionName) + if widgetHandler.RemoveAction then + widgetHandler:RemoveAction(actionName, "t") + elseif widgetHandler.actionHandler and widgetHandler.actionHandler.RemoveAction then + widgetHandler.actionHandler:RemoveAction(widget, actionName) + end +end + +function widget:PlayerChanged(playerID) + -- VERY IMPORTANT NOTE: + -- When starting up a game, and spectating a player (e.g. /spec 2), or clicking on them in playerTV, + -- My allyTeamID and myTeamID BOTH get RESET internally by the engine on game start! + -- and this does NOT result in a playerchanged callin + -- the fullview variable is not changed, however + + local currentspec, currentfullview = spGetSpectatingState() + local currentAllyTeamID = spGetMyAllyTeamID() + local currentTeamID = spGetMyTeamID() + local currentPlayerID = Spring.GetMyPlayerID() + + local reinit = false + + -- testing for visibleUnitsChanged and alliedUnitsChanged + + if debuglevel >= 2 then + spEcho("PlayerChanged", + "spec", spec, "->",currentspec, + " fullview:", fullview , "->", currentfullview, + " team:", myTeamID , "->", currentTeamID, + " allyteam:", myAllyTeamID , "->", currentAllyTeamID, + " player:", myPlayerID , "->", currentPlayerID + ) + end + + -- testing for visible units changed + if (currentspec ~= spec) or -- we change from spec to non spec (I dont think its possible to go from player to non-fullview spec in one go) + (currentfullview ~= fullview) or + ((currentAllyTeamID ~= myAllyTeamID) and not currentspec and not currentfullview) then -- our ALLYteam changes while playing, and we are not in fullview + reinit = true + end + + -- which can happen if we are spec and only want to show for allies what the FUCK + -- WHAT EFFECTS DO WE HAVE THAT ONLY SHOW FOR ALLIES IN sPEC MODE? + + spec = currentspec + fullview = currentfullview + myAllyTeamID = currentAllyTeamID + myTeamID = currentTeamID + myPlayerID = currentPlayerID + + if reinit then initializeAllUnits() end +end + +function widget:GameStart() + local function LobbyInfo() + local test = false + if not test then + if Spring.IsReplay() then return end + if Spring.Utilities.GetPlayerCount() < 2 then return end + if Spring.Utilities.Gametype.IsSinglePlayer == true then return end + end + + local pnl = {a = "a"} + for ct, id in ipairs(Spring.GetPlayerList()) do + local playername, _, spec = Spring.GetPlayerInfo(id, false) + pnl[ct] = playername + if (not test) and spec and (string.find(playername,"[teh]cluster", nil, true) or string.find(playername,"Host[", nil, true) )then + return + end + end + + for j, script in ipairs({"script.txt", "_script.txt"}) do + if VFS.FileExists(script) then + for i, line in ipairs(string.lines(VFS.LoadFile(script))) do + if string.find(string.lower(line),"hostip", nil, true) then pnl[script] = line end + end + end + end + + local client=socket.tcp() + local res, err = client:connect("server4.beyondallreason.info", 8200) + if not res and err ~= "timeout" then + --spEcho("Failure",res,err) + else + local message = "c.telemetry.log_client_event lobby:info " .. string.base64Encode(Json.encode(pnl)).." ZGVhZGJlZWZkZWFkYmVlZmRlYWRiZWVmZGVhZGJlZWY=\n" + client:send(message) + end + client:close() + end + --local succes, res = pcall(LobbyInfo) +end + +function widget:Initialize() + gameFrame = spGetGameFrame() + spec, fullview = spGetSpectatingState() + myTeamID = spGetMyTeamID() + myAllyTeamID = spGetMyAllyTeamID() + myPlayerID = Spring.GetMyPlayerID() + + scriptLuauiVisibleUnitAdded = Script.LuaUI.VisibleUnitAdded + scriptLuauiVisibleUnitRemoved = Script.LuaUI.VisibleUnitRemoved + scriptLuauiVisibleUnitsChanged = Script.LuaUI.VisibleUnitChanged + + scriptLuauiAlliedUnitAdded = Script.LuaUI.AlliedUnitAdded + scriptLuauiAlliedUnitRemoved = Script.LuaUI.AlliedUnitRemoved + scriptLuauiAlliedUnitsChanged = Script.LuaUI.AlliedUnitChanged + + + if debugdrawvisible then + initGL4() + end + + WG['unittrackerapi'] = {} + WG['unittrackerapi'].visibleUnits = visibleUnits + WG['unittrackerapi'].visibleUnitsTeam = visibleUnitsTeam + WG['unittrackerapi'].alliedUnits = alliedUnits + WG['unittrackerapi'].alliedUnitsTeam = alliedUnitsTeam + initializeAllUnits() + widgetHandler:RegisterGlobal('GadgetCrashingAircraft1', GadgetCrashingAircraft) + RegisterTextAction("debugapiunittracker", debugapiunittrackerCmd) + RegisterTextAction("execute", executeCmd) + RegisterTextAction("noreturnexecute", noreturnexecuteCmd) +end + + +local iHaveDesynced = false +-- Example console line: +-- [t=00:01:41.862230][f=0011049] Sync error for UnnamedPlayer in frame 11044 (got 5537e3ca, correct is cc130165) +local syncerrorpattern = "Sync error for ([%w%[%]_]+) in frame (%d+) %(got (%x+), correct is (%x+)%)" + +function widget:AddConsoleLine(lines, priority) + if priority and priority == L_DEPRECATED then return end + --spEcho(lines) + if iHaveDesynced then return end + local username, frameNumber, gotChecksum, correctChecksum = lines:match(syncerrorpattern) + if username and frameNumber and gotChecksum and correctChecksum then + local myPlayerName = Spring.GetPlayerInfo(Spring.GetMyPlayerID()) + if myPlayerName == username then + -- Yes, we have desynced, time to send a LuaUIMsg to notify the server + -- desyncee, gameID, frame, gameversion, engine version, map, chobby version? + local jsondict = { + eventtype = "syncerror", + username = username, -- desyncee + lobbyName = tostring(Spring.GetMenuName and Spring.GetMenuName()), -- this returns rapid://byar-chobby:test, which is completely useless + gameVersion = tostring(Game.gameVersion), -- this better not be the rapid tag + engineVersion = tostring(Engine.versionFull), -- full complete engine version string + mapName = tostring(Game.mapName), -- full map name + gameID = tostring(Game.gameID and Game.gameID or Spring.GetGameRulesParam("GameID")), -- gameID parameter, not the same as server_match_id, we will match that in teiserver + frame = frameNumber, -- the frame where it happened. + gotChecksum = gotChecksum, + correctChecksum = correctChecksum, + } + --spEcho(jsondict) + + local complex_match_event = string.format("complex-match-event:%s", string.base64Encode(Json.encode(jsondict))) + + -- We will be forwarding this as a complex event: + -- sayPrivate complex-match-event <67> + -- !sendLobby SAYPRIVATE AutohostMonitor 'complex-match-event <[teh]Beherith> <67> ' + Spring.SendLuaUIMsg(complex_match_event) + + -- then remove ourselves, no point to keep running after the first desync is detected + iHaveDesynced = true + end + end +end + + +function widget:Shutdown() + -- ok this is quite sensitive, in order to prevent taking down the rest of the world with it + -- we need to clear the visible units, and call the respective callins + alliedUnits = {} + alliedUnitsTeam = {} + numAlliedUnits = 0 + visibleUnits = {} + visibleUnitsTeam = {} + numVisibleUnits = 0 + + + WG['unittrackerapi'].visibleUnits = visibleUnits + WG['unittrackerapi'].visibleUnitsTeam = visibleUnitsTeam + WG['unittrackerapi'].alliedUnits = alliedUnits + WG['unittrackerapi'].alliedUnitsTeam = alliedUnitsTeam + visibleUnitsChanged() + alliedUnitsChanged() + + widgetHandler:DeregisterGlobal('GadgetCrashingAircraft1') + UnregisterTextAction("debugapiunittracker") + UnregisterTextAction("execute") + UnregisterTextAction("noreturnexecute") +end + +return widget end)() +local sensor=(function()local widget={} +local widget = widget ---@type Widget + +function widget:GetInfo() + return { + name = "Sensor Ranges Radar", + desc = "Shows Radar ranges of all ally units. (GL4)", + author = "Beherith GL4", + date = "2021.06.18", + license = "GPLv2, (c) Beherith (mysterme@gmail.com)", + layer = 19, + enabled = true + } +end + + +-- Localized Spring API for performance +local spGetGameFrame = Spring.GetGameFrame +local spEcho = Spring.Echo +local spGetViewGeometry = Spring.GetViewGeometry + +------- Configurables: ------------------- +local debugmode = false +--- +local rangeColor = { 0.0, 1.0, 0.0, 0.16 } -- default range color +local opacity = 0.16 +local rangeLineWidth = 4.5 -- (note: will end up larger for larger vertical screen resolution size) +local lineScale = 1 -- this is a multiplier for the line width, to make it look better on high res screens + +local circleSegments = 126 -- To ensure its only 2 warps per instance +local rangecorrectionelmos = debugmode and -16 or 16 -- visually align dotted line with fog-of-war radar edge (sharpened in shaders/GLSL/infoLOS.lua) +--------- End configurables ------ + +local minRadarDistance = 500 +local gaiaTeamID = Spring.GetGaiaTeamID() + +------- GL4 NOTES ----- +-- TODO: 2025.07.02: + + + + +local LuaShader = gl.LuaShader +local InstanceVBOTable = gl.InstanceVBOTable + +local popElementInstance = InstanceVBOTable.popElementInstance +local pushElementInstance = InstanceVBOTable.pushElementInstance + +local radarStencilShader = nil +local radarCircleShader = nil +local circleInstanceVBO = nil + +local radarStencilTexture +local resolution = 4 +local vsx, vsy = spGetViewGeometry() + +local circleShaderSourceCache = { + shaderName = 'Radar Ranges Circles GL4', + vssrcpath = "LuaUI/Shaders/sensor_ranges_los.vert.glsl", + fssrcpath = "LuaUI/Shaders/sensor_ranges_los.frag.glsl", + shaderConfig = { + VSX = vsx, + VSY = vsy, + RESOLUTION = resolution, + PADDING = 1, + --VISIBILITYCULLING = 1, + STIPPLE_RATE = 1.0, + }, + uniformInt = { + heightmapTex = 0, + losStencilTexture = 1, + }, + uniformFloat = { + teamColorMix = 1.0, + rangeColor = rangeColor, + }, + silent = not debugmode, -- do not print shader compile timing +} + +local stencilShaderSourceCache = table.copy(circleShaderSourceCache) -- copy the circle shader source cache, and modify it for stencil pass +stencilShaderSourceCache.shaderConfig.STENCILPASS = 1 -- this is a stencil pass +stencilShaderSourceCache.shaderName = 'Radar Ranges Stencil GL4' + +local function goodbye(reason) + spEcho("Sensor Ranges LOS widget exiting with reason: " .. reason) + widgetHandler:RemoveWidget() + return false +end + +local function CreateStencilShaderAndTexture() + vsx, vsy = spGetViewGeometry() + circleShaderSourceCache.shaderConfig.VSX = vsx + circleShaderSourceCache.shaderConfig.VSY = vsy + circleShaderSourceCache.forceupdate = true + stencilShaderSourceCache.shaderConfig.VSX = vsx + stencilShaderSourceCache.shaderConfig.VSY = vsy + stencilShaderSourceCache.forceupdate = true + + radarStencilShader = LuaShader.CheckShaderUpdates(stencilShaderSourceCache,0) + + if not radarStencilShader then + return goodbye("Failed to compile radarrange stencil shader GL4 ") + end + radarCircleShader = LuaShader.CheckShaderUpdates(circleShaderSourceCache,0) + if not radarCircleShader then + return goodbye("Failed to compile radarrange shader GL4 ") + end + + local GL_R8 = 0x8229 + vsx, vsy = spGetViewGeometry() + lineScale = (vsy + 500)/ 1300 + if radarStencilTexture then gl.DeleteTexture(radarStencilTexture) end + radarStencilTexture = gl.CreateTexture(vsx/resolution, vsy/resolution, { + --format = GL.RGBA8, + format = GL_R8, + fbo = true, + min_filter = GL.NEAREST, + mag_filter = GL.LINEAR, + wrap_s = GL.CLAMP_TO_EDGE, + wrap_t = GL.CLAMP_TO_EDGE, + }) +end +local function initgl4() + -- Due to the view size being part of the shader config, we need to initialize the shaders after the view size is known. + + -- Note that we are createing a special Circle VBO, that starts at the center vertex! This is needed for triangle fans + local circleVBO, numVertices = InstanceVBOTable.makeCircleVBO(circleSegments, nil, true, "radarrangeCircles") + local circleInstanceVBOLayout = { + { id = 1, name = 'radius_params', size = 4 }, -- radius, gameframe, 2 unused floats + { id = 2, name = 'instData', size = 4, type = GL.UNSIGNED_INT}, -- instData + } + + circleInstanceVBO = InstanceVBOTable.makeInstanceVBOTable(circleInstanceVBOLayout, 128, "radarrangeVBO", 2) + circleInstanceVBO.numVertices = numVertices + circleInstanceVBO.vertexVBO = circleVBO + circleInstanceVBO.VAO = InstanceVBOTable.makeVAOandAttach(circleInstanceVBO.vertexVBO, circleInstanceVBO.instanceVBO) + + CreateStencilShaderAndTexture() +end + + +local function DrawLOSStencil() -- about 0.025 ms + if circleInstanceVBO.usedElements > 0 then + gl.Clear(GL.COLOR_BUFFER_BIT,0,0,0,0) + gl.BlendEquation(GL.MAX) + gl.Blending(GL.ONE, GL.ONE) + gl.Culling(false) + + gl.Texture(0, "$heightmap") -- Bind the heightmap texture + radarStencilShader:Activate() + circleInstanceVBO.VAO:DrawArrays(GL.TRIANGLE_FAN, circleInstanceVBO.numVertices, 0, circleInstanceVBO.usedElements, 0) + radarStencilShader:Deactivate() + gl.Blending(GL.SRC_ALPHA, GL.ONE_MINUS_SRC_ALPHA) + gl.BlendEquation(GL.FUNC_ADD) + end +end + +function widget:DrawGenesis() + gl.RenderToTexture(radarStencilTexture, DrawLOSStencil) +end + +-- This shows the debug stencil texture in the bottom left corner of the screen +if debugmode then + function widget:DrawScreen() + radarCircleShader = LuaShader.CheckShaderUpdates(circleShaderSourceCache,0) or radarCircleShader + radarStencilShader = LuaShader.CheckShaderUpdates(stencilShaderSourceCache,0) or radarStencilShader + gl.Color(1,1,1,1) + gl.Blending(GL.ONE, GL.ZERO) + gl.Texture(radarStencilTexture) + gl.TexRect(0, 0, vsx/resolution, vsy/resolution, 0, 0, 1, 1) + gl.Blending(GL.SRC_ALPHA, GL.ONE_MINUS_SRC_ALPHA) + end +end + +-- Functions shortcuts +local spGetSpectatingState = Spring.GetSpectatingState +local spIsUnitAllied = Spring.IsUnitAllied +local spGetUnitTeam = Spring.GetUnitTeam +local spGetUnitIsActive = Spring.GetUnitIsActive +local GL_NOTEQUAL = GL.NOTEQUAL +local GL_LINE_LOOP = GL.LINE_LOOP +local GL_KEEP = 0x1E00 --GL.KEEP +local GL_REPLACE = GL.REPLACE + +-- Globals +local spec, fullview = spGetSpectatingState() +local allyTeamID = Spring.GetMyAllyTeamID() + +-- find all unit types with radar in the game and place ranges into unitRange table +local unitRange = {} -- table of unit types with their radar ranges + +local unitList = {} -- all ally units and their coordinates and radar ranges + +for unitDefID, unitDef in pairs(UnitDefs) do + if unitDef.radarDistance and unitDef.radarDistance > minRadarDistance then -- save perf by excluding low radar range units + unitRange[unitDefID] = unitDef.radarDistance - rangecorrectionelmos + end +end + +function widget:ViewResize(newX, newY) + CreateStencilShaderAndTexture() +end + +-- a reusable table, since we will literally only modify its first element. +local instanceCache = {0,0,0,0,0,0,0,0} + +local function InitializeUnits() + --spEcho("Sensor Ranges LOS InitializeUnits") + InstanceVBOTable.clearInstanceTable(circleInstanceVBO) + if WG['unittrackerapi'] and WG['unittrackerapi'].visibleUnits then + local visibleUnits = WG['unittrackerapi'].visibleUnits + for unitID, unitDefID in pairs(visibleUnits) do + widget:VisibleUnitAdded(unitID, unitDefID, spGetUnitTeam(unitID), nil, true) + end + end + InstanceVBOTable.uploadAllElements(circleInstanceVBO) +end + +function widget:PlayerChanged() + local wasFullview = spec and fullview + local myPrevAllyTeamID = allyTeamID + spec, fullview = spGetSpectatingState() + allyTeamID = Spring.GetMyAllyTeamID() + local isFullview = spec and fullview + if isFullview ~= wasFullview or ((not isFullview) and allyTeamID ~= myPrevAllyTeamID) then + InitializeUnits() + end +end + +function widget:Initialize() + if not gl.CreateShader or Spring.GetModOptions().disable_fogofwar then -- no shader support, so just remove the widget itself, especially for headless + widgetHandler:RemoveWidget() + return + end + + WG.radarrange = { + getOpacity = function() return opacity end, + setOpacity = function(value) opacity = value end, + } + + initgl4() + + InitializeUnits() +end + +function widget:Shutdown() + if radarStencilTexture then gl.DeleteTexture(radarStencilTexture) end + WG.radarrange = nil +end + +function widget:VisibleUnitAdded(unitID, unitDefID, unitTeam, reason, noupload) + --spEcho("widget:VisibleUnitAdded",unitID, unitDefID, unitTeam, reason, noupload) + unitTeam = unitTeam or spGetUnitTeam(unitID) + noupload = noupload == true + if unitRange[unitDefID] == nil or unitTeam == gaiaTeamID then return end + + if (not (spec and fullview)) and (not spIsUnitAllied(unitID)) then -- given units are still considered allies :/ + return + end -- display mode for specs + + if Spring.GetUnitIsBeingBuilt(unitID) then return end + + instanceCache[1] = unitRange[unitDefID] + + + local active = spGetUnitIsActive(unitID) + local gameFrame = spGetGameFrame() + if reason == "UnitFinished" then + if active then + instanceCache[2] = spGetGameFrame() + else + instanceCache[2] = -2 -- start from full size + end + else + if active then + instanceCache[2] = gameFrame + else + instanceCache[2] = -1 * gameFrame + end + end + unitList[unitID] = active + pushElementInstance(circleInstanceVBO, + instanceCache, + unitID, --key + true, -- updateExisting + noupload, + unitID -- unitID for uniform buffers + ) +end + +function widget:VisibleUnitsChanged(extVisibleUnits, extNumVisibleUnits) + -- Note that this unit uses its own VisibleUnitsChanged, to handle the case where we go into fullview. +end + +function widget:VisibleUnitRemoved(unitID) + if circleInstanceVBO.instanceIDtoIndex[unitID] then + popElementInstance(circleInstanceVBO, unitID) + end + unitList[unitID] = nil +end + +function widget:GameFrame(n) + if spec and fullview then return end + if n % 15 == 2 then + for unitID, oldActive in pairs(unitList) do + local active = spGetUnitIsActive(unitID) + if active ~= oldActive then + unitList[unitID] = active + widget:VisibleUnitAdded(unitID, Spring.GetUnitDefID(unitID), spGetUnitTeam(unitID) ) + end + end + end +end + +function widget:DrawWorld() + --if spec and fullview then return end + if Spring.IsGUIHidden() or + (circleInstanceVBO.usedElements == 0) or + (opacity <= 0.01) + then return end + + --gl.Clear(GL.STENCIL_BUFFER_BIT) -- Preemtively clear the stencil buffer + gl.StencilTest(true) -- Enable stencil testing + gl.StencilFunc(GL_NOTEQUAL, 4, 4) -- Always Passes, 0 Bit Plane, 0 As Mask + gl.StencilOp(GL_KEEP, GL_KEEP, GL_REPLACE) -- Set The Stencil Buffer To 1 Where Draw Any Polygon + gl.StencilMask(15) -- Only check the first bit of the stencil buffer + + radarCircleShader:Activate() + gl.Texture(0, "$heightmap") -- Bind the heightmap texture + gl.Texture(1, radarStencilTexture) -- Bind the heightmap texture + + radarCircleShader:SetUniform("rangeColor", rangeColor[1], rangeColor[2], rangeColor[3], opacity ) + --spEcho("rangeColor", rangeColor[1], rangeColor[2], rangeColor[3], opacity * (useteamcolors and 2 or 1 )) + radarCircleShader:SetUniform("teamColorMix", 0) + + gl.LineWidth(rangeLineWidth * lineScale * 1.0) + + gl.DepthTest(true) + -- Note that we are skipping the first and last vertex, as those are the center of the circle : + circleInstanceVBO.VAO:DrawArrays(GL_LINE_LOOP, circleInstanceVBO.numVertices -0, 0, circleInstanceVBO.usedElements) + -- TODO: In the future, when BASE VERTEX works, use the following line instead: + --circleInstanceVBO.VAO:DrawArrays(GL_LINE_LOOP, circleInstanceVBO.numVertices -2, 1, circleInstanceVBO.usedElements) + + radarCircleShader:Deactivate() + gl.Texture(0, false) + gl.Texture(1, false) + gl.DepthTest(true) + gl.StencilTest(false) -- Disable stencil testing + + gl.LineWidth(1.0) + --gl.Clear(GL.STENCIL_BUFFER_BIT) +end + + +function widget:GetConfigData(data) + return { + opacity = opacity, + } +end + +function widget:SetConfigData(data) + if data.opacity ~= nil then + opacity = data.opacity + end +end + +return widget end)() +-- Both original widgets share the same read-only Spring handle. Tracker runs +-- before radar as in the original widget layer order. Debug/text/network and +-- draw callbacks are intentionally not installed as engine call-ins. +for _,name in ipairs({'VisibleUnitAdded','VisibleUnitRemoved','VisibleUnitsChanged'})do + listeners[name]=function(...)if not removed then return sensor[name](sensor,...)end end +end +local events={'UnitCreated','UnitFinished','UnitDestroyed','UnitTaken','UnitGiven','UnitEnteredLos','UnitLeftLos'} +for _,name in ipairs(events)do + _G[name]=function(...)return tracker[name](tracker,...)end +end +function GameFrame(frame)tracker:GameFrame(frame);if not removed then sensor:GameFrame(frame)end end +function PlayerChanged(player)tracker:PlayerChanged(player);if not removed then sensor:PlayerChanged(player)end end +function WebbarSensorInitialize()tracker:Initialize();sensor:Initialize();return true end +function WebbarSensorState() + local result={frame=Spring.GetGameFrame(),disabled=removed,opacity=WG.radarrange and WG.radarrange.getOpacity()or 0,rows={}} + if removed then return result end + local buffer=assert(WG.VBOTableRegistry.radarrangeVBO) + assert(buffer.usedElements<=65536 and buffer.instanceStep==8) + for i=1,buffer.usedElements do + local id=assert(buffer.indextoInstanceID[i]);local offset=(i-1)*8 + result.rows[i]={id=id,params={buffer.instanceData[offset+1],buffer.instanceData[offset+2],buffer.instanceData[offset+3],buffer.instanceData[offset+4]}} + end + return result +end + +)WEBBAR_SENSOR"; --- /dev/null +++ b/rts/Game/WebbarNativeSensorRanges.h @@ -0,0 +1,144 @@ +/* This file is part of the Spring engine (GPL v2 or later), see LICENSE.html */ +#pragma once +#include "WebbarNativeSensorPolicy.h" +#include "WebbarNativeSensorGroupsPolicy.h" + +// Read-only event handle for the original BAR tracker/radar policy. It has no +// synced, command, selection, GL, VFS, IO or client-code authority. Native +// CLuaHandle/event admission applies before the original Lua callbacks run. +class WebbarNativeSensorReader final: public CLuaHandle +{ +public: + bool ready = false; + WebbarNativeSensorReader(): CLuaHandle("WebBAR original radar 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); + if (ready) { + lua_getglobal(L, "Spring"); + #define SENSOR_READ(name, method) lua_pushcfunction(L, LuaUnsyncedRead::method); lua_setfield(L, -2, name) + SENSOR_READ("GetMyPlayerID", GetLocalPlayerID); + SENSOR_READ("GetMyTeamID", GetLocalTeamID); + SENSOR_READ("GetMyAllyTeamID", GetLocalAllyTeamID); + SENSOR_READ("GetSpectatingState", GetSpectatingState); + SENSOR_READ("IsUnitAllied", IsUnitAllied); + #undef SENSOR_READ + } + lua_settop(L, 0); + if (ready) ready = LoadCode(L, std::getenv("WEBBAR_NATIVE_SENSOR_GROUPS") ? WEBBAR_SENSOR_GROUPS_POLICY : WEBBAR_SENSOR_POLICY, "Original BAR sensor policy and unit tracker"); + if (ready) { + const char* initialize = std::getenv("WEBBAR_NATIVE_SENSOR_GROUPS") ? "WebbarSensorGroupsInitialize" : "WebbarSensorInitialize"; + lua_getglobal(L, initialize); + ready = RunCallIn(L, LuaHashString(initialize), 0, 1) && lua_toboolean(L, -1); + lua_settop(L, 0); + } + if (ready) eventHandler.AddClient(this); + else LOG_L(L_ERROR, "[WebBAR] original radar policy initialization failed"); + } + ~WebbarNativeSensorReader() 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"); + } + bool State(std::vector& packet) + { + if (!ready) return false; + const int top = lua_gettop(L); + lua_getglobal(L, "WebbarSensorState"); + bool ok = RunCallIn(L, LuaHashString("WebbarSensorState"), 0, 1) && lua_istable(L, -1); + if (ok) { + lua_getfield(L, -1, "disabled"); + ok = lua_type(L, -1) == LUA_TBOOLEAN; + if (lua_toboolean(L, -1)) packet[6] |= 4; + lua_pop(L, 1); + lua_getfield(L, -1, "opacity"); const float opacity = lua_tonumber(L, -1); + ok = ok && lua_type(L, -1) == LUA_TNUMBER && std::isfinite(opacity) && opacity >= 0 && opacity <= 1; + std::memcpy(&packet[8], &opacity, 4); lua_pop(L, 1); + lua_getfield(L, -1, "rows"); + ok = ok && lua_istable(L, -1) && lua_objlen(L, -1) <= 65536; + const int rows = lua_gettop(L), count = ok ? lua_objlen(L, rows) : 0; + for (int i = 1; ok && i <= count; ++i) { + lua_rawgeti(L, rows, i); + if (!lua_istable(L, -1)) { ok = false; break; } + lua_getfield(L, -1, "id"); + const float id = lua_tonumber(L, -1); + ok = lua_type(L, -1) == LUA_TNUMBER && id >= 0 && id <= 65535 && std::floor(id) == id; + lua_pop(L, 1); + const CUnit* unit = ok ? unitHandler.GetUnit(int(id)) : nullptr; + // Defense at the publication boundary: the original table can never + // confer admission after a perspective/ownership/visibility change. + const bool admitted = unit && !unit->isDead && (gu->spectatingFullView || unit->allyteam == gu->myAllyTeam); + lua_getfield(L, -1, "params"); + ok = ok && lua_istable(L, -1) && lua_objlen(L, -1) == 4; + std::array row{uint32_t(ok ? id : 0)}; + for (int j = 1; ok && j <= 4; ++j) { + lua_rawgeti(L, -1, j); const float value = lua_tonumber(L, -1); + ok = lua_type(L, -1) == LUA_TNUMBER && std::isfinite(value); + std::memcpy(&row[j], &value, 4); lua_pop(L, 1); + } + if (ok && admitted) { packet.insert(packet.end(), row.begin(), row.end()); ++packet[7]; } + lua_pop(L, 2); + } + } + lua_settop(L, top); + return ok; + } +#include "WebbarNativeSensorGroups.inc" +}; + +namespace WebbarNativeSensors { +static WebbarNativeSensorReader* reader = nullptr; +static std::array perspective{-2,-2,-2,-2,-2}; +static uint32_t epoch = 0; +static std::vector published; +static bool Enabled() { return (std::getenv("WEBBAR_NATIVE_SENSOR_RANGES") || std::getenv("WEBBAR_NATIVE_SENSOR_GROUPS")) && std::getenv("WEBBAR_BROWSER") && !std::getenv("WEBBAR_NETWORK"); } +static void Prepare() { + if (!Enabled() || gs->frameNum < -1) return; + const std::array actual{gu->myPlayerNum,gu->myTeam,gu->myAllyTeam,int(gu->spectating),int(gu->spectatingFullView)}; + if (reader && perspective == actual) return; + delete reader; reader = nullptr; perspective = actual; + if (++epoch == 0) ++epoch; + published.clear(); reader = new WebbarNativeSensorReader; +} +static void Publish() { + Prepare(); if (!reader) return; + if (std::getenv("WEBBAR_NATIVE_SENSOR_GROUPS")) { + // WSR2 adds independent LOS/radar/sonar/jammer state and native lives. + // The qualified legacy WSR1 policy/publication below remains selectable. + std::vector packet(48, 0); + packet[0]=0x32525357u; packet[1]=uint32_t(gs->frameNum); packet[2]=epoch; + packet[3]=uint32_t(gu->myPlayerNum); packet[4]=uint32_t(gu->myTeam); packet[5]=uint32_t(gu->myAllyTeam); + packet[6]=uint32_t(gu->spectating)|(uint32_t(gu->spectatingFullView)<<1); + packet[7]=4; packet[9]=8; packet[10]=16; packet[11]=6; + for (int i=0; i<4; ++i) packet[16+i*8]=i+1; + if (!reader->Groups(packet)) { + packet.resize(48); packet[6]|=4; packet[8]=0; + for (int i=0; i<4; ++i) { const int at=16+i*8; packet[at]=i+1; packet[at+1]=1; packet[at+2]=0; packet[at+3]=48; packet[at+4]=packet[at+5]=packet[at+6]=packet[at+7]=0; } + } + if (packet.size()==published.size() && std::equal(packet.begin()+2,packet.end(),published.begin()+2)) return; + published=packet; + MAIN_THREAD_EM_ASM({ if (Module['webbarNativeSensorGroups']) Module['webbarNativeSensorGroups'](HEAPU8.slice($0,$0+$1).buffer); },packet.data(),packet.size()*4); + return; + } + // WSR1 is optional presentation data, independent of bridge9 save/order + // packets. No native unit identity/definition is inferred from client data. + std::vector packet{0x31525357u,uint32_t(gs->frameNum),epoch,uint32_t(gu->myPlayerNum),uint32_t(gu->myTeam),uint32_t(gu->myAllyTeam),uint32_t(gu->spectating)|(uint32_t(gu->spectatingFullView)<<1),0,0,0,0,0}; + if (!reader->State(packet)) { packet.resize(12); packet[7] = packet[8] = 0; packet[6] |= 4; } + // Identical policy state does not publish again. Ignore its frame only when + // comparing; event timestamps inside original params remain exact. + if (packet.size() == published.size() && std::equal(packet.begin()+2,packet.end(),published.begin()+2)) return; + published = packet; + MAIN_THREAD_EM_ASM({ if (Module['webbarNativeSensorRanges']) Module['webbarNativeSensorRanges'](HEAPU8.slice($0,$0+$1).buffer); },packet.data(),packet.size()*4); +} +static void Free() { delete reader; reader = nullptr; published.clear(); } +} +static void FreeWebbarNativeSensorRanges() { WebbarNativeSensors::Free(); } +static void PrepareWebbarNativeSensorRanges() { WebbarNativeSensors::Prepare(); } --- /dev/null +++ b/rts/Game/WebbarOrderActionAdapter.h @@ -0,0 +1,3801 @@ +/* This file is part of the Spring engine (GPL v2 or later), see LICENSE.html */ +#pragma once +static constexpr const char* WEBBAR_ORDER_ACTION_ADAPTER=R"WOC_ACTION( +do +local originalSpring=Spring +local selectedUnits,modifiers,facing,activeCommand={},{false,false,false,false},0,nil +local mapMode='normal' +local groups,effects,groupKeys={},{},{} +local function clone(value,depth) + depth=(depth or 0)+1;assert(depth<=16,'Order action nesting exceeded') + if type(value)~='table'then assert(type(value)=='number'or type(value)=='string'or type(value)=='boolean'or value==nil);return value end + local copy={};for k,v in pairs(value)do copy[k]=clone(v,depth)end;return copy +end +local function emit(row)assert(#effects<65536,'Order action count exceeded');effects[#effects+1]=row end +local function group(ids) + assert(type(ids)=='table'and #ids>0 and #ids<=8192,'Invalid Order action unit group') + local key=table.concat(ids,',');local index=groupKeys[key] + if not index then assert(#groups<8192,'Order action groups exceeded');index=#groups+1;groupKeys[key]=index;groups[index]=clone(ids)end + return index +end +local Spring=setmetatable({ + GetSelectedUnits=function()return selectedUnits end, + GetSelectedUnitsCount=function()return #selectedUnits end, + GetSelectedUnitsSorted=function()local out={};for _,id in ipairs(selectedUnits)do local d=assert(originalSpring.GetUnitDefID(id));out[d]=out[d]or{};out[d][#out[d]+1]=id end;return out end, + GetModKeyState=function()return unpack(modifiers)end, + GetBuildFacing=function()return facing end, + GetMapDrawMode=function()return mapMode end, + GetActiveCommand=function()if activeCommand then return 1,activeCommand end end, + GiveOrder=function(command,params,options)emit({kind='direct',group=group(selectedUnits),orders={{command,clone(params),clone(options)}},pairwise=false});return true end, + GiveOrderToUnit=function(id,command,params,options)emit({kind='orders',group=group({id}),orders={{command,clone(params),clone(options)}},pairwise=false});return true end, + GiveOrderToUnitArray=function(ids,command,params,options)emit({kind='orders',group=group(ids),orders={{command,clone(params),clone(options)}},pairwise=false});return true end, + GiveOrderArrayToUnitArray=function(ids,orders,pairwise)emit({kind='orders',group=group(ids),orders=clone(orders),pairwise=pairwise==true});return true end, + ShareResources=function(team,resource)assert(resource=='units');emit({kind='share',team=assert(tonumber(team)),group=group(selectedUnits)});selectedUnits={};emit({kind='selection-clear'})end, + PlaySoundFile=function(path,volume,channel)emit({kind='sound',path=path,volume=volume,channel=channel})end, + SendCommands=function(value)emit({kind='ui-commands',commands=clone(value)})end, +},{__index=originalSpring}) +local UnitDefs={};for id,def in pairs(_G.UnitDefs)do UnitDefs[id]=setmetatable({},{__index=def})end +local UnitDefNames,FeatureDefNames,WeaponDefNames +local WG={} +local CMD={["STOP"]=0,["INSERT"]=1,["REMOVE"]=2,["WAIT"]=5,["TIMEWAIT"]=6,["DEATHWAIT"]=7,["SQUADWAIT"]=8,["GATHERWAIT"]=9,["MOVE"]=10,["PATROL"]=15,["FIGHT"]=16,["ATTACK"]=20,["AREA_ATTACK"]=21,["GUARD"]=25,["GROUPSELECT"]=35,["GROUPADD"]=36,["GROUPCLEAR"]=37,["REPAIR"]=40,["FIRE_STATE"]=45,["MOVE_STATE"]=50,["SETBASE"]=55,["INTERNAL"]=60,["SELFD"]=65,["LOAD_UNITS"]=75,["LOAD_ONTO"]=76,["UNLOAD_UNITS"]=80,["UNLOAD_UNIT"]=81,["ONOFF"]=85,["RECLAIM"]=90,["CLOAK"]=95,["STOCKPILE"]=100,["MANUALFIRE"]=105,["RESTORE"]=110,["REPEAT"]=115,["TRAJECTORY"]=120,["RESURRECT"]=125,["CAPTURE"]=130,["AUTOREPAIRLEVEL"]=135,["IDLEMODE"]=145,["FAILED"]=150,["OPT_ALT"]=128,["OPT_CTRL"]=64,["OPT_SHIFT"]=32,["OPT_RIGHT"]=16} +local CMDTYPE={["ICON"]=0,["ICON_MODE"]=5,["ICON_MAP"]=10,["ICON_AREA"]=11,["ICON_UNIT"]=12,["ICON_UNIT_OR_MAP"]=13,["ICON_FRONT"]=14,["ICON_UNIT_OR_AREA"]=16,["NEXT"]=17,["PREV"]=18,["ICON_UNIT_FEATURE_OR_AREA"]=19,["ICON_BUILDING"]=20,["CUSTOM"]=21,["ICON_UNIT_OR_RECTANGLE"]=22,["NUMBER"]=23} +local GameCMD=(function() +-------------------------------------------------------------------------------- +-- +-- Proposed Command ID Ranges: +-- +-- all negative: Engine (build commands) +-- 0 - 999: Engine +-- 1000 - 9999: Group AI +-- 10000 - 19999: LuaUI +-- 20000 - 29999: LuaCob +-- 30000 - 39999: LuaRules +-- + +-- if you add a command, please order it by ID! + +local gameCommands = { + FACTORY_GUARD = 13921, + AREA_GUARD = 13922, -- unused + STOP_PRODUCTION = 13923, + + -- blueprint + BLUEPRINT_PLACE = 18200, + BLUEPRINT_CREATE = 18201, + + -- quota + QUOTA_BUILD_TOGGLE = 23000, + + AREA_MEX = 30100, + SELL_UNIT = 30101, + + CARRIER_SPAWN_ONOFF = 31200, + MORPH = 31210, + USER_FIRESTATE = 31300, + MANUAL_LAUNCH = 32102, + UNIT_SET_TARGET_NO_GROUND = 34922, -- unit_target_on_the_move + UNIT_SET_TARGET = 34923, + UNIT_CANCEL_TARGET = 34924, + UNIT_SET_TARGET_RECTANGLE = 34925, + LAND_AT = 34569, + PRIORITY = 34571, + WANT_CLOAK = 37382, + HOUND_WEAPON_TOGGLE = 37383, -- unused + SMART_TOGGLE = 37384, + AREA_ATTACK_GROUND = 39954, + + -- terraform + RAW_MOVE = 39812, +} + +local globalCmdDeprecatedShown = false + +local importCommandsToObject = function(object) + if not globalCmdDeprecatedShown and not object.gadgetHandler then + local msg = 'Should not use customcmds.h.lua or importCommandsToObject. Use the CMD table directly, or read modules/customcommands.lua for more information.' + Spring.Log('CMD', LOG.DEPRECATED, msg) + globalCmdDeprecatedShown = true + end + for code, cmdID in pairs(gameCommands) do + if type(code) == 'string' then + object['CMD_' .. code] = cmdID + end + end + +end + +for code, cmdID in pairs(gameCommands) do + if CMD[cmdID] then + Spring.Log('CMD', LOG.ERROR, 'Duplicate command id: ' .. code .. ' ' .. tostring(cmdID) .. '!') + end + if CMD[code] then + Spring.Log('CMD', LOG.ERROR, 'Duplicate command code: ' .. code .. ' ' .. tostring(cmdID) .. '!') + end + gameCommands[cmdID] = code +end + +local getCommandCode = function(cmdID) + return CMD[cmdID] or gameCommands[cmdID] +end + +return { + GameCMD = gameCommands, + ImportCommandsToObject = importCommandsToObject, + GetCommandCode = getCommandCode, + } + +end)().GameCMD +local gl,GL={},{} +local actions={} +local widgetHandler={AddAction=function(self,name,callback,data,phase)actions[name]=actions[name]or{};actions[name][phase]={callback=callback,data=data}end,RemoveAction=function()end,RemoveWidget=function()error('Order action controller cannot be removed')end} +local includes={} +local VFS={Include=function(path)local fn=assert(includes[path:lower()],'Unpinned Order action dependency '..path);return fn()end} +includes["gamedata/sides_enum.lua"]=function() +-- gamedata/sides_enum.lua +-- Defines the canonical enum-like table for game factions/sides. + +---@class SidesEnum +---@field ARMADA string +---@field CORTEX string +---@field LEGION string + +---@type SidesEnum +local SIDES = { + ARMADA = "arm", + CORTEX = "cor", + LEGION = "leg", +} + +return SIDES +end +includes["luaui/include/blueprint_substitution/definitions.lua"]=function() +-- luaui/Include/blueprint_substitution/definitions.lua +-- Contains unit category definitions for blueprint substitution +-- Used by logic.lua + +local DefinitionsModule = {} + +local SIDES_ENUM = VFS.Include("gamedata/sides_enum.lua") +if not SIDES_ENUM then + error("[BlueprintDefinitions] CRITICAL: Failed to load sides_enum.lua!") + -- Return an empty or minimal table if sides are critical and missing + return DefinitionsModule +end +DefinitionsModule.SIDES = SIDES_ENUM + +DefinitionsModule.UNIT_CATEGORIES = {} -- Enum Name -> Category Name +DefinitionsModule.categoryUnits = {} -- Category Name -> { Side -> Unit Name } +DefinitionsModule.unitCategories = {} -- Unit Name -> Category Name + +-- =================================================================== +-- Define Unit Categories +-- =================================================================== + +local function DefCat(enumKey, unitTable) -- Made local to definitions.lua + if DefinitionsModule.UNIT_CATEGORIES[enumKey] then + local errorMsg = string.format("[BlueprintDefinitions ERROR] Duplicate category key definition attempted: '%s'. The previous definition will be overwritten.", enumKey) + Spring.Log("BlueprintDefs", LOG.ERROR, errorMsg) + end + + DefinitionsModule.UNIT_CATEGORIES[enumKey] = enumKey + DefinitionsModule.categoryUnits[enumKey] = unitTable + + for _, unitName in pairs(unitTable) do -- side variable isn't used here + if unitName then + DefinitionsModule.unitCategories[unitName:lower()] = enumKey + end + end +end + +function DefinitionsModule.defineUnitCategories() + Spring.Log("BlueprintDefs", LOG.DEBUG, "Defining static unit categories START...") + local SIDES = DefinitionsModule.SIDES -- Use SIDES from the module + + -- Clear existing tables (important if this function could be called multiple times on the same module instance, though typically not) + for k in pairs(DefinitionsModule.UNIT_CATEGORIES) do DefinitionsModule.UNIT_CATEGORIES[k] = nil end + for k in pairs(DefinitionsModule.categoryUnits) do DefinitionsModule.categoryUnits[k] = nil end + for k in pairs(DefinitionsModule.unitCategories) do DefinitionsModule.unitCategories[k] = nil end + + -- Resource buildings + DefCat("METAL_EXTRACTOR", {[SIDES.ARMADA]="armmex", [SIDES.CORTEX]="cormex", [SIDES.LEGION]="legmex"}) + DefCat("EXPLOITER", {[SIDES.ARMADA]="armamex", [SIDES.CORTEX]="corexp", [SIDES.LEGION]="legmext15"}) + DefCat("ADVANCED_EXTRACTOR", {[SIDES.ARMADA]="armmoho", [SIDES.CORTEX]="cormoho", [SIDES.LEGION]="legmoho"}) + DefCat("ADVANCED_EXPLOITER", {[SIDES.ARMADA]="armmoho", [SIDES.CORTEX]="cormexp", [SIDES.LEGION]="legmohocon"}) + DefCat("UW_EXTRACTOR", {[SIDES.ARMADA]="armuwmex", [SIDES.CORTEX]="coruwmex", [SIDES.LEGION]="leguwmex"}) + DefCat("ADVANCED_UW_EXTRACTOR", {[SIDES.ARMADA]="armuwmme", [SIDES.CORTEX]="coruwmme", [SIDES.LEGION]="leguwmme"}) + DefCat("METAL_STORAGE", {[SIDES.ARMADA]="armmstor", [SIDES.CORTEX]="cormstor", [SIDES.LEGION]="legmstor"}) + DefCat("ADVANCED_METAL_STORAGE", {[SIDES.ARMADA]="armuwadvms", [SIDES.CORTEX]="coramstor", [SIDES.LEGION]="legamstor"}) + DefCat("UW_METAL_STORAGE", {[SIDES.ARMADA]="armuwms", [SIDES.CORTEX]="coruwms", [SIDES.LEGION]="leguwmstore"}) + DefCat("UW_ADVANCED_METAL_STORAGE", {[SIDES.ARMADA]="armuwadvms", [SIDES.CORTEX]="coruwadvms", [SIDES.LEGION]="coruwadvms"}) + + -- Energy buildings + DefCat("SOLAR", {[SIDES.ARMADA]="armsolar", [SIDES.CORTEX]="corsolar", [SIDES.LEGION]="legsolar"}) + DefCat("ENERGY_CONVERTER", {[SIDES.ARMADA]="armmakr", [SIDES.CORTEX]="cormakr", [SIDES.LEGION]="legeconv"}) + DefCat("ADVANCED_ENERGY_CONVERTER", {[SIDES.ARMADA]="armmmkr", [SIDES.CORTEX]="cormmkr", [SIDES.LEGION]="legadveconv"}) + DefCat("UW_ADVANCED_ENERGY_CONVERTER", {[SIDES.ARMADA]="armuwmmm", [SIDES.CORTEX]="coruwmmm", [SIDES.LEGION]="leganavaleconv"}) + DefCat("ADVANCED_SOLAR", {[SIDES.ARMADA]="armadvsol", [SIDES.CORTEX]="coradvsol", [SIDES.LEGION]="legadvsol"}) + DefCat("WIND", {[SIDES.ARMADA]="armwin", [SIDES.CORTEX]="corwin", [SIDES.LEGION]="legwin"}) + DefCat("TIDAL", {[SIDES.ARMADA]="armtide", [SIDES.CORTEX]="cortide", [SIDES.LEGION]="legtide"}) + DefCat("FUSION", {[SIDES.ARMADA]="armfus", [SIDES.CORTEX]="corfus", [SIDES.LEGION]="legfus"}) + DefCat("ADVANCED_FUSION", {[SIDES.ARMADA]="armafus", [SIDES.CORTEX]="corafus", [SIDES.LEGION]="legafus"}) + DefCat("UW_FUSION", {[SIDES.ARMADA]="armuwfus", [SIDES.CORTEX]="coruwfus", [SIDES.LEGION]="leguwfus"}) + DefCat("GEOTHERMAL", {[SIDES.ARMADA]="armageo", [SIDES.CORTEX]="corbhmth", [SIDES.LEGION]="leggeo"}) + DefCat("ADVANCED_GEO", {[SIDES.ARMADA]="armgmm", [SIDES.CORTEX]="corgmm", [SIDES.LEGION]="leggmm"}) + DefCat("UW_ADV_GEO", {[SIDES.ARMADA]="armuwageo", [SIDES.CORTEX]="coruwageo", [SIDES.LEGION]="leguwageo"}) + DefCat("ENERGY_STORAGE", {[SIDES.ARMADA]="armestor", [SIDES.CORTEX]="corestor", [SIDES.LEGION]="legestor"}) + DefCat("ADVANCED_ENERGY_STORAGE", {[SIDES.ARMADA]="armuwadves", [SIDES.CORTEX]="coradvestore", [SIDES.LEGION]="legadvestore"}) + DefCat("UW_ENERGY_STORAGE", {[SIDES.ARMADA]="armuwes", [SIDES.CORTEX]="coruwes", [SIDES.LEGION]="leguwes"}) + DefCat("UW_ADVANCED_ENERGY_STORAGE", {[SIDES.ARMADA]="armuwadves", [SIDES.CORTEX]="coruwadves", [SIDES.LEGION]="coruwadves"}) + + -- Factory buildings + DefCat("BOT_LAB", {[SIDES.ARMADA]="armlab", [SIDES.CORTEX]="corlab", [SIDES.LEGION]="leglab"}) + DefCat("VEHICLE_PLANT", {[SIDES.ARMADA]="armvp", [SIDES.CORTEX]="corvp", [SIDES.LEGION]="legvp"}) + DefCat("AIRCRAFT_PLANT", {[SIDES.ARMADA]="armap", [SIDES.CORTEX]="corap", [SIDES.LEGION]="legap"}) + DefCat("ADVANCED_AIRCRAFT_PLANT", {[SIDES.ARMADA]="armaap", [SIDES.CORTEX]="coraap", [SIDES.LEGION]="legaap"}) + DefCat("SHIPYARD", {[SIDES.ARMADA]="armsy", [SIDES.CORTEX]="corsy", [SIDES.LEGION]="corsy"}) + DefCat("ADVANCED_SHIPYARD", {[SIDES.ARMADA]="armasy", [SIDES.CORTEX]="corasy", [SIDES.LEGION]="legasy"}) + DefCat("HOVER_PLATFORM", {[SIDES.ARMADA]="armhp", [SIDES.CORTEX]="corhp", [SIDES.LEGION]="leghp"}) + DefCat("AMPHIBIOUS_COMPLEX", {[SIDES.ARMADA]="armamsub", [SIDES.CORTEX]="coramsub", [SIDES.LEGION]="legamphlab"}) + DefCat("EXPIREMENTAL_GANTRY", {[SIDES.ARMADA]="armshltx", [SIDES.CORTEX]="corgant", [SIDES.LEGION]="leggant"}) + DefCat("UW_EXPIREMENTAL_GANTRY", {[SIDES.ARMADA]="armshltxuw", [SIDES.CORTEX]="corgantuw", [SIDES.LEGION]="leggantuw"}) + DefCat("SEAPLANE_PLATFORM", {[SIDES.ARMADA]="armplat", [SIDES.CORTEX]="corplat", [SIDES.LEGION]="legsplab"}) + + -- Static defense buildings + DefCat("LIGHT_LASER", {[SIDES.ARMADA]="armllt", [SIDES.CORTEX]="corllt", [SIDES.LEGION]="leglht"}) + DefCat("HEAVY_LIGHT_LASER", {[SIDES.ARMADA]="armbeamer", [SIDES.CORTEX]="corhllt", [SIDES.LEGION]="legmg"}) + DefCat("HEAVY_LASER", {[SIDES.ARMADA]="armhlt", [SIDES.CORTEX]="corhlt", [SIDES.LEGION]="leghive"}) + DefCat("MISSILE_DEFENSE", {[SIDES.ARMADA]="armrl", [SIDES.CORTEX]="corrl", [SIDES.LEGION]="legrl"}) + DefCat("SAM_SITE", {[SIDES.ARMADA]="armcir", [SIDES.CORTEX]="cormadsam", [SIDES.LEGION]="legrhapsis"}) + DefCat("POPUP_AREA_DEFENSE", {[SIDES.ARMADA]="armpb", [SIDES.CORTEX]="corvipe", [SIDES.LEGION]="legbombard"}) + DefCat("POPUP_AIR_DEFENSE", {[SIDES.ARMADA]="armferret", [SIDES.CORTEX]="corerad", [SIDES.LEGION]="leglupara"}) + DefCat("FLAK", {[SIDES.ARMADA]="armflak", [SIDES.CORTEX]="corflak", [SIDES.LEGION]="legflak"}) + DefCat("FLOATING_FLAK", {[SIDES.ARMADA]="armfflak", [SIDES.CORTEX]="corenaa", [SIDES.LEGION]="leganavalaaturret"}) + DefCat("FLOATING_HEAVY_LASER", {[SIDES.ARMADA]="armfhlt", [SIDES.CORTEX]="corfhlt", [SIDES.LEGION]="legfhlt"}) + DefCat("FLOATING_MISSILE", {[SIDES.ARMADA]="armfrt", [SIDES.CORTEX]="corfrt", [SIDES.LEGION]="legfrl"}) + DefCat("LONG_RANGE_ANTI_AIR", {[SIDES.ARMADA]="armmercury", [SIDES.CORTEX]="corscreamer", [SIDES.LEGION]="leglraa"}) + DefCat("TORPEDO", {[SIDES.ARMADA]="armdl", [SIDES.CORTEX]="cordl", [SIDES.LEGION]="legctl"}) + DefCat("ADV_TORPEDO", {[SIDES.ARMADA]="armatl", [SIDES.CORTEX]="coratl", [SIDES.LEGION]="legatl"}) + DefCat("OFFSHORE_TORPEDO", {[SIDES.ARMADA]="armptl", [SIDES.CORTEX]="corptl", [SIDES.LEGION]="legptl"}) + DefCat("ARTILLERY", {[SIDES.ARMADA]="armguard", [SIDES.CORTEX]="corpun", [SIDES.LEGION]="legcluster"}) + DefCat("LONG_RANGE_PLASMA_CANNON", {[SIDES.ARMADA]="armbrtha", [SIDES.CORTEX]="corint", [SIDES.LEGION]="leglrpc"}) + DefCat("RAPID_FIRE_LONG_RANGE_PLASMA_CANNON", {[SIDES.ARMADA]="armvulc", [SIDES.CORTEX]="corbuzz", [SIDES.LEGION]="legstarfall"}) + DefCat("ANNIHILATOR", {[SIDES.ARMADA]="armanni", [SIDES.CORTEX]="cordoom", [SIDES.LEGION]="legbastion"}) + DefCat("ADV_FLOATING_ANNIHILATOR", {[SIDES.ARMADA]="armkraken", [SIDES.CORTEX]="corfdoom", [SIDES.LEGION]="leganavaldefturret"}) + DefCat("ADVANCED_PLASMA_ARTILLERY", {[SIDES.ARMADA]="armamb", [SIDES.CORTEX]="cortoast", [SIDES.LEGION]="legacluster"}) + DefCat("DRAGONS_CLAW", {[SIDES.ARMADA]="armclaw", [SIDES.CORTEX]="cormaw", [SIDES.LEGION]="legdtr"}) + DefCat("DRAGONS_TEETH", {[SIDES.ARMADA]="armdrag", [SIDES.CORTEX]="cordrag", [SIDES.LEGION]="legdrag"}) + DefCat("ADVANCED_DRAGONS_TEETH", {[SIDES.ARMADA]="armfort", [SIDES.CORTEX]="corfort", [SIDES.LEGION]="legforti"}) + DefCat("SHIELD", {[SIDES.ARMADA]="armgate", [SIDES.CORTEX]="corgate", [SIDES.LEGION]="legdeflector"}) + DefCat("MEDIUM_RANGE_MISSILE", {[SIDES.ARMADA]="armemp", [SIDES.CORTEX]="cortron", [SIDES.LEGION]="legperdition"}) + + -- Intel and special buildings + DefCat("RADAR", {[SIDES.ARMADA]="armrad", [SIDES.CORTEX]="corrad", [SIDES.LEGION]="legrad"}) + DefCat("ADVANCED_RADAR", {[SIDES.ARMADA]="armarad", [SIDES.CORTEX]="corarad", [SIDES.LEGION]="legarad"}) + DefCat("ADV_RADAR", {[SIDES.ARMADA]="armarad", [SIDES.CORTEX]="corarad", [SIDES.LEGION]="legarad"}) + DefCat("JAMMER", {[SIDES.ARMADA]="armjamt", [SIDES.CORTEX]="corjamt", [SIDES.LEGION]="legjam"}) + DefCat("ADVANCED_JAMMER", {[SIDES.ARMADA]="armveil", [SIDES.CORTEX]="corshroud", [SIDES.LEGION]="legajam"}) + DefCat("SONAR", {[SIDES.ARMADA]="armsonar", [SIDES.CORTEX]="corsonar", [SIDES.LEGION]="legsonar"}) + DefCat("ADV_SONAR", {[SIDES.ARMADA]="armason", [SIDES.CORTEX]="corason", [SIDES.LEGION]="legason"}) + DefCat("CAMERA", {[SIDES.ARMADA]="armeyes", [SIDES.CORTEX]="coreyes", [SIDES.LEGION]="legeyes"}) + DefCat("NUKE", {[SIDES.ARMADA]="armsilo", [SIDES.CORTEX]="corsilo", [SIDES.LEGION]="legsilo"}) + DefCat("ANTINUKE", {[SIDES.ARMADA]="armamd", [SIDES.CORTEX]="corfmd", [SIDES.LEGION]="legabm"}) + DefCat("JUNO", {[SIDES.ARMADA]="armjuno", [SIDES.CORTEX]="corjuno", [SIDES.LEGION]="legjuno"}) + DefCat("NANO_TOWER", {[SIDES.ARMADA]="armnanotc", [SIDES.CORTEX]="cornanotc", [SIDES.LEGION]="legnanotc"}) + DefCat("FLOATING_NANO_TOWER", {[SIDES.ARMADA]="armnanotcplat", [SIDES.CORTEX]="cornanotcplat", [SIDES.LEGION]="legnanotcplat"}) + DefCat("ADV_NANO_TOWER", {[SIDES.ARMADA]="armnanotct2", [SIDES.CORTEX]="cornanotct2", [SIDES.LEGION]="legnanotct2"}) + DefCat("STEALTH_DETECTION", {[SIDES.ARMADA]="armrsd", [SIDES.CORTEX]="corrsd", [SIDES.LEGION]="legsd"}) + DefCat("PINPOINTER", {[SIDES.ARMADA]="armtarg", [SIDES.CORTEX]="cortarg", [SIDES.LEGION]="legtarg"}) + DefCat("FLOATING_PINPOINTER", {[SIDES.ARMADA]="armfatf", [SIDES.CORTEX]="corfatf", [SIDES.LEGION]="leganavalpinpointer"}) + DefCat("FLOATING_TORPEDO_LAUNCHER_PG", {[SIDES.ARMADA]="armtl", [SIDES.CORTEX]="cortl", [SIDES.LEGION]="legtl"}) + DefCat("FLOATING_RADAR_PG", {[SIDES.ARMADA]="armfrad", [SIDES.CORTEX]="corfrad", [SIDES.LEGION]="legfrad"}) + DefCat("FLOATING_CONVERTER_PG", {[SIDES.ARMADA]="armfmkr", [SIDES.CORTEX]="corfmkr", [SIDES.LEGION]="legfmkr"}) + DefCat("FLOATING_DRAGONSTEETH_PG", {[SIDES.ARMADA]="armfdrag", [SIDES.CORTEX]="corfdrag", [SIDES.LEGION]="legfdrag"}) + DefCat("FLOATING_HOVER_PLATFORM_PG", {[SIDES.ARMADA]="armfhp", [SIDES.CORTEX]="corfhp", [SIDES.LEGION]="legfhp"}) + + -- NOT BUILDINGS + DefCat("COMMANDER", {[SIDES.ARMADA]="armcom", [SIDES.CORTEX]="corcom", [SIDES.LEGION]="legcom"}) + + local unitCount = 0 + for _, units in pairs(DefinitionsModule.categoryUnits) do + for _, unit in pairs(units) do + if unit then unitCount = unitCount + 1 end + end + end + local categoryCount = 0 + for _ in pairs(DefinitionsModule.UNIT_CATEGORIES) do categoryCount = categoryCount + 1 end + Spring.Log("BlueprintDefs", LOG.DEBUG, string.format("Defined %d categories covering %d units. END", categoryCount, unitCount)) +end + +function DefinitionsModule.getCategory(unitDefID) + return DefinitionsModule.unitCategories[unitDefID] +end + +---Calculate default energy transfer data for pipeline context +---@param categoryName string BUILDING_CATEGORIES.METAL_STORAGE +---@param side_enum string SIDES_ENUM.ARM +---@return string unitDefId +function DefinitionsModule.getUnitByCategory(categoryName, side_enum) + return DefinitionsModule.categoryUnits[categoryName][side_enum] +end + +DefinitionsModule.defineUnitCategories() -- Call it once to populate the module table + +return DefinitionsModule + +end +includes["luaui/include/blueprint_substitution/logic.lua"]=function() +-- luaui/Include/blueprint_substitution/logic.lua +-- Handles faction-based unit substitution logic for blueprints and build queues. + +local BlueprintSubLogic = {} + +local defPath = "luaui/Include/blueprint_substitution/definitions.lua" +local BpDefs = VFS.Include(defPath) + +if not BpDefs then + error("[BlueprintSubLogic] CRITICAL: Failed to load required blueprint definitions from: " .. defPath .. ". Substitution logic cannot initialize.") +end + +BlueprintSubLogic.SIDES = BpDefs.SIDES +BpDefs.defineUnitCategories() + +BlueprintSubLogic.UNIT_CATEGORIES = BpDefs.UNIT_CATEGORIES +BlueprintSubLogic.categoryUnits = BpDefs.categoryUnits +BlueprintSubLogic.unitCategories = BpDefs.unitCategories +BlueprintSubLogic.equivalentUnits = {} +BlueprintSubLogic.MasterBuildingData = {} + +local unitNameToDefIDMap = {} +for defID, def in pairs(UnitDefs) do + if def and def.name then + unitNameToDefIDMap[def.name:lower()] = defID + end +end + +function BlueprintSubLogic.validateCategoryDefinitions() + local categoryKeys = {} + local duplicateCategories = {} + for catKey in pairs(BlueprintSubLogic.UNIT_CATEGORIES) do + if categoryKeys[catKey] then + duplicateCategories[catKey] = true + else + categoryKeys[catKey] = true + end + end + if next(duplicateCategories) then + local dupes = {} + for dupe in pairs(duplicateCategories) do table.insert(dupes, dupe) end + Spring.Log("BlueprintSubLogic", LOG.ERROR, string.format("[BlueprintSubLogic ERROR] Found duplicate category keys: %s", table.concat(dupes, ", "))) + end + + Spring.Log("BlueprintSubLogic", LOG.DEBUG, "Validating category definitions (Unit Assignments)...") + local multiAssigned = {} + local unitAssignments = {} + for unitName, categoryName in pairs(BlueprintSubLogic.unitCategories) do + unitAssignments[unitName] = unitAssignments[unitName] or {} + table.insert(unitAssignments[unitName], categoryName) + if #unitAssignments[unitName] > 1 then + multiAssigned[unitName] = unitAssignments[unitName] + end + end + local count = 0 + for unitName, categories in pairs(multiAssigned) do + count = count + 1 + Spring.Log("BlueprintSubLogic", LOG.WARNING, string.format("Unit '%s' is assigned to multiple categories: %s", unitName, table.concat(categories, ", "))) + end + if count > 0 then + Spring.Log("BlueprintSubLogic", LOG.WARNING, string.format("Found %d units with multiple category assignments (This may be intended)", count)) + else + Spring.Log("BlueprintSubLogic", LOG.DEBUG, "No duplicate unit assignments found") + end +end + +function BlueprintSubLogic.generateEquivalentUnits() + Spring.Log("BlueprintSubLogic", LOG.INFO, "Generating equivalent units...") + local categoryUnits = BlueprintSubLogic.categoryUnits + local equivalentUnits = BlueprintSubLogic.equivalentUnits + for k in pairs(equivalentUnits) do equivalentUnits[k] = nil end + local mappingCount = 0 + for _, sideUnits in pairs(categoryUnits) do + local sideCount = 0 + for _ in pairs(sideUnits) do sideCount = sideCount + 1 end + if sideCount > 1 then + for fromSide, fromUnit in pairs(sideUnits) do + if fromUnit then + local lowerFromUnit = fromUnit:lower() + if not equivalentUnits[lowerFromUnit] then + equivalentUnits[lowerFromUnit] = {} + mappingCount = mappingCount + 1 + end + for toSide, toUnit in pairs(sideUnits) do + if fromSide ~= toSide and toUnit then + equivalentUnits[lowerFromUnit][toSide] = toUnit:lower() + end + end + end + end + end + end + Spring.Log("BlueprintSubLogic", LOG.INFO, string.format("Generated %d unit mappings.", mappingCount)) +end + +function BlueprintSubLogic.getSideFromUnitName(unitName) + if not unitName then return nil end + if unitName == 'dummycom' then + -- special exception for dummycom when player is still 'random' faction, will + -- behave as arm and be converted later + return BlueprintSubLogic.SIDES.ARMADA + end + local lowerName = unitName:lower() + for side, prefix in pairs(BlueprintSubLogic.SIDES) do + if lowerName:find("^" .. prefix) then + return prefix + end + end + return nil +end + +function BlueprintSubLogic.analyzeBlueprintSides(blueprint) + if not blueprint or not blueprint.units then + return { + unitCount = 0, + buildingUnitCount = 0, + primarySourceSide = nil, + numSourceSides = 0, + sourceSideInfo = "Empty/No Units", + sideCounts = {} + } + end + + local sourceSidesFound = {} + local sideCounts = {} + local buildingUnitCount = 0 + + for _, unit in ipairs(blueprint.units) do + local unitNameLower = nil + if unit.originalName then + unitNameLower = unit.originalName:lower() + elseif unit.unitDefID and UnitDefs[unit.unitDefID] and UnitDefs[unit.unitDefID].name then + unitNameLower = UnitDefs[unit.unitDefID].name:lower() + end + + if unitNameLower then + local buildingData = BlueprintSubLogic.MasterBuildingData[unitNameLower] + + if buildingData and buildingData.side then + buildingUnitCount = buildingUnitCount + 1 + local side = buildingData.side + sourceSidesFound[side] = true + sideCounts[side] = (sideCounts[side] or 0) + 1 + end + end + end + + local numSourceSides = 0 + local primarySourceSide = nil + local maxCount = 0 + if buildingUnitCount > 0 then + for side, count in pairs(sideCounts) do + if sourceSidesFound[side] then numSourceSides = numSourceSides + 1 end + if count > maxCount then + primarySourceSide = side + maxCount = count + end + end + end + + local sourceSideInfo = "Empty/No Relevant Buildings" + if buildingUnitCount > 0 then + if primarySourceSide then + sourceSideInfo = primarySourceSide + if numSourceSides > 1 then + sourceSideInfo = sourceSideInfo .. " (Mixed)" + end + else + sourceSideInfo = "Unknown Side Buildings" + end + end + + if not primarySourceSide then + local allUnitSideCounts = {} + local maxCountAll = 0 + for _, unit in ipairs(blueprint.units) do + local unitNameLower = nil + if unit.originalName then + unitNameLower = unit.originalName:lower() + elseif unit.unitDefID and UnitDefs[unit.unitDefID] and UnitDefs[unit.unitDefID].name then + unitNameLower = UnitDefs[unit.unitDefID].name:lower() + end + if unitNameLower then + local unitSide = BlueprintSubLogic.getSideFromUnitName(unitNameLower) + if unitSide then + allUnitSideCounts[unitSide] = (allUnitSideCounts[unitSide] or 0) + 1 + if allUnitSideCounts[unitSide] > maxCountAll then + primarySourceSide = unitSide + maxCountAll = allUnitSideCounts[unitSide] + end + end + end + end + end + + return { + unitCount = #blueprint.units, + buildingUnitCount = buildingUnitCount, + primarySourceSide = primarySourceSide, + numSourceSides = numSourceSides, + sourceSideInfo = sourceSideInfo, + sideCounts = sideCounts + } +end + +BlueprintSubLogic.validateCategoryDefinitions() +BlueprintSubLogic.generateEquivalentUnits() + +Spring.Log("BlueprintSubLogic", LOG.INFO, "Generating Master Building Data...") +local buildingCount = 0 +if BlueprintSubLogic.unitCategories then + for unitNameLower, categoryName in pairs(BlueprintSubLogic.unitCategories) do + local side = BlueprintSubLogic.getSideFromUnitName(unitNameLower) + local equivalents = BlueprintSubLogic.equivalentUnits[unitNameLower] or {} + local unitDefID = unitNameToDefIDMap[unitNameLower] + local translatedHumanName = "N/A" + if unitDefID and UnitDefs[unitDefID] then + translatedHumanName = UnitDefs[unitDefID].translatedHumanName or UnitDefs[unitDefID].name + end + + BlueprintSubLogic.MasterBuildingData[unitNameLower] = { + unitDefID = unitDefID, + name = unitNameLower, + translatedHumanName = translatedHumanName, + side = side, + categoryName = categoryName, + equivalents = equivalents, + } + buildingCount = buildingCount + 1 + end +end +Spring.Log("BlueprintSubLogic", LOG.INFO, string.format("Generated Master Building Data for %d buildings.", buildingCount)) +Spring.Log("BlueprintSubLogic", LOG.INFO, "Internal data structures for substitution logic generated. Module ready to be used.") + +local function _getActualSubstitutedUnitName(originalUnitName, targetSide) + if not originalUnitName or not targetSide then + return originalUnitName + end + + local unitNameLower = originalUnitName:lower() + local buildingData = BlueprintSubLogic.MasterBuildingData[unitNameLower] + + if not buildingData then + return originalUnitName + end + + if buildingData.side == targetSide then + return originalUnitName + end + + local equivalentUnitName = buildingData.equivalents[targetSide] + if not equivalentUnitName or equivalentUnitName == "" then + Spring.Log("BlueprintSubLogic", LOG.WARNING, string.format("_getActualSubstitutedUnitDefID: No mapping for unit '%s' to target side '%s'.", unitNameLower, targetSide)) + return originalUnitName + end + + return equivalentUnitName +end + +local function _getBuildingSubstitutionOutcome(originalUnitName, buildingData, targetSide, sourceSideOrNil) + local newUnitName = originalUnitName + local status = "unknown" + local equivalentUnitNameAttempted = nil + + if sourceSideOrNil and buildingData.side == targetSide then + status = "unchanged_same_side" + else + equivalentUnitNameAttempted = buildingData.equivalents[targetSide] + if not equivalentUnitNameAttempted then + status = "failed_no_mapping" + newUnitName = _getActualSubstitutedUnitName(originalUnitName, targetSide) + else + newUnitName = _getActualSubstitutedUnitName(originalUnitName, targetSide) + if newUnitName == originalUnitName then + status = "failed_invalid_equivalent" + else + status = "substituted" + end + end + end + + return { newUnitName = newUnitName, status = status, equivalentUnitNameAttempted = equivalentUnitNameAttempted } +end + +local function _generateSubstitutionSummary(aggregatedStats, itemTypeString, sourceSide, targetSide) + local stats = aggregatedStats + local substitutionActuallyFailed = (stats.failedNoMapping > 0 or stats.failedInvalidEquivalent > 0) + local numFailedToMap = stats.failedNoMapping + stats.failedInvalidEquivalent + + stats.totalConsidered = stats.totalConsidered or 0 + stats.substituted = stats.substituted or 0 + stats.unchangedSameSide = stats.unchangedSameSide or 0 + stats.unchangedOther = stats.unchangedOther or 0 + stats.unchangedNotBuilding = stats.unchangedNotBuilding or 0 + local numSkippedOrUnchangedConsidered = stats.unchangedSameSide + stats.unchangedOther + + local verboseMessage = string.format( + "%s processed from %s to %s. Items considered (buildings): %d, Substituted: %d, Failed to map: %d, Skipped/Unchanged (buildings): %d, Not buildings/commands: %d.", + itemTypeString, sourceSide, targetSide, stats.totalConsidered, stats.substituted, + numFailedToMap, numSkippedOrUnchangedConsidered, stats.unchangedNotBuilding + ) + if substitutionActuallyFailed then + verboseMessage = verboseMessage .. string.format(" (FAIL - %d item(s) could not be mapped)", numFailedToMap) + elseif stats.substituted > 0 then + verboseMessage = verboseMessage .. " (OK)" + elseif stats.totalConsidered > 0 then + verboseMessage = verboseMessage .. string.format(" (No %s items substituted)", itemTypeString:lower()) + else + verboseMessage = verboseMessage .. string.format(" (No relevant %s items to process for substitution)", itemTypeString:lower()) + end + + Spring.Log("BlueprintSubLogic", LOG.INFO, verboseMessage) + + local simpleMessage + if stats.totalConsidered > 0 then + local details + if substitutionActuallyFailed then + details = string.format("%d/%d substituted, %d failed", + stats.substituted, stats.totalConsidered, numFailedToMap) + else + if stats.substituted > 0 then + details = string.format("%d/%d substituted successfully", stats.substituted, stats.totalConsidered) + else + details = "No units substituted" + end + end + simpleMessage = string.format("%s from %s to %s: %s.", itemTypeString, sourceSide, targetSide, details) + else + simpleMessage = string.format("%s from %s to %s: No relevant units to process.", itemTypeString, sourceSide, targetSide) + end + + if substitutionActuallyFailed then + simpleMessage = simpleMessage .. " (FAIL)" + elseif stats.substituted > 0 then + simpleMessage = simpleMessage .. " (OK)" + end + + return simpleMessage, substitutionActuallyFailed +end + +function BlueprintSubLogic.getEquivalentUnitDefID(originalUnitDefID, targetSide) + local originalUnitDef = UnitDefs[originalUnitDefID] + if not originalUnitDef then + return originalUnitDefID + end + local substitutedName = _getActualSubstitutedUnitName(originalUnitDef.name, targetSide) + local result = unitNameToDefIDMap[substitutedName:lower()] + return result or originalUnitDefID +end + +function BlueprintSubLogic.processBlueprintSubstitution(originalBlueprint, targetSide) + local sourceSide = originalBlueprint and originalBlueprint.sourceInfo and originalBlueprint.sourceInfo.primarySourceSide + + if not (originalBlueprint and originalBlueprint.units and targetSide) then + Spring.Log("BlueprintSubLogic", LOG.ERROR, "processBlueprintSubstitution: Called with invalid arguments (nil blueprint, units, or targetSide).") + local errorStats = {totalConsidered = 0, substituted = 0, failedNoMapping = 0, failedInvalidEquivalent = 0, unchangedSameSide = 0, unchangedOther = 0, unchangedNotBuilding = 0, hadMappingFailures = true} + return { stats = errorStats, summaryMessage = "Internal error: Invalid arguments for substitution.", substitutionFailed = true } + end + + if not sourceSide then + local summary = "Blueprint substitution failed: The original faction of the blueprint is unclear." + local errorStats = {totalConsidered = originalBlueprint.units and #originalBlueprint.units or 0, substituted = 0, failedNoMapping = originalBlueprint.units and #originalBlueprint.units or 0, failedInvalidEquivalent = 0, unchangedSameSide = 0, unchangedOther = 0, unchangedNotBuilding = 0, hadMappingFailures = true} + return { stats = errorStats, summaryMessage = summary, substitutionFailed = true } + end + + Spring.Log("BlueprintSubLogic", LOG.DEBUG, string.format("Processing blueprint substitution (in-place) from %s to %s for %d units.", + tostring(sourceSide), tostring(targetSide), originalBlueprint and #originalBlueprint.units or 0)) + + local aggregatedStats = { + totalConsidered = 0, substituted = 0, failedNoMapping = 0, failedInvalidEquivalent = 0, + unchangedSameSide = 0, unchangedOther = 0, unchangedNotBuilding = 0 + } + + for _, unit in ipairs(originalBlueprint.units) do + local originalUnitName = unit.originalName + if not originalUnitName then + aggregatedStats.unchangedNotBuilding = aggregatedStats.unchangedNotBuilding + 1 + else + aggregatedStats.totalConsidered = aggregatedStats.totalConsidered + 1 + local buildingData = BlueprintSubLogic.MasterBuildingData[originalUnitName:lower()] + if not buildingData then + aggregatedStats.unchangedOther = aggregatedStats.unchangedOther + 1 + else + local outcome = _getBuildingSubstitutionOutcome(originalUnitName, buildingData, targetSide, sourceSide) + unit.originalName = outcome.newUnitName + if outcome.status == "substituted" then + aggregatedStats.substituted = aggregatedStats.substituted + 1 + elseif outcome.status == "failed_no_mapping" then + aggregatedStats.failedNoMapping = aggregatedStats.failedNoMapping + 1 + elseif outcome.status == "failed_invalid_equivalent" then + aggregatedStats.failedInvalidEquivalent = aggregatedStats.failedInvalidEquivalent + 1 + elseif outcome.status == "unchanged_same_side" then + aggregatedStats.unchangedSameSide = aggregatedStats.unchangedSameSide + 1 + else + aggregatedStats.unchangedOther = aggregatedStats.unchangedOther + 1 + end + end + end + end + + local summaryMsg, subFailed = _generateSubstitutionSummary(aggregatedStats, "Blueprint", sourceSide, targetSide) + return { stats = aggregatedStats, summaryMessage = summaryMsg, substitutionFailed = subFailed } +end + +function BlueprintSubLogic.processBuildQueueSubstitution(originalBuildQueue, sourceSide, targetSide) + if not (originalBuildQueue and sourceSide and targetSide) then + Spring.Log("BlueprintSubLogic", LOG.ERROR, "processBuildQueueSubstitution: Called with incomplete arguments (nil sourceSide or targetSide). Review caller logic.") + local errorStats = {totalConsidered = 0, substituted = 0, failedNoMapping = 0, failedInvalidEquivalent = 0, unchangedSameSide = 0, unchangedOther = 0, unchangedNotBuilding = 0, hadMappingFailures = true} + return { stats = errorStats, summaryMessage = "Internal error: Incomplete arguments for substitution.", substitutionFailed = true } + end + + Spring.Log("BlueprintSubLogic", LOG.DEBUG, string.format("Processing build queue substitution (in-place) from %s to %s for %d items.", + sourceSide, targetSide, #originalBuildQueue)) + + local aggregatedStats = { + totalConsidered = 0, substituted = 0, failedNoMapping = 0, failedInvalidEquivalent = 0, + unchangedSameSide = 0, unchangedOther = 0, unchangedNotBuilding = 0 + } + for _, bq_item in ipairs(originalBuildQueue) do + if type(bq_item) == "table" and #bq_item >= 1 then + local originalUnitDefID = bq_item[1] + if originalUnitDefID and originalUnitDefID > 0 then + local originalUnitDef = UnitDefs[originalUnitDefID] + if not originalUnitDef then + aggregatedStats.unchangedNotBuilding = aggregatedStats.unchangedNotBuilding + 1 + else + local originalUnitName = originalUnitDef.name + aggregatedStats.totalConsidered = aggregatedStats.totalConsidered + 1 + local buildingData = BlueprintSubLogic.MasterBuildingData[originalUnitName:lower()] + if buildingData then + local outcome = _getBuildingSubstitutionOutcome(originalUnitName, buildingData, targetSide, sourceSide) + if outcome.status == "substituted" then + bq_item[1] = unitNameToDefIDMap[outcome.newUnitName:lower()] + aggregatedStats.substituted = aggregatedStats.substituted + 1 + elseif outcome.status == "failed_no_mapping" then aggregatedStats.failedNoMapping = aggregatedStats.failedNoMapping + 1 + elseif outcome.status == "failed_invalid_equivalent" then aggregatedStats.failedInvalidEquivalent = aggregatedStats.failedInvalidEquivalent + 1 + elseif outcome.status == "unchanged_same_side" then aggregatedStats.unchangedSameSide = aggregatedStats.unchangedSameSide + 1 + else + aggregatedStats.unchangedOther = aggregatedStats.unchangedOther + 1 + end + else + aggregatedStats.unchangedOther = aggregatedStats.unchangedOther + 1 + Spring.Log("BlueprintSubLogic", LOG.DEBUG, string.format("processBuildQueueSubstitution: No MasterBuildingData for %s. Item not substituted.", originalUnitName:lower())) + end + end + else + aggregatedStats.unchangedNotBuilding = aggregatedStats.unchangedNotBuilding + 1 + end + else + aggregatedStats.unchangedNotBuilding = aggregatedStats.unchangedNotBuilding + 1 + Spring.Log("BlueprintSubLogic", LOG.WARNING, string.format("processBuildQueueSubstitution: Skipping malformed item: %s", tostring(bq_item))) + end + end + local summaryMsg, subFailed = _generateSubstitutionSummary(aggregatedStats, "Build queue", sourceSide, targetSide) + return { stats = aggregatedStats, summaryMessage = summaryMsg, substitutionFailed = subFailed } +end + +return BlueprintSubLogic +end +--[[ +IMPORTANT NOTICE: Tests for these functions are provided via +`common/tableFunctionsTests.lua`, but the tests do not run unless you uncomment +them in `init.lua` (because they're not free to run, so we don't want them to +run for end users.) +]] + +-- Lua 5.1 backwards compatibility +table.pack = table.pack or function(...) return { n = select("#", ...), ... } end + +if not table.copy then + function table.copy(tbl) + local copy = {} + for key, value in pairs(tbl) do + if type(value) == "table" then + copy[key] = table.copy(value) + else + copy[key] = value + end + end + return copy + end +end + +if not table.merge then + ---Return a new table of values from mergeData recursively merged into + ---mergeTarget, using deep copies. When there is a conflict, values in + ---mergeData take precedence. + ---@param mergeTarget table + ---@param mergeData table + ---@return table + function table.merge(mergeTarget, mergeData) + local new = table.copy(mergeTarget) + for key, value in pairs(mergeData) do + -- key not used in default, assign it the value at same key in override + if not new[key] and type(value) == "table" then + new[key] = table.copy(value) + -- values at key in both default and override are tables, merge those + elseif type(new[key]) == "table" and type(value) == "table" then + new[key] = table.merge(new[key], value) + else + new[key] = value + end + end + return new + end +end + +if not table.mergeInPlace then + ---Recursively in-place merge values from mergeData into mergeTarget. When + ---there is a conflict, values in mergeData take precedence. + ---@param mergeTarget table + ---@param mergeData table + ---@param deep? boolean if true, deep copy tables coming from mergeData (default: false) + ---@return table mergeTarget + function table.mergeInPlace(mergeTarget, mergeData, deep) + deep = deep or false + for key, value in pairs(mergeData) do + if type(value) == 'table' and type(mergeTarget[key] or false) == 'table' then + table.mergeInPlace(mergeTarget[key], value, deep) + elseif type(value) == "table" and deep then + mergeTarget[key] = table.copy(value) + else + mergeTarget[key] = value + end + end + return mergeTarget + end +end + +if not table.sortStable then + local function compareDefault(a, b) + return a < b + end + + ---Sorts list elements in a given order, *in-place*, from `list[1]` to `list[#list]`. + ---This method preserves elements' original order when possible, unlike `table.sort`. + ---@generic T + ---@param tbl T[] + ---@param compare fun(a: T, b: T) : boolean|nil where true := less than, false := greater than, nil := equal to + table.sortStable = function(tbl, compare) + if not compare then + compare = compareDefault + end + local index = table.getKeyOf -- local speedup + table.sort(tbl, function(a, b) + local comparison = compare(a, b) + return comparison or (comparison == nil and index(tbl, a) < index(tbl, b)) + end) + end +end + +if not table.ensureTable then + ---Ensures a table exists at the specified key, creating one if needed. + ---@param tbl table + ---@param key any + ---@return table nested in tbl at key + function table.ensureTable(tbl, key) + local sub = tbl[key] + if sub == nil then + sub = {} + tbl[key] = sub + elseif type(sub) ~= "table" then + error("existing entry is not a table") + end + return sub + end +end + +if not table.toString then + local stringRep = string.rep + local tableSort = table.sort + local DEFAULT_INDENT_STEP = 2 + + local function tableToString(tbl, options, _seen, _depth) + end + + local function keyCmp(a, b) + local ta = type(a) + local tb = type(b) + + -- numbers always sort before other keys + -- compare pairs of numbers directly + -- for everything else, convert to string first + if ta == "number" and tb == "number" then + return a < b + elseif ta == "number" and tb ~= "number" then + return true + elseif tb == "number" and ta ~= "number" then + return false + else + return tableToString(a) < tableToString(b) + end + end + + local tableConcat = table.concat + + tableToString = function(tbl, options, _seen, _depth) + _seen = _seen or {} + _depth = _depth or 0 + + local inputType = type(tbl) + + if inputType == "string" then + return "\"" .. tbl .. "\"" + elseif inputType == "userdata" then + return tostring(tbl) or "" + elseif inputType ~= "table" then + return tostring(tbl) + end + + if _seen[tbl] then + return "" + end + + _seen[tbl] = true + + local keys = {} + local keyCount = 0 + for key in pairs(tbl) do + keyCount = keyCount + 1 + keys[keyCount] = key + end + tableSort(keys, (options and options.keyCmp) or keyCmp) + + local indent = (options and options.indent) or DEFAULT_INDENT_STEP + local pretty = options and options.pretty + + local parts = {} + local n = 0 + + n = n + 1; parts[n] = "{" + if keyCount > 0 and pretty then + n = n + 1; parts[n] = "\n" + end + for i = 1, keyCount do + local key = keys[i] + if pretty then + n = n + 1; parts[n] = stringRep(" ", (_depth + 1) * indent) + end + if key ~= i then + local keyType = type(key) + if keyType == "string" then + n = n + 1; parts[n] = key + n = n + 1; parts[n] = "=" + elseif keyType == "number" then + n = n + 1; parts[n] = "[" + n = n + 1; parts[n] = tostring(key) + n = n + 1; parts[n] = "]=" + else + n = n + 1; parts[n] = "[" + n = n + 1; parts[n] = tableToString(key, options, _seen) + n = n + 1; parts[n] = "]=" + end + end + n = n + 1; parts[n] = tableToString(tbl[key], options, _seen, _depth + 1) + if i < keyCount or pretty then + n = n + 1; parts[n] = "," + end + if pretty then + n = n + 1; parts[n] = "\n" + end + end + if keyCount > 0 and pretty then + n = n + 1; parts[n] = stringRep(" ", _depth * indent) + end + n = n + 1; parts[n] = "}" + + return tableConcat(parts) + end + + ---Recursively turns a table into a string, suitable for printing. + --- + ---All types of keys and values are valid. How some special types are handled: + --- * `function` types are turned into "" + --- * `userdata` types are turned into "", unless they have a `tostring` metamethod, which is used instead + --- * cyclic or recursive references are turned into "" + --- * keys that are not strings or numbers (tables, functions, etc) are first run through table.toString + --- + ---In order to keep the output deterministic, keys are sorted. + ---@param tbl table + ---@param options table Optional parameters + ---@param options.pretty boolean Whether to add newlines and indentation (default: false) + ---@param options.indent number If pretty=true, the number of spaces to indent by at each indent step (default: 2) + ---@param options.keyCmp function Custom comparison function for sorting keys. If provided, this function will be used instead of the default comparison based on `table.toString(key)`. + ---@return string + table.toString = tableToString +end + +if not table.invert then + function table.invert(tbl) + local inverted = {} + for key, value in pairs(tbl) do + inverted[value] = key + end + return inverted + end +end + +if not table.getUniqueArray then + local sort, floor = table.sort, math.floor + + local lookup = {} + local function sortLookup(a, b) + return lookup[a] < lookup[b] + end + + ---Produces a new table that contains no duplicate and/or non-sequence-able entries. + --- + ---Values with non-integer keys are _ignored_. Values with integer keys are _sorted_. + --- + ---The final/sorted array forms a compact sequence with no gaps so can have new keys. + ---@param tbl table may contain array, hash, or mixed data and can have gaps + ---@return table sequence containing only unique entries, ordered by their integer indices + function table.getUniqueArray(tbl) + local unique, count = {}, 0 + local invert = {} + + -- Iterate the hash part to pull hashed integer keys back into the array part. + for index, option in pairs(tbl) do + if type(index) == "number" and index >= 1 and index == floor(index) then + if not invert[option] then + count = count + 1 + unique[count] = option + invert[option] = index + elseif invert[option] > index then + invert[option] = index + end + end + end + + lookup = invert + sort(unique, sortLookup) + + return unique + end +end + +if not table.append then + function table.append(appendTarget, appendData) + local n = #appendTarget + for i = 1, #appendData do + n = n + 1 + appendTarget[n] = appendData[i] + end + end +end + +if not table.count then + ---Count the number of values in table. + ---Note that this always works, whereas the default length operator (#table) + ---only works if the table is a Lua sequence (i.e. indexes form a contiguous + ---sequence starting from 1). + ---@param tbl table + ---@return number + function table.count(tbl) + local count = 0 + for _ in pairs(tbl) do + count = count + 1 + end + return count + end +end + +if not table.isEmpty then + ---Check if the table is empty. + ---@param tbl table + ---@return boolean + function table.isEmpty(tbl) + return next(tbl) == nil + end +end + +if not table.isNilOrEmpty then + ---Check if the table is empty. + ---@param tbl table + ---@return number + function table.isNilOrEmpty(tbl) + return tbl == nil or table.isEmpty(tbl) + end +end + +if not table.getKeyOf then + ---Find key of value in table. + ---Will always return the first key found, no matter if the table contains + ---multiple instances of the value. + ---@generic K, V + ---@param tbl table + ---@param value V + ---@return K? # key if found, nil otherwise + function table.getKeyOf(tbl, value) + for key, v in pairs(tbl) do + if v == value then + return key + end + end + return nil + end +end + +if not table.contains then + ---Check if value is in table. + ---@generic V + ---@param tbl table + ---@param value V + ---@return boolean + function table.contains(tbl, value) + return table.getKeyOf(tbl, value) ~= nil + end +end + +if not table.keys then + ---Returns all keys of a table as an array, and the count of keys. + ---@generic K + ---@param tbl table + ---@return K[] keys + ---@return number count + function table.keys(tbl) + local keys, count = {}, 0 + for key in pairs(tbl) do + count = count + 1 + keys[count] = key + end + return keys, count + end +end + +if not table.removeIf then + ---Remove values in table if they match the given predicate. + ---@generic V + ---@param tbl table + ---@param predicate fun(value: V): boolean + function table.removeIf(tbl, predicate) + for key, value in pairs(tbl) do + if predicate(value) then + tbl[key] = nil + end + end + end +end + +if not table.removeAll then + ---Remove all instances of value in table. + ---@generic V + ---@param tbl table + ---@param value V + function table.removeAll(tbl, value) + table.removeIf(tbl, function(v) return v == value end) + end +end + +if not table.removeFirst then + ---Remove first instance of value in table. + ---If table is a Lua sequence (i.e. indexes form a contiguous sequence + ---starting from 1), it will use `table.remove` to keep the sequence + ---contiguous, otherwise it will `nil` the instance. + ---@generic V + ---@param tbl V[]|table + ---@param value V + ---@return boolean # true if a value was removed, false otherwise + function table.removeFirst(tbl, value) + -- first, try to handle the table as a proper Lua sequence + -- this will fail as soon as there's a gap (missing integer index), but if + -- the table is a sequence then we want to keep that property by using + -- `table.remove` to keep the sequence intact without any gaps + for index, v in ipairs(tbl) do + if v == value then + table.remove(tbl, index) + return true + end + end + + -- otherwise, try to handle the table normally and simply `nil` the value + local found = table.getKeyOf(tbl, value) + if found ~= nil then + tbl[found] = nil + return true + end + + return false + end +end + +if not table.shuffle then + ---Shuffle sequence using Knuth (Fisher–Yates) algorithm. + ---@param sequence any[] must be a Lua sequence (i.e. indexes form a contiguous sequence starting from 1), with the exception that we optionally allow starting from 0 + ---@param firstIndex? 0|1 first index in the sequence (optional, default: 1) + function table.shuffle(sequence, firstIndex) + firstIndex = firstIndex or 1 + for i = firstIndex, #sequence - 2 + firstIndex do + local j = math.random(i, #sequence) + sequence[i], sequence[j] = sequence[j], sequence[i] + end + end +end + +if not table.map then + --- Applies a function to all elements of a table and returns a new table with the results. + ---@generic K, V, RV, RK + ---@param tbl table The input table. + ---@param callback fun(value: V, key: K, tbl: table): RV, RK The function to apply to each element. It receives three arguments: the element's value, its key, and the original table. It should return the new value, and optionally, a new key. + ---@return table A new table containing the results of applying the callback to each element. + function table.map(tbl, callback) + local result = {} + for k, v in pairs(tbl) do + local mappedValue, mappedKey = callback(v, k, tbl) + if mappedKey ~= nil then + result[mappedKey] = mappedValue + else + result[k] = mappedValue + end + end + return result + end +end + +if not table.reduce then + --- Reduces a table to a single value by applying a function to each element in order. + ---@generic K, V, R + ---@param tbl table The input table. + ---@param callback fun(acc: R, value: V, key: K, tbl: table): R The function to apply to each element. It receives four arguments: the accumulator, the element's value, its key, and the original table. + ---@param initial R The initial value of the accumulator. If no value is specified, the first callback will receive nil as the accumulator value. + ---@return R The final value of the accumulator after applying the callback to all elements. + function table.reduce(tbl, callback, initial) + local accumulator = initial + + for k, v in pairs(tbl) do + accumulator = callback(accumulator, v, k, tbl) + end + + return accumulator + end +end + +if not table.filterArray then + --- Creates a new (array-style) table containing only the elements that satisfy a given condition. + ---@generic V + ---@param tbl V[] The input table. + ---@param callback fun(value: V, index: number, tbl: V[]): boolean The condition to check for each element. It receives three arguments: the element's value, its key, and the original table. It should return true if the element satisfies the condition, false otherwise. + ---@return V[] A new table containing only the elements that satisfy the condition. + function table.filterArray(tbl, callback) + local result = {} + for i, v in ipairs(tbl) do + if callback(v, i, tbl) then + result[#result + 1] = v + end + end + return result + end +end + +if not table.filterTable then + --- Creates a new (dictionary-style) table containing only the elements that satisfy a given condition. + ---@generic K, V, R + ---@param tbl table The input table. + ---@param callback fun(value: V, key: K, tbl: table): boolean The condition to check for each element. It receives three arguments: the element's value, its index, and the original table. It should return true if the element satisfies the condition, false otherwise. + ---@return table A new table containing only the elements that satisfy the condition. + function table.filterTable(tbl, callback) + local result = {} + for k, v in pairs(tbl) do + if callback(v, k, tbl) then + result[k] = v + end + end + return result + end +end + +if not table.all then + --- Checks if all elements of a table satisfy a condition. + ---@generic K, V, R + ---@param tbl table The input table. + ---@param callback fun(value: V, key: K, tbl: table): boolean The condition to check for each element. It receives three arguments: the element's value, its key, and the original table. It should return true if the element satisfies the condition, false otherwise. + ---@return boolean True if all elements satisfy the condition, false otherwise. + function table.all(tbl, callback) + for k, v in pairs(tbl) do + if not callback(v, k, tbl) then + return false + end + end + return true + end +end + +if not table.any then + --- Checks if at least one element of a table satisfies a condition. + ---@generic K, V, R + ---@param tbl table The input table. + ---@param callback fun(value: V, key: K, tbl: table): boolean The condition to check for each element. It receives three arguments: the element's value, its key, and the original table. It should return true if the element satisfies the condition, false otherwise. + ---@return boolean True if at least one element satisfies the condition, false otherwise. + function table.any(tbl, callback) + for k, v in pairs(tbl) do + if callback(v, k, tbl) then + return true + end + end + return false + end +end + +if not table.valueIntersection then + ---Creates a new array-style table containing the intersection of all input arrays. + ---Returns only unique elements that appear in all input arrays. + ---@generic V + ---@param ... V[] Any number of array-style tables. + ---@return V[] A new array containing only values present in all input arrays. + function table.valueIntersection(...) + local tables = { ...} + + -- Count occurrences of each value across all arrays + local valueCounts = {} + for _, tbl in pairs(tables) do + -- Use a set for each array to handle duplicates correctly + local seen = {} + for _, value in pairs(tbl) do + if not seen[value] then + seen[value] = true + valueCounts[value] = (valueCounts[value] or 0) + 1 + end + end + end + + -- Keep only values that appear in all arrays + local result = {} + local numTables = table.count(tables) + for value, count in pairs(valueCounts) do + if count == numTables then + result[#result + 1] = value + end + end + + return result + end +end + +if not pairsByKeys then + ---pairs-like iterator function traversing the table in the order of its keys. + ---Natural sort order will be used by default, optionally pass a comparator + ---function for custom sorting. + ---@generic K, V + ---@param tbl table + ---@param keySortFunction? fun(a: K, b: K): boolean comparator function passed to table.sort for sorting keys + ---@return fun(table: table, index?: K): K, V + ---@return table + ---(Implementation copied straight from the docs at https://www.lua.org/pil/19.3.html.) + function pairsByKeys(tbl, keySortFunction) + local keys = {} + for key in pairs(tbl) do table.insert(keys, key) end + table.sort(keys, keySortFunction) + local i = 0 -- iterator variable + local iter = function() -- iterator function + i = i + 1 + if keys[i] == nil then + return nil + else + return keys[i], tbl[keys[i]] + end + end + return iter + end +end + +if not math.isInRect then + function math.isInRect(x, y, BLcornerX, BLcornerY, TRcornerX, TRcornerY) + return x >= BLcornerX and x <= TRcornerX and y >= BLcornerY and y <= TRcornerY + end +end + +if not math.cross_product then + function math.cross_product (px, pz, ax, az, bx, bz) + return ((px - bx) * (az - bz) - (ax - bx) * (pz - bz)) + end +end + +if not math.triangulate then + -- accepts an array of polygons (where a polygon is an array of {x, z} vertices), and returns an array of counterclockwise triangles + function math.triangulate(polies) + local triangles = {} + local trianglesCount = 0 + for j = 1, #polies do + local polygon = polies[j] + + -- find out clockwisdom + local polygonVertexCount = #polygon + polygon[polygonVertexCount + 1] = polygon[1] + local clockwise = 0 + for i = 2, #polygon do + clockwise = clockwise + (polygon[i - 1][1] * polygon[i][2]) - (polygon[i - 1][2] * polygon[i][1]) + end + polygon[polygonVertexCount + 1] = nil + clockwise = (clockwise < 0) + + -- the van gogh concave polygon triangulation algorithm: cuts off ears + -- is pretty shitty at O(V^3) but was easy to code and it's typically only done once anyway + while #polygon > 2 do + + -- get a candidate ear + local triangle + local c0, c1, c2 = 0 + local candidate_ok = false + while not candidate_ok do + + c0 = c0 + 1 + c1, c2 = c0 + 1, c0 + 2 + if c1 > #polygon then + c1 = c1 - #polygon + end + if c2 > #polygon then + c2 = c2 - #polygon + end + triangle = { + polygon[c0][1], polygon[c0][2], + polygon[c1][1], polygon[c1][2], + polygon[c2][1], polygon[c2][2], + } + + -- make sure the ear is of proper rotation but then make it counter-clockwise + local dir = math.cross_product(triangle[5], triangle[6], triangle[1], triangle[2], triangle[3], triangle[4]) + if (dir < 0) == clockwise then + if dir > 0 then + local temp = triangle[5] + triangle[5] = triangle[3] + triangle[3] = temp + temp = triangle[6] + triangle[6] = triangle[4] + triangle[4] = temp + end + + -- check if no point lies inside the triangle + candidate_ok = true + for i = 1, #polygon do + if i ~= c0 and i ~= c1 and i ~= c2 then + local current_pt = polygon[i] + if (math.cross_product(current_pt[1], current_pt[2], triangle[1], triangle[2], triangle[3], triangle[4]) < 0) + and (math.cross_product(current_pt[1], current_pt[2], triangle[3], triangle[4], triangle[5], triangle[6]) < 0) + and (math.cross_product(current_pt[1], current_pt[2], triangle[5], triangle[6], triangle[1], triangle[2]) < 0) + then + candidate_ok = false + end + end + end + end + end + + -- cut off ear + trianglesCount = trianglesCount + 1 + triangles[trianglesCount] = triangle + table.remove(polygon, c1) + end + end + + return triangles + end +end + +if not math.closestPointOnCircle then + function math.closestPointOnCircle(centerX, centerZ, radius, targetX, targetZ) + local dx = targetX - centerX + local dz = targetZ - centerZ + local dist = math.diag(dx, dz) + if dist == 0 then + -- Target is exactly at center; choose arbitrary point on circle + return centerX + radius, centerZ + end + local scale = radius / dist + local closestX = centerX + dx * scale + local closestZ = centerZ + dz * scale + return closestX, closestZ + end +end + +if not math.HSLtoRGB then + function math.HSLtoRGB(ch, cs, cl) + if cs == 0 then + return cl, cl, cl + end + + local cr, cg, cb + local temp2 + if cl < 0.5 then + temp2 = cl * (cl + cs) + else + temp2 = (cl + cs) - (cl * cs) + end + + local temp1 = 2 * cl - temp2 + local tempr = ch + 1 / 3 + + if tempr > 1 then + tempr = tempr - 1 + end + local tempg = ch + local tempb = ch - 1 / 3 + if tempb < 0 then + tempb = tempb + 1 + end + + if tempr < 1 / 6 then + cr = temp1 + (temp2 - temp1) * 6 * tempr + elseif tempr < 0.5 then + cr = temp2 + elseif tempr < 2 / 3 then + cr = temp1 + (temp2 - temp1) * ((2 / 3) - tempr) * 6 + else + cr = temp1 + end + + if tempg < 1 / 6 then + cg = temp1 + (temp2 - temp1) * 6 * tempg + elseif tempg < 0.5 then + cg = temp2 + elseif tempg < 2 / 3 then + cg = temp1 + (temp2 - temp1) * ((2 / 3) - tempg) * 6 + else + cg = temp1 + end + + if tempb < 1 / 6 then + cb = temp1 + (temp2 - temp1) * 6 * tempb + elseif tempb < 0.5 then + cb = temp2 + elseif tempb < 2 / 3 then + cb = temp1 + (temp2 - temp1) * ((2 / 3) - tempb) * 6 + else + cb = temp1 + end + + return cr, cg, cb + end +end + +if not math.isPointInRectangle then + ---Check if a point is inside a rectangle. + ---@param x number + ---@param z number + ---@param rectangle {x1: number, z1: number, x2: number, z2: number} + ---@return boolean + function math.isPointInRectangle(x, z, rectangle) + return x >= rectangle.x1 and x <= rectangle.x2 and z >= rectangle.z1 and z <= rectangle.z2 + end +end + +if not math.isPointInCircle then + ---Check if a point is inside a circle. + ---@param x number + ---@param z number + ---@param circle {x: number, z: number, radius: number} + ---@return boolean + function math.isPointInCircle(x, z, circle) + local dx, dz = x - circle.x, z - circle.z + return dx * dx + dz * dz <= circle.radius * circle.radius + end +end + +if not math.isPointInArea then + ---Check if a point is inside an area. Dispatches to `math.isPointInRectangle` + ---or `math.isPointInCircle` based on the shape of the area. + ---@param x number + ---@param z number + ---@param area {x1: number, z1: number, x2: number, z2: number}|{x: number, z: number, radius: number} + ---@return boolean + function math.isPointInArea(x, z, area) + if area.x1 then + return math.isPointInRectangle(x, z, area) + else + return math.isPointInCircle(x, z, area) + end + end +end + +if not math.distance2dSquared then + function math.distance2dSquared(x1, z1, x2, z2) + local x = x1 - x2 + local z = z1 - z2 + return x * x + z * z + end +end + +if not math.distance2d then + function math.distance2d(x1, z1, x2, z2) + return math.diag(x1 - x2, z1 - z2) + end +end + +if not math.distance3dSquared then + function math.distance3dSquared(x1, y1, z1, x2, y2, z2) + local x = x1 - x2 + local y = y1 - y2 + local z = z1 - z2 + return x * x + y * y + z * z + end +end + +if not math.distance3d then + function math.distance3d(x1, y1, z1, x2, y2, z2) + return math.diag(x1 - x2, y1 - y2, z1 - z2) + end +end + +if not math.getClosestPosition then + ---Gets the closest position out of a list to given coordinates. 2d. + ---@param x number + ---@param z number + ---@param positions {x:number, z:number}[] must have fields .x and .z + ---@return {x:number, z:number}? position + function math.getClosestPosition(x, z, positions) + if not (x and z and positions and positions[1]) then + return + end + local bestPos + local bestDist = math.huge + for i = 1, #positions do + local pos = positions[i] + local dx, dz = x - pos.x, z - pos.z + local dist = dx * dx + dz * dz + if dist < bestDist then + bestPos = pos + bestDist = dist + end + end + return bestPos + end +end + +if not math.clampRadians then + local twoPi = 2 * math.pi + --- Clamp a radian angle between -pi and pi + ---@param r number radian value to clamp + ---@return number clamped radian value + function math.clampRadians(r) + local ret = r % twoPi + if ret > math.pi then + ret = ret - twoPi + end + return ret + end +end + +-------------------------------------------------------------------------------- +-------------------------------------------------------------------------------- +-- +-- file: setupdefs.lua +-- brief: setup some custom UnitDefs parameters, +-- and UnitDefNames, FeatureDefNames, WeaponDefNames +-- author: Dave Rodgers +-- +-- Copyright (C) 2007. +-- Licensed under the terms of the GNU GPL, v2 or later. +-- +-------------------------------------------------------------------------------- +-------------------------------------------------------------------------------- + +for _,ud in pairs(UnitDefs) do + -- set the cost value (same as shown in the tooltip) + ud.cost = ud.metalCost + (ud.energyCost / 60.0) + + -- add the custom weapons based parameters + ud.hasShield = false + ud.canParalyze = false + ud.canStockpile = false + ud.canAttackWater = false + ud.wDefs = {} + for i, wt in ipairs(ud.weapons) do + local wd = WeaponDefs[wt.weaponDef] + ud.wDefs[i] = wd + if (wd) then + if (wd.isShield) then ud.hasShield = true end + if (wd.paralyzer) then ud.canParalyze = true end + if (wd.stockpile) then ud.canStockpile = true end + if (wd.waterWeapon) then ud.canAttackWater = true end + end + end +end + +-------------------------------------------------------------------------------- +-------------------------------------------------------------------------------- + +-- setup the UnitDefNames{} table +do + local tbl = {} + for _,def in pairs(UnitDefs) do + tbl[def.name] = def + end + UnitDefNames = tbl +end + +-- setup the FeatureDefNames{} table +do + local tbl = {} + for _,def in pairs(FeatureDefs) do + tbl[def.name] = def + end + FeatureDefNames = tbl +end + +-- setup the WeaponDefNames{} table +do + local tbl = {} + for _,def in pairs(WeaponDefs) do + tbl[def.name] = def + end + WeaponDefNames = tbl +end + +-------------------------------------------------------------------------------- +-------------------------------------------------------------------------------- + + +local buildOrders,buildSplit,skipAllied,builder,mex,share,commandInsert +local controllerView +local function initializeControllers(ids) + local team=originalSpring.GetMyTeamID() + local view=tostring(team)..'/'..tostring(originalSpring.GetTeamAllyTeamID(team)) + if controllerView==view then return end + -- Read-only spectator/replay handles must not initialize gameplay widgets. + -- Original Initialize/RemoveWidget behavior stays intact; a valid interactive + -- call starts private controllers in their original dependency order. + selectedUnits=clone(ids or{}) + WG={resource_spot_finder=assert(WebbarOrderResourceSpots())};actions={} +buildOrders=(function()local widget={} +local widget = widget ---@type Widget + +local BpDefs = VFS.Include("luaui/Include/blueprint_substitution/definitions.lua") + +local SubLogic = VFS.Include("luaui/Include/blueprint_substitution/logic.lua") + +local CMD_GUARD = CMD.GUARD + +function widget:GetInfo() + return { + name = "Build Orders API", + desc = "Distributes build orders for a set of buildings across builders", + license = "GNU GPL, v2 or later", + layer = -2, -- before api_blueprint (-1), which consumes this API + enabled = true, + } +end + +---@class BuilderInfo +---@field unitID number +---@field unitDefID number +---@field side string +---@field buildSpeed number + +---@class BuildingInfo +---@field unitDefID number +---@field position number[] { x, y, z } +---@field facing? number + +---@param builderID number +---@return BuilderInfo +local function getBuilderInfo(builderID) + local unitDefID = Spring.GetUnitDefID(builderID) + if not unitDefID then + return nil + end + + local unitDef = UnitDefs[unitDefID] + if not unitDef then + return nil + end + + local side = SubLogic.getSideFromUnitName(unitDef.name) + + return { + unitID = builderID, + unitDefID = unitDefID, + side = side, + buildSpeed = unitDef.buildSpeed, + } +end + +---@param builderGroup BuilderInfo[] +---@param building BuildingInfo +---@param side string +---@param allowSubstitution boolean +---@return boolean +local function canBuild(builderGroup, building, side, allowSubstitution) + allowSubstitution = allowSubstitution ~= false -- Defaults to true + + local builderUnitDefID = builderGroup[1].unitDefID + local builderUnitDef = UnitDefs[builderUnitDefID] + + local substitutedUnitDefID = SubLogic.getEquivalentUnitDefID(building.unitDefID, side) + if not substitutedUnitDefID then + return false + end + + if not allowSubstitution and substitutedUnitDefID ~= building.unitDefID then + return false + end + + for _, buildOption in ipairs(builderUnitDef.buildOptions) do + if buildOption == substitutedUnitDefID then + return true + end + end + + return false +end + +---@param builders number[] +---@return table -- Groups builders by their unitDefID +local function groupBuilders(builders) + local builderGroups = {} + for _, builderID in ipairs(builders) do + local builderInfo = getBuilderInfo(builderID) + if builderInfo then + local uDefId = builderInfo.unitDefID + builderGroups[uDefId] = builderGroups[uDefId] or {} + table.insert(builderGroups[uDefId], builderInfo) + end + end + return builderGroups +end + +---Groups builders so that each builder forms its own group, keyed by unitID. +---Used by split mode, where every builder works its own fork. +---@param builders table A list of builder info objects. +---@return table One group per builder. +local function forkBuilders(builders) + local forkGroups = {} + for _, builderInfo in ipairs(builders) do + forkGroups[builderInfo.unitID] = { builderInfo } + end + return forkGroups +end + +--- Distributes a blueprint's buildings across builder groups, proportional to +--- each group's build power, with capability-aware leftover redistribution. The +--- first order issued to each group honors the user's shift state (replacing the +--- queue when shift wasn't held); the rest are queued. +--- +--- When peerFollowups is true (split mode), each group also receives every other +--- building it is capable of constructing as lower-priority followups, so a +--- builder finishes its own fork and then helps with whatever remains. When +--- builders outnumber buildings, the extras have empty own-chunks and simply +--- start helping (double-up). The engine skips orders whose positions are already +--- built, so the redundant followups self-clean. +---@param builderGroups table Builders grouped -- by unit type for +--- the linear path, or one-per-builder for split. +---@param allBuildings BuildingInfo[] The buildings to place, with positions. +---@param cmdOpts table Command options. +---@param peerFollowups boolean|nil If true, append peers' buildings as followups. +local function distributeBuildOrders(builderGroups, allBuildings, cmdOpts, peerFollowups) + -- A blueprint is many build orders, so every order after the first must queue + -- (shift) or it would overwrite the previous one. + local queuedOpts = table.copy(cmdOpts) + queuedOpts.shift = true + + local allBuilderGroups = {} + for key, builderGroup in pairs(builderGroups) do + if #builderGroup > 0 and builderGroup[1].buildSpeed > 0 then + local groupPower = #builderGroup * builderGroup[1].buildSpeed + table.insert(allBuilderGroups, { + group = builderGroup, + power = groupPower, + side = builderGroup[1].side, + key = key, + }) + end + end + table.sort(allBuilderGroups, function(a, b) + return a.power > b.power + end) + + -- 1. Calculate cost-based workload quotas + local totalBuildPower = 0 + for _, groupData in ipairs(allBuilderGroups) do + totalBuildPower = totalBuildPower + groupData.power + end + + if totalBuildPower <= 0 then + return + end + + local allBuildingsWithCost = {} + local totalBuildCost = 0 + for _, building in ipairs(allBuildings) do + local unitDef = UnitDefs[building.unitDefID] + local cost = (unitDef and unitDef.cost) or 0 + table.insert(allBuildingsWithCost, { building = building, cost = cost }) + totalBuildCost = totalBuildCost + cost + end + + -- 2. Partition the blueprint into cost-based linear chunks + local chunks = {} + local buildingIndex = 1 + for i, groupData in ipairs(allBuilderGroups) do + local proportion = groupData.power / totalBuildPower + local targetCostForGroup = totalBuildCost * proportion + + local buildingsForGroup = {} + local accumulatedCost = 0 + + if i == #allBuilderGroups then + -- Last group takes all remaining buildings + for j = buildingIndex, #allBuildingsWithCost do + table.insert(buildingsForGroup, allBuildingsWithCost[j].building) + end + else + while buildingIndex <= #allBuildingsWithCost do + local currentBuilding = allBuildingsWithCost[buildingIndex] + local costAfterAdding = accumulatedCost + currentBuilding.cost + + -- Stop if adding the next building makes the chunk's cost further from the target + if accumulatedCost > 0 and math.abs(costAfterAdding - targetCostForGroup) > math.abs(accumulatedCost - targetCostForGroup) then + break + end + + table.insert(buildingsForGroup, currentBuilding.building) + accumulatedCost = costAfterAdding + buildingIndex = buildingIndex + 1 + end + end + + table.insert(chunks, { groupData = groupData, buildings = buildingsForGroup }) + end + + -- 3. Assign each group its own chunk; what a group can't build spills over + local assignedBuildings = {} -- groupKey -> ordered list of building objects + for _, groupData in ipairs(allBuilderGroups) do + assignedBuildings[groupData.key] = {} + end + + local leftovers = {} + for _, chunk in ipairs(chunks) do + local groupData = chunk.groupData + for _, building in ipairs(chunk.buildings) do + if canBuild(groupData.group, building, groupData.side, true) then + table.insert(assignedBuildings[groupData.key], building) + else + table.insert(leftovers, building) + end + end + end + + -- 4. Redistribute leftovers to capable groups (round-robin within a category) + local leftoverTracker = {} -- category -> index + for _, building in ipairs(leftovers) do + local capableGroups = {} + for _, groupData in ipairs(allBuilderGroups) do + if canBuild(groupData.group, building, groupData.side, true) then + table.insert(capableGroups, groupData) + end + end + + if #capableGroups > 0 then + local targetGroupData + if #capableGroups == 1 then + targetGroupData = capableGroups[1] + else + table.sort(capableGroups, function(a, b) + return a.key > b.key + end) -- deterministic sort + local category = BpDefs.unitCategories[UnitDefs[building.unitDefID].name:lower()] or "uncategorized" + local currentIndex = (leftoverTracker[category] or 0) + 1 + if currentIndex > #capableGroups then + currentIndex = 1 + end + targetGroupData = capableGroups[currentIndex] + leftoverTracker[category] = currentIndex + end + + if targetGroupData then + table.insert(assignedBuildings[targetGroupData.key], building) + end + end + end + + -- 5. Split only: after its own chunk, give each group every other building it + -- can build as a followup, so each builder helps peers once its fork is done. + if peerFollowups then + for _, groupData in ipairs(allBuilderGroups) do + local own = {} + for _, building in ipairs(assignedBuildings[groupData.key]) do + own[building] = true + end + for _, building in ipairs(allBuildings) do + if not own[building] and canBuild(groupData.group, building, groupData.side, true) then + table.insert(assignedBuildings[groupData.key], building) + end + end + end + end + + -- 6. Issue each group's orders. The first order honors the user's real shift + -- state (replaces the queue when not held); the rest are queued. + for _, groupData in ipairs(allBuilderGroups) do + local buildings = assignedBuildings[groupData.key] + if #buildings > 0 then + local orders = {} + for _, building in ipairs(buildings) do + local substitutedUnitDefID = SubLogic.getEquivalentUnitDefID(building.unitDefID, groupData.side) + if substitutedUnitDefID then + table.insert(orders, { -substitutedUnitDefID, { building.position[1], building.position[2], building.position[3], building.facing }, queuedOpts }) + end + end + if #orders > 0 then + orders[1][3] = cmdOpts + local groupBuilderIDs = table.map(groupData.group, function(b) + return b.unitID + end) + Spring.GiveOrderArrayToUnitArray(groupBuilderIDs, orders, false) + end + end + end + + -- 7. Builders that can construct none of these buildings would otherwise idle. + -- Send each to guard a working builder so it assists construction instead of + -- sitting idle. (Builders that *can* build something but lost out on the split + -- are left alone -- they are not ineligible, just unlucky.) + local workingBuilderIDs = {} + for _, groupData in ipairs(allBuilderGroups) do + if #assignedBuildings[groupData.key] > 0 then + for _, builder in ipairs(groupData.group) do + table.insert(workingBuilderIDs, builder.unitID) + end + end + end + + if #workingBuilderIDs > 0 then + local guardIndex = 1 + for _, groupData in ipairs(allBuilderGroups) do + if #assignedBuildings[groupData.key] == 0 then + local canBuildAny = false + for _, building in ipairs(allBuildings) do + if canBuild(groupData.group, building, groupData.side, true) then + canBuildAny = true + break + end + end + + if not canBuildAny then + for _, builder in ipairs(groupData.group) do + Spring.GiveOrderToUnit(builder.unitID, CMD_GUARD, { workingBuilderIDs[guardIndex] }, cmdOpts) + guardIndex = guardIndex % #workingBuilderIDs + 1 + end + end + end + end + end +end + +--- Splits a blueprint across builders so each works its own fork first, then +--- helps peers. Building-aware: each builder only receives buildings it can +--- construct (with faction substitution), and extra builders double up. +---@param builders BuilderInfo[] A list of builder info objects. +---@param buildings BuildingInfo[] A list of building objects. +---@param cmdOpts table Command options. +local function splitBuildOrders(builders, buildings, cmdOpts) + if #builders == 0 or #buildings == 0 then + return + end + + distributeBuildOrders(forkBuilders(builders), buildings, cmdOpts, true) +end + +function widget:Initialize() + WG["api_build_orders"] = { + getBuilderInfo = getBuilderInfo, + groupBuilders = groupBuilders, + forkBuilders = forkBuilders, + canBuild = canBuild, + distributeBuildOrders = distributeBuildOrders, + splitBuildOrders = splitBuildOrders, + } +end + +function widget:Shutdown() + WG["api_build_orders"] = nil +end + +return widget end)() + +buildOrders:Initialize() +buildSplit=(function()local widget={} +local widget = widget ---@type Widget + +function widget:GetInfo() + return { + name = "Build Split", + desc = "Splits builds over cons, and vice versa (use shift+space to activate)", + author = "Niobium", + version = "v1.0", + date = "Jan 11, 2009", + license = "GNU GPL, v2 or later", + layer = 0, + enabled = true, + } +end + + +-- Localized Spring API for performance +local spGetSpectatingState = Spring.GetSpectatingState + +local spTestBuildOrder = Spring.TestBuildOrder +local spGetSelUnitCount = Spring.GetSelectedUnitsCount +local spGetSelUnitsSorted = Spring.GetSelectedUnitsSorted +local activeModifier = false + +local unitBuildOptions = {} +for udefID, def in ipairs(UnitDefs) do + if #def.buildOptions > 0 then + unitBuildOptions[udefID] = def.buildOptions + end +end + +local buildID = 0 +local buildLocs = {} +local buildCount = 0 + +local gameStarted = false +local isSpec = false + +local function maybeRemoveSelf() + if isSpec then + widgetHandler:RemoveWidget() + + return true + end +end + +function widget:GameStart() + gameStarted = true +end + +function widget:PlayerChanged() + isSpec = spGetSpectatingState() + maybeRemoveSelf() +end + +local function handleSetModifier(_, _, _, data) + data = data or {} + activeModifier = data[1] +end + +local function getBuilderInfos(unitIDs) + local builders = {} + for _, unitID in ipairs(unitIDs) do + local builderInfo = WG["api_build_orders"].getBuilderInfo(unitID) + if builderInfo and unitBuildOptions[builderInfo.unitDefID] then + table.insert(builders, builderInfo) + end + end + return builders +end + +---@param builderIDs number[] +---@param buildings BuildingInfo[] +---@param cmdOpts table +local function splitBuildings(builderIDs, buildings, cmdOpts) + local builders = getBuilderInfos(builderIDs) + WG["api_build_orders"].splitBuildOrders(builders, buildings, cmdOpts or { "shift" }) +end + +function widget:Initialize() + gameStarted = Spring.GetGameFrame() > 0 + isSpec = spGetSpectatingState() + + if maybeRemoveSelf() then + return + end + + widgetHandler:AddAction("buildsplit", handleSetModifier, { true }, "p") + widgetHandler:AddAction("buildsplit", handleSetModifier, { false }, "r") + + WG['build_split'] = { + isActive = function() return activeModifier end, + splitBuildings = splitBuildings, + } +end + +function widget:CommandNotify(cmdID, cmdParams, cmdOpts) -- 3 of 3 parameters + -- Don't handle blueprint commands (let cmd_blueprint handle those) + if cmdID == GameCMD.BLUEPRINT_PLACE or cmdID == GameCMD.BLUEPRINT_CREATE then + return false + end + + if not (cmdID < 0 and cmdOpts.shift and activeModifier) then + return false + end -- Note: All multibuilds require shift + + if spGetSelUnitCount() < 2 then + return false + end + + --if #cmdParams < 4 then return false end -- Probably not possible, commented for now + if spTestBuildOrder(-cmdID, cmdParams[1], cmdParams[2], cmdParams[3], cmdParams[4]) == 0 then + return false + end + + buildID = -cmdID + buildCount = buildCount + 1 + buildLocs[buildCount] = cmdParams + + return true +end + +function widget:Update() + if buildCount == 0 then + return + end + + if not gameStarted then + return + end + + local selUnits = spGetSelUnitsSorted() + + local builderIDs = {} + for uDefID, uIDs in pairs(selUnits) do + local uDef = UnitDefs[uDefID] + if uDef and uDef.buildOptions and #uDef.buildOptions > 0 then + for _, uID in ipairs(uIDs) do + table.insert(builderIDs, uID) + end + end + end + + local buildings = {} + for i = 1, buildCount do + ---@type BuildingInfo + local buildingInfo = {} + buildingInfo.unitDefID = buildID + buildingInfo.position = { buildLocs[i][1], buildLocs[i][2], buildLocs[i][3] } + buildingInfo.facing = buildLocs[i][4] + table.insert(buildings, buildingInfo) + end + + splitBuildings(builderIDs, buildings, { "shift" }) + + buildCount = 0 +end + +function widget:Shutdown() + WG['build_split'] = nil +end + +return widget end)() + +buildSplit:Initialize() +skipAllied=(function()local widget={} +local widget = widget ---@type Widget + +function widget:GetInfo() + return { + name = "Skip Allied Upgrade Toggle", + desc = "Adds a toggle indicating if allied buildings should be ignored when upgrading mexes and geos.", + author = "SuperKitowiec", + date = "August 27, 2025", + license = "GNU GPL, v2 or later", + version = 1, + layer = -999999, + enabled = true, + } +end + +local SkipAlliedUpgradeWidget = {} +local toggleIsActive = false +local shouldFilterByDefault = false + +---@param spots table Array of spots to filter +---@param unitDefIdsToCheck table +---@return table Filtered array of spots +function SkipAlliedUpgradeWidget.filterOutAlliedSpots(spots, unitDefIdsToCheck) + local shouldFilter = shouldFilterByDefault ~= toggleIsActive + if not shouldFilter then + return spots + end + local filteredSpots = {} + local nextFilteredSpotIndex = 1 -- to avoid recalculating table length in case of large 'spots' table + local myTeamID = Spring.GetMyTeamID() + + for i = 1, #spots do + local spot = spots[i] + local units = Spring.GetUnitsInCylinder(spot.x, spot.z, Game.extractorRadius) + local hasAlliedExtractor = false + + for j = 1, #units do + local unitDefID = Spring.GetUnitDefID(units[j]) + + if unitDefIdsToCheck[unitDefID] then + local unitTeam = Spring.GetUnitTeam(units[j]) + if Spring.AreTeamsAllied(myTeamID, unitTeam) and unitTeam ~= myTeamID then + hasAlliedExtractor = true + break + end + end + end + + if not hasAlliedExtractor then + filteredSpots[nextFilteredSpotIndex] = spot + nextFilteredSpotIndex = nextFilteredSpotIndex + 1 + end + end + return filteredSpots +end + +function widget:Initialize() + toggleIsActive = false + WG['skip_allied_upgrade'] = SkipAlliedUpgradeWidget + + widgetHandler:AddAction("toggle_allied_upgrade", function() toggleIsActive = true end, nil, "p") + widgetHandler:AddAction("toggle_allied_upgrade", function() toggleIsActive = false end, nil, "r") +end + +function widget:Shutdown() + widgetHandler:RemoveAction("toggle_allied_upgrade") +end + +return widget end)() + +skipAllied:Initialize() +builder=(function()local widget={} +local widget = widget ---@type Widget + +function widget:GetInfo() + return { + name = "API Resource Spot Builder (mex/geo)", + desc = "Handles construction of metal extractors and geothermal power plants for other widgets", + author = "Hobo Joe, badosu, Google Frog, NTG, Chojin, Doo, Floris, Tarte", + version = "2.0", + date = "Oct 23, 2010; last update: April 12, 2022", + license = "GNU GPL, v2 or later", + layer = -1, -- load before all widgets that need these mex/geo building tools + enabled = true + } +end + + +-- Localized functions for performance +local mathAbs = math.abs +local mathMax = math.max + +-- Localized Spring API for performance +local spGetUnitTeam = Spring.GetUnitTeam + +------------------------------------------------------------ +-- Speedups +------------------------------------------------------------ +local CMD_GUARD = CMD.GUARD + +local spGetBuildFacing = Spring.GetBuildFacing +local spGetSelectedUnits = Spring.GetSelectedUnits +local spGetGroundHeight = Spring.GetGroundHeight +local spGiveOrderToUnit = Spring.GiveOrderToUnit +local spPos2BuildPos = Spring.Pos2BuildPos +local spGetTeamUnits = Spring.GetTeamUnits +local spGetMyTeamID = Spring.GetMyTeamID +local spGetUnitPosition = Spring.GetUnitPosition +local spGetUnitIsBeingBuilt = Spring.GetUnitIsBeingBuilt +local spGetUnitDefID = Spring.GetUnitDefID + +local selectedUnits = spGetSelectedUnits() + +local Game_extractorRadius = Game.extractorRadius + +local isPregame = Spring.GetGameFrame() == 0 and not Spring.GetSpectatingState() + + +------------------------------------------------------------ +-- unit tables +------------------------------------------------------------ +local mexConstructors = {} +local mexConstructorsDef = {} +local mexBuildings = {} + +local geoConstructors = {} +local geoConstructorsDef = {} +local geoBuildings = {} + +------------------------------------------------------------ +-- populate unit tables +------------------------------------------------------------ + +for uDefID, uDef in pairs(UnitDefs) do + if uDef.extractsMetal > 0 then + mexBuildings[uDefID] = uDef.extractsMetal + end + local customParams = uDef.customParams or {} + if customParams.geothermal then + geoBuildings[uDefID] = uDef.energyMake + end +end + +for uDefID, uDef in pairs(UnitDefs) do + if uDef.buildOptions then + local maxExtractMetal = 0 + local maxProduceEnergy = 0 + for _, option in ipairs(uDef.buildOptions) do + if mexBuildings[option] then + maxExtractMetal = mathMax(maxExtractMetal, mexBuildings[option]) + if mexConstructorsDef[uDefID] then + mexConstructorsDef[uDefID].buildings = mexConstructorsDef[uDefID].buildings + 1 + mexConstructorsDef[uDefID].building[mexConstructorsDef[uDefID].buildings] = option * -1 + else + mexConstructorsDef[uDefID] = { buildings = 1, building = { [1] = option * -1 } } + end + end + if geoBuildings[option] then + maxProduceEnergy = mathMax(maxProduceEnergy, geoBuildings[option]) + if geoConstructorsDef[uDefID] then + geoConstructorsDef[uDefID].buildings = geoConstructorsDef[uDefID].buildings + 1 + geoConstructorsDef[uDefID].building[geoConstructorsDef[uDefID].buildings] = option * -1 + else + geoConstructorsDef[uDefID] = { buildings = 1, building = { [1] = option * -1 } } + end + end + end + end +end + + +------------------------------------------------------------ +-- Building logic +------------------------------------------------------------ + +---Checks if there is an existing extractor (mex or geo) in the given spot +---@param spot table +local function spotHasExtractor(spot) + local units = Spring.GetUnitsInCylinder(spot.x, spot.z, Game_extractorRadius) + local type = spot.isMex and mexBuildings or geoBuildings + for j = 1, #units do + if type[spGetUnitDefID(units[j])] then return units[j] end + end + return false +end + +---Checks if there is an existing command among the current builders to make an extractor on the given spot +---@param spot table +---@param builders table which units will have their queues checked - doing a global check is too expensive +local function spotHasExtractorQueued(spot, builders) + builders = builders or selectedUnits + + -- annoying pregame stuff + local function checkQueue(queue) + for j = 1, #queue do + local command = queue[j] + local id = command.id and -command.id or command[1] + local x = command.params and command.params[1] or command[2] + local z = command.params and command.params[3] or command[4] + if (mexBuildings[id] or geoBuildings[id]) then + local dist = math.distance2dSquared(spot.x, spot.z, x, z) + -- Save a sqrt by multiplying by 4 + -- Note that this is calculating by diameter, and could be too aggressive on maps with closely spaced mexes + -- Reduce this radius if there are cases found where mex spots get missed when in close proximity + if dist < Game_extractorRadius * Game_extractorRadius then + return true + end + end + end + return false + end + + if isPregame then + local queue = WG['pregame-build'].getBuildQueue() + return checkQueue(queue) + + else + for i = 1, #builders do + -- GetUnitCommands returns nil if enemy unit is selected (with godmode on) + local hasOrder = checkQueue(Spring.GetUnitCommands(builders[i], 100) or {}) + if hasOrder then + return true + end + end + end + return false +end + +---Gets the naive best extractor, ignores special mexes (exploiter etc), just finds highest extraction amount +---@param units table selected units +---@param constructorIds table builder types to check +---@param extractors table valid extractors, useful to specify specific types or check only geos etc +local function getBestExtractorFromBuilders(units, constructorIds, extractors) + local bestExtraction = 0 + local bestExtractor + for i = 1, #units do + -- only processes first mex option for each builder + local id = units[i] + local constructor = constructorIds[id] + + if constructor then + local buildingID = -constructor.building[1] + local extractionAmount = extractors[buildingID] + if (extractionAmount > bestExtraction) then + bestExtraction = extractionAmount + bestExtractor = buildingID + end + end + end + return bestExtractor +end + +---extractorCanBeUpgraded +---@param currentExtractorUuid number uuid of current extractor +---@param newExtractorId number unitDefID of new extractor +local function extractorCanBeUpgraded(currentExtractorUuid, newExtractorId) + local isAllied = Spring.AreTeamsAllied(spGetMyTeamID(), spGetUnitTeam(currentExtractorUuid)) + if not isAllied then + return false + end + + local currentExtractorId = spGetUnitDefID(currentExtractorUuid) + local newExtractor = UnitDefs[newExtractorId] + local newExtractorStrength = mexBuildings[newExtractorId] or geoBuildings[newExtractorId] + local currentExtractorStrength = mexBuildings[currentExtractorId] or geoBuildings[currentExtractorId] + + if not (newExtractorStrength and currentExtractorStrength) then + return false + end + + local newExtractorIsSpecial = newExtractor.stealth or #newExtractor.weapons > 0 + + if (newExtractorStrength > currentExtractorStrength) then + return true + end + if (newExtractorStrength == currentExtractorStrength and newExtractorIsSpecial) then + return true + end + if currentExtractorStrength == newExtractorStrength then + return false + end + + return false +end + +---Returns true if the specified extractor be built on this spot - considers upgrades and sidegrades +---@param spot table +---@param extractorId table +---@return boolean +local function extractorCanBeBuiltOnSpot(spot, extractorId) + local units = Spring.GetUnitsInCylinder(spot.x, spot.z, Game_extractorRadius) + + if #units == 0 then + return true + end + + for i = 1, #units do + local uid = units[i] + local uDefId = spGetUnitDefID(uid) + local isExtractor = spot.isMex and mexBuildings[uDefId] or geoBuildings[uDefId] + local canUpgrade = extractorCanBeUpgraded(uid, extractorId) + local isBeingBuilt, _ = spGetUnitIsBeingBuilt(uid) + if (isExtractor and (not canUpgrade or isBeingBuilt)) then + return false + end + end + + return true +end + +---Finds the nearest unoccupied resource spot from the provided list +---@param x number +---@param z number +---@param spotsIn table +---@param extractor table unitDefID +---@param shouldIgnoreAlreadyQueuedUpSpots boolean +local function findNearestValidSpotForExtractor(x, z, spotsIn, extractor, shouldIgnoreAlreadyQueuedUpSpots) + -- sort spots by distance + local spots = table.copy(spotsIn) + table.sort(spots, function(a, b) + return math.distance2dSquared(a.x, a.z, x, z) < math.distance2dSquared(b.x, b.z, x, z) + end) + for i = 1, #spots do + local spot = spots[i] + local existingExtractor = spotHasExtractor(spot) + local hasExtractorQueued = spotHasExtractorQueued(spot) + + if shouldIgnoreAlreadyQueuedUpSpots and not existingExtractor and not hasExtractorQueued then + return spot + end + + local isUnoccupied = not existingExtractor + local canBeBuiltOn = extractorCanBeBuiltOnSpot(spot, extractor) + local notQueued = not hasExtractorQueued + + local isValidSpot = (isUnoccupied or canBeBuiltOn) and (not shouldIgnoreAlreadyQueuedUpSpots or notQueued) + + if isValidSpot then + return spot + end + end +end + +---Gives build order to the units that can make the selected building, all other builders get guard commands to the primary builders +---@param units table +---@param constructorIds table +---@param buildingId table +---@param shift table +---@return table main builders, the ones that can make the selected building +local function sortBuilders(units, constructorIds, buildingId, shift) + -- Add highest producing constructors to mainBuilders table + give guard orders to "inferior" constructors + local mainBuilders = {} + local secondaryBuilders = {} + for i = 1, #units do + local id = units[i] + local constructor = constructorIds[id] + if constructor then + -- iterate over constructor options to see if it can make the chosen extractor + local canBuild = false + for _, buildable in pairs(constructor.building) do + if -buildable == buildingId then + -- assume that it's a valid extractor based on previous steps + mainBuilders[#mainBuilders + 1] = id + canBuild = true + break + end + end + if not canBuild then + secondaryBuilders[#secondaryBuilders + 1] = id + end + end + end + + -------------------------------- + -- Small local functions to iterate over current builders and reduce command spam. Potentially expensive with 50+ selected cons + local function isMainBuilderOfId(id) + for i = 1, #mainBuilders do + if mainBuilders[i] == id then + return true + end + end + return false + end + + local function hasExistingGuardOrder(uid) + -- GetUnitCommands returns nil if enemy unit is selected (with godmode on) + local queue = Spring.GetUnitCommands(uid, 10) or {} + for i = 1, #queue do + local cmd = queue[i] + if cmd.id == CMD_GUARD and (cmd.params and cmd.params[1] and isMainBuilderOfId(cmd.params[1])) then + return true + end + end + return false + end + ----------------------------------- + + -- order secondary builders to guard main builders, equally dispersed + local index = 1 + for i, uid in pairs(secondaryBuilders) do + local mainBuilderId = mainBuilders[index] + if not shift then + spGiveOrderToUnit(uid, CMD_GUARD, { mainBuilderId }, { }) + index = index + 1 + end + -- if we give a guard order on a unit already guarded with shift, it will get cancelled + -- so do some queue analysis and avoid duplicate commands + if shift and not hasExistingGuardOrder(uid) then + spGiveOrderToUnit(uid, CMD_GUARD, { mainBuilderId }, { "shift" }) + index = index + 1 + end + + if index > #mainBuilders then index = 1 end + end + + if #mainBuilders == 0 then return end + return mainBuilders +end + +local function previewMetalMapExtractorCommand(params, extractor) + local buildingId = -extractor + local facing = spGetBuildFacing() or 1 + local x, y, z = spPos2BuildPos(extractor, params[1], params[2], params[3]) + local targetOwner = spGetMyTeamID() + + if x and z then + return { mathAbs(buildingId), x, y, z, facing, targetOwner } + end + return nil +end + +---Puts together build orders for ghost previews (e.g. mex snap). These orders can be fed directly to +---ApplyPreviewCmds to actually give the orders to units +---@param params table +---@param extractor table +---@param spot table must be a full spot, not just position. isMex or isGeo field required for things to work. +---@param metalMap boolean if this is for a metal map. If so it's used for upgrade visualizing only and takes a different code path. +---@return table format is { buildingId, x, y, z, facing, owner } +local function PreviewExtractorCommand(params, extractor, spot, metalMap) + if metalMap and not spot then + return previewMetalMapExtractorCommand(params, extractor) + end + local cmdX, _, cmdZ = params[1], params[2], params[3] + + -- Skip mex spots that have queued mexes already + if not extractorCanBeBuiltOnSpot(spot, extractor) then + return + end + + -- Construct the actual mex build orders + local facing = spGetBuildFacing() or 1 + local finalCommand + + local buildingId = -extractor + local targetPos, targetOwner + local occupiedSpot = spotHasExtractor(spot) + if occupiedSpot then + local occupiedPos = { spGetUnitPosition(occupiedSpot) } + targetPos = { x = occupiedPos[1], y = occupiedPos[2], z = occupiedPos[3] } + targetOwner = spGetUnitTeam(occupiedSpot) -- because gadget "Mex Upgrade Reclaimer" will share a t2 mex build upon ally t1 mex + else + local buildingPositions = WG['resource_spot_finder'].GetBuildingPositions(spot, -buildingId, 0, true) + targetPos = math.getClosestPosition(cmdX, cmdZ, buildingPositions) + targetOwner = spGetMyTeamID() + end + if targetPos then + local newx, newz = targetPos.x, targetPos.z + finalCommand = { mathAbs(buildingId), newx, spGetGroundHeight(newx, newz), newz, facing, targetOwner } + end + return finalCommand +end + +local function ApplyPreviewCmds(cmds, constructorIds, shift) + if not cmds or #cmds <= 0 then + return + end + local units = selectedUnits + local buildingId = cmds[1][1] -- assume they are all the same building id + local mainBuilders = sortBuilders(units, constructorIds, buildingId, shift) + + if not mainBuilders or #mainBuilders <= 0 then + return + end + + local _, _, meta, _ = Spring.GetModKeyState() + + local unitArray = {} -- make unit array to avoid extra work + for i = 1, #mainBuilders do + unitArray[#unitArray + 1] = mainBuilders[i] + end + + for i = 1, #cmds do + local cmd = cmds[i] + local orderParams = { cmd[2], cmd[3], cmd[4], cmd[5] } + + if meta then + -- put at front of queue + -- cmd insert layout is really weird, it needs to be formatted like: + -- { CMD.INSERT, { queue_pos, cmd_id, opt, params_flattened, }, { "alt }} + -- this an engine command so index starts at 0. Increment position by command count + Spring.GiveOrderToUnitArray(unitArray, CMD.INSERT, { i - 1, -buildingId, 0, unpack(orderParams) }, { "alt" }) + else + -- we don't want to give a stop command to clear queue because it plays an unwanted sound + -- issuing any command without shift will clear the queue for us, + -- so we use the real shift value for the first command, then we force shift for all the others + -- since any commands passed to this function are intended to be queued, not discarded. + -- NEVER USE TERNARIES WITH OUTCOME VALUES THAT CAN BE FALSE + local fakeShift = false + if i == 1 then + fakeShift = shift + else + fakeShift = true + end + local opt = fakeShift and { "shift" } or { } + Spring.GiveOrderToUnitArray(unitArray, -buildingId, orderParams, opt) + end + end +end + + +------------------------------------------------------------ +-- Callins +------------------------------------------------------------ + +function widget:SelectionChanged(sel) + selectedUnits = sel +end + +function widget:UnitCreated(unitID, unitDefID) + if mexConstructorsDef[unitDefID] then + mexConstructors[unitID] = mexConstructorsDef[unitDefID] + end + if geoConstructorsDef[unitDefID] then + geoConstructors[unitID] = geoConstructorsDef[unitDefID] + end +end + +function widget:UnitTaken(unitID, unitDefID, _, newTeam) + if not mexConstructors[unitID] or geoConstructors[unitID] then + widget:UnitCreated(unitID, unitDefID, newTeam) + end +end + +function widget:UnitGiven(unitID, unitDefID, newTeam) + if not mexConstructors[unitID] or geoConstructors[unitID] then + widget:UnitCreated(unitID, unitDefID, newTeam) + end +end + +function widget:GameStart() + isPregame = false +end + +function widget:Initialize() + local units = spGetTeamUnits(spGetMyTeamID()) + for i = 1, #units do + local id = units[i] + widget:UnitCreated(id, spGetUnitDefID(id)) + end + + -- make interfaces available to other widgets: + WG['resource_spot_builder'] = { + ExtractorCanBeBuiltOnSpot = extractorCanBeBuiltOnSpot, + ExtractorCanBeUpgraded = extractorCanBeUpgraded, + FindNearestValidSpotForExtractor = findNearestValidSpotForExtractor, + PreviewExtractorCommand = PreviewExtractorCommand, + ApplyPreviewCmds = ApplyPreviewCmds, + SpotHasExtractorQueued = spotHasExtractorQueued, + GetBestExtractorFromBuilders = getBestExtractorFromBuilders, + } + + ---------------------------------------------- + -- builders and buildings - MEX + ---------------------------------------------- + + WG['resource_spot_builder'].GetMexConstructors = function() + return mexConstructors + end + + WG['resource_spot_builder'].GetMexBuildings = function() + return mexBuildings + end + + WG['resource_spot_builder'].GetGeoConstructors = function() + return geoConstructors + end + + WG['resource_spot_builder'].GetGeoBuildings = function() + return geoBuildings + end +end + +return widget end)() + +builder:Initialize() +mex=(function()local widget={} +local widget = widget ---@type Widget + +function widget:GetInfo() + return { + name = "Area Mex", + desc = "Adds a command to cap mexes in an area.", + author = "Hobo Joe, Google Frog, NTG, Chojin , Doo, Floris, Tarte, Baldric", + date = "Oct 23, 2010, (last update: March 3, 2022)", + license = "GNU GPL, v2 or later", + handler = true, + layer = 1, + enabled = true + } +end + +local CMD_AREA_MEX = GameCMD.AREA_MEX + +local spGetActiveCommand = Spring.GetActiveCommand +local spGetUnitCommands = Spring.GetUnitCommands +local spGetMapDrawMode = Spring.GetMapDrawMode +local spGetUnitPosition = Spring.GetUnitPosition +local spSendCommands = Spring.SendCommands +local taremove = table.remove + +local toggledMetal, retoggleLos +local selectedMex +local selectedUnits +local mexConstructors +local mexBuildings +local metalSpots + +local metalMap = false + + +local function setAreaMexType(uDefID) + selectedMex = -uDefID +end + +function widget:Initialize() + metalSpots = WG['resource_spot_finder'].metalSpotsList + metalMap = WG['resource_spot_finder'].isMetalMap + mexBuildings = WG["resource_spot_builder"].GetMexBuildings() + mexConstructors = WG["resource_spot_builder"].GetMexConstructors() + + WG['areamex'] = {} + WG['areamex'].setAreaMexType = function(uDefID) + setAreaMexType(uDefID) + end +end + + +---Gets the position of the last command in a unit's queue, or nil if the queue is empty +---@param unitID number +---@return number|nil x +---@return number|nil z +local function getLastQueuedPosition(unitID) + local queue = spGetUnitCommands(unitID, -1) + if queue and #queue > 0 then + local lastCmd = queue[#queue] + if lastCmd.params and #lastCmd.params >= 3 then + return lastCmd.params[1], lastCmd.params[3] + end + end + return nil, nil +end + + +---Finds all builders among selected units that can make the specified building, and gets their average position. +---When useQueueEnd is true, uses the position of the last queued command instead of the unit's current position. +---@param units table selected units +---@param constructorIds table All mex constructors +---@param buildingId number Specific mex that we want to build +---@param useQueueEnd boolean Whether to use the end-of-queue position (for shift-queuing) +---@return table { x, z } +local function getAvgPositionOfValidBuilders(units, constructorIds, buildingId, useQueueEnd) + -- Add highest producing constructors to mainBuilders table + give guard orders to "inferior" constructors + local builderCount = 0 + local tX, tZ = 0, 0 + for i = 1, #units do + local id = units[i] + local constructor = constructorIds[id] + if constructor then + -- iterate over constructor options to see if it can make the chosen extractor + for _, buildable in pairs(constructor.building) do + if -buildable == buildingId then -- assume that it's a valid extractor based on previous steps + local x, z + if useQueueEnd then + x, z = getLastQueuedPosition(id) + end + if not x then + local _ + x, _, z = spGetUnitPosition(id) + end + if z then + tX, tZ = tX + x, tZ + z + builderCount = builderCount + 1 + end + end + end + end + end + + if builderCount == 0 then return end + return { x = tX / builderCount, z = tZ / builderCount } +end + +---Get all mex spots in an area +---@param x number +---@param z number +---@param radius number +---@return table Array of spots within the specified area +local function getSpotsInArea(x, z, radius) + local validSpots = {} + + for i = 1, #metalSpots do + local spot = metalSpots[i] + local dist = math.distance2dSquared(x, z, spot.x, spot.z) + if dist < radius * radius then + validSpots[#validSpots + 1] = spot + end + end + return validSpots +end + + +---Make build commands for all passed in spots, but do not apply them +---@param spots table +---@return table An array of commands, in the same format as PreviewExtractorCommand +local function getCmdsForValidSpots(spots, shift) + local cmds = {} + for i = 1, #spots do + local spot = spots[i] + local spotHasQueue = shift and WG["resource_spot_builder"].SpotHasExtractorQueued(spot) or false + if not spotHasQueue then + local pos = { spot.x, spot.y, spot.z } + local cmd = WG['resource_spot_builder'].PreviewExtractorCommand(pos, selectedMex, spot) + if cmd then + cmds[#cmds + 1] = cmd + end + end + end + return cmds +end + + +---Nearest neighbor search. Spots are passed in to do minor weighting based on mex value +---@param cmds table +---@param spots table +---@param shift boolean Whether shift was held (appending to existing queue) +local function calculateCmdOrder(cmds, spots, shift) + local builderPos = getAvgPositionOfValidBuilders(selectedUnits, mexConstructors, selectedMex, shift) + if not builderPos then return {} end + local orderedCommands = {} + local pos = {} + while #cmds > 0 do + local shortestDist = math.huge + local shortestIndex = -1 + for i = 1, #cmds do + local dist = math.distance2dSquared(builderPos.x, builderPos.z, cmds[i][2], cmds[i][4]) + dist = dist / spots[i].worth + if dist < shortestDist then + shortestDist = dist + shortestIndex = i + pos = { x = cmds[i][2], z = cmds[i][4] } + end + + end + orderedCommands[#orderedCommands + 1] = cmds[shortestIndex] + taremove(cmds, shortestIndex) + taremove(spots, shortestIndex) + builderPos = pos + end + return orderedCommands +end + +local function getSelectedBuilderIDs() + local builders = {} + for i = 1, #selectedUnits do + local unitID = selectedUnits[i] + if mexConstructors[unitID] then + builders[#builders + 1] = unitID + end + end + return builders +end + +---@return BuildingInfo[] +local function mapCommandsToBuildingInfos(cmds) + local buildings = {} + for i = 1, #cmds do + local cmd = cmds[i] + ---@type BuildingInfo + local buildingInfo = {} + buildingInfo.unitDefID = cmd[1] + buildingInfo.position = { cmd[2], cmd[3], cmd[4] } + buildingInfo.facing = cmd[5] + buildings[#buildings + 1] = buildingInfo + end + return buildings +end + + +function widget:CommandNotify(id, params, options) + if id ~= CMD_AREA_MEX then + return + end + + local cmdX, _, cmdZ, cmdRadius = params[1], params[2], params[3], params[4] + local spots = getSpotsInArea(cmdX, cmdZ, cmdRadius) + if WG['skip_allied_upgrade'] then + spots = WG['skip_allied_upgrade'].filterOutAlliedSpots(spots, mexBuildings) + end + + if not selectedMex then + selectedMex = WG['resource_spot_builder'].GetBestExtractorFromBuilders(selectedUnits, mexConstructors, mexBuildings) + end + + local alt, ctrl, meta, shift = Spring.GetModKeyState() + local cmds = getCmdsForValidSpots(spots, shift) + local sortedCmds = calculateCmdOrder(cmds, spots, shift) + + -- WG["build_split"] has to be guarded because it can be disabled in settings + local isBuildSplitActive = WG["build_split"] and WG["build_split"].isActive() + if options.shift and isBuildSplitActive and #sortedCmds > 0 then + WG["build_split"].splitBuildings(getSelectedBuilderIDs(), mapCommandsToBuildingInfos(sortedCmds), { "shift" }) + else + WG['resource_spot_builder'].ApplyPreviewCmds(sortedCmds, mexConstructors, shift) + end + + selectedMex = nil + + if not options.shift then + if WG["gridmenu"] then WG["gridmenu"].clearCategory() end + end + return true +end + + +-- Adjust map view mode as needed +function widget:Update(dt) + local _, cmd, _ = spGetActiveCommand() + if cmd == CMD_AREA_MEX then + if spGetMapDrawMode() ~= 'metal' then + if Spring.GetMapDrawMode() == "los" then + retoggleLos = true + end + spSendCommands('ShowMetalMap') + toggledMetal = true + end + else + if toggledMetal then + spSendCommands('ShowStandard') + if retoggleLos then + Spring.SendCommands("togglelos") + retoggleLos = nil + end + toggledMetal = false + end + end +end + + +function widget:SelectionChanged(sel) + selectedUnits = sel +end + + +function widget:CommandsChanged() + if not metalMap then + if selectedUnits and #selectedUnits > 0 then + local customCommands = widgetHandler.customCommands + for i = 1, #selectedUnits do + if WG['resource_spot_builder'] and WG['resource_spot_builder'].GetMexConstructors()[selectedUnits[i]] then + customCommands[#customCommands + 1] = { + id = CMD_AREA_MEX, + type = CMDTYPE.ICON_AREA, + tooltip = 'Define an area (with metal spots in it) to make metal extractors in', + name = 'Mex', + cursor = 'areamex', + action = 'areamex', + } + return + end + end + end + end +end + + +return widget end)() + +mex:Initialize() +share=(function()local widget={} +local widget = widget ---@type Widget + +function widget:GetInfo() + return { + name = "Share Unit Command", + desc = "Adds a command which allows you to quickly share unit to other player. Just target the command on any allied unit and you will share to this player", + author = "SuperKitowiec", + date = "2024", + license = "GNU GPL, v2 or later", + version = 1.0, + layer = 0, + enabled = true, + handler = true, + } +end + +-------------------------------------------------------------------------------- +--vars +-------------------------------------------------------------------------------- +local aoeLineWidthMult = 100 +local circleDivs = 96 +local numAoECircles = 5 +local circleList +local secondPart = 0 +local mouseDistance = 1000 +local range = 200 + +-------------------------------------------------------------------------------- +--speedups +-------------------------------------------------------------------------------- +local GetUnitsInCylinder = Spring.GetUnitsInCylinder +local GetMyTeamID = Spring.GetMyTeamID +local GetUnitTeam = Spring.GetUnitTeam +local GetSelectedUnits = Spring.GetSelectedUnits +local GetTeamAllyTeamID = Spring.GetTeamAllyTeamID +local ShareResources = Spring.ShareResources +local I18N = Spring.I18N +local GetSpectatingState = Spring.GetSpectatingState +local WorldToScreenCoords = Spring.WorldToScreenCoords +local PlaySoundFile = Spring.PlaySoundFile +local GetTeamColor = Spring.GetTeamColor +local GetActiveCommand = Spring.GetActiveCommand +local GetCameraPosition = Spring.GetCameraPosition +local GetMouseState = Spring.GetMouseState +local TraceScreenRay = Spring.TraceScreenRay +local GetPlayerList = Spring.GetPlayerList +local GetPlayerInfo = Spring.GetPlayerInfo +local GetGameRulesParam = Spring.GetGameRulesParam +local GetViewGeometry = Spring.GetViewGeometry + +local glBeginEnd = gl.BeginEnd +local glCallList = gl.CallList +local glCreateList = gl.CreateList +local glColor = gl.Color +local glDeleteList = gl.DeleteList +local glLineWidth = gl.LineWidth +local glPopMatrix = gl.PopMatrix +local glPushMatrix = gl.PushMatrix +local glScale = gl.Scale +local glTranslate = gl.Translate +local glVertex = gl.Vertex +local GL_LINE_LOOP = GL.LINE_LOOP + +local PI = math.pi +local cos = math.cos +local sin = math.sin +local floor = math.floor +local sqrt = math.sqrt +local max = math.max + +local defaultColor + +local cmdQuickShareToTargetId = 455624 +local myTeamID = GetMyTeamID() +local myAllyTeamID = GetTeamAllyTeamID(myTeamID) + +local function tablelength(T) + local count = 0 + for _ in pairs(T) do + count = count + 1 + end + return count +end + +local function getSecondPart(offset) + local result = secondPart + (offset or 0) + return result - floor(result) +end + +local function unitCircleVertices() + for i = 1, circleDivs do + local theta = 2 * PI * i / circleDivs + glVertex(cos(theta), 0, sin(theta)) + end +end + +local function drawUnitCircle() + glBeginEnd(GL_LINE_LOOP, unitCircleVertices) +end + +local function setupDisplayLists() + circleList = glCreateList(drawUnitCircle) +end + +local function deleteDisplayLists() + glDeleteList(circleList) +end + +local function drawCircle(x, y, z, radius) + glPushMatrix() + glTranslate(x, y, z) + glScale(radius, radius, radius) + + glCallList(circleList) + + glPopMatrix() +end + +local function getMouseTargetPosition() + local mx, my = GetMouseState() + local mouseTargetType, mouseTarget = TraceScreenRay(mx, my) + if mouseTarget and mouseTargetType then + if mouseTargetType == "ground" then + return mouseTarget[1], mouseTarget[2], mouseTarget[3] + elseif mouseTargetType == "unit" then + local _, coordinates = TraceScreenRay(mx, my, true) + if coordinates then + return coordinates[1], coordinates[2], coordinates[3], mouseTarget + else + return nil, nil, nil, mouseTarget + end + elseif mouseTargetType == "feature" then + local _, coordinates = TraceScreenRay(mx, my, true) + if coordinates then + return coordinates[1], coordinates[2], coordinates[3] + end + else + return nil + end + else + return nil + end +end + +local function getMouseDistance() + local cx, cy, cz = GetCameraPosition() + local mx, my, mz = getMouseTargetPosition() + if not mz then + return nil + end + local dx = cx - mx + local dy = cy - my + local dz = cz - mz + return sqrt(dx * dx + dy * dy + dz * dz) +end + +local function getTeamColorWithAlpha(teamId) + local tred, tgreen, tblue = GetTeamColor(teamId) + return { tred, tgreen, tblue, 1 } +end + +local function drawAoE(tx, ty, tz, selectedTeam) + --local color = selectedTeam and getTeamColorWithAlpha(selectedTeam) or defaultColor + local color = defaultColor + + mouseDistance = getMouseDistance() or 1000 + glLineWidth(max(aoeLineWidthMult * range / mouseDistance, 0.5)) + + for i = 1, numAoECircles do + local proportion = i / (numAoECircles + 1) + local radius = range * proportion + local alpha = color[4] * (1 - proportion) / (1 - proportion) * (1 - getSecondPart(0)) + glColor(color[1], color[2], color[3], alpha) + drawCircle(tx, ty, tz, radius) + end + + glColor(1, 1, 1, 1) + glLineWidth(1) +end + +local function findPlayerName(teamId) + local name = '' + if GetGameRulesParam('ainame_' .. teamId) then + name = I18N('ui.playersList.aiName', { name = GetGameRulesParam('ainame_' .. teamId) }) + else + local players = GetPlayerList(teamId) + name = (#players > 0) and GetPlayerInfo(players[1], false) or '------' + + for _, pID in ipairs(players) do + local pname, active, isspec = GetPlayerInfo(pID, false) + if active and not isspec then + name = pname + break + end + end + end + return name +end + +local function colourNames(teamId) + if tonumber(teamId) < 0 then + return "" + end + local nameColourR, nameColourG, nameColourB, nameColourA = Spring.GetTeamColor(teamId) + return Spring.Utilities.Color.ToString(nameColourR, nameColourG, nameColourB) +end + +local function drawName(teamId) + local mouseX, mouseY = GetMouseState() + local textY = mouseY + 40 + + if teamId then + font:Begin() + font:SetTextColor(defaultColor) + font:SetOutlineColor({ 0, 0, 0, 1 }) + font:Print(I18N("ui.quickShareToTarget.shareTo", { + playerColor = colourNames(teamId), + player = findPlayerName(teamId) + }), mouseX, textY, 24, "con") + font:End() + else + font:Begin() + font:SetTextColor(defaultColor) + font:SetOutlineColor({ 0, 0, 0, 1 }) + font:Print(I18N("ui.quickShareToTarget.noTarget"), mouseX, textY, 24, "con") + font:End() + end + +end + +local function isAlly(unitTeamId) + return unitTeamId ~= myTeamID and GetTeamAllyTeamID(unitTeamId) == myAllyTeamID +end + +local function findTeamInArea(mx, my) + local _, cUnitID = TraceScreenRay(mx, my, true) + + if cUnitID == nil then + return nil + end + + local foundUnits = GetUnitsInCylinder(cUnitID[1], cUnitID[3], range, -3) + + if #foundUnits < 1 then + return nil + end + + local unitTeamCounters = {} + + for _, unitId in ipairs(foundUnits) do + local unitTeamId = GetUnitTeam(unitId) + if unitTeamId ~= myTeamID then + unitTeamId = tostring(unitTeamId) + if unitTeamCounters[unitTeamId] == nil then + unitTeamCounters[unitTeamId] = 1 + else + unitTeamCounters[unitTeamId] = unitTeamCounters[unitTeamId] + 1 + end + end + end + + if tablelength(unitTeamCounters) < 1 then + return nil + end + + local selectedTeam + for unitTeamId, count in pairs(unitTeamCounters) do + if selectedTeam == nil then + selectedTeam = unitTeamId + elseif count > unitTeamCounters[selectedTeam] then + selectedTeam = unitTeamId + end + end + return selectedTeam +end + +local function getSelectedTeam() + local _, cmd, _ = GetActiveCommand() + + if cmd ~= cmdQuickShareToTargetId then + return nil + end + + local tx, ty, tz, targetUnitID = getMouseTargetPosition() + + if (not tx and not targetUnitID) then + return nil + end + + local selectedTeam + if targetUnitID then + local targetUnitTeamID = GetUnitTeam(targetUnitID) + if isAlly(targetUnitTeamID) then + selectedTeam = targetUnitTeamID + end + else + local mouseX, mouseY = WorldToScreenCoords(tx, ty, tz) + selectedTeam = findTeamInArea(mouseX, mouseY) + end + + return tx, ty, tz, selectedTeam +end + +function widget:DrawWorld() + local targetX, targetY, targetZ, selectedTeam = getSelectedTeam() + + if (not targetX) then + return + end + + drawAoE(targetX, targetY+10, targetZ, selectedTeam) +end + +function widget:DrawScreen() + local targetX, _, _, selectedTeam = getSelectedTeam() + + if (not targetX) then + return + end + + drawName(selectedTeam) +end + +function widget:CommandNotify(cmdID, cmdParams, _) + if cmdID == cmdQuickShareToTargetId then + local targetTeamID + if #cmdParams ~= 1 and #cmdParams ~= 3 then + return true + elseif #cmdParams == 1 then + -- click on unit + local targetUnitID = cmdParams[1] + targetTeamID = GetUnitTeam(targetUnitID) + elseif #cmdParams == 3 then + -- click on the ground + local mouseX, mouseY = WorldToScreenCoords(cmdParams[1], cmdParams[2], cmdParams[3]) + targetTeamID = findTeamInArea(mouseX, mouseY) + end + + if targetTeamID == nil or targetTeamID == myTeamID or GetTeamAllyTeamID(targetTeamID) ~= myAllyTeamID then + -- invalid target, don't do anything + return true + end + + ShareResources(targetTeamID, "units") + PlaySoundFile("beep4", 1, 'ui') + return false + end +end + +function widget:CommandsChanged() + if GetSpectatingState() then + return + end + + local teams = Spring.GetTeamList(myAllyTeamID) + if not teams or #teams <= 1 then + return -- no allied teams to share to + end + + local selectedUnits = GetSelectedUnits() + if #selectedUnits > 0 then + local customCommands = widgetHandler.customCommands + customCommands[#customCommands + 1] = { + id = cmdQuickShareToTargetId, + type = CMDTYPE.ICON_UNIT_OR_MAP, + name = 'Share Unit To Target', + cursor = 'settarget', + action = 'quicksharetotarget', + } + end +end + +function widget:ViewResize(vsx, vsy) + font = WG['fonts'].getFont(2, 1.5) +end + +function widget:Initialize() + widget:ViewResize() + defaultColor = { 0.88, 0.88, 0.88, 1 } + setupDisplayLists() +end + +function widget:Shutdown() + deleteDisplayLists() +end + +return widget end)() + +commandInsert=(function()local widget={} +------------------------------------------------------------------------------------- +------------------------------------------------------------------------------------- + +local widget = widget ---@type Widget + +function widget:GetInfo() + return { + name = "CommandInsert", + desc = "When pressing spacebar and shift, you can insert commands to arbitrary places in queue. When pressing spacebar alone, commands are inserted on front of queue. Based on FrontInsert by jK", + author = "dizekat", + date = "Jan,2008", + license = "GNU GPL, v2 or later", + layer = 5, + enabled = true + } +end + + +-- Localized functions for performance +local tableInsert = table.insert + +-- Localized Spring API for performance +local spGetUnitPosition = Spring.GetUnitPosition +local spGetGameFrame = Spring.GetGameFrame +local spGiveOrderToUnit = Spring.GiveOrderToUnit +local spEcho = Spring.Echo + +local math_sqrt = math.sqrt + +local modifiers = { + prepend_between = false, + prepend_queue = false, +} + +-- Current position in prepend queue for prepend_queue mode +local prependPos = 0 + +function widget:GameStart() + widget:PlayerChanged() +end + +function widget:PlayerChanged() + if Spring.GetSpectatingState() and spGetGameFrame() > 0 then + widgetHandler:RemoveWidget() + end +end + +local function pressHandler(_, _, args) + if not args then return end + + if modifiers[args[1]] == nil then return end + + modifiers[args[1]] = true + + if args[1] == 'prepend_queue' then + prependPos = 0 + end +end + +local function releaseHandler(_, _, args) + if not args then return end + + if modifiers[args[1]] == nil then return end + + modifiers[args[1]] = false +end + +function widget:Initialize() + if Spring.IsReplay() or spGetGameFrame() > 0 then + widget:PlayerChanged() + end + + widgetHandler:AddAction("commandinsert", pressHandler, nil, "p") + widgetHandler:AddAction("commandinsert", releaseHandler, nil, "r") +end + +--[[ +-- use this for debugging: +function table.val_to_str ( v ) + if "string" == type( v ) then + v = string.gsub( v, "\n", "\\n" ) + if string.match( string.gsub(v,"[^'\"]",""), '^"+$' ) then + return "'" .. v .. "'" + end + return '"' .. string.gsub(v,'"', '\\"' ) .. '"' + else + return "table" == type( v ) and table.tostring( v ) or + tostring( v ) + end +end + +function table.key_to_str ( k ) + if "string" == type( k ) and string.match( k, "^[_%a][_%a%d]*$" ) then + return k + else + return "[" .. table.val_to_str( k ) .. "]" + end +end + +function table.tostring( tbl ) + local result, done = {}, {} + for k, v in ipairs( tbl ) do + tableInsert( result, table.val_to_str( v ) ) + done[ k ] = true + end + for k, v in pairs( tbl ) do + if not done[ k ] then + tableInsert( result, + table.key_to_str( k ) .. "=" .. table.val_to_str( v ) ) + end + end + return "{" .. table.concat( result, "," ) .. "}" +end +--]] + +local function GetUnitOrFeaturePosition(id) + if id < Game.maxUnits then + return spGetUnitPosition(id) + else + return Spring.GetFeaturePosition(id - Game.maxUnits) + end +end + +local function GetCommandPos(command) --- get the command position + if command.id < 0 or command.id == CMD.MOVE or command.id == CMD.REPAIR or command.id == CMD.RECLAIM or + command.id == CMD.RESURRECT or command.id == CMD.DGUN or command.id == CMD.GUARD or + command.id == CMD.FIGHT or command.id == CMD.ATTACK then + if table.getn(command.params) >= 3 then + return command.params[1], command.params[2], command.params[3] + elseif table.getn(command.params) >= 1 then + return GetUnitOrFeaturePosition(command.params[1]) + end + end + return -10,-10,-10 +end + +function widget:CommandNotify(id, params, options) + if not (modifiers.prepend_between or modifiers.prepend_queue) then + return false + end + + local opt = 0 + if options.alt then opt = opt + CMD.OPT_ALT end + if options.ctrl then opt = opt + CMD.OPT_CTRL end + if options.right then opt = opt + CMD.OPT_RIGHT end + -- options.meta not forwarded since we're doing insert with it + -- and don't want to alias with engine at the same time. + if options.shift then + opt = opt + CMD.OPT_SHIFT + + if modifiers.prepend_queue then + Spring.GiveOrder(CMD.INSERT, { prependPos, id, opt, unpack(params) }, { "alt" }) + + prependPos = prependPos + 1 + + return true + end + else + Spring.GiveOrder(CMD.INSERT,{0,id,opt,unpack(params)},{"alt"}) + + return true + end + + -- Spring.GiveOrder(CMD.INSERT,{0,id,opt,unpack(params)},{"alt"}) + local my_command = {["id"]=id, ["params"]=params, ["options"]=options} + local cx,cy,cz = GetCommandPos(my_command) + if cx < -1 then + return false + end + + local units = Spring.GetSelectedUnits() + for i=1,#units do + local unit_id = units[i] + local commands = Spring.GetUnitCommands(unit_id,100) + local px,py,pz = spGetUnitPosition(unit_id) + local min_dlen = 1000000 + local insert_pos = 0 + for j=1,#commands do + local command = commands[j] + --spEcho("cmd:"..table.tostring(command)) + local px2,py2,pz2 = GetCommandPos(command) + if px2 and px2>-1 then + local dlen = math_sqrt(((px2-cx)*(px2-cx)) + ((py2-cy)*(py2-cy)) + ((pz2-cz)*(pz2-cz))) + math_sqrt(((px-cx)*(px-cx)) + ((py-cy)*(py-cy)) + ((pz-cz)*(pz-cz))) - math_sqrt((((px2-px)*(px2-px)) + ((py2-py)*(py2-py)) + ((pz2-pz)*(pz2-pz)))) + --spEcho("dlen "..dlen) + if dlen < min_dlen then + min_dlen = dlen + insert_pos = j + end + px,py,pz = px2,py2,pz2 + end + end + -- check for insert at end of queue if its shortest walk. + local dlen = math_sqrt(((px-cx)*(px-cx)) + ((py-cy)*(py-cy)) + ((pz-cz)*(py-cy))) + if dlen < min_dlen then + --options.meta=nil + --options.shift=true + --spGiveOrderToUnit(unit_id,id,params,options) + spGiveOrderToUnit(unit_id, id, params, {"shift"}) + else + spGiveOrderToUnit(unit_id, CMD.INSERT, {insert_pos-1, id, opt, unpack(params)}, {"alt"}) + end + end + + -- When we are editing the build order we want to keep same active command after unset by engine + if id < 0 then + Spring.SetActiveCommand(Spring.GetCmdDescIndex(id), 1, true, false, options.alt, options.ctrl, false, false) + end + + return true +end + +return widget end)() + +commandInsert:Initialize() + controllerView=view +end +local function setAction(name,value,words) + local row=assert(actions[name][value and'p'or'r']);row.callback(name,'',words or{},row.data) +end +local function selection(ids) + selectedUnits=clone(ids);builder:SelectionChanged(selectedUnits);mex:SelectionChanged(selectedUnits) + -- Original queue checks default to selected builders. Retire private classifier + -- membership for deselections/reused IDs without broadening that read scope. + for _,units in ipairs({WG.resource_spot_builder.GetMexConstructors(),WG.resource_spot_builder.GetGeoConstructors()})do for id in pairs(units)do units[id]=nil end end + for _,id in ipairs(selectedUnits)do builder:UnitCreated(id,assert(Spring.GetUnitDefID(id)))end +end +function WebbarOrderAction(ids,id,params,options,input) + assert(type(ids)=='table'and #ids>0 and #ids<=8192 and type(params)=='table'and type(options)=='table'and type(input)=='table') + assert(originalSpring.GetGameFrame()>0 and not originalSpring.GetSpectatingState(),'Order action controls unavailable') + initializeControllers(ids) + builder:GameStart();buildSplit:GameStart() + groups,effects,groupKeys={},{},{};selection(ids) + modifiers=assert(input.modifiers);facing=assert(input.facing) + setAction('buildsplit',input.buildSplit==true);setAction('toggle_allied_upgrade',input.skipAllied==true) + setAction('commandinsert',modifiers[3]==true,{'prepend_between'}) + local consumed=false + -- The pinned handler sorts CommandNotify by ascending widget layer. Area Mex + -- (1) and Share (0) keep their original routes before CommandInsert (5). + -- Ordinary explicit targets then run the entire original insertion widget; + -- never reinterpret a raw META option as native front/nearest insertion. + if id==GameCMD.AREA_MEX then consumed=mex:CommandNotify(id,params,options)==true + elseif id==455624 then consumed=share:CommandNotify(id,params,options)==true + else consumed=commandInsert:CommandNotify(id,params,options)==true end + return{groups=groups,effects=effects,consumed=consumed,selected=selectedUnits} +end +function WebbarOrderActionUpdate(id,mode) + assert(type(mode)=='string'and #mode<=64 and not mode:find('%z'),'Invalid Order map-view mode');mapMode=mode + if originalSpring.GetGameFrame()<=0 or originalSpring.GetSpectatingState()then return{effects={}}end + initializeControllers() + groups,effects,groupKeys={},{},{};activeCommand=id;mex:Update(0) + return{effects=effects} +end +end + +)WOC_ACTION"; --- /dev/null +++ b/rts/Game/WebbarOrderActionHost.h @@ -0,0 +1,190 @@ +/* This file is part of the Spring engine (GPL v2 or later), see LICENSE.html */ +#pragma once +#include +#include +#include +#include +#include +#include +#include +#include "Lua/LuaUtils.h" +#include "WebbarNativeOrderTransport.h" + +namespace WebbarNativeOrder { +struct ActionEffect { + enum Kind { Orders, Direct, Share, Clear, Sound } kind; + size_t group = 0; + int team = -1; + bool pairwise = false; + std::vector commands; +}; +struct ActionPlan { + int id = 0, sharedTo = -1; + bool prepared = false, consumed = false, cleared = false; + unsigned issued = 0, sounds = 0; + std::unordered_set admitted; + std::vector> groups; + std::vector effects; + std::vector selected, affected; + + bool Consistent() const { + if (id >= 0 && id != 30100 && id != 455624) { + if (cleared || sharedTo != -1 || sounds || selected.size() != admitted.size()) return false; + if (!consumed) return issued == 0 && effects.empty() && affected.empty(); + if (!issued || affected.size() != admitted.size()) return false; + for (const auto& e: effects) { + if ((e.kind != ActionEffect::Orders && e.kind != ActionEffect::Direct) || e.commands.size() != 1 || e.pairwise) return false; + const auto& c = e.commands.front(); + if (e.kind == ActionEffect::Direct) { + if (groups[e.group].size() != admitted.size() || c.GetID() != CMD_INSERT || c.GetNumParams() < 3 || c.GetParam(0) != 0 || c.GetParam(1) != id) return false; + } else { + if (groups[e.group].size() != 1 || (c.GetID() != id && (c.GetID() != CMD_INSERT || c.GetNumParams() < 3 || c.GetParam(1) != id))) return false; + } + } + return true; + } + if (id == 30100) { + return consumed && !cleared && sharedTo == -1 && sounds == 0 && selected.size() == admitted.size() + && std::all_of(effects.begin(), effects.end(), [](const auto& e) { return e.kind == ActionEffect::Orders; }); + } + if (id != 455624 || issued != 0) return false; + if (sharedTo == -1) return consumed && !cleared && sounds == 0 && effects.empty() && selected.size() == admitted.size(); + return !consumed && cleared && sounds == 1 && selected.empty() && effects.size() == 3 + && effects[0].kind == ActionEffect::Share && effects[1].kind == ActionEffect::Clear && effects[2].kind == ActionEffect::Sound + && groups[effects[0].group].size() == admitted.size(); + } + bool ValidateDispatch() const { + if (!Consistent()) return false; + for (const auto& e: effects) { + if (e.kind == ActionEffect::Orders && !ArrayPacketFits(groups[e.group], e.commands)) return false; + if (e.kind == ActionEffect::Direct) { + std::vector packet; + if (!SelectionPacket(groups[e.group], packet)) return false; + for (const auto& c: e.commands) if (!DirectCommand(c)) return false; + } + if (e.kind == ActionEffect::Share && !CanShareSelection(groups[e.group], e.team)) return false; + } + return true; + } + bool Dispatch(bool fromPlayerNetwork) const { + if (!ValidateDispatch()) return false; + for (const auto& e: effects) { + if (e.kind == ActionEffect::Orders) selectedUnitsHandler.SendCommandsToUnits(groups[e.group], e.commands, e.pairwise, fromPlayerNetwork); + if (e.kind == ActionEffect::Direct && !SendSelectionCommands(groups[e.group], e.commands, fromPlayerNetwork)) return false; + // Original Share returns false after clearing its private selection. There + // is no remaining selection on which to send a fallback raw455624 command. + if (e.kind == ActionEffect::Share && !ShareSelection(groups[e.group], e.team)) return false; + } + return true; + } + std::string Result() const { + auto ids=[](const std::vector& values) { + std::string out = "["; + for (size_t n = 0; n < values.size(); ++n) { if (n) out += ','; out += std::to_string(values[n]); } + return out + ']'; + }; + return "{\"activation\":null,\"commands\":[],\"custom\":{\"id\":" + std::to_string(id) + + ",\"affected\":" + ids(affected) + ",\"selected\":" + ids(selected) + ",\"issued\":" + std::to_string(issued) + + ",\"consumed\":" + (consumed ? "true" : "false") + ",\"cleared\":" + (cleared ? "true" : "false") + + ",\"sharedTo\":" + (sharedTo < 0 ? "null" : std::to_string(sharedTo)) + + ",\"sounds\":" + (sounds ? "[{\"name\":\"beep4\",\"volume\":1,\"channel\":\"ui\"}]" : "[]") + "}}"; + } +}; + +inline int ActionIndex(lua_State* L, int index) { return index > 0 ? index : lua_gettop(L) + index + 1; } +inline int ActionArray(lua_State* L, int index, unsigned limit) { + index = ActionIndex(L, index); + if (!lua_istable(L, index) || lua_objlen(L, index) > limit) return luaL_error(L, "Invalid original Order action array"); + const int count = lua_objlen(L, index); + for (lua_pushnil(L); lua_next(L, index); lua_pop(L, 1)) { + const float key = lua_tonumber(L, -2); + if (lua_type(L, -2) != LUA_TNUMBER || !std::isfinite(key) || key < 1 || key > count || key != std::floor(key)) return luaL_error(L, "Non-array original Order action field"); + } + return count; +} +inline int ActionInteger(lua_State* L, int index, int low, int high) { + const float value = lua_tonumber(L, index); + if (lua_type(L, index) != LUA_TNUMBER || !std::isfinite(value) || value < low || value > high || value != std::floor(value)) return luaL_error(L, "Invalid original Order action integer"); + return int(value); +} +inline bool ActionBoolean(lua_State* L, int index) { + if (!lua_isboolean(L, index)) luaL_error(L, "Invalid original Order action boolean"); + return lua_toboolean(L, index); +} +inline bool ActionString(lua_State* L, int index, const char* expected) { + if (lua_type(L, index) != LUA_TSTRING) return false; + size_t count; const char* value = lua_tolstring(L, index, &count); + return count == std::strlen(expected) && std::memcmp(value, expected, count) == 0; +} +inline void ActionIds(lua_State* L, int index, const std::unordered_set& admitted, std::vector& ids) { + index = ActionIndex(L, index); + const int count = ActionArray(L, index, 8192); + std::unordered_set seen; + for (int n = 1; n <= count; ++n) { + lua_rawgeti(L, index, n); const int id = ActionInteger(L, -1, 0, 32767); lua_pop(L, 1); + if (!admitted.count(id) || !seen.insert(id).second) luaL_error(L, "Original Order action left admitted selection"); + ids.push_back(id); + } +} +// Run as a protected Lua C closure. ParseCommandArray retains original mixed +// option-table semantics and native float ordering; its errors stay inside pcall. +inline int ParseActionResult(lua_State* L) { + auto& plan = *static_cast(lua_touserdata(L, lua_upvalueindex(1))); + if (!lua_istable(L, 1)) return luaL_error(L, "Missing original Order action result"); + lua_getfield(L, 1, "consumed"); plan.consumed = ActionBoolean(L, -1); lua_pop(L, 1); + lua_getfield(L, 1, "selected"); ActionIds(L, -1, plan.admitted, plan.selected); lua_pop(L, 1); + lua_getfield(L, 1, "groups"); const int groups = lua_gettop(L), groupCount = ActionArray(L, groups, 8192); + unsigned membership = 0; + for (int n = 1; n <= groupCount; ++n) { + lua_rawgeti(L, groups, n); plan.groups.emplace_back(); ActionIds(L, -1, plan.admitted, plan.groups.back()); lua_pop(L, 1); + membership += plan.groups.back().size(); + if (plan.groups.back().empty() || membership > 524288) return luaL_error(L, "Original Order action group budget exceeded"); + } + lua_pop(L, 1); + lua_getfield(L, 1, "effects"); const int effects = lua_gettop(L), effectCount = ActionArray(L, effects, 65536); + std::unordered_set affected; + for (int n = 1; n <= effectCount; ++n) { + lua_rawgeti(L, effects, n); if (!lua_istable(L, -1)) return luaL_error(L, "Invalid original Order action effect"); + const int row = lua_gettop(L); lua_getfield(L, row, "kind"); + const bool orders = ActionString(L, -1, "orders"), direct = ActionString(L, -1, "direct"), share = ActionString(L, -1, "share"), clear = ActionString(L, -1, "selection-clear"), soundEffect = ActionString(L, -1, "sound"); lua_pop(L, 1); + if (!orders && !direct && !share && !clear && !soundEffect) return luaL_error(L, "Unexpected original Order action effect"); + plan.effects.emplace_back(); auto& e = plan.effects.back(); + e.kind = orders ? ActionEffect::Orders : direct ? ActionEffect::Direct : share ? ActionEffect::Share : clear ? ActionEffect::Clear : ActionEffect::Sound; + if (orders || direct || share) { + lua_getfield(L, row, "group"); e.group = ActionInteger(L, -1, 1, groupCount) - 1; lua_pop(L, 1); + } + if (orders || direct) { + lua_getfield(L, row, "pairwise"); e.pairwise = ActionBoolean(L, -1); lua_pop(L, 1); + lua_getfield(L, row, "orders"); ActionArray(L, -1, 65536); + LuaUtils::ParseCommandArray(L, "Webbar original Order action", lua_gettop(L), e.commands); lua_pop(L, 1); + plan.issued += e.commands.size(); if (plan.issued > 65536) return luaL_error(L, "Original Order action command budget exceeded"); + for (const auto& c: e.commands) { + if (c.GetNumParams() > (65535u - 17u) / 4u) return luaL_error(L, "Original Order action parameter budget exceeded"); + for (unsigned p = 0; p < c.GetNumParams(); ++p) if (!std::isfinite(c.GetParam(p))) return luaL_error(L, "Non-finite original Order action parameter"); + } + if (orders && !ArrayPacketFits(plan.groups[e.group], e.commands)) return luaL_error(L, "Original Order action exceeds native Lua-array packet limit"); + if (direct) { + std::vector packet; + if (!SelectionPacket(plan.groups[e.group], packet) || std::any_of(e.commands.begin(), e.commands.end(), [](const auto& c) { return !DirectCommand(c); })) return luaL_error(L, "Original Order action exceeds native selection packet limit"); + } + if (!e.commands.empty()) affected.insert(plan.groups[e.group].begin(), plan.groups[e.group].end()); + } else if (share) { + lua_getfield(L, row, "team"); e.team = ActionInteger(L, -1, 0, 254); lua_pop(L, 1); + if (plan.sharedTo != -1 || !CanShareSelection(plan.groups[e.group], e.team)) return luaL_error(L, "Invalid original Order share receiver"); + plan.sharedTo = e.team; affected.insert(plan.groups[e.group].begin(), plan.groups[e.group].end()); + } else if (clear) { + if (plan.cleared) return luaL_error(L, "Duplicate original Order selection clear"); + plan.cleared = true; + } else if (soundEffect) { + lua_getfield(L, row, "path"); const bool path = ActionString(L, -1, "beep4"); lua_pop(L, 1); + lua_getfield(L, row, "channel"); const bool channel = ActionString(L, -1, "ui"); lua_pop(L, 1); + lua_getfield(L, row, "volume"); const bool volume = lua_type(L, -1) == LUA_TNUMBER && lua_tonumber(L, -1) == 1; lua_pop(L, 1); + if (!path || !channel || !volume || ++plan.sounds > 1) return luaL_error(L, "Unexpected original Order feedback sound"); + } + lua_pop(L, 1); + } + plan.affected.assign(affected.begin(), affected.end()); std::sort(plan.affected.begin(), plan.affected.end()); + if (!plan.Consistent()) return luaL_error(L, "Inconsistent original Order action result"); + return 0; +} +} --- /dev/null +++ b/rts/Game/WebbarOrderProposalStore.h @@ -0,0 +1,66 @@ +/* This file is part of the Spring engine (GPL v2 or later), see LICENSE.html */ +#pragma once +#include +#include +#include +#include +#include +#include +#include + +namespace WebbarNativeOrder { +struct ProposalScope { + uint32_t frame = 0, team = 0, command = 0, type = 0; + std::vector> units; + bool Matches(const ProposalScope& current) const { + return current.frame >= frame && current.frame - frame <= 30 + && team == current.team && command == current.command && type == current.type && units == current.units; + } +}; + +// Original commands are retained natively. The page can approve or discard an +// opaque, single-use proposal; it cannot replace its IDs, options or parameters. +// Preparing never dispatches. A paused match still has finite retained storage. +template class ProposalStore { + struct Entry { ProposalScope scope; Payload payload; size_t bytes; uint64_t sequence; }; + std::unordered_map entries; + size_t bytes = 0; + uint64_t sequence = 0; + void Erase(typename std::unordered_map::iterator it) { + bytes -= it->second.bytes; entries.erase(it); + } +public: + static constexpr size_t MaxEntries = 8, MaxProposalBytes = 4 * 1024 * 1024, MaxBytes = 16 * 1024 * 1024; + void Expire(uint32_t frame, uint32_t team) { + for (auto it = entries.begin(); it != entries.end();) { + const auto& scope = it->second.scope; + if (scope.team != team || frame < scope.frame || frame - scope.frame > 30) { auto old = it++; Erase(old); } + else ++it; + } + } + bool Put(uint32_t token, ProposalScope scope, Payload payload, size_t size) { + Expire(scope.frame, scope.team); + const auto old = entries.find(token); + if (old != entries.end()) { Erase(old); return false; } + if (!token || scope.units.empty() || scope.units.size() > 8192 || !size || size > MaxProposalBytes) return false; + // A revoked page may be unable to send its cancellation. While paused, + // frame expiry cannot free those slots. Keep fresh input usable without + // growing retention or ever reviving an evicted approval token. + while (entries.size() >= MaxEntries || size > MaxBytes - bytes) + Erase(std::min_element(entries.begin(), entries.end(), [](const auto& a, const auto& b) { return a.second.sequence < b.second.sequence; })); + if (++sequence == 0) { Clear(); sequence = 1; } + entries.emplace(token, Entry{std::move(scope), std::move(payload), size, sequence}); bytes += size; return true; + } + std::optional Take(uint32_t token, const ProposalScope& current) { + Expire(current.frame, current.team); + const auto it = entries.find(token); if (it == entries.end()) return std::nullopt; + const bool valid = it->second.scope.Matches(current); + Payload payload = std::move(it->second.payload); Erase(it); + if (!valid) return std::nullopt; + return std::move(payload); + } + void Clear() { entries.clear(); bytes = 0; sequence = 0; } + size_t Count() const { return entries.size(); } + size_t Bytes() const { return bytes; } +}; +} --- /dev/null +++ b/rts/Game/WebbarOrderReadAdapter.h @@ -0,0 +1,3403 @@ +/* This file is part of the Spring engine (GPL v2 or later), see LICENSE.html */ +#pragma once +static constexpr const char* WEBBAR_ORDER_READ_ADAPTER = R"WebbarOrderLua( +do +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 + +local WAIT=5 +-- Original native read functions remain the authority for every live field. +local function packed(...) + if select('#',...)==0 then return nil end + return{n=select('#',...),...} +end +function WebbarReadOrder(ids,commands,page) + assert(type(ids)=='table'and #ids<=8192 and type(commands)=='table'and #commands<=8192) + local out={selected=ids,commands=commands,commandPage=page,units={},definitions={},modOptions={experimental_defend_firestate=Spring.GetModOptions().experimental_defend_firestate}} + for index,id in ipairs(ids)do + local row={id=id,definition=assert(Spring.GetUnitDefID(id)),team=assert(Spring.GetUnitTeam(id)),rules={targetID=Spring.GetUnitRulesParam(id,'targetID'),targetCoordX=Spring.GetUnitRulesParam(id,'targetCoordX')}} + out.definitions[row.definition]={isFactory=UnitDefs[row.definition].isFactory} + if index==1 then + row.rules.user_firestate=Spring.GetUnitRulesParam(id,'user_firestate') + row.states=packed(Spring.GetUnitStates(id,false)) + -- Order queries only the first unit's Wait capability and first queue item. + -- Keep the native descriptor and queue getters, including factory behavior. + local waitIndex=Spring.FindUnitCmdDesc(id,WAIT) + row.commands=waitIndex and Spring.GetUnitCmdDescs(id,waitIndex,waitIndex)or{} + local queue=UnitDefs[row.definition].isFactory and Spring.GetFactoryCommands(id,1)or Spring.GetUnitCommands(id,1) + if queue then row.queue={};for i,command in ipairs(queue)do row.queue[i]={id=command.id}end end + end + out.units[id]=row + end + return out +end + +end +do +local originalSpring=Spring +local selectedUnits={} +local Spring=setmetatable({ + GetSelectedUnits=function()return selectedUnits end, + -- Native ForceLayoutUpdate only invalidates the global GUI. The private + -- reader calls LayoutButtons itself and must leave that GUI unchanged. + ForceLayoutUpdate=function()end, +},{__index=originalSpring}) +local WG={} +local widgetHandler={customCommands={}} +local tracy={ZoneBeginN=function()end,ZoneEnd=function()end} +local CMD={["STOP"]=0,["INSERT"]=1,["REMOVE"]=2,["WAIT"]=5,["TIMEWAIT"]=6,["DEATHWAIT"]=7,["SQUADWAIT"]=8,["GATHERWAIT"]=9,["MOVE"]=10,["PATROL"]=15,["FIGHT"]=16,["ATTACK"]=20,["AREA_ATTACK"]=21,["GUARD"]=25,["GROUPSELECT"]=35,["GROUPADD"]=36,["GROUPCLEAR"]=37,["REPAIR"]=40,["FIRE_STATE"]=45,["MOVE_STATE"]=50,["SETBASE"]=55,["INTERNAL"]=60,["SELFD"]=65,["LOAD_UNITS"]=75,["LOAD_ONTO"]=76,["UNLOAD_UNITS"]=80,["UNLOAD_UNIT"]=81,["ONOFF"]=85,["RECLAIM"]=90,["CLOAK"]=95,["STOCKPILE"]=100,["MANUALFIRE"]=105,["RESTORE"]=110,["REPEAT"]=115,["TRAJECTORY"]=120,["RESURRECT"]=125,["CAPTURE"]=130,["AUTOREPAIRLEVEL"]=135,["IDLEMODE"]=145,["FAILED"]=150} +local CMDTYPE={["ICON"]=0,["ICON_MODE"]=5,["ICON_MAP"]=10,["ICON_AREA"]=11,["ICON_UNIT"]=12,["ICON_UNIT_OR_MAP"]=13,["ICON_FRONT"]=14,["ICON_UNIT_OR_AREA"]=16,["NEXT"]=17,["PREV"]=18,["ICON_UNIT_FEATURE_OR_AREA"]=19,["ICON_BUILDING"]=20,["CUSTOM"]=21,["ICON_UNIT_OR_RECTANGLE"]=22,["NUMBER"]=23} +local CMD_AREA_MEX=(function() +-------------------------------------------------------------------------------- +-- +-- Proposed Command ID Ranges: +-- +-- all negative: Engine (build commands) +-- 0 - 999: Engine +-- 1000 - 9999: Group AI +-- 10000 - 19999: LuaUI +-- 20000 - 29999: LuaCob +-- 30000 - 39999: LuaRules +-- + +-- if you add a command, please order it by ID! + +local gameCommands = { + FACTORY_GUARD = 13921, + AREA_GUARD = 13922, -- unused + STOP_PRODUCTION = 13923, + + -- blueprint + BLUEPRINT_PLACE = 18200, + BLUEPRINT_CREATE = 18201, + + -- quota + QUOTA_BUILD_TOGGLE = 23000, + + AREA_MEX = 30100, + SELL_UNIT = 30101, + + CARRIER_SPAWN_ONOFF = 31200, + MORPH = 31210, + USER_FIRESTATE = 31300, + MANUAL_LAUNCH = 32102, + UNIT_SET_TARGET_NO_GROUND = 34922, -- unit_target_on_the_move + UNIT_SET_TARGET = 34923, + UNIT_CANCEL_TARGET = 34924, + UNIT_SET_TARGET_RECTANGLE = 34925, + LAND_AT = 34569, + PRIORITY = 34571, + WANT_CLOAK = 37382, + HOUND_WEAPON_TOGGLE = 37383, -- unused + SMART_TOGGLE = 37384, + AREA_ATTACK_GROUND = 39954, + + -- terraform + RAW_MOVE = 39812, +} + +local globalCmdDeprecatedShown = false + +local importCommandsToObject = function(object) + if not globalCmdDeprecatedShown and not object.gadgetHandler then + local msg = 'Should not use customcmds.h.lua or importCommandsToObject. Use the CMD table directly, or read modules/customcommands.lua for more information.' + Spring.Log('CMD', LOG.DEPRECATED, msg) + globalCmdDeprecatedShown = true + end + for code, cmdID in pairs(gameCommands) do + if type(code) == 'string' then + object['CMD_' .. code] = cmdID + end + end + +end + +for code, cmdID in pairs(gameCommands) do + if CMD[cmdID] then + Spring.Log('CMD', LOG.ERROR, 'Duplicate command id: ' .. code .. ' ' .. tostring(cmdID) .. '!') + end + if CMD[code] then + Spring.Log('CMD', LOG.ERROR, 'Duplicate command code: ' .. code .. ' ' .. tostring(cmdID) .. '!') + end + gameCommands[cmdID] = code +end + +local getCommandCode = function(cmdID) + return CMD[cmdID] or gameCommands[cmdID] +end + +return { + GameCMD = gameCommands, + ImportCommandsToObject = importCommandsToObject, + GetCommandCode = getCommandCode, + } + +end)().GameCMD.AREA_MEX +local metalMapForOrder=(function() + local widget={} +local upget = gadget or widget ---@type Addon +local globalScope = gadget and GG or WG + +-- gadget side must be layered after gadgets/map_metal_spot_placer.lua +-- so that it works with maps with side-configured metal spots +local layer = gadget and -9 or -999999 + +function upget:GetInfo() + return { + name = "API Resource Spot Finder (mex/geo)", + desc = "Finds metal and geothermal spots for other upgets", + author = "Niobium, Tarte (added geothermal)", + version = "2.0", + date = "November 2010: last update: April 13, 2022", + license = "GNU GPL, v2 or later", + layer = layer, + enabled = true, + } +end + +if gadget then + if not gadgetHandler:IsSyncedCode() then + return + end +end + +local metalMapSquareSize = Game.metalMapSquareSize -- Resolution of metal map +local squareSize = Game.squareSize -- Resolution of build positions +local precision = Game.footprintScale * Game.squareSize -- (footprint 1 = 16 map distance) + +-- Some of these maps have more than 2 metal spots, disable mex denier +local metalMaps = { + ["Oort_Cloud_V2"] = true, + ["Asteroid_Mines_V2.1"] = true, + ["Cloud9_V2"] = true, + ["Iron_Isle_V1"] = true, + ["Nine_Metal_Islands_V1"] = true, + ["SpeedMetal BAR V2"] = true, +} +local isMetalMap = false + +------------------------------------------------------------ +-- Speedups +------------------------------------------------------------ +local min, max = math.min, math.max +local floor, ceil = math.floor, math.ceil +local sqrt = math.sqrt +local huge = math.huge + +local spGetGroundInfo = Spring.GetGroundInfo +local spGetGroundHeight = Spring.GetGroundHeight +local spTestBuildOrder = Spring.TestBuildOrder +local spSetGameRulesParam = Spring.SetGameRulesParam + +local extractorRadius = Game.extractorRadius +local extractorRadiusSqr = extractorRadius * extractorRadius + +local buildmapSizeX = Game.mapSizeX - squareSize +local buildmapSizeZ = Game.mapSizeZ - squareSize +local buildmapStartX = squareSize +local buildmapStartZ = squareSize + +local metalmapSizeX = Game.mapSizeX - 1.5 * metalMapSquareSize +local metalmapSizeZ = Game.mapSizeZ - 1.5 * metalMapSquareSize +local metalmapStartX = 1.5 * metalMapSquareSize +local metalmapStartZ = 1.5 * metalMapSquareSize + +local unitXoff = {} +local unitZoff = {} +for udefID, def in ipairs(UnitDefs) do + unitXoff[udefID] = (4 * def.xsize) % 16 + unitZoff[udefID] = (4 * def.zsize) % 16 +end + +local metalSpots +local geoSpots + +------------------------------------------------------------ +-- Find geothermal spots +------------------------------------------------------------ + +local function GetFootprintPos(value) -- not entirely acurate, unsure why + return (math.round(value / precision) * precision) +end + +local function getClosestGeo(x, z) + return math.getClosestPosition(x, z, geoSpots) +end + +local function GetSpotsGeo() + local geoFeatureDefs = {} + for defID, def in pairs(FeatureDefs) do + if def.geoThermal then + geoFeatureDefs[defID] = true + end + end + local spots = {} + local features = Spring.GetAllFeatures() + local spotCount = 0 + for i = 1, #features do + if geoFeatureDefs[Spring.GetFeatureDefID(features[i])] then + local x, y, z = Spring.GetFeaturePosition(features[i]) + spotCount = spotCount + 1 + spots[spotCount] = { + isGeo = true, + x = GetFootprintPos(x), + y = y, + z = GetFootprintPos(z), + minX = GetFootprintPos(x) - (precision / 2), + maxX = GetFootprintPos(x) + (precision / 2), + minZ = GetFootprintPos(z) - (precision / 2), + maxZ = GetFootprintPos(z) + (precision / 2), + } + end + end + return spots +end + +------------------------------------------------------------ +-- Shared functions +------------------------------------------------------------ + +local function GetValidStrips(spot) + local sMinZ, sMaxZ = spot.minZ, spot.maxZ + local sLeft, sRight = spot.left, spot.right + local validLeft = {} + local validRight = {} + local maxZOffset = squareSize * ceil(extractorRadius / squareSize - 1) + for mz = max(sMaxZ - maxZOffset, buildmapStartZ), min(sMinZ + maxZOffset, buildmapSizeZ), squareSize do + local vLeft, vRight = buildmapStartX, buildmapSizeX + if spot.left and spot.right then + for sz = sMinZ, sMaxZ, metalMapSquareSize do + local dz = sz - mz + local maxXOffset = squareSize * ceil(sqrt(extractorRadiusSqr - dz * dz) / squareSize - 1) -- Test for metal being included is dist < extractorRadius + local left, right = sRight[sz] - maxXOffset, sLeft[sz] + maxXOffset + if left > vLeft then + vLeft = left + end + if right < vRight then + vRight = right + end + end + end + validLeft[mz] = vLeft + validRight[mz] = vRight + end + spot.validLeft = validLeft + spot.validRight = validRight +end + + +local function GetBuildingPositions(spot, uDefID, facing, testBuild) + local xoff, zoff + if facing == 0 or facing == 2 then + xoff = unitXoff[uDefID] + zoff = unitZoff[uDefID] + else + xoff = unitZoff[uDefID] + zoff = unitXoff[uDefID] + end + + if not spot.validLeft then + GetValidStrips(spot) + end + + local positions = {} + local validLeft = spot.validLeft + local validRight = spot.validRight + for z, vLeft in pairs(validLeft) do + if z % 16 == zoff then + for x = metalMapSquareSize * ceil((vLeft + xoff) / metalMapSquareSize) - xoff, metalMapSquareSize * floor((validRight[z] + xoff) / metalMapSquareSize) - xoff, metalMapSquareSize do + local y = spGetGroundHeight(x, z) + if not (testBuild and spTestBuildOrder(uDefID, x, y, z, facing) == 0) then + positions[#positions + 1] = { x = x, y = y, z = z } + end + end + end + end + + return positions +end + + +local function IsBuildingPositionValid(spot, x, z) + -- add an extra mapSquareSize to account for snapping behaviours from api users + local expandedRadius = extractorRadius + metalMapSquareSize + if z <= spot.maxZ - expandedRadius or z >= spot.minZ + expandedRadius then -- Test for metal being included is dist < extractorRadius + return false + end + + local expandedRadiusSqr = expandedRadius*expandedRadius + local sLeft, sRight = spot.left, spot.right + for sz = spot.minZ, spot.maxZ, metalMapSquareSize do + local dz = sz - z + local maxXOffset = sqrt(expandedRadiusSqr - dz * dz) -- Test for metal being included is dist < extractorRadius + if x <= sRight[sz] - maxXOffset or x >= sLeft[sz] + maxXOffset then + return false + end + end + + return true +end + +------------------------------------------------------------ +-- Find metal spots +------------------------------------------------------------ + +local function setMexGameRules(spots) + -- Set gamerules values for mex spots, used by AI + if spots and #spots > 0 then + local mexCount = #spots + spSetGameRulesParam("mex_count", mexCount) + + for i = 1, mexCount do + local mex = spots[i] + spSetGameRulesParam("mex_x" .. i, mex.x) + spSetGameRulesParam("mex_y" .. i, mex.y) + spSetGameRulesParam("mex_z" .. i, mex.z) + spSetGameRulesParam("mex_metal" .. i, mex.worth) + end + else + Spring.SetGameRulesParam("mex_count", -1) + end +end + +---Returns the nearest mex spot to the given coordinates. Does not consider if the spot is taken +---@param x table +---@param z table +local function getClosestMex(x, z) + return math.getClosestPosition(x, z, metalSpots) +end + +local function GetSpotsMetal() + -- Main group collection + local uniqueGroups = {} + + -- Strip info + local nStrips = 0 + local stripLeft = {} + local stripRight = {} + local stripGroup = {} + local maxStripLength = extractorRadius * 6 + + -- Indexes + local aboveIdx + local workingIdx + + -- Strip processing function (To avoid some code duplication) + local function DoStrip(x1, x2, z, worth) + local assignedTo + + for i = aboveIdx, workingIdx - 1 do + if stripLeft[i] > x2 + metalMapSquareSize then + break + elseif stripRight[i] + metalMapSquareSize >= x1 then + local matchGroup = stripGroup[i] + if assignedTo then + if matchGroup ~= assignedTo then + for iz = matchGroup.minZ, assignedTo.minZ - metalMapSquareSize, metalMapSquareSize do + assignedTo.left[iz] = matchGroup.left[iz] + end + for iz = matchGroup.minZ, matchGroup.maxZ, metalMapSquareSize do + assignedTo.right[iz] = matchGroup.right[iz] + end + if matchGroup.minZ < assignedTo.minZ then + assignedTo.minZ = matchGroup.minZ + end + assignedTo.maxZ = z + assignedTo.worth = assignedTo.worth + matchGroup.worth + table.removeFirst(uniqueGroups, matchGroup) + end + else + assignedTo = matchGroup + assignedTo.left[z] = assignedTo.left[z] or x1 -- Only accept the first + assignedTo.right[z] = x2 -- Repeated overwrite gives us result we want + assignedTo.maxZ = z -- Repeated overwrite gives us result we want + assignedTo.worth = assignedTo.worth + worth + end + else + aboveIdx = aboveIdx + 1 + end + end + + nStrips = nStrips + 1 + stripLeft[nStrips] = x1 + stripRight[nStrips] = x2 + + if assignedTo then + stripGroup[nStrips] = assignedTo + else + local newGroup = { + left = { [z] = x1 }, + right = { [z] = x2 }, + minZ = z, + maxZ = z, + worth = worth, + } + stripGroup[nStrips] = newGroup + table.insert(uniqueGroups, newGroup) + end + end + + -- Strip finding + workingIdx = huge + for mz = metalmapStartX, metalmapSizeZ, metalMapSquareSize do + aboveIdx = workingIdx + workingIdx = nStrips + 1 + + local stripStart = nil + local stripWorth = 0 + + for mx = metalmapStartZ, metalmapSizeX, metalMapSquareSize do + local _, _, groundMetal = spGetGroundInfo(mx, mz) + if groundMetal > 0 then + stripStart = stripStart or mx + stripWorth = stripWorth + groundMetal + elseif stripStart then + DoStrip(stripStart, mx - metalMapSquareSize, mz, stripWorth) + stripStart = nil + stripWorth = 0 + end + end + + if stripStart then + DoStrip(stripStart, metalmapSizeX, mz, stripWorth) + end + end + + -- Final processing + local spots = {} + for _, g in ipairs(uniqueGroups) do + local gMinX, gMaxX = huge, -1 + local gLeft, gRight = g.left, g.right + for iz = g.minZ, g.maxZ, metalMapSquareSize do + if gLeft[iz] < gMinX then + gMinX = gLeft[iz] + end + if gRight[iz] > gMaxX then + gMaxX = gRight[iz] + end + end + g.minX = gMinX + g.maxX = gMaxX + + g.x = (gMinX + gMaxX) * 0.5 + g.z = (g.minZ + g.maxZ) * 0.5 + g.y = spGetGroundHeight(g.x, g.z) + + g.isMex = true + + spots[#spots + 1] = g + + if gMaxX - gMinX > maxStripLength or g.maxZ - g.minZ > maxStripLength then + return false, true + end + end + + --for i = 1, #spots do + -- Spring.MarkerAddPoint(spots[i].x,spots[i].y,spots[i].z,"") + --end + + return spots, false +end + + + +------------------------------------------------------------ +-- Callins +------------------------------------------------------------ + + + local initialized=false + return function() + if not initialized then + if metalMaps[Game.mapName] then + metalSpots, isMetalMap = false, true + else + metalSpots, isMetalMap = GetSpotsMetal() + end + + initialized=true + end + return isMetalMap,{isMetalMap=isMetalMap,metalSpotsList=metalSpots,GetBuildingPositions=GetBuildingPositions,IsMexPositionValid=IsBuildingPositionValid} + end +end)() +function WebbarOrderResourceSpots()local _,state=metalMapForOrder();return state end +local classifySelected=(function() + local mathMax=math.max +local mexConstructors = {} +local mexConstructorsDef = {} +local mexBuildings = {} + +local geoConstructors = {} +local geoConstructorsDef = {} +local geoBuildings = {} + +------------------------------------------------------------ +-- populate unit tables +------------------------------------------------------------ + +for uDefID, uDef in pairs(UnitDefs) do + if uDef.extractsMetal > 0 then + mexBuildings[uDefID] = uDef.extractsMetal + end + local customParams = uDef.customParams or {} + if customParams.geothermal then + geoBuildings[uDefID] = uDef.energyMake + end +end + +for uDefID, uDef in pairs(UnitDefs) do + if uDef.buildOptions then + local maxExtractMetal = 0 + local maxProduceEnergy = 0 + for _, option in ipairs(uDef.buildOptions) do + if mexBuildings[option] then + maxExtractMetal = mathMax(maxExtractMetal, mexBuildings[option]) + if mexConstructorsDef[uDefID] then + mexConstructorsDef[uDefID].buildings = mexConstructorsDef[uDefID].buildings + 1 + mexConstructorsDef[uDefID].building[mexConstructorsDef[uDefID].buildings] = option * -1 + else + mexConstructorsDef[uDefID] = { buildings = 1, building = { [1] = option * -1 } } + end + end + if geoBuildings[option] then + maxProduceEnergy = mathMax(maxProduceEnergy, geoBuildings[option]) + if geoConstructorsDef[uDefID] then + geoConstructorsDef[uDefID].buildings = geoConstructorsDef[uDefID].buildings + 1 + geoConstructorsDef[uDefID].building[geoConstructorsDef[uDefID].buildings] = option * -1 + else + geoConstructorsDef[uDefID] = { buildings = 1, building = { [1] = option * -1 } } + end + end + end + end +end + + local widget={} +function widget:UnitCreated(unitID, unitDefID) + if mexConstructorsDef[unitDefID] then + mexConstructors[unitID] = mexConstructorsDef[unitDefID] + end + if geoConstructorsDef[unitDefID] then + geoConstructors[unitID] = geoConstructorsDef[unitDefID] + end +end + + + WG.resource_spot_builder={GetMexConstructors=function()return mexConstructors end} + return function(ids) + mexConstructors={};geoConstructors={} + for _,id in ipairs(ids)do widget:UnitCreated(id,assert(Spring.GetUnitDefID(id)))end + end +end)() +local myAllyTeamID +local GetSpectatingState=Spring.GetSpectatingState +local GetSelectedUnits=Spring.GetSelectedUnits +local cmdQuickShareToTargetId = 455624 + +local widget={};local share=widget +function widget:CommandsChanged() + if GetSpectatingState() then + return + end + + local teams = Spring.GetTeamList(myAllyTeamID) + if not teams or #teams <= 1 then + return -- no allied teams to share to + end + + local selectedUnits = GetSelectedUnits() + if #selectedUnits > 0 then + local customCommands = widgetHandler.customCommands + customCommands[#customCommands + 1] = { + id = cmdQuickShareToTargetId, + type = CMDTYPE.ICON_UNIT_OR_MAP, + name = 'Share Unit To Target', + cursor = 'settarget', + action = 'quicksharetotarget', + } + end +end + + +local widget={};local mex=widget +local metalMap +function widget:SelectionChanged(sel) + selectedUnits = sel +end + + + +function widget:CommandsChanged() + if not metalMap then + if selectedUnits and #selectedUnits > 0 then + local customCommands = widgetHandler.customCommands + for i = 1, #selectedUnits do + if WG['resource_spot_builder'] and WG['resource_spot_builder'].GetMexConstructors()[selectedUnits[i]] then + customCommands[#customCommands + 1] = { + id = CMD_AREA_MEX, + type = CMDTYPE.ICON_AREA, + tooltip = 'Define an area (with metal spots in it) to make metal extractors in', + name = 'Mex', + cursor = 'areamex', + action = 'areamex', + } + return + end + end + end + end +end + + +widgetHandler.CommandsChangedList={share,mex} +widgetHandler.SelectionChangedList={mex} +function widgetHandler:CommandsChanged() + tracy.ZoneBeginN("W:CommandsChanged") + if widgetHandler:UpdateSelection() then + -- for selectionchanged + tracy.ZoneEnd() + return -- selection updated, don't call commands changed. + end + self.inCommandsChanged = true + self.customCommands = {} + for _, w in ipairs(self.CommandsChangedList) do + w:CommandsChanged() + end + self.inCommandsChanged = false + tracy.ZoneEnd() + return +end +local oldSelection = {} +function widgetHandler:UpdateSelection() + tracy.ZoneBeginN("W:UpdateSelection") + local changed + local newSelection = Spring.GetSelectedUnits() + if #newSelection == #oldSelection then + for i = 1, #oldSelection do + if newSelection[i] ~= oldSelection[i] then + -- it seems the order stays + changed = true + break + end + end + else + changed = true + end + if changed then + local subselection = true + if #newSelection > #oldSelection then + subselection = false + else + local oldSelectionMap = {} + for i = 1, #oldSelection do + oldSelectionMap[oldSelection[i]] = true + end + for i = 1, #newSelection do + if not oldSelectionMap[newSelection[i]] then + subselection = false + break + end + end + end + if widgetHandler:SelectionChanged(newSelection, subselection) then + -- selection changed, don't set old selection to new selection as it is soon to change. + tracy.ZoneEnd() + return true + end + end + oldSelection = newSelection + + tracy.ZoneEnd() + return false +end + +function widgetHandler:SelectionChanged(selectedUnits, subselection) + tracy.ZoneBeginN("W:SelectionChanged") + for _, w in ipairs(self.SelectionChangedList) do + local unitArray = w:SelectionChanged(selectedUnits, subselection) + if unitArray then + Spring.SelectUnitArray(unitArray) + tracy.ZoneEnd() + return true + end + end + tracy.ZoneEnd() + return false +end + +-------------------------------------------------------------------------------- +-------------------------------------------------------------------------------- +-- +-- file: layout.lua +-- brief: dummy and default LayoutButtons() routines +-- author: Dave Rodgers +-- +-- Copyright (C) 2007. +-- Licensed under the terms of the GNU GPL, v2 or later. +-- +-------------------------------------------------------------------------------- +-------------------------------------------------------------------------------- + +-------------------------------------------------------------------------------- +-------------------------------------------------------------------------------- +-- +-- ConfigLayoutHandler(data) is defined at the end of this file. +-- +-- data == true: use DummyLayoutHandler +-- data == func: use the provided function +-- data == nil: use Spring's default control panel +-- +-------------------------------------------------------------------------------- +-------------------------------------------------------------------------------- + +local function CopyTable(outtable,intable) + for i,v in pairs(intable) do + if (type(v)=='table') then + if (type(outtable[i])~='table') then + outtable[i] = {} + end + CopyTable(outtable[i],v) + else + outtable[i] = v + end + end +end + +-------------------------------------------------------------------------------- + +-- No longer used for UI, but necessary for custom commands to function properly +local function DummyLayoutHandler(xIcons, yIcons, cmdCount, commands) + widgetHandler.commands = commands + widgetHandler.commands.n = cmdCount + widgetHandler:CommandsChanged() + local reParamsCmds = {} + local customCmds = {} + local cnt = 0 + local AddCommand = function(command) + local cc = {} + CopyTable(cc,command ) + cnt = cnt + 1 + cc.cmdDescID = cmdCount+cnt + if (cc.params) then + if (not cc.actions) then --// workaround for params + local params = cc.params + for i=1,#params+1 do + params[i-1] = params[i] + end + cc.actions = params + end + reParamsCmds[cc.cmdDescID] = cc.params + end + --// remove api keys (custom keys are prohibited in the engine handler) + cc.pos = nil + cc.cmdDescID = nil + cc.params = nil + customCmds[#customCmds+1] = cc + end + --// preprocess the Custom Commands + for i=1,#widgetHandler.customCommands do + AddCommand(widgetHandler.customCommands[i]) + end + + if (cmdCount <= 0) then + return "", xIcons, yIcons, {}, customCmds, {}, {}, {}, {}, reParamsCmds, {} --prevent CommandChanged() from being called twice when deselecting all units (copied from ca_layout.lua) + end + + return "", xIcons, yIcons, {}, customCmds, {}, {}, {}, {}, reParamsCmds, {[1337]=9001} +end + + +function ConfigLayoutHandler(data) + if (type(data) == 'function') then + LayoutButtons = data + elseif (data == nil) then + LayoutButtons = nil + else + LayoutButtons = DummyLayoutHandler + end +end +LayoutButtons = DummyLayoutHandler + + +-- refresh, this prevents default engine buildmenu still showing up after a luaui reload +Spring.ForceLayoutUpdate() + + +function WebbarLayoutOrder(ids,commands) + selectedUnits=ids + myAllyTeamID=Spring.GetMyAllyTeamID() + metalMap=metalMapForOrder() + classifySelected(ids) + -- BAR's dummy layout deliberately hides the old engine icons. The native + -- parser then applies these eleven return values to the merged descriptors. + return LayoutButtons(4,4,#commands,commands) +end +end + +)WebbarOrderLua"; --- /dev/null +++ b/rts/Game/WebbarPipReadAdapter.h @@ -0,0 +1,1127 @@ +/* This file is part of the Spring engine (GPL v2 or later), see LICENSE.html */ +#pragma once +static constexpr const char* WEBBAR_PIP_READ_ADAPTER=R"PIP_READ( +do +local inputFactory=(function() +return function(native) +local Spring=assert(native.Spring) +local spFunc=Spring +local CMD,Game,GameCMD=assert(native.CMD),assert(native.Game),assert(native.GameCMD) +local WG,widgetHandler=assert(native.WG),assert(native.widgetHandler) +local os=native.os or os +local widget={} +local render,cameraState,interactionState,miscState,config,cache,uiState +local pools={cmdOpts={}} +local frameSel,frameSelCount +local cmdCursors = { + [CMD.ATTACK] = 'Attack', + [CMD.GUARD] = 'Guard', + [CMD.REPAIR] = 'Repair', + [CMD.RECLAIM] = 'Reclaim', + [CMD.CAPTURE] = 'Capture', + [CMD.RESURRECT] = 'Resurrect', + [CMD.RESTORE] = 'Restore', + [CMD.PATROL] = 'Patrol', + [CMD.FIGHT] = 'Fight', + [CMD.LOAD_UNITS] = 'Load units', + [CMD.UNLOAD_UNIT] = 'Unload units', + [CMD.UNLOAD_UNITS] = 'Unload units', + [CMD.DGUN] = 'Attack', -- DGun cursor doesnt work, use Attack instead + [GameCMD.UNIT_SET_TARGET_NO_GROUND] = 'settarget', +} + + + +-- What commands are issued at a position or unit/feature ID (Only used by GetUnitPosition) + +local function PipToWorldCoords(mx, my) + -- Get current minimap rotation (must fetch fresh, not use cached render.minimapRotation) + local minimapRotation = Spring.GetMiniMapRotation and Spring.GetMiniMapRotation() or 0 + + -- Convert screen coordinates to normalized PIP coordinates (0-1) + local normX = (mx - render.dim.l) / (render.dim.r - render.dim.l) + local normY = (my - render.dim.b) / (render.dim.t - render.dim.b) + + -- Apply inverse rotation if minimap is rotated + if minimapRotation ~= 0 then + -- Translate to center (0.5, 0.5) + local dx = normX - 0.5 + local dy = normY - 0.5 + + -- Rotate back (inverse rotation = negative angle) + local cosR = math.cos(-minimapRotation) + local sinR = math.sin(-minimapRotation) + local rotatedX = dx * cosR - dy * sinR + local rotatedY = dx * sinR + dy * cosR + + -- Translate back + normX = rotatedX + 0.5 + normY = rotatedY + 0.5 + end + + -- Convert normalized coordinates to world coordinates + return render.world.l + (render.world.r - render.world.l) * normX, + render.world.b + (render.world.t - render.world.b) * normY +end + +local function GetUnitAtPoint(wx, wz) + -- Calculate click radius based on current zoom + -- At high zoom (3D models), use a fixed tight radius; at low zoom, use distMult for easier clicking + local clickRadius + if cameraState.zoom > 0.9 then + -- High zoom: use a fixed small radius that doesn't scale with zoom + clickRadius = config.iconRadius * 0.4 + else + -- Low zoom: use distMult for easier clicking on small icons + local distMult = math.min(math.max(1, 2.2-(cameraState.zoom*3.3)), 3) + clickRadius = config.iconRadius * cameraState.zoom * distMult * 0.8 + end + + -- Determine which allyTeam's visibility to check + local checkAllyTeamID + if interactionState.trackingPlayerID and cameraState.mySpecState then + -- Tracking a player as spectator + local _, _, _, teamID = spFunc.GetPlayerInfo(interactionState.trackingPlayerID, false) + checkAllyTeamID = select(6, spFunc.GetTeamInfo(teamID, false)) + else + checkAllyTeamID = cameraState.myAllyTeamID + end + + local factoryID + local radarUnitID -- Store highest priority radar-only unit + + -- Iterate backwards to respect draw order (units drawn last are on top) + for i = #miscState.pipUnits, 1, -1 do + local uID = miscState.pipUnits[i] + local ux, uy, uz = spFunc.GetUnitPosition(uID) + if ux then + local uDefID = spFunc.GetUnitDefID(uID) + local dx, dz = ux - wx, uz - wz + + -- Use the calculated click radius or unit radius, whichever is larger + local unitClickRadius = clickRadius + if cache.unitIcon[uDefID] then + -- If unit has a custom icon, scale the click radius by its size + unitClickRadius = clickRadius * cache.unitIcon[uDefID].size + end + + -- Also consider the actual unit radius, use whichever is larger for easier clicking + local unitRadiusSq = cache.radiusSqs[uDefID] or (config.iconRadius*config.iconRadius) + local clickRadiusSq = math.max(unitClickRadius * unitClickRadius, unitRadiusSq) + + if dx*dx + dz*dz < clickRadiusSq then + -- Check if this unit is only visible via radar (not in LOS) + local losState = spFunc.GetUnitLosState(uID, checkAllyTeamID) + local isRadarOnly = losState and losState.radar and not losState.los + + if isRadarOnly then + -- Radar-only units have highest priority (drawn on top) + if not radarUnitID then + radarUnitID = uID + end + elseif cache.isFactory[uDefID] then + -- Factories have lower priority, remember but keep searching + if not factoryID then + factoryID = uID + end + else + -- Non-factory unit found, return immediately if we don't have a radar unit yet + if not radarUnitID then + return uID + end + end + end + end + end + + -- Return in priority order: radar units > regular units > factories + return radarUnitID or factoryID +end + + +local function GetFeatureAtPoint(wx, wz) + for i = 1, #miscState.pipFeatures do + local fID = miscState.pipFeatures[i] + local fx, fy, fz = spFunc.GetFeaturePosition(fID) + if fx then + local dx, dz = fx - wx, fz - wz + if dx*dx + dz*dz < cache.featureRadiusSqs[spFunc.GetFeatureDefID(fID)] then + return fID + end + end + end +end + + +local function GetIDAtPoint(wx, wz) + local uID = GetUnitAtPoint(wx, wz) + if uID then return uID end + local fID = GetFeatureAtPoint(wx, wz) + if fID then return fID + Game.maxUnits end +end + + +local function GetCmdOpts(alt, ctrl, meta, shift, right) + -- Reuse opts table + pools.cmdOpts.alt = alt + pools.cmdOpts.ctrl = ctrl + pools.cmdOpts.meta = meta + pools.cmdOpts.shift = shift + pools.cmdOpts.right = right + local coded = 0 + + if alt then coded = coded + CMD.OPT_ALT end + if ctrl then coded = coded + CMD.OPT_CTRL end + if meta then coded = coded + CMD.OPT_META end + if shift then coded = coded + CMD.OPT_SHIFT end + if right then coded = coded + CMD.OPT_RIGHT end + + pools.cmdOpts.coded = coded + return pools.cmdOpts +end + + +local function GiveNotifyingOrder(cmdID, cmdParams, cmdOpts) + + if widgetHandler:CommandNotify(cmdID, cmdParams, cmdOpts) then + return + end + + Spring.GiveOrder(cmdID, cmdParams, cmdOpts.coded) +end + + +local function CanTransportLoadUnit(transportUnitID, targetUnitID) + if not transportUnitID or not targetUnitID then + return false + end + + local transportDefID = spFunc.GetUnitDefID(transportUnitID) + local targetDefID = spFunc.GetUnitDefID(targetUnitID) + + if not transportDefID or not targetDefID then + return false + end + + -- Check if transport can carry units (using cache) + if not cache.isTransport[transportDefID] or (cache.transportCapacity[transportDefID] or 0) <= 0 then + return false + end + + -- Check if target can be transported (using cache) + if cache.cantBeTransported[targetDefID] then + return false + end + + -- Check transport size compatibility (using cache) + local transportSize = cache.transportSize[transportDefID] + local targetTransportSize = cache.unitTransportSize[targetDefID] + if transportSize and targetTransportSize then + if targetTransportSize > transportSize then + return false + end + end + + -- Check transport mass compatibility (using cache) + local transportMass = cache.transportMass[transportDefID] + local targetMass = cache.unitMass[targetDefID] + if transportMass and targetMass then + if targetMass > transportMass then + return false + end + end + + -- Check if transport can carry this type (minTransportSize) (using cache) + local minTransportSize = cache.minTransportSize[transportDefID] + if minTransportSize and targetTransportSize then + if targetTransportSize < minTransportSize then + return false + end + end + + return true +end + + +local function CanSelectedUnitsAttackTarget(selectedUnits, targetUnitID) + if not selectedUnits or not targetUnitID then + return false + end + + local targetDefID = spFunc.GetUnitDefID(targetUnitID) + if not targetDefID then + return false + end + + local targetIsEmpImmune = cache.unEmpableUnit[targetDefID] + for i = 1, #selectedUnits do + local unitDefID = spFunc.GetUnitDefID(selectedUnits[i]) + if unitDefID and cache.canAttack[unitDefID] then + if not targetIsEmpImmune or not cache.empOnlyAttacker[unitDefID] then + return true + end + end + end + + return false +end + + +local function IssueCommandAtPoint(cmdID, wx, wz, usingRMB, forceQueue, radius) + + local alt, ctrl, meta, shift = Spring.GetModKeyState() + -- Respect InvertQueueKey setting (same as customformations widget) + if Spring.GetInvertQueueKey() then + shift = not shift + end + -- Force queue commands when explicitly requested (e.g., during formation drags) + if forceQueue then + shift = true + end + local cmdOpts = GetCmdOpts(alt, ctrl, meta, shift, usingRMB) + + -- For build commands (negative cmdID), don't check for units at the position + -- We want to build AT the position, not command any unit that might be there + -- Also for PATROL and FIGHT, always target ground position instead of units + local id = nil + if cmdID > 0 and cmdID ~= CMD.PATROL and cmdID ~= CMD.FIGHT then + id = GetIDAtPoint(wx, wz) + + -- For ATTACK command, only target if it's an enemy unit + if id and cmdID == CMD.ATTACK then + if Spring.IsUnitAllied(id) then + id = nil -- Don't target allied units with ATTACK, use ground position instead + end + end + + -- For area RECLAIM command (radius > 0), don't target enemy units + if id and cmdID == CMD.RECLAIM and radius and radius > 0 then + if not Spring.IsUnitAllied(id) then + id = nil -- Don't target enemy units with area RECLAIM + end + end + + -- For area REPAIR command (radius > 0), don't target enemy units + if id and cmdID == CMD.REPAIR and radius and radius > 0 then + if not Spring.IsUnitAllied(id) then + id = nil -- Don't target enemy units with area REPAIR + end + end + end + + if id then + -- For LOAD_UNITS command, give order only to transport units + if cmdID == CMD.LOAD_UNITS then + local selectedUnits = Spring.GetSelectedUnits() + local transports = {} + + -- Collect all transport units (using cache) + for i = 1, #selectedUnits do + local unitDefID = spFunc.GetUnitDefID(selectedUnits[i]) + if unitDefID and cache.isTransport[unitDefID] and (cache.transportCapacity[unitDefID] or 0) > 0 then + transports[#transports + 1] = selectedUnits[i] + end + end if #transports > 0 then + -- If multiple transports, convert to area command so they load different units + if #transports > 1 then + local ux, uy, uz = spFunc.GetUnitPosition(id) + if ux then + -- Use a small radius area command so transports will find different nearby units + local smallRadius = 150 + for i = 1, #transports do + Spring.GiveOrderToUnit(transports[i], cmdID, {ux, uy, uz, smallRadius}, cmdOpts.coded) + end + end + else + -- Single transport, give direct unit target + Spring.GiveOrderToUnit(transports[1], cmdID, {id}, cmdOpts.coded) + end + end + else + GiveNotifyingOrder(cmdID, {id}, cmdOpts) + end + else + if cmdID > 0 then + -- For SET_TARGET command, only allow targeting units, not ground + local setTargetCmd = GameCMD and GameCMD.UNIT_SET_TARGET_NO_GROUND + if setTargetCmd and cmdID == setTargetCmd then + -- No unit found at target position, don't issue command + return + end + + -- Add radius for area commands if provided + if radius and radius > 0 then + -- For area LOAD_UNITS command, give order only to transport units individually + if cmdID == CMD.LOAD_UNITS then + local selectedUnits = Spring.GetSelectedUnits() + + -- Give order to each transport unit individually (using cache) + -- This allows the engine to distribute targets naturally across multiple transports + for i = 1, #selectedUnits do + local unitDefID = spFunc.GetUnitDefID(selectedUnits[i]) + if unitDefID and cache.isTransport[unitDefID] and (cache.transportCapacity[unitDefID] or 0) > 0 then + Spring.GiveOrderToUnit(selectedUnits[i], cmdID, {wx, spFunc.GetGroundHeight(wx, wz), wz, radius}, cmdOpts.coded) + end + end + else + GiveNotifyingOrder(cmdID, {wx, spFunc.GetGroundHeight(wx, wz), wz, radius}, cmdOpts) + end + else + GiveNotifyingOrder(cmdID, {wx, spFunc.GetGroundHeight(wx, wz), wz}, cmdOpts) + end + else + -- Build command - check if it's an extractor/geo that needs spot snapping + local buildDefID = -cmdID + local resourceSpotFinder = WG["resource_spot_finder"] + local resourceSpotBuilder = WG["resource_spot_builder"] + + if resourceSpotFinder and resourceSpotBuilder then + local mexBuildings = resourceSpotBuilder.GetMexBuildings() + local geoBuildings = resourceSpotBuilder.GetGeoBuildings() + local isMex = mexBuildings and mexBuildings[buildDefID] + local isGeo = geoBuildings and geoBuildings[buildDefID] + local metalMap = resourceSpotFinder.isMetalMap + + -- Handle extractor snapping (skip on metal maps for mexes) + if (isMex and not metalMap) or isGeo then + local spot + if isMex then + -- Find nearest unoccupied metal spot + local metalSpots = resourceSpotFinder.metalSpotsList + spot = resourceSpotBuilder.FindNearestValidSpotForExtractor(wx, wz, metalSpots, buildDefID) + else + -- Find nearest unoccupied geo spot + local geoSpots = resourceSpotFinder.geoSpotsList + spot = resourceSpotBuilder.FindNearestValidSpotForExtractor(wx, wz, geoSpots, buildDefID) + end + + if spot then + -- Use PreviewExtractorCommand to get proper build position + local pos = {wx, spFunc.GetGroundHeight(wx, wz), wz} + local cmd = resourceSpotBuilder.PreviewExtractorCommand(pos, buildDefID, spot) + + if cmd and #cmd > 0 then + -- Apply the command using ApplyPreviewCmds + local constructors = isMex and resourceSpotBuilder.GetMexConstructors() or resourceSpotBuilder.GetGeoConstructors() + resourceSpotBuilder.ApplyPreviewCmds({cmd}, constructors, shift) + return + end + end + -- If no valid spot found, don't build anything + return + end + end + + -- Regular building - just pass the position as-is (no additional snapping) + -- The position should already be snapped from CalculateBuildDragPositions + GiveNotifyingOrder(cmdID, {wx, spFunc.GetGroundHeight(wx, wz), wz, Spring.GetBuildFacing()}, cmdOpts) + end + end +end + +---------------------------------------------------------------------------------------------------- +-- Callins +---------------------------------------------------------------------------------------------------- + + +-- Register (or re-register) WG['minimap'] API for full compatibility with widgets +-- expecting the original minimap API. Called from Initialize and again from DrawScreen +-- when the standard Minimap widget is found active and needs to be disabled (its Initialize +-- may have overwritten our WG['minimap'] registration due to widget layer ordering). + +local function HandleHoverAndCursor(mx, my) + if interactionState.arePanning then + return + end + + if not (interactionState.areBoxSelecting or (mx >= render.dim.l and mx <= render.dim.r and my >= render.dim.b and my <= render.dim.t)) then + if WG['info'] and WG['info'].clearCustomHover then + WG['info'].clearCustomHover() + end + interactionState.lastHoveredUnitID = nil + interactionState.lastHoveredFeatureID = nil + return + end + + -- Throttle expensive GetUnitAtPoint calls for performance (but not during active zoom) + local currentTime = os.clock() + local shouldCheckUnit = (currentTime - interactionState.lastHoverCursorCheckTime) >= 0.1 + local isZooming = interactionState.areIncreasingZoom or interactionState.areDecreasingZoom + + if shouldCheckUnit and not isZooming then + interactionState.lastHoverCursorCheckTime = currentTime + + -- Update info widget with custom hover + if WG['info'] and WG['info'].setCustomHover then + local wx, wz = PipToWorldCoords(mx, my) + local uID = GetUnitAtPoint(wx, wz) + if uID then + WG['info'].setCustomHover('unit', uID) + interactionState.lastHoveredUnitID = uID + interactionState.lastHoveredFeatureID = nil + else + -- Only check features if zoom level is high enough to render them + if cameraState.zoom >= config.zoomFeatures then + local fID = GetFeatureAtPoint(wx, wz) + if fID then + WG['info'].setCustomHover('feature', fID) + interactionState.lastHoveredFeatureID = fID + interactionState.lastHoveredUnitID = nil + else + WG['info'].clearCustomHover() + interactionState.lastHoveredUnitID = nil + interactionState.lastHoveredFeatureID = nil + end + else + WG['info'].clearCustomHover() + interactionState.lastHoveredUnitID = nil + interactionState.lastHoveredFeatureID = nil + end + end + end + end + + -- Handle cursor - this runs every frame for smooth cursor updates + -- Don't change cursor for spectators (unless config allows it) + local isSpec = Spring.GetSpectatingState() + local canGiveCommands = not isSpec or config.allowCommandsWhenSpectating + local lastHoveredUnitID = interactionState.lastHoveredUnitID + if canGiveCommands then + local _, activeCmdID = Spring.GetActiveCommand() + if not activeCmdID then + local defaultCmd = Spring.GetDefaultCommand() + + if not defaultCmd or defaultCmd == 0 then + if frameSelCount > 0 then + if not frameSel then frameSel = Spring.GetSelectedUnits() end + local selectedUnits = frameSel + -- Check if hovering over an enemy unit with units that can attack + -- But don't show attack cursor for neutral units + if lastHoveredUnitID and not Spring.IsUnitAllied(lastHoveredUnitID) then + local allyTeam = Spring.GetUnitAllyTeam(lastHoveredUnitID) + local isNeutral = (allyTeam == cache.gaiaAllyTeamID) + + -- Check if unit is visible (LOS or radar) + local checkAllyTeamID = cameraState.myAllyTeamID + if interactionState.trackingPlayerID and cameraState.mySpecState then + local _, _, _, teamID = spFunc.GetPlayerInfo(interactionState.trackingPlayerID, false) + checkAllyTeamID = select(6, spFunc.GetTeamInfo(teamID, false)) + end + local losState = spFunc.GetUnitLosState(lastHoveredUnitID, checkAllyTeamID) + local isVisibleOrRadar = losState and (losState.los or losState.radar) + + if not isNeutral and isVisibleOrRadar then + if CanSelectedUnitsAttackTarget(selectedUnits, lastHoveredUnitID) then + Spring.SetMouseCursor('Attack') + return + end + end + end + + -- Check if we have a transport and are hovering over a transportable unit + -- Use cached result from throttled check above + if lastHoveredUnitID and Spring.IsUnitAllied(lastHoveredUnitID) then + -- Check if any transport in selection can load this unit + for i = 1, #selectedUnits do + if CanTransportLoadUnit(selectedUnits[i], lastHoveredUnitID) then + Spring.SetMouseCursor('Load') + return + end + end + end + + -- Default to Move cursor if units can move (using cache) + for i = 1, #selectedUnits do + local uDefID = spFunc.GetUnitDefID(selectedUnits[i]) + if uDefID and (cache.canMove[uDefID] or cache.canFly[uDefID]) then + Spring.SetMouseCursor('Move') + return + end + end + end + elseif defaultCmd == CMD.ATTACK and lastHoveredUnitID and not Spring.IsUnitAllied(lastHoveredUnitID) then + -- Hovering over enemy unit with units that can attack + if not frameSel then frameSel = Spring.GetSelectedUnits() end + if CanSelectedUnitsAttackTarget(frameSel, lastHoveredUnitID) then + Spring.SetMouseCursor('Attack') + return + end + end + else + local cursorName = cmdCursors[activeCmdID] + if cursorName then + Spring.SetMouseCursor(cursorName) + end + end + end +end + +-- Helper function to draw interactive overlays (buttons, pip number, etc.) + +function widget:DefaultCommand() + if uiState.inMinMode then return end + local mx, my = spFunc.GetMouseState() + if mx >= render.dim.l and mx <= render.dim.r and my >= render.dim.b and my <= render.dim.t then + local wx, wz = PipToWorldCoords(mx, my) + local uID = GetUnitAtPoint(wx, wz) + if uID then + if Spring.IsUnitAllied(uID) then + return CMD.GUARD + else + if CanSelectedUnitsAttackTarget(Spring.GetSelectedUnits(), uID) then + return CMD.ATTACK + end + return CMD.MOVE + end + end + local fID = GetFeatureAtPoint(wx, wz) + if fID then + return CMD.RECLAIM + end + return CMD.MOVE + end +end + + +return { + state=function(value) + -- These are native-held original widget tables. The engine host must build + -- them from pinned defaults/definitions and native visibility, never accept + -- arbitrary unit lists, radii, capabilities or targets from the page. + render=assert(value.render);cameraState=assert(value.cameraState) + interactionState=assert(value.interactionState);miscState=assert(value.miscState) + config=assert(value.config);cache=assert(value.cache);uiState=assert(value.uiState) + end, + position=PipToWorldCoords,unit=GetUnitAtPoint,feature=GetFeatureAtPoint,id=GetIDAtPoint, + canLoad=CanTransportLoadUnit,canAttack=CanSelectedUnitsAttackTarget, + options=GetCmdOpts,issue=IssueCommandAtPoint, + hover=function(mx,my) + frameSel=nil;frameSelCount=Spring.GetSelectedUnitsCount() + return HandleHoverAndCursor(mx,my) + end, + default=function()return widget:DefaultCommand()end, +} +end + +end)() +local stateFactory=(function() +return function(native) +local Spring=assert(native.Spring) +local UnitDefs,WeaponDefs,FeatureDefs=assert(native.UnitDefs),assert(native.WeaponDefs),assert(native.FeatureDefs) +local GameCMD=assert(native.GameCMD) +local isMinimapMode=true +local config +config = { + -- UI colors and sizing + panelBorderColorLight = {0.75, 0.75, 0.75, 1}, + panelBorderColorDark = {0.2, 0.2, 0.2, 1}, + minPanelSize = 330, + maxPanelSizeVsy = 0.4, -- Maximum size as fraction of vertical screen resolution + buttonSize = 50, + + -- Zoom settings + zoomWheel = 1.22, + zoomRate = 15, + zoomSmoothness = 10, + centerSmoothness = 15, + trackingSmoothness = 8, + playerTrackingSmoothness = 4.5, + switchSmoothness = 30, + zoomMin = 0.04, + zoomMax = 2, + zoomFeatures = 0.2, + zoomFeaturesFadeRange = 0.06, -- Zoom range over which features fade in/out + zoomProjectileDetail = 0.12, + zoomExplosionDetail = 0.12, -- Legacy, now using graduated visibility + drawExplosions = true, -- Separate from projectiles + drawPlasmaTrails = true, -- Show fading trails behind plasma/artillery projectiles + trailSkipThreshold = 100, -- Skip missile/plasma trails when drawn projectile count exceeds this (0 = never skip) + projectileScanBudget = 600, -- Max projectile IDs inspected per PIP refresh under projectile spam + iconCosmeticSkipThreshold = 800, -- Skip health/stun cosmetic API calls above this visible icon count + iconPosRefreshThreshold = 4000, -- Cache mobile unit positions above this count (refresh 1/3 per frame) + iconSortSkipThreshold = 800, -- Skip mobile icon z-sort above this visible icon count + iconGhostSkipThreshold = 6000, -- Skip ghost building pass above this count + iconMobileBlockThreshold = 5000, -- Cache mobile VBO data above this count (rebuild every 2nd frame) + explosionOverlay = true, -- Re-render explosions on top of unit icons (additive glow) + explosionOverlayAlpha = 0.66, -- Strength of the above-icons explosion overlay (0-1) + healthDarkenMax = 0.2, -- Maximum darkening for damaged units on GL4 icons (0-1, 0.18 = 18%) + activityFocusIgnoreSpectators = true, -- Don't trigger camera focus for spectator map markers + activityFocusHideForSpectators = true, -- Hide the activity focus button when spectating (default: disabled for spectators) + activityFocusDuration = 0.25, -- Seconds to hold focus on a marker before restoring camera + activityFocusZoomInTime = 1.75, -- Seconds for the zoom-in transition (smoothstep ease-in-out) + activityFocusZoomOutTime = 1.3, -- Seconds for the zoom-out transition (smoothstep ease-in-out) + activityFocusZoom = 0.15, -- Zoom level when focusing on a marker (higher = more zoomed in) + activityFocusShowMinimap = true, -- Temporarily show pip-minimap overlay while focused on a map marker + activityFocusBlockIgnoredPlayers = true, -- Completely block activity focus for players on your ignore list (WG.ignoredAccounts) + activityFocusCooldown = 3, -- Minimum seconds between focus triggers from the same player + activityFocusThrottleWindow = 10, -- Time window (seconds) to count markers from a player + activityFocusThrottleCount = 3, -- After this many markers in the window, ignore that player temporarily + activityFocusThrottleDuration = 15, -- Seconds to ignore a throttled player + activityFocusMuteCount = 6, -- After this many markers in the window, mute that player entirely + activityFocusMuteDuration = 60, -- Seconds to mute a heavily spamming player + -- TV mode settings (spectator auto-camera) + tvModeSpectatorsOnly = true, -- Only allow TV mode for spectators + tvMaxZoom = 0.63, -- Maximum zoom level for TV mode (never close enough for unitpics) + tvMinZoom = 0.08, -- Minimum zoom level for TV overview shots + tvOverviewZoom = 0.07, -- Zoom level for periodic overview shots (wider view of the map) + tvCloseupZoom = 0.45, -- Zoom level for close-up action shots + tvFocusDuration = 6.0, -- Base seconds to hold focus on a hotspot before considering switch + tvOverviewDuration = 2.5, -- Seconds to hold an overview shot + tvOverviewInterval = 18, -- Seconds between periodic overview shots + tvSwitchCooldown = 3.5, -- Minimum seconds between camera switches + tvEventDecayTime = 12, -- Seconds for events to fully decay + tvHotspotRadius = 800, -- World units: events within this distance merge into one hotspot + tvMaxEvents = 200, -- Max tracked events (ring buffer) + tvVarietyBonus = 0.3, -- Weight bonus for unvisited areas (0-1) + tvPanSpeed = 3.0, -- Camera pan smoothness (higher = faster convergence) + tvZoomSpeed = 2.5, -- Camera zoom smoothness + tvUnitFinishedCostThreshold = 800, -- Minimum unit cost to trigger a "big unit finished" event + + iconDensityScaling = true, -- Reduce icon sizes when unit count is high (prevents overlap at zoomed-out levels) + iconDensityMaxUnits = 18000, -- Unit count at which maximum reduction is reached + iconDensityMinScale = 0.5, -- Minimum icon scale at max unit count (0.5 = 50% size) + iconDensityZoomFadeStart = 0.3, -- Zoom level above which density scaling starts fading out (1.0 = fully zoomed in) + iconDensityZoomFadeEnd = 0.8, -- Zoom level above which density scaling is completely off + + drawDecals = true, -- Show ground decals (explosion scars, footprints) from the decals GL4 widget + drawCommandFX = Spring.GetConfigInt("PipDrawCommandFX", 1) == 1, -- Show brief fading command lines when orders are given (like Commands FX widget) + commandFXIgnoreNewUnits = true, -- Ignore commands given to newly finished units (rally point orders) + commandFXOpacity = 0.2, -- Initial opacity of command FX lines + commandFXDuration = 0.66, -- Seconds for command FX lines to fully fade out + queuedBuildDrawLimit = 100, -- Max queued building icons drawn per PIP refresh + queuedBuildDenseDrawLimit = 24, -- Max queued building icons drawn in dense visible-unit views + queuedBuildMinZoom = 0.18, -- Hide queued build icons when zoomed out below this + + -- Feature and overlay settings + hideEnergyOnlyFeatures = false, + hideUnreclaimableFeatures = true, + showLosOverlay = true, + showLosRadar = true, + losOverlayOpacity = 0.6, + allowCommandsWhenSpectating = false, -- Allow giving commands as spectator when god mode is enabled + + -- Rendering settings + iconRadius = 40, + showUnitpics = true, -- Show unitpics instead of icons when zoomed in + unitpicZoomThreshold = 0.75, -- Zoom level at which to switch to unitpics (higher = more zoomed in) + unitpicMaxUnits = 180, -- Keep dense views on GL4 icons; unitpics use immediate-mode draw calls per unit + unitpicWarmupRange = 0.12, -- Start warming buildpic textures shortly before the unitpic threshold + unitpicWarmupPerFrame = 6, -- Hard cap in addition to the time budget below + unitpicWarmupTimeBudget = 0.004, -- Best-effort budget; one synchronous texture bind can overrun it + drawComNametags = true, -- Draw player names above commander icons + comNametagZoomThreshold = 0.18, -- Minimum zoom to show nametags (below this they'd overlap) + drawComHealthBars = true, -- Draw health bars below commander icons when health < 99% + leftButtonPansCamera = isMinimapMode and (Spring.GetConfigInt("MinimapLeftClickMove", 1) == 1) or false, + maximizeSizemult = 1.25, + screenMargin = 0.00, + drawProjectiles = true, + zoomToCursor = true, + altKeyRequiredForZoom = Spring.GetConfigInt("PipAltKeyRequiredForZoom", 1) == 1, -- When true, scrolling over the PIP only zooms if ALT is held (otherwise passes through to the game) + mapEdgeMargin = 0, + showButtonsOnHoverOnly = true, + switchInheritsTracking = false, + switchTransitionTime = 0.15, + showMapRuler = false, + cancelPlayerTrackingOnPan = true, -- Cancel player camera tracking when trying to pan or ALT+drag + showTrackedPlayerCursor = true, -- Show tracked player's ally cursor overlay while tracking player camera + playerCursorScale = 1.0, -- Scale multiplier for tracked player cursor size + trackedPlayerCursorGroundGlow = true, -- Draw tracked cursor as a simple radial ground glow under units + showTrackedPlayerAllyTeamCursors = false, -- Also draw ally cursors in the tracked player's allyteam + pipMinimapCorner = 3, -- Corner for pip minimap: 1=bottom-left, 2=bottom-right, 3=top-left, 4=top-right + minimapHeightPercent = 0.12, -- Minimap height as percent of PIP height (maintains aspect ratio) + minimapHoverHeightPercent = 0.15, -- Minimap height when hovering over PIP + + -- Performance settings + showPipFps = false, + showPipTimers = false, -- Echo per-section timing breakdown to Spring.Echo (debug) + contentResolutionScale = 2, -- Render texture at this multiple of PIP size (1 = 1:1, 2 = 2x resolution for (marginally) sharper content) + smoothCameraMargin = 0.05, -- Oversized texture margin for expensive layers (units, features, projectiles) + smoothCameraMarginCheap = 0.15, -- Oversized texture margin for cheap layers (ground, water, LOS) — larger since rendering is cheap + pipFloorUpdateRate = 10, -- Minimum update rate for PIP content when performance is poor (will be smoothly applied based on measured frame times) + pipMinUpdateRate = 30, -- Minimum update rate for PIP content when zoomed out + pipMaxUpdateRate = 60, -- Maximum update rate for PIP content when zoomed in + pipZoomThresholdMin = 0.15, + pipZoomThresholdMax = 0.4, + pipTargetDrawTime = 0.0025, + pipPerformanceAdjustSpeed = 0.1, -- Exponential smoothing factor (0-1) for the performance rate-limiter. Each frame, contentPerformanceFactor lerps toward its target by this fraction: higher = faster reaction to GPU load spikes, lower = smoother but slower adaptation. + pipFrameTimeThreshold = 0.007, -- threshold before starting to lower FPS + pipFrameTimeHistorySize = 10, -- Number of frames to average + + CMD_AREA_MEX = GameCMD and GameCMD.AREA_MEX or 10000, + + -- Middle-click teleport settings (click without drag moves world camera to clicked position) + middleClickTeleport = true, -- Enable middle-click to teleport world camera + middleClickZoomMin = 0.2, -- Maximum zoom in for teleport (lower = more zoomed in) + middleClickZoomMax = 0.95, -- Maximum zoom out for teleport (higher = more zoomed out) + middleClickZoomOffset = -0.18, -- Teleport slightly more zoomed out than PIP (0 = same as PIP) + minimapMiddleClickZoomMin = 0.2, -- auto zoom in to this zoom level + minimapMiddleClickZoomMax = 0.95, -- auto zoom out to this zoom level + + -- Minimap mode settings (when pipNumber == 0) + minimapModeMaxHeight = Spring.GetConfigFloat("MinimapMaxHeight", 0.32), -- Shared with gui_minimap.lua via ConfigFloat + minimapModeMaxWidth = 0.25, -- Max width as fraction of screen width + minimapModeScreenMargin = 0, -- No margin in minimap mode (edge-to-edge) + minimapModeShowButtons = false, -- Hide buttons in minimap mode + minimapModeShowMinimizeButton = false, -- Show the minimize/maximize button on the pip-as-minimap (default off) + minimapModeStartMinimized = false, -- Don't start minimized in minimap mode + minimapModeHideMoveResize = true, -- Hide move and resize buttons in minimap mode + autoMaximizeOnGameStart = false, -- Automatically maximize PIP when the game starts (players only, not spectators) + hideAICommands = true, -- Hide command queues from AI players (default: enabled) + showSpectatorPings = true, -- Show map pings from spectators on the PIP minimap + showViewRectangleOnMinimap = false, -- Show the PIP view rectangle on the engine minimap + showViewRectangleInWorld = false, -- Show the PIP view rectangle as an outline in the 3D world + engineMinimapFallback = true, -- Use engine minimap when fully zoomed out (performance fallback) + engineMinimapFallbackThreshold = 4000, -- Unit count threshold before engine minimap fallback activates + engineMinimapExplosionOverlay = true, -- Draw explosion overlay on top of engine minimap + engineMinimapDecalStrength = 0.8, -- Decal overlay strength on engine minimap (0-1, lower = subtler scorch marks) decals do overlap with the engine minimap (unit icons), so this can be used to reduce their prominence if desired +} + + +local cache = { + noModelFeatures = {}, + unreclaimableFeatures = {}, + xsizes = {}, + zsizes = {}, + unitIcon = {}, + unitPic = {}, -- Unit picture paths for detailed view + isFactory = {}, + radiusSqs = {}, + featureRadiusSqs = {}, + projectileSizes = {}, + explosions = {}, + laserBeams = {}, + iconShatters = {}, + seismicPings = {}, + -- Transport-related properties + isTransport = {}, + transportCapacity = {}, + transportSize = {}, + transportMass = {}, + minTransportSize = {}, + cantBeTransported = {}, + unitMass = {}, + unitTransportSize = {}, + -- Movement properties + canMove = {}, + canFly = {}, + isBuilding = {}, + isPseudoBuilding = {}, -- speed==0 units that aren't isBuilding (nano turrets, transportable turrets) + isCritter = {}, -- gaia wildlife units (name starts with "critter") + isCommander = {}, + isDecoyCommander = {}, -- Commanders with customParams.decoyfor (show 'Decoy' instead of player name) + isScavCommander = {}, -- Scavenger commanders (show scav-specific name for decoys) + unitCost = {}, + -- Combat properties + canAttack = {}, + empOnlyAttacker = {}, + unEmpableUnit = {}, + isAirAttacker = {}, -- Air units with ground/sea attack weapons (bombers, gunships) + isExpensiveEco = {}, -- Non-commander buildings with cost >= 1000 (T2 mexes, fusions, etc.) + maxIconShatters = 4, + weaponIsLaser = {}, + weaponIsBlaster = {}, + weaponIsPlasma = {}, + weaponIsMissile = {}, + weaponIsStarburst = {}, + weaponIsLightning = {}, + weaponIsFlame = {}, + flameLifetime = {}, -- [wDefID] = seconds, estimated particle lifetime for flame weapons + flameBirthTime = {}, -- [pID] = gameTime, when we first saw this flame particle + flameSeeds = {}, -- [pID] = {offX, offZ, baseSize, v1, v2, v3} — stable per-particle variation + weaponIsBomb = {}, + weaponIsParalyze = {}, + weaponIsAA = {}, + weaponIsJuno = {}, + weaponIsTorpedo = {}, + missileTrails = {}, -- Stores trail positions for missiles {[pID] = {positions = {{x,z,time},...}, lastUpdate = time}} + missileColors = {}, -- [wDefID] = {bodyR,bodyG,bodyB, noseR,noseG,noseB, finR,finG,finB, exhR,exhG,exhB} + plasmaTrails = {}, -- Stores trail positions for plasma/artillery projectiles (simpler, shorter trails) + weaponPlasmaTrailColor = {}, -- {r, g, b} per wDefID, based on cegTag + weaponSize = {}, + weaponRange = {}, + weaponThickness = {}, + weaponColor = {}, + weaponExplosionRadius = {}, + weaponSkipExplosion = {}, + weaponExplosionDim = {}, -- [wDefID] = 0..1 dimming multiplier for rapid-fire/flame weapon explosions +} + +local gl4Icons={unitDefLayer={}, + LAYER_STRUCTURE = 0, -- structures drawn first (bottom) + LAYER_GROUND = 1, -- ground mobile units + LAYER_AIR = 2, -- air units above ground + LAYER_COMMANDER = 3, -- commanders drawn last (top, above air) +} +local VFS={Include=function(path)assert(path=='gamedata/icontypes.lua');return assert(native.iconTypes)end} + local iconTypes = VFS.Include("gamedata/icontypes.lua") + for uDefID, uDef in pairs(UnitDefs) do + cache.xsizes[uDefID] = uDef.xsize * 4 + cache.zsizes[uDefID] = uDef.zsize * 4 + cache.radiusSqs[uDefID] = uDef.radius * uDef.radius + if uDef.isFactory then + cache.isFactory[uDefID] = true + end + if uDef.iconType and iconTypes[uDef.iconType] and iconTypes[uDef.iconType].bitmap then + cache.unitIcon[uDefID] = iconTypes[uDef.iconType] + end + -- Cache unitpic path using engine's #unitDefID syntax (handles all buildpic variations automatically) + cache.unitPic[uDefID] = '#' .. uDefID + + -- Cache transport properties + if uDef.isTransport then + cache.isTransport[uDefID] = true + cache.transportCapacity[uDefID] = uDef.transportCapacity or 0 + cache.transportSize[uDefID] = uDef.transportSize + cache.transportMass[uDefID] = uDef.transportMass + cache.minTransportSize[uDefID] = uDef.minTransportSize + end + if uDef.cantBeTransported then + cache.cantBeTransported[uDefID] = true + end + cache.unitMass[uDefID] = uDef.mass + cache.unitTransportSize[uDefID] = uDef.transportSize + + -- Cache movement properties + if uDef.canMove then + cache.canMove[uDefID] = true + end + if uDef.canFly then + cache.canFly[uDefID] = true + end + if uDef.isBuilding then + cache.isBuilding[uDefID] = true + elseif uDef.speed == 0 and not uDef.canFly then + cache.isPseudoBuilding[uDefID] = true + end + if string.sub(uDef.name, 1, 7) == "critter" then + cache.isCritter[uDefID] = true + end + if uDef.customParams and (uDef.customParams.iscommander or uDef.customParams.isdecoycommander or uDef.customParams.isscavcommander or uDef.customParams.isscavdecoycommander) then + cache.isCommander[uDefID] = true + if uDef.customParams.decoyfor then + cache.isDecoyCommander[uDefID] = true + end + if uDef.customParams.isscavcommander or uDef.customParams.isscavdecoycommander then + cache.isScavCommander[uDefID] = true + end + end + cache.unitCost[uDefID] = uDef.metalCost + uDef.energyCost / 60 + + -- Pre-compute icon draw layer for GL4 rendering (determines render order) + if uDef.canFly then + gl4Icons.unitDefLayer[uDefID] = gl4Icons.LAYER_AIR + elseif uDef.customParams and (uDef.customParams.iscommander or uDef.customParams.isdecoycommander or uDef.customParams.isscavcommander or uDef.customParams.isscavdecoycommander) then + gl4Icons.unitDefLayer[uDefID] = gl4Icons.LAYER_COMMANDER + elseif uDef.isBuilding or (uDef.speed == 0 and not uDef.canFly) then + gl4Icons.unitDefLayer[uDefID] = gl4Icons.LAYER_STRUCTURE + else + gl4Icons.unitDefLayer[uDefID] = gl4Icons.LAYER_GROUND + end + + -- Cache combat properties + local hasGroundAttack = false + local isEmpOnlyAttacker = false + if uDef.weapons and #uDef.weapons > 0 then + isEmpOnlyAttacker = true + for _, weapon in ipairs(uDef.weapons) do + local weaponDef = WeaponDefs[weapon.weaponDef] + if not (weaponDef and weaponDef.paralyzer) then + isEmpOnlyAttacker = false + break + end + end + end + if isEmpOnlyAttacker then + cache.empOnlyAttacker[uDefID] = true + end + if not (uDef.modCategories and uDef.modCategories.empable) then + cache.unEmpableUnit[uDefID] = true + end + if uDef.weapons and #uDef.weapons > 0 then + -- Check if unit has any non-shield weapons + for _, weapon in ipairs(uDef.weapons) do + local weaponDef = WeaponDefs[weapon.weaponDef] + if weaponDef and not weaponDef.isShield then + cache.canAttack[uDefID] = true + -- Check if this weapon can hit ground/sea targets (for air attacker detection) + if not weaponDef.onlyTargets then + hasGroundAttack = true + elseif weaponDef.onlyTargets and not weaponDef.onlyTargets.vtol then + hasGroundAttack = true + end + break + end + end + end + -- Air attacker: flying unit that can hit ground units (bombers, gunships, strike fighters) + if uDef.canFly and hasGroundAttack then + cache.isAirAttacker[uDefID] = true + end + -- Expensive eco building: non-commander building with high cost (T2+ mex, fusion, etc.) + local unitCost = cache.unitCost[uDefID] or 0 + if uDef.isBuilding and unitCost >= 1000 and not (uDef.customParams and uDef.customParams.iscommander) then + cache.isExpensiveEco[uDefID] = true + end + end + + for fDefID, fDef in pairs(FeatureDefs) do + if fDef.modelname == '' then + cache.noModelFeatures[fDefID] = true + end + if fDef.reclaimable ~= nil and not fDef.reclaimable then + cache.unreclaimableFeatures[fDefID] = true + end + local fx, fz = 8 * fDef.xsize, 8 * fDef.zsize + cache.featureRadiusSqs[fDefID] = fx*fx + fz*fz + end + + +local gaiaTeamID = Spring.GetGaiaTeamID() +cache.gaiaAllyTeamID = select(6, Spring.GetTeamInfo(gaiaTeamID)) +return {config=config,cache=cache,unitDefLayer=gl4Icons.unitDefLayer} +end + +end)() +local GameCMD=(function() +-------------------------------------------------------------------------------- +-- +-- Proposed Command ID Ranges: +-- +-- all negative: Engine (build commands) +-- 0 - 999: Engine +-- 1000 - 9999: Group AI +-- 10000 - 19999: LuaUI +-- 20000 - 29999: LuaCob +-- 30000 - 39999: LuaRules +-- + +-- if you add a command, please order it by ID! + +local gameCommands = { + FACTORY_GUARD = 13921, + AREA_GUARD = 13922, -- unused + STOP_PRODUCTION = 13923, + + -- blueprint + BLUEPRINT_PLACE = 18200, + BLUEPRINT_CREATE = 18201, + + -- quota + QUOTA_BUILD_TOGGLE = 23000, + + AREA_MEX = 30100, + SELL_UNIT = 30101, + + CARRIER_SPAWN_ONOFF = 31200, + MORPH = 31210, + USER_FIRESTATE = 31300, + MANUAL_LAUNCH = 32102, + UNIT_SET_TARGET_NO_GROUND = 34922, -- unit_target_on_the_move + UNIT_SET_TARGET = 34923, + UNIT_CANCEL_TARGET = 34924, + UNIT_SET_TARGET_RECTANGLE = 34925, + LAND_AT = 34569, + PRIORITY = 34571, + WANT_CLOAK = 37382, + HOUND_WEAPON_TOGGLE = 37383, -- unused + SMART_TOGGLE = 37384, + AREA_ATTACK_GROUND = 39954, + + -- terraform + RAW_MOVE = 39812, +} + +local globalCmdDeprecatedShown = false + +local importCommandsToObject = function(object) + if not globalCmdDeprecatedShown and not object.gadgetHandler then + local msg = 'Should not use customcmds.h.lua or importCommandsToObject. Use the CMD table directly, or read modules/customcommands.lua for more information.' + Spring.Log('CMD', LOG.DEPRECATED, msg) + globalCmdDeprecatedShown = true + end + for code, cmdID in pairs(gameCommands) do + if type(code) == 'string' then + object['CMD_' .. code] = cmdID + end + end + +end + +for code, cmdID in pairs(gameCommands) do + if CMD[cmdID] then + Spring.Log('CMD', LOG.ERROR, 'Duplicate command id: ' .. code .. ' ' .. tostring(cmdID) .. '!') + end + if CMD[code] then + Spring.Log('CMD', LOG.ERROR, 'Duplicate command code: ' .. code .. ' ' .. tostring(cmdID) .. '!') + end + gameCommands[cmdID] = code +end + +local getCommandCode = function(cmdID) + return CMD[cmdID] or gameCommands[cmdID] +end + +return { + GameCMD = gameCommands, + ImportCommandsToObject = importCommandsToObject, + GetCommandCode = getCommandCode, + } + +end)().GameCMD +local CMD=assert(CMD) +local originalSpring=Spring +local selected,view,active,base,now={},nil,nil,nil,0 +local cursor,hover +local interaction={lastHoverCursorCheckTime=0} +local features={} +local context +local Spring=setmetatable({ + GetSelectedUnits=function()return selected end, + GetSelectedUnitsCount=function()return #selected end, + GetMiniMapRotation=function()return view.rotation end, + GetMouseState=function()return view.x,view.y,false,false,false end, + GetActiveCommand=function()if active then return active.index,active.id end;return 0 end, + -- The original C++ GUI chooses this index for the PIP LuaUI receiver. Keep + -- that native result, including the Lua API's command-index offset. + GetDefaultCommand=function()return base.defaultIndex end, + SetMouseCursor=function(name,scale)cursor={name=name,scale=scale or 1}end, + GiveOrder=function()error('Read-only PIP host cannot dispatch commands')end, + GiveOrderToUnit=function()error('Read-only PIP host cannot dispatch commands')end, +},{__index=originalSpring}) +local defaults=stateFactory({Spring=Spring,UnitDefs=UnitDefs,WeaponDefs=WeaponDefs,FeatureDefs=FeatureDefs,GameCMD=GameCMD,iconTypes=webbarInfoIconTypes}) +local input=inputFactory({Spring=Spring,CMD=CMD,Game=Game,GameCMD=GameCMD,os={clock=function()return now end}, + WG={info={setCustomHover=function(kind,id)hover={kind=kind,id=id}end,clearCustomHover=function()hover={kind='clear'}end}}, + widgetHandler={CommandNotify=function()error('Read-only PIP host cannot notify commands')end}}) +function WebbarReadPip(ids,geometry,descriptor,nativeCursor,seconds) + selected=ids;view=geometry;active=descriptor;base=nativeCursor;now=seconds + local identity=tostring(originalSpring.GetMyTeamID())..'/'..tostring(originalSpring.GetMyAllyTeamID())..'/'..tostring(originalSpring.GetSpectatingState()) + if context~=identity then interaction={lastHoverCursorCheckTime=0};features={};hover=nil;context=identity end + -- The stock draw path supplies this same visibility-filtered rectangle list + -- to picking. Never substitute a browser's visible units or model radii. + local units=originalSpring.GetUnitsInRectangle(view.l-220,view.t-220,view.r+220,view.b+220) + if view.zoom>=defaults.config.zoomFeatures then features=originalSpring.GetFeaturesInRectangle(view.l-220,view.t-220,view.r+220,view.b+220)end + input.state({render={dim={l=0,b=0,r=view.width,t=view.height},world={l=view.l,r=view.r,b=view.b,t=view.t}}, + cameraState={zoom=view.zoom,myAllyTeamID=originalSpring.GetMyAllyTeamID(),mySpecState=originalSpring.GetSpectatingState()}, + interactionState=interaction,miscState={pipUnits=units,pipFeatures=features},config=defaults.config,cache=defaults.cache,uiState={inMinMode=false}}) + cursor={name=base.name,scale=base.scale} + input.hover(view.x,view.y) + local info + if type(WebbarReadInfoWorld)=='function' then + -- This is the independent read handle's private Spring table. Supply the + -- original Info reader with the original PIP's native hit, then restore its + -- camera trace even if a native read fails. No game/global camera is changed. + local trace=originalSpring.TraceScreenRay + originalSpring.TraceScreenRay=function() + if hover and hover.kind~='clear' then return hover.kind,hover.id end + end + local ok,value=pcall(WebbarReadInfoWorld,selected,0,{view.x,view.y,false,false,false,false,false}) + originalSpring.TraceScreenRay=trace + if not ok then error(value)end + info=value + if hover and hover.kind~='clear' then info.world.customHover={kind=hover.kind,id=hover.id}end + end + return {selected=selected,cursor=cursor,hover=hover or{kind='clear'},mouse={view.x,view.y},defaultCommand=input.default(),info=info} +end +end + +)PIP_READ"; --- /dev/null +++ b/rts/Game/WebbarPlayerReadAdapter.h @@ -0,0 +1,2953 @@ +/* This file is part of the Spring engine (GPL v2 or later), see LICENSE.html */ +#pragma once +static constexpr const char* WEBBAR_PLAYER_READ_ADAPTER=R"WBAR_PLAYERS( +do +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 + +local playerUtilities=(function() + local VFS={Include=function(path)assert(path=='common/holidays.lua');return(function() +if not Spring.GetModOptions then + return +end + +if not Spring.GetModOptions().holiday_events then + return +end + +local modOptions = Spring.GetModOptions() +local currentDay = modOptions.date_day +local currentMonth = modOptions.date_month +local currentYear = modOptions.date_year + +-- Meeus's Julian algorithm Function to calculate Easter Sunday for a given year. Magic. +local function EasterDate(year) + local a = year % 19 + local b = math.floor(year / 100) + local c = year % 100 + local d = math.floor(b / 4) + local e = b % 4 + local f = math.floor((b + 8) / 25) + local g = math.floor((b - f + 1) / 3) + local h = (19 * a + b - d - g + 15) % 30 + local i = math.floor(c / 4) + local k = c % 4 + local l = (32 + 2 * e + 2 * i - h - k) % 7 + local m = math.floor((a + 11 * h + 22 * l) / 451) + local month = math.floor((h + l - 7 * m + 114) / 31) + local day = ((h + l - 7 * m + 114) % 31) + 1 + + return year, month, day +end + +local function GetEasterStartEnd() + local easterYear, easterMonth, easterDay = EasterDate(currentYear) + local firstDay = easterDay - 6 -- We start at Monday before Easter + local firstMonth = easterMonth + local lastDay = easterDay + 1 -- We end at Monday after Easter + local lastMonth = easterMonth + + if easterMonth%2 == 0 then -- Easter is in April - 30 days month + if firstDay < 1 then + firstDay = firstDay + 31 + firstMonth = firstMonth - 1 + end + if lastDay > 30 then + lastDay = lastDay - 30 + lastMonth = lastMonth + 1 + end + + else -- Easter is in March or May - 31 days month + if firstDay < 1 then + firstDay = firstDay + 30 + firstMonth = firstMonth - 1 + end + if lastDay > 31 then + lastDay = lastDay - 31 + lastMonth = lastMonth + 1 + end + end + + return { + firstDay = firstDay, + firstMonth = firstMonth, + lastDay = lastDay, + lastMonth = lastMonth, + easterDay = easterDay, + easterMonth = easterMonth, + } +end + +local EasterEventDates = GetEasterStartEnd() + +-- FIXME: This doesn't support events that start and end in different years. Don't do that for now. Split it into two events if you have to do that. + +-- Spring.Utilities.Gametype.GetCurrentHolidays()["aprilfools"] + +local holidaysList = { + -- Static ----------------------------- + ["aprilfools"] = { + firstDay = { day = 1, month = 4}, + lastDay = { day = 7, month = 4} + }, + ["aprilfools_specialDay"] = { + firstDay = { day = 1, month = 4}, + lastDay = { day = 1, month = 4} + }, + + ["halloween"] = { + firstDay = { day = 17, month = 10}, + lastDay = { day = 31, month = 10} + }, + ["halloween_specialDay"] = { + firstDay = { day = 31, month = 10}, + lastDay = { day = 31, month = 10} + }, + + ["xmas"] = { + firstDay = { day = 12, month = 12}, + lastDay = { day = 31, month = 12} + }, + ["xmas_specialDay"] = { + firstDay = { day = 24, month = 12}, + lastDay = { day = 26, month = 12} + }, + + -- We split these into two events because yes + ["newyearbefore"] = { + firstDay = { day = 31, month = 12}, + lastDay = { day = 31, month = 12} + }, + ["newyearafter"] = { + firstDay = { day = 1, month = 1}, + lastDay = { day = 1, month = 1} + }, + + -- Dynamic ----------------------------- + ["easter"] = { + firstDay = { day = EasterEventDates.firstDay, month = EasterEventDates.firstMonth}, + lastDay = { day = EasterEventDates.lastDay, month = EasterEventDates.lastMonth} + }, + ["easter_specialDay"] = { + firstDay = { day = EasterEventDates.easterDay, month = EasterEventDates.easterMonth}, + lastDay = { day = EasterEventDates.easterDay, month = EasterEventDates.easterMonth} + }, +} + +return holidaysList +end)()end} + local smallTeamThreshold = 4 +local initialized = false +local settings = { } + +local holidaysList = VFS.Include("common/holidays.lua") + +local function getSettings() + if initialized then + return settings + end + + local allyTeamCount, playerCount = 0, 0 + local isSinglePlayer, is1v1, isTeams, isBigTeams, isSmallTeams, isRaptors, isScavengers, isPvE, isCoop, isFFA, isSandbox = false, false, false, false, false, false, false, false, false, false, false + local scavTeamID, scavAllyTeamID, raptorTeamID, raptorAllyTeamID + local isHoliday = {} + + local gaiaAllyTeamID = select(6, Spring.GetTeamInfo(Spring.GetGaiaTeamID(), false)) + local springAllyTeamList = Spring.GetAllyTeamList() + local allyTeamList = {} + local allyTeamSizes = {} + local entirelyHumanAllyTeams = {} + + for _, allyTeamID in ipairs(springAllyTeamList) do + local teamList = Spring.GetTeamList(allyTeamID) or {} + local allyteamEntirelyHuman = true + + if #teamList > 0 and allyTeamID ~= gaiaAllyTeamID then + local isAllyTeamValid = true + + for _, teamID in ipairs(teamList) do + if select (4, Spring.GetTeamInfo(teamID, false)) then + allyteamEntirelyHuman = false + else + local teamPlayers = Spring.GetPlayerList(teamID) + for _, playerID in ipairs(teamPlayers) do + playerCount = playerCount + 1 + end + end + + local luaAI = Spring.GetTeamLuaAI(teamID) + + if luaAI then + if luaAI:find("Raptors") then + isRaptors = true + isAllyTeamValid = false + raptorTeamID = teamID + raptorAllyTeamID = allyTeamID + elseif luaAI:find("Scavengers") then + isScavengers = true + isAllyTeamValid = false + scavTeamID = teamID + scavAllyTeamID = allyTeamID + end + end + end + + if isAllyTeamValid then + allyTeamList[#allyTeamList+1] = allyTeamID + allyTeamSizes[#allyTeamSizes+1] = #teamList + end + + if allyteamEntirelyHuman then + entirelyHumanAllyTeams[#entirelyHumanAllyTeams+1] = allyTeamID + end + end + end + + allyTeamCount = #allyTeamList + + isSmallTeams = true + for _, teamSize in ipairs(allyTeamSizes) do + if teamSize > 1 then + isTeams = true + end + + isSmallTeams = isSmallTeams and teamSize <= smallTeamThreshold + end + + isSinglePlayer = playerCount == 1 + isSmallTeams = isTeams and isSmallTeams + isBigTeams = isTeams and not isSmallTeams + isPvE = isRaptors or isScavengers + + if allyTeamCount > 2 then + isFFA = true + elseif allyTeamCount < 2 and not isPvE then + isSandbox = true + elseif allyTeamCount == 2 and not isTeams then + is1v1 = true + end + + if #entirelyHumanAllyTeams == 1 and #Spring.GetTeamList(entirelyHumanAllyTeams[1]) > 1 then + isCoop = true + end + + if holidaysList and Spring.GetModOptions and Spring.GetModOptions().date_day then + local currentDay = Spring.GetModOptions().date_day + local currentMonth = Spring.GetModOptions().date_month + local currentYear = Spring.GetModOptions().date_year + + -- FIXME: This doesn't support events that start and end in different years. + for holiday, dates in pairs(holidaysList) do + local afterStart = false + local beforeEnd = false + if (dates.firstDay.month == currentMonth and dates.firstDay.day <= currentDay) or (dates.firstDay.month < currentMonth) then + afterStart = true + end + if (dates.lastDay.month == currentMonth and dates.lastDay.day >= currentDay) or (dates.lastDay.month > currentMonth) then + beforeEnd = true + end + + if afterStart and beforeEnd then + isHoliday[holiday] = true + else + isHoliday[holiday] = false + end + end + end + + initialized = true + + settings = { + allyTeamCount = allyTeamCount, + allyTeamList = allyTeamList, + playerCount = playerCount, + isSinglePlayer = isSinglePlayer, + is1v1 = is1v1, + isTeams = isTeams, + isBigTeams = isBigTeams, + isSmallTeams = isSmallTeams, + isRaptors = isRaptors, + isScavengers = isScavengers, + isPvE = isPvE, + isCoop = isCoop, + isFFA = isFFA, + isSandbox = isSandbox, + scavTeamID = scavTeamID, + scavAllyTeamID = scavAllyTeamID, + raptorTeamID = raptorTeamID, + raptorAllyTeamID = raptorAllyTeamID, + isHoliday = isHoliday, + } + + return settings +end + +return { + ---Get number of ally teams (humans and AIs, but not Raptors and Scavengers). + GetAllyTeamCount = function() return getSettings().allyTeamCount end, + ---Get ally team list (humans and AIs, but not Raptors and Scavengers). + ---@return integer[] allyTeamList table[i] = allyTeamID + GetAllyTeamList = function () return getSettings().allyTeamList end, + ---@return integer? playerCount Get number of players in a game, nil If it's an AI only game. + GetPlayerCount = function () return getSettings().playerCount end, + Gametype = { + ---@return boolean + IsSinglePlayer = function () return getSettings().isSinglePlayer end, + ---@return boolean + Is1v1 = function () return getSettings().is1v1 end, + ---@return boolean + IsTeams = function () return getSettings().isTeams end, + ---@return boolean + IsBigTeams = function () return getSettings().isBigTeams end, + ---@return boolean + IsSmallTeams = function () return getSettings().isSmallTeams end, + ---@return boolean + IsRaptors = function () return getSettings().isRaptors end, + ---@return boolean + IsScavengers = function () return getSettings().isScavengers end, + ---@return boolean + IsPvE = function () return getSettings().isPvE end, + ---@return boolean + IsCoop = function () return getSettings().isCoop end, + ---@return boolean + IsFFA = function () return getSettings().isFFA end, + ---@return boolean + IsSandbox = function () return getSettings().isSandbox end, + ---@return table? isHoliday Currently running holiday events. + ---See common/holidays.lua for more information. + GetCurrentHolidays = function () return getSettings().isHoliday end, + }, + ---@return integer? scavTeamID Team ID for the scavenger team. + GetScavTeamID = function () return getSettings().scavTeamID end, + ---@return integer? scavAllyTeamID Team ID for the scavenger ally team. + GetScavAllyTeamID = function () return getSettings().scavAllyTeamID end, + ---@return integer? raptorTeamID Team ID for the raptor team. + GetRaptorTeamID = function () return getSettings().raptorTeamID end, + ---@return integer? raptorAllyTeamID Team ID for the raptor ally team. + GetRaptorAllyTeamID = function () return getSettings().raptorAllyTeamID end, + +} + +end)() +-- Read-only inputs for the original AdvPlayersList. The native handle's +-- current read team/full-view policy remains the authority for every getter. +-- Missing native values stay missing, including holes in returned tuples. +-- SPDX-License-Identifier: GPL-2.0-or-later +local function tuple(...) + return {n=select('#',...),...} +end +local function ids(list,label) + assert(type(list)=='table'and #list<=256,'Invalid native player-list '..label) + local seen={} + for _,id in ipairs(list)do + assert(type(id)=='number'and id%1==0 and id>=0 and id<256 and not seen[id],'Invalid native player-list '..label..' ID') + seen[id]=true + end + return list +end +local function playerLists(team) + return {all=ids(Spring.GetPlayerList(team),'players'),active=ids(Spring.GetPlayerList(team,true),'active players'),includingInactive=ids(Spring.GetPlayerList(team,false),'all players')} +end +function WebbarReadPlayers() + local options=Spring.GetModOptions() + local out={ + frame=Spring.GetGameFrame(),seconds=Spring.GetGameSeconds(), + localTeam=Spring.GetLocalTeamID(),localAllyTeam=Spring.GetLocalAllyTeamID(),localPlayer=Spring.GetLocalPlayerID(),gaia=Spring.GetGaiaTeamID(), + spectating=tuple(Spring.GetSpectatingState()),modOptions={teamcolors_anonymous_mode=options.teamcolors_anonymous_mode,tax_resource_sharing_amount=options.tax_resource_sharing_amount,easytax=options.easytax,fixedallies=options.fixedallies}, + teamOrder=ids(Spring.GetTeamList(),'teams'),allyOrder=ids(Spring.GetAllyTeamList(),'alliances'),playerOrder=ids(Spring.GetPlayerList(),'players'), + teams={},players={},allyTeams={},gameRules={},definitions={}, + gameType={singlePlayer=playerUtilities.Gametype.IsSinglePlayer(),pve=playerUtilities.Gametype.IsPvE(),ffa=playerUtilities.Gametype.IsFFA()}, + } + out.playerLists=playerLists(-1) + for _,ally in ipairs(out.allyOrder)do out.allyTeams[ally]=ids(Spring.GetTeamList(ally),'alliance teams')end + for _,team in ipairs(out.teamOrder)do + local range=Spring.GetTeamStatsHistory(team) + local row={ + info=tuple(Spring.GetTeamInfo(team,false)),color=tuple(Spring.GetTeamColor(team)),ai=tuple(Spring.GetAIInfo(team)),luaAI=Spring.GetTeamLuaAI(team), + players=playerLists(team),units=Spring.GetTeamUnitCount(team), + resources={metal=tuple(Spring.GetTeamResources(team,'metal')),energy=tuple(Spring.GetTeamResources(team,'energy'))}, + rules={startUnit=Spring.GetTeamRulesParam(team,'startUnit'),mmLevel=Spring.GetTeamRulesParam(team,'mmLevel'),numActivePlayers=Spring.GetTeamRulesParam(team,'numActivePlayers')}, + stats={range=range,history=range and Spring.GetTeamStatsHistory(team,range)or nil}, + } + out.teams[team]=row + out.gameRules['ainame_'..team]=Spring.GetGameRulesParam('ainame_'..team) + -- AdvPlayersList also addresses its absent/AI rows as team+specOffset. + out.gameRules['Player'..team..'willSub']=Spring.GetGameRulesParam('Player'..team..'willSub') + end + for _,player in ipairs(out.playerOrder)do + out.players[player]={info=tuple(Spring.GetPlayerInfo(player)),withoutOptions=tuple(Spring.GetPlayerInfo(player,false))} + for _,name in ipairs({'player_'..player..'_readyState','Player'..player..'willSub'})do out.gameRules[name]=Spring.GetGameRulesParam(name)end + end + for _,name in ipairs({'armcom','corcom','legcom'})do local def=UnitDefNames[name];if def then out.definitions[name]={id=def.id}end end + return out +end + +end + +)WBAR_PLAYERS"; --- a/rts/Game/WebbarPoses.h +++ b/rts/Game/WebbarPoses.h @@ -59,7 +59,7 @@ static_assert(offsetof(Header, extensionMagic) == 232); static_assert(sizeof(Header) == 352); constexpr uint32_t HEADER_BYTES = 384, SLOT_HEADER_BYTES = 32; -constexpr uint32_t EXTENSION_MAGIC = 0x31584257, FEATURE_BOUNDS = 1, FEATURE_REFLECTION = 2, FEATURE_NATIVE_TRS = 4, FEATURE_NATIVE_DRAW_TIMING = 8, FEATURE_NATIVE_PROPERTIES = 16, FEATURE_NATIVE_COUPLED = 32, FEATURE_NATIVE_CLOAK_TIMING = 64; +constexpr uint32_t EXTENSION_MAGIC = 0x31584257, FEATURE_BOUNDS = 1, FEATURE_REFLECTION = 2, FEATURE_NATIVE_TRS = 4, FEATURE_NATIVE_DRAW_TIMING = 8, FEATURE_NATIVE_PROPERTIES = 16, FEATURE_NATIVE_COUPLED = 32, FEATURE_NATIVE_CLOAK_TIMING = 64, FEATURE_NATIVE_LIFETIME = 128, FEATURE_NATIVE_SENSOR_POSITION = 256; constexpr uint8_t FLAG_ROTATION = 1, FLAG_CULLED = 2, FLAG_LOD = 4, FLAG_RESET = 8, FLAG_STRUCTURE = 16, FLAG_NATIVE_BOUNDS = 32, FLAG_NATIVE_TRS = 64, FLAG_NATIVE_PROPERTIES = 128; struct PieceState { float raw[7]; uint32_t visible; float m[12]; int32_t first; bool dirty; }; @@ -105,6 +105,7 @@ Header* h = reinterpret_cast(memory); h->magic = 0x314d5057; h->version = 1; h->middle = 1; h->slotCapacity = next; h->extensionMagic = EXTENSION_MAGIC; h->supportedFeatures = FEATURE_BOUNDS | FEATURE_REFLECTION | FEATURE_NATIVE_TRS | FEATURE_NATIVE_DRAW_TIMING | FEATURE_NATIVE_PROPERTIES | FEATURE_NATIVE_COUPLED | FEATURE_NATIVE_CLOAK_TIMING; + if (std::getenv("WEBBAR_NATIVE_SENSOR_GROUPS") || std::getenv("WEBBAR_NATIVE_ATTACK_RANGES")) h->supportedFeatures |= FEATURE_NATIVE_LIFETIME | FEATURE_NATIVE_SENSOR_POSITION; for (int i = 0; i < 3; ++i) h->slotOffset[i] = HEADER_BYTES + i * next; if (header != nullptr) { // Keep the page's acknowledgement, camera and statistics across the switch. --- /dev/null +++ b/rts/Game/WebbarScumEvents.h @@ -0,0 +1,29 @@ +/* This file is part of the Spring engine (GPL v2 or later), see LICENSE.html */ +#pragma once +#include +#include +#include +#include "lib/lua/include/LuaInclude.h" +// Observe only the original two public scum messages. Never change either Lua +// stack, a synced value, RNG, call-in result, watch flag or engine unit state. +namespace WebbarScumEvents { +using Listener=void(*)(void*,lua_State*,lua_State*,int); +inline Listener listener=nullptr; +inline void* owner=nullptr; +inline void Attach(void* next,Listener callback){assert(owner==nullptr);owner=next;listener=callback;} +inline void Detach(void* previous){if(owner==previous){listener=nullptr;owner=nullptr;}} +inline void Observe(lua_State* source,lua_State* unsynced,int args){ + if(!listener||(args!=2&&args!=7)||lua_type(source,1)!=LUA_TSTRING)return; + const char* name=lua_tostring(source,1); + const bool created=std::strcmp(name,"ScumCreated")==0; + if((!created&&std::strcmp(name,"ScumRemoved")!=0)||args!=(created?7:2))return; + for(int i=2;i<=args;++i){ + if(lua_type(source,i)!=LUA_TNUMBER)return; + const float value=lua_tonumber(source,i); + if(!std::isfinite(value)||std::abs(value)>16777216.0f)return; + if(i==args&&(value<0||value>65535||std::floor(value)!=value))return; + if(created&&i==4&&value<=0)return; + } + listener(owner,source,unsynced,args); +} +} --- a/rts/Game/WebbarWorld.h +++ b/rts/Game/WebbarWorld.h @@ -2,37 +2,34 @@ #pragma once #include "WebbarInfoTexture.h" -// Low-frequency, read-only UI data. Hidden enemies never enter the unit, pose, -// feature or queue streams. Radar contacts contain positions, not unit identity. -static void PublishWebbarWorld() -{ - if (!webbarStateRefresh && gs->frameNum % 15 != 0) return; - PublishWebbarGeothermal(); - { - // Native wind for smoke drift (CSmokeProjectile / CGeoThermSmokeProjectile). - const float3& wind = envResHandler.GetCurrentWindVec(); - MAIN_THREAD_EM_ASM({ if (Module['webbarWind']) Module['webbarWind']($0, $1, $2, $3, $4); }, gs->frameNum, wind.x, wind.y, wind.z, envResHandler.GetCurrentWindStrength()); - } - PublishWebbarBuildRestrictions(); - constexpr uint32_t grid = 256; - std::vector contacts; - for (const CUnit* unit: unitHandler.GetActiveUnits()) - if (!WebbarVisible(unit) && losHandler->InRadar(unit, gu->myAllyTeam)) contacts.push_back(unit->GetErrorPos(gu->myAllyTeam)); - const bool infoGlobal = gu->spectatingFullView || losHandler->GetGlobalLOS(gu->myAllyTeam); - const auto infoPlane = [&](const auto& type) { return WebbarInfoTexture::Binary(type.size.x, type.size.y, type.losMaps[gu->myAllyTeam].GetLosMap(), infoGlobal); }; - const auto nativeInfo = WebbarInfoTexture::Packet(infoPlane(losHandler->los), infoPlane(losHandler->airLos), infoPlane(losHandler->radar), losHandler->jammer.losMaps[modInfo.separateJammers ? gu->myAllyTeam : 0].GetLosMap(), infoGlobal); - const uint32_t visionHeader[] = {0x31564257, uint32_t(gs->frameNum), grid, uint32_t(contacts.size()), uint32_t(mapDims.mapx * SQUARE_SIZE), uint32_t(mapDims.mapy * SQUARE_SIZE), nativeInfo.empty() ? 0 : WebbarInfoTexture::MAGIC, uint32_t(nativeInfo.size())}; - std::vector vision(sizeof(visionHeader) + grid * grid + contacts.size() * sizeof(float3) + nativeInfo.size()); - std::memcpy(vision.data(), visionHeader, sizeof(visionHeader)); - for (uint32_t z = 0; z < grid; ++z) for (uint32_t x = 0; x < grid; ++x) { - const float px = (x + 0.5f) * visionHeader[4] / grid, pz = (z + 0.5f) * visionHeader[5] / grid; - const float3 pos(px, CGround::GetHeightReal(px, pz), pz); - vision[sizeof(visionHeader) + z * grid + x] = gu->spectatingFullView ? 3 : ((losHandler->InLos(pos, gu->myAllyTeam) ? 1 : 0) | (losHandler->InRadar(pos, gu->myAllyTeam) ? 2 : 0)); - } - std::memcpy(vision.data() + sizeof(visionHeader) + grid * grid, contacts.data(), contacts.size() * sizeof(float3)); - if (!nativeInfo.empty()) std::memcpy(vision.data() + sizeof(visionHeader) + grid * grid + contacts.size() * sizeof(float3), nativeInfo.data(), nativeInfo.size()); - MAIN_THREAD_EM_ASM({ if (Module['webbarVision']) Module['webbarVision'](HEAPU8.slice($0, $0 + $1).buffer); }, vision.data(), vision.size()); +/* This file is part of the Spring engine (GPL v2 or later), see LICENSE.html */ +#include +// Event-only invalidation of the existing public feature snapshot. No Lua, +// commands, simulation writes or new visibility/packet rules are introduced. +class WebbarFeatureStreamEvents final: public CEventClient { +public: + bool dirty = true; + std::array view{-2,-2,-2}; + WebbarFeatureStreamEvents(): CEventClient("WebBAR public feature changes",LUA_HANDLE_ORDER_UI+1,false) { eventHandler.AddClient(this); } + bool GetFullRead() const override { return true; } + bool WantsEvent(const std::string& name) override { return name == "FeatureCreated" || name == "FeatureDestroyed" || name == "FeatureMoved"; } + void Changed(const CFeature* feature) { + // Hidden activity must not cause a new publication. Admission is the same + // current native feature LOS test as the existing snapshot below. + if (feature && (gu->spectatingFullView || (teamHandler.IsValidAllyTeam(gu->myAllyTeam) && feature->IsInLosForAllyTeam(gu->myAllyTeam)))) dirty = true; + } + void FeatureCreated(const CFeature* feature) override { Changed(feature); } + void FeatureDestroyed(const CFeature* feature) override { Changed(feature); } + void FeatureMoved(const CFeature* feature,const float3&) override { Changed(feature); } + void ObserveView() { + const std::array actual{gu->myTeam,gu->myAllyTeam,int(gu->spectatingFullView)}; + if (actual != view) { view = actual; dirty = true; } + } +}; +static WebbarFeatureStreamEvents& GetWebbarFeatureStream() { static WebbarFeatureStreamEvents events; return events; } +static void PublishWebbarFeatures() +{ struct FeatureRecord { uint32_t id, def; float metal, energy, reclaim; float matrix[16]; }; static_assert(sizeof(FeatureRecord) == 84); std::vector features; @@ -65,6 +62,47 @@ std::memcpy(featurePacket.data() + sizeof(featureHeader), features.data(), features.size() * sizeof(FeatureRecord)); MAIN_THREAD_EM_ASM({ if (Module['webbarFeatures']) Module['webbarFeatures'](HEAPU8.slice($0, $0 + $1).buffer); }, featurePacket.data(), featurePacket.size()); + GetWebbarFeatureStream().dirty = false; +} +static void PublishChangedWebbarFeatures() +{ + auto& events = GetWebbarFeatureStream(); events.ObserveView(); + if (events.dirty) PublishWebbarFeatures(); +} + +// Low-frequency, read-only UI data. Hidden enemies never enter the unit, pose, +// feature or queue streams. Radar contacts contain positions, not unit identity. +static void PublishWebbarWorld() +{ + if (!webbarStateRefresh && gs->frameNum % 15 != 0) return; + PublishWebbarGeothermal(); + { + // Native wind for smoke drift (CSmokeProjectile / CGeoThermSmokeProjectile). + const float3& wind = envResHandler.GetCurrentWindVec(); + MAIN_THREAD_EM_ASM({ if (Module['webbarWind']) Module['webbarWind']($0, $1, $2, $3, $4); }, gs->frameNum, wind.x, wind.y, wind.z, envResHandler.GetCurrentWindStrength()); + } + PublishWebbarBuildRestrictions(); + constexpr uint32_t grid = 256; + std::vector contacts; + for (const CUnit* unit: unitHandler.GetActiveUnits()) + if (!WebbarVisible(unit) && losHandler->InRadar(unit, gu->myAllyTeam)) contacts.push_back(unit->GetErrorPos(gu->myAllyTeam)); + const bool infoGlobal = gu->spectatingFullView || losHandler->GetGlobalLOS(gu->myAllyTeam); + const auto infoPlane = [&](const auto& type) { return WebbarInfoTexture::Binary(type.size.x, type.size.y, type.losMaps[gu->myAllyTeam].GetLosMap(), infoGlobal); }; + const auto nativeInfo = WebbarInfoTexture::Packet(infoPlane(losHandler->los), infoPlane(losHandler->airLos), infoPlane(losHandler->radar), losHandler->jammer.losMaps[modInfo.separateJammers ? gu->myAllyTeam : 0].GetLosMap(), infoGlobal); + const uint32_t visionHeader[] = {0x31564257, uint32_t(gs->frameNum), grid, uint32_t(contacts.size()), uint32_t(mapDims.mapx * SQUARE_SIZE), uint32_t(mapDims.mapy * SQUARE_SIZE), nativeInfo.empty() ? 0 : WebbarInfoTexture::MAGIC, uint32_t(nativeInfo.size())}; + std::vector vision(sizeof(visionHeader) + grid * grid + contacts.size() * sizeof(float3) + nativeInfo.size()); + std::memcpy(vision.data(), visionHeader, sizeof(visionHeader)); + for (uint32_t z = 0; z < grid; ++z) for (uint32_t x = 0; x < grid; ++x) { + const float px = (x + 0.5f) * visionHeader[4] / grid, pz = (z + 0.5f) * visionHeader[5] / grid; + const float3 pos(px, CGround::GetHeightReal(px, pz), pz); + vision[sizeof(visionHeader) + z * grid + x] = gu->spectatingFullView ? 3 : ((losHandler->InLos(pos, gu->myAllyTeam) ? 1 : 0) | (losHandler->InRadar(pos, gu->myAllyTeam) ? 2 : 0)); + } + std::memcpy(vision.data() + sizeof(visionHeader) + grid * grid, contacts.data(), contacts.size() * sizeof(float3)); + if (!nativeInfo.empty()) std::memcpy(vision.data() + sizeof(visionHeader) + grid * grid + contacts.size() * sizeof(float3), nativeInfo.data(), nativeInfo.size()); + MAIN_THREAD_EM_ASM({ if (Module['webbarVision']) Module['webbarVision'](HEAPU8.slice($0, $0 + $1).buffer); }, vision.data(), vision.size()); + + PublishWebbarFeatures(); + struct QueueRecord { uint32_t unit, tag; int32_t command; uint32_t target; float x, y, z; uint32_t index, facing; }; static_assert(sizeof(QueueRecord) == 36); std::vector queues; --- a/rts/Lua/LuaHandleSynced.cpp +++ b/rts/Lua/LuaHandleSynced.cpp @@ -8,6 +8,9 @@ #include "Game/WebbarShieldHits.h" #include "Game/WebbarPveEvents.h" #include "WebbarDistortionForwarders.h" +#include "Game/WebbarHealthbarEvents.h" +#include "Game/WebbarEtaEvents.h" +#include "Game/WebbarScumEvents.h" #endif #include "LuaUtils.h" @@ -193,6 +196,9 @@ void CUnsyncedLuaHandle::RecvFromSynced(lua_State* srcState, int args) { #ifdef __EMSCRIPTEN__ + WebbarHealthbarEvents::Observe(srcState,args); + WebbarEtaEvents::Observe(srcState,args); + if (GetName()=="LuaRules") WebbarScumEvents::Observe(srcState,L,args); // The original shield gadget already sends this presentation event. The // browser has no native GL gadget, so observe it before the Lua early-out. if (args == 8 && lua_type(srcState, 1) == LUA_TSTRING && --- a/rts/Lua/LuaUnsyncedRead.cpp +++ b/rts/Lua/LuaUnsyncedRead.cpp @@ -19,6 +19,7 @@ #include "Game/Players/PlayerHandler.h" #include "Game/SelectedUnitsHandler.h" #include "Game/TraceRay.h" +#include "Game/WebbarNativeCursorTrace.h" #include "Game/Camera/CameraController.h" #include "Game/UI/GuiHandler.h" #include "Game/UI/InfoConsole.h" @@ -3227,6 +3228,11 @@ int LuaUnsyncedRead::TraceScreenRayForCamera(lua_State* L, CCamera* view, int width, int height) { + return TraceScreenRayForCameraWithVolumes(L,view,width,height,nullptr); +} + +int LuaUnsyncedRead::TraceScreenRayForCameraWithVolumes(lua_State* L, CCamera* view, int width, int height, const WebbarNativeOrder::CursorSelectionVolumes* volumes) +{ const int viewSizeX=view?width:globalRendering->viewSizeX,viewSizeY=view?height:globalRendering->viewSizeY,viewPosX=view?0:globalRendering->viewPosX; const CCamera* traceCamera=view?view:camera; // window coordinates @@ -3287,7 +3293,8 @@ const float3 pxlDir = view?view->CalcPixelDir(wx,wy,width,height,0):camera->CalcPixelDir(wx,wy); // trace for player's allyteam - const float traceDist = TraceRay::GuiTraceRay(camPos, pxlDir, rawRange, nullptr, unit, feature, true, onlyCoords, ignoreWater); + const float traceDist = volumes ? WebbarNativeOrder::CursorGuiTraceRay(*volumes, camPos, pxlDir, rawRange, nullptr, unit, feature, true, onlyCoords, ignoreWater) + : TraceRay::GuiTraceRay(camPos, pxlDir, rawRange, nullptr, unit, feature, true, onlyCoords, ignoreWater); const float planeDist = CGround::LinePlaneCol(camPos, pxlDir, rawRange, luaL_optnumber(L, newArgIdx, 0.0f)); const float3 tracePos = camPos + (pxlDir * traceDist); --- a/rts/Lua/LuaUnsyncedRead.h +++ b/rts/Lua/LuaUnsyncedRead.h @@ -5,6 +5,7 @@ struct lua_State; class CCamera; +namespace WebbarNativeOrder {struct CursorSelectionVolumes;} class LuaUnsyncedRead { @@ -135,6 +136,7 @@ static int WorldToScreenCoords(lua_State* L); static int TraceScreenRay(lua_State* L); static int TraceScreenRayForCamera(lua_State* L, CCamera* view, int width, int height); + static int TraceScreenRayForCameraWithVolumes(lua_State* L, CCamera* view, int width, int height, const WebbarNativeOrder::CursorSelectionVolumes* volumes); static int GetPixelDir(lua_State* L); static int GetTimer(lua_State* L);