1 float SPAWNFLAG_NO_WAYPOINTS_FOR_ITEMS = 1;
2 string redirection_target;
3 float world_initialized;
9 float() DoNextMapOverride;
11 void SetDefaultAlpha()
13 if(cvar("g_running_guns"))
15 default_player_alpha = -1;
16 default_weapon_alpha = +1;
20 default_player_alpha = cvar("g_balance_cloaked_alpha");
21 default_weapon_alpha = default_player_alpha;
25 default_player_alpha = cvar("g_player_alpha");
26 if(default_player_alpha == 0)
27 default_player_alpha = 1;
28 default_weapon_alpha = default_player_alpha;
32 void fteqcc_testbugs()
36 if(!cvar("developer_fteqccbugs"))
39 dprint("*** fteqcc test: checking for bugs...\n");
43 if(sqrt(a) - sqrt(b - a) == 0)
44 dprint("*** fteqcc test: found same-function-twice bug\n");
46 dprint("*** fteqcc test: same-function-twice bug got FINALLY FIXED! HOORAY!\n");
50 world.enemy.cnt += 10;
51 if(world.cnt > 0.2 || world.cnt < -0.2) // don't error out if it's just roundoff errors
52 dprint("*** fteqcc test: found += bug\n");
54 dprint("*** fteqcc test: += bug got FINALLY FIXED! HOORAY!\n");
59 * Takes care of pausing and unpausing the game.
60 * Centerprints the information about an upcoming or active timeout to all active
61 * players. Also plays reminder sounds.
63 void timeoutHandler_Think() {
66 if (timeoutStatus == 1) {
67 if (remainingLeadTime > 0) {
68 //centerprint the information to every player
69 timeStr = getTimeoutText(0);
70 FOR_EACH_REALCLIENT(plr) {
71 if(plr.classname == "player") {
72 centerprint_atprio(plr, CENTERPRIO_SPAM, timeStr);
75 remainingLeadTime -= 1;
76 //think again in 1 second:
77 self.nextthink = time + 1;
82 cvar_set("slowmo", ftos(TIMEOUT_SLOWMO_VALUE));
83 //copy .v_angle to .lastV_angle for every player in order to fix their view during pause (see PlayerPreThink)
84 FOR_EACH_REALPLAYER(plr) {
85 plr.lastV_angle = plr.v_angle;
87 self.nextthink = time;
90 else if (timeoutStatus == 2) {
91 if (remainingTimeoutTime > 0) {
92 timeStr = getTimeoutText(0);
93 FOR_EACH_REALCLIENT(plr) {
94 if(plr.classname == "player") {
95 centerprint_atprio(plr, CENTERPRIO_SPAM, timeStr);
98 if(remainingTimeoutTime == cvar("sv_timeout_resumetime")) { //play a warning sound when only <sv_timeout_resumetime> seconds are left
99 play2all("announcer/robotic/prepareforbattle.wav");
101 remainingTimeoutTime -= 1;
102 self.nextthink = time + TIMEOUT_SLOWMO_VALUE;
105 //unpause the game again
106 remainingTimeoutTime = timeoutStatus = 0;
107 cvar_set("slowmo", ftos(orig_slowmo));
108 //and unlock the fixed view again once there is no timeout active anymore
109 FOR_EACH_REALPLAYER(plr) {
110 plr.fixangle = FALSE;
112 //get rid of the countdown message
113 FOR_EACH_REALCLIENT(plr) {
114 if(plr.classname == "player") {
115 centerprint_atprio(plr, CENTERPRIO_SPAM, "");
123 else if (timeoutStatus == 0) { //if a player called the resumegame command (which set timeoutStatus to 0 already)
124 FOR_EACH_REALCLIENT(plr) {
125 if(plr.classname == "player") {
126 centerprint_atprio(plr, CENTERPRIO_SPAM, "");
138 cvar_set("_sv_init", "0");
139 if(cvar("g_maplist_shuffle"))
141 tokenizebyseparator(cvar_string("g_maplist"), " ");
143 cvar_set("nextmap", argv(0));
146 MapInfo_FilterGametype(MapInfo_CurrentGametype(), MapInfo_CurrentFeatures(), 0, (g_maplist_allow_hidden ? MAPINFO_FLAG_HIDDEN : 0), 0);
148 if(!DoNextMapOverride())
157 void cvar_changes_init()
164 strunzone(cvar_changes);
165 cvar_changes = string_null;
168 buf_cvarlist(h, "", "_"); // exclude all _ cvars as they are temporary
171 for(i = 0; i < n; ++i)
173 k = bufstr_get(h, i);
175 #define BADPREFIX(p) if(substring(k, 0, strlen(p)) == p) continue
176 #define BADCVAR(p) if(k == p) continue
179 BADPREFIX("cvar_check_");
181 BADCVAR("g_configversion");
182 BADCVAR("g_maplist_index");
183 BADCVAR("halflifebsp");
188 BADPREFIX("g_campaign");
192 BADPREFIX("net_slist_");
196 BADPREFIX("userbind");
199 BADPREFIX("crosshair");
200 BADCVAR("mod_q3bsp_lightmapmergepower");
201 BADCVAR("mod_q3bsp_nolightmaps");
205 BADPREFIX("g_chat_flood_");
207 BADPREFIX("settemp_");
208 BADPREFIX("sv_allowdownloads_");
209 BADPREFIX("sv_autodemo");
210 BADPREFIX("sv_curl_");
211 BADPREFIX("sv_eventlog");
212 BADPREFIX("sv_logscores_");
213 BADPREFIX("sv_master");
214 BADCVAR("g_banned_list");
215 BADCVAR("log_dest_udp");
217 BADCVAR("net_address");
219 BADCVAR("savedgamecfg");
220 BADCVAR("sv_heartbeatperoid");
221 BADCVAR("sv_vote_master_password");
222 BADCVAR("sys_colortranslation");
223 BADCVAR("sys_specialcharactertranslation");
224 BADCVAR("timestamps");
227 BADCVAR("timelimit");
228 BADCVAR("fraglimit");
230 BADCVAR("g_assault");
233 BADCVAR("g_domination");
234 BADCVAR("g_keyhunt");
235 BADCVAR("g_keyhunt_teams");
236 BADCVAR("g_onslaught");
238 BADCVAR("g_runematch");
244 BADCVAR("g_maplist");
245 BADCVAR("g_maplist_mostrecent");
251 d = cvar_defstring(k);
254 cvar_changes = strcat(cvar_changes, k, " \"", v, "\" // \"", d, "\"\n");
255 if(strlen(cvar_changes) > 16384)
257 cvar_changes = "// too many settings have been changed to show them here\n";
263 if(cvar_changes == "")
264 cvar_changes = "// this server runs at default settings\n";
266 cvar_changes = strcat("// this server runs at modified settings:\n", cvar_changes);
267 cvar_changes = strzone(cvar_changes);
270 void detect_maptype()
279 o_x += random() * (world.maxs_x - world.mins_x);
280 o_y += random() * (world.maxs_y - world.mins_y);
281 o_z += random() * (world.maxs_z - world.mins_z);
283 tracebox(o, PL_MIN, PL_MAX, o - '0 0 32768', MOVE_WORLDONLY, world);
284 if(trace_fraction == 1)
289 for(i = 0; i < 64; i += 4)
291 tracebox(o, '-1 -1 -1' * i, '1 1 1' * i, o - '0 0 32768', MOVE_WORLDONLY, world);
292 if(trace_fraction == 1)
294 print(ftos(i), " -> ", vtos(trace_endpos), "\n");
303 float RandomSeed_Send(entity to, float sf)
305 WriteByte(MSG_ENTITY, ENT_CLIENT_RANDOMSEED);
306 WriteShort(MSG_ENTITY, self.cnt);
309 void RandomSeed_Think()
311 self.cnt = bound(0, floor(random() * 65536), 65535);
312 self.nextthink = time + 5;
316 void RandomSeed_Spawn()
318 randomseed = spawn();
319 randomseed.think = RandomSeed_Think;
320 Net_LinkEntity(randomseed, FALSE, 0, RandomSeed_Send);
325 self.think(); // sets random seed and nextthink
329 void Map_MarkAsRecent(string m);
330 float world_already_spawned;
331 void RegisterWeapons();
333 void ClientInit_Spawn();
334 void spawnfunc_worldspawn (void)
336 float fd, l, i, j, n;
339 dprint_load(); // load dprint status from cvar
341 if(world_already_spawned)
342 error("world already spawned - you may have EXACTLY ONE worldspawn!");
343 world_already_spawned = TRUE;
345 remove = remove_safely; // during spawning, watch what you remove!
347 if(cvar_string("cvar_check_default") != "bypass")
349 if(cvar_string("cvar_check_default") != CVAR_CHECK_DEFAULT)
350 error("Config file mismatch! Please update defaultNexuiz.cfg to match the QuakeC code!");
352 if(cvar_string("cvar_check_weapons") != CVAR_CHECK_WEAPONS)
353 error("Config file mismatch! Please update weapons.cfg and weaponsPro.cfg to match the QuakeC code!");
356 compressShortVector_init();
359 head = nextent(world);
364 head = nextent(head);
367 // needs to be done so early as they would still spawn
372 world_initialized = -1; // don't complain
377 ServerProgsDB = db_create();
379 ServerProgsDB = db_load("server.db");
381 TemporaryDB = db_create();
384 TODO sound pack system
385 // initialize sound pack system
386 soundpack = cvar_string("g_soundpack");
388 soundpack = strcat(soundpack, "/");
389 soundpack = strzone(soundpack);
395 // 1 FLICKER (first variety)
396 lightstyle(1, "mmnmmommommnonmmonqnmmo");
398 // 2 SLOW STRONG PULSE
399 lightstyle(2, "abcdefghijklmnopqrstuvwxyzyxwvutsrqponmlkjihgfedcba");
401 // 3 CANDLE (first variety)
402 lightstyle(3, "mmmmmaaaaammmmmaaaaaabcdefgabcdefg");
405 lightstyle(4, "mamamamamama");
408 lightstyle(5,"jklmnopqrstuvwxyzyxwvutsrqponmlkj");
410 // 6 FLICKER (second variety)
411 lightstyle(6, "nmonqnmomnmomomno");
413 // 7 CANDLE (second variety)
414 lightstyle(7, "mmmaaaabcdefgmmmmaaaammmaamm");
416 // 8 CANDLE (third variety)
417 lightstyle(8, "mmmaaammmaaammmabcdefaaaammmmabcdefmmmaaaa");
419 // 9 SLOW STROBE (fourth variety)
420 lightstyle(9, "aaaaaaaazzzzzzzz");
422 // 10 FLUORESCENT FLICKER
423 lightstyle(10, "mmamammmmammamamaaamammma");
425 // 11 SLOW PULSE NOT FADE TO BLACK
426 lightstyle(11, "abcdefghijklmnopqrrqponmlkjihgfedcba");
428 // styles 32-62 are assigned by the spawnfunc_light program for switchable lights
433 if(cvar("g_campaign"))
436 Map_MarkAsRecent(mapname);
438 precache_model ("null"); // we need this one before InitGameplayMode
444 bot_waypoints_for_items = cvar("g_waypoints_for_items");
445 if(bot_waypoints_for_items == 1)
446 if(self.spawnflags & SPAWNFLAG_NO_WAYPOINTS_FOR_ITEMS)
447 bot_waypoints_for_items = 0;
449 // for setting by mapinfo
450 q3acompat_machineshotgunswap = cvar("sv_q3acompat_machineshotgunswap");
451 cvar_set("sv_q3acompat_machineshotgunswap", "0");
455 WaypointSprite_Init();
460 GameLogInit(); // prepare everything
461 if(cvar("sv_eventlog"))
463 s = strcat(cvar_string("sv_eventlog_files_counter"), ".");
464 s = strcat(s, ftos(random()));
465 GameLogEcho(strcat(":gamestart:", GetGametype(), "_", GetMapname(), ":", s));
466 s = ":gameinfo:mutators:LIST";
467 if(cvar("g_grappling_hook"))
468 s = strcat(s, ":grappling_hook");
469 if(!cvar("g_use_ammunition"))
470 s = strcat(s, ":no_use_ammunition");
471 if(!cvar("g_pickup_items"))
472 s = strcat(s, ":no_pickup_items");
473 if(cvar("g_instagib"))
474 s = strcat(s, ":instagib");
475 if(cvar_string("g_weaponarena") != "0")
476 s = strcat(s, ":", cvar_string("g_weaponarena"), " arena");
478 s = strcat(s, ":nixnex");
479 if(cvar("g_vampire"))
480 s = strcat(s, ":vampire");
481 if(cvar("g_laserguided_missile"))
482 s = strcat(s, ":laserguided_missile");
483 if(cvar("g_norecoil"))
484 s = strcat(s, ":norecoil");
486 s = strcat(s, ":midair");
487 if(cvar("g_minstagib"))
488 s = strcat(s, ":minstagib");
490 GameLogEcho(":gameinfo:end");
493 cvar_set("nextmap", "");
497 if(cvar("g_campaign"))
504 //initialise globals related to sv_timeout
505 sys_ticrate = cvar("sys_ticrate");
506 orig_slowmo = cvar("slowmo");
509 MapInfo_FilterGametype(MapInfo_CurrentGametype(), MapInfo_CurrentFeatures(), 0, (g_maplist_allow_hidden ? MAPINFO_FLAG_HIDDEN : 0), 1);
511 if(whichpack(strcat("maps/", mapname, ".cfg")) != "")
513 fd = fopen(strcat("maps/", mapname, ".cfg"), FILE_READ);
516 while((s = fgets(fd)))
518 l = tokenize_sane(s);
523 print("Found ^1DEPRECATED^7 cd loop command in .cfg file; put this line in mapinfo instead:\n");
524 print(" cdtrack ", argv(2), "\n");
526 else if(argv(0) == "fog")
528 print("Found ^1DEPRECATED^7 fog command in .cfg file; put this line in worldspawn in the .map/.bsp/.ent file instead:\n");
529 print(" \"fog\" \"", s, "\"\n");
531 else if(argv(0) == "set")
533 print("Found ^1DEPRECATED^7 set command in .cfg file; put this line in mapinfo instead:\n");
534 print(" clientsettemp_for_type all ", argv(1), " ", argv(2), "\n");
536 else if(argv(0) != "//")
538 print("Found ^1DEPRECATED^7 set command in .cfg file; put this line in mapinfo instead:\n");
539 print(" clientsettemp_for_type all ", argv(0), " ", argv(1), "\n");
546 addstat(STAT_SYS_TICRATE, AS_FLOAT, stat_sys_ticrate);
547 addstat(STAT_WEAPONS, AS_INT, weapons);
548 addstat(STAT_SWITCHWEAPON, AS_INT, switchweapon);
549 addstat(STAT_GAMESTARTTIME, AS_FLOAT, stat_game_starttime);
550 addstat(STAT_ALLOW_OLDNEXBEAM, AS_INT, stat_allow_oldnexbeam);
553 addstat(STAT_STRENGTH_FINISHED, AS_FLOAT, strength_finished);
554 addstat(STAT_INVINCIBLE_FINISHED, AS_FLOAT, invincible_finished);
556 addstat(STAT_PRESSED_KEYS, AS_FLOAT, pressedkeys);
558 next_pingtime = time + 5;
559 InitializeEntity(self, cvar_changes_init, INITPRIO_CVARS);
563 lsmaps_reply = "^7Maps available: ";
564 for(i = 0, j = 0; i < MapInfo_count; ++i)
566 if(MapInfo_Get_ByID(i))
567 if not(MapInfo_Map_flags & MAPINFO_FLAG_HIDDEN)
574 lsmaps_reply = strcat(lsmaps_reply, col, MapInfo_Map_bspname, " ");
577 lsmaps_reply = strzone(strcat(lsmaps_reply, "\n"));
579 maplist_reply = "^7Maps in list: ";
580 n = tokenize_sane(cvar_string("g_maplist"));
581 for(i = 0, j = 0; i < n; ++i)
583 if(MapInfo_CheckMap(argv(i)))
589 maplist_reply = strcat(maplist_reply, col, argv(i), " ");
593 maplist_reply = strzone(strcat(maplist_reply, "\n"));
595 records_reply = strzone(getrecords());
600 world_initialized = 1;
603 void spawnfunc_light (void)
605 //makestatic (self); // Who the f___ did that?
609 float TryFile( string pFilename )
612 dprint("TryFile(\"", pFilename, "\")\n");
613 lHandle = fopen( pFilename, FILE_READ );
614 if( lHandle != -1 ) {
624 return GametypeNameFromType(game);
627 string getmapname_stored;
633 float Map_Count, Map_Current;
634 string Map_Current_Name;
636 // NOTE: this now expects the map list to be already tokenize()d and the count in Map_Count
637 float GetMaplistPosition()
643 idx = cvar("g_maplist_index");
650 for(pos = 0; pos < Map_Count; ++pos)
654 // resume normal maplist rotation if current map is not in g_maplist
658 float MapHasRightSize(string map)
661 if(currentbots || cvar("bot_number") || player_count < cvar("minplayers"))
662 if(cvar("g_maplist_check_waypoints"))
664 dprint("checkwp "); dprint(map);
665 fh = fopen(strcat("maps/", map, ".waypoints"), FILE_READ);
668 dprint(": no waypoints\n");
671 dprint(": has waypoints\n");
675 // open map size restriction file
676 dprint("opensize "); dprint(map);
677 fh = fopen(strcat("maps/", map, ".sizes"), FILE_READ);
680 float mapmin, mapmax;
682 mapmin = stof(fgets(fh));
683 mapmax = stof(fgets(fh));
685 if(player_count < mapmin)
687 dprint("not enough\n");
690 if(player_count > mapmax)
692 dprint("too many\n");
695 dprint("right size\n");
698 dprint(": not found\n");
702 string Map_Filename(float position)
704 return strcat("maps/", argv(position), ".bsp");
707 string strwords(string s, float w)
710 for(endpos = 0; w && endpos >= 0; --w)
711 endpos = strstrofs(s, " ", endpos + 1);
715 return substring(s, 0, endpos);
718 float strhasword(string s, string w)
720 return strstrofs(strcat(" ", s, " "), strcat(" ", w, " "), 0) >= 0;
723 void Map_MarkAsRecent(string m)
725 cvar_set("g_maplist_mostrecent", strwords(strcat(m, " ", cvar_string("g_maplist_mostrecent")), max(0, cvar("g_maplist_mostrecent_count"))));
728 float Map_IsRecent(string m)
730 return strhasword(cvar_string("g_maplist_mostrecent"), m);
733 float Map_Check(float position, float pass)
737 map_next = argv(position);
740 if(Map_IsRecent(map_next))
743 filename = Map_Filename(position);
744 if(MapInfo_CheckMap(map_next))
748 if(MapHasRightSize(map_next))
753 dprint( "Couldn't select '", filename, "'..\n" );
758 void Map_Goto_SetStr(string nextmapname)
760 if(getmapname_stored != "")
761 strunzone(getmapname_stored);
762 if(nextmapname == "")
763 getmapname_stored = "";
765 getmapname_stored = strzone(nextmapname);
768 void Map_Goto_SetFloat(float position)
770 cvar_set("g_maplist_index", ftos(position));
771 Map_Goto_SetStr(argv(position));
776 // settings persist, except...
777 if(cvar("g_campaign"))
778 localcmd("\nexec mutator_reset.cfg\n");
779 localcmd("\nsettemp_restore\n");
785 MapInfo_LoadMap(getmapname_stored);
788 // return codes of map selectors:
789 // -1 = temporary failure (that is, try some method that is guaranteed to succeed)
790 // -2 = permanent failure
791 float() MaplistMethod_Iterate = // usual method
795 for(pass = 1; pass <= 2; ++pass)
797 for(i = 1; i < Map_Count; ++i)
800 mapindex = mod(i + Map_Current, Map_Count);
801 if(Map_Check(mapindex, pass))
808 float() MaplistMethod_Repeat = // fallback method
810 if(Map_Check(Map_Current, 2))
815 float() MaplistMethod_Random = // random map selection
821 for(i = 0; i <= imax; ++i)
824 mapindex = mod(Map_Current + floor(random() * (Map_Count - 1) + 1), Map_Count); // any OTHER map
825 if(Map_Check(mapindex, 1))
831 float(float exponent) MaplistMethod_Shuffle = // more clever shuffling
832 // the exponent sets a bias on the map selection:
833 // the higher the exponent, the less likely "shortly repeated" same maps are
835 float i, j, imax, insertpos;
839 for(i = 0; i <= imax; ++i)
843 // now reinsert this at another position
844 insertpos = pow(random(), 1 / exponent); // ]0, 1]
845 insertpos = insertpos * (Map_Count - 1); // ]0, Map_Count - 1]
846 insertpos = ceil(insertpos) + 1; // {2, 3, 4, ..., Map_Count}
847 dprint("SHUFFLE: insert pos = ", ftos(insertpos), "\n");
849 // insert the current map there
851 for(j = 1; j < insertpos; ++j) // i == 1: no loop, will be inserted as first; however, i == 1 has been excluded above
852 newlist = strcat(newlist, " ", argv(j));
853 newlist = strcat(newlist, " ", argv(0)); // now insert the just selected map
854 for(j = insertpos; j < Map_Count; ++j) // i == Map_Count: no loop, has just been inserted as last
855 newlist = strcat(newlist, " ", argv(j));
856 newlist = substring(newlist, 1, strlen(newlist) - 1);
857 cvar_set("g_maplist", newlist);
858 Map_Count = tokenizebyseparator(cvar_string("g_maplist"), " ");
860 // NOTE: the selected map has just been inserted at (insertpos-1)th position
861 Map_Current = insertpos - 1; // this is not really valid, but this way the fallback has a chance of working
862 if(Map_Check(Map_Current, 1))
870 Map_Count = tokenizebyseparator(cvar_string("g_maplist"), " ");
873 bprint( "Maplist is empty! Resetting it to default map list.\n" );
874 cvar_set("g_maplist", MapInfo_ListAllowedMaps(0, MAPINFO_FLAG_HIDDEN));
875 if(cvar("g_maplist_shuffle"))
877 localcmd("\nmenu_cmd sync\n");
878 Map_Count = tokenizebyseparator(cvar_string("g_maplist"), " ");
881 error("empty maplist, cannot select a new map");
882 Map_Current = bound(0, GetMaplistPosition(), Map_Count - 1);
885 strunzone(Map_Current_Name);
886 Map_Current_Name = strzone(argv(Map_Current)); // will be automatically freed on exit thanks to DP
887 // this may or may not be correct, but who cares, in the worst case a map
888 // isn't chosen in the first pass that should have been
899 if(cvar("g_maplist_shuffle") > 0)
900 nextMap = MaplistMethod_Shuffle(cvar("g_maplist_shuffle") + 1);
903 if(cvar("g_maplist_selectrandom"))
904 nextMap = MaplistMethod_Random();
907 nextMap = MaplistMethod_Iterate();
910 nextMap = MaplistMethod_Repeat();
914 Map_Goto_SetFloat(nextMap);
915 return getmapname_stored;
921 float DoNextMapOverride()
923 if(cvar("g_campaign"))
925 CampaignPostIntermission();
926 alreadychangedlevel = TRUE;
929 if(cvar("quit_when_empty"))
931 if(player_count <= currentbots)
934 alreadychangedlevel = TRUE;
938 if(cvar_string("quit_and_redirect") != "")
940 redirection_target = strzone(cvar_string("quit_and_redirect"));
941 alreadychangedlevel = TRUE;
944 if (cvar("samelevel")) // if samelevel is set, stay on same level
946 // 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)
947 //localcmd(strcat("exec \"maps/", mapname, ".mapcfg\"\n"));
948 // so instead just restart the current map using the restart command (DOES NOT WORK PROPERLY WITH exit_cfg STUFF)
949 localcmd("restart\n");
950 //changelevel (mapname);
951 alreadychangedlevel = TRUE;
954 if(cvar_string("nextmap") != "")
955 if(MapInfo_CheckMap(cvar_string("nextmap")))
957 Map_Goto_SetStr(cvar_string("nextmap"));
959 alreadychangedlevel = TRUE;
962 if(cvar("lastlevel"))
965 localcmd("set lastlevel 0\ntogglemenu\n");
966 alreadychangedlevel = TRUE;
974 //local string nextmap;
975 //local float n, nummaps;
977 if (alreadychangedlevel)
979 alreadychangedlevel = TRUE;
985 for(allowReset = 1; allowReset >= 0; --allowReset)
987 nextMap = GetNextMap();
993 bprint( "Maplist contains no single playable map! Resetting it to default map list.\n" );
994 cvar_set("g_maplist", MapInfo_ListAllowedMaps(0, MAPINFO_FLAG_HIDDEN));
995 if(cvar("g_maplist_shuffle"))
997 localcmd("\nmenu_cmd sync\n");
1001 error("Everything is broken - not even the default map list works. Please report this to the developers.");
1013 When the player presses attack or jump, change to the next level
1016 .float autoscreenshot;
1017 void() MapVote_Start;
1018 void() MapVote_Think;
1019 float mapvote_initialized;
1020 void IntermissionThink()
1022 FixIntermissionClient(self);
1024 if(cvar("sv_autoscreenshot"))
1025 if(self.autoscreenshot > 0)
1026 if(time > self.autoscreenshot)
1028 self.autoscreenshot = -1;
1029 if(clienttype(self) == CLIENTTYPE_REAL)
1030 stuffcmd(self, "\nscreenshot\necho \"^5A screenshot has been taken at request of the server.\"\n");
1034 if (time < intermission_exittime)
1037 if(!mapvote_initialized)
1038 if (time < intermission_exittime + 10 && !self.BUTTON_ATCK && !self.BUTTON_JUMP && !self.BUTTON_ATCK2 && !self.BUTTON_HOOK && !self.BUTTON_USE)
1048 Returns the entity to view from
1052 entity FindIntermission()
1057 // look for info_intermission first
1058 spot = find (world, classname, "info_intermission");
1060 { // pick a random one
1064 spot = find (spot, classname, "info_intermission");
1066 spot = find (spot, classname, "info_intermission");
1072 // then look for the start position
1073 spot = find (world, classname, "info_player_start");
1077 // testinfo_player_start is only found in regioned levels
1078 spot = find (world, classname, "testplayerstart");
1082 // then look for the start position
1083 spot = find (world, classname, "info_player_deathmatch");
1087 //objerror ("FindIntermission: no spot");
1093 ===============================================================================
1097 ===============================================================================
1100 void DumpStats(float final)
1104 local float to_console;
1105 local float to_eventlog;
1106 local float to_file;
1109 to_console = cvar("sv_logscores_console");
1110 to_eventlog = cvar("sv_eventlog");
1111 to_file = cvar("sv_logscores_file");
1115 to_console = TRUE; // always print printstats replies
1116 to_eventlog = FALSE; // but never print them to the event log
1120 if(cvar("sv_eventlog_console"))
1121 to_console = FALSE; // otherwise we get the output twice
1127 s = strcat(s, GetGametype(), "_", GetMapname(), ":", ftos(rint(time)));
1135 file = fopen(cvar_string("sv_logscores_filename"), FILE_APPEND);
1139 fputs(file, strcat(s, "\n"));
1142 s = strcat(":labels:player:", GetPlayerScoreString(world, 0));
1148 fputs(file, strcat(s, "\n"));
1150 FOR_EACH_CLIENT(other)
1152 if ((clienttype(other) == CLIENTTYPE_REAL) || (clienttype(other) == CLIENTTYPE_BOT && cvar("sv_logscores_bots")))
1154 s = strcat(":player:see-labels:", GetPlayerScoreString(other, 0), ":");
1155 s = strcat(s, ftos(rint(time - other.jointime)), ":");
1156 if(other.classname == "player" || g_arena || g_lms)
1157 s = strcat(s, ftos(other.team), ":");
1159 s = strcat(s, "spectator:");
1162 print(s, other.netname, "\n");
1164 GameLogEcho(strcat(s, ftos(other.playerid), ":", other.netname));
1166 fputs(file, strcat(s, other.netname, "\n"));
1172 s = strcat(":labels:teamscores:", GetTeamScoreString(0, 0));
1178 fputs(file, strcat(s, "\n"));
1180 for(i = 1; i < 16; ++i)
1182 s = strcat(":teamscores:see-labels:", GetTeamScoreString(i, 0));
1183 s = strcat(s, ":", ftos(i));
1189 fputs(file, strcat(s, "\n"));
1196 GameLogEcho(":end");
1199 fputs(file, ":end\n");
1204 void FixIntermissionClient(entity e)
1207 if(!e.autoscreenshot) // initial call
1209 e.angles = e.v_angle;
1210 e.angles_x = -e.angles_x;
1211 e.autoscreenshot = time + 0.8; // used for autoscreenshot
1213 // first intermission phase; voting phase has positive health (used to decide whether to send SVC_FINALE or not)
1214 e.solid = SOLID_NOT;
1215 e.movetype = MOVETYPE_NONE;
1216 e.takedamage = DAMAGE_NO;
1218 e.weaponentity.effects = EF_NODRAW;
1219 if(clienttype(e) == CLIENTTYPE_REAL)
1221 stuffcmd(e, "\nscr_printspeed 1000000\n");
1222 s = cvar_string("sv_intermission_cdtrack");
1224 stuffcmd(e, strcat("\ncd loop ", s, "\n"));
1226 WriteByte(MSG_ONE, SVC_INTERMISSION);
1230 //e.velocity = '0 0 0';
1231 //e.fixangle = TRUE;
1233 // TODO halt weapon animation
1238 go to the next level for deathmatch
1239 only called if a time or frag limit has expired
1243 float minTotalFrags;
1244 float maxTotalFrags;
1250 intermission_running = 1;
1252 // enforce a wait time before allowing changelevel
1253 if(player_count > 0)
1254 intermission_exittime = time + cvar("sv_mapchange_delay");
1256 intermission_exittime = -1;
1259 WriteByte (MSG_ALL, SVC_CDTRACK);
1260 WriteByte (MSG_ALL, 3);
1261 WriteByte (MSG_ALL, 3);
1262 // done in FixIntermission
1265 //pos = FindIntermission ();
1271 if(cvar("sv_eventlog"))
1272 GameLogEcho(":gameover");
1276 FOR_EACH_CLIENT(other)
1278 FixIntermissionClient(other);
1281 bprint(other.netname, " ^7wins.\n");
1286 FOR_EACH_PLAYER(other)
1288 if(maxTotalFrags < other.totalfrags)
1289 maxTotalFrags = other.totalfrags;
1290 if(minTotalFrags > other.totalfrags)
1291 minTotalFrags = other.totalfrags;
1296 FOR_EACH_PLAYER(other)
1298 score = (other.totalfrags - minTotalFrags) / max(maxTotalFrags - minTotalFrags, 1);
1299 f = bound(0, other.play_time / max(time, 1), 1);
1300 // store some statistics?
1304 if(cvar("g_campaign"))
1305 CampaignPreIntermission();
1307 // WriteByte (MSG_ALL, SVC_INTERMISSION);
1314 Exit deathmatch games upon conditions
1317 void CheckRules_Player()
1319 if (gameover) // someone else quit the game already
1322 if(self.deadflag == DEAD_NO)
1323 self.play_time += frametime;
1325 // fixme: don't check players; instead check spawnfunc_dom_team and spawnfunc_ctf_team entities
1326 // (div0: and that in CheckRules_World please)
1329 float checkrules_oneminutewarning;
1331 float checkrules_equality;
1332 float checkrules_suddendeathwarning;
1333 float checkrules_suddendeathend;
1334 float checkrules_overtimesadded; //how many overtimes have been already added
1335 float checkrules_status;
1337 float WINNING_NO = 0; // no winner, but time limits may terminate the game
1338 float WINNING_YES = 1; // winner found
1339 float WINNING_NEVER = 2; // no winner, enter overtime if time limit is reached
1340 float WINNING_STARTSUDDENDEATHOVERTIME = 3; // no winner, enter suddendeath overtime NOW
1342 void InitiateOvertime()
1344 // Check first whether normal overtimes could be added before initiating suddendeath mode
1345 // - for this timelimit_overtime needs to be >0 of course
1346 // - also check the winning condition calculated in the previous frame and only add normal overtime
1347 // again, if at the point at which timelimit would be extended again, still no winner was found
1348 if ((checkrules_overtimesadded < cvar("timelimit_overtimes")) && cvar("timelimit_overtime") && (checkrules_status == WINNING_NEVER))
1350 ++checkrules_overtimesadded;
1351 //add one more overtime by simply extending the timelimit
1353 tl = cvar("timelimit");
1354 tl += cvar("timelimit_overtime");
1355 cvar_set("timelimit", ftos(tl));
1356 string minutesPlural;
1357 if (cvar("timelimit_overtime") == 1)
1358 minutesPlural = " ^3minute";
1360 minutesPlural = " ^3minutes";
1364 "^3Now playing ^1OVERTIME^3!\n\n^3Added ^1",
1365 ftos(cvar("timelimit_overtime")),
1373 if(!checkrules_suddendeathend)
1374 checkrules_suddendeathend = time + 60 * cvar("timelimit_suddendeath");
1378 float GetWinningCode(float fraglimitreached, float equality)
1381 if(fraglimitreached)
1382 return WINNING_STARTSUDDENDEATHOVERTIME;
1384 return WINNING_NEVER;
1386 if(fraglimitreached)
1392 // set the .winning flag for exactly those players with a given field value
1393 void SetWinners(.float field, float value)
1396 FOR_EACH_PLAYER(head)
1397 head.winning = (head.field == value);
1400 // set the .winning flag for those players with a given field value
1401 void AddWinners(.float field, float value)
1404 FOR_EACH_PLAYER(head)
1405 if(head.field == value)
1409 // clear the .winning flags
1410 void ClearWinners(void)
1413 FOR_EACH_PLAYER(head)
1417 // Onslaught winning condition:
1418 // game terminates if only one team has a working generator (or none)
1419 float WinningCondition_Onslaught()
1422 local float t1, t2, t3, t4;
1424 WinningConditionHelper(); // set worldstatus
1426 // first check if the game has ended
1427 t1 = t2 = t3 = t4 = 0;
1428 head = find(world, classname, "onslaught_generator");
1431 if (head.health > 0)
1433 if (head.team == COLOR_TEAM1) t1 = 1;
1434 if (head.team == COLOR_TEAM2) t2 = 1;
1435 if (head.team == COLOR_TEAM3) t3 = 1;
1436 if (head.team == COLOR_TEAM4) t4 = 1;
1438 head = find(head, classname, "onslaught_generator");
1440 if (t1 + t2 + t3 + t4 < 2)
1442 // game over, only one team remains (or none)
1444 if (t1) SetWinners(team, COLOR_TEAM1);
1445 if (t2) SetWinners(team, COLOR_TEAM2);
1446 if (t3) SetWinners(team, COLOR_TEAM3);
1447 if (t4) SetWinners(team, COLOR_TEAM4);
1448 dprint("Have a winner, ending game.\n");
1452 // Two or more teams remain
1456 float LMS_NewPlayerLives()
1459 fl = cvar("fraglimit");
1463 // first player has left the game for dying too much? Nobody else can get in.
1464 if(lms_lowest_lives < 1)
1467 if(!cvar("g_lms_join_anytime"))
1468 if(lms_lowest_lives < fl - cvar("g_lms_last_join"))
1471 return bound(1, lms_lowest_lives, fl);
1474 // Assault winning condition: If the attackers triggered a round end (by fulfilling all objectives)
1475 // they win. Otherwise the defending team wins once the timelimit passes.
1476 void assault_new_round();
1477 float WinningCondition_Assault()
1481 WinningConditionHelper(); // set worldstatus
1483 status = WINNING_NO;
1484 // as the timelimit has not yet passed just assume the defending team will win
1485 if(assault_attacker_team == COLOR_TEAM1)
1487 SetWinners(team, COLOR_TEAM2);
1491 SetWinners(team, COLOR_TEAM1);
1495 ent = find(world, classname, "target_assault_roundend");
1498 if(ent.winning) // round end has been triggered by attacking team
1500 bprint("ASSAULT: round completed...\n");
1501 SetWinners(team, assault_attacker_team);
1503 TeamScore_AddToTeam(assault_attacker_team, ST_ASSAULT_OBJECTIVES, 666 - TeamScore_AddToTeam(assault_attacker_team, ST_ASSAULT_OBJECTIVES, 0));
1505 if(ent.cnt == 1) // this was the second round
1507 status = WINNING_YES;
1511 local entity oldself;
1514 assault_new_round();
1523 // LMS winning condition: game terminates if and only if there's at most one
1524 // one player who's living lives. Top two scores being equal cancels the time
1526 float WinningCondition_LMS()
1533 have_player = FALSE;
1534 have_players = FALSE;
1535 l = LMS_NewPlayerLives();
1537 head = find(world, classname, "player");
1540 head2 = find(head, classname, "player");
1542 have_players = TRUE;
1546 // we have at least one player
1549 // two or more active players - continue with the game
1553 // exactly one player?
1556 SetWinners(winning, 0); // NOTE: exactly one player is still "player", so this works out
1560 // game still running (that is, nobody got removed from the game by a frag yet)? then continue
1566 // and assign him his first place
1567 PlayerScore_Add(head, SP_LMS_RANK, 1);
1574 // nobody is playing at all...
1577 // wait for players...
1581 // SNAFU (maybe a draw game?)
1583 dprint("No players, ending game.\n");
1588 // When we get here, we have at least two players who are actually LIVING,
1589 // now check if the top two players have equal score.
1590 WinningConditionHelper();
1593 if(WinningConditionHelper_winner)
1594 WinningConditionHelper_winner.winning = TRUE;
1595 if(WinningConditionHelper_equality)
1596 return WINNING_NEVER;
1598 // Top two have different scores? Way to go for our beloved TIMELIMIT!
1602 void ShuffleMaplist()
1610 result = cvar_string("g_maplist");
1611 litems = tokenizebyseparator(result, " ");
1613 for(start = 0; start < litems - 1; ++start)
1617 // select a random item
1618 selected = floor(random() * (litems - start) + start);
1620 // shift this item to the place start
1621 for(i = 0; i < start; ++i)
1622 result = strcat(result, " ", argv(i));
1623 result = strcat(result, " ", argv(selected));
1624 for(i = start; i < litems; ++i)
1626 result = strcat(result, " ", argv(i));
1627 result = substring(result, 1, strlen(result) - 1);
1629 litems = tokenizebyseparator(result, " ");
1631 //dprint(result, "\n");
1634 cvar_set("g_maplist", result);
1638 float WinningCondition_Scores(float limit)
1640 // TODO make everything use THIS winning condition (except LMS)
1641 WinningConditionHelper();
1645 team1_score = TeamScore_GetCompareValue(COLOR_TEAM1);
1646 team2_score = TeamScore_GetCompareValue(COLOR_TEAM2);
1647 team3_score = TeamScore_GetCompareValue(COLOR_TEAM3);
1648 team4_score = TeamScore_GetCompareValue(COLOR_TEAM4);
1652 if(WinningConditionHelper_winner)
1653 WinningConditionHelper_winner.winning = 1;
1654 if(WinningConditionHelper_winnerteam >= 0)
1655 SetWinners(team, WinningConditionHelper_winnerteam);
1657 if(WinningConditionHelper_lowerisbetter)
1659 WinningConditionHelper_topscore = -WinningConditionHelper_topscore;
1663 if(g_dm || g_tdm || g_arena || (g_race && !g_race_qualifying))
1664 // these modes always score in increments of 1, thus this makes sense
1666 if(leaderfrags != WinningConditionHelper_topscore)
1668 leaderfrags = WinningConditionHelper_topscore;
1671 if (leaderfrags == limit - 1)
1672 play2all("announcer/robotic/1fragleft.wav");
1673 else if (leaderfrags == limit - 2)
1674 play2all("announcer/robotic/2fragsleft.wav");
1675 else if (leaderfrags == limit - 3)
1676 play2all("announcer/robotic/3fragsleft.wav");
1680 return GetWinningCode(limit && WinningConditionHelper_topscore && (WinningConditionHelper_topscore >= limit), WinningConditionHelper_equality);
1683 float WinningCondition_Race(float fraglimit)
1687 wc = WinningCondition_Scores(fraglimit);
1689 // ALWAYS initiate overtime, unless EVERYONE has finished the race!
1690 if(wc == WINNING_YES || wc == WINNING_STARTSUDDENDEATHOVERTIME)
1691 // do NOT support equality when the laps are all raced!
1694 if not(p.race_completed)
1695 return WINNING_STARTSUDDENDEATHOVERTIME;
1701 void ReadyRestart();
1702 float WinningCondition_QualifyingThenRace(float limit)
1705 wc = WinningCondition_Scores(limit);
1707 // NEVER initiate overtime
1708 if(wc == WINNING_YES || wc == WINNING_STARTSUDDENDEATHOVERTIME)
1716 float WinningCondition_RanOutOfSpawns()
1720 if(!have_team_spawns)
1723 if(!some_spawn_has_been_used)
1726 team1_score = team2_score = team3_score = team4_score = 0;
1728 FOR_EACH_PLAYER(head) if(head.deadflag == DEAD_NO)
1730 if(head.team == COLOR_TEAM1)
1732 else if(head.team == COLOR_TEAM2)
1734 else if(head.team == COLOR_TEAM3)
1736 else if(head.team == COLOR_TEAM4)
1740 for(head = world; (head = find(head, classname, "info_player_deathmatch")) != world; )
1742 if(head.team == COLOR_TEAM1)
1744 else if(head.team == COLOR_TEAM2)
1746 else if(head.team == COLOR_TEAM3)
1748 else if(head.team == COLOR_TEAM4)
1753 if(team1_score + team2_score + team3_score + team4_score == 0)
1755 checkrules_equality = TRUE;
1758 else if(team1_score + team2_score + team3_score + team4_score == 1)
1761 if(team1_score) t = COLOR_TEAM1;
1762 if(team2_score) t = COLOR_TEAM2;
1763 if(team3_score) t = COLOR_TEAM3;
1764 if(team4_score) t = COLOR_TEAM4;
1765 CheckAllowedTeams(world);
1766 for(i = 0; i < MAX_TEAMSCORE; ++i)
1768 if(t != COLOR_TEAM1) if(c1 >= 0) TeamScore_AddToTeam(COLOR_TEAM1, i, -1000);
1769 if(t != COLOR_TEAM2) if(c2 >= 0) TeamScore_AddToTeam(COLOR_TEAM2, i, -1000);
1770 if(t != COLOR_TEAM3) if(c3 >= 0) TeamScore_AddToTeam(COLOR_TEAM3, i, -1000);
1771 if(t != COLOR_TEAM4) if(c4 >= 0) TeamScore_AddToTeam(COLOR_TEAM4, i, -1000);
1774 AddWinners(team, t);
1785 Exit deathmatch games upon conditions
1788 void CheckRules_World()
1790 local float timelimit;
1791 local float fraglimit;
1799 MapVote_Think should now do that part
1800 if (intermission_running)
1801 if (time >= intermission_exittime + 60)
1803 if(!DoNextMapOverride())
1809 if (gameover) // someone else quit the game already
1811 if(player_count == 0) // Nobody there? Then let's go to the next map
1813 // this will actually check the player count in the next frame
1814 // again, but this shouldn't hurt
1818 timelimit = cvar("timelimit") * 60;
1819 fraglimit = cvar("fraglimit");
1821 if(inWarmupStage || time <= game_starttime) // NOTE: this is <= to prevent problems in the very tic where the game starts
1824 timelimit = 0; // timelimit is not made for warmup
1826 fraglimit = 0; // no fraglimit for now
1831 timelimit += game_starttime;
1833 else if (timelimit < 0)
1840 if(checkrules_suddendeathend)
1842 if(!checkrules_suddendeathwarning)
1844 checkrules_suddendeathwarning = TRUE;
1845 if(g_race && !g_race_qualifying)
1846 bcenterprint("^3Everyone, finish your lap! The race is over!");
1848 bcenterprint("^3Now playing ^1OVERTIME^3!\n\n^3Keep fragging until we have a ^1winner^3!");
1853 if (timelimit && time >= timelimit)
1855 if(g_race && g_race_qualifying == 2 && timelimit > 0)
1858 float playerswithlaps;
1861 totalplayers = playerswithlaps = readyplayers = 0;
1862 FOR_EACH_PLAYER(head)
1865 if(PlayerScore_Add(head, SP_RACE_FASTEST, 0))
1871 // at least 2/3 of the players have completed a lap: start the RACE
1872 // otherwise, the players should end the qualifying on their own
1873 if(readyplayers || ((totalplayers >= 3) && (playerswithlaps * 3 >= totalplayers * 2)))
1875 checkrules_suddendeathend = 0;
1876 ReadyRestart(); // go to race
1886 if (checkrules_suddendeathend && time >= checkrules_suddendeathend)
1892 if (!checkrules_oneminutewarning && timelimit > 0 && time > timelimit - 60)
1894 checkrules_oneminutewarning = TRUE;
1895 play2all("announcer/robotic/1minuteremains.wav");
1898 checkrules_status = WinningCondition_RanOutOfSpawns();
1899 if(checkrules_status == WINNING_YES)
1901 bprint("Hey! Someone ran out of spawns!\n");
1903 else if(g_race && !g_race_qualifying && timelimit >= 0)
1905 checkrules_status = WinningCondition_Race(fraglimit);
1907 else if(g_race && g_race_qualifying == 2 && timelimit >= 0)
1909 checkrules_status = WinningCondition_QualifyingThenRace(fraglimit);
1913 checkrules_status = WinningCondition_Assault(); // TODO remove this?
1917 checkrules_status = WinningCondition_LMS();
1919 else if (g_onslaught)
1921 checkrules_status = WinningCondition_Onslaught(); // TODO remove this?
1925 checkrules_status = WinningCondition_Scores(fraglimit);
1928 if(checkrules_status == WINNING_STARTSUDDENDEATHOVERTIME)
1930 checkrules_status = WINNING_NEVER;
1934 if(checkrules_status == WINNING_NEVER)
1935 // equality cases! Nobody wins if the overtime ends in a draw.
1938 if(checkrules_suddendeathend)
1939 if(checkrules_status != WINNING_NEVER || time >= checkrules_suddendeathend)
1940 checkrules_status = WINNING_YES;
1942 if(checkrules_status == WINNING_YES)
1946 float mapvote_nextthink;
1947 float mapvote_initialized;
1948 float mapvote_keeptwotime;
1949 float mapvote_timeout;
1950 string mapvote_message;
1951 string mapvote_screenshot_dir;
1953 float mapvote_count;
1954 float mapvote_count_real;
1955 string mapvote_maps[MAPVOTE_COUNT];
1956 float mapvote_maps_suggested[MAPVOTE_COUNT];
1957 string mapvote_suggestions[MAPVOTE_COUNT];
1958 float mapvote_suggestion_ptr;
1959 float mapvote_maxlen;
1960 float mapvote_voters;
1961 float mapvote_votes[MAPVOTE_COUNT];
1963 float mapvote_detail;
1964 float mapvote_abstain;
1967 void MapVote_ClearAllVotes()
1969 FOR_EACH_CLIENT(other)
1973 string MapVote_Suggest(string m)
1977 return "That's not how to use this command.";
1978 if(!cvar("g_maplist_votable_suggestions"))
1979 return "Suggestions are not accepted on this server.";
1980 if(mapvote_initialized)
1981 return "Can't suggest - voting is already in progress!";
1982 m = MapInfo_FixName(m);
1984 return "The map you suggested is not available on this server.";
1985 if(!cvar("g_maplist_votable_override_mostrecent"))
1987 return "This server does not allow for recent maps to be played again. Please be patient for some rounds.";
1989 if(!MapInfo_CheckMap(m))
1990 return "The map you suggested does not support the current game mode.";
1991 for(i = 0; i < mapvote_suggestion_ptr; ++i)
1992 if(mapvote_suggestions[i] == m)
1993 return "This map was already suggested.";
1994 if(mapvote_suggestion_ptr >= MAPVOTE_COUNT)
1996 i = floor(random() * mapvote_suggestion_ptr);
2000 i = mapvote_suggestion_ptr;
2001 mapvote_suggestion_ptr += 1;
2003 if(mapvote_suggestions[i] != "")
2004 strunzone(mapvote_suggestions[i]);
2005 mapvote_suggestions[i] = strzone(m);
2006 if(cvar("sv_eventlog"))
2007 GameLogEcho(strcat(":vote:suggested:", m, ":", ftos(self.playerid)));
2008 return strcat("Suggestion of ", m, " accepted.");
2011 void MapVote_AddVotable(string nextMap, float isSuggestion)
2016 for(j = 0; j < mapvote_count; ++j)
2017 if(mapvote_maps[j] == nextMap)
2019 if(strlen(nextMap) > mapvote_maxlen)
2020 mapvote_maxlen = strlen(nextMap);
2021 mapvote_maps[mapvote_count] = strzone(nextMap);
2022 mapvote_maps_suggested[mapvote_count] = isSuggestion;
2026 void MapVote_Spawn();
2032 MapVote_ClearAllVotes();
2035 mapvote_detail = !cvar("g_maplist_votable_nodetail");
2036 mapvote_abstain = cvar("g_maplist_votable_abstain");
2039 nmax = min(MAPVOTE_COUNT - 1, cvar("g_maplist_votable"));
2041 nmax = min(MAPVOTE_COUNT, cvar("g_maplist_votable"));
2042 smax = min3(nmax, cvar("g_maplist_votable_suggestions"), mapvote_suggestion_ptr);
2044 if(mapvote_suggestion_ptr)
2045 for(i = 0; i < 100 && mapvote_count < smax; ++i)
2046 MapVote_AddVotable(mapvote_suggestions[floor(random() * mapvote_suggestion_ptr)], TRUE);
2048 for(i = 0; i < 100 && mapvote_count < nmax; ++i)
2049 MapVote_AddVotable(GetNextMap(), FALSE);
2051 if(mapvote_count == 0)
2053 bprint( "Maplist contains no single playable map! Resetting it to default map list.\n" );
2054 cvar_set("g_maplist", MapInfo_ListAllowedMaps(0, MAPINFO_FLAG_HIDDEN));
2055 if(cvar("g_maplist_shuffle"))
2057 localcmd("\nmenu_cmd sync\n");
2058 for(i = 0; i < 100 && mapvote_count < nmax; ++i)
2059 MapVote_AddVotable(GetNextMap(), FALSE);
2062 mapvote_count_real = mapvote_count;
2064 MapVote_AddVotable("don't care", 0);
2066 //dprint("mapvote count is ", ftos(mapvote_count), "\n");
2068 mapvote_keeptwotime = time + cvar("g_maplist_votable_keeptwotime");
2069 mapvote_timeout = time + cvar("g_maplist_votable_timeout");
2070 if(mapvote_count_real < 3 || mapvote_keeptwotime <= time)
2071 mapvote_keeptwotime = 0;
2072 mapvote_message = "Choose a map and press its key!";
2074 mapvote_screenshot_dir = cvar_string("g_maplist_votable_screenshot_dir");
2075 if(mapvote_screenshot_dir == "")
2076 mapvote_screenshot_dir = "maps";
2077 mapvote_screenshot_dir = strzone(mapvote_screenshot_dir);
2082 void MapVote_SendPicture(float id)
2085 WriteByte(MSG_ONE, SVC_TEMPENTITY);
2086 WriteByte(MSG_ONE, TE_CSQC_PICTURE);
2087 WriteByte(MSG_ONE, id);
2088 WritePicture(MSG_ONE, strcat(mapvote_screenshot_dir, "/", mapvote_maps[id]), 3072);
2091 float GameCommand_MapVote(string cmd)
2093 if(!intermission_running)
2096 if(cmd == "mv_getpic")
2098 MapVote_SendPicture(stof(argv(1)));
2105 float MapVote_GetMapMask()
2107 float mask, i, power;
2109 for(i = 0, power = 1; i < mapvote_count; ++i, power *= 2)
2110 if(mapvote_maps[i] != "")
2116 float MapVote_SendEntity(entity to, float sf)
2118 string mapfile, pakfile;
2121 WriteByte(MSG_ENTITY, ENT_CLIENT_MAPVOTE);
2122 WriteByte(MSG_ENTITY, sf);
2126 // flag 1 == initialization
2127 WriteString(MSG_ENTITY, mapvote_screenshot_dir);
2128 WriteByte(MSG_ENTITY, mapvote_count);
2129 WriteByte(MSG_ENTITY, mapvote_abstain);
2130 WriteByte(MSG_ENTITY, mapvote_detail);
2131 WriteCoord(MSG_ENTITY, mapvote_timeout);
2132 if(mapvote_count <= 8)
2133 WriteByte(MSG_ENTITY, MapVote_GetMapMask());
2135 WriteShort(MSG_ENTITY, MapVote_GetMapMask());
2136 for(i = 0; i < mapvote_count; ++i)
2137 if(mapvote_maps[i] != "")
2139 WriteString(MSG_ENTITY, mapvote_maps[i]);
2140 mapfile = strcat(mapvote_screenshot_dir, "/", mapvote_maps[i]);
2141 pakfile = whichpack(strcat(mapfile, ".tga"));
2143 pakfile = whichpack(strcat(mapfile, ".jpg"));
2145 pakfile = whichpack(strcat(mapfile, ".png"));
2146 for(o = strstr(pakfile, "/", 0)+1; o > 0; o = strstr(pakfile, "/", 0)+1)
2147 pakfile = substring(pakfile, o, 999);
2148 WriteString(MSG_ENTITY, pakfile);
2154 // flag 2 == update of mask
2155 if(mapvote_count <= 8)
2156 WriteByte(MSG_ENTITY, MapVote_GetMapMask());
2158 WriteShort(MSG_ENTITY, MapVote_GetMapMask());
2164 for(i = 0; i < mapvote_count; ++i)
2165 if(mapvote_maps[i] != "")
2166 WriteByte(MSG_ENTITY, mapvote_votes[i]);
2168 WriteByte(MSG_ENTITY, to.mapvote);
2174 void MapVote_Spawn()
2176 Net_LinkEntity(mapvote_ent = spawn(), FALSE, 0, MapVote_SendEntity);
2179 void MapVote_TouchMask()
2181 mapvote_ent.SendFlags |= 2;
2184 void MapVote_TouchVotes(entity voter)
2186 mapvote_ent.SendFlags |= 4;
2189 float MapVote_Finished(float mappos)
2195 if(cvar("sv_eventlog"))
2197 result = strcat(":vote:finished:", mapvote_maps[mappos]);
2198 result = strcat(result, ":", ftos(mapvote_votes[mappos]), "::");
2199 didntvote = mapvote_voters;
2200 for(i = 0; i < mapvote_count; ++i)
2201 if(mapvote_maps[i] != "")
2203 didntvote -= mapvote_votes[i];
2206 result = strcat(result, ":", mapvote_maps[i]);
2207 result = strcat(result, ":", ftos(mapvote_votes[i]));
2210 result = strcat(result, ":didn't vote:", ftos(didntvote));
2212 GameLogEcho(result);
2213 if(mapvote_maps_suggested[mappos])
2214 GameLogEcho(strcat(":vote:suggestion_accepted:", mapvote_maps[mappos]));
2217 FOR_EACH_REALCLIENT(other)
2218 FixClientCvars(other);
2220 Map_Goto_SetStr(mapvote_maps[mappos]);
2222 alreadychangedlevel = TRUE;
2225 void MapVote_CheckRules_1()
2229 for(i = 0; i < mapvote_count; ++i) if(mapvote_maps[i] != "")
2231 //dprint("Map ", ftos(i), ": "); dprint(mapvote_maps[i], "\n");
2232 mapvote_votes[i] = 0;
2236 FOR_EACH_REALCLIENT(other)
2241 i = other.mapvote - 1;
2242 //dprint("Player ", other.netname, " vote = ", ftos(other.mapvote - 1), "\n");
2243 mapvote_votes[i] = mapvote_votes[i] + 1;
2248 float MapVote_CheckRules_2()
2251 float firstPlace, secondPlace;
2252 float firstPlaceVotes, secondPlaceVotes;
2253 float mapvote_voters_real;
2256 mapvote_voters_real = mapvote_voters;
2258 mapvote_voters_real -= mapvote_votes[mapvote_count - 1];
2260 RandomSelection_Init();
2261 for(i = 0; i < mapvote_count_real; ++i) if(mapvote_maps[i] != "")
2262 RandomSelection_Add(world, i, 1, mapvote_votes[i]);
2263 firstPlace = RandomSelection_chosen_float;
2264 firstPlaceVotes = RandomSelection_best_priority;
2265 //dprint("First place: ", ftos(firstPlace), "\n");
2266 //dprint("First place votes: ", ftos(firstPlaceVotes), "\n");
2268 RandomSelection_Init();
2269 for(i = 0; i < mapvote_count_real; ++i) if(mapvote_maps[i] != "")
2271 RandomSelection_Add(world, i, 1, mapvote_votes[i]);
2272 secondPlace = RandomSelection_chosen_float;
2273 secondPlaceVotes = RandomSelection_best_priority;
2274 //dprint("Second place: ", ftos(secondPlace), "\n");
2275 //dprint("Second place votes: ", ftos(secondPlaceVotes), "\n");
2277 if(firstPlace == -1)
2278 error("No first place in map vote... WTF?");
2280 if(secondPlace == -1 || time > mapvote_timeout || (mapvote_voters_real - firstPlaceVotes) < firstPlaceVotes)
2281 return MapVote_Finished(firstPlace);
2283 if(mapvote_keeptwotime)
2284 if(time > mapvote_keeptwotime || (mapvote_voters_real - firstPlaceVotes - secondPlaceVotes) < secondPlaceVotes)
2287 MapVote_TouchMask();
2288 mapvote_message = "Now decide between the TOP TWO!";
2289 mapvote_keeptwotime = 0;
2290 result = strcat(":vote:keeptwo:", mapvote_maps[firstPlace]);
2291 result = strcat(result, ":", ftos(firstPlaceVotes));
2292 result = strcat(result, ":", mapvote_maps[secondPlace]);
2293 result = strcat(result, ":", ftos(secondPlaceVotes), "::");
2294 didntvote = mapvote_voters;
2295 for(i = 0; i < mapvote_count; ++i)
2296 if(mapvote_maps[i] != "")
2298 didntvote -= mapvote_votes[i];
2300 if(i != secondPlace)
2302 result = strcat(result, ":", mapvote_maps[i]);
2303 result = strcat(result, ":", ftos(mapvote_votes[i]));
2304 if(i < mapvote_count_real)
2306 strunzone(mapvote_maps[i]);
2307 mapvote_maps[i] = "";
2311 result = strcat(result, ":didn't vote:", ftos(didntvote));
2312 if(cvar("sv_eventlog"))
2313 GameLogEcho(result);
2323 keeptwo = mapvote_keeptwotime;
2324 MapVote_CheckRules_1(); // count
2325 if(MapVote_CheckRules_2()) // decide
2329 FOR_EACH_REALCLIENT(other)
2331 // hide scoreboard again
2332 if(other.health != 2342)
2334 other.health = 2342;
2336 if(clienttype(other) == CLIENTTYPE_REAL)
2339 WriteByte(MSG_ONE, SVC_FINALE);
2340 WriteString(MSG_ONE, "");
2344 // notify about keep-two
2345 if(keeptwo != 0 && mapvote_keeptwotime == 0)
2346 play2(other, "misc/invshot.wav");
2348 // clear possibly invalid votes
2349 if(mapvote_maps[other.mapvote - 1] == "")
2351 // use impulses as new vote
2352 if(other.impulse >= 1 && other.impulse <= mapvote_count)
2353 if(mapvote_maps[other.impulse - 1] != "")
2355 other.mapvote = other.impulse;
2356 MapVote_TouchVotes(other);
2364 MapVote_CheckRules_1(); // just count
2366 void MapVote_Start()
2371 MapInfo_Enumerate();
2372 if(MapInfo_FilterGametype(MapInfo_CurrentGametype(), MapInfo_CurrentFeatures(), 0, (g_maplist_allow_hidden ? MAPINFO_FLAG_HIDDEN : 0), 1))
2375 void MapVote_Think()
2380 if(alreadychangedlevel)
2383 if(time < mapvote_nextthink)
2387 mapvote_nextthink = time + 0.5;
2389 if(!mapvote_initialized)
2391 mapvote_initialized = TRUE;
2392 if(DoNextMapOverride())
2394 if(!cvar("g_maplist_votable") || player_count <= 0)
2405 string GotoMap(string m)
2407 if(!MapInfo_CheckMap(m))
2408 return "The map you chose is not available on this server.";
2409 cvar_set("nextmap", m);
2410 cvar_set("timelimit", "-1");
2411 if(mapvote_initialized || alreadychangedlevel)
2413 if(DoNextMapOverride())
2414 return "Map switch initiated.";
2416 return "Hm... no. For some reason I like THIS map more.";
2419 return "Map switch will happen after scoreboard.";
2425 FOR_EACH_REALCLIENT(self)
2427 if(self.classname == "spectator")
2429 if(self.enemy.typehitsound)
2430 play2(self, "misc/typehit.wav");
2431 else if(self.enemy.hitsound && self.cvar_cl_hitsound)
2432 play2(self, "misc/hit.wav");
2436 if(self.typehitsound)
2437 play2(self, "misc/typehit.wav");
2438 else if(self.hitsound && self.cvar_cl_hitsound)
2439 play2(self, "misc/hit.wav");
2442 FOR_EACH_CLIENT(self)
2444 self.hitsound = FALSE;
2445 self.typehitsound = FALSE;
2452 * returns TRUE if redirecting
2454 float redirection_timeout;
2455 float redirection_nextthink;
2456 float RedirectionThink()
2458 float clients_found;
2460 if(redirection_target == "")
2463 if(!redirection_timeout)
2465 cvar_set("sv_public", "-2");
2466 redirection_timeout = time + 0.6; // this will only try twice... should be able to keep more clients
2467 if(redirection_target == "self")
2468 bprint("^3SERVER NOTICE:^7 restarting the server\n");
2470 bprint("^3SERVER NOTICE:^7 redirecting everyone to ", redirection_target, "\n");
2473 if(time < redirection_nextthink)
2476 redirection_nextthink = time + 1;
2479 FOR_EACH_REALCLIENT(self)
2481 print("Redirecting: sending connect command to ", self.netname, "\n");
2482 if(redirection_target == "self")
2483 stuffcmd(self, "\ndisconnect; reconnect\n");
2485 stuffcmd(self, strcat("\ndisconnect; connect ", redirection_target, "\n"));
2489 print("Redirecting: ", ftos(clients_found), " clients left.\n");
2491 if(time > redirection_timeout || clients_found == 0)
2492 localcmd("\nwait; wait; wait; quit\n");
2499 // Loaded from a save game
2500 // some things then break, so let's work around them...
2502 // Progs DB (capture records)
2504 ServerProgsDB = db_create();
2506 ServerProgsDB = db_load("server.db");
2510 MapInfo_Enumerate();
2511 MapInfo_FilterGametype(MapInfo_CurrentGametype(), MapInfo_CurrentFeatures(), 0, (g_maplist_allow_hidden ? MAPINFO_FLAG_HIDDEN : 0), 1);
2516 if(world_initialized > 0)
2518 world_initialized = 0;
2519 print("Saving persistent data...\n");
2522 db_save(ServerProgsDB, "server.db");
2523 if(cvar("developer"))
2524 db_save(TemporaryDB, "server-temp.db");
2525 db_close(ServerProgsDB);
2526 db_close(TemporaryDB);
2528 // tell the bot system the game is ending now
2533 else if(world_initialized == 0)
2535 print("NOTE: crashed before even initializing the world, not saving persistent data\n");