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