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 BADCVAR("mod_q3bsp_lightmapmergepower");
200 BADCVAR("mod_q3bsp_nolightmaps");
204 BADPREFIX("g_chat_flood_");
206 BADPREFIX("settemp_");
207 BADPREFIX("sv_allowdownloads_");
208 BADPREFIX("sv_autodemo");
209 BADPREFIX("sv_curl_");
210 BADPREFIX("sv_eventlog");
211 BADPREFIX("sv_logscores_");
212 BADPREFIX("sv_master");
213 BADCVAR("g_banned_list");
214 BADCVAR("log_dest_udp");
216 BADCVAR("net_address");
218 BADCVAR("savedgamecfg");
219 BADCVAR("sv_heartbeatperoid");
220 BADCVAR("sv_vote_master_password");
221 BADCVAR("sys_colortranslation");
222 BADCVAR("sys_specialcharactertranslation");
223 BADCVAR("timestamps");
226 BADCVAR("timelimit");
227 BADCVAR("fraglimit");
229 BADCVAR("g_assault");
232 BADCVAR("g_domination");
233 BADCVAR("g_keyhunt");
234 BADCVAR("g_keyhunt_teams");
235 BADCVAR("g_onslaught");
237 BADCVAR("g_runematch");
243 BADCVAR("g_maplist");
244 BADCVAR("g_maplist_mostrecent");
250 d = cvar_defstring(k);
253 cvar_changes = strcat(cvar_changes, k, " \"", v, "\" // \"", d, "\"\n");
254 if(strlen(cvar_changes) > 16384)
256 cvar_changes = "// too many settings have been changed to show them here\n";
262 if(cvar_changes == "")
263 cvar_changes = "// this server runs at default settings\n";
265 cvar_changes = strcat("// this server runs at modified settings:\n", cvar_changes);
266 cvar_changes = strzone(cvar_changes);
269 void detect_maptype()
278 o_x += random() * (world.maxs_x - world.mins_x);
279 o_y += random() * (world.maxs_y - world.mins_y);
280 o_z += random() * (world.maxs_z - world.mins_z);
282 tracebox(o, PL_MIN, PL_MAX, o - '0 0 32768', MOVE_WORLDONLY, world);
283 if(trace_fraction == 1)
288 for(i = 0; i < 64; i += 4)
290 tracebox(o, '-1 -1 -1' * i, '1 1 1' * i, o - '0 0 32768', MOVE_WORLDONLY, world);
291 if(trace_fraction == 1)
293 print(ftos(i), " -> ", vtos(trace_endpos), "\n");
302 float RandomSeed_Send(entity to, float sf)
304 WriteByte(MSG_ENTITY, ENT_CLIENT_RANDOMSEED);
305 WriteShort(MSG_ENTITY, self.cnt);
308 void RandomSeed_Think()
310 self.cnt = bound(0, floor(random() * 65536), 65535);
311 self.nextthink = time + 5;
315 void RandomSeed_Spawn()
317 randomseed = spawn();
318 randomseed.think = RandomSeed_Think;
319 Net_LinkEntity(randomseed, FALSE, 0, RandomSeed_Send);
324 self.think(); // sets random seed and nextthink
328 float world_already_spawned;
329 void RegisterWeapons();
331 void ClientInit_Spawn();
332 void spawnfunc_worldspawn (void)
334 float fd, l, i, j, n;
337 dprint_load(); // load dprint status from cvar
339 if(world_already_spawned)
340 error("world already spawned - you may have EXACTLY ONE worldspawn!");
341 world_already_spawned = TRUE;
343 remove = remove_safely; // during spawning, watch what you remove!
345 if(cvar_string("cvar_check_default") != "bypass")
347 if(cvar_string("cvar_check_default") != CVAR_CHECK_DEFAULT)
348 error("Config file mismatch! Please update defaultNexuiz.cfg to match the QuakeC code!");
350 if(cvar_string("cvar_check_weapons") != CVAR_CHECK_WEAPONS)
351 error("Config file mismatch! Please update weapons.cfg and weaponsPro.cfg to match the QuakeC code!");
354 compressShortVector_init();
357 head = nextent(world);
362 head = nextent(head);
365 // needs to be done so early as they would still spawn
370 world_initialized = -1; // don't complain
375 ServerProgsDB = db_create();
377 ServerProgsDB = db_load("server.db");
379 TemporaryDB = db_create();
382 TODO sound pack system
383 // initialize sound pack system
384 soundpack = cvar_string("g_soundpack");
386 soundpack = strcat(soundpack, "/");
387 soundpack = strzone(soundpack);
393 // 1 FLICKER (first variety)
394 lightstyle(1, "mmnmmommommnonmmonqnmmo");
396 // 2 SLOW STRONG PULSE
397 lightstyle(2, "abcdefghijklmnopqrstuvwxyzyxwvutsrqponmlkjihgfedcba");
399 // 3 CANDLE (first variety)
400 lightstyle(3, "mmmmmaaaaammmmmaaaaaabcdefgabcdefg");
403 lightstyle(4, "mamamamamama");
406 lightstyle(5,"jklmnopqrstuvwxyzyxwvutsrqponmlkj");
408 // 6 FLICKER (second variety)
409 lightstyle(6, "nmonqnmomnmomomno");
411 // 7 CANDLE (second variety)
412 lightstyle(7, "mmmaaaabcdefgmmmmaaaammmaamm");
414 // 8 CANDLE (third variety)
415 lightstyle(8, "mmmaaammmaaammmabcdefaaaammmmabcdefmmmaaaa");
417 // 9 SLOW STROBE (fourth variety)
418 lightstyle(9, "aaaaaaaazzzzzzzz");
420 // 10 FLUORESCENT FLICKER
421 lightstyle(10, "mmamammmmammamamaaamammma");
423 // 11 SLOW PULSE NOT FADE TO BLACK
424 lightstyle(11, "abcdefghijklmnopqrrqponmlkjihgfedcba");
426 // styles 32-62 are assigned by the spawnfunc_light program for switchable lights
431 if(cvar("g_campaign"))
439 bot_waypoints_for_items = cvar("g_waypoints_for_items");
440 if(bot_waypoints_for_items == 1)
441 if(self.spawnflags & SPAWNFLAG_NO_WAYPOINTS_FOR_ITEMS)
442 bot_waypoints_for_items = 0;
444 // for setting by mapinfo
445 q3acompat_machineshotgunswap = cvar("sv_q3acompat_machineshotgunswap");
446 cvar_set("sv_q3acompat_machineshotgunswap", "0");
450 WaypointSprite_Init();
455 GameLogInit(); // prepare everything
456 if(cvar("sv_eventlog"))
458 s = strcat(cvar_string("sv_eventlog_files_counter"), ".");
459 s = strcat(s, ftos(random()));
460 GameLogEcho(strcat(":gamestart:", GetGametype(), "_", GetMapname(), ":", s));
461 s = ":gameinfo:mutators:LIST";
462 if(cvar("g_grappling_hook"))
463 s = strcat(s, ":grappling_hook");
464 if(!cvar("g_use_ammunition"))
465 s = strcat(s, ":no_use_ammunition");
466 if(!cvar("g_pickup_items"))
467 s = strcat(s, ":no_pickup_items");
468 if(cvar("g_instagib"))
469 s = strcat(s, ":instagib");
470 if(cvar_string("g_weaponarena") != "0")
471 s = strcat(s, ":", cvar_string("g_weaponarena"), " arena");
473 s = strcat(s, ":nixnex");
474 if(cvar("g_vampire"))
475 s = strcat(s, ":vampire");
476 if(cvar("g_laserguided_missile"))
477 s = strcat(s, ":laserguided_missile");
478 if(cvar("g_norecoil"))
479 s = strcat(s, ":norecoil");
481 s = strcat(s, ":midair");
482 if(cvar("g_minstagib"))
483 s = strcat(s, ":minstagib");
485 GameLogEcho(":gameinfo:end");
488 cvar_set("nextmap", "");
492 if(cvar("g_campaign"))
499 //initialise globals related to sv_timeout
500 sys_ticrate = cvar("sys_ticrate");
501 orig_slowmo = cvar("slowmo");
504 MapInfo_FilterGametype(MapInfo_CurrentGametype(), MapInfo_CurrentFeatures(), 0, (g_maplist_allow_hidden ? MAPINFO_FLAG_HIDDEN : 0), 1);
506 if(whichpack(strcat("maps/", mapname, ".cfg")) != "")
508 fd = fopen(strcat("maps/", mapname, ".cfg"), FILE_READ);
511 while((s = fgets(fd)))
513 l = tokenize_sane(s);
518 print("Found ^1DEPRECATED^7 cd loop command in .cfg file; put this line in mapinfo instead:\n");
519 print(" cdtrack ", argv(2), "\n");
521 else if(argv(0) == "fog")
523 print("Found ^1DEPRECATED^7 fog command in .cfg file; put this line in worldspawn in the .map/.bsp/.ent file instead:\n");
524 print(" \"fog\" \"", s, "\"\n");
526 else if(argv(0) == "set")
528 print("Found ^1DEPRECATED^7 set command in .cfg file; put this line in mapinfo instead:\n");
529 print(" clientsettemp_for_type all ", argv(1), " ", argv(2), "\n");
531 else if(argv(0) != "//")
533 print("Found ^1DEPRECATED^7 set command in .cfg file; put this line in mapinfo instead:\n");
534 print(" clientsettemp_for_type all ", argv(0), " ", argv(1), "\n");
541 addstat(STAT_SYS_TICRATE, AS_FLOAT, stat_sys_ticrate);
542 addstat(STAT_WEAPONS, AS_INT, weapons);
543 addstat(STAT_SWITCHWEAPON, AS_INT, switchweapon);
544 addstat(STAT_GAMESTARTTIME, AS_FLOAT, stat_game_starttime);
547 addstat(STAT_STRENGTH_FINISHED, AS_FLOAT, strength_finished);
548 addstat(STAT_INVINCIBLE_FINISHED, AS_FLOAT, invincible_finished);
550 next_pingtime = time + 5;
551 InitializeEntity(self, cvar_changes_init, INITPRIO_CVARS);
555 lsmaps_reply = "^7Maps available: ";
556 for(i = 0, j = 0; i < MapInfo_count; ++i)
558 if(MapInfo_Get_ByID(i))
559 if not(MapInfo_Map_flags & MAPINFO_FLAG_HIDDEN)
566 lsmaps_reply = strcat(lsmaps_reply, col, MapInfo_Map_bspname, " ");
569 lsmaps_reply = strzone(strcat(lsmaps_reply, "\n"));
571 maplist_reply = "^7Maps in list: ";
572 n = tokenize_sane(cvar_string("g_maplist"));
573 for(i = 0, j = 0; i < n; ++i)
575 if(MapInfo_CheckMap(argv(i)))
581 maplist_reply = strcat(maplist_reply, col, argv(i), " ");
585 maplist_reply = strzone(strcat(maplist_reply, "\n"));
587 records_reply = strzone(getrecords());
592 world_initialized = 1;
595 void spawnfunc_light (void)
597 //makestatic (self); // Who the f___ did that?
601 float TryFile( string pFilename )
604 dprint("TryFile(\"", pFilename, "\")\n");
605 lHandle = fopen( pFilename, FILE_READ );
606 if( lHandle != -1 ) {
616 return GametypeNameFromType(game);
619 string getmapname_stored;
625 float Map_Count, Map_Current;
626 string Map_Current_Name;
628 // NOTE: this now expects the map list to be already tokenize()d and the count in Map_Count
629 float GetMaplistPosition()
635 idx = cvar("g_maplist_index");
642 for(pos = 0; pos < Map_Count; ++pos)
646 // resume normal maplist rotation if current map is not in g_maplist
650 float MapHasRightSize(string map)
653 if(currentbots || cvar("bot_number") || player_count < cvar("minplayers"))
654 if(cvar("g_maplist_check_waypoints"))
656 dprint("checkwp "); dprint(map);
657 fh = fopen(strcat("maps/", map, ".waypoints"), FILE_READ);
660 dprint(": no waypoints\n");
663 dprint(": has waypoints\n");
667 // open map size restriction file
668 dprint("opensize "); dprint(map);
669 fh = fopen(strcat("maps/", map, ".sizes"), FILE_READ);
672 float mapmin, mapmax;
674 mapmin = stof(fgets(fh));
675 mapmax = stof(fgets(fh));
677 if(player_count < mapmin)
679 dprint("not enough\n");
682 if(player_count > mapmax)
684 dprint("too many\n");
687 dprint("right size\n");
690 dprint(": not found\n");
694 string Map_Filename(float position)
696 return strcat("maps/", argv(position), ".bsp");
699 string strwords(string s, float w)
702 for(endpos = 0; w && endpos >= 0; --w)
703 endpos = strstrofs(s, " ", endpos + 1);
707 return substring(s, 0, endpos);
710 float strhasword(string s, string w)
712 return strstrofs(strcat(" ", s, " "), strcat(" ", w, " "), 0) >= 0;
715 void Map_MarkAsRecent(string m)
717 cvar_set("g_maplist_mostrecent", strwords(strcat(m, " ", cvar_string("g_maplist_mostrecent")), cvar("g_maplist_mostrecent_count")));
720 float Map_IsRecent(string m)
722 return strhasword(cvar_string("g_maplist_mostrecent"), m);
725 float Map_Check(float position, float pass)
729 map_next = argv(position);
732 if(map_next == Map_Current_Name) // same map again in first pass?
734 if(Map_IsRecent(map_next))
737 filename = Map_Filename(position);
738 if(MapInfo_CheckMap(map_next))
742 if(MapHasRightSize(map_next))
747 dprint( "Couldn't select '", filename, "'..\n" );
752 void Map_Goto_SetStr(string nextmapname)
754 if(getmapname_stored != "")
755 strunzone(getmapname_stored);
756 if(nextmapname == "")
757 getmapname_stored = "";
759 getmapname_stored = strzone(nextmapname);
762 void Map_Goto_SetFloat(float position)
764 cvar_set("g_maplist_index", ftos(position));
765 Map_Goto_SetStr(argv(position));
770 // settings persist, except...
771 if(cvar("g_campaign"))
772 localcmd("\nexec mutator_reset.cfg\n");
773 localcmd("\nsettemp_restore\n");
778 Map_MarkAsRecent(getmapname_stored);
780 MapInfo_LoadMap(getmapname_stored);
783 // return codes of map selectors:
784 // -1 = temporary failure (that is, try some method that is guaranteed to succeed)
785 // -2 = permanent failure
786 float() MaplistMethod_Iterate = // usual method
790 for(pass = 1; pass <= 2; ++pass)
792 for(i = 1; i < Map_Count; ++i)
795 mapindex = mod(i + Map_Current, Map_Count);
796 if(Map_Check(mapindex, pass))
803 float() MaplistMethod_Repeat = // fallback method
805 if(Map_Check(Map_Current, 2))
810 float() MaplistMethod_Random = // random map selection
816 for(i = 0; i <= imax; ++i)
819 mapindex = mod(Map_Current + floor(random() * (Map_Count - 1) + 1), Map_Count); // any OTHER map
820 if(Map_Check(mapindex, 1))
826 float(float exponent) MaplistMethod_Shuffle = // more clever shuffling
827 // the exponent sets a bias on the map selection:
828 // the higher the exponent, the less likely "shortly repeated" same maps are
830 float i, j, imax, insertpos;
834 for(i = 0; i <= imax; ++i)
838 // now reinsert this at another position
839 insertpos = pow(random(), 1 / exponent); // ]0, 1]
840 insertpos = insertpos * (Map_Count - 1); // ]0, Map_Count - 1]
841 insertpos = ceil(insertpos) + 1; // {2, 3, 4, ..., Map_Count}
842 dprint("SHUFFLE: insert pos = ", ftos(insertpos), "\n");
844 // insert the current map there
846 for(j = 1; j < insertpos; ++j) // i == 1: no loop, will be inserted as first; however, i == 1 has been excluded above
847 newlist = strcat(newlist, " ", argv(j));
848 newlist = strcat(newlist, " ", argv(0)); // now insert the just selected map
849 for(j = insertpos; j < Map_Count; ++j) // i == Map_Count: no loop, has just been inserted as last
850 newlist = strcat(newlist, " ", argv(j));
851 newlist = substring(newlist, 1, strlen(newlist) - 1);
852 cvar_set("g_maplist", newlist);
853 Map_Count = tokenizebyseparator(cvar_string("g_maplist"), " ");
855 // NOTE: the selected map has just been inserted at (insertpos-1)th position
856 Map_Current = insertpos - 1; // this is not really valid, but this way the fallback has a chance of working
857 if(Map_Check(Map_Current, 1))
865 Map_Count = tokenizebyseparator(cvar_string("g_maplist"), " ");
868 bprint( "Maplist is empty! Resetting it to default map list.\n" );
869 cvar_set("g_maplist", MapInfo_ListAllowedMaps(0, MAPINFO_FLAG_HIDDEN));
870 if(cvar("g_maplist_shuffle"))
872 localcmd("\nmenu_cmd sync\n");
873 Map_Count = tokenizebyseparator(cvar_string("g_maplist"), " ");
876 error("empty maplist, cannot select a new map");
877 Map_Current = bound(0, GetMaplistPosition(), Map_Count - 1);
880 strunzone(Map_Current_Name);
881 Map_Current_Name = strzone(argv(Map_Current)); // will be automatically freed on exit thanks to DP
882 // this may or may not be correct, but who cares, in the worst case a map
883 // isn't chosen in the first pass that should have been
894 if(cvar("g_maplist_shuffle") > 0)
895 nextMap = MaplistMethod_Shuffle(cvar("g_maplist_shuffle") + 1);
898 if(cvar("g_maplist_selectrandom"))
899 nextMap = MaplistMethod_Random();
902 nextMap = MaplistMethod_Iterate();
905 nextMap = MaplistMethod_Repeat();
909 Map_Goto_SetFloat(nextMap);
910 return getmapname_stored;
916 float DoNextMapOverride()
918 if(cvar("g_campaign"))
920 CampaignPostIntermission();
921 alreadychangedlevel = TRUE;
924 if(cvar("quit_when_empty"))
926 if(player_count <= currentbots)
929 alreadychangedlevel = TRUE;
933 if(cvar_string("quit_and_redirect") != "")
935 redirection_target = strzone(cvar_string("quit_and_redirect"));
936 alreadychangedlevel = TRUE;
939 if (cvar("samelevel")) // if samelevel is set, stay on same level
941 // 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)
942 //localcmd(strcat("exec \"maps/", mapname, ".mapcfg\"\n"));
943 // so instead just restart the current map using the restart command (DOES NOT WORK PROPERLY WITH exit_cfg STUFF)
944 localcmd("restart\n");
945 //changelevel (mapname);
946 alreadychangedlevel = TRUE;
949 if(cvar_string("nextmap") != "")
950 if(MapInfo_CheckMap(cvar_string("nextmap")))
952 Map_Goto_SetStr(cvar_string("nextmap"));
954 alreadychangedlevel = TRUE;
957 if(cvar("lastlevel"))
960 localcmd("set lastlevel 0\ntogglemenu\n");
961 alreadychangedlevel = TRUE;
969 //local string nextmap;
970 //local float n, nummaps;
972 if (alreadychangedlevel)
974 alreadychangedlevel = TRUE;
980 for(allowReset = 1; allowReset >= 0; --allowReset)
982 nextMap = GetNextMap();
988 bprint( "Maplist contains no single playable map! Resetting it to default map list.\n" );
989 cvar_set("g_maplist", MapInfo_ListAllowedMaps(0, MAPINFO_FLAG_HIDDEN));
990 if(cvar("g_maplist_shuffle"))
992 localcmd("\nmenu_cmd sync\n");
996 error("Everything is broken - not even the default map list works. Please report this to the developers.");
1008 When the player presses attack or jump, change to the next level
1011 .float autoscreenshot;
1012 void() MapVote_Start;
1013 void() MapVote_Think;
1014 float mapvote_initialized;
1015 void IntermissionThink()
1017 FixIntermissionClient(self);
1019 if(cvar("sv_autoscreenshot"))
1020 if(self.autoscreenshot > 0)
1021 if(time > self.autoscreenshot)
1023 self.autoscreenshot = -1;
1024 if(clienttype(self) == CLIENTTYPE_REAL)
1025 stuffcmd(self, "\nscreenshot\necho \"^5A screenshot has been taken at request of the server.\"\n");
1029 if (time < intermission_exittime)
1032 if(!mapvote_initialized)
1033 if (time < intermission_exittime + 10 && !self.BUTTON_ATCK && !self.BUTTON_JUMP && !self.BUTTON_ATCK2 && !self.BUTTON_HOOK && !self.BUTTON_USE)
1043 Returns the entity to view from
1047 entity FindIntermission()
1052 // look for info_intermission first
1053 spot = find (world, classname, "info_intermission");
1055 { // pick a random one
1059 spot = find (spot, classname, "info_intermission");
1061 spot = find (spot, classname, "info_intermission");
1067 // then look for the start position
1068 spot = find (world, classname, "info_player_start");
1072 // testinfo_player_start is only found in regioned levels
1073 spot = find (world, classname, "testplayerstart");
1077 // then look for the start position
1078 spot = find (world, classname, "info_player_deathmatch");
1082 //objerror ("FindIntermission: no spot");
1088 ===============================================================================
1092 ===============================================================================
1095 void DumpStats(float final)
1099 local float to_console;
1100 local float to_eventlog;
1101 local float to_file;
1104 to_console = cvar("sv_logscores_console");
1105 to_eventlog = cvar("sv_eventlog");
1106 to_file = cvar("sv_logscores_file");
1110 to_console = TRUE; // always print printstats replies
1111 to_eventlog = FALSE; // but never print them to the event log
1115 if(cvar("sv_eventlog_console"))
1116 to_console = FALSE; // otherwise we get the output twice
1122 s = strcat(s, GetGametype(), "_", GetMapname(), ":", ftos(rint(time)));
1130 file = fopen(cvar_string("sv_logscores_filename"), FILE_APPEND);
1134 fputs(file, strcat(s, "\n"));
1137 s = strcat(":labels:player:", GetPlayerScoreString(world, 0));
1143 fputs(file, strcat(s, "\n"));
1145 FOR_EACH_CLIENT(other)
1147 if ((clienttype(other) == CLIENTTYPE_REAL) || (clienttype(other) == CLIENTTYPE_BOT && cvar("sv_logscores_bots")))
1149 s = strcat(":player:see-labels:", GetPlayerScoreString(other, 0), ":");
1150 s = strcat(s, ftos(rint(time - other.jointime)), ":");
1151 if(other.classname == "player" || g_arena || g_lms)
1152 s = strcat(s, ftos(other.team), ":");
1154 s = strcat(s, "spectator:");
1157 print(s, other.netname, "\n");
1159 GameLogEcho(strcat(s, ftos(other.playerid), ":", other.netname));
1161 fputs(file, strcat(s, other.netname, "\n"));
1167 s = strcat(":labels:teamscores:", GetTeamScoreString(0, 0));
1173 fputs(file, strcat(s, "\n"));
1175 for(i = 1; i < 16; ++i)
1177 s = strcat(":teamscores:see-labels:", GetTeamScoreString(i, 0));
1178 s = strcat(s, ":", ftos(i));
1184 fputs(file, strcat(s, "\n"));
1191 GameLogEcho(":end");
1194 fputs(file, ":end\n");
1199 void FixIntermissionClient(entity e)
1202 if(!e.autoscreenshot) // initial call
1204 e.angles = e.v_angle;
1205 e.angles_x = -e.angles_x;
1206 e.autoscreenshot = time + 0.8; // used for autoscreenshot
1208 // first intermission phase; voting phase has positive health (used to decide whether to send SVC_FINALE or not)
1209 e.solid = SOLID_NOT;
1210 e.movetype = MOVETYPE_NONE;
1211 e.takedamage = DAMAGE_NO;
1213 e.weaponentity.effects = EF_NODRAW;
1214 if(clienttype(e) == CLIENTTYPE_REAL)
1216 stuffcmd(e, "\nscr_printspeed 1000000\n");
1217 s = cvar_string("sv_intermission_cdtrack");
1219 stuffcmd(e, strcat("\ncd loop ", s, "\n"));
1221 WriteByte(MSG_ONE, SVC_INTERMISSION);
1225 //e.velocity = '0 0 0';
1226 //e.fixangle = TRUE;
1228 // TODO halt weapon animation
1233 go to the next level for deathmatch
1234 only called if a time or frag limit has expired
1238 float minTotalFrags;
1239 float maxTotalFrags;
1245 intermission_running = 1;
1247 // enforce a wait time before allowing changelevel
1248 if(player_count > 0)
1249 intermission_exittime = time + cvar("sv_mapchange_delay");
1251 intermission_exittime = -1;
1254 WriteByte (MSG_ALL, SVC_CDTRACK);
1255 WriteByte (MSG_ALL, 3);
1256 WriteByte (MSG_ALL, 3);
1257 // done in FixIntermission
1260 //pos = FindIntermission ();
1266 if(cvar("sv_eventlog"))
1267 GameLogEcho(":gameover");
1271 FOR_EACH_CLIENT(other)
1273 FixIntermissionClient(other);
1276 bprint(other.netname, " ^7wins.\n");
1281 FOR_EACH_PLAYER(other)
1283 if(maxTotalFrags < other.totalfrags)
1284 maxTotalFrags = other.totalfrags;
1285 if(minTotalFrags > other.totalfrags)
1286 minTotalFrags = other.totalfrags;
1291 FOR_EACH_PLAYER(other)
1293 score = (other.totalfrags - minTotalFrags) / max(maxTotalFrags - minTotalFrags, 1);
1294 f = bound(0, other.play_time / max(time, 1), 1);
1295 // store some statistics?
1299 if(cvar("g_campaign"))
1300 CampaignPreIntermission();
1302 // WriteByte (MSG_ALL, SVC_INTERMISSION);
1309 Exit deathmatch games upon conditions
1312 void CheckRules_Player()
1314 if (gameover) // someone else quit the game already
1317 if(self.deadflag == DEAD_NO)
1318 self.play_time += frametime;
1320 // fixme: don't check players; instead check spawnfunc_dom_team and spawnfunc_ctf_team entities
1321 // (div0: and that in CheckRules_World please)
1324 float checkrules_oneminutewarning;
1326 float checkrules_equality;
1327 float checkrules_overtimewarning;
1328 float checkrules_overtimeend;
1330 void InitiateOvertime()
1332 if(!checkrules_overtimeend)
1333 checkrules_overtimeend = time + 60 * cvar("timelimit_maxovertime");
1336 float WINNING_NO = 0; // no winner, but time limits may terminate the game
1337 float WINNING_YES = 1; // winner found
1338 float WINNING_NEVER = 2; // no winner, enter overtime if time limit is reached
1339 float WINNING_STARTOVERTIME = 3; // no winner, enter overtime NOW
1341 float GetWinningCode(float fraglimitreached, float equality)
1344 if(fraglimitreached)
1345 return WINNING_STARTOVERTIME;
1347 return WINNING_NEVER;
1349 if(fraglimitreached)
1355 // set the .winning flag for exactly those players with a given field value
1356 void SetWinners(.float field, float value)
1359 FOR_EACH_PLAYER(head)
1360 head.winning = (head.field == value);
1363 // set the .winning flag for those players with a given field value
1364 void AddWinners(.float field, float value)
1367 FOR_EACH_PLAYER(head)
1368 if(head.field == value)
1372 // clear the .winning flags
1373 void ClearWinners(void)
1376 FOR_EACH_PLAYER(head)
1380 // Onslaught winning condition:
1381 // game terminates if only one team has a working generator (or none)
1382 float WinningCondition_Onslaught()
1385 local float t1, t2, t3, t4;
1387 WinningConditionHelper(); // set worldstatus
1389 // first check if the game has ended
1390 t1 = t2 = t3 = t4 = 0;
1391 head = find(world, classname, "onslaught_generator");
1394 if (head.health > 0)
1396 if (head.team == COLOR_TEAM1) t1 = 1;
1397 if (head.team == COLOR_TEAM2) t2 = 1;
1398 if (head.team == COLOR_TEAM3) t3 = 1;
1399 if (head.team == COLOR_TEAM4) t4 = 1;
1401 head = find(head, classname, "onslaught_generator");
1403 if (t1 + t2 + t3 + t4 < 2)
1405 // game over, only one team remains (or none)
1407 if (t1) SetWinners(team, COLOR_TEAM1);
1408 if (t2) SetWinners(team, COLOR_TEAM2);
1409 if (t3) SetWinners(team, COLOR_TEAM3);
1410 if (t4) SetWinners(team, COLOR_TEAM4);
1411 dprint("Have a winner, ending game.\n");
1415 // Two or more teams remain
1419 float LMS_NewPlayerLives()
1422 fl = cvar("fraglimit");
1426 // first player has left the game for dying too much? Nobody else can get in.
1427 if(lms_lowest_lives < 1)
1430 if(!cvar("g_lms_join_anytime"))
1431 if(lms_lowest_lives < fl - cvar("g_lms_last_join"))
1434 return bound(1, lms_lowest_lives, fl);
1437 // Assault winning condition: If the attackers triggered a round end (by fulfilling all objectives)
1438 // they win. Otherwise the defending team wins once the timelimit passes.
1439 void assault_new_round();
1440 float WinningCondition_Assault()
1444 WinningConditionHelper(); // set worldstatus
1446 status = WINNING_NO;
1447 // as the timelimit has not yet passed just assume the defending team will win
1448 if(assault_attacker_team == COLOR_TEAM1)
1450 SetWinners(team, COLOR_TEAM2);
1454 SetWinners(team, COLOR_TEAM1);
1458 ent = find(world, classname, "target_assault_roundend");
1461 if(ent.winning) // round end has been triggered by attacking team
1463 bprint("ASSAULT: round completed...\n");
1464 SetWinners(team, assault_attacker_team);
1466 TeamScore_AddToTeam(assault_attacker_team, ST_ASSAULT_OBJECTIVES, 666 - TeamScore_AddToTeam(assault_attacker_team, ST_ASSAULT_OBJECTIVES, 0));
1468 if(ent.cnt == 1) // this was the second round
1470 status = WINNING_YES;
1474 local entity oldself;
1477 assault_new_round();
1486 // LMS winning condition: game terminates if and only if there's at most one
1487 // one player who's living lives. Top two scores being equal cancels the time
1489 float WinningCondition_LMS()
1496 have_player = FALSE;
1497 have_players = FALSE;
1498 l = LMS_NewPlayerLives();
1500 head = find(world, classname, "player");
1503 head2 = find(head, classname, "player");
1505 have_players = TRUE;
1509 // we have at least one player
1512 // two or more active players - continue with the game
1516 // exactly one player?
1519 SetWinners(winning, 0); // NOTE: exactly one player is still "player", so this works out
1523 // game still running (that is, nobody got removed from the game by a frag yet)? then continue
1529 // and assign him his first place
1530 PlayerScore_Add(head, SP_LMS_RANK, 1);
1537 // nobody is playing at all...
1540 // wait for players...
1544 // SNAFU (maybe a draw game?)
1546 dprint("No players, ending game.\n");
1551 // When we get here, we have at least two players who are actually LIVING,
1552 // now check if the top two players have equal score.
1553 WinningConditionHelper();
1556 if(WinningConditionHelper_winner)
1557 WinningConditionHelper_winner.winning = TRUE;
1558 if(WinningConditionHelper_equality)
1559 return WINNING_NEVER;
1561 // Top two have different scores? Way to go for our beloved TIMELIMIT!
1565 void ShuffleMaplist()
1573 result = cvar_string("g_maplist");
1574 litems = tokenizebyseparator(result, " ");
1576 for(start = 0; start < litems - 1; ++start)
1580 // select a random item
1581 selected = floor(random() * (litems - start) + start);
1583 // shift this item to the place start
1584 for(i = 0; i < start; ++i)
1585 result = strcat(result, " ", argv(i));
1586 result = strcat(result, " ", argv(selected));
1587 for(i = start; i < litems; ++i)
1589 result = strcat(result, " ", argv(i));
1590 result = substring(result, 1, strlen(result) - 1);
1592 litems = tokenizebyseparator(result, " ");
1594 //dprint(result, "\n");
1597 cvar_set("g_maplist", result);
1601 float WinningCondition_Scores(float limit)
1603 // TODO make everything use THIS winning condition (except LMS)
1604 WinningConditionHelper();
1608 team1_score = TeamScore_GetCompareValue(COLOR_TEAM1);
1609 team2_score = TeamScore_GetCompareValue(COLOR_TEAM2);
1610 team3_score = TeamScore_GetCompareValue(COLOR_TEAM3);
1611 team4_score = TeamScore_GetCompareValue(COLOR_TEAM4);
1615 if(WinningConditionHelper_winner)
1616 WinningConditionHelper_winner.winning = 1;
1617 if(WinningConditionHelper_winnerteam >= 0)
1618 SetWinners(team, WinningConditionHelper_winnerteam);
1620 if(WinningConditionHelper_lowerisbetter)
1622 WinningConditionHelper_topscore = -WinningConditionHelper_topscore;
1626 if(g_dm || g_tdm || g_arena || (g_race && !g_race_qualifying))
1627 // these modes always score in increments of 1, thus this makes sense
1629 if(leaderfrags != WinningConditionHelper_topscore)
1631 leaderfrags = WinningConditionHelper_topscore;
1634 if (leaderfrags == limit - 1)
1635 play2all("announcer/robotic/1fragleft.wav");
1636 else if (leaderfrags == limit - 2)
1637 play2all("announcer/robotic/2fragsleft.wav");
1638 else if (leaderfrags == limit - 3)
1639 play2all("announcer/robotic/3fragsleft.wav");
1643 return GetWinningCode(limit && WinningConditionHelper_topscore && (WinningConditionHelper_topscore >= limit), WinningConditionHelper_equality);
1646 float WinningCondition_Race(float fraglimit)
1650 wc = WinningCondition_Scores(fraglimit);
1652 // ALWAYS initiate overtime, unless EVERYONE has finished the race!
1653 if(wc == WINNING_YES || wc == WINNING_STARTOVERTIME)
1654 // do NOT support equality when the laps are all raced!
1657 if not(p.race_completed)
1658 return WINNING_STARTOVERTIME;
1664 void ReadyRestart();
1665 float WinningCondition_QualifyingThenRace(float limit)
1668 wc = WinningCondition_Scores(limit);
1670 // NEVER initiate overtime
1671 if(wc == WINNING_YES || wc == WINNING_STARTOVERTIME)
1679 float WinningCondition_RanOutOfSpawns()
1683 if(!have_team_spawns)
1686 if(!some_spawn_has_been_used)
1689 team1_score = team2_score = team3_score = team4_score = 0;
1691 FOR_EACH_PLAYER(head) if(head.deadflag == DEAD_NO)
1693 if(head.team == COLOR_TEAM1)
1695 else if(head.team == COLOR_TEAM2)
1697 else if(head.team == COLOR_TEAM3)
1699 else if(head.team == COLOR_TEAM4)
1703 for(head = world; (head = find(head, classname, "info_player_deathmatch")) != world; )
1705 if(head.team == COLOR_TEAM1)
1707 else if(head.team == COLOR_TEAM2)
1709 else if(head.team == COLOR_TEAM3)
1711 else if(head.team == COLOR_TEAM4)
1716 if(team1_score + team2_score + team3_score + team4_score == 0)
1718 checkrules_equality = TRUE;
1721 else if(team1_score + team2_score + team3_score + team4_score == 1)
1724 if(team1_score) t = COLOR_TEAM1;
1725 if(team2_score) t = COLOR_TEAM2;
1726 if(team3_score) t = COLOR_TEAM3;
1727 if(team4_score) t = COLOR_TEAM4;
1728 CheckAllowedTeams(world);
1729 for(i = 0; i < MAX_TEAMSCORE; ++i)
1731 if(t != COLOR_TEAM1) if(c1 >= 0) TeamScore_AddToTeam(COLOR_TEAM1, i, -1000);
1732 if(t != COLOR_TEAM2) if(c2 >= 0) TeamScore_AddToTeam(COLOR_TEAM2, i, -1000);
1733 if(t != COLOR_TEAM3) if(c3 >= 0) TeamScore_AddToTeam(COLOR_TEAM3, i, -1000);
1734 if(t != COLOR_TEAM4) if(c4 >= 0) TeamScore_AddToTeam(COLOR_TEAM4, i, -1000);
1737 AddWinners(team, t);
1748 Exit deathmatch games upon conditions
1751 void CheckRules_World()
1754 local float timelimit;
1755 local float fraglimit;
1763 MapVote_Think should now do that part
1764 if (intermission_running)
1765 if (time >= intermission_exittime + 60)
1767 if(!DoNextMapOverride())
1773 if (gameover) // someone else quit the game already
1775 if(player_count == 0) // Nobody there? Then let's go to the next map
1777 // this will actually check the player count in the next frame
1778 // again, but this shouldn't hurt
1782 timelimit = cvar("timelimit") * 60;
1783 fraglimit = cvar("fraglimit");
1785 if(inWarmupStage || time <= game_starttime) // NOTE: this is <= to prevent problems in the very tic where the game starts
1788 timelimit = 0; // timelimit is not made for warmup
1790 fraglimit = 0; // no fraglimit for now
1795 timelimit += game_starttime;
1797 else if (timelimit < 0)
1804 if(checkrules_overtimeend)
1806 if(!checkrules_overtimewarning)
1808 checkrules_overtimewarning = TRUE;
1809 //announceall("announcer/robotic/1minuteremains.wav");
1810 if(g_race && !g_race_qualifying)
1811 bcenterprint("^3Everyone, finish your lap! The race is over!");
1813 bcenterprint("^3Now playing ^1OVERTIME^3!\n\n^3Keep fragging until we have a ^1winner^3!");
1818 if (timelimit && time >= timelimit)
1820 if(g_race && g_race_qualifying == 2 && timelimit > 0)
1823 float playerswithlaps;
1826 totalplayers = playerswithlaps = readyplayers = 0;
1827 FOR_EACH_PLAYER(head)
1830 if(PlayerScore_Add(head, SP_RACE_FASTEST, 0))
1836 // at least 2/3 of the players have completed a lap: start the RACE
1837 // otherwise, the players should end the qualifying on their own
1838 if(readyplayers || ((totalplayers >= 3) && (playerswithlaps * 3 >= totalplayers * 2)))
1840 checkrules_overtimeend = 0;
1841 ReadyRestart(); // go to race
1851 if (checkrules_overtimeend && time >= checkrules_overtimeend)
1857 if (!checkrules_oneminutewarning && timelimit > 0 && time > timelimit - 60)
1859 checkrules_oneminutewarning = TRUE;
1860 play2all("announcer/robotic/1minuteremains.wav");
1863 status = WinningCondition_RanOutOfSpawns();
1864 if(status == WINNING_YES)
1866 bprint("Hey! Someone ran out of spawns!\n");
1868 else if(g_race && !g_race_qualifying && timelimit >= 0)
1870 status = WinningCondition_Race(fraglimit);
1872 else if(g_race && g_race_qualifying == 2 && timelimit >= 0)
1874 status = WinningCondition_QualifyingThenRace(fraglimit);
1878 status = WinningCondition_Assault(); // TODO remove this?
1882 status = WinningCondition_LMS();
1884 else if (g_onslaught)
1886 status = WinningCondition_Onslaught(); // TODO remove this?
1890 status = WinningCondition_Scores(fraglimit);
1893 if(status == WINNING_STARTOVERTIME)
1895 status = WINNING_NEVER;
1899 if(status == WINNING_NEVER)
1900 // equality cases! Nobody wins if the overtime ends in a draw.
1903 if(checkrules_overtimeend)
1904 if(status != WINNING_NEVER || time >= checkrules_overtimeend)
1905 status = WINNING_YES;
1907 if(status == WINNING_YES)
1911 float mapvote_nextthink;
1912 float mapvote_initialized;
1913 float mapvote_keeptwotime;
1914 float mapvote_timeout;
1915 string mapvote_message;
1916 string mapvote_screenshot_dir;
1918 float mapvote_count;
1919 float mapvote_count_real;
1920 string mapvote_maps[MAPVOTE_COUNT];
1921 float mapvote_maps_suggested[MAPVOTE_COUNT];
1922 string mapvote_suggestions[MAPVOTE_COUNT];
1923 float mapvote_suggestion_ptr;
1924 float mapvote_maxlen;
1925 float mapvote_voters;
1926 float mapvote_votes[MAPVOTE_COUNT];
1928 float mapvote_detail;
1929 float mapvote_abstain;
1932 void MapVote_ClearAllVotes()
1934 FOR_EACH_CLIENT(other)
1938 string MapVote_Suggest(string m)
1942 return "That's not how to use this command.";
1943 if(!cvar("g_maplist_votable_suggestions"))
1944 return "Suggestions are not accepted on this server.";
1945 if(mapvote_initialized)
1946 return "Can't suggest - voting is already in progress!";
1947 m = MapInfo_FixName(m);
1949 return "The map you suggested is not available on this server.";
1950 if(!cvar("g_maplist_votable_override_mostrecent"))
1952 return "This server does not allow for recent maps to be played again. Please be patient for some rounds.";
1954 if(!MapInfo_CheckMap(m))
1955 return "The map you suggested does not support the current game mode.";
1956 for(i = 0; i < mapvote_suggestion_ptr; ++i)
1957 if(mapvote_suggestions[i] == m)
1958 return "This map was already suggested.";
1959 if(mapvote_suggestion_ptr >= MAPVOTE_COUNT)
1961 i = floor(random() * mapvote_suggestion_ptr);
1965 i = mapvote_suggestion_ptr;
1966 mapvote_suggestion_ptr += 1;
1968 if(mapvote_suggestions[i] != "")
1969 strunzone(mapvote_suggestions[i]);
1970 mapvote_suggestions[i] = strzone(m);
1971 if(cvar("sv_eventlog"))
1972 GameLogEcho(strcat(":vote:suggested:", m, ":", ftos(self.playerid)));
1973 return strcat("Suggestion of ", m, " accepted.");
1976 void MapVote_AddVotable(string nextMap, float isSuggestion)
1981 for(j = 0; j < mapvote_count; ++j)
1982 if(mapvote_maps[j] == nextMap)
1984 if(strlen(nextMap) > mapvote_maxlen)
1985 mapvote_maxlen = strlen(nextMap);
1986 mapvote_maps[mapvote_count] = strzone(nextMap);
1987 mapvote_maps_suggested[mapvote_count] = isSuggestion;
1991 void MapVote_Spawn();
1997 MapVote_ClearAllVotes();
2000 mapvote_detail = !cvar("g_maplist_votable_nodetail");
2001 mapvote_abstain = cvar("g_maplist_votable_abstain");
2004 nmax = min(MAPVOTE_COUNT - 1, cvar("g_maplist_votable"));
2006 nmax = min(MAPVOTE_COUNT, cvar("g_maplist_votable"));
2007 smax = min3(nmax, cvar("g_maplist_votable_suggestions"), mapvote_suggestion_ptr);
2009 if(mapvote_suggestion_ptr)
2010 for(i = 0; i < 100 && mapvote_count < smax; ++i)
2011 MapVote_AddVotable(mapvote_suggestions[floor(random() * mapvote_suggestion_ptr)], TRUE);
2013 for(i = 0; i < 100 && mapvote_count < nmax; ++i)
2014 MapVote_AddVotable(GetNextMap(), FALSE);
2016 if(mapvote_count == 0)
2018 bprint( "Maplist contains no single playable map! Resetting it to default map list.\n" );
2019 cvar_set("g_maplist", MapInfo_ListAllowedMaps(0, MAPINFO_FLAG_HIDDEN));
2020 if(cvar("g_maplist_shuffle"))
2022 localcmd("\nmenu_cmd sync\n");
2023 for(i = 0; i < 100 && mapvote_count < nmax; ++i)
2024 MapVote_AddVotable(GetNextMap(), FALSE);
2027 mapvote_count_real = mapvote_count;
2029 MapVote_AddVotable("don't care", 0);
2031 //dprint("mapvote count is ", ftos(mapvote_count), "\n");
2033 mapvote_keeptwotime = time + cvar("g_maplist_votable_keeptwotime");
2034 mapvote_timeout = time + cvar("g_maplist_votable_timeout");
2035 if(mapvote_count_real < 3 || mapvote_keeptwotime <= time)
2036 mapvote_keeptwotime = 0;
2037 mapvote_message = "Choose a map and press its key!";
2039 mapvote_screenshot_dir = cvar_string("g_maplist_votable_screenshot_dir");
2040 if(mapvote_screenshot_dir == "")
2041 mapvote_screenshot_dir = "maps";
2042 mapvote_screenshot_dir = strzone(mapvote_screenshot_dir);
2047 void MapVote_SendPicture(float id)
2050 WriteByte(MSG_ONE, SVC_TEMPENTITY);
2051 WriteByte(MSG_ONE, TE_CSQC_PICTURE);
2052 WriteByte(MSG_ONE, id);
2053 WritePicture(MSG_ONE, strcat(mapvote_screenshot_dir, "/", mapvote_maps[id]), 3072);
2056 float GameCommand_MapVote(string cmd)
2058 if(!intermission_running)
2061 if(cmd == "mv_getpic")
2063 MapVote_SendPicture(stof(argv(1)));
2070 float MapVote_GetMapMask()
2072 float mask, i, power;
2074 for(i = 0, power = 1; i < mapvote_count; ++i, power *= 2)
2075 if(mapvote_maps[i] != "")
2081 float MapVote_SendEntity(entity to, float sf)
2083 string mapfile, pakfile;
2086 WriteByte(MSG_ENTITY, ENT_CLIENT_MAPVOTE);
2087 WriteByte(MSG_ENTITY, sf);
2091 // flag 1 == initialization
2092 WriteString(MSG_ENTITY, mapvote_screenshot_dir);
2093 WriteByte(MSG_ENTITY, mapvote_count);
2094 WriteByte(MSG_ENTITY, mapvote_abstain);
2095 WriteByte(MSG_ENTITY, mapvote_detail);
2096 WriteCoord(MSG_ENTITY, mapvote_timeout);
2097 if(mapvote_count <= 8)
2098 WriteByte(MSG_ENTITY, MapVote_GetMapMask());
2100 WriteShort(MSG_ENTITY, MapVote_GetMapMask());
2101 for(i = 0; i < mapvote_count; ++i)
2102 if(mapvote_maps[i] != "")
2104 WriteString(MSG_ENTITY, mapvote_maps[i]);
2105 mapfile = strcat(mapvote_screenshot_dir, "/", mapvote_maps[i]);
2106 pakfile = whichpack(strcat(mapfile, ".tga"));
2108 pakfile = whichpack(strcat(mapfile, ".jpg"));
2110 pakfile = whichpack(strcat(mapfile, ".png"));
2111 for(o = strstr(pakfile, "/", 0)+1; o > 0; o = strstr(pakfile, "/", 0)+1)
2112 pakfile = substring(pakfile, o, 999);
2113 WriteString(MSG_ENTITY, pakfile);
2119 // flag 2 == update of mask
2120 if(mapvote_count <= 8)
2121 WriteByte(MSG_ENTITY, MapVote_GetMapMask());
2123 WriteShort(MSG_ENTITY, MapVote_GetMapMask());
2129 for(i = 0; i < mapvote_count; ++i)
2130 if(mapvote_maps[i] != "")
2131 WriteByte(MSG_ENTITY, mapvote_votes[i]);
2133 WriteByte(MSG_ENTITY, to.mapvote);
2139 void MapVote_Spawn()
2141 Net_LinkEntity(mapvote_ent = spawn(), FALSE, 0, MapVote_SendEntity);
2144 void MapVote_TouchMask()
2146 mapvote_ent.SendFlags |= 2;
2149 void MapVote_TouchVotes(entity voter)
2151 mapvote_ent.SendFlags |= 4;
2154 float MapVote_Finished(float mappos)
2160 if(cvar("sv_eventlog"))
2162 result = strcat(":vote:finished:", mapvote_maps[mappos]);
2163 result = strcat(result, ":", ftos(mapvote_votes[mappos]), "::");
2164 didntvote = mapvote_voters;
2165 for(i = 0; i < mapvote_count; ++i)
2166 if(mapvote_maps[i] != "")
2168 didntvote -= mapvote_votes[i];
2171 result = strcat(result, ":", mapvote_maps[i]);
2172 result = strcat(result, ":", ftos(mapvote_votes[i]));
2175 result = strcat(result, ":didn't vote:", ftos(didntvote));
2177 GameLogEcho(result);
2178 if(mapvote_maps_suggested[mappos])
2179 GameLogEcho(strcat(":vote:suggestion_accepted:", mapvote_maps[mappos]));
2182 FOR_EACH_REALCLIENT(other)
2183 FixClientCvars(other);
2185 Map_Goto_SetStr(mapvote_maps[mappos]);
2187 alreadychangedlevel = TRUE;
2190 void MapVote_CheckRules_1()
2194 for(i = 0; i < mapvote_count; ++i) if(mapvote_maps[i] != "")
2196 //dprint("Map ", ftos(i), ": "); dprint(mapvote_maps[i], "\n");
2197 mapvote_votes[i] = 0;
2201 FOR_EACH_REALCLIENT(other)
2206 i = other.mapvote - 1;
2207 //dprint("Player ", other.netname, " vote = ", ftos(other.mapvote - 1), "\n");
2208 mapvote_votes[i] = mapvote_votes[i] + 1;
2213 float MapVote_CheckRules_2()
2216 float firstPlace, secondPlace;
2217 float firstPlaceVotes, secondPlaceVotes;
2218 float mapvote_voters_real;
2221 mapvote_voters_real = mapvote_voters;
2223 mapvote_voters_real -= mapvote_votes[mapvote_count - 1];
2225 RandomSelection_Init();
2226 for(i = 0; i < mapvote_count_real; ++i) if(mapvote_maps[i] != "")
2227 RandomSelection_Add(world, i, 1, mapvote_votes[i]);
2228 firstPlace = RandomSelection_chosen_float;
2229 firstPlaceVotes = RandomSelection_best_priority;
2230 //dprint("First place: ", ftos(firstPlace), "\n");
2231 //dprint("First place votes: ", ftos(firstPlaceVotes), "\n");
2233 RandomSelection_Init();
2234 for(i = 0; i < mapvote_count_real; ++i) if(mapvote_maps[i] != "")
2236 RandomSelection_Add(world, i, 1, mapvote_votes[i]);
2237 secondPlace = RandomSelection_chosen_float;
2238 secondPlaceVotes = RandomSelection_best_priority;
2239 //dprint("Second place: ", ftos(secondPlace), "\n");
2240 //dprint("Second place votes: ", ftos(secondPlaceVotes), "\n");
2242 if(firstPlace == -1)
2243 error("No first place in map vote... WTF?");
2245 if(secondPlace == -1 || time > mapvote_timeout || (mapvote_voters_real - firstPlaceVotes) < firstPlaceVotes)
2246 return MapVote_Finished(firstPlace);
2248 if(mapvote_keeptwotime)
2249 if(time > mapvote_keeptwotime || (mapvote_voters_real - firstPlaceVotes - secondPlaceVotes) < secondPlaceVotes)
2252 MapVote_TouchMask();
2253 mapvote_message = "Now decide between the TOP TWO!";
2254 mapvote_keeptwotime = 0;
2255 result = strcat(":vote:keeptwo:", mapvote_maps[firstPlace]);
2256 result = strcat(result, ":", ftos(firstPlaceVotes));
2257 result = strcat(result, ":", mapvote_maps[secondPlace]);
2258 result = strcat(result, ":", ftos(secondPlaceVotes), "::");
2259 didntvote = mapvote_voters;
2260 for(i = 0; i < mapvote_count; ++i)
2261 if(mapvote_maps[i] != "")
2263 didntvote -= mapvote_votes[i];
2265 if(i != secondPlace)
2267 result = strcat(result, ":", mapvote_maps[i]);
2268 result = strcat(result, ":", ftos(mapvote_votes[i]));
2269 if(i < mapvote_count_real)
2271 strunzone(mapvote_maps[i]);
2272 mapvote_maps[i] = "";
2276 result = strcat(result, ":didn't vote:", ftos(didntvote));
2277 if(cvar("sv_eventlog"))
2278 GameLogEcho(result);
2288 keeptwo = mapvote_keeptwotime;
2289 MapVote_CheckRules_1(); // count
2290 if(MapVote_CheckRules_2()) // decide
2294 FOR_EACH_REALCLIENT(other)
2296 // hide scoreboard again
2297 if(other.health != 2342)
2299 other.health = 2342;
2301 if(clienttype(other) == CLIENTTYPE_REAL)
2304 WriteByte(MSG_ONE, SVC_FINALE);
2305 WriteString(MSG_ONE, "");
2309 // notify about keep-two
2310 if(keeptwo != 0 && mapvote_keeptwotime == 0)
2311 play2(other, "misc/invshot.wav");
2313 // clear possibly invalid votes
2314 if(mapvote_maps[other.mapvote - 1] == "")
2316 // use impulses as new vote
2317 if(other.impulse >= 1 && other.impulse <= mapvote_count)
2318 if(mapvote_maps[other.impulse - 1] != "")
2320 other.mapvote = other.impulse;
2321 MapVote_TouchVotes(other);
2329 MapVote_CheckRules_1(); // just count
2331 void MapVote_Start()
2336 MapInfo_Enumerate();
2337 if(MapInfo_FilterGametype(MapInfo_CurrentGametype(), MapInfo_CurrentFeatures(), 0, (g_maplist_allow_hidden ? MAPINFO_FLAG_HIDDEN : 0), 1))
2340 void MapVote_Think()
2345 if(alreadychangedlevel)
2348 if(time < mapvote_nextthink)
2352 mapvote_nextthink = time + 0.5;
2354 if(!mapvote_initialized)
2356 mapvote_initialized = TRUE;
2357 if(DoNextMapOverride())
2359 if(!cvar("g_maplist_votable") || player_count <= 0)
2370 string GotoMap(string m)
2372 if(!MapInfo_CheckMap(m))
2373 return "The map you chose is not available on this server.";
2374 cvar_set("nextmap", m);
2375 cvar_set("timelimit", "-1");
2376 if(mapvote_initialized || alreadychangedlevel)
2378 if(DoNextMapOverride())
2379 return "Map switch initiated.";
2381 return "Hm... no. For some reason I like THIS map more.";
2384 return "Map switch will happen after scoreboard.";
2390 FOR_EACH_REALCLIENT(self)
2392 if(self.classname == "spectator")
2394 if(self.enemy.typehitsound)
2395 play2(self, "misc/typehit.wav");
2396 else if(self.enemy.hitsound && self.cvar_cl_hitsound)
2397 play2(self, "misc/hit.wav");
2401 if(self.typehitsound)
2402 play2(self, "misc/typehit.wav");
2403 else if(self.hitsound && self.cvar_cl_hitsound)
2404 play2(self, "misc/hit.wav");
2407 FOR_EACH_CLIENT(self)
2409 self.hitsound = FALSE;
2410 self.typehitsound = FALSE;
2417 * returns TRUE if redirecting
2419 float redirection_timeout;
2420 float redirection_nextthink;
2421 float RedirectionThink()
2423 float clients_found;
2425 if(redirection_target == "")
2428 if(!redirection_timeout)
2430 cvar_set("sv_public", "-2");
2431 redirection_timeout = time + 0.6; // this will only try twice... should be able to keep more clients
2432 if(redirection_target == "self")
2433 bprint("^3SERVER NOTICE:^7 restarting the server\n");
2435 bprint("^3SERVER NOTICE:^7 redirecting everyone to ", redirection_target, "\n");
2438 if(time < redirection_nextthink)
2441 redirection_nextthink = time + 1;
2444 FOR_EACH_REALCLIENT(self)
2446 print("Redirecting: sending connect command to ", self.netname, "\n");
2447 if(redirection_target == "self")
2448 stuffcmd(self, "\ndisconnect; reconnect\n");
2450 stuffcmd(self, strcat("\ndisconnect; connect ", redirection_target, "\n"));
2454 print("Redirecting: ", ftos(clients_found), " clients left.\n");
2456 if(time > redirection_timeout || clients_found == 0)
2457 localcmd("\nwait; wait; wait; quit\n");
2464 // Loaded from a save game
2465 // some things then break, so let's work around them...
2467 // Progs DB (capture records)
2469 ServerProgsDB = db_create();
2471 ServerProgsDB = db_load("server.db");
2475 MapInfo_Enumerate();
2476 MapInfo_FilterGametype(MapInfo_CurrentGametype(), MapInfo_CurrentFeatures(), 0, (g_maplist_allow_hidden ? MAPINFO_FLAG_HIDDEN : 0), 1);
2481 if(world_initialized > 0)
2483 world_initialized = 0;
2484 print("Saving persistent data...\n");
2487 db_save(ServerProgsDB, "server.db");
2488 if(cvar("developer"))
2489 db_save(TemporaryDB, "server-temp.db");
2490 db_close(ServerProgsDB);
2491 db_close(TemporaryDB);
2493 // tell the bot system the game is ending now
2498 else if(world_initialized == 0)
2500 print("NOTE: crashed before even initializing the world, not saving persistent data\n");