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