]> de.git.xonotic.org Git - xonotic/xonotic-data.pk3dir.git/blob - qcsrc/server/g_world.qc
Remove runematch gamemode
[xonotic/xonotic-data.pk3dir.git] / qcsrc / server / g_world.qc
1 #define LATENCY_THINKRATE 10
2 .float latency_sum;
3 .float latency_cnt;
4 .float latency_time;
5 entity pingplreport;
6 void PingPLReport_Think()
7 {
8         float delta;
9         entity e;
10
11         delta = 3 / maxclients;
12         if(delta < sys_frametime)
13                 delta = 0;
14         self.nextthink = time + delta;
15
16         e = edict_num(self.cnt + 1);
17         if(clienttype(e) == CLIENTTYPE_REAL)
18         {
19                 WriteByte(MSG_BROADCAST, SVC_TEMPENTITY);
20                 WriteByte(MSG_BROADCAST, TE_CSQC_PINGPLREPORT);
21                 WriteByte(MSG_BROADCAST, self.cnt);
22                 WriteShort(MSG_BROADCAST, max(1, e.ping));
23                 WriteByte(MSG_BROADCAST, ceil(e.ping_packetloss * 255));
24                 WriteByte(MSG_BROADCAST, ceil(e.ping_movementloss * 255));
25
26                 // record latency times for clients throughout the match so we can report it to playerstats
27                 if(time > (e.latency_time + LATENCY_THINKRATE))
28                 {
29                         e.latency_sum += e.ping;
30                         e.latency_cnt += 1;
31                         e.latency_time = time;
32                         //print("sum: ", ftos(e.latency_sum), ", cnt: ", ftos(e.latency_cnt), ", avg: ", ftos(e.latency_sum / e.latency_cnt), ".\n");
33                 }
34         }
35         else
36         {
37                 WriteByte(MSG_BROADCAST, SVC_TEMPENTITY);
38                 WriteByte(MSG_BROADCAST, TE_CSQC_PINGPLREPORT);
39                 WriteByte(MSG_BROADCAST, self.cnt);
40                 WriteShort(MSG_BROADCAST, 0);
41                 WriteByte(MSG_BROADCAST, 0);
42                 WriteByte(MSG_BROADCAST, 0);
43         }
44         self.cnt = mod(self.cnt + 1, maxclients);
45 }
46 void PingPLReport_Spawn()
47 {
48         pingplreport = spawn();
49         pingplreport.classname = "pingplreport";
50         pingplreport.think = PingPLReport_Think;
51         pingplreport.nextthink = time;
52 }
53
54 float SPAWNFLAG_NO_WAYPOINTS_FOR_ITEMS = 1;
55 string redirection_target;
56 float world_initialized;
57
58 string GetMapname();
59 string GetGametype();
60 void GotoNextMap(float reinit);
61 void ShuffleMaplist();
62 float(float reinit) DoNextMapOverride;
63
64 void SetDefaultAlpha()
65 {
66         if(autocvar_g_running_guns)
67         {
68                 default_player_alpha = -1;
69                 default_weapon_alpha = +1;
70         }
71         else if(g_cloaked)
72         {
73                 default_player_alpha = autocvar_g_balance_cloaked_alpha;
74                 default_weapon_alpha = default_player_alpha;
75         }
76         else
77         {
78                 default_player_alpha = autocvar_g_player_alpha;
79                 if(default_player_alpha == 0)
80                         default_player_alpha = 1;
81                 default_weapon_alpha = default_player_alpha;
82         }
83 }
84
85 void fteqcc_testbugs()
86 {
87         float a, b;
88
89         if(!autocvar_developer_fteqccbugs)
90                 return;
91
92         dprint("*** fteqcc test: checking for bugs...\n");
93
94         a = 1;
95         b = 5;
96         if(sqrt(a) - sqrt(b - a) == 0)
97                 dprint("*** fteqcc test: found same-function-twice bug\n");
98         else
99                 dprint("*** fteqcc test: same-function-twice bug got FINALLY FIXED! HOORAY!\n");
100
101         world.cnt = -10;
102         world.enemy = world;
103         world.enemy.cnt += 10;
104         if(world.cnt > 0.2 || world.cnt < -0.2) // don't error out if it's just roundoff errors
105                 dprint("*** fteqcc test: found += bug\n");
106         else
107                 dprint("*** fteqcc test: += bug got FINALLY FIXED! HOORAY!\n");
108         world.cnt = 0;
109 }
110
111 void GotoFirstMap()
112 {
113         float n;
114         if(autocvar__sv_init)
115         {
116                 // cvar_set("_sv_init", "0");
117                 // we do NOT set this to 0 any more, so someone "accidentally" changing
118                 // to this "init" map on a dedicated server will cause no permanent
119                 // harm
120                 if(autocvar_g_maplist_shuffle)
121                         ShuffleMaplist();
122                 n = tokenizebyseparator(autocvar_g_maplist, " ");
123                 cvar_set("g_maplist_index", ftos(n - 1)); // jump to map 0 in GotoNextMap
124
125                 MapInfo_Enumerate();
126                 MapInfo_FilterGametype(MapInfo_CurrentGametype(), MapInfo_CurrentFeatures(), MapInfo_RequiredFlags(), MapInfo_ForbiddenFlags(), 0);
127
128                 if(!DoNextMapOverride(1))
129                         GotoNextMap(1);
130
131                 return;
132         }
133
134         if(time < 5)
135         {
136                 self.nextthink = time;
137         }
138         else
139         {
140                 self.nextthink = time + 1;
141                 print("Waiting for _sv_init being set to 1 by initialization scripts...\n");
142         }
143 }
144
145 void cvar_changes_init()
146 {
147         float h;
148         string k, v, d;
149         float n, i, adding, pureadding;
150
151         if(cvar_changes)
152                 strunzone(cvar_changes);
153         cvar_changes = string_null;
154         if(cvar_purechanges)
155                 strunzone(cvar_purechanges);
156         cvar_purechanges = string_null;
157         cvar_purechanges_count = 0;
158
159         h = buf_create();
160         buf_cvarlist(h, "", "_"); // exclude all _ cvars as they are temporary
161         n = buf_getsize(h);
162
163         adding = TRUE;
164         pureadding = TRUE;
165
166         for(i = 0; i < n; ++i)
167         {
168                 k = bufstr_get(h, i);
169
170 #define BADPREFIX(p) if(substring(k, 0, strlen(p)) == p) continue
171 #define BADPRESUFFIX(p,s) if(substring(k, 0, strlen(p)) == p && substring(k, -strlen(s), -1) == s) continue
172 #define BADCVAR(p) if(k == p) continue
173
174                 // general excludes and namespaces for server admin used cvars
175                 BADPREFIX("help_"); // PN's server has this listed as changed, let's not rat him out for THAT
176
177                 // internal
178                 BADPREFIX("csqc_");
179                 BADPREFIX("cvar_check_");
180                 BADCVAR("gamecfg");
181                 BADCVAR("g_configversion");
182                 BADCVAR("g_maplist_index");
183                 BADCVAR("halflifebsp");
184                 BADPREFIX("sv_world");
185
186                 // client
187                 BADPREFIX("chase_");
188                 BADPREFIX("cl_");
189                 BADPREFIX("con_");
190                 BADPREFIX("scoreboard_");
191                 BADPREFIX("g_campaign");
192                 BADPREFIX("g_waypointsprite_");
193                 BADPREFIX("gl_");
194                 BADPREFIX("joy");
195                 BADPREFIX("hud_");
196                 BADPREFIX("m_");
197                 BADPREFIX("menu_");
198                 BADPREFIX("net_slist_");
199                 BADPREFIX("r_");
200                 BADPREFIX("sbar_");
201                 BADPREFIX("scr_");
202                 BADPREFIX("snd_");
203                 BADPREFIX("show");
204                 BADPREFIX("sensitivity");
205                 BADPREFIX("userbind");
206                 BADPREFIX("v_");
207                 BADPREFIX("vid_");
208                 BADPREFIX("crosshair");
209                 BADCVAR("mod_q3bsp_lightmapmergepower");
210                 BADCVAR("mod_q3bsp_nolightmaps");
211                 BADCVAR("fov");
212                 BADCVAR("mastervolume");
213                 BADCVAR("volume");
214                 BADCVAR("bgmvolume");
215
216                 // private
217                 BADCVAR("developer");
218                 BADCVAR("log_dest_udp");
219                 BADCVAR("log_file");
220                 BADCVAR("net_address");
221                 BADCVAR("net_address_ipv6");
222                 BADCVAR("port");
223                 BADCVAR("savedgamecfg");
224                 BADCVAR("serverconfig");
225                 BADCVAR("sv_autoscreenshot");
226                 BADCVAR("sv_heartbeatperiod");
227                 BADCVAR("sv_vote_master_password");
228                 BADCVAR("sys_colortranslation");
229                 BADCVAR("sys_specialcharactertranslation");
230                 BADCVAR("timeformat");
231                 BADCVAR("timestamps");
232                 BADPREFIX("developer_");
233                 BADPREFIX("g_ban_");
234                 BADPREFIX("g_banned_list");
235                 BADPREFIX("g_chat_flood_");
236                 BADPREFIX("g_ghost_items");
237                 BADPREFIX("g_playerstats_");
238                 BADPREFIX("g_respawn_ghosts");
239                 BADPREFIX("g_voice_flood_");
240                 BADPREFIX("rcon_");
241                 BADPREFIX("sv_allowdownloads");
242                 BADPREFIX("sv_autodemo");
243                 BADPREFIX("sv_curl_");
244                 BADPREFIX("sv_eventlog");
245                 BADPREFIX("sv_logscores_");
246                 BADPREFIX("sv_master");
247                 BADPREFIX("sv_weaponstats_");
248                 BADPREFIX("sv_waypointsprite_");
249                 BADCVAR("rescan_pending");
250
251                 // these can contain player IDs, so better hide
252                 BADPREFIX("g_forced_team_");
253
254                 // mapinfo
255                 BADCVAR("fraglimit");
256                 BADCVAR("g_arena");
257                 BADCVAR("g_assault");
258                 BADCVAR("g_ca");
259                 BADCVAR("g_ctf");
260                 BADCVAR("g_cts");
261                 BADCVAR("g_dm");
262                 BADCVAR("g_domination");
263                 BADCVAR("g_domination_default_teams");
264                 BADCVAR("g_freezetag");
265                 BADCVAR("g_keepaway");
266                 BADCVAR("g_keyhunt");
267                 BADCVAR("g_keyhunt_teams");
268                 BADCVAR("g_keyhunt_teams");
269                 BADCVAR("g_lms");
270                 BADCVAR("g_nexball");
271                 BADCVAR("g_onslaught");
272                 BADCVAR("g_race");
273                 BADCVAR("g_race_qualifying_timelimit");
274                 BADCVAR("g_tdm");
275                 BADCVAR("g_tdm_teams");
276                 BADCVAR("leadlimit");
277                 BADCVAR("nextmap");
278                 BADCVAR("teamplay");
279                 BADCVAR("timelimit");
280
281                 // long
282                 BADCVAR("hostname");
283                 BADCVAR("g_maplist");
284                 BADCVAR("g_maplist_mostrecent");
285                 BADCVAR("sv_motd");
286
287                 v = cvar_string(k);
288                 d = cvar_defstring(k);
289                 if(v == d)
290                         continue;
291
292                 if(adding)
293                 {
294                         cvar_changes = strcat(cvar_changes, k, " \"", v, "\" // \"", d, "\"\n");
295                         if(strlen(cvar_changes) > 16384)
296                         {
297                                 cvar_changes = "// too many settings have been changed to show them here\n";
298                                 adding = 0;
299                         }
300                 }
301
302                 // now check if the changes are actually gameplay relevant
303
304                 // does nothing visible
305                 BADCVAR("captureleadlimit_override");
306                 BADCVAR("g_arena_point_leadlimit");
307                 BADCVAR("g_balance_kill_delay");
308                 BADCVAR("g_ca_point_leadlimit");
309                 BADCVAR("g_ctf_captimerecord_always");
310                 BADCVAR("g_ctf_flag_glowtrails");
311                 BADCVAR("g_ctf_flag_pickup_verbosename");
312                 BADCVAR("g_domination_point_leadlimit");
313                 BADCVAR("g_forced_respawn");
314                 BADCVAR("g_keyhunt_point_leadlimit");
315                 BADPREFIX("g_mod_");
316                 BADCVAR("g_nexball_goalleadlimit");
317                 BADCVAR("leadlimit_and_fraglimit");
318                 BADCVAR("leadlimit_override");
319                 BADCVAR("pausable");
320                 BADCVAR("sv_allow_fullbright");
321                 BADCVAR("sv_checkforpacketsduringsleep");
322                 BADCVAR("sv_fraginfo");
323                 BADCVAR("sv_timeout");
324                 BADPREFIX("sv_timeout_");
325                 BADCVAR("welcome_message_time");
326                 BADPREFIX("crypto_");
327                 BADPREFIX("g_chat_");
328                 BADPREFIX("g_ctf_captimerecord_");
329                 BADPREFIX("g_maplist_votable_");
330                 BADPREFIX("net_");
331                 BADPREFIX("prvm_");
332                 BADPREFIX("skill_");
333                 BADPREFIX("sv_cullentities_");
334                 BADPREFIX("sv_fraginfo_");
335                 BADPREFIX("sv_maxidle_");
336                 BADPREFIX("sv_vote_");
337                 BADPREFIX("timelimit_");
338                 BADCVAR("gameversion");
339                 BADPREFIX("gameversion_");
340                 BADCVAR("sv_namechangetimer");
341
342                 // allowed changes to server admins (please sync this to server.cfg)
343                 // vi commands:
344                 //   :/"impure"/,$d
345                 //   :g!,^\/\/[^ /],d
346                 //   :%s,//\([^ ]*\).*,BADCVAR("\1");,
347                 //   :%!sort
348                 // yes, this does contain some redundant stuff, don't really care
349                 BADCVAR("bot_config_file");
350                 BADCVAR("bot_number");
351                 BADCVAR("bot_prefix");
352                 BADCVAR("bot_suffix");
353                 BADCVAR("capturelimit_override");
354                 BADCVAR("fraglimit_override");
355                 BADCVAR("gametype");
356                 BADCVAR("g_antilag");
357                 BADCVAR("g_balance_teams");
358                 BADCVAR("g_balance_teams_prevent_imbalance");
359                 BADCVAR("g_balance_teams_scorefactor");
360                 BADCVAR("g_ban_sync_trusted_servers");
361                 BADCVAR("g_ban_sync_uri");
362                 BADCVAR("g_ctf_ignore_frags");
363                 BADCVAR("g_domination_point_limit");
364                 BADCVAR("g_friendlyfire");
365                 BADCVAR("g_fullbrightitems");
366                 BADCVAR("g_fullbrightplayers");
367                 BADCVAR("g_keyhunt_point_limit");
368                 BADCVAR("g_keyhunt_teams_override");
369                 BADCVAR("g_lms_lives_override");
370                 BADCVAR("g_maplist");
371                 BADCVAR("g_maplist_check_waypoints");
372                 BADCVAR("g_maplist_mostrecent_count");
373                 BADCVAR("g_maplist_shuffle");
374                 BADCVAR("g_maplist_votable");
375                 BADCVAR("g_maplist_votable_abstain");
376                 BADCVAR("g_maplist_votable_nodetail");
377                 BADCVAR("g_maplist_votable_suggestions");
378                 BADCVAR("g_maxplayers");
379                 BADCVAR("g_mirrordamage");
380                 BADCVAR("g_nexball_goallimit");
381                 BADCVAR("g_powerups");
382                 BADCVAR("g_start_delay");
383                 BADCVAR("g_warmup");
384                 BADCVAR("g_weapon_stay"); BADPRESUFFIX("g_", "_weapon_stay");
385                 BADCVAR("hostname");
386                 BADCVAR("log_file");
387                 BADCVAR("maxplayers");
388                 BADCVAR("minplayers");
389                 BADCVAR("net_address");
390                 BADCVAR("port");
391                 BADCVAR("rcon_password");
392                 BADCVAR("rcon_restricted_commands");
393                 BADCVAR("rcon_restricted_password");
394                 BADCVAR("skill");
395                 BADCVAR("sv_adminnick");
396                 BADCVAR("sv_autoscreenshot");
397                 BADCVAR("sv_autotaunt");
398                 BADCVAR("sv_curl_defaulturl");
399                 BADCVAR("sv_defaultcharacter");
400                 BADCVAR("sv_defaultplayercolors");
401                 BADCVAR("sv_defaultplayermodel");
402                 BADCVAR("sv_defaultplayerskin");
403                 BADCVAR("sv_maxidle");
404                 BADCVAR("sv_maxrate");
405                 BADCVAR("sv_motd");
406                 BADCVAR("sv_public");
407                 BADCVAR("sv_ready_restart");
408                 BADCVAR("sv_status_privacy");
409                 BADCVAR("sv_taunt");
410                 BADCVAR("sv_vote_call");
411                 BADCVAR("sv_vote_commands");
412                 BADCVAR("sv_vote_majority_factor");
413                 BADCVAR("sv_vote_master");
414                 BADCVAR("sv_vote_master_commands");
415                 BADCVAR("sv_vote_master_password");
416                 BADCVAR("sv_vote_simple_majority_factor");
417                 BADCVAR("sys_ticrate");
418                 BADCVAR("teamplay_mode");
419                 BADCVAR("timelimit_override");
420                 BADCVAR("g_spawnshieldtime");
421                 BADPREFIX("g_warmup_");
422                 BADPREFIX("sv_ready_restart_");
423
424                 // mutators that announce themselves properly to the server browser
425                 BADCVAR("g_minstagib");
426                 BADCVAR("g_new_toys");
427                 BADCVAR("g_nix");
428
429                 if(autocvar_g_minstagib)
430                 {
431                         BADCVAR("g_grappling_hook");
432                         BADCVAR("g_jetpack");
433                 }
434 #undef BADPREFIX
435 #undef BADCVAR
436
437                 if(pureadding)
438                 {
439                         cvar_purechanges = strcat(cvar_purechanges, k, " \"", v, "\" // \"", d, "\"\n");
440                         if(strlen(cvar_purechanges) > 16384)
441                         {
442                                 cvar_purechanges = "// too many settings have been changed to show them here\n";
443                                 pureadding = 0;
444                         }
445                 }
446                 ++cvar_purechanges_count;
447                 // WARNING: this variable is used for the server list
448                 // NEVER dare to skip this code!
449                 // Hacks to intentionally appearing as "pure server" even though you DO have
450                 // modified settings may be punished by removal from the server list.
451                 // You can do to the variables cvar_changes and cvar_purechanges all you want,
452                 // though.
453         }
454         buf_del(h);
455         if(cvar_changes == "")
456                 cvar_changes = "// this server runs at default server settings\n";
457         else
458                 cvar_changes = strcat("// this server runs at modified server settings:\n", cvar_changes);
459         cvar_changes = strzone(cvar_changes);
460         if(cvar_purechanges == "")
461                 cvar_purechanges = "// this server runs at default gameplay settings\n";
462         else
463                 cvar_purechanges = strcat("// this server runs at modified gameplay settings:\n", cvar_purechanges);
464         cvar_purechanges = strzone(cvar_purechanges);
465 }
466
467 void detect_maptype()
468 {
469 #if 0
470         vector o, v;
471         float i;
472
473         for(;;)
474         {
475                 o = world.mins;
476                 o_x += random() * (world.maxs_x - world.mins_x);
477                 o_y += random() * (world.maxs_y - world.mins_y);
478                 o_z += random() * (world.maxs_z - world.mins_z);
479
480                 tracebox(o, PL_MIN, PL_MAX, o - '0 0 32768', MOVE_WORLDONLY, world);
481                 if(trace_fraction == 1)
482                         continue;
483
484                 v = trace_endpos;
485
486                 for(i = 0; i < 64; i += 4)
487                 {
488                         tracebox(o, '-1 -1 -1' * i, '1 1 1' * i, o - '0 0 32768', MOVE_WORLDONLY, world);
489         if(trace_fraction == 1)
490                 continue;
491                         print(ftos(i), " -> ", vtos(trace_endpos), "\n");
492                 }
493
494                 break;
495         }
496 #endif
497 }
498
499 entity randomseed;
500 float RandomSeed_Send(entity to, float sf)
501 {
502         WriteByte(MSG_ENTITY, ENT_CLIENT_RANDOMSEED);
503         WriteShort(MSG_ENTITY, self.cnt);
504         return TRUE;
505 }
506 void RandomSeed_Think()
507 {
508         self.cnt = bound(0, floor(random() * 65536), 65535);
509         self.nextthink = time + 5;
510
511         self.SendFlags |= 1;
512 }
513 void RandomSeed_Spawn()
514 {
515         randomseed = spawn();
516         randomseed.think = RandomSeed_Think;
517         Net_LinkEntity(randomseed, FALSE, 0, RandomSeed_Send);
518
519         entity oldself;
520         oldself = self;
521         self = randomseed;
522         self.think(); // sets random seed and nextthink
523         self = oldself;
524 }
525
526 void spawnfunc___init_dedicated_server(void)
527 {
528         // handler for _init/_init map (only for dedicated server initialization)
529
530         world_initialized = -1; // don't complain
531         cvar = cvar_normal;
532         cvar_string = cvar_string_normal;
533         cvar_set = cvar_set_normal;
534
535         remove = remove_unsafely;
536
537         entity e;
538         e = spawn();
539         e.think = GotoFirstMap;
540         e.nextthink = time; // this is usually 1 at this point
541
542         e = spawn();
543         e.classname = "info_player_deathmatch"; // safeguard against player joining
544
545         self.classname = "worldspawn"; // safeguard against various stuff ;)
546
547         // needs to be done so early because of the constants they create
548         CALL_ACCUMULATED_FUNCTION(RegisterWeapons);
549         CALL_ACCUMULATED_FUNCTION(RegisterGametypes);
550
551         MapInfo_Enumerate();
552         MapInfo_FilterGametype(MapInfo_CurrentGametype(), MapInfo_CurrentFeatures(), MapInfo_RequiredFlags(), MapInfo_ForbiddenFlags(), 0);
553 }
554
555 void Map_MarkAsRecent(string m);
556 float world_already_spawned;
557 void Nagger_Init();
558 void ClientInit_Spawn();
559 void WeaponStats_Init();
560 void WeaponStats_Shutdown();
561 void spawnfunc_worldspawn (void)
562 {
563         float fd, l, i, j, n;
564         string s, col;
565
566         cvar = cvar_normal;
567         cvar_string = cvar_string_normal;
568         cvar_set = cvar_set_normal;
569
570         if(world_already_spawned)
571                 error("world already spawned - you may have EXACTLY ONE worldspawn!");
572         world_already_spawned = TRUE;
573
574         remove = remove_safely; // during spawning, watch what you remove!
575
576         check_unacceptable_compiler_bugs();
577
578         cvar_changes_init(); // do this very early now so it REALLY matches the server config
579
580         compressShortVector_init();
581
582         allowed_to_spawn = TRUE;
583
584         entity head;
585         head = nextent(world);
586         maxclients = 0;
587         while(head)
588         {
589                 ++maxclients;
590                 head = nextent(head);
591         }
592
593         // needs to be done so early because of the constants they create
594         CALL_ACCUMULATED_FUNCTION(RegisterWeapons);
595         CALL_ACCUMULATED_FUNCTION(RegisterGametypes);
596
597         ServerProgsDB = db_load(strcat("server.db", autocvar_sessionid));
598
599         TemporaryDB = db_create();
600
601         // 0 normal
602         lightstyle(0, "m");
603
604         // 1 FLICKER (first variety)
605         lightstyle(1, "mmnmmommommnonmmonqnmmo");
606
607         // 2 SLOW STRONG PULSE
608         lightstyle(2, "abcdefghijklmnopqrstuvwxyzyxwvutsrqponmlkjihgfedcba");
609
610         // 3 CANDLE (first variety)
611         lightstyle(3, "mmmmmaaaaammmmmaaaaaabcdefgabcdefg");
612
613         // 4 FAST STROBE
614         lightstyle(4, "mamamamamama");
615
616         // 5 GENTLE PULSE 1
617         lightstyle(5,"jklmnopqrstuvwxyzyxwvutsrqponmlkj");
618
619         // 6 FLICKER (second variety)
620         lightstyle(6, "nmonqnmomnmomomno");
621
622         // 7 CANDLE (second variety)
623         lightstyle(7, "mmmaaaabcdefgmmmmaaaammmaamm");
624
625         // 8 CANDLE (third variety)
626         lightstyle(8, "mmmaaammmaaammmabcdefaaaammmmabcdefmmmaaaa");
627
628         // 9 SLOW STROBE (fourth variety)
629         lightstyle(9, "aaaaaaaazzzzzzzz");
630
631         // 10 FLUORESCENT FLICKER
632         lightstyle(10, "mmamammmmammamamaaamammma");
633
634         // 11 SLOW PULSE NOT FADE TO BLACK
635         lightstyle(11, "abcdefghijklmnopqrrqponmlkjihgfedcba");
636
637         // styles 32-62 are assigned by the spawnfunc_light program for switchable lights
638
639         // 63 testing
640         lightstyle(63, "a");
641
642         if(autocvar_g_campaign)
643                 CampaignPreInit();
644
645         Map_MarkAsRecent(mapname);
646
647         PlayerStats_Init(); // we need this to be initiated before InitGameplayMode
648
649         precache_model ("null"); // we need this one before InitGameplayMode
650         InitGameplayMode();
651         readlevelcvars();
652         GrappleHookInit();
653         ElectroInit();
654         LaserInit();
655
656         player_count = 0;
657         bot_waypoints_for_items = autocvar_g_waypoints_for_items;
658         if(bot_waypoints_for_items == 1)
659                 if(self.spawnflags & SPAWNFLAG_NO_WAYPOINTS_FOR_ITEMS)
660                         bot_waypoints_for_items = 0;
661
662         precache();
663
664         WaypointSprite_Init();
665
666         GameLogInit(); // prepare everything
667         // NOTE for matchid:
668         // changing the logic generating it is okay. But:
669         // it HAS to stay <= 64 chars
670         // character set: ASCII 33-126 without the following characters: : ; ' " \ $
671         if(autocvar_sv_eventlog)
672         {
673                 s = sprintf("%d.%s.%06d", ftos(autocvar_sv_eventlog_files_counter), strftime(FALSE, "%s"), floor(random() * 1000000));
674                 matchid = strzone(s);
675
676                 GameLogEcho(strcat(":gamestart:", GetGametype(), "_", GetMapname(), ":", s));
677                 s = ":gameinfo:mutators:LIST";
678
679                 ret_string = s;
680                 MUTATOR_CALLHOOK(BuildMutatorsString);
681                 s = ret_string;
682
683                 // simple, probably not good in the mutator system
684                 if(autocvar_g_grappling_hook)
685                         s = strcat(s, ":grappling_hook");
686
687                 // initialiation stuff, not good in the mutator system
688                 if(!autocvar_g_use_ammunition)
689                         s = strcat(s, ":no_use_ammunition");
690
691                 // initialiation stuff, not good in the mutator system
692                 if(autocvar_g_pickup_items == 0)
693                         s = strcat(s, ":no_pickup_items");
694                 if(autocvar_g_pickup_items > 0)
695                         s = strcat(s, ":pickup_items");
696
697                 // initialiation stuff, not good in the mutator system
698                 if(autocvar_g_weaponarena != "0")
699                         s = strcat(s, ":", autocvar_g_weaponarena, " arena");
700
701                 // TODO to mutator system
702                 if(autocvar_g_norecoil)
703                         s = strcat(s, ":norecoil");
704
705                 // TODO to mutator system
706                 if(autocvar_g_midair)
707                         s = strcat(s, ":midair");
708
709                 // TODO to mutator system
710                 if(autocvar_g_minstagib)
711                         s = strcat(s, ":minstagib");
712
713                 // TODO to mutator system
714                 if(autocvar_g_powerups == 0)
715                         s = strcat(s, ":no_powerups");
716                 if(autocvar_g_powerups > 0)
717                         s = strcat(s, ":powerups");
718
719                 GameLogEcho(s);
720                 GameLogEcho(":gameinfo:end");
721         }
722         else
723                 matchid = strzone(ftos(random()));
724
725         cvar_set("nextmap", "");
726
727         SetDefaultAlpha();
728
729         if(autocvar_g_campaign)
730                 CampaignPostInit();
731
732         fteqcc_testbugs();
733
734         Ban_LoadBans();
735
736         MapInfo_Enumerate();
737         MapInfo_FilterGametype(MapInfo_CurrentGametype(), MapInfo_CurrentFeatures(), MapInfo_RequiredFlags(), MapInfo_ForbiddenFlags(), 1);
738
739         if(whichpack(strcat("maps/", mapname, ".cfg")) != "")
740         {
741                 fd = fopen(strcat("maps/", mapname, ".cfg"), FILE_READ);
742                 if(fd != -1)
743                 {
744                         while((s = fgets(fd)))
745                         {
746                                 l = tokenize_console(s);
747                                 if(l < 2)
748                                         continue;
749                                 if(argv(0) == "cd")
750                                 {
751                                         print("Found ^1UNSUPPORTED^7 cd loop command in .cfg file; put this line in mapinfo instead:\n");
752                                         print("  cdtrack ", argv(2), "\n");
753                                 }
754                                 else if(argv(0) == "fog")
755                                 {
756                                         print("Found ^1UNSUPPORTED^7 fog command in .cfg file; put this line in worldspawn in the .map/.bsp/.ent file instead:\n");
757                                         print("  \"fog\" \"", s, "\"\n");
758                                 }
759                                 else if(argv(0) == "set")
760                                 {
761                                         print("Found ^1UNSUPPORTED^7 set command in .cfg file; put this line in mapinfo instead:\n");
762                                         print("  clientsettemp_for_type all ", argv(1), " ", argv(2), "\n");
763                                 }
764                                 else if(argv(0) != "//")
765                                 {
766                                         print("Found ^1UNSUPPORTED^7 set command in .cfg file; put this line in mapinfo instead:\n");
767                                         print("  clientsettemp_for_type all ", argv(0), " ", argv(1), "\n");
768                                 }
769                         }
770                         fclose(fd);
771                 }
772         }
773
774         WeaponStats_Init();
775
776         WEPSET_ADDSTAT();
777         addstat(STAT_SWITCHWEAPON, AS_INT, switchweapon);
778         addstat(STAT_SWITCHINGWEAPON, AS_INT, switchingweapon);
779         addstat(STAT_GAMESTARTTIME, AS_FLOAT, stat_game_starttime);
780         addstat(STAT_ALLOW_OLDNEXBEAM, AS_INT, stat_allow_oldnexbeam);
781         Nagger_Init();
782
783         addstat(STAT_STRENGTH_FINISHED, AS_FLOAT, strength_finished);
784         addstat(STAT_INVINCIBLE_FINISHED, AS_FLOAT, invincible_finished);
785         addstat(STAT_SUPERWEAPONS_FINISHED, AS_FLOAT, superweapons_finished);
786         addstat(STAT_PRESSED_KEYS, AS_FLOAT, pressedkeys);
787         addstat(STAT_FUEL, AS_INT, ammo_fuel);
788         addstat(STAT_SHOTORG, AS_INT, stat_shotorg);
789         addstat(STAT_LEADLIMIT, AS_FLOAT, stat_leadlimit);
790         addstat(STAT_WEAPON_CLIPLOAD, AS_INT, clip_load);
791         addstat(STAT_WEAPON_CLIPSIZE, AS_INT, clip_size);
792         addstat(STAT_LAST_PICKUP, AS_FLOAT, last_pickup);
793         addstat(STAT_HIT_TIME, AS_FLOAT, hit_time);
794         addstat(STAT_TYPEHIT_TIME, AS_FLOAT, typehit_time);
795         addstat(STAT_LAYED_MINES, AS_INT, minelayer_mines);
796
797         addstat(STAT_NEX_CHARGE, AS_FLOAT, nex_charge);
798         addstat(STAT_NEX_CHARGEPOOL, AS_FLOAT, nex_chargepool_ammo);
799
800         addstat(STAT_HAGAR_LOAD, AS_INT, hagar_load);
801
802         if(g_ca || g_freezetag)
803         {
804                 addstat(STAT_REDALIVE, AS_INT, redalive_stat);
805                 addstat(STAT_BLUEALIVE, AS_INT, bluealive_stat);
806                 addstat(STAT_YELLOWALIVE, AS_INT, yellowalive_stat);
807                 addstat(STAT_PINKALIVE, AS_INT, pinkalive_stat);
808         }
809         if(g_freezetag)
810         {
811                 addstat(STAT_FROZEN, AS_INT, freezetag_frozen);
812                 addstat(STAT_REVIVE_PROGRESS, AS_FLOAT, freezetag_revive_progress);
813         }
814
815         // g_movementspeed hack
816         addstat(STAT_MOVEVARS_AIRSPEEDLIMIT_NONQW, AS_FLOAT, stat_sv_airspeedlimit_nonqw);
817         addstat(STAT_MOVEVARS_MAXSPEED, AS_FLOAT, stat_sv_maxspeed);
818         addstat(STAT_MOVEVARS_AIRACCEL_QW, AS_FLOAT, stat_sv_airaccel_qw);
819         addstat(STAT_MOVEVARS_AIRSTRAFEACCEL_QW, AS_FLOAT, stat_sv_airstrafeaccel_qw);
820
821         // secrets
822         addstat(STAT_SECRETS_TOTAL, AS_FLOAT, stat_secrets_total);
823         addstat(STAT_SECRETS_FOUND, AS_FLOAT, stat_secrets_found);
824
825         // misc
826         addstat(STAT_RESPAWN_TIME, AS_FLOAT, stat_respawn_time);
827
828         next_pingtime = time + 5;
829
830         detect_maptype();
831
832         // set up information replies for clients and server to use
833         lsmaps_reply = "^7Maps available: ";
834         lsnewmaps_reply = "^7Maps without a record set: ";
835         for(i = 0, j = 0; i < MapInfo_count; ++i)
836         {
837                 if(MapInfo_Get_ByID(i))
838                         if not(MapInfo_Map_flags & (MAPINFO_FLAG_HIDDEN | MAPINFO_FLAG_FORBIDDEN))
839                         {
840                                 if(mod(i, 2))
841                                         col = "^2";
842                                 else
843                                         col = "^3";
844
845                                 ++j;
846
847                                 lsmaps_reply = strcat(lsmaps_reply, col, MapInfo_Map_bspname, " ");
848
849                                 if(g_race && !stof(db_get(ServerProgsDB, strcat(MapInfo_Map_bspname, RACE_RECORD, "time"))))
850                                         lsnewmaps_reply = strcat(lsnewmaps_reply, col, MapInfo_Map_bspname, " ");
851                                 else if(g_cts && !stof(db_get(ServerProgsDB, strcat(MapInfo_Map_bspname, CTS_RECORD, "time"))))
852                                         lsnewmaps_reply = strcat(lsnewmaps_reply, col, MapInfo_Map_bspname, " ");
853                         }
854         }
855
856         lsmaps_reply = strzone(strcat(lsmaps_reply, "\n"));
857         lsnewmaps_reply = strzone(strcat(((!g_race && !g_cts) ? "Need to be playing race or CTS for lsnewmaps to work." : lsnewmaps_reply), "\n"));
858
859         maplist_reply = "^7Maps in list: ";
860         n = tokenize_console(autocvar_g_maplist);
861         for(i = 0, j = 0; i < n; ++i)
862         {
863                 if(MapInfo_CheckMap(argv(i)))
864                 {
865                         if(mod(j, 2))
866                                 col = "^2";
867                         else
868                                 col = "^3";
869                         maplist_reply = strcat(maplist_reply, col, argv(i), " ");
870                         ++j;
871                 }
872         }
873         maplist_reply = strzone(strcat(maplist_reply, "\n"));
874         MapInfo_ClearTemps();
875
876         for(i = 0; i < 10; ++i)
877         {
878                 s = getrecords(i);
879                 if (s)
880                         records_reply[i] = strzone(s);
881         }
882
883         ladder_reply = strzone(getladder());
884
885         rankings_reply = strzone(getrankings());
886
887         // begin other init
888         ClientInit_Spawn();
889         RandomSeed_Spawn();
890         PingPLReport_Spawn();
891
892         CheatInit();
893
894         localcmd("\n_sv_hook_gamestart ", GetGametype(), "\n");
895
896         // fill sv_curl_serverpackages from .serverpackage files
897         if(autocvar_sv_curl_serverpackages_auto)
898         {
899                 s = "";
900                 n = tokenize_console(cvar_string("sv_curl_serverpackages"));
901                 for(i = 0; i < n; ++i)
902                         if(substring(argv(i), -14, -1) != "-serverpackage.txt")
903                         if(substring(argv(i), -14, -1) != ".serverpackage") // OLD legacy
904                                 s = strcat(s, " ", argv(i));
905                 fd = search_begin("*-serverpackage.txt", TRUE, FALSE);
906                 if(fd >= 0)
907                 {
908                         j = search_getsize(fd);
909                         for(i = 0; i < j; ++i)
910                                 s = strcat(s, " ", search_getfilename(fd, i));
911                         search_end(fd);
912                 }
913                 fd = search_begin("*.serverpackage", TRUE, FALSE);
914                 if(fd >= 0)
915                 {
916                         j = search_getsize(fd);
917                         for(i = 0; i < j; ++i)
918                                 s = strcat(s, " ", search_getfilename(fd, i));
919                         search_end(fd);
920                 }
921                 cvar_set("sv_curl_serverpackages", substring(s, 1, -1));
922         }
923
924         // MOD AUTHORS: change this, and possibly remove a few of the blocks below to ignore certain changes
925         modname = "Xonotic";
926         // physics/balance/config changes that count as mod
927         if(cvar_string("g_mod_physics") != cvar_defstring("g_mod_physics"))
928                 modname = cvar_string("g_mod_physics");
929         if(cvar_string("g_mod_balance") != cvar_defstring("g_mod_balance"))
930                 modname = cvar_string("g_mod_balance");
931         if(cvar_string("g_mod_config") != cvar_defstring("g_mod_config"))
932                 modname = cvar_string("g_mod_config");
933         // weird mutators that deserve to count as mod
934         if(autocvar_g_minstagib)
935                 modname = "MinstaGib";
936         // extra mutators that deserve to count as mod
937         MUTATOR_CALLHOOK(SetModname);
938
939         // save it for later
940         modname = strzone(modname);
941
942         WinningConditionHelper(); // set worldstatus
943
944         world_initialized = 1;
945 }
946
947 void spawnfunc_light (void)
948 {
949         //makestatic (self); // Who the f___ did that?
950         remove(self);
951 }
952
953 string GetGametype()
954 {
955         return MapInfo_Type_ToString(MapInfo_LoadedGametype);
956 }
957
958 string getmapname_stored;
959 string GetMapname()
960 {
961         return mapname;
962 }
963
964 float Map_Count, Map_Current;
965 string Map_Current_Name;
966
967 // NOTE: this now expects the map list to be already tokenized and the count in Map_Count
968 float GetMaplistPosition()
969 {
970         float pos, idx;
971         string map;
972
973         map = GetMapname();
974         idx = autocvar_g_maplist_index;
975
976         if(idx >= 0)
977                 if(idx < Map_Count)
978                         if(map == argv(idx))
979                                 return idx;
980
981         for(pos = 0; pos < Map_Count; ++pos)
982                 if(map == argv(pos))
983                         return pos;
984
985         // resume normal maplist rotation if current map is not in g_maplist
986         return idx;
987 }
988
989 float MapHasRightSize(string map)
990 {
991         float fh;
992         if(currentbots || autocvar_bot_number || player_count < autocvar_minplayers)
993         if(autocvar_g_maplist_check_waypoints)
994         {
995                 dprint("checkwp "); dprint(map);
996                 if(!fexists(strcat("maps/", map, ".waypoints")))
997                 {
998                         dprint(": no waypoints\n");
999                         return FALSE;
1000                 }
1001                 dprint(": has waypoints\n");
1002         }
1003
1004         // open map size restriction file
1005         dprint("opensize "); dprint(map);
1006         fh = fopen(strcat("maps/", map, ".sizes"), FILE_READ);
1007         if(fh >= 0)
1008         {
1009                 float mapmin, mapmax;
1010                 dprint(": ok, ");
1011                 mapmin = stof(fgets(fh));
1012                 mapmax = stof(fgets(fh));
1013                 fclose(fh);
1014                 if(player_count < mapmin)
1015                 {
1016                         dprint("not enough\n");
1017                         return FALSE;
1018                 }
1019                 if(player_count > mapmax)
1020                 {
1021                         dprint("too many\n");
1022                         return FALSE;
1023                 }
1024                 dprint("right size\n");
1025                 return TRUE;
1026         }
1027         dprint(": not found\n");
1028         return TRUE;
1029 }
1030
1031 string Map_Filename(float position)
1032 {
1033         return strcat("maps/", argv(position), ".bsp");
1034 }
1035
1036 string strwords(string s, float w)
1037 {
1038         float endpos;
1039         for(endpos = 0; w && endpos >= 0; --w)
1040                 endpos = strstrofs(s, " ", endpos + 1);
1041         if(endpos < 0)
1042                 return s;
1043         else
1044                 return substring(s, 0, endpos);
1045 }
1046
1047 float strhasword(string s, string w)
1048 {
1049         return strstrofs(strcat(" ", s, " "), strcat(" ", w, " "), 0) >= 0;
1050 }
1051
1052 void Map_MarkAsRecent(string m)
1053 {
1054         cvar_set("g_maplist_mostrecent", strwords(strcat(m, " ", autocvar_g_maplist_mostrecent), max(0, autocvar_g_maplist_mostrecent_count)));
1055 }
1056
1057 float Map_IsRecent(string m)
1058 {
1059         return strhasword(autocvar_g_maplist_mostrecent, m);
1060 }
1061
1062 float Map_Check(float position, float pass)
1063 {
1064         string filename;
1065         string map_next;
1066         map_next = argv(position);
1067         if(pass <= 1)
1068         {
1069                 if(Map_IsRecent(map_next))
1070                         return 0;
1071         }
1072         filename = Map_Filename(position);
1073         if(MapInfo_CheckMap(map_next))
1074         {
1075                 if(pass == 2)
1076                         return 1;
1077                 if(MapHasRightSize(map_next))
1078                         return 1;
1079                 return 0;
1080         }
1081         else
1082                 dprint( "Couldn't select '", filename, "'..\n" );
1083
1084         return 0;
1085 }
1086
1087 void Map_Goto_SetStr(string nextmapname)
1088 {
1089         if(getmapname_stored != "")
1090                 strunzone(getmapname_stored);
1091         if(nextmapname == "")
1092                 getmapname_stored = "";
1093         else
1094                 getmapname_stored = strzone(nextmapname);
1095 }
1096
1097 void Map_Goto_SetFloat(float position)
1098 {
1099         cvar_set("g_maplist_index", ftos(position));
1100         Map_Goto_SetStr(argv(position));
1101 }
1102
1103 void Map_Goto(float reinit)
1104 {
1105         MapInfo_LoadMap(getmapname_stored, reinit);
1106 }
1107
1108 // return codes of map selectors:
1109 //   -1 = temporary failure (that is, try some method that is guaranteed to succeed)
1110 //   -2 = permanent failure
1111 float() MaplistMethod_Iterate = // usual method
1112 {
1113         float pass, i;
1114
1115         for(pass = 1; pass <= 2; ++pass)
1116         {
1117                 for(i = 1; i < Map_Count; ++i)
1118                 {
1119                         float mapindex;
1120                         mapindex = mod(i + Map_Current, Map_Count);
1121                         if(Map_Check(mapindex, pass))
1122                                 return mapindex;
1123                 }
1124         }
1125         return -1;
1126 }
1127
1128 float() MaplistMethod_Repeat = // fallback method
1129 {
1130         if(Map_Check(Map_Current, 2))
1131                 return Map_Current;
1132         return -2;
1133 }
1134
1135 float() MaplistMethod_Random = // random map selection
1136 {
1137         float i, imax;
1138
1139         imax = 42;
1140
1141         for(i = 0; i <= imax; ++i)
1142         {
1143                 float mapindex;
1144                 mapindex = mod(Map_Current + floor(random() * (Map_Count - 1) + 1), Map_Count); // any OTHER map
1145                 if(Map_Check(mapindex, 1))
1146                         return mapindex;
1147         }
1148         return -1;
1149 }
1150
1151 float(float exponent) MaplistMethod_Shuffle = // more clever shuffling
1152 // the exponent sets a bias on the map selection:
1153 // the higher the exponent, the less likely "shortly repeated" same maps are
1154 {
1155         float i, j, imax, insertpos;
1156
1157         imax = 42;
1158
1159         for(i = 0; i <= imax; ++i)
1160         {
1161                 string newlist;
1162
1163                 // now reinsert this at another position
1164                 insertpos = pow(random(), 1 / exponent);       // ]0, 1]
1165                 insertpos = insertpos * (Map_Count - 1);       // ]0, Map_Count - 1]
1166                 insertpos = ceil(insertpos) + 1;               // {2, 3, 4, ..., Map_Count}
1167                 dprint("SHUFFLE: insert pos = ", ftos(insertpos), "\n");
1168
1169                 // insert the current map there
1170                 newlist = "";
1171                 for(j = 1; j < insertpos; ++j)                 // i == 1: no loop, will be inserted as first; however, i == 1 has been excluded above
1172                         newlist = strcat(newlist, " ", argv(j));
1173                 newlist = strcat(newlist, " ", argv(0));       // now insert the just selected map
1174                 for(j = insertpos; j < Map_Count; ++j)         // i == Map_Count: no loop, has just been inserted as last
1175                         newlist = strcat(newlist, " ", argv(j));
1176                 newlist = substring(newlist, 1, strlen(newlist) - 1);
1177                 cvar_set("g_maplist", newlist);
1178                 Map_Count = tokenizebyseparator(autocvar_g_maplist, " ");
1179
1180                 // NOTE: the selected map has just been inserted at (insertpos-1)th position
1181                 Map_Current = insertpos - 1; // this is not really valid, but this way the fallback has a chance of working
1182                 if(Map_Check(Map_Current, 1))
1183                         return Map_Current;
1184         }
1185         return -1;
1186 }
1187
1188 void Maplist_Init()
1189 {
1190         Map_Count = tokenizebyseparator(autocvar_g_maplist, " ");
1191         if(Map_Count == 0)
1192         {
1193                 bprint( "Maplist is empty!  Resetting it to default map list.\n" );
1194                 cvar_set("g_maplist", MapInfo_ListAllAllowedMaps(MapInfo_RequiredFlags(), MapInfo_ForbiddenFlags()));
1195                 if(autocvar_g_maplist_shuffle)
1196                         ShuffleMaplist();
1197                 localcmd("\nmenu_cmd sync\n");
1198                 Map_Count = tokenizebyseparator(autocvar_g_maplist, " ");
1199         }
1200         if(Map_Count == 0)
1201                 error("empty maplist, cannot select a new map");
1202         Map_Current = bound(0, GetMaplistPosition(), Map_Count - 1);
1203
1204         if(Map_Current_Name)
1205                 strunzone(Map_Current_Name);
1206         Map_Current_Name = strzone(argv(Map_Current)); // will be automatically freed on exit thanks to DP
1207         // this may or may not be correct, but who cares, in the worst case a map
1208         // isn't chosen in the first pass that should have been
1209 }
1210
1211 string GetNextMap()
1212 {
1213         float nextMap;
1214
1215         Maplist_Init();
1216         nextMap = -1;
1217
1218         if(nextMap == -1)
1219                 if(autocvar_g_maplist_shuffle > 0)
1220                         nextMap = MaplistMethod_Shuffle(autocvar_g_maplist_shuffle + 1);
1221
1222         if(nextMap == -1)
1223                 if(autocvar_g_maplist_selectrandom)
1224                         nextMap = MaplistMethod_Random();
1225
1226         if(nextMap == -1)
1227                 nextMap = MaplistMethod_Iterate();
1228
1229         if(nextMap == -1)
1230                 nextMap = MaplistMethod_Repeat();
1231
1232         if(nextMap >= 0)
1233         {
1234                 Map_Goto_SetFloat(nextMap);
1235                 return getmapname_stored;
1236         }
1237
1238         return "";
1239 }
1240
1241 float DoNextMapOverride(float reinit)
1242 {
1243         if(autocvar_g_campaign)
1244         {
1245                 CampaignPostIntermission();
1246                 alreadychangedlevel = TRUE;
1247                 return TRUE;
1248         }
1249         if(autocvar_quit_when_empty)
1250         {
1251                 if(player_count <= currentbots)
1252                 {
1253                         localcmd("quit\n");
1254                         alreadychangedlevel = TRUE;
1255                         return TRUE;
1256                 }
1257         }
1258         if(autocvar_quit_and_redirect != "")
1259         {
1260                 redirection_target = strzone(autocvar_quit_and_redirect);
1261                 alreadychangedlevel = TRUE;
1262                 return TRUE;
1263         }
1264         if (!reinit && autocvar_samelevel) // if samelevel is set, stay on same level
1265         {
1266                 localcmd("restart\n");
1267                 alreadychangedlevel = TRUE;
1268                 return TRUE;
1269         }
1270         if(autocvar_nextmap != "")
1271                 if(MapInfo_CheckMap(autocvar_nextmap))
1272                 {
1273                         Map_Goto_SetStr(autocvar_nextmap);
1274                         Map_Goto(reinit);
1275                         alreadychangedlevel = TRUE;
1276                         return TRUE;
1277                 }
1278         if(!reinit && autocvar_lastlevel)
1279         {
1280                 cvar_settemp_restore();
1281                 localcmd("set lastlevel 0\ntogglemenu 1\n");
1282                 alreadychangedlevel = TRUE;
1283                 return TRUE;
1284         }
1285         return FALSE;
1286 }
1287
1288 void GotoNextMap(float reinit)
1289 {
1290         //string nextmap;
1291         //float n, nummaps;
1292         //string s;
1293         if (alreadychangedlevel)
1294                 return;
1295         alreadychangedlevel = TRUE;
1296
1297         {
1298                 string nextMap;
1299                 float allowReset;
1300
1301                 for(allowReset = 1; allowReset >= 0; --allowReset)
1302                 {
1303                         nextMap = GetNextMap();
1304                         if(nextMap != "")
1305                                 break;
1306
1307                         if(allowReset)
1308                         {
1309                                 bprint( "Maplist contains no single playable map!  Resetting it to default map list.\n" );
1310                                 cvar_set("g_maplist", MapInfo_ListAllAllowedMaps(MapInfo_RequiredFlags(), MapInfo_ForbiddenFlags()));
1311                                 if(autocvar_g_maplist_shuffle)
1312                                         ShuffleMaplist();
1313                                 localcmd("\nmenu_cmd sync\n");
1314                         }
1315                         else
1316                         {
1317                                 error("Everything is broken - not even the default map list works. Please report this to the developers.");
1318                         }
1319                 }
1320                 Map_Goto(reinit);
1321         }
1322 }
1323
1324
1325 /*
1326 ============
1327 IntermissionThink
1328
1329 When the player presses attack or jump, change to the next level
1330 ============
1331 */
1332 .float autoscreenshot;
1333 void() MapVote_Start;
1334 void() MapVote_Think;
1335 float mapvote_initialized;
1336 void IntermissionThink()
1337 {
1338         FixIntermissionClient(self);
1339
1340         float server_screenshot = (autocvar_sv_autoscreenshot && self.cvar_cl_autoscreenshot);
1341         float client_screenshot = (self.cvar_cl_autoscreenshot == 2);
1342
1343         if( (server_screenshot || client_screenshot)
1344                 && ((self.autoscreenshot > 0) && (time > self.autoscreenshot)) )
1345         {
1346                 self.autoscreenshot = -1;
1347                 if(clienttype(self) == CLIENTTYPE_REAL) { stuffcmd(self, sprintf("\nscreenshot screenshots/autoscreenshot/%s-%s.jpg; echo \"^5A screenshot has been taken at request of the server.\"", GetMapname(), strftime(FALSE, "%s"))); }
1348                 return;
1349         }
1350
1351         if (time < intermission_exittime)
1352                 return;
1353
1354         if(!mapvote_initialized)
1355                 if (time < intermission_exittime + 10 && !(self.BUTTON_ATCK || self.BUTTON_JUMP || self.BUTTON_ATCK2 || self.BUTTON_HOOK || self.BUTTON_USE))
1356                         return;
1357
1358         MapVote_Start();
1359 }
1360
1361 /*
1362 ============
1363 FindIntermission
1364
1365 Returns the entity to view from
1366 ============
1367 */
1368 /*
1369 entity FindIntermission()
1370 {
1371         local   entity spot;
1372         local   float cyc;
1373
1374 // look for info_intermission first
1375         spot = find (world, classname, "info_intermission");
1376         if (spot)
1377         {       // pick a random one
1378                 cyc = random() * 4;
1379                 while (cyc > 1)
1380                 {
1381                         spot = find (spot, classname, "info_intermission");
1382                         if (!spot)
1383                                 spot = find (spot, classname, "info_intermission");
1384                         cyc = cyc - 1;
1385                 }
1386                 return spot;
1387         }
1388
1389 // then look for the start position
1390         spot = find (world, classname, "info_player_start");
1391         if (spot)
1392                 return spot;
1393
1394 // testinfo_player_start is only found in regioned levels
1395         spot = find (world, classname, "testplayerstart");
1396         if (spot)
1397                 return spot;
1398
1399 // then look for the start position
1400         spot = find (world, classname, "info_player_deathmatch");
1401         if (spot)
1402                 return spot;
1403
1404         //objerror ("FindIntermission: no spot");
1405         return world;
1406 }
1407 */
1408
1409 /*
1410 ===============================================================================
1411
1412 RULES
1413
1414 ===============================================================================
1415 */
1416
1417 void DumpStats(float final)
1418 {
1419         float file;
1420         string s;
1421         float to_console;
1422         float to_eventlog;
1423         float to_file;
1424         float i;
1425
1426         to_console = autocvar_sv_logscores_console;
1427         to_eventlog = autocvar_sv_eventlog;
1428         to_file = autocvar_sv_logscores_file;
1429
1430         if(!final)
1431         {
1432                 to_console = TRUE; // always print printstats replies
1433                 to_eventlog = FALSE; // but never print them to the event log
1434         }
1435
1436         if(to_eventlog)
1437                 if(autocvar_sv_eventlog_console)
1438                         to_console = FALSE; // otherwise we get the output twice
1439
1440         if(final)
1441                 s = ":scores:";
1442         else
1443                 s = ":status:";
1444         s = strcat(s, GetGametype(), "_", GetMapname(), ":", ftos(rint(time)));
1445
1446         if(to_console)
1447                 print(s, "\n");
1448         if(to_eventlog)
1449                 GameLogEcho(s);
1450
1451         file = -1;
1452         if(to_file)
1453         {
1454                 file = fopen(autocvar_sv_logscores_filename, FILE_APPEND);
1455                 if(file == -1)
1456                         to_file = FALSE;
1457                 else
1458                         fputs(file, strcat(s, "\n"));
1459         }
1460
1461         s = strcat(":labels:player:", GetPlayerScoreString(world, 0));
1462         if(to_console)
1463                 print(s, "\n");
1464         if(to_eventlog)
1465                 GameLogEcho(s);
1466         if(to_file)
1467                 fputs(file, strcat(s, "\n"));
1468
1469         FOR_EACH_CLIENT(other)
1470         {
1471                 if ((clienttype(other) == CLIENTTYPE_REAL) || (clienttype(other) == CLIENTTYPE_BOT && autocvar_sv_logscores_bots))
1472                 {
1473                         s = strcat(":player:see-labels:", GetPlayerScoreString(other, 0), ":");
1474                         s = strcat(s, ftos(rint(time - other.jointime)), ":");
1475                         if(other.classname == "player" || g_arena || g_ca || g_lms)
1476                                 s = strcat(s, ftos(other.team), ":");
1477                         else
1478                                 s = strcat(s, "spectator:");
1479
1480                         if(to_console)
1481                                 print(s, other.netname, "\n");
1482                         if(to_eventlog)
1483                                 GameLogEcho(strcat(s, ftos(other.playerid), ":", other.netname));
1484                         if(to_file)
1485                                 fputs(file, strcat(s, other.netname, "\n"));
1486                 }
1487         }
1488
1489         if(teamplay)
1490         {
1491                 s = strcat(":labels:teamscores:", GetTeamScoreString(0, 0));
1492                 if(to_console)
1493                         print(s, "\n");
1494                 if(to_eventlog)
1495                         GameLogEcho(s);
1496                 if(to_file)
1497                         fputs(file, strcat(s, "\n"));
1498
1499                 for(i = 1; i < 16; ++i)
1500                 {
1501                         s = strcat(":teamscores:see-labels:", GetTeamScoreString(i, 0));
1502                         s = strcat(s, ":", ftos(i));
1503                         if(to_console)
1504                                 print(s, "\n");
1505                         if(to_eventlog)
1506                                 GameLogEcho(s);
1507                         if(to_file)
1508                                 fputs(file, strcat(s, "\n"));
1509                 }
1510         }
1511
1512         if(to_console)
1513                 print(":end\n");
1514         if(to_eventlog)
1515                 GameLogEcho(":end");
1516         if(to_file)
1517         {
1518                 fputs(file, ":end\n");
1519                 fclose(file);
1520         }
1521 }
1522
1523 void FixIntermissionClient(entity e)
1524 {
1525         string s;
1526         if(!e.autoscreenshot) // initial call
1527         {
1528                 e.autoscreenshot = time + 0.8;  // used for autoscreenshot
1529                 e.health = -2342;
1530                 // first intermission phase; voting phase has positive health (used to decide whether to send SVC_FINALE or not)
1531                 e.solid = SOLID_NOT;
1532                 e.movetype = MOVETYPE_NONE;
1533                 e.takedamage = DAMAGE_NO;
1534                 if(e.weaponentity)
1535                 {
1536                         e.weaponentity.effects = EF_NODRAW;
1537                         if (e.weaponentity.weaponentity)
1538                                 e.weaponentity.weaponentity.effects = EF_NODRAW;
1539                 }
1540                 if(clienttype(e) == CLIENTTYPE_REAL)
1541                 {
1542                         stuffcmd(e, "\nscr_printspeed 1000000\n");
1543                         s = autocvar_sv_intermission_cdtrack;
1544                         if(s != "")
1545                                 stuffcmd(e, strcat("\ncd loop ", s, "\n"));
1546                         msg_entity = e;
1547                         WriteByte(MSG_ONE, SVC_INTERMISSION);
1548                 }
1549         }
1550 }
1551
1552 void minstagib_stop_countdown(entity e);
1553 /*
1554 go to the next level for deathmatch
1555 only called if a time or frag limit has expired
1556 */
1557 void NextLevel()
1558 {
1559         gameover = TRUE;
1560
1561         intermission_running = 1;
1562
1563 // enforce a wait time before allowing changelevel
1564         if(player_count > 0)
1565                 intermission_exittime = time + autocvar_sv_mapchange_delay;
1566         else
1567                 intermission_exittime = -1;
1568
1569         /*
1570         WriteByte (MSG_ALL, SVC_CDTRACK);
1571         WriteByte (MSG_ALL, 3);
1572         WriteByte (MSG_ALL, 3);
1573         // done in FixIntermission
1574         */
1575
1576         //pos = FindIntermission ();
1577
1578         VoteReset();
1579
1580         DumpStats(TRUE);
1581
1582         // send statistics
1583         entity e;
1584         PlayerStats_EndMatch(1);
1585         FOR_EACH_CLIENT(e)
1586                 PlayerStats_AddGlobalInfo(e);
1587         PlayerStats_Shutdown();
1588         WeaponStats_Shutdown();
1589
1590         if(autocvar_sv_eventlog)
1591                 GameLogEcho(":gameover");
1592
1593         GameLogClose();
1594
1595         FOR_EACH_PLAYER(other) {
1596                 minstagib_stop_countdown(other);
1597                 FixIntermissionClient(other);
1598                 if(other.winning)
1599                         bprint(other.netname, " ^7wins.\n");
1600         }
1601
1602         if(autocvar_g_campaign)
1603                 CampaignPreIntermission();
1604
1605         MUTATOR_CALLHOOK(MatchEnd);
1606
1607         localcmd("\nsv_hook_gameend\n");
1608 }
1609
1610 /*
1611 ============
1612 CheckRules_Player
1613
1614 Exit deathmatch games upon conditions
1615 ============
1616 */
1617 void CheckRules_Player()
1618 {
1619         if (gameover)   // someone else quit the game already
1620                 return;
1621
1622         if(self.deadflag == DEAD_NO)
1623                 self.play_time += frametime;
1624
1625         // fixme: don't check players; instead check spawnfunc_dom_team and spawnfunc_ctf_team entities
1626         //   (div0: and that in CheckRules_World please)
1627 }
1628
1629 float checkrules_equality;
1630 float checkrules_suddendeathwarning;
1631 float checkrules_suddendeathend;
1632 float checkrules_overtimesadded; //how many overtimes have been already added
1633
1634 float WINNING_NO = 0; // no winner, but time limits may terminate the game
1635 float WINNING_YES = 1; // winner found
1636 float WINNING_NEVER = 2; // no winner, enter overtime if time limit is reached
1637 float WINNING_STARTSUDDENDEATHOVERTIME = 3; // no winner, enter suddendeath overtime NOW
1638
1639 float InitiateSuddenDeath()
1640 {
1641         // Check first whether normal overtimes could be added before initiating suddendeath mode
1642         // - for this timelimit_overtime needs to be >0 of course
1643         // - also check the winning condition calculated in the previous frame and only add normal overtime
1644         //   again, if at the point at which timelimit would be extended again, still no winner was found
1645         if (!autocvar_g_campaign && (checkrules_overtimesadded >= 0) && (checkrules_overtimesadded < autocvar_timelimit_overtimes) && autocvar_timelimit_overtime && !(g_race && !g_race_qualifying))
1646         {
1647                 return 1; // need to call InitiateOvertime later
1648         }
1649         else
1650         {
1651                 if(!checkrules_suddendeathend)
1652                 {
1653                         if(autocvar_g_campaign)
1654                                 checkrules_suddendeathend = time; // no suddendeath in campaign
1655                         else
1656                                 checkrules_suddendeathend = time + 60 * autocvar_timelimit_suddendeath;
1657                         if(g_race && !g_race_qualifying)
1658                                 race_StartCompleting();
1659                 }
1660                 return 0;
1661         }
1662 }
1663
1664 void InitiateOvertime() // ONLY call this if InitiateSuddenDeath returned true
1665 {
1666         ++checkrules_overtimesadded;
1667         //add one more overtime by simply extending the timelimit
1668         float tl;
1669         tl = autocvar_timelimit;
1670         tl += autocvar_timelimit_overtime;
1671         cvar_set("timelimit", ftos(tl));
1672         string minutesPlural;
1673         if (autocvar_timelimit_overtime == 1)
1674                 minutesPlural = " ^3minute";
1675         else
1676                 minutesPlural = " ^3minutes";
1677
1678         bcenterprint(
1679                 strcat(
1680                         "^3Now playing ^1OVERTIME^3!\n\n^3Added ^1",
1681                         ftos(autocvar_timelimit_overtime),
1682                         minutesPlural,
1683                         " to the game!"
1684                 )
1685         );
1686 }
1687
1688 float GetWinningCode(float fraglimitreached, float equality)
1689 {
1690         if(autocvar_g_campaign == 1)
1691                 if(fraglimitreached)
1692                         return WINNING_YES;
1693                 else
1694                         return WINNING_NO;
1695
1696         else
1697                 if(equality)
1698                         if(fraglimitreached)
1699                                 return WINNING_STARTSUDDENDEATHOVERTIME;
1700                         else
1701                                 return WINNING_NEVER;
1702                 else
1703                         if(fraglimitreached)
1704                                 return WINNING_YES;
1705                         else
1706                                 return WINNING_NO;
1707 }
1708
1709 // set the .winning flag for exactly those players with a given field value
1710 void SetWinners(.float field, float value)
1711 {
1712         entity head;
1713         FOR_EACH_PLAYER(head)
1714                 head.winning = (head.field == value);
1715 }
1716
1717 // set the .winning flag for those players with a given field value
1718 void AddWinners(.float field, float value)
1719 {
1720         entity head;
1721         FOR_EACH_PLAYER(head)
1722                 if(head.field == value)
1723                         head.winning = 1;
1724 }
1725
1726 // clear the .winning flags
1727 void ClearWinners(void)
1728 {
1729         entity head;
1730         FOR_EACH_PLAYER(head)
1731                 head.winning = 0;
1732 }
1733
1734 // Onslaught winning condition:
1735 // game terminates if only one team has a working generator (or none)
1736 float WinningCondition_Onslaught()
1737 {
1738         entity head;
1739         float t1, t2, t3, t4;
1740
1741         WinningConditionHelper(); // set worldstatus
1742
1743         if(inWarmupStage)
1744                 return WINNING_NO;
1745
1746         // first check if the game has ended
1747         t1 = t2 = t3 = t4 = 0;
1748         head = find(world, classname, "onslaught_generator");
1749         while (head)
1750         {
1751                 if (head.health > 0)
1752                 {
1753                         if (head.team == COLOR_TEAM1) t1 = 1;
1754                         if (head.team == COLOR_TEAM2) t2 = 1;
1755                         if (head.team == COLOR_TEAM3) t3 = 1;
1756                         if (head.team == COLOR_TEAM4) t4 = 1;
1757                 }
1758                 head = find(head, classname, "onslaught_generator");
1759         }
1760         if (t1 + t2 + t3 + t4 < 2)
1761         {
1762                 // game over, only one team remains (or none)
1763                 ClearWinners();
1764                 if (t1) SetWinners(team, COLOR_TEAM1);
1765                 if (t2) SetWinners(team, COLOR_TEAM2);
1766                 if (t3) SetWinners(team, COLOR_TEAM3);
1767                 if (t4) SetWinners(team, COLOR_TEAM4);
1768                 dprint("Have a winner, ending game.\n");
1769                 return WINNING_YES;
1770         }
1771
1772         // Two or more teams remain
1773         return WINNING_NO;
1774 }
1775
1776 float LMS_NewPlayerLives()
1777 {
1778         float fl;
1779         fl = autocvar_fraglimit;
1780         if(fl == 0)
1781                 fl = 999;
1782
1783         // first player has left the game for dying too much? Nobody else can get in.
1784         if(lms_lowest_lives < 1)
1785                 return 0;
1786
1787         if(!autocvar_g_lms_join_anytime)
1788                 if(lms_lowest_lives < fl - autocvar_g_lms_last_join)
1789                         return 0;
1790
1791         return bound(1, lms_lowest_lives, fl);
1792 }
1793
1794 // Assault winning condition: If the attackers triggered a round end (by fulfilling all objectives)
1795 // they win. Otherwise the defending team wins once the timelimit passes.
1796 void assault_new_round();
1797 float WinningCondition_Assault()
1798 {
1799         float status;
1800
1801         WinningConditionHelper(); // set worldstatus
1802
1803         status = WINNING_NO;
1804         // as the timelimit has not yet passed just assume the defending team will win
1805         if(assault_attacker_team == COLOR_TEAM1)
1806         {
1807                 SetWinners(team, COLOR_TEAM2);
1808         }
1809         else
1810         {
1811                 SetWinners(team, COLOR_TEAM1);
1812         }
1813
1814         entity ent;
1815         ent = find(world, classname, "target_assault_roundend");
1816         if(ent)
1817         {
1818                 if(ent.winning) // round end has been triggered by attacking team
1819                 {
1820                         bprint("ASSAULT: round completed...\n");
1821                         SetWinners(team, assault_attacker_team);
1822
1823                         TeamScore_AddToTeam(assault_attacker_team, ST_ASSAULT_OBJECTIVES, 666 - TeamScore_AddToTeam(assault_attacker_team, ST_ASSAULT_OBJECTIVES, 0));
1824
1825                         if(ent.cnt == 1 || autocvar_g_campaign) // this was the second round
1826                         {
1827                                 status = WINNING_YES;
1828                         }
1829                         else
1830                         {
1831                                 entity oldself;
1832                                 oldself = self;
1833                                 self = ent;
1834                                 assault_new_round();
1835                                 self = oldself;
1836                         }
1837                 }
1838         }
1839
1840         return status;
1841 }
1842
1843 // LMS winning condition: game terminates if and only if there's at most one
1844 // one player who's living lives. Top two scores being equal cancels the time
1845 // limit.
1846 float WinningCondition_LMS()
1847 {
1848         entity head, head2;
1849         float have_player;
1850         float have_players;
1851         float l;
1852
1853         have_player = FALSE;
1854         have_players = FALSE;
1855         l = LMS_NewPlayerLives();
1856
1857         head = find(world, classname, "player");
1858         if(head)
1859                 have_player = TRUE;
1860         head2 = find(head, classname, "player");
1861         if(head2)
1862                 have_players = TRUE;
1863
1864         if(have_player)
1865         {
1866                 // we have at least one player
1867                 if(have_players)
1868                 {
1869                         // two or more active players - continue with the game
1870                 }
1871                 else
1872                 {
1873                         // exactly one player?
1874
1875                         ClearWinners();
1876                         SetWinners(winning, 0); // NOTE: exactly one player is still "player", so this works out
1877
1878                         if(l)
1879                         {
1880                                 // game still running (that is, nobody got removed from the game by a frag yet)? then continue
1881                                 return WINNING_NO;
1882                         }
1883                         else
1884                         {
1885                                 // a winner!
1886                                 // and assign him his first place
1887                                 PlayerScore_Add(head, SP_LMS_RANK, 1);
1888                                 return WINNING_YES;
1889                         }
1890                 }
1891         }
1892         else
1893         {
1894                 // nobody is playing at all...
1895                 if(l)
1896                 {
1897                         // wait for players...
1898                 }
1899                 else
1900                 {
1901                         // SNAFU (maybe a draw game?)
1902                         ClearWinners();
1903                         dprint("No players, ending game.\n");
1904                         return WINNING_YES;
1905                 }
1906         }
1907
1908         // When we get here, we have at least two players who are actually LIVING,
1909         // now check if the top two players have equal score.
1910         WinningConditionHelper();
1911
1912         ClearWinners();
1913         if(WinningConditionHelper_winner)
1914                 WinningConditionHelper_winner.winning = TRUE;
1915         if(WinningConditionHelper_topscore == WinningConditionHelper_secondscore)
1916                 return WINNING_NEVER;
1917
1918         // Top two have different scores? Way to go for our beloved TIMELIMIT!
1919         return WINNING_NO;
1920 }
1921
1922 void ShuffleMaplist()
1923 {
1924         cvar_set("g_maplist", shufflewords(autocvar_g_maplist));
1925 }
1926
1927 float leaderfrags;
1928 float WinningCondition_Scores(float limit, float leadlimit)
1929 {
1930         float limitreached;
1931
1932         // TODO make everything use THIS winning condition (except LMS)
1933         WinningConditionHelper();
1934
1935         if(teamplay)
1936         {
1937                 team1_score = TeamScore_GetCompareValue(COLOR_TEAM1);
1938                 team2_score = TeamScore_GetCompareValue(COLOR_TEAM2);
1939                 team3_score = TeamScore_GetCompareValue(COLOR_TEAM3);
1940                 team4_score = TeamScore_GetCompareValue(COLOR_TEAM4);
1941         }
1942
1943         ClearWinners();
1944         if(WinningConditionHelper_winner)
1945                 WinningConditionHelper_winner.winning = 1;
1946         if(WinningConditionHelper_winnerteam >= 0)
1947                 SetWinners(team, WinningConditionHelper_winnerteam);
1948
1949         if(WinningConditionHelper_lowerisbetter)
1950         {
1951                 WinningConditionHelper_topscore = -WinningConditionHelper_topscore;
1952                 WinningConditionHelper_secondscore = -WinningConditionHelper_secondscore;
1953                 limit = -limit;
1954         }
1955
1956         if(WinningConditionHelper_zeroisworst)
1957                 leadlimit = 0; // not supported in this mode
1958
1959         if(g_dm || g_tdm || g_arena || g_ca || (g_race && !g_race_qualifying) || g_nexball)
1960         // these modes always score in increments of 1, thus this makes sense
1961         {
1962                 if(leaderfrags != WinningConditionHelper_topscore)
1963                 {
1964                         leaderfrags = WinningConditionHelper_topscore;
1965
1966                         if (limit)
1967                         if (leaderfrags == limit - 1)
1968                                 Announce("1fragleft");
1969                         else if (leaderfrags == limit - 2)
1970                                 Announce("2fragsleft");
1971                         else if (leaderfrags == limit - 3)
1972                                 Announce("3fragsleft");
1973                 }
1974         }
1975
1976         limitreached = FALSE;
1977         if(limit)
1978                 if(WinningConditionHelper_topscore >= limit)
1979                         limitreached = TRUE;
1980         if(leadlimit)
1981         {
1982                 float leadlimitreached;
1983                 leadlimitreached = (WinningConditionHelper_topscore - WinningConditionHelper_secondscore >= leadlimit);
1984                 if(autocvar_leadlimit_and_fraglimit)
1985                         limitreached = (limitreached && leadlimitreached);
1986                 else
1987                         limitreached = (limitreached || leadlimitreached);
1988         }
1989
1990         if(limit)
1991                 game_completion_ratio = max(game_completion_ratio, bound(0, WinningConditionHelper_topscore / limit, 1));
1992
1993         return GetWinningCode(
1994                 WinningConditionHelper_topscore && limitreached,
1995                 WinningConditionHelper_equality
1996         );
1997 }
1998
1999 float WinningCondition_Race(float fraglimit)
2000 {
2001         float wc;
2002         entity p;
2003         float n, c;
2004
2005         n = 0;
2006         c = 0;
2007         FOR_EACH_PLAYER(p)
2008         {
2009                 ++n;
2010                 if(p.race_completed)
2011                         ++c;
2012         }
2013         if(n && (n == c))
2014                 return WINNING_YES;
2015         wc = WinningCondition_Scores(fraglimit, 0);
2016
2017         // ALWAYS initiate overtime, unless EVERYONE has finished the race!
2018         if(wc == WINNING_YES || wc == WINNING_STARTSUDDENDEATHOVERTIME)
2019         // do NOT support equality when the laps are all raced!
2020                 return WINNING_STARTSUDDENDEATHOVERTIME;
2021         else
2022                 return WINNING_NEVER;
2023 }
2024
2025 float WinningCondition_QualifyingThenRace(float limit)
2026 {
2027         float wc;
2028         wc = WinningCondition_Scores(limit, 0);
2029
2030         // NEVER initiate overtime
2031         if(wc == WINNING_YES || wc == WINNING_STARTSUDDENDEATHOVERTIME)
2032         {
2033                 return WINNING_YES;
2034         }
2035
2036         return wc;
2037 }
2038
2039 float WinningCondition_RanOutOfSpawns()
2040 {
2041         entity head;
2042
2043         if(have_team_spawns <= 0)
2044                 return WINNING_NO;
2045
2046         if(autocvar_g_spawn_useallspawns <= 0)
2047                 return WINNING_NO;
2048
2049         if(!some_spawn_has_been_used)
2050                 return WINNING_NO;
2051
2052         team1_score = team2_score = team3_score = team4_score = 0;
2053
2054         FOR_EACH_PLAYER(head) if(head.deadflag == DEAD_NO)
2055         {
2056                 if(head.team == COLOR_TEAM1)
2057                         team1_score = 1;
2058                 else if(head.team == COLOR_TEAM2)
2059                         team2_score = 1;
2060                 else if(head.team == COLOR_TEAM3)
2061                         team3_score = 1;
2062                 else if(head.team == COLOR_TEAM4)
2063                         team4_score = 1;
2064         }
2065
2066         for(head = world; (head = find(head, classname, "info_player_deathmatch")) != world; )
2067         {
2068                 if(head.team == COLOR_TEAM1)
2069                         team1_score = 1;
2070                 else if(head.team == COLOR_TEAM2)
2071                         team2_score = 1;
2072                 else if(head.team == COLOR_TEAM3)
2073                         team3_score = 1;
2074                 else if(head.team == COLOR_TEAM4)
2075                         team4_score = 1;
2076         }
2077
2078         ClearWinners();
2079         if(team1_score + team2_score + team3_score + team4_score == 0)
2080         {
2081                 checkrules_equality = TRUE;
2082                 return WINNING_YES;
2083         }
2084         else if(team1_score + team2_score + team3_score + team4_score == 1)
2085         {
2086                 float t, i;
2087                 if(team1_score)
2088                         t = COLOR_TEAM1;
2089                 else if(team2_score)
2090                         t = COLOR_TEAM2;
2091                 else if(team3_score)
2092                         t = COLOR_TEAM3;
2093                 else // if(team4_score)
2094                         t = COLOR_TEAM4;
2095                 CheckAllowedTeams(world);
2096                 for(i = 0; i < MAX_TEAMSCORE; ++i)
2097                 {
2098                         if(t != COLOR_TEAM1) if(c1 >= 0) TeamScore_AddToTeam(COLOR_TEAM1, i, -1000);
2099                         if(t != COLOR_TEAM2) if(c2 >= 0) TeamScore_AddToTeam(COLOR_TEAM2, i, -1000);
2100                         if(t != COLOR_TEAM3) if(c3 >= 0) TeamScore_AddToTeam(COLOR_TEAM3, i, -1000);
2101                         if(t != COLOR_TEAM4) if(c4 >= 0) TeamScore_AddToTeam(COLOR_TEAM4, i, -1000);
2102                 }
2103
2104                 AddWinners(team, t);
2105                 return WINNING_YES;
2106         }
2107         else
2108                 return WINNING_NO;
2109 }
2110
2111 /*
2112 ============
2113 CheckRules_World
2114
2115 Exit deathmatch games upon conditions
2116 ============
2117 */
2118 void ReadyRestart();
2119 void CheckRules_World()
2120 {
2121         float timelimit;
2122         float fraglimit;
2123         float leadlimit;
2124
2125         VoteThink();
2126         MapVote_Think();
2127
2128         SetDefaultAlpha();
2129
2130         /*
2131         MapVote_Think should now do that part
2132         if (intermission_running)
2133                 if (time >= intermission_exittime + 60)
2134                 {
2135                         if(!DoNextMapOverride())
2136                                 GotoNextMap();
2137                         return;
2138                 }
2139         */
2140
2141         if (gameover)   // someone else quit the game already
2142         {
2143                 if(player_count == 0) // Nobody there? Then let's go to the next map
2144                         MapVote_Start();
2145                         // this will actually check the player count in the next frame
2146                         // again, but this shouldn't hurt
2147                 return;
2148         }
2149
2150         timelimit = autocvar_timelimit * 60;
2151         fraglimit = autocvar_fraglimit;
2152         leadlimit = autocvar_leadlimit;
2153
2154         if(inWarmupStage || time <= game_starttime) // NOTE: this is <= to prevent problems in the very tic where the game starts
2155         {
2156                 if(timelimit > 0)
2157                         timelimit = 0; // timelimit is not made for warmup
2158                 if(fraglimit > 0)
2159                         fraglimit = 0; // no fraglimit for now
2160                 leadlimit = 0; // no leadlimit for now
2161         }
2162
2163         if(timelimit > 0)
2164         {
2165                 timelimit += game_starttime;
2166         }
2167         else if (timelimit < 0)
2168         {
2169                 // endmatch
2170                 NextLevel();
2171                 return;
2172         }
2173
2174         if(g_onslaught)
2175                 timelimit = 0; // ONS has its own overtime rule
2176
2177         float wantovertime;
2178         wantovertime = 0;
2179
2180         if(timelimit > game_starttime)
2181                 game_completion_ratio = (time - game_starttime) / (timelimit - game_starttime);
2182         else
2183                 game_completion_ratio = 0;
2184
2185         if(checkrules_suddendeathend)
2186         {
2187                 if(!checkrules_suddendeathwarning)
2188                 {
2189                         checkrules_suddendeathwarning = TRUE;
2190                         if(g_race && !g_race_qualifying)
2191                                 bcenterprint("^3Everyone, finish your lap! The race is over!");
2192                         else
2193                                 bcenterprint("^3Now playing ^1OVERTIME^3!\n\n^3Keep fragging until we have a ^1winner^3!");
2194                 }
2195         }
2196         else
2197         {
2198                 if (timelimit && time >= timelimit)
2199                 {
2200                         if(g_race && (g_race_qualifying == 2) && timelimit > 0)
2201                         {
2202                                 float totalplayers;
2203                                 float playerswithlaps;
2204                                 float readyplayers;
2205                                 entity head;
2206                                 totalplayers = playerswithlaps = readyplayers = 0;
2207                                 FOR_EACH_PLAYER(head)
2208                                 {
2209                                         ++totalplayers;
2210                                         if(PlayerScore_Add(head, SP_RACE_FASTEST, 0))
2211                                                 ++playerswithlaps;
2212                                         if(head.ready)
2213                                                 ++readyplayers;
2214                                 }
2215
2216                                 // at least 2 of the players have completed a lap: start the RACE
2217                                 // otherwise, the players should end the qualifying on their own
2218                                 if(readyplayers || playerswithlaps >= 2)
2219                                 {
2220                                         checkrules_suddendeathend = 0;
2221                                         ReadyRestart(); // go to race
2222                                         return;
2223                                 }
2224                                 else
2225                                         wantovertime |= InitiateSuddenDeath();
2226                         }
2227                         else
2228                                 wantovertime |= InitiateSuddenDeath();
2229                 }
2230         }
2231
2232         if (checkrules_suddendeathend && time >= checkrules_suddendeathend)
2233         {
2234                 NextLevel();
2235                 return;
2236         }
2237
2238         float checkrules_status;
2239         checkrules_status = WinningCondition_RanOutOfSpawns();
2240         if(checkrules_status == WINNING_YES)
2241         {
2242                 bprint("Hey! Someone ran out of spawns!\n");
2243         }
2244         else if(g_race && !g_race_qualifying && timelimit >= 0)
2245         {
2246                 checkrules_status = WinningCondition_Race(fraglimit);
2247                 //print("WC_RACE yields ", ftos(checkrules_status), "\n");
2248         }
2249         else if(g_race && g_race_qualifying == 2 && timelimit >= 0)
2250         {
2251                 checkrules_status = WinningCondition_QualifyingThenRace(fraglimit);
2252                 //print("WC_QUALIFYING_THEN_RACE yields ", ftos(checkrules_status), "\n");
2253         }
2254         else if(g_assault)
2255         {
2256                 checkrules_status = WinningCondition_Assault(); // TODO remove this?
2257         }
2258         else if(g_lms)
2259         {
2260                 checkrules_status = WinningCondition_LMS();
2261         }
2262         else if (g_onslaught)
2263         {
2264                 checkrules_status = WinningCondition_Onslaught(); // TODO remove this?
2265         }
2266         else
2267         {
2268                 checkrules_status = WinningCondition_Scores(fraglimit, leadlimit);
2269                 //print("WC_SCORES yields ", ftos(checkrules_status), "\n");
2270         }
2271
2272         if(checkrules_status == WINNING_STARTSUDDENDEATHOVERTIME)
2273         {
2274                 checkrules_status = WINNING_NEVER;
2275                 checkrules_overtimesadded = -1;
2276                 wantovertime |= InitiateSuddenDeath();
2277         }
2278
2279         if(checkrules_status == WINNING_NEVER)
2280                 // equality cases! Nobody wins if the overtime ends in a draw.
2281                 ClearWinners();
2282
2283         if(wantovertime)
2284         {
2285                 if(checkrules_status == WINNING_NEVER)
2286                         InitiateOvertime();
2287                 else
2288                         checkrules_status = WINNING_YES;
2289         }
2290
2291         if(checkrules_suddendeathend)
2292                 if(checkrules_status != WINNING_NEVER || time >= checkrules_suddendeathend)
2293                         checkrules_status = WINNING_YES;
2294
2295         if(checkrules_status == WINNING_YES)
2296         {
2297                 //print("WINNING\n");
2298                 NextLevel();
2299         }
2300 }
2301
2302 float mapvote_nextthink;
2303 float mapvote_initialized;
2304 float mapvote_keeptwotime;
2305 float mapvote_timeout;
2306 string mapvote_message;
2307 #define MAPVOTE_SCREENSHOT_DIRS_COUNT 4
2308 string mapvote_screenshot_dirs[MAPVOTE_SCREENSHOT_DIRS_COUNT];
2309 float mapvote_screenshot_dirs_count;
2310
2311 float mapvote_count;
2312 float mapvote_count_real;
2313 string mapvote_maps[MAPVOTE_COUNT];
2314 float mapvote_maps_screenshot_dir[MAPVOTE_COUNT];
2315 string mapvote_maps_pakfile[MAPVOTE_COUNT];
2316 float mapvote_maps_suggested[MAPVOTE_COUNT];
2317 string mapvote_suggestions[MAPVOTE_COUNT];
2318 float mapvote_suggestion_ptr;
2319 float mapvote_voters;
2320 float mapvote_selections[MAPVOTE_COUNT];
2321 float mapvote_run;
2322 float mapvote_detail;
2323 float mapvote_abstain;
2324 .float mapvote;
2325
2326 void MapVote_ClearAllVotes()
2327 {
2328         FOR_EACH_CLIENT(other)
2329                 other.mapvote = 0;
2330 }
2331
2332 string MapVote_Suggest(string m)
2333 {
2334         float i;
2335         if(m == "")
2336                 return "That's not how to use this command.";
2337         if(!autocvar_g_maplist_votable_suggestions)
2338                 return "Suggestions are not accepted on this server.";
2339         if(mapvote_initialized)
2340                 return "Can't suggest - voting is already in progress!";
2341         m = MapInfo_FixName(m);
2342         if not(m)
2343                 return "The map you suggested is not available on this server.";
2344         if(!autocvar_g_maplist_votable_suggestions_override_mostrecent)
2345                 if(Map_IsRecent(m))
2346                         return "This server does not allow for recent maps to be played again. Please be patient for some rounds.";
2347
2348         if(!MapInfo_CheckMap(m))
2349                 return "The map you suggested does not support the current game mode.";
2350         for(i = 0; i < mapvote_suggestion_ptr; ++i)
2351                 if(mapvote_suggestions[i] == m)
2352                         return "This map was already suggested.";
2353         if(mapvote_suggestion_ptr >= MAPVOTE_COUNT)
2354         {
2355                 i = floor(random() * mapvote_suggestion_ptr);
2356         }
2357         else
2358         {
2359                 i = mapvote_suggestion_ptr;
2360                 mapvote_suggestion_ptr += 1;
2361         }
2362         if(mapvote_suggestions[i] != "")
2363                 strunzone(mapvote_suggestions[i]);
2364         mapvote_suggestions[i] = strzone(m);
2365         if(autocvar_sv_eventlog)
2366                 GameLogEcho(strcat(":vote:suggested:", m, ":", ftos(self.playerid)));
2367         return strcat("Suggestion of ", m, " accepted.");
2368 }
2369
2370 void MapVote_AddVotable(string nextMap, float isSuggestion)
2371 {
2372         float j, i, o;
2373         string pakfile, mapfile;
2374
2375         if(nextMap == "")
2376                 return;
2377         for(j = 0; j < mapvote_count; ++j)
2378                 if(mapvote_maps[j] == nextMap)
2379                         return;
2380         // suggestions might be no longer valid/allowed after gametype switch!
2381         if(isSuggestion)
2382                 if(!MapInfo_CheckMap(nextMap))
2383                         return;
2384         mapvote_maps[mapvote_count] = strzone(nextMap);
2385         mapvote_maps_suggested[mapvote_count] = isSuggestion;
2386
2387         pakfile = string_null;
2388         for(i = 0; i < mapvote_screenshot_dirs_count; ++i)
2389         {
2390                 mapfile = strcat(mapvote_screenshot_dirs[i], "/", mapvote_maps[i]);
2391                 pakfile = whichpack(strcat(mapfile, ".tga"));
2392                 if(pakfile == "")
2393                         pakfile = whichpack(strcat(mapfile, ".jpg"));
2394                 if(pakfile == "")
2395                         pakfile = whichpack(strcat(mapfile, ".png"));
2396                 if(pakfile != "")
2397                         break;
2398         }
2399         if(i >= mapvote_screenshot_dirs_count)
2400                 i = 0; // FIXME maybe network this error case, as that means there is no mapshot on the server?
2401         for(o = strstr(pakfile, "/", 0)+1; o > 0; o = strstr(pakfile, "/", 0)+1)
2402                 pakfile = substring(pakfile, o, -1);
2403
2404         mapvote_maps_screenshot_dir[mapvote_count] = i;
2405         mapvote_maps_pakfile[mapvote_count] = strzone(pakfile);
2406
2407         mapvote_count += 1;
2408 }
2409
2410 void MapVote_Spawn();
2411 void MapVote_Init()
2412 {
2413         float i;
2414         float nmax, smax;
2415
2416         MapVote_ClearAllVotes();
2417
2418         mapvote_count = 0;
2419         mapvote_detail = !autocvar_g_maplist_votable_nodetail;
2420         mapvote_abstain = autocvar_g_maplist_votable_abstain;
2421
2422         if(mapvote_abstain)
2423                 nmax = min(MAPVOTE_COUNT - 1, autocvar_g_maplist_votable);
2424         else
2425                 nmax = min(MAPVOTE_COUNT, autocvar_g_maplist_votable);
2426         smax = min3(nmax, autocvar_g_maplist_votable_suggestions, mapvote_suggestion_ptr);
2427
2428         // we need this for AddVotable, as that cycles through the screenshot dirs
2429         mapvote_screenshot_dirs_count = tokenize_console(autocvar_g_maplist_votable_screenshot_dir);
2430         if(mapvote_screenshot_dirs_count == 0)
2431                 mapvote_screenshot_dirs_count = tokenize_console("maps levelshots");
2432         mapvote_screenshot_dirs_count = min(mapvote_screenshot_dirs_count, MAPVOTE_SCREENSHOT_DIRS_COUNT);
2433         for(i = 0; i < mapvote_screenshot_dirs_count; ++i)
2434                 mapvote_screenshot_dirs[i] = strzone(argv(i));
2435
2436         if(mapvote_suggestion_ptr)
2437                 for(i = 0; i < 100 && mapvote_count < smax; ++i)
2438                         MapVote_AddVotable(mapvote_suggestions[floor(random() * mapvote_suggestion_ptr)], TRUE);
2439
2440         for(i = 0; i < 100 && mapvote_count < nmax; ++i)
2441                 MapVote_AddVotable(GetNextMap(), FALSE);
2442
2443         if(mapvote_count == 0)
2444         {
2445                 bprint( "Maplist contains no single playable map!  Resetting it to default map list.\n" );
2446                 cvar_set("g_maplist", MapInfo_ListAllAllowedMaps(MapInfo_RequiredFlags(), MapInfo_ForbiddenFlags()));
2447                 if(autocvar_g_maplist_shuffle)
2448                         ShuffleMaplist();
2449                 localcmd("\nmenu_cmd sync\n");
2450                 for(i = 0; i < 100 && mapvote_count < nmax; ++i)
2451                         MapVote_AddVotable(GetNextMap(), FALSE);
2452         }
2453
2454         mapvote_count_real = mapvote_count;
2455         if(mapvote_abstain)
2456                 MapVote_AddVotable("don't care", 0);
2457
2458         //dprint("mapvote count is ", ftos(mapvote_count), "\n");
2459
2460         mapvote_keeptwotime = time + autocvar_g_maplist_votable_keeptwotime;
2461         mapvote_timeout = time + autocvar_g_maplist_votable_timeout;
2462         if(mapvote_count_real < 3 || mapvote_keeptwotime <= time)
2463                 mapvote_keeptwotime = 0;
2464         mapvote_message = "Choose a map and press its key!";
2465
2466         MapVote_Spawn();
2467 }
2468
2469 void MapVote_SendPicture(float id)
2470 {
2471         msg_entity = self;
2472         WriteByte(MSG_ONE, SVC_TEMPENTITY);
2473         WriteByte(MSG_ONE, TE_CSQC_PICTURE);
2474         WriteByte(MSG_ONE, id);
2475         WritePicture(MSG_ONE, strcat(mapvote_screenshot_dirs[mapvote_maps_screenshot_dir[id]], "/", mapvote_maps[id]), 3072);
2476 }
2477
2478 float MapVote_GetMapMask()
2479 {
2480         float mask, i, power;
2481         mask = 0;
2482         for(i = 0, power = 1; i < mapvote_count; ++i, power *= 2)
2483                 if(mapvote_maps[i] != "")
2484                         mask |= power;
2485         return mask;
2486 }
2487
2488 entity mapvote_ent;
2489 float MapVote_SendEntity(entity to, float sf)
2490 {
2491         float i;
2492
2493         if(sf & 1)
2494                 sf &~= 2; // if we send 1, we don't need to also send 2
2495
2496         WriteByte(MSG_ENTITY, ENT_CLIENT_MAPVOTE);
2497         WriteByte(MSG_ENTITY, sf);
2498
2499         if(sf & 1)
2500         {
2501                 // flag 1 == initialization
2502                 for(i = 0; i < mapvote_screenshot_dirs_count; ++i)
2503                         WriteString(MSG_ENTITY, mapvote_screenshot_dirs[i]);
2504                 WriteString(MSG_ENTITY, "");
2505                 WriteByte(MSG_ENTITY, mapvote_count);
2506                 WriteByte(MSG_ENTITY, mapvote_abstain);
2507                 WriteByte(MSG_ENTITY, mapvote_detail);
2508                 WriteCoord(MSG_ENTITY, mapvote_timeout);
2509                 if(mapvote_count <= 8)
2510                         WriteByte(MSG_ENTITY, MapVote_GetMapMask());
2511                 else
2512                         WriteShort(MSG_ENTITY, MapVote_GetMapMask());
2513                 for(i = 0; i < mapvote_count; ++i)
2514                         if(mapvote_maps[i] != "")
2515                         {
2516                                 if(mapvote_abstain && i == mapvote_count - 1)
2517                                 {
2518                                         WriteString(MSG_ENTITY, ""); // abstain needs no text
2519                                         WriteString(MSG_ENTITY, ""); // abstain needs no pack
2520                                         WriteByte(MSG_ENTITY, 0); // abstain needs no screenshot dir
2521                                 }
2522                                 else
2523                                 {
2524                                         WriteString(MSG_ENTITY, mapvote_maps[i]);
2525                                         WriteString(MSG_ENTITY, mapvote_maps_pakfile[i]);
2526                                         WriteByte(MSG_ENTITY, mapvote_maps_screenshot_dir[i]);
2527                                 }
2528                         }
2529         }
2530
2531         if(sf & 2)
2532         {
2533                 // flag 2 == update of mask
2534                 if(mapvote_count <= 8)
2535                         WriteByte(MSG_ENTITY, MapVote_GetMapMask());
2536                 else
2537                         WriteShort(MSG_ENTITY, MapVote_GetMapMask());
2538         }
2539
2540         if(sf & 4)
2541         {
2542                 if(mapvote_detail)
2543                         for(i = 0; i < mapvote_count; ++i)
2544                                 if(mapvote_maps[i] != "")
2545                                         WriteByte(MSG_ENTITY, mapvote_selections[i]);
2546
2547                 WriteByte(MSG_ENTITY, to.mapvote);
2548         }
2549
2550         return TRUE;
2551 }
2552
2553 void MapVote_Spawn()
2554 {
2555         Net_LinkEntity(mapvote_ent = spawn(), FALSE, 0, MapVote_SendEntity);
2556 }
2557
2558 void MapVote_TouchMask()
2559 {
2560         mapvote_ent.SendFlags |= 2;
2561 }
2562
2563 void MapVote_TouchVotes(entity voter)
2564 {
2565         mapvote_ent.SendFlags |= 4;
2566 }
2567
2568 float MapVote_Finished(float mappos)
2569 {
2570         string result;
2571         float i;
2572         float didntvote;
2573
2574         if(autocvar_sv_eventlog)
2575         {
2576                 result = strcat(":vote:finished:", mapvote_maps[mappos]);
2577                 result = strcat(result, ":", ftos(mapvote_selections[mappos]), "::");
2578                 didntvote = mapvote_voters;
2579                 for(i = 0; i < mapvote_count; ++i)
2580                         if(mapvote_maps[i] != "")
2581                         {
2582                                 didntvote -= mapvote_selections[i];
2583                                 if(i != mappos)
2584                                 {
2585                                         result = strcat(result, ":", mapvote_maps[i]);
2586                                         result = strcat(result, ":", ftos(mapvote_selections[i]));
2587                                 }
2588                         }
2589                 result = strcat(result, ":didn't vote:", ftos(didntvote));
2590
2591                 GameLogEcho(result);
2592                 if(mapvote_maps_suggested[mappos])
2593                         GameLogEcho(strcat(":vote:suggestion_accepted:", mapvote_maps[mappos]));
2594         }
2595
2596         FOR_EACH_REALCLIENT(other)
2597                 FixClientCvars(other);
2598
2599         Map_Goto_SetStr(mapvote_maps[mappos]);
2600         Map_Goto(0);
2601         alreadychangedlevel = TRUE;
2602         return TRUE;
2603 }
2604 void MapVote_CheckRules_1()
2605 {
2606         float i;
2607
2608         for(i = 0; i < mapvote_count; ++i) if(mapvote_maps[i] != "")
2609         {
2610                 //dprint("Map ", ftos(i), ": "); dprint(mapvote_maps[i], "\n");
2611                 mapvote_selections[i] = 0;
2612         }
2613
2614         mapvote_voters = 0;
2615         FOR_EACH_REALCLIENT(other)
2616         {
2617                 ++mapvote_voters;
2618                 if(other.mapvote)
2619                 {
2620                         i = other.mapvote - 1;
2621                         //dprint("Player ", other.netname, " vote = ", ftos(other.mapvote - 1), "\n");
2622                         mapvote_selections[i] = mapvote_selections[i] + 1;
2623                 }
2624         }
2625 }
2626
2627 float MapVote_CheckRules_2()
2628 {
2629         float i;
2630         float firstPlace, secondPlace;
2631         float firstPlaceVotes, secondPlaceVotes;
2632         float mapvote_voters_real;
2633         string result;
2634
2635         if(mapvote_count_real == 1)
2636                 return MapVote_Finished(0);
2637
2638         mapvote_voters_real = mapvote_voters;
2639         if(mapvote_abstain)
2640                 mapvote_voters_real -= mapvote_selections[mapvote_count - 1];
2641
2642         RandomSelection_Init();
2643         for(i = 0; i < mapvote_count_real; ++i) if(mapvote_maps[i] != "")
2644                 RandomSelection_Add(world, i, string_null, 1, mapvote_selections[i]);
2645         firstPlace = RandomSelection_chosen_float;
2646         firstPlaceVotes = RandomSelection_best_priority;
2647         //dprint("First place: ", ftos(firstPlace), "\n");
2648         //dprint("First place votes: ", ftos(firstPlaceVotes), "\n");
2649
2650         RandomSelection_Init();
2651         for(i = 0; i < mapvote_count_real; ++i) if(mapvote_maps[i] != "")
2652                 if(i != firstPlace)
2653                         RandomSelection_Add(world, i, string_null, 1, mapvote_selections[i]);
2654         secondPlace = RandomSelection_chosen_float;
2655         secondPlaceVotes = RandomSelection_best_priority;
2656         //dprint("Second place: ", ftos(secondPlace), "\n");
2657         //dprint("Second place votes: ", ftos(secondPlaceVotes), "\n");
2658
2659         if(firstPlace == -1)
2660                 error("No first place in map vote... WTF?");
2661
2662         if(secondPlace == -1 || time > mapvote_timeout || (mapvote_voters_real - firstPlaceVotes) < firstPlaceVotes)
2663                 return MapVote_Finished(firstPlace);
2664
2665         if(mapvote_keeptwotime)
2666                 if(time > mapvote_keeptwotime || (mapvote_voters_real - firstPlaceVotes - secondPlaceVotes) < secondPlaceVotes)
2667                 {
2668                         float didntvote;
2669                         MapVote_TouchMask();
2670                         mapvote_message = "Now decide between the TOP TWO!";
2671                         mapvote_keeptwotime = 0;
2672                         result = strcat(":vote:keeptwo:", mapvote_maps[firstPlace]);
2673                         result = strcat(result, ":", ftos(firstPlaceVotes));
2674                         result = strcat(result, ":", mapvote_maps[secondPlace]);
2675                         result = strcat(result, ":", ftos(secondPlaceVotes), "::");
2676                         didntvote = mapvote_voters;
2677                         for(i = 0; i < mapvote_count; ++i)
2678                                 if(mapvote_maps[i] != "")
2679                                 {
2680                                         didntvote -= mapvote_selections[i];
2681                                         if(i != firstPlace)
2682                                                 if(i != secondPlace)
2683                                                 {
2684                                                         result = strcat(result, ":", mapvote_maps[i]);
2685                                                         result = strcat(result, ":", ftos(mapvote_selections[i]));
2686                                                         if(i < mapvote_count_real)
2687                                                         {
2688                                                                 strunzone(mapvote_maps[i]);
2689                                                                 mapvote_maps[i] = "";
2690                                                                 strunzone(mapvote_maps_pakfile[i]);
2691                                                                 mapvote_maps_pakfile[i] = "";
2692                                                         }
2693                                                 }
2694                                 }
2695                         result = strcat(result, ":didn't vote:", ftos(didntvote));
2696                         if(autocvar_sv_eventlog)
2697                                 GameLogEcho(result);
2698                 }
2699
2700         return FALSE;
2701 }
2702 void MapVote_Tick()
2703 {
2704         float keeptwo;
2705         float totalvotes;
2706
2707         keeptwo = mapvote_keeptwotime;
2708         MapVote_CheckRules_1(); // count
2709         if(MapVote_CheckRules_2()) // decide
2710                 return;
2711
2712         totalvotes = 0;
2713         FOR_EACH_REALCLIENT(other)
2714         {
2715                 // hide scoreboard again
2716                 if(other.health != 2342)
2717                 {
2718                         other.health = 2342;
2719                         other.impulse = 0;
2720                         if(clienttype(other) == CLIENTTYPE_REAL)
2721                         {
2722                                 msg_entity = other;
2723                                 WriteByte(MSG_ONE, SVC_FINALE);
2724                                 WriteString(MSG_ONE, "");
2725                         }
2726                 }
2727
2728                 // clear possibly invalid votes
2729                 if(mapvote_maps[other.mapvote - 1] == "")
2730                         other.mapvote = 0;
2731                 // use impulses as new vote
2732                 if(other.impulse >= 1 && other.impulse <= mapvote_count)
2733                         if(mapvote_maps[other.impulse - 1] != "")
2734                         {
2735                                 other.mapvote = other.impulse;
2736                                 MapVote_TouchVotes(other);
2737                         }
2738                 other.impulse = 0;
2739
2740                 if(other.mapvote)
2741                         ++totalvotes;
2742         }
2743
2744         MapVote_CheckRules_1(); // just count
2745 }
2746 void MapVote_Start()
2747 {
2748         if(mapvote_run)
2749                 return;
2750
2751         // wait for stats to be sent first
2752         if(!playerstats_waitforme)
2753                 return;
2754
2755         MapInfo_Enumerate();
2756         if(MapInfo_FilterGametype(MapInfo_CurrentGametype(), MapInfo_CurrentFeatures(), MapInfo_RequiredFlags(), MapInfo_ForbiddenFlags(), 1))
2757                 mapvote_run = TRUE;
2758 }
2759 void MapVote_Think()
2760 {
2761         if(!mapvote_run)
2762                 return;
2763
2764         if(alreadychangedlevel)
2765                 return;
2766
2767         if(time < mapvote_nextthink)
2768                 return;
2769         //dprint("tick\n");
2770
2771         mapvote_nextthink = time + 0.5;
2772
2773         if(!mapvote_initialized)
2774         {
2775                 if(autocvar_rescan_pending == 1)
2776                 {
2777                         cvar_set("rescan_pending", "2");
2778                         localcmd("fs_rescan\nrescan_pending 3\n");
2779                         return;
2780                 }
2781                 else if(autocvar_rescan_pending == 2)
2782                 {
2783                         return;
2784                 }
2785                 else if(autocvar_rescan_pending == 3)
2786                 {
2787                         // now build missing mapinfo files
2788                         if(!MapInfo_FilterGametype(MapInfo_CurrentGametype(), MapInfo_CurrentFeatures(), MapInfo_RequiredFlags(), MapInfo_ForbiddenFlags(), 1))
2789                                 return;
2790
2791                         // we're done, start the timer
2792                         cvar_set("rescan_pending", "0");
2793                 }
2794
2795                 mapvote_initialized = TRUE;
2796                 if(DoNextMapOverride(0))
2797                         return;
2798                 if(!autocvar_g_maplist_votable || player_count <= 0)
2799                 {
2800                         GotoNextMap(0);
2801                         return;
2802                 }
2803                 MapVote_Init();
2804         }
2805
2806         MapVote_Tick();
2807 }
2808
2809 string GotoMap(string m)
2810 {
2811         if(!MapInfo_CheckMap(m))
2812                 return "The map you chose is not available on this server.";
2813         cvar_set("nextmap", m);
2814         cvar_set("timelimit", "-1");
2815         if(mapvote_initialized || alreadychangedlevel)
2816         {
2817                 if(DoNextMapOverride(0))
2818                         return "Map switch initiated.";
2819                 else
2820                         return "Hm... no. For some reason I like THIS map more.";
2821         }
2822         else
2823                 return "Map switch will happen after scoreboard.";
2824 }
2825
2826
2827 void EndFrame()
2828 {
2829         float altime;
2830         FOR_EACH_REALCLIENT(self)
2831         {
2832                 if(self.classname == "spectator")
2833                 {
2834                         if(self.enemy.typehitsound)
2835                                 self.typehit_time = time;
2836                         else if(self.enemy.hitsound)
2837                                 self.hit_time = time;
2838                 }
2839                 else
2840                 {
2841                         if(self.typehitsound)
2842                                 self.typehit_time = time;
2843                         else if(self.hitsound)
2844                                 self.hit_time = time;
2845                 }
2846         }
2847         altime = time + frametime * (1 + autocvar_g_antilag_nudge);
2848         // add 1 frametime because after this, engine SV_Physics
2849         // increases time by a frametime and then networks the frame
2850         // add another frametime because client shows everything with
2851         // 1 frame of lag (cl_nolerp 0). The last +1 however should not be
2852         // needed!
2853         FOR_EACH_CLIENT(self)
2854         {
2855                 self.hitsound = FALSE;
2856                 self.typehitsound = FALSE;
2857                 antilag_record(self, altime);
2858         }
2859 }
2860
2861
2862 /*
2863  * RedirectionThink:
2864  * returns TRUE if redirecting
2865  */
2866 float redirection_timeout;
2867 float redirection_nextthink;
2868 float RedirectionThink()
2869 {
2870         float clients_found;
2871
2872         if(redirection_target == "")
2873                 return FALSE;
2874
2875         if(!redirection_timeout)
2876         {
2877                 cvar_set("sv_public", "-2");
2878                 redirection_timeout = time + 0.6; // this will only try twice... should be able to keep more clients
2879                 if(redirection_target == "self")
2880                         bprint("^3SERVER NOTICE:^7 restarting the server\n");
2881                 else
2882                         bprint("^3SERVER NOTICE:^7 redirecting everyone to ", redirection_target, "\n");
2883         }
2884
2885         if(time < redirection_nextthink)
2886                 return TRUE;
2887
2888         redirection_nextthink = time + 1;
2889
2890         clients_found = 0;
2891         FOR_EACH_REALCLIENT(self)
2892         {
2893                 // TODO add timer
2894                 print("Redirecting: sending connect command to ", self.netname, "\n");
2895                 if(redirection_target == "self")
2896                         stuffcmd(self, "\ndisconnect; defer ", ftos(autocvar_quit_and_redirect_timer), " reconnect\n");
2897                 else
2898                         stuffcmd(self, strcat("\ndisconnect; defer ", ftos(autocvar_quit_and_redirect_timer), " \"connect ", redirection_target, "\"\n"));
2899                 ++clients_found;
2900         }
2901
2902         print("Redirecting: ", ftos(clients_found), " clients left.\n");
2903
2904         if(time > redirection_timeout || clients_found == 0)
2905                 localcmd("\nwait; wait; wait; quit\n");
2906
2907         return TRUE;
2908 }
2909
2910 void TargetMusic_RestoreGame();
2911 void RestoreGame()
2912 {
2913         // Loaded from a save game
2914         // some things then break, so let's work around them...
2915
2916         // Progs DB (capture records)
2917         ServerProgsDB = db_load(strcat("server.db", autocvar_sessionid));
2918
2919         // Mapinfo
2920         MapInfo_Shutdown();
2921         MapInfo_Enumerate();
2922         MapInfo_FilterGametype(MapInfo_CurrentGametype(), MapInfo_CurrentFeatures(), MapInfo_RequiredFlags(), MapInfo_ForbiddenFlags(), 1);
2923         WeaponStats_Init();
2924
2925         TargetMusic_RestoreGame();
2926 }
2927
2928 void Shutdown()
2929 {
2930         entity e;
2931
2932         gameover = 2;
2933
2934         if(world_initialized > 0)
2935         {
2936                 world_initialized = 0;
2937                 print("Saving persistent data...\n");
2938                 Ban_SaveBans();
2939
2940                 PlayerStats_EndMatch(0);
2941                 FOR_EACH_CLIENT(e)
2942                         PlayerStats_AddGlobalInfo(e);
2943                 PlayerStats_Shutdown();
2944
2945                 if(!cheatcount_total)
2946                 {
2947                         if(autocvar_sv_db_saveasdump)
2948                                 db_dump(ServerProgsDB, strcat("server.db", autocvar_sessionid));
2949                         else
2950                                 db_save(ServerProgsDB, strcat("server.db", autocvar_sessionid));
2951                 }
2952                 if(autocvar_developer)
2953                 {
2954                         if(autocvar_sv_db_saveasdump)
2955                                 db_dump(TemporaryDB, "server-temp.db");
2956                         else
2957                                 db_save(TemporaryDB, "server-temp.db");
2958                 }
2959                 CheatShutdown(); // must be after cheatcount check
2960                 db_close(ServerProgsDB);
2961                 db_close(TemporaryDB);
2962                 print("done!\n");
2963                 // tell the bot system the game is ending now
2964                 bot_endgame();
2965
2966                 WeaponStats_Shutdown();
2967                 MapInfo_Shutdown();
2968         }
2969         else if(world_initialized == 0)
2970         {
2971                 print("NOTE: crashed before even initializing the world, not saving persistent data\n");
2972         }
2973 }