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