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