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