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 Announce("prepareforbattle");
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");
239 BADPREFIX("sv_world");
244 BADPREFIX("g_campaign");
248 BADPREFIX("net_slist_");
252 BADPREFIX("userbind");
255 BADPREFIX("crosshair");
256 BADCVAR("mod_q3bsp_lightmapmergepower");
257 BADCVAR("mod_q3bsp_nolightmaps");
260 BADCVAR("serverconfig");
262 BADPREFIX("g_chat_flood_");
263 BADPREFIX("g_voice_flood_");
265 BADPREFIX("settemp_");
266 BADPREFIX("sv_allowdownloads_");
267 BADPREFIX("sv_autodemo");
268 BADPREFIX("sv_curl_");
269 BADPREFIX("sv_eventlog");
270 BADPREFIX("sv_logscores_");
271 BADPREFIX("sv_master");
272 BADCVAR("g_banned_list");
273 BADCVAR("log_dest_udp");
275 BADCVAR("net_address");
277 BADCVAR("savedgamecfg");
278 BADCVAR("sv_heartbeatperiod");
279 BADCVAR("sv_vote_master_password");
280 BADCVAR("sys_colortranslation");
281 BADCVAR("sys_specialcharactertranslation");
282 BADCVAR("timestamps");
285 BADCVAR("timelimit");
286 BADCVAR("fraglimit");
289 BADCVAR("g_assault");
292 BADCVAR("g_domination");
293 BADCVAR("g_keyhunt");
294 BADCVAR("g_keyhunt_teams");
295 BADCVAR("g_onslaught");
298 BADCVAR("g_runematch");
300 BADCVAR("g_nexball");
305 BADCVAR("g_maplist");
306 BADCVAR("g_maplist_mostrecent");
312 d = cvar_defstring(k);
315 cvar_changes = strcat(cvar_changes, k, " \"", v, "\" // \"", d, "\"\n");
316 if(strlen(cvar_changes) > 16384)
318 cvar_changes = "// too many settings have been changed to show them here\n";
324 if(cvar_changes == "")
325 cvar_changes = "// this server runs at default settings\n";
327 cvar_changes = strcat("// this server runs at modified settings:\n", cvar_changes);
328 cvar_changes = strzone(cvar_changes);
331 void detect_maptype()
340 o_x += random() * (world.maxs_x - world.mins_x);
341 o_y += random() * (world.maxs_y - world.mins_y);
342 o_z += random() * (world.maxs_z - world.mins_z);
344 tracebox(o, PL_MIN, PL_MAX, o - '0 0 32768', MOVE_WORLDONLY, world);
345 if(trace_fraction == 1)
350 for(i = 0; i < 64; i += 4)
352 tracebox(o, '-1 -1 -1' * i, '1 1 1' * i, o - '0 0 32768', MOVE_WORLDONLY, world);
353 if(trace_fraction == 1)
355 print(ftos(i), " -> ", vtos(trace_endpos), "\n");
364 float RandomSeed_Send(entity to, float sf)
366 WriteByte(MSG_ENTITY, ENT_CLIENT_RANDOMSEED);
367 WriteShort(MSG_ENTITY, self.cnt);
370 void RandomSeed_Think()
372 self.cnt = bound(0, floor(random() * 65536), 65535);
373 self.nextthink = time + 5;
377 void RandomSeed_Spawn()
379 randomseed = spawn();
380 randomseed.think = RandomSeed_Think;
381 Net_LinkEntity(randomseed, FALSE, 0, RandomSeed_Send);
386 self.think(); // sets random seed and nextthink
390 void spawnfunc___init_dedicated_server(void)
392 // handler for _init/_init map (only for dedicated server initialization)
394 world_initialized = -1; // don't complain
396 cvar_string = cvar_string_normal;
397 cvar_set = cvar_set_normal;
399 remove = remove_unsafely;
403 e.think = GotoFirstMap;
404 e.nextthink = time; // this is usually 1 at this point
407 e.classname = "info_player_deathmatch"; // safeguard against player joining
409 self.classname = "worldspawn"; // safeguard against various stuff ;)
412 MapInfo_FilterGametype(MapInfo_CurrentGametype(), MapInfo_CurrentFeatures(), MapInfo_RequiredFlags(), MapInfo_ForbiddenFlags(), 0);
415 void Map_MarkAsRecent(string m);
416 float world_already_spawned;
417 void RegisterWeapons();
419 void ClientInit_Spawn();
420 void WeaponStats_Init();
421 void WeaponStats_Shutdown();
422 void spawnfunc_worldspawn (void)
424 float fd, l, i, j, n;
428 cvar_string = cvar_string_normal;
429 cvar_set = cvar_set_normal;
431 if(world_already_spawned)
432 error("world already spawned - you may have EXACTLY ONE worldspawn!");
433 world_already_spawned = TRUE;
435 remove = remove_safely; // during spawning, watch what you remove!
437 check_unacceptable_compiler_bugs();
439 compressShortVector_init();
442 head = nextent(world);
447 head = nextent(head);
450 // needs to be done so early as they would still spawn
453 ServerProgsDB = db_load("server.db");
455 TemporaryDB = db_create();
458 TODO sound pack system
459 // initialize sound pack system
460 soundpack = cvar_string("g_soundpack");
462 soundpack = strcat(soundpack, "/");
463 soundpack = strzone(soundpack);
469 // 1 FLICKER (first variety)
470 lightstyle(1, "mmnmmommommnonmmonqnmmo");
472 // 2 SLOW STRONG PULSE
473 lightstyle(2, "abcdefghijklmnopqrstuvwxyzyxwvutsrqponmlkjihgfedcba");
475 // 3 CANDLE (first variety)
476 lightstyle(3, "mmmmmaaaaammmmmaaaaaabcdefgabcdefg");
479 lightstyle(4, "mamamamamama");
482 lightstyle(5,"jklmnopqrstuvwxyzyxwvutsrqponmlkj");
484 // 6 FLICKER (second variety)
485 lightstyle(6, "nmonqnmomnmomomno");
487 // 7 CANDLE (second variety)
488 lightstyle(7, "mmmaaaabcdefgmmmmaaaammmaamm");
490 // 8 CANDLE (third variety)
491 lightstyle(8, "mmmaaammmaaammmabcdefaaaammmmabcdefmmmaaaa");
493 // 9 SLOW STROBE (fourth variety)
494 lightstyle(9, "aaaaaaaazzzzzzzz");
496 // 10 FLUORESCENT FLICKER
497 lightstyle(10, "mmamammmmammamamaaamammma");
499 // 11 SLOW PULSE NOT FADE TO BLACK
500 lightstyle(11, "abcdefghijklmnopqrrqponmlkjihgfedcba");
502 // styles 32-62 are assigned by the spawnfunc_light program for switchable lights
507 if(cvar("g_campaign"))
510 Map_MarkAsRecent(mapname);
512 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";
547 MUTATOR_CALLHOOK(BuildMutatorsString);
550 if(cvar("g_grappling_hook"))
551 s = strcat(s, ":grappling_hook");
552 if(!cvar("g_use_ammunition"))
553 s = strcat(s, ":no_use_ammunition");
554 if(!cvar("g_pickup_items"))
555 s = strcat(s, ":no_pickup_items");
556 if(cvar_string("g_weaponarena") != "0")
557 s = strcat(s, ":", cvar_string("g_weaponarena"), " arena");
558 if(cvar("g_vampire"))
559 s = strcat(s, ":vampire");
560 if(cvar("g_laserguided_missile"))
561 s = strcat(s, ":laserguided_missile");
562 if(cvar("g_norecoil"))
563 s = strcat(s, ":norecoil");
565 s = strcat(s, ":midair");
566 if(cvar("g_minstagib"))
567 s = strcat(s, ":minstagib");
569 GameLogEcho(":gameinfo:end");
572 matchid = strzone(ftos(random()));
574 cvar_set("nextmap", "");
578 if(cvar("g_campaign"))
586 MapInfo_FilterGametype(MapInfo_CurrentGametype(), MapInfo_CurrentFeatures(), MapInfo_RequiredFlags(), MapInfo_ForbiddenFlags(), 1);
588 if(whichpack(strcat("maps/", mapname, ".cfg")) != "")
590 fd = fopen(strcat("maps/", mapname, ".cfg"), FILE_READ);
593 while((s = fgets(fd)))
595 l = tokenize_console(s);
600 print("Found ^1DEPRECATED^7 cd loop command in .cfg file; put this line in mapinfo instead:\n");
601 print(" cdtrack ", argv(2), "\n");
603 else if(argv(0) == "fog")
605 print("Found ^1DEPRECATED^7 fog command in .cfg file; put this line in worldspawn in the .map/.bsp/.ent file instead:\n");
606 print(" \"fog\" \"", s, "\"\n");
608 else if(argv(0) == "set")
610 print("Found ^1DEPRECATED^7 set command in .cfg file; put this line in mapinfo instead:\n");
611 print(" clientsettemp_for_type all ", argv(1), " ", argv(2), "\n");
613 else if(argv(0) != "//")
615 print("Found ^1DEPRECATED^7 set command in .cfg file; put this line in mapinfo instead:\n");
616 print(" clientsettemp_for_type all ", argv(0), " ", argv(1), "\n");
625 addstat(STAT_WEAPONS, AS_INT, weapons);
626 addstat(STAT_SWITCHWEAPON, AS_INT, switchweapon);
627 addstat(STAT_GAMESTARTTIME, AS_FLOAT, stat_game_starttime);
628 addstat(STAT_ALLOW_OLDNEXBEAM, AS_INT, stat_allow_oldnexbeam);
631 addstat(STAT_STRENGTH_FINISHED, AS_FLOAT, strength_finished);
632 addstat(STAT_INVINCIBLE_FINISHED, AS_FLOAT, invincible_finished);
633 addstat(STAT_PRESSED_KEYS, AS_FLOAT, pressedkeys);
634 addstat(STAT_FUEL, AS_INT, ammo_fuel);
635 addstat(STAT_DAMAGE_HITS, AS_INT, stat_hit);
636 addstat(STAT_DAMAGE_FIRED, AS_INT, stat_fired);
637 addstat(STAT_SHOTORG, AS_INT, stat_shotorg);
638 addstat(STAT_LEADLIMIT, AS_FLOAT, stat_leadlimit);
639 addstat(STAT_BULLETS_LOADED, AS_INT, campingrifle_bulletcounter);
641 addstat(STAT_NEX_CHARGE, AS_FLOAT, nex_charge);
643 // g_movementspeed hack
644 addstat(STAT_MOVEVARS_AIRSPEEDLIMIT_NONQW, AS_FLOAT, stat_sv_airspeedlimit_nonqw);
645 addstat(STAT_MOVEVARS_AIRACCEL_QW, AS_FLOAT, stat_sv_airaccel_qw);
646 addstat(STAT_MOVEVARS_AIRSTRAFEACCEL_QW, AS_FLOAT, stat_sv_airstrafeaccel_qw);
648 next_pingtime = time + 5;
649 InitializeEntity(self, cvar_changes_init, INITPRIO_CVARS);
653 lsmaps_reply = "^7Maps available: ";
654 lsnewmaps_reply = "^7Maps without a record set: ";
655 for(i = 0, j = 0; i < MapInfo_count; ++i)
657 if(MapInfo_Get_ByID(i))
658 if not(MapInfo_Map_flags & (MAPINFO_FLAG_HIDDEN | MAPINFO_FLAG_FORBIDDEN))
665 lsmaps_reply = strcat(lsmaps_reply, col, MapInfo_Map_bspname, " ");
666 if(g_race && !stof(db_get(ServerProgsDB, strcat(MapInfo_Map_bspname, RACE_RECORD, "time"))))
667 lsnewmaps_reply = strcat(lsnewmaps_reply, col, MapInfo_Map_bspname, " ");
668 else if(g_cts && !stof(db_get(ServerProgsDB, strcat(MapInfo_Map_bspname, CTS_RECORD, "time"))))
669 lsnewmaps_reply = strcat(lsnewmaps_reply, col, MapInfo_Map_bspname, " ");
672 lsmaps_reply = strzone(strcat(lsmaps_reply, "\n"));
673 if (!g_race && !g_cts)
674 lsnewmaps_reply = "Need to be playing race or CTS for lsnewmaps to work.";
675 lsnewmaps_reply = strzone(strcat(lsnewmaps_reply, "\n"));
677 maplist_reply = "^7Maps in list: ";
678 n = tokenize_console(cvar_string("g_maplist"));
679 for(i = 0, j = 0; i < n; ++i)
681 if(MapInfo_CheckMap(argv(i)))
687 maplist_reply = strcat(maplist_reply, col, argv(i), " ");
691 maplist_reply = strzone(strcat(maplist_reply, "\n"));
692 MapInfo_ClearTemps();
694 for(i = 0; i < 10; ++i)
696 records_reply[i] = strzone(getrecords(i));
699 rankings_reply = strzone(getrankings());
703 PingPLReport_Spawn();
707 localcmd("\n_sv_hook_gamestart ", GetGametype(), "\n");
709 // fill sv_curl_serverpackages from .serverpackage files
710 if(cvar("sv_curl_serverpackages_auto"))
712 fd = search_begin("*.serverpackage", TRUE, FALSE);
716 j = search_getsize(fd);
717 for(i = 0; i < j; ++i)
718 s = strcat(s, " ", search_getfilename(fd, i));
721 cvar_set("sv_curl_serverpackages", substring(s, 1, -1));
724 world_initialized = 1;
727 void spawnfunc_light (void)
729 //makestatic (self); // Who the f___ did that?
733 float TryFile( string pFilename )
736 dprint("TryFile(\"", pFilename, "\")\n");
737 lHandle = fopen( pFilename, FILE_READ );
738 if( lHandle != -1 ) {
748 return GametypeNameFromType(game);
751 string getmapname_stored;
757 float Map_Count, Map_Current;
758 string Map_Current_Name;
760 // NOTE: this now expects the map list to be already tokenize()d and the count in Map_Count
761 float GetMaplistPosition()
767 idx = cvar("g_maplist_index");
774 for(pos = 0; pos < Map_Count; ++pos)
778 // resume normal maplist rotation if current map is not in g_maplist
782 float MapHasRightSize(string map)
785 if(currentbots || cvar("bot_number") || player_count < cvar("minplayers"))
786 if(cvar("g_maplist_check_waypoints"))
788 dprint("checkwp "); dprint(map);
789 fh = fopen(strcat("maps/", map, ".waypoints"), FILE_READ);
792 dprint(": no waypoints\n");
795 dprint(": has waypoints\n");
799 // open map size restriction file
800 dprint("opensize "); dprint(map);
801 fh = fopen(strcat("maps/", map, ".sizes"), FILE_READ);
804 float mapmin, mapmax;
806 mapmin = stof(fgets(fh));
807 mapmax = stof(fgets(fh));
809 if(player_count < mapmin)
811 dprint("not enough\n");
814 if(player_count > mapmax)
816 dprint("too many\n");
819 dprint("right size\n");
822 dprint(": not found\n");
826 string Map_Filename(float position)
828 return strcat("maps/", argv(position), ".bsp");
831 string strwords(string s, float w)
834 for(endpos = 0; w && endpos >= 0; --w)
835 endpos = strstrofs(s, " ", endpos + 1);
839 return substring(s, 0, endpos);
842 float strhasword(string s, string w)
844 return strstrofs(strcat(" ", s, " "), strcat(" ", w, " "), 0) >= 0;
847 void Map_MarkAsRecent(string m)
849 cvar_set("g_maplist_mostrecent", strwords(strcat(m, " ", cvar_string("g_maplist_mostrecent")), max(0, cvar("g_maplist_mostrecent_count"))));
852 float Map_IsRecent(string m)
854 return strhasword(cvar_string("g_maplist_mostrecent"), m);
857 float Map_Check(float position, float pass)
861 map_next = argv(position);
864 if(Map_IsRecent(map_next))
867 filename = Map_Filename(position);
868 if(MapInfo_CheckMap(map_next))
872 if(MapHasRightSize(map_next))
877 dprint( "Couldn't select '", filename, "'..\n" );
882 void Map_Goto_SetStr(string nextmapname)
884 if(getmapname_stored != "")
885 strunzone(getmapname_stored);
886 if(nextmapname == "")
887 getmapname_stored = "";
889 getmapname_stored = strzone(nextmapname);
892 void Map_Goto_SetFloat(float position)
894 cvar_set("g_maplist_index", ftos(position));
895 Map_Goto_SetStr(argv(position));
900 // settings persist, except...
901 localcmd("\nsettemp_restore\n");
907 MapInfo_LoadMap(getmapname_stored);
910 // return codes of map selectors:
911 // -1 = temporary failure (that is, try some method that is guaranteed to succeed)
912 // -2 = permanent failure
913 float() MaplistMethod_Iterate = // usual method
917 for(pass = 1; pass <= 2; ++pass)
919 for(i = 1; i < Map_Count; ++i)
922 mapindex = mod(i + Map_Current, Map_Count);
923 if(Map_Check(mapindex, pass))
930 float() MaplistMethod_Repeat = // fallback method
932 if(Map_Check(Map_Current, 2))
937 float() MaplistMethod_Random = // random map selection
943 for(i = 0; i <= imax; ++i)
946 mapindex = mod(Map_Current + floor(random() * (Map_Count - 1) + 1), Map_Count); // any OTHER map
947 if(Map_Check(mapindex, 1))
953 float(float exponent) MaplistMethod_Shuffle = // more clever shuffling
954 // the exponent sets a bias on the map selection:
955 // the higher the exponent, the less likely "shortly repeated" same maps are
957 float i, j, imax, insertpos;
961 for(i = 0; i <= imax; ++i)
965 // now reinsert this at another position
966 insertpos = pow(random(), 1 / exponent); // ]0, 1]
967 insertpos = insertpos * (Map_Count - 1); // ]0, Map_Count - 1]
968 insertpos = ceil(insertpos) + 1; // {2, 3, 4, ..., Map_Count}
969 dprint("SHUFFLE: insert pos = ", ftos(insertpos), "\n");
971 // insert the current map there
973 for(j = 1; j < insertpos; ++j) // i == 1: no loop, will be inserted as first; however, i == 1 has been excluded above
974 newlist = strcat(newlist, " ", argv(j));
975 newlist = strcat(newlist, " ", argv(0)); // now insert the just selected map
976 for(j = insertpos; j < Map_Count; ++j) // i == Map_Count: no loop, has just been inserted as last
977 newlist = strcat(newlist, " ", argv(j));
978 newlist = substring(newlist, 1, strlen(newlist) - 1);
979 cvar_set("g_maplist", newlist);
980 Map_Count = tokenizebyseparator(cvar_string("g_maplist"), " ");
982 // NOTE: the selected map has just been inserted at (insertpos-1)th position
983 Map_Current = insertpos - 1; // this is not really valid, but this way the fallback has a chance of working
984 if(Map_Check(Map_Current, 1))
992 Map_Count = tokenizebyseparator(cvar_string("g_maplist"), " ");
995 bprint( "Maplist is empty! Resetting it to default map list.\n" );
996 cvar_set("g_maplist", MapInfo_ListAllowedMaps(MapInfo_RequiredFlags(), MapInfo_ForbiddenFlags()));
997 if(cvar("g_maplist_shuffle"))
999 localcmd("\nmenu_cmd sync\n");
1000 Map_Count = tokenizebyseparator(cvar_string("g_maplist"), " ");
1003 error("empty maplist, cannot select a new map");
1004 Map_Current = bound(0, GetMaplistPosition(), Map_Count - 1);
1006 if(Map_Current_Name)
1007 strunzone(Map_Current_Name);
1008 Map_Current_Name = strzone(argv(Map_Current)); // will be automatically freed on exit thanks to DP
1009 // this may or may not be correct, but who cares, in the worst case a map
1010 // isn't chosen in the first pass that should have been
1021 if(cvar("g_maplist_shuffle") > 0)
1022 nextMap = MaplistMethod_Shuffle(cvar("g_maplist_shuffle") + 1);
1025 if(cvar("g_maplist_selectrandom"))
1026 nextMap = MaplistMethod_Random();
1029 nextMap = MaplistMethod_Iterate();
1032 nextMap = MaplistMethod_Repeat();
1036 Map_Goto_SetFloat(nextMap);
1037 return getmapname_stored;
1043 float DoNextMapOverride()
1045 if(cvar("g_campaign"))
1047 CampaignPostIntermission();
1048 alreadychangedlevel = TRUE;
1051 if(cvar("quit_when_empty"))
1053 if(player_count <= currentbots)
1056 alreadychangedlevel = TRUE;
1060 if(cvar_string("quit_and_redirect") != "")
1062 redirection_target = strzone(cvar_string("quit_and_redirect"));
1063 alreadychangedlevel = TRUE;
1066 if (cvar("samelevel")) // if samelevel is set, stay on same level
1068 // 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)
1069 //localcmd(strcat("exec \"maps/", mapname, ".mapcfg\"\n"));
1070 // so instead just restart the current map using the restart command (DOES NOT WORK PROPERLY WITH exit_cfg STUFF)
1071 localcmd("restart\n");
1072 //changelevel (mapname);
1073 alreadychangedlevel = TRUE;
1076 if(cvar_string("nextmap") != "")
1077 if(MapInfo_CheckMap(cvar_string("nextmap")))
1079 Map_Goto_SetStr(cvar_string("nextmap"));
1081 alreadychangedlevel = TRUE;
1084 if(cvar("lastlevel"))
1087 localcmd("set lastlevel 0\ntogglemenu\n");
1088 alreadychangedlevel = TRUE;
1096 //local string nextmap;
1097 //local float n, nummaps;
1099 if (alreadychangedlevel)
1101 alreadychangedlevel = TRUE;
1107 for(allowReset = 1; allowReset >= 0; --allowReset)
1109 nextMap = GetNextMap();
1115 bprint( "Maplist contains no single playable map! Resetting it to default map list.\n" );
1116 cvar_set("g_maplist", MapInfo_ListAllowedMaps(MapInfo_RequiredFlags(), MapInfo_ForbiddenFlags()));
1117 if(cvar("g_maplist_shuffle"))
1119 localcmd("\nmenu_cmd sync\n");
1123 error("Everything is broken - not even the default map list works. Please report this to the developers.");
1135 When the player presses attack or jump, change to the next level
1138 .float autoscreenshot;
1139 void() MapVote_Start;
1140 void() MapVote_Think;
1141 float mapvote_initialized;
1142 void IntermissionThink()
1144 FixIntermissionClient(self);
1146 if(cvar("sv_autoscreenshot"))
1147 if(self.autoscreenshot > 0)
1148 if(time > self.autoscreenshot)
1150 self.autoscreenshot = -1;
1151 if(clienttype(self) == CLIENTTYPE_REAL)
1152 stuffcmd(self, "\nscreenshot\necho \"^5A screenshot has been taken at request of the server.\"\n");
1156 if (time < intermission_exittime)
1159 if(!mapvote_initialized)
1160 if (time < intermission_exittime + 10 && !self.BUTTON_ATCK && !self.BUTTON_JUMP && !self.BUTTON_ATCK2 && !self.BUTTON_HOOK && !self.BUTTON_USE)
1170 Returns the entity to view from
1174 entity FindIntermission()
1179 // look for info_intermission first
1180 spot = find (world, classname, "info_intermission");
1182 { // pick a random one
1186 spot = find (spot, classname, "info_intermission");
1188 spot = find (spot, classname, "info_intermission");
1194 // then look for the start position
1195 spot = find (world, classname, "info_player_start");
1199 // testinfo_player_start is only found in regioned levels
1200 spot = find (world, classname, "testplayerstart");
1204 // then look for the start position
1205 spot = find (world, classname, "info_player_deathmatch");
1209 //objerror ("FindIntermission: no spot");
1215 ===============================================================================
1219 ===============================================================================
1222 void DumpStats(float final)
1226 local float to_console;
1227 local float to_eventlog;
1228 local float to_file;
1231 to_console = cvar("sv_logscores_console");
1232 to_eventlog = cvar("sv_eventlog");
1233 to_file = cvar("sv_logscores_file");
1237 to_console = TRUE; // always print printstats replies
1238 to_eventlog = FALSE; // but never print them to the event log
1242 if(cvar("sv_eventlog_console"))
1243 to_console = FALSE; // otherwise we get the output twice
1249 s = strcat(s, GetGametype(), "_", GetMapname(), ":", ftos(rint(time)));
1257 file = fopen(cvar_string("sv_logscores_filename"), FILE_APPEND);
1261 fputs(file, strcat(s, "\n"));
1264 s = strcat(":labels:player:", GetPlayerScoreString(world, 0));
1270 fputs(file, strcat(s, "\n"));
1272 FOR_EACH_CLIENT(other)
1274 if ((clienttype(other) == CLIENTTYPE_REAL) || (clienttype(other) == CLIENTTYPE_BOT && cvar("sv_logscores_bots")))
1276 s = strcat(":player:see-labels:", GetPlayerScoreString(other, 0), ":");
1277 s = strcat(s, ftos(rint(time - other.jointime)), ":");
1278 if(other.classname == "player" || g_arena || g_ca || g_lms)
1279 s = strcat(s, ftos(other.team), ":");
1281 s = strcat(s, "spectator:");
1284 print(s, other.netname, "\n");
1286 GameLogEcho(strcat(s, ftos(other.playerid), ":", other.netname));
1288 fputs(file, strcat(s, other.netname, "\n"));
1294 s = strcat(":labels:teamscores:", GetTeamScoreString(0, 0));
1300 fputs(file, strcat(s, "\n"));
1302 for(i = 1; i < 16; ++i)
1304 s = strcat(":teamscores:see-labels:", GetTeamScoreString(i, 0));
1305 s = strcat(s, ":", ftos(i));
1311 fputs(file, strcat(s, "\n"));
1318 GameLogEcho(":end");
1321 fputs(file, ":end\n");
1326 void FixIntermissionClient(entity e)
1329 if(!e.autoscreenshot) // initial call
1331 e.angles = e.v_angle;
1332 e.angles_x = -e.angles_x;
1333 e.autoscreenshot = time + 0.8; // used for autoscreenshot
1335 // first intermission phase; voting phase has positive health (used to decide whether to send SVC_FINALE or not)
1336 e.solid = SOLID_NOT;
1337 e.movetype = MOVETYPE_NONE;
1338 e.takedamage = DAMAGE_NO;
1341 e.weaponentity.effects = EF_NODRAW;
1342 if (e.weaponentity.weaponentity)
1343 e.weaponentity.weaponentity.effects = EF_NODRAW;
1345 if(clienttype(e) == CLIENTTYPE_REAL)
1347 stuffcmd(e, "\nscr_printspeed 1000000\n");
1348 s = cvar_string("sv_intermission_cdtrack");
1350 stuffcmd(e, strcat("\ncd loop ", s, "\n"));
1352 WriteByte(MSG_ONE, SVC_INTERMISSION);
1356 //e.velocity = '0 0 0';
1357 //e.fixangle = TRUE;
1359 // TODO halt weapon animation
1364 go to the next level for deathmatch
1365 only called if a time or frag limit has expired
1373 intermission_running = 1;
1375 // enforce a wait time before allowing changelevel
1376 if(player_count > 0)
1377 intermission_exittime = time + cvar("sv_mapchange_delay");
1379 intermission_exittime = -1;
1382 WriteByte (MSG_ALL, SVC_CDTRACK);
1383 WriteByte (MSG_ALL, 3);
1384 WriteByte (MSG_ALL, 3);
1385 // done in FixIntermission
1388 //pos = FindIntermission ();
1394 if(cvar("sv_eventlog"))
1395 GameLogEcho(":gameover");
1401 // save the stats to a text file on the client
1402 // stuffcmd(other, log_stats "stats/file_name");
1404 // stuffcmd(other, log_stats "");
1405 // use a filename similar to the demo name
1406 // string file_name;
1407 // file_name = strcat("\nlog_file \"stats/", strftime(TRUE, "%Y-%m-%d_%H-%M"), "_", mapname, ".txt\""); // open the log file
1409 // write a stats parser for the menu
1411 if(cvar("sv_accuracy_data_send")) {
1412 string stats_to_send;
1414 FOR_EACH_CLIENT(other) { // make the string to send
1415 FixIntermissionClient(other);
1417 if(other.cvar_cl_accuracy_data_share) {
1418 stats_to_send = strcat(stats_to_send, ":hits:", other.netname);
1420 for(i = WEP_FIRST; i <= WEP_LAST; ++i)
1421 stats_to_send = strcat(stats_to_send, ":", ftos(other.stats_hit[i-1]));
1423 stats_to_send = strcat(stats_to_send, "\n:fired:", other.netname);
1425 for(i = WEP_FIRST; i <= WEP_LAST; ++i)
1426 stats_to_send = strcat(stats_to_send, ":", ftos(other.stats_fired[i-1]));
1428 stats_to_send = strcat(stats_to_send, "\n");
1432 FOR_EACH_REALCLIENT(other) { // only spam humans
1433 Score_NicePrint(other); // print the score
1435 if(other.cvar_cl_accuracy_data_receive) // send the stats string to all the willing clients
1436 bprint(stats_to_send);
1438 } else { // ye olde message
1439 FOR_EACH_PLAYER(other) {
1440 FixIntermissionClient(other);
1443 bprint(other.netname, " ^7wins.\n");
1447 if(cvar("g_campaign"))
1448 CampaignPreIntermission();
1450 localcmd("\nsv_hook_gameend\n");
1457 Exit deathmatch games upon conditions
1460 void CheckRules_Player()
1462 if (gameover) // someone else quit the game already
1465 if(self.deadflag == DEAD_NO)
1466 self.play_time += frametime;
1468 // fixme: don't check players; instead check spawnfunc_dom_team and spawnfunc_ctf_team entities
1469 // (div0: and that in CheckRules_World please)
1472 float checkrules_equality;
1473 float checkrules_suddendeathwarning;
1474 float checkrules_suddendeathend;
1475 float checkrules_overtimesadded; //how many overtimes have been already added
1477 float WINNING_NO = 0; // no winner, but time limits may terminate the game
1478 float WINNING_YES = 1; // winner found
1479 float WINNING_NEVER = 2; // no winner, enter overtime if time limit is reached
1480 float WINNING_STARTSUDDENDEATHOVERTIME = 3; // no winner, enter suddendeath overtime NOW
1482 float InitiateSuddenDeath()
1484 // Check first whether normal overtimes could be added before initiating suddendeath mode
1485 // - for this timelimit_overtime needs to be >0 of course
1486 // - also check the winning condition calculated in the previous frame and only add normal overtime
1487 // again, if at the point at which timelimit would be extended again, still no winner was found
1488 if ((checkrules_overtimesadded >= 0) && (checkrules_overtimesadded < cvar("timelimit_overtimes")) && cvar("timelimit_overtime") && !(g_race && !g_race_qualifying))
1490 return 1; // need to call InitiateOvertime later
1494 if(!checkrules_suddendeathend)
1496 checkrules_suddendeathend = time + 60 * cvar("timelimit_suddendeath");
1497 if(g_race && !g_race_qualifying)
1498 race_StartCompleting();
1504 void InitiateOvertime() // ONLY call this if InitiateSuddenDeath returned true
1506 ++checkrules_overtimesadded;
1507 //add one more overtime by simply extending the timelimit
1509 tl = cvar("timelimit");
1510 tl += cvar("timelimit_overtime");
1511 cvar_set("timelimit", ftos(tl));
1512 string minutesPlural;
1513 if (cvar("timelimit_overtime") == 1)
1514 minutesPlural = " ^3minute";
1516 minutesPlural = " ^3minutes";
1520 "^3Now playing ^1OVERTIME^3!\n\n^3Added ^1",
1521 ftos(cvar("timelimit_overtime")),
1528 float GetWinningCode(float fraglimitreached, float equality)
1530 if(cvar("g_campaign") == 1)
1531 if(fraglimitreached)
1538 if(fraglimitreached)
1539 return WINNING_STARTSUDDENDEATHOVERTIME;
1541 return WINNING_NEVER;
1543 if(fraglimitreached)
1549 // set the .winning flag for exactly those players with a given field value
1550 void SetWinners(.float field, float value)
1553 FOR_EACH_PLAYER(head)
1554 head.winning = (head.field == value);
1557 // set the .winning flag for those players with a given field value
1558 void AddWinners(.float field, float value)
1561 FOR_EACH_PLAYER(head)
1562 if(head.field == value)
1566 // clear the .winning flags
1567 void ClearWinners(void)
1570 FOR_EACH_PLAYER(head)
1574 // Onslaught winning condition:
1575 // game terminates if only one team has a working generator (or none)
1576 float WinningCondition_Onslaught()
1579 local float t1, t2, t3, t4;
1581 WinningConditionHelper(); // set worldstatus
1586 // first check if the game has ended
1587 t1 = t2 = t3 = t4 = 0;
1588 head = find(world, classname, "onslaught_generator");
1591 if (head.health > 0)
1593 if (head.team == COLOR_TEAM1) t1 = 1;
1594 if (head.team == COLOR_TEAM2) t2 = 1;
1595 if (head.team == COLOR_TEAM3) t3 = 1;
1596 if (head.team == COLOR_TEAM4) t4 = 1;
1598 head = find(head, classname, "onslaught_generator");
1600 if (t1 + t2 + t3 + t4 < 2)
1602 // game over, only one team remains (or none)
1604 if (t1) SetWinners(team, COLOR_TEAM1);
1605 if (t2) SetWinners(team, COLOR_TEAM2);
1606 if (t3) SetWinners(team, COLOR_TEAM3);
1607 if (t4) SetWinners(team, COLOR_TEAM4);
1608 dprint("Have a winner, ending game.\n");
1612 // Two or more teams remain
1616 float LMS_NewPlayerLives()
1619 fl = cvar("fraglimit");
1623 // first player has left the game for dying too much? Nobody else can get in.
1624 if(lms_lowest_lives < 1)
1627 if(!cvar("g_lms_join_anytime"))
1628 if(lms_lowest_lives < fl - cvar("g_lms_last_join"))
1631 return bound(1, lms_lowest_lives, fl);
1634 // Assault winning condition: If the attackers triggered a round end (by fulfilling all objectives)
1635 // they win. Otherwise the defending team wins once the timelimit passes.
1636 void assault_new_round();
1637 float WinningCondition_Assault()
1641 WinningConditionHelper(); // set worldstatus
1643 status = WINNING_NO;
1644 // as the timelimit has not yet passed just assume the defending team will win
1645 if(assault_attacker_team == COLOR_TEAM1)
1647 SetWinners(team, COLOR_TEAM2);
1651 SetWinners(team, COLOR_TEAM1);
1655 ent = find(world, classname, "target_assault_roundend");
1658 if(ent.winning) // round end has been triggered by attacking team
1660 bprint("ASSAULT: round completed...\n");
1661 SetWinners(team, assault_attacker_team);
1663 TeamScore_AddToTeam(assault_attacker_team, ST_ASSAULT_OBJECTIVES, 666 - TeamScore_AddToTeam(assault_attacker_team, ST_ASSAULT_OBJECTIVES, 0));
1665 if(ent.cnt == 1 || cvar("g_campaign")) // this was the second round
1667 status = WINNING_YES;
1671 local entity oldself;
1674 assault_new_round();
1683 // LMS winning condition: game terminates if and only if there's at most one
1684 // one player who's living lives. Top two scores being equal cancels the time
1686 float WinningCondition_LMS()
1693 have_player = FALSE;
1694 have_players = FALSE;
1695 l = LMS_NewPlayerLives();
1697 head = find(world, classname, "player");
1700 head2 = find(head, classname, "player");
1702 have_players = TRUE;
1706 // we have at least one player
1709 // two or more active players - continue with the game
1713 // exactly one player?
1716 SetWinners(winning, 0); // NOTE: exactly one player is still "player", so this works out
1720 // game still running (that is, nobody got removed from the game by a frag yet)? then continue
1726 // and assign him his first place
1727 PlayerScore_Add(head, SP_LMS_RANK, 1);
1734 // nobody is playing at all...
1737 // wait for players...
1741 // SNAFU (maybe a draw game?)
1743 dprint("No players, ending game.\n");
1748 // When we get here, we have at least two players who are actually LIVING,
1749 // now check if the top two players have equal score.
1750 WinningConditionHelper();
1753 if(WinningConditionHelper_winner)
1754 WinningConditionHelper_winner.winning = TRUE;
1755 if(WinningConditionHelper_topscore == WinningConditionHelper_secondscore)
1756 return WINNING_NEVER;
1758 // Top two have different scores? Way to go for our beloved TIMELIMIT!
1762 void ShuffleMaplist()
1764 cvar_set("g_maplist", shufflewords(cvar_string("g_maplist")));
1768 float WinningCondition_Scores(float limit, float leadlimit)
1772 // TODO make everything use THIS winning condition (except LMS)
1773 WinningConditionHelper();
1777 team1_score = TeamScore_GetCompareValue(COLOR_TEAM1);
1778 team2_score = TeamScore_GetCompareValue(COLOR_TEAM2);
1779 team3_score = TeamScore_GetCompareValue(COLOR_TEAM3);
1780 team4_score = TeamScore_GetCompareValue(COLOR_TEAM4);
1784 if(WinningConditionHelper_winner)
1785 WinningConditionHelper_winner.winning = 1;
1786 if(WinningConditionHelper_winnerteam >= 0)
1787 SetWinners(team, WinningConditionHelper_winnerteam);
1789 if(WinningConditionHelper_lowerisbetter)
1791 WinningConditionHelper_topscore = -WinningConditionHelper_topscore;
1792 WinningConditionHelper_secondscore = -WinningConditionHelper_secondscore;
1796 if(WinningConditionHelper_zeroisworst)
1797 leadlimit = 0; // not supported in this mode
1799 if(g_dm || g_tdm || g_arena || g_ca || (g_race && !g_race_qualifying) || g_nexball)
1800 // these modes always score in increments of 1, thus this makes sense
1802 if(leaderfrags != WinningConditionHelper_topscore)
1804 leaderfrags = WinningConditionHelper_topscore;
1807 if (leaderfrags == limit - 1)
1808 Announce("1fragleft");
1809 else if (leaderfrags == limit - 2)
1810 Announce("2fragsleft");
1811 else if (leaderfrags == limit - 3)
1812 Announce("3fragsleft");
1816 limitreached = FALSE;
1818 if(WinningConditionHelper_topscore >= limit)
1819 limitreached = TRUE;
1822 float leadlimitreached;
1823 leadlimitreached = (WinningConditionHelper_topscore - WinningConditionHelper_secondscore >= leadlimit);
1824 if(cvar("leadlimit_and_fraglimit"))
1825 limitreached = (limitreached && leadlimitreached);
1827 limitreached = (limitreached || leadlimitreached);
1830 return GetWinningCode(
1831 WinningConditionHelper_topscore && limitreached,
1832 WinningConditionHelper_equality
1836 float WinningCondition_Race(float fraglimit)
1847 if(p.race_completed)
1852 wc = WinningCondition_Scores(fraglimit, 0);
1854 // ALWAYS initiate overtime, unless EVERYONE has finished the race!
1855 if(wc == WINNING_YES || wc == WINNING_STARTSUDDENDEATHOVERTIME)
1856 // do NOT support equality when the laps are all raced!
1857 return WINNING_STARTSUDDENDEATHOVERTIME;
1859 return WINNING_NEVER;
1863 void ReadyRestart();
1864 float WinningCondition_QualifyingThenRace(float limit)
1867 wc = WinningCondition_Scores(limit, 0);
1869 // NEVER initiate overtime
1870 if(wc == WINNING_YES || wc == WINNING_STARTSUDDENDEATHOVERTIME)
1878 float WinningCondition_RanOutOfSpawns()
1882 if(have_team_spawns <= 0)
1885 if(!some_spawn_has_been_used)
1888 team1_score = team2_score = team3_score = team4_score = 0;
1890 FOR_EACH_PLAYER(head) if(head.deadflag == DEAD_NO)
1892 if(head.team == COLOR_TEAM1)
1894 else if(head.team == COLOR_TEAM2)
1896 else if(head.team == COLOR_TEAM3)
1898 else if(head.team == COLOR_TEAM4)
1902 for(head = world; (head = find(head, classname, "info_player_deathmatch")) != world; )
1904 if(head.team == COLOR_TEAM1)
1906 else if(head.team == COLOR_TEAM2)
1908 else if(head.team == COLOR_TEAM3)
1910 else if(head.team == COLOR_TEAM4)
1915 if(team1_score + team2_score + team3_score + team4_score == 0)
1917 checkrules_equality = TRUE;
1920 else if(team1_score + team2_score + team3_score + team4_score == 1)
1923 if(team1_score) t = COLOR_TEAM1;
1924 if(team2_score) t = COLOR_TEAM2;
1925 if(team3_score) t = COLOR_TEAM3;
1926 if(team4_score) t = COLOR_TEAM4;
1927 CheckAllowedTeams(world);
1928 for(i = 0; i < MAX_TEAMSCORE; ++i)
1930 if(t != COLOR_TEAM1) if(c1 >= 0) TeamScore_AddToTeam(COLOR_TEAM1, i, -1000);
1931 if(t != COLOR_TEAM2) if(c2 >= 0) TeamScore_AddToTeam(COLOR_TEAM2, i, -1000);
1932 if(t != COLOR_TEAM3) if(c3 >= 0) TeamScore_AddToTeam(COLOR_TEAM3, i, -1000);
1933 if(t != COLOR_TEAM4) if(c4 >= 0) TeamScore_AddToTeam(COLOR_TEAM4, i, -1000);
1936 AddWinners(team, t);
1947 Exit deathmatch games upon conditions
1950 void CheckRules_World()
1962 MapVote_Think should now do that part
1963 if (intermission_running)
1964 if (time >= intermission_exittime + 60)
1966 if(!DoNextMapOverride())
1972 if (gameover) // someone else quit the game already
1974 if(player_count == 0) // Nobody there? Then let's go to the next map
1976 // this will actually check the player count in the next frame
1977 // again, but this shouldn't hurt
1981 timelimit = cvar("timelimit") * 60;
1982 fraglimit = cvar("fraglimit");
1983 leadlimit = cvar("leadlimit");
1985 if(inWarmupStage || time <= game_starttime) // NOTE: this is <= to prevent problems in the very tic where the game starts
1988 timelimit = 0; // timelimit is not made for warmup
1990 fraglimit = 0; // no fraglimit for now
1991 leadlimit = 0; // no leadlimit for now
1995 timelimit = 0; // ONS has its own overtime rule
1999 timelimit += game_starttime;
2001 else if (timelimit < 0)
2011 if(checkrules_suddendeathend)
2013 if(!checkrules_suddendeathwarning)
2015 checkrules_suddendeathwarning = TRUE;
2016 if(g_race && !g_race_qualifying)
2017 bcenterprint("^3Everyone, finish your lap! The race is over!");
2019 bcenterprint("^3Now playing ^1OVERTIME^3!\n\n^3Keep fragging until we have a ^1winner^3!");
2024 if (timelimit && time >= timelimit)
2026 if(g_race && (g_race_qualifying == 2) && timelimit > 0)
2029 float playerswithlaps;
2032 totalplayers = playerswithlaps = readyplayers = 0;
2033 FOR_EACH_PLAYER(head)
2036 if(PlayerScore_Add(head, SP_RACE_FASTEST, 0))
2042 // at least 2 of the players have completed a lap: start the RACE
2043 // otherwise, the players should end the qualifying on their own
2044 if(readyplayers || playerswithlaps >= 2)
2046 checkrules_suddendeathend = 0;
2047 ReadyRestart(); // go to race
2051 wantovertime |= InitiateSuddenDeath();
2054 wantovertime |= InitiateSuddenDeath();
2058 if (checkrules_suddendeathend && time >= checkrules_suddendeathend)
2064 float checkrules_status;
2065 checkrules_status = WinningCondition_RanOutOfSpawns();
2066 if(checkrules_status == WINNING_YES)
2068 bprint("Hey! Someone ran out of spawns!\n");
2070 else if(g_race && !g_race_qualifying && timelimit >= 0)
2072 checkrules_status = WinningCondition_Race(fraglimit);
2073 //print("WC_RACE yields ", ftos(checkrules_status), "\n");
2075 else if(g_race && g_race_qualifying == 2 && timelimit >= 0)
2077 checkrules_status = WinningCondition_QualifyingThenRace(fraglimit);
2078 //print("WC_QUALIFYING_THEN_RACE yields ", ftos(checkrules_status), "\n");
2082 checkrules_status = WinningCondition_Assault(); // TODO remove this?
2086 checkrules_status = WinningCondition_LMS();
2088 else if (g_onslaught)
2090 checkrules_status = WinningCondition_Onslaught(); // TODO remove this?
2094 checkrules_status = WinningCondition_Scores(fraglimit, leadlimit);
2095 //print("WC_SCORES yields ", ftos(checkrules_status), "\n");
2098 if(checkrules_status == WINNING_STARTSUDDENDEATHOVERTIME)
2100 checkrules_status = WINNING_NEVER;
2101 checkrules_overtimesadded = -1;
2102 wantovertime |= InitiateSuddenDeath();
2105 if(checkrules_status == WINNING_NEVER)
2106 // equality cases! Nobody wins if the overtime ends in a draw.
2111 if(checkrules_status == WINNING_NEVER)
2114 checkrules_status = WINNING_YES;
2117 if(checkrules_suddendeathend)
2118 if(checkrules_status != WINNING_NEVER || time >= checkrules_suddendeathend)
2119 checkrules_status = WINNING_YES;
2121 if(checkrules_status == WINNING_YES)
2123 //print("WINNING\n");
2128 float mapvote_nextthink;
2129 float mapvote_initialized;
2130 float mapvote_keeptwotime;
2131 float mapvote_timeout;
2132 string mapvote_message;
2133 #define MAPVOTE_SCREENSHOT_DIRS_COUNT 4
2134 string mapvote_screenshot_dirs[MAPVOTE_SCREENSHOT_DIRS_COUNT];
2135 float mapvote_screenshot_dirs_count;
2137 float mapvote_count;
2138 float mapvote_count_real;
2139 string mapvote_maps[MAPVOTE_COUNT];
2140 float mapvote_maps_screenshot_dir[MAPVOTE_COUNT];
2141 string mapvote_maps_pakfile[MAPVOTE_COUNT];
2142 float mapvote_maps_suggested[MAPVOTE_COUNT];
2143 string mapvote_suggestions[MAPVOTE_COUNT];
2144 float mapvote_suggestion_ptr;
2145 float mapvote_maxlen;
2146 float mapvote_voters;
2147 float mapvote_votes[MAPVOTE_COUNT];
2149 float mapvote_detail;
2150 float mapvote_abstain;
2153 void MapVote_ClearAllVotes()
2155 FOR_EACH_CLIENT(other)
2159 string MapVote_Suggest(string m)
2163 return "That's not how to use this command.";
2164 if(!cvar("g_maplist_votable_suggestions"))
2165 return "Suggestions are not accepted on this server.";
2166 if(mapvote_initialized)
2167 return "Can't suggest - voting is already in progress!";
2168 m = MapInfo_FixName(m);
2170 return "The map you suggested is not available on this server.";
2171 if(!cvar("g_maplist_votable_suggestions_override_mostrecent"))
2173 return "This server does not allow for recent maps to be played again. Please be patient for some rounds.";
2175 if(!MapInfo_CheckMap(m))
2176 return "The map you suggested does not support the current game mode.";
2177 for(i = 0; i < mapvote_suggestion_ptr; ++i)
2178 if(mapvote_suggestions[i] == m)
2179 return "This map was already suggested.";
2180 if(mapvote_suggestion_ptr >= MAPVOTE_COUNT)
2182 i = floor(random() * mapvote_suggestion_ptr);
2186 i = mapvote_suggestion_ptr;
2187 mapvote_suggestion_ptr += 1;
2189 if(mapvote_suggestions[i] != "")
2190 strunzone(mapvote_suggestions[i]);
2191 mapvote_suggestions[i] = strzone(m);
2192 if(cvar("sv_eventlog"))
2193 GameLogEcho(strcat(":vote:suggested:", m, ":", ftos(self.playerid)));
2194 return strcat("Suggestion of ", m, " accepted.");
2197 void MapVote_AddVotable(string nextMap, float isSuggestion)
2200 string pakfile, mapfile;
2204 for(j = 0; j < mapvote_count; ++j)
2205 if(mapvote_maps[j] == nextMap)
2207 if(strlen(nextMap) > mapvote_maxlen)
2208 mapvote_maxlen = strlen(nextMap);
2209 mapvote_maps[mapvote_count] = strzone(nextMap);
2210 mapvote_maps_suggested[mapvote_count] = isSuggestion;
2212 for(i = 0; i < mapvote_screenshot_dirs_count; ++i)
2214 mapfile = strcat(mapvote_screenshot_dirs[i], "/", mapvote_maps[i]);
2215 pakfile = whichpack(strcat(mapfile, ".tga"));
2217 pakfile = whichpack(strcat(mapfile, ".jpg"));
2219 pakfile = whichpack(strcat(mapfile, ".png"));
2223 if(i >= mapvote_screenshot_dirs_count)
2224 i = 0; // FIXME maybe network this error case, as that means there is no mapshot on the server?
2225 for(o = strstr(pakfile, "/", 0)+1; o > 0; o = strstr(pakfile, "/", 0)+1)
2226 pakfile = substring(pakfile, o, -1);
2228 mapvote_maps_screenshot_dir[mapvote_count] = i;
2229 mapvote_maps_pakfile[mapvote_count] = strzone(pakfile);
2234 void MapVote_Spawn();
2240 MapVote_ClearAllVotes();
2243 mapvote_detail = !cvar("g_maplist_votable_nodetail");
2244 mapvote_abstain = cvar("g_maplist_votable_abstain");
2247 nmax = min(MAPVOTE_COUNT - 1, cvar("g_maplist_votable"));
2249 nmax = min(MAPVOTE_COUNT, cvar("g_maplist_votable"));
2250 smax = min3(nmax, cvar("g_maplist_votable_suggestions"), mapvote_suggestion_ptr);
2252 // we need this for AddVotable, as that cycles through the screenshot dirs
2253 mapvote_screenshot_dirs_count = tokenize_console(cvar_string("g_maplist_votable_screenshot_dir"));
2254 if(mapvote_screenshot_dirs_count == 0)
2255 mapvote_screenshot_dirs_count = tokenize_console("maps levelshots");
2256 mapvote_screenshot_dirs_count = min(mapvote_screenshot_dirs_count, MAPVOTE_SCREENSHOT_DIRS_COUNT);
2257 for(i = 0; i < mapvote_screenshot_dirs_count; ++i)
2258 mapvote_screenshot_dirs[i] = strzone(argv(i));
2260 if(mapvote_suggestion_ptr)
2261 for(i = 0; i < 100 && mapvote_count < smax; ++i)
2262 MapVote_AddVotable(mapvote_suggestions[floor(random() * mapvote_suggestion_ptr)], TRUE);
2264 for(i = 0; i < 100 && mapvote_count < nmax; ++i)
2265 MapVote_AddVotable(GetNextMap(), FALSE);
2267 if(mapvote_count == 0)
2269 bprint( "Maplist contains no single playable map! Resetting it to default map list.\n" );
2270 cvar_set("g_maplist", MapInfo_ListAllowedMaps(MapInfo_RequiredFlags(), MapInfo_ForbiddenFlags()));
2271 if(cvar("g_maplist_shuffle"))
2273 localcmd("\nmenu_cmd sync\n");
2274 for(i = 0; i < 100 && mapvote_count < nmax; ++i)
2275 MapVote_AddVotable(GetNextMap(), FALSE);
2278 mapvote_count_real = mapvote_count;
2280 MapVote_AddVotable("don't care", 0);
2282 //dprint("mapvote count is ", ftos(mapvote_count), "\n");
2284 mapvote_keeptwotime = time + cvar("g_maplist_votable_keeptwotime");
2285 mapvote_timeout = time + cvar("g_maplist_votable_timeout");
2286 if(mapvote_count_real < 3 || mapvote_keeptwotime <= time)
2287 mapvote_keeptwotime = 0;
2288 mapvote_message = "Choose a map and press its key!";
2293 void MapVote_SendPicture(float id)
2296 WriteByte(MSG_ONE, SVC_TEMPENTITY);
2297 WriteByte(MSG_ONE, TE_CSQC_PICTURE);
2298 WriteByte(MSG_ONE, id);
2299 WritePicture(MSG_ONE, strcat(mapvote_screenshot_dirs[mapvote_maps_screenshot_dir[id]], "/", mapvote_maps[id]), 3072);
2302 float GameCommand_MapVote(string cmd)
2304 if(!intermission_running)
2307 if(cmd == "mv_getpic")
2309 MapVote_SendPicture(stof(argv(1)));
2316 float MapVote_GetMapMask()
2318 float mask, i, power;
2320 for(i = 0, power = 1; i < mapvote_count; ++i, power *= 2)
2321 if(mapvote_maps[i] != "")
2327 float MapVote_SendEntity(entity to, float sf)
2332 sf &~= 2; // if we send 1, we don't need to also send 2
2334 WriteByte(MSG_ENTITY, ENT_CLIENT_MAPVOTE);
2335 WriteByte(MSG_ENTITY, sf);
2339 // flag 1 == initialization
2340 for(i = 0; i < mapvote_screenshot_dirs_count; ++i)
2341 WriteString(MSG_ENTITY, mapvote_screenshot_dirs[i]);
2342 WriteString(MSG_ENTITY, "");
2343 WriteByte(MSG_ENTITY, mapvote_count);
2344 WriteByte(MSG_ENTITY, mapvote_abstain);
2345 WriteByte(MSG_ENTITY, mapvote_detail);
2346 WriteCoord(MSG_ENTITY, mapvote_timeout);
2347 if(mapvote_count <= 8)
2348 WriteByte(MSG_ENTITY, MapVote_GetMapMask());
2350 WriteShort(MSG_ENTITY, MapVote_GetMapMask());
2351 for(i = 0; i < mapvote_count; ++i)
2352 if(mapvote_maps[i] != "")
2354 if(mapvote_abstain && i == mapvote_count - 1)
2356 WriteString(MSG_ENTITY, ""); // abstain needs no text
2357 WriteString(MSG_ENTITY, ""); // abstain needs no pack
2358 WriteByte(MSG_ENTITY, 0); // abstain needs no screenshot dir
2362 WriteString(MSG_ENTITY, mapvote_maps[i]);
2363 WriteString(MSG_ENTITY, mapvote_maps_pakfile[i]);
2364 WriteByte(MSG_ENTITY, mapvote_maps_screenshot_dir[i]);
2371 // flag 2 == update of mask
2372 if(mapvote_count <= 8)
2373 WriteByte(MSG_ENTITY, MapVote_GetMapMask());
2375 WriteShort(MSG_ENTITY, MapVote_GetMapMask());
2381 for(i = 0; i < mapvote_count; ++i)
2382 if(mapvote_maps[i] != "")
2383 WriteByte(MSG_ENTITY, mapvote_votes[i]);
2385 WriteByte(MSG_ENTITY, to.mapvote);
2391 void MapVote_Spawn()
2393 Net_LinkEntity(mapvote_ent = spawn(), FALSE, 0, MapVote_SendEntity);
2396 void MapVote_TouchMask()
2398 mapvote_ent.SendFlags |= 2;
2401 void MapVote_TouchVotes(entity voter)
2403 mapvote_ent.SendFlags |= 4;
2406 float MapVote_Finished(float mappos)
2412 if(cvar("sv_eventlog"))
2414 result = strcat(":vote:finished:", mapvote_maps[mappos]);
2415 result = strcat(result, ":", ftos(mapvote_votes[mappos]), "::");
2416 didntvote = mapvote_voters;
2417 for(i = 0; i < mapvote_count; ++i)
2418 if(mapvote_maps[i] != "")
2420 didntvote -= mapvote_votes[i];
2423 result = strcat(result, ":", mapvote_maps[i]);
2424 result = strcat(result, ":", ftos(mapvote_votes[i]));
2427 result = strcat(result, ":didn't vote:", ftos(didntvote));
2429 GameLogEcho(result);
2430 if(mapvote_maps_suggested[mappos])
2431 GameLogEcho(strcat(":vote:suggestion_accepted:", mapvote_maps[mappos]));
2434 FOR_EACH_REALCLIENT(other)
2435 FixClientCvars(other);
2437 Map_Goto_SetStr(mapvote_maps[mappos]);
2439 alreadychangedlevel = TRUE;
2442 void MapVote_CheckRules_1()
2446 for(i = 0; i < mapvote_count; ++i) if(mapvote_maps[i] != "")
2448 //dprint("Map ", ftos(i), ": "); dprint(mapvote_maps[i], "\n");
2449 mapvote_votes[i] = 0;
2453 FOR_EACH_REALCLIENT(other)
2458 i = other.mapvote - 1;
2459 //dprint("Player ", other.netname, " vote = ", ftos(other.mapvote - 1), "\n");
2460 mapvote_votes[i] = mapvote_votes[i] + 1;
2465 float MapVote_CheckRules_2()
2468 float firstPlace, secondPlace;
2469 float firstPlaceVotes, secondPlaceVotes;
2470 float mapvote_voters_real;
2473 if(mapvote_count_real == 1)
2474 return MapVote_Finished(0);
2476 mapvote_voters_real = mapvote_voters;
2478 mapvote_voters_real -= mapvote_votes[mapvote_count - 1];
2480 RandomSelection_Init();
2481 for(i = 0; i < mapvote_count_real; ++i) if(mapvote_maps[i] != "")
2482 RandomSelection_Add(world, i, string_null, 1, mapvote_votes[i]);
2483 firstPlace = RandomSelection_chosen_float;
2484 firstPlaceVotes = RandomSelection_best_priority;
2485 //dprint("First place: ", ftos(firstPlace), "\n");
2486 //dprint("First place votes: ", ftos(firstPlaceVotes), "\n");
2488 RandomSelection_Init();
2489 for(i = 0; i < mapvote_count_real; ++i) if(mapvote_maps[i] != "")
2491 RandomSelection_Add(world, i, string_null, 1, mapvote_votes[i]);
2492 secondPlace = RandomSelection_chosen_float;
2493 secondPlaceVotes = RandomSelection_best_priority;
2494 //dprint("Second place: ", ftos(secondPlace), "\n");
2495 //dprint("Second place votes: ", ftos(secondPlaceVotes), "\n");
2497 if(firstPlace == -1)
2498 error("No first place in map vote... WTF?");
2500 if(secondPlace == -1 || time > mapvote_timeout || (mapvote_voters_real - firstPlaceVotes) < firstPlaceVotes)
2501 return MapVote_Finished(firstPlace);
2503 if(mapvote_keeptwotime)
2504 if(time > mapvote_keeptwotime || (mapvote_voters_real - firstPlaceVotes - secondPlaceVotes) < secondPlaceVotes)
2507 MapVote_TouchMask();
2508 mapvote_message = "Now decide between the TOP TWO!";
2509 mapvote_keeptwotime = 0;
2510 result = strcat(":vote:keeptwo:", mapvote_maps[firstPlace]);
2511 result = strcat(result, ":", ftos(firstPlaceVotes));
2512 result = strcat(result, ":", mapvote_maps[secondPlace]);
2513 result = strcat(result, ":", ftos(secondPlaceVotes), "::");
2514 didntvote = mapvote_voters;
2515 for(i = 0; i < mapvote_count; ++i)
2516 if(mapvote_maps[i] != "")
2518 didntvote -= mapvote_votes[i];
2520 if(i != secondPlace)
2522 result = strcat(result, ":", mapvote_maps[i]);
2523 result = strcat(result, ":", ftos(mapvote_votes[i]));
2524 if(i < mapvote_count_real)
2526 strunzone(mapvote_maps[i]);
2527 mapvote_maps[i] = "";
2528 strunzone(mapvote_maps_pakfile[i]);
2529 mapvote_maps_pakfile[i] = "";
2533 result = strcat(result, ":didn't vote:", ftos(didntvote));
2534 if(cvar("sv_eventlog"))
2535 GameLogEcho(result);
2545 keeptwo = mapvote_keeptwotime;
2546 MapVote_CheckRules_1(); // count
2547 if(MapVote_CheckRules_2()) // decide
2551 FOR_EACH_REALCLIENT(other)
2553 // hide scoreboard again
2554 if(other.health != 2342)
2556 other.health = 2342;
2558 if(clienttype(other) == CLIENTTYPE_REAL)
2561 WriteByte(MSG_ONE, SVC_FINALE);
2562 WriteString(MSG_ONE, "");
2566 // clear possibly invalid votes
2567 if(mapvote_maps[other.mapvote - 1] == "")
2569 // use impulses as new vote
2570 if(other.impulse >= 1 && other.impulse <= mapvote_count)
2571 if(mapvote_maps[other.impulse - 1] != "")
2573 other.mapvote = other.impulse;
2574 MapVote_TouchVotes(other);
2582 MapVote_CheckRules_1(); // just count
2584 void MapVote_Start()
2589 MapInfo_Enumerate();
2590 if(MapInfo_FilterGametype(MapInfo_CurrentGametype(), MapInfo_CurrentFeatures(), MapInfo_RequiredFlags(), MapInfo_ForbiddenFlags(), 1))
2593 void MapVote_Think()
2598 if(alreadychangedlevel)
2601 if(time < mapvote_nextthink)
2605 mapvote_nextthink = time + 0.5;
2607 if(!mapvote_initialized)
2609 if(cvar("rescan_pending") == 1)
2611 cvar_set("rescan_pending", "2");
2612 localcmd("fs_rescan\nrescan_pending 3\n");
2615 else if(cvar("rescan_pending") == 2)
2619 else if(cvar("rescan_pending") == 3)
2621 // now build missing mapinfo files
2622 if(!MapInfo_FilterGametype(MapInfo_CurrentGametype(), MapInfo_CurrentFeatures(), MapInfo_RequiredFlags(), MapInfo_ForbiddenFlags(), 1))
2625 // we're done, start the timer
2626 cvar_set("rescan_pending", "0");
2629 mapvote_initialized = TRUE;
2630 if(DoNextMapOverride())
2632 if(!cvar("g_maplist_votable") || player_count <= 0)
2643 string GotoMap(string m)
2645 if(!MapInfo_CheckMap(m))
2646 return "The map you chose is not available on this server.";
2647 cvar_set("nextmap", m);
2648 cvar_set("timelimit", "-1");
2649 if(mapvote_initialized || alreadychangedlevel)
2651 if(DoNextMapOverride())
2652 return "Map switch initiated.";
2654 return "Hm... no. For some reason I like THIS map more.";
2657 return "Map switch will happen after scoreboard.";
2664 FOR_EACH_REALCLIENT(self)
2666 if(self.classname == "spectator")
2668 if(self.enemy.typehitsound)
2669 play2(self, "misc/typehit.wav");
2670 else if(self.enemy.hitsound && self.cvar_cl_hitsound)
2671 play2(self, "misc/hit.wav");
2675 if(self.typehitsound)
2676 play2(self, "misc/typehit.wav");
2677 else if(self.hitsound && self.cvar_cl_hitsound)
2678 play2(self, "misc/hit.wav");
2681 altime = time + frametime * (1 + cvar("g_antilag_nudge"));
2682 // add 1 frametime because after this, engine SV_Physics
2683 // increases time by a frametime and then networks the frame
2684 // add another frametime because client shows everything with
2685 // 1 frame of lag (cl_nolerp 0). The last +1 however should not be
2687 FOR_EACH_CLIENT(self)
2689 self.hitsound = FALSE;
2690 self.typehitsound = FALSE;
2691 antilag_record(self, altime);
2698 * returns TRUE if redirecting
2700 float redirection_timeout;
2701 float redirection_nextthink;
2702 float RedirectionThink()
2704 float clients_found;
2706 if(redirection_target == "")
2709 if(!redirection_timeout)
2711 cvar_set("sv_public", "-2");
2712 redirection_timeout = time + 0.6; // this will only try twice... should be able to keep more clients
2713 if(redirection_target == "self")
2714 bprint("^3SERVER NOTICE:^7 restarting the server\n");
2716 bprint("^3SERVER NOTICE:^7 redirecting everyone to ", redirection_target, "\n");
2719 if(time < redirection_nextthink)
2722 redirection_nextthink = time + 1;
2725 FOR_EACH_REALCLIENT(self)
2727 print("Redirecting: sending connect command to ", self.netname, "\n");
2728 if(redirection_target == "self")
2729 stuffcmd(self, "\ndisconnect; reconnect\n");
2731 stuffcmd(self, strcat("\ndisconnect; connect ", redirection_target, "\n"));
2735 print("Redirecting: ", ftos(clients_found), " clients left.\n");
2737 if(time > redirection_timeout || clients_found == 0)
2738 localcmd("\nwait; wait; wait; quit\n");
2743 void TargetMusic_RestoreGame();
2746 // Loaded from a save game
2747 // some things then break, so let's work around them...
2749 // Progs DB (capture records)
2750 ServerProgsDB = db_load("server.db");
2754 MapInfo_Enumerate();
2755 MapInfo_FilterGametype(MapInfo_CurrentGametype(), MapInfo_CurrentFeatures(), MapInfo_RequiredFlags(), MapInfo_ForbiddenFlags(), 1);
2758 TargetMusic_RestoreGame();
2763 if(gameover > 1) // shutting down already?
2766 gameover = 2; // 2 = server shutting down
2768 if(world_initialized > 0)
2770 world_initialized = 0;
2771 print("Saving persistent data...\n");
2773 if(!cheatcount_total)
2774 db_save(ServerProgsDB, "server.db");
2775 if(cvar("developer"))
2776 db_save(TemporaryDB, "server-temp.db");
2777 CheatShutdown(); // must be after cheatcount check
2778 db_close(ServerProgsDB);
2779 db_close(TemporaryDB);
2781 // tell the bot system the game is ending now
2784 WeaponStats_Shutdown();
2787 else if(world_initialized == 0)
2789 print("NOTE: crashed before even initializing the world, not saving persistent data\n");