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