-- Conservative per-arm GEOMETRIC HEURISTIC, NOT a native parent relationship. -- Descriptors must already be linked to actual live Units by spatial_runtime. -- No blanket body-separation gate, no remembered ownership, no HP/order matching. local P={radius=6,margin=3,max_mechs=8,max_arms=16} local function same(a,b)return a and b and a.entity==b.entity and a.goid==b.goid and a.unit==b.unit and a.resource==b.resource end local function finite(v)return type(v)=='number'and v==v and math.abs(v)<=1000000 end local function pos(v)return type(v)=='table'and finite(v[1])and finite(v[2])and finite(v[3])end local function distance(a,b)local x,y,z=a[1]-b[1],a[2]-b[2],a[3]-b[3];return math.sqrt(x*x+y*y+z*z)end P.distance=distance function P.key(d)return d.resource..':'..string.format('%.0f:%.0f:%.0f',d.entity,d.goid,d.unit)end function P.select(current,mechs,arms,side_by_resource) local meta={heuristic=true,policy='PER_ARM_MARGIN_V2',separation_gate=false,radius=P.radius,margin=P.margin,mech_distances={},distances={}} local function no(reason)return nil,reason,meta end if #mechs<1 or #mechs>P.max_mechs or #arms<1 or #arms>P.max_arms then return no('SPATIAL_COUNT_BOUND')end local seen={};local here for _,m in ipairs(mechs)do if not pos(m.position)or seen[m.descriptor.entity]then return no('SPATIAL_INVALID_MECH')end seen[m.descriptor.entity]=true if same(current,m.descriptor)then if here then return no('SPATIAL_DUPLICATE_CURRENT')end;here=m end end if not here then return no('SPATIAL_CURRENT_NOT_FOUND')end for _,m in ipairs(mechs)do if m~=here then local d=distance(here.position,m.position) meta.mech_distances[#meta.mech_distances+1]={entity=m.descriptor.entity,goid=m.descriptor.goid,distance=d} if not meta.nearest_mech_distance or d=P.margin then row.decision='EXCLUDED_CLOSER_TO_OTHER' elseif other and other-dist