2 void PingPLReport_Think()
7 delta = 3 / maxclients;
8 if(delta < sys_frametime)
10 self.nextthink = time + delta;
12 e = edict_num(self.cnt + 1);
13 if(clienttype(e) == CLIENTTYPE_REAL)
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));
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);
31 self.cnt = mod(self.cnt + 1, maxclients);
33 void PingPLReport_Spawn()
35 pingplreport = spawn();
36 pingplreport.classname = "pingplreport";
37 pingplreport.think = PingPLReport_Think;
38 pingplreport.nextthink = time;
41 float SPAWNFLAG_NO_WAYPOINTS_FOR_ITEMS = 1;
42 string redirection_target;
43 float world_initialized;
49 float() DoNextMapOverride;
51 void SetDefaultAlpha()
53 if(cvar("g_running_guns"))
55 default_player_alpha = -1;
56 default_weapon_alpha = +1;
60 default_player_alpha = cvar("g_balance_cloaked_alpha");
61 default_weapon_alpha = default_player_alpha;
65 default_player_alpha = cvar("g_player_alpha");
66 if(default_player_alpha == 0)
67 default_player_alpha = 1;
68 default_weapon_alpha = default_player_alpha;
72 void fteqcc_testbugs()
76 if(!cvar("developer_fteqccbugs"))
79 dprint("*** fteqcc test: checking for bugs...\n");
83 if(sqrt(a) - sqrt(b - a) == 0)
84 dprint("*** fteqcc test: found same-function-twice bug\n");
86 dprint("*** fteqcc test: same-function-twice bug got FINALLY FIXED! HOORAY!\n");
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");
94 dprint("*** fteqcc test: += bug got FINALLY FIXED! HOORAY!\n");
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.
103 void timeoutHandler_Think() {
104 local string timeStr;
106 if (timeoutStatus == 1) {
107 if (remainingLeadTime > 0) {
108 //centerprint the information to every player
109 timeStr = getTimeoutText(0);
110 FOR_EACH_REALCLIENT(plr) {
111 if(plr.classname == "player") {
112 centerprint_atprio(plr, CENTERPRIO_SPAM, timeStr);
115 remainingLeadTime -= 1;
116 //think again in 1 second:
117 self.nextthink = time + 1;
120 //now pause the game:
122 //reset all the flood variables
123 FOR_EACH_CLIENT(plr) {
124 plr.nickspamcount = plr.nickspamtime = plr.floodcontrol_chat = plr.floodcontrol_chatteam = plr.floodcontrol_chattell = plr.floodcontrol_voice = plr.floodcontrol_voiceteam = 0;
126 cvar_set("slowmo", ftos(TIMEOUT_SLOWMO_VALUE));
127 //copy .v_angle to .lastV_angle for every player in order to fix their view during pause (see PlayerPreThink)
128 FOR_EACH_REALPLAYER(plr) {
129 plr.lastV_angle = plr.v_angle;
131 self.nextthink = time;
134 else if (timeoutStatus == 2) {
135 if (remainingTimeoutTime > 0) {
136 timeStr = getTimeoutText(0);
137 FOR_EACH_REALCLIENT(plr) {
138 if(plr.classname == "player") {
139 centerprint_atprio(plr, CENTERPRIO_SPAM, timeStr);
142 if(remainingTimeoutTime == cvar("sv_timeout_resumetime")) { //play a warning sound when only <sv_timeout_resumetime> seconds are left
143 play2all("announcer/robotic/prepareforbattle.wav");
145 remainingTimeoutTime -= 1;
146 self.nextthink = time + TIMEOUT_SLOWMO_VALUE;
149 //unpause the game again
150 remainingTimeoutTime = timeoutStatus = 0;
151 cvar_set("slowmo", ftos(orig_slowmo));
152 //and unlock the fixed view again once there is no timeout active anymore
153 FOR_EACH_REALPLAYER(plr) {
154 plr.fixangle = FALSE;
156 //get rid of the countdown message
157 FOR_EACH_REALCLIENT(plr) {
158 if(plr.classname == "player") {
159 centerprint_atprio(plr, CENTERPRIO_SPAM, "");
167 else if (timeoutStatus == 0) { //if a player called the resumegame command (which set timeoutStatus to 0 already)
168 FOR_EACH_REALCLIENT(plr) {
169 if(plr.classname == "player") {
170 centerprint_atprio(plr, CENTERPRIO_SPAM, "");
183 // cvar_set("_sv_init", "0");
184 // we do NOT set this to 0 any more, so someone "accidentally" changing
185 // to this "init" map on a dedicated server will cause no permanent
187 if(cvar("g_maplist_shuffle"))
189 n = tokenizebyseparator(cvar_string("g_maplist"), " ");
190 cvar_set("g_maplist_index", ftos(n - 1)); // jump to map 0 in GotoNextMap
193 MapInfo_FilterGametype(MapInfo_CurrentGametype(), MapInfo_CurrentFeatures(), MapInfo_RequiredFlags(), MapInfo_ForbiddenFlags(), 0);
195 if(!DoNextMapOverride())
203 self.nextthink = time;
207 self.nextthink = time + 1;
208 print("Waiting for _sv_init being set to 1 by initialization scripts...\n");
212 void cvar_changes_init()
219 strunzone(cvar_changes);
220 cvar_changes = string_null;
223 buf_cvarlist(h, "", "_"); // exclude all _ cvars as they are temporary
226 for(i = 0; i < n; ++i)
228 k = bufstr_get(h, i);
230 #define BADPREFIX(p) if(substring(k, 0, strlen(p)) == p) continue
231 #define BADCVAR(p) if(k == p) continue
234 BADPREFIX("cvar_check_");
236 BADCVAR("g_configversion");
237 BADCVAR("g_maplist_index");
238 BADCVAR("halflifebsp");
243 BADPREFIX("g_campaign");
247 BADPREFIX("net_slist_");
251 BADPREFIX("userbind");
254 BADPREFIX("crosshair");
255 BADCVAR("mod_q3bsp_lightmapmergepower");
256 BADCVAR("mod_q3bsp_nolightmaps");
259 BADCVAR("serverconfig");
261 BADPREFIX("g_chat_flood_");
262 BADPREFIX("g_voice_flood_");
264 BADPREFIX("settemp_");
265 BADPREFIX("sv_allowdownloads_");
266 BADPREFIX("sv_autodemo");
267 BADPREFIX("sv_curl_");
268 BADPREFIX("sv_eventlog");
269 BADPREFIX("sv_logscores_");
270 BADPREFIX("sv_master");
271 BADCVAR("g_banned_list");
272 BADCVAR("log_dest_udp");
274 BADCVAR("net_address");
276 BADCVAR("savedgamecfg");
277 BADCVAR("sv_heartbeatperiod");
278 BADCVAR("sv_vote_master_password");
279 BADCVAR("sys_colortranslation");
280 BADCVAR("sys_specialcharactertranslation");
281 BADCVAR("timestamps");
284 BADCVAR("timelimit");
285 BADCVAR("fraglimit");
288 BADCVAR("g_assault");
291 BADCVAR("g_domination");
292 BADCVAR("g_keyhunt");
293 BADCVAR("g_keyhunt_teams");
294 BADCVAR("g_onslaught");
297 BADCVAR("g_runematch");
299 BADCVAR("g_nexball");
304 BADCVAR("g_maplist");
305 BADCVAR("g_maplist_mostrecent");
311 d = cvar_defstring(k);
314 cvar_changes = strcat(cvar_changes, k, " \"", v, "\" // \"", d, "\"\n");
315 if(strlen(cvar_changes) > 16384)
317 cvar_changes = "// too many settings have been changed to show them here\n";
323 if(cvar_changes == "")
324 cvar_changes = "// this server runs at default settings\n";
326 cvar_changes = strcat("// this server runs at modified settings:\n", cvar_changes);
327 cvar_changes = strzone(cvar_changes);
330 void detect_maptype()
339 o_x += random() * (world.maxs_x - world.mins_x);
340 o_y += random() * (world.maxs_y - world.mins_y);
341 o_z += random() * (world.maxs_z - world.mins_z);
343 tracebox(o, PL_MIN, PL_MAX, o - '0 0 32768', MOVE_WORLDONLY, world);
344 if(trace_fraction == 1)
349 for(i = 0; i < 64; i += 4)
351 tracebox(o, '-1 -1 -1' * i, '1 1 1' * i, o - '0 0 32768', MOVE_WORLDONLY, world);
352 if(trace_fraction == 1)
354 print(ftos(i), " -> ", vtos(trace_endpos), "\n");
363 float RandomSeed_Send(entity to, float sf)
365 WriteByte(MSG_ENTITY, ENT_CLIENT_RANDOMSEED);
366 WriteShort(MSG_ENTITY, self.cnt);
369 void RandomSeed_Think()
371 self.cnt = bound(0, floor(random() * 65536), 65535);
372 self.nextthink = time + 5;
376 void RandomSeed_Spawn()
378 randomseed = spawn();
379 randomseed.think = RandomSeed_Think;
380 Net_LinkEntity(randomseed, FALSE, 0, RandomSeed_Send);
385 self.think(); // sets random seed and nextthink
389 void spawnfunc___init_dedicated_server(void)
391 // handler for _init/_init map (only for dedicated server initialization)
393 world_initialized = -1; // don't complain
395 cvar_string = cvar_string_normal;
396 cvar_set = cvar_set_normal;
398 remove = remove_unsafely;
402 e.think = GotoFirstMap;
403 e.nextthink = time; // this is usually 1 at this point
406 e.classname = "info_player_deathmatch"; // safeguard against player joining
408 self.classname = "worldspawn"; // safeguard against various stuff ;)
411 MapInfo_FilterGametype(MapInfo_CurrentGametype(), MapInfo_CurrentFeatures(), MapInfo_RequiredFlags(), MapInfo_ForbiddenFlags(), 0);
414 void Map_MarkAsRecent(string m);
415 float world_already_spawned;
416 void RegisterWeapons();
418 void ClientInit_Spawn();
419 void WeaponStats_Init();
420 void WeaponStats_Shutdown();
421 void spawnfunc_worldspawn (void)
423 float fd, l, i, j, n;
427 cvar_string = cvar_string_normal;
428 cvar_set = cvar_set_normal;
430 if(world_already_spawned)
431 error("world already spawned - you may have EXACTLY ONE worldspawn!");
432 world_already_spawned = TRUE;
434 remove = remove_safely; // during spawning, watch what you remove!
436 check_unacceptable_compiler_bugs();
438 compressShortVector_init();
441 head = nextent(world);
446 head = nextent(head);
449 // needs to be done so early as they would still spawn
453 ServerProgsDB = db_create();
455 ServerProgsDB = db_load("server.db");
457 TemporaryDB = db_create();
460 TODO sound pack system
461 // initialize sound pack system
462 soundpack = cvar_string("g_soundpack");
464 soundpack = strcat(soundpack, "/");
465 soundpack = strzone(soundpack);
471 // 1 FLICKER (first variety)
472 lightstyle(1, "mmnmmommommnonmmonqnmmo");
474 // 2 SLOW STRONG PULSE
475 lightstyle(2, "abcdefghijklmnopqrstuvwxyzyxwvutsrqponmlkjihgfedcba");
477 // 3 CANDLE (first variety)
478 lightstyle(3, "mmmmmaaaaammmmmaaaaaabcdefgabcdefg");
481 lightstyle(4, "mamamamamama");
484 lightstyle(5,"jklmnopqrstuvwxyzyxwvutsrqponmlkj");
486 // 6 FLICKER (second variety)
487 lightstyle(6, "nmonqnmomnmomomno");
489 // 7 CANDLE (second variety)
490 lightstyle(7, "mmmaaaabcdefgmmmmaaaammmaamm");
492 // 8 CANDLE (third variety)
493 lightstyle(8, "mmmaaammmaaammmabcdefaaaammmmabcdefmmmaaaa");
495 // 9 SLOW STROBE (fourth variety)
496 lightstyle(9, "aaaaaaaazzzzzzzz");
498 // 10 FLUORESCENT FLICKER
499 lightstyle(10, "mmamammmmammamamaaamammma");
501 // 11 SLOW PULSE NOT FADE TO BLACK
502 lightstyle(11, "abcdefghijklmnopqrrqponmlkjihgfedcba");
504 // styles 32-62 are assigned by the spawnfunc_light program for switchable lights
509 if(cvar("g_campaign"))
512 Map_MarkAsRecent(mapname);
514 precache_model ("null"); // we need this one before InitGameplayMode
520 bot_waypoints_for_items = cvar("g_waypoints_for_items");
521 if(bot_waypoints_for_items == 1)
522 if(self.spawnflags & SPAWNFLAG_NO_WAYPOINTS_FOR_ITEMS)
523 bot_waypoints_for_items = 0;
525 // for setting by mapinfo
526 q3acompat_machineshotgunswap = cvar("sv_q3acompat_machineshotgunswap");
527 cvar_set("sv_q3acompat_machineshotgunswap", "0");
531 WaypointSprite_Init();
536 GameLogInit(); // prepare everything
537 if(cvar("sv_eventlog"))
539 s = strcat(cvar_string("sv_eventlog_files_counter"), ".");
540 s = strcat(s, ftos(random()));
541 matchid = strzone(s);
543 GameLogEcho(strcat(":gamestart:", GetGametype(), "_", GetMapname(), ":", s));
544 s = ":gameinfo:mutators:LIST";
545 if(cvar("g_grappling_hook"))
546 s = strcat(s, ":grappling_hook");
547 if(!cvar("g_use_ammunition"))
548 s = strcat(s, ":no_use_ammunition");
549 if(!cvar("g_pickup_items"))
550 s = strcat(s, ":no_pickup_items");
551 if(cvar_string("g_weaponarena") != "0")
552 s = strcat(s, ":", cvar_string("g_weaponarena"), " arena");
554 s = strcat(s, ":nixnex");
555 if(cvar("g_vampire"))
556 s = strcat(s, ":vampire");
557 if(cvar("g_laserguided_missile"))
558 s = strcat(s, ":laserguided_missile");
559 if(cvar("g_norecoil"))
560 s = strcat(s, ":norecoil");
562 s = strcat(s, ":midair");
563 if(cvar("g_minstagib"))
564 s = strcat(s, ":minstagib");
566 GameLogEcho(":gameinfo:end");
569 matchid = strzone(ftos(random()));
571 cvar_set("nextmap", "");
575 if(cvar("g_campaign"))
583 MapInfo_FilterGametype(MapInfo_CurrentGametype(), MapInfo_CurrentFeatures(), MapInfo_RequiredFlags(), MapInfo_ForbiddenFlags(), 1);
585 if(whichpack(strcat("maps/", mapname, ".cfg")) != "")
587 fd = fopen(strcat("maps/", mapname, ".cfg"), FILE_READ);
590 while((s = fgets(fd)))
592 l = tokenize_console(s);
597 print("Found ^1DEPRECATED^7 cd loop command in .cfg file; put this line in mapinfo instead:\n");
598 print(" cdtrack ", argv(2), "\n");
600 else if(argv(0) == "fog")
602 print("Found ^1DEPRECATED^7 fog command in .cfg file; put this line in worldspawn in the .map/.bsp/.ent file instead:\n");
603 print(" \"fog\" \"", s, "\"\n");
605 else if(argv(0) == "set")
607 print("Found ^1DEPRECATED^7 set command in .cfg file; put this line in mapinfo instead:\n");
608 print(" clientsettemp_for_type all ", argv(1), " ", argv(2), "\n");
610 else if(argv(0) != "//")
612 print("Found ^1DEPRECATED^7 set command in .cfg file; put this line in mapinfo instead:\n");
613 print(" clientsettemp_for_type all ", argv(0), " ", argv(1), "\n");
622 addstat(STAT_WEAPONS, AS_INT, weapons);
623 addstat(STAT_SWITCHWEAPON, AS_INT, switchweapon);
624 addstat(STAT_GAMESTARTTIME, AS_FLOAT, stat_game_starttime);
625 addstat(STAT_ALLOW_OLDNEXBEAM, AS_INT, stat_allow_oldnexbeam);
628 addstat(STAT_STRENGTH_FINISHED, AS_FLOAT, strength_finished);
629 addstat(STAT_INVINCIBLE_FINISHED, AS_FLOAT, invincible_finished);
630 addstat(STAT_PRESSED_KEYS, AS_FLOAT, pressedkeys);
631 addstat(STAT_FUEL, AS_INT, ammo_fuel);
632 addstat(STAT_DAMAGE_HITS, AS_INT, stat_hit);
633 addstat(STAT_DAMAGE_FIRED, AS_INT, stat_fired);
634 addstat(STAT_SHOTORG, AS_INT, stat_shotorg);
635 addstat(STAT_LEADLIMIT, AS_FLOAT, stat_leadlimit);
636 addstat(STAT_BULLETS_LOADED, AS_INT, campingrifle_bulletcounter);
638 next_pingtime = time + 5;
639 InitializeEntity(self, cvar_changes_init, INITPRIO_CVARS);
643 lsmaps_reply = "^7Maps available: ";
644 for(i = 0, j = 0; i < MapInfo_count; ++i)
646 if(MapInfo_Get_ByID(i))
647 if not(MapInfo_Map_flags & (MAPINFO_FLAG_HIDDEN | MAPINFO_FLAG_FORBIDDEN))
654 lsmaps_reply = strcat(lsmaps_reply, col, MapInfo_Map_bspname, " ");
657 lsmaps_reply = strzone(strcat(lsmaps_reply, "\n"));
659 maplist_reply = "^7Maps in list: ";
660 n = tokenize_console(cvar_string("g_maplist"));
661 for(i = 0, j = 0; i < n; ++i)
663 if(MapInfo_CheckMap(argv(i)))
669 maplist_reply = strcat(maplist_reply, col, argv(i), " ");
673 maplist_reply = strzone(strcat(maplist_reply, "\n"));
674 MapInfo_ClearTemps();
676 records_reply = strzone(getrecords());
677 rankings_reply = strzone(getrankings());
681 PingPLReport_Spawn();
683 localcmd("\n_sv_hook_gamestart ", GetGametype(), ";");
685 world_initialized = 1;
688 void spawnfunc_light (void)
690 //makestatic (self); // Who the f___ did that?
694 float TryFile( string pFilename )
697 dprint("TryFile(\"", pFilename, "\")\n");
698 lHandle = fopen( pFilename, FILE_READ );
699 if( lHandle != -1 ) {
709 return GametypeNameFromType(game);
712 string getmapname_stored;
718 float Map_Count, Map_Current;
719 string Map_Current_Name;
721 // NOTE: this now expects the map list to be already tokenize()d and the count in Map_Count
722 float GetMaplistPosition()
728 idx = cvar("g_maplist_index");
735 for(pos = 0; pos < Map_Count; ++pos)
739 // resume normal maplist rotation if current map is not in g_maplist
743 float MapHasRightSize(string map)
746 if(currentbots || cvar("bot_number") || player_count < cvar("minplayers"))
747 if(cvar("g_maplist_check_waypoints"))
749 dprint("checkwp "); dprint(map);
750 fh = fopen(strcat("maps/", map, ".waypoints"), FILE_READ);
753 dprint(": no waypoints\n");
756 dprint(": has waypoints\n");
760 // open map size restriction file
761 dprint("opensize "); dprint(map);
762 fh = fopen(strcat("maps/", map, ".sizes"), FILE_READ);
765 float mapmin, mapmax;
767 mapmin = stof(fgets(fh));
768 mapmax = stof(fgets(fh));
770 if(player_count < mapmin)
772 dprint("not enough\n");
775 if(player_count > mapmax)
777 dprint("too many\n");
780 dprint("right size\n");
783 dprint(": not found\n");
787 string Map_Filename(float position)
789 return strcat("maps/", argv(position), ".bsp");
792 string strwords(string s, float w)
795 for(endpos = 0; w && endpos >= 0; --w)
796 endpos = strstrofs(s, " ", endpos + 1);
800 return substring(s, 0, endpos);
803 float strhasword(string s, string w)
805 return strstrofs(strcat(" ", s, " "), strcat(" ", w, " "), 0) >= 0;
808 void Map_MarkAsRecent(string m)
810 cvar_set("g_maplist_mostrecent", strwords(strcat(m, " ", cvar_string("g_maplist_mostrecent")), max(0, cvar("g_maplist_mostrecent_count"))));
813 float Map_IsRecent(string m)
815 return strhasword(cvar_string("g_maplist_mostrecent"), m);
818 float Map_Check(float position, float pass)
822 map_next = argv(position);
825 if(Map_IsRecent(map_next))
828 filename = Map_Filename(position);
829 if(MapInfo_CheckMap(map_next))
833 if(MapHasRightSize(map_next))
838 dprint( "Couldn't select '", filename, "'..\n" );
843 void Map_Goto_SetStr(string nextmapname)
845 if(getmapname_stored != "")
846 strunzone(getmapname_stored);
847 if(nextmapname == "")
848 getmapname_stored = "";
850 getmapname_stored = strzone(nextmapname);
853 void Map_Goto_SetFloat(float position)
855 cvar_set("g_maplist_index", ftos(position));
856 Map_Goto_SetStr(argv(position));
861 // settings persist, except...
862 localcmd("\nsettemp_restore\n");
868 MapInfo_LoadMap(getmapname_stored);
871 // return codes of map selectors:
872 // -1 = temporary failure (that is, try some method that is guaranteed to succeed)
873 // -2 = permanent failure
874 float() MaplistMethod_Iterate = // usual method
878 for(pass = 1; pass <= 2; ++pass)
880 for(i = 1; i < Map_Count; ++i)
883 mapindex = mod(i + Map_Current, Map_Count);
884 if(Map_Check(mapindex, pass))
891 float() MaplistMethod_Repeat = // fallback method
893 if(Map_Check(Map_Current, 2))
898 float() MaplistMethod_Random = // random map selection
904 for(i = 0; i <= imax; ++i)
907 mapindex = mod(Map_Current + floor(random() * (Map_Count - 1) + 1), Map_Count); // any OTHER map
908 if(Map_Check(mapindex, 1))
914 float(float exponent) MaplistMethod_Shuffle = // more clever shuffling
915 // the exponent sets a bias on the map selection:
916 // the higher the exponent, the less likely "shortly repeated" same maps are
918 float i, j, imax, insertpos;
922 for(i = 0; i <= imax; ++i)
926 // now reinsert this at another position
927 insertpos = pow(random(), 1 / exponent); // ]0, 1]
928 insertpos = insertpos * (Map_Count - 1); // ]0, Map_Count - 1]
929 insertpos = ceil(insertpos) + 1; // {2, 3, 4, ..., Map_Count}
930 dprint("SHUFFLE: insert pos = ", ftos(insertpos), "\n");
932 // insert the current map there
934 for(j = 1; j < insertpos; ++j) // i == 1: no loop, will be inserted as first; however, i == 1 has been excluded above
935 newlist = strcat(newlist, " ", argv(j));
936 newlist = strcat(newlist, " ", argv(0)); // now insert the just selected map
937 for(j = insertpos; j < Map_Count; ++j) // i == Map_Count: no loop, has just been inserted as last
938 newlist = strcat(newlist, " ", argv(j));
939 newlist = substring(newlist, 1, strlen(newlist) - 1);
940 cvar_set("g_maplist", newlist);
941 Map_Count = tokenizebyseparator(cvar_string("g_maplist"), " ");
943 // NOTE: the selected map has just been inserted at (insertpos-1)th position
944 Map_Current = insertpos - 1; // this is not really valid, but this way the fallback has a chance of working
945 if(Map_Check(Map_Current, 1))
953 Map_Count = tokenizebyseparator(cvar_string("g_maplist"), " ");
956 bprint( "Maplist is empty! Resetting it to default map list.\n" );
957 cvar_set("g_maplist", MapInfo_ListAllowedMaps(MapInfo_RequiredFlags(), MapInfo_ForbiddenFlags()));
958 if(cvar("g_maplist_shuffle"))
960 localcmd("\nmenu_cmd sync\n");
961 Map_Count = tokenizebyseparator(cvar_string("g_maplist"), " ");
964 error("empty maplist, cannot select a new map");
965 Map_Current = bound(0, GetMaplistPosition(), Map_Count - 1);
968 strunzone(Map_Current_Name);
969 Map_Current_Name = strzone(argv(Map_Current)); // will be automatically freed on exit thanks to DP
970 // this may or may not be correct, but who cares, in the worst case a map
971 // isn't chosen in the first pass that should have been
982 if(cvar("g_maplist_shuffle") > 0)
983 nextMap = MaplistMethod_Shuffle(cvar("g_maplist_shuffle") + 1);
986 if(cvar("g_maplist_selectrandom"))
987 nextMap = MaplistMethod_Random();
990 nextMap = MaplistMethod_Iterate();
993 nextMap = MaplistMethod_Repeat();
997 Map_Goto_SetFloat(nextMap);
998 return getmapname_stored;
1004 float DoNextMapOverride()
1006 if(cvar("g_campaign"))
1008 CampaignPostIntermission();
1009 alreadychangedlevel = TRUE;
1012 if(cvar("quit_when_empty"))
1014 if(player_count <= currentbots)
1017 alreadychangedlevel = TRUE;
1021 if(cvar_string("quit_and_redirect") != "")
1023 redirection_target = strzone(cvar_string("quit_and_redirect"));
1024 alreadychangedlevel = TRUE;
1027 if (cvar("samelevel")) // if samelevel is set, stay on same level
1029 // this does not work because it tries to exec maps/nexdm01.mapcfg (which doesn't exist, it should be trying maps/dm_nexdm01.mapcfg for example)
1030 //localcmd(strcat("exec \"maps/", mapname, ".mapcfg\"\n"));
1031 // so instead just restart the current map using the restart command (DOES NOT WORK PROPERLY WITH exit_cfg STUFF)
1032 localcmd("restart\n");
1033 //changelevel (mapname);
1034 alreadychangedlevel = TRUE;
1037 if(cvar_string("nextmap") != "")
1038 if(MapInfo_CheckMap(cvar_string("nextmap")))
1040 Map_Goto_SetStr(cvar_string("nextmap"));
1042 alreadychangedlevel = TRUE;
1045 if(cvar("lastlevel"))
1048 localcmd("set lastlevel 0\ntogglemenu\n");
1049 alreadychangedlevel = TRUE;
1057 //local string nextmap;
1058 //local float n, nummaps;
1060 if (alreadychangedlevel)
1062 alreadychangedlevel = TRUE;
1068 for(allowReset = 1; allowReset >= 0; --allowReset)
1070 nextMap = GetNextMap();
1076 bprint( "Maplist contains no single playable map! Resetting it to default map list.\n" );
1077 cvar_set("g_maplist", MapInfo_ListAllowedMaps(MapInfo_RequiredFlags(), MapInfo_ForbiddenFlags()));
1078 if(cvar("g_maplist_shuffle"))
1080 localcmd("\nmenu_cmd sync\n");
1084 error("Everything is broken - not even the default map list works. Please report this to the developers.");
1096 When the player presses attack or jump, change to the next level
1099 .float autoscreenshot;
1100 void() MapVote_Start;
1101 void() MapVote_Think;
1102 float mapvote_initialized;
1103 void IntermissionThink()
1105 FixIntermissionClient(self);
1107 if(cvar("sv_autoscreenshot"))
1108 if(self.autoscreenshot > 0)
1109 if(time > self.autoscreenshot)
1111 self.autoscreenshot = -1;
1112 if(clienttype(self) == CLIENTTYPE_REAL)
1113 stuffcmd(self, "\nscreenshot\necho \"^5A screenshot has been taken at request of the server.\"\n");
1117 if (time < intermission_exittime)
1120 if(!mapvote_initialized)
1121 if (time < intermission_exittime + 10 && !self.BUTTON_ATCK && !self.BUTTON_JUMP && !self.BUTTON_ATCK2 && !self.BUTTON_HOOK && !self.BUTTON_USE)
1131 Returns the entity to view from
1135 entity FindIntermission()
1140 // look for info_intermission first
1141 spot = find (world, classname, "info_intermission");
1143 { // pick a random one
1147 spot = find (spot, classname, "info_intermission");
1149 spot = find (spot, classname, "info_intermission");
1155 // then look for the start position
1156 spot = find (world, classname, "info_player_start");
1160 // testinfo_player_start is only found in regioned levels
1161 spot = find (world, classname, "testplayerstart");
1165 // then look for the start position
1166 spot = find (world, classname, "info_player_deathmatch");
1170 //objerror ("FindIntermission: no spot");
1176 ===============================================================================
1180 ===============================================================================
1183 void DumpStats(float final)
1187 local float to_console;
1188 local float to_eventlog;
1189 local float to_file;
1192 to_console = cvar("sv_logscores_console");
1193 to_eventlog = cvar("sv_eventlog");
1194 to_file = cvar("sv_logscores_file");
1198 to_console = TRUE; // always print printstats replies
1199 to_eventlog = FALSE; // but never print them to the event log
1203 if(cvar("sv_eventlog_console"))
1204 to_console = FALSE; // otherwise we get the output twice
1210 s = strcat(s, GetGametype(), "_", GetMapname(), ":", ftos(rint(time)));
1218 file = fopen(cvar_string("sv_logscores_filename"), FILE_APPEND);
1222 fputs(file, strcat(s, "\n"));
1225 s = strcat(":labels:player:", GetPlayerScoreString(world, 0));
1231 fputs(file, strcat(s, "\n"));
1233 FOR_EACH_CLIENT(other)
1235 if ((clienttype(other) == CLIENTTYPE_REAL) || (clienttype(other) == CLIENTTYPE_BOT && cvar("sv_logscores_bots")))
1237 s = strcat(":player:see-labels:", GetPlayerScoreString(other, 0), ":");
1238 s = strcat(s, ftos(rint(time - other.jointime)), ":");
1239 if(other.classname == "player" || g_arena || g_ca || g_lms)
1240 s = strcat(s, ftos(other.team), ":");
1242 s = strcat(s, "spectator:");
1245 print(s, other.netname, "\n");
1247 GameLogEcho(strcat(s, ftos(other.playerid), ":", other.netname));
1249 fputs(file, strcat(s, other.netname, "\n"));
1255 s = strcat(":labels:teamscores:", GetTeamScoreString(0, 0));
1261 fputs(file, strcat(s, "\n"));
1263 for(i = 1; i < 16; ++i)
1265 s = strcat(":teamscores:see-labels:", GetTeamScoreString(i, 0));
1266 s = strcat(s, ":", ftos(i));
1272 fputs(file, strcat(s, "\n"));
1279 GameLogEcho(":end");
1282 fputs(file, ":end\n");
1287 void FixIntermissionClient(entity e)
1290 if(!e.autoscreenshot) // initial call
1292 e.angles = e.v_angle;
1293 e.angles_x = -e.angles_x;
1294 e.autoscreenshot = time + 0.8; // used for autoscreenshot
1296 // first intermission phase; voting phase has positive health (used to decide whether to send SVC_FINALE or not)
1297 e.solid = SOLID_NOT;
1298 e.movetype = MOVETYPE_NONE;
1299 e.takedamage = DAMAGE_NO;
1302 e.weaponentity.effects = EF_NODRAW;
1303 if (e.weaponentity.weaponentity)
1304 e.weaponentity.weaponentity.effects = EF_NODRAW;
1306 if(clienttype(e) == CLIENTTYPE_REAL)
1308 stuffcmd(e, "\nscr_printspeed 1000000\n");
1309 s = cvar_string("sv_intermission_cdtrack");
1311 stuffcmd(e, strcat("\ncd loop ", s, "\n"));
1313 WriteByte(MSG_ONE, SVC_INTERMISSION);
1317 //e.velocity = '0 0 0';
1318 //e.fixangle = TRUE;
1320 // TODO halt weapon animation
1325 go to the next level for deathmatch
1326 only called if a time or frag limit has expired
1334 intermission_running = 1;
1336 // enforce a wait time before allowing changelevel
1337 if(player_count > 0)
1338 intermission_exittime = time + cvar("sv_mapchange_delay");
1340 intermission_exittime = -1;
1343 WriteByte (MSG_ALL, SVC_CDTRACK);
1344 WriteByte (MSG_ALL, 3);
1345 WriteByte (MSG_ALL, 3);
1346 // done in FixIntermission
1349 //pos = FindIntermission ();
1355 if(cvar("sv_eventlog"))
1356 GameLogEcho(":gameover");
1362 // save the stats to a text file on the client
1363 // stuffcmd(other, log_stats "stats/file_name");
1365 // stuffcmd(other, log_stats "");
1366 // use a filename similar to the demo name
1367 // string file_name;
1368 // file_name = strcat("\nlog_file \"stats/", strftime(TRUE, "%Y-%m-%d_%H-%M"), "_", mapname, ".txt\""); // open the log file
1370 // write a stats parser for the menu
1372 if(cvar("sv_accuracy_data_send")) {
1373 string stats_to_send;
1375 FOR_EACH_CLIENT(other) { // make the string to send
1376 FixIntermissionClient(other);
1378 if(other.cvar_cl_accuracy_data_share) {
1379 stats_to_send = strcat(stats_to_send, ":hits:", other.netname);
1381 for(i = WEP_FIRST; i <= WEP_LAST; ++i)
1382 stats_to_send = strcat(stats_to_send, ":", ftos(other.stats_hit[i-1]));
1384 stats_to_send = strcat(stats_to_send, "\n:fired:", other.netname);
1386 for(i = WEP_FIRST; i <= WEP_LAST; ++i)
1387 stats_to_send = strcat(stats_to_send, ":", ftos(other.stats_fired[i-1]));
1389 stats_to_send = strcat(stats_to_send, "\n");
1393 FOR_EACH_REALCLIENT(other) { // only spam humans
1394 Score_NicePrint(other); // print the score
1396 if(other.cvar_cl_accuracy_data_receive) // send the stats string to all the willing clients
1397 bprint(stats_to_send);
1399 } else { // ye olde message
1400 FOR_EACH_PLAYER(other) {
1401 FixIntermissionClient(other);
1404 bprint(other.netname, " ^7wins.\n");
1408 if(cvar("g_campaign"))
1409 CampaignPreIntermission();
1411 localcmd("\nsv_hook_gameend;");
1418 Exit deathmatch games upon conditions
1421 void CheckRules_Player()
1423 if (gameover) // someone else quit the game already
1426 if(self.deadflag == DEAD_NO)
1427 self.play_time += frametime;
1429 // fixme: don't check players; instead check spawnfunc_dom_team and spawnfunc_ctf_team entities
1430 // (div0: and that in CheckRules_World please)
1433 float checkrules_equality;
1434 float checkrules_suddendeathwarning;
1435 float checkrules_suddendeathend;
1436 float checkrules_overtimesadded; //how many overtimes have been already added
1438 float WINNING_NO = 0; // no winner, but time limits may terminate the game
1439 float WINNING_YES = 1; // winner found
1440 float WINNING_NEVER = 2; // no winner, enter overtime if time limit is reached
1441 float WINNING_STARTSUDDENDEATHOVERTIME = 3; // no winner, enter suddendeath overtime NOW
1443 float InitiateSuddenDeath()
1445 // Check first whether normal overtimes could be added before initiating suddendeath mode
1446 // - for this timelimit_overtime needs to be >0 of course
1447 // - also check the winning condition calculated in the previous frame and only add normal overtime
1448 // again, if at the point at which timelimit would be extended again, still no winner was found
1449 if ((checkrules_overtimesadded >= 0) && (checkrules_overtimesadded < cvar("timelimit_overtimes")) && cvar("timelimit_overtime") && !(g_race && !g_race_qualifying))
1451 return 1; // need to call InitiateOvertime later
1455 if(!checkrules_suddendeathend)
1457 checkrules_suddendeathend = time + 60 * cvar("timelimit_suddendeath");
1458 if(g_race && !g_race_qualifying)
1459 race_StartCompleting();
1465 void InitiateOvertime() // ONLY call this if InitiateSuddenDeath returned true
1467 ++checkrules_overtimesadded;
1468 //add one more overtime by simply extending the timelimit
1470 tl = cvar("timelimit");
1471 tl += cvar("timelimit_overtime");
1472 cvar_set("timelimit", ftos(tl));
1473 string minutesPlural;
1474 if (cvar("timelimit_overtime") == 1)
1475 minutesPlural = " ^3minute";
1477 minutesPlural = " ^3minutes";
1481 "^3Now playing ^1OVERTIME^3!\n\n^3Added ^1",
1482 ftos(cvar("timelimit_overtime")),
1489 float GetWinningCode(float fraglimitreached, float equality)
1492 if(fraglimitreached)
1493 return WINNING_STARTSUDDENDEATHOVERTIME;
1495 return WINNING_NEVER;
1497 if(fraglimitreached)
1503 // set the .winning flag for exactly those players with a given field value
1504 void SetWinners(.float field, float value)
1507 FOR_EACH_PLAYER(head)
1508 head.winning = (head.field == value);
1511 // set the .winning flag for those players with a given field value
1512 void AddWinners(.float field, float value)
1515 FOR_EACH_PLAYER(head)
1516 if(head.field == value)
1520 // clear the .winning flags
1521 void ClearWinners(void)
1524 FOR_EACH_PLAYER(head)
1528 // Onslaught winning condition:
1529 // game terminates if only one team has a working generator (or none)
1530 float WinningCondition_Onslaught()
1533 local float t1, t2, t3, t4;
1535 WinningConditionHelper(); // set worldstatus
1540 // first check if the game has ended
1541 t1 = t2 = t3 = t4 = 0;
1542 head = find(world, classname, "onslaught_generator");
1545 if (head.health > 0)
1547 if (head.team == COLOR_TEAM1) t1 = 1;
1548 if (head.team == COLOR_TEAM2) t2 = 1;
1549 if (head.team == COLOR_TEAM3) t3 = 1;
1550 if (head.team == COLOR_TEAM4) t4 = 1;
1552 head = find(head, classname, "onslaught_generator");
1554 if (t1 + t2 + t3 + t4 < 2)
1556 // game over, only one team remains (or none)
1558 if (t1) SetWinners(team, COLOR_TEAM1);
1559 if (t2) SetWinners(team, COLOR_TEAM2);
1560 if (t3) SetWinners(team, COLOR_TEAM3);
1561 if (t4) SetWinners(team, COLOR_TEAM4);
1562 dprint("Have a winner, ending game.\n");
1566 // Two or more teams remain
1570 float LMS_NewPlayerLives()
1573 fl = cvar("fraglimit");
1577 // first player has left the game for dying too much? Nobody else can get in.
1578 if(lms_lowest_lives < 1)
1581 if(!cvar("g_lms_join_anytime"))
1582 if(lms_lowest_lives < fl - cvar("g_lms_last_join"))
1585 return bound(1, lms_lowest_lives, fl);
1588 // Assault winning condition: If the attackers triggered a round end (by fulfilling all objectives)
1589 // they win. Otherwise the defending team wins once the timelimit passes.
1590 void assault_new_round();
1591 float WinningCondition_Assault()
1595 WinningConditionHelper(); // set worldstatus
1597 status = WINNING_NO;
1598 // as the timelimit has not yet passed just assume the defending team will win
1599 if(assault_attacker_team == COLOR_TEAM1)
1601 SetWinners(team, COLOR_TEAM2);
1605 SetWinners(team, COLOR_TEAM1);
1609 ent = find(world, classname, "target_assault_roundend");
1612 if(ent.winning) // round end has been triggered by attacking team
1614 bprint("ASSAULT: round completed...\n");
1615 SetWinners(team, assault_attacker_team);
1617 TeamScore_AddToTeam(assault_attacker_team, ST_ASSAULT_OBJECTIVES, 666 - TeamScore_AddToTeam(assault_attacker_team, ST_ASSAULT_OBJECTIVES, 0));
1619 if(ent.cnt == 1) // this was the second round
1621 status = WINNING_YES;
1625 local entity oldself;
1628 assault_new_round();
1637 // LMS winning condition: game terminates if and only if there's at most one
1638 // one player who's living lives. Top two scores being equal cancels the time
1640 float WinningCondition_LMS()
1647 have_player = FALSE;
1648 have_players = FALSE;
1649 l = LMS_NewPlayerLives();
1651 head = find(world, classname, "player");
1654 head2 = find(head, classname, "player");
1656 have_players = TRUE;
1660 // we have at least one player
1663 // two or more active players - continue with the game
1667 // exactly one player?
1670 SetWinners(winning, 0); // NOTE: exactly one player is still "player", so this works out
1674 // game still running (that is, nobody got removed from the game by a frag yet)? then continue
1680 // and assign him his first place
1681 PlayerScore_Add(head, SP_LMS_RANK, 1);
1688 // nobody is playing at all...
1691 // wait for players...
1695 // SNAFU (maybe a draw game?)
1697 dprint("No players, ending game.\n");
1702 // When we get here, we have at least two players who are actually LIVING,
1703 // now check if the top two players have equal score.
1704 WinningConditionHelper();
1707 if(WinningConditionHelper_winner)
1708 WinningConditionHelper_winner.winning = TRUE;
1709 if(WinningConditionHelper_topscore == WinningConditionHelper_secondscore)
1710 return WINNING_NEVER;
1712 // Top two have different scores? Way to go for our beloved TIMELIMIT!
1716 void ShuffleMaplist()
1718 cvar_set("g_maplist", shufflewords(cvar_string("g_maplist")));
1722 float WinningCondition_Scores(float limit, float leadlimit)
1724 // TODO make everything use THIS winning condition (except LMS)
1725 WinningConditionHelper();
1729 team1_score = TeamScore_GetCompareValue(COLOR_TEAM1);
1730 team2_score = TeamScore_GetCompareValue(COLOR_TEAM2);
1731 team3_score = TeamScore_GetCompareValue(COLOR_TEAM3);
1732 team4_score = TeamScore_GetCompareValue(COLOR_TEAM4);
1736 if(WinningConditionHelper_winner)
1737 WinningConditionHelper_winner.winning = 1;
1738 if(WinningConditionHelper_winnerteam >= 0)
1739 SetWinners(team, WinningConditionHelper_winnerteam);
1741 if(WinningConditionHelper_lowerisbetter)
1743 WinningConditionHelper_topscore = -WinningConditionHelper_topscore;
1744 WinningConditionHelper_secondscore = -WinningConditionHelper_secondscore;
1748 if(WinningConditionHelper_zeroisworst)
1749 leadlimit = 0; // not supported in this mode
1751 if(g_dm || g_tdm || g_arena || g_ca || (g_race && !g_race_qualifying) || g_nexball)
1752 // these modes always score in increments of 1, thus this makes sense
1754 if(leaderfrags != WinningConditionHelper_topscore)
1756 leaderfrags = WinningConditionHelper_topscore;
1759 if (leaderfrags == limit - 1)
1760 play2all("announcer/robotic/1fragleft.wav");
1761 else if (leaderfrags == limit - 2)
1762 play2all("announcer/robotic/2fragsleft.wav");
1763 else if (leaderfrags == limit - 3)
1764 play2all("announcer/robotic/3fragsleft.wav");
1768 return GetWinningCode(
1769 WinningConditionHelper_topscore &&
1771 (limit && (WinningConditionHelper_topscore >= limit))
1773 (leadlimit && (WinningConditionHelper_topscore - WinningConditionHelper_secondscore >= leadlimit))
1775 WinningConditionHelper_equality
1779 float WinningCondition_Race(float fraglimit)
1790 if(p.race_completed)
1795 wc = WinningCondition_Scores(fraglimit, 0);
1797 // ALWAYS initiate overtime, unless EVERYONE has finished the race!
1798 if(wc == WINNING_YES || wc == WINNING_STARTSUDDENDEATHOVERTIME)
1799 // do NOT support equality when the laps are all raced!
1800 return WINNING_STARTSUDDENDEATHOVERTIME;
1802 return WINNING_NEVER;
1806 void ReadyRestart();
1807 float WinningCondition_QualifyingThenRace(float limit)
1810 wc = WinningCondition_Scores(limit, 0);
1812 // NEVER initiate overtime
1813 if(wc == WINNING_YES || wc == WINNING_STARTSUDDENDEATHOVERTIME)
1821 float WinningCondition_RanOutOfSpawns()
1825 if(have_team_spawns <= 0)
1828 if(!some_spawn_has_been_used)
1831 team1_score = team2_score = team3_score = team4_score = 0;
1833 FOR_EACH_PLAYER(head) if(head.deadflag == DEAD_NO)
1835 if(head.team == COLOR_TEAM1)
1837 else if(head.team == COLOR_TEAM2)
1839 else if(head.team == COLOR_TEAM3)
1841 else if(head.team == COLOR_TEAM4)
1845 for(head = world; (head = find(head, classname, "info_player_deathmatch")) != world; )
1847 if(head.team == COLOR_TEAM1)
1849 else if(head.team == COLOR_TEAM2)
1851 else if(head.team == COLOR_TEAM3)
1853 else if(head.team == COLOR_TEAM4)
1858 if(team1_score + team2_score + team3_score + team4_score == 0)
1860 checkrules_equality = TRUE;
1863 else if(team1_score + team2_score + team3_score + team4_score == 1)
1866 if(team1_score) t = COLOR_TEAM1;
1867 if(team2_score) t = COLOR_TEAM2;
1868 if(team3_score) t = COLOR_TEAM3;
1869 if(team4_score) t = COLOR_TEAM4;
1870 CheckAllowedTeams(world);
1871 for(i = 0; i < MAX_TEAMSCORE; ++i)
1873 if(t != COLOR_TEAM1) if(c1 >= 0) TeamScore_AddToTeam(COLOR_TEAM1, i, -1000);
1874 if(t != COLOR_TEAM2) if(c2 >= 0) TeamScore_AddToTeam(COLOR_TEAM2, i, -1000);
1875 if(t != COLOR_TEAM3) if(c3 >= 0) TeamScore_AddToTeam(COLOR_TEAM3, i, -1000);
1876 if(t != COLOR_TEAM4) if(c4 >= 0) TeamScore_AddToTeam(COLOR_TEAM4, i, -1000);
1879 AddWinners(team, t);
1890 Exit deathmatch games upon conditions
1893 void CheckRules_World()
1905 MapVote_Think should now do that part
1906 if (intermission_running)
1907 if (time >= intermission_exittime + 60)
1909 if(!DoNextMapOverride())
1915 if (gameover) // someone else quit the game already
1917 if(player_count == 0) // Nobody there? Then let's go to the next map
1919 // this will actually check the player count in the next frame
1920 // again, but this shouldn't hurt
1924 timelimit = cvar("timelimit") * 60;
1925 fraglimit = cvar("fraglimit");
1926 leadlimit = cvar("leadlimit");
1928 if(inWarmupStage || time <= game_starttime) // NOTE: this is <= to prevent problems in the very tic where the game starts
1931 timelimit = 0; // timelimit is not made for warmup
1933 fraglimit = 0; // no fraglimit for now
1934 leadlimit = 0; // no leadlimit for now
1938 timelimit = 0; // ONS has its own overtime rule
1942 timelimit += game_starttime;
1944 else if (timelimit < 0)
1954 if(checkrules_suddendeathend)
1956 if(!checkrules_suddendeathwarning)
1958 checkrules_suddendeathwarning = TRUE;
1959 if(g_race && !g_race_qualifying)
1960 bcenterprint("^3Everyone, finish your lap! The race is over!");
1962 bcenterprint("^3Now playing ^1OVERTIME^3!\n\n^3Keep fragging until we have a ^1winner^3!");
1967 if (timelimit && time >= timelimit)
1969 if(g_race && (g_race_qualifying == 2) && timelimit > 0)
1972 float playerswithlaps;
1975 totalplayers = playerswithlaps = readyplayers = 0;
1976 FOR_EACH_PLAYER(head)
1979 if(PlayerScore_Add(head, SP_RACE_FASTEST, 0))
1985 // at least 2 of the players have completed a lap: start the RACE
1986 // otherwise, the players should end the qualifying on their own
1987 if(readyplayers || playerswithlaps >= 2)
1989 checkrules_suddendeathend = 0;
1990 ReadyRestart(); // go to race
1994 wantovertime |= InitiateSuddenDeath();
1997 wantovertime |= InitiateSuddenDeath();
2001 if (checkrules_suddendeathend && time >= checkrules_suddendeathend)
2007 float checkrules_status;
2008 checkrules_status = WinningCondition_RanOutOfSpawns();
2009 if(checkrules_status == WINNING_YES)
2011 bprint("Hey! Someone ran out of spawns!\n");
2013 else if(g_race && !g_race_qualifying && timelimit >= 0)
2015 checkrules_status = WinningCondition_Race(fraglimit);
2016 //print("WC_RACE yields ", ftos(checkrules_status), "\n");
2018 else if(g_race && g_race_qualifying == 2 && timelimit >= 0)
2020 checkrules_status = WinningCondition_QualifyingThenRace(fraglimit);
2021 //print("WC_QUALIFYING_THEN_RACE yields ", ftos(checkrules_status), "\n");
2025 checkrules_status = WinningCondition_Assault(); // TODO remove this?
2029 checkrules_status = WinningCondition_LMS();
2031 else if (g_onslaught)
2033 checkrules_status = WinningCondition_Onslaught(); // TODO remove this?
2037 checkrules_status = WinningCondition_Scores(fraglimit, leadlimit);
2038 //print("WC_SCORES yields ", ftos(checkrules_status), "\n");
2041 if(checkrules_status == WINNING_STARTSUDDENDEATHOVERTIME)
2043 checkrules_status = WINNING_NEVER;
2044 checkrules_overtimesadded = -1;
2045 wantovertime |= InitiateSuddenDeath();
2048 if(checkrules_status == WINNING_NEVER)
2049 // equality cases! Nobody wins if the overtime ends in a draw.
2054 if(checkrules_status == WINNING_NEVER)
2057 checkrules_status = WINNING_YES;
2060 if(checkrules_suddendeathend)
2061 if(checkrules_status != WINNING_NEVER || time >= checkrules_suddendeathend)
2062 checkrules_status = WINNING_YES;
2064 if(checkrules_status == WINNING_YES)
2066 //print("WINNING\n");
2071 float mapvote_nextthink;
2072 float mapvote_initialized;
2073 float mapvote_keeptwotime;
2074 float mapvote_timeout;
2075 string mapvote_message;
2076 #define MAPVOTE_SCREENSHOT_DIRS_COUNT 4
2077 string mapvote_screenshot_dirs[MAPVOTE_SCREENSHOT_DIRS_COUNT];
2078 float mapvote_screenshot_dirs_count;
2080 float mapvote_count;
2081 float mapvote_count_real;
2082 string mapvote_maps[MAPVOTE_COUNT];
2083 float mapvote_maps_screenshot_dir[MAPVOTE_COUNT];
2084 string mapvote_maps_pakfile[MAPVOTE_COUNT];
2085 float mapvote_maps_suggested[MAPVOTE_COUNT];
2086 string mapvote_suggestions[MAPVOTE_COUNT];
2087 float mapvote_suggestion_ptr;
2088 float mapvote_maxlen;
2089 float mapvote_voters;
2090 float mapvote_votes[MAPVOTE_COUNT];
2092 float mapvote_detail;
2093 float mapvote_abstain;
2096 void MapVote_ClearAllVotes()
2098 FOR_EACH_CLIENT(other)
2102 string MapVote_Suggest(string m)
2106 return "That's not how to use this command.";
2107 if(!cvar("g_maplist_votable_suggestions"))
2108 return "Suggestions are not accepted on this server.";
2109 if(mapvote_initialized)
2110 return "Can't suggest - voting is already in progress!";
2111 m = MapInfo_FixName(m);
2113 return "The map you suggested is not available on this server.";
2114 if(!cvar("g_maplist_votable_suggestions_override_mostrecent"))
2116 return "This server does not allow for recent maps to be played again. Please be patient for some rounds.";
2118 if(!MapInfo_CheckMap(m))
2119 return "The map you suggested does not support the current game mode.";
2120 for(i = 0; i < mapvote_suggestion_ptr; ++i)
2121 if(mapvote_suggestions[i] == m)
2122 return "This map was already suggested.";
2123 if(mapvote_suggestion_ptr >= MAPVOTE_COUNT)
2125 i = floor(random() * mapvote_suggestion_ptr);
2129 i = mapvote_suggestion_ptr;
2130 mapvote_suggestion_ptr += 1;
2132 if(mapvote_suggestions[i] != "")
2133 strunzone(mapvote_suggestions[i]);
2134 mapvote_suggestions[i] = strzone(m);
2135 if(cvar("sv_eventlog"))
2136 GameLogEcho(strcat(":vote:suggested:", m, ":", ftos(self.playerid)));
2137 return strcat("Suggestion of ", m, " accepted.");
2140 void MapVote_AddVotable(string nextMap, float isSuggestion)
2143 string pakfile, mapfile;
2147 for(j = 0; j < mapvote_count; ++j)
2148 if(mapvote_maps[j] == nextMap)
2150 if(strlen(nextMap) > mapvote_maxlen)
2151 mapvote_maxlen = strlen(nextMap);
2152 mapvote_maps[mapvote_count] = strzone(nextMap);
2153 mapvote_maps_suggested[mapvote_count] = isSuggestion;
2155 for(i = 0; i < mapvote_screenshot_dirs_count; ++i)
2157 mapfile = strcat(mapvote_screenshot_dirs[i], "/", mapvote_maps[i]);
2158 pakfile = whichpack(strcat(mapfile, ".tga"));
2160 pakfile = whichpack(strcat(mapfile, ".jpg"));
2162 pakfile = whichpack(strcat(mapfile, ".png"));
2166 if(i >= mapvote_screenshot_dirs_count)
2167 i = 0; // FIXME maybe network this error case, as that means there is no mapshot on the server?
2168 for(o = strstr(pakfile, "/", 0)+1; o > 0; o = strstr(pakfile, "/", 0)+1)
2169 pakfile = substring(pakfile, o, -1);
2171 mapvote_maps_screenshot_dir[mapvote_count] = i;
2172 mapvote_maps_pakfile[mapvote_count] = strzone(pakfile);
2177 void MapVote_Spawn();
2183 MapVote_ClearAllVotes();
2186 mapvote_detail = !cvar("g_maplist_votable_nodetail");
2187 mapvote_abstain = cvar("g_maplist_votable_abstain");
2190 nmax = min(MAPVOTE_COUNT - 1, cvar("g_maplist_votable"));
2192 nmax = min(MAPVOTE_COUNT, cvar("g_maplist_votable"));
2193 smax = min3(nmax, cvar("g_maplist_votable_suggestions"), mapvote_suggestion_ptr);
2195 // we need this for AddVotable, as that cycles through the screenshot dirs
2196 mapvote_screenshot_dirs_count = tokenize_console(cvar_string("g_maplist_votable_screenshot_dir"));
2197 if(mapvote_screenshot_dirs_count == 0)
2198 mapvote_screenshot_dirs_count = tokenize_console("maps levelshots");
2199 mapvote_screenshot_dirs_count = min(mapvote_screenshot_dirs_count, MAPVOTE_SCREENSHOT_DIRS_COUNT);
2200 for(i = 0; i < mapvote_screenshot_dirs_count; ++i)
2201 mapvote_screenshot_dirs[i] = strzone(argv(i));
2203 if(mapvote_suggestion_ptr)
2204 for(i = 0; i < 100 && mapvote_count < smax; ++i)
2205 MapVote_AddVotable(mapvote_suggestions[floor(random() * mapvote_suggestion_ptr)], TRUE);
2207 for(i = 0; i < 100 && mapvote_count < nmax; ++i)
2208 MapVote_AddVotable(GetNextMap(), FALSE);
2210 if(mapvote_count == 0)
2212 bprint( "Maplist contains no single playable map! Resetting it to default map list.\n" );
2213 cvar_set("g_maplist", MapInfo_ListAllowedMaps(MapInfo_RequiredFlags(), MapInfo_ForbiddenFlags()));
2214 if(cvar("g_maplist_shuffle"))
2216 localcmd("\nmenu_cmd sync\n");
2217 for(i = 0; i < 100 && mapvote_count < nmax; ++i)
2218 MapVote_AddVotable(GetNextMap(), FALSE);
2221 mapvote_count_real = mapvote_count;
2223 MapVote_AddVotable("don't care", 0);
2225 //dprint("mapvote count is ", ftos(mapvote_count), "\n");
2227 mapvote_keeptwotime = time + cvar("g_maplist_votable_keeptwotime");
2228 mapvote_timeout = time + cvar("g_maplist_votable_timeout");
2229 if(mapvote_count_real < 3 || mapvote_keeptwotime <= time)
2230 mapvote_keeptwotime = 0;
2231 mapvote_message = "Choose a map and press its key!";
2236 void MapVote_SendPicture(float id)
2239 WriteByte(MSG_ONE, SVC_TEMPENTITY);
2240 WriteByte(MSG_ONE, TE_CSQC_PICTURE);
2241 WriteByte(MSG_ONE, id);
2242 WritePicture(MSG_ONE, strcat(mapvote_screenshot_dirs[mapvote_maps_screenshot_dir[id]], "/", mapvote_maps[id]), 3072);
2245 float GameCommand_MapVote(string cmd)
2247 if(!intermission_running)
2250 if(cmd == "mv_getpic")
2252 MapVote_SendPicture(stof(argv(1)));
2259 float MapVote_GetMapMask()
2261 float mask, i, power;
2263 for(i = 0, power = 1; i < mapvote_count; ++i, power *= 2)
2264 if(mapvote_maps[i] != "")
2270 float MapVote_SendEntity(entity to, float sf)
2275 sf &~= 2; // if we send 1, we don't need to also send 2
2277 WriteByte(MSG_ENTITY, ENT_CLIENT_MAPVOTE);
2278 WriteByte(MSG_ENTITY, sf);
2282 // flag 1 == initialization
2283 for(i = 0; i < mapvote_screenshot_dirs_count; ++i)
2284 WriteString(MSG_ENTITY, mapvote_screenshot_dirs[i]);
2285 WriteString(MSG_ENTITY, "");
2286 WriteByte(MSG_ENTITY, mapvote_count);
2287 WriteByte(MSG_ENTITY, mapvote_abstain);
2288 WriteByte(MSG_ENTITY, mapvote_detail);
2289 WriteCoord(MSG_ENTITY, mapvote_timeout);
2290 if(mapvote_count <= 8)
2291 WriteByte(MSG_ENTITY, MapVote_GetMapMask());
2293 WriteShort(MSG_ENTITY, MapVote_GetMapMask());
2294 for(i = 0; i < mapvote_count; ++i)
2295 if(mapvote_maps[i] != "")
2297 if(mapvote_abstain && i == mapvote_count - 1)
2299 WriteString(MSG_ENTITY, ""); // abstain needs no text
2300 WriteByte(MSG_ENTITY, 0); // abstain needs no screenshot dir
2301 WriteString(MSG_ENTITY, ""); // abstain needs no pack
2305 WriteString(MSG_ENTITY, mapvote_maps[i]);
2306 WriteByte(MSG_ENTITY, mapvote_maps_screenshot_dir[i]);
2307 WriteString(MSG_ENTITY, mapvote_maps_pakfile[i]);
2314 // flag 2 == update of mask
2315 if(mapvote_count <= 8)
2316 WriteByte(MSG_ENTITY, MapVote_GetMapMask());
2318 WriteShort(MSG_ENTITY, MapVote_GetMapMask());
2324 for(i = 0; i < mapvote_count; ++i)
2325 if(mapvote_maps[i] != "")
2326 WriteByte(MSG_ENTITY, mapvote_votes[i]);
2328 WriteByte(MSG_ENTITY, to.mapvote);
2334 void MapVote_Spawn()
2336 Net_LinkEntity(mapvote_ent = spawn(), FALSE, 0, MapVote_SendEntity);
2339 void MapVote_TouchMask()
2341 mapvote_ent.SendFlags |= 2;
2344 void MapVote_TouchVotes(entity voter)
2346 mapvote_ent.SendFlags |= 4;
2349 float MapVote_Finished(float mappos)
2355 if(cvar("sv_eventlog"))
2357 result = strcat(":vote:finished:", mapvote_maps[mappos]);
2358 result = strcat(result, ":", ftos(mapvote_votes[mappos]), "::");
2359 didntvote = mapvote_voters;
2360 for(i = 0; i < mapvote_count; ++i)
2361 if(mapvote_maps[i] != "")
2363 didntvote -= mapvote_votes[i];
2366 result = strcat(result, ":", mapvote_maps[i]);
2367 result = strcat(result, ":", ftos(mapvote_votes[i]));
2370 result = strcat(result, ":didn't vote:", ftos(didntvote));
2372 GameLogEcho(result);
2373 if(mapvote_maps_suggested[mappos])
2374 GameLogEcho(strcat(":vote:suggestion_accepted:", mapvote_maps[mappos]));
2377 FOR_EACH_REALCLIENT(other)
2378 FixClientCvars(other);
2380 Map_Goto_SetStr(mapvote_maps[mappos]);
2382 alreadychangedlevel = TRUE;
2385 void MapVote_CheckRules_1()
2389 for(i = 0; i < mapvote_count; ++i) if(mapvote_maps[i] != "")
2391 //dprint("Map ", ftos(i), ": "); dprint(mapvote_maps[i], "\n");
2392 mapvote_votes[i] = 0;
2396 FOR_EACH_REALCLIENT(other)
2401 i = other.mapvote - 1;
2402 //dprint("Player ", other.netname, " vote = ", ftos(other.mapvote - 1), "\n");
2403 mapvote_votes[i] = mapvote_votes[i] + 1;
2408 float MapVote_CheckRules_2()
2411 float firstPlace, secondPlace;
2412 float firstPlaceVotes, secondPlaceVotes;
2413 float mapvote_voters_real;
2416 if(mapvote_count_real == 1)
2417 return MapVote_Finished(0);
2419 mapvote_voters_real = mapvote_voters;
2421 mapvote_voters_real -= mapvote_votes[mapvote_count - 1];
2423 RandomSelection_Init();
2424 for(i = 0; i < mapvote_count_real; ++i) if(mapvote_maps[i] != "")
2425 RandomSelection_Add(world, i, string_null, 1, mapvote_votes[i]);
2426 firstPlace = RandomSelection_chosen_float;
2427 firstPlaceVotes = RandomSelection_best_priority;
2428 //dprint("First place: ", ftos(firstPlace), "\n");
2429 //dprint("First place votes: ", ftos(firstPlaceVotes), "\n");
2431 RandomSelection_Init();
2432 for(i = 0; i < mapvote_count_real; ++i) if(mapvote_maps[i] != "")
2434 RandomSelection_Add(world, i, string_null, 1, mapvote_votes[i]);
2435 secondPlace = RandomSelection_chosen_float;
2436 secondPlaceVotes = RandomSelection_best_priority;
2437 //dprint("Second place: ", ftos(secondPlace), "\n");
2438 //dprint("Second place votes: ", ftos(secondPlaceVotes), "\n");
2440 if(firstPlace == -1)
2441 error("No first place in map vote... WTF?");
2443 if(secondPlace == -1 || time > mapvote_timeout || (mapvote_voters_real - firstPlaceVotes) < firstPlaceVotes)
2444 return MapVote_Finished(firstPlace);
2446 if(mapvote_keeptwotime)
2447 if(time > mapvote_keeptwotime || (mapvote_voters_real - firstPlaceVotes - secondPlaceVotes) < secondPlaceVotes)
2450 MapVote_TouchMask();
2451 mapvote_message = "Now decide between the TOP TWO!";
2452 mapvote_keeptwotime = 0;
2453 result = strcat(":vote:keeptwo:", mapvote_maps[firstPlace]);
2454 result = strcat(result, ":", ftos(firstPlaceVotes));
2455 result = strcat(result, ":", mapvote_maps[secondPlace]);
2456 result = strcat(result, ":", ftos(secondPlaceVotes), "::");
2457 didntvote = mapvote_voters;
2458 for(i = 0; i < mapvote_count; ++i)
2459 if(mapvote_maps[i] != "")
2461 didntvote -= mapvote_votes[i];
2463 if(i != secondPlace)
2465 result = strcat(result, ":", mapvote_maps[i]);
2466 result = strcat(result, ":", ftos(mapvote_votes[i]));
2467 if(i < mapvote_count_real)
2469 strunzone(mapvote_maps[i]);
2470 mapvote_maps[i] = "";
2471 strunzone(mapvote_maps_pakfile[i]);
2472 mapvote_maps_pakfile[i] = "";
2476 result = strcat(result, ":didn't vote:", ftos(didntvote));
2477 if(cvar("sv_eventlog"))
2478 GameLogEcho(result);
2488 keeptwo = mapvote_keeptwotime;
2489 MapVote_CheckRules_1(); // count
2490 if(MapVote_CheckRules_2()) // decide
2494 FOR_EACH_REALCLIENT(other)
2496 // hide scoreboard again
2497 if(other.health != 2342)
2499 other.health = 2342;
2501 if(clienttype(other) == CLIENTTYPE_REAL)
2504 WriteByte(MSG_ONE, SVC_FINALE);
2505 WriteString(MSG_ONE, "");
2509 // clear possibly invalid votes
2510 if(mapvote_maps[other.mapvote - 1] == "")
2512 // use impulses as new vote
2513 if(other.impulse >= 1 && other.impulse <= mapvote_count)
2514 if(mapvote_maps[other.impulse - 1] != "")
2516 other.mapvote = other.impulse;
2517 MapVote_TouchVotes(other);
2525 MapVote_CheckRules_1(); // just count
2527 void MapVote_Start()
2532 MapInfo_Enumerate();
2533 if(MapInfo_FilterGametype(MapInfo_CurrentGametype(), MapInfo_CurrentFeatures(), MapInfo_RequiredFlags(), MapInfo_ForbiddenFlags(), 1))
2536 void MapVote_Think()
2541 if(alreadychangedlevel)
2544 if(time < mapvote_nextthink)
2548 mapvote_nextthink = time + 0.5;
2550 if(!mapvote_initialized)
2552 if(cvar("rescan_pending") == 1)
2554 cvar_set("rescan_pending", "2");
2555 localcmd("fs_rescan\nrescan_pending 3\n");
2558 else if(cvar("rescan_pending") == 2)
2562 else if(cvar("rescan_pending") == 3)
2564 // now build missing mapinfo files
2565 if(!MapInfo_FilterGametype(MapInfo_CurrentGametype(), MapInfo_CurrentFeatures(), MapInfo_RequiredFlags(), MapInfo_ForbiddenFlags(), 1))
2568 // we're done, start the timer
2569 cvar_set("rescan_pending", "0");
2572 mapvote_initialized = TRUE;
2573 if(DoNextMapOverride())
2575 if(!cvar("g_maplist_votable") || player_count <= 0)
2586 string GotoMap(string m)
2588 if(!MapInfo_CheckMap(m))
2589 return "The map you chose is not available on this server.";
2590 cvar_set("nextmap", m);
2591 cvar_set("timelimit", "-1");
2592 if(mapvote_initialized || alreadychangedlevel)
2594 if(DoNextMapOverride())
2595 return "Map switch initiated.";
2597 return "Hm... no. For some reason I like THIS map more.";
2600 return "Map switch will happen after scoreboard.";
2607 FOR_EACH_REALCLIENT(self)
2609 if(self.classname == "spectator")
2611 if(self.enemy.typehitsound)
2612 play2(self, "misc/typehit.wav");
2613 else if(self.enemy.hitsound && self.cvar_cl_hitsound)
2614 play2(self, "misc/hit.wav");
2618 if(self.typehitsound)
2619 play2(self, "misc/typehit.wav");
2620 else if(self.hitsound && self.cvar_cl_hitsound)
2621 play2(self, "misc/hit.wav");
2624 altime = time + frametime * (1 + cvar("g_antilag_nudge"));
2625 // add 1 frametime because after this, engine SV_Physics
2626 // increases time by a frametime and then networks the frame
2627 // add another frametime because client shows everything with
2628 // 1 frame of lag (cl_nolerp 0). The last +1 however should not be
2630 FOR_EACH_CLIENT(self)
2632 self.hitsound = FALSE;
2633 self.typehitsound = FALSE;
2634 antilag_record(self, altime);
2641 * returns TRUE if redirecting
2643 float redirection_timeout;
2644 float redirection_nextthink;
2645 float RedirectionThink()
2647 float clients_found;
2649 if(redirection_target == "")
2652 if(!redirection_timeout)
2654 cvar_set("sv_public", "-2");
2655 redirection_timeout = time + 0.6; // this will only try twice... should be able to keep more clients
2656 if(redirection_target == "self")
2657 bprint("^3SERVER NOTICE:^7 restarting the server\n");
2659 bprint("^3SERVER NOTICE:^7 redirecting everyone to ", redirection_target, "\n");
2662 if(time < redirection_nextthink)
2665 redirection_nextthink = time + 1;
2668 FOR_EACH_REALCLIENT(self)
2670 print("Redirecting: sending connect command to ", self.netname, "\n");
2671 if(redirection_target == "self")
2672 stuffcmd(self, "\ndisconnect; reconnect\n");
2674 stuffcmd(self, strcat("\ndisconnect; connect ", redirection_target, "\n"));
2678 print("Redirecting: ", ftos(clients_found), " clients left.\n");
2680 if(time > redirection_timeout || clients_found == 0)
2681 localcmd("\nwait; wait; wait; quit\n");
2688 // Loaded from a save game
2689 // some things then break, so let's work around them...
2691 // Progs DB (capture records)
2693 ServerProgsDB = db_create();
2695 ServerProgsDB = db_load("server.db");
2699 MapInfo_Enumerate();
2700 MapInfo_FilterGametype(MapInfo_CurrentGametype(), MapInfo_CurrentFeatures(), MapInfo_RequiredFlags(), MapInfo_ForbiddenFlags(), 1);
2706 if(gameover > 1) // shutting down already?
2709 gameover = 2; // 2 = server shutting down
2711 if(world_initialized > 0)
2713 world_initialized = 0;
2714 print("Saving persistent data...\n");
2717 db_save(ServerProgsDB, "server.db");
2718 if(cvar("developer"))
2719 db_save(TemporaryDB, "server-temp.db");
2720 db_close(ServerProgsDB);
2721 db_close(TemporaryDB);
2723 // tell the bot system the game is ending now
2726 WeaponStats_Shutdown();
2729 else if(world_initialized == 0)
2731 print("NOTE: crashed before even initializing the world, not saving persistent data\n");