]> de.git.xonotic.org Git - xonotic/xonotic-data.pk3dir.git/blob - qcsrc/server/g_world.qc
Merge branch 'master' into TimePath/itemstime2.0
[xonotic/xonotic-data.pk3dir.git] / qcsrc / server / g_world.qc
1 #include "g_world.qh"
2 #include "_all.qh"
3
4 #include "anticheat.qh"
5 #include "antilag.qh"
6 #include "bot/bot.qh"
7 #include "campaign.qh"
8 #include "cheats.qh"
9 #include "cl_client.qh"
10 #include "command/common.qh"
11 #include "command/getreplies.qh"
12 #include "command/sv_cmd.qh"
13 #include "command/vote.qh"
14 #include "g_hook.qh"
15 #include "ipban.qh"
16 #include "mapvoting.qh"
17 #include "mutators/mutators_include.qh"
18 #include "race.qh"
19 #include "scores.qh"
20 #include "teamplay.qh"
21 #include "waypointsprites.qh"
22 #include "weapons/weaponstats.qh"
23 #include "../common/buffs.qh"
24 #include "../common/constants.qh"
25 #include "../common/deathtypes.qh"
26 #include "../common/effects.qh"
27 #include "../common/mapinfo.qh"
28 #include "../common/monsters/all.qh"
29 #include "../common/monsters/sv_monsters.qh"
30 #include "../common/vehicles/all.qh"
31 #include "../common/notifications.qh"
32 #include "../common/playerstats.qh"
33 #include "../common/stats.qh"
34 #include "../common/teams.qh"
35 #include "../common/util.qh"
36 #include "../common/items/all.qh"
37 #include "../common/weapons/all.qh"
38
39 const float LATENCY_THINKRATE = 10;
40 .float latency_sum;
41 .float latency_cnt;
42 .float latency_time;
43 entity pingplreport;
44 void PingPLReport_Think()
45 {
46         float delta;
47         entity e;
48
49         delta = 3 / maxclients;
50         if(delta < sys_frametime)
51                 delta = 0;
52         self.nextthink = time + delta;
53
54         e = edict_num(self.cnt + 1);
55         if(IS_REAL_CLIENT(e))
56         {
57                 WriteByte(MSG_BROADCAST, SVC_TEMPENTITY);
58                 WriteByte(MSG_BROADCAST, TE_CSQC_PINGPLREPORT);
59                 WriteByte(MSG_BROADCAST, self.cnt);
60                 WriteShort(MSG_BROADCAST, max(1, e.ping));
61                 WriteByte(MSG_BROADCAST, ceil(e.ping_packetloss * 255));
62                 WriteByte(MSG_BROADCAST, ceil(e.ping_movementloss * 255));
63
64                 // record latency times for clients throughout the match so we can report it to playerstats
65                 if(time > (e.latency_time + LATENCY_THINKRATE))
66                 {
67                         e.latency_sum += e.ping;
68                         e.latency_cnt += 1;
69                         e.latency_time = time;
70                         //print("sum: ", ftos(e.latency_sum), ", cnt: ", ftos(e.latency_cnt), ", avg: ", ftos(e.latency_sum / e.latency_cnt), ".\n");
71                 }
72         }
73         else
74         {
75                 WriteByte(MSG_BROADCAST, SVC_TEMPENTITY);
76                 WriteByte(MSG_BROADCAST, TE_CSQC_PINGPLREPORT);
77                 WriteByte(MSG_BROADCAST, self.cnt);
78                 WriteShort(MSG_BROADCAST, 0);
79                 WriteByte(MSG_BROADCAST, 0);
80                 WriteByte(MSG_BROADCAST, 0);
81         }
82         self.cnt = (self.cnt + 1) % maxclients;
83 }
84 void PingPLReport_Spawn()
85 {
86         pingplreport = spawn();
87         pingplreport.classname = "pingplreport";
88         pingplreport.think = PingPLReport_Think;
89         pingplreport.nextthink = time;
90 }
91
92 const float SPAWNFLAG_NO_WAYPOINTS_FOR_ITEMS = 1;
93 string redirection_target;
94 float world_initialized;
95
96 string GetGametype();
97 void ShuffleMaplist();
98
99 void SetDefaultAlpha()
100 {
101         if(autocvar_g_running_guns)
102         {
103                 default_player_alpha = -1;
104                 default_weapon_alpha = +1;
105         }
106         else if(g_cloaked)
107         {
108                 default_player_alpha = autocvar_g_balance_cloaked_alpha;
109                 default_weapon_alpha = default_player_alpha;
110         }
111         else
112         {
113                 default_player_alpha = autocvar_g_player_alpha;
114                 if(default_player_alpha == 0)
115                         default_player_alpha = 1;
116                 default_weapon_alpha = default_player_alpha;
117         }
118 }
119
120 void GotoFirstMap()
121 {
122         float n;
123         if(autocvar__sv_init)
124         {
125                 // cvar_set("_sv_init", "0");
126                 // we do NOT set this to 0 any more, so someone "accidentally" changing
127                 // to this "init" map on a dedicated server will cause no permanent
128                 // harm
129                 if(autocvar_g_maplist_shuffle)
130                         ShuffleMaplist();
131                 n = tokenizebyseparator(autocvar_g_maplist, " ");
132                 cvar_set("g_maplist_index", ftos(n - 1)); // jump to map 0 in GotoNextMap
133
134                 MapInfo_Enumerate();
135                 MapInfo_FilterGametype(MapInfo_CurrentGametype(), MapInfo_CurrentFeatures(), MapInfo_RequiredFlags(), MapInfo_ForbiddenFlags(), 0);
136
137                 if(!DoNextMapOverride(1))
138                         GotoNextMap(1);
139
140                 return;
141         }
142
143         if(time < 5)
144         {
145                 self.nextthink = time;
146         }
147         else
148         {
149                 self.nextthink = time + 1;
150                 print("Waiting for _sv_init being set to 1 by initialization scripts...\n");
151         }
152 }
153
154 void cvar_changes_init()
155 {
156         float h;
157         string k, v, d;
158         float n, i, adding, pureadding;
159
160         if(cvar_changes)
161                 strunzone(cvar_changes);
162         cvar_changes = string_null;
163         if(cvar_purechanges)
164                 strunzone(cvar_purechanges);
165         cvar_purechanges = string_null;
166         cvar_purechanges_count = 0;
167
168         h = buf_create();
169         buf_cvarlist(h, "", "_"); // exclude all _ cvars as they are temporary
170         n = buf_getsize(h);
171
172         adding = true;
173         pureadding = true;
174
175         for(i = 0; i < n; ++i)
176         {
177                 k = bufstr_get(h, i);
178
179 #define BADPREFIX(p) if(substring(k, 0, strlen(p)) == p) continue
180 #define BADPRESUFFIX(p,s) if(substring(k, 0, strlen(p)) == p && substring(k, -strlen(s), -1) == s) continue
181 #define BADCVAR(p) if(k == p) continue
182
183                 // general excludes and namespaces for server admin used cvars
184                 BADPREFIX("help_"); // PN's server has this listed as changed, let's not rat him out for THAT
185
186                 // internal
187                 BADPREFIX("csqc_");
188                 BADPREFIX("cvar_check_");
189                 BADCVAR("gamecfg");
190                 BADCVAR("g_configversion");
191                 BADCVAR("g_maplist_index");
192                 BADCVAR("halflifebsp");
193                 BADCVAR("sv_mapformat_is_quake2");
194                 BADCVAR("sv_mapformat_is_quake3");
195                 BADPREFIX("sv_world");
196
197                 // client
198                 BADPREFIX("chase_");
199                 BADPREFIX("cl_");
200                 BADPREFIX("con_");
201                 BADPREFIX("scoreboard_");
202                 BADPREFIX("g_campaign");
203                 BADPREFIX("g_waypointsprite_");
204                 BADPREFIX("gl_");
205                 BADPREFIX("joy");
206                 BADPREFIX("hud_");
207                 BADPREFIX("m_");
208                 BADPREFIX("menu_");
209                 BADPREFIX("net_slist_");
210                 BADPREFIX("r_");
211                 BADPREFIX("sbar_");
212                 BADPREFIX("scr_");
213                 BADPREFIX("snd_");
214                 BADPREFIX("show");
215                 BADPREFIX("sensitivity");
216                 BADPREFIX("userbind");
217                 BADPREFIX("v_");
218                 BADPREFIX("vid_");
219                 BADPREFIX("crosshair");
220                 BADCVAR("mod_q3bsp_lightmapmergepower");
221                 BADCVAR("mod_q3bsp_nolightmaps");
222                 BADCVAR("fov");
223                 BADCVAR("mastervolume");
224                 BADCVAR("volume");
225                 BADCVAR("bgmvolume");
226
227                 // private
228                 BADCVAR("developer");
229                 BADCVAR("log_dest_udp");
230                 BADCVAR("net_address");
231                 BADCVAR("net_address_ipv6");
232                 BADCVAR("port");
233                 BADCVAR("savedgamecfg");
234                 BADCVAR("serverconfig");
235                 BADCVAR("sv_autoscreenshot");
236                 BADCVAR("sv_heartbeatperiod");
237                 BADCVAR("sv_vote_master_password");
238                 BADCVAR("sys_colortranslation");
239                 BADCVAR("sys_specialcharactertranslation");
240                 BADCVAR("timeformat");
241                 BADCVAR("timestamps");
242                 BADPREFIX("developer_");
243                 BADPREFIX("g_ban_");
244                 BADPREFIX("g_banned_list");
245                 BADPREFIX("g_chat_flood_");
246                 BADPREFIX("g_ghost_items");
247                 BADPREFIX("g_playerstats_");
248                 BADPREFIX("g_respawn_ghosts");
249                 BADPREFIX("g_voice_flood_");
250                 BADPREFIX("log_file");
251                 BADPREFIX("rcon_");
252                 BADPREFIX("sv_allowdownloads");
253                 BADPREFIX("sv_autodemo");
254                 BADPREFIX("sv_curl_");
255                 BADPREFIX("sv_eventlog");
256                 BADPREFIX("sv_logscores_");
257                 BADPREFIX("sv_master");
258                 BADPREFIX("sv_weaponstats_");
259                 BADPREFIX("sv_waypointsprite_");
260                 BADCVAR("rescan_pending");
261
262                 // these can contain player IDs, so better hide
263                 BADPREFIX("g_forced_team_");
264
265                 // mapinfo
266                 BADCVAR("fraglimit");
267                 BADCVAR("g_assault");
268                 BADCVAR("g_ca");
269                 BADCVAR("g_ca_teams");
270                 BADCVAR("g_ctf");
271                 BADCVAR("g_cts");
272                 BADCVAR("g_dm");
273                 BADCVAR("g_domination");
274                 BADCVAR("g_domination_default_teams");
275                 BADCVAR("g_freezetag");
276                 BADCVAR("g_freezetag_teams");
277                 BADCVAR("g_invasion_teams");
278                 BADCVAR("g_keepaway");
279                 BADCVAR("g_keyhunt");
280                 BADCVAR("g_keyhunt_teams");
281                 BADCVAR("g_lms");
282                 BADCVAR("g_nexball");
283                 BADCVAR("g_onslaught");
284                 BADCVAR("g_race");
285                 BADCVAR("g_race_qualifying_timelimit");
286                 BADCVAR("g_tdm");
287                 BADCVAR("g_tdm_teams");
288                 BADCVAR("leadlimit");
289                 BADCVAR("nextmap");
290                 BADCVAR("teamplay");
291                 BADCVAR("timelimit");
292
293                 // long
294                 BADCVAR("hostname");
295                 BADCVAR("g_maplist");
296                 BADCVAR("g_maplist_mostrecent");
297                 BADCVAR("sv_motd");
298
299                 v = cvar_string(k);
300                 d = cvar_defstring(k);
301                 if(v == d)
302                         continue;
303
304                 if(adding)
305                 {
306                         cvar_changes = strcat(cvar_changes, k, " \"", v, "\" // \"", d, "\"\n");
307                         if(strlen(cvar_changes) > 16384)
308                         {
309                                 cvar_changes = "// too many settings have been changed to show them here\n";
310                                 adding = 0;
311                         }
312                 }
313
314                 // now check if the changes are actually gameplay relevant
315
316                 // does nothing visible
317                 BADCVAR("captureleadlimit_override");
318                 BADCVAR("g_balance_kill_delay");
319                 BADCVAR("g_ca_point_limit");
320                 BADCVAR("g_ca_point_leadlimit");
321                 BADCVAR("g_ctf_captimerecord_always");
322                 BADCVAR("g_ctf_flag_glowtrails");
323                 BADCVAR("g_ctf_flag_pickup_verbosename");
324                 BADCVAR("g_domination_point_leadlimit");
325                 BADCVAR("g_forced_respawn");
326                 BADCVAR("g_freezetag_point_limit");
327                 BADCVAR("g_freezetag_point_leadlimit");
328                 BADCVAR("g_keyhunt_point_leadlimit");
329                 BADPREFIX("g_mod_");
330                 BADCVAR("g_invasion_point_limit");
331                 BADCVAR("g_nexball_goalleadlimit");
332                 BADCVAR("g_tdm_point_limit");
333                 BADCVAR("g_tdm_point_leadlimit");
334                 BADCVAR("leadlimit_and_fraglimit");
335                 BADCVAR("leadlimit_override");
336                 BADCVAR("pausable");
337                 BADCVAR("sv_allow_fullbright");
338                 BADCVAR("sv_checkforpacketsduringsleep");
339                 BADCVAR("sv_timeout");
340                 BADPREFIX("sv_timeout_");
341                 BADPREFIX("crypto_");
342                 BADPREFIX("g_chat_");
343                 BADPREFIX("g_ctf_captimerecord_");
344                 BADPREFIX("g_maplist_votable_");
345                 BADPREFIX("net_");
346                 BADPREFIX("prvm_");
347                 BADPREFIX("skill_");
348                 BADPREFIX("sv_cullentities_");
349                 BADPREFIX("sv_maxidle_");
350                 BADPREFIX("sv_vote_");
351                 BADPREFIX("timelimit_");
352                 BADCVAR("gameversion");
353                 BADPREFIX("gameversion_");
354                 BADCVAR("sv_namechangetimer");
355
356                 // allowed changes to server admins (please sync this to server.cfg)
357                 // vi commands:
358                 //   :/"impure"/,$d
359                 //   :g!,^\/\/[^ /],d
360                 //   :%s,//\([^ ]*\).*,BADCVAR("\1");,
361                 //   :%!sort
362                 // yes, this does contain some redundant stuff, don't really care
363                 BADCVAR("bot_config_file");
364                 BADCVAR("bot_number");
365                 BADCVAR("bot_prefix");
366                 BADCVAR("bot_suffix");
367                 BADCVAR("capturelimit_override");
368                 BADCVAR("fraglimit_override");
369                 BADCVAR("gametype");
370                 BADCVAR("g_antilag");
371                 BADCVAR("g_balance_teams");
372                 BADCVAR("g_balance_teams_prevent_imbalance");
373                 BADCVAR("g_balance_teams_scorefactor");
374                 BADCVAR("g_ban_sync_trusted_servers");
375                 BADCVAR("g_ban_sync_uri");
376                 BADCVAR("g_ca_teams_override");
377                 BADCVAR("g_ctf_ignore_frags");
378                 BADCVAR("g_domination_point_limit");
379                 BADCVAR("g_domination_teams_override");
380                 BADCVAR("g_freezetag_teams_override");
381                 BADCVAR("g_friendlyfire");
382                 BADCVAR("g_fullbrightitems");
383                 BADCVAR("g_fullbrightplayers");
384                 BADCVAR("g_keyhunt_point_limit");
385                 BADCVAR("g_keyhunt_teams_override");
386                 BADCVAR("g_lms_lives_override");
387                 BADCVAR("g_maplist");
388                 BADCVAR("g_maplist_check_waypoints");
389                 BADCVAR("g_maplist_mostrecent_count");
390                 BADCVAR("g_maplist_shuffle");
391                 BADCVAR("g_maplist_votable");
392                 BADCVAR("g_maplist_votable_abstain");
393                 BADCVAR("g_maplist_votable_nodetail");
394                 BADCVAR("g_maplist_votable_suggestions");
395                 BADCVAR("g_maxplayers");
396                 BADCVAR("g_mirrordamage");
397                 BADCVAR("g_nexball_goallimit");
398                 BADCVAR("g_powerups");
399                 BADCVAR("g_start_delay");
400                 BADCVAR("g_tdm_teams_override");
401                 BADCVAR("g_warmup");
402                 BADCVAR("g_weapon_stay"); BADPRESUFFIX("g_", "_weapon_stay");
403                 BADCVAR("hostname");
404                 BADCVAR("log_file");
405                 BADCVAR("maxplayers");
406                 BADCVAR("minplayers");
407                 BADCVAR("net_address");
408                 BADCVAR("port");
409                 BADCVAR("rcon_password");
410                 BADCVAR("rcon_restricted_commands");
411                 BADCVAR("rcon_restricted_password");
412                 BADCVAR("skill");
413                 BADCVAR("sv_adminnick");
414                 BADCVAR("sv_autoscreenshot");
415                 BADCVAR("sv_autotaunt");
416                 BADCVAR("sv_curl_defaulturl");
417                 BADCVAR("sv_defaultcharacter");
418                 BADCVAR("sv_defaultplayercolors");
419                 BADCVAR("sv_defaultplayermodel");
420                 BADCVAR("sv_defaultplayerskin");
421                 BADCVAR("sv_maxidle");
422                 BADCVAR("sv_maxrate");
423                 BADCVAR("sv_motd");
424                 BADCVAR("sv_public");
425                 BADCVAR("sv_ready_restart");
426                 BADCVAR("sv_status_privacy");
427                 BADCVAR("sv_taunt");
428                 BADCVAR("sv_vote_call");
429                 BADCVAR("sv_vote_commands");
430                 BADCVAR("sv_vote_majority_factor");
431                 BADCVAR("sv_vote_master");
432                 BADCVAR("sv_vote_master_commands");
433                 BADCVAR("sv_vote_master_password");
434                 BADCVAR("sv_vote_simple_majority_factor");
435                 BADCVAR("teamplay_mode");
436                 BADCVAR("timelimit_override");
437                 BADCVAR("g_spawnshieldtime");
438                 BADPREFIX("g_warmup_");
439                 BADPREFIX("sv_ready_restart_");
440
441                 // mutators that announce themselves properly to the server browser
442                 BADCVAR("g_instagib");
443                 BADCVAR("g_new_toys");
444                 BADCVAR("g_nix");
445                 BADCVAR("g_grappling_hook");
446                 BADCVAR("g_jetpack");
447
448 #undef BADPREFIX
449 #undef BADCVAR
450
451                 if(pureadding)
452                 {
453                         cvar_purechanges = strcat(cvar_purechanges, k, " \"", v, "\" // \"", d, "\"\n");
454                         if(strlen(cvar_purechanges) > 16384)
455                         {
456                                 cvar_purechanges = "// too many settings have been changed to show them here\n";
457                                 pureadding = 0;
458                         }
459                 }
460                 ++cvar_purechanges_count;
461                 // WARNING: this variable is used for the server list
462                 // NEVER dare to skip this code!
463                 // Hacks to intentionally appearing as "pure server" even though you DO have
464                 // modified settings may be punished by removal from the server list.
465                 // You can do to the variables cvar_changes and cvar_purechanges all you want,
466                 // though.
467         }
468         buf_del(h);
469         if(cvar_changes == "")
470                 cvar_changes = "// this server runs at default server settings\n";
471         else
472                 cvar_changes = strcat("// this server runs at modified server settings:\n", cvar_changes);
473         cvar_changes = strzone(cvar_changes);
474         if(cvar_purechanges == "")
475                 cvar_purechanges = "// this server runs at default gameplay settings\n";
476         else
477                 cvar_purechanges = strcat("// this server runs at modified gameplay settings:\n", cvar_purechanges);
478         cvar_purechanges = strzone(cvar_purechanges);
479 }
480
481 void detect_maptype()
482 {
483 #if 0
484         vector o, v;
485         float i;
486
487         for (;;)
488         {
489                 o = world.mins;
490                 o.x += random() * (world.maxs.x - world.mins.x);
491                 o.y += random() * (world.maxs.y - world.mins.y);
492                 o.z += random() * (world.maxs.z - world.mins.z);
493
494                 tracebox(o, PL_MIN, PL_MAX, o - '0 0 32768', MOVE_WORLDONLY, world);
495                 if(trace_fraction == 1)
496                         continue;
497
498                 v = trace_endpos;
499
500                 for(i = 0; i < 64; i += 4)
501                 {
502                         tracebox(o, '-1 -1 -1' * i, '1 1 1' * i, o - '0 0 32768', MOVE_WORLDONLY, world);
503         if(trace_fraction == 1)
504                 continue;
505                         print(ftos(i), " -> ", vtos(trace_endpos), "\n");
506                 }
507
508                 break;
509         }
510 #endif
511 }
512
513 entity randomseed;
514 float RandomSeed_Send(entity to, int sf)
515 {
516         WriteByte(MSG_ENTITY, ENT_CLIENT_RANDOMSEED);
517         WriteShort(MSG_ENTITY, self.cnt);
518         return true;
519 }
520 void RandomSeed_Think()
521 {
522         self.cnt = bound(0, floor(random() * 65536), 65535);
523         self.nextthink = time + 5;
524
525         self.SendFlags |= 1;
526 }
527 void RandomSeed_Spawn()
528 {
529         randomseed = spawn();
530         randomseed.think = RandomSeed_Think;
531         Net_LinkEntity(randomseed, false, 0, RandomSeed_Send);
532
533         entity oldself;
534         oldself = self;
535         self = randomseed;
536         self.think(); // sets random seed and nextthink
537         self = oldself;
538 }
539
540 void spawnfunc___init_dedicated_server(void)
541 {
542         // handler for _init/_init map (only for dedicated server initialization)
543
544         world_initialized = -1; // don't complain
545         cvar = cvar_normal;
546         cvar_string = cvar_string_normal;
547         cvar_set = cvar_set_normal;
548
549         remove = remove_unsafely;
550
551         entity e;
552         e = spawn();
553         e.think = GotoFirstMap;
554         e.nextthink = time; // this is usually 1 at this point
555
556         e = spawn();
557         e.classname = "info_player_deathmatch"; // safeguard against player joining
558
559         self.classname = "worldspawn"; // safeguard against various stuff ;)
560
561         // needs to be done so early because of the constants they create
562         static_init();
563         CALL_ACCUMULATED_FUNCTION(RegisterTurrets);
564         CALL_ACCUMULATED_FUNCTION(RegisterNotifications);
565         CALL_ACCUMULATED_FUNCTION(RegisterDeathtypes);
566         CALL_ACCUMULATED_FUNCTION(RegisterEffects);
567
568         MapInfo_Enumerate();
569         MapInfo_FilterGametype(MapInfo_CurrentGametype(), MapInfo_CurrentFeatures(), MapInfo_RequiredFlags(), MapInfo_ForbiddenFlags(), 0);
570 }
571
572 void Map_MarkAsRecent(string m);
573 float world_already_spawned;
574 void Nagger_Init();
575 void ClientInit_Spawn();
576 void WeaponStats_Init();
577 void WeaponStats_Shutdown();
578 void Physics_AddStats();
579 void spawnfunc_worldspawn (void)
580 {
581         float fd, l, j, n;
582         string s;
583
584         cvar = cvar_normal;
585         cvar_string = cvar_string_normal;
586         cvar_set = cvar_set_normal;
587
588         if(world_already_spawned)
589                 error("world already spawned - you may have EXACTLY ONE worldspawn!");
590         world_already_spawned = true;
591
592         remove = remove_safely; // during spawning, watch what you remove!
593
594         cvar_changes_init(); // do this very early now so it REALLY matches the server config
595
596         compressShortVector_init();
597
598         entity head;
599         head = nextent(world);
600         maxclients = 0;
601         while(head)
602         {
603                 ++maxclients;
604                 head = nextent(head);
605         }
606
607         server_is_dedicated = (stof(cvar_defstring("is_dedicated")) ? true : false);
608
609         // needs to be done so early because of the constants they create
610         static_init();
611         CALL_ACCUMULATED_FUNCTION(RegisterTurrets);
612         CALL_ACCUMULATED_FUNCTION(RegisterNotifications);
613         CALL_ACCUMULATED_FUNCTION(RegisterDeathtypes);
614         CALL_ACCUMULATED_FUNCTION(RegisterEffects);
615
616         ServerProgsDB = db_load(strcat("server.db", autocvar_sessionid));
617
618         TemporaryDB = db_create();
619
620         // 0 normal
621         lightstyle(0, "m");
622
623         // 1 FLICKER (first variety)
624         lightstyle(1, "mmnmmommommnonmmonqnmmo");
625
626         // 2 SLOW STRONG PULSE
627         lightstyle(2, "abcdefghijklmnopqrstuvwxyzyxwvutsrqponmlkjihgfedcba");
628
629         // 3 CANDLE (first variety)
630         lightstyle(3, "mmmmmaaaaammmmmaaaaaabcdefgabcdefg");
631
632         // 4 FAST STROBE
633         lightstyle(4, "mamamamamama");
634
635         // 5 GENTLE PULSE 1
636         lightstyle(5,"jklmnopqrstuvwxyzyxwvutsrqponmlkj");
637
638         // 6 FLICKER (second variety)
639         lightstyle(6, "nmonqnmomnmomomno");
640
641         // 7 CANDLE (second variety)
642         lightstyle(7, "mmmaaaabcdefgmmmmaaaammmaamm");
643
644         // 8 CANDLE (third variety)
645         lightstyle(8, "mmmaaammmaaammmabcdefaaaammmmabcdefmmmaaaa");
646
647         // 9 SLOW STROBE (fourth variety)
648         lightstyle(9, "aaaaaaaazzzzzzzz");
649
650         // 10 FLUORESCENT FLICKER
651         lightstyle(10, "mmamammmmammamamaaamammma");
652
653         // 11 SLOW PULSE NOT FADE TO BLACK
654         lightstyle(11, "abcdefghijklmnopqrrqponmlkjihgfedcba");
655
656         // styles 32-62 are assigned by the spawnfunc_light program for switchable lights
657
658         // 63 testing
659         lightstyle(63, "a");
660
661         if(autocvar_g_campaign)
662                 CampaignPreInit();
663
664         Map_MarkAsRecent(mapname);
665
666         PlayerStats_GameReport_Init(); // we need this to be initiated before InitGameplayMode
667
668         precache_model ("null"); // we need this one before InitGameplayMode
669         InitGameplayMode();
670         readlevelcvars();
671         GrappleHookInit();
672
673         player_count = 0;
674         bot_waypoints_for_items = autocvar_g_waypoints_for_items;
675         if(bot_waypoints_for_items == 1)
676                 if(self.spawnflags & SPAWNFLAG_NO_WAYPOINTS_FOR_ITEMS)
677                         bot_waypoints_for_items = 0;
678
679         precache();
680
681         WaypointSprite_Init();
682
683         GameLogInit(); // prepare everything
684         // NOTE for matchid:
685         // changing the logic generating it is okay. But:
686         // it HAS to stay <= 64 chars
687         // character set: ASCII 33-126 without the following characters: : ; ' " \ $
688         if(autocvar_sv_eventlog)
689         {
690                 s = sprintf("%d.%s.%06d", itos(autocvar_sv_eventlog_files_counter), strftime(false, "%s"), floor(random() * 1000000));
691                 matchid = strzone(s);
692
693                 GameLogEcho(strcat(":gamestart:", GetGametype(), "_", GetMapname(), ":", s));
694                 s = ":gameinfo:mutators:LIST";
695
696                 MUTATOR_CALLHOOK(BuildMutatorsString, s);
697                 s = ret_string;
698
699                 // simple, probably not good in the mutator system
700                 if(autocvar_g_grappling_hook)
701                         s = strcat(s, ":grappling_hook");
702
703                 // initialiation stuff, not good in the mutator system
704                 if(!autocvar_g_use_ammunition)
705                         s = strcat(s, ":no_use_ammunition");
706
707                 // initialiation stuff, not good in the mutator system
708                 if(autocvar_g_pickup_items == 0)
709                         s = strcat(s, ":no_pickup_items");
710                 if(autocvar_g_pickup_items > 0)
711                         s = strcat(s, ":pickup_items");
712
713                 // initialiation stuff, not good in the mutator system
714                 if(autocvar_g_weaponarena != "0")
715                         s = strcat(s, ":", autocvar_g_weaponarena, " arena");
716
717                 // TODO to mutator system
718                 if(autocvar_g_norecoil)
719                         s = strcat(s, ":norecoil");
720
721                 // TODO to mutator system
722                 if(autocvar_g_powerups == 0)
723                         s = strcat(s, ":no_powerups");
724                 if(autocvar_g_powerups > 0)
725                         s = strcat(s, ":powerups");
726
727                 GameLogEcho(s);
728                 GameLogEcho(":gameinfo:end");
729         }
730         else
731                 matchid = strzone(ftos(random()));
732
733         cvar_set("nextmap", "");
734
735         SetDefaultAlpha();
736
737         if(autocvar_g_campaign)
738                 CampaignPostInit();
739
740         Ban_LoadBans();
741
742         MapInfo_Enumerate();
743         MapInfo_FilterGametype(MapInfo_CurrentGametype(), MapInfo_CurrentFeatures(), MapInfo_RequiredFlags(), MapInfo_ForbiddenFlags(), 1);
744
745         if(whichpack(strcat("maps/", mapname, ".cfg")) != "")
746         {
747                 fd = fopen(strcat("maps/", mapname, ".cfg"), FILE_READ);
748                 if(fd != -1)
749                 {
750                         while((s = fgets(fd)))
751                         {
752                                 l = tokenize_console(s);
753                                 if(l < 2)
754                                         continue;
755                                 if(argv(0) == "cd")
756                                 {
757                                         print("Found ^1UNSUPPORTED^7 cd loop command in .cfg file; put this line in mapinfo instead:\n");
758                                         print("  cdtrack ", argv(2), "\n");
759                                 }
760                                 else if(argv(0) == "fog")
761                                 {
762                                         print("Found ^1UNSUPPORTED^7 fog command in .cfg file; put this line in worldspawn in the .map/.bsp/.ent file instead:\n");
763                                         print("  \"fog\" \"", s, "\"\n");
764                                 }
765                                 else if(argv(0) == "set")
766                                 {
767                                         print("Found ^1UNSUPPORTED^7 set command in .cfg file; put this line in mapinfo instead:\n");
768                                         print("  clientsettemp_for_type all ", argv(1), " ", argv(2), "\n");
769                                 }
770                                 else if(argv(0) != "//")
771                                 {
772                                         print("Found ^1UNSUPPORTED^7 set command in .cfg file; put this line in mapinfo instead:\n");
773                                         print("  clientsettemp_for_type all ", argv(0), " ", argv(1), "\n");
774                                 }
775                         }
776                         fclose(fd);
777                 }
778         }
779
780         WeaponStats_Init();
781
782         WepSet_AddStat();
783         WepSet_AddStat_InMap();
784         addstat(STAT_SWITCHWEAPON, AS_INT, switchweapon);
785         addstat(STAT_SWITCHINGWEAPON, AS_INT, switchingweapon);
786         addstat(STAT_GAMESTARTTIME, AS_FLOAT, stat_game_starttime);
787         addstat(STAT_ROUNDSTARTTIME, AS_FLOAT, stat_round_starttime);
788         addstat(STAT_ALLOW_OLDVORTEXBEAM, AS_INT, stat_allow_oldvortexbeam);
789         Nagger_Init();
790
791         addstat(STAT_STRENGTH_FINISHED, AS_FLOAT, strength_finished);
792         addstat(STAT_INVINCIBLE_FINISHED, AS_FLOAT, invincible_finished);
793         addstat(STAT_SUPERWEAPONS_FINISHED, AS_FLOAT, superweapons_finished);
794         addstat(STAT_PRESSED_KEYS, AS_FLOAT, pressedkeys);
795         addstat(STAT_FUEL, AS_INT, ammo_fuel);
796         addstat(STAT_PLASMA, AS_INT, ammo_plasma);
797         addstat(STAT_SHOTORG, AS_INT, stat_shotorg);
798         addstat(STAT_LEADLIMIT, AS_FLOAT, stat_leadlimit);
799         addstat(STAT_WEAPON_CLIPLOAD, AS_INT, clip_load);
800         addstat(STAT_WEAPON_CLIPSIZE, AS_INT, clip_size);
801         addstat(STAT_LAST_PICKUP, AS_FLOAT, last_pickup);
802         addstat(STAT_HIT_TIME, AS_FLOAT, hit_time);
803         addstat(STAT_DAMAGE_DEALT_TOTAL, AS_INT, damage_dealt_total);
804         addstat(STAT_TYPEHIT_TIME, AS_FLOAT, typehit_time);
805         addstat(STAT_LAYED_MINES, AS_INT, minelayer_mines);
806
807         addstat(STAT_VORTEX_CHARGE, AS_FLOAT, vortex_charge);
808         addstat(STAT_VORTEX_CHARGEPOOL, AS_FLOAT, vortex_chargepool_ammo);
809
810         addstat(STAT_HAGAR_LOAD, AS_INT, hagar_load);
811
812         addstat(STAT_ARC_HEAT, AS_FLOAT, arc_heat_percent);
813
814         // freeze attacks
815         addstat(STAT_FROZEN, AS_INT, frozen);
816         addstat(STAT_REVIVE_PROGRESS, AS_FLOAT, revive_progress);
817
818         // physics
819         Physics_AddStats();
820
821         // new properties
822         addstat(STAT_MOVEVARS_JUMPVELOCITY, AS_FLOAT, stat_sv_jumpvelocity);
823         addstat(STAT_MOVEVARS_AIRACCEL_QW_STRETCHFACTOR, AS_FLOAT, stat_sv_airaccel_qw_stretchfactor);
824         addstat(STAT_MOVEVARS_MAXAIRSTRAFESPEED, AS_FLOAT, stat_sv_maxairstrafespeed);
825         addstat(STAT_MOVEVARS_MAXAIRSPEED, AS_FLOAT, stat_sv_maxairspeed);
826         addstat(STAT_MOVEVARS_AIRSTRAFEACCELERATE, AS_FLOAT, stat_sv_airstrafeaccelerate);
827         addstat(STAT_MOVEVARS_WARSOWBUNNY_TURNACCEL, AS_FLOAT, stat_sv_warsowbunny_turnaccel);
828         addstat(STAT_MOVEVARS_AIRACCEL_SIDEWAYS_FRICTION, AS_FLOAT, stat_sv_airaccel_sideways_friction);
829         addstat(STAT_MOVEVARS_AIRCONTROL, AS_FLOAT, stat_sv_aircontrol);
830         addstat(STAT_MOVEVARS_AIRCONTROL_POWER, AS_FLOAT, stat_sv_aircontrol_power);
831         addstat(STAT_MOVEVARS_AIRCONTROL_PENALTY, AS_FLOAT, stat_sv_aircontrol_penalty);
832         addstat(STAT_MOVEVARS_WARSOWBUNNY_AIRFORWARDACCEL, AS_FLOAT, stat_sv_warsowbunny_airforwardaccel);
833         addstat(STAT_MOVEVARS_WARSOWBUNNY_TOPSPEED, AS_FLOAT, stat_sv_warsowbunny_topspeed);
834         addstat(STAT_MOVEVARS_WARSOWBUNNY_ACCEL, AS_FLOAT, stat_sv_warsowbunny_accel);
835         addstat(STAT_MOVEVARS_WARSOWBUNNY_BACKTOSIDERATIO, AS_FLOAT, stat_sv_warsowbunny_backtosideratio);
836         addstat(STAT_MOVEVARS_FRICTION, AS_FLOAT, stat_sv_friction);
837         addstat(STAT_MOVEVARS_ACCELERATE, AS_FLOAT, stat_sv_accelerate);
838         addstat(STAT_MOVEVARS_STOPSPEED, AS_FLOAT, stat_sv_stopspeed);
839         addstat(STAT_MOVEVARS_AIRACCELERATE, AS_FLOAT, stat_sv_airaccelerate);
840         addstat(STAT_MOVEVARS_AIRSTOPACCELERATE, AS_FLOAT, stat_sv_airstopaccelerate);
841
842         // secrets
843         addstat(STAT_SECRETS_TOTAL, AS_FLOAT, stat_secrets_total);
844         addstat(STAT_SECRETS_FOUND, AS_FLOAT, stat_secrets_found);
845
846         // monsters
847         addstat(STAT_MONSTERS_TOTAL, AS_FLOAT, stat_monsters_total);
848         addstat(STAT_MONSTERS_KILLED, AS_FLOAT, stat_monsters_killed);
849
850         // misc
851         addstat(STAT_RESPAWN_TIME, AS_FLOAT, stat_respawn_time);
852
853         next_pingtime = time + 5;
854
855         detect_maptype();
856
857         // set up information replies for clients and server to use
858         maplist_reply = strzone(getmaplist());
859         lsmaps_reply = strzone(getlsmaps());
860         monsterlist_reply = strzone(getmonsterlist());
861         for(int i = 0; i < 10; ++i)
862         {
863                 s = getrecords(i);
864                 if (s)
865                         records_reply[i] = strzone(s);
866         }
867         ladder_reply = strzone(getladder());
868         rankings_reply = strzone(getrankings());
869
870         // begin other init
871         ClientInit_Spawn();
872         RandomSeed_Spawn();
873         PingPLReport_Spawn();
874
875         CheatInit();
876
877         localcmd("\n_sv_hook_gamestart ", GetGametype(), "\n");
878
879         // fill sv_curl_serverpackages from .serverpackage files
880         if(autocvar_sv_curl_serverpackages_auto)
881         {
882                 s = "";
883                 n = tokenize_console(cvar_string("sv_curl_serverpackages"));
884                 for(int i = 0; i < n; ++i)
885                         if(substring(argv(i), -18, -1) != "-serverpackage.txt")
886                         if(substring(argv(i), -14, -1) != ".serverpackage") // OLD legacy
887                                 s = strcat(s, " ", argv(i));
888                 fd = search_begin("*-serverpackage.txt", true, false);
889                 if(fd >= 0)
890                 {
891                         j = search_getsize(fd);
892                         for(int i = 0; i < j; ++i)
893                                 s = strcat(s, " ", search_getfilename(fd, i));
894                         search_end(fd);
895                 }
896                 fd = search_begin("*.serverpackage", true, false);
897                 if(fd >= 0)
898                 {
899                         j = search_getsize(fd);
900                         for(int i = 0; i < j; ++i)
901                                 s = strcat(s, " ", search_getfilename(fd, i));
902                         search_end(fd);
903                 }
904                 cvar_set("sv_curl_serverpackages", substring(s, 1, -1));
905         }
906
907         // MOD AUTHORS: change this, and possibly remove a few of the blocks below to ignore certain changes
908         modname = "Xonotic";
909         // physics/balance/config changes that count as mod
910         if(cvar_string("g_mod_physics") != cvar_defstring("g_mod_physics"))
911                 modname = cvar_string("g_mod_physics");
912         if(cvar_string("g_mod_balance") != cvar_defstring("g_mod_balance"))
913                 modname = cvar_string("g_mod_balance");
914         if(cvar_string("g_mod_config") != cvar_defstring("g_mod_config"))
915                 modname = cvar_string("g_mod_config");
916         // extra mutators that deserve to count as mod
917         MUTATOR_CALLHOOK(SetModname);
918
919         // save it for later
920         modname = strzone(modname);
921
922         WinningConditionHelper(); // set worldstatus
923
924         world_initialized = 1;
925 }
926
927 void spawnfunc_light (void)
928 {
929         //makestatic (self); // Who the f___ did that?
930         remove(self);
931 }
932
933 string GetGametype()
934 {
935         return MapInfo_Type_ToString(MapInfo_LoadedGametype);
936 }
937
938 string GetMapname()
939 {
940         return mapname;
941 }
942
943 float Map_Count, Map_Current;
944 string Map_Current_Name;
945
946 // NOTE: this now expects the map list to be already tokenized and the count in Map_Count
947 float GetMaplistPosition()
948 {
949         float pos, idx;
950         string map;
951
952         map = GetMapname();
953         idx = autocvar_g_maplist_index;
954
955         if(idx >= 0)
956                 if(idx < Map_Count)
957                         if(map == argv(idx))
958                                 return idx;
959
960         for(pos = 0; pos < Map_Count; ++pos)
961                 if(map == argv(pos))
962                         return pos;
963
964         // resume normal maplist rotation if current map is not in g_maplist
965         return idx;
966 }
967
968 float MapHasRightSize(string map)
969 {
970         float fh;
971         if(currentbots || autocvar_bot_number || player_count < autocvar_minplayers)
972         if(autocvar_g_maplist_check_waypoints)
973         {
974                 dprint("checkwp "); dprint(map);
975                 if(!fexists(strcat("maps/", map, ".waypoints")))
976                 {
977                         dprint(": no waypoints\n");
978                         return false;
979                 }
980                 dprint(": has waypoints\n");
981         }
982
983         // open map size restriction file
984         dprint("opensize "); dprint(map);
985         fh = fopen(strcat("maps/", map, ".sizes"), FILE_READ);
986         if(fh >= 0)
987         {
988                 float mapmin, mapmax;
989                 dprint(": ok, ");
990                 mapmin = stof(fgets(fh));
991                 mapmax = stof(fgets(fh));
992                 fclose(fh);
993                 if(player_count < mapmin)
994                 {
995                         dprint("not enough\n");
996                         return false;
997                 }
998                 if(player_count > mapmax)
999                 {
1000                         dprint("too many\n");
1001                         return false;
1002                 }
1003                 dprint("right size\n");
1004                 return true;
1005         }
1006         dprint(": not found\n");
1007         return true;
1008 }
1009
1010 string Map_Filename(float position)
1011 {
1012         return strcat("maps/", argv(position), ".bsp");
1013 }
1014
1015 string strwords(string s, float w)
1016 {
1017         float endpos;
1018         for(endpos = 0; w && endpos >= 0; --w)
1019                 endpos = strstrofs(s, " ", endpos + 1);
1020         if(endpos < 0)
1021                 return s;
1022         else
1023                 return substring(s, 0, endpos);
1024 }
1025
1026 float strhasword(string s, string w)
1027 {
1028         return strstrofs(strcat(" ", s, " "), strcat(" ", w, " "), 0) >= 0;
1029 }
1030
1031 void Map_MarkAsRecent(string m)
1032 {
1033         cvar_set("g_maplist_mostrecent", strwords(strcat(m, " ", autocvar_g_maplist_mostrecent), max(0, autocvar_g_maplist_mostrecent_count)));
1034 }
1035
1036 float Map_IsRecent(string m)
1037 {
1038         return strhasword(autocvar_g_maplist_mostrecent, m);
1039 }
1040
1041 float Map_Check(float position, float pass)
1042 {
1043         string filename;
1044         string map_next;
1045         map_next = argv(position);
1046         if(pass <= 1)
1047         {
1048                 if(Map_IsRecent(map_next))
1049                         return 0;
1050         }
1051         filename = Map_Filename(position);
1052         if(MapInfo_CheckMap(map_next))
1053         {
1054                 if(pass == 2)
1055                         return 1;
1056                 if(MapHasRightSize(map_next))
1057                         return 1;
1058                 return 0;
1059         }
1060         else
1061                 dprint( "Couldn't select '", filename, "'..\n" );
1062
1063         return 0;
1064 }
1065
1066 void Map_Goto_SetStr(string nextmapname)
1067 {
1068         if(getmapname_stored != "")
1069                 strunzone(getmapname_stored);
1070         if(nextmapname == "")
1071                 getmapname_stored = "";
1072         else
1073                 getmapname_stored = strzone(nextmapname);
1074 }
1075
1076 void Map_Goto_SetFloat(float position)
1077 {
1078         cvar_set("g_maplist_index", ftos(position));
1079         Map_Goto_SetStr(argv(position));
1080 }
1081
1082 void Map_Goto(float reinit)
1083 {
1084         MapInfo_LoadMap(getmapname_stored, reinit);
1085 }
1086
1087 // return codes of map selectors:
1088 //   -1 = temporary failure (that is, try some method that is guaranteed to succeed)
1089 //   -2 = permanent failure
1090 float() MaplistMethod_Iterate = // usual method
1091 {
1092         float pass, i;
1093
1094         dprint("Trying MaplistMethod_Iterate\n");
1095
1096         for(pass = 1; pass <= 2; ++pass)
1097         {
1098                 for(i = 1; i < Map_Count; ++i)
1099                 {
1100                         float mapindex;
1101                         mapindex = (i + Map_Current) % Map_Count;
1102                         if(Map_Check(mapindex, pass))
1103                                 return mapindex;
1104                 }
1105         }
1106         return -1;
1107 }
1108
1109 float() MaplistMethod_Repeat = // fallback method
1110 {
1111         dprint("Trying MaplistMethod_Repeat\n");
1112
1113         if(Map_Check(Map_Current, 2))
1114                 return Map_Current;
1115         return -2;
1116 }
1117
1118 float() MaplistMethod_Random = // random map selection
1119 {
1120         float i, imax;
1121
1122         dprint("Trying MaplistMethod_Random\n");
1123
1124         imax = 42;
1125
1126         for(i = 0; i <= imax; ++i)
1127         {
1128                 float mapindex;
1129                 mapindex = (Map_Current + floor(random() * (Map_Count - 1) + 1)) % Map_Count; // any OTHER map
1130                 if(Map_Check(mapindex, 1))
1131                         return mapindex;
1132         }
1133         return -1;
1134 }
1135
1136 float(float exponent) MaplistMethod_Shuffle = // more clever shuffling
1137 // the exponent sets a bias on the map selection:
1138 // the higher the exponent, the less likely "shortly repeated" same maps are
1139 {
1140         float i, j, imax, insertpos;
1141
1142         dprint("Trying MaplistMethod_Shuffle\n");
1143
1144         imax = 42;
1145
1146         for(i = 0; i <= imax; ++i)
1147         {
1148                 string newlist;
1149
1150                 // now reinsert this at another position
1151                 insertpos = pow(random(), 1 / exponent);       // ]0, 1]
1152                 insertpos = insertpos * (Map_Count - 1);       // ]0, Map_Count - 1]
1153                 insertpos = ceil(insertpos) + 1;               // {2, 3, 4, ..., Map_Count}
1154                 dprint("SHUFFLE: insert pos = ", ftos(insertpos), "\n");
1155
1156                 // insert the current map there
1157                 newlist = "";
1158                 for(j = 1; j < insertpos; ++j)                 // i == 1: no loop, will be inserted as first; however, i == 1 has been excluded above
1159                         newlist = strcat(newlist, " ", argv(j));
1160                 newlist = strcat(newlist, " ", argv(0));       // now insert the just selected map
1161                 for(j = insertpos; j < Map_Count; ++j)         // i == Map_Count: no loop, has just been inserted as last
1162                         newlist = strcat(newlist, " ", argv(j));
1163                 newlist = substring(newlist, 1, strlen(newlist) - 1);
1164                 cvar_set("g_maplist", newlist);
1165                 Map_Count = tokenizebyseparator(autocvar_g_maplist, " ");
1166
1167                 // NOTE: the selected map has just been inserted at (insertpos-1)th position
1168                 Map_Current = insertpos - 1; // this is not really valid, but this way the fallback has a chance of working
1169                 if(Map_Check(Map_Current, 1))
1170                         return Map_Current;
1171         }
1172         return -1;
1173 }
1174
1175 void Maplist_Init()
1176 {
1177         Map_Count = tokenizebyseparator(autocvar_g_maplist, " ");
1178         float i;
1179         for (i = 0; i < Map_Count; ++i)
1180                 if (Map_Check(i, 2))
1181                         break;
1182         if (i == Map_Count)
1183         {
1184                 bprint( "Maplist contains no usable maps!  Resetting it to default map list.\n" );
1185                 cvar_set("g_maplist", MapInfo_ListAllAllowedMaps(MapInfo_RequiredFlags(), MapInfo_ForbiddenFlags() | MAPINFO_FLAG_NOAUTOMAPLIST));
1186                 if(autocvar_g_maplist_shuffle)
1187                         ShuffleMaplist();
1188                 localcmd("\nmenu_cmd sync\n");
1189                 Map_Count = tokenizebyseparator(autocvar_g_maplist, " ");
1190         }
1191         if(Map_Count == 0)
1192                 error("empty maplist, cannot select a new map");
1193         Map_Current = bound(0, GetMaplistPosition(), Map_Count - 1);
1194
1195         if(Map_Current_Name)
1196                 strunzone(Map_Current_Name);
1197         Map_Current_Name = strzone(argv(Map_Current)); // will be automatically freed on exit thanks to DP
1198         // this may or may not be correct, but who cares, in the worst case a map
1199         // isn't chosen in the first pass that should have been
1200 }
1201
1202 string GetNextMap()
1203 {
1204         float nextMap;
1205
1206         Maplist_Init();
1207         nextMap = -1;
1208
1209         if(nextMap == -1)
1210                 if(autocvar_g_maplist_shuffle > 0)
1211                         nextMap = MaplistMethod_Shuffle(autocvar_g_maplist_shuffle + 1);
1212
1213         if(nextMap == -1)
1214                 if(autocvar_g_maplist_selectrandom)
1215                         nextMap = MaplistMethod_Random();
1216
1217         if(nextMap == -1)
1218                 nextMap = MaplistMethod_Iterate();
1219
1220         if(nextMap == -1)
1221                 nextMap = MaplistMethod_Repeat();
1222
1223         if(nextMap >= 0)
1224         {
1225                 Map_Goto_SetFloat(nextMap);
1226                 return getmapname_stored;
1227         }
1228
1229         return "";
1230 }
1231
1232 float DoNextMapOverride(float reinit)
1233 {
1234         if(autocvar_g_campaign)
1235         {
1236                 CampaignPostIntermission();
1237                 alreadychangedlevel = true;
1238                 return true;
1239         }
1240         if(autocvar_quit_when_empty)
1241         {
1242                 if(player_count <= currentbots)
1243                 {
1244                         localcmd("quit\n");
1245                         alreadychangedlevel = true;
1246                         return true;
1247                 }
1248         }
1249         if(autocvar_quit_and_redirect != "")
1250         {
1251                 redirection_target = strzone(autocvar_quit_and_redirect);
1252                 alreadychangedlevel = true;
1253                 return true;
1254         }
1255         if (!reinit && autocvar_samelevel) // if samelevel is set, stay on same level
1256         {
1257                 localcmd("restart\n");
1258                 alreadychangedlevel = true;
1259                 return true;
1260         }
1261         if(autocvar_nextmap != "")
1262         {
1263                 string m;
1264                 m = GameTypeVote_MapInfo_FixName(autocvar_nextmap);
1265                 cvar_set("nextmap",m);
1266
1267                 if(!m || gametypevote)
1268                         return false;
1269                 if(autocvar_sv_vote_gametype)
1270                 {
1271                         Map_Goto_SetStr(m);
1272                         return false;
1273                 }
1274
1275                 if(MapInfo_CheckMap(m))
1276                 {
1277                         Map_Goto_SetStr(m);
1278                         Map_Goto(reinit);
1279                         alreadychangedlevel = true;
1280                         return true;
1281                 }
1282         }
1283         if(!reinit && autocvar_lastlevel)
1284         {
1285                 cvar_settemp_restore();
1286                 localcmd("set lastlevel 0\ntogglemenu 1\n");
1287                 alreadychangedlevel = true;
1288                 return true;
1289         }
1290         return false;
1291 }
1292
1293 void GotoNextMap(float reinit)
1294 {
1295         //string nextmap;
1296         //float n, nummaps;
1297         //string s;
1298         if (alreadychangedlevel)
1299                 return;
1300         alreadychangedlevel = true;
1301
1302         string nextMap;
1303
1304         nextMap = GetNextMap();
1305         if(nextMap == "")
1306                 error("Everything is broken - cannot find a next map. Please report this to the developers.");
1307         Map_Goto(reinit);
1308 }
1309
1310
1311 /*
1312 ============
1313 IntermissionThink
1314
1315 When the player presses attack or jump, change to the next level
1316 ============
1317 */
1318 .float autoscreenshot;
1319 void IntermissionThink()
1320 {
1321         FixIntermissionClient(self);
1322
1323         float server_screenshot = (autocvar_sv_autoscreenshot && self.cvar_cl_autoscreenshot);
1324         float client_screenshot = (self.cvar_cl_autoscreenshot == 2);
1325
1326         if( (server_screenshot || client_screenshot)
1327                 && ((self.autoscreenshot > 0) && (time > self.autoscreenshot)) )
1328         {
1329                 self.autoscreenshot = -1;
1330                 if(IS_REAL_CLIENT(self)) { stuffcmd(self, sprintf("\nscreenshot screenshots/autoscreenshot/%s-%s.jpg; echo \"^5A screenshot has been taken at request of the server.\"\n", GetMapname(), strftime(false, "%s"))); }
1331                 return;
1332         }
1333
1334         if (time < intermission_exittime)
1335                 return;
1336
1337         if(!mapvote_initialized)
1338                 if (time < intermission_exittime + 10 && !(self.BUTTON_ATCK || self.BUTTON_JUMP || self.BUTTON_ATCK2 || self.BUTTON_HOOK || self.BUTTON_USE))
1339                         return;
1340
1341         MapVote_Start();
1342 }
1343
1344 /*
1345 ============
1346 FindIntermission
1347
1348 Returns the entity to view from
1349 ============
1350 */
1351 /*
1352 entity FindIntermission()
1353 {
1354         local   entity spot;
1355         local   float cyc;
1356
1357 // look for info_intermission first
1358         spot = find (world, classname, "info_intermission");
1359         if (spot)
1360         {       // pick a random one
1361                 cyc = random() * 4;
1362                 while (cyc > 1)
1363                 {
1364                         spot = find (spot, classname, "info_intermission");
1365                         if (!spot)
1366                                 spot = find (spot, classname, "info_intermission");
1367                         cyc = cyc - 1;
1368                 }
1369                 return spot;
1370         }
1371
1372 // then look for the start position
1373         spot = find (world, classname, "info_player_start");
1374         if (spot)
1375                 return spot;
1376
1377 // testinfo_player_start is only found in regioned levels
1378         spot = find (world, classname, "testplayerstart");
1379         if (spot)
1380                 return spot;
1381
1382 // then look for the start position
1383         spot = find (world, classname, "info_player_deathmatch");
1384         if (spot)
1385                 return spot;
1386
1387         //objerror ("FindIntermission: no spot");
1388         return world;
1389 }
1390 */
1391
1392 /*
1393 ===============================================================================
1394
1395 RULES
1396
1397 ===============================================================================
1398 */
1399
1400 void DumpStats(float final)
1401 {
1402         float file;
1403         string s;
1404         float to_console;
1405         float to_eventlog;
1406         float to_file;
1407         float i;
1408
1409         to_console = autocvar_sv_logscores_console;
1410         to_eventlog = autocvar_sv_eventlog;
1411         to_file = autocvar_sv_logscores_file;
1412
1413         if(!final)
1414         {
1415                 to_console = true; // always print printstats replies
1416                 to_eventlog = false; // but never print them to the event log
1417         }
1418
1419         if(to_eventlog)
1420                 if(autocvar_sv_eventlog_console)
1421                         to_console = false; // otherwise we get the output twice
1422
1423         if(final)
1424                 s = ":scores:";
1425         else
1426                 s = ":status:";
1427         s = strcat(s, GetGametype(), "_", GetMapname(), ":", ftos(rint(time)));
1428
1429         if(to_console)
1430                 print(s, "\n");
1431         if(to_eventlog)
1432                 GameLogEcho(s);
1433
1434         file = -1;
1435         if(to_file)
1436         {
1437                 file = fopen(autocvar_sv_logscores_filename, FILE_APPEND);
1438                 if(file == -1)
1439                         to_file = false;
1440                 else
1441                         fputs(file, strcat(s, "\n"));
1442         }
1443
1444         s = strcat(":labels:player:", GetPlayerScoreString(world, 0));
1445         if(to_console)
1446                 print(s, "\n");
1447         if(to_eventlog)
1448                 GameLogEcho(s);
1449         if(to_file)
1450                 fputs(file, strcat(s, "\n"));
1451
1452         FOR_EACH_CLIENT(other)
1453         {
1454                 if ((IS_REAL_CLIENT(other)) || (IS_BOT_CLIENT(other) && autocvar_sv_logscores_bots))
1455                 {
1456                         s = strcat(":player:see-labels:", GetPlayerScoreString(other, 0), ":");
1457                         s = strcat(s, ftos(rint(time - other.jointime)), ":");
1458                         if(IS_PLAYER(other) || other.caplayer == 1 || g_lms)
1459                                 s = strcat(s, ftos(other.team), ":");
1460                         else
1461                                 s = strcat(s, "spectator:");
1462
1463                         if(to_console)
1464                                 print(s, other.netname, "\n");
1465                         if(to_eventlog)
1466                                 GameLogEcho(strcat(s, ftos(other.playerid), ":", other.netname));
1467                         if(to_file)
1468                                 fputs(file, strcat(s, other.netname, "\n"));
1469                 }
1470         }
1471
1472         if(teamplay)
1473         {
1474                 s = strcat(":labels:teamscores:", GetTeamScoreString(0, 0));
1475                 if(to_console)
1476                         print(s, "\n");
1477                 if(to_eventlog)
1478                         GameLogEcho(s);
1479                 if(to_file)
1480                         fputs(file, strcat(s, "\n"));
1481
1482                 for(i = 1; i < 16; ++i)
1483                 {
1484                         s = strcat(":teamscores:see-labels:", GetTeamScoreString(i, 0));
1485                         s = strcat(s, ":", ftos(i));
1486                         if(to_console)
1487                                 print(s, "\n");
1488                         if(to_eventlog)
1489                                 GameLogEcho(s);
1490                         if(to_file)
1491                                 fputs(file, strcat(s, "\n"));
1492                 }
1493         }
1494
1495         if(to_console)
1496                 print(":end\n");
1497         if(to_eventlog)
1498                 GameLogEcho(":end");
1499         if(to_file)
1500         {
1501                 fputs(file, ":end\n");
1502                 fclose(file);
1503         }
1504 }
1505
1506 void FixIntermissionClient(entity e)
1507 {
1508         string s;
1509         if(!e.autoscreenshot) // initial call
1510         {
1511                 e.autoscreenshot = time + 0.8;  // used for autoscreenshot
1512                 e.health = -2342;
1513                 // first intermission phase; voting phase has positive health (used to decide whether to send SVC_FINALE or not)
1514                 e.solid = SOLID_NOT;
1515                 e.movetype = MOVETYPE_NONE;
1516                 e.takedamage = DAMAGE_NO;
1517                 if(e.weaponentity)
1518                 {
1519                         e.weaponentity.effects = EF_NODRAW;
1520                         if (e.weaponentity.weaponentity)
1521                                 e.weaponentity.weaponentity.effects = EF_NODRAW;
1522                 }
1523                 if(IS_REAL_CLIENT(e))
1524                 {
1525                         stuffcmd(e, "\nscr_printspeed 1000000\n");
1526                         s = autocvar_sv_intermission_cdtrack;
1527                         if(s != "")
1528                                 stuffcmd(e, strcat("\ncd loop ", s, "\n"));
1529                         msg_entity = e;
1530                         WriteByte(MSG_ONE, SVC_INTERMISSION);
1531                 }
1532         }
1533 }
1534
1535 /*
1536 go to the next level for deathmatch
1537 only called if a time or frag limit has expired
1538 */
1539 void NextLevel()
1540 {
1541         gameover = true;
1542
1543         intermission_running = 1;
1544
1545 // enforce a wait time before allowing changelevel
1546         if(player_count > 0)
1547                 intermission_exittime = time + autocvar_sv_mapchange_delay;
1548         else
1549                 intermission_exittime = -1;
1550
1551         /*
1552         WriteByte (MSG_ALL, SVC_CDTRACK);
1553         WriteByte (MSG_ALL, 3);
1554         WriteByte (MSG_ALL, 3);
1555         // done in FixIntermission
1556         */
1557
1558         //pos = FindIntermission ();
1559
1560         VoteReset();
1561
1562         DumpStats(true);
1563
1564         // send statistics
1565         PlayerStats_GameReport(true);
1566         WeaponStats_Shutdown();
1567
1568         Kill_Notification(NOTIF_ALL, world, MSG_CENTER, 0); // kill all centerprints now
1569
1570         if(autocvar_sv_eventlog)
1571                 GameLogEcho(":gameover");
1572
1573         GameLogClose();
1574
1575         FOR_EACH_PLAYER(other) {
1576                 FixIntermissionClient(other);
1577                 if(other.winning)
1578                         bprint(other.netname, " ^7wins.\n");
1579         }
1580
1581         if(autocvar_g_campaign)
1582                 CampaignPreIntermission();
1583
1584         MUTATOR_CALLHOOK(MatchEnd);
1585
1586         localcmd("\nsv_hook_gameend\n");
1587 }
1588
1589 /*
1590 ============
1591 CheckRules_Player
1592
1593 Exit deathmatch games upon conditions
1594 ============
1595 */
1596 void CheckRules_Player()
1597 {
1598         if (gameover)   // someone else quit the game already
1599                 return;
1600
1601         if(self.deadflag == DEAD_NO)
1602                 self.play_time += frametime;
1603
1604         // fixme: don't check players; instead check spawnfunc_dom_team and spawnfunc_ctf_team entities
1605         //   (div0: and that in CheckRules_World please)
1606 }
1607
1608
1609 float InitiateSuddenDeath()
1610 {
1611         // Check first whether normal overtimes could be added before initiating suddendeath mode
1612         // - for this timelimit_overtime needs to be >0 of course
1613         // - also check the winning condition calculated in the previous frame and only add normal overtime
1614         //   again, if at the point at which timelimit would be extended again, still no winner was found
1615         if (!autocvar_g_campaign && (checkrules_overtimesadded >= 0) && (checkrules_overtimesadded < autocvar_timelimit_overtimes || autocvar_timelimit_overtimes < 0) && autocvar_timelimit_overtime && !(g_race && !g_race_qualifying))
1616         {
1617                 return 1; // need to call InitiateOvertime later
1618         }
1619         else
1620         {
1621                 if(!checkrules_suddendeathend)
1622                 {
1623                         if(autocvar_g_campaign)
1624                                 checkrules_suddendeathend = time; // no suddendeath in campaign
1625                         else
1626                                 checkrules_suddendeathend = time + 60 * autocvar_timelimit_suddendeath;
1627                         if(g_race && !g_race_qualifying)
1628                                 race_StartCompleting();
1629                 }
1630                 return 0;
1631         }
1632 }
1633
1634 void InitiateOvertime() // ONLY call this if InitiateSuddenDeath returned true
1635 {
1636         ++checkrules_overtimesadded;
1637         //add one more overtime by simply extending the timelimit
1638         float tl;
1639         tl = autocvar_timelimit;
1640         tl += autocvar_timelimit_overtime;
1641         cvar_set("timelimit", ftos(tl));
1642
1643         Send_Notification(NOTIF_ALL, world, MSG_CENTER, CENTER_OVERTIME_TIME, autocvar_timelimit_overtime * 60);
1644 }
1645
1646 float GetWinningCode(float fraglimitreached, float equality)
1647 {
1648         if(autocvar_g_campaign == 1)
1649                 if(fraglimitreached)
1650                         return WINNING_YES;
1651                 else
1652                         return WINNING_NO;
1653
1654         else
1655                 if(equality)
1656                         if(fraglimitreached)
1657                                 return WINNING_STARTSUDDENDEATHOVERTIME;
1658                         else
1659                                 return WINNING_NEVER;
1660                 else
1661                         if(fraglimitreached)
1662                                 return WINNING_YES;
1663                         else
1664                                 return WINNING_NO;
1665 }
1666
1667 // set the .winning flag for exactly those players with a given field value
1668 void SetWinners(.float field, float value)
1669 {
1670         entity head;
1671         FOR_EACH_PLAYER(head)
1672                 head.winning = (head.(field) == value);
1673 }
1674
1675 // set the .winning flag for those players with a given field value
1676 void AddWinners(.float field, float value)
1677 {
1678         entity head;
1679         FOR_EACH_PLAYER(head)
1680                 if (head.(field) == value)
1681                         head.winning = 1;
1682 }
1683
1684 // clear the .winning flags
1685 void ClearWinners(void)
1686 {
1687         entity head;
1688         FOR_EACH_PLAYER(head)
1689                 head.winning = 0;
1690 }
1691
1692 // Assault winning condition: If the attackers triggered a round end (by fulfilling all objectives)
1693 // they win. Otherwise the defending team wins once the timelimit passes.
1694 void assault_new_round();
1695 float WinningCondition_Assault()
1696 {
1697         float status;
1698
1699         WinningConditionHelper(); // set worldstatus
1700
1701         status = WINNING_NO;
1702         // as the timelimit has not yet passed just assume the defending team will win
1703         if(assault_attacker_team == NUM_TEAM_1)
1704         {
1705                 SetWinners(team, NUM_TEAM_2);
1706         }
1707         else
1708         {
1709                 SetWinners(team, NUM_TEAM_1);
1710         }
1711
1712         entity ent;
1713         ent = find(world, classname, "target_assault_roundend");
1714         if(ent)
1715         {
1716                 if(ent.winning) // round end has been triggered by attacking team
1717                 {
1718                         bprint("ASSAULT: round completed...\n");
1719                         SetWinners(team, assault_attacker_team);
1720
1721                         TeamScore_AddToTeam(assault_attacker_team, ST_ASSAULT_OBJECTIVES, 666 - TeamScore_AddToTeam(assault_attacker_team, ST_ASSAULT_OBJECTIVES, 0));
1722
1723                         if(ent.cnt == 1 || autocvar_g_campaign) // this was the second round
1724                         {
1725                                 status = WINNING_YES;
1726                         }
1727                         else
1728                         {
1729                                 entity oldself;
1730                                 oldself = self;
1731                                 self = ent;
1732                                 assault_new_round();
1733                                 self = oldself;
1734                         }
1735                 }
1736         }
1737
1738         return status;
1739 }
1740
1741 // LMS winning condition: game terminates if and only if there's at most one
1742 // one player who's living lives. Top two scores being equal cancels the time
1743 // limit.
1744 float WinningCondition_LMS()
1745 {
1746         entity head, head2;
1747         float have_player;
1748         float have_players;
1749         float l;
1750
1751         have_player = false;
1752         have_players = false;
1753         l = LMS_NewPlayerLives();
1754
1755         head = find(world, classname, "player");
1756         if(head)
1757                 have_player = true;
1758         head2 = find(head, classname, "player");
1759         if(head2)
1760                 have_players = true;
1761
1762         if(have_player)
1763         {
1764                 // we have at least one player
1765                 if(have_players)
1766                 {
1767                         // two or more active players - continue with the game
1768                 }
1769                 else
1770                 {
1771                         // exactly one player?
1772
1773                         ClearWinners();
1774                         SetWinners(winning, 0); // NOTE: exactly one player is still "player", so this works out
1775
1776                         if(l)
1777                         {
1778                                 // game still running (that is, nobody got removed from the game by a frag yet)? then continue
1779                                 return WINNING_NO;
1780                         }
1781                         else
1782                         {
1783                                 // a winner!
1784                                 // and assign him his first place
1785                                 PlayerScore_Add(head, SP_LMS_RANK, 1);
1786                                 return WINNING_YES;
1787                         }
1788                 }
1789         }
1790         else
1791         {
1792                 // nobody is playing at all...
1793                 if(l)
1794                 {
1795                         // wait for players...
1796                 }
1797                 else
1798                 {
1799                         // SNAFU (maybe a draw game?)
1800                         ClearWinners();
1801                         dprint("No players, ending game.\n");
1802                         return WINNING_YES;
1803                 }
1804         }
1805
1806         // When we get here, we have at least two players who are actually LIVING,
1807         // now check if the top two players have equal score.
1808         WinningConditionHelper();
1809
1810         ClearWinners();
1811         if(WinningConditionHelper_winner)
1812                 WinningConditionHelper_winner.winning = true;
1813         if(WinningConditionHelper_topscore == WinningConditionHelper_secondscore)
1814                 return WINNING_NEVER;
1815
1816         // Top two have different scores? Way to go for our beloved TIMELIMIT!
1817         return WINNING_NO;
1818 }
1819
1820 void ShuffleMaplist()
1821 {
1822         cvar_set("g_maplist", shufflewords(autocvar_g_maplist));
1823 }
1824
1825 float leaderfrags;
1826 float WinningCondition_Scores(float limit, float leadlimit)
1827 {
1828         float limitreached;
1829
1830         // TODO make everything use THIS winning condition (except LMS)
1831         WinningConditionHelper();
1832
1833         if(teamplay)
1834         {
1835                 team1_score = TeamScore_GetCompareValue(NUM_TEAM_1);
1836                 team2_score = TeamScore_GetCompareValue(NUM_TEAM_2);
1837                 team3_score = TeamScore_GetCompareValue(NUM_TEAM_3);
1838                 team4_score = TeamScore_GetCompareValue(NUM_TEAM_4);
1839         }
1840
1841         ClearWinners();
1842         if(WinningConditionHelper_winner)
1843                 WinningConditionHelper_winner.winning = 1;
1844         if(WinningConditionHelper_winnerteam >= 0)
1845                 SetWinners(team, WinningConditionHelper_winnerteam);
1846
1847         if(WinningConditionHelper_lowerisbetter)
1848         {
1849                 WinningConditionHelper_topscore = -WinningConditionHelper_topscore;
1850                 WinningConditionHelper_secondscore = -WinningConditionHelper_secondscore;
1851                 limit = -limit;
1852         }
1853
1854         if(WinningConditionHelper_zeroisworst)
1855                 leadlimit = 0; // not supported in this mode
1856
1857         if(g_dm || g_tdm || g_ca || g_freezetag || (g_race && !g_race_qualifying) || g_nexball)
1858         // these modes always score in increments of 1, thus this makes sense
1859         {
1860                 if(leaderfrags != WinningConditionHelper_topscore)
1861                 {
1862                         leaderfrags = WinningConditionHelper_topscore;
1863
1864                         if (limit)
1865                         if (leaderfrags == limit - 1)
1866                                 Send_Notification(NOTIF_ALL, world, MSG_ANNCE, ANNCE_REMAINING_FRAG_1);
1867                         else if (leaderfrags == limit - 2)
1868                                 Send_Notification(NOTIF_ALL, world, MSG_ANNCE, ANNCE_REMAINING_FRAG_2);
1869                         else if (leaderfrags == limit - 3)
1870                                 Send_Notification(NOTIF_ALL, world, MSG_ANNCE, ANNCE_REMAINING_FRAG_3);
1871                 }
1872         }
1873
1874         limitreached = false;
1875         if(limit)
1876                 if(WinningConditionHelper_topscore >= limit)
1877                         limitreached = true;
1878         if(leadlimit)
1879         {
1880                 float leadlimitreached;
1881                 leadlimitreached = (WinningConditionHelper_topscore - WinningConditionHelper_secondscore >= leadlimit);
1882                 if(autocvar_leadlimit_and_fraglimit)
1883                         limitreached = (limitreached && leadlimitreached);
1884                 else
1885                         limitreached = (limitreached || leadlimitreached);
1886         }
1887
1888         if(limit)
1889                 game_completion_ratio = max(game_completion_ratio, bound(0, WinningConditionHelper_topscore / limit, 1));
1890
1891         return GetWinningCode(
1892                 WinningConditionHelper_topscore && limitreached,
1893                 WinningConditionHelper_equality
1894         );
1895 }
1896
1897 float WinningCondition_Race(float fraglimit)
1898 {
1899         float wc;
1900         entity p;
1901         float n, c;
1902
1903         n = 0;
1904         c = 0;
1905         FOR_EACH_PLAYER(p)
1906         {
1907                 ++n;
1908                 if(p.race_completed)
1909                         ++c;
1910         }
1911         if(n && (n == c))
1912                 return WINNING_YES;
1913         wc = WinningCondition_Scores(fraglimit, 0);
1914
1915         // ALWAYS initiate overtime, unless EVERYONE has finished the race!
1916         if(wc == WINNING_YES || wc == WINNING_STARTSUDDENDEATHOVERTIME)
1917         // do NOT support equality when the laps are all raced!
1918                 return WINNING_STARTSUDDENDEATHOVERTIME;
1919         else
1920                 return WINNING_NEVER;
1921 }
1922
1923 float WinningCondition_QualifyingThenRace(float limit)
1924 {
1925         float wc;
1926         wc = WinningCondition_Scores(limit, 0);
1927
1928         // NEVER initiate overtime
1929         if(wc == WINNING_YES || wc == WINNING_STARTSUDDENDEATHOVERTIME)
1930         {
1931                 return WINNING_YES;
1932         }
1933
1934         return wc;
1935 }
1936
1937 float WinningCondition_RanOutOfSpawns()
1938 {
1939         entity head;
1940
1941         if(have_team_spawns <= 0)
1942                 return WINNING_NO;
1943
1944         if(!autocvar_g_spawn_useallspawns)
1945                 return WINNING_NO;
1946
1947         if(!some_spawn_has_been_used)
1948                 return WINNING_NO;
1949
1950         team1_score = team2_score = team3_score = team4_score = 0;
1951
1952         FOR_EACH_PLAYER(head) if(head.deadflag == DEAD_NO)
1953         {
1954                 if(head.team == NUM_TEAM_1)
1955                         team1_score = 1;
1956                 else if(head.team == NUM_TEAM_2)
1957                         team2_score = 1;
1958                 else if(head.team == NUM_TEAM_3)
1959                         team3_score = 1;
1960                 else if(head.team == NUM_TEAM_4)
1961                         team4_score = 1;
1962         }
1963
1964         for(head = world; (head = find(head, classname, "info_player_deathmatch")) != world; )
1965         {
1966                 if(head.team == NUM_TEAM_1)
1967                         team1_score = 1;
1968                 else if(head.team == NUM_TEAM_2)
1969                         team2_score = 1;
1970                 else if(head.team == NUM_TEAM_3)
1971                         team3_score = 1;
1972                 else if(head.team == NUM_TEAM_4)
1973                         team4_score = 1;
1974         }
1975
1976         ClearWinners();
1977         if(team1_score + team2_score + team3_score + team4_score == 0)
1978         {
1979                 checkrules_equality = true;
1980                 return WINNING_YES;
1981         }
1982         else if(team1_score + team2_score + team3_score + team4_score == 1)
1983         {
1984                 float t, i;
1985                 if(team1_score)
1986                         t = NUM_TEAM_1;
1987                 else if(team2_score)
1988                         t = NUM_TEAM_2;
1989                 else if(team3_score)
1990                         t = NUM_TEAM_3;
1991                 else // if(team4_score)
1992                         t = NUM_TEAM_4;
1993                 CheckAllowedTeams(world);
1994                 for(i = 0; i < MAX_TEAMSCORE; ++i)
1995                 {
1996                         if(t != NUM_TEAM_1) if(c1 >= 0) TeamScore_AddToTeam(NUM_TEAM_1, i, -1000);
1997                         if(t != NUM_TEAM_2) if(c2 >= 0) TeamScore_AddToTeam(NUM_TEAM_2, i, -1000);
1998                         if(t != NUM_TEAM_3) if(c3 >= 0) TeamScore_AddToTeam(NUM_TEAM_3, i, -1000);
1999                         if(t != NUM_TEAM_4) if(c4 >= 0) TeamScore_AddToTeam(NUM_TEAM_4, i, -1000);
2000                 }
2001
2002                 AddWinners(team, t);
2003                 return WINNING_YES;
2004         }
2005         else
2006                 return WINNING_NO;
2007 }
2008
2009 /*
2010 ============
2011 CheckRules_World
2012
2013 Exit deathmatch games upon conditions
2014 ============
2015 */
2016 void CheckRules_World()
2017 {
2018         float timelimit;
2019         float fraglimit;
2020         float leadlimit;
2021
2022         VoteThink();
2023         MapVote_Think();
2024
2025         SetDefaultAlpha();
2026
2027         if (gameover)   // someone else quit the game already
2028         {
2029                 if(player_count == 0) // Nobody there? Then let's go to the next map
2030                         MapVote_Start();
2031                         // this will actually check the player count in the next frame
2032                         // again, but this shouldn't hurt
2033                 return;
2034         }
2035
2036         timelimit = autocvar_timelimit * 60;
2037         fraglimit = autocvar_fraglimit;
2038         leadlimit = autocvar_leadlimit;
2039
2040         if(warmup_stage || time <= game_starttime) // NOTE: this is <= to prevent problems in the very tic where the game starts
2041         {
2042                 if(timelimit > 0)
2043                         timelimit = 0; // timelimit is not made for warmup
2044                 if(fraglimit > 0)
2045                         fraglimit = 0; // no fraglimit for now
2046                 leadlimit = 0; // no leadlimit for now
2047         }
2048
2049         if(timelimit > 0)
2050         {
2051                 timelimit += game_starttime;
2052         }
2053         else if (timelimit < 0)
2054         {
2055                 // endmatch
2056                 NextLevel();
2057                 return;
2058         }
2059
2060         float wantovertime;
2061         wantovertime = 0;
2062
2063         if(timelimit > game_starttime)
2064                 game_completion_ratio = (time - game_starttime) / (timelimit - game_starttime);
2065         else
2066                 game_completion_ratio = 0;
2067
2068         if(checkrules_suddendeathend)
2069         {
2070                 if(!checkrules_suddendeathwarning)
2071                 {
2072                         checkrules_suddendeathwarning = true;
2073                         if(g_race && !g_race_qualifying)
2074                                 Send_Notification(NOTIF_ALL, world, MSG_CENTER, CENTER_RACE_FINISHLAP);
2075                         else
2076                                 Send_Notification(NOTIF_ALL, world, MSG_CENTER, CENTER_OVERTIME_FRAG);
2077                 }
2078         }
2079         else
2080         {
2081                 if (timelimit && time >= timelimit)
2082                 {
2083                         if(g_race && (g_race_qualifying == 2) && timelimit > 0)
2084                         {
2085                                 float totalplayers;
2086                                 float playerswithlaps;
2087                                 float readyplayers;
2088                                 entity head;
2089                                 totalplayers = playerswithlaps = readyplayers = 0;
2090                                 FOR_EACH_PLAYER(head)
2091                                 {
2092                                         ++totalplayers;
2093                                         if(PlayerScore_Add(head, SP_RACE_FASTEST, 0))
2094                                                 ++playerswithlaps;
2095                                         if(head.ready)
2096                                                 ++readyplayers;
2097                                 }
2098
2099                                 // at least 2 of the players have completed a lap: start the RACE
2100                                 // otherwise, the players should end the qualifying on their own
2101                                 if(readyplayers || playerswithlaps >= 2)
2102                                 {
2103                                         checkrules_suddendeathend = 0;
2104                                         ReadyRestart(); // go to race
2105                                         return;
2106                                 }
2107                                 else
2108                                         wantovertime |= InitiateSuddenDeath();
2109                         }
2110                         else
2111                                 wantovertime |= InitiateSuddenDeath();
2112                 }
2113         }
2114
2115         if (checkrules_suddendeathend && time >= checkrules_suddendeathend)
2116         {
2117                 NextLevel();
2118                 return;
2119         }
2120
2121         float checkrules_status;
2122         checkrules_status = WinningCondition_RanOutOfSpawns();
2123         if(checkrules_status == WINNING_YES)
2124         {
2125                 bprint("Hey! Someone ran out of spawns!\n");
2126         }
2127         else if(g_race && !g_race_qualifying && timelimit >= 0)
2128         {
2129                 checkrules_status = WinningCondition_Race(fraglimit);
2130                 //print("WC_RACE yields ", ftos(checkrules_status), "\n");
2131         }
2132         else if(g_race && g_race_qualifying == 2 && timelimit >= 0)
2133         {
2134                 checkrules_status = WinningCondition_QualifyingThenRace(fraglimit);
2135                 //print("WC_QUALIFYING_THEN_RACE yields ", ftos(checkrules_status), "\n");
2136         }
2137         else if(g_assault)
2138         {
2139                 checkrules_status = WinningCondition_Assault(); // TODO remove this?
2140         }
2141         else if(g_lms)
2142         {
2143                 checkrules_status = WinningCondition_LMS();
2144         }
2145         else
2146         {
2147                 checkrules_status = WinningCondition_Scores(fraglimit, leadlimit);
2148                 //print("WC_SCORES yields ", ftos(checkrules_status), "\n");
2149         }
2150
2151         if(checkrules_status == WINNING_STARTSUDDENDEATHOVERTIME)
2152         {
2153                 checkrules_status = WINNING_NEVER;
2154                 checkrules_overtimesadded = -1;
2155                 wantovertime |= InitiateSuddenDeath();
2156         }
2157
2158         if(checkrules_status == WINNING_NEVER)
2159                 // equality cases! Nobody wins if the overtime ends in a draw.
2160                 ClearWinners();
2161
2162         if(wantovertime)
2163         {
2164                 if(checkrules_status == WINNING_NEVER)
2165                         InitiateOvertime();
2166                 else
2167                         checkrules_status = WINNING_YES;
2168         }
2169
2170         if(checkrules_suddendeathend)
2171                 if(checkrules_status != WINNING_NEVER || time >= checkrules_suddendeathend)
2172                         checkrules_status = WINNING_YES;
2173
2174         if(checkrules_status == WINNING_YES)
2175         {
2176                 //print("WINNING\n");
2177                 NextLevel();
2178         }
2179 }
2180
2181 string GotoMap(string m)
2182 {
2183         m = GameTypeVote_MapInfo_FixName(m);
2184         if (!m)
2185                 return "The map you suggested is not available on this server.";
2186         if (!autocvar_sv_vote_gametype)
2187         if(!MapInfo_CheckMap(m))
2188                 return "The map you suggested does not support the current game mode.";
2189         cvar_set("nextmap", m);
2190         cvar_set("timelimit", "-1");
2191         if(mapvote_initialized || alreadychangedlevel)
2192         {
2193                 if(DoNextMapOverride(0))
2194                         return "Map switch initiated.";
2195                 else
2196                         return "Hm... no. For some reason I like THIS map more.";
2197         }
2198         else
2199                 return "Map switch will happen after scoreboard.";
2200 }
2201
2202
2203 void EndFrame()
2204 {
2205         anticheat_endframe();
2206
2207         float altime;
2208         FOR_EACH_REALCLIENT(self)
2209         {
2210                 entity e = IS_SPEC(self) ? self.enemy : self;
2211                 if(e.typehitsound)
2212                         self.typehit_time = time;
2213                 else if(e.damage_dealt)
2214                 {
2215                         self.hit_time = time;
2216                         self.damage_dealt_total += ceil(e.damage_dealt);
2217                 }
2218         }
2219         altime = time + frametime * (1 + autocvar_g_antilag_nudge);
2220         // add 1 frametime because after this, engine SV_Physics
2221         // increases time by a frametime and then networks the frame
2222         // add another frametime because client shows everything with
2223         // 1 frame of lag (cl_nolerp 0). The last +1 however should not be
2224         // needed!
2225         FOR_EACH_CLIENT(self)
2226         {
2227                 self.typehitsound = false;
2228                 self.damage_dealt = 0;
2229                 antilag_record(self, altime);
2230         }
2231         FOR_EACH_MONSTER(self)
2232                 antilag_record(self, altime);
2233 }
2234
2235
2236 /*
2237  * RedirectionThink:
2238  * returns true if redirecting
2239  */
2240 float redirection_timeout;
2241 float redirection_nextthink;
2242 float RedirectionThink()
2243 {
2244         float clients_found;
2245
2246         if(redirection_target == "")
2247                 return false;
2248
2249         if(!redirection_timeout)
2250         {
2251                 cvar_set("sv_public", "-2");
2252                 redirection_timeout = time + 0.6; // this will only try twice... should be able to keep more clients
2253                 if(redirection_target == "self")
2254                         bprint("^3SERVER NOTICE:^7 restarting the server\n");
2255                 else
2256                         bprint("^3SERVER NOTICE:^7 redirecting everyone to ", redirection_target, "\n");
2257         }
2258
2259         if(time < redirection_nextthink)
2260                 return true;
2261
2262         redirection_nextthink = time + 1;
2263
2264         clients_found = 0;
2265         FOR_EACH_REALCLIENT(self)
2266         {
2267                 // TODO add timer
2268                 print("Redirecting: sending connect command to ", self.netname, "\n");
2269                 if(redirection_target == "self")
2270                         stuffcmd(self, "\ndisconnect; defer ", ftos(autocvar_quit_and_redirect_timer), " reconnect\n");
2271                 else
2272                         stuffcmd(self, strcat("\ndisconnect; defer ", ftos(autocvar_quit_and_redirect_timer), " \"connect ", redirection_target, "\"\n"));
2273                 ++clients_found;
2274         }
2275
2276         print("Redirecting: ", ftos(clients_found), " clients left.\n");
2277
2278         if(time > redirection_timeout || clients_found == 0)
2279                 localcmd("\nwait; wait; wait; quit\n");
2280
2281         return true;
2282 }
2283
2284 void TargetMusic_RestoreGame();
2285 void RestoreGame()
2286 {
2287         // Loaded from a save game
2288         // some things then break, so let's work around them...
2289
2290         // Progs DB (capture records)
2291         ServerProgsDB = db_load(strcat("server.db", autocvar_sessionid));
2292
2293         // Mapinfo
2294         MapInfo_Shutdown();
2295         MapInfo_Enumerate();
2296         MapInfo_FilterGametype(MapInfo_CurrentGametype(), MapInfo_CurrentFeatures(), MapInfo_RequiredFlags(), MapInfo_ForbiddenFlags(), 1);
2297         WeaponStats_Init();
2298
2299         TargetMusic_RestoreGame();
2300 }
2301
2302 void Shutdown()
2303 {
2304         gameover = 2;
2305
2306         if(world_initialized > 0)
2307         {
2308                 world_initialized = 0;
2309                 print("Saving persistent data...\n");
2310                 Ban_SaveBans();
2311
2312                 // playerstats with unfinished match
2313                 PlayerStats_GameReport(false);
2314
2315                 if(!cheatcount_total)
2316                 {
2317                         if(autocvar_sv_db_saveasdump)
2318                                 db_dump(ServerProgsDB, strcat("server.db", autocvar_sessionid));
2319                         else
2320                                 db_save(ServerProgsDB, strcat("server.db", autocvar_sessionid));
2321                 }
2322                 if(autocvar_developer)
2323                 {
2324                         if(autocvar_sv_db_saveasdump)
2325                                 db_dump(TemporaryDB, "server-temp.db");
2326                         else
2327                                 db_save(TemporaryDB, "server-temp.db");
2328                 }
2329                 CheatShutdown(); // must be after cheatcount check
2330                 db_close(ServerProgsDB);
2331                 db_close(TemporaryDB);
2332                 print("done!\n");
2333                 // tell the bot system the game is ending now
2334                 bot_endgame();
2335
2336                 WeaponStats_Shutdown();
2337                 MapInfo_Shutdown();
2338         }
2339         else if(world_initialized == 0)
2340         {
2341                 print("NOTE: crashed before even initializing the world, not saving persistent data\n");
2342         }
2343 }