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");
283 BADCVAR("net_address");
284 BADCVAR("net_address_ipv6");
287 BADCVAR("timelimit");
288 BADCVAR("fraglimit");
291 BADCVAR("g_assault");
294 BADCVAR("g_domination");
295 BADCVAR("g_keyhunt");
296 BADCVAR("g_keyhunt_teams");
297 BADCVAR("g_onslaught");
300 BADCVAR("g_runematch");
302 BADCVAR("g_nexball");
307 BADCVAR("g_maplist");
308 BADCVAR("g_maplist_mostrecent");
314 d = cvar_defstring(k);
317 cvar_changes = strcat(cvar_changes, k, " \"", v, "\" // \"", d, "\"\n");
318 if(strlen(cvar_changes) > 16384)
320 cvar_changes = "// too many settings have been changed to show them here\n";
326 if(cvar_changes == "")
327 cvar_changes = "// this server runs at default settings\n";
329 cvar_changes = strcat("// this server runs at modified settings:\n", cvar_changes);
330 cvar_changes = strzone(cvar_changes);
333 void detect_maptype()
342 o_x += random() * (world.maxs_x - world.mins_x);
343 o_y += random() * (world.maxs_y - world.mins_y);
344 o_z += random() * (world.maxs_z - world.mins_z);
346 tracebox(o, PL_MIN, PL_MAX, o - '0 0 32768', MOVE_WORLDONLY, world);
347 if(trace_fraction == 1)
352 for(i = 0; i < 64; i += 4)
354 tracebox(o, '-1 -1 -1' * i, '1 1 1' * i, o - '0 0 32768', MOVE_WORLDONLY, world);
355 if(trace_fraction == 1)
357 print(ftos(i), " -> ", vtos(trace_endpos), "\n");
366 float RandomSeed_Send(entity to, float sf)
368 WriteByte(MSG_ENTITY, ENT_CLIENT_RANDOMSEED);
369 WriteShort(MSG_ENTITY, self.cnt);
372 void RandomSeed_Think()
374 self.cnt = bound(0, floor(random() * 65536), 65535);
375 self.nextthink = time + 5;
379 void RandomSeed_Spawn()
381 randomseed = spawn();
382 randomseed.think = RandomSeed_Think;
383 Net_LinkEntity(randomseed, FALSE, 0, RandomSeed_Send);
388 self.think(); // sets random seed and nextthink
392 void spawnfunc___init_dedicated_server(void)
394 // handler for _init/_init map (only for dedicated server initialization)
396 world_initialized = -1; // don't complain
398 cvar_string = cvar_string_normal;
399 cvar_set = cvar_set_normal;
401 remove = remove_unsafely;
405 e.think = GotoFirstMap;
406 e.nextthink = time; // this is usually 1 at this point
409 e.classname = "info_player_deathmatch"; // safeguard against player joining
411 self.classname = "worldspawn"; // safeguard against various stuff ;)
414 MapInfo_FilterGametype(MapInfo_CurrentGametype(), MapInfo_CurrentFeatures(), MapInfo_RequiredFlags(), MapInfo_ForbiddenFlags(), 0);
417 void Map_MarkAsRecent(string m);
418 float world_already_spawned;
419 void RegisterWeapons();
421 void ClientInit_Spawn();
422 void WeaponStats_Init();
423 void WeaponStats_Shutdown();
424 void spawnfunc_worldspawn (void)
426 float fd, l, i, j, n;
430 cvar_string = cvar_string_normal;
431 cvar_set = cvar_set_normal;
433 if(world_already_spawned)
434 error("world already spawned - you may have EXACTLY ONE worldspawn!");
435 world_already_spawned = TRUE;
437 remove = remove_safely; // during spawning, watch what you remove!
439 check_unacceptable_compiler_bugs();
441 compressShortVector_init();
444 head = nextent(world);
449 head = nextent(head);
452 // needs to be done so early as they would still spawn
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
522 bot_waypoints_for_items = cvar("g_waypoints_for_items");
523 if(bot_waypoints_for_items == 1)
524 if(self.spawnflags & SPAWNFLAG_NO_WAYPOINTS_FOR_ITEMS)
525 bot_waypoints_for_items = 0;
527 // for setting by mapinfo
528 q3acompat_machineshotgunswap = cvar("sv_q3acompat_machineshotgunswap");
529 cvar_set("sv_q3acompat_machineshotgunswap", "0");
533 WaypointSprite_Init();
538 GameLogInit(); // prepare everything
539 if(cvar("sv_eventlog"))
541 s = strcat(cvar_string("sv_eventlog_files_counter"), ".");
542 s = strcat(s, ftos(random()));
543 matchid = strzone(s);
545 GameLogEcho(strcat(":gamestart:", GetGametype(), "_", GetMapname(), ":", s));
546 s = ":gameinfo:mutators:LIST";
549 MUTATOR_CALLHOOK(BuildMutatorsString);
552 if(cvar("g_grappling_hook"))
553 s = strcat(s, ":grappling_hook");
554 if(!cvar("g_use_ammunition"))
555 s = strcat(s, ":no_use_ammunition");
556 if(!cvar("g_pickup_items"))
557 s = strcat(s, ":no_pickup_items");
558 if(cvar_string("g_weaponarena") != "0")
559 s = strcat(s, ":", cvar_string("g_weaponarena"), " arena");
560 if(cvar("g_vampire"))
561 s = strcat(s, ":vampire");
562 if(cvar("g_laserguided_missile"))
563 s = strcat(s, ":laserguided_missile");
564 if(cvar("g_norecoil"))
565 s = strcat(s, ":norecoil");
567 s = strcat(s, ":midair");
568 if(cvar("g_minstagib"))
569 s = strcat(s, ":minstagib");
571 GameLogEcho(":gameinfo:end");
574 matchid = strzone(ftos(random()));
576 cvar_set("nextmap", "");
580 if(cvar("g_campaign"))
588 MapInfo_FilterGametype(MapInfo_CurrentGametype(), MapInfo_CurrentFeatures(), MapInfo_RequiredFlags(), MapInfo_ForbiddenFlags(), 1);
590 if(whichpack(strcat("maps/", mapname, ".cfg")) != "")
592 fd = fopen(strcat("maps/", mapname, ".cfg"), FILE_READ);
595 while((s = fgets(fd)))
597 l = tokenize_console(s);
602 print("Found ^1DEPRECATED^7 cd loop command in .cfg file; put this line in mapinfo instead:\n");
603 print(" cdtrack ", argv(2), "\n");
605 else if(argv(0) == "fog")
607 print("Found ^1DEPRECATED^7 fog command in .cfg file; put this line in worldspawn in the .map/.bsp/.ent file instead:\n");
608 print(" \"fog\" \"", s, "\"\n");
610 else if(argv(0) == "set")
612 print("Found ^1DEPRECATED^7 set command in .cfg file; put this line in mapinfo instead:\n");
613 print(" clientsettemp_for_type all ", argv(1), " ", argv(2), "\n");
615 else if(argv(0) != "//")
617 print("Found ^1DEPRECATED^7 set command in .cfg file; put this line in mapinfo instead:\n");
618 print(" clientsettemp_for_type all ", argv(0), " ", argv(1), "\n");
627 addstat(STAT_WEAPONS, AS_INT, weapons);
628 addstat(STAT_SWITCHWEAPON, AS_INT, switchweapon);
629 addstat(STAT_GAMESTARTTIME, AS_FLOAT, stat_game_starttime);
630 addstat(STAT_ALLOW_OLDNEXBEAM, AS_INT, stat_allow_oldnexbeam);
633 addstat(STAT_STRENGTH_FINISHED, AS_FLOAT, strength_finished);
634 addstat(STAT_INVINCIBLE_FINISHED, AS_FLOAT, invincible_finished);
635 addstat(STAT_PRESSED_KEYS, AS_FLOAT, pressedkeys);
636 addstat(STAT_FUEL, AS_INT, ammo_fuel);
637 addstat(STAT_DAMAGE_HITS, AS_INT, stat_hit);
638 addstat(STAT_DAMAGE_FIRED, AS_INT, stat_fired);
639 addstat(STAT_SHOTORG, AS_INT, stat_shotorg);
640 addstat(STAT_LEADLIMIT, AS_FLOAT, stat_leadlimit);
641 addstat(STAT_BULLETS_LOADED, AS_INT, campingrifle_bulletcounter);
643 addstat(STAT_NEX_CHARGE, AS_FLOAT, nex_charge);
645 // g_movementspeed hack
646 addstat(STAT_MOVEVARS_AIRSPEEDLIMIT_NONQW, AS_FLOAT, stat_sv_airspeedlimit_nonqw);
647 addstat(STAT_MOVEVARS_AIRACCEL_QW, AS_FLOAT, stat_sv_airaccel_qw);
648 addstat(STAT_MOVEVARS_AIRSTRAFEACCEL_QW, AS_FLOAT, stat_sv_airstrafeaccel_qw);
650 next_pingtime = time + 5;
651 InitializeEntity(self, cvar_changes_init, INITPRIO_CVARS);
655 lsmaps_reply = "^7Maps available: ";
656 lsnewmaps_reply = "^7Maps without a record set: ";
657 for(i = 0, j = 0; i < MapInfo_count; ++i)
659 if(MapInfo_Get_ByID(i))
660 if not(MapInfo_Map_flags & (MAPINFO_FLAG_HIDDEN | MAPINFO_FLAG_FORBIDDEN))
667 lsmaps_reply = strcat(lsmaps_reply, col, MapInfo_Map_bspname, " ");
668 if(g_race && !stof(db_get(ServerProgsDB, strcat(MapInfo_Map_bspname, RACE_RECORD, "time"))))
669 lsnewmaps_reply = strcat(lsnewmaps_reply, col, MapInfo_Map_bspname, " ");
670 else if(g_cts && !stof(db_get(ServerProgsDB, strcat(MapInfo_Map_bspname, CTS_RECORD, "time"))))
671 lsnewmaps_reply = strcat(lsnewmaps_reply, col, MapInfo_Map_bspname, " ");
674 lsmaps_reply = strzone(strcat(lsmaps_reply, "\n"));
675 if (!g_race && !g_cts)
676 lsnewmaps_reply = "Need to be playing race or CTS for lsnewmaps to work.";
677 lsnewmaps_reply = strzone(strcat(lsnewmaps_reply, "\n"));
679 maplist_reply = "^7Maps in list: ";
680 n = tokenize_console(cvar_string("g_maplist"));
681 for(i = 0, j = 0; i < n; ++i)
683 if(MapInfo_CheckMap(argv(i)))
689 maplist_reply = strcat(maplist_reply, col, argv(i), " ");
693 maplist_reply = strzone(strcat(maplist_reply, "\n"));
694 MapInfo_ClearTemps();
696 for(i = 0; i < 10; ++i)
698 records_reply[i] = strzone(getrecords(i));
701 rankings_reply = strzone(getrankings());
705 PingPLReport_Spawn();
709 localcmd("\n_sv_hook_gamestart ", GetGametype(), "\n");
711 // fill sv_curl_serverpackages from .serverpackage files
712 if(cvar("sv_curl_serverpackages_auto"))
714 fd = search_begin("*.serverpackage", TRUE, FALSE);
718 j = search_getsize(fd);
719 for(i = 0; i < j; ++i)
720 s = strcat(s, " ", search_getfilename(fd, i));
723 cvar_set("sv_curl_serverpackages", substring(s, 1, -1));
726 world_initialized = 1;
729 void spawnfunc_light (void)
731 //makestatic (self); // Who the f___ did that?
735 float TryFile( string pFilename )
738 dprint("TryFile(\"", pFilename, "\")\n");
739 lHandle = fopen( pFilename, FILE_READ );
740 if( lHandle != -1 ) {
750 return GametypeNameFromType(game);
753 string getmapname_stored;
759 float Map_Count, Map_Current;
760 string Map_Current_Name;
762 // NOTE: this now expects the map list to be already tokenize()d and the count in Map_Count
763 float GetMaplistPosition()
769 idx = cvar("g_maplist_index");
776 for(pos = 0; pos < Map_Count; ++pos)
780 // resume normal maplist rotation if current map is not in g_maplist
784 float MapHasRightSize(string map)
787 if(currentbots || cvar("bot_number") || player_count < cvar("minplayers"))
788 if(cvar("g_maplist_check_waypoints"))
790 dprint("checkwp "); dprint(map);
791 fh = fopen(strcat("maps/", map, ".waypoints"), FILE_READ);
794 dprint(": no waypoints\n");
797 dprint(": has waypoints\n");
801 // open map size restriction file
802 dprint("opensize "); dprint(map);
803 fh = fopen(strcat("maps/", map, ".sizes"), FILE_READ);
806 float mapmin, mapmax;
808 mapmin = stof(fgets(fh));
809 mapmax = stof(fgets(fh));
811 if(player_count < mapmin)
813 dprint("not enough\n");
816 if(player_count > mapmax)
818 dprint("too many\n");
821 dprint("right size\n");
824 dprint(": not found\n");
828 string Map_Filename(float position)
830 return strcat("maps/", argv(position), ".bsp");
833 string strwords(string s, float w)
836 for(endpos = 0; w && endpos >= 0; --w)
837 endpos = strstrofs(s, " ", endpos + 1);
841 return substring(s, 0, endpos);
844 float strhasword(string s, string w)
846 return strstrofs(strcat(" ", s, " "), strcat(" ", w, " "), 0) >= 0;
849 void Map_MarkAsRecent(string m)
851 cvar_set("g_maplist_mostrecent", strwords(strcat(m, " ", cvar_string("g_maplist_mostrecent")), max(0, cvar("g_maplist_mostrecent_count"))));
854 float Map_IsRecent(string m)
856 return strhasword(cvar_string("g_maplist_mostrecent"), m);
859 float Map_Check(float position, float pass)
863 map_next = argv(position);
866 if(Map_IsRecent(map_next))
869 filename = Map_Filename(position);
870 if(MapInfo_CheckMap(map_next))
874 if(MapHasRightSize(map_next))
879 dprint( "Couldn't select '", filename, "'..\n" );
884 void Map_Goto_SetStr(string nextmapname)
886 if(getmapname_stored != "")
887 strunzone(getmapname_stored);
888 if(nextmapname == "")
889 getmapname_stored = "";
891 getmapname_stored = strzone(nextmapname);
894 void Map_Goto_SetFloat(float position)
896 cvar_set("g_maplist_index", ftos(position));
897 Map_Goto_SetStr(argv(position));
902 // settings persist, except...
903 localcmd("\nsettemp_restore\n");
909 MapInfo_LoadMap(getmapname_stored);
912 // return codes of map selectors:
913 // -1 = temporary failure (that is, try some method that is guaranteed to succeed)
914 // -2 = permanent failure
915 float() MaplistMethod_Iterate = // usual method
919 for(pass = 1; pass <= 2; ++pass)
921 for(i = 1; i < Map_Count; ++i)
924 mapindex = mod(i + Map_Current, Map_Count);
925 if(Map_Check(mapindex, pass))
932 float() MaplistMethod_Repeat = // fallback method
934 if(Map_Check(Map_Current, 2))
939 float() MaplistMethod_Random = // random map selection
945 for(i = 0; i <= imax; ++i)
948 mapindex = mod(Map_Current + floor(random() * (Map_Count - 1) + 1), Map_Count); // any OTHER map
949 if(Map_Check(mapindex, 1))
955 float(float exponent) MaplistMethod_Shuffle = // more clever shuffling
956 // the exponent sets a bias on the map selection:
957 // the higher the exponent, the less likely "shortly repeated" same maps are
959 float i, j, imax, insertpos;
963 for(i = 0; i <= imax; ++i)
967 // now reinsert this at another position
968 insertpos = pow(random(), 1 / exponent); // ]0, 1]
969 insertpos = insertpos * (Map_Count - 1); // ]0, Map_Count - 1]
970 insertpos = ceil(insertpos) + 1; // {2, 3, 4, ..., Map_Count}
971 dprint("SHUFFLE: insert pos = ", ftos(insertpos), "\n");
973 // insert the current map there
975 for(j = 1; j < insertpos; ++j) // i == 1: no loop, will be inserted as first; however, i == 1 has been excluded above
976 newlist = strcat(newlist, " ", argv(j));
977 newlist = strcat(newlist, " ", argv(0)); // now insert the just selected map
978 for(j = insertpos; j < Map_Count; ++j) // i == Map_Count: no loop, has just been inserted as last
979 newlist = strcat(newlist, " ", argv(j));
980 newlist = substring(newlist, 1, strlen(newlist) - 1);
981 cvar_set("g_maplist", newlist);
982 Map_Count = tokenizebyseparator(cvar_string("g_maplist"), " ");
984 // NOTE: the selected map has just been inserted at (insertpos-1)th position
985 Map_Current = insertpos - 1; // this is not really valid, but this way the fallback has a chance of working
986 if(Map_Check(Map_Current, 1))
994 Map_Count = tokenizebyseparator(cvar_string("g_maplist"), " ");
997 bprint( "Maplist is empty! Resetting it to default map list.\n" );
998 cvar_set("g_maplist", MapInfo_ListAllowedMaps(MapInfo_RequiredFlags(), MapInfo_ForbiddenFlags()));
999 if(cvar("g_maplist_shuffle"))
1001 localcmd("\nmenu_cmd sync\n");
1002 Map_Count = tokenizebyseparator(cvar_string("g_maplist"), " ");
1005 error("empty maplist, cannot select a new map");
1006 Map_Current = bound(0, GetMaplistPosition(), Map_Count - 1);
1008 if(Map_Current_Name)
1009 strunzone(Map_Current_Name);
1010 Map_Current_Name = strzone(argv(Map_Current)); // will be automatically freed on exit thanks to DP
1011 // this may or may not be correct, but who cares, in the worst case a map
1012 // isn't chosen in the first pass that should have been
1023 if(cvar("g_maplist_shuffle") > 0)
1024 nextMap = MaplistMethod_Shuffle(cvar("g_maplist_shuffle") + 1);
1027 if(cvar("g_maplist_selectrandom"))
1028 nextMap = MaplistMethod_Random();
1031 nextMap = MaplistMethod_Iterate();
1034 nextMap = MaplistMethod_Repeat();
1038 Map_Goto_SetFloat(nextMap);
1039 return getmapname_stored;
1045 float DoNextMapOverride()
1047 if(cvar("g_campaign"))
1049 CampaignPostIntermission();
1050 alreadychangedlevel = TRUE;
1053 if(cvar("quit_when_empty"))
1055 if(player_count <= currentbots)
1058 alreadychangedlevel = TRUE;
1062 if(cvar_string("quit_and_redirect") != "")
1064 redirection_target = strzone(cvar_string("quit_and_redirect"));
1065 alreadychangedlevel = TRUE;
1068 if (cvar("samelevel")) // if samelevel is set, stay on same level
1070 // 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)
1071 //localcmd(strcat("exec \"maps/", mapname, ".mapcfg\"\n"));
1072 // so instead just restart the current map using the restart command (DOES NOT WORK PROPERLY WITH exit_cfg STUFF)
1073 localcmd("restart\n");
1074 //changelevel (mapname);
1075 alreadychangedlevel = TRUE;
1078 if(cvar_string("nextmap") != "")
1079 if(MapInfo_CheckMap(cvar_string("nextmap")))
1081 Map_Goto_SetStr(cvar_string("nextmap"));
1083 alreadychangedlevel = TRUE;
1086 if(cvar("lastlevel"))
1089 localcmd("set lastlevel 0\ntogglemenu\n");
1090 alreadychangedlevel = TRUE;
1098 //local string nextmap;
1099 //local float n, nummaps;
1101 if (alreadychangedlevel)
1103 alreadychangedlevel = TRUE;
1109 for(allowReset = 1; allowReset >= 0; --allowReset)
1111 nextMap = GetNextMap();
1117 bprint( "Maplist contains no single playable map! Resetting it to default map list.\n" );
1118 cvar_set("g_maplist", MapInfo_ListAllowedMaps(MapInfo_RequiredFlags(), MapInfo_ForbiddenFlags()));
1119 if(cvar("g_maplist_shuffle"))
1121 localcmd("\nmenu_cmd sync\n");
1125 error("Everything is broken - not even the default map list works. Please report this to the developers.");
1137 When the player presses attack or jump, change to the next level
1140 .float autoscreenshot;
1141 void() MapVote_Start;
1142 void() MapVote_Think;
1143 float mapvote_initialized;
1144 void IntermissionThink()
1146 FixIntermissionClient(self);
1148 if(cvar("sv_autoscreenshot"))
1149 if(self.autoscreenshot > 0)
1150 if(time > self.autoscreenshot)
1152 self.autoscreenshot = -1;
1153 if(clienttype(self) == CLIENTTYPE_REAL)
1154 stuffcmd(self, "\nscreenshot\necho \"^5A screenshot has been taken at request of the server.\"\n");
1158 if (time < intermission_exittime)
1161 if(!mapvote_initialized)
1162 if (time < intermission_exittime + 10 && !self.BUTTON_ATCK && !self.BUTTON_JUMP && !self.BUTTON_ATCK2 && !self.BUTTON_HOOK && !self.BUTTON_USE)
1172 Returns the entity to view from
1176 entity FindIntermission()
1181 // look for info_intermission first
1182 spot = find (world, classname, "info_intermission");
1184 { // pick a random one
1188 spot = find (spot, classname, "info_intermission");
1190 spot = find (spot, classname, "info_intermission");
1196 // then look for the start position
1197 spot = find (world, classname, "info_player_start");
1201 // testinfo_player_start is only found in regioned levels
1202 spot = find (world, classname, "testplayerstart");
1206 // then look for the start position
1207 spot = find (world, classname, "info_player_deathmatch");
1211 //objerror ("FindIntermission: no spot");
1217 ===============================================================================
1221 ===============================================================================
1224 void DumpStats(float final)
1228 local float to_console;
1229 local float to_eventlog;
1230 local float to_file;
1233 to_console = cvar("sv_logscores_console");
1234 to_eventlog = cvar("sv_eventlog");
1235 to_file = cvar("sv_logscores_file");
1239 to_console = TRUE; // always print printstats replies
1240 to_eventlog = FALSE; // but never print them to the event log
1244 if(cvar("sv_eventlog_console"))
1245 to_console = FALSE; // otherwise we get the output twice
1251 s = strcat(s, GetGametype(), "_", GetMapname(), ":", ftos(rint(time)));
1259 file = fopen(cvar_string("sv_logscores_filename"), FILE_APPEND);
1263 fputs(file, strcat(s, "\n"));
1266 s = strcat(":labels:player:", GetPlayerScoreString(world, 0));
1272 fputs(file, strcat(s, "\n"));
1274 FOR_EACH_CLIENT(other)
1276 if ((clienttype(other) == CLIENTTYPE_REAL) || (clienttype(other) == CLIENTTYPE_BOT && cvar("sv_logscores_bots")))
1278 s = strcat(":player:see-labels:", GetPlayerScoreString(other, 0), ":");
1279 s = strcat(s, ftos(rint(time - other.jointime)), ":");
1280 if(other.classname == "player" || g_arena || g_ca || g_lms)
1281 s = strcat(s, ftos(other.team), ":");
1283 s = strcat(s, "spectator:");
1286 print(s, other.netname, "\n");
1288 GameLogEcho(strcat(s, ftos(other.playerid), ":", other.netname));
1290 fputs(file, strcat(s, other.netname, "\n"));
1296 s = strcat(":labels:teamscores:", GetTeamScoreString(0, 0));
1302 fputs(file, strcat(s, "\n"));
1304 for(i = 1; i < 16; ++i)
1306 s = strcat(":teamscores:see-labels:", GetTeamScoreString(i, 0));
1307 s = strcat(s, ":", ftos(i));
1313 fputs(file, strcat(s, "\n"));
1320 GameLogEcho(":end");
1323 fputs(file, ":end\n");
1328 void FixIntermissionClient(entity e)
1331 if(!e.autoscreenshot) // initial call
1333 e.angles = e.v_angle;
1334 e.angles_x = -e.angles_x;
1335 e.autoscreenshot = time + 0.8; // used for autoscreenshot
1337 // first intermission phase; voting phase has positive health (used to decide whether to send SVC_FINALE or not)
1338 e.solid = SOLID_NOT;
1339 e.movetype = MOVETYPE_NONE;
1340 e.takedamage = DAMAGE_NO;
1343 e.weaponentity.effects = EF_NODRAW;
1344 if (e.weaponentity.weaponentity)
1345 e.weaponentity.weaponentity.effects = EF_NODRAW;
1347 if(clienttype(e) == CLIENTTYPE_REAL)
1349 stuffcmd(e, "\nscr_printspeed 1000000\n");
1350 s = cvar_string("sv_intermission_cdtrack");
1352 stuffcmd(e, strcat("\ncd loop ", s, "\n"));
1354 WriteByte(MSG_ONE, SVC_INTERMISSION);
1358 //e.velocity = '0 0 0';
1359 //e.fixangle = TRUE;
1361 // TODO halt weapon animation
1366 go to the next level for deathmatch
1367 only called if a time or frag limit has expired
1375 intermission_running = 1;
1377 // enforce a wait time before allowing changelevel
1378 if(player_count > 0)
1379 intermission_exittime = time + cvar("sv_mapchange_delay");
1381 intermission_exittime = -1;
1384 WriteByte (MSG_ALL, SVC_CDTRACK);
1385 WriteByte (MSG_ALL, 3);
1386 WriteByte (MSG_ALL, 3);
1387 // done in FixIntermission
1390 //pos = FindIntermission ();
1396 if(cvar("sv_eventlog"))
1397 GameLogEcho(":gameover");
1403 // save the stats to a text file on the client
1404 // stuffcmd(other, log_stats "stats/file_name");
1406 // stuffcmd(other, log_stats "");
1407 // use a filename similar to the demo name
1408 // string file_name;
1409 // file_name = strcat("\nlog_file \"stats/", strftime(TRUE, "%Y-%m-%d_%H-%M"), "_", mapname, ".txt\""); // open the log file
1411 // write a stats parser for the menu
1413 if(cvar("sv_accuracy_data_send")) {
1414 string stats_to_send;
1416 FOR_EACH_CLIENT(other) { // make the string to send
1417 FixIntermissionClient(other);
1419 if(other.cvar_cl_accuracy_data_share) {
1420 stats_to_send = strcat(stats_to_send, ":hits:", other.netname);
1422 for(i = WEP_FIRST; i <= WEP_LAST; ++i)
1423 stats_to_send = strcat(stats_to_send, ":", ftos(other.stats_hit[i-1]));
1425 stats_to_send = strcat(stats_to_send, "\n:fired:", other.netname);
1427 for(i = WEP_FIRST; i <= WEP_LAST; ++i)
1428 stats_to_send = strcat(stats_to_send, ":", ftos(other.stats_fired[i-1]));
1430 stats_to_send = strcat(stats_to_send, "\n");
1434 FOR_EACH_REALCLIENT(other) { // only spam humans
1435 Score_NicePrint(other); // print the score
1437 if(other.cvar_cl_accuracy_data_receive) // send the stats string to all the willing clients
1438 bprint(stats_to_send);
1440 } else { // ye olde message
1441 FOR_EACH_PLAYER(other) {
1442 FixIntermissionClient(other);
1445 bprint(other.netname, " ^7wins.\n");
1449 if(cvar("g_campaign"))
1450 CampaignPreIntermission();
1452 localcmd("\nsv_hook_gameend\n");
1459 Exit deathmatch games upon conditions
1462 void CheckRules_Player()
1464 if (gameover) // someone else quit the game already
1467 if(self.deadflag == DEAD_NO)
1468 self.play_time += frametime;
1470 // fixme: don't check players; instead check spawnfunc_dom_team and spawnfunc_ctf_team entities
1471 // (div0: and that in CheckRules_World please)
1474 float checkrules_equality;
1475 float checkrules_suddendeathwarning;
1476 float checkrules_suddendeathend;
1477 float checkrules_overtimesadded; //how many overtimes have been already added
1479 float WINNING_NO = 0; // no winner, but time limits may terminate the game
1480 float WINNING_YES = 1; // winner found
1481 float WINNING_NEVER = 2; // no winner, enter overtime if time limit is reached
1482 float WINNING_STARTSUDDENDEATHOVERTIME = 3; // no winner, enter suddendeath overtime NOW
1484 float InitiateSuddenDeath()
1486 // Check first whether normal overtimes could be added before initiating suddendeath mode
1487 // - for this timelimit_overtime needs to be >0 of course
1488 // - also check the winning condition calculated in the previous frame and only add normal overtime
1489 // again, if at the point at which timelimit would be extended again, still no winner was found
1490 if ((checkrules_overtimesadded >= 0) && (checkrules_overtimesadded < cvar("timelimit_overtimes")) && cvar("timelimit_overtime") && !(g_race && !g_race_qualifying))
1492 return 1; // need to call InitiateOvertime later
1496 if(!checkrules_suddendeathend)
1498 checkrules_suddendeathend = time + 60 * cvar("timelimit_suddendeath");
1499 if(g_race && !g_race_qualifying)
1500 race_StartCompleting();
1506 void InitiateOvertime() // ONLY call this if InitiateSuddenDeath returned true
1508 ++checkrules_overtimesadded;
1509 //add one more overtime by simply extending the timelimit
1511 tl = cvar("timelimit");
1512 tl += cvar("timelimit_overtime");
1513 cvar_set("timelimit", ftos(tl));
1514 string minutesPlural;
1515 if (cvar("timelimit_overtime") == 1)
1516 minutesPlural = " ^3minute";
1518 minutesPlural = " ^3minutes";
1522 "^3Now playing ^1OVERTIME^3!\n\n^3Added ^1",
1523 ftos(cvar("timelimit_overtime")),
1530 float GetWinningCode(float fraglimitreached, float equality)
1532 if(cvar("g_campaign") == 1)
1533 if(fraglimitreached)
1540 if(fraglimitreached)
1541 return WINNING_STARTSUDDENDEATHOVERTIME;
1543 return WINNING_NEVER;
1545 if(fraglimitreached)
1551 // set the .winning flag for exactly those players with a given field value
1552 void SetWinners(.float field, float value)
1555 FOR_EACH_PLAYER(head)
1556 head.winning = (head.field == value);
1559 // set the .winning flag for those players with a given field value
1560 void AddWinners(.float field, float value)
1563 FOR_EACH_PLAYER(head)
1564 if(head.field == value)
1568 // clear the .winning flags
1569 void ClearWinners(void)
1572 FOR_EACH_PLAYER(head)
1576 // Onslaught winning condition:
1577 // game terminates if only one team has a working generator (or none)
1578 float WinningCondition_Onslaught()
1581 local float t1, t2, t3, t4;
1583 WinningConditionHelper(); // set worldstatus
1588 // first check if the game has ended
1589 t1 = t2 = t3 = t4 = 0;
1590 head = find(world, classname, "onslaught_generator");
1593 if (head.health > 0)
1595 if (head.team == COLOR_TEAM1) t1 = 1;
1596 if (head.team == COLOR_TEAM2) t2 = 1;
1597 if (head.team == COLOR_TEAM3) t3 = 1;
1598 if (head.team == COLOR_TEAM4) t4 = 1;
1600 head = find(head, classname, "onslaught_generator");
1602 if (t1 + t2 + t3 + t4 < 2)
1604 // game over, only one team remains (or none)
1606 if (t1) SetWinners(team, COLOR_TEAM1);
1607 if (t2) SetWinners(team, COLOR_TEAM2);
1608 if (t3) SetWinners(team, COLOR_TEAM3);
1609 if (t4) SetWinners(team, COLOR_TEAM4);
1610 dprint("Have a winner, ending game.\n");
1614 // Two or more teams remain
1618 float LMS_NewPlayerLives()
1621 fl = cvar("fraglimit");
1625 // first player has left the game for dying too much? Nobody else can get in.
1626 if(lms_lowest_lives < 1)
1629 if(!cvar("g_lms_join_anytime"))
1630 if(lms_lowest_lives < fl - cvar("g_lms_last_join"))
1633 return bound(1, lms_lowest_lives, fl);
1636 // Assault winning condition: If the attackers triggered a round end (by fulfilling all objectives)
1637 // they win. Otherwise the defending team wins once the timelimit passes.
1638 void assault_new_round();
1639 float WinningCondition_Assault()
1643 WinningConditionHelper(); // set worldstatus
1645 status = WINNING_NO;
1646 // as the timelimit has not yet passed just assume the defending team will win
1647 if(assault_attacker_team == COLOR_TEAM1)
1649 SetWinners(team, COLOR_TEAM2);
1653 SetWinners(team, COLOR_TEAM1);
1657 ent = find(world, classname, "target_assault_roundend");
1660 if(ent.winning) // round end has been triggered by attacking team
1662 bprint("ASSAULT: round completed...\n");
1663 SetWinners(team, assault_attacker_team);
1665 TeamScore_AddToTeam(assault_attacker_team, ST_ASSAULT_OBJECTIVES, 666 - TeamScore_AddToTeam(assault_attacker_team, ST_ASSAULT_OBJECTIVES, 0));
1667 if(ent.cnt == 1 || cvar("g_campaign")) // this was the second round
1669 status = WINNING_YES;
1673 local entity oldself;
1676 assault_new_round();
1685 // LMS winning condition: game terminates if and only if there's at most one
1686 // one player who's living lives. Top two scores being equal cancels the time
1688 float WinningCondition_LMS()
1695 have_player = FALSE;
1696 have_players = FALSE;
1697 l = LMS_NewPlayerLives();
1699 head = find(world, classname, "player");
1702 head2 = find(head, classname, "player");
1704 have_players = TRUE;
1708 // we have at least one player
1711 // two or more active players - continue with the game
1715 // exactly one player?
1718 SetWinners(winning, 0); // NOTE: exactly one player is still "player", so this works out
1722 // game still running (that is, nobody got removed from the game by a frag yet)? then continue
1728 // and assign him his first place
1729 PlayerScore_Add(head, SP_LMS_RANK, 1);
1736 // nobody is playing at all...
1739 // wait for players...
1743 // SNAFU (maybe a draw game?)
1745 dprint("No players, ending game.\n");
1750 // When we get here, we have at least two players who are actually LIVING,
1751 // now check if the top two players have equal score.
1752 WinningConditionHelper();
1755 if(WinningConditionHelper_winner)
1756 WinningConditionHelper_winner.winning = TRUE;
1757 if(WinningConditionHelper_topscore == WinningConditionHelper_secondscore)
1758 return WINNING_NEVER;
1760 // Top two have different scores? Way to go for our beloved TIMELIMIT!
1764 void ShuffleMaplist()
1766 cvar_set("g_maplist", shufflewords(cvar_string("g_maplist")));
1770 float WinningCondition_Scores(float limit, float leadlimit)
1774 // TODO make everything use THIS winning condition (except LMS)
1775 WinningConditionHelper();
1779 team1_score = TeamScore_GetCompareValue(COLOR_TEAM1);
1780 team2_score = TeamScore_GetCompareValue(COLOR_TEAM2);
1781 team3_score = TeamScore_GetCompareValue(COLOR_TEAM3);
1782 team4_score = TeamScore_GetCompareValue(COLOR_TEAM4);
1786 if(WinningConditionHelper_winner)
1787 WinningConditionHelper_winner.winning = 1;
1788 if(WinningConditionHelper_winnerteam >= 0)
1789 SetWinners(team, WinningConditionHelper_winnerteam);
1791 if(WinningConditionHelper_lowerisbetter)
1793 WinningConditionHelper_topscore = -WinningConditionHelper_topscore;
1794 WinningConditionHelper_secondscore = -WinningConditionHelper_secondscore;
1798 if(WinningConditionHelper_zeroisworst)
1799 leadlimit = 0; // not supported in this mode
1801 if(g_dm || g_tdm || g_arena || g_ca || (g_race && !g_race_qualifying) || g_nexball)
1802 // these modes always score in increments of 1, thus this makes sense
1804 if(leaderfrags != WinningConditionHelper_topscore)
1806 leaderfrags = WinningConditionHelper_topscore;
1809 if (leaderfrags == limit - 1)
1810 Announce("1fragleft");
1811 else if (leaderfrags == limit - 2)
1812 Announce("2fragsleft");
1813 else if (leaderfrags == limit - 3)
1814 Announce("3fragsleft");
1818 limitreached = FALSE;
1820 if(WinningConditionHelper_topscore >= limit)
1821 limitreached = TRUE;
1824 float leadlimitreached;
1825 leadlimitreached = (WinningConditionHelper_topscore - WinningConditionHelper_secondscore >= leadlimit);
1826 if(cvar("leadlimit_and_fraglimit"))
1827 limitreached = (limitreached && leadlimitreached);
1829 limitreached = (limitreached || leadlimitreached);
1832 return GetWinningCode(
1833 WinningConditionHelper_topscore && limitreached,
1834 WinningConditionHelper_equality
1838 float WinningCondition_Race(float fraglimit)
1849 if(p.race_completed)
1854 wc = WinningCondition_Scores(fraglimit, 0);
1856 // ALWAYS initiate overtime, unless EVERYONE has finished the race!
1857 if(wc == WINNING_YES || wc == WINNING_STARTSUDDENDEATHOVERTIME)
1858 // do NOT support equality when the laps are all raced!
1859 return WINNING_STARTSUDDENDEATHOVERTIME;
1861 return WINNING_NEVER;
1865 void ReadyRestart();
1866 float WinningCondition_QualifyingThenRace(float limit)
1869 wc = WinningCondition_Scores(limit, 0);
1871 // NEVER initiate overtime
1872 if(wc == WINNING_YES || wc == WINNING_STARTSUDDENDEATHOVERTIME)
1880 float WinningCondition_RanOutOfSpawns()
1884 if(have_team_spawns <= 0)
1887 if(!some_spawn_has_been_used)
1890 team1_score = team2_score = team3_score = team4_score = 0;
1892 FOR_EACH_PLAYER(head) if(head.deadflag == DEAD_NO)
1894 if(head.team == COLOR_TEAM1)
1896 else if(head.team == COLOR_TEAM2)
1898 else if(head.team == COLOR_TEAM3)
1900 else if(head.team == COLOR_TEAM4)
1904 for(head = world; (head = find(head, classname, "info_player_deathmatch")) != world; )
1906 if(head.team == COLOR_TEAM1)
1908 else if(head.team == COLOR_TEAM2)
1910 else if(head.team == COLOR_TEAM3)
1912 else if(head.team == COLOR_TEAM4)
1917 if(team1_score + team2_score + team3_score + team4_score == 0)
1919 checkrules_equality = TRUE;
1922 else if(team1_score + team2_score + team3_score + team4_score == 1)
1925 if(team1_score) t = COLOR_TEAM1;
1926 if(team2_score) t = COLOR_TEAM2;
1927 if(team3_score) t = COLOR_TEAM3;
1928 if(team4_score) t = COLOR_TEAM4;
1929 CheckAllowedTeams(world);
1930 for(i = 0; i < MAX_TEAMSCORE; ++i)
1932 if(t != COLOR_TEAM1) if(c1 >= 0) TeamScore_AddToTeam(COLOR_TEAM1, i, -1000);
1933 if(t != COLOR_TEAM2) if(c2 >= 0) TeamScore_AddToTeam(COLOR_TEAM2, i, -1000);
1934 if(t != COLOR_TEAM3) if(c3 >= 0) TeamScore_AddToTeam(COLOR_TEAM3, i, -1000);
1935 if(t != COLOR_TEAM4) if(c4 >= 0) TeamScore_AddToTeam(COLOR_TEAM4, i, -1000);
1938 AddWinners(team, t);
1949 Exit deathmatch games upon conditions
1952 void CheckRules_World()
1964 MapVote_Think should now do that part
1965 if (intermission_running)
1966 if (time >= intermission_exittime + 60)
1968 if(!DoNextMapOverride())
1974 if (gameover) // someone else quit the game already
1976 if(player_count == 0) // Nobody there? Then let's go to the next map
1978 // this will actually check the player count in the next frame
1979 // again, but this shouldn't hurt
1983 timelimit = cvar("timelimit") * 60;
1984 fraglimit = cvar("fraglimit");
1985 leadlimit = cvar("leadlimit");
1987 if(inWarmupStage || time <= game_starttime) // NOTE: this is <= to prevent problems in the very tic where the game starts
1990 timelimit = 0; // timelimit is not made for warmup
1992 fraglimit = 0; // no fraglimit for now
1993 leadlimit = 0; // no leadlimit for now
1997 timelimit = 0; // ONS has its own overtime rule
2001 timelimit += game_starttime;
2003 else if (timelimit < 0)
2013 if(checkrules_suddendeathend)
2015 if(!checkrules_suddendeathwarning)
2017 checkrules_suddendeathwarning = TRUE;
2018 if(g_race && !g_race_qualifying)
2019 bcenterprint("^3Everyone, finish your lap! The race is over!");
2021 bcenterprint("^3Now playing ^1OVERTIME^3!\n\n^3Keep fragging until we have a ^1winner^3!");
2026 if (timelimit && time >= timelimit)
2028 if(g_race && (g_race_qualifying == 2) && timelimit > 0)
2031 float playerswithlaps;
2034 totalplayers = playerswithlaps = readyplayers = 0;
2035 FOR_EACH_PLAYER(head)
2038 if(PlayerScore_Add(head, SP_RACE_FASTEST, 0))
2044 // at least 2 of the players have completed a lap: start the RACE
2045 // otherwise, the players should end the qualifying on their own
2046 if(readyplayers || playerswithlaps >= 2)
2048 checkrules_suddendeathend = 0;
2049 ReadyRestart(); // go to race
2053 wantovertime |= InitiateSuddenDeath();
2056 wantovertime |= InitiateSuddenDeath();
2060 if (checkrules_suddendeathend && time >= checkrules_suddendeathend)
2066 float checkrules_status;
2067 checkrules_status = WinningCondition_RanOutOfSpawns();
2068 if(checkrules_status == WINNING_YES)
2070 bprint("Hey! Someone ran out of spawns!\n");
2072 else if(g_race && !g_race_qualifying && timelimit >= 0)
2074 checkrules_status = WinningCondition_Race(fraglimit);
2075 //print("WC_RACE yields ", ftos(checkrules_status), "\n");
2077 else if(g_race && g_race_qualifying == 2 && timelimit >= 0)
2079 checkrules_status = WinningCondition_QualifyingThenRace(fraglimit);
2080 //print("WC_QUALIFYING_THEN_RACE yields ", ftos(checkrules_status), "\n");
2084 checkrules_status = WinningCondition_Assault(); // TODO remove this?
2088 checkrules_status = WinningCondition_LMS();
2090 else if (g_onslaught)
2092 checkrules_status = WinningCondition_Onslaught(); // TODO remove this?
2096 checkrules_status = WinningCondition_Scores(fraglimit, leadlimit);
2097 //print("WC_SCORES yields ", ftos(checkrules_status), "\n");
2100 if(checkrules_status == WINNING_STARTSUDDENDEATHOVERTIME)
2102 checkrules_status = WINNING_NEVER;
2103 checkrules_overtimesadded = -1;
2104 wantovertime |= InitiateSuddenDeath();
2107 if(checkrules_status == WINNING_NEVER)
2108 // equality cases! Nobody wins if the overtime ends in a draw.
2113 if(checkrules_status == WINNING_NEVER)
2116 checkrules_status = WINNING_YES;
2119 if(checkrules_suddendeathend)
2120 if(checkrules_status != WINNING_NEVER || time >= checkrules_suddendeathend)
2121 checkrules_status = WINNING_YES;
2123 if(checkrules_status == WINNING_YES)
2125 //print("WINNING\n");
2130 float mapvote_nextthink;
2131 float mapvote_initialized;
2132 float mapvote_keeptwotime;
2133 float mapvote_timeout;
2134 string mapvote_message;
2135 #define MAPVOTE_SCREENSHOT_DIRS_COUNT 4
2136 string mapvote_screenshot_dirs[MAPVOTE_SCREENSHOT_DIRS_COUNT];
2137 float mapvote_screenshot_dirs_count;
2139 float mapvote_count;
2140 float mapvote_count_real;
2141 string mapvote_maps[MAPVOTE_COUNT];
2142 float mapvote_maps_screenshot_dir[MAPVOTE_COUNT];
2143 string mapvote_maps_pakfile[MAPVOTE_COUNT];
2144 float mapvote_maps_suggested[MAPVOTE_COUNT];
2145 string mapvote_suggestions[MAPVOTE_COUNT];
2146 float mapvote_suggestion_ptr;
2147 float mapvote_maxlen;
2148 float mapvote_voters;
2149 float mapvote_votes[MAPVOTE_COUNT];
2151 float mapvote_detail;
2152 float mapvote_abstain;
2155 void MapVote_ClearAllVotes()
2157 FOR_EACH_CLIENT(other)
2161 string MapVote_Suggest(string m)
2165 return "That's not how to use this command.";
2166 if(!cvar("g_maplist_votable_suggestions"))
2167 return "Suggestions are not accepted on this server.";
2168 if(mapvote_initialized)
2169 return "Can't suggest - voting is already in progress!";
2170 m = MapInfo_FixName(m);
2172 return "The map you suggested is not available on this server.";
2173 if(!cvar("g_maplist_votable_suggestions_override_mostrecent"))
2175 return "This server does not allow for recent maps to be played again. Please be patient for some rounds.";
2177 if(!MapInfo_CheckMap(m))
2178 return "The map you suggested does not support the current game mode.";
2179 for(i = 0; i < mapvote_suggestion_ptr; ++i)
2180 if(mapvote_suggestions[i] == m)
2181 return "This map was already suggested.";
2182 if(mapvote_suggestion_ptr >= MAPVOTE_COUNT)
2184 i = floor(random() * mapvote_suggestion_ptr);
2188 i = mapvote_suggestion_ptr;
2189 mapvote_suggestion_ptr += 1;
2191 if(mapvote_suggestions[i] != "")
2192 strunzone(mapvote_suggestions[i]);
2193 mapvote_suggestions[i] = strzone(m);
2194 if(cvar("sv_eventlog"))
2195 GameLogEcho(strcat(":vote:suggested:", m, ":", ftos(self.playerid)));
2196 return strcat("Suggestion of ", m, " accepted.");
2199 void MapVote_AddVotable(string nextMap, float isSuggestion)
2202 string pakfile, mapfile;
2206 for(j = 0; j < mapvote_count; ++j)
2207 if(mapvote_maps[j] == nextMap)
2209 if(strlen(nextMap) > mapvote_maxlen)
2210 mapvote_maxlen = strlen(nextMap);
2211 mapvote_maps[mapvote_count] = strzone(nextMap);
2212 mapvote_maps_suggested[mapvote_count] = isSuggestion;
2214 for(i = 0; i < mapvote_screenshot_dirs_count; ++i)
2216 mapfile = strcat(mapvote_screenshot_dirs[i], "/", mapvote_maps[i]);
2217 pakfile = whichpack(strcat(mapfile, ".tga"));
2219 pakfile = whichpack(strcat(mapfile, ".jpg"));
2221 pakfile = whichpack(strcat(mapfile, ".png"));
2225 if(i >= mapvote_screenshot_dirs_count)
2226 i = 0; // FIXME maybe network this error case, as that means there is no mapshot on the server?
2227 for(o = strstr(pakfile, "/", 0)+1; o > 0; o = strstr(pakfile, "/", 0)+1)
2228 pakfile = substring(pakfile, o, -1);
2230 mapvote_maps_screenshot_dir[mapvote_count] = i;
2231 mapvote_maps_pakfile[mapvote_count] = strzone(pakfile);
2236 void MapVote_Spawn();
2242 MapVote_ClearAllVotes();
2245 mapvote_detail = !cvar("g_maplist_votable_nodetail");
2246 mapvote_abstain = cvar("g_maplist_votable_abstain");
2249 nmax = min(MAPVOTE_COUNT - 1, cvar("g_maplist_votable"));
2251 nmax = min(MAPVOTE_COUNT, cvar("g_maplist_votable"));
2252 smax = min3(nmax, cvar("g_maplist_votable_suggestions"), mapvote_suggestion_ptr);
2254 // we need this for AddVotable, as that cycles through the screenshot dirs
2255 mapvote_screenshot_dirs_count = tokenize_console(cvar_string("g_maplist_votable_screenshot_dir"));
2256 if(mapvote_screenshot_dirs_count == 0)
2257 mapvote_screenshot_dirs_count = tokenize_console("maps levelshots");
2258 mapvote_screenshot_dirs_count = min(mapvote_screenshot_dirs_count, MAPVOTE_SCREENSHOT_DIRS_COUNT);
2259 for(i = 0; i < mapvote_screenshot_dirs_count; ++i)
2260 mapvote_screenshot_dirs[i] = strzone(argv(i));
2262 if(mapvote_suggestion_ptr)
2263 for(i = 0; i < 100 && mapvote_count < smax; ++i)
2264 MapVote_AddVotable(mapvote_suggestions[floor(random() * mapvote_suggestion_ptr)], TRUE);
2266 for(i = 0; i < 100 && mapvote_count < nmax; ++i)
2267 MapVote_AddVotable(GetNextMap(), FALSE);
2269 if(mapvote_count == 0)
2271 bprint( "Maplist contains no single playable map! Resetting it to default map list.\n" );
2272 cvar_set("g_maplist", MapInfo_ListAllowedMaps(MapInfo_RequiredFlags(), MapInfo_ForbiddenFlags()));
2273 if(cvar("g_maplist_shuffle"))
2275 localcmd("\nmenu_cmd sync\n");
2276 for(i = 0; i < 100 && mapvote_count < nmax; ++i)
2277 MapVote_AddVotable(GetNextMap(), FALSE);
2280 mapvote_count_real = mapvote_count;
2282 MapVote_AddVotable("don't care", 0);
2284 //dprint("mapvote count is ", ftos(mapvote_count), "\n");
2286 mapvote_keeptwotime = time + cvar("g_maplist_votable_keeptwotime");
2287 mapvote_timeout = time + cvar("g_maplist_votable_timeout");
2288 if(mapvote_count_real < 3 || mapvote_keeptwotime <= time)
2289 mapvote_keeptwotime = 0;
2290 mapvote_message = "Choose a map and press its key!";
2295 void MapVote_SendPicture(float id)
2298 WriteByte(MSG_ONE, SVC_TEMPENTITY);
2299 WriteByte(MSG_ONE, TE_CSQC_PICTURE);
2300 WriteByte(MSG_ONE, id);
2301 WritePicture(MSG_ONE, strcat(mapvote_screenshot_dirs[mapvote_maps_screenshot_dir[id]], "/", mapvote_maps[id]), 3072);
2304 float GameCommand_MapVote(string cmd)
2306 if(!intermission_running)
2309 if(cmd == "mv_getpic")
2311 MapVote_SendPicture(stof(argv(1)));
2318 float MapVote_GetMapMask()
2320 float mask, i, power;
2322 for(i = 0, power = 1; i < mapvote_count; ++i, power *= 2)
2323 if(mapvote_maps[i] != "")
2329 float MapVote_SendEntity(entity to, float sf)
2334 sf &~= 2; // if we send 1, we don't need to also send 2
2336 WriteByte(MSG_ENTITY, ENT_CLIENT_MAPVOTE);
2337 WriteByte(MSG_ENTITY, sf);
2341 // flag 1 == initialization
2342 for(i = 0; i < mapvote_screenshot_dirs_count; ++i)
2343 WriteString(MSG_ENTITY, mapvote_screenshot_dirs[i]);
2344 WriteString(MSG_ENTITY, "");
2345 WriteByte(MSG_ENTITY, mapvote_count);
2346 WriteByte(MSG_ENTITY, mapvote_abstain);
2347 WriteByte(MSG_ENTITY, mapvote_detail);
2348 WriteCoord(MSG_ENTITY, mapvote_timeout);
2349 if(mapvote_count <= 8)
2350 WriteByte(MSG_ENTITY, MapVote_GetMapMask());
2352 WriteShort(MSG_ENTITY, MapVote_GetMapMask());
2353 for(i = 0; i < mapvote_count; ++i)
2354 if(mapvote_maps[i] != "")
2356 if(mapvote_abstain && i == mapvote_count - 1)
2358 WriteString(MSG_ENTITY, ""); // abstain needs no text
2359 WriteString(MSG_ENTITY, ""); // abstain needs no pack
2360 WriteByte(MSG_ENTITY, 0); // abstain needs no screenshot dir
2364 WriteString(MSG_ENTITY, mapvote_maps[i]);
2365 WriteString(MSG_ENTITY, mapvote_maps_pakfile[i]);
2366 WriteByte(MSG_ENTITY, mapvote_maps_screenshot_dir[i]);
2373 // flag 2 == update of mask
2374 if(mapvote_count <= 8)
2375 WriteByte(MSG_ENTITY, MapVote_GetMapMask());
2377 WriteShort(MSG_ENTITY, MapVote_GetMapMask());
2383 for(i = 0; i < mapvote_count; ++i)
2384 if(mapvote_maps[i] != "")
2385 WriteByte(MSG_ENTITY, mapvote_votes[i]);
2387 WriteByte(MSG_ENTITY, to.mapvote);
2393 void MapVote_Spawn()
2395 Net_LinkEntity(mapvote_ent = spawn(), FALSE, 0, MapVote_SendEntity);
2398 void MapVote_TouchMask()
2400 mapvote_ent.SendFlags |= 2;
2403 void MapVote_TouchVotes(entity voter)
2405 mapvote_ent.SendFlags |= 4;
2408 float MapVote_Finished(float mappos)
2414 if(cvar("sv_eventlog"))
2416 result = strcat(":vote:finished:", mapvote_maps[mappos]);
2417 result = strcat(result, ":", ftos(mapvote_votes[mappos]), "::");
2418 didntvote = mapvote_voters;
2419 for(i = 0; i < mapvote_count; ++i)
2420 if(mapvote_maps[i] != "")
2422 didntvote -= mapvote_votes[i];
2425 result = strcat(result, ":", mapvote_maps[i]);
2426 result = strcat(result, ":", ftos(mapvote_votes[i]));
2429 result = strcat(result, ":didn't vote:", ftos(didntvote));
2431 GameLogEcho(result);
2432 if(mapvote_maps_suggested[mappos])
2433 GameLogEcho(strcat(":vote:suggestion_accepted:", mapvote_maps[mappos]));
2436 FOR_EACH_REALCLIENT(other)
2437 FixClientCvars(other);
2439 Map_Goto_SetStr(mapvote_maps[mappos]);
2441 alreadychangedlevel = TRUE;
2444 void MapVote_CheckRules_1()
2448 for(i = 0; i < mapvote_count; ++i) if(mapvote_maps[i] != "")
2450 //dprint("Map ", ftos(i), ": "); dprint(mapvote_maps[i], "\n");
2451 mapvote_votes[i] = 0;
2455 FOR_EACH_REALCLIENT(other)
2460 i = other.mapvote - 1;
2461 //dprint("Player ", other.netname, " vote = ", ftos(other.mapvote - 1), "\n");
2462 mapvote_votes[i] = mapvote_votes[i] + 1;
2467 float MapVote_CheckRules_2()
2470 float firstPlace, secondPlace;
2471 float firstPlaceVotes, secondPlaceVotes;
2472 float mapvote_voters_real;
2475 if(mapvote_count_real == 1)
2476 return MapVote_Finished(0);
2478 mapvote_voters_real = mapvote_voters;
2480 mapvote_voters_real -= mapvote_votes[mapvote_count - 1];
2482 RandomSelection_Init();
2483 for(i = 0; i < mapvote_count_real; ++i) if(mapvote_maps[i] != "")
2484 RandomSelection_Add(world, i, string_null, 1, mapvote_votes[i]);
2485 firstPlace = RandomSelection_chosen_float;
2486 firstPlaceVotes = RandomSelection_best_priority;
2487 //dprint("First place: ", ftos(firstPlace), "\n");
2488 //dprint("First place votes: ", ftos(firstPlaceVotes), "\n");
2490 RandomSelection_Init();
2491 for(i = 0; i < mapvote_count_real; ++i) if(mapvote_maps[i] != "")
2493 RandomSelection_Add(world, i, string_null, 1, mapvote_votes[i]);
2494 secondPlace = RandomSelection_chosen_float;
2495 secondPlaceVotes = RandomSelection_best_priority;
2496 //dprint("Second place: ", ftos(secondPlace), "\n");
2497 //dprint("Second place votes: ", ftos(secondPlaceVotes), "\n");
2499 if(firstPlace == -1)
2500 error("No first place in map vote... WTF?");
2502 if(secondPlace == -1 || time > mapvote_timeout || (mapvote_voters_real - firstPlaceVotes) < firstPlaceVotes)
2503 return MapVote_Finished(firstPlace);
2505 if(mapvote_keeptwotime)
2506 if(time > mapvote_keeptwotime || (mapvote_voters_real - firstPlaceVotes - secondPlaceVotes) < secondPlaceVotes)
2509 MapVote_TouchMask();
2510 mapvote_message = "Now decide between the TOP TWO!";
2511 mapvote_keeptwotime = 0;
2512 result = strcat(":vote:keeptwo:", mapvote_maps[firstPlace]);
2513 result = strcat(result, ":", ftos(firstPlaceVotes));
2514 result = strcat(result, ":", mapvote_maps[secondPlace]);
2515 result = strcat(result, ":", ftos(secondPlaceVotes), "::");
2516 didntvote = mapvote_voters;
2517 for(i = 0; i < mapvote_count; ++i)
2518 if(mapvote_maps[i] != "")
2520 didntvote -= mapvote_votes[i];
2522 if(i != secondPlace)
2524 result = strcat(result, ":", mapvote_maps[i]);
2525 result = strcat(result, ":", ftos(mapvote_votes[i]));
2526 if(i < mapvote_count_real)
2528 strunzone(mapvote_maps[i]);
2529 mapvote_maps[i] = "";
2530 strunzone(mapvote_maps_pakfile[i]);
2531 mapvote_maps_pakfile[i] = "";
2535 result = strcat(result, ":didn't vote:", ftos(didntvote));
2536 if(cvar("sv_eventlog"))
2537 GameLogEcho(result);
2547 keeptwo = mapvote_keeptwotime;
2548 MapVote_CheckRules_1(); // count
2549 if(MapVote_CheckRules_2()) // decide
2553 FOR_EACH_REALCLIENT(other)
2555 // hide scoreboard again
2556 if(other.health != 2342)
2558 other.health = 2342;
2560 if(clienttype(other) == CLIENTTYPE_REAL)
2563 WriteByte(MSG_ONE, SVC_FINALE);
2564 WriteString(MSG_ONE, "");
2568 // clear possibly invalid votes
2569 if(mapvote_maps[other.mapvote - 1] == "")
2571 // use impulses as new vote
2572 if(other.impulse >= 1 && other.impulse <= mapvote_count)
2573 if(mapvote_maps[other.impulse - 1] != "")
2575 other.mapvote = other.impulse;
2576 MapVote_TouchVotes(other);
2584 MapVote_CheckRules_1(); // just count
2586 void MapVote_Start()
2591 MapInfo_Enumerate();
2592 if(MapInfo_FilterGametype(MapInfo_CurrentGametype(), MapInfo_CurrentFeatures(), MapInfo_RequiredFlags(), MapInfo_ForbiddenFlags(), 1))
2595 void MapVote_Think()
2600 if(alreadychangedlevel)
2603 if(time < mapvote_nextthink)
2607 mapvote_nextthink = time + 0.5;
2609 if(!mapvote_initialized)
2611 if(cvar("rescan_pending") == 1)
2613 cvar_set("rescan_pending", "2");
2614 localcmd("fs_rescan\nrescan_pending 3\n");
2617 else if(cvar("rescan_pending") == 2)
2621 else if(cvar("rescan_pending") == 3)
2623 // now build missing mapinfo files
2624 if(!MapInfo_FilterGametype(MapInfo_CurrentGametype(), MapInfo_CurrentFeatures(), MapInfo_RequiredFlags(), MapInfo_ForbiddenFlags(), 1))
2627 // we're done, start the timer
2628 cvar_set("rescan_pending", "0");
2631 mapvote_initialized = TRUE;
2632 if(DoNextMapOverride())
2634 if(!cvar("g_maplist_votable") || player_count <= 0)
2645 string GotoMap(string m)
2647 if(!MapInfo_CheckMap(m))
2648 return "The map you chose is not available on this server.";
2649 cvar_set("nextmap", m);
2650 cvar_set("timelimit", "-1");
2651 if(mapvote_initialized || alreadychangedlevel)
2653 if(DoNextMapOverride())
2654 return "Map switch initiated.";
2656 return "Hm... no. For some reason I like THIS map more.";
2659 return "Map switch will happen after scoreboard.";
2666 FOR_EACH_REALCLIENT(self)
2668 if(self.classname == "spectator")
2670 if(self.enemy.typehitsound)
2671 play2(self, "misc/typehit.wav");
2672 else if(self.enemy.hitsound && self.cvar_cl_hitsound)
2673 play2(self, "misc/hit.wav");
2677 if(self.typehitsound)
2678 play2(self, "misc/typehit.wav");
2679 else if(self.hitsound && self.cvar_cl_hitsound)
2680 play2(self, "misc/hit.wav");
2683 altime = time + frametime * (1 + cvar("g_antilag_nudge"));
2684 // add 1 frametime because after this, engine SV_Physics
2685 // increases time by a frametime and then networks the frame
2686 // add another frametime because client shows everything with
2687 // 1 frame of lag (cl_nolerp 0). The last +1 however should not be
2689 FOR_EACH_CLIENT(self)
2691 self.hitsound = FALSE;
2692 self.typehitsound = FALSE;
2693 antilag_record(self, altime);
2700 * returns TRUE if redirecting
2702 float redirection_timeout;
2703 float redirection_nextthink;
2704 float RedirectionThink()
2706 float clients_found;
2708 if(redirection_target == "")
2711 if(!redirection_timeout)
2713 cvar_set("sv_public", "-2");
2714 redirection_timeout = time + 0.6; // this will only try twice... should be able to keep more clients
2715 if(redirection_target == "self")
2716 bprint("^3SERVER NOTICE:^7 restarting the server\n");
2718 bprint("^3SERVER NOTICE:^7 redirecting everyone to ", redirection_target, "\n");
2721 if(time < redirection_nextthink)
2724 redirection_nextthink = time + 1;
2727 FOR_EACH_REALCLIENT(self)
2729 print("Redirecting: sending connect command to ", self.netname, "\n");
2730 if(redirection_target == "self")
2731 stuffcmd(self, "\ndisconnect; reconnect\n");
2733 stuffcmd(self, strcat("\ndisconnect; connect ", redirection_target, "\n"));
2737 print("Redirecting: ", ftos(clients_found), " clients left.\n");
2739 if(time > redirection_timeout || clients_found == 0)
2740 localcmd("\nwait; wait; wait; quit\n");
2745 void TargetMusic_RestoreGame();
2748 // Loaded from a save game
2749 // some things then break, so let's work around them...
2751 // Progs DB (capture records)
2752 ServerProgsDB = db_load("server.db");
2756 MapInfo_Enumerate();
2757 MapInfo_FilterGametype(MapInfo_CurrentGametype(), MapInfo_CurrentFeatures(), MapInfo_RequiredFlags(), MapInfo_ForbiddenFlags(), 1);
2760 TargetMusic_RestoreGame();
2765 if(gameover > 1) // shutting down already?
2768 gameover = 2; // 2 = server shutting down
2770 if(world_initialized > 0)
2772 world_initialized = 0;
2773 print("Saving persistent data...\n");
2775 if(!cheatcount_total)
2776 db_save(ServerProgsDB, "server.db");
2777 if(cvar("developer"))
2778 db_save(TemporaryDB, "server-temp.db");
2779 CheatShutdown(); // must be after cheatcount check
2780 db_close(ServerProgsDB);
2781 db_close(TemporaryDB);
2783 // tell the bot system the game is ending now
2786 WeaponStats_Shutdown();
2789 else if(world_initialized == 0)
2791 print("NOTE: crashed before even initializing the world, not saving persistent data\n");