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