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