initial commit - cross reference with 5th port - obviously has compile errors

This commit is contained in:
LetterJay
2016-07-03 02:17:19 -05:00
commit 35a1723e98
4355 changed files with 2221257 additions and 0 deletions
+50
View File
@@ -0,0 +1,50 @@
// Clickable stat() button.
/obj/effect/statclick
var/target
/obj/effect/statclick/New(text, target)
name = text
src.target = target
/obj/effect/statclick/proc/update(text)
name = text
return src
/obj/effect/statclick/debug
var/class
/obj/effect/statclick/debug/Click()
if(!usr.client.holder)
return
if(!class)
if(istype(target, /datum/subsystem))
class = "subsystem"
else if(istype(target, /datum/controller))
class = "controller"
else if(istype(target, /datum))
class = "datum"
else
class = "unknown"
usr.client.debug_variables(target)
message_admins("Admin [key_name_admin(usr)] is debugging the [target] [class].")
// Debug verbs.
/client/proc/restart_controller(controller in list("Master", "Failsafe"))
set category = "Debug"
set name = "Restart Controller"
set desc = "Restart one of the various periodic loop controllers for the game (be careful!)"
if(!holder)
return
switch(controller)
if("Master")
new/datum/controller/master()
Master.process()
feedback_add_details("admin_verb","RMC")
if("Failsafe")
new /datum/controller/failsafe()
feedback_add_details("admin_verb","RFailsafe")
message_admins("Admin [key_name_admin(usr)] has restarted the [controller] controller.")
+779
View File
@@ -0,0 +1,779 @@
//Configuraton defines //TODO: Move all yes/no switches into bitflags
//Used by jobs_have_maint_access
#define ASSISTANTS_HAVE_MAINT_ACCESS 1
#define SECURITY_HAS_MAINT_ACCESS 2
#define EVERYONE_HAS_MAINT_ACCESS 4
//Not accessible from usual debug controller verb
/datum/protected_configuration
var/autoadmin = 0
var/autoadmin_rank = "Game Admin"
/datum/configuration
var/name = "Configuration" // datum name
var/server_name = null // server name (the name of the game window)
var/station_name = null // station name (the name of the station in-game)
var/server_suffix = 0 // generate numeric suffix based on server port
var/lobby_countdown = 120 // In between round countdown.
var/round_end_countdown = 25 // Post round murder death kill countdown
var/log_ooc = 0 // log OOC channel
var/log_access = 0 // log login/logout
var/log_say = 0 // log client say
var/log_admin = 0 // log admin actions
var/log_game = 0 // log game events
var/log_vote = 0 // log voting
var/log_whisper = 0 // log client whisper
var/log_prayer = 0 // log prayers
var/log_law = 0 // log lawchanges
var/log_emote = 0 // log emotes
var/log_attack = 0 // log attack messages
var/log_adminchat = 0 // log admin chat messages
var/log_pda = 0 // log pda messages
var/log_hrefs = 0 // log all links clicked in-game. Could be used for debugging and tracking down exploits
var/log_world_topic = 0 // log all world.Topic() calls
var/sql_enabled = 0 // for sql switching
var/allow_admin_ooccolor = 0 // Allows admins with relevant permissions to have their own ooc colour
var/allow_vote_restart = 0 // allow votes to restart
var/allow_vote_mode = 0 // allow votes to change mode
var/vote_delay = 6000 // minimum time between voting sessions (deciseconds, 10 minute default)
var/vote_period = 600 // length of voting period (deciseconds, default 1 minute)
var/vote_no_default = 0 // vote does not default to nochange/norestart (tbi)
var/vote_no_dead = 0 // dead people can't vote (tbi)
var/del_new_on_log = 1 // del's new players if they log before they spawn in
var/allow_Metadata = 0 // Metadata is supported.
var/popup_admin_pm = 0 //adminPMs to non-admins show in a pop-up 'reply' window when set to 1.
var/fps = 20
var/allow_holidays = 0 //toggles whether holiday-specific content should be used
var/hostedby = null
var/respawn = 1
var/guest_jobban = 1
var/usewhitelist = 0
var/kick_inactive = 0 //force disconnect for inactive players
var/load_jobs_from_txt = 0
var/automute_on = 0 //enables automuting/spam prevention
var/minimal_access_threshold = 0 //If the number of players is larger than this threshold, minimal access will be turned on.
var/jobs_have_minimal_access = 0 //determines whether jobs use minimal access or expanded access.
var/jobs_have_maint_access = 0 //Who gets maint access? See defines above.
var/sec_start_brig = 0 //makes sec start in brig or dept sec posts
var/server
var/banappeals
var/wikiurl = "http://www.tgstation13.org/wiki" // Default wiki link.
var/forumurl = "http://tgstation13.org/phpBB/index.php" //default forums
var/rulesurl = "http://www.tgstation13.org/wiki/Rules" // default rules
var/githuburl = "https://www.github.com/tgstation/-tg-station" //default github
var/forbid_singulo_possession = 0
var/useircbot = 0
//IP Intel vars
var/ipintel_email
var/ipintel_rating_bad = 1
var/ipintel_save_good = 12
var/ipintel_save_bad = 1
var/ipintel_domain = "check.getipintel.net"
var/admin_legacy_system = 0 //Defines whether the server uses the legacy admin system with admins.txt or the SQL system. Config option in config.txt
var/ban_legacy_system = 0 //Defines whether the server uses the legacy banning system with the files in /data or the SQL system. Config option in config.txt
var/use_age_restriction_for_jobs = 0 //Do jobs use account age restrictions? --requires database
var/see_own_notes = 0 //Can players see their own admin notes (read-only)? Config option in config.txt
//Population cap vars
var/soft_popcap = 0
var/hard_popcap = 0
var/extreme_popcap = 0
var/soft_popcap_message = "Be warned that the server is currently serving a high number of users, consider using alternative game servers."
var/hard_popcap_message = "The server is currently serving a high number of users, You cannot currently join. You may wait for the number of living crew to decline, observe, or find alternative servers."
var/extreme_popcap_message = "The server is currently serving a high number of users, find alternative servers."
//game_options.txt configs
var/force_random_names = 0
var/list/mode_names = list()
var/list/modes = list() // allowed modes
var/list/votable_modes = list() // votable modes
var/list/probabilities = list() // relative probability of each mode
var/humans_need_surnames = 0
var/allow_ai = 0 // allow ai job
var/forbid_secborg = 0 // disallow secborg module to be chosen.
var/forbid_peaceborg = 0
var/panic_bunker = 0 // prevents new people it hasn't seen before from connecting
var/notify_new_player_age = 0 // how long do we notify admins of a new player
var/irc_first_connection_alert = 0 // do we notify the irc channel when somebody is connecting for the first time?
var/traitor_scaling_coeff = 6 //how much does the amount of players get divided by to determine traitors
var/changeling_scaling_coeff = 6 //how much does the amount of players get divided by to determine changelings
var/security_scaling_coeff = 8 //how much does the amount of players get divided by to determine open security officer positions
var/abductor_scaling_coeff = 15 //how many players per abductor team
var/traitor_objectives_amount = 2
var/protect_roles_from_antagonist = 0 //If security and such can be traitor/cult/other
var/protect_assistant_from_antagonist = 0 //If assistants can be traitor/cult/other
var/enforce_human_authority = 0 //If non-human species are barred from joining as a head of staff
var/allow_latejoin_antagonists = 0 // If late-joining players can be traitor/changeling
var/list/continuous = list() // which roundtypes continue if all antagonists die
var/list/midround_antag = list() // which roundtypes use the midround antagonist system
var/midround_antag_time_check = 60 // How late (in minutes) you want the midround antag system to stay on, setting this to 0 will disable the system
var/midround_antag_life_check = 0.7 // A ratio of how many people need to be alive in order for the round not to immediately end in midround antagonist
var/shuttle_refuel_delay = 12000
var/show_game_type_odds = 0 //if set this allows players to see the odds of each roundtype on the get revision screen
var/mutant_races = 0 //players can choose their mutant race before joining the game
var/list/roundstart_races = list() //races you can play as from the get go. If left undefined the game's roundstart var for species is used
var/mutant_humans = 0 //players can pick mutant bodyparts for humans before joining the game
var/no_summon_guns //No
var/no_summon_magic //Fun
var/no_summon_events //Allowed
var/intercept = 1 //Whether or not to send a communications intercept report roundstart. This may be overriden by gamemodes.
var/alert_desc_green = "All threats to the station have passed. Security may not have weapons visible, privacy laws are once again fully enforced."
var/alert_desc_blue_upto = "The station has received reliable information about possible hostile activity on the station. Security staff may have weapons visible, random searches are permitted."
var/alert_desc_blue_downto = "The immediate threat has passed. Security may no longer have weapons drawn at all times, but may continue to have them visible. Random searches are still allowed."
var/alert_desc_red_upto = "There is an immediate serious threat to the station. Security may have weapons unholstered at all times. Random searches are allowed and advised."
var/alert_desc_red_downto = "The station's destruction has been averted. There is still however an immediate serious threat to the station. Security may have weapons unholstered at all times, random searches are allowed and advised."
var/alert_desc_delta = "Destruction of the station is imminent. All crew are instructed to obey all instructions given by heads of staff. Any violations of these orders can be punished by death. This is not a drill."
var/health_threshold_crit = 0
var/health_threshold_dead = -100
var/revival_pod_plants = 1
var/revival_cloning = 1
var/revival_brain_life = -1
var/rename_cyborg = 0
var/ooc_during_round = 0
var/emojis = 0
//Used for modifying movement speed for mobs.
//Unversal modifiers
var/run_speed = 0
var/walk_speed = 0
//Mob specific modifiers. NOTE: These will affect different mob types in different ways
var/human_delay = 0
var/robot_delay = 0
var/monkey_delay = 0
var/alien_delay = 0
var/slime_delay = 0
var/animal_delay = 0
var/gateway_delay = 18000 //How long the gateway takes before it activates. Default is half an hour.
var/ghost_interaction = 0
var/silent_ai = 0
var/silent_borg = 0
var/allowwebclient = 0
var/webclientmembersonly = 0
var/sandbox_autoclose = 0 // close the sandbox panel after spawning an item, potentially reducing griff
var/default_laws = 0 //Controls what laws the AI spawns with.
var/silicon_max_law_amount = 12
var/assistant_cap = -1
var/starlight = 0
var/generate_minimaps = 0
var/grey_assistants = 0
var/lavaland_budget = 60
var/aggressive_changelog = 0
var/reactionary_explosions = 0 //If we use reactionary explosions, explosions that react to walls and doors
var/autoconvert_notes = 0 //if all connecting player's notes should attempt to be converted to the database
var/announce_admin_logout = 0
var/announce_admin_login = 0
var/list/datum/votablemap/maplist = list()
var/datum/votablemap/defaultmap = null
var/maprotation = 1
var/maprotatechancedelta = 0.75
// Enables random events mid-round when set to 1
var/allow_random_events = 0
// Multipliers for random events minimal starting time and minimal players amounts
var/events_min_time_mul = 1
var/events_min_players_mul = 1
// The object used for the clickable stat() button.
var/obj/effect/statclick/statclick
var/client_warn_version = 0
var/client_warn_message = "Your version of byond may have issues or be blocked from accessing this server in the future."
var/client_error_version = 0
var/client_error_message = "Your version of byond is too old, may have issues, and is blocked from accessing this server."
var/cross_name = "Other server"
/datum/configuration/New()
var/list/L = subtypesof(/datum/game_mode)
for(var/T in L)
// I wish I didn't have to instance the game modes in order to look up
// their information, but it is the only way (at least that I know of).
var/datum/game_mode/M = new T()
if(M.config_tag)
if(!(M.config_tag in modes)) // ensure each mode is added only once
diary << "Adding game mode [M.name] ([M.config_tag]) to configuration."
modes += M.config_tag
mode_names[M.config_tag] = M.name
probabilities[M.config_tag] = M.probability
if(M.votable)
votable_modes += M.config_tag
qdel(M)
votable_modes += "secret"
/datum/configuration/proc/load(filename, type = "config") //the type can also be game_options, in which case it uses a different switch. not making it separate to not copypaste code - Urist
var/list/Lines = file2list(filename)
for(var/t in Lines)
if(!t)
continue
t = trim(t)
if(length(t) == 0)
continue
else if(copytext(t, 1, 2) == "#")
continue
var/pos = findtext(t, " ")
var/name = null
var/value = null
if(pos)
name = lowertext(copytext(t, 1, pos))
value = copytext(t, pos + 1)
else
name = lowertext(t)
if(!name)
continue
if(type == "config")
switch(name)
if("admin_legacy_system")
config.admin_legacy_system = 1
if("ban_legacy_system")
config.ban_legacy_system = 1
if("use_age_restriction_for_jobs")
config.use_age_restriction_for_jobs = 1
if("lobby_countdown")
config.lobby_countdown = text2num(value)
if("round_end_countdown")
config.round_end_countdown = text2num(value)
if("log_ooc")
config.log_ooc = 1
if("log_access")
config.log_access = 1
if("log_say")
config.log_say = 1
if("log_admin")
config.log_admin = 1
if("log_prayer")
config.log_prayer = 1
if("log_law")
config.log_law = 1
if("log_game")
config.log_game = 1
if("log_vote")
config.log_vote = 1
if("log_whisper")
config.log_whisper = 1
if("log_attack")
config.log_attack = 1
if("log_emote")
config.log_emote = 1
if("log_adminchat")
config.log_adminchat = 1
if("log_pda")
config.log_pda = 1
if("log_hrefs")
config.log_hrefs = 1
if("log_world_topic")
config.log_world_topic = 1
if("allow_admin_ooccolor")
config.allow_admin_ooccolor = 1
if("allow_vote_restart")
config.allow_vote_restart = 1
if("allow_vote_mode")
config.allow_vote_mode = 1
if("no_dead_vote")
config.vote_no_dead = 1
if("default_no_vote")
config.vote_no_default = 1
if("vote_delay")
config.vote_delay = text2num(value)
if("vote_period")
config.vote_period = text2num(value)
if("norespawn")
config.respawn = 0
if("servername")
config.server_name = value
if("stationname")
config.station_name = value
if("serversuffix")
config.server_suffix = 1
if("hostedby")
config.hostedby = value
if("server")
config.server = value
if("banappeals")
config.banappeals = value
if("wikiurl")
config.wikiurl = value
if("forumurl")
config.forumurl = value
if("rulesurl")
config.rulesurl = value
if("githuburl")
config.githuburl = value
if("guest_jobban")
config.guest_jobban = 1
if("guest_ban")
guests_allowed = 0
if("usewhitelist")
config.usewhitelist = 1
if("allow_metadata")
config.allow_Metadata = 1
if("kick_inactive")
if(value < 1)
value = INACTIVITY_KICK
config.kick_inactive = value
if("load_jobs_from_txt")
load_jobs_from_txt = 1
if("forbid_singulo_possession")
forbid_singulo_possession = 1
if("popup_admin_pm")
config.popup_admin_pm = 1
if("allow_holidays")
config.allow_holidays = 1
if("useircbot")
useircbot = 1
if("ticklag")
var/ticklag = text2num(value)
if(ticklag > 0)
fps = 10 / ticklag
if("fps")
fps = text2num(value)
if("automute_on")
automute_on = 1
if("comms_key")
global.comms_key = value
if(value != "default_pwd" && length(value) > 6) //It's the default value or less than 6 characters long, warn badmins
global.comms_allowed = 1
if("cross_server_address")
global.cross_address = value
if(value != "byond:\\address:port")
global.cross_allowed = 1
if("cross_comms_name")
cross_name = value
if("see_own_notes")
config.see_own_notes = 1
if("soft_popcap")
config.soft_popcap = text2num(value)
if("hard_popcap")
config.hard_popcap = text2num(value)
if("extreme_popcap")
config.extreme_popcap = text2num(value)
if("soft_popcap_message")
config.soft_popcap_message = value
if("hard_popcap_message")
config.hard_popcap_message = value
if("extreme_popcap_message")
config.extreme_popcap_message = value
if("panic_bunker")
config.panic_bunker = 1
if("notify_new_player_age")
config.notify_new_player_age = text2num(value)
if("irc_first_connection_alert")
config.irc_first_connection_alert = 1
if("ipintel_email")
if (value != "ch@nge.me")
config.ipintel_email = value
if("ipintel_rating_bad")
config.ipintel_rating_bad = text2num(value)
if("ipintel_domain")
config.ipintel_domain = value
if("ipintel_save_good")
config.ipintel_save_good = text2num(value)
if("ipintel_save_bad")
config.ipintel_save_bad = text2num(value)
if("aggressive_changelog")
config.aggressive_changelog = 1
if("log_runtimes")
var/newlog = file("data/logs/runtimes/runtime-[time2text(world.realtime, "YYYY-MM-DD")].log")
if (world.log != newlog)
world.log << "Now logging runtimes to data/logs/runtimes/runtime-[time2text(world.realtime, "YYYY-MM-DD")].log"
world.log = newlog
if("autoconvert_notes")
config.autoconvert_notes = 1
if("allow_webclient")
config.allowwebclient = 1
if("webclient_only_byond_members")
config.webclientmembersonly = 1
if("announce_admin_logout")
config.announce_admin_logout = 1
if("announce_admin_login")
config.announce_admin_login = 1
if("maprotation")
config.maprotation = 1
if("maprotationchancedelta")
config.maprotatechancedelta = text2num(value)
if("autoadmin")
protected_config.autoadmin = 1
if(value)
protected_config.autoadmin_rank = ckeyEx(value)
if("generate_minimaps")
config.generate_minimaps = 1
if("client_warn_version")
config.client_warn_version = text2num(value)
if("client_warn_message")
config.client_warn_message = value
if("client_error_version")
config.client_error_version = text2num(value)
if("client_error_message")
config.client_error_message = value
else
diary << "Unknown setting in configuration: '[name]'"
else if(type == "game_options")
switch(name)
if("health_threshold_crit")
config.health_threshold_crit = text2num(value)
if("health_threshold_dead")
config.health_threshold_dead = text2num(value)
if("revival_pod_plants")
config.revival_pod_plants = text2num(value)
if("revival_cloning")
config.revival_cloning = text2num(value)
if("revival_brain_life")
config.revival_brain_life = text2num(value)
if("rename_cyborg")
config.rename_cyborg = 1
if("ooc_during_round")
config.ooc_during_round = 1
if("emojis")
config.emojis = 1
if("run_delay")
config.run_speed = text2num(value)
if("walk_delay")
config.walk_speed = text2num(value)
if("human_delay")
config.human_delay = text2num(value)
if("robot_delay")
config.robot_delay = text2num(value)
if("monkey_delay")
config.monkey_delay = text2num(value)
if("alien_delay")
config.alien_delay = text2num(value)
if("slime_delay")
config.slime_delay = text2num(value)
if("animal_delay")
config.animal_delay = text2num(value)
if("alert_red_upto")
config.alert_desc_red_upto = value
if("alert_red_downto")
config.alert_desc_red_downto = value
if("alert_blue_downto")
config.alert_desc_blue_downto = value
if("alert_blue_upto")
config.alert_desc_blue_upto = value
if("alert_green")
config.alert_desc_green = value
if("alert_delta")
config.alert_desc_delta = value
if("no_intercept_report")
config.intercept = 0
if("assistants_have_maint_access")
config.jobs_have_maint_access |= ASSISTANTS_HAVE_MAINT_ACCESS
if("security_has_maint_access")
config.jobs_have_maint_access |= SECURITY_HAS_MAINT_ACCESS
if("everyone_has_maint_access")
config.jobs_have_maint_access |= EVERYONE_HAS_MAINT_ACCESS
if("sec_start_brig")
config.sec_start_brig = 1
if("gateway_delay")
config.gateway_delay = text2num(value)
if("continuous")
var/mode_name = lowertext(value)
if(mode_name in config.modes)
config.continuous[mode_name] = 1
else
diary << "Unknown continuous configuration definition: [mode_name]."
if("midround_antag")
var/mode_name = lowertext(value)
if(mode_name in config.modes)
config.midround_antag[mode_name] = 1
else
diary << "Unknown midround antagonist configuration definition: [mode_name]."
if("midround_antag_time_check")
config.midround_antag_time_check = text2num(value)
if("midround_antag_life_check")
config.midround_antag_life_check = text2num(value)
if("shuttle_refuel_delay")
config.shuttle_refuel_delay = text2num(value)
if("show_game_type_odds")
config.show_game_type_odds = 1
if("ghost_interaction")
config.ghost_interaction = 1
if("traitor_scaling_coeff")
config.traitor_scaling_coeff = text2num(value)
if("changeling_scaling_coeff")
config.changeling_scaling_coeff = text2num(value)
if("security_scaling_coeff")
config.security_scaling_coeff = text2num(value)
if("abductor_scaling_coeff")
config.abductor_scaling_coeff = text2num(value)
if("traitor_objectives_amount")
config.traitor_objectives_amount = text2num(value)
if("probability")
var/prob_pos = findtext(value, " ")
var/prob_name = null
var/prob_value = null
if(prob_pos)
prob_name = lowertext(copytext(value, 1, prob_pos))
prob_value = copytext(value, prob_pos + 1)
if(prob_name in config.modes)
config.probabilities[prob_name] = text2num(prob_value)
else
diary << "Unknown game mode probability configuration definition: [prob_name]."
else
diary << "Incorrect probability configuration definition: [prob_name] [prob_value]."
if("protect_roles_from_antagonist")
config.protect_roles_from_antagonist = 1
if("protect_assistant_from_antagonist")
config.protect_assistant_from_antagonist = 1
if("enforce_human_authority")
config.enforce_human_authority = 1
if("allow_latejoin_antagonists")
config.allow_latejoin_antagonists = 1
if("allow_random_events")
config.allow_random_events = 1
if("events_min_time_mul")
config.events_min_time_mul = text2num(value)
if("events_min_players_mul")
config.events_min_players_mul = text2num(value)
if("minimal_access_threshold")
config.minimal_access_threshold = text2num(value)
if("jobs_have_minimal_access")
config.jobs_have_minimal_access = 1
if("humans_need_surnames")
humans_need_surnames = 1
if("force_random_names")
config.force_random_names = 1
if("allow_ai")
config.allow_ai = 1
if("disable_secborg")
config.forbid_secborg = 1
if("disable_peaceborg")
config.forbid_peaceborg = 1
if("silent_ai")
config.silent_ai = 1
if("silent_borg")
config.silent_borg = 1
if("sandbox_autoclose")
config.sandbox_autoclose = 1
if("default_laws")
config.default_laws = text2num(value)
if("silicon_max_law_amount")
config.silicon_max_law_amount = text2num(value)
if("join_with_mutant_race")
config.mutant_races = 1
if("roundstart_races")
var/race_id = lowertext(value)
for(var/species_id in species_list)
if(species_id == race_id)
roundstart_races += species_list[species_id]
roundstart_species[species_id] = species_list[species_id]
if("join_with_mutant_humans")
config.mutant_humans = 1
if("assistant_cap")
config.assistant_cap = text2num(value)
if("starlight")
config.starlight = 1
if("grey_assistants")
config.grey_assistants = 1
if("lavaland_budget")
config.lavaland_budget = text2num(value)
if("no_summon_guns")
config.no_summon_guns = 1
if("no_summon_magic")
config.no_summon_magic = 1
if("no_summon_events")
config.no_summon_events = 1
if("reactionary_explosions")
config.reactionary_explosions = 1
if("bombcap")
var/BombCap = text2num(value)
if (!BombCap)
continue
if (BombCap < 4)
BombCap = 4
MAX_EX_DEVESTATION_RANGE = round(BombCap/4)
MAX_EX_HEAVY_RANGE = round(BombCap/2)
MAX_EX_LIGHT_RANGE = BombCap
MAX_EX_FLASH_RANGE = BombCap
MAX_EX_FLAME_RANGE = BombCap
else
diary << "Unknown setting in configuration: '[name]'"
fps = round(fps)
if(fps <= 0)
fps = initial(fps)
/datum/configuration/proc/loadmaplist(filename)
var/list/Lines = file2list(filename)
var/datum/votablemap/currentmap = null
for(var/t in Lines)
if(!t)
continue
t = trim(t)
if(length(t) == 0)
continue
else if(copytext(t, 1, 2) == "#")
continue
var/pos = findtext(t, " ")
var/command = null
var/data = null
if(pos)
command = lowertext(copytext(t, 1, pos))
data = copytext(t, pos + 1)
else
command = lowertext(t)
if(!command)
continue
if (!currentmap && command != "map")
continue
switch (command)
if ("map")
currentmap = new (data)
if ("friendlyname")
currentmap.friendlyname = data
if ("minplayers","minplayer")
currentmap.minusers = text2num(data)
if ("maxplayers","maxplayer")
currentmap.maxusers = text2num(data)
if ("friendlyname")
currentmap.friendlyname = data
if ("weight","voteweight")
currentmap.voteweight = text2num(data)
if ("default","defaultmap")
config.defaultmap = currentmap
if ("endmap")
config.maplist[currentmap.name] = currentmap
currentmap = null
else
diary << "Unknown command in map vote config: '[command]'"
/datum/configuration/proc/loadsql(filename)
var/list/Lines = file2list(filename)
for(var/t in Lines)
if(!t)
continue
t = trim(t)
if(length(t) == 0)
continue
else if(copytext(t, 1, 2) == "#")
continue
var/pos = findtext(t, " ")
var/name = null
var/value = null
if(pos)
name = lowertext(copytext(t, 1, pos))
value = copytext(t, pos + 1)
else
name = lowertext(t)
if(!name)
continue
switch(name)
if("sql_enabled")
config.sql_enabled = 1
if("address")
sqladdress = value
if("port")
sqlport = value
if("feedback_database")
sqlfdbkdb = value
if("feedback_login")
sqlfdbklogin = value
if("feedback_password")
sqlfdbkpass = value
if("feedback_tableprefix")
sqlfdbktableprefix = value
else
diary << "Unknown setting in configuration: '[name]'"
/datum/configuration/proc/pick_mode(mode_name)
// I wish I didn't have to instance the game modes in order to look up
// their information, but it is the only way (at least that I know of).
for(var/T in subtypesof(/datum/game_mode))
var/datum/game_mode/M = new T()
if(M.config_tag && M.config_tag == mode_name)
return M
qdel(M)
return new /datum/game_mode/extended()
/datum/configuration/proc/get_runnable_modes()
var/list/datum/game_mode/runnable_modes = new
for(var/T in subtypesof(/datum/game_mode))
var/datum/game_mode/M = new T()
//world << "DEBUG: [T], tag=[M.config_tag], prob=[probabilities[M.config_tag]]"
if(!(M.config_tag in modes))
qdel(M)
continue
if(probabilities[M.config_tag]<=0)
qdel(M)
continue
if(M.can_start())
runnable_modes[M] = probabilities[M.config_tag]
//world << "DEBUG: runnable_mode\[[runnable_modes.len]\] = [M.config_tag]"
return runnable_modes
/datum/configuration/proc/get_runnable_midround_modes(crew)
var/list/datum/game_mode/runnable_modes = new
for(var/T in (subtypesof(/datum/game_mode) - ticker.mode.type))
var/datum/game_mode/M = new T()
if(!(M.config_tag in modes))
qdel(M)
continue
if(probabilities[M.config_tag]<=0)
qdel(M)
continue
if(M.required_players <= crew)
runnable_modes[M] = probabilities[M.config_tag]
return runnable_modes
/datum/configuration/proc/stat_entry()
if(!statclick)
statclick = new/obj/effect/statclick/debug("Edit", src)
stat("[name]:", statclick)
+4
View File
@@ -0,0 +1,4 @@
/datum/controller
var/name
// The object used for the clickable stat() button.
var/obj/effect/statclick/statclick
+96
View File
@@ -0,0 +1,96 @@
/**
* Failsafe
*
* Pretty much pokes the MC to make sure it's still alive.
**/
var/datum/controller/failsafe/Failsafe
/datum/controller/failsafe // This thing pretty much just keeps poking the master controller
name = "Failsafe"
// The length of time to check on the MC (in deciseconds).
// Set to 0 to disable.
var/processing_interval = 20
// The alert level. For every failed poke, we drop a DEFCON level. Once we hit DEFCON 1, restart the MC.
var/defcon = 5
//the world.time of the last check, so the mc can restart US if we hang.
// (Real friends look out for *eachother*)
var/lasttick = 0
// Track the MC iteration to make sure its still on track.
var/master_iteration = 0
/datum/controller/failsafe/New()
// Highlander-style: there can only be one! Kill off the old and replace it with the new.
if(Failsafe != src)
if(istype(Failsafe))
qdel(Failsafe)
Failsafe = src
spawn()
Failsafe.Loop()
qdel(Failsafe) //when Loop() returns, we delete ourselves and let the mc recreate us
/datum/controller/failsafe/Destroy()
..()
return QDEL_HINT_HARDDEL_NOW
/datum/controller/failsafe/proc/Loop()
while(1)
lasttick = world.time
if(!Master)
// Replace the missing Master! This should never, ever happen.
new /datum/controller/master()
// Only poke it if overrides are not in effect.
if(processing_interval > 0)
if(Master.processing && Master.iteration)
// Check if processing is done yet.
if(Master.iteration == master_iteration)
switch(defcon)
if(4,5)
--defcon
if(3)
admins << "<span class='adminnotice'>Notice: DEFCON [defcon_pretty()]. The Master Controller has not fired in the last [(5-defcon) * processing_interval] ticks."
--defcon
if(2)
admins << "<span class='boldannounce'>Warning: DEFCON [defcon_pretty()]. The Master Controller has not fired in the last [(5-defcon) * processing_interval] ticks. Automatic restart in [processing_interval] ticks.</span>"
--defcon
if(1)
admins << "<span class='boldannounce'>Warning: DEFCON [defcon_pretty()]. The Master Controller has still not fired within the last [(5-defcon) * processing_interval] ticks. Killing and restarting...</span>"
--defcon
var/rtn = Recreate_MC()
if(rtn > 0)
defcon = 4
master_iteration = 0
admins << "<span class='adminnotice'>MC restarted successfully</span>"
else if(rtn < 0)
log_game("FailSafe: Could not restart MC, runtime encountered. Entering defcon 0")
admins << "<span class='boldannounce'>ERROR: DEFCON [defcon_pretty()]. Could not restart MC, runtime encountered. I will silently keep retrying.</span>"
//if the return number was 0, it just means the mc was restarted too recently, and it just needs some time before we try again
//no need to handle that specially when defcon 0 can handle it
if(0) //DEFCON 0! (mc failed to restart)
var/rtn = Recreate_MC()
if(rtn > 0)
defcon = 4
master_iteration = 0
admins << "<span class='adminnotice'>MC restarted successfully</span>"
else
defcon = min(defcon + 1,5)
master_iteration = Master.iteration
if (defcon <= 1)
sleep(processing_interval*2)
else
sleep(processing_interval)
else
defcon = 5
sleep(initial(processing_interval))
/datum/controller/failsafe/proc/defcon_pretty()
return defcon
/datum/controller/failsafe/proc/stat_entry()
if(!statclick)
statclick = new/obj/effect/statclick/debug("Initializing...", src)
stat("Failsafe Controller:", statclick.update("Defcon: [defcon_pretty()] (Interval: [Failsafe.processing_interval] | Iteration: [Failsafe.master_iteration])"))
+491
View File
@@ -0,0 +1,491 @@
/**
* StonedMC
*
* Designed to properly split up a given tick among subsystems
* Note: if you read parts of this code and think "why is it doing it that way"
* Odds are, there is a reason
*
**/
var/datum/controller/master/Master = new()
var/MC_restart_clear = 0
var/MC_restart_timeout = 0
var/MC_restart_count = 0
//current tick limit, assigned by the queue controller before running a subsystem.
//used by check_tick as well so that the procs subsystems call can obey that SS's tick limits
var/CURRENT_TICKLIMIT = TICK_LIMIT_RUNNING
/datum/controller/master
name = "Master"
// Are we processing (higher values increase the processing delay by n ticks)
var/processing = 1
// How many times have we ran
var/iteration = 0
// world.time of last fire, for tracking lag outside of the mc
var/last_run
// List of subsystems to process().
var/list/subsystems
// Vars for keeping track of tick drift.
var/init_timeofday
var/init_time
var/tickdrift = 0
var/make_runtime = 0
// Has round started? (So we know what subsystems to run)
var/round_started = 0
// The type of the last subsystem to be process()'d.
var/last_type_processed
var/datum/subsystem/queue_head //Start of queue linked list
var/datum/subsystem/queue_tail //End of queue linked list (used for appending to the list)
var/queue_priority_count = 0 //Running total so that we don't have to loop thru the queue each run to split up the tick
var/queue_priority_count_bg = 0 //Same, but for background subsystems
/datum/controller/master/New()
// Highlander-style: there can only be one! Kill off the old and replace it with the new.
check_for_cleanbot_bug()
subsystems = list()
if (Master != src)
if (istype(Master))
Recover()
qdel(Master)
else
init_subtypes(/datum/subsystem, subsystems)
Master = src
/datum/controller/master/Destroy()
..()
// Tell qdel() to Del() this object.
return QDEL_HINT_HARDDEL_NOW
// Returns 1 if we created a new mc, 0 if we couldn't due to a recent restart,
// -1 if we encountered a runtime trying to recreate it
/proc/Recreate_MC()
. = -1 //so if we runtime, things know we failed
if (world.time < MC_restart_timeout)
return 0
if (world.time < MC_restart_clear)
MC_restart_count *= 0.5
var/delay = 50 * ++MC_restart_count
MC_restart_timeout = world.time + delay
MC_restart_clear = world.time + (delay * 2)
Master.processing = 0 //stop ticking this one
try
new/datum/controller/master()
catch
return -1
return 1
/datum/controller/master/proc/Recover()
var/msg = "## DEBUG: [time2text(world.timeofday)] MC restarted. Reports:\n"
for (var/varname in Master.vars)
switch (varname)
if("name", "tag", "bestF", "type", "parent_type", "vars", "statclick") // Built-in junk.
continue
else
var/varval = Master.vars[varname]
if (istype(varval, /datum)) // Check if it has a type var.
var/datum/D = varval
msg += "\t [varname] = [D]([D.type])\n"
else
msg += "\t [varname] = [varval]\n"
world.log << msg
if (istype(Master.subsystems))
subsystems = Master.subsystems
spawn (10)
StartProcessing()
else
world << "<span class='boldannounce'>The Master Controller is having some issues, we will need to re-initialize EVERYTHING</span>"
spawn (20)
init_subtypes(/datum/subsystem, subsystems)
Setup()
// Please don't stuff random bullshit here,
// Make a subsystem, give it the SS_NO_FIRE flag, and do your work in it's Initialize()
/datum/controller/master/proc/Setup()
check_for_cleanbot_bug()
world << "<span class='boldannounce'>Initializing subsystems...</span>"
// Sort subsystems by init_order, so they initialize in the correct order.
sortTim(subsystems, /proc/cmp_subsystem_init)
// Initialize subsystems.
CURRENT_TICKLIMIT = TICK_LIMIT_MC_INIT
for (var/datum/subsystem/SS in subsystems)
if (SS.flags & SS_NO_INIT)
continue
SS.Initialize(world.timeofday)
CHECK_TICK
CURRENT_TICKLIMIT = TICK_LIMIT_RUNNING
world << "<span class='boldannounce'>Initializations complete!</span>"
world.log << "Initializations complete."
// Sort subsystems by display setting for easy access.
sortTim(subsystems, /proc/cmp_subsystem_display)
check_for_cleanbot_bug()
// Set world options.
world.sleep_offline = 1
world.fps = config.fps
check_for_cleanbot_bug()
sleep(1)
check_for_cleanbot_bug()
// Loop.
Master.StartProcessing()
// Notify the MC that the round has started.
/datum/controller/master/proc/RoundStart()
round_started = 1
var/timer = world.time
for (var/datum/subsystem/SS in subsystems)
if (SS.flags & SS_FIRE_IN_LOBBY || SS.flags & SS_TICKER)
continue //already firing
// Stagger subsystems.
timer += world.tick_lag * rand(1, 5)
SS.next_fire = timer
// Starts the mc, and sticks around to restart it if the loop ever ends.
/datum/controller/master/proc/StartProcessing()
set waitfor = 0
var/rtn = Loop()
if (rtn > 0 || processing < 0)
return //this was suppose to happen.
//loop ended, restart the mc
log_game("MC crashed or runtimed, restarting")
message_admins("MC crashed or runtimed, restarting")
var/rtn2 = Recreate_MC()
if (rtn2 <= 0)
log_game("Failed to recreate MC (Error code: [rtn2]), its up to the failsafe now")
message_admins("Failed to recreate MC (Error code: [rtn2]), its up to the failsafe now")
Failsafe.defcon = 2
// Main loop.
/datum/controller/master/proc/Loop()
. = -1
//Prep the loop (most of this is because we want MC restarts to reset as much state as we can, and because
// local vars rock
// Schedule the first run of the Subsystems.
round_started = world.has_round_started()
//all this shit is here so that flag edits can be refreshed by restarting the MC. (and for speed)
var/list/tickersubsystems = list()
var/list/normalsubsystems = list()
var/list/lobbysubsystems = list()
var/timer = world.time
for (var/thing in subsystems)
var/datum/subsystem/SS = thing
if (SS.flags & SS_NO_FIRE)
continue
SS.queued_time = 0
SS.queue_next = null
SS.queue_prev = null
if (SS.flags & SS_TICKER)
tickersubsystems += SS
timer += world.tick_lag * rand(1, 5)
SS.next_fire = timer
continue
if (SS.flags & SS_FIRE_IN_LOBBY)
lobbysubsystems += SS
timer += world.tick_lag * rand(1, 5)
SS.next_fire = timer
else if (round_started)
timer += world.tick_lag * rand(1, 5)
SS.next_fire = timer
normalsubsystems += SS
queue_head = null
queue_tail = null
//these sort by lower priorities first to reduce the number of loops needed to add subsequent SS's to the queue
//(higher subsystems will be sooner in the queue, adding them later in the loop means we don't have to loop thru them next queue add)
sortTim(tickersubsystems, /proc/cmp_subsystem_priority)
sortTim(normalsubsystems, /proc/cmp_subsystem_priority)
sortTim(lobbysubsystems, /proc/cmp_subsystem_priority)
normalsubsystems += tickersubsystems
lobbysubsystems += tickersubsystems
init_timeofday = world.timeofday
init_time = world.time
iteration = 1
var/error_level = 0
var/sleep_delta = 0
var/list/subsystems_to_check
//the actual loop.
while (1)
tickdrift = max(0, MC_AVERAGE_FAST(tickdrift, (((world.timeofday - init_timeofday) - (world.time - init_time)) / world.tick_lag)))
if (processing <= 0)
sleep(10)
continue
//if there are mutiple sleeping procs running before us hogging the cpu, we have to run later
// because sleeps are processed in the order received, so longer sleeps are more likely to run first
if (world.tick_usage > TICK_LIMIT_MC)
sleep_delta += 2
sleep(world.tick_lag * (processing + sleep_delta))
continue
sleep_delta = MC_AVERAGE_FAST(sleep_delta, 0)
if (last_run + (world.tick_lag * processing) > world.time)
sleep_delta += 1
if (world.tick_usage > (TICK_LIMIT_MC*0.5))
sleep_delta += 1
if (make_runtime)
var/datum/subsystem/SS
SS.can_fire = 0
if (!Failsafe || (Failsafe.processing_interval > 0 && (Failsafe.lasttick+(Failsafe.processing_interval*5)) < world.time))
new/datum/controller/failsafe() // (re)Start the failsafe.
if (!queue_head || !(iteration % 3))
if (round_started)
subsystems_to_check = normalsubsystems
else
subsystems_to_check = lobbysubsystems
else
subsystems_to_check = tickersubsystems
if (CheckQueue(subsystems_to_check) <= 0)
if (!SoftReset(tickersubsystems, normalsubsystems, lobbysubsystems))
world.log << "MC: SoftReset() failed, crashing"
return
if (!error_level)
iteration++
error_level++
sleep(10)
continue
if (queue_head)
if (RunQueue() <= 0)
if (!SoftReset(tickersubsystems, normalsubsystems, lobbysubsystems))
world.log << "MC: SoftReset() failed, crashing"
return
if (!error_level)
iteration++
error_level++
sleep(10)
continue
error_level--
if (!queue_head) //reset the counts if the queue is empty, in the off chance they get out of sync
queue_priority_count = 0
queue_priority_count_bg = 0
iteration++
last_run = world.time
sleep(world.tick_lag * (processing + sleep_delta))
// This is what decides if something should run.
/datum/controller/master/proc/CheckQueue(list/subsystemstocheck)
. = 0 //so the mc knows if we runtimed
//we create our variables outside of the loops to save on overhead
var/datum/subsystem/SS
var/SS_flags
for (var/thing in subsystemstocheck)
if (!thing)
subsystemstocheck -= thing
SS = thing
if (SS.queued_time) //already in the queue
continue
if (SS.can_fire <= 0)
continue
if (SS.next_fire > world.time)
continue
SS_flags = SS.flags
if (SS_flags & SS_NO_FIRE)
subsystemstocheck -= SS
if (!(SS_flags & SS_TICKER) && (SS_flags & SS_KEEP_TIMING) && SS.last_fire + (SS.wait * 0.75) > world.time)
continue
//Queue it to run.
// (we loop thru a linked list until we get to the end or find the right point)
// (this lets us sort our run order correctly without having to re-sort the entire already sorted list)
SS.enqueue()
. = 1
// Run thru the queue of subsystems to run, running them while balancing out their allocated tick precentage
/datum/controller/master/proc/RunQueue()
. = 0
var/datum/subsystem/queue_node
var/queue_node_flags
var/queue_node_priority
var/queue_node_paused
var/current_tick_budget
var/tick_precentage
var/tick_remaining
var/ran = TRUE //this is right
var/ran_non_ticker = FALSE
var/bg_calc //have we swtiched current_tick_budget to background mode yet?
var/tick_usage
//keep running while we have stuff to run and we haven't gone over a tick
// this is so subsystems paused eariler can use tick time that later subsystems never used
while (ran && queue_head && world.tick_usage < TICK_LIMIT_MC)
ran = FALSE
bg_calc = FALSE
current_tick_budget = queue_priority_count
queue_node = queue_head
while (queue_node)
if (ran && world.tick_usage > TICK_LIMIT_RUNNING)
break
if (!istype(queue_node))
world.log << "[__FILE__]:[__LINE__] queue_node bad, now equals: [queue_node](\ref[queue_node])"
return
queue_node_flags = queue_node.flags
queue_node_priority = queue_node.queued_priority
//super special case, subsystems where we can't make them pause mid way through
//if we can't run them this tick (without going over a tick)
//we bump up their priority and attempt to run them next tick
//(unless we haven't even ran anything this tick, since its unlikely they will ever be able run
// in those cases, so we just let them run)
if (queue_node_flags & SS_NO_TICK_CHECK)
if (queue_node.tick_usage > TICK_LIMIT_RUNNING - world.tick_usage && ran_non_ticker)
queue_node.queued_priority += queue_priority_count * 0.10
queue_priority_count -= queue_node_priority
queue_priority_count += queue_node.queued_priority
current_tick_budget -= queue_node_priority
if (!istype(queue_node))
world.log << "[__FILE__]:[__LINE__] queue_node bad, now equals: [queue_node](\ref[queue_node])"
return
queue_node = queue_node.queue_next
continue
if ((queue_node_flags & SS_BACKGROUND) && !bg_calc)
current_tick_budget = queue_priority_count_bg
bg_calc = TRUE
tick_remaining = TICK_LIMIT_RUNNING - world.tick_usage
if (current_tick_budget > 0 && queue_node_priority > 0)
tick_precentage = tick_remaining / (current_tick_budget / queue_node_priority)
else
tick_precentage = tick_remaining
CURRENT_TICKLIMIT = world.tick_usage + tick_precentage
if (!(queue_node_flags & SS_TICKER))
ran_non_ticker = TRUE
ran = TRUE
tick_usage = world.tick_usage
queue_node_paused = queue_node.paused
queue_node.paused = FALSE
last_type_processed = queue_node
queue_node.fire(queue_node_paused)
current_tick_budget -= queue_node_priority
tick_usage = world.tick_usage - tick_usage
if (tick_usage < 0)
tick_usage = 0
if (queue_node.paused)
queue_node.paused_ticks++
queue_node.paused_tick_usage += tick_usage
if (!istype(queue_node))
world.log << "[__FILE__]:[__LINE__] queue_node bad, now equals: [queue_node](\ref[queue_node])"
return
queue_node = queue_node.queue_next
continue
queue_node.ticks = MC_AVERAGE(queue_node.ticks, queue_node.paused_ticks)
tick_usage += queue_node.paused_tick_usage
queue_node.tick_usage = MC_AVERAGE_FAST(queue_node.tick_usage, tick_usage)
queue_node.cost = MC_AVERAGE_FAST(queue_node.cost, TICK_DELTA_TO_MS(tick_usage))
queue_node.paused_ticks = 0
queue_node.paused_tick_usage = 0
if (queue_node_flags & SS_BACKGROUND) //update our running total
queue_priority_count_bg -= queue_node_priority
else
queue_priority_count -= queue_node_priority
queue_node.last_fire = world.time
queue_node.times_fired++
if (queue_node_flags & SS_TICKER)
queue_node.next_fire = world.time + (world.tick_lag * queue_node.wait)
else if (queue_node_flags & SS_POST_FIRE_TIMING)
queue_node.next_fire = world.time + queue_node.wait
else if (queue_node_flags & SS_KEEP_TIMING)
queue_node.next_fire += queue_node.wait
else
queue_node.next_fire = queue_node.queued_time + queue_node.wait
queue_node.queued_time = 0
//remove from queue
queue_node.dequeue()
if (!istype(queue_node))
world.log << "[__FILE__]:[__LINE__] queue_node bad, now equals: [queue_node](\ref[queue_node])"
return
queue_node = queue_node.queue_next
CURRENT_TICKLIMIT = TICK_LIMIT_RUNNING
. = 1
//resets the queue, and all subsystems, while filtering out the subsystem lists
// called if any mc's queue procs runtime or exit improperly.
/datum/controller/master/proc/SoftReset(list/ticker_SS, list/normal_SS, list/lobby_SS)
. = 0
world.log << "MC: SoftReset called, resetting MC queue state."
if (!istype(subsystems) || !istype(ticker_SS) || !istype(normal_SS) || !istype(lobby_SS))
world.log << "MC: SoftReset: Bad list contents: '[subsystems]' '[ticker_SS]' '[normal_SS]' '[lobby_SS]' Crashing!"
return
var/subsystemstocheck = subsystems + ticker_SS + normal_SS + lobby_SS
for (var/thing in subsystemstocheck)
var/datum/subsystem/SS = thing
if (!SS || !istype(SS))
//list(SS) is so if a list makes it in the subsystem list, we remove the list, not the contents
subsystems -= list(SS)
ticker_SS -= list(SS)
normal_SS -= list(SS)
lobby_SS -= list(SS)
world.log << "MC: SoftReset: Found bad entry in subsystem list, '[SS]'"
continue
if (SS.queue_next && !istype(SS.queue_next))
world.log << "MC: SoftReset: Found bad data in subsystem queue, queue_next = '[SS.queue_next]'"
SS.queue_next = null
if (SS.queue_prev && !istype(SS.queue_prev))
world.log << "MC: SoftReset: Found bad data in subsystem queue, queue_prev = '[SS.queue_prev]'"
SS.queue_prev = null
SS.queued_priority = 0
SS.queued_time = 0
SS.paused = 0
if (queue_head && !istype(queue_head))
world.log << "MC: SoftReset: Found bad data in subsystem queue, queue_head = '[queue_head]'"
queue_head = null
if (queue_tail && !istype(queue_tail))
world.log << "MC: SoftReset: Found bad data in subsystem queue, queue_tail = '[queue_tail]'"
queue_tail = null
queue_priority_count = 0
queue_priority_count_bg = 0
world.log << "MC: SoftReset: Finished."
. = 1
/datum/controller/master/proc/stat_entry()
if(!statclick)
statclick = new/obj/effect/statclick/debug("Initializing...", src)
stat("Master Controller:", statclick.update("(TickRate:[Master.processing]) (TickDrift:[round(Master.tickdrift)]) (Iteration:[Master.iteration])"))
+164
View File
@@ -0,0 +1,164 @@
/datum/subsystem
// Metadata; you should define these.
var/name = "fire coderbus" //name of the subsystem
var/init_order = 0 //order of initialization. Higher numbers are initialized first, lower numbers later. Can be decimal and negative values.
var/wait = 20 //time to wait (in deciseconds) between each call to fire(). Must be a positive integer.
var/display_order = 100 //display affects the order the subsystem is displayed in the MC tab
var/priority = 50 //When mutiple subsystems need to run in the same tick, higher priority subsystems will run first and be given a higher share of the tick before MC_TICK_CHECK triggers a sleep
var/flags = 0 //see MC.dm in __DEFINES Most flags must be set on world start to take full effect. (You can also restart the mc to force them to process again)
//set to 0 to prevent fire() calls, mostly for admin use or subsystems that may be resumed later
// use the SS_NO_FIRE flag instead for systems that never fire to keep it from even being added to the list
var/can_fire = TRUE
// Bookkeeping variables; probably shouldn't mess with these.
var/last_fire = 0 //last world.time we called fire()
var/next_fire = 0 //scheduled world.time for next fire()
var/cost = 0 //average time to execute
var/tick_usage = 0 //average tick usage
var/paused = 0 //was this subsystem paused mid fire.
var/paused_ticks = 0 //ticks this ss is taking to run right now.
var/paused_tick_usage //total tick_usage of all of our runs while pausing this run
var/ticks = 1 //how many ticks does this ss take to run on avg.
var/times_fired = 0 //number of times we have called fire()
var/queued_time = 0 //time we entered the queue, (for timing and priority reasons)
var/queued_priority //we keep a running total to make the math easier, if it changes mid-fire that would break our running total, so we store it here
//linked list stuff for the queue
var/datum/subsystem/queue_next
var/datum/subsystem/queue_prev
// The object used for the clickable stat() button.
var/obj/effect/statclick/statclick
// Used to initialize the subsystem BEFORE the map has loaded
/datum/subsystem/New()
//previously, this would have been named 'process()' but that name is used everywhere for different things!
//fire() seems more suitable. This is the procedure that gets called every 'wait' deciseconds.
//fire(), and the procs it calls, SHOULD NOT HAVE ANY SLEEP OPERATIONS in them!
//YE BE WARNED!
/datum/subsystem/proc/fire(resumed = 0)
set waitfor = 0 //this should not be depended upon, this is just to solve issues with sleeps messing up tick tracking
can_fire = 0
flags |= SS_NO_FIRE
throw EXCEPTION("Subsystem [src]([type]) does not fire() but did not set the SS_NO_FIRE flag. Please add the SS_NO_FIRE flag to any subsystem that doesn't fire so it doesn't get added to the processing list and waste cpu.")
/datum/subsystem/Destroy()
dequeue()
can_fire = 0
flags |= SS_NO_FIRE
Master.subsystems -= src
/datum/subsystem/proc/enqueue()
var/SS_priority = priority
var/SS_flags = flags
var/datum/subsystem/queue_node
var/queue_node_priority
var/queue_node_flags
for (queue_node = Master.queue_head; queue_node; queue_node = queue_node.queue_next)
queue_node_priority = queue_node.queued_priority
queue_node_flags = queue_node.flags
if (queue_node_flags & SS_TICKER)
if (!(SS_flags & SS_TICKER))
continue
if (queue_node_priority < SS_priority)
break
else if (queue_node_flags & SS_BACKGROUND)
if (!(SS_flags & SS_BACKGROUND))
break
if (queue_node_priority < SS_priority)
break
else
if (SS_flags & SS_BACKGROUND)
continue
if (SS_flags & SS_TICKER)
break
if (queue_node_priority < SS_priority)
break
queued_time = world.time
queued_priority = SS_priority
if (SS_flags & SS_BACKGROUND) //update our running total
Master.queue_priority_count_bg += SS_priority
else
Master.queue_priority_count += SS_priority
queue_next = queue_node
if (!queue_node)//we stopped at the end, add to tail
queue_prev = Master.queue_tail
if (Master.queue_tail)
Master.queue_tail.queue_next = src
else //empty queue, we also need to set the head
Master.queue_head = src
Master.queue_tail = src
else if (queue_node == Master.queue_head)//insert at start of list
Master.queue_head.queue_prev = src
Master.queue_head = src
queue_prev = null
else
queue_node.queue_prev.queue_next = src
queue_prev = queue_node.queue_prev
queue_node.queue_prev = src
/datum/subsystem/proc/dequeue()
if (queue_next)
queue_next.queue_prev = queue_prev
if (queue_prev)
queue_prev.queue_next = queue_next
if (src == Master.queue_tail)
Master.queue_tail = queue_prev
if (src == Master.queue_head)
Master.queue_head = queue_next
queued_time = 0
/datum/subsystem/proc/pause()
. = 1
paused = TRUE
paused_ticks++
//used to initialize the subsystem AFTER the map has loaded
/datum/subsystem/proc/Initialize(start_timeofday)
var/time = (world.timeofday - start_timeofday) / 10
var/msg = "Initialized [name] subsystem within [time] seconds!"
world << "<span class='boldannounce'>[msg]</span>"
return time
//hook for printing stats to the "MC" statuspanel for admins to see performance and related stats etc.
/datum/subsystem/proc/stat_entry(msg)
if(!statclick)
statclick = new/obj/effect/statclick/debug("Initializing...", src)
if(can_fire)
msg = "[round(cost*ticks,1)]ms|[round(tick_usage,1)]%|[round(ticks,0.1)]\t[msg]"
else
msg = "OFFLINE\t[msg]"
stat(name, statclick.update(msg))
//could be used to postpone a costly subsystem for (default one) var/cycles, cycles
//for instance, during cpu intensive operations like explosions
/datum/subsystem/proc/postpone(cycles = 1)
if(next_fire - world.time < wait)
next_fire += (wait*cycles)
//usually called via datum/subsystem/New() when replacing a subsystem (i.e. due to a recurring crash)
//should attempt to salvage what it can from the old instance of subsystem
/datum/subsystem/proc/Recover()
//this is so the subsystem doesn't rapid fire to make up missed ticks causing more lag
/datum/subsystem/on_varedit(edited_var)
if (edited_var == "can_fire" && can_fire)
next_fire = world.time + wait
..()
+354
View File
@@ -0,0 +1,354 @@
#define SSAIR_PIPENETS 1
#define SSAIR_ATMOSMACHINERY 2
#define SSAIR_ACTIVETURFS 3
#define SSAIR_EXCITEDGROUPS 4
#define SSAIR_HIGHPRESSURE 5
#define SSAIR_HOTSPOTS 6
#define SSAIR_SUPERCONDUCTIVITY 7
var/datum/subsystem/air/SSair
/datum/subsystem/air
name = "Air"
init_order = -1
priority = 20
wait = 5
flags = SS_BACKGROUND
display_order = 1
var/cost_turfs = 0
var/cost_groups = 0
var/cost_highpressure = 0
var/cost_hotspots = 0
var/cost_superconductivity = 0
var/cost_pipenets = 0
var/cost_atmos_machinery = 0
var/list/excited_groups = list()
var/list/active_turfs = list()
var/list/hotspots = list()
var/list/networks = list()
var/list/obj/machinery/atmos_machinery = list()
//Special functions lists
var/list/turf/active_super_conductivity = list()
var/list/turf/open/high_pressure_delta = list()
var/list/currentrun = list()
var/currentpart = SSAIR_PIPENETS
/datum/subsystem/air/New()
NEW_SS_GLOBAL(SSair)
/datum/subsystem/air/stat_entry(msg)
msg += "C:{"
msg += "AT:[round(cost_turfs)]|"
msg += "EG:[round(cost_groups)]|"
msg += "HP:[round(cost_highpressure)]|"
msg += "HS:[round(cost_hotspots)]|"
msg += "SC:[round(cost_superconductivity)]|"
msg += "PN:[round(cost_pipenets)]|"
msg += "AM:[round(cost_atmos_machinery)]"
msg += "} "
msg += "AT:[active_turfs.len]|"
msg += "EG:[excited_groups.len]|"
msg += "HS:[hotspots.len]|"
msg += "AS:[active_super_conductivity.len]"
..(msg)
/datum/subsystem/air/Initialize(timeofday)
setup_allturfs()
setup_atmos_machinery()
setup_pipenets()
..()
/datum/subsystem/air/fire(resumed = 0)
var/timer = world.tick_usage
if(currentpart == SSAIR_PIPENETS || !resumed)
process_pipenets(resumed)
cost_pipenets = MC_AVERAGE(cost_pipenets, TICK_DELTA_TO_MS(world.tick_usage - timer))
if(paused)
return
resumed = 0
currentpart = SSAIR_ATMOSMACHINERY
if(currentpart == SSAIR_ATMOSMACHINERY)
timer = world.tick_usage
process_atmos_machinery(resumed)
cost_atmos_machinery = MC_AVERAGE(cost_atmos_machinery, TICK_DELTA_TO_MS(world.tick_usage - timer))
if(paused)
return
resumed = 0
currentpart = SSAIR_ACTIVETURFS
if(currentpart == SSAIR_ACTIVETURFS)
timer = world.tick_usage
process_active_turfs(resumed)
cost_turfs = MC_AVERAGE(cost_turfs, TICK_DELTA_TO_MS(world.tick_usage - timer))
if(paused)
return
resumed = 0
currentpart = SSAIR_EXCITEDGROUPS
if(currentpart == SSAIR_EXCITEDGROUPS)
timer = world.tick_usage
process_excited_groups(resumed)
cost_groups = MC_AVERAGE(cost_groups, TICK_DELTA_TO_MS(world.tick_usage - timer))
if(paused)
return
resumed = 0
currentpart = SSAIR_HIGHPRESSURE
if(currentpart == SSAIR_HIGHPRESSURE)
timer = world.tick_usage
process_high_pressure_delta(resumed)
cost_highpressure = MC_AVERAGE(cost_highpressure, TICK_DELTA_TO_MS(world.tick_usage - timer))
if(paused)
return
resumed = 0
currentpart = SSAIR_HOTSPOTS
if(currentpart == SSAIR_HOTSPOTS)
timer = world.tick_usage
process_hotspots(resumed)
cost_hotspots = MC_AVERAGE(cost_hotspots, TICK_DELTA_TO_MS(world.tick_usage - timer))
if(paused)
return
resumed = 0
currentpart = SSAIR_SUPERCONDUCTIVITY
if(currentpart == SSAIR_SUPERCONDUCTIVITY)
timer = world.tick_usage
process_super_conductivity(resumed)
cost_superconductivity = MC_AVERAGE(cost_superconductivity, TICK_DELTA_TO_MS(world.tick_usage - timer))
if(paused)
return
resumed = 0
currentpart = SSAIR_PIPENETS
/datum/subsystem/air/proc/process_pipenets(resumed = 0)
if (!resumed)
src.currentrun = networks.Copy()
//cache for sanic speed (lists are references anyways)
var/list/currentrun = src.currentrun
while(currentrun.len)
var/datum/thing = currentrun[currentrun.len]
currentrun.len--
if(thing)
thing.process()
else
networks.Remove(thing)
if(MC_TICK_CHECK)
return
/datum/subsystem/air/proc/process_atmos_machinery(resumed = 0)
var/seconds = wait * 0.1
if (!resumed)
src.currentrun = atmos_machinery.Copy()
//cache for sanic speed (lists are references anyways)
var/list/currentrun = src.currentrun
while(currentrun.len)
var/obj/machinery/M = currentrun[currentrun.len]
currentrun.len--
if(!M || (M.process_atmos(seconds) == PROCESS_KILL))
atmos_machinery.Remove(M)
if(MC_TICK_CHECK)
return
/datum/subsystem/air/proc/process_super_conductivity(resumed = 0)
if (!resumed)
src.currentrun = active_super_conductivity.Copy()
//cache for sanic speed (lists are references anyways)
var/list/currentrun = src.currentrun
while(currentrun.len)
var/turf/T = currentrun[currentrun.len]
currentrun.len--
T.super_conduct()
if(MC_TICK_CHECK)
return
/datum/subsystem/air/proc/process_hotspots(resumed = 0)
if (!resumed)
src.currentrun = hotspots.Copy()
//cache for sanic speed (lists are references anyways)
var/list/currentrun = src.currentrun
while(currentrun.len)
var/obj/effect/hotspot/H = currentrun[currentrun.len]
currentrun.len--
if (H)
H.process()
else
hotspots -= H
if(MC_TICK_CHECK)
return
/datum/subsystem/air/proc/process_high_pressure_delta(resumed = 0)
while (high_pressure_delta.len)
var/turf/open/T = high_pressure_delta[high_pressure_delta.len]
high_pressure_delta.len--
T.high_pressure_movements()
T.pressure_difference = 0
if(MC_TICK_CHECK)
return
/datum/subsystem/air/proc/process_active_turfs(resumed = 0)
//cache for sanic speed
var/fire_count = times_fired
if (!resumed)
src.currentrun = active_turfs.Copy()
//cache for sanic speed (lists are references anyways)
var/list/currentrun = src.currentrun
while(currentrun.len)
var/turf/open/T = currentrun[currentrun.len]
currentrun.len--
if (T)
T.process_cell(fire_count)
if (MC_TICK_CHECK)
return
/datum/subsystem/air/proc/process_excited_groups(resumed = 0)
if (!resumed)
src.currentrun = excited_groups.Copy()
//cache for sanic speed (lists are references anyways)
var/list/currentrun = src.currentrun
while(currentrun.len)
var/datum/excited_group/EG = currentrun[currentrun.len]
currentrun.len--
EG.breakdown_cooldown++
EG.dismantle_cooldown++
if(EG.breakdown_cooldown >= EXCITED_GROUP_BREAKDOWN_CYCLES)
EG.self_breakdown()
else if(EG.dismantle_cooldown >= EXCITED_GROUP_DISMANTLE_CYCLES)
EG.dismantle()
if (MC_TICK_CHECK)
return
/datum/subsystem/air/proc/remove_from_active(turf/open/T)
active_turfs -= T
if(istype(T))
T.excited = 0
if(T.excited_group)
T.excited_group.garbage_collect()
/datum/subsystem/air/proc/add_to_active(turf/open/T, blockchanges = 1)
if(istype(T) && T.air)
T.excited = 1
active_turfs |= T
if(blockchanges && T.excited_group)
T.excited_group.garbage_collect()
else
for(var/turf/S in T.atmos_adjacent_turfs)
add_to_active(S)
/datum/subsystem/air/proc/setup_allturfs()
var/list/turfs_to_init = block(locate(1, 1, 1), locate(world.maxx, world.maxy, world.maxz))
var/list/active_turfs = src.active_turfs
var/times_fired = ++src.times_fired
for(var/thing in turfs_to_init)
var/turf/T = thing
active_turfs -= T
if (T.blocks_air)
continue
T.Initalize_Atmos(times_fired)
if(active_turfs.len)
var/starting_ats = active_turfs.len
sleep(world.tick_lag)
var/timer = world.timeofday
warning("There are [starting_ats] active turfs at roundstart, this is a mapping error caused by a difference of the air between the adjacent turfs. You can see its coordinates using \"Mapping -> Show roundstart AT list\" verb (debug verbs required)")
for(var/turf/T in active_turfs)
active_turfs_startlist += text("[T.x], [T.y], [T.z]\n")
//now lets clear out these active turfs
var/list/turfs_to_check = active_turfs.Copy()
do
var/list/new_turfs_to_check = list()
for(var/turf/open/T in turfs_to_check)
new_turfs_to_check += T.resolve_active_graph()
active_turfs += new_turfs_to_check
turfs_to_check = new_turfs_to_check
while (turfs_to_check.len)
var/ending_ats = active_turfs.len
for(var/thing in excited_groups)
var/datum/excited_group/EG = thing
EG.self_breakdown(space_is_all_consuming = 1)
EG.dismantle()
var/msg = "HEY! LISTEN! [(world.timeofday - timer)/10] Seconds were wasted processing [starting_ats] turf(s) (connected to [ending_ats] other turfs) with atmos differences at round start."
world << "<span class='boldannounce'>[msg]</span>"
warning(msg)
/turf/open/proc/resolve_active_graph()
. = list()
var/datum/excited_group/EG = excited_group
if (blocks_air || !air)
return
if (!EG)
EG = new
EG.add_turf(src)
for (var/turf/open/ET in atmos_adjacent_turfs)
if ( ET.blocks_air || !ET.air)
continue
var/ET_EG = ET.excited_group
if (ET_EG)
if (ET_EG != EG)
EG.merge_groups(ET_EG)
EG = excited_group //merge_groups() may decide to replace our current EG
else
EG.add_turf(ET)
if (!ET.excited)
ET.excited = 1
. += ET
/turf/open/space/resolve_active_graph()
return list()
/datum/subsystem/air/proc/setup_atmos_machinery()
for (var/obj/machinery/atmospherics/AM in atmos_machinery)
AM.atmosinit()
CHECK_TICK
//this can't be done with setup_atmos_machinery() because
// all atmos machinery has to initalize before the first
// pipenet can be built.
/datum/subsystem/air/proc/setup_pipenets()
for (var/obj/machinery/atmospherics/AM in atmos_machinery)
AM.build_network()
CHECK_TICK
/datum/subsystem/air/proc/setup_template_machinery(list/atmos_machines)
for(var/A in atmos_machines)
var/obj/machinery/atmospherics/AM = A
AM.atmosinit()
CHECK_TICK
for(var/A in atmos_machines)
var/obj/machinery/atmospherics/AM = A
AM.build_network()
CHECK_TICK
#undef SSAIR_PIPENETS
#undef SSAIR_ATMOSMACHINERY
#undef SSAIR_ACTIVETURFS
#undef SSAIR_EXCITEDGROUPS
#undef SSAIR_HIGHPRESSURE
#undef SSAIR_HOTSPOT
#undef SSAIR_SUPERCONDUCTIVITY
+21
View File
@@ -0,0 +1,21 @@
var/datum/subsystem/assets/SSasset
/datum/subsystem/assets
name = "Assets"
init_order = -3
flags = SS_NO_FIRE
var/list/cache = list()
/datum/subsystem/assets/New()
NEW_SS_GLOBAL(SSasset)
/datum/subsystem/assets/Initialize(timeofday)
for(var/type in typesof(/datum/asset) - list(/datum/asset, /datum/asset/simple))
var/datum/asset/A = new type()
A.register()
for(var/client/C in clients)
// Doing this to a client too soon after they've connected can cause issues, also the proc we call sleeps.
spawn(10)
getFilesSlow(C, cache, FALSE)
..()
+30
View File
@@ -0,0 +1,30 @@
var/datum/subsystem/diseases/SSdisease
/datum/subsystem/diseases
name = "Diseases"
flags = SS_KEEP_TIMING|SS_NO_INIT
var/list/currentrun = list()
var/list/processing = list()
/datum/subsystem/diseases/New()
NEW_SS_GLOBAL(SSdisease)
/datum/subsystem/diseases/stat_entry(msg)
..("P:[processing.len]")
/datum/subsystem/diseases/fire(resumed = 0)
if(!resumed)
src.currentrun = processing.Copy()
//cache for sanic speed (lists are references anyways)
var/list/currentrun = src.currentrun
while(currentrun.len)
var/datum/thing = currentrun[currentrun.len]
currentrun.len--
if(thing)
thing.process()
else
processing.Remove(thing)
if (MC_TICK_CHECK)
return
+204
View File
@@ -0,0 +1,204 @@
var/datum/subsystem/events/SSevent
/datum/subsystem/events
name = "Events"
init_order = 6
var/list/control = list() //list of all datum/round_event_control. Used for selecting events based on weight and occurrences.
var/list/running = list() //list of all existing /datum/round_event
var/list/currentrun = list()
var/scheduled = 0 //The next world.time that a naturally occuring random event can be selected.
var/frequency_lower = 1800 //3 minutes lower bound.
var/frequency_upper = 6000 //10 minutes upper bound. Basically an event will happen every 3 to 10 minutes.
var/list/holidays //List of all holidays occuring today or null if no holidays
var/wizardmode = 0
/datum/subsystem/events/New()
NEW_SS_GLOBAL(SSevent)
/datum/subsystem/events/Initialize(time, zlevel)
for(var/type in typesof(/datum/round_event_control))
var/datum/round_event_control/E = new type()
if(!E.typepath)
continue //don't want this one! leave it for the garbage collector
control += E //add it to the list of all events (controls)
reschedule()
getHoliday()
..()
/datum/subsystem/events/fire(resumed = 0)
if(!resumed)
checkEvent() //only check these if we aren't resuming a paused fire
src.currentrun = running.Copy()
//cache for sanic speed (lists are references anyways)
var/list/currentrun = src.currentrun
while(currentrun.len)
var/datum/thing = currentrun[currentrun.len]
currentrun.len--
if(thing)
thing.process()
else
running.Remove(thing)
if (MC_TICK_CHECK)
return
//checks if we should select a random event yet, and reschedules if necessary
/datum/subsystem/events/proc/checkEvent()
if(scheduled <= world.time)
spawnEvent()
reschedule()
//decides which world.time we should select another random event at.
/datum/subsystem/events/proc/reschedule()
scheduled = world.time + rand(frequency_lower, max(frequency_lower,frequency_upper))
//selects a random event based on whether it can occur and it's 'weight'(probability)
/datum/subsystem/events/proc/spawnEvent()
if(!config.allow_random_events)
// var/datum/round_event_control/E = locate(/datum/round_event_control/dust) in control
// if(E) E.runEvent()
return
var/gamemode = ticker.mode.config_tag
var/players_amt = get_active_player_count(alive_check = 1, afk_check = 1, human_check = 1)
// Only alive, non-AFK human players count towards this.
var/sum_of_weights = 0
for(var/datum/round_event_control/E in control)
if(!E.canSpawnEvent(players_amt, gamemode))
continue
if(E.weight < 0) //for round-start events etc.
if(E.runEvent() == PROCESS_KILL)
E.max_occurrences = 0
continue
if (E.alertadmins)
message_admins("Random Event triggering: [E.name] ([E.typepath])")
log_game("Random Event triggering: [E.name] ([E.typepath])")
return
sum_of_weights += E.weight
sum_of_weights = rand(0,sum_of_weights) //reusing this variable. It now represents the 'weight' we want to select
for(var/datum/round_event_control/E in control)
if(!E.canSpawnEvent(players_amt, gamemode))
continue
sum_of_weights -= E.weight
if(sum_of_weights <= 0) //we've hit our goal
if(E.runEvent() == PROCESS_KILL)//we couldn't run this event for some reason, set its max_occurrences to 0
E.max_occurrences = 0
continue
if (E.alertadmins)
message_admins("Random Event triggering: [E.name] ([E.typepath])")
log_game("Random Event triggering: [E.name] ([E.typepath])")
return
/datum/round_event/proc/findEventArea() //Here's a nice proc to use to find an area for your event to land in!
var/list/safe_areas = list(
/area/turret_protected/ai,
/area/turret_protected/ai_upload,
/area/engine,
/area/solar,
/area/holodeck,
/area/shuttle
)
//These are needed because /area/engine has to be removed from the list, but we still want these areas to get fucked up.
var/list/danger_areas = list(
/area/engine/break_room,
/area/engine/chiefs_office)
//Need to locate() as it's just a list of paths.
return locate(pick((the_station_areas - safe_areas) + danger_areas))
//allows a client to trigger an event
//aka Badmin Central
/client/proc/forceEvent()
set name = "Trigger Event"
set category = "Fun"
if(!holder ||!check_rights(R_FUN))
return
holder.forceEvent()
/datum/admins/proc/forceEvent()
var/dat = ""
var/normal = ""
var/magic = ""
var/holiday = ""
for(var/datum/round_event_control/E in SSevent.control)
dat = "<BR><A href='?src=\ref[src];forceevent=\ref[E]'>[E]</A>"
if(E.holidayID)
holiday += dat
else if(E.wizardevent)
magic += dat
else
normal += dat
dat = normal + "<BR>" + magic + "<BR>" + holiday
var/datum/browser/popup = new(usr, "forceevent", "Force Random Event", 300, 750)
popup.set_content(dat)
popup.open()
/*
//////////////
// HOLIDAYS //
//////////////
//Uncommenting ALLOW_HOLIDAYS in config.txt will enable holidays
//It's easy to add stuff. Just add a holiday datum in code/modules/holiday/holidays.dm
//You can then check if it's a special day in any code in the game by doing if(SSevent.holidays["Groundhog Day"])
//You can also make holiday random events easily thanks to Pete/Gia's system.
//simply make a random event normally, then assign it a holidayID string which matches the holiday's name.
//Anything with a holidayID, which isn't in the holidays list, will never occur.
//Please, Don't spam stuff up with stupid stuff (key example being april-fools Pooh/ERP/etc),
//And don't forget: CHECK YOUR CODE!!!! We don't want any zero-day bugs which happen only on holidays and never get found/fixed!
//////////////////////////////////////////////////////////////////////////////////////////////////////////
//ALSO, MOST IMPORTANTLY: Don't add stupid stuff! Discuss bonus content with Project-Heads first please!//
//////////////////////////////////////////////////////////////////////////////////////////////////////////
*/
//sets up the holidays and holidays list
/datum/subsystem/events/proc/getHoliday()
if(!config.allow_holidays)
return // Holiday stuff was not enabled in the config!
var/YY = text2num(time2text(world.timeofday, "YY")) // get the current year
var/MM = text2num(time2text(world.timeofday, "MM")) // get the current month
var/DD = text2num(time2text(world.timeofday, "DD")) // get the current day
for(var/H in subtypesof(/datum/holiday))
var/datum/holiday/holiday = new H()
if(holiday.shouldCelebrate(DD, MM, YY))
holiday.celebrate()
if(!holidays)
holidays = list()
holidays[holiday.name] = holiday
if(holidays)
holidays = shuffle(holidays)
world.update_status()
/datum/subsystem/events/proc/toggleWizardmode()
wizardmode = !wizardmode
message_admins("Summon Events has been [wizardmode ? "enabled, events will occur every [SSevent.frequency_lower / 600] to [SSevent.frequency_upper / 600] minutes" : "disabled"]!")
log_game("Summon Events was [wizardmode ? "enabled" : "disabled"]!")
/datum/subsystem/events/proc/resetFrequency()
frequency_lower = initial(frequency_lower)
frequency_upper = initial(frequency_upper)
+33
View File
@@ -0,0 +1,33 @@
var/datum/subsystem/fastprocess/SSfastprocess
/datum/subsystem/fastprocess
name = "Fast Process"
priority = 25
flags = SS_BACKGROUND|SS_POST_FIRE_TIMING|SS_NO_INIT
wait = 2
var/list/processing = list()
var/list/currentrun = list()
/datum/subsystem/fastprocess/New()
NEW_SS_GLOBAL(SSfastprocess)
/datum/subsystem/fastprocess/stat_entry()
..("FP:[processing.len]")
/datum/subsystem/fastprocess/fire(resumed = 0)
if (!resumed)
src.currentrun = processing.Copy()
//cache for sanic speed (lists are references anyways)
var/list/currentrun = src.currentrun
while(currentrun.len)
var/datum/thing = currentrun[currentrun.len]
currentrun.len--
if(thing)
thing.process(wait)
else
SSfastprocess.processing -= thing
if (MC_TICK_CHECK)
return
+312
View File
@@ -0,0 +1,312 @@
var/datum/subsystem/garbage_collector/SSgarbage
/datum/subsystem/garbage_collector
name = "Garbage"
priority = 15
wait = 5
display_order = 2
flags = SS_FIRE_IN_LOBBY|SS_POST_FIRE_TIMING|SS_BACKGROUND|SS_NO_INIT
var/collection_timeout = 3000// deciseconds to wait to let running procs finish before we just say fuck it and force del() the object
var/delslasttick = 0 // number of del()'s we've done this tick
var/gcedlasttick = 0 // number of things that gc'ed last tick
var/totaldels = 0
var/totalgcs = 0
var/highest_del_time = 0
var/highest_del_tickusage = 0
var/list/queue = list() // list of refID's of things that should be garbage collected
// refID's are associated with the time at which they time out and need to be manually del()
// we do this so we aren't constantly locating them and preventing them from being gc'd
var/list/tobequeued = list() //We store the references of things to be added to the queue seperately so we can spread out GC overhead over a few ticks
var/list/didntgc = list() // list of all types that have failed to GC associated with the number of times that's happened.
// the types are stored as strings
var/list/noqdelhint = list()// list of all types that do not return a QDEL_HINT
// all types that did not respect qdel(A, force=TRUE) and returned one
// of the immortality qdel hints
var/list/noforcerespect = list()
#ifdef TESTING
var/list/qdel_list = list() // list of all types that have been qdel()eted
#endif
/datum/subsystem/garbage_collector/New()
NEW_SS_GLOBAL(SSgarbage)
/datum/subsystem/garbage_collector/stat_entry(msg)
msg += "Q:[queue.len]|D:[delslasttick]|G:[gcedlasttick]|"
msg += "GR:"
if (!(delslasttick+gcedlasttick))
msg += "n/a|"
else
msg += "[round((gcedlasttick/(delslasttick+gcedlasttick))*100, 0.01)]%|"
msg += "TD:[totaldels]|TG:[totalgcs]|"
if (!(totaldels+totalgcs))
msg += "n/a|"
else
msg += "TGR:[round((totalgcs/(totaldels+totalgcs))*100, 0.01)]%"
..(msg)
/datum/subsystem/garbage_collector/fire()
HandleToBeQueued()
if (!paused)
HandleQueue()
//If you see this proc high on the profile, what you are really seeing is the garbage collection/soft delete overhead in byond.
//Don't attempt to optimize, not worth the effort.
/datum/subsystem/garbage_collector/proc/HandleToBeQueued()
var/list/tobequeued = src.tobequeued
var/starttime = world.time
var/starttimeofday = world.timeofday
while(tobequeued.len && starttime == world.time && starttimeofday == world.timeofday)
if (MC_TICK_CHECK)
break
var/ref = tobequeued[1]
Queue(ref)
tobequeued.Cut(1, 2)
/datum/subsystem/garbage_collector/proc/HandleQueue(time_to_stop)
delslasttick = 0
gcedlasttick = 0
var/time_to_kill = world.time - collection_timeout // Anything qdel() but not GC'd BEFORE this time needs to be manually del()
var/list/queue = src.queue
var/starttime = world.time
var/starttimeofday = world.timeofday
while(queue.len && starttime == world.time && starttimeofday == world.timeofday)
if (MC_TICK_CHECK)
break
var/refID = queue[1]
if (!refID)
queue.Cut(1, 2)
continue
var/GCd_at_time = queue[refID]
if(GCd_at_time > time_to_kill)
break // Everything else is newer, skip them
queue.Cut(1, 2)
var/datum/A
A = locate(refID)
if (A && A.gc_destroyed == GCd_at_time) // So if something else coincidently gets the same ref, it's not deleted by mistake
// Something's still referring to the qdel'd object. Kill it.
var/type = A.type
testing("GC: -- \ref[A] | [type] was unable to be GC'd and was deleted --")
didntgc["[type]"]++
var/time = world.timeofday
var/tick = world.tick_usage
var/ticktime = world.time
del(A)
tick = (world.tick_usage-tick+((world.time-ticktime)/world.tick_lag*100))
if (tick > highest_del_tickusage)
highest_del_tickusage = tick
time = world.timeofday - time
if (!time && TICK_DELTA_TO_MS(tick) > 1)
time = TICK_DELTA_TO_MS(tick)/100
if (time > highest_del_time)
highest_del_time = time
if (time > 10)
log_game("Error: [type]([refID]) took longer then 1 second to delete (took [time/10] seconds to delete)")
message_admins("Error: [type]([refID]) took longer then 1 second to delete (took [time/10] seconds to delete).")
postpone(time/5)
break
++delslasttick
++totaldels
else
++gcedlasttick
++totalgcs
/datum/subsystem/garbage_collector/proc/QueueForQueuing(datum/A)
if (istype(A) && isnull(A.gc_destroyed))
tobequeued += A
A.gc_destroyed = GC_QUEUED_FOR_QUEUING
/datum/subsystem/garbage_collector/proc/Queue(datum/A)
if (!istype(A) || (!isnull(A.gc_destroyed) && A.gc_destroyed >= 0))
return
if (A.gc_destroyed == GC_QUEUED_FOR_HARD_DEL)
del(A)
return
var/gctime = world.time
var/refid = "\ref[A]"
A.gc_destroyed = gctime
if (queue[refid])
queue -= refid // Removing any previous references that were GC'd so that the current object will be at the end of the list.
queue[refid] = gctime
/datum/subsystem/garbage_collector/proc/HardQueue(datum/A)
if (istype(A) && isnull(A.gc_destroyed))
tobequeued += A
A.gc_destroyed = GC_QUEUED_FOR_HARD_DEL
/datum/subsystem/garbage_collector/Recover()
if (istype(SSgarbage.queue))
queue |= SSgarbage.queue
if (istype(SSgarbage.tobequeued))
tobequeued |= SSgarbage.tobequeued
// Should be treated as a replacement for the 'del' keyword.
// Datums passed to this will be given a chance to clean up references to allow the GC to collect them.
/proc/qdel(datum/D, force=FALSE)
if(!D)
return
#ifdef TESTING
SSgarbage.qdel_list += "[A.type]"
#endif
if(!istype(D))
del(D)
else if(isnull(D.gc_destroyed))
var/hint = D.Destroy(force) // Let our friend know they're about to get fucked up.
if(!D)
return
switch(hint)
if (QDEL_HINT_QUEUE) //qdel should queue the object for deletion.
SSgarbage.QueueForQueuing(D)
if (QDEL_HINT_LETMELIVE, QDEL_HINT_IWILLGC) //qdel should let the object live after calling destory.
if(!force)
return
// Returning LETMELIVE after being told to force destroy
// indicates the objects Destroy() does not respect force
if(!SSgarbage.noforcerespect["[D.type]"])
SSgarbage.noforcerespect["[D.type]"] = "[D.type]"
testing("WARNING: [D.type] has been force deleted, but is \
returning an immortal QDEL_HINT, indicating it does \
not respect the force flag for qdel(). It has been \
placed in the queue, further instances of this type \
will also be queued.")
SSgarbage.QueueForQueuing(D)
if (QDEL_HINT_HARDDEL) //qdel should assume this object won't gc, and queue a hard delete using a hard reference to save time from the locate()
SSgarbage.HardQueue(D)
if (QDEL_HINT_HARDDEL_NOW) //qdel should assume this object won't gc, and hard del it post haste.
del(D)
if (QDEL_HINT_PUTINPOOL) //qdel will put this object in the pool.
PlaceInPool(D, 0)
if (QDEL_HINT_FINDREFERENCE)//qdel will, if TESTING is enabled, display all references to this object, then queue the object for deletion.
SSgarbage.QueueForQueuing(D)
#ifdef TESTING
A.find_references()
#endif
else
if(!SSgarbage.noqdelhint["[D.type]"])
SSgarbage.noqdelhint["[D.type]"] = "[D.type]"
testing("WARNING: [D.type] is not returning a qdel hint. It is being placed in the queue. Further instances of this type will also be queued.")
SSgarbage.QueueForQueuing(D)
// Returns 1 if the object has been queued for deletion.
/proc/qdeleted(datum/D)
if(!istype(D))
return FALSE
if(D.gc_destroyed)
return TRUE
return FALSE
// Default implementation of clean-up code.
// This should be overridden to remove all references pointing to the object being destroyed.
// Return the appropriate QDEL_HINT; in most cases this is QDEL_HINT_QUEUE.
/datum/proc/Destroy(force=FALSE)
tag = null
return QDEL_HINT_QUEUE
/datum/var/gc_destroyed //Time when this object was destroyed.
#ifdef TESTING
/client/var/running_find_references
/datum/var/running_find_references
/datum/verb/find_references()
set category = "Debug"
set name = "Find References"
set background = 1
set src in world
running_find_references = type
if(usr && usr.client)
if(usr.client.running_find_references)
testing("CANCELLED search for references to a [usr.client.running_find_references].")
usr.client.running_find_references = null
running_find_references = null
//restart the garbage collector
SSgarbage.can_fire = 1
SSgarbage.next_fire = world.time + world.tick_lag
return
if(alert("Running this will create a lot of lag until it finishes. You can cancel it by running it again. Would you like to begin the search?", "Find References", "Yes", "No") == "No")
running_find_references = null
return
//this keeps the garbage collector from failing to collect objects being searched for in here
SSgarbage.can_fire = 0
if(usr && usr.client)
usr.client.running_find_references = type
testing("Beginning search for references to a [type].")
var/list/things = list()
for(var/client/thing)
things |= thing
for(var/datum/thing)
things |= thing
testing("Collected list of things in search for references to a [type]. ([things.len] Thing\s)")
for(var/datum/thing in things)
if(usr && usr.client && !usr.client.running_find_references) return
for(var/varname in thing.vars)
var/variable = thing.vars[varname]
if(variable == src)
testing("Found [src.type] \ref[src] in [thing.type]'s [varname] var.")
else if(islist(variable))
if(src in variable)
testing("Found [src.type] \ref[src] in [thing.type]'s [varname] list var.")
testing("Completed search for references to a [type].")
if(usr && usr.client)
usr.client.running_find_references = null
running_find_references = null
//restart the garbage collector
SSgarbage.can_fire = 1
SSgarbage.next_fire = world.time + world.tick_lag
/client/verb/purge_all_destroyed_objects()
set category = "Debug"
if(SSgarbage)
while(SSgarbage.queue.len)
var/datum/o = locate(SSgarbage.queue[1])
if(istype(o) && o.gc_destroyed)
del(o)
SSgarbage.totaldels++
SSgarbage.queue.Cut(1, 2)
/datum/verb/qdel_then_find_references()
set category = "Debug"
set name = "qdel() then Find References"
set background = 1
set src in world
qdel(src)
if(!running_find_references)
find_references()
/client/verb/show_qdeleted()
set category = "Debug"
set name = "Show qdel() Log"
set desc = "Render the qdel() log and display it"
var/dat = "<B>List of things that have been qdel()eted this round</B><BR><BR>"
var/tmplist = list()
for(var/elem in SSgarbage.qdel_list)
if(!(elem in tmplist))
tmplist[elem] = 0
tmplist[elem]++
for(var/path in tmplist)
dat += "[path] - [tmplist[path]] times<BR>"
usr << browse(dat, "window=qdeletedlog")
#endif
+32
View File
@@ -0,0 +1,32 @@
var/datum/subsystem/icon_smooth/SSicon_smooth
/datum/subsystem/icon_smooth
name = "Icon Smoothing"
init_order = -5
wait = 1
priority = 35
flags = SS_TICKER
var/list/smooth_queue = list()
/datum/subsystem/icon_smooth/New()
NEW_SS_GLOBAL(SSicon_smooth)
/datum/subsystem/icon_smooth/fire()
while(smooth_queue.len)
var/atom/A = smooth_queue[smooth_queue.len]
smooth_queue.len--
ss_smooth_icon(A)
if (MC_TICK_CHECK)
return
if (!smooth_queue.len)
can_fire = 0
/datum/subsystem/icon_smooth/Initialize()
smooth_zlevel(1,TRUE)
smooth_zlevel(2,TRUE)
for(var/V in smooth_queue)
var/atom/A = V
if(A.z == 1 || A.z == 2)
smooth_queue -= A
..()
+19
View File
@@ -0,0 +1,19 @@
var/datum/subsystem/ipintel/SSipintel
/datum/subsystem/ipintel
name = "XKeyScore"
init_order = -10
flags = SS_NO_FIRE
var/enabled = 0 //disable at round start to avoid checking reconnects
var/throttle = 0
var/errors = 0
var/list/cache = list()
/datum/subsystem/ipintel/New()
NEW_SS_GLOBAL(SSipintel)
/datum/subsystem/ipintel/Initialize(timeofday, zlevel)
enabled = 1
. = ..()
+489
View File
@@ -0,0 +1,489 @@
var/datum/subsystem/job/SSjob
/datum/subsystem/job
name = "Jobs"
init_order = 5
flags = SS_NO_FIRE
var/list/occupations = list() //List of all jobs
var/list/unassigned = list() //Players who need jobs
var/list/job_debug = list() //Debug info
var/initial_players_to_assign = 0 //used for checking against population caps
/datum/subsystem/job/New()
NEW_SS_GLOBAL(SSjob)
/datum/subsystem/job/Initialize(timeofday)
SetupOccupations()
if(config.load_jobs_from_txt)
LoadJobs()
..()
/datum/subsystem/job/proc/SetupOccupations(faction = "Station")
occupations = list()
var/list/all_jobs = subtypesof(/datum/job)
if(!all_jobs.len)
world << "<span class='boldannounce'>Error setting up jobs, no job datums found</span>"
return 0
for(var/J in all_jobs)
var/datum/job/job = new J()
if(!job)
continue
if(job.faction != faction)
continue
if(!job.config_check())
continue
occupations += job
return 1
/datum/subsystem/job/proc/Debug(text)
if(!Debug2)
return 0
job_debug.Add(text)
return 1
/datum/subsystem/job/proc/GetJob(rank)
if(!rank)
return null
for(var/datum/job/J in occupations)
if(!J)
continue
if(J.title == rank)
return J
return null
/datum/subsystem/job/proc/AssignRole(mob/new_player/player, rank, latejoin=0)
Debug("Running AR, Player: [player], Rank: [rank], LJ: [latejoin]")
if(player && player.mind && rank)
var/datum/job/job = GetJob(rank)
if(!job)
return 0
if(jobban_isbanned(player, rank))
return 0
if(!job.player_old_enough(player.client))
return 0
var/position_limit = job.total_positions
if(!latejoin)
position_limit = job.spawn_positions
Debug("Player: [player] is now Rank: [rank], JCP:[job.current_positions], JPL:[position_limit]")
player.mind.assigned_role = rank
unassigned -= player
job.current_positions++
return 1
Debug("AR has failed, Player: [player], Rank: [rank]")
return 0
/datum/subsystem/job/proc/FindOccupationCandidates(datum/job/job, level, flag)
Debug("Running FOC, Job: [job], Level: [level], Flag: [flag]")
var/list/candidates = list()
for(var/mob/new_player/player in unassigned)
if(jobban_isbanned(player, job.title))
Debug("FOC isbanned failed, Player: [player]")
continue
if(!job.player_old_enough(player.client))
Debug("FOC player not old enough, Player: [player]")
continue
if(flag && (!(flag in player.client.prefs.be_special)))
Debug("FOC flag failed, Player: [player], Flag: [flag], ")
continue
if(player.mind && job.title in player.mind.restricted_roles)
Debug("FOC incompatible with antagonist role, Player: [player]")
continue
if(config.enforce_human_authority && !player.client.prefs.pref_species.qualifies_for_rank(job.title, player.client.prefs.features))
Debug("FOC non-human failed, Player: [player]")
continue
if(player.client.prefs.GetJobDepartment(job, level) & job.flag)
Debug("FOC pass, Player: [player], Level:[level]")
candidates += player
return candidates
/datum/subsystem/job/proc/GiveRandomJob(mob/new_player/player)
Debug("GRJ Giving random job, Player: [player]")
for(var/datum/job/job in shuffle(occupations))
if(!job)
continue
if(istype(job, GetJob("Assistant"))) // We don't want to give him assistant, that's boring!
continue
if(job.title in command_positions) //If you want a command position, select it!
continue
if(jobban_isbanned(player, job.title))
Debug("GRJ isbanned failed, Player: [player], Job: [job.title]")
continue
if(!job.player_old_enough(player.client))
Debug("GRJ player not old enough, Player: [player]")
continue
if(player.mind && job.title in player.mind.restricted_roles)
Debug("GRJ incompatible with antagonist role, Player: [player], Job: [job.title]")
continue
if(config.enforce_human_authority && !player.client.prefs.pref_species.qualifies_for_rank(job.title, player.client.prefs.features))
Debug("GRJ non-human failed, Player: [player]")
continue
if((job.current_positions < job.spawn_positions) || job.spawn_positions == -1)
Debug("GRJ Random job given, Player: [player], Job: [job]")
AssignRole(player, job.title)
unassigned -= player
break
/datum/subsystem/job/proc/ResetOccupations()
for(var/mob/new_player/player in player_list)
if((player) && (player.mind))
player.mind.assigned_role = null
player.mind.special_role = null
SetupOccupations()
unassigned = list()
return
//This proc is called before the level loop of DivideOccupations() and will try to select a head, ignoring ALL non-head preferences for every level until
//it locates a head or runs out of levels to check
//This is basically to ensure that there's atleast a few heads in the round
/datum/subsystem/job/proc/FillHeadPosition()
for(var/level = 1 to 3)
for(var/command_position in command_positions)
var/datum/job/job = GetJob(command_position)
if(!job)
continue
if((job.current_positions >= job.total_positions) && job.total_positions != -1)
continue
var/list/candidates = FindOccupationCandidates(job, level)
if(!candidates.len)
continue
var/mob/new_player/candidate = pick(candidates)
if(AssignRole(candidate, command_position))
return 1
return 0
//This proc is called at the start of the level loop of DivideOccupations() and will cause head jobs to be checked before any other jobs of the same level
//This is also to ensure we get as many heads as possible
/datum/subsystem/job/proc/CheckHeadPositions(level)
for(var/command_position in command_positions)
var/datum/job/job = GetJob(command_position)
if(!job)
continue
if((job.current_positions >= job.total_positions) && job.total_positions != -1)
continue
var/list/candidates = FindOccupationCandidates(job, level)
if(!candidates.len)
continue
var/mob/new_player/candidate = pick(candidates)
AssignRole(candidate, command_position)
return
/datum/subsystem/job/proc/FillAIPosition()
var/ai_selected = 0
var/datum/job/job = GetJob("AI")
if(!job)
return 0
for(var/i = job.total_positions, i > 0, i--)
for(var/level = 1 to 3)
var/list/candidates = list()
candidates = FindOccupationCandidates(job, level)
if(candidates.len)
var/mob/new_player/candidate = pick(candidates)
if(AssignRole(candidate, "AI"))
ai_selected++
break
if(ai_selected)
return 1
return 0
/** Proc DivideOccupations
* fills var "assigned_role" for all ready players.
* This proc must not have any side effect besides of modifying "assigned_role".
**/
/datum/subsystem/job/proc/DivideOccupations()
//Setup new player list and get the jobs list
Debug("Running DO")
//Holder for Triumvirate is stored in the ticker, this just processes it
if(ticker)
for(var/datum/job/ai/A in occupations)
if(ticker.triai)
A.spawn_positions = 3
//Get the players who are ready
for(var/mob/new_player/player in player_list)
if(player.ready && player.mind && !player.mind.assigned_role)
unassigned += player
initial_players_to_assign = unassigned.len
Debug("DO, Len: [unassigned.len]")
if(unassigned.len == 0)
return 0
//Scale number of open security officer slots to population
setup_officer_positions()
//Jobs will have fewer access permissions if the number of players exceeds the threshold defined in game_options.txt
if(config.minimal_access_threshold)
if(config.minimal_access_threshold > unassigned.len)
config.jobs_have_minimal_access = 0
else
config.jobs_have_minimal_access = 1
//Shuffle players and jobs
unassigned = shuffle(unassigned)
HandleFeedbackGathering()
//People who wants to be assistants, sure, go on.
Debug("DO, Running Assistant Check 1")
var/datum/job/assist = new /datum/job/assistant()
var/list/assistant_candidates = FindOccupationCandidates(assist, 3)
Debug("AC1, Candidates: [assistant_candidates.len]")
for(var/mob/new_player/player in assistant_candidates)
Debug("AC1 pass, Player: [player]")
AssignRole(player, "Assistant")
assistant_candidates -= player
Debug("DO, AC1 end")
//Select one head
Debug("DO, Running Head Check")
FillHeadPosition()
Debug("DO, Head Check end")
//Check for an AI
Debug("DO, Running AI Check")
FillAIPosition()
Debug("DO, AI Check end")
//Other jobs are now checked
Debug("DO, Running Standard Check")
// New job giving system by Donkie
// This will cause lots of more loops, but since it's only done once it shouldn't really matter much at all.
// Hopefully this will add more randomness and fairness to job giving.
// Loop through all levels from high to low
var/list/shuffledoccupations = shuffle(occupations)
for(var/level = 1 to 3)
//Check the head jobs first each level
CheckHeadPositions(level)
// Loop through all unassigned players
for(var/mob/new_player/player in unassigned)
if(PopcapReached())
RejectPlayer(player)
// Loop through all jobs
for(var/datum/job/job in shuffledoccupations) // SHUFFLE ME BABY
if(!job)
continue
if(jobban_isbanned(player, job.title))
Debug("DO isbanned failed, Player: [player], Job:[job.title]")
continue
if(!job.player_old_enough(player.client))
Debug("DO player not old enough, Player: [player], Job:[job.title]")
continue
if(player.mind && job.title in player.mind.restricted_roles)
Debug("DO incompatible with antagonist role, Player: [player], Job:[job.title]")
continue
if(config.enforce_human_authority && !player.client.prefs.pref_species.qualifies_for_rank(job.title, player.client.prefs.features))
Debug("DO non-human failed, Player: [player], Job:[job.title]")
continue
// If the player wants that job on this level, then try give it to him.
if(player.client.prefs.GetJobDepartment(job, level) & job.flag)
// If the job isn't filled
if((job.current_positions < job.spawn_positions) || job.spawn_positions == -1)
Debug("DO pass, Player: [player], Level:[level], Job:[job.title]")
AssignRole(player, job.title)
unassigned -= player
break
// Hand out random jobs to the people who didn't get any in the last check
// Also makes sure that they got their preference correct
for(var/mob/new_player/player in unassigned)
if(PopcapReached())
RejectPlayer(player)
else if(jobban_isbanned(player, "Assistant"))
GiveRandomJob(player) //you get to roll for random before everyone else just to be sure you don't get assistant. you're so speshul
for(var/mob/new_player/player in unassigned)
if(PopcapReached())
RejectPlayer(player)
else if(player.client.prefs.userandomjob)
GiveRandomJob(player)
Debug("DO, Standard Check end")
Debug("DO, Running AC2")
// For those who wanted to be assistant if their preferences were filled, here you go.
for(var/mob/new_player/player in unassigned)
if(PopcapReached())
RejectPlayer(player)
Debug("AC2 Assistant located, Player: [player]")
AssignRole(player, "Assistant")
return 1
//Gives the player the stuff he should have with his rank
/datum/subsystem/job/proc/EquipRank(mob/living/H, rank, joined_late=0)
var/datum/job/job = GetJob(rank)
H.job = rank
//If we joined at roundstart we should be positioned at our workstation
if(!joined_late)
var/obj/S = null
for(var/obj/effect/landmark/start/sloc in start_landmarks_list)
if(sloc.name != rank)
S = sloc //so we can revert to spawning them on top of eachother if something goes wrong
continue
if(locate(/mob/living) in sloc.loc)
continue
S = sloc
break
if(!S) //if there isn't a spawnpoint send them to latejoin, if there's no latejoin go yell at your mapper
world.log << "Couldn't find a round start spawn point for [rank]"
S = pick(latejoin)
if(!S) //final attempt, lets find some area in the arrivals shuttle to spawn them in to.
world.log << "Couldn't find a round start latejoin spawn point."
for(var/turf/T in get_area_turfs(/area/shuttle/arrival))
if(!T.density)
var/clear = 1
for(var/obj/O in T)
if(O.density)
clear = 0
break
if(clear)
S = T
continue
if(istype(S, /obj/effect/landmark) && istype(S.loc, /turf))
H.loc = S.loc
if(H.mind)
H.mind.assigned_role = rank
if(job)
var/new_mob = job.equip(H)
if(ismob(new_mob))
H = new_mob
job.apply_fingerprints(H)
H << "<b>You are the [rank].</b>"
H << "<b>As the [rank] you answer directly to [job.supervisors]. Special circumstances may change this.</b>"
H << "<b>To speak on your departments radio, use the :h button. To see others, look closely at your headset.</b>"
if(job.req_admin_notify)
H << "<b>You are playing a job that is important for Game Progression. If you have to disconnect, please notify the admins via adminhelp.</b>"
if(config.minimal_access_threshold)
H << "<FONT color='blue'><B>As this station was initially staffed with a [config.jobs_have_minimal_access ? "full crew, only your job's necessities" : "skeleton crew, additional access may"] have been added to your ID card.</B></font>"
return 1
/datum/subsystem/job/proc/setup_officer_positions()
var/datum/job/J = SSjob.GetJob("Security Officer")
if(!J)
throw EXCEPTION("setup_officer_positions(): Security officer job is missing")
if(config.security_scaling_coeff > 0)
if(J.spawn_positions > 0)
var/officer_positions = min(12, max(J.spawn_positions, round(unassigned.len/config.security_scaling_coeff))) //Scale between configured minimum and 12 officers
Debug("Setting open security officer positions to [officer_positions]")
J.total_positions = officer_positions
J.spawn_positions = officer_positions
//Spawn some extra eqipment lockers if we have more than 5 officers
var/equip_needed = J.total_positions
if(equip_needed < 0) // -1: infinite available slots
equip_needed = 12
for(var/i=equip_needed-5, i>0, i--)
if(secequipment.len)
var/spawnloc = secequipment[1]
new /obj/structure/closet/secure_closet/security/sec(spawnloc)
secequipment -= spawnloc
else //We ran out of spare locker spawns!
break
/datum/subsystem/job/proc/LoadJobs()
var/jobstext = return_file_text("config/jobs.txt")
for(var/datum/job/J in occupations)
var/regex/jobs = new("[J.title]=(-1|\\d+),(-1|\\d+)")
jobs.Find(jobstext)
J.total_positions = text2num(jobs.group[1])
J.spawn_positions = text2num(jobs.group[2])
/datum/subsystem/job/proc/HandleFeedbackGathering()
for(var/datum/job/job in occupations)
var/tmp_str = "|[job.title]|"
var/level1 = 0 //high
var/level2 = 0 //medium
var/level3 = 0 //low
var/level4 = 0 //never
var/level5 = 0 //banned
var/level6 = 0 //account too young
for(var/mob/new_player/player in player_list)
if(!(player.ready && player.mind && !player.mind.assigned_role))
continue //This player is not ready
if(jobban_isbanned(player, job.title))
level5++
continue
if(!job.player_old_enough(player.client))
level6++
continue
if(player.client.prefs.GetJobDepartment(job, 1) & job.flag)
level1++
else if(player.client.prefs.GetJobDepartment(job, 2) & job.flag)
level2++
else if(player.client.prefs.GetJobDepartment(job, 3) & job.flag)
level3++
else level4++ //not selected
tmp_str += "HIGH=[level1]|MEDIUM=[level2]|LOW=[level3]|NEVER=[level4]|BANNED=[level5]|YOUNG=[level6]|-"
feedback_add_details("job_preferences",tmp_str)
/datum/subsystem/job/proc/PopcapReached()
if(config.hard_popcap || config.extreme_popcap)
var/relevent_cap = max(config.hard_popcap, config.extreme_popcap)
if((initial_players_to_assign - unassigned.len) >= relevent_cap)
return 1
return 0
/datum/subsystem/job/proc/RejectPlayer(mob/new_player/player)
if(player.mind && player.mind.special_role)
return
Debug("Popcap overflow Check observer located, Player: [player]")
player << "<b>You have failed to qualify for any job you desired.</b>"
unassigned -= player
player.ready = 0
/datum/subsystem/job/Recover()
var/oldjobs = SSjob.occupations
spawn(20)
for (var/datum/job/J in oldjobs)
spawn(-1)
var/datum/job/newjob = GetJob(J.title)
if (!istype(newjob))
return
newjob.total_positions = J.total_positions
newjob.spawn_positions = J.spawn_positions
newjob.current_positions = J.current_positions
+116
View File
@@ -0,0 +1,116 @@
var/datum/subsystem/lighting/SSlighting
#define SSLIGHTING_LIGHTS 1
#define SSLIGHTING_TURFS 2
/datum/subsystem/lighting
name = "Lighting"
init_order = 1
wait = 1
flags = SS_POST_FIRE_TIMING
priority = 40
display_order = 5
var/list/changed_lights = list() //list of all datum/light_source that need updating
var/changed_lights_workload = 0 //stats on the largest number of lights (max changed_lights.len)
var/list/changed_turfs = list() //list of all turfs which may have a different light level
var/changed_turfs_workload = 0 //stats on the largest number of turfs changed (max changed_turfs.len)
/datum/subsystem/lighting/New()
NEW_SS_GLOBAL(SSlighting)
return ..()
/datum/subsystem/lighting/stat_entry()
..("L:[round(changed_lights_workload,1)]|T:[round(changed_turfs_workload,1)]")
//Workhorse of lighting. It cycles through each light that needs updating. It updates their
//effects and then processes every turf in the queue, updating their lighting object's appearance
//Any light that returns 1 in check() deletes itself
//By using queues we are ensuring we don't perform more updates than are necessary
/datum/subsystem/lighting/fire(resumed = 0)
var/ticklimit = CURRENT_TICKLIMIT
//split our tick allotment in half so we don't spend it all on lightshift checks
CURRENT_TICKLIMIT = world.tick_usage + ((ticklimit-world.tick_usage)/2)
var/list/changed_lights = src.changed_lights
if (!resumed)
changed_lights_workload = MC_AVERAGE(changed_lights_workload, changed_lights.len)
var/i = 1
while (i <= changed_lights.len)
var/datum/light_source/LS = changed_lights[i++]
LS.check()
if (MC_TICK_CHECK)
break
if (i > 1)
changed_lights.Cut(1,i)
CURRENT_TICKLIMIT = ticklimit
var/list/changed_turfs = src.changed_turfs
if (!resumed)
changed_turfs_workload = MC_AVERAGE(changed_turfs_workload, changed_turfs.len)
i = 1
while (i <= changed_turfs.len)
var/turf/T = changed_turfs[i++]
if(T.lighting_changed)
T.redraw_lighting()
if (MC_TICK_CHECK)
break
if (i > 1)
changed_turfs.Cut(1,i)
//same as above except it attempts to shift ALL turfs in the world regardless of lighting_changed status
/datum/subsystem/lighting/Initialize(timeofday)
var/list/turfs_to_init = block(locate(1, 1, 1), locate(world.maxx, world.maxy, world.maxz))
if (config.starlight)
for(var/area/A in world)
if (A.lighting_use_dynamic == DYNAMIC_LIGHTING_IFSTARLIGHT)
A.luminosity = 0
for(var/thing in changed_lights)
var/datum/light_source/LS = thing
LS.check()
changed_lights.Cut()
for(var/thing in turfs_to_init)
var/turf/T = thing
T.init_lighting()
changed_turfs.Cut()
..()
//Used to strip valid information from an existing instance and transfer it to the replacement. i.e. when a crash occurs
//It works by using spawn(-1) to transfer the data, if there is a runtime the data does not get transfered but the loop
//does not crash
/datum/subsystem/lighting/Recover()
if(!istype(SSlighting.changed_turfs))
SSlighting.changed_turfs = list()
if(!istype(SSlighting.changed_lights))
SSlighting.changed_lights = list()
for(var/thing in SSlighting.changed_lights)
var/datum/light_source/LS = thing
spawn(-1) //so we don't crash the loop (inefficient)
LS.check()
for(var/thing in changed_turfs)
var/turf/T = thing
if(T.lighting_changed)
spawn(-1)
T.redraw_lighting()
var/msg = "## DEBUG: [time2text(world.timeofday)] [name] subsystem restarted. Reports:\n"
for(var/varname in SSlighting.vars)
switch(varname)
if("tag","bestF","type","parent_type","vars")
continue
else
var/varval1 = SSlighting.vars[varname]
var/varval2 = vars[varname]
if(istype(varval1,/list))
varval1 = "/list([length(varval1)])"
varval2 = "/list([length(varval2)])"
msg += "\t [varname] = [varval1] -> [varval2]\n"
world.log << msg
+72
View File
@@ -0,0 +1,72 @@
var/datum/subsystem/machines/SSmachine
/datum/subsystem/machines
name = "Machines"
init_order = 9
display_order = 3
flags = SS_KEEP_TIMING
var/list/processing = list()
var/list/currentrun = list()
var/list/powernets = list()
/datum/subsystem/machines/Initialize()
makepowernets()
fire()
..()
/datum/subsystem/machines/proc/makepowernets()
for(var/datum/powernet/PN in powernets)
qdel(PN)
powernets.Cut()
for(var/obj/structure/cable/PC in cable_list)
if(!PC.powernet)
var/datum/powernet/NewPN = new()
NewPN.add_cable(PC)
propagate_network(PC,PC.powernet)
/datum/subsystem/machines/New()
NEW_SS_GLOBAL(SSmachine)
/datum/subsystem/machines/stat_entry()
..("M:[processing.len]|PN:[powernets.len]")
/datum/subsystem/machines/fire(resumed = 0)
if (!resumed)
for(var/datum/powernet/Powernet in powernets)
Powernet.reset() //reset the power state.
src.currentrun = processing.Copy()
//cache for sanic speed (lists are references anyways)
var/list/currentrun = src.currentrun
var/seconds = wait * 0.1
while(currentrun.len)
var/datum/thing = currentrun[currentrun.len]
currentrun.len--
if(thing && thing.process(seconds) != PROCESS_KILL)
if(thing:use_power)
thing:auto_use_power() //add back the power state
else
processing -= thing
if (thing)
thing.isprocessing = 0
if (MC_TICK_CHECK)
return
/datum/subsystem/machines/proc/setup_template_powernets(list/cables)
for(var/A in cables)
var/obj/structure/cable/PC = A
if(!PC.powernet)
var/datum/powernet/NewPN = new()
NewPN.add_cable(PC)
propagate_network(PC,PC.powernet)
/datum/subsystem/machines/Recover()
if (istype(SSmachine.processing))
processing = SSmachine.processing
if (istype(SSmachine.powernets))
powernets = SSmachine.powernets
+44
View File
@@ -0,0 +1,44 @@
var/datum/subsystem/mapping/SSmapping
/datum/subsystem/mapping
name = "Mapping"
init_order = 100000
flags = SS_NO_FIRE
display_order = 50
/datum/subsystem/mapping/New()
NEW_SS_GLOBAL(SSmapping)
return ..()
/datum/subsystem/mapping/Initialize(timeofday)
preloadTemplates()
// Pick a random away mission.
createRandomZlevel()
// Generate mining.
var/mining_type = MINETYPE
if (mining_type == "lavaland")
seedRuins(list(5), config.lavaland_budget, /area/lavaland/surface/outdoors, lava_ruins_templates)
spawn_rivers()
else
make_mining_asteroid_secrets()
// deep space ruins
var/space_zlevels = list()
for(var/i in ZLEVEL_SPACEMIN to ZLEVEL_SPACEMAX)
switch(i)
if(ZLEVEL_MINING, ZLEVEL_LAVALAND, ZLEVEL_EMPTY_SPACE)
continue
else
space_zlevels += i
seedRuins(space_zlevels, rand(8,16), /area/space, space_ruins_templates)
// Set up Z-level transistions.
setup_map_transitions()
..()
/datum/subsystem/mapping/Recover()
flags |= SS_NO_INIT
+110
View File
@@ -0,0 +1,110 @@
var/datum/subsystem/minimap/SSminimap
/datum/subsystem/minimap
name = "Minimap"
init_order = -2
flags = SS_NO_FIRE
var/const/MINIMAP_SIZE = 2048
var/const/TILE_SIZE = 8
var/list/z_levels = list(ZLEVEL_STATION)
/datum/subsystem/minimap/New()
NEW_SS_GLOBAL(SSminimap)
/datum/subsystem/minimap/Initialize(timeofday)
if(!config.generate_minimaps)
world << "Minimap generation disabled... Skipping"
return
var/hash = md5(file2text("_maps/[MAP_PATH]/[MAP_FILE]"))
if(hash == trim(file2text(hash_path())))
return ..()
for(var/z in z_levels)
generate(z)
register_asset("minimap_[z].png", fcopy_rsc(map_path(z)))
fdel(hash_path())
text2file(hash, hash_path())
..()
/datum/subsystem/minimap/proc/hash_path()
return "data/minimaps/[MAP_NAME].md5"
/datum/subsystem/minimap/proc/map_path(z)
return "data/minimaps/[MAP_NAME]_[z].png"
/datum/subsystem/minimap/proc/send(client/client)
for(var/z in z_levels)
send_asset(client, "minimap_[z].png")
/datum/subsystem/minimap/proc/generate(z = 1, x1 = 1, y1 = 1, x2 = world.maxx, y2 = world.maxy)
// Load the background.
var/icon/minimap = new /icon('icons/minimap.dmi')
// Scale it up to our target size.
minimap.Scale(MINIMAP_SIZE, MINIMAP_SIZE)
var/counter = 512
// Loop over turfs and generate icons.
for(var/T in block(locate(x1, y1, z), locate(x2, y2, z)))
generate_tile(T, minimap)
//byond bug, this fixes OOM crashes by flattening and reseting the minimap icon holder every so and so tiles
counter--
if(counter <= 0)
counter = 512
var/icon/flatten = new /icon()
flatten.Insert(minimap, "", SOUTH, 1, 0)
del(minimap)
minimap = flatten
stoplag() //we have to sleep in order to get byond to clear out the proc's garbage bin
CHECK_TICK
// Create a new icon and insert the generated minimap, so that BYOND doesn't generate different directions.
var/icon/final = new /icon()
final.Insert(minimap, "", SOUTH, 1, 0)
fcopy(final, map_path(z))
/datum/subsystem/minimap/proc/generate_tile(turf/tile, icon/minimap)
var/icon/tile_icon
var/obj/obj
var/list/obj_icons = list()
// Don't use icons for space, just add objects in space if they exist.
if(istype(tile, /turf/open/space))
obj = locate(/obj/structure/lattice/catwalk) in tile
if(obj)
tile_icon = new /icon('icons/obj/smooth_structures/catwalk.dmi', "catwalk", SOUTH)
obj = locate(/obj/structure/lattice) in tile
if(obj)
tile_icon = new /icon('icons/obj/smooth_structures/lattice.dmi', "lattice", SOUTH)
obj = locate(/obj/structure/grille) in tile
if(obj)
tile_icon = new /icon('icons/obj/structures.dmi', "grille", SOUTH)
obj = locate(/obj/structure/transit_tube) in tile
if(obj)
tile_icon = new /icon('icons/obj/atmospherics/pipes/transit_tube.dmi', obj.icon_state, obj.dir)
else
tile_icon = new /icon(tile.icon, tile.icon_state, tile.dir)
obj_icons.Cut()
obj = locate(/obj/structure) in tile
if(obj)
obj_icons += getFlatIcon(obj)
obj = locate(/obj/machinery) in tile
if(obj)
obj_icons += new /icon(obj.icon, obj.icon_state, obj.dir, 1, 0)
obj = locate(/obj/structure/window) in tile
if(obj)
obj_icons += new /icon('icons/obj/smooth_structures/window.dmi', "window", SOUTH)
for(var/I in obj_icons)
var/icon/obj_icon = I
tile_icon.Blend(obj_icon, ICON_OVERLAY)
if(tile_icon)
// Scale the icon.
tile_icon.Scale(TILE_SIZE, TILE_SIZE)
// Add the tile to the minimap.
minimap.Blend(tile_icon, ICON_OVERLAY, ((tile.x - 1) * TILE_SIZE), ((tile.y - 1) * TILE_SIZE))
del(tile_icon)
+36
View File
@@ -0,0 +1,36 @@
var/datum/subsystem/mobs/SSmob
/datum/subsystem/mobs
name = "Mobs"
init_order = 4
display_order = 4
priority = 100
flags = SS_KEEP_TIMING|SS_NO_INIT
var/list/currentrun = list()
/datum/subsystem/mobs/New()
NEW_SS_GLOBAL(SSmob)
/datum/subsystem/mobs/stat_entry()
..("P:[mob_list.len]")
/datum/subsystem/mobs/fire(resumed = 0)
var/seconds = wait * 0.1
if (!resumed)
src.currentrun = mob_list.Copy()
//cache for sanic speed (lists are references anyways)
var/list/currentrun = src.currentrun
while(currentrun.len)
var/mob/M = currentrun[currentrun.len]
currentrun.len--
if(M)
M.Life(seconds)
else
mob_list.Remove(M)
if (MC_TICK_CHECK)
return
+128
View File
@@ -0,0 +1,128 @@
var/datum/subsystem/npcpool/SSnpc
/datum/subsystem/npcpool
name = "NPC Pool"
init_order = 17
display_order = 6
flags = SS_POST_FIRE_TIMING|SS_NO_INIT|SS_NO_TICK_CHECK
priority = 25
var/list/canBeUsed = list()
var/list/canBeUsed_non = list()
var/list/needsDelegate = list()
var/list/needsAssistant = list()
var/list/needsHelp_non = list()
var/list/botPool_l = list() //list of all npcs using the pool
var/list/botPool_l_non = list() //list of all non SNPC mobs using the pool
/datum/subsystem/npcpool/proc/insertBot(toInsert)
if(istype(toInsert,/mob/living/carbon/human/interactive))
botPool_l |= toInsert
/datum/subsystem/npcpool/New()
NEW_SS_GLOBAL(SSnpc)
/datum/subsystem/npcpool/stat_entry()
..("T:[botPool_l.len + botPool_l_non.len]|D:[needsDelegate.len]|A:[needsAssistant.len + needsHelp_non.len]|U:[canBeUsed.len + canBeUsed_non.len]")
/datum/subsystem/npcpool/proc/cleanNull()
//cleanup nulled bots
listclearnulls(botPool_l)
listclearnulls(needsDelegate)
listclearnulls(canBeUsed)
listclearnulls(needsAssistant)
/datum/subsystem/npcpool/fire()
//bot delegation and coordination systems
//General checklist/Tasks for delegating a task or coordinating it (for SNPCs)
// 1. Bot proximity to task target: if too far, delegate, if close, coordinate
// 2. Bot Health/status: check health with bots in local area, if their health is higher, delegate task to them, else coordinate
// 3. Process delegation: if a bot (or bots) has been delegated, assign them to the task.
// 4. Process coordination: if a bot(or bots) has been asked to coordinate, assign them to help.
// 5. Do all assignments: goes through the delegated/coordianted bots and assigns the right variables/tasks to them.
var/npcCount = 1
cleanNull()
//SNPC handling
for(var/mob/living/carbon/human/interactive/check in botPool_l)
if(!check)
botPool_l.Cut(npcCount,npcCount+1)
continue
var/checkInRange = view(MAX_RANGE_FIND,check)
if(!(locate(check.TARGET) in checkInRange))
needsDelegate |= check
else if(check.IsDeadOrIncap(FALSE))
needsDelegate |= check
else if(check.doing & FIGHTING)
needsAssistant |= check
else
canBeUsed |= check
npcCount++
if(needsDelegate.len)
needsDelegate -= pick(needsDelegate) // cheapo way to make sure stuff doesn't pingpong around in the pool forever. delegation runs seperately to each loop so it will work much smoother
npcCount = 1 //reset the count
for(var/mob/living/carbon/human/interactive/check in needsDelegate)
if(!check)
needsDelegate.Cut(npcCount,npcCount+1)
continue
if(canBeUsed.len)
var/mob/living/carbon/human/interactive/candidate = pick(canBeUsed)
var/facCount = 0
var/helpProb = 0
for(var/C in check.faction)
for(var/D in candidate.faction)
if(D == C)
helpProb = min(100,helpProb + 25)
facCount++
if(facCount == 1 && helpProb > 0)
helpProb = 100
if(prob(helpProb))
if(candidate.takeDelegate(check))
needsDelegate -= check
canBeUsed -= candidate
candidate.eye_color = "red"
candidate.update_icons()
npcCount++
if(needsAssistant.len)
needsAssistant -= pick(needsAssistant)
npcCount = 1 //reset the count
for(var/mob/living/carbon/human/interactive/check in needsAssistant)
if(!check)
needsAssistant.Cut(npcCount,npcCount+1)
continue
if(canBeUsed.len)
var/mob/living/carbon/human/interactive/candidate = pick(canBeUsed)
var/facCount = 0
var/helpProb = 0
for(var/C in check.faction)
for(var/D in candidate.faction)
if(D == C)
helpProb = min(100,helpProb + 25)
facCount++
if(facCount == 1 && helpProb > 0)
helpProb = 100
if(prob(helpProb))
if(candidate.takeDelegate(check,FALSE))
needsAssistant -= check
canBeUsed -= candidate
candidate.eye_color = "yellow"
candidate.update_icons()
npcCount++
/datum/subsystem/npcpool/Recover()
if (istype(SSnpc.botPool_l))
botPool_l = SSnpc.botPool_l
if (istype(SSnpc.botPool_l_non))
botPool_l_non = SSnpc.botPool_l_non
+77
View File
@@ -0,0 +1,77 @@
var/datum/subsystem/objects/SSobj
/datum/var/isprocessing = 0
/datum/proc/process()
set waitfor = 0
STOP_PROCESSING(SSobj, src)
return 0
/datum/subsystem/objects
name = "Objects"
init_order = 12
priority = 40
var/list/atom_spawners = list()
var/list/processing = list()
var/list/currentrun = list()
var/list/burning = list()
/datum/subsystem/objects/New()
NEW_SS_GLOBAL(SSobj)
/datum/subsystem/objects/Initialize(timeofdayl)
trigger_atom_spawners()
setupGenetics()
for(var/thing in world)
var/atom/A = thing
A.initialize()
CHECK_TICK
. = ..()
/datum/subsystem/objects/proc/trigger_atom_spawners(zlevel, ignore_z=FALSE)
for(var/V in atom_spawners)
var/atom/A = V
if (!ignore_z && (zlevel && A.z != zlevel))
continue
A.spawn_atom_to_world()
/datum/subsystem/objects/stat_entry()
..("P:[processing.len]")
/datum/subsystem/objects/fire(resumed = 0)
if (!resumed)
src.currentrun = processing.Copy()
//cache for sanic speed (lists are references anyways)
var/list/currentrun = src.currentrun
while(currentrun.len)
var/datum/thing = currentrun[currentrun.len]
currentrun.len--
if(thing)
thing.process(wait)
else
SSobj.processing -= thing
if (MC_TICK_CHECK)
return
for(var/obj/burningobj in SSobj.burning)
if(burningobj && (burningobj.burn_state == ON_FIRE))
if(burningobj.burn_world_time < world.time)
burningobj.burn()
else
SSobj.burning.Remove(burningobj)
/datum/subsystem/objects/proc/setup_template_objects(list/objects)
trigger_atom_spawners(0, ignore_z=TRUE)
for(var/A in objects)
var/atom/B = A
B.initialize()
/datum/subsystem/objects/Recover()
if (istype(SSobj.atom_spawners))
atom_spawners = SSobj.atom_spawners
if (istype(SSobj.processing))
processing = SSobj.processing
if (istype(SSobj.burning))
burning = SSobj.burning
+219
View File
@@ -0,0 +1,219 @@
var/datum/subsystem/pai/SSpai
/datum/subsystem/pai
name = "pAI"
init_order = 20
flags = SS_NO_FIRE|SS_NO_INIT
var/askDelay = 600
var/const/NEVER_FOR_THIS_ROUND = -1
var/list/candidates = list()
var/list/asked = list()
/datum/subsystem/pai/New()
NEW_SS_GLOBAL(SSpai)
/datum/subsystem/pai/Topic(href, href_list[])
if(href_list["download"])
var/datum/paiCandidate/candidate = locate(href_list["candidate"])
var/obj/item/device/paicard/card = locate(href_list["device"])
if(card.pai)
return
if(istype(card,/obj/item/device/paicard) && istype(candidate,/datum/paiCandidate))
var/mob/living/silicon/pai/pai = new(card)
if(!candidate.name)
pai.name = pick(ninja_names)
else
pai.name = candidate.name
pai.real_name = pai.name
pai.key = candidate.key
card.setPersonality(pai)
card.looking_for_personality = 0
ticker.mode.update_cult_icons_removed(card.pai.mind)
ticker.mode.update_rev_icons_removed(card.pai.mind)
candidates -= candidate
usr << browse(null, "window=findPai")
if(href_list["new"])
var/datum/paiCandidate/candidate = locate(href_list["candidate"])
var/option = href_list["option"]
var/t = ""
switch(option)
if("name")
t = input("Enter a name for your pAI", "pAI Name", candidate.name) as text
if(t)
candidate.name = copytext(sanitize(t),1,MAX_NAME_LEN)
if("desc")
t = input("Enter a description for your pAI", "pAI Description", candidate.description) as message
if(t)
candidate.description = copytext(sanitize(t),1,MAX_MESSAGE_LEN)
if("role")
t = input("Enter a role for your pAI", "pAI Role", candidate.role) as text
if(t)
candidate.role = copytext(sanitize(t),1,MAX_MESSAGE_LEN)
if("ooc")
t = input("Enter any OOC comments", "pAI OOC Comments", candidate.comments) as message
if(t)
candidate.comments = copytext(sanitize(t),1,MAX_MESSAGE_LEN)
if("save")
candidate.savefile_save(usr)
if("load")
candidate.savefile_load(usr)
//In case people have saved unsanitized stuff.
if(candidate.name)
candidate.name = copytext(sanitize(candidate.name),1,MAX_NAME_LEN)
if(candidate.description)
candidate.description = copytext(sanitize(candidate.description),1,MAX_MESSAGE_LEN)
if(candidate.role)
candidate.role = copytext(sanitize(candidate.role),1,MAX_MESSAGE_LEN)
if(candidate.comments)
candidate.comments = copytext(sanitize(candidate.comments),1,MAX_MESSAGE_LEN)
if("submit")
if(candidate)
candidate.ready = 1
for(var/obj/item/device/paicard/p in world)
if(p.looking_for_personality == 1)
p.alertUpdate()
usr << browse(null, "window=paiRecruit")
return
recruitWindow(usr)
/datum/subsystem/pai/proc/recruitWindow(mob/M)
var/datum/paiCandidate/candidate
for(var/datum/paiCandidate/c in candidates)
if(c.key == M.key)
candidate = c
if(!candidate)
candidate = new /datum/paiCandidate()
candidate.key = M.key
candidates.Add(candidate)
var/dat = ""
dat += {"
<style type="text/css">
p.top {
background-color: #AAAAAA; color: black;
}
tr.d0 td {
background-color: #CC9999; color: black;
}
tr.d1 td {
background-color: #9999CC; color: black;
}
</style>
"}
dat += "<p class=\"top\">Please configure your pAI personality's options. Remember, what you enter here could determine whether or not the user requesting a personality chooses you!</p>"
dat += "<table>"
dat += "<tr class=\"d0\"><td>Name:</td><td>[candidate.name]</td></tr>"
dat += "<tr class=\"d1\"><td><a href='byond://?src=\ref[src];option=name;new=1;candidate=\ref[candidate]'>\[Edit\]</a></td><td>What you plan to call yourself. Suggestions: Any character name you would choose for a station character OR an AI.</td></tr>"
dat += "<tr class=\"d0\"><td>Description:</td><td>[candidate.description]</td></tr>"
dat += "<tr class=\"d1\"><td><a href='byond://?src=\ref[src];option=desc;new=1;candidate=\ref[candidate]'>\[Edit\]</a></td><td>What sort of pAI you typically play; your mannerisms, your quirks, etc. This can be as sparse or as detailed as you like.</td></tr>"
dat += "<tr class=\"d0\"><td>Preferred Role:</td><td>[candidate.role]</td></tr>"
dat += "<tr class=\"d1\"><td><a href='byond://?src=\ref[src];option=role;new=1;candidate=\ref[candidate]'>\[Edit\]</a></td><td>Do you like to partner with sneaky social ninjas? Like to help security hunt down thugs? Enjoy watching an engineer's back while he saves the station yet again? This doesn't have to be limited to just station jobs. Pretty much any general descriptor for what you'd like to be doing works here.</td></tr>"
dat += "<tr class=\"d0\"><td>OOC Comments:</td><td>[candidate.comments]</td></tr>"
dat += "<tr class=\"d1\"><td><a href='byond://?src=\ref[src];option=ooc;new=1;candidate=\ref[candidate]'>\[Edit\]</a></td><td>Anything you'd like to address specifically to the player reading this in an OOC manner. \"I prefer more serious RP.\", \"I'm still learning the interface!\", etc. Feel free to leave this blank if you want.</td></tr>"
dat += "</table>"
dat += "<br>"
dat += "<h3><a href='byond://?src=\ref[src];option=submit;new=1;candidate=\ref[candidate]'>Submit Personality</a></h3><br>"
dat += "<a href='byond://?src=\ref[src];option=save;new=1;candidate=\ref[candidate]'>Save Personality</a><br>"
dat += "<a href='byond://?src=\ref[src];option=load;new=1;candidate=\ref[candidate]'>Load Personality</a><br>"
M << browse(dat, "window=paiRecruit")
/datum/subsystem/pai/proc/findPAI(obj/item/device/paicard/p, mob/user)
requestRecruits()
var/list/available = list()
for(var/datum/paiCandidate/c in SSpai.candidates)
if(c.ready)
var/found = 0
for(var/mob/dead/observer/o in player_list)
if(o.key == c.key)
found = 1
if(found)
available.Add(c)
var/dat = ""
dat += {"
<style type="text/css">
p.top {
background-color: #AAAAAA; color: black;
}
tr.d0 td {
background-color: #CC9999; color: black;
}
tr.d1 td {
background-color: #9999CC; color: black;
}
tr.d2 td {
background-color: #99CC99; color: black;
}
</style>
"}
dat += "<p class=\"top\">Requesting AI personalities from central database... If there are no entries, or if a suitable entry is not listed, check again later as more personalities may be added.</p>"
dat += "<table>"
for(var/datum/paiCandidate/c in available)
dat += "<tr class=\"d0\"><td>Name:</td><td>[c.name]</td></tr>"
dat += "<tr class=\"d1\"><td>Description:</td><td>[c.description]</td></tr>"
dat += "<tr class=\"d0\"><td>Preferred Role:</td><td>[c.role]</td></tr>"
dat += "<tr class=\"d1\"><td>OOC Comments:</td><td>[c.comments]</td></tr>"
dat += "<tr class=\"d2\"><td><a href='byond://?src=\ref[src];download=1;candidate=\ref[c];device=\ref[p]'>\[Download [c.name]\]</a></td><td></td></tr>"
dat += "</table>"
user << browse(dat, "window=findPai")
/datum/subsystem/pai/proc/requestRecruits()
for(var/mob/dead/observer/O in player_list)
if(jobban_isbanned(O, ROLE_PAI))
continue
if(asked[O.ckey])
if(world.time < asked[O.ckey] + askDelay || asked[O.ckey] == NEVER_FOR_THIS_ROUND)
continue
else
asked.Remove(O.ckey)
if(O.client)
var/hasSubmitted = 0
for(var/datum/paiCandidate/c in SSpai.candidates)
if(c.key == O.key)
hasSubmitted = 1
if(!hasSubmitted && (ROLE_PAI in O.client.prefs.be_special))
question(O.client)
/datum/subsystem/pai/proc/question(client/C)
set waitfor = 0
if(!C)
return
asked[C.ckey] = world.time
var/response = tgalert(C, "Someone is requesting a pAI personality. Would you like to play as a personal AI?", "pAI Request", "Yes", "No", "Never for this round", StealFocus=0, Timeout=askDelay)
if(!C)
return //handle logouts that happen whilst the alert is waiting for a response.
if(response == "Yes")
recruitWindow(C.mob)
else if (response == "Never for this round")
asked[C.ckey] = NEVER_FOR_THIS_ROUND
/datum/paiCandidate
var/name
var/key
var/description
var/role
var/comments
var/ready = 0
+47
View File
@@ -0,0 +1,47 @@
var/datum/subsystem/radio/SSradio
/datum/subsystem/radio
name = "Radio"
init_order = 18
flags = SS_NO_FIRE|SS_NO_INIT
var/list/datum/radio_frequency/frequencies = list()
/datum/subsystem/radio/New()
NEW_SS_GLOBAL(SSradio)
/datum/subsystem/radio/proc/add_object(obj/device, new_frequency as num, filter = null as text|null)
var/f_text = num2text(new_frequency)
var/datum/radio_frequency/frequency = frequencies[f_text]
if(!frequency)
frequency = new
frequency.frequency = new_frequency
frequencies[f_text] = frequency
frequency.add_listener(device, filter)
return frequency
/datum/subsystem/radio/proc/remove_object(obj/device, old_frequency)
var/f_text = num2text(old_frequency)
var/datum/radio_frequency/frequency = frequencies[f_text]
if(frequency)
frequency.remove_listener(device)
if(frequency.devices.len == 0)
qdel(frequency)
frequencies -= f_text
return 1
/datum/subsystem/radio/proc/return_frequency(new_frequency as num)
var/f_text = num2text(new_frequency)
var/datum/radio_frequency/frequency = frequencies[f_text]
if(!frequency)
frequency = new
frequency.frequency = new_frequency
frequencies[f_text] = frequency
return frequency
@@ -0,0 +1,24 @@
var/datum/subsystem/server_maint/SSserver
/datum/subsystem/server_maint
name = "Server Tasks"
wait = 6000
init_order = 19
flags = SS_NO_TICK_CHECK|SS_NO_INIT
/datum/subsystem/server_maint/New()
NEW_SS_GLOBAL(SSserver)
/datum/subsystem/server_maint/fire()
//handle kicking inactive players
if(config.kick_inactive > 0)
for(var/client/C in clients)
if(C.is_afk(INACTIVITY_KICK))
if(!istype(C.mob, /mob/dead))
log_access("AFK: [key_name(C)]")
C << "<span class='danger'>You have been inactive for more than 10 minutes and have been disconnected.</span>"
del(C)
if(config.sql_enabled)
sql_poll_players()
sql_poll_admins()
+246
View File
@@ -0,0 +1,246 @@
var/datum/subsystem/shuttle/SSshuttle
/datum/subsystem/shuttle
name = "Shuttles"
wait = 10
init_order = 3
flags = SS_KEEP_TIMING|SS_NO_TICK_CHECK
var/list/mobile = list()
var/list/stationary = list()
var/list/transit = list()
//emergency shuttle stuff
var/obj/docking_port/mobile/emergency/emergency
var/obj/docking_port/mobile/emergency/backup/backup_shuttle
var/emergencyCallTime = 6000 //time taken for emergency shuttle to reach the station when called (in deciseconds)
var/emergencyDockTime = 1800 //time taken for emergency shuttle to leave again once it has docked (in deciseconds)
var/emergencyEscapeTime = 1200 //time taken for emergency shuttle to reach a safe distance after leaving station (in deciseconds)
var/area/emergencyLastCallLoc
var/emergencyNoEscape
//supply shuttle stuff
var/obj/docking_port/mobile/supply/supply
var/ordernum = 1 //order number given to next order
var/points = 5000 //number of trade-points we have
var/centcom_message = "" //Remarks from Centcom on how well you checked the last order.
var/list/discoveredPlants = list() //Typepaths for unusual plants we've already sent CentComm, associated with their potencies
var/list/supply_packs = list()
var/list/shoppinglist = list()
var/list/requestlist = list()
var/list/orderhistory = list()
var/datum/round_event/shuttle_loan/shuttle_loan
/datum/subsystem/shuttle/New()
NEW_SS_GLOBAL(SSshuttle)
/datum/subsystem/shuttle/Initialize(timeofday)
if(!emergency)
WARNING("No /obj/docking_port/mobile/emergency placed on the map!")
if(!backup_shuttle)
WARNING("No /obj/docking_port/mobile/emergency/backup placed on the map!")
if(!supply)
WARNING("No /obj/docking_port/mobile/supply placed on the map!")
ordernum = rand(1, 9000)
for(var/pack in subtypesof(/datum/supply_pack))
var/datum/supply_pack/P = new pack()
if(!P.contains)
continue
supply_packs[P.type] = P
initial_move()
..()
/datum/subsystem/shuttle/fire()
for(var/thing in mobile)
if(thing)
var/obj/docking_port/mobile/P = thing
P.check()
continue
mobile.Remove(thing)
/datum/subsystem/shuttle/proc/getShuttle(id)
for(var/obj/docking_port/mobile/M in mobile)
if(M.id == id)
return M
WARNING("couldn't find shuttle with id: [id]")
/datum/subsystem/shuttle/proc/getDock(id)
for(var/obj/docking_port/stationary/S in stationary)
if(S.id == id)
return S
WARNING("couldn't find dock with id: [id]")
/datum/subsystem/shuttle/proc/requestEvac(mob/user, call_reason)
if(!emergency)
WARNING("requestEvac(): There is no emergency shuttle, but the \
shuttle was called. Using the backup shuttle instead.")
if(!backup_shuttle)
throw EXCEPTION("requestEvac(): There is no emergency shuttle, \
or backup shuttle! The game will be unresolvable. This is \
possibly a mapping error, more likely a bug with the shuttle \
manipulation system, or badminry. It is possible to manually \
resolve this problem by loading an emergency shuttle template \
manually, and then calling register() on the mobile docking port. \
Good luck.")
return
emergency = backup_shuttle
if(world.time - round_start_time < config.shuttle_refuel_delay)
user << "The emergency shuttle is refueling. Please wait another [abs(round(((world.time - round_start_time) - config.shuttle_refuel_delay)/600))] minutes before trying again."
return
switch(emergency.mode)
if(SHUTTLE_RECALL)
user << "The emergency shuttle may not be called while returning to Centcom."
return
if(SHUTTLE_CALL)
user << "The emergency shuttle is already on its way."
return
if(SHUTTLE_DOCKED)
user << "The emergency shuttle is already here."
return
if(SHUTTLE_ESCAPE)
user << "The emergency shuttle is moving away to a safe distance."
return
if(SHUTTLE_STRANDED)
user << "The emergency shuttle has been disabled by Centcom."
return
call_reason = trim(html_encode(call_reason))
if(length(call_reason) < CALL_SHUTTLE_REASON_LENGTH)
user << "You must provide a reason."
return
var/area/signal_origin = get_area(user)
var/emergency_reason = "\nNature of emergency:\n\n[call_reason]"
if(seclevel2num(get_security_level()) == SEC_LEVEL_RED) // There is a serious threat we gotta move no time to give them five minutes.
emergency.request(null, 0.5, signal_origin, html_decode(emergency_reason), 1)
else
emergency.request(null, 1, signal_origin, html_decode(emergency_reason), 0)
log_game("[key_name(user)] has called the shuttle.")
message_admins("[key_name_admin(user)] has called the shuttle.")
return
// Called when an emergency shuttle mobile docking port is
// destroyed, which will only happen with admin intervention
/datum/subsystem/shuttle/proc/emergencyDeregister()
// When a new emergency shuttle is created, it will override the
// backup shuttle.
src.emergency = src.backup_shuttle
/datum/subsystem/shuttle/proc/cancelEvac(mob/user)
if(canRecall())
emergency.cancel(get_area(user))
log_game("[key_name(user)] has recalled the shuttle.")
message_admins("[key_name_admin(user)] has recalled the shuttle.")
return 1
/datum/subsystem/shuttle/proc/canRecall()
if(emergency.mode != SHUTTLE_CALL)
return
if(ticker.mode.name == "meteor")
return
if(seclevel2num(get_security_level()) == SEC_LEVEL_RED)
if(emergency.timeLeft(1) < emergencyCallTime * 0.25)
return
else
if(emergency.timeLeft(1) < emergencyCallTime * 0.5)
return
return 1
/datum/subsystem/shuttle/proc/autoEvac()
var/callShuttle = 1
for(var/thing in shuttle_caller_list)
if(istype(thing, /mob/living/silicon/ai))
var/mob/living/silicon/ai/AI = thing
if(AI.stat || !AI.client)
continue
else if(istype(thing, /obj/machinery/computer/communications))
var/obj/machinery/computer/communications/C = thing
if(C.stat & BROKEN)
continue
var/turf/T = get_turf(thing)
if(T && T.z == ZLEVEL_STATION)
callShuttle = 0
break
if(callShuttle)
if(EMERGENCY_IDLE_OR_RECALLED)
emergency.request(null, 2.5)
log_game("There is no means of calling the shuttle anymore. Shuttle automatically called.")
message_admins("All the communications consoles were destroyed and all AIs are inactive. Shuttle called.")
//try to move/request to dockHome if possible, otherwise dockAway. Mainly used for admin buttons
/datum/subsystem/shuttle/proc/toggleShuttle(shuttleId, dockHome, dockAway, timed)
var/obj/docking_port/mobile/M = getShuttle(shuttleId)
if(!M)
return 1
var/obj/docking_port/stationary/dockedAt = M.get_docked()
var/destination = dockHome
if(dockedAt && dockedAt.id == dockHome)
destination = dockAway
if(timed)
if(M.request(getDock(destination)))
return 2
else
if(M.dock(getDock(destination)))
return 2
return 0 //dock successful
/datum/subsystem/shuttle/proc/moveShuttle(shuttleId, dockId, timed)
var/obj/docking_port/mobile/M = getShuttle(shuttleId)
var/obj/docking_port/stationary/D = getDock(dockId)
if(!M)
return 1
if(timed)
if(M.request(D))
return 2
else
if(M.dock(D))
return 2
return 0 //dock successful
/datum/subsystem/shuttle/proc/initial_move()
for(var/obj/docking_port/mobile/M in mobile)
if(!M.roundstart_move)
continue
moveShuttle(M.id, "[M.roundstart_move]", 0)
CHECK_TICK
/datum/subsystem/shuttle/Recover()
if (istype(SSshuttle.mobile))
mobile = SSshuttle.mobile
if (istype(SSshuttle.stationary))
stationary = SSshuttle.stationary
if (istype(SSshuttle.transit))
transit = SSshuttle.transit
if (istype(SSshuttle.discoveredPlants))
discoveredPlants = SSshuttle.discoveredPlants
if (istype(SSshuttle.requestlist))
requestlist = SSshuttle.requestlist
if (istype(SSshuttle.orderhistory))
orderhistory = SSshuttle.orderhistory
if (istype(SSshuttle.emergency))
emergency = SSshuttle.emergency
if (istype(SSshuttle.backup_shuttle))
backup_shuttle = SSshuttle.backup_shuttle
if (istype(SSshuttle.supply))
supply = SSshuttle.supply
centcom_message = SSshuttle.centcom_message
ordernum = SSshuttle.ordernum
points = SSshuttle.points
+54
View File
@@ -0,0 +1,54 @@
var/datum/subsystem/sun/SSsun
/datum/subsystem/sun
name = "Sun"
wait = 600
init_order = 2
flags = SS_NO_TICK_CHECK|SS_NO_INIT
var/angle
var/dx
var/dy
var/rate
var/list/solars = list()
/datum/subsystem/sun/New()
NEW_SS_GLOBAL(SSsun)
angle = rand (0,360) // the station position to the sun is randomised at round start
rate = rand(50,200)/100 // 50% - 200% of standard rotation
if(prob(50)) // same chance to rotate clockwise than counter-clockwise
rate = -rate
/datum/subsystem/sun/stat_entry(msg)
..("P:[solars.len]")
/datum/subsystem/sun/fire()
angle = (360 + angle + rate * 6) % 360 // increase/decrease the angle to the sun, adjusted by the rate
// now calculate and cache the (dx,dy) increments for line drawing
var/s = sin(angle)
var/c = cos(angle)
// Either "abs(s) < abs(c)" or "abs(s) >= abs(c)"
// In both cases, the greater is greater than 0, so, no "if 0" check is needed for the divisions
if(abs(s) < abs(c))
dx = s / abs(c)
dy = c / abs(c)
else
dx = s / abs(s)
dy = c / abs(s)
//now tell the solar control computers to update their status and linked devices
for(var/obj/machinery/power/solar_control/SC in solars)
if(!SC.powernet)
solars.Remove(SC)
continue
SC.update()
+39
View File
@@ -0,0 +1,39 @@
var/datum/subsystem/tgui/SStgui
/datum/subsystem/tgui
name = "tgui"
wait = 9
init_order = 16
display_order = 6
flags = SS_NO_INIT|SS_FIRE_IN_LOBBY
priority = 110
var/list/currentrun = list()
var/list/open_uis = list() // A list of open UIs, grouped by src_object and ui_key.
var/list/processing_uis = list() // A list of processing UIs, ungrouped.
var/basehtml // The HTML base used for all UIs.
/datum/subsystem/tgui/New()
basehtml = file2text('tgui/tgui.html') // Read the HTML from disk.
NEW_SS_GLOBAL(SStgui)
/datum/subsystem/tgui/stat_entry()
..("P:[processing_uis.len]")
/datum/subsystem/tgui/fire(resumed = 0)
if (!resumed)
src.currentrun = processing_uis.Copy()
//cache for sanic speed (lists are references anyways)
var/list/currentrun = src.currentrun
while(currentrun.len)
var/datum/tgui/ui = currentrun[currentrun.len]
currentrun.len--
if(ui && ui.user && ui.src_object)
ui.process()
else
processing_uis.Remove(ui)
if (MC_TICK_CHECK)
return
+547
View File
@@ -0,0 +1,547 @@
var/round_start_time = 0
var/datum/subsystem/ticker/ticker
/datum/subsystem/ticker
name = "Ticker"
init_order = 0
priority = 200
flags = SS_FIRE_IN_LOBBY|SS_KEEP_TIMING
var/current_state = GAME_STATE_STARTUP //state of current round (used by process()) Use the defines GAME_STATE_* !
var/force_ending = 0 //Round was ended by admin intervention
var/hide_mode = 0
var/datum/game_mode/mode = null
var/event_time = null
var/event = 0
var/login_music //music played in pregame lobby
var/round_end_sound //music/jingle played when the world reboots
var/list/datum/mind/minds = list() //The characters in the game. Used for objective tracking.
//These bible variables should be a preference
var/Bible_icon_state //icon_state the chaplain has chosen for his bible
var/Bible_item_state //item_state the chaplain has chosen for his bible
var/Bible_name //name of the bible
var/Bible_deity_name //name of chaplin's deity
var/list/syndicate_coalition = list() //list of traitor-compatible factions
var/list/factions = list() //list of all factions
var/list/availablefactions = list() //list of factions with openings
var/delay_end = 0 //if set true, the round will not restart on it's own
var/triai = 0 //Global holder for Triumvirate
var/tipped = 0 //Did we broadcast the tip of the day yet?
var/selected_tip // What will be the tip of the day?
var/timeLeft = 1200 //pregame timer
var/totalPlayers = 0 //used for pregame stats on statpanel
var/totalPlayersReady = 0 //used for pregame stats on statpanel
var/queue_delay = 0
var/list/queued_players = list() //used for join queues when the server exceeds the hard population cap
var/obj/screen/cinematic = null //used for station explosion cinematic
var/maprotatechecked = 0
/datum/subsystem/ticker/New()
NEW_SS_GLOBAL(ticker)
login_music = pickweight(list('sound/ambience/title2.ogg' = 31, 'sound/ambience/title1.ogg' = 31, 'sound/ambience/title3.ogg' =31, 'sound/ambience/clown.ogg' = 7)) // choose title music!
if(SSevent.holidays && SSevent.holidays[APRIL_FOOLS])
login_music = 'sound/ambience/clown.ogg'
/datum/subsystem/ticker/Initialize(timeofday)
if(!syndicate_code_phrase)
syndicate_code_phrase = generate_code_phrase()
if(!syndicate_code_response)
syndicate_code_response = generate_code_phrase()
setupFactions()
..()
/datum/subsystem/ticker/fire()
switch(current_state)
if(GAME_STATE_STARTUP)
timeLeft = config.lobby_countdown * 10
world << "<b><font color='blue'>Welcome to the pre-game lobby!</font></b>"
world << "Please, setup your character and select ready. Game will start in [config.lobby_countdown] seconds"
current_state = GAME_STATE_PREGAME
if(GAME_STATE_PREGAME)
//lobby stats for statpanels
totalPlayers = 0
totalPlayersReady = 0
for(var/mob/new_player/player in player_list)
++totalPlayers
if(player.ready)
++totalPlayersReady
//countdown
if(timeLeft < 0)
return
timeLeft -= wait
if(timeLeft <= 300 && !tipped)
send_tip_of_the_round()
tipped = TRUE
if(timeLeft <= 0)
current_state = GAME_STATE_SETTING_UP
if(GAME_STATE_SETTING_UP)
if(!setup())
//setup failed
current_state = GAME_STATE_STARTUP
if(GAME_STATE_PLAYING)
mode.process(wait * 0.1)
check_queue()
check_maprotate()
if(!mode.explosion_in_progress && mode.check_finished() || force_ending)
current_state = GAME_STATE_FINISHED
toggle_ooc(1) // Turn it on
declare_completion(force_ending)
spawn(50)
if(mode.station_was_nuked)
world.Reboot("Station destroyed by Nuclear Device.", "end_proper", "nuke")
else
world.Reboot("Round ended.", "end_proper", "proper completion")
/datum/subsystem/ticker/proc/setup()
//Create and announce mode
var/list/datum/game_mode/runnable_modes
if(master_mode == "random" || master_mode == "secret")
runnable_modes = config.get_runnable_modes()
if(master_mode == "secret")
hide_mode = 1
if(secret_force_mode != "secret")
var/datum/game_mode/smode = config.pick_mode(secret_force_mode)
if(!smode.can_start())
message_admins("\blue Unable to force secret [secret_force_mode]. [smode.required_players] players and [smode.required_enemies] eligible antagonists needed.")
else
mode = smode
if(!mode)
if(!runnable_modes.len)
world << "<B>Unable to choose playable game mode.</B> Reverting to pre-game lobby."
return 0
mode = pickweight(runnable_modes)
else
mode = config.pick_mode(master_mode)
if(!mode.can_start())
world << "<B>Unable to start [mode.name].</B> Not enough players, [mode.required_players] players and [mode.required_enemies] eligible antagonists needed. Reverting to pre-game lobby."
qdel(mode)
mode = null
SSjob.ResetOccupations()
return 0
//Configure mode and assign player to special mode stuff
var/can_continue = 0
can_continue = src.mode.pre_setup() //Choose antagonists
SSjob.DivideOccupations() //Distribute jobs
if(!Debug2)
if(!can_continue)
qdel(mode)
mode = null
world << "<B>Error setting up [master_mode].</B> Reverting to pre-game lobby."
SSjob.ResetOccupations()
return 0
else
world << "<span class='notice'>DEBUG: Bypassing prestart checks..."
if(hide_mode)
var/list/modes = new
for (var/datum/game_mode/M in runnable_modes)
modes += M.name
modes = sortList(modes)
world << "<B>The current game mode is - Secret!</B>"
world << "<B>Possibilities:</B> [english_list(modes)]"
else
mode.announce()
current_state = GAME_STATE_PLAYING
if(!config.ooc_during_round)
toggle_ooc(0) // Turn it off
round_start_time = world.time
start_landmarks_list = shuffle(start_landmarks_list) //Shuffle the order of spawn points so they dont always predictably spawn bottom-up and right-to-left
create_characters() //Create player characters and transfer them
collect_minds()
equip_characters()
data_core.manifest()
Master.RoundStart()
world << "<FONT color='blue'><B>Welcome to [station_name()], enjoy your stay!</B></FONT>"
world << sound('sound/AI/welcome.ogg')
if(SSevent.holidays)
world << "<font color='blue'>and...</font>"
for(var/holidayname in SSevent.holidays)
var/datum/holiday/holiday = SSevent.holidays[holidayname]
world << "<h4>[holiday.greet()]</h4>"
spawn(0)//Forking here so we dont have to wait for this to finish
mode.post_setup()
//Cleanup some stuff
for(var/obj/effect/landmark/start/S in landmarks_list)
//Deleting Startpoints but we need the ai point to AI-ize people later
if(S.name != "AI")
qdel(S)
var/list/adm = get_admin_counts()
if(!adm["present"])
send2irc("Server", "Round just started with no active admins online!")
return 1
//Plus it provides an easy way to make cinematics for other events. Just use this as a template
/datum/subsystem/ticker/proc/station_explosion_cinematic(station_missed=0, override = null)
if( cinematic )
return //already a cinematic in progress!
for (var/datum/html_interface/hi in html_interfaces)
hi.closeAll()
//initialise our cinematic screen object
cinematic = new /obj/screen{icon='icons/effects/station_explosion.dmi';icon_state="station_intact";layer=21;mouse_opacity=0;screen_loc="1,0";}(src)
var/obj/structure/bed/temp_buckle = new(src)
if(station_missed)
for(var/mob/M in mob_list)
M.buckled = temp_buckle //buckles the mob so it can't do anything
if(M.client)
M.client.screen += cinematic //show every client the cinematic
else //nuke kills everyone on z-level 1 to prevent "hurr-durr I survived"
for(var/mob/M in mob_list)
M.buckled = temp_buckle
if(M.client)
M.client.screen += cinematic
if(M.stat != DEAD)
var/turf/T = get_turf(M)
if(T && T.z==1)
M.death(0) //no mercy
//Now animate the cinematic
switch(station_missed)
if(1) //nuke was nearby but (mostly) missed
if( mode && !override )
override = mode.name
switch( override )
if("nuclear emergency") //Nuke wasn't on station when it blew up
flick("intro_nuke",cinematic)
sleep(35)
world << sound('sound/effects/explosionfar.ogg')
flick("station_intact_fade_red",cinematic)
cinematic.icon_state = "summary_nukefail"
if("gang war") //Gang Domination (just show the override screen)
cinematic.icon_state = "intro_malf_still"
flick("intro_malf",cinematic)
sleep(70)
if("fake") //The round isn't over, we're just freaking people out for fun
flick("intro_nuke",cinematic)
sleep(35)
world << sound('sound/items/bikehorn.ogg')
flick("summary_selfdes",cinematic)
else
flick("intro_nuke",cinematic)
sleep(35)
world << sound('sound/effects/explosionfar.ogg')
//flick("end",cinematic)
if(2) //nuke was nowhere nearby //TODO: a really distant explosion animation
sleep(50)
world << sound('sound/effects/explosionfar.ogg')
else //station was destroyed
if( mode && !override )
override = mode.name
switch( override )
if("nuclear emergency") //Nuke Ops successfully bombed the station
flick("intro_nuke",cinematic)
sleep(35)
flick("station_explode_fade_red",cinematic)
world << sound('sound/effects/explosionfar.ogg')
cinematic.icon_state = "summary_nukewin"
if("AI malfunction") //Malf (screen,explosion,summary)
flick("intro_malf",cinematic)
sleep(76)
flick("station_explode_fade_red",cinematic)
world << sound('sound/effects/explosionfar.ogg')
cinematic.icon_state = "summary_malf"
if("blob") //Station nuked (nuke,explosion,summary)
flick("intro_nuke",cinematic)
sleep(35)
flick("station_explode_fade_red",cinematic)
world << sound('sound/effects/explosionfar.ogg')
cinematic.icon_state = "summary_selfdes"
if("no_core") //Nuke failed to detonate as it had no core
flick("intro_nuke",cinematic)
sleep(35)
flick("station_intact",cinematic)
world << sound('sound/ambience/signal.ogg')
sleep(100)
if(cinematic)
qdel(cinematic)
cinematic = null
if(temp_buckle)
qdel(temp_buckle)
return //Faster exit, since nothing happened
else //Station nuked (nuke,explosion,summary)
flick("intro_nuke",cinematic)
sleep(35)
flick("station_explode_fade_red", cinematic)
world << sound('sound/effects/explosionfar.ogg')
cinematic.icon_state = "summary_selfdes"
//If its actually the end of the round, wait for it to end.
//Otherwise if its a verb it will continue on afterwards.
spawn(300)
if(cinematic)
qdel(cinematic) //end the cinematic
if(temp_buckle)
qdel(temp_buckle) //release everybody
return
/datum/subsystem/ticker/proc/create_characters()
for(var/mob/new_player/player in player_list)
if(player.ready && player.mind)
joined_player_list += player.ckey
if(player.mind.assigned_role=="AI")
player.close_spawn_windows()
player.AIize()
else
player.create_character()
qdel(player)
else
player.new_player_panel()
/datum/subsystem/ticker/proc/collect_minds()
for(var/mob/living/player in player_list)
if(player.mind)
ticker.minds += player.mind
/datum/subsystem/ticker/proc/equip_characters()
var/captainless=1
for(var/mob/living/carbon/human/player in player_list)
if(player && player.mind && player.mind.assigned_role)
if(player.mind.assigned_role == "Captain")
captainless=0
if(player.mind.assigned_role != player.mind.special_role)
SSjob.EquipRank(player, player.mind.assigned_role, 0)
if(captainless)
for(var/mob/M in player_list)
if(!istype(M,/mob/new_player))
M << "Captainship not forced on anyone."
/datum/subsystem/ticker/proc/declare_completion()
var/station_evacuated = EMERGENCY_ESCAPED_OR_ENDGAMED
var/num_survivors = 0
var/num_escapees = 0
world << "<BR><BR><BR><FONT size=3><B>The round has ended.</B></FONT>"
//Player status report
for(var/mob/Player in mob_list)
if(Player.mind && !isnewplayer(Player))
if(Player.stat != DEAD && !isbrain(Player))
num_survivors++
if(station_evacuated) //If the shuttle has already left the station
if(!Player.onCentcom() && !Player.onSyndieBase())
Player << "<font color='blue'><b>You managed to survive, but were marooned on [station_name()]...</b></FONT>"
else
num_escapees++
Player << "<font color='green'><b>You managed to survive the events on [station_name()] as [Player.real_name].</b></FONT>"
else
Player << "<font color='green'><b>You managed to survive the events on [station_name()] as [Player.real_name].</b></FONT>"
else
Player << "<font color='red'><b>You did not survive the events on [station_name()]...</b></FONT>"
//Round statistics report
var/datum/station_state/end_state = new /datum/station_state()
end_state.count()
var/station_integrity = min(round( 100 * start_state.score(end_state), 0.1), 100)
world << "<BR>[TAB]Shift Duration: <B>[round(world.time / 36000)]:[add_zero("[world.time / 600 % 60]", 2)]:[world.time / 100 % 6][world.time / 100 % 10]</B>"
world << "<BR>[TAB]Station Integrity: <B>[mode.station_was_nuked ? "<font color='red'>Destroyed</font>" : "[station_integrity]%"]</B>"
if(joined_player_list.len)
world << "<BR>[TAB]Total Population: <B>[joined_player_list.len]</B>"
if(station_evacuated)
world << "<BR>[TAB]Evacuation Rate: <B>[num_escapees] ([round((num_escapees/joined_player_list.len)*100, 0.1)]%)</B>"
world << "<BR>[TAB]Survival Rate: <B>[num_survivors] ([round((num_survivors/joined_player_list.len)*100, 0.1)]%)</B>"
world << "<BR>"
//Silicon laws report
for (var/mob/living/silicon/ai/aiPlayer in mob_list)
if (aiPlayer.stat != 2 && aiPlayer.mind)
world << "<b>[aiPlayer.name] (Played by: [aiPlayer.mind.key])'s laws at the end of the round were:</b>"
aiPlayer.show_laws(1)
else if (aiPlayer.mind) //if the dead ai has a mind, use its key instead
world << "<b>[aiPlayer.name] (Played by: [aiPlayer.mind.key])'s laws when it was deactivated were:</b>"
aiPlayer.show_laws(1)
world << "<b>Total law changes: [aiPlayer.law_change_counter]</b>"
if (aiPlayer.connected_robots.len)
var/robolist = "<b>[aiPlayer.real_name]'s minions were:</b> "
for(var/mob/living/silicon/robot/robo in aiPlayer.connected_robots)
if(robo.mind)
robolist += "[robo.name][robo.stat?" (Deactivated) (Played by: [robo.mind.key]), ":" (Played by: [robo.mind.key]), "]"
world << "[robolist]"
for (var/mob/living/silicon/robot/robo in mob_list)
if (!robo.connected_ai && robo.mind)
if (robo.stat != 2)
world << "<b>[robo.name] (Played by: [robo.mind.key]) survived as an AI-less borg! Its laws were:</b>"
else
world << "<b>[robo.name] (Played by: [robo.mind.key]) was unable to survive the rigors of being a cyborg without an AI. Its laws were:</b>"
if(robo) //How the hell do we lose robo between here and the world messages directly above this?
robo.laws.show_laws(world)
mode.declare_completion()//To declare normal completion.
//calls auto_declare_completion_* for all modes
for(var/handler in typesof(/datum/game_mode/proc))
if (findtext("[handler]","auto_declare_completion_"))
call(mode, handler)(force_ending)
//Print a list of antagonists to the server log
var/list/total_antagonists = list()
//Look into all mobs in world, dead or alive
for(var/datum/mind/Mind in minds)
var/temprole = Mind.special_role
if(temprole) //if they are an antagonist of some sort.
if(temprole in total_antagonists) //If the role exists already, add the name to it
total_antagonists[temprole] += ", [Mind.name]([Mind.key])"
else
total_antagonists.Add(temprole) //If the role doesnt exist in the list, create it and add the mob
total_antagonists[temprole] += ": [Mind.name]([Mind.key])"
//Now print them all into the log!
log_game("Antagonists at round end were...")
for(var/i in total_antagonists)
log_game("[i]s[total_antagonists[i]].")
//Adds the del() log to world.log in a format condensable by the runtime condenser found in tools
if(SSgarbage.didntgc.len)
var/dellog = ""
for(var/path in SSgarbage.didntgc)
dellog += "Path : [path] \n"
dellog += "Failures : [SSgarbage.didntgc[path]] \n"
world.log << dellog
return 1
/datum/subsystem/ticker/proc/send_tip_of_the_round()
var/m
if(selected_tip)
m = selected_tip
else
var/list/randomtips = file2list("config/tips.txt")
var/list/memetips = file2list("config/sillytips.txt")
if(randomtips.len && prob(95))
m = pick(randomtips)
else if(memetips.len)
m = pick(memetips)
if(m)
world << "<font color='purple'><b>Tip of the round: \
</b>[html_encode(m)]</font>"
/datum/subsystem/ticker/proc/check_queue()
if(!queued_players.len || !config.hard_popcap)
return
queue_delay++
var/mob/new_player/next_in_line = queued_players[1]
switch(queue_delay)
if(5) //every 5 ticks check if there is a slot available
if(living_player_count() < config.hard_popcap)
if(next_in_line && next_in_line.client)
next_in_line << "<span class='userdanger'>A slot has opened! You have approximately 20 seconds to join. <a href='?src=\ref[next_in_line];late_join=override'>\>\>Join Game\<\<</a></span>"
next_in_line << sound('sound/misc/notice1.ogg')
next_in_line.LateChoices()
return
queued_players -= next_in_line //Client disconnected, remove he
queue_delay = 0 //No vacancy: restart timer
if(25 to INFINITY) //No response from the next in line when a vacancy exists, remove he
next_in_line << "<span class='danger'>No response recieved. You have been removed from the line.</span>"
queued_players -= next_in_line
queue_delay = 0
/datum/subsystem/ticker/proc/check_maprotate()
if (!config.maprotation || !SERVERTOOLS)
return
if (SSshuttle.emergency.mode != SHUTTLE_ESCAPE || SSshuttle.canRecall())
return
if (maprotatechecked)
return
maprotatechecked = 1
//map rotate chance defaults to 75% of the length of the round (in minutes)
if (!prob((world.time/600)*config.maprotatechancedelta))
return
spawn(0) //compiling a map can lock up the mc for 30 to 60 seconds if we don't spawn
maprotate()
/world/proc/has_round_started()
if (ticker && ticker.current_state >= GAME_STATE_PLAYING)
return TRUE
return FALSE
/datum/subsystem/ticker/Recover()
current_state = ticker.current_state
force_ending = ticker.force_ending
hide_mode = ticker.hide_mode
mode = ticker.mode
event_time = ticker.event_time
event = ticker.event
login_music = ticker.login_music
round_end_sound = ticker.round_end_sound
minds = ticker.minds
Bible_icon_state = ticker.Bible_icon_state
Bible_item_state = ticker.Bible_item_state
Bible_name = ticker.Bible_name
Bible_deity_name = ticker.Bible_deity_name
syndicate_coalition = ticker.syndicate_coalition
factions = ticker.factions
availablefactions = ticker.availablefactions
delay_end = ticker.delay_end
triai = ticker.triai
tipped = ticker.tipped
selected_tip = ticker.selected_tip
timeLeft = ticker.timeLeft
totalPlayers = ticker.totalPlayers
totalPlayersReady = ticker.totalPlayersReady
queue_delay = ticker.queue_delay
queued_players = ticker.queued_players
cinematic = ticker.cinematic
maprotatechecked = ticker.maprotatechecked
+102
View File
@@ -0,0 +1,102 @@
var/datum/subsystem/timer/SStimer
/datum/subsystem/timer
name = "Timer"
wait = 2 //SS_TICKER subsystem, so wait is in ticks
init_order = 1
display_order = 3
can_fire = 0 //start disabled
flags = SS_FIRE_IN_LOBBY|SS_TICKER|SS_POST_FIRE_TIMING|SS_NO_INIT
var/list/datum/timedevent/processing
var/list/hashes
/datum/subsystem/timer/New()
processing = list()
hashes = list()
NEW_SS_GLOBAL(SStimer)
/datum/subsystem/timer/stat_entry(msg)
..("P:[processing.len]")
/datum/subsystem/timer/fire()
if(!processing.len)
can_fire = 0 //nothing to do, lets stop firing.
return
for(var/datum/timedevent/event in processing)
if(!event.thingToCall || qdeleted(event.thingToCall))
qdel(event)
if(event.timeToRun <= world.time)
runevent(event)
qdel(event)
if (MC_TICK_CHECK)
return
/datum/subsystem/timer/proc/runevent(datum/timedevent/event)
set waitfor = 0
if(event.thingToCall == GLOBAL_PROC && istext(event.procToCall))
call("/proc/[event.procToCall]")(arglist(event.argList))
else
call(event.thingToCall, event.procToCall)(arglist(event.argList))
/datum/subsystem/timer/Recover()
processing |= SStimer.processing
hashes |= SStimer.hashes
/datum/timedevent
var/thingToCall
var/procToCall
var/timeToRun
var/argList
var/id
var/hash
var/static/nextid = 1
/datum/timedevent/New()
id = nextid++
/datum/timedevent/Destroy()
SStimer.processing -= src
SStimer.hashes -= hash
return QDEL_HINT_IWILLGC
/proc/addtimer(thingToCall, procToCall, wait, unique = FALSE, ...)
if (!thingToCall || !procToCall)
return
if (!SStimer.can_fire)
SStimer.can_fire = 1
var/datum/timedevent/event = new()
event.thingToCall = thingToCall
event.procToCall = procToCall
event.timeToRun = world.time + wait
var/hashlist = args.Copy()
hashlist[1] = "[thingToCall](\ref[thingToCall])"
event.hash = jointext(args, null)
if(args.len > 4)
event.argList = args.Copy(5)
// Check for dupes if unique = 1.
if(unique)
var/datum/timedevent/hash_event = SStimer.hashes[event.hash]
if(hash_event)
return hash_event.id
SStimer.hashes[event.hash] = event
if (wait <= 0)
SStimer.runevent(event)
SStimer.hashes -= event.hash
return
// If we are unique (or we're not checking that), add the timer and return the id.
SStimer.processing += event
return event.id
/proc/deltimer(id)
for(var/datum/timedevent/event in SStimer.processing)
if(event.id == id)
qdel(event)
return 1
return 0
+310
View File
@@ -0,0 +1,310 @@
var/datum/subsystem/vote/SSvote
/datum/subsystem/vote
name = "Vote"
wait = 10
flags = SS_FIRE_IN_LOBBY|SS_KEEP_TIMING|SS_NO_INIT
var/initiator = null
var/started_time = null
var/time_remaining = 0
var/mode = null
var/question = null
var/list/choices = list()
var/list/voted = list()
var/list/voting = list()
var/list/generated_actions = list()
/datum/subsystem/vote/New()
NEW_SS_GLOBAL(SSvote)
/datum/subsystem/vote/fire() //called by master_controller
if(mode)
time_remaining = round((started_time + config.vote_period - world.time)/10)
if(time_remaining < 0)
result()
for(var/client/C in voting)
C << browse(null, "window=vote;can_close=0")
reset()
else
var/datum/browser/client_popup
for(var/client/C in voting)
client_popup = new(C, "vote", "Voting Panel")
client_popup.set_window_options("can_close=0")
client_popup.set_content(interface(C))
client_popup.open(0)
/datum/subsystem/vote/proc/reset()
initiator = null
time_remaining = 0
mode = null
question = null
choices.Cut()
voted.Cut()
voting.Cut()
remove_action_buttons()
/datum/subsystem/vote/proc/get_result()
//get the highest number of votes
var/greatest_votes = 0
var/total_votes = 0
for(var/option in choices)
var/votes = choices[option]
total_votes += votes
if(votes > greatest_votes)
greatest_votes = votes
//default-vote for everyone who didn't vote
if(!config.vote_no_default && choices.len)
var/non_voters = (clients.len - total_votes)
if(non_voters > 0)
if(mode == "restart")
choices["Continue Playing"] += non_voters
if(choices["Continue Playing"] >= greatest_votes)
greatest_votes = choices["Continue Playing"]
else if(mode == "gamemode")
if(master_mode in choices)
choices[master_mode] += non_voters
if(choices[master_mode] >= greatest_votes)
greatest_votes = choices[master_mode]
//get all options with that many votes and return them in a list
. = list()
if(greatest_votes)
for(var/option in choices)
if(choices[option] == greatest_votes)
. += option
return .
/datum/subsystem/vote/proc/announce_result()
var/list/winners = get_result()
var/text
if(winners.len > 0)
if(question)
text += "<b>[question]</b>"
else
text += "<b>[capitalize(mode)] Vote</b>"
for(var/i=1,i<=choices.len,i++)
var/votes = choices[choices[i]]
if(!votes)
votes = 0
text += "\n<b>[choices[i]]:</b> [votes]"
if(mode != "custom")
if(winners.len > 1)
text = "\n<b>Vote Tied Between:</b>"
for(var/option in winners)
text += "\n\t[option]"
. = pick(winners)
text += "\n<b>Vote Result: [.]</b>"
else
text += "\n<b>Did not vote:</b> [clients.len-voted.len]"
else
text += "<b>Vote Result: Inconclusive - No Votes!</b>"
log_vote(text)
remove_action_buttons()
world << "\n<font color='purple'>[text]</font>"
return .
/datum/subsystem/vote/proc/result()
. = announce_result()
var/restart = 0
if(.)
switch(mode)
if("restart")
if(. == "Restart Round")
restart = 1
if("gamemode")
if(master_mode != .)
world.save_mode(.)
if(ticker && ticker.mode)
restart = 1
else
master_mode = .
if(restart)
var/active_admins = 0
for(var/client/C in admins)
if(!C.is_afk() && check_rights_for(C, R_SERVER))
active_admins = 1
break
if(!active_admins)
world.Reboot("Restart vote successful.", "end_error", "restart vote")
else
world << "<span style='boldannounce'>Notice:Restart vote will not restart the server automatically because there are active admins on.</span>"
message_admins("A restart vote has passed, but there are active admins on with +server, so it has been canceled. If you wish, you may restart the server.")
return .
/datum/subsystem/vote/proc/submit_vote(vote)
if(mode)
if(config.vote_no_dead && usr.stat == DEAD && !usr.client.holder)
return 0
if(!(usr.ckey in voted))
if(vote && 1<=vote && vote<=choices.len)
voted += usr.ckey
choices[choices[vote]]++ //check this
return vote
return 0
/datum/subsystem/vote/proc/initiate_vote(vote_type, initiator_key)
if(!mode)
if(started_time)
var/next_allowed_time = (started_time + config.vote_delay)
if(mode)
usr << "<span class='warning'>There is already a vote in progress! please wait for it to finish.</span>"
return 0
var/admin = FALSE
var/ckey = ckey(initiator_key)
if((admin_datums[ckey]) || (ckey in deadmins))
admin = TRUE
if(next_allowed_time > world.time && !admin)
usr << "<span class='warning'>A vote was initiated recently, you must wait roughly [(next_allowed_time-world.time)/10] seconds before a new vote can be started!</span>"
return 0
reset()
switch(vote_type)
if("restart")
choices.Add("Restart Round","Continue Playing")
if("gamemode")
choices.Add(config.votable_modes)
if("custom")
question = stripped_input(usr,"What is the vote for?")
if(!question)
return 0
for(var/i=1,i<=10,i++)
var/option = capitalize(stripped_input(usr,"Please enter an option or hit cancel to finish"))
if(!option || mode || !usr.client)
break
choices.Add(option)
else
return 0
mode = vote_type
initiator = initiator_key
started_time = world.time
var/text = "[capitalize(mode)] vote started by [initiator]."
if(mode == "custom")
text += "\n[question]"
log_vote(text)
world << "\n<font color='purple'><b>[text]</b>\nType <b>vote</b> or click <a href='?src=\ref[src]'>here</a> to place your votes.\nYou have [config.vote_period/10] seconds to vote.</font>"
time_remaining = round(config.vote_period/10)
for(var/c in clients)
var/client/C = c
var/datum/action/vote/V = new
if(question)
V.name = "Vote: [question]"
V.Grant(C.mob)
generated_actions += V
return 1
return 0
/datum/subsystem/vote/proc/interface(client/C)
if(!C)
return
var/admin = 0
var/trialmin = 0
if(C.holder)
admin = 1
if(check_rights_for(C, R_ADMIN))
trialmin = 1
voting |= C
if(mode)
if(question)
. += "<h2>Vote: '[question]'</h2>"
else
. += "<h2>Vote: [capitalize(mode)]</h2>"
. += "Time Left: [time_remaining] s<hr><ul>"
for(var/i=1,i<=choices.len,i++)
var/votes = choices[choices[i]]
if(!votes)
votes = 0
. += "<li><a href='?src=\ref[src];vote=[i]'>[choices[i]]</a> ([votes] votes)</li>"
. += "</ul><hr>"
if(admin)
. += "(<a href='?src=\ref[src];vote=cancel'>Cancel Vote</a>) "
else
. += "<h2>Start a vote:</h2><hr><ul><li>"
//restart
if(trialmin || config.allow_vote_restart)
. += "<a href='?src=\ref[src];vote=restart'>Restart</a>"
else
. += "<font color='grey'>Restart (Disallowed)</font>"
if(trialmin)
. += "\t(<a href='?src=\ref[src];vote=toggle_restart'>[config.allow_vote_restart?"Allowed":"Disallowed"]</a>)"
. += "</li><li>"
//gamemode
if(trialmin || config.allow_vote_mode)
. += "<a href='?src=\ref[src];vote=gamemode'>GameMode</a>"
else
. += "<font color='grey'>GameMode (Disallowed)</font>"
if(trialmin)
. += "\t(<a href='?src=\ref[src];vote=toggle_gamemode'>[config.allow_vote_mode?"Allowed":"Disallowed"]</a>)"
. += "</li>"
//custom
if(trialmin)
. += "<li><a href='?src=\ref[src];vote=custom'>Custom</a></li>"
. += "</ul><hr>"
. += "<a href='?src=\ref[src];vote=close' style='position:absolute;right:50px'>Close</a>"
return .
/datum/subsystem/vote/Topic(href,href_list[],hsrc)
if(!usr || !usr.client)
return //not necessary but meh...just in-case somebody does something stupid
switch(href_list["vote"])
if("close")
voting -= usr.client
usr << browse(null, "window=vote")
return
if("cancel")
if(usr.client.holder)
reset()
if("toggle_restart")
if(usr.client.holder)
config.allow_vote_restart = !config.allow_vote_restart
if("toggle_gamemode")
if(usr.client.holder)
config.allow_vote_mode = !config.allow_vote_mode
if("restart")
if(config.allow_vote_restart || usr.client.holder)
initiate_vote("restart",usr.key)
if("gamemode")
if(config.allow_vote_mode || usr.client.holder)
initiate_vote("gamemode",usr.key)
if("custom")
if(usr.client.holder)
initiate_vote("custom",usr.key)
else
submit_vote(round(text2num(href_list["vote"])))
usr.vote()
/datum/subsystem/vote/proc/remove_action_buttons()
for(var/v in generated_actions)
var/datum/action/vote/V = v
if(!qdeleted(V))
V.Remove(V.owner)
generated_actions = list()
/mob/verb/vote()
set category = "OOC"
set name = "Vote"
var/datum/browser/popup = new(src, "vote", "Voting Panel")
popup.set_window_options("can_close=0")
popup.set_content(SSvote.interface(client))
popup.open(0)
/datum/action/vote
name = "Vote!"
button_icon_state = "vote"
/datum/action/vote/Trigger()
if(owner)
owner.vote()
Remove(owner)
/datum/action/vote/IsAvailable()
return 1