--- a/rts/Game/Game.cpp +++ b/rts/Game/Game.cpp @@ -293,6 +293,7 @@ // The private unsynced presentation VM must close before game definitions. #if defined(__EMSCRIPTEN__) static void FreeWebbarNativeBeams(); +static void FreeWebbarNativeInfo(); static void PrepareWebbarNativeBeams(); static void InitializeWebbarReplayView(); #endif @@ -301,6 +302,7 @@ { #if defined(__EMSCRIPTEN__) FreeWebbarNativeBeams(); + FreeWebbarNativeInfo(); #endif ENTER_SYNCED_CODE(); LOG("[Game::%s][1]", __func__); --- a/rts/Game/WebbarBrowser.h +++ b/rts/Game/WebbarBrowser.h @@ -115,6 +115,7 @@ #include "WebbarOrderEvents.h" #include "WebbarAutomationBrowser.h" #include "WebbarWidgetQueries.h" +#include "WebbarNativeInfo.h" static void PublishWebbarPlayState() { @@ -245,6 +246,7 @@ static const bool enabled = std::getenv("WEBBAR_PLAYABLE") != nullptr; if (!enabled || !game->playing || gs->frameNum < 0) return; + WebbarNativeInfo::Poll(); if (webbarReplay::Enabled()) { PollWebbarReplay(); UpdateWebbarNativeBeams(); return; } GetWebbarEffects(); GetWebbarMatchResult(); @@ -316,6 +318,9 @@ 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 == 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])); } else if (order.kind == 1000) { clientNet->Send(CBaseNetProtocol::Get().SendPause(gu->myPlayerNum, order.target != 0)); } else if (order.kind == 1013) { --- /dev/null +++ b/rts/Game/WebbarInfoReadAdapter.h @@ -0,0 +1,720 @@ +/* This file is part of the Spring engine (GPL v2 or later), see LICENSE.html */ +#pragma once +// Original pinned Info refreshUnitInfo plus bounded native-read adapter. +static constexpr const char* WEBBAR_INFO_READ_ADAPTER = R"WEBBAR_INFO_READ( +local iconTypes=assert(webbarInfoIconTypes) +local math_floor,math_min,math_max=math.floor,math.min,math.max +UnitDefNames={};for id,def in pairs(UnitDefs)do UnitDefNames[def.name]=def end +WeaponDefNames={};for id,def in pairs(WeaponDefs)do WeaponDefNames[def.name]=def end +FeatureDefNames={};if FeatureDefs then for id,def in pairs(FeatureDefs)do FeatureDefNames[def.name]=def end end +-- Reverse armor type table +local armorIndex = {} +for ii = 1, #Game.armorTypes do + armorIndex[Game.armorTypes[ii]] = ii +end + +local function round(value, numDecimalPlaces) + if type(numDecimalPlaces) ~= "number" then + numDecimalPlaces = 0 + end + if type(value) == "number" and value == value and value > -math.huge and value < math.huge then + local rounded = math.round(value, numDecimalPlaces) + if rounded == rounded and rounded > -math.huge and rounded < math.huge then + return string.format("%0." .. numDecimalPlaces .. "f", rounded) + end + end + return 0 +end + +local unitDefInfo = {} +local unitRestricted = {} +local isWaterUnit = {} +local isGeothermalUnit = {} + +-- Cache frequently used translated strings +local cachedTranslations = {} +local function getCachedTranslation(key) + if not cachedTranslations[key] then + cachedTranslations[key] = Spring.I18N(key) + end + return cachedTranslations[key] +end + +-- String buffer for concatenation to reduce allocations +local stringBuffer = {} +local function clearStringBuffer() + for i = #stringBuffer, 1, -1 do + stringBuffer[i] = nil + end +end + +-- Reusable tables to reduce allocations in hot paths +local rightMouseButtonMap = {} +local emptyTable = {} +local shiftTable = { "shift" } +local unloadParams = { 0, 0, 0, 0 } -- x, y, z, unitID +local viewSelectionCmd = { "viewselection" } +local selectionUnitpicWarm = { warmed = {}, queued = {}, queuedSet = {}, candidateSet = {}, count = 0 } +local selectionUnitpicWarmPerFrame = 1 + +local showWeaponGroups = { ["0"] = true, ["1"] = true } -- <0:=fake weapons, 0:=always active, 1:=primary set, >1:=alternate sets + +local function refreshUnitInfo() + local builderTraits = { + canBuild = function(def) return def.isFactory or next(def.buildOptions) ~= nil end, + canAssist = function(def) return not def.isFactory and def.canAssist end, + canCapture = function(def) return not def.isFactory and def.canCapture and def.buildDistance > 0 end, + canReclaim = function(def) return not def.isFactory and def.canReclaim and def.buildDistance > 0 end, + canRepair = function(def) return not def.isFactory and def.canRepair and def.buildDistance > 0 end, + canRestore = function(def) return not def.isFactory and def.canRestore and def.buildDistance > 0 end, + } + local function hasBuilderTrait(def) + for trait, check in pairs(builderTraits) do + if check(def) then + return true + end + end + return false + end + + for unitDefID, unitDef in pairs(UnitDefs) do + unitDefInfo[unitDefID] = {} + + if unitDef.iconType and iconTypes[unitDef.iconType] and iconTypes[unitDef.iconType].bitmap then + unitDefInfo[unitDefID].icontype = iconTypes[unitDef.iconType].bitmap + end + + if unitDef.name == 'armdl' or unitDef.name == 'cordl' or unitDef.name == 'armlance' or unitDef.name == 'cortitan' + or (unitDef.minWaterDepth > 0 or unitDef.modCategories['ship']) then + if not (unitDef.modCategories['hover'] or (unitDef.modCategories['mobile'] and unitDef.modCategories['canbeuw'])) then + isWaterUnit[unitDefID] = true + end + end + + if unitDef.needGeo then + isGeothermalUnit[unitDefID] = true + end + + if unitDef.maxThisUnit == 0 then + unitRestricted[unitDefID] = true + end + + if unitDef.isAirUnit then + unitDefInfo[unitDefID].airUnit = true + end + + unitDefInfo[unitDefID].translatedHumanName = unitDef.translatedHumanName + if unitDef.maxWeaponRange > 16 then + unitDefInfo[unitDefID].maxWeaponRange = unitDef.maxWeaponRange + end + if unitDef.speed > 0 then + if (tonumber(unitDef.customParams.speedfactorinwater or 1) or 1) == 1 then + unitDefInfo[unitDefID].speed = round(unitDef.speed, 0) + else + local speed = unitDef.speed + local speedInWater = math.round(speed * math.clamp(tonumber(unitDef.customParams.speedfactorinwater), 0, 1e4)) + unitDefInfo[unitDefID].speedMin = math.min(speed, speedInWater) + unitDefInfo[unitDefID].speedMax = math.max(speed, speedInWater) + end + end + if unitDef.rSpeed > 0 then + unitDefInfo[unitDefID].reverseSpeed = round(unitDef.rSpeed, 0) + end + if unitDef.stealth then + unitDefInfo[unitDefID].stealth = true + end + if unitDef.cloakCost and unitDef.canCloak then + unitDefInfo[unitDefID].cloakCost = unitDef.cloakCost + if unitDef.cloakCostMoving > unitDef.cloakCost then + unitDefInfo[unitDefID].cloakCostMoving = unitDef.cloakCostMoving + end + end + if unitDef.isTransport then + unitDefInfo[unitDefID].transport = { unitDef.transportMass, unitDef.transportSize, unitDef.transportCapacity } + end + if unitDef.customParams.paralyzemultiplier then + unitDefInfo[unitDefID].paralyzeMult = tonumber(unitDef.customParams.paralyzemultiplier) + end + unitDefInfo[unitDefID].armorType = Game.armorTypes[unitDef.armorType or 0] or '???' + + if unitDef.sightDistance > 0 then + unitDefInfo[unitDefID].sightDistance = unitDef.sightDistance + end + if unitDef.airSightDistance > 0 then + unitDefInfo[unitDefID].airSightDistance = unitDef.airSightDistance + end + if unitDef.radarDistance > 0 then + unitDefInfo[unitDefID].radarDistance = unitDef.radarDistance + end + if unitDef.sonarDistance > 0 then + unitDefInfo[unitDefID].sonarDistance = unitDef.sonarDistance + end + if unitDef.radarDistanceJam > 0 then + unitDefInfo[unitDefID].radarDistanceJam = unitDef.radarDistanceJam + end + if unitDef.sonarDistanceJam > 0 then + unitDefInfo[unitDefID].sonarDistanceJam = unitDef.sonarDistanceJam + end + if unitDef.seismicDistance > 0 then + unitDefInfo[unitDefID].seismicDistance = unitDef.seismicDistance + end + + if unitDef.customParams.energyconv_capacity and unitDef.customParams.energyconv_efficiency then + unitDefInfo[unitDefID].metalmaker = { tonumber(unitDef.customParams.energyconv_capacity), tonumber(unitDef.customParams.energyconv_efficiency) } + end + + unitDefInfo[unitDefID].description = unitDef.translatedTooltip + unitDefInfo[unitDefID].energyCost = unitDef.energyCost + unitDefInfo[unitDefID].metalCost = unitDef.metalCost + unitDefInfo[unitDefID].energyStorage = unitDef.energyStorage + unitDefInfo[unitDefID].metalStorage = unitDef.metalStorage + + unitDefInfo[unitDefID].health = unitDef.health + unitDefInfo[unitDefID].buildTime = unitDef.buildTime + unitDefInfo[unitDefID].buildPic = unitDef.buildPic and true or false + if unitDef.canStockpile then + unitDefInfo[unitDefID].canStockpile = true + end + if unitDef.buildSpeed > 0 and hasBuilderTrait(unitDef) then + unitDefInfo[unitDefID].buildSpeed = unitDef.buildSpeed + end + if unitDef.buildOptions[1] then + unitDefInfo[unitDefID].buildOptions = unitDef.buildOptions + end + if unitDef.extractsMetal > 0 then + unitDefInfo[unitDefID].mex = true + end + local weapons = unitDef.weapons + + + ----------------------------------------------------- + -- Utility functions for calculating weapon values -- + ----------------------------------------------------- + + local function addPrimaryDPS(minDPS, maxDPS) + unitDefInfo[unitDefID].mindps = (unitDefInfo[unitDefID].mindps or 0) + minDPS + unitDefInfo[unitDefID].maxdps = (unitDefInfo[unitDefID].maxdps or 0) + maxDPS + end + + local function addSecondaryDPS(minDPS, maxDPS) + unitDefInfo[unitDefID].maxdps = (unitDefInfo[unitDefID].maxdps or 0) + maxDPS + end + + + local function calculateLaserDPS(def, damage) + local minIntensity = math.max(def.minIntensity, 0.5) + local mindps = minIntensity*(damage * def.salvoSize / def.reload) + local maxdps = damage * def.salvoSize / def.reload + return mindps, maxdps + end + + local function calculateWeaponDPS(def, damage) + local reloadDPS = damage * (def.salvoSize * def.projectiles) / def.reload + local stockpileDPS = damage * (def.salvoSize * def.projectiles) / (def.stockpile and def.stockpileTime/30 or def.reload) + return math_min(reloadDPS, stockpileDPS), math_max(reloadDPS, stockpileDPS) + end + + local function calculateClusterDPS(def, damage) + local munition = unitDef.name .. '_' .. def.customParams.cluster_def + local cmNumber = def.customParams.cluster_number + local cmDamage = WeaponDefNames[munition].damages[0] + + local mainDps = (def.salvoSize * def.projectiles) / def.reload * (damage) + local cmunDps = (def.salvoSize * def.projectiles) / def.reload * (cmNumber * cmDamage) + return mainDps, mainDps + cmunDps + end + + local function calculateAreaDPS(def, damage) + local burst = def.salvoSize * def.projectiles + local impactDps = damage * burst / def.reload + local areaDps = def.customParams.area_onhit_damage -- by definition + local damageMax = math_max(impactDps + areaDps, areaDps * burst * def.customParams.area_onhit_time / def.reload) + return impactDps, damageMax + end + + + local function setEnergyAndMetalCosts(def) + if def.energyCost > 0 and (not unitDefInfo[unitDefID].energyPerShot or def.energyCost > unitDefInfo[unitDefID].energyPerShot) then + unitDefInfo[unitDefID].energyPerShot = def.energyCost + end + if def.metalCost > 0 and (not unitDefInfo[unitDefID].metalPerShot or def.metalCost > unitDefInfo[unitDefID].metalPerShot) then + unitDefInfo[unitDefID].metalPerShot = def.metalCost + end + end + + ----------------------------------------------------- + + local unitExempt = false + + local function refreshUnitWeaponInfo(i, weaponDef, isPrimaryWeapon) + unitDefInfo[unitDefID].weapons[i] = weaponDef + + if isPrimaryWeapon and weapons[i].onlyTargets['vtol'] then + unitDefInfo[unitDefID].isAaUnit = true -- displays airLOS range + end + + local addDPS = isPrimaryWeapon and addPrimaryDPS or addSecondaryDPS + + if weaponDef.interceptor ~= 0 and weaponDef.coverageRange then + unitDefInfo[unitDefID].maxCoverage = math.max(unitDefInfo[unitDefID].maxCoverage or 1, weaponDef.coverageRange) + + elseif weaponDef.shieldRadius and weaponDef.shieldRadius > 0 then + if #weapons == 1 then + unitDefInfo[unitDefID].weapons = {} + unitDefInfo[unitDefID].shieldOnly = true + end + unitDefInfo[unitDefID].shieldRange = weaponDef.shieldRadius + unitDefInfo[unitDefID].shieldCapacity = weaponDef.shieldPower + unitDefInfo[unitDefID].shieldRechargeRate = weaponDef.shieldPowerRegen + unitDefInfo[unitDefID].shieldRechargeCost = weaponDef.shieldPowerRegenEnergy + + else + if unitDef.name == 'armamb' or unitDef.name == 'cortoast' then -- weapons with low/high traj, this list is incomplete + unitExempt = true + if i==1 then --Calculating using first weapon only + addDPS(calculateWeaponDPS(weaponDef, weaponDef.damages[0])) --Damage to default armor category + end + + elseif + unitDef.customParams.evocomlvl or -- use primary weapon for evolving commanders + unitDef.name == 'armcom' or -- ignore underwater secondary + unitDef.name == 'corcom' or + unitDef.name == 'legcom' or + unitDef.name == 'corkarg' or -- ignore secondary weapons, kick + unitDef.name == 'armguard' or -- ignore high-trajectory modes + unitDef.name == 'corpun' or + unitDef.name == 'legcluster' or + unitDef.name == 'leglob' or + unitDef.name == 'legnavyfrigate' or + unitDef.name == 'armamb' or + unitDef.name == 'cortoast' or + unitDef.name == 'armvang' + then + unitExempt = true + if i == 1 then --Calculating using first weapon only + setEnergyAndMetalCosts(weaponDef) + + if weaponDef.type == "BeamLaser" then + addDPS(calculateLaserDPS(weaponDef, weaponDef.damages[0])) + elseif weaponDef.customParams.cluster then -- Bullets that shoot other, smaller bullets + addDPS(calculateClusterDPS(weaponDef, weaponDef.damages[0])) + elseif weapons[i].onlyTargets['vtol'] ~= nil then + addDPS(calculateWeaponDPS(weaponDef, weaponDef.damages[armorIndex.vtol])) --Damage to air category + else + addDPS(calculateWeaponDPS(weaponDef, weaponDef.damages[0])) --Damage to default armor category + end + end + + elseif unitDef.name == 'corkorg' then --excluding korstomp from dps calcuation for juggernaut + unitExempt = true + if i==1 then + local defDmg + defDmg = weaponDef.damages[0] --Damage to default armor category + addDPS(calculateWeaponDPS(weaponDef, defDmg)) + end + + if i==2 then + setEnergyAndMetalCosts(weaponDef) + addDPS(calculateLaserDPS(weaponDef, weaponDef.damages[0])) + end + + if i==3 then + addDPS(calculateWeaponDPS(weaponDef, weaponDef.damages[0])) --Damage to default armor category + end + + elseif weaponDef.customParams.area_onhit_damage and weaponDef.customParams.area_onhit_time then + unitExempt = true + addDPS(calculateAreaDPS(weaponDef, weaponDef.damages[0])) + elseif weaponDef.customParams.cluster then -- Bullets that explode into other, smaller bullets + unitExempt = true + addDPS(calculateClusterDPS(weaponDef, weaponDef.damages[0])) + elseif weaponDef.customParams.speceffect == "split" then -- Bullets that split into other, smaller bullets + unitExempt = true + local splitd = WeaponDefNames[weaponDef.customParams.speceffect_def].damages[0] + local splitn = weaponDef.customParams.number or 1 + addDPS(calculateWeaponDPS(weaponDef, splitd * splitn)) + elseif weaponDef.customParams.spark_forkdamage then -- Lightning + unitExempt = true + addDPS(calculateWeaponDPS(weaponDef, weaponDef.damages[0])) + -- Sparks cannot retarget the original unit they hit, so add them as secondary damages. + local forkDamageRate = weaponDef.customParams.spark_forkdamage + addSecondaryDPS(calculateWeaponDPS(weaponDef, weaponDef.damages[0] * forkDamageRate)) + if unitExempt and weaponDef.paralyzer then -- DPS => EMP + unitDefInfo[unitDefID].minemp = unitDefInfo[unitDefID].mindps + unitDefInfo[unitDefID].maxemp = unitDefInfo[unitDefID].maxdps + unitDefInfo[unitDefID].mindps = nil + unitDefInfo[unitDefID].maxdps = nil + end + end + + if unitDefInfo[unitDefID].mainWeapon == 0 then + unitDefInfo[unitDefID].mainWeapon = i + unitDefInfo[unitDefID].range = weaponDef.range + unitDefInfo[unitDefID].reloadTime = weaponDef.customParams.dronesuesestockpile + and weaponDef.stockpileTime + or weaponDef.reload + end + if weaponDef.type == "BeamLaser" and not unitExempt then -- BeamLaser dps calc + + local defDmg + + if weapons[1].onlyTargets['vtol'] ~= nil then --if main weapon isn't dedicated aa, then all weapons calculate using default armor category + defDmg = weaponDef.damages[armorIndex.vtol] + else + defDmg = weaponDef.damages[0] + end + + setEnergyAndMetalCosts(weaponDef) + + if weaponDef.paralyzer ~= true then + + + if weaponDef.customParams then + + if weaponDef.customParams.sweepfire then + unitDefInfo[unitDefID].maxdps = (weaponDef.damages[0] * weaponDef.customParams.sweepfire) / math.max(weaponDef.minIntensity, 0.5) + unitDefInfo[unitDefID].mindps = weaponDef.damages[0] * weaponDef.customParams.sweepfire + else + addDPS(calculateLaserDPS(weaponDef, defDmg)) + end + else + addDPS(calculateLaserDPS(weaponDef, defDmg)) + end + else + -- calculate laser emp dmg + local minIntensity = math.max(weaponDef.minIntensity, 0.5) + local prevMinDps = unitDefInfo[unitDefID].minemp or 0 + local prevMaxDps = unitDefInfo[unitDefID].maxemp or 0 + local mindps = minIntensity*(weaponDef.damages[0] * weaponDef.salvoSize / weaponDef.reload) + local maxdps = weaponDef.damages[0] * weaponDef.salvoSize / weaponDef.reload + + unitDefInfo[unitDefID].minemp = mindps + prevMinDps + unitDefInfo[unitDefID].maxemp = maxdps + prevMaxDps + end + elseif weaponDef.paralyzer == true and unitDef.name ~= 'armthor' then -- exclude thor emp missile + local defDmg = weaponDef.damages[0] --Damage to default armor category + local emp = math_floor(defDmg * weaponDef.salvoSize / weaponDef.reload) + unitDefInfo[unitDefID].minemp = emp + unitDefInfo[unitDefID].maxemp = emp + unitDefInfo[unitDefID].range = weaponDef.range + unitDefInfo[unitDefID].reloadTime = weaponDef.reload + end + if weaponDef.type ~= "BeamLaser" and weaponDef.paralyzer ~= true and not unitExempt then + + local defDmg + + if weapons[1].onlyTargets['vtol'] ~= nil then --if main weapon isn't dedicated aa, then all weapons calculate using default armor category + defDmg = weaponDef.damages[armorIndex.vtol] + else + defDmg = weaponDef.damages[0] + end + + if(defDmg > 0) then + addDPS(calculateWeaponDPS(weaponDef, defDmg)) + setEnergyAndMetalCosts(weaponDef) + end + end + end + end + for i = 1, #weapons do + if not unitDefInfo[unitDefID].weapons then + unitDefInfo[unitDefID].weapons = {} + unitDefInfo[unitDefID].mindps = 0 + unitDefInfo[unitDefID].maxdps = 0 + unitDefInfo[unitDefID].range = 0 + unitDefInfo[unitDefID].reloadTime = 0 + unitDefInfo[unitDefID].mainWeapon = 0 + end + local weaponDef = WeaponDefs[weapons[i].weaponDef] + -- Only groups 0 [always active] and 1 [primary weapon set] are aggregated. + -- Others might be checked for abilities still, e.g. antinuke interceptors. + if showWeaponGroups[weaponDef.customParams.weapons_group] and weaponDef.customParams.bogus ~= "1" then + refreshUnitWeaponInfo(i, weaponDef, weaponDef.customParams.weapons_role ~= "secondary") + end + end + if unitDefInfo[unitDefID].mainWeapon == 0 then + unitDefInfo[unitDefID].mainWeapon = 1 -- All the unit's weapons were fakes. + end + + if unitDef.customParams.unitgroup and unitDef.customParams.unitgroup == 'explo' and unitDef.deathExplosion and WeaponDefNames[unitDef.deathExplosion] then + local weapon = WeaponDefs[WeaponDefNames[unitDef.deathExplosion].id] + if weapon then + local dmg = weapon.damages[Game.armorTypes["default"]] + unitDefInfo[unitDefID].mindps = dmg + unitDefInfo[unitDefID].maxdps = dmg + unitDefInfo[unitDefID].reloadTime = nil + end + end + end + + -- Account for sub-unit damages, namely carriers and drones. + local mins = { "mindps", "minemp", } + local maxs = { "maxdps", "maxemp", } + for unitDefID, unitDef in pairs(UnitDefs) do + local unitInfo = unitDefInfo[unitDefID] + for index, weapon in ipairs(unitDef.weapons) do + local weaponDef = WeaponDefs[weapon.weaponDef] + if weaponDef.customParams.carried_unit and UnitDefNames[weaponDef.customParams.carried_unit] then + local droneCount = weaponDef.customParams.maxunits or 1 + local droneDef = UnitDefNames[weaponDef.customParams.carried_unit] + local droneInfo = unitDefInfo[droneDef.id] + + for _, key in ipairs(mins) do + if droneInfo[key] then + unitInfo[key] = (unitInfo[key] or 0) -- times zero drones == zero + end + end + + for _, key in ipairs(maxs) do + if droneInfo[key] then + unitInfo[key] = (unitInfo[key] or 0) + (droneInfo[key] * droneCount) + end + end + end + end + end + + -- Convert aggregated values to display formats last to avoid rounding errors. + local summedKeys = { "mindps", "maxdps", "minemp", "maxemp", } + for unitDefID, unitInfo in pairs(unitDefInfo) do + for _, key in pairs(summedKeys) do + if type(unitInfo[key]) == "number" then + unitInfo[key] = math_floor(unitInfo[key]) + end + end + end +end + +refreshUnitInfo() +-- Separate native read handle; original per-field authority remains decisive. +local function packed(...) + if select('#',...)==0 then return nil end + return {n=select('#',...),...} +end +local function definition(id) + local native,info=UnitDefs[id],unitDefInfo[id] + if not native or not info then return nil end + local cp=native.customParams + local proxy=cp.fromunit and UnitDefNames[cp.fromunit] + local out={name=native.name,corpse=native.corpse,presentation={buildPic=native.buildPic,iconType=native.iconType,unitGroup=cp.unitgroup,humanName=native.humanName,tooltip=native.tooltip,i18nFromUnit=cp.i18nfromunit,fromUnit=cp.fromunit,scavenger=cp.isscavenger,proxyI18nFromUnit=proxy and proxy.customParams.i18nfromunit,humanNameEn=cp.i18n_en_humanname,tooltipEn=cp.i18n_en_tooltip}} + for key,value in pairs(info)do if key=='weapons'then out.weapons=true else out[key]=value end end + return out +end +function WebbarReadInfo(kind,ids,sampleDefinition) + assert((kind==1 or kind==2 or kind==3)and type(ids)=='table'and #ids>0 and #ids<=(kind==3 and 8192 or 64),'Invalid Info read batch') + local out,count={definitions={},units={}},0 + if kind==2 then for _,id in ipairs(ids)do out.definitions[id]=definition(id)end;return out end + local function pairedResources(row) + local paired=row.rules.pairedUnitID + if type(paired)=='number'then + local resources=packed(Spring.GetUnitResources(paired)) + if resources then + if out.units[paired]then out.units[paired].resources=resources + else count=count+1;assert(count<=(kind==3 and 8256 or 256),'Info linked-unit budget exceeded');out.units[paired]={id=paired,resources=resources,pairedOnly=true}end + end + end + end + if kind==3 then + out.sampled={};out.sampleDefinition=sampleDefinition + for _,id in ipairs(ids)do + local fromPair=out.units[id]and out.units[id].pairedOnly and out.units[id].resources + if out.units[id]and out.units[id].pairedOnly then out.units[id]=nil;count=count-1 end + assert(not out.units[id],'Duplicate selected Info unit') + local def=Spring.GetUnitDefID(id) + if def then + count=count+1;assert(count<=8256,'Info selection budget exceeded') + local row={id=id,definition=def,team=Spring.GetUnitTeam(id),resources=fromPair,rules={kills=Spring.GetUnitRulesParam(id,'kills')}} + out.units[id]=row + -- Selection cells sum every unit's kills. The original resource-total + -- loop samples first50 of the complete selection or the hovered type. + if #out.sampled<50 and(sampleDefinition==0 or sampleDefinition==def)then + out.sampled[#out.sampled+1]=id + row.resources=packed(Spring.GetUnitResources(id)) + row.rules.pairedUnitID=Spring.GetUnitRulesParam(id,'pairedUnitID') + pairedResources(row) + end + end + end + -- Definitions are immutable match-public records fetched separately in + -- batches64 and cached by the actual engine/match identity. Do not repeat + -- thousands of complete specification records on every selection refresh. + return out + end + local function unit(id,linked) + if out.units[id]and out.units[id].pairedOnly then out.units[id]=nil;count=count-1 end + if out.units[id]then return end + local def=Spring.GetUnitDefID(id);if not def then return end + count=count+1;assert(count<=256,'Info linked-unit budget exceeded') + local info=assert(definition(def));out.definitions[def]=info + local row={id=id,definition=def,team=Spring.GetUnitTeam(id),health=packed(Spring.GetUnitHealth(id)),resources=packed(Spring.GetUnitResources(id)),experience=Spring.GetUnitExperience(id),rules={},weapons={}} + out.units[id]=row;row.rules.kills=Spring.GetUnitRulesParam(id,'kills');row.rules.pairedUnitID=Spring.GetUnitRulesParam(id,'pairedUnitID') + if info.mainWeapon then row.weapons[info.mainWeapon]={range=Spring.GetUnitWeaponState(id,info.mainWeapon,'range'),reloadTimeXP=Spring.GetUnitWeaponState(id,info.mainWeapon,'reloadTimeXP')}end + row.cargo=Spring.GetUnitIsTransporting(id);pairedResources(row) + if not linked then for _,cargo in ipairs(row.cargo or{})do unit(cargo,true)end end + end + for _,id in ipairs(ids)do unit(id,false)end + return out +end + +-- Native TraceScreenRay and LuaSyncedRead remain the authority. All feature +-- definitions/owner paths are public; live IDs and resources require native +-- visibility. This handle exposes no control, selection or camera mutation. +local worldFeatureOwners +local function featureOwners() + if worldFeatureOwners then return worldFeatureOwners end + local owners={} + -- Preserve the original refreshFeatureDefs UnitDefs iteration order. Shared + -- corpse/heap definitions must receive the same final owner's translation. + for unitID,unit in pairs(UnitDefs)do + local chain,seen={},{} + local feature=FeatureDefNames[unit.corpse] + while feature do + assert(not seen[feature.id]and #chain<256,'Invalid native corpse chain') + seen[feature.id]=true;chain[#chain+1]=feature.id + feature=FeatureDefs[feature.deathFeatureID] + end + for _,id in ipairs(chain)do + local list=owners[id]or{};owners[id]=list + list[#list+1]={unit=unitID,chain=chain} + end + end + worldFeatureOwners=owners;return owners +end +function WebbarReadInfoWorld(ids,sampleDefinition,mouse) + assert(type(ids)=='table'and #ids<=8192 and type(mouse)=='table'and #mouse==7,'Invalid native Info world request') + local out=#ids>0 and WebbarReadInfo(#ids==1 and 1 or 3,ids,sampleDefinition)or{definitions={},units={}} + if not out.sampled then + out.sampled={};out.sampleDefinition=sampleDefinition + for _,id in ipairs(ids)do local u=out.units[id];if u and(sampleDefinition==0 or u.definition==sampleDefinition)then out.sampled[#out.sampled+1]=id end end + end + local world={mouse=mouse,features={},definitions={},unitOrder={}} + out.world=world + local kind,hit + if not mouse[6]then kind,hit=Spring.TraceScreenRay(mouse[1],mouse[2])end + if kind=='unit'then + local hovered=WebbarReadInfo(1,{hit},0) + if hovered.units[hit]then + world.type,world.data=kind,hit + for id,value in pairs(hovered.units)do out.units[id]=value end + for id,value in pairs(hovered.definitions)do out.definitions[id]=value end + end + elseif kind=='feature'then + local id=Spring.GetFeatureDefID(hit) + local resources={Spring.GetFeatureResources(hit)} + if id and #resources==6 then + world.type,world.data=kind,hit + world.features[tostring(hit)]={definition=id,resources=resources} + local function includeFeature(defID) + local f=assert(FeatureDefs[defID],'Native Info feature definition missing') + local cp=f.customParams + world.definitions[defID]={name=f.name,tooltip=f.tooltip,reclaimable=f.reclaimable,deathFeatureID=f.deathFeatureID,customParams={category=cp.category,i18nfrom=cp.i18nfrom}} + end + includeFeature(id) + for _,owner in ipairs(featureOwners()[id]or{})do + assert(#world.unitOrder<256,'Native Info feature owner budget exceeded') + world.unitOrder[#world.unitOrder+1]=owner.unit + out.definitions[owner.unit]=definition(owner.unit) + for _,defID in ipairs(owner.chain)do includeFeature(defID)end + end + end + elseif kind=='ground'then + local desc,coordinates=Spring.TraceScreenRay(mouse[1],mouse[2],true) + if desc=='ground'and type(coordinates)=='table'and #coordinates==6 then + local info={Spring.GetGroundInfo(coordinates[1],coordinates[3])} + local height=Spring.GetGroundHeight(coordinates[1],coordinates[3]) + if #info==9 and height then + world.type,world.data=kind,hit + world.ground={coordinates=coordinates,info=info,height=height} + end + end + end + local count=0;for _ in pairs(out.definitions)do count=count+1 end;assert(count<=256,'Native Info definition budget exceeded') + return out +end + +do +local CMD={STOP=0,MOVE=10,UNLOAD_UNIT=81} +local emptyTable,shiftTable,unloadParams={},{'shift'},{0,0,0,0} +local mapSizeX, mapSizeZ = Game.mapSizeX, Game.mapSizeZ +local function unloadTransport(transportID, unitID, x, z, shift, depth) + if not depth then + depth = 1 + end + local radius = 20 * depth + local orgX, orgZ = x, z + local y = Spring.GetGroundHeight(x, z) + local unitSphereRadius = 60 -- too low value will result in unload conflicts + local areaUnits = Spring.GetUnitsInSphere(x, y, z, unitSphereRadius) + if #areaUnits == 0 then -- unblocked spot! + unloadParams[1], unloadParams[2], unloadParams[3], unloadParams[4] = x, y, z, unitID + Spring.GiveOrderToUnit(transportID, CMD.UNLOAD_UNIT, unloadParams, shift and shiftTable or emptyTable) + else + -- unload is blocked by unit at ground just lets find free alternative spot in a radius around it + local samples = 8 + local sideAngle = (math.pi * 2) / samples + local foundUnloadSpot = false + for i = 1, samples + 1 do + x = x + (radius * math.cos(i * sideAngle)) + z = z + (radius * math.sin(i * sideAngle)) + if x > 0 and z > 0 and x < mapSizeX and z < mapSizeZ then + y = Spring.GetGroundHeight(x, z) + areaUnits = Spring.GetUnitsInSphere(x, y, z, unitSphereRadius) + if #areaUnits == 0 then -- unblocked spot! + local areaFeatures = Spring.GetFeaturesInSphere(x, y, z, unitSphereRadius) + if #areaFeatures == 0 then + unloadParams[1], unloadParams[2], unloadParams[3], unloadParams[4] = x, y, z, unitID + Spring.GiveOrderToUnit(transportID, CMD.UNLOAD_UNIT, unloadParams, shift and shiftTable or emptyTable) + foundUnloadSpot = true + break + end + end + end + end + -- try again with increased radius + if not foundUnloadSpot and depth < 15 then -- limit depth for safety + unloadTransport(transportID, unitID, orgX, orgZ, shift, depth+1) + end + end +end + +function WebbarPlanInfoUnload(displayUnitID,unitID,queued) + local plan={} + local cargo=Spring.GetUnitIsTransporting(displayUnitID)or{} + local aboard=false;for _,id in ipairs(cargo)do if id==unitID then aboard=true;break end end + assert(aboard,'Native Info cargo changed') + local spGetModKeyState=function()return false,false,false,queued end + local previous=Spring.GiveOrderToUnit + Spring.GiveOrderToUnit=function(id,command,params,options) + assert(id==displayUnitID and #plan<36 and type(command)=='number'and command%1==0 and type(params)=='table'and #params<=256,'Invalid original Info unload plan') + local shift=type(options)=='table'and #options==1 and options[1]=='shift' + assert(shift or options==0 or(type(options)=='table'and #options==0),'Invalid original Info unload options') + local copy={};for i,value in ipairs(params)do assert(type(value)=='number'and value==value and math.abs(value) +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "Lua/LuaHandle.h" +#include "Lua/LuaLibs.h" +#include "Lua/LuaSyncedRead.h" +#include "Lua/LuaUnitDefs.h" +#include "Lua/LuaWeaponDefs.h" +#include "Lua/LuaFeatureDefs.h" +#include "Lua/LuaUnsyncedRead.h" +#include "Game/Camera.h" +#include "Lua/LuaConstGame.h" +#include "System/FileSystem/FileHandler.h" +#include "System/FileSystem/VFSModes.h" +#include "WebbarInfoReadAdapter.h" +#include "System/UnorderedSet.hpp" + +struct WebbarInfoWorldView { + int32_t mouseX, mouseY; + uint32_t width, height; + float position[3], rotation[3], verticalFov, aspect, nearPlane, farPlane; + uint32_t mouseFlags, reserved; +}; +static_assert(sizeof(WebbarInfoWorldView) == 64); + +// Independent unsynced read handle. Native LuaSyncedRead decides each field's +// ally/LOS/decoy/hideDamage/rules-param availability. No synced LuaRules state, +// control API, selection API, VFS/IO binding or client-supplied code is used. +class WebbarNativeInfoReader final: public CLuaHandle +{ +public: + WebbarNativeInfoReader(): CLuaHandle("WebBAR original Info reads", LUA_HANDLE_ORDER_UI, false, false) + { + SetFullCtrl(false); + SetCtrlTeam(NoAccessTeam); + SetSelectTeam(NoAccessTeam); + SetView(); + LuaLibs::OpenSynced(L, false); + lua_pushvalue(L, LUA_GLOBALSINDEX); + ready = AddBasicCalls(L) && AddCommonModules(L) + && AddEntriesToTable(L, "Spring", LuaSyncedRead::PushEntries) + && AddEntriesToTable(L, "UnitDefs", LuaUnitDefs::PushEntries) + && AddEntriesToTable(L, "WeaponDefs", LuaWeaponDefs::PushEntries) + && AddEntriesToTable(L, "FeatureDefs", LuaFeatureDefs::PushEntries) + && AddEntriesToTable(L, "Game", LuaConstGame::PushEntries); + if (ready) { + lua_getglobal(L, "Spring"); + lua_pushcfunction(L, ScreenRay); lua_setfield(L, -2, "TraceScreenRay"); + } + 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) LOG_L(L_ERROR, "[WebBAR] original Info read initialization failed"); + } + ~WebbarNativeInfoReader() override { KillLua(); } + + void SetView() + { + const bool full = gu->spectatingFullView; + SetFullRead(full); + SetReadTeam(full ? AllAccessTeam : gu->myTeam); + SetReadAllyTeam(full ? AllAccessTeam : gu->myAllyTeam); + } + + bool Read(uint32_t kind, const std::vector& ids, uint32_t sampleDefinition, std::string& json) + { + if (!ready) return false; + SetView(); + const int top = lua_gettop(L); + lua_getglobal(L, "WebbarReadInfo"); + lua_pushnumber(L, kind); + 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_pushnumber(L, sampleDefinition); + bool ok = RunCallIn(L, LuaHashString("WebbarReadInfo"), 3, 1); + if (ok && kind == 1) AddLifetimes(-1); + uint32_t nodes = 0; + if (ok) ok = JsonValue(-1, json, 0, nodes); + lua_settop(L, top); + // This handle has no event registration or per-frame work. Bound transient + // query allocations without adding a simulation or global GC policy. + CollectGarbage(true); + return ok; + } + + bool PlanUnload(uint32_t transport, uint32_t cargo, bool queued, std::vector& plan) + { + if (!ready) return false; + SetView(); + const int top = lua_gettop(L); + lua_getglobal(L, "WebbarPlanInfoUnload"); + lua_pushnumber(L, transport); lua_pushnumber(L, cargo); lua_pushboolean(L, queued); + bool ok = RunCallIn(L, LuaHashString("WebbarPlanInfoUnload"), 3, 1); + ok = ok && lua_istable(L, -1) && lua_objlen(L, -1) <= 36; + if (ok) { + const int rows = lua_gettop(L), count = lua_objlen(L, rows); + for (int i = 1; ok && i <= count; ++i) { + lua_rawgeti(L, rows, i); + if (!lua_istable(L, -1)) { ok = false; break; } + const int row = lua_gettop(L); + lua_getfield(L, row, "id"); + const float id = lua_tonumber(L, -1); + ok = lua_type(L, -1) == LUA_TNUMBER && std::isfinite(id) && std::fabs(id) < 16777216.0f && std::floor(id) == id; + lua_pop(L, 1); + lua_getfield(L, row, "options"); + const float options = lua_tonumber(L, -1); + ok = ok && lua_type(L, -1) == LUA_TNUMBER && (options == 0 || options == SHIFT_KEY); + lua_pop(L, 1); + if (!ok) break; + Command command{int(id), uint8_t(options)}; + lua_getfield(L, row, "params"); + if (!lua_istable(L, -1) || lua_objlen(L, -1) > 256) { ok = false; break; } + const int params = lua_gettop(L), size = lua_objlen(L, params); + for (int j = 1; ok && j <= size; ++j) { + lua_rawgeti(L, params, j); + const float value = lua_tonumber(L, -1); + ok = lua_type(L, -1) == LUA_TNUMBER && std::isfinite(value); + if (ok) command.PushParam(value); + lua_pop(L, 1); + } + if (ok) plan.push_back(std::move(command)); + lua_pop(L, 2); + } + } + lua_settop(L, top); + CollectGarbage(true); + if (!ok) plan.clear(); + return ok; + } + + bool ReadWorld(const WebbarInfoWorldView& request, const std::vector& ids, uint32_t sampleDefinition, std::string& json) + { + 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 int top = lua_gettop(L); + lua_getglobal(L, "WebbarReadInfoWorld"); + 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_pushnumber(L, sampleDefinition); + lua_createtable(L, 7, 0); + 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); } + bool ok = RunCallIn(L, LuaHashString("WebbarReadInfoWorld"), 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; + } + +private: + bool ready = false; + CCamera worldView{CCamera::CAMTYPE_VISCUL}; + int worldWidth = 0, worldHeight = 0; + static int ScreenRay(lua_State* L) + { + auto* self = static_cast(CLuaHandle::GetHandle(L)); + return LuaUnsyncedRead::TraceScreenRayForCamera(L, &self->worldView, self->worldWidth, self->worldHeight); + } + void AddLifetimes(int result) + { + if (result < 0) result = lua_gettop(L) + result + 1; + lua_getfield(L, result, "units"); + if (lua_istable(L, -1)) { + const int units = lua_gettop(L); + lua_pushnil(L); + while (lua_next(L, units)) { + if (lua_type(L, -2) == LUA_TNUMBER && lua_istable(L, -1)) { + const auto* unit = unitHandler.GetUnit(lua_tointeger(L, -2)); + lua_getfield(L, -1, "definition"); + const bool admitted = lua_isnumber(L, -1); + lua_pop(L, 1); + if (admitted && unit && WebbarVisible(unit)) { + // The Lua read VM is f32; preserve all32 token bits as hex. + char token[9]; std::snprintf(token, sizeof(token), "%08x", WebbarHudLifetime(unit)); + lua_pushstring(L, token); lua_setfield(L, -2, "lifetimeHex"); + } + } + lua_pop(L, 1); + } + } + lua_pop(L, 1); + } + bool JsonValue(int index, std::string& out, uint32_t depth, uint32_t& nodes) + { + if (depth > 12 || ++nodes > 262144 || out.size() > 1048576) return false; + if (index < 0) index = lua_gettop(L) + index + 1; + switch (lua_type(L, index)) { + case LUA_TNIL: out += "null"; break; + case LUA_TBOOLEAN: out += lua_toboolean(L, index) ? "true" : "false"; break; + case LUA_TNUMBER: { + const float value = lua_tonumber(L, index); + if (std::isfinite(value)) WebbarJsonNumber(out, value); + else { + // Zero-reload definitions can produce original Inf/NaN DPS. Keep + // their f32 bits explicit; never substitute a finite default. + uint32_t bits; std::memcpy(&bits, &value, 4); + out += "{\"nativeNumberBits\":" + std::to_string(bits) + '}'; + } + } break; + case LUA_TSTRING: { + size_t length; const char* text = lua_tolstring(L, index, &length); + if (length > 65536) return false; + if (std::all_of(text, text + length, [](unsigned char c) { return c < 128; })) { + WebbarJsonString(out, std::string(text, length)); + } else { + // Lua text may mix UTF8 and raw CglFont colour bytes. A JSON + // UTF8 conversion must not replace those original byte values. + constexpr char HEX[] = "0123456789abcdef"; + out += "{\"nativeTextHex\":\""; + for (size_t i = 0; i < length; ++i) { + const uint8_t c = uint8_t(text[i]); + out += HEX[c >> 4]; out += HEX[c & 15]; + } + out += "\"}"; + } + } break; + case LUA_TTABLE: { + out += '{'; bool first = true; + lua_pushnil(L); + while (lua_next(L, index)) { + if (!first) out += ','; first = false; + const int type = lua_type(L, -2); + if (type == LUA_TNUMBER) { + const float key = lua_tonumber(L, -2); + if (!std::isfinite(key) || key < 0 || key > 65535 || key != std::floor(key)) { lua_pop(L, 2); return false; } + WebbarJsonString(out, std::to_string(uint32_t(key))); + } else if (type == LUA_TSTRING) { + size_t length; const char* text = lua_tolstring(L, -2, &length); + if (length > 256) { lua_pop(L, 2); return false; } + WebbarJsonString(out, std::string(text, length)); + } else { lua_pop(L, 2); return false; } + out += ':'; + if (!JsonValue(-1, out, depth + 1, nodes)) { lua_pop(L, 2); return false; } + lua_pop(L, 1); + } + out += '}'; + } break; + default: return false; + } + return out.size() <= 1048576; + } +}; + +namespace WebbarNativeInfo { +constexpr uint32_t MAGIC = 0x31495157; // WQI1, separate optional bridge9 extension +struct Header { + uint32_t magic, version, request, generation; + int32_t team, allyTeam; + // Kind3 uses reserved[0] for the hovered definition (zero = all types). + uint32_t frame, kind, count, flags, reserved[2]; +}; +struct Row { uint32_t id, lifetime; }; +static_assert(sizeof(Header) == 48 && sizeof(Row) == 8); +static WebbarNativeInfoReader* reader = nullptr; + +static void Reply(const Header& h, uint32_t status, const std::string& data = "null") +{ + const bool full = gu->spectatingFullView; + const std::string json = "{\"version\":1,\"request\":" + std::to_string(h.request) + + ",\"generation\":" + std::to_string(h.generation) + ",\"kind\":" + std::to_string(h.kind) + + ",\"team\":" + std::to_string(gu->myTeam) + ",\"allyTeam\":" + std::to_string(gu->myAllyTeam) + + ",\"fullView\":" + (full ? "true" : "false") + ",\"frame\":" + std::to_string(gs->frameNum) + + ",\"status\":" + std::to_string(status) + ",\"data\":" + data + '}'; + MAIN_THREAD_EM_ASM({ if (Module['webbarNativeInfoResult']) Module['webbarNativeInfoResult'](UTF8ToString($0)); }, json.c_str()); +} + +// Read-only counterpart of ViewSelectionActionExecutor. Use actual native +// midPos, float3 arithmetic and the engine's selected-unit container type. +// No selection, camera controller, command or synced state is changed here. +static bool ViewSelection(const std::vector& ids, std::string& json) +{ + spring::unordered_set selected; + for (const auto id: ids) selected.insert(int(id)); + float3 position; + for (const auto id: selected) position += unitHandler.GetUnit(id)->midPos; + position *= (1.0f / selected.size()); + if (!std::isfinite(position.x) || !std::isfinite(position.y) || !std::isfinite(position.z)) return false; + // CSpringController::SetPos calls Update: its default terrain tracking + // clamps x/z and focuses on native terrain, not the unit midpoint height. + float3 focus = position; + focus.x = std::clamp(focus.x, 0.01f, mapDims.mapx * SQUARE_SIZE - 0.01f); + focus.z = std::clamp(focus.z, 0.01f, mapDims.mapy * SQUARE_SIZE - 0.01f); + focus.y = CGround::GetHeightReal(focus.x, focus.z, false); + json = "{\"definitions\":{},\"units\":{},\"camera\":{\"position\":{\"1\":"; + WebbarJsonNumber(json, position.x); json += ",\"2\":"; + WebbarJsonNumber(json, position.y); json += ",\"3\":"; + WebbarJsonNumber(json, position.z); json += "},\"focus\":{\"1\":"; + WebbarJsonNumber(json, focus.x); json += ",\"2\":"; + WebbarJsonNumber(json, focus.y); json += ",\"3\":"; + WebbarJsonNumber(json, focus.z); json += "},\"duration\":"; + WebbarJsonNumber(json, 0.6f); json += ",\"ids\":{"; + for (size_t i = 0; i < ids.size(); ++i) { + if (i) json += ','; + WebbarJsonString(json, std::to_string(i + 1)); json += ':' + std::to_string(ids[i]); + } + json += "}}}"; + return true; +} + +// A user click names the carrier/cargo and their complete native lifetimes. +// The original LuaUI code plans against current native reads; its commands +// enter the normal network/journal path together. No client position or +// arbitrary command sequence is admitted by this optional bridge9 extension. +static uint32_t Unload(uint32_t count, const uint32_t* words, uint32_t cargoID, uint32_t options, float x, float z, float radius, bool fromPlayerNetwork) +{ + if (std::getenv("WEBBAR_NATIVE_INFO_TRANSPORT") == nullptr || gu->spectating || webbarReplay::Enabled() || std::getenv("WEBBAR_NETWORK") != nullptr) return 5; + if (count != 1 || words[0] > 65535 || cargoID > 65535 || words[0] == cargoID || words[1] == 0 || words[1] == 0xffffffffu || words[2] == 0 || words[2] == 0xffffffffu) return 1; + if ((options & ~uint32_t(SHIFT_KEY)) || x != 0 || z != 0 || radius != 0) return 3; + for (int i = 3; i < 64; ++i) if (words[i] != 0) return 1; + const auto* carrier = unitHandler.GetUnit(words[0]); + const auto* cargo = unitHandler.GetUnit(cargoID); + if (!WebbarSelectable(carrier) || !cargo || cargo->isDead || cargo->GetTransporter() != carrier || WebbarHudLifetime(carrier) != words[1] || WebbarHudLifetime(cargo) != words[2]) return 4; + if (!reader) reader = new WebbarNativeInfoReader; + std::vector commands; + if (!reader->PlanUnload(words[0], cargoID, options & SHIFT_KEY, commands)) return 5; + selectedUnitsHandler.SendCommandsToUnits({int(words[0])}, commands, false, fromPlayerNetwork); + return 0; +} + +static void Poll() +{ + static const bool enabled = std::getenv("WEBBAR_NATIVE_INFO_READS") != nullptr; + if (!enabled || WebbarUiEvents::CatchingUp()) return; + // Batches64 for units/specifications; selections8192 carry kill facts and + // the original first50 resource sample. At most ten reads a second, including + // paused reads. No queue/world publication or simulation tick is added. + 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['webbarPollNativeInfo'] ? Module['webbarPollNativeInfo']($0, $1) : 0; }, bytes.data(), bytes.size()); + if (size <= 0 || size < int(sizeof(Header)) || size > int(bytes.size())) return; + 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; } + 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; } + 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; } + std::vector ids; + std::unordered_set seen; + for (uint32_t i = 0; i < h.count; ++i) { + Row row; std::memcpy(&row, bytes.data() + rowOffset + i * sizeof(Row), sizeof(Row)); + if (row.id > 65535 || !seen.insert(row.id).second || (h.kind == 2 && (row.id == 0 || row.lifetime != 0))) { Reply(h, 1); return; } + if (h.kind == 4 && (row.lifetime == 0 || !WebbarSelectable(unitHandler.GetUnit(row.id)))) { Reply(h, 2); return; } + if (h.kind != 2 && row.lifetime != 0) { + 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; } + } + 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 == 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; + 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; + valid = 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; + if (!valid) { Reply(h, 1); return; } + if (!reader->ReadWorld(view, ids, h.reserved[0], json)) { Reply(h, 4); return; } + Reply(h, 0, json); return; + } + if (!reader->Read(h.kind, ids, h.reserved[0], json)) { Reply(h, 4); return; } + Reply(h, 0, json); +} +} // namespace WebbarNativeInfo + +static void FreeWebbarNativeInfo() +{ + delete WebbarNativeInfo::reader; + WebbarNativeInfo::reader = nullptr; +}