]> icculus.org git repositories - divverent/nexuiz.git/blob - data/qcsrc/server/g_world.qc
when abstaining is allowed, make an extra empty line
[divverent/nexuiz.git] / data / qcsrc / server / g_world.qc
1 float SPAWNFLAG_NO_WAYPOINTS_FOR_ITEMS = 1;
2 string redirection_target;
3
4 string GetMapname();
5 string GetGametype();
6 void GotoNextMap();
7 void ShuffleMaplist()
8 float() DoNextMapOverride;
9
10 void SetDefaultAlpha()
11 {
12         if(cvar("g_running_guns"))
13         {
14                 default_player_alpha = -1;
15                 default_weapon_alpha = +1;
16         }
17         else if(g_cloaked)
18         {
19                 default_player_alpha = cvar("g_balance_cloaked_alpha");
20                 default_weapon_alpha = default_player_alpha;
21         }
22         else
23         {
24                 default_player_alpha = cvar("g_player_alpha");
25                 if(default_player_alpha <= 0)
26                         default_player_alpha = 1;
27                 default_weapon_alpha = default_player_alpha;
28         }
29 }
30
31 void fteqcc_testbugs()
32 {
33         float a, b;
34
35         if(!cvar("developer_fteqccbugs"))
36                 return;
37
38         dprint("*** fteqcc test: checking for bugs...\n");
39
40         a = 1;
41         b = 5;
42         if(sqrt(a) - sqrt(b - a) == 0)
43                 dprint("*** fteqcc test: found same-function-twice bug\n");
44         else
45                 dprint("*** fteqcc test: same-function-twice bug got FINALLY FIXED! HOORAY!\n");
46
47         world.frags = -10;
48         world.enemy = world;
49         world.enemy.frags += 10;
50         if(world.frags > 0.2 || world.frags < -0.2) // don't error out if it's just roundoff errors
51                 dprint("*** fteqcc test: found += bug\n");
52         else
53                 dprint("*** fteqcc test: += bug got FINALLY FIXED! HOORAY!\n");
54         world.frags = 0;
55 }
56
57 void GotoFirstMap()
58 {
59         if(cvar("_sv_init"))
60         {
61                 cvar_set("_sv_init", "0");
62                 if(cvar("g_maplist_shuffle"))
63                         ShuffleMaplist();
64 #ifdef MAPINFO
65                 tokenizebyseparator(cvar_string("g_maplist"), " ");
66 #else
67                 tokenize(cvar_string("g_maplist"));
68 #endif
69                 if(argv(0) != GetMapname())
70                 {
71                         cvar_set("nextmap", argv(0));
72
73 #ifdef MAPINFO
74                         MapInfo_Enumerate();
75                         MapInfo_FilterGametype(MapInfo_CurrentGametype(), MapInfo_CurrentFeatures(), 0);
76 #endif
77
78                         if(!DoNextMapOverride())
79                                 GotoNextMap();
80                 }
81         }
82 }
83
84 float world_already_spawned;
85 void worldspawn (void)
86 {
87         dprint_load(); // load dprint status from cvar
88
89         if(world_already_spawned)
90                 error("world already spawned - you may have EXACTLY ONE worldspawn!");
91         world_already_spawned = TRUE;
92
93         /*
94         TODO sound pack system
95         // initialize sound pack system
96         soundpack = cvar_string("g_soundpack");
97         if(soundpack != "")
98                 soundpack = strcat(soundpack, "/");
99         soundpack = strzone(soundpack);
100         */
101
102         // 0 normal
103         lightstyle(0, "m");
104
105         // 1 FLICKER (first variety)
106         lightstyle(1, "mmnmmommommnonmmonqnmmo");
107
108         // 2 SLOW STRONG PULSE
109         lightstyle(2, "abcdefghijklmnopqrstuvwxyzyxwvutsrqponmlkjihgfedcba");
110
111         // 3 CANDLE (first variety)
112         lightstyle(3, "mmmmmaaaaammmmmaaaaaabcdefgabcdefg");
113
114         // 4 FAST STROBE
115         lightstyle(4, "mamamamamama");
116
117         // 5 GENTLE PULSE 1
118         lightstyle(5,"jklmnopqrstuvwxyzyxwvutsrqponmlkj");
119
120         // 6 FLICKER (second variety)
121         lightstyle(6, "nmonqnmomnmomomno");
122
123         // 7 CANDLE (second variety)
124         lightstyle(7, "mmmaaaabcdefgmmmmaaaammmaamm");
125
126         // 8 CANDLE (third variety)
127         lightstyle(8, "mmmaaammmaaammmabcdefaaaammmmabcdefmmmaaaa");
128
129         // 9 SLOW STROBE (fourth variety)
130         lightstyle(9, "aaaaaaaazzzzzzzz");
131
132         // 10 FLUORESCENT FLICKER
133         lightstyle(10, "mmamammmmammamamaaamammma");
134
135         // 11 SLOW PULSE NOT FADE TO BLACK
136         lightstyle(11, "abcdefghijklmnopqrrqponmlkjihgfedcba");
137
138         // styles 32-62 are assigned by the light program for switchable lights
139
140         // 63 testing
141         lightstyle(63, "a");
142
143         player_count = 0;
144         lms_lowest_lives = 0;
145         lms_next_place = 0;
146
147         GotoFirstMap();
148
149         bot_waypoints_for_items = cvar("g_waypoints_for_items");
150         if(bot_waypoints_for_items == 1)
151                 if(self.spawnflags & SPAWNFLAG_NO_WAYPOINTS_FOR_ITEMS)
152                         bot_waypoints_for_items = 0;
153
154         if(cvar("g_campaign"))
155                 CampaignPreInit();
156
157         InitGameplayMode();
158         readlevelcvars();
159         precache();
160
161         WaypointSprite_Init();
162
163         //if (g_domination)
164         //      dom_init();
165
166         local entity head;
167         head = nextent(world);
168         maxclients = 0;
169         while(head)
170         {
171                 maxclients++;
172                 head = nextent(head);
173         }
174
175         GameLogInit(); // prepare everything
176         if(cvar("sv_eventlog"))
177         {
178                 local string s;
179                 GameLogEcho(":logversion:2", FALSE);
180                 s = strcat(cvar_string("sv_eventlog_files_counter"), ".");
181                 s = strcat(s, ftos(random()));
182 #ifdef MAPINFO
183                 GameLogEcho(strcat(":gamestart:", GetGametype(), "_", GetMapname(), ":", s), FALSE);
184 #else
185                 GameLogEcho(strcat(":gamestart:", GetMapname(), ":", s), FALSE);
186 #endif
187                 s = ":gameinfo:mutators:LIST";
188                 if(cvar("g_grappling_hook"))
189                         s = strcat(s, ":grappling_hook");
190                 if(!cvar("g_use_ammunition"))
191                         s = strcat(s, ":no_use_ammunition");
192                 if(!cvar("g_pickup_items"))
193                         s = strcat(s, ":no_pickup_items");
194                 if(cvar("g_instagib"))
195                         s = strcat(s, ":instagib");
196                 if(cvar("g_rocketarena"))
197                         s = strcat(s, ":rockerarena");
198                 if(cvar("g_nixnex"))
199                         s = strcat(s, ":nixnex");
200                 if(cvar("g_vampire"))
201                         s = strcat(s, ":vampire");
202                 if(cvar("g_laserguided_missile"))
203                         s = strcat(s, ":laserguided_missile");
204                 if(cvar("g_norecoil"))
205                         s = strcat(s, ":norecoil");
206                 if(cvar("g_midair"))
207                         s = strcat(s, ":midair");
208                 if(cvar("g_minstagib"))
209                         s = strcat(s, ":minstagib");
210                 GameLogEcho(s, FALSE);
211                 GameLogEcho(":gameinfo:end", FALSE);
212         }
213
214         cvar_set("nextmap", "");
215
216         SetDefaultAlpha();
217
218         if(cvar("g_campaign"))
219                 CampaignPostInit();
220
221         fteqcc_testbugs();
222
223         Ban_LoadBans();
224
225 #ifdef MAPINFO
226         MapInfo_Enumerate();
227         MapInfo_FilterGametype(MapInfo_CurrentGametype(), MapInfo_CurrentFeatures(), 1);
228 #endif
229 }
230
231 void light (void)
232 {
233         //makestatic (self); // Who the f___ did that?
234         remove(self);
235 }
236
237 float( string pFilename ) TryFile =
238 {
239         local float lHandle;
240         dprint("TryFile(\"", pFilename, "\")\n");
241         lHandle = fopen( pFilename, FILE_READ );
242         if( lHandle != -1 ) {
243                 fclose( lHandle );
244                 return TRUE;
245         } else {
246                 return FALSE;
247         }
248 };
249
250 string GetGametype()
251 {
252         if (game == GAME_DEATHMATCH)
253                 return "dm";
254         else if (game == GAME_TEAM_DEATHMATCH)
255                 return "tdm";
256         else if (game == GAME_DOMINATION)
257                 return "dom";
258         else if (game == GAME_CTF)
259                 return "ctf";
260         else if (game == GAME_RUNEMATCH)
261                 return "rune";
262         else if (game == GAME_LMS)
263                 return "lms";
264         else if (game == GAME_KEYHUNT)
265                 return "kh";
266         else if (game == GAME_ONSLAUGHT)
267                 return "ons";
268         else if (game == GAME_ASSAULT)
269                 return "as";
270         return "dm";
271 }
272
273 float IsSameGametype(string mapcfgname)
274 {
275 #ifdef MAPINFO
276         return TRUE; // can't change game type by map name here
277 #else
278         string gt;
279         gt = GetGametype();
280         if(substring(mapcfgname, 0, strlen(gt) + 1) == strcat(gt, "_"))
281                 return TRUE;
282         return FALSE;
283 #endif
284 }
285
286 string getmapname_stored;
287 string GetMapname()
288 {
289 #ifdef MAPINFO
290         return mapname;
291 #else
292         if(getmapname_stored == "")
293                 getmapname_stored = strzone(strcat(GetGametype(), "_", mapname));
294         return getmapname_stored;
295 #endif
296 }
297
298 float Map_Count, Map_Current;
299 string Map_Current_Name;
300
301 // NOTE: this now expects the map list to be already tokenize()d and the count in Map_Count
302 float GetMaplistPosition()
303 {
304         float pos, idx;
305         string map;
306
307         map = GetMapname();
308         idx = cvar("g_maplist_index");
309
310         if(idx >= 0)
311                 if(idx < Map_Count)
312                         if(map == argv(idx))
313                                 return idx;
314
315         for(pos = 0; pos < Map_Count; ++pos)
316                 if(map == argv(pos))
317                         return pos;
318
319         // resume normal maplist rotation if current map is not in g_maplist
320         return idx;
321 }
322
323 float MapHasRightSize(string map)
324 {
325         // open map size restriction file
326         float fh;
327         dprint("opensize "); dprint(map);
328         fh = fopen(strcat("maps/", map, ".sizes"), FILE_READ);
329         if(fh >= 0)
330         {
331                 float mapmin, mapmax;
332                 dprint(": ok, ");
333                 mapmin = stof(fgets(fh));
334                 mapmax = stof(fgets(fh));
335                 fclose(fh);
336                 if(player_count < mapmin)
337                 {
338                         dprint("not enough\n");
339                         return FALSE;
340                 }
341                 if(player_count > mapmax)
342                 {
343                         dprint("too many\n");
344                         return FALSE;
345                 }
346                 dprint("right size\n");
347                 return TRUE;
348         }
349         dprint(": not found\n");
350         return TRUE;
351 }
352
353 string Map_Filename(float position)
354 {
355 #ifdef MAPINFO
356         return strcat("maps/", argv(position), ".bsp");
357 #else
358         return strcat("maps/", argv(position), ".mapcfg");
359 #endif
360 }
361
362 string strwords(string s, float w)
363 {
364         float endpos;
365         for(endpos = 0; w && endpos >= 0; --w)
366                 endpos = strstrofs(s, " ", endpos + 1);
367         if(endpos < 0)
368                 return s;
369         else
370                 return substring(s, 0, endpos);
371 }
372
373 float strhasword(string s, string w)
374 {
375         return strstrofs(strcat(" ", s, " "), strcat(" ", w, " "), 0) >= 0;
376 }
377
378 void Map_MarkAsRecent(string m)
379 {
380         cvar_set("g_maplist_mostrecent", strwords(strcat(m, " ", cvar_string("g_maplist_mostrecent")), cvar("g_maplist_mostrecent_count")));
381 }
382
383 float Map_IsRecent(string m)
384 {
385         return strhasword(cvar_string("g_maplist_mostrecent"), m);
386 }
387
388 float(float position, float pass) Map_Check =
389 {
390         string filename;
391         string map_next;
392         map_next = argv(position);
393         if(pass <= 1)
394         {
395                 if(map_next == Map_Current_Name) // same map again in first pass?
396                         return 0;
397                 if(Map_IsRecent(map_next))
398                         return 0;
399         }
400         filename = Map_Filename(position);
401 #ifdef MAPINFO
402         if(MapInfo_CheckMap(map_next))
403 #else
404         if(TryFile(filename))
405 #endif
406         {
407                 if(pass == 2)
408                         return 1;
409                 if(MapHasRightSize(map_next))
410                         return 1;
411                 return 0;
412         }
413         else
414                 dprint( "Couldn't find '", filename, "'..\n" );
415
416         return 0;
417 }
418
419 void(string nextmapname) Map_Goto_SetStr =
420 {
421         if(getmapname_stored != "")
422                 strunzone(getmapname_stored);
423         if(nextmapname == "")
424                 getmapname_stored = "";
425         else
426                 getmapname_stored = strzone(nextmapname);
427 }
428
429 void(float position) Map_Goto_SetFloat =
430 {
431         cvar_set("g_maplist_index", ftos(position));
432         Map_Goto_SetStr(argv(position));
433 }
434
435 void() GameResetCfg =
436 {
437 #ifdef MAPINFO
438         // settings persist, except...
439         if(cvar("g_campaign"))
440                 localcmd("\nexec mutator_reset.cfg\n");
441         localcmd("\nsettemp_restore\n");
442 #else
443         // if an exit cfg is defined by exiting map, exec it.
444         string exit_cfg;
445         exit_cfg = cvar_string("exit_cfg");
446         if(exit_cfg != "")
447                 localcmd(strcat("exec \"", exit_cfg, "\"\n"));
448
449         localcmd("exec game_reset.cfg\n");
450 #endif
451
452         Ban_SaveBans();
453 };
454
455 void() Map_Goto =
456 {
457         Map_MarkAsRecent(getmapname_stored);
458         GameResetCfg();
459 #ifdef MAPINFO
460         MapInfo_LoadMap(getmapname_stored);
461 #else
462         localcmd(strcat("exec \"maps/", getmapname_stored ,".mapcfg\"\n"));
463 #endif
464 }
465
466 // return codes of map selectors:
467 //   -1 = temporary failure (that is, try some method that is guaranteed to succeed)
468 //   -2 = permanent failure
469 float() MaplistMethod_Iterate = // usual method
470 {
471         float pass, i;
472
473         for(pass = 1; pass <= 2; ++pass)
474         {
475                 for(i = 1; i < Map_Count; ++i)
476                 {
477                         float mapindex;
478                         mapindex = math_mod(i + Map_Current, Map_Count);
479                         if(Map_Check(mapindex, pass))
480                                 return mapindex;
481                 }
482         }
483         return -1;
484 }
485
486 float() MaplistMethod_Repeat = // fallback method
487 {
488         if(Map_Check(Map_Current, 2))
489                 return Map_Current;
490         return -2;
491 }
492
493 float() MaplistMethod_Random = // random map selection
494 {
495         float i, imax;
496
497         imax = 42;
498
499         for(i = 0; i <= imax; ++i)
500         {
501                 float mapindex;
502                 mapindex = math_mod(Map_Current + ceil(random() * (Map_Count - 1)), Map_Count); // any OTHER map
503                 if(Map_Check(mapindex, 1))
504                         return mapindex;
505         }
506         return -1;
507 }
508
509 float(float exponent) MaplistMethod_Shuffle = // more clever shuffling
510 // the exponent sets a bias on the map selection:
511 // the higher the exponent, the less likely "shortly repeated" same maps are
512 {
513         float i, j, imax, insertpos;
514
515         imax = 42;
516
517         for(i = 0; i <= imax; ++i)
518         {
519                 string newlist;
520
521                 // now reinsert this at another position
522                 insertpos = pow(random(), 1 / exponent);       // ]0, 1]
523                 insertpos = insertpos * (Map_Count - 1);       // ]0, Map_Count - 1]
524                 insertpos = ceil(insertpos) + 1;               // {2, 3, 4, ..., Map_Count}
525                 dprint("SHUFFLE: insert pos = ", ftos(insertpos), "\n");
526
527                 // insert the current map there
528                 newlist = "";
529 #ifdef MAPINFO
530                 for(j = 1; j < insertpos; ++j)                 // i == 1: no loop, will be inserted as first; however, i == 1 has been excluded above
531                         newlist = strcat(newlist, " ", argv(j));
532                 newlist = strcat(newlist, " ", argv(0));       // now insert the just selected map
533                 for(j = insertpos; j < Map_Count; ++j)         // i == Map_Count: no loop, has just been inserted as last
534                         newlist = strcat(newlist, " ", argv(j));
535                 newlist = substring(newlist, 1, strlen(newlist) - 1);
536 #else
537                 for(j = 1; j < insertpos; ++j)                 // i == 1: no loop, will be inserted as first; however, i == 1 has been excluded above
538                         newlist = strcat(newlist, "'", argv(j), "'");
539                 newlist = strcat(newlist, "'", argv(0), "'");  // now insert the just selected map
540                 for(j = insertpos; j < Map_Count; ++j)         // i == Map_Count: no loop, has just been inserted as last
541                         newlist = strcat(newlist, "'", argv(j), "'");
542 #endif
543                 cvar_set("g_maplist", newlist);
544 #ifdef MAPINFO
545                 Map_Count = tokenizebyseparator(cvar_string("g_maplist"), " ");
546 #else
547                 Map_Count = tokenize(newlist);
548 #endif
549
550                 // NOTE: the selected map has just been inserted at (insertpos-1)th position
551                 Map_Current = insertpos - 1; // this is not really valid, but this way the fallback has a chance of working
552                 if(Map_Check(Map_Current, 1))
553                         return Map_Current;
554         }
555         return -1;
556 }
557
558 void() Maplist_Init =
559 {
560         string temp;
561         temp = cvar_string("g_maplist");
562 #ifdef MAPINFO
563         Map_Count = tokenizebyseparator(cvar_string("g_maplist"), " ");
564 #else
565         Map_Count = tokenize(temp);
566 #endif
567         if(Map_Count == 0)
568         {
569                 bprint( "Maplist is empty!  Resetting it to default map list.\n" );
570 #ifdef MAPINFO
571                 cvar_set("g_maplist", temp = MapInfo_ListAllowedMaps());
572                 localcmd("\nmenu_cmd sync\n");
573                 Map_Count = tokenizebyseparator(temp, " ");
574 #else
575                 cvar_set("g_maplist", temp = cvar_string("g_maplist_defaultlist"));
576                 Map_Count = tokenize(temp);
577 #endif
578         }
579         if(Map_Count == 0)
580                 error("empty maplist, cannot select a new map");
581         Map_Current = bound(0, GetMaplistPosition(), Map_Count - 1);
582
583         Map_Current_Name = strzone(argv(Map_Current)); // will be automatically freed on exit thanks to DP
584         // this may or may not be correct, but who cares, in the worst case a map
585         // isn't chosen in the first pass that should have been
586 }
587
588 string() GetNextMap =
589 {
590         float nextMap;
591
592         Maplist_Init();
593         nextMap = -1;
594
595         if(nextMap == -1)
596                 if(cvar("g_maplist_shuffle") > 0)
597                         nextMap = MaplistMethod_Shuffle(cvar("g_maplist_shuffle") + 1);
598
599         if(nextMap == -1)
600                 if(cvar("g_maplist_selectrandom"))
601                         nextMap = MaplistMethod_Random();
602
603         if(nextMap == -1)
604                 nextMap = MaplistMethod_Iterate();
605
606         if(nextMap == -1)
607                 nextMap = MaplistMethod_Repeat();
608
609         if(nextMap >= 0)
610         {
611                 Map_Goto_SetFloat(nextMap);
612                 return getmapname_stored;
613         }
614
615         return "";
616 };
617
618 float() DoNextMapOverride =
619 {
620         Ban_SaveBans();
621
622         if(cvar("g_campaign"))
623         {
624                 CampaignPostIntermission();
625                 alreadychangedlevel = TRUE;
626                 return TRUE;
627         }
628         if(cvar("quit_when_empty"))
629         {
630                 if(player_count <= currentbots)
631                 {
632                         localcmd("quit\n");
633                         alreadychangedlevel = TRUE;
634                         return TRUE;
635                 }
636         }
637         if(cvar_string("quit_and_redirect") != "")
638         {
639                 redirection_target = strzone(cvar_string("quit_and_redirect"));
640                 alreadychangedlevel = TRUE;
641                 return TRUE;
642         }
643         if (cvar("samelevel")) // if samelevel is set, stay on same level
644         {
645                 // 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)
646                 //localcmd(strcat("exec \"maps/", mapname, ".mapcfg\"\n"));
647                 // so instead just restart the current map using the restart command (DOES NOT WORK PROPERLY WITH exit_cfg STUFF)
648                 localcmd("restart\n");
649                 //changelevel (mapname);
650                 alreadychangedlevel = TRUE;
651                 return TRUE;
652         }
653         if(cvar_string("nextmap") != "")
654 #ifdef MAPINFO
655                 if(MapInfo_CheckMap(cvar_string("nextmap")))
656 #else
657                 if(TryFile(strcat("maps/", cvar_string("nextmap"), ".mapcfg")))
658 #endif
659                 {
660                         Map_Goto_SetStr(cvar_string("nextmap"));
661                         Map_Goto();
662                         alreadychangedlevel = TRUE;
663                         return TRUE;
664                 }
665         if(cvar("lastlevel"))
666         {
667                 GameResetCfg();
668                 localcmd("set lastlevel 0\ntogglemenu\n");
669                 alreadychangedlevel = TRUE;
670                 return TRUE;
671         }
672         return FALSE;
673 };
674
675 void() GotoNextMap =
676 {
677         //local string nextmap;
678         //local float n, nummaps;
679         //local string s;
680         if (alreadychangedlevel)
681                 return;
682         alreadychangedlevel = TRUE;
683
684         {
685                 string nextMap;
686                 float allowReset;
687
688                 for(allowReset = 1; allowReset >= 0; --allowReset)
689                 {
690                         nextMap = GetNextMap();
691                         if(nextMap != "")
692                                 break;
693
694                         if(allowReset)
695                         {
696                                 bprint( "Maplist contains no single playable map!  Resetting it to default map list.\n" );
697 #ifdef MAPINFO
698                                 cvar_set("g_maplist", MapInfo_ListAllowedMaps());
699                                 localcmd("\nmenu_cmd sync\n");
700 #else
701                                 cvar_set("g_maplist", cvar_string("g_maplist_defaultlist"));
702 #endif
703                         }
704                         else
705                         {
706                                 error("Everything is broken - not even the default map list works. Please report this to the developers.");
707                         }
708                 }
709                 Map_Goto();
710         }
711 };
712
713
714 /*
715 ============
716 IntermissionThink
717
718 When the player presses attack or jump, change to the next level
719 ============
720 */
721 .float autoscreenshot;
722 void() MapVote_Start;
723 void() MapVote_Think;
724 float mapvote_initialized;
725 void() IntermissionThink =
726 {
727         FixIntermissionClient(self);
728
729         if(cvar("sv_autoscreenshot"))
730         if(self.autoscreenshot > 0)
731         if(time > self.autoscreenshot)
732         {
733                 self.autoscreenshot = -1;
734                 if(clienttype(self) == CLIENTTYPE_REAL)
735                         stuffcmd(self, "\nscreenshot\necho \"^5A screenshot has been taken at request of the server.\"\n");
736                 return;
737         }
738
739         if (time < intermission_exittime)
740                 return;
741
742         if(!mapvote_initialized)
743                 if (time < intermission_exittime + 10 && !self.button0 && !self.button2 && !self.button3 && !self.button6 && !self.buttonuse)
744                         return;
745
746         MapVote_Start();
747 };
748
749 /*
750 ============
751 FindIntermission
752
753 Returns the entity to view from
754 ============
755 */
756 /*
757 entity() FindIntermission =
758 {
759         local   entity spot;
760         local   float cyc;
761
762 // look for info_intermission first
763         spot = find (world, classname, "info_intermission");
764         if (spot)
765         {       // pick a random one
766                 cyc = random() * 4;
767                 while (cyc > 1)
768                 {
769                         spot = find (spot, classname, "info_intermission");
770                         if (!spot)
771                                 spot = find (spot, classname, "info_intermission");
772                         cyc = cyc - 1;
773                 }
774                 return spot;
775         }
776
777 // then look for the start position
778         spot = find (world, classname, "info_player_start");
779         if (spot)
780                 return spot;
781
782 // testinfo_player_start is only found in regioned levels
783         spot = find (world, classname, "testplayerstart");
784         if (spot)
785                 return spot;
786
787 // then look for the start position
788         spot = find (world, classname, "info_player_deathmatch");
789         if (spot)
790                 return spot;
791
792         //objerror ("FindIntermission: no spot");
793         return world;
794 };
795 */
796
797 /*
798 ===============================================================================
799
800 RULES
801
802 ===============================================================================
803 */
804
805 void(float final) DumpStats =
806 {
807         local float file;
808         local string s;
809         local float to_console;
810         local float to_eventlog;
811         local float to_file;
812
813         to_console = cvar("sv_logscores_console");
814         to_eventlog = cvar("sv_eventlog");
815         to_file = cvar("sv_logscores_file");
816
817         if(!final)
818         {
819                 to_console = TRUE; // always print printstats replies
820                 to_eventlog = FALSE; // but never print them to the event log
821         }
822
823         if(to_eventlog)
824                 if(cvar("sv_eventlog_console"))
825                         to_console = FALSE; // otherwise we get the output twice
826
827         if(final)
828                 s = ":scores:";
829         else
830                 s = ":status:";
831 #ifdef MAPINFO
832         s = strcat(s, GetGametype(), "_", GetMapname(), ":", ftos(rint(time)));
833 #else
834         s = strcat(s, GetMapname(), ":", ftos(rint(time)));
835 #endif
836
837         if(to_console)
838                 ServerConsoleEcho(s, FALSE);
839         if(to_eventlog)
840                 GameLogEcho(s, FALSE);
841         if(to_file)
842         {
843                 file = fopen(cvar_string("sv_logscores_filename"), FILE_APPEND);
844                 if(file == -1)
845                         to_file = FALSE;
846                 else
847                         fputs(file, strcat(s, "\n"));
848         }
849
850         FOR_EACH_CLIENT(other)
851         {
852                 if ((clienttype(other) == CLIENTTYPE_REAL) || (clienttype(other) == CLIENTTYPE_BOT && cvar("sv_logscores_bots")))
853                 {
854                         s = strcat(":player:", ftos(other.frags), ":");
855                         s = strcat(s, ftos(other.deaths), ":");
856                         s = strcat(s, ftos(rint(time - other.jointime)), ":");
857                         s = strcat(s, ftos(other.team), ":");
858
859                         if(to_console)
860                                 ServerConsoleEcho(strcat(s, other.netname), TRUE);
861                         if(to_eventlog)
862                                 GameLogEcho(strcat(s, ftos(other.playerid), ":", other.netname), TRUE);
863                         if(to_file)
864                                 fputs(file, strcat(s, other.netname, "\n"));
865                 }
866         }
867
868         if(to_console)
869                 ServerConsoleEcho(":end", FALSE);
870         if(to_eventlog)
871                 GameLogEcho(":end", FALSE);
872         if(to_file)
873         {
874                 fputs(file, ":end\n");
875                 fclose(file);
876         }
877 }
878
879 void FixIntermissionClient(entity e)
880 {
881         if(!e.autoscreenshot) // initial call
882         {
883                 e.angles = e.v_angle;
884                 e.angles_x = -e.angles_x;
885                 e.autoscreenshot = time + 0.8;  // used for autoscreenshot
886                 e.health = -2342;
887                 // first intermission phase; voting phase has positive health (used to decide whether to send SVC_FINALE or not)
888                 e.solid = SOLID_NOT;
889                 e.movetype = MOVETYPE_NONE;
890                 e.takedamage = DAMAGE_NO;
891                 if(e.weaponentity)
892                         e.weaponentity.effects = EF_NODRAW;
893                 stuffcmd(e, "\nscr_printspeed 1000000\n");
894                 if(clienttype(e) == CLIENTTYPE_REAL)
895                 {
896                         msg_entity = e;
897                         WriteByte(MSG_ONE, SVC_INTERMISSION);
898                 }
899         }
900
901         //e.velocity = '0 0 0';
902         //e.fixangle = TRUE;
903
904         // TODO halt weapon animation
905 }
906
907
908 /*
909 go to the next level for deathmatch
910 only called if a time or frag limit has expired
911 */
912 void() NextLevel =
913 {
914         float minTotalFrags;
915         float maxTotalFrags;
916         float score;
917         float f;
918
919         gameover = TRUE;
920
921         intermission_running = 1;
922
923 // enforce a wait time before allowing changelevel
924         if(player_count > 0)
925                 intermission_exittime = time + cvar("sv_mapchange_delay");
926         else
927                 intermission_exittime = -1;
928
929         WriteByte (MSG_ALL, SVC_CDTRACK);
930         WriteByte (MSG_ALL, 3);
931         WriteByte (MSG_ALL, 3);
932
933         //pos = FindIntermission ();
934
935         VoteReset();
936
937         DumpStats(TRUE);
938
939         if(cvar("sv_eventlog"))
940                 GameLogEcho(":gameover", FALSE);
941
942         GameLogClose();
943
944         FOR_EACH_CLIENT(other)
945         {
946                 FixIntermissionClient(other);
947
948                 if(other.winning)
949                         bprint(other.netname, " ^7wins.\n");
950         }
951
952         minTotalFrags = 0;
953         maxTotalFrags = 0;
954         FOR_EACH_PLAYER(other)
955         {
956                 if(maxTotalFrags < other.totalfrags)
957                         maxTotalFrags = other.totalfrags;
958                 if(minTotalFrags > other.totalfrags)
959                         minTotalFrags = other.totalfrags;
960         }
961
962         if(!currentbots)
963         {
964                 FOR_EACH_PLAYER(other)
965                 {
966                         score = (other.totalfrags - minTotalFrags) / max(maxTotalFrags - minTotalFrags, 1);
967                         f = bound(0, other.play_time / max(time, 1), 1);
968                         // store some statistics?
969                 }
970         }
971
972         if(cvar("g_campaign"))
973                 CampaignPreIntermission();
974
975         // WriteByte (MSG_ALL, SVC_INTERMISSION);
976 };
977
978 /*
979 ============
980 CheckRules_Player
981
982 Exit deathmatch games upon conditions
983 ============
984 */
985 void() CheckRules_Player =
986 {
987         if (gameover)   // someone else quit the game already
988                 return;
989
990         if(self.deadflag == DEAD_NO)
991                 self.play_time += frametime;
992
993         // fixme: don't check players; instead check dom_team and ctf_team entities
994         //   (div0: and that in CheckRules_World please)
995 };
996
997 float checkrules_oneminutewarning;
998 float checkrules_leaderfrags;
999 float tdm_max_score, tdm_old_score;
1000
1001 float checkrules_equality;
1002 float checkrules_overtimewarning;
1003 float checkrules_overtimeend;
1004
1005 void() InitiateOvertime =
1006 {
1007         if(!checkrules_overtimeend)
1008                 checkrules_overtimeend = time + 60 * cvar("timelimit_maxovertime");
1009 }
1010
1011 float WINNING_NO = 0; // no winner, but time limits may terminate the game
1012 float WINNING_YES = 1; // winner found
1013 float WINNING_NEVER = 2; // no winner, enter overtime if time limit is reached
1014 float WINNING_STARTOVERTIME = 3; // no winner, enter overtime NOW
1015
1016 float(float fraglimitreached, float equality) GetWinningCode =
1017 {
1018         if(equality)
1019                 if(fraglimitreached)
1020                         return WINNING_STARTOVERTIME;
1021                 else
1022                         return WINNING_NEVER;
1023         else
1024                 if(fraglimitreached)
1025                         return WINNING_YES;
1026                 else
1027                         return WINNING_NO;
1028 }
1029
1030 // set the .winning flag for exactly those players with a given field value
1031 void(.float field, float value) SetWinners =
1032 {
1033         entity head;
1034         FOR_EACH_PLAYER(head)
1035                 head.winning = (head.field == value);
1036 }
1037
1038 // set the .winning flag for those players with a given field value
1039 void(.float field, float value) AddWinners =
1040 {
1041         entity head;
1042         FOR_EACH_PLAYER(head)
1043                 if(head.field == value)
1044                         head.winning = 1;
1045 }
1046
1047 // clear the .winning flags
1048 void(void) ClearWinners =
1049 {
1050         entity head;
1051         FOR_EACH_PLAYER(head)
1052                 head.winning = 0;
1053 }
1054
1055 // Onslaught winning condition:
1056 // game terminates if only one team has a working generator (or none)
1057 float() WinningCondition_Onslaught =
1058 {
1059         entity head;
1060         local float t1, t2, t3, t4;
1061         // first check if the game has ended
1062         t1 = t2 = t3 = t4 = 0;
1063         head = find(world, classname, "onslaught_generator");
1064         while (head)
1065         {
1066                 if (head.health > 0)
1067                 {
1068                         if (head.team == COLOR_TEAM1) t1 = 1;
1069                         if (head.team == COLOR_TEAM2) t2 = 1;
1070                         if (head.team == COLOR_TEAM3) t3 = 1;
1071                         if (head.team == COLOR_TEAM4) t4 = 1;
1072                 }
1073                 head = find(head, classname, "onslaught_generator");
1074         }
1075         if (t1 + t2 + t3 + t4 < 2)
1076         {
1077                 // game over, only one team remains (or none)
1078                 ClearWinners();
1079                 if (t1) SetWinners(team, COLOR_TEAM1);
1080                 if (t2) SetWinners(team, COLOR_TEAM2);
1081                 if (t3) SetWinners(team, COLOR_TEAM3);
1082                 if (t4) SetWinners(team, COLOR_TEAM4);
1083                 dprint("Have a winner, ending game.\n");
1084                 return WINNING_YES;
1085         }
1086
1087         // Two or more teams remain
1088         return WINNING_NO;
1089 }
1090
1091 float() LMS_NewPlayerLives =
1092 {
1093         float fl;
1094         fl = cvar("fraglimit");
1095         if(fl == 0)
1096                 fl = 999;
1097
1098         // first player has left the game for dying too much? Nobody else can get in.
1099         if(lms_lowest_lives < 1)
1100                 return FALSE;
1101
1102         if(!cvar("g_lms_join_anytime"))
1103                 if(lms_lowest_lives < fl - cvar("g_lms_last_join"))
1104                         return FALSE;
1105
1106         return bound(1, lms_lowest_lives, fl);
1107 }
1108
1109 // Assault winning condition: If the attackers triggered a round end (by fulfilling all objectives)
1110 // they win. Otherwise the defending team wins once the timelimit passes.
1111 void assault_new_round();
1112 float() WinningCondition_Assault =
1113 {
1114         local float status;
1115         status = WINNING_NO;
1116
1117         // as the timelimit has not yet passed just assume the defending team will win
1118         if(assault_attacker_team == COLOR_TEAM1)
1119         {
1120                 SetWinners(team, COLOR_TEAM2);
1121         }
1122         else
1123         {
1124                 SetWinners(team, COLOR_TEAM1);
1125         }       
1126                 
1127         local entity ent;
1128         ent = find(world, classname, "target_assault_roundend");
1129         if(ent)
1130         {
1131                 if(ent.winning) // round end has been triggered by attacking team
1132                 {
1133                         SetWinners(team, assault_attacker_team);
1134                         if(assault_attacker_team == COLOR_TEAM1)
1135                         {
1136                                 team1_score = team1_score + 50;
1137                         }
1138                         else
1139                         {
1140                                 team2_score = team2_score + 50;
1141                         }
1142
1143                         if(ent.cnt == 1) // this was the second round
1144                         {
1145                                 status = WINNING_YES;
1146                         }
1147                         else
1148                         {
1149                                 cvar_set("timelimit", ftos((2*time)/60));
1150                                 assault_new_round();
1151                         }
1152                 }               
1153         }
1154
1155         return status;
1156
1157 }
1158
1159
1160 // LMS winning condition: game terminates if and only if there's at most one
1161 // one player who's living lives. Top two scores being equal cancels the time
1162 // limit.
1163 float() WinningCondition_LMS =
1164 {
1165         entity head;
1166         float have_player;
1167         float have_players;
1168         float l;
1169
1170         have_player = FALSE;
1171         have_players = FALSE;
1172         l = LMS_NewPlayerLives();
1173
1174         head = find(world, classname, "player");
1175         if(head)
1176                 have_player = TRUE;
1177         head = find(head, classname, "player");
1178         if(head)
1179                 have_players = TRUE;
1180
1181         if(have_player)
1182         {
1183                 // we have at least one player
1184                 if(have_players)
1185                 {
1186                         // two or more active players - continue with the game
1187                 }
1188                 else
1189                 {
1190                         // exactly one player?
1191                         if(l)
1192                         {
1193                                 // but no game has taken place yet
1194                         }
1195                         else
1196                         {
1197                                 // a winner!
1198                                 ClearWinners(); SetWinners(winning, 0); // NOTE: exactly one player is still "player", so this works out
1199                                 dprint("Have a winner, ending game.\n");
1200                                 return WINNING_YES;
1201                         }
1202                 }
1203         }
1204         else
1205         {
1206                 // nobody is playing at all...
1207                 if(l)
1208                 {
1209                         // wait for players...
1210                 }
1211                 else
1212                 {
1213                         // SNAFU (maybe a draw game?)
1214                         ClearWinners();
1215                         dprint("No players, ending game.\n");
1216                         return WINNING_YES;
1217                 }
1218         }
1219
1220         // When we get here, we have at least two players who are actually LIVING,
1221         // or one player who is still waiting for a victim to join the server. Now
1222         // check if the top two players have equal score.
1223
1224         checkrules_leaderfrags = 0;
1225         checkrules_equality = FALSE;
1226         FOR_EACH_PLAYER(head)
1227         {
1228                 if(head.frags > checkrules_leaderfrags)
1229                 {
1230                         checkrules_leaderfrags = head.frags;
1231                         checkrules_equality = FALSE;
1232                 }
1233                 else if(head.frags > 0 && head.frags == checkrules_leaderfrags)
1234                         checkrules_equality = TRUE;
1235         }
1236
1237         SetWinners(frags, checkrules_leaderfrags);
1238
1239         // The top two players have the same amount of lives? No timelimit then,
1240         // enter overtime...
1241
1242         if(checkrules_equality)
1243                 return WINNING_NEVER;
1244
1245         // Top two have different scores? Way to go for our beloved TIMELIMIT!
1246         return WINNING_NO;
1247 }
1248
1249 // DM winning condition: game terminates if a player reached the fraglimit,
1250 // unless the first two players have the same score. The latter case also
1251 // breaks the time limit.
1252 float(float fraglimit) WinningCondition_MaxIndividualScore =
1253 {
1254         float checkrules_oldleaderfrags;
1255         entity head;
1256
1257         checkrules_oldleaderfrags = checkrules_leaderfrags;
1258         checkrules_leaderfrags = 0;
1259         checkrules_equality = FALSE;
1260         FOR_EACH_PLAYER(head)
1261         {
1262                 if(head.frags > checkrules_leaderfrags)
1263                 {
1264                         checkrules_leaderfrags = head.frags;
1265                         checkrules_equality = FALSE;
1266                 }
1267                 else if(head.frags > 0 && head.frags == checkrules_leaderfrags)
1268                         checkrules_equality = TRUE;
1269         }
1270
1271         if(checkrules_leaderfrags > 0)
1272                 SetWinners(frags, checkrules_leaderfrags);
1273         else
1274                 ClearWinners();
1275
1276         if (!g_runematch)
1277                 if (checkrules_leaderfrags != checkrules_oldleaderfrags)
1278                 {
1279                         if (checkrules_leaderfrags == fraglimit - 1)
1280                                 sound(world, CHAN_AUTO, "announcer/robotic/1fragleft.wav", 1, ATTN_NONE);
1281                         else if (checkrules_leaderfrags == fraglimit - 2)
1282                                 sound(world, CHAN_AUTO, "announcer/robotic/2fragsleft.wav", 1, ATTN_NONE);
1283                         else if (checkrules_leaderfrags == fraglimit - 3)
1284                                 sound(world, CHAN_AUTO, "announcer/robotic/3fragsleft.wav", 1, ATTN_NONE);
1285                 }
1286
1287         return GetWinningCode(fraglimit && checkrules_leaderfrags >= fraglimit, checkrules_equality);
1288 }
1289
1290 float(float fraglimit) WinningConditionBase_Teamplay =
1291 {
1292         tdm_old_score = tdm_max_score;
1293         tdm_max_score = max4(team1_score, team2_score, team3_score, team4_score);
1294
1295         checkrules_equality =
1296         (
1297                 (tdm_max_score > 0)
1298                 &&
1299                 (
1300                           (team1_score == tdm_max_score)
1301                         + (team2_score == tdm_max_score)
1302                         + (team3_score == tdm_max_score)
1303                         + (team4_score == tdm_max_score)
1304                         >= 2));
1305
1306         ClearWinners();
1307         if(tdm_max_score > 0)
1308         {
1309                 if(team1_score == tdm_max_score)
1310                         AddWinners(team, COLOR_TEAM1);
1311                 if(team2_score == tdm_max_score)
1312                         AddWinners(team, COLOR_TEAM2);
1313                 if(team3_score == tdm_max_score)
1314                         AddWinners(team, COLOR_TEAM3);
1315                 if(team4_score == tdm_max_score)
1316                         AddWinners(team, COLOR_TEAM4);
1317         }
1318
1319         if(!g_runematch && !g_domination)
1320                 if(tdm_max_score != tdm_old_score)
1321                 {
1322                         if(tdm_max_score == fraglimit - 1)
1323                                 sound(world, CHAN_AUTO, "announcer/robotic/1fragleft.wav", 1, ATTN_NONE);
1324                         else if(tdm_max_score == fraglimit - 2)
1325                                 sound(world, CHAN_AUTO, "announcer/robotic/2fragsleft.wav", 1, ATTN_NONE);
1326                         else if(tdm_max_score == fraglimit - 3)
1327                                 sound(world, CHAN_AUTO, "announcer/robotic/3fragsleft.wav", 1, ATTN_NONE);
1328                 }
1329
1330         return GetWinningCode(fraglimit && tdm_max_score >= fraglimit, checkrules_equality);
1331 }
1332
1333 // TDM winning condition: game terminates if a team's score sum reached the
1334 // fraglimit, unless the first two teams have the same total score. The latter
1335 // case also breaks the time limit.
1336 float(float fraglimit) WinningCondition_MaxTeamSum =
1337 {
1338         entity head;
1339
1340         team1_score = team2_score = team3_score = team4_score = 0;
1341
1342         FOR_EACH_PLAYER(head)
1343         {
1344                 if(head.team == COLOR_TEAM1)
1345                         team1_score += head.frags;
1346                 else if(head.team == COLOR_TEAM2)
1347                         team2_score += head.frags;
1348                 else if(head.team == COLOR_TEAM3)
1349                         team3_score += head.frags;
1350                 else if(head.team == COLOR_TEAM4)
1351                         team4_score += head.frags;
1352         }
1353
1354         return WinningConditionBase_Teamplay(fraglimit);
1355 }
1356
1357 // DOM/CTF winning condition: game terminates if the max of a team's players'
1358 // score reached the fraglimit, unless the first two teams have the same
1359 // maximum score. The latter case also breaks the time limit.
1360 float(float fraglimit) WinningCondition_MaxTeamMax =
1361 {
1362         entity head;
1363
1364         team1_score = team2_score = team3_score = team4_score = 0;
1365
1366         FOR_EACH_PLAYER(head)
1367         {
1368                 if(head.team == COLOR_TEAM1)
1369                 {
1370                         if(head.frags > team1_score)
1371                                 team1_score = head.frags;
1372                 }
1373                 else if(head.team == COLOR_TEAM2)
1374                 {
1375                         if(head.frags > team2_score)
1376                                 team2_score = head.frags;
1377                 }
1378                 else if(head.team == COLOR_TEAM3)
1379                 {
1380                         if(head.frags > team3_score)
1381                                 team3_score = head.frags;
1382                 }
1383                 else if(head.team == COLOR_TEAM4)
1384                 {
1385                         if(head.frags > team4_score)
1386                                 team4_score = head.frags;
1387                 }
1388         }
1389
1390         return WinningConditionBase_Teamplay(fraglimit);
1391 }
1392
1393 void print_to(entity e, string s)
1394 {
1395         if(e)
1396                 sprint(e, strcat(s, "\n"));
1397         else
1398                 ServerConsoleEcho(s, TRUE);
1399 }
1400
1401 void PrintScoreboardFor(entity e, string name, string colorcode, float whichteam)
1402 {
1403         entity head;
1404         float v;
1405         float teamvalue;
1406         float fragtotal;
1407         string s;
1408         float found;
1409         found = FALSE;
1410         teamvalue = 0;
1411         FOR_EACH_PLAYER(head)
1412         {
1413                 if(!whichteam || head.team == whichteam)
1414                 {
1415                         if(name != "")
1416                                 if(!found)
1417                                         print_to(e, strcat(" ", colorcode, name, ":"));
1418                         found = TRUE;
1419                         fragtotal = fragtotal + head.frags;
1420                         s = ftos(head.frags);
1421                         s = strcat(s, "/", ftos(head.deaths));
1422                         s = strcat(s, " @ ", ftos(head.ping));
1423                         if(clienttype(head) == CLIENTTYPE_BOT)
1424                                 s = strcat(s, "botms");
1425                         else
1426                                 s = strcat(s, "ms");
1427                         v = PlayerValue(head);
1428                         teamvalue += v;
1429                         s = strcat(s, " / ", ftos(v));
1430                         print_to(e, strcat("  ", colorcode, head.netname, colorcode, " (", s, ")"));
1431                 }
1432         }
1433         if(whichteam && found)
1434         {
1435                 s = ftos(fragtotal);
1436                 s = strcat(s, " / ", ftos(teamvalue));
1437                 print_to(e, strcat(colorcode, "  (total: ", s, ")"));
1438         }
1439 }
1440
1441 void PrintScoreboard(entity e)
1442 {
1443         print_to(e, strcat("Time:      ", ftos(time / 60)));
1444         print_to(e, strcat("Timelimit: ", ftos(cvar("timelimit"))));
1445         print_to(e, strcat("Fraglimit: ", ftos(cvar("fraglimit"))));
1446         print_to(e, "Scoreboard:");
1447         if(teams_matter)
1448         {
1449                 PrintScoreboardFor(e, "Red", "^1", COLOR_TEAM1);
1450                 PrintScoreboardFor(e, "Blue", "^4", COLOR_TEAM2);
1451                 PrintScoreboardFor(e, "Yellow", "^3", COLOR_TEAM3);
1452                 PrintScoreboardFor(e, "Pink", "^6", COLOR_TEAM4);
1453         }
1454         else
1455         {
1456                 PrintScoreboardFor(e, "", "^7", 0);
1457         }
1458         print_to(e, ".");
1459 }
1460
1461 void ShuffleMaplist()
1462 {
1463         string result;
1464         float start;
1465         float litems;
1466         float selected;
1467         float i;
1468
1469         result = cvar_string("g_maplist");
1470 #ifdef MAPINFO
1471         litems = tokenizebyseparator(result, " ");
1472 #else
1473         litems = tokenize(result);
1474 #endif
1475
1476         for(start = 0; start < litems - 1; ++start)
1477         {
1478                 result = "";
1479
1480                 // select a random item
1481                 selected = ceil(random() * (litems - start) + start) - 1;
1482
1483                 // shift this item to the place start
1484 #ifdef MAPINFO
1485                 for(i = 0; i < start; ++i)
1486                         result = strcat(result, " ", argv(i));
1487                 result = strcat(result, " ", argv(selected));
1488                 for(i = start; i < litems; ++i)
1489                         if(i != selected)
1490                                 result = strcat(result, " ", argv(i));
1491                 result = substring(result, 1, strlen(result) - 1);
1492
1493                 litems = tokenizebyseparator(result, " ");
1494 #else
1495                 for(i = 0; i < start; ++i)
1496                         result = strcat(result, "'", argv(i), "'");
1497                 result = strcat(result, "'", argv(selected), "'");
1498                 for(i = start; i < litems; ++i)
1499                         if(i != selected)
1500                                 result = strcat(result, "'", argv(i), "'");
1501
1502                 litems = tokenize(result);
1503 #endif
1504
1505                 //dprint(result, "\n");
1506         }
1507
1508         cvar_set("g_maplist", result);
1509 }
1510
1511 /*
1512 ============
1513 CheckRules_World
1514
1515 Exit deathmatch games upon conditions
1516 ============
1517 */
1518 void() CheckRules_World =
1519 {
1520         local float status;
1521         local float timelimit;
1522         local float fraglimit;
1523
1524         VoteThink();
1525         MapVote_Think();
1526
1527         SetDefaultAlpha();
1528
1529         /*
1530         MapVote_Think should now do that part
1531         if (intermission_running)
1532                 if (time >= intermission_exittime + 60)
1533                 {
1534                         if(!DoNextMapOverride())
1535                                 GotoNextMap();
1536                         return;
1537                 }
1538         */
1539
1540         if (gameover)   // someone else quit the game already
1541         {
1542                 if(player_count == 0) // Nobody there? Then let's go to the next map
1543                         MapVote_Start();
1544                         // this will actually check the player count in the next frame
1545                         // again, but this shouldn't hurt
1546                 return;
1547         }
1548
1549         timelimit = cvar("timelimit") * 60;
1550         fraglimit = cvar("fraglimit");
1551
1552         if(checkrules_overtimeend)
1553         {
1554                 if(!checkrules_overtimewarning)
1555                 {
1556                         checkrules_overtimewarning = TRUE;
1557                         //sound(world, CHAN_AUTO, "announcer/robotic/1minuteremains.wav", 1, ATTN_NONE);
1558                         bcenterprint("^3Now playing ^1OVERTIME^3!\n\n^3Keep fragging until we have a ^1winner^3!");
1559                 }
1560         }
1561         else
1562         {
1563                 if (timelimit && time >= timelimit)
1564                         InitiateOvertime();
1565         }
1566
1567         if (checkrules_overtimeend && time >= checkrules_overtimeend)
1568         {
1569                 NextLevel();
1570                 return;
1571         }
1572
1573         if (!checkrules_oneminutewarning && timelimit > 0 && time > timelimit - 60)
1574         {
1575                 checkrules_oneminutewarning = TRUE;
1576                 sound(world, CHAN_AUTO, "announcer/robotic/1minuteremains.wav", 1, ATTN_NONE);
1577         }
1578
1579         status = WINNING_NO;
1580         if(g_assault)
1581         {
1582                 status = WinningCondition_Assault();
1583         }
1584         else if(g_lms)
1585         {
1586                 status = WinningCondition_LMS();
1587         }
1588         else if (g_onslaught)
1589         {
1590                 status = WinningCondition_Onslaught();
1591         }
1592         else
1593         {
1594                 if(teams_matter)
1595                 {
1596                         if(g_tdm || g_runematch || g_ctf || g_domination || g_keyhunt)
1597                                 status = WinningCondition_MaxTeamSum(fraglimit);
1598                         //else if()
1599                         //      status = WinningCondition_MaxTeamMax(fraglimit);
1600                         else
1601                         {
1602                                 dprint("div0: How can this happen?\n");
1603                                 status = WinningCondition_MaxTeamMax(fraglimit);
1604                         }
1605                 }
1606                 else
1607                         status = WinningCondition_MaxIndividualScore(fraglimit);
1608         }
1609
1610         if(status == WINNING_STARTOVERTIME)
1611         {
1612                 status = WINNING_NEVER;
1613                 InitiateOvertime();
1614         }
1615
1616         if(status == WINNING_NEVER)
1617                 // equality cases! Nobody wins if the overtime ends in a draw.
1618                 ClearWinners();
1619
1620         if(checkrules_overtimeend)
1621                 if(status != WINNING_NEVER || time >= checkrules_overtimeend)
1622                         status = WINNING_YES;
1623
1624         if(status == WINNING_YES)
1625                 NextLevel();
1626 };
1627
1628 float randsel_value;
1629 float randsel_priority;
1630 float randsel_count;
1631 void RandSel_Init()
1632 {
1633         randsel_value = -1;
1634         randsel_priority = -1;
1635         randsel_count = -1;
1636 }
1637 void RandSel_Add(float priority, float value)
1638 {
1639         if(priority > randsel_priority)
1640         {
1641                 randsel_priority = priority;
1642                 randsel_value = value;
1643                 randsel_count = 1;
1644         }
1645         else if(priority == randsel_priority)
1646         {
1647                 randsel_count += 1;
1648                 if(ceil(random() * randsel_count) == 1)
1649                         randsel_value = value;
1650         }
1651 }
1652
1653 float mapvote_nextthink;
1654 float mapvote_initialized;
1655 float mapvote_keeptwotime;
1656 float mapvote_timeout;
1657 string mapvote_message;
1658
1659 #define MAPVOTE_COUNT 10
1660 float mapvote_count;
1661 float mapvote_count_real;
1662 string mapvote_maps[MAPVOTE_COUNT];
1663 float mapvote_maps_suggested[MAPVOTE_COUNT];
1664 string mapvote_suggestions[MAPVOTE_COUNT];
1665 float mapvote_suggestion_ptr;
1666 float mapvote_maxlen;
1667 float mapvote_voters;
1668 float mapvote_votes[MAPVOTE_COUNT];
1669 float mapvote_run;
1670 float mapvote_detail;
1671 float mapvote_abstain;
1672 .float mapvote;
1673
1674 void MapVote_ClearAllVotes()
1675 {
1676         FOR_EACH_CLIENT(other)
1677                 other.mapvote = 0;
1678 }
1679
1680 string MapVote_Suggest(string m)
1681 {
1682         float i;
1683         if(m == "")
1684                 return "That's not how to use this command.";
1685         if(!cvar("g_maplist_votable_suggestions"))
1686                 return "Suggestions are not accepted on this server.";
1687         if(mapvote_initialized)
1688                 return "Can't suggest - voting is already in progress!";
1689 #ifdef MAPINFO
1690         m = MapInfo_FixName(m);
1691         if(!m)
1692                 return "The map you suggested is not available on this server.";
1693 #endif
1694         if(!cvar("g_maplist_votable_suggestions_change_gametype"))
1695                 if(!IsSameGametype(m))
1696                         return "This server does not allow changing the game type by map suggestions.";
1697         if(!cvar("g_maplist_votable_override_mostrecent"))
1698                 if(Map_IsRecent(m))
1699                         return "This server does not allow for recent maps to be played again. Please be patient for some rounds.";
1700
1701 #ifdef MAPINFO
1702         if(!MapInfo_CheckMap(m))
1703                 return "The map you suggested does not support the current game mode.";
1704 #else
1705         if(!TryFile(strcat("maps/", m, ".mapcfg")))
1706                 return "The map you suggested is not available on this server.";
1707 #endif
1708         for(i = 0; i < mapvote_suggestion_ptr; ++i)
1709                 if(mapvote_suggestions[i] == m)
1710                         return "This map was already suggested.";
1711         if(mapvote_suggestion_ptr >= MAPVOTE_COUNT)
1712         {
1713                 i = ceil(random() * mapvote_suggestion_ptr) - 1;
1714         }
1715         else
1716         {
1717                 i = mapvote_suggestion_ptr;
1718                 mapvote_suggestion_ptr += 1;
1719         }
1720         if(mapvote_suggestions[i] != "")
1721                 strunzone(mapvote_suggestions[i]);
1722         mapvote_suggestions[i] = strzone(m);
1723         GameLogEcho(strcat(":vote:suggested:", m, ":", ftos(self.playerid), ":", self.netname), TRUE);
1724         return strcat("Suggestion of ", m, " accepted.");
1725 }
1726
1727 void MapVote_AddVotable(string nextMap, float isSuggestion)
1728 {
1729         float j;
1730         if(nextMap == "")
1731                 return;
1732         for(j = 0; j < mapvote_count; ++j)
1733                 if(mapvote_maps[j] == nextMap)
1734                         return;
1735         if(strlen(nextMap) > mapvote_maxlen)
1736                 mapvote_maxlen = strlen(nextMap);
1737         mapvote_maps[mapvote_count] = strzone(nextMap);
1738         mapvote_maps_suggested[mapvote_count] = isSuggestion;
1739         mapvote_count += 1;
1740 }
1741
1742 void MapVote_Init()
1743 {
1744         float i;
1745         float nmax, smax;
1746
1747         MapVote_ClearAllVotes();
1748
1749         mapvote_count = 0;
1750         mapvote_detail = !cvar("g_maplist_votable_nodetail");
1751         mapvote_abstain = cvar("g_maplist_votable_abstain");
1752         
1753         if(mapvote_abstain)
1754                 nmax = min(MAPVOTE_COUNT - 1, cvar("g_maplist_votable"));
1755         else
1756                 nmax = min(MAPVOTE_COUNT, cvar("g_maplist_votable"));
1757         smax = min(nmax, cvar("g_maplist_votable_suggestions"));
1758
1759         for(i = 0; i < 100 && mapvote_count < smax; ++i)
1760                 MapVote_AddVotable(mapvote_suggestions[ceil(random() * mapvote_suggestion_ptr) - 1], TRUE);
1761
1762         for(i = 0; i < 100 && mapvote_count < nmax; ++i)
1763                 MapVote_AddVotable(GetNextMap(), FALSE);
1764
1765         if(mapvote_count == 0)
1766         {
1767                 bprint( "Maplist contains no single playable map!  Resetting it to default map list.\n" );
1768 #ifdef MAPINFO
1769                 cvar_set("g_maplist", MapInfo_ListAllowedMaps());
1770                 localcmd("\nmenu_cmd sync\n");
1771 #else
1772                 cvar_set("g_maplist", cvar_string("g_maplist_defaultlist"));
1773 #endif
1774                 for(i = 0; i < 100 && mapvote_count < nmax; ++i)
1775                         MapVote_AddVotable(GetNextMap(), FALSE);
1776         }
1777
1778         mapvote_count_real = mapvote_count;
1779         if(mapvote_abstain)
1780                 MapVote_AddVotable("don't care", 0);
1781
1782         //dprint("mapvote count is ", ftos(mapvote_count), "\n");
1783
1784         mapvote_keeptwotime = time + cvar("g_maplist_votable_keeptwotime");
1785         mapvote_timeout = time + cvar("g_maplist_votable_timeout");
1786         if(mapvote_count_real < 3 || mapvote_keeptwotime <= time)
1787                 mapvote_keeptwotime = 0;
1788         mapvote_message = "Choose a map and press its key!";
1789 }
1790 float MapVote_Finished(float mappos)
1791 {
1792         string result;
1793         float i;
1794
1795         result = strcat(":vote:finished:", mapvote_maps[mappos]);
1796         result = strcat(result, ":", ftos(mapvote_votes[mappos]), "::");
1797         for(i = 0; i < mapvote_count_real; ++i)
1798                 if(i != mappos)
1799                         if(mapvote_maps[i] != "")
1800                         {
1801                                 result = strcat(result, ":", mapvote_maps[i]);
1802                                 result = strcat(result, ":", ftos(mapvote_votes[i]));
1803                         }
1804         GameLogEcho(result, FALSE);
1805         if(mapvote_maps_suggested[mappos])
1806                 GameLogEcho(strcat(":vote:suggestion_accepted:", mapvote_maps[mappos]), FALSE);
1807
1808         FOR_EACH_REALCLIENT(other)
1809                 FixClientCvars(other);
1810
1811         Map_Goto_SetStr(mapvote_maps[mappos]);
1812         Map_Goto();
1813         alreadychangedlevel = TRUE;
1814         return TRUE;
1815 }
1816 void MapVote_CheckRules_1()
1817 {
1818         float i;
1819
1820         for(i = 0; i < mapvote_count; ++i) if(mapvote_maps[i] != "")
1821         {
1822                 //dprint("Map ", ftos(i), ": "); dprint(mapvote_maps[i], "\n");
1823                 mapvote_votes[i] = 0;
1824         }
1825
1826         mapvote_voters = 0;
1827         FOR_EACH_REALCLIENT(other)
1828         {
1829                 ++mapvote_voters;
1830                 if(other.mapvote)
1831                 {
1832                         i = other.mapvote - 1;
1833                         //dprint("Player ", other.netname, " vote = ", ftos(other.mapvote - 1), "\n");
1834                         mapvote_votes[i] = mapvote_votes[i] + 1;
1835                 }
1836         }
1837 }
1838
1839 float MapVote_CheckRules_2()
1840 {
1841         float i;
1842         float firstPlace, secondPlace;
1843         float firstPlaceVotes, secondPlaceVotes;
1844         float mapvote_voters_real;
1845         string result;
1846
1847         mapvote_voters_real = mapvote_voters;
1848         if(mapvote_abstain)
1849                 mapvote_voters_real -= mapvote_votes[mapvote_count - 1];
1850
1851         RandSel_Init();
1852         for(i = 0; i < mapvote_count_real; ++i) if(mapvote_maps[i] != "")
1853                 RandSel_Add(mapvote_votes[i], i);
1854         firstPlace = randsel_value;
1855         firstPlaceVotes = randsel_priority;
1856         //dprint("First place: ", ftos(firstPlace), "\n");
1857         //dprint("First place votes: ", ftos(firstPlaceVotes), "\n");
1858
1859         RandSel_Init();
1860         for(i = 0; i < mapvote_count_real; ++i) if(mapvote_maps[i] != "")
1861                 if(i != firstPlace)
1862                         RandSel_Add(mapvote_votes[i], i);
1863         secondPlace = randsel_value;
1864         secondPlaceVotes = randsel_priority;
1865         //dprint("Second place: ", ftos(secondPlace), "\n");
1866         //dprint("Second place votes: ", ftos(secondPlaceVotes), "\n");
1867
1868         if(firstPlace == -1)
1869                 error("No first place in map vote... WTF?");
1870
1871         if(secondPlace == -1 || time > mapvote_timeout || (mapvote_voters_real - firstPlaceVotes) < firstPlaceVotes)
1872                 return MapVote_Finished(firstPlace);
1873
1874         if(mapvote_keeptwotime)
1875                 if(time > mapvote_keeptwotime || (mapvote_voters_real - firstPlaceVotes - secondPlaceVotes) < secondPlaceVotes)
1876                 {
1877                         mapvote_message = "Now decide between the TOP TWO!";
1878                         mapvote_keeptwotime = 0;
1879                         result = strcat(":vote:keeptwo:", mapvote_maps[firstPlace]);
1880                         result = strcat(result, ":", ftos(firstPlaceVotes));
1881                         result = strcat(result, ":", mapvote_maps[secondPlace]);
1882                         result = strcat(result, ":", ftos(secondPlaceVotes), "::");
1883                         for(i = 0; i < mapvote_count_real; ++i)
1884                                 if(i != firstPlace)
1885                                         if(i != secondPlace)
1886                                                 if(mapvote_maps[i] != "")
1887                                                 {
1888                                                         result = strcat(result, ":", mapvote_maps[i]);
1889                                                         result = strcat(result, ":", ftos(mapvote_votes[i]));
1890                                                         strunzone(mapvote_maps[i]);
1891                                                         mapvote_maps[i] = "";
1892                                                 }
1893                         GameLogEcho(result, FALSE);
1894                 }
1895
1896         return FALSE;
1897 }
1898 void MapVote_Tick()
1899 {
1900         string msgstr;
1901         string tmp;
1902         float i;
1903         float keeptwo;
1904         float totalvotes;
1905
1906         keeptwo = mapvote_keeptwotime;
1907         MapVote_CheckRules_1(); // count
1908         if(MapVote_CheckRules_2()) // decide
1909                 return;
1910
1911         totalvotes = 0;
1912         FOR_EACH_REALCLIENT(other)
1913         {
1914                 // hide scoreboard again
1915                 if(other.health != 2342)
1916                 {
1917                         other.health = 2342;
1918                         other.impulse = 0;
1919                         if(clienttype(other) == CLIENTTYPE_REAL)
1920                         {
1921                                 stuffcmd(other, "\nin_bind 7 1 \"impulse 1\"; in_bind 7 2 \"impulse 2\"; in_bind 7 3 \"impulse 3\"; in_bind 7 4 \"impulse 4\"; in_bind 7 5 \"impulse 5\"; in_bind 7 6 \"impulse 6\"; in_bind 7 7 \"impulse 7\"; in_bind 7 8 \"impulse 8\"; in_bind 7 9 \"impulse 9\"; in_bind 7 0 \"impulse 10\"; in_bind 7 KP_1 \"impulse 1\"; in_bind 7 KP_2 \"impulse 2\"; in_bind 7 KP_3 \"impulse 3\"; in_bind 7 KP_4 \"impulse 4\"; in_bind 7 KP_5 \"impulse 5\"; in_bind 7 KP_6 \"impulse 6\"; in_bind 7 KP_7 \"impulse 7\"; in_bind 7 KP_8 \"impulse 8\"; in_bind 7 KP_9 \"impulse 9\"; in_bind 7 KP_0 \"impulse 10\"; in_bindmap 7 0\n");
1922                                 msg_entity = other;
1923                                 WriteByte(MSG_ONE, SVC_FINALE);
1924                                 WriteString(MSG_ONE, "");
1925                         }
1926                 }
1927
1928                 // notify about keep-two
1929                 if(keeptwo != 0 && mapvote_keeptwotime == 0)
1930                         play2(other, "misc/invshot.wav");
1931
1932                 // clear possibly invalid votes
1933                 if(mapvote_maps[other.mapvote - 1] == "")
1934                         other.mapvote = 0;
1935                 // use impulses as new vote
1936                 if(other.impulse >= 1 && other.impulse <= mapvote_count)
1937                         if(mapvote_maps[other.impulse - 1] != "")
1938                                 other.mapvote = other.impulse;
1939                 other.impulse = 0;
1940
1941                 if(other.mapvote)
1942                         ++totalvotes;
1943         }
1944
1945         MapVote_CheckRules_1(); // just count
1946
1947         FOR_EACH_REALCLIENT(other)
1948         {
1949                 // display voting screen
1950                 msgstr = "\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n";
1951                 msgstr = substring(msgstr, 0, strlen(msgstr) - mapvote_count);
1952                 if(mapvote_abstain)
1953                         msgstr = substring(msgstr, 1, strlen(msgstr) - 1);
1954                 msgstr = strcat(msgstr, mapvote_message);
1955                 msgstr = strcat(msgstr, "\n\n");
1956                 for(i = 0; i < mapvote_count; ++i)
1957                         if(mapvote_maps[i] == "")
1958                                 msgstr = strcat(msgstr, "\n");
1959                         else
1960                         {
1961                                 tmp = mapvote_maps[i];
1962                                 tmp = strpad(mapvote_maxlen, tmp);
1963                                 tmp = strcat(ftos(math_mod(i + 1, 10)), ": ", tmp);
1964                                 if(mapvote_detail)
1965                                 {
1966                                         tmp = strcat(tmp, " ^2(", ftos(mapvote_votes[i]), " vote");
1967                                         if(mapvote_votes[i] != 1)
1968                                                 tmp = strcat(tmp, "s");
1969                                         tmp = strcat(tmp, ")");
1970                                         tmp = strpad(mapvote_maxlen + 15, tmp);
1971                                 }
1972                                 if(mapvote_abstain)
1973                                         if(i == mapvote_count - 1)
1974                                                 msgstr = strcat(msgstr, "\n");
1975                                 if(other.mapvote == i + 1)
1976                                         msgstr = strcat(msgstr, "^3> ", tmp, "\n");
1977                                 else
1978                                         msgstr = strcat(msgstr, "^7  ", tmp, "\n");
1979                         }
1980
1981                 msgstr = strcat(msgstr, "\n\n^2", ftos(totalvotes), " vote");
1982                 if(totalvotes != 1)
1983                         msgstr = strcat(msgstr, "s");
1984                 msgstr = strcat(msgstr, " cast");
1985                 i = ceil(mapvote_timeout - time);
1986                 msgstr = strcat(msgstr, "\n", ftos(i), " second");
1987                 if(i != 1)
1988                         msgstr = strcat(msgstr, "s");
1989                 msgstr = strcat(msgstr, " left");
1990
1991                 centerprint_atprio(other, CENTERPRIO_MAPVOTE, msgstr);
1992         }
1993 }
1994 void MapVote_Start()
1995 {
1996         if(mapvote_run)
1997                 return;
1998
1999 #ifdef MAPINFO
2000         MapInfo_Enumerate();
2001         if(MapInfo_FilterGametype(MapInfo_CurrentGametype(), MapInfo_CurrentFeatures(), 1))
2002 #endif
2003                 mapvote_run = TRUE;
2004 }
2005 void MapVote_Think()
2006 {
2007         if(!mapvote_run)
2008                 return;
2009
2010         if(alreadychangedlevel)
2011                 return;
2012
2013         if(time < mapvote_nextthink)
2014                 return;
2015         //dprint("tick\n");
2016
2017         mapvote_nextthink = time + 0.5;
2018
2019         if(!mapvote_initialized)
2020         {
2021                 mapvote_initialized = TRUE;
2022                 if(DoNextMapOverride())
2023                         return;
2024                 if(!cvar("g_maplist_votable") || player_count <= 0)
2025                 {
2026                         GotoNextMap();
2027                         return;
2028                 }
2029                 MapVote_Init();
2030         }
2031
2032         MapVote_Tick();
2033 };
2034
2035 string GotoMap(string m)
2036 {
2037 #ifdef MAPINFO
2038         if(!MapInfo_CheckMap(m))
2039 #else
2040         if(!TryFile(strcat("maps/", m, ".mapcfg")))
2041 #endif
2042                 return "The map you chose is not available on this server.";
2043         cvar_set("nextmap", m);
2044         cvar_set("timelimit", "-1");
2045         if(mapvote_initialized || alreadychangedlevel)
2046         {
2047                 if(DoNextMapOverride())
2048                         return "Map switch initiated.";
2049                 else
2050                         return "Hm... no. For some reason I like THIS map more.";
2051         }
2052         else
2053                 return "Map switch will happen after scoreboard.";
2054 }
2055
2056
2057 void EndFrame()
2058 {
2059         FOR_EACH_REALCLIENT(self)
2060         {
2061                 if(self.classname == "spectator")
2062                 {
2063                         if(self.enemy.hitsound)
2064                                 play2(self, "misc/hit.wav");
2065                 }
2066                 else
2067                 {
2068                         if(self.hitsound)
2069                                 play2(self, "misc/hit.wav");
2070                 }
2071         }
2072         FOR_EACH_CLIENT(self)
2073                 self.hitsound = FALSE;
2074 }
2075
2076
2077 /*
2078  * RedirectionThink:
2079  * returns TRUE if redirecting
2080  */
2081 float redirection_timeout;
2082 float redirection_nextthink;
2083 float RedirectionThink()
2084 {
2085         float clients_found;
2086
2087         if(redirection_target == "")
2088                 return FALSE;
2089
2090         if(!redirection_timeout)
2091         {
2092                 cvar_set("sv_public", "-2");
2093                 redirection_timeout = time + 0.5; // this will only try twice... should be able to keep more clients
2094                 if(redirection_target == "self")
2095                         bprint("^3SERVER NOTICE:^7 restarting the server\n");
2096                 else
2097                         bprint("^3SERVER NOTICE:^7 redirecting everyone to ", redirection_target, "\n");
2098         }
2099
2100         if(time < redirection_nextthink)
2101                 return TRUE;
2102
2103         redirection_nextthink = time + 1;
2104
2105         clients_found = 0;
2106         FOR_EACH_REALCLIENT(self)
2107         {
2108                 ServerConsoleEcho(strcat("Redirecting: sending connect command to ", self.netname), FALSE);
2109                 if(redirection_target == "self")
2110                         stuffcmd(self, "\ndisconnect; reconnect\n");
2111                 else
2112                         stuffcmd(self, strcat("\ndisconnect; connect ", redirection_target, "\n"));
2113                 ++clients_found;
2114         }
2115
2116         ServerConsoleEcho(strcat("Redirecting: ", ftos(clients_found), " clients left."), FALSE);
2117
2118         if(time > redirection_timeout || clients_found == 0)
2119                 localcmd("\nwait; wait; wait; quit\n");
2120
2121         return TRUE;
2122 }