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