]> de.git.xonotic.org Git - xonotic/xonotic-data.pk3dir.git/blob - qcsrc/server/g_world.qc
Merge branch 'master' into terencehill/itemstime
[xonotic/xonotic-data.pk3dir.git] / qcsrc / server / g_world.qc
1 #define LATENCY_THINKRATE 10
2 .float latency_sum;
3 .float latency_cnt;
4 .float latency_time;
5 entity pingplreport;
6 void PingPLReport_Think()
7 {
8         float delta;
9         entity e;
10
11         delta = 3 / maxclients;
12         if(delta < sys_frametime)
13                 delta = 0;
14         self.nextthink = time + delta;
15
16         e = edict_num(self.cnt + 1);
17         if(IS_REAL_CLIENT(e))
18         {
19                 WriteByte(MSG_BROADCAST, SVC_TEMPENTITY);
20                 WriteByte(MSG_BROADCAST, TE_CSQC_PINGPLREPORT);
21                 WriteByte(MSG_BROADCAST, self.cnt);
22                 WriteShort(MSG_BROADCAST, max(1, e.ping));
23                 WriteByte(MSG_BROADCAST, ceil(e.ping_packetloss * 255));
24                 WriteByte(MSG_BROADCAST, ceil(e.ping_movementloss * 255));
25
26                 // record latency times for clients throughout the match so we can report it to playerstats
27                 if(time > (e.latency_time + LATENCY_THINKRATE))
28                 {
29                         e.latency_sum += e.ping;
30                         e.latency_cnt += 1;
31                         e.latency_time = time;
32                         //print("sum: ", ftos(e.latency_sum), ", cnt: ", ftos(e.latency_cnt), ", avg: ", ftos(e.latency_sum / e.latency_cnt), ".\n");
33                 }
34         }
35         else
36         {
37                 WriteByte(MSG_BROADCAST, SVC_TEMPENTITY);
38                 WriteByte(MSG_BROADCAST, TE_CSQC_PINGPLREPORT);
39                 WriteByte(MSG_BROADCAST, self.cnt);
40                 WriteShort(MSG_BROADCAST, 0);
41                 WriteByte(MSG_BROADCAST, 0);
42                 WriteByte(MSG_BROADCAST, 0);
43         }
44         self.cnt = (self.cnt + 1) % maxclients;
45 }
46 void PingPLReport_Spawn()
47 {
48         pingplreport = spawn();
49         pingplreport.classname = "pingplreport";
50         pingplreport.think = PingPLReport_Think;
51         pingplreport.nextthink = time;
52 }
53
54 const float SPAWNFLAG_NO_WAYPOINTS_FOR_ITEMS = 1;
55 string redirection_target;
56 float world_initialized;
57
58 string GetGametype();
59 void GotoNextMap(float reinit);
60 void ShuffleMaplist();
61 float(float reinit) DoNextMapOverride;
62
63 void SetDefaultAlpha()
64 {
65         if(autocvar_g_running_guns)
66         {
67                 default_player_alpha = -1;
68                 default_weapon_alpha = +1;
69         }
70         else if(g_cloaked)
71         {
72                 default_player_alpha = autocvar_g_balance_cloaked_alpha;
73                 default_weapon_alpha = default_player_alpha;
74         }
75         else
76         {
77                 default_player_alpha = autocvar_g_player_alpha;
78                 if(default_player_alpha == 0)
79                         default_player_alpha = 1;
80                 default_weapon_alpha = default_player_alpha;
81         }
82 }
83
84 void GotoFirstMap()
85 {
86         float n;
87         if(autocvar__sv_init)
88         {
89                 // cvar_set("_sv_init", "0");
90                 // we do NOT set this to 0 any more, so someone "accidentally" changing
91                 // to this "init" map on a dedicated server will cause no permanent
92                 // harm
93                 if(autocvar_g_maplist_shuffle)
94                         ShuffleMaplist();
95                 n = tokenizebyseparator(autocvar_g_maplist, " ");
96                 cvar_set("g_maplist_index", ftos(n - 1)); // jump to map 0 in GotoNextMap
97
98                 MapInfo_Enumerate();
99                 MapInfo_FilterGametype(MapInfo_CurrentGametype(), MapInfo_CurrentFeatures(), MapInfo_RequiredFlags(), MapInfo_ForbiddenFlags(), 0);
100
101                 if(!DoNextMapOverride(1))
102                         GotoNextMap(1);
103
104                 return;
105         }
106
107         if(time < 5)
108         {
109                 self.nextthink = time;
110         }
111         else
112         {
113                 self.nextthink = time + 1;
114                 print("Waiting for _sv_init being set to 1 by initialization scripts...\n");
115         }
116 }
117
118 void cvar_changes_init()
119 {
120         float h;
121         string k, v, d;
122         float n, i, adding, pureadding;
123
124         if(cvar_changes)
125                 strunzone(cvar_changes);
126         cvar_changes = string_null;
127         if(cvar_purechanges)
128                 strunzone(cvar_purechanges);
129         cvar_purechanges = string_null;
130         cvar_purechanges_count = 0;
131
132         h = buf_create();
133         buf_cvarlist(h, "", "_"); // exclude all _ cvars as they are temporary
134         n = buf_getsize(h);
135
136         adding = TRUE;
137         pureadding = TRUE;
138
139         for(i = 0; i < n; ++i)
140         {
141                 k = bufstr_get(h, i);
142
143 #define BADPREFIX(p) if(substring(k, 0, strlen(p)) == p) continue
144 #define BADPRESUFFIX(p,s) if(substring(k, 0, strlen(p)) == p && substring(k, -strlen(s), -1) == s) continue
145 #define BADCVAR(p) if(k == p) continue
146
147                 // general excludes and namespaces for server admin used cvars
148                 BADPREFIX("help_"); // PN's server has this listed as changed, let's not rat him out for THAT
149
150                 // internal
151                 BADPREFIX("csqc_");
152                 BADPREFIX("cvar_check_");
153                 BADCVAR("gamecfg");
154                 BADCVAR("g_configversion");
155                 BADCVAR("g_maplist_index");
156                 BADCVAR("halflifebsp");
157                 BADPREFIX("sv_world");
158
159                 // client
160                 BADPREFIX("chase_");
161                 BADPREFIX("cl_");
162                 BADPREFIX("con_");
163                 BADPREFIX("scoreboard_");
164                 BADPREFIX("g_campaign");
165                 BADPREFIX("g_waypointsprite_");
166                 BADPREFIX("gl_");
167                 BADPREFIX("joy");
168                 BADPREFIX("hud_");
169                 BADPREFIX("m_");
170                 BADPREFIX("menu_");
171                 BADPREFIX("net_slist_");
172                 BADPREFIX("r_");
173                 BADPREFIX("sbar_");
174                 BADPREFIX("scr_");
175                 BADPREFIX("snd_");
176                 BADPREFIX("show");
177                 BADPREFIX("sensitivity");
178                 BADPREFIX("userbind");
179                 BADPREFIX("v_");
180                 BADPREFIX("vid_");
181                 BADPREFIX("crosshair");
182                 BADCVAR("mod_q3bsp_lightmapmergepower");
183                 BADCVAR("mod_q3bsp_nolightmaps");
184                 BADCVAR("fov");
185                 BADCVAR("mastervolume");
186                 BADCVAR("volume");
187                 BADCVAR("bgmvolume");
188
189                 // private
190                 BADCVAR("developer");
191                 BADCVAR("log_dest_udp");
192                 BADCVAR("net_address");
193                 BADCVAR("net_address_ipv6");
194                 BADCVAR("port");
195                 BADCVAR("savedgamecfg");
196                 BADCVAR("serverconfig");
197                 BADCVAR("sv_autoscreenshot");
198                 BADCVAR("sv_heartbeatperiod");
199                 BADCVAR("sv_vote_master_password");
200                 BADCVAR("sys_colortranslation");
201                 BADCVAR("sys_specialcharactertranslation");
202                 BADCVAR("timeformat");
203                 BADCVAR("timestamps");
204                 BADPREFIX("developer_");
205                 BADPREFIX("g_ban_");
206                 BADPREFIX("g_banned_list");
207                 BADPREFIX("g_chat_flood_");
208                 BADPREFIX("g_ghost_items");
209                 BADPREFIX("g_playerstats_");
210                 BADPREFIX("g_respawn_ghosts");
211                 BADPREFIX("g_voice_flood_");
212                 BADPREFIX("log_file");
213                 BADPREFIX("rcon_");
214                 BADPREFIX("sv_allowdownloads");
215                 BADPREFIX("sv_autodemo");
216                 BADPREFIX("sv_curl_");
217                 BADPREFIX("sv_eventlog");
218                 BADPREFIX("sv_logscores_");
219                 BADPREFIX("sv_master");
220                 BADPREFIX("sv_weaponstats_");
221                 BADPREFIX("sv_waypointsprite_");
222                 BADCVAR("rescan_pending");
223
224                 // these can contain player IDs, so better hide
225                 BADPREFIX("g_forced_team_");
226
227                 // mapinfo
228                 BADCVAR("fraglimit");
229                 BADCVAR("g_assault");
230                 BADCVAR("g_ca");
231                 BADCVAR("g_ca_teams");
232                 BADCVAR("g_ctf");
233                 BADCVAR("g_cts");
234                 BADCVAR("g_dm");
235                 BADCVAR("g_domination");
236                 BADCVAR("g_domination_default_teams");
237                 BADCVAR("g_freezetag");
238                 BADCVAR("g_freezetag_teams");
239                 BADCVAR("g_keepaway");
240                 BADCVAR("g_keyhunt");
241                 BADCVAR("g_keyhunt_teams");
242                 BADCVAR("g_lms");
243                 BADCVAR("g_nexball");
244                 BADCVAR("g_onslaught");
245                 BADCVAR("g_race");
246                 BADCVAR("g_race_qualifying_timelimit");
247                 BADCVAR("g_tdm");
248                 BADCVAR("g_tdm_teams");
249                 BADCVAR("leadlimit");
250                 BADCVAR("nextmap");
251                 BADCVAR("teamplay");
252                 BADCVAR("timelimit");
253
254                 // long
255                 BADCVAR("hostname");
256                 BADCVAR("g_maplist");
257                 BADCVAR("g_maplist_mostrecent");
258                 BADCVAR("sv_motd");
259
260                 v = cvar_string(k);
261                 d = cvar_defstring(k);
262                 if(v == d)
263                         continue;
264
265                 if(adding)
266                 {
267                         cvar_changes = strcat(cvar_changes, k, " \"", v, "\" // \"", d, "\"\n");
268                         if(strlen(cvar_changes) > 16384)
269                         {
270                                 cvar_changes = "// too many settings have been changed to show them here\n";
271                                 adding = 0;
272                         }
273                 }
274
275                 // now check if the changes are actually gameplay relevant
276
277                 // does nothing visible
278                 BADCVAR("captureleadlimit_override");
279                 BADCVAR("g_balance_kill_delay");
280                 BADCVAR("g_ca_point_leadlimit");
281                 BADCVAR("g_ctf_captimerecord_always");
282                 BADCVAR("g_ctf_flag_glowtrails");
283                 BADCVAR("g_ctf_flag_pickup_verbosename");
284                 BADCVAR("g_domination_point_leadlimit");
285                 BADCVAR("g_forced_respawn");
286                 BADCVAR("g_keyhunt_point_leadlimit");
287                 BADPREFIX("g_mod_");
288                 BADCVAR("g_nexball_goalleadlimit");
289                 BADCVAR("leadlimit_and_fraglimit");
290                 BADCVAR("leadlimit_override");
291                 BADCVAR("pausable");
292                 BADCVAR("sv_allow_fullbright");
293                 BADCVAR("sv_checkforpacketsduringsleep");
294                 BADCVAR("sv_fraginfo");
295                 BADCVAR("sv_timeout");
296                 BADPREFIX("sv_timeout_");
297                 BADPREFIX("crypto_");
298                 BADPREFIX("g_chat_");
299                 BADPREFIX("g_ctf_captimerecord_");
300                 BADPREFIX("g_maplist_votable_");
301                 BADPREFIX("net_");
302                 BADPREFIX("prvm_");
303                 BADPREFIX("skill_");
304                 BADPREFIX("sv_cullentities_");
305                 BADPREFIX("sv_fraginfo_");
306                 BADPREFIX("sv_maxidle_");
307                 BADPREFIX("sv_vote_");
308                 BADPREFIX("timelimit_");
309                 BADCVAR("gameversion");
310                 BADPREFIX("gameversion_");
311                 BADCVAR("sv_namechangetimer");
312
313                 // allowed changes to server admins (please sync this to server.cfg)
314                 // vi commands:
315                 //   :/"impure"/,$d
316                 //   :g!,^\/\/[^ /],d
317                 //   :%s,//\([^ ]*\).*,BADCVAR("\1");,
318                 //   :%!sort
319                 // yes, this does contain some redundant stuff, don't really care
320                 BADCVAR("bot_config_file");
321                 BADCVAR("bot_number");
322                 BADCVAR("bot_prefix");
323                 BADCVAR("bot_suffix");
324                 BADCVAR("capturelimit_override");
325                 BADCVAR("fraglimit_override");
326                 BADCVAR("gametype");
327                 BADCVAR("g_antilag");
328                 BADCVAR("g_balance_teams");
329                 BADCVAR("g_balance_teams_prevent_imbalance");
330                 BADCVAR("g_balance_teams_scorefactor");
331                 BADCVAR("g_ban_sync_trusted_servers");
332                 BADCVAR("g_ban_sync_uri");
333                 BADCVAR("g_ca_teams_override");
334                 BADCVAR("g_ctf_ignore_frags");
335                 BADCVAR("g_domination_point_limit");
336                 BADCVAR("g_freezetag_teams_override");
337                 BADCVAR("g_friendlyfire");
338                 BADCVAR("g_fullbrightitems");
339                 BADCVAR("g_fullbrightplayers");
340                 BADCVAR("g_keyhunt_point_limit");
341                 BADCVAR("g_keyhunt_teams_override");
342                 BADCVAR("g_lms_lives_override");
343                 BADCVAR("g_maplist");
344                 BADCVAR("g_maplist_check_waypoints");
345                 BADCVAR("g_maplist_mostrecent_count");
346                 BADCVAR("g_maplist_shuffle");
347                 BADCVAR("g_maplist_votable");
348                 BADCVAR("g_maplist_votable_abstain");
349                 BADCVAR("g_maplist_votable_nodetail");
350                 BADCVAR("g_maplist_votable_suggestions");
351                 BADCVAR("g_maxplayers");
352                 BADCVAR("g_mirrordamage");
353                 BADCVAR("g_nexball_goallimit");
354                 BADCVAR("g_powerups");
355                 BADCVAR("g_start_delay");
356                 BADCVAR("g_warmup");
357                 BADCVAR("g_weapon_stay"); BADPRESUFFIX("g_", "_weapon_stay");
358                 BADCVAR("hostname");
359                 BADCVAR("log_file");
360                 BADCVAR("maxplayers");
361                 BADCVAR("minplayers");
362                 BADCVAR("net_address");
363                 BADCVAR("port");
364                 BADCVAR("rcon_password");
365                 BADCVAR("rcon_restricted_commands");
366                 BADCVAR("rcon_restricted_password");
367                 BADCVAR("skill");
368                 BADCVAR("sv_adminnick");
369                 BADCVAR("sv_autoscreenshot");
370                 BADCVAR("sv_autotaunt");
371                 BADCVAR("sv_curl_defaulturl");
372                 BADCVAR("sv_defaultcharacter");
373                 BADCVAR("sv_defaultplayercolors");
374                 BADCVAR("sv_defaultplayermodel");
375                 BADCVAR("sv_defaultplayerskin");
376                 BADCVAR("sv_maxidle");
377                 BADCVAR("sv_maxrate");
378                 BADCVAR("sv_motd");
379                 BADCVAR("sv_public");
380                 BADCVAR("sv_ready_restart");
381                 BADCVAR("sv_status_privacy");
382                 BADCVAR("sv_taunt");
383                 BADCVAR("sv_vote_call");
384                 BADCVAR("sv_vote_commands");
385                 BADCVAR("sv_vote_majority_factor");
386                 BADCVAR("sv_vote_master");
387                 BADCVAR("sv_vote_master_commands");
388                 BADCVAR("sv_vote_master_password");
389                 BADCVAR("sv_vote_simple_majority_factor");
390                 BADCVAR("teamplay_mode");
391                 BADCVAR("timelimit_override");
392                 BADCVAR("g_spawnshieldtime");
393                 BADPREFIX("g_warmup_");
394                 BADPREFIX("sv_ready_restart_");
395
396                 // mutators that announce themselves properly to the server browser
397                 BADCVAR("g_instagib");
398                 BADCVAR("g_new_toys");
399                 BADCVAR("g_nix");
400                 BADCVAR("g_grappling_hook");
401                 BADCVAR("g_jetpack");
402
403 #undef BADPREFIX
404 #undef BADCVAR
405
406                 if(pureadding)
407                 {
408                         cvar_purechanges = strcat(cvar_purechanges, k, " \"", v, "\" // \"", d, "\"\n");
409                         if(strlen(cvar_purechanges) > 16384)
410                         {
411                                 cvar_purechanges = "// too many settings have been changed to show them here\n";
412                                 pureadding = 0;
413                         }
414                 }
415                 ++cvar_purechanges_count;
416                 // WARNING: this variable is used for the server list
417                 // NEVER dare to skip this code!
418                 // Hacks to intentionally appearing as "pure server" even though you DO have
419                 // modified settings may be punished by removal from the server list.
420                 // You can do to the variables cvar_changes and cvar_purechanges all you want,
421                 // though.
422         }
423         buf_del(h);
424         if(cvar_changes == "")
425                 cvar_changes = "// this server runs at default server settings\n";
426         else
427                 cvar_changes = strcat("// this server runs at modified server settings:\n", cvar_changes);
428         cvar_changes = strzone(cvar_changes);
429         if(cvar_purechanges == "")
430                 cvar_purechanges = "// this server runs at default gameplay settings\n";
431         else
432                 cvar_purechanges = strcat("// this server runs at modified gameplay settings:\n", cvar_purechanges);
433         cvar_purechanges = strzone(cvar_purechanges);
434 }
435
436 void detect_maptype()
437 {
438 #if 0
439         vector o, v;
440         float i;
441
442         for(;;)
443         {
444                 o = world.mins;
445                 o_x += random() * (world.maxs_x - world.mins_x);
446                 o_y += random() * (world.maxs_y - world.mins_y);
447                 o_z += random() * (world.maxs_z - world.mins_z);
448
449                 tracebox(o, PL_MIN, PL_MAX, o - '0 0 32768', MOVE_WORLDONLY, world);
450                 if(trace_fraction == 1)
451                         continue;
452
453                 v = trace_endpos;
454
455                 for(i = 0; i < 64; i += 4)
456                 {
457                         tracebox(o, '-1 -1 -1' * i, '1 1 1' * i, o - '0 0 32768', MOVE_WORLDONLY, world);
458         if(trace_fraction == 1)
459                 continue;
460                         print(ftos(i), " -> ", vtos(trace_endpos), "\n");
461                 }
462
463                 break;
464         }
465 #endif
466 }
467
468 entity randomseed;
469 float RandomSeed_Send(entity to, float sf)
470 {
471         WriteByte(MSG_ENTITY, ENT_CLIENT_RANDOMSEED);
472         WriteShort(MSG_ENTITY, self.cnt);
473         return TRUE;
474 }
475 void RandomSeed_Think()
476 {
477         self.cnt = bound(0, floor(random() * 65536), 65535);
478         self.nextthink = time + 5;
479
480         self.SendFlags |= 1;
481 }
482 void RandomSeed_Spawn()
483 {
484         randomseed = spawn();
485         randomseed.think = RandomSeed_Think;
486         Net_LinkEntity(randomseed, FALSE, 0, RandomSeed_Send);
487
488         entity oldself;
489         oldself = self;
490         self = randomseed;
491         self.think(); // sets random seed and nextthink
492         self = oldself;
493 }
494
495 void spawnfunc___init_dedicated_server(void)
496 {
497         // handler for _init/_init map (only for dedicated server initialization)
498
499         world_initialized = -1; // don't complain
500         cvar = cvar_normal;
501         cvar_string = cvar_string_normal;
502         cvar_set = cvar_set_normal;
503
504         remove = remove_unsafely;
505
506         entity e;
507         e = spawn();
508         e.think = GotoFirstMap;
509         e.nextthink = time; // this is usually 1 at this point
510
511         e = spawn();
512         e.classname = "info_player_deathmatch"; // safeguard against player joining
513
514         self.classname = "worldspawn"; // safeguard against various stuff ;)
515
516         // needs to be done so early because of the constants they create
517         CALL_ACCUMULATED_FUNCTION(RegisterWeapons);
518         CALL_ACCUMULATED_FUNCTION(RegisterMonsters);
519         CALL_ACCUMULATED_FUNCTION(RegisterGametypes);
520         CALL_ACCUMULATED_FUNCTION(RegisterNotifications);
521         CALL_ACCUMULATED_FUNCTION(RegisterDeathtypes);
522         CALL_ACCUMULATED_FUNCTION(RegisterBuffs);
523
524         MapInfo_Enumerate();
525         MapInfo_FilterGametype(MapInfo_CurrentGametype(), MapInfo_CurrentFeatures(), MapInfo_RequiredFlags(), MapInfo_ForbiddenFlags(), 0);
526 }
527
528 void Map_MarkAsRecent(string m);
529 float world_already_spawned;
530 void Nagger_Init();
531 void Item_ItemsTime_Init();
532 void ClientInit_Spawn();
533 void WeaponStats_Init();
534 void WeaponStats_Shutdown();
535 void spawnfunc_worldspawn (void)
536 {
537         float fd, l, i, j, n;
538         string s;
539
540         cvar = cvar_normal;
541         cvar_string = cvar_string_normal;
542         cvar_set = cvar_set_normal;
543
544         if(world_already_spawned)
545                 error("world already spawned - you may have EXACTLY ONE worldspawn!");
546         world_already_spawned = TRUE;
547
548         remove = remove_safely; // during spawning, watch what you remove!
549
550         cvar_changes_init(); // do this very early now so it REALLY matches the server config
551
552         compressShortVector_init();
553
554         entity head;
555         head = nextent(world);
556         maxclients = 0;
557         while(head)
558         {
559                 ++maxclients;
560                 head = nextent(head);
561         }
562
563         server_is_dedicated = (stof(cvar_defstring("is_dedicated")) ? TRUE : FALSE);
564
565         // needs to be done so early because of the constants they create
566         CALL_ACCUMULATED_FUNCTION(RegisterWeapons);
567         CALL_ACCUMULATED_FUNCTION(RegisterMonsters);
568         CALL_ACCUMULATED_FUNCTION(RegisterGametypes);
569         CALL_ACCUMULATED_FUNCTION(RegisterNotifications);
570         CALL_ACCUMULATED_FUNCTION(RegisterDeathtypes);
571         CALL_ACCUMULATED_FUNCTION(RegisterBuffs);
572
573         ServerProgsDB = db_load(strcat("server.db", autocvar_sessionid));
574
575         TemporaryDB = db_create();
576
577         // 0 normal
578         lightstyle(0, "m");
579
580         // 1 FLICKER (first variety)
581         lightstyle(1, "mmnmmommommnonmmonqnmmo");
582
583         // 2 SLOW STRONG PULSE
584         lightstyle(2, "abcdefghijklmnopqrstuvwxyzyxwvutsrqponmlkjihgfedcba");
585
586         // 3 CANDLE (first variety)
587         lightstyle(3, "mmmmmaaaaammmmmaaaaaabcdefgabcdefg");
588
589         // 4 FAST STROBE
590         lightstyle(4, "mamamamamama");
591
592         // 5 GENTLE PULSE 1
593         lightstyle(5,"jklmnopqrstuvwxyzyxwvutsrqponmlkj");
594
595         // 6 FLICKER (second variety)
596         lightstyle(6, "nmonqnmomnmomomno");
597
598         // 7 CANDLE (second variety)
599         lightstyle(7, "mmmaaaabcdefgmmmmaaaammmaamm");
600
601         // 8 CANDLE (third variety)
602         lightstyle(8, "mmmaaammmaaammmabcdefaaaammmmabcdefmmmaaaa");
603
604         // 9 SLOW STROBE (fourth variety)
605         lightstyle(9, "aaaaaaaazzzzzzzz");
606
607         // 10 FLUORESCENT FLICKER
608         lightstyle(10, "mmamammmmammamamaaamammma");
609
610         // 11 SLOW PULSE NOT FADE TO BLACK
611         lightstyle(11, "abcdefghijklmnopqrrqponmlkjihgfedcba");
612
613         // styles 32-62 are assigned by the spawnfunc_light program for switchable lights
614
615         // 63 testing
616         lightstyle(63, "a");
617
618         if(autocvar_g_campaign)
619                 CampaignPreInit();
620
621         Map_MarkAsRecent(mapname);
622
623         PlayerStats_GameReport_Init(); // we need this to be initiated before InitGameplayMode
624
625         precache_model ("null"); // we need this one before InitGameplayMode
626         InitGameplayMode();
627         readlevelcvars();
628         GrappleHookInit();
629
630         player_count = 0;
631         bot_waypoints_for_items = autocvar_g_waypoints_for_items;
632         if(bot_waypoints_for_items == 1)
633                 if(self.spawnflags & SPAWNFLAG_NO_WAYPOINTS_FOR_ITEMS)
634                         bot_waypoints_for_items = 0;
635
636         precache();
637
638         WaypointSprite_Init();
639
640         GameLogInit(); // prepare everything
641         // NOTE for matchid:
642         // changing the logic generating it is okay. But:
643         // it HAS to stay <= 64 chars
644         // character set: ASCII 33-126 without the following characters: : ; ' " \ $
645         if(autocvar_sv_eventlog)
646         {
647                 s = sprintf("%d.%s.%06d", ftos(autocvar_sv_eventlog_files_counter), strftime(FALSE, "%s"), floor(random() * 1000000));
648                 matchid = strzone(s);
649
650                 GameLogEcho(strcat(":gamestart:", GetGametype(), "_", GetMapname(), ":", s));
651                 s = ":gameinfo:mutators:LIST";
652
653                 ret_string = s;
654                 MUTATOR_CALLHOOK(BuildMutatorsString);
655                 s = ret_string;
656
657                 // simple, probably not good in the mutator system
658                 if(autocvar_g_grappling_hook)
659                         s = strcat(s, ":grappling_hook");
660
661                 // initialiation stuff, not good in the mutator system
662                 if(!autocvar_g_use_ammunition)
663                         s = strcat(s, ":no_use_ammunition");
664
665                 // initialiation stuff, not good in the mutator system
666                 if(autocvar_g_pickup_items == 0)
667                         s = strcat(s, ":no_pickup_items");
668                 if(autocvar_g_pickup_items > 0)
669                         s = strcat(s, ":pickup_items");
670
671                 // initialiation stuff, not good in the mutator system
672                 if(autocvar_g_weaponarena != "0")
673                         s = strcat(s, ":", autocvar_g_weaponarena, " arena");
674
675                 // TODO to mutator system
676                 if(autocvar_g_norecoil)
677                         s = strcat(s, ":norecoil");
678
679                 // TODO to mutator system
680                 if(autocvar_g_powerups == 0)
681                         s = strcat(s, ":no_powerups");
682                 if(autocvar_g_powerups > 0)
683                         s = strcat(s, ":powerups");
684
685                 GameLogEcho(s);
686                 GameLogEcho(":gameinfo:end");
687         }
688         else
689                 matchid = strzone(ftos(random()));
690
691         cvar_set("nextmap", "");
692
693         SetDefaultAlpha();
694
695         if(autocvar_g_campaign)
696                 CampaignPostInit();
697
698         Ban_LoadBans();
699
700         MapInfo_Enumerate();
701         MapInfo_FilterGametype(MapInfo_CurrentGametype(), MapInfo_CurrentFeatures(), MapInfo_RequiredFlags(), MapInfo_ForbiddenFlags(), 1);
702
703         if(whichpack(strcat("maps/", mapname, ".cfg")) != "")
704         {
705                 fd = fopen(strcat("maps/", mapname, ".cfg"), FILE_READ);
706                 if(fd != -1)
707                 {
708                         while((s = fgets(fd)))
709                         {
710                                 l = tokenize_console(s);
711                                 if(l < 2)
712                                         continue;
713                                 if(argv(0) == "cd")
714                                 {
715                                         print("Found ^1UNSUPPORTED^7 cd loop command in .cfg file; put this line in mapinfo instead:\n");
716                                         print("  cdtrack ", argv(2), "\n");
717                                 }
718                                 else if(argv(0) == "fog")
719                                 {
720                                         print("Found ^1UNSUPPORTED^7 fog command in .cfg file; put this line in worldspawn in the .map/.bsp/.ent file instead:\n");
721                                         print("  \"fog\" \"", s, "\"\n");
722                                 }
723                                 else if(argv(0) == "set")
724                                 {
725                                         print("Found ^1UNSUPPORTED^7 set command in .cfg file; put this line in mapinfo instead:\n");
726                                         print("  clientsettemp_for_type all ", argv(1), " ", argv(2), "\n");
727                                 }
728                                 else if(argv(0) != "//")
729                                 {
730                                         print("Found ^1UNSUPPORTED^7 set command in .cfg file; put this line in mapinfo instead:\n");
731                                         print("  clientsettemp_for_type all ", argv(0), " ", argv(1), "\n");
732                                 }
733                         }
734                         fclose(fd);
735                 }
736         }
737
738         WeaponStats_Init();
739
740         WepSet_AddStat();
741         addstat(STAT_SWITCHWEAPON, AS_INT, switchweapon);
742         addstat(STAT_SWITCHINGWEAPON, AS_INT, switchingweapon);
743         addstat(STAT_GAMESTARTTIME, AS_FLOAT, stat_game_starttime);
744         addstat(STAT_ROUNDSTARTTIME, AS_FLOAT, stat_round_starttime);
745         addstat(STAT_ALLOW_OLDVORTEXBEAM, AS_INT, stat_allow_oldvortexbeam);
746         Nagger_Init();
747
748         addstat(STAT_STRENGTH_FINISHED, AS_FLOAT, strength_finished);
749         addstat(STAT_INVINCIBLE_FINISHED, AS_FLOAT, invincible_finished);
750         addstat(STAT_SUPERWEAPONS_FINISHED, AS_FLOAT, superweapons_finished);
751         addstat(STAT_PRESSED_KEYS, AS_FLOAT, pressedkeys);
752         addstat(STAT_FUEL, AS_INT, ammo_fuel);
753         addstat(STAT_PLASMA, AS_INT, ammo_plasma);
754         addstat(STAT_SHOTORG, AS_INT, stat_shotorg);
755         addstat(STAT_LEADLIMIT, AS_FLOAT, stat_leadlimit);
756         addstat(STAT_WEAPON_CLIPLOAD, AS_INT, clip_load);
757         addstat(STAT_WEAPON_CLIPSIZE, AS_INT, clip_size);
758         addstat(STAT_LAST_PICKUP, AS_FLOAT, last_pickup);
759         addstat(STAT_HIT_TIME, AS_FLOAT, hit_time);
760         addstat(STAT_DAMAGE_DEALT_TOTAL, AS_INT, damage_dealt_total);
761         addstat(STAT_TYPEHIT_TIME, AS_FLOAT, typehit_time);
762         addstat(STAT_LAYED_MINES, AS_INT, minelayer_mines);
763
764         addstat(STAT_VORTEX_CHARGE, AS_FLOAT, vortex_charge);
765         addstat(STAT_VORTEX_CHARGEPOOL, AS_FLOAT, vortex_chargepool_ammo);
766
767         addstat(STAT_HAGAR_LOAD, AS_INT, hagar_load);
768         
769         addstat(STAT_ARC_HEAT, AS_FLOAT, arc_heat_percent);
770
771         // items time
772         addstat(STAT_ARMOR_LARGE_TIME, AS_FLOAT, item_armor_large_time);
773         addstat(STAT_HEALTH_MEGA_TIME, AS_FLOAT, item_health_mega_time);
774         addstat(STAT_INVISIBLE_TIME, AS_FLOAT, item_invisible_time);
775         addstat(STAT_SPEED_TIME, AS_FLOAT, item_speed_time);
776         addstat(STAT_EXTRALIFE_TIME, AS_FLOAT, item_extralife_time);
777         addstat(STAT_STRENGTH_TIME, AS_FLOAT, item_strength_time);
778         addstat(STAT_SHIELD_TIME, AS_FLOAT, item_shield_time);
779         addstat(STAT_FUELREGEN_TIME, AS_FLOAT, item_fuelregen_time);
780         addstat(STAT_JETPACK_TIME, AS_FLOAT, item_jetpack_time);
781         addstat(STAT_SUPERWEAPONS_TIME, AS_FLOAT, item_superweapons_time);
782         Item_ItemsTime_Init();
783
784         // freeze attacks
785         addstat(STAT_FROZEN, AS_INT, frozen);
786         addstat(STAT_REVIVE_PROGRESS, AS_FLOAT, revive_progress);
787
788         // g_movementspeed hack
789         addstat(STAT_MOVEVARS_AIRSPEEDLIMIT_NONQW, AS_FLOAT, stat_sv_airspeedlimit_nonqw);
790         addstat(STAT_MOVEVARS_MAXSPEED, AS_FLOAT, stat_sv_maxspeed);
791         addstat(STAT_MOVEVARS_AIRACCEL_QW, AS_FLOAT, stat_sv_airaccel_qw);
792         addstat(STAT_MOVEVARS_AIRSTRAFEACCEL_QW, AS_FLOAT, stat_sv_airstrafeaccel_qw);
793
794         // secrets
795         addstat(STAT_SECRETS_TOTAL, AS_FLOAT, stat_secrets_total);
796         addstat(STAT_SECRETS_FOUND, AS_FLOAT, stat_secrets_found);
797
798         // monsters
799         addstat(STAT_MONSTERS_TOTAL, AS_FLOAT, stat_monsters_total);
800         addstat(STAT_MONSTERS_KILLED, AS_FLOAT, stat_monsters_killed);
801
802         // misc
803         addstat(STAT_RESPAWN_TIME, AS_FLOAT, stat_respawn_time);
804
805         next_pingtime = time + 5;
806
807         detect_maptype();
808
809         // set up information replies for clients and server to use
810         maplist_reply = strzone(getmaplist());
811         lsmaps_reply = strzone(getlsmaps());
812         monsterlist_reply = strzone(getmonsterlist());
813         for(i = 0; i < 10; ++i)
814         {
815                 s = getrecords(i);
816                 if (s)
817                         records_reply[i] = strzone(s);
818         }
819         ladder_reply = strzone(getladder());
820         rankings_reply = strzone(getrankings());
821
822         // begin other init
823         ClientInit_Spawn();
824         RandomSeed_Spawn();
825         PingPLReport_Spawn();
826
827         CheatInit();
828
829         localcmd("\n_sv_hook_gamestart ", GetGametype(), "\n");
830
831         // fill sv_curl_serverpackages from .serverpackage files
832         if(autocvar_sv_curl_serverpackages_auto)
833         {
834                 s = "";
835                 n = tokenize_console(cvar_string("sv_curl_serverpackages"));
836                 for(i = 0; i < n; ++i)
837                         if(substring(argv(i), -18, -1) != "-serverpackage.txt")
838                         if(substring(argv(i), -14, -1) != ".serverpackage") // OLD legacy
839                                 s = strcat(s, " ", argv(i));
840                 fd = search_begin("*-serverpackage.txt", TRUE, FALSE);
841                 if(fd >= 0)
842                 {
843                         j = search_getsize(fd);
844                         for(i = 0; i < j; ++i)
845                                 s = strcat(s, " ", search_getfilename(fd, i));
846                         search_end(fd);
847                 }
848                 fd = search_begin("*.serverpackage", TRUE, FALSE);
849                 if(fd >= 0)
850                 {
851                         j = search_getsize(fd);
852                         for(i = 0; i < j; ++i)
853                                 s = strcat(s, " ", search_getfilename(fd, i));
854                         search_end(fd);
855                 }
856                 cvar_set("sv_curl_serverpackages", substring(s, 1, -1));
857         }
858
859         // MOD AUTHORS: change this, and possibly remove a few of the blocks below to ignore certain changes
860         modname = "Xonotic";
861         // physics/balance/config changes that count as mod
862         if(cvar_string("g_mod_physics") != cvar_defstring("g_mod_physics"))
863                 modname = cvar_string("g_mod_physics");
864         if(cvar_string("g_mod_balance") != cvar_defstring("g_mod_balance"))
865                 modname = cvar_string("g_mod_balance");
866         if(cvar_string("g_mod_config") != cvar_defstring("g_mod_config"))
867                 modname = cvar_string("g_mod_config");
868         // extra mutators that deserve to count as mod
869         MUTATOR_CALLHOOK(SetModname);
870
871         // save it for later
872         modname = strzone(modname);
873
874         WinningConditionHelper(); // set worldstatus
875
876         world_initialized = 1;
877 }
878
879 void spawnfunc_light (void)
880 {
881         //makestatic (self); // Who the f___ did that?
882         remove(self);
883 }
884
885 string GetGametype()
886 {
887         return MapInfo_Type_ToString(MapInfo_LoadedGametype);
888 }
889
890 string GetMapname()
891 {
892         return mapname;
893 }
894
895 float Map_Count, Map_Current;
896 string Map_Current_Name;
897
898 // NOTE: this now expects the map list to be already tokenized and the count in Map_Count
899 float GetMaplistPosition()
900 {
901         float pos, idx;
902         string map;
903
904         map = GetMapname();
905         idx = autocvar_g_maplist_index;
906
907         if(idx >= 0)
908                 if(idx < Map_Count)
909                         if(map == argv(idx))
910                                 return idx;
911
912         for(pos = 0; pos < Map_Count; ++pos)
913                 if(map == argv(pos))
914                         return pos;
915
916         // resume normal maplist rotation if current map is not in g_maplist
917         return idx;
918 }
919
920 float MapHasRightSize(string map)
921 {
922         float fh;
923         if(currentbots || autocvar_bot_number || player_count < autocvar_minplayers)
924         if(autocvar_g_maplist_check_waypoints)
925         {
926                 dprint("checkwp "); dprint(map);
927                 if(!fexists(strcat("maps/", map, ".waypoints")))
928                 {
929                         dprint(": no waypoints\n");
930                         return FALSE;
931                 }
932                 dprint(": has waypoints\n");
933         }
934
935         // open map size restriction file
936         dprint("opensize "); dprint(map);
937         fh = fopen(strcat("maps/", map, ".sizes"), FILE_READ);
938         if(fh >= 0)
939         {
940                 float mapmin, mapmax;
941                 dprint(": ok, ");
942                 mapmin = stof(fgets(fh));
943                 mapmax = stof(fgets(fh));
944                 fclose(fh);
945                 if(player_count < mapmin)
946                 {
947                         dprint("not enough\n");
948                         return FALSE;
949                 }
950                 if(player_count > mapmax)
951                 {
952                         dprint("too many\n");
953                         return FALSE;
954                 }
955                 dprint("right size\n");
956                 return TRUE;
957         }
958         dprint(": not found\n");
959         return TRUE;
960 }
961
962 string Map_Filename(float position)
963 {
964         return strcat("maps/", argv(position), ".bsp");
965 }
966
967 string strwords(string s, float w)
968 {
969         float endpos;
970         for(endpos = 0; w && endpos >= 0; --w)
971                 endpos = strstrofs(s, " ", endpos + 1);
972         if(endpos < 0)
973                 return s;
974         else
975                 return substring(s, 0, endpos);
976 }
977
978 float strhasword(string s, string w)
979 {
980         return strstrofs(strcat(" ", s, " "), strcat(" ", w, " "), 0) >= 0;
981 }
982
983 void Map_MarkAsRecent(string m)
984 {
985         cvar_set("g_maplist_mostrecent", strwords(strcat(m, " ", autocvar_g_maplist_mostrecent), max(0, autocvar_g_maplist_mostrecent_count)));
986 }
987
988 float Map_IsRecent(string m)
989 {
990         return strhasword(autocvar_g_maplist_mostrecent, m);
991 }
992
993 float Map_Check(float position, float pass)
994 {
995         string filename;
996         string map_next;
997         map_next = argv(position);
998         if(pass <= 1)
999         {
1000                 if(Map_IsRecent(map_next))
1001                         return 0;
1002         }
1003         filename = Map_Filename(position);
1004         if(MapInfo_CheckMap(map_next))
1005         {
1006                 if(pass == 2)
1007                         return 1;
1008                 if(MapHasRightSize(map_next))
1009                         return 1;
1010                 return 0;
1011         }
1012         else
1013                 dprint( "Couldn't select '", filename, "'..\n" );
1014
1015         return 0;
1016 }
1017
1018 void Map_Goto_SetStr(string nextmapname)
1019 {
1020         if(getmapname_stored != "")
1021                 strunzone(getmapname_stored);
1022         if(nextmapname == "")
1023                 getmapname_stored = "";
1024         else
1025                 getmapname_stored = strzone(nextmapname);
1026 }
1027
1028 void Map_Goto_SetFloat(float position)
1029 {
1030         cvar_set("g_maplist_index", ftos(position));
1031         Map_Goto_SetStr(argv(position));
1032 }
1033
1034 void Map_Goto(float reinit)
1035 {
1036         MapInfo_LoadMap(getmapname_stored, reinit);
1037 }
1038
1039 // return codes of map selectors:
1040 //   -1 = temporary failure (that is, try some method that is guaranteed to succeed)
1041 //   -2 = permanent failure
1042 float() MaplistMethod_Iterate = // usual method
1043 {
1044         float pass, i;
1045
1046         dprint("Trying MaplistMethod_Iterate\n");
1047
1048         for(pass = 1; pass <= 2; ++pass)
1049         {
1050                 for(i = 1; i < Map_Count; ++i)
1051                 {
1052                         float mapindex;
1053                         mapindex = (i + Map_Current) % Map_Count;
1054                         if(Map_Check(mapindex, pass))
1055                                 return mapindex;
1056                 }
1057         }
1058         return -1;
1059 }
1060
1061 float() MaplistMethod_Repeat = // fallback method
1062 {
1063         dprint("Trying MaplistMethod_Repeat\n");
1064
1065         if(Map_Check(Map_Current, 2))
1066                 return Map_Current;
1067         return -2;
1068 }
1069
1070 float() MaplistMethod_Random = // random map selection
1071 {
1072         float i, imax;
1073
1074         dprint("Trying MaplistMethod_Random\n");
1075
1076         imax = 42;
1077
1078         for(i = 0; i <= imax; ++i)
1079         {
1080                 float mapindex;
1081                 mapindex = (Map_Current + floor(random() * (Map_Count - 1) + 1)) % Map_Count; // any OTHER map
1082                 if(Map_Check(mapindex, 1))
1083                         return mapindex;
1084         }
1085         return -1;
1086 }
1087
1088 float(float exponent) MaplistMethod_Shuffle = // more clever shuffling
1089 // the exponent sets a bias on the map selection:
1090 // the higher the exponent, the less likely "shortly repeated" same maps are
1091 {
1092         float i, j, imax, insertpos;
1093
1094         dprint("Trying MaplistMethod_Shuffle\n");
1095
1096         imax = 42;
1097
1098         for(i = 0; i <= imax; ++i)
1099         {
1100                 string newlist;
1101
1102                 // now reinsert this at another position
1103                 insertpos = pow(random(), 1 / exponent);       // ]0, 1]
1104                 insertpos = insertpos * (Map_Count - 1);       // ]0, Map_Count - 1]
1105                 insertpos = ceil(insertpos) + 1;               // {2, 3, 4, ..., Map_Count}
1106                 dprint("SHUFFLE: insert pos = ", ftos(insertpos), "\n");
1107
1108                 // insert the current map there
1109                 newlist = "";
1110                 for(j = 1; j < insertpos; ++j)                 // i == 1: no loop, will be inserted as first; however, i == 1 has been excluded above
1111                         newlist = strcat(newlist, " ", argv(j));
1112                 newlist = strcat(newlist, " ", argv(0));       // now insert the just selected map
1113                 for(j = insertpos; j < Map_Count; ++j)         // i == Map_Count: no loop, has just been inserted as last
1114                         newlist = strcat(newlist, " ", argv(j));
1115                 newlist = substring(newlist, 1, strlen(newlist) - 1);
1116                 cvar_set("g_maplist", newlist);
1117                 Map_Count = tokenizebyseparator(autocvar_g_maplist, " ");
1118
1119                 // NOTE: the selected map has just been inserted at (insertpos-1)th position
1120                 Map_Current = insertpos - 1; // this is not really valid, but this way the fallback has a chance of working
1121                 if(Map_Check(Map_Current, 1))
1122                         return Map_Current;
1123         }
1124         return -1;
1125 }
1126
1127 void Maplist_Init()
1128 {
1129         Map_Count = tokenizebyseparator(autocvar_g_maplist, " ");
1130         float i;
1131         for (i = 0; i < Map_Count; ++i)
1132                 if (Map_Check(i, 2))
1133                         break;
1134         if (i == Map_Count)
1135         {
1136                 bprint( "Maplist contains no usable maps!  Resetting it to default map list.\n" );
1137                 cvar_set("g_maplist", MapInfo_ListAllAllowedMaps(MapInfo_RequiredFlags(), MapInfo_ForbiddenFlags() | MAPINFO_FLAG_NOAUTOMAPLIST));
1138                 if(autocvar_g_maplist_shuffle)
1139                         ShuffleMaplist();
1140                 localcmd("\nmenu_cmd sync\n");
1141                 Map_Count = tokenizebyseparator(autocvar_g_maplist, " ");
1142         }
1143         if(Map_Count == 0)
1144                 error("empty maplist, cannot select a new map");
1145         Map_Current = bound(0, GetMaplistPosition(), Map_Count - 1);
1146
1147         if(Map_Current_Name)
1148                 strunzone(Map_Current_Name);
1149         Map_Current_Name = strzone(argv(Map_Current)); // will be automatically freed on exit thanks to DP
1150         // this may or may not be correct, but who cares, in the worst case a map
1151         // isn't chosen in the first pass that should have been
1152 }
1153
1154 string GetNextMap()
1155 {
1156         float nextMap;
1157
1158         Maplist_Init();
1159         nextMap = -1;
1160
1161         if(nextMap == -1)
1162                 if(autocvar_g_maplist_shuffle > 0)
1163                         nextMap = MaplistMethod_Shuffle(autocvar_g_maplist_shuffle + 1);
1164
1165         if(nextMap == -1)
1166                 if(autocvar_g_maplist_selectrandom)
1167                         nextMap = MaplistMethod_Random();
1168
1169         if(nextMap == -1)
1170                 nextMap = MaplistMethod_Iterate();
1171
1172         if(nextMap == -1)
1173                 nextMap = MaplistMethod_Repeat();
1174
1175         if(nextMap >= 0)
1176         {
1177                 Map_Goto_SetFloat(nextMap);
1178                 return getmapname_stored;
1179         }
1180
1181         return "";
1182 }
1183
1184 float DoNextMapOverride(float reinit)
1185 {
1186         if(autocvar_g_campaign)
1187         {
1188                 CampaignPostIntermission();
1189                 alreadychangedlevel = TRUE;
1190                 return TRUE;
1191         }
1192         if(autocvar_quit_when_empty)
1193         {
1194                 if(player_count <= currentbots)
1195                 {
1196                         localcmd("quit\n");
1197                         alreadychangedlevel = TRUE;
1198                         return TRUE;
1199                 }
1200         }
1201         if(autocvar_quit_and_redirect != "")
1202         {
1203                 redirection_target = strzone(autocvar_quit_and_redirect);
1204                 alreadychangedlevel = TRUE;
1205                 return TRUE;
1206         }
1207         if (!reinit && autocvar_samelevel) // if samelevel is set, stay on same level
1208         {
1209                 localcmd("restart\n");
1210                 alreadychangedlevel = TRUE;
1211                 return TRUE;
1212         }
1213         if(autocvar_nextmap != "")
1214         {
1215                 string m;
1216                 m = GameTypeVote_MapInfo_FixName(autocvar_nextmap);
1217                 cvar_set("nextmap",m);
1218         
1219                 if(!m || gametypevote)
1220                         return FALSE;
1221                 if(autocvar_sv_vote_gametype)
1222                 {
1223                         Map_Goto_SetStr(m);
1224                         return FALSE;
1225                 }
1226                 
1227                 if(MapInfo_CheckMap(m))
1228                 {
1229                         Map_Goto_SetStr(m);
1230                         Map_Goto(reinit);
1231                         alreadychangedlevel = TRUE;
1232                         return TRUE;
1233                 }
1234         }
1235         if(!reinit && autocvar_lastlevel)
1236         {
1237                 cvar_settemp_restore();
1238                 localcmd("set lastlevel 0\ntogglemenu 1\n");
1239                 alreadychangedlevel = TRUE;
1240                 return TRUE;
1241         }
1242         return FALSE;
1243 }
1244
1245 void GotoNextMap(float reinit)
1246 {
1247         //string nextmap;
1248         //float n, nummaps;
1249         //string s;
1250         if (alreadychangedlevel)
1251                 return;
1252         alreadychangedlevel = TRUE;
1253
1254         string nextMap;
1255
1256         nextMap = GetNextMap();
1257         if(nextMap == "")
1258                 error("Everything is broken - cannot find a next map. Please report this to the developers.");
1259         Map_Goto(reinit);
1260 }
1261
1262
1263 /*
1264 ============
1265 IntermissionThink
1266
1267 When the player presses attack or jump, change to the next level
1268 ============
1269 */
1270 .float autoscreenshot;
1271 void IntermissionThink()
1272 {
1273         FixIntermissionClient(self);
1274
1275         float server_screenshot = (autocvar_sv_autoscreenshot && self.cvar_cl_autoscreenshot);
1276         float client_screenshot = (self.cvar_cl_autoscreenshot == 2);
1277
1278         if( (server_screenshot || client_screenshot)
1279                 && ((self.autoscreenshot > 0) && (time > self.autoscreenshot)) )
1280         {
1281                 self.autoscreenshot = -1;
1282                 if(IS_REAL_CLIENT(self)) { stuffcmd(self, sprintf("\nscreenshot screenshots/autoscreenshot/%s-%s.jpg; echo \"^5A screenshot has been taken at request of the server.\"\n", GetMapname(), strftime(FALSE, "%s"))); }
1283                 return;
1284         }
1285
1286         if (time < intermission_exittime)
1287                 return;
1288
1289         if(!mapvote_initialized)
1290                 if (time < intermission_exittime + 10 && !(self.BUTTON_ATCK || self.BUTTON_JUMP || self.BUTTON_ATCK2 || self.BUTTON_HOOK || self.BUTTON_USE))
1291                         return;
1292
1293         MapVote_Start();
1294 }
1295
1296 /*
1297 ============
1298 FindIntermission
1299
1300 Returns the entity to view from
1301 ============
1302 */
1303 /*
1304 entity FindIntermission()
1305 {
1306         local   entity spot;
1307         local   float cyc;
1308
1309 // look for info_intermission first
1310         spot = find (world, classname, "info_intermission");
1311         if (spot)
1312         {       // pick a random one
1313                 cyc = random() * 4;
1314                 while (cyc > 1)
1315                 {
1316                         spot = find (spot, classname, "info_intermission");
1317                         if (!spot)
1318                                 spot = find (spot, classname, "info_intermission");
1319                         cyc = cyc - 1;
1320                 }
1321                 return spot;
1322         }
1323
1324 // then look for the start position
1325         spot = find (world, classname, "info_player_start");
1326         if (spot)
1327                 return spot;
1328
1329 // testinfo_player_start is only found in regioned levels
1330         spot = find (world, classname, "testplayerstart");
1331         if (spot)
1332                 return spot;
1333
1334 // then look for the start position
1335         spot = find (world, classname, "info_player_deathmatch");
1336         if (spot)
1337                 return spot;
1338
1339         //objerror ("FindIntermission: no spot");
1340         return world;
1341 }
1342 */
1343
1344 /*
1345 ===============================================================================
1346
1347 RULES
1348
1349 ===============================================================================
1350 */
1351
1352 void DumpStats(float final)
1353 {
1354         float file;
1355         string s;
1356         float to_console;
1357         float to_eventlog;
1358         float to_file;
1359         float i;
1360
1361         to_console = autocvar_sv_logscores_console;
1362         to_eventlog = autocvar_sv_eventlog;
1363         to_file = autocvar_sv_logscores_file;
1364
1365         if(!final)
1366         {
1367                 to_console = TRUE; // always print printstats replies
1368                 to_eventlog = FALSE; // but never print them to the event log
1369         }
1370
1371         if(to_eventlog)
1372                 if(autocvar_sv_eventlog_console)
1373                         to_console = FALSE; // otherwise we get the output twice
1374
1375         if(final)
1376                 s = ":scores:";
1377         else
1378                 s = ":status:";
1379         s = strcat(s, GetGametype(), "_", GetMapname(), ":", ftos(rint(time)));
1380
1381         if(to_console)
1382                 print(s, "\n");
1383         if(to_eventlog)
1384                 GameLogEcho(s);
1385
1386         file = -1;
1387         if(to_file)
1388         {
1389                 file = fopen(autocvar_sv_logscores_filename, FILE_APPEND);
1390                 if(file == -1)
1391                         to_file = FALSE;
1392                 else
1393                         fputs(file, strcat(s, "\n"));
1394         }
1395
1396         s = strcat(":labels:player:", GetPlayerScoreString(world, 0));
1397         if(to_console)
1398                 print(s, "\n");
1399         if(to_eventlog)
1400                 GameLogEcho(s);
1401         if(to_file)
1402                 fputs(file, strcat(s, "\n"));
1403
1404         FOR_EACH_CLIENT(other)
1405         {
1406                 if ((IS_REAL_CLIENT(other)) || (IS_BOT_CLIENT(other) && autocvar_sv_logscores_bots))
1407                 {
1408                         s = strcat(":player:see-labels:", GetPlayerScoreString(other, 0), ":");
1409                         s = strcat(s, ftos(rint(time - other.jointime)), ":");
1410                         if(IS_PLAYER(other) || other.caplayer == 1 || g_lms)
1411                                 s = strcat(s, ftos(other.team), ":");
1412                         else
1413                                 s = strcat(s, "spectator:");
1414
1415                         if(to_console)
1416                                 print(s, other.netname, "\n");
1417                         if(to_eventlog)
1418                                 GameLogEcho(strcat(s, ftos(other.playerid), ":", other.netname));
1419                         if(to_file)
1420                                 fputs(file, strcat(s, other.netname, "\n"));
1421                 }
1422         }
1423
1424         if(teamplay)
1425         {
1426                 s = strcat(":labels:teamscores:", GetTeamScoreString(0, 0));
1427                 if(to_console)
1428                         print(s, "\n");
1429                 if(to_eventlog)
1430                         GameLogEcho(s);
1431                 if(to_file)
1432                         fputs(file, strcat(s, "\n"));
1433
1434                 for(i = 1; i < 16; ++i)
1435                 {
1436                         s = strcat(":teamscores:see-labels:", GetTeamScoreString(i, 0));
1437                         s = strcat(s, ":", ftos(i));
1438                         if(to_console)
1439                                 print(s, "\n");
1440                         if(to_eventlog)
1441                                 GameLogEcho(s);
1442                         if(to_file)
1443                                 fputs(file, strcat(s, "\n"));
1444                 }
1445         }
1446
1447         if(to_console)
1448                 print(":end\n");
1449         if(to_eventlog)
1450                 GameLogEcho(":end");
1451         if(to_file)
1452         {
1453                 fputs(file, ":end\n");
1454                 fclose(file);
1455         }
1456 }
1457
1458 void FixIntermissionClient(entity e)
1459 {
1460         string s;
1461         if(!e.autoscreenshot) // initial call
1462         {
1463                 e.autoscreenshot = time + 0.8;  // used for autoscreenshot
1464                 e.health = -2342;
1465                 // first intermission phase; voting phase has positive health (used to decide whether to send SVC_FINALE or not)
1466                 e.solid = SOLID_NOT;
1467                 e.movetype = MOVETYPE_NONE;
1468                 e.takedamage = DAMAGE_NO;
1469                 if(e.weaponentity)
1470                 {
1471                         e.weaponentity.effects = EF_NODRAW;
1472                         if (e.weaponentity.weaponentity)
1473                                 e.weaponentity.weaponentity.effects = EF_NODRAW;
1474                 }
1475                 if(IS_REAL_CLIENT(e))
1476                 {
1477                         stuffcmd(e, "\nscr_printspeed 1000000\n");
1478                         s = autocvar_sv_intermission_cdtrack;
1479                         if(s != "")
1480                                 stuffcmd(e, strcat("\ncd loop ", s, "\n"));
1481                         msg_entity = e;
1482                         WriteByte(MSG_ONE, SVC_INTERMISSION);
1483                 }
1484         }
1485 }
1486
1487 /*
1488 go to the next level for deathmatch
1489 only called if a time or frag limit has expired
1490 */
1491 void NextLevel()
1492 {
1493         gameover = TRUE;
1494
1495         intermission_running = 1;
1496
1497 // enforce a wait time before allowing changelevel
1498         if(player_count > 0)
1499                 intermission_exittime = time + autocvar_sv_mapchange_delay;
1500         else
1501                 intermission_exittime = -1;
1502
1503         /*
1504         WriteByte (MSG_ALL, SVC_CDTRACK);
1505         WriteByte (MSG_ALL, 3);
1506         WriteByte (MSG_ALL, 3);
1507         // done in FixIntermission
1508         */
1509
1510         //pos = FindIntermission ();
1511
1512         VoteReset();
1513
1514         DumpStats(TRUE);
1515
1516         // send statistics
1517         PlayerStats_GameReport(TRUE);
1518         WeaponStats_Shutdown();
1519
1520         Kill_Notification(NOTIF_ALL, world, MSG_CENTER, 0); // kill all centerprints now
1521
1522         if(autocvar_sv_eventlog)
1523                 GameLogEcho(":gameover");
1524
1525         GameLogClose();
1526
1527         FOR_EACH_PLAYER(other) {
1528                 FixIntermissionClient(other);
1529                 if(other.winning)
1530                         bprint(other.netname, " ^7wins.\n");
1531         }
1532
1533         if(autocvar_g_campaign)
1534                 CampaignPreIntermission();
1535
1536         MUTATOR_CALLHOOK(MatchEnd);
1537
1538         localcmd("\nsv_hook_gameend\n");
1539 }
1540
1541 /*
1542 ============
1543 CheckRules_Player
1544
1545 Exit deathmatch games upon conditions
1546 ============
1547 */
1548 void CheckRules_Player()
1549 {
1550         if (gameover)   // someone else quit the game already
1551                 return;
1552
1553         if(self.deadflag == DEAD_NO)
1554                 self.play_time += frametime;
1555
1556         // fixme: don't check players; instead check spawnfunc_dom_team and spawnfunc_ctf_team entities
1557         //   (div0: and that in CheckRules_World please)
1558 }
1559
1560 float checkrules_equality;
1561 float checkrules_suddendeathwarning;
1562 float checkrules_suddendeathend;
1563 float checkrules_overtimesadded; //how many overtimes have been already added
1564
1565 const float WINNING_NO = 0; // no winner, but time limits may terminate the game
1566 const float WINNING_YES = 1; // winner found
1567 const float WINNING_NEVER = 2; // no winner, enter overtime if time limit is reached
1568 const float WINNING_STARTSUDDENDEATHOVERTIME = 3; // no winner, enter suddendeath overtime NOW
1569
1570 float InitiateSuddenDeath()
1571 {
1572         // Check first whether normal overtimes could be added before initiating suddendeath mode
1573         // - for this timelimit_overtime needs to be >0 of course
1574         // - also check the winning condition calculated in the previous frame and only add normal overtime
1575         //   again, if at the point at which timelimit would be extended again, still no winner was found
1576         if (!autocvar_g_campaign && (checkrules_overtimesadded >= 0) && (checkrules_overtimesadded < autocvar_timelimit_overtimes || autocvar_timelimit_overtimes < 0) && autocvar_timelimit_overtime && !(g_race && !g_race_qualifying))
1577         {
1578                 return 1; // need to call InitiateOvertime later
1579         }
1580         else
1581         {
1582                 if(!checkrules_suddendeathend)
1583                 {
1584                         if(autocvar_g_campaign)
1585                                 checkrules_suddendeathend = time; // no suddendeath in campaign
1586                         else
1587                                 checkrules_suddendeathend = time + 60 * autocvar_timelimit_suddendeath;
1588                         if(g_race && !g_race_qualifying)
1589                                 race_StartCompleting();
1590                 }
1591                 return 0;
1592         }
1593 }
1594
1595 void InitiateOvertime() // ONLY call this if InitiateSuddenDeath returned true
1596 {
1597         ++checkrules_overtimesadded;
1598         //add one more overtime by simply extending the timelimit
1599         float tl;
1600         tl = autocvar_timelimit;
1601         tl += autocvar_timelimit_overtime;
1602         cvar_set("timelimit", ftos(tl));
1603
1604         Send_Notification(NOTIF_ALL, world, MSG_CENTER, CENTER_OVERTIME_TIME, autocvar_timelimit_overtime * 60);
1605 }
1606
1607 float GetWinningCode(float fraglimitreached, float equality)
1608 {
1609         if(autocvar_g_campaign == 1)
1610                 if(fraglimitreached)
1611                         return WINNING_YES;
1612                 else
1613                         return WINNING_NO;
1614
1615         else
1616                 if(equality)
1617                         if(fraglimitreached)
1618                                 return WINNING_STARTSUDDENDEATHOVERTIME;
1619                         else
1620                                 return WINNING_NEVER;
1621                 else
1622                         if(fraglimitreached)
1623                                 return WINNING_YES;
1624                         else
1625                                 return WINNING_NO;
1626 }
1627
1628 // set the .winning flag for exactly those players with a given field value
1629 void SetWinners(.float field, float value)
1630 {
1631         entity head;
1632         FOR_EACH_PLAYER(head)
1633                 head.winning = (head.field == value);
1634 }
1635
1636 // set the .winning flag for those players with a given field value
1637 void AddWinners(.float field, float value)
1638 {
1639         entity head;
1640         FOR_EACH_PLAYER(head)
1641                 if(head.field == value)
1642                         head.winning = 1;
1643 }
1644
1645 // clear the .winning flags
1646 void ClearWinners(void)
1647 {
1648         entity head;
1649         FOR_EACH_PLAYER(head)
1650                 head.winning = 0;
1651 }
1652
1653 // Onslaught winning condition:
1654 // game terminates if only one team has a working generator (or none)
1655 float WinningCondition_Onslaught()
1656 {
1657         entity head;
1658         float t1, t2, t3, t4;
1659
1660         WinningConditionHelper(); // set worldstatus
1661
1662         if(warmup_stage)
1663                 return WINNING_NO;
1664
1665         // first check if the game has ended
1666         t1 = t2 = t3 = t4 = 0;
1667         head = find(world, classname, "onslaught_generator");
1668         while (head)
1669         {
1670                 if (head.health > 0)
1671                 {
1672                         if (head.team == NUM_TEAM_1) t1 = 1;
1673                         if (head.team == NUM_TEAM_2) t2 = 1;
1674                         if (head.team == NUM_TEAM_3) t3 = 1;
1675                         if (head.team == NUM_TEAM_4) t4 = 1;
1676                 }
1677                 head = find(head, classname, "onslaught_generator");
1678         }
1679         if (t1 + t2 + t3 + t4 < 2)
1680         {
1681                 // game over, only one team remains (or none)
1682                 ClearWinners();
1683                 if (t1) SetWinners(team, NUM_TEAM_1);
1684                 if (t2) SetWinners(team, NUM_TEAM_2);
1685                 if (t3) SetWinners(team, NUM_TEAM_3);
1686                 if (t4) SetWinners(team, NUM_TEAM_4);
1687                 dprint("Have a winner, ending game.\n");
1688                 return WINNING_YES;
1689         }
1690
1691         // Two or more teams remain
1692         return WINNING_NO;
1693 }
1694
1695 // Assault winning condition: If the attackers triggered a round end (by fulfilling all objectives)
1696 // they win. Otherwise the defending team wins once the timelimit passes.
1697 void assault_new_round();
1698 float WinningCondition_Assault()
1699 {
1700         float status;
1701
1702         WinningConditionHelper(); // set worldstatus
1703
1704         status = WINNING_NO;
1705         // as the timelimit has not yet passed just assume the defending team will win
1706         if(assault_attacker_team == NUM_TEAM_1)
1707         {
1708                 SetWinners(team, NUM_TEAM_2);
1709         }
1710         else
1711         {
1712                 SetWinners(team, NUM_TEAM_1);
1713         }
1714
1715         entity ent;
1716         ent = find(world, classname, "target_assault_roundend");
1717         if(ent)
1718         {
1719                 if(ent.winning) // round end has been triggered by attacking team
1720                 {
1721                         bprint("ASSAULT: round completed...\n");
1722                         SetWinners(team, assault_attacker_team);
1723
1724                         TeamScore_AddToTeam(assault_attacker_team, ST_ASSAULT_OBJECTIVES, 666 - TeamScore_AddToTeam(assault_attacker_team, ST_ASSAULT_OBJECTIVES, 0));
1725
1726                         if(ent.cnt == 1 || autocvar_g_campaign) // this was the second round
1727                         {
1728                                 status = WINNING_YES;
1729                         }
1730                         else
1731                         {
1732                                 entity oldself;
1733                                 oldself = self;
1734                                 self = ent;
1735                                 assault_new_round();
1736                                 self = oldself;
1737                         }
1738                 }
1739         }
1740
1741         return status;
1742 }
1743
1744 // LMS winning condition: game terminates if and only if there's at most one
1745 // one player who's living lives. Top two scores being equal cancels the time
1746 // limit.
1747 float WinningCondition_LMS()
1748 {
1749         entity head, head2;
1750         float have_player;
1751         float have_players;
1752         float l;
1753
1754         have_player = FALSE;
1755         have_players = FALSE;
1756         l = LMS_NewPlayerLives();
1757
1758         head = find(world, classname, "player");
1759         if(head)
1760                 have_player = TRUE;
1761         head2 = find(head, classname, "player");
1762         if(head2)
1763                 have_players = TRUE;
1764
1765         if(have_player)
1766         {
1767                 // we have at least one player
1768                 if(have_players)
1769                 {
1770                         // two or more active players - continue with the game
1771                 }
1772                 else
1773                 {
1774                         // exactly one player?
1775
1776                         ClearWinners();
1777                         SetWinners(winning, 0); // NOTE: exactly one player is still "player", so this works out
1778
1779                         if(l)
1780                         {
1781                                 // game still running (that is, nobody got removed from the game by a frag yet)? then continue
1782                                 return WINNING_NO;
1783                         }
1784                         else
1785                         {
1786                                 // a winner!
1787                                 // and assign him his first place
1788                                 PlayerScore_Add(head, SP_LMS_RANK, 1);
1789                                 return WINNING_YES;
1790                         }
1791                 }
1792         }
1793         else
1794         {
1795                 // nobody is playing at all...
1796                 if(l)
1797                 {
1798                         // wait for players...
1799                 }
1800                 else
1801                 {
1802                         // SNAFU (maybe a draw game?)
1803                         ClearWinners();
1804                         dprint("No players, ending game.\n");
1805                         return WINNING_YES;
1806                 }
1807         }
1808
1809         // When we get here, we have at least two players who are actually LIVING,
1810         // now check if the top two players have equal score.
1811         WinningConditionHelper();
1812
1813         ClearWinners();
1814         if(WinningConditionHelper_winner)
1815                 WinningConditionHelper_winner.winning = TRUE;
1816         if(WinningConditionHelper_topscore == WinningConditionHelper_secondscore)
1817                 return WINNING_NEVER;
1818
1819         // Top two have different scores? Way to go for our beloved TIMELIMIT!
1820         return WINNING_NO;
1821 }
1822
1823 void ShuffleMaplist()
1824 {
1825         cvar_set("g_maplist", shufflewords(autocvar_g_maplist));
1826 }
1827
1828 float leaderfrags;
1829 float WinningCondition_Scores(float limit, float leadlimit)
1830 {
1831         float limitreached;
1832
1833         // TODO make everything use THIS winning condition (except LMS)
1834         WinningConditionHelper();
1835
1836         if(teamplay)
1837         {
1838                 team1_score = TeamScore_GetCompareValue(NUM_TEAM_1);
1839                 team2_score = TeamScore_GetCompareValue(NUM_TEAM_2);
1840                 team3_score = TeamScore_GetCompareValue(NUM_TEAM_3);
1841                 team4_score = TeamScore_GetCompareValue(NUM_TEAM_4);
1842         }
1843
1844         ClearWinners();
1845         if(WinningConditionHelper_winner)
1846                 WinningConditionHelper_winner.winning = 1;
1847         if(WinningConditionHelper_winnerteam >= 0)
1848                 SetWinners(team, WinningConditionHelper_winnerteam);
1849
1850         if(WinningConditionHelper_lowerisbetter)
1851         {
1852                 WinningConditionHelper_topscore = -WinningConditionHelper_topscore;
1853                 WinningConditionHelper_secondscore = -WinningConditionHelper_secondscore;
1854                 limit = -limit;
1855         }
1856
1857         if(WinningConditionHelper_zeroisworst)
1858                 leadlimit = 0; // not supported in this mode
1859
1860         if(g_dm || g_tdm || g_ca || g_freezetag || (g_race && !g_race_qualifying) || g_nexball)
1861         // these modes always score in increments of 1, thus this makes sense
1862         {
1863                 if(leaderfrags != WinningConditionHelper_topscore)
1864                 {
1865                         leaderfrags = WinningConditionHelper_topscore;
1866
1867                         if (limit)
1868                         if (leaderfrags == limit - 1)
1869                                 Send_Notification(NOTIF_ALL, world, MSG_ANNCE, ANNCE_REMAINING_FRAG_1);
1870                         else if (leaderfrags == limit - 2)
1871                                 Send_Notification(NOTIF_ALL, world, MSG_ANNCE, ANNCE_REMAINING_FRAG_2);
1872                         else if (leaderfrags == limit - 3)
1873                                 Send_Notification(NOTIF_ALL, world, MSG_ANNCE, ANNCE_REMAINING_FRAG_3);
1874                 }
1875         }
1876
1877         limitreached = FALSE;
1878         if(limit)
1879                 if(WinningConditionHelper_topscore >= limit)
1880                         limitreached = TRUE;
1881         if(leadlimit)
1882         {
1883                 float leadlimitreached;
1884                 leadlimitreached = (WinningConditionHelper_topscore - WinningConditionHelper_secondscore >= leadlimit);
1885                 if(autocvar_leadlimit_and_fraglimit)
1886                         limitreached = (limitreached && leadlimitreached);
1887                 else
1888                         limitreached = (limitreached || leadlimitreached);
1889         }
1890
1891         if(limit)
1892                 game_completion_ratio = max(game_completion_ratio, bound(0, WinningConditionHelper_topscore / limit, 1));
1893
1894         return GetWinningCode(
1895                 WinningConditionHelper_topscore && limitreached,
1896                 WinningConditionHelper_equality
1897         );
1898 }
1899
1900 float WinningCondition_Race(float fraglimit)
1901 {
1902         float wc;
1903         entity p;
1904         float n, c;
1905
1906         n = 0;
1907         c = 0;
1908         FOR_EACH_PLAYER(p)
1909         {
1910                 ++n;
1911                 if(p.race_completed)
1912                         ++c;
1913         }
1914         if(n && (n == c))
1915                 return WINNING_YES;
1916         wc = WinningCondition_Scores(fraglimit, 0);
1917
1918         // ALWAYS initiate overtime, unless EVERYONE has finished the race!
1919         if(wc == WINNING_YES || wc == WINNING_STARTSUDDENDEATHOVERTIME)
1920         // do NOT support equality when the laps are all raced!
1921                 return WINNING_STARTSUDDENDEATHOVERTIME;
1922         else
1923                 return WINNING_NEVER;
1924 }
1925
1926 float WinningCondition_QualifyingThenRace(float limit)
1927 {
1928         float wc;
1929         wc = WinningCondition_Scores(limit, 0);
1930
1931         // NEVER initiate overtime
1932         if(wc == WINNING_YES || wc == WINNING_STARTSUDDENDEATHOVERTIME)
1933         {
1934                 return WINNING_YES;
1935         }
1936
1937         return wc;
1938 }
1939
1940 float WinningCondition_RanOutOfSpawns()
1941 {
1942         entity head;
1943
1944         if(have_team_spawns <= 0)
1945                 return WINNING_NO;
1946
1947         if(autocvar_g_spawn_useallspawns <= 0)
1948                 return WINNING_NO;
1949
1950         if(!some_spawn_has_been_used)
1951                 return WINNING_NO;
1952
1953         team1_score = team2_score = team3_score = team4_score = 0;
1954
1955         FOR_EACH_PLAYER(head) if(head.deadflag == DEAD_NO)
1956         {
1957                 if(head.team == NUM_TEAM_1)
1958                         team1_score = 1;
1959                 else if(head.team == NUM_TEAM_2)
1960                         team2_score = 1;
1961                 else if(head.team == NUM_TEAM_3)
1962                         team3_score = 1;
1963                 else if(head.team == NUM_TEAM_4)
1964                         team4_score = 1;
1965         }
1966
1967         for(head = world; (head = find(head, classname, "info_player_deathmatch")) != world; )
1968         {
1969                 if(head.team == NUM_TEAM_1)
1970                         team1_score = 1;
1971                 else if(head.team == NUM_TEAM_2)
1972                         team2_score = 1;
1973                 else if(head.team == NUM_TEAM_3)
1974                         team3_score = 1;
1975                 else if(head.team == NUM_TEAM_4)
1976                         team4_score = 1;
1977         }
1978
1979         ClearWinners();
1980         if(team1_score + team2_score + team3_score + team4_score == 0)
1981         {
1982                 checkrules_equality = TRUE;
1983                 return WINNING_YES;
1984         }
1985         else if(team1_score + team2_score + team3_score + team4_score == 1)
1986         {
1987                 float t, i;
1988                 if(team1_score)
1989                         t = NUM_TEAM_1;
1990                 else if(team2_score)
1991                         t = NUM_TEAM_2;
1992                 else if(team3_score)
1993                         t = NUM_TEAM_3;
1994                 else // if(team4_score)
1995                         t = NUM_TEAM_4;
1996                 CheckAllowedTeams(world);
1997                 for(i = 0; i < MAX_TEAMSCORE; ++i)
1998                 {
1999                         if(t != NUM_TEAM_1) if(c1 >= 0) TeamScore_AddToTeam(NUM_TEAM_1, i, -1000);
2000                         if(t != NUM_TEAM_2) if(c2 >= 0) TeamScore_AddToTeam(NUM_TEAM_2, i, -1000);
2001                         if(t != NUM_TEAM_3) if(c3 >= 0) TeamScore_AddToTeam(NUM_TEAM_3, i, -1000);
2002                         if(t != NUM_TEAM_4) if(c4 >= 0) TeamScore_AddToTeam(NUM_TEAM_4, i, -1000);
2003                 }
2004
2005                 AddWinners(team, t);
2006                 return WINNING_YES;
2007         }
2008         else
2009                 return WINNING_NO;
2010 }
2011
2012 /*
2013 ============
2014 CheckRules_World
2015
2016 Exit deathmatch games upon conditions
2017 ============
2018 */
2019 void ReadyRestart();
2020 void CheckRules_World()
2021 {
2022         float timelimit;
2023         float fraglimit;
2024         float leadlimit;
2025
2026         VoteThink();
2027         MapVote_Think();
2028
2029         SetDefaultAlpha();
2030
2031         if (gameover)   // someone else quit the game already
2032         {
2033                 if(player_count == 0) // Nobody there? Then let's go to the next map
2034                         MapVote_Start();
2035                         // this will actually check the player count in the next frame
2036                         // again, but this shouldn't hurt
2037                 return;
2038         }
2039
2040         timelimit = autocvar_timelimit * 60;
2041         fraglimit = autocvar_fraglimit;
2042         leadlimit = autocvar_leadlimit;
2043
2044         if(warmup_stage || time <= game_starttime) // NOTE: this is <= to prevent problems in the very tic where the game starts
2045         {
2046                 if(timelimit > 0)
2047                         timelimit = 0; // timelimit is not made for warmup
2048                 if(fraglimit > 0)
2049                         fraglimit = 0; // no fraglimit for now
2050                 leadlimit = 0; // no leadlimit for now
2051         }
2052
2053         if(timelimit > 0)
2054         {
2055                 timelimit += game_starttime;
2056         }
2057         else if (timelimit < 0)
2058         {
2059                 // endmatch
2060                 NextLevel();
2061                 return;
2062         }
2063
2064         if(g_onslaught)
2065                 timelimit = 0; // ONS has its own overtime rule
2066
2067         float wantovertime;
2068         wantovertime = 0;
2069
2070         if(timelimit > game_starttime)
2071                 game_completion_ratio = (time - game_starttime) / (timelimit - game_starttime);
2072         else
2073                 game_completion_ratio = 0;
2074
2075         if(checkrules_suddendeathend)
2076         {
2077                 if(!checkrules_suddendeathwarning)
2078                 {
2079                         checkrules_suddendeathwarning = TRUE;
2080                         if(g_race && !g_race_qualifying)
2081                                 Send_Notification(NOTIF_ALL, world, MSG_CENTER, CENTER_RACE_FINISHLAP);
2082                         else
2083                                 Send_Notification(NOTIF_ALL, world, MSG_CENTER, CENTER_OVERTIME_FRAG);
2084                 }
2085         }
2086         else
2087         {
2088                 if (timelimit && time >= timelimit)
2089                 {
2090                         if(g_race && (g_race_qualifying == 2) && timelimit > 0)
2091                         {
2092                                 float totalplayers;
2093                                 float playerswithlaps;
2094                                 float readyplayers;
2095                                 entity head;
2096                                 totalplayers = playerswithlaps = readyplayers = 0;
2097                                 FOR_EACH_PLAYER(head)
2098                                 {
2099                                         ++totalplayers;
2100                                         if(PlayerScore_Add(head, SP_RACE_FASTEST, 0))
2101                                                 ++playerswithlaps;
2102                                         if(head.ready)
2103                                                 ++readyplayers;
2104                                 }
2105
2106                                 // at least 2 of the players have completed a lap: start the RACE
2107                                 // otherwise, the players should end the qualifying on their own
2108                                 if(readyplayers || playerswithlaps >= 2)
2109                                 {
2110                                         checkrules_suddendeathend = 0;
2111                                         ReadyRestart(); // go to race
2112                                         return;
2113                                 }
2114                                 else
2115                                         wantovertime |= InitiateSuddenDeath();
2116                         }
2117                         else
2118                                 wantovertime |= InitiateSuddenDeath();
2119                 }
2120         }
2121
2122         if (checkrules_suddendeathend && time >= checkrules_suddendeathend)
2123         {
2124                 NextLevel();
2125                 return;
2126         }
2127
2128         float checkrules_status;
2129         checkrules_status = WinningCondition_RanOutOfSpawns();
2130         if(checkrules_status == WINNING_YES)
2131         {
2132                 bprint("Hey! Someone ran out of spawns!\n");
2133         }
2134         else if(g_race && !g_race_qualifying && timelimit >= 0)
2135         {
2136                 checkrules_status = WinningCondition_Race(fraglimit);
2137                 //print("WC_RACE yields ", ftos(checkrules_status), "\n");
2138         }
2139         else if(g_race && g_race_qualifying == 2 && timelimit >= 0)
2140         {
2141                 checkrules_status = WinningCondition_QualifyingThenRace(fraglimit);
2142                 //print("WC_QUALIFYING_THEN_RACE yields ", ftos(checkrules_status), "\n");
2143         }
2144         else if(g_assault)
2145         {
2146                 checkrules_status = WinningCondition_Assault(); // TODO remove this?
2147         }
2148         else if(g_lms)
2149         {
2150                 checkrules_status = WinningCondition_LMS();
2151         }
2152         else if (g_onslaught)
2153         {
2154                 checkrules_status = WinningCondition_Onslaught(); // TODO remove this?
2155         }
2156         else
2157         {
2158                 checkrules_status = WinningCondition_Scores(fraglimit, leadlimit);
2159                 //print("WC_SCORES yields ", ftos(checkrules_status), "\n");
2160         }
2161
2162         if(checkrules_status == WINNING_STARTSUDDENDEATHOVERTIME)
2163         {
2164                 checkrules_status = WINNING_NEVER;
2165                 checkrules_overtimesadded = -1;
2166                 wantovertime |= InitiateSuddenDeath();
2167         }
2168
2169         if(checkrules_status == WINNING_NEVER)
2170                 // equality cases! Nobody wins if the overtime ends in a draw.
2171                 ClearWinners();
2172
2173         if(wantovertime)
2174         {
2175                 if(checkrules_status == WINNING_NEVER)
2176                         InitiateOvertime();
2177                 else
2178                         checkrules_status = WINNING_YES;
2179         }
2180
2181         if(checkrules_suddendeathend)
2182                 if(checkrules_status != WINNING_NEVER || time >= checkrules_suddendeathend)
2183                         checkrules_status = WINNING_YES;
2184
2185         if(checkrules_status == WINNING_YES)
2186         {
2187                 //print("WINNING\n");
2188                 NextLevel();
2189         }
2190 }
2191
2192 string GotoMap(string m)
2193 {
2194         m = GameTypeVote_MapInfo_FixName(m);
2195         if (!m)
2196                 return "The map you suggested is not available on this server.";
2197         if (!autocvar_sv_vote_gametype)
2198         if(!MapInfo_CheckMap(m))
2199                 return "The map you suggested does not support the current game mode.";
2200         cvar_set("nextmap", m);
2201         cvar_set("timelimit", "-1");
2202         if(mapvote_initialized || alreadychangedlevel)
2203         {
2204                 if(DoNextMapOverride(0))
2205                         return "Map switch initiated.";
2206                 else
2207                         return "Hm... no. For some reason I like THIS map more.";
2208         }
2209         else
2210                 return "Map switch will happen after scoreboard.";
2211 }
2212
2213
2214 void EndFrame()
2215 {
2216         anticheat_endframe();
2217
2218         float altime;
2219         FOR_EACH_REALCLIENT(self)
2220         {
2221                 entity e = IS_SPEC(self) ? self.enemy : self;
2222                 if(e.typehitsound)
2223                         self.typehit_time = time;
2224                 else if(e.damage_dealt)
2225                 {
2226                         self.hit_time = time;
2227                         self.damage_dealt_total += ceil(e.damage_dealt);
2228                 }
2229         }
2230         altime = time + frametime * (1 + autocvar_g_antilag_nudge);
2231         // add 1 frametime because after this, engine SV_Physics
2232         // increases time by a frametime and then networks the frame
2233         // add another frametime because client shows everything with
2234         // 1 frame of lag (cl_nolerp 0). The last +1 however should not be
2235         // needed!
2236         FOR_EACH_CLIENT(self)
2237         {
2238                 self.typehitsound = FALSE;
2239                 self.damage_dealt = 0;
2240                 antilag_record(self, altime);
2241         }
2242         FOR_EACH_MONSTER(self)
2243                 antilag_record(self, altime);
2244 }
2245
2246
2247 /*
2248  * RedirectionThink:
2249  * returns TRUE if redirecting
2250  */
2251 float redirection_timeout;
2252 float redirection_nextthink;
2253 float RedirectionThink()
2254 {
2255         float clients_found;
2256
2257         if(redirection_target == "")
2258                 return FALSE;
2259
2260         if(!redirection_timeout)
2261         {
2262                 cvar_set("sv_public", "-2");
2263                 redirection_timeout = time + 0.6; // this will only try twice... should be able to keep more clients
2264                 if(redirection_target == "self")
2265                         bprint("^3SERVER NOTICE:^7 restarting the server\n");
2266                 else
2267                         bprint("^3SERVER NOTICE:^7 redirecting everyone to ", redirection_target, "\n");
2268         }
2269
2270         if(time < redirection_nextthink)
2271                 return TRUE;
2272
2273         redirection_nextthink = time + 1;
2274
2275         clients_found = 0;
2276         FOR_EACH_REALCLIENT(self)
2277         {
2278                 // TODO add timer
2279                 print("Redirecting: sending connect command to ", self.netname, "\n");
2280                 if(redirection_target == "self")
2281                         stuffcmd(self, "\ndisconnect; defer ", ftos(autocvar_quit_and_redirect_timer), " reconnect\n");
2282                 else
2283                         stuffcmd(self, strcat("\ndisconnect; defer ", ftos(autocvar_quit_and_redirect_timer), " \"connect ", redirection_target, "\"\n"));
2284                 ++clients_found;
2285         }
2286
2287         print("Redirecting: ", ftos(clients_found), " clients left.\n");
2288
2289         if(time > redirection_timeout || clients_found == 0)
2290                 localcmd("\nwait; wait; wait; quit\n");
2291
2292         return TRUE;
2293 }
2294
2295 void TargetMusic_RestoreGame();
2296 void RestoreGame()
2297 {
2298         // Loaded from a save game
2299         // some things then break, so let's work around them...
2300
2301         // Progs DB (capture records)
2302         ServerProgsDB = db_load(strcat("server.db", autocvar_sessionid));
2303
2304         // Mapinfo
2305         MapInfo_Shutdown();
2306         MapInfo_Enumerate();
2307         MapInfo_FilterGametype(MapInfo_CurrentGametype(), MapInfo_CurrentFeatures(), MapInfo_RequiredFlags(), MapInfo_ForbiddenFlags(), 1);
2308         WeaponStats_Init();
2309
2310         TargetMusic_RestoreGame();
2311 }
2312
2313 void Shutdown()
2314 {
2315         gameover = 2;
2316
2317         if(world_initialized > 0)
2318         {
2319                 world_initialized = 0;
2320                 print("Saving persistent data...\n");
2321                 Ban_SaveBans();
2322
2323                 // playerstats with unfinished match
2324                 PlayerStats_GameReport(FALSE);
2325
2326                 if(!cheatcount_total)
2327                 {
2328                         if(autocvar_sv_db_saveasdump)
2329                                 db_dump(ServerProgsDB, strcat("server.db", autocvar_sessionid));
2330                         else
2331                                 db_save(ServerProgsDB, strcat("server.db", autocvar_sessionid));
2332                 }
2333                 if(autocvar_developer)
2334                 {
2335                         if(autocvar_sv_db_saveasdump)
2336                                 db_dump(TemporaryDB, "server-temp.db");
2337                         else
2338                                 db_save(TemporaryDB, "server-temp.db");
2339                 }
2340                 CheatShutdown(); // must be after cheatcount check
2341                 db_close(ServerProgsDB);
2342                 db_close(TemporaryDB);
2343                 print("done!\n");
2344                 // tell the bot system the game is ending now
2345                 bot_endgame();
2346
2347                 WeaponStats_Shutdown();
2348                 MapInfo_Shutdown();
2349         }
2350         else if(world_initialized == 0)
2351         {
2352                 print("NOTE: crashed before even initializing the world, not saving persistent data\n");
2353         }
2354 }