Files

894 lines
32 KiB
Lua

if not SERVER then return end
local botCount = CreateConVar(
"gc_bot_count",
"2",
FCVAR_ARCHIVE,
"Number of clearly identified cooperative player bots",
0,
8
)
local legacyBotPrefix = "[BOT] "
-- These are deliberately plausible Steam-style handles rather than labels
-- announcing that they are server bots.
local botNames = {
"toasty_boi", "xX_barnaclebait_Xx", "cr0wbarEnjoyer", "mike.exe",
"shyCombine", "PIZZA_4_BREAKFAST", "gladosFan_2007", "[EU] 1tapLarry"
}
local managedBotNames = {}
for _, name in ipairs(botNames) do managedBotNames[name] = true end
local retiredBotNames = {
["Alyx's Intern"] = true, ["Crowbar Carl"] = true,
["Dr. Kleiner Jr."] = true, ["Lamar's Chauffeur"] = true,
["Definitely Human"] = true, ["Scanner Wrangler"] = true,
["Barney's Backup"] = true, ["Headcrab Snack"] = true
}
local ignoredEnemyClasses = {
npc_bullseye = true,
npc_combine_camera = true,
npc_enemyfinder = true
}
CustomCoopBotRuntime = CustomCoopBotRuntime or {}
CustomCoopBotRuntime.botState = CustomCoopBotRuntime.botState
or setmetatable({}, { __mode = "k" })
CustomCoopBotRuntime.humanTrails = CustomCoopBotRuntime.humanTrails
or setmetatable({}, { __mode = "k" })
CustomCoopBotRuntime.fakeProfiles = CustomCoopBotRuntime.fakeProfiles or {}
CustomCoopBotRuntime.nextNoveltyMusicAt = CustomCoopBotRuntime.nextNoveltyMusicAt or 0
local botState = CustomCoopBotRuntime.botState
local humanTrails = CustomCoopBotRuntime.humanTrails
local fakeProfiles = CustomCoopBotRuntime.fakeProfiles
local breadcrumbSpacingSquared = 24 * 24
local maximumBreadcrumbs = 512
local function IsManagedBot(ply)
if not IsValid(ply) or not ply:IsPlayer() or not ply:IsBot() then return false end
return ply.CustomCoopManagedBot == true
or managedBotNames[ply:Nick()] == true
or retiredBotNames[ply:Nick()] == true
or string.StartWith(ply:Nick(), legacyBotPrefix)
end
local function ManagedBots()
local result = {}
for _, ply in ipairs(player.GetBots()) do
if IsManagedBot(ply) then result[#result + 1] = ply end
end
return result
end
local function SelectRandomBotTrail()
-- Half the bots deliberately have no trail. The other half choose only
-- visible, effect-producing entries from the player shop catalogue.
if math.random(2) ~= 1 then return nil end
local progression = CustomCoopProgression
if not progression or not istable(progression.Trails) then return nil end
local trails = {}
for _, trail in ipairs(progression.Trails) do
if trail.material and trail.material ~= "" then trails[#trails + 1] = trail end
end
return #trails > 0 and trails[math.random(#trails)].id or nil
end
local function BotProfile(bot)
if not IsManagedBot(bot) then return end
local key = bot:Nick()
local profile = fakeProfiles[key]
if not profile then
profile = {
-- Existing history makes a bot look like it joined mid-campaign.
score = math.random(15, 2500),
playtime = math.random(20 * 60, 90 * 60 * 60),
modelID = nil,
trailID = nil,
lastUpdated = CurTime()
}
local progression = CustomCoopProgression
if progression then
if istable(progression.Models) and #progression.Models > 0 then
profile.modelID = progression.Models[math.random(#progression.Models)].id
end
end
fakeProfiles[key] = profile
end
-- Versioning applies the corrected 50/50 selection to profiles created
-- before this behaviour was introduced, including a live Lua refresh.
if profile.cosmeticVersion ~= 2 then
profile.trailID = SelectRandomBotTrail()
profile.cosmeticVersion = 2
end
return profile
end
local function SyncBotProfile(bot, profile)
if not IsValid(bot) or not profile then return end
local score = math.max(math.floor(profile.score or 0), 0)
local playtime = math.max(math.floor(profile.playtime or 0), 0)
local progression = CustomCoopProgression
local rank = progression and progression.GetRank
and progression.GetRank(score)
or "Newbie"
bot:SetNW2Int("CustomCoopScore", score)
bot:SetNW2Int("CustomCoopCredits", 0)
bot:SetNW2Int("CustomCoopPlaytime", playtime)
bot:SetNW2String("CustomCoopRank", rank)
bot:SetNW2String("CustomCoopTrail", profile.trailID or "none")
end
local function ApplyBotCosmetics(bot, profile)
if not IsValid(bot) or not profile then return end
local progression = CustomCoopProgression
local model = progression and progression.GetModel and progression.GetModel(profile.modelID)
if model and model.model and model.model ~= "" then bot:SetModel(model.model) end
if IsValid(bot.CustomCoopTrailEntity) then bot.CustomCoopTrailEntity:Remove() end
bot.CustomCoopTrailEntity = nil
local trail = progression and progression.GetTrail and progression.GetTrail(profile.trailID)
if not trail or trail.material == "" then return end
local startWidth = math.Clamp(tonumber(trail.startWidth) or 24, 1, 128)
local endWidth = math.Clamp(tonumber(trail.endWidth) or 2, 0, 128)
local lifetime = math.Clamp(tonumber(trail.lifetime) or 2.5, 0.1, 10)
bot.CustomCoopTrailEntity = util.SpriteTrail(
bot, 0, trail.color or color_white, trail.additive == true,
startWidth, endWidth, lifetime,
1 / math.max((startWidth + endWidth) * 0.5, 0.0001), trail.material .. ".vmt"
)
end
hook.Add("Think", "Feedc0deCoopBotRainbowTrails", function()
for _, bot in ipairs(ManagedBots()) do
local profile = BotProfile(bot)
local trail = profile and CustomCoopProgression
and CustomCoopProgression.GetTrail and CustomCoopProgression.GetTrail(profile.trailID)
if trail and trail.rainbow and IsValid(bot.CustomCoopTrailEntity) then
bot.CustomCoopTrailEntity:SetColor(
HSVToColor((CurTime() * 90 + bot:EntIndex() * 23) % 360, 1, 1)
)
end
end
end)
local function UpdateBotProfiles()
local now = CurTime()
for _, bot in ipairs(ManagedBots()) do
local profile = BotProfile(bot)
if profile then
local previous = profile.lastUpdated or now
profile.playtime = math.max(profile.playtime or 0, 0) + math.max(now - previous, 0)
profile.lastUpdated = now
SyncBotProfile(bot, profile)
if profile.cosmeticsAppliedVersion ~= profile.cosmeticVersion and bot:Alive() then
ApplyBotCosmetics(bot, profile)
profile.cosmeticsAppliedVersion = profile.cosmeticVersion
end
end
end
end
local function ResolveManagedBotAttacker(attacker, inflictor)
if IsManagedBot(attacker) then return attacker end
if IsValid(attacker) then
local owner = attacker:GetOwner()
if IsManagedBot(owner) then return owner end
if attacker:IsVehicle() then
local driver = attacker:GetDriver()
if IsManagedBot(driver) then return driver end
end
end
if IsValid(inflictor) then
local owner = inflictor:GetOwner()
if IsManagedBot(owner) then return owner end
end
end
hook.Add("OnNPCKilled", "Feedc0deCoopBotFakeScore", function(npc, attacker, inflictor)
if not IsValid(npc) or npc.CustomCoopNoScore or npc.CustomCoopBotScoreAwarded then return end
local progression = CustomCoopProgression
local reward = progression and progression.GetMonsterReward
and progression.GetMonsterReward(npc:GetClass())
if not reward then return end
local creator = npc:GetCreator()
if IsValid(creator) and creator:IsPlayer() then return end
local bot = ResolveManagedBotAttacker(attacker, inflictor)
if not IsManagedBot(bot) then return end
npc.CustomCoopBotScoreAwarded = true
local profile = BotProfile(bot)
if not profile then return end
profile.score = math.max(profile.score or 0, 0) + math.max(math.floor(reward), 1)
SyncBotProfile(bot, profile)
end)
local function MaintainBots()
if game.SinglePlayer() then return end
local bots = ManagedBots()
-- Bots cannot be renamed through the player API. Replace legacy and
-- retired-name instances once; current bots retain their state.
for index = #bots, 1, -1 do
if string.StartWith(bots[index]:Nick(), legacyBotPrefix)
or retiredBotNames[bots[index]:Nick()] then
bots[index]:Kick("Refreshing co-op bot profile")
table.remove(bots, index)
end
end
local maximum = math.max(game.MaxPlayers() - #player.GetHumans() - 1, 0)
local wanted = math.min(math.Clamp(botCount:GetInt(), 0, #botNames), maximum)
while #bots > wanted do
local bot = table.remove(bots)
if IsValid(bot) then bot:Kick("Coop bot count reduced") end
end
local usedNames = {}
for _, ply in ipairs(player.GetAll()) do usedNames[ply:Nick()] = true end
for index = #bots + 1, wanted do
local name = botNames[index]
if usedNames[name] then name = name .. " " .. index end
local bot = player.CreateNextBot(name)
if IsValid(bot) then
bot.CustomCoopManagedBot = true
local profile = BotProfile(bot)
if profile then profile.lastUpdated = CurTime() end
SyncBotProfile(bot, profile)
ApplyBotCosmetics(bot, profile)
usedNames[name] = true
end
end
end
local function ClosestHuman(bot)
local closest
local closestDistance
for _, ply in ipairs(player.GetHumans()) do
if ply:Alive() then
local distance = bot:GetPos():DistToSqr(ply:GetPos())
if not closestDistance or distance < closestDistance then
closest = ply
closestDistance = distance
end
end
end
return closest, closestDistance
end
local function ResetHumanTrail(ply)
if not IsValid(ply) or ply:IsBot() then return end
humanTrails[ply] = {
points = {
{ position = Vector(ply:GetPos()), recordedAt = CurTime() }
},
lastPosition = Vector(ply:GetPos())
}
end
local function RecordHumanTrails()
local now = CurTime()
for _, ply in ipairs(player.GetHumans()) do
if ply:Alive() then
local trail = humanTrails[ply]
if not trail then
ResetHumanTrail(ply)
trail = humanTrails[ply]
end
local position = ply:GetPos()
if position:DistToSqr(trail.lastPosition) >= breadcrumbSpacingSquared then
trail.points[#trail.points + 1] = {
position = Vector(position),
recordedAt = now
}
trail.lastPosition = Vector(position)
while #trail.points > maximumBreadcrumbs do table.remove(trail.points, 1) end
end
end
end
end
timer.Create("Feedc0deCoopBotHumanBreadcrumbs", 0.1, 0, RecordHumanTrails)
hook.Add("PlayerSpawn", "Feedc0deCoopBotResetHumanTrail", function(ply)
if ply:IsBot() then return end
timer.Simple(0.1, function()
if IsValid(ply) and ply:Alive() then ResetHumanTrail(ply) end
end)
end)
hook.Add("PlayerDisconnected", "Feedc0deCoopBotForgetHumanTrail", function(ply)
humanTrails[ply] = nil
if IsManagedBot(ply) then
local profile = fakeProfiles[ply:Nick()]
if profile then profile.lastUpdated = nil end
end
end)
local function RoutePointVisible(bot, human, position)
local players = player.GetAll()
local trace = util.TraceHull({
start = bot:GetPos() + Vector(0, 0, 42),
endpos = position + Vector(0, 0, 42),
mins = Vector(-8, -8, -12),
maxs = Vector(8, 8, 12),
filter = players,
mask = MASK_PLAYERSOLID
})
return not trace.Hit
end
local function FollowPosition(bot, human)
if RoutePointVisible(bot, human, human:GetPos()) then
return human:WorldSpaceCenter(), false
end
local trail = humanTrails[human]
local points = trail and trail.points
if not points or #points == 0 then return human:WorldSpaceCenter(), false end
-- Start with the newest breadcrumb that is directly reachable from the
-- bot's current corridor, then aim one short segment beyond it. The extra
-- segment makes the bot actually round a corner instead of stopping just
-- before it. Large discontinuities are teleports, so those are never
-- skipped: the bot must touch the entry point itself.
for index = #points, 1, -1 do
local point = points[index]
if CurTime() - point.recordedAt <= 300
and RoutePointVisible(bot, human, point.position) then
local target = point.position
local following = points[index + 1]
if following and target:DistToSqr(following.position) <= 144 * 144 then
target = following.position
end
return target + Vector(0, 0, 40), true
end
end
return human:WorldSpaceCenter(), false
end
local function VisibleAimPosition(bot, target)
if not IsValid(target) then return false end
local position = target:BodyTarget(bot:GetShootPos())
local trace = util.TraceLine({
start = bot:GetShootPos(),
endpos = position,
filter = bot,
mask = MASK_SHOT
})
return trace.Entity == target, position
end
local function ClosestEnemy(bot)
local closest
local closestDistance
local relationshipTarget = ClosestHuman(bot) or bot
for _, candidate in ipairs(ents.FindInSphere(bot:GetPos(), 1400)) do
if candidate:IsNPC()
and candidate:Health() > 0
and not ignoredEnemyClasses[candidate:GetClass()]
and candidate:Disposition(relationshipTarget) == D_HT
and VisibleAimPosition(bot, candidate)
then
local distance = bot:GetPos():DistToSqr(candidate:GetPos())
if not closestDistance or distance < closestDistance then
closest = candidate
closestDistance = distance
end
end
end
return closest, closestDistance
end
local function MovementBlocked(bot, direction)
local trace = util.TraceHull({
start = bot:GetPos() + Vector(0, 0, 8),
endpos = bot:GetPos() + direction * 56 + Vector(0, 0, 8),
mins = Vector(-16, -16, 0),
maxs = Vector(16, 16, 64),
filter = bot,
mask = MASK_PLAYERSOLID
})
return trace.Hit
end
local function DoorOrButtonAhead(bot, direction)
local trace = util.TraceLine({
start = bot:GetShootPos(),
endpos = bot:GetShootPos() + direction * 80,
filter = player.GetAll(),
mask = MASK_PLAYERSOLID
})
if not IsValid(trace.Entity) then return false end
local className = trace.Entity:GetClass()
return className == "prop_door_rotating"
or className == "func_door"
or className == "func_door_rotating"
or className == "func_button"
or className == "func_rot_button"
end
local function ForceObstacleHop(bot, state, direction, now)
state.duckUntil = now + 0.45
if not bot:OnGround() or (state.nextForcedHop or 0) > now then return end
state.nextForcedHop = now + 0.65
-- StartCommand's jump bit is enough for normal ledges. This small,
-- rate-limited impulse handles workshop props whose collision hulls eat
-- the button-driven jump before the fake client leaves the ground.
bot:SetVelocity(direction * 90 + Vector(0, 0, math.max(bot:GetJumpPower(), 210)))
end
local weaponPriority = {
weapon_crowbar = 15,
weapon_stunstick = 12,
weapon_pistol = 25,
weapon_357 = 58,
weapon_smg1 = 45,
weapon_ar2 = 72,
weapon_shotgun = 68,
weapon_crossbow = 62,
weapon_frag = 52,
weapon_rpg = 85,
coop_glock = 28,
coop_p228 = 30,
coop_usp = 32,
coop_fiveseven = 34,
coop_mac10 = 44,
coop_mp5 = 48,
coop_famas = 66,
coop_ak47 = 70,
coop_m4 = 69,
coop_deagle = 60,
coop_pumpshotgun = 67,
coop_autoshotgun = 76,
coop_para = 80
}
local meleeWeapons = {
weapon_crowbar = true,
weapon_stunstick = true,
npc_knife = true,
weapon_lightsaber = true
}
local ignoredWeaponPickups = {
gmod_camera = true,
gmod_tool = true,
weapon_physgun = true
}
local pickupClasses = {
item_healthkit = "health",
item_healthvial = "health",
item_battery = "armour",
item_ammo_crate = "ammo",
item_ammo_pistol = "ammo",
item_ammo_pistol_large = "ammo",
item_ammo_smg1 = "ammo",
item_ammo_smg1_large = "ammo",
item_ammo_smg1_grenade = "ammo",
item_ammo_ar2 = "ammo",
item_ammo_ar2_large = "ammo",
item_ammo_ar2_altfire = "ammo",
item_box_buckshot = "ammo",
item_ammo_357 = "ammo",
item_ammo_357_large = "ammo",
item_ammo_crossbow = "ammo",
item_rpg_round = "ammo"
}
local function WeaponCanFire(bot, weapon)
if not IsValid(weapon) then return false end
if meleeWeapons[weapon:GetClass()] then return true end
if weapon:Clip1() > 0 then return true end
local ammoType = weapon:GetPrimaryAmmoType()
if ammoType and ammoType >= 0 then return bot:GetAmmoCount(ammoType) > 0 end
return weapon:Clip1() == -1
end
local function WeaponScore(weapon)
if not IsValid(weapon) then return -1 end
return weaponPriority[weapon:GetClass()] or 35
end
local function SelectBestWeapon(bot, state, now)
local active = bot:GetActiveWeapon()
if (state.nextWeaponChoice or 0) > now and WeaponCanFire(bot, active) then return active end
state.nextWeaponChoice = now + 0.4
local best = WeaponCanFire(bot, active) and active or nil
local bestScore = WeaponScore(best)
for _, weapon in ipairs(bot:GetWeapons()) do
local score = WeaponScore(weapon)
if WeaponCanFire(bot, weapon) and score > bestScore then
best = weapon
bestScore = score
end
end
if IsValid(best) and best ~= active then bot:SelectWeapon(best:GetClass()) end
return best
end
local function PickupWanted(bot, candidate, activeWeapon)
if candidate:IsWeapon() then
if IsValid(candidate:GetOwner()) then return false end
local creator = candidate:GetCreator()
if IsValid(creator) and creator:IsPlayer() then return false end
return not ignoredWeaponPickups[candidate:GetClass()]
and not bot:HasWeapon(candidate:GetClass())
end
local pickupType = pickupClasses[candidate:GetClass()]
if pickupType == "health" then return bot:Health() < bot:GetMaxHealth() end
if pickupType == "armour" then return bot:Armor() < 75 end
if pickupType == "ammo" then
if not WeaponCanFire(bot, activeWeapon) then return true end
if not IsValid(activeWeapon) then return true end
local ammoType = activeWeapon:GetPrimaryAmmoType()
return ammoType and ammoType >= 0 and bot:GetAmmoCount(ammoType) < 20
end
return false
end
local function ClosestUsefulPickup(bot, activeWeapon, state, now)
local closest
local closestDistance
for _, candidate in ipairs(ents.FindInSphere(bot:GetPos(), 800)) do
if IsValid(candidate)
and not (candidate == state.ignoredPickup and (state.ignorePickupUntil or 0) > now)
and PickupWanted(bot, candidate, activeWeapon)
and RoutePointVisible(bot, bot, candidate:GetPos()) then
local distance = bot:GetPos():DistToSqr(candidate:GetPos())
if not closestDistance or distance < closestDistance then
closest = candidate
closestDistance = distance
end
end
end
return closest, closestDistance
end
local function CatchUpToHuman(bot)
local human = ClosestHuman(bot)
if not IsValid(human) or not human:OnGround() then return false end
local offsets = {
Vector(48, 0, 0),
Vector(-48, 0, 0),
Vector(0, 48, 0),
Vector(0, -48, 0),
Vector(64, 64, 0),
Vector(-64, -64, 0),
Vector(64, -64, 0),
Vector(-64, 64, 0)
}
for _, offset in ipairs(offsets) do
local probe = human:GetPos() + offset
local floor = util.TraceLine({
start = probe + Vector(0, 0, 32),
endpos = probe - Vector(0, 0, 96),
filter = { bot, human },
mask = MASK_PLAYERSOLID
})
if floor.Hit and not floor.StartSolid and floor.HitNormal.z > 0.45 then
local position = floor.HitPos + Vector(0, 0, 1)
local clearance = util.TraceHull({
start = position,
endpos = position,
mins = Vector(-16, -16, 0),
maxs = Vector(16, 16, 72),
filter = { bot, human },
mask = MASK_PLAYERSOLID
})
if not clearance.StartSolid and util.IsInWorld(position) then
bot:SetPos(position)
return true
end
end
end
return false
end
hook.Add("StartCommand", "Feedc0deCoopBotControl", function(bot, command)
if not IsManagedBot(bot) or not bot:Alive() then return end
command:ClearButtons()
command:ClearMovement()
local state = botState[bot] or {}
botState[bot] = state
local now = CurTime()
local activeWeapon = SelectBestWeapon(bot, state, now)
if (state.nextEnemySearch or 0) <= now then
state.enemy, state.enemyDistance = ClosestEnemy(bot)
state.nextEnemySearch = now + 0.35
end
local target = IsValid(state.enemy) and state.enemy or nil
local distanceSquared = state.enemyDistance
local targetPosition
local attacking = false
local followingHuman = false
local seekingPickup = false
if target and target:Health() > 0 then
attacking, targetPosition = VisibleAimPosition(bot, target)
if attacking then
distanceSquared = bot:GetPos():DistToSqr(target:GetPos())
else
state.enemy = nil
target = nil
end
end
if attacking and not WeaponCanFire(bot, activeWeapon) then
local pickup
pickup, distanceSquared = ClosestUsefulPickup(bot, activeWeapon, state, now)
if IsValid(pickup) then
target = pickup
targetPosition = pickup:WorldSpaceCenter()
attacking = false
seekingPickup = true
state.hasBreadcrumbRoute = false
end
end
if not target then
local human, humanDistanceSquared = ClosestHuman(bot)
local pickup
-- Collect gear only while staying near the player. A tempting weapon
-- must never replace the human as a long-distance navigation target.
if not humanDistanceSquared or humanDistanceSquared <= 450 * 450 then
pickup, distanceSquared = ClosestUsefulPickup(bot, activeWeapon, state, now)
end
if IsValid(pickup) then
target = pickup
targetPosition = pickup:WorldSpaceCenter()
seekingPickup = true
state.hasBreadcrumbRoute = false
else
target, distanceSquared = human, humanDistanceSquared
if IsValid(target) then
targetPosition, state.hasBreadcrumbRoute = FollowPosition(bot, target)
distanceSquared = bot:GetPos():DistToSqr(targetPosition)
followingHuman = true
end
end
end
if not targetPosition then return end
local direction = targetPosition - bot:GetShootPos()
local aim = direction:Angle()
aim.p = math.Clamp(math.NormalizeAngle(aim.p), -85, 85)
aim.r = 0
command:SetViewAngles(aim)
bot:SetEyeAngles(aim)
local buttons = 0
if (state.duckUntil or 0) > now then buttons = bit.bor(buttons, IN_DUCK) end
local wantsMovement = false
local needsReload = IsValid(activeWeapon)
and activeWeapon:Clip1() == 0
and activeWeapon:GetPrimaryAmmoType() >= 0
and bot:GetAmmoCount(activeWeapon:GetPrimaryAmmoType()) > 0
if needsReload then
buttons = bit.bor(buttons, IN_RELOAD)
elseif attacking and WeaponCanFire(bot, activeWeapon) then
buttons = bit.bor(buttons, IN_ATTACK)
end
local horizontal = Vector(direction.x, direction.y, 0)
if horizontal:LengthSqr() > 1 then horizontal:Normalize() end
if followingHuman then
local verticalDifference = target:GetPos().z - bot:GetPos().z
local humanDistanceSquared = bot:GetPos():DistToSqr(target:GetPos())
local badlySeparated = humanDistanceSquared > 650 * 650 or math.abs(verticalDifference) > 220
if badlySeparated then
state.separatedSince = state.separatedSince or now
local catchUpDelay = state.hasBreadcrumbRoute and 12 or 4
if now - state.separatedSince >= catchUpDelay
and (state.nextCatchUpAttempt or 0) <= now then
state.nextCatchUpAttempt = now + 1
if CatchUpToHuman(bot) then
state.separatedSince = nil
return
end
end
else
state.separatedSince = nil
end
-- Direct steering otherwise tends to hesitate at ledges because it
-- has no navmesh route saying that the human deliberately dropped.
if verticalDifference < -72 then
command:SetForwardMove(300)
buttons = bit.bor(buttons, IN_JUMP)
wantsMovement = true
end
else
state.separatedSince = nil
end
local movementDistance = attacking and 420
or seekingPickup and 34
or followingHuman and state.hasBreadcrumbRoute and 48
or 190
if distanceSquared and distanceSquared > movementDistance * movementDistance then
command:SetForwardMove(260)
wantsMovement = true
if MovementBlocked(bot, horizontal) then
if DoorOrButtonAhead(bot, horizontal) then
buttons = bit.bor(buttons, IN_USE)
command:SetForwardMove(140)
else
buttons = bit.bor(buttons, IN_JUMP, IN_DUCK)
ForceObstacleHop(bot, state, horizontal, now)
command:SetSideMove(state.strafeRight == false and -220 or 220)
end
if (state.nextStrafeChange or 0) <= now then
state.strafeRight = not state.strafeRight
state.nextStrafeChange = now + math.Rand(0.8, 1.8)
end
end
elseif attacking and distanceSquared and distanceSquared < 150 * 150 then
command:SetForwardMove(-120)
end
if seekingPickup and IsValid(target) and distanceSquared and distanceSquared <= 100 * 100
and target:GetClass() == "item_ammo_crate" then
buttons = bit.bor(buttons, IN_USE)
elseif not attacking and IsValid(activeWeapon)
and activeWeapon:Clip1() >= 0
and activeWeapon:Clip1() < math.max(activeWeapon:GetMaxClip1() * 0.35, 1)
and activeWeapon:GetPrimaryAmmoType() >= 0
and bot:GetAmmoCount(activeWeapon:GetPrimaryAmmoType()) > 0 then
buttons = bit.bor(buttons, IN_RELOAD)
end
if wantsMovement then
local position = bot:GetPos()
if not state.progressPosition or position:DistToSqr(state.progressPosition) >= 20 * 20 then
state.progressPosition = position
state.lastProgressAt = now
elseif now - (state.lastProgressAt or now) >= 0.8 then
buttons = bit.bor(buttons, IN_JUMP, IN_DUCK)
ForceObstacleHop(bot, state, horizontal, now)
command:SetForwardMove(-80)
command:SetSideMove(state.strafeRight == false and -280 or 280)
if (state.nextStrafeChange or 0) <= now then
state.strafeRight = not state.strafeRight
state.nextStrafeChange = now + math.Rand(0.6, 1.2)
end
if DoorOrButtonAhead(bot, horizontal) then buttons = bit.bor(buttons, IN_USE) end
if seekingPickup and now - (state.lastProgressAt or now) >= 2.5 then
state.ignoredPickup = target
state.ignorePickupUntil = now + 20
state.progressPosition = bot:GetPos()
state.lastProgressAt = now
return
end
if followingHuman and now - (state.lastProgressAt or now) >= 8 then
if CatchUpToHuman(bot) then
state.progressPosition = bot:GetPos()
state.lastProgressAt = now
return
end
end
end
else
state.progressPosition = bot:GetPos()
state.lastProgressAt = now
end
command:SetButtons(buttons)
end)
hook.Add("PlayerSpawn", "Feedc0deCoopBotLoadout", function(bot)
if not IsManagedBot(bot) then return end
local profile = BotProfile(bot)
SyncBotProfile(bot, profile)
timer.Simple(0.5, function()
if not IsValid(bot) or not bot:Alive() then return end
ApplyBotCosmetics(bot, profile)
CatchUpToHuman(bot)
bot:SetJumpPower(math.max(bot:GetJumpPower(), 210))
if not bot:HasWeapon("weapon_smg1") then bot:Give("weapon_smg1") end
bot:GiveAmmo(120, "SMG1", true)
bot:SelectWeapon("weapon_smg1")
end)
end)
-- A 1% roll each minute, with a shared 30 minute floor, makes Trolololo an
-- occasional surprise instead of a recurring soundtrack.
timer.Create("Feedc0deCoopBotNoveltyMusic", 60, 0, function()
local runtime = CustomCoopBotRuntime
if CurTime() < runtime.nextNoveltyMusicAt or math.random(100) ~= 1 then return end
local progression = CustomCoopProgression
local music = progression and progression.GetMusic and progression.GetMusic("trololo")
local playMusic = progression and progression.PlayMusic
local bots = ManagedBots()
if not music or not playMusic or #bots == 0 then return end
local bot = bots[math.random(#bots)]
if IsValid(bot) and bot:Alive() then
if playMusic(bot, music, "") then
runtime.nextNoveltyMusicAt = CurTime() + 30 * 60
end
end
end)
hook.Add("PlayerDeath", "Feedc0deCoopBotRespawn", function(bot)
if not IsManagedBot(bot) then return end
timer.Simple(3, function()
if not IsValid(bot) or bot:Alive() then return end
bot:Spawn()
end)
end)
local function RecoverStalledBots()
local now = CurTime()
for _, bot in ipairs(ManagedBots()) do
if bot:Alive() then
local human, distanceSquared = ClosestHuman(bot)
local state = botState[bot] or {}
botState[bot] = state
local position = bot:GetPos()
if not IsValid(human) or not distanceSquared or distanceSquared <= 300 * 300 then
state.recoveryPosition = position
state.recoveryProgressAt = now
state.recoveryFarSince = nil
else
if not state.recoveryPosition
or position:DistToSqr(state.recoveryPosition) >= 24 * 24 then
state.recoveryPosition = position
state.recoveryProgressAt = now
end
if distanceSquared > 700 * 700 then
state.recoveryFarSince = state.recoveryFarSince or now
else
state.recoveryFarSince = nil
end
local stalled = now - (state.recoveryProgressAt or now) >= 6
local veryFar = state.recoveryFarSince and now - state.recoveryFarSince >= 4
if (stalled or veryFar) and CatchUpToHuman(bot) then
state.recoveryPosition = bot:GetPos()
state.recoveryProgressAt = now
state.recoveryFarSince = nil
state.separatedSince = nil
state.progressPosition = bot:GetPos()
state.lastProgressAt = now
end
end
end
end
end
hook.Add("Initialize", "Feedc0deCoopBotsInitialize", function()
timer.Simple(2, MaintainBots)
end)
timer.Create("Feedc0deCoopBotsMaintain", 10, 0, MaintainBots)
timer.Create("Feedc0deCoopBotsRecoverStalls", 1, 0, RecoverStalledBots)
timer.Create("Feedc0deCoopBotFakeProfiles", 1, 0, UpdateBotProfiles)
cvars.AddChangeCallback("gc_bot_count", function()
timer.Simple(0, MaintainBots)
end, "Feedc0deCoopBotsCount")
concommand.Remove("coop_bots_refresh")
concommand.Add("coop_bots_refresh", function(ply)
if IsValid(ply) and not ply:IsAdmin() then return end
MaintainBots()
end)