443 lines
14 KiB
Lua
443 lines
14 KiB
Lua
local changeDelay = CreateConVar(
|
|
"gc_mapchangedelay",
|
|
"8",
|
|
FCVAR_ARCHIVE,
|
|
"Seconds between resolving the end-of-map vote and loading its winner"
|
|
)
|
|
|
|
local maxMapTime = CreateConVar(
|
|
"gc_mapmaxtime",
|
|
"3600",
|
|
FCVAR_ARCHIVE,
|
|
"Maximum map time in seconds before opening the map vote; 0 disables the time limit"
|
|
)
|
|
|
|
local skipVoteRatio = CreateConVar(
|
|
"gc_mapskipvoteratio",
|
|
"0.6",
|
|
FCVAR_ARCHIVE,
|
|
"Fraction of connected human players required to end the current map"
|
|
)
|
|
|
|
local mapVoteDuration = CreateConVar(
|
|
"gc_mapvoteduration",
|
|
"30",
|
|
FCVAR_ARCHIVE,
|
|
"Seconds players have to choose the next map"
|
|
)
|
|
|
|
local mapVoteChoiceCount = CreateConVar(
|
|
"gc_mapvotechoices",
|
|
"8",
|
|
FCVAR_ARCHIVE,
|
|
"Number of installed maps offered by the end-of-map vote (2-12)"
|
|
)
|
|
|
|
local mapPreviewBaseURL = CreateConVar(
|
|
"gc_mapvotepreviewurl",
|
|
"https://garrysmod.brunner.ninja/assets/map-previews",
|
|
FCVAR_ARCHIVE,
|
|
"Public HTTPS directory containing <mapname>.jpg vote previews"
|
|
)
|
|
|
|
util.AddNetworkString("CustomCoopMapVoteStart")
|
|
util.AddNetworkString("CustomCoopMapVoteCast")
|
|
util.AddNetworkString("CustomCoopMapVoteUpdate")
|
|
util.AddNetworkString("CustomCoopMapVoteResult")
|
|
|
|
local MAP_VOTE_TIMER = "CustomCoopMapVoteDeadline"
|
|
local MAP_CHANGE_TIMER = "CustomCoopChangeCompletedMap"
|
|
local MAP_CHANGE_WATCHDOG = "CustomCoopChangeLevelWatchdog"
|
|
local TRANSITION_RELAY_NAME = "custom_coop_map_vote_relay"
|
|
local TRANSITION_SENTINEL = "__custom_coop_vote__"
|
|
|
|
local skipVotes = {}
|
|
local failedMapChanges = {}
|
|
local installedMaps
|
|
local changeQueued = false
|
|
local voteActive = false
|
|
local voteID = math.random(1, 65535)
|
|
local voteEndsAt = 0
|
|
local voteReason = ""
|
|
local voteChoices = {}
|
|
local mapVotes = {}
|
|
local lastVoteAt = {}
|
|
|
|
local function RefreshInstalledMaps()
|
|
installedMaps = {}
|
|
for _, fileName in ipairs(file.Find("maps/*.bsp", "GAME")) do
|
|
installedMaps[string.lower(string.StripExtension(fileName))] = true
|
|
end
|
|
end
|
|
|
|
local function MapExists(mapName)
|
|
if not mapName or mapName == "" then return false end
|
|
if not installedMaps then RefreshInstalledMaps() end
|
|
local normalizedName = string.lower(string.StripExtension(mapName))
|
|
return installedMaps[normalizedName] == true and not failedMapChanges[normalizedName]
|
|
end
|
|
|
|
local function PlayerVoteID(ply)
|
|
local steamID64 = ply:SteamID64()
|
|
if steamID64 and steamID64 ~= "" then return steamID64 end
|
|
return "user:" .. tostring(ply:UserID())
|
|
end
|
|
|
|
local function RequiredSkipVotes()
|
|
local humanCount = #player.GetHumans()
|
|
local ratio = math.Clamp(skipVoteRatio:GetFloat(), 0.1, 1)
|
|
return math.max(math.ceil(humanCount * ratio), 1)
|
|
end
|
|
|
|
local function BuildMapVoteChoices()
|
|
local candidates = {}
|
|
local currentMap = string.lower(game.GetMap() or "")
|
|
|
|
for _, mapName in ipairs(GetInstalledCoopLevels()) do
|
|
if mapName ~= currentMap and MapExists(mapName) then
|
|
candidates[#candidates + 1] = mapName
|
|
end
|
|
end
|
|
|
|
for index = #candidates, 2, -1 do
|
|
local other = math.random(index)
|
|
candidates[index], candidates[other] = candidates[other], candidates[index]
|
|
end
|
|
|
|
local choices = {}
|
|
local limit = math.Clamp(mapVoteChoiceCount:GetInt(), 2, 12)
|
|
for index = 1, math.min(limit, #candidates) do
|
|
choices[index] = candidates[index]
|
|
end
|
|
return choices
|
|
end
|
|
|
|
local function ConnectedVoteCounts()
|
|
local counts = {}
|
|
local submitted = 0
|
|
for index = 1, #voteChoices do counts[index] = 0 end
|
|
|
|
for _, ply in ipairs(player.GetHumans()) do
|
|
local choice = mapVotes[PlayerVoteID(ply)]
|
|
if choice and voteChoices[choice] then
|
|
counts[choice] = counts[choice] + 1
|
|
submitted = submitted + 1
|
|
end
|
|
end
|
|
return counts, submitted
|
|
end
|
|
|
|
local function SendVoteStart(ply)
|
|
if not voteActive or not IsValid(ply) or ply:IsBot() then return end
|
|
|
|
net.Start("CustomCoopMapVoteStart")
|
|
net.WriteUInt(voteID, 16)
|
|
net.WriteFloat(math.max(voteEndsAt - CurTime(), 0))
|
|
net.WriteString(voteReason)
|
|
net.WriteString(mapPreviewBaseURL:GetString())
|
|
net.WriteUInt(#voteChoices, 4)
|
|
for _, mapName in ipairs(voteChoices) do
|
|
net.WriteString(mapName)
|
|
net.WriteString(tostring((COOP_WORKSHOP_IDS or {})[mapName] or ""))
|
|
end
|
|
net.Send(ply)
|
|
end
|
|
|
|
local function BroadcastVoteCounts()
|
|
if not voteActive then return end
|
|
local counts, submitted = ConnectedVoteCounts()
|
|
|
|
net.Start("CustomCoopMapVoteUpdate")
|
|
net.WriteUInt(voteID, 16)
|
|
net.WriteUInt(math.min(#player.GetHumans(), 255), 8)
|
|
net.WriteUInt(math.min(submitted, 255), 8)
|
|
net.WriteUInt(#counts, 4)
|
|
for _, count in ipairs(counts) do net.WriteUInt(math.min(count, 255), 8) end
|
|
net.Broadcast()
|
|
end
|
|
|
|
local function EveryoneHasVoted()
|
|
local humans = player.GetHumans()
|
|
if #humans == 0 then return false end
|
|
for _, ply in ipairs(humans) do
|
|
if not mapVotes[PlayerVoteID(ply)] then return false end
|
|
end
|
|
return true
|
|
end
|
|
|
|
local function BeginMapChange(destination, resolution)
|
|
changeQueued = true
|
|
RunConsoleCommand("nextlevel", destination)
|
|
|
|
local serverIsEmpty = #player.GetHumans() == 0
|
|
local delay = serverIsEmpty and 0 or math.max(changeDelay:GetFloat(), 0)
|
|
net.Start("CustomCoopMapVoteResult")
|
|
net.WriteUInt(voteID, 16)
|
|
net.WriteString(destination)
|
|
net.WriteString(resolution)
|
|
net.WriteFloat(delay)
|
|
net.Broadcast()
|
|
|
|
print(string.format(
|
|
"[custom_coop] Map vote selected %s (%s); changing in %.1f seconds",
|
|
destination,
|
|
resolution,
|
|
delay
|
|
))
|
|
|
|
timer.Create(MAP_CHANGE_TIMER, delay, 1, function()
|
|
local sourceMap = string.lower(game.GetMap() or "")
|
|
if serverIsEmpty then
|
|
RunConsoleCommand("changelevel", destination)
|
|
elseif CompleteCoopMapChange then
|
|
CompleteCoopMapChange(destination)
|
|
else
|
|
RunConsoleCommand("changelevel", destination)
|
|
end
|
|
|
|
timer.Create(MAP_CHANGE_WATCHDOG, 12, 1, function()
|
|
if string.lower(game.GetMap() or "") ~= sourceMap then return end
|
|
|
|
failedMapChanges[destination] = true
|
|
changeQueued = false
|
|
skipVotes = {}
|
|
if string.lower(GetConVar("nextlevel"):GetString()) == destination then
|
|
RunConsoleCommand("nextlevel", "")
|
|
end
|
|
|
|
PrintMessage(HUD_PRINTTALK, "[CO-OP] Could not load " .. destination .. "; opening a new map vote.")
|
|
ErrorNoHalt("[custom_coop] changelevel failed for " .. destination .. "; destination quarantined until restart\n")
|
|
timer.Simple(1, function() QueueCoopMapChange("Map load failed") end)
|
|
end)
|
|
end)
|
|
end
|
|
|
|
local function ResolveMapVote()
|
|
if not voteActive then return end
|
|
voteActive = false
|
|
timer.Remove(MAP_VOTE_TIMER)
|
|
|
|
local counts, submitted = ConnectedVoteCounts()
|
|
local winnerIndex
|
|
local resolution
|
|
|
|
if submitted > 0 then
|
|
for index, count in ipairs(counts) do
|
|
if count > submitted / 2 then
|
|
winnerIndex = index
|
|
resolution = "Majority choice"
|
|
break
|
|
end
|
|
end
|
|
|
|
if not winnerIndex then
|
|
local selected = {}
|
|
for index, count in ipairs(counts) do
|
|
if count > 0 then selected[#selected + 1] = index end
|
|
end
|
|
winnerIndex = selected[math.random(#selected)]
|
|
resolution = "No majority — randomly selected from the voted maps"
|
|
end
|
|
else
|
|
winnerIndex = math.random(#voteChoices)
|
|
resolution = "No votes — randomly selected from all choices"
|
|
end
|
|
|
|
BeginMapChange(voteChoices[winnerIndex], resolution)
|
|
end
|
|
|
|
local function StartMapVote(reason)
|
|
if voteActive or changeQueued then return false end
|
|
|
|
voteChoices = BuildMapVoteChoices()
|
|
if #voteChoices == 0 then
|
|
ErrorNoHalt("[custom_coop] Map completed, but no alternative installed co-op map is available\n")
|
|
return false
|
|
end
|
|
|
|
voteID = (voteID % 65535) + 1
|
|
voteActive = true
|
|
voteReason = reason or "Mission complete"
|
|
mapVotes = {}
|
|
lastVoteAt = {}
|
|
voteEndsAt = CurTime() + math.Clamp(mapVoteDuration:GetFloat(), 5, 120)
|
|
RunConsoleCommand("nextlevel", "")
|
|
|
|
if #player.GetHumans() == 0 then
|
|
ResolveMapVote()
|
|
return true
|
|
end
|
|
|
|
for _, ply in ipairs(player.GetHumans()) do SendVoteStart(ply) end
|
|
BroadcastVoteCounts()
|
|
timer.Create(MAP_VOTE_TIMER, math.max(voteEndsAt - CurTime(), 0), 1, ResolveMapVote)
|
|
print("[custom_coop] End-of-map vote started: " .. voteReason)
|
|
return true
|
|
end
|
|
|
|
function QueueCoopMapChange(reason)
|
|
return StartMapVote(reason)
|
|
end
|
|
|
|
local function CountCurrentSkipVotes()
|
|
local connectedPlayers = {}
|
|
for _, ply in ipairs(player.GetHumans()) do
|
|
connectedPlayers[PlayerVoteID(ply)] = true
|
|
end
|
|
|
|
local count = 0
|
|
for voterID in pairs(skipVotes) do
|
|
if connectedPlayers[voterID] then
|
|
count = count + 1
|
|
else
|
|
skipVotes[voterID] = nil
|
|
end
|
|
end
|
|
return count
|
|
end
|
|
|
|
local function CheckSkipVote()
|
|
if voteActive or changeQueued then return end
|
|
if CountCurrentSkipVotes() >= RequiredSkipVotes() then
|
|
StartMapVote("Players voted to skip")
|
|
end
|
|
end
|
|
|
|
local function CastSkipVote(ply)
|
|
if voteActive or changeQueued then
|
|
ply:ChatPrint("[CO-OP] The end-of-map vote is already underway.")
|
|
return
|
|
end
|
|
|
|
local voterID = PlayerVoteID(ply)
|
|
if skipVotes[voterID] then
|
|
ply:ChatPrint("[CO-OP] You have already voted to skip this map.")
|
|
return
|
|
end
|
|
|
|
skipVotes[voterID] = true
|
|
local voteCount = CountCurrentSkipVotes()
|
|
local required = RequiredSkipVotes()
|
|
PrintMessage(HUD_PRINTTALK, string.format(
|
|
"%s voted to skip this map (%d/%d). Type !skip to vote.",
|
|
ply:Nick(), voteCount, required
|
|
))
|
|
CheckSkipVote()
|
|
end
|
|
|
|
net.Receive("CustomCoopMapVoteCast", function(_, ply)
|
|
if not voteActive or not IsValid(ply) or ply:IsBot() then return end
|
|
if net.ReadUInt(16) ~= voteID then return end
|
|
|
|
local now = CurTime()
|
|
local voterID = PlayerVoteID(ply)
|
|
if now < (lastVoteAt[voterID] or 0) + 0.1 then return end
|
|
lastVoteAt[voterID] = now
|
|
|
|
local choice = net.ReadUInt(4)
|
|
if not voteChoices[choice] then return end
|
|
mapVotes[voterID] = choice
|
|
BroadcastVoteCounts()
|
|
|
|
if EveryoneHasVoted() then ResolveMapVote() end
|
|
end)
|
|
|
|
hook.Add("PlayerSay", "CustomCoopMapVoting", function(ply, text)
|
|
local command = string.lower(string.Trim(text or ""))
|
|
if command == "!skip" or command == "/skip" or command == "!skipmap" then
|
|
CastSkipVote(ply)
|
|
return ""
|
|
end
|
|
end)
|
|
|
|
hook.Add("PlayerInitialSpawn", "CustomCoopExplainMapVoting", function(ply)
|
|
timer.Simple(2, function()
|
|
if IsValid(ply) and voteActive then
|
|
SendVoteStart(ply)
|
|
BroadcastVoteCounts()
|
|
end
|
|
end)
|
|
timer.Simple(6, function()
|
|
if not IsValid(ply) then return end
|
|
ply:ChatPrint("[CO-OP] Type !skip if the current map is stuck. The next map is chosen on-screen when the mission ends.")
|
|
end)
|
|
end)
|
|
|
|
hook.Add("PlayerDisconnected", "CustomCoopRecountMapVotes", function(ply)
|
|
skipVotes[PlayerVoteID(ply)] = nil
|
|
mapVotes[PlayerVoteID(ply)] = nil
|
|
timer.Simple(0, function()
|
|
CheckSkipVote()
|
|
if voteActive then
|
|
BroadcastVoteCounts()
|
|
if EveryoneHasVoted() then ResolveMapVote() end
|
|
end
|
|
end)
|
|
end)
|
|
|
|
hook.Add("AcceptInput", "CustomCoopDetectMapCompletion", function(ent, inputName, _, _, value)
|
|
if not IsValid(ent) then return end
|
|
|
|
local className = string.lower(ent:GetClass())
|
|
local input = string.lower(inputName or "")
|
|
|
|
if className == "game_end" and input == "endgame" then
|
|
StartMapVote("Mission complete")
|
|
return true
|
|
end
|
|
|
|
if className == "point_changelevel" and (input == "changelevel" or input == "changelevelnow") then
|
|
StartMapVote("Mission complete")
|
|
return true
|
|
end
|
|
|
|
if className ~= "point_servercommand" or input ~= "command" then return end
|
|
local command = string.lower(string.Trim(tostring(value or "")))
|
|
if string.match(command, "^changelevel%s+") or string.match(command, "^map%s+") then
|
|
StartMapVote("Mission complete")
|
|
return true
|
|
end
|
|
end)
|
|
|
|
-- A trigger_changelevel performs its transition inside the engine instead of
|
|
-- issuing an interceptable console command. Point it at a guaranteed-missing
|
|
-- sentinel and add a Lua output which opens the normal vote when touched.
|
|
hook.Add("EntityKeyValue", "CustomCoopInterceptChangelevelTargets", function(ent, key, value)
|
|
if string.lower(ent:GetClass()) ~= "trigger_changelevel" then return end
|
|
if string.lower(key or "") ~= "map" then return end
|
|
ent.CustomCoopOriginalTransition = value
|
|
return TRANSITION_SENTINEL
|
|
end)
|
|
|
|
local function ArmChangelevelTriggers()
|
|
local relay = ents.FindByName(TRANSITION_RELAY_NAME)[1]
|
|
if not IsValid(relay) then
|
|
relay = ents.Create("lua_run")
|
|
if not IsValid(relay) then return end
|
|
relay:SetName(TRANSITION_RELAY_NAME)
|
|
relay:Spawn()
|
|
end
|
|
|
|
for _, ent in ipairs(ents.FindByClass("trigger_changelevel")) do
|
|
ent:Fire(
|
|
"AddOutput",
|
|
"OnStartTouch " .. TRANSITION_RELAY_NAME .. ":RunPassedCode:QueueCoopMapChange('Mission complete'):0:-1"
|
|
)
|
|
end
|
|
end
|
|
|
|
hook.Add("InitPostEntity", "CustomCoopStartMapRotation", function()
|
|
RunConsoleCommand("nextlevel", "")
|
|
ArmChangelevelTriggers()
|
|
|
|
local limit = maxMapTime:GetFloat()
|
|
if limit <= 0 then return end
|
|
timer.Create("CustomCoopMapTimeLimit", limit, 1, function()
|
|
StartMapVote("Map time limit reached")
|
|
end)
|
|
end)
|
|
|
|
hook.Add("PostCleanupMap", "CustomCoopRearmChangelevelTriggers", function()
|
|
timer.Simple(0, ArmChangelevelTriggers)
|
|
end)
|