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