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