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