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